Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
cadon committed Jan 1, 2024
2 parents ec41d0a + dcf02d1 commit 6f1680c
Show file tree
Hide file tree
Showing 28 changed files with 501 additions and 140 deletions.
10 changes: 10 additions & 0 deletions ARKBreedingStats/ARKBreedingStats.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
<Compile Include="library\CreatureSpawnCommand.cs" />
<Compile Include="library\DummyCreatures.cs" />
<Compile Include="multiplierTesting\CalculateMultipliers.cs" />
<Compile Include="NamePatterns\NameList.cs" />
<Compile Include="NamePatterns\NamePatternEntry.cs">
<SubType>Component</SubType>
</Compile>
Expand Down Expand Up @@ -666,6 +667,15 @@
<None Include="json\variantsDefaultUnselected.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<Content Include="json\creatureNamesF.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="json\creatureNamesM.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="json\creatureNamesU.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="_manifest.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>_manifest.json</LastGenOutput>
Expand Down
17 changes: 9 additions & 8 deletions ARKBreedingStats/AsbServer/Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public static async void StartListeningAsync(

try
{
using (var client = new HttpClient())
var client = FileService.GetHttpClient;
using (var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead))
{
if (!response.IsSuccessStatusCode)
Expand Down Expand Up @@ -186,16 +186,17 @@ public static async void SendCreatureData(Creature creature, string token)
{
if (creature == null || string.IsNullOrEmpty(token)) return;

using (var client = new HttpClient())
var client = FileService.GetHttpClient;

var contentString = Newtonsoft.Json.JsonConvert.SerializeObject(ImportExportGun.ConvertCreatureToExportGunFile(creature, out _));
var msg = new HttpRequestMessage(HttpMethod.Put, ApiUri + "export/" + token);
msg.Content = new StringContent(contentString, Encoding.UTF8, "application/json");
msg.Content.Headers.Add("Content-Length", contentString.Length.ToString());
using (var response = await client.SendAsync(msg))
{
var contentString = Newtonsoft.Json.JsonConvert.SerializeObject(ImportExportGun.ConvertCreatureToExportGunFile(creature, out _));
var msg = new HttpRequestMessage(HttpMethod.Put, ApiUri + "export/" + token);
msg.Content = new StringContent(contentString, Encoding.UTF8, "application/json");
msg.Content.Headers.Add("Content-Length", contentString.Length.ToString());
var response = await client.SendAsync(msg);
Console.WriteLine($"Sent creature data of {creature} using token: {token}\nContent:\n{contentString}");
Console.WriteLine(msg.ToString());
Console.WriteLine($"Response: Status: {(int)response.StatusCode}, ReasonPhrase: {response.ReasonPhrase}");
Console.WriteLine($"Response: StatusCode {(int)response.StatusCode}, ReasonPhrase: {response.ReasonPhrase}");
}
}

Expand Down
4 changes: 2 additions & 2 deletions ARKBreedingStats/BreedingPlanning/BreedingScore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ public static List<BreedingPair> CalculateBreedingScores(Creature[] females, Cre
{
if (s == Stats.Torpidity || !species.UsesStat(s)) continue;
bestPossLevels[s] = 0;
int higherLevel = Math.Max(female.levelsWild[s] + female.levelsMutated?[s] ?? 0, male.levelsWild[s] + male.levelsMutated?[s] ?? 0);
int lowerLevel = Math.Min(female.levelsWild[s] + female.levelsMutated?[s] ?? 0, male.levelsWild[s] + male.levelsMutated?[s] ?? 0);
int higherLevel = Math.Max(female.levelsWild[s] + (female.levelsMutated?[s] ?? 0), male.levelsWild[s] + (male.levelsMutated?[s] ?? 0));
int lowerLevel = Math.Min(female.levelsWild[s] + (female.levelsMutated?[s] ?? 0), male.levelsWild[s] + (male.levelsMutated?[s] ?? 0));
if (higherLevel < 0) higherLevel = 0;
if (lowerLevel < 0) lowerLevel = 0;
maxPossibleOffspringLevel += higherLevel;
Expand Down
16 changes: 16 additions & 0 deletions ARKBreedingStats/FileService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Serialization;

Expand Down Expand Up @@ -280,5 +281,20 @@ internal static bool IsValidJsonFile(string filePath)
//}
//catch { return false; }
}

private static HttpClient _httpClient;

/// <summary>
/// Returns a static HttpClient. It's apparently better to reuse on object per app only.
/// </summary>
public static HttpClient GetHttpClient
{
get
{
if (_httpClient == null)
_httpClient = new HttpClient();
return _httpClient;
}
}
}
}
17 changes: 10 additions & 7 deletions ARKBreedingStats/Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ private void Form1_Load(object sender, EventArgs e)
if (Properties.Settings.Default.LibraryShowMutationLevelColumns)
toolStripMenuItemMutationColumns.Checked = true;
else
ShowLibraryMutationLevels(false);
ToggleLibraryMutationLevelColumns(false);

_creatureListSorter.SortColumnIndex = Properties.Settings.Default.listViewSortCol;
_creatureListSorter.Order = Properties.Settings.Default.listViewSortAsc
Expand Down Expand Up @@ -1282,14 +1282,17 @@ private void Form1_FormClosed(object sender, FormClosedEventArgs e)
}

// Save column-widths, display-indices and sort-order of the TimerControlListView
SaveListViewSettings(timerList1.ListViewTimers, "TCLVColumnWidths", "TCLVColumnDisplayIndices", "TCLVSortCol", "TCLVSortAsc");
SaveListViewSettings(pedigree1.ListViewCreatures, "PedigreeListViewColumnWidths");
SaveListViewSettings(timerList1.ListViewTimers, nameof(Properties.Settings.TCLVColumnWidths),
nameof(Properties.Settings.TCLVColumnDisplayIndices), nameof(Properties.Settings.TCLVSortCol), nameof(Properties.Settings.TCLVSortAsc));
SaveListViewSettings(pedigree1.ListViewCreatures, nameof(Properties.Settings.PedigreeListViewColumnWidths));
Properties.Settings.Default.PedigreeWidthLeftColum = pedigree1.LeftColumnWidth;
SaveListViewSettings(tribesControl1.ListViewPlayers, "PlayerListColumnWidths", "PlayerListColumnDisplayIndices", "PlayerListSortColumn", "PlayerListSortAsc");
SaveListViewSettings(tribesControl1.ListViewPlayers, nameof(Properties.Settings.PlayerListColumnWidths),
nameof(Properties.Settings.PlayerListColumnDisplayIndices), nameof(Properties.Settings.PlayerListSortColumn), nameof(Properties.Settings.PlayerListSortAsc));

// Save column-widths, display-indices and sort-order of the listViewLibrary
ShowLibraryMutationLevels(true); // restore collapsed column widths before saving
SaveListViewSettings(listViewLibrary, "columnWidths", "libraryColumnDisplayIndices");
if (!Properties.Settings.Default.LibraryShowMutationLevelColumns)
ToggleLibraryMutationLevelColumns(true); // restore collapsed column widths before saving
SaveListViewSettings(listViewLibrary, nameof(Properties.Settings.columnWidths), nameof(Properties.Settings.libraryColumnDisplayIndices));
Properties.Settings.Default.listViewSortCol = _creatureListSorter.SortColumnIndex;
Properties.Settings.Default.listViewSortAsc = _creatureListSorter.Order == SortOrder.Ascending;

Expand Down Expand Up @@ -2089,7 +2092,7 @@ private void SetupExportFileWatcher()
if (_fileWatcherExports == null)
{
_fileWatcherExports =
new FileWatcherExports(exportFolderDefault, ImportExportedAddIfPossible_WatcherThread);
new FileWatcherExports(exportFolderDefault, ImportExportedFileChanged, this);
}
else
{
Expand Down
5 changes: 3 additions & 2 deletions ARKBreedingStats/Form1.extractor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,9 @@ private bool ExtractLevels(bool autoExtraction = false, bool statInputsHighPreci
}

// get mean-level (most probable for the wild levels)
// TODO handle species without wild levels in speed better (some flyers)
double meanWildLevel = Math.Round((double)_extractor.LevelWildSum / 7, 1);
var statsWithLevels = Enumerable.Range(0, Stats.StatsCount).Aggregate(0,
(c, s) => c += s != Stats.Torpidity && speciesSelector1.SelectedSpecies.CanLevelUpWildOrHaveMutations(s) ? 1 : 0);
double meanWildLevel = Math.Round((double)_extractor.LevelWildSum / statsWithLevels, 1);
bool nonUniqueStats = false;

for (int s = 0; s < Stats.StatsCount; s++)
Expand Down
12 changes: 7 additions & 5 deletions ARKBreedingStats/Form1.importExported.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,16 +166,18 @@ private void ExportedCreatureList_CopyValuesToExtractor(importExported.ExportedC
}
}

private void ImportExportedAddIfPossible_WatcherThread(string filePath, importExported.FileWatcherExports fwe)
/// <summary>
/// The fileWatcher detected a new or changed file in the watched folder.
/// </summary>
private void ImportExportedFileChanged(string filePath, importExported.FileWatcherExports fwe)
{
fwe.Watching = false;
// wait a moment until the file is readable. why is this necessary? blocked by fileWatcher?
// wait a moment until the file is fully written
System.Threading.Thread.Sleep(200);

// moving to the archived folder can trigger another fileWatcherEvent, first check if the file is still there
// moving a file to the archived folder can trigger another fileWatcherEvent, first check if the file is still there
if (File.Exists(filePath))
// fileWatcher is on another thread, invoke ui-thread to work with ui
Invoke(new Action(delegate { ImportExportedAddIfPossible(filePath); }));
ImportExportedAddIfPossible(filePath);

fwe.Watching = true;
}
Expand Down
46 changes: 25 additions & 21 deletions ARKBreedingStats/Form1.library.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using ARKBreedingStats.importExportGun;
using ARKBreedingStats.library;
using ARKBreedingStats.settings;

Expand Down Expand Up @@ -2076,12 +2077,12 @@ private void resetColumnWidthNoMutationLevelColumnsToolStripMenuItem_Click(objec

private void restoreMutationLevelsASAToolStripMenuItem_Click(object sender, EventArgs e)
{
LibraryColumnsMutationsWidth(false);
ToggleLibraryMutationLevelColumns(true, true);
}

private void collapseMutationsLevelsASEToolStripMenuItem_Click(object sender, EventArgs e)
{
LibraryColumnsMutationsWidth(true);
ToggleLibraryMutationLevelColumns(false);
}

private void ResetColumnWidthListViewLibrary(bool mutationColumnWidthsZero)
Expand All @@ -2093,46 +2094,49 @@ private void ResetColumnWidthListViewLibrary(bool mutationColumnWidthsZero)
: ci < ColumnIndexFirstStat || ci >= ColumnIndexPostColor ? 60
: ci >= ColumnIndexFirstStat + Stats.StatsCount + Stats.StatsCount ? 30 // color
: ci < ColumnIndexFirstStat + Stats.StatsCount ? statWidths[ci - ColumnIndexFirstStat] // wild levels
: ci - ColumnIndexFirstStat - Stats.StatsCount == Stats.Torpidity ? 0 // no mutations for torpidity
: (int)(statWidths[ci - ColumnIndexFirstStat - Stats.StatsCount] * 1.24); // mutated needs space for one more letter

if (mutationColumnWidthsZero)
LibraryColumnsMutationsWidth(true);
// save in settings so it can be used when toggle the mutation columns, which use the settings
var widths = new int[listViewLibrary.Columns.Count];
for (int c = 0; c < widths.Length; c++)
widths[c] = listViewLibrary.Columns[c].Width;
Properties.Settings.Default.columnWidths = widths;

listViewLibrary.EndUpdate();
}
if (mutationColumnWidthsZero)
ToggleLibraryMutationLevelColumns(false);

/// <summary>
/// Set width of mutation level columns to zero or restore.
/// </summary>
private void LibraryColumnsMutationsWidth(bool collapse)
{
listViewLibrary.BeginUpdate();
var statWidths = Stats.UsuallyVisibleStats.Select(w => !collapse && w ? 38 : 0).ToArray();
for (int c = 0; c < Stats.StatsCount; c++)
{
listViewLibrary.Columns[c + ColumnIndexFirstStat + Stats.StatsCount].Width = statWidths[c];
}
listViewLibrary.EndUpdate();
}

private void toolStripMenuItemMutationColumns_CheckedChanged(object sender, EventArgs e)
{
var showMutationColumns = toolStripMenuItemMutationColumns.Checked;
Properties.Settings.Default.LibraryShowMutationLevelColumns = showMutationColumns;
ShowLibraryMutationLevels(showMutationColumns);
ToggleLibraryMutationLevelColumns(showMutationColumns);
}

/// <summary>
/// Set width of library mutation level columns to 0 or restore.
/// </summary>
private void ShowLibraryMutationLevels(bool show)
private void ToggleLibraryMutationLevelColumns(bool show, bool resetWidth = false)
{
var widths = Properties.Settings.Default.columnWidths;
if (widths == null || widths.Length < ColumnIndexFirstStat + 2 * Stats.StatsCount) return;

if (widths == null || widths.Length < ColumnIndexFirstStat + 2 * Stats.StatsCount)
{
SaveListViewSettings(listViewLibrary, nameof(Properties.Settings.columnWidths), nameof(Properties.Settings.libraryColumnDisplayIndices));
widths = Properties.Settings.Default.columnWidths;
}

listViewLibrary.BeginUpdate();
if (show)
{
if (resetWidth)
{
var mutationStatWidths = Stats.UsuallyVisibleStats.Select((v, i) => v && i != Stats.Torpidity ? 37 : 0).ToArray();
mutationStatWidths.CopyTo(widths, ColumnIndexFirstStat + Stats.StatsCount);
}

for (int ci = ColumnIndexFirstStat + Stats.StatsCount; ci < ColumnIndexFirstStat + 2 * Stats.StatsCount; ci++)
listViewLibrary.Columns[ci].Width = widths[ci];
}
Expand Down
70 changes: 70 additions & 0 deletions ARKBreedingStats/NamePatterns/NameList.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ARKBreedingStats.NamePatterns
{
/// <summary>
/// Loads a list of names from a file.
/// </summary>
internal static class NameList
{
/// <summary>
/// Contains all name lists, key is the fileName suffix.
/// </summary>
private static readonly Dictionary<string, string[]> nameLists = new Dictionary<string, string[]>();
private static readonly Dictionary<string, DateTime> listFileCheckedAt = new Dictionary<string, DateTime>();

/// <summary>
/// Returns a name from a list. If the file wasn't checked recently, it's checked and reloaded.
/// </summary>
public static string GetName(int nameIndex = 0, string listSuffix = null)
{
if (nameIndex < 0) return null;
var nameList = GetNameList(listSuffix);
if (nameList == null || nameList.Length == 0) return null;

if (nameIndex >= nameList.Length)
nameIndex %= nameList.Length;
return nameList[nameIndex];
}

/// <summary>
/// Returns a name list.
/// </summary>
public static string[] GetNameList(string listSuffix = null)
{
if (listSuffix == null) listSuffix = string.Empty;
string[] list;
if (!listFileCheckedAt.TryGetValue(listSuffix, out var checkedAt)
|| (DateTime.Now - checkedAt).TotalSeconds > 10
|| !nameLists.TryGetValue(listSuffix, out list))
{
list = LoadList(listSuffix, checkedAt);
}
return list;
}

private static string[] LoadList(string listSuffix, DateTime checkedAt)
{
var filePath = FileService.GetJsonPath("creatureNames" + listSuffix + ".txt");

if (!File.Exists(filePath)) return null;
try
{
if (new FileInfo(filePath).LastWriteTime > checkedAt)
{
var list = File.ReadAllLines(filePath);
nameLists[listSuffix] = list;
}
listFileCheckedAt[listSuffix] = DateTime.Now;
return nameLists[listSuffix];
}
catch { }
return null;
}
}
}
7 changes: 3 additions & 4 deletions ARKBreedingStats/NamePatterns/NamePattern.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public static class NamePattern
/// </summary>
private const string PipeEscapeSequence = @"\pipe";

public static Random Random = new Random();

/// <summary>
/// Generate a creature name with the naming pattern.
/// </summary>
Expand Down Expand Up @@ -203,9 +205,6 @@ public static Dictionary<string, string> CreateTokenDictionary(Creature creature
double imp = creature.imprintingBonus * 100;
double eff = creature.tamingEff * 100;

Random rand = new Random(DateTime.Now.Millisecond);
string randStr = rand.Next(0, 999999).ToString("000000");

string effImp = "Z";
string prefix = string.Empty;
if (creature.isBred)
Expand Down Expand Up @@ -332,7 +331,7 @@ public static Dictionary<string, string> CreateTokenDictionary(Creature creature
{ "genn", (speciesCreatures?.Count(c=>c.generation==generation) ?? 0 + 1).ToString()},
{ "nr_in_gen", nrInGeneration.ToString()},
{ "nr_in_gen_sex", nrInGenerationAndSameSex.ToString()},
{ "rnd", randStr },
{ "rnd", Random.Next(0, 999999).ToString("000000")},
{ "ln", libraryCreatureCount.ToString()},
{ "tn", speciesCount.ToString()},
{ "sn", speciesSexCount.ToString()},
Expand Down
Loading

0 comments on commit 6f1680c

Please sign in to comment.