Files
LuaCsForBarotraumaEP/Barotrauma/BarotraumaShared/Source/Map/Levels/Ruins/RuinGenerator.cs
T
Joonas Rikkonen 74f32d14d4 e08c5e7...2ad9b5d
commit 2ad9b5de40f128e8413f1ad5f568a4bc006d0971
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 20:11:41 2019 +0200

    v0.8.9.3

commit 2d64da9d1e0d10f9ccb08d6e3fbc45d69fcda368
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 18:08:10 2019 +0200

    Randomize the races and the heads in the net lobby. TODO: remember the previous heads and check that the next in line is unique (not exactly the same as the current).

commit 09f74ab37692291ca070bac5dbc53eef395fb1cf
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 16:30:16 2019 +0200

    AI characters can give treatment to characters who aren't unconscious, fixed AI characters attempting to treat dead characters. Closes #1083

commit a8fea2450cf4ef0b80a8fc809aee339bc39b28c6
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 16:28:23 2019 +0200

    Fixed horizontal docking ports failing to find the hull prefab

commit dd5a7a4f09195ecfeb82605e1e73ea22607694e7
Author: ezjamsen <ezjames.fi@gmail.com>
Date:   Wed Feb 6 16:02:52 2019 +0200

    halved the hitpoints for baby moloch

commit 92ae260558ece991560d83819168ef51d5267a66
Merge: 75fe087d7 8f451825e
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 15:44:08 2019 +0200

    Merge branch 'dev' of https://github.com/Regalis11/Barotrauma into dev

commit 75fe087d7263b46611fb0aad5c91c616e22ad41b
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 15:43:12 2019 +0200

    Update the ai block in the moloch boss config file.

commit caf11944294dfe66b5d302888baecbfddad7293a
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 15:42:42 2019 +0200

    Remove the lowercase version of the moloch boss config file.

commit b422feece1e620c427fa62d41c2b847b6b8837e9
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 15:41:40 2019 +0200

    Fix molochbaby character name in the config file.

commit 913762516dd17921c185de2cb912333f2e5230dd
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 15:41:22 2019 +0200

    Include the baby moloch files in the project.

commit 8f451825e95b415b1262f984d83828c379d36ea2
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 15:36:50 2019 +0200

    Added molochbaby to the project file

commit 2078307f255f432c19fcbbc0b690acf5655f3c99
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 15:33:08 2019 +0200

    Disable creating humanoids in the wizard for now, because it can go wrong in so many ways.

commit 55a931795ac5f60699033c4ff484a9a2d0ae9b7e
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 15:32:18 2019 +0200

    Unfreeze when adjusting the joint scale, because the limbs are not otherwise updated to the joint positions.

commit 2c92373ccbf331c545c830c9780f450b116f0359
Author: Iiro Enges <iiro@fakefish.fi>
Date:   Wed Feb 6 15:28:22 2019 +0200

    Tinted baby moloch to differentiate from the adult version (for testing purposes)

commit f05be351cdf8a6073702e988ed1861f665399048
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 15:26:52 2019 +0200

    Fixed automatic temperature control setting turbine output above 100 if the power consumption is higher than what the reactor can generate. Caused "failed to write an event for the entity" errors in MP when the server tried to write the targetTurbineOutput using WriteRangedSingle with a maximum value of 100. Closes #1085

commit 7b737ebbea41fd5b7825a6c6373e578c1b1c91fd
Author: ezjamsen <ezjames.fi@gmail.com>
Date:   Wed Feb 6 15:15:59 2019 +0200

    Baby moloch, doo doo doo doo doo doo

commit f5d13649915ba761bbc6fe78370c607905e2d5f8
Author: ezjamsen <ezjames.fi@gmail.com>
Date:   Wed Feb 6 15:15:04 2019 +0200

    Small fixes and tweaks to gun performance dependent on skill of user.

commit 4bf61738c6da08d771dedf1c96160cc76e0b4dd7
Author: ezjamsen <ezjames.fi@gmail.com>
Date:   Wed Feb 6 15:14:11 2019 +0200

    New staggered swarm medium difficulty event

commit 3e593f46850987ba074d9b26d59d08eeeddd1d70
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 15:05:43 2019 +0200

    Removed incorrect item name/description instructions fron EnglishVanilla.xml. Correct instructions are at the beginning of the file.

commit ce33a523e440a5b5037b84ca96bebf1f977e0aa8
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 15:00:48 2019 +0200

    Attempt to fix "attempted to move pull joint extremely far" errors (#895). I think they were (at least for the most part) caused by characters switching to simple physics mode and then moving a significant distance, and when the character switched back to normal animation, the pull joints were still somewhere far away and lerping them to the position of the collider failed (because the lerped position triggers the error).

commit c8212e3eff6d9272c9d38b833743b0f33b3611a2
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 13:54:15 2019 +0200

    Fixed nullref exception when teleporting from a sub to ruins or vice versa. Closes #1037

commit 0d812394944eb05be4291be7b56593cc4def6d0f
Author: Daniel Asteljoki <daniel.asteljoki@gmail.com>
Date:   Wed Feb 6 13:34:58 2019 +0200

    Made regular ruin walls much more durable (500 -> 5000)

commit c9a4d9d6f6c9c767ecd8cf34f917db9da852f4bf
Author: Daniel Asteljoki <daniel.asteljoki@gmail.com>
Date:   Wed Feb 6 13:34:26 2019 +0200

    Rebalanced Humpback battery grid, added toggles for using backup power

commit 47617a6d54f933714dffeca5fa311776e9d0523c
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 13:17:57 2019 +0200

    Remove the lowercase variant of moloch's config file from the source control.

commit 640662835684464e4a66b106b1958e5a9fde8a0c
Merge: 80e91f96b 7861d00a6
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 13:10:00 2019 +0200

    Merge branch 'dev' of https://github.com/Regalis11/Barotrauma into dev

commit 80e91f96bf5f1e9f89c5a6e4695292298a802b06
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 13:09:37 2019 +0200

    Fix a null reference exception.

commit 91b16aaa7aacc658cb36325ea85944802166ef53
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 13:09:26 2019 +0200

    Instead of having a bad sight, make the Hammerhead deaf. Add "provocative" priority tag, remove "sonar". Make slightly less aggressive towards weaker.

commit a383c136f6f6915163e98c472ec7ba7f575ea479
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 13:02:00 2019 +0200

    Add "provocative" tag on Moloch and Mudraptor targeting priorities. Tweak moloch priorities a bit.

commit 7861d00a609f2555a19f510d72591bd0330f607e
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 12:53:37 2019 +0200

    Attempt to fix/diagnose "collection was modified; enumeration operation may not execute" exceptions when using the fixhulls command (see #1011). Haven't been able to reproduce this issue.

commit 1d1321c60e8815b3beaffb81bfb9c5f5c2528297
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 12:52:29 2019 +0200

    Add "provocative" tag that can be used as a red flag for the monsters. Add the tag on the diving scooter. Also add an ai target with sound ranges.

commit 8530f4c9e4b1c444687cadbf615a9ade0440262b
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 12:50:43 2019 +0200

    Propulsion can now make sound that attracts the enemies. The sound is on when the propulsion is active.

commit 291f12676e5148da1a83d4dd72071381c1ae73e3
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 12:49:39 2019 +0200

    If a target item is held by a character, attack the character instead.

commit 2aeaa9eaa51f3ed3db71f7853efef37bf5998838
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 12:46:27 2019 +0200

    Allow to define min and max sound ranges.

commit 3bf5d2383cbcc33fa862a79c06756e6d9f20a753
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 12:42:57 2019 +0200

    Adjust the ai debug info.

commit 369355ffef340875335c0d81d9a2c9a4bfac898b
Author: EdusFF <pitkanen.eetu@gmail.com>
Date:   Wed Feb 6 12:40:30 2019 +0200

    ContextualTutorial Update cleanup

commit 101387adc1308ad87e3134ab2960d3032f725735
Author: EdusFF <pitkanen.eetu@gmail.com>
Date:   Wed Feb 6 12:34:07 2019 +0200

    Formatting

commit cc44eff21d57d93e4b0a67249af2135e5782e3c3
Merge: 9a338a2d4 33d1cd1be
Author: EdusFF <pitkanen.eetu@gmail.com>
Date:   Wed Feb 6 12:31:54 2019 +0200

    Merge branch 'dev' of https://github.com/Regalis11/Barotrauma into dev

commit 9a338a2d440ff12426171fe9c3121efb934b6803
Author: EdusFF <pitkanen.eetu@gmail.com>
Date:   Wed Feb 6 12:31:50 2019 +0200

    Modified: ContextualTutorial dismissal logic to use buttons instead of the press any key logic

commit 33d1cd1beb61862a91bce16ebeb5090a8969cf1b
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 12:07:21 2019 +0200

    Fixed spectate button staying disabled if starting a round fails (due to a missing sub file for example). Closes #1066

commit 8935825146203725759463278e7776a42d84a6a0
Merge: 2cdc96214 9fd3de63b
Author: EdusFF <pitkanen.eetu@gmail.com>
Date:   Wed Feb 6 11:45:06 2019 +0200

    Merge branch 'dev' of https://github.com/Regalis11/Barotrauma into dev

commit 2cdc96214e2285bfa83a566ed8bc2aed4156c31d
Author: EdusFF <pitkanen.eetu@gmail.com>
Date:   Wed Feb 6 11:44:56 2019 +0200

    Added: Saving of the download size to the Workshop.Item, allows displaying the file size for non-downloaded content in SteamWorshopScreen. Closes #1052

commit 9fd3de63bc08e06a924bf5ec8a8b2938a647282f
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 11:34:38 2019 +0200

    Watchmen cannot be dragged or grabbed, fixed watchmen imploding continuously if they end up outside. Closes #1072

commit eb3fca43d77e79f04e0ae80daac53b7e2c1e37f7
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 11:14:06 2019 +0200

    Fixed server not sending PowerContainer events until the charge of the PowerContainer has changed by more then 100% (i.e. never). Closes #1068

commit 5b3b71bab75489714f72ce55621f6da7d5ec8d94
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 10:59:09 2019 +0200

    Prevent locations from being generated too close to each other. Closes #1048

commit b032b36a50b60432f565cab0178de749585562ad
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Wed Feb 6 10:48:43 2019 +0200

    Fixed a couple of errors in the translation instructions in EnglishVanilla.xml

commit a31b2f257ef863f2cdd1504a3a15356f95262225
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Wed Feb 6 09:34:11 2019 +0200

    Show inventory icons in the sprite editor.

commit fb7a69d6179824dde0a44d27ce5143a1a25d0147
Author: Roni Kovaniemi <roni.kovaniemi@gmail.com>
Date:   Wed Feb 6 02:18:44 2019 +0200

    Improved background smoke texture

commit 888e86a0e7d6e6a70feb2b87ea16cee17adcfd76
Author: Juan Pablo Arce <juanjp600@users.noreply.github.com>
Date:   Tue Feb 5 11:36:06 2019 -0300

    whoops strikes again

commit 67e94c6bb9e59b20bc1b9f3cb796780d1c2141f7
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Tue Feb 5 16:32:45 2019 +0200

    Adjust the min and max values for the sight range and add a todo note.

commit ad0becdf175a66c963b2cbea5259b435c250ffa6
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Tue Feb 5 16:31:47 2019 +0200

    Refactor the sound range calculation. It was way off.

commit adc0aa96be5426dbb845e4138acab87c44c935ba
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Tue Feb 5 16:31:18 2019 +0200

    Improve the ai target debug info.

commit 9230ba0865896d5740898993ab3389659a4cbb4a
Author: Juan Pablo Arce <juanjp600@users.noreply.github.com>
Date:   Tue Feb 5 10:53:51 2019 -0300

    Attempted audio buffer queue fix

commit dfbc61628de37a60acbaa208934957a9d892eb99
Author: Eetu <pitkanen.eetu@gmail.com>
Date:   Tue Feb 5 15:18:34 2019 +0200

    Fixed: Rubber ducks not floating like a good duck should

commit 8b8523dad99b5c1db271ac13e48975487a7c7c99
Merge: 509c67594 c0156c3d3
Author: Eetu <pitkanen.eetu@gmail.com>
Date:   Tue Feb 5 14:34:59 2019 +0200

    Merge branch 'dev' of https://github.com/Regalis11/Barotrauma into dev

commit 509c6759484750d44a154a7f1703f92d0d6e1692
Author: Eetu <pitkanen.eetu@gmail.com>
Date:   Tue Feb 5 14:34:53 2019 +0200

    Fixed: Holdable items retaining their pushing ability even when the user is stunned or unconscious. Closes #1061

commit c0156c3d350b64309c8068f437ddd57765f0b911
Author: itchyOwl <lauri.harkanen@gmail.com>
Date:   Tue Feb 5 13:46:32 2019 +0200

    If no limb is selected, select the limb with the most critical affliction. Re-evaluate when new affliction is received. Sort afflictions so that dmg/sec is prioritized. Implements the feature request #1033.

commit 4a056c6e9b78f3d6f43574b1b9ff5493d36565b0
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Tue Feb 5 13:25:57 2019 +0200

    Fixed order messages not being visible in single player if the character issuing the order has no headset. Closes #1030

commit 357b14fb4f4b1a56a04d192c17a2ce8e0ab7405e
Author: ezjamsen <ezjames.fi@gmail.com>
Date:   Tue Feb 5 12:52:40 2019 +0200

    new load tips

commit 1f158760e1ed79968f10647c0a2931d2c603281e
Author: ezjamsen <ezjames.fi@gmail.com>
Date:   Tue Feb 5 12:52:20 2019 +0200

    minor formatting tweak to xml

commit c53438151043174e18fbfe979ac3b3b862d24255
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Tue Feb 5 12:48:47 2019 +0200

    Stop Steam auth session of a client when they disconnect. Probably fixes servers reporting incorrect player counts (#1049)?

commit 2073b170e4fdd5cedd998ff9d01f37842995194b
Merge: 9914631c7 9b912a7bf
Author: Eetu <pitkanen.eetu@gmail.com>
Date:   Tue Feb 5 12:43:05 2019 +0200

    Merge branch 'dev' of https://github.com/Regalis11/Barotrauma into dev

commit 9914631c7eb30c02913cd4ed44f7b7827169ad83
Author: Eetu <pitkanen.eetu@gmail.com>
Date:   Tue Feb 5 12:42:53 2019 +0200

    Fixed: Fabricator allowing new items to be created when the output is not empty, resulting in wasted materials.

commit 9b912a7bf16bd121bbe8b7eae20f4a253a9e1eba
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Tue Feb 5 12:33:00 2019 +0200

    Fixed LOS effect not working on ruins when looking at them from inside a sub

commit aeaf190c6d3b45d4d12654926acbe223dc4f5888
Author: Joonas Rikkonen <poe.regalis@gmail.com>
Date:   Tue Feb 5 11:57:17 2019 +0200

    Pressing the radio chat hotkey doesn't deselect the chatbox. Closes #1044
2019-03-18 21:12:20 +02:00

1309 lines
58 KiB
C#

using FarseerPhysics;
using FarseerPhysics.Factories;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Voronoi2;
using Barotrauma.Extensions;
using Barotrauma.Items.Components;
namespace Barotrauma.RuinGeneration
{
abstract class RuinShape
{
protected Rectangle rect;
public Rectangle Rect
{
get { return rect; }
}
public int DistanceFromEntrance
{
get;
set;
}
public Vector2 Center
{
get { return rect.Center.ToVector2(); }
}
public RuinRoom RoomType;
public List<Line> Walls;
public virtual void CreateWalls() { }
public Alignment GetLineAlignment(Line line)
{
if (line.IsHorizontal)
{
if (line.A.Y > rect.Center.Y && line.B.Y > rect.Center.Y)
{
return Alignment.Bottom;
}
else if (line.A.Y < rect.Center.Y && line.B.Y < rect.Center.Y)
{
return Alignment.Top;
}
}
else
{
if (line.A.X < rect.Center.X && line.B.X < rect.Center.X)
{
return Alignment.Left;
}
else if (line.A.X > rect.Center.X && line.B.X > rect.Center.X)
{
return Alignment.Right;
}
}
return Alignment.Center;
}
/// <summary>
/// Goes through all the walls of the ruin shape and clips off parts that are inside the rectangle
/// </summary>
public void SplitWalls(Rectangle rectangle)
{
List<Line> newLines = new List<Line>();
foreach (Line line in Walls)
{
if (!line.IsHorizontal) //vertical line
{
//line doesn't intersect the rectangle
if (rectangle.X > line.A.X || rectangle.Right < line.A.X ||
rectangle.Y > line.B.Y || rectangle.Bottom < line.A.Y)
{
newLines.Add(line);
}
//line completely inside the rectangle, no need to create a wall at all
else if (line.A.Y >= rectangle.Y && line.B.Y <= rectangle.Bottom)
{
continue;
}
//point A is within the rectangle -> cut a portion from the top of the line
else if (line.A.Y >= rectangle.Y && line.A.Y <= rectangle.Bottom)
{
newLines.Add(new Line(new Vector2(line.A.X, rectangle.Bottom), line.B));
}
//point B is within the rectangle -> cut a portion from the bottom of the line
else if (line.B.Y >= rectangle.Y && line.B.Y <= rectangle.Bottom)
{
newLines.Add(new Line(line.A, new Vector2(line.A.X, rectangle.Y)));
}
//rect is in between the lines -> split the line into two
else
{
newLines.Add(new Line(line.A, new Vector2(line.A.X, rectangle.Y)));
newLines.Add(new Line(new Vector2(line.A.X, rectangle.Bottom), line.B));
}
}
else
{
//line doesn't intersect the rectangle
if (rectangle.X > line.B.X || rectangle.Right < line.A.X ||
rectangle.Y > line.A.Y || rectangle.Bottom < line.A.Y)
{
newLines.Add(line);
}
else if (line.A.X >= rectangle.X && line.B.X <= rectangle.Right)
{
continue;
}
//point A is within the rectangle -> cut a portion from the left side of the line
else if (line.A.X >= rectangle.X && line.A.X <= rectangle.Right)
{
newLines.Add(new Line(new Vector2(rectangle.Right, line.A.Y), line.B));
}
//point B is within the rectangle -> cut a portion from the right side of the line
else if (line.B.X >= rectangle.X && line.B.X <= rectangle.Right)
{
newLines.Add(new Line(line.A, new Vector2(rectangle.X, line.A.Y)));
}
//rect is in between the lines -> split the line into two
else
{
newLines.Add(new Line(line.A, new Vector2(rectangle.X, line.A.Y)));
newLines.Add(new Line(new Vector2(rectangle.Right, line.A.Y), line.B));
}
}
}
Walls = newLines;
}
public void MirrorX(Vector2 mirrorOrigin)
{
rect.X = (int)(mirrorOrigin.X + (mirrorOrigin.X - rect.Right));
for (int i = 0; i < Walls.Count; i++)
{
Walls[i].A = new Vector2(mirrorOrigin.X + (mirrorOrigin.X - Walls[i].A.X), Walls[i].A.Y);
Walls[i].B = new Vector2(mirrorOrigin.X + (mirrorOrigin.X - Walls[i].B.X), Walls[i].B.Y);
if (Walls[i].B.X < Walls[i].A.X)
{
var temp = Walls[i].A.X;
Walls[i].A.X = Walls[i].B.X;
Walls[i].B.X = temp;
}
}
}
}
class Line
{
public Vector2 A, B;
public float Radius;
public bool IsHorizontal
{
get { return Math.Abs(A.Y - B.Y) < Math.Abs(A.X - B.X); }
}
public Line(Vector2 a, Vector2 b)
{
Debug.Assert(a.X <= b.X);
Debug.Assert(a.Y <= b.Y);
A = a;
B = b;
}
}
partial class Ruin
{
private List<BTRoom> rooms;
private List<Corridor> corridors;
private List<Line> walls;
private List<RuinShape> allShapes;
private RuinGenerationParams generationParams;
private BTRoom entranceRoom;
private List<RuinEntity> ruinEntities = new List<RuinEntity>();
private List<Door> doors = new List<Door>();
public IEnumerable<RuinEntity> RuinEntities
{
get { return ruinEntities; }
}
public List<RuinShape> RuinShapes
{
get { return allShapes; }
}
public List<Line> Walls
{
get { return walls; }
}
public Rectangle Area
{
get;
private set;
}
public Ruin(VoronoiCell closestPathCell, List<VoronoiCell> caveCells, RuinGenerationParams generationParams, Rectangle area, bool mirror = false)
{
this.generationParams = generationParams;
Area = area;
corridors = new List<Corridor>();
rooms = new List<BTRoom>();
walls = new List<Line>();
allShapes = new List<RuinShape>();
Generate(closestPathCell, caveCells, area, mirror);
}
public void Generate(VoronoiCell closestPathCell, List<VoronoiCell> caveCells, Rectangle area, bool mirror = false)
{
corridors.Clear();
rooms.Clear();
int iterations = Rand.Range(generationParams.RoomDivisionIterationsMin, generationParams.RoomDivisionIterationsMax, Rand.RandSync.Server);
float verticalProbability = generationParams.VerticalSplitProbability;
BTRoom baseRoom = new BTRoom(area);
rooms = new List<BTRoom> { baseRoom };
for (int i = 0; i < iterations; i++)
{
rooms.ForEach(l => l.Split(0.3f, verticalProbability, generationParams.MinSplitWidth));
rooms = baseRoom.GetLeaves();
}
foreach (BTRoom leaf in rooms)
{
leaf.Scale
(
new Vector2(
Rand.Range(generationParams.RoomWidthRange.X, generationParams.RoomWidthRange.Y, Rand.RandSync.Server),
Rand.Range(generationParams.RoomHeightRange.X, generationParams.RoomHeightRange.Y, Rand.RandSync.Server))
);
}
baseRoom.GenerateCorridors(generationParams.CorridorWidthRange.X, generationParams.CorridorWidthRange.Y, corridors);
walls = new List<Line>();
rooms.ForEach(leaf => { leaf.CreateWalls(); });
//---------------------------
float shortestDistance = 0.0f;
foreach (BTRoom leaf in rooms)
{
Vector2 leafPos = leaf.Rect.Center.ToVector2();
if (mirror)
{
leafPos.X = area.Center.X + (area.Center.X - leafPos.X);
}
float distance = Vector2.Distance(leafPos, closestPathCell.Center);
if (entranceRoom == null || distance < shortestDistance)
{
entranceRoom = leaf;
shortestDistance = distance;
}
}
rooms.Remove(entranceRoom);
//---------------------------
foreach (BTRoom leaf in rooms)
{
foreach (Corridor corridor in corridors)
{
leaf.SplitWalls(corridor.Rect);
}
walls.AddRange(leaf.Walls);
}
foreach (Corridor corridor in corridors)
{
corridor.CreateWalls();
foreach (BTRoom leaf in rooms)
{
corridor.SplitWalls(leaf.Rect);
}
foreach (Corridor corridor2 in corridors)
{
if (corridor == corridor2) continue;
corridor.SplitWalls(corridor2.Rect);
}
walls.AddRange(corridor.Walls);
}
BTRoom.CalculateDistancesFromEntrance(entranceRoom, rooms, corridors);
GenerateRuinEntities(caveCells, area, mirror);
}
public class RuinEntity
{
public readonly RuinEntityConfig Config;
public readonly MapEntity Entity;
public readonly MapEntity Parent;
public readonly RuinShape Room;
public RuinEntity(RuinEntityConfig config, MapEntity entity, RuinShape room, MapEntity parent = null)
{
Config = config;
Entity = entity;
Room = room;
Parent = parent;
}
}
private void GenerateRuinEntities(List<VoronoiCell> caveCells, Rectangle ruinArea, bool mirror)
{
var entityGrid = Hull.GenerateEntityGrid(new Rectangle(ruinArea.X, ruinArea.Y + ruinArea.Height, ruinArea.Width, ruinArea.Height));
doors.Clear();
allShapes = new List<RuinShape>(rooms);
allShapes.AddRange(corridors);
if (mirror)
{
foreach (RuinShape shape in allShapes)
{
shape.MirrorX(ruinArea.Center.ToVector2());
}
}
int maxRoomDistanceFromEntrance = rooms.Max(s => s.DistanceFromEntrance);
int maxCorridorDistanceFromEntrance = corridors.Max(s => s.DistanceFromEntrance);
//assign the room types for the first and last rooms
foreach (RuinRoom roomType in generationParams.RoomTypeList)
{
RuinShape selectedRoom = null;
switch (roomType.Placement)
{
case RuinRoom.RoomPlacement.First:
//find the room nearest to the entrance
//there may be multiple ones, choose one that hasn't been assigned yet
selectedRoom = roomType.IsCorridor ? FindFirstRoom(corridors, r => r.RoomType == null) : FindFirstRoom(rooms, r => r.RoomType == null);
break;
case RuinRoom.RoomPlacement.Last:
//find the room furthest to the entrance
//there may be multiple ones, choose one that hasn't been assigned yet
selectedRoom = roomType.IsCorridor ? FindLastRoom(corridors, r => r.RoomType == null) : FindLastRoom(rooms, r => r.RoomType == null);
break;
}
if (selectedRoom == null) continue;
//step forwards/backwards from the selected room according to the placement offset
for (int i = 0; i < Math.Abs(roomType.PlacementOffset); i++)
{
selectedRoom = FindNearestRoom(
selectedRoom,
roomType.IsCorridor ? corridors : (IEnumerable<RuinShape>)rooms,
roomType.PlacementOffset,
r => r.RoomType == null);
}
if (selectedRoom != null) selectedRoom.RoomType = roomType;
}
//go through the unassigned rooms
foreach (RuinShape room in allShapes)
{
if (room.RoomType != null) continue;
room.RoomType = generationParams.RoomTypeList.GetRandom(rt =>
rt.IsCorridor == room is Corridor &&
rt.Placement == RuinRoom.RoomPlacement.Any,
Rand.RandSync.Server);
if (room.RoomType == null)
{
DebugConsole.ThrowError("Could not find a suitable room type for a room (is corridor: " + (room is Corridor) + ")");
}
}
List<Rectangle> hullRects = new List<Rectangle>(allShapes.Select(s => s.Rect));
//split intersecting hulls into multiple parts to prevent overlaps
for (int i = 0; i < hullRects.Count; i++)
{
if (hullRects[i].Width <= 0 || hullRects[i].Height <= 0) continue;
for (int j = 0; j < hullRects.Count; j++)
{
if (i == j) continue;
if (hullRects[j].Width <= 0 || hullRects[j].Height <= 0) continue;
if (!hullRects[i].Intersects(hullRects[j])) continue;
//hull i goes through hull j vertically
if (hullRects[i].X >= hullRects[j].X && hullRects[i].Right <= hullRects[j].Right &&
hullRects[i].Y <= hullRects[j].Y && hullRects[i].Bottom >= hullRects[j].Bottom)
{
Rectangle rectLeft = new Rectangle(hullRects[j].X, hullRects[j].Y, hullRects[i].X - hullRects[j].X, hullRects[j].Height);
Rectangle rectRight = new Rectangle(hullRects[i].Right, hullRects[j].Y, hullRects[j].Right - hullRects[i].Right, hullRects[j].Height);
hullRects[j] = rectLeft;
hullRects.Add(rectRight);
}
else if //hull i goes through hull j horizontally
(hullRects[i].Y >= hullRects[j].Y && hullRects[i].Bottom <= hullRects[j].Bottom &&
hullRects[i].X <= hullRects[j].X && hullRects[i].Right >= hullRects[j].Right)
{
Rectangle rectBottom = new Rectangle(hullRects[j].X, hullRects[j].Y, hullRects[j].Width, hullRects[i].Y - hullRects[j].Y);
Rectangle rectTop = new Rectangle(hullRects[j].X, hullRects[i].Bottom, hullRects[j].Width, hullRects[j].Bottom - hullRects[i].Bottom);
hullRects[j] = rectBottom;
hullRects.Add(rectTop);
}
//upper side of hull i is inside hull j
else if (hullRects[j].Contains(hullRects[i].Location) && hullRects[j].Contains(new Vector2(hullRects[i].Right, hullRects[i].Y)))
{
hullRects[i] = new Rectangle(hullRects[i].X, hullRects[j].Bottom, hullRects[i].Width, hullRects[i].Bottom - hullRects[j].Bottom);
}
//lower side of hull i is inside hull j
else if (hullRects[j].Contains(new Vector2(hullRects[i].X, hullRects[i].Bottom)) && hullRects[j].Contains(new Vector2(hullRects[i].Right, hullRects[i].Bottom)))
{
hullRects[i] = new Rectangle(hullRects[i].X, hullRects[i].Y, hullRects[i].Width, hullRects[j].Y - hullRects[i].Y);
}
//left side of hull i is inside hull j
else if (hullRects[j].Contains(hullRects[i].Location) && hullRects[j].Contains(new Vector2(hullRects[i].X, hullRects[i].Bottom)))
{
hullRects[i] = new Rectangle(hullRects[j].X, hullRects[i].Y, hullRects[i].Right - hullRects[j].X, hullRects[i].Height);
}
//right side of hull i is inside hull j
else if (hullRects[j].Contains(new Vector2(hullRects[i].Right, hullRects[i].Y)) && hullRects[j].Contains(new Vector2(hullRects[i].Right, hullRects[i].Bottom)))
{
hullRects[i] = new Rectangle(hullRects[i].X, hullRects[i].Y, hullRects[j].X - hullRects[i].X, hullRects[i].Height);
}
}
}
foreach (RuinShape room in allShapes)
{
if (room.RoomType == null) continue;
//generate walls --------------------------------------------------------------
foreach (Line wall in room.Walls)
{
var ruinEntityConfig = room.RoomType.GetRandomEntity(RuinEntityType.Wall, room.GetLineAlignment(wall));
if (ruinEntityConfig == null) continue;
wall.Radius = (wall.A.X == wall.B.X) ?
(ruinEntityConfig.Prefab as StructurePrefab).Size.X * 0.5f :
(ruinEntityConfig.Prefab as StructurePrefab).Size.Y * 0.5f;
Rectangle rect = new Rectangle(
(int)(wall.A.X - wall.Radius),
(int)(wall.B.Y + wall.Radius),
(int)((wall.B.X - wall.A.X) + wall.Radius * 2.0f),
(int)((wall.B.Y - wall.A.Y) + wall.Radius * 2.0f));
//cut a section off from both ends of a horizontal wall to get nicer looking corners
if (wall.A.Y == wall.B.Y)
{
rect.Inflate(-32, 0);
if (rect.Width < Submarine.GridSize.X) continue;
}
var structure = new Structure(rect, ruinEntityConfig.Prefab as StructurePrefab, null)
{
ShouldBeSaved = false
};
structure.SetCollisionCategory(Physics.CollisionLevel);
CreateChildEntities(ruinEntityConfig, structure, room);
ruinEntities.Add(new RuinEntity(ruinEntityConfig, structure, room));
}
//generate backgrounds --------------------------------------------------------------
var backgroundConfig = room.RoomType.GetRandomEntity(RuinEntityType.Back, Alignment.Center);
if (backgroundConfig != null)
{
Rectangle backgroundRect = new Rectangle(room.Rect.X, room.Rect.Y + room.Rect.Height, room.Rect.Width, room.Rect.Height);
var backgroundStructure = new Structure(backgroundRect, (backgroundConfig.Prefab as StructurePrefab), null)
{
ShouldBeSaved = false
};
CreateChildEntities(backgroundConfig, backgroundStructure, room);
ruinEntities.Add(new RuinEntity(backgroundConfig, backgroundStructure, room));
}
var submarineBlocker = BodyFactory.CreateRectangle(GameMain.World,
ConvertUnits.ToSimUnits(room.Rect.Width),
ConvertUnits.ToSimUnits(room.Rect.Height),
1, ConvertUnits.ToSimUnits(room.Center));
submarineBlocker.IsStatic = true;
submarineBlocker.CollisionCategories = Physics.CollisionWall;
submarineBlocker.CollidesWith = Physics.CollisionWall;
//generate doors --------------------------------------------------------------
if (room is Corridor corridor)
{
var doorConfig = room.RoomType.GetRandomEntity(corridor.IsHorizontal ? RuinEntityType.Door : RuinEntityType.Hatch, Alignment.Center);
if (corridor != null && doorConfig != null)
{
//find all walls that are parallel to the corridor
var suitableWalls = corridor.IsHorizontal ?
corridor.Walls.FindAll(c => c.A.Y == c.B.Y) : corridor.Walls.FindAll(c => c.A.X == c.B.X);
if (suitableWalls.Any())
{
//choose a random wall to place the door next to
Vector2 doorPos = corridor.Center;
var wall = suitableWalls[Rand.Int(suitableWalls.Count, Rand.RandSync.Server)];
if (corridor.IsHorizontal)
{
doorPos.X = (wall.A.X + wall.B.X) / 2.0f;
}
else
{
doorPos.Y = (wall.A.Y + wall.B.Y) / 2.0f;
}
Item doorItem = null;
if (doorConfig.Prefab is ItemPrefab itemPrefab)
{
doorItem = new Item(doorConfig.Prefab as ItemPrefab, doorPos, null)
{
ShouldBeSaved = false
};
}
else if (doorConfig.Prefab is ItemAssemblyPrefab itemAssemblyPrefab)
{
var entities = itemAssemblyPrefab.CreateInstance(doorPos, sub: null);
foreach (MapEntity e in entities)
{
if (e is Structure) e.ShouldBeSaved = false;
if (doorItem == null && e is Item item && item.GetComponent<Door>() != null)
{
doorItem = item;
}
else
{
ruinEntities.Add(new RuinEntity(doorConfig, e, room));
}
}
if (doorConfig.Expand) { ExpandEntities(entities); }
//make sure the door gets positioned at the correct place regardless of its position in the item assembly
if (doorItem != null)
{
Vector2 doorOffset = doorPos - doorItem.WorldPosition;
foreach (MapEntity e in entities)
{
e.Move(doorOffset);
}
}
}
else
{
DebugConsole.ThrowError("Failed to create a ruin door. Ruin entity \"" + doorConfig.Name + "\" is marked as a door but is neither an item or an item assembly.");
continue;
}
Door door = doorItem?.GetComponent<Door>();
if (door == null)
{
DebugConsole.ThrowError("Failed to create a ruin door. Door not found in the ruin entity \"" + doorConfig.Name + "\".");
continue;
}
CreateChildEntities(doorConfig, doorItem, corridor);
doors.Add(door);
ruinEntities.Add(new RuinEntity(doorConfig, doorItem, room));
}
}
}
//generate props --------------------------------------------------------------
var props = room.RoomType.GetPropList(room, Rand.RandSync.Server);
foreach (RuinEntityConfig prop in props)
{
int amount = Rand.Range(prop.MinAmount, prop.MaxAmount + 1, Rand.RandSync.Server);
for (int i = 0; i < amount; i++)
{
CreateEntity(prop, room, parent: null);
}
}
}
foreach (RuinEntity entity in ruinEntities)
{
if (!entity.Room.RoomType.IsCorridor) { continue; }
Item item = entity.Entity as Item;
Door door = item?.GetComponent<Door>();
if (door == null) { continue; }
//split the hull the door is inside
for (int i = 0; i < hullRects.Count; i++)
{
Vector2 doorPos = door.Item.WorldPosition;
if (!hullRects[i].Contains(doorPos)) continue;
if (door.IsHorizontal)
{
Rectangle rectBottom = new Rectangle(hullRects[i].X, hullRects[i].Y, hullRects[i].Width, (int)doorPos.Y - hullRects[i].Y);
Rectangle rectTop = new Rectangle(hullRects[i].X, (int)doorPos.Y, hullRects[i].Width, hullRects[i].Bottom - (int)doorPos.Y);
hullRects[i] = rectBottom;
hullRects.Add(rectTop);
}
else
{
Rectangle rectLeft = new Rectangle(hullRects[i].X, hullRects[i].Y, (int)doorPos.X - hullRects[i].X, hullRects[i].Height);
Rectangle rectRight = new Rectangle((int)doorPos.X, hullRects[i].Y, hullRects[i].Right - (int)doorPos.X, hullRects[i].Height);
hullRects[i] = rectLeft;
hullRects.Add(rectRight);
}
break;
}
}
//randomize door states (20% open on average)
foreach (Door door in doors)
{
door.IsOpen = Rand.Range(0.0f, 1.0f, Rand.RandSync.Server) < 0.2f;
}
//create connections between all generated entities ---------------------------
foreach (RuinEntity ruinEntity in ruinEntities)
{
CreateConnections(ruinEntity);
ruinEntity.Entity.ParentRuin = this;
}
foreach (RuinEntity ruinEntity in ruinEntities)
{
if (ruinEntity.Entity is Item item)
{
foreach (ItemComponent ic in item.components)
{
// Prevent wiring & interacting
if (ic is ConnectionPanel connectionPanel)
{
connectionPanel.Locked = true;
connectionPanel.CanBeSelected = false;
}
// Hide wires for now
if (ic is Wire wire)
{
wire.Hidden = true;
wire.CanBeSelected = false;
}
}
}
}
//create hulls ---------------------------
foreach (Rectangle hullRect in hullRects)
{
if (hullRect.Width <= 0 || hullRect.Height <= 0) continue;
var hull = new Hull(MapEntityPrefab.Find(null, "hull"),
new Rectangle(hullRect.X, hullRect.Y + hullRect.Height, hullRect.Width, hullRect.Height), submarine: null)
{
ParentRuin = this,
ShouldBeSaved = false
};
RuinShape room = allShapes.Find(s => s.Rect.Contains(hullRect.Center));
if (room?.RoomType != null)
{
hull.WaterVolume = hull.Volume * Rand.Range(room.RoomType.MinWaterAmount, room.RoomType.MaxWaterAmount, Rand.RandSync.Server);
}
entityGrid.InsertEntity(hull);
}
//create gaps between hulls ---------------------------
hullRects.Add(entranceRoom.Rect);
for (int i = 0; i < hullRects.Count; i++)
{
if (hullRects[i].Width <= 0 || hullRects[i].Height <= 0) continue;
for (int j = i + 1; j < hullRects.Count; j++)
{
Rectangle? gapRect = null;
if (Math.Abs(hullRects[i].X - hullRects[j].Right) <= 1 && hullYIntersect(hullRects[i], hullRects[j]))
{
gapRect = new Rectangle(
hullRects[i].X - 3, Math.Max(hullRects[i].Y, hullRects[j].Y),
6, Math.Min(hullRects[i].Bottom, hullRects[j].Bottom) - Math.Max(hullRects[i].Y, hullRects[j].Y));
}
else if (Math.Abs(hullRects[i].Right - hullRects[j].X) <= 1 && hullYIntersect(hullRects[i], hullRects[j]))
{
gapRect = new Rectangle(
hullRects[i].Right - 3, Math.Max(hullRects[i].Y, hullRects[j].Y),
6, Math.Min(hullRects[i].Bottom, hullRects[j].Bottom) - Math.Max(hullRects[i].Y, hullRects[j].Y));
}
else if (Math.Abs(hullRects[i].Y - hullRects[j].Bottom) <= 1 && hullXIntersect(hullRects[i], hullRects[j]))
{
gapRect = new Rectangle(
Math.Max(hullRects[i].X, hullRects[j].X), hullRects[i].Y - 3,
Math.Min(hullRects[i].Right, hullRects[j].Right) - Math.Max(hullRects[i].X, hullRects[j].X), 6);
}
else if (Math.Abs(hullRects[i].Bottom - hullRects[j].Y) <= 1 && hullXIntersect(hullRects[i], hullRects[j]))
{
gapRect = new Rectangle(
Math.Max(hullRects[i].X, hullRects[j].X), hullRects[i].Bottom - 3,
Math.Min(hullRects[i].Right, hullRects[j].Right) - Math.Max(hullRects[i].X, hullRects[j].X), 6);
}
if (!gapRect.HasValue || gapRect.Value.Width <= 0 || gapRect.Value.Height <= 0) continue;
//doors create their own gaps, don't create an additional one if there's a door at this
bool doorFound = false;
foreach (Door door in doors)
{
if (Math.Abs(door.Item.WorldPosition.X - gapRect.Value.Center.X) < 5 &&
Math.Abs(door.Item.WorldPosition.Y - gapRect.Value.Center.Y) < 5)
{
doorFound = true;
break;
}
}
if (doorFound) { continue; }
new Gap(new Rectangle(gapRect.Value.X, gapRect.Value.Y + gapRect.Value.Height, gapRect.Value.Width, gapRect.Value.Height),
isHorizontal: gapRect.Value.Height > gapRect.Value.Width, submarine: null)
{
ParentRuin = this,
ShouldBeSaved = false
};
}
}
bool hullXIntersect(Rectangle rect1, Rectangle rect2)
{
return
(rect1.X >= rect2.X && rect1.X <= rect2.Right) ||
(rect2.X >= rect1.X && rect2.X <= rect1.Right);
}
bool hullYIntersect(Rectangle rect1, Rectangle rect2)
{
return
(rect1.Y >= rect2.Y && rect1.Y <= rect2.Bottom) ||
(rect2.Y >= rect1.Y && rect2.Y <= rect1.Bottom);
}
}
private void CreateEntity(RuinEntityConfig entityConfig, RuinShape room, MapEntity parent)
{
if (room == null) return;
int leftWallThickness = 32, rightWallThickness = 32;
int topWallThickness = 32, bottomWallThickness = 32;
foreach (Line wall in room.Walls)
{
if (wall.IsHorizontal)
{
if (wall.A.Y > room.Rect.Center.Y)
bottomWallThickness = (int)wall.Radius;
else
topWallThickness = (int)wall.Radius;
}
else
{
if (wall.A.X > room.Rect.Center.X)
rightWallThickness = (int)wall.Radius;
else
leftWallThickness = (int)wall.Radius;
}
}
Rectangle roomBounds = new Rectangle(
room.Rect.X + leftWallThickness,
room.Rect.Y + bottomWallThickness,
room.Rect.Width - leftWallThickness - rightWallThickness,
room.Rect.Height - topWallThickness - bottomWallThickness);
Vector2 size = Vector2.Zero;
if (entityConfig.Prefab is StructurePrefab structurePrefab)
{
size = structurePrefab.Size;
}
else if (entityConfig.Prefab is ItemPrefab itemPrefab)
{
size = itemPrefab.Size;
}
else if (entityConfig.Prefab is ItemAssemblyPrefab assemblyPrefab)
{
size = new Vector2(assemblyPrefab.Bounds.Width, assemblyPrefab.Bounds.Height);
Vector2 boundsMin = new Vector2(-assemblyPrefab.Bounds.X, -assemblyPrefab.Bounds.Y);
Vector2 boundsMax = new Vector2(assemblyPrefab.Bounds.Right, assemblyPrefab.Bounds.Bottom);
roomBounds = new Rectangle(
(int)(roomBounds.X + boundsMin.X),
(int)(roomBounds.Y + boundsMin.Y),
(int)(roomBounds.Width - boundsMin.X - boundsMax.X),
(int)(roomBounds.Height - boundsMin.Y - boundsMax.Y));
}
List<Vector2> potentialAnchorPositions = new List<Vector2>();
if (entityConfig.Alignment.HasFlag(Alignment.Top))
{
potentialAnchorPositions.Add(new Vector2(roomBounds.Center.X, roomBounds.Bottom));
}
if (entityConfig.Alignment.HasFlag(Alignment.Bottom))
{
potentialAnchorPositions.Add(new Vector2(roomBounds.Center.X, roomBounds.Top));
}
if (entityConfig.Alignment.HasFlag(Alignment.Right))
{
potentialAnchorPositions.Add(new Vector2(roomBounds.Right, roomBounds.Center.Y));
}
if (entityConfig.Alignment.HasFlag(Alignment.Left))
{
potentialAnchorPositions.Add(new Vector2(roomBounds.X, roomBounds.Center.Y));
}
if (entityConfig.Alignment.HasFlag(Alignment.Center) || potentialAnchorPositions.Count == 0)
{
potentialAnchorPositions.Add(roomBounds.Center.ToVector2());
}
Vector2 position = potentialAnchorPositions[Rand.Int(potentialAnchorPositions.Count, Rand.RandSync.Server)];
Vector2 minPosition = new Vector2(
position.X + entityConfig.MinOffset.X * roomBounds.Width,
position.Y + entityConfig.MinOffset.Y * roomBounds.Height);
Vector2 maxPosition = new Vector2(
position.X + entityConfig.MaxOffset.X * roomBounds.Width,
position.Y + entityConfig.MaxOffset.Y * roomBounds.Height);
position = new Vector2(
Rand.Range(minPosition.X, maxPosition.X, Rand.RandSync.Server),
Rand.Range(minPosition.Y, maxPosition.Y, Rand.RandSync.Server));
position.X = MathHelper.Clamp(position.X, roomBounds.X, roomBounds.Right);
position.Y = MathHelper.Clamp(position.Y, roomBounds.Y, roomBounds.Bottom);
int iterations = 0;
while (iterations < 100)
{
bool overlapFound = false;
foreach (RuinEntity ruinEntity in ruinEntities)
{
if (ruinEntity.Config.Type == RuinEntityType.Back || ruinEntity.Config.Type == RuinEntityType.Wall) continue;
Vector2 diff = position - ruinEntity.Entity.Position;
if (Math.Abs(diff.X) < (size.X + ruinEntity.Entity.Rect.Width) / 2 &&
Math.Abs(diff.Y) < (size.Y + ruinEntity.Entity.Rect.Height) / 2)
{
float dist = diff.Length();
Vector2 moveDir = dist < 0.01f ? Vector2.UnitY : diff / dist;
position += moveDir * 100.0f;
position.X = MathHelper.Clamp(position.X, roomBounds.X, roomBounds.Right);
position.Y = MathHelper.Clamp(position.Y, roomBounds.Y, roomBounds.Bottom);
overlapFound = true;
}
}
iterations++;
if (!overlapFound) { break; }
}
MapEntity entity = null;
if (entityConfig.Prefab is ItemPrefab)
{
Item container = null;
if (entityConfig.TargetContainer != "")
{
List<RuinEntity> roomContents = ruinEntities.FindAll(re => re.Room == room);
for (int j = 0; j < roomContents.Count; j++)
{
if (roomContents[j].Entity is Item && (roomContents[j].Entity as Item).HasTag(entityConfig.TargetContainer))
{
container = roomContents[j].Entity as Item;
break;
}
}
if (container == null) DebugConsole.ThrowError("No container with tag \"" + entityConfig.TargetContainer + "\" found, placing item in the room");
}
if (container != null)
{
entity = new Item((ItemPrefab)entityConfig.Prefab, container.Position, null);
if (container.OwnInventory.TryPutItem(entity as Item, null, createNetworkEvent: false))
{
CreateChildEntities(entityConfig, entity, room);
ruinEntities.Add(new RuinEntity(entityConfig, entity, room, parent));
}
else // Removing items that don't fit in the container
{
entity.Remove();
}
}
else
{
entity = new Item((ItemPrefab)entityConfig.Prefab, position, null);
CreateChildEntities(entityConfig, entity, room);
ruinEntities.Add(new RuinEntity(entityConfig, entity, room, parent));
}
}
else if (entityConfig.Prefab is ItemAssemblyPrefab itemAssemblyPrefab)
{
var entities = itemAssemblyPrefab.CreateInstance(position, sub: null);
foreach (MapEntity e in entities)
{
if (e is Structure)
{
e.ShouldBeSaved = false;
}
else if (e is Item item)
{
var door = item.GetComponent<Door>();
if (door != null) { doors.Add(door); }
}
ruinEntities.Add(new RuinEntity(entityConfig, e, room, parent));
}
if (entityConfig.Expand)
{
ExpandEntities(entities);
}
CreateChildEntities(entityConfig, entity, room);
}
else
{
entity = new Structure(new Rectangle(
(int)(position.X - size.X / 2.0f), (int)(position.Y + size.Y / 2.0f),
(int)size.X, (int)size.Y),
entityConfig.Prefab as StructurePrefab, null)
{
ShouldBeSaved = false
};
if (entityConfig.Expand)
{
ExpandEntities(new List<MapEntity>() { entity });
}
CreateChildEntities(entityConfig, entity, room);
ruinEntities.Add(new RuinEntity(entityConfig, entity, room, parent));
}
}
private void CreateChildEntities(RuinEntityConfig parentEntityConfig, MapEntity parentEntity, RuinShape room, Rand.RandSync randSync = Rand.RandSync.Server)
{
Dictionary<int, List<RuinEntityConfig>> propGroups = new Dictionary<int, List<RuinEntityConfig>>();
foreach (RuinEntityConfig entityConfig in parentEntityConfig.ChildEntities)
{
if (!propGroups.ContainsKey(entityConfig.SingleGroupIndex))
{
propGroups[entityConfig.SingleGroupIndex] = new List<RuinEntityConfig>();
}
propGroups[entityConfig.SingleGroupIndex].Add(entityConfig);
}
List<RuinEntityConfig> props = new List<RuinEntityConfig>();
foreach (KeyValuePair<int, List<RuinEntityConfig>> propGroup in propGroups)
{
if (propGroup.Key == 0)
{
props.AddRange(propGroup.Value);
}
else
{
props.Add(propGroup.Value[Rand.Int(propGroup.Value.Count, randSync)]);
}
}
foreach (RuinEntityConfig childEntity in props)
{
var childRoom = FindRoom(childEntity.PlacementRelativeToParent, room);
if (childRoom != null)
{
int amount = Rand.Range(childEntity.MinAmount, childEntity.MaxAmount + 1, Rand.RandSync.Server);
for (int i = 0; i < amount; i++)
{
CreateEntity(childEntity, childRoom, parentEntity);
}
}
}
}
private void CreateConnections(RuinEntity entity)
{
foreach (RuinEntityConfig.EntityConnection connection in entity.Config.EntityConnections)
{
if (!string.IsNullOrEmpty(connection.SourceEntityIdentifier) &&
connection.SourceEntityIdentifier != entity.Entity?.prefab.Identifier)
{
continue;
}
MapEntity targetEntity = null;
if (connection.TargetEntityIdentifier == "parent")
{
targetEntity = entity.Parent;
}
else if (!string.IsNullOrEmpty(connection.RoomName))
{
RuinShape targetRoom = null;
if (Enum.TryParse(connection.RoomName, out RuinEntityConfig.RelativePlacement placement))
{
targetRoom = FindRoom(placement, entity.Room);
}
else
{
targetRoom = allShapes.Find(s => s.RoomType?.Name == connection.RoomName);
}
if (targetRoom == null)
{
DebugConsole.ThrowError("Error while generating ruins - could not find a room of the type \"" + connection.RoomName + "\".");
}
else
{
targetEntity = ruinEntities.GetRandom(e =>
e.Room == targetRoom &&
e.Entity.prefab?.Identifier == connection.TargetEntityIdentifier)?.Entity;
}
}
else
{
targetEntity = ruinEntities.GetRandom(e => e.Entity.prefab?.Identifier == connection.TargetEntityIdentifier)?.Entity;
}
if (targetEntity == null) continue;
if (connection.WireConnection != null)
{
Item item = entity.Entity as Item;
if (item == null)
{
DebugConsole.ThrowError("Could not connect a wire to the ruin entity \"" + entity.Entity.Name + "\" - the entity is not an item.");
continue;
}
else if (item.Connections == null)
{
DebugConsole.ThrowError("Could not connect a wire to the ruin entity \"" + entity.Entity.Name + "\" - the item does not have a connection panel component.");
continue;
}
Item parentItem = entity.Parent as Item;
if (parentItem == null)
{
DebugConsole.ThrowError("Could not connect a wire to the ruin entity \"" + parentItem.Name + "\" - the entity is not an item.");
continue;
}
else if (parentItem.Connections == null)
{
DebugConsole.ThrowError("Could not connect a wire to the ruin entity \"" + parentItem.Name + "\" - the item does not have a connection panel component.");
continue;
}
//TODO: alien wire prefab w/ custom sprite?
var wirePrefab = MapEntityPrefab.Find(null, "blackwire") as ItemPrefab;
var conn1 = item.Connections.Find(c => c.Name == connection.WireConnection.First);
if (conn1 == null)
{
DebugConsole.ThrowError("Could not connect a wire to the ruin entity \"" + item.Name +
"\" - the item does not have a connection named \"" + connection.WireConnection.First + "\".");
continue;
}
var conn2 = parentItem.Connections.Find(c => c.Name == connection.WireConnection.Second);
if (conn2 == null)
{
DebugConsole.ThrowError("Could not connect a wire to the ruin entity \"" + parentItem.Name +
"\" - the item does not have a connection named \"" + connection.WireConnection.Second + "\".");
continue;
}
var wire = new Item(wirePrefab, parentItem.WorldPosition, null).GetComponent<Items.Components.Wire>();
wire.Item.ShouldBeSaved = false;
conn1.TryAddLink(wire);
wire.Connect(conn1, true);
conn2.TryAddLink(wire);
wire.Connect(conn2, true);
wire.Hidden = true; // Hidden for now
}
else
{
entity.Entity.linkedTo.Add(targetEntity);
targetEntity.linkedTo.Add(entity.Entity);
}
}
}
private void ExpandEntities(IEnumerable<MapEntity> entities)
{
Vector2 xBounds = new Vector2(entities.Min(e => e.Rect.X), entities.Max(e => e.Rect.Right));
Vector2 yBounds = new Vector2(entities.Min(e => e.Rect.Y - e.Rect.Height), entities.Max(e => e.Rect.Y));
Vector2 center = new Vector2((xBounds.X + xBounds.Y) / 2.0f, (yBounds.X + yBounds.Y) / 2.0f);
foreach (MapEntity entity in entities)
{
if (entity is Item item)
{
Vector2 moveTo = StretchPoint(entity.WorldPosition, center, xBounds, yBounds);
Vector2 moveAmount = moveTo - entity.WorldPosition;
var connectionPanel = item.GetComponent<ConnectionPanel>();
connectionPanel?.MoveConnectedWires(moveAmount);
entity.Move(moveAmount);
}
else if (entity is Structure structure)
{
if (!entity.ResizeHorizontal && !entity.ResizeVertical)
{
Vector2 moveTo = StretchPoint(entity.WorldPosition, center, xBounds, yBounds);
entity.Move(moveTo - entity.WorldPosition);
continue;
}
Vector2 structureBoundsMin = new Vector2(structure.Rect.X, structure.Rect.Y - structure.Rect.Height);
Vector2 structureBoundsMax = new Vector2(structure.Rect.Right, structure.Rect.Y);
if (structure.ResizeHorizontal)
{
if (structure.Rect.Right > center.X)
{
Vector2 moveTo = StretchPoint(
new Vector2(structureBoundsMax.X, structure.Rect.Y - structure.Rect.Height / 2),
new Vector2(center.X, structure.Rect.Y - structure.Rect.Height / 2),
xBounds, yBounds);
structureBoundsMax.X = moveTo.X;
}
if (structure.Rect.X < center.X)
{
Vector2 moveTo = StretchPoint(
new Vector2(structureBoundsMin.X, structure.Rect.Y - structure.Rect.Height / 2),
new Vector2(center.X, structure.Rect.Y - structure.Rect.Height / 2),
xBounds, yBounds);
structureBoundsMin.X = moveTo.X;
}
}
if (structure.ResizeVertical)
{
if (structure.Rect.Y > center.X)
{
Vector2 moveTo = StretchPoint(
new Vector2(structure.Rect.Center.X, structureBoundsMax.Y),
new Vector2(structure.Rect.Center.X, center.Y),
xBounds, yBounds);
structureBoundsMax.Y = moveTo.Y;
}
if (structure.Rect.Y - structure.Rect.Height < center.Y)
{
Vector2 moveTo = StretchPoint(
new Vector2(structure.Rect.Center.X, structureBoundsMin.Y),
new Vector2(structure.Rect.Center.X, center.Y),
xBounds, yBounds);
structureBoundsMin.Y = moveTo.Y;
}
}
structure.Rect = new Rectangle(
(int)structureBoundsMin.X,
(int)structureBoundsMax.Y,
(int)(structureBoundsMax.X - structureBoundsMin.X),
(int)(structureBoundsMax.Y - structureBoundsMin.Y));
}
}
}
private Vector2 StretchPoint(Vector2 point, Vector2 center, Vector2 xBounds, Vector2 yBounds)
{
Vector2 diff = point - center;
if (diff.LengthSquared() < 0.0001f) return point;
Vector2? closestIntersection = RayCastWalls(point, Vector2.Normalize(diff));
if (!closestIntersection.HasValue) return point;
Vector2 moveAmount = closestIntersection.Value - point;
Vector2 moveRatio = new Vector2(
Math.Abs(diff.X) / ((xBounds.Y - xBounds.X) * 0.5f),
Math.Abs(diff.Y) / ((yBounds.Y - yBounds.X) * 0.5f));
return point + new Vector2(moveAmount.X * moveRatio.X, moveAmount.Y * moveRatio.Y);
}
private Vector2? RayCastWalls(Vector2 worldPosition, Vector2 dir)
{
float rayLength = 10000.0f;
Vector2 rayStart = worldPosition;
Vector2 rayEnd = worldPosition + dir * rayLength;
Vector2? closestIntersection = null;
float closestDist = rayLength * rayLength;
foreach (Line line in walls)
{
if (!MathUtils.GetLineIntersection(line.A, line.B, rayStart, rayEnd, out Vector2 intersection)) { continue; }
intersection = line.IsHorizontal ?
new Vector2(intersection.X, intersection.Y - Math.Sign(dir.Y) * line.Radius) :
new Vector2(intersection.X - Math.Sign(dir.X) * line.Radius, intersection.Y);
float dist = Vector2.DistanceSquared(rayStart, intersection);
if (dist < closestDist)
{
closestIntersection = intersection;
closestDist = dist;
}
}
return closestIntersection;
}
private RuinShape FindRoom(RuinEntityConfig.RelativePlacement placement, RuinShape relativeTo)
{
switch (placement)
{
case RuinEntityConfig.RelativePlacement.SameRoom:
return relativeTo;
case RuinEntityConfig.RelativePlacement.NextRoom:
return FindNearestRoom(relativeTo, rooms, 1);
case RuinEntityConfig.RelativePlacement.NextCorridor:
return FindNearestRoom(relativeTo, corridors, 1);
case RuinEntityConfig.RelativePlacement.PreviousRoom:
return FindNearestRoom(relativeTo, rooms, -1);
case RuinEntityConfig.RelativePlacement.PreviousCorridor:
return FindNearestRoom(relativeTo, corridors, -1);
case RuinEntityConfig.RelativePlacement.FirstRoom:
return FindFirstRoom(rooms);
case RuinEntityConfig.RelativePlacement.FirstCorridor:
return FindFirstRoom(corridors);
case RuinEntityConfig.RelativePlacement.LastRoom:
return FindLastRoom(rooms);
case RuinEntityConfig.RelativePlacement.LastCorridor:
return FindLastRoom(corridors);
default:
throw new NotImplementedException();
}
}
/// <summary>
/// Find the nearest room relative to a specific room.
/// </summary>
/// <param name="relativeTo">The room to compare the distance with</param>
/// <param name="roomList">List of rooms to check (use a list that only contains rooms/corridors if you want a specific types of rooms)</param>
/// <param name="dir">Direction to check: 1 = find the next room, -1 = find the previous room</param>
private RuinShape FindNearestRoom(RuinShape relativeTo, IEnumerable<RuinShape> roomList, int dir, Func<RuinShape, bool> predicate = null)
{
dir = Math.Sign(dir);
RuinShape selectedRoom = null;
foreach (RuinShape room in roomList)
{
if (room == relativeTo) continue;
if (predicate != null && !predicate(room)) continue;
int roomDir = Math.Sign(room.DistanceFromEntrance - relativeTo.DistanceFromEntrance);
if (roomDir == 0 || roomDir == dir)
{
if (selectedRoom == null)
{
selectedRoom = room;
}
else //room already selected, check if this one is closer
{
//closer than the previously selected room
if (Math.Abs(room.DistanceFromEntrance - relativeTo.DistanceFromEntrance) <
Math.Abs(selectedRoom.DistanceFromEntrance - relativeTo.DistanceFromEntrance))
{
selectedRoom = room;
}
//same distance measured in room indices, select the room if the actual distance is smaller
else if (room.DistanceFromEntrance == selectedRoom.DistanceFromEntrance &&
Vector2.DistanceSquared(relativeTo.Center, room.Center) < Vector2.DistanceSquared(relativeTo.Center, selectedRoom.Center))
{
selectedRoom = room;
}
}
}
}
return selectedRoom;
}
private RuinShape FindFirstRoom(IEnumerable<RuinShape> roomList, Func<RuinShape, bool> predicate = null)
{
if (!roomList.Any()) { return null; }
RuinShape firstRoom = null;
foreach (RuinShape room in roomList)
{
if (predicate != null && !predicate(room)) continue;
if (firstRoom == null || room.DistanceFromEntrance < firstRoom.DistanceFromEntrance)
{
firstRoom = room;
}
}
return firstRoom;
}
private RuinShape FindLastRoom(IEnumerable<RuinShape> roomList, Func<RuinShape, bool> predicate = null)
{
if (!roomList.Any()) { return null; }
RuinShape lastRoom = null;
foreach (RuinShape room in roomList)
{
if (predicate != null && !predicate(room)) continue;
if (lastRoom == null || room.DistanceFromEntrance > lastRoom.DistanceFromEntrance)
{
lastRoom = room;
}
}
return lastRoom;
}
}
}