moved much of UI to lua scripts. applied various bugfixes

This commit is contained in:
j0sh.oleary11
2020-11-30 06:15:01 -08:00
parent 0236a6fd59
commit 9246df59a4
256 changed files with 4463 additions and 2133 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@@ -0,0 +1,24 @@
{
"Lua.diagnostics.globals": [
"import",
"UIRoot",
"MultiplayerInputHistory",
"Label",
"script",
"Color",
"GameFonts",
"UICoords",
"Vector2",
"TextYAlignment",
"TextXAlignment",
"menumanager",
"TextButton",
"game",
"TextInputLabel",
"UIListContainer",
"UIRect",
"Globals",
"OperatingSystem",
"UITheme"
]
}

View File

@@ -0,0 +1,22 @@
local compiledLogs = {};
for _,update in pairs(Globals.UpdateLog) do
compiledLogs.Add(">>" .. update.UpdateName);
compiledLogs.Add("version " .. update.VersionString);
compiledLogs.Add("" .. update.Date);
compiledLogs.Add(">Change log:");
for t in list(update.ChangeLog) do
compiledLogs.Add(t);
end
--update.ChangeLog.ForEach(t => compiledLogs.Add(t));
compiledLogs.Add(">Additional notes:");
--update.Notes.ForEach(t => compiledLogs.Add(t));
for tn in list(update.Notes) do
compiledLogs.Add(tn);
end
end
return compiledLogs;

View File

@@ -0,0 +1,26 @@
import ('MonoGame.Framework', 'Microsoft.Xna.Framework')
import ('CaveGame', 'CaveGame.Client')
import ('CaveGame', 'CaveGame.Client.UI')
import ('CaveGame', 'CaveGame.Core')
import ('System', 'System.Collections.Generic')
local compiledLogs = {};
for update in list(Globals.UpdateLog) do
table.insert(compiledLogs, ">>" .. update.UpdateName);
table.insert(compiledLogs, "version " .. update.VersionString);
table.insert(compiledLogs, "" .. update.Date);
table.insert(compiledLogs, ">Change log:");
for t in list(update.ChangeLog) do
table.insert(compiledLogs, t);
end
--update.ChangeLog.ForEach(t => compiledLogs.Add(t));
table.insert(compiledLogs, ">Additional notes:");
--update.Notes.ForEach(t => compiledLogs.Add(t));
for tn in list(update.Notes) do
table.insert(compiledLogs, tn);
end
end
return compiledLogs;

View File

@@ -0,0 +1,98 @@
import ('MonoGame.Framework', 'Microsoft.Xna.Framework')
import ('CaveGame', 'CaveGame.Client')
import ('CaveGame', 'CaveGame.Client.UI')
import ('CaveGame', 'CaveGame.Client.Menu')
import('CaveGame', 'CaveGame.Core')
local credits = {
">>CAVE GAME",
"",
">Josh O'Leary",
"Programming, Game Design",
"",
">invinciblespeed",
"Art",
"",
">Tyler Stewart",
"Biz",
"",
">Contributing Developers",
"dodeadam - Programming",
"ConcurrentSquared - Programming & Design",
"Mescalyne - Music",
"Bumpylegoman02 - Security Testing & Design",
"WheezyBackports - Community Multiplayer Servers",
"",
">Testing",
"Andrew J.",
"squidthonkv2",
"Billy J.",
"WheezyBackports",
"",
"Copyright Conarium Software 2020",
}
local CreditsPage = UIRoot();
local creditslist = UIRect(script,
{
Size = UICoords(0, 0, 1.0, 1.0),
Position = UICoords(0, 0, 0, 0),
Parent = CreditsPage,
BGColor = Color.Black*0.5,
});
local backButton = TextButton(script,
{
TextColor = Color.White,
Text = "BACK",
Font = GraphicsEngine.Instance.Fonts.Arial16,
Size = UICoords(100, 30, 0, 0),
Position = UICoords(10, -30, 0, 1.0),
AnchorPoint = Vector2(0, 1),
TextWrap = true,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
Parent = creditslist,
UnselectedBGColor = Color(0.2, 0.2, 0.2),
SelectedBGColor = Color(0.1, 0.1, 0.1),
});
backButton.OnLMBClick:Bind(function(ev, mb)
menumanager.CurrentPage = menumanager.Pages["mainmenu"];
--Game.CurrentGameContext = Game.MenuContext;
end)
local container = UIListContainer();
container.Padding = 0;
container.Parent = creditslist;
for _, text in pairs(credits) do
local displayedText = text;
local font = GraphicsEngine.Instance.Fonts.Arial14;
local size = 16;
if text:find(">>") then
font = GraphicsEngine.Instance.Fonts.Arial20;
size = 24;
displayedText = text:gsub(">>", "");
elseif text:find(">") then
font = GraphicsEngine.Instance.Fonts.Arial16;
size = 20;
displayedText = text:gsub(">", "");
end
local label = Label(script,
{
TextColor = UITheme.SmallButtonTextColor,
Text = displayedText,
Font = font,
Size = UICoords(1, size, 1.0, 0),
BGColor = Color.Black * 0.0,
TextXAlign = TextXAlignment.Center,
Parent = container,
});
end
return CreditsPage;

View File

@@ -0,0 +1,14 @@
return function(text, parent)
return TextButton(script, {
Parent = parent,
Text = text,
TextColor = Color.White,
Size = UICoords(0, -10, 1, 0.125),
Font = GraphicsEngine.Instance.Fonts.Arial14,
TextWrap = false,
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
UnselectedBGColor = Color(0.05, 0.05, 0.05),
SelectedBGColor = Color(0.05, 0.05, 0.05),
})
end

View File

@@ -12,7 +12,7 @@ MainMenu.OnLoad:Bind(function(ev)
end)
MainMenu.OnUnload:Bind(function(ev)
end)
local title = Label(script, {
@@ -23,7 +23,7 @@ local title = Label(script, {
AnchorPoint = Vector2(0,0),
Position = UICoords(10,10, 0, 0),
TextColor = Color.White,
Font = GameFonts.Arial30,
Font = GraphicsEngine.Instance.Fonts.Arial30,
BorderSize = 0,
TextWrap = false,
TextXAlign = TextXAlignment.Center,
@@ -41,7 +41,7 @@ local copyright_label = Label(script, {
TextColor = Color.White,
Text = "Copyright Conarium Software 2019-2020",
BorderSize = 0,
Font = GameFonts.Arial10,
Font = GraphicsEngine.Instance.Fonts.Arial10,
TextWrap = false,
TextYAlign = TextYAlignment.Bottom,
TextXAlign = TextXAlignment.Left,
@@ -57,7 +57,7 @@ local versionTag = Label(script, {
TextColor = Color.White,
Text = "v"..Globals.CurrentVersionString,
BorderSize = 0,
Font = GameFonts.Arial10,
Font = GraphicsEngine.Instance.Fonts.Arial10,
TextWrap = false,
TextXAlign = TextXAlignment.Right,
TextYAlign = TextYAlignment.Bottom,
@@ -78,39 +78,14 @@ buttonContainer.Parent = buttonList;
-- Singleplayerbutton
local function GetButton(text)
return TextButton(script, {
Parent = buttonContainer,
Text = text,
TextColor = Color.White,
Size = UICoords(0, -10, 1, 0.125),
Font = GameFonts.Arial14,
TextWrap = false,
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
UnselectedBGColor = Color(0.2, 0.2, 0.2),
SelectedBGColor = Color(0.1, 0.1, 0.1)
})
end
local function GetInactiveButton(text)
return TextButton(script, {
Parent = buttonContainer,
Text = text,
TextColor = Color.White,
Size = UICoords(0, -10, 1, 0.125),
Font = GameFonts.Arial14,
TextWrap = false,
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
UnselectedBGColor = Color(0.05, 0.05, 0.05),
SelectedBGColor = Color(0.05, 0.05, 0.05),
})
end
local spb = GetButton("SINGLEPLAYER");
spb.OnLMBClick:Bind(function(ev, mousedata)
menumanager.CurrentPage = menumanager.Pages["creditsmenu"];
end)
local GetButton = require("Assets.Scripts.MenuScripts.MenuButton");
local GetInactiveButton = require("Assets.Scripts.MenuScripts.InactiveMenuButton");
local spb = GetInactiveButton("SINGLEPLAYER", buttonContainer);
--spb.OnLMBClick:Bind(function(ev, mousedata)
--menumanager.CurrentPage = menumanager.Pages["creditsmenu"];
--end)
-- example of 9slice
--[[local slicer = NineSlice(script, {
@@ -130,32 +105,38 @@ end)
local multiplayerButton = GetButton("MULTIPLAYER");
local multiplayerButton = GetButton("MULTIPLAYER", buttonContainer);
multiplayerButton.OnLMBClick:Bind(function(ev, mousedata)
menumanager.CurrentPage = menumanager.Pages["multiplayermenu"]
end)
local statisticsButton = GetInactiveButton("STATISTICS");
local statisticsButton = GetInactiveButton("STATISTICS", buttonContainer);
statisticsButton.OnLMBClick:Bind(function(ev, md)
end)
local steamPageButton = GetButton("STEAM WORKSHOP");
local steamPageButton = GetButton("STEAM WORKSHOP", buttonContainer);
steamPageButton.OnLMBClick:Bind(function(ev, md)
OperatingSystem.OpenUrl("https://steamcommunity.com/app/1238250");
end)
local discordButton = GetButton("DISCORD COMMUNITY");
local discordButton = GetButton("DISCORD COMMUNITY", buttonContainer);
discordButton.OnLMBClick:Bind(function (ev, md)
OperatingSystem.OpenUrl("https://discord.gg/6mDmYqs");
end)
local creditsButton = GetButton("CREDITS");
local settingsButton = GetButton("SETTINGS", buttonContainer);
settingsButton.OnLMBClick:Bind(function(ev, md)
--menumanager.CurrentPage = menumanager.Pages["mainmenu"];
game.CurrentGameContext = game.SettingsContext;
end)
local creditsButton = GetButton("CREDITS", buttonContainer);
creditsButton.OnLMBClick:Bind(function(ev, md)
menumanager.CurrentPage = menumanager.Pages["creditsmenu"];
end)
local quitButton = GetButton("QUIT");
local quitButton = GetButton("QUIT", buttonContainer);
quitButton.OnLMBClick:Bind(function(ev, md)
game:Exit();
end)
@@ -176,24 +157,24 @@ local updateLog = UIListContainer();
updateLog.Padding = 2;
updateLog.Parent = changeLogContentWindow;
local changeLogTextEntries = require("Assets.Scripts.ChangeLogGenerator")
local changeLogTextEntries = require("Assets.Scripts.MenuScripts.ChangeLogGenerator")
for _, text in pairs(changeLogTextEntries) do
local displayedText = text;
local font = GameFonts.Arial10;
local font = GraphicsEngine.Instance.Fonts.Arial10;
local size = 18;
if (text:find(">>>")) then
font = GameFonts.Arial16;
if (text:find(">>")) then
font = GraphicsEngine.Instance.Fonts.Arial16;
size = 24;
displayedText = text:gsub(">>", "");
elseif text:find(">") then
font = GameFonts.Arial14;
font = GraphicsEngine.Instance.Fonts.Arial14;
size = 16;
displayedText = text:gsub(">", "")
elseif text:find("-") then
font = GameFonts.Arial10;
font = GraphicsEngine.Instance.Fonts.Arial10;
size = 12;
end

View File

@@ -0,0 +1,14 @@
return function(text, parent)
return TextButton(script, {
Parent = parent,
Text = text,
TextColor = Color.White,
Size = UICoords(0, -10, 1, 0.125),
Font = GraphicsEngine.Instance.Fonts.Arial14,
TextWrap = false,
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
UnselectedBGColor = Color(0.2, 0.2, 0.2),
SelectedBGColor = Color(0.1, 0.1, 0.1)
})
end

View File

@@ -0,0 +1,134 @@
import ('MonoGame.Framework', 'Microsoft.Xna.Framework')
import ('CaveGame', 'CaveGame.Client')
import ('CaveGame', 'CaveGame.Client.UI')
import ('CaveGame', 'CaveGame.Client.Menu')
import ('CaveGame', 'CaveGame.Core')
local MultiplayerMenu = UIRoot();
local inputHistory = MultiplayerInputHistory.Load();
local GetButton = require("Assets.Scripts.MenuScripts.MenuButton");
local GetInactiveButton = require("Assets.Scripts.MenuScripts.InactiveMenuButton");
local title = Label(script, {
BGColor = Color.Transparent,
BorderColor = Color.Transparent,
Size = UICoords(0, 0, 0.3, 0.1),
AnchorPoint = Vector2(0.5, 0.5),
Position = UICoords(0, 0, 0.5, 0.05),
Parent = MultiplayerMenu,
TextColor = Color.White,
Text = "MULTIPLAYER",
Font = GraphicsEngine.Instance.Fonts.Arial20,
BorderSize = 0,
TextWrap = false,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
});
local buttonList = UIRect(script,
{
Size = UICoords(220, -20, 0, 0.8),
Position = UICoords(10, 0, 0, 0.1),
Parent = MultiplayerMenu,
BGColor = Color.DarkBlue,
});
local buttons = UIListContainer();
buttons.Padding = 1;
buttons.Parent = buttonList;
local serverInputBox = TextInputLabel(script, {
Size = UICoords(0, 30, 1, 0),
AnchorPoint = Vector2(0, 0),
Parent = buttons,
BGColor = Color(0.2, 0.2, 0.3),
BorderColor = Color.DarkBlue,
Font = GraphicsEngine.Instance.Fonts.Arial12,
BackgroundText = "Server Address",
BackgroundTextColor = Color.Gray,
TextColor = Color.White,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
});
serverInputBox.Input.InputBuffer = inputHistory.IPAddress;
serverInputBox.Input.Focused = false;
serverInputBox.Input.CursorPosition = inputHistory.IPAddress.Length;
local usernameInputBox = TextInputLabel(script, {
Size = UICoords(0, 30, 1, 0),
AnchorPoint = Vector2(0, 0),
Parent = buttons,
Font = GraphicsEngine.Instance.Fonts.Arial12,
BGColor = Color(0.2, 0.2, 0.3),
BorderColor = Color.DarkBlue,
BackgroundText = "Nickname",
BackgroundTextColor = Color.Gray,
TextColor = Color.White,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
});
usernameInputBox.Input.InputBuffer = inputHistory.Username;
usernameInputBox.Input:BlacklistCharacter(' ');
usernameInputBox.Input.Focused = true;
local function Timeout(message)
menumanager.CurrentPage = menumanager.Pages["timeout"];
menumanager.Pages["timeout"].Message = message;
end
local function OnJoinServer(address, username)
if address == "localhost" then
address = "127.0.0.1";
end
if not address:find(":") then
address = address .. ":40269"
end
if #address == 0 then
Timeout("Server Address is empty! Please enter a valid IP Address!");
return;
end
if #username == 0 then
Timeout("Please enter a nickname!");
return;
end
game.CurrentGameContext = game.GameClientContext;
game.GameClientContext.NetworkUsername = username;
game.GameClientContext.ConnectAddress = address;
inputHistory.IPAddress = address;
inputHistory.Username = username;
inputHistory:Save();
end
local connect = GetButton("CONNECT", buttons)
connect.OnLMBClick:Bind(function(ev, mb)
OnJoinServer(serverInputBox.Input.InternalText, usernameInputBox.Input.InternalText);
end)
local back = TextButton(script, {
Size = UICoords(0, 30, 1, 0),
Parent = buttons,
Text = "BACK",
Font = GraphicsEngine.Instance.Fonts.Arial14,
BorderSize = 0,
TextColor = Color.White,
TextWrap = false,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
UnselectedBGColor = Color(0.2, 0.2, 0.2),
SelectedBGColor = Color(0.1, 0.1, 0.1),
});
back.OnLMBClick:Bind(function(ev, mb)
menumanager.CurrentPage = menumanager.Pages["mainmenu"];
end)
return MultiplayerMenu;

View File

@@ -17,14 +17,14 @@ MainMenu.OnUnload:Bind(function(ev)
end)
local title = Label(script, {
Parent = menu,
Parent = MainMenu,
Text = 'CAVE GAME',
BGColor = Color.Transparent,
Size = UICoords(220, -20, 0, 0.1),
AnchorPoint = Vector2(0,0),
Position = UICoords(10,10, 0, 0),
TextColor = Color.White,
Font = GameFonts.Arial30,
Font = GraphicsEngine.Instance.Fonts.Arial30,
BorderSize = 0,
TextWrap = false,
TextXAlign = TextXAlignment.Center,
@@ -38,11 +38,11 @@ local copyright_label = Label(script, {
Size = UICoords(200, 10, 0, 0),
AnchorPoint = Vector2(0, 1),
Position = UICoords(10, 0, 0, 1),
Parent = menu,
Parent = MainMenu,
TextColor = Color.White,
Text = "Copyright Conarium Software 2019-2020",
BorderSize = 0,
Font = GameFonts.Arial10,
Font = GraphicsEngine.Instance.Fonts.Arial10,
TextWrap = false,
TextYAlign = TextYAlignment.Bottom,
TextXAlign = TextXAlignment.Left,
@@ -58,7 +58,7 @@ local versionTag = Label(script, {
TextColor = Color.White,
Text = "v"..Globals.CurrentVersionString,
BorderSize = 0,
Font = GameFonts.Arial10,
Font = GraphicsEngine.Instance.Fonts.Arial10,
TextWrap = false,
TextXAlign = TextXAlignment.Right,
TextYAlign = TextYAlignment.Bottom,
@@ -85,7 +85,7 @@ local function GetButton(text)
Text = text,
TextColor = Color.White,
Size = UICoords(0, -10, 1, 0.125),
Font = GameFonts.Arial14,
Font = GraphicsEngine.Instance.Fonts.Arial14,
TextWrap = false,
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,

View File

@@ -0,0 +1,34 @@
import ('MonoGame.Framework', 'Microsoft.Xna.Framework')
import ('CaveGame', 'CaveGame.Client')
import ('CaveGame', 'CaveGame.Client.UI')
import ('CaveGame', 'CaveGame.Client.Menu')
import ('CaveGame', 'CaveGame.Core')
local TimeoutPage = UIRoot();
local message = Label(script,
{
BGColor = Color.Transparent,
BorderColor = Color.Transparent,
Size = UICoords(0, 0, 1.0, 0.1),
AnchorPoint = Vector2(0.5, 0.5),
Position = UICoords(0, 0, 0.5, 0.3),
Parent = TimeoutPage,
Text = menumanager.TimeoutMessage,
TextColor = Color.White,
Font = GraphicsEngine.Instance.Fonts.Arial16,
BorderSize = 0,
TextWrap = false,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
});
local GetButton = require("Assets.Scripts.MenuScripts.MenuButton");
local GetInactiveButton = require("Assets.Scripts.MenuScripts.InactiveMenuButton");
local back = GetButton("BACK", TimeoutPage)
back.OnLMBClick:Bind(function(ev, mb)
menumanager.CurrentPage = menumanager.Pages["mainmenu"];
end)
return TimeoutPage;

View File

@@ -2,10 +2,16 @@
import ('CaveGame', 'CaveGame.Client')
import ('CaveGame', 'CaveGame.Client.UI')
local MainMenu = require("Assets.Scripts.MainMenu")
local MultiplayerMenu = require("Assets.Scripts.MultiplayerMenu")
local MainMenu = require("Assets.Scripts.MenuScripts.MainMenu")
local MultiplayerMenu = require("Assets.Scripts.MenuScripts.MultiplayerMenu")
local TimeoutMenu = require("Assets.Scripts.MenuScripts.TimeoutMenu")
local SingleplayerMenu = require("Assets.Scripts.MenuScripts.SingleplayerMenu")
local CreditsMenu = require("Assets.Scripts.MenuScripts.CreditsMenu")
menumanager.Pages:Add("mainmenu", MainMenu);
menumanager.Pages:Add("multiplayermenu", MultiplayerMenu);
menumanager.Pages:Add("timeoutmenu", TimeoutMenu);
menumanager.Pages:Add("singleplayermenu", SingleplayerMenu);
menumanager.Pages:Add("creditsmenu", CreditsMenu);
menumanager.CurrentPage = MainMenu;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 39 KiB

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net5.0</TargetFramework>
<PublishReadyToRun>false</PublishReadyToRun>
<TieredCompilation>false</TieredCompilation>
<Platforms>AnyCPU;x86</Platforms>

View File

@@ -9,16 +9,11 @@ using CaveGame.Core.FileUtil;
using System.IO;
using Microsoft.Xna.Framework.Input;
using System.Globalization;
using CaveGame.Core.Network;
using CaveGame.Core.Generic;
namespace CaveGame.Client
{
public static class GameGlobals
{
public static int Width;
public static int Height;
public static GraphicsDevice GraphicsDevice;
}
public class CaveGameGL : Microsoft.Xna.Framework.Game
{
public GameSettings GameSettings { get; set; }
@@ -27,24 +22,24 @@ namespace CaveGame.Client
private IGameContext PreviousGameContext { get; set; }
#region Game States
public GameClient InWorldContext;
public Menu.MenuManager HomePageContext;
public Menu.Multiplayer MultiplayerPageContext;
public GameClient GameClientContext;
public Menu.MenuManager MenuContext;
public Menu.Settings SettingsContext;
public Menu.TimeoutMenu TimeoutContext;
public Menu.Credits CreditsContext;
#endregion
public GraphicsEngine GraphicsEngine { get; private set; }
public GraphicsDeviceManager GraphicsDeviceManager { get; private set; }
public SpriteBatch SpriteBatch { get; private set; }
#region GameComponents
public CommandBar Console { get; private set; }
public FPSGraph FPSGraph { get; private set; }
public FrameCounter FPSCounter { get; private set; }
public Splash Splash { get; private set; }
#endregion
public static float ClickTimer;
public SteamManager SteamManager { get; private set; }
public void OnSetFPSLimit(int limit)
@@ -93,30 +88,35 @@ namespace CaveGame.Client
IsFullScreen = false,
PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8
};
IsMouseVisible = true;
Content.RootDirectory = "Content";
Window.AllowUserResizing = true;
Window.AllowAltF4 = true;
GraphicsEngine = new GraphicsEngine();
Splash = new Splash();
#if DEBUG
GraphicsEngine.LoadingDelay = 0.05f;
Splash.SplashTimer = 5f;
#endif
OnSetFPSLimit(GameSettings.FPSLimit);
}
void Window_ClientSizeChanged(object sender, EventArgs e)
{
GameGlobals.Width = Window.ClientBounds.Width;
GameGlobals.Height = Window.ClientBounds.Height;
if (InWorldContext != null)
GraphicsEngine.WindowSize = Window.ClientBounds.Size.ToVector2();
if (GameClientContext != null)
{
InWorldContext.Camera.Bounds = Window.ClientBounds;
InWorldContext.Camera._screenSize = new Vector2(Window.ClientBounds.Width, Window.ClientBounds.Height);
GameClientContext.Camera.Bounds = Window.ClientBounds;
GameClientContext.Camera._screenSize = new Vector2(Window.ClientBounds.Width, Window.ClientBounds.Height);
}
}
private void OnTestCommand(CommandBar sender, Command command, params string[] args) {}
private void OnTeleportCommand(CommandBar sender, Command command, params string[] args)
{
@@ -145,20 +145,20 @@ namespace CaveGame.Client
return;
}
if (InWorldContext.MyPlayer != null)
if (GameClientContext.MyPlayer != null)
{
InWorldContext.MyPlayer.NextPosition = new Vector2(x, y);
GameClientContext.MyPlayer.NextPosition = new Vector2(x, y);
}
}
private void OnGodCommand(CommandBar sender, Command command, params string[] args)
{
InWorldContext.MyPlayer.God = !InWorldContext.MyPlayer.God;
GameClientContext.MyPlayer.God = !GameClientContext.MyPlayer.God;
}
private void OnDisconnectCommand(CommandBar sender, Command command, params string[] args)
{
if (CurrentGameContext == InWorldContext)
if (CurrentGameContext == GameClientContext)
{
InWorldContext.OverrideDisconnect();
GameClientContext.OverrideDisconnect();
} else
{
@@ -166,14 +166,6 @@ namespace CaveGame.Client
return;
}
}
private void OnGraphCommand(CommandBar sender, Command command, params string[] args)
{
if (args.Length > 0)
{
}
}
private void OnScreenshot(CommandBar sender, Command command, params string[] args)
{
if (args.Length>0)
@@ -187,13 +179,37 @@ namespace CaveGame.Client
}
}
private void OnTimeCommand(CommandBar sender, Command command, params string[] args)
private void SendAdminCommand(string command, params string[] args) => GameClientContext.Send(new AdminCommandPacket(command, args, GameClientContext.MyPlayer.EntityNetworkID));
private void CmdTimeCommand(CommandBar sender, Command command, params string[] args)
{
if (args.Length > 0)
InWorldContext.World.TimeOfDay = float.Parse(args[0], CultureInfo.InvariantCulture.NumberFormat);
GameClientContext.World.TimeOfDay = float.Parse(args[0], CultureInfo.InvariantCulture.NumberFormat);
else
sender.Out("Time of day (hours): " + InWorldContext.World.TimeOfDay.ToString());
sender.Out("Time of day (hours): " + GameClientContext.World.TimeOfDay.ToString());
}
private void CmdRequestSummonEntity(CommandBar sender, Command command, params string[] args)
{
if (args.Length == 0) // give list of entities
{
sender.Out("Syntax: sv_summon <entity_id> <xpos> <ypos> <metadata>");
sender.Out("Entity ID list:");
sender.Out("itemstack, wurmhole");
}
else
{
SendAdminCommand(command.Keyword, args);
}
}
private void CmdRequestItemstack(CommandBar sender, Command command, params string[] args)
{
if (args.Length == 0)
{
}
else
SendAdminCommand(command.Keyword, args);
}
protected override void Initialize()
@@ -204,57 +220,60 @@ namespace CaveGame.Client
Console = new CommandBar(this);
Console.BindCommandInformation(new Command("test", "it does a thing", new List<string>{"argA", "argB", "argC"}, OnGodCommand));
Console.BindCommandInformation(new Command("teleport", "", new List<string> { "x", "y" }, OnTeleportCommand));
Console.BindCommandInformation(new Command("god", "AAOKSOKADFOS", new List<string> {}, OnGodCommand));
Console.BindCommandInformation(new Command("disconnect", "", new List<string> { }, OnDisconnectCommand));
Console.BindCommandInformation(new Command("connect", "", new List<string> { }, OnDisconnectCommand));
Console.BindCommandInformation(new Command("graph", "", new List<string> { }, OnGraphCommand));
Console.BindCommandInformation(new Command("screen", "", new List<string> { }, OnScreenshot));
Console.BindCommandInformation(new Command("time", "Set/Get time of day", new List<string> { "time" }, OnTimeCommand));
//Console.Handler += CommandBarEvent;
// epic new .NET 5 feature
Command[] commands =
{
new ("teleport", "", new List<string> { "x", "y" }, OnTeleportCommand),
new ("god", "", new List<string> {}, OnGodCommand),
new ("disconnect", "", new List<string> { }, OnDisconnectCommand),
new ("connect", "", new List<string> { }, OnDisconnectCommand),
new ("screenshot", "", new List<string> { }, OnScreenshot),
new ("time", "Set/Get time of day", new List<string> { "time" }, CmdTimeCommand),
new ("sv_summon", "Summon an entity", new List<string>{"entityid, xpos, ypos, metadatastring" }, CmdRequestSummonEntity)
};
foreach (var command in commands)
Console.BindCommandInformation(command);
Components.Add(Console);
FPSCounter = new FrameCounter(this);
Components.Add(FPSCounter);
FPSGraph = new FPSGraph(this, 25, 500);
Components.Add(FPSGraph);
SteamManager.Initialize();
Components.Add(SteamManager);
GameGlobals.Width = Window.ClientBounds.Width;
GameGlobals.Height = Window.ClientBounds.Height;
GameGlobals.GraphicsDevice = GraphicsDeviceManager.GraphicsDevice;
base.Initialize();
}
private void CreateGameStates()
{
HomePageContext = new MenuManager(this);
InWorldContext = new GameClient(this);
CreditsContext = new Credits(this);
MultiplayerPageContext = new Multiplayer(this);
TimeoutContext = new TimeoutMenu(this);
MenuContext = new MenuManager(this);
GameClientContext = new GameClient(this);
SettingsContext = new Settings(this);
Window.TextInput += SettingsContext.OnTextInput;
CurrentGameContext = HomePageContext;
CurrentGameContext = MenuContext;
}
protected override void LoadContent()
{
SpriteBatch = new SpriteBatch(GraphicsDevice);
Renderer.Initialize(this);
GameFonts.LoadAssets(Content);
GameSounds.LoadAssets(Content);
GameTextures.LoadAssets(GraphicsDevice);
ItemTextures.LoadAssets(GraphicsDevice);
GraphicsEngine.ContentManager = Content;
GraphicsEngine.GraphicsDevice = GraphicsDevice;
GraphicsEngine.GraphicsDeviceManager = GraphicsDeviceManager;
GraphicsEngine.Initialize();
GraphicsEngine.LoadAssets(GraphicsDevice);
//GameTextures.LoadAssets(GraphicsDevice);
//ItemTextures.LoadAssets(GraphicsDevice);
CreateGameStates();
}
float splashTimer = 3;
public void TakeScreenshot(string filename = "")
{
@@ -285,14 +304,24 @@ namespace CaveGame.Client
KeyboardState previousKB = Keyboard.GetState();
protected override void Update(GameTime gameTime)
{
// update graphics information
GraphicsEngine.WindowSize = Window.ClientBounds.Size.ToVector2();
GraphicsEngine.Update(gameTime);
if (!GraphicsEngine.ContentLoaded)
return;
if (Splash.SplashActive)
{
Splash.Update(gameTime);
//return;
}
KeyboardState currentKB = Keyboard.GetState();
if (currentKB.IsKeyDown(Keys.F5) && !previousKB.IsKeyDown(Keys.F5)) {
TakeScreenshot();
}
splashTimer -= (float)gameTime.ElapsedGameTime.TotalSeconds;
if (CurrentGameContext != PreviousGameContext && PreviousGameContext != null)
{
PreviousGameContext.Unload();
@@ -315,70 +344,85 @@ namespace CaveGame.Client
private void DrawDebugOverlay()
{
SpriteBatch.Begin();
SpriteBatch.Print(Color.White, new Vector2(2, 0), String.Format("fps: {0} ", Math.Floor(FPSCounter.GetAverageFramerate())));
SpriteBatch.End();
GraphicsEngine.Begin();
GraphicsEngine.Text(String.Format("fps: {0} ", Math.Floor(FPSCounter.GetAverageFramerate())), new Vector2(2, 0));
GraphicsEngine.End();
}
protected override void OnExiting(object sender, EventArgs args)
{
GameSettings.Save();
InWorldContext.Disconnect();
GameClientContext.Disconnect();
SteamManager.Shutdown();
base.OnExiting(sender, args);
}
private void DrawSplash()
{
private void DrawLoadingBar(GraphicsEngine GFX)
{
if (!GFX.FontsLoaded)
return;
float frac = (float)GFX.LoadedTextures / (float)GFX.TotalTextures;
string text = String.Format("Loading: {0} of {1} ({2}%)", GFX.LoadedTextures, GFX.TotalTextures, (int)(frac*100));
GFX.GraphicsDevice.Clear(Color.Black);
GFX.Begin();
GFX.Text(GFX.Fonts.Arial20, text, GFX.WindowSize / 2.0f, Color.White, TextXAlignment.Center, TextYAlignment.Center);
float barY = (GFX.WindowSize.Y / 2.0f) + 20.0f;
float barX = GFX.WindowSize.X / 2.0f;
float barLength = GFX.WindowSize.X / 3.0f;
float barHeight = 10.0f;
Vector2 center = new Vector2(barX, barY);
GraphicsDevice.Clear(Color.Black);
SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp);
Vector2 center = new Vector2(GameGlobals.Width / 2.0f, GameGlobals.Height / 2.0f);
Vector2 origin = new Vector2(GameTextures.EyeOfHorus.Width / 2.0f, GameTextures.EyeOfHorus.Height / 2.0f);
float scale = 8;
Vector2 bounds = GameFonts.Arial30.MeasureString("CONARIUM SOFTWARE");
SpriteBatch.Draw(GameTextures.EyeOfHorus, center-new Vector2(0, (float)Math.Sin(splashTimer*2)*10), null, Color.White, 0, origin, scale, SpriteEffects.None, 0);
SpriteBatch.Print(GameFonts.Arial30, Color.White, center - new Vector2(bounds.X/2, -bounds.Y*2), "CONARIUM SOFTWARE");
SpriteBatch.End();
}
GFX.Rect(
Color.Gray,
center - new Vector2(barLength/2.0f, 0),
new Vector2(barLength, barHeight)
);
GFX.Rect(
Color.White,
center - new Vector2(barLength / 2.0f, 0),
new Vector2(barLength*frac, barHeight)
);
GFX.End();
}
protected override void Draw(GameTime gameTime)
{
if (!GameTextures.ContentLoaded)
return;
if (splashTimer > 0)
{
DrawSplash();
if (!GraphicsEngine.ContentLoaded)
{
DrawLoadingBar(GraphicsEngine);
return;
}
if (Splash.SplashActive)
{
Splash.Draw(GraphicsEngine);
return;
}
GraphicsDevice.Clear(Color.Black);
GraphicsEngine.Clear(Color.Black);
GraphicsEngine.Begin();
SpriteBatch.Begin();
Vector2 center = new Vector2(GameGlobals.Width / 2.0f, GameGlobals.Height / 2.0f);
Vector2 origin = new Vector2(GameTextures.BG.Width / 2.0f, GameTextures.BG.Height / 2.0f);
float horizscale = GameGlobals.Width / (float)GameTextures.BG.Width;
float vertscale = GameGlobals.Height / (float)GameTextures.BG.Height;
Vector2 center = GraphicsEngine.WindowSize / 2.0f;
Vector2 origin = new Vector2(GraphicsEngine.BG.Width, GraphicsEngine.BG.Height) / 2.0f;
float horizscale = GraphicsEngine.WindowSize.X / (float)GraphicsEngine.BG.Width;
float vertscale = GraphicsEngine.WindowSize.Y / (float)GraphicsEngine.BG.Height;
float scale = Math.Max(horizscale, vertscale);
SpriteBatch.Draw(GameTextures.BG, center, null, Color.White, 0, origin, scale, SpriteEffects.None, 0);
SpriteBatch.End();
GraphicsEngine.Sprite(GraphicsEngine.BG, center, null, Color.White, Rotation.Zero, origin, scale, SpriteEffects.None, 0);
GraphicsEngine.End();
if (CurrentGameContext.Active == true)
{
CurrentGameContext.Draw(SpriteBatch);
}
FPSGraph.Draw(SpriteBatch);
CurrentGameContext.Draw(GraphicsEngine);
DrawDebugOverlay();
Console.Draw(SpriteBatch);
Console.Draw(GraphicsEngine);
base.Draw(gameTime);
}
}

132
CaveGL/CrashReport.cs Normal file
View File

@@ -0,0 +1,132 @@
using CaveGame.Client;
using CaveGame.Core;
using System;
using System.IO;
namespace Cave
{
public class CrashReport
{
CaveGameGL Game;
Exception Exception;
public bool ReuseSingleCrashFile { get; set; }
public CrashReport(CaveGameGL game, Exception e)
{
Game = game;
Exception = e;
#if DEBUG
ReuseSingleCrashFile = true;
#else
ReuseSingleCrashFile = false;
#endif
}
public void GenerateHTMLReport()
{
string crashReportHTML =
@"
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #cccccc;
text: black;
}
.data {
border: 3px outset black;
background-color: white;
color: black;
text-align: left;
font-family: monospace;
}
</style>
" + @$"
<title>CaveGame Crash Report</title>
</head>
<body>
<h3>CaveGame Crash Report </h3>
<p>CaveGame has experienced a fatal crash! This file has been generated to document the error, and make reporting bugs to the devs easy.</p>
<p>Please consider sending this report to us. It helps us tremendously when tracking down bugs.</p>
<p>You can send this to us via Discord, Steam, or Twitter</p>
<p>Game Details:</p>
<p>Exception message: </p>
<div class='data'><p>{Exception.Message.Replace(" at", "<br/>at")}</p></div>
<p>StackTrace:</p>
<div class='data'><p>{Exception.StackTrace.Replace(" at", "<br/>at")}</p></div>
<p>Collected Data:</p>
<div class='data'><p>
GameVersion: {Globals.CurrentVersionFullString} <br/>
NetworkProtocolVersion: {Globals.ProtocolVersion} <br/>
TextureLoadSuccess: {GraphicsEngine.Instance.ContentLoaded} <br/>
TextureCount: {GraphicsEngine.Instance.Textures.Count} <br/>
Steam Enabled: {Game.SteamManager.Enabled}<br/>
Average Recent Framerate: {Game.FPSCounter.GetAverageFramerate()}<br/>
Exact Framerate: {Game.FPSCounter.GetExactFramerate()}<br/>
IsOS64Bit: {Environment.Is64BitOperatingSystem} <br/>
OperatingSystem: {Environment.OSVersion.Platform} <br/>
OSVersion: {Environment.OSVersion.VersionString} <br/>
Architecture: {Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")} <br/>
ProcessorID: {Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER")} <br/>
ProcessorLevel: {Environment.GetEnvironmentVariable("PROCESSOR_LEVEL")} <br/>
IsCaveGame64Bit: {Environment.Is64BitProcess} <br/>
CLRVersion: {Environment.Version} <br/>
WorkingSet: {Environment.WorkingSet} <br/>
ProcessorCount: {Environment.ProcessorCount} <br/>
SystemUptime: {Environment.TickCount64} <br/>
UserName: {Environment.UserName} <br/>
OSVersion: {Environment.OSVersion.VersionString} <br/>
ScrDeviceName: {Game.Window.ScreenDeviceName} <br/>
ScrDeviceName: {Game.Window.ScreenDeviceName} <br/>
GraphicsDeviceStatus: {Game.GraphicsDevice.GraphicsDeviceStatus} <br/>
GraphicsProfile: {Game.GraphicsDevice.GraphicsProfile} <br/>
GraphicsDebug: {Game.GraphicsDevice.GraphicsDebug} <br/>
HardwareModeSwitch: {Game.GraphicsDeviceManager.HardwareModeSwitch} <br/>
DesireVSync: {Game.GraphicsDeviceManager.SynchronizeWithVerticalRetrace} <br/>
GraphicsProfile: {Game.GraphicsDevice.GraphicsProfile} <br/>
GraphicsDebug: {Game.GraphicsDevice.GraphicsDebug} <br/>
Window Dimensions: {Game.Window.ClientBounds.Width}x{Game.Window.ClientBounds.Height} <br/>
In World: {Game.GameClientContext?.Active}<br/>
Connection Address: {Game.GameClientContext?.ConnectAddress}<br/>
Username: {Game.GameClientContext?.NetworkUsername}<br/>
Entity Count: {Game.GameClientContext?.World.Entities.Count}<br/>
Chunks Loaded: {Game.GameClientContext?.World.Chunks.Count}<br/>
Chunks Awaiting: {Game.GameClientContext?.World.RequestedChunks.Count}<br/>
Lighting Thread Status: {Game.GameClientContext?.World.Lighting.LightThread.ThreadState}<br/>
Window Dimensions: {Game.Window.ClientBounds.Width}x{Game.Window.ClientBounds.Height} <br/>
Screen Dimensions: {Game.GraphicsDeviceManager.GraphicsDevice.Adapter.CurrentDisplayMode.Width}x{Game.GraphicsDeviceManager.GraphicsDevice.Adapter.CurrentDisplayMode.Height}<br/>
Fullscreen: {Game.GraphicsDeviceManager.IsFullScreen}<br/>
Settings.FPSLimit: {Game.GameSettings.FPSLimit}<br/>
Settings.CameraShake: {Game.GameSettings.CameraShake}<br/>
Settings.ParticlesEnabled: {Game.GameSettings.Particles}<br/>
Game Context: {Game.CurrentGameContext}<br/>
<p></div>
</body>
</html>
";
if (ReuseSingleCrashFile)
{
string name = "crash.html";//$"crash_{DateTime.Now.ToString("MM-dd-yy-HH-mm-ss")}.html";
File.WriteAllText(name, crashReportHTML);
CaveGame.Core.OperatingSystem.OpenUrl(Path.GetFullPath(name));
} else {
string name = $"crash_{DateTime.Now.ToString("MM-dd-yy-HH-mm-ss")}.html";
File.WriteAllText(name, crashReportHTML);
CaveGame.Core.OperatingSystem.OpenUrl(Path.GetFullPath(name));
}
}
}
}

View File

@@ -1,13 +1,11 @@
using CaveGame.Client;
using CaveGame.Core;
using CaveGame.Core.Game.Tiles;
using System;
using System.Diagnostics;
using System.IO;
namespace Cave
{
public static class Program
public static class Program
{
[STAThread]
@@ -16,87 +14,25 @@ namespace Cave
Tile.AssertTileEnumeration();
using (var game = new CaveGameGL())
{
#if !DEBUG
try
{
game.Run();
game.Exit();
} catch(Exception e)
{
string crashReportHTML =
@"
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #cccccc;
text: black;
}
.data {
border: 3px outset black;
background-color: white;
color: black;
text-align: left;
font-family: monospace;
}
</style>
" + @$"
<title>CaveGame Crash Report</title>
</head>
<body>
<h3>CaveGame Crash Report </h3>
<p>CaveGame has experienced a fatal crash! This file has been generated to document the error, and make reporting bugs to the devs easy.</p>
<p>Game Details:</p>
<p>Exception message: </p>
<div class='data'><p>{e.Message.Replace("at", "<br/>at")}</p></div>
<p>StackTrace:</p>
<div class='data'><p>{e.StackTrace.Replace("at", "<br/>at")}</p></div>
<p>Collected Data:</p>
<div class='data'><p>
GameVersion: {Globals.CurrentVersionFullString} <br/>
NetworkProtocolVersion: {Globals.ProtocolVersion} <br/>
TextureLoadSuccess: {GameTextures.ContentLoaded} <br/>
TextureCount: {GameTextures.Textures.Count} <br/>
Steam Enabled: {game.SteamManager.Enabled}<br/>
Average Recent Framerate: {game.FPSCounter.GetAverageFramerate()}<br/>
Exact Framerate: {game.FPSCounter.GetExactFramerate()}<br/>
ScrDeviceName: {game.Window.ScreenDeviceName} <br/>
GraphicsDeviceStatus: {game.GraphicsDevice.GraphicsDeviceStatus} <br/>
GraphicsProfile: {game.GraphicsDevice.GraphicsProfile} <br/>
GraphicsDebug: {game.GraphicsDevice.GraphicsDebug} <br/>
HardwareModeSwitch: {game.GraphicsDeviceManager.HardwareModeSwitch} <br/>
DesireVSync: {game.GraphicsDeviceManager.SynchronizeWithVerticalRetrace} <br/>
GraphicsProfile: {game.GraphicsDevice.GraphicsProfile} <br/>
GraphicsDebug: {game.GraphicsDevice.GraphicsDebug} <br/>
Window Dimensions: {game.Window.ClientBounds.Width}x{game.Window.ClientBounds.Height} <br/>
In World: {game.InWorldContext?.Active}<br/>
Connection Address: {game.InWorldContext?.ConnectAddress}<br/>
Username: {game.InWorldContext?.NetworkUsername}<br/>
Entity Count: {game.InWorldContext?.World.Entities.Count}<br/>
Chunks Loaded: {game.InWorldContext?.World.Chunks.Count}<br/>
Chunks Awaiting: {game.InWorldContext?.World.RequestedChunks.Count}<br/>
Lighting Thread Status: {game.InWorldContext?.World.Lighting.LightThread.ThreadState}<br/>
Window Dimensions: {game.Window.ClientBounds.Width}x{game.Window.ClientBounds.Height} <br/>
Screen Dimensions: {game.GraphicsDeviceManager.GraphicsDevice.Adapter.CurrentDisplayMode.Width}x{game.GraphicsDeviceManager.GraphicsDevice.Adapter.CurrentDisplayMode.Height}<br/>
Fullscreen: {game.GraphicsDeviceManager.IsFullScreen}<br/>
Settings.FPSLimit: {game.GameSettings.FPSLimit}<br/>
Settings.CameraShake: {game.GameSettings.CameraShake}<br/>
Settings.ParticlesEnabled: {game.GameSettings.Particles}<br/>
Game Context: {game.CurrentGameContext}<br/>
<p></div>
</body>
</html>
";
string name = "crash.html";//$"crash_{DateTime.Now.ToString("MM-dd-yy-HH-mm-ss")}.html";
File.WriteAllText(name, crashReportHTML);
CaveGame.Core.OperatingSystem.OpenUrl(Path.GetFullPath(name));
CrashReport report = new CrashReport(game, e);
report.GenerateHTMLReport();
throw e;
}
#else
game.Run();
game.Exit();
#endif
}
Process.GetCurrentProcess().CloseMainWindow();

View File

@@ -9,13 +9,15 @@ using System.Text;
namespace CaveGame.Client
{
public static class Achievements
{
public static Achievement[] List =
{
new Achievement("FIRST_TREE"),
new Achievement("BRUG"),
new Achievement("DUMP"),
new ("FIRST_TREE"),
new ("BRUG"),
new ("DUMP"),
};
}
public class Achievement
@@ -43,8 +45,22 @@ namespace CaveGame.Client
}
public class SteamManager: GameComponent
public class SteamManager: GameComponent, ISteamManager
{
// api members
public bool HasAchievement(GameSteamAchievement achievement)
{
return false;
}
public void AwardAchievement(GameSteamAchievement achievement)
{
}
//
public SteamManager Instance { get; set; }
@@ -168,6 +184,8 @@ namespace CaveGame.Client
SteamAPI.Shutdown();
}
private void PollStats()
{
if (!receivedUserStats)

View File

@@ -1,217 +0,0 @@
using KeraLua;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Media;
using NLua;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace CaveGame.Client
{
public static class GameFonts
{
public static SpriteFont Arial8 { get; private set; }
public static SpriteFont Arial10 { get; private set; }
public static SpriteFont Arial12 { get; private set; }
public static SpriteFont Arial14 { get; private set; }
public static SpriteFont Arial16 { get; private set; }
public static SpriteFont Arial20 { get; private set; }
public static SpriteFont Arial30 { get; private set; }
public static SpriteFont Arial10Italic { get; private set; }
public static SpriteFont Consolas10 { get; private set; }
public static SpriteFont Consolas12 { get; private set; }
public static SpriteFont ComicSans10 { get; private set; }
public static void LoadAssets(ContentManager Content)
{
Arial8 = Content.Load<SpriteFont>("Fonts/Arial8");
Arial10 = Content.Load<SpriteFont>("Fonts/Arial10");
Arial12 = Content.Load<SpriteFont>("Fonts/Arial12");
Arial14 = Content.Load<SpriteFont>("Fonts/Arial14");
Arial16 = Content.Load<SpriteFont>("Fonts/Arial16");
Arial20 = Content.Load<SpriteFont>("Fonts/Arial20");
Arial30 = Content.Load<SpriteFont>("Fonts/Arial30");
Arial10Italic = Content.Load<SpriteFont>("Fonts/Arial10Italic");
Consolas10 = Content.Load<SpriteFont>("Fonts/Consolas10");
Consolas12 = Content.Load<SpriteFont>("Fonts/Consolas12");
ComicSans10 = Content.Load<SpriteFont>("Fonts/ComicSans10");
}
}
public static class GameTextures
{
public static bool ContentLoaded = false;
public static Dictionary<string, Texture2D> Textures = new Dictionary<string, Texture2D>();
public static Texture2D Player => Textures["Entities/player.png"];
public static Texture2D TitleScreen => Textures["TitleScreen.png"];
public static Texture2D EyeOfHorus => Textures["csoft.png"];
public static Texture2D ParticleSet => Textures["particles.png"];
public static Texture2D TileSheet => Textures["tilesheet.png"];
public static Texture2D BG => Textures["bg.png"];
public static Texture2D Border => Textures["border.png"];
public static Texture2D Slot => Textures["slot.png"];
public static void LoadAssets(GraphicsDevice graphicsDevice)
{
foreach (var tex in Directory.GetFiles("Assets/Textures/", "*.png"))
{
Texture2D loaded = AssetLoader.LoadTexture(graphicsDevice, tex);
Textures.Add(tex.Replace("Assets/Textures/", ""), loaded);
}
foreach (var tex in Directory.GetFiles("Assets/Entities/", "*.png"))
{
Texture2D loaded = AssetLoader.LoadTexture(graphicsDevice, tex);
Textures.Add(tex.Replace("Assets/", ""), loaded);
}
ContentLoaded = true;
}
}
public class TextureWrap {
public string Name;
public string File;
public TextureWrap(string name, string file)
{
Name = name;
File = file;
}
}
public static class AssetLoader
{
private static Texture2D FromStream(GraphicsDevice GraphicsProcessor, Stream DataStream)
{
Texture2D Asset = Texture2D.FromStream(GraphicsProcessor, DataStream);
// Fix Alpha Premultiply
Color[] data = new Color[Asset.Width * Asset.Height];
Asset.GetData(data);
for (int i = 0; i != data.Length; ++i)
data[i] = Color.FromNonPremultiplied(data[i].ToVector4());
Asset.SetData(data);
return Asset;
}
public static Texture2D LoadTexture(GraphicsDevice device, string filepath)
{
return FromStream(device, TitleContainer.OpenStream(filepath));
}
}
public static class ItemTextures
{
public static Dictionary<string, Texture2D> Textures = new Dictionary<string, Texture2D>();
private static TextureMeta[] texturelist =
{
//new TextureMeta("Arrow", "Assets/Items/arrow.png"),
//new TextureMeta("Bomb", "Assets/Items/bomb.png"),
//new TextureMeta("Bong", "Assets/Items/bong.png"),
////new TextureMeta("Ingot", "Assets/Items/ingot.png"),
//new TextureMeta("BigPickaxe", "Assets/Items/bigpickaxe"),
// new TextureMeta("WallScraper", "Assets/Items/wallscraper"),
};
public static void LoadAssets(GraphicsDevice graphicsDevice)
{
foreach (var tex in Directory.GetFiles("Assets/Items/", "*.png"))
{
Texture2D loaded = AssetLoader.LoadTexture(graphicsDevice, tex);
Textures.Add(tex.Replace("Assets/Items/", ""), loaded);
}
// if you want to hardcode textures like a dumbass
foreach (TextureMeta textureMeta in texturelist)
{
Texture2D loaded = AssetLoader.LoadTexture(graphicsDevice, textureMeta.FilePath);
Textures.Add(textureMeta.Name, loaded);
}
}
public static Texture2D Bomb => Textures["bomb.png"];
public static Texture2D Bong => Textures["bong.png"];
public static Texture2D Arrow => Textures["arrow.png"];
public static Texture2D Bucket => Textures["bucket.png"];
public static Texture2D BigPickaxe => Textures["bigpickaxe.png"];
public static Texture2D Helmet => Textures["helmet.png"];
public static Texture2D Chestplate => Textures["chestplate.png"];
public static Texture2D Sword => Textures["sword.png"];
public static Texture2D WallScraper => Textures["wallscraper.png"];
public static Texture2D PickaxeNew => Textures["pickaxenew.png"];
public static Texture2D Scroll => Textures["scroll.png"];
public static Texture2D Dynamite => Textures["dynamite.png"];
public static Texture2D Workbench => Textures["workbench.png"];
public static Texture2D Potion => Textures["potion.png"];
public static Texture2D Jetpack => Textures["jetpack.png"];
public static Texture2D Door => Textures["door.png"];
public static Texture2D ForestPainting=>Textures["forestpainting.png"];
public static Texture2D Ingot => Textures["ingot.png"];
public static Texture2D Leggings => Textures["leggings.png"];
public static Texture2D Furnace => Textures["furnace.png"];
public static Texture2D Campfire => Textures["campfire.png"];
//public static Texture2D Campfire => Textures["campfire.png"];
}
public struct TextureMeta
{
public string Name { get; private set; }
public string FilePath { get; private set; }
public TextureMeta(string name, string file)
{
Name = name;
FilePath = file;
}
}
public static class GameSounds
{
public static SoundEffect MenuBlip { get; private set; }
public static SoundEffect MenuBlip2 { get; private set; }
public static Song AmbientLava { get; private set; }
public static Song AmbientBirds1 { get; private set; }
public static Song AmbientBirds2 { get; private set; }
public static Song AmbientBirds3 { get; private set; }
public static Song AmbientBirds4 { get; private set; }
public static Song AmbientBirds5 { get; private set; }
public static Song AmbientBirds6 { get; private set; }
public static Song AmbientBirds7 { get; private set; }
public static Song AmbientCreepy1 { get; private set; }
public static Song AmbientCreepy2 { get; private set; }
public static Song AmbientCreepy3 { get; private set; }
public static Song AmbientCreepy4 { get; private set; }
public static void LoadAssets(ContentManager Content)
{
MenuBlip = Content.Load<SoundEffect>("Sound/click1");
MenuBlip2 = Content.Load<SoundEffect>("Sound/menu1");
AmbientLava = Content.Load<Song>("Sound/ambient/lava");
AmbientBirds1 = Content.Load<Song>("Sound/ambient/birds1");
AmbientBirds2 = Content.Load<Song>("Sound/ambient/birds2");
AmbientBirds3 = Content.Load<Song>("Sound/ambient/birds3");
AmbientBirds4 = Content.Load<Song>("Sound/ambient/birds4");
AmbientBirds5 = Content.Load<Song>("Sound/ambient/birds5");
AmbientBirds6 = Content.Load<Song>("Sound/ambient/birds6");
AmbientBirds7 = Content.Load<Song>("Sound/ambient/birds7");
AmbientCreepy1 = Content.Load<Song>("Sound/ambient/birds1");
AmbientBirds7 = Content.Load<Song>("Sound/ambient/birds1");
}
}
}

View File

@@ -9,7 +9,7 @@
<Import_RootNamespace>CaveGame.Client</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Assets.cs" />
<Compile Include="$(MSBuildThisFileDirectory)GameSounds.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DebugTools\ChunkGridLineRenderer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)GameSettings.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Game\Entities\LocalPlayer.cs" />
@@ -18,25 +18,23 @@
<Compile Include="$(MSBuildThisFileDirectory)InputManager.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Input\KeyPressDetector.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Menu\Multiplayer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Menu\TimeoutMenu.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DebugTools\NetGraph.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ISteamManager.cs" />
<Compile Include="$(MSBuildThisFileDirectory)GameChat.cs" />
<Compile Include="$(MSBuildThisFileDirectory)LightingEngine.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CommandBar\CommandBar.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DebugTools\FPSGraph.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DebugTools\FrameCounter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)GameClient.cs" />
<Compile Include="$(MSBuildThisFileDirectory)LocalWorld.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Menu\Credits.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Menu\Settings.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Menu\UITheme.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Particles\ParticleEmitter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NetworkClient.cs" />
<Compile Include="$(MSBuildThisFileDirectory)IGameContext.cs" />
<Compile Include="$(MSBuildThisFileDirectory)PauseMenu.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Splash.cs" />
<Compile Include="..\Client\Menu\MenuManager.cs" />
<Compile Include="$(MSBuildThisFileDirectory)PlayerContainerFrontend.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Renderer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UI\Label.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UI\NineSlice.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UI\Slider.cs" />

View File

@@ -142,9 +142,9 @@ namespace CaveGame.Core
List<Message> MessageHistory;
List<string> CommandHistory;
List<string> CommandHistory { get; set; }
int inputCurrent;
int inputCurrent { get; set; }
Lua consoleLua;
@@ -206,6 +206,10 @@ namespace CaveGame.Core
{
MessageHistory.Add(new Message(">" + command, new Color(0.75f, 0.75f, 0.75f)));
CommandHistory.Add(command);
inputCurrent = CommandHistory.Count-1;
string cleaned = command.Trim();
string[] keywords = cleaned.Split(' ');
@@ -218,6 +222,7 @@ namespace CaveGame.Core
}
}
MessageHistory.Add(new Message("No command " + keywords[0] + " found!", new Color(1.0f, 0, 0)));
}
public void OnTextInput(object sender, TextInputEventArgs args)
@@ -252,7 +257,7 @@ namespace CaveGame.Core
return additional;
}
public void Draw(SpriteBatch spriteBatch)
public void Draw(GraphicsEngine GFX)
{
if (!Open)
return;
@@ -266,10 +271,10 @@ namespace CaveGame.Core
Vector2 inputBoxPosition = consolePosition + new Vector2(0, consoleSize.Y - 20);
Vector2 inputBoxSize = new Vector2(consoleSize.X, 20);
spriteBatch.Begin();
spriteBatch.Rect(backgroundColor, consolePosition, consoleSize);
spriteBatch.Rect(inputBoxColor, inputBoxPosition, inputBoxSize);
spriteBatch.OutlineRect(new Color(0.0f, 0.0f, 0.0f), consolePosition, consoleSize);
GFX.Begin();
GFX.Rect(backgroundColor, consolePosition, consoleSize);
GFX.Rect(inputBoxColor, inputBoxPosition, inputBoxSize);
GFX.OutlineRect(new Color(0.0f, 0.0f, 0.0f), consolePosition, consoleSize);
#endregion
//Draw message history
@@ -284,10 +289,10 @@ namespace CaveGame.Core
for (int i = MessageHistory.Count-1; i >= 0; i--)
{
var message = history[i];
string text = message.Text.WrapText(GameFonts.Arial10, consoleSize.X);
string text = message.Text.WrapText(GFX.Fonts.Arial10, consoleSize.X);
visIter++;
visIter += text.Count(c => c == '\n');
spriteBatch.Print(message.TextColor, consolePosition + new Vector2(0, (consoleSize.Y - 20) - (visIter * 14)), text);
GFX.Text(text, consolePosition + new Vector2(0, (consoleSize.Y - 20) - (visIter * 14)), message.TextColor);
}
}
@@ -304,7 +309,7 @@ namespace CaveGame.Core
if (cmd.Keyword.StartsWith(cleaned))
{
spriteBatch.Print(new Color(0.5f, 0.5f, 0.0f), inputBoxPosition, InputBufferProcess(cmd.Keyword) + " " + GetArgsInfo(cmd));
GFX.Text(InputBufferProcess(cmd.Keyword) + " " + GetArgsInfo(cmd), inputBoxPosition , new Color(0.5f, 0.5f, 0.0f));
break;
}
}
@@ -316,14 +321,14 @@ namespace CaveGame.Core
autocompleteOptionIndex++;
if (autocompleteOptionIndex > 0)
spriteBatch.Rect(new Color(0.0f, 0.0f, 0.0f, 0.2f), inputBoxPosition - new Vector2(-5, (autocompleteOptionIndex + 1) * 14), new Vector2(300, autocompleteOptionIndex * 14));
GFX.Rect(new Color(0.0f, 0.0f, 0.0f, 0.2f), inputBoxPosition - new Vector2(-5, (autocompleteOptionIndex + 1) * 14), new Vector2(300, autocompleteOptionIndex * 14));
var iterator2 = 0;
foreach (Command cmd in Commands)
{
if (cmd.Keyword.StartsWith(cleaned))
{
spriteBatch.Print(new Color(1.0f, 1.0f, 0), inputBoxPosition - new Vector2(-5, (iterator2 + 2) * 14), cmd.Keyword + " " + GetArgsInfo(cmd));
GFX.Text(cmd.Keyword + " " + GetArgsInfo(cmd), inputBoxPosition - new Vector2(-5, (iterator2 + 2) * 14), new Color(1.0f, 1.0f, 0));
iterator2++;
}
}
@@ -332,27 +337,27 @@ namespace CaveGame.Core
if (inputBox.SpecialSelection)
{
var font = GameFonts.Arial10;
var font = GFX.Fonts.Arial10;
var beforeText = inputBox.GetScissorTextBefore();
var middleText = inputBox.GetScissorTextDuring();
var afterText = inputBox.GetScissorTextAfter();
var start = font.MeasureString(beforeText);
var end = font.MeasureString(middleText);
spriteBatch.Rect(Color.Blue, inputBoxPosition + new Vector2(start.X, 0), end);
GFX.Rect(Color.Blue, inputBoxPosition + new Vector2(start.X, 0), end);
// first section
spriteBatch.Print(Color.White, inputBoxPosition, beforeText);
spriteBatch.Print(Color.Black, inputBoxPosition + new Vector2(start.X, 0), middleText);
spriteBatch.Print(Color.White, inputBoxPosition + new Vector2(start.X + end.X, 0), afterText);
GFX.Text(beforeText, inputBoxPosition, Color.White);
GFX.Text(middleText, inputBoxPosition + new Vector2(start.X, 0), Color.Black);
GFX.Text(afterText, inputBoxPosition + new Vector2(start.X + end.X, 0), Color.White);
} else
{
// Input buffer
spriteBatch.Print(new Color(1.0f, 1.0f, 1.0f), inputBoxPosition, inputBox.DisplayText);
GFX.Text(inputBox.DisplayText, inputBoxPosition, new Color(1.0f, 1.0f, 1.0f));
}
spriteBatch.End();
GFX.End();
}
public override void Update(GameTime gameTime)
@@ -392,8 +397,9 @@ namespace CaveGame.Core
if (keyboard.IsKeyDown(Keys.Up) && !previousKBState.IsKeyDown(Keys.Up))
{
inputCurrent = Math.Max(inputCurrent - 1, 0);
inputBox.InputBuffer = CommandHistory[inputCurrent];
inputCurrent = Math.Max(inputCurrent - 1, 0);
}

View File

@@ -9,7 +9,7 @@ namespace CaveGame.Client.DebugTools
{
public class ChunkGridLineRenderer
{
public void Draw(SpriteBatch spriteBatch, Camera2D Camera)
public void Draw(GraphicsEngine gfx, Camera2D Camera)
{
int camChunkX = (int)Math.Floor(Camera.ScreenCenterToWorldSpace.X / (Globals.ChunkSize * Globals.TileSize));
int camChunkY = (int)Math.Floor(Camera.ScreenCenterToWorldSpace.Y / (Globals.ChunkSize * Globals.TileSize));
@@ -18,7 +18,7 @@ namespace CaveGame.Client.DebugTools
for (int x = -rendr; x <= rendr; x++)
{
spriteBatch.Line(Color.White, new Vector2(
gfx.Line(Color.White, new Vector2(
(camChunkX + x) * (Globals.ChunkSize * Globals.TileSize),
(camChunkY - rendr) * (Globals.ChunkSize * Globals.TileSize)
), new Vector2(
@@ -29,7 +29,7 @@ namespace CaveGame.Client.DebugTools
for (int y = -rendr; y <= rendr; y++)
{
spriteBatch.Line(Color.White, new Vector2(
gfx.Line(Color.White, new Vector2(
(camChunkX - rendr) * (Globals.ChunkSize * Globals.TileSize),
(camChunkY + y) * (Globals.ChunkSize * Globals.TileSize)
), new Vector2(
@@ -43,7 +43,7 @@ namespace CaveGame.Client.DebugTools
for (int y = -rendr; y <= rendr; y++)
{
var pos = new Vector2(camChunkX + x, camChunkY + y) * (Globals.ChunkSize * Globals.TileSize);
spriteBatch.Print(GameFonts.Arial8, new Color(1, 1, 1, 0.5f), pos, (camChunkX + x) + ", " + (camChunkY + y));
gfx.Text(gfx.Fonts.Arial8, (camChunkX + x) + ", " + (camChunkY + y), pos, new Color(1, 1, 1, 0.5f));
}
}
}

View File

@@ -1,102 +0,0 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Text;
namespace CaveGame.Client
{
public struct GraphEntry
{
public float FrameTime;
}
public class FPSGraph: GameComponent
{
public bool Enabled { get; set; }
public int PollingRate { get; set; }
public int SampleCount { get; set; }
public Vector2 Position;
public FPSGraph(Microsoft.Xna.Framework.Game game, int pollrate, int samplecount) : base(game)
{
Position = new Vector2(0, 0);
PollingRate = pollrate;
SampleCount = samplecount;
SamplePoints = new List<GraphEntry>();
Enabled = false;
for (int x = 0; x < SampleCount+1; x++)
{
SamplePoints.Add(new GraphEntry() { FrameTime = 0 });
}
}
float timer;
public List<GraphEntry> SamplePoints;
KeyboardState prevKeyboard;
public override void Update(GameTime gt)
{
KeyboardState keyboard = Keyboard.GetState();
if (prevKeyboard != null)
{
if (keyboard.IsKeyDown(Keys.F1) && !prevKeyboard.IsKeyDown(Keys.F1)) {
Enabled = !Enabled;
}
}
prevKeyboard = keyboard;
if (!Enabled)
return;
float frametime = (float)gt.ElapsedGameTime.TotalSeconds;
timer += frametime;
if (timer > (PollingRate/1000.0f))
{
timer = 0;
var entry = new GraphEntry();
entry.FrameTime = frametime;
SamplePoints.Insert(0, entry);
if (SamplePoints.Count > SampleCount)
{
SamplePoints.RemoveAt(SampleCount);
}
}
}
int sampleWidth = 3;
float heightScale = 5000f;
public void Draw(SpriteBatch sb)
{
if (!Enabled)
return;
sb.Begin(SpriteSortMode.BackToFront, null, SamplerState.PointClamp);
for (int idx = 0; idx < SampleCount; idx++)
{
var entry = SamplePoints[idx];
sb.Rect(Color.Red, Position + new Vector2(sampleWidth * idx, 0), new Vector2(sampleWidth, 2+(entry.FrameTime * heightScale)));
}
sb.End();
}
}
}

View File

@@ -1,5 +1,6 @@
using CaveGame.Core;
using CaveGame.Core.Game.Entities;
using CaveGame.Core.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
@@ -10,7 +11,7 @@ namespace CaveGame.Client.Game.Entities
{
public abstract class ClientPlayer : Core.Game.Entities.Player
{
public override void Draw(SpriteBatch sb)
public override void Draw(GraphicsEngine gfx)
{
Rectangle spriteFrame = new Rectangle(0, 0, 16, 24);
@@ -32,10 +33,13 @@ namespace CaveGame.Client.Game.Entities
if (!OnGround)
spriteFrame = new Rectangle(48, 0, 16, 24);
Vector2 hpbounds = GameFonts.Arial8.MeasureString(Health + "/" + MaxHealth + " HP");
sb.Print(GameFonts.Arial8, Color.Red, Position - new Vector2(hpbounds.X / 2, hpbounds.Y*2), Health + "/" + MaxHealth + " HP");
string hptext = Health + "/" + MaxHealth + " HP";
Vector2 hpbounds = gfx.Fonts.Arial8.MeasureString(Health + "/" + MaxHealth + " HP");
//sb.Print(GameFonts.Arial8, Color.Red, Position - new Vector2(hpbounds.X / 2, hpbounds.Y*2), );
sb.Draw(GameTextures.Player, TopLeft, spriteFrame, Color, 0, new Vector2(0, 0), 1, (SpriteEffects)flipSprite, 0);
gfx.Text(gfx.Fonts.Arial8, hptext, Position-new Vector2(0, BoundingBox.Y/2), Color.White, TextXAlignment.Center, TextYAlignment.Bottom);
gfx.Sprite(gfx.Player, TopLeft, spriteFrame, Color, Rotation.Zero, new Vector2(0, 0), 1, (SpriteEffects)flipSprite, 0);
}
}
}

View File

@@ -12,12 +12,12 @@ namespace CaveGame.Client.Game.Entities
public class PeerPlayer : ClientPlayer, IClientPhysicsObserver
{
//public void ClientPhysicsTick(IClientWorld world, float step) => PhysicsStep(world, step);
public override void Draw(SpriteBatch sb)
public override void Draw(GraphicsEngine GFX)
{
Vector2 namebounds = GameFonts.Arial8.MeasureString(DisplayName);
sb.Print(GameFonts.Arial8, Color.White, Position - new Vector2(namebounds.X/2, namebounds.Y), DisplayName);
base.Draw(sb);
Vector2 namebounds = GFX.Fonts.Arial8.MeasureString(DisplayName);
GFX.Text(GFX.Fonts.Arial8, DisplayName, Position - new Vector2(namebounds.X/2, namebounds.Y), Color.White);
base.Draw(GFX);
}
public void ClientPhysicsTick(IClientWorld world, float step) => Position = Position.Lerp(NextPosition, 0.5f);

View File

@@ -85,10 +85,10 @@ namespace CaveGame.Client
}
}
public void Draw(SpriteBatch spriteBatch)
public void Draw(GraphicsEngine GFX)
{
int textHeight = 14;
SpriteFont font = GameFonts.Arial10;
SpriteFont font = GFX.Fonts.Arial10;
if (ChatSize == GameChatSize.Small)
{
@@ -97,14 +97,14 @@ namespace CaveGame.Client
if (ChatSize == GameChatSize.Normal)
{
font = GameFonts.Arial14;
font = GFX.Fonts.Arial14;
textHeight = 20;
}
if (ChatSize == GameChatSize.Large)
{
font = GameFonts.Arial16;
font = GFX.Fonts.Arial16;
textHeight = 24;
}
@@ -113,18 +113,17 @@ namespace CaveGame.Client
#region Draw box
Color backgroundColor = new Color(0, 0, 0, 0.75f);
Vector2 chatsize = new Vector2(500, 15* textHeight);
Vector2 chatpos = new Vector2(0, GameGlobals.Height - 30 - (15 * textHeight));
Vector2 chatpos = new Vector2(0, GFX.WindowSize.Y - 30 - (15 * textHeight));
Color inputBoxColor = new Color(0.15f, 0.15f, 0.25f);
Vector2 inputBoxPosition = new Vector2(0, GameGlobals.Height-30);
Vector2 inputBoxPosition = new Vector2(0, GFX.WindowSize.Y - 30);
Vector2 inputBoxSize = new Vector2(chatsize.X, 20);
spriteBatch.Begin();
GFX.Begin();
if (Open)
{
spriteBatch.Rect(backgroundColor, chatpos, chatsize);
spriteBatch.Rect(inputBoxColor, inputBoxPosition, inputBoxSize);
spriteBatch.OutlineRect(new Color(0.0f, 0.0f, 0.0f), chatpos, chatsize);
GFX.Rect(backgroundColor, chatpos, chatsize);
GFX.Rect(inputBoxColor, inputBoxPosition, inputBoxSize);
GFX.OutlineRect(new Color(0.0f, 0.0f, 0.0f), chatpos, chatsize);
}
#endregion
@@ -134,8 +133,8 @@ namespace CaveGame.Client
lock (MessageHistory)
foreach (Message message in MessageHistory.ToArray().Reverse())
{
var pos = new Vector2(0, GameGlobals.Height - 20 - ((count+1)*textHeight));
spriteBatch.Print(font, message.TextColor, pos, message.Text);
var pos = new Vector2(0, GFX.WindowSize.Y - 20 - ((count+1)*textHeight));
GFX.Text(font, message.Text, pos, message.TextColor);
iter--;
count++;
@@ -160,21 +159,21 @@ namespace CaveGame.Client
//Debug.WriteLine("{0}|{1}|{2}", beforeText, middleText, afterText);
spriteBatch.Rect(Color.Blue, inputBoxPosition + new Vector2(start.X, 0), end);
GFX.Rect(Color.Blue, inputBoxPosition + new Vector2(start.X, 0), end);
// first section
spriteBatch.Print(font, Color.White, inputBoxPosition, beforeText);
spriteBatch.Print(font, Color.Black, inputBoxPosition + new Vector2(start.X, 0), middleText);
spriteBatch.Print(font, Color.White, inputBoxPosition + new Vector2(start.X + end.X, 0), afterText);
GFX.Text(font, beforeText , inputBoxPosition, Color.White);
GFX.Text(font, middleText , inputBoxPosition + new Vector2(start.X, 0), Color.Black);
GFX.Text(font, afterText, inputBoxPosition + new Vector2(start.X + end.X, 0), Color.White);
} else
{
spriteBatch.Print(font, new Color(1.0f, 1.0f, 1.0f), inputBoxPosition, inputBox.DisplayText);
GFX.Text(font, inputBox.DisplayText, inputBoxPosition, new Color(1.0f, 1.0f, 1.0f));
}
}
spriteBatch.End();
GFX.End();
}
}
}

View File

@@ -24,13 +24,6 @@ using CaveGame.Client.DebugTools;
namespace CaveGame.Client
{
public class TempItemDef
{
public Rectangle Quad;
public byte TileID;
public Color Color;
}
// The testbench for building the server/client archite ture
public class Hotbar
{
@@ -96,37 +89,50 @@ namespace CaveGame.Client
}
public void Draw(SpriteBatch sb)
public void Draw(GraphicsEngine GFX)
{
sb.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp);
GFX.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp);
int travel = 0;
Vector2 pos = new Vector2(GameGlobals.Width - ( (24 * (ItemSet.Length-1))+48), 2);
Vector2 pos = new Vector2(GFX.WindowSize.X - ( (24 * (ItemSet.Length-1))+48), 2);
for (int i = 0; i < ItemSet.Length; i++)
{
if (Index == i)
{
sb.Rect(new Color(0.8f, 0.8f, 0.8f), pos+new Vector2(travel, 0), new Vector2(48, 48));
ItemSet[i].Draw(sb, pos + new Vector2(travel, 0), 3f);
GFX.Rect(
color: new Color(0.8f, 0.8f, 0.8f),
position: pos+new Vector2(travel, 0),
size: new Vector2(48, 48)
);
ItemSet[i].Draw(GFX, pos + new Vector2(travel, 0), 3f);
Vector2 dim = GameFonts.Arial14.MeasureString(ItemSet[Index].Name);
float x = Math.Min(GameGlobals.Width - dim.X, pos.X+travel + 24 - (dim.X / 2));
Vector2 dim = GFX.Fonts.Arial14.MeasureString(ItemSet[Index].Name);
float x = Math.Min(GFX.WindowSize.X - dim.X, pos.X+travel + 24 - (dim.X / 2));
x = Math.Max(pos.X, x);
sb.Print(GameFonts.Arial14, Color.White, new Vector2(x, pos.Y+48), ItemSet[Index].Name);
GFX.Text(
font: GFX.Fonts.Arial14,
text: ItemSet[Index].Name,
position: new Vector2(x, pos.Y + 48)
);
travel += 48;
}
else
{
sb.Rect(new Color(0.3f, 0.3f, 0.3f), pos + new Vector2(travel, 0), new Vector2(24, 24));
ItemSet[i].Draw(sb, pos + new Vector2(travel, 0), 1.5f);
GFX.Rect(
color: new Color(0.3f, 0.3f, 0.3f),
position: pos + new Vector2(travel, 0),
size: new Vector2(24, 24)
);
ItemSet[i].Draw(GFX, pos + new Vector2(travel, 0), 1.5f);
travel += 24;
}
}
sb.End();
GFX.End();
}
}
@@ -142,7 +148,7 @@ namespace CaveGame.Client
public string ConnectAddress { get; set; }
public bool Active { get; set; }
Microsoft.Xna.Framework.Game IGameContext.Game => Game;
IGameWorld IGameClient.World => World;
IClientWorld IGameClient.World => World;
//public Hotbar Hotbar { get; set; }
public PlayerContainerFrontend Inventory { get; set; }
public LocalWorld World { get; private set; }
@@ -161,75 +167,36 @@ namespace CaveGame.Client
private int IntitalScrollValue;
bool pauseMenuOpen;
UIRoot pauseMenu;
//bool pauseMenuOpen;
//UIRoot pauseMenu;
Effect effect { get; set; }
private void ConstructPauseMenu()
{
pauseMenu = new UIRoot();
UIRect bg = new UIRect
{
BGColor = Color.Transparent,
Size = new UICoords(0, 0, 1, 1),
Position = new UICoords(0, 0, 0, 0),
Parent = pauseMenu
};
TextButton resumeButton = new TextButton
{
Parent = bg,
TextColor = Color.White,
Text = "Resume",
Font = GameFonts.Arial14,
Size = new UICoords(150, 25, 0, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
UnselectedBGColor = new Color(0.2f, 0.2f, 0.2f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
Position = new UICoords(10, -100, 0, 1)
};
resumeButton.OnLeftClick += (x, y) => pauseMenuOpen = false;
TextButton exitButton = new TextButton
{
Parent = bg,
TextColor = Color.White,
Text = "Disconnect",
Font = GameFonts.Arial14,
Size = new UICoords(150, 25, 0, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
UnselectedBGColor = new Color(0.2f, 0.2f, 0.2f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
Position = new UICoords(10, -50, 0, 1)
};
exitButton.OnLeftClick += onClientExit;
}
PauseMenu PauseMenu { get; set; }
private void onClientExit(TextButton sender, MouseState state)=>OverrideDisconnect();
public void OverrideDisconnect()
{
pauseMenuOpen = false;
PauseMenu.Open = false;
Disconnect();
Game.CurrentGameContext = Game.HomePageContext;
Game.CurrentGameContext = Game.MenuContext;
}
public GameClient(CaveGameGL _game)
{
Game = _game;
ConstructPauseMenu();
MouseState mouse = Mouse.GetState();
World = new LocalWorld();
Camera = new Camera2D(Game.GraphicsDevice.Viewport) { Zoom = CameraZoom };
Chat = new GameChat(this);
World = new LocalWorld(this);
Camera = new Camera2D(Game.GraphicsDevice.Viewport) { Zoom = CameraZoom };
Chat = new GameChat(this);
PauseMenu = new PauseMenu(this);
Inventory = new PlayerContainerFrontend();
IntitalScrollValue = mouse.ScrollWheelValue;
playerStateReplicationTask = new DelayedTask(ReplicatePlayerState, 1 / 10.0f);
@@ -238,7 +205,7 @@ namespace CaveGame.Client
ChunkingRadius = 1;
Inventory = new PlayerContainerFrontend();
}
@@ -421,8 +388,8 @@ namespace CaveGame.Client
RejectJoinPacket packet = new RejectJoinPacket(message.Packet.GetBytes());
// TODO: send player to the rejection screen
Game.CurrentGameContext = Game.TimeoutContext;
Game.TimeoutContext.Message = packet.RejectReason;
Game.CurrentGameContext = Game.MenuContext;
Game.MenuContext.TimeoutMessage = packet.RejectReason;
}
private void OnServerAcceptJoining(NetworkMessage message)
{
@@ -438,16 +405,24 @@ namespace CaveGame.Client
MyPlayer = myplayer;
World.Entities.Add(myplayer);
Inventory.Player = myplayer;
Inventory.Container.ForceSetSlot(0, 0, new ItemStack {Item = new GenericPickaxe(), Quantity = 4 });
Inventory.Container.ForceSetSlot(1, 0, new ItemStack { Item = new TileItem(new Core.Game.Tiles.OakPlank()), Quantity = 25 });
Inventory.Container.ForceSetSlot(2, 0, new ItemStack { Item = new TileItem(new Core.Game.Tiles.OakPlank()), Quantity = 25 });
Inventory.Container.ForceSetSlot(3, 0, new ItemStack { Item = new TileItem(new Core.Game.Tiles.EbonyPlank()), Quantity = 50 });
Inventory.Container.ForceSetSlot(0, 0, new ItemStack {Item = new CopperPickaxe(), Quantity = 1 });
Inventory.Container.ForceSetSlot(0, 1, new ItemStack { Item = new IronPickaxe(), Quantity = 1 });
Inventory.Container.ForceSetSlot(0, 2, new ItemStack { Item = new LeadPickaxe(), Quantity = 1 });
Inventory.Container.ForceSetSlot(1, 0, new ItemStack { Item = new TileItem(new Core.Game.Tiles.OakPlank()), Quantity = 999 });
Inventory.Container.ForceSetSlot(1, 1, new ItemStack { Item = new GenericWallScraper(), Quantity = 1 });
Inventory.Container.ForceSetSlot(2, 0, new ItemStack { Item = new TileItem(new Core.Game.Tiles.StoneBrick()), Quantity = 999 });
Inventory.Container.ForceSetSlot(3, 0, new ItemStack { Item = new TileItem(new Core.Game.Tiles.ClayBrick()), Quantity = 999 });
Inventory.Container.ForceSetSlot(4, 0, new ItemStack { Item = new BombItem(), Quantity = 999 });
Inventory.Container.ForceSetSlot(5, 0, new ItemStack { Item = new TileItem(new RedTorch()), Quantity = 999 });
Inventory.Container.ForceSetSlot(6, 0, new ItemStack { Item = new TileItem(new GreenTorch()), Quantity = 999 });
Inventory.Container.ForceSetSlot(7, 0, new ItemStack { Item = new TileItem(new BlueTorch()), Quantity = 999 });
Inventory.Container.ForceSetSlot(8, 0, new ItemStack { Item = new TileItem(new Torch()), Quantity = 999 });
Inventory.Container.ForceSetSlot(9, 0, new ItemStack { Item = new TileItem(new Water()), Quantity = 999 });
Inventory.Container.ForceSetSlot(2, 1, new ItemStack { Item = new WallItem(new Core.Game.Walls.ClayBrick()), Quantity = 999 });
Inventory.Container.ForceSetSlot(3, 1, new ItemStack { Item = new WallItem(new Core.Game.Walls.Dirt()), Quantity = 999 });
Inventory.Container.ForceSetSlot(4, 1, new ItemStack { Item = new WallItem(new Core.Game.Walls.OakPlank()), Quantity = 999 });
Inventory.Container.ForceSetSlot(5, 1, new ItemStack { Item = new WallItem(new Core.Game.Walls.StoneBrick()), Quantity = 999 });
}
Random r = new Random();
@@ -461,13 +436,13 @@ namespace CaveGame.Client
float dist = (1.0f/Math.Clamp(pos.Distance(Camera.Position), 0.2f, 200f)) * 200f;
Camera.Shake(dist, dist);
for (int i = 0; i<360; i+=10)
for (int i = 0; i<360; i+=5)
{
float randy = r.Next(0, 20)-10;
float randy = r.Next(0, 10)-5;
Rotation rotation = Rotation.FromDeg(i+randy);
Vector2 direction = new Vector2((float)Math.Sin(rotation.Radians), (float)Math.Cos(rotation.Radians));
float size = ((float)r.NextDouble() *0.25f) + (packet.Strength*0.35f);
World.ParticleSystem.Add(new SmokeParticle(pos, Color.White, Rotation.FromDeg(0), size, direction* (packet.Radius*1.0f+((float)r.NextDouble()*4))));
float size = ((float)r.NextDouble() *0.4f) + (packet.Strength*0.2f);
World.ParticleSystem.EmitSmokeParticle(pos, Color.White, Rotation.FromDeg(0), size, direction* (packet.Radius*1.0f+((float)r.NextDouble()*5)));
}
}
@@ -566,7 +541,28 @@ namespace CaveGame.Client
MyPlayer.Inventory.AddItem(packet.Reward);
}
private void OnSpawnedWurmhole(NetworkMessage msg)
{
SpawnWurmholeEntityPacket packet = new SpawnWurmholeEntityPacket(msg.Packet.GetBytes());
Wurmhole wurm = new Wurmhole();
wurm.EntityNetworkID = packet.EntityNetworkID;
World.Entities.Add(wurm);
}
private void OnWurmholeTriggered(NetworkMessage msg)
{
TriggerWurmholeEntityPacket packet = new TriggerWurmholeEntityPacket(msg.Packet.GetBytes());
var entity = World.FindEntityOfID(packet.EntityNetworkID);
if (entity is Wurmhole wurmhole)
{
wurmhole.Triggered = true;
}
}
#endregion
// gameclient
@@ -618,11 +614,17 @@ namespace CaveGame.Client
OnDamageTile(msg);
if (msg.Packet.Type == PacketType.GivePlayerItem)
GiveItToMeDaddy(msg);
if (msg.Packet.Type == PacketType.SpawnWurmholeEntity)
OnSpawnedWurmhole(msg);
if (msg.Packet.Type == PacketType.TriggerWurmholeEntity)
OnWurmholeTriggered(msg);
// DickSack
}
}
private void DrawChunks(SpriteBatch sb)
private void DrawChunks(GraphicsEngine GFX)
{
if (drawTimer > (1/5.0f))
{
@@ -630,23 +632,21 @@ namespace CaveGame.Client
Chunk.RefreshedThisFrame = false;
foreach (var chunkpair in World.Chunks)
{
chunkpair.Value.Draw(GameTextures.TileSheet, Game.GraphicsDevice, sb);
chunkpair.Value.Draw(GFX);
}
}
}
private void EntityRendering(SpriteBatch sb)
private void EntityRendering(GraphicsEngine gfx)
{
foreach (Entity entity in World.Entities)
{
if (entity.DurationAlive > 0)
entity.Draw(sb);
entity.Draw(gfx);
}
}
private void DrawChunkFGTextures(SpriteBatch sb)
private void DrawChunkFGTextures(GraphicsEngine gfx)
{
foreach (var chunkpair in World.Chunks)
{
@@ -654,11 +654,11 @@ namespace CaveGame.Client
Chunk chunk = chunkpair.Value;
Vector2 pos = new Vector2(chunk.Coordinates.X * Globals.ChunkSize * Globals.TileSize, chunk.Coordinates.Y * Globals.ChunkSize * Globals.TileSize);
if (chunk.ForegroundRenderBuffer != null)
sb.Draw(chunk.ForegroundRenderBuffer, pos, Color.White);
gfx.Sprite(chunk.ForegroundRenderBuffer, pos, Color.White);
}
}
private void DrawChunkBGTextures(SpriteBatch sb)
private void DrawChunkBGTextures(GraphicsEngine gfx)
{
foreach (var chunkpair in World.Chunks)
{
@@ -667,12 +667,12 @@ namespace CaveGame.Client
Vector2 pos = new Vector2(chunk.Coordinates.X * Globals.ChunkSize * Globals.TileSize, chunk.Coordinates.Y * Globals.ChunkSize * Globals.TileSize);
if (chunk.BackgroundRenderBuffer != null)
sb.Draw(chunk.BackgroundRenderBuffer, pos, Color.White);
gfx.Sprite(chunk.BackgroundRenderBuffer, pos, Color.White);
}
}
private void DrawDebugInfo(SpriteBatch sb)
private void DrawDebugInfo(GraphicsEngine gfx)
{
sb.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp);
gfx.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp);
MouseState mouse = Mouse.GetState();
var mp = Camera.ScreenToWorldCoordinates(mouse.Position.ToVector2());
@@ -689,38 +689,41 @@ namespace CaveGame.Client
if (MyPlayer != null)
{
sb.Print(Color.White, new Vector2(2, 12),
String.Format("pos {0} {1} vel {2} {3}",
string positionData = String.Format("pos {0} {1} vel {2} {3}",
Math.Floor(MyPlayer.Position.X / Globals.TileSize),
Math.Floor(MyPlayer.Position.Y / Globals.TileSize),
Math.Round(MyPlayer.Velocity.X, 2),
Math.Round(MyPlayer.Velocity.Y, 2)
)
);
sb.Print(Color.White, new Vector2(2, 24),
String.Format("pin {0}, pout {1} myid {2}",
string networkData = String.Format("pin {0}, pout {1} myid {2}",
gameClient.ReceivedCount,
gameClient.SentCount,
MyPlayer?.EntityNetworkID
)
);
sb.Print(Color.White, new Vector2(2, 36),
String.Format("tid {0}, state {1} tdmg {2} wid {3} wdmg {4} light {5}",
string worldData = String.Format("tid {0}, state {1} tdmg {2} wid {3} wdmg {4} light {5}",
tileat.ID,
tileat.TileState,
tileat.Damage,
wallat.ID,
wallat.Damage,
World.GetLight((int)tileCoords.X, (int)tileCoords.Y).ToString()
)
);
sb.Print(Color.White, new Vector2(2, 48), String.Format("entities {0} furn {1}", World.Entities.Count, World.Furniture.Count) );
string mObjectData = String.Format("entities {0} furn {1}", World.Entities.Count, World.Furniture.Count);
gfx.Text(positionData, new Vector2(2, 12));
gfx.Text(networkData, new Vector2(2, 24));
gfx.Text(worldData, new Vector2(2, 36));
gfx.Text(mObjectData, new Vector2(2, 48));
}
sb.End();
gfx.End();
}
private void DrawSkyColor(SpriteBatch sb)
private void DrawSkyColor(GraphicsEngine GFX)
{
for (int y = 0; y<10; y++)
{
@@ -740,49 +743,37 @@ namespace CaveGame.Client
var finalColor = Color.Lerp(prevSection, thisSection, (World.TimeOfDay % 2.0f) / 2.0f);
float sliceHeight = Camera._screenSize.Y / 10.0f;
sb.Rect(finalColor, new Vector2(0,(sliceHeight*y)), new Vector2(Camera._screenSize.X, sliceHeight + 1));
GFX.Rect(finalColor, new Vector2(0,(sliceHeight*y)), new Vector2(Camera._screenSize.X, sliceHeight + 1));
}
}
private SpriteBatch sbReference;
public void Draw(SpriteBatch sb)
public void Draw(GraphicsEngine GFX)
{
if (sbReference == null)
sbReference = sb;
DrawChunks(sb);
DrawChunks(GFX);
Game.GraphicsDevice.Clear(World.SkyColor);
sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp);
GFX.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp);
DrawSkyColor(sb);
sb.End();
sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, Camera.View);
if (pauseMenuOpen)
{
effect.Parameters["xSize"].SetValue((float)256);
effect.Parameters["ySize"].SetValue((float)256);
effect.Parameters["xDraw"].SetValue((float)16);
effect.Parameters["yDraw"].SetValue((float)16);
//effect.Parameters["filterColor"].SetValue(Color.White.ToVector4());
effect.CurrentTechnique.Passes[0].Apply();
DrawSkyColor(GFX);
GFX.End();
GFX.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, Camera.View);
if (PauseMenu.Open)
PauseMenu.DrawWaterPixelsFilter(GFX);
}
DrawChunkBGTextures(sb);
DrawChunkFGTextures(sb);
//effect.CurrentTechnique.Passes[0].();
DrawChunkBGTextures(GFX);
DrawChunkFGTextures(GFX);
foreach (var furn in World.Furniture)
{
furn.Draw(GameTextures.TileSheet, sb);
furn.Draw(GFX);
}
EntityRendering(sb);
EntityRendering(GFX);
World.ParticleSystem.Draw(sb);
World.ParticleSystem.Draw(GFX);
MouseState mouse = Mouse.GetState();
@@ -796,41 +787,33 @@ namespace CaveGame.Client
if (mouse.LeftButton == ButtonState.Pressed)
{
sb.Rect(Color.Green, mp, new Vector2(8, 8));
GFX.Rect(Color.Green, mp, new Vector2(8, 8));
} else
{
sb.Rect(new Color(1,1,1,0.5f), mp, new Vector2(8, 8));
GFX.Rect(new Color(1,1,1,0.5f), mp, new Vector2(8, 8));
}
sb.End();
GFX.End();
if (ShowChunkBoundaries)
{
sb.Begin(SpriteSortMode.Immediate, null, SamplerState.PointClamp, null, null, null, Camera.View);
chunkGridTool?.Draw(sb, Camera);
sb.End();
GFX.Begin(SpriteSortMode.Immediate, null, SamplerState.PointClamp, null, null, null, Camera.View);
chunkGridTool?.Draw(GFX, Camera);
GFX.End();
}
// TODO: Consolidate draw calls
sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp);
Inventory.Draw(sb);
sb.End();
DrawDebugInfo(sb);
Chat.Draw(sb);
GFX.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp);
Inventory.Draw(GFX);
GFX.End();
DrawDebugInfo(GFX);
Chat.Draw(GFX);
if (pauseMenuOpen)
{
sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp);
//effect.CurrentTechnique.Passes[0].Apply();
pauseMenu.Draw(sb);
sb.End();
}
PauseMenu.Draw(GFX);
}
public void Load()
{
effect = Game.Content.Load<Effect>("ShaderTest");
//Hotbar = new Hotbar();
PauseMenu.LoadShader(Game.Content);
gameClient = new NetworkClient(ConnectAddress);
//gameClient = new NetworkClient("127.0.0.1:40269");
@@ -957,7 +940,7 @@ namespace CaveGame.Client
if (PressedThisFrame(Keys.Escape))
pauseMenuOpen = !pauseMenuOpen;
PauseMenu.Open = !PauseMenu.Open;
if (PressedThisFrame(Keys.Tab))
Inventory.InventoryOpen = !Inventory.InventoryOpen;
@@ -988,7 +971,7 @@ namespace CaveGame.Client
if (MyPlayer != null)
{
if (pauseMenuOpen == true || Chat.Open == true || Game.Console.Open == true)
if (PauseMenu.Open == true || Chat.Open == true || Game.Console.Open == true)
MyPlayer.IgnoreInput = true;
else
MyPlayer.IgnoreInput = false;
@@ -996,12 +979,8 @@ namespace CaveGame.Client
Inventory.Update(gt);
if (pauseMenuOpen)
pauseMenu.Update(gt);
PauseMenu.Update(gt);
Chat.Update(gt);
//Hotbar.Update(gt);
World.Update(gt);
HotbarUpdate(gt);
UpdateCamera(gt);

View File

@@ -31,6 +31,7 @@ namespace CaveGame.Client
public static SliderIndex<int>[] GetIntArray(int minimum, int maximum, int increment = 1)
{
SliderIndex<int>[] arr = new SliderIndex<int>[maximum-minimum];
for (int i = 0; i<(maximum - minimum); i++)
{

51
Client/GameSounds.cs Normal file
View File

@@ -0,0 +1,51 @@
using CaveGame.Core;
using KeraLua;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Media;
using NLua;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace CaveGame.Client
{
public static class GameSounds
{
public static SoundEffect MenuBlip { get; private set; }
public static SoundEffect MenuBlip2 { get; private set; }
public static Song AmbientLava { get; private set; }
public static Song AmbientBirds1 { get; private set; }
public static Song AmbientBirds2 { get; private set; }
public static Song AmbientBirds3 { get; private set; }
public static Song AmbientBirds4 { get; private set; }
public static Song AmbientBirds5 { get; private set; }
public static Song AmbientBirds6 { get; private set; }
public static Song AmbientBirds7 { get; private set; }
public static Song AmbientCreepy1 { get; private set; }
public static Song AmbientCreepy2 { get; private set; }
public static Song AmbientCreepy3 { get; private set; }
public static Song AmbientCreepy4 { get; private set; }
public static void LoadAssets(ContentManager Content)
{
MenuBlip = Content.Load<SoundEffect>("Sound/click1");
MenuBlip2 = Content.Load<SoundEffect>("Sound/menu1");
/*AmbientLava = Content.Load<Song>("Sound/ambient/lava");
AmbientBirds1 = Content.Load<Song>("Sound/ambient/birds1");
AmbientBirds2 = Content.Load<Song>("Sound/ambient/birds2");
AmbientBirds3 = Content.Load<Song>("Sound/ambient/birds3");
AmbientBirds4 = Content.Load<Song>("Sound/ambient/birds4");
AmbientBirds5 = Content.Load<Song>("Sound/ambient/birds5");
AmbientBirds6 = Content.Load<Song>("Sound/ambient/birds6");
AmbientBirds7 = Content.Load<Song>("Sound/ambient/birds7");
AmbientCreepy1 = Content.Load<Song>("Sound/ambient/birds1");
AmbientBirds7 = Content.Load<Song>("Sound/ambient/birds1");*/
}
}
}

View File

@@ -1,4 +1,5 @@
using Microsoft.Xna.Framework;
using CaveGame.Core;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CaveGame.Client
@@ -12,17 +13,6 @@ namespace CaveGame.Client
void Load();
void Unload();
void Update(GameTime gt);
void Draw(SpriteBatch sb);
void Draw(GraphicsEngine gfx);
}
/* public interface IGameState
{
public Game Game { get; }
public bool Active { get; set; }
void Initialize();
void LoadContent();
void UnloadContent();
void Update(GameTime gt);
void Draw(SpriteBatch sb);
}*/
}

View File

@@ -31,8 +31,16 @@ namespace CaveGame.Client
protected DelayedTask localTileUpdateTask;
protected DelayedTask localLightingUpdateTask;
public LocalWorld() : base()
public override int GetHashCode()
{
return base.GetHashCode();
}
public GameClient Client { get; set; }
public LocalWorld(GameClient client) : base()
{
Client = client;
localTileUpdateTask = new DelayedTask(ApplyVisualTileUpdates, 1 / 10.0f);
localLightingUpdateTask = new DelayedTask(GetLatestDataFromLightingThread, 1 / 20.0f);
ParticleSystem = new ParticleEmitter(this);
@@ -40,6 +48,7 @@ namespace CaveGame.Client
RequestedChunks = new List<ChunkCoordinates>();
LoadedChunks = new List<ChunkCoordinates>();
Lighting.On();
Tile.InitializeManager(420);
}
@@ -144,7 +153,7 @@ namespace CaveGame.Client
foreach (IEntity entity in Entities)
entity.ClientUpdate(this, gt);
entity.ClientUpdate(Client, gt);
base.Update(gt);

View File

@@ -1,146 +0,0 @@
using CaveGame.Client.UI;
using CaveGame.Core;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Text;
namespace CaveGame.Client.Menu
{
public class Credits : IGameContext
{
private static List<string> credits = new List<string>
{
">>CAVE GAME",
"",
">Josh O'Leary",
"Programming, Game Design",
"",
">invinciblespeed",
"Art",
"",
">Tyler Stewart",
"Biz",
"",
">Contributing Developers",
"dodeadam - Programming",
"ConcurrentSquared - Programming & Design",
"Mescalyne - Music",
"Bumpylegoman02 - Security Testing & Design",
"WheezyBackports - Community Multiplayer Servers",
"",
">Testing",
"Andrew J.",
"squidthonkv2",
"Billy J.",
"WheezyBackports",
"",
"Copyright Conarium Software 2020",
};
Microsoft.Xna.Framework.Game IGameContext.Game => Game;
public CaveGameGL Game { get; set; }
public bool Active { get; set; }
static UIRoot CreditsPage;
private void ConstructUIElements()
{
CreditsPage = new UIRoot();
UIRect creditslist = new UIRect
{
Size = new UICoords(0, 0, 1.0f, 1.0f),
Position = new UICoords(0, 0, 0, 0),
Parent = CreditsPage,
BGColor = Color.Black*0.5f,
};
TextButton backButton = new TextButton
{
TextColor = Color.White,
Text = "BACK",
Font = GameFonts.Arial16,
Size = new UICoords(100, 30, 0, 0),
Position = new UICoords(10, -30, 0, 1.0f),
AnchorPoint = new Vector2(0, 1),
TextWrap = true,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
Parent = creditslist,
UnselectedBGColor = new Color(0.2f, 0.2f, 0.2f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
};
backButton.OnLeftClick += (btn, mouse) => Game.CurrentGameContext = Game.HomePageContext;
UIListContainer container = new UIListContainer
{
Padding = 0,
Parent = creditslist,
};
foreach(string text in credits)
{
string displayedText = text;
SpriteFont font = GameFonts.Arial14;
int size = 16;
if (text.StartsWith(">>"))
{
font = GameFonts.Arial20;
size = 24;
displayedText = text.Replace(">>", "");
} else if (text.StartsWith(">"))
{
font = GameFonts.Arial16;
size = 20;
displayedText = text.Replace(">", "");
}
var label = new Label
{
TextColor = UITheme.SmallButtonTextColor,
Text = displayedText,
Font = font,
Size = new UICoords(1, size, 1.0f, 0),
BGColor = Color.Black * 0.0f,
TextXAlign = TextXAlignment.Center,
Parent = container,
};
}
}
public Credits(CaveGameGL _game)
{
Game = _game;
}
public void Draw(SpriteBatch sb)
{
sb.Begin();
CreditsPage.Draw(sb);
sb.End();
}
public void Load()
{
if (CreditsPage == null)
ConstructUIElements();
}
public void Unload()
{
}
public void Update(GameTime gt)
{
CreditsPage.Update(gt);
}
}
}

View File

@@ -14,7 +14,13 @@ using CaveGame.Core.LuaInterop;
namespace CaveGame.Client.Menu
{
public static class EnumExtensions
{
public static int ToInt(this GameChatSize e)
{
return (int)e;
}
}
public class MenuManager : IGameContext
{
@@ -37,6 +43,8 @@ namespace CaveGame.Client.Menu
}
}
public string TimeoutMessage { get; set; }
public MenuManager(CaveGameGL _game)
{
@@ -44,11 +52,11 @@ namespace CaveGame.Client.Menu
Game = _game;
}
public void Draw(SpriteBatch sb)
public void Draw(GraphicsEngine GFX)
{
sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointWrap);
CurrentPage?.Draw(sb);
sb.End();
GFX.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointWrap);
CurrentPage?.Draw(GFX);
GFX.End();
}
@@ -64,6 +72,35 @@ namespace CaveGame.Client.Menu
luastate.DoFile(Path.Combine("Assets", "Scripts", "menu.lua"));
}
// Temporary solution until I figure out generics within lua
public Slider<SliderIndex<int>> GetFPSCapSlider()
{
return new UI.Slider<SliderIndex<int>>
{
DataSet = GameSettings.FramerateCapSliderOptions,
Size = new UICoords(0, 25, 0.5f, 0),
AnchorPoint = new Vector2(0.0f, 0.0f),
UnselectedBGColor = new Color(0.6f, 0.6f, 0.6f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
Scrubber = new Scrubber{ Width = 20 },
BGColor = new Color(0.25f, 0.25f, 0.25f),
};
}
public Slider<SliderIndex<GameChatSize>> GetChatSizeSlider()
{
return new UI.Slider<SliderIndex<GameChatSize>>
{
DataSet = GameSettings.ChatSizeSliderOptions,
Size = new UICoords(0, 25, 0.5f, 0),
AnchorPoint = new Vector2(0.0f, 0.0f),
UnselectedBGColor = new Color(0.6f, 0.6f, 0.6f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
Scrubber = new Scrubber { Width = 20 },
BGColor = new Color(0.25f, 0.25f, 0.25f),
};
}
/*
private void ConstructSingleplayerMenu()
{

View File

@@ -28,7 +28,6 @@ namespace CaveGame.Client.Menu
public string IPAddress;
public string Username;
}
[Serializable]
@@ -42,227 +41,4 @@ namespace CaveGame.Client.Menu
public List<string> IPAddress;
}
public class Multiplayer : IGameContext
{
ServerHistoryPersistence serverHistory;
MultiplayerInputHistory inputHistory;
public CaveGameGL Game { get; set; }
Microsoft.Xna.Framework.Game IGameContext.Game => Game;
public bool Active { get; set; }
public Multiplayer(CaveGameGL _game)
{
inputHistory = Configuration.Load<MultiplayerInputHistory>("mphistory.xml");
serverHistory = Configuration.Load<ServerHistoryPersistence>("serverhistory.xml");
Game = _game;
}
private void WhenMouseOverButton(TextButton b, MouseState m)
{
GameSounds.MenuBlip?.Play(1.0f, 1, 0.0f);
}
private void WhenMouseOffButton(TextButton b, MouseState m)
{
GameSounds.MenuBlip?.Play(0.8f, 1, 0.0f);
}
UIRoot MultiplayerPage;
private void Timeout(string message)
{
Game.CurrentGameContext = Game.TimeoutContext;
Game.TimeoutContext.Message = message;
}
private void OnJoinServer(string address, string username)
{
if (address.Length == 0)
{
Timeout("Server Address is empty! Please enter a valid IP Address!");
return;
}
if (username.Length == 0)
{
Timeout("Please enter a nickname!");
return;
}
if (IPAddress.TryParse(address, out IPAddress _) == false)
{
// Timeout("Server Address is not valid!");
// return;
}
Game.CurrentGameContext = Game.InWorldContext;
Game.InWorldContext.NetworkUsername = username;
Game.InWorldContext.ConnectAddress = address;
inputHistory.IPAddress = address;
inputHistory.Username = username;
inputHistory.Save();
}
private void ConstructUIElements()
{
// what would be epic:
// ability to enforce a ui style on
// multiple objects
MultiplayerPage = new UIRoot();
Label title = new Label
{
BGColor = Color.Transparent,
BorderColor = Color.Transparent,
Size = new UICoords(0, 0, 0.3f, 0.1f),
AnchorPoint = new Vector2(0.5f, 0.5f),
Position = new UICoords(0, 0, 0.5f, 0.05f),
Parent = MultiplayerPage,
TextColor = Color.White,
Text = "MULTIPLAYER",
Font = GameFonts.Arial20,
BorderSize = 0,
TextWrap = false,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
};
UIRect buttonList = new UIRect
{
Size = new UICoords(220, -20, 0, 0.8f),
Position = new UICoords(10, 0, 0, 0.1f),
Parent = MultiplayerPage,
BGColor = Color.DarkBlue,
};
UIListContainer buttons = new UIListContainer
{
Padding = 1,
Parent = buttonList,
};
//buttonList.Children.Add(buttons);
//MultiplayerMenu.Children.Add(buttonList);
var serverInputBox = new TextInputLabel
{
// Size = new UICoords(200, 25, 0, 0),
Size = new UICoords(0, 30, 1, 0),
AnchorPoint = new Vector2(0, 0),
//Position = new UICoords(20, 0, 0, 0.2f),
Parent = buttons,
BGColor = new Color(0.2f, 0.2f, 0.3f),
BorderColor = Color.DarkBlue,
//Provider = inputter,
Font = GameFonts.Arial12,
BackgroundText = "Server Address",
BackgroundTextColor = Color.Gray,
TextColor = Color.White,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
};
serverInputBox.Input.InputBuffer = inputHistory.IPAddress;
serverInputBox.Input.Focused = false;
serverInputBox.Input.CursorPosition = inputHistory.IPAddress.Length;
//buttons.Children.Add(serverInputBox);
var usernameInputBox = new TextInputLabel
{
Size = new UICoords(0, 30, 1, 0),
AnchorPoint = new Vector2(0, 0),
// Position = new UICoords(20, 40, 0, 0.2f),
Parent = buttons,
//Text = "Test1",
Font = GameFonts.Arial12,
BGColor = new Color(0.2f, 0.2f, 0.3f),
BorderColor = Color.DarkBlue,
BackgroundText = "Nickname",
BackgroundTextColor = Color.Gray,
TextColor = Color.White,
//Provider = inputter2,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
};
usernameInputBox.Input.InputBuffer = inputHistory.Username;
usernameInputBox.Input.BlacklistedCharacters.Add(' ');
usernameInputBox.Input.Focused = true;
//buttons.Children.Add(usernameInputBox);
var connect = new TextButton
{
Size = new UICoords(0, 35, 1, 0),
//AnchorPoint = new Vector2(0, 1),
//Position = new UICoords(10, -10, 0, 1f),
Parent = buttons,
Text = "CONNECT",
Font = GameFonts.Arial14,
BorderSize = 0,
TextColor = Color.White,
TextWrap = false,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
UnselectedBGColor = new Color(0.2f, 0.2f, 0.2f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
};
connect.OnMouseEnter += WhenMouseOverButton;
connect.OnMouseExit += WhenMouseOffButton;
connect.OnLeftClick += (b, m) => OnJoinServer(serverInputBox.Input.InternalText, usernameInputBox.Input.InternalText);
//buttons.Children.Add(connect);
var back = new TextButton
{
Size = new UICoords(0, 30, 1, 0),
//AnchorPoint = new Vector2(0, 1),
//Position = new UICoords(10, -10, 0, 1f),
Parent = buttons,
Text = "BACK",
Font = GameFonts.Arial14,
BorderSize = 0,
TextColor = Color.White,
TextWrap = false,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
UnselectedBGColor = new Color(0.2f, 0.2f, 0.2f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
};
back.OnMouseEnter += WhenMouseOverButton;
back.OnMouseExit += WhenMouseOffButton;
back.OnLeftClick += (b, m) => Game.CurrentGameContext = Game.HomePageContext;
//MultiplayerMenu.Children.Add(back);
}
public void Draw(SpriteBatch sb)
{
sb.Begin();
MultiplayerPage.Draw(sb);
sb.End();
}
public void Load()
{
if (MultiplayerPage == null)
ConstructUIElements();
}
public void Unload()
{
//throw new NotImplementedException();
}
public void Update(GameTime gt)
{
MultiplayerPage.Update(gt);
}
}
}

View File

@@ -1,4 +1,5 @@
using CaveGame.Client.UI;
using CaveGame.Core;
using CaveGame.Core.Game.Tiles;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
@@ -10,19 +11,7 @@ using System.Text;
namespace CaveGame.Client.Menu
{
// settings:
// Video
// fullscreen (boolean toggle)
// screen resolution (a selection list)
// max particles (particles off)
// Max FPS (Unlimited, 240, 144, 120, 90, 60, 30)
// Audio
// Music Volume
// Menu Volume
// Game Master Volume
// Player Volume
// World Volume
// Entity Volume
public class BindButton : TextButton
{
public event KeysHandler OnRebind;
@@ -41,6 +30,8 @@ namespace CaveGame.Client.Menu
UIRoot SettingsUI;
GraphicsEngine GFX => Game.GraphicsEngine;
public Settings(CaveGameGL _game)
{
Game = _game;
@@ -52,11 +43,11 @@ namespace CaveGame.Client.Menu
public bool Active { get; set; }
public void Draw(SpriteBatch sb)
public void Draw(GraphicsEngine GFX)
{
sb.Begin();
SettingsUI.Draw(sb);
sb.End();
GFX.Begin();
SettingsUI.Draw(GFX);
GFX.End();
}
@@ -85,7 +76,7 @@ namespace CaveGame.Client.Menu
Parent = SettingsUI,
TextColor = Color.White,
Text = "Settings",
Font = GameFonts.Arial20,
Font = GFX.Fonts.Arial20,
BorderSize = 0,
TextWrap = false,
TextXAlign = TextXAlignment.Center,
@@ -112,7 +103,7 @@ namespace CaveGame.Client.Menu
Parent = container,
TextColor = Color.White,
Text = "Fullscreen: "+ReadableBoolean(GameSettings.CurrentSettings.Fullscreen),
Font = GameFonts.Arial14,
Font = GFX.Fonts.Arial14,
Size = new UICoords(0, 25, 1, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
@@ -134,7 +125,7 @@ namespace CaveGame.Client.Menu
Parent = container,
TextColor = Color.White,
Text = "Particles: " + ReadableBoolean(GameSettings.CurrentSettings.Particles),
Font = GameFonts.Arial14,
Font = GFX.Fonts.Arial14,
Size = new UICoords(0, 25, 1, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
@@ -155,7 +146,7 @@ namespace CaveGame.Client.Menu
TextColor = Color.White,
Parent = container,
Size = new UICoords(0, 25, 1, 0),
Font = GameFonts.Arial14,
Font = GFX.Fonts.Arial14,
Text = "Framerate Cap: " + GameSettings.CurrentSettings.FPSLimit,
};
@@ -186,7 +177,7 @@ namespace CaveGame.Client.Menu
TextColor = Color.White,
Parent = container,
Size = new UICoords(0, 25, 1, 0),
Font = GameFonts.Arial14,
Font = GFX.Fonts.Arial14,
Text = "Chat Size: " + GameSettings.ChatSizeSliderOptions[(int)GameSettings.CurrentSettings.ChatSize].Display,
};
Slider<SliderIndex<GameChatSize>> chatSizeSlider = new UI.Slider<SliderIndex<GameChatSize>>
@@ -227,7 +218,7 @@ namespace CaveGame.Client.Menu
{
TextColor = Color.White,
Text = "Jump: " + GameSettings.CurrentSettings.JumpKey.ToString(),
Font = GameFonts.Arial14,
Font = GFX.Fonts.Arial14,
Size = new UICoords(0, 25, 1, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
@@ -249,7 +240,7 @@ namespace CaveGame.Client.Menu
{
TextColor = Color.White,
Text = "Climb/Up: " + GameSettings.CurrentSettings.MoveUpKey.ToString(),
Font = GameFonts.Arial14,
Font = GFX.Fonts.Arial14,
Size = new UICoords(0, 25, 1, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
@@ -266,7 +257,7 @@ namespace CaveGame.Client.Menu
{
TextColor = Color.White,
Text = "Descend/Down: " + GameSettings.CurrentSettings.MoveDownKey.ToString(),
Font = GameFonts.Arial14,
Font = GFX.Fonts.Arial14,
Size = new UICoords(0, 25, 1, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
@@ -287,7 +278,7 @@ namespace CaveGame.Client.Menu
{
TextColor = Color.White,
Text = "Walk Left: " + GameSettings.CurrentSettings.MoveLeftKey.ToString(),
Font = GameFonts.Arial14,
Font = GFX.Fonts.Arial14,
Size = new UICoords(0, 25, 1, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
@@ -307,7 +298,7 @@ namespace CaveGame.Client.Menu
{
TextColor = Color.White,
Text = "Walk Right: " + GameSettings.CurrentSettings.MoveRightKey.ToString(),
Font = GameFonts.Arial14,
Font = GFX.Fonts.Arial14,
Size = new UICoords(0, 25, 1, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
@@ -327,7 +318,7 @@ namespace CaveGame.Client.Menu
{
TextColor = Color.White,
Text = "BACK",
Font = GameFonts.Arial16,
Font = GFX.Fonts.Arial16,
Size = new UICoords(100, 30, 0, 0),
Position = new UICoords(10, -30, 0, 1.0f),
AnchorPoint = new Vector2(0, 1),
@@ -339,7 +330,7 @@ namespace CaveGame.Client.Menu
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
};
backButton.OnLeftClick += (btn, mouse) => Game.CurrentGameContext = Game.HomePageContext;
backButton.OnLeftClick += (btn, mouse) => Game.CurrentGameContext = Game.MenuContext;
}
BindButton rebinding;

View File

@@ -1,101 +0,0 @@
using CaveGame.Client.UI;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Text;
namespace CaveGame.Client.Menu
{
public class TimeoutMenu : IGameContext
{
public CaveGameGL Game { get; set; }
Microsoft.Xna.Framework.Game IGameContext.Game => Game;
UIRoot TimeoutPage;
public bool Active { get; set; }
public string Message { get; set; }
public TimeoutMenu(CaveGameGL _game)
{
Game = _game;
}
private void ConstructUIElements()
{
TimeoutPage = new UIRoot();
Label message = new Label
{
BGColor = Color.Transparent,
BorderColor = Color.Transparent,
Size = new UICoords(0, 0, 1.0f, 0.1f),
AnchorPoint = new Vector2(0.5f, 0.5f),
Position = new UICoords(0, 0, 0.5f, 0.3f),
Parent = TimeoutPage,
Text = Message,
TextColor = Color.White,
Font = GameFonts.Arial16,
BorderSize = 0,
TextWrap = false,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
};
TextButton back = new TextButton
{
Parent = TimeoutPage,
Size = new UICoords(200, 30, 0, 0),
AnchorPoint = new Vector2(0.5f, 0.5f),
Position = new UICoords(0, 0, 0.5f, 0.7f),
Text = "Back",
Font = GameFonts.Arial10,
BorderSize = 0,
TextColor = Color.White,
TextWrap = false,
TextYAlign = TextYAlignment.Center,
TextXAlign = TextXAlignment.Center,
UnselectedBGColor = new Color(0.2f, 0.2f, 0.2f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
};
back.OnMouseEnter += WhenMouseOverButton;
back.OnMouseExit += WhenMouseOffButton;
back.OnLeftClick += (b, m) => Game.CurrentGameContext = Game.HomePageContext;
}
public void Load()
{
if (TimeoutPage == null)
ConstructUIElements();
}
private void WhenMouseOverButton(TextButton b, MouseState m) {
GameSounds.MenuBlip?.Play(1.0f, 1, 0.0f);
}
private void WhenMouseOffButton(TextButton b, MouseState m)
{
GameSounds.MenuBlip?.Play(0.8f, 1, 0.0f);
}
public void Unload()
{
}
public void Update(GameTime gt)
{
TimeoutPage.Update(gt);
}
public void Draw(SpriteBatch sb)
{
sb.Begin();
TimeoutPage.Draw(sb);
sb.End();
}
}
}

View File

@@ -1,4 +1,5 @@
using Microsoft.Xna.Framework;
using CaveGame.Core;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
@@ -9,6 +10,6 @@ namespace CaveGame.Client.Menu
public static class UITheme
{
public static Color SmallButtonTextColor = Color.White;
public static SpriteFont SmallButtonFont = GameFonts.Arial10;
public static SpriteFont SmallButtonFont = GraphicsEngine.Instance.Fonts.Arial10;
}
}

View File

@@ -8,6 +8,7 @@ using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Collections.Concurrent;
namespace CaveGame.Core.Particles
{
@@ -15,7 +16,7 @@ namespace CaveGame.Core.Particles
public abstract class Particle
{
public virtual void Draw(SpriteBatch sb) { }
public virtual void Draw(GraphicsEngine gfx) { }
public virtual void Update(GameTime gt) { }
public virtual void PhysicsStep(IGameWorld world, float step) { }
public virtual void OnCollide(IGameWorld world, Tile t, Vector2 separation, Vector2 Normal) { }
@@ -24,23 +25,22 @@ namespace CaveGame.Core.Particles
public virtual float MaxParticleAge { get; }
private bool _disposed = false;
}
protected virtual void Dispose(bool disposing)
public class ObjectPool<T>
{
private readonly ConcurrentBag<T> _objects;
private readonly Func<T> _objectGenerator;
public ObjectPool(Func<T> objectGenerator)
{
if (_disposed)
return;
if (disposing)
_disposed = true;
_objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator));
_objects = new ConcurrentBag<T>();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public T Get() => _objects.TryTake(out T item) ? item : _objectGenerator();
public void Return(T item) => _objects.Add(item);
}
@@ -52,26 +52,30 @@ namespace CaveGame.Core.Particles
public static float Mass = 0.1f;
public override float MaxParticleAge => 2.0f;
private Rotation rotation;
private Vector2 position;
private Color color;
private float scale;
private Vector2 nextPosition;
private Vector2 velocity;
private Vector2 accelleration;
public Rotation Rotation { get; set; }
public Vector2 Position { get; set; }
public Color Color { get; set; }
public float Scale { get; set; }
public Vector2 NextPosition;
public Vector2 Velocity;
public Vector2 Accelleration;
public SmokeParticle() { }
public SmokeParticle(Vector2 _position, Color _color, Rotation _rotation, float _scale, Vector2 _accel)
{
position = _position;
color = _color;
rotation = _rotation;
scale = _scale;
accelleration = _accel;
public void Initialize(Vector2 _position, Color _color, Rotation _rotation, float _scale, Vector2 _accel)
{
ParticleAge = 0;
Position = _position;
Color = _color;
Rotation = _rotation;
Scale = _scale;
Accelleration = _accel;
//velocity = _velocity;
NextPosition = _position;
Dead = false;
nextPosition = _position;
}
public override void Update(GameTime gt)
@@ -82,23 +86,23 @@ namespace CaveGame.Core.Particles
public override void PhysicsStep(IGameWorld world, float step)
{
velocity += (accelleration * step*3);
accelleration -= (accelleration * step*3);
Velocity += (Accelleration * step*3);
Accelleration -= (Accelleration * step*3);
velocity = new Vector2(velocity.X * Friction.X, velocity.Y * Friction.Y);
Velocity = new Vector2(Velocity.X * Friction.X, Velocity.Y * Friction.Y);
position = nextPosition;
nextPosition += velocity;
Position = NextPosition;
NextPosition += Velocity;
//base.PhysicsStep(world, step);
}
public override void Draw(SpriteBatch sb)
public override void Draw(GraphicsEngine gfx)
{
float alpha = Math.Min(1, (1- (ParticleAge / MaxParticleAge))*2);
sb.Draw(GameTextures.ParticleSet, position, Quad, color*alpha, rotation.Radians, Origin, scale, SpriteEffects.None, 0);
gfx.Sprite(gfx.ParticleSet, Position, Quad, Color*alpha, Rotation, Origin, Scale, SpriteEffects.None, 0);
}
public override void OnCollide(IGameWorld world, Tile t, Vector2 separation, Vector2 Normal)
@@ -126,68 +130,69 @@ namespace CaveGame.Core.Particles
public class ParticleEmitter
{
const int MAX_PARTICLES = 4096;
private CircularArray<Particle> particles;
ObjectPool<SmokeParticle> SmokeParticlePool = new ObjectPool<SmokeParticle>(() => new SmokeParticle());
private List<Particle> Particles;
public IGameWorld World { get; set; }
public ParticleEmitter(IGameWorld world)
{
World = world;
particles = new CircularArray<Particle>(MAX_PARTICLES);
Particles = new List<Particle>();
}
public void Add(Particle p)
public void Add(Particle p) => Particles.Add(p);
public void EmitSmokeParticle(Vector2 position, Color color, Rotation rotation, float scale, Vector2 accel)
{
particles.Next(p);
var myParticle = SmokeParticlePool.Get();
myParticle.Initialize(position, color, rotation, scale, accel);
Add(myParticle);
}
public void Update(GameTime gt)
{
Particle particle;
for (int i = 0; i <particles.Size; i++)
foreach (var particle in Particles.ToArray())
{
particles.Get(i, out particle);
if (particle == null)
continue;
if (particle.ParticleAge > particle.MaxParticleAge)
particle.Dead = true;
if (particle.Dead)
if (particle.Dead && particle is SmokeParticle smokey)
{
particle.Dispose();
SmokeParticlePool.Return(smokey);
Particles.Remove(particle);
continue;
}
particle.Update(gt);
}
}
public void Draw(SpriteBatch sb)
public void Draw(GraphicsEngine gfx)
{
Particle particle;
for (int i = 0; i < particles.Size; i++)
foreach (Particle particle in Particles)
{
particles.Get(i, out particle);
if (particle == null)
continue;
if (particle.Dead)
continue;
particle.Draw(sb);
particle.Draw(gfx);
}
}
public void PhysicsStep(IGameWorld world, float step)
{
Particle particle;
for (int i = 0; i < particles.Size; i++)
foreach (Particle particle in Particles)
{
particles.Get(i, out particle);
if (particle == null)
continue;

103
Client/PauseMenu.cs Normal file
View File

@@ -0,0 +1,103 @@
using CaveGame.Client.UI;
using CaveGame.Core;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Text;
namespace CaveGame.Client
{
public class PauseMenu
{
public PauseMenu(GameClient client)
{
Client = client;
}
public GameClient Client { get; private set; }
public UIRoot Menu { get; private set; }
public bool Open { get; set; }
Effect WaterpixelsShader { get; set; }
public void DrawWaterPixelsFilter(GraphicsEngine gfx)
{
WaterpixelsShader.Parameters["xSize"].SetValue((float)256);
WaterpixelsShader.Parameters["ySize"].SetValue((float)256);
WaterpixelsShader.Parameters["xDraw"].SetValue((float)16);
WaterpixelsShader.Parameters["yDraw"].SetValue((float)16);
//effect.Parameters["filterColor"].SetValue(Color.White.ToVector4());
WaterpixelsShader.CurrentTechnique.Passes[0].Apply();
}
public void LoadShader(ContentManager GameContent)
{
WaterpixelsShader = GameContent.Load<Effect>("ShaderTest");
}
public void Update(GameTime gt) {
if (Open)
Menu.Update(gt);
}
public void Draw(GraphicsEngine gfx)
{
if (Open)
Menu.Draw(gfx);
}
private void ConstructPauseMenu(GraphicsEngine gfx)
{
Menu = new UIRoot();
UIRect bg = new UIRect
{
BGColor = Color.Transparent,
Size = new UICoords(0, 0, 1, 1),
Position = new UICoords(0, 0, 0, 0),
Parent = Menu
};
TextButton resumeButton = new TextButton
{
Parent = bg,
TextColor = Color.White,
Text = "Resume",
Font = gfx.Fonts.Arial14,
Size = new UICoords(150, 25, 0, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
UnselectedBGColor = new Color(0.2f, 0.2f, 0.2f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
Position = new UICoords(10, -100, 0, 1)
};
resumeButton.OnLeftClick += (x, y) => Open = false;
TextButton exitButton = new TextButton
{
Parent = bg,
TextColor = Color.White,
Text = "Disconnect",
Font = gfx.Fonts.Arial14,
Size = new UICoords(150, 25, 0, 0),
TextXAlign = TextXAlignment.Center,
TextYAlign = TextYAlignment.Center,
UnselectedBGColor = new Color(0.2f, 0.2f, 0.2f),
SelectedBGColor = new Color(0.1f, 0.1f, 0.1f),
Position = new UICoords(10, -50, 0, 1)
};
exitButton.OnLeftClick += TryClientExit;
}
public void TryClientExit(TextButton tbtn, MouseState ms)
{
}
}
}

View File

@@ -1,6 +1,7 @@
using CaveGame.Client.Game.Entities;
using CaveGame.Core;
using CaveGame.Core.Game.Inventory;
using CaveGame.Core.Generic;
using CaveGame.Core.Inventory;
using DataManagement;
using Microsoft.Xna.Framework;
@@ -58,48 +59,48 @@ namespace CaveGame.Client
private string GetDisplayStringForItemQuantity(int quantity) => quantity.ToString() + "x";
private void DrawTextForStack(SpriteBatch sb, Vector2 slotPos, float uiScale, int quantity, Color color)
private void DrawTextForStack(GraphicsEngine gfx, Vector2 slotPos, float uiScale, int quantity, Color color)
{
string displayStr = GetDisplayStringForItemQuantity(quantity);
Vector2 dimensions = GameFonts.Arial16.MeasureString(displayStr);
Vector2 dimensions = gfx.Fonts.Arial16.MeasureString(displayStr);
Vector2 offset = new Vector2(ItemTextureSize * uiScale, ItemTextureSize * uiScale) - dimensions;
//sb.Print(GameFonts.Arial16, Color.Black, slotPos + offset + new Vector2(4, 4), displayStr);
sb.Print(GameFonts.Arial16, color, slotPos + offset, displayStr);
gfx.Text(gfx.Fonts.Arial16, displayStr, slotPos + offset, color);
}
private void DrawItemSlot(SpriteBatch sb, Vector2 containerOffset, Point position, float uiScale, ItemStack stack, bool bgOverride = false)
private void DrawItemSlot(GraphicsEngine gfx, Vector2 containerOffset, Point position, float uiScale, ItemStack stack, bool bgOverride = false)
{
Vector2 slotPos = GetSlotIndexPosition(containerOffset, position, uiScale);
if (!bgOverride)
sb.Draw(GameTextures.Slot, slotPos - new Vector2(1, 1), null, Color.Gray, 0, Vector2.Zero, uiScale, SpriteEffects.None, 0);
gfx.Sprite(gfx.Slot, slotPos - new Vector2(1, 1), null, Color.Gray, Rotation.Zero, Vector2.Zero, uiScale, SpriteEffects.None, 0);
if (!stack.Equals(ItemStack.Empty))
{
stack.Item?.Draw(sb, slotPos, uiScale);
stack.Item?.Draw(gfx, slotPos, uiScale);
if (stack.Quantity > 1)
DrawTextForStack(sb, slotPos, uiScale, stack.Quantity, Color.White);
DrawTextForStack(gfx, slotPos, uiScale, stack.Quantity, Color.White);
}
}
private void DrawHighlightedItemSlot(SpriteBatch sb, Vector2 containerOffset, Point position, float uiScale, ItemStack stack)
private void DrawHighlightedItemSlot(GraphicsEngine gfx, Vector2 containerOffset, Point position, float uiScale, ItemStack stack)
{
Vector2 slotPos = GetSlotIndexPosition(containerOffset, position, uiScale);
sb.Draw(GameTextures.Slot, slotPos-new Vector2(1, 1), null, Color.White, 0, Vector2.Zero, uiScale, SpriteEffects.None, 0);
gfx.Sprite(gfx.Slot, slotPos-new Vector2(1, 1), null, Color.White, Rotation.Zero, Vector2.Zero, uiScale, SpriteEffects.None, 0);
if (!stack.Equals(ItemStack.Empty))
{
stack.Item?.Draw(sb, slotPos, UIScale);
stack.Item?.Draw(gfx, slotPos, UIScale);
if (stack.Quantity > 1)
DrawTextForStack(sb, slotPos, uiScale, stack.Quantity, Color.Black);
DrawTextForStack(gfx, slotPos, uiScale, stack.Quantity, Color.Black);
}
}
private void DrawOpenInventory(SpriteBatch sb)
private void DrawOpenInventory(GraphicsEngine gfx)
{
// the player's primary inventory
@@ -110,14 +111,25 @@ namespace CaveGame.Client
ItemStack stack = Container.GetItemStack(x, y);
if (IsHighlighted && HighlightedSlot.X == x && HighlightedSlot.Y == y)
DrawHighlightedItemSlot(sb, InventoryDrawPosition, new Point(x, y), UIScale, stack);
{
DrawHighlightedItemSlot(gfx, InventoryDrawPosition, new Point(x, y), UIScale, stack);
if (!stack.Equals(ItemStack.Empty))
{
string text = stack.Item.DisplayName;
Vector2 offset = gfx.Fonts.Arial16.MeasureString(text);
gfx.Text(gfx.Fonts.Arial16, text, InventoryDrawPosition + new Vector2(-(offset.X+10) , 20));
}
}
else
DrawItemSlot(sb, InventoryDrawPosition, new Point(x, y), UIScale, stack);
DrawItemSlot(gfx, InventoryDrawPosition, new Point(x, y), UIScale, stack);
}
}
}
private void DrawHotbar(SpriteBatch sb)
private void DrawHotbar(GraphicsEngine gfx)
{
// draw top of hotbar
for (int x = 0; x < Container.Width; x++)
@@ -125,34 +137,34 @@ namespace CaveGame.Client
ItemStack stack = Container.GetItemStack(x, 0);
if (IsHighlighted && HighlightedSlot.X == x)
DrawHighlightedItemSlot(sb, HotbarDrawPosition, new Point(x, 0), UIScale, stack);
DrawHighlightedItemSlot(gfx, HotbarDrawPosition, new Point(x, 0), UIScale, stack);
else
DrawItemSlot(sb, HotbarDrawPosition, new Point(x, 0), UIScale, stack);
DrawItemSlot(gfx, HotbarDrawPosition, new Point(x, 0), UIScale, stack);
}
}
private void DrawMouseHeldItem(SpriteBatch sb)
private void DrawMouseHeldItem(GraphicsEngine gfx)
{
MouseState ms = Mouse.GetState();
DrawItemSlot(sb, ms.Position.ToVector2(), new Point(0, 0), UIScale, MouseHeldItem, true);
DrawItemSlot(gfx, ms.Position.ToVector2(), new Point(0, 0), UIScale, MouseHeldItem, true);
}
public void Draw(SpriteBatch sb)
public void Draw(GraphicsEngine gfx)
{
if (Player == null)
return;
if (InventoryOpen)
DrawOpenInventory(sb);
DrawOpenInventory(gfx);
else
DrawHotbar(sb);
DrawHotbar(gfx);
if (MouseHeldItem!=null)
{
DrawMouseHeldItem(sb);
DrawMouseHeldItem(gfx);
}
}

View File

@@ -1,195 +0,0 @@
using CaveGame;
using CaveGame.Core.Game.Entities;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaveGame.Client
{
using Circle = List<Vector2>;
using Arc = List<Vector2>;
static class ShapeCache
{
private static readonly Dictionary<String, Circle> circleCache = new Dictionary<string, Circle>();
public static Arc GetArc(float radius, int sides, float startingAngle, float radians)
{
Arc points = new Arc();
points.AddRange(GetCircle(radius, sides));
points.RemoveAt(points.Count - 1);
double curAngle = 0.0;
double anglePerSide = MathHelper.TwoPi / sides;
while ((curAngle + (anglePerSide / 2.0)) < startingAngle)
{
curAngle += anglePerSide;
points.Add(points[0]);
points.RemoveAt(0);
}
points.Add(points[0]);
int sidesInArc = (int)((radians / anglePerSide) + 0.5);
points.RemoveRange(sidesInArc + 1, points.Count - sidesInArc - 1);
return points;
}
public static Circle GetCircle(double radius, int sides)
{
String circleKey = radius + "x" + sides;
if (circleCache.ContainsKey(circleKey))
return circleCache[circleKey];
Circle circleDef = new Circle();
const double max = 2.0 * Math.PI;
double step = max / sides;
for (double theta = 0.0; theta < max; theta += step)
{
circleDef.Add(new Vector2( (float) (radius * Math.Cos(theta)), (float)(radius * Math.Sin(theta))));
}
circleDef.Add(new Vector2((float)(radius * Math.Cos(0)), (float)(radius * Math.Sin(0))));
circleCache.Add(circleKey, circleDef);
return circleDef;
}
}
public static class Renderer
{
static Texture2D _pixel;
static Microsoft.Xna.Framework.Game _game;
static BasicEffect _effect3D;
public static void Initialize(Microsoft.Xna.Framework.Game game)
{
_game = game;
_pixel = new Texture2D(game.GraphicsDevice, 1, 1);
_pixel.SetData<Color>(new Color[] { Color.White });
_effect3D = new BasicEffect(game.GraphicsDevice);
}
public static void OutlineRect(this SpriteBatch sb, Color color, Vector2 position, Vector2 size, float thickness = 2.0f)
{
Line(sb, color, position, position + new Vector2(0, size.Y), thickness);
Line(sb, color, position, position + new Vector2(size.X, 0), thickness);
Line(sb, color, position + new Vector2(size.X, 0), position + size, thickness);
Line(sb, color, position + new Vector2(0, size.Y), position + new Vector2(size.X, size.Y), thickness);
}
public static void Rect(this SpriteBatch sb, Color color, Vector2 position, Vector2 size, float rotation = 0)
{
Rect(sb, color, (int)position.X, (int)position.Y, (int)size.X, (int)size.Y, rotation);
}
public static void Rect(this SpriteBatch sb, Color color, int x, int y, int width, int height, float rotation = 0)
{
sb.Draw(
_pixel,
new Rectangle(x, y, width, height),
null,
color, rotation, new Vector2(0, 0), SpriteEffects.None, 0
);
// retardretardretardretardretardretard
}
public static void Line(this SpriteBatch spriteBatch, Color color, Vector2 point1, Vector2 point2, float thickness = 1f)
{
float distance = Vector2.Distance(point1, point2);
float angle = (float)Math.Atan2(point2.Y - point1.Y, point2.X - point1.X);
float expanded = (float)Math.Floor(angle * Math.PI);
float backDown = expanded / (float)Math.PI;
Line(spriteBatch, color, point1, distance, angle, thickness);
}
public static void Line(this SpriteBatch sb, Color color, Vector2 point, float length, float angle, float thickness = 1f)
{
Vector2 origin = new Vector2(0f, 0.5f);
Vector2 scale = new Vector2(length, thickness);
sb.Draw(_pixel, point, null, color, angle, origin, scale, SpriteEffects.None, 0);
}
public static void Points(this SpriteBatch sb, Color color, List<Vector2> points, float thickness = 1f)
{
if (points.Count < 2)
return;
for (int i = 1; i < points.Count; i++)
{
Line(sb, color, points[i - 1], points[i], thickness);
}
}
public static void Points(this SpriteBatch sb, Color color, Vector2 position, List<Vector2> points, float thickness = 1f)
{
if (points.Count < 2)
return;
for (int i = 1; i < points.Count; i++)
{
Line(sb, color, points[i - 1]+position, points[i]+position, thickness);
}
}
public static void Circle(this SpriteBatch sb, Color color, Vector2 position, double radius, int sides = 12, float thickness = 1f)
{
Circle c = ShapeCache.GetCircle(radius, sides);
Points(sb, color, position, c, thickness);
}
public static void Arc(this SpriteBatch sb, Color color, Vector2 center, float radius, int sides, float startingAngle, float radians, float thickness = 1f)
{
Arc arc = ShapeCache.GetArc(radius, sides, startingAngle, radians);
Points(sb, color, center, arc, thickness);
}
public static void Print(this SpriteBatch sb, Color color, Vector2 position, string text)
{
Print(sb, GameFonts.Arial10, color, position, text);
}
public static void Print(this SpriteBatch sb, SpriteFont font, Color color, Vector2 position, string text)
{
sb.DrawString(font, text, position, color);
}
/*public static void Line3D(this SpriteBatch sb, Camera camera, Vector3 pointA, Vector3 pointB, Color color)
{
Line3D(camera, pointA, pointB, color, color);
}
public static void Line3D(this SpriteBatch sb, Camera camera, Vector3 pointA, Vector3 pointB, Color colorA, Color colorB)
{
Line3D(camera, pointA, pointB, colorA, colorB);
}
public static void Line3D(Camera camera, Vector3 pointA, Vector3 pointB, Color color)
{
Line3D(camera, pointA, pointB, color, color);
}
public static void Line3D(Camera camera, Vector3 pointA, Vector3 pointB, Color colorA, Color colorB)
{
_effect3D.View = camera.View;
_effect3D.Projection = camera.Projection;
_effect3D.CurrentTechnique.Passes[0].Apply();
var vertices = new[] { new VertexPositionColor(pointA, colorA), new VertexPositionColor(pointB, colorB)};
_game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, vertices, 0, 1);
}*/
}
}

50
Client/Splash.cs Normal file
View File

@@ -0,0 +1,50 @@
using CaveGame.Core;
using CaveGame.Core.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Text;
namespace CaveGame.Client
{
public class Splash
{
public bool SplashActive => (SplashTimer > 0);
public float SplashTimer { get; set; }
public Splash()
{
SplashTimer = 5;
}
public void Update(GameTime gt)
{
SplashTimer -= gt.GetDelta();
}
public void Draw(GraphicsEngine GraphicsEngine)
{
GraphicsEngine.Clear(Color.Black);
//GraphicsEngine.Begin();
GraphicsEngine.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp);
Vector2 center = new Vector2(GraphicsEngine.WindowSize.X / 2.0f, GraphicsEngine.WindowSize.Y / 2.0f);
Vector2 origin = new Vector2(GraphicsEngine.EyeOfHorus.Width / 2.0f, GraphicsEngine.EyeOfHorus.Height / 2.0f);
float scale = 8;
Vector2 bounds = GraphicsEngine.Fonts.Arial30.MeasureString("CONARIUM SOFTWARE");
GraphicsEngine.Sprite(GraphicsEngine.EyeOfHorus, center - new Vector2(0, (float)Math.Sin(SplashTimer * 2) * 10), null, Color.White, Rotation.Zero, origin, scale, SpriteEffects.None, 0);
GraphicsEngine.Text(
font: GraphicsEngine.Fonts.Arial30,
text: "CONARIUM SOFTWARE",
position: center + new Vector2(0, 100), Color.White, TextXAlignment.Center, TextYAlignment.Center);
GraphicsEngine.End();
}
}
}

View File

@@ -9,19 +9,7 @@ using System.Text;
namespace CaveGame.Client.UI
{
public enum TextXAlignment
{
Left,
Center,
Right
}
public enum TextYAlignment
{
Top,
Center,
Bottom,
}
public interface ITextInputListener
@@ -88,8 +76,14 @@ namespace CaveGame.Client.UI
BackgroundTextColor = Color.Gray;
}
public TextInputLabel(NLua.Lua state, NLua.LuaTable table) : base(state, table)
{
Input = new TextInput();
TextInputManager.ListenTextInput += Input.OnTextInput;
Selected = false;
}
private bool IsMouseInside(MouseState mouse)
{
@@ -129,7 +123,7 @@ namespace CaveGame.Client.UI
base.Update(gt);
}
public override void Draw(SpriteBatch sb)
public override void Draw(GraphicsEngine GFX)
{
Vector2 textDim = Font.MeasureString(BackgroundText);
Vector2 TextOutputPosition = AbsolutePosition;
@@ -159,7 +153,7 @@ namespace CaveGame.Client.UI
if (Input.SpecialSelection)
{
base.Draw(sb, false);
base.Draw(GFX, true);
var beforeText = Input.GetScissorTextBefore();
var middleText = Input.GetScissorTextDuring();
var afterText = Input.GetScissorTextAfter();
@@ -169,18 +163,18 @@ namespace CaveGame.Client.UI
//sb.Rect(Color.Blue, TextOutputPosition + new Vector2(start.X, 0), end);
// first section
sb.Print(Font, TextColor, TextOutputPosition, beforeText);
sb.Print(Font, Color.Black, TextOutputPosition + new Vector2(start.X, 0), middleText);
sb.Print(Font, TextColor, TextOutputPosition + new Vector2(start.X + end.X, 0), afterText);
GFX.Text(Font, beforeText, TextOutputPosition, TextColor);
GFX.Text(Font, middleText, TextOutputPosition + new Vector2(start.X, 0), Color.Black);
GFX.Text(Font, afterText , TextOutputPosition + new Vector2(start.X + end.X, 0), TextColor);
} else
{
base.Draw(sb, false);
base.Draw(GFX, false);
//sb.Print(Font, TextColor, TextOutputPosition, Input.InputBuffer);
}
if (Input.InputBuffer == "")
{
sb.Print(Font, BackgroundTextColor, TextOutputPosition, BackgroundText);
GFX.Text(Font, BackgroundText , TextOutputPosition, BackgroundTextColor);
}
}
}
@@ -261,15 +255,17 @@ namespace CaveGame.Client.UI
return Font.MeasureString(Text);
}
public void Draw(SpriteBatch sb, bool TextOverride)
public void Draw(GraphicsEngine GFX, bool TextOverride)
{
base.Draw(sb);
base.Draw(GFX);
if (TextOverride)
return;
string DisplayedText = Text;
string DisplayedText = "";
if (Text!=null)
DisplayedText = Text;
if (TextWrap)
DisplayedText = WrapText(Font, Text, AbsoluteSize.X);
@@ -295,12 +291,12 @@ namespace CaveGame.Client.UI
TextOutputPosition += new Vector2(0, AbsoluteSize.Y - textDim.Y);
}
TextOutputPosition.Floor();
sb.Print(Font, TextColor, TextOutputPosition, DisplayedText);
GFX.Text(Font, DisplayedText, TextOutputPosition, TextColor);
}
public override void Draw(SpriteBatch sb)
public override void Draw(GraphicsEngine GFX)
{
Draw(sb, false);
Draw(GFX, false);
}
}
}

View File

@@ -1,4 +1,5 @@
using Microsoft.Xna.Framework;
using CaveGame.Core;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
@@ -32,11 +33,11 @@ namespace CaveGame.Client.UI
public new UICoords Position { get => Parent.Position; set { } }
public new UICoords Size { get => Parent.Size; set { } }
public override void Draw(SpriteBatch sb)
public override void Draw(GraphicsEngine GFX)
{
// topleft
sb.Draw(Texture, AbsolutePosition, TopLeftCornerQuad, Color, 0, Vector2.Zero, TextureScale, SpriteEffects.None, 0);
GFX.Sprite(Texture, AbsolutePosition, TopLeftCornerQuad, Color, Rotation.Zero, Vector2.Zero, TextureScale, SpriteEffects.None, 0);
// left
Vector2 TopLeftCornerOffset = new Vector2(TopLeftCornerQuad.Width * TextureScale, TopLeftCornerQuad.Height * TextureScale);
@@ -45,30 +46,30 @@ namespace CaveGame.Client.UI
Vector2 BottomRightCornerOffset = new Vector2(BottomRightCornerQuad.Width * TextureScale, BottomRightCornerQuad.Height * TextureScale);
float SideLength = AbsoluteSize.Y - TopLeftCornerOffset.Y - BottomLeftCornerOffset.Y;
sb.Draw(Texture, AbsolutePosition + new Vector2(0, TopLeftCornerOffset.Y), LeftSideQuad, Color, 0, Vector2.Zero, new Vector2(TextureScale, SideLength / LeftSideQuad.Height), SpriteEffects.None, 0);
GFX.Sprite(Texture, AbsolutePosition + new Vector2(0, TopLeftCornerOffset.Y), LeftSideQuad, Color, Rotation.Zero, Vector2.Zero, new Vector2(TextureScale, SideLength / LeftSideQuad.Height), SpriteEffects.None, 0);
//bottomleft
sb.Draw(Texture, AbsolutePosition + new Vector2(0, SideLength + TopLeftCornerOffset.Y), BottomLeftCornerQuad, Color, 0, Vector2.Zero, TextureScale, SpriteEffects.None, 0);
GFX.Sprite(Texture, AbsolutePosition + new Vector2(0, SideLength + TopLeftCornerOffset.Y), BottomLeftCornerQuad, Color, Rotation.Zero, Vector2.Zero, TextureScale, SpriteEffects.None, 0);
//top
float TopLength = AbsoluteSize.X - TopLeftCornerOffset.X - TopRightCornerOffset.X;
sb.Draw(Texture, AbsolutePosition +new Vector2(TopLeftCornerOffset.X, 0), TopSideQuad, Color, 0, Vector2.Zero, new Vector2(TopLength/TopSideQuad.Width, TextureScale), SpriteEffects.None, 0);
GFX.Sprite(Texture, AbsolutePosition +new Vector2(TopLeftCornerOffset.X, 0), TopSideQuad, Color, Rotation.Zero, Vector2.Zero, new Vector2(TopLength/TopSideQuad.Width, TextureScale), SpriteEffects.None, 0);
// topright
Vector2 TopRightOffset = new Vector2(TopLeftCornerOffset.X + TopLength, 0);
sb.Draw(Texture, AbsolutePosition + TopRightOffset, TopRightCornerQuad, Color, 0, Vector2.Zero, TextureScale, SpriteEffects.None, 0);
GFX.Sprite(Texture, AbsolutePosition + TopRightOffset, TopRightCornerQuad, Color, Rotation.Zero, Vector2.Zero, TextureScale, SpriteEffects.None, 0);
// Right
sb.Draw(Texture, AbsolutePosition + new Vector2(TopRightOffset.X, TopRightCornerOffset.Y), RightSideQuad, Color, 0, Vector2.Zero, new Vector2(TextureScale, SideLength / RightSideQuad.Height), SpriteEffects.None, 0);
GFX.Sprite(Texture, AbsolutePosition + new Vector2(TopRightOffset.X, TopRightCornerOffset.Y), RightSideQuad, Color, Rotation.Zero, Vector2.Zero, new Vector2(TextureScale, SideLength / RightSideQuad.Height), SpriteEffects.None, 0);
// bottomright
sb.Draw(Texture, AbsolutePosition + new Vector2(TopRightOffset.X, TopRightCornerOffset.Y+SideLength), BottomRightCornerQuad, Color, 0, Vector2.Zero, TextureScale, SpriteEffects.None, 0);
GFX.Sprite(Texture, AbsolutePosition + new Vector2(TopRightOffset.X, TopRightCornerOffset.Y+SideLength), BottomRightCornerQuad, Color, Rotation.Zero, Vector2.Zero, TextureScale, SpriteEffects.None, 0);
// bottom
sb.Draw(Texture, AbsolutePosition + TopLeftCornerOffset + new Vector2(0, SideLength), BottomSideQuad, Color, 0, Vector2.Zero, new Vector2(TopLength/BottomSideQuad.Width, TextureScale), SpriteEffects.None, 0);
GFX.Sprite(Texture, AbsolutePosition + TopLeftCornerOffset + new Vector2(0, SideLength), BottomSideQuad, Color, Rotation.Zero, Vector2.Zero, new Vector2(TopLength/BottomSideQuad.Width, TextureScale), SpriteEffects.None, 0);
}

View File

@@ -1,4 +1,6 @@
using Microsoft.Xna.Framework;
using CaveGame.Core;
using CaveGame.Core.LuaInterop;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
@@ -8,14 +10,39 @@ using System.Text;
namespace CaveGame.Client.UI
{
public class SliderChangedEventArgs : LuaEventArgs
{
}
public class Scrubber
{
public int Width { get; set; }
}
public class IntSlider : Slider<SliderIndex<int>>
{
public IntSlider() : base()
{
}
}
public class FloatSlider : Slider<SliderIndex<float>>
{
public FloatSlider() : base()
{
}
}
public class Slider<T> : UIRect
{
public Slider() {
}
public LuaEvent<SliderChangedEventArgs> SliderChanged = new LuaEvent<SliderChangedEventArgs>();
private int selectionIndex = 0;
public T Current {
@@ -132,16 +159,16 @@ namespace CaveGame.Client.UI
base.Update(gt);
}
public override void Draw(SpriteBatch sb)
public override void Draw(GraphicsEngine GFX)
{
base.Draw(sb);
base.Draw(GFX);
Color sliderColor;
if (Selected)
sliderColor = SelectedBGColor;
else
sliderColor = UnselectedBGColor;
sb.Rect(sliderColor, new Vector2(AbsolutePosition.X+ scrubberVisualPos, AbsolutePosition.Y), new Vector2(Scrubber.Width, AbsoluteSize.Y));
GFX.Rect(sliderColor, new Vector2(AbsolutePosition.X+ scrubberVisualPos, AbsolutePosition.Y), new Vector2(Scrubber.Width, AbsoluteSize.Y));
}

View File

@@ -8,6 +8,7 @@ using CaveGame;
using CaveGame.Core.LuaInterop;
using NLua;
using System.Diagnostics;
using CaveGame.Core;
namespace CaveGame.Client.UI
{
@@ -104,9 +105,9 @@ namespace CaveGame.Client.UI
base.Update(gt);
}
public override void Draw(SpriteBatch sb)
public override void Draw(GraphicsEngine GFX)
{
base.Draw(sb);
base.Draw(GFX);
}
}
}

View File

@@ -75,15 +75,25 @@ namespace CaveGame.Client.UI
}
public void BlacklistCharacter(char block)
{
BlacklistedCharacters.Add(block);
}
public void BlacklistCharacter(string block)
{
BlacklistedCharacters.Add(block[0]);
}
public void OnTextInput(object sender, TextInputEventArgs args)
{
if (Focused)
{
if (BlacklistedCharacters.Contains(args.Character))
return;
if (args.Key == Keys.Tab)
return;
if (args.Key == Keys.Enter)
{

View File

@@ -1,4 +1,5 @@
using CaveGame.Client.UI;
using CaveGame.Core;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
@@ -56,11 +57,11 @@ namespace CaveGame.Client.UI
ExpandSelected = false;
}
public void Draw(SpriteBatch sb)
public void Draw(GraphicsEngine GFX)
{
foreach (UINode child in Children)
{
child.Draw(sb);
child.Draw(GFX);
}
}

View File

@@ -1,6 +1,7 @@
#define UI_DEBUG
using CaveGame.Core;
using CaveGame.Core.LuaInterop;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
@@ -19,7 +20,7 @@ namespace CaveGame.Client.UI
public interface UIRootNode
{
void Update(GameTime gt);
void Draw(SpriteBatch sb);
void Draw(GraphicsEngine gfx);
List<UINode> Children { get; }
bool Visible { get; }
bool Active { get; }
@@ -144,21 +145,21 @@ namespace CaveGame.Client.UI
}
//[Conditional("UI_DEBUG")]
private void DrawAnchorPoint(SpriteBatch sb)
private void DrawAnchorPoint(GraphicsEngine gfx)
{
sb.Circle(new Color(0, 1, 0.0f), AbsolutePosition + (AnchorPoint*AbsoluteSize), 2);
gfx.Circle(new Color(0, 1, 0.0f), AbsolutePosition + (AnchorPoint*AbsoluteSize), 2);
}
public virtual void Draw(SpriteBatch sb)
public virtual void Draw(GraphicsEngine gfx)
{
sb.Rect(BGColor, AbsolutePosition, AbsoluteSize);
sb.OutlineRect(BorderColor, AbsolutePosition, AbsoluteSize, BorderSize);
DrawAnchorPoint(sb);
gfx.Rect(BGColor, AbsolutePosition, AbsoluteSize);
gfx.OutlineRect(BorderColor, AbsolutePosition, AbsoluteSize, BorderSize);
DrawAnchorPoint(gfx);
foreach (UINode child in Children)
{
child.Draw(sb);
child.Draw(gfx);
}
}
@@ -176,19 +177,9 @@ namespace CaveGame.Client.UI
public List<UINode> Children { get; }
public Vector2 AnchorPoint { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public Vector2 AbsoluteSize {
get {
return new Vector2(GameGlobals.Width, GameGlobals.Height);
}
}
public Vector2 AbsoluteSize { get; private set; }
public Vector2 AbsolutePosition
{
get
{
return Vector2.Zero;
}
}
public Vector2 AbsolutePosition=> Vector2.Zero;
public UICoords Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
@@ -229,11 +220,12 @@ namespace CaveGame.Client.UI
}
}
public virtual void Draw(SpriteBatch sb)
public virtual void Draw(GraphicsEngine gfx)
{
AbsoluteSize = gfx.WindowSize;
foreach (UINode child in Children)
{
child.Draw(sb);
child.Draw(gfx);
}
}

29
Core/AssetLoader.cs Normal file
View File

@@ -0,0 +1,29 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace CaveGame.Core
{
public class AssetLoader
{
private Texture2D FromStream(GraphicsDevice GraphicsProcessor, Stream DataStream)
{
Texture2D Asset = Texture2D.FromStream(GraphicsProcessor, DataStream);
// Fix Alpha Premultiply
Color[] data = new Color[Asset.Width * Asset.Height];
Asset.GetData(data);
for (int i = 0; i != data.Length; ++i)
data[i] = Color.FromNonPremultiplied(data[i].ToVector4());
Asset.SetData(data);
return Asset;
}
public Texture2D LoadTexture(GraphicsDevice device, string filepath) => FromStream(device, TitleContainer.OpenStream(filepath));
}
}

View File

@@ -9,6 +9,7 @@
<Import_RootNamespace>CaveGame.Core</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)AssetLoader.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Camera.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Enums.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FileUtil\FilePathSanitizer.cs" />
@@ -43,12 +44,13 @@
<Compile Include="$(MSBuildThisFileDirectory)Game\Furniture\Furniture.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Generic\CircularArray.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Generic\ThreadSafeValue.cs" />
<Compile Include="$(MSBuildThisFileDirectory)IGameServer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)GraphicsEngine.cs" />
<Compile Include="$(MSBuildThisFileDirectory)IGameMainControllers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Logger.cs" />
<Compile Include="$(MSBuildThisFileDirectory)LuaInterop\LuaEvent.cs" />
<Compile Include="$(MSBuildThisFileDirectory)LuaInterop\LuaInterop.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Network\User.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Generic\Rotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DataTypes\Rotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Physics\RaycastSolver.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Shell.cs" />
<Compile Include="$(MSBuildThisFileDirectory)World\Chunk.cs" />
@@ -83,5 +85,6 @@
</ItemGroup>
<ItemGroup>
<Folder Include="$(MSBuildThisFileDirectory)Game\Items\" />
<Folder Include="$(MSBuildThisFileDirectory)DataTypes\" />
</ItemGroup>
</Project>

View File

@@ -3,10 +3,16 @@ using System;
using System.Collections.Generic;
using System.Text;
namespace CaveGame.Core.Generic
namespace CaveGame.Core
{
public struct Rotation : IEquatable<Rotation>
{
public static Rotation Zero = FromDeg(0);
public static Rotation Pi = FromRad((float)Math.PI);
public static Rotation TwoPi = FromRad((float)Math.PI * 2);
public static Rotation RightAngle = FromDeg(90);
public const float PI = MathHelper.Pi;
private float _radians;
@@ -43,6 +49,10 @@ namespace CaveGame.Core.Generic
return new Rotation { Degrees = degree };
}
public Rotation RotateDeg(float degree) => FromDeg(this.Degrees + degree);
public Rotation RotateRad(float radians) => FromRad(this.Radians + radians);
public bool EqualsRadians(float rad, float toleranceDegrees = 1.0f)
{
return Math.Abs(Radians - rad) < (toleranceDegrees * (PI / 180.0f));

View File

@@ -4,6 +4,7 @@ using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Text;
using CaveGame.Core.Generic;
#if CLIENT
using CaveGame.Client;
@@ -114,26 +115,29 @@ namespace CaveGame.Core.Game.Entities
base.PhysicsStep(world, step);
}
public override void ServerUpdate(IServerWorld world, GameTime gt)
public override void ServerUpdate(IGameServer server, GameTime gt)
{
detonationCountdown -= (float)gt.ElapsedGameTime.TotalSeconds;
if (detonationCountdown <= 0)
Explode(world);
Explode(server.World);
base.ServerUpdate(world, gt);
base.ServerUpdate(server, gt);
}
public void ServerPhysicsTick(IServerWorld world, float step)
{
PhysicsStep(world, step);
}
#if CLIENT
public override void Draw(SpriteBatch sb)
{
sb.Draw(ItemTextures.Bomb, TopLeft, null, Color.White, 0, new Vector2(0, 0), 0.75f, SpriteEffects.None, 0);
}
#endif
public void ServerPhysicsTick(IServerWorld world, float step) => PhysicsStep(world, step);
public override void Draw(GraphicsEngine gfx) => gfx.Sprite(
texture: gfx.BombSprite,
position: TopLeft,
quad: null,
color: Color.White,
rotation: Rotation.Zero,
origin: Vector2.Zero,
scale: 0.75f,
efx: SpriteEffects.None,
layer: 0
);
}
}

View File

@@ -36,26 +36,30 @@ namespace CaveGame.Core.Game.Entities
{
Vector2 Friction { get; }
}
public interface IClientLogical {
void ClientUpdate(IClientWorld world, GameTime gt);
}
public interface IServerLogical {
void ServerUpdate(IServerWorld world, GameTime gt);
}
public interface IEntity
{
int EntityNetworkID { get; set; }
float DurationAlive { get; }
bool Dead { get; }
float DurationAlive { get; set; }
bool Dead { get; set; }
int Health { get; set; }
int MaxHealth { get; }
//void Update(IGameWorld world, GameTime gt);
void ClientUpdate(IClientWorld world, GameTime gt);
void ServerUpdate(IServerWorld world, GameTime gt);
}
public interface IExpirationTime{
float ExpirationTicks { get; set; }
void ClientUpdate(IGameClient client, GameTime gt);
void ServerUpdate(IGameServer server, GameTime gt);
void Draw(GraphicsEngine engine);
}
public interface IThinker
{
float Anger { get; }
float Fear { get; }
float ResponseTime { get; } // time between Think() ticks
int IQ { get; } // affects properties within Think() such as accuracy of pathfinding
void Think(IGameServer server, GameTime gt);
public class Entity: IEntity, IServerLogical, IClientLogical
}
public class Entity: IEntity
{
public float DurationAlive { get; set; }
public bool Dead { get; set; } // Gets collected on death
@@ -63,13 +67,10 @@ namespace CaveGame.Core.Game.Entities
public int EntityNetworkID { get; set; }
public int Health { get; set; }
public virtual int MaxHealth { get; }
public List<StatusEffect> ActiveEffects { get; private set; }
public void ClearActiveEffects()
{
ActiveEffects.Clear();
}
public void ClearActiveEffects() => ActiveEffects.Clear();
public void AddEffect(StatusEffect effect)
{
@@ -80,11 +81,11 @@ namespace CaveGame.Core.Game.Entities
}
public virtual void ClientUpdate(IClientWorld world, GameTime gt) {
public virtual void ClientUpdate(IGameClient client, GameTime gt) {
DurationAlive += gt.GetDelta();
}
public virtual void ServerUpdate(IServerWorld world, GameTime gt) {
public virtual void ServerUpdate(IGameServer server, GameTime gt) {
DurationAlive += gt.GetDelta();
@@ -95,6 +96,6 @@ namespace CaveGame.Core.Game.Entities
}
ActiveEffects.RemoveAll(e => e.Duration < 0);
}
public virtual void Draw(SpriteBatch sb) { }
}
public virtual void Draw(GraphicsEngine gfx) { }
}
}

View File

@@ -26,13 +26,13 @@ namespace CaveGame.Core.Game.Entities
public void ClientPhysicsTick(IClientWorld world, float step) => PhysicsStep(world, step);
public override void ClientUpdate(IClientWorld world, GameTime gt)
public override void ClientUpdate(IGameClient client, GameTime gt)
{
hover += gt.GetDelta();
base.ClientUpdate(world, gt);
base.ClientUpdate(client, gt);
}
public override void Draw(SpriteBatch sb)
public override void Draw(GraphicsEngine GFX)
{
var drawPos = TopLeft + new Vector2(0, (float)Math.Sin((double)hover * 1.5) * 1.0f);
@@ -42,25 +42,22 @@ namespace CaveGame.Core.Game.Entities
if (ItemStack.Quantity > 10)
{
ItemStack.Item.Draw(sb, drawPos + new Vector2(-2f, -2f), 0.5f);
ItemStack.Item.Draw(GFX, drawPos + new Vector2(-2f, -2f), 0.5f);
}
if (ItemStack.Quantity > 1)
{
ItemStack.Item.Draw(sb, drawPos + new Vector2(-1f, -1f), 0.5f);
ItemStack.Item.Draw(GFX, drawPos + new Vector2(-1f, -1f), 0.5f);
}
ItemStack.Item.Draw(sb, drawPos, 0.5f);
ItemStack.Item.Draw(GFX, drawPos, 0.5f);
if (ItemStack.Quantity > 100)
{
ItemStack.Item.Draw(sb, drawPos + new Vector2(1f, 1f), 0.5f);
ItemStack.Item.Draw(GFX, drawPos + new Vector2(1f, 1f), 0.5f);
}
}
#if CLIENT
sb.Print(Color.White, drawPos - new Vector2(0, 10), ItemStack.Quantity.ToString());
#endif
GFX.Text(ItemStack.Quantity.ToString(), drawPos - new Vector2(0, 10));
}
}
@@ -68,7 +65,7 @@ namespace CaveGame.Core.Game.Entities
// server-relevant code
public partial class ItemstackEntity : PhysicsEntity, IServerPhysicsObserver, IServerLogical
public partial class ItemstackEntity : PhysicsEntity, IServerPhysicsObserver
{
public void ServerPhysicsTick(IServerWorld world, float step)
{
@@ -114,7 +111,7 @@ namespace CaveGame.Core.Game.Entities
base.PhysicsStep(world, step);
}
public override void ServerUpdate(IServerWorld world, GameTime gt)
public override void ServerUpdate(IGameServer server, GameTime gt)
{
if (ItemStack.Quantity <= 0)
@@ -123,7 +120,7 @@ namespace CaveGame.Core.Game.Entities
return;
}
base.ServerUpdate(world, gt);
base.ServerUpdate(server, gt);
}
}
}

View File

@@ -18,7 +18,7 @@ namespace CaveGame.Core.Game.Entities
public abstract class PhysicsEntity : Entity, IPhysicsObject, IPositional, IVelocity, INextPosition, IBoundingBox, IFriction
{
public Vector2 TopLeft
public virtual Vector2 TopLeft
{
get { return Position - BoundingBox; }
}

View File

@@ -17,7 +17,7 @@ using System.Text;
namespace CaveGame.Core.Game.Entities
{
public class Player : PhysicsEntity, IClientLogical, IPhysicsObject, IPositional, IVelocity, INextPosition, IHorizontalDirectionState
public class Player : PhysicsEntity, IPhysicsObject, IPositional, IVelocity, INextPosition, IHorizontalDirectionState
{
public override Vector2 BoundingBox => new Vector2(6, 12);
@@ -54,12 +54,10 @@ namespace CaveGame.Core.Game.Entities
Color = Color.White;
}
public override void ClientUpdate(IClientWorld world, GameTime gt)
public override void ClientUpdate(IGameClient client, GameTime gt)
{
walkingAnimationTimer += (float)gt.ElapsedGameTime.TotalSeconds * 5;
base.ClientUpdate(world, gt);
base.ClientUpdate(client, gt);
}
}
}

View File

@@ -1,10 +1,200 @@
using System;
#if CLIENT
using CaveGame.Client;
#endif
using CaveGame.Core.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Text;
namespace CaveGame.Core.Game.Entities
{
class Wurmhole
// Würmhole
public class Wurmhole : PhysicsEntity, IServerPhysicsObserver, IClientPhysicsObserver, IThinker
{
#region Sprite Quads
public static Rectangle SP_IDLE0 = new Rectangle(0, 0, 16, 16);
public static Rectangle SP_IDLE1 = new Rectangle(0, 16, 16, 16);
public static Rectangle SP_IDLE2 = new Rectangle(0, 32, 16, 16);
public static Rectangle SP_IDLE3 = new Rectangle(0, 48, 16, 16);
public static Rectangle SP_DEATH0 = new Rectangle(16, 0, 16, 16);
public static Rectangle SP_DEATH1 = new Rectangle(16, 16, 16, 16);
public static Rectangle SP_DEATH2 = new Rectangle(16, 32, 16, 16);
public static Rectangle SP_DEATH3 = new Rectangle(16, 48, 16, 16);
public static Rectangle SP_DEATH4 = new Rectangle(16, 64, 16, 16);
public static Rectangle SP_DEATH5 = new Rectangle(16, 80, 16, 16);
public static Rectangle SP_DEATH6 = new Rectangle(16, 80, 16, 16);
// final apoptosis
public static Rectangle SP_DEATH7 = new Rectangle(0, 120, 8, 8);
public static Rectangle SP_DEATH8 = new Rectangle(8, 120, 8, 8);
public static Rectangle SP_DEATH9 = new Rectangle(16,120, 8, 8);
#endregion
public static Rectangle[] IDLE_FRAMES =
{
//SP_IDLE0,
SP_IDLE1,
SP_IDLE2,
SP_IDLE3,
SP_IDLE2,
};
public static Rectangle[] DEATH_FRAMES =
{
SP_DEATH0,
SP_DEATH1,
SP_DEATH1,
SP_DEATH1,
SP_DEATH1,
SP_DEATH2,
SP_DEATH2,
SP_DEATH3,
SP_DEATH4,
SP_DEATH5,
SP_DEATH6,
SP_DEATH7,
SP_DEATH7,
SP_DEATH8,
SP_DEATH9,
SP_DEATH9,
};
public override float Mass => 0.1f;
public override Vector2 BoundingBox => new Vector2(4, 4);
public override Vector2 TopLeft => Position - new Vector2(8, 8);
public override Vector2 Friction => new Vector2(0.25f, 0.25f);
public bool Triggered { get; set; }
public bool TriggerNetworkHandled { get; set; }
public override int MaxHealth => 20;
public float Anger { get; }
public float Fear { get; }
public float ResponseTime { get; }
public int IQ { get; }
float animationTimer;
float triggeredAnimationTimer;
float autonomousMovement;
public Wurmhole()
{
animationTimer = 0;
triggeredAnimationTimer = 0;
Triggered = false;
TriggerNetworkHandled = false;
}
public override void ClientUpdate(IGameClient client, GameTime gt)
{
animationTimer += gt.GetDelta()*5;
if (Triggered)
{
triggeredAnimationTimer += gt.GetDelta()*8;
}
base.ClientUpdate(client, gt);
}
public override void ServerUpdate(IGameServer server, GameTime gt)
{
if (Triggered)
{
triggeredAnimationTimer += gt.GetDelta()*8; // LUL
if (triggeredAnimationTimer > DEATH_FRAMES.Length+2)
{
this.Dead = true;
}
}
base.ServerUpdate(server, gt);
}
public void ClientPhysicsTick(IClientWorld world, float step) => PhysicsStep(world, step);
public void ServerPhysicsTick(IServerWorld world, float step)
{
// vortex
foreach(var entity in world.Entities)
{
if (entity!=this && entity is PhysicsEntity physEntity)
{
var distanceFromSingularityVector = this.Position - physEntity.Position;
var distance = distanceFromSingularityVector.Length();
var directionVector = Vector2.Normalize(distanceFromSingularityVector);
var rotation = Rotation.FromUnitVector(directionVector);
var rotated90 = rotation.RotateDeg(15);
var rotatedUnitVec = rotated90.ToUnitVector();
if (distance < 300)
{
Velocity -= rotatedUnitVec * Math.Min((300.0f - distance) / 500.0f, 0.01f);
}
if (distance < 100)
{
physEntity.Velocity += rotatedUnitVec * ((100.0f - distance)/230.0f);
if (entity is Bomb bomb && distance < 5)
{
Triggered = true;
bomb.Dead = true;
}
if (entity is ItemstackEntity itemstk && distance < 3)
{
itemstk.Dead = true;
}
}
}
}
PhysicsStep(world, step);
}
public override void Draw(GraphicsEngine gfx)
{
Rectangle currentQuad = SP_IDLE0;
if (Triggered)
{
currentQuad = DEATH_FRAMES[Math.Min((int)triggeredAnimationTimer, DEATH_FRAMES.Length-1)];
} else
{
currentQuad = IDLE_FRAMES[(int)(animationTimer % 3)];
}
gfx.Sprite(
texture: gfx.VoidMonster,
position: Position,
quad: currentQuad,
color: Color.White,
rotation: Rotation.Zero,
origin: new Vector2(currentQuad.Width/2, currentQuad.Height / 2),
scale: Vector2.One,
efx: SpriteEffects.None,
layer: 0
);
#if CLIENT
// sb.Print(Color.White, TopLeft-new Vector2(0, 16), "Triggered:"+Triggered.ToString());
#endif
}
public void Think(IGameServer server, GameTime gt)
{
throw new NotImplementedException();
}
}
}

View File

@@ -66,9 +66,9 @@ namespace CaveGame.Core.Furniture
public virtual void OnCollide(){}
public virtual void OnPlayerInteracts(Player player, IGameWorld world, IGameClient client) { }
public virtual void Draw(Texture2D tilesheet, SpriteBatch sb)
public virtual void Draw(GraphicsEngine gfx)
{
sb.Draw(tilesheet, Position.ToVector2()*Globals.TileSize, Quad, Color);
gfx.Sprite(gfx.TileSheet, Position.ToVector2()*Globals.TileSize, Quad, Color);
}
public virtual void OnTileUpdate(IGameWorld world, int x, int y) { }
}
@@ -287,16 +287,16 @@ namespace CaveGame.Core.Furniture
State = DoorState.Closed;
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb)
public override void Draw(GraphicsEngine GFX)
{
var pos = Position.ToVector2() * Globals.TileSize;
if (State == DoorState.Closed)
sb.Draw(tilesheet, pos, ClosedDoorQuad, Color, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
GFX.Sprite(GFX.TileSheet, pos, ClosedDoorQuad, Color, Rotation.Zero, Vector2.Zero, 1, SpriteEffects.None, 0);
if (State == DoorState.OpenLeft)
sb.Draw(tilesheet, pos-new Vector2(8, 0), OpenDoorQuad, Color, 0, Vector2.Zero, 1, SpriteEffects.FlipHorizontally, 0);
GFX.Sprite(GFX.TileSheet, pos-new Vector2(8, 0), OpenDoorQuad, Color, Rotation.Zero, Vector2.Zero, 1, SpriteEffects.FlipHorizontally, 0);
if (State == DoorState.OpenRight)
sb.Draw(tilesheet, pos, OpenDoorQuad, Color, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
GFX.Sprite(GFX.TileSheet, pos, OpenDoorQuad, Color, Rotation.Zero, Vector2.Zero, 1, SpriteEffects.None, 0);
}
public static bool CanPlace(IGameWorld world, int x, int y)

View File

@@ -16,20 +16,18 @@ namespace CaveGame.Core.Inventory
public abstract class FurnitureItem : Item
{
public override int MaxStack => 99;
public virtual Texture2D ItemTexture { get; }
public override void Draw(SpriteBatch sb, Vector2 position, float scale)
public void Draw(GraphicsEngine GFX, Texture2D ItemTexture, Vector2 position, float scale)
{
sb.Draw(ItemTexture, position, null, Color.White, 0, Vector2.Zero, scale * 2, SpriteEffects.None, 0);
GFX.Sprite(ItemTexture, position, null, Color.White, Rotation.Zero, Vector2.Zero, scale * 2, SpriteEffects.None, 0);
}
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale) { }
}
public class FurnaceItem : FurnitureItem
{
#if CLIENT
public override Texture2D ItemTexture => ItemTextures.Furnace;
#endif
public override void OnClientLMBHeld(Player player, IGameClient client, ItemStack stack, GameTime gt)
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale) => Draw(GFX, GFX.Furnace, position, scale);
public override void OnClientLMBHeld(Player player, IGameClient client, ItemStack stack, GameTime gt)
{
MouseState mouse = Mouse.GetState();
@@ -52,9 +50,7 @@ namespace CaveGame.Core.Inventory
public class DoorItem : FurnitureItem
{
#if CLIENT
public override Texture2D ItemTexture => ItemTextures.Door;
#endif
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale) => Draw(GFX, GFX.Furnace, position, scale);
public override void OnClientLMBHeld(Player player, IGameClient client, ItemStack stack, GameTime gt)
{
MouseState mouse = Mouse.GetState();
@@ -77,19 +73,15 @@ namespace CaveGame.Core.Inventory
public class WorkbenchItem : FurnitureItem
{
#if CLIENT
public override Texture2D ItemTexture => ItemTextures.Workbench;
#endif
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale) => Draw(GFX, GFX.Workbench, position, scale);
public override void OnClientLMBHeld(Player player, IGameClient client, ItemStack stack, GameTime gt)
{
MouseState mouse = Mouse.GetState();
var mp = client.Camera.ScreenToWorldCoordinates(mouse.Position.ToVector2());
Point pos = new Point(
(int)Math.Floor(mp.X / Globals.TileSize),
(int)Math.Floor(mp.Y / Globals.TileSize)
);
if (Furniture.Workbench.CanPlace(client.World, pos.X, pos.Y))
{
stack.Quantity--;

View File

@@ -37,12 +37,10 @@ namespace CaveGame.Core.Inventory
int MaxStack { get; }
string Name { get; }
#if CLIENT
void Draw(SpriteBatch sb, Vector2 position, float scale);
void Draw(GraphicsEngine GFX, Vector2 position, float scale);
#endif
}
public class Item : IItem
{
public virtual List<ItemTag> Tags => new List<ItemTag>();
@@ -59,7 +57,12 @@ namespace CaveGame.Core.Inventory
public virtual int MaxStack => 99;
public virtual string Name => this.GetType().Name;
public virtual void Draw(SpriteBatch sb, Vector2 position, float scale) { }
public virtual string DisplayName => Name;
public void Draw(GraphicsEngine GFX, Texture2D texture, Vector2 position, float scale)
{
GFX.Sprite(texture, position, null, Color.Gray, Rotation.Zero, Vector2.Zero, scale, SpriteEffects.None, 0);
} // pseudo- default draw
public virtual void Draw(GraphicsEngine GFX, Vector2 position, float scale) {}
public virtual void OnClientLMBDown(Player player, IGameClient client, ItemStack stack) { }
public virtual void OnClientLMBUp(Player player, IGameClient client) {}
public virtual void OnClientLMBHeld(Player player, IGameClient client, ItemStack stack, GameTime gt) { }
@@ -82,6 +85,17 @@ namespace CaveGame.Core.Inventory
public static Item FromName(string name)
{
if (name.StartsWith("TileItem"))
{
var tilename = name.Substring(9);
return new TileItem(Tile.FromName(tilename));
}
if (name.StartsWith("WallItem"))
{
var wallname = name.Substring(9);
return new WallItem(Wall.FromName(wallname));
}
var basetype = typeof(Item);
var types = basetype.Assembly.GetTypes().Where(type => type.IsSubclassOf(basetype));
@@ -109,17 +123,13 @@ namespace CaveGame.Core.Inventory
}
public interface IGameClient
{
Camera2D Camera { get; }
void Send(Packet p);
IGameWorld World { get; }
}
public class GenericPickaxe : Item
{
public virtual float SwingTime => 0.15f;
public virtual byte Strength => 2;
public virtual Color Tint => Color.Gray;
public virtual float Size => 1.0f;
public float swingingTimer;
@@ -154,15 +164,41 @@ namespace CaveGame.Core.Inventory
}
}
}
public override void Draw(SpriteBatch sb, Vector2 position, float scale)
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale)
{
#if CLIENT
sb.Draw(ItemTextures.PickaxeNew, position, null, Color.Gray, 0, Vector2.Zero, scale, SpriteEffects.None, 0);
#endif
GFX.Sprite(GFX.PickaxeNew, position+new Vector2(8*scale, 8*scale), null, Tint, Rotation.Zero, new Vector2(8, 8), scale* Size, SpriteEffects.None, 0);
}
}
public class CopperPickaxe : GenericPickaxe
{
public override string DisplayName => "Copper Pickaxe";
public override Color Tint => new Color(1.0f, 0.7f, 0.2f);
public override float SwingTime => 0.2f;
public override byte Strength => 2;
public override float Size => 0.8f;
}
public class LeadPickaxe : GenericPickaxe
{
public override string DisplayName => "Lead Pickaxe";
public override Color Tint => new Color(0.3f, 0.3f, 0.4f);
public override float SwingTime => 0.4f;
public override byte Strength => 12;
public override float Size => 1.25f;
}
public class IronPickaxe : GenericPickaxe
{
public override string DisplayName => "Iron Pickaxe";
public override Color Tint => new Color(0.75f, 0.5f, 0.4f);
public override float SwingTime => 0.3f;
public override byte Strength => 6;
}
// TODO: Make walls break
public class GenericWallScraper : Item
{
public override void OnClientLMBHeld(Player player, IGameClient client, ItemStack stack, GameTime gt)
@@ -183,21 +219,15 @@ namespace CaveGame.Core.Inventory
client.World.SetWall(x, y, new Game.Walls.Air());
}
}
public override void Draw(SpriteBatch sb, Vector2 position, float scale)
{
#if CLIENT
sb.Draw(ItemTextures.WallScraper, position, null, Color.Red, 0, Vector2.Zero, scale, SpriteEffects.None, 0);
#endif
}
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale) => Draw(GFX, GFX.WallScraper, position, scale);
}
public class WallItem : Item
{
public override int MaxStack => 999;
public string DisplayName => Wall.WallName;
public override string DisplayName => Wall.WallName + " Wall";
public override string Name => "WallItem:" + Wall.WallName;
public Wall Wall;
@@ -235,13 +265,9 @@ namespace CaveGame.Core.Inventory
return fatass;
}
public override void Draw(SpriteBatch sb, Vector2 position, float scale)
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale)
{
Texture2D tex = null;
#if CLIENT
tex = GameTextures.TileSheet;
#endif
sb.Draw(tex, position, Wall.Quad, Wall.Color, 0, Vector2.Zero, scale * 2, SpriteEffects.None, 0);
GFX.Sprite(GFX.TileSheet, position + (new Vector2(1.5f, 1.5f) * scale * 1.5f), Wall.Quad, Wall.Color, Rotation.Zero, Vector2.Zero, scale * 1.5f, SpriteEffects.None, 0);
}
}
@@ -249,8 +275,10 @@ namespace CaveGame.Core.Inventory
public class TileItem : Item
{
public override int MaxStack => 999;
public string DisplayName => Tile.TileName;
public override string DisplayName => Tile.TileName + " Block";
public override string Name => "TileItem:" + Tile.TileName;
public Tile Tile;
@@ -292,13 +320,9 @@ namespace CaveGame.Core.Inventory
return fatass;
}
public override void Draw(SpriteBatch sb, Vector2 position, float scale)
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale)
{
Texture2D tex = null;
#if CLIENT
tex = GameTextures.TileSheet;
#endif
sb.Draw(tex, position+(new Vector2(1.5f, 1.5f)*scale*1.5f), Tile.Quad, Tile.Color, 0, Vector2.Zero, scale*1.5f, SpriteEffects.None, 0);
GFX.Sprite(GFX.TileSheet, position+(new Vector2(1.5f, 1.5f)*scale*1.5f), Tile.Quad, Tile.Color, Rotation.Zero, Vector2.Zero, scale*1.5f, SpriteEffects.None, 0);
}
}
@@ -324,12 +348,7 @@ namespace CaveGame.Core.Inventory
#if CLIENT
public override void Draw(SpriteBatch sb, Vector2 position, float scale)
{
sb.Draw(ItemTextures.Bomb, position, null, Color.White, 0, Vector2.Zero, scale, SpriteEffects.None, 0);
}
#endif
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale) => Draw(GFX, GFX.BombSprite, position, scale);
}
@@ -341,12 +360,10 @@ namespace CaveGame.Core.Inventory
public virtual Color Color { get; }
#if CLIENT
public override void Draw(SpriteBatch sb, Vector2 position, float scale)
public override void Draw(GraphicsEngine GFX, Vector2 position, float scale)
{
sb.Draw(ItemTextures.Ingot, position, null, Color, 0, Vector2.Zero, scale, SpriteEffects.None, 0);
GFX.Sprite(GFX.Ingot, position, null, Color, Rotation.Zero, Vector2.Zero, scale, SpriteEffects.None, 0);
}
#endif
}
public class CopperIngot: Ingot {
@@ -406,17 +423,13 @@ namespace CaveGame.Core.Inventory
public class TopHat { }
public class ArmyHelmet { }
public class NordicHelm { }
public class PhilosopherStone { }
public class PoisonVial { }
public class ShoeSpikes { }
public class Jetpack { }
public class ExoskelHead { }
public class ExoskelTorso { }
public class ExoskelLegs { }
public class GrassSeeds { }
public class Bucket { }
public class WaterBucket { }

View File

@@ -33,7 +33,7 @@ namespace CaveGame.Core.Game.Tiles
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
SpriteEffects effects = SpriteEffects.None;
Vector2 position = new Vector2((Globals.TileSize * x) + (x % 3) - (y % 6), (Globals.TileSize * y));
@@ -42,7 +42,7 @@ namespace CaveGame.Core.Game.Tiles
{
effects = SpriteEffects.FlipHorizontally;
}
sb.Draw(tilesheet, position, TileMap.CryingLily, color.MultiplyAgainst(Color), 0, Vector2.Zero, Vector2.One, effects, 0);
GFX.Sprite(GFX.TileSheet, position, TileMap.CryingLily, color.MultiplyAgainst(Color), Rotation.Zero, Vector2.Zero, Vector2.One, effects, 0);
//base.Draw(tilesheet, sb, x, y, color);
}
}

View File

@@ -24,33 +24,33 @@ namespace CaveGame.Core.Game.Tiles
public static Rectangle Patch = new Rectangle(8 * Globals.TileSize, 6 * Globals.TileSize, Globals.TileSize, Globals.TileSize);
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
#if EDITOR
sb.Draw(tilesheet, new Vector2(x * Globals.TileSize, y * Globals.TileSize), Quad, Color);
GFX.Sprite(GFX.TileSheet, new Vector2(x * Globals.TileSize, y * Globals.TileSize), Quad, Color);
return;
#endif
sb.Draw(tilesheet, new Vector2(x * Globals.TileSize, y * Globals.TileSize), TileMap.Soil, color.MultiplyAgainst(Color.SaddleBrown));
GFX.Sprite(GFX.TileSheet, new Vector2(x * Globals.TileSize, y * Globals.TileSize), TileMap.Soil, color.MultiplyAgainst(Color.SaddleBrown));
var corner = new Rectangle(9 * Globals.TileSize, 6 * Globals.TileSize, Globals.TileSize, Globals.TileSize);
Vector2 position = new Vector2(x * Globals.TileSize, y * Globals.TileSize) + new Vector2(4, 4);
if (TileState.Get(0)) // cornerd
sb.Draw(tilesheet, position, corner, color.MultiplyAgainst(Color), MathHelper.ToRadians(270), new Vector2(4, 4), 1, SpriteEffects.None, 1);
GFX.Sprite(GFX.TileSheet, position, corner, color.MultiplyAgainst(Color), Rotation.FromDeg(270), new Vector2(4, 4), 1, SpriteEffects.None, 1);
if (TileState.Get(1)) // cornerc
sb.Draw(tilesheet, position, corner, color.MultiplyAgainst(Color), MathHelper.ToRadians(180), new Vector2(4, 4), 1, SpriteEffects.None, 1);
GFX.Sprite(GFX.TileSheet, position, corner, color.MultiplyAgainst(Color), Rotation.FromDeg(180), new Vector2(4, 4), 1, SpriteEffects.None, 1);
if (TileState.Get(2)) // cornerb
sb.Draw(tilesheet, position, corner, color.MultiplyAgainst(Color), MathHelper.ToRadians(90), new Vector2(4, 4), 1, SpriteEffects.None, 1);
GFX.Sprite(GFX.TileSheet, position, corner, color.MultiplyAgainst(Color), Rotation.FromDeg(90), new Vector2(4, 4), 1, SpriteEffects.None, 1);
if (TileState.Get(3)) // cornera
sb.Draw(tilesheet, position, corner, color.MultiplyAgainst(Color), 0, new Vector2(4, 4), 1, SpriteEffects.None, 1);
GFX.Sprite(GFX.TileSheet, position, corner, color.MultiplyAgainst(Color), Rotation.Zero, new Vector2(4, 4), 1, SpriteEffects.None, 1);
if (TileState.Get(4)) // planeright
sb.Draw(tilesheet, position, Patch, color.MultiplyAgainst(Color), MathHelper.ToRadians(90), new Vector2(4, 4), 1, SpriteEffects.None, 1);
GFX.Sprite(GFX.TileSheet, position, Patch, color.MultiplyAgainst(Color), Rotation.FromDeg(90), new Vector2(4, 4), 1, SpriteEffects.None, 1);
if (TileState.Get(5)) // planebottom
sb.Draw(tilesheet, position, Patch, color.MultiplyAgainst(Color), MathHelper.ToRadians(0), new Vector2(4, 4), 1, SpriteEffects.FlipVertically, 1);
GFX.Sprite(GFX.TileSheet, position, Patch, color.MultiplyAgainst(Color), Rotation.FromDeg(0), new Vector2(4, 4), 1, SpriteEffects.FlipVertically, 1);
if (TileState.Get(6)) // planeleft
sb.Draw(tilesheet, position, Patch, color.MultiplyAgainst(Color), MathHelper.ToRadians(270), new Vector2(4, 4), 1, SpriteEffects.None, 1);
GFX.Sprite(GFX.TileSheet, position, Patch, color.MultiplyAgainst(Color), Rotation.FromDeg(270), new Vector2(4, 4), 1, SpriteEffects.None, 1);
if (TileState.Get(7)) // planetop
sb.Draw(tilesheet, position, Patch, color.MultiplyAgainst(Color), MathHelper.ToRadians(0), new Vector2(4, 4), 1, SpriteEffects.None, 1);
GFX.Sprite(GFX.TileSheet, position, Patch, color.MultiplyAgainst(Color), Rotation.FromDeg(0), new Vector2(4, 4), 1, SpriteEffects.None, 1);
}

View File

@@ -162,10 +162,10 @@ namespace CaveGame.Core.Game.Tiles
public override Color Color => Color.Red;
public override void Drop(IGameServer server, IGameWorld world, Point tilePosition) { }
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 light)
public override void Draw(GraphicsEngine gfx, int x, int y, Light3 light)
{
var rect = new Rectangle(0, 15 * Globals.TileSize, Globals.TileSize, TileState);
sb.Draw(tilesheet, new Vector2(x * Globals.TileSize, (y * Globals.TileSize) + (8 - TileState)), rect, light.MultiplyAgainst(Color.Red));
gfx.Sprite(gfx.TileSheet, new Vector2(x * Globals.TileSize, (y * Globals.TileSize) + (8 - TileState)), rect, light.MultiplyAgainst(Color));
}
public override float Viscosity => 1.06f;
@@ -220,13 +220,13 @@ namespace CaveGame.Core.Game.Tiles
public override float Viscosity => 1.04f;
public Water() { TileState = 8; }
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 light)
public override void Draw(GraphicsEngine gfx, int x, int y, Light3 light)
{
float brug = Math.Max(0.5f, (1 - (light.Blue / 16.0f)) * 2.0f);
var rect = new Rectangle(0, 15 * Globals.TileSize, Globals.TileSize, TileState);
sb.Draw(tilesheet, new Vector2(x * Globals.TileSize, (y * Globals.TileSize) + (8 - TileState)), rect, light.MultiplyAgainst(Color.Blue) * brug);
gfx.Sprite(gfx.TileSheet, new Vector2(x * Globals.TileSize, (y * Globals.TileSize) + (8 - TileState)), rect, light.MultiplyAgainst(Color.Blue) * brug);
}
public void TileUpdate(IGameWorld world, int x, int y)
@@ -246,11 +246,11 @@ namespace CaveGame.Core.Game.Tiles
public Sludge() { TileState = 8; }
public Light3 Light => new Light3(14, 32, 8);
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 light)
public override void Draw(GraphicsEngine gfx, int x, int y, Light3 light)
{
var rect = new Rectangle(0, 15 * Globals.TileSize, Globals.TileSize, TileState);
sb.Draw(tilesheet, new Vector2(x * Globals.TileSize, (y * Globals.TileSize) + (8 - TileState)), rect, light.MultiplyAgainst(new Color(0.6f, 0.9f, 0.3f)));
gfx.Sprite(gfx.TileSheet, new Vector2(x * Globals.TileSize, (y * Globals.TileSize) + (8 - TileState)), rect, light.MultiplyAgainst(new Color(0.6f, 0.9f, 0.3f)));
}
public void LocalTileUpdate(IGameWorld world, int x, int y)

View File

@@ -1,5 +1,6 @@
#if CLIENT
using CaveGame.Client;
using CaveGame.Core.Generic;
#endif
using DataManagement;
using Microsoft.Xna.Framework;
@@ -15,60 +16,48 @@ namespace CaveGame.Core.Game.Tiles
{
public override byte Hardness => 12;
public override Rectangle Quad => TileMap.Ore;
#if CLIENT
private void DrawMask(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color, int rotation, Rectangle quad, Color tilecolor)
private void DrawMask(GraphicsEngine gfx, int x, int y, Light3 color, int rotation, Rectangle quad, Color tilecolor)
{
if (GameGlobals.GraphicsDevice != null)
{
var position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
var pixels4 = new Vector2(4, 4);
sb.Draw(tilesheet, position + pixels4, quad, color.MultiplyAgainst(tilecolor), MathHelper.ToRadians(rotation), new Vector2(4, 4), 1, SpriteEffects.None, 1);
}
var position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
var pixels4 = new Vector2(4, 4);
gfx.Sprite(gfx.TileSheet, position + pixels4, quad, color.MultiplyAgainst(tilecolor), Rotation.FromDeg(rotation), new Vector2(4, 4), 1, SpriteEffects.None, 1);
}
private void DrawDirtMask(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color, int rotation)
{
DrawMask(tilesheet, sb, x, y, color, rotation, TileMap.DirtFading, Color.SaddleBrown);
}
private void DrawDirtMask(GraphicsEngine gfx, int x, int y, Light3 color, int rotation) => DrawMask(gfx, x, y, color, rotation, TileMap.DirtFading, Color.SaddleBrown);
private void DrawStoneMask(GraphicsEngine gfx, int x, int y, Light3 color, int rot) => DrawMask(gfx, x, y, color, rot, TileMap.StoneFading, new Color(0.7f, 0.7f, 0.7f));
private void DrawStoneMask(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color, int rotation)
{
DrawMask(tilesheet, sb, x, y, color, rotation, TileMap.StoneFading, new Color(0.7f, 0.7f, 0.7f));
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine gfx, int x, int y, Light3 color)
{
var position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
sb.Draw(tilesheet, position, Quad, color.MultiplyAgainst(Color));
gfx.Sprite(gfx.TileSheet, position, Quad, color.MultiplyAgainst(Color));
//sb.End();
if (TileState.Get(0)) // Top Dirt
DrawDirtMask(tilesheet, sb, x, y, color, 0);
DrawDirtMask(gfx, x, y, color, 0);
if (TileState.Get(1)) // Top Stone
DrawStoneMask(tilesheet, sb, x, y, color, 0);
DrawStoneMask(gfx, x, y, color, 0);
if (TileState.Get(2)) // Bottom Dirt
DrawDirtMask(tilesheet, sb, x, y, color, 180);
DrawDirtMask(gfx, x, y, color, 180);
if (TileState.Get(3)) // Bottom Stone
DrawStoneMask(tilesheet, sb, x, y, color, 180);
DrawStoneMask(gfx, x, y, color, 180);
if (TileState.Get(4)) // Left Dirt
DrawDirtMask(tilesheet, sb, x, y, color, 270);
DrawDirtMask(gfx, x, y, color, 270);
if (TileState.Get(5)) // Left Stone
DrawStoneMask(tilesheet, sb, x, y, color, 270);
DrawStoneMask(gfx, x, y, color, 270);
if (TileState.Get(6)) // Right Dirt
DrawDirtMask(tilesheet, sb, x, y, color, 90);
DrawDirtMask(gfx, x, y, color, 90);
if (TileState.Get(7)) // Right Stone
DrawStoneMask(tilesheet, sb, x, y, color, 90);
DrawStoneMask(gfx, x, y, color, 90);
//sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
}
#endif
public void LocalTileUpdate(IGameWorld world, int x, int y)
{
var top = world.GetTile(x, y - 1);

View File

@@ -1,5 +1,7 @@
using CaveGame.Core.Game.Tiles;
using CaveGame.Core.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Text;
@@ -22,8 +24,8 @@ namespace CaveGame.Core.Game.Tiles
}
public class Sand : Tile, ITileUpdate
{
public override Rectangle Quad => TileMap.Soil;
public override Color Color => new Color(0.9f, 0.8f, 0.4f);
public override Rectangle Quad => TileMap.Sand;
public override Color Color => new Color(0.9f, 0.9f, 0.5f);
public void TileUpdate(IGameWorld world, int x, int y)
{
@@ -40,6 +42,37 @@ namespace CaveGame.Core.Game.Tiles
world.SetTile(x, y + 1, new Sand());
}
}
public override void Draw(GraphicsEngine gfx, int x, int y, Light3 color)
{
var rngval = RNGIntMap[x, y];
if (rngval % 2 == 0)
{
gfx.Sprite(
gfx.TileSheet,
new Vector2(x * Globals.TileSize, y * Globals.TileSize),
Quad, color.MultiplyAgainst(Color), Rotation.Zero,
Vector2.Zero, 1, SpriteEffects.None, 0
);
} else if (rngval % 2 == 1)
{
gfx.Sprite(
gfx.TileSheet,
new Vector2(x * Globals.TileSize, y * Globals.TileSize),
Quad, color.MultiplyAgainst(Color), Rotation.Zero,
Vector2.Zero, 1, SpriteEffects.FlipVertically, 0
);
} else
{
gfx.Sprite(
gfx.TileSheet,
new Vector2(x * Globals.TileSize, y * Globals.TileSize),
Quad, color.MultiplyAgainst(Color), Rotation.Zero,
Vector2.Zero, 1, SpriteEffects.FlipHorizontally, 0
);
}
}
}
public class Snow : Tile
{

View File

@@ -13,41 +13,37 @@ namespace CaveGame.Core.Game.Tiles
public override Rectangle Quad => TileMap.Stone;
public override byte Hardness => 4;
private void DrawMask(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color, int rotation, Rectangle quad, Color tilecolor)
private void DrawMask(GraphicsEngine GFX, int x, int y, Light3 color, int rotation, Rectangle quad, Color tilecolor)
{
//if (GameGlobals.GraphicsDevice != null)
//{
var position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
var pixels4 = new Vector2(4, 4);
sb.Draw(tilesheet, position + pixels4, quad, color.MultiplyAgainst(tilecolor), MathHelper.ToRadians(rotation), new Vector2(4, 4), 1, SpriteEffects.None, 1);
GFX.Sprite(GFX.TileSheet, position + pixels4, quad, color.MultiplyAgainst(tilecolor), Rotation.FromDeg(rotation), new Vector2(4, 4), 1, SpriteEffects.None, 1);
// }
}
private void DrawDirtMask(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color, int rotation)
private void DrawDirtMask(GraphicsEngine GFX, int x, int y, Light3 color, int rotation)
{
DrawMask(tilesheet, sb, x, y, color, rotation, TileMap.DirtFading, Color.SaddleBrown);
DrawMask(GFX, x, y, color, rotation, TileMap.DirtFading, Color.SaddleBrown);
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
var position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
sb.Draw(tilesheet, position, Quad, color.MultiplyAgainst(Color));
//sb.End();
GFX.Sprite(GFX.TileSheet, position, Quad, color.MultiplyAgainst(Color));
if (TileState.Get(0)) // Top Dirt
DrawDirtMask(tilesheet, sb, x, y, color, 0);
DrawDirtMask(GFX, x, y, color, 0);
if (TileState.Get(1)) // Bottom Dirt
DrawDirtMask(tilesheet, sb, x, y, color, 180);
DrawDirtMask(GFX, x, y, color, 180);
if (TileState.Get(2)) // Left Dirt
DrawDirtMask(tilesheet, sb, x, y, color, 270);
DrawDirtMask(GFX, x, y, color, 270);
if (TileState.Get(3)) // Right Dirt
DrawDirtMask(tilesheet, sb, x, y, color, 90);
//sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
DrawDirtMask(GFX, x, y, color, 90);
}
@@ -111,7 +107,7 @@ namespace CaveGame.Core.Game.Tiles
}
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
var gx = TileMap.Glass.X;
var gy = TileMap.Glass.Y;
@@ -123,19 +119,19 @@ namespace CaveGame.Core.Game.Tiles
Vector2 position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
sb.Draw(tilesheet, position, TileMap.GlassBG, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, TileMap.GlassBG, color.MultiplyAgainst(Color));
if (TileState.Get(3)) // Right
sb.Draw(tilesheet, position + new Vector2(7, 0), right, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(7, 0), right, color.MultiplyAgainst(Color));
if (TileState.Get(2)) // Bottom
sb.Draw(tilesheet, position + new Vector2(0, 7), bottom, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(0, 7), bottom, color.MultiplyAgainst(Color));
if (TileState.Get(1)) // Left
sb.Draw(tilesheet, position, left, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, left, color.MultiplyAgainst(Color));
if (TileState.Get(0)) // Top
sb.Draw(tilesheet, position, top, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, top, color.MultiplyAgainst(Color));
}
//sb.Draw(tilesheet, new Vector2(x * Globals.TileSize, y * Globals.TileSize), TileMap.Soil, color.MultiplyAgainst(Color.SaddleBrown));
@@ -145,7 +141,7 @@ namespace CaveGame.Core.Game.Tiles
{
public override Rectangle Quad => TileMap.Brick;
public override byte Hardness => 12;
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
//sb.Draw(tilesheet, new Vector2(x * Globals.TileSize, y * Globals.TileSize), TileMap.Soil, color.MultiplyAgainst(Color.SaddleBrown));
var TL = new Rectangle(0, Globals.TileSize, 4, 4);
@@ -162,24 +158,24 @@ namespace CaveGame.Core.Game.Tiles
if (TileState.Get(3)) // BottomRight
sb.Draw(tilesheet, position + new Vector2(4, 4), RBR, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(4, 4), RBR, color.MultiplyAgainst(Color));
else
sb.Draw(tilesheet, position + new Vector2(4, 4), BR, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(4, 4), BR, color.MultiplyAgainst(Color));
if (TileState.Get(2)) // BottomLeft
sb.Draw(tilesheet, position + new Vector2(0, 4), RBL, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(0, 4), RBL, color.MultiplyAgainst(Color));
else
sb.Draw(tilesheet, position + new Vector2(0, 4), BL, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(0, 4), BL, color.MultiplyAgainst(Color));
if (TileState.Get(1)) // TopLeft
sb.Draw(tilesheet, position, RTL, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, RTL, color.MultiplyAgainst(Color));
else
sb.Draw(tilesheet, position, TL, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, TL, color.MultiplyAgainst(Color));
if (TileState.Get(0)) // TopRight
sb.Draw(tilesheet, position + new Vector2(4, 0), RTR, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(4, 0), RTR, color.MultiplyAgainst(Color));
else
sb.Draw(tilesheet, position + new Vector2(4, 0), TR, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(4, 0), TR, color.MultiplyAgainst(Color));
}
@@ -213,7 +209,7 @@ namespace CaveGame.Core.Game.Tiles
{
public override Rectangle Quad => TileMap.RedBrick;
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
//sb.Draw(tilesheet, new Vector2(x * Globals.TileSize, y * Globals.TileSize), TileMap.Soil, color.MultiplyAgainst(Color.SaddleBrown));
var TL = new Rectangle(0, (Globals.TileSize * 3), 4, 4);
@@ -230,24 +226,24 @@ namespace CaveGame.Core.Game.Tiles
if (TileState.Get(3)) // BottomRight
sb.Draw(tilesheet, position + new Vector2(4, 4), RBR, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(4, 4), RBR, color.MultiplyAgainst(Color));
else
sb.Draw(tilesheet, position + new Vector2(4, 4), BR, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(4, 4), BR, color.MultiplyAgainst(Color));
if (TileState.Get(2)) // BottomLeft
sb.Draw(tilesheet, position + new Vector2(0, 4), RBL, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(0, 4), RBL, color.MultiplyAgainst(Color));
else
sb.Draw(tilesheet, position + new Vector2(0, 4), BL, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(0, 4), BL, color.MultiplyAgainst(Color));
if (TileState.Get(1)) // TopLeft
sb.Draw(tilesheet, position, RTL, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, RTL, color.MultiplyAgainst(Color));
else
sb.Draw(tilesheet, position, TL, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, TL, color.MultiplyAgainst(Color));
if (TileState.Get(0)) // TopRight
sb.Draw(tilesheet, position + new Vector2(4, 0), RTR, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(4, 0), RTR, color.MultiplyAgainst(Color));
else
sb.Draw(tilesheet, position + new Vector2(4, 0), TR, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position + new Vector2(4, 0), TR, color.MultiplyAgainst(Color));
}

View File

@@ -1,9 +1,8 @@
#if CLIENT
using CaveGame.Client;
#endif
using CaveGame.Core.Game.Entities;
using CaveGame.Core.Game.Entities;
using CaveGame.Core.Generic;
using CaveGame.Core.Inventory;
using CaveGame.Core.Network;
using CaveGame.Core.Noise;
using DataManagement;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
@@ -29,7 +28,42 @@ namespace CaveGame.Core.Game.Tiles
public abstract class Tile : IEquatable<Tile>
{
[Conditional("DEBUG")]
const int grid_width = 64;
const int grid_height = 64;
const float n_scale = 0.5f;
const float n_mult = 40;
private static float[,] PrecomputeFloatMap()
{
var map = new float[grid_width, grid_height];
SimplexNoise noise = new SimplexNoise();
for (int x = 0; x < grid_width; x++)
for (int y = 0; y < grid_height; y++)
map[x, y] = noise.Noise(x/n_scale, y/n_scale)* n_mult;
return map;
}
private static int[,] PrecomputeIntMap()
{
var map = new int[grid_width, grid_height];
SimplexNoise noise = new SimplexNoise();
for (int x = 0; x < grid_width; x++)
for (int y = 0; y < grid_height; y++)
map[x, y] = (int) ( noise.Noise(x / n_scale, y / n_scale)* n_mult);
return map;
}
public static float[,] RNGFloatMap = PrecomputeFloatMap();
public static int[,] RNGIntMap = PrecomputeIntMap();
public static void InitializeManager(int rngseed)
{
}
public static void AssertTileEnumeration() { }
// Tile Properties
@@ -56,13 +90,17 @@ namespace CaveGame.Core.Game.Tiles
// Default Methods
public virtual void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public virtual void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
sb.Draw(
tilesheet,
new Vector2(x * Globals.TileSize, y * Globals.TileSize),
Quad, color.MultiplyAgainst(Color), 0,
Vector2.Zero, 1, SpriteEffects.None, 0
GFX.Sprite(
texture: GFX.TileSheet,
position: new Vector2(x * Globals.TileSize, y * Globals.TileSize),
quad: Quad, color.MultiplyAgainst(Color),
rotation: Rotation.Zero,
origin: Vector2.Zero,
scale: 1,
efx: SpriteEffects.None,
layer: 0
);
}
@@ -141,11 +179,7 @@ namespace CaveGame.Core.Game.Tiles
// static shit
#if CLIENT
public static Texture2D Tilesheet = GameTextures.TileSheet;
#else
public static Texture2D Tilesheet;
#endif
public static Random RNG = new Random();
public static short IDOf<T>()

View File

@@ -68,7 +68,7 @@ namespace CaveGame.Core.Game.Tiles
public static Rectangle Reeds = Quad(9, 4);
public static Rectangle ReedsTop = Quad(8, 4);
public static Rectangle BMPY_WoodGrain = Quad(0, 4);
public static Rectangle Sand = Quad(0, 4);
public static Rectangle BMPY_Stone = Quad(3, 3);
public static Rectangle BMPY_DarkStone = Quad(1, 4);
public static Rectangle RedBrick = Quad(0, 3);

View File

@@ -12,19 +12,19 @@ namespace CaveGame.Core.Game.Tiles
{
public class FurniturePointer : Tile
{
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 light) { } // leave empty
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 light) { } // leave empty
}
public class Void : Tile
{
public override void Drop(IGameServer server, IGameWorld world, Point tilePosition) { }
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 light) { } // leave empty
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 light) { } // leave empty
}
public class Air : Tile, INonSolid, IWaterBreakable
{
public override void Drop(IGameServer server, IGameWorld world, Point tilePosition) { }
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 light) { } // leave empty
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 light) { } // leave empty
}
public class Vacuum { }
public class Fog { }

View File

@@ -26,16 +26,16 @@ namespace CaveGame.Core.Game.Tiles
new Rectangle(Globals.TileSize*14, Globals.TileSize*5, Globals.TileSize, Globals.TileSize),
};
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
Vector2 position = new Vector2(Globals.TileSize * x, Globals.TileSize * y);
sb.Draw(tilesheet, position, TileMap.Torch, color.MultiplyAgainst(Color.White));
GFX.Sprite(GFX.TileSheet, position, TileMap.Torch, color.MultiplyAgainst(Color.White));
#if CLIENT
sb.Rect(FlameColor * 0.5f, position + new Vector2(2, -1), new Vector2(4, 4));
sb.Rect(FlameColor * 1.2f, position + new Vector2(3, 0), new Vector2(2, 2));
GFX.Rect(FlameColor * 0.5f, position + new Vector2(2, -1), new Vector2(4, 4));
GFX.Rect(FlameColor * 1.2f, position + new Vector2(3, 0), new Vector2(2, 2));
#endif
}

View File

@@ -21,17 +21,17 @@ namespace CaveGame.Core.Game.Tiles
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
Vector2 position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
if (TileState == 0) // Upright
sb.Draw(tilesheet, position, Quad, color.MultiplyAgainst(Color), 0, Vector2.Zero, Vector2.One, SpriteEffects.None, 0);
GFX.Sprite(GFX.TileSheet, position, Quad, color.MultiplyAgainst(Color), Rotation.Zero, Vector2.Zero, Vector2.One, SpriteEffects.None, 0);
if (TileState == 1) // Right
sb.Draw(tilesheet, position, Quad, color.MultiplyAgainst(Color), MathHelper.ToRadians(90), Vector2.Zero, Vector2.One, SpriteEffects.None, 0);
GFX.Sprite(GFX.TileSheet, position, Quad, color.MultiplyAgainst(Color), Rotation.FromDeg(90), Vector2.Zero, Vector2.One, SpriteEffects.None, 0);
if (TileState == 2) // Bottom
sb.Draw(tilesheet, position, Quad, color.MultiplyAgainst(Color), MathHelper.ToRadians(180), Vector2.Zero, Vector2.One, SpriteEffects.None, 0);
GFX.Sprite(GFX.TileSheet, position, Quad, color.MultiplyAgainst(Color), Rotation.FromDeg(180), Vector2.Zero, Vector2.One, SpriteEffects.None, 0);
if (TileState == 3) // Left
sb.Draw(tilesheet, position, Quad, color.MultiplyAgainst(Color), MathHelper.ToRadians(270), Vector2.Zero, Vector2.One, SpriteEffects.None, 0);
GFX.Sprite(GFX.TileSheet, position, Quad, color.MultiplyAgainst(Color), Rotation.FromDeg(270), Vector2.Zero, Vector2.One, SpriteEffects.None, 0);
//base.Draw(tilesheet, sb, x, y, color);
}
@@ -58,11 +58,11 @@ namespace CaveGame.Core.Game.Tiles
}
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
Vector2 position = new Vector2((x * Globals.TileSize) + (x.Mod(4)), (y * Globals.TileSize));
sb.Draw(tilesheet, position, Quad, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, Quad, color.MultiplyAgainst(Color));
}
public void TileUpdate(IGameWorld world, int x, int y)
@@ -87,7 +87,7 @@ namespace CaveGame.Core.Game.Tiles
world.SetTile(x, y, new Air()); // grass sometimes randomly dies
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
Vector2 position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
Rectangle quad = TileMap.TallGrass;
@@ -99,7 +99,7 @@ namespace CaveGame.Core.Game.Tiles
if (state == 1)
quad = TileMap.TallGrass3;
sb.Draw(tilesheet, position, quad, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, quad, color.MultiplyAgainst(Color));
//base.Draw(tilesheet, sb, x, y, color);
}
@@ -126,7 +126,7 @@ namespace CaveGame.Core.Game.Tiles
world.SetTile(x, y, new Air()); // grass sometimes randomly dies
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
Vector2 position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
Rectangle quad = TileMap.TallGrass;
@@ -138,7 +138,7 @@ namespace CaveGame.Core.Game.Tiles
if (state == 1)
quad = TileMap.TallGrass3;
sb.Draw(tilesheet, position, quad, color.MultiplyAgainst(Color));
GFX.Sprite(GFX.TileSheet, position, quad, color.MultiplyAgainst(Color));
//base.Draw(tilesheet, sb, x, y, color);
}

View File

@@ -1,4 +1,5 @@
using CaveGame.Core.Inventory;
using CaveGame.Core.Generic;
using CaveGame.Core.Inventory;
using CaveGame.Core.WorldGeneration;
using DataManagement;
using Microsoft.Xna.Framework;
@@ -51,8 +52,10 @@ namespace CaveGame.Core.Game.Tiles
public override Rectangle Quad => TileMap.Plank;
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine gfx, int x, int y, Light3 color)
{
var Plank = new Rectangle(2 * Globals.TileSize, 0, 4, Globals.TileSize);
var PlankRight = new Rectangle((2 * Globals.TileSize) + 4, 0 * Globals.TileSize, 4, Globals.TileSize);
var RPlank = new Rectangle(8 * Globals.TileSize, 0, 4, Globals.TileSize);
@@ -61,18 +64,21 @@ namespace CaveGame.Core.Game.Tiles
Vector2 position = new Vector2(x * Globals.TileSize, y * Globals.TileSize);
var texture = gfx.TileSheet;
var outputColor = color.MultiplyAgainst(Color);
if (TileState.Get(1)) // cornerd
sb.Draw(tilesheet, position, RPlank, color.MultiplyAgainst(Color), MathHelper.ToRadians(0), Vector2.Zero, 1, SpriteEffects.None, 1);
gfx.Sprite(texture, position, RPlank, outputColor, Rotation.Zero, Vector2.Zero, 1, SpriteEffects.None, 1);
else
sb.Draw(tilesheet, position, Plank, color.MultiplyAgainst(Color), MathHelper.ToRadians(0), Vector2.Zero, 1, SpriteEffects.None, 1);
gfx.Sprite(texture, position, Plank, outputColor, Rotation.Zero, Vector2.Zero, 1, SpriteEffects.None, 1);
if (TileState.Get(0)) // cornerc
sb.Draw(tilesheet, position + new Vector2(4, 0), RPlankRight, color.MultiplyAgainst(Color), MathHelper.ToRadians(0), Vector2.Zero, 1, SpriteEffects.None, 1);
gfx.Sprite(texture, position + new Vector2(4, 0), RPlankRight, outputColor, Rotation.Zero, Vector2.Zero, 1, SpriteEffects.None, 1);
else
sb.Draw(tilesheet, position + new Vector2(4, 0), PlankRight, color.MultiplyAgainst(Color), MathHelper.ToRadians(0), Vector2.Zero, 1, SpriteEffects.None, 1);
gfx.Sprite(texture, position + new Vector2(4, 0), PlankRight, outputColor, Rotation.Zero, Vector2.Zero, 1, SpriteEffects.None, 1);
#if EDITOR
base.Draw(tilesheet, sb, x, y, color);
base.Draw(gfx, x, y, color);
#endif
}
@@ -180,11 +186,6 @@ namespace CaveGame.Core.Game.Tiles
}
}
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
{
base.Draw(tilesheet, sb, x, y, color);
}
}
public class PineNeedles { }
}

View File

@@ -48,13 +48,6 @@ namespace CaveGame.Core.Game.Walls
public static Color BGDarken = new Color(92, 92, 92);
#if CLIENT
public static Texture2D Tilesheet = GameTextures.TileSheet;
#else
public static Texture2D Tilesheet;
#endif
public static Random RNG = new Random();
public byte Damage { get; set; }
@@ -108,30 +101,44 @@ namespace CaveGame.Core.Game.Walls
throw new Exception(String.Format("WallID not valid! {0}", t));
}
public virtual void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public virtual void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
sb.Draw(
tilesheet,
GFX.Sprite(
GFX.TileSheet,
new Vector2(x * Globals.TileSize, y * Globals.TileSize),
Quad, color.MultiplyAgainst(Color)
);
}
}
internal static Wall FromName(string name)
{
var basetype = typeof(Wall);
var types = basetype.Assembly.GetTypes().Where(type => type.IsSubclassOf(basetype));
foreach (var type in types)
{
if (name == type.Name)
return (Wall)type.GetConstructor(Type.EmptyTypes).Invoke(null);
}
throw new Exception("ID not valid!");
}
}
public class Void : Wall
{
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color) { }
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color) { }
}
public class Air : Wall, INonSolid {
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color) { }
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color) { }
}
public abstract class RockWall : Wall
{
public override byte Hardness => 5;
public override Rectangle Quad => TileMap.Stone;
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
Rectangle quad = TileMap.BGBrickTL;
@@ -145,8 +152,8 @@ namespace CaveGame.Core.Game.Walls
quad = TileMap.BGStoneBR;
//base.Dquad = TileMap.BGStoneBL;raw(tilesheet, sb, x, y, color);
sb.Draw(
tilesheet,
GFX.Sprite(
GFX.TileSheet,
new Vector2(x * Globals.TileSize, y * Globals.TileSize),
quad, color.MultiplyAgainst(Color)
);
@@ -193,7 +200,7 @@ namespace CaveGame.Core.Game.Walls
public override void Draw(Texture2D tilesheet, SpriteBatch sb, int x, int y, Light3 color)
public override void Draw(GraphicsEngine GFX, int x, int y, Light3 color)
{
Rectangle quad = TileMap.BGBrickTL;
@@ -212,8 +219,8 @@ namespace CaveGame.Core.Game.Walls
//base.Draw(tilesheet, sb, x, y, color);
sb.Draw(
tilesheet,
GFX.Sprite(
GFX.TileSheet,
new Vector2(x * Globals.TileSize, y * Globals.TileSize),
quad, color.MultiplyAgainst(Color)
);

View File

@@ -27,20 +27,29 @@ namespace CaveGame.Core
new UpdateDescription
{
VersionString = "2.2.0",
Date = "2020 November 13",
Date = "2020 November 27",
UpdateName = "Multiplayer Update 2",
Notes = new string[]{
"f",
},
ChangeLog = new string[]{
"+ Added Biomes",
"+ Added Inventory",
"+ Added Itemstacks",
"+ Upgraded rendering code",
"+ Added loading screen",
"+ Added more settings",
"+ Menus are now lua scripts.",
"+ Many under-the-hood changes and upgrades",
"+ Added summon command",
"+ Added Entity Health Stat",
"+ Added a crash report system",
"+ Added Entity Status Effects",
"+ Liquids slow entities down, some even float.",
"+ Lava damages entities and inflicts Burning debuff",
"+ Fixed some UI bugs",
}
"+ Fixed numerous bugs"
},
Notes = new string[]{
"This version will be distributed to playtesters only.",
"2.2.1 will be released on Steam in one week."
},
},
new UpdateDescription
{

390
Core/GraphicsEngine.cs Normal file
View File

@@ -0,0 +1,390 @@
using CaveGame.Core;
using CaveGame.Core.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace CaveGame.Core
{
using Circle = List<Vector2>;
using Arc = List<Vector2>;
public static class ShapeCache
{
private static readonly Dictionary<String, Circle> circleCache = new Dictionary<string, Circle>();
public static Arc GetArc(float radius, int sides, float startingAngle, float radians)
{
Arc points = new Arc();
points.AddRange(GetCircle(radius, sides));
points.RemoveAt(points.Count - 1);
double curAngle = 0.0;
double anglePerSide = MathHelper.TwoPi / sides;
while ((curAngle + (anglePerSide / 2.0)) < startingAngle)
{
curAngle += anglePerSide;
points.Add(points[0]);
points.RemoveAt(0);
}
points.Add(points[0]);
int sidesInArc = (int)((radians / anglePerSide) + 0.5);
points.RemoveRange(sidesInArc + 1, points.Count - sidesInArc - 1);
return points;
}
public static Circle GetCircle(double radius, int sides)
{
String circleKey = radius + "x" + sides;
if (circleCache.ContainsKey(circleKey))
return circleCache[circleKey];
Circle circleDef = new Circle();
const double max = 2.0 * Math.PI;
double step = max / sides;
for (double theta = 0.0; theta < max; theta += step)
{
circleDef.Add(new Vector2((float)(radius * Math.Cos(theta)), (float)(radius * Math.Sin(theta))));
}
circleDef.Add(new Vector2((float)(radius * Math.Cos(0)), (float)(radius * Math.Sin(0))));
circleCache.Add(circleKey, circleDef);
return circleDef;
}
}
public class FontManager
{
public SpriteFont Arial8 { get; private set; }
public SpriteFont Arial10 { get; private set; }
public SpriteFont Arial12 { get; private set; }
public SpriteFont Arial14 { get; private set; }
public SpriteFont Arial16 { get; private set; }
public SpriteFont Arial20 { get; private set; }
public SpriteFont Arial30 { get; private set; }
public SpriteFont Arial10Italic { get; private set; }
public SpriteFont Consolas10 { get; private set; }
public SpriteFont Consolas12 { get; private set; }
public SpriteFont ComicSans10 { get; private set; }
public void LoadAssets(ContentManager Content)
{
Arial8 = Content.Load<SpriteFont>("Fonts/Arial8");
Arial10 = Content.Load<SpriteFont>("Fonts/Arial10");
Arial12 = Content.Load<SpriteFont>("Fonts/Arial12");
Arial14 = Content.Load<SpriteFont>("Fonts/Arial14");
Arial16 = Content.Load<SpriteFont>("Fonts/Arial16");
Arial20 = Content.Load<SpriteFont>("Fonts/Arial20");
Arial30 = Content.Load<SpriteFont>("Fonts/Arial30");
Arial10Italic = Content.Load<SpriteFont>("Fonts/Arial10Italic");
Consolas10 = Content.Load<SpriteFont>("Fonts/Consolas10");
Consolas12 = Content.Load<SpriteFont>("Fonts/Consolas12");
ComicSans10 = Content.Load<SpriteFont>("Fonts/ComicSans10");
}
}
public class GraphicsEngine : IGraphicsEngine
{
public bool LoadFonts { get; set; }
public static GraphicsEngine Instance { get; private set; }
#region Texture Shortcuts
public Texture2D Player => Textures["Entities/player.png"];
public Texture2D TitleScreen => Textures["TitleScreen.png"];
public Texture2D EyeOfHorus => Textures["csoft.png"];
public Texture2D ParticleSet => Textures["particles.png"];
public Texture2D TileSheet => Textures["tilesheet.png"];
public Texture2D BG => Textures["bg.png"];
public Texture2D Border => Textures["border.png"];
public Texture2D Slot => Textures["slot.png"];
public Texture2D BombSprite => Textures["bomb.png"];
public Texture2D Bong => Textures["bong.png"];
public Texture2D Arrow => Textures["arrow.png"];
public Texture2D Bucket => Textures["bucket.png"];
public Texture2D BigPickaxe => Textures["bigpickaxe.png"];
public Texture2D Helmet => Textures["helmet.png"];
public Texture2D Chestplate => Textures["chestplate.png"];
public Texture2D Sword => Textures["sword.png"];
public Texture2D WallScraper => Textures["wallscraper.png"];
public Texture2D PickaxeNew => Textures["pickaxenew.png"];
public Texture2D Scroll => Textures["scroll.png"];
public Texture2D Dynamite => Textures["dynamite.png"];
public Texture2D Workbench => Textures["workbench.png"];
public Texture2D Potion => Textures["potion.png"];
public Texture2D Jetpack => Textures["jetpack.png"];
public Texture2D Door => Textures["door.png"];
public Texture2D ForestPainting => Textures["forestpainting.png"];
public Texture2D Ingot => Textures["ingot.png"];
public Texture2D Leggings => Textures["leggings.png"];
public Texture2D Furnace => Textures["furnace.png"];
public Texture2D Campfire => Textures["campfire.png"];
public Texture2D VoidMonster => Textures["Entities/tortured.png"];
//public static Texture2D Campfire => Textures["campfire.png"];
#endregion
public Dictionary<string, Texture2D> Textures = new Dictionary<string, Texture2D>();
struct TextureDef
{
public string Path { get; set; }
public string Name { get; set; }
public TextureDef(string name, string path)
{
Name = name;
Path = path;
}
}
private Queue<TextureDef> LoadingQueue = new Queue<TextureDef>();
public AssetLoader AssetLoader = new AssetLoader();
private Texture2D pixel;
private void LoadNextAsset(GraphicsDevice gdev)
{
TextureDef nextTex = LoadingQueue.Dequeue();
Texture2D loaded = AssetLoader.LoadTexture(gdev, nextTex.Path);
Textures.Add(nextTex.Name, loaded);
LoadedTextures++;
}
public int TotalTextures { get; private set; }
public int LoadedTextures { get; private set; }
public bool FontsLoaded { get; set; }
public void LoadAssets(GraphicsDevice graphicsDevice)
{
// var texturesPath = Path.Combine("Assets", "Textures");
// if (Directory.Exists(texturesPath))
// {
foreach (var tex in Directory.GetFiles("Assets/Textures/", "*.png"))
{
//Texture2D loaded = AssetLoader.LoadTexture(graphicsDevice, tex);
LoadingQueue.Enqueue(new TextureDef(
tex.Replace("Assets/Textures/", ""),
tex
));
TotalTextures++;
}
//}
foreach (var tex in Directory.GetFiles("Assets/Entities/", "*.png"))
{
// Texture2D loaded = AssetLoader.LoadTexture(graphicsDevice, tex);
LoadingQueue.Enqueue(new TextureDef(
tex.Replace("Assets/", ""),
tex
));
TotalTextures++;
}
foreach (var tex in Directory.GetFiles("Assets/Items/", "*.png"))
{
//Texture2D loaded = AssetLoader.LoadTexture(graphicsDevice, tex);
LoadingQueue.Enqueue(new TextureDef(
tex.Replace("Assets/Items/", ""),
tex
));
TotalTextures++;
}
}
public void Initialize()
{
SpriteBatch = new SpriteBatch(GraphicsDevice);
if (LoadFonts)
Fonts.LoadAssets(ContentManager);
// create pixel
pixel = new Texture2D(GraphicsDevice, 1, 1);
pixel.SetData<Color>(new Color[] { Color.White });
FontsLoaded = true;
}
public FontManager Fonts = new FontManager();
public Vector2 WindowSize { get; set; }
public SpriteSortMode SpriteSortMode { get; set; }
public BlendState BlendState { get; set; }
public SamplerState SamplerState { get; set; }
public DepthStencilState DepthStencilState { get; set; }
public RasterizerState RasterizerState { get; set; }
public Effect Shader { get; set; }
public Matrix Matrix { get; set; }
public ContentManager ContentManager { get; set; }
public SpriteBatch SpriteBatch { get; set; }
public GraphicsDevice GraphicsDevice { get; set; }
public GraphicsDeviceManager GraphicsDeviceManager { get; set; }
public bool ContentLoaded { get; private set; }
public float GraphicsTimer { get; set; }
public float LoadingDelay { get; set; }
public GraphicsEngine()
{
Instance = this;
LoadingDelay = 0.03f;
FontsLoaded = false;
LoadFonts = true;
}
float ardeusIsADipshit;
public void Update(GameTime gt)
{
//ardeusIsADipshit += gt.GetDelta();
// if (ardeusIsADipshit > LoadingDelay)
// {
// ardeusIsADipshit = 0;
if (LoadingQueue.Count > 0)
LoadNextAsset(GraphicsDevice);
if (LoadingQueue.Count == 0)
ContentLoaded = true;
// }
}
public void Clear(Color color) => GraphicsDevice.Clear(color);
public void End() => SpriteBatch.End();
public void Begin() => SpriteBatch.Begin();
public void Begin(SpriteSortMode sorting = SpriteSortMode.Deferred, BlendState blending = null, SamplerState sampling = null, DepthStencilState depthStencil = null, RasterizerState rasterizing = null, Effect effect = null, Matrix? transform = null)
{
SpriteBatch.Begin(sorting, blending, sampling, depthStencil, rasterizing, effect, transform);
}
public void Arc(Color color, Vector2 center, float radius, int sides, Rotation startingAngle, Rotation radians, float thickness = 1)
{
List<Vector2> arc = ShapeCache.GetArc(radius, sides, startingAngle.Radians, radians.Radians);
Polygon(color, center, arc, thickness);
}
public void Circle(Color color, Vector2 position, double radius, int sides = 12, float thickness = 1)
{
List<Vector2> c = ShapeCache.GetCircle(radius, sides);
Polygon(color, position, c, thickness);
}
public void Line(Color color, Vector2 point, float length, Rotation angle, float thickness = 1)
{
Vector2 origin = new Vector2(0f, 0.5f);
Vector2 scale = new Vector2(length, thickness);
SpriteBatch.Draw(pixel, point, null, color, angle.Radians, origin, scale, SpriteEffects.None, 0);
}
public void Line(Color color, Vector2 point1, Vector2 point2, float thickness = 1)
{
float distance = Vector2.Distance(point1, point2);
float angle = (float)Math.Atan2(point2.Y - point1.Y, point2.X - point1.X);
float expanded = (float)Math.Floor(angle * Math.PI);
float backDown = expanded / (float)Math.PI;
Line(color, point1, distance, Rotation.FromRad(angle), thickness);
}
public void OutlineRect(Color color, Vector2 position, Vector2 size, float thickness = 2.0f)
{
Line(color, position, position + new Vector2(0, size.Y), thickness);
Line(color, position, position + new Vector2(size.X, 0), thickness);
Line(color, position + new Vector2(size.X, 0), position + size, thickness);
Line(color, position + new Vector2(0, size.Y), position + new Vector2(size.X, size.Y), thickness);
}
public void Polygon(Color color, Vector2 position, List<Vector2> points, float thickness = 1)
{
if (points.Count < 2)
return;
for (int i = 1; i < points.Count; i++)
Line(color, points[i - 1] + position, points[i] + position, thickness);
}
public void Polygon(Color color, List<Vector2> points, float thickness = 1)
{
if (points.Count < 2)
return;
for (int i = 1; i < points.Count; i++)
Line(color, points[i - 1], points[i], thickness);
}
public void Rect(Color color, Vector2 position, Vector2 size) => Rect(color, position, size, Rotation.Zero);
public void Rect(Color color, Vector2 position, Vector2 size, Rotation rotation)
{
SpriteBatch.Draw(
pixel,
new Rectangle(position.ToPoint(), size.ToPoint()),
null,
color, rotation.Degrees, new Vector2(0, 0), SpriteEffects.None, 0
);
}
public void Sprite(Texture2D texture, Vector2 position) => Sprite(texture, position, Color.White);
public void Sprite(Texture2D texture, Vector2 position, Color color) => SpriteBatch.Draw(texture, position, color);
public void Sprite(Texture2D texture, Vector2 position, Rectangle? quad, Color color) => SpriteBatch.Draw(texture, position, quad, color);
public void Sprite(Texture2D texture, Vector2 position, Rectangle? quad, Color color, Rotation rotation, Vector2 origin, Vector2 scale, SpriteEffects efx, float layer) => SpriteBatch.Draw(texture,position,quad,color,rotation.Degrees,origin,scale,efx,layer);
public void Sprite(Texture2D texture, Vector2 position, Rectangle? quad, Color color, Rotation rotation, Vector2 origin, float scale, SpriteEffects efx, float layer) => SpriteBatch.Draw(texture, position, quad, color, rotation.Degrees, origin, scale, efx, layer);
public void Text(string text, Vector2 position) => Text(Fonts.Arial10, text, position);
public void Text(string text, Vector2 position, Color color) => SpriteBatch.DrawString(Fonts.Arial10, text, position, color);
public void Text(SpriteFont font, string text, Vector2 position) => Text(font, text, position, Color.White, TextXAlignment.Left, TextYAlignment.Top);
public void Text(SpriteFont font, string text, Vector2 position, Color color, TextXAlignment textX = TextXAlignment.Left, TextYAlignment textY = TextYAlignment.Top)
{
float xoffset = 0;
float yoffset = 0;
Vector2 bounds = font.MeasureString(text);
if (textX == TextXAlignment.Center)
xoffset = bounds.X / 2;
if (textX == TextXAlignment.Right)
xoffset = bounds.X;
if (textY == TextYAlignment.Center)
yoffset = bounds.Y / 2;
if (textY == TextYAlignment.Bottom)
yoffset = bounds.Y;
SpriteBatch.DrawString(font, text, position-new Vector2(xoffset, yoffset), color);
}
/*public void Line3D(Camera camera, Vector3 pointA, Vector3 pointB, Color color)
{
Line3D(camera, pointA, pointB, color, color);
}
public void Line3D(Camera camera, Vector3 pointA, Vector3 pointB, Color colorA, Color colorB)
{
Line3D(camera, pointA, pointB, colorA, colorB);
}
public void Line3D(Camera camera, Vector3 pointA, Vector3 pointB, Color color)
{
Line3D(camera, pointA, pointB, color, color);
}
public void Line3D(Camera camera, Vector3 pointA, Vector3 pointB, Color colorA, Color colorB)
{
_effect3D.View = camera.View;
_effect3D.Projection = camera.Projection;
_effect3D.CurrentTechnique.Passes[0].Apply();
var vertices = new[] { new VertexPositionColor(pointA, colorA), new VertexPositionColor(pointB, colorB)};
GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, vertices, 0, 1);
}*/
}
}

View File

@@ -0,0 +1,109 @@
using CaveGame.Core.Game.Entities;
using CaveGame.Core.Generic;
using CaveGame.Core.Network;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace CaveGame.Core
{
public enum TextXAlignment
{
Left,
Center,
Right
}
public enum TextYAlignment
{
Top,
Center,
Bottom,
}
public enum GameSteamAchievement : byte
{
HELLO_WORLD = 0,
MORNING_WOOD = 1,
}
public interface IEntityManager
{
int GetNextEntityNetworkID();
}
public interface ISteamManager
{
bool HasAchievement(GameSteamAchievement ach);
void AwardAchievement(GameSteamAchievement ach);
}
public interface ICaveGame
{
}
public interface ICommonGameDriver
{
IMessageOutlet Output { get; }
}
public interface IGameClient
{
Camera2D Camera { get; }
void Send(Packet p);
IClientWorld World { get; }
}
public interface IGameServer
{
void SendTo(Packet p, User user);
void SendToAll(Packet p);
void SendToAllExcept(Packet p, User exclusion);
User GetConnectedUser(IPEndPoint ep);
void OutputAndChat(string text);
void Chat(string text);
void Chat(string text, Color color);
IServerWorld World { get; }
void SpawnEntity(IEntity entity);
void Update(GameTime gt);
int TickRate { get; }
int MaxPlayers { get; }
IEntityManager EntityManager { get; }
}
// TODO: Make comprehensive render contract
public interface IGraphicsEngine
{
Vector2 WindowSize { get; set; }
SpriteBatch SpriteBatch { get; set; }
SpriteSortMode SpriteSortMode { get; set; }
BlendState BlendState { get; set; }
SamplerState SamplerState { get; set; }
DepthStencilState DepthStencilState { get; set; }
RasterizerState RasterizerState { get; set; }
Effect Shader { get; set; }
Matrix Matrix { get; set; }
void Begin(SpriteSortMode sorting = SpriteSortMode.Deferred, BlendState blending = null, SamplerState sampling = null,
DepthStencilState depthStencil = null, RasterizerState rasterizing = null, Effect effect = null, Matrix? transform = null);
void Begin();
void End();
}
// todo: sound
public interface ISoundEngine
{
}
}

View File

@@ -1,20 +0,0 @@
using CaveGame.Core.Game.Entities;
using CaveGame.Core.Network;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace CaveGame.Core
{
public interface IGameServer
{
void SendTo(Packet p, User user);
void SendToAll(Packet p);
void SendToAllExcept(Packet p, User exclusion);
User GetConnectedUser(IPEndPoint ep);
void OutputAndChat(string text);
void SpawnEntity(IEntity entity);
}
}

View File

@@ -14,6 +14,7 @@ using CaveGame.Core.FileUtil;
using CaveGame.Core.Inventory;
using CaveGame.Core.Generic;
using DataManagement;
using System.Collections.Generic;
namespace CaveGame.Core.Network
{
@@ -80,6 +81,8 @@ namespace CaveGame.Core.Network
SExplosion,
PlayerThrowItemAction,
SpawnBombEntity,
SpawnWurmholeEntity,
TriggerWurmholeEntity,
SpawnItemStackEntity,
PlaceFurniture, RemoveFurniture,
OpenDoor, CloseDoor, TimeOfDay,
@@ -87,7 +90,7 @@ namespace CaveGame.Core.Network
UpdateContainer,
DamageTile,
GivePlayerItem, // Temporary for testing?
AdminCommand
}
@@ -374,6 +377,38 @@ namespace CaveGame.Core.Network
public SpawnBombEntityPacket(byte[] data) : base(data) { }
}
public class SpawnWurmholeEntityPacket : Packet
{
public int EntityNetworkID
{
get => Payload.ReadInt(0);
set => Payload.WriteInt(0, value);
}
public SpawnWurmholeEntityPacket(byte[] data) : base(data) { }
public SpawnWurmholeEntityPacket(int entityNetworkID) : base(PacketType.SpawnWurmholeEntity)
{
Payload = new byte[8];
EntityNetworkID = entityNetworkID;
}
}
public class TriggerWurmholeEntityPacket : Packet
{
public int EntityNetworkID
{
get => Payload.ReadInt(0);
set => Payload.WriteInt(0, value);
}
public TriggerWurmholeEntityPacket(byte[] data) : base(data) { }
public TriggerWurmholeEntityPacket(int entityNetworkID) : base(PacketType.TriggerWurmholeEntity) // should be PacketType.TriggerWurmholeEntity
{
Payload = new byte[8];
EntityNetworkID = entityNetworkID;
}
}
public class SpawnItemStackPacket : Packet {
public int EntityNetworkID
@@ -391,20 +426,15 @@ namespace CaveGame.Core.Network
{
get
{
int quantity = Payload.ReadInt(12);
var binary = Metabinary.Deserialize(Payload, 16);
Metabinary.DebugText(binary);
return new ItemStack { Quantity = quantity, Item = Item.FromMetadataComplex(binary) };
int quantity = Payload.ReadInt(12);
Payload.ReadStringAuto(16, Encoding.ASCII, out string itemname);
return new ItemStack { Quantity = quantity, Item = Item.FromName(itemname) };
}
set
{
Metabinary data = value.Item.GetMetadataComplex();
byte[] bytedata = data.Serialize();
Payload = new byte[16+bytedata.Length];
Payload = new byte[16+4+Encoding.ASCII.GetByteCount(value.Item.Name)];
Payload.WriteInt(12, value.Quantity);
Array.Copy(bytedata, 0, Payload, 16, bytedata.Length);
Payload.WriteStringAuto(16, value.Item.Name, Encoding.ASCII);
}
}
@@ -425,23 +455,21 @@ namespace CaveGame.Core.Network
{
get
{
int quantity = TypeSerializer.ToInt(Payload, 0);
var binary = Metabinary.Deserialize(Payload, 4);
Metabinary.DebugText(binary);
return new ItemStack { Quantity = quantity, Item = Item.FromMetadataComplex(binary) };
int quantity = Payload.ReadInt(0);
Payload.ReadStringAuto(4, Encoding.ASCII, out string itemname);
return new ItemStack { Quantity = quantity, Item = Item.FromName(itemname) };
}
set
{
Metabinary data = value.Item.GetMetadataComplex();
byte[] bytedata = data.Serialize();
Payload = new byte[bytedata.Length + 4];
TypeSerializer.FromInt(ref Payload, 0, value.Quantity);
Array.Copy(bytedata, 0, Payload, 4, bytedata.Length);
Payload = new byte[4 + 4 + Encoding.ASCII.GetByteCount(value.Item.Name)];
Payload.WriteInt(0, value.Quantity);
Payload.WriteStringAuto(4, value.Item.Name, Encoding.ASCII);
}
}
public GivePlayerItemPacket(byte[] data) : base(data) { }
public GivePlayerItemPacket(ItemStack reward) : base(PacketType.GivePlayerItem)
{
@@ -962,9 +990,82 @@ namespace CaveGame.Core.Network
{
}
}
public class AdminCommandPacket : Packet
{
// 0 - PlayerNetworkID int
// 4 - CommandStringLength int
//
//
//
//
//
//
public string Command
{
get
{
Payload.ReadStringAuto(4, Encoding.ASCII, out string ret);
return ret;
}
set => Payload.WriteStringAuto(4, value, Encoding.ASCII);
}
public int CommandByteDataLength => Payload.ReadInt(4);
public int PlayerNetworkID
{
get => Payload.ReadInt(0);
set => Payload.WriteInt(0, value);
}
public string[] Arguments
{
get
{
int index = 4+CommandByteDataLength+4;
int expectedStrings = Payload.ReadInt(index);
List<string> argdata = new List<string>();
index += 4;
for (int i = 0; i < expectedStrings; i++)
{
index += Payload.ReadStringAuto(index, Encoding.ASCII, out string result);
argdata.Add(result);
}
return argdata.ToArray();
}
set
{
int index = 4+CommandByteDataLength+4;
Payload.WriteInt(index, value.Length);
index += 4;
foreach (string str in value)
index += Payload.WriteStringAuto(index, str, Encoding.ASCII);
}
}
public AdminCommandPacket(byte[] data) : base(data) { }
public AdminCommandPacket(string command, string[] args, int playerNetworkID) : base(PacketType.AdminCommand) {
// get size?
int size = 8+ Encoding.ASCII.GetBytes(command).Length + 4;
foreach (var str in args)
size += Encoding.ASCII.GetBytes(str).Length + 4;
Payload = new byte[size];
Command = command;
Arguments = args;
PlayerNetworkID = playerNetworkID;
}
}
public class PlaceWallPacket : Packet
{

View File

@@ -162,15 +162,15 @@ namespace CaveGame.Core
// }
}
private void DrawForegroundBuffer(Texture2D tilesheet, GraphicsDevice device, SpriteBatch sb)
private void DrawForegroundBuffer(GraphicsEngine GFX)
{
if (ForegroundRenderBuffer == null)
ForegroundRenderBuffer = new RenderTarget2D(device, ChunkSize * Globals.TileSize, ChunkSize * Globals.TileSize);
ForegroundRenderBuffer = new RenderTarget2D(GFX.GraphicsDevice, ChunkSize * Globals.TileSize, ChunkSize * Globals.TileSize);
device.SetRenderTarget(ForegroundRenderBuffer);
device.Clear(Color.Black * 0f);
GFX.GraphicsDevice.SetRenderTarget(ForegroundRenderBuffer);
GFX.Clear(Color.Black * 0f);
sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
GFX.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
Tile tile;
for (int x = 0; x < ChunkSize; x++)
@@ -179,24 +179,22 @@ namespace CaveGame.Core
{
tile = GetTile(x, y);
if (tile.ID > 0)
{
tile.Draw(tilesheet, sb, x, y, Lights[x, y]);
}
tile.Draw(GFX, x, y, Lights[x, y]);
}
}
sb.End();
device.SetRenderTarget(null);
GFX.End();
GFX.GraphicsDevice.SetRenderTarget(null);
}
private void DrawBackgroundBuffer(Texture2D tilesheet, GraphicsDevice device, SpriteBatch sb)
private void DrawBackgroundBuffer(GraphicsEngine GFX)
{
if (BackgroundRenderBuffer == null)
BackgroundRenderBuffer = new RenderTarget2D(device, ChunkSize * Globals.TileSize, ChunkSize * Globals.TileSize);
BackgroundRenderBuffer = new RenderTarget2D(GFX.GraphicsDevice, ChunkSize * Globals.TileSize, ChunkSize * Globals.TileSize);
device.SetRenderTarget(BackgroundRenderBuffer);
device.Clear(Color.Black * 0f);
GFX.GraphicsDevice.SetRenderTarget(BackgroundRenderBuffer);
GFX.Clear(Color.Black * 0f);
sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
GFX.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
Wall wall;
for (int x = 0; x < ChunkSize; x++)
@@ -206,22 +204,22 @@ namespace CaveGame.Core
wall = GetWall(x, y);
if (wall.ID > 0)
{
wall.Draw(tilesheet, sb, x, y, Lights[x, y]);
wall.Draw(GFX, x, y, Lights[x, y]);
}
}
}
sb.End();
device.SetRenderTarget(null);
GFX.End();
GFX.GraphicsDevice.SetRenderTarget(null);
}
public void Draw(Texture2D tilesheet, GraphicsDevice device, SpriteBatch sb)
public void Draw(GraphicsEngine GFX)
{
Chunk.RefreshedThisFrame = true;
// cock and ball torture
UpdateRenderBuffer = false;
DrawBackgroundBuffer(tilesheet, device, sb);
DrawForegroundBuffer(tilesheet, device, sb);
DrawBackgroundBuffer(GFX);
DrawForegroundBuffer(GFX);
}
}
}

View File

@@ -74,14 +74,14 @@ namespace CaveGame.Core
public Color[] SkyColors =
{
new Color(0, 5, 12), new Color(0, 10, 64), //0 or 24
new Color(5, 10, 12), new Color(10, 20, 92), //2
new Color(32, 32, 32), new Color(48, 48, 130), //4
new Color(35, 30, 51), new Color(76, 50, 150), //6
new Color(0, 2, 6), new Color(5, 5, 30), //0 or 24
new Color(2, 2, 10), new Color(16, 16, 40), //2
new Color(2, 2, 10), new Color(20, 20, 45), //4
new Color(8, 9, 50), new Color(85, 85, 40), //6
new Color(40, 60, 90), new Color(90, 90, 190), //8
new Color(70, 90, 130), new Color(110, 110, 230), //10
new Color(70, 80, 170), new Color(150, 150, 255), //12
new Color(80, 100, 140), new Color(110, 110, 220), //14
new Color(70, 80, 170), new Color(170, 170, 255), //12
new Color(80, 100, 140), new Color(140, 140, 250), //14
new Color(35, 41, 60), new Color(60, 80, 140), //14
new Color(50, 32, 50), new Color(170, 100, 70), // 18
new Color(25, 25, 55), new Color(92, 52, 23), //20

View File

@@ -25,7 +25,8 @@ namespace DataManagement
public struct IntegerRange : IRange<int>
{
public static IntegerRange PercentInterval = new IntegerRange(0, 100);
public static IntegerRange I_PercentInterval = new IntegerRange(0, 100);
public bool Inclusive { get; private set; }
public int LowerLimit { get; private set; }

View File

@@ -45,6 +45,26 @@ namespace DataManagement
public static void WriteFloat(this byte[] data, int index, float value) => FromFloat(ref data, index, value);
public static double ReadDouble(this byte[] data, int index) => ToDouble(data, index);
public static void WriteDouble(this byte[] data, int index, double value) => FromDouble(ref data, index, value);
public static string ReadString(this byte[] data, int index, int length, Encoding encoder) => ToString(encoder, data, index, length);
public static void WriteString(this byte[] data, int index, string msg, Encoding encoder, int length) => FromString(ref data, encoder, msg, index, length);
public static int ReadStringAuto(this byte[] data, int index, Encoding encoder, out string result)
{
int length = data.ReadInt(index);
result = data.ReadString(index + 4, length, encoder);
return length+4;
}
public static int WriteStringAuto(this byte[] data, int index, string msg, Encoding encoder)
{
byte[] stringbytes = encoder.GetBytes(msg);
data.WriteInt(index, stringbytes.Length);
data.WriteString(index+4, msg, encoder, stringbytes.Length);
return stringbytes.Length+4;
}
public static byte[] FromChar(char input) => BitConverter.GetBytes(input);

View File

@@ -123,6 +123,8 @@ namespace Editor.Actions
StructureMetadata newMetadata;
Tile[,] oldTileGrid;
Wall[,] oldWallGrid;
Tile[,] newTileGrid;
Wall[,] newWallGrid;
public StructureResizeAction(StructureFile file, StructureMetadata _newMD, Point _newSize)
{
@@ -159,11 +161,16 @@ namespace Editor.Actions
structure.Layers[0].Walls[x, y] = oldWallGrid[x, y];
}
}
newTileGrid = structure.Layers[0].Tiles;
newWallGrid = structure.Layers[0].Walls;
}
public void Redo()
{
throw new System.NotImplementedException();
structure.Metadata = newMetadata;
structure.Layers[0].Tiles = newTileGrid;
structure.Layers[0].Walls = newWallGrid;
}
public void Undo()

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 968 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 918 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 414 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 694 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

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