diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d4176b..fe7395d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,12 +14,14 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Install V - uses: vlang/setup-v@v1 + uses: vlang/setup-v@v1.4 with: - version: weekly.2025.09 + version: weekly.2025.48 - name: Checkout ${{ github.event.repository.name }} - uses: actions/checkout@v2 + uses: actions/checkout@v4 + with: + submodules: recursive - name: Build ${{ github.event.repository.name }} run: v -prod -gc none compiler.v diff --git a/.github/workflows/manual-release.yml b/.github/workflows/manual-release.yml index da86ad2..c5773bb 100644 --- a/.github/workflows/manual-release.yml +++ b/.github/workflows/manual-release.yml @@ -41,15 +41,17 @@ jobs: steps: - name: Checkout Code - uses: actions/checkout@v2 + uses: actions/checkout@v4 + with: + submodules: recursive - name: Install V - uses: vlang/setup-v@v1 + uses: vlang/setup-v@v1.4 with: - version: weekly.2025.09 + version: weekly.2025.48 - name: Build Project - run: v -prod -gc none -o "bin/papyrus" compiler.v + run: v -prod -g -gc none -o "bin/papyrus" compiler.v - name: Get the date id: date diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..7d0320e --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "modules/tests/sources"] + path = modules/tests/sources + url = https://github.com/russo-2025/papyrus-compiler-test-sources diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..cb33f7a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,271 @@ +# AGENTS.md — System Prompt for AI Assistants + +You are working on **Papyrus Compiler** — an open-source compiler for the Papyrus scripting language (Skyrim SE/AE). The compiler is written in the **V programming language** (vlang.io). It compiles `.psc` (Papyrus Source Code) files into `.pex` (Papyrus Executable) binary files — the same format as Bethesda's official Creation Kit compiler. + +--- + +## Project Structure + +``` +compiler.v — Entry point: CLI dispatch (compile, read, disassembly, dump, help, version) +fast.v — Benchmarking harness for performance tracking across commits +v.mod — V module metadata (version, dependencies) +run.bat — Quick-launch script for compilation + +modules/ +├── pref/ — CLI argument parsing, Preferences struct +├── papyrus/ +│ ├── token/ — Token kinds (enum Kind), Position struct +│ ├── scanner/ — Lexer: .psc text → token stream +│ ├── ast/ — AST nodes, type system, symbol table (Table), scopes +│ ├── parser/ — Recursive-descent parser: tokens → AST +│ ├── checker/ — Semantic analysis: type checking, cast validation, scope resolution +│ ├── errors/ — Error/Warning structs, predefined error message constants +│ └── util/ — Helpers: BOM handling, char classification, error formatting +├── pex/ — PEX binary format: data structures, reader, writer, opcodes, dump +├── gen/ +│ ├── gen_pex/ — Code generator: AST → PEX bytecode instructions +│ └── ts_binding/ — TypeScript binding generator (secondary feature) +├── builder/ — Orchestrator: drives the full compile pipeline, caching, stats +└── tests/ — Test suite (V's built-in test framework) +``` + +### Directories that should NOT be modified: +- `modules/tests/*Sources/` — Third-party Skyrim mod source files used as test fixtures. Do not edit. +- `modules/tests/psc_deps/` — 83 Skyrim base class header stubs (Actor.psc, Form.psc, etc.) used as dependencies for tests. Do not edit unless specifically adding new base class stubs. +- `test-files/` — Output directory for compiled test artifacts (.pex files). Not source code. +- `bin/` — Build output directory for the compiler binary. + +--- + +## Compilation Pipeline + +The compiler processes files through these stages in order: + +``` +.psc source → Scanner → Parser → Checker → Gen (gen_pex) → PEX Writer → .pex binary +``` + +1. **Scanning** (`modules/papyrus/scanner/`) — Character-by-character lexer. Handles `;` line comments, `{block}` comments, `;/ multi-line /;` comments. Case-insensitive keywords. Line continuation with `\`. +2. **Parsing** (`modules/papyrus/parser/`) — Recursive-descent parser producing `[]&ast.File`. Split into: `parser.v` (main + statements), `expr.v` (expressions with precedence climbing), `fn.v` (function/event declarations), `type.v` (type parsing). **Selective header loading**: unknown types are pushed onto `table.deps` stack, resolved by the builder iteratively. +3. **Checking** (`modules/papyrus/checker/`) — Type checking, autocast validation, scope resolution, method resolution via inheritance chains. Split into: `checker.v` (core), `checker_stmt.v` (statements), `checker_expr.v` (expressions). +4. **Code Generation** (`modules/gen/gen_pex/`) — Generates PEX bytecode from AST. Manages temp variables (`::temp0`, `::temp1`, ...), string interning, control flow jump patching. Split into: `gen.v` (main), `gen_stmt.v` (statements), `gen_expr.v` (expressions). +5. **PEX Writing** (`modules/pex/writer.v`) — Big-endian binary serialization. Generic `write[T]()` with compile-time type dispatch. + +--- + +## Key Data Structures + +### Type System (`modules/papyrus/ast/types.v`) +- `Type = int` — Index into `Table.types[]` +- Built-in type indices: 1=None, 2=Int, 3=Float, 4=String, 5=Bool, 6=Array, 7-10=typed arrays (String[], Int[], Float[], Bool[]) +- `TypeSymbol` — Holds: kind, parent_idx, methods, props, states, vars +- Placeholder types used for forward references, resolved during dependency loading + +### Symbol Table (`modules/papyrus/ast/table.v`) +- `Table` — Central registry: `types[]TypeSymbol`, `type_idxs map[string]int`, `fns map[string]Fn`, `deps Stack[string]` +- **All lookups are case-insensitive** (`.to_lower()` on keys) +- Functions keyed as `"objname.fnname"` + +### AST Nodes (`modules/papyrus/ast/ast.v`, `expr.v`) +- Top-level: `TopStmt = ScriptDecl | FnDecl | Comment | PropertyDecl | VarDecl | StateDecl` +- Statements: `Stmt = Return | If | While | ExprStmt | AssignStmt | VarDecl | Comment` +- Expressions: `Expr = InfixExpr | IntegerLiteral | FloatLiteral | BoolLiteral | StringLiteral | Ident | CallExpr | SelectorExpr | IndexExpr | ParExpr | PrefixExpr | EmptyExpr | ArrayInit | NoneLiteral | CastExpr` + +--- + +## V Language Conventions Used in This Project + +### Naming +- Structs: `PascalCase` +- Functions/methods: `snake_case` +- Enum variants: `snake_case` with `.` prefix (e.g., `.key_if`) +- Constants: `snake_case` +- Module names: lowercase + +### V-specific patterns used +- Sum types for AST: `type Expr = InfixExpr | IntegerLiteral | ...` +- Compile-time generics: `$if T is u8 { ... }` in binary read/write +- Performance attributes: `@[inline]`, `@[direct_array_access]`, `@[heap]` +- Result type: `!` operator for error-returning functions +- `mut` receivers for mutable method calls +- `spawn` for parallel code generation (up to 8 threads) + +### Comments +- Comments may contain Russian (Cyrillic) text. When you encounter Russian comments during your work, replace them with an English equivalent. + +--- + +## Build & Run Commands + +### Build +```bash +# Debug build +v -o "bin\papyrus.exe" compiler.v + +# Production build (optimized, no GC) +v -o "bin\papyrus.exe" -prod -gc none compiler.v + +# Debug with symbols +v -g -gc none -o "bin\papyrus.exe" compiler.v +``` + +### Run Tests +```bash +# Run all tests with stats +v -stats test modules + +# Run specific test file +v test modules/tests/ast_test.v +``` + +--- + +## Testing Conventions + +Tests are in `modules/tests/` and use V's built-in test framework (functions prefixed with `fn test_*`). + +### Test Categories + +| Category | File | Purpose | +|----------|------|---------| +| AST shape | `ast_test.v` | Verify parsed AST node types and properties | +| Error messages | `errors_test.v` | Verify compiler produces correct errors | +| Type casting | `checker_cast_test.v` | Exhaustive autocast/explicit cast matrix | +| PEX codegen | `pex_stmt_test.v` | End-to-end: source → PEX instructions | +| PEX binary | `binary_read_write_test.v`, `pex_read_write_test.v` | Serialize/deserialize roundtrip | +| Project integration | `projects_test.v` | Compile entire real Skyrim mod sources | +| Selective loading | `selective_headers_loading_test.v` | Verify only needed headers are parsed | +| PEX enum ordinals | `pex_test.v` | Validate opcode/value enum values | + +### Test Helpers Pattern +Each test file defines its own `compile()` helper tailored to its needs: + +- **`ast_test.v`**: `compile(src) → (&ast.File, &ast.Table, []errors.Error)` plus `compile_stmts()`, `compile_stmt()`, `compile_expr()` wrappers for convenience. +- **`errors_test.v`**: Same helpers but return only `[]errors.Error`. +- **`pex_stmt_test.v`**: `compile(src) → &pex.PexFile` (full pipeline round-trip) plus `get_instructions()`. + +All test files define `const prefs` with `no_cache: true, output_mode: .silent` and provide fixture scripts as module-level string constants (`src_template`, `other_src`, `parent_src`). + +### Test Fixtures +- `modules/tests/psc/` — Small custom `.psc` files for specific tests +- `modules/tests/psc_deps/` — Skyrim base script headers (dependencies for all tests) +- `modules/tests/*Sources/` — Real Skyrim mod source trees for integration tests + +--- + +## Mandatory Rules + +### 1. Bug fixes MUST include a test +When fixing a bug, **always** create a test case that covers the bug scenario. Choose the appropriate test file: +- Parser/AST bug → add test in `ast_test.v` +- Type checking / semantic error → add test in `errors_test.v` or `checker_cast_test.v` +- Code generation bug → add test in `pex_stmt_test.v` +- Binary format bug → add test in `binary_read_write_test.v` or `pex_read_write_test.v` + +### 2. Run tests after changes +After any code change, run `v -stats test modules` to verify nothing is broken. All existing tests must pass. + +### 3. Preserve case-insensitivity +Papyrus is a **case-insensitive language**. All identifier lookups, type resolution, and keyword matching must use `.to_lower()`. Never add case-sensitive comparisons for Papyrus identifiers. + +### 4. Error messages must be clear and user-facing +Error messages shown to the user should be clear, lowercase, and descriptive. Avoid technical jargon. Include context like expected vs actual values. Follow the existing style in `errors_test.v` — e.g., `'function takes 1 parameters not 0'`. + +### 5. Maintain pipeline separation +Keep the compiler stages cleanly separated: +- **Scanner** should only tokenize, never interpret semantics +- **Parser** should only build AST, never type-check +- **Checker** should only validate, never generate code +- **Gen** should only emit bytecode, never modify AST + +### 6. PEX format compliance +Generated `.pex` files must be binary-compatible with Bethesda's Papyrus VM. The format is big-endian. Do not change the opcode enum values or binary layout without verifying against the [Compiled Script File Format](https://en.uesp.net/wiki/Skyrim_Mod:Compiled_Script_File_Format) specification. + +### 7. Do not modify third-party test sources +Files in `modules/tests/*Sources/` directories are real-world Skyrim mod scripts. They must not be modified — they serve as regression test fixtures. + +### 8. Update changelog for user-visible changes +When you modify behavior, add features, or fix bugs, update the `Next Release` section in `CHANGELOG.md` in the same change. Use clear, user-facing bullet points that state what was changed or added. Changelog entries in this section must be written in English; if Russian text is present, translate it to English. + +Changelog entries must be written for **users of the compiler** (people writing Papyrus scripts), not for compiler developers. Follow these rules: +- Describe what the user would observe: what input previously failed or behaved incorrectly, and what happens now. +- Do **not** mention internal implementation details: no function names (`try_cast_to_type`, `cast_to_type`), no module names (`checker`, `gen_pex`), no compiler-internal terms (`AST`, `infix expression`, `autocast`, `opcode`, `assert`). +- Do **not** include entries about internal tests, CI, or build system changes unless they directly affect the user. +- Good example: `Fixed a compiler crash when using None in arithmetic expressions (e.g., None + 1). A proper error is now shown.` +- Bad example: `Fixed a checker assert on invalid autocasts in infix expressions: added try_cast_to_type.` + +--- + +## How To: Common Tasks + +### Add support for a new language feature +1. Add token(s) in `modules/papyrus/token/` if needed +2. Update scanner in `modules/papyrus/scanner/` to recognize new tokens +3. Add AST node(s) in `modules/papyrus/ast/` +4. Update parser in `modules/papyrus/parser/` to produce new AST +5. Add semantic checks in `modules/papyrus/checker/` +6. Add code generation in `modules/gen/gen_pex/` +7. Write tests at each level (AST, errors, PEX output) + +### Add a new error message +1. If it's a CLI-level error, add a `pub const msg_*` in `modules/papyrus/errors/errors.v` +2. If it's a checker/parser error, use inline string in the `error()` call +3. Add a test in `errors_test.v` that triggers the error and asserts the exact message + +### Add a new integration test project +1. Place source files in a new directory `modules/tests/Sources/` +2. In `projects_test.v`, add a `const` using `get_source_dir('Sources', '')` +3. Add `fn test_project_()` calling `get_prefs()` + `builder.compile()` +4. The test uses `backend: .check` (type-check only, no PEX output) + +### Fix a bug in code generation +1. Write a minimal `.psc` snippet that reproduces the issue +2. Add test in `pex_stmt_test.v` using `compile()` + `get_instructions()` +3. Fix the code in `modules/gen/gen_pex/` +4. Assert on expected PEX opcodes/operands in the test + +--- + +## Module Dependency Graph + +``` +compiler.v → pref, builder, pex, papyrus.util +builder → pref, papyrus.{ast, parser, checker, util}, gen.gen_pex, pex +gen_pex → papyrus.{ast, token, util}, pex, pref +checker → papyrus.{ast, token, errors, util}, pex, pref +parser → papyrus.{ast, scanner, token, errors, util}, pex, pref +scanner → papyrus.{token, util, errors}, pref +ast → papyrus.{token, util} +pex → papyrus.util, encoding.binary +pref → papyrus.errors +``` + +**Rule**: Do not introduce circular dependencies between modules. The dependency flow is: `compiler.v → builder → {checker, parser, gen_pex} → {ast, scanner, pex} → {token, util, errors}`. + +--- + +## Notable Implementation Details + +- **Selective header loading**: Only headers referenced by `table.deps` stack are parsed — not the entire Skyrim script library. This is a key performance optimization. +- **Caching**: File modification times are cached in `.papyrus/*.obj` files. Use `-nocache` to bypass. +- **Parallel codegen**: Enabled with `-use-threads`, divides work across up to 8 OS threads. Parse and check remain sequential. +- **String interning**: PEX uses a shared string table. All strings are interned via `gen_string_ref()` during code generation. +- **Temp variables**: Code generator manages a pool of `::temp0`, `::temp1`, etc. with free/reuse tracking. +- **Built-in methods**: `GetState`, `GotoState`, `onBeginState`, `onEndState` are auto-added to every object. Arrays have `Find`, `RFind`, `Length`. + +--- + +## Papyrus Language Quick Reference + +Papyrus is a **case-insensitive**, statically-typed, object-oriented scripting language: +- Types: `Int`, `Float`, `Bool`, `String`, `None`, script objects, arrays (`Type[]`) +- Inheritance: `Scriptname X extends Y` +- Properties: `Auto`, `AutoReadOnly`, full (with get/set) +- States: `State`, `Auto State` +- Events and Functions (can be `native`, `global`) +- Comments: `; line`, `{block}`, `;/ multi-line /;` +- Operators: arithmetic (`+`, `-`, `*`, `/`, `%`), comparison, logical (`&&`, `||`, `!`), string concatenation (`+`), compound assignment (`+=`, `-=`, etc.) +- `as` keyword for explicit type casting +- `new` keyword for array initialization: `new Int[10]` +- `self` refers to the current script object, `parent` calls parent's version of a function diff --git a/CHANGELOG.md b/CHANGELOG.md index 00ce8c8..729ae62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,38 @@ -## Next release +## Next Release + ... +## V 0.0.4 + +### New Features + +- Added `version` command — run `papyrus version` to display the current compiler version. +- String literals are now accepted as default values for typed properties and function parameters and are automatically converted to the declared type. + ``` + int Property MyProp = "123" Auto ; now valid — "123" is converted to 123 + ``` + ``` + Int Function MyFunc(int n1, int n2 = "12") ; "12" is converted to 12 + EndFunction + ``` + +### Improvements + +- The compiler now reports an error when a script referenced in `extends` or a variable type cannot be found, instead of failing silently. +- The compiler now reports an error when two scripts with the same name are found in different source folders. +- Added a check that the script name declared in `Scriptname` matches the source file name. +- Default parameter values are now validated to be type-compatible with the declared parameter type. +- Improved error messages to be clearer and more consistent (e.g., "undefined identifier" instead of "variable declaration not found"). +- Internal compiler errors now display a structured diagnostic message with version info, a stack trace, and instructions for reporting the issue, instead of crashing with an unhelpful message. + +### Fixes + +- Fixed incorrect handling of `None` as a default value in properties and function parameters. +- Fixed a compiler crash when `None` was used in arithmetic or logical expressions (e.g., `None + 1`). A proper error message is now shown instead. +- Fixed a compiler crash when an undefined script type was used in expressions that require conversion (for example, `value && true` where `value` has an unknown type). The compiler now reports an undefined type error instead of crashing. +- Fixed an issue where calling a function with default parameters inside a `State` block was not validated correctly (#14). +- Fixed parsing of comments inside parenthesized expressions and call argument lists (for example, `if !(PlayerRef ;/comment/;)`). The compiler now accepts these scripts instead of failing with a parser error. + ## V 0.0.3 ### Fixes diff --git a/README.RU.md b/README.RU.md index eed834e..2ad1294 100644 --- a/README.RU.md +++ b/README.RU.md @@ -1,7 +1,11 @@ # Papyrus Compiler +[![Discord Chat](https://img.shields.io/discord/1377359857220321416?label=Discord&logo=Discord)](https://discord.gg/JqQZXAXvPT) + Компилятор скриптового языка Papyrus с открытым исходным кодом. На данный момент компилятор поддерживает только Skyrim (тестировался на Skyrim SE/AE). +![Papyrus Compiler](docs/image.png) + Компилятор был создан для следующих целей: 1. **Понимание языков программирования:** Проект разработан для того, чтобы глубже понять, как работают языки программирования. 2. **Эксперименты с языком V:** Использует язык программирования V для реализации. @@ -29,6 +33,7 @@ papyrus [arguments] ``` ### Команды: +- `version`: Выводит версию компилятора и некоторую дополнительную информацию о билде. - `compile`: Компилирует файлы с расширением `.psc` в бинарный формат `.pex`. - `read`: Читает и дизассемблирует файл с расширением `.pex`, выводя его содержимое в человекочитаемом формате в консоль. - `disassembly`: Читает и дизассемблирует файл с расширением `.pex`, сохраняя содержимое в человекочитаемом формате в текстовый файл. @@ -45,7 +50,7 @@ papyrus [arguments] - `-silent`: Отключает вывод сообщений об ошибках в консоль. - `-original`: Использует оригинальный компилятор Papyrus для компиляции. - `-stats`: Сохраняет статистику по скомпилированным файлам в .md файлы (количество вызовов функций, наследований, файлов). -- `-check`: Проверяет синтаксис .psc файлов без генерации .pex файлов. +- `-check`: Проверяет синтаксис .psc файлов, но не создает .pex файлы. - `-verbose`: ... ### Примеры использования @@ -125,10 +130,10 @@ Function EquipItem(Form akItem, bool abPreventRemoval = false, bool abSilent = f ## Сборка ### Требования: -- [V compiler f3d2eb1 (weekly.2025.09)](https://github.com/vlang/v/releases/tag/weekly.2025.09) +- [V compiler d0dc13e (weekly.2025.48)](https://github.com/vlang/v/releases/tag/weekly.2025.48) ```bash -v -o "bin\papyrus.exe" -prod -gc none compiler.v +v -o "bin\papyrus.exe" -prod -g -gc none compiler.v ``` ## Тестирование diff --git a/README.md b/README.md index 0d69548..ca89979 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,11 @@ # Papyrus Compiler +[![Discord Chat](https://img.shields.io/discord/1377359857220321416?label=Discord&logo=Discord)](https://discord.gg/JqQZXAXvPT) + An open-source compiler for the Papyrus scripting language. Currently, the compiler only supports Skyrim (tested on Skyrim SE/AE). +![Papyrus Compiler](docs/image.png) + The compiler was created for the following purposes: 1. **Understanding Programming Languages:** The project is designed to gain a deeper understanding of how programming languages work. 2. **Experimenting with the V Language:** It uses the V programming language for implementation. @@ -125,10 +129,10 @@ Scripts from the directory specified by the `-h "..."` argument will NOT be comp ## Building ### Requirements: -- [V compiler f3d2eb1 (weekly.2025.09)](https://github.com/vlang/v/releases/tag/weekly.2025.09) +- [V compiler d0dc13e (weekly.2025.48)](https://github.com/vlang/v/releases/tag/weekly.2025.48) ```bash -v -o "bin\papyrus.exe" -prod -gc none compiler.v +v -o "bin\papyrus.exe" -prod -g -gc none compiler.v ``` ## Testing diff --git a/bin/Original Compiler/README.md b/bin/Original Compiler/README.md new file mode 100644 index 0000000..0db53a7 --- /dev/null +++ b/bin/Original Compiler/README.md @@ -0,0 +1,3 @@ +# Original Compiler Files + +This directory contains the original Papyrus compiler files from the Creation Kit. \ No newline at end of file diff --git a/compiler.v b/compiler.v index 47b4c89..b826fe2 100644 --- a/compiler.v +++ b/compiler.v @@ -6,16 +6,26 @@ import json import builder import pref import pex +import papyrus.util //#flag -lucrtd fn main() { prefs := pref.parse_args() - + mut sw := time.new_stopwatch() sw.start() match prefs.mode { + .version { + info := util.collect_info() + println("Version: ${info.version}") + println("Commit: ${info.git_commit}") + println("Build date: ${info.build_date}") + println("Build type: ${info.build_type}") + println("Repository: https://github.com/russo-2025/papyrus-compiler") + exit(0) + } .compile { builder.compile(prefs) } @@ -27,12 +37,18 @@ fn main() { .disassembly { println("disassembly file: `${prefs.paths[0]}` ") pex_file := pex.read_from_file(prefs.paths[0]) - os.write_file(prefs.paths[0] + ".txt", pex_file.str()) or { panic(err) } + output_file_name := prefs.paths[0] + ".txt" + os.write_file(output_file_name, pex_file.str()) or { + util.fatal_error("failed to write file ${output_file_name}; ${err}") + } } .create_dump { dump_objects := pex.create_dump_from_pex_dir(prefs.paths[0]) json_data := json.encode_pretty(dump_objects) - os.write_file(os.real_path("dump.json"), json_data) or { panic(err) } + output_file_name := os.real_path("dump.json") + os.write_file(output_file_name, json_data) or { + util.fatal_error("failed to write file ${output_file_name}; ${err}") + } } .help { pref.print_help_info() diff --git a/docs/image.png b/docs/image.png new file mode 100644 index 0000000..6c92f99 Binary files /dev/null and b/docs/image.png differ diff --git a/modules/builder/builder.v b/modules/builder/builder.v index 562e1b1..63def27 100644 --- a/modules/builder/builder.v +++ b/modules/builder/builder.v @@ -7,6 +7,7 @@ import pref import papyrus.ast import papyrus.checker import gen.gen_pex +import papyrus.util const cache_path = os.real_path('./.papyrus') const compiler_exe_path = os.real_path('./Original Compiler/PapyrusCompiler.exe') @@ -64,7 +65,7 @@ pub fn (mut b Builder) run() bool { b.pref.header_dirs = b.pref.header_dirs.reverse() - println("used header dirs ${b.pref.header_dirs}") + b.print("used header dirs ${b.pref.header_dirs}") b.files, b.files_names = find_all_src_files(b.pref.paths) @@ -141,11 +142,11 @@ fn (mut b Builder) start_timer(name string) { fn (mut b Builder) print_timer(name string) { if sw := b.timers[name] { time_ms := f32(sw.elapsed().microseconds()) / 1000 - b.print('$name: $time_ms ms') + b.print('${name}: ${time_ms} ms') b.timers.delete(name) } else { - panic('invalid timer') + util.compiler_error(msg: "failed to find timer", phase: "builder", prefs: b.pref, file: @FILE, func: @FN, line: @LINE) } } @@ -167,8 +168,7 @@ fn (b Builder) print(msg string) { @[noreturn] fn error(msg string) { - eprintln(msg) - exit(1) + util.fatal_error(msg) } /* @@ -188,7 +188,9 @@ fn (mut b Builder) register_info_from_dump(dump_obj &pex.DumpObject) { methods: []ast.Fn{} ) - mut sym := b.table.find_type(dump_obj.name) or { panic("failed to find type") } + mut sym := b.table.find_type(dump_obj.name) or { + util.compiler_error(msg: "failed to find type", phase: "builder", prefs: b.pref, file: @FILE, func: @FN, line: @LINE) + } for dump_method in dump_obj.methods { if !sym.has_method(dump_method.name) { diff --git a/modules/builder/cache.v b/modules/builder/cache.v index e14c320..0b385c3 100644 --- a/modules/builder/cache.v +++ b/modules/builder/cache.v @@ -4,6 +4,7 @@ import os import pref import papyrus.ast +import papyrus.util struct CacheFile { pub mut: @@ -11,16 +12,27 @@ pub mut: } fn read_cache(path string) &CacheFile { - mut file := os.open(path) or { panic(err) } + mut file := os.open(path) or { + util.fatal_error("failed to open file: ${err}") + } + mut cache := CacheFile{} - file.read_struct(mut cache) or { panic(err) } + file.read_struct(mut cache) or { + util.fatal_error("failed to read file: ${err}") + } file.close() return &cache } fn write_cache(path string, cache &CacheFile) { - mut file := os.create(path) or { panic(err) } - file.write_struct(cache) or { panic(err) } + mut file := os.create(path) or { + util.fatal_error("failed to create file: ${err}") + } + + file.write_struct(cache) or { + util.fatal_error("failed to write file: ${err}") + } + file.close() } diff --git a/modules/builder/original.v b/modules/builder/original.v index e231182..b4b69cd 100644 --- a/modules/builder/original.v +++ b/modules/builder/original.v @@ -16,15 +16,18 @@ fn (mut b Builder) compile_original() { for file in b.files { cmd := '"${compiler_exe_path}" "${file}" -quiet -i="${header_dirs}" -o="${b.pref.output_dir}" -f="${compiler_flags_path}"' + + b.print("executing: `${cmd}`") + res := unsafe { os.raw_execute(cmd) } if res.exit_code == 0 { - println('successfully - ${file}') + b.print('successfully - ${file}') } else { - println('failed - ${file}') - println('console output:') - println(res.output) + b.print('failed - ${file}') + b.print('console output:') + b.print(res.output) } } } \ No newline at end of file diff --git a/modules/builder/pex.v b/modules/builder/pex.v index b7bdd17..084cd26 100644 --- a/modules/builder/pex.v +++ b/modules/builder/pex.v @@ -6,6 +6,7 @@ import pex import papyrus.ast import papyrus.parser import papyrus.checker +import papyrus.util @[inline] fn (mut b Builder) compile_pex() { @@ -20,8 +21,6 @@ fn (mut b Builder) compile_pex() { b.start_timer('parse headers files') b.parse_deps() b.print_timer('parse headers files') - - //fns_dump.load("FunctionsDump.json", mut b.table) or { panic(err) } b.start_timer('check files') mut c := checker.new_checker(b.table, b.pref) @@ -29,17 +28,19 @@ fn (mut b Builder) compile_pex() { b.print_timer('check files') if !os.exists(cache_path) { - os.mkdir(cache_path) or { panic(err) } + os.mkdir(cache_path) or { + util.fatal_error("failed to make dir: ${err}") + } } if c.errors.len != 0 { - println("failed to compile files, ${c.errors.len} errors") - $if test { + println(c.errors) + print_backtrace() assert false, "checker.errors.len != 0" } - exit(1) + util.fatal_error("failed to compile files, ${c.errors.len} errors") } if b.pref.backend == .check { @@ -106,8 +107,12 @@ fn (mut b Builder) gen_to_pex_file(mut parsed_file ast.File, mut buff_bytes pex. assert !buff_bytes.is_empty() - mut file := os.create(output_file_path) or { panic(err) } - file.write(buff_bytes.bytes) or { panic(err) } + mut file := os.create(output_file_path) or { + util.fatal_error("failed to create file: ${err}") + } + file.write(buff_bytes.bytes) or { + util.fatal_error("failed to write file: ${err}") + } file.close() } } diff --git a/modules/builder/stats.v b/modules/builder/stats.v index b15c7aa..3b8b582 100644 --- a/modules/builder/stats.v +++ b/modules/builder/stats.v @@ -3,6 +3,7 @@ module builder import os import strings import papyrus.ast +import papyrus.util struct FnInfo { pub mut: @@ -172,7 +173,9 @@ fn (s Stats) save() { b.writeln("| native global fns | ${s.count_native_static_fns} |") b.writeln("| all methods | ${s.count_all_methods} |") b.writeln("| native methods | ${s.count_native_methods}") - os.write_file("stats.md", b.str()) or { panic(err) } + os.write_file("stats.md", b.str()) or { + util.fatal_error("failed to write file: ${err}") + } mut obj_info_arr := s.obj_info.values() obj_info_arr.sort(a.count > b.count) @@ -186,7 +189,9 @@ fn (s Stats) save() { b.writeln("| ${obj_info.name} | ${obj_info.count} | ") } - os.write_file("obj_extends_count.md", b.str()) or { panic(err) } + os.write_file("obj_extends_count.md", b.str()) or { + util.fatal_error("failed to write file: ${err}") + } mut call_info_arr := s.call_info.values() call_info_arr.sort(a.count > b.count) @@ -200,7 +205,9 @@ fn (s Stats) save() { b.writeln("| ${call_info.obj_name}.${call_info.name} | ${call_info.count} | ") } - os.write_file("all_fns_count.md", b.str()) or { panic(err) } + os.write_file("all_fns_count.md", b.str()) or { + util.fatal_error("failed to write file: ${err}") + } // only native b = strings.new_builder(100) @@ -213,5 +220,7 @@ fn (s Stats) save() { } } - os.write_file("native_fns_count.md", b.str()) or { panic(err) } + os.write_file("native_fns_count.md", b.str()) or { + util.fatal_error("failed to write file: ${err}") + } } \ No newline at end of file diff --git a/modules/gen/gen_pex/gen_expr.v b/modules/gen/gen_pex/gen_expr.v index 2497bfa..06003be 100644 --- a/modules/gen/gen_pex/gen_expr.v +++ b/modules/gen/gen_pex/gen_expr.v @@ -3,6 +3,7 @@ module gen_pex import papyrus.ast import pex import papyrus.token +import papyrus.util @[inline] fn (mut g Gen) get_free_temp(typ ast.Type) pex.VariableValue { @@ -206,6 +207,8 @@ fn (mut g Gen) gen_call(calltype pex.OpCode, mut expr ast.CallExpr) pex.Variable //имя функции args << pex.value_ident(g.gen_string_ref(expr.name)) + mut need_free_left := ?pex.VariableValue(none) + if calltype == .callmethod { //у кого вызывать метод @@ -218,9 +221,7 @@ fn (mut g Gen) gen_call(calltype pex.OpCode, mut expr ast.CallExpr) pex.Variable left_obj := g.get_operand_from_expr(mut &expr.left) args << left_obj - defer { - g.free_temp(left_obj) - } + need_free_left = left_obj } } @@ -249,6 +250,10 @@ fn (mut g Gen) gen_call(calltype pex.OpCode, mut expr ast.CallExpr) pex.Variable args: args } + if need_free_left != none { + g.free_temp(need_free_left) + } + return result_value } @@ -452,7 +457,7 @@ fn (mut g Gen) get_operand_from_expr(mut expr ast.Expr) pex.VariableValue { g.gen_cast(result_value, expr_value) } ast.EmptyExpr { - panic("wtf") + util.compiler_error(msg: "invalid expr(ast.EmptyExpr)", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } @@ -470,14 +475,14 @@ fn (mut g Gen) get_prefix_opcode_operator(typ ast.Type, kind token.Kind) pex.OpC return .fneg } else { - panic("Gen error: operator: `$kind` not supported type: ${g.table.type_to_str(typ)}") + util.compiler_error(msg: "operator: `${kind}` not supported type: ${g.table.type_to_str(typ)}", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } .not { return .not } else { - panic("Gen error: invalid infix operator: `$kind`") + util.compiler_error(msg: "invalid infix operator: `${kind}`", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } } @@ -496,7 +501,7 @@ fn (mut g Gen) get_infix_opcode_operator(typ ast.Type, kind token.Kind) pex.OpCo return .fadd } else { - panic("Gen error: operator: `$kind` not supported type: ${g.table.type_to_str(typ)}") + util.compiler_error(msg: "operator: `${kind}` not supported type: ${g.table.type_to_str(typ)}", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } .minus { @@ -507,7 +512,7 @@ fn (mut g Gen) get_infix_opcode_operator(typ ast.Type, kind token.Kind) pex.OpCo return .fsub } else { - panic("Gen error: operator: `$kind` not supported type: ${g.table.type_to_str(typ)}") + util.compiler_error(msg: "operator: `${kind}` not supported type: ${g.table.type_to_str(typ)}", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } .mul { @@ -518,7 +523,7 @@ fn (mut g Gen) get_infix_opcode_operator(typ ast.Type, kind token.Kind) pex.OpCo return .fmul } else { - panic("Gen error: operator: `$kind` not supported type: ${g.table.type_to_str(typ)}") + util.compiler_error(msg: "operator: `${kind}` not supported type: ${g.table.type_to_str(typ)}", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } .div { @@ -529,7 +534,7 @@ fn (mut g Gen) get_infix_opcode_operator(typ ast.Type, kind token.Kind) pex.OpCo return .fdiv } else { - panic("Gen error: operator: `$kind` not supported type: ${g.table.type_to_str(typ)}") + util.compiler_error(msg: "operator: `${kind}` not supported type: ${g.table.type_to_str(typ)}", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } .mod { @@ -537,21 +542,12 @@ fn (mut g Gen) get_infix_opcode_operator(typ ast.Type, kind token.Kind) pex.OpCo return .imod } else { - panic("Gen error: operator: `$kind` not supported type: ${g.table.type_to_str(typ)}") + util.compiler_error(msg: "operator: `${kind}` not supported type: ${g.table.type_to_str(typ)}", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } - .logical_and { - panic("Gen error: infix operator: `and`") - } - .logical_or { - panic("Gen error: infix operator: `or`") - } .eq { return .cmp_eq } - .ne { - panic("Gen error: infix operator: `not equal`") - } .gt { return .cmp_gt } @@ -564,8 +560,17 @@ fn (mut g Gen) get_infix_opcode_operator(typ ast.Type, kind token.Kind) pex.OpCo .le { return .cmp_le } + .logical_and { + util.compiler_error(msg: "invalid infix operator: `${kind}`", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) + } + .logical_or { + util.compiler_error(msg: "invalid infix operator: `${kind}`", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) + } + .ne { + util.compiler_error(msg: "invalid infix operator: `${kind}`", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) + } else { - panic("Gen error: invalid infix operator: `$kind`") + util.compiler_error(msg: "invalid infix operator: `${kind}`", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } } \ No newline at end of file diff --git a/modules/gen/gen_pex/gen_stmt.v b/modules/gen/gen_pex/gen_stmt.v index 8d01304..ed35ed3 100644 --- a/modules/gen/gen_pex/gen_stmt.v +++ b/modules/gen/gen_pex/gen_stmt.v @@ -3,6 +3,7 @@ module gen_pex import papyrus.ast import papyrus.token import pex +import papyrus.util @[inline] fn (mut g Gen) script_decl(mut s ast.ScriptDecl) { @@ -23,7 +24,7 @@ fn (mut g Gen) script_decl(mut s ast.ScriptDecl) { g.cur_obj.user_flags |= 0b0010 } else { - panic("invalid flag: `${flag.str()}`") + util.compiler_error(msg: "invalid flag: `${flag.str()}`", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } @@ -53,7 +54,9 @@ fn (mut g Gen) state_decl(mut s ast.StateDecl) { } if s.name.to_lower() in g.states { - g.cur_state = g.states[s.name.to_lower()] or { panic("wtf") } + g.cur_state = g.states[s.name.to_lower()] or { + util.compiler_error(msg: "failed to find state `${s.name.to_lower()}`", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) + } } else { mut state := g.create_state(s.name) @@ -170,7 +173,7 @@ fn (mut g Gen) gen_fn(mut node ast.FnDecl) &pex.Function { f.info.flags |= 0b0010 } else { - panic("invalid flag: `${flag.str()}`") + util.compiler_error(msg: "invalid flag: `${flag.str()}`", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } @@ -271,7 +274,7 @@ fn (mut g Gen) assign(mut stmt ast.AssignStmt) { } } else { - panic("Gen assign stmt TODO") + util.compiler_error(msg: "unprocessed expression on the left ${stmt.left.type_name()}", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } } @@ -289,7 +292,7 @@ fn (mut g Gen) var_decl(mut stmt ast.VarDecl) { if stmt.assign.right !is ast.EmptyExpr { if !stmt.assign.right.is_literal() { eprintln(stmt) - panic("wtf") + util.compiler_error(msg: "stmt.assign.right is not literal", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } data = g.get_operand_from_expr(mut &stmt.assign.right) @@ -338,7 +341,7 @@ fn (mut g Gen) prop_decl(mut stmt ast.PropertyDecl) { if stmt.expr !is ast.EmptyExpr { if !stmt.expr.is_literal() { - panic("wtf ${stmt}") + util.compiler_error(msg: "unexpected expression (${stmt.expr.type_name()}), expected literal", phase: "gen pex", prefs: g.pref, file: @FILE, func: @FN, line: @LINE) } value = g.get_operand_from_expr(mut &stmt.expr) diff --git a/modules/papyrus/ast/ast.v b/modules/papyrus/ast/ast.v index 486dfb9..ac78dbb 100644 --- a/modules/papyrus/ast/ast.v +++ b/modules/papyrus/ast/ast.v @@ -119,12 +119,13 @@ pub mut: pub struct AssignStmt { pub: - pos token.Position + pos token.Position pub mut: - op token.Kind - right Expr - left Expr - typ Type + op token.Kind + right Expr + left Expr + typ Type + is_object_var bool } pub struct VarDecl { diff --git a/modules/papyrus/ast/expr.v b/modules/papyrus/ast/expr.v index db2de44..e226044 100644 --- a/modules/papyrus/ast/expr.v +++ b/modules/papyrus/ast/expr.v @@ -43,30 +43,98 @@ pub: val string } +pub fn (lit IntegerLiteral) string() string { + return lit.val +} + +pub fn (lit IntegerLiteral) f32() f32 { + return f32(lit.int()) +} + +pub fn (lit IntegerLiteral) int() int { + return lit.val.int() +} + +pub fn (lit IntegerLiteral) bool() bool { + return if lit.int() > 0 { true } else { false } +} + pub struct NoneLiteral { pub: pos token.Position val string } +pub fn (lit NoneLiteral) bool() bool { + return false +} + pub struct FloatLiteral { pub: pos token.Position val string } +pub fn (lit FloatLiteral) string() string { + return lit.val +} + +pub fn (lit FloatLiteral) f32() f32 { + return lit.val.f32() +} + +pub fn (lit FloatLiteral) int() int { + return int(lit.f32()) +} + +pub fn (lit FloatLiteral) bool() bool { + return if lit.f32() > 0 { true } else { false } +} + pub struct StringLiteral { pub: pos token.Position val string } +pub fn (lit StringLiteral) string() string { + return lit.val +} + +pub fn (lit StringLiteral) f32() f32 { + return lit.val.f32() +} + +pub fn (lit StringLiteral) int() int { + return lit.val.int() +} + +pub fn (lit StringLiteral) bool() bool { + return lit.val.len != 0 +} + pub struct BoolLiteral { pub: pos token.Position val string } +pub fn (lit BoolLiteral) bool() bool { + return lit.val.to_lower() == 'true' +} + +pub fn (lit BoolLiteral) f32() f32 { + return if lit.val.to_lower() == 'true' { f32(1.0) } else { f32(0.0) } +} + +pub fn (lit BoolLiteral) int() int { + return if lit.val.to_lower() == 'true' { 1 } else { 0 } +} + +pub fn (lit BoolLiteral) string() string { + return if lit.val.to_lower() == 'true' { "true" } else { "false" } +} + pub struct Ident { pub: name string diff --git a/modules/papyrus/ast/scope.v b/modules/papyrus/ast/scope.v index 7742d9d..3b088e1 100644 --- a/modules/papyrus/ast/scope.v +++ b/modules/papyrus/ast/scope.v @@ -1,6 +1,7 @@ module ast import papyrus.token +import papyrus.util @[heap] pub struct Scope { @@ -40,7 +41,9 @@ pub fn (mut s Scope) find(name string) ?ScopeObject { mut current_scope := &Scope(&s) for { if lname in current_scope.objects { - return current_scope.objects[lname] or { panic('key not found') } + return current_scope.objects[lname] or { + util.compiler_error(msg: "key not found(${lname})", phase: "scope find", file: @FILE, func: @FN, line: @LINE) + } } if !isnil(current_scope.parent) { @@ -87,6 +90,6 @@ pub fn (mut s Scope) register(obj ScopeObject) { s.objects[name] = obj } else { - panic("invalid scope object") + util.compiler_error(msg: "unexpected ScopeObject(${obj.type_name()})", phase: "scope register", file: @FILE, func: @FN, line: @LINE) } } \ No newline at end of file diff --git a/modules/papyrus/ast/table.v b/modules/papyrus/ast/table.v index 1fb219f..fea8c6f 100644 --- a/modules/papyrus/ast/table.v +++ b/modules/papyrus/ast/table.v @@ -2,6 +2,7 @@ module ast import papyrus.token import datatypes +import papyrus.util @[heap] @@ -162,7 +163,7 @@ pub fn (mut t Table) register_type_symbol(sym TypeSymbol) Type { return existing_idx } else { - panic("Warning: override type(${sym.name}) - table.register_type_symbol()") + util.compiler_error(msg: "Warning: override type(${sym.name}) - table.register_type_symbol()", phase: "table register_type_symbol", file: @FILE, func: @FN, line: @LINE) return existing_idx } } @@ -176,7 +177,7 @@ pub fn (mut t Table) register_type_symbol(sym TypeSymbol) Type { @[inline] pub fn (t &Table) find_type_idx(name string) Type { - return t.type_idxs[name.to_lower()] + return t.type_idxs[name.to_lower()] or { 0 } } @[inline] @@ -208,7 +209,8 @@ pub fn (t &Table) get_type_symbol(typ Type) &TypeSymbol { return unsafe { &t.types[idx] } } // this should never happen - panic('get_type_symbol: invalid type (typ=${typ} idx=${idx}). Compiler bug.') + util.compiler_error(msg: "get_type_symbol: invalid type (typ=${typ} idx=${idx}). Compiler bug.", phase: "table get_type_symbol", file: @FILE, func: @FN, line: @LINE) + return 0 } diff --git a/modules/papyrus/ast/types.v b/modules/papyrus/ast/types.v index b42166e..a0a19a4 100644 --- a/modules/papyrus/ast/types.v +++ b/modules/papyrus/ast/types.v @@ -1,5 +1,7 @@ module ast +import papyrus.util + pub type Type = int pub struct TypeSymbol { @@ -114,7 +116,7 @@ pub fn (t Type) idx() int { @[inline] pub fn new_type(idx int) Type { if idx < 1 || idx > 65535 { - panic('new_type: idx(${idx}) must be between 1 & 65535') + util.compiler_error(msg: "new_type: idx(${idx}) must be between 1 & 65535", phase: "table new_type", file: @FILE, func: @FN, line: @LINE) } return idx } @@ -255,7 +257,9 @@ pub fn (t &TypeSymbol) find_method_in_state(state_name string, name string) ?Fn pub fn (mut t TypeSymbol) register_method_in_state(state_name string, new_fn Fn) int { key := state_name.to_lower() - mut state := t.states[key] or { panic("state not found") } + mut state := t.states[key] or { + util.compiler_error(msg: "state not found(${key})", phase: "TypeSymbol.register_method_in_state", file: @FILE, func: @FN, line: @LINE) + } state.methods << new_fn return state.methods.len - 1 diff --git a/modules/papyrus/checker/checker.v b/modules/papyrus/checker/checker.v index 0505572..f77cd23 100644 --- a/modules/papyrus/checker/checker.v +++ b/modules/papyrus/checker/checker.v @@ -50,13 +50,13 @@ pub fn (mut c Checker) check(mut ast_file ast.File) { } } -fn (mut c Checker) type_is_valid(typ ast.Type) bool { +fn (c Checker) type_is_valid(typ ast.Type) bool { if typ == 0 { return false } sym := c.table.get_type_symbol(typ) - assert sym.kind != .placeholder, sym.name + if sym.kind == .placeholder { return false } @@ -69,19 +69,34 @@ fn (c &Checker) get_type_name(typ ast.Type) string { return c.table.get_type_symbol(typ).name } -//может ли тип var_typ иметь значение с типом value_typ -pub fn (mut c Checker) valid_type(var_typ ast.Type, value_typ ast.Type) bool { +pub fn (mut c Checker) valid_type(var_typ ast.Type, value_typ ast.Type, allow_none_type_for_object_and_array bool) bool { assert var_typ != 0 assert value_typ != 0 + if var_typ == 0 || value_typ == 0 { + return false + } + if var_typ == value_typ { return true } + if allow_none_type_for_object_and_array { + var_sym := c.table.get_type_symbol(var_typ) + if var_sym.kind == .script || var_sym.kind == .array { + if value_typ == ast.none_type { + return true + } + } + } + return false } -pub fn (mut c Checker) valid_prop_type(var_typ ast.Type, value_typ ast.Type) bool { +/* +//может ли тип var_typ иметь значение с типом value_typ +// TODO rename -> value_type_is_valid +pub fn (mut c Checker) value_type_is_valid(var_typ ast.Type, value_typ ast.Type) bool { if c.valid_type(var_typ, value_typ) { return true } @@ -95,19 +110,27 @@ pub fn (mut c Checker) valid_prop_type(var_typ ast.Type, value_typ ast.Type) boo return false } +*/ -//можно ли кастануть тип from_type к типу to_type +// checks whether from_type can be implicitly cast to to_type pub fn (mut c Checker) can_autocast(from_type ast.Type, to_type ast.Type) bool { assert from_type != 0 assert to_type != 0 assert from_type != to_type from_sym := c.table.get_type_symbol(from_type) to_sym := c.table.get_type_symbol(to_type) - assert from_sym.kind != .placeholder, from_sym.name - assert to_sym.kind != .placeholder, to_sym.name + + if from_sym.kind == .placeholder || to_sym.kind == .placeholder { + return false + } + + //assert from_sym.kind != .placeholder, 'from_sym.kind == .placeholder, from_sym.name: ${from_sym.name}, to_sym.name: ${to_sym.name}' + //assert to_sym.kind != .placeholder, 'to_sym.kind == .placeholder, from_sym.name: ${from_sym.name}, to_sym.name: ${to_sym.name}' match to_sym.kind { - .placeholder { panic("wtf") } + .placeholder { + return false + } .none_ { return false } @@ -150,7 +173,7 @@ pub fn (mut c Checker) can_autocast(from_type ast.Type, to_type ast.Type) bool { return false } -//можно ли кастануть тип from_type к типу to_type +// checks whether from_type can be explicitly cast to to_type pub fn (mut c Checker) can_cast(from_type ast.Type, to_type ast.Type) bool { assert from_type != 0 assert to_type != 0 @@ -158,11 +181,14 @@ pub fn (mut c Checker) can_cast(from_type ast.Type, to_type ast.Type) bool { from_sym := c.table.get_type_symbol(from_type) to_sym := c.table.get_type_symbol(to_type) - assert from_sym.kind != .placeholder, from_sym.name - assert to_sym.kind != .placeholder, to_sym.name + if from_sym.kind == .placeholder || to_sym.kind == .placeholder { + return false + } match from_sym.kind { - .placeholder { panic("wtf") } + .placeholder { + util.compiler_error(msg: "placeholder type symbol / invalid type in can_cast", phase: "checker", prefs: c.pref, file: @FILE, func: @FN, line: @LINE) + } .none_ { match to_sym.kind { .string, @@ -228,7 +254,7 @@ pub fn (mut c Checker) can_cast(from_type ast.Type, to_type ast.Type) bool { } pub fn (mut c Checker) cast_to_type(node ast.Expr, from_type ast.Type, to_type ast.Type) &ast.Expr { - assert c.can_cast(from_type, to_type) || c.can_autocast(from_type, to_type) + assert c.can_cast(from_type, to_type) || c.can_autocast(from_type, to_type), "cannot cast from `${c.get_type_name(from_type)}` to `${c.get_type_name(to_type)}`" new_node := ast.CastExpr { expr: node @@ -240,13 +266,101 @@ pub fn (mut c Checker) cast_to_type(node ast.Expr, from_type ast.Type, to_type a return &new_node } +pub fn (mut c Checker) try_cast_to_type(node ast.Expr, from_type ast.Type, to_type ast.Type) ?&ast.Expr { + if !c.type_is_valid(from_type) { + c.undefined_type_error(from_type, node.pos) + return none + } + + if !c.type_is_valid(to_type) { + c.undefined_type_error(to_type, node.pos) + return none + } + + if !c.can_cast(from_type, to_type) && !c.can_autocast(from_type, to_type) { + c.error("cannot cast from `${c.get_type_name(from_type)}` to `${c.get_type_name(to_type)}`", node.pos) + return none + } + + return c.cast_to_type(node, from_type, to_type) +} + +pub fn (mut c Checker) compile_time_cast_to_type(node ast.Expr, from_type ast.Type, to_type ast.Type) ?&ast.Expr { + //assert c.can_cast(from_type, to_type) || c.can_autocast(from_type, to_type) + + match from_type { + ast.none_type { + match to_type { + ast.bool_type { return &ast.BoolLiteral{ val: "False" } } + ast.string_type { return &ast.StringLiteral{ val: "None" } } + else { + return none + } + } + } + ast.bool_type { + bool_lit := node as ast.BoolLiteral + + match to_type { + ast.int_type { return &ast.IntegerLiteral{ val: bool_lit.int().str() } } + ast.float_type { return &ast.FloatLiteral{ val: bool_lit.f32().str() } } + ast.string_type { return &ast.StringLiteral{ val: bool_lit.string() } } + // object + // array + else { + return none + } + } + } + ast.int_type { + int_lit := node as ast.IntegerLiteral + + match to_type { + ast.bool_type { return &ast.BoolLiteral{ val: int_lit.bool().str() } } + ast.float_type { return &ast.FloatLiteral{ val: int_lit.f32().str() } } + ast.string_type { return &ast.StringLiteral{ val: int_lit.string() } } + else { + return none + } + } + } + ast.float_type { + float_lit := node as ast.FloatLiteral + + match to_type { + ast.bool_type { return &ast.BoolLiteral{ val: float_lit.bool().str() } } + ast.int_type { return &ast.IntegerLiteral{ val: float_lit.int().str() } } + ast.string_type { return &ast.StringLiteral{ val: float_lit.string() } } + else { + return none + } + } + } + ast.string_type { + string_value := (node as ast.StringLiteral) + + match to_type { + ast.bool_type { return &ast.BoolLiteral{ val: string_value.bool().str() } } + ast.int_type { return &ast.IntegerLiteral{ val: string_value.int().str() } } + ast.float_type { return &ast.FloatLiteral{ val: string_value.f32().str() } } + else { + return none + } + } + } + else { + return none + } + } + + return none +} + pub fn (mut c Checker) find_method(typ ast.Type, name string) ?ast.Fn { mut sym := c.table.get_type_symbol(typ) mut tsym := sym for { - assert tsym.kind != .placeholder, tsym.name - if func := tsym.find_method(name) { return func } @@ -397,13 +511,30 @@ pub fn (mut c Checker) get_default_value(typ ast.Type) ast.Expr { .script { return ast.NoneLiteral{ val: "None" } } - .none_, + .none_ { + util.compiler_error(msg: "none type / invalid type in get_default_value", phase: "checker", prefs: c.pref, file: @FILE, func: @FN, line: @LINE) + } .placeholder { - panic("invalid typ") + util.compiler_error(msg: "placeholder type symbol / invalid type in get_default_value", phase: "checker", prefs: c.pref, file: @FILE, func: @FN, line: @LINE) } } } +fn (mut c Checker) check_type_or_error(typ ast.Type, pos token.Position) ast.Type { + if !c.type_is_valid(typ) { + c.undefined_type_error(typ, pos) + return ast.none_type + } + + return typ +} + +fn (mut c Checker) undefined_type_error(typ ast.Type, pos token.Position) { + type_name := c.get_type_name(typ) + c.error("undefined type: `${type_name}`", pos) + +} + fn (c &Checker) find_var_or_property_type(typ ast.Type, name string) ?ast.Type { mut sym := c.table.get_type_symbol(typ) diff --git a/modules/papyrus/checker/checker_expr.v b/modules/papyrus/checker/checker_expr.v index eaa144e..6929d7d 100644 --- a/modules/papyrus/checker/checker_expr.v +++ b/modules/papyrus/checker/checker_expr.v @@ -1,6 +1,7 @@ module checker import papyrus.ast +import papyrus.util const base_objects_events = [ "oninit", "onbeginstate", "onendstate" ] @@ -22,7 +23,7 @@ pub fn (mut c Checker) expr(mut node ast.Expr) ast.Type { match node.op { .not { - if c.valid_type(ast.bool_type, node.right_type) {} + if c.valid_type(ast.bool_type, node.right_type, false) {} else if c.can_autocast(node.right_type, ast.bool_type) { new_expr := ast.CastExpr { expr: node.right @@ -74,21 +75,21 @@ pub fn (mut c Checker) expr(mut node ast.Expr) ast.Type { } ast.Ident { if var := c.cur_scope.find_var(node.name) { - node.typ = var.typ + node.typ = c.check_type_or_error(var.typ, node.pos) return var.typ } else if prop := c.table.find_object_property(c.cur_obj, node.name) { - node.typ = prop.typ + node.typ = c.check_type_or_error(prop.typ, node.pos) node.is_object_property = true return node.typ } else if var := c.table.find_object_var(c.cur_obj, node.name) { - node.typ = var.typ + node.typ = c.check_type_or_error(var.typ, node.pos) node.is_object_var = true return node.typ } + c.error("undefined identifier `${node.name}`", node.pos) - c.error("variable declaration not found: `${node.name}`", node.pos) return ast.none_type } ast.CallExpr { @@ -138,11 +139,11 @@ pub fn (mut c Checker) expr(mut node ast.Expr) ast.Type { } else { if typ := c.find_var_or_property_type(node.typ, node.field_name) { - node.typ = typ + node.typ = c.check_type_or_error(typ, node.pos) return typ } - c.error("`${sym.obj_name}.${node.field_name}` property declaration not found", node.pos) + c.error("field or property `${node.field_name}` not found", node.pos) return ast.none_type } @@ -178,7 +179,7 @@ pub fn (mut c Checker) expr(mut node ast.Expr) ast.Type { } eprintln(node) - panic("expression not processed in file: `${c.file.path}`") + util.compiler_error(msg: "expression not processed in file: `${c.file.path}`", phase: "checker", prefs: c.pref, file: @FILE, func: @FN, line: @LINE) } pub fn (mut c Checker) expr_infix(mut node ast.InfixExpr) ast.Type { @@ -207,36 +208,48 @@ pub fn (mut c Checker) expr_infix(mut node ast.InfixExpr) ast.Type { node.result_type = ast.string_type if node.left_type == ast.string_type { - node.right = c.cast_to_type(node.right, node.right_type, ast.string_type) - node.right_type = ast.string_type + if cast_expr := c.try_cast_to_type(node.right, node.right_type, ast.string_type) { + node.right = cast_expr + node.right_type = ast.string_type + } } else if node.right_type == ast.string_type { - node.left = c.cast_to_type(node.left, node.left_type, ast.string_type) - node.left_type = ast.string_type + if cast_expr := c.try_cast_to_type(node.left, node.left_type, ast.string_type) { + node.left = cast_expr + node.left_type = ast.string_type + } } } else if node.left_type == ast.float_type || node.right_type == ast.float_type { node.result_type = ast.float_type if node.left_type == ast.float_type { - node.right = c.cast_to_type(node.right, node.right_type, ast.float_type) - node.right_type = ast.float_type + if cast_expr := c.try_cast_to_type(node.right, node.right_type, ast.float_type) { + node.right = cast_expr + node.right_type = ast.float_type + } } else if node.right_type == ast.float_type { - node.left = c.cast_to_type(node.left, node.left_type, ast.float_type) - node.left_type = ast.float_type + if cast_expr := c.try_cast_to_type(node.left, node.left_type, ast.float_type) { + node.left = cast_expr + node.left_type = ast.float_type + } } } else { node.result_type = ast.int_type if node.left_type == ast.int_type { - node.right = c.cast_to_type(node.right, node.right_type, ast.int_type) - node.right_type = ast.int_type + if cast_expr := c.try_cast_to_type(node.right, node.right_type, ast.int_type) { + node.right = cast_expr + node.right_type = ast.int_type + } } else if node.right_type == ast.int_type { - node.left = c.cast_to_type(node.left, node.left_type, ast.int_type) - node.left_type = ast.int_type + if cast_expr := c.try_cast_to_type(node.left, node.left_type, ast.int_type) { + node.left = cast_expr + node.left_type = ast.int_type + } } else { type_name := c.get_type_name(node.left_type) @@ -257,24 +270,32 @@ pub fn (mut c Checker) expr_infix(mut node ast.InfixExpr) ast.Type { node.result_type = ast.float_type if node.left_type == ast.float_type { - node.right = c.cast_to_type(node.right, node.right_type, ast.float_type) - node.right_type = ast.float_type + if cast_expr := c.try_cast_to_type(node.right, node.right_type, ast.float_type) { + node.right = cast_expr + node.right_type = ast.float_type + } } else if node.right_type == ast.float_type { - node.left = c.cast_to_type(node.left, node.left_type, ast.float_type) - node.left_type = ast.float_type + if cast_expr := c.try_cast_to_type(node.left, node.left_type, ast.float_type) { + node.left = cast_expr + node.left_type = ast.float_type + } } } else { node.result_type = ast.int_type if node.left_type == ast.int_type { - node.right = c.cast_to_type(node.right, node.right_type, ast.int_type) - node.right_type = ast.int_type + if cast_expr := c.try_cast_to_type(node.right, node.right_type, ast.int_type) { + node.right = cast_expr + node.right_type = ast.int_type + } } else if node.right_type == ast.int_type { - node.left = c.cast_to_type(node.left, node.left_type, ast.int_type) - node.left_type = ast.int_type + if cast_expr := c.try_cast_to_type(node.left, node.left_type, ast.int_type) { + node.left = cast_expr + node.left_type = ast.int_type + } } else { type_name := c.get_type_name(node.left_type) @@ -294,22 +315,30 @@ pub fn (mut c Checker) expr_infix(mut node ast.InfixExpr) ast.Type { } else if node.left_type == ast.float_type || node.right_type == ast.float_type { if node.left_type == ast.float_type { - node.right = c.cast_to_type(node.right, node.right_type, ast.float_type) - node.right_type = ast.float_type + if cast_expr := c.try_cast_to_type(node.right, node.right_type, ast.float_type) { + node.right = cast_expr + node.right_type = ast.float_type + } } else if node.right_type == ast.float_type { - node.left = c.cast_to_type(node.left, node.left_type, ast.float_type) - node.left_type = ast.float_type + if cast_expr := c.try_cast_to_type(node.left, node.left_type, ast.float_type) { + node.left = cast_expr + node.left_type = ast.float_type + } } } else { if node.left_type == ast.int_type { - node.right = c.cast_to_type(node.right, node.right_type, ast.int_type) - node.right_type = ast.int_type + if cast_expr := c.try_cast_to_type(node.right, node.right_type, ast.int_type) { + node.right = cast_expr + node.right_type = ast.int_type + } } else if node.right_type == ast.int_type { - node.left = c.cast_to_type(node.left, node.left_type, ast.int_type) - node.left_type = ast.int_type + if cast_expr := c.try_cast_to_type(node.left, node.left_type, ast.int_type) { + node.left = cast_expr + node.left_type = ast.int_type + } } else { type_name := c.get_type_name(node.left_type) @@ -324,12 +353,16 @@ pub fn (mut c Checker) expr_infix(mut node ast.InfixExpr) ast.Type { } else if node.left_type == ast.int_type { - node.right = c.cast_to_type(node.right, node.right_type, ast.int_type) - node.right_type = ast.int_type + if cast_expr := c.try_cast_to_type(node.right, node.right_type, ast.int_type) { + node.right = cast_expr + node.right_type = ast.int_type + } } else if node.right_type == ast.int_type { - node.left = c.cast_to_type(node.left, node.left_type, ast.int_type) - node.left_type = ast.int_type + if cast_expr := c.try_cast_to_type(node.left, node.left_type, ast.int_type) { + node.left = cast_expr + node.left_type = ast.int_type + } } else { ltype_name := c.get_type_name(node.left_type) @@ -340,7 +373,7 @@ pub fn (mut c Checker) expr_infix(mut node ast.InfixExpr) ast.Type { .eq, .ne { node.result_type = ast.bool_type - if c.valid_type(node.left_type, node.right_type) || c.valid_type(node.right_type, node.left_type) {} + if c.valid_type(node.left_type, node.right_type, false) || c.valid_type(node.right_type, node.left_type, false) {} else { if c.can_autocast(node.right_type, node.left_type) { node.right = c.cast_to_type(node.right, node.right_type, node.left_type) @@ -359,19 +392,23 @@ pub fn (mut c Checker) expr_infix(mut node ast.InfixExpr) ast.Type { } .logical_and, .logical_or { if node.left_type != ast.bool_type { - node.left = c.cast_to_type(node.left, node.left_type, ast.bool_type) - node.left_type = ast.bool_type + if cast_expr := c.try_cast_to_type(node.left, node.left_type, ast.bool_type) { + node.left = cast_expr + node.left_type = ast.bool_type + } } if node.right_type != ast.bool_type { - node.right = c.cast_to_type(node.right, node.right_type, ast.bool_type) - node.right_type = ast.bool_type + if cast_expr := c.try_cast_to_type(node.right, node.right_type, ast.bool_type) { + node.right = cast_expr + node.right_type = ast.bool_type + } } node.result_type = ast.bool_type } else { - panic("wtf (${node.op})") + util.compiler_error(msg: "invalid operator(${node.op}) in expr_infix", phase: "checker", prefs: c.pref, file: @FILE, func: @FN, line: @LINE) } } @@ -412,6 +449,11 @@ pub fn (mut c Checker) call_expr(mut node ast.CallExpr) ast.Type { //find method typ = c.expr(mut node.left) + if !c.type_is_valid(typ) { + c.undefined_type_error(typ, node.pos) + return ast.none_type + } + if mut tfunc := c.find_method(typ, node.name) { func = &tfunc } @@ -442,11 +484,16 @@ pub fn (mut c Checker) call_expr(mut node ast.CallExpr) ast.Type { arg_typ := c.expr(mut node.args[i].expr) node.args[i].typ = arg_typ func_arg_type := func.params[i].typ - - if c.valid_type(func_arg_type, arg_typ) {} + + if !c.type_is_valid(arg_typ) { + c.undefined_type_error(arg_typ, node.args[i].pos) + i++ + continue + } + + if c.valid_type(func_arg_type, arg_typ, false) {} else if c.can_autocast(arg_typ, func_arg_type) { node.args[i].expr = c.cast_to_type(node.args[i].expr, arg_typ, func_arg_type) - } else { left_type_name := c.get_type_name(func_arg_type) @@ -466,7 +513,7 @@ pub fn (mut c Checker) call_expr(mut node ast.CallExpr) ast.Type { lname := param.name.to_lower() if lname in node.redefined_args { - mut r_arg := &(node.redefined_args[lname]) + mut r_arg := unsafe { &(node.redefined_args[lname]) } node.args << ast.CallArg { expr: r_arg.expr @@ -487,11 +534,13 @@ pub fn (mut c Checker) call_expr(mut node ast.CallExpr) ast.Type { assert param.default_value.is_literal() assert param.default_value !is ast.EmptyExpr - default_value_typ := c.expr(mut param.default_value) + mut default_value := param.default_value + default_value_typ := c.expr(mut default_value) - optional_is_valid := c.table.type_is_script(param.typ) && default_value_typ == ast.none_type - - if c.valid_type(param.typ, default_value_typ) || optional_is_valid {} + if c.valid_type(param.typ, default_value_typ, false) {} + else if c.can_autocast(default_value_typ, param.typ) { + default_value = *c.cast_to_type(default_value, default_value_typ, param.typ) + } else { arg_type_name := c.get_type_name(param.typ) expr_type_name := c.get_type_name(default_value_typ) @@ -499,7 +548,7 @@ pub fn (mut c Checker) call_expr(mut node ast.CallExpr) ast.Type { } node.args << ast.CallArg { - expr: param.default_value + expr: default_value typ: param.typ } diff --git a/modules/papyrus/checker/checker_stmt.v b/modules/papyrus/checker/checker_stmt.v index f3ed8cd..cbc2053 100644 --- a/modules/papyrus/checker/checker_stmt.v +++ b/modules/papyrus/checker/checker_stmt.v @@ -12,10 +12,19 @@ fn (mut c Checker) top_stmt(mut node ast.TopStmt) { c.cur_obj = c.table.find_type_idx(node.name) c.auto_state_is_exist = false - if node.parent_name != "" { - if !c.table.known_type(node.parent_name) { - c.error("invalid parent `${node.parent_name}`", node.pos) + mut tsym := c.table.get_type_symbol(c.cur_obj) + for { + if tsym.kind == .placeholder { + c.error("script with name `${tsym.name}` not found", node.pos) + break } + + if tsym.parent_idx != 0 { + tsym = c.table.get_type_symbol(tsym.parent_idx) + continue + } + + break } } ast.StateDecl { @@ -45,45 +54,51 @@ fn (mut c Checker) top_stmt(mut node ast.TopStmt) { c.var_decl(mut node) } ast.PropertyDecl { - if c.type_is_valid(node.typ) { - c.inside_property = true + if !c.type_is_valid(node.typ) { + c.undefined_type_error(node.typ, node.pos) + return + } - if node.expr !is ast.EmptyExpr { - if !node.expr.is_literal() { - c.error("expression in object property can only be a literal", node.pos) - } + c.inside_property = true + + if node.expr !is ast.EmptyExpr { + if !node.expr.is_literal() { + c.error("expression in object property can only be a literal", node.pos) + } - left_type := node.typ - mut right_type := c.expr(mut node.expr) + left_type := node.typ + mut right_type := c.expr(mut node.expr) - if c.valid_prop_type(left_type, right_type) {} + if c.valid_type(left_type, right_type, true) {} + else { + mb_new_expr := c.compile_time_cast_to_type(node.expr, right_type, left_type) + if new_expr := mb_new_expr { + node.expr = new_expr + } else { ltype_name := c.get_type_name(left_type) rtype_name := c.get_type_name(right_type) c.error("value with type `${rtype_name}` cannot be assigned to a property with type `${ltype_name}`", node.pos) } } + } - if mut node.read is ast.FnDecl { - c.top_stmt(mut &node.read) - } + if mut node.read is ast.FnDecl { + c.top_stmt(mut &node.read) + } - if mut node.write is ast.FnDecl { - c.top_stmt(mut &node.write) - } + if mut node.write is ast.FnDecl { + c.top_stmt(mut &node.write) + } - sym := c.table.get_type_symbol(c.cur_obj) - if t_prop := sym.find_property(node.name) { - if t_prop.pos.pos != node.pos.pos { - c.error("property with this name already exists", node.pos) - } + sym := c.table.get_type_symbol(c.cur_obj) + if t_prop := sym.find_property(node.name) { + if t_prop.pos.pos != node.pos.pos { + c.error("property with `${node.name}` name already exists", node.pos) } - - c.inside_property = false - } - else { - c.error("invalid type in property declaration", node.pos) } + + c.inside_property = false } ast.Comment {} } @@ -99,8 +114,13 @@ fn (mut c Checker) stmt(mut node ast.Stmt) { match mut node { ast.Return { typ := c.expr(mut node.expr) + + if !c.type_is_valid(c.cur_fn.return_type) { + c.undefined_type_error(c.cur_fn.return_type, node.pos) + return + } - if c.valid_type(c.cur_fn.return_type, typ) {} + if c.valid_type(c.cur_fn.return_type, typ, false) {} else if c.can_autocast(typ, c.cur_fn.return_type) { new_expr := ast.CastExpr { expr: node.expr @@ -162,9 +182,19 @@ fn (mut c Checker) stmt(mut node ast.Stmt) { c.error("invalid right exression in assignment", node.pos) } + if !c.type_is_valid(left_type) { + c.undefined_type_error(left_type, node.pos) + return + } + + if !c.type_is_valid(right_type) { + c.undefined_type_error(right_type, node.pos) + return + } + node.typ = left_type - if c.valid_type(left_type, right_type) {} + if c.valid_type(left_type, right_type, node.is_object_var) {} else if c.can_autocast(right_type, left_type) { node.right = c.cast_to_type(node.right, right_type, left_type) right_type = left_type @@ -218,10 +248,54 @@ fn (mut c Checker) fn_decl(mut node ast.FnDecl) { c.cur_scope = node.scope c.inside_fn = true - for param in node.params { + if !c.type_is_valid(node.return_type) { + c.undefined_type_error(node.return_type, node.pos) + } + + for i := 0; i < node.params.len; i++ { + mut param := node.params[i] + if !c.type_is_valid(param.typ) { type_name := c.get_type_name(param.typ) - c.error("unknown type of function argument `${type_name}`", node.pos) + c.error("invalid type `${type_name}` for parameter #${i + 1} `${param.name}` in function `${node.name}`", node.pos) + continue + } + + if param.is_optional { + if param.default_value is ast.EmptyExpr { + c.error("optional parameter `${param.name}` must have a default value", node.pos) + continue + } + + if !param.default_value.is_literal() { + c.error("default value for parameter `${param.name}` must be a literal", node.pos) + continue + } + + default_value_typ := match param.default_value { + ast.FloatLiteral { ast.float_type } + ast.IntegerLiteral { ast.int_type } + ast.BoolLiteral { ast.bool_type } + ast.StringLiteral { ast.string_type } + ast.NoneLiteral { ast.none_type } + else { ast.none_type } + } + + c.expr(mut node.params[i].default_value) + + if c.valid_type(param.typ, default_value_typ, true) {} + else { + mb_new_expr := c.compile_time_cast_to_type(node.params[i].default_value, default_value_typ, param.typ) + if new_expr := mb_new_expr { + node.params[i].default_value = new_expr + } + else { + default_value_name := c.get_type_name(default_value_typ) + type_name := c.get_type_name(param.typ) + c.error("default value for parameter `${param.name}` has type `${default_value_name}` which cannot be assigned to parameter type `${type_name}`", node.pos) + continue + } + } } } @@ -251,11 +325,11 @@ fn (mut c Checker) fn_decl(mut node ast.FnDecl) { if func := c.find_fn(c.cur_obj, c.cur_obj_name, node.name) { if node.is_global != func.is_global { - c.error('declaration of the $node.name function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) + c.error('declaration of the ${node.name} function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) } if node.return_type != func.return_type { - c.error('declaration of the $node.name function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) + c.error('declaration of the ${node.name} function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) } if node.params.len == func.params.len { @@ -265,15 +339,54 @@ fn (mut c Checker) fn_decl(mut node ast.FnDecl) { func_param := func.params[i] if node_param.typ != func_param.typ { - c.error('declaration of the $node.name function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) + c.error('declaration of the ${node.name} function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) + i++ + continue } if node_param.is_optional != func_param.is_optional { - c.error('declaration of the $node.name function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) + c.error('declaration of the ${node.name} function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) + i++ + continue } - if node_param.default_value != func_param.default_value { - c.error('declaration of the $node.name function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) + if node_param.is_optional { + mut bad_default_value := false + + if node_param.default_value is ast.NoneLiteral && func_param.default_value is ast.NoneLiteral { + if (node_param.default_value as ast.NoneLiteral).val != (func_param.default_value as ast.NoneLiteral).val { + bad_default_value = true + } + } + else if node_param.default_value is ast.FloatLiteral && func_param.default_value is ast.FloatLiteral { + if (node_param.default_value as ast.FloatLiteral).val != (func_param.default_value as ast.FloatLiteral).val { + bad_default_value = true + } + } + else if node_param.default_value is ast.IntegerLiteral && func_param.default_value is ast.IntegerLiteral { + if (node_param.default_value as ast.IntegerLiteral).val != (func_param.default_value as ast.IntegerLiteral).val { + bad_default_value = true + } + } + else if node_param.default_value is ast.BoolLiteral && func_param.default_value is ast.BoolLiteral { + if (node_param.default_value as ast.BoolLiteral).val != (func_param.default_value as ast.BoolLiteral).val { + bad_default_value = true + } + } + else if node_param.default_value is ast.StringLiteral && func_param.default_value is ast.StringLiteral { + if (node_param.default_value as ast.StringLiteral).val != (func_param.default_value as ast.StringLiteral).val { + bad_default_value = true + } + } + else { + bad_default_value = true + } + + if bad_default_value { + c.error('declaration of the ${node.name} function in the ${c.cur_state_name} state is different from the declaration in the empty state', node.pos) + i++ + continue + } } i++ @@ -319,7 +432,7 @@ pub fn (mut c Checker) var_decl(mut node ast.VarDecl) { } if !c.type_is_valid(node.typ) { - c.error("invalid type in variable declaration", node.pos) + c.undefined_type_error(node.typ, node.pos) return } @@ -331,7 +444,7 @@ pub fn (mut c Checker) var_decl(mut node ast.VarDecl) { left_type := node.typ mut right_type := c.expr(mut node.assign.right) - if c.valid_prop_type(left_type, right_type) {} + if c.valid_type(left_type, right_type, true) {} else { ltype_name := c.get_type_name(left_type) rtype_name := c.get_type_name(right_type) @@ -342,7 +455,7 @@ pub fn (mut c Checker) var_decl(mut node ast.VarDecl) { left_type := node.typ mut right_type := c.expr(mut node.assign.right) - if c.valid_type(left_type, right_type) {} + if c.valid_type(left_type, right_type, false) {} else if c.can_autocast(right_type, left_type) { node.assign.right = c.cast_to_type(node.assign.right, right_type, left_type) } diff --git a/modules/papyrus/parser/expr.v b/modules/papyrus/parser/expr.v index 1772026..8cab90e 100644 --- a/modules/papyrus/parser/expr.v +++ b/modules/papyrus/parser/expr.v @@ -2,8 +2,11 @@ module parser import papyrus.ast import papyrus.token +import papyrus.util pub fn (mut p Parser) expr(precedence int) ?ast.Expr { + p.skip_comments() + mut node := ast.Expr(ast.EmptyExpr{ pos:p.tok.position() }) match p.tok.kind { @@ -59,6 +62,7 @@ pub fn (mut p Parser) expr(precedence int) ?ast.Expr { mut pos := p.tok.position() p.check(.lpar) node = p.expr(0) or { ast.EmptyExpr{} } + p.skip_comments() p.check(.rpar) node = ast.ParExpr{ @@ -76,6 +80,7 @@ pub fn (mut p Parser) expr(precedence int) ?ast.Expr { pub fn (mut p Parser) expr_with_left(left ast.Expr, precedence int) ast.Expr { mut node := left + p.skip_comments() for p.tok.precedence() > precedence { //println("aaaasw ${left} ${p.tok}") @@ -95,6 +100,8 @@ pub fn (mut p Parser) expr_with_left(left ast.Expr, precedence int) ast.Expr { else { return node } + + p.skip_comments() } return node @@ -176,7 +183,7 @@ pub fn (mut p Parser) parse_number_literal() ast.Expr { } if is_hex && is_neg { - panic("negative hex wtf") + util.compiler_error(msg: "negative hex wtf", phase: "parser", prefs: p.pref, file: @FILE, func: @FN, line: @LINE) } if is_neg { diff --git a/modules/papyrus/parser/fn.v b/modules/papyrus/parser/fn.v index 2977ce3..938e116 100644 --- a/modules/papyrus/parser/fn.v +++ b/modules/papyrus/parser/fn.v @@ -136,11 +136,14 @@ pub fn (mut p Parser) fn_decl() ast.FnDecl { fn (mut p Parser) fn_args() []ast.Param { p.check(.lpar) + p.skip_comments() mut args := []ast.Param{} if p.tok.kind != .rpar { for { + p.skip_comments() + mut param := ast.Param{} mut pos := p.tok.position() @@ -154,11 +157,6 @@ fn (mut p Parser) fn_args() []ast.Param { default_value := p.expr(0) or { ast.EmptyExpr{} } - if !default_value.is_literal() { - println(default_value) - p.error("default value is not literal") - } - param.default_value = default_value param.is_optional = true } @@ -176,6 +174,7 @@ fn (mut p Parser) fn_args() []ast.Param { if p.tok.kind == .comma { p.next() + p.skip_comments() continue } @@ -196,6 +195,12 @@ pub fn (mut p Parser) call_args() ([]ast.CallArg, map[string]ast.RedefinedOption mut optional_args_is_started := false for p.tok.kind != .rpar { + p.skip_comments() + + if p.tok.kind == .rpar { + break + } + if p.tok.kind == .eof { p.error_with_pos('unexpected eof reached, while parsing call argument', start_pos) } @@ -211,7 +216,7 @@ pub fn (mut p Parser) call_args() ([]ast.CallArg, map[string]ast.RedefinedOption pos := arg_start_pos.extend(p.prev_tok.position()) if name in redefined_args { - p.error('a parameter named `$name` has already been set') // уже присутствует + p.error('a parameter named `$name` has already been set') // already provided } redefined_args[name.to_lower()] = ast.RedefinedOptionalArg{ @@ -222,7 +227,7 @@ pub fn (mut p Parser) call_args() ([]ast.CallArg, map[string]ast.RedefinedOption } else { if optional_args_is_started { - p.error("parameter is expected in the format 'name = value`") // ожидается параметр в формате `name = value` + p.error("parameter is expected in the format 'name = value`") // expected format is 'name = value' } e := p.expr(0) or { p.error("invalid expression") } @@ -238,6 +243,7 @@ pub fn (mut p Parser) call_args() ([]ast.CallArg, map[string]ast.RedefinedOption } p.check(.comma) + p.skip_comments() if p.tok.kind == .rpar { p.error('unexpected end of arguments `$p.tok.lit`') diff --git a/modules/papyrus/parser/parser.v b/modules/papyrus/parser/parser.v index 3ad76fc..ce44324 100644 --- a/modules/papyrus/parser/parser.v +++ b/modules/papyrus/parser/parser.v @@ -184,7 +184,7 @@ pub fn (mut p Parser) top_stmt() ?ast.TopStmt { } } - panic("wtf") + util.compiler_error(msg: "dead code / break while?", phase: "parse", prefs: p.pref, file: @FILE, func: @FN, line: @LINE) } pub fn (mut p Parser) stmts() []ast.Stmt { @@ -369,6 +369,19 @@ pub fn (mut p Parser) script_decl() ast.ScriptDecl { name: name name_pos: p.tok.position() } + + if os.base(p.path).to_lower().ends_with('.psc') { + file_name := os.base(p.path).all_before_last('.') + if name.to_lower() != file_name.to_lower() { + p.error_with_pos("script name `${name}` does not match file name `${file_name}`", node.name_pos) + } + } + + if existing := p.table.find_type(name) { + if existing.kind == .script { + p.error_with_pos("script with name `${name}` is already defined", node.name_pos) + } + } mut parent_idx := 0 @@ -682,6 +695,7 @@ pub fn (mut p Parser) var_decl(is_object_var bool) ast.VarDecl { } right: expr typ: typ + is_object_var: is_object_var } flags: flags pos: pos @@ -737,6 +751,13 @@ fn (mut p Parser) next() { p.peek_tok3 = p.scanner.scan() } +@[inline] +fn (mut p Parser) skip_comments() { + for p.tok.kind == .comment { + p.next() + } +} + @[inline] pub fn (mut p Parser) check_name() string { name := p.tok.lit @@ -809,7 +830,7 @@ pub fn (mut p Parser) error(s string) { @[noreturn] pub fn (mut p Parser) error_with_pos(s string, pos token.Position) { if p.pref.output_mode == .stdout { - $if debug { + $if debug && !test { print_backtrace() } $else { diff --git a/modules/papyrus/parser/type.v b/modules/papyrus/parser/type.v index 386ebde..a024e2f 100644 --- a/modules/papyrus/parser/type.v +++ b/modules/papyrus/parser/type.v @@ -1,10 +1,11 @@ module parser import papyrus.ast +import papyrus.util pub fn (mut p Parser) get_parsed_type() ast.Type { if p.parsed_type == 0 { - panic("invalid type") + util.compiler_error(msg: "invalid parsed type", phase: "parser", prefs: p.pref, file: @FILE, func: @FN, line: @LINE) } typ := p.parsed_type diff --git a/modules/papyrus/scanner/scanner.v b/modules/papyrus/scanner/scanner.v index bce067d..8f9e6a8 100644 --- a/modules/papyrus/scanner/scanner.v +++ b/modules/papyrus/scanner/scanner.v @@ -29,11 +29,11 @@ mut: pub fn new_scanner_file(file_path string, prefs &pref.Preferences) &Scanner { if !os.exists(file_path) { - panic("$file_path doesn't exist") + util.fatal_error("file not exist `${file_path}`") } raw_text := util.read_file(file_path) or { - panic(err) + util.fatal_error("failed to read file: ${err}") } return &Scanner{ @@ -349,8 +349,9 @@ fn (mut s Scanner) end_of_file() token.Token { s.eofs++ if s.eofs > 50 { s.line_nr-- - panic('the end of file `$s.file_path` has been reached 50 times already, the v parser is probably stuck.\n' + - 'This should not happen. Please report the bug here, and include the last 2-3 lines of your source code:\n') + util.compiler_error(msg: "the end of file `${s.file_path}` has been reached 50 times already, the v parser is probably stuck.\n' + + 'This should not happen. Please report the bug here, and include the last 2-3 lines of your source code:\n", phase: "scanner", prefs: s.pref, file: @FILE, func: @FN, line: @LINE) + } if s.pos != s.text.len && s.eofs == 1 { s.inc_line_number() @@ -476,7 +477,9 @@ fn trim_slash_line_break(s string) string { mut start := 0 mut ret_str := s for { - idx := ret_str.index_after('\\\n', start) + idx := ret_str.index_after('\\\n', start) or { + util.compiler_error(msg: "index_after `\\n`; ${err}", phase: "scanner", file: @FILE, func: @FN, line: @LINE) + } if idx != -1 { ret_str = ret_str[..idx] + ret_str[idx + 2..].trim_left(' \n\t\v\f\r') start = idx @@ -642,6 +645,5 @@ pub fn (mut s Scanner) error(msg string) { pos: s.pos } - eprintln(util.formatted_error('Scanner error:', msg, s.file_path, pos)) - exit(1) + util.fatal_error(util.formatted_error('Scanner error:', msg, s.file_path, pos)) } \ No newline at end of file diff --git a/modules/papyrus/util/errors.v b/modules/papyrus/util/errors.v index 18514f0..6e45b9f 100644 --- a/modules/papyrus/util/errors.v +++ b/modules/papyrus/util/errors.v @@ -4,6 +4,7 @@ import os import term import papyrus.token import papyrus.errors +import pref const error_context_before = 2 const error_context_after = 2 @@ -36,14 +37,14 @@ pub fn formatted_error(kind string, omsg string, filepath string, pos token.Posi } // source, column := filepath_pos_to_source_and_column(filepath, pos) - position := '$path:${pos.line_nr + 1}:${imax(1, column + 1)}:' + position := '${path}:${pos.line_nr + 1}:${imax(1, column + 1)}:' scontext := source_context(kind, source, column, pos).join('\n') final_position := bold(position) final_kind := bold(color(kind, kind)) final_msg := emsg final_context := if scontext.len > 0 { '\n$scontext' } else { '' } // - return '$final_position $final_kind $final_msg$final_context'.trim_space() + return '${final_position} ${final_kind} ${final_msg}${final_context}'.trim_space() } pub fn filepath_pos_to_source_and_column(filepath string, pos token.Position) (string, int) { @@ -118,4 +119,72 @@ pub fn source_context(kind string, source string, column int, pos token.Position pub fn show_compiler_message(kind string, err errors.CompilerMessage) { ferror := util.formatted_error(kind, err.message, err.file_path, err.pos) eprintln(ferror) +} + +@[params] +pub struct CompilerConfigParams { +pub mut: + msg string + phase string + prefs ?&pref.Preferences + file string = @FILE + func string = @FN + line string = @LINE +} + +@[noreturn] +pub fn fatal_error(msg string) { + eprintln(msg) + exit(1) +} + +@[noreturn] +pub fn compiler_error(params CompilerConfigParams) { + info := collect_info() + + println( +" + +================================================================================ + INTERNAL COMPILER ERROR - This is a bug in the compiler! +================================================================================ + +You have encountered an internal compiler error. This is NOT your fault - it's +a bug in our compiler that should never happen. We apologize for the inconvenience. + +COMPILER INFORMATION: + Version: ${info.version} + Commit: ${info.git_commit} + Built: ${info.build_date} + Type: ${info.build_type} + +ERROR DETAILS: + Phase: ${params.phase} + Function: ${params.func} + File: ${params.file}:${params.line} + Message: ${params.msg} + +ENVIRONMENT: + OS: ${info.os} + exe: ${info.exe} + flags: ${arguments()} + +STACK TRACE:") +print_backtrace() + +println(" +PLEASE REPORT THIS BUG: + GitHub: https://github.com/russo-2025/papyrus-compiler/issues/new?template=bug-report.yml + Discord: https://discord.gg/JqQZXAXvPT (channel: #help) + +When reporting, please: + 1. Copy this ENTIRE error message + 2. Include the source code that triggered this error (if possible) + 3. Mention what you were trying to do + +Thank you for helping us improve the compiler! +================================================================================ +") + + exit(1) } \ No newline at end of file diff --git a/modules/papyrus/util/sys_info.v b/modules/papyrus/util/sys_info.v new file mode 100644 index 0000000..1bf5076 --- /dev/null +++ b/modules/papyrus/util/sys_info.v @@ -0,0 +1,221 @@ +module util + +import v.vmod +import os +import runtime +import encoding.iconv + +struct CmdConfig { + line int + command string +} + +fn cmd(c CmdConfig) string { + x := os.execute(c.command) + os_kind := os.user_os() + if x.exit_code < 0 || x.exit_code == 127 || (os_kind == 'windows' && x.exit_code == 1) { + return 'N/A' + } + if x.exit_code == 0 { + if c.line < 0 { + return x.output + } + output := x.output.split_into_lines() + if output.len > 0 && output.len > c.line { + return output[c.line] + } + } + return 'Error: ${x.output}' +} + +fn cpu_info() map[string]string { + info := os.execute('cat /proc/cpuinfo') + if info.exit_code != 0 { + return map[string]string{} + } + + return parse(info.output, ':') +} + +fn parse(config string, sep string) map[string]string { + mut m := map[string]string{} + lines := config.split_into_lines() + for line in lines { + sline := line.trim_space() + if sline.len == 0 || sline[0] == `#` { + continue + } + x := sline.split(sep) + if x.len < 2 { + continue + } + m[x[0].trim_space().to_lower()] = x[1].trim_space().trim('"') + } + return m +} + +pub fn collect_info() DeviceInfo { + mut os_kind := os.user_os() + + mut arch_details := []string{} + arch_details << '${runtime.nr_cpus()} cpus' + if runtime.is_32bit() { + arch_details << '32bit' + } + if runtime.is_64bit() { + arch_details << '64bit' + } + if runtime.is_big_endian() { + arch_details << 'big endian' + } + if runtime.is_little_endian() { + arch_details << 'little endian' + } + if os_kind == 'macos' { + arch_details << cmd(command: 'sysctl -n machdep.cpu.brand_string') + } + if os_kind == 'linux' { + info := cpu_info() + + mut cpu_details := '' + if cpu_details == '' { + cpu_details = info['model name'] or { "`cat /proc/cpuinfo` could not run" } + } + if cpu_details == '' { + cpu_details = info['hardware'] or { "`cat /proc/cpuinfo` could not run" } + } + if cpu_details == '' { + cpu_details = os.uname().machine + } + arch_details << cpu_details + } + if os_kind == 'windows' { + arch_details << cmd( + command: 'wmic cpu get name /format:table' + line: 2 + ) + } + + mut os_details := '' + wsl_check := cmd(command: 'cat /proc/sys/kernel/osrelease') + if os_kind == 'linux' { + os_details = get_linux_os_name() + if cpu_info()['flags'] or { "`cat /proc/cpuinfo` could not run" }.contains('hypervisor') { + if wsl_check.contains('microsoft') { + // WSL 2 is a Managed VM and Full Linux Kernel + // See https://docs.microsoft.com/en-us/windows/wsl/compare-versions + os_details += ' (WSL 2)' + } else { + os_details += ' (VM)' + } + } + // WSL 1 is NOT a Managed VM and Full Linux Kernel + // See https://docs.microsoft.com/en-us/windows/wsl/compare-versions + if wsl_check.contains('Microsoft') { + os_details += ' (WSL)' + } + // From https://unix.stackexchange.com/a/14346 + awk_cmd := '[ "$(awk \'\$5=="/" {print \$1}\' = u8(OpCode._opcode_end) { - panic("invalid opcode: 0x" + v.hex()) + util.compiler_error(msg: "invalid opcode: 0x${v.hex()}", phase: "pex opcode_from_byte", file: @FILE, func: @FN, line: @LINE) } return unsafe { OpCode(v) } @@ -684,7 +686,8 @@ fn (op OpCode) get_count_arguments() int { return 3//3+ } ._opcode_end { - panic("error") + util.compiler_error(msg: "invalid op code ${op}", phase: "pex op", file: @FILE, func: @FN, line: @LINE) + return 0 } } } \ No newline at end of file diff --git a/modules/pex/reader.v b/modules/pex/reader.v index c24df29..d8b4830 100644 --- a/modules/pex/reader.v +++ b/modules/pex/reader.v @@ -1,6 +1,7 @@ module pex import os +import papyrus.util pub struct Reader{ pub mut: @@ -11,16 +12,16 @@ pub mut: pub fn read_from_file(path string) &PexFile { if !os.is_file(path) { - eprintln("invalid file path: `${path}`") - exit(1) + util.fatal_error("invalid file path: `${path}`") } if os.file_ext(path) != ".pex" { - eprintln("unexpected file extension `*${os.file_ext(path)}` , expecting `*.pex`") - exit(1) + util.fatal_error("unexpected file extension `*${os.file_ext(path)}` , expecting `*.pex`") } - mut bytes := os.read_bytes(path) or { panic(err) } + mut bytes := os.read_bytes(path) or { + util.fatal_error("failed to read bytes: ${err}") + } assert bytes.len > 0 @@ -321,6 +322,5 @@ fn (mut r Reader) read_variable_value() !VariableValue { } fn (mut r Reader) error(msg string) { - eprintln("Reader error: " + msg) - exit(1) + util.fatal_error("Reader error: ${msg}") } \ No newline at end of file diff --git a/modules/pref/pref.v b/modules/pref/pref.v index dcf3b70..55f03fb 100644 --- a/modules/pref/pref.v +++ b/modules/pref/pref.v @@ -1,6 +1,7 @@ module pref import os +import strings import papyrus.errors pub enum OutputMode { @@ -14,12 +15,32 @@ pub enum Backend { original // use a vanilla compiler to compile files } +pub fn (b Backend) str() string { + return match b { + .pex { "-pex" } + .check { "-check" } + .original { "-original" } + } +} + pub enum RunMode { compile read disassembly create_dump help + version +} + +pub fn (m RunMode) str() string { + return match m { + .version { "version" } + .compile { "compile" } + .read { "read" } + .disassembly { "disassembly" } + .create_dump { "create-dump" } + .help { "help" } + } } @[heap] @@ -37,6 +58,32 @@ pub mut: stats_enabled bool } +pub fn (p Preferences) cmd_str() string { + mut b := strings.new_builder(30) + + b.write_string(p.mode.str()) + b.write_string(" ") + + b.write_string(p.backend.str()) + b.write_string(" ") + + for path in p.paths { + b.write_string("-i \"${path}\" ") + } + + b.write_string("-o \"${p.output_dir}\" ") + + for dir in p.header_dirs { + b.write_string("-h \"${dir}\" ") + } + + if p.no_cache { + b.write_string("-nocache") + } + + return b.str() +} + fn (mut p Preferences) parse_compile_args(args []string) { p.mode = .compile p.backend = .pex @@ -103,6 +150,10 @@ fn (mut p Preferences) parse_compile_args(args []string) { p.header_dirs << path i++ } + "-pex" { + p.backend = .pex + i++ + } "-check" { p.backend = .check i++ @@ -157,6 +208,9 @@ pub fn parse_args() Preferences { } match args[0] { + "version" { + p.mode = .version + } "help" { p.mode = .help } @@ -194,6 +248,8 @@ pub fn parse_args() Preferences { p.paths << path } + "createdump", + "create_dump", "create-dump" { if args.len < 2 { error(errors.msg_wrong_number_of_arguments) diff --git a/modules/tests/ast_test.v b/modules/tests/ast_test.v index 251a198..b4214f8 100644 --- a/modules/tests/ast_test.v +++ b/modules/tests/ast_test.v @@ -3,13 +3,15 @@ import papyrus.ast import papyrus.parser import papyrus.checker import papyrus.token +import papyrus.errors const prefs = pref.Preferences { - paths: []string{} - mode: .compile - backend: .pex - no_cache: true - } + paths: []string{} + mode: .compile + backend: .pex + no_cache: true + output_mode: .silent +} const other_src = "Scriptname OtherScript @@ -58,7 +60,7 @@ int Property myAutoProp = 123 Auto OtherScript Property otherProp Auto OtherScript Property OtherScript2 Auto\n" -fn compile(src string) (&ast.File, &ast.Table) { +fn compile(src string) (&ast.File, &ast.Table, []errors.Error) { mut table := ast.new_table() mut global_scope := &ast.Scope{} @@ -76,16 +78,20 @@ fn compile(src string) (&ast.File, &ast.Table) { c.check(mut parent_file) c.check(mut file) - assert c.errors.len == 0, src - - return file, table + return file, table, c.errors } fn compile_top_stmts(src string) ([]ast.TopStmt, &ast.Table) { - mut file, table := compile(src) + mut file, table, errs := compile(src) + assert errs.len == 0, src return file.stmts, table } +fn compile_top_stmts_error(src string) ([]ast.TopStmt, &ast.Table, []errors.Error) { + mut file, table, errs := compile(src) + return file.stmts, table, errs +} + fn compile_stmts(src string) ([]ast.Stmt, &ast.Table) { full_src := "Function MyTestFn(string arg1, int arg2, float arg3, bool arg4, ABCD obj, CDFG pobj, int[] int_arr)\n${src}\nEndFunction\n" mut top_stmts, table := compile_top_stmts(full_src) @@ -158,6 +164,28 @@ fn test_prefix_expr() { assert ((expr as ast.PrefixExpr).right as ast.Ident).typ == ast.int_type } +fn test_multiline_comment_inside_paren_condition() { + stmts, _ := compile_stmts(' + if !(arg4 ;/&& False/;) + return + endif + ') + + assert stmts.len == 1 + assert stmts[0] is ast.If + + if_stmt := stmts[0] as ast.If + assert if_stmt.branches.len == 1 + + cond := if_stmt.branches[0].cond as ast.PrefixExpr + assert cond.op == token.Kind.not + assert cond.right is ast.ParExpr + + inner := (cond.right as ast.ParExpr).expr + assert inner is ast.Ident + assert (inner as ast.Ident).name == 'arg4' +} + fn test_infix() { mut expr := &ast.Expr(ast.EmptyExpr{}) @@ -1058,4 +1086,414 @@ fn test_line_nr_bug() { assert stmts.len == 3 assert (((stmts[2] as ast.VarDecl).assign as ast.AssignStmt).right as ast.IntegerLiteral).val == "123" assert ((stmts[2] as ast.VarDecl).assign as ast.AssignStmt).pos.line_nr == start_line + 2 +} + +fn test_object_property_object_none() { + mut stmts := []ast.TopStmt{} + mut table := ast.new_table() + mut prop := ast.PropertyDecl{} + + stmts, table = compile_top_stmts("ABCD Property MyPropAutoCast = none Auto") + prop = stmts.last() as ast.PropertyDecl + + abcd_type := table.find_type_idx("ABCD") + assert abcd_type != 0 + + assert prop.name == "MyPropAutoCast" + assert prop.typ == abcd_type + assert prop.is_auto == true + assert prop.expr is ast.NoneLiteral + + stmts, table = compile_top_stmts("ABCD[] Property MyPropAutoCast = none Auto") + prop = stmts.last() as ast.PropertyDecl + + abcd_array_type := table.find_type_idx("ABCD[]") + assert abcd_array_type != 0 + + assert prop.name == "MyPropAutoCast" + assert prop.typ == abcd_array_type + assert prop.is_auto == true + assert prop.expr is ast.NoneLiteral +} + +fn test_object_property_cast() { + mut stmts := []ast.TopStmt{} + mut prop := ast.PropertyDecl{} + + // to bool + stmts, _ = compile_top_stmts("bool Property MyPropAutoCast = none Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.bool_type + assert prop.is_auto == true + assert prop.expr is ast.BoolLiteral + assert (prop.expr as ast.BoolLiteral).val == "False" + + stmts, _ = compile_top_stmts("bool Property MyPropAutoCast = 0 Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.bool_type + assert prop.is_auto == true + assert prop.expr is ast.BoolLiteral + assert (prop.expr as ast.BoolLiteral).val == "false" + + stmts, _ = compile_top_stmts("bool Property MyPropAutoCast = 1 Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.bool_type + assert prop.is_auto == true + assert prop.expr is ast.BoolLiteral + assert (prop.expr as ast.BoolLiteral).val == "true" + + stmts, _ = compile_top_stmts("bool Property MyPropAutoCast = \"\" Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.bool_type + assert prop.is_auto == true + assert prop.expr is ast.BoolLiteral + assert (prop.expr as ast.BoolLiteral).val == "false" + + stmts, _ = compile_top_stmts("bool Property MyPropAutoCast = \"asd\" Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.bool_type + assert prop.is_auto == true + assert prop.expr is ast.BoolLiteral + assert (prop.expr as ast.BoolLiteral).val == "true" + + + // to int + stmts, _ = compile_top_stmts("int Property MyPropAutoCast = 111.0 Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.int_type + assert prop.is_auto == true + assert prop.expr is ast.IntegerLiteral + assert (prop.expr as ast.IntegerLiteral).val == "111" + + stmts, _ = compile_top_stmts("int Property MyPropAutoCast = \"123\" Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.int_type + assert prop.is_auto == true + assert prop.expr is ast.IntegerLiteral + assert (prop.expr as ast.IntegerLiteral).val == "123" + + stmts, _ = compile_top_stmts("int Property MyPropAutoCast = true Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.int_type + assert prop.is_auto == true + assert prop.expr is ast.IntegerLiteral + assert (prop.expr as ast.IntegerLiteral).val == "1" + + // to float + stmts, _ = compile_top_stmts("float Property MyPropAutoCast = 111 Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.float_type + assert prop.is_auto == true + assert prop.expr is ast.FloatLiteral + assert (prop.expr as ast.FloatLiteral).val == "111.0" + + stmts, _ = compile_top_stmts("float Property MyPropAutoCast = \"123.12\" Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.float_type + assert prop.is_auto == true + assert prop.expr is ast.FloatLiteral + assert (prop.expr as ast.FloatLiteral).val == "123.12" + + stmts, _ = compile_top_stmts("float Property MyPropAutoCast = false Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.float_type + assert prop.is_auto == true + assert prop.expr is ast.FloatLiteral + assert (prop.expr as ast.FloatLiteral).val == "0.0" + + // to string + stmts, _ = compile_top_stmts("string Property MyPropAutoCast = 1 Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.string_type + assert prop.is_auto == true + assert prop.expr is ast.StringLiteral + assert (prop.expr as ast.StringLiteral).val == "1" + + stmts, _ = compile_top_stmts("string Property MyPropAutoCast = 12.13 Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.string_type + assert prop.is_auto == true + assert prop.expr is ast.StringLiteral + assert (prop.expr as ast.StringLiteral).val == "12.13" + + stmts, _ = compile_top_stmts("string Property MyPropAutoCast = false Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.string_type + assert prop.is_auto == true + assert prop.expr is ast.StringLiteral + assert (prop.expr as ast.StringLiteral).val == "false" + + stmts, _ = compile_top_stmts("string Property MyPropAutoCast = none Auto") + prop = stmts.last() as ast.PropertyDecl + + assert prop.name == "MyPropAutoCast" + assert prop.typ == ast.string_type + assert prop.is_auto == true + assert prop.expr is ast.StringLiteral + assert (prop.expr as ast.StringLiteral).val == "None" +} + +fn test_error_state_fn_with_default_arg() { + mut stmts := []ast.TopStmt{} + mut table := ast.new_table() + mut errs := []errors.Error{} + + mut src := " + Int Function MyFunc(int n1, int n2 = 12) + return n1 + n2 + EndFunction + + State Disabled + Int Function MyFunc(int n1, int n2 = 12) + return n1 + n2 + EndFunction + EndState" + + stmts, table = compile_top_stmts(src) + + src = " + Int Function MyFunc(int n1, int n2 = 12) + return n1 + n2 + EndFunction + + State Disabled + Int Function MyFunc(int n1, int n2 = none) + return n1 + n2 + EndFunction + EndState" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 2 + assert errs[0].message == "default value for parameter `n2` has type `None` which cannot be assigned to parameter type `Int`" + assert errs[1].message == "declaration of the MyFunc function in the Disabled state is different from the declaration in the empty state" + + src = " + Int Function MyFunc(int n1, int n2 = 12) + return n1 + n2 + EndFunction + + State Disabled + Int Function MyFunc(int n1, int n2 = 11) + return n1 + n2 + EndFunction + EndState" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 1 + assert errs[0].message == "declaration of the MyFunc function in the Disabled state is different from the declaration in the empty state" +} + +fn test_fn_default_arg_comptime_cast() { + mut stmts := []ast.TopStmt{} + mut table := ast.new_table() + mut errs := []errors.Error{} + + mut src := " + Int Function MyFunc(int n1, int n2 = \"12\") + return n1 + EndFunction" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 0 + + src = " + Int Function MyFunc(int n1, string n2 = 12) + return n1 + EndFunction" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 0 + + src = " + Int Function MyFunc(int n1, bool n2 = 1) + return n1 + EndFunction" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 0 +} + +fn test_error_fn_default_arg() { + mut stmts := []ast.TopStmt{} + mut table := ast.new_table() + mut errs := []errors.Error{} + + mut src := " + Int Function MyFunc(int n1, int n2 = none) + return n1 + n2 + EndFunction" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 1 + assert errs[0].message == "default value for parameter `n2` has type `None` which cannot be assigned to parameter type `Int`" + + src = " + Int Function MyFunc(int n1, int n2 = ) + return n1 + n2 + EndFunction" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 1 + assert errs[0].message == "optional parameter `n2` must have a default value" + + src = " + Int Function MyFunc(int n1, int n2 = 1 + 1) + return n1 + n2 + EndFunction" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 1 + assert errs[0].message == "default value for parameter `n2` must be a literal" +} + +fn test_error_msg() +{ + mut stmts := []ast.TopStmt{} + mut table := ast.new_table() + mut errs := []errors.Error{} + mut src := "" + + src = " + Function MyFunc(int n1, int n2) + MyFunc(foooo, 1) + EndFunction" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 2 + assert errs[0].message == "undefined identifier `foooo`" + assert errs[1].message == "cannot convert type `None` to type `Int`" + + src = " + Function MyFunc(int n1, int n2) + MyFunc(ABCD.foooo, 1) + EndFunction" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 3 + assert errs[0].message == "undefined identifier `ABCD`" + assert errs[1].message == "field or property `foooo` not found" + assert errs[2].message == "cannot convert type `None` to type `Int`" + + src = " + InvalidType Property propWithInvalidType Auto + Function MyFunc(ABCD n1, int n2) + MyFunc(n1.propWithInvalidType, 1) + EndFunction" + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 3 + assert errs[0].message == "undefined type: `InvalidType`" // checker property error + assert errs[1].message == "undefined type: `InvalidType`" // checker expr error + assert errs[2].message == "undefined type: `InvalidType`" // checker expr error + + src = " + InvalidType propWithInvalidType + Function MyFunc(ABCD n1, int n2) + If propWithInvalidType + EndIf + EndFunction" + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 2 + assert errs[0].message == "undefined type: `InvalidType`" + assert errs[1].message == "undefined type: `InvalidType`" + + src = " + InvalidType Function MyFunc() + return none + EndFunction" + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 2 + assert errs[0].message == "undefined type: `InvalidType`" + assert errs[1].message == "undefined type: `InvalidType`" +} + +fn test_none_value() +{ + mut stmts := []ast.TopStmt{} + mut table := ast.new_table() + mut errs := []errors.Error{} + mut src := "" + + src = "ABCD ABCDInstance = none + string[] MyStringArray = none + + String[] MyStringArrayValue = none + String[] Property MyStringArrayProp + String[] Function Get() + return none + EndFunction + Function Set(string[] value) + MyStringArrayValue = none + EndFunction + EndProperty + + ABCD ABCDValue = none + ABCD Property ABCDProp + ABCD Function Get() + return none + EndFunction + Function Set(ABCD value) + ABCDValue = none + EndFunction + EndProperty + + Function MyFunc1(int n1, ABCD n_1_2) + EndFunction + + Function MyFunc2(int n1, string[] n_2_2) + EndFunction + + Function MyFunc3(int n1, ABCD n_3_2 = none) + EndFunction + + Function MyFunc4(int n1, string[] n_4_2 = none) + EndFunction + + String[] Function Foo() + ABCD localValue1 = none + String[] localValue2 = none + + ABCDInstance = none + MyStringArray = none + MyStringArrayProp = none + ABCDProp = none + MyFunc1(123, none) + MyFunc2(123, none) + MyFunc3(123) + MyFunc4(123) + + return none + EndFunction + " + + stmts, table, errs = compile_top_stmts_error(src) + assert errs.len == 0 } \ No newline at end of file diff --git a/modules/tests/checker_cast_test.v b/modules/tests/checker_cast_test.v index f362f64..b2f3363 100644 --- a/modules/tests/checker_cast_test.v +++ b/modules/tests/checker_cast_test.v @@ -8,6 +8,7 @@ const prefs = pref.Preferences { mode: .compile backend: .pex no_cache: true + output_mode: .silent } const other_src = @@ -210,9 +211,9 @@ fn test_cast2() { int_array_typ := table.find_type_idx("Int[]") assert int_array_typ != 0 - assert !c.valid_type(typ, ast.none_type) + assert !c.valid_type(typ, ast.none_type, false) assert c.can_autocast(ast.none_type, typ) - assert !c.valid_type(int_array_typ, ast.none_type) + assert !c.valid_type(int_array_typ, ast.none_type, false) assert c.can_autocast(ast.none_type, int_array_typ) } \ No newline at end of file diff --git a/modules/tests/errors_test.v b/modules/tests/errors_test.v index 2a7199f..9902e48 100644 --- a/modules/tests/errors_test.v +++ b/modules/tests/errors_test.v @@ -64,4 +64,17 @@ fn test_call_expr() { errs := compile_expr('obj.FuncIntArg()') assert errs.len == 1 assert errs[0].message == 'function takes 1 parameters not 0' +} + +fn test_none_plus_int_reports_error() { + errs := compile_expr('none + 1') + assert errs.len == 1 + assert errs[0].message == 'cannot cast from `None` to `Int`' +} + +fn test_undefined_type_in_infix_reports_error() { + errs := compile_top_stmts('Function Broken(Actor value)\n\tbool b = value && true\nEndFunction') + assert errs.len >= 1 + assert errs[0].message == 'invalid type `Actor` for parameter #1 `value` in function `Broken`' + assert errs.any(it.message == 'undefined type: `Actor`') } \ No newline at end of file diff --git a/modules/tests/iEquip/LibFire.psc b/modules/tests/iEquip/LibFire.psc deleted file mode 100644 index 4ed8496..0000000 --- a/modules/tests/iEquip/LibFire.psc +++ /dev/null @@ -1,257 +0,0 @@ -ScriptName LibFire Hidden - -{ Actor } - -; Returns the index of the first keyword in `argKeywords` assigned to `akActor` - if not found, -1 is returned -Int Function ActorFindAnyKeyword(Actor akActor, Keyword[] argKeywords) Global Native - -; Returns the index of the first perk in `argPerks` assigned to `akActor` - if not found, -1 is returned -Int Function ActorFindAnyPerk(Actor akActor, Perk[] argPerks) Global Native - -; Returns an array of factions that track crime and of which `akActor` is a current member -Faction[] Function ActorFindCrimeFactions(Actor akActor) Global Native - -; Returns whether `akActor` has any keyword in `akKeywords` -Bool Function ActorHasAnyKeyword(Actor akActor, FormList akKeywords) Global Native - -; Returns whether `akActor` has `akPerk` and its rank is `aiRank` - if match not found, `False` is returned -Bool Function ActorHasPerkRank(Actor akActor, Perk akPerk, Int aiRank) Global Native - -; Returns whether `akActor` is commanded by `akOtherActor` -Bool Function ActorIsCommandedBy(Actor akActor, Actor akOtherActor) Global Native - -; Returns whether `akActor` is commanded by the player -Bool Function ActorIsCommandedByPlayer(Actor akActor) Global Native - -; Returns whether `akActor` is a teammate or player-controlled commanded/summoned actor -Bool Function ActorIsFollower(Actor akActor) Global Native - -; Returns whether `akActor` is a member of any faction in `akFactions` with a rank greater than -1 -Bool Function ActorIsInAnyFaction(Actor akActor, FormList akFactions) Global Native - -; Returns whether `akActor` is a member of `akFaction` with a rank greater than -1 -Bool Function ActorIsInFaction(Actor akActor, Faction akFaction) Global Native - -; Returns whether `akActor` is a summoned actor -Bool Function ActorIsSummoned(Actor akActor) Global Native - -; Returns the current rank of `akPerk` assigned to `akActor` - if perk not assigned, -1 is returned -Int Function GetActorPerkRank(Actor akActor, Perk akPerk) Global Native - -; Returns an array of perks assigned to `akActor` -Perk[] Function GetActorPerks(Actor akActor) Global Native - -; Returns an array of commanded actors for `akActor` or `None` -Actor[] Function GetCommandedActors(Actor akActor) Global Native - -; Returns the commanding actor for `akActor` when actor is commanded -Actor Function GetCommandingActor(Actor akActor) Global Native - -; Returns the ammo currently used by `akActor` -Ammo Function GetEquippedAmmo(Actor akActor) Global Native - -{ Array } - -; Searches `argActors` for closest actor to `akOrigin` and returns index of member - if not found, -1 is returned -Int Function ArrayFindClosestActor(Actor[] argActors, ObjectReference akOrigin) Global Native - -; Searches `argHaystack` for `afValue` and returns index of member - if not found, -1 is returned -Int Function ArrayFindGlobalValue(GlobalVariable[] argGlobals, Float afValue) Global Native - -{ Faction } - -; Returns flag values for `akFaction` -Bool Function GetFactionIgnoresMurder(Faction akFaction) Global Native -Bool Function GetFactionIgnoresAssault(Faction akFaction) Global Native -Bool Function GetFactionIgnoresTrespass(Faction akFaction) Global Native -Bool Function GetFactionIgnoresPickpocket(Faction akFaction) Global Native -Bool Function GetFactionIgnoresStealing(Faction akFaction) Global Native -Bool Function GetFactionIgnoresWerewolf(Faction akFaction) Global Native -Bool Function GetFactionReportsCrimesAgainstMembers(Faction akFaction) Global Native -Bool Function GetFactionTracksCrime(Faction akFaction) Global Native -Bool Function GetFactionUsesCrimeGoldDefaults(Faction akFaction) Global Native - -; Returns crime value (murder, assault, etc.) for `akFaction` at `aiMember` offset -; Valid offsets: -; - 0x0 Arrest (cast to Boolean) -; - 0x01 Attack On Sight (cast to Boolean) -; - 0x02 Murder (cast to Int) -; - 0x04 Assault (cast to Int) -; - 0x06 Trespass (cast to Int) -; - 0x08 Pickpocket (cast to Int) -; - 0x0C Steal Multiplier (Float) -; - 0x10 Escape (cast to Int) -; - 0x12 Werewolf (cast to Int) -Float Function GetFactionCrimeValue(Faction akFaction, Int aiMember) Global Native - -; Sets `akFaction` as ally or friend to each faction in `akFactions` -Function SetAllies(Faction akFaction, FormList akFactions, Bool abSelfIsFriendToOther = False, Bool abOtherIsFriendToSelf = False) Global Native - -; Sets `akFaction` as enemy or neutral to each faction in `akFactions` -Function SetEnemies(Faction akFaction, FormList akFactions, Bool abSelfIsNeutralToOther = False, Bool abOtherIsNeutralToSelf = False) Global Native - -; Copies violent and nonviolent crime gold from `akFaction` to `akOtherFaction`. If `abModify` is True, -; adds crime gold values to existing values instead. -Function CopyFactionCrimeGold(Faction akFaction, Faction akOtherFaction, Bool abModify) Global Native - -; Zeroes out violent and nonviolent crime gold on `akFaction` -Function ResetFactionCrimeGold(Faction akFaction) Global Native - -; Clears cached faction fight reactions (sometimes required to update faction actors) -; Note: SetAllies and SetEnemies already clears the faction reactions cache. -Bool Function ClearFactionReactionsCache() Global Native - -{ FormList } - -; Returns whether `akHaystack` contains each form in `argNeedles` -Bool[] Function SearchListForForms(FormList akHaystack, Form[] argNeedles) Global Native - -; Returns whether each formlist in `akHaystack` contains `akNeedle` -Bool[] Function SearchListsForForm(FormList akHaystack, Form akNeedle) Global Native - -{ ObjectReference } - -; Returns closest actor within `afRadius` of and line of sight to `akOrigin` -Actor Function FindClosestActorByLOS(ObjectReference akOrigin, Float afRadius) Global Native - -; Returns closest actor who is a member of `akFaction` within `afRadius` of `akOrigin` -Actor Function FindClosestActorInFaction(ObjectReference akOrigin, Faction akFaction, Float afRadius) Global Native - -; Returns closest actor who is a member of `akFaction` within `afRadius` of and line of sight to `akOrigin` -Actor Function FindClosestActorInFactionByLOS(ObjectReference akOrigin, Faction akFaction, Float afRadius) Global Native - -; Returns actors in loaded cells within `afRadius` of `akOrigin` -Actor[] Function FindNearbyActors(ObjectReference akOrigin, Float afRadius) Global Native - -; Returns actors who are members of `akFaction` in loaded cells within `afRadius` of `akOrigin` -Actor[] Function FindNearbyActorsInFaction(ObjectReference akOrigin, Faction akFaction, Float afRadius) Global Native - -; Returns actors who are members of `akFaction` in loaded cells within `afRadius` of and line of sight to `akOrigin` -Actor[] Function FindNearbyActorsInFactionByLOS(ObjectReference akOrigin, Faction akFaction, Float afRadius) Global Native - -; Returns books in loaded cells within `afRadius` of `akOrigin` -ObjectReference[] Function FindNearbyBooks(ObjectReference akOrigin, Float afRadius) Global Native - -; Returns commanded actors in loaded cells within `afRadius` of `akOrigin` who are controlled by `akOrigin` -Actor[] Function FindNearbyCommandedActors(ObjectReference akOrigin, Float afRadius) Global Native - -; Returns teammates and player-controlled commanded/summoned actors in loaded cells within `afRadius` of player -Actor[] Function FindNearbyFollowers(Float afRadius) Global Native - -; Returns summoned actors in loaded cells within `afRadius` of `akOrigin` -Actor[] Function FindNearbySummons(ObjectReference akOrigin, Float afRadius) Global Native - -; Returns teammates in loaded cells within `afRadius` of player -Actor[] Function FindNearbyTeammates(Float afRadius) Global Native - -; Returns the permanent value of `asActorValue` for `akActor` -Float Function GetPermanentActorValue(ObjectReference akActor, String asActorValue) Global Native - -{ Player Character } - -; Returns an array of factions with which the player is infamous -Faction[] Function FindPlayerInfamousWithFactions() Global Native - -; Returns an array of factions to which the player owes crime gold -Faction[] Function FindPlayerWantedByFactions() Global Native - -; Returns whether the player is infamous with any faction -Bool Function IsPlayerInfamous() Global Native - -; Returns whether the player is wanted by any faction -Bool Function IsPlayerWanted() Global Native - -{ Race } - -; Returns the skill boost value of `asActorValue` for `akRace` -Int Function GetRaceSkillBonus(Race akRace, String asActorValue) Global Native - -; Returns names of boosted actor values for `akRace` -String[] Function GetRaceSkills(Race akRace) Global Native - -; Returns the base male height for `akRace` -Float Function GetRaceMaleHeight(Race akRace) Global Native - -; Returns the base female height for `akRace` -Float Function GetRaceFemaleHeight(Race akRace) Global Native - -; Returns the base male weight for `akRace` -Float Function GetRaceMaleWeight(Race akRace) Global Native - -; Returns the base female weight for `akRace` -Float Function GetRaceFemaleWeight(Race akRace) Global Native - -; Returns the starting health for `akRace` -Float Function GetRaceStartingHealth(Race akRace) Global Native - -; Returns the starting magicka for `akRace` -Float Function GetRaceStartingMagicka(Race akRace) Global Native - -; Returns the starting stamina for `akRace` -Float Function GetRaceStartingStamina(Race akRace) Global Native - -; Returns the base carry weight for `akRace` -Float Function GetRaceCarryWeight(Race akRace) Global Native - -; Returns the base mass for `akRace` -Float Function GetRaceMass(Race akRace) Global Native - -; Returns the base health regen for `akRace` -Float Function GetRaceHealthRegen(Race akRace) Global Native - -; Returns the base magicka regen for `akRace` -Float Function GetRaceMagickaRegen(Race akRace) Global Native - -; Returns the base stamina regen for `akRace` -Float Function GetRaceStaminaRegen(Race akRace) Global Native - -; Returns the base unarmed damage for `akRace` -Float Function GetRaceUnarmedDamage(Race akRace) Global Native - -; Returns the base unarmed reach for `akRace` -Float Function GetRaceUnarmedReach(Race akRace) Global Native - -{ String } - -; Returns whether `asText` contains `asSubText` (all Papyrus string comparisons are case-insensitive) -Bool Function ContainsText(String asText, String asSubText) Global Native - -; Replaces `{}` tokens in `asFormat` with `argValues` (supports up to 9 values) -; Note: Arrays exceeding the maximum number of values will be truncated. -; Syntax: https://fmt.dev/latest/syntax.html -String Function FormatFloat(String asFormat, Float[] argValues) Global Native - -; Replaces `{}` tokens in `asFormat` with `argValues` (supports up to 9 values) -; Note: Arrays exceeding the maximum number of values will be truncated. -; Syntax: https://fmt.dev/latest/syntax.html -String Function FormatInt(String asFormat, Int[] argValues) Global Native - -; Replaces `{}` tokens in `asFormat` with `argValues` (supports up to 9 values) -; Note: Arrays exceeding the maximum number of values will be truncated. -; Syntax: https://fmt.dev/latest/syntax.html -String Function FormatString(String asFormat, String[] argValues) Global Native - -; Returns the hexadecimal string representation of `aiSource` -String Function IntToHex(Int aiSource) Global Native - -; Returns `asSource` as array of String split by `asDelimiter` -String[] Function SplitString(String asSource, String asDelimiter) Global Native - -; Returns `asSource` as array of Float split by `asDelimiter` -Float[] Function StrToFloatArray(String asSource, String asDelimiter) Global Native - -; Returns `asSource` as array of Int split by `asDelimiter` -Int[] Function StrToIntArray(String asSource, String asDelimiter) Global Native - -; Returns `asSource` wrapped to column `aiMaxLength` with lines delimited by newline character -String Function WrapString(String asSource, Int aiMaxLength) Global Native - -{ Spell } - -; Returns highest minimum skill level for `akSpell` (does not account for conditions) -Int Function GetHighestMinSkillLevelForSpell(Spell akSpell) Global Native - -{ Time } - -; Returns hours passed since current day began -Float Function GetCurrentHourOfDay() Global Native diff --git a/modules/tests/iEquip/LibMathf.psc b/modules/tests/iEquip/LibMathf.psc deleted file mode 100644 index 13845be..0000000 --- a/modules/tests/iEquip/LibMathf.psc +++ /dev/null @@ -1,122 +0,0 @@ -ScriptName LibMathf Hidden - - -; Returns the absolute value of f -Float Function Abs(Float f) Global Native - -; Returns the arc-cosine of f - the angle in radians whose cosine is f -Float Function Acos(Float f) Global Native - -; Returns the arc-tangent of f - the angle in radians whose tangent is f -Float Function Atan(Float f) Global Native - -; Returns the angle in radians whose tan is y/x -Float Function Atan2(Float y, Float x) Global Native - -; Compares two floating point values and returns true if they are similar -Bool Function Approximately(Float a, Float b) Global Native - -; Returns the arc-sine of f - the angle in radians whose sine is f -Float Function Asin(Float f) Global Native - -; Returns the smallest number (as Float) greater than or equal to f -Float Function Ceil(Float f) Global Native - -; Returns the smallest number (as Int) greater than or equal to f -Int Function CeilToInt(Float f) Global Native - -; Returns value clamped between min and max -Float Function Clamp(Float value, Float min, Float max) Global Native - -; Returns value clamped between 0 and 1 -Float Function Clamp01(Float value) Global Native - -; Returns the closest power of two number -Int Function ClosestPowerOfTwo(Int value) Global Native - -; Returns the cosine of angle f -Float Function Cos(Float f) Global Native - -; Calculates the shortest difference between two angles in degrees -Float Function DeltaAngle(Float current, Float target) Global Native - -; Returns e raised to the specified power -Float Function Exp(Float p) Global Native - -; Returns the largest number (as Float) smaller than or equal to f -Float Function Floor(Float f) Global Native - -; Returns the largest number (as Int) smaller than or equal to f -Int Function FloorToInt(Float f) Global Native - -; Returns t if value is true or f if value is false -Float Function IfThen(Bool value, Float t, Float f) Global Native - -; Returns true if value is between min and max -Bool Function InRange(Float value, Float min, Float max) Global Native - -; Calculates the linear parameter t that produces the interpolant value within the range [a, b] -Float Function InverseLerp(Float a, Float b, Float value) Global Native - -; Returns true if the number is power of two -Bool Function IsPowerOfTwo(Int n) Global Native - -; Linearly interpolates between a and b by t -Float Function Lerp(Float a, Float b, Float t) Global Native - -; Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees -Float Function LerpAngle(Float a, Float b, Float t) Global Native - -; Linearly interpolates between a and b by t with no limit to t -Float Function LerpUnclamped(Float a, Float b, Float t) Global Native - -; Returns the largest of two numbers -Float Function Max(Float x, Float y) Global Native - -; Returns the smallest of two numbers -Float Function Min(Float x, Float y) Global Native - -; Moves current value towards target -Float Function MoveTowards(Float current, Float target, Float maxDelta) Global Native - -; Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees -Float Function MoveTowardsAngle(Float current, Float target, Float maxDelta) Global Native - -; Returns the next power of two greater than or equal to n -Int Function NextPowerOfTwo(Int n) Global Native - -; Returns number that will increment and decrement between 0 and length -Float Function PingPong(Float t, Float len) Global Native - -; Returns the logarithm of a number -Float Function Log(Float f) Global Native - -; Returns the base 10 logarithm of a number -Float Function Log10(Float f) Global Native - -; Returns f raised to power p -Float Function Pow(Float f, Float p) Global Native - -; Loops t so t is never larger than length and never smaller than 0 -Float Function Repeat(Float t, Float len) Global Native - -; Returns f (as Float) rounded to the nearest integer -Float Function Round(Float f) Global Native - -; Returns f (as Int) rounded to the nearest integer -Int Function RoundToInt(Float f) Global Native - -; Returns the sign of f -Float Function Sign(Float f) Global Native - -; Returns the sine of angle f -Float Function Sin(Float f) Global Native - -; Interpolates between min and max with smoothing at the limits -Float Function SmoothStep(Float current, Float target, Float t) Global Native - -; Returns square root of f -Float Function Sqrt(Float f) Global Native - -; Returns the tangent of angle f in radians -Float Function Tan(Float f) Global Native diff --git a/modules/tests/iEquip/LibTurtleClub.psc b/modules/tests/iEquip/LibTurtleClub.psc deleted file mode 100644 index 589501b..0000000 --- a/modules/tests/iEquip/LibTurtleClub.psc +++ /dev/null @@ -1,18 +0,0 @@ -ScriptName LibTurtleClub Hidden - -{ Actor } - -; Returns whether `akActor` is a member of each faction in `akFactions` (does not evaluate faction rank) -Bool[] Function GetFactionStates(Actor akActor, FormList akFactions) Global Native - -; Returns armor items equipped in each slot and each weapon equipped in either hand when `abLeftWeapon` or -; `abRightWeapon` are True (Note: Return values are in array order and can be None) -Form[] Function GetWornEquipment(Actor akActor, Bool abWeaponL, Bool abWeaponR) Global Native - -{ Misc } - -; Returns whether disguise can activate based on map of mutually exclusive faction indices -Bool Function CanDisguiseActivate(Int aiFactionIndex, Bool[] akFactionStates) Global Native - -; Returns index to `akPlayerRace` in `argRaces` after checking if `akPlayerRace` is mapped to `aiFactionIndex` -Int Function LookupRaceWeightIndex(Int aiFactionIndex, Race akPlayerRace, Race[] argRaces) Global Native diff --git a/modules/tests/iEquip/README.md b/modules/tests/iEquip/README.md deleted file mode 100644 index a01b586..0000000 --- a/modules/tests/iEquip/README.md +++ /dev/null @@ -1 +0,0 @@ -https://github.com/pijaczkar8/iEquip \ No newline at end of file diff --git a/modules/tests/iEquip/SKI_ConfigBase.psc b/modules/tests/iEquip/SKI_ConfigBase.psc deleted file mode 100644 index 830c803..0000000 --- a/modules/tests/iEquip/SKI_ConfigBase.psc +++ /dev/null @@ -1,1205 +0,0 @@ -scriptname SKI_ConfigBase extends SKI_QuestBase - -; CONSTANTS --------------------------------------------------------------------------------------- - -string property JOURNAL_MENU = "Journal Menu" autoReadonly -string property MENU_ROOT = "_root.ConfigPanelFader.configPanel" autoReadonly - -int property STATE_DEFAULT = 0 autoReadonly -int property STATE_RESET = 1 autoReadonly -int property STATE_SLIDER = 2 autoReadonly -int property STATE_MENU = 3 autoReadonly -int property STATE_COLOR = 4 autoReadonly -int property STATE_INPUT = 5 autoReadonly - -int property OPTION_TYPE_EMPTY = 0x00 autoReadonly -int property OPTION_TYPE_HEADER = 0x01 autoReadonly -int property OPTION_TYPE_TEXT = 0x02 autoReadonly -int property OPTION_TYPE_TOGGLE = 0x03 autoReadonly -int property OPTION_TYPE_SLIDER = 0x04 autoReadonly -int property OPTION_TYPE_MENU = 0x05 autoReadonly -int property OPTION_TYPE_COLOR = 0x06 autoReadonly -int property OPTION_TYPE_KEYMAP = 0x07 autoReadonly -int property OPTION_TYPE_INPUT = 0x08 autoReadonly - -int property OPTION_FLAG_NONE = 0x00 autoReadonly -int property OPTION_FLAG_DISABLED = 0x01 autoReadonly -int property OPTION_FLAG_HIDDEN = 0x02 autoReadonly -int property OPTION_FLAG_WITH_UNMAP = 0x04 autoReadonly - -int property LEFT_TO_RIGHT = 1 autoReadonly -int property TOP_TO_BOTTOM = 2 autoReadonly - - -; PRIVATE VARIABLES ------------------------------------------------------------------------------- - -SKI_ConfigManager _configManager -bool _initialized = false -int _configID = -1 -string _currentPage = "" -int _currentPageNum = 0 ; 0 for "", real pages start at 1 - -; Keep track of what we're doing at the moment for stupidity checks -int _state = 0 - -int _cursorPosition = 0 -int _cursorFillMode = 1 ;LEFT_TO_RIGHT - -; Local buffers -int[] _optionFlagsBuf ; byte 1 type, byte 2 flags -string[] _textBuf -string[] _strValueBuf -float[] _numValueBuf - -float[] _sliderParams -int[] _menuParams -int[] _colorParams - -int _activeOption = -1 - -string _infoText -string _inputStartText - -bool _messageResult = false -bool _waitForMessage = false - -string[] _stateOptionMap - - -; PROPERTIES -------------------------------------------------------------------------------------- - -string property ModName auto - -string[] property Pages auto - -string property CurrentPage - string function get() - return _currentPage - endFunction -endProperty - - -; INITIALIZATION ---------------------------------------------------------------------------------- - -event OnInit() - OnGameReload() -endEvent - -; @implements SKI_QuestBase -event OnGameReload() - if (!_initialized) - _initialized = true - - ; Buffer alloc/free on config open/close - ;_optionFlagsBuf = new int[128] - ;_textBuf = new string[128] - ;_strValueBuf = new string[128] - ;_numValueBuf = new float[128] - - ; 0 startValue - ; 1 defaultValue - ; 2 minValue - ; 3 maxValue - ; 4 interval - _sliderParams = new float[5] - - ; 0 startIndex - ; 1 defaultIndex - _menuParams = new int[2] - - ; 0 currentColor - ; 1 defaultColor - _colorParams = new int[2] - - OnConfigInit() - - Debug.Trace(self + " INITIALIZED") - endIf - - RegisterForModEvent("SKICP_configManagerReady", "OnConfigManagerReady") - RegisterForModEvent("SKICP_configManagerReset", "OnConfigManagerReset") - - CheckVersion() -endEvent - - -; EVENTS ------------------------------------------------------------------------------------------ - -; @interface -event OnConfigInit() - {Called when this config menu is initialized} -endEvent - -; @interface -event OnConfigRegister() - {Called when this config menu registered at the control panel} -endEvent - -; @interface -event OnConfigOpen() - {Called when this config menu is opened} -endEvent - -; @interface -event OnConfigClose() - {Called when this config menu is closed} -endEvent - -; @interface(SKI_QuestBase) -event OnVersionUpdate(int a_version) - {Called when a version update of this script has been detected} -endEvent - -; @interface -event OnPageReset(string a_page) - {Called when a new page is selected, including the initial empty page} -endEvent - -; @interface -event OnOptionHighlight(int a_option) - {Called when highlighting an option} -endEvent - -; @interface -event OnOptionSelect(int a_option) - {Called when a non-interactive option has been selected} -endEvent - -; @interface -event OnOptionDefault(int a_option) - {Called when resetting an option to its default value} -endEvent - -; @interface -event OnOptionSliderOpen(int a_option) - {Called when a slider option has been selected} -endEvent - -; @interface -event OnOptionSliderAccept(int a_option, float a_value) - {Called when a new slider value has been accepted} -endEvent - -; @interface -event OnOptionMenuOpen(int a_option) - {Called when a menu option has been selected} -endEvent - -; @interface -event OnOptionMenuAccept(int a_option, int a_index) - {Called when a menu entry has been accepted} -endEvent - -; @interface -event OnOptionColorOpen(int a_option) - {Called when a color option has been selected} -endEvent - -; @interface -event OnOptionColorAccept(int a_option, int a_color) - {Called when a new color has been accepted} -endEvent - -; @interface -event OnOptionKeyMapChange(int a_option, int a_keyCode, string a_conflictControl, string a_conflictName) - {Called when a key has been remapped} -endEvent - -; @interface -event OnHighlightST() - {Called when highlighting a state option} -endEvent - -; @interface -event OnSelectST() - {Called when a non-interactive state option has been selected} -endEvent - -; @interface -event OnDefaultST() - {Called when resetting a state option to its default value} -endEvent - -; @interface -event OnSliderOpenST() - {Called when a slider state option has been selected} -endEvent - -; @interface -event OnSliderAcceptST(float a_value) - {Called when a new slider state value has been accepted} -endEvent - -; @interface -event OnMenuOpenST() - {Called when a menu state option has been selected} -endEvent - -; @interface -event OnMenuAcceptST(int a_index) - {Called when a menu entry has been accepted for this state option} -endEvent - -; @interface -event OnColorOpenST() - {Called when a color state option has been selected} -endEvent - -; @interface -event OnColorAcceptST(int a_color) - {Called when a new color has been accepted for this state option} -endEvent - -; @interface -event OnKeyMapChangeST(int a_keyCode, string a_conflictControl, string a_conflictName) - {Called when a key has been remapped for this state option} -endEvent - -event OnConfigManagerReset(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - _configManager = none -endEvent - -event OnConfigManagerReady(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - SKI_ConfigManager newManager = a_sender as SKI_ConfigManager - ; Already registered? - if (_configManager == newManager || newManager == none) - return - endIf - - _configID = newManager.RegisterMod(self, ModName) - - ; Success - if (_configID >= 0) - _configManager = newManager - OnConfigRegister() - Debug.Trace(self + ": Registered " + ModName + " at MCM.") - endIf - endEvent - -event OnMessageDialogClose(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - _messageResult = a_numArg as bool - _waitForMessage = false -endEvent - - -; FUNCTIONS --------------------------------------------------------------------------------------- - -; @interface(SKI_QuestBase) -int function GetVersion() - {Returns version of this script} - return 1 -endFunction - -; @interface -string function GetCustomControl(int a_keyCode) - {Returns the name of a custom control mapped to given keyCode, or "" if the key is not in use by this config} - return "" -endFunction - -; @interface -function ForcePageReset() - {Forces a full reset of the current page} - UI.Invoke(JOURNAL_MENU, MENU_ROOT + ".forcePageReset") -endFunction - -; @interface -function SetTitleText(string a_text) - UI.InvokeString(JOURNAL_MENU, MENU_ROOT + ".setTitleText", a_text) -endFunction - -; @interface -function SetInfoText(string a_text) - _infoText = a_text -endFunction - -; @interface -function SetCursorPosition(int a_position) - if (a_position < 128) - _cursorPosition = a_position - endIf -endFunction - -; @interface -function SetCursorFillMode(int a_fillMode) - if (a_fillMode == LEFT_TO_RIGHT || a_fillMode == TOP_TO_BOTTOM) - _cursorFillMode = a_fillMode - endIf -endFunction - -; @interface -int function AddEmptyOption() - return AddOption(OPTION_TYPE_EMPTY, none, none, 0, 0) -endFunction - -; @interface -int function AddHeaderOption(string a_text, int a_flags = 0) - return AddOption(OPTION_TYPE_HEADER, a_text, none, 0, a_flags) -endFunction - -; @interface -int function AddTextOption(string a_text, string a_value, int a_flags = 0) - return AddOption(OPTION_TYPE_TEXT, a_text, a_value, 0, a_flags) -endFunction - -; @interface -int function AddToggleOption(string a_text, bool a_checked, int a_flags = 0) - return AddOption(OPTION_TYPE_TOGGLE, a_text, none, a_checked as int, a_flags) -endfunction - -; @interface -int function AddSliderOption(string a_text, float a_value, string a_formatString = "{0}", int a_flags = 0) - return AddOption(OPTION_TYPE_SLIDER, a_text, a_formatString, a_value, a_flags) -endFunction - -; @interface -int function AddMenuOption(string a_text, string a_value, int a_flags = 0) - return AddOption(OPTION_TYPE_MENU, a_text, a_value, 0, a_flags) -endFunction - -; @interface -int function AddColorOption(string a_text, int a_color, int a_flags = 0) - return AddOption(OPTION_TYPE_COLOR, a_text, none, a_color, a_flags) -endFunction - -; @interface -int function AddKeyMapOption(string a_text, int a_keyCode, int a_flags = 0) - return AddOption(OPTION_TYPE_KEYMAP, a_text, none, a_keyCode, a_flags) -endFunction - -; @interface -function AddTextOptionST(string a_stateName, string a_text, string a_value, int a_flags = 0) - AddOptionST(a_stateName, OPTION_TYPE_TEXT, a_text, a_value, 0, a_flags) -endFunction - -; @interface -function AddToggleOptionST(string a_stateName, string a_text, bool a_checked, int a_flags = 0) - AddOptionST(a_stateName, OPTION_TYPE_TOGGLE, a_text, none, a_checked as int, a_flags) -endfunction - -; @interface -function AddSliderOptionST(string a_stateName, string a_text, float a_value, string a_formatString = "{0}", int a_flags = 0) - AddOptionST(a_stateName, OPTION_TYPE_SLIDER, a_text, a_formatString, a_value, a_flags) -endFunction - -; @interface -function AddMenuOptionST(string a_stateName, string a_text, string a_value, int a_flags = 0) - AddOptionST(a_stateName, OPTION_TYPE_MENU, a_text, a_value, 0, a_flags) -endFunction - -; @interface -function AddColorOptionST(string a_stateName, string a_text, int a_color, int a_flags = 0) - AddOptionST(a_stateName, OPTION_TYPE_COLOR, a_text, none, a_color, a_flags) -endFunction - -; @interface -function AddKeyMapOptionST(string a_stateName, string a_text, int a_keyCode, int a_flags = 0) - AddOptionST(a_stateName, OPTION_TYPE_KEYMAP, a_text, none, a_keyCode, a_flags) -endFunction - -; @interface -function LoadCustomContent(string a_source, float a_x = 0.0, float a_y = 0.0) - float[] params = new float[2] - params[0] = a_x - params[1] = a_y - UI.InvokeFloatA(JOURNAL_MENU, MENU_ROOT + ".setCustomContentParams", params) - UI.InvokeString(JOURNAL_MENU, MENU_ROOT + ".loadCustomContent", a_source) -endFunction - -; @interface -function UnloadCustomContent() - UI.Invoke(JOURNAL_MENU, MENU_ROOT + ".unloadCustomContent") -endFunction - -; @interface -function SetOptionFlags(int a_option, int a_flags, bool a_noUpdate = false) - if (_state == STATE_RESET) - Error("Cannot set option flags while in OnPageReset(). Pass flags to AddOption instead") - return - endIf - - int index = a_option % 0x100 - - ; Update flags buffer - int oldFlags = _optionFlagsBuf[index] as int - oldFlags %= 0x100 ; Clear upper bytes, keep type - oldFlags += a_flags * 0x100 ; Set new flags - - ; Update display - int[] params = new int[2] - params[0] = index - params[1] = a_flags - UI.InvokeIntA(JOURNAL_MENU, MENU_ROOT + ".setOptionFlags", params) - - if (!a_noUpdate) - UI.Invoke(JOURNAL_MENU, MENU_ROOT + ".invalidateOptionData") - endIf -endFunction - -; @interface -function SetTextOptionValue(int a_option, string a_value, bool a_noUpdate = false) - int index = a_option % 0x100 - int type = _optionFlagsBuf[index] % 0x100 - - if (type != OPTION_TYPE_TEXT) - int pageIdx = ((a_option / 0x100) as int) - 1 - if (pageIdx != -1) - Error("Option type mismatch. Expected text option, page \"" + Pages[pageIdx] + "\", index " + index) - else - Error("Option type mismatch. Expected text option, page \"\", index " + index) - endIf - return - endIf - - SetOptionStrValue(index, a_value, a_noUpdate) -endFunction - -; @interface -function SetToggleOptionValue(int a_option, bool a_checked, bool a_noUpdate = false) - int index = a_option % 0x100 - int type = _optionFlagsBuf[index] % 0x100 - - if (type != OPTION_TYPE_TOGGLE) - int pageIdx = ((a_option / 0x100) as int) - 1 - if (pageIdx != -1) - Error("Option type mismatch. Expected toggle option, page \"" + Pages[pageIdx] + "\", index " + index) - else - Error("Option type mismatch. Expected toggle option, page \"\", index " + index) - endIf - return - endIf - - SetOptionNumValue(index, a_checked as int, a_noUpdate) -endfunction - -; @interface -function SetSliderOptionValue(int a_option, float a_value, string a_formatString = "{0}", bool a_noUpdate = false) - int index = a_option % 0x100 - int type = _optionFlagsBuf[index] % 0x100 - - if (type != OPTION_TYPE_SLIDER) - int pageIdx = ((a_option / 0x100) as int) - 1 - if (pageIdx != -1) - Error("Option type mismatch. Expected slider option, page \"" + Pages[pageIdx] + "\", index " + index) - else - Error("Option type mismatch. Expected slider option, page \"\", index " + index) - endIf - return - endIf - - SetOptionValues(index, a_formatString, a_value, a_noUpdate) -endFunction - -; @interface -function SetMenuOptionValue(int a_option, string a_value, bool a_noUpdate = false) - int index = a_option % 0x100 - int type = _optionFlagsBuf[index] % 0x100 - - if (type != OPTION_TYPE_MENU) - int pageIdx = ((a_option / 0x100) as int) - 1 - if (pageIdx != -1) - Error("Option type mismatch. Expected menu option, page \"" + Pages[pageIdx] + "\", index " + index) - else - Error("Option type mismatch. Expected menu option, page \"\", index " + index) - endIf - return - endIf - - SetOptionStrValue(index, a_value, a_noUpdate) -endFunction - -; @interface -function SetColorOptionValue(int a_option, int a_color, bool a_noUpdate = false) - int index = a_option % 0x100 - int type = _optionFlagsBuf[index] % 0x100 - - if (type != OPTION_TYPE_COLOR) - int pageIdx = ((a_option / 0x100) as int) - 1 - if (pageIdx != -1) - Error("Option type mismatch. Expected color option, page \"" + Pages[pageIdx] + "\", index " + index) - else - Error("Option type mismatch. Expected color option, page \"\", index " + index) - endIf - return - endIf - - SetOptionNumValue(index, a_color, a_noUpdate) -endFunction - -; @interface -function SetKeyMapOptionValue(int a_option, int a_keyCode, bool a_noUpdate = false) - int index = a_option % 0x100 - int type = _optionFlagsBuf[index] % 0x100 - - if (type != OPTION_TYPE_KEYMAP) - int pageIdx = ((a_option / 0x100) as int) - 1 - if (pageIdx != -1) - Error("Option type mismatch. Expected keymap option, page \"" + Pages[pageIdx] + "\", index " + index) - else - Error("Option type mismatch. Expected keymap option, page \"\", index " + index) - endIf - return - endIf - - SetOptionNumValue(index, a_keyCode, a_noUpdate) -endFunction - -; @interface -function SetOptionFlagsST(int a_flags, bool a_noUpdate = false, string a_stateName = "") - if (_state == STATE_RESET) - Error("Cannot set option flags while in OnPageReset(). Pass flags to AddOption instead") - return - endIf - - int index = GetStateOptionIndex(a_stateName) - if (index < 0) - Error("Cannot use SetOptionFlagsST outside a valid option state") - return - endIf - - SetOptionFlags(index, a_flags, a_noUpdate) -endFunction - -; @interface -function SetTextOptionValueST(string a_value, bool a_noUpdate = false, string a_stateName = "") - int index = GetStateOptionIndex(a_stateName) - if (index < 0) - Error("Cannot use SetTextOptionValueST outside a valid option state") - return - endIf - - SetTextOptionValue(index, a_value, a_noUpdate) -endFunction - -; @interface -function SetToggleOptionValueST(bool a_checked, bool a_noUpdate = false, string a_stateName = "") - int index = GetStateOptionIndex(a_stateName) - if (index < 0) - Error("Cannot use SetToggleOptionValueST outside a valid option state") - return - endIf - - SetToggleOptionValue(index, a_checked, a_noUpdate) -endFunction - -; @interface -function SetSliderOptionValueST(float a_value, string a_formatString = "{0}", bool a_noUpdate = false, string a_stateName = "") - int index = GetStateOptionIndex(a_stateName) - if (index < 0) - Error("Cannot use SetSliderOptionValueST outside a valid option state") - return - endIf - - SetSliderOptionValue(index, a_value, a_formatString, a_noUpdate) -endFunction - -; @interface -function SetMenuOptionValueST(string a_value, bool a_noUpdate = false, string a_stateName = "") - int index = GetStateOptionIndex(a_stateName) - if (index < 0) - Error("Cannot use SetMenuOptionValueST outside a valid option state") - return - endIf - - SetMenuOptionValue(index, a_value, a_noUpdate) -endFunction - -; @interface -function SetColorOptionValueST(int a_color, bool a_noUpdate = false, string a_stateName = "") - int index = GetStateOptionIndex(a_stateName) - if (index < 0) - Error("Cannot use SetColorOptionValueST outside a valid option state") - return - endIf - - SetColorOptionValue(index, a_color, a_noUpdate) -endFunction - -; @interface -function SetKeyMapOptionValueST(int a_keyCode, bool a_noUpdate = false, string a_stateName = "") - int index = GetStateOptionIndex(a_stateName) - if (index < 0) - Error("Cannot use SetKeyMapOptionValueST outside a valid option state") - return - endIf - - SetKeyMapOptionValue(index, a_keyCode, a_noUpdate) -endFunction - -; @interface -function SetSliderDialogStartValue(float a_value) - if (_state != STATE_SLIDER) - Error("Cannot set slider dialog params while outside OnOptionSliderOpen()") - return - endIf - - _sliderParams[0] = a_value -endFunction - -; @interface -function SetSliderDialogDefaultValue(float a_value) - if (_state != STATE_SLIDER) - Error("Cannot set slider dialog params while outside OnOptionSliderOpen()") - return - endIf - - _sliderParams[1] = a_value -endFunction - -; @interface -function SetSliderDialogRange(float a_minValue, float a_maxValue) - if (_state != STATE_SLIDER) - Error("Cannot set slider dialog params while outside OnOptionSliderOpen()") - return - endIf - - _sliderParams[2] = a_minValue - _sliderParams[3] = a_maxValue -endFunction - -; @interface -function SetSliderDialogInterval(float a_value) - if (_state != STATE_SLIDER) - Error("Cannot set slider dialog params while outside OnOptionSliderOpen()") - return - endIf - - _sliderParams[4] = a_value -endFunction - -; @interface -function SetMenuDialogStartIndex(int a_value) - if (_state != STATE_MENU) - Error("Cannot set menu dialog params while outside OnOptionMenuOpen()") - return - endIf - - _menuParams[0] = a_value -endFunction - -; @interface -function SetMenuDialogDefaultIndex(int a_value) - if (_state != STATE_MENU) - Error("Cannot set menu dialog params while outside OnOptionMenuOpen()") - return - endIf - - _menuParams[1] = a_value -endFunction - -; @interface -function SetMenuDialogOptions(string[] a_options) - if (_state != STATE_MENU) - Error("Cannot set menu dialog params while outside OnOptionMenuOpen()") - return - endIf - - UI.InvokeStringA(JOURNAL_MENU, MENU_ROOT + ".setMenuDialogOptions", a_options) -endFunction - -; @interface -function SetColorDialogStartColor(int a_color) - if (_state != STATE_COLOR) - Error("Cannot set color dialog params while outside OnOptionColorOpen()") - return - endIf - - _colorParams[0] = a_color -endFunction - -; @interface -function SetColorDialogDefaultColor(int a_color) - if (_state != STATE_COLOR) - Error("Cannot set color dialog params while outside OnOptionColorOpen()") - return - endIf - - _colorParams[1] = a_color -endFunction - -; @interface -bool function ShowMessage(string a_message, bool a_withCancel = true, string a_acceptLabel = "$Accept", string a_cancelLabel = "$Cancel") - if (_waitForMessage) - Error("Called ShowMessage() while another message was already open") - return false - endIf - - _waitForMessage = true - _messageResult = false - - string[] params = new string[3] - params[0] = a_message - params[1] = a_acceptLabel - if (a_withCancel) - params[2] = a_cancelLabel - else - params[2] = "" - endIf - - RegisterForModEvent("SKICP_messageDialogClosed", "OnMessageDialogClose") - UI.InvokeStringA(JOURNAL_MENU, MENU_ROOT + ".showMessageDialog", params) - - ; Wait for result - while (_waitForMessage) - Utility.WaitMenuMode(0.1) - endWhile - - UnregisterForModEvent("SKICP_messageDialogClosed") - - return _messageResult -endFunction - -function Error(string a_msg) - Debug.Trace(self + " ERROR: " + a_msg) -endFunction - -function OpenConfig() - ; Alloc - _optionFlagsBuf = new int[128] - _textBuf = new string[128] - _strValueBuf = new string[128] - _numValueBuf = new float[128] - _stateOptionMap = new string[128] - - SetPage("", -1) - - OnConfigOpen() - - UI.InvokeStringA(JOURNAL_MENU, MENU_ROOT + ".setPageNames", Pages) -endFunction - -function CloseConfig() - OnConfigClose() - ClearOptionBuffers() - _waitForMessage = false - - ; Free - _optionFlagsBuf = new int[1] - _textBuf = new string[1] - _strValueBuf = new string[1] - _numValueBuf = new float[1] - _stateOptionMap = new string[1] -endFunction - -function SetPage(string a_page, int a_index) - _currentPage = a_page - _currentPageNum = 1+a_index - - ; Set default title, can be overridden in OnPageReset - if (a_page != "") - SetTitleText(a_page) - else - SetTitleText(ModName) - endIf - - ClearOptionBuffers() - _state = STATE_RESET - OnPageReset(a_page) - _state = STATE_DEFAULT - WriteOptionBuffers() -endFunction - -int function AddOption(int a_optionType, string a_text, string a_strValue, float a_numValue, int a_flags) - if (_state != STATE_RESET) - Error("Cannot add option " + a_text + " outside of OnPageReset()") - return -1 - endIf - - int pos = _cursorPosition - if (pos == -1) - return -1 ; invalid - endIf - - _optionFlagsBuf[pos] = a_optionType + a_flags * 0x100 - _textBuf[pos] = a_text - _strValueBuf[pos] = a_strValue - _numValueBuf[pos] = a_numValue - - ; Just use numerical value of fill mode - _cursorPosition += _cursorFillMode - if (_cursorPosition >= 128) - _cursorPosition = -1 - endIf - - ; byte 1 - position - ; byte 2 - page - return pos + _currentPageNum * 0x100 -endFunction - -function AddOptionST(string a_stateName, int a_optionType, string a_text, string a_strValue, float a_numValue, int a_flags) - if (_stateOptionMap.find(a_stateName) != -1) - Error("State option name " + a_stateName + " is already in use") - return - endIf - - int index = AddOption(a_optionType, a_text, a_strValue, a_numValue, a_flags) % 0x100 - if (index < 0) - return - endIf - - if (_stateOptionMap[index] != "") - Error("State option index " + index + " already in use") - return - endIf - - _stateOptionMap[index] = a_stateName -endFunction - -int function GetStateOptionIndex(string a_stateName) - if (a_stateName == "") - a_stateName = GetState() - endIf - - if (a_stateName == "") - return -1 - endIf - - return _stateOptionMap.find(a_stateName) -endFunction - -function WriteOptionBuffers() - string menu = JOURNAL_MENU - string root = MENU_ROOT - int t = OPTION_TYPE_EMPTY - int i = 0 - int optionCount = 0; - - ; Tell UI where to cut off the buffer - i = 0 - while (i < 128) - if (_optionFlagsBuf[i] != t) - optionCount = i + 1 - endif - i += 1 - endWhile - - UI.InvokeIntA(menu, root + ".setOptionFlagsBuffer", _optionFlagsBuf) - UI.InvokeStringA(menu, root + ".setOptionTextBuffer", _textBuf) - UI.InvokeStringA(menu, root + ".setOptionStrValueBuffer", _strValueBuf) - UI.InvokeFloatA(menu, root + ".setOptionNumValueBuffer", _numValueBuf) - UI.InvokeInt(menu, root + ".flushOptionBuffers", optionCount) -endFunction - -function ClearOptionBuffers() - int t = OPTION_TYPE_EMPTY - int i = 0 - while (i < 128) - _optionFlagsBuf[i] = t - _textBuf[i] = "" - _strValueBuf[i] = "" - _numValueBuf[i] = 0 - - ; Also clear state map as it's tied to the buffers - _stateOptionMap[i] = "" - i += 1 - endWhile - - _cursorPosition = 0 - _cursorFillMode = LEFT_TO_RIGHT -endFunction - -function SetOptionStrValue(int a_index, string a_strValue, bool a_noUpdate) - if (_state == STATE_RESET) - Error("Cannot modify option data while in OnPageReset()") - return - endIf - - string menu = JOURNAL_MENU - string root = MENU_ROOT - - UI.SetInt(menu, root + ".optionCursorIndex", a_index) - UI.SetString(menu, root + ".optionCursor.strValue", a_strValue) - if (!a_noUpdate) - UI.Invoke(menu, root + ".invalidateOptionData") - endIf -endFunction - -function SetOptionNumValue(int a_index, float a_numValue, bool a_noUpdate) - if (_state == STATE_RESET) - Error("Cannot modify option data while in OnPageReset()") - return - endIf - - string menu = JOURNAL_MENU - string root = MENU_ROOT - - UI.SetInt(menu, root + ".optionCursorIndex", a_index) - UI.SetFloat(menu, root + ".optionCursor.numValue", a_numValue) - if (!a_noUpdate) - UI.Invoke(menu, root + ".invalidateOptionData") - endIf -endFunction - -function SetOptionValues(int a_index, string a_strValue, float a_numValue, bool a_noUpdate) - if (_state == STATE_RESET) - Error("Cannot modify option data while in OnPageReset()") - return - endIf - - string menu = JOURNAL_MENU - string root = MENU_ROOT - - UI.SetInt(menu, root + ".optionCursorIndex", a_index) - UI.SetString(menu, root + ".optionCursor.strValue", a_strValue) - UI.SetFloat(menu, root + ".optionCursor.numValue", a_numValue) - if (!a_noUpdate) - UI.Invoke(menu, root + ".invalidateOptionData") - endIf -endFunction - -function RequestSliderDialogData(int a_index) - _activeOption = a_index + _currentPageNum * 0x100 - - ; Defaults - _sliderParams[0] = 0 - _sliderParams[1] = 0 - _sliderParams[2] = 0 - _sliderParams[3] = 1 - _sliderParams[4] = 1 - - _state = STATE_SLIDER - - string optionState = _stateOptionMap[a_index] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnSliderOpenST() - gotoState(oldState) - else - OnOptionSliderOpen(_activeOption) - endIf - - _state = STATE_DEFAULT - - UI.InvokeFloatA(JOURNAL_MENU, MENU_ROOT + ".setSliderDialogParams", _sliderParams) -endFunction - -function RequestMenuDialogData(int a_index) - _activeOption = a_index + _currentPageNum * 0x100 - - ; Defaults - _menuParams[0] = -1 - _menuParams[1] = -1 - - _state = STATE_MENU - - string optionState = _stateOptionMap[a_index] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnMenuOpenST() - gotoState(oldState) - else - OnOptionMenuOpen(_activeOption) - endIf - - _state = STATE_DEFAULT - - UI.InvokeIntA(JOURNAL_MENU, MENU_ROOT + ".setMenuDialogParams", _menuParams) -endFunction - -function RequestColorDialogData(int a_index) - _activeOption = a_index + _currentPageNum * 0x100 - - ; Defaults - _colorParams[0] = -1 - _colorParams[1] = -1 - - _state = STATE_COLOR - - string optionState = _stateOptionMap[a_index] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnColorOpenST() - gotoState(oldState) - else - OnOptionColorOpen(_activeOption) - endIf - - _state = STATE_DEFAULT - - UI.InvokeIntA(JOURNAL_MENU, MENU_ROOT + ".setColorDialogParams", _colorParams) -endFunction - -function SetSliderValue(float a_value) - string optionState = _stateOptionMap[_activeOption % 0x100] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnSliderAcceptST(a_value) - gotoState(oldState) - else - OnOptionSliderAccept(_activeOption, a_value) - endIf - _activeOption = -1 -endFunction - -function SetMenuIndex(int a_index) - string optionState = _stateOptionMap[_activeOption % 0x100] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnMenuAcceptST(a_index) - gotoState(oldState) - else - OnOptionMenuAccept(_activeOption, a_index) - endIf - _activeOption = -1 -endFunction - -function SetColorValue(int a_color) - string optionState = _stateOptionMap[_activeOption % 0x100] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnColorAcceptST(a_color) - gotoState(oldState) - else - OnOptionColorAccept(_activeOption, a_color) - endIf - _activeOption = -1 -endFunction - -function SelectOption(int a_index) - string optionState = _stateOptionMap[a_index] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnSelectST() - gotoState(oldState) - else - int option = a_index + _currentPageNum * 0x100 - OnOptionSelect(option) - endIf -endFunction - -function ResetOption(int a_index) - string optionState = _stateOptionMap[a_index] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnDefaultST() - gotoState(oldState) - else - int option = a_index + _currentPageNum * 0x100 - OnOptionDefault(option) - endIf -endFunction - -function HighlightOption(int a_index) - _infoText = "" - - if (a_index != -1) - string optionState = _stateOptionMap[a_index] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnHighlightST() - gotoState(oldState) - else - int option = a_index + _currentPageNum * 0x100 - OnOptionHighlight(option) - endIf - endIf - - UI.InvokeString(JOURNAL_MENU, MENU_ROOT + ".setInfoText", _infoText) -endFunction - -function RemapKey(int a_index, int a_keyCode, string a_conflictControl, string a_conflictName) - string optionState = _stateOptionMap[a_index] - if (optionState != "") - string oldState = GetState() - gotoState(optionState) - OnKeyMapChangeST(a_keyCode, a_conflictControl, a_conflictName) - gotoState(oldState) - else - int option = a_index + _currentPageNum * 0x100 - OnOptionKeyMapChange(option, a_keyCode, a_conflictControl, a_conflictName) - endIf -endFunction - -function OnOptionInputOpen(Int a_option) -{Called when a text input option has been selected} -endFunction - -function OnInputOpenST() -{Called when a text input state option has been selected} -endFunction - -function OnOptionInputAccept(Int a_option, String a_input) -{Called when a new text input has been accepted} -endFunction - -function OnInputAcceptST(String a_input) -{Called when a new text input has been accepted for this state option} -endFunction - -function SetInputOptionValue(Int a_option, String a_value, Bool a_noUpdate) - Int index = a_option % 256 - Int type = _optionFlagsBuf[index] % 256 - if type != self.OPTION_TYPE_INPUT - Int pageIdx = a_option / 256 - 1 - if pageIdx != -1 - self.Error("Option type mismatch. Expected input option, page \"" + Pages[pageIdx] + "\", index " + index as String) - else - self.Error("Option type mismatch. Expected input option, page \"\", index " + index as String) - endIf - return - endIf - self.SetOptionStrValue(index, a_value, a_noUpdate) -endFunction - -function SetInputOptionValueST(String a_value, Bool a_noUpdate, String a_stateName) - Int index = self.GetStateOptionIndex(a_stateName) - if index < 0 - self.Error("Cannot use SetInputOptionValueST outside a valid option state") - return - endIf - self.SetInputOptionValue(index, a_value, a_noUpdate) -endFunction - -function RequestInputDialogData(Int a_index) - _activeOption = a_index + _currentPageNum * 256 - _inputStartText = "" - _state = self.STATE_INPUT - String optionState = _stateOptionMap[a_index] - if optionState != "" - String oldState = self.GetState() - self.GotoState(optionState) - self.OnInputOpenST() - self.GotoState(oldState) - else - self.OnOptionInputOpen(_activeOption) - endIf - _state = self.STATE_DEFAULT - ui.InvokeString(self.JOURNAL_MENU, self.MENU_ROOT + ".setInputDialogParams", _inputStartText) -endFunction - -Int function AddInputOption(String a_text, String a_value, Int a_flags) - return self.AddOption(self.OPTION_TYPE_INPUT, a_text, a_value, 0 as Float, a_flags) -endFunction - -function AddInputOptionST(String a_stateName, String a_text, String a_value, Int a_flags) - self.AddOptionST(a_stateName, self.OPTION_TYPE_INPUT, a_text, a_value, 0 as Float, a_flags) -endFunction - -function SetInputDialogStartText(String a_text) - if _state != self.STATE_INPUT - self.Error("Cannot set input dialog params while outside OnOptionInputOpen()") - return - endIf - _inputStartText = a_text -endFunction - -function SetInputText(String a_text) - String optionState = _stateOptionMap[_activeOption % 256] - if optionState != "" - String oldState = self.GetState() - self.GotoState(optionState) - self.OnInputAcceptST(a_text) - self.GotoState(oldState) - else - self.OnOptionInputAccept(_activeOption, a_text) - endIf - _activeOption = -1 -endFunction diff --git a/modules/tests/iEquip/SKI_ConfigManager.psc b/modules/tests/iEquip/SKI_ConfigManager.psc deleted file mode 100644 index ae5ddf8..0000000 --- a/modules/tests/iEquip/SKI_ConfigManager.psc +++ /dev/null @@ -1,388 +0,0 @@ -scriptname SKI_ConfigManager extends SKI_QuestBase hidden - -; SCRIPT VERSION ---------------------------------------------------------------------------------- -; -; History -; -; 1: - Initial version -; -; 2: - Added lock for API functions -; -; 3: - Removed lock again until I have time to test it properly -; -; 4: - Added redundancy for registration process - -int function GetVersion() - return 4 -endFunction - - -; CONSTANTS --------------------------------------------------------------------------------------- - -string property JOURNAL_MENU = "Journal Menu" autoReadonly -string property MENU_ROOT = "_root.ConfigPanelFader.configPanel" autoReadonly - - -; PRIVATE VARIABLES ------------------------------------------------------------------------------- - -; -- Version 1 -- - -SKI_ConfigBase[] _modConfigs -string[] _modNames -int _curConfigID = 0 -int _configCount = 0 - -SKI_ConfigBase _activeConfig - -; -- Version 2 -- - -; keep those for now -bool _lockInit = false -bool _locked = false - -; -- Version 4 -- - -bool _cleanupFlag = false -int _addCounter = 0 -int _updateCounter = 0 - - -; INITIALIZATION ---------------------------------------------------------------------------------- - -event OnInit() - _modConfigs = new SKI_ConfigBase[128] - _modNames = new string[128] - - OnGameReload() -endEvent - -; @implements SKI_QuestBase -event OnGameReload() - RegisterForModEvent("SKICP_modSelected", "OnModSelect") - RegisterForModEvent("SKICP_pageSelected", "OnPageSelect") - RegisterForModEvent("SKICP_optionHighlighted", "OnOptionHighlight") - RegisterForModEvent("SKICP_optionSelected", "OnOptionSelect") - RegisterForModEvent("SKICP_optionDefaulted", "OnOptionDefault") - RegisterForModEvent("SKICP_keymapChanged", "OnKeymapChange") - RegisterForModEvent("SKICP_sliderSelected", "OnSliderSelect") - RegisterForModEvent("SKICP_sliderAccepted", "OnSliderAccept") - RegisterForModEvent("SKICP_menuSelected", "OnMenuSelect") - RegisterForModEvent("SKICP_menuAccepted", "OnMenuAccept") - RegisterForModEvent("SKICP_colorSelected", "OnColorSelect") - RegisterForModEvent("SKICP_colorAccepted", "OnColorAccept") - self.RegisterForModEvent("SKICP_inputSelected", "OnInputSelect") - self.RegisterForModEvent("SKICP_inputAccepted", "OnInputAccept") - RegisterForModEvent("SKICP_dialogCanceled", "OnDialogCancel") - - RegisterForMenu(JOURNAL_MENU) - - ; no longer used but better safe than sorry - _lockInit = true - - _cleanupFlag = true - - CleanUp() - SendModEvent("SKICP_configManagerReady") - - _updateCounter = 0 - RegisterForSingleUpdate(5) -endEvent - - -; EVENTS ------------------------------------------------------------------------------------------ - -event OnUpdate() - - if (_cleanupFlag) - CleanUp() - endIf - - if (_addCounter > 0) - Debug.Notification("MCM: Registered " + _addCounter + " new menu(s).") - _addCounter = 0 - endIf - - SendModEvent("SKICP_configManagerReady") - - if (_updateCounter < 6) - _updateCounter += 1 - RegisterForSingleUpdate(5) - else - RegisterForSingleUpdate(30) - endIf -endEvent - -event OnMenuOpen(string a_menuName) - GotoState("BUSY") - _activeConfig = none - UI.InvokeStringA(JOURNAL_MENU, MENU_ROOT + ".setModNames", _modNames); -endEvent - -event OnMenuClose(string a_menuName) - GotoState("") - if (_activeConfig) - _activeConfig.CloseConfig() - endIf - - _activeConfig = none -endEvent - -event OnModSelect(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int configIndex = a_numArg as int - if (configIndex > -1) - - ; We can clean the buffers of the previous menu now - if (_activeConfig) - _activeConfig.CloseConfig() - endIf - - _activeConfig = _modConfigs[configIndex] - _activeConfig.OpenConfig() - endIf - UI.InvokeBool(JOURNAL_MENU, MENU_ROOT + ".unlock", true) -endEvent - -event OnPageSelect(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - string page = a_strArg - int index = a_numArg as int - _activeConfig.SetPage(page, index) - UI.InvokeBool(JOURNAL_MENU, MENU_ROOT + ".unlock", true) -endEvent - -event OnOptionHighlight(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int optionIndex = a_numArg as int - _activeConfig.HighlightOption(optionIndex) -endEvent - -event OnOptionSelect(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int optionIndex = a_numArg as int - _activeConfig.SelectOption(optionIndex) - UI.InvokeBool(JOURNAL_MENU, MENU_ROOT + ".unlock", true) -endEvent - -event OnOptionDefault(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int optionIndex = a_numArg as int - _activeConfig.ResetOption(optionIndex) - UI.InvokeBool(JOURNAL_MENU, MENU_ROOT + ".unlock", true) -endEvent - -event OnKeymapChange(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int optionIndex = a_numArg as int - int keyCode = UI.GetInt(JOURNAL_MENU, MENU_ROOT + ".selectedKeyCode") - - ; First test vanilla controls - string conflictControl = Input.GetMappedControl(keyCode) - string conflictName = "" - - ; Then test mod controls - int i = 0 - while (conflictControl == "" && i < _modConfigs.length) - if (_modConfigs[i] != none) - conflictControl = _modConfigs[i].GetCustomControl(keyCode) - if (conflictControl != "") - conflictName = _modNames[i] - endIf - endIf - - i += 1 - endWhile - - _activeConfig.RemapKey(optionIndex, keyCode, conflictControl, conflictName) - UI.InvokeBool(JOURNAL_MENU, MENU_ROOT + ".unlock", true) -endEvent - -event OnSliderSelect(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int optionIndex = a_numArg as int - _activeConfig.RequestSliderDialogData(optionIndex) -endEvent - -event OnSliderAccept(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - float value = a_numArg - _activeConfig.SetSliderValue(value) - UI.InvokeBool(JOURNAL_MENU, MENU_ROOT + ".unlock", true) -endEvent - -event OnMenuSelect(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int optionIndex = a_numArg as int - _activeConfig.RequestMenuDialogData(optionIndex) -endEvent - -event OnMenuAccept(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int value = a_numArg as int - _activeConfig.SetMenuIndex(value) - UI.InvokeBool(JOURNAL_MENU, MENU_ROOT + ".unlock", true) -endEvent - -event OnColorSelect(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int optionIndex = a_numArg as int - _activeConfig.RequestColorDialogData(optionIndex) -endEvent - -event OnColorAccept(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - int color = a_numArg as int - _activeConfig.SetColorValue(color) - UI.InvokeBool(JOURNAL_MENU, MENU_ROOT + ".unlock", true) -endEvent - -event OnDialogCancel(string a_eventName, string a_strArg, float a_numArg, Form a_sender) - UI.InvokeBool(JOURNAL_MENU, MENU_ROOT + ".unlock", true) -endEvent - - -; FUNCTIONS --------------------------------------------------------------------------------------- - -; @interface -int function RegisterMod(SKI_ConfigBase a_menu, string a_modName) - GotoState("BUSY") - ;Log("Registering config menu: " + a_menu + "(" + a_modName + ")") - - if (_configCount >= 128) - GotoState("") - return -1 - endIf - - ; Already registered? - int i = 0 - while (i < _modConfigs.length) - if (_modConfigs[i] == a_menu) - GotoState("") - return i - endIf - - i += 1 - endWhile - - ; New registration - int configID = NextID() - - if (configID == -1) - GotoState("") - return -1 - endIf - - _modConfigs[configID] = a_menu - _modNames[configID] = a_modName - - _configCount += 1 - - ; Track mods added in the current cycle so we don't have to display one message per mod - _addCounter += 1 - - GotoState("") - - return configID -endFunction - -; @interface -int function UnregisterMod(SKI_ConfigBase a_menu) - GotoState("BUSY") - ;Log("Unregistering config menu: " + a_menu) - - int i = 0 - while (i < _modConfigs.length) - if (_modConfigs[i] == a_menu) - _modConfigs[i] = none - _modNames[i] = "" - _configCount -= 1 - - GotoState("") - return i - endIf - - i += 1 - endWhile - - GotoState("") - return -1 -endFunction - -; @interface -function ForceReset() - Log("Forcing config manager reset...") - SendModEvent("SKICP_configManagerReset") - - GotoState("BUSY") - - int i = 0 - while (i < _modConfigs.length) - _modConfigs[i] = none - _modNames[i] = "" - i += 1 - endWhile - - _curConfigID = 0 - _configCount = 0 - - GotoState("") - - SendModEvent("SKICP_configManagerReady") -endFunction - -function CleanUp() - GotoState("BUSY") - - _cleanupFlag = false - - _configCount = 0 - int i = 0 - while (i < _modConfigs.length) - if (_modConfigs[i] == none || _modConfigs[i].GetFormID() == 0) - _modConfigs[i] = none - _modNames[i] = "" - else - _configCount += 1 - endIf - - i += 1 - endWhile - - GotoState("") -endFunction - -int function NextID() - int startIdx = _curConfigID - - while (_modConfigs[_curConfigID] != none) - _curConfigID += 1 - if (_curConfigID >= 128) - _curConfigID = 0 - endIf - if (_curConfigID == startIdx) - return -1 ; Just to be sure. - endIf - endWhile - - return _curConfigID -endFunction - -function Log(string a_msg) - Debug.Trace(self + ": " + a_msg) -endFunction - -function OnInputSelect(String a_eventName, String a_strArg, Float a_numArg, Form a_sender) - Int optionIndex = a_numArg as Int - _activeConfig.RequestInputDialogData(optionIndex) -endFunction - -function OnInputAccept(String a_eventName, String a_strArg, Float a_numArg, Form a_sender) - _activeConfig.SetInputText(a_strArg) - ui.InvokeBool(self.JOURNAL_MENU, self.MENU_ROOT + ".unlock", true) -endFunction - -; STATES --------------------------------------------------------------------------------------- - -state BUSY - int function RegisterMod(SKI_ConfigBase a_menu, string a_modName) - return -2 - endFunction - - int function UnregisterMod(SKI_ConfigBase a_menu) - return -2 - endFunction - - function ForceReset() - endFunction - - function CleanUp() - endFunction -endState \ No newline at end of file diff --git a/modules/tests/iEquip/SKI_QuestBase.psc b/modules/tests/iEquip/SKI_QuestBase.psc deleted file mode 100644 index cbef0d9..0000000 --- a/modules/tests/iEquip/SKI_QuestBase.psc +++ /dev/null @@ -1,42 +0,0 @@ -scriptname SKI_QuestBase extends Quest hidden - -; ------------------------------------------------------------------------------------------------- -; Version Tracking -; -; Quest implements -; GetVersion, to return the static version number -; OnVersionUpdate to handle the updating -; Update process is triggered by calling CheckVersion() - -int property CurrentVersion auto hidden - -function CheckVersion() - int version = GetVersion() - if (CurrentVersion < version) - OnVersionUpdateBase(version) - OnVersionUpdate(version) - CurrentVersion = version - endIf -endFunction - -int function GetVersion() - return 1 -endFunction - -event OnVersionUpdateBase(int a_version) -endEvent - -event OnVersionUpdate(int a_version) -endEvent - - -; ------------------------------------------------------------------------------------------------- -; Reload Events -; -; Helper to add reload event to quest script. -; 1. Create quest -; 2. Add player alias to quest -; 3. Attach SKI_PlayerLoadGameAlias to player alias - -event OnGameReload() -endEvent \ No newline at end of file diff --git a/modules/tests/iEquip/dubhApplyingEffectScript.psc b/modules/tests/iEquip/dubhApplyingEffectScript.psc deleted file mode 100644 index 6489360..0000000 --- a/modules/tests/iEquip/dubhApplyingEffectScript.psc +++ /dev/null @@ -1,153 +0,0 @@ -ScriptName dubhApplyingEffectScript Extends ActiveMagicEffect - -Import dubhUtilityScript - -; ============================================================================= -; PROPERTIES -; ============================================================================= - -GlobalVariable Property Global_fLOSDistanceMax Auto -GlobalVariable Property Global_iAlwaysSucceedDremora Auto -GlobalVariable Property Global_iAlwaysSucceedWerewolves Auto -GlobalVariable Property Global_iDiscoveryEnabled Auto -GlobalVariable Property Global_iPapyrusLoggingEnabled Auto - -Actor Property PlayerRef Auto -FormList Property BaseFactions Auto -FormList Property DisguiseFactions Auto -FormList Property ExcludedActors Auto -FormList Property ExcludedFactions Auto -Spell Property MonitorAbility Auto - -FormList Property BanditAllies Auto -FormList Property BanditFriends Auto - -; ============================================================================= -; SCRIPT-LOCAL VARIABLES -; ============================================================================= - -Actor NPC -Bool[] FactionStatesPlayer -Bool[] FactionStatesTarget - -; ============================================================================= -; FUNCTIONS -; ============================================================================= - -Function _Log(String asTextToPrint, Int aiSeverity = 0) - If IntToBool(Global_iPapyrusLoggingEnabled) - Debug.OpenUserLog("MasterOfDisguise") - Debug.TraceUser("MasterOfDisguise", "dubhApplyingEffectScript> " + asTextToPrint, aiSeverity) - EndIf -EndFunction - - -Function LogInfo(String asTextToPrint) - _Log("[INFO] " + asTextToPrint, 0) -EndFunction - - -Function LogWarning(String asTextToPrint) - _Log("[WARN] " + asTextToPrint, 1) -EndFunction - - -Function LogError(String asTextToPrint) - _Log("[ERRO] " + asTextToPrint, 2) -EndFunction - - -Int Function FindActiveDisguise() - ; Returns the index of the active disguise faction when player and NPC are in matching factions - - Int i = 0 - - While i < FactionStatesPlayer.Length && NPC - If FactionStatesPlayer[i] && FactionStatesTarget[i] - Return i - EndIf - - i += 1 - EndWhile - - Return -1 -EndFunction - -; ============================================================================= -; EVENTS -; ============================================================================= - -Event OnEffectStart(Actor akTarget, Actor akCaster) - NPC = akTarget - - If !IntToBool(Global_iDiscoveryEnabled) - LogInfo("Cannot attach monitor because the discovery system is disabled") - NPC = None - Return - EndIf - - If LibFire.ActorHasAnyKeyword(NPC, ExcludedActors) - LogError(NPC + ": cannot attach monitor because NPC has an excluded keyword") - NPC = None - Return - EndIf - - If LibFire.ActorIsInAnyFaction(NPC, ExcludedFactions) - LogError(NPC + ": cannot attach monitor because NPC is an excluded faction") - NPC = None - Return - EndIf - - If NPC.HasSpell(MonitorAbility) - LogError(NPC + ": cannot attach monitor because NPC monitor already attached") - NPC = None - Return - EndIf - - FactionStatesPlayer = LibTurtleClub.GetFactionStates(PlayerRef, DisguiseFactions) - - If FactionStatesPlayer.Find(True) < 0 - LogError(NPC + ": cannot attach monitor because Player is not in any disguise factions") - NPC = None - Return - EndIf - - FactionStatesTarget = LibTurtleClub.GetFactionStates(NPC, BaseFactions) - - If IntToBool(Global_iAlwaysSucceedDremora) && FactionStatesTarget[28] - LogError(NPC + ": cannot attach monitor because NPC is a dremora and always succeed vs. dremora is enabled") - NPC = None - Return - EndIf - - If IntToBool(Global_iAlwaysSucceedWerewolves) && FactionStatesTarget[16] - LogError(NPC + ": cannot attach monitor because NPC is a werewolf and always succeed vs. werewolves is enabled") - NPC = None - Return - EndIf - - If FactionStatesPlayer[30] && !FactionStatesTarget[30] - FactionStatesTarget[30] = LibFire.ActorIsInAnyFaction(NPC, BanditAllies) || LibFire.ActorIsInAnyFaction(NPC, BanditFriends) - EndIf - - If FactionStatesTarget.Find(True) < 0 - LogError(NPC + ": cannot attach monitor because NPC is not in any base or bandit factions") - NPC = None - Return - EndIf - - If FindActiveDisguise() < 0 - LogError(NPC + ": cannot attach monitor because Player and NPC are not in matching factions") - NPC = None - Return - EndIf - - If NPC.AddSpell(MonitorAbility) - LogInfo(NPC + ": attached monitor after satisfying all conditions") - NPC = None - Return - EndIf - - LogError(NPC + ": cannot attach monitor for reasons unknown") - NPC = None -EndEvent diff --git a/modules/tests/iEquip/dubhCompatibilityQuestScript.psc b/modules/tests/iEquip/dubhCompatibilityQuestScript.psc deleted file mode 100644 index 60d3e27..0000000 --- a/modules/tests/iEquip/dubhCompatibilityQuestScript.psc +++ /dev/null @@ -1,78 +0,0 @@ -ScriptName dubhCompatibilityQuestScript Extends Quest - -Import dubhUtilityScript - -; ============================================================================= -; PROPERTIES -; ============================================================================= - -GlobalVariable Property Global_fDetectionViewConeMCM Auto -GlobalVariable Property Global_fScriptUpdateFrequencyCompatibility Auto -GlobalVariable Property Global_iFactionsUpdateCompleted Auto -GlobalVariable Property Global_iPapyrusLoggingEnabled Auto - -Faction Property DA03VampireFaction Auto -Faction Property VampireFaction Auto -Faction Property VampireThrallFaction Auto - -; ============================================================================= -; FUNCTIONS -; ============================================================================= - -Function _Log(String asTextToPrint, Int aiSeverity = 0) - If IntToBool(Global_iPapyrusLoggingEnabled) - Debug.OpenUserLog("MasterOfDisguise") - Debug.TraceUser("MasterOfDisguise", "Master of Disguise: dubhCompatibilityQuestScript> " + asTextToPrint, aiSeverity) - EndIf -EndFunction - - -Function LogInfo(String asTextToPrint) - _Log("[INFO] " + asTextToPrint, 0) -EndFunction - - -Function LogWarning(String asTextToPrint) - _Log("[WARN] " + asTextToPrint, 1) -EndFunction - - -Function LogError(String asTextToPrint) - _Log("[ERRO] " + asTextToPrint, 2) -EndFunction - - -Function SetUpFactions() - Faction UDGPVampireFriendFaction = Game.GetFormFromFile(0x000969F9, "Unofficial Skyrim Special Edition Patch.esp") as Faction - - If UDGPVampireFriendFaction - LogInfo("Updating faction relationships: Unofficial Skyrim Special Edition Patch") - - DA03VampireFaction.SetAlly(UDGPVampireFriendFaction, true, true) ; Friend - VampireFaction.SetAlly(UDGPVampireFriendFaction, true, true) ; Friend - VampireThrallFaction.SetAlly(UDGPVampireFriendFaction, true, true) ; Friend - - LogInfo("Finished factions update.") - EndIf -EndFunction - -; ============================================================================= -; EVENTS -; ============================================================================= - -Event OnInit() - RegisterForSingleUpdate(Global_fScriptUpdateFrequencyCompatibility.GetValue()) -EndEvent - - -Event OnUpdate() - If !IntToBool(Global_iFactionsUpdateCompleted) - SetUpFactions() - Global_iFactionsUpdateCompleted.SetValue(1) - EndIf - - Float fDetectionViewCone = Game.GetGameSettingFloat("fDetectionViewCone") - Global_fDetectionViewConeMCM.SetValue(fDetectionViewCone) - - RegisterForSingleUpdate(Global_fScriptUpdateFrequencyCompatibility.GetValue()) -EndEvent diff --git a/modules/tests/iEquip/dubhDisguiseMCMHelper.psc b/modules/tests/iEquip/dubhDisguiseMCMHelper.psc deleted file mode 100644 index d64e95d..0000000 --- a/modules/tests/iEquip/dubhDisguiseMCMHelper.psc +++ /dev/null @@ -1,366 +0,0 @@ -ScriptName dubhDisguiseMCMHelper Extends SKI_ConfigBase -{Utility to make SkyUI MCM menu syntax a little easier.} - -;CAVEATS -;If a child implements MCM events, they must call Parent.eventname(args....) to pass the call up to this class. - -Import Debug -Import StringUtil -Import Math - -Int[] iOptionTypes -Int kToggle = 1 -Int kToggleGlobal = -1 -Int kSlider = 2 -Int kSliderGlobal = -2 -Int kText = 3 -Int kMenu = 4 -Int kKeyMap = 5 -Int kKeyMapGlobal = -5 -Int kColor = 6 -Int kTextToggle = 7 -Int kToggleGlobalBitmask = 8 - -String[] sLabels -String[] sHelpInfos -GlobalVariable[] gGlobalVars -Bool[] bBoolVals -Float[] fFloatVals -Float[] fSliderMaxs -Float[] fSliderMins -Float[] fSliderDefaults -Float[] fSliderIntervals -String[] sSliderFormats -String[] sKeyConflicts -Int[] iIntVals -String[] sStringVals -String[] sModEvents -Int[] iBitMasks - -Event OnInit() - RegisterForSingleUpdate(1.0) - InitArrays() - Parent.OnInit() -EndEvent - -Event OnUpdate() - RegisterForModEvent("SKICP_pageSelected", "OnPageSelect") ;mod event registration does not endure game reload - RegisterForModEvent("SKICP_configManagerReady", "OnConfigManagerReadyMCMHelper") - RegisterForSingleUpdate(30.0) -EndEvent - -Event OnConfigManagerReadyMCMHelper(String a_eventName, String a_strArg, Float a_numArg, Form a_sender) - ;eliminates the need to have a player ReferenceAlias with ski_playerloadgamealias to get MCM menus to show - OnGameReload() -EndEvent - -Int Function DefineMCMToggleOption(String sTextLabel, Bool bInitialState = False, Int iFlags = 0, String sHelpInfo = "", String sModEvent = "") - ; A single line of code that sets up a menu item for toggling value of a GlobalVariable without all the event handling stuff - ; just add to OnPageReset area - Int iOID = AddToggleOption(sTextLabel, bInitialState, iFlags) % 128 ;- iOIDOffset - - sLabels[iOID] = sTextLabel - sHelpInfos[iOID] = sHelpInfo - bBoolVals[iOID] = bInitialState - iOptionTypes[iOID] = kToggle - sModEvents[iOID] = sModEvent - Return iOID -EndFunction - -Int Function DefineMCMToggleOptionGlobal(String sTextLabel, GlobalVariable gToggleVar, Int iFlags = 0, String sHelpInfo = "", String sModEvent = "") - ; A single line of code that sets up a menu item for toggling value of a GlobalVariable without all the event handling stuff - ; just add to OnPageReset area - - Int iOID = DefineMCMToggleOption(sTextLabel, gToggleVar.GetValueInt() as Bool, iFlags, sHelpInfo, sModEvent) % 128 - - gGlobalVars[iOID] = gToggleVar - iOptionTypes[iOID] = kToggle ;Global - Return iOID -EndFunction - -Int Function DefineMCMToggleOptionGlobalBitmask(String sTextLabel, GlobalVariable gToggleVar, Int iBitmask, Int iFlags = 0, String sHelpInfo = "", String sModEvent = "") - ; A single line of code that sets up a menu item for toggling value of a bitmask value within a GlobalVariable without all the event handling stuff - ; just add to OnPageReset area - ; NOTE: DUE TO FLOAT ROUNDING OF GlobalVariables, THIS FUNCTION ONLY SUPPORTS BITMASKS UP TO 0x100000 (= 21 DIFFERENT BIT VALUES) - - Bool bVal = LogicalAnd(gToggleVar.GetValue() as Int, iBitMask) as Bool - Int iOID = DefineMCMToggleOption(sTextLabel, bVal, iFlags, sHelpInfo, sModEvent) % 128 - - gGlobalVars[iOID] = gToggleVar - bBoolVals[iOID] = bVal - iOptionTypes[iOID] = kToggleGlobalBitmask - iBitmasks[iOID] = iBitmask - Return iOID -EndFunction - -Int Function DefineMCMSliderOption(String sTextLabel, Float fValue, Float fDefault, Float fMin, Float fMax, Float fInterval, String sHelpInfo = "", String formatString = "{0}", Int flags = 0, String sModEvent = "") - Int iOID = AddSliderOption(sTextLabel, fValue, formatString, flags) % 128 ; - iOIDOffset - - sLabels[iOID] = sTextLabel - sHelpInfos[iOID] = sHelpInfo - fFloatVals[iOID] = fValue - fSliderMaxs[iOID] = fMax - fSliderMins[iOID] = fMin - fSliderDefaults[iOID] = fDefault - fSliderIntervals[iOID] = fInterval - iOptionTypes[iOID] = kSlider - sSliderFormats[iOID] = formatString - sModEvents[iOID] = sModEvent - Return iOID -EndFunction - -Int Function DefineMCMSliderOptionGlobal(String sTextLabel, GlobalVariable gSliderVar, Float fDefault, Float fMin, Float fMax, Float fInterval, String sHelpInfo = "", String formatString = "{0}", Int flags = 0, String sModEvent = "") - Int iOID = DefineMCMSliderOption(sTextLabel, gSliderVar.GetValue(), fDefault, fMin, fMax, fInterval, sHelpInfo, formatString, flags, sModEvent) % 128 - - gGlobalVars[iOID] = gSliderVar - iOptionTypes[iOID] = kSliderGlobal - return iOID -EndFunction - -Int Function DefineMCMKeymapOption(String sTextLabel, Int iKeyCode, Int iFlags = 0, Int iDefault, String sHelpInfo = "", String sKeyConflict = "", string sModEvent = "") - Int iOID = AddKeyMapOption(sTextLabel, iKeyCode, iFlags) % 128 ; - iOIDOffset - - iOptionTypes[iOID] = kKeyMap - sLabels[iOID] = sTextLabel - sHelpInfos[iOID] = sHelpInfo - sKeyConflicts[iOID] = sKeyConflict - iIntVals[iOID] = iKeyCode - fSliderDefaults[iOID] = iDefault as Float - sModEvents[iOID] = sModEvent - Return iOID -EndFunction - -Int Function DefineMCMKeymapOptionGlobal(String sTextLabel, GlobalVariable gGlobalVar, Int iFlags = 0, Int iDefault = -1, String sHelpInfo = "", String sKeyConflict = "", String sModEvent = "") - Int iOID = DefineMCMKeymapOption(sTextLabel, gGlobalVar.GetValueInt(), iFlags, iDefault, sHelpInfo, sKeyConflict, sModEvent) % 128 - - gGlobalVars[iOID] = gGlobalVar - iOptionTypes[iOID] = kKeyMapGlobal - Return iOID -EndFunction - -Int Function DefineMCMTextOption(String sTextLabel, String sValue, Int iFlags = 0, String sHelpInfo = "", String sModEvent = "") - Int iOID = AddTextOption(sTextLabel, sValue, iFlags) % 128 ; - iOIDOffset - - iOptionTypes[iOID] = kText - sLabels[iOID] = sTextLabel - sHelpInfos[iOID] = sHelpInfo - sStringVals[iOID] = sValue - sModEvents[iOID] = sModEvent - Return iOID -EndFunction - -Int Property OPTION_FLAG_AS_TEXTTOGGLE = 0x64 AutoReadonly ;show a menu alternatively as a toggling value text option - -Int Function DefineMCMMenuOption(String sTextLabel, String sValuesCSV, Int iSelected = 0, Int iDefault = 0, Int iFlags = 0, String sHelpInfo = "", String sModEvent = "") - Int iOID - String[] sValues = LibFire.SplitString(sValuesCSV, ",") - - If Math.LogicalAnd(iFlags, OPTION_FLAG_AS_TEXTTOGGLE) - iOID = AddTextOption(sTextLabel, sValues[iSelected], iFlags) % 128 ; - iOIDOffset - iOptionTypes[iOID] = kTextToggle - Else - iOID = AddMenuOption(sTextLabel, sValues[iSelected], iFlags) % 128 ; - iOIDOffset - iOptionTypes[iOID] = kMenu - SetMenuOptionValue(iOID, sValues[iSelected]) - EndIf - - iIntVals[iOID] = iSelected - sLabels[iOID] = sTextLabel - sHelpInfos[iOID] = sHelpInfo - sStringVals[iOID] = sValuesCSV - fSliderDefaults[iOID] = iDefault as Float - sModEvents[iOID] = sModEvent - Return iOID -EndFunction - -Int Function DefineMCMMenuOptionGlobal(String sTextLabel, String sValuesCSV, GlobalVariable giSelected, Int iDefault = 0, Int iFlags = 0, String sHelpInfo = "", String sModEvent = "") - Int iSelected = giSelected.GetValue() as Int - Int iOID = DefineMCMMenuOption(sTextLabel, sValuesCSV, iSelected, iDefault, iFlags, sHelpInfo, sModEvent) - gGlobalVars[iOID] = giSelected - Return iOID -EndFunction - -Function DefineMCMParagraph(String asText, Int aiFlags = 0x1) ;disabled type text by default - AddTextOption(asText, "", aiFlags) -EndFunction - -Int Function DefineMCMHelpTopic(String sTopic, String sHelpInfo = "") -;simplified call to display a string of text with topic info - Return DefineMCMTextOption(sTopic, "", 0, sHelpInfo) -EndFunction - -Bool Function GetMCMValueBool(String sTextLabel) -;return the current state for a toggle by its label - Return bBoolVals[GetMCMiOID(sTextLabel)] -EndFunction - -Int Function GetMCMValueInt(String sTextLabel) - Return iIntVals[GetMCMiOID(sTextLabel)] -EndFunction - -Float Function GetMCMValueFloat(String sTextLabel) - Return fFloatVals[GetMCMiOID(sTextLabel)] -EndFunction - -String Function GetMCMValueString(String sTextLabel) - Int iOID = GetMCMiOID(sTextLabel) - If (iOptionTypes[iOID] == kMenu) || (iOptionTypes[iOID] == kTextToggle) - String[] sValues = LibFire.SplitString(sStringVals[iOID], ",") - Return sValues[iIntVals[iOID]] - EndIf - Return sStringVals[iOID] -EndFunction - -Int Function GetMCMiOID(String sTextLabel) - Int iOID = 0 - While iOID < 128 ;sLabels.Length - If sLabels[iOID] == sTextLabel - Return iOID - EndIf - iOID += 1 - EndWhile - Return 0 -EndFunction - -;MCM EVENTS -;if child uses any of these events, they should call Parent.eventname(args,...) as part of their function or the event will be masked - -Event OnOptionSelect(Int iMCMOID) - Int iOID = iMCMOID % 128 ;-= iOIDOffset - If iOptionTypes[iOID] == kTextToggle - String[] sValues = LibFire.SplitString(sStringVals[iOID], ",") - iIntVals[iOID] = (iIntVals[iOID] + 1) % sValues.Length - If gGlobalVars[iOID] - gGlobalVars[iOID].SetValue(iIntVals[iOID] as Float) - EndIf - SetTextOptionValue(iMCMOID, sValues[iIntVals[iOID]]) - ElseIf iOptionTypes[iOID] == kToggle - bBoolVals[iOID] = !bBoolVals[iOID] - SetToggleOptionValue(iMCMOID, bBoolVals[iOID]) - If gGlobalVars[iOID] - gGlobalVars[iOID].SetValue(bBoolVals[iOID] as Float) - EndIf - ElseIf iOptionTypes[iOID] == kToggleGlobalBitmask - bBoolVals[iOID] = !bBoolVals[iOID] - SetToggleOptionValue(iMCMOID, bBoolVals[iOID]) - gGlobalVars[iOID].SetValue(logicalOr(logicalAnd(gGlobalVars[iOID].GetValueInt(), logicalNot(iBitMasks[iOID])), (iBitMasks[iOID] * (bBoolVals[iOID] as int))) as float) - EndIf - DispatchModEvent(iOID) -EndEvent - -Event OnOptionHighlight(Int iOID) - iOID = iOID % 128 ; -= iOIDOffset - SetInfoText(sHelpInfos[iOID]) -EndEvent - -Event OnOptionSliderOpen(Int iOID) - iOID = iOID % 128 ; -= iOIDOffset - SetSliderDialogStartValue(fFloatVals[iOID]) - SetSliderDialogDefaultValue(fSliderDefaults[iOID]) - SetSliderDialogRange(fSliderMins[iOID], fSliderMaxs[iOID]) - SetSliderDialogInterval(fSliderIntervals[iOID]) -EndEvent - -Event OnOptionSliderAccept(Int iMCMOID, Float value) - Int iOID = iMCMOID % 128 ; -= iOIDOffset - fFloatVals[iOID] = value - If gGlobalVars[iOID] - gGlobalVars[iOID].SetValue(value) - EndIf - SetSliderOptionValue(iMCMOID, value, sSliderFormats[iOID]) - DispatchModEvent(iOID) -EndEvent - -Event OnOptionDefault(Int iMCMOID) - Int iOID = iMCMOID % 128 ; -= iOIDOffset - If iOptionTypes[iOID] == kSlider - OnOptionSliderAccept(iMCMOID, fSliderDefaults[iOID]) - ElseIf iOptionTypes[iOID] == kKeyMap || iOptionTypes[iOID] == kKeyMapGlobal - OnOptionKeyMapChange(iMCMOID, fSliderDefaults[iOID] as Int, "", "") - EndIf -EndEvent - -event OnOptionKeyMapChange(Int iMCMOID, Int KeyCode, String conflictControl, String conflictName) - Int iOID = iMCMOID % 128 ; -= iOIDOffset - If (conflictControl != "") && !ShowMessage("This key is already mapped to:\n\"" + conflictControl + "\"\n(" + conflictName + ")\n\nAre you sure you want to continue?", true, "Yes", "No") - ; If conflict avoided - Else - iIntVals[iOID] = KeyCode - SetKeyMapOptionValue(iMCMOID, KeyCode) - If gGlobalVars[iOID] - gGlobalVars[iOID].SetValue(KeyCode) - EndIf - DispatchModEvent(iOID) - EndIf -EndEvent - -Event OnOptionMenuOpen(Int iOID) - iOID = iOID % 128 ; -= iOIDOffset - SetMenuDialogOptions(LibFire.SplitString(sStringVals[iOID], ",")) - SetMenuDialogStartIndex(iIntVals[iOID]) - SetMenuDialogDefaultIndex(fSliderDefaults[iOID] as Int) -EndEvent - -Event OnOptionMenuAccept(Int iMCMOID, Int index) - Int iOID = iMCMOID % 128 ; -= iOIDOffset - String[] sValues = LibFire.SplitString(sStringVals[iOID], ",") - iIntVals[iOID] = index - If gGlobalVars[iOID] - gGlobalVars[iOID].SetValue(index as Float) - EndIf - SetMenuOptionValue(iMCMOID, sValues[index]) -EndEvent - -;UTILITY INTERNAL FUNCTIONS - -Bool Function DispatchModEvent(Int iOID) -;sent ModEvent calls to the child or any listener -;dispatch any ModEvents - iOID = iOID % 128 - If sModEvents[iOID] != "" - If iOptionTypes[iOID] == kToggle - SendModEvent(sModEvents[iOID], sStringVals[iOID], bBoolVals[iOID] as Float) - ElseIf iOptionTypes[iOID] == kSlider - SendModEvent(sModEvents[iOID], sStringVals[iOID], fFloatVals[iOID]) - Else - SendModEvent(sModEvents[iOID], sStringVals[iOID], iIntVals[iOID] as Float) - EndIf - Return True - EndIf - Return False -EndFunction - -String Function GetCustomControl(Int keyCode) -;helper to notify other plugins of keymapping conflict - Int iOID - While iOID < iIntVals.Length - If iIntVals[iOID] == keyCode - Return sKeyConflicts[iOID] - EndIf - iOID += 1 - EndWhile -EndFunction - -Event OnPageSelect(String a_eventName, String a_page, Float a_index, Form a_sender) -;listen for this ModEvent and to reinitialize the page - InitArrays() -EndEvent - -Function InitArrays() - iOptionTypes = new Int[128] - sHelpInfos = new String[128] - sLabels = new String[128] - gGlobalVars = new GlobalVariable[128] - bBoolVals = new Bool[128] - fFloatVals = new Float[128] - fSliderMaxs = new Float[128] - fSliderMins = new Float[128] - fSliderDefaults = new Float[128] - fSliderIntervals = new Float[128] - sSliderFormats = new String[128] - sKeyConflicts = new String[128] - iIntVals = new Int[128] - sStringVals = new String[128] - sModEvents = new String[128] - iBitMasks = new Int[128] -EndFunction diff --git a/modules/tests/iEquip/dubhDisguiseMCMQuestScript.psc b/modules/tests/iEquip/dubhDisguiseMCMQuestScript.psc deleted file mode 100644 index a7b2916..0000000 --- a/modules/tests/iEquip/dubhDisguiseMCMQuestScript.psc +++ /dev/null @@ -1,628 +0,0 @@ -ScriptName dubhDisguiseMCMQuestScript Extends dubhDisguiseMCMHelper - -GlobalVariable Property Global_fBestSkillContribMax Auto -GlobalVariable Property Global_fBountyPenaltyMult Auto -GlobalVariable Property Global_fDetectionViewConeMCM Auto -GlobalVariable Property Global_fEscapeDistance Auto -GlobalVariable Property Global_fFOVPenaltyClear Auto -GlobalVariable Property Global_fFOVPenaltyDistorted Auto -GlobalVariable Property Global_fFOVPenaltyPeripheral Auto -GlobalVariable Property Global_fLOSDistanceMax Auto -GlobalVariable Property Global_fLOSPenaltyFar Auto -GlobalVariable Property Global_fLOSPenaltyMid Auto -GlobalVariable Property Global_fMobilityBonus Auto -GlobalVariable Property Global_fMobilityPenalty Auto -GlobalVariable Property Global_fRaceArgonian Auto -GlobalVariable Property Global_fRaceArgonianVampire Auto -GlobalVariable Property Global_fRaceBreton Auto -GlobalVariable Property Global_fRaceBretonVampire Auto -GlobalVariable Property Global_fRaceDarkElf Auto -GlobalVariable Property Global_fRaceDarkElfVampire Auto -GlobalVariable Property Global_fRaceHighElf Auto -GlobalVariable Property Global_fRaceHighElfVampire Auto -GlobalVariable Property Global_fRaceImperial Auto -GlobalVariable Property Global_fRaceImperialVampire Auto -GlobalVariable Property Global_fRaceKhajiit Auto -GlobalVariable Property Global_fRaceKhajiitVampire Auto -GlobalVariable Property Global_fRaceNord Auto -GlobalVariable Property Global_fRaceNordVampire Auto -GlobalVariable Property Global_fRaceOrc Auto -GlobalVariable Property Global_fRaceOrcVampire Auto -GlobalVariable Property Global_fRaceRedguard Auto -GlobalVariable Property Global_fRaceRedguardVampire Auto -GlobalVariable Property Global_fRaceWoodElf Auto -GlobalVariable Property Global_fRaceWoodElfVampire Auto -GlobalVariable Property Global_fScriptDistanceMax Auto -GlobalVariable Property Global_fScriptSuspendTime Auto -GlobalVariable Property Global_fScriptSuspendTimeBeforeAttack Auto -GlobalVariable Property Global_fScriptUpdateFrequencyCompatibility Auto -GlobalVariable Property Global_fScriptUpdateFrequencyMonitor Auto -GlobalVariable Property Global_fSlotAmulet Auto -GlobalVariable Property Global_fSlotBody Auto -GlobalVariable Property Global_fSlotCirclet Auto -GlobalVariable Property Global_fSlotFeet Auto -GlobalVariable Property Global_fSlotHair Auto -GlobalVariable Property Global_fSlotHands Auto -GlobalVariable Property Global_fSlotRing Auto -GlobalVariable Property Global_fSlotShield Auto -GlobalVariable Property Global_fSlotWeaponLeft Auto -GlobalVariable Property Global_fSlotWeaponRight Auto -GlobalVariable Property Global_iAlwaysSucceedDremora Auto -GlobalVariable Property Global_iAlwaysSucceedWerewolves Auto -GlobalVariable Property Global_iCrimeFalkreath Auto -GlobalVariable Property Global_iCrimeHjaalmarch Auto -GlobalVariable Property Global_iCrimeImperial Auto -GlobalVariable Property Global_iCrimeMarkarth Auto -GlobalVariable Property Global_iCrimePale Auto -GlobalVariable Property Global_iCrimeRavenRock Auto -GlobalVariable Property Global_iCrimeRiften Auto -GlobalVariable Property Global_iCrimeSolitude Auto -GlobalVariable Property Global_iCrimeStormcloaks Auto -GlobalVariable Property Global_iCrimeWhiterun Auto -GlobalVariable Property Global_iCrimeWindhelm Auto -GlobalVariable Property Global_iCrimeWinterhold Auto -GlobalVariable Property Global_iDiscoveryEnabled Auto -GlobalVariable Property Global_iDisguiseEssentialSlotBandit Auto -GlobalVariable Property Global_iNotifyEnabled Auto -GlobalVariable Property Global_iPapyrusLoggingEnabled Auto -GlobalVariable Property Global_iVampireNightOnly Auto -GlobalVariable Property Global_iVampireNightOnlyDayHourBegin Auto -GlobalVariable Property Global_iVampireNightOnlyDayHourEnd Auto - -GlobalVariable[] Property rgDisguisesEnabled Auto - -Actor Property PlayerRef Auto -Faction Property DisguiseFaction03 Auto ; Dark Brotherhood -Faction Property DisguiseFaction12 Auto ; Thieves Guild -Faction Property DisguiseFaction31 Auto ; Bandits -Faction Property DarkBrotherhoodFaction Auto -Faction Property ThievesGuildFaction Auto -FormList Property BaseFactions Auto -FormList Property DisguiseFactions Auto -FormList Property DisguiseFormLists Auto -FormList Property GuardFactions Auto -FormList Property TrackedBounties Auto -Quest Property CompatibilityQuest Auto -Quest Property DetectionQuest Auto - -dubhPlayerScript Property PlayerScript Auto - -Sound Property PickUpSound Auto - -Bool bGuardsVsDarkBrotherhood = False -Bool bGuardsVsDarkBrotherhoodNPC = False -Bool bGuardsVsThievesGuild = False -Bool bGuardsVsThievesGuildNPC = False - -String ModName - -; ============================================================================= -; FUNCTIONS -; ============================================================================= - -Function _Log(String asTextToPrint, Int aiSeverity = 0) - If (Global_iPapyrusLoggingEnabled.GetValue() as Int) as Bool - Debug.OpenUserLog("MasterOfDisguise") - Debug.TraceUser("MasterOfDisguise", "dubhDisguiseMCMQuestScript> " + asTextToPrint, aiSeverity) - EndIf -EndFunction - - -Function LogInfo(String asTextToPrint) - _Log("[INFO] " + asTextToPrint, 0) -EndFunction - - -Function LogWarning(String asTextToPrint) - _Log("[WARN] " + asTextToPrint, 1) -EndFunction - - -Function LogError(String asTextToPrint) - _Log("[ERRO] " + asTextToPrint, 2) -EndFunction - - -Function Alias_DefineMCMToggleOptionModEvent(String asName, String asModEvent, Bool abInitialState = False, Int aiFlags = 0) - ; when asName and asModEvent need to differ - RegisterForModEvent(asModEvent, "OnBooleanToggleClick") - DefineMCMToggleOption("$dubh" + asName, abInitialState, aiFlags, "$dubhHelp" + asName, asModEvent) -EndFunction - -Function Alias_DefineMCMToggleModEvent(String asModEvent, Bool abInitialState = False, Int aiFlags = 0) - ; when mod event name will be used as option name - RegisterForModEvent(asModEvent, "OnBooleanToggleClick") - DefineMCMToggleOption("$dubh" + asModEvent, abInitialState, aiFlags, "$dubhHelp" + asModEvent, asModEvent) -EndFunction - - -Function Alias_DefineMCMToggleOptionGlobal(String asName, GlobalVariable akGlobal, Int aiFlags = 0) - DefineMCMToggleOptionGlobal("$dubh" + asName, akGlobal, aiFlags, "$dubhHelp" + asName) -EndFunction - - -Function Alias_DefineMCMSliderOptionGlobal(String asName, GlobalVariable akGlobal, Float afMin, Float afMax, Float afInterval, Int aiFlags = 0) - DefineMCMSliderOptionGlobal("$dubh" + asName, akGlobal, akGlobal.GetValue(), afMin, afMax, afInterval, "$dubhHelp" + asName, "{2}", aiFlags) -EndFunction - -Function Alias_DefineMCMMenuOptionGlobal(String asTextLabel, String asValuesCSV, GlobalVariable akGlobal, Int iDefault = 0) - DefineMCMMenuOptionGlobal("$dubh" + asTextLabel, asValuesCSV, akGlobal, iDefault, 0, "$dubhHelp" + asTextLabel, "") -EndFunction - - -Function DefineMCMToggleDisguise(Int aiIndex) - Int actualIndex = aiIndex - 1 - String sModEvent = "TryUpdateDisguise_" + actualIndex - RegisterForModEvent(sModEvent, "OnBooleanToggleClick") - DefineMCMToggleOptionGlobal("$dubhDisguise" + aiIndex, rgDisguisesEnabled[actualIndex] as GlobalVariable, 0, "$dubhHelpDisguise" + aiIndex, sModEvent) -EndFunction - -Function DefineMCMCheatDisguise(Int aiIndex) - String sModEvent = "CheatDisguise_" + aiIndex - RegisterForModEvent(sModEvent, "OnBooleanToggleClick") - DefineMCMTextOption("$dubhDisguise" + aiIndex, "", OPTION_FLAG_AS_TEXTTOGGLE, "$dubhHelpCheatDisguise" + aiIndex, sModEvent) -EndFunction - - -Function ClearDisguiseFactions() - ; Removes player from all disguise factions - - Int i = 0 - - While i < DisguiseFactions.GetSize() - Faction kFaction = DisguiseFactions.GetAt(i) as Faction - If PlayerRef.IsInFaction(kFaction) - PlayerRef.RemoveFromFaction(kFaction) - EndIf - i += 1 - EndWhile - - LogInfo("Removed the player from all disguise factions.") -EndFunction - - -Bool Function StartQuest(Quest akQuest) - If akQuest.IsStopping() - LogInfo(akQuest + ": could not start because quest is stopping") - Return False - EndIf - - If !akQuest.IsStopped() - LogInfo(akQuest + ": could not start because quest is not stopped") - Return False - EndIf - - If akQuest.Start() - LogInfo(akQuest + ": successfully started") - Return True - EndIf - - LogWarning(akQuest + ": could not start due to unknown reasons") - Return False -EndFunction - - -Bool Function StopQuest(Quest akQuest) - If akQuest.IsStopped() || akQuest.IsStopping() - LogWarning(akQuest + ": could not stop because quest is already stopped or stopping") - Return False - EndIf - - Int _cycles = 0 - - akQuest.Stop() - - While akQuest.IsRunning() - LogInfo(akQuest + ": waiting until quest stops running") - _cycles += 1 - EndWhile - - While akQuest.IsStopping() - LogInfo(akQuest + ": waiting until quest stops stopping") - _cycles += 1 - EndWhile - - If akQuest.IsStopped() - LogInfo(akQuest + ": successfully stopped") - Return True - EndIf - - LogWarning(akQuest + ": could not stop due to unknown reasons") - Return False -EndFunction - -; ============================================================================= -; EVENTS -; ============================================================================= - -Event OnConfigInit() - Pages = new String[9] - Pages[0] = "$dubhPageInformation" - Pages[1] = "$dubhPageDisguises" - Pages[2] = "$dubhPageDiscovery" - Pages[3] = "$dubhPageScoring" - Pages[4] = "$dubhPageRace" - Pages[5] = "$dubhPageCrime" - Pages[6] = "$dubhPageCrimeBounties" - Pages[7] = "$dubhPageAdvanced" - Pages[8] = "$dubhPageCheats" -EndEvent - -Event OnPageReset(String asPageName) - SetCursorFillMode(TOP_TO_BOTTOM) - - If asPageName == "" - LoadCustomContent("dubhDisguiseLogo.dds") - Return - EndIf - - If asPageName != "" - UnloadCustomContent() - EndIf - - If asPageName == "$dubhPageInformation" - SetCursorFillMode(TOP_TO_BOTTOM) - - AddHeaderOption("$dubhHeadingInformationAccolades") - DefineMCMParagraph("$dubhInformationAccoladesText01") - DefineMCMParagraph("$dubhInformationAccoladesText02") - DefineMCMParagraph("$dubhInformationAccoladesText03") - DefineMCMParagraph("$dubhInformationAccoladesText04") - DefineMCMParagraph("$dubhInformationAccoladesText05") - DefineMCMParagraph("$dubhInformationAccoladesText06") - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingInformationCredits") - DefineMCMParagraph("$dubhInformationCredits01") - DefineMCMParagraph("$dubhInformationCredits02") - DefineMCMParagraph("$dubhInformationCredits03") - - SetCursorPosition(1) - - AddHeaderOption("$dubhHeadingInformationSupport") - - DefineMCMParagraph("$dubhInformationSupportText01") - DefineMCMParagraph("$dubhInformationSupportText02") - DefineMCMParagraph("$dubhInformationSupportText03") - - AddEmptyOption() - - DefineMCMParagraph("$dubhInformationSupportText04") - DefineMCMParagraph("$dubhInformationSupportText05") - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingInformationPermissions") - DefineMCMParagraph("$dubhInformationPermissions01") - DefineMCMParagraph("$dubhInformationPermissions02") - - ElseIf asPageName == "$dubhPageDiscovery" - SetCursorFillMode(TOP_TO_BOTTOM) - - AddHeaderOption("$dubhHeadingDiscoveryFov") - Alias_DefineMCMSliderOptionGlobal("DiscoveryOptionViewCone", Global_fDetectionViewConeMCM, 30.0, 360.0, 5.0) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingDiscoveryLos") - Alias_DefineMCMSliderOptionGlobal("DiscoveryOptionLosMax", Global_fLOSDistanceMax, 1024.0, Global_fScriptDistanceMax.GetValue(), 256.0) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingDiscoveryFovPenalties") - Alias_DefineMCMSliderOptionGlobal("DiscoveryOptionFovClear", Global_fFOVPenaltyClear, 0.0, 1.0, 0.05) - Alias_DefineMCMSliderOptionGlobal("DiscoveryOptionFovDistorted", Global_fFOVPenaltyDistorted, 0.0, 1.0, 0.05) - Alias_DefineMCMSliderOptionGlobal("DiscoveryOptionFovPeripheral", Global_fFOVPenaltyPeripheral, 0.0, 1.0, 0.05) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingDiscoveryLosPenalties") - Alias_DefineMCMSliderOptionGlobal("DiscoveryOptionLosMid", Global_fLOSPenaltyMid, 0.0, 1.0, 0.05) - Alias_DefineMCMSliderOptionGlobal("DiscoveryOptionLosFar", Global_fLOSPenaltyFar, 0.0, 1.0, 0.05) - - SetCursorPosition(1) - - AddHeaderOption("$dubhHeadingDiscoveryBiWinning") - Alias_DefineMCMToggleOptionGlobal("DiscoveryOptionDremora", Global_iAlwaysSucceedDremora) - Alias_DefineMCMToggleOptionGlobal("DiscoveryOptionWerewolves", Global_iAlwaysSucceedWerewolves) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingDiscoveryVN") - Alias_DefineMCMToggleOptionGlobal("DiscoveryOptionVN", Global_iVampireNightOnly) - Alias_DefineMCMSliderOptionGlobal("DiscoveryOptionVNDayBegins", Global_iVampireNightOnlyDayHourBegin, 0.0, 24.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("DiscoveryOptionVNDayEnds", Global_iVampireNightOnlyDayHourEnd, 0.0, 24.0, 1.0) - - ElseIf asPageName == "$dubhPageScoring" - SetCursorFillMode(TOP_TO_BOTTOM) - - AddHeaderOption("$dubhHeadingScoringBestSkill") - Alias_DefineMCMSliderOptionGlobal("ScoringOptionBestSkillMax", Global_fBestSkillContribMax, 0.0, 100.0, 10.0) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingScoringMobility") - Alias_DefineMCMSliderOptionGlobal("ScoringOptionMobilityBonus", Global_fMobilityBonus, 1.0, 1.5, 0.05) - Alias_DefineMCMSliderOptionGlobal("ScoringOptionMobilityPenalty", Global_fMobilityPenalty, 0.5, 1.0, 0.05) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingScoringWeapons") - Alias_DefineMCMSliderOptionGlobal("ScoringOptionWeaponLeft", Global_fSlotWeaponLeft, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("ScoringOptionWeaponRight", Global_fSlotWeaponRight, 0.0, 100.0, 1.0) - - SetCursorPosition(1) - - AddHeaderOption("$dubhHeadingScoringEquipment") - Alias_DefineMCMSliderOptionGlobal("ScoringOptionAmulet", Global_fSlotAmulet, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("ScoringOptionBody", Global_fSlotBody, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("ScoringOptionCirclet", Global_fSlotCirclet, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("ScoringOptionFeet", Global_fSlotFeet, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("ScoringOptionHair", Global_fSlotHair, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("ScoringOptionHands", Global_fSlotHands, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("ScoringOptionRing", Global_fSlotRing, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("ScoringOptionShield", Global_fSlotShield, 0.0, 100.0, 1.0) - - ElseIf asPageName == "$dubhPageRace" - SetCursorFillMode(TOP_TO_BOTTOM) - - AddHeaderOption("$dubhHeadingRaceModifiers1") - Alias_DefineMCMSliderOptionGlobal("RaceOptionAltmer", Global_fRaceHighElf, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionArgonian", Global_fRaceArgonian, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionBosmer", Global_fRaceWoodElf, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionBreton", Global_fRaceBreton, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionDunmer", Global_fRaceDarkElf, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionImperial", Global_fRaceImperial, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionKhajiit", Global_fRaceKhajiit, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionNord", Global_fRaceNord, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionOrc", Global_fRaceOrc, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionRedguard", Global_fRaceRedguard, 0.0, 100.0, 1.0) - - SetCursorPosition(1) - - AddHeaderOption("$dubhHeadingRaceModifiers2") - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireAltmer", Global_fRaceHighElfVampire, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireArgonian", Global_fRaceArgonianVampire, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireBosmer", Global_fRaceWoodElfVampire, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireBreton", Global_fRaceBretonVampire, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireDunmer", Global_fRaceDarkElfVampire, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireImperial", Global_fRaceImperialVampire, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireKhajiit", Global_fRaceKhajiitVampire, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireNord", Global_fRaceNordVampire, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireOrc", Global_fRaceOrcVampire, 0.0, 100.0, 1.0) - Alias_DefineMCMSliderOptionGlobal("RaceOptionVampireRedguard", Global_fRaceRedguardVampire, 0.0, 100.0, 1.0) - - ElseIf asPageName == "$dubhPageCrime" - SetCursorFillMode(TOP_TO_BOTTOM) - - AddHeaderOption("$dubhHeadingCrimeBountyPenalty") - Alias_DefineMCMSliderOptionGlobal("CrimeOptionBountyMult", Global_fBountyPenaltyMult, 0.0, 1.0, 0.01, 1) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingCrimeBanditDisguise") - Alias_DefineMCMToggleOptionGlobal("CrimeOptionBandits", rgDisguisesEnabled[30] as GlobalVariable) - Alias_DefineMCMMenuOptionGlobal("CrimeOptionBanditSlot", "$dubhSlot0,$dubhSlot1,$dubhSlot2,$dubhSlot3,$dubhSlot4,$dubhSlot5,$dubhSlot6,$dubhSlot7,$dubhSlot8,$dubhSlot9", Global_iDisguiseEssentialSlotBandit, 1) - - SetCursorPosition(1) - - AddHeaderOption("$dubhHeadingCrimeFactionRelations") - Alias_DefineMCMToggleOptionModEvent("CrimeOptionGuardsVsDB", "dubhToggleGuardsVsDarkBrotherhood", bGuardsVsDarkBrotherhood) - Alias_DefineMCMToggleOptionModEvent("CrimeOptionGuardsVsTG", "dubhToggleGuardsVsThievesGuild", bGuardsVsThievesGuild) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingCrimeFactionRelationsNPC") - Alias_DefineMCMToggleOptionModEvent("CrimeOptionGuardsVsDBNPC", "dubhToggleGuardsVsDarkBrotherhoodNPC", bGuardsVsDarkBrotherhoodNPC) - Alias_DefineMCMToggleOptionModEvent("CrimeOptionGuardsVsTGNPC", "dubhToggleGuardsVsThievesGuildNPC", bGuardsVsThievesGuildNPC) - - ElseIf asPageName == "$dubhPageCrimeBounties" - SetCursorFillMode(TOP_TO_BOTTOM) - - AddHeaderOption("$dubhHeadingCrimeEmpireLovesLists") - Alias_DefineMCMSliderOptionGlobal("CrimeOptionImperial", Global_iCrimeImperial, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionStormcloaks", Global_iCrimeStormcloaks, 0.0, 99999.0, 1.0, 1) - - SetCursorPosition(1) - - AddHeaderOption("$dubhHeadingCrimeTrackedBounties") - Alias_DefineMCMSliderOptionGlobal("CrimeOptionFalkreath", Global_iCrimeFalkreath, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionHjaalmarch", Global_iCrimeHjaalmarch, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionMarkarth", Global_iCrimeMarkarth, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionPale", Global_iCrimePale, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionRavenRock", Global_iCrimeRavenRock, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionRiften", Global_iCrimeRiften, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionSolitude", Global_iCrimeSolitude, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionWhiterun", Global_iCrimeWhiterun, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionWindhelm", Global_iCrimeWindhelm, 0.0, 99999.0, 1.0, 1) - Alias_DefineMCMSliderOptionGlobal("CrimeOptionWinterhold", Global_iCrimeWinterhold, 0.0, 99999.0, 1.0, 1) - - ElseIf asPageName == "$dubhPageAdvanced" - SetCursorFillMode(TOP_TO_BOTTOM) - - AddHeaderOption("$dubhHeadingAdvancedWatchRate") - Alias_DefineMCMSliderOptionGlobal("AdvancedOptionWatchRate", Global_fScriptSuspendTime, 0.0, 60.0, 1.0) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingAdvancedDiscovery") - Alias_DefineMCMSliderOptionGlobal("AdvancedOptionDiscoveryMax", Global_fScriptDistanceMax, 0.0, Global_fEscapeDistance.GetValue(), 256.0) - Alias_DefineMCMSliderOptionGlobal("AdvancedOptionUpdateRateDiscovery", Global_fScriptUpdateFrequencyMonitor, 0.0, 30.0, 1.0) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingAdvancedCompatibility") - Alias_DefineMCMSliderOptionGlobal("AdvancedOptionUpdateRateCompatibility", Global_fScriptUpdateFrequencyCompatibility, 0.0, 30.0, 1.0) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingAdvancedEnemies") - Alias_DefineMCMSliderOptionGlobal("AdvancedOptionEscapeDistance", Global_fEscapeDistance, Global_fScriptDistanceMax.GetValue(), 8192.0, 256.0) - - SetCursorPosition(1) - - AddHeaderOption("$dubhHeadingAdvancedCombatDelay") - Alias_DefineMCMSliderOptionGlobal("AdvancedOptionCombatDelay", Global_fScriptSuspendTimeBeforeAttack, 0.0, 60.0, 1.0) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingAdvancedDebug") - Alias_DefineMCMToggleOptionGlobal("AdvancedOptionNotifyEnabled", Global_iNotifyEnabled) - Alias_DefineMCMToggleOptionGlobal("AdvancedOptionPapyrusLogging", Global_iPapyrusLoggingEnabled) - - AddEmptyOption() - - AddHeaderOption("$dubhHeadingAdvancedSetup") - Alias_DefineMCMToggleOptionModEvent("AdvancedOptionCompatibility", "ToggleDynamicCompatibility", CompatibilityQuest.IsRunning()) - Alias_DefineMCMToggleOptionModEvent("AdvancedOptionDiscoverySystem", "ToggleDiscoverySystem", DetectionQuest.IsRunning()) - - ElseIf asPageName == "$dubhPageDisguises" - SetCursorFillMode(TOP_TO_BOTTOM) - - DefineMCMParagraph("$dubhHelpPageDisguises1") - DefineMCMParagraph("$dubhHelpPageDisguises2") - - AddEmptyOption() - - DefineMCMParagraph("$dubhHelpPageDisguises3") - DefineMCMParagraph("$dubhHelpPageDisguises4") - DefineMCMParagraph("$dubhHelpPageDisguises5") - - SetCursorPosition(1) - - DefineMCMToggleDisguise(1) - DefineMCMToggleDisguise(2) - DefineMCMToggleDisguise(3) - DefineMCMToggleDisguise(4) - DefineMCMToggleDisguise(5) - DefineMCMToggleDisguise(6) - DefineMCMToggleDisguise(7) - DefineMCMToggleDisguise(8) - DefineMCMToggleDisguise(9) - DefineMCMToggleDisguise(10) - DefineMCMToggleDisguise(11) - DefineMCMToggleDisguise(12) - DefineMCMToggleDisguise(13) - DefineMCMToggleDisguise(14) - DefineMCMToggleDisguise(15) - DefineMCMToggleDisguise(16) - DefineMCMToggleDisguise(17) - DefineMCMToggleDisguise(18) - DefineMCMToggleDisguise(19) - DefineMCMToggleDisguise(20) - DefineMCMToggleDisguise(21) - DefineMCMToggleDisguise(22) - DefineMCMToggleDisguise(23) - DefineMCMToggleDisguise(24) - DefineMCMToggleDisguise(25) - DefineMCMToggleDisguise(26) - DefineMCMToggleDisguise(27) - DefineMCMToggleDisguise(28) - DefineMCMToggleDisguise(29) - DefineMCMToggleDisguise(30) - DefineMCMToggleDisguise(31) - - ElseIf asPageName == "$dubhPageCheats" - SetCursorFillMode(TOP_TO_BOTTOM) - - DefineMCMParagraph("$dubhHelpPageCheats1") - DefineMCMParagraph("$dubhHelpPageCheats2") - - SetCursorPosition(1) - - DefineMCMCheatDisguise(1) - DefineMCMCheatDisguise(2) - DefineMCMCheatDisguise(3) - DefineMCMCheatDisguise(4) - DefineMCMCheatDisguise(5) - DefineMCMCheatDisguise(6) - DefineMCMCheatDisguise(7) - DefineMCMCheatDisguise(8) - DefineMCMCheatDisguise(9) - DefineMCMCheatDisguise(10) - DefineMCMCheatDisguise(11) - DefineMCMCheatDisguise(12) - DefineMCMCheatDisguise(13) - DefineMCMCheatDisguise(14) - DefineMCMCheatDisguise(15) - DefineMCMCheatDisguise(16) - DefineMCMCheatDisguise(17) - DefineMCMCheatDisguise(18) - DefineMCMCheatDisguise(19) - DefineMCMCheatDisguise(20) - DefineMCMCheatDisguise(21) - DefineMCMCheatDisguise(22) - DefineMCMCheatDisguise(23) - DefineMCMCheatDisguise(24) - DefineMCMCheatDisguise(25) - DefineMCMCheatDisguise(26) - DefineMCMCheatDisguise(27) - DefineMCMCheatDisguise(28) - DefineMCMCheatDisguise(29) - DefineMCMCheatDisguise(30) - DefineMCMCheatDisguise(31) - EndIf -EndEvent - -Event OnBooleanToggleClick(String asEventName, String strArg, Float numArg, Form sender) - FormList kForms = None - - If asEventName == "dubhToggleDynamicCompatibility" - If CompatibilityQuest.IsRunning() - StopQuest(CompatibilityQuest) - Else - StartQuest(CompatibilityQuest) - EndIf - ElseIf asEventName == "dubhToggleDiscoverySystem" - If DetectionQuest.IsRunning() - StopQuest(DetectionQuest) - Else - StartQuest(DetectionQuest) - EndIf - ElseIf LibFire.ContainsText(asEventName, "CheatDisguise") - String[] results = LibFire.SplitString(asEventName, "_") - Int factionIndex = (results[1] as Int) - 1 - PlayerRef.AddItem(DisguiseFormLists.GetAt(factionIndex) as FormList, 1, True) - LogInfo("Added items from disguise formlist: factionIndex = " + factionIndex) - Int instanceId = PickUpSound.Play(PlayerRef) - Sound.SetInstanceVolume(instanceId, 1.0) - ElseIf LibFire.ContainsText(asEventName, "TryUpdateDisguise") - String[] results = LibFire.SplitString(asEventName, "_") - Int factionIndex = results[1] as Int - PlayerScript.UpdateDisguise(factionIndex) - LogInfo("Updated disguise: factionIndex = " + factionIndex) - ElseIf asEventName == "dubhToggleGuardsVsDarkBrotherhood" - bGuardsVsDarkBrotherhood = numArg as Bool - If bGuardsVsDarkBrotherhood - LibFire.SetEnemies(DisguiseFaction03, GuardFactions) - Else - LibFire.SetEnemies(DisguiseFaction03, GuardFactions, True, True) - EndIf - ElseIf asEventName == "dubhToggleGuardsVsDarkBrotherhoodNPC" - bGuardsVsDarkBrotherhoodNPC = numArg as Bool - If bGuardsVsDarkBrotherhoodNPC - LibFire.SetEnemies(DarkBrotherhoodFaction, GuardFactions) - Else - LibFire.SetEnemies(DarkBrotherhoodFaction, GuardFactions, True, True) - EndIf - ElseIf asEventName == "dubhToggleGuardsVsThievesGuild" - bGuardsVsThievesGuild = numArg as Bool - If bGuardsVsThievesGuild - LibFire.SetEnemies(DisguiseFaction12, GuardFactions) - LogInfo("Guards vs. Thieves Guild toggled on for Player") - Else - LibFire.SetEnemies(DisguiseFaction12, GuardFactions, True, True) - LogInfo("Guards vs. Thieves Guild toggled off for Player") - EndIf - ElseIf asEventName == "dubhToggleGuardsVsThievesGuildNPC" - bGuardsVsThievesGuildNPC = numArg as Bool - If bGuardsVsThievesGuildNPC - LibFire.SetEnemies(ThievesGuildFaction, GuardFactions) - LogInfo("Guards vs. Thieves Guild toggled on for NPCs") - Else - LibFire.SetEnemies(ThievesGuildFaction, GuardFactions, True, True) - LogInfo("Guards vs. Thieves Guild toggled off for NPCs") - EndIf - EndIf -EndEvent \ No newline at end of file diff --git a/modules/tests/iEquip/dubhFactionEnemyScript.psc b/modules/tests/iEquip/dubhFactionEnemyScript.psc deleted file mode 100644 index d140835..0000000 --- a/modules/tests/iEquip/dubhFactionEnemyScript.psc +++ /dev/null @@ -1,207 +0,0 @@ -ScriptName dubhFactionEnemyScript Extends ActiveMagicEffect - -Import dubhUtilityScript - -; ============================================================================= -; PROPERTIES -; ============================================================================= - -GlobalVariable Property Global_fEscapeDistance Auto -GlobalVariable Property Global_fScriptDistanceMax Auto -GlobalVariable Property Global_iDiscoveryEnabled Auto -GlobalVariable Property Global_iPapyrusLoggingEnabled Auto - -Actor Property PlayerRef Auto -FormList Property BaseFactions Auto -FormList Property DisguiseFactions Auto -Spell Property FactionEnemyAbility Auto - -; States -Bool[] Property rgDisguisesRemoved Auto - -; ============================================================================= -; SCRIPT-LOCAL VARIABLES -; ============================================================================= - -Actor NPC - -; ============================================================================= -; FUNCTIONS -; ============================================================================= - -Function _Log(String asTextToPrint, Int aiSeverity = 0) - If IntToBool(Global_iPapyrusLoggingEnabled) - Debug.OpenUserLog("MasterOfDisguise") - Debug.TraceUser("MasterOfDisguise", "dubhFactionEnemyScript> " + asTextToPrint, aiSeverity) - EndIf -EndFunction - - -Function LogInfo(String asTextToPrint) - _Log("[INFO] " + asTextToPrint, 0) -EndFunction - - -Function LogWarning(String asTextToPrint) - _Log("[WARN] " + asTextToPrint, 1) -EndFunction - - -Function LogError(String asTextToPrint) - _Log("[ERRO] " + asTextToPrint, 2) -EndFunction - - -Function TryAddDisguises() - ; Restores previously removed disguises to player - - Int i = 0 - - While i < rgDisguisesRemoved.Length - If rgDisguisesRemoved[i] - If TryAddToFaction(PlayerRef, DisguiseFactions.GetAt(i) as Faction) - rgDisguisesRemoved[i] = False - LogInfo("Successfully added disguise to player at index: " + i) - EndIf - - ; TODO: if player is wearing guard disguise, save bounties to crime gold arrays and clear actual crime gold - EndIf - - i += 1 - EndWhile -EndFunction - - -Function TryRemoveDisguises() - ; Removes all disguises from player - - Int i = 0 - - While i < rgDisguisesRemoved.Length - If !rgDisguisesRemoved[i] - If TryRemoveFromFaction(PlayerRef, DisguiseFactions.GetAt(i) as Faction) - rgDisguisesRemoved[i] = True - LogInfo("Successfully removed disguise from player at index: " + i) - EndIf - - ; TODO: if player is wearing guard disguise, add penalty amount to current crime faction and restore bounties - EndIf - - i += 1 - EndWhile -EndFunction - - -Function TryRestoreDisguise(String asLogText) - ; Restore disguised state - - If NPC && !NPC.HasSpell(FactionEnemyAbility) - Return - EndIf - - If !PlayerRef.IsDead() - TryAddDisguises() - EndIf - - If NPC && NPC.RemoveSpell(FactionEnemyAbility) - LogInfo(asLogText) - NPC = None - EndIf -EndFunction - -; =============================================================================== -; EVENTS -; =============================================================================== - -Event OnEffectStart(Actor akTarget, Actor akCaster) - NPC = akCaster - - If PlayerRef.IsDead() - If NPC && NPC.RemoveSpell(FactionEnemyAbility) - LogInfo("Detached enemy marker from " + NPC + " because the Player was prematurely dead") - NPC = None - Return - EndIf - Else - If NPC && NPC.GetDistance(PlayerRef) <= Global_fScriptDistanceMax.GetValue() - TryRemoveDisguises() - - NPC.EvaluatePackage() - - If NPC.IsHostileToActor(PlayerRef) - If !NPC.IsAlerted() - NPC.SetAlert(True) - EndIf - - If !NPC.IsWeaponDrawn() - NPC.DrawWeapon() - EndIf - - Game.ShakeCamera(afStrength = 0.4) - - NPC.EvaluatePackage() - EndIf - - Suspend(5.0) - EndIf - EndIf - - If NPC && NPC.Is3DLoaded() && !NPC.IsDead() - RegisterForSingleUpdate(1.0) - Else - TryRestoreDisguise("Detached enemy marker from " + NPC + " because the NPC was either not loaded or dead") - EndIf -EndEvent - - -Event OnCellDetach() - TryRestoreDisguise("Detached enemy marker from " + NPC + " because the NPC's parent cell has been detached") -EndEvent - - -Event OnDetachedFromCell() - TryRestoreDisguise("Detached enemy marker from " + NPC + " because the NPC was detached from the cell") -EndEvent - - -Event OnUnload() - TryRestoreDisguise("Detached enemy marker from " + NPC + " because the NPC has been unloaded") -EndEvent - - -Event OnUpdate() - If !IntToBool(Global_iDiscoveryEnabled) - If NPC && NPC.RemoveSpell(FactionEnemyAbility) - LogInfo("Detached enemy marker from " + NPC + " because detection is disabled") - NPC = None - Return - EndIf - ElseIf PlayerRef.IsDead() - If NPC && NPC.RemoveSpell(FactionEnemyAbility) - LogInfo("Detached enemy marker from " + NPC + " because the Player died") - NPC = None - Return - EndIf - ElseIf NPC && NPC.IsDead() - TryRestoreDisguise("Detached enemy marker from " + NPC + " because the NPC was dead") - Return - ElseIf NPC && NPC.IsHostileToActor(PlayerRef) && NPC.GetDistance(PlayerRef) >= Global_fEscapeDistance.GetValue() - TryRestoreDisguise("Detached enemy marker from " + NPC + " because the Player escaped") - Return - ElseIf NPC && !NPC.IsHostileToActor(PlayerRef) - TryRestoreDisguise("Detached enemy marker from " + NPC + " because the NPC was no longer hostile") - Return - ElseIf NPC && !NPC.IsDead() && NPC.IsHostileToActor(PlayerRef) - RegisterForSingleUpdate(1.0) - EndIf -EndEvent - - -Event OnDeath(Actor akKiller) - TryRestoreDisguise("Detached enemy marker from " + NPC + " because the NPC was killed by " + akKiller) -EndEvent - - -Event OnEffectFinish(Actor akTarget, Actor akCaster) - TryRestoreDisguise("Detached enemy marker from " + NPC + " because the effect finished") -EndEvent diff --git a/modules/tests/iEquip/dubhMonitorEffectScript.psc b/modules/tests/iEquip/dubhMonitorEffectScript.psc deleted file mode 100644 index 7489e09..0000000 --- a/modules/tests/iEquip/dubhMonitorEffectScript.psc +++ /dev/null @@ -1,620 +0,0 @@ -ScriptName dubhMonitorEffectScript Extends ActiveMagicEffect - -Import dubhUtilityScript - -; ============================================================================= -; PROPERTIES -; ============================================================================= - -GlobalVariable Property Global_fBestSkillContribMax Auto -GlobalVariable Property Global_fLOSDistanceMax Auto -GlobalVariable Property Global_fFOVPenaltyClear Auto -GlobalVariable Property Global_fFOVPenaltyDistorted Auto -GlobalVariable Property Global_fFOVPenaltyPeripheral Auto -GlobalVariable Property Global_fLOSPenaltyFar Auto -GlobalVariable Property Global_fLOSPenaltyMid Auto -GlobalVariable Property Global_fMobilityBonus Auto -GlobalVariable Property Global_fMobilityPenalty Auto -GlobalVariable Property Global_fScriptDistanceMax Auto -GlobalVariable Property Global_fScriptSuspendTime Auto -GlobalVariable Property Global_fScriptSuspendTimeBeforeAttack Auto -GlobalVariable Property Global_fScriptUpdateFrequencyMonitor Auto -GlobalVariable Property Global_iCrimeArrestOnSightNonViolentThreshold Auto -GlobalVariable Property Global_iPapyrusLoggingEnabled Auto - -Actor Property PlayerRef Auto -Faction Property PlayerFaction Auto -FormList Property BaseFactions Auto -FormList Property DisguiseFactions Auto -FormList Property DisguiseFormLists Auto -FormList Property ExcludedDamageSources Auto -FormList Property GuardFactions Auto -MagicEffect Property FactionEnemyEffect Auto -Message Property DisguiseWarningSuspicious Auto ; "You are being watched..." (5 second delay) -Spell Property FactionEnemyAbility Auto -Spell Property MonitorAbility Auto - -; Ranges -GlobalVariable[] Property rgRaceWeights Auto -GlobalVariable[] Property rgSlotWeights Auto -Race[] Property rgRaces Auto - -; ============================================================================= -; SCRIPT-LOCAL VARIABLES -; ============================================================================= - -Actor NPC -Bool[] FactionStatesPlayer -Bool[] FactionStatesTarget - -; =============================================================================== -; FUNCTIONS -; =============================================================================== - -Function _Log(String asTextToPrint, Int aiSeverity = 0) - If IntToBool(Global_iPapyrusLoggingEnabled) - Debug.OpenUserLog("MasterOfDisguise") - Debug.TraceUser("MasterOfDisguise", "dubhMonitorEffectScript> " + asTextToPrint, aiSeverity) - EndIf -EndFunction - - -Function LogInfo(String asTextToPrint) - _Log("[INFO] " + asTextToPrint, 0) -EndFunction - - -Function LogWarning(String asTextToPrint) - _Log("[WARN] " + asTextToPrint, 1) -EndFunction - - -Function LogError(String asTextToPrint) - _Log("[ERRO] " + asTextToPrint, 2) -EndFunction - - -Float Function CalculateBestSkillWeight() - ; Calculates the skill score for the player's best skill - - Float fBestSkillValue = GetBestSkill(PlayerRef) - - Return ((Global_fBestSkillContribMax.GetValue() * LibMathf.Min(fBestSkillValue, 100.0)) / 100.0) -EndFunction - - -Bool[] Function WhichSlotsEquipped(Int aiFactionIndex) - Bool[] rgSlotsEquipped = new Bool[10] - - Form[] rgWornEquipment = LibTurtleClub.GetWornEquipment(PlayerRef, True, True) - - If !rgWornEquipment - LogError(NPC + ": rgWornEquipment was None - cannot get worn equipment for Player") - Return rgSlotsEquipped - EndIf - - If rgWornEquipment.Length == 0 - LogWarning(NPC + ": rgWornEquipment was empty - Player has no worn equipment") - Return rgSlotsEquipped - EndIf - - FormList kCurrentDisguise = DisguiseFormLists.GetAt(aiFactionIndex) as FormList - - ; WARN: if length of DisguiseFormLists increases, this will blow up - rgSlotsEquipped = LibFire.SearchListForForms(kCurrentDisguise, rgWornEquipment) - - Return rgSlotsEquipped -EndFunction - - -Float Function CalculateEquipWeight(Bool[] rgEquippedSlots) - ; Returns the equipment score from worn items - ; 1. Get worn items - ; 2. Check if worn items are in formlist - ; 3. If worn items are in formlist, return those slots as Bool array - - Float fEquipScore = 0.0 - - ; Hair and Circlet - If rgEquippedSlots[0] || rgEquippedSlots[7] - ; Both - If rgEquippedSlots[0] && rgEquippedSlots[7] - fEquipScore += (rgSlotWeights[7] as GlobalVariable).GetValue() - Else - ; Hair, but not Circlet - If rgEquippedSlots[0] && !rgEquippedSlots[7] - fEquipScore += (rgSlotWeights[0] as GlobalVariable).GetValue() - ; Circlet, but not Hair - Else - fEquipScore += (rgSlotWeights[7] as GlobalVariable).GetValue() - EndIf - EndIf - EndIf - - Int i = 1 - While i < 7 - If rgEquippedSlots[i] - fEquipScore += (rgSlotWeights[i] as GlobalVariable).GetValue() - EndIf - i += 1 - EndWhile - - ; Weapons Left and Right - If rgEquippedSlots[8] || rgEquippedSlots[9] - If rgEquippedSlots[8] - fEquipScore += (rgSlotWeights[8] as GlobalVariable).GetValue() - ElseIf rgEquippedSlots[9] - fEquipScore += (rgSlotWeights[9] as GlobalVariable).GetValue() - EndIf - EndIf - - Return LibMathf.Clamp(fEquipScore, 0, 100) -EndFunction - - -Float Function LookupRaceWeight(Int aiFactionIndex) - ; Calculates the race score for player based on faction - - Race kPlayerRace = PlayerRef.GetRace() - - Int iRaceIndex = LibTurtleClub.LookupRaceWeightIndex(aiFactionIndex, kPlayerRace, rgRaces) - - If iRaceIndex < 0 - LogWarning(NPC + ": cannot find player race in race weight table: aiFactionIndex = " + aiFactionIndex + ", kPlayerRace = " + kPlayerRace) - Return 0.0 - EndIf - - Float fRaceWeight = (rgRaceWeights[iRaceIndex] as GlobalVariable).GetValue() - - If LibMathf.InRange(aiFactionIndex, 0, 2) || LibMathf.InRange(aiFactionIndex, 5, 7) || LibMathf.InRange(aiFactionIndex, 13, 19) || LibMathf.InRange(aiFactionIndex, 21, 23) - Return fRaceWeight - EndIf - - If aiFactionIndex == 11 || aiFactionIndex == 25 || aiFactionIndex == 27 - Return fRaceWeight - EndIf - - If aiFactionIndex == 3 || aiFactionIndex == 12 || aiFactionIndex == 28 - Return -fRaceWeight - EndIf - - If aiFactionIndex == 4 - Return LibMathf.IfThen(iRaceIndex == 2, fRaceWeight, -fRaceWeight) - EndIf - - If aiFactionIndex == 8 || aiFactionIndex == 9 || aiFactionIndex == 20 || aiFactionIndex == 26 - Return LibMathf.IfThen(iRaceIndex == 12, fRaceWeight, -fRaceWeight) - EndIf - - If aiFactionIndex == 10 - Return LibMathf.IfThen(iRaceIndex == 6 || iRaceIndex == 18, fRaceWeight, -fRaceWeight) - EndIf - - If aiFactionIndex == 24 - Return LibMathf.IfThen(iRaceIndex == 12 || iRaceIndex == 14, fRaceWeight, -fRaceWeight) - EndIf - - If aiFactionIndex == 29 - Return LibMathf.IfThen(iRaceIndex == 16, fRaceWeight, -fRaceWeight) - EndIf - - If aiFactionIndex == 30 - Return LibMathf.IfThen(iRaceIndex == 6, -fRaceWeight, fRaceWeight) - EndIf - - Return 0.0 -EndFunction - - -Float Function Roll(Int aiFactionIndex) - ; Returns a value between 0.0 and 1.0 weighted by skill, race, and equipment - - Float result = 0.0 - result += CalculateBestSkillWeight() - result += LookupRaceWeight(aiFactionIndex) - - Bool[] rgSlotsEquipped = WhichSlotsEquipped(aiFactionIndex) - result += CalculateEquipWeight(rgSlotsEquipped) - - Return LibMathf.Min(LibMathf.Clamp(result, 0, 100) * 0.01, 1) -EndFunction - - -Int Function FindActiveDisguise() - ; Returns the index of the active disguise faction when player and NPC are in matching factions - - If !LibFire.ActorIsInAnyFaction(PlayerRef, DisguiseFactions) - Return -1 - EndIf - - If NPC && !LibFire.ActorIsInAnyFaction(NPC, BaseFactions) - Return -1 - EndIF - - Int i = 0 - - While i < FactionStatesPlayer.Length && NPC - If FactionStatesPlayer[i] && FactionStatesTarget[i] - If NPC && LibFire.ActorIsInFaction(NPC, BaseFactions.GetAt(i) as Faction) - Return i - EndIf - EndIf - - i += 1 - EndWhile - - Return -1 -EndFunction - - -Float Function QueryFOVPenalty(Int aiFovType) - ; Returns the FOV penalty to max FOV width (affects NPC roll) - - If aiFovType == 1 ; Clear - Return Global_fFOVPenaltyClear.GetValue() - EndIf - - If aiFovType == 2 ; Distorted - Return Global_fFOVPenaltyDistorted.GetValue() - EndIf - - If aiFovType == 3 ; Peripheral - Return Global_fFOVPenaltyPeripheral.GetValue() - EndIf - - Return 1.0 -EndFunction - - -Float Function QueryLOSPenalty(Int aiLosType) - ; Returns the LOS penalty to max LOS distance (affects NPC roll) - - If aiLosType == 1 ; Near - Return 1.0 - EndIf - - If aiLosType == 2 ; Mid - Return Global_fLOSPenaltyMid.GetValue() - EndIf - - If aiLosType == 3 ; Far - Return Global_fLOSPenaltyFar.GetValue() - EndIf - - Return 1.0 -EndFunction - - -Float Function QueryMobilityMult() - ; Retrieves mobility bonus or penalty (affects Player roll) - - If PlayerRef.IsRunning() || PlayerRef.IsSprinting() || PlayerRef.IsSneaking() || PlayerRef.IsWeaponDrawn() - Return Global_fMobilityPenalty.GetValue() - EndIf - - Return Global_fMobilityBonus.GetValue() -EndFunction - - -Bool Function TryToDiscoverPlayer(Int aiFactionIndex) - ; Returns whether PlayerRef was discovered by NPC - - If !NPC - Return False - EndIf - - If NPC && !NPC.HasLOS(PlayerRef) - LogInfo(NPC + ": cannot start rolling for discovery because line of sight to Player lost") - Return False - EndIf - - Float fLightLevel = PlayerRef.GetLightLevel() - - Float fMaxDistance = (Global_fLOSDistanceMax.GetValue() * (fLightLevel / 100)) - - If Global_fScriptSuspendTime.GetValue() > 0.0 - Float fDistanceToPlayer = NPC.GetDistance(PlayerRef) - - If LibMathf.InRange(fDistanceToPlayer, 0.0, fMaxDistance) - If !PlayerRef.IsRunning() && !PlayerRef.IsSprinting() && !PlayerRef.IsSneaking() && !PlayerRef.IsWeaponDrawn() - LogInfo(NPC + ": watching player") - NPC.SetLookAt(PlayerRef) - - DisguiseWarningSuspicious.Show() - Suspend(Global_fScriptSuspendTime.GetValue()) - - If NPC && !NPC.HasLOS(PlayerRef) - LogInfo(NPC + ": exiting early while rolling for discovery because line of sight to Player lost") - Return False - EndIf - EndIf - EndIf - EndIf - - Float fMaxHeadingAngle = Game.GetGameSettingFloat("fDetectionViewCone") - - Float fHeadingAngle = NPC.GetHeadingAngle(PlayerRef) - - If !LibMathf.InRange(fHeadingAngle, Math.Abs(fMaxHeadingAngle) * -1.0, fMaxHeadingAngle) - LogInfo(NPC + ": exiting discovery roll because Player is outside detection view cone") - Return False - EndIf - - Float fDistanceToPlayer = NPC.GetDistance(PlayerRef) - - If !LibMathf.InRange(fDistanceToPlayer, 0.0, fMaxDistance) - LogInfo(NPC + ": exiting discovery roll because Player not found within " + fDistanceToPlayer + " light-adjusted distance units") - Return False - EndIf - - If NPC && !NPC.HasLOS(PlayerRef) - LogInfo(NPC + ": exiting discovery roll because line of sight to Player lost") - Return False - EndIf - - Int iFovType = GetFovType(fHeadingAngle, fMaxHeadingAngle) - Int iLosType = GetLosType(fDistanceToPlayer, fMaxDistance) - - Float fFOVPenalty = QueryFOVPenalty(iFovType) - Float fLOSPenalty = QueryLOSPenalty(iLosType) - - Float fDiceRollNPC = Utility.RandomFloat(0.0, 1.0) - Float fDiceRollPlayer = Roll(aiFactionIndex) - - Float fMobilityMult = QueryMobilityMult() - - fDiceRollPlayer = fDiceRollPlayer * fMobilityMult - fDiceRollNPC *= fFOVPenalty - fDiceRollNPC /= fLOSPenalty - - If fDiceRollPlayer > fDiceRollNPC - LogInfo(NPC + ": player won dice roll (" + fDiceRollPlayer + " vs. " + fDiceRollNPC + ") and escaped notice") - Return False - EndIf - - LogInfo(NPC + ": player lost dice roll (" + fDiceRollPlayer + " vs. " + fDiceRollNPC + ") and was discovered") - Return True -EndFunction - - -Bool Function TryRemoveMonitorAbility(String asLogMessage) - If NPC && MonitorAbility && NPC.RemoveSpell(MonitorAbility) - LogInfo(asLogMessage) - NPC = None - Return True - EndIf - Return False -EndFunction - - -Bool Function TryIncreaseBounty(Int aiFactionIndex) - ; Increases bounty if player is in Thieves Guild Disguise and NPC is in a guard faction - - If aiFactionIndex != 11 - Return False - EndIf - - If NPC && !LibFire.ActorIsInAnyFaction(NPC, GuardFactions) - Return False - EndIf - - Faction kCrimeFaction = NPC.GetCrimeFaction() - - If !kCrimeFaction - Return False - EndIf - - Int iNonViolentThreshold = Global_iCrimeArrestOnSightNonViolentThreshold.GetValue() as Int - - If kCrimeFaction.GetCrimeGoldNonViolent() < iNonViolentThreshold - Int result = LibMathf.RoundToInt(iNonViolentThreshold * 0.1) - kCrimeFaction.ModCrimeGold(result, False) - LogInfo("Increased crime gold by " + result + " for faction: aiFactionIndex = " + aiFactionIndex + ", kCrimeFaction = " + kCrimeFaction) - Return True - EndIf - - Return False -EndFunction - - -; =============================================================================== -; EVENTS -; =============================================================================== - -Event OnEffectStart(Actor akTarget, Actor akCaster) - NPC = akTarget - If NPC && NPC.Is3DLoaded() && !NPC.IsDead() && NPC.HasSpell(MonitorAbility) - RegisterForSingleUpdate(Global_fScriptUpdateFrequencyMonitor.GetValue()) - Else - TryRemoveMonitorAbility(NPC + ": detached monitor because NPC was not loaded and dead") - EndIf -EndEvent - - -Event OnCellDetach() - TryRemoveMonitorAbility(NPC + ": detached monitor because NPC's parent cell has been detached") -EndEvent - - -Event OnDetachedFromCell() - TryRemoveMonitorAbility(NPC + ": detached monitor because NPC was detached from the cell") -EndEvent - - -Event OnUnload() - TryRemoveMonitorAbility(NPC + ": detached monitor because NPC has been unloaded") -EndEvent - - -Event OnUpdate() - If NPC && !NPC.HasSpell(MonitorAbility) - LogInfo(NPC + ": stopping monitor because ability was removed") - NPC = None - Return - EndIf - - If NPC && NPC.IsDead() - If TryRemoveMonitorAbility(NPC + ": detached monitor because NPC is dead") - Return - EndIf - EndIf - - ; don't execute anything if the player has a menu open - If !Utility.IsInMenuMode() - FactionStatesPlayer = LibTurtleClub.GetFactionStates(PlayerRef, DisguiseFactions) - - If NPC - FactionStatesTarget = LibTurtleClub.GetFactionStates(NPC, BaseFactions) - Else - Return - EndIf - - ; ----------------------------------------------------------------------- - ; ERRANT HOSTILITY - ; ----------------------------------------------------------------------- - ; no reason to call TryToDiscoverPlayer() if the actor is already hostile - ; ----------------------------------------------------------------------- - If NPC && !PlayerRef.IsDead() && !NPC.IsDead() && NPC.GetCombatTarget() == PlayerRef && !NPC.HasMagicEffect(FactionEnemyEffect) - ; player and npc must be in an appropriate disguise/base faction pair - If FindActiveDisguise() > -1 - ; try to make the npc hostile - If NPC && NPC.AddSpell(FactionEnemyAbility) - LogInfo(NPC + ": attached " + FactionEnemyAbility + " due to unknown hostility") - EndIf - EndIf - EndIf - - ; ----------------------------------------------------------------------- - ; CORE LOOP - ; ----------------------------------------------------------------------- - If NPC && !PlayerRef.IsDead() && !NPC.IsDead() - ; NPC must satisfy various conditions before running expensive loops and math calculations - If NPC && !NPC.IsHostileToActor(PlayerRef) && !NPC.HasMagicEffect(FactionEnemyEffect) && !NPC.IsInCombat() && NPC.HasLOS(PlayerRef) && PlayerRef.IsDetectedBy(NPC) && !NPC.IsAlerted() && !NPC.IsArrested() && !NPC.IsArrestingTarget() && !NPC.IsBleedingOut() && !NPC.IsCommandedActor() && !NPC.IsGhost() && !NPC.IsInKillMove() && !NPC.IsPlayerTeammate() && !NPC.IsTrespassing() && !NPC.IsUnconscious() && !LibMathf.InRange(NPC.GetSleepState() as Float, 3, 4) - ; player and NPC must be in an appropriate disguise/base faction pair - Int iActiveDisguise = FindActiveDisguise() - If iActiveDisguise > -1 - ; try to roll for detection - If TryToDiscoverPlayer(iActiveDisguise) - ; suspend for some amount of seconds, if global set - Float fTimeBeforeAttack = Global_fScriptSuspendTimeBeforeAttack.GetValue() - If fTimeBeforeAttack > 0 - Suspend(fTimeBeforeAttack) - EndIf - - ; ensure that the actor still has line of sight to the Player - If NPC && NPC.HasLOS(PlayerRef) - If !TryIncreaseBounty(iActiveDisguise) && NPC.AddSpell(FactionEnemyAbility) - LogInfo(NPC + ": attached " + FactionEnemyAbility + " to " + NPC + " who won detection roll") - EndIf - - NPC.ClearLookAt() - Else - If NPC - LogInfo(NPC + ": discarded dice roll because line of sight to Player lost") - NPC.ClearLookAt() - EndIf - EndIf - Else - If NPC - NPC.ClearLookAt() - EndIf - EndIf - EndIf - EndIf - EndIf - - ; extra performance management - Suspend(Global_fScriptUpdateFrequencyMonitor.GetValue()) - EndIf - - If NPC && !NPC.Is3DLoaded() - If NPC && TryRemoveMonitorAbility(NPC + ": detached monitor because NPC is not loaded") - Return - EndIf - EndIf - - If NPC && NPC.IsDead() - If NPC && TryRemoveMonitorAbility(NPC + ": detached monitor because NPC is dead") - Return - EndIf - EndIf - - If PlayerRef.IsDead() - If NPC && TryRemoveMonitorAbility(NPC + ": detached monitor because Player is dead") - Return - EndIf - EndIf - - If NPC && (NPC.GetDistance(PlayerRef) > Global_fScriptDistanceMax.GetValue()) - If NPC && TryRemoveMonitorAbility(NPC + ": detached monitor because Player is too far away") - Return - EndIf - EndIf - - If NPC - RegisterForSingleUpdate(Global_fScriptUpdateFrequencyMonitor.GetValue()) - EndIf -EndEvent - - -Event OnHit(ObjectReference akAggressor, Form akSource, Projectile akProjectile, Bool abPowerAttack, Bool abSneakAttack, Bool abBashAttack, Bool abHitBlocked) - If akAggressor != PlayerRef as ObjectReference - Return - EndIf - - If PlayerRef.IsDead() - Return - EndIf - - If NPC && NPC.IsDead() - Return - EndIf - - If NPC && NPC.IsHostileToActor(PlayerRef) - Return - EndIf - - If NPC && NPC.HasMagicEffect(FactionEnemyEffect) - Return - EndIf - - If ExcludedDamageSources.HasForm(akSource) - Return - EndIf - - If !NPC - Return - EndIf - - If NPC - LogInfo(NPC + ": attacked by " + PlayerRef + " with " + akSource) - EndIf - - If NPC - ; StartCombat checks if attacker/target are alive, if attacker is in dialogue, and if attacker/target have processes - ; calls BSTaskPool->QueueStartCombat - how fast NPC starts combat is dependent on task pool - NPC.StartCombat(PlayerRef) - EndIf - - If NPC && FactionEnemyAbility && NPC.AddSpell(FactionEnemyAbility) - LogInfo(NPC + ": attached " + FactionEnemyAbility + " because NPC hit by " + akAggressor) - - If NPC && TryRemoveMonitorAbility(NPC + ": detached monitor because NPC was attacked by " + akAggressor) - Return - EndIf - EndIf -EndEvent - - -Event OnDeath(Actor akKiller) - If NPC && TryRemoveMonitorAbility(NPC + ": detached monitor because NPC was killed by " + akKiller) - Return - EndIf -EndEvent - - -Event OnEffectFinish(Actor akTarget, Actor akCaster) - If NPC && TryRemoveMonitorAbility(NPC + ": detached monitor because effect finished") - Return - EndIf -EndEvent diff --git a/modules/tests/iEquip/dubhPlayerScript.psc b/modules/tests/iEquip/dubhPlayerScript.psc deleted file mode 100644 index fb78447..0000000 --- a/modules/tests/iEquip/dubhPlayerScript.psc +++ /dev/null @@ -1,410 +0,0 @@ -ScriptName dubhPlayerScript Extends ReferenceAlias - -Import dubhUtilityScript - -; ============================================================================= -; PROPERTIES -; ============================================================================= - -GlobalVariable Property Global_iCloakEnabled Auto -GlobalVariable Property Global_iDisguiseEquippedVampire Auto -GlobalVariable Property Global_iDisguiseEssentialSlotBandit Auto -GlobalVariable Property Global_iNotifyEnabled Auto -GlobalVariable Property Global_iPapyrusLoggingEnabled Auto -GlobalVariable Property Global_iTutorialCompleted Auto -GlobalVariable Property Global_iVampireNightOnly Auto -GlobalVariable Property Global_iVampireNightOnlyDayHourBegin Auto -GlobalVariable Property Global_iVampireNightOnlyDayHourEnd Auto - -Actor Property PlayerRef Auto -Spell Property CloakAbility Auto - -; FormLists -FormList Property BaseFactions Auto -FormList Property DisguiseFactionAllies Auto -FormList Property DisguiseFactionEnemies Auto -FormList Property DisguiseFactionFriends Auto -FormList Property DisguiseFactionNeutrals Auto -FormList Property DisguiseFactions Auto -FormList Property DisguiseFormLists Auto -FormList Property DisguiseMessageOff Auto -FormList Property DisguiseMessageOn Auto -FormList Property DisguiseNotifyOff Auto -FormList Property DisguiseNotifyOn Auto - -; Ranges -Int[] Property rgGuardFactions Auto -Int[] Property rgVampireFactions Auto -GlobalVariable[] Property rgDisguisesEnabled Auto - -; Sequences -Message[] Property MessageChain Auto - - -; ============================================================================= -; SCRIPT-LOCAL VARIABLES -; ============================================================================= - -Bool[] FactionStates - -; ============================================================================= -; FUNCTIONS -; ============================================================================= - -Function _Log(String asTextToPrint, Int aiSeverity = 0) - If Global_iPapyrusLoggingEnabled.GetValue() as Bool - Debug.OpenUserLog("MasterOfDisguise") - Debug.TraceUser("MasterOfDisguise", "dubhPlayerScript> " + asTextToPrint, aiSeverity) - EndIf -EndFunction - - -Function LogInfo(String asTextToPrint) - _Log("[INFO] " + asTextToPrint, 0) -EndFunction - - -Function LogWarning(String asTextToPrint) - _Log("[WARN] " + asTextToPrint, 1) -EndFunction - - -Function LogError(String asTextToPrint) - _Log("[ERRO] " + asTextToPrint, 2) -EndFunction - - -Bool Function IsKeySlotEquipped(Int aiFactionIndex) - Form[] rgWornEquipment = LibTurtleClub.GetWornEquipment(PlayerRef, True, True) - - If !rgWornEquipment - LogError("rgWornEquipment was None - cannot get worn equipment for Player") - Return False - EndIf - - If rgWornEquipment.Length == 0 - LogWarning("rgWornEquipment was empty - Player has no worn equipment") - Return False - EndIf - - FormList kCurrentDisguise = DisguiseFormLists.GetAt(aiFactionIndex) as FormList - - If aiFactionIndex == 1 ; Cultists - Return rgWornEquipment[7] && kCurrentDisguise.HasForm(rgWornEquipment[7] as Form) - EndIf - - If aiFactionIndex == 8 ; Silver Hand - Return rgWornEquipment[4] && kCurrentDisguise.HasForm(rgWornEquipment[4] as Form) - EndIf - - If aiFactionIndex == 12 ; Vigil of Stendarr - Return rgWornEquipment[3] && kCurrentDisguise.HasForm(rgWornEquipment[3] as Form) - EndIf - - If aiFactionIndex == 26 ; Windhelm Guard - Return rgWornEquipment[6] && kCurrentDisguise.HasForm(rgWornEquipment[6] as Form) - EndIf - - If aiFactionIndex == 28 ; Daedric Influence - ; When Daedric gear is equipped in ANY slot, that's enough to match. - Bool[] rgDaedricWornForms = LibFire.SearchListForForms(kCurrentDisguise, rgWornEquipment) - - Return rgDaedricWornForms && rgDaedricWornForms.Find(True) > -1 - EndIf - - If aiFactionIndex == 30 ; Bandits - ; The essential slot for Bandits is configurable because this disguise can be disabled. - Int iSlot = Global_iDisguiseEssentialSlotBandit.GetValue() as Int - - If LibMathf.InRange(iSlot, 0, 9) - Return rgWornEquipment[iSlot] && kCurrentDisguise.HasForm(rgWornEquipment[iSlot] as Form) - EndIf - EndIf - - Return rgWornEquipment[1] && kCurrentDisguise.HasForm(rgWornEquipment[1] as Form) -EndFunction - - -Function ShowMessageChain() - If Global_iTutorialCompleted.GetValue() as Int == 1 - Return - EndIf - - Global_iTutorialCompleted.SetValue(1) - - (MessageChain[0] as Message).Show() - (MessageChain[1] as Message).Show() - (MessageChain[2] as Message).Show() -EndFunction - - -Function UpdateFactionRelations(Int aiFactionIndex) - LogInfo("Updating faction relations: aiFactionIndex = " + aiFactionIndex) - - Faction kFaction = DisguiseFactions.GetAt(aiFactionIndex) as Faction - - LibFire.SetAllies(kFaction, DisguiseFactionAllies.GetAt(aiFactionIndex) as FormList) - LibFire.SetEnemies(kFaction, DisguiseFactionEnemies.GetAt(aiFactionIndex) as FormList) - LibFire.SetAllies(kFaction, DisguiseFactionFriends.GetAt(aiFactionIndex) as FormList, True, True) - LibFire.SetEnemies(kFaction, DisguiseFactionNeutrals.GetAt(aiFactionIndex) as FormList, True, True) -EndFunction - - -Function AddDisguise(Int aiFactionIndex) - If FactionStates[aiFactionIndex] - Return - EndIf - - Faction kDisguiseFaction = DisguiseFactions.GetAt(aiFactionIndex) as Faction - - If TryAddToFaction(PlayerRef, kDisguiseFaction) - LogInfo("Added player to disguise faction: aiFactionIndex = " + aiFactionIndex) - - UpdateFactionRelations(aiFactionIndex) - - If IntToBool(Global_iNotifyEnabled) - (DisguiseNotifyOn.GetAt(aiFactionIndex) as Message).Show() - Else - (DisguiseMessageOn.GetAt(aiFactionIndex) as Message).Show() - EndIf - - FactionStates[aiFactionIndex] = True - - ; TODO: if faction is a guard disguise, save bounties to crime gold arrays and clear actual crime gold - ;If Mathf.InRange(aiFactionIndex, 18, 27) - ; save bounties to crime gold arrays - ; clear actual crime gold - ;EndIf - EndIf - - If FactionStates[aiFactionIndex] - ShowMessageChain() - EndIf -EndFunction - - -Function TryAddDisguise(Int aiFactionIndex) - If FactionStates[aiFactionIndex] - Return - EndIf - - ; prevent adding disguise if disabled - If !IntToBool(rgDisguisesEnabled[aiFactionIndex]) - LogWarning("Cannot add disguise because disguise " + aiFactionIndex + " is disabled.") - Return - EndIf - - If PlayerRef.IsInFaction(BaseFactions.GetAt(aiFactionIndex) as Faction) - LogWarning("Cannot add disguise because player is in base faction: aiFactionIndex = " + aiFactionIndex) - Return - EndIf - - ; prevent adding mutually exclusive disguises - If !LibTurtleClub.CanDisguiseActivate(aiFactionIndex, FactionStates) || !IntToBool(rgDisguisesEnabled[aiFactionIndex]) - LogWarning("Cannot activate disguise because disguise " + aiFactionIndex + " is disabled.") - Return - EndIf - - Bool bVampireDisguise = rgVampireFactions.Find(aiFactionIndex) > -1 - Bool bKeySlotEquipped = IsKeySlotEquipped(aiFactionIndex) - - ; for vampire night only feature - If bVampireDisguise - Global_iDisguiseEquippedVampire.SetValue(LibMathf.IfThen(bKeySlotEquipped, aiFactionIndex, 0)) - EndIf - - If bVampireDisguise && IntToBool(Global_iVampireNightOnly) - Float fCurrentHourOfDay = LibFire.GetCurrentHourOfDay() - If LibMathf.InRange(fCurrentHourOfDay, Global_iVampireNightOnlyDayHourBegin.GetValue(), Global_iVampireNightOnlyDayHourEnd.GetValue()) - LogInfo("Vampire disguise can be activated at night only because day/night mode is enabled.") - Return - EndIf - EndIf - - If bKeySlotEquipped && !FactionStates[aiFactionIndex] - AddDisguise(aiFactionIndex) - EndIf -EndFunction - - -Function RemoveDisguise(Int aiFactionIndex) - If !FactionStates[aiFactionIndex] - LogWarning("Cannot remove disguise because player is not in disguise faction: aiFactionIndex = " + aiFactionIndex) - Return - EndIf - - Faction kDisguiseFaction = DisguiseFactions.GetAt(aiFactionIndex) as Faction - - If TryRemoveFromFaction(PlayerRef, kDisguiseFaction) - LogInfo("Removed player from disguise faction: kDisguiseFaction = " + kDisguiseFaction) - - If IntToBool(Global_iNotifyEnabled) - (DisguiseNotifyOff.GetAt(aiFactionIndex) as Message).Show() - Else - (DisguiseMessageOff.GetAt(aiFactionIndex) as Message).Show() - EndIf - - FactionStates[aiFactionIndex] = False - - ; TODO: if faction is a guard disguise, restore bounties and clear crime gold arrays - ;If Mathf.InRange(aiFactionIndex, 18, 27) - ; restore bounties - ; clear crime gold arrays - ;EndIf - EndIf -EndFunction - - -Function TryRemoveDisguise(Int aiFactionIndex) - If !FactionStates[aiFactionIndex] - Return - EndIf - - ; remove disguise if player had disguise equipped and then disabled it - If !IntToBool(rgDisguisesEnabled[aiFactionIndex]) - RemoveDisguise(aiFactionIndex) - LogWarning("Removed disguise because disguise " + aiFactionIndex + " is disabled.") - Return - EndIf - - If PlayerRef.IsInFaction(BaseFactions.GetAt(aiFactionIndex) as Faction) - RemoveDisguise(aiFactionIndex) - LogWarning("Removed disguise because player is in base faction: aiFactionIndex = " + aiFactionIndex) - Return - EndIf - - Bool bVampireDisguise = rgVampireFactions.Find(aiFactionIndex) > -1 - - If bVampireDisguise && IntToBool(Global_iVampireNightOnly) - Float fCurrentHourOfDay = LibFire.GetCurrentHourOfDay() - If LibMathf.InRange(fCurrentHourOfDay, Global_iVampireNightOnlyDayHourBegin.GetValue(), Global_iVampireNightOnlyDayHourEnd.GetValue()) - RemoveDisguise(aiFactionIndex) - LogWarning("Removed vampire disguise because time restrictions are enabled.") - Return - EndIf - EndIf - - If FactionStates[aiFactionIndex] - ; if essential gear is still equipped, do not remove disguise - If IsKeySlotEquipped(aiFactionIndex) - LogInfo("Cannot remove disguise because key slot still equipped: aiFactionIndex = " + aiFactionIndex) - Return - EndIf - - RemoveDisguise(aiFactionIndex) - - ; for vampire night only feature - If bVampireDisguise - Global_iDisguiseEquippedVampire.SetValueInt(aiFactionIndex) - EndIf - EndIf -EndFunction - - -Function UpdateDisguise(Int aiFactionIndex) ; used in event scope - TryRemoveDisguise(aiFactionIndex) - TryAddDisguise(aiFactionIndex) -EndFunction - - -Function TryUpdateDisguise(Form akBaseObject) ; used in event scope - ; Attempts to update disguise and base faction memberships - - Int iCycles = 0 - While Utility.IsInMenuMode() || PlayerRef.IsInCombat() - iCycles += 1 - EndWhile - - Bool[] rgPossibleDisguises = LibFire.SearchListsForForm(DisguiseFormLists, akBaseObject) - - If rgPossibleDisguises.Find(True) < 0 - LogWarning("Cannot determine possible disguises for form: " + akBaseObject) - Return - EndIf - - Int i = 0 - - While i < rgPossibleDisguises.Length - If rgPossibleDisguises[i] - UpdateDisguise(i) - EndIf - - i += 1 - EndWhile -EndFunction - - -; ============================================================================= -; EVENTS -; ============================================================================= - -Event OnInit() - RegisterForSingleUpdate(1.0) -EndEvent - - -Event OnPlayerLoadGame() - RegisterForSingleUpdate(1.0) -EndEvent - - -Event OnCellLoad() - RegisterForSingleUpdate(1.0) -EndEvent - - -Event OnUpdate() - If !PlayerRef.IsInCombat() - If Global_iCloakEnabled.GetValue() as Bool - If !PlayerRef.HasSpell(CloakAbility) - PlayerRef.AddSpell(CloakAbility, False) - Utility.Wait(1.0) - PlayerRef.RemoveSpell(CloakAbility) - EndIf - EndIf - - ; for vampire night only feature - ; try to add vampire disguise, needed for day/night cycle - Int iFactionIndex = Global_iDisguiseEquippedVampire.GetValue() as Int - - If rgVampireFactions.Find(iFactionIndex) > -1 - UpdateDisguise(iFactionIndex) - EndIf - EndIf - - RegisterForSingleUpdate(4.0) -EndEvent - - -Event OnObjectEquipped(Form akBaseObject, ObjectReference akReference) - Int _cycles = 0 - - While Utility.IsInMenuMode() || PlayerRef.IsInCombat() - _cycles += 1 - EndWhile - - Utility.Wait(1.0) - - If akBaseObject - FactionStates = LibTurtleClub.GetFactionStates(PlayerRef, DisguiseFactions) - - LogInfo("Trying to update disguise because the player equipped: " + akBaseObject) - TryUpdateDisguise(akBaseObject) - EndIf -EndEvent - - -Event OnObjectUnequipped(Form akBaseObject, ObjectReference akReference) - Int _cycles = 0 - - While Utility.IsInMenuMode() || PlayerRef.IsInCombat() - _cycles += 1 - EndWhile - - If akBaseObject - FactionStates = LibTurtleClub.GetFactionStates(PlayerRef, DisguiseFactions) - - LogInfo("Trying to update disguise because the player unequipped: " + akBaseObject) - TryUpdateDisguise(akBaseObject) - EndIf -EndEvent diff --git a/modules/tests/iEquip/dubhUtilityScript.psc b/modules/tests/iEquip/dubhUtilityScript.psc deleted file mode 100644 index 2376ae2..0000000 --- a/modules/tests/iEquip/dubhUtilityScript.psc +++ /dev/null @@ -1,102 +0,0 @@ -ScriptName dubhUtilityScript - - -Bool Function TryAddToFaction(Actor akActor, Faction akFaction) Global - If !akActor.IsInFaction(akFaction) - akActor.AddToFaction(akFaction) - Return akActor.IsInFaction(akFaction) - EndIf - Return False -EndFunction - - -Bool Function TryRemoveFromFaction(Actor akActor, Faction akFaction) Global - If akActor.IsInFaction(akFaction) - akActor.RemoveFromFaction(akFaction) - Return !akActor.IsInFaction(akFaction) - EndIf - Return False -EndFunction - -; ============================================================================= -; Used in: -; - dubhMonitorEffectScript -; ============================================================================= - -Float Function GetBestSkill(Actor akActor) Global - ; Gets the actor's best skill, either Sneak or Illusion, and returns the weight - ; of the best skill on the chance to remain undetected - ; Ex: fDetectionWeight += GetBestSkillWeight(PlayerRef) - - Float fSneakValue = akActor.GetActorValue("Sneak") - Float fIllusionValue = akActor.GetActorValue("Illusion") - Float fSpeechValue = akActor.GetActorValue("Speechcraft") - - Return LibMathf.Max(fSneakValue, LibMathf.Max(fIllusionValue, fSpeechValue)) -EndFunction - - -Int Function GetFovType(Float afHeadingAngle, Float afMaxHeadingAngle) Global - ; Returns type of field of view (clear, distorted, peripheral) - - ; When fDetectionViewCone == 190.0, fClearAngleMax = 15 degrees - Float fClearAngleMax = afMaxHeadingAngle / (190.0 / 15.0) - - If LibMathf.InRange(afHeadingAngle, -fClearAngleMax, fClearAngleMax) - Return 1 - EndIf - - ; When fDetectionViewCone == 190.0, fDistortedAngleMax = 30 degrees - Float fDistortedAngleMax = fClearAngleMax * 2.0 - - If LibMathf.InRange(afHeadingAngle, -fDistortedAngleMax, fDistortedAngleMax) - Return 2 - EndIf - - ; When fDetectionViewCone == 190.0, fPeripheralAngleMax = 60 degrees - Float fPeripheralAngleMax = fDistortedAngleMax * 2.0 - - If LibMathf.InRange(afHeadingAngle, -fPeripheralAngleMax, fPeripheralAngleMax) - Return 3 - EndIf - - Return 0 -EndFunction - - -Int Function GetLosType(Float afDistanceToPlayer, Float afMaxDistanceToPlayer) Global - ; Returns type of line of sight (near, mid, far) - - ; When afMaxDistanceToPlayer == 2048, fNearDistanceMax = 512 - Float fNearDistanceMax = afMaxDistanceToPlayer / 4.0 - - If LibMathf.InRange(afDistanceToPlayer, 0.0, fNearDistanceMax) - Return 1 - EndIf - - ; When afMaxDistanceToPlayer == 2048, fMidDistanceMax = 1024 - Float fMidDistanceMax = afMaxDistanceToPlayer / 2.0 - - If LibMathf.InRange(afDistanceToPlayer, fNearDistanceMax, fMidDistanceMax) - Return 2 - EndIf - - If LibMathf.InRange(afDistanceToPlayer, fMidDistanceMax, afMaxDistanceToPlayer) - Return 3 - EndIf - - Return 0 -EndFunction - - -Function Suspend(Float afSeconds) Global - Float fGoal = Utility.GetCurrentRealTime() + afSeconds - - While (Utility.GetCurrentRealTime() < fGoal) - Utility.Wait(1.0) - EndWhile -EndFunction - -Bool Function IntToBool(GlobalVariable AGlobalVariable) Global - Return AGlobalVariable.GetValue() as Int == 1 -EndFunction diff --git a/modules/tests/iequip_test.v b/modules/tests/iequip_test.v deleted file mode 100644 index 26909d6..0000000 --- a/modules/tests/iequip_test.v +++ /dev/null @@ -1,34 +0,0 @@ -module tests - -import os -import pref -import builder - -fn test_selective_headers_loading() { - input_dir := os.real_path(os.join_path("modules", "tests", "iEquip")) - output_dir := os.real_path(os.join_path("test-files", "compiled")) - header_dir := os.real_path(os.join_path("modules", "tests", "psc_deps")) - - if !os.is_dir(input_dir) || !os.is_file(os.join_path(input_dir, "dubhMonitorEffectScript.psc")) { - assert false, "invalid input dir ${input_dir}" - } - - if !os.is_dir(header_dir) || !os.is_file(os.join_path(header_dir, "Form.psc")) { - assert false, "invalid header dir ${header_dir}" - } - - if !os.is_dir(output_dir) { - os.mkdir(output_dir, os.MkdirParams{}) or { assert false, "failed to create output folder" } - } - - prefs := pref.Preferences { - paths: [ input_dir ] - output_dir: output_dir - mode: .compile - backend: .check - no_cache: true - header_dirs: [ header_dir ] - } - - builder.compile(&prefs) -} \ No newline at end of file diff --git a/modules/tests/pex_read_write_test.v b/modules/tests/pex_read_write_test.v index 6b21056..b7bfa2b 100644 --- a/modules/tests/pex_read_write_test.v +++ b/modules/tests/pex_read_write_test.v @@ -23,6 +23,7 @@ fn test_build() { mode: .compile backend: .pex no_cache: true + output_mode: .silent } mut table := ast.new_table() mut global_scope := &ast.Scope{} diff --git a/modules/tests/pex_stmt_test.v b/modules/tests/pex_stmt_test.v index 31a5b32..f178221 100644 --- a/modules/tests/pex_stmt_test.v +++ b/modules/tests/pex_stmt_test.v @@ -10,6 +10,7 @@ const prefs = pref.Preferences { mode: .compile backend: .pex no_cache: true + output_mode: .silent } const other_src = @@ -142,7 +143,7 @@ fn compile(src string) &pex.PexFile { } fn get_instructions(pex_file &pex.PexFile) []pex.Instruction { - func := pex_file.get_function_from_empty_state("ABCD", "Bar") or { panic("function not found") } + func := pex_file.get_function_from_empty_state("ABCD", "Bar") or { assert false, "function not found"; panic("function not found") } $if false { println("") @@ -167,8 +168,8 @@ fn test_state_decl_1() { pex_file := compile_top('State MyTestState1 EndState') - obj := pex_file.get_object("ABCD") or { panic("object not found") } - state := pex_file.get_state(obj, "MyTestState1") or { panic("state not found") } + obj := pex_file.get_object("ABCD") or { assert false, "object not found"; panic("object not found") } + state := pex_file.get_state(obj, "MyTestState1") or { assert false, "state not found"; panic("state not found") } assert pex_file.get_string(state.name) == "MyTestState1" assert state.functions.len == 0 @@ -206,8 +207,8 @@ fn test_state_decl_2() { EndFunction EndState') - obj := pex_file.get_object("ABCD") or { panic("object not found") } - state := pex_file.get_state(obj, "MyTestState2") or { panic("state not found") } + obj := pex_file.get_object("ABCD") or { assert false, "object not found"; panic("object not found") } + state := pex_file.get_state(obj, "MyTestState2") or { assert false, "state not found"; panic("state not found") } assert pex_file.get_string(state.name) == "MyTestState2" assert state.functions.len == 1 @@ -267,10 +268,10 @@ fn test_state_decl_3() { pex_file := compile_top('') - obj := pex_file.get_object("ABCD") or { panic("object not found") } + obj := pex_file.get_object("ABCD") or { assert false, "object not found"; panic("object not found") } assert pex_file.get_string(obj.auto_state_name) == "MyAutoState" - state := pex_file.get_state(obj, "MyAutoState") or { panic("state not found") } + state := pex_file.get_state(obj, "MyAutoState") or { assert false, "state not found"; panic("state not found") } assert pex_file.get_string(state.name) == "MyAutoState" assert state.functions.len == 1 @@ -302,11 +303,11 @@ fn test_state_decl_4() { Function ReadyStateFn3() EndFunction') - obj := pex_file.get_object("ABCD") or { panic("object not found") } + obj := pex_file.get_object("ABCD") or { assert false, "object not found"; panic("object not found") } assert pex_file.get_string(obj.auto_state_name) == "MyAutoState" assert obj.states.len == 5 - state := pex_file.get_state(obj, "ready") or { panic("state not found") } + state := pex_file.get_state(obj, "ready") or { assert false, "state not found"; panic("state not found") } assert pex_file.get_string(state.name) == "ready" assert state.functions.len == 3 @@ -318,7 +319,7 @@ fn test_state_decl_4() { fn test_object_var_decl_1() { pex_file := compile_top('ABCD myTestObjectVar') - var := pex_file.get_var("ABCD", "myTestObjectVar") or { panic("object variable not found") } + var := pex_file.get_var("ABCD", "myTestObjectVar") or { assert false, "object variable not found"; panic("object variable not found") } assert pex_file.get_string(var.name) == "myTestObjectVar" assert pex_file.get_string(var.type_name) == "ABCD" @@ -327,7 +328,7 @@ fn test_object_var_decl_1() { fn test_object_var_decl_2() { pex_file := compile_top('int myTestObjectVar2 = 10') - var := pex_file.get_var("ABCD", "myTestObjectVar2") or { panic("object variable not found") } + var := pex_file.get_var("ABCD", "myTestObjectVar2") or { assert false, "object variable not found"; panic("object variable not found") } assert pex_file.get_string(var.name) == "myTestObjectVar2" assert pex_file.get_string(var.type_name) == "Int" @@ -338,7 +339,7 @@ fn test_object_var_decl_2() { fn test_object_var_decl_3() { pex_file := compile_top('ABCD[] myTestObjectVar3') - var := pex_file.get_var("ABCD", "myTestObjectVar3") or { panic("object variable not found") } + var := pex_file.get_var("ABCD", "myTestObjectVar3") or { assert false, "object variable not found"; panic("object variable not found") } assert pex_file.get_string(var.name) == "myTestObjectVar3" assert pex_file.get_string(var.type_name) == "ABCD[]" @@ -348,7 +349,7 @@ fn test_object_var_decl_3() { fn test_object_var_decl_4() { pex_file := compile_top('bool waiting') - var := pex_file.get_var("ABCD", "waiting") or { panic("object variable not found") } + var := pex_file.get_var("ABCD", "waiting") or { assert false, "object variable not found"; panic("object variable not found") } assert pex_file.get_string(var.name) == "waiting" assert pex_file.get_string(var.type_name) == "Bool" @@ -358,7 +359,7 @@ fn test_object_var_decl_4() { fn test_object_var_decl_5() { pex_file := compile_top('int waiting') - var := pex_file.get_var("ABCD", "waiting") or { panic("object variable not found") } + var := pex_file.get_var("ABCD", "waiting") or { assert false, "object variable not found"; panic("object variable not found") } assert pex_file.get_string(var.name) == "waiting" assert pex_file.get_string(var.type_name) == "Int" @@ -366,21 +367,19 @@ fn test_object_var_decl_5() { } fn test_object_var_decl_6() { - pex_file := compile_top('ABCD objVarTest = None') - - var := pex_file.get_var("ABCD", "objVarTest") or { panic("object variable not found") } + pex_file := compile_top('ABCD objVarTest11111 = None') + var := pex_file.get_var("ABCD", "objVarTest11111") or { assert false, "object variable not found"; panic("object variable not found") } - assert pex_file.get_string(var.name) == "objVarTest" + assert pex_file.get_string(var.name) == "objVarTest11111" assert pex_file.get_string(var.type_name) == "ABCD" assert var.data.typ == .null } fn test_object_var_decl_7() { - pex_file := compile_top('ABCD[] objVarTest = None') + pex_file := compile_top('ABCD[] objVarTest22222 = None') + var := pex_file.get_var("ABCD", "objVarTest22222") or { assert false, "object variable not found"; panic("object variable not found") } - var := pex_file.get_var("ABCD", "objVarTest") or { panic("object variable not found") } - - assert pex_file.get_string(var.name) == "objVarTest" + assert pex_file.get_string(var.name) == "objVarTest22222" assert pex_file.get_string(var.type_name) == "ABCD[]" assert var.data.typ == .null } @@ -430,7 +429,7 @@ fn test_property_decl_1() { // auto var name: '::Hello_var' mut pex_file := compile_top('string Property Hello = "Hello world!" Auto') - mut prop := pex_file.get_property("ABCD", "Hello") or { panic("property not found") } + mut prop := pex_file.get_property("ABCD", "Hello") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello" @@ -442,10 +441,7 @@ fn test_property_decl_1() { assert prop.is_autovar() assert pex_file.get_string(prop.auto_var_name) == "::Hello_var" - mut var := pex_file.get_var("ABCD", "::Hello_var") or { - assert false, "variable not found" - panic("variable not found") - } + mut var := pex_file.get_var("ABCD", "::Hello_var") or { assert false, "variable not found"; panic("variable not found") } assert pex_file.get_string(var.name) == "::Hello_var" assert pex_file.get_string(var.type_name).to_lower() == "string" assert var.user_flags == 0 @@ -473,7 +469,7 @@ fn test_property_decl_2() { // opcode: 'ret', args: [string('Hello world!')] pex_file := compile_top('string Property Hello2 = "Hello world2!" AutoReadOnly') - prop := pex_file.get_property("ABCD", "Hello2") or { panic("property not found") } + prop := pex_file.get_property("ABCD", "Hello2") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello2" @@ -505,7 +501,7 @@ fn test_property_decl_3() { // auto var name: '::Hello3_var' pex_file := compile_top('string Property Hello3 = "Hello world3!" Auto Hidden') - prop := pex_file.get_property("ABCD", "Hello3") or { panic("property not found") } + prop := pex_file.get_property("ABCD", "Hello3") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello3" @@ -519,10 +515,7 @@ fn test_property_decl_3() { assert pex_file.get_string(prop.auto_var_name) == "::Hello3_var" //var - var := pex_file.get_var("ABCD", "::Hello3_var") or { - assert false, "variable not found" - panic("variable not found") - } + var := pex_file.get_var("ABCD", "::Hello3_var") or { assert false, "variable not found"; panic("variable not found") } assert pex_file.get_string(var.name) == "::Hello3_var" assert pex_file.get_string(var.type_name).to_lower() == "string" assert var.user_flags == 0 @@ -541,7 +534,7 @@ fn test_property_decl_4() { // auto var name: '::Hello5_var' pex_file := compile_top('string Property Hello5 = "Hello world5!" Auto Conditional') - prop := pex_file.get_property("ABCD", "Hello5") or { panic("property not found") } + prop := pex_file.get_property("ABCD", "Hello5") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello5" @@ -554,10 +547,7 @@ fn test_property_decl_4() { assert pex_file.get_string(prop.auto_var_name) == "::Hello5_var" //var - var := pex_file.get_var("ABCD", "::Hello5_var") or { - assert false, "variable not found" - panic("variable not found") - } + var := pex_file.get_var("ABCD", "::Hello5_var") or { assert false, "variable not found"; panic("variable not found") } assert pex_file.get_string(var.name) == "::Hello5_var" assert pex_file.get_string(var.type_name).to_lower() == "string" assert var.user_flags == 0b0010 @@ -612,7 +602,7 @@ fn test_property_decl_5() { return myValue EndFunction EndProperty') - prop := pex_file.get_property("ABCD", "Hello6") or { panic("property not found") } + prop := pex_file.get_property("ABCD", "Hello6") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello6" @@ -676,7 +666,7 @@ fn test_property_decl_6() { myValue = value EndFunction EndProperty') - prop := pex_file.get_property("ABCD", "Hello7") or { panic("property not found") } + prop := pex_file.get_property("ABCD", "Hello7") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello7" @@ -728,7 +718,7 @@ fn test_property_decl_7() { return myValue EndFunction EndProperty') - prop := pex_file.get_property("ABCD", "Hello8") or { panic("property not found") } + prop := pex_file.get_property("ABCD", "Hello8") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello8" @@ -750,7 +740,7 @@ fn test_property_decl_7() { fn test_property_decl_8() { mut pex_file := compile_top('int Property Hello Auto') - mut prop := pex_file.get_property("ABCD", "Hello") or { panic("property not found") } + mut prop := pex_file.get_property("ABCD", "Hello") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello" @@ -762,10 +752,7 @@ fn test_property_decl_8() { assert prop.is_autovar() assert pex_file.get_string(prop.auto_var_name) == "::Hello_var" - mut var := pex_file.get_var("ABCD", "::Hello_var") or { - assert false, "variable not found" - panic("variable not found") - } + mut var := pex_file.get_var("ABCD", "::Hello_var") or { assert false, "variable not found"; panic("variable not found") } assert pex_file.get_string(var.name) == "::Hello_var" assert pex_file.get_string(var.type_name).to_lower() == "int" assert var.user_flags == 0 @@ -774,7 +761,7 @@ fn test_property_decl_8() { fn test_property_decl_9() { mut pex_file := compile_top('ABCD Property Hello = None Auto') - mut prop := pex_file.get_property("ABCD", "Hello") or { panic("property not found") } + mut prop := pex_file.get_property("ABCD", "Hello") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello" @@ -786,10 +773,7 @@ fn test_property_decl_9() { assert prop.is_autovar() assert pex_file.get_string(prop.auto_var_name) == "::Hello_var" - mut var := pex_file.get_var("ABCD", "::Hello_var") or { - assert false, "variable not found" - panic("variable not found") - } + mut var := pex_file.get_var("ABCD", "::Hello_var") or { assert false, "variable not found"; panic("variable not found") } assert pex_file.get_string(var.name) == "::Hello_var" assert pex_file.get_string(var.type_name).to_lower() == "abcd" assert var.user_flags == 0 @@ -798,7 +782,7 @@ fn test_property_decl_9() { fn test_property_decl_10() { mut pex_file := compile_top('ABCD[] Property Hello = None Auto') - mut prop := pex_file.get_property("ABCD", "Hello") or { panic("property not found") } + mut prop := pex_file.get_property("ABCD", "Hello") or { assert false, "property not found"; panic("property not found") } //prop assert pex_file.get_string(prop.name) == "Hello" @@ -810,10 +794,7 @@ fn test_property_decl_10() { assert prop.is_autovar() assert pex_file.get_string(prop.auto_var_name) == "::Hello_var" - mut var := pex_file.get_var("ABCD", "::Hello_var") or { - assert false, "variable not found" - panic("variable not found") - } + mut var := pex_file.get_var("ABCD", "::Hello_var") or { assert false, "variable not found"; panic("variable not found") } assert pex_file.get_string(var.name) == "::Hello_var" assert pex_file.get_string(var.type_name).to_lower() == "abcd[]" assert var.user_flags == 0 @@ -1662,7 +1643,8 @@ fn test_call_cast() { "opcode: 'callmethod', args: [ident(FuncWithOptionalObjArg), ident(self), ident(::NoneVar), integer(1), ident(obj)]" "opcode: 'cast', args: [ident(::temp2), none]" "opcode: 'callmethod', args: [ident(FuncWithOptionalObjArg), ident(self), ident(::NoneVar), integer(1), ident(::temp2)]" - "opcode: 'callmethod', args: [ident(FuncWithOptionalObjArg), ident(self), ident(::NoneVar), integer(1), none]" + "opcode: 'cast', args: [ident(::temp2), none]" + "opcode: 'callmethod', args: [ident(FuncWithOptionalObjArg), ident(self), ident(::NoneVar), integer(1), ident(::temp2)]" ] assert ins.len == expected.len diff --git a/modules/tests/projects_test.v b/modules/tests/projects_test.v new file mode 100644 index 0000000..1e5135b --- /dev/null +++ b/modules/tests/projects_test.v @@ -0,0 +1,309 @@ +module tests + +import os +import pref +import builder + +fn get_prefs(input_dir string, header_dirs []string, output_dir string) pref.Preferences { + return pref.Preferences { + paths: [ input_dir ] + output_dir: output_dir + mode: .compile + backend: .check + no_cache: true + output_mode: .silent + header_dirs: header_dirs + } +} + +fn get_source_dir(dir_name string, required_file_name string) string { + // First try with the new submodule structure + mut path := os.abs_path(os.join_path("modules", "tests", "sources", dir_name)) + mut required_file := os.join_path(path, required_file_name) + + // If not found, try original structure (for backward compatibility) + if !os.is_dir(path) || !os.is_file(required_file) { + // For psc_deps specifically, check if it exists directly under sources + if dir_name == "psc_deps" { + path = os.abs_path(os.join_path("modules", "tests", "sources", "psc_deps")) + required_file = os.join_path(path, required_file_name) + if os.is_dir(path) && os.is_file(required_file) { + return path + } + } + + // Check the old path as a fallback + path = os.abs_path(os.join_path("modules", "tests", dir_name)) + required_file = os.join_path(path, required_file_name) + if os.is_dir(path) && os.is_file(required_file) { + return path + } + + assert false, "[get_source_dir] invalid directory ${path} or missing required file ${required_file}" + } + + return path +} + +fn get_output_dir(dir_name string) string { + path := os.abs_path(os.join_path("test-files", "compiled", "__project_test_" + dir_name)) + + if !os.is_dir(path) { + os.mkdir_all(path, os.MkdirParams{}) or { assert false, "[get_output_dir] failed to create output folder ${path}; error: ${err}" } + } + + if !os.is_dir(path) { + assert false, "[get_output_dir] invalid output directory ${path}" + } + + return path +} + +const skyrim_deps = get_source_dir("psc_deps", "Form.psc") +const skyui_sdk_51 = get_source_dir("SkyuiSDK_v5.1", "SKI_ConfigBase.psc") +const skyui_sdk_52 = get_source_dir("SkyuiSDK_v5.2", "SKI_ConfigBase.psc") +const mcm_helper = get_source_dir("MCMHelper", "MCM_ConfigBase.psc") +const lovense_api = get_source_dir("LovenseAPI", "Lovense.psc") +const fnis = get_source_dir("FNIS", "fnis.psc") +const mfgfix = get_source_dir("MfgFix", "MfgFix_Settings.psc") +const libfire = get_source_dir("LibFire", "LibFire.psc") +const libturtleclub = get_source_dir("LibTurtleClub", "LibTurtleClub.psc") +const papyrus_util = get_source_dir("PapyrusUtil", "PapyrusUtil.psc") +const console_util = get_source_dir("ConsoleUtil", "ConsoleUtil.psc") +const ni_override = get_source_dir("NiOverride", "NiOverride.psc") +const race_menu = get_source_dir("RaceMenu", "racemenu.psc") +const ui_extensions = get_source_dir("UIExtensions", "UIExtensions.psc") +const lib_mathf = get_source_dir("LibMathf", "LibMathf.psc") +const jcontainers = get_source_dir("JContainers", "JContainers.psc") +const iequip = get_source_dir("iEquip", "dubhMonitorEffectScript.psc") +const mantella_spell = get_source_dir("MantellaSpell", "MantellaLauncher.psc") +const master_of_disguise = get_source_dir("MasterOfDisguise", "dubhDisguiseMCMQuestScript.psc") +const osa = get_source_dir("OSA", "OSA.psc") +const ostim = get_source_dir("OStimNG", "OStimAddon.psc") +const sexlab = get_source_dir("SexLab", "SexLabFramework.psc") +const requiem = get_source_dir("Requiem", "Req_VampireDustScript.psc") +const ussep = get_source_dir("USSEP", "ussep_clearaliasonactivate.psc") + +fn test_project_skyrim_deps_sources() { + prefs := get_prefs(skyrim_deps, [], get_output_dir("SkyrimDeps")) + + builder.compile(&prefs) +} + +fn test_project_skyui_sdk_51() { + prefs := get_prefs(skyui_sdk_51, [ + skyrim_deps + ], get_output_dir("SkyuiSDK51")) + + builder.compile(&prefs) +} + +fn test_project_skyui_sdk_52() { + prefs := get_prefs(skyui_sdk_52, [ + skyrim_deps + ], get_output_dir("SkyuiSDK52")) + + builder.compile(&prefs) +} + +fn test_project_mcm_helper() { + prefs := get_prefs(mcm_helper, [ + skyrim_deps, + skyui_sdk_52 + ], get_output_dir("MCMHelper")) + + builder.compile(&prefs) +} + +fn test_project_lovense_api() { + prefs := get_prefs(lovense_api, [ + skyrim_deps + ], get_output_dir("LovenseAPI")) + + builder.compile(&prefs) +} + +fn test_project_fnis() +{ + prefs := get_prefs(fnis, [ + skyrim_deps + ], get_output_dir("FNIS")) + + builder.compile(&prefs) +} + +fn test_project_mfgfix() +{ + prefs := get_prefs(mfgfix, [ + skyrim_deps + ], get_output_dir("MfgFix")) + + builder.compile(&prefs) +} + +fn test_project_libfire() { + prefs := get_prefs(libfire, [ + skyrim_deps + ], get_output_dir("LibFire")) + + builder.compile(&prefs) +} + +fn test_project_libturtleclub() { + prefs := get_prefs(libturtleclub, [ + skyrim_deps + ], get_output_dir("LibTurtleClub")) + + builder.compile(&prefs) +} + +fn test_project_papyrus_util() { + prefs := get_prefs(papyrus_util, [ + skyrim_deps + ], get_output_dir("PapyrusUtil")) + + builder.compile(&prefs) +} + +fn test_project_console_util() { + prefs := get_prefs(console_util, [ + skyrim_deps + ], get_output_dir("ConsoleUtil")) + + builder.compile(&prefs) +} + +fn test_project_ni_override() { + prefs := get_prefs(ni_override, [ + skyrim_deps + ], get_output_dir("NiOverride")) + + builder.compile(&prefs) +} + +fn test_project_race_menu() { + prefs := get_prefs(race_menu, [ + skyrim_deps, + ni_override + ], get_output_dir("RaceMenu")) + + builder.compile(&prefs) +} + +fn test_project_ui_extensions() { + prefs := get_prefs(ui_extensions, [ + skyrim_deps, + ni_override, + race_menu + ], get_output_dir("UIExtensions")) + + builder.compile(&prefs) +} + +fn test_project_lib_mathf() { + prefs := get_prefs(lib_mathf, [ + skyrim_deps + ], get_output_dir("LibMathf")) + + builder.compile(&prefs) +} + +fn test_project_jcontainers() { + prefs := get_prefs(jcontainers, [ + skyrim_deps + ], get_output_dir("JContainers")) + + builder.compile(&prefs) +} + +fn test_project_iequip() { + prefs := get_prefs(iequip, [ + skyrim_deps, + skyui_sdk_52, + libturtleclub, + lib_mathf, + libfire + ], get_output_dir("iEquip")) + + builder.compile(&prefs) +} + +fn test_project_mantella_spell() { + prefs := get_prefs(mantella_spell, [ + skyrim_deps, + ui_extensions, + skyui_sdk_51 + ], get_output_dir("MantellaSpell")) + + builder.compile(&prefs) +} + +fn test_project_master_of_disguise() { + prefs := get_prefs(master_of_disguise, [ + skyrim_deps, + libfire, + libturtleclub, + skyui_sdk_51, + lib_mathf + ], get_output_dir("MasterOfDisguise")) + + builder.compile(&prefs) +} + +fn test_project_osa() { + prefs := get_prefs(osa, [ + skyrim_deps, + skyui_sdk_52, + papyrus_util + ], get_output_dir("OSA")) + + builder.compile(&prefs) +} + +fn test_project_ostim() { + prefs := get_prefs(ostim, [ + skyrim_deps, + ui_extensions, + papyrus_util, + ni_override, + jcontainers, + skyui_sdk_51, + console_util + ], get_output_dir("OStim")) + + builder.compile(&prefs) +} + +fn test_project_sexlab(){ + prefs := get_prefs(sexlab, [ + skyrim_deps, + ni_override, + mfgfix, + skyui_sdk_51, + lovense_api, + fnis, + papyrus_util + ], get_output_dir("SexLab")) + + builder.compile(&prefs) +} + +fn test_project_requiem(){ + prefs := get_prefs(requiem, [ + skyrim_deps, + ussep, + skyui_sdk_51 + ], get_output_dir("Requiem")) + + builder.compile(&prefs) +} + +fn test_project_ussep(){ + prefs := get_prefs(ussep, [ + skyrim_deps + ], get_output_dir("USSEP")) + + builder.compile(&prefs) +} + + diff --git a/modules/tests/psc_deps/ActiveMagicEffect.psc b/modules/tests/psc_deps/ActiveMagicEffect.psc deleted file mode 100644 index 9267041..0000000 --- a/modules/tests/psc_deps/ActiveMagicEffect.psc +++ /dev/null @@ -1,433 +0,0 @@ -Scriptname ActiveMagicEffect Hidden - -; Add an inventory event filter to this effect. Item added/removed events matching the -; specified form (or in the specified form list) will now be let through. -Function AddInventoryEventFilter(Form akFilter) native - -; Dispel this effect -Function Dispel() native - -; Get the base MagicEffect this active effect is using -MagicEffect Function GetBaseObject() native - -; Get the actor that cast this spell -Actor Function GetCasterActor() native - -; Get the actor this spell is targeting (is attached to) -Actor Function GetTargetActor() native - -; Register for the specified animation event from the specified object - returns true if it successfully registered -bool Function RegisterForAnimationEvent(ObjectReference akSender, string asEventName) native - -; Register for LOS gain and lost events between the viewer and the target -; A loss or gain event will be sent immediately, depending on whether or not the viewer is already looking at the target or not -; If the viewer is not the player, the target must be another actor -Function RegisterForLOS(Actor akViewer, ObjectReference akTarget) native - -; Register for only the first LOS gain event between the viewer and the target -; If the viewer is already looking at the target, an event will be received almost immediately -; If the viewer is not the player, the target must be another actor -Function RegisterForSingleLOSGain(Actor akViewer, ObjectReference akTarget) native - -; Register for only the first LOS lost event between the viewer and the target -; If the viewer is already not looking at the target, an event will be received almost immediately -; If the viewer is not the player, the target must be another actor -Function RegisterForSingleLOSLost(Actor akViewer, ObjectReference akTarget) native - -; Register for a single OnUpdate event, in afInterval seconds. All scripts attached to this magic effect will get the update events -; Of course, this means you don't need to call UnregisterForUpdate() -; If you find yourself doing this: -; Event OnUpdate() -; UnregisterForUpdate() -; {Do some stuff} -; endEvent -; Then you should use RegisterForSingleUpdate instead -Function RegisterForSingleUpdate(float afInterval) native - -; Registers this magic effect to receive events when the player sleeps and wakes up -Function RegisterForSleep() native - -; Registers this alias to receive events when tracked stats are updated -Function RegisterForTrackedStatsEvent() native - -; Register for OnUpdate events, every X seconds, where X is the interval. All scripts attached to this magic effect will get the update events -Function RegisterForUpdate(float afInterval) native - -; Register for OnUpdateGameTime events, every X hours of game time, where X is the interval. All scripts attached to this magic effect will get the update events -Function RegisterForUpdateGameTime(float afInterval) native - -; Register for a single OnUpdateGameTime event, in afInterval hours of game time. All scripts attached to this magic effect will get the update events -Function RegisterForSingleUpdateGameTime(float afInterval) native - -; Remove all inventory event filters from this effect - all item added/removed events will now be received -Function RemoveAllInventoryEventFilters() native - -; Remove an inventory event filter from this effect. Item added/removed events matching the -; specified form (or in the specified form list) will no longer be let through. -Function RemoveInventoryEventFilter(Form akFilter) native - -; Turns on profiling for this specific object and all scripts attached to it - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StartObjectProfiling() native - -; Turns off profiling for this specific object and all scripts attached to it - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StopObjectProfiling() native - -; Unregister for any LOS events between the viewer and target -Function UnregisterForLOS(Actor akViewer, ObjectReference akTarget) native - -; Unregister for the specified animation event from the specified object -Function UnregisterForAnimationEvent(ObjectReference akSender, string asEventName) native - -; Unregisters this magic effect to receive events when the player sleeps and wakes up -Function UnregisterForSleep() native - -; Unregisters this magic effect from receiving events when tracked stats are updated -Function UnregisterForTrackedStatsEvent() native - -; Unregister for OnUpdate events, all attached scripts will stop getting update events -Function UnregisterForUpdate() native - -; Unregister for OnUpdateGameTime events, all attached scripts will stop getting update game time events -Function UnregisterForUpdateGameTime() native - -; Animation event, sent when an object we are listening to hits one of the events we are listening for -Event OnAnimationEvent(ObjectReference akSource, string asEventName) -EndEvent - -; Event sent when you have been unregistered from receiving an animation event because the target -; object's animation graph has been unloaded -Event OnAnimationEventUnregistered(ObjectReference akSource, string asEventName) -EndEvent - -; Event received when this effect is first started (OnInit may not have been run yet!) -Event OnEffectStart(Actor akTarget, Actor akCaster) -EndEvent - -; Event received when this effect is finished (effect may already be deleted, calling -; functions on this effect will fail) -Event OnEffectFinish(Actor akTarget, Actor akCaster) -EndEvent - -; LOS event, sent whenever the viewer first sees the target (after registering) -Event OnGainLOS(Actor akViewer, ObjectReference akTarget) -EndEvent - -; Lost LOS event, sent whenever the viewer first loses sight of the target (after registering) -Event OnLostLOS(Actor akViewer, ObjectReference akTarget) -EndEvent - -; Received when the player sleeps. Start and desired end time are in game time days (after registering) -Event OnSleepStart(float afSleepStartTime, float afDesiredSleepEndTime) -EndEvent - -; Received when the player stops sleeping - whether naturally or interrupted (after registering) -Event OnSleepStop(bool abInterrupted) -EndEvent - -; Event received when a tracked stat is updated for the player -Event OnTrackedStatsEvent(string arStatName, int aiStatValue) -EndEvent - -; Update event, sent every X seconds while this magic effect is registered for them -Event OnUpdate() -EndEvent - -; Update event, sent every X hours of game time while this magic effect is registered for them -Event OnUpdateGameTime() -EndEvent - -; The following events are received from the actor this effect is attached to: - -; Event received when this reference is activated -Event OnActivate(ObjectReference akActionRef) -EndEvent - -; Event received when this object has moved to an attached cell from a detached one -Event OnAttachedToCell() -EndEvent - -; Event received when this object's parent cell is attached -Event OnCellAttach() -EndEvent - -; Event received when this object's parent cell is detached -Event OnCellDetach() -EndEvent - -; Event received when every object in this object's parent cell is loaded (TODO: Find restrictions) -Event OnCellLoad() -EndEvent - -; Event received when this object is closed -Event OnClose(ObjectReference akActionRef) -EndEvent - -; Event received when this object enters, exits, or changes containers -Event OnContainerChanged(ObjectReference akNewContainer, ObjectReference akOldContainer) -EndEvent - -; Event received when this reference's destruction stage has changed -Event OnDestructionStageChanged(int aiOldStage, int aiCurrentStage) -EndEvent - -; Event recieved when this object moves to a detached cell from an attached one -Event OnDetachedFromCell() -EndEvent - -; Event received when this object is equipped by an actor -Event OnEquipped(Actor akActor) -EndEvent - -; Event received when this object is grabbed by the player -Event OnGrab() -EndEvent - -; Event received when this object is hit by a source (weapon, spell, explosion) or projectile attack -Event OnHit(ObjectReference akAggressor, Form akSource, Projectile akProjectile, bool abPowerAttack, bool abSneakAttack, bool abBashAttack, bool abHitBlocked) -EndEvent - -; Event received when an item is added to this object's inventory. If the item is a persistant reference, akItemReference will -; point at it - otherwise the parameter will be None -Event OnItemAdded(Form akBaseItem, int aiItemCount, ObjectReference akItemReference, ObjectReference akSourceContainer) -EndEvent - -; Event received when an item is removed from this object's inventory. If the item is a persistant reference, akItemReference -; will point at it - otherwise the parameter will be None -Event OnItemRemoved(Form akBaseItem, int aiItemCount, ObjectReference akItemReference, ObjectReference akDestContainer) -EndEvent - -; Event recieved when this object is completely loaded - will be fired every time this object is loaded -Event OnLoad() -EndEvent - -; Event received when the lock on this object changes -Event OnLockStateChanged() -EndEvent - -; Event received when a magic affect is being applied to this object -Event OnMagicEffectApply(ObjectReference akCaster, MagicEffect akEffect) -EndEvent - -; Event received when this object is opened -Event OnOpen(ObjectReference akActionRef) -EndEvent - -; Event received when this actor finishes changing its race -Event OnRaceSwitchComplete() -EndEvent - -; Event received when this object, if a book, is read -Event OnRead() -EndEvent - -; Event received when this object is released by the player -Event OnRelease() -EndEvent - -; Event received when this reference is reset -Event OnReset() -EndEvent - -; Event received when this reference is sold by an actor -Event OnSell(Actor akSeller) -EndEvent - -; Event received when a spell is cast by this object -Event OnSpellCast(Form akSpell) -EndEvent - -; Event received when translation is complete (from a call to TranslateTo) -Event OnTranslationComplete() -EndEvent - -; Event received when translation is aborted (from a call to StopTranslateTo) -Event OnTranslationFailed() -EndEvent - -; Event recieved when this reference hits a target -Event OnTrapHit(ObjectReference akTarget, float afXVel, float afYVel, float afZVel, float afXPos, float afYPos, float afZPos, \ - int aeMaterial, bool abInitialHit, int aeMotionType) -EndEvent - -; Event recieved when this starts hitting a target -Event OnTrapHitStart(ObjectReference akTarget, float afXVel, float afYVel, float afZVel, float afXPos, float afYPos, float afZPos, \ - int aeMaterial, bool abInitialHit, int aeMotionType) -EndEvent - -; Event recieved when this stops hitting a target -Event OnTrapHitStop(ObjectReference akTarget) -EndEvent - -; Event received when a this trigger is tripped -Event OnTrigger(ObjectReference akActionRef) -EndEvent - -; Event received when this trigger volume is entered -Event OnTriggerEnter(ObjectReference akActionRef) -EndEvent - -; Event received when this trigger volume is left -Event OnTriggerLeave(ObjectReference akActionRef) -EndEvent - -; Event received when this object is unequipped by an actor -Event OnUnequipped(Actor akActor) -EndEvent - -; Event recieved when this object is being unloaded - will be fired every time this object is unloaded -Event OnUnload() -EndEvent - -; Event that is triggered when this actor's combat state against the target changes -; State is as follows: -; 0 - not in combat -; 1 - in combat -; 2 - searching -Event OnCombatStateChanged(Actor akTarget, int aeCombatState) -EndEvent - -; Event that is triggered when this actor sits in the furniture -Event OnSit(ObjectReference akFurniture) -EndEvent - -; Event that is triggered when this actor leaves the furniture -Event OnGetUp(ObjectReference akFurniture) -EndEvent - -; Event that is triggered when this actor finishes dying -Event OnDeath(Actor akKiller) -EndEvent - -; Event that is triggered when this actor begins dying -Event OnDying(Actor akKiller) -EndEvent - -; Event that is triggered when this actor changes from one location to another -Event OnLocationChange(Location akOldLoc, Location akNewLoc) -EndEvent - -; Event received when this actor equips something - akReference may be None if object is not persistent -Event OnObjectEquipped(Form akBaseObject, ObjectReference akReference) -EndEvent - -; Event received when this actor unequips something - akReference may be None if object is not persistent -Event OnObjectUnequipped(Form akBaseObject, ObjectReference akReference) -EndEvent - -; Event received when this actor starts a new package -Event OnPackageStart(Package akNewPackage) -EndEvent - -; Event received when this actor's package changes -Event OnPackageChange(Package akOldPackage) -EndEvent - -; Event received when this actor's package ends -Event OnPackageEnd(Package akOldPackage) -EndEvent - -; Event received when this object's Ward is hit by a spell -Event OnWardHit(ObjectReference akCaster, Spell akSpell, int aiStatus) -EndEvent - -; Received when the player fires a bow. akWeapon will be a bow, akAmmo is the ammo or None, -; afPower will be 1.0 for a full-power shot, less for a dud, and abSunGazing will be true if the player is looking at the sun. -Event OnPlayerBowShot(Weapon akWeapon, Ammo akAmmo, float afPower, bool abSunGazing) -EndEvent - -; Received immediately after the player has loaded a save game. A good time to check for additional content. -Event OnPlayerLoadGame() -EndEvent - - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; Additional useful effect information -float Function GetDuration() native -float Function GetTimeElapsed() native - -; Registers for OnKeyDown and OnKeyUp events for the given keycode. -Function RegisterForKey(int keyCode) native -Function UnregisterForKey(int keyCode) native -Function UnregisterForAllKeys() native - -Event OnKeyDown(int keyCode) -EndEvent - -Event OnKeyUp(int keyCode, float holdTime) -EndEvent - -; Registers for OnControlDown and OnControlUp events for the given control. -; For a list of valid controls, see Input.psc. -Function RegisterForControl(string control) native -Function UnregisterForControl(string control) native -Function UnregisterForAllControls() native - -Event OnControlDown(string control) -EndEvent - -Event OnControlUp(string control, float holdTime) -EndEvent - -; Registers for OnMenuOpen and OnMenuClose events for the given menu. -; Registrations have to be refreshed after each game load. -; For a list of valid menu names, see UI.psc. -Function RegisterForMenu(string menuName) native -Function UnregisterForMenu(string menuName) native -Function UnregisterForAllMenus() native - -Event OnMenuOpen(string menuName) -endEvent - -Event OnMenuClose(string menuName) -endEvent - -; Registers a custom event callback for given event name. -; Registrations have to be refreshed after each game load. -; -; Examples: -; RegisterForModEvent("myCustomEvent", "MyModEventCallback") -; -; Event signature of custom event callbacks: -; Event MyModEventCallback(string eventName, string strArg, float numArg, Form sender) -; endEvent -; -Function RegisterForModEvent(string eventName, string callbackName) native -Function UnregisterForModEvent(string eventName) native -Function UnregisterForAllModEvents() native - -; Sends custom event with given generic parameters. -Function SendModEvent(string eventName, string strArg = "", float numArg = 0.0) native - -; See Form.psc -Function RegisterForCameraState() native -Function UnregisterForCameraState() native - -Event OnPlayerCameraState(int oldState, int newState) -EndEvent - -; See Form.psc -Function RegisterForCrosshairRef() native -Function UnregisterForCrosshairRef() native - -Event OnCrosshairRefChange(ObjectReference ref) -EndEvent - -; See Form.psc -Function RegisterForActorAction(int actionType) native -Function UnregisterForActorAction(int actionType) native - -Event OnActorAction(int actionType, Actor akActor, Form source, int slot) -EndEvent - -; Registers the script for when a QueueNiNodeUpdate is called -Function RegisterForNiNodeUpdate() native -Function UnregisterForNiNodeUpdate() native - -Event OnNiNodeUpdate(ObjectReference akActor) -EndEvent - -; returns the magnitude of the active effect -float Function GetMagnitude() native \ No newline at end of file diff --git a/modules/tests/psc_deps/Actor.psc b/modules/tests/psc_deps/Actor.psc deleted file mode 100644 index 075f200..0000000 --- a/modules/tests/psc_deps/Actor.psc +++ /dev/null @@ -1,941 +0,0 @@ -Scriptname Actor extends ObjectReference Hidden - -; Relationship functions use the following values: -; 4 - Lover -; 3 - Ally -; 2 - Confidant -; 1 - Friend -; 0 - Acquaintance -; -1 - Rival -; -2 - Foe -; -3 - Enemy -; -4 - Archnemesis - -; DEPRECATED - use MakePlayerFriend() instead -; replacement for ModFavorPoints -; if iFavorPoints > 0, will setRelationshipRank to 1 if 0 -; otherwise, won't do anything -Function ModFavorPoints(int iFavorPoints = 1) - if iFavorPoints > 0 - MakePlayerFriend() - else -; debug.trace(self + " ModFavorPoints called with negative param. NO EFFECT.") - endif -endFunction - -; also DEPRECATED -Function ModFavorPointsWithGlobal(GlobalVariable FavorPointsGlobal) - ModFavorPoints(FavorPointsGlobal.GetValueInt()) -endFunction - -;this function will make an actor a friend of the player if allowed -Function MakePlayerFriend() - ActorBase myBase = GetActorBase() - if myBase.IsUnique() - if GetRelationshipRank(Game.GetPlayer())== 0 -; debug.trace(self + " MakePlayerFriend called on neutral actor - changed to FRIEND.") - SetRelationshipRank(Game.GetPlayer(), 1) - else -; debug.trace(self + " MakePlayerFriend called on non-neutral actor - NO EFFECT.") - endif - else -; debug.trace(self + " MakePlayerFriend called on non-Unique actor. NO EFFECT.") - endif -endFunction - -; Adds the specified perk to this actor -Function AddPerk(Perk akPerk) native - -; Adds the specified shout to this actor - returns true on success -bool Function AddShout(Shout akShout) native - -; Adds the specified spell to this actor - returns true on success -bool Function AddSpell(Spell akSpell, bool abVerbose=true) native - -; Sets this a essential actors ability to talk when in a bleedout state -Function AllowBleedoutDialogue(bool abCanTalk ) native - -; overrides the race flag on an actor and determines if he can talk to the player in dialogue menu -Function AllowPCDialogue(bool abTalk) native - -; Attaches an "ash pile" to this actor, placing it at this actor's location and using the specified -; base object (or leveled item list) to represent the pile. If None is passed, it will use the -; default ash pile object -Function AttachAshPile(Form akAshPileBase = None) native - -; Can this actor fly here? -bool Function CanFlyHere() native - -; Clears this actor's arrested state -Function ClearArrested() native - -; Clears any expression override on the actor -Function ClearExpressionOverride() native - -; Clears this actor's extra arrows 3D -Function ClearExtraArrows() native - -; Remove the obligation to use a particular marker when this actor has to land. -Function ClearForcedLandingMarker() - SetForcedLandingMarker( None ) -endFunction - -; Clear any keep offset from actor settings -Function ClearKeepOffsetFromActor() native - -; Clears this actor's look at target -Function ClearLookAt() native - -; Damages the specified actor value -Function DamageActorValue(string asValueName, float afDamage) native - -; Alias for DamageActorValue - damages the specified actor value -Function DamageAV(string asValueName, float afDamage) - DamageActorValue(asValueName, afDamage) -EndFunction - -; Initiates a dismount. -bool Function Dismount() native - -; Dispel all spells from this actor -Function DispelAllSpells() native - -; Dispel a spell from this actor -bool Function DispelSpell( Spell akSpell ) native - -; Apply a spell to a target in combat -Function DoCombatSpellApply( Spell akSpell, ObjectReference akTarget ) native - -; Enables or disable's this actor's AI -Function EnableAI(bool abEnable = true) native - -; End the Deferred Kill state. This must only be called if StartDeferredKill was called first. -Function EndDeferredKill() native - -; Forces this actor to equip the specified item, preventing removal if requested -Function EquipItem(Form akItem, bool abPreventRemoval = false, bool abSilent = false) native - -; Forces this actor to equip the specified shout -Function EquipShout(Shout akShout) native - -; Forces this actor to equip the specified spell. The casting source can be: -; 0 - Left hand -; 1 - Right hand -Function EquipSpell(Spell akSpell, int aiSource) native - -; Forces the AI to re-evaluate its package stack -Function EvaluatePackage() native - -; Force the specified actor value to a specified value -Function ForceActorValue(string asValueName, float afNewValue) native - -; Alias for ForceActorValue - force the specified actor value to a specified value -Function ForceAV(string asValueName, float afNewValue) - ForceActorValue(asValueName, afNewValue) -EndFunction - -;returns the ActorBase -ActorBase function GetActorBase() - return GetBaseObject() as ActorBase -endFunction - -; Gets the specified actor value - returns 0 and logs an error if the value is unknown -float Function GetActorValue(string asValueName) native - -; Gets the specified actor value as a percentage of its max value - from 0 to 1 -float Function GetActorValuePercentage(string asValueName) native - -; Alias for GetActorValue - retrives the specified actor value -float Function GetAV(string asValueName) - return GetActorValue(asValueName) -EndFunction - -; Alias for GetActorValuePercentage - gets the actor value as a percent of max -float Function GetAVPercentage(string asValueName) - return GetActorValuePercentage(asValueName) -EndFunction - -; Gets the base value of the specified actor value - returns 0 and logs an error if the value is unknown -float Function GetBaseActorValue(string asValueName) native - -; Alias for GetBaseActorValue - retrieves the specified actor value's base value -float Function GetBaseAV(string asValueName) - return GetBaseActorValue(asValueName) -EndFunction - -; Obtains how much it would cost to bribe this actor -int Function GetBribeAmount() native - -; Get the faction this actor reports crimes to -Faction Function GetCrimeFaction() native - -; Gets this actor's current combat state -int Function GetCombatState() native - -; Gets this actor's current combat target -Actor Function GetCombatTarget() native - -; Gets this actor's current AI package -Package Function GetCurrentPackage() native - -; Gets this actor's current dialogue target -Actor Function GetDialogueTarget() native - -; Obtains the item quipped in the specified hand (0 - Left hand, 1 - Right hand) -; Return values are: -; -1 - Error -; 0 - Nothing -; 1 - One-handed sword -; 2 - One-handed dagger -; 3 - One-handed axe -; 4 - One-handed mace -; 5 - Two-handed sword -; 6 - Two-handed axe -; 7 - Bow -; 8 - Staff -; 9 - Magic spell -; 10 - Shield -; 11 - Torch -int Function GetEquippedItemType(int aiHand) native - -; Gets this actor's currently equipped shout -Shout Function GetEquippedShout() native - -; Gets this actor's currently equipped weapon -; false - Default - Right Hand -; true - Left Hand -Weapon Function GetEquippedWeapon(bool abLeftHand = false) native - -; Gets this actor's currently equipped shield -Armor Function GetEquippedShield() native - -; Gets the spell currently equipped in the specified source -; 0 - Left Hand -; 1 - Right Hand -; 2 - Other -; 3 - Instant -Spell Function GetEquippedSpell(int aiSource) native - -; Obtains this actor's rank with the specified faction - returns -1 if the actor is not a member -int Function GetFactionRank(Faction akFaction) native - -; Obtains this actor's faction-based reaction to the other actor -; 0 - Neutral -; 1 - Enemy -; 2 - Ally -; 3 - Friend -int Function GetFactionReaction(Actor akOther) native - -; Obtains this actor's current flight state -; 0 - Not flying -; 1 - Taking off -; 2 - Cruising -; 3 - Hovering -; 4 - Landing -int Function GetFlyingState() native - -; Get the ref at which this actor is obliged to land, if one is set (or none, if not). -ObjectReference Function GetForcedLandingMarker() native - -; Retrieves the amount of gold this actor has -int Function GetGoldAmount() native - -; Gets this actor's highest relationship rank - returns 0 if they have no relationships -int Function GetHighestRelationshipRank() native - -; Returns this actor's killer - or None if this actor is still alive -Actor Function GetKiller() native - -; Returns this actor's current level. -int Function GetLevel() native - -; Returns this actor's current light level. -float Function GetLightLevel() native - -; Gets this actor's highest relationship rank - returns 0 if they have no relationships -int Function GetLowestRelationshipRank() native - -; Obtains a leveled actor's "fake" base (the one generated by the game when the -; actor is leveled. This differs from GetActorBase which will return the editor base -; object) -ActorBase Function GetLeveledActorBase() native - -; Queries whether this actor has no bleedout recovery flag set. -bool Function GetNoBleedoutRecovery() native - -; Queries whether this actor receives player input -bool Function GetPlayerControls() native - -; Returns this actor's race -Race Function GetRace() native - -; Obtains the relationship rank between this actor and another -int Function GetRelationshipRank(Actor akOther) native - -; Obtains this actor's sit state, which is one of the following: -; 0 - Not sitting -; 2 - Not sitting, wants to sit -; 3 - Sitting -; 4 - Sitting, wants to stand -int Function GetSitState() native - -; Obtains this actor's sleep state, which is one of the following: -; 0 - Not sleeping -; 2 - Not sleeping, wants to sleep -; 3 - Sleeping -; 4 - Sleeping, wants to wake -int Function GetSleepState() native - -; Gets the voice recovery timer from the actor -float Function GetVoiceRecoveryTime() native - -; Checks to see if this actor has the specified association with the other actor - or anyone (if no actor is passed) -bool Function HasAssociation(AssociationType akAssociation, Actor akOther = None) native - -; Checks to see if this actor has a family relationship with the other actor - or anyone (if no actor is passed) -bool Function HasFamilyRelationship(Actor akOther = None) native - -; Sees if this actor has line-of-sight to another object. Only the player can check LOS to a non-actor -bool Function HasLOS(ObjectReference akOther) native - -; Checks to see if this actor is currently being affected by the given Magic Effect -bool Function HasMagicEffect(MagicEffect akEffect) native - -; Checks to see if this actor is currently being affected by a Magic Effect with the given Keyword -bool Function HasMagicEffectWithKeyword(Keyword akKeyword) native - -; Checks to see if this actor has a parent relationship with the other actor -bool Function HasParentRelationship(Actor akOther) native - -; Checks to see if this actor has the given Perk -bool Function HasPerk(Perk akPerk) native - -; Checks to see if this actor has the given Spell or Shout -bool Function HasSpell(Form akForm) native - -; Returns if this actor is alarmed or not -bool Function IsAlarmed() native - -; Returns if this actor is alerted or not -bool Function IsAlerted() native - -; Is this actor allowed to fly? -bool Function IsAllowedToFly() native - -; Is this actor currently arrested? -bool Function IsArrested() native - -; Is this actor currently arresting his target? (Must be a guard and alarmed) -bool Function IsArrestingTarget() native - -; Is the actor being ridden? -bool Function IsBeingRidden() native - -; Is this actor currently bleeding out? -bool Function IsBleedingOut() native - -; Queries whether this actor has player bribe flag set. -bool Function IsBribed() native - -; Is this actor a child? -bool Function IsChild() native - -; Is this actor a commanded by another? -bool Function IsCommandedActor() native - -; Returns if this actor is dead or not -bool Function IsDead() native - -; Returns if this actor is detected by the other one -bool Function IsDetectedBy(Actor akOther) native - -; Is this actor doing a favor for the player? -bool Function IsDoingFavor() native - -; Returns if the specified object is equipped on this actor -bool Function IsEquipped(Form akItem) native - -; Is this actor essential? -bool Function IsEssential() native - -; Returns if this actor is flying or not -bool Function IsFlying() native - -; Returns if this actor is a guard or not -bool Function IsGuard() native - -; Is this actor flagged as a ghost? -bool Function IsGhost() native - -; Is this actor hostile to another actor? -bool Function IsHostileToActor(Actor akActor) native - -; Returns if this actor is currently in combat -bool Function IsInCombat() native - -; Checks to see if this actor is a member of the specified faction -bool Function IsInFaction(Faction akFaction) native - -; Returns if this actor is in a kill move or not -bool Function IsInKillMove() native - -; Queries whether this actor has player intimidated flag set. -bool Function IsIntimidated() native - -; Is the actor on a mount? -bool Function IsOnMount() native - -; Checks to see if this actor the last ridden horse of the player -bool Function IsPlayersLastRiddenHorse() native - -; Is this actor currently a teammate of the player? -bool Function IsPlayerTeammate() native - -; Is this actor currently running? -bool Function IsRunning() native - -; Is this actor currently sneaking? -bool Function IsSneaking() native - -; Is this actor currently sprinting? -bool Function IsSprinting() native - -; Is this actor trespassing? -bool Function IsTrespassing() native - -; Is this actor unconscious? -bool Function IsUnconscious() native - -; Does this actor have his weapon and/or magic drawn? -bool Function IsWeaponDrawn() native - -; Sets the actor to a mode where it will keep a given offset from another actor -Function KeepOffsetFromActor(Actor arTarget, float afOffsetX, float afOffsetY, float afOffsetZ, float afOffsetAngleX = 0.0, float afOffsetAngleY = 0.0, float afOffsetAngleZ = 0.0, float afCatchUpRadius = 20.0, float afFollowRadius = 5.0) native - -; Kills this actor with the killer being the guilty party -Function Kill(Actor akKiller = None) native - -; Kills this actor even if essential -Function KillEssential(Actor akKiller = None) - ActorBase akActorBase = GetBaseObject() as ActorBase - if akActorBase.IsUnique() - akActorBase.SetEssential(0) - endif - Kill(akKiller) -endFunction - -; Kills this actor without a kill event with the killer being the guilty party -Function KillSilent(Actor akKiller = None) native - -; Modifies the specified actor value -Function ModActorValue(string asValueName, float afAmount) native - -; Alias for ModActorValue - modifies the specified actor value -Function ModAV(string asValueName, float afAmount) - ModActorValue(asValueName, afAmount) -EndFunction - -; Modifies this actor's rank in the faction -Function ModFactionRank(Faction akFaction, int aiMod) native - -; Pop this actor to the initial location for a package. Mainly for use on -; disabled actors, since they would normally start at their editor locations. -Function MoveToPackageLocation( ) native - -; Opens this actor's inventory, as if you were pick-pocketing them. Only works on teammates, or anyone if forced. -Function OpenInventory(bool abForceOpen = false) native - -; Make the actor path to a reference, latent version -; Note: this method doesn't return until the goal is reached or pathing -; failed or was interrupted (by another request for instance) -bool Function PathToReference(ObjectReference aTarget, float afWalkRunPercent) native - -; Send an idle to the actor to load in and play. -bool Function PlayIdle(Idle akIdle) native - -; Send an idle to the actor to play, overriding its target with the specified reference -bool Function PlayIdleWithTarget(Idle akIdle, ObjectReference akTarget) native - -; Send an event to the subgraphs of an actor. -Function PlaySubGraphAnimation(string asEventName) native - -; Removes this actor from the specified faction -Function RemoveFromFaction(Faction akFaction) native - -; Removes this actor from all factions -Function RemoveFromAllFactions() native - -; Removes the specified perk from this actor -Function RemovePerk(Perk akPerk) native - -; Removes the specified shout from this actor - returns true on success -bool Function RemoveShout(Shout akShout) native - -; Removes the specified spell from this actor - returns true on success -bool Function RemoveSpell(Spell akSpell) native - -; Resets this actor's health and limb state -Function ResetHealthAndLimbs() native - -; Restores damage done to the actor value (up to 0 damage) -Function RestoreActorValue(string asValueName, float afAmount) native - -; Resurrects this actor -Function Resurrect() native - -; Alias for RestoreActorValue - restores damage done to the actor value -Function RestoreAV(string asValueName, float afAmount) - RestoreActorValue(asValueName, afAmount) -EndFunction - -; Has this actor behave as if assaulted -Function SendAssaultAlarm() native - -; Has this actor behave as if they caught the target trespassing -Function SendTrespassAlarm(Actor akCriminal) native - -; Sets the specified actor value -Function SetActorValue(string asValueName, float afValue) native - -; Sets the actor in an alerted state -Function SetAlert(bool abAlerted = true) native - -; Sets whether this actor is allowed to fly or not - if not, will land the actor -Function SetAllowFlying(bool abAllowed = true) native - -; Sets whether this actor is allowed to fly or not - if not, will land the actor -Function SetAllowFlyingEx(bool abAllowed = true, bool abAllowCrash = true, bool abAllowSearch = false) native - -; Sets this actor's alpha - with an optional fade to that alpha -; The alpha will be clamped between 0 and 1 -Function SetAlpha(float afTargetAlpha, bool abFade = false) native - -; Sets this actor to be attacked by all other actors on sight -Function SetAttackActorOnSight(bool abAttackOnSight = true) native - -; Alias for SetActorValue - sets the specified actor value -Function SetAV(string asValueName, float afValue) - SetActorValue(asValueName, afValue) -EndFunction - -; Flags/unflags this actor as bribed by the player -Function SetBribed(bool abBribe = true) native - -; Sets the faction this actor reports crimes to -Function SetCrimeFaction(Faction akFaction) native - -; Sets this actor's critical stage, which is one of the following (properties below also match this) -; 0 - None -; 1 - Goo start -; 2 - Goo end -; 3 - Disintegrate start -; 4 - Disintegrate end -Function SetCriticalStage(int aiStage) native - -; Flag this actor as currently doing a favor for the player -Function SetDoingFavor(bool abDoingFavor = true) native - -; Sets this actor as "don't move" or not -Function SetDontMove(bool abDontMove = true) native - -; Sets an expression to override any other expression other systems may give this actor. -; 7 - Mood Neutral -; 0 - Dialogue Anger 8 - Mood Anger 15 - Combat Anger -; 1 - Dialogue Fear 9 - Mood Fear 16 - Combat Shout -; 2 - Dialogue Happy 10 - Mood Happy -; 3 - Dialogue Sad 11 - Mood Sad -; 4 - Dialogue Surprise 12 - Mood Surprise -; 5 - Dialogue Puzzled 13 - Mood Puzzled -; 6 - Dialogue Disgusted 14 - Mood Disgusted -; aiStrength is from 0 to 100 (percent) -Function SetExpressionOverride(int aiMood, int aiStrength = 100) native - -;forces the eye texture for this actor to the give texture set -Function SetEyeTexture(TextureSet akNewTexture) native - -; Sets this actor's rank with the specified faction -Function SetFactionRank(Faction akFaction, int aiRank) native - -; Set a specific marker as the place at which this actor must land from flight. -; params: -; - aMarker: The ObjectReference to set as this actor's landing marker -Function SetForcedLandingMarker( ObjectReference aMarker ) native - -; Flags/unflags this actor as a ghost -Function SetGhost(bool abIsGhost = true) native - -; Adds this actor to a faction at rank 0 if they aren't already in it -Function AddToFaction(Faction akFaction) - if (!IsInFaction(akFaction)) - SetFactionRank(akFaction, 0) - endif -EndFunction - -; Turns on/off headtracking on this actor -Function SetHeadTracking(bool abEnable = true) native - -; Flags/unflags this actor as intimidated by the player -Function SetIntimidated(bool abIntimidate = true) native - -; Sets this actor's head tracking target, optionally forcing it as their pathing look-at target -Function SetLookAt(ObjectReference akTarget, bool abPathingLookAt = false) native - -; Set the no bleedout recovery flag on this actor -Function SetNoBleedoutRecovery(bool abAllowed) native - -; Sets this actor to not effect the detection level on the stealth meter if he is not hostile to the player -Function SetNotShowOnStealthMeter(bool abNotShow) native - -; Sets the actors outfit and makes him wear it -Function SetOutfit( Outfit akOutfit, bool abSleepOutfit = false ) native - -; Set/reset whether player input being sent to the actor -Function SetPlayerControls(bool abControls) native - -; Sets the player as resisting arrest from this actor's faction -Function SetPlayerResistingArrest() native - -; Sets or clears this actor as a teammate of the player -; abCanDoFavor - OPTIONAL default is true the teammate can do favors -Function SetPlayerTeammate(bool abTeammate = true, bool abCanDoFavor=true) native - -; Sets the actors race -; akRace - OPTIONAL (Def=None) New race for this actor. Default, no race, to switch back to the original race. -Function SetRace( Race akRace = None ) native - -; Sets the relationship rank between this actor and another (See GetRelationshipRank for the ranks) -Function SetRelationshipRank(Actor akOther, int aiRank) native - -; Sets this actor as restrained or not -Function SetRestrained(bool abRestrained = true) native - -; Set a variable on all of an actor's subgraphs -Function SetSubGraphFloatVariable(string asVariableName, float afValue) native - -; Sets this actor as unconscious or not -Function SetUnconscious(bool abUnconscious = true) native - -; Attach the actor to (or detach it from) a horse, cart, or other vehicle. -; akVehicle is the vehicle ref. To detach the actor from its current vehicle, set akVehicle to None (or to the Actor itself). -Function SetVehicle( ObjectReference akVehicle ) native - -; Sets the voice recovery timer on the actor -; afTime is recovery time in seconds -Function SetVoiceRecoveryTime( float afTime ) native - -; Opens the Barter menu -Function ShowBarterMenu() native - -; Opens the Gift menu -; Params: -; - abGivingGift: True if we're giving a gift to this Actor, false if the player is taking a gift from this Actor -; - apFilterList: OPTIONAL (Def=None) -- If present, this form list is used to filter the item list. Only items -; that match keywords / items in the list will get shown -; - abShowStolenItems: OPTIONAL (Def=false) -- If true, stolen items are shown -; - abUseFavorPoints: OPTIONAL (Def=true) -- If true, favor points are added / subtracted with each transaction. If false, FPs aren't used at all. -; Returns: The number of favor points spent / gained while in the menu. -int Function ShowGiftMenu( bool abGivingGift, FormList apFilterList = None, bool abShowStolenItems = false, bool abUseFavorPoints = true ) native - -; Starts Cannibal with the target -Function StartCannibal(Actor akTarget) native - -; Starts combat with the target -Function StartCombat(Actor akTarget) native - -; Start the Deferred Kill state. Be sure to call EndDeferredKill or the actor will be invulnerable. -Function StartDeferredKill() native - -; Starts vampire feed with the target -Function StartVampireFeed(Actor akTarget) native - -; Removes this actor from combat -Function StopCombat() native - -; Stops all combat and alarms against this actor -Function StopCombatAlarm() native - -; Returns whether the actor can trap the soul of the given actor. -bool Function TrapSoul(Actor akTarget) native - -; Unequips the all items from this actor -Function UnequipAll() native - -; Unequips the specified item from this actor -Function UnequipItem(Form akItem, bool abPreventEquip = false, bool abSilent = false) native - -; Unequips the all items in this slot for the actor -Function UnequipItemSlot(int aiSlot) native - -; Forces this actor to unequip the specified shout -Function UnequipShout(Shout akShout) native - -; Forces this actor to unequip the specified spell. The casting source can be: -; 0 - Left hand -; 1 - Right hand -Function UnequipSpell(Spell akSpell, int aiSource) native - -; This actor will unlock all the doors that he qualifies for ownership in his current parentcell -Function UnLockOwnedDoorsInCell() native - -; Returns whether intimidate will succeed against this actor or not -bool Function WillIntimidateSucceed() native - -; Returns whether anything the actor is wearing has the specified keyword -bool Function WornHasKeyword(Keyword akKeyword) native - -; Makes this actor start sneaking -Function StartSneaking() native - -; Makes this actor draw his weapon -Function DrawWeapon() native - -; Event that is triggered when this actor's combat state against the target changes -; State is as follows: -; 0 - not in combat -; 1 - in combat -; 2 - searching -Event OnCombatStateChanged(Actor akTarget, int aeCombatState) -EndEvent - -; Event that is triggered when this actor sits in the furniture -Event OnSit(ObjectReference akFurniture) -EndEvent - -; Event that is triggered when this actor leaves the furniture -Event OnGetUp(ObjectReference akFurniture) -EndEvent - -; Event that is triggered when this actor finishes dying -Event OnDeath(Actor akKiller) -EndEvent - -; Event that is triggered when this actor begins to die -Event OnDying(Actor akKiller) -EndEvent - -; Event received when an actor enters bleedout. -Event OnEnterBleedout() -EndEvent - -; Event that is triggered when this actor changes from one location to another -Event OnLocationChange(Location akOldLoc, Location akNewLoc) -EndEvent - -; Event received when this actor equips something - akReference may be None if object is not persistent -Event OnObjectEquipped(Form akBaseObject, ObjectReference akReference) -EndEvent - -; Event received when this actor unequips something - akReference may be None if object is not persistent -Event OnObjectUnequipped(Form akBaseObject, ObjectReference akReference) -EndEvent - -; Event received when this actor starts a new package -Event OnPackageStart(Package akNewPackage) -EndEvent - -; Event received when this actor's package changes -Event OnPackageChange(Package akOldPackage) -EndEvent - -; Event received when this actor's package ends -Event OnPackageEnd(Package akOldPackage) -EndEvent - -; Event received when this actor finishes changing its race -Event OnRaceSwitchComplete() -EndEvent - -; Received when the player fires a bow. akWeapon will be a bow, akAmmo is the ammo or None, -; afPower will be 1.0 for a full-power shot, less for a dud, and abSunGazing will be true if the player is looking at the sun. -Event OnPlayerBowShot(Weapon akWeapon, Ammo akAmmo, float afPower, bool abSunGazing) -EndEvent - - -; Received immediately after the player has loaded a save game. A good time to check for additional content. -Event OnPlayerLoadGame() -EndEvent - -; Set of read-only properties to essentually make a fake enum for critical stages -int Property CritStage_None = 0 AutoReadOnly -int Property CritStage_GooStart = 1 AutoReadOnly -int Property CritStage_GooEnd = 2 AutoReadOnly -int Property CritStage_DisintegrateStart = 3 AutoReadOnly -int Property CritStage_DisintegrateEnd = 4 AutoReadOnly - -; **** For Debugging Movement Animations (not in release builds) **** -; Forces the movement direction on the actor -; afXAngle, afYAngle and afZAngle are in degrees -Function ForceMovementDirection(float afXAngle = 0.0, float afYAngle = 0.0, float afZAngle = 0.0) native - -; Forces the movement speed on the actor -; afSpeedMult is a speed multiplier based on the current max speeds -; - 0 -> 1 Scales between 0 and the Walk speed -; - 1 -> 2 Scales between Walk speed and Run Speed -; - 2 and above is a multiplier of the run speed (less 1.0 since Run is 2.0) -Function ForceMovementSpeed(float afSpeedMult) native - -; Forces the movement rotation speed on the actor -; Each component of the rotation speed is a multiplier following these rules: -; - 0 -> 1 Scales between 0 and the Walk speed -; - 1 -> 2 Scales between Walk speed and Run Speed -; - 2 and above is a multiplier of the run speed (less 1.0 since Run is 2.0) -Function ForceMovementRotationSpeed(float afXMult = 0.0, float afYMult = 0.0, float afZMult = 0.0) native - -; Ramps the movement direction on the actor to the passed in value over the passed in time -; afXAngle, afYAngle and afZAngle are in degrees -; afRampTime is in seconds -Function ForceMovementDirectionRamp(float afXAngle = 0.0, float afYAngle = 0.0, float afZAngle = 0.0, float afRampTime = 0.1) native - -; Ramps the movement speed on the actor to the passed in value over the passed in time -; afSpeedMult is a speed multiplier based on the current max speeds -; - 0 -> 1 Scales between 0 and the Walk speed -; - 1 -> 2 Scales between Walk speed and Run Speed -; - 2 and above is a multiplier of the run speed (less 1.0 since Run is 2.0) -; afRampTime is in seconds -Function ForceMovementSpeedRamp(float afSpeedMult, float afRampTime = 0.1) native - -; Ramps the movement rotation speed on the actor to the passed in value over the passed in time -; Each component of the rotation speed is a multiplier following these rules: -; - 0 -> 1 Scales between 0 and the Walk speed -; - 1 -> 2 Scales between Walk speed and Run Speed -; - 2 and above is a multiplier of the run speed (less 1.0 since Run is 2.0) -; afRampTime is in seconds -Function ForceMovementRotationSpeedRamp(float afXMult = 0.0, float afYMult = 0.0, float afZMult = 0.0, float afRampTime = 0.1) native - -; Sets the target movement direction on the actor -; afXAngle, afYAngle and afZAngle are in degrees -Function ForceTargetDirection(float afXAngle = 0.0, float afYAngle = 0.0, float afZAngle = 0.0) native - -; Sets the target movement speed on the actor -; afSpeedMult is a speed multiplier based on the current max speeds -; - 0 -> 1 Scales between 0 and the Walk speed -; - 1 -> 2 Scales between Walk speed and Run Speed -; - 2 and above is a multiplier of the run speed (less 1.0 since Run is 2.0) -Function ForceTargetSpeed(float afSpeed) native - -; Sets the target facing angle on the actor -; afXAngle, afYAngle and afZAngle are in degrees -Function ForceTargetAngle(float afXAngle = 0.0, float afYAngle = 0.0, float afZAngle = 0.0) native - -; Clears any forced movement on the actor and return it to its standard state -Function ClearForcedMovement() native - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; returns the form for the item worn at the specified slotMask -; use Armor.GetMaskForSlot() to generate appropriate slotMask -Form Function GetWornForm(int slotMask) native - -; returns the itemId for the item worn at the specified slotMask -int Function GetWornItemId(int slotMask) native - -; returns the object currently equipped in the specified location -; 0 - left hand -; 1 - right hand -; 2 - shout -Form Function GetEquippedObject(int location) native - -; returns the itemId of the object currently equipped in the specified hand -; 0 - left hand -; 1 - right hand -int Function GetEquippedItemId(int location) native - -; returns the number of added spells for the actor -Int Function GetSpellCount() native - -; returns the specified added spell for the actor -Spell Function GetNthSpell(int n) native - -; Updates an Actors meshes (Used for Armor mesh/texture changes and face changes) -; DO NOT USE WHILE MOUNTED -Function QueueNiNodeUpdate() native - -; Updates an Actors head mesh -Function RegenerateHead() native - -int Property EquipSlot_Default = 0 AutoReadOnly -int Property EquipSlot_RightHand = 1 AutoReadOnly -int Property EquipSlot_LeftHand = 2 AutoReadOnly - -; equips item at the given slot -Function EquipItemEx(Form item, int equipSlot = 0, bool preventUnequip = false, bool equipSound = true) native - -; equips item with matching itemId at the given slot -Function EquipItemById(Form item, int itemId, int equipSlot = 0, bool preventUnequip = false, bool equipSound = true) native - -; unequips item at the given slot -Function UnequipItemEx(Form item, int equipSlot = 0, bool preventEquip = false) native - -; Adds a headpart, if the type exists it will replace, must not be misc type -; Beware: This function also affects the ActorBase -Function ChangeHeadPart(HeadPart hPart) native - -; Replaces a headpart on the loaded mesh does not affect ActorBase -; Both old and new must exist, and be of the same type -Function ReplaceHeadPart(HeadPart oPart, HeadPart newPart) native - -; Visually updates the actors weight -; neckDelta = (oldWeight / 100) - (newWeight / 100) -; Neck changes are player persistent, but actor per-session -; Weight itself is persistent either way so keep track of your -; original weight if you use this for Actors other than the player -; DO NOT USE WHILE MOUNTED -Function UpdateWeight(float neckDelta) native - -; Returns whether the actors AI is enabled -bool Function IsAIEnabled() native - -; Resets Actor AI -Function ResetAI() native - -; Returns whether the actor is currently swimming -bool Function IsSwimming() native - -; Sheathes the actors weapon -Function SheatheWeapon() native - -; Returns the reference of the furniture the actor is currently using -ObjectReference Function GetFurnitureReference() native - -; 0 - "Aah" -; 1 - "BigAah" -; 2 - "BMP" -; 3 - "ChJSh" -; 4 - "DST" -; 5 - "Eee" -; 6 - "Eh" -; 7 - "FV" -; 8 - "I" -; 9 - "K" -; 10 - "N" -; 11 - "Oh" -; 12 - "OohQ" -; 13 - "R" -; 14 - "Th" -; 15 - "W" -Function SetExpressionPhoneme(int index, float value) native - -; 0 - "BlinkLeft" -; 1 - "BlinkRight" -; 2 - "BrowDownLeft" -; 3 - "BrowDownRight" -; 4 - "BrowInLeft" -; 5 - "BrowInRight" -; 6 - "BrowUpLeft" -; 7 - "BrowUpRight" -; 8 - "LookDown" -; 9 - "LookLeft" -; 10 - "LookRight" -; 11 - "LookUp" -; 12 - "SquintLeft" -; 13 - "SquintRight" -; 14 - "HeadPitch" -; 15 - "HeadRoll" -; 16 - "HeadYaw" -Function SetExpressionModifier(int index, float value) native - -; Resets all expression, phoneme, and modifiers -Function ResetExpressionOverrides() native - -; Returns all factions with the specified min and max ranks (-128 to 127) -Faction[] Function GetFactions(int minRank, int maxRank) native \ No newline at end of file diff --git a/modules/tests/psc_deps/ActorBase.psc b/modules/tests/psc_deps/ActorBase.psc deleted file mode 100644 index 54b5f32..0000000 --- a/modules/tests/psc_deps/ActorBase.psc +++ /dev/null @@ -1,116 +0,0 @@ -Scriptname ActorBase extends Form Hidden - -; Returns this actor's class -Class Function GetClass() native - -; Gets the number of actors of this type that have been killed -int Function GetDeadCount() native - -; Returns this actor's gift filter formlist -FormList Function GetGiftFilter() native - -; Returns this actor's race -Race Function GetRace() native - -; Returns this actor's sex. Values for sex are: -; -1 - None -; 0 - Male -; 1 - Female -int Function GetSex() native - -; Is this actor essential? -bool Function IsEssential() native - -; Is this actor invulnerable? -bool Function IsInvulnerable() native - -; Is this actor protected (can only be killed by player)? -bool Function IsProtected() native - -; Is this actor base unique? -bool Function IsUnique() native - -; Sets this actor as essential or not - if set as essential, will UNSET protected -Function SetEssential(bool abEssential = true) native - -; Sets this actor as invulnerable or not -Function SetInvulnerable(bool abInvulnerable = true) native - -; Sets this actor as protected or not - if set as protected, will UNSET essential -Function SetProtected(bool abProtected = true) native - -; Sets the actors outfit -Function SetOutfit( Outfit akOutfit, bool abSleepOutfit = false ) native - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; get/set the CombatStyle of the actor -CombatStyle Function GetCombatStyle() native -Function SetCombatStyle(CombatStyle cs) native - -; Get the Outfit of the actor -Outfit Function GetOutfit(bool bSleepOutfit = false) native - -; set the Class of the actor -Function SetClass(Class c) native - -; Get/Set the actors body height -float Function GetHeight() native -Function SetHeight(float height) native - -; Get/Set the actors body weight -float Function GetWeight() native -Function SetWeight(float weight) native - -; Get/Set actors HeadPart by index -int Function GetNumHeadParts() native -HeadPart Function GetNthHeadPart(int slotPart) native -Function SetNthHeadPart(HeadPart headPart, int slotPart) native -int Function GetIndexOfHeadPartByType(int type) native - -; These functions are READ-ONLY they are for accessing the -; HeadPart list when the ActorBase's Race has been overlayed -; with another race (e.g. Vampires) -int Function GetNumOverlayHeadParts() native -HeadPart Function GetNthOverlayHeadPart(int slotPart) native -int Function GetIndexOfOverlayHeadPartByType(int type) native - -; Get/Set actors face morph value by index -float Function GetFaceMorph(int index) native -Function SetFaceMorph(float value, int index) native - -; Get/Set actors facemorph preset by index -; 0 - Nose -; 1 - ?? -; 2 - Mouth -; 3 - Eyes -int Function GetFacePreset(int index) native -Function SetFacePreset(int value, int index) native - -ColorForm Function GetHairColor() native -Function SetHairColor(ColorForm color) native - -; returns the number of spells defined in the base actor form -int Function GetSpellCount() native - -; returns the specified spell defined in the base actor form -Spell Function GetNthSpell(int n) native - -; returns the face textureset of the actor (Player Only?) -TextureSet Function GetFaceTextureSet() native -Function SetFaceTextureSet(TextureSet textures) native - -; Gets/sets the Actor's voicetype -VoiceType Function GetVoiceType() native -Function SetVoiceType(VoiceType nVoice) native - -; Gets/sets the skin of the actorbase -Armor Function GetSkin() native -Function SetSkin(Armor skin) native - -; Gets/sets the far away skin of the actorbase -Armor Function GetSkinFar() native -Function SetSkinFar(Armor skin) native - -; Gets the root template of the ActorBase -ActorBase Function GetTemplate() native \ No newline at end of file diff --git a/modules/tests/psc_deps/ActorValueInfo.psc b/modules/tests/psc_deps/ActorValueInfo.psc deleted file mode 100644 index 99fec70..0000000 --- a/modules/tests/psc_deps/ActorValueInfo.psc +++ /dev/null @@ -1,66 +0,0 @@ -Scriptname ActorValueInfo extends Form Hidden - -; Returns the AVI by name -ActorValueInfo Function GetActorValueInfoByName(string avName) global native -ActorValueInfo Function GetAVIByName(string avName) global - return GetActorValueInfoByName(avName) -EndFunction - -; Returns the AVI by id (0-164) -ActorValueInfo Function GetActorValueInfoByID(int id) global native -ActorValueInfo Function GetAVIByID(int id) global - return GetActorValueInfoByID(id) -EndFunction - -; Returns whether this AVI is a skill -bool Function IsSkill() native - -; Skill Multiplier manipulation -float Function GetSkillUseMult() native -Function SetSkillUseMult(float value) native - -float Function GetSkillOffsetMult() native -Function SetSkillOffsetMult(float value) native - -float Function GetSkillImproveMult() native -Function SetSkillImproveMult(float value) native - -float Function GetSkillImproveOffset() native -Function SetSkillImproveOffset(float value) native - -; Returns the amount of experienced gained in this skill -float Function GetSkillExperience() native - -; Does not trigger skill-up -Function SetSkillExperience(float exp) native - -; Adds experience to this skill (Same as console AdvanceSkill, triggers skill-up) -Function AddSkillExperience(float exp) native - -; Returns the experience required for skill-up -; (ImproveMult * currentLevel ^ fSkillUseCurve + ImproveOffset) -float Function GetExperienceForLevel(int currentLevel) native - -; Returns the legendary level of this skill -int Function GetSkillLegendaryLevel() native - -; Sets the legendary level of this skill -Function SetSkillLegendaryLevel(int level) native - -; Returns perks from the skill into the FormList -; Actor filter applies to unowned and allRanks -; unowned will add perks that the actor does not own, or only perks the actor owns -; allRanks will add all ranks of each perk to the list, unowned/owned filter also applies -Function GetPerkTree(FormList list, Actor akActor = None, bool unowned = true, bool allRanks = false) native - -; Same as GetPerkTree except returns into a new array -Perk[] Function GetPerks(Actor akActor = None, bool unowned = true, bool allRanks = false) native - -; Same as Actor.GetActorValue (convenience function) -float Function GetCurrentValue(Actor akActor) native - -; Same as Actor.GetBaseActorValue (convenience function) -float Function GetBaseValue(Actor akActor) native - -; Acquires the Maximum value for the current ActorValue -float Function GetMaximumValue(Actor akActor) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Alias.psc b/modules/tests/psc_deps/Alias.psc deleted file mode 100644 index bc443c5..0000000 --- a/modules/tests/psc_deps/Alias.psc +++ /dev/null @@ -1,198 +0,0 @@ -Scriptname Alias Hidden - -; Returns the quest that owns this alias -Quest Function GetOwningQuest() native - -; Register for the specified animation event from the specified object - returns true if it successfully registered -bool Function RegisterForAnimationEvent(ObjectReference akSender, string asEventName) native - -; Register for LOS gain and lost events between the viewer and the target -; A loss or gain event will be sent immediately, depending on whether or not the viewer is already looking at the target or not -; If the viewer is not the player, the target must be another actor -Function RegisterForLOS(Actor akViewer, ObjectReference akTarget) native - -; Register for only the first LOS gain event between the viewer and the target -; If the viewer is already looking at the target, an event will be received almost immediately -; If the viewer is not the player, the target must be another actor -Function RegisterForSingleLOSGain(Actor akViewer, ObjectReference akTarget) native - -; Register for only the first LOS lost event between the viewer and the target -; If the viewer is already not looking at the target, an event will be received almost immediately -; If the viewer is not the player, the target must be another actor -Function RegisterForSingleLOSLost(Actor akViewer, ObjectReference akTarget) native - -; Register for a single OnUpdate event, in afInterval seconds. All scripts attached to this alias will get the update events -; Of course, this means you don't need to call UnregisterForUpdate() -; If you find yourself doing this: -; Event OnUpdate() -; UnregisterForUpdate() -; {Do some stuff} -; endEvent -; Then you should use RegisterForSingleUpdate instead -Function RegisterForSingleUpdate(float afInterval) native - -; Register for OnUpdate events, every X seconds, where X is the interval. All scripts attached to this alias will get the update events -Function RegisterForUpdate(float afInterval) native - -; Register for OnUpdateGameTime events, every X hours of game time, where X is the interval. All scripts attached to this alias will get the update events -Function RegisterForUpdateGameTime(float afInterval) native - -; Register for a single OnUpdateGameTime event, in afInterval hours of game time. All scripts attached to this alias will get the update events -Function RegisterForSingleUpdateGameTime(float afInterval) native - -; Registers this alias to receive events when the player sleeps and wakes up -Function RegisterForSleep() native - -; Registers this alias to receive events when tracked stats are updated -Function RegisterForTrackedStatsEvent() native - -; Turns on profiling for this specific object and all scripts attached to it - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StartObjectProfiling() native - -; Turns off profiling for this specific object and all scripts attached to it - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StopObjectProfiling() native - -; Unregister for any LOS events between the viewer and target -Function UnregisterForLOS(Actor akViewer, ObjectReference akTarget) native - -; Unregister for the specified animation event from the specified object -Function UnregisterForAnimationEvent(ObjectReference akSender, string asEventName) native - -; Unregisters this alias to receive events when the player sleeps and wakes up -Function UnregisterForSleep() native - -; Unregisters this alias from receiving events when tracked stats are updated -Function UnregisterForTrackedStatsEvent() native - -; Unregister for OnUpdate events, all attached scripts will stop getting update events -Function UnregisterForUpdate() native - -; Unregister for OnUpdateGameTime events, all attached scripts will stop getting update game time events -Function UnregisterForUpdateGameTime() native - -; Animation event, sent when an object we are listening to hits one of the events we are listening for -Event OnAnimationEvent(ObjectReference akSource, string asEventName) -EndEvent - -; Event sent when you have been unregistered from receiving an animation event because the target -; object's animation graph has been unloaded -Event OnAnimationEventUnregistered(ObjectReference akSource, string asEventName) -EndEvent - -; LOS event, sent whenever the viewer first sees the target (after registering) -Event OnGainLOS(Actor akViewer, ObjectReference akTarget) -EndEvent - -; Lost LOS event, sent whenever the viewer first loses sight of the target (after registering) -Event OnLostLOS(Actor akViewer, ObjectReference akTarget) -EndEvent - -; Received when the player sleeps. Start and desired end time are in game time days (after registering) -Event OnSleepStart(float afSleepStartTime, float afDesiredSleepEndTime) -EndEvent - -; Received when the player stops sleeping - whether naturally or interrupted (after registering) -Event OnSleepStop(bool abInterrupted) -EndEvent - -; Event received when a tracked stat is updated for the player -Event OnTrackedStatsEvent(string arStatName, int aiStatValue) -EndEvent - -; Update event, sent every X seconds while this alias is registered for them -Event OnUpdate() -EndEvent - -; Update event, sent every X hours of game time while this alias is registered for them -Event OnUpdateGameTime() -EndEvent - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; return the name of the alias -string Function GetName() native - -; return the id of the alias -int Function GetID() native - -; Registers for OnKeyDown and OnKeyUp events for the given keycode. -Function RegisterForKey(int keyCode) native -Function UnregisterForKey(int keyCode) native -Function UnregisterForAllKeys() native - -Event OnKeyDown(int keyCode) -EndEvent - -Event OnKeyUp(int keyCode, float holdTime) -EndEvent - -; Registers for OnControlDown and OnControlUp events for the given control. -; For a list of valid controls, see Input.psc. -Function RegisterForControl(string control) native -Function UnregisterForControl(string control) native -Function UnregisterForAllControls() native - -Event OnControlDown(string control) -EndEvent - -Event OnControlUp(string control, float holdTime) -EndEvent - -; Registers for OnMenuOpen and OnMenuClose events for the given menu. -; Registrations have to be refreshed after each game load. -; For a list of valid menu names, see UI.psc. -Function RegisterForMenu(string menuName) native -Function UnregisterForMenu(string menuName) native -Function UnregisterForAllMenus() native - -Event OnMenuOpen(string menuName) -endEvent - -Event OnMenuClose(string menuName) -endEvent - -; Registers a custom event callback for given event name. -; Registrations have to be refreshed after each game load. -; -; Examples: -; RegisterForModEvent("myCustomEvent", "MyModEventCallback") -; -; Event signature of custom event callbacks: -; Event MyModEventCallback(string eventName, string strArg, float numArg, Form sender) -; endEvent -; -Function RegisterForModEvent(string eventName, string callbackName) native -Function UnregisterForModEvent(string eventName) native -Function UnregisterForAllModEvents() native - -; Sends custom event with given generic parameters. -Function SendModEvent(string eventName, string strArg = "", float numArg = 0.0) native - -; See Form.psc -Function RegisterForCameraState() native -Function UnregisterForCameraState() native - -Event OnPlayerCameraState(int oldState, int newState) -EndEvent - -; See Form.psc -Function RegisterForCrosshairRef() native -Function UnregisterForCrosshairRef() native - -Event OnCrosshairRefChange(ObjectReference ref) -EndEvent - -; See Form.psc -Function RegisterForActorAction(int actionType) native -Function UnregisterForActorAction(int actionType) native - -Event OnActorAction(int actionType, Actor akActor, Form source, int slot) -EndEvent - -; Registers the script for when a QueueNiNodeUpdate is called -Function RegisterForNiNodeUpdate() native -Function UnregisterForNiNodeUpdate() native - -Event OnNiNodeUpdate(ObjectReference akActor) -EndEvent \ No newline at end of file diff --git a/modules/tests/psc_deps/Ammo.psc b/modules/tests/psc_deps/Ammo.psc deleted file mode 100644 index 46f967c..0000000 --- a/modules/tests/psc_deps/Ammo.psc +++ /dev/null @@ -1,12 +0,0 @@ -Scriptname Ammo extends Form Hidden - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC - -; Returns whether this ammo is a bolt -bool Function IsBolt() native - -; Returns the projectile associated with this ammo -Projectile Function GetProjectile() native - -; Returns the base damage of this ammo -float Function GetDamage() native diff --git a/modules/tests/psc_deps/Armor.psc b/modules/tests/psc_deps/Armor.psc deleted file mode 100644 index 9adc44a..0000000 --- a/modules/tests/psc_deps/Armor.psc +++ /dev/null @@ -1,164 +0,0 @@ -Scriptname Armor extends Form Hidden - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -int Function GetArmorRating() native -int Function GetAR() - return GetArmorRating() -endFunction - -Function SetArmorRating(int armorRating) native -Function SetAR(int armorRating) - return SetArmorRating(armorRating) -endFunction - -Function ModArmorRating(int modBy) native -Function ModAR(int modBy) - return ModArmorRating(modBy) -endFunction - -; works on the path to the nif file representing the in-game model of the weapon -string Function GetModelPath(bool bFemalePath) native -Function SetModelPath(string path, bool bFemalePath) native - -; works on the path to the nif file representing the icon for the weapon in the inventory -string Function GetIconPath(bool bFemalePath) native -Function SetIconPath(string path, bool bFemalePath) native - -; works on the path to the file representing the message icon for the weapon -string Function GetMessageIconPath(bool bFemalePath) native -Function SetMessageIconPath(string path, bool bFemalePath) native - -; Weight Class -; 0 = Light Armor -; 1 = Heavy Armor -; 2 = None -int Function GetWeightClass() native -Function SetWeightClass(int weightClass) native - -; works on the enchantment associated with the armor -Enchantment Function GetEnchantment() native -Function SetEnchantment(Enchantment e) native - -; Armor info by keyword -bool Function IsLightArmor() - return HasKeywordString("ArmorLight") -endFunction - -bool Function IsHeavyArmor() - return HasKeywordString("ArmorHeavy") -endFunction - -bool Function IsClothing() - return HasKeywordString("ArmorClothing") -endFunction - -bool Function IsBoots() - return HasKeywordString("ArmorBoots") -endFunction - -bool Function IsCuirass() - return HasKeywordString("ArmorCuirass") -endFunction - -bool Function IsGauntlets() - return HasKeywordString("ArmorGauntlets") -endFunction - -bool Function IsHelmet() - return HasKeywordString("ArmorHelmet") -endFunction - -bool Function IsShield() - return HasKeywordString("ArmorShield") -endFunction - -bool Function IsJewelry() - return HasKeywordString("ArmorJewelry") -endFunction - -bool Function IsClothingHead() - return HasKeywordString("ClothingHead") -endFunction - -bool Function IsClothingBody() - return HasKeywordString("ClothingBody") -endFunction - -bool Function IsClothingFeet() - return HasKeywordString("ClothingFeet") -endFunction - -bool Function IsClothingHands() - return HasKeywordString("ClothingHands") -endFunction - -bool Function IsClothingRing() - return HasKeywordString("ClothingRing") -endFunction - -bool Function IsClothingRich() - return HasKeywordString("ClothingRich") -endFunction - -bool Function IsClothingPoor() - return HasKeywordString("ClothingPoor") -endFunction - - -; Functions and Flags dealing the BipedObject slot values from the CK -; These are the equivalent of 1 << (SlotMask-30). Basically -; these are a flags where 30 is the first bit, and 61 is the 31st bit. - -; returns the slot mask for the armor. -int Function GetSlotMask() native -; sets the slot mask for the armor -Function SetSlotMask(int slotMask) native -; adds the specified slotMask to the armor -int Function AddSlotToMask(int slotMask) native -; removes the specified slot masks from the armor -int Function RemoveSlotFromMask(int slotMask) native - -; calculates the equivalent value for the properties below -int Function GetMaskForSlot(int slot) global native - -; returns the number of armor addons for this armor -int Function GetNumArmorAddons() native - -; returns the nth armor addon for this armor -ArmorAddon Function GetNthArmorAddon(int n) native - -; returns the SlotMask for a single slot from the CK -; can be used with the non-global SlotMask functions above -; and with the Math bit shifting functions -int Property kSlotMask30 = 0x00000001 AutoReadOnly -int Property kSlotMask31 = 0x00000002 AutoReadOnly -int Property kSlotMask32 = 0x00000004 AutoReadOnly -int Property kSlotMask33 = 0x00000008 AutoReadOnly -int Property kSlotMask34 = 0x00000010 AutoReadOnly -int Property kSlotMask35 = 0x00000020 AutoReadOnly -int Property kSlotMask36 = 0x00000040 AutoReadOnly -int Property kSlotMask37 = 0x00000080 AutoReadOnly -int Property kSlotMask38 = 0x00000100 AutoReadOnly -int Property kSlotMask39 = 0x00000200 AutoReadOnly -int Property kSlotMask40 = 0x00000400 AutoReadOnly -int Property kSlotMask41 = 0x00000800 AutoReadOnly -int Property kSlotMask42 = 0x00001000 AutoReadOnly -int Property kSlotMask43 = 0x00002000 AutoReadOnly -int Property kSlotMask44 = 0x00004000 AutoReadOnly -int Property kSlotMask45 = 0x00008000 AutoReadOnly -int Property kSlotMask46 = 0x00010000 AutoReadOnly -int Property kSlotMask47 = 0x00020000 AutoReadOnly -int Property kSlotMask48 = 0x00040000 AutoReadOnly -int Property kSlotMask49 = 0x00080000 AutoReadOnly -int Property kSlotMask50 = 0x00100000 AutoReadOnly -int Property kSlotMask51 = 0x00200000 AutoReadOnly -int Property kSlotMask52 = 0x00400000 AutoReadOnly -int Property kSlotMask53 = 0x00800000 AutoReadOnly -int Property kSlotMask54 = 0x01000000 AutoReadOnly -int Property kSlotMask55 = 0x02000000 AutoReadOnly -int Property kSlotMask56 = 0x04000000 AutoReadOnly -int Property kSlotMask57 = 0x08000000 AutoReadOnly -int Property kSlotMask58 = 0x10000000 AutoReadOnly -int Property kSlotMask59 = 0x20000000 AutoReadOnly -int Property kSlotMask60 = 0x40000000 AutoReadOnly -int Property kSlotMask61 = 0x80000000 AutoReadOnly diff --git a/modules/tests/psc_deps/Art.psc b/modules/tests/psc_deps/Art.psc deleted file mode 100644 index 190ccc5..0000000 --- a/modules/tests/psc_deps/Art.psc +++ /dev/null @@ -1,4 +0,0 @@ -Scriptname Art extends Form Hidden - -string Function GetModelPath() native -Function SetModelPath(string path) native \ No newline at end of file diff --git a/modules/tests/psc_deps/AssociationType.psc b/modules/tests/psc_deps/AssociationType.psc deleted file mode 100644 index f1ef6f6..0000000 --- a/modules/tests/psc_deps/AssociationType.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname AssociationType extends Form Hidden \ No newline at end of file diff --git a/modules/tests/psc_deps/Cell.psc b/modules/tests/psc_deps/Cell.psc deleted file mode 100644 index 3beeabf..0000000 --- a/modules/tests/psc_deps/Cell.psc +++ /dev/null @@ -1,45 +0,0 @@ -Scriptname Cell extends Form Hidden - -; Gets the actor that owns this cell (or none if not owned by an actor) -ActorBase Function GetActorOwner() native - -; Gets the faction that owns this cell (or none if not owned by a faction) -Faction Function GetFactionOwner() native - -; Is this cell "attached"? (In the loaded area) -bool Function IsAttached() native - -; Is this cell an interior cell? -bool Function IsInterior() native - -; Flags the cell for reset on next load -Function Reset() native - -; Sets this cell's owner as the specified actor -Function SetActorOwner(ActorBase akActor) native - -; Sets this cell's owner as the specified faction -Function SetFactionOwner(Faction akFaction) native - -; Sets the fog color for this cell (interior, non-sky-lit cells only) -Function SetFogColor(int aiNearRed, int aiNearGreen, int aiNearBlue, \ - int aiFarRed, int aiFarGreen, int aiFarBlue) native - -; Adjusts this cell's fog near and far planes (interior, non-sky-lit cells only) -Function SetFogPlanes(float afNear, float afFar) native - -; Sets the fog power for this cell (interior, non-sky-lit cells only) -Function SetFogPower(float afPower) native - -; Sets this cell as public or private -Function SetPublic(bool abPublic = true) native - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; Returns the number of refs in the cell -int Function GetNumRefs(int formTypeFilter = 0) native - -; returns the ref at the specified index -ObjectReference Function GetNthRef(int n, int formTypeFilter = 0) native - -; Returns the water level of the cell (-2147483648 if no water) -float Function GetWaterLevel() native \ No newline at end of file diff --git a/modules/tests/psc_deps/Class.psc b/modules/tests/psc_deps/Class.psc deleted file mode 100644 index 666ca87..0000000 --- a/modules/tests/psc_deps/Class.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname Class extends Form Hidden \ No newline at end of file diff --git a/modules/tests/psc_deps/ColorComponent.psc b/modules/tests/psc_deps/ColorComponent.psc deleted file mode 100644 index b0873fa..0000000 --- a/modules/tests/psc_deps/ColorComponent.psc +++ /dev/null @@ -1,19 +0,0 @@ -Scriptname ColorComponent Hidden - -int Function GetAlpha(int argb) global native -int Function GetRed(int argb) global native -int Function GetGreen(int argb) global native -int Function GetBlue(int argb) global native - -float Function GetHue(int argb) global native -float Function GetSaturation(int argb) global native -float Function GetValue(int argb) global native - -int Function SetAlpha(int argb, int a) global native -int Function SetRed(int argb, int r) global native -int Function SetGreen(int argb, int g) global native -int Function SetBlue(int argb, int b) global native - -int Function SetHue(int argb, float h) global native -int Function SetSaturation(int argb, float s) global native -int Function SetValue(int argb, float v) global native \ No newline at end of file diff --git a/modules/tests/psc_deps/ColorForm.psc b/modules/tests/psc_deps/ColorForm.psc deleted file mode 100644 index 09ce676..0000000 --- a/modules/tests/psc_deps/ColorForm.psc +++ /dev/null @@ -1,28 +0,0 @@ -Scriptname ColorForm extends Form Hidden - -int Function GetColor() native -Function SetColor(int color) native - -int Function GetRed() - return ColorComponent.GetRed(Self.GetColor()) -EndFunction - -int Function GetGreen() - return ColorComponent.GetGreen(Self.GetColor()) -EndFunction - -int Function GetBlue() - return ColorComponent.GetBlue(Self.GetColor()) -EndFunction - -float Function GetHue() - return ColorComponent.GetHue(Self.GetColor()) -EndFunction - -float Function GetSaturation() - return ColorComponent.GetSaturation(Self.GetColor()) -EndFunction - -float Function GetValue() - return ColorComponent.GetValue(Self.GetColor()) -EndFunction \ No newline at end of file diff --git a/modules/tests/psc_deps/CombatStyle.psc b/modules/tests/psc_deps/CombatStyle.psc deleted file mode 100644 index a19caee..0000000 --- a/modules/tests/psc_deps/CombatStyle.psc +++ /dev/null @@ -1,71 +0,0 @@ -Scriptname CombatStyle extends Form Hidden - -; functions related to the General Tab values -float Function GetOffensiveMult() native -float Function GetDefensiveMult() native -float Function GetGroupOffensiveMult() native -float Function GetAvoidThreatChance() native -float Function GetMeleeMult() native -float Function GetRangedMult() native -float Function GetMagicMult() native -float Function GetShoutMult() native -float Function GetStaffMult() native -float Function GetUnarmedMult() native - -Function SetOffensiveMult(float mult) native -Function SetDefensiveMult(float mult) native -Function SetGroupOffensiveMult(float mult) native -Function SetAvoidThreatChance(float chance) native -Function SetMeleeMult(float mult) native -Function SetRangedMult(float mult) native -Function SetMagicMult(float mult) native -Function SetShoutMult(float mult) native -Function SetStaffMult(float mult) native -Function SetUnarmedMult(float mult) native - -; functions related to the Melee tab values -float Function GetMeleeAttackStaggeredMult() native -float Function GetMeleePowerAttackStaggeredMult() native -float Function GetMeleePowerAttackBlockingMult() native -float Function GetMeleeBashMult() native -float Function GetMeleeBashRecoiledMult() native -float Function GetMeleeBashAttackMult() native -float Function GetMeleeBashPowerAttackMult() native -float Function GetMeleeSpecialAttackMult() native -bool Function GetAllowDualWielding() native - -Function SetMeleeAttackStaggeredMult(float mult) native -Function SetMeleePowerAttackStaggeredMult(float mult) native -Function SetMeleePowerAttackBlockingMult(float mult) native -Function SetMeleeBashMult(float mult) native -Function SetMeleeBashRecoiledMult(float mult) native -Function SetMeleeBashAttackMult(float mult) native -Function SetMeleeBashPowerAttackMult(float mult) native -Function SetMeleeSpecialAttackMult(float mult) native -Function SetAllowDualWielding(bool allow) native - -; functions related to the Close Range tab values -float Function GetCloseRangeDuelingCircleMult() native -float Function GetCloseRangeDuelingFallbackMult() native -float Function GetCloseRangeFlankingFlankDistance() native -float Function GetCloseRangeFlankingStalkTime() native - -Function SetCloseRangeDuelingCircleMult(float mult) native -Function SetCloseRangeDuelingFallbackMult(float mult) native -Function SetCloseRangeFlankingFlankDistance(float mult) native -Function SetCloseRangeFlankingStalkTime(float mult) native - -; functions related to the LongRange tab values -float Function GetLongRangeStrafeMult() native -Function SetLongRangeStrafeMult(float mult) native - -; functions related to the Flight tab values -float Function GetFlightHoverChance() native -float Function GetFlightDiveBombChance() native -float Function GetFlightFlyingAttackChance() native - -Function SetFlightHoverChance(float chance) native -Function SetFlightDiveBombChance(float chance) native -Function SetFlightFlyingAttackChance(float mult) native - - diff --git a/modules/tests/psc_deps/Debug.psc b/modules/tests/psc_deps/Debug.psc deleted file mode 100644 index f81b8a1..0000000 --- a/modules/tests/psc_deps/Debug.psc +++ /dev/null @@ -1,115 +0,0 @@ -Scriptname Debug Hidden - -; Note that these functions will do nothing in release console builds - -; COC functionality -Function CenterOnCell(string asCellname) native global - -; COC functionality -float Function CenterOnCellAndWait(string asCellname) native global - -; player.moveto functionality -float Function PlayerMoveToAndWait(string asDestRef) native global - -; Closes the specified user log -Function CloseUserLog(string asLogName) native global - -; Outputs the string to a named debug channel (useful on the Xenon currently) -Function DebugChannelNotify(string channel, string message) native global - -; Dumps all alias fill information for the quest to the AliasDump log in Logs/Script/ -Function DumpAliasData(Quest akQuest) native global - -; Returns the config name -string Function GetConfigName() native global - -; Returns the platform name -string Function GetPlatformName() native global - -; Returns the version number string -string Function GetVersionNumber() native global - -; Displays an in-game message box -Function MessageBox(string asMessageBoxText) native global - -; Displays an in-game notification -Function Notification(string asNotificationText) native global - -; Opens a user log - fails if the log is already open -bool Function OpenUserLog(string asLogName) native global - -; Quits the game -Function QuitGame() native global - -; Toggles Foot IK on/off -Function SetFootIK(bool abFootIK) native global - -; TGM functionality -Function SetGodMode(bool abGodMode) native global - -; Forcibly sends an animation event to a reference's behavior graph -; used to bypass actor limitation on the ObjectReference version -Function SendAnimationEvent(ObjectReference arRef, string asEventName) native global - -; Start profiing a specific script - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StartScriptProfiling(string asScriptName) native global - -; Start profiling the calling stack - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StartStackProfiling() native global - -; Stop profiling a specific script - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StopScriptProfiling(string asScriptName) native global - -; Stop profiling the calling stack - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StopStackProfiling() native global - -; Takes a screenshot (Xenon only) -Function TakeScreenshot(string asFilename) native global - -; ToggleAI -Function ToggleAI() native global - -; TCL functionality -Function ToggleCollisions() native global - -; Toggles menus on/off -Function ToggleMenus() native global - -; Outputs the string to the log -; Severity is one of the following: -; 0 - Info -; 1 - Warning -; 2 - Error -Function Trace(string asTextToPrint, int aiSeverity = 0) native global - -; Outputs the current stack to the log -Function TraceStack(string asTextToPrint = "Tracing stack on request", int aiSeverity = 0) native global - -; Outputs the string to a user log - fails if the log hasn't been opened -bool Function TraceUser(string asUserLog, string asTextToPrint, int aiSeverity = 0) native global - -;Suppressable Trace -Function TraceConditional(string TextToPrint, bool ShowTrace) Global -{As Trace() but takes a second parameter bool ShowTrace (which if false suppresses the message). Used to turn off and on traces that might be otherwise annoying.} -;jduval - if ShowTrace - trace(TextToPrint) - EndIf -EndFunction - -Function TraceAndBox(string asTextToPrint, int aiSeverity = 0) global -{A convenience function to both throw a message box AND write to the trace log, since message boxes sometimes stack in weird ways and won't show up reliably.} - ;SJML - MessageBox(asTextToPrint) - Trace(asTextToPrint, aiSeverity) -EndFunction - -; Used to add a tripod to a reference (non-release builds only) -Function ShowRefPosition(ObjectReference arRef) native global - -;Prints out the players position to the database (non-release PC and Xenon builds only) -Function DBSendPlayerPosition() native global diff --git a/modules/tests/psc_deps/EffectShader.psc b/modules/tests/psc_deps/EffectShader.psc deleted file mode 100644 index 1e592a8..0000000 --- a/modules/tests/psc_deps/EffectShader.psc +++ /dev/null @@ -1,7 +0,0 @@ -Scriptname EffectShader extends Form Hidden - -; Starts playing this effect shader on the specified object for the specified length of time in seconds. Negative values indiciate "infinite" -Function Play(ObjectReference akObject, float afDuration = -1.0) native - -; Stops playing this effect shader on the specified object -Function Stop(ObjectReference akObject) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Enchantment.psc b/modules/tests/psc_deps/Enchantment.psc deleted file mode 100644 index c96ddfb..0000000 --- a/modules/tests/psc_deps/Enchantment.psc +++ /dev/null @@ -1,41 +0,0 @@ -Scriptname Enchantment extends Form Hidden - -; Is this enchantment classified as hostile? -bool Function IsHostile() native - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; return the number of the effects -int Function GetNumEffects() native - -; return the magnitude of the specified effect -float Function GetNthEffectMagnitude(int index) native - -; return the area of the specified effect -int Function GetNthEffectArea(int index) native - -; return the duration of the specified effect -int Function GetNthEffectDuration(int index) native - -; return the magic effect of the specified effect -MagicEffect Function GetNthEffectMagicEffect(int index) native - -; return the index of the costliest effect -int Function GetCostliestEffectIndex() native - -; sets the magnitude of the specified effect -Function SetNthEffectMagnitude(int index, float value) native - -; sets the area of the specified effect -Function SetNthEffectArea(int index, int value) native - -; sets the duration of the specified effect -Function SetNthEffectDuration(int index, int value) native - -; returns the base enchantment of this enchantment -Enchantment Function GetBaseEnchantment() native - -; Returns a Formlist of Keywords -FormList Function GetKeywordRestrictions() native - -; Sets the FormList of keywords -Function SetKeywordRestrictions(FormList newKeywordList) native \ No newline at end of file diff --git a/modules/tests/psc_deps/EncounterZone.psc b/modules/tests/psc_deps/EncounterZone.psc deleted file mode 100644 index 4aef1c2..0000000 --- a/modules/tests/psc_deps/EncounterZone.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname EncounterZone extends Form Hidden \ No newline at end of file diff --git a/modules/tests/psc_deps/EquipSlot.psc b/modules/tests/psc_deps/EquipSlot.psc deleted file mode 100644 index 7638267..0000000 --- a/modules/tests/psc_deps/EquipSlot.psc +++ /dev/null @@ -1,7 +0,0 @@ -Scriptname EquipSlot extends Form Hidden - -; Returns the number of parent slots -int Function GetNumParents() native - -; Returns the Nth parent slot -EquipSlot Function GetNthParent(int n) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Explosion.psc b/modules/tests/psc_deps/Explosion.psc deleted file mode 100644 index eeb117d..0000000 --- a/modules/tests/psc_deps/Explosion.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname Explosion extends Form Hidden diff --git a/modules/tests/psc_deps/Faction.psc b/modules/tests/psc_deps/Faction.psc deleted file mode 100644 index 07b9abe..0000000 --- a/modules/tests/psc_deps/Faction.psc +++ /dev/null @@ -1,131 +0,0 @@ -Scriptname Faction extends Form Hidden - -; Checks to see if the player can pay the crime gold for this faction -bool Function CanPayCrimeGold() native - -; Gets the amount of gold the player is to pay to this faction for crimes -int Function GetCrimeGold() native - -; Gets the amount of gold the player is to pay to this faction for non-violent crimes -int Function GetCrimeGoldNonViolent() native - -; Gets the amount of gold the player is to pay to this faction for violent crimes -int Function GetCrimeGoldViolent() native - -; Get the player's "infamy" with this faction (accumulated crime gold) -int Function GetInfamy() native - -; Get the player's "non-violent infamy" with this faction (accumulated non-violent crime gold) -int Function GetInfamyNonViolent() native - -; Get the player's "violent infamy" with this faction (accumulated violent crime gold) -int Function GetInfamyViolent() native - -; Gets this faction's reaction towards the other -int Function GetReaction(Faction akOther) native - -; Obtains the value of all items stolen by the player from this faction that was witnessed -int Function GetStolenItemValueCrime() native - -; Obtains the value of all items stolen by the player from this faction that was NOT witnessed -int Function GetStolenItemValueNoCrime() native - -; Is the passed in faction in this faction's crime group -bool Function IsFactionInCrimeGroup(Faction akOther) native - -; Is the player expelled from this faction? -bool Function IsPlayerExpelled() native - -; Modifies the amount of crime gold for this faction - violent or non-violent -Function ModCrimeGold(int aiAmount, bool abViolent = false) native - -; Modifies this faction's reaction towards the other faction -Function ModReaction(Faction akOther, int aiAmount) native - -; Has the player pay the crime gold for this faction -Function PlayerPayCrimeGold(bool abRemoveStolenItems = true, bool abGoToJail = true) native - -; Finds a nearby NPC in this faction and has them behave as if assaulted -Function SendAssaultAlarm() native - -; Sends the player to this faction's jail - removing inventory if requested, and to a "real" jail or not -Function SendPlayerToJail(bool abRemoveInventory = true, bool abRealJail = true) native - -; Sets this faction and the other as allies or friends - if the friend booleans are true - the specified one-way relationship -; is a friend instead of an ally -Function SetAlly(Faction akOther, bool abSelfIsFriendToOther = false, bool abOtherIsFriendToSelf = false) native - -; Sets the non-violent crime gold on this faction -Function SetCrimeGold(int aiGold) native - -; Sets the violent crime gold on this faction -Function SetCrimeGoldViolent(int aiGold) native - -; Sets this faction and the other as enemies or neutral - if the friend booleans are true - the specified one-way relationship -; is a neutral instead of an enemy -Function SetEnemy(Faction akOther, bool abSelfIsNeutralToOther = false, bool abOtherIsNeutralToSelf = false) native - -; Sets or clears the player as an enemy of this faction -Function SetPlayerEnemy(bool abIsEnemy = true) native - -; Sets or clears the expelled flag for this faction on the player -Function SetPlayerExpelled(bool abIsExpelled = true) native - -; Sets this faction's reaction towards the other -Function SetReaction(Faction akOther, int aiNewValue) native - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC - -int property kFaction_HiddenFromNPC = 0x00000001 AutoReadOnly -int property kFaction_SpecialCombat = 0x00000002 AutoReadOnly -int property kFaction_TrackCrime = 0x00000010 AutoReadOnly -int property kFaction_IgnoreMurder = 0x00000020 AutoReadOnly -int property kFaction_IgnoreAssault = 0x00000040 AutoReadOnly -int property kFaction_IgnoreStealing = 0x00000080 AutoReadOnly -int property kFaction_IgnoreTrespass = 0x00000100 AutoReadOnly -int property kFaction_NoReportCrime = 0x00000200 AutoReadOnly -int property kFaction_CrimeGoldDefaults = 0x00000400 AutoReadOnly -int property kFaction_IgnorePickpocket = 0x00000800 AutoReadOnly -int property kFaction_Vendor = 0x00001000 AutoReadOnly -int property kFaction_CanBeOwner = 0x00002000 AutoReadOnly -int property kFaction_IgnoreWerewolf = 0x00004000 AutoReadOnly - -; Not recommended unless the faction was previously a vendor -; due to the faction not having a package location the vendor -; may not be able to set up shop anywhere at all -Function MakeVendor() - SetFactionFlag(self.kFaction_Vendor) -EndFunction - -bool Function IsVendor() - return IsFactionFlagSet(self.kFaction_Vendor) -EndFunction - -Function ClearVendor() - ClearFactionFlag(self.kFaction_Vendor) -EndFunction - -bool Function IsFactionFlagSet(int flag) native -Function SetFactionFlag(int flag) native -Function ClearFactionFlag(int flag) native - -bool Function OnlyBuysStolenItems() native -Function SetOnlyBuysStolenItems(bool onlyStolen) native - -int Function GetVendorStartHour() native -Function SetVendorStartHour(int hour) native - -int Function GetVendorEndHour() native -Function SetVendorEndHour(int hour) native - -int Function GetVendorRadius() native -Function SetVendorRadius(int radius) native - -ObjectReference Function GetMerchantContainer() native -Function SetMerchantContainer(ObjectReference akContainer) native - -bool Function IsNotSellBuy() native -Function SetNotSellBuy(bool notSellBuy) native - -FormList Function GetBuySellList() native -Function SetBuySellList(FormList akList) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Form.psc b/modules/tests/psc_deps/Form.psc deleted file mode 100644 index 52162df..0000000 --- a/modules/tests/psc_deps/Form.psc +++ /dev/null @@ -1,280 +0,0 @@ -Scriptname Form Hidden - -; Returns the formID for this object -Int Function GetFormID() native - -; Obtains this form's value in gold. Will return -1 if the form doesn't have any value (like a quest) -int Function GetGoldValue() native - -; Returns if this form has the specified keyword attached -bool Function HasKeyword(Keyword akKeyword) native - -; Is the "Known" flag set for this form? -bool Function PlayerKnows() native - -; Register for the specified animation event from the specified object - returns true if it successfully registered -bool Function RegisterForAnimationEvent(ObjectReference akSender, string asEventName) native - -; Register for LOS gain and lost events between the viewer and the target -; A loss or gain event will be sent immediately, depending on whether or not the viewer is already looking at the target or not -; If the viewer is not the player, the target must be another actor -Function RegisterForLOS(Actor akViewer, ObjectReference akTarget) native - -; Register for only the first LOS gain event between the viewer and the target -; If the viewer is already looking at the target, an event will be received almost immediately -; If the viewer is not the player, the target must be another actor -Function RegisterForSingleLOSGain(Actor akViewer, ObjectReference akTarget) native - -; Register for only the first LOS lost event between the viewer and the target -; If the viewer is already not looking at the target, an event will be received almost immediately -; If the viewer is not the player, the target must be another actor -Function RegisterForSingleLOSLost(Actor akViewer, ObjectReference akTarget) native - -; Register for a single OnUpdate event, in afInterval seconds. All scripts attached to this form will get the update events -; Of course, this means you don't need to call UnregisterForUpdate() -; If you find yourself doing this: -; Event OnUpdate() -; UnregisterForUpdate() -; {Do some stuff} -; endEvent -; Then you should use RegisterForSingleUpdate instead -Function RegisterForSingleUpdate(float afInterval) native - -; Registers this form to receive events when the player sleeps and wakes up -Function RegisterForSleep() native - -; Registers this form to receive events when tracked stats are updated -Function RegisterForTrackedStatsEvent() native - -; Register for OnUpdate events, every X seconds, where X is the interval. All scripts attached to this form will get the update events -Function RegisterForUpdate(float afInterval) native - -; Register for OnUpdateGameTime events, every X hours of game time, where X is the interval. All scripts attached to this form will get the update events -Function RegisterForUpdateGameTime(float afInterval) native - -; Register for a single OnUpdateGameTime event, in afInterval hours of game time. All scripts attached to this form will get the update events -Function RegisterForSingleUpdateGameTime(float afInterval) native - -; Turns on profiling for this specific object and all scripts attached to it - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StartObjectProfiling() native - -; Turns off profiling for this specific object and all scripts attached to it - setting doesn't persist across saves -; Will do nothing on release console builds, and if the Papyrus:bEnableProfiling ini setting is off -Function StopObjectProfiling() native - -; Unregister for the specified animation event from the specified object -Function UnregisterForAnimationEvent(ObjectReference akSender, string asEventName) native - -; Unregister for any LOS events between the viewer and target -Function UnregisterForLOS(Actor akViewer, ObjectReference akTarget) native - -; Unregisters this form to receive events when the player sleeps and wakes up -Function UnregisterForSleep() native - -; Unregisters this form from receiving events when tracked stats are updated -Function UnregisterForTrackedStatsEvent() native - -; Unregister for OnUpdate events, all attached scripts will stop getting update events -Function UnregisterForUpdate() native - -; Unregister for OnUpdateGameTime events, all attached scripts will stop getting update game time events -Function UnregisterForUpdateGameTime() native - -; Animation event, sent when an object we are listening to hits one of the events we are listening for -Event OnAnimationEvent(ObjectReference akSource, string asEventName) -EndEvent - -; Event sent when you have been unregistered from receiving an animation event because the target -; object's animation graph has been unloaded -Event OnAnimationEventUnregistered(ObjectReference akSource, string asEventName) -EndEvent - -; LOS event, sent whenever the viewer first sees the target (after registering) -Event OnGainLOS(Actor akViewer, ObjectReference akTarget) -EndEvent - -; Lost LOS event, sent whenever the viewer first loses sight of the target (after registering) -Event OnLostLOS(Actor akViewer, ObjectReference akTarget) -EndEvent - -; Received when the player sleeps. Start and desired end time are in game time days (after registering) -Event OnSleepStart(float afSleepStartTime, float afDesiredSleepEndTime) -EndEvent - -; Received when the player stops sleeping - whether naturally or interrupted (after registering) -Event OnSleepStop(bool abInterrupted) -EndEvent - -; Event received when a tracked stat is updated for the player -Event OnTrackedStatsEvent(string arStatName, int aiStatValue) -EndEvent - -; Update event, sent every X seconds while this form is registered for them -Event OnUpdate() -EndEvent - -; Update event, sent every X hours of game time while this form is registered for them -Event OnUpdateGameTime() -EndEvent - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC - -; Returns the typecode for this form object -Int Function GetType() native - -; returns the form's name, full name if possible -string Function GetName() native - -; sets the name of the form -Function SetName(string name) native - -; returns the weight of the form -float Function GetWeight() native - -; sets the weight of the form -Function SetWeight(float weight) native - -; sets the gold value of the form -Function SetGoldValue(int value) native - -; returns the number of keywords on the form -int Function GetNumKeywords() native - -; returns the keyword at the specified index -Keyword Function GetNthKeyword(int index) native - -; returns all keywords of the form -Keyword[] Function GetKeywords() native - -bool Function HasKeywordString(string s) - Keyword k = Keyword.GetKeyword(s) - if k == None - return false - endif - return HasKeyword(k) -endFunction - -; Sets whether the player knows this form -; Should only be used for Magic Effects, -; Words of Power, and Enchantments -Function SetPlayerKnows(bool knows) native - -; Registers for OnKeyDown and OnKeyUp events for the given keycode. -Function RegisterForKey(int keyCode) native -Function UnregisterForKey(int keyCode) native -Function UnregisterForAllKeys() native - -Event OnKeyDown(int keyCode) -EndEvent - -Event OnKeyUp(int keyCode, float holdTime) -EndEvent - -; Registers for OnControlDown and OnControlUp events for the given control. -; For a list of valid controls, see Input.psc. -Function RegisterForControl(string control) native -Function UnregisterForControl(string control) native -Function UnregisterForAllControls() native - -Event OnControlDown(string control) -EndEvent - -Event OnControlUp(string control, float holdTime) -EndEvent - -; Registers for OnMenuOpen and OnMenuClose events for the given menu. -; Registrations have to be refreshed after each game load. -; For a list of valid menu names, see UI.psc. -Function RegisterForMenu(string menuName) native -Function UnregisterForMenu(string menuName) native -Function UnregisterForAllMenus() native - -Event OnMenuOpen(string menuName) -endEvent - -Event OnMenuClose(string menuName) -endEvent - -; Registers a custom event callback for given event name. -; Registrations have to be refreshed after each game load. -; -; Examples: -; RegisterForModEvent("myCustomEvent", "MyModEventCallback") -; -; Event signature of custom event callbacks: -; Event MyModEventCallback(string eventName, string strArg, float numArg, Form sender) -; endEvent -; -Function RegisterForModEvent(string eventName, string callbackName) native -Function UnregisterForModEvent(string eventName) native -Function UnregisterForAllModEvents() native - -; Sends custom event with given generic parameters. -Function SendModEvent(string eventName, string strArg = "", float numArg = 0.0) native - -; Registers for OnPlayerCameraState events -Function RegisterForCameraState() native -Function UnregisterForCameraState() native - -Event OnPlayerCameraState(int oldState, int newState) -EndEvent - -; Registers for OnCrosshairRefChange events -Function RegisterForCrosshairRef() native -Function UnregisterForCrosshairRef() native - -; Note: ref is none for no target -Event OnCrosshairRefChange(ObjectReference ref) -EndEvent - -Function RegisterForActorAction(int actionType) native -Function UnregisterForActorAction(int actionType) native - -; ActionTypes -; 0 - Weapon Swing (Melee weapons that are swung, also barehand) -; 1 - Spell Cast (Spells and staves) -; 2 - Spell Fire (Spells and staves) -; 3 - Voice Cast -; 4 - Voice Fire -; 5 - Bow Draw -; 6 - Bow Release -; 7 - Unsheathe Begin -; 8 - Unsheathe End -; 9 - Sheathe Begin -; 10 - Sheathe End -; Slots -; 0 - Left Hand -; 1 - Right Hand -; 2 - Voice -Event OnActorAction(int actionType, Actor akActor, Form source, int slot) -EndEvent - -; Registers the script for when a QueueNiNodeUpdate is called -Function RegisterForNiNodeUpdate() native -Function UnregisterForNiNodeUpdate() native - -Event OnNiNodeUpdate(ObjectReference akActor) -EndEvent - -; Returns a temporary clone of this form -Form Function TempClone() native - -; Returns whether this Form has a World Model (fast) -bool Function HasWorldModel() native - -; Returns the world model path of this Form, if it has a world model -string Function GetWorldModelPath() native -Function SetWorldModelPath(string path) native - -; Returns the number of texture sets the world model has, if its textures can be swapped -int Function GetWorldModelNumTextureSets() native - -; Returns the Nth texture set of the world model, if the textures can be swapped -TextureSet Function GetWorldModelNthTextureSet(int n) native - -; Sets the world models Nth texture set, if the textures can be set -Function SetWorldModelNthTextureSet(TextureSet nSet, int n) native - -; Returns whether this Form is playable, only applied to Forms with the playable flag -bool Function IsPlayable() native \ No newline at end of file diff --git a/modules/tests/psc_deps/FormList.psc b/modules/tests/psc_deps/FormList.psc deleted file mode 100644 index 4e3b7fe..0000000 --- a/modules/tests/psc_deps/FormList.psc +++ /dev/null @@ -1,31 +0,0 @@ -Scriptname FormList extends Form - -; Adds the given form to this form list -Function AddForm(Form apForm) native - -; Finds the specified form in the form list and returns its index. -; If not found, returns a negative number -int Function Find(Form apForm) native - -; Returns the number of forms in the list -int Function GetSize() native - -; Returns the form at index 'aiIndex' in the list -Form Function GetAt(int aiIndex) native - -; Queries the form list to see if it contains the passed in form -bool Function HasForm(Form akForm) native - -; Removes the given added form from this form list -Function RemoveAddedForm(Form apForm) native - -; Removes all script added forms from this form list -Function Revert() native - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; Returns a Form array of this list (Invalid entries will be None) -Form[] Function ToArray() native - -; Adds an Array of Forms to this list -Function AddForms(Form[] forms) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Game.psc b/modules/tests/psc_deps/Game.psc deleted file mode 100644 index 7dd4f1e..0000000 --- a/modules/tests/psc_deps/Game.psc +++ /dev/null @@ -1,440 +0,0 @@ -Scriptname Game Hidden - -; Adds the specified achievement to the player's profile -Function AddAchievement(int aiAchievementID) native global - -; Add the specified number of perk points to the player -Function AddPerkPoints(int aiPerkPoints) native global - -; Advance the given skill on the player by the provided amount of skill usage -Function AdvanceSkill(string asSkillName, float afMagnitude) native global - -; Adds a ball-and-socket constraint between two rigid bodies, identified by their ref and node names -bool Function AddHavokBallAndSocketConstraint( ObjectReference arRefA, string arRefANode, ObjectReference arRefB, string arRefBNode, float afRefALocalOffsetX = 0.0, float afRefALocalOffsetY = 0.0, float afRefALocalOffsetZ = 0.0, float afRefBLocalOffsetX = 0.0, float afRefBLocalOffsetY = 0.0, float afRefBLocalOffsetZ = 0.0) native global - -; Removes any constraint between two rigid bodies -bool Function RemoveHavokConstraints(ObjectReference arFirstRef, string arFirstRefNodeName, ObjectReference arSecondRef, string arSecondRefNodeName) native global - -; Calculates how much a x point favor would cost the player -int Function CalculateFavorCost(int aiFavorPrice) native global - -; Clears the prison variables on the player -Function ClearPrison() native global - -; Clears temp effects from game -Function ClearTempEffects() native global - -; Disables the user's controls -Function DisablePlayerControls(bool abMovement = true, bool abFighting = true, bool abCamSwitch = false, bool abLooking = false, \ - bool abSneaking = false, bool abMenu = true, bool abActivate = true, bool abJournalTabs = false, int aiDisablePOVType = 0) native global - -; Enables the user's controls -Function EnablePlayerControls(bool abMovement = true, bool abFighting = true, bool abCamSwitch = true, bool abLooking = true, \ - bool abSneaking = true, bool abMenu = true, bool abActivate = true, bool abJournalTabs = true, int aiDisablePOVType = 0) native global - -; Enables or disables the ability to fast travel -Function EnableFastTravel(bool abEnable = true) native global - -; Fades out the game to black, or vice versa -Function FadeOutGame(bool abFadingOut, bool abBlackFade, float afSecsBeforeFade, float afFadeDuration) native global - -; Fast-travels the player to the specified object's location -Function FastTravel(ObjectReference akDestination) native global - -; Finds the closest reference of a given base object within a given radius of a location -ObjectReference Function FindClosestReferenceOfType(Form arBaseObject, float afX, float afY, float afZ, float afRadius) native global - -; Finds a random reference of a given base object within a given radius of a location -ObjectReference Function FindRandomReferenceOfType(Form arBaseObject, float afX, float afY, float afZ, float afRadius) native global - -; Finds the closest reference of any base object in the list within a given radius of a location -ObjectReference Function FindClosestReferenceOfAnyTypeInList(FormList arBaseObjects, float afX, float afY, float afZ, float afRadius) native global - -; Finds a random reference of a any base object in the list within a given radius of a location -ObjectReference Function FindRandomReferenceOfAnyTypeInList(FormList arBaseObjects, float afX, float afY, float afZ, float afRadius) native global - -; Finds the closest reference of a given base object within a given radius of a reference -ObjectReference Function FindClosestReferenceOfTypeFromRef(Form arBaseObject, ObjectReference arCenter, float afRadius) global - return FindClosestReferenceOfType(arBaseObject, arCenter.X, arCenter.Y, arCenter.Z, afRadius) -endFunction - -; Finds a random reference of a given base object within a given radius of a reference -ObjectReference Function FindRandomReferenceOfTypeFromRef(Form arBaseObject, ObjectReference arCenter, float afRadius) global - return FindRandomReferenceOfType(arBaseObject, arCenter.X, arCenter.Y, arCenter.Z, afRadius) -endFunction - -; Finds the closest reference of a given base object within a given radius of a reference -ObjectReference Function FindClosestReferenceOfAnyTypeInListFromRef(FormList arBaseObjects, ObjectReference arCenter, float afRadius) global - return FindClosestReferenceOfAnyTypeInList(arBaseObjects, arCenter.X, arCenter.Y, arCenter.Z, afRadius) -endFunction - -; Finds a random reference of a given base object within a given radius of a reference -ObjectReference Function FindRandomReferenceOfAnyTypeInListFromRef(FormList arBaseObjects, ObjectReference arCenter, float afRadius) global - return FindRandomReferenceOfAnyTypeInList(arBaseObjects, arCenter.X, arCenter.Y, arCenter.Z, afRadius) -endFunction - -; Finds the closest actor within a given radius of a location -Actor Function FindClosestActor(float afX, float afY, float afZ, float afRadius) native global - -; Finds a random actor within a given radius of a location -Actor Function FindRandomActor(float afX, float afY, float afZ, float afRadius) native global - -; Finds the closest actor within a given radius of a reference -Actor Function FindClosestActorFromRef(ObjectReference arCenter, float afRadius) global - return FindClosestActor(arCenter.X, arCenter.Y, arCenter.Z, afRadius) -endFunction - -; Finds a random actor within a given radius of a reference -Actor Function FindRandomActorFromRef(ObjectReference arCenter, float afRadius) global - return FindRandomActor(arCenter.X, arCenter.Y, arCenter.Z, afRadius) -endFunction - -; Make the player got to 3rd person camera mode -Function ForceThirdPerson() native global - -; Make the player got to 1st person camera mode -Function ForceFirstPerson() native global - -; Show the players first person geometry. -Function ShowFirstPersonGeometry( bool abShow = true ) native global - -; Returns the form specified by the ID -Form Function GetForm(int aiFormID) native global - -; Returns the form specified by the ID originating in the given file -Form Function GetFormFromFile(int aiFormID, string asFilename) native global - -; Obtains the value of a game setting - one for each type of game setting -float Function GetGameSettingFloat(string asGameSetting) native global -int Function GetGameSettingInt(string asGameSetting) native global -string Function GetGameSettingString(string asGameSetting) native global - -; Returns the player actor -Actor Function GetPlayer() native global - -; Returns the reference the player is currently grabbing -ObjectReference Function GetPlayerGrabbedRef() native global - -; Returns the horse last ridden by the player -Actor Function GetPlayersLastRiddenHorse() native global - -; Returns the X position of the Sun. -float Function GetSunPositionX() native global - -; Returns the Y position of the Sun. -float Function GetSunPositionY() native global - -; Returns the Z position of the Sun. -float Function GetSunPositionZ() native global - -; Returns the number of days spent in play -float Function GetRealHoursPassed() native global - -; Increment the given skill on the player by the one point -Function IncrementSkill(string asSkillName) native global - -; Increment the given skill on the player by the given number of points -Function IncrementSkillBy(string asSkillName, int aiCount) native global - -; Modifies the specified MiscStat by the given amount. -Function IncrementStat(string asStatName, int aiModAmount = 1) native global - -; Are the activation controls enabled? -bool Function IsActivateControlsEnabled() native global - -; Are the camera switch controls enabled? -bool Function IsCamSwitchControlsEnabled() native global - -; Is fast travel controls enabled? Returns false if EnableFastTravel(false) has been called -bool Function IsFastTravelControlsEnabled() native global - -; Is fast travel enabled? -bool Function IsFastTravelEnabled() native global - -; Are the fighting controls enabled? -bool Function IsFightingControlsEnabled() native global - -; Are the journal menu controls enabled? -bool Function IsJournalControlsEnabled() native global - -; Are the looking controls enabled? -bool Function IsLookingControlsEnabled() native global - -; Are the menu controls enabled? -bool Function IsMenuControlsEnabled() native global - -; Are the movement controls enabled? -bool Function IsMovementControlsEnabled() native global - -; Is the player looking at the sun? -bool Function IsPlayerSungazing() native global - -; Are the sneaking controls enabled? -bool Function IsSneakingControlsEnabled() native global - -; Is the specified Word of Power Unlocked? -bool Function IsWordUnlocked(WordOfPower akWord) native global - -; Plays a bink video - does not return until bink has finished, use with care! -Function PlayBink(string asFileName, bool abInterruptible = false, bool abMuteAudio = true, bool abMuteMusic = true, \ - bool abLetterbox = true ) native global - -; Precaches character gen data. -Function PrecacheCharGen() native global - -; Clears Precached character gen data. -Function PrecacheCharGenClear() native global - -; Queries the given stat and returns its value -int Function QueryStat(string asStat) native global - -; Forces the game back to the main menu -Function QuitToMainMenu() native global - -; Request that an auto-save be made -Function RequestAutoSave() native global - -; Requests the specified model -Function RequestModel(string asModelName) native global - -; Request that a normal save be made -Function RequestSave() native global - -; Has the player serve their prison time -Function ServeTime() native global - -; Finds an actor in high who can detect the player to call werewolf crime on the player -Function SendWereWolfTransformation() native global - -; Called as we enter/exit beast form -Function SetBeastForm(bool abEntering) native global - -; Sets the camera target actor -Function SetCameraTarget(Actor arTarget) native global - -; Sets or clears "cart mode" for the HUD -Function SetHudCartMode(bool abSetCartMode = true) native global - -; Informs the game whether we are in CharGen or not -Function SetInChargen(bool abDisableSaving, bool abDisableWaiting, bool abShowControlsDisabledMessage) native global - -; Enables or disables the AI driven flag on Player -Function SetPlayerAIDriven(bool abAIDriven = true) native global - -; Enables or disables crime reporting on Player -Function SetPlayerReportCrime(bool abReportCrime = true) native global - -; Set the players sitting camera rotation - in degrees, offset from the standard angle. -Function SetSittingRotation(float afValue) native global - -; Shakes the object from the location of the passed-in object. If none, it will shake the camera from the player's location. -; Strength is clamped from 0 to 1 -; Duration in seconds. By default (0.0) use the game setting. -Function ShakeCamera(ObjectReference akSource = None, float afStrength = 0.5, float afDuration = 0.0) native global - -; Shakes the controller for the specified length of time (in seconds). The strength values are clamped from 0 to 1 -Function ShakeController(float afSmallMotorStrength, float afBigMotorStreangth, float afDuration) native global - -; Displays the race/sex menu -Function ShowRaceMenu() native global -Function ShowLimitedRaceMenu() native global - -; Title Sequence menu functions -Function ShowTitleSequenceMenu() native global -Function HideTitleSequenceMenu() native global -Function StartTitleSequence(string asSequenceName) native global - -; Allow or disallow player requests to have a flying mount land. -Function SetAllowFlyingMountLandingRequests(bool abAllow) native global - -; Sets the Image Space Modifier that is triggered when the player gazes at the sun. -Function SetSunGazeImageSpaceModifier(ImageSpaceModifier apImod = NONE ) native global - -; Displays the training menu based on passed in trainer actor -Function ShowTrainingMenu(Actor aTrainer) native global - -; Teaches the specified word of power to the player -Function TeachWord(WordOfPower akWord) native global - -; Trigger screen blood with the given count -Function TriggerScreenBlood(int aiValue) native global - -; Unlocks the specified word of power so the player can use it -Function UnlockWord(WordOfPower akWord) native global - -; Returns true if we're using a gamepad -bool Function UsingGamepad() native global - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; Get/Set Perk Points -int Function GetPerkPoints() global native -Function SetPerkPoints(int perkPoints) global native -Function ModPerkPoints(int perkPoints) global native - -; returns the number of active mods -int Function GetModCount() native global - -; returns the index of the specified mod -int Function GetModByName(string name) native global - -; returns the name of the mod at the specified modIndex -string Function GetModName(int modIndex) native global - -; returns the author of the mod at the specified modIndex -string Function GetModAuthor(int modIndex) native global - -; returns the description of the mod at the specified modIndex -string Function GetModDescription(int modIndex) native global - -; gets the count of mods the specified mod depends upon -int Function GetModDependencyCount(int modIndex) native global - -; gets the index of the nth mod dependency of the specfied mod -int Function GetNthModDependency(int modIndex, int n) native global - -; GameSetting functions - SKSE 1.5.10 -Function SetGameSettingFloat(string setting, float value) global native -Function SetGameSettingInt(string setting, int value) global native -Function SetGameSettingBool(string setting, bool value) global native -Function SetGameSettingString(string setting, string value) global native - -; save/load game -Function SaveGame(string name) native global -Function LoadGame(string name) native global - -; TintMasks (AARRGGBB) - -; Returns the total number of tints for the player -int Function GetNumTintMasks() native global - -; Returns the color of the Nth tint mask -int Function GetNthTintMaskColor(int n) native global - -; Returns the type of the Nth tint mask -int Function GetNthTintMaskType(int n) native global - -; Sets the color of the Nth tint mask -Function SetNthTintMaskColor(int n, int color) native global - -; Returns the texture path of the Nth tint mask -string Function GetNthTintMaskTexturePath(int n) native global - -; Sets the texturepath of the Nth tint mask -Function SetNthTintMaskTexturePath(string path, int n) native global - -; Types -; 0 - Frekles -; 1 - Lips -; 2 - Cheeks -; 3 - Eyeliner -; 4 - Upper Eyesocket -; 5 - Lower Eyesocket -; 6 - SkinTone -; 7 - Warpaint -; 8 - Frownlines -; 9 - Lower Cheeks -; 10 - Nose -; 11 - Chin -; 12 - Neck -; 13 - Forehead -; 14 - Dirt - -; Returns how many indexes there are for this type -int Function GetNumTintsByType(int type) native global - -; Returns the color for the particular tintMask type and index -int Function GetTintMaskColor(int type, int index) global native - -; Sets the tintMask color for the particular type and index -Function SetTintMaskColor(int color, int type, int index) global native - -; Returns the texture path for the particular tintMask type and index -string Function GetTintMaskTexturePath(int type, int index) global native - -; Sets the tintMask texture for the particular type and index -Function SetTintMaskTexturePath(string path, int type, int index) global native - -; Updates tintMask colors without updating the entire model -Function UpdateTintMaskColors() global native - -; Updates the players hair color immediately -Function UpdateHairColor() global native - -; Returns the character's current camera state -; 0 - first person -; 1 - auto vanity -; 2 - VATS -; 3 - free -; 4 - iron sights -; 5 - furniture -; 6 - transition -; 7 - tweenmenu -; 8 - third person 1 -; 9 - third person 2 -; 10 - horse -; 11 - bleedout -; 12 - dragon -int Function GetCameraState() global native - -; set a misc stat value -; use QueryStat to read the value -Function SetMiscStat(string name, int value) global native - -; Sets the players last ridden horse, None will clear the lastRiddenHorse -Function SetPlayersLastRiddenHorse(Actor horse) global native - -; Returns the legendary level for the skill -; -1 indicates the particular skill cannot have a legendary level -; DEPRECATED -int Function GetSkillLegendaryLevel(string actorValue) global - return ActorValueInfo.GetActorValueInfoByName(actorValue).GetSkillLegendaryLevel() -EndFunction - -; Sets the legendary level for the skill -; DEPRECATED -Function SetSkillLegendaryLevel(string actorValue, int level) global - ActorValueInfo.GetActorValueInfoByName(actorValue).SetSkillLegendaryLevel(level) -EndFunction - -; Returns the players experience for this level (not total experience) -float Function GetPlayerExperience() global native - -; Sets the players experience, does not trigger level-up notification -Function SetPlayerExperience(float exp) global native - -; Calculates the experience required for to level-up -; (fXPLevelUpBase + currentLevel * fXPLevelUpMult) -float Function GetExperienceForLevel(int currentLevel) global native - -; Returns true if in run mode, false if in walk mode -; Does not reflect actual movement state, only the control mode -bool Function GetPlayerMovementMode() global native - -; Updates the camera when changing Shoulder positions -Function UpdateThirdPerson() global native - -; Hotkeys 0-7 reflect keys 1-8 -; Unbinds a favorited item bound to the specified hotkey -Function UnbindObjectHotkey(int hotkey) global native - -; Returns the base form object that is bound to the specified hotkey -Form Function GetHotkeyBoundObject(int hotkey) global native - -; Returns if base form is favorited by the player -bool Function IsObjectFavorited(Form form) global native - -; Same as GetForm, but also works for formIds >= 0x80000000 -Form Function GetFormEx(int formId) global native - -; Returns the object reference the player is in dialogue with -ObjectReference Function GetDialogueTarget() global native - -; Returns the current crosshair ref -ObjectReference Function GetCurrentCrosshairRef() global native - -; Returns the currently selected ref in the console -ObjectReference Function GetCurrentConsoleRef() global native - -; Sets the player level -Function SetPlayerLevel(int level) global native \ No newline at end of file diff --git a/modules/tests/psc_deps/GlobalVariable.psc b/modules/tests/psc_deps/GlobalVariable.psc deleted file mode 100644 index 88ec055..0000000 --- a/modules/tests/psc_deps/GlobalVariable.psc +++ /dev/null @@ -1,34 +0,0 @@ -Scriptname GlobalVariable extends Form Hidden - -; Obtains the global's current value -float Function GetValue() native - -; Sets the global's current value -Function SetValue(float afNewValue) native - -; convenience functions for ints -int Function GetValueInt() - return GetValue() as int -endFunction - -; Sets the global's current value -Function SetValueInt(int aiNewValue) - SetValue(aiNewValue as float) -endFunction - -; Easy access to the global's value -float Property Value Hidden - float Function get() - return GetValue() - EndFunction - - Function set(float afValue) - SetValue(afValue) - EndFunction -EndProperty - -; the threadsafe way to modify a global variable -float Function Mod(float afHowMuch) - Value += afHowMuch - Return Value -EndFunction diff --git a/modules/tests/psc_deps/HeadPart.psc b/modules/tests/psc_deps/HeadPart.psc deleted file mode 100644 index 162ec61..0000000 --- a/modules/tests/psc_deps/HeadPart.psc +++ /dev/null @@ -1,27 +0,0 @@ -Scriptname HeadPart extends Form Hidden - -int Property Type_Misc = 0 AutoReadOnly -int Property Type_Face = 1 AutoReadOnly -int Property Type_Eyes = 2 AutoReadOnly -int Property Type_Hair = 3 AutoReadOnly -int Property Type_FacialHair = 4 AutoReadOnly -int Property Type_Scar = 5 AutoReadOnly -int Property Type_Brows = 6 AutoReadOnly - -HeadPart Function GetHeadPart(string name) native global - -; Returns the head part type -int Function GetType() native - -int Function GetNumExtraParts() native -HeadPart Function GetNthExtraPart(int n) native - -bool Function HasExtraPart(HeadPart p) native -int Function GetIndexOfExtraPart(HeadPart p) native - -; Returns a formlist of the valid races for this head part -FormList Function GetValidRaces() native -Function SetValidRaces(FormList vRaces) native - -; Returns whether the head part is an extra part -bool Function IsExtraPart() native \ No newline at end of file diff --git a/modules/tests/psc_deps/Idle.psc b/modules/tests/psc_deps/Idle.psc deleted file mode 100644 index 61c588e..0000000 --- a/modules/tests/psc_deps/Idle.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname Idle extends Form Hidden diff --git a/modules/tests/psc_deps/ImageSpaceModifier.psc b/modules/tests/psc_deps/ImageSpaceModifier.psc deleted file mode 100644 index d129360..0000000 --- a/modules/tests/psc_deps/ImageSpaceModifier.psc +++ /dev/null @@ -1,16 +0,0 @@ -Scriptname ImageSpaceModifier extends Form Hidden - -; Applies this modifier with the specified strength (which is not clamped) -Function Apply(float afStrength = 1.0) native - -; Adds this modifier to the cross-fade chain, removing the previous modifier, and fading over the specified duration (in seconds) -Function ApplyCrossFade(float afFadeDuration = 1.0) native - -; Disables this modifier and enables the new one, "popping" between the two. Will not interrupt any running cross-fade (if the modifiers aren't the ones fading) -Function PopTo(ImageSpaceModifier akNewModifier, float afStrength = 1.0) native - -; Removes this modifier -Function Remove() native - -; Removes whatever modifier is on the cross-fade chain, fading it out -Function RemoveCrossFade(float afFadeDuration = 1.0) native global \ No newline at end of file diff --git a/modules/tests/psc_deps/ImpactDataSet.psc b/modules/tests/psc_deps/ImpactDataSet.psc deleted file mode 100644 index 3417cea..0000000 --- a/modules/tests/psc_deps/ImpactDataSet.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname ImpactDataSet extends Form Hidden diff --git a/modules/tests/psc_deps/Input.psc b/modules/tests/psc_deps/Input.psc deleted file mode 100644 index 99c6add..0000000 --- a/modules/tests/psc_deps/Input.psc +++ /dev/null @@ -1,38 +0,0 @@ -Scriptname Input Hidden - -; returns whether a key is pressed -bool Function IsKeyPressed(Int dxKeycode) global native - -; taps the specified key -Function TapKey(Int dxKeycode) global native - -; holds down the specified key until released -Function HoldKey(Int dxKeycode) global native - -; releases the specified key -Function ReleaseKey(Int dxKeycode) global native - -; how many keys are pressed -int Function GetNumKeysPressed() global native - -; for walking over the pressed keys -int Function GetNthKeyPressed(int n) global native - -; returns keycode bound to a control for given device -; -; Valid controls: -; "Forward", "Back", "Strafe Left", "Strafe Right", "Move", "Look", "Left Attack/Block", "Right Attack/Block" -; "Activate", "Ready Weapon", "Tween Menu", "Toggle POV", "Zoom Out", "Zoom In", "Jump", "Sprint", "Shout", -; "Sneak", "Run", "Toggle Always Run", "Auto-Move", "Favorites", "Hotkey1", "Hotkey2", "Hotkey3", "Hotkey4", -; "Hotkey5", "Hotkey6", "Hotkey7", "Hotkey8", "Quicksave", "Quickload", "Wait", "Journal", "Pause", "Screenshot", -; "Multi-Screenshot", "Console", "CameraPath", "Quick Inventory", "Quick Magic", "Quick Stats", "Quick Map" -; -; Valid device types: -; (default) auto detect -; 0 keyboard -; 1 mouse -; 2 gamepad -int Function GetMappedKey(string control, int deviceType = 0xFF) global native - -; returns name of control bound to given keycode, or "" if unbound -string Function GetMappedControl(int keycode) global native \ No newline at end of file diff --git a/modules/tests/psc_deps/Key.psc b/modules/tests/psc_deps/Key.psc deleted file mode 100644 index db2fea4..0000000 --- a/modules/tests/psc_deps/Key.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname Key extends MiscObject Hidden \ No newline at end of file diff --git a/modules/tests/psc_deps/Keyword.psc b/modules/tests/psc_deps/Keyword.psc deleted file mode 100644 index 0396d4c..0000000 --- a/modules/tests/psc_deps/Keyword.psc +++ /dev/null @@ -1,16 +0,0 @@ -Scriptname Keyword Extends Form Hidden - -; Sends this keyword as a story event to the story manager -Function SendStoryEvent(Location akLoc = None, ObjectReference akRef1 = None, ObjectReference akRef2 = None, int aiValue1 = 0, \ - int aiValue2 = 0) native - -; Sends this keyword as a story event to the story manager and waits for it to be processed. Returns true if a quest was started. -bool Function SendStoryEventAndWait(Location akLoc = None, ObjectReference akRef1 = None, ObjectReference akRef2 = None, \ - int aiValue1 = 0, int aiValue2 = 0) native - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; return the keyword with the specified key -Keyword Function GetKeyword(string key) global native - -; return the string value of the keyword -string Function GetString() native \ No newline at end of file diff --git a/modules/tests/psc_deps/LeveledItem.psc b/modules/tests/psc_deps/LeveledItem.psc deleted file mode 100644 index 92faf27..0000000 --- a/modules/tests/psc_deps/LeveledItem.psc +++ /dev/null @@ -1,23 +0,0 @@ -Scriptname LeveledItem extends Form Hidden - -; Adds the given count of the given form to the under the given level in this leveled list -Function AddForm(Form apForm, int aiLevel, int aiCount) native - -; Removes all script added forms from this leveled list -Function Revert() native - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -int function GetChanceNone() native -Function SetChanceNone(int chance) native - -GlobalVariable Function GetChanceGlobal() native -Function SetChanceGlobal(GlobalVariable glob) native - -int Function GetNumForms() native -Form Function GetNthForm(int n) native - -int Function GetNthLevel(int n) native -Function SetNthLevel(int n, int level) native - -int Function GetNthCount(int n) native -Function SetNthCount(int n, int count) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Light.psc b/modules/tests/psc_deps/Light.psc deleted file mode 100644 index 3efd25f..0000000 --- a/modules/tests/psc_deps/Light.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname Light extends Form Hidden diff --git a/modules/tests/psc_deps/Location.psc b/modules/tests/psc_deps/Location.psc deleted file mode 100644 index af1556c..0000000 --- a/modules/tests/psc_deps/Location.psc +++ /dev/null @@ -1,49 +0,0 @@ -Scriptname Location extends Form Hidden - -; Returns the float value attached to the specified keyword attached to this location -float Function GetKeywordData(Keyword akKeyword) native - -; Returns the number of alive references matching the specified reference type -int Function GetRefTypeAliveCount(LocationRefType akRefType) native - -; Returns the number of dead references matching the specified reference type -int Function GetRefTypeDeadCount(LocationRefType akRefType) native - -; Returns if these two locations have a common parent - filtered with the keyword, if provided -bool Function HasCommonParent(Location akOther, Keyword akFilter = None) native - -; Returns if this location has the specified reference type -bool Function HasRefType(LocationRefType akRefType) native - -; Returns whether this location is flagged as "cleared" or not -bool Function IsCleared() native - -; Returns whether the other location is a child of this one -bool Function IsChild(Location akOther) native - -; Is this location loaded in game? -bool Function IsLoaded() native - -bool Function IsSameLocation(Location akOtherLocation, Keyword akKeyword = None) -{Returns true if the calling location is the same as the supplied location - if an optional keyword is supplied, it also returns true if the locations share a parent with that keyword, or if either location is a child of the other and the other has that keyword.} -;jduvall - bool bmatching = self == akOtherLocation - if !bmatching && akKeyword - bmatching = HasCommonParent(akOtherLocation, akKeyword) - - if !bmatching && akOtherLocation.HasKeyword(akKeyword) - bmatching = akOtherLocation.IsChild(self) - elseif !bmatching && self.HasKeyword(akKeyword) - bmatching = self.IsChild(akOtherLocation) - endif - - endif - return bmatching -endFunction - - -; Sets the specified keyword's data on the location -Function SetKeywordData(Keyword akKeyword, float afData) native - -; Sets this location as cleared or not -Function SetCleared(bool abCleared = true) native \ No newline at end of file diff --git a/modules/tests/psc_deps/LocationRefType.psc b/modules/tests/psc_deps/LocationRefType.psc deleted file mode 100644 index bce6510..0000000 --- a/modules/tests/psc_deps/LocationRefType.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname LocationRefType extends Keyword Hidden \ No newline at end of file diff --git a/modules/tests/psc_deps/MagicEffect.psc b/modules/tests/psc_deps/MagicEffect.psc deleted file mode 100644 index fd6afca..0000000 --- a/modules/tests/psc_deps/MagicEffect.psc +++ /dev/null @@ -1,94 +0,0 @@ -Scriptname MagicEffect extends Form Hidden -; Get the Associated Skill for this MagicEffect -string Function GetAssociatedSkill() native - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -Function SetAssociatedSkill(string skill) native - -string Function GetResistance() native -Function SetResistance(string skill) native - -; Hostile 0x00000001 -; Recover 0x00000002 -; Detrimental 0x00000004 -; NoHitEvent 0x00000010 -; DispelKeywords 0x00000100 -; NoDuration 0x00000200 -; NoMagnitude 0x00000400 -; NoArea 0x00000800 -; FXPersist 0x00001000 -; GloryVisuals 0x00004000 -; HideInUI 0x00008000 -; NoRecast 0x00020000 -; Magnitude 0x00200000 -; Duration 0x00400000 -; Painless 0x04000000 -; NoHitEffect 0x08000000 -; NoDeathDispel 0x10000000 - -bool Function IsEffectFlagSet(int flag) native -Function SetEffectFlag(int flag) native -Function ClearEffectFlag(int flag) native - -float Function GetCastTime() native -Function SetCastTime(float castTime) native - -int Function GetSkillLevel() native -Function SetSkillLevel(int level) native - -int Function GetArea() native -Function SetArea(int area) native - -float Function GetSkillUsageMult() native -Function SetSkillUsageMult(float usageMult) native - -float Function GetBaseCost() native -Function SetBaseCost(float cost) native - -Light Function GetLight() native -Function SetLight(Light obj) native - -EffectShader Function GetHitShader() native -Function SetHitShader(EffectShader obj) native - -EffectShader Function GetEnchantShader() native -Function SetEnchantShader(EffectShader obj) native - -Projectile Function GetProjectile() native -Function SetProjectile(Projectile obj) native - -Explosion Function GetExplosion() native -Function SetExplosion(Explosion obj) native - -Art Function GetCastingArt() native -Function SetCastingArt(Art obj) native - -Art Function GetHitEffectArt() native -Function SetHitEffectArt(Art obj) native - -Art Function GetEnchantArt() native -Function SetEnchantArt(Art obj) native - -ImpactDataSet Function GetImpactDataSet() native -Function SetImpactDataSet(ImpactDataSet obj) native - -Spell Function GetEquipAbility() native -Function SetEquipAbility(Spell obj) native - -ImageSpaceModifier Function GetImageSpaceMod() native -Function SetImageSpaceMod(ImageSpaceModifier obj) native - -Perk Function GetPerk() native -Function SetPerk(Perk obj) native - -int Function GetCastingType() native -; Constant Effect 0 -; Fire And Forget 1 -; Concentration 2 - -int Function GetDeliveryType() native -; Self 0 -; Contact 1 -; Aimed 2 -; Target Actor 3 -; Target Location 4 \ No newline at end of file diff --git a/modules/tests/psc_deps/Math.psc b/modules/tests/psc_deps/Math.psc deleted file mode 100644 index 4200697..0000000 --- a/modules/tests/psc_deps/Math.psc +++ /dev/null @@ -1,49 +0,0 @@ -Scriptname Math Hidden - -; Calculates the absolute value of the passed in value - N for N, and N for (-N) -float Function abs(float afValue) global native - -; Calculates the arccosine of the passed in value, returning degrees -float Function acos(float afValue) global native - -; Calculates the arcsine of the passed in value, returning degrees -float Function asin(float afValue) global native - -; Calculates the arctangent of the passed in value, returning degrees -float Function atan(float afValue) global native - -; Calculates the ceiling of the passed in value - the smallest integer greater than or equal to the value -int Function Ceiling(float afValue) global native - -; Calculates the cosine of the passed in value (in degrees) -float Function cos(float afValue) global native - -; Converts degrees to radians -float Function DegreesToRadians(float afDegrees) global native - -; Calculates the floor of the passed in value - the largest integer less than or equal to the value -int Function Floor(float afValue) global native - -; Calculates x raised to the y power -float Function pow(float x, float y) global native - -; Converts radians to degrees -float Function RadiansToDegrees(float afRadians) global native - -; Calculates the sine of the passed in value (in degrees) -float Function sin(float afValue) global native - -; Calculate the square root of the passed in value -float Function sqrt(float afValue) global native - -; Calculates the tangent of the passed in value (in degrees) -float Function tan(float afValue) global native - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -int Function LeftShift(int value, int shiftBy) global native -int Function RightShift(int value, int shiftBy) global native -int Function LogicalAnd(int arg1, int arg2) global native -int Function LogicalOr(int arg1, int arg2) global native -int Function LogicalXor(int arg1, int arg2) global native -int Function LogicalNot(int arg1) global native -float Function Log(float arg1) global native \ No newline at end of file diff --git a/modules/tests/psc_deps/Message.psc b/modules/tests/psc_deps/Message.psc deleted file mode 100644 index 0f59d19..0000000 --- a/modules/tests/psc_deps/Message.psc +++ /dev/null @@ -1,13 +0,0 @@ -Scriptname Message extends Form Hidden - -; Show this message on the screen, substituting the values as appropriate. If a message box, it will wait until the user closes the box -; before returning - returning the button the user hit. If not a message box, or something went wrong, it will return -1 -int Function Show(float afArg1 = 0.0, float afArg2 = 0.0, float afArg3 = 0.0, float afArg4 = 0.0, float afArg5 = 0.0, float afArg6 = 0.0, float afArg7 = 0.0, float afArg8 = 0.0, float afArg9 = 0.0) native - - -; Shows help message for a user action on screen. -Function ShowAsHelpMessage(string asEvent, float afDuration, float afInterval, int aiMaxTimes) native - - -; Resets help message status for an input event so a new message can be displayed for that event. -Function ResetHelpMessage(string asEvent) native global diff --git a/modules/tests/psc_deps/MiscObject.psc b/modules/tests/psc_deps/MiscObject.psc deleted file mode 100644 index a5369fe..0000000 --- a/modules/tests/psc_deps/MiscObject.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname MiscObject extends Form Hidden \ No newline at end of file diff --git a/modules/tests/psc_deps/ObjectReference.psc b/modules/tests/psc_deps/ObjectReference.psc deleted file mode 100644 index 59aa79a..0000000 --- a/modules/tests/psc_deps/ObjectReference.psc +++ /dev/null @@ -1,834 +0,0 @@ -Scriptname ObjectReference extends Form Hidden - -bool FUNCTION rampRumble(float power = 0.5, float duration = 0.25, float falloff = 1600.0) - ; Function to shake cam/controller based on distance from player - ; should always be called on the source of the rumble, - ; as final intensity is relevant to player - if power > 1.0 || power <= 0 -; debug.traceStack(self + " called rampRumble() but parameter 'power' was invalid. Must be a non-zero float less than 1.0",1) - ; throw the warning, but don't return false - value gets clamped anyway - endif - float playerDist = game.getplayer().getDistance(self) - ; ignore if the player is too far away - if playerDist < falloff - float intensity = (1 - (playerDist / falloff)) - ; ramp actual intensity down based on parameter value - intensity = intensity*power - if intensity > 1.0 - ; clamp to prevent invalid values -; debug.traceStack(self + " called for too much controller/camera shake. Clamped to 1.0", 0) - intensity = 1.0 - elseif intensity <= 0 - ; clamp to prevent invalid values -; debug.traceStack(self + " called for too little controller/camera shake", 0) - intensity = 0 - return false - endif - game.shakeCamera(game.getPlayer(), intensity) - game.shakeController(intensity, intensity, duration) - return true - else -; debug.traceStack(self + "called for rampedRumble(), but player is too far away", 0) - return False - endif -endFUNCTION - -; Function to know if I'm near the player (whether I can be safely enabled or disabled) -bool Function IsNearPlayer() - Actor player = Game.GetPlayer() - Cell targetCell = self.GetParentCell() - Cell playerCell = player.GetParentCell() - - if (targetCell != playerCell) - ; player and target are in different cells - if (targetCell && targetCell.IsInterior() || playerCell && playerCell.IsInterior()) - ; in different cells and at least one is an interior - ; -- we can safely enable or disable - return false - else - ; both in an exterior -- no means of testing - ; worldspace at the moment, so this will do. - if (player.GetDistance(self) > 3000) - ; pretty darned far away -- safe - return false - else - ; too close for comfort - return true - endif - endif - else - ; in the same cell -- err on the side of caution - return true - endif -endFunction - -;jduvall -bool Function IsInInterior() -{Returns !IsInExterior()} - Cell parentCell = GetParentCell() - Return parentCell && parentCell.IsInterior() -EndFunction - -;kkuhlmann: -bool function MoveToIfUnloaded(ObjectReference akTarget, float afXOffset = 0.0, float afYOffset = 0.0, float afZOffset = 0.0) -{Calls MoveTo if the calling ObjectReference is currently unloaded. Doesn't do anything if it IS loaded. No waiting or while loops. Returns true if it does the moveto} - if !Is3DLoaded() - MoveTo(akTarget, afXOffset, afYOffset, afZOffset) - return true - else - return false - endif -endFunction - -;jduvall: -function MoveToWhenUnloaded(ObjectReference akTarget, float afXOffset = 0.0, float afYOffset = 0.0, float afZOffset = 0.0) -{DEPRECATED: DO NOT USE. Calls MoveTo if both the calling ObjectReference and the akTarget ObjectReference have current locations that are not loaded.} - while self.GetCurrentLocation().IsLoaded() || akTarget.GetCurrentLocation().IsLoaded() - ;do nothing -; debug.trace(self + "MoveToWhenUnloaded() waiting for current location and target location to be unloaded before moving. If called by a quest stage fragment, this may cause that quest stage to not complete until this function finishes (and if it's a startup stage, the quest will not report itself as running until the stage finishes.).", 1) - Utility.Wait(5) ;when this function is threaded we can increase this wait time... I set it lower for testing purposes so it reevaluates faster when I need to purge cell buffers in the Civil War when calling moveto on the player between Civil War campaigns - EndWhile - self.MoveTo(akTarget, afXOffset, afYOffset, afZOffset) -EndFunction - -;jduvall -Function DeleteWhenAble() -{This will become a native function... it will wait until the object is not persisting, then delete itself.} - While GetParentCell() && GetParentCell().IsAttached() - ;do nothing -; debug.trace(self + "DeleteWhenAble() waiting for current location to be unloaded before deleting. If called by a quest stage fragment, this may cause that quest stage to not complete until this function finishes (and if it's a startup stage, the quest will not report itself as running until the stage finishes.).", 1) - Utility.Wait(5) ;when this function is threaded we can increase this wait time... I set it lower for testing purposes so it reevaluates faster when I need to purge cell buffers in the Civil War when calling moveto on the player between Civil War campaigns - EndWhile - Delete() -EndFunction - - - -;jduvall -Function AddKeyIfNeeded(ObjectReference ObjectWithNeededKey) -{Should only be called by ObjectReferences that have/are containers (ie Containers and Actors). Checks to see if self has the key to ObjectWithNeededKey, and if not, creates a copy of the key and puts it in self.} - key NeededKey = ObjectWithNeededKey.GetKey() - if NeededKey != None - if GetItemCount(NeededKey) == 0 - AddItem(NeededKey) - EndIf - EndIf -EndFunction - - -; Property to obtain the current X position of the object -float Property X - float Function get() - return GetPositionX() - EndFunction -EndProperty - -; Property to obtain the current Y position of the object -float Property Y - float Function get() - return GetPositionY() - EndFunction -EndProperty - -; Property to obtain the current Z position of the object -float Property Z - float Function get() - return GetPositionZ() - EndFunction -EndProperty - -; Have akActivator activate this reference. If abDefaultProcessingOnly is true then any block will be bypassed -; and no OnActivate event will be sent. The function returns true if default processing ran, and succeeded. If -; default processing has been blocked, will always return false. -bool Function Activate(ObjectReference akActivator, bool abDefaultProcessingOnly = false) native - -; Sets up a dependent animated object -; This function should be used only with a coder supervision. It is left undocumented because it can cause dangling pointers as well as very broken functionality -; for the dependent object if used improperly. -bool Function AddDependentAnimatedObjectReference( ObjectReference akDependent ) native - -; Add an inventory event filter to this reference. Item added/removed events matching the -; specified form (or in the specified form list) will now be let through. -Function AddInventoryEventFilter(Form akFilter) native - -; Adds the specified base object or object reference to this object reference's container/inventory -; Note that you cannot add more then one copy of a reference to a container (a warning will be printed if you try) -Function AddItem(Form akItemToAdd, int aiCount = 1, bool abSilent = false) native - -; Adds this reference (which is a map marker) to the map, optionally making it available for fast travel -Function AddToMap(bool abAllowFastTravel = false) native - -; Apply an impulse to this reference -Function ApplyHavokImpulse(float afX, float afY, float afZ, float afMagnitude) native - -; Turns on and off blocking of normal activation - OnActivate events will still be sent -Function BlockActivation(bool abBlocked = true) native - -; Calculate's this references encounter level based on the requested difficulty level -; 0 - Easy -; 1 - Medium -; 2 - Hard -; 3 - Very Hard -; 4 - None -int Function CalculateEncounterLevel(int aiDifficulty = 4) native - -; Can the map marker be fast traveled to? -bool Function CanFastTravelToMarker() native - -; Clears all effects of destruction from this object -Function ClearDestruction() native - -; Create a detection event at this reference, with the specified owner. Sound level is between 0 and 100 - -Function CreateDetectionEvent(Actor akOwner, int aiSoundLevel = 0 ) native - -; Damages this object and advances the destruction stage - does not return until the object is damaged -Function DamageObject(float afDamage) native - -; Delets this object -Function Delete() native - -; Disables this object - fading out if requested -Function Disable(bool abFadeOut = false) native - -; Disables this object - fading out if requested. Does NOT wait for the fade or disable to finish -Function DisableNoWait(bool abFadeOut = false) native - -; Drops the specified object from this object's inventory -ObjectReference Function DropObject(Form akObject, int aiCount = 1) native - -; Enables this object - fading in if requested -Function Enable(bool abFadeIn = false) native - -; Enables the ability to fast travel to this marker - or disables it. Note that if you disable -; fast travel the player will see "You haven't discovered this location" as an error message -Function EnableFastTravel(bool abEnable = true) native - -; Enables this object - fading in if requested. Does NOT wait for the fade or enable to finish -Function EnableNoWait(bool abFadeIn = false) native - -; Forcibly adds / removes the ragdoll for a reference to the world -Function ForceAddRagdollToWorld() native -Function ForceRemoveRagdollFromWorld() native - -; Gets the actor that owns this object (or None if not owned by an Actor) -ActorBase Function GetActorOwner() native - -; Get the current X angle of this object -float Function GetAngleX() native - -; Get the current Y angle of this object -float Function GetAngleY() native - -; Get the current Z angle of this object -float Function GetAngleZ() native - -; Get a variable from the reference's animation graph (if applicable). Bool version. -bool Function GetAnimationVariableBool(string arVariableName) native - -; Get a variable from the reference's animation graph (if applicable). Int version. -int Function GetAnimationVariableInt(string arVariableName) native - -; Get a variable from the reference's animation graph (if applicable). Float version. -float Function GetAnimationVariableFloat(string arVariableName) native - -; Returns the base object this reference represents -Form Function GetBaseObject() native - -; Returns the object's current destruction stage -int Function GetCurrentDestructionStage() native - -; Returns this reference's current location -Location Function GetCurrentLocation() native - -; Returns the scene this reference is currently in - if any -Scene Function GetCurrentScene() native - -; Calculates the distance between this reference and another - both must either be in the same interior, or same worldspace -float Function GetDistance(ObjectReference akOther) native - -; Returns this reference's editor location -Location Function GetEditorLocation() native - -; Gets the faction that owns this object (or None if not owned by a Faction) -Faction Function GetFactionOwner() native - -; Gets the angle between this object's heading and the other object in degrees - in the range from -180 to 180 -float Function GetHeadingAngle(ObjectReference akOther) native - -; Get the current height of the object -float Function GetHeight() native - -; Returns how many of the specified item is in this object reference's inventory -int Function GetItemCount(Form akItem) native - -; Returns the smithed health of this object reference (1.0 == 100%) -float Function GetItemHealthPercent() native - -; Returns the key base object that will unlock this object -Key Function GetKey() native - -; Get the current length of the object -float Function GetLength() native - -; Get our linked reference -ObjectReference Function GetLinkedRef(Keyword apKeyword = NONE) native - -; Get the level of the lock on this object -int Function GetLockLevel() native - -;jtucker, jduvall -;This function counts the number of linked refs that are in a linked Ref chain (ie object is linked to A, A is linked to B, etc. this then counts all the linked refs.) -;Often used in conjunction with GetNthLinkedRef() -;*** WARNING: Having a link ref chain that at any point loops back on itself and calling this function will result in very bad things. Don't do that!*** -int Function countLinkedRefChain(keyword apKeyword = None, int maxExpectedLinkedRefs = 100) - ;Don't use this on a loop of linked refs. - ObjectReference CurrentLink = self - ObjectReference NewLink - int NumLinkedRefs = 0 - - while(currentLink) && NumLinkedRefs <= maxExpectedLinkedRefs - - NewLink = currentLink.getLinkedRef(apKeyword) - - if NewLink != self - currentLink = NewLink - NumLinkedRefs = NumLinkedRefs + 1 - Else - currentLink = None -; debug.trace( self + "countLinkedRefs() found itself. This suggests it was linked back to itself. This will create an infinite loop, so we are killing the function now. NumLinkedRefs =" + NumLinkedRefs) - EndIf - - endWhile - - if NumLinkedRefs >= maxExpectedLinkedRefs -; debug.trace( self + "countLinkedRefs() bailing out early because it found more linked refs than maxExpectedLinkRefs (suggesting an infinite loop). LinkedRefs found:" + NumLinkedRefs + ", maxExpectedLinkedRefs:" + maxExpectedLinkedRefs) - EndIf - - - return NumLinkedRefs - -endFunction - - -; Returns the Nth linked ref from this reference (0 = self, 1 = GetLinkedRef, 2 = GetLinkedRef.GetLinkedRef, etc) -ObjectReference Function GetNthLinkedRef(int aiLinkedRef) native - - -; Enables all of the references that are linked, in a chain, to this one. -Function EnableLinkChain(Keyword apKeyword = None) - ObjectReference CurrentLink = GetLinkedRef(apKeyword) - While CurrentLink - CurrentLink.Enable() - CurrentLink = CurrentLink.GetLinkedRef(apKeyword) - endWhile -endFunction - - -; Disables all of the references that are linked, in a chain, to this one. -Function DisableLinkChain(Keyword apKeyword = None, bool abFadeOut = false) - ObjectReference CurrentLink = GetLinkedRef(apKeyword) - While CurrentLink - CurrentLink.Disable(abFadeOut) - CurrentLink = CurrentLink.GetLinkedRef(apKeyword) - endWhile -endFunction - - -; Get this object's mass -float Function GetMass() native - -; Gets the open state of this object. Which can be one of the following: -; 0 - None -; 1 - Open -; 2 - Opening -; 3 - Closed -; 4 - Closing -int Function GetOpenState() native - -; Gets the cell this object is in -Cell Function GetParentCell() native - -; Get the current X position of the object -float Function GetPositionX() native - -; Get the current Y position of the object -float Function GetPositionY() native - -; Get the current Z position of the object -float Function GetPositionZ() native - -; Get the current scale of the object -float Function GetScale() native - -; Get the number of objects inside this trigger (throws warning if not a triggger) -int Function GetTriggerObjectCount() native - -; Gets the voice type for this reference. Will return None if not an actor or a talking activator -VoiceType Function GetVoiceType() native - -; Get the current width of the object -float Function GetWidth() native - -; Get this objects worldspace -WorldSpace Function GetWorldSpace() native - -; Returns self cast as an actor -actor Function GetSelfAsActor() - return self as Actor -endFunction - -; Returns if this reference has an active effect coming from a magic effect with the specified keyword attached -bool Function HasEffectKeyword(Keyword akKeyword) native - -; Returns whether the reference has the given node -bool Function HasNode(string asNodeName) native - -; Returns if this reference has the specified location ref type -bool Function HasRefType(LocationRefType akRefType) native - -; Flags this reference as ignoring (or not ignoring) friendly hits -Function IgnoreFriendlyHits(bool abIgnore = true) native - -; Interrupts any spell-casting this object may be doing -Function InterruptCast() native - -; Checks to see if the passed in reference is the activate child of this one -bool Function IsActivateChild(ObjectReference akChild) native - -; Checks to see if activation is currently blocked on this object -bool Function IsActivationBlocked() native - -; Returns if the 3d for this object is loaded or not -bool Function Is3DLoaded() native - -; Is this object currently flagged for delete? -bool Function IsDeleted() native - -; Is this object currently disabled? -bool Function IsDisabled() native - -; Because Shane got tired of remembering which way to call this -bool Function IsEnabled() - return !IsDisabled() -EndFunction - -; Is any marker on this furniture in use? -bool Function IsFurnitureInUse(bool abIgnoreReserved = false) native - -; Is a particular marker on this furniture in use? -bool Function IsFurnitureMarkerInUse(int aiMarker, bool abIgnoreReserved = false) native - -; Is this object ignoring friendly hits? -bool Function IsIgnoringFriendlyHits() native - -; Is this actor or talking activator currently talking to the player? -bool Function IsInDialogueWithPlayer() native - -; Is the lock on this object broken? -bool Function IsLockBroken() native - -; Is the lock on this object locked? -bool Function IsLocked() native - -; Is the map marker visible? -bool Function IsMapMarkerVisible() native - -; Executes a knock effect to an area -Function KnockAreaEffect(float afMagnitude, float afRadius) native - -; Lock/unlock this object. If told to lock it, it will add a lock if it doesn't have one. If locked/unlocked as the owner on a door, -; the adjoining cell will be made public/private as appropriate -Function Lock(bool abLock = true, bool abAsOwner = false) native - -; Moves this object to the position of the specified object, with an offset, and optionally matching its rotation -Function MoveTo(ObjectReference akTarget, float afXOffset = 0.0, float afYOffset = 0.0, float afZOffset = 0.0, bool abMatchRotation = true) native - -; Moves this object to the position (and rotation) of the specified object's interaction position -Function MoveToInteractionLocation(ObjectReference akTarget) native - -; Moves this object to its editor location -Function MoveToMyEditorLocation() native - -; Moves this object to the position (and rotation) of the specified node on the specified object's 3D -Function MoveToNode(ObjectReference akTarget, string asNodeName) native - -; Create x copies of the passed in form (forcing them to persist if desired) and place them at our location, returning the last object created -ObjectReference Function PlaceAtMe(Form akFormToPlace, int aiCount = 1, bool abForcePersist = false, bool abInitiallyDisabled = false) native - -; Create an actor at this object's location. Level mod is one of the following: -; 0 - Easy -; 1 - Medium -; 2 - Hard -; 3 - Boss -; 4 - None -Actor Function PlaceActorAtMe(ActorBase akActorToPlace, int aiLevelMod = 4, EncounterZone akZone = None) native - -; Start the specified animation playing - returns true if it succeeds -bool Function PlayAnimation(string asAnimation) native - -; Start the specified animation playing and wait for the specified event - returns true if succeeds -bool Function PlayAnimationAndWait(string asAnimation, string asEventName) native - -; Start the specified Gamebryo animation playing - returns true if it succeeds -bool Function PlayGamebryoAnimation(string asAnimation, bool abStartOver = false, float afEaseInTime = 0.0) native - -; Play the specified impact effect - returns true if it succeeds -bool Function PlayImpactEffect(ImpactDataSet akImpactEffect, string asNodeName = "", float afPickDirX = 0.0, float afPickDirY = 0.0, float afPickDirZ = -1.0, float afPickLength = 512.0, bool abApplyNodeRotation = false, bool abUseNodeLocalRotation = false) native - -; Play two animations at once - one on this object, one on another object -bool Function PlaySyncedAnimationSS(string asAnimation1, ObjectReference akObj2, string asAnimation2) native - -; Play two animations at once - one on this object, one on another object - and wait for both -bool Function PlaySyncedAnimationAndWaitSS(string asAnimation1, string asEvent1, ObjectReference akObj2, string asAnimation2, string asEvent2) native - -; Play a terrain effect that is attached to the specified bone of this object. -Function PlayTerrainEffect(string asEffectModelName, string asAttachBoneName) native - -; Tells this object to process a trap hitting it -Function ProcessTrapHit(ObjectReference akTrap, float afDamage, float afPushback, float afXVel, float afYVel, float afZVel, float afXPos, float afYPos, float afZPos, int aeMaterial, float afStagger) native - -; Pushes the passed-in actor away from this object, using the passed in knockback force to determine the speed -Function PushActorAway(Actor akActorToPush, float aiKnockbackForce) native - -; Remove all inventory event filters from this reference - all item added/removed events will now be received -Function RemoveAllInventoryEventFilters() native - -; Removes all items from this container, transferring it to the other object if passed -Function RemoveAllItems(ObjectReference akTransferTo = None, bool abKeepOwnership = false, bool abRemoveQuestItems = false) native - -; Remove an inventory event filter from this reference. Item added/removed events matching the -; specified form (or in the specified form list) will no longer be let through. -Function RemoveInventoryEventFilter(Form akFilter) native - -; Removes the specified item from this object reference's inventory -Function RemoveItem(Form akItemToRemove, int aiCount = 1, bool abSilent = false, ObjectReference akOtherContainer = None) native - -; Removes a previously added dependent object -; This function should be used only with a coder supervision. It is left undocumented because it can cause dangling pointers as well as very broken functionality -; for the dependent object if used improperly. -bool Function RemoveDependentAnimatedObjectReference( ObjectReference akDependent ) native - -; Resets this object, optional place the object at the new target -Function Reset(ObjectReference akTarget = None) native - -; Has this object "say" the specified topic, as if spoken by the specified actor (if one is -; provided, and potentially "speaking" in the player's head. -Function Say(Topic akTopicToSay, Actor akActorToSpeakAs = None, bool abSpeakInPlayersHead = false) native - -; Has this object behave as if the specified actor attempted to steal it -Function SendStealAlarm(Actor akThief) native - -; Sets this object's actor cause to the specified actor -Function SetActorCause(Actor akActor) native - -; Sets this object's owner to the specified actor base - None means to remove ownership -Function SetActorOwner(ActorBase akActorBase) native - -; Set the orientation of the object (angles are in degrees) -Function SetAngle(float afXAngle, float afYAngle, float afZAngle) native - -; Set a variable on the reference's animation graph (if applicable). Bool version. -Function SetAnimationVariableBool(string arVariableName, bool abNewValue) native - -; Set a variable on the reference's animation graph (if applicable). Int version. -Function SetAnimationVariableInt(string arVariableName, int aiNewValue) native - -; Set a variable on the reference's animation graph (if applicable). Float version. -Function SetAnimationVariableFloat(string arVariableName, float afNewValue) native - -; Sets this object as destroyed or not -Function SetDestroyed(bool abDestroyed = true) native - -; Sets this object's owner to the specified faction -Function SetFactionOwner(Faction akFaction) native - -; Sets the lock level on this object. Will add an unlocked lock to it if it doesn't have one -Function SetLockLevel(int aiLockLevel) native - -; Sets the motion type of the reference -; aeMotionType: The type of motion (see properties at end of file) -; abAllowActivate: When setting to a dynamic type, allows the simulation to be activated -Function SetMotionType(int aeMotionType, bool abAllowActivate = true) native - -; Sets this object reference as one that teammates will refuse to do favors on -Function SetNoFavorAllowed(bool abNoFavor = true) native - -; Opens/closes this object -Function SetOpen(bool abOpen = true) native - -; Set the position of the object -Function SetPosition(float afX, float afY, float afZ) native - -; Set the current scale of the object -Function SetScale(float afScale) native - -; Makes the reference translate to the given position/orientation -; Note: Rotation speed is entirely dependent on the length of the path and the movement speed -; that is, the rotation will happen such that the reference reaches the goal orientation at the end -; of the translation. -Function TranslateTo(float afX, float afY, float afZ, float afXAngle, float afYAngle, float afZAngle, float afSpeed, float afMaxRotationSpeed = 0.0) native - -; Makes the reference translate to the given position/orientation on a spline -Function SplineTranslateTo(float afX, float afY, float afZ, float afXAngle, float afYAngle, float afZAngle, float afTangentMagnitude, float afSpeed, float afMaxRotationSpeed = 0.0) native - -; Makes the reference translate to the target node's ref/orient on a spline at the given speed -Function SplineTranslateToRefNode(ObjectReference arTarget, string arNodeName, float afTangentMagnitude, float afSpeed, float afMaxRotationSpeed = 0.0) native - -; Stops the reference from moving -Function StopTranslation() native - -; Makes the reference translate to the target ref position/orient at the given speed -Function TranslateToRef(ObjectReference arTarget, float afSpeed, float afMaxRotationSpeed = 0.0) - TranslateTo(arTarget.X, arTarget.Y, arTarget.Z, arTarget.GetAngleX(), arTarget.GetAngleY(), arTarget.GetAngleZ(), afSpeed, afMaxRotationSpeed) -endFunction - -; Makes the reference translate to the target ref position/orient on a spline at the given speed -Function SplineTranslateToRef(ObjectReference arTarget, float afTangentMagnitude, float afSpeed, float afMaxRotationSpeed = 0.0) - SplineTranslateTo(arTarget.X, arTarget.Y, arTarget.Z, arTarget.GetAngleX(), arTarget.GetAngleY(), arTarget.GetAngleZ(), afTangentMagnitude, afSpeed, afMaxRotationSpeed) -endFunction - -; Tether a prisoner cart to the given horse. -Function TetherToHorse(ObjectReference akHorse) native - -; Waits for the animation graph to send the specified event -bool Function WaitForAnimationEvent(string asEventName) native - -; Convenience function to check if I'm in a location or any of its children -bool Function IsInLocation(Location akLocation) - ; cache current location to avoid changing location while this function is running (surprisingly that seems to be happening occasionally) - Location currLoc = GetCurrentLocation() - if currLoc == None - return false - else - return akLocation.IsChild(currLoc) || currLoc == akLocation - endif -endFunction - -; Event received when this reference is activated -Event OnActivate(ObjectReference akActionRef) -EndEvent - -; Event received when this object has moved to an attached cell from a detached one -Event OnAttachedToCell() -EndEvent - -; Event received when this object's parent cell is attached -Event OnCellAttach() -EndEvent - -; Event received when this object's parent cell is detached -Event OnCellDetach() -EndEvent - -; Event received when every object in this object's parent cell is loaded (TODO: Find restrictions) -Event OnCellLoad() -EndEvent - -; Event received when this object is closed -Event OnClose(ObjectReference akActionRef) -EndEvent - -; Event received when this object enters, exits, or changes containers -Event OnContainerChanged(ObjectReference akNewContainer, ObjectReference akOldContainer) -EndEvent - -; Event received when this reference's destruction stage has changed -Event OnDestructionStageChanged(int aiOldStage, int aiCurrentStage) -EndEvent - -; Event recieved when this object moves to a detached cell from an attached one -Event OnDetachedFromCell() -EndEvent - -; Event received when this object is equipped by an actor -Event OnEquipped(Actor akActor) -EndEvent - -; Event received when this object is grabbed by the player -Event OnGrab() -EndEvent - -; Event received when a this trigger is tripped -Event OnTrigger(ObjectReference akActionRef) -EndEvent - -; Event received when this trigger volume is entered -Event OnTriggerEnter(ObjectReference akActionRef) -EndEvent - -; Event received when this trigger volume is left -Event OnTriggerLeave(ObjectReference akActionRef) -EndEvent - -; Event received when this object is hit by a source (weapon, spell, explosion) or projectile attack -Event OnHit(ObjectReference akAggressor, Form akSource, Projectile akProjectile, bool abPowerAttack, bool abSneakAttack, bool abBashAttack, bool abHitBlocked) -EndEvent - -; Event received when an item is added to this object's inventory. If the item is a persistant reference, akItemReference will -; point at it - otherwise the parameter will be None -Event OnItemAdded(Form akBaseItem, int aiItemCount, ObjectReference akItemReference, ObjectReference akSourceContainer) -EndEvent - -; Event received when an item is removed from this object's inventory. If the item is a persistant reference, akItemReference -; will point at it - otherwise the parameter will be None -Event OnItemRemoved(Form akBaseItem, int aiItemCount, ObjectReference akItemReference, ObjectReference akDestContainer) -EndEvent - -; Event recieved when this object is completely loaded - will be fired every time this object is loaded -Event OnLoad() -EndEvent - -; Event received when the lock on this object changes -Event OnLockStateChanged() -EndEvent - -; Event received when a magic affect is being applied to this object -Event OnMagicEffectApply(ObjectReference akCaster, MagicEffect akEffect) -EndEvent - -; Event received when this object is opened -Event OnOpen(ObjectReference akActionRef) -EndEvent - -; Event received when this object, if a book, is read -Event OnRead() -EndEvent - -; Event received when this object is released by the player -Event OnRelease() -EndEvent - -; Event received when this reference is reset -Event OnReset() -EndEvent - -; Event received when this reference is sold by an actor -Event OnSell(Actor akSeller) -EndEvent - -; Event received when a spell is cast by this object -Event OnSpellCast(Form akSpell) -EndEvent - -; Event received when translation is almost complete (from a call to TranslateTo, "almost" is determined by a gamesetting, default is 90% of the way) -Event OnTranslationAlmostComplete() -EndEvent - -; Event received when translation is complete (from a call to TranslateTo) -Event OnTranslationComplete() -EndEvent - -; Event received when translation is aborted (from a call to StopTranslateTo) -Event OnTranslationFailed() -EndEvent - -; Event recieved when this reference hits a target -Event OnTrapHit(ObjectReference akTarget, float afXVel, float afYVel, float afZVel, float afXPos, float afYPos, float afZPos, \ - int aeMaterial, bool abInitialHit, int aeMotionType) -EndEvent - -; Event recieved when this starts hitting a target -Event OnTrapHitStart(ObjectReference akTarget, float afXVel, float afYVel, float afZVel, float afXPos, float afYPos, float afZPos, \ - int aeMaterial, bool abInitialHit, int aeMotionType) -EndEvent - -; Event recieved when this stops hitting a target -Event OnTrapHitStop(ObjectReference akTarget) -EndEvent - -; Event received when this object is unequipped by an actor -Event OnUnequipped(Actor akActor) -EndEvent - -; Event recieved when this object is being unloaded - will be fired every time this object is unloaded -Event OnUnload() -EndEvent - -; Event received when this object's Ward is hit by a spell -Event OnWardHit(ObjectReference akCaster, Spell akSpell, int aiStatus) -EndEvent - -; Set of read-only properties to essentually make a fake enum for motion types passed in to the trap hit -int Property Motion_Dynamic = 1 AutoReadOnly -int Property Motion_SphereIntertia = 2 AutoReadOnly -int Property Motion_BoxIntertia = 3 AutoReadOnly -int Property Motion_Keyframed = 4 AutoReadOnly -int Property Motion_Fixed = 5 AutoReadOnly -int Property Motion_ThinBoxIntertia = 6 AutoReadOnly -int Property Motion_Character = 7 AutoReadOnly - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC - -; Container-only functions -int Function GetNumItems() native -Form Function GetNthForm(int index) native -float Function GetTotalItemWeight() native -float Function GetTotalArmorWeight() native - -; Tree and Flora only functions -bool Function IsHarvested() native -Function SetHarvested(bool harvested) native - -; Tempering -Function SetItemHealthPercent(float health) native - -; Charges - -; Only works on ObjectReferences that have user-enchants -Function SetItemMaxCharge(float maxCharge) native -; Works on any enchanted item -float Function GetItemMaxCharge() native - -float Function GetItemCharge() native -Function SetItemCharge(float charge) native - -Function ResetInventory() native - -bool Function IsOffLimits() native - -; Returns the name of this reference -; this is the name that is displayed -string Function GetDisplayName() native - -; Sets a reference's display name -; returns false if force is false and the reference -; is held by an alias using 'Stored Text' or 'Uses Stored Text' -; Text Replacement does not use this name and may be lost if forced -bool Function SetDisplayName(string name, bool force = false) native - -; Returns the enable parent object -ObjectReference Function GetEnableParent() native - -; Returns the player-made enchantment if there is one -Enchantment Function GetEnchantment() native - -; Changes an item's player-made enchantment to something else -; None enchantment will remove the existing enchantment -; does not delete the custom enchantment, only removes it -Function SetEnchantment(Enchantment source, float maxCharge) native - -; Creates a new enchantment on the item given the specified parameters -; all arrays must be the same size -; created enchantments are not purged from the save when removed or overwritten -; exact same enchantments are re-used by the game -Function CreateEnchantment(float maxCharge, MagicEffect[] effects, float[] magnitudes, int[] areas, int[] durations) native - -; Returns the number of ref aliases holding this reference -int Function GetNumReferenceAliases() native - -; Returns the nth ReferenceAlias holding this reference -ReferenceAlias Function GetNthReferenceAlias(int n) native - -; Returns the poison applied to the weapon -Potion Function GetPoison() native - -; Returns all base forms in the inventory/container into the specified FormList -Function GetAllForms(FormList toFill) native - -; Returns all base forms from the container into a new array -Form[] Function GetContainerForms() native - -; Returns all of the aliases holding this reference -ReferenceAlias[] Function GetReferenceAliases() native \ No newline at end of file diff --git a/modules/tests/psc_deps/Outfit.psc b/modules/tests/psc_deps/Outfit.psc deleted file mode 100644 index 1476682..0000000 --- a/modules/tests/psc_deps/Outfit.psc +++ /dev/null @@ -1,7 +0,0 @@ -Scriptname Outfit extends Form Hidden - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC - -int Function GetNumParts() native -Form Function GetNthPart(int n) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Package.psc b/modules/tests/psc_deps/Package.psc deleted file mode 100644 index 4400fb4..0000000 --- a/modules/tests/psc_deps/Package.psc +++ /dev/null @@ -1,7 +0,0 @@ -Scriptname Package extends Form Hidden - -; Returns the quest that owns this package -Quest Function GetOwningQuest() native - -; Obtains the package that is the parent template of this one (if any) -Package Function GetTemplate() native \ No newline at end of file diff --git a/modules/tests/psc_deps/Perk.psc b/modules/tests/psc_deps/Perk.psc deleted file mode 100644 index b3c78a7..0000000 --- a/modules/tests/psc_deps/Perk.psc +++ /dev/null @@ -1,31 +0,0 @@ -Scriptname Perk extends Form Hidden - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -Perk Function GetNextPerk() native - -int Function GetNumEntries() native - -int Function GetNthEntryRank(int n) native -bool Function SetNthEntryRank(int n, int rank) native - -int Function GetNthEntryPriority(int n) native -bool Function SetNthEntryPriority(int n, int priority) native - -Quest Function GetNthEntryQuest(int n) native -bool Function SetNthEntryQuest(int n, Quest newQuest) native - -int Function GetNthEntryStage(int n) native -bool Function SetNthEntryStage(int n, int stage) native - -Spell Function GetNthEntrySpell(int n) native -bool Function SetNthEntrySpell(int n, Spell newSpell) native - -LeveledItem Function GetNthEntryLeveledList(int n) native -bool Function SetNthEntryLeveledList(int n, LeveledItem lList) native - -string Function GetNthEntryText(int n) native -bool Function SetNthEntryText(int n, string newText) native - -float Function GetNthEntryValue(int n, int i) native -bool Function SetNthEntryValue(int n, int i, float value) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Projectile.psc b/modules/tests/psc_deps/Projectile.psc deleted file mode 100644 index d291897..0000000 --- a/modules/tests/psc_deps/Projectile.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname Projectile extends Form Hidden diff --git a/modules/tests/psc_deps/Quest.psc b/modules/tests/psc_deps/Quest.psc deleted file mode 100644 index 82fc278..0000000 --- a/modules/tests/psc_deps/Quest.psc +++ /dev/null @@ -1,268 +0,0 @@ -Scriptname Quest extends Form Hidden - -; non-native functions - -; thread-safe way to modify a global value -; optional parameters: -; aiObjectiveID = objective ID to redisplay -; afTargetValue = value you're counting up (or down) towards -- if included, function will return TRUE when the global reaches the target value -; abCountingUp = by default, function assumes you're counting up towards the target value; make this false to count DOWN towards target value -; abCompleteObjective = by default, function assumes you're completing the objective once you reach the target value; make this false to FAIL the objective -; abRedisplayObjective = by default, function asssume you want to redisplay the objective every time the global is incremeneted; make this FALSE to only display the objectives on complete or failure -bool Function ModObjectiveGlobal(float afModValue, GlobalVariable aModGlobal, int aiObjectiveID = -1, float afTargetValue = -1.0, bool abCountingUp = true, bool abCompleteObjective = true, bool abRedisplayObjective = true) - aModGlobal.Mod(afModValue) - UpdateCurrentInstanceGlobal(aModGlobal) - if aiObjectiveID >= 0 - ; display/complete objectives automatically - if afTargetValue > -1 - if (abCountingUp && aModGlobal.value >= afTargetValue) || (!abCountingUp && aModGlobal.value <= afTargetValue) - if (abCompleteObjective) - ; complete objective - SetObjectiveCompleted(aiObjectiveID) - return true - Else - ; fail objective - SetObjectiveFailed(aiObjectiveID) - return true - Endif - elseIf (abRedisplayObjective) - ; redisplay objective - SetObjectiveDisplayed(aiObjectiveID, true, true) - Else - SetObjectiveDisplayed(aiObjectiveID, true, false) - endif - elseIf (abRedisplayObjective) - ; no target value, always redisplay objective - SetObjectiveDisplayed(aiObjectiveID, true, true) - Else - SetObjectiveDisplayed(aiObjectiveID, true, false) - endif - endif - return false -endFunction - - -; native functions - -; Flags all objectives as complete -Function CompleteAllObjectives() native - -; Flags this quest as completed -Function CompleteQuest() native - -; Flags all objectives as failed -Function FailAllObjectives() native - -; Obtains the specified alias on the quest -Alias Function GetAlias(int aiAliasID) native - -; Obtains the id of the highest completed stage on this quest -int Function GetCurrentStageID() native - -; Alias for GetCurrentStage - obtains the highest completed stage on this quest -int Function GetStage() - return GetCurrentStageID() -EndFunction - -; Alias for IsStageDone - checks to see whether the given stage is done or not -bool Function GetStageDone(int aiStage) - return IsStageDone(aiStage) -EndFunction - -; Is this quest "active" (tracked by the player)? -bool Function IsActive() native - -; Checks to see if the quest is completed -bool Function IsCompleted() native - -; Checks to see if the specified objective is completed -bool Function IsObjectiveCompleted(int aiObjective) native - -; Checks to see if the specified objective is displayed -bool Function IsObjectiveDisplayed(int aiObjective) native - -; Checks to see if the specified objective is failed -bool Function IsObjectiveFailed(int aiObjective) native - -; Checks to see if the quest is running -bool Function IsRunning() native - -; Obtains whether the specified stage is done or not -bool Function IsStageDone(int aiStage) native - -; Checks to see if the quest is enabled but not running yet -bool Function IsStarting() native - -; Checks to see if the quest is not enabled anymore but still shutting down -bool Function IsStopping() native - -; Checks to see if the quest is no longer enabled or running -bool Function IsStopped() native - -; Resets the quest -Function Reset() native - -; Flags this quest as "active" (tracked by the player) -Function SetActive(bool abActive = true) native - -; Set the quest to the requested stage ID - returns true if stage exists and was set. -; This function is latent and will wait for the quest to start up before returning (if it needed to be started) -bool Function SetCurrentStageID(int aiStageID) native - -; Sets the specified objective to completed or not -Function SetObjectiveCompleted(int aiObjective, bool abCompleted = true) native - -; Sets the specified objective to displayed or hidden - if abForce is true, will display the objective even if it has already been displayed -Function SetObjectiveDisplayed(int aiObjective, bool abDisplayed = true, bool abForce = false) native - -; Sets the specified objective to failed or not -Function SetObjectiveFailed(int aiObjective, bool abFailed = true) native - -; Alias of SetCurrentStage - Set the quest to the requested stage -; This function is latent and will wait for the quest to start up before returning (if it needed to be started) -bool Function SetStage(int aiStage) - return SetCurrentStageID(aiStage) -EndFunction - -; Starts the quest - returns whether the quest was able to be started or not -; This function is latent and will wait for the quest to start up before returning -bool Function Start() native - -; Stops the quest -Function Stop() native - -; Updates current instance's value for the given global -bool Function UpdateCurrentInstanceGlobal( GlobalVariable aUpdateGlobal ) native - -; Story manager events - fired in parallel with the quest startup stage - -Event OnStoryAddToPlayer(ObjectReference akOwner, ObjectReference akContainer, \ - Location akLocation, Form akItemBase, int aiAcquireType) -EndEvent - -Event OnStoryArrest(ObjectReference akArrestingGuard, ObjectReference akCriminal, \ - Location akLocation, int aiCrime) -EndEvent - -Event OnStoryAssaultActor(ObjectReference akVictim, ObjectReference akAttacker, \ - Location akLocation, int aiCrime) -EndEvent - -Event OnStoryBribeNPC(ObjectReference akActor) -EndEvent - -Event OnStoryCastMagic(ObjectReference akCastingActor, ObjectReference akSpellTarget, \ - Location akLocation, Form akSpell) -EndEvent - -Event OnStoryChangeLocation(ObjectReference akActor, Location akOldLocation, \ - Location akNewLocation) -EndEvent - -Event OnStoryCrimeGold(ObjectReference akVictim, ObjectReference akCriminal, \ - Form akFaction, int aiGoldAmount, int aiCrime) -EndEvent - -Event OnStoryCure(Form akInfection) -EndEvent - -Event OnStoryDialogue(Location akLocation, ObjectReference akActor1, ObjectReference akActor2) -EndEvent - -Event OnStoryDiscoverDeadBody(ObjectReference akActor, ObjectReference akDeadActor, \ - Location akLocation) -EndEvent - -Event OnStoryEscapeJail(Location akLocation, Form akCrimeGroup) -EndEvent - -Event OnStoryActivateActor(Location akLocation, ObjectReference akActor) -EndEvent - -Event OnStoryFlatterNPC(ObjectReference akActor) -EndEvent - -Event OnStoryHello(Location akLocation, ObjectReference akActor1, ObjectReference akActor2) -EndEvent - -Event OnStoryIncreaseLevel(int aiNewLevel) -EndEvent - -Event OnStoryIncreaseSkill(string asSkill) -EndEvent - -Event OnStoryInfection(ObjectReference akTransmittingActor, Form akInfection) -EndEvent - -Event OnStoryIntimidateNPC(ObjectReference akActor) -EndEvent - -Event OnStoryJail(ObjectReference akGuard, Form akCrimeGroup, Location akLocation, \ - int aiCrimeGold) -EndEvent - -Event OnStoryKillActor(ObjectReference akVictim, ObjectReference akKiller, \ - Location akLocation, int aiCrimeStatus, int aiRelationshipRank) -EndEvent - -Event OnStoryCraftItem(ObjectReference akBench, Location akLocation, Form akCreatedItem) -EndEvent - -Event OnStoryNewVoicePower(ObjectReference akActor, Form akVoicePower) -EndEvent - -Event OnStoryPickLock(ObjectReference akActor, ObjectReference akLock) -EndEvent - -Event OnStoryPayFine(ObjectReference akCriminal, ObjectReference akGuard, \ - Form akCrimeGroup, int aiCrimeGold) -EndEvent - -Event OnStoryPlayerGetsFavor(ObjectReference akActor) -EndEvent - -Event OnStoryRelationshipChange(ObjectReference akActor1, ObjectReference akActor2, \ - int aiOldRelationship, int aiNewRelationship) -EndEvent - -Event OnStoryRemoveFromPlayer(ObjectReference akOwner, ObjectReference akItem, \ - Location akLocation, Form akItemBase, int aiRemoveType) -EndEvent - -Event OnStoryScript(Keyword akKeyword, Location akLocation, ObjectReference akRef1, \ - ObjectReference akRef2, int aiValue1, int aiValue2) -EndEvent - -Event OnStoryServedTime(Location akLocation, Form akCrimeGroup, int aiCrimeGold, \ - int aiDaysJail) -EndEvent - -Event OnStoryTrespass(ObjectReference akVictim, ObjectReference akTrespasser, \ - Location akLocation, int aiCrime) -EndEvent - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC - -; returns the quest with the specified editor id -Quest Function GetQuest(string editorId) global native - -; returns the editor ID of the quest -string Function GetID() native - -; returns the priority of the quest -int Function GetPriority() native - -; returns the number of aliases associated with the quest -int Function GetNumAliases() native - -; returns the specified alias associated with the queest -Alias Function GetNthAlias(int index) native - -; returns the alias associated with the quest by name -Alias Function GetAliasByName(string name) native - -; returns the alias by AlisID -Alias Function GetAliasById(int aliasId) native - -; Returns all the aliases of this quest -Alias[] Function GetAliases() native \ No newline at end of file diff --git a/modules/tests/psc_deps/Race.psc b/modules/tests/psc_deps/Race.psc deleted file mode 100644 index 4e8b316..0000000 --- a/modules/tests/psc_deps/Race.psc +++ /dev/null @@ -1,231 +0,0 @@ -Scriptname Race extends Form Hidden - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; returns the number of spells for the race -int Function GetSpellCount() native - -; returns the specified spell from the race -Spell Function GetNthSpell(int n) native - -; returns whether the specified race flag is set -bool Function IsRaceFlagSet(int n) native - -; sets the specified race flag -Function SetRaceFlag(int n) native - -; clears the specified race flag -Function ClearRaceFlag(int n) native - -; Returns the races default voice type -VoiceType Function GetDefaultVoiceType(bool female) native - -; Sets the races default voice type -Function SetDefaultVoiceType(bool female, VoiceType voice) native - -; Gets/sets the skin of the race -Armor Function GetSkin() native -Function SetSkin(Armor skin) native - -; Returns the number of playable races -int Function GetNumPlayableRaces() native global - -; Returns the nth playable race -Race Function GetNthPlayableRace(int n) native global - -; Returns a race by it's editorId name -Race Function GetRace(string editorId) native global - -; race flags for previous functions -int property kRace_Playable = 0x00000001 AutoReadOnly -int property kRace_FaceGenHead = 0x00000002 AutoReadOnly -int property kRace_Child = 0x00000004 AutoReadOnly -int property kRace_TiltFrontBack = 0x00000008 AutoReadOnly -int property kRace_TiltLeftRight = 0x00000010 AutoReadOnly -int property kRace_NoShadow = 0x00000020 AutoReadOnly -int property kRace_Swims = 0x00000040 AutoReadOnly -int property kRace_Flies = 0x00000080 AutoReadOnly -int property kRace_Walks = 0x00000100 AutoReadOnly -int property kRace_Immobile = 0x00000200 AutoReadOnly -int property kRace_NotPushable = 0x00000400 AutoReadOnly -int property kRace_NoCombatInWater = 0x00000800 AutoReadOnly -int property kRace_NoRotatingToHeadTrack = 0x00001000 AutoReadOnly -int property kRace_UseHeadTrackAnim = 0x00008000 AutoReadOnly -int property kRace_SpellsAlignWithMagicNode = 0x00010000 AutoReadOnly -int property kRace_UseWorldRaycasts = 0x00020000 AutoReadOnly -int property kRace_AllowRagdollCollision = 0x00040000 AutoReadOnly -int property kRace_CantOpenDoors = 0x00100000 AutoReadOnly -int property kRace_AllowPCDialogue = 0x00200000 AutoReadOnly -int property kRace_NoKnockdowns = 0x00400000 AutoReadOnly -int property kRace_AllowPickpocket = 0x00800000 AutoReadOnly -int property kRace_AlwaysUseProxyController = 0x01000000 AutoReadOnly -int property kRace_AllowMultipleMembraneShaders = 0x20000000 AutoReadOnly -int property kRace_AvoidsRoads = 0x80000000 AutoReadOnly - -bool Function IsPlayable() - return IsRaceFlagSet(self.kRace_Playable) -endFunction - -Function MakePlayable() - SetRaceFlag(self.kRace_Playable) -endFunction - -Function MakeUnplayable() - ClearRaceFlag(self.kRace_Playable) -endFunction - -bool Function IsChildRace() - return IsRaceFlagSet(self.kRace_Child) -endFunction - -Function MakeChildRace() - SetRaceFlag(self.kRace_Child) -endFunction - -Function MakeNonChildRace() - ClearRaceFlag(self.kRace_Child) -endFunction - -bool Function CanFly() - return IsRaceFlagSet(self.kRace_Flies) -endFunction - -Function MakeCanFly() - SetRaceFlag(self.kRace_Flies) -endFunction - -Function MakeNonFlying() - ClearRaceFlag(self.kRace_Flies) -endFunction - -bool Function CanSwim() - return IsRaceFlagSet(self.kRace_Swims) -endFunction - -Function MakeCanSwim() - SetRaceFlag(self.kRace_Swims) -endFunction - -Function MakeNonSwimming() - ClearRaceFlag(self.kRace_Swims) -endFunction - -bool Function CanWalk() - return IsRaceFlagSet(self.kRace_Walks) -endFunction - -Function MakeCanWalk() - SetRaceFlag(self.kRace_Walks) -endFunction - -Function MakeNonWalking() - ClearRaceFlag(self.kRace_Walks) -endFunction - -bool Function IsImmobile() - return IsRaceFlagSet(self.kRace_Immobile) -endFunction - -Function MakeImmobile() - SetRaceFlag(self.kRace_Immobile) -endFunction - -Function MakeMobile() - ClearRaceFlag(self.kRace_Immobile) -endFunction - -bool Function IsNotPushable() - return IsRaceFlagSet(self.kRace_NotPushable) -endFunction - -Function MakeNotPushable() - SetRaceFlag(self.kRace_NotPushable) -endFunction - -Function MakePushable() - ClearRaceFlag(self.kRace_NotPushable) -endFunction - -bool Function NoKnockdowns() - return IsRaceFlagSet(self.kRace_AllowPickpocket) -endFunction - -Function MakeNoKnockdowns() - SetRaceFlag(self.kRace_AllowPickpocket) -endFunction - -Function ClearNoKNockdowns() - ClearRaceFlag(self.kRace_AllowPickpocket) -endFunction - -bool Function NoCombatInWater() - return IsRaceFlagSet(self.kRace_NoCombatInWater) -endFunction - -Function SetNoCombatInWater() - SetRaceFlag(self.kRace_NoCombatInWater) -endFunction - -Function ClearNoCombatInWater() - ClearRaceFlag(self.kRace_NoCombatInWater) -endFunction - -bool Function AvoidsRoads() - return IsRaceFlagSet(self.kRace_AvoidsRoads) -endFunction - -Function SetAvoidsRoads() - SetRaceFlag(self.kRace_AvoidsRoads) -endFunction - -Function ClearAvoidsRoads() - ClearRaceFlag(self.kRace_AvoidsRoads) -endFunction - -bool Function AllowPickpocket() - return IsRaceFlagSet(self.kRace_AllowPickpocket) -endFunction - -Function SetAllowPickpocket() - SetRaceFlag(self.kRace_AllowPickpocket) -endFunction - -Function ClearAllowPickpocket() - ClearRaceFlag(self.kRace_AllowPickpocket) -endFunction - -bool Function AllowPCDialogue() - return IsRaceFlagSet(self.kRace_AllowPCDialogue) -endFunction - -Function SetAllowPCDialogue() - SetRaceFlag(self.kRace_AllowPCDialogue) -endFunction - -Function ClearAllowPCDialogue() - ClearRaceFlag(self.kRace_AllowPCDialogue) -endFunction - -bool Function CantOpenDoors() - return IsRaceFlagSet(self.kRace_CantOpenDoors) -endFunction - -Function SetCantOpenDoors() - SetRaceFlag(self.kRace_CantOpenDoors) -endFunction - -Function ClearCantOpenDoors() - ClearRaceFlag(self.kRace_CantOpenDoors) -endFunction - -bool Function NoShadow() - return IsRaceFlagSet(self.kRace_NoShadow) -endFunction - -Function SetNoShadow() - SetRaceFlag(self.kRace_NoShadow) -endFunction - -Function ClearNoShadow() - ClearRaceFlag(self.kRace_NoShadow) -endFunction - diff --git a/modules/tests/psc_deps/ReferenceAlias.psc b/modules/tests/psc_deps/ReferenceAlias.psc deleted file mode 100644 index 3d71a7b..0000000 --- a/modules/tests/psc_deps/ReferenceAlias.psc +++ /dev/null @@ -1,398 +0,0 @@ -Scriptname ReferenceAlias extends Alias Hidden -import ObjectReference - -; Add an inventory event filter to this alias. Item added/removed events matching the -; specified form (or in the specified form list) will now be let through. -Function AddInventoryEventFilter(Form akFilter) native - -; Clears the alias - fails on non-optional aliases -Function Clear() native - -; Get the object reference this alias refers to -ObjectReference Function GetReference() native - -; Forces this alias to use the specified reference -Function ForceRefTo(ObjectReference akNewRef) native - -; Remove all inventory event filters from this alias - all item added/removed events will now be received -Function RemoveAllInventoryEventFilters() native - -; Remove an inventory event filter from this alias. Item added/removed events matching the -; specified form (or in the specified form list) will no longer be let through. -Function RemoveInventoryEventFilter(Form akFilter) native - -; SJML -- tries to force a reference into the alias, but only if it's already empty. -; returns true if the alias now holds the passed reference, false if it was already filled. -bool Function ForceRefIfEmpty(ObjectReference akNewRef) - if (GetReference()) - return False - else - ForceRefTo(akNewRef) - return True - endif -EndFunction - -; Autocast to Actor is applicable -Actor Function GetActorReference() - return GetReference() as Actor -endFunction - -; Convenience function -ObjectReference Function GetRef() - return GetReference() -endFunction - -; Convenience fucntion -Actor Function GetActorRef() - return GetActorReference() -endFunction - - -; Convenience function - jduvall -bool Function TryToAddToFaction(Faction FactionToAddTo) - Actor ActorRef = GetActorReference() - - if ActorRef - ActorRef.AddToFaction(FactionToAddTo) - Return True - EndIf - - Return False -EndFunction - -; Convenience function - jduvall -bool Function TryToRemoveFromFaction(Faction FactionToRemoveFrom) - Actor ActorRef = GetActorReference() - - if ActorRef - ActorRef.RemoveFromFaction(FactionToRemoveFrom) - Return True - EndIf - - Return False -EndFunction - -; Convenience function - jduvall -bool Function TryToStopCombat() - Actor ActorRef = GetActorReference() - - if ActorRef - ActorRef.StopCombat() - Return True - EndIf - - Return False -EndFunction - -; Convenience function - jduvall -bool Function TryToDisable() - ObjectReference Ref = GetReference() - - if Ref - Ref.Disable() - Return True - EndIf - - Return False -EndFunction - -; Convenience function - wshen -bool Function TryToDisableNoWait() - ObjectReference Ref = GetReference() - - if Ref - Ref.DisableNoWait() - Return True - EndIf - - Return False -EndFunction - -; Convenience function - jduvall -bool Function TryToEnable() - ObjectReference Ref = GetReference() - - if Ref - Ref.Enable() - Return True - EndIf - - Return False -EndFunction - -; Convenience function - wshen -bool Function TryToEnableNoWait() - ObjectReference Ref = GetReference() - - if Ref - Ref.EnableNoWait() - Return True - EndIf - - Return False -EndFunction - -; Convenience function - jduvall -bool Function TryToEvaluatePackage() - Actor ActorRef = GetActorReference() - - if ActorRef - ActorRef.EvaluatePackage() - Return True - EndIf - - Return False -EndFunction - -; Convenience function - jduvall -bool Function TryToKill() - Actor ActorRef = GetActorReference() - - if ActorRef - ActorRef.Kill() - Return True - EndIf - - Return False -EndFunction - -; Convenience function - jduvall -bool Function TryToMoveTo(ObjectReference RefToMoveTo) - ObjectReference Ref = GetReference() - - if Ref - Ref.MoveTo(RefToMoveTo) - Return True - EndIf - - Return False -EndFunction - -; Convenience function - jduvall -bool Function TryToReset() - ObjectReference Ref = GetReference() - - if Ref - Ref.Reset() - Return True - EndIf - - Return False -EndFunction - -; Convenience function - sjml -bool Function TryToClear() - if (GetReference()) - Clear() - return True - endif - - return False -EndFunction - -; The following events are received if the object the alias points at receives the events: - -; Event received when this reference is activated -Event OnActivate(ObjectReference akActionRef) -EndEvent - -; Event received when this object has moved to an attached cell from a detached one -Event OnAttachedToCell() -EndEvent - -; Event received when this object's parent cell is attached -Event OnCellAttach() -EndEvent - -; Event received when this object's parent cell is detached -Event OnCellDetach() -EndEvent - -; Event received when every object in this object's parent cell is loaded (TODO: Find restrictions) -Event OnCellLoad() -EndEvent - -; Event received when this object is closed -Event OnClose(ObjectReference akActionRef) -EndEvent - -; Event received when this object enters, exits, or changes containers -Event OnContainerChanged(ObjectReference akNewContainer, ObjectReference akOldContainer) -EndEvent - -; Event received when this reference's destruction stage has changed -Event OnDestructionStageChanged(int aiOldStage, int aiCurrentStage) -EndEvent - -; Event recieved when this object moves to a detached cell from an attached one -Event OnDetachedFromCell() -EndEvent - -; Event received when this object is equipped by an actor -Event OnEquipped(Actor akActor) -EndEvent - -; Event received when this object is grabbed by the player -Event OnGrab() -EndEvent - -; Event received when this object is hit by a source (weapon, spell, explosion) or projectile attack -Event OnHit(ObjectReference akAggressor, Form akSource, Projectile akProjectile, bool abPowerAttack, bool abSneakAttack, bool abBashAttack, bool abHitBlocked) -EndEvent - -; Event received when an item is added to this object's inventory. If the item is a persistant reference, akItemReference will -; point at it - otherwise the parameter will be None -Event OnItemAdded(Form akBaseItem, int aiItemCount, ObjectReference akItemReference, ObjectReference akSourceContainer) -EndEvent - -; Event received when an item is removed from this object's inventory. If the item is a persistant reference, akItemReference -; will point at it - otherwise the parameter will be None -Event OnItemRemoved(Form akBaseItem, int aiItemCount, ObjectReference akItemReference, ObjectReference akDestContainer) -EndEvent - -; Event recieved when this object is completely loaded - will be fired every time this object is loaded -Event OnLoad() -EndEvent - -; Event received when the lock on this object changes -Event OnLockStateChanged() -EndEvent - -; Event received when a magic affect is being applied to this object -Event OnMagicEffectApply(ObjectReference akCaster, MagicEffect akEffect) -EndEvent - -; Event received when this object is opened -Event OnOpen(ObjectReference akActionRef) -EndEvent - -; Event received when this object, if a book, is read -Event OnRead() -EndEvent - -; Event received when this object is released by the player -Event OnRelease() -EndEvent - -; Event received when this reference is reset -Event OnReset() -EndEvent - -; Event received when this reference is sold by an actor -Event OnSell(Actor akSeller) -EndEvent - -; Event received when a spell is cast by this object -Event OnSpellCast(Form akSpell) -EndEvent - -; Event received when translation is complete (from a call to TranslateTo) -Event OnTranslationComplete() -EndEvent - -; Event received when translation is aborted (from a call to StopTranslateTo) -Event OnTranslationFailed() -EndEvent - -; Event recieved when this reference hits a target -Event OnTrapHit(ObjectReference akTarget, float afXVel, float afYVel, float afZVel, float afXPos, float afYPos, float afZPos, \ - int aeMaterial, bool abInitialHit, int aeMotionType) -EndEvent - -; Event recieved when this starts hitting a target -Event OnTrapHitStart(ObjectReference akTarget, float afXVel, float afYVel, float afZVel, float afXPos, float afYPos, float afZPos, \ - int aeMaterial, bool abInitialHit, int aeMotionType) -EndEvent - -; Event recieved when this stops hitting a target -Event OnTrapHitStop(ObjectReference akTarget) -EndEvent - -; Event received when a this trigger is tripped -Event OnTrigger(ObjectReference akActionRef) -EndEvent - -; Event received when this trigger volume is entered -Event OnTriggerEnter(ObjectReference akActionRef) -EndEvent - -; Event received when this trigger volume is left -Event OnTriggerLeave(ObjectReference akActionRef) -EndEvent - -; Event received when this object is unequipped by an actor -Event OnUnequipped(Actor akActor) -EndEvent - -; Event recieved when this object is being unloaded - will be fired every time this object is unloaded -Event OnUnload() -EndEvent - -; Event that is triggered when this actor's combat state against the target changes -; State is as follows: -; 0 - not in combat -; 1 - in combat -; 2 - searching -Event OnCombatStateChanged(Actor akTarget, int aeCombatState) -EndEvent - -; Event that is triggered when this actor sits in the furniture -Event OnSit(ObjectReference akFurniture) -EndEvent - -; Event that is triggered when this actor leaves the furniture -Event OnGetUp(ObjectReference akFurniture) -EndEvent - -; Event that is triggered when this actor finishes dying (only if this alias points at an actor) -Event OnDeath(Actor akKiller) -EndEvent - -; Event that is triggered when this actor begins dying (only if this alias points at an actor) -Event OnDying(Actor akKiller) -EndEvent - -; Event received when an actor enters bleedout. (only if this alias points at an actor) -Event OnEnterBleedout() -EndEvent - -; Event that is triggered when this actor changes from one location to another (only if this alias points at an actor) -Event OnLocationChange(Location akOldLoc, Location akNewLoc) -EndEvent - -; Event received when this actor equips something - akReference may be None if object is not persistent (only if this alias points at an actor) -Event OnObjectEquipped(Form akBaseObject, ObjectReference akReference) -EndEvent - -; Event received when this actor unequips something - akReference may be None if object is not persistent (only if this alias points at an actor) -Event OnObjectUnequipped(Form akBaseObject, ObjectReference akReference) -EndEvent - -; Event received when this actor starts a new package (only if this alias points at an actor) -Event OnPackageStart(Package akNewPackage) -EndEvent - -; Event received when this actor's package changes (only if this alias points at an actor) -Event OnPackageChange(Package akOldPackage) -EndEvent - -; Event received when this actor's package ends (only if this alias points at an actor) -Event OnPackageEnd(Package akOldPackage) -EndEvent - -; Event received when this actor finishes changing its race -Event OnRaceSwitchComplete() -EndEvent - -; Event received when this object's Ward is hit by a spell -Event OnWardHit(ObjectReference akCaster, Spell akSpell, int aiStatus) -EndEvent - -; Received when the player fires a bow. akWeapon will be a bow, akAmmo is the ammo or None, -; afPower will be 1.0 for a full-power shot, less for a dud, and abSunGazing will be true if the player is looking at the sun. -Event OnPlayerBowShot(Weapon akWeapon, Ammo akAmmo, float afPower, bool abSunGazing) -EndEvent - -; Received immediately after the player has loaded a save game. A good time to check for additional content. -Event OnPlayerLoadGame() -EndEvent diff --git a/modules/tests/psc_deps/Shout.psc b/modules/tests/psc_deps/Shout.psc deleted file mode 100644 index 9ed9f1e..0000000 --- a/modules/tests/psc_deps/Shout.psc +++ /dev/null @@ -1,10 +0,0 @@ -Scriptname Shout extends Form Hidden - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -WordOfPower Function GetNthWordOfPower(int n) native -Spell Function GetNthSpell(int n) native -float Function GetNthRecoveryTime(int n) native - -Function SetNthWordOfPower(int n, WordOfPower aWoop) native -Function SetNthSpell(int n, Spell aSpell) native -Function SetNthRecoveryTime(int n, float time) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Sound.psc b/modules/tests/psc_deps/Sound.psc deleted file mode 100644 index 1cc82e2..0000000 --- a/modules/tests/psc_deps/Sound.psc +++ /dev/null @@ -1,19 +0,0 @@ -Scriptname Sound extends Form Hidden -import ObjectReference - -; Play this sound base object from the specified source -int Function Play(ObjectReference akSource) native - -; Play this sound from the specified source, and wait for it to finish -bool Function PlayAndWait(ObjectReference akSource) native - -; Stops a given playback instance of a sound -Function StopInstance(int aiPlaybackInstance) native global - -; Set the volume of a given playback instance of a sound. Clamped between 0 and 1. -Function SetInstanceVolume(int aiPlaybackInstance, float afVolume) native global - - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -SoundDescriptor Function GetDescriptor() native \ No newline at end of file diff --git a/modules/tests/psc_deps/Spell.psc b/modules/tests/psc_deps/Spell.psc deleted file mode 100644 index 26252ba..0000000 --- a/modules/tests/psc_deps/Spell.psc +++ /dev/null @@ -1,79 +0,0 @@ -Scriptname Spell extends Form Hidden - -; Cast this spell from an ObjectReference, optionally toward another. -Function Cast(ObjectReference akSource, ObjectReference akTarget=NONE) native - -; Cast this spell from an ObjectReference, optionally toward another, and blame it on a particular actor. -Function RemoteCast(ObjectReference akSource, Actor akBlameActor, ObjectReference akTarget=NONE) native - -; Is this spell classified as hostile? -bool Function IsHostile() native - -; Preload the art for this spell. Useful for spells you equip & unequip on the player. -; Warning: Misuse of this function can lead to erroneous behavior as well as excessive -; memory consumption. It's best to avoid using this. This function will likely be -; deprecated in the future. -Function Preload() native - -; Unload the art for this spell. Call this only if you've previously called Preload. -; Warning: Misuse of this function can lead to erroneous behavior including spell art -; being unloaded while in use, and excessive memory consumption. It's best to avoid using this. -; This function will likely be deprecated in the future. -Function Unload() native - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC -; return the casting time -float Function GetCastTime() native - -; return the perk associated with the spell -Perk Function GetPerk() native - -; return the number of the effects -int Function GetNumEffects() native - -; return the magnitude of the specified effect -float Function GetNthEffectMagnitude(int index) native - -; return the area of the specified effect -int Function GetNthEffectArea(int index) native - -; return the duration of the specified effect -int Function GetNthEffectDuration(int index) native - -; return the magic effect of the specified effect -MagicEffect Function GetNthEffectMagicEffect(int index) native - -; return the index of the costliest effect -int Function GetCostliestEffectIndex() native - -; return the base magicka cost of the spell -int Function GetMagickaCost() native - -; return the effective magicka cost of the spell for given caster -int Function GetEffectiveMagickaCost(Actor caster) native - -; sets the magnitude of the specified effect -Function SetNthEffectMagnitude(int index, float value) native - -; sets the area of the specified effect -Function SetNthEffectArea(int index, int value) native - -; sets the duration of the specified effect -Function SetNthEffectDuration(int index, int value) native - -; Returns the particular equipslot type -EquipSlot Function GetEquipType() native -Function SetEquipType(EquipSlot type) native - -; Returns all the magnitudes of this object in order -float[] Function GetEffectMagnitudes() native - -; Returns all the areas of this object in order -int[] Function GetEffectAreas() native - -; Returns all the durations of this object in order -int[] Function GetEffectDurations() native - -; Returns all the magic effects of this object in order -MagicEffect[] Function GetMagicEffects() native \ No newline at end of file diff --git a/modules/tests/psc_deps/Static.psc b/modules/tests/psc_deps/Static.psc deleted file mode 100644 index 40e950d..0000000 --- a/modules/tests/psc_deps/Static.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname Static Extends Form diff --git a/modules/tests/psc_deps/StringUtil.psc b/modules/tests/psc_deps/StringUtil.psc deleted file mode 100644 index a1640a0..0000000 --- a/modules/tests/psc_deps/StringUtil.psc +++ /dev/null @@ -1,45 +0,0 @@ -Scriptname StringUtil Hidden - -; Note about the internal Skyrim implementation of the string classes used for scripting: -; the strings are case-insensitive. Each BSFixedString is managed in a cache and reused -; everywhere it is needed. This means that strings like "O" and "o" are technically equivalent; -; Which string is used depends greatly on which version is found first. We are investigating -; how to manage this, but for the time being be aware that the distinction between uppercase -; and lowercase may not exist. It also means that functions below returning an integer -; for the character may not correspond exactly. Also GetNthChar("Hello Skyrim!", 4) will -; return a string with either "O" or "o" depnding on which might be registered first. All -; my tests so far have it return the uppercase, eventhough in the string it is lowercase. -; We may solve this problem by switching back to returning an integer rather than a string -; for GetNthChar, but this will still have problems. - -; return the length of the string -int Function GetLength(string s) global native - -; returns a single character string with the character at index -string Function GetNthChar(string s, int index) global native - -; Functions to work on Chars -; returns information about a specific character -; assumes a single character string. If a multicharacter string is passed -; the information about the first character is returned -bool Function IsLetter(string c) global native -bool Function IsDigit(string c) global native -bool Function IsPunctuation(string c) global native -bool Function IsPrintable(string c) global native - -; returns the index of the first character of toFind inside string s -; returns -1 if toFind is not part of the string or if startIndex is invalid -int Function Find(string s, string toFind, int startIndex = 0) global native - -; returns a substring of the specified string starting at startIndex and going for len characters -; or until the end of the string. Default len of 0 means for the entire string -string Function Substring(string s, int startIndex, int len = 0) global native - -; returns the numeric value of the first character as an int -int Function AsOrd(string c) global native - -; returns a single character string interpreting c as a character -string Function AsChar(int c) global native - -; returns array of strings separated by the specified delimiter -string[] Function Split(string s, string delim) global native \ No newline at end of file diff --git a/modules/tests/psc_deps/TextureSet.psc b/modules/tests/psc_deps/TextureSet.psc deleted file mode 100644 index 9802876..0000000 --- a/modules/tests/psc_deps/TextureSet.psc +++ /dev/null @@ -1,12 +0,0 @@ -Scriptname TextureSet extends Form Hidden - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC - -; Returns the number of texture paths -int Function GetNumTexturePaths() native - -; Returns the path of the texture -string Function GetNthTexturePath(int n) native - -; Sets the path of the texture -Function SetNthTexturePath(int n, string texturePath) native \ No newline at end of file diff --git a/modules/tests/psc_deps/Topic.psc b/modules/tests/psc_deps/Topic.psc deleted file mode 100644 index 220b34a..0000000 --- a/modules/tests/psc_deps/Topic.psc +++ /dev/null @@ -1,4 +0,0 @@ -Scriptname Topic extends Form Hidden - -; Adds this topic to the list the player knows about -Function Add() native \ No newline at end of file diff --git a/modules/tests/psc_deps/UI.psc b/modules/tests/psc_deps/UI.psc deleted file mode 100644 index f1b95a3..0000000 --- a/modules/tests/psc_deps/UI.psc +++ /dev/null @@ -1,119 +0,0 @@ -Scriptname UI Hidden - -; For functions that require a menuName, potential values are -; "InventoryMenu" -; "Console" -; "Dialogue Menu" -; "HUD Menu" -; "Main Menu" -; "MessageBoxMenu" -; "Cursor Menu" -; "Fader Menu" -; "MagicMenu" -; "Top Menu" -; "Overlay Menu" -; "Overlay Interaction Menu" -; "Loading Menu" -; "TweenMenu" -; "BarterMenu" -; "GiftMenu" -; "Debug Text Menu" -; "MapMenu" -; "Lockpicking Menu" -; "Quantity Menu" -; "StatsMenu" -; "ContainerMenu" -; "Sleep/Wait Menu" -; "LevelUp Menu" -; "Journal Menu" -; "Book Menu" -; "FavoritesMenu" -; "RaceSex Menu" -; "Crafting Menu" -; "Training Menu" -; "Mist Menu" -; "Tutorial Menu" -; "Credits Menu" -; "TitleSequence Menu" -; "Console Native UI Menu" -; "Kinect Menu" -; -; The target parameter requires one the following prefixes: -; _global , for the default namespace; -; _root , for the movie root. - - -; Returns if the menu is currently open. -bool Function IsMenuOpen(string menuName) global native - - -; Sets bool/number/string value at target location. -; Target value must already exist. -; -; Examples: -; UI.SetBool("InventoryMenu", "_root.Menu_mc._visible", false) -; UI.SetString("FavoritesMenu", "_root.Menu_mc.panel.message.text", "My Text") -; -Function SetBool(string menuName, string target, bool value) global native -Function SetInt(string menuName, string target, int value) global native -Function SetFloat(string menuName, string target, float value) global native -Function SetString(string menuName, string target, string value) global native -Function SetNumber(string menuName, string target, float value) global ; DEPRECIATED - SetFloat(menuName, target, value) -EndFunction - -; Gets bool/number/string from target location, or false/0/none if the value doesn't exist. -; -; Examples: -; bool visible = UI.GetBool("Inventory Menu", "_root.Menu_mc._visible") -; float height = UI.GetNumber("Magic Menu", "_root.Menu_mc._height") -; -bool Function GetBool(string menuName, string target) global native -int Function GetInt(string menuName, string target) global native -float Function GetFloat(string menuName, string target) global native -string Function GetString(string menuName, string target) global native -float Function GetNumber(string menuName, string target) global ; DEPRECIATED - return GetFloat(menuName, target) -EndFunction - - -; Invokes the ActionScript function at given target location. -; -; Examples: -; UI.InvokeString("InventoryMenu", "_global.skse.Log", "Printed to logfile") -; UI.InvokeStringA("InventoryMenu", "_global.myFunction", myArray) -; -Function Invoke(string menuName, string target) global - InvokeBool(menuName, target, false) -EndFunction - -Function InvokeBool(string menuName, string target, bool arg) global native -Function InvokeInt(string menuName, string target, int arg) global native -Function InvokeFloat(string menuName, string target, float arg) global native -Function InvokeString(string menuName, string target, string arg) global native -Function InvokeNumber(string menuName, string target, float arg) global ; DEPRECIATED - InvokeFloat(menuName, target, arg) -EndFunction - -Function InvokeBoolA(string menuName, string target, bool[] args) global native -Function InvokeIntA(string menuName, string target, int[] args) global native -Function InvokeFloatA(string menuName, string target, float[] args) global native -Function InvokeStringA(string menuName, string target, string[] args) global native -Function InvokeNumberA(string menuName, string target, float[] args) global ; DEPRECIATED - InvokeFloatA(menuName, target, args) -EndFunction - -; Sends Form data to Scaleform as a Flash object, FormLists included. -Function InvokeForm(string menuName, string target, Form arg) global native - -; returns if scaleform is in 'text input' mode -; this is useful for ignoring keys that should get swallowed by an editable text box -bool Function IsTextInputEnabled() global native - -; open a custom menu named "CustomMenu" by loading the given swf from the interface folder -; (filename without extension) -; there can only be a single custom menu open at the same time -Function OpenCustomMenu(string swfPath, int flags = 0) global native - -; close the custom menu if it's currently open. -Function CloseCustomMenu() global native \ No newline at end of file diff --git a/modules/tests/psc_deps/Utility.psc b/modules/tests/psc_deps/Utility.psc deleted file mode 100644 index d608d24..0000000 --- a/modules/tests/psc_deps/Utility.psc +++ /dev/null @@ -1,83 +0,0 @@ -Scriptname Utility Hidden - -; Converts a float game time (in terms of game days passed) to a string detailing the date -; and time it represents in "MM/DD/YYYY HH:MM" format. A 24-hour clock is used, and the function -; is latent (due to issues in the current architecture with returning strings from code) -string Function GameTimeToString(float afGameTime) native global - -; Obtains the current game time in terms of game days passed (same as the global variable) -float Function GetCurrentGameTime() native global - -; Obtains the number of seconds since the application started (the same timer that WaitMenuMode uses) -; Does not take into account menu-mode, or VM frozen time -; Most useful for determining how long something took to run -float Function GetCurrentRealTime() native global - -; Returns whether the game is currently in menu mode or not -bool Function IsInMenuMode() native global - -; Generates a random integer between aiMin and aiMax (inclusive) -int Function RandomInt(int aiMin = 0, int aiMax = 100) native global - -; Generates a random floating point number between afMin and afMax (inclusive) -float Function RandomFloat(float afMin = 0.0, float afMax = 1.0) native global - -; Set the given INI by type -function SetINIFloat(string ini, float value) native global -function SetINIInt(string ini, int value) native global -function SetINIBool(string ini, bool value) native global -function SetINIString(string ini, string value) native global - -; Waits for the specified amount of time (latent). Timer will not run during menu mode -Function Wait(float afSeconds) native global - -; Waits for the specified amount of game time (latent) -Function WaitGameTime(float afHours) native global - -; Waits for the specified amount of time (latent) - Timer WILL run during menu mode -Function WaitMenuMode(float afSeconds) native global - -; Frame rate capture functions only available in beta version - -; Gets you a string describing the frame rate for a certain number of frames -; (String will be no longer than 1K characters long, separated by commas) -string Function CaptureFrameRate(int numFrames) native global - -; Starts or ends a frame rate capture -- then you can get the min or max since -; frame capture started at any time -Function StartFrameRateCapture() native global -Function EndFrameRateCapture() native global -float Function GetAverageFrameRate() native global -float Function GetMinFrameRate() native global -float Function GetMaxFrameRate() native global - -; Memory tracking functions - only available if memory tracking is turned on -int Function GetCurrentMemory() native global ; Must be called first, it sets up the memory stats used by the other functions -int Function GetBudgetCount() native global -int Function GetCurrentBudget(int aiBudgetNumber) native global -bool Function OverBudget(int aiBudgetNumber) native global -string Function GetBudgetName(int aiBudgetNumber) native global - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC - -float Function GetINIFloat(string ini) global native -int Function GetINIInt(string ini) global native -bool Function GetINIBool(string ini) global native -string Function GetINIString(string ini) global native - - -; Size is treated as unsigned, negative numbers will result -; extremely large positive numbers, USE WITH CARE -float[] Function CreateFloatArray(int size, float fill = 0.0) global native -int[] Function CreateIntArray(int size, int fill = 0) global native -bool[] Function CreateBoolArray(int size, bool fill = false) global native -string[] Function CreateStringArray(int size, string fill = "") global native -Form[] Function CreateFormArray(int size, Form fill = None) global native -Alias[] Function CreateAliasArray(int size, Alias fill = None) global native - -float[] Function ResizeFloatArray(float[] source, int size, float fill = 0.0) global native -int[] Function ResizeIntArray(int[] source, int size, int fill = 0) global native -bool[] Function ResizeBoolArray(bool[] source, int size, bool fill = false) global native -string[] Function ResizeStringArray(string[] source, int size, string fill = "") global native -Form[] Function ResizeFormArray(Form[] source, int size, Form fill = None) global native -Alias[] Function ResizeAliasArray(Alias[] source, int size, Alias fill = None) global native \ No newline at end of file diff --git a/modules/tests/psc_deps/VoiceType.psc b/modules/tests/psc_deps/VoiceType.psc deleted file mode 100644 index 7bd539f..0000000 --- a/modules/tests/psc_deps/VoiceType.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname VoiceType extends Form Hidden diff --git a/modules/tests/psc_deps/Weapon.psc b/modules/tests/psc_deps/Weapon.psc deleted file mode 100644 index 5ea6c9a..0000000 --- a/modules/tests/psc_deps/Weapon.psc +++ /dev/null @@ -1,122 +0,0 @@ -Scriptname Weapon extends Form Hidden - -; Fire this weapon base object from the specified source -Function Fire(ObjectReference akSource, Ammo akAmmo = None) native - - -; SKSE additions built 2015-05-24 00:46:48.937000 UTC - -int Function GetBaseDamage() native -Function SetBaseDamage(int damage) native - -int Function GetCritDamage() native -Function SetCritDamage(int damage) native - -float Function GetReach() native -Function SetReach(float reach) native - -float Function GetMinRange() native -Function SetMinRange(float minRange) native - -float Function GetMaxRange() native -Function SetMaxRange(float maxRange) native - -float Function GetSpeed() native -Function SetSpeed(float speed) native - -float Function GetStagger() native -Function SetStagger(float stagger) native - -int Function GetWeaponType() native -Function SetWeaponType(int type) native - -; works on the path to the nif file representing the in-game model of the weapon -string Function GetModelPath() native -Function SetModelPath(string path) native - -; works on the path to the nif file representing the icon for the weapon in the inventory -string Function GetIconPath() native -Function SetIconPath(string path) native - -; works on the path to the file representing the message icon for the weapon -string Function GetMessageIconPath() native -Function SetMessageIconPath(string path) native - -; works on the enchantment associated with the weapon -Enchantment Function GetEnchantment() native -Function SetEnchantment(Enchantment e) native - -; works on the enchantment value of the associated weapon -int Function GetEnchantmentValue() native -Function SetEnchantmentValue(int value) native - -; works on the weapon model when equipped of the associated weapon -Static Function GetEquippedModel() native -Function SetEquippedModel(Static model) native - -; Returns the particular equipslot type -EquipSlot Function GetEquipType() native -Function SetEquipType(EquipSlot type) native - -string Function GetSkill() native -Function SetSkill(string skill) native - -; DamageResist -; ElectricResist -; FireResist -; FrostResist -; MagicResist -; PoisonResist -string Function GetResist() native -Function SetResist(string resist) native - -; works on the spell that applies when critting -Spell Function GetCritEffect() native -Function SetCritEffect(Spell ce) native - -; Gets, sets or unsets whether the the crit effect should only occur on death -bool Function GetCritEffectOnDeath() native -Function SetCritEffectOnDeath(bool ceod) native - -; Gets/sets the weapons crit multiplier -float Function GetCritMultiplier() native -Function SetCritMultiplier(float crit) native - -; returns the weapon template of this weapon -Weapon Function GetTemplate() native - -bool Function IsBattleaxe() - return HasKeywordString("WeapTypeBattleaxe") -endFunction - -bool Function IsBow() - return HasKeywordString("WeapTypeBow") -endFunction - -bool Function IsDagger() - return HasKeywordString("WeapTypeDagger") -endFunction - -bool Function IsGreatsword() - return HasKeywordString("WeapTypeGreatsword") -endFunction - -bool Function IsMace() - return HasKeywordString("WeapTypeMace") -endFunction - -bool Function IsStaff() - return HasKeywordString("WeapTypeStaff") -endFunction - -bool Function IsSword() - return HasKeywordString("WeapTypeSword") -endFunction - -bool Function IsWarhammer() - return HasKeywordString("WeapTypeWarhammer") -endFunction - -bool Function IsWarAxe() - return HasKeywordString("WeapTypeWarAxe") -endFunction diff --git a/modules/tests/psc_deps/WordOfPower.psc b/modules/tests/psc_deps/WordOfPower.psc deleted file mode 100644 index f210078..0000000 --- a/modules/tests/psc_deps/WordOfPower.psc +++ /dev/null @@ -1 +0,0 @@ -Scriptname WordOfPower Extends Form Hidden \ No newline at end of file diff --git a/modules/tests/selective_headers_loading_test.v b/modules/tests/selective_headers_loading_test.v index d77a578..ad2aa50 100644 --- a/modules/tests/selective_headers_loading_test.v +++ b/modules/tests/selective_headers_loading_test.v @@ -13,16 +13,22 @@ const placeholder_objects = ["actor", "textureset", "keyword", "magiceffect", fn test_selective_headers_loading() { src_file := os.real_path(os.join_path("modules", "tests", "psc", "TestSelectiveLoading.psc")) output_dir := os.real_path(os.join_path("test-files", "compiled")) - header_dir := os.real_path(os.join_path("modules", "tests", "psc_deps")) - + + // Try multiple possible locations for the header directory + mut header_dir := os.real_path(os.join_path("modules", "tests", "sources", "psc_deps")) + + // If not found, try the original location + if !os.is_dir(header_dir) || !os.is_file(os.join_path(header_dir, "Form.psc")) { + header_dir = os.real_path(os.join_path("modules", "tests", "psc_deps")) + if !os.is_dir(header_dir) || !os.is_file(os.join_path(header_dir, "Form.psc")) { + assert false, "invalid header dir ${header_dir}" + } + } + if !os.is_file(src_file) { assert false, "invalid input file ${src_file}" } - if !os.is_dir(header_dir) || !os.is_file(os.join_path(header_dir, "Form.psc")) { - assert false, "invalid header dir ${header_dir}" - } - if !os.is_dir(output_dir) { os.mkdir(output_dir, os.MkdirParams{}) or { assert false, "failed to create output folder" } } @@ -34,6 +40,7 @@ fn test_selective_headers_loading() { backend: .check no_cache: true header_dirs: [ header_dir ] + output_mode: .silent } mut b := builder.new_builder(&prefs) @@ -46,8 +53,8 @@ fn test_selective_headers_loading() { } /* - // нужно проверить все ли необходимые типы загружены. - // есть те типы которые могут быть placeholder, но они не нужны?????????????????????????????????????????????? + // verify that all required types are loaded + // some types can be placeholders, but they are not needed for obj_name in placeholder_objects { if sym := b.table.find_type(obj_name) { assert sym.kind == .placeholder, obj_name diff --git a/modules/tests/sources b/modules/tests/sources new file mode 160000 index 0000000..0feb38c --- /dev/null +++ b/modules/tests/sources @@ -0,0 +1 @@ +Subproject commit 0feb38ce672772404160047406daa687083dd72f diff --git a/modules/tests/vm_tests_test.v b/modules/tests/vm_tests_test.v index c45bae4..7303e7f 100644 --- a/modules/tests/vm_tests_test.v +++ b/modules/tests/vm_tests_test.v @@ -31,7 +31,7 @@ fn test_builder() { backend: .pex no_cache: true header_dirs: [] - output_mode: pref.OutputMode.silent + output_mode: .silent } out_file1 := os.join_path(prefs.output_dir, "AAATestObject.pex") diff --git a/v.mod b/v.mod index 422bd19..07b8cab 100644 --- a/v.mod +++ b/v.mod @@ -1,7 +1,7 @@ Module { name: 'Papyrus Compiler' description: 'Papyrus Compiler' - version: '0.0.3' + version: '0.0.4' license: 'MIT' repo_url: 'https://github.com/russo-2025/papyrus-compiler' dependencies: []