Open source release

This commit imports the C# engine code and game files, excluding C++ source code.

[Source-Commit: ceb3d758046e50faa6258bc3b658a30c97743268]
This commit is contained in:
s&box team
2025-11-24 09:37:23 +01:00
commit 71f266059a
7435 changed files with 1331403 additions and 0 deletions

378
.editorconfig Normal file
View File

@@ -0,0 +1,378 @@
# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true
# Xml project files
[*.{csproj,slnx}]
indent_size = 2
# Xml config files
[*.{props,targets,config,nuspec}]
indent_size = 2
[*.json]
indent_size = 2
# C# files
[*.{cs,razor}]
indent_style = tab
indent_size = 4
# New line preferences
end_of_line = crlf
insert_final_newline = true
#### .NET Coding Conventions ####
# Organize usings
# dotnet_separate_import_directive_groups = false
# dotnet_sort_system_directives_first = true
file_header_template = unset
# this. and Me. preferences
dotnet_style_qualification_for_event = false:silent
dotnet_style_qualification_for_field = false:silent
dotnet_style_qualification_for_method = false:silent
dotnet_style_qualification_for_property = false:silent
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true:silent
dotnet_style_predefined_type_for_member_access = true:silent
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
# Expression-level preferences
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_namespace_match_folder = false
dotnet_style_null_propagation = true:suggestion
dotnet_style_object_initializer = true:suggestion
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true:suggestion
dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
# Field preferences
dotnet_style_readonly_field = true:suggestion
# Parameter preferences
dotnet_code_quality_unused_parameters = all:suggestion
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
#### C# Coding Conventions ####
# var preferences
csharp_style_var_elsewhere = false:silent
csharp_style_var_for_built_in_types = false:silent
csharp_style_var_when_type_is_apparent = false:silent
# Expression-bodied members
csharp_style_expression_bodied_accessors = true:silent
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_indexers = true:silent
csharp_style_expression_bodied_lambdas = true:suggestion
csharp_style_expression_bodied_local_functions = false:silent
csharp_style_expression_bodied_methods = false:silent
csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_properties = true:silent
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_prefer_extended_property_pattern = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_pattern_matching = true:silent
csharp_style_prefer_switch_expression = true:suggestion
# Null-checking preferences
csharp_style_conditional_delegate_call = true:suggestion
# Modifier preferences
csharp_prefer_static_anonymous_function = true:suggestion
csharp_prefer_static_local_function = true:warning
csharp_preferred_modifier_order = public,private,protected,internal,file,const,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:suggestion
csharp_style_prefer_readonly_struct = true:suggestion
csharp_style_prefer_readonly_struct_member = true:suggestion
# Code-block preferences
csharp_prefer_braces = true:silent
csharp_prefer_simple_using_statement = true:suggestion
csharp_style_namespace_declarations = file_scoped:suggestion
csharp_style_prefer_method_group_conversion = true:silent
csharp_style_prefer_primary_constructors = true:suggestion
csharp_style_prefer_top_level_statements = true:silent
# Expression-level preferences
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_prefer_index_operator = true:suggestion
csharp_style_prefer_local_over_anonymous_function = true:suggestion
csharp_style_prefer_null_check_over_type_check = true:suggestion
csharp_style_prefer_range_operator = true:suggestion
csharp_style_prefer_tuple_swap = true:suggestion
csharp_style_prefer_utf8_string_literals = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_unused_value_assignment_preference = discard_variable:suggestion
csharp_style_unused_value_expression_statement_preference = discard_variable:silent
# 'using' directive preferences
csharp_using_directive_placement = outside_namespace:silent
#### C# Formatting Rules ####
# New line preferences
csharp_new_line_before_catch = true
csharp_new_line_before_else = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = all
csharp_new_line_between_query_expression_clauses = true
# Indentation preferences
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true
csharp_indent_labels = no_change
csharp_indent_switch_labels = true
# Space preferences
csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = true
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses = true
csharp_space_between_parentheses = control_flow_statements
csharp_space_between_square_brackets = false
# Wrapping preferences
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true
#### Naming styles ####
# Naming rules
dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.symbols = types_and_namespaces
dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.interfaces_should_be_ipascalcase.severity = suggestion
dotnet_naming_rule.interfaces_should_be_ipascalcase.symbols = interfaces
dotnet_naming_rule.interfaces_should_be_ipascalcase.style = ipascalcase
dotnet_naming_rule.type_parameters_should_be_tpascalcase.severity = suggestion
dotnet_naming_rule.type_parameters_should_be_tpascalcase.symbols = type_parameters
dotnet_naming_rule.type_parameters_should_be_tpascalcase.style = tpascalcase
dotnet_naming_rule.methods_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.methods_should_be_pascalcase.symbols = methods
dotnet_naming_rule.methods_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.properties_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.properties_should_be_pascalcase.symbols = properties
dotnet_naming_rule.properties_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.events_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.events_should_be_pascalcase.symbols = events
dotnet_naming_rule.events_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.local_variables_should_be_camelcase.severity = suggestion
dotnet_naming_rule.local_variables_should_be_camelcase.symbols = local_variables
dotnet_naming_rule.local_variables_should_be_camelcase.style = camelcase
dotnet_naming_rule.local_constants_should_be_camelcase.severity = suggestion
dotnet_naming_rule.local_constants_should_be_camelcase.symbols = local_constants
dotnet_naming_rule.local_constants_should_be_camelcase.style = camelcase
dotnet_naming_rule.parameters_should_be_camelcase.severity = suggestion
dotnet_naming_rule.parameters_should_be_camelcase.symbols = parameters
dotnet_naming_rule.parameters_should_be_camelcase.style = camelcase
dotnet_naming_rule.public_fields_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.public_fields_should_be_pascalcase.symbols = public_fields
dotnet_naming_rule.public_fields_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.private_fields_should_be__camelcase.severity = suggestion
dotnet_naming_rule.private_fields_should_be__camelcase.symbols = private_fields
dotnet_naming_rule.private_fields_should_be__camelcase.style = _camelcase
dotnet_naming_rule.private_static_fields_should_be_s_camelcase.severity = suggestion
dotnet_naming_rule.private_static_fields_should_be_s_camelcase.symbols = private_static_fields
dotnet_naming_rule.private_static_fields_should_be_s_camelcase.style = s_camelcase
dotnet_naming_rule.public_constant_fields_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.public_constant_fields_should_be_pascalcase.symbols = public_constant_fields
dotnet_naming_rule.public_constant_fields_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.private_constant_fields_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.private_constant_fields_should_be_pascalcase.symbols = private_constant_fields
dotnet_naming_rule.private_constant_fields_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.symbols = public_static_readonly_fields
dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.symbols = private_static_readonly_fields
dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.enums_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.enums_should_be_pascalcase.symbols = enums
dotnet_naming_rule.enums_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.local_functions_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.local_functions_should_be_pascalcase.symbols = local_functions
dotnet_naming_rule.local_functions_should_be_pascalcase.style = pascalcase
dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase
# Symbol specifications
dotnet_naming_symbols.interfaces.applicable_kinds = interface
dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interfaces.required_modifiers =
dotnet_naming_symbols.enums.applicable_kinds = enum
dotnet_naming_symbols.enums.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.enums.required_modifiers =
dotnet_naming_symbols.events.applicable_kinds = event
dotnet_naming_symbols.events.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.events.required_modifiers =
dotnet_naming_symbols.methods.applicable_kinds = method
dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.methods.required_modifiers =
dotnet_naming_symbols.properties.applicable_kinds = property
dotnet_naming_symbols.properties.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.properties.required_modifiers =
dotnet_naming_symbols.public_fields.applicable_kinds = field
dotnet_naming_symbols.public_fields.applicable_accessibilities = public, internal
dotnet_naming_symbols.public_fields.required_modifiers =
dotnet_naming_symbols.private_fields.applicable_kinds = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
dotnet_naming_symbols.private_fields.required_modifiers =
dotnet_naming_symbols.private_static_fields.applicable_kinds = field
dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
dotnet_naming_symbols.private_static_fields.required_modifiers = static
dotnet_naming_symbols.types_and_namespaces.applicable_kinds = namespace, class, struct, interface, enum
dotnet_naming_symbols.types_and_namespaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types_and_namespaces.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
dotnet_naming_symbols.type_parameters.applicable_kinds = namespace
dotnet_naming_symbols.type_parameters.applicable_accessibilities = *
dotnet_naming_symbols.type_parameters.required_modifiers =
dotnet_naming_symbols.private_constant_fields.applicable_kinds = field
dotnet_naming_symbols.private_constant_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
dotnet_naming_symbols.private_constant_fields.required_modifiers = const
dotnet_naming_symbols.local_variables.applicable_kinds = local
dotnet_naming_symbols.local_variables.applicable_accessibilities = local
dotnet_naming_symbols.local_variables.required_modifiers =
dotnet_naming_symbols.local_constants.applicable_kinds = local
dotnet_naming_symbols.local_constants.applicable_accessibilities = local
dotnet_naming_symbols.local_constants.required_modifiers = const
dotnet_naming_symbols.parameters.applicable_kinds = parameter
dotnet_naming_symbols.parameters.applicable_accessibilities = *
dotnet_naming_symbols.parameters.required_modifiers =
dotnet_naming_symbols.public_constant_fields.applicable_kinds = field
dotnet_naming_symbols.public_constant_fields.applicable_accessibilities = public, internal
dotnet_naming_symbols.public_constant_fields.required_modifiers = const
dotnet_naming_symbols.public_static_readonly_fields.applicable_kinds = field
dotnet_naming_symbols.public_static_readonly_fields.applicable_accessibilities = public, internal
dotnet_naming_symbols.public_static_readonly_fields.required_modifiers = readonly, static
dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field
dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private, protected, protected_internal, private_protected
dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = readonly, static
dotnet_naming_symbols.local_functions.applicable_kinds = local_function
dotnet_naming_symbols.local_functions.applicable_accessibilities = *
dotnet_naming_symbols.local_functions.required_modifiers =
# Naming styles
dotnet_naming_style.pascalcase.required_prefix =
dotnet_naming_style.pascalcase.required_suffix =
dotnet_naming_style.pascalcase.word_separator =
dotnet_naming_style.pascalcase.capitalization = pascal_case
dotnet_naming_style.ipascalcase.required_prefix = I
dotnet_naming_style.ipascalcase.required_suffix =
dotnet_naming_style.ipascalcase.word_separator =
dotnet_naming_style.ipascalcase.capitalization = pascal_case
dotnet_naming_style.tpascalcase.required_prefix = T
dotnet_naming_style.tpascalcase.required_suffix =
dotnet_naming_style.tpascalcase.word_separator =
dotnet_naming_style.tpascalcase.capitalization = pascal_case
dotnet_naming_style._camelcase.required_prefix = _
dotnet_naming_style._camelcase.required_suffix =
dotnet_naming_style._camelcase.word_separator =
dotnet_naming_style._camelcase.capitalization = camel_case
dotnet_naming_style.camelcase.required_prefix =
dotnet_naming_style.camelcase.required_suffix =
dotnet_naming_style.camelcase.word_separator =
dotnet_naming_style.camelcase.capitalization = camel_case
dotnet_naming_style.s_camelcase.required_prefix = s_
dotnet_naming_style.s_camelcase.required_suffix =
dotnet_naming_style.s_camelcase.word_separator =
dotnet_naming_style.s_camelcase.capitalization = camel_case
# RS2008: Enable analyzer release tracking
dotnet_diagnostic.RS2008.severity = suggestion

5
Bootstrap.bat Normal file
View File

@@ -0,0 +1,5 @@
@echo off
dotnet run --project .\engine\Tools\SboxBuild\SboxBuild.csproj -- build --config Developer
dotnet run --project .\engine\Tools\SboxBuild\SboxBuild.csproj -- build-shaders
dotnet run --project .\engine\Tools\SboxBuild\SboxBuild.csproj -- build-content

28
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,28 @@
# Contributors guidelines
If you want to report bugs or request new features, see [sbox-issues](https://github.com/Facepunch/sbox-issues/)
## Making Changes
### Adding new features
Before you start trying to add a new feature, it should be something people want and has been discussed in a proposal issue ideally.
### Fixing bugs
If you're fixing a bug, make sure you reference any applicable bug reports, explain what the problem was and how it was solved.
Unit tests are always great where applicable.
### Guidelines
A few guidelines that will make it easier to review and merge your changes:
* **Scope**
* Keep your pull requests in scope and avoid unnecessary changes.
* **Commits**
* Should group relevant changes together, the message should explain concisely what it's doing, there should be a longer summary elaborating if required.
* Remove unnecessary commits and squash commits together where appropriate.
* **Formatting**
* Your IDE should adhere to the style set in `.editorconfig`
* Auto formatting can be done with `dotnet format`

27
LICENSE.md Normal file
View File

@@ -0,0 +1,27 @@
Copyright (c) 2025 Facepunch Studios Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
## Third-Party Components
This project includes third-party components that are separately licensed.
Those components are not covered by the MIT license above and remain subject
to their original licenses as indicated in `game/thirdpartylegalnotices`.

67
README.md Normal file
View File

@@ -0,0 +1,67 @@
<div align="center">
<img src="https://sbox.game/img/sbox-logo-square.svg" width="80px" alt="s&box logo">
[Website] | [Getting Started] | [Forums] | [Documentation] | [Contributing]
</div>
[Website]: https://sbox.game/
[Getting Started]: https://sbox.game/dev/doc/about/getting-started/first-steps/
[Forums]: https://sbox.game/f/
[Documentation]: https://sbox.game/dev/doc/
[Contributing]: CONTRIBUTING.md
# s&box
s&box is a modern game engine, built on Valve's Source 2 and the latest .NET technology, it provides a modern intuitive editor for creating games.
![s&box editor](https://files.facepunch.com/matt/1b2211b1/sbox-dev_FoZ5NNZQTi.jpg)
If your goal is to create games using s&box, please start with the [getting started guide](https://sbox.game/dev/doc/about/getting-started/first-steps/).
This repository is for building the engine from source for those who want to contribute to the development of the engine.
## Getting the Engine
### Steam
You can download and install the s&box editor directly from [Steam](https://sbox.game/give-me-that).
### Compiling from Source
If you want to build from source, this repository includes all the necessary files to compile the engine yourself.
#### Prerequisites
* [Git](https://git-scm.com/install/windows)
* [Visual Studio 2026](https://visualstudio.microsoft.com/)
* [.NET 10 SDK](https://dotnet.microsoft.com/en-us/download)
#### Building
```bash
# Clone the repo
git clone https://github.com/Facepunch/sbox-public.git
```
Once you've cloned the repo simply run `Bootstrap.bat` which will download dependencies and build the engine.
The game and editor can be run from the binaries in the game folder.
## Contributing
If you would like to contribute to the engine, please see the [contributing guide](CONTRIBUTING.md).
If you want to report bugs or request new features, see [sbox-issues](https://github.com/Facepunch/sbox-issues/).
## Documentation
Full documentation, tutorials, and API references are available at [sbox.game/dev/](https://sbox.game/dev/).
## License
The s&box engine source code is licensed under the [MIT License](LICENSE.md).
Certain native binaries in `game/bin` are not covered by the MIT license. These binaries are distributed under the s&box EULA. You must agree to the terms of the EULA to use them.
This project includes third-party components that are separately licensed.
Those components are not covered by the MIT license above and remain subject
to their original licenses as indicated in `game/thirdpartylegalnotices`.

7
engine/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
obj
bin
*.user
launchSettings.json
*.exe
*.pdb
.idea

View File

@@ -0,0 +1,21 @@
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
public class Program
{
public static void Main( string[] args )
{
var config = ManualConfig
.Create( DefaultConfig.Instance )
.WithOptions( ConfigOptions.JoinSummary | ConfigOptions.DisableLogFile | ConfigOptions.LogBuildOutput )
.AddJob( Job.MediumRun );
//BenchmarkRunner.Run<StringtHashSet>( config );
//BenchmarkRunner.Run<MemoryAlloc>( config );
//BenchmarkRunner.Run<StringHashing>( config );
BenchmarkRunner.Run<ByteStreamTest>( config );
//BenchmarkRunner.Run( typeof( Program ).Assembly, config );
}
}

View File

@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<OutputType>Exe</OutputType>
<NoWarn>1701;1702;1591;NETSDK1138</NoWarn>
<IsPackable>false</IsPackable>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<IsPublishable>false</IsPublishable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.14.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Sandbox.Bind\Sandbox.Bind.csproj" />
<ProjectReference Include="..\Sandbox.Generator\Sandbox.Generator.csproj" />
<ProjectReference Include="..\Sandbox.System\Sandbox.System.csproj" />
<ProjectReference Include="..\Sandbox.Engine\Sandbox.Engine.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,175 @@
using BenchmarkDotNet.Attributes;
using Sandbox;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
[MemoryDiagnoser]
[ThreadingDiagnoser]
public class ByteStreamTest
{
Guid Guid = Guid.NewGuid();
byte[] byteBuffer = new byte[34];
int initialBuffer = 512;
[GlobalSetup]
public void Setup()
{
}
[Benchmark]
public void ByteStreamInt()
{
using var writer = ByteStream.Create( initialBuffer );
for ( int i = 0; i < 512; i++ )
{
writer.Write( i );
}
}
[Benchmark]
public void ByteStreamByte()
{
using var writer = ByteStream.Create( initialBuffer );
for ( int i = 0; i < 512; i++ )
{
writer.Write( byteBuffer );
}
}
[Benchmark]
public void ByteStreamGuid()
{
using var writer = ByteStream.Create( initialBuffer );
for ( int i = 0; i < 512; i++ )
{
writer.Write( Guid );
}
}
[Benchmark]
public void ByteStreamString()
{
using var writer = ByteStream.Create( initialBuffer );
for ( int i = 0; i < 512; i++ )
{
writer.Write( "Hello there" );
}
}
[Benchmark]
public void PooledMemoryStreamInt()
{
var memoryStream = PooledMemoryStream.Rent( initialBuffer );
using var writer = new BinaryWriter( memoryStream, Encoding.UTF8, true );
for ( int i = 0; i < 512; i++ )
{
writer.Write( (uint)i );
}
}
[Benchmark]
public void PooledMemoryStreamByte()
{
var memoryStream = PooledMemoryStream.Rent( initialBuffer );
using var writer = new BinaryWriter( memoryStream, Encoding.UTF8, true );
for ( int i = 0; i < 512; i++ )
{
writer.Write( byteBuffer );
}
}
[Benchmark]
public unsafe void PooledMemoryStreamGuid()
{
var memoryStream = PooledMemoryStream.Rent( initialBuffer );
using var writer = new BinaryWriter( memoryStream, Encoding.UTF8, true );
for ( int i = 0; i < 512; i++ )
{
WriteGuid( writer, in Guid );
}
}
[Benchmark]
public unsafe void PooledMemoryStreamString()
{
var memoryStream = PooledMemoryStream.Rent( initialBuffer );
using var writer = new BinaryWriter( memoryStream, Encoding.UTF8, true );
for ( int i = 0; i < 512; i++ )
{
writer.Write( "Hello there" );
}
}
private void WriteGuid( BinaryWriter writer, in Guid guid )
{
Span<byte> buffer = stackalloc byte[16];
MemoryMarshal.Write( buffer, in guid );
writer.Write( buffer );
}
/// <summary>
/// A wrapper around <see cref="MemoryStream"/> used internally here to rent a pooled
/// stream and avoid allocations where possible.
/// </summary>
private class PooledMemoryStream : MemoryStream
{
private PooledMemoryStream( int capacity ) : base( capacity )
{
}
// Non-thread-safe pool queue
private static readonly Queue<PooledMemoryStream> Pool = new();
/// <summary>
/// Rent a new stream from the pool or create one if none are available.
/// </summary>
public static PooledMemoryStream Rent( int initialSize = 8192 )
{
if ( !Pool.TryDequeue( out var s ) )
return new PooledMemoryStream( initialSize );
s.Position = 0;
s.SetLength( 0 );
return s;
}
/// <summary>
/// Get a span of only the written portion of the buffer.
/// </summary>
public ReadOnlySpan<byte> GetWrittenSpan()
{
return new ReadOnlySpan<byte>( GetBuffer(), 0, (int)Length );
}
/// <summary>
/// Return this stream to the pool and reset it.
/// </summary>
public void Return()
{
Position = 0;
SetLength( 0 );
Pool.Enqueue( this );
}
protected override void Dispose( bool disposing )
{
throw new InvalidOperationException( "Use Return() instead of Dispose() to recycle the stream" );
}
}
}

View File

@@ -0,0 +1,101 @@
using BenchmarkDotNet.Attributes;
using Sandbox.Hashing;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
[MemoryDiagnoser]
public class StringHashing
{
[Params( 10, 50, 200, 1000, 3000, 5000, 10000, 200000 )]
public int StringSize { get; set; }
private string _testString;
[GlobalSetup]
public void Setup()
{
_testString = GenerateDeterministicString( StringSize );
}
private static string GenerateDeterministicString( int length )
{
var sb = new StringBuilder( length );
// First part: Generate some alphabet characters with variation
for ( int i = 0; i < length; i++ )
{
if ( i % 5 == 0 && i > 0 )
{
// Add a space every 5 characters for readability in shorter strings
sb.Append( ' ' );
}
else if ( i % 64 == 63 )
{
// Add some numeric variation every 64 characters
sb.Append( (i / 64) % 10 );
}
else
{
// Generate a deterministic pattern using the index
char c = (char)('a' + (i % 26));
// Capitalize some letters for variety
if ( i % 7 == 0 )
{
c = char.ToUpper( c );
}
sb.Append( c );
}
}
return sb.ToString();
}
[Benchmark( Baseline = true )]
public int GetHashCodeBuiltIn()
{
return _testString.GetHashCode();
}
[Benchmark]
public int FastHash2009()
{
return FastHashLegacy( _testString );
}
// Moved from Sandbox.Utility
// Preserved for future reference/comparison
public static int FastHashLegacy( string str )
{
// FNV-1a hash
uint hash = 0x811C9DC5;
byte[] data = Encoding.Unicode.GetBytes( str );
foreach ( byte b in data )
{
hash ^= b;
hash *= 0x1000193;
}
return unchecked((int)hash);
}
[Benchmark]
public int XxHash3DotNet10()
{
return (int)XxHash3.HashToUInt64( GetUtf16Bytes( _testString ) );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static ReadOnlySpan<byte> GetUtf16Bytes( string s )
{
ref char firstChar = ref MemoryMarshal.GetReference( s.AsSpan() );
return MemoryMarshal.CreateReadOnlySpan(
ref Unsafe.As<char, byte>( ref firstChar ),
s.Length * sizeof( char ) );
}
}

View File

@@ -0,0 +1,53 @@
using BenchmarkDotNet.Attributes;
using System.Buffers;
using System.Runtime.InteropServices;
[MemoryDiagnoser]
public unsafe class MemoryAlloc
{
const int allocSize = 1024 * 32;
[Benchmark]
public void AllocHGlobal()
{
var ptr = Marshal.AllocHGlobal( allocSize );
Marshal.FreeHGlobal( ptr );
}
[Benchmark]
public void MemoryPool()
{
using var ptr = MemoryPool<byte>.Shared.Rent( allocSize );
using var ptrPinned = ptr.Memory.Pin();
}
[Benchmark]
public void ArrayPool()
{
var ptr = ArrayPool<byte>.Shared.Rent( allocSize );
ArrayPool<byte>.Shared.Return( ptr );
}
[Benchmark]
public void ArrayPoolPinned()
{
var ptr = ArrayPool<byte>.Shared.Rent( allocSize );
var ptrHandle = GCHandle.Alloc( ptr, GCHandleType.Pinned );
ptrHandle.Free();
ArrayPool<byte>.Shared.Return( ptr );
}
[Benchmark]
public void NativeMemoryAlloc()
{
var data = NativeMemory.Alloc( allocSize );
NativeMemory.Free( data );
}
[Benchmark]
public void NativeMemoryBlock()
{
using var ptr = Sandbox.NativeMemoryBlock.GetOrCreatePooled( allocSize );
}
}

View File

@@ -0,0 +1,69 @@
using BenchmarkDotNet.Attributes;
using System;
using System.Collections.Generic;
//
// Does it matter that our style classes are stored in a HashSet<string> and not a HashSet<int>
// Answer: yes it fucking does
//
// | Method | Mean | Error | StdDev
// |--------------- |----------:|----------:|----------:
// | RegularHashSet | 17.592 ns | 0.2151 ns | 0.2012 ns
// | CaseHashSet | 16.023 ns | 0.2322 ns | 0.2172 ns
// | IntHashSet | 2.935 ns | 0.0774 ns | 0.0761 ns
[MemoryDiagnoser]
[ThreadingDiagnoser]
public class StringtHashSet
{
HashSet<string> subset;
HashSet<int> subsetInt;
HashSet<string> hashSetRegular;
HashSet<string> hashSetCaseins;
HashSet<int> hashSetInt;
[GlobalSetup]
public void Setup()
{
hashSetRegular = new HashSet<string>();
subset = new HashSet<string>();
subsetInt = new HashSet<int>();
hashSetCaseins = new HashSet<string>( StringComparer.OrdinalIgnoreCase );
hashSetInt = new HashSet<int>();
for ( int i = 0; i < 100; i++ )
{
var str = Guid.NewGuid().ToString().Substring( 0, 10 );
hashSetRegular.Add( str );
hashSetCaseins.Add( str );
hashSetInt.Add( str.GetHashCode() );
}
for ( int i = 0; i < 10; i++ )
{
var str = Guid.NewGuid().ToString().Substring( 0, 10 );
subset.Add( str );
subsetInt.Add( str.GetHashCode() );
}
}
[Benchmark]
public void RegularHashSet()
{
hashSetRegular.IsSubsetOf( subset );
}
[Benchmark]
public void CaseHashSet()
{
hashSetRegular.IsSubsetOf( subset );
}
[Benchmark]
public void IntHashSet()
{
hashSetInt.IsSubsetOf( subsetInt );
}
}

View File

@@ -0,0 +1,16 @@
using BenchmarkDotNet.Attributes;
using Sandbox.Internal;
[MemoryDiagnoser]
[ThreadingDiagnoser]
public class TypelibraryMark
{
[Benchmark]
public void AddAssembly()
{
var tl = new TypeLibrary();
tl.AddAssembly( typeof( Sandbox.CookieContainer ).Assembly, true );
}
}

43
engine/CodeGen.Targets Normal file
View File

@@ -0,0 +1,43 @@
<Project>
<PropertyGroup Condition="'$(OS)' == 'Windows_NT'">
<CodeGeneratorExe Condition="'$(CodeGeneratorExe)' == ''">..\\Tools\\CodeGen\\bin\\CodeGen.exe</CodeGeneratorExe>
</PropertyGroup>
<PropertyGroup Condition="'$(OS)' != 'Windows_NT'">
<CodeGeneratorExe Condition="'$(CodeGeneratorExe)' == ''">../Tools/CodeGen/bin/CodeGen</CodeGeneratorExe>
</PropertyGroup>
<Target Name="CleanCodeGen" AfterTargets="Clean">
<RemoveDir Directories="obj/.generated" />
</Target>
<ItemGroup>
<ProjectReference Include="../Tools/CodeGen/CodeGen.csproj" OutputItemType="CodeGenTool" ReferenceOutputAssembly="false" Private="true" />
</ItemGroup>
<Target Name="CodeGenFiles" BeforeTargets="CoreCompile" Condition="'$(DesignTimeBuild)' != 'true'">
<Message Importance="high" Text="Running Code Generation.."></Message>
<Exec Command="$(CodeGeneratorExe)" />
<Message Importance="high" Text="Code Generation Complete"></Message>
<ItemGroup>
<!-- Include all files in .generated directory but exclude assembly info files -->
<GeneratedFiles Include="obj/.generated/**/*.cs" Exclude="obj/.generated/obj/**/*.cs" />
</ItemGroup>
<!-- For each generated file, remove the corresponding file from Compile -->
<ItemGroup>
<Compile Remove="@(GeneratedFiles->'%(RecursiveDir)%(Filename)%(Extension)')" />
</ItemGroup>
<!-- Build -->
<ItemGroup>
<Compile Include="@(GeneratedFiles)" />
</ItemGroup>
</Target>
</Project>

View File

@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>1.0.1</VersionPrefix>
<TargetFramework>net10.0</TargetFramework>
<NoWarn>1701;1702;1591;NETSDK1138</NoWarn>
<IsPublishable>false</IsPublishable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,13 @@

#include "qanimgraph_previewdockwidget.h"
native class CQAnimGraphPreviewDockWidget as NativeAnimgraph.CQAnimGraphPreviewDockWidget
{
string GetPreviewModel();
void SetPreviewModel( string model );
}
managed static class Editor.Animgraph
{
QWidget CreateModelPicker( CQAnimGraphPreviewDockWidget widget );
}

View File

@@ -0,0 +1,47 @@

native class CUtlVector<IAssetType*> as NativeEngine.CUtlVectorAssetType
{
void DeleteThis(); [delete]
static CUtlVectorAssetType Create( int growsize, int initialcapacity ); [new]
int Count();
IAssetType Element( int i );
}
managed static class Editor.AssetSystem
{
void PreInitialize();
void AssetAdded( IAsset asset );
void AssetRemoved( uint index );
void AssetChanged( uint index );
void UpdateAssetAutoTags( uint index );
void RecordAssetOpen( uint index );
void AssetScanComplete();
void RegisterAssetType( int, IAssetType assetType );
void InitializeCompilerForFilename( IResourceCompilerContext context, string filename );
bool TryManagedCompile( IResourceCompilerContext context );
void OnSoundReload( string filename );
void OnSoundReloaded( string filename );
void OnDemandRecompile( uint index, string reason );
// Lots of parameters, a struct would be nice but pointers are weird in structs
void OpenPicker( QWidget pParentWidget, CUtlVectorAssetType assetTypes, IAssetPickerListener callback, int viewmode, IAsset selectedAsset, string titleAndSettingsName, bool cloudAllowed, string initialSearchText );
void PopulateAssetMenu( QMenu qMenu, IAsset asset );
}
// Wraps a AssetPickedInfo_t struct, least bullshit way to do it and we only use it once
native class AssetPickedWrapper
{
void DeleteThis(); [delete]
static AssetPickedWrapper Create(); [new]
void AddAsset( IAsset asset );
}
native class IAssetPickerListener
{
inline void NotifyAssetPicked( AssetPickedWrapper wrapper )
{
self->NotifyAssetPicked( wrapper->m_info );
}
}

View File

@@ -0,0 +1,151 @@

#include "assetsystem/iassetsystem.h"
#include "toolframework2/itoolframework2.h"
native enum AssetLocation_t;
native enum AssetRelatedPathType_t;
native class CUtlVector<IAsset*> as NativeEngine.CUtlVectorAsset
{
void DeleteThis(); [delete]
static CUtlVectorAsset Create( int growsize, int initialcapacity ); [new]
int Count();
IAsset Element( int i );
}
native class IAsset
{
string GetFriendlyName_Transient();
string GetRelativePath_Transient( AssetLocation_t source );
string GetAbsolutePath_Transient( AssetLocation_t source );
bool HasAnyFiles();
bool IsCached();
bool CanReload();
bool CanRecompile();
uint GetAssetIndexInt();
bool OpenInTool();
inline bool OpenInSecondaryTool( string tool )
{
EngineToolID_t nEditorTool = g_pToolFramework2->FindEngineTool( tool );
if ( nEditorTool == ENGINE_TOOL_INVALID )
return false;
CUtlVector< IAsset* > assetFiles;
assetFiles.AddToTail( self );
g_pToolFramework2->GetEngineToolByID( nEditorTool )->OpenInTool( assetFiles );
return true;
}
void GetAssetsIDependOn( CUtlVectorAsset pOutAssetsIDependOn, bool bDeep );
void GetAssetsIParent( CUtlVectorAsset pOutChildren, bool bDeep );
void GetAssetsIReference( CUtlVectorAsset pOutReferencers, bool bDeep );
void GetAssetsDependingOnMe( CUtlVectorAsset pOutDependencies, bool bDeep );
void GetAssetsReferencingMe( CUtlVectorAsset pOutReferencers, bool bDeep );
void GetAssetsParentingMe( CUtlVectorAsset pOutParents, bool bDeep );
int AdditionalRelatedFileCount();
int AdditionalInputDependencyCount();
string GetAdditionalRelatedFile_Transient( int nIndex );
string GetAdditionalInputDependency_Transient( int nIndex );
inline void GetUnrecognizedRelatedPaths( AssetRelatedPathType_t filterType, CUtlVectorString paths )
{
int nUnrecognized = this->UnrecognizedRelatedPathCount( filterType );
for ( int iAsset = 0; iAsset < nUnrecognized; ++iAsset )
{
CUtlString pathVal;
AssetRelatedPathType_t nGarbage;
bool bOptional;
if ( !this->GetUnrecognizedRelatedPath( filterType, iAsset, &pathVal, &nGarbage, &bOptional ) )
{
continue;
}
paths->AddToTail( pathVal );
}
}
void RequireDependencyInfo_Virtual();
bool NeedAnyDependencyUpdate_Virtual();
bool IsTrivialChildAsset();
bool HasHiddenAssetFlag();
inline int GetAssetTypeId()
{
return this->GetType()->GetIndex();
}
virtual void CacheAsset( bool bIsBlocking );
virtual void UncacheAsset();
inline bool HasSourceFile()
{
return this->HasFileInLocation( ASSET_LOCATION_CONTENT );
}
inline bool HasCompiledFile()
{
return this->HasFileInLocation( ASSET_LOCATION_GAME );
}
inline bool IsCompiled()
{
// Must have a resource type
bool bResourceAsset = ( this->GetResourceType() != RESOURCE_TYPE_NONE );
if ( false == bResourceAsset )
return false;
// Must have a file in GAME
if ( !this->HasFileInLocation( ASSET_LOCATION_GAME ) )
return false;
return true;
}
inline bool IsCompiledAndUpToDate()
{
return this->CompileState() == ASSET_FILE_COMPILED;
}
inline bool IsCompileFailed()
{
return this->CompileState() == ASSET_FILE_COMPILE_FAILED;
}
inline bool CompileIfNeeded()
{
return this->RecompileAsset( COMPILE_AS_NEEDED );
}
inline int FindIntEditInfo( string name )
{
int output = 0;
this->FindIntEditInfo( name, &output );
return output;
}
inline string FindStringEditInfo( string name )
{
CUtlString output;
this->FindStringEditInfo( name, &output );
return output;
}
string GetCompileStateReason_Transient();
inline bool SetInMemoryReplacement( string data )
{
CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
buf.PutString( data );
return self->CompileAndReplaceResource( buf );
}
void DiscardInMemoryReplacement();
}

View File

@@ -0,0 +1,10 @@

#include "assetpreview/iassetpreviewsystem.h"
native static accessor g_pAssetPreviewSystem as IAssetPreviewSystem
{
bool RenderAssetThumbnail( IAsset pAsset, QPixmap targetPixmap );
void OnThumbnailGenerated( IAsset asset, QPixmap renderedPixmap );
IModel GetModelForAsset( IAsset pAsset );
}

View File

@@ -0,0 +1,28 @@

#include "assetsystem/iassetsystem.h"
native static accessor g_pAssetSystem as IAssetSystem
{
void RecordAssetOpen( IAsset pAsset );
void RecordAssetOpen( string pAssetFileName );
IAsset FindAssetByFilename( string pFilename );
IAsset FindAssetByAssetRelativePath( string pFilename );
IAsset RegisterAssetFile( string pFilename );
void RunFrame();
void UpdateMods();
int GetAllModsCount();
inline bool RecompileAsset( IAsset asset, bool full )
{
CUtlVector<IAsset*> assets;
assets.AddToTail( asset );
return g_pAssetSystem->RecompileMultipleAssets( assets, full ? COMPILE_PARENTS_AND_CHILDREN_AND_ASSOCIATES : COMPILE_AS_NEEDED );
}
void UpdateGameResourceType( string title, string extension );
void LoadWorkingSetsAndTags();
}

View File

@@ -0,0 +1,24 @@

#include "assetsystem/iassetsystem.h"
native class IAssetType
{
string GetFriendlyName();
string GetIconLg();
string GetIconSm();
string GetPrimaryExtension();
string GetColor();
string GetCategory();
bool HideTypeByDefault();
bool IgnoreCompiledState();
bool IsContentFileText();
bool IsSimpleAsset();
bool HasDependencies();
bool PrefersIconForThumbnail();
string GetAssetTypeName();
void GetAdditionalExtensions( CUtlVectorString pExts );
}

View File

@@ -0,0 +1,68 @@

native class IResourceCompilerContext
{
void SetExtension( string name );
void SetCompiler( string name );
string FullPath();
string RelativePath();
string ResourceName();
void SpecifyResourceVersion( int nVersion );
void RegisterSpecialDependency( string str, uint nUserData, uint nFingerprint );
inline bool RegisterReference( string filename )
{
CPathBufferString fixedResourceName;
if ( !FixupResourceName( filename, &fixedResourceName ) )
return false;
ResourceType_t nType = DeduceResourceTypeFromResourceName( fixedResourceName );
self->RegisterResourceReference( nType, fixedResourceName );
return true;
}
inline void RegisterInputFileDependency( string filename, int flags )
{
self->RegisterInputFileDependency( filename, (InputFileDependencyFlags_t) flags );
}
inline int WriteBlock( string blockName, void* data, int count )
{
auto blockId = MK_RSRC_BLOCK_ID( blockName[0], blockName[1], blockName[2], blockName[3] );
return self->RegisterAdditionalBlock( blockId, data, count );
}
inline CUtlBuffer GetOverrideData()
{
return self->RequestBufferArg( "___OverrideInputData___", INPUT_DEPENDENCY_NORMAL );
}
CResourceStream Data();
CResourceStream StreamingData();
IResourceCompilerContextChild CreateChildContext( string pFileName );
}
native class CResourceStream
{
void WriteBytes( void* data, int size );
void Align( int alignment, int offset );
void AlignPointer();
uint Tell();
}
native class IResourceCompilerContextChild
{
inline void SetOverrideInputData( string data )
{
CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
buf.PutString( data );
self->SetOverrideInputData( buf );
}
bool CompileImmediately();
}

View File

@@ -0,0 +1,15 @@
//
// Built in c# functions like Unsafe.CopyBlockUnaligned benchmark slower
// than calling into native and using those methods instead. So lets do that.
//
[nogc]
native static class NativeLowLevel
{
inline void Copy( void* dest, void* src, long count )
{
V_memcpy( dest, src, (size_t)count );
}
}

View File

@@ -0,0 +1,43 @@
#include "vphysics2/iphysicsbody.h"
#include "vphysics2/iphysicsjoint.h"
[Handle:Sandbox.PhysicsGroup]
native class IPhysAggregateInstance as NativeEngine.IPhysAggregateInstance
{
void WakeUp();
void PutToSleep();
bool IsAsleep();
void SetVelocity( Vector3 v );
void AddVelocity( Vector3 v );
void SetAngularVelocity( Vector3 v );
void AddAngularVelocity( Vector3 v );
int GetBodyCount();
IPhysicsBody GetBodyHandle( int i );
string GetBodyName( int i );
uint GetBodyNameHash( int i );
IPhysicsBody GetBodyByNameHash( int i );
int GetBodyIndex( IPhysicsBody body );
IPhysicsBody FindBodyByName( string name );
int GetJointCount();
IPhysicsJoint GetJointHandle( int nIndex );
void RemoveJoint( IPhysicsJoint pJoint );
Vector3 GetOrigin();
Vector3 GetMassCenter();
void SetSurfaceProperties( StringToken name );
float GetTotalMass();
void SetTotalMass( float flMass );
void SetLinearDamping( float flLinearDamping );
void SetAngularDamping( float flAngularDamping );
IPhysicsWorld GetWorld();
}

View File

@@ -0,0 +1,126 @@
#include "vphysics2/iphysicsbody.h"
//
// Native Type
//
[Handle:Sandbox.PhysicsBody]
native class IPhysicsBody as NativeEngine.IPhysicsBody
{
IPhysicsWorld GetWorld();
void SetGravityScale( float f );
float GetGravityScale();
bool IsGravityEnabled();
void EnableGravity( bool value );
void SetMass( float f );
float GetMass();
Vector3 GetMassCenter();
Vector3 GetLocalMassCenter();
void SetLocalMassCenter( Vector3 v );
void SetOverrideMassCenter( bool bOverride );
bool GetOverrideMassCenter();
void SetPosition( Vector3 v );
Vector3 GetPosition();
void SetOrientation( Rotation q );
Rotation GetOrientation();
void SetTransform( Vector3 v, Rotation q );
Transform GetTransform();
void SetLinearVelocity( Vector3 v );
Vector3 GetLinearVelocity();
Vector3 GetVelocityAtPoint( Vector3 v );
void AddLinearVelocity( Vector3 v );
void SetAngularVelocity( Vector3 v );
Vector3 GetAngularVelocity();
void Wake();
void Sleep();
bool IsSleeping();
void EnableAutoSleeping();
void DisableAutoSleeping();
void EnableTouchEvents();
void DisableTouchEvents();
bool IsTouchEventEnabled();
PhysicsBodyType GetType();
void SetType( PhysicsBodyType type );
int GetShapeCount();
IPhysicsShape GetShape( int nShape );
IPhysicsShape AddSphereShape( Vector3 vCenter, float flRadius );
IPhysicsShape AddCapsuleShape( Vector3 vCenter1, Vector3 vCenter2, float flRadius );
IPhysicsShape AddBoxShape( Vector3 position, Rotation rotation, Vector3 extent );
IPhysicsShape AddHullShape( Vector3 position, Rotation rotation, int numVertices, CastTo[Vector*] void* vertices );
IPhysicsShape AddHullShape( RnHull_t hull, Transform xform );
IPhysicsShape AddHullShape( RnMesh_t mesh, Transform xform );
IPhysicsShape AddMeshShape( int numVertices, CastTo[Vector*] void* vertices, int numIndices, CastTo[uint32*] void* indices, int nMaterialCount );
IPhysicsShape AddMeshShape( RnMesh_t mesh, Transform xform, int nMaterialCount );
IPhysicsShape AddHeightFieldShape( CastTo[uint16_t*] void* pHeights, CastTo[uint8_t*] void* pMaterials, int sizeX, int sizeY, float sizeScale, float heightScale, int nMaterialCount );
void RemoveShape( IPhysicsShape pShape );
void PurgeShapes();
void ApplyLinearImpulse( Vector3 impulse );
void ApplyLinearImpulseAtWorldSpace( Vector3 impulse, Vector3 pos );
void ApplyAngularImpulse( Vector3 impulse );
void ApplyForce( Vector3 F );
void ApplyForceAt( Vector3 F, Vector3 r );
void ApplyTorque( Vector3 M );
void ClearForces();
void ClearTorque();
void Enable();
void Disable();
bool IsEnabled();
void BuildMass();
void SetLinearDamping( float d );
float GetLinearDamping();
void SetAngularDamping( float d );
float GetAngularDamping();
BBox BuildBounds();
float GetDensity();
Vector3 GetClosestPoint( Vector3 vPoint );
void SetMaterialIndex( StringToken name );
inline IPhysAggregateInstance GetAggregate()
{
return static_cast<IPhysAggregateInstance*>(self->GetAggregateInstance());
}
void SetTargetTransform( Vector3 vTargetPosition, Rotation vTargetAngles, float flTimeOffset );
bool CheckOverlap( IPhysicsBody body, Transform transform );
Vector3 GetLocalInertiaVector();
Rotation GetLocalInertiaOrientation();
void SetLocalInertia( Vector3 vInertia, Rotation qRotation );
void ResetLocalInertia();
inline IPhysicsBody ManagedObject()
{
return self;
}
void SetMotionLocks( bool x, bool y, bool z, bool pitch, bool yaw, bool roll );
bool IsTouching( IPhysicsBody pBody, bool bTriggers );
bool IsTouching( IPhysicsShape pShape, bool bTriggers );
void SetTrigger( bool trigger );
}

View File

@@ -0,0 +1,88 @@
#include "vphysics2/iphysicsbody.h"
#include "vphysics2/iphysicsjoint.h"
[Handle:Sandbox.Physics.PhysicsJoint]
native class IPhysicsJoint as NativeEngine.IPhysicsJoint
{
IPhysicsWorld GetWorld();
IPhysicsBody GetBody1();
IPhysicsBody GetBody2();
void GetLocalFrameA( cref out Vector3 position, cref out Quaternion rotation );
void GetLocalFrameB( cref out Vector3 position, cref out Quaternion rotation );
void SetLocalFrameA( Vector3 position, Quaternion rotation );
void SetLocalFrameB( Vector3 position, Quaternion rotation );
void SetEnableCollision( bool bEnabled );
bool IsCollisionEnabled();
PhysicsJointType GetType();
void SetLinearSpring( Vector3 vec );
Vector3 GetLinearSpring();
void SetAngularSpring( Vector3 vec );
Vector3 GetAngularSpring();
void SetAngularMotor( float targetVelocity, float maxTorque );
void SetMinLength( float f );
float GetMinLength();
void SetMaxLength( float f );
float GetMaxLength();
void SetMinForce( float f );
float GetMinForce();
void SetMaxForce( float f );
float GetMaxForce();
void SetFriction( float f );
void SetLimit( string name, Vector3 limit );
void SetLimitEnabled( string name, bool state );
float GetAngle();
float GetLinearImpulse();
float GetAngularImpulse();
float GetMaxLinearImpulse();
float GetMaxAngularImpulse();
void SetMaxLinearImpulse( float flMaxLinearImpulse );
void SetMaxAngularImpulse( float flMaxAngularImpulse );
void SetMotorVelocity( Vector3 velocity, float maxTorque );
void SetTargetRotation( Rotation rotation, float hertz, float damping );
void Motor_SetLinearVelocity( Vector3 velocity );
void Motor_SetAngularVelocity( Vector3 velocity );
void Motor_SetMaxVelocityForce( float maxForce );
void Motor_SetMaxVelocityTorque( float maxTorque );
void Motor_SetLinearHertz( float hertz );
void Motor_SetLinearDampingRatio( float damping );
void Motor_SetAngularHertz( float hertz );
void Motor_SetAngularDampingRatio( float damping );
void Motor_SetMaxSpringForce( float maxForce );
void Motor_SetMaxSpringTorque( float maxTorque );
Vector3 Motor_GetLinearVelocity();
Vector3 Motor_GetAngularVelocity();
float Motor_GetMaxVelocityForce();
float Motor_GetMaxVelocityTorque();
float Motor_GetLinearHertz();
float Motor_GetLinearDampingRatio();
float Motor_GetAngularHertz();
float Motor_GetAngularDampingRatio();
float Motor_GetMaxSpringForce();
float Motor_GetMaxSpringTorque();
}
managed static class Sandbox.Physics.PhysicsEngine
{
static void OnPhysicsJointBreak( IPhysicsJoint joint );
static void OnActive( IPhysicsBody body, Transform transform, Vector3 velocity, Vector3 linearVelocity );
}

View File

@@ -0,0 +1,86 @@
#include "vphysics2/iphysicsbody.h"
#include "vphysics2/iphysicsshape.h"
#include "vphysics2/iphysicsjoint.h"
native class CQueryResult as NativeEngine.CQueryResult
{
void DeleteThis(); [delete]
static CQueryResult Create(); [new]
int Count();
IPhysicsShape Element( int i );
}
[Handle:Sandbox.PhysicsShape]
native class IPhysicsShape as NativeEngine.IPhysicsShape
{
void AddCollisionFunctionMask( byte nMask );
void RemoveCollisionFunctionMask( byte nMask );
inline byte GetCollisionFunctionMask()
{
return self->GetCollisionAttributes().GetCollisionFunctionMask();
}
bool HasTag( uint tag );
bool AddTag( uint tag );
bool RemoveTag( uint tag );
bool ClearTags();
IPhysicsBody GetBody();
void SetMaterialIndex( StringToken name );
void SetSurfaceIndex( int nSurfaceIndex, int index );
inline string GetMaterialName()
{
if ( !self->GetMaterial().m_pUserData ) return "";
return self->GetMaterial().m_pUserData->m_name.Get();
}
PhysicsShapeType GetType();
void UpdateMeshShape( int numVertices, CastTo[Vector*] void* vertices, int numIndices, CastTo[uint32*] void* indices );
void UpdateHeightShape( CastTo[uint16_t*] void* pHeights, CastTo[uint8_t*] void* pMaterials, int x, int y, int w, int h, float SizeScale, float HeightScale );
void UpdateSphereShape( Vector3 vCenter, float flRadius );
void UpdateCapsuleShape( Vector3 vCenter1, Vector3 vCenter2, float flRadius );
void UpdateHullShape( Vector position, Rotation rotation, int nVertexCount, CastTo[Vector*] void* pvVertexBase );
inline IPhysicsShape ManagedObject()
{
return self;
}
void SetTrigger( bool trigger );
bool IsTrigger();
void GetTriangulation( CUtlVectorVector arrVectors, CUtlVectorUInt32 arrIndices );
void GetTriangulationForNavmesh( CUtlVectorVector arrVectors, CUtlVectorUInt32 arrIndices, BBox bounds );
void GetOutline( CUtlVectorVector arrVectors );
Sphere AsSphere();
Capsule AsCapsule();
void UpdateBoxShape( Vector3 vCenter, Rotation qRotation, Vector3 vExtents );
void SetFriction( float f );
float GetFriction();
void SetLocalVelocity( Vector3 v );
Vector3 GetLocalVelocity();
void SetElasticity( float f );
void SetRollingResistance( float f );
void SetIgnoreTraces( bool b );
void SetHasNoMass( bool b );
BBox BuildBounds();
inline BBox LocalBounds()
{
return self->BuildBounds( g_MatrixIdentity );
}
bool IsTouching( IPhysicsShape pShape, bool bTriggers );
}

View File

@@ -0,0 +1,89 @@
#include "vphysics2/iphysicsbody.h"
native enum JointMotion_t is Sandbox.JointMotion;
native enum PhysicsBodyType_t is Sandbox.PhysicsBodyType;
native enum PhysicsJointType_t is Sandbox.PhysicsJointType;
native enum PhysicsShapeType_t is Sandbox.PhysicsShapeType;
native enum PhysicsSimulation_t is Sandbox.PhysicsSimulationMode;
native enum VPhysicsMotionType_t is Sandbox.PhysicsMotionType;
delegate ProcessIntersectionsDelegate_t;
delegate DebugDrawDelegate_t;
[Handle:Sandbox.PhysicsWorld]
native class IPhysicsWorld
{
// Bodies
IPhysicsBody AddBody();
void RemoveBody( IPhysicsBody pBody );
IPhysicsBody GetWorldReferenceBody();
void SetWorldReferenceBody( IPhysicsBody pBody );
// Joints
void RemoveJoint( IPhysicsJoint pJoint );
void SetGravity( Vector3 gravity );
Vector3 GetGravity();
void SetSimulation( PhysicsSimulationMode simulation );
PhysicsSimulationMode GetSimulation();
// Sleeping
void EnableSleeping();
void DisableSleeping();
bool IsSleepingEnabled();
void SetMaximumLinearSpeed( float flSpeed );
IPhysicsJoint AddWeldJoint( IPhysicsBody pBody1, IPhysicsBody pBody2, Transform localFrame1, Transform localFrame2 );
IPhysicsJoint AddSpringJoint( IPhysicsBody pBody1, IPhysicsBody pBody2, Transform localFrame1, Transform localFrame2 );
IPhysicsJoint AddRevoluteJoint( IPhysicsBody pBody1, IPhysicsBody pBody2, Transform localFrame1, Transform localFrame2 );
IPhysicsJoint AddPrismaticJoint( IPhysicsBody pBody1, IPhysicsBody pBody2, Transform localFrame1, Transform localFrame2 );
IPhysicsJoint AddSphericalJoint( IPhysicsBody pBody1, IPhysicsBody pBody2, Transform localFrame1, Transform localFrame2 );
IPhysicsJoint AddMotorJoint( IPhysicsBody pBody1, IPhysicsBody pBody2, Transform localFrame1, Transform localFrame2 );
//
// Sets the collision rules using a json serialized Sandbox.Internal.CollisionRules
//
void SetCollisionRulesFromJson( string rules );
inline void StepSimulation( float flTimestep, int nNumSteps )
{
g_pPhysicsSystem->StepSimulation( &self, 1, flTimestep, nNumSteps );
}
void ProcessIntersections( ProcessIntersectionsDelegate_t f );
void DestroyAggregateInstance( IPhysAggregateInstance pAggregate );
inline IPhysAggregateInstance CreateAggregateInstance( string resourceName, Transform tmStart, ulong nGSNHandle, PhysicsMotionType nMotionType )
{
HPhysAggregateData_Internal hPhysicsData = g_pResourceSystem->FindExistingResourceByName< RESOURCE_TYPE_PHYSICSDATA_INTERNAL >( CResourceName( resourceName ) );
IPhysAggregateInstance *pInstance = nullptr;
if ( !hPhysicsData.HasData() )
return pInstance;
pInstance = self->CreateAggregateInstance( hPhysicsData, tmStart, nGSNHandle, nMotionType );
return pInstance;
}
inline IPhysAggregateInstance CreateAggregateInstance( IModel model, Transform tmStart, ulong nGSNHandle, PhysicsMotionType nMotionType )
{
return self->CreateAggregateInstance( model->GetPhysicsContainer(), tmStart, nGSNHandle, nMotionType );
}
void SetDebugScene( ISceneWorld world );
ISceneWorld GetDebugScene();
void Draw( DebugDrawDelegate_t debugDrawFcn );
inline IPhysicsWorld ManagedObject()
{
return self;
}
void Query( cref CQueryResult result, Vector3 vCenter, float flRadius, CastTo[RnQueryObjectSet] ushort nObjectSetMask );
void Query( cref CQueryResult result, AABB_t bounds, CastTo[RnQueryObjectSet] ushort nObjectSetMask );
void Query( cref CQueryResult result, CastTo[Vector*] void* pPoints, int nPoints, CastTo[RnQueryObjectSet] ushort nObjectSetMask );
}

View File

@@ -0,0 +1,59 @@

native class CRenderAttributes as NativeEngine.CRenderAttributes
{
void DeleteThis(); [delete]
static CRenderAttributes Create(); [new]
void SetFloatValue( StringToken nTokenID, float flValue );
float GetFloatValue( StringToken nTokenID, float flDefaultValue );
void DeleteFloatValue( StringToken nTokenID );
void SetVector2DValue( StringToken nTokenID, Vector2 vValue );
Vector2 GetVector2DValue( StringToken nTokenID, Vector2 vDefaultValue );
void DeleteVector2DValue( StringToken nTokenID );
void SetVectorValue( StringToken nTokenID, Vector3 vValue );
Vector3 GetVectorValue( StringToken nTokenID, Vector3 vDefaultValue );
void DeleteVectorValue( StringToken nTokenID );
void SetVector4DValue( StringToken nTokenID, Vector4 vValue );
Vector4 GetVector4DValue( StringToken nTokenID, Vector4 vDefaultValue );
void DeleteVector4DValue( StringToken nTokenID );
void SetVMatrixValue( StringToken nTokenID, Matrix value );
Matrix GetVMatrixValue( StringToken nTokenID, Matrix vDefaultValue );
void DeleteVMatrixValue( StringToken nTokenID );
void SetStringValue( StringToken nTokenID, string str );
void DeleteStringValue( StringToken nTokenID );
void SetIntValue( StringToken nTokenID, int nValue );
int GetIntValue( StringToken nTokenID, int nDefaultValue );
void DeleteIntValue( StringToken nTokenID );
void SetComboValue( StringToken nTokenID, byte nValue );
byte GetComboValue( StringToken nTokenID, byte nValue );
void DeleteComboValue( StringToken nTokenID );
void SetBoolValue( StringToken nTokenID, bool bValue );
bool GetBoolValue( StringToken nTokenID, bool bValue );
void DeleteBoolValue( StringToken nTokenID );
void SetTextureValue( StringToken nTokenID, ITexture txtr, int nSingleMipLevelToBind );
ITexture GetTextureValue( StringToken nTokenID, ITexture defaultTxtr );
void DeleteTextureValue( StringToken nTokenID );
void SetSamplerValue( StringToken nTokenID, CSamplerStateDesc samplerDesc );
void SetBufferValue( StringToken nTokenID, RenderBufferHandle_t hRenderBuffer );
void SetPtrValue( StringToken nTokenID, void* ptr );
void DeletePtrValue( StringToken nTokenID );
void SetIntVector4DValue( StringToken nTokenID, int x, int y, int z, int w );
void MergeToPtr( CRenderAttributes attrList );
bool IsEmpty();
void Clear( bool freeMemory, bool resetParent );
}

View File

@@ -0,0 +1,23 @@
#include "sbox/imanagedrenderpipeline.h"
native struct ManagedRenderSetup_t;
native enum ManagedRenderHookStage is Sandbox.Rendering.Stage;
managed static class Sandbox.Graphics
{
//
// Called multiple times per rendering, for each stage.
//
void OnLayer( int renderHookStage, ManagedRenderSetup_t setup );
}
managed static class Sandbox.RenderTarget
{
void Flush();
}
managed static class Sandbox.Rendering.RenderPipeline
{
void InternalAddLayersToView( ISceneView view, RenderViewport viewport, HSceneViewRenderTarget hColor, HSceneViewRenderTarget hDepth, RenderMultisampleType nMSAA, CRenderAttributes pipelineAttributes, RenderViewport screenDimensions );
void InternalPipelineEnd( ISceneView view, RenderViewport viewport, HSceneViewRenderTarget hColor, HSceneViewRenderTarget hDepth, RenderMultisampleType nMSAA, CRenderAttributes pipelineAttributes, RenderViewport screenDimensions );
}

View File

@@ -0,0 +1,4 @@
native class IMaterialMode as NativeEngine.IMaterialMode
{
}

View File

@@ -0,0 +1,9 @@

native class IPVS
{
bool IsEmptyPVS();
bool IsInPVS( int numSources, CastTo[Vector*] void* sources, Vector position );
bool IsAbsBoxInPVS( int numSources, CastTo[Vector*] void* sources, Vector mins, Vector maxs );
bool IsSkyVisibleFromPosition( Vector position );
bool IsSunVisibleFromPosition( Vector position );
}

View File

@@ -0,0 +1,170 @@
native enum RenderPrimitiveType_t as NativeEngine.RenderPrimitiveType
native enum RenderTextureDimension_t as NativeEngine.RenderTextureDimension
native enum RenderShaderType_t as NativeEngine.RenderShaderType
native enum RenderColorSpace_t as NativeEngine.RenderColorSpace
native enum RsFilter_t is Sandbox.Rendering.FilterMode;
native enum RsTextureAddressMode_t is Sandbox.Rendering.TextureAddressMode;
native enum RsComparison_t is NativeEngine.ComparisonMode;
native enum RenderBarrierAccessFlags_t is NativeEngine.RenderBarrierAccessFlags_t;
native enum RenderBarrierPipelineStageFlags_t is NativeEngine.RenderBarrierPipelineStageFlags_t;
native pointer VertexBufferHandle_t as NativeEngine.VertexBufferHandle_t
native pointer IndexBufferHandle_t as NativeEngine.IndexBufferHandle_t
native pointer RenderShaderHandle_t as NativeEngine.RenderShaderHandle_t
native enum RenderImageLayout_t is NativeEngine.RenderImageLayout_t;
native class IReadTexturePixelsCallback as NativeEngine.IReadTexturePixelsCallback
{
}
native class IReadBufferCallback as NativeEngine.IReadBufferCallback
{
}
native class IRenderContext as NativeEngine.IRenderContext
{
void Draw( RenderPrimitiveType type, int nFirstVertex, int nVertexCount );
void DrawInstanced( RenderPrimitiveType type, int nFirstVertex, int nVertexCountPerInstance, int nInstanceCount );
void DrawIndexed( RenderPrimitiveType type, int nFirstIndex, int nIndexCount, int nMaxVertexCount, int nBaseVertex );
void DrawIndexedInstanced( RenderPrimitiveType type, int nFirstIndex, int nIndexCountPerInstance, int nInstanceCount, int nMaxVertexCount, int nBaseVertex );
void DrawInstancedIndirect( RenderPrimitiveType type, RenderBufferHandle_t hDrawArgBuffer, uint nBufferOffset );
void DrawIndexedInstancedIndirect( RenderPrimitiveType type, RenderBufferHandle_t hDrawArgBuffer, uint nBufferOffset );
inline void TextureBarrierTransition( ITexture hSrc, int mips, RenderBarrierPipelineStageFlags_t srcStage, RenderBarrierPipelineStageFlags_t dstStage, RenderImageLayout_t layout, RenderBarrierAccessFlags_t srcFlags, RenderBarrierAccessFlags_t dstFlags )
{
RenderUAVBarrier_t uavBarrier { hSrc, srcStage, dstStage, srcFlags, dstFlags, -1, -1, layout };
self->TextureBarrier( 1, &hSrc, &layout );
self->UAVBarrier( 1, &uavBarrier );
}
inline void BufferBarrierTransition( RenderBufferHandle_t hSrc, RenderBarrierPipelineStageFlags_t srcStage, RenderBarrierPipelineStageFlags_t dstStage, RenderBarrierAccessFlags_t srcFlags, RenderBarrierAccessFlags_t dstFlags )
{
self->BufferBarrier( RenderBufferBarrier_t{ hSrc, srcStage, dstStage, srcFlags, dstFlags } );
}
void SetScissorRect( NativeRect rect );
CRenderAttributes GetAttributesPtrForModify();
void GenerateMipMaps( ITexture material );
inline void Clear( Vector4 col, bool clearColor, bool clearDepth, bool clearStencil )
{
RenderClearFlags_t flags = (RenderClearFlags_t)0;
if ( clearColor ) flags |= RENDER_CLEAR_FLAGS_CLEAR_COLOR;
if ( clearDepth ) flags |= RENDER_CLEAR_FLAGS_CLEAR_DEPTH;
if ( clearStencil ) flags |= RENDER_CLEAR_FLAGS_CLEAR_STENCIL;
self->Clear( col, flags );
}
inline void BindRenderTargets( ITexture colorTexture, ITexture depthTexture, ISceneLayer layer )
{
// We can have a layer that only renders to color but if we only bind depth assume we want to blit to main framebuffer
if( colorTexture == RENDER_TEXTURE_HANDLE_INVALID )
colorTexture = layer->GetRenderTargetDesc().m_pColorTargets[0];
RenderTargetDesc_t rtDesc( colorTexture, depthTexture, RENDER_SRGB );
self->BindRenderTargets( rtDesc );
}
inline void RestoreRenderTargets( ISceneLayer layer )
{
self->BindRenderTargets( layer->GetRenderTargetDesc() );
}
inline void SetViewport( Rect_t rect )
{
RenderViewport_t vp;
vp.Init( rect );
self->SetViewports( 1, &vp );
}
inline void SetViewport( RenderViewport_t viewport )
{
self->SetViewports( 1, &viewport );
}
inline void SetViewport( int x, int y, int w, int h )
{
RenderViewport_t vp;
vp.Init( x, y, w, h );
self->SetViewports( 1, &vp );
}
inline RenderViewport_t GetViewport()
{
RenderViewport_t viewport;
self->GetViewport( &viewport, 0 );
return viewport;
}
void Submit();
void SetAssociatedThreadIndex();
inline void BindRenderTargets( SwapChainHandle_t swapChain, bool color, bool depth )
{
self->BindRenderTargets( RenderTargetDesc_t( swapChain, color, depth ) );
}
bool BindIndexBuffer( IndexBufferHandle_t hIndexBuffer, int nOffset );
bool BindIndexBuffer( RenderBufferHandle_t hIndexBuffer, int nIndexSize, int nOffset );
bool BindVertexBuffer( int nSlot, VertexBufferHandle_t hVertexBuffer, int nOffset );
bool BindVertexBuffer( int nSlot, VertexBufferHandle_t hVertexBuffer, int nOffset, int nStride );
bool BindVertexBuffer( int nSlot, RenderBufferHandle_t hVertexBuffer, int nOffset );
bool BindVertexBuffer( int nSlot, RenderBufferHandle_t hVertexBuffer, int nOffset, int nStride );
inline void BindVertexShader( RenderShaderHandle_t hVertexShader, VertexBufferHandle_t hInputLayout )
{
self->BindVertexShader( hVertexShader, self->GetInputLayoutForVertexBuffer( hInputLayout ) );
}
inline void BindPixelShader( RenderShaderHandle_t hShader )
{
self->BindShader( RENDER_PIXEL_SHADER, hShader );
}
inline void SetDynamicConstantBufferData( RenderShaderType shaderType, void* pData, int nSize, int slot )
{
DynamicLockDesc_t lock;
ConstantBufferHandle_t hConstantBuffer = self->LockDynamicConstantBuffer( nSize, &lock );
if ( lock.m_pMemory != nullptr )
{
V_memcpy( lock.m_pMemory, pData, nSize );
self->UnlockDynamicConstantBuffer( hConstantBuffer, nSize );
self->BindConstantBuffer( shaderType, hConstantBuffer, 0 );
}
}
inline void BindTexture( int nTextureIndex, ITexture hTexture )
{
self->SetSamplerStatePS( 0, RS_FILTER_MIN_MAG_MIP_POINT, RS_TEXTURE_ADDRESS_WRAP, RS_TEXTURE_ADDRESS_WRAP, RS_TEXTURE_ADDRESS_WRAP );
self->BindTexture( nTextureIndex, hTexture, RENDER_TEXTURE_DIMENSION_2D, RENDER_PIXEL_SHADER, RENDER_SRGB );
}
inline void ReadTexturePixels(ITexture hTexture, IReadTexturePixelsCallback pCallback, NativeRect srcRect, int nSrcSlice, int nSrcMip, bool bDeleteCallbackWhenFinished )
{
Rect_t* pSrcRect = nullptr;
if ( !srcRect.IsEmpty() )
{
pSrcRect = &srcRect;
}
self->ReadTexturePixels( hTexture, pCallback, pSrcRect, nSrcSlice, nSrcMip, bDeleteCallbackWhenFinished );
}
void ReadBuffer( RenderBufferHandle_t hBuffer, IReadBufferCallback pCallback, int nOffset, int nBytesToRead, bool bDeleteCallbackWhenFinished );
// PIX/RenderDoc markers
void BeginPixEvent( string name );
void EndPixEvent();
void PixSetMarker( string name );
}

View File

@@ -0,0 +1,78 @@

native accessor g_pWorldRendererMgr
{
void ServiceWorldRequests();
inline uint UpdateObjectsForRendering( StringToken worldGroupId, Vector3 eyePos, float flLODScale, float flMaxVisibleDistance )
{
return g_pWorldRendererMgr->UpdateObjectsForRendering( worldGroupId, eyePos, flLODScale, flMaxVisibleDistance );
}
inline IWorldReference CreateWorld( string pMapName, ISceneWorld pSceneWorld, bool bAsyncLoad, bool bIgnoreExistingWorlds, bool bLoadVis, bool bPrecacheOnly, StringToken worldGroupId, Transform transform )
{
CreateWorldInfo_t info;
info.m_pWorldName = pMapName;
info.m_pSceneWorld = pSceneWorld;
info.m_bAsyncLoad = bAsyncLoad;
info.m_bLoadVis = bLoadVis;
info.m_worldGroupId = worldGroupId;
info.m_bPrecacheOnly = bPrecacheOnly;
info.m_bIgnoreExistingWorlds = bIgnoreExistingWorlds;
info.m_mWorldTransform = transform.ToMatrix();
return g_pWorldRendererMgr->CreateWorld( info );
}
bool MountWorldVPK( string pWorldName, string pVpkPath );
bool UnmountWorldVPK( string pWorldName );
}
native class IWorldReference as NativeEngine.IWorldReference
{
void Release();
bool IsWorldLoaded();
bool IsErrorWorld();
bool IsMarkedForDeletion();
bool GetWorldBounds( cref out Vector3 vMin, cref out Vector vMax );
ISceneWorld GetSceneWorld();
void PrecacheAllWorldNodes( CastTo[WorldNodeFlags_t] uint flags );
string GetFolder();
inline int GetEntityCount( string pEntityLumpName )
{
const CUtlVector< const CEntityKeyValues* > *pEnts = g_pWorldRendererMgr->GetEntityList( self, pEntityLumpName );
return pEnts ? pEnts->Count() : 0;
}
inline CEntityKeyValues GetEntityKeyValues( string pEntityLumpName, int index )
{
const CUtlVector< const CEntityKeyValues* > *pEnts = g_pWorldRendererMgr->GetEntityList( self, pEntityLumpName );
return pEnts ? pEnts->Element( index ) : 0;
}
inline void SetWorldTransform( Transform transform )
{
if ( IWorld *pGeometryWorld = self->GetGeometryWorld() )
{
pGeometryWorld->SetWorldTransform( transform.ToMatrix() );
}
}
}
native class CEntityKeyValues as NativeEngine.CEntityKeyValues
{
string GetValueString( StringToken key, string pDefaultValue );
int GetKeyCount();
inline uint GetKey( int nIdx )
{
return self->GetKey( nIdx ).GetHashCode();
}
inline string GetValueString( uint key, string pDefaultValue )
{
return self->GetValueString( StringTokenFromHashCode( key ), pDefaultValue );
}
}

View File

@@ -0,0 +1,185 @@

#include "rendersystem/sheet.h"
native struct TextureCreationConfig_t is NativeEngine.TextureCreationConfig_t;
native struct CTextureDesc is NativeEngine.CTextureDesc;
native enum RenderDeviceAPI_t is NativeEngine.RenderDeviceAPI_t;
native pointer SwapChainHandle_t;
native pointer RenderBufferHandle_t is NativeEngine.RenderBufferHandle_t;
native pointer RenderInputLayout_t is NativeEngine.RenderInputLayout_t;
native struct BufferDesc_t is NativeEngine.BufferDesc;
native enum RenderBufferType_t is NativeEngine.RenderBufferType;
native enum RenderBufferFlags_t is NativeEngine.RenderBufferFlags;
native enum DeviceSpecificInfo_t is NativeEngine.DeviceSpecificInfo_t;
native struct VulkanDeviceSpecificTexture_t is NativeEngine.VulkanDeviceSpecificTexture_t;
native struct RenderDeviceInfo_t;
native pointer SamplerStateHandle_t;
native struct CSamplerStateDesc is NativeEngine.CSamplerStateDesc;
native accessor g_pRenderDevice
{
SamplerStateHandle_t FindOrCreateSamplerState(CSamplerStateDesc samplerDesc );
int GetSamplerIndex( SamplerStateHandle_t samplerState );
RenderDeviceInfo_t GetSwapChainInfo( SwapChainHandle_t swapChain );
ITexture FindOrCreateFileTexture( string pFileName, RenderSystemAssetFileLoadMode nLoadMode );
ITexture FindOrCreateTexture2( string pResourceName, bool bIsAnonymous, TextureCreationConfig_t pDescriptor, void* data, int dataSize );
void ClearTexture( ITexture hTexture, Color color );
void AsyncSetTextureData2( ITexture hTexture, void* pData, int nDataSize, Rect3D rect );
ITexture GetSwapChainTexture( SwapChainHandle_t swapChain, SwapChainBuffer bufferType );
bool GetGPUFrameTimeMS( SwapChainHandle_t swapChain, out float pGPUFrameTimeMSOut, out uint pFrameNumberOut );
asref cast CTextureDesc GetTextureDesc( ITexture hTexture );
asref cast CTextureDesc GetOnDiskTextureDesc( ITexture hTexture );
RenderMultisampleType GetTextureMultisampleType( ITexture hTexture );
IRenderContext CreateRenderContext( uint flags );
void ReleaseRenderContext( IRenderContext context );
bool ReadTexturePixels( ITexture hTexture, ref Rect_t pSrcRect, int nSrcSlice, int nSrcMip, ref Rect_t pDstRect, void* pData, ImageFormat dstFormat, int nDstStride );
void DestroySwapChain( SwapChainHandle_t hSwapChain );
bool Present( SwapChainHandle_t chain );
void Flush();
bool CanRenderToSwapChain( SwapChainHandle_t chain );
bool IsUsing32BitDepthBuffer();
inline Vector2 GetBackbufferDimensions( SwapChainHandle_t chain )
{
int nBBWidth, nBBHeight;
g_pRenderDevice->GetBackBufferDimensions( chain, &nBBWidth, &nBBHeight );
return Vector2D( (float)nBBWidth, (float)nBBHeight );
}
RenderShaderHandle_t CompileAndCreateShader( RenderShaderType nType, string pProgram, uint nBufLen, string pShaderVersion, string pDebugName );
int GetTextureLastUsed( ITexture hTexture );
void UnThrottleTextureStreamingForNFrames( uint nNumberOfFramesForUnthrottledTextureLoading );
int GetNumTextureLoadsInFlight();
void SetForcePreloadStreamingData( bool bForcePreloadStreamingData );
RenderDeviceAPI_t GetRenderDeviceAPI();
void MarkTextureUsed( ITexture texture, int nRequiredMipSize );
bool IsTextureRenderTarget( ITexture texture );
inline RenderBufferHandle_t CreateGPUBuffer( RenderBufferType_t nType, BufferDesc_t desc, RenderBufferFlags_t usage, string pDebugName )
{
desc.m_pDebugName = pDebugName;
return g_pRenderDevice->CreateGPUBuffer( nType, desc, usage );
}
void DestroyGPUBuffer( RenderBufferHandle_t hGPUBuffer );
bool ReadBuffer( RenderBufferHandle_t hBuffer, uint nOffsetInBytes, void* pBuf, uint nBytesToRead );
IntPtr GetDeviceSpecificInfo( DeviceSpecificInfo_t info );
IntPtr GetGraphicsAPISpecificTextureHandle( ITexture hTexture );
IntPtr GetDeviceSpecificTexture( ITexture hTexture );
int GetTextureViewIndex( ITexture hTexture, CastTo[RenderColorSpace_t] byte colorSpace, RenderTextureDimension_t dim );
inline void GetTextureResidencyInfo( CUtlVectorTexture pTextures, CUtlVectorString pNames )
{
TextureResidencyStats_t textureResidencyStats;
CUtlVector<TextureResidencyInfo_t> rawTextures;
g_pRenderDevice->GetTextureResidencyInfo( rawTextures, textureResidencyStats );
pTextures->EnsureCapacity( rawTextures.Count() );
pNames->EnsureCapacity( rawTextures.Count() );
for ( const TextureResidencyInfo_t &info : rawTextures )
{
if ( info.m_hTexture.IsLoaded() == false ) continue;
CPathBufferString texName;
info.m_hTexture.GetResourceName( &texName );
pTextures->AddToTail( info.m_hTexture );
pNames->AddToTail( texName );
}
}
inline Vector4 GetSheetInfo( ITexture texture )
{
Vector4D vec(0, 0, 0, 0 );
Vector2D vSheetSequenceDataUVCoords;
HRenderTexture hSequenceDataTexture;
int nSequenceCount;
if ( g_pRenderDevice->GetSheetSequenceTextureData( texture, &hSequenceDataTexture, &vSheetSequenceDataUVCoords, &nSequenceCount ) )
{
vec[0] = vSheetSequenceDataUVCoords.y;
const CTextureDesc *pTexHeader = g_pRenderDevice->GetTextureDesc( hSequenceDataTexture );
if ( pTexHeader )
{
vec[1] = pTexHeader->m_nWidth;
vec[2] = 1.0f / pTexHeader->m_nHeight;
vec[3] = (float)nSequenceCount;
}
}
return vec;
}
inline int GetSequenceCount( ITexture texture )
{
const Sheet_t *pSheet = g_pRenderDevice->GetTextureSheet( texture );
if ( pSheet == nullptr ) return 0;
return pSheet->m_Sequences.Count();
}
inline SheetSequence_t GetSequence( ITexture texture, int index )
{
const Sheet_t *pSheet = g_pRenderDevice->GetTextureSheet( texture );
if ( pSheet == nullptr ) return 0;
return &pSheet->m_Sequences[index];
}
}
native static class ImageLoader as NativeEngine.ImageLoader
{
int GetMemRequired( int width, int height, int depth, ImageFormat imageFormat, bool mipmap );
int GetMemRequired( int width, int height, int depth, int mipmaps, ImageFormat imageFormat );
bool ConvertImageFormat( CastTo[uint8*] void* src, ImageFormat srcImageFormat, CastTo[uint8*] void* dst, ImageFormat dstImageFormat, int width, int height, int srcStride, int dstStride );
}
native class SheetSequence_t
{
uint m_nId;
bool m_bClamp;
bool m_bAlphaCrop;
bool m_bNoColor;
bool m_bNoAlpha;
float m_flTotalTime;
inline int FrameCount()
{
return self->m_Frames.Count();
}
}
native class SheetSequenceFrame_t
{
float m_flDisplayTime;
inline int ImageCount()
{
return self->m_Images.Count();
}
inline SheetFrameImage_t GetImage( int i )
{
return self->m_Images[i];
}
}
native struct SheetFrameImage_t;

View File

@@ -0,0 +1,27 @@
#include "scenesystem/decal.h"
[Handle:Sandbox.DecalSceneObject]
native class CDecalSceneObject as NativeEngine.CDecalSceneObject : CSceneObject
{
ITexture m_hColor;
ITexture m_hNormal;
ITexture m_hRMO;
uint m_nSortOrder;
uint m_nExclusionBitMask;
Vector4 m_vColorTint;
float m_flAttenuationAngle;
float m_flColorMix;
// Extra data
ITexture m_hEmission;
float m_flEmissionEnergy;
uint m_nSequenceIndex;
ITexture m_hHeight;
float m_flParallaxStrength;
int m_nSamplerIndex;
}

View File

@@ -0,0 +1,21 @@
#include "scenesystem/envmapsceneobject.h"
native enum CubemapProjectionMode_t as Sandbox.SceneCubemap.ProjectionMode;
[Handle:Sandbox.SceneCubemap]
native class CEnvMapSceneObject as NativeEngine.CEnvMapSceneObject : CSceneLightObject
{
CubemapProjectionMode_t m_nProjectionMode;
Vector3 m_vBoxProjectMins;
Vector3 m_vBoxProjectMaxs;
Vector3 m_vColor;
int m_nRenderPriority;
ITexture m_hEnvMapTexture;
Vector4D m_vNormalizationSH;
float m_flFeathering;
void CalculateRadianceSH();
void CalculateRadianceSH( ITexture hTexture );
void CalculateNormalizationSH();
void CalculateBounds();
}

View File

@@ -0,0 +1,121 @@
#include "scenesystem/sceneanimatableobject.h"
delegate SboxAnimationEventCallback;
delegate SboxAnimTagEventCallback;
delegate SboxAnimGraphChangedCallback;
[Handle:Sandbox.SceneModel]
native class CSceneAnimatableObject as NativeEngine.CSceneAnimatableObject : CSceneObject
{
void SetWorldSpaceRenderBoneTransform( int nBoneIndex, Transform pRenderWorldTransform );
Transform GetWorldSpaceRenderBoneTransform( int nBoneIndex );
Transform GetWorldSpaceRenderBoneTransform( string boneName );
Transform GetWorldSpaceRenderBonePreviousTransform( int nBoneIndex );
Transform GetWorldSpaceRenderBonePreviousTransform( string boneName );
Transform GetLocalSpaceRenderBoneTransform( int nBoneIndex );
Transform GetLocalSpaceRenderBoneTransform( string boneName );
Transform GetWorldSpaceAnimationTransform( int nBoneIndex );
void Update( float dt );
void MergeFrom( CSceneAnimatableObject other );
void SetBindPose();
void CalculateWorldSpaceBones();
void FinishUpdate();
void ResetGraphParameters();
Transform GetParentSpaceBone( int index );
void SetParentSpaceBone( int index, Transform tx );
void InitAnimGraph( SboxAnimGraphChangedCallback pAnimGraphChangedCallback );
void SetAnimGraph( string graphName );
void SetAnimGraph( HAnimationGraph hGraph );
HAnimationGraph GetAnimGraph();
void SBox_SetFlexOverride( StringToken name, float flWeight );
void SBox_SetFlexOverride( int flexId, float flWeight );
float SBox_GetFlexOverride( int flexId );
float SBox_GetFlexOverride( StringToken name );
void SBox_ClearFlexOverride();
void DirectPlayback_PlaySequence( string pSequenceName );
void DirectPlayback_PlaySequence( string pSequenceName, Vector3 vTargetPos, float flFacingHeading, float flInterpTime );
void DirectPlayback_CancelSequence();
float DirectPlayback_GetSequenceCycle();
string DirectPlayback_GetSequence();
void DirectPlayback_SetSequenceStartTime( float flStartTime );
float DirectPlayback_GetSequenceDuration();
bool SBox_GetAttachment( StringToken name, bool worldspace, cref out Transform tx );
void SetShouldUseAnimGraph( bool bEnabled );
bool GetShouldUseAnimGraph();
string GetSequence();
void SetSequence( string pSequenceName );
float GetSequenceDuration();
float GetSequenceCycle();
void SetSequenceCycle( float flCycle );
void SetSequenceLooping( bool bLooping );
bool IsSequenceFinished();
void SetSequenceBlending( bool bBlending );
float GetPlaybackRate();
void SetPlaybackRate( float flPlaybackRate );
int GetParameterInt( string name );
Float GetParameterFloat( string name );
Vector3 GetParameterVector3( string name );
Rotation GetParameterRotation( string name );
//
// Anim Events
//
int PendingAnimationEvents();
void RunAnimationEvents( SboxAnimationEventCallback callback );
void DispatchTagEvents( SboxAnimTagEventCallback callback );
//
// Bone Overrides
//
void ClearPhysicsBones();
void SetPhysicsBone( ushort bone, Transform transform );
Transform GetRootMotion();
float m_flDeltaTime;
inline bool HasPhysicsBones()
{
return self->m_PhysicsBoneTransform.Count() > 0;
}
IAnimParameterInstance GetAnimParameter( string name );
IAnimParameterInstance GetAnimParameter( int index );
BBox m_worldBounds;
BBox m_localBounds;
}
native class IAnimParameterInstance as NativeEngine.IAnimParameterInstance
{
void SetValue( bool val );
void SetValue( int val );
void SetValue( float val );
void SetValue( Vector3 val );
void SetValue( Rotation val );
inline void SetEnumValue( int val )
{
self->SetValue( CAnimEnum( (AnimEnumValue_t)val ) );
}
CUtlString GetName();
bool IsAutoReset();
NativeEngine.AnimParamType GetParameterType();
}

View File

@@ -0,0 +1,80 @@
native enum LightSourceShape_t is NativeEngine.LightSourceShape_t;
[Handle:Sandbox.SceneLight]
native class CSceneLightObject as NativeEngine.CSceneLightObject : CSceneObject
{
void SetWorldPosition( Vector3 pos );
Vector3 GetWorldPosition();
void SetWorldDirection( Rotation dir );
Vector3 GetWorldDirection();
void SetColor( Vector3 color );
void SetBounceColor( Vector3 color );
Vector3 GetColor();
void SetRadius( float radius );
float GetRadius();
void SetTheta( float f );
float GetTheta();
void SetPhi( float f );
float GetPhi();
void SetFallOff( float f );
float GetFallOff();
int GetShadowTextureResolution();
void SetShadowTextureResolution( int v );
bool GetShadows();
void SetShadows( bool v );
void SetConstantAttn(float f);
float GetConstantAttn();
void SetLinearAttn( float f );
float GetLinearAttn();
void SetQuadraticAttn( float f );
float GetQuadraticAttn();
void SetLightCookie( ITexture f );
ITexture GetLightCookie();
int GetShadowCascades();
void SetShadowCascades( int v );
float GetCascadeDistanceScale();
void SetCascadeDistanceScale( float dist );
float GetFogContributionStength();
void SetFogContributionStength( float v );
int GetFogLightingMode();
void SetFogLightingMode( int v );
void SetBakeLightIndex( int v );
void SetBakeLightIndexScale( float v );
void SetUsesIndexedBakedLighting( bool v );
void SetRenderDiffuse( bool v );
void SetRenderSpecular( bool v );
void SetRenderTransmissive( bool v );
void SetLightSourceSize0( float v );
void SetLightSourceSize1( float v );
void SetShadowTextureWidth( int v );
void SetShadowTextureHeight( int v );
int GetShadowTextureWidth();
int GetShadowTextureHeight();
uint GetLightFlags();
void SetLightFlags( uint flags );
LightSourceShape_t GetLightShape();
void SetLightShape( LightSourceShape_t shape );
void SetLightSourceDim0( float v );
void SetLightSourceDim1( float v );
}

View File

@@ -0,0 +1,17 @@
#include "scenesystem/scenelightprobevolumeobject.h"
[Handle:Sandbox.SceneLightProbe]
native class CSceneLightProbeVolumeObject as NativeEngine.CSceneLightProbeVolumeObject : CSceneObject
{
Vector3 m_vBoxMins;
Vector3 m_vBoxMaxs;
int m_nHandshake;
int m_nRenderPriority;
ITexture m_hLightProbeTexture;
ITexture m_hLightProbeDirectLightIndicesTexture;
ITexture m_hLightProbeDirectLightScalarsTexture;
void CreateConstants();
}

View File

@@ -0,0 +1,109 @@
#include "scenesystem/iscenesystem.h"
#include "scenesystem/sceneobject.h"
native enum ESceneObjectFlags is Sandbox.Rendering.SceneObjectFlags;
native enum ESceneObjectTypeFlags is NativeEngine.ESceneObjectTypeFlags;
[Handle:Sandbox.SceneObject]
native class CSceneObject as NativeEngine.CSceneObject
{
void ChangeFlags(ESceneObjectFlags nNewFlags, ESceneObjectFlags nNewFlagsMask);
void SetFlags(ESceneObjectFlags nFlagsToOR);
bool HasFlags(ESceneObjectFlags nFlags);
ESceneObjectFlags GetFlags();
ESceneObjectFlags GetOriginalFlags();
void ClearFlags(ESceneObjectFlags nFlagsToClear);
void SetCullDistance( float dist );
void EnableLightingCache();
void SetLightingOrigin( Vector3 vPos, bool worldspace );
Vector3 GetLightingOrigin();
bool HasLightingOrigin();
void SetTintRGBA( Vector4 color );
Vector4 GetTintRGBA();
void SetAlphaFade( float nAlpha );
float GetAlphaFade();
void SetMaterialOverrideForMeshInstances( IMaterial mat );
void ClearMaterialOverrideList();
void SetMaterialOverride( IMaterial hMaterial, StringToken nAttr, int nAttrValueMatch );
bool IsLoaded();
bool IsRenderingEnabled();
void SetLoaded();
void ClearLoaded();
void DisableRendering();
void EnableRendering();
void SetRenderingEnabled( bool bEnabled );
float GetBoundingSphereRadius();
void SetTransform( Transform tx );
Transform GetCTransform();
void SetBounds( BBox box );
BBox GetBounds();
void SetBoundsInfinite();
CSceneObject GetParent();
void AddChildObject( StringToken nId, CSceneObject pChild, uint nChildUpdateFlags );
void RemoveChild( CSceneObject obj );
CRenderAttributes GetAttributesPtrForModify();
void EnableMeshGroups( ulong nMask );
void DisableMeshGroups( ulong nMask );
void ResetMeshGroups( ulong nMask );
ulong GetCurrentMeshGroupMask();
ISceneWorld GetWorld();
void SetLOD( int nLOD );
void DisableLOD();
ulong GetCurrentLODGroupMask();
int GetCurrentLODLevel();
IModel GetModelHandle();
void SetMaterialGroup( StringToken token );
void SetBodyGroup( StringToken token, int value );
void SetBatchable( bool bIsBatchable );
bool IsNotBatchable();
void SetUniqueBatchGroup( bool bUnique );
void RemoveTag( uint tag );
void RemoveAllTags();
int GetTagCount();
uint GetTagAt( int i);
void AddTag( uint tag );
bool HasTag( uint tag );
// draw on this layer regardless of flags
void SetForceLayerID( StringToken nTok );
// draw only on this layer
void SetLayerMatchID( StringToken nTok );
inline void UpdateFlagsBasedOnMaterial()
{
g_pMeshSystem->UpdateTranslucencyFlagsOnMaterialChange( self );
self->UpdateFlagsBasedOnMaterial();
}
void SetMaterialOverrideByIndex( int index, IMaterial material );
}

View File

@@ -0,0 +1,24 @@
#include "scenesystem/skybox.h"
[Handle:Sandbox.SceneSkyBox]
native class CSceneSkyBoxObject as NativeEngine.CSceneSkyBoxObject : CSceneObject
{
void SetLighting_ConstantColorHemisphere( Vector3 vSkyColor );
void SetLighting_Samples( CastTo[Vector*] void* pSkyColors, CastTo[Vector*] void* pSkyDirections, int nSkyColors );
IMaterial GetMaterial();
void SetMaterial( IMaterial hMaterial );
void SetSkyTint( Vector3 vTint );
Vector3 GetSkyTint();
void SetFogType( CastTo[ESkyboxFogType_t] int nType );
int GetFogType();
void SetAngularFogParams( float flFogMinStart, float flFogMinEnd, float flFogMaxStart, float flFogMaxEnd );
float GetFogMinStart();
float GetFogMinEnd();
float GetFogMaxStart();
float GetFogMaxEnd();
}

View File

@@ -0,0 +1,55 @@
#include "scenesystem/iscenelayer.h"
native enum ELayerFlags as Sandbox.Rendering.LayerFlags
native enum ELayerEnum as Sandbox.SceneLayerType
native pointer HSceneViewRenderTarget as Sandbox.Rendering.SceneViewRenderTargetHandle
native enum SceneLayerMSAAMode_t is NativeEngine.SceneLayerMSAAMode_t
native class ISceneLayer as NativeEngine.ISceneLayer
{
void SetObjectMatchID( StringToken nTok );
void AddObjectFlagsRequiredMask( ESceneObjectFlags nRequiredFlags );
void AddObjectFlagsExcludedMask( ESceneObjectFlags nExcludedFlags );
void RemoveObjectFlagsRequiredMask( ESceneObjectFlags nRequiredFlags );
void RemoveObjectFlagsExcludedMask( ESceneObjectFlags nExcludedFlags );
ESceneObjectFlags GetObjectFlagsRequiredMask() const;
ESceneObjectFlags GetObjectFlagsExcludedMask() const;
string GetDebugName();
ELayerFlags m_nLayerFlags;
SceneLayerType LayerEnum;
RenderViewport m_viewport;
int m_nClearFlags;
inline CRenderAttributes GetRenderAttributesPtr()
{
return &self->m_Attrs;
}
void SetAttr( StringToken nTokenID, HSceneViewRenderTarget hRenderTarget, SceneLayerMSAAMode_t msaa, uint flags );
void SetBoundingVolumeSizeCullThresholdInPercent( float flSizeCullThreshold );
void SetClearColor( Vector4 vecColor, int nRenderTargetIndex );
ITexture GetTextureValue( StringToken nTokenID, ITexture nDefaultValue );
ITexture GetTextureValue( StringToken nTokenID );
inline ITexture GetColorTarget()
{
return this->GetRenderTargetDesc().m_pColorTargets[0];
}
inline ITexture GetDepthTarget()
{
return this->GetRenderTargetDesc().m_hDepthTarget;
}
inline void SetOutput( HSceneViewRenderTarget hColor, HSceneViewRenderTarget hDepth )
{
this->m_RenderTargetOutputs.Init( hColor, hDepth );
}
}

View File

@@ -0,0 +1,47 @@
native struct RenderViewport_t is NativeEngine.RenderViewport
delegate SboxProceduralLayerCallback;
native class ISceneView as NativeEngine.ISceneView
{
RenderViewport GetMainViewport();
void* GetSwapChain();
void AddDependentView( ISceneView pView, int nSlot );
CRenderAttributes GetRenderAttributesPtr();
ISceneLayer AddRenderLayer( string pszDebugName, RenderViewport viewport, StringToken eShaderMode, ISceneLayer pAddBefore );
ISceneLayer AddManagedProceduralLayer( string pszDebugName, RenderViewport viewport, SboxProceduralLayerCallback renderCallback, ISceneLayer pAddBefore, bool bDeleteWhenDone );
void SetDefaultLayerObjectRequiredFlags( ESceneObjectFlags nFlags );
void SetDefaultLayerObjectExcludedFlags( ESceneObjectFlags nFlags );
ESceneObjectFlags GetDefaultLayerObjectRequiredFlags();
ESceneObjectFlags GetDefaultLayerObjectExcludedFlags();
void AddWorldToRenderList( ISceneWorld pWorld );
HSceneViewRenderTarget FindOrCreateRenderTarget( string pName, ITexture hTexture, int nFlags );
void SetParent( ISceneView pParent );
ISceneView GetParent();
int GetPriority();
void SetPriority( int nPriority );
inline CFrustum GetFrustum()
{
return &this->GetFrustum();
}
int m_ViewUniqueId;
int m_ManagedCameraId;
bool GetPostProcessEnabled();
inline int GetToolsVisMode()
{
auto attrs = this->GetRenderAttributesPtr();
if ( !attrs )
return 0;
return attrs->GetIntValue( StringTokenFromHashCode( 3329653539u ), 0 );
}
}

View File

@@ -0,0 +1,29 @@
#include "scenesystem/iscenesystem.h"
[Handle:Sandbox.SceneWorld]
native class ISceneWorld as NativeEngine.ISceneWorld
{
void DeleteAllObjects();
void Release();
int GetSceneObjectCount();
bool IsEmpty();
string GetWorldDebugName();
void SetDeleteAtEndOfFrame( bool bDelete );
bool GetDeleteAtEndOfFrame();
void DeleteEndOfFrameObjects();
inline bool MeshTrace( MeshTraceInput input, ref MeshTraceOutput output )
{
return self->MeshTrace( input, *output );
}
IPVS GetPVS();
void SetPVS( IPVS pPVS );
void Add3DSkyboxWorld( ISceneWorld world );
void Remove3DSkyboxWorld( ISceneWorld world );
void Set3DSkyboxParameters( Vector3 origin, Angles angle, float scale );
}

View File

@@ -0,0 +1,15 @@

#include "scenesystem/itonemapsystem.h"
native struct SceneTonemapParameters_t;
native class ITonemapSystem
{
void SetTonemapParameters( ref SceneTonemapParameters_t pParams );
inline void ResetTonemapParameters()
{
this->SetTonemapParameters( NULL );
}
}

View File

@@ -0,0 +1,11 @@

#include "scenesystem/ivolumetricfog.h"
native struct SceneVolumetricFogParameters2_t is NativeEngine.SceneVolumetricFogParameters;
native class IVolumetricFog
{
void IsFoggingEnabled();
void SetParams( SceneVolumetricFogParameters parameters, ITexture bakedTexture );
}

View File

@@ -0,0 +1,163 @@
#include "scenesystem/iscenesystem.h"
native enum SceneSystemRenderTargetSize_t as NativeEngine.SceneSystemRenderTargetSize;
native enum SceneSystemWellKnownMaterialObjectID_t as NativeEngine.SceneSystemWellKnownMaterialObjectID;
native enum SceneSystemWellKnownTextureObjectID_t as NativeEngine.SceneSystemWellKnownTextureObjectID;
native struct SceneVolumetricFogVolume_t is NativeEngine.SceneVolumetricFogVolume;
native class SceneSystemPerFrameStats_t
{
uint m_nTrianglesRendered;
uint m_nArtistTrianglesRendered;
uint m_nRenderBatchDraws;
uint m_nDrawCalls;
uint m_nDrawPrimitives;
uint m_nBaseSceneObjectPrimDraws;
uint m_nAnimatableObjectPrimDraws;
uint m_nAggregateSceneObjectPrimDraws;
uint m_nAggregateSceneObjectsFullyCulled;
uint m_nAggregateSceneObjectDrawCalls;
uint m_nNumMaterialCompute;
uint m_nNumMaterialSet;
uint m_nNumSimilarMaterialSet;
uint m_nNumTextureOnlyMaterialSet;
uint m_nNumVfxEval;
uint m_nNumVfxRule;
uint m_nNumConstantBufferUpdates;
uint m_nNumConstantBufferBytes;
uint m_nMaterialChangesNonShadow;
uint m_nMaterialChangesNonShadowInitial;
uint m_nMaterialChangesShadow;
uint m_nMaterialChangesShadowInitial;
uint m_nMaterialChangesShadowAlphaTested;
uint m_nCopyMaterialChangesNonShadow;
uint m_nMaxTransformRow;
uint m_nNumRowsUsed;
uint m_nNumObjectsTested;
uint m_nNumObjectsPreCullCheck;
uint m_nNumObjectsPassingCullCheck;
uint m_nNumVerticesReferenced;
uint m_nNumPrimaryContexts;
uint m_nNumSecondaryContexts;
uint m_nNumDisplayListsSubmitted;
int m_nNumViewsRendered;
uint m_nNumResolves;
uint m_nNumCullBoxes;
ulong m_nCullingBoxCycleCount;
uint m_nNumObjectsTestedAgainstCullingBoxes;
uint m_nNumObjectsRejectedByBoundsIndex;
uint m_nNumObjectsRejectedByCullBoxes;
uint m_nNumObjectsRejectedByVis;
uint m_nNumObjectsRejectedByBackfaceCulling;
uint m_nNumObjectsRejectedByScreenSizeCulling;
uint m_nNumObjectsRejectedByFading;
uint m_nNumFadingObjects;
uint m_nNumUniqueMaterialsSeen;
uint m_nNumUnshadowedLightsInView;
uint m_nNumShadowedLightsInView;
uint m_nNumShadowMaps;
uint m_nNumRenderTargetBinds;
uint m_nPushConstantSets;
}
native accessor g_pSceneSystem as NativeEngine.CSceneSystem
{
void DeleteSceneObject( CSceneObject pObj );
void DeleteSceneObjectAtFrameEnd( CSceneObject pObj );
CSceneSkyBoxObject CreateSkyBox( IMaterial skyMaterial, ISceneWorld world );
CDecalSceneObject CreateDecal( ISceneWorld world );
void BeginRenderingDynamicView( ISceneView pView );
//ISceneView AddDynamicView( string pszDebugName, ISceneView pParentView, CFrustum frustum, void* hSwapChain, ISceneWorld pWorld, RenderViewport mainViewport, void* pVis, int nPriority, int nViewProducerIndex );
ITexture GetWellKnownTexture( SceneSystemWellKnownTextureObjectID a );
IMaterial GetWellKnownMaterialHandle( SceneSystemWellKnownMaterialObjectID a );
inline SceneSystemPerFrameStats_t GetPerFrameStats()
{
return &(g_pSceneSystem->GetPerFrameStats());
}
ISceneWorld CreateWorld( string debugName );
void DestroyWorld( ISceneWorld world );
inline void SetupPerObjectLighting( CRenderAttributes renderAttributes, CSceneObject pSceneObject, ISceneLayer pSceneLayerInterface )
{
g_pSceneSystem->SetupPerObjectLighting( *renderAttributes, pSceneObject, pSceneLayerInterface );
}
inline CSceneLightObject CreatePointLight( ISceneWorld pWorld )
{
LightDesc_t desc;
desc.Clear();
desc.InitPoint( vec3_origin, Vector( 100, 0, 100 ) );
desc.m_Attenuation0 = 0; // if this is 1 then the light has no falloff
return g_pSceneSystem->CreateLight( desc, pWorld, false );
}
inline CSceneLightObject CreateSpotLight( ISceneWorld pWorld )
{
LightDesc_t desc;
desc.Clear();
desc.InitSpot( vec3_origin, Vector( 100, 0, 100 ), Vector( 10, 0, 0 ), 15, 30 );
desc.m_Attenuation0 = 0; // if this is 1 then the light has no falloff
return g_pSceneSystem->CreateLight( desc, pWorld, false );
}
inline CSceneLightObject CreateOrthoLight( ISceneWorld pWorld )
{
LightDesc_t desc;
desc.Clear();
desc.m_Type = MATERIAL_LIGHT_ORTHO;
desc.RecalculateDerivedValues();
return g_pSceneSystem->CreateLight( desc, pWorld, false );
}
inline CSceneLightObject CreateDirectionalLight( ISceneWorld pWorld, Vector3 direction )
{
LightDesc_t desc;
desc.Clear();
desc.InitDirectional( direction, Vector( 100, 0, 100 ) );
desc.m_nShadowCascadeCount = 3;
return g_pSceneSystem->CreateLight( desc, pWorld, false );
}
inline CSceneLightObject CreateEnvMap( ISceneWorld pWorld, int nProjectionMode )
{
LightDesc_t desc;
desc.InitEnvironmentProbe( vec3_origin, 512 );
desc.m_nEnvProbeId = 0;
desc.RecalculateDerivedValues();
CEnvMapSceneObject* pSceneObject = ( CEnvMapSceneObject* )g_pSceneSystem->CreateLight( desc, pWorld, false );
pSceneObject->m_nProjectionMode = ( CubemapProjectionMode_t )nProjectionMode;
return pSceneObject;
}
CSceneLightProbeVolumeObject CreateLightProbeVolume( ISceneWorld pWorld );
void MarkEnvironmentMapObjectUpdated( CEnvMapSceneObject pEnvMap );
void MarkLightProbeVolumeObjectUpdated( CSceneLightProbeVolumeObject pLightProbe );
inline uint AddCullingBox( ISceneWorld pWorld, bool nCullMode, Vector3 vOrigin, Angles vAngles, Vector3 vExtents )
{
return g_pSceneSystem->AddCullingBox( pWorld, nCullMode ? SCENESYSTEM_BOX_CULL_INSIDE : SCENESYSTEM_BOX_CULL_OUTSIDE, vOrigin, vAngles, vExtents );
}
void RemoveCullingBox( ISceneWorld pWorld, uint nBoxId );
uint AddVolumetricFogVolume( ISceneWorld pWorld, SceneVolumetricFogVolume_t volume );
void RemoveVolumetricFogVolume( ISceneWorld pWorld, uint nId );
inline void DownsampleTexture( IRenderContext ctx, ITexture src, byte nDownsampleType )
{
return g_pSceneSystem->DownsampleTexture( ctx, src, nullptr, nDownsampleType );
}
void RenderTiledLightCulling( IRenderContext pCtx, ISceneView pView, RenderViewport viewport );
void BindTransformSlot( IRenderContext pCtx, int nVBSlot, int nTransformSlotIndex );
}

View File

@@ -0,0 +1,12 @@

#include "scenesystem/isceneutils.h"
native accessor g_pSceneUtils
{
ITonemapSystem CreateTonemapSystem();
void DestroyTonemapSystem( ITonemapSystem pTonemapSystem );
IVolumetricFog CreateVolumetricFog();
void DestroyVolumetricFog( IVolumetricFog pVolumetricFog );
}

View File

@@ -0,0 +1,11 @@
native enum TextureDecodingFlags_t is NativeEngine.TextureDecodingFlags;
native enum ImageFormat is Sandbox.ImageFormat;
native enum RuntimeTextureSpecificationFlags_t is NativeEngine.RuntimeTextureSpecificationFlags;
native enum RenderMultisampleType_t is NativeEngine.RenderMultisampleType;
native enum TextureUsage_t is NativeEngine.TextureUsage;
native enum TextureScope_t is NativeEngine.TextureScope;
native enum TextureOnDiskCompressionType_t is NativeEngine.TextureOnDiskCompressionType;
native enum RenderSystemAssetFileLoadMode_t is NativeEngine.RenderSystemAssetFileLoadMode;
native enum ColorFormat_t is NativeEngine.ColorFormat;
native enum SwapChainBuffer_t is NativeEngine.SwapChainBuffer;

View File

@@ -0,0 +1,23 @@
#include "engine2/iinputservice.h"
native enum ButtonCode_t is NativeEngine.ButtonCode;
native enum GameControllerCode_t is NativeEngine.GameControllerCode;
native enum GameControllerAxis_t is NativeEngine.GameControllerAxis;
native enum GameControllerType_t is NativeEngine.GameControllerType;
native accessor g_pInputService
{
bool IsAppActive();
// Some key trapping stuff here that could be useful
bool HasMouseFocus();
string Key_NameForBinding( string binding );
string GetBinding( ButtonCode button );
void SetCursorPosition( int x, int y );
void Pump();
}

View File

@@ -0,0 +1,52 @@
native enum KeyValues3Type_t;
native class KeyValues3
{
void DeleteThis(); [delete]
static KeyValues3 Create(); [new]
bool IsArray();
bool IsTable();
KeyValues3Type_t GetType();
bool GetValueBool();
int GetValueInt();
long GetValueInt64();
ulong GetValueUint64();
float GetValueFloat();
double GetValueDouble();
string GetValueString();
Vector3 GetValueVector();
Color GetValueColor();
void SetValueBool( bool o );
void SetValueString( string o );
void SetValueResourceString( string o );
void SetValueInt( int o );
void SetValueFloat( float o );
void SetMemberString( CastTo[CKV3MemberName] string key, string value );
void SetMemberInt( CastTo[CKV3MemberName] string key, int value );
void SetMemberFloat( CastTo[CKV3MemberName] string key, float value );
string GetMemberString( CastTo[CKV3MemberName] string key );
int GetMemberInt( CastTo[CKV3MemberName] string key, int defaultValue );
float GetMemberFloat( CastTo[CKV3MemberName] string key, float defaultValue );
Vector3 GetMemberVector( CastTo[CKV3MemberName] string key, Vector3 defaultValue );
void SetToEmptyArray();
int GetArrayLength();
KeyValues3 ArrayAddToTail();
KeyValues3 GetArrayElement( int i );
KeyValues3 FindOrCreateMember( CastTo[CKV3MemberName] string name );
void SetToEmptyTable();
int GetMemberCount();
KeyValues3 GetMember( int idx );
string GetMemberName( int idx );
}

View File

@@ -0,0 +1,8 @@
include "meshsystem/imeshsystem.h"
native accessor g_pMeshSystem as NativeEngine.MeshSystem
{
CSceneObject CreateSceneObject( IModel model, Transform modelToWorld, string pDescName, ESceneObjectFlags nFlags, ESceneObjectTypeFlags nObjectTypeFlags, ISceneWorld pWorld, int creationFlags );
void ChangeModel( CSceneObject obj, IModel model );
}

View File

@@ -0,0 +1,8 @@
include "dbg.h"
include "convar.h"
managed static class Sandbox.RealTime
{
void Update( float time );
}

View File

@@ -0,0 +1,11 @@
native class CUtlBuffer
{
static CUtlBuffer Create();[new]
void Dispose(); [delete]
void* Base();
int TellMaxPut();
}

View File

@@ -0,0 +1,7 @@
native class CUtlSymbolTable
{
void AddString( string pString );
}

View File

@@ -0,0 +1,43 @@
include "dbg.h"
include "convar.h"
native class CUtlVector<CUtlString> as NativeEngine.CUtlVectorString
{
void DeleteThis(); [delete]
static CUtlVectorString Create( int growsize, int initialcapacity ); [new]
int Count();
void SetCount( int count );
CUtlString Element( int i );
}
native class CUtlVector<Vector> as NativeEngine.CUtlVectorVector
{
void DeleteThis(); [delete]
static CUtlVectorVector Create( int growsize, int initialcapacity ); [new]
int Count();
void SetCount( int count );
Vector Element( int i );
}
native class CUtlVector<float> as NativeEngine.CUtlVectorFloat
{
void DeleteThis(); [delete]
static CUtlVectorFloat Create( int growsize, int initialcapacity ); [new]
int Count();
void SetCount( int count );
float Element( int i );
}
native class CUtlVector<uint32> as NativeEngine.CUtlVectorUInt32
{
void DeleteThis(); [delete]
static CUtlVectorUInt32 Create( int growsize, int initialcapacity ); [new]
int Count();
void SetCount( int count );
uint Element( int i );
}

View File

@@ -0,0 +1,35 @@
ident "engine"
nativedll engine2.dll
// A static function to report exceptions to in C#
exceptions "Sandbox.Interop.BindingException"
// Management classes will appear under this namespace
namespace "Managed.SandboxEngine"
// Paths are relative to the def file
cpp "../../src/engine2/interop.engine.cpp"
hpp "../../src/engine2/interop.engine.h"
cs "../Sandbox.Engine/Interop.Engine.cs"
include "dbg.h"
include "color.h"
include "engine/*"
include "tier3"
include "common/*"
include "resources"
managed static class Sandbox.Engine.Bootstrap
{
static void EnvironmentExit( int nCode );
}
managed static class Sandbox.Engine.SystemInfo
{
static void Set( string cpu, ushort processorCount, ulong frequency, ulong totalMemory );
static void SetGpu( string driver, string version, ulong memory );
}

View File

@@ -0,0 +1,25 @@

#include "sbox/dynamicsceneobject.h"
native class CDynamicSceneObject : CSceneObject
{
static CDynamicSceneObject Create( ISceneWorld world );
IMaterial Material;
[nogc]
void Begin( RenderPrimitiveType type, int vertexCount );
[nogc]
void End();
[nogc]
void AddVertex( SboxVertex_t vertex );
[nogc]
void AddVertexRange( void* vertex, int length );
[nogc]
void Reset();
}

View File

@@ -0,0 +1,16 @@

#include "sbox/managedsceneobject.h"
[Handle:Sandbox.SceneCustomObject]
native class CManagedSceneObject as NativeEngine.CManagedSceneObject : CSceneObject
{
static CManagedSceneObject Create( ISceneWorld world );
bool ExecuteOnMainThread;
}
managed static class Sandbox.SceneCustomObjectRender
{
void RenderObject( ManagedRenderSetup_t setup, CManagedSceneObject obj );
}

View File

@@ -0,0 +1,70 @@
#include "appframework/materialsystem2app.h"
native struct MaterialSystem2AppSystemDictCreateInfo as NativeEngine.MaterialSystem2AppSystemDictCreateInfo;
native class CMaterialSystem2AppSystemDict
{
static void CMaterialSystem2AppSystemDict Create( MaterialSystem2AppSystemDictCreateInfo createInfo ); [new]
void Destroy(); [delete]
bool Init();
bool InitWithoutMaterialSystem();
bool InitFinishSetupMaterialSystem();
void* GetAppWindow();
SwapChainHandle_t GetAppWindowSwapChain();
void SetAppWindowTitle( string title );
void SetAppWindowIcon( string title );
void SetInitialAppWindowImage( string vmat );
void SetAppWindowDiscardMouseFocusClick( bool discard );
void DrawInitialWindowImage();
void SuppressStartupManifestLoad( bool b );
void SetModuleSearchPath( string dir );
void SetModGameSubdir( string dir );
void SetModFromFileName( string filename, bool noExeCheck );
void DisableModPathCheck();
void SetDefaultRenderSystemOption( string system );
void SetInitializationPhase( int p );
int GetInitializationPhase();
void PreShutdown();
bool InitSDL( uint flags );
void ShutdownSDL();
bool IsConsoleApp();
bool IsGameApp();
void SetDedicatedServer( bool bIsDedicatedServer );
bool IsDedicatedServer( );
string GetContentPath();
string GetModGameSubdir();
void SetInToolsMode();
bool IsInToolsMode();
bool IsInDeveloperMode();
bool IsInVRMode();
void* CreateAppWindow( string pTitle, int nPlatWindowFlags, int x, int y, int w, int h, int nRefreshRateHz );
void SuppressCOMInitialization();
bool IsRunningOnCustomerMachine();
void* AddSystem( string dllName, string interfaceName );
void SetInTestMode();
bool IsInTestMode();
void SetInStandaloneApp();
bool IsStandaloneApp();
void SetSteamAppId( uint appId );
uint GetSteamAppId();
}

View File

@@ -0,0 +1,6 @@
managed static class Sandbox.HandleIndex
{
static int RegisterHandle( IntPtr ptr, uint type );
static void FreeHandle( int handle );
}

View File

@@ -0,0 +1,40 @@

#include "resourcesystem/iresourcecompiler.h"
native static accessor g_pResourceCompilerSystem as IResourceCompilerSystem
{
inline bool GenerateResourceFile( string path, void* pData, int size )
{
CUtlBuffer inputData( pData, size );
ResourceCompileSettings_t compileSettings;
compileSettings.m_pOverrideInputData = &inputData;
return g_pResourceCompilerSystem->GenerateResourceFile( path, compileSettings );
}
inline bool GenerateResourceFile( string path, string text )
{
CUtlBuffer inputData( 0, 0, CUtlBuffer::TEXT_BUFFER );
inputData.PutString( text );
ResourceCompileSettings_t compileSettings;
compileSettings.m_pOverrideInputData = &inputData;
return g_pResourceCompilerSystem->GenerateResourceFile( path, compileSettings );
}
inline CUtlBuffer GenerateResourceBytes( string path, void* pData, int size )
{
CUtlBuffer inputData;
inputData.Put( pData, size );
CUtlBuffer* outputData = new CUtlBuffer();
ResourceCompileSettings_t compileSettings;
compileSettings.m_pOverrideInputData = &inputData;
if ( !g_pResourceCompilerSystem->GenerateResourceBytes( path, *outputData, compileSettings ) )
{
delete outputData;
return nullptr;
}
return outputData;
}
}

View File

@@ -0,0 +1,6 @@
managed static class Sandbox.Diagnostics.Logging
{
static void RegisterEngineLogger( int id, string name );
}

View File

@@ -0,0 +1,6 @@
native static class ErrorReports as NativeErrorReporter
{
void SetTag( string key, string value );
void Breadcrumb( bool action, string category, string description );
}

View File

@@ -0,0 +1,13 @@
include "tier0/perftrace.h"
[nogc]
native static class PerformanceTrace as NativeEngine.PerformanceTrace
{
inline static void BeginEvent( void* name, string data, uint color )
{
PerformanceTrace::BeginEvent( (const char*)name, data, color );
}
static void EndEvent();
}

View File

@@ -0,0 +1,24 @@

#include "sbox/physics_trace.h"
native struct PhysicsTrace.Result;
native struct PhysicsTrace.Request;
native class CUtlVector<PhysicsTrace.Result> as NativeEngine.CUtlVectorTraceResult
{
void DeleteThis(); [delete]
static CUtlVectorTraceResult Create( int growsize, int initialcapacity ); [new]
int Count();
PhysicsTrace.Result Element( int i );
}
native static class PhysicsTrace
{
PhysicsTrace.Result Trace( PhysicsTrace.Request request );
void TraceAll( PhysicsTrace.Request request, CUtlVectorTraceResult results );
PhysicsTrace.Result TraceAgainstCapsule( PhysicsTrace.Request request, Capsule capsule, Transform tx );
PhysicsTrace.Result TraceAgainstBBox( PhysicsTrace.Request request, BBox box, Transform tx );
PhysicsTrace.Result TraceAgainstSphere( PhysicsTrace.Request request, Sphere sphere, Transform tx );
}

View File

@@ -0,0 +1,56 @@

#include "camerarenderer.h"
native enum SceneViewFlags_t is NativeEngine.SceneViewFlags;
native class CCameraRenderer
{
void DeleteThis(); [delete]
static CCameraRenderer Create( string name, int cameraId ); [new]
void ClearSceneWorlds();
void AddSceneWorld( ISceneWorld world );
void SetRenderAttributes( CRenderAttributes attributes );
void Render( SwapChainHandle_t targetSwapChain );
void RenderToTexture( ITexture hTexture, ISceneView parentView );
void RenderToCubeTexture( ITexture hTexture, int nSlice );
void RenderToBitmap( void* pixels, int width, int height, int bytesPerPixel );
void RenderStereo( int eye, int eyeWidth, int eyeHeight, bool bSubmitThisEye );
void SubmitStereo( int eyeWidth, int eyeHeight );
void BlitStereo( int eyeWidth, int eyeHeight );
void ClearRenderTags();
void ClearExcludeTags();
void AddRenderTag( uint hash );
void AddExcludeTag( uint hash );
int ViewUniqueId;
Vector3 CameraPosition;
Angles CameraRotation;
float FieldOfView;
float ZNear;
float ZFar;
NativeRect Rect;
Vector4 Viewport;
Vector4 ClipSpaceBounds;
bool EnablePostprocessing;
bool EnableEngineOverlays;
bool Ortho;
float OrthoSize;
bool NeedTonemapRenderer;
SceneViewFlags SceneViewFlags;
bool IsRenderingStereo;
Vector3 MiddleEyePosition;
Angles MiddleEyeRotation;
Matrix OverrideProjection;
bool HasOverrideProjection;
bool FlipX;
bool FlipY;
}

View File

@@ -0,0 +1,29 @@
#include "sbox/rendercallbacks.h"
native class CReadTexturePixelsManagedCallback as NativeEngine.CReadTexturePixelsManagedCallback : IReadTexturePixelsCallback
{
void DeleteThis(); [delete]
static CReadTexturePixelsManagedCallback Create(); [new]
void SetManagedId( int id );
int GetManagedId();
void Done();
}
native class CReadBufferManagedCallback as NativeEngine.CReadBufferManagedCallback : IReadBufferCallback
{
void DeleteThis(); [delete]
static CReadBufferManagedCallback Create(); [new]
void SetManagedId( int id );
int GetManagedId();
void Done();
}
managed static class Sandbox.AsyncGPUReadback
{
void DispatchManagedReadTextureCallback( NativeEngine.CReadTexturePixelsManagedCallback caller, IntPtr pData, ImageFormat format, int nMipLevel, int nWidth, int nHeight, int nPitchInBytes );
void DispatchManagedReadBufferCallback( NativeEngine.CReadBufferManagedCallback caller, IntPtr pData, int nBytes );
}

View File

@@ -0,0 +1,79 @@

#include "sbox/rendertools.h"
native static class RenderTools as NativeEngine.RenderTools
{
bool SetRenderState( IRenderContext context, CRenderAttributes attributes, IMaterialMode materialMode, VertexLayout layout, SceneSystemPerFrameStats_t stats );
void Draw( IRenderContext context, RenderPrimitiveType type, VertexLayout layout, void* vertices, int numVertices, CastTo[uint16*] void* indices, int numIndices, SceneSystemPerFrameStats_t stats );
void ResolveFrameBuffer( IRenderContext renderContext, ITexture texture, NativeRect viewport );
void ResolveDepthBuffer( IRenderContext renderContext, ITexture texture, NativeRect viewport );
void DrawSceneObject( IRenderContext renderContext, ISceneLayer sceneLayer, CSceneObject sceneObject, Transform transform, Vector4 color, IMaterial material, CRenderAttributes attributes );
void DrawModel( IRenderContext renderContext, ISceneLayer sceneLayer, IModel hModel, CastTo[CTransformUnaligned*] void* transforms, int numTransforms, CRenderAttributes attributes );
void DrawModel( IRenderContext renderContext, ISceneLayer sceneLayer, IModel hModel, RenderBufferHandle_t hDrawArgBuffer, int nBufferOffset, CRenderAttributes attributes );
//
// Render context can be null and we'll create one
//
void Compute( IRenderContext renderContext, CRenderAttributes attributes, IMaterialMode pMode, int tx, int ty, int tz );
void ComputeIndirect( IRenderContext renderContext, CRenderAttributes attributes, IMaterialMode pMode, RenderBufferHandle_t hIndirectBuffer, uint nIndirectBufferOffset );
void SetDynamicConstantBufferData( CRenderAttributes attributes, StringToken nTokenID, IRenderContext renderContext, void* data, int dataSize );
void CopyTexture( IRenderContext renderContext, ITexture sourceTexture, ITexture destTexture, Rect_t pSrcRect, int nDestX, int nDestY, uint nSrcMipSlice, uint nSrcArraySlice, uint nDstMipSlice, uint nDstArraySlice );
inline void SetGPUBufferData( IRenderContext renderContext, RenderBufferHandle_t hGpuBuffer, void* pData, uint nDataSize, uint nOffset )
{
// Create and submit
if ( renderContext == nullptr )
{
CRenderContextPtr pRenderContext( g_pRenderDevice );
pRenderContext->SetGPUBufferData( hGpuBuffer, pData, nDataSize, nOffset );
// Not flushing on purpose, no readback needed
}
else
{
renderContext->SetGPUBufferData( hGpuBuffer, pData, nDataSize, nOffset );
}
}
inline void CopyGPUBufferHiddenStructureCount( IRenderContext renderContext, RenderBufferHandle_t hSrcBuffer, RenderBufferHandle_t hDestBuffer, uint nDestBufferOffset )
{
// Create and submit
if ( renderContext == nullptr )
{
CRenderContextPtr pRenderContext( g_pRenderDevice );
pRenderContext->CopyGPUBufferHiddenStructureCount( hSrcBuffer, hDestBuffer, nDestBufferOffset );
// Not flushing on purpose, no readback needed
}
else
{
renderContext->CopyGPUBufferHiddenStructureCount( hSrcBuffer, hDestBuffer, nDestBufferOffset );
}
}
inline void SetGPUBufferHiddenStructureCount( IRenderContext renderContext, RenderBufferHandle_t hBuffer, uint nCounter )
{
// Create and submit
if ( renderContext == nullptr )
{
CRenderContextPtr pRenderContext( g_pRenderDevice );
pRenderContext->SetGPUBufferHiddenStructureCount( hBuffer, nCounter );
// Not flushing on purpose, no readback needed
}
else
{
renderContext->SetGPUBufferHiddenStructureCount( hBuffer, nCounter );
}
}
}
native class VertexLayout as NativeEngine.VertexLayout
{
static VertexLayout Create( string name, int size ); [new]
void Destroy(); [delete]
void Free();
void Add( string semanticName, int semanticIndex, uint format, int offset );
void Build();
}

View File

@@ -0,0 +1,9 @@

#include "pvs.h"
native accessor g_pEnginePVSManager
{
IPVS BuildPvs( IWorldReference world );
void DestroyPvs( IPVS pvs );
}

View File

@@ -0,0 +1,7 @@

managed static class Sandbox.SceneSystem
{
void OnBeforeRender( CSceneObject obj, ManagedRenderSetup_t setup );
void OnAfterRender( CSceneObject obj, ManagedRenderSetup_t setup );
}

View File

@@ -0,0 +1,5 @@
managed static class Sandbox.ScreenRecorder
{
void RecordVideoFrame( IRenderContext context, ITexture hColor );
bool IsRecording();
}

View File

@@ -0,0 +1,4 @@
managed static class Sandbox.ScreenshotService
{
void ProcessFrame( IRenderContext context, ITexture hColor );
}

View File

@@ -0,0 +1,18 @@

#include "sbox/serverlist.h"
native class CServerList
{
static CServerList Create( ServerList serverObj ); [new]
void Destroy(); [delete]
void StartQuery();
void AddFilter( string key, string value );
}
managed class Sandbox.Services.ServerList
{
void OnStarted();
void OnServerResponded( void* ptr, ulong steamid );
void OnFinished();
}

View File

@@ -0,0 +1,5 @@

managed static class Steamworks.Dispatch
{
static void OnClientCallback( int type, void* data, int datasize, bool isServer );
}

View File

@@ -0,0 +1,30 @@
include "steam/isteamapps.h"
native class ISteamApps
{
bool BIsAppInstalled( int appid );
bool BIsCybercafe();
bool BIsDlcInstalled( int appID );
bool BIsLowViolence();
bool BIsSubscribed();
bool BIsSubscribedApp( int appID );
string GetAvailableGameLanguages();
string GetCurrentGameLanguage();
int GetAppBuildId();
bool BIsVACBanned();
inline string GetCommandLine()
{
char buffer[2048];
self->GetLaunchCommandLine( buffer, 2048 );
return buffer;
}
inline string GetAppInstallDir( int appid )
{
char buffer[2048];
self->GetAppInstallDir( appid, buffer, 2048 );
return buffer;
}
}

View File

@@ -0,0 +1,14 @@
native class ISteamFriends
{
inline string GetProfileItemPropertyString( ulong steamID, int itemType, int prop )
{
return self->GetProfileItemPropertyString( steamID, (ECommunityProfileItemType)itemType, (ECommunityProfileItemProperty)prop );
}
ulong RequestEquippedProfileItems( ulong steamID );
string GetPersonaName();
bool SetRichPresence( string pchKey, string pchValue );
void ClearRichPresence();
}

View File

@@ -0,0 +1,34 @@
include "steam/steam_gameserver.h"
native class ISteamGameServer
{
void SetServerName( string name );
void SetMapName( string name );
void SetGameTags( string tags );
void SetDedicatedServer( bool isDedicatedServer );
void SetAdvertiseServerActive( bool heartbeats );
void SetMaxPlayerCount( int maxPlayers );
void LogOnAnonymous();
void LogOn( string token );
void LogOff();
void SetGameDescription( string description );
void SetProduct( string productName );
void SetModDir( string modDir );
bool BLoggedOn();
inline HAuthTicket GetAuthSessionTicket( ulong targetSteamId, void* buffer, out uint ticketLength )
{
SteamNetworkingIdentity ident;
ident.SetSteamID64( targetSteamId );
return self->GetAuthSessionTicket( buffer, 1024, ticketLength, &ident );
}
inline EBeginAuthSessionResult BeginAuthSession( ulong senderSteamId, void* buffer, int length )
{
CSteamID ident = CSteamID( senderSteamId );
return self->BeginAuthSession( buffer, length, ident );
}
void CancelAuthTicket( HAuthTicket ticket );
void EndAuthSession( ulong steamId );
}

View File

@@ -0,0 +1,40 @@
native class ISteamHTMLSurface
{
bool Init();
bool Shutdown();
ulong CreateBrowser( string pchUserAgent, string pchUserCSS );
void RemoveBrowser( uint bx );
void LoadURL( uint bx, string pchURL, string pchPostData );
void AddHeader( uint bx, string key, string value );
void SetSize( uint bx, uint w, uint h );
void GetLinkAtPosition( uint bx, uint w, uint h );
void SetHorizontalScroll( uint unBrowserHandle, uint nAbsolutePixelScroll );
void SetVerticalScroll( uint unBrowserHandle, uint nAbsolutePixelScroll );
void SetKeyFocus( uint unBrowserHandle, bool b );
void AllowStartRequest( uint bx, bool b );
void JSDialogResponse( uint bx, bool b );
void SetBackgroundMode( uint bx, bool b );
void SetDPIScalingFactor( uint bx, float scale );
void KeyDown( uint unBrowserHandle, uint key, CastTo[ISteamHTMLSurface::EHTMLKeyModifiers] int modifiers, bool isSystemKey );
void KeyUp( uint unBrowserHandle, uint key, CastTo[ISteamHTMLSurface::EHTMLKeyModifiers] int modifiers );
void KeyChar( uint unBrowserHandle, uint unicodeChar, CastTo[ISteamHTMLSurface::EHTMLKeyModifiers] int modifiers );
void MouseUp( uint unBrowserHandle, CastTo[ISteamHTMLSurface::EHTMLMouseButton] int eMouseButton );
void MouseDown( uint unBrowserHandle, CastTo[ISteamHTMLSurface::EHTMLMouseButton] int eMouseButton );
void MouseDoubleClick( uint unBrowserHandle, CastTo[ISteamHTMLSurface::EHTMLMouseButton] int eMouseButton );
void MouseMove( uint unBrowserHandle, int x, int y );
void MouseWheel( uint unBrowserHandle, int nDelta );
void SetCookie( string pchHostname, string pchKey, string pchValue, string pchPath, uint nExpires, bool bSecure, bool bHTTPOnly );
}

View File

@@ -0,0 +1,50 @@
#include "sbox/steam/steaminventory.h"
native class CSteamItemInstance
{
ulong ItemId();
uint DefinitionId();
}
native class CSteamInventoryResult
{
void Destroy(); [delete]
bool IsPending();
bool IsOk();
bool CheckSteamId( ulong steamid );
uint GetTimestamp();
int Count();
CSteamItemInstance Get( int index );
}
native static class Steam.Inventory as NativeEngine.SteamInventory
{
// getting an inventory contents
CSteamInventoryResult GetAllItems();
// getting a list of inventories
int DefinitionCount();
int GetDefinitionId( int index );
string GetDefinitionProperty( int definitionId, string propertyName );
bool GetDefinitionPrice( int index, out ulong price, out ulong baseprice );
bool HasPrices();
string GetCurrency();
void CheckOut( int[] defs, int count );
bool IsCheckingOut();
bool WasCheckoutSuccessful();
}
managed static class Sandbox.Services.Inventory
{
static void OnDefinitionUpdate();
static void OnPricesUpdate( bool success, string currency );
static void OnPurchaseResult( bool success, ulong orderid, ulong transid );
}

View File

@@ -0,0 +1,22 @@
native class ISteamMatchmaking
{
void LeaveLobby( ulong steamid );
int GetNumLobbyMembers( ulong steamid );
inline ulong GetLobbyMemberByIndex( ulong steamid, int index )
{
return self->GetLobbyMemberByIndex( steamid, index ).ConvertToUint64();
}
void* GetLobbyData( ulong steamid, string key );
bool SetLobbyData( ulong steamid, string key, string data );
int GetLobbyDataCount( ulong steamid );
void DeleteLobbyData( ulong steamid, string key );
inline bool GetLobbyDataByIndex( ulong steamid, int index, void* data, int datasize, void* value, int valueSize )
{
return self->GetLobbyDataByIndex( steamid, index, (char*) data, datasize, (char*)value, valueSize );
}
}

View File

@@ -0,0 +1,51 @@
native struct SteamNetConnectionRealTimeStatus_t as Steamworks.Data.SteamNetConnectionRealTimeStatus_t;
native class ISteamNetworkingMessages
{
inline int SendMessageToUser( ulong steamid, void* data, int dataSize, int flags, int channel )
{
SteamNetworkingIdentity ident;
ident.SetSteamID( steamid );
EResult result = self->SendMessageToUser( ident, data, dataSize, flags, channel );
return result;
}
inline int ReceiveMessagesOnChannel( int channel, void* array_of_pointers, int maxmessages )
{
return self->ReceiveMessagesOnChannel( channel, (SteamNetworkingMessage_t**)array_of_pointers, maxmessages );
}
inline bool AcceptSessionWithUser( ulong steamid )
{
SteamNetworkingIdentity ident;
ident.SetSteamID( steamid );
return self->AcceptSessionWithUser( ident );
}
inline bool CloseChannelWithUser( ulong steamid, int nLocalChannel )
{
SteamNetworkingIdentity ident;
ident.SetSteamID( steamid );
return self->CloseChannelWithUser( ident, nLocalChannel );
}
inline void ReleaseMessage( void* message )
{
SteamNetworkingMessage_t* msg = (SteamNetworkingMessage_t*)message;
msg->Release();
}
inline SteamNetConnectionRealTimeStatus_t GetConnectionInfo( ulong steamid )
{
SteamNetworkingIdentity ident;
ident.SetSteamID( steamid );
SteamNetConnectionInfo_t info;
SteamNetConnectionRealTimeStatus_t status;
self->GetSessionConnectionInfo( ident, &info, &status );
return status;
}
}

View File

@@ -0,0 +1,27 @@
native enum EResult as Steamworks.Result;
native class ISteamNetworkingSockets
{
inline SteamNetConnectionRealTimeStatus_t GetConnectionInfo( HSteamNetConnection handle )
{
SteamNetConnectionRealTimeStatus_t status;
self->GetConnectionRealTimeStatus( handle, &status, 0, nullptr );
return status;
}
inline void StartAuthentication()
{
self->InitAuthentication();
}
inline void BeginRequestFakeIP()
{
self->BeginAsyncRequestFakeIP( 1 );
}
inline void ReleaseMessage( void* message )
{
SteamNetworkingMessage_t* msg = (SteamNetworkingMessage_t*)message;
msg->Release();
}
}

View File

@@ -0,0 +1,19 @@
native enum ESteamNetworkingConfigValue as Steamworks.NetConfig;
native class ISteamNetworkingUtils
{
inline void SetConfig( ESteamNetworkingConfigValue key, int value )
{
self->SetGlobalConfigValueInt32( key, value );
}
inline void SetConfig( ESteamNetworkingConfigValue key, string value )
{
self->SetGlobalConfigValueString( key, value );
}
inline void InitializeRelayNetwork()
{
self->InitRelayNetworkAccess();
}
}

View File

@@ -0,0 +1,6 @@
#include "sbox/steam/steamscreenshots.h"
native static class Steam.Screenshots as NativeEngine.SteamScreenshots
{
bool WriteScreenshot( void* pubRGB, uint cubRGB, int nWidth, int nHeight );
}

View File

@@ -0,0 +1,87 @@
#include "sbox/steam/steamugc.h"
native class Steam.Ugc.CUgcUpdate as NativeEngine.CUgcUpdate
{
inline static CUgcUpdate CreateCommunityItem()
{
return new Steam::Ugc::CUgcUpdate( k_EWorkshopFileTypeCommunity );
}
inline static CUgcUpdate CreateMtxItem()
{
return new Steam::Ugc::CUgcUpdate( k_EWorkshopFileTypeMicrotransaction );
}
inline static CUgcUpdate OpenCommunityItem( ulong itemid )
{
return new Steam::Ugc::CUgcUpdate( (PublishedFileId_t) itemid );
}
void Dispose(); [delete]
ulong GetPublishedFileId();
void SetTitle( string title );
void SetDescription( string description );
void SetLanguage( string language );
void SetMetadata( string metadata );
void SetVisibility( int visibility );
void SetTag( string tag );
void SetContentFolder( string contentFolder );
void SetPreviewImage( string previewFile );
void SetAllowLegacyUpload( bool allow );
void AddKeyValueTag( string key, string value );
void RemoveKeyValueTags( string key );
void RemoveAllKeyValueTags();
void AddPreviewFile( string previewFile, int type );
void AddPreviewVideo( string videoId );
void UpdatePreviewFile( uint index, string previewFile );
void UpdatePreviewVideo( uint index, string videoId );
void RemovePreview( uint index );
void SetRequiredGameVersions( string minVersion, string maxVersion );
bool Submit( string changeNote );
float GetProgressPercent();
ulong GetBytesProcessed();
ulong GetBytesTotal();
bool m_creating;
bool m_created;
bool m_submitted;
bool m_complete;
bool m_success;
bool m_bNeedsLegalAgreement;
int m_resultCode;
}
native class Steam.Ugc.CUgcQuery as NativeEngine.CUgcQuery
{
static CUgcQuery CreateQuery( string json, string cursor );
void Dispose(); [delete]
bool m_complete;
bool m_success;
int m_resultCode;
string GetResultJson();
}
native class Steam.Ugc.CUgcInstall as NativeEngine.CUgcInstall
{
inline static CUgcInstall Create( ulong fileid )
{
return new Steam::Ugc::CUgcInstall( (PublishedFileId_t) fileid );
}
void Dispose(); [delete]
bool m_complete;
bool m_success;
int m_resultCode;
string GetResultJson();
}

View File

@@ -0,0 +1,35 @@
include "steam/isteamuser.h"
native class ISteamUser
{
bool BLoggedOn();
inline ulong GetSteamID()
{
return self->GetSteamID().ConvertToUint64();
}
int GetVoice( bool bWantCompressed, void* pDestBuffer, uint cbDestBufferSize, out uint nBytesWritten );
int GetAvailableVoice( out uint availableData );
uint GetVoiceOptimalSampleRate();
int DecompressVoice( void* pCompressed, uint cbCompressed, void* pDestBuffer, uint cbDestBufferSize, out uint nBytesWritten, uint nDesiredSampleRate );
void StartVoiceRecording();
void StopVoiceRecording();
inline HAuthTicket GetAuthSessionTicket( ulong targetSteamId, void* buffer, out uint ticketLength )
{
SteamNetworkingIdentity ident;
ident.SetSteamID64( targetSteamId );
return self->GetAuthSessionTicket( buffer, 1024, ticketLength, &ident );
}
inline EBeginAuthSessionResult BeginAuthSession( ulong senderSteamId, void* buffer, int length )
{
CSteamID ident = CSteamID( senderSteamId );
return self->BeginAuthSession( buffer, length, ident );
}
void CancelAuthTicket( HAuthTicket ticket );
void EndAuthSession( ulong steamId );
}

View File

@@ -0,0 +1,9 @@
include "steam/isteamutils.h"
native enum ETextFilteringContext as Steamworks.TextFilteringContext;
native class ISteamUtils
{
bool InitFilterText( uint unFilterOptions );
int FilterText( Steamworks.TextFilteringContext eContext, ulong sourceSteamID, string pchInputMessage, CastTo[char*] void* pchOutFilteredText, uint nByteSizeOutFilteredText );
}

View File

@@ -0,0 +1,14 @@
managed static class Sandbox.LobbyManager
{
static void OnLobbyInvite( ulong lobbyid, ulong memberid );
static void OnMemberEntered( ulong lobbyid, ulong memberid );
static void OnMemberLeave( ulong lobbyid, ulong memberid );
static void OnEntered( ulong lobbyid );
static void OnCreated( ulong lobbyid );
static void OnDataUpdate( ulong lobbyid, ulong targetid );
static void OnChatMessage( ulong lobbyid, ulong memberid, void* message, int length );
}

View File

@@ -0,0 +1,35 @@
native static class globalSteam as NativeEngine.Steam
{
static ISteamHTMLSurface SteamHTMLSurface();
static void SteamAPI_RunCallbacks();
static void SteamGameServer_RunCallbacks();
static ISteamUser SteamUser();
static ISteamFriends SteamFriends();
static ISteamNetworkingMessages SteamNetworkingMessages();
static ISteamNetworkingUtils SteamNetworkingUtils();
static ISteamMatchmaking SteamMatchmaking();
static ISteamGameServer SteamGameServer();
static ISteamApps SteamApps();
static ISteamUtils SteamUtils();
static bool SteamGameServer_BSecure();
static ulong SteamGameServer_GetSteamID();
static void SteamGameServer_Shutdown();
static void SteamGameServer_ReleaseCurrentThreadMemory();
inline ISteamNetworkingSockets SteamNetworkingSockets()
{
if ( SteamGameServerNetworkingSockets() )
return SteamGameServerNetworkingSockets();
if ( SteamNetworkingSockets() )
return SteamNetworkingSockets();
return nullptr;
}
inline void SteamGameServer_Init( int gamePort, int queryPort, string serverVersion )
{
SteamGameServer_InitEx( 0, static_cast<uint16>( gamePort ), static_cast<uint16>( queryPort ), eServerModeAuthenticationAndSecure, serverVersion, nullptr );
}
}

View File

@@ -0,0 +1,101 @@
include "fpxr/fpxr.h"
native enum fpxr::Result as Facepunch.XR.XRResult;
native enum fpxr::GraphicsAPI as Facepunch.XR.GraphicsAPI;
native enum fpxr::InputSource as Facepunch.XR.InputSource;
native struct fpxr::VulkanInfo as Facepunch.XR.VulkanInfo;
native struct fpxr::InstanceInfo as Facepunch.XR.InstanceInfo;
native struct fpxr::Event as Facepunch.XR.Event;
native struct fpxr::TextureSubmitInfo as Facepunch.XR.TextureSubmitInfo;
[small]
native struct fpxr::InputBooleanActionState as Facepunch.XR.InputBooleanActionState;
native struct fpxr::InputFloatActionState as Facepunch.XR.InputFloatActionState;
native struct fpxr::InputVector2ActionState as Facepunch.XR.InputVector2ActionState;
native struct fpxr::InputPoseActionState as Facepunch.XR.InputPoseActionState;
native struct fpxr::InputPoseHandState as Facepunch.XR.InputPoseHandState;
native struct fpxr::ViewInfo as Facepunch.XR.ViewInfo;
[small]
native struct fpxr::InstanceProperties as Facepunch.XR.InstanceProperties;
native struct fpxr::Matrix as Facepunch.XR.XrMatrix;
native enum fpxr::Finger as Sandbox.VR.FingerValue;
native enum fpxr::HandPoseMotionRange as Sandbox.VR.MotionRange;
native class fpxr::ApplicationConfig as Facepunch.XR.ApplicationConfig
{
inline static void SetDebugCallback( IntPtr dbgCallback )
{
fpxr::ApplicationConfig::GetInstance().m_debugCallback = (fpxr::PFN_DebugCallback)dbgCallback;
}
}
native class fpxr::EventManager as Facepunch.XR.EventManager
{
inline XRResult PumpEvent( out Event ev )
{
return this->PumpEvent( *ev );
}
}
native class fpxr::Compositor as Facepunch.XR.Compositor
{
EventManager EventManager();
XRResult Submit( TextureSubmitInfo info );
XRResult BeginFrame();
XRResult EndFrame();
uint GetEyeWidth();
uint GetEyeHeight();
uint GetRenderTargetWidth();
uint GetRenderTargetHeight();
float GetDisplayRefreshRate();
XRResult GetViewInfo( uint viewIndex, out ViewInfo outViewInfo );
XRResult GetProjectionMatrix( uint viewIndex, float flNearZ, float flFarZ, out XrMatrix outViewInfo );
}
native class fpxr::Input as Facepunch.XR.Input
{
XRResult GetBooleanActionState( string path, InputSource inputSource, out InputBooleanActionState outState );
XRResult GetFloatActionState( string path, InputSource inputSource, out InputFloatActionState outState );
XRResult GetVector2ActionState( string path, InputSource inputSource, out InputVector2ActionState outState );
XRResult GetPoseActionState( string path, InputSource inputSource, out InputPoseActionState outState );
XRResult TriggerHapticVibration(float duration, float frequency, float amplitude, InputSource inputSource);
XRResult GetHandPoseState(InputSource inputSource, MotionRange motionRange, out InputPoseHandState outState);
float GetFingerCurl(InputSource inputSource, FingerValue finger);
}
[WindowsOnly]
native class fpxr::Instance as Facepunch.XR.Instance
{
inline static Instance Create(InstanceInfo instanceInfo) [new]
{
return fpxr::Init( instanceInfo );
}
inline static bool HasHeadset()
{
return fpxr::HasHeadset();
}
Compositor Compositor( VulkanInfo vulkanInfo );
Input Input();
inline string GetRequiredDeviceExtensions()
{
return this->GetDeviceExtensions();
}
inline string GetRequiredInstanceExtensions()
{
return this->GetInstanceExtensions();
}
InstanceProperties GetProperties();
}

View File

@@ -0,0 +1,16 @@
// Things in managed that we might want to call from native (i.e. during specific points in the render loop)
managed static class Sandbox.VR.VRSystem
{
bool InternalIsActive();
bool InternalWantsInit();
void BeginFrame();
void EndFrame();
bool Submit( IntPtr pTexture, IntPtr pDepthTexture );
string GetVulkanInstanceExtensionsRequired();
string GetVulkanDeviceExtensionsRequired();
void RenderOverlays();
}

View File

@@ -0,0 +1,17 @@
native class IRD_RegisterResourceDataUtils as NativeEngine.ResourceDataUtils
{
void SetDataRegistrationFailed();
bool IsReloading();
void SetFinalResourceData( void* pPtr );
bool GetDataRegistrationFailed();
void* GetFinalResourceData();
long GetResultBufferSize();
}
native class IAsyncResourceDataRequest as NativeEngine.IAsyncResourceDataRequest
{
string GetFileName();
void* GetResultBuffer();
long GetResultBufferSize();
}

View File

@@ -0,0 +1,52 @@
include "bitmap/floatbitmap.h"
native enum FBMGammaType_t;
native class FloatBitMap_t
{
static FloatBitMap_t Create(); [new]
static FloatBitMap_t Create( int width, int height); [new]
void Delete(); [delete]
bool LoadFromFile( string filename, FBMGammaType_t gamma );
bool LoadFromPFM( string pFilename );
bool LoadFromPSD( string pFilename, FBMGammaType_t ldrFileGammaType );
bool LoadFromTIF( string pFilename, FBMGammaType_t ldrFileGammaType );
bool LoadFromPNG( string pFilename, FBMGammaType_t ldrFileGammaType );
bool LoadFromJPG( string pFilename, FBMGammaType_t ldrFileGammaType );
bool LoadFromEXR( string pFilename );
void LoadFromBuffer( void* data, int size, ImageFormat format, FBMGammaType_t gamma );
void Init( int nWidth, int nHeight, int depth );
void Shutdown();
void SetChannel( int nComponent, float flValue );
void Rotate90DegreesCW();
void Rotate90DegreesCCW();
void Rotate180Degrees();
void MirrorHorizontally();
void MirrorVertically();
bool WriteTGAFile( string pFilename );
bool WritePFM( string pFilename );
bool WriteEXR( string pFilename, int nExrCompressionTypeType );
bool LoadFromInMemoryTGA( void* pBuffer, int nSize );
bool LoadFromInMemoryPSD( void* pBuffer, int nSize );
bool LoadFromInMemoryTIF( void* pBuffer, int nSize );
float Pixel( int x, int y, int z, int comp );
float PixelWrapped( int x, int y, int z, int comp );
float PixelClamped( int x, int y, int z, int comp );
float Alpha( int x, int y, int z );
Vector3 RGBPixelAsVector( int nX, int nY, int nZ );
int Width();
int Height();
int Depth();
void Resize2D( int nNewWidth, int nNewHeight, bool bClamp );
bool WriteToBuffer( void* pBuffer, int nBufSize, ImageFormat fmt, bool bLowQualityFastCompile, bool bIsSrgb, uint nFlags );
}

View File

@@ -0,0 +1,44 @@
include "dbg.h"
include "convar.h"
native enum ConVarFlags_t;
include "sandbox.console.h"
native class ConVar as NativeEngine.ConVar
{
string GetName();
string GetHelpText();
void SetValue( string value );
void SetValue( float flValue );
void SetValue( int nValue );
string GetString();
void Revert();
bool HasMin();
bool HasMax();
float GetMinValue();
float GetMaxValue();
string GetDefault();
ConVarFlags_t GetFlags();
}
native class ConCommand as NativeEngine.ConCommand
{
string GetName();
string GetHelpText();
ConVarFlags_t GetFlags();
void Run( string command );
}
managed static class Sandbox.ConVarSystem
{
static void RegisterNativeVar( ConVar convar );
static void RegisterNativeCommand( ConCommand concommand );
static void OnConVarChanged( string convarname, string value, string previous );
}

View File

@@ -0,0 +1,99 @@
#include "engine2.h"
#include "tier0/platform_extra.h"
#include "sbox/media/mediainterface.h"
#include "protocol.h"
#include "tier0/tools_stall_monitor.h"
native static class global as NativeEngine.EngineGlobal
{
void Plat_ScreenToWindowCoords( CastTo[PlatWindow_t] IntPtr hwnd, cref ref int x, cref ref int y );
void Plat_WindowToScreenCoords( CastTo[PlatWindow_t] IntPtr hwnd, cref ref int x, cref ref int y );
void Plat_MessageBox( string title, string message );
bool Plat_GetDesktopResolution( int nMonitorIndex, ref int pWidth, ref int pHeight, ref uint pRefreshRate );
int Plat_GetDefaultMonitorIndex();
bool Plat_SafeRemoveFile( string file );
void Plat_SetModuleFilename( string filename );
void Plat_SetCurrentDirectory( string filename );
ulong Plat_GetCurrentFrame();
void Plat_SetCurrentFrame( ulong nFrame );
void Plat_ChangeCurrentFrame( long nDelta );
bool Plat_IsRunningOnCustomerMachine();
bool Plat_HasClipboardText();
void Plat_SetClipboardText( string text );
string Plat_GetClipboardText();
void Plat_ClearClipboardText();
inline bool IsWindowFocused()
{
PlatWindow_t window = g_pEngineServiceMgr->GetEngineWindow();
return Plat_IsWindowFocused( window );
}
inline bool IsRetail()
{
return IsRetail();
}
inline bool HasLaunchParameter( string name )
{
return CommandLine()->FindParm( name );
}
void Plat_SetNoAssert();
inline string GetGameRootFolder()
{
static CPathBufferString gamePath;
g_pFullFileSystem->GetSearchPath( "GAMEROOT", &gamePath );
return gamePath.String();
}
inline string GetGameSearchPath()
{
static CPathBufferString gamePath;
g_pFullFileSystem->GetSearchPathArgs( "PROJECT", &gamePath );
return gamePath.String();
}
// int LaunchGame( CMaterialSystem2AppSystemDict appDict, string lpCmdLine, bool withClient, bool withTools );
bool SourceEngineUnitTestInit();
bool SourceEnginePreInit( string lpCmdLine, CMaterialSystem2AppSystemDict appDict );
bool SourceEngineInit( CMaterialSystem2AppSystemDict appDict );
bool SourceEngineFrame( CMaterialSystem2AppSystemDict appDict, double currentTime, double previousTime );
void SourceEngineShutdown( CMaterialSystem2AppSystemDict appDict, bool forced );
inline void UpdateWindowSize()
{
VideoModeChange_t* pModeChange = g_pEngineServiceMgr->GetVideoModeChange();
if ( pModeChange )
{
g_pRenderService->SetVideoMode( pModeChange->m_deviceInfo );
pModeChange->ModeChangeComplete();
}
SwapChainHandle_t m_hSwapChain = g_pEngineServiceMgr->GetEngineSwapChain();
RenderViewport_t renderViewport;
renderViewport.Init( 0, 0, 512, 512, 0, 1 );
CRenderContextPtr pRenderContext( g_pRenderDevice, RenderTargetDesc_t( m_hSwapChain, RENDER_SRGB ), "Clear" );
pRenderContext->Clear( Vector4D( 0, 0, 0, 0 ) );
pRenderContext->SetViewports( 1, &renderViewport );
pRenderContext->Submit();
g_pRenderDevice->Present( m_hSwapChain );
}
inline float GetDiagonalDpi()
{
return Plat_GetDPI();
}
bool AppIsDedicatedServer();
void ToolsStallMonitor_IndicateActivity();
}

View File

@@ -0,0 +1,39 @@
include "sbox/engineglue.h"
native static class EngineGlue as NativeEngine.EngineGlue
{
KeyValues3 JsonToKeyValues3( string json );
string KeyValuesToJson( string kv );
string KeyValues3ToJson( KeyValues3 kv );
KeyValues3 LoadKeyValues3( string kvString );
uint GetStringToken( string str );
string GetStringTokenValue( uint token );
void AddSearchPath( string path, string groupid, bool head );
bool RemoveSearchPath( string path, string groupid );
ulong ApproximateProcessMemoryUsage();
string ReadCompiledResourceFileJson( void* data );
inline void* ReadCompiledResourceFileBlock( string blockName, CastTo[ResourceFileHeader_t*] void* pHeader, cref out int nSize )
{
auto blockId = MK_RSRC_BLOCK_ID( blockName[0], blockName[1], blockName[2], blockName[3] );
ResourceHeaderBlockInfo_t info;
if ( !Resource_FindBlockInfo( pHeader, blockId, &info ) )
return nullptr;
*__nSize = info.m_nBlockSize;
return info.m_pBlockData;
}
string ReadCompiledResourceFileJsonFromFilesystem( string filename );
void SetEngineLoggingVerbose( bool verbose );
void RequestWebAuthTicket();
void CancelWebAuthTicket();
string GetWebAuthTicket();
}

View File

@@ -0,0 +1,8 @@
managed static class Sandbox.EngineLoop
{
void Print( int severitty, string logger, string message );
void DispatchConsoleCommand( string name, string args, long flags );
void OnClientOutput();
void OnSceneViewSubmitted( ISceneView view );
}

View File

@@ -0,0 +1,14 @@
include "filesystem/ifilesystem.h"
native accessor g_pFullFileSystem as NativeEngine.FullFileSystem
{
string GetSymLink( string pPath, string pathID );
void AddSymLink( string pPath, string pathID, string realPath );
void RemoveSymLink( string pPath, string pathID );
void ResetProjectPaths( bool includeCloudAssets );
void AddProjectPath( string ident, string fullPath );
void AddCloudPath( string ident, string fullPath );
}

Some files were not shown because too many files have changed in this diff Show More