Add first block children ConsoleBlock and TextBlock, I hope they're not bullied at school for those names

This commit is contained in:
NGnius (Graham) 2020-05-17 23:19:16 -04:00
parent 6dce87fb66
commit 97de5e606b
7 changed files with 514 additions and 214 deletions

View file

@ -1,4 +1,5 @@
using System; using System;
using System.Reflection;
using Svelto.ECS; using Svelto.ECS;
using Svelto.ECS.EntityStructs; using Svelto.ECS.EntityStructs;
@ -11,179 +12,209 @@ using GamecraftModdingAPI.Utility;
namespace GamecraftModdingAPI namespace GamecraftModdingAPI
{ {
/// <summary> /// <summary>
/// A single (perhaps scaled) block. Properties may return default values if the block is removed and then setting them is ignored. /// A single (perhaps scaled) block. Properties may return default values if the block is removed and then setting them is ignored.
/// </summary> /// </summary>
public class Block public class Block
{ {
private static readonly PlacementEngine PlacementEngine = new PlacementEngine(); protected static readonly PlacementEngine PlacementEngine = new PlacementEngine();
private static readonly MovementEngine MovementEngine = new MovementEngine(); protected static readonly MovementEngine MovementEngine = new MovementEngine();
private static readonly RotationEngine RotationEngine = new RotationEngine(); protected static readonly RotationEngine RotationEngine = new RotationEngine();
private static readonly RemovalEngine RemovalEngine = new RemovalEngine(); protected static readonly RemovalEngine RemovalEngine = new RemovalEngine();
private static readonly BlockEngine BlockEngine = new BlockEngine(); protected static readonly BlockEngine BlockEngine = new BlockEngine();
/// <summary> /// <summary>
/// Place a new block at the given position. If scaled, position means the center of the block. The default block size is 0.2 in terms of position. /// Place a new block at the given position. If scaled, position means the center of the block. The default block size is 0.2 in terms of position.
/// Place blocks next to each other to connect them. /// Place blocks next to each other to connect them.
/// The placed block will be a complete block with a placement grid and collision which will be saved along with the game. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
/// </summary> /// </summary>
/// <param name="block">The block's type</param> /// <param name="block">The block's type</param>
/// <param name="color">The block's color</param> /// <param name="color">The block's color</param>
/// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param> /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
/// <param name="position">The block's position in the grid - default block size is 0.2</param> /// <param name="position">The block's position in the grid - default block size is 0.2</param>
/// <param name="rotation">The block's rotation in degrees</param> /// <param name="rotation">The block's rotation in degrees</param>
/// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param> /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
/// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param> /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
/// <param name="player">The player who placed the block</param> /// <param name="player">The player who placed the block</param>
/// <returns>The placed block or null if failed</returns> /// <returns>The placed block or null if failed</returns>
public static Block PlaceNew(BlockIDs block, float3 position, public static Block PlaceNew(BlockIDs block, float3 position,
float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0, float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
int uscale = 1, float3 scale = default, Player player = null) int uscale = 1, float3 scale = default, Player player = null)
{ {
if (PlacementEngine.IsInGame && GameState.IsBuildMode()) if (PlacementEngine.IsInGame && GameState.IsBuildMode())
{ {
try try
{ {
return new Block(PlacementEngine.PlaceBlock(block, color, darkness, return new Block(PlacementEngine.PlaceBlock(block, color, darkness,
position, uscale, scale, player, rotation)); position, uscale, scale, player, rotation));
} }
catch (Exception e) catch (Exception e)
{ {
Logging.MetaDebugLog(e); Logging.MetaDebugLog(e);
} }
} }
return null; return null;
} }
/// <summary> /// <summary>
/// Returns the most recently placed block. /// Returns the most recently placed block.
/// </summary> /// </summary>
/// <returns>The block object</returns> /// <returns>The block object</returns>
public static Block GetLastPlacedBlock() public static Block GetLastPlacedBlock()
{ {
return new Block(BlockIdentifiers.LatestBlockID); return new Block(BlockIdentifiers.LatestBlockID);
} }
public Block(EGID id) public Block(EGID id)
{ {
Id = id; Id = id;
} }
public Block(uint id) public Block(uint id)
{ {
Id = new EGID(id, CommonExclusiveGroups.OWNED_BLOCKS_GROUP); Id = new EGID(id, CommonExclusiveGroups.OWNED_BLOCKS_GROUP);
} }
public EGID Id { get; } protected static void Sync()
{
DeterministicStepCompositionRootPatch.SubmitEntitiesNow();
}
/// <summary> public EGID Id { get; }
/// The block's current position or zero if the block no longer exists.
/// A block is 0.2 wide by default in terms of position.
/// </summary>
public float3 Position
{
get => Exists ? MovementEngine.GetPosition(Id.entityID) : float3.zero;
set
{
if (Exists) MovementEngine.MoveBlock(Id.entityID, value);
}
}
/// <summary> /// <summary>
/// The block's current rotation in degrees or zero if the block doesn't exist. /// The block's current position or zero if the block no longer exists.
/// </summary> /// A block is 0.2 wide by default in terms of position.
public float3 Rotation /// </summary>
{ public float3 Position
get => Exists ? RotationEngine.GetRotation(Id.entityID) : float3.zero; {
set get => Exists ? MovementEngine.GetPosition(Id.entityID) : float3.zero;
{ set
if (Exists) RotationEngine.RotateBlock(Id.entityID, value); {
} if (Exists) MovementEngine.MoveBlock(Id.entityID, value);
} }
}
/// <summary> /// <summary>
/// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling. /// The block's current rotation in degrees or zero if the block doesn't exist.
/// </summary> /// </summary>
public float3 Scale public float3 Rotation
{ {
get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id)?.scale ?? float3.zero; get => Exists ? RotationEngine.GetRotation(Id.entityID) : float3.zero;
set set
{ {
var def = new ScalingEntityStruct(); if (Exists) RotationEngine.RotateBlock(Id.entityID, value);
BlockEngine.GetBlockInfo(Id, ref def).scale = value; }
} }
}
/// <summary> /// <summary>
/// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
/// </summary> /// </summary>
public int UniformScale public float3 Scale
{ {
get => BlockEngine.GetBlockInfo<BlockPlacementScaleEntityStruct>(Id)?.desiredScaleFactor ?? 0; get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id)?.scale ?? float3.zero;
set set
{ {
var def = new BlockPlacementScaleEntityStruct(); var def = new ScalingEntityStruct();
ref var scaleStruct = ref BlockEngine.GetBlockInfo(Id, ref def); BlockEngine.GetBlockInfo(Id, ref def).scale = value;
scaleStruct.blockPlacementHeight = scaleStruct.blockPlacementWidth = }
scaleStruct.desiredScaleFactor = scaleStruct.snapGridScale = value; }
Scale = new float3(value, value, value);
}
}
/// <summary> /// <summary>
/// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
/// </summary> /// </summary>
public BlockIDs Type => (BlockIDs) (BlockEngine.GetBlockInfo<DBEntityStruct>(Id)?.DBID ?? ushort.MaxValue); public int UniformScale
{
get => BlockEngine.GetBlockInfo<BlockPlacementScaleEntityStruct>(Id)?.desiredScaleFactor ?? 0;
set
{
var def = new BlockPlacementScaleEntityStruct();
ref var scaleStruct = ref BlockEngine.GetBlockInfo(Id, ref def);
scaleStruct.blockPlacementHeight = scaleStruct.blockPlacementWidth =
scaleStruct.desiredScaleFactor = scaleStruct.snapGridScale = value;
Scale = new float3(value, value, value);
}
}
/// <summary> /// <summary>
/// The block's color. Returns BlockColors.Default if the block no longer exists. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
/// </summary> /// </summary>
public BlockColor Color public BlockIDs Type => (BlockIDs)(BlockEngine.GetBlockInfo<DBEntityStruct>(Id)?.DBID ?? ushort.MaxValue);
{
get
{
byte index = BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id)?.indexInPalette ?? byte.MaxValue;
if (index == byte.MaxValue) return new BlockColor {Color = BlockColors.Default};
return new BlockColor {Color = (BlockColors) (index % 10), Darkness = (byte) (index / 10)};
}
set
{
var def = new ColourParameterEntityStruct();
ref var color = ref BlockEngine.GetBlockInfo(Id, ref def);
color.indexInPalette = (byte) (value.Color + value.Darkness * 10);
color.needsUpdate = true;
}
}
/// <summary> /// <summary>
/// Whether the block exists. The other properties will return a default value if the block doesn't exist. /// The block's color. Returns BlockColors.Default if the block no longer exists.
/// </summary> /// </summary>
public bool Exists => BlockEngine.BlockExists(Id); public BlockColor Color
{
get
{
byte index = BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id)?.indexInPalette ?? byte.MaxValue;
if (index == byte.MaxValue) return new BlockColor { Color = BlockColors.Default };
return new BlockColor { Color = (BlockColors)(index % 10), Darkness = (byte)(index / 10) };
}
set
{
var def = new ColourParameterEntityStruct();
ref var color = ref BlockEngine.GetBlockInfo(Id, ref def);
color.indexInPalette = (byte)(value.Color + value.Darkness * 10);
color.needsUpdate = true;
}
}
/// <summary> /// <summary>
/// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
/// </summary> /// </summary>
public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id); public bool Exists => BlockEngine.BlockExists(Id);
/// <summary> /// <summary>
/// Removes this block. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
/// </summary> /// </summary>
/// <returns>True if the block exists and could be removed.</returns> public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
public bool Remove() => RemovalEngine.RemoveBlock(Id);
public override string ToString() /// <summary>
{ /// Removes this block.
return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Rotation)}: {Rotation}"; /// </summary>
} /// <returns>True if the block exists and could be removed.</returns>
public bool Remove() => RemovalEngine.RemoveBlock(Id);
public static void Init() public override string ToString()
{ {
GameEngineManager.AddGameEngine(PlacementEngine); return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Rotation)}: {Rotation}";
GameEngineManager.AddGameEngine(MovementEngine); }
GameEngineManager.AddGameEngine(RotationEngine);
GameEngineManager.AddGameEngine(RemovalEngine); public static void Init()
GameEngineManager.AddGameEngine(BlockEngine); {
} GameEngineManager.AddGameEngine(PlacementEngine);
} GameEngineManager.AddGameEngine(MovementEngine);
GameEngineManager.AddGameEngine(RotationEngine);
GameEngineManager.AddGameEngine(RemovalEngine);
GameEngineManager.AddGameEngine(BlockEngine);
}
public T Specialise<T>(bool sameTick = true) where T : Block
{
// What have I gotten myself into?
// C# can't cast to a child of Block unless the object was originally that child type
// And C# doesn't let me make implicit cast operators for child types
// So thanks to Microsoft, we've got this horrible implementation using reflection
ConstructorInfo ctor = typeof(T).GetConstructor(types: new System.Type[] { typeof(EGID) });
if (ctor == null)
{
throw new BlockSpecializationException("Specialized block constructor does not accept an EGID");
}
if (sameTick) Sync();
return (T)ctor.Invoke(new object[] { Id });
}
#if DEBUG
public static EntitiesDB entitiesDB
{
get
{
return BlockEngine.GetEntitiesDB();
}
}
#endif
}
} }

View file

@ -9,66 +9,78 @@ using GamecraftModdingAPI.Engines;
namespace GamecraftModdingAPI.Blocks namespace GamecraftModdingAPI.Blocks
{ {
public class BlockEngine : IApiEngine public class BlockEngine : IApiEngine
{ {
public string Name { get; } = "GamecraftModdingAPIBlockGameEngine"; public string Name { get; } = "GamecraftModdingAPIBlockGameEngine";
public EntitiesDB entitiesDB { set; private get; } public EntitiesDB entitiesDB { set; private get; }
public bool isRemovable => false; public bool isRemovable => false;
public void Dispose() public void Dispose()
{ {
} }
public void Ready() public void Ready()
{ {
} }
public Block[] GetConnectedBlocks(EGID blockID) public Block[] GetConnectedBlocks(EGID blockID)
{ {
if (!BlockExists(blockID)) return new Block[0]; if (!BlockExists(blockID)) return new Block[0];
Stack<uint> cubeStack = new Stack<uint>(); Stack<uint> cubeStack = new Stack<uint>();
FasterList<uint> cubesToProcess = new FasterList<uint>(); FasterList<uint> cubesToProcess = new FasterList<uint>();
ConnectedCubesUtility.TreeTraversal.GetConnectedCubes(entitiesDB, blockID.entityID, cubeStack, cubesToProcess, (in GridConnectionsEntityStruct g) => { return false; }); ConnectedCubesUtility.TreeTraversal.GetConnectedCubes(entitiesDB, blockID.entityID, cubeStack, cubesToProcess, (in GridConnectionsEntityStruct g) => { return false; });
var ret = new Block[cubesToProcess.count]; var ret = new Block[cubesToProcess.count];
for (int i = 0; i < cubesToProcess.count; i++) for (int i = 0; i < cubesToProcess.count; i++)
ret[i] = new Block(cubesToProcess[i]); ret[i] = new Block(cubesToProcess[i]);
return ret; return ret;
} }
/// <summary> /// <summary>
/// Get a struct of a block. Can be used to set properties. /// Get a struct of a block. Can be used to set properties.
/// When only querying parameters, use the other overload for convenience. /// When only querying parameters, use the other overload for convenience.
/// </summary> /// </summary>
/// <param name="blockID"></param> /// <param name="blockID"></param>
/// <param name="def"></param> /// <param name="def"></param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public ref T GetBlockInfo<T>(EGID blockID, ref T def) where T : struct, IEntityComponent public ref T GetBlockInfo<T>(EGID blockID, ref T def) where T : struct, IEntityComponent
{ {
if (entitiesDB.Exists<T>(blockID)) if (entitiesDB.Exists<T>(blockID))
return ref entitiesDB.QueryEntity<T>(blockID); return ref entitiesDB.QueryEntity<T>(blockID);
return ref def; return ref def;
} }
/// <summary> /// <summary>
/// Get a struct of a block. Can only be used to retrieve information. /// Get a struct of a block. Can only be used to retrieve information.
/// Use the overload with a default parameter to get the struct by reference to set values. /// Use the overload with a default parameter to get the struct by reference to set values.
/// </summary> /// </summary>
/// <param name="blockID">The block's EGID</param> /// <param name="blockID">The block's EGID</param>
/// <typeparam name="T">The struct's type to get</typeparam> /// <typeparam name="T">The struct's type to get</typeparam>
/// <returns>A copy of the struct or null</returns> /// <returns>A copy of the struct or null</returns>
public T? GetBlockInfo<T>(EGID blockID) where T : struct, IEntityComponent public T? GetBlockInfo<T>(EGID blockID) where T : struct, IEntityComponent
{ {
if (entitiesDB.Exists<T>(blockID)) if (entitiesDB.Exists<T>(blockID))
return entitiesDB.QueryEntity<T>(blockID); return entitiesDB.QueryEntity<T>(blockID);
return null; return null;
} }
public bool BlockExists(EGID id) public bool BlockExists(EGID id)
{ {
return entitiesDB.Exists<DBEntityStruct>(id); return entitiesDB.Exists<DBEntityStruct>(id);
} }
}
public bool GetBlockInfoExists<T>(EGID blockID) where T : struct, IEntityComponent
{
return entitiesDB.Exists<T>(blockID);
}
#if DEBUG
public EntitiesDB GetEntitiesDB()
{
return entitiesDB;
}
#endif
}
} }

View file

@ -0,0 +1,43 @@
using System;
using GamecraftModdingAPI;
namespace GamecraftModdingAPI.Blocks
{
public class BlockException : GamecraftModdingAPIException
{
public BlockException()
{
}
public BlockException(System.String message) : base(message)
{
}
public BlockException(System.String message, Exception innerException) : base(message, innerException)
{
}
}
public class BlockTypeException : BlockException
{
public BlockTypeException()
{
}
public BlockTypeException(string message) : base(message)
{
}
}
public class BlockSpecializationException : BlockException
{
public BlockSpecializationException()
{
}
public BlockSpecializationException(string message) : base(message)
{
}
}
}

View file

@ -0,0 +1,97 @@
using System;
using RobocraftX.Blocks;
using Svelto.ECS;
using Unity.Mathematics;
using GamecraftModdingAPI;
using GamecraftModdingAPI.Utility;
namespace GamecraftModdingAPI.Blocks
{
public class ConsoleBlock : Block
{
public static ConsoleBlock PlaceNew(float3 position,
float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
int uscale = 1, float3 scale = default, Player player = null)
{
if (PlacementEngine.IsInGame && GameState.IsBuildMode())
{
try
{
EGID id = PlacementEngine.PlaceBlock(BlockIDs.ConsoleBlock, color, darkness,
position, uscale, scale, player, rotation);
Sync();
return new ConsoleBlock(id);
}
catch (Exception e)
{
Logging.MetaDebugLog(e);
}
}
return null;
}
public ConsoleBlock(EGID id): base(id)
{
if (!BlockEngine.GetBlockInfoExists<ConsoleBlockEntityStruct>(this.Id))
{
throw new BlockTypeException($"Block is not a {this.GetType().Name} block");
}
}
public ConsoleBlock(uint id): base(id)
{
if (!BlockEngine.GetBlockInfoExists<ConsoleBlockEntityStruct>(this.Id))
{
throw new BlockTypeException($"Block is not a {this.GetType().Name} block");
}
}
// custom console block properties
public string Command
{
get
{
return BlockEngine.GetBlockInfo<ConsoleBlockEntityStruct>(Id)?.commandName ?? null;
}
set
{
BlockEngine.GetBlockInfo<ConsoleBlockEntityStruct>(Id)?.commandName.Set(value);
}
}
public string Arg1
{
get => BlockEngine.GetBlockInfo<ConsoleBlockEntityStruct>(Id)?.arg1 ?? null;
set
{
BlockEngine.GetBlockInfo<ConsoleBlockEntityStruct>(Id)?.arg1.Set(value);
}
}
public string Arg2
{
get => BlockEngine.GetBlockInfo<ConsoleBlockEntityStruct>(Id)?.arg2 ?? null;
set
{
BlockEngine.GetBlockInfo<ConsoleBlockEntityStruct>(Id)?.arg2.Set(value);
}
}
public string Arg3
{
get => BlockEngine.GetBlockInfo<ConsoleBlockEntityStruct>(Id)?.arg3 ?? null;
set
{
BlockEngine.GetBlockInfo<ConsoleBlockEntityStruct>(Id)?.arg3.Set(value);
}
}
}
}

View file

@ -0,0 +1,92 @@
using System;
using Gamecraft.Blocks.GUI;
using Svelto.ECS;
using Unity.Mathematics;
using GamecraftModdingAPI;
using GamecraftModdingAPI.Utility;
namespace GamecraftModdingAPI.Blocks
{
public class TextBlock : Block
{
public static TextBlock PlaceNew(float3 position,
float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
int uscale = 1, float3 scale = default, Player player = null)
{
if (PlacementEngine.IsInGame && GameState.IsBuildMode())
{
try
{
EGID id = PlacementEngine.PlaceBlock(BlockIDs.TextBlock, color, darkness,
position, uscale, scale, player, rotation);
Sync();
return new TextBlock(id);
}
catch (Exception e)
{
Logging.MetaDebugLog(e);
}
}
return null;
}
public TextBlock(EGID id) : base(id)
{
if (!BlockEngine.GetBlockInfoExists<TextBlockDataStruct>(this.Id))
{
throw new BlockTypeException($"Block is not a {this.GetType().Name} block");
}
}
public TextBlock(uint id) : base(id)
{
if (!BlockEngine.GetBlockInfoExists<TextBlockDataStruct>(this.Id))
{
throw new BlockTypeException($"Block is not a {this.GetType().Name} block");
}
}
// custom text block properties
/// <summary>
/// The text block's current text.
/// </summary>
public string Text
{
get
{
return BlockEngine.GetBlockInfo<TextBlockDataStruct>(Id)?.textCurrent ?? null;
}
set
{
TextBlockDataStruct def = default;
ref TextBlockDataStruct tbds = ref BlockEngine.GetBlockInfo<TextBlockDataStruct>(Id, ref def);
tbds.textCurrent.Set(value);
tbds.textStored.Set(value);
BlockEngine.GetBlockInfo<TextBlockNetworkDataStruct>(Id)?.newTextBlockStringContent.Set(value);
}
}
/// <summary>
/// The text block's current text block ID (used in ChangeTextBlockCommand).
/// </summary>
public string TextBlockId
{
get
{
return BlockEngine.GetBlockInfo<TextBlockDataStruct>(Id)?.textBlockID ?? null;
}
set
{
BlockEngine.GetBlockInfo<TextBlockDataStruct>(Id)?.textBlockID.Set(value);
BlockEngine.GetBlockInfo<TextBlockNetworkDataStruct>(Id)?.newTextBlockID.Set(value);
}
}
}
}

View file

@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net472</TargetFramework> <TargetFramework>net472</TargetFramework>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Version>1.0.2</Version> <Version>1.1.0</Version>
<Authors>Exmods</Authors> <Authors>Exmods</Authors>
<PackageLicenseExpression>GNU General Public Licence 3+</PackageLicenseExpression> <PackageLicenseExpression>GNU General Public Licence 3+</PackageLicenseExpression>
<PackageProjectUrl>https://git.exmods.org/modtainers/GamecraftModdingAPI</PackageProjectUrl> <PackageProjectUrl>https://git.exmods.org/modtainers/GamecraftModdingAPI</PackageProjectUrl>

View file

@ -0,0 +1,25 @@
using System;
using RobocraftX.StateSync;
using Svelto.ECS;
using HarmonyLib;
namespace GamecraftModdingAPI.Utility
{
[HarmonyPatch(typeof(DeterministicStepCompositionRoot), "ResetWorld")]
public static class DeterministicStepCompositionRootPatch
{
private static SimpleEntitiesSubmissionScheduler engineRootScheduler;
public static void Postfix(SimpleEntitiesSubmissionScheduler scheduler)
{
engineRootScheduler = scheduler;
}
internal static void SubmitEntitiesNow()
{
if (engineRootScheduler != null)
engineRootScheduler.SubmitEntities();
}
}
}