Here are the examples of the csharp api System.Array.GetLength(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2072 Examples
19
Source : Formatters.DimensionalArray.cs
with MIT License
from 1996v
with MIT License
from 1996v
public void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, T[,] value)
{
if (value == null)
{
writer.WriteNull();
return;
}
int i = value.GetLength(0);
int j = value.GetLength(1);
IBssomFormatter<T> formatter = context.Option.FormatterResolver.GetFormatterWithVerify<T>();
writer.WriteArray2Type();
long pos = writer.FillUInt32FixNumber();
writer.WriteVariableNumber(ArrayLength);
//first
writer.Write((byte)i);
//second
writer.Write((byte)j);
//third
writer.WriteArray2Type();
long posSecond = writer.FillUInt32FixNumber();
writer.WriteVariableNumber(value.Length);
foreach (T item in value)
{
context.CancellationToken.ThrowIfCancellationRequested();
formatter.Serialize(ref writer, ref context, item);
}
writer.WriteBackFixNumber(pos, checked((int)(writer.Position - pos - BssomBinaryPrimitives.FixUInt32NumberSize)));
writer.WriteBackFixNumber(posSecond, checked((int)(writer.Position - posSecond - BssomBinaryPrimitives.FixUInt32NumberSize)));
}
19
Source : Formatters.DimensionalArray.cs
with MIT License
from 1996v
with MIT License
from 1996v
public void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, T[,,] value)
{
if (value == null)
{
writer.WriteNull();
return;
}
int i = value.GetLength(0);
int j = value.GetLength(1);
int k = value.GetLength(2);
IBssomFormatter<T> formatter = context.Option.FormatterResolver.GetFormatterWithVerify<T>();
writer.WriteArray2Type();
long pos = writer.FillUInt32FixNumber();
writer.WriteVariableNumber(ArrayLength);
//first
writer.Write((byte)i);
//second
writer.Write((byte)j);
//third
writer.Write((byte)k);
//fourth
writer.WriteArray2Type();
long posSecond = writer.FillUInt32FixNumber();
writer.WriteVariableNumber(value.Length);
foreach (T item in value)
{
context.CancellationToken.ThrowIfCancellationRequested();
formatter.Serialize(ref writer, ref context, item);
}
writer.WriteBackFixNumber(pos, checked((int)(writer.Position - posSecond + BssomBinaryPrimitives.FixUInt32NumberSize)));
writer.WriteBackFixNumber(pos, checked((int)(writer.Position - pos + BssomBinaryPrimitives.FixUInt32NumberSize)));
}
19
Source : Formatters.DimensionalArray.cs
with MIT License
from 1996v
with MIT License
from 1996v
public void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, T[,,,] value)
{
if (value == null)
{
writer.WriteNull();
}
else
{
int i = value.GetLength(0);
int j = value.GetLength(1);
int k = value.GetLength(2);
int l = value.GetLength(3);
IBssomFormatter<T> formatter = context.Option.FormatterResolver.GetFormatterWithVerify<T>();
writer.WriteArray2Type();
long pos = writer.FillUInt32FixNumber();
writer.WriteVariableNumber(ArrayLength);
writer.Write((byte)i);
writer.Write((byte)j);
writer.Write((byte)k);
writer.Write((byte)l);
writer.WriteArray2Type();
long posSecond = writer.FillUInt32FixNumber();
writer.WriteVariableNumber(value.Length);
foreach (T item in value)
{
context.CancellationToken.ThrowIfCancellationRequested();
formatter.Serialize(ref writer, ref context, item);
}
writer.WriteBackFixNumber(pos, checked((int)(writer.Position - posSecond + BssomBinaryPrimitives.FixUInt32NumberSize)));
writer.WriteBackFixNumber(pos, checked((int)(writer.Position - pos + BssomBinaryPrimitives.FixUInt32NumberSize)));
}
}
19
Source : Builder.cs
with MIT License
from a3geek
with MIT License
from a3geek
public void CreateBuilds(Section[,] sections, float specialRate)
{
this.Procedurals.Clear();
this.Geoms.Clear();
this.Frags.Clear();
this.Decos.Clear();
this.Seeds.Clear();
this.index = 0;
for(var i = 0; i < sections.GetLength(0); i++)
{
for(var j = 0; j < sections.GetLength(1); j++)
{
this.CreateBuild(sections[i, j], specialRate);
}
}
}
19
Source : LandblockMesh.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void LoadVertices(float[,] height)
{
var xSize = height.GetLength(0);
var ySize = height.GetLength(1);
Vertices = new List<Vector3>(xSize * ySize);
for (int x = 0; x < xSize; x++)
{
for (int y = 0; y < ySize; y++)
{
Vertices.Add(new Vector3(x * CellSize, y * CellSize, height[x, y]));
}
}
}
19
Source : Mesh.cs
with GNU General Public License v3.0
from ACEmulator
with GNU General Public License v3.0
from ACEmulator
public void LoadVertices(float[,] height)
{
var xSize = height.GetLength(0);
var ySize = height.GetLength(1);
Vertices = new List<VertexPositionColor>(xSize * ySize);
for (int x = 0; x < xSize; x++)
{
for (int y = 0; y < ySize; y++)
{
Vertices.Add(new VertexPositionColor(new Vector3(x * LandDefs.CellLength, y * LandDefs.CellLength, height[x, y]), Color.White));
}
}
}
19
Source : ImageToModelContainer.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
private static Bitmap ConvolutionFilter(Bitmap sourceBitmap,
double[,] filterMatrix,
double factor = 1,
int bias = 0,
bool grayscale = false)
{
BitmapData sourceData =
sourceBitmap.LockBits(new Rectangle(0, 0,
sourceBitmap.Width, sourceBitmap.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppArgb);
byte[] pixelBuffer = new byte[sourceData.Stride *
sourceData.Height];
byte[] resultBuffer = new byte[sourceData.Stride *
sourceData.Height];
Marshal.Copy(sourceData.Scan0, pixelBuffer, 0,
pixelBuffer.Length);
sourceBitmap.UnlockBits(sourceData);
if (grayscale == true)
{
float rgb = 0;
for (int k = 0; k < pixelBuffer.Length; k += 4)
{
rgb = pixelBuffer[k] * 0.11f;
rgb += pixelBuffer[k + 1] * 0.59f;
rgb += pixelBuffer[k + 2] * 0.3f;
pixelBuffer[k] = (byte)rgb;
pixelBuffer[k + 1] = pixelBuffer[k];
pixelBuffer[k + 2] = pixelBuffer[k];
pixelBuffer[k + 3] = 255;
}
}
double blue = 0.0;
double green = 0.0;
double red = 0.0;
int filterWidth = filterMatrix.GetLength(1);
int filterHeight = filterMatrix.GetLength(0);
int filterOffset = (filterWidth - 1) / 2;
int calcOffset = 0;
int byteOffset = 0;
for (int offsetY = filterOffset; offsetY <
sourceBitmap.Height - filterOffset; offsetY++)
{
for (int offsetX = filterOffset; offsetX <
sourceBitmap.Width - filterOffset; offsetX++)
{
blue = 0;
green = 0;
red = 0;
byteOffset = offsetY *
sourceData.Stride +
offsetX * 4;
for (int filterY = -filterOffset;
filterY <= filterOffset; filterY++)
{
for (int filterX = -filterOffset;
filterX <= filterOffset; filterX++)
{
calcOffset = byteOffset +
(filterX * 4) +
(filterY * sourceData.Stride);
blue += (double)(pixelBuffer[calcOffset]) *
filterMatrix[filterY + filterOffset,
filterX + filterOffset];
green += (double)(pixelBuffer[calcOffset + 1]) *
filterMatrix[filterY + filterOffset,
filterX + filterOffset];
red += (double)(pixelBuffer[calcOffset + 2]) *
filterMatrix[filterY + filterOffset,
filterX + filterOffset];
}
}
blue = factor * blue + bias;
green = factor * green + bias;
red = factor * red + bias;
if (blue > 255)
{ blue = 255; }
else if (blue < 0)
{ blue = 0; }
if (green > 255)
{ green = 255; }
else if (green < 0)
{ green = 0; }
if (red > 255)
{ red = 255; }
else if (red < 0)
{ red = 0; }
resultBuffer[byteOffset] = (byte)(blue);
resultBuffer[byteOffset + 1] = (byte)(green);
resultBuffer[byteOffset + 2] = (byte)(red);
resultBuffer[byteOffset + 3] = 255;
}
}
Bitmap resultBitmap = new Bitmap(sourceBitmap.Width,
sourceBitmap.Height);
BitmapData resultData =
resultBitmap.LockBits(new Rectangle(0, 0,
resultBitmap.Width, resultBitmap.Height),
ImageLockMode.WriteOnly,
PixelFormat.Format32bppArgb);
Marshal.Copy(resultBuffer, 0, resultData.Scan0,
resultBuffer.Length);
resultBitmap.UnlockBits(resultData);
return resultBitmap;
}
19
Source : GenericExtensions.cs
with MIT License
from adrenak
with MIT License
from adrenak
public static T[] MatrixToArray<T>(this T[,] matrix, bool rowMajor) {
var arr = new T[matrix.GetLength(0) * matrix.GetLength(1)];
if (rowMajor) {
for (int i = 0; i < matrix.GetLength(0); i++) {
for (int j = 0; j < matrix.GetLength(1); j++)
arr[i * matrix.GetLength(1) + j] = matrix[i, j];
}
}
else {
for (int i = 0; i < matrix.GetLength(1); i++) {
for (int j = 0; j < matrix.GetLength(0); j++)
arr[i * matrix.GetLength(0) + j] = matrix[j, i];
}
}
return arr;
}
19
Source : TerrainManager.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static void SetSplatMap(float[,,] array, LayerType layer, int topology = -1)
{
if (array == null)
{
Debug.LogError($"SetSplatMap(array) is null.");
return;
}
if (layer == LayerType.Alpha)
{
Debug.LogWarning($"SetSplatMap(float[,,], {layer}) is not a valid layer to set. Use SetAlphaMap(bool[,]) to set {layer}.");
return;
}
// Check for array dimensions not matching alphamap.
if (array.GetLength(0) != SplatMapRes || array.GetLength(1) != SplatMapRes || array.GetLength(2) != LayerCount(layer))
{
Debug.LogError($"SetSplatMap(array[{array.GetLength(0)}, {array.GetLength(1)}, {LayerCount(layer)}]) dimensions invalid, should be " +
$"array[{ SplatMapRes}, { SplatMapRes}, {LayerCount(layer)}].");
return;
}
switch (layer)
{
case LayerType.Ground:
Ground = array;
break;
case LayerType.Biome:
Biome = array;
break;
case LayerType.Topology:
if (topology < 0 || topology >= TerrainTopology.COUNT)
{
Debug.LogError($"SetSplatMap({layer}, {topology}) topology parameter out of bounds. Should be between 0 - {TerrainTopology.COUNT - 1}");
return;
}
Topology[topology] = array;
break;
}
if (CurrentLayerType == layer)
{
if (CurrentLayerType == LayerType.Topology && TopologyLayer != topology)
return;
if (!GetTerrainLayers().Equals(Land.terrainData.terrainLayers))
Land.terrainData.terrainLayers = GetTerrainLayers();
RegisterSplatMapUndo($"{layer}");
Land.terrainData.SetAlphamaps(0, 0, array);
LayerDirty = false;
}
}
19
Source : TerrainManager.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static void SetAlphaMap(bool[,] array)
{
if (array == null)
{
Debug.LogError($"SetAlphaMap(array) is null.");
return;
}
// Check for array dimensions not matching alphamap.
if (array.GetLength(0) != AlphaMapRes || array.GetLength(1) != AlphaMapRes)
{
// Special case for converting Alphamaps from the Rust resolution to the Unity Editor resolution.
if (array.GetLength(0) == SplatMapRes && array.GetLength(1) == SplatMapRes)
{
if (Alpha == null || Alpha.GetLength(0) != AlphaMapRes)
Alpha = new bool[AlphaMapRes, AlphaMapRes];
Parallel.For(0, AlphaMapRes, i =>
{
for (int j = 0; j < AlphaMapRes; j++)
Alpha[i, j] = array[i / 2, j / 2];
});
Land.terrainData.SetHoles(0, 0, Alpha);
AlphaDirty = false;
return;
}
else
{
Debug.LogError($"SetAlphaMap(array[{array.GetLength(0)}, {array.GetLength(1)}]) dimensions invalid, should be array[{AlphaMapRes}, {AlphaMapRes}].");
return;
}
}
Alpha = array;
Land.terrainData.SetHoles(0, 0, Alpha);
AlphaDirty = false;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static float[,,] SetValues(float[,,] array, int channel, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
});
return array;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static bool[,] CheckConditions(bool[,] array, bool[,] conditionsMet, bool value)
{
int arrayLength = array.GetLength(0);
Parallel.For(0, arrayLength, i =>
{
for (int j = 0; j < arrayLength; j++)
{
if (array[i, j] != value)
conditionsMet[i, j] = true;
}
});
return conditionsMet;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static float[,,] Rotate(float[,,] array, bool CW, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
float[,,] newArray = new float[array.GetLength(0), array.GetLength(1), array.GetLength(2)];
if (CW)
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
for (int k = 0; k < channelLength; k++)
newArray[i, j, k] = array[j, dmns.x1 - i - 1, k];
}
});
}
else
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
for (int k = 0; k < channelLength; k++)
newArray[i, j, k] = array[dmns.z1 - j - 1, i, k];
}
});
}
return newArray;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static float[,] ShortMapToFloatArray(TerrainMap<short> terrainMap)
{
float[,] array = new float[terrainMap.res, terrainMap.res];
int arrayLength = array.GetLength(0);
Parallel.For(0, arrayLength, i =>
{
for (int j = 0; j < arrayLength; j++)
array[i, j] = BitUtility.Short2Float(terrainMap[i, j]);
});
return array;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static byte[] FloatArrayToByteArray(float[,] array)
{
short[] shortArray = new short[array.GetLength(0) * array.GetLength(1)];
int arrayLength = array.GetLength(0);
Parallel.For(0, arrayLength, i =>
{
for (int j = 0; j < arrayLength; j++)
shortArray[(i * arrayLength) + j] = BitUtility.Float2Short(array[i, j]);
});
byte[] byteArray = new byte[shortArray.Length * 2];
Buffer.BlockCopy(shortArray, 0, byteArray, 0, byteArray.Length);
return byteArray;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static float[,,] NormaliseMulti(float[,,] array, int texturesAmount)
{
int length = (int)Math.Sqrt(array.Length / texturesAmount);
int arrayLength = array.GetLength(0);
int channelLength = array.GetLength(2);
Parallel.For(0, arrayLength, i =>
{
float[] splatWeights = new float[channelLength];
for (int j = 0; j < arrayLength; j++)
{
for (int k = 0; k < channelLength; k++)
splatWeights[k] = array[i, j, k];
float normalisedWeights = splatWeights.Sum();
for (int k = 0; k < channelLength; k++)
{
splatWeights[k] /= normalisedWeights;
array[i, j, k] = splatWeights[k];
}
}
});
return array;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static float[,,] SetRange(float[,,] array, float[,] range, int channel, float rangeLow, float rangeHigh, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelCount = array.GetLength(2);
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (range[i, j] >= rangeLow && range[i, j] <= rangeHigh)
{
for (int k = 0; k < channelCount; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
}
});
return array;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static float[,,] SetRangeBlend(float[,,] array, float[,] range, int channel, float rangeLow, float rangeHigh, float rangeBlendLow, float rangeBlendHigh, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
for (int i = dmns.x0; i < dmns.x1; i++)
{
Parallel.For(dmns.z0, dmns.z1, j =>
{
float[] normalised = new float[channelLength];
if (range[i, j] >= rangeLow && range[i, j] <= rangeHigh)
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
else if (range[i, j] >= rangeBlendLow && range[i, j] < rangeLow)
{
float normalisedRange = range[i, j] - rangeBlendLow;
float newRange = rangeLow - rangeBlendLow;
float rangeBlend = normalisedRange / newRange; // Holds data about the texture weight between the blend ranges.
for (int k = 0; k < channelLength; k++) // Gets the weights of the textures in the pos.
{
if (k == channel)
array[i, j, channel] = rangeBlend;
else
array[i, j, k] = array[i, j, k] * Mathf.Clamp01(1f - rangeBlend);
normalised[k] = array[i, j, k];
}
float normalisedWeights = normalised.Sum();
for (int k = 0; k < channelLength; k++)
{
normalised[k] /= normalisedWeights;
array[i, j, k] = normalised[k];
}
}
else if (range[i, j] > rangeHigh && range[i, j] <= rangeBlendHigh)
{
float normalisedRange = range[i, j] - rangeHigh;
float newRange = rangeBlendHigh - rangeHigh;
float rangeBlend = normalisedRange / newRange; // Holds data about the texture weight between the blend ranges.
float rangeBlendInverted = 1 - rangeBlend;
for (int k = 0; k < channelLength; k++) // Gets the weights of the textures in the pos.
{
if (k == channel)
array[i, j, channel] = rangeBlendInverted;
else
array[i, j, k] = array[i, j, k] * Mathf.Clamp01(1f - rangeBlendInverted);
normalised[k] = array[i, j, k];
}
float normalisedWeights = normalised.Sum();
for (int k = 0; k < channelLength; k++)
{
normalised[k] /= normalisedWeights;
array[i, j, k] = normalised[k];
}
}
});
}
return array;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static float[,,] SetRiver(float[,,] array, float[,] landHeights, float[,] waterHeights, bool aboveTerrain, int channel, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
if (aboveTerrain)
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (waterHeights[i, j] > 500 && waterHeights[i, j] > landHeights[i, j])
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
}
});
}
else
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (waterHeights[i, j] > 500)
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
}
});
}
return array;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static bool[,] CheckConditions(float[,] array, bool[,] conditionsMet, float minValue, float maxValue)
{
int arrayLength = array.GetLength(0);
Parallel.For(0, arrayLength, i =>
{
for (int j = 0; j < arrayLength; j++)
{
if (array[i, j] < minValue)
conditionsMet[i, j] = true;
else if (array[i, j] > maxValue)
conditionsMet[i, j] = true;
}
});
return conditionsMet;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static bool[,] CheckConditions(float[,,] array, bool[,] conditionsMet, int layer, float weight)
{
int arrayLength = array.GetLength(0);
int channelLength = array.GetLength(2);
Parallel.For(0, arrayLength, i =>
{
for (int j = 0; j < arrayLength; j++)
{
if (array[i, j, layer] < weight)
conditionsMet[i, j] = true;
}
});
return conditionsMet;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static float[,] Rotate(float[,] array, bool CW, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
float[,] newArray = new float[array.GetLength(0), array.GetLength(1)];
if (CW)
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
newArray[i, j] = array[j, dmns.x1 - i - 1];
});
}
else
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
newArray[i, j] = array[dmns.z1 - j - 1, i];
});
}
return newArray;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static bool[,] Rotate(bool[,] array, bool CW, Area dmns = null)
{
if (dmns == null)
dmns = new Area(AreaManager.ActiveArea.x0, AreaManager.ActiveArea.x1 * 2, AreaManager.ActiveArea.z0, AreaManager.ActiveArea.z1 * 2);
bool[,] newArray = new bool[array.GetLength(0), array.GetLength(1)];
if (CW)
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
newArray[i, j] = array[j, dmns.x1 - i - 1];
});
}
else
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
newArray[i, j] = array[dmns.z1 - j - 1, i];
});
}
return newArray;
}
19
Source : Array.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static float[,,] Invert(float[,,] array, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 1 - array[i, j, k];
}
});
return array;
}
19
Source : Misc.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void ExtendMap(FarmHouse farmHouse, int w, int h)
{
List<Layer> layers = AccessTools.Field(typeof(Map), "m_layers").GetValue(farmHouse.map) as List<Layer>;
for (int i = 0; i < layers.Count; i++)
{
Tile[,] tiles = AccessTools.Field(typeof(Layer), "m_tiles").GetValue(layers[i]) as Tile[,];
Size size = (Size)AccessTools.Field(typeof(Layer), "m_layerSize").GetValue(layers[i]);
if (tiles.GetLength(0) >= w && tiles.GetLength(1) >= h)
continue;
w = Math.Max(w, tiles.GetLength(0));
h = Math.Max(h, tiles.GetLength(1));
ModEntry.PMonitor.Log($"Extending layer {layers[i].Id} from {size.Width},{size.Height} ({tiles.GetLength(0)},{tiles.GetLength(1)}) to {w},{h}");
size = new Size(w, h);
AccessTools.Field(typeof(Layer), "m_layerSize").SetValue(layers[i], size);
AccessTools.Field(typeof(Map), "m_layers").SetValue(farmHouse.map, layers);
Tile[,] newTiles = new Tile[w, h];
for (int k = 0; k < tiles.GetLength(0); k++)
{
for (int l = 0; l < tiles.GetLength(1); l++)
{
newTiles[k, l] = tiles[k, l];
}
}
AccessTools.Field(typeof(Layer), "m_tiles").SetValue(layers[i], newTiles);
AccessTools.Field(typeof(Layer), "m_tileArray").SetValue(layers[i], new TileArray(layers[i], newTiles));
}
AccessTools.Field(typeof(Map), "m_layers").SetValue(farmHouse.map, layers);
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private void ResizeMap(ref Map map)
{
int mult = Config.FloorSizeMult;
Monitor.Log($"Multiplying map size by {mult}x");
Point newSize = new Point(map.Layers[0].LayerWidth * mult, map.Layers[0].LayerHeight * mult);
Monitor.Log($"old size {map.Layers[0].LayerWidth},{map.Layers[0].LayerHeight} new size {newSize.X},{newSize.Y}");
for (int i = 0; i < map.Layers.Count; i++)
{
FieldRefAccess<Layer, Size>(map.Layers[i], "m_layerSize") = new Size(newSize.X, newSize.Y);
Tile[,] tiles = FieldRefAccess<Layer, Tile[,]>(map.Layers[i], "m_tiles");
Tile[,] newTiles = new Tile[newSize.X, newSize.Y];
for (int k = 0; k < tiles.GetLength(0); k++)
{
for (int l = 0; l < tiles.GetLength(1); l++)
{
newTiles[k, l] = tiles[k, l];
}
}
FieldRefAccess<Layer, Tile[,]>(map.Layers[i], "m_tiles") = newTiles;
FieldRefAccess<Layer, TileArray>(map.Layers[i], "m_tileArray") = new TileArray(map.Layers[i], newTiles);
}
Monitor.Log($"map new size {map.Layers[0].LayerWidth},{map.Layers[0].LayerHeight}");
}
19
Source : Maps.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static void ExtendMap(FarmHouse farmHouse, int v)
{
ModEntry.PMonitor.Log($"Extending map width to {v}");
List<Layer> layers = AccessTools.Field(typeof(Map), "m_layers").GetValue(farmHouse.map) as List<Layer>;
for (int i = 0; i < layers.Count; i++)
{
Tile[,] tiles = AccessTools.Field(typeof(Layer), "m_tiles").GetValue(layers[i]) as Tile[,];
Size size = (Size)AccessTools.Field(typeof(Layer), "m_layerSize").GetValue(layers[i]);
if (size.Width >= v)
continue;
size = new Size(v, size.Height);
AccessTools.Field(typeof(Layer), "m_layerSize").SetValue(layers[i], size);
AccessTools.Field(typeof(Map), "m_layers").SetValue(farmHouse.map, layers);
Tile[,] newTiles = new Tile[v, tiles.GetLength(1)];
for (int k = 0; k < tiles.GetLength(0); k++)
{
for (int l = 0; l < tiles.GetLength(1); l++)
{
newTiles[k, l] = tiles[k, l];
}
}
AccessTools.Field(typeof(Layer), "m_tiles").SetValue(layers[i], newTiles);
AccessTools.Field(typeof(Layer), "m_tileArray").SetValue(layers[i], new TileArray(layers[i], newTiles));
}
AccessTools.Field(typeof(Map), "m_layers").SetValue(farmHouse.map, layers);
}
19
Source : RoomPlacementAlgorithm.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private void PlaceRoom(Block[,] room)
{
int[] direction = new int[2];
bool TunnelPlacementValid(Point start, int tunnelLength)
{
for (int i = 0; i <= tunnelLength + 1; i++)
{
int x = start.X + direction[0] * i;
int y = start.Y + direction[1] * i;
if (dungeonFloor[x, y].Solid == false
|| dungeonFloor[x + direction[1], y + direction[0]].Solid == false
|| dungeonFloor[x - direction[1], y - direction[0]].Solid == false)
return false;
}
return true;
}
void SetRandomDirection()
{
int rand = rng.Next(0, 4);
switch (rand)
{
case (0):
direction[0] = 1;
direction[1] = 0;
break;
case (1):
direction[0] = -1;
direction[1] = 0;
break;
case (2):
direction[0] = 0;
direction[1] = 1;
break;
default:
direction[0] = 0;
direction[1] = -1;
break;
}
}
if (rooms.Count == 0) {
// place the first room. It can't go out of bounds if the player is on the edge of the map,
// so place it so that it will touch the edge while containing the player
Point tempPos = new Point(firstRoomPos.X - room.GetLength(0) / 2, firstRoomPos.Y - room.GetLength(1) / 2);
if (tempPos.X + room.GetLength(0) > dungeonFloor.Width)
tempPos.X = (dungeonFloor.Width - 1) - room.GetLength(0) - 1;
else if (tempPos.X < 0)
tempPos.X = 1;
if (tempPos.Y + room.GetLength(1) > dungeonFloor.Height)
tempPos.Y = (dungeonFloor.Height - 1) - room.GetLength(1) - 1;
else if (tempPos.Y < 0)
tempPos.Y = 1;
AddRoom(room, tempPos);
}
else {
int attempts = 0;
while (attempts < maxRoomPlaceAttempts)
{
SetRandomDirection();
Point potentialPos = ReturnRandomPositionWithFreeSpaceInDirection(direction);
Point startPos = new Point();
while (startPos.Equals(new Point()))
{
Point randRoomPos = new Point(rng.Next(0, room.GetLength(0)), rng.Next(0, room.GetLength(1)));
if (room[randRoomPos.X, randRoomPos.Y] is Air) {
startPos.X = potentialPos.X - randRoomPos.X;
startPos.Y = potentialPos.Y - randRoomPos.Y;
}
}
for (int tunnelLength = 0; tunnelLength < maxTunnelLength; tunnelLength++)
{
Point possibleRoomPos = new Point(startPos.X + direction[0] * tunnelLength, startPos.Y + direction[1] * tunnelLength);
if (RoomPlacementValid(possibleRoomPos, room) && TunnelPlacementValid(potentialPos, tunnelLength)) {
AddRoom(room, possibleRoomPos);
AddTunnel(potentialPos, tunnelLength, direction);
return;
}
}
attempts++;
}
}
}
19
Source : RoomPlacementAlgorithm.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private void AddRoom(Block[,] room, Point pos)
{
for (int i = 0; i < room.GetLength(0); i++)
for (int j = 0; j < room.GetLength(1); j++)
dungeonFloor[i + pos.X, j + pos.Y] = room[i, j];
rooms.Add(room);
if (dungeonFloor[pos.X + room.GetLength(0) / 2, pos.Y + room.GetLength(1) / 2] is Air)
dungeonFloor.PatrolPoints.Add(new Point(pos.X + room.GetLength(0) / 2, pos.Y + room.GetLength(1) / 2));
}
19
Source : Dungeon.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public void Init()
{
Point firstRoomPos = Program.Player.Position;
Point worldIndex = Program.Player.WorldIndex;
for (int i = 0; i < floors.GetLength(0); i++) {
floors[i] = new DungeonFloor(new Point(Program.WorldMap.TileWidth, Program.WorldMap.TileHeight));
floors[i].Init(dungeonType, monsterTypes, worldIndex, i);
}
OnFinishedGenerating(this, EventArgs.Empty);
}
19
Source : WorldMap.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public void UpdatePlants()
{
for (int i = 0; i < worldMap.GetLength(0); i++)
for (int j = 0; j < worldMap.GetLength(1); j++)
worldMap[i, j].UpdatePlants(updateInterval);
updateInterval++;
completedUpdateHour = Program.TimeHandler.CurrentTime.Hour;
}
19
Source : WorldMap.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public void CleanSplatters()
{
for (int i = 0; i < worldMap.GetLength(0); i++)
for (int j = 0; j < worldMap.GetLength(1); j++)
worldMap[i, j].CleanSplatters();
}
19
Source : RoomPlacementAlgorithm.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private Block[,] GenerateAutomataRoom()
{
while (true)
{
Block[,] room = new Block[maxCellularAutomataSize, maxCellularAutomataSize];
for (int i = 0; i < room.GetLength(0); i++)
for (int j = 0; j < room.GetLength(1); j++)
{
if (rng.Next(0, 100) >= wallProbability && i >= 2 && i < room.GetLength(0) - 2 && j >= 2 && j < room.GetLength(1) - 2)
room[i, j] = new Air();
else
room[i, j] = new Wall(Material.Stone);
}
for (int c = 0; c < 3; c++)
{
for (int i = 1; i < room.GetLength(0) - 1; i++)
for (int j = 1; j < room.GetLength(1) - 1; j++)
{
if (DungeonHelper.GetNumOfAdjacentWalls(new Point(i, j), room) > 4)
room[i, j] = new Wall(Material.Stone);
else if (DungeonHelper.GetNumOfAdjacentWalls(new Point(i, j), room) < 4)
room[i, j] = new Air();
}
}
room = FloodFill(room);
for (int i = 0; i < room.GetLength(0); i++)
for (int j = 0; j < room.GetLength(1); j++)
if (room[i, j].Solid == false)
return room;
}
}
19
Source : RoomPlacementAlgorithm.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private Block[,] FloodFill(Block[,] room)
{
bool ListContains(Point point, List<Point> list)
{
foreach (Point p in list)
if (p.Equals(point))
return true;
return false;
}
Point roomSize = new Point(room.GetLength(0), room.GetLength(1));
List<Point> largestRegion = new List<Point>();
for (int x = 0; x < roomSize.X; x++)
{
for (int y = 0; y < roomSize.Y; y++)
{
if (room[x,y].Solid == false)
{
List<Point> newRegion = new List<Point>();
Point tile = new Point(x, y);
List<Point> toBeFilled = new List<Point>() { tile };
while (toBeFilled.Any())
{
tile = toBeFilled[0];
toBeFilled.RemoveAt(0);
if (!ListContains(tile, newRegion))
{
newRegion.Add(tile);
room[tile.X, tile.Y] = new Wall(Material.Stone);
List<Point> directions = new List<Point>()
{
new Point(tile.X, tile.Y + 1),
new Point(tile.X, tile.Y - 1),
new Point(tile.X + 1, tile.Y),
new Point(tile.X - 1, tile.Y)
};
foreach (Point direction in directions)
if (room[direction.X, direction.Y].Solid == false)
if (!ListContains(direction, toBeFilled) && !ListContains(direction, newRegion))
toBeFilled.Add(direction);
}
}
if (newRegion.Count >= minCellularAutomataTiles && newRegion.Count > largestRegion.Count)
largestRegion = newRegion;
}
}
}
foreach (Point tile in largestRegion)
room[tile.X, tile.Y] = new Air();
return room;
}
19
Source : RoomPlacementAlgorithm.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private Block[,] GenerateCrossRoom()
{
int roomHorWidth = (rng.Next(minCrossRoomSize+ 2, maxCrossRoomSize));
int roomVerHeight = (rng.Next(minCrossRoomSize + 2, maxCrossRoomSize));
int roomHorHeight = (rng.Next(minCrossRoomSize, roomVerHeight - 2));
int roomVerWidth = (rng.Next(minCrossRoomSize, roomHorWidth - 2));
Block[,] room = new Block[roomHorWidth, roomVerHeight];
for (int i = 0; i < room.GetLength(0); i++)
for (int j = 0; j < room.GetLength(1); j++)
room[i, j] = new Wall(Material.Stone);
int verOffset = roomVerHeight / 2 - roomHorHeight / 2;
for (int i = 0; i < roomHorWidth; i++)
for (int j = verOffset; j < roomHorHeight + verOffset; j++)
room[i, j] = new Air();
int horOffset = roomHorWidth / 2 - roomVerWidth / 2;
for (int i = horOffset; i < roomVerWidth + horOffset; i++)
for (int j = 0; j < roomVerHeight; j++)
room[i, j] = new Air();
return room;
}
19
Source : RoomPlacementAlgorithm.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private Block[,] GenerateRectRoom()
{
Point size = new Point(rng.Next(minCrossRoomSize, maxCrossRoomSize), rng.Next(minCrossRoomSize, maxCrossRoomSize));
Block[,] room = new Block[size.X, size.Y];
for (int i = 0; i < room.GetLength(0); i++)
for (int j = 0; j < room.GetLength(1); j++)
room[i, j] = new Air();
return room;
}
19
Source : RoomPlacementAlgorithm.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private bool RoomPlacementValid(Point pos, Block[,] room)
{
for (int i = -1; i <= room.GetLength(0); i++)
for (int j = -1; j <= room.GetLength(1); j++) {
if (!dungeonFloor.PointWithinBounds(new Point(i + pos.X, j + pos.Y)) || dungeonFloor.PointOnEdge(new Point(i + pos.X, j + pos.Y)))
return false;
if (dungeonFloor[i + pos.X, j + pos.Y].Solid == false)
return false;
}
return true;
}
19
Source : BuildingManager.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private static void DetermineNextConstruction()
{
if (nextConstruction.Equals(new Point() )) {
for (int i = 0; i < constructionMap.GetLength(0); i++)
for (int j = 0; j < constructionMap.GetLength(1); j++) {
if (constructionMap[i, j] != null) {
nextConstruction = new Point(i, j);
bool enoughMaterials = DetermineIfEnoughMaterials();
if (!enoughMaterials)
{
Menus.DisplayIncorrectUsage("You don't have the required materials!");
RemoveAllConstructionsWithName(constructionMap[i, j].Name);
nextConstruction = new Point();
DetermineNextConstruction();
}
else
currentConstructRecipe = GetConstructRecipe();
}
}
}
}
19
Source : BuildingManager.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private static void RemoveAllConstructionsWithName(string name)
{
for (int i = 0; i < constructionMap.GetLength(0); i++)
for (int j = 0; j < constructionMap.GetLength(1); j++) {
if (constructionMap[i, j] != null && constructionMap[i, j].Name == name)
constructionMap[i, j] = null;
}
}
19
Source : TerrainShape.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public void GetBoundingBox(ref AffineTransform transform, out BoundingBox boundingBox)
{
#if !WINDOWS
boundingBox = new BoundingBox();
#endif
float minX = float.MaxValue, maxX = -float.MaxValue,
minY = float.MaxValue, maxY = -float.MaxValue,
minZ = float.MaxValue, maxZ = -float.MaxValue;
Vector3 minXvertex = new Vector3(),
maxXvertex = new Vector3(),
minYvertex = new Vector3(),
maxYvertex = new Vector3(),
minZvertex = new Vector3(),
maxZvertex = new Vector3();
//Find the extreme locations.
for (int i = 0; i < heights.GetLength(0); i++)
{
for (int j = 0; j < heights.GetLength(1); j++)
{
var vertex = new Vector3(i, heights[i, j], j);
Matrix3x3.Transform(ref vertex, ref transform.LinearTransform, out vertex);
if (vertex.X < minX)
{
minX = vertex.X;
minXvertex = vertex;
}
else if (vertex.X > maxX)
{
maxX = vertex.X;
maxXvertex = vertex;
}
if (vertex.Y < minY)
{
minY = vertex.Y;
minYvertex = vertex;
}
else if (vertex.Y > maxY)
{
maxY = vertex.Y;
maxYvertex = vertex;
}
if (vertex.Z < minZ)
{
minZ = vertex.Z;
minZvertex = vertex;
}
else if (vertex.Z > maxZ)
{
maxZ = vertex.Z;
maxZvertex = vertex;
}
}
}
//Shift the bounding box.
boundingBox.Min.X = minXvertex.X + transform.Translation.X;
boundingBox.Min.Y = minYvertex.Y + transform.Translation.Y;
boundingBox.Min.Z = minZvertex.Z + transform.Translation.Z;
boundingBox.Max.X = maxXvertex.X + transform.Translation.X;
boundingBox.Max.Y = maxYvertex.Y + transform.Translation.Y;
boundingBox.Max.Z = maxZvertex.Z + transform.Translation.Z;
}
19
Source : TerrainShape.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public bool RayCast(ref Ray ray, float maximumLength, ref AffineTransform transform, TriangleSidedness sidedness, out RayHit hit)
{
hit = new RayHit();
//Put the ray into local space.
Ray localRay;
AffineTransform inverse;
AffineTransform.Invert(ref transform, out inverse);
Matrix3x3.Transform(ref ray.Direction, ref inverse.LinearTransform, out localRay.Direction);
AffineTransform.Transform(ref ray.Position, ref inverse, out localRay.Position);
//Use rasterizey traversal.
//The origin is at 0,0,0 and the map goes +X, +Y, +Z.
//if it's before the origin and facing away, or outside the max and facing out, early out.
float maxX = heights.GetLength(0) - 1;
float maxZ = heights.GetLength(1) - 1;
Vector3 progressingOrigin = localRay.Position;
float distance = 0;
//Check the outside cases first.
if (progressingOrigin.X < 0)
{
if (localRay.Direction.X > 0)
{
//Off the left side.
float timeToMinX = -progressingOrigin.X / localRay.Direction.X;
distance += timeToMinX;
Vector3 increment;
Vector3.Multiply(ref localRay.Direction, timeToMinX, out increment);
Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin);
}
else
return false; //Outside and pointing away from the terrain.
}
else if (progressingOrigin.X > maxX)
{
if (localRay.Direction.X < 0)
{
//Off the left side.
float timeToMinX = -(progressingOrigin.X - maxX) / localRay.Direction.X;
distance += timeToMinX;
Vector3 increment;
Vector3.Multiply(ref localRay.Direction, timeToMinX, out increment);
Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin);
}
else
return false; //Outside and pointing away from the terrain.
}
if (progressingOrigin.Z < 0)
{
if (localRay.Direction.Z > 0)
{
float timeToMinZ = -progressingOrigin.Z / localRay.Direction.Z;
distance += timeToMinZ;
Vector3 increment;
Vector3.Multiply(ref localRay.Direction, timeToMinZ, out increment);
Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin);
}
else
return false;
}
else if (progressingOrigin.Z > maxZ)
{
if (localRay.Direction.Z < 0)
{
float timeToMinZ = -(progressingOrigin.Z - maxZ) / localRay.Direction.Z;
distance += timeToMinZ;
Vector3 increment;
Vector3.Multiply(ref localRay.Direction, timeToMinZ, out increment);
Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin);
}
else
return false;
}
if (distance > maximumLength)
return false;
//By now, we should be entering the main body of the terrain.
int xCell = (int)progressingOrigin.X;
int zCell = (int)progressingOrigin.Z;
//If it's hitting the border and going in, then correct the index
//so that it will initially target a valid quad.
//Without this, a quad beyond the border would be tried and failed.
if (xCell == heights.GetLength(0) - 1 && localRay.Direction.X < 0)
xCell = heights.GetLength(0) - 2;
if (zCell == heights.GetLength(1) - 1 && localRay.Direction.Z < 0)
zCell = heights.GetLength(1) - 2;
while (true)
{
//Check for a miss.
if (xCell < 0 ||
zCell < 0 ||
xCell >= heights.GetLength(0) - 1 ||
zCell >= heights.GetLength(1) - 1)
return false;
//Test the triangles of this cell.
Vector3 v1, v2, v3, v4;
// v3 v4
// v1 v2
GetLocalPosition(xCell, zCell, out v1);
GetLocalPosition(xCell + 1, zCell, out v2);
GetLocalPosition(xCell, zCell + 1, out v3);
GetLocalPosition(xCell + 1, zCell + 1, out v4);
RayHit hit1, hit2;
bool didHit1;
bool didHit2;
//Don't bother doing ray intersection tests if the ray can't intersect it.
float highest = v1.Y;
float lowest = v1.Y;
if (v2.Y > highest)
highest = v2.Y;
else if (v2.Y < lowest)
lowest = v2.Y;
if (v3.Y > highest)
highest = v3.Y;
else if (v3.Y < lowest)
lowest = v3.Y;
if (v4.Y > highest)
highest = v4.Y;
else if (v4.Y < lowest)
lowest = v4.Y;
if (!(progressingOrigin.Y > highest && localRay.Direction.Y > 0 ||
progressingOrigin.Y < lowest && localRay.Direction.Y < 0))
{
if (quadTriangleOrganization == QuadTriangleOrganization.BottomLeftUpperRight)
{
//Always perform the raycast as if Y+ in local space is the way the triangles are facing.
didHit1 = Toolbox.FindRayTriangleIntersection(ref localRay, maximumLength, sidedness, ref v1, ref v2, ref v3, out hit1);
didHit2 = Toolbox.FindRayTriangleIntersection(ref localRay, maximumLength, sidedness, ref v2, ref v4, ref v3, out hit2);
}
else //if (quadTriangleOrganization == CollisionShapes.QuadTriangleOrganization.BottomRightUpperLeft)
{
didHit1 = Toolbox.FindRayTriangleIntersection(ref localRay, maximumLength, sidedness, ref v1, ref v2, ref v4, out hit1);
didHit2 = Toolbox.FindRayTriangleIntersection(ref localRay, maximumLength, sidedness, ref v1, ref v4, ref v3, out hit2);
}
if (didHit1 && didHit2)
{
if (hit1.T < hit2.T)
{
Vector3.Multiply(ref ray.Direction, hit1.T, out hit.Location);
Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location);
Matrix3x3.TransformTranspose(ref hit1.Normal, ref inverse.LinearTransform, out hit.Normal);
hit.T = hit1.T;
return true;
}
Vector3.Multiply(ref ray.Direction, hit2.T, out hit.Location);
Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location);
Matrix3x3.TransformTranspose(ref hit2.Normal, ref inverse.LinearTransform, out hit.Normal);
hit.T = hit2.T;
return true;
}
else if (didHit1)
{
Vector3.Multiply(ref ray.Direction, hit1.T, out hit.Location);
Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location);
Matrix3x3.TransformTranspose(ref hit1.Normal, ref inverse.LinearTransform, out hit.Normal);
hit.T = hit1.T;
return true;
}
else if (didHit2)
{
Vector3.Multiply(ref ray.Direction, hit2.T, out hit.Location);
Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location);
Matrix3x3.TransformTranspose(ref hit2.Normal, ref inverse.LinearTransform, out hit.Normal);
hit.T = hit2.T;
return true;
}
}
//Move to the next cell.
float timeToX;
if (localRay.Direction.X < 0)
timeToX = -(progressingOrigin.X - xCell) / localRay.Direction.X;
else if (ray.Direction.X > 0)
timeToX = (xCell + 1 - progressingOrigin.X) / localRay.Direction.X;
else
timeToX = float.MaxValue;
float timeToZ;
if (localRay.Direction.Z < 0)
timeToZ = -(progressingOrigin.Z - zCell) / localRay.Direction.Z;
else if (localRay.Direction.Z > 0)
timeToZ = (zCell + 1 - progressingOrigin.Z) / localRay.Direction.Z;
else
timeToZ = float.MaxValue;
//Move to the next cell.
if (timeToX < timeToZ)
{
if (localRay.Direction.X < 0)
xCell--;
else
xCell++;
distance += timeToX;
if (distance > maximumLength)
return false;
Vector3 increment;
Vector3.Multiply(ref localRay.Direction, timeToX, out increment);
Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin);
}
else
{
if (localRay.Direction.Z < 0)
zCell--;
else
zCell++;
distance += timeToZ;
if (distance > maximumLength)
return false;
Vector3 increment;
Vector3.Multiply(ref localRay.Direction, timeToZ, out increment);
Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin);
}
}
}
19
Source : TerrainShape.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public void GetPosition(int i, int j, ref AffineTransform transform, out Vector3 position)
{
if (i <= 0)
i = 0;
else if (i >= heights.GetLength(0))
i = heights.GetLength(0) - 1;
if (j <= 0)
j = 0;
else if (j >= heights.GetLength(1))
j = heights.GetLength(1) - 1;
#if !WINDOWS
position = new Vector3();
#endif
position.X = i;
position.Y = heights[i, j];
position.Z = j;
AffineTransform.Transform(ref position, ref transform, out position);
}
19
Source : TerrainShape.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public void GetNormal(int i, int j, ref AffineTransform transform, out Vector3 normal)
{
Vector3 top;
Vector3 bottom;
Vector3 right;
Vector3 left;
if (i <= 0)
i = 0;
else if (i >= heights.GetLength(0))
i = heights.GetLength(0) - 1;
if (j <= 0)
j = 0;
else if (j >= heights.GetLength(1))
j = heights.GetLength(1) - 1;
GetPosition(i, Math.Min(j + 1, heights.GetLength(1) - 1), ref transform, out top);
GetPosition(i, Math.Max(j - 1, 0), ref transform, out bottom);
GetPosition(Math.Min(i + 1, heights.GetLength(0) - 1), j, ref transform, out right);
GetPosition(Math.Max(i - 1, 0), j, ref transform, out left);
Vector3 temp;
Vector3.Subtract(ref top, ref bottom, out temp);
Vector3.Subtract(ref right, ref left, out normal);
Vector3.Cross(ref temp, ref normal, out normal);
normal.Normalize();
}
19
Source : TerrainShape.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public void GetTriangle(ref TriangleMeshConvexContactManifold.TriangleIndices indices, ref AffineTransform transform, out Vector3 a, out Vector3 b, out Vector3 c)
{
//Reverse the encoded index:
//index = i + width * j
int width = heights.GetLength(0);
int columnA = indices.A / width;
int rowA = indices.A - columnA * width;
int columnB = indices.B / width;
int rowB = indices.B - columnB * width;
int columnC = indices.C / width;
int rowC = indices.C - columnC * width;
GetPosition(rowA, columnA, ref transform, out a);
GetPosition(rowB, columnB, ref transform, out b);
GetPosition(rowC, columnC, ref transform, out c);
}
19
Source : TerrainShape.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public void GetTriangle(int index, ref AffineTransform transform, out Vector3 a, out Vector3 b, out Vector3 c)
{
//Find the quad.
int quadIndex = index / 2;
bool isFirstTriangle = quadIndex * 2 == index;
int column = quadIndex / heights.GetLength(0);
int row = quadIndex - column * heights.GetLength(0);
if (quadTriangleOrganization == CollisionShapes.QuadTriangleOrganization.BottomLeftUpperRight)
{
if (isFirstTriangle)
{
GetPosition(row, column, ref transform, out a);
GetPosition(row + 1, column, ref transform, out b);
GetPosition(row, column + 1, ref transform, out c);
}
else
{
GetPosition(row, column + 1, ref transform, out a);
GetPosition(row + 1, column + 1, ref transform, out b);
GetPosition(row + 1, column, ref transform, out c);
}
}
else
{
//The quad is BottomRightUpperLeft.
if (isFirstTriangle)
{
GetPosition(row, column, ref transform, out a);
GetPosition(row + 1, column, ref transform, out b);
GetPosition(row + 1, column + 1, ref transform, out c);
}
else
{
GetPosition(row, column, ref transform, out a);
GetPosition(row, column + 1, ref transform, out b);
GetPosition(row + 1, column + 1, ref transform, out c);
}
}
}
19
Source : TerrainShape.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public bool GetOverlaps(BoundingBox localSpaceBoundingBox, RawList<TriangleMeshConvexContactManifold.TriangleIndices> overlappedTriangles)
{
int width = heights.GetLength(0);
int minX = Math.Max((int)localSpaceBoundingBox.Min.X, 0);
int minY = Math.Max((int)localSpaceBoundingBox.Min.Z, 0);
int maxX = Math.Min((int)localSpaceBoundingBox.Max.X, width - 2);
int maxY = Math.Min((int)localSpaceBoundingBox.Max.Z, heights.GetLength(1) - 2);
for (int i = minX; i <= maxX; i++)
{
for (int j = minY; j <= maxY; j++)
{
//Before adding a triangle to the list, make sure the object isn't too high or low from the quad.
float highest, lowest;
float y1 = heights[i, j];
float y2 = heights[i + 1, j];
float y3 = heights[i, j + 1];
float y4 = heights[i + 1, j + 1];
highest = y1;
lowest = y1;
if (y2 > highest)
highest = y2;
else if (y2 < lowest)
lowest = y2;
if (y3 > highest)
highest = y3;
else if (y3 < lowest)
lowest = y3;
if (y4 > highest)
highest = y4;
else if (y4 < lowest)
lowest = y4;
if (localSpaceBoundingBox.Max.Y < lowest ||
localSpaceBoundingBox.Min.Y > highest)
continue;
//Now the local bounding box is very likely intersecting those of the triangles.
//Add the triangles to the list.
var indices = new TriangleMeshConvexContactManifold.TriangleIndices();
//v3 v4
//v1 v2
if (quadTriangleOrganization == QuadTriangleOrganization.BottomLeftUpperRight)
{
//v1 v2 v3
indices.A = i + j * width;
indices.B = i + 1 + j * width;
indices.C = i + (j + 1) * width;
overlappedTriangles.Add(indices);
//v2 v4 v3
indices.A = i + 1 + j * width;
indices.B = i + 1 + (j + 1) * width;
indices.C = i + (j + 1) * width;
overlappedTriangles.Add(indices);
}
else //Bottom right, Upper left
{
//v1 v2 v4
indices.A = i + j * width;
indices.B = i + 1 + j * width;
indices.C = i + 1 + (j + 1) * width;
overlappedTriangles.Add(indices);
//v1 v4 v3
indices.A = i + j * width;
indices.B = i + 1 + (j + 1) * width;
indices.C = i + (j + 1) * width;
overlappedTriangles.Add(indices);
}
}
}
return overlappedTriangles.Count > 0;
}
19
Source : TerrainShape.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public bool GetOverlaps(BoundingBox localBoundingBox, RawList<int> overlappedElements)
{
int width = heights.GetLength(0);
int minX = Math.Max((int)localBoundingBox.Min.X, 0);
int minY = Math.Max((int)localBoundingBox.Min.Z, 0);
int maxX = Math.Min((int)localBoundingBox.Max.X, width - 2);
int maxY = Math.Min((int)localBoundingBox.Max.Z, heights.GetLength(1) - 2);
for (int i = minX; i <= maxX; i++)
{
for (int j = minY; j <= maxY; j++)
{
//Before adding a triangle to the list, make sure the object isn't too high or low from the quad.
float highest, lowest;
float y1 = heights[i, j];
float y2 = heights[i + 1, j];
float y3 = heights[i, j + 1];
float y4 = heights[i + 1, j + 1];
highest = y1;
lowest = y1;
if (y2 > highest)
highest = y2;
else if (y2 < lowest)
lowest = y2;
if (y3 > highest)
highest = y3;
else if (y3 < lowest)
lowest = y3;
if (y4 > highest)
highest = y4;
else if (y4 < lowest)
lowest = y4;
if (localBoundingBox.Max.Y < lowest ||
localBoundingBox.Min.Y > highest)
continue;
//Now the local bounding box is very likely intersecting those of the triangles.
//Add the triangles to the list.
int quadIndex = (i + j * width) * 2;
overlappedElements.Add(quadIndex);
overlappedElements.Add(quadIndex + 1);
}
}
return overlappedElements.Count > 0;
}
19
Source : Pathfinding.cs
with Apache License 2.0
from Aggrathon
with Apache License 2.0
from Aggrathon
public LinkedList<PathFindNode> PathFind(PathFindNode start, PathFindNode target)
{
int width = nodes.GetLength(0);
int height = nodes.GetLength(1);
if (!Utils.InMargin(start.x, start.y, width, height, 1) || !Utils.InMargin(target.x, target.y, width, height, 1) || target == null || start == null)
return null;
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
if (nodes[i, j] != null)
nodes[i, j].Reset();
int jumpDistance = 1;
LinkedList<PathFindNode> queue = new LinkedList<PathFindNode>();
start.distance = 0;
queue.AddFirst(start);
while (queue.Count > 0)
{
PathFindNode current = queue.First.Value;
queue.RemoveFirst();
current.queueNode = null;
current.visited = true;
if (current == target)
{
LinkedList<PathFindNode> path = new LinkedList<PathFindNode>();
while (target != null)
{
path.AddFirst(target);
target = target.prevNode;
}
return path;
}
PathFindTryPath(current, nodes[current.x + jumpDistance, current.y], target, queue);
PathFindTryPath(current, nodes[current.x - jumpDistance, current.y], target, queue);
PathFindTryPath(current, nodes[current.x, current.y + jumpDistance], target, queue);
PathFindTryPath(current, nodes[current.x, current.y - jumpDistance], target, queue);
PathFindTryPath(current, nodes[current.x + jumpDistance, current.y + jumpDistance], target, queue);
PathFindTryPath(current, nodes[current.x + jumpDistance, current.y - jumpDistance], target, queue);
PathFindTryPath(current, nodes[current.x - jumpDistance, current.y + jumpDistance], target, queue);
PathFindTryPath(current, nodes[current.x - jumpDistance, current.y - jumpDistance], target, queue);
if (queue.Count > nodes.Length / 8)
{
return null;
}
}
return null;
}
19
Source : RoadGenerator.cs
with Apache License 2.0
from Aggrathon
with Apache License 2.0
from Aggrathon
public void Generate(float[,] heights, Vector3 terrainSize, Vector3 terrainPosition, float waterRelativeHeight)
{
int heightWidth = heights.GetLength(0);
System.Random rnd = new System.Random();
int pathFindingGraphSize = heightWidth / pathFindingSpacing - 2 * pathFindingGraphMargin;
Pathfinding.PathFindNode[,] nodes = new Pathfinding.PathFindNode[pathFindingGraphSize, pathFindingGraphSize];
for (int i = 1; i < pathFindingGraphSize - 1; i++)
{
for (int j = 1; j < pathFindingGraphSize - 1; j++)
{
float nodeHeight = heights[(i + pathFindingGraphMargin) * pathFindingSpacing, (j + pathFindingGraphMargin) * pathFindingSpacing];
if (nodeHeight > waterRelativeHeight + 0.03f)
nodes[i, j] = new Pathfinding.PathFindNode(i, j, nodeHeight);
}
}
Pathfinding pf = new Pathfinding(nodes, heightPenalty);
List<Pathfinding.PathFindNode> path = pf.GetRoad(numCheckpoints, rnd);
road.Clear();
for (int i = 0; i < path.Count; i++)
{
Vector3 pos = Vector3.Scale(terrainSize, path[i].GetLocalPosition(pathFindingGraphSize, pathFindingGraphSize, pathFindingGraphMargin)) + terrainPosition;
if (road.Count < 1 || Vector3.SqrMagnitude(pos - road[road.Count - 1]) > 1)
road.Add(pos);
}
}
19
Source : RoadGenerator.cs
with Apache License 2.0
from Aggrathon
with Apache License 2.0
from Aggrathon
public void DrawRoadHeights(float[,] heights, Vector3 terrainSize, Vector3 terrainPosition, int textureWidth)
{
int heightWidth = heights.GetLength(0);
int roadWidth = (int)((float)this.roadWidth * (float)heightWidth / (float)(textureWidth - 1)) + 3;
int px = 0;
int py = 0;
//Flag waypoints
RoadSmoothNode[,] smooths = new RoadSmoothNode[heightWidth, heightWidth];
for (int i = 0; i < road.Count; i++)
{
py = GetScalePosition(road[i].x, terrainSize.x, terrainPosition.x, heightWidth);
px = GetScalePosition(road[i].z, terrainSize.z, terrainPosition.z, heightWidth);
Drawing.DrawCircle(px, py, roadWidth + 2, (x, y) => {
smooths[x, y].AddNode(road[i], 1f);
});
Drawing.DrawCircle(px, py, roadWidth + 3, (x, y) => {
smooths[x, y].smooth = true;
});
}
//Flag roads
int prev = road.Count - 1;
for (int i = 0; i < road.Count; i++)
{
int hy = GetScalePosition(road[i].x, terrainSize.x, terrainPosition.x, heightWidth);
int hx = GetScalePosition(road[i].z, terrainSize.z, terrainPosition.z, heightWidth);
Drawing.DrawFatLine(hx, hy, px, py, roadWidth + 3, (x, y, pa, pb) => {
smooths[x, y].smooth = true;
}, false);
Drawing.DrawFatLine(hx, hy, px, py, roadWidth + 2, (x, y, pa, pb) => {
smooths[x, y].AddNode(road[prev], pa);
smooths[x, y].AddNode(road[i], pb);
}, true);
prev = i;
px = hx;
py = hy;
}
//Smooth and flatten
float scale = 1f / terrainSize.y;
for (int x = 0; x < heightWidth; x++)
for (int y = 0; y < heightWidth; y++)
smooths[x, y].CalculateRoads(heights, x, y, scale);
for (int x = 0; x < heightWidth; x++)
for (int y = 0; y < heightWidth; y++)
smooths[x, y].CalculateSmooth(heights, x, y);
for (int x = 0; x < heightWidth; x++)
for (int y = 0; y < heightWidth; y++)
smooths[x, y].ApplySmooth(heights, x, y);
}
See More Examples