Compare commits

...

57 Commits
0.0.4 ... 0.0.6

Author SHA1 Message Date
clusterfack
1bb0227ff0 Makes Coordinates more Structy (#417)
More readonly-ish and less write-ish
2017-09-14 17:38:46 -05:00
Pieter-Jan Briers
4c2632710c Fix solution file. (#416)
I n S t A m E r G e
2017-09-14 15:13:59 -06:00
Pieter-Jan Briers
518a366c7e Attempt to fix Python on Travis being too old. (#415)
* Attempt to fix Python on Travis being too old.

* Fix RUN_THIS.py too.

* Fix CI builds blocking.

* Fix BuildChecker.csproj Python versioning in Travis.
2017-09-14 14:47:00 -06:00
clusterfack
07878ad7a7 Multiple Map System (#414)
* The million error march

This commit replaces many of the vector2's with their appropriate version of either LocalCoordinates, WorldCoordinates, or ScreenCoordinates

* Change transforms to send back worldcoordinates for position instead

* Adds coordinate class file

* What the fuck is going onnnnnn

* What the fuck is goign onnnnnnnnnnnn

* Changes some shit to use multiple maps instead
Fixes the compile errors in shared first

* Compile errors mostly fixed, about to rebase

* Merge branch 'master-wizfederation' into multiplemaps

# Conflicts:
#	SS14.Client.Graphics/CluwneLib.cs
#	SS14.Client/GameObjects/ClientEntityManager.cs
#	SS14.Client/GameObjects/Components/Renderable/AnimatedSpriteComponent.cs
#	SS14.Client/GameObjects/Components/Renderable/ItemSpriteComponent.cs
#	SS14.Client/GameObjects/Components/Renderable/ParticleSystemComponent.cs
#	SS14.Client/GameObjects/Components/Renderable/SpriteComponent.cs
#	SS14.Client/GameObjects/Components/Transform/TransformComponent.cs
#	SS14.Client/Interfaces/GameObjects/IClickTargetComponent.cs
#	SS14.Client/Placement/Modes/AlignSimilar.cs
#	SS14.Client/Placement/Modes/AlignSnapgridBorder.cs
#	SS14.Client/Placement/Modes/AlignSnapgridCenter.cs
#	SS14.Client/Placement/Modes/AlignTileAny.cs
#	SS14.Client/Placement/Modes/AlignTileEmpty.cs
#	SS14.Client/Placement/Modes/AlignTileNonSolid.cs
#	SS14.Client/Placement/Modes/AlignTileSolid.cs
#	SS14.Client/Placement/Modes/AlignWall.cs
#	SS14.Client/Placement/PlacementManager.cs
#	SS14.Server/GameObjects/ServerEntityManager.cs
#	SS14.Server/Interfaces/Player/IPlayerManager.cs
#	SS14.Server/Player/PlayerManager.cs

* Whops

* Compiles, loads somewhat, lights nonfunctional, many TODOs left

* serializes states, fixes incorrect spawn

* Fix map sending to the client

* Makes things only render on the correct zlevel

* Makes entity manager wait to intiialize shit after the maps arrive

* Fixes placement net messages

* Improves some of the placement managers, others need a bit of testing and tidying up again

* Transform fix

* Polishing, make coordinates into structs

* Remove resolved comments

* Last commit before master merge

* Fix the rest of the conflicts

* Fixes super spooky bug

* Fixes cross zlevel collisions

* Fix the rendering system to render the tile system regardless of grid location
2017-09-14 07:37:31 -06:00
Acruid
a483c8c88a Sprite Clicking Rework (#413)
* Fixed AnimatedSpriteComponent clicking, SpriteComponent is still bugged.

* Added Box2.Scale helper function.
Cleaned up the WasClicked function in AnimatedSpriteComponent.

* Renamed AABB to LocalAABB in ISpriteComponent and IRenderableComponent, so it is clearer what the property contains.
Fixed more bugs in AnimatedSpriteComponent.WasClicked(), and added exceptions.

* Fixed SpriteComponent.WasClicked().
Fixed unrelated bug in EntityManager, so entities can be properly deleted again.

* Fixed issue with sprite sorting using TextRect instead of LocalAABB.
2017-09-13 07:18:35 -06:00
Dumplin
cd74d12812 Fixed Movement; Edited OSX error message; Fixed some Sonar complaints (#410)
* * CluwneLib.cs: Make _window a local variable

* BaseCollection.cs: Formatting issue

* BaseServer.cs: Removed unused parameter

* ChatManager.cs: Made public encapsulated fields

* BoundKeyEventArgs.cs: Public encapsulated parameters

* CVarFlags.cs: Explicit variable setting

* ComponentFactory.cs: unused variable

* * CluwneLib.cs: Make _window a local variable

* BaseCollection.cs: Formatting issue

* BaseServer.cs: Removed unused parameter

* ChatManager.cs: Made public encapsulated fields

* BoundKeyEventArgs.cs: Public encapsulated parameters

* CVarFlags.cs: Explicit variable setting

* ComponentFactory.cs: unused variable

* CVar fixes

* Edited the OSX error message to be a little more helpful. (You have to edit the .dylibs because they come broken).

* Fixing the sprite movement problem

* Reverted error message

* Revert Again
2017-09-11 09:43:21 -06:00
Pieter-Jan Briers
eda5ad606b Make Sonar only run on master. (#409) 2017-09-06 22:59:30 -06:00
Pieter-Jan Briers
ddefef65ae Add our own Vector2 type. (#407)
* Add our own Vector2 type.

* Fix Clamp() typo.

* I shouldn't code when tired.

* Some unit tests.
2017-09-05 17:12:14 -06:00
Pieter-Jan Briers
062db741bd Update Mac Natives error message. (#406)
Now looks for 2.4 instead of 2.2 and suggests simply copying files instead of doing complicated InstallNameGuiTool stuff.
2017-09-05 17:11:21 -06:00
Pieter-Jan Briers
d46c2da175 Adds x64 platform targets. (#405)
Note that these won't work on Windows as that's still x86 SFML natives.
2017-09-02 21:51:08 -06:00
Acruid
1c6200666f Texture Loading Performance (#404)
* ~20% speed increase for loading textures.

* clickmap was useless, it is completely removed.
2017-09-01 14:39:40 -06:00
Acruid
c9666413b2 CluwneLib Static Variables Removal (#403)
* Changed Cluwnelib.TileSize name to CluwneLib.PixelsPerMeter. I think its more descriptive of what the name is.
Removed the splash screen debug #ifdef's, and replaced with proper ConditionalAttributes.

* Window encapsulated.

* Add the RELEASE compilation symbol to Release builds of all SS14 projects.

* More CluwneLib cleanup.
2017-09-01 14:39:27 -06:00
Pieter-Jan Briers
2575786a6e Allow deletion of entities and components during iteration. (#401)
* Allow deletion of entities and components during iteration.

* Remove some cases of _entities.Values
2017-09-01 14:07:00 -06:00
Acruid
149a6280b0 Move Lighting to SS14.Client.Graphics (#400)
* Interface to Interfaces.

* Lighting moved to SS14.Client.Graphics.

* Remove more dead code.
2017-08-31 08:21:14 -06:00
clusterfack
340d75c350 Fixes Bounding/Clicking Bugs (#396)
* Fixes Bounding/Clicking Bugs

This fixes a number of bugs with the clicking system.

- Wearable animated components were fixed so that they properly report their AABB
- Wearable animated components were fixed so that they properly use their nonwornsprite or wornsprite for checkclicking
- Fixes the clicking system only choosing the player character
- Fixes the eraser only working within a 1.5 tile range

* Uses FloatMath.CloseTo()
2017-08-29 12:03:09 -06:00
clusterfack
8d9a0e5142 Creates a Snap Checking System (#389)
* Creates a Snap Checking System

Creates a system that attempts to sanitize placement of objects when attempting to spawn them on snapping grids. This checks whether an object is trying to spawn specifically on a snap grid, and if it is checks against a snapflag of the type to see if other exclusive snappable objects are on that snap grid point.

Separates the spawnentityat into tryspawnentityat which checks for snappables, and forcespawnentityat which completely ignores that.

* Fixes the yaml placement
Fixes exemption from tryspawnentityat which didn't use the bool
Snap placement managers show when canspawnat is preventing them from spawning

* Improve snap placement managers again
Fix using prototype.name instead of prototype.ID

* Nope nope

* I need to unify these two types after the next refactor

* Move to strings for snap flags.

* Check

* 「s h i t c o d e」

* Gracias appveyor now I have seen the light

* Uses FloatMath.CloseTo() to check float equality
2017-08-29 12:01:44 -06:00
clusterfack
22f0cbd8f7 Changes CloseTo again slightly (#399) 2017-08-29 07:33:17 -06:00
clusterfack
5d443b6452 Adds closeto function for checking floating point equality (#398) 2017-08-28 18:28:33 -06:00
Acruid
83f8f37dc1 Prototypes now use ResourceManager. (#394)
* "./Resources/" folder is now mounted instead of "./" in the ResourceManager.
Prototypes now use the ResourceManager.
Added FindFiles(string path) to recursively find files in the ResourceManager.
General FileHelper bug fixing and cleanup.

* Ran SS14.Shared/ContentPack* through the code cleanup again.

* Put PJB's comma back in.
2017-08-28 17:10:15 -06:00
UristMcDorf
cc886ab614 Add required registrations in whitelist for temperature, damageable, destructible. (#393) 2017-08-28 14:21:30 +02:00
clusterfack
4273266950 Adds rendering color parameter to sprite components (#388)
* Adds rendering color parameter to sprite components

* Forgot to remove this

* Sets default value to white

* Like this you mean?
2017-08-27 10:02:11 -06:00
Acruid
658a0aee7f Entity Component Shutdown Fix. (#387)
Moved various component cleanup code from OnRemove to Shutdown.
2017-08-27 09:58:04 -06:00
Acruid
9898c2cf49 Turns INetSerializableType into NetSerializableAttribute (#386)
Turns INetSerializableType into NetSerializableAttribute.
2017-08-26 22:16:27 -06:00
Acruid
ddb5d9f3a8 NetGrapher Cleanup (#385)
Fixed bug in NetManager.
2017-08-26 22:15:36 -06:00
clusterfack
f227b3abc0 Adds grid to snap grid placement manager (#384)
* Adds grid to snap grid placement manager
Fixes drawline

* Done
2017-08-26 19:21:02 +02:00
Acruid
3920da2d9f Fixes moonwalk bug and inverted up/down controls. (#380) 2017-08-26 19:20:56 +02:00
clusterfack
bfbb31aa58 Snapgrid placement (#377)
* Snapgrid placement

* REEEEEEEEEEEE world space
2017-08-26 09:33:41 +02:00
clusterfack
799be40018 Fixes scrollable containers (#381) 2017-08-26 09:33:33 +02:00
wixoaGit
152eb8dd19 Ignore outdated state update messages (#383) 2017-08-26 09:33:23 +02:00
wixoaGit
c168c0fde1 Move client GameState management (#375)
* Move client GameState management

* Remove unnecessary sequence sending

* Move resolves to dependencies, set CurrentState instead of finding it
2017-08-25 21:21:14 +02:00
clusterfack
af3c90e2a8 Removes bad shutdown (#376)
* Undoes this

* Move it to the entity manager shutdown
2017-08-25 21:20:32 +02:00
clusterfack
12e6ef88c3 Makes Walls Entities, removes tile walls (#373)
* Makes walls into entities

* Fix the align tile empty placement mode, holy shit collision bounds is fucked

* Make shadowcasting from walls work again

* Fix lights on tiles
2017-08-24 09:38:28 -06:00
clusterfack
28d74cec56 Shifts down the mobs bounding box by 0.6 tiles. (#374) 2017-08-24 14:40:28 +02:00
Pieter-Jan Briers
02efd0b41a Made the git hooks history tolerant. (#372)
If its python file doesn't exist the hooks don't run.
2017-08-23 17:13:43 -05:00
Pieter-Jan Briers
5bf337479f Fix UnknowPrototypeException typo. (#371) 2017-08-23 16:02:36 -05:00
clusterfack
3816cdb3e4 Tiles Helper Functions (#370)
* Creates a helper function for making tile indices into tile refs, and a function to get a tileref one step in any particular direction of another tileref.

* Gottem

* k
2017-08-23 11:08:42 +02:00
Pieter-Jan Briers
e54339bb5c Make null data nodes on prototypes not call LoadData() on spawned entities. (#368) 2017-08-23 07:53:31 +02:00
Pieter-Jan Briers
98d867393c Update NUnit package version. (#367)
* Update NUnit package version.

* Let's not have Travis blow up.

* And I still messed the HintPath up.
2017-08-23 07:53:16 +02:00
Pieter-Jan Briers
8dd9a3c097 Content prefixes for the reflection manager. (#369)
Allows doing class: Prototypes.DiscoBall instead of Content.Client.Prototypes.DiscoBall
2017-08-23 07:53:04 +02:00
Pieter-Jan Briers
61d30be6b3 Lighting API cleanup. (#366) 2017-08-22 07:59:13 -06:00
Pieter-Jan Briers
7aa85c0b0c ColorUtils extensions, fixes and tests. (#365)
* Color4 extensions for byte color parts, fix WithAlpha with byte.

* Unit tests and bug fix for FromHex.
2017-08-22 07:38:29 -06:00
Pieter-Jan Briers
3574395843 Fix the entity spawn panel throwing NotImplementedException, Color -> Color4 (#364)
* Fix the entity spawn panel throwing NotImplementedException.

* More rabbit hole Color conversions.
2017-08-22 07:37:04 -06:00
Pieter-Jan Briers
13b333dcf6 Fix entity initialization. (#363) 2017-08-21 15:37:04 -06:00
Pieter-Jan Briers
bead08fc7c Fix prototype class inheritance. (#362) 2017-08-21 15:36:34 -06:00
Pieter-Jan Briers
073fb20b66 Adds a per-frame virtual entity update method. (#361) 2017-08-20 19:39:42 -06:00
Pieter-Jan Briers
7adca8280c Remove some IComponent type bounds, component shutdown event. (#360)
* Remove some IComponent type bounds, component shutdown event.

Methods like GetComponent<T> don't require T to implement IComponent anymore.

Added an event to IComponent that is invoked whenever the component is shut down.

* Always at least compile your stuff kids.
2017-08-20 19:38:20 -06:00
Gilles Coremans
61183eaba3 Fixes a sonar bug. (#359) 2017-08-20 19:37:08 -06:00
wixoaGit
477b0460e8 Implement MsgEntity (#358)
* Implement MsgEntity

* Move MsgEntity registration to GameController

* Fix serializer usage
2017-08-20 19:36:33 -06:00
Pieter-Jan Briers
dd18105c92 Remove SFML from shared and server. (#355)
* Remove SFML from shared and server.

* Fix unit tests.
2017-08-20 11:07:35 -06:00
Silver
585f2467c2 Update Linux Readme (#357) 2017-08-19 23:13:12 -06:00
Pieter-Jan Briers
0c3e4ea495 Allows inputting the server port on the client. (#354) 2017-08-19 20:19:00 -06:00
Pieter-Jan Briers
afe0c95cea Fix a race condition in collidablecomponent.OnAdd (#353) 2017-08-19 20:17:11 -06:00
PJB3005
e84f072278 Update submodule to hopefully disable SFML Sonar. 2017-08-19 13:55:31 +02:00
PJB3005
ca0bbab8c0 Attempt two. 2017-08-19 13:43:46 +02:00
PJB3005
6530b8806c Attempt to ignore SFML on Sonar 2017-08-19 13:35:57 +02:00
Pieter-Jan Briers
294057e3a1 Fix resource copying on the client. (#352) 2017-08-19 11:10:55 +02:00
Pieter-Jan Briers
a57abb2ca7 Move to our own SFML.NET fork with a submodule. (#351)
* Remove SFML binaries in repo.

* Add SFML.NET submodule from our fork.

* Get build checker for submodule handling.

* Fix project references. Remove SFML from non-client.

* Make it work!

* Automatically fetch Windows CSFML natives.

* Fix project file now I'm done debugging.

* Fix project references.

* Fix CI

* Now if only I didn't typo...

* Fix Travis too

* Fix lighting.

* Move shaders over to new API.

* Fix some obsoletions.

* Improve SetUniformArray casts
2017-08-19 10:28:39 +02:00
276 changed files with 5845 additions and 5052 deletions

View File

@@ -15,9 +15,10 @@ install:
- ps: if (-Not $env:APPVEYOR_PULL_REQUEST_NUMBER) { cinst msbuild-sonarqube-runner }
before_build:
- cmd: py -3.5 RUN_THIS.py --no-prompt
- cmd: py -3.5 Resources\buildResourcePack.py --resources-dir .\Resources --out .\Resources\ResourcePack.zip --atlas-tool .\Tools\AtlasTool.exe --no-animations --to-stderr
- cmd: nuget restore SpaceStation14.sln
- ps: if (-Not $env:APPVEYOR_PULL_REQUEST_NUMBER) { MSBuild.SonarQube.Runner.exe begin /k:"ss14" /d:"sonar.host.url=https://sonarqube.com" /d:"sonar.login=$env:sonarqubekey" /d:"sonar.organization=space-wizards" }
- ps: if (-Not $env:APPVEYOR_PULL_REQUEST_NUMBER -And $env:APPVEYOR_REPO_BRANCH -Eq "master") { MSBuild.SonarQube.Runner.exe begin /k:"ss14" /d:"sonar.host.url=https://sonarqube.com" /d:"sonar.login=$env:sonarqubekey" /d:"sonar.organization=space-wizards" /d:"sonar.exclusions=SFML/**"}
build:
project: SpaceStation14.sln
@@ -25,4 +26,4 @@ build:
verbosity: minimal
after_build:
- ps: if (-Not $env:APPVEYOR_PULL_REQUEST_NUMBER) { MSBuild.SonarQube.Runner.exe end /d:"sonar.login=$env:sonarqubekey" }
- ps: if (-Not $env:APPVEYOR_PULL_REQUEST_NUMBER -And $env:APPVEYOR_REPO_BRANCH -Eq "master") { MSBuild.SonarQube.Runner.exe end /d:"sonar.login=$env:sonarqubekey" }

6
.gitignore vendored
View File

@@ -79,3 +79,9 @@ NetSerializerDebug.dll
# We're not gonna ship Mac extlibs with the repo due to size. (11 MB)
Third-Party/extlibs/Mac/
# Or the automatically-fetched Windows natives, for that matter.
Third-Party/extlibs/Windows/
# Python stuff
__pycache__
.mypy_cache

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "SFML"]
path = SFML
url = https://github.com/space-wizards/SFML.Net.git

View File

@@ -7,15 +7,24 @@ os:
- linux
- osx
addons:
apt:
sources:
- deadsnakes
packages:
- python3.6
before_install:
- if [ $TRAVIS_OS_NAME = osx ]; then brew update && brew install python3; fi
before_script:
- "nuget restore SpaceStation14.sln"
- "python3.6 RUN_THIS.py --no-prompt"
script:
- "python3 ./Resources/buildResourcePack.py --resources-dir ./Resources --out ./Resources/ResourcePack.zip --no-atlas --no-animations --to-stderr"
- "msbuild /p:Configuration=Release /p:HEADLESS=1 /nologo /m /p:AllowMissingMacNatives=yes SpaceStation14.sln"
- "cd packages/NUnit.ConsoleRunner.3.6.1/tools"
- "python3.6 ./Resources/buildResourcePack.py --resources-dir ./Resources --out ./Resources/ResourcePack.zip --no-atlas --no-animations --to-stderr"
- "msbuild /p:Configuration=Release /p:Platform=x86 /p:HEADLESS=1 /nologo /m /p:AllowMissingMacNatives=yes SpaceStation14.sln /p:Python=python3.6"
- "cd packages/NUnit.ConsoleRunner.3.7.0/tools"
- "mono --debug nunit3-console.exe ../../../bin/UnitTesting/SS14.UnitTesting.dll"

1
BuildChecker/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
INSTALLED_HOOKS_VERSION

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This is a dummy .csproj file to check things like submodules.
Better this than other errors.
If you want to create this kind of file yourself, you have to create an empty .NET application,
Then strip it of everything until you have the <Project> tags.
VS refuses to load the project if you make a bare project file and use Add -> Existing Project... for some reason.
You want to handle the Build, Clean and Rebuild tasks to prevent missing task errors on build.
If you want to learn more about these kinds of things, check out Microsoft's official documentation about MSBuild:
https://docs.microsoft.com/en-us/visualstudio/msbuild/msbuild
-->
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Choose>
<When Condition="'$(Python)' == ''">
<PropertyGroup>
<Python>python3</Python>
<Python Condition="'$(OS)'=='Windows_NT' Or '$(OS)'=='Windows'">py -3</Python>
</PropertyGroup>
</When>
</Choose>
<PropertyGroup>
<ProjectGuid>{D0DA124B-5580-4345-A02B-9F051F78915F}</ProjectGuid>
<OutputType>Exe</OutputType>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
</PropertyGroup>
<Target Name="Build">
<Exec Command="$(Python) git_helper.py" CustomErrorRegularExpression="^Error" />
</Target>
<Target Name="Rebuild" DependsOnTargets="Build" />
<Target Name="Clean">
<Message Importance="low" Text="Ignoring 'Clean' target." />
</Target>
</Project>

103
BuildChecker/git_helper.py Executable file
View File

@@ -0,0 +1,103 @@
#!/usr/bin/env python3
# Installs git hooks, updates them, updates submodules, that kind of thing.
import subprocess
import sys
import os
import shutil
from pathlib import Path
from typing import List
BUILD_CHECKER_PATH = Path(Path(__file__).resolve(strict=True).parent)
SS14_ROOT_PATH = Path(BUILD_CHECKER_PATH.parent)
SOLUTION_PATH = Path(SS14_ROOT_PATH/"SpaceStation14Content.sln")
CURRENT_HOOKS_VERSION = "2" # If this doesn't match the saved version we overwrite them all.
QUIET = "--quiet" in sys.argv
NO_HOOKS = "--nohooks" in sys.argv
def run_command(command: List[str], capture: bool = False) -> subprocess.CompletedProcess:
"""
Runs a command with pretty output.
"""
text = ' '.join(command)
if not QUIET:
print("$ {}".format(text))
sys.stdout.flush()
completed = None
if capture:
completed = subprocess.run(command, cwd=str(SS14_ROOT_PATH), stdout=subprocess.PIPE)
else:
completed = subprocess.run(command, cwd=str(SS14_ROOT_PATH))
if completed.returncode != 0:
raise RuntimeError("Error: command exited with code {}!".format(completed.returncode))
return completed
def update_submodules():
"""
Updates all submodules.
"""
status = run_command(["git", "submodule", "update", "--init", "--recursive"], capture=True)
if status.stdout.decode().strip():
print("Git submodules changed. Reloading solution.")
reset_solution()
def install_hooks():
"""
Installs the necessary git hooks into .git/hooks.
"""
# Read version file.
if os.path.isfile(BUILD_CHECKER_PATH/"INSTALLED_HOOKS_VERSION"):
with open(BUILD_CHECKER_PATH/"INSTALLED_HOOKS_VERSION", "r") as f:
if f.read() == CURRENT_HOOKS_VERSION:
if not QUIET:
print("No hooks change detected.")
return
with open(BUILD_CHECKER_PATH/"INSTALLED_HOOKS_VERSION", "w") as f:
f.write(CURRENT_HOOKS_VERSION)
print("Hooks need updating.")
hooks_target_dir = SS14_ROOT_PATH/".git"/"hooks"
hooks_source_dir = BUILD_CHECKER_PATH/"hooks"
if not os.path.exists(str(hooks_target_dir)):
os.makedirs(str(hooks_target_dir))
# Clear entire tree since we need to kill deleted files too.
for filename in os.listdir(str(hooks_target_dir)):
os.remove(str(hooks_target_dir/filename))
for filename in os.listdir(str(hooks_source_dir)):
print("Copying hook {}".format(filename))
shutil.copyfile(str(hooks_source_dir/filename), str(hooks_target_dir/filename))
def reset_solution():
"""
Force VS to think the solution has been changed to prompt the user to reload it,
thus fixing any load errors.
"""
with SOLUTION_PATH.open("r") as f:
content = f.read()
with SOLUTION_PATH.open("w") as f:
f.write(content)
def main():
if not NO_HOOKS:
install_hooks()
update_submodules()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,19 @@
#!/bin/bash
gitroot=`git rev-parse --show-toplevel`
cd "$gitroot/BuildChecker"
if [ -f "git_helper.py" ]
then
if [[ `uname` == MINGW* || `uname` == CYGWIN* ]]; then
# Windows
# Can't update hooks from here because we are a hook,
# and the file is read only while it's used.
# Thanks Windows.
py -3 git_helper.py --quiet --nohooks
else
# Not Windows, so probably some other Unix thing.
python3 git_helper.py --quiet
fi
fi

View File

@@ -0,0 +1,5 @@
#!/bin/bash
# Just call post-checkout since it does the same thing.
gitroot=`git rev-parse --show-toplevel`
bash "$gitroot/.git/hooks/post-checkout"

View File

@@ -6,72 +6,54 @@
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{59250BAF-0000-0000-0000-000000000000}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<ApplicationIcon>
</ApplicationIcon>
<AssemblyKeyContainerName>
</AssemblyKeyContainerName>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ApplicationIcon />
<AssemblyKeyContainerName />
<AssemblyName>Lidgren.Network</AssemblyName>
<DefaultClientScript>JScript</DefaultClientScript>
<DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>
<DefaultTargetSchema>IE50</DefaultTargetSchema>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<OutputType>Library</OutputType>
<AppDesignerFolder>
</AppDesignerFolder>
<AppDesignerFolder />
<RootNamespace>Lidgren.Network</RootNamespace>
<StartupObject>
</StartupObject>
<StartArguments>
</StartArguments>
<FileUpgradeFlags>
</FileUpgradeFlags>
<StartupObject />
<StartArguments />
<FileUpgradeFlags />
<ConfigurationOverrideFile />
<TargetFrameworkProfile />
<DocumentationFile />
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<FileAlignment>4096</FileAlignment>
<OutputPath>$(SolutionDir)bin\Lidgren\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<RemoveIntegerChecks>False</RemoveIntegerChecks>
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<NoStdLib>False</NoStdLib>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>True</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<Optimize>False</Optimize>
<OutputPath>$(SolutionDir)bin\Lidgren\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<RemoveIntegerChecks>False</RemoveIntegerChecks>
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<NoStdLib>False</NoStdLib>
<NoWarn>
</NoWarn>
<PlatformTarget>x86</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>False</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<Optimize>True</Optimize>
<OutputPath>$(SolutionDir)bin\Lidgren\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<RemoveIntegerChecks>False</RemoveIntegerChecks>
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<NoStdLib>False</NoStdLib>
<NoWarn>
</NoWarn>
<PlatformTarget>x86</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<DefineConstants>TRACE;DEBUG</DefineConstants>
<DebugSymbols>True</DebugSymbols>
<Optimize>False</Optimize>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
<DefineConstants>TRACE</DefineConstants>
<DebugSymbols>False</DebugSymbols>
<Optimize>True</Optimize>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp">

View File

@@ -263,7 +263,7 @@ namespace Lidgren.Network
}
return new string(c);
}
/// <summary>
/// Gets the local broadcast address
/// </summary>
@@ -275,7 +275,7 @@ namespace Lidgren.Network
if (wifi.IsWifiEnabled)
{
var dhcp = wifi.DhcpInfo;
int broadcast = (dhcp.IpAddress & dhcp.Netmask) | ~dhcp.Netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
@@ -289,7 +289,7 @@ namespace Lidgren.Network
{
return IPAddress.Broadcast;
}
#endif
#endif
#if IS_FULL_NET_AVAILABLE
try
{
@@ -298,7 +298,7 @@ namespace Lidgren.Network
{
return null;
}
IPInterfaceProperties properties = ni.GetIPProperties();
foreach (UnicastIPAddressInformation unicastAddress in properties.UnicastAddresses)
{
@@ -307,24 +307,24 @@ namespace Lidgren.Network
var mask = unicastAddress.IPv4Mask;
byte[] ipAdressBytes = unicastAddress.Address.GetAddressBytes();
byte[] subnetMaskBytes = mask.GetAddressBytes();
if (ipAdressBytes.Length != subnetMaskBytes.Length)
throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
byte[] broadcastAddress = new byte[ipAdressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++)
{
broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));
}
return new IPAddress(broadcastAddress);
return new IPAddress(broadcastAddress);
}
}
}
catch // Catch any errors
catch // Catch any errors
{
return IPAddress.Broadcast;
}
#endif
#endif
return IPAddress.Broadcast;
}
@@ -340,21 +340,21 @@ namespace Lidgren.Network
Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)Android.App.Application.Context.GetSystemService(Android.App.Activity.WifiService);
if (!wifi.IsWifiEnabled) return null;
var dhcp = wifi.DhcpInfo;
int addr = dhcp.IpAddress;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
{
quads[k] = (byte) ((addr >> k * 8) & 0xFF);
}
}
return new IPAddress(quads);
}
catch // Catch Access Denied errors
{
return null;
}
#endif
#endif
#if IS_FULL_NET_AVAILABLE
NetworkInterface ni = GetNetworkInterface();
if (ni == null)
@@ -577,4 +577,4 @@ namespace Lidgren.Network
return bdr.ToString();
}
}
}
}

View File

@@ -23,5 +23,7 @@
</Choose>
<PropertyGroup>
<TargetOS Condition="'$(TargetOS)' == ''">$(ActualOS)</TargetOS>
<Python>python3</Python>
<Python Condition="'$(ActualOS)' == 'Windows'">py -3</Python>
</PropertyGroup>
</Project>

41
RUN_THIS.py Executable file
View File

@@ -0,0 +1,41 @@
#!/usr/bin/env python3
# Import future so people on py2 still get the clear error that they need to upgrade.
from __future__ import print_function
import os
import sys
import traceback
VERSION = sys.version_info
NO_PROMPT = "--no-prompt" in sys.argv
sane_input = raw_input if VERSION.major < 3 else input
def main():
if VERSION.major < 3 or (VERSION.major == 3 and VERSION.minor < 5):
print("ERROR: You need at least Python 3.5 to build SS14.")
# Need "press enter to exit" stuff because Windows just immediately closes conhost.
if not NO_PROMPT:
sane_input("Press enter to exit...")
exit(1)
# Import git_helper by modifying the path.
ss14_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(ss14_dir, "BuildChecker"))
try:
import git_helper
git_helper.main()
except Exception as e:
print("ERROR:")
traceback.print_exc()
print("This was NOT intentional. If the error is not immediately obvious, ask on Discord or IRC for help.")
if not NO_PROMPT:
sane_input("Press enter to exit...")
exit(1)
if __name__ == "__main__":
main()
if not NO_PROMPT:
sane_input("Success! Press enter to exit...")

View File

@@ -22,7 +22,7 @@
- type: Transform
- type: Clickable
- type: WearableAnimatedSprite
sprite: player_toolbox
sprite: player_shoes
notWornSprite: shoes
- type: Icon

View File

@@ -15,3 +15,7 @@
- type: BoundingBox
- type: Collidable
placement:
snap:
- Wall

View File

@@ -5,7 +5,7 @@
- type: Transform
- type: Clickable
- type: WearableAnimatedSprite
sprite: player_toolbox
sprite: player_mop
notWornSprite: mop
- type: Icon

View File

@@ -12,11 +12,9 @@
icon: wall_light
- type: PointLight
lightoffsetx: 0
lightoffsety: 0
lightradius: 1024
lightColorR: 220
lightColorG: 220
lightColorB: 198
mask: whitemask
startState: On
radius: 1024
color: "#DCDCC6"
placement:
snap:
- Wallmount

View File

@@ -13,6 +13,7 @@
- type: BoundingBox
sizeX: 0.9
sizeY: 0.9
offsetY: 0.6
- type: ParticleSystem
- type: Physics

View File

@@ -11,10 +11,12 @@
placement:
mode: AlignWall
range: 200
modes:
nodes:
- 18
- 26
- 32
snap:
- Wallmount
- type: entity
id: FireAlarm
@@ -36,6 +38,8 @@
- 5
- 10
- 15
snap:
- Wallmount
- type: entity
id: MedCabinet
@@ -52,3 +56,5 @@
placement:
mode: AlignWall
snap:
- Wallmount

View File

@@ -0,0 +1,21 @@
- type: entity
id: Wall
name: Wall
components:
- type: Transform
- type: Clickable
- type: Sprite
drawdepth: FloorPlaceable
sprites:
- wall_texture
- type: Icon
icon: wall_texture
- type: BoundingBox
- type: Collidable
placement:
snap:
- Wall

View File

@@ -3,75 +3,23 @@
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform vec2 weights_offsets7;
uniform vec2 weights_offsets8;
uniform vec2 weights_offsets9;
uniform vec2 weights_offsets10;
uniform vec2 weights_offsets11;
uniform vec2 weights_offsets12;
uniform vec2 weights_offsets13;
uniform vec2 weights_offsets14;
uniform vec2 weights_offsets15;
uniform vec2 weights_offsets16;
uniform vec2 weights_offsets17;
uniform vec2 weights_offsets18;
uniform vec2 weights_offsets19;
uniform vec2 weights_offsets20;
uniform vec2 weights_offsets21;
uniform vec2 weights_offsets22;
uniform sampler2D colorMapTexture;
vec4 GaussianBlurHorizontal()
{
vec4 color = vec4(0,0,0,0);
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6,
weights_offsets7,
weights_offsets8,
weights_offsets9,
weights_offsets10,
weights_offsets11,
weights_offsets12,
weights_offsets13,
weights_offsets14,
weights_offsets15,
weights_offsets16,
weights_offsets17,
weights_offsets18,
weights_offsets19,
weights_offsets20,
weights_offsets21,
weights_offsets22
);
vec4 color = vec4(0,0,0,0);
for (int i = 0; i < KERNEL_SIZE; ++i)
{
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x + weights_offsets[i].y, gl_TexCoord[0].y))* weights_offsets[i].x;
{
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x + weights_offsets[i].y, gl_TexCoord[0].y))* weights_offsets[i].x;
}
return color;
}
void main()
{
gl_FragColor = GaussianBlurHorizontal();
gl_FragColor = GaussianBlurHorizontal();
}

View File

@@ -1,73 +1,23 @@
#version 120
#define RADIUS 11
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform vec2 weights_offsets7;
uniform vec2 weights_offsets8;
uniform vec2 weights_offsets9;
uniform vec2 weights_offsets10;
uniform vec2 weights_offsets11;
uniform vec2 weights_offsets12;
uniform vec2 weights_offsets13;
uniform vec2 weights_offsets14;
uniform vec2 weights_offsets15;
uniform vec2 weights_offsets16;
uniform vec2 weights_offsets17;
uniform vec2 weights_offsets18;
uniform vec2 weights_offsets19;
uniform vec2 weights_offsets20;
uniform vec2 weights_offsets21;
uniform vec2 weights_offsets22;
uniform sampler2D colorMapTexture;
vec4 GaussianBlurVertical()
{
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6,
weights_offsets7,
weights_offsets8,
weights_offsets9,
weights_offsets10,
weights_offsets11,
weights_offsets12,
weights_offsets13,
weights_offsets14,
weights_offsets15,
weights_offsets16,
weights_offsets17,
weights_offsets18,
weights_offsets19,
weights_offsets20,
weights_offsets21,
weights_offsets22
);
vec4 color = vec4(0,0,0,0);
for (int i = 0; i < KERNEL_SIZE; ++i)
{
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y + weights_offsets[i].y)) * weights_offsets[i].x; // M A G I K
}
}
return color;
}
void main()
{
gl_FragColor = GaussianBlurVertical();
gl_FragColor = GaussianBlurVertical();
}

View File

@@ -3,38 +3,20 @@
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform sampler2D colorMapTexture;
vec4 GaussianBlurHorizontal()
{
vec4 color = vec4(0,0,0,0);
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6
);
vec4 color = vec4(0,0,0,0);
for (int i = 0; i < KERNEL_SIZE; ++i)
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x + weights_offsets[i].y, gl_TexCoord[0].y)) * weights_offsets[i].x;
return color;
}
void main()
{
gl_FragColor = GaussianBlurHorizontal();
{
gl_FragColor = GaussianBlurHorizontal();
}

View File

@@ -1,40 +1,22 @@
#version 120
#define RADIUS 3
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform sampler2D colorMapTexture;
vec4 GaussianBlurVertical()
{
vec4 color = vec4(0,0,0,0);
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6
);
for (int i = 0; i < KERNEL_SIZE; ++i)
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y + weights_offsets[i].y)) * weights_offsets[i].x;
return color;
}
void main()
{
gl_FragColor = GaussianBlurVertical();
{
gl_FragColor = GaussianBlurVertical();
}

View File

@@ -3,47 +3,21 @@
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform vec2 weights_offsets7;
uniform vec2 weights_offsets8;
uniform vec2 weights_offsets9;
uniform vec2 weights_offsets10;
uniform sampler2D colorMapTexture;
vec4 GaussianBlurHorizontal()
{
vec4 color = vec4(0,0,0,0);
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6,
weights_offsets7,
weights_offsets8,
weights_offsets9,
weights_offsets10
);
vec4 color = vec4(0,0,0,0);
for (int i = 0; i < KERNEL_SIZE; ++i)
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x + weights_offsets[i].y, gl_TexCoord[0].y)) * weights_offsets[i].x;
return color;
}
void main()
{
gl_FragColor = GaussianBlurHorizontal();
gl_FragColor = GaussianBlurHorizontal();
}

View File

@@ -1,50 +1,24 @@
#version 120
#define RADIUS 5
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform vec2 weights_offsets7;
uniform vec2 weights_offsets8;
uniform vec2 weights_offsets9;
uniform vec2 weights_offsets10;
uniform sampler2D colorMapTexture;
vec4 GaussianBlurVertical()
{
vec4 color = vec4(0,0,0,0);
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6,
weights_offsets7,
weights_offsets8,
weights_offsets9,
weights_offsets10
);
for (int i = 0; i < KERNEL_SIZE; ++i)
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y + weights_offsets[i].y)) * weights_offsets[i].x;
return color;
}
void main()
{
gl_FragColor = GaussianBlurVertical();
{
gl_FragColor = GaussianBlurVertical();
}

View File

@@ -3,54 +3,21 @@
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform vec2 weights_offsets7;
uniform vec2 weights_offsets8;
uniform vec2 weights_offsets9;
uniform vec2 weights_offsets10;
uniform vec2 weights_offsets11;
uniform vec2 weights_offsets12;
uniform vec2 weights_offsets13;
uniform vec2 weights_offsets14;
uniform sampler2D colorMapTexture;
vec4 GaussianBlurHorizontal()
{
vec4 color = vec4(0,0,0,0);
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6,
weights_offsets7,
weights_offsets8,
weights_offsets9,
weights_offsets10,
weights_offsets11,
weights_offsets12,
weights_offsets13,
weights_offsets14
);
vec4 color = vec4(0,0,0,0);
for (int i = 0; i < KERNEL_SIZE; ++i)
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x + weights_offsets[i].y, gl_TexCoord[0].y)) * weights_offsets[i].x;
return color;
}
void main()
{
{
gl_FragColor = GaussianBlurHorizontal();
}

View File

@@ -1,57 +1,22 @@
#version 120
#define RADIUS 7
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform vec2 weights_offsets7;
uniform vec2 weights_offsets8;
uniform vec2 weights_offsets9;
uniform vec2 weights_offsets10;
uniform vec2 weights_offsets11;
uniform vec2 weights_offsets12;
uniform vec2 weights_offsets13;
uniform vec2 weights_offsets14;
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform sampler2D colorMapTexture;
vec4 GaussianBlurVertical()
{
vec4 color = vec4(0,0,0,0);
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6,
weights_offsets7,
weights_offsets8,
weights_offsets9,
weights_offsets10,
weights_offsets11,
weights_offsets12,
weights_offsets13,
weights_offsets14
);
for (int i = 0; i < KERNEL_SIZE; ++i)
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y + weights_offsets[i].y)) * weights_offsets[i].x;
return color;
}
void main()
{
gl_FragColor = GaussianBlurVertical();
gl_FragColor = GaussianBlurVertical();
}

View File

@@ -3,63 +3,21 @@
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform vec2 weights_offsets7;
uniform vec2 weights_offsets8;
uniform vec2 weights_offsets9;
uniform vec2 weights_offsets10;
uniform vec2 weights_offsets11;
uniform vec2 weights_offsets12;
uniform vec2 weights_offsets13;
uniform vec2 weights_offsets14;
uniform vec2 weights_offsets15;
uniform vec2 weights_offsets16;
uniform vec2 weights_offsets17;
uniform vec2 weights_offsets18;
uniform sampler2D colorMapTexture;
vec4 GaussianBlurHorizontal()
{
vec4 color = vec4(0,0,0,0);
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6,
weights_offsets7,
weights_offsets8,
weights_offsets9,
weights_offsets10,
weights_offsets11,
weights_offsets12,
weights_offsets13,
weights_offsets14,
weights_offsets15,
weights_offsets16,
weights_offsets17,
weights_offsets18
);
for (int i = 0; i < KERNEL_SIZE; ++i)
vec4 color = vec4(0,0,0,0);
for (int i = 0; i < KERNEL_SIZE; ++i)
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x + weights_offsets[i].y, gl_TexCoord[0].y)) * weights_offsets[i].x;
return color;
}
void main()
{
gl_FragColor = GaussianBlurHorizontal();
return color;
}
void main()
{
gl_FragColor = GaussianBlurHorizontal();
}

View File

@@ -1,66 +1,22 @@
#version 120
#define RADIUS 9
#define KERNEL_SIZE (RADIUS * 2 + 1)
uniform vec2 weights_offsets[KERNEL_SIZE];
uniform vec2 weights_offsets0;
uniform vec2 weights_offsets1;
uniform vec2 weights_offsets2;
uniform vec2 weights_offsets3;
uniform vec2 weights_offsets4;
uniform vec2 weights_offsets5;
uniform vec2 weights_offsets6;
uniform vec2 weights_offsets7;
uniform vec2 weights_offsets8;
uniform vec2 weights_offsets9;
uniform vec2 weights_offsets10;
uniform vec2 weights_offsets11;
uniform vec2 weights_offsets12;
uniform vec2 weights_offsets13;
uniform vec2 weights_offsets14;
uniform vec2 weights_offsets15;
uniform vec2 weights_offsets16;
uniform vec2 weights_offsets17;
uniform vec2 weights_offsets18;
uniform sampler2D colorMapTexture;
vec4 GaussianBlurVertical()
{
vec4 color = vec4(0,0,0,0);
vec2 weights_offsets[KERNEL_SIZE] = vec2[KERNEL_SIZE]
(
weights_offsets0,
weights_offsets1,
weights_offsets2,
weights_offsets3,
weights_offsets4,
weights_offsets5,
weights_offsets6,
weights_offsets7,
weights_offsets8,
weights_offsets9,
weights_offsets10,
weights_offsets11,
weights_offsets12,
weights_offsets13,
weights_offsets14,
weights_offsets15,
weights_offsets16,
weights_offsets17,
weights_offsets18
);
for (int i = 0; i < KERNEL_SIZE; ++i)
color += texture2D(colorMapTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y + weights_offsets[i].y)) * weights_offsets[i].x;
return color;
}
void main()
{
gl_FragColor = GaussianBlurVertical();
gl_FragColor = GaussianBlurVertical();
}

View File

@@ -1,20 +1,8 @@
#version 120
#define NUM_LIGHTS 6
uniform vec4 LightPosData0;
uniform vec4 LightPosData1;
uniform vec4 LightPosData2;
uniform vec4 LightPosData3;
uniform vec4 LightPosData4;
uniform vec4 LightPosData5;
uniform vec4 LightPosData[NUM_LIGHTS];
uniform vec4 LightPosData[NUM_LIGHTS];
uniform vec4 Colors[NUM_LIGHTS];
uniform vec4 Colors0;
uniform vec4 Colors1;
uniform vec4 Colors2;
uniform vec4 Colors3;
uniform vec4 Colors4;
uniform vec4 Colors5;
uniform sampler2D light0;
uniform sampler2D light1;
@@ -25,61 +13,41 @@ uniform sampler2D light5;
uniform sampler2D sceneTexture;
vec4 PreLightBlendPS()
vec4 PreLightBlendPS()
{
vec4 Colors[NUM_LIGHTS] = vec4[NUM_LIGHTS]
(
Colors0,
Colors1,
Colors2,
Colors3,
Colors4,
Colors5
);
vec4 LightPosData[NUM_LIGHTS] = vec4[NUM_LIGHTS]
(
LightPosData0,
LightPosData1,
LightPosData2,
LightPosData3,
LightPosData4,
LightPosData5
);
vec4 l[NUM_LIGHTS];
vec2 ltc[NUM_LIGHTS];
for(int i = 0;i<NUM_LIGHTS;i++)
{
ltc[i] = vec2((gl_TexCoord[0].x - LightPosData[i].x) * LightPosData[i].z, (gl_TexCoord[0].y - LightPosData[i].y) * LightPosData[i].w);
}
l[0] = texture2D(light0, ltc[0]);
l[1] = texture2D(light1, ltc[1]);
l[2] = texture2D(light2, ltc[2]);
l[3] = texture2D(light3, ltc[3]);
l[4] = texture2D(light4, ltc[4]);
l[5] = texture2D(light5, ltc[5]);
vec4 l[NUM_LIGHTS];
vec2 ltc[NUM_LIGHTS];
for(int i = 0;i<NUM_LIGHTS;i++)
{
ltc[i] = vec2((gl_TexCoord[0].x - LightPosData[i].x) * LightPosData[i].z, (gl_TexCoord[0].y - LightPosData[i].y) * LightPosData[i].w);
}
l[0] = texture2D(light0, ltc[0]);
l[1] = texture2D(light1, ltc[1]);
l[2] = texture2D(light2, ltc[2]);
l[3] = texture2D(light3, ltc[3]);
l[4] = texture2D(light4, ltc[4]);
l[5] = texture2D(light5, ltc[5]);
l[0].rgb = l[0].rgb * Colors[0].rgb;
l[1].rgb = l[1].rgb * Colors[1].rgb;
l[2].rgb = l[2].rgb * Colors[2].rgb;
l[3].rgb = l[3].rgb * Colors[3].rgb;
l[4].rgb = l[4].rgb * Colors[4].rgb;
l[5].rgb = l[5].rgb * Colors[5].rgb;
vec4 s = texture2D(sceneTexture, gl_TexCoord[0].xy); // sample existing lights
//Add the lights together
float r = sqrt(pow(l[0].r, 2) + pow(l[1].r, 2) + pow(l[2].r, 2) + pow(l[3].r, 2) + pow(l[4].r, 2) + pow(l[5].r, 2) + pow(s.r, 2));
float g = sqrt(pow(l[0].g, 2) + pow(l[1].g, 2) + pow(l[2].g, 2) + pow(l[3].g, 2) + pow(l[4].g, 2) + pow(l[5].g, 2) + pow(s.g, 2));
float b = sqrt(pow(l[0].b, 2) + pow(l[1].b, 2) + pow(l[2].b, 2) + pow(l[3].b, 2) + pow(l[4].b, 2) + pow(l[5].b, 2) + pow(s.b, 2));
vec4 c = vec4(r,g,b, 1);
return c;
//Return the light color
return vec4(c.rgb,min(1, 1/max(c.r, max(c.g,c.b))));
l[0].rgb = l[0].rgb * Colors[0].rgb;
l[1].rgb = l[1].rgb * Colors[1].rgb;
l[2].rgb = l[2].rgb * Colors[2].rgb;
l[3].rgb = l[3].rgb * Colors[3].rgb;
l[4].rgb = l[4].rgb * Colors[4].rgb;
l[5].rgb = l[5].rgb * Colors[5].rgb;
vec4 s = texture2D(sceneTexture, gl_TexCoord[0].xy); // sample existing lights
//Add the lights together
float r = sqrt(pow(l[0].r, 2) + pow(l[1].r, 2) + pow(l[2].r, 2) + pow(l[3].r, 2) + pow(l[4].r, 2) + pow(l[5].r, 2) + pow(s.r, 2));
float g = sqrt(pow(l[0].g, 2) + pow(l[1].g, 2) + pow(l[2].g, 2) + pow(l[3].g, 2) + pow(l[4].g, 2) + pow(l[5].g, 2) + pow(s.g, 2));
float b = sqrt(pow(l[0].b, 2) + pow(l[1].b, 2) + pow(l[2].b, 2) + pow(l[3].b, 2) + pow(l[4].b, 2) + pow(l[5].b, 2) + pow(s.b, 2));
vec4 c = vec4(r,g,b, 1);
return c;
//Return the light color
return vec4(c.rgb,min(1, 1/max(c.r, max(c.g,c.b))));
}
void main()
{
gl_FragColor = PreLightBlendPS();
}
gl_FragColor = PreLightBlendPS();
}

1
SFML Submodule

Submodule SFML added at 0f22866353

View File

@@ -6,14 +6,17 @@ using SFML.Window;
using SS14.Client.Graphics.Render;
using SS14.Client.Graphics.Settings;
using SS14.Client.Graphics.Shader;
using SS14.Client.Graphics.View;
using System;
using System.Reflection;
using SS14.Shared.Network;
using SS14.Shared.Timing;
using SS14.Client.Graphics.Utility;
using SS14.Shared.Maths;
using SS14.Shared.Timing;
using System;
using GraphicsContext = OpenTK.Graphics.GraphicsContext;
using Vector2i = SS14.Shared.Maths.Vector2i;
using Vector2u = SS14.Shared.Maths.Vector2u;
using Vector2 = SS14.Shared.Maths.Vector2;
using SS14.Shared.Map;
using SS14.Shared.Interfaces.Map;
using SS14.Shared.IoC;
namespace SS14.Client.Graphics
{
@@ -23,45 +26,20 @@ namespace SS14.Client.Graphics
public static GameTiming Time { get; private set; }
public static event EventHandler<FrameEventArgs> FrameEvent;
public static Viewport CurrentClippingViewport;
public delegate void EventHandler();
public static event EventHandler RefreshVideoSettings;
#region Accessors
public static Vector2 WorldCenter { get; set; }
public static Vector2u ScreenViewportSize { get; set; }
public static Box2 WorldViewport => ScreenToWorld(Box2i.FromDimensions(0, 0, (int)Window.Viewport.Size.X, (int)Window.Viewport.Size.Y));
/// <summary>
/// Viewport scaling
/// </summary>
public static int TileSize { get; set; } = 32;
public static Box2 WorldViewport
{
get
{
return ScreenToWorld(ScreenViewport);
}
}
public static Box2i ScreenViewport
{
get
{
return Box2i.FromDimensions(0, 0, (int)ScreenViewportSize.X, (int)ScreenViewportSize.Y);
}
}
public static bool IsInitialized { get; set; }
public static bool IsRunning { get; set; }
private static bool IsInitialized { get; set; }
public static bool IsRunning { get; private set; }
public static bool FrameStatsVisible { get; set; }
public static CluwneWindow SplashScreen { get; set; }
public static CluwneWindow Screen { get; set; }
public static VideoSettings Video { get; private set; }
public static Debug Debug { get; private set; }
public static InputEvents Input { get; internal set; }
private static CluwneWindow SplashScreen { get; set; }
public static CluwneWindow Window { get; private set; }
public static VideoSettings Video { get; }
public static Debug Debug { get; }
public static GLSLShader CurrentShader { get; internal set; }
public static BlendingModes BlendingMode { get; set; }
@@ -70,21 +48,19 @@ namespace SS14.Client.Graphics
get
{
if (renderTargetArray[0] == null)
renderTargetArray[0] = Screen;
renderTargetArray[0] = Window.Screen;
return renderTargetArray[0];
}
internal set
{
if (value == null)
value = Screen;
value = Window.Screen;
setAdditionalRenderTarget(0, value);
}
}
#endregion
static CluwneLib()
{
Video = new VideoSettings();
@@ -98,13 +74,12 @@ namespace SS14.Client.Graphics
/// Shamelessly taken from Gorgon.
public static void Go()
{
if (!IsInitialized)
{
Initialize();
}
if ((Screen != null) && (renderTargetArray == null))
if ((Window != null) && (renderTargetArray == null))
throw new InvalidOperationException("Something has gone terribly wrong!");
if (IsRunning)
@@ -116,10 +91,9 @@ namespace SS14.Client.Graphics
{
if (renderTargetArray[0] == null)
{
renderTargetArray[0] = Screen;
renderTargetArray[0] = Window.Screen;
}
}
}
IsRunning = true;
@@ -127,12 +101,11 @@ namespace SS14.Client.Graphics
public static CluwneWindow ShowSplashScreen(VideoMode vMode)
{
if (SplashScreen == null)
{
SplashScreen = new CluwneWindow(vMode, "Space Station 14", Styles.None);
}
if (SplashScreen != null)
return SplashScreen;
return SplashScreen;
var video = new VideoSettings(vMode);
return SplashScreen = new CluwneWindow(new RenderWindow(vMode, "Space Station 14", Styles.None), video);
}
public static void CleanupSplashScreen()
@@ -141,11 +114,6 @@ namespace SS14.Client.Graphics
SplashScreen = null;
}
public static void drawRectangle(int x, int y, int width, int height, object p)
{
throw new NotImplementedException();
}
public static void Initialize()
{
if (IsInitialized)
@@ -153,37 +121,34 @@ namespace SS14.Client.Graphics
Time = new GameTiming();
Screen = new CluwneWindow(CluwneLib.Video.getVideoMode(), "Developer Station 14", CluwneLib.Video.getWindowStyle());
Screen.SetVerticalSyncEnabled(true);
Screen.SetFramerateLimit(300);
var video = Video;
var wind = new RenderWindow(video.GetVideoMode(), "Developer Station 14", video.GetWindowStyle());
Window = new CluwneWindow(wind, video);
Window.Graphics.SetVerticalSyncEnabled(true);
Window.Graphics.SetFramerateLimit(300);
renderTargetArray = new RenderTarget[5];
CurrentClippingViewport = new Viewport(0, 0, Screen.Size.X, Screen.Size.Y);
//Window.Viewport = new Viewport(0, 0, 800, 600);
IsInitialized = true;
//Hook OpenTK into SFMLs Opengl
OpenTK.Toolkit.Init(new OpenTK.ToolkitOptions{
OpenTK.Toolkit.Init(new OpenTK.ToolkitOptions
{
// Non-Native backend doesn't have a default GetAddress method
Backend = OpenTK.PlatformBackend.PreferNative
});
new GraphicsContext(OpenTK.ContextHandle.Zero, null);
}
public static void RequestGC(Action action)
public static void ClearCurrentRendertarget(Color4 color)
{
action.Invoke();
}
public static void ClearCurrentRendertarget(Color color)
{
CurrentRenderTarget.Clear(color);
CurrentRenderTarget.Clear(color.Convert());
}
public static void Terminate()
{
CurrentClippingViewport = null;
IsInitialized = false;
Screen.Close();
Window.Close();
}
public static void RunIdle(object sender, FrameEventArgs e)
@@ -194,24 +159,21 @@ namespace SS14.Client.Graphics
public static void Stop()
{
Console.WriteLine("CluwneLib: Stop() requested");
IsRunning=false;
IsRunning = false;
}
public static void UpdateVideoSettings()
{
RefreshVideoSettings();
RefreshVideoSettings();
}
#endregion
#endregion CluwneEngine
#region RenderTarget Stuff
public static void setAdditionalRenderTarget(int index, RenderTarget _target)
{
renderTargetArray[index] = _target;
renderTargetArray[index] = _target;
}
public static RenderTarget getAdditionalRenderTarget(int index)
@@ -219,7 +181,6 @@ namespace SS14.Client.Graphics
return renderTargetArray[index];
}
/// <summary>
/// resets the Current Render Target back to the screen
/// </summary>
@@ -236,9 +197,7 @@ namespace SS14.Client.Graphics
CurrentShader = null;
}
#endregion
#endregion RenderTarget Stuff
#region Drawing Methods
@@ -252,12 +211,12 @@ namespace SS14.Client.Graphics
/// <param name="WidthX"> Width X of rectangle </param>
/// <param name="HeightY"> Height Y of rectangle </param>
/// <param name="Color"> Fill Color </param>
public static void drawRectangle(int posX, int posY, int WidthX, int HeightY, Color Color)
public static void drawRectangle(int posX, int posY, int WidthX, int HeightY, Color4 Color)
{
RectangleShape rectangle = new RectangleShape();
rectangle.Position = new SFML.System.Vector2f(posX, posY);
rectangle.Size = new SFML.System.Vector2f(WidthX, HeightY);
rectangle.FillColor = Color;
rectangle.FillColor = Color.Convert();
CurrentRenderTarget.Draw(rectangle);
}
@@ -270,17 +229,16 @@ namespace SS14.Client.Graphics
/// <param name="WidthX"> Width X of rectangle </param>
/// <param name="HeightY"> Height Y of rectangle </param>
/// <param name="Color"> Fill Color </param>
public static void drawRectangle(float posX, float posY, float WidthX, float HeightY, Color Color)
public static void drawRectangle(float posX, float posY, float WidthX, float HeightY, Color4 Color)
{
RectangleShape rectangle = new RectangleShape();
rectangle.Position = new SFML.System.Vector2f(posX, posY);
rectangle.Size = new SFML.System.Vector2f(WidthX, HeightY);
rectangle.FillColor = Color;
rectangle.FillColor = Color.Convert();
CurrentRenderTarget.Draw(rectangle);
}
/// <summary>
/// Draws a Hollow Rectangle to the Current RenderTarget
/// </summary>
@@ -290,18 +248,18 @@ namespace SS14.Client.Graphics
/// <param name="heightY"> Height Y of rectangle </param>
/// <param name="OutlineThickness"> Outline Thickness of rectangle </param>
/// <param name="OutlineColor"> Outline Color </param>
public static void drawHollowRectangle(int posX, int posY, int widthX, int heightY, float OutlineThickness, Color OutlineColor)
public static void drawHollowRectangle(int posX, int posY, int widthX, int heightY, float OutlineThickness, Color4 OutlineColor)
{
RectangleShape HollowRect = new RectangleShape();
HollowRect.FillColor = Color.Transparent;
HollowRect.Position = new SFML.System.Vector2f(posX, posY);
HollowRect.Size = new SFML.System.Vector2f(widthX, heightY);
HollowRect.OutlineThickness = OutlineThickness;
HollowRect.OutlineColor = OutlineColor;
HollowRect.OutlineColor = OutlineColor.Convert();
CurrentRenderTarget.Draw(HollowRect);
}
#endregion
#endregion Rectangle
#region Circle
/// <summary>
@@ -311,16 +269,14 @@ namespace SS14.Client.Graphics
/// <param name="posY"> Pos Y of Circle </param>
/// <param name="radius"> Radius of Circle </param>
/// <param name="color"> Fill Color </param>
public static void drawCircle(int posX, int posY, int radius, Color color)
public static void drawCircle(int posX, int posY, int radius, Color4 color)
{
CircleShape Circle = new CircleShape();
Circle.Position = new Vector2f(posX, posY);
Circle.Radius = radius;
Circle.FillColor = color;
Circle.FillColor = color.Convert();
CurrentRenderTarget.Draw(Circle);
}
/// <summary>
/// Draws a Hollow Circle to the CurrentRenderTarget
@@ -330,36 +286,19 @@ namespace SS14.Client.Graphics
/// <param name="radius"> Radius of Circle </param>
/// <param name="OutlineThickness"> Thickness of Circle Outline </param>
/// <param name="OutlineColor"> Circle outline Color </param>
public static void drawHollowCircle(int posX, int posY, int radius,float OutlineThickness, Color OutlineColor)
public static void drawHollowCircle(int posX, int posY, int radius, float OutlineThickness, Color4 OutlineColor)
{
CircleShape Circle = new CircleShape();
Circle.Position = new Vector2f(posX-radius, posY-radius);
Circle.Position = new Vector2f(posX - radius, posY - radius);
Circle.Radius = radius;
Circle.FillColor = Color.Transparent;
Circle.OutlineThickness = OutlineThickness;
Circle.OutlineColor = OutlineColor;
Circle.OutlineColor = OutlineColor.Convert();
CurrentRenderTarget.Draw(Circle);
}
/// <summary>
/// Draws a Filled Circle to the CurrentRenderTarget
/// </summary>
/// <param name="posX"> Pos X of Circle </param>
/// <param name="posY"> Pos Y of Circle </param>
/// <param name="radius"> Radius of Cirle </param>
/// <param name="color"> Fill Color </param>
/// <param name="vector2"></param>
public static void drawCircle(float posX, float posY, int radius, Color color, Vector2 vector2)
{
CircleShape Circle = new CircleShape();
Circle.Position = new Vector2f(posX, posY);
Circle.Radius = radius;
Circle.FillColor = Color.Transparent;
CurrentRenderTarget.Draw(Circle);
}
#endregion
#endregion Circle
#region Point
/// <summary>
@@ -368,12 +307,12 @@ namespace SS14.Client.Graphics
/// <param name="posX"> Pos X of Point </param>
/// <param name="posY"> Pos Y of Point </param>
/// <param name="color"> Fill Color </param>
public static void drawPoint(int posX, int posY, Color color)
public static void drawPoint(int posX, int posY, Color4 color)
{
RectangleShape Point = new RectangleShape();
Point.Position = new Vector2f(posX, posY);
Point.Size = new Vector2f(1, 1);
Point.FillColor = color;
Point.FillColor = color.Convert();
CurrentRenderTarget.Draw(Point);
}
@@ -384,19 +323,19 @@ namespace SS14.Client.Graphics
/// <param name="posX"> Pos X of Point </param>
/// <param name="posY"> Pos Y of Point </param>
/// <param name="OutlineColor"> Outline Color </param>
public static void drawHollowPoint(int posX, int posY, Color OutlineColor)
public static void drawHollowPoint(int posX, int posY, Color4 OutlineColor)
{
RectangleShape hollowPoint = new RectangleShape();
hollowPoint.Position = new Vector2f(posX, posY);
hollowPoint.Size = new Vector2f(1, 1);
hollowPoint.FillColor = Color.Transparent;
hollowPoint.OutlineThickness = .6f;
hollowPoint.OutlineColor = OutlineColor;
hollowPoint.OutlineColor = OutlineColor.Convert();
CurrentRenderTarget.Draw(hollowPoint);
}
#endregion
#endregion Point
#region Line
/// <summary>
@@ -407,18 +346,20 @@ namespace SS14.Client.Graphics
/// <param name="rotate"> Line Rotation </param>
/// <param name="thickness"> Line Thickness </param>
/// <param name="Color"> Line Color </param>
public static void drawLine(int posX, int posY, int rotate,float thickness, Color Color)
public static void drawLine(float posX, float posY, float length, float rotate, float thickness, Color4 Color)
{
RectangleShape line = new RectangleShape();
line.Position = new Vector2f(posX, posY);
line.Size = new Vector2f(length, thickness);
line.Rotation = rotate;
line.OutlineThickness = thickness;
line.FillColor = Color;
line.FillColor = Color.Convert();
line.OutlineColor = Color.Convert();
CurrentRenderTarget.Draw(line);
}
#endregion
#endregion Line
#region Text
/// <summary>
@@ -429,28 +370,33 @@ namespace SS14.Client.Graphics
/// <param name="text"> Text to render </param>
/// <param name="size"> Size of the font </param>
/// <param name="textColor"> Color of the text </param>
public static void drawText(float posX, float posY, string text, uint size, Color textColor, Font font)
public static void drawText(float posX, float posY, string text, uint size, Color4 textColor, Font font)
{
Text _text = new Text(text, font);
_text.Position = new SFML.System.Vector2f(posX, posY);
_text.Color = textColor;
_text.FillColor = textColor.Convert();
_text.CharacterSize = size;
CurrentRenderTarget.Draw(_text);
}
#endregion
#endregion Text
#endregion
#endregion Drawing Methods
#region Client Window Data
/// <summary>
/// Transforms a point from the world (tile) space, to screen (pixel) space.
/// </summary>
public static ScreenCoordinates WorldToScreen(LocalCoordinates point)
{
return new ScreenCoordinates(((point.Position - Window.Camera.Position) * Window.Camera.PixelsPerMeter + Window.Viewport.Size / 2), point.MapID);
}
public static Vector2 WorldToScreen(Vector2 point)
{
var center = WorldCenter;
return (point - center) * TileSize + ScreenViewportSize / 2;
var center = Window.Camera.Position;
return (point - center) * Window.Camera.PixelsPerMeter + Window.Viewport.Size / 2;
}
/// <summary>
@@ -458,7 +404,6 @@ namespace SS14.Client.Graphics
/// </summary>
public static Box2 WorldToScreen(Box2 rect)
{
var center = WorldCenter;
var topLeft = new Vector2(rect.Left, rect.Top);
var bottomRight = new Vector2(rect.Right, rect.Bottom);
return new Box2(
@@ -486,9 +431,11 @@ namespace SS14.Client.Graphics
/// <summary>
/// Transforms a point from the screen (pixel) space, to world (tile) space.
/// </summary>
public static Vector2 ScreenToWorld(Vector2i point)
public static LocalCoordinates ScreenToCoordinates(ScreenCoordinates point)
{
return ((Vector2)point - ScreenViewportSize / 2) / TileSize + WorldCenter;
var pos = (point.Position - Window.Viewport.Size / 2) / Window.Camera.PixelsPerMeter + Window.Camera.Position;
var grid = IoCManager.Resolve<IMapManager>().GetMap(point.MapID).FindGridAt(pos);
return new LocalCoordinates(pos, grid);
}
/// <summary>
@@ -496,13 +443,23 @@ namespace SS14.Client.Graphics
/// </summary>
public static Box2 ScreenToWorld(Box2i rect)
{
var center = WorldCenter;
var center = Window.Camera.Position;
return new Box2(
((Vector2)rect.TopLeft - ScreenViewportSize / 2) / TileSize + center,
((Vector2)rect.BottomRight - ScreenViewportSize / 2) / TileSize + center
((Vector2)rect.TopLeft - Window.Viewport.Size / 2) / Window.Camera.PixelsPerMeter + center,
((Vector2)rect.BottomRight - Window.Viewport.Size / 2) / Window.Camera.PixelsPerMeter + center
);
}
/// <summary>
/// Transforms a point from the screen (pixel) space, to world (tile) space.
/// </summary>
public static LocalCoordinates ScreenToWorld(Vector2i point, int argMap)
{
var pos = ((Vector2)point - Window.Viewport.Size / 2) / Window.Camera.PixelsPerMeter + Window.Camera.Position;
var grid = IoCManager.Resolve<IMapManager>().GetMap(argMap).FindGridAt(pos);
return new LocalCoordinates(pos, grid);
}
/// <summary>
/// Scales a vector from pixel coordinates to tile coordinates.
/// </summary>
@@ -510,35 +467,44 @@ namespace SS14.Client.Graphics
/// <returns></returns>
public static Vector2 PixelToTile(Vector2 vec)
{
return vec / TileSize;
return vec / Window.Camera.PixelsPerMeter;
}
/// <summary>
/// Scales a rectangle from pixel coordinates to tile coordinates.
/// </summary>
/// <param name="size"></param>
/// <returns></returns>
public static Box2 PixelToTile(Box2 rect)
#endregion Client Window Data
}
public class InputEvents
{
public InputEvents(RenderWindow window)
{
return new Box2(
rect.Left / TileSize,
rect.Top / TileSize,
rect.Right / TileSize,
rect.Bottom / TileSize
);
// if dummy don't attach events
if (window == null)
return;
RenderWindow _window = window;
_window.KeyPressed += (sender, args) => KeyPressed?.Invoke(sender, args);
_window.KeyReleased += (sender, args) => KeyReleased?.Invoke(sender, args);
_window.MouseButtonPressed += (sender, args) => MouseButtonPressed?.Invoke(sender, args);
_window.MouseButtonReleased += (sender, args) => MouseButtonReleased?.Invoke(sender, args);
_window.MouseMoved += (sender, args) => MouseMoved?.Invoke(sender, args);
_window.MouseWheelMoved += (sender, args) => MouseWheelMoved?.Invoke(sender, args);
_window.MouseEntered += (sender, args) => MouseEntered?.Invoke(sender, args);
_window.MouseLeft += (sender, args) => MouseLeft?.Invoke(sender, args);
_window.TextEntered += (sender, args) => TextEntered?.Invoke(sender, args);
}
/// <summary>
/// Takes a point in world (tile) coordinates, and rounds it to the nearest pixel.
/// </summary>
public static Vector2 GetNearestPixel(Vector2 worldPoint)
{
return new Vector2(
(float)Math.Round(worldPoint.X * TileSize) / TileSize,
(float)Math.Round(worldPoint.Y * TileSize) / TileSize
);
}
#endregion
public event EventHandler<KeyEventArgs> KeyPressed;
public event EventHandler<KeyEventArgs> KeyReleased;
public event EventHandler<MouseButtonEventArgs> MouseButtonPressed;
public event EventHandler<MouseButtonEventArgs> MouseButtonReleased;
public event EventHandler<MouseMoveEventArgs> MouseMoved;
public event EventHandler<MouseWheelEventArgs> MouseWheelMoved;
public event EventHandler<EventArgs> MouseEntered;
public event EventHandler<EventArgs> MouseLeft;
public event EventHandler<TextEventArgs> TextEntered;
}
}

View File

@@ -20,8 +20,7 @@ namespace SS14.Client.Graphics.Collection
/// </para>
/// </remarks>
/// <typeparam name="T">Type of data to store.</typeparam>
public abstract class BaseCollection<T>
: IEnumerable<T>
public abstract class BaseCollection<T> : IEnumerable<T>
{
#region Variables.
private SortedList<string, T> _items = null; // Container for the collection data.

View File

@@ -1,41 +1,9 @@
using System;
namespace SS14.Client.Graphics
{
/// <summary>
/// Enumeration for primitive drawing style.
/// </summary>
public enum PrimitiveStyle
{
/// <summary>A series of individual points.</summary>
PointList = 0,
/// <summary>A series of individual lines.</summary>
LineList = 1,
/// <summary>A series of lines connected in a strip.</summary>
LineStrip = 2,
/// <summary>A series of individual triangles.</summary>
TriangleList = 3,
/// <summary>A series of triangles connected in a strip.</summary>
TriangleStrip = 4,
/// <summary>A series of triangles connected in a fan.</summary>
TriangleFan = 5
}
/// <summary>
/// Enumeration for culling modes.
/// </summary>
public enum CullingMode
{
/// <summary>Cull counter clockwise.</summary>
CounterClockwise = 0,
/// <summary>Cull clockwise.</summary>
Clockwise = 1,
/// <summary>No culling.</summary>
None = 2,
}
/// <summary>
/// Enumerator for vertex field contexts.
/// Used to define in which context the field will be used.
/// </summary>
@@ -206,204 +174,10 @@ namespace SS14.Client.Graphics
BufferRGB565 = 46
}
/// <summary>
/// Enumeration containing image operation flags.
/// </summary>
public enum ImageOperations
{
/// <summary>Disable the image layer.</summary>
Disable = 0,
/// <summary>Select the previous first operation argument.</summary>
SelectArgument1 = 1,
/// <summary>Select the previous second operation argument.</summary>
SelectArgument2 = 2,
/// <summary>Modulate the layer.</summary>
Modulate = 3,
/// <summary>Modulate the layer times 2.</summary>
Modulatex2 = 4,
/// <summary>Modulate the layer times 4.</summary>
Modulatex4 = 5,
/// <summary>Additive blending.</summary>
Additive = 6,
/// <summary>Additive blending with sign.</summary>
AdditiveSigned = 7,
/// <summary>Additive blending with sign times 2.</summary>
AdditiveSignedx2 = 8,
/// <summary>Additive blending with interpolation.</summary>
AdditiveSmooth = 9,
/// <summary>Subtract blending.</summary>
Subtract = 10,
/// <summary>Blend diffuse and alpha.</summary>
BlendDiffuseAlpha = 11,
/// <summary>Blend texture alpha.</summary>
BlendTextureAlpha = 12,
/// <summary>Blend factor alpha.</summary>
BlendFactorAlpha = 13,
/// <summary>Blend pre-multipled alpha.</summary>
BlendPreMultipliedTextureAlpha = 14,
/// <summary>Blend current alpha.</summary>
BlendCurrentAlpha = 15,
/// <summary>Pre modulate.</summary>
PreModulate = 16,
/// <summary>Modulate alpha, additive blending.</summary>
ModulateAlphaAddColor = 17,
/// <summary>Modulate color, additive alpha.</summary>
ModulateColorAddAlpha = 18,
/// <summary>Modulate inverse alpha, additive color.</summary>
ModulateInverseAlphaAddColor = 19,
/// <summary>Modulate inverse color, additive alpha.</summary>
ModulateInverseColorAddAlpha = 20,
/// <summary>Bump mapping using an environment map.</summary>
BumpEnvironmentMap = 21,
/// <summary>Bump mapping using an environment map with luminance.</summary>
BumpEnvironmentMapLuminance = 22,
/// <summary>Bump mapping using Dot3 product.</summary>
BumpDotProduct = 23,
/// <summary>Multiply and Add.</summary>
MultiplyAdd = 24,
/// <summary>Linear interpolation.</summary>
Lerp = 25
}
/// <summary>
/// Enumeration containing arguments for image operations.
/// </summary>
public enum ImageOperationArguments
{
/// <summary>Get the current setting.</summary>
Current = 0,
/// <summary>Diffuse color from the vertex.</summary>
Diffuse = 1,
/// <summary>Texture color from the layer.</summary>
Texture = 2,
/// <summary>Texture factor.</summary>
TextureFactor = 3,
/// <summary>Temporary register.</summary>
Temp = 4,
/// <summary>Constant value.</summary>
Constant = 5,
/// <summary>Copy alpha values to color values.</summary>
AlphaReplicate = 6,
/// <summary>One's complement.</summary>
Complement = 7,
/// <summary>Specular value from the vertex.</summary>
Specular = 8
}
/// <summary>
/// Enumeration containing filter types for images.
/// </summary>
public enum ImageFilters
{
/// <summary>No filtering.</summary>
None = 0,
/// <summary>Point filtering.</summary>
Point = 1,
/// <summary>Bilinear filtering.</summary>
Bilinear = 2,
/// <summary>Anisotropic filtering.</summary>
Anisotropic = 3,
/// <summary>Pyramidal quadratic filtering.</summary>
PyramidalQuadratic = 4,
/// <summary>Gaussian quadratic filtering.</summary>
GaussianQuadratic = 5
}
/// <summary>
/// Enumeration containing the types of images we can create.
/// </summary>
/// <remarks>The RenderTarget value is used internally by Gorgon and should not be used when creating an image, however it can be used when validating an image format with
/// <see cref="M:GorgonLibrary.Driver.ValidImageFormat">Driver.ValidImageFormat</see> or <see cref="M:GorgonLibrary.Graphics.Image.ValidateFormat">Image.ValidateFormat</see>.
/// <para>The Dynamic value will ensure the image is dynamic whether the <see cref="P:GorgonLibrary.Driver.SupportDynamicTextures">Driver.SupportDynamicTextures</see> property is TRUE or FALSE.
/// If the hardware supports dynamic textures then Gorgon will make use of it, otherwise the image will be a normal image placed in the default pool.</para>
/// </remarks>
public enum ImageType
{
/// <summary>A normal static image.</summary>
Normal = 0,
/// <summary>Dynamic image.</summary>
Dynamic = 1,
/// <summary>
/// A render target image.
/// </summary>
RenderTarget = 0x7FFF
}
/// <summary>
/// Enumeration containing the types of image addressing modes.
/// </summary>
public enum ImageAddressing
{
/// <summary>Make image wrap around.</summary>
Wrapping = 0,
/// <summary>Make image mirror.</summary>
Mirror = 1,
/// <summary>Make image mirror only once.</summary>
MirrorOnce = 2,
/// <summary>Make image clamp to values..</summary>
Clamp = 3,
/// <summary>Display a border.</summary>
Border = 4
}
/// <summary>
/// Enumeration containing image file formats.
/// </summary>
public enum ImageFileFormat
{
/// <summary>
/// Windows bitmap format.
/// </summary>
BMP = 0,
/// <summary>
/// Joint photographers expert group.
/// </summary>
JPEG = 1,
/// <summary>
/// Portable network graphics.
/// </summary>
PNG = 2,
/// <summary>
/// Truevision Targa.
/// </summary>
TGA = 3,
/// <summary>
/// Direct X surface.
/// </summary>
DDS = 4,
/// <summary>
/// Device independant bitmap.
/// </summary>
DIB = 5,
/// <summary>
/// Portable pixmap.
/// </summary>
PPM = 6,
/// <summary>
/// Portable floating point.
/// </summary>
PFM = 7
}
/// <summary>
/// Enumeration containing locations of the vertices.
/// </summary>
public enum VertexLocations
{
/// <summary>Upper left corner.</summary>
UpperLeft = 0,
/// <summary>Lower left corner.</summary>
LowerLeft = 3,
/// <summary>Upper right corner.</summary>
UpperRight = 1,
/// <summary>Lower right corner.</summary>
LowerRight = 2
}
/// <summary>
/// Enumeration containing blending modes.
/// </summary>
[Flags()]
[Flags]
public enum BlendingModes
{
/// <summary>No blending.</summary>
@@ -423,103 +197,5 @@ namespace SS14.Client.Graphics
/// <summary>Invert.</summary>
Inverted = 64
}
/// <summary>
/// Enumeration for smoothing operations.
/// </summary>
public enum Smoothing
{
/// <summary>No smoothing.</summary>
None = 0,
/// <summary>Smooth both zoomed in and out.</summary>
Smooth = 1,
/// <summary>Smooth only zoomed in.</summary>
MagnificationSmooth = 2,
/// <summary>Smooth only zoomed out.</summary>
MinificationSmooth = 3
}
/// <summary>
/// Enumeration for aligment.
/// </summary>
public enum Alignment
{
/// <summary>Left aligned.</summary>
Left = 0,
/// <summary>Centered.</summary>
Center = 1,
/// <summary>Right aligned.</summary>
Right = 2,
/// <summary>Upper left corner.</summary>
UpperLeft = 3,
/// <summary>Upper centered.</summary>
UpperCenter = 4,
/// <summary>Upper right.</summary>
UpperRight = 5,
/// <summary>Lower left.</summary>
LowerLeft = 6,
/// <summary>Lower centered.</summary>
LowerCenter = 7,
/// <summary>Lower right.</summary>
LowerRight = 8
}
/// <summary>
/// Enumeration for stencil buffer operations.
/// </summary>
public enum StencilOperations
{
/// <summary>Write zero to the buffer.</summary>
Zero = 0,
/// <summary>Decrement buffer value.</summary>
Decrement = 1,
/// <summary>Increment buffer value.</summary>
Increment = 2,
/// <summary>Invert buffer value.</summary>
Invert = 3,
/// <summary>Decrement buffer value, clamp to minimum.</summary>
DecrementSaturate = 4,
/// <summary>Increment buffer value, clamp to maximum.</summary>
IncrementSaturate = 5,
/// <summary>Keep the current value.</summary>
Keep = 6,
/// <summary>Replace the value with the reference value.</summary>
Replace = 7
}
/// <summary>
/// Enumeration for alpha blending operations.
/// </summary>
public enum AlphaBlendOperation
{
/// <summary>Blend factor of 0,0,0.</summary>
Zero = 0,
/// <summary>Blend factor is 1,1,1.</summary>
One = 1,
/// <summary>Blend factor is Rs', Gs', Bs', As.</summary>
SourceColor = 2,
/// <summary>Blend factor is As', As', As', As.</summary>
SourceAlpha = 3,
/// <summary>Blend factor is 1-Rs', 1-Gs', 1-Bs', 1-As.</summary>
InverseSourceColor = 4,
/// <summary>Blend factor is 1-As', 1-As', 1-As', 1-As.</summary>
InverseSourceAlpha = 5,
/// <summary>Blend factor is Rd', Gd', Bd', Ad.</summary>
DestinationColor = 6,
/// <summary>Blend factor is Ad', Ad', Ad', Ad.</summary>
DestinationAlpha = 7,
/// <summary>Blend factor is 1-Rd', 1-Gd', 1-Bd', 1-Ad.</summary>
InverseDestinationColor = 8,
/// <summary>Blend factor is 1-Ad', 1-Ad', 1-Ad', 1-Ad.</summary>
InverseDestinationAlpha = 9,
/// <summary>Blend factor is f,f,f,1 where f = min(A, 1-Ad)</summary>
SourceAlphaSaturation = 10,
/// <summary>Source blend factor is 1-As', 1-As', 1-As', 1-As and destination is As', As', As', As. Overrides the blend destination, and is only valid if the SourceBlend state is true.</summary>
BothInverseSourceAlpha = 11,
/// <summary>Constant color blend factor. Only valid if the driver SupportBlendingFactor is true.</summary>
BlendFactor = 12,
/// <summary>Inverted constant color blend factor. Only valid if the driver SupportBlendingFactor capability is true.</summary>
InverseBlendFactor = 13
}
}

View File

@@ -1,7 +0,0 @@
namespace SS14.Client.Graphics.Interface
{
public interface ICluwneDrawable
{
void Draw();
}
}

View File

@@ -0,0 +1,21 @@
using OpenTK;
using OpenTK.Graphics;
using SS14.Shared;
using SS14.Shared.Map;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.Graphics.Lighting
{
public interface ILight
{
int Radius { get; set; }
Color4 Color { get; set; }
Vector4 ColorVec { get; }
LocalCoordinates Coordinates { get; set; }
LightState LightState { get; set; }
ILightArea LightArea { get; }
LightMode LightMode { get; set; }
void Update(float frametime);
void SetMask(SFML.Graphics.Sprite _mask);
}
}

View File

@@ -0,0 +1,16 @@
using SS14.Shared.Maths;
namespace SS14.Client.Graphics.Lighting
{
public interface ILightArea
{
Vector2 LightPosition { get; set; }
Vector2 LightAreaSize { get; }
bool Calculated { get; set; }
Vector2 ToRelativePosition(Vector2 worldPosition);
void BeginDrawingShadowCasters();
void EndDrawingShadowCasters();
void SetMask(SFML.Graphics.Sprite mask);
}
}

View File

@@ -1,21 +1,16 @@
using OpenTK;
using SFML.Graphics;
using SFML.System;
using SS14.Shared;
using SS14.Shared.IoC;
namespace SS14.Client.Interfaces.Lighting
namespace SS14.Client.Graphics.Lighting
{
public interface ILightManager
{
SFML.Graphics.Sprite LightMask { get; set; }
ILight CreateLight();
void AddLight(ILight light);
void RemoveLight(ILight light);
ILight[] lightsInRadius(Vector2 point, float radius);
void RecalculateLights();
void RecalculateLightsInView(Vector2 point);
void RecalculateLightsInView(Box2 rect);
ILight[] LightsIntersectingPoint(Vector2 point);
ILight[] LightsIntersectingRect(Box2 rect);
ILight[] GetLights();
void SetLightMode(LightModeClass? mode, ILight light);

View File

@@ -0,0 +1,97 @@
using OpenTK;
using OpenTK.Graphics;
using SS14.Shared;
using SS14.Shared.IoC;
using SS14.Shared.Map;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.Graphics.Lighting
{
public class Light : ILight
{
private LightState lightState = LightState.On;
private Vector2 position;
private int MapID;
private int GridID;
private int radius;
public Light()
{
Radius = 256;
}
public LocalCoordinates Coordinates
{
get => new LocalCoordinates(position, GridID, MapID);
set
{
if (position != value.Position || MapID != value.MapID || GridID != value.GridID)
{
position = value.Position;
MapID = value.MapID;
GridID = value.GridID;
LightArea.Calculated = false;
}
}
}
public Color4 Color { get; set; }
public Vector4 ColorVec => new Vector4(Color.R, Color.G, Color.B, Color.A);
public int Radius
{
get => radius;
set
{
if (radius != value)
{
radius = value;
LightArea = new LightArea(RadiusToShadowMapSize(radius), IoCManager.Resolve<ILightManager>().LightMask);
}
}
}
public ILightArea LightArea { get; private set; }
public LightState LightState
{
get => lightState;
set
{
if (lightState != value)
{
lightState = value;
LightArea.Calculated = false;
}
}
}
public LightMode LightMode { get; set; }
public void SetMask(SFML.Graphics.Sprite mask)
{
LightArea.SetMask(mask);
}
public void Update(float frametime)
{
LightMode?.Update(this);
}
public static ShadowmapSize RadiusToShadowMapSize(int Radius)
{
if (Radius <= 128)
return ShadowmapSize.Size128;
if (Radius <= 256)
return ShadowmapSize.Size256;
if (Radius <= 512)
return ShadowmapSize.Size512;
return ShadowmapSize.Size1024;
}
}
}

View File

@@ -0,0 +1,81 @@
using OpenTK;
using SFML.Graphics;
using SS14.Client.Graphics.Render;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.Graphics.Lighting
{
public class LightArea : ILightArea
{
public LightArea(ShadowmapSize shadowmapSize, SFML.Graphics.Sprite mask)
{
var baseSize = 2 << (int) shadowmapSize;
LightAreaSize = new Vector2(baseSize, baseSize);
RenderTarget = new RenderImage("LightArea" + shadowmapSize, (uint) baseSize, (uint) baseSize);
Mask = mask;
}
public RenderImage RenderTarget { get; }
public SFML.Graphics.Sprite Mask { get; set; }
public bool MaskFlipX { get; set; }
public bool MaskFlipY { get; set; }
public bool Rot90 { get; set; }
public Vector4 MaskProps
{
get
{
if (Rot90 && MaskFlipX && MaskFlipY)
return maskPropsVec(false, false, false);
if (Rot90 && MaskFlipX && !MaskFlipY)
return maskPropsVec(true, false, true);
if (Rot90 && !MaskFlipX && MaskFlipY)
return maskPropsVec(true, true, false);
if (Rot90 && !MaskFlipX && !MaskFlipY)
return maskPropsVec(true, false, false);
if (!Rot90 && MaskFlipX && MaskFlipY)
return maskPropsVec(false, true, true);
if (!Rot90 && MaskFlipX && !MaskFlipY)
return maskPropsVec(false, true, false);
if (!Rot90 && !MaskFlipX && MaskFlipY)
return maskPropsVec(false, false, true);
return maskPropsVec(false, false, false);
}
}
/// <summary>
/// World position coordinates of the light's center
/// </summary>
public Vector2 LightPosition { get; set; }
public Vector2 LightAreaSize { get; set; }
public bool Calculated { get; set; }
public Vector2 ToRelativePosition(Vector2 worldPosition)
{
return worldPosition - (CluwneLib.WorldToScreen(LightPosition) - LightAreaSize * 0.5f);
}
public void BeginDrawingShadowCasters()
{
RenderTarget.BeginDrawing();
RenderTarget.Clear(new Color(0, 0, 0, 0));
}
public void EndDrawingShadowCasters()
{
RenderTarget.EndDrawing();
}
public void SetMask(SFML.Graphics.Sprite mask)
{
Mask = mask;
}
private Vector4 maskPropsVec(bool rot, bool flipx, bool flipy)
{
return new Vector4(rot ? 1 : 0, flipx ? 1 : 0, flipy ? 1 : 0, 0);
}
}
}

View File

@@ -1,31 +1,27 @@
using OpenTK;
using SFML.Graphics;
using SFML.System;
using SS14.Client.Interfaces.Lighting;
using SS14.Shared;
using SS14.Shared.Maths;
using SS14.Shared.IoC;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using OpenTK;
using SS14.Shared;
using SS14.Shared.Maths;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.Lighting
namespace SS14.Client.Graphics.Lighting
{
public class LightManager : ILightManager
{
private readonly List<Type> LightModes = new List<Type>();
private readonly List<ILight> _lights = new List<ILight>();
private readonly List<Type> LightModes = new List<Type>();
public LightManager()
{
List<Assembly> assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
LightModes =
assemblies.SelectMany(t => t.GetTypes()).Where(
p => typeof (LightMode).IsAssignableFrom(p) && !p.IsInterface).ToList();
p => typeof(LightMode).IsAssignableFrom(p) && !p.IsInterface).ToList();
}
#region ILightManager Members
public SFML.Graphics.Sprite LightMask { get; set; }
public void SetLightMode(LightModeClass? mode, ILight light)
{
@@ -39,7 +35,7 @@ namespace SS14.Client.Lighting
return;
}
foreach (Type t in LightModes)
foreach (var t in LightModes)
{
var temp = (LightMode) Activator.CreateInstance(t);
if (temp.LightModeClass == mode.Value)
@@ -73,11 +69,6 @@ namespace SS14.Client.Lighting
return _lights.ToArray();
}
public ILight[] lightsInRadius(Vector2 point, float radius)
{
return _lights.FindAll(l => Math.Abs((l.Position - point).LengthSquared) <= radius * radius).ToArray();
}
public ILight[] LightsIntersectingRect(Box2 rect)
{
return _lights
@@ -85,13 +76,6 @@ namespace SS14.Client.Lighting
.ToArray();
}
public ILight[] LightsIntersectingPoint(Vector2 point)
{
return _lights
.FindAll(l => Box2.FromDimensions(l.LightArea.LightPosition - l.LightArea.LightAreaSize / 2, l.LightArea.LightAreaSize).Contains(point))
.ToArray();
}
public ILight CreateLight()
{
return new Light();
@@ -99,16 +83,7 @@ namespace SS14.Client.Lighting
public void RecalculateLights()
{
foreach (ILight l in _lights)
{
l.LightArea.Calculated = false;
}
}
public void RecalculateLightsInView(Vector2 point)
{
ILight[] lights = LightsIntersectingPoint(point);
foreach (ILight l in lights)
foreach (var l in _lights)
{
l.LightArea.Calculated = false;
}
@@ -116,13 +91,32 @@ namespace SS14.Client.Lighting
public void RecalculateLightsInView(Box2 rect)
{
ILight[] lights = LightsIntersectingRect(rect);
foreach (ILight l in lights)
var lights = LightsIntersectingRect(rect);
foreach (var l in lights)
{
l.LightArea.Calculated = false;
}
}
#endregion
public ILight[] lightsInRadius(Vector2 point, float radius)
{
return _lights.FindAll(l => Math.Abs((l.Coordinates.Position - point).LengthSquared) <= radius * radius).ToArray();
}
public ILight[] LightsIntersectingPoint(Vector2 point)
{
return _lights
.FindAll(l => Box2.FromDimensions(l.LightArea.LightPosition - l.LightArea.LightAreaSize / 2, l.LightArea.LightAreaSize).Contains(point))
.ToArray();
}
public void RecalculateLightsInView(Vector2 point)
{
var lights = LightsIntersectingPoint(point);
foreach (var l in lights)
{
l.LightArea.Calculated = false;
}
}
}
}

View File

@@ -0,0 +1,12 @@
using SS14.Shared;
namespace SS14.Client.Graphics.Lighting
{
public interface LightMode
{
LightModeClass LightModeClass { get; }
void OnAdd(ILight owner);
void OnRemove(ILight owner);
void Update(ILight owner);
}
}

View File

@@ -1,21 +1,13 @@
using OpenTK;
using System;
using OpenTK;
using SFML.Graphics;
using SFML.System;
using SS14.Client.Graphics;
using SS14.Client.Graphics.Render;
using SS14.Client.Graphics.Shader;
using SS14.Client.Interfaces.Resource;
using SS14.Shared.Maths;
using SS14.Shared.Utility;
using System;
using Color = SFML.Graphics.Color;
namespace SS14.Client.Lighting
namespace SS14.Client.Graphics.Lighting
{
public class ShadowMapResolver : IDisposable
{
private readonly IResourceCache _resourceCache;
private readonly int baseSize;
private readonly int reductionChainCount;
@@ -25,29 +17,38 @@ namespace SS14.Client.Lighting
private RenderImage distancesRT;
private RenderImage distortRT;
private RenderImage processedShadowsRT;
private RenderImage shadowMap;
private RenderImage shadowsRT;
private TechniqueList reductionEffectTechnique;
private RenderImage[] reductionRT;
private TechniqueList resolveShadowsEffectTechnique;
private TechniqueList reductionEffectTechnique;
private RenderImage shadowMap;
private RenderImage shadowsRT;
public ShadowMapResolver(ShadowmapSize maxShadowmapSize, ShadowmapSize maxDepthBufferSize,
IResourceCache resourceCache)
public ShadowMapResolver(ShadowmapSize maxShadowmapSize, ShadowmapSize maxDepthBufferSize)
{
_resourceCache = resourceCache;
reductionChainCount = (int) maxShadowmapSize;
baseSize = 2 << reductionChainCount;
depthBufferSize = 2 << (int) maxDepthBufferSize;
}
public void LoadContent()
public void Dispose()
{
reductionEffectTechnique = _resourceCache.GetTechnique("reductionEffect");
resolveShadowsEffectTechnique = _resourceCache.GetTechnique("resolveShadowsEffect");
distancesRT.Dispose();
distortRT.Dispose();
processedShadowsRT.Dispose();
foreach (var rt in reductionRT)
{
rt.Dispose();
}
shadowMap.Dispose();
shadowsRT.Dispose();
}
public void LoadContent(TechniqueList reduction, TechniqueList resolve)
{
reductionEffectTechnique = reduction;
resolveShadowsEffectTechnique = resolve;
//// BUFFER TYPES ARE VERY IMPORTANT HERE AND IT WILL BREAK IF YOU CHANGE THEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! HONK HONK
//these work fine
@@ -57,23 +58,23 @@ namespace SS14.Client.Lighting
//these need the buffer format
shadowMap = new RenderImage("shadowMap" + baseSize, 2, baseSize, ImageBufferFormats.BufferGR1616F);
reductionRT = new RenderImage[reductionChainCount];
for (int i = 0; i < reductionChainCount; i++)
for (var i = 0; i < reductionChainCount; i++)
{
reductionRT[i] = new RenderImage("reductionRT" + i + baseSize, 2 << i, baseSize,
ImageBufferFormats.BufferGR1616F);
ImageBufferFormats.BufferGR1616F);
}
shadowsRT = new RenderImage("shadowsRT" + baseSize, baseSize, baseSize, ImageBufferFormats.BufferRGB888A8);
processedShadowsRT = new RenderImage("processedShadowsRT" + baseSize, baseSize, baseSize,
ImageBufferFormats.BufferRGB888A8);
ImageBufferFormats.BufferRGB888A8);
}
public void ResolveShadows(LightArea Area, bool attenuateShadows, Texture mask = null)
{
RenderImage Result = Area.RenderTarget;
Texture MaskTexture = mask == null ? Area.Mask.Texture : mask;
Vector4 MaskProps = Vector4.Zero;
Vector4 diffuseColor = Vector4.One;
var Result = Area.RenderTarget;
var MaskTexture = mask == null ? Area.Mask.Texture : mask;
var MaskProps = Vector4.Zero;
var diffuseColor = Vector4.One;
ExecuteTechnique(Area.RenderTarget, distancesRT, "ComputeDistances");
ExecuteTechnique(distancesRT, distortRT, "Distort");
@@ -81,12 +82,12 @@ namespace SS14.Client.Lighting
ApplyHorizontalReduction(distortRT, shadowMap);
//only DrawShadows needs these vars
resolveShadowsEffectTechnique["DrawShadows"].SetParameter("AttenuateShadows", attenuateShadows ? 0 : 1);
resolveShadowsEffectTechnique["DrawShadows"].SetParameter("MaskProps", MaskProps);
resolveShadowsEffectTechnique["DrawShadows"].SetParameter("DiffuseColor", diffuseColor);
resolveShadowsEffectTechnique["DrawShadows"].SetUniform("AttenuateShadows", attenuateShadows ? 0 : 1);
resolveShadowsEffectTechnique["DrawShadows"].SetUniform("MaskProps", MaskProps);
resolveShadowsEffectTechnique["DrawShadows"].SetUniform("DiffuseColor", diffuseColor);
var maskSize = MaskTexture.Size;
RenderImage MaskTarget = new RenderImage("MaskTarget", maskSize.X, maskSize.Y);
var MaskTarget = new RenderImage("MaskTarget", maskSize.X, maskSize.Y);
ExecuteTechnique(MaskTarget, Result, "DrawShadows", shadowMap);
resolveShadowsEffectTechnique["DrawShadows"].ResetCurrentShader();
@@ -113,13 +114,12 @@ namespace SS14.Client.Lighting
destinationTarget.BeginDrawing();
destinationTarget.Clear(Color.White);
resolveShadowsEffectTechnique[techniqueName].setAsCurrentShader() ;
resolveShadowsEffectTechnique[techniqueName].setAsCurrentShader();
resolveShadowsEffectTechnique[techniqueName].SetParameter("renderTargetSize", renderTargetSize.Convert());
if (source != null)
resolveShadowsEffectTechnique[techniqueName].SetParameter("inputSampler", source);
resolveShadowsEffectTechnique[techniqueName].SetUniform("renderTargetSize", renderTargetSize);
resolveShadowsEffectTechnique[techniqueName].SetUniform("inputSampler", source);
if (shadowMap != null)
resolveShadowsEffectTechnique[techniqueName].SetParameter("shadowMapSampler", shadowMap);
resolveShadowsEffectTechnique[techniqueName].SetUniform("shadowMapSampler", shadowMap);
// Blit and use normal sampler instead of doing that weird InputTexture bullshit
// Use destination width/height otherwise you can see some cropping result erroneously.
@@ -128,13 +128,11 @@ namespace SS14.Client.Lighting
destinationTarget.EndDrawing();
}
private void ApplyHorizontalReduction(RenderImage source, RenderImage destination)
{
int step = reductionChainCount - 1;
RenderImage src = source;
RenderImage HorizontalReduction= reductionRT[step];
var step = reductionChainCount - 1;
var src = source;
var HorizontalReduction = reductionRT[step];
reductionEffectTechnique["HorizontalReduction"].setAsCurrentShader();
// Disabled GLTexture stuff for now just to get the pipeline working.
// The only side effect is that floating point precision will be low,
@@ -145,19 +143,18 @@ namespace SS14.Client.Lighting
HorizontalReduction.BeginDrawing();
HorizontalReduction.Clear(Color.White);
reductionEffectTechnique["HorizontalReduction"].SetParameter("TextureDimensions",1.0f/src.Width);
reductionEffectTechnique["HorizontalReduction"].SetUniform("TextureDimensions", 1.0f / src.Width);
// Sourcetexture not needed... just blit!
src.Blit(0, 0, HorizontalReduction.Width, HorizontalReduction.Height, BlitterSizeMode.Scale); // draw SRC to HR
//fix
//fix
HorizontalReduction.EndDrawing();
src = HorizontalReduction; // hr becomes new src
step--;
}
CluwneLib.ResetShader();
//copy to destination
destination.BeginDrawing();
@@ -167,21 +164,5 @@ namespace SS14.Client.Lighting
destination.EndDrawing();
CluwneLib.ResetRenderTarget();
}
public void Dispose()
{
distancesRT.Dispose();
distortRT.Dispose();
processedShadowsRT.Dispose();
foreach(var rt in reductionRT)
{
rt.Dispose();
}
shadowMap.Dispose();
shadowsRT.Dispose();
}
}
}

View File

@@ -1,4 +1,4 @@
namespace SS14.Client.Lighting
namespace SS14.Client.Graphics.Lighting
{
public enum ShadowmapSize
{

View File

@@ -1,36 +1,73 @@
using SFML.Graphics;
using SFML.Window;
using SFML.Graphics;
using System;
using SFML.Window;
using SS14.Client.Graphics.Settings;
using SS14.Client.Graphics.View;
namespace SS14.Client.Graphics.Render
{
public class CluwneWindow : RenderWindow
public class CluwneWindow
{
public CluwneWindow(VideoMode mode, string title) : base(mode, title)
private readonly RenderWindow _window;
private readonly VideoSettings _settings;
internal CluwneWindow(RenderWindow window, VideoSettings settings)
{
_window = window;
_settings = settings;
Graphics = new GraphicsContext(_window);
Camera = new Camera(_window);
Viewport = new Viewport(0,0,_window.Size.X, _window.Size.Y);
CluwneLib.Input = new InputEvents(_window);
_window.Closed += (sender, args) => Closed?.Invoke(sender, args);
_window.Resized += (sender, args) =>
{
Viewport.Width = _window.Size.X;
Viewport.Height = _window.Size.Y;
Resized?.Invoke(sender, args);
};
}
public CluwneWindow(VideoMode mode, string title, Styles style) : base(mode, title, style)
public Viewport Viewport { get; set; }
public RenderTarget Screen => _window;
/// <summary>
/// Graphics context of the window.
/// </summary>
public GraphicsContext Graphics { get; }
public Camera Camera { get; }
public void SetMouseCursorVisible(bool visible)
{
_window.SetMouseCursorVisible(visible);
}
public CluwneWindow(VideoMode mode, string title, Styles style, ContextSettings settings) : base(mode, title, style, settings)
public void DispatchEvents()
{
_window.DispatchEvents();
}
public CluwneWindow(IntPtr handle) : base(handle)
// close the window
public void Close()
{
// prevents null issues
CluwneLib.Input = new InputEvents(null);
_window.Close();
}
public CluwneWindow(IntPtr handle, ContextSettings settings) : base(handle, settings)
[Obsolete("Use the new API.")]
public static implicit operator RenderWindow(CluwneWindow window)
{
return window._window;
}
public Color BackgroundColor
{
get;
set;
}
public event EventHandler<EventArgs> Closed;
public event EventHandler<SizeEventArgs> Resized;
}
}

View File

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML.Graphics;
namespace SS14.Client.Graphics.Render
{
public class GraphicsContext
{
private readonly RenderWindow _window;
internal GraphicsContext(RenderWindow window)
{
_window = window;
}
/// <summary>
/// Clear color
/// </summary>
public Color BackgroundColor { get; set; }
public void SetVerticalSyncEnabled(bool enabled)
{
_window.SetVerticalSyncEnabled(enabled);
}
public void SetFramerateLimit(uint limit)
{
_window.SetFramerateLimit(limit);
}
public void Draw(SFML.Graphics.Sprite sprite)
{
_window.Draw(sprite);
}
public void Display()
{
_window.Display();
}
public void Clear(Color color)
{
_window.Clear(color);
}
}
}

View File

@@ -5,54 +5,51 @@
<ProjectType>Local</ProjectType>
<ProjectGuid>{302B877E-0000-0000-0000-000000000000}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<AssemblyKeyContainerName>
</AssemblyKeyContainerName>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<AssemblyKeyContainerName />
<AssemblyName>SS14.Client.Graphics</AssemblyName>
<DefaultClientScript>JScript</DefaultClientScript>
<DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>
<DefaultTargetSchema>IE50</DefaultTargetSchema>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<OutputType>Library</OutputType>
<AppDesignerFolder>
</AppDesignerFolder>
<AppDesignerFolder />
<RootNamespace>SS14.Client.Graphics</RootNamespace>
<StartArguments>
</StartArguments>
<FileUpgradeFlags>
</FileUpgradeFlags>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<StartArguments />
<FileUpgradeFlags />
<TargetFrameworkProfile />
<ConfigurationOverrideFile />
<AllowedReferenceRelatedFileExtensions>.pdb;.dll.config</AllowedReferenceRelatedFileExtensions>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<FileAlignment>4096</FileAlignment>
<OutputPath>$(SolutionDir)bin\Graphics\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<RemoveIntegerChecks>False</RemoveIntegerChecks>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<DebugSymbols>True</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<Optimize>false</Optimize>
<OutputPath>$(SolutionDir)bin\Graphics\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<RemoveIntegerChecks>False</RemoveIntegerChecks>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE</DefineConstants>
<FileAlignment>4096</FileAlignment>
<DefineConstants>TRACE;RELEASE</DefineConstants>
<Optimize>True</Optimize>
<OutputPath>$(SolutionDir)bin\Graphics\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<RemoveIntegerChecks>False</RemoveIntegerChecks>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<Prefer32Bit>true</Prefer32Bit>
<AllowedReferenceRelatedFileExtensions>.dll.config</AllowedReferenceRelatedFileExtensions>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<DefineConstants>TRACE;DEBUG</DefineConstants>
<DebugSymbols>True</DebugSymbols>
<Optimize>false</Optimize>
<PlatformTarget>x64</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
<DefineConstants>TRACE;RELEASE</DefineConstants>
<Optimize>True</Optimize>
<PlatformTarget>x64</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
<AllowedReferenceRelatedFileExtensions>.dll.config</AllowedReferenceRelatedFileExtensions>
</PropertyGroup>
@@ -63,19 +60,8 @@
<Reference Include="OpenTK, Version=3.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL">
<HintPath>$(SolutionDir)packages\OpenTK.3.0.0-pre\lib\net20\OpenTK.dll</HintPath>
</Reference>
<Reference Include="sfmlnet-graphics-2">
<Name>sfmlnet-graphics-2</Name>
<HintPath>..\Third-Party\sfmlnet-graphics-2.dll</HintPath>
</Reference>
<Reference Include="sfmlnet-system-2">
<Name>sfmlnet-system-2</Name>
<HintPath>..\Third-Party\sfmlnet-system-2.dll</HintPath>
</Reference>
<Reference Include="sfmlnet-window-2">
<Name>sfmlnet-window-2</Name>
<HintPath>..\Third-Party\sfmlnet-window-2.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Drawing" />
</ItemGroup>
<ItemGroup>
<Compile Include="CluwneLib.cs">
@@ -89,6 +75,16 @@
<Compile Include="Enums\GraphicsEnums.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Render\GraphicsContext.cs" />
<Compile Include="Lighting\ILight.cs" />
<Compile Include="Lighting\ILightArea.cs" />
<Compile Include="Lighting\ILightManager.cs" />
<Compile Include="Lighting\LightArea.cs" />
<Compile Include="Lighting\LightManager.cs" />
<Compile Include="Lighting\LightMode.cs" />
<Compile Include="Lighting\Light.cs" />
<Compile Include="Lighting\ShadowMapResolver.cs" />
<Compile Include="Lighting\ShadowmapSize.cs" />
<Compile Include="Shader\TechniqueList.cs" />
<Compile Include="Sprite\AnimationInfo.cs" />
<Compile Include="Sprite\SpriteInfo.cs" />
@@ -96,9 +92,6 @@
<Compile Include="texture\TextureCache.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Interface\ICluwneDrawable.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
@@ -120,9 +113,6 @@
<Compile Include="Sprite\TextSprite.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="VertexData\VertexEnums.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="VertexData\VertexField.cs">
<SubType>Code</SubType>
</Compile>
@@ -133,27 +123,31 @@
<SubType>Code</SubType>
</Compile>
<Compile Include="Settings\VideoSettings.cs" />
<Compile Include="View\Camera.cs" />
<Compile Include="View\Viewport.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Utility\SfmlExt.cs" />
<Compile Include="Utility\SfmlCompatibility.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SFML\src\Graphics\sfml-graphics.csproj">
<Project>{46786269-57b9-48e7-aa4f-8f4d84609fe6}</Project>
<Name>sfml-graphics</Name>
</ProjectReference>
<ProjectReference Include="..\SFML\src\System\sfml-system.csproj">
<Project>{31d24303-f6a9-4d53-bb03-a73edcb3186d}</Project>
<Name>sfml-system</Name>
</ProjectReference>
<ProjectReference Include="..\SFML\src\Window\sfml-window.csproj">
<Project>{d17de83d-a592-461f-8af2-53f9e22e1d0f}</Project>
<Name>sfml-window</Name>
</ProjectReference>
<ProjectReference Include="..\SS14.Shared\SS14.Shared.csproj">
<Project>{0529f740-0000-0000-0000-000000000000}</Project>
<Name>SS14.Shared</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup Condition="'$(TargetOS)' == 'Windows'">
<Content Include="..\Third-Party\extlibs\csfml-graphics-2.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\Third-Party\extlibs\csfml-system-2.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\Third-Party\extlibs\csfml-window-2.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<Content Include="$(SolutionDir)packages\OpenTK.3.0.0-pre\content\OpenTK.dll.config">
@@ -161,6 +155,7 @@
</Content>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>

View File

@@ -1,101 +1,96 @@
using SFML.Window;
using SFML.Window;
namespace SS14.Client.Graphics.Settings
{
public class VideoSettings
{
private Styles WindowStyle;
private ContextSettings OpenGLSettings;
private VideoMode WindowSettings;
private uint RefreshRate;
private ContextSettings _glContextSettings;
private uint _refreshRate;
private VideoMode _videoMode;
private Styles _windowStyle;
public VideoSettings()
{
WindowStyle = Styles.Default; // Titlebar + Resize + Close
WindowSettings = VideoMode.DesktopMode;
_windowStyle = Styles.Default; // Titlebar + Resize + Close
_videoMode = VideoMode.DesktopMode;
OpenGLSettings = new ContextSettings();
RefreshRate = 30;
_glContextSettings = new ContextSettings();
_refreshRate = 30;
}
public VideoSettings(VideoMode mode)
{
_videoMode = mode;
}
/// <summary>
/// Returns a valid Video Mode
/// Returns a valid Video Mode
/// </summary>
/// <returns></returns>
public VideoMode getVideoMode()
public VideoMode GetVideoMode()
{
if (WindowSettings.IsValid())
return WindowSettings;
else
return new VideoMode(800, 600);
//TODO logmanager show that the windowsettings were invalid
if (_videoMode.IsValid())
return _videoMode;
return new VideoMode(800, 600);
}
/// <summary>
/// Returns the current windowStyle
/// Returns the current windowStyle
/// </summary>
/// <returns></returns>
public Styles getWindowStyle()
public Styles GetWindowStyle()
{
return WindowStyle;
return _windowStyle;
}
/// <summary>
/// Sets the Window Size
/// Sets the Window Size
/// </summary>
/// <param name="width"> Width of the window</param>
/// <param name="height">Height of the window </param>
public void SetWindowSize(uint width, uint height)
{
WindowSettings.Height = height;
WindowSettings.Width = width;
_videoMode.Height = height;
_videoMode.Width = width;
}
/// <summary>
/// Activates or deactivates fullscreen
/// Activates or deactivates fullscreen
/// </summary>
/// <param name="active"> true for fullscreen, false for no fullscreen</param>
public void SetFullscreen(bool active)
public void SetFullScreen(bool active)
{
if (active)
{
if (WindowSettings.IsValid())
WindowStyle = Styles.Fullscreen;
if (_videoMode.IsValid())
_windowStyle = Styles.Fullscreen;
else
WindowStyle = Styles.Default;
}
else
WindowStyle = Styles.Default;
// Logmanager Windowsettings are invalid
_windowStyle = Styles.Default;
else
_windowStyle = Styles.Default;
}
/// <summary>
/// Sets the Refresh Rate of the game
/// Sets the Refresh Rate of the game
/// </summary>
/// <param name="rate"> Refresh Rate</param>
public void SetRefreshRate(uint rate)
{
if ((rate >= 30) && (rate <= 144))
RefreshRate = rate;
if (rate >= 30 && rate <= 144)
_refreshRate = rate;
else
RefreshRate = 30;
//Logmanager Rate is either above 144 or below 30
_refreshRate = 30;
//Logmanager Rate is either above 144 or below 30
}
/// <summary>
/// Checks if the VideoSettings are valid and will work on the current PC system
/// Checks if the VideoSettings are valid and will work on the current PC system
/// </summary>
/// <returns>True if not null and settings are valid </returns>
public bool IsValid()
{
if (!WindowStyle.Equals(null) && WindowSettings.IsValid() && !OpenGLSettings.Equals(null))
{
if (!_windowStyle.Equals(null) && _videoMode.IsValid() && !_glContextSettings.Equals(null))
return true;
}
else return false;
return false;
}
}
}

View File

@@ -1,10 +1,15 @@
using OpenTK;
using SFML.System;
using SFML.Graphics.Glsl;
using SS14.Client.Graphics.Render;
using SS14.Client.Graphics.Utility;
using SS14.Shared.Maths;
using SS14.Shared.Utility;
using System.Diagnostics;
using System.IO;
using System.Linq;
using ShaderClass = SFML.Graphics.Shader;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.Graphics.Shader
@@ -18,13 +23,13 @@ namespace SS14.Client.Graphics.Shader
public GLSLShader(string vertexShaderFilename, string fragmentShaderFilename)
: base(vertexShaderFilename, fragmentShaderFilename)
: base(vertexShaderFilename, null, fragmentShaderFilename)
{
}
public GLSLShader(Stream vertexShaderStream, Stream fragmentShaderStream)
: base(vertexShaderStream, fragmentShaderStream)
: base(vertexShaderStream, null, fragmentShaderStream)
{
}
@@ -50,45 +55,59 @@ namespace SS14.Client.Graphics.Shader
}
public void SetParameter(string Parameter, RenderImage Image)
public void SetUniform(string Parameter, RenderImage Image)
{
base.SetParameter(Parameter, Image.Texture);
base.SetUniform(Parameter, Image.Texture);
}
public void SetParameter(string Parameter, Vector3f vec3)
public void SetUniform(string Parameter, Vector2f vec2)
{
base.SetParameter(Parameter, vec3.X, vec3.Y, vec3.Z);
base.SetUniform(Parameter, vec2);
}
public void SetParameter(string Parameter, Vector4 vec4)
public void SetUniform(string Parameter, Vector2 vec2)
{
base.SetParameter(Parameter, vec4.X, vec4.Y, vec4.Z, vec4.W);
base.SetUniform(Parameter, vec2.Convert());
}
public void SetParameter(string Parameter, Vector2f[] vec2array)
public void SetUniform(string Parameter, Vector3f vec3)
{
for (int i = 0; i < vec2array.Length; i++)
{
this.SetParameter(Parameter + i, vec2array[i]);
}
base.SetUniform(Parameter, vec3);
}
public void SetParameter(string Parameter, Vector3f[] vec3array)
public void SetUniform(string Parameter, Vector3 vec3)
{
for (int i = 0; i < vec3array.Length; i++)
{
this.SetParameter(Parameter + i, vec3array[i]);
}
base.SetUniform(Parameter, vec3.Convert());
}
public void SetParameter(string Parameter, Vector4[] vec4array)
public void SetUniform(string Parameter, Vector4 vec4)
{
for (int i = 0; i < vec4array.Length; i++)
{
this.SetParameter(Parameter + i, vec4array[i]);
}
base.SetUniform(Parameter, new Vec4(vec4.X, vec4.Y, vec4.Z, vec4.W));
}
public void SetUniformArray(string Parameter, Vector2f[] vec2array)
{
SetUniformArray(Parameter, vec2array.Select(v => (Vec2)v).ToArray());
}
public void SetUniformArray(string Parameter, Vector3f[] vec3array)
{
SetUniformArray(Parameter, vec3array.Select(v => (Vec3)v).ToArray());
}
public void SetUniformArray(string Parameter, Vector4[] vec4array)
{
SetUniformArray(Parameter, vec4array.Select(v => new Vec4(v.X, v.Y, v.Z, v.W)).ToArray());
}
public void SetUniformArray(string Parameter, Vector2[] vec2array)
{
SetUniformArray(Parameter, vec2array.Select(v => new Vec2(v.X, v.Y)).ToArray());
}
public void SetUniformArray(string Parameter, Vector3[] vec3array)
{
SetUniformArray(Parameter, vec3array.Select(v => new Vec3(v.X, v.Y, v.Z)).ToArray());
}
}
}

View File

@@ -1,7 +1,8 @@
using SFML.Graphics;
using SFML.System;
using OpenTK;
using SS14.Client.Graphics.Interface;
using OpenTK.Graphics;
using SS14.Client.Graphics.Utility;
using SS14.Shared.Utility;
using Vector2i = SS14.Shared.Maths.Vector2i;
@@ -10,10 +11,10 @@ namespace SS14.Client.Graphics.Sprite
/// <summary>
/// Sprite that contains Text
/// </summary>
public class TextSprite : ICluwneDrawable
public class TextSprite
{
private bool _shadowed; // Is the Text Shadowed
private Color _shadowColor; // Shadow Color
private Color4 _shadowColor; // Shadow Color
private Text _textSprite;
private string Label;
@@ -56,13 +57,13 @@ namespace SS14.Client.Graphics.Sprite
public void Draw()
{
_textSprite.Position = new Vector2f(Position.X, Position.Y);
_textSprite.Color = Color;
_textSprite.FillColor = Color.Convert();
CluwneLib.CurrentRenderTarget.Draw(_textSprite);
if (CluwneLib.Debug.DebugTextboxes)
{
var fr = _textSprite.GetGlobalBounds().Convert();
CluwneLib.drawHollowRectangle((int)fr.Left, (int)fr.Top, (int)fr.Width, (int)fr.Height, 1.0f, Color.Red);
CluwneLib.drawHollowRectangle((int)fr.Left, (int)fr.Top, (int)fr.Width, (int)fr.Height, 1.0f, Color4.Red);
}
}
@@ -97,7 +98,7 @@ namespace SS14.Client.Graphics.Sprite
public Vector2i Size;
public Color Color;
public Color4 Color;
public Vector2 ShadowOffset { get; set; }
@@ -113,7 +114,7 @@ namespace SS14.Client.Graphics.Sprite
set => _textSprite.CharacterSize = value;
}
public Color ShadowColor
public Color4 ShadowColor
{
get => _shadowColor;
set => this._shadowColor = value;

View File

@@ -0,0 +1,118 @@
using OpenTK;
using OpenTK.Graphics;
using SFML.Graphics;
using SFML.System;
using SS14.Shared.Maths;
using Vector2i = SS14.Shared.Maths.Vector2i;
using Vector2u = SS14.Shared.Maths.Vector2u;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.Graphics.Utility
{
/// <summary>
/// Provides compatibility extensions to convert between SFML and OpenTK types.
/// </summary>
public static class SfmlCompatibility
{
/// <summary>
/// Converts a OpenTK Vector2 to a SFML Vector2.
/// </summary>
/// <param name="vec">OpenTK Vector2.</param>
/// <returns>SFML Vector2.</returns>
public static Vector2f Convert(this Vector2 vec)
{
return new Vector2f(vec.X, vec.Y);
}
/// <summary>
/// Converts a SFML Vector2 to a OpenTK Vector2.
/// </summary>
/// <param name="vec">SFML Vector2.</param>
/// <returns>OpenTK Vector2.</returns>
public static Vector2 Convert(this Vector2f vec)
{
return new Vector2(vec.X, vec.Y);
}
/// <summary>
/// Converts a OpenTK Vector3 to a SFML Vector3.
/// </summary>
/// <param name="vec">OpenTK Vector3.</param>
/// <returns>SFML Vector3.</returns>
public static Vector3f Convert(this Vector3 vec)
{
return new Vector3f(vec.X, vec.Y, vec.Z);
}
/// <summary>
/// Converts a SFML Vector3 to a OpenTK Vector3.
/// </summary>
/// <param name="vec">SFML Vector3.</param>
/// <returns>OpenTK Vector3.</returns>
public static Vector3 Convert(this Vector3f vec)
{
return new Vector3(vec.X, vec.Y, vec.Z);
}
/// <summary>
/// Converts a OpenTK Box2 to a SFML FloatRect.
/// </summary>
/// <param name="box">OpenTK Box2.</param>
/// <returns>SFML FloatRect.</returns>
public static FloatRect Convert(this Box2 box)
{
return new FloatRect(box.Left, box.Top, box.Width, box.Height);
}
/// <summary>
/// Converts a SFML FloatRect to a OpenTK Box2.
/// </summary>
/// <param name="rect">SFML FloatRect.</param>
/// <returns>OpenTK Box2.</returns>
public static Box2 Convert(this FloatRect rect)
{
return new Box2(rect.Left, rect.Top, rect.Right(), rect.Bottom());
}
public static IntRect Convert(this Box2i box)
{
return new IntRect(box.Left, box.Top, box.Width, box.Height);
}
public static Box2i Convert(this IntRect rect)
{
return new Box2i(rect.Left, rect.Top, rect.Right(), rect.Bottom());
}
public static Vector2i Convert(this SFML.System.Vector2i vector)
{
return new Vector2i(vector.X, vector.Y);
}
public static SFML.System.Vector2i Convert(this Vector2i vector)
{
return new SFML.System.Vector2i(vector.X, vector.Y);
}
public static Vector2u Convert(this SFML.System.Vector2u vector)
{
return new Vector2u(vector.X, vector.Y);
}
public static Vector2 Convertf(this SFML.System.Vector2u vector)
{
return new Vector2(vector.X, vector.Y);
}
public static Color Convert(this Color4 color)
{
var bcolor = (System.Drawing.Color)color;
return new Color(bcolor.R, bcolor.G, bcolor.B, bcolor.A);
}
public static Color4 Convert(this Color color)
{
return new Color4(color.R, color.G, color.B, color.A);
}
}
}

View File

@@ -2,7 +2,7 @@
using SFML.System;
using System;
namespace SS14.Shared.Maths
namespace SS14.Client.Graphics.Utility
{
public static class SfmlExt
{
@@ -59,59 +59,6 @@ namespace SS14.Shared.Maths
(byte)(color >> 0),
(byte)(color >> 24)));
/// <summary>
/// Values used internally by <see cref="DirectionTo" />
/// </summary>
private static Direction[] AngleDirections = new Direction[]
{
Direction.East,
Direction.NorthEast,
Direction.North,
Direction.NorthWest,
Direction.West,
Direction.SouthWest,
Direction.South,
Direction.SouthEast,
Direction.East
};
/// <summary>
/// Find the direction that <paramref name="target" /> is from <paramref name="origin" />.
/// </summary>
/// <param name="origin">The origin vector.</param>
/// <param name="target">The target vector.</param>
/// <param name="fallback">The direction used if no direction could be calculated (difference between vectors too small).</param>
public static Direction DirectionTo(this Vector2f origin, Vector2f target, Direction fallback=Direction.South)
{
var mag1 = origin.Magnitude();
var mag2 = target.Magnitude();
// Check whether the vectors are almost zero.
// Don't use == because equality checking on floats is dangerous and unreliable.
// If the range is too wide go ahead and make it smaller.
if (mag1 < 0.0001 && mag1 > -0.0001 && mag2 < 0.0001 && mag2 > -0.0001)
{
return fallback;
}
// Angle in degrees.
// Keep in mind: Cartesian plane so 0° is to the right.
var angle = FloatMath.ToDegrees((float)Math.Atan2(target.Y - origin.Y, target.X - origin.X));
// The directions are assumed to be perfect 45° surfaces.
// So 0° is between the east one, and 22.5° is the edge between east and north east.
// Wrap negative angles around so we're always dealing with positives.
if (angle < 0)
{
angle += 360;
}
// Add 22.5° to offset the angles since 0° is inside one.
angle += 22.5f;
int dirindex = FloatMath.Clamp((int)Math.Floor(angle / 45f), 0, 8);
return AngleDirections[dirindex];
}
/// <summary>
/// Returns the dot product of two vectors

View File

@@ -1,56 +0,0 @@
namespace SS14.Client.Graphics.VertexData
{
public class VertexEnums
{
public enum VertexFieldContext
{
/// Position, 3 reals per vertex.
Position ,
/// Normal, 3 reals per vertex.
Normal ,
/// Blending weights.
BlendWeights ,
/// Blending indices.
BlendIndices ,
/// Diffuse colors.
Diffuse ,
/// Specular colors.
Specular ,
/// Texture coordinates.
TexCoords ,
/// Binormal (Y axis if normal is Z).
Binormal ,
/// Tangent (X axis if normal is Z).
Tangent
}
/// <summary>
/// Enumerator for vertex field types.
/// Used to define what type of field we're using.
/// </summary>
public enum VertexFieldType
{
/// 1 Floating point number.
Float1 ,
/// 2 Floating point numbers.
Float2 ,
/// 3 Floating point numbers.
Float3 ,
/// 4 Floating point numbers.
Float4 ,
/// DWORD color value.
Color ,
/// 1 signed short integers.
Short1 ,
/// 2 signed short integers.
Short2 ,
/// 3 signed short integers.
Short3 ,
/// 4 signed short integers.
Short4 ,
/// 4 Unsigned bytes.
UByte4
}
}
}

View File

@@ -1,6 +1,7 @@
using SFML.Graphics;
using SFML.System;
using SS14.Client.Graphics.Collection;
using SS14.Client.Graphics.Utility;
using SS14.Shared.Maths;
using System;
using System.Runtime.InteropServices;
@@ -221,4 +222,4 @@ namespace SS14.Client.Graphics.VertexData
}
#endregion
}
}
}

View File

@@ -0,0 +1,26 @@
using SFML.Graphics;
using SS14.Shared.Maths;
namespace SS14.Client.Graphics.View
{
public class Camera
{
private Viewport _view;
private readonly RenderWindow _viewport;
public Camera(Viewport viewport) { }
public Camera(RenderWindow viewport)
{
_viewport = viewport;
}
public int PixelsPerMeter { get; } = 32;
public Vector2 Position { get; set; }
public void SetView(SFML.Graphics.View view)
{
_viewport.SetView(view);
}
}
}

View File

@@ -1,3 +1,5 @@
using SS14.Shared.Maths;
namespace SS14.Client.Graphics.View
{
public class Viewport
@@ -7,13 +9,14 @@ namespace SS14.Client.Graphics.View
// TODO: Complete member initialization
this.OriginX = originX;
this.OriginY = originY;
this.Width = (int)width;
this.Height = (int)height;
this.Width = width;
this.Height = height;
}
public int Width { get; set; }
public int Height { get; set; }
public uint Width { get; set; }
public uint Height { get; set; }
public int OriginX { get; set; }
public int OriginY { get; set; }
public Vector2u Size => new Vector2u(Width, Height);
}
}

View File

@@ -1,4 +1,4 @@
using SFMLTexture = SFML.Graphics.Texture;
using SFMLTexture = SFML.Graphics.Texture;
using SFML.Graphics;
using System.Collections.Generic;
@@ -8,19 +8,17 @@ namespace SS14.Client.Graphics.TexHelpers
{
public SFMLTexture Texture;
public Image Image;
public bool[,] Opacity;
public TextureInfo(SFMLTexture tex, Image img, bool[,] opacity)
public TextureInfo(SFMLTexture tex, Image img)
{
Texture = tex;
Image = img;
Opacity = opacity;
}
}
public static class TextureCache
{
private static Dictionary<string, TextureInfo> _textures = null;
private static Dictionary<string, TextureInfo> _textures;
public static Dictionary<string, TextureInfo> Textures
{

View File

@@ -2,6 +2,7 @@
// Not some generic console command type.
// Couldn't think of a better name sorry.
using OpenTK.Graphics;
using SS14.Client.Interfaces.Console;
using SS14.Client.Interfaces.UserInterface;
using SS14.Shared.IoC;
@@ -30,7 +31,7 @@ namespace SS14.Client.Console
public bool Execute(IDebugConsole console, params string[] args)
{
SFML.Graphics.Color[] colors = { SFML.Graphics.Color.Green, SFML.Graphics.Color.Blue, SFML.Graphics.Color.Red };
Color4[] colors = { Color4.Green, Color4.Blue, Color4.Red };
Random random = new Random();
for (int x = 0; x < 50; x++)
{

View File

@@ -1,3 +1,4 @@
using OpenTK.Graphics;
using SFML.Graphics;
using SS14.Client.GameObjects;
using SS14.Client.Interfaces.Console;
@@ -24,7 +25,7 @@ namespace SS14.Client.Console
foreach (IEntity e in entitymanager.GetEntities(new ComponentEntityQuery()))
{
console.AddLine($"entity {e.Uid}, {e.Prototype.Name}.", Color.White);
console.AddLine($"entity {e.Uid}, {e.Prototype.Name}.", Color4.White);
}
return false;
@@ -47,7 +48,7 @@ namespace SS14.Client.Console
foreach (var component in components)
{
console.AddLine($"{component.Owner.Uid}: {component.GetType()}", Color.White);
console.AddLine($"{component.Owner.Uid}: {component.GetType()}", Color4.White);
}
return false;
}
@@ -63,7 +64,7 @@ namespace SS14.Client.Console
{
if (args.Length < 1)
{
console.AddLine($"Not enough arguments.", Color.Red);
console.AddLine($"Not enough arguments.", Color4.Red);
return false;
}
var componentFactory = IoCManager.Resolve<IComponentFactory>();
@@ -83,16 +84,16 @@ namespace SS14.Client.Console
}
message.Append($", NSE: {registration.NetworkSynchronizeExistence}, references:");
console.AddLine(message.ToString(), Color.White);
console.AddLine(message.ToString(), Color4.White);
foreach (Type type in registration.References)
{
console.AddLine($" {type}", Color.White);
console.AddLine($" {type}", Color4.White);
}
}
catch (UnknownComponentException)
{
console.AddLine($"No registration found for '{args[0]}'", Color.Red);
console.AddLine($"No registration found for '{args[0]}'", Color4.Red);
}
return false;

View File

@@ -1,4 +1,5 @@
using System;
using OpenTK.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -23,7 +24,7 @@ namespace SS14.Client.Console
switch (args.Length)
{
case 0:
console.AddLine("To display help for a specific command, write 'help <command>'. To list all available commands, write 'list'.", Color.White);
console.AddLine("To display help for a specific command, write 'help <command>'. To list all available commands, write 'list'.", Color4.White);
break;
case 1:
@@ -33,19 +34,19 @@ namespace SS14.Client.Console
if (!IoCManager.Resolve<IClientNetManager>().IsConnected)
{
// No server so nothing to respond with unknown command.
console.AddLine("Unknown command: " + commandname, Color.Red);
console.AddLine("Unknown command: " + commandname, Color4.Red);
return false;
}
// TODO: Maybe have a server side help?
return false;
}
IConsoleCommand command = console.Commands[commandname];
console.AddLine(string.Format("{0} - {1}", command.Command, command.Description), Color.White);
console.AddLine(command.Help, Color.White);
console.AddLine(string.Format("{0} - {1}", command.Command, command.Description), Color4.White);
console.AddLine(command.Help, Color4.White);
break;
default:
console.AddLine("Invalid amount of arguments.", Color.Red);
console.AddLine("Invalid amount of arguments.", Color4.Red);
break;
}
return false;
@@ -62,7 +63,7 @@ namespace SS14.Client.Console
{
foreach (IConsoleCommand command in console.Commands.Values)
{
console.AddLine(command.Command + ": " + command.Description, Color.White);
console.AddLine(command.Command + ": " + command.Description, Color4.White);
}
return false;

View File

@@ -1,4 +1,5 @@
using OpenTK;
using OpenTK.Graphics;
using SFML.Graphics;
using SFML.Window;
using SFML.System;
@@ -15,19 +16,21 @@ using SS14.Shared.Interfaces.Configuration;
using SS14.Shared.Interfaces.Map;
using SS14.Shared.Interfaces.Serialization;
using SS14.Shared.Configuration;
using SS14.Shared.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Log;
using SS14.Shared.Prototypes;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using SS14.Shared.ContentPack;
using SS14.Shared.Interfaces;
using SS14.Shared.Interfaces.Network;
using SS14.Shared.Interfaces.Timing;
using KeyArgs = SFML.Window.KeyEventArgs;
using SS14.Shared.Network.Messages;
using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.GameStates;
namespace SS14.Client
{
@@ -95,12 +98,16 @@ namespace SS14.Client
_serializer.Initialize();
var prototypeManager = IoCManager.Resolve<IPrototypeManager>();
prototypeManager.LoadDirectory(PathHelpers.ExecutableRelativeFile("Resources/Prototypes"));
prototypeManager.LoadDirectory(@"Prototypes");
prototypeManager.Resync();
_networkManager.Initialize(false);
_netGrapher.Initialize();
_userInterfaceManager.Initialize();
_mapManager.Initialize();
_networkManager.RegisterNetMessage<MsgFullState>(MsgFullState.NAME, (int)MsgFullState.ID, message => IoCManager.Resolve<IGameStateManager>().HandleFullStateMessage((MsgFullState)message));
_networkManager.RegisterNetMessage<MsgStateUpdate>(MsgStateUpdate.NAME, (int)MsgStateUpdate.ID, message => IoCManager.Resolve<IGameStateManager>().HandleStateUpdateMessage((MsgStateUpdate)message));
_networkManager.RegisterNetMessage<MsgEntity>(MsgEntity.NAME, (int)MsgEntity.ID, message => IoCManager.Resolve<IClientEntityManager>().HandleEntityNetworkMessage((MsgEntity)message));
_stateManager.RequestStateChange<MainScreen>();
@@ -243,8 +250,8 @@ namespace SS14.Client
/// <param name="e">Current GameTiming.RealFrameTime</param>
private void Render(FrameEventArgs e)
{
CluwneLib.ClearCurrentRendertarget(Color.Black);
CluwneLib.Screen.DispatchEvents();
CluwneLib.ClearCurrentRendertarget(Color4.Black);
CluwneLib.Window.DispatchEvents();
// draw everything
_stateManager.Render(e);
@@ -257,7 +264,7 @@ namespace SS14.Client
_netGrapher.Update();
// swap buffers to show the screen
CluwneLib.Screen.Display();
CluwneLib.Window.Graphics.Display();
}
private void LoadSplashResources()
@@ -272,17 +279,17 @@ namespace SS14.Client
_resourceCache.LoadSpriteFromTexture("ss14_logo_nt", nanotrasenTexture);
}
[Conditional("RELEASE")]
private void ShowSplashScreen()
{
// Do nothing when we're on DEBUG builds.
// The splash is just annoying.
#if !DEBUG
const uint SIZE_X = 600;
const uint SIZE_Y = 300;
// Size of the NT logo in the bottom right.
const float NT_SIZE_X = SIZE_X / 10f;
const float NT_SIZE_Y = SIZE_Y / 10f;
CluwneWindow window = CluwneLib.ShowSplashScreen(new VideoMode(SIZE_X, SIZE_Y));
var window = CluwneLib.ShowSplashScreen(new VideoMode(SIZE_X, SIZE_Y)).Graphics;
var logo = _resourceCache.GetSprite("ss14_logo");
logo.Position = new Vector2f(SIZE_X / 2 - logo.TextureRect.Width / 2, SIZE_Y / 2 - logo.TextureRect.Height / 2);
@@ -299,16 +306,12 @@ namespace SS14.Client
window.Draw(logo);
window.Draw(nanotrasen);
window.Display();
#endif
}
[Conditional("RELEASE")]
private void CleanupSplashScreen()
{
// Do nothing when we're on DEBUG builds.
// The splash is just annoying.
#if !DEBUG
CluwneLib.CleanupSplashScreen();
#endif
}
#endregion Constructors
@@ -326,7 +329,7 @@ namespace SS14.Client
new SFML.System.Vector2f(e.Width / 2, e.Height / 2),
new SFML.System.Vector2f(e.Width, e.Height)
);
CluwneLib.Screen.SetView(view);
CluwneLib.Window.Camera.SetView(view);
_stateManager.FormResize();
}
private void MainWindowRequestClose(object sender, EventArgs e)
@@ -449,18 +452,18 @@ namespace SS14.Client
private void SetupCluwne()
{
_configurationManager.RegisterCVar("display.width", 1280, CVarFlags.ARCHIVE);
_configurationManager.RegisterCVar("display.height", 720, CVarFlags.ARCHIVE);
_configurationManager.RegisterCVar("display.fullscreen", false, CVarFlags.ARCHIVE);
_configurationManager.RegisterCVar("display.refresh", 60, CVarFlags.ARCHIVE);
_configurationManager.RegisterCVar("display.vsync", false, CVarFlags.ARCHIVE);
_configurationManager.RegisterCVar("display.width", 1280, CVar.ARCHIVE);
_configurationManager.RegisterCVar("display.height", 720, CVar.ARCHIVE);
_configurationManager.RegisterCVar("display.fullscreen", false, CVar.ARCHIVE);
_configurationManager.RegisterCVar("display.refresh", 60, CVar.ARCHIVE);
_configurationManager.RegisterCVar("display.vsync", false, CVar.ARCHIVE);
uint displayWidth = (uint) _configurationManager.GetCVar<int>("display.width");
uint displayHeight = (uint) _configurationManager.GetCVar<int>("display.height");
bool isFullscreen = _configurationManager.GetCVar<bool>("display.fullscreen");
uint refresh = (uint) _configurationManager.GetCVar<int>("display.refresh");
CluwneLib.Video.SetFullscreen(isFullscreen);
CluwneLib.Video.SetFullScreen(isFullscreen);
CluwneLib.Video.SetRefreshRate(refresh);
CluwneLib.Video.SetWindowSize(displayWidth, displayHeight);
CluwneLib.Initialize();
@@ -471,19 +474,19 @@ namespace SS14.Client
CluwneLib.RefreshVideoSettings += SetupCluwne;
onetime = false;
}
CluwneLib.Screen.SetMouseCursorVisible(false);
CluwneLib.Screen.BackgroundColor = Color.Black;
CluwneLib.Screen.Resized += MainWindowResizeEnd;
CluwneLib.Screen.Closed += MainWindowRequestClose;
CluwneLib.Screen.KeyPressed += KeyDownEvent;
CluwneLib.Screen.KeyReleased += KeyUpEvent;
CluwneLib.Screen.MouseButtonPressed += MouseDownEvent;
CluwneLib.Screen.MouseButtonReleased += MouseUpEvent;
CluwneLib.Screen.MouseMoved += MouseMoveEvent;
CluwneLib.Screen.MouseWheelMoved += MouseWheelMoveEvent;
CluwneLib.Screen.MouseEntered += MouseEntered;
CluwneLib.Screen.MouseLeft += MouseLeft;
CluwneLib.Screen.TextEntered += TextEntered;
CluwneLib.Window.SetMouseCursorVisible(false);
CluwneLib.Window.Graphics.BackgroundColor = Color.Black;
CluwneLib.Window.Resized += MainWindowResizeEnd;
CluwneLib.Window.Closed += MainWindowRequestClose;
CluwneLib.Input.KeyPressed += KeyDownEvent;
CluwneLib.Input.KeyReleased += KeyUpEvent;
CluwneLib.Input.MouseButtonPressed += MouseDownEvent;
CluwneLib.Input.MouseButtonReleased += MouseUpEvent;
CluwneLib.Input.MouseMoved += MouseMoveEvent;
CluwneLib.Input.MouseWheelMoved += MouseWheelMoveEvent;
CluwneLib.Input.MouseEntered += MouseEntered;
CluwneLib.Input.MouseLeft += MouseLeft;
CluwneLib.Input.TextEntered += TextEntered;
CluwneLib.Go();
IoCManager.Resolve<IKeyBindingManager>().Initialize();

View File

@@ -2,12 +2,14 @@
using OpenTK;
using SS14.Client.Graphics.Collection;
using SS14.Client.Graphics.States;
using SS14.Client.Graphics.Utility;
using SS14.Client.Interfaces.Resource;
using SS14.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using SS14.Shared.Maths;
using OpenTK.Graphics;
namespace SS14.Client.Graphics.Sprite
{
@@ -56,15 +58,15 @@ namespace SS14.Client.Graphics.Sprite
#region Sprite passthrough methods
public Box2i AABB
{
get
{
if (_currentSprite != null)
return _currentSprite.TextureRect;
return new Box2i();
}
}
/// <summary>
/// Sub-rectangle of the texture to use as the sprite. This is NOT the local bounds of the sprite.
/// </summary>
public Box2i TextureRect => _currentSprite?.TextureRect.Convert() ?? new Box2i();
/// <summary>
/// Local bounding box of the sprite, with the origin at the top left.
/// </summary>
public Box2 LocalAABB => _currentSprite?.GetLocalBounds().Convert() ?? new Box2();
public bool HorizontalFlip { get; set; }
@@ -134,10 +136,12 @@ namespace SS14.Client.Graphics.Sprite
return _currentSprite;
}
public void Draw()
public void Draw(Color4 Color)
{
_currentSprite.Scale = new SFML.System.Vector2f(HorizontalFlip ? -1 : 1, 1);
_currentSprite.Color = Color.Convert();
_currentSprite.Draw();
_currentSprite.Color = Color4.White.Convert();
}
public void SetPosition(float x, float y)
@@ -159,7 +163,6 @@ namespace SS14.Client.Graphics.Sprite
return;
_currentAnimationState.Reset();
}
if (state != null)
{
_currentAnimationState = AnimationStates[state];

View File

@@ -10,6 +10,8 @@ using System;
using System.Collections.Generic;
using System.Linq;
using SS14.Shared.Utility;
using SS14.Shared.Map;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.GameObjects
{
@@ -18,14 +20,14 @@ namespace SS14.Client.GameObjects
/// </summary>
public class ClientEntityManager : EntityManager, IClientEntityManager
{
public IEnumerable<IEntity> GetEntitiesInRange(Vector2 position, float Range)
public IEnumerable<IEntity> GetEntitiesInRange(LocalCoordinates worldPos, float Range)
{
Range *= Range; // Square it here to avoid Sqrt
foreach (var entity in _entities.Values)
foreach (var entity in GetEntities())
{
var transform = entity.GetComponent<ITransformComponent>();
var relativePosition = position - transform.Position;
var relativePosition = worldPos.Position - transform.WorldPosition;
if (relativePosition.LengthSquared <= Range)
{
yield return entity;
@@ -33,6 +35,67 @@ namespace SS14.Client.GameObjects
}
}
public IEnumerable<IEntity> GetEntitiesIntersecting(Box2 position)
{
foreach (var entity in GetEntities())
{
if (entity.TryGetComponent<BoundingBoxComponent>(out var component))
{
if (position.Intersects(component.WorldAABB))
yield return entity;
}
else
{
var transform = entity.GetComponent<ITransformComponent>();
if (position.Contains(transform.WorldPosition))
{
yield return entity;
}
}
}
}
public IEnumerable<IEntity> GetEntitiesIntersecting(Vector2 position)
{
foreach (var entity in GetEntities())
{
if (entity.TryGetComponent<BoundingBoxComponent>(out var component))
{
if (component.WorldAABB.Contains(position))
yield return entity;
}
else
{
var transform = entity.GetComponent<ITransformComponent>();
if (FloatMath.CloseTo(transform.LocalPosition.X, position.X) && FloatMath.CloseTo(transform.LocalPosition.Y, position.Y))
{
yield return entity;
}
}
}
}
public bool AnyEntitiesIntersecting(Box2 position)
{
foreach (var entity in GetEntities())
{
if (entity.TryGetComponent<BoundingBoxComponent>(out var component))
{
if (position.Intersects(component.WorldAABB))
return true;
}
else
{
var transform = entity.GetComponent<ITransformComponent>();
if (position.Contains(transform.WorldPosition))
{
return true;
}
}
}
return false;
}
public void Initialize()
{
if (Initialized)
@@ -73,7 +136,7 @@ namespace SS14.Client.GameObjects
}
// After the first set of states comes in we do the initialization.
if (!Initialized)
if (!Initialized && MapsInitialized)
{
Initialize();
}

View File

@@ -5,6 +5,7 @@ using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.Interfaces.Network;
using SS14.Shared.Interfaces.Serialization;
using SS14.Shared.IoC;
using SS14.Shared.Network.Messages;
using System;
using System.Collections.Generic;
using System.IO;
@@ -52,7 +53,7 @@ namespace SS14.Client.GameObjects
}
public void SendDirectedComponentNetworkMessage(IEntity sendingEntity, uint netID,
NetDeliveryMethod method, NetConnection recipient,
NetDeliveryMethod method, INetChannel recipient,
params object[] messageParams)
{
throw new NotImplementedException();
@@ -187,92 +188,21 @@ namespace SS14.Client.GameObjects
/// </summary>
/// <param name="message">raw network message</param>
/// <returns>An IncomingEntityMessage object</returns>
public IncomingEntityMessage HandleEntityNetworkMessage(NetIncomingMessage message)
public IncomingEntityMessage HandleEntityNetworkMessage(MsgEntity message)
{
var messageType = (EntityMessage)message.ReadByte();
int uid;
IncomingEntityMessage result = IncomingEntityMessage.Null;
switch (messageType)
switch (message.Type)
{
case EntityMessage.ComponentMessage:
uid = message.ReadInt32();
IncomingEntityComponentMessage messageContent = HandleEntityComponentNetworkMessage(message);
result = new IncomingEntityMessage(uid, EntityMessage.ComponentMessage, messageContent,
message.SenderConnection);
break;
return new IncomingEntityMessage(message);
case EntityMessage.SystemMessage: //TODO: Not happy with this resolving the entmgr everytime a message comes in.
var manager = IoCManager.Resolve<IEntitySystemManager>();
manager.HandleSystemMessage(new EntitySystemData(message.SenderConnection, message));
manager.HandleSystemMessage(message);
break;
case EntityMessage.PositionMessage:
uid = message.ReadInt32();
//TODO: Handle position messages!
break;
}
return result;
}
/// <summary>
/// Handles an incoming entity component message
/// </summary>
/// <param name="message">Raw network message</param>
/// <returns>An IncomingEntityComponentMessage object</returns>
public IncomingEntityComponentMessage HandleEntityComponentNetworkMessage(NetIncomingMessage message)
{
var netID = message.ReadUInt32();
var messageParams = new List<object>();
while (message.Position < message.LengthBits)
{
switch ((NetworkDataType)message.ReadByte())
{
case NetworkDataType.d_enum:
messageParams.Add(message.ReadInt32());
break;
case NetworkDataType.d_bool:
messageParams.Add(message.ReadBoolean());
break;
case NetworkDataType.d_byte:
messageParams.Add(message.ReadByte());
break;
case NetworkDataType.d_sbyte:
messageParams.Add(message.ReadSByte());
break;
case NetworkDataType.d_ushort:
messageParams.Add(message.ReadUInt16());
break;
case NetworkDataType.d_short:
messageParams.Add(message.ReadInt16());
break;
case NetworkDataType.d_int:
messageParams.Add(message.ReadInt32());
break;
case NetworkDataType.d_uint:
messageParams.Add(message.ReadUInt32());
break;
case NetworkDataType.d_ulong:
messageParams.Add(message.ReadUInt64());
break;
case NetworkDataType.d_long:
messageParams.Add(message.ReadInt64());
break;
case NetworkDataType.d_float:
messageParams.Add(message.ReadFloat());
break;
case NetworkDataType.d_double:
messageParams.Add(message.ReadDouble());
break;
case NetworkDataType.d_string:
messageParams.Add(message.ReadString());
break;
case NetworkDataType.d_byteArray:
int length = message.ReadInt32();
messageParams.Add(message.ReadBytes(length));
break;
}
}
return new IncomingEntityComponentMessage(netID, messageParams);
return null;
}
#endregion Receiving

View File

@@ -34,11 +34,11 @@ namespace SS14.Client.GameObjects
var trans = Owner.GetComponent<ITransformComponent>();
var bounds = AABB;
return new FloatRect(
bounds.Left + trans.Position.X,
bounds.Top + trans.Position.Y,
return Box2.FromDimensions(
bounds.Left + trans.WorldPosition.X,
bounds.Top + trans.WorldPosition.Y,
bounds.Width,
bounds.Height).Convert();
bounds.Height);
}
}

View File

@@ -1,5 +1,6 @@
using System;
using OpenTK;
using OpenTK.Graphics;
using SFML.Graphics;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
@@ -14,7 +15,7 @@ namespace SS14.Client.GameObjects
// no client side collision support for now
private bool collisionEnabled;
public Color DebugColor { get; } = Color.Red;
public Color4 DebugColor { get; } = Color4.Red;
/// <inheritdoc />
public override string Name => "Collidable";
@@ -31,6 +32,9 @@ namespace SS14.Client.GameObjects
/// <inheritdoc />
Box2 ICollidable.AABB => Owner.GetComponent<BoundingBoxComponent>().AABB;
/// <inheritdoc />
public int MapID => Owner.GetComponent<ITransformComponent>().MapID;
/// <summary>
/// Called when the collidable is bumped into by someone/something
/// </summary>
@@ -48,9 +52,9 @@ namespace SS14.Client.GameObjects
/// gets the AABB from the sprite component and sends it to the CollisionManager.
/// </summary>
/// <param name="owner"></param>
public override void OnAdd(IEntity owner)
public override void Initialize()
{
base.OnAdd(owner);
base.Initialize();
if (collisionEnabled)
{
@@ -62,7 +66,7 @@ namespace SS14.Client.GameObjects
/// <summary>
/// removes the AABB from the CollisionManager.
/// </summary>
public override void OnRemove()
public override void Shutdown()
{
if (collisionEnabled)
{
@@ -70,7 +74,7 @@ namespace SS14.Client.GameObjects
cm.RemoveCollidable(this);
}
base.OnRemove();
base.Shutdown();
}
/// <summary>

View File

@@ -8,6 +8,7 @@ using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.Interfaces.GameObjects.Components;
using SS14.Shared.IoC;
using System;
using SS14.Shared.Map;
namespace SS14.Client.GameObjects
{
@@ -19,7 +20,7 @@ namespace SS14.Client.GameObjects
public event EventHandler<ClickEventArgs> OnClick;
public bool CheckClick(Vector2 worldPos, out int drawdepth)
public bool CheckClick(LocalCoordinates worldPos, out int drawdepth)
{
var component = Owner.GetComponent<IClickTargetComponent>();

View File

@@ -33,15 +33,6 @@ namespace SS14.Client.GameObjects
//Set up keystates
}
public override void OnRemove()
{
base.OnRemove();
var keyBindingManager = IoCManager.Resolve<IKeyBindingManager>();
keyBindingManager.BoundKeyDown -= KeyDown;
keyBindingManager.BoundKeyUp -= KeyUp;
}
public override void OnAdd(IEntity owner)
{
base.OnAdd(owner);

View File

@@ -2,7 +2,6 @@
using OpenTK.Graphics;
using Lidgren.Network;
using SFML.System;
using SS14.Client.Interfaces.Lighting;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
@@ -11,7 +10,11 @@ using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using SS14.Client.Graphics.Lighting;
using SS14.Client.Interfaces.Resource;
using YamlDotNet.RepresentationModel;
using Vector2 = SS14.Shared.Maths.Vector2;
using SS14.Shared.Map;
namespace SS14.Client.GameObjects
{
@@ -19,118 +22,161 @@ namespace SS14.Client.GameObjects
{
public override string Name => "PointLight";
public override uint? NetID => NetIDs.POINT_LIGHT;
//Contains a standard light
public ILight _light;
public Color4 _lightColor = new Color4(190, 190, 190, 255);
public Vector2 _lightOffset = Vector2.Zero;
public int _lightRadius = 512;
protected string _mask = "";
public LightModeClass _mode = LightModeClass.Constant;
public override Type StateType => typeof(PointLightComponentState);
//When added, set up the light.
public override void OnAdd(IEntity owner)
public ILight Light { get; private set; }
public Color4 Color
{
base.OnAdd(owner);
get => Light.Color;
set => Light.Color = value;
}
_light = IoCManager.Resolve<ILightManager>().CreateLight();
IoCManager.Resolve<ILightManager>().AddLight(_light);
private Vector2 offset = Vector2.Zero;
public Vector2 Offset
{
get => offset;
set
{
offset = value;
UpdateLightPosition();
}
}
_light.SetRadius(_lightRadius);
_light.SetColor(255, (int)_lightColor.R, (int)_lightColor.G, (int)_lightColor.B);
_light.Move(Owner.GetComponent<ITransformComponent>().Position + _lightOffset);
_light.SetMask(_mask);
public int Radius
{
get => Light.Radius;
set => Light.Radius = value;
}
private string mask;
protected string Mask
{
get => mask;
set
{
mask = value;
var sprMask = IoCManager.Resolve<IResourceCache>().GetSprite(value);
Light.SetMask(sprMask);
}
}
public LightModeClass ModeClass
{
get => Light.LightMode.LightModeClass;
set => IoCManager.Resolve<ILightManager>().SetLightMode(value, Light);
}
public LightMode Mode => Light.LightMode;
public LightState State
{
get => Light.LightState;
set => Light.LightState = value;
}
public override void Initialize()
{
base.Initialize();
Owner.GetComponent<ITransformComponent>().OnMove += OnMove;
UpdateLightPosition();
}
public override void LoadParameters(YamlMappingNode mapping)
{
var mgr = IoCManager.Resolve<ILightManager>();
Light = mgr.CreateLight();
mgr.AddLight(Light);
YamlNode node;
if (mapping.TryGetNode("lightoffsetx", out node))
if (mapping.TryGetNode("offset", out node))
{
_lightOffset.X = node.AsFloat();
Offset = node.AsVector2();
}
if (mapping.TryGetNode("lightoffsety", out node))
if (mapping.TryGetNode("radius", out node))
{
_lightOffset.Y = node.AsFloat();
Radius = node.AsInt();
}
else
{
Radius = 512;
}
if (mapping.TryGetNode("lightradius", out node))
if (mapping.TryGetNode("color", out node))
{
_lightRadius = node.AsInt();
Color = node.AsHexColor();
}
if (mapping.TryGetNode("lightColorR", out node))
else
{
_lightColor.R = node.AsFloat() / 255f;
}
if (mapping.TryGetNode("lightColorG", out node))
{
_lightColor.G = node.AsFloat() / 255f;
}
if (mapping.TryGetNode("lightColorB", out node))
{
_lightColor.B = node.AsFloat() / 255f;
Color = new Color4(200, 200, 200, 255);
}
if (mapping.TryGetNode("mask", out node))
{
_mask = node.AsString();
Mask = node.AsString();
}
else
{
Mask = "whitemask";
}
if (mapping.TryGetNode("state", out node))
{
State = node.AsEnum<LightState>();
}
else
{
State = LightState.On;
}
if (mapping.TryGetNode("mode", out node))
{
ModeClass = node.AsEnum<LightModeClass>();
}
else
{
ModeClass = LightModeClass.Constant;
}
}
protected void SetMode(LightModeClass mode)
{
IoCManager.Resolve<ILightManager>().SetLightMode(mode, _light);
}
public override void OnRemove()
public override void Shutdown()
{
Owner.GetComponent<ITransformComponent>().OnMove -= OnMove;
IoCManager.Resolve<ILightManager>().RemoveLight(_light);
base.OnRemove();
IoCManager.Resolve<ILightManager>().RemoveLight(Light);
base.Shutdown();
}
private void OnMove(object sender, VectorEventArgs args)
private void OnMove(object sender, MoveEventArgs args)
{
_light.Move(args.VectorTo + _lightOffset);
UpdateLightPosition(args.NewPosition);
}
protected void UpdateLightPosition(LocalCoordinates NewPosition)
{
Light.Coordinates = new LocalCoordinates(NewPosition.Position + Offset, NewPosition.Grid);
}
protected void UpdateLightPosition()
{
var transform = Owner.GetComponent<ITransformComponent>();
UpdateLightPosition(transform.LocalPosition);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
_light.Update(frameTime);
}
protected void SetMask(string mask)
{
_light.SetMask(mask);
Light.Update(frameTime);
}
/// <inheritdoc />
public override void HandleComponentState(ComponentState state)
{
var newState = (PointLightComponentState) state;
if (_light.LightState != newState.State)
_light.SetState(newState.State);
if (_light.Color.R != newState.ColorR || _light.Color.G != newState.ColorG || _light.Color.B != newState.ColorB)
SetColor(newState.ColorR, newState.ColorG, newState.ColorB);
if (_mode != newState.Mode)
SetMode(newState.Mode);
}
protected void SetColor(int R, int G, int B)
{
_lightColor.R = R/255f;
_lightColor.G = G/255f;
_lightColor.B = B/255f;
_light.SetColor(255, R, G, B);
var newState = (PointLightComponentState)state;
State = newState.State;
Color = newState.Color;
ModeClass = newState.Mode;
}
}
}

View File

@@ -1,4 +1,5 @@
using OpenTK;
using OpenTK.Graphics;
using SFML.Graphics;
using SFML.System;
using SS14.Client.Graphics;
@@ -12,13 +13,16 @@ using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.Interfaces.GameObjects.Components;
using SS14.Shared.IoC;
using SS14.Shared.Maths;
using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using SS14.Shared.Maths;
using YamlDotNet.RepresentationModel;
using Vector2i = SFML.System.Vector2i;
using Vector2i = SS14.Shared.Maths.Vector2i;
using SS14.Shared.Map;
using Vector2 = SS14.Shared.Maths.Vector2;
using SS14.Client.Graphics.Utility;
namespace SS14.Client.GameObjects
{
@@ -34,43 +38,31 @@ namespace SS14.Client.GameObjects
protected bool visible = true;
public DrawDepth DrawDepth { get; set; }
private SpeechBubble _speechBubble;
public Color4 Color { get; set; } = Color4.White;
public int MapID { get; private set; }
public override Type StateType => typeof(AnimatedSpriteComponentState);
public float Bottom
{
get
{
return Owner.GetComponent<ITransformComponent>().Position.Y +
(sprite.AABB.Height / 2);
}
}
/// <summary>
/// Center of the Y axis of the sprite bounds in world coords.
/// </summary>
public float Bottom => Owner.GetComponent<ITransformComponent>().WorldPosition.Y + sprite.LocalAABB.Height / 2;
public Box2 AverageAABB
{
get
{
var tileSize = IoCManager.Resolve<IMapManager>().TileSize;
var aaabb = sprite.AverageAABB;
return Box2.FromDimensions(
aaabb.Left / tileSize, aaabb.Top / tileSize,
aaabb.Width / tileSize, aaabb.Height / tileSize
aaabb.Left, aaabb.Top,
aaabb.Width, aaabb.Height
);
}
}
#region ISpriteComponent Members
public Box2 AABB
{
get
{
var tileSize = IoCManager.Resolve<IMapManager>().TileSize;
return Box2.FromDimensions(0, 0, sprite.AABB.Width / (float)tileSize,
sprite.AABB.Height / (float)tileSize);
}
}
public virtual Box2 LocalAABB => sprite.LocalAABB;
public bool HorizontalFlip { get; set; }
@@ -81,6 +73,20 @@ namespace SS14.Client.GameObjects
base.OnAdd(owner);
//Send a spritechanged message so everything knows whassup.
Owner.SendMessage(this, ComponentMessageType.SpriteChanged);
var transform = Owner.GetComponent<ITransformComponent>();
transform.OnMove += OnMove;
}
public override void Shutdown()
{
var transform = Owner.GetComponent<ITransformComponent>();
transform.OnMove -= OnMove;
base.Shutdown();
}
public void OnMove(object sender, MoveEventArgs args)
{
MapID = args.NewPosition.MapID;
}
public void SetSprite()
@@ -94,7 +100,7 @@ namespace SS14.Client.GameObjects
public void SetSprite(string name)
{
currentSprite = name;
sprite = (AnimatedSprite)IoCManager.Resolve<IResourceCache>().GetAnimatedSprite(name);
sprite = IoCManager.Resolve<IResourceCache>().GetAnimatedSprite(name);
}
public void SetAnimationState(string state, bool loop = true)
@@ -143,47 +149,64 @@ namespace SS14.Client.GameObjects
DrawDepth = p;
}
public Sprite GetCurrentSprite()
public virtual Sprite GetCurrentSprite()
{
return sprite.GetCurrentSprite();
}
public virtual bool WasClicked(Vector2 worldPos)
/// <summary>
/// Check if the world position is inside of the sprite texture. This checks both sprite bounds and transparency.
/// </summary>
/// <param name="worldPos">World position to check.</param>
/// <returns>Is the world position inside of the sprite?</returns>
public virtual bool WasClicked(LocalCoordinates worldPos)
{
if (sprite == null || !visible) return false;
Sprite spriteToCheck = sprite.GetCurrentSprite();
var bounds = spriteToCheck.GetLocalBounds();
var spriteToCheck = GetCurrentSprite();
var AABB =
Box2.FromDimensions(
Owner.GetComponent<ITransformComponent>().Position.X -
(bounds.Width / 2),
Owner.GetComponent<ITransformComponent>().Position.Y -
(bounds.Height / 2), bounds.Width, bounds.Height);
if (!AABB.Contains(new Vector2(worldPos.X, worldPos.Y))) return false;
var screenScale = CluwneLib.Window.Camera.PixelsPerMeter;
// local screen bounds
var localBounds = spriteToCheck.GetLocalBounds().Convert();
// local world bounds
var worldBounds = localBounds.Scale(1.0f / screenScale);
// move the origin from bottom right to center
worldBounds = worldBounds.Translated(new Vector2(-worldBounds.Width / 2, -worldBounds.Height / 2));
// absolute world bounds
worldBounds = worldBounds.Translated(Owner.GetComponent<ITransformComponent>().WorldPosition);
// check if clicked inside of the rectangle
if (!worldBounds.Contains(worldPos.ToWorld().Position))
return false;
// Get the sprite's position within the texture
var texRect = spriteToCheck.TextureRect;
// Get the clicked position relative to the texture
var spritePosition = new Vector2i((int)(worldPos.X - AABB.Left + texRect.Left),
(int)(worldPos.Y - AABB.Top + texRect.Top));
// Get the clicked position relative to the texture (World to Texture)
var pixelPos = new Vector2i((int) ((worldPos.X - worldBounds.Left) * screenScale), (int) ((worldPos.Y - worldBounds.Top) * screenScale));
if (spritePosition.X < 0 || spritePosition.Y < 0)
return false;
// offset pos by texture sub-rectangle
pixelPos = pixelPos + new Vector2i(texRect.Left, texRect.Top);
IResourceCache resCache = IoCManager.Resolve<IResourceCache>();
Dictionary<Texture, string> tmp = resCache.TextureToKey;
if (!tmp.ContainsKey(spriteToCheck.Texture)) { return false; } //if it doesn't exist, something's fucked
string textureKey = tmp[spriteToCheck.Texture];
bool[,] opacityMap = TextureCache.Textures[textureKey].Opacity; //get our clickthrough 'map'
if (!opacityMap[spritePosition.X, spritePosition.Y]) // Check if the clicked pixel is opaque
{
return false;
}
// make sure the position is actually inside the texture
if (!texRect.Contains(pixelPos.X, pixelPos.Y))
throw new InvalidOperationException("The click was inside the sprite bounds, but not inside the texture bounds? Check yo math.");
return true;
// fetch texture key of the sprite
var resCache = IoCManager.Resolve<IResourceCache>();
if (!resCache.TextureToKey.TryGetValue(spriteToCheck.Texture, out string textureKey))
throw new InvalidOperationException("Trying to look up a texture that does not exist in the ResourceCache.");
// use the texture key to fetch the Image of the sprite
if(!TextureCache.Textures.TryGetValue(textureKey, out TextureInfo texInfo))
throw new InvalidOperationException("The texture exists in the ResourceCache, but not in the CluwneLib TextureCache?");
// Check if the clicked pixel is transparent enough in the Image
return texInfo.Image.GetPixel((uint) pixelPos.X, (uint) pixelPos.Y).A >= Limits.ClickthroughLimit;
}
public override void LoadParameters(YamlMappingNode mapping)
@@ -194,6 +217,18 @@ namespace SS14.Client.GameObjects
SetDrawDepth(node.AsEnum<DrawDepth>());
}
if (mapping.TryGetNode("color", out node))
{
try
{
Color = System.Drawing.Color.FromName(node.ToString());
}
catch
{
Color = node.AsHexColor();
}
}
if (mapping.TryGetNode("sprite", out node))
{
baseSprite = node.AsString();
@@ -221,11 +256,11 @@ namespace SS14.Client.GameObjects
if (!visible) return;
if (sprite == null) return;
var ownerPos = Owner.GetComponent<ITransformComponent>().Position;
var ownerPos = Owner.GetComponent<ITransformComponent>().LocalPosition;
Vector2 renderPos = CluwneLib.WorldToScreen(ownerPos);
SetSpriteCenter(renderPos);
var bounds = sprite.AABB;
var renderPos = CluwneLib.WorldToScreen(ownerPos);
SetSpriteCenter(renderPos.Position);
var bounds = sprite.TextureRect;
if (ownerPos.X + bounds.Left + bounds.Width < topLeft.X
|| ownerPos.X > bottomRight.X
@@ -234,7 +269,7 @@ namespace SS14.Client.GameObjects
return;
sprite.HorizontalFlip = HorizontalFlip;
sprite.Draw();
sprite.Draw(Color);
//Render slaves above
IEnumerable<IRenderableComponent> renderablesAbove = from IRenderableComponent c in slaves
@@ -249,10 +284,10 @@ namespace SS14.Client.GameObjects
}
//Draw AABB
var aabb = AABB;
var aabb = LocalAABB;
if (_speechBubble != null)
_speechBubble.Draw(CluwneLib.WorldToScreen(Owner.GetComponent<ITransformComponent>().Position),
_speechBubble.Draw(CluwneLib.WorldToScreen(Owner.GetComponent<ITransformComponent>().WorldPosition),
new Vector2(), aabb);
}
@@ -264,8 +299,19 @@ namespace SS14.Client.GameObjects
if (sprite == null || IsSlaved())
return;
sprite.Direction = Owner.GetComponent<TransformComponent>().Rotation.GetDir();
sprite.Update(frameTime);
var worldRot = Owner.GetComponent<TransformComponent>().Rotation.ToVec();
// world2screen
worldRot = new Vector2(worldRot.X, worldRot.Y * -1);
//If the sprite is idle, it won't try to update Direction, meaning you stay facing the way you move
if (sprite.CurrentAnimationStateKey.Equals("idle"))
sprite.Update(frameTime);
else
{
sprite.Direction = worldRot.GetDir();
sprite.Update(frameTime);
}
}
public virtual void UpdateSlaves()
@@ -289,8 +335,8 @@ namespace SS14.Client.GameObjects
public void SetSpriteCenter(Vector2 center)
{
sprite.SetPosition(center.X - (sprite.AABB.Width / 2),
center.Y - (sprite.AABB.Height / 2));
sprite.SetPosition(center.X - (sprite.TextureRect.Width / 2),
center.Y - (sprite.TextureRect.Height / 2));
}
public bool IsSlaved()

View File

@@ -11,6 +11,9 @@ using System;
using System.Collections.Generic;
using SS14.Shared.Maths;
using YamlDotNet.RepresentationModel;
using OpenTK.Graphics;
using SS14.Shared.Map;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.GameObjects
{
@@ -150,6 +153,18 @@ namespace SS14.Client.GameObjects
SetDrawDepth(node.AsEnum<DrawDepth>());
}
if (mapping.TryGetNode("color", out node))
{
try
{
Color = System.Drawing.Color.FromName(node.ToString());
}
catch
{
Color = node.AsHexColor();
}
}
if (mapping.TryGetNode("basename", out node))
{
basename = node.AsString();
@@ -191,7 +206,7 @@ namespace SS14.Client.GameObjects
}
}
public override bool WasClicked(Vector2 worldPos)
public override bool WasClicked(LocalCoordinates worldPos)
{
return !IsInHand && base.WasClicked(worldPos);
}

View File

@@ -11,6 +11,8 @@ using System;
using System.Collections.Generic;
using SS14.Shared.Maths;
using YamlDotNet.RepresentationModel;
using OpenTK.Graphics;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.GameObjects
{
@@ -105,11 +107,23 @@ namespace SS14.Client.GameObjects
SetDrawDepth(node.AsEnum<DrawDepth>());
}
if (mapping.TryGetNode("drawdepth", out node))
if (mapping.TryGetNode("basename", out node))
{
_basename = node.AsString();
LoadSprites();
}
if (mapping.TryGetNode("color", out node))
{
try
{
Color = System.Drawing.Color.FromName(node.ToString());
}
catch
{
Color = node.AsHexColor();
}
}
}
protected override Sprite GetBaseSprite()
@@ -138,7 +152,7 @@ namespace SS14.Client.GameObjects
return;
}
var position = Owner.GetComponent<ITransformComponent>().Position;
var position = Owner.GetComponent<ITransformComponent>().WorldPosition;
if (position.X < topLeft.X
|| position.X > bottomRight.X

View File

@@ -3,6 +3,7 @@ using SFML.Graphics;
using SFML.System;
using SS14.Client.Graphics;
using SS14.Client.Graphics.Sprite;
using SS14.Client.Graphics.Utility;
using SS14.Client.Interfaces.Resource;
using SS14.Shared.GameObjects;
using SS14.Shared.IoC;
@@ -12,6 +13,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.GameObjects
{

View File

@@ -13,6 +13,8 @@ using System;
using System.Collections.Generic;
using System.Linq;
using SS14.Shared.Utility;
using SS14.Shared.Map;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.GameObjects
{
@@ -24,28 +26,30 @@ namespace SS14.Client.GameObjects
private Dictionary<string, ParticleSystem> _emitters = new Dictionary<string, ParticleSystem>(); // List of particle emitters.
protected IRenderableComponent master;
protected List<IRenderableComponent> slaves = new List<IRenderableComponent>();
public int MapID { get; private set; }
public DrawDepth DrawDepth { get; set; } = DrawDepth.ItemsOnTables;
#endregion Variables.
#region Properties
public Box2 AverageAABB => AABB;
public Box2 AverageAABB => LocalAABB;
public Box2 AABB => new Box2();
public Box2 LocalAABB => new Box2();
#endregion Properties
public override Type StateType => typeof(ParticleSystemComponentState);
public void OnMove(object sender, VectorEventArgs args)
public void OnMove(object sender, MoveEventArgs args)
{
var offset = new Vector2(args.VectorTo.X, args.VectorTo.Y) -
new Vector2(args.VectorFrom.X, args.VectorFrom.Y);
var offset = new Vector2(args.NewPosition.Position.X, args.NewPosition.Position.Y) -
new Vector2(args.OldPosition.Position.X, args.OldPosition.Position.Y);
foreach (KeyValuePair<string, ParticleSystem> particleSystem in _emitters)
{
particleSystem.Value.MoveEmitter(particleSystem.Value.EmitterPosition + offset);
}
MapID = args.NewPosition.MapID;
}
public override void OnAdd(IEntity owner)
@@ -55,11 +59,11 @@ namespace SS14.Client.GameObjects
transform.OnMove += OnMove;
}
public override void OnRemove()
public override void Shutdown()
{
var transform = Owner.GetComponent<ITransformComponent>();
transform.OnMove -= OnMove;
base.OnRemove();
base.Shutdown();
}
public override void Update(float frameTime)
@@ -73,12 +77,11 @@ namespace SS14.Client.GameObjects
public virtual void Render(Vector2 topLeft, Vector2 bottomRight)
{
Vector2 renderPos = CluwneLib.WorldToScreen(
Owner.GetComponent<ITransformComponent>().Position);
ScreenCoordinates renderPos = CluwneLib.WorldToScreen(Owner.GetComponent<ITransformComponent>().LocalPosition);
foreach (KeyValuePair<string, ParticleSystem> particleSystem in _emitters)
{
particleSystem.Value.Move(renderPos);
particleSystem.Value.Move(renderPos.Position);
particleSystem.Value.Render();
}
}
@@ -87,7 +90,7 @@ namespace SS14.Client.GameObjects
{
get
{
return Owner.GetComponent<ITransformComponent>().Position.Y;
return Owner.GetComponent<ITransformComponent>().WorldPosition.Y;
}
}

View File

@@ -8,6 +8,7 @@ using SS14.Shared.IoC;
using System;
using System.Text;
using SS14.Client.ResourceManagement;
using SS14.Shared.Map;
namespace SS14.Client.GameObjects
{
@@ -73,7 +74,7 @@ namespace SS14.Client.GameObjects
_mobName = mobname;
_buildTime = DateTime.Now;
_textSprite = new Text(String.Empty, _resourceCache.GetResource<FontResource>("Fonts/CALIBRI.TTF").Font);
_textSprite.Color = Color.Black;
_textSprite.FillColor = Color.Black;
// TODO Word wrap!
_textSprite.Position = new Vector2f(5, 3);
_stringBuilder = new StringBuilder();

View File

@@ -1,5 +1,6 @@
using Lidgren.Network;
using OpenTK;
using OpenTK.Graphics;
using SFML.Graphics;
using SFML.System;
using SS14.Client.Graphics;
@@ -15,9 +16,13 @@ using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using SS14.Client.Graphics.Sprite;
using SS14.Shared.Maths;
using YamlDotNet.RepresentationModel;
using Vector2i = SFML.System.Vector2i;
using Vector2i = SS14.Shared.Maths.Vector2i;
using SS14.Client.Graphics.Utility;
using SS14.Shared.Map;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.GameObjects
{
@@ -39,6 +44,8 @@ namespace SS14.Client.GameObjects
protected Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();
protected bool visible = true;
public DrawDepth DrawDepth { get; set; }
public Color4 Color { get; set; } = Color4.White;
public int MapID {get; private set;}
public override Type StateType => typeof(SpriteComponentState);
@@ -46,16 +53,18 @@ namespace SS14.Client.GameObjects
{
get
{
return Owner.GetComponent<ITransformComponent>().Position.Y +
return Owner.GetComponent<ITransformComponent>().WorldPosition.Y +
(GetActiveDirectionalSprite().GetLocalBounds().Height / 2);
}
}
#region ISpriteComponent Members
public Box2 AverageAABB => AABB;
public Box2 AverageAABB => LocalAABB;
public Box2 AABB
public Box2 LocalAABB
{
get
{
@@ -144,6 +153,20 @@ namespace SS14.Client.GameObjects
base.OnAdd(owner);
//Send a spritechanged message so everything knows whassup.
Owner.SendMessage(this, ComponentMessageType.SpriteChanged);
var transform = Owner.GetComponent<ITransformComponent>();
transform.OnMove += OnMove;
}
public override void Shutdown()
{
var transform = Owner.GetComponent<ITransformComponent>();
transform.OnMove -= OnMove;
base.Shutdown();
}
public void OnMove(object sender, MoveEventArgs args)
{
MapID = args.NewPosition.MapID;
}
public void ClearSprites()
@@ -219,40 +242,59 @@ namespace SS14.Client.GameObjects
return sprite;
}
public virtual bool WasClicked(Vector2 worldPos)
/// <summary>
/// Check if the world position is inside of the sprite texture. This checks both sprite bounds and transparency.
/// </summary>
/// <param name="worldPos">World position to check.</param>
/// <returns>Is the world position inside of the sprite?</returns>
public virtual bool WasClicked(LocalCoordinates worldPos)
{
if (currentBaseSprite == null || !visible) return false;
var spriteToCheck = GetActiveDirectionalSprite();
Sprite spriteToCheck = GetActiveDirectionalSprite();
var bounds = spriteToCheck.GetLocalBounds();
if (spriteToCheck == null || !visible) return false;
var AABB =
Box2.FromDimensions(
Owner.GetComponent<ITransformComponent>().Position.X - (bounds.Width / 2),
Owner.GetComponent<ITransformComponent>().Position.Y - (bounds.Height / 2), bounds.Width, bounds.Height);
if (!AABB.Contains(new Vector2(worldPos.X, worldPos.Y))) return false;
var screenScale = CluwneLib.Window.Camera.PixelsPerMeter;
// local screen bounds
var localBounds = spriteToCheck.GetLocalBounds().Convert();
// local world bounds
var worldBounds = localBounds.Scale(1.0f / screenScale);
// move the origin from bottom right to center
worldBounds = worldBounds.Translated(new Vector2(-worldBounds.Width / 2, -worldBounds.Height / 2));
// absolute world bounds
worldBounds = worldBounds.Translated(Owner.GetComponent<ITransformComponent>().WorldPosition);
// check if clicked inside of the rectangle
if (!worldBounds.Contains(worldPos.ToWorld().Position))
return false;
// Get the sprite's position within the texture
var texRect = spriteToCheck.TextureRect;
// Get the clicked position relative to the texture
var spritePosition = new Vector2i((int)(worldPos.X - AABB.Left + texRect.Left),
(int)(worldPos.Y - AABB.Top + texRect.Top));
// Get the clicked position relative to the texture (World to Texture)
var pixelPos = new Vector2i((int)((worldPos.X - worldBounds.Left) * screenScale), (int)((worldPos.Y - worldBounds.Top) * screenScale));
if (spritePosition.X < 0 || spritePosition.Y < 0)
return false;
// offset pos by texture sub-rectangle
pixelPos = pixelPos + new Vector2i(texRect.Left, texRect.Top);
IResourceCache resCache = IoCManager.Resolve<IResourceCache>();
Dictionary<Texture, string> tmp = resCache.TextureToKey;
if (!tmp.ContainsKey(spriteToCheck.Texture)) { return false; } //if it doesn't exist, something's fucked
string textureKey = tmp[spriteToCheck.Texture];
bool[,] opacityMap = TextureCache.Textures[textureKey].Opacity; //get our clickthrough 'map'
if (!opacityMap[spritePosition.X, spritePosition.Y]) // Check if the clicked pixel is opaque
{
return false;
}
// make sure the position is actually inside the texture
if (!texRect.Contains(pixelPos.X, pixelPos.Y))
throw new InvalidOperationException("The click was inside the sprite bounds, but not inside the texture bounds? Check yo math.");
return true;
// fetch texture key of the sprite
var resCache = IoCManager.Resolve<IResourceCache>();
if (!resCache.TextureToKey.TryGetValue(spriteToCheck.Texture, out string textureKey))
throw new InvalidOperationException("Trying to look up a texture that does not exist in the ResourceCache.");
// use the texture key to fetch the Image of the sprite
if (!TextureCache.Textures.TryGetValue(textureKey, out TextureInfo texInfo))
throw new InvalidOperationException("The texture exists in the ResourceCache, but not in the CluwneLib TextureCache?");
// Check if the clicked pixel is transparent enough in the Image
return texInfo.Image.GetPixel((uint)pixelPos.X, (uint)pixelPos.Y).A >= Limits.ClickthroughLimit;
}
public bool SpriteExists(string key)
@@ -270,6 +312,18 @@ namespace SS14.Client.GameObjects
SetDrawDepth(node.AsEnum<DrawDepth>());
}
if (mapping.TryGetNode("color", out node))
{
try
{
Color = System.Drawing.Color.FromName(node.ToString());
}
catch
{
Color = node.AsHexColor();
}
}
if (mapping.TryGetNode<YamlSequenceNode>("sprites", out var sequence))
{
foreach (YamlNode spriteNode in sequence)
@@ -299,18 +353,20 @@ namespace SS14.Client.GameObjects
Sprite spriteToRender = GetActiveDirectionalSprite();
Vector2 renderPos = CluwneLib.WorldToScreen(Owner.GetComponent<ITransformComponent>().Position);
ScreenCoordinates renderPos = CluwneLib.WorldToScreen(Owner.GetComponent<ITransformComponent>().LocalPosition);
var bounds = spriteToRender.GetLocalBounds();
SetSpriteCenter(spriteToRender, renderPos);
SetSpriteCenter(spriteToRender, renderPos.Position);
if (Owner.GetComponent<ITransformComponent>().Position.X + bounds.Left + bounds.Width < topLeft.X
|| Owner.GetComponent<ITransformComponent>().Position.X > bottomRight.X
|| Owner.GetComponent<ITransformComponent>().Position.Y + bounds.Top + bounds.Height < topLeft.Y
|| Owner.GetComponent<ITransformComponent>().Position.Y > bottomRight.Y)
if (Owner.GetComponent<ITransformComponent>().WorldPosition.X + bounds.Left + bounds.Width < topLeft.X
|| Owner.GetComponent<ITransformComponent>().WorldPosition.X > bottomRight.X
|| Owner.GetComponent<ITransformComponent>().WorldPosition.Y + bounds.Top + bounds.Height < topLeft.Y
|| Owner.GetComponent<ITransformComponent>().WorldPosition.Y > bottomRight.Y)
return;
spriteToRender.Scale = new Vector2f(HorizontalFlip ? -1 : 1, 1);
spriteToRender.Color = this.Color.Convert();
spriteToRender.Draw();
spriteToRender.Color = Color4.White.Convert();
//Render slaves above
IEnumerable<SpriteComponent> renderablesAbove = from SpriteComponent c in slaves
@@ -325,9 +381,9 @@ namespace SS14.Client.GameObjects
}
//Draw AABB
var aabb = AABB;
var aabb = LocalAABB;
if (CluwneLib.Debug.DebugColliders)
CluwneLib.drawRectangle((int)(renderPos.X - aabb.Width / 2), (int)(renderPos.Y - aabb.Height / 2), aabb.Width, aabb.Height, new SFML.Graphics.Color(0, 255, 0));
CluwneLib.drawRectangle((int)(renderPos.X - aabb.Width / 2), (int)(renderPos.Y - aabb.Height / 2), aabb.Width, aabb.Height, Color4.Blue);
}
public void SetSpriteCenter(string sprite, Vector2 center)
@@ -342,6 +398,11 @@ namespace SS14.Client.GameObjects
center.Y - (bounds.Height / 2));
}
public void SetSpriteCenter(Sprite sprite, LocalCoordinates worldPos)
{
SetSpriteCenter(sprite, worldPos.Position);
}
public bool IsSlaved()
{
return master != null;

View File

@@ -1,4 +1,5 @@
using OpenTK;
using OpenTK.Graphics;
using SFML.Graphics;
using SFML.System;
using SS14.Client.Graphics;
@@ -6,11 +7,13 @@ using SS14.Client.Interfaces.Resource;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects.Components;
using SS14.Shared.IoC;
using SS14.Shared.Map;
using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using YamlDotNet.RepresentationModel;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.GameObjects
{
@@ -43,6 +46,13 @@ namespace SS14.Client.GameObjects
CarriedSprite = spritename;
}
public override Sprite GetCurrentSprite()
{
if (!IsCurrentlyWorn)
return NotWornSprite;
return base.GetCurrentSprite();
}
public override void LoadParameters(YamlMappingNode mapping)
{
base.LoadParameters(mapping);
@@ -59,6 +69,19 @@ namespace SS14.Client.GameObjects
}
}
public override Box2 LocalAABB
{
get
{
if (!IsCurrentlyWorn)
{
var bounds = GetCurrentSprite().GetLocalBounds();
return Box2.FromDimensions(0, 0, bounds.Width, bounds.Height);
}
return base.LocalAABB;
}
}
public override void Render(Vector2 topLeft, Vector2 bottomRight)
{
if (IsCurrentlyWorn && currentSprite == baseSprite)
@@ -92,15 +115,14 @@ namespace SS14.Client.GameObjects
Sprite spriteToRender = NotWornSprite;
var bounds = spriteToRender.GetLocalBounds();
Vector2 renderPos = CluwneLib.WorldToScreen(
Owner.GetComponent<ITransformComponent>().Position);
ScreenCoordinates renderPos = CluwneLib.WorldToScreen(Owner.GetComponent<ITransformComponent>().LocalPosition);
spriteToRender.Position = new Vector2f(renderPos.X - (bounds.Width / 2),
renderPos.Y - (bounds.Height / 2));
if (Owner.GetComponent<ITransformComponent>().Position.X + bounds.Left + bounds.Width < topLeft.X
|| Owner.GetComponent<ITransformComponent>().Position.X > bottomRight.X
|| Owner.GetComponent<ITransformComponent>().Position.Y + bounds.Top + bounds.Height < topLeft.Y
|| Owner.GetComponent<ITransformComponent>().Position.Y > bottomRight.Y)
if (Owner.GetComponent<ITransformComponent>().WorldPosition.X + bounds.Left + bounds.Width < topLeft.X
|| Owner.GetComponent<ITransformComponent>().WorldPosition.X > bottomRight.X
|| Owner.GetComponent<ITransformComponent>().WorldPosition.Y + bounds.Top + bounds.Height < topLeft.Y
|| Owner.GetComponent<ITransformComponent>().WorldPosition.Y > bottomRight.Y)
return;
spriteToRender.Scale = new Vector2f(HorizontalFlip ? -1 : 1, 1);
@@ -117,6 +139,12 @@ namespace SS14.Client.GameObjects
{
component.Render(topLeft, bottomRight);
}
//Draw AABB
var aabb = LocalAABB;
if (CluwneLib.Debug.DebugColliders)
CluwneLib.drawRectangle((int)(renderPos.X - aabb.Width / 2), (int)(renderPos.Y - aabb.Height / 2), aabb.Width, aabb.Height, Color4.Blue);
}
}
}

View File

@@ -6,6 +6,10 @@ using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.Interfaces.GameObjects.Components;
using SS14.Shared.Maths;
using SS14.Shared.Map;
using Vector2 = SS14.Shared.Maths.Vector2;
using SS14.Shared.IoC;
using SS14.Shared.Interfaces.Map;
namespace SS14.Client.GameObjects
{
@@ -14,10 +18,11 @@ namespace SS14.Client.GameObjects
/// </summary>
public class TransformComponent : Component, ITransformComponent
{
public Vector2 Position { get; private set; }
private Vector2 _position;
public int MapID { get; private set; }
public int GridID { get; private set; }
public Angle Rotation { get; private set; }
public ITransformComponent Parent { get; private set; }
//TODO: Make parenting actually work.
/// <inheritdoc />
@@ -30,7 +35,24 @@ namespace SS14.Client.GameObjects
public override Type StateType => typeof(TransformComponentState);
/// <inheritdoc />
public event EventHandler<VectorEventArgs> OnMove;
public event EventHandler<MoveEventArgs> OnMove;
public LocalCoordinates LocalPosition => new LocalCoordinates(_position, GridID, MapID);
public Vector2 WorldPosition
{
get
{
if (Parent != null)
{
return GetMapTransform().WorldPosition; //Search up the tree for the true map position
}
else
{
return IoCManager.Resolve<IMapManager>().GetMap(MapID).GetGrid(GridID).ConvertToWorld(_position);
}
}
}
/// <inheritdoc />
public override void HandleComponentState(ComponentState state)
@@ -38,10 +60,12 @@ namespace SS14.Client.GameObjects
var newState = (TransformComponentState)state;
Rotation = newState.Rotation;
if (Position != newState.Position)
if (_position != newState.Position || MapID != newState.MapID || GridID != newState.GridID)
{
OnMove?.Invoke(this, new VectorEventArgs(Position, newState.Position));
Position = newState.Position;
OnMove?.Invoke(this, new MoveEventArgs(LocalPosition, new LocalCoordinates(newState.Position, newState.GridID, newState.MapID)));
_position = newState.Position;
MapID = newState.MapID;
GridID = newState.GridID;
}
if (Parent != newState.Parent)

View File

@@ -29,7 +29,6 @@ namespace SS14.Client.GameObjects.EntitySystems
foreach (var entity in entities)
{
var inputs = entity.GetComponent<KeyBindingInputComponent>();
//Animation setting
if (entity.TryGetComponent<AnimatedSpriteComponent>(out var component))
{

View File

@@ -1,57 +1,91 @@
using Lidgren.Network;
using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.GameStates;
using SS14.Client.Interfaces.Player;
using SS14.Shared;
using SS14.Shared.GameStates;
using SS14.Shared.Interfaces.Network;
using SS14.Shared.Interfaces.Timing;
using SS14.Shared.IoC;
using SS14.Shared.Network.Messages;
using System.Collections.Generic;
using System.Linq;
namespace SS14.Client.GameStates
{
public class GameStateManager : Dictionary<uint, GameState>, IGameStateManager
public class GameStateManager : IGameStateManager
{
private readonly Dictionary<long, uint> ackedStates = new Dictionary<long, uint>();
private uint currentStateSeq;
public Dictionary<uint, GameState> GameStates;
[Dependency]
private readonly IGameTiming timing;
[Dependency]
private readonly IClientNetManager networkManager;
[Dependency]
private readonly IClientEntityManager entityManager;
[Dependency]
private readonly IPlayerManager playerManager;
public GameState CurrentState { get; private set; }
#region IGameStateManager Members
public void Cull()
public GameStateManager()
{
foreach (uint v in Keys.Where(v => v < OldestStateAcked).ToList())
Remove(v);
GameStates = new Dictionary<uint, GameState>();
}
public uint OldestStateAcked
#region Network
public void HandleFullStateMessage(MsgFullState message)
{
get
if (!GameStates.Keys.Contains(message.State.Sequence))
{
uint state = ackedStates.Values.FirstOrDefault(val => val == ackedStates.Values.Max());
return state;
AckGameState(message.State.Sequence);
message.State.GameTime = (float)timing.CurTime.TotalSeconds;
ApplyGameState(message.State);
}
}
public void Ack(long uniqueIdentifier, uint stateAcked)
public void HandleStateUpdateMessage(MsgStateUpdate message)
{
if (!ackedStates.ContainsKey(uniqueIdentifier))
ackedStates.Add(uniqueIdentifier, stateAcked);
else
ackedStates[uniqueIdentifier] = stateAcked;
GameStateDelta delta = message.StateDelta;
if (GameStates.ContainsKey(delta.FromSequence))
{
AckGameState(delta.Sequence);
GameState fromState = GameStates[delta.FromSequence];
GameState newState = fromState + delta;
newState.GameTime = (float)timing.CurTime.TotalSeconds;
ApplyGameState(newState);
CullOldStates(delta.FromSequence);
}
}
#endregion
#endregion Network
public void CullAll()
private void CullOldStates(uint sequence)
{
Clear();
foreach (uint v in GameStates.Keys.Where(v => v <= sequence).ToList())
GameStates.Remove(v);
}
public void ApplyFullState(uint seq, GameState fullState)
private void AckGameState(uint sequence)
{
CurrentState = fullState;
currentStateSeq = seq;
NetOutgoingMessage ack = networkManager.CreateMessage();
ack.Write((byte)NetMessages.StateAck);
ack.Write(sequence);
networkManager.ClientSendMessage(ack, NetDeliveryMethod.ReliableUnordered);
}
public void ApplyDeltaState(uint oldStateSeq, uint newStateSeq, GameStateDelta delta)
private void ApplyGameState(GameState gameState)
{
GameStates[gameState.Sequence] = gameState;
CurrentState = gameState;
entityManager.ApplyEntityStates(CurrentState.EntityStates, CurrentState.GameTime);
playerManager.ApplyPlayerStates(CurrentState.PlayerStates);
}
}
}

View File

@@ -9,6 +9,7 @@ using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System;
using System.Linq;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.Helpers
{
@@ -214,18 +215,18 @@ namespace SS14.Client.Helpers
SetUpIntermediateTarget(sourceImage.Width, sourceImage.Height);
_intermediateTarget.BeginDrawing();
_intermediateTarget.Clear(Color.Black);
GaussianBlurTechnique["GaussianBlur" + Radius + "Horizontal"].SetParameter("colorMapTexture", GLSLShader.CurrentTexture);
GaussianBlurTechnique["GaussianBlur" + Radius + "Horizontal"].SetParameter("weights_offsets", WeightsOffsetsX.Select(v => v.Convert()).ToArray());
GaussianBlurTechnique["GaussianBlur" + Radius + "Horizontal"].SetUniform("colorMapTexture", GLSLShader.CurrentTexture);
GaussianBlurTechnique["GaussianBlur" + Radius + "Horizontal"].SetUniformArray("weights_offsets", WeightsOffsetsX);
GaussianBlurTechnique["GaussianBlur" + Radius + "Horizontal"].setAsCurrentShader();
sourceImage.Blit(0, 0, sourceImage.Width, sourceImage.Height);
_intermediateTarget.EndDrawing();
GaussianBlurTechnique["GaussianBlur" + Radius + "Horizontal"].ResetCurrentShader();
//// blur the blur vertically
// blur the blur vertically
sourceImage.BeginDrawing();
GaussianBlurTechnique["GaussianBlur" + Radius + "Vertical"].SetParameter("colorMapTexture", GLSLShader.CurrentTexture);
GaussianBlurTechnique["GaussianBlur" + Radius + "Vertical"].SetParameter("weights_offsets", WeightsOffsetsY.Select(v => v.Convert()).ToArray());
GaussianBlurTechnique["GaussianBlur" + Radius + "Vertical"].SetUniform("colorMapTexture", GLSLShader.CurrentTexture);
GaussianBlurTechnique["GaussianBlur" + Radius + "Vertical"].SetUniformArray("weights_offsets", WeightsOffsetsY);
GaussianBlurTechnique["GaussianBlur" + Radius + "Vertical"].setAsCurrentShader() ;
_intermediateTarget.Blit(0, 0, _intermediateTarget.Width, _intermediateTarget.Height);
sourceImage.EndDrawing();

View File

@@ -1,5 +1,6 @@
using SFML.System;
using OpenTK;
using OpenTK.Graphics;
using SS14.Client.Graphics;
using System;
@@ -23,27 +24,27 @@ namespace SS14.Client.Helpers
{
for (int i = 0; i < _stars.Length/4; i++)
{
_stars[i, layer].Position = new Vector2((float) (_random.NextDouble()*CluwneLib.Screen.Size.X),
_stars[i, layer].Position = new Vector2((float) (_random.NextDouble()*CluwneLib.Window.Viewport.Size.X),
(float)
(_random.NextDouble()*CluwneLib.CurrentClippingViewport.Height));
(_random.NextDouble()* CluwneLib.Window.Viewport.Height));
// Select magnitude.
switch (layer)
{
case 0:
_stars[i, layer].Magnitude = SFML.Graphics.Color.White;
_stars[i, layer].Magnitude = Color4.White;
_stars[i, layer].VDelta = (float) (_random.NextDouble()*100.0) + 55.0f;
break;
case 1:
_stars[i, layer].Magnitude = new SFML.Graphics.Color(192, 192, 192);
_stars[i, layer].Magnitude = new Color4(192, 192, 192, 255);
_stars[i, layer].VDelta = (float) (_random.NextDouble()*50.0) + 27.5f;
break;
case 2:
_stars[i, layer].Magnitude = new SFML.Graphics.Color(128, 128, 128);
_stars[i, layer].Magnitude = Color4.Gray;
_stars[i, layer].VDelta = (float) (_random.NextDouble()*25.0) + 13.5f;
break;
default:
_stars[i, layer].Magnitude = new SFML.Graphics.Color(64, 64, 64);
_stars[i, layer].Magnitude = new Color4(64, 64, 64, 255);
_stars[i, layer].VDelta = (float) (_random.NextDouble()*12.5) + 1.0f;
break;
}
@@ -63,16 +64,16 @@ namespace SS14.Client.Helpers
_stars[i, layer].Position.Y += _stars[i, layer].VDelta*deltaTime;
// Wrap around.
if (_stars[i, layer].Position.Y > CluwneLib.CurrentClippingViewport.Height)
if (_stars[i, layer].Position.Y > CluwneLib.Window.Viewport.Height)
_stars[i, layer].Position =
new Vector2((float) (_random.NextDouble()*CluwneLib.CurrentClippingViewport.Width), 0);
new Vector2((float) (_random.NextDouble()* CluwneLib.Window.Viewport.Width), 0);
}
}
public void Render(float xTopleft, float yTopleft)
{
var delta = CluwneLib.Time.FrameTime.TotalSeconds;
CluwneLib.ClearCurrentRendertarget(SFML.Graphics.Color.Black);
CluwneLib.ClearCurrentRendertarget(Color4.Black);
DrawStars(3, (float)delta / 2000);
DrawStars(2, (float)delta / 2000);
for (int layer = 1; layer >= 0; layer--)
@@ -86,7 +87,7 @@ namespace SS14.Client.Helpers
/// <summary>
/// Magnitude of the star.
/// </summary>
public SFML.Graphics.Color Magnitude;
public Color4 Magnitude;
/// <summary>
/// Position of the star.

View File

@@ -27,8 +27,8 @@ namespace SS14.Client.Input
public void Initialize()
{
Enabled = true;
CluwneLib.Screen.KeyPressed += KeyDown;
CluwneLib.Screen.KeyReleased += KeyUp;
CluwneLib.Input.KeyPressed += KeyDown;
CluwneLib.Input.KeyReleased += KeyUp;
LoadKeys();
}
@@ -39,8 +39,8 @@ namespace SS14.Client.Input
/// </summary>
~KeyBindingManager()
{
CluwneLib.Screen.KeyPressed -= KeyDown;
CluwneLib.Screen.KeyReleased -= KeyUp;
CluwneLib.Input.KeyPressed -= KeyDown;
CluwneLib.Input.KeyReleased -= KeyUp;
}
private void KeyDown(object sender, KeyEventArgs e)

View File

@@ -1,9 +1,5 @@
using System;
using OpenTK.Graphics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML.Graphics;
namespace SS14.Client.Interfaces.Console
{
@@ -14,7 +10,7 @@ namespace SS14.Client.Interfaces.Console
/// <summary>
/// Write a line with a specific color to the console window.
/// </summary>
void AddLine(string text, Color color);
void AddLine(string text, Color4 color);
void Clear();
}

View File

@@ -1,9 +1,10 @@
using OpenTK;
using OpenTK;
using SFML.System;
using SS14.Client.State.States;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.Interfaces.GameObjects.Components;
using SS14.Shared.Map;
namespace SS14.Client.Interfaces.GameObjects.Components
{
@@ -18,7 +19,7 @@ namespace SS14.Client.Interfaces.GameObjects.Components
/// Used by <see cref="GameScreen" /> to sort and pick the highest successful one when multiple overlapping entities passed.
/// </param>
/// <returns>True if the click worked, false otherwise.</returns>
bool CheckClick(Vector2 worldPos, out int drawdepth);
bool CheckClick(LocalCoordinates worldPos, out int drawdepth);
/// <summary>
/// Sends the click to the sister component on the server and things subscribed to

View File

@@ -1,7 +1,7 @@
using OpenTK;
using SFML.System;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.Maths;
using SS14.Shared.Map;
namespace SS14.Client.Interfaces.GameObjects
{
@@ -10,7 +10,7 @@ namespace SS14.Client.Interfaces.GameObjects
/// </summary>
public interface IClickTargetComponent : IComponent
{
bool WasClicked(Vector2 worldPos);
bool WasClicked(LocalCoordinates worldPos);
DrawDepth DrawDepth { get; }
}
}

View File

@@ -3,13 +3,18 @@ using SFML.System;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Map;
using System.Collections.Generic;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.Interfaces.GameObjects
{
public interface IClientEntityManager : IEntityManager
{
IEnumerable<IEntity> GetEntitiesInRange(Vector2 position, float Range);
IEnumerable<IEntity> GetEntitiesInRange(LocalCoordinates position, float Range);
IEnumerable<IEntity> GetEntitiesIntersecting(Box2 position);
IEnumerable<IEntity> GetEntitiesIntersecting(Vector2 position);
bool AnyEntitiesIntersecting(Box2 position);
void ApplyEntityStates(IEnumerable<EntityState> entityStates, float serverTime);
}
}

View File

@@ -1,8 +1,9 @@
using OpenTK;
using OpenTK;
using SFML.Graphics;
using SFML.System;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using Vector2 = SS14.Shared.Maths.Vector2;
namespace SS14.Client.Interfaces.GameObjects
{
@@ -11,12 +12,13 @@ namespace SS14.Client.Interfaces.GameObjects
DrawDepth DrawDepth { get; set; }
float Bottom { get; }
void Render(Vector2 topLeft, Vector2 bottomRight);
Box2 AABB { get; }
Box2 LocalAABB { get; }
Box2 AverageAABB { get; }
bool IsSlaved();
void SetMaster(IEntity m);
void UnsetMaster();
void AddSlave(IRenderableComponent slavecompo);
void RemoveSlave(IRenderableComponent slavecompo);
int MapID { get; }
}
}

View File

@@ -1,4 +1,4 @@
using OpenTK;
using OpenTK;
using SFML.Graphics;
using SS14.Shared.Interfaces.GameObjects;
using System.Collections.Generic;
@@ -7,7 +7,7 @@ namespace SS14.Client.Interfaces.GameObjects
{
public interface ISpriteComponent : IComponent
{
Box2 AABB { get; }
Box2 LocalAABB { get; }
Sprite GetCurrentSprite();
Sprite GetSprite(string spriteKey);
List<Sprite> GetAllSprites();

View File

@@ -1,3 +1,4 @@
using OpenTK.Graphics;
using SFML.Graphics;
namespace SS14.Client.Interfaces.GameObjects
@@ -5,5 +6,6 @@ namespace SS14.Client.Interfaces.GameObjects
public interface ISpriteRenderableComponent : IRenderableComponent
{
Sprite GetCurrentSprite();
Color4 Color { get; set; }
}
}

View File

@@ -1,12 +1,12 @@
using SS14.Shared.GameStates;
using SS14.Shared.GameStates;
using SS14.Shared.Network.Messages;
using System.Collections.Generic;
namespace SS14.Client.Interfaces.GameStates
{
public interface IGameStateManager : IDictionary<uint, GameState>
public interface IGameStateManager
{
uint OldestStateAcked { get; }
void Cull();
void Ack(long uniqueIdentifier, uint state);
void HandleFullStateMessage(MsgFullState message);
void HandleStateUpdateMessage(MsgStateUpdate message);
}
}

View File

@@ -1,28 +0,0 @@
using OpenTK;
using SFML.Graphics;
using SFML.System;
using SS14.Shared;
using SS14.Shared.Maths;
namespace SS14.Client.Interfaces.Lighting
{
public interface ILight
{
int Radius { get; }
Color Color { get; }
Vector2 Position { get; }
LightState LightState { get; }
ILightArea LightArea { get; }
LightMode LightMode { get; set; }
void Move(Vector2 toPosition);
void SetRadius(int Radius);
void SetColor(int a, int r, int g, int b);
void SetColor(Color color);
void Update(float frametime);
void SetMask(string _mask);
Vector4 GetColorVec();
void SetState(LightState state);
}
}

View File

@@ -1,26 +0,0 @@
using SFML.Graphics;
using SFML.System;
using OpenTK;
using SS14.Client.Graphics.Render;
using SS14.Shared.Maths;
namespace SS14.Client.Interfaces.Lighting
{
public interface ILightArea
{
RenderImage RenderTarget { get; }
Vector2 LightPosition { get; set; }
Vector2 LightAreaSize { get; set; }
bool Calculated { get; set; }
Sprite Mask { get; set; }
bool MaskFlipX { get; set; }
bool MaskFlipY { get; set; }
bool Rot90 { get; set; }
Vector4 MaskProps { get; }
Vector2 ToRelativePosition(Vector2 worldPosition);
void BeginDrawingShadowCasters();
void EndDrawingShadowCasters();
void SetMask(string mask);
}
}

View File

@@ -1,12 +0,0 @@
using SS14.Shared;
namespace SS14.Client.Interfaces.Lighting
{
public interface LightMode
{
LightModeClass LightModeClass { get; set; }
void OnAdd(ILight owner);
void OnRemove(ILight owner);
void Update(ILight owner, float frametime);
}
}

View File

@@ -6,6 +6,7 @@ using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using System;
using Vector2i = SS14.Shared.Maths.Vector2i;
using SS14.Shared.Map;
namespace SS14.Client.Interfaces.Placement
{
@@ -24,7 +25,7 @@ namespace SS14.Client.Interfaces.Placement
void ToggleEraser();
void Rotate();
void Update(Vector2i mouseScreen, IMapManager currentMap);
void Update(ScreenCoordinates mouseScreen);
void HandleNetMessage(NetIncomingMessage msg);
}
}

View File

@@ -16,7 +16,7 @@ namespace SS14.Client.Interfaces.Player
IEntity ControlledEntity { get; }
event EventHandler<TypeEventArgs> RequestedStateSwitch;
event EventHandler<VectorEventArgs> OnPlayerMove;
event EventHandler<MoveEventArgs> OnPlayerMove;
void Attach(IEntity newEntity);
void Detach();

View File

@@ -1,5 +1,6 @@
using SFML.Graphics;
using SS14.Client.Graphics.Shader;
using SS14.Client.Graphics.Sprite;
using SS14.Client.ResourceManagement;
using SS14.Shared.GameObjects;
using System.Collections.Generic;
@@ -15,7 +16,7 @@ namespace SS14.Client.Interfaces.Resource
GLSLShader GetShader(string key);
TechniqueList GetTechnique(string key);
ParticleSettings GetParticles(string key);
object GetAnimatedSprite(string key);
AnimatedSprite GetAnimatedSprite(string key);
void LoadLocalResources();
void LoadBaseResources();
/// <summary>

View File

@@ -1,92 +0,0 @@
using OpenTK;
using SFML.Graphics;
using SFML.System;
using SS14.Client.Interfaces.Lighting;
using SS14.Shared;
using SS14.Shared.Maths;
namespace SS14.Client.Lighting
{
public class Light : ILight
{
public Light()
{
Radius = 256;
LightState = LightState.On;
}
#region ILight Members
public Vector2 Position { get; private set; }
public Color Color { get; private set; }
public int Radius { get; private set; }
public ILightArea LightArea { get; private set; }
public LightState LightState { get; private set; }
public LightMode LightMode { get; set; }
public void Move(Vector2 toPosition)
{
Position = toPosition;
LightArea.Calculated = false;
}
public void SetRadius(int radius)
{
if (Radius != radius)
{
Radius = radius;
LightArea = new LightArea(RadiusToShadowMapSize(radius));
}
}
public void SetColor(int a, int r, int g, int b)
{
Color = new Color((byte)r, (byte)g, (byte)b, (byte)a);
}
public void SetColor(Color color)
{
Color = color;
}
public Vector4 GetColorVec()
{
return new Vector4((float) Color.R/255, (float) Color.G/255, (float) Color.B/255, (float) Color.A/255);
}
public void SetMask(string mask)
{
LightArea.SetMask(mask);
}
public void Update(float frametime)
{
if (LightMode != null) LightMode.Update(this, frametime);
}
public void SetState(LightState state)
{
LightState = state;
LightArea.Calculated = false;
}
#endregion
public static ShadowmapSize RadiusToShadowMapSize(int Radius)
{
switch (Radius)
{
case 128:
return ShadowmapSize.Size128;
case 256:
return ShadowmapSize.Size256;
case 512:
return ShadowmapSize.Size512;
case 1024:
return ShadowmapSize.Size1024;
default:
return ShadowmapSize.Size1024;
}
}
}
}

View File

@@ -1,112 +0,0 @@
using OpenTK;
using SFML.Graphics;
using SFML.System;
using SS14.Client.Graphics;
using SS14.Client.Graphics.Render;
using SS14.Client.Interfaces.Lighting;
using SS14.Client.Interfaces.Resource;
using SS14.Shared.IoC;
using SS14.Shared.Maths;
namespace SS14.Client.Lighting
{
public class LightArea : ILightArea
{
public RenderImage RenderTarget { get; private set; }
/// <summary>
/// World position coordinates of the light's center
/// </summary>
public Vector2 LightPosition { get; set; }
public Vector2 LightAreaSize { get; set; }
public bool Calculated { get; set; }
public Sprite Mask { get; set; }
public bool MaskFlipX { get; set; }
public bool MaskFlipY { get; set; }
public bool Rot90 { get; set; }
public Vector4 MaskProps
{
get
{
if (Rot90 && MaskFlipX && MaskFlipY)
return maskPropsVec(false, false, false);
else if (Rot90 && MaskFlipX && !MaskFlipY)
return maskPropsVec(true, false, true);
else if (Rot90 && !MaskFlipX && MaskFlipY)
return maskPropsVec(true, true, false);
else if (Rot90 && !MaskFlipX && !MaskFlipY)
return maskPropsVec(true, false, false);
else if (!Rot90 && MaskFlipX && MaskFlipY)
return maskPropsVec(false, true, true);
else if (!Rot90 && MaskFlipX && !MaskFlipY)
return maskPropsVec(false, true, false);
else if (!Rot90 && !MaskFlipX && MaskFlipY)
return maskPropsVec(false, false, true);
else
return maskPropsVec(false, false, false);
}
}
public LightArea(int size)
{
int baseSize = 2 << (int) size;
LightAreaSize = new Vector2(baseSize, baseSize);
RenderTarget = new RenderImage("LightArea"+ size, (uint)baseSize, (uint)baseSize);
Mask = IoCManager.Resolve<IResourceCache>().GetSprite("whitemask");
}
public LightArea(ShadowmapSize shadowmapSize)
{
int baseSize = 2 << (int)shadowmapSize;
LightAreaSize = new Vector2(baseSize, baseSize);
RenderTarget = new RenderImage("LightArea"+ shadowmapSize,(uint)baseSize, (uint)baseSize);
Mask = IoCManager.Resolve<IResourceCache>().GetSprite("whitemask");
}
#region ILightArea Members
public Vector2 ToRelativePosition(Vector2 worldPosition)
{
return worldPosition - (CluwneLib.WorldToScreen(LightPosition) - LightAreaSize * 0.5f);
}
public void BeginDrawingShadowCasters()
{
RenderTarget.BeginDrawing();
RenderTarget.Clear(new SFML.Graphics.Color(0, 0, 0, 0));
}
public void EndDrawingShadowCasters()
{
RenderTarget.EndDrawing();
}
public void SetMask(string mask)
{
Mask = IoCManager.Resolve<IResourceCache>().GetSprite(mask);
}
#endregion
private Vector4 maskPropsVec(bool rot, bool flipx, bool flipy)
{
return new Vector4(rot ? 1 : 0, flipx ? 1 : 0, flipy ? 1 : 0, 0);
}
}
}

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