Skip to content

Commit

Permalink
refactor storage of priorities
Browse files Browse the repository at this point in the history
Completely reworked how priorities are stored. Instead of using defmaps where only the priorities are stored and the workgiverdefs are assumed to stay constant, we now store a list of workgiverdefs with the priorities to ascertain ordering, and match priorities to current workgiverdefs upon loading.

In addition, we no longer use a list of lists for storing priorities, but a much more compressed block of digits per pawn, where each line is an hour and each column a workgiver.

Migrating from the old to new format is done by setting a 'newFormat' flag in the save game, and should work out-of-the-box.
  • Loading branch information
FluffierThanThou committed Feb 8, 2017
1 parent 144abd4 commit b7cf412
Show file tree
Hide file tree
Showing 9 changed files with 223 additions and 43 deletions.
Binary file modified Assemblies/Fluffy_Tabs.dll
Binary file not shown.
83 changes: 50 additions & 33 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,29 @@
Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
The following MIT license applies to the software and any documentation.
Any original content (e.g. text, imagery or sounds) are licensed under
CC-BY-SA 4.0, the text of which is given below.
=======================================================================

Copyright 2017 Fluffy

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.






=======================================================================
The following CC BY-SA 4.0 license applies to any original content. The
software and documentation are licensed under the MIT license, the text
of which is given above.
=======================================================================

Attribution-ShareAlike 4.0 International

=======================================================================

Expand Down Expand Up @@ -54,18 +79,18 @@ exhaustive, and do not form part of our licenses.

=======================================================================

Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Public License
Creative Commons Attribution-ShareAlike 4.0 International Public
License

By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International Public License
("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.


Section 1 -- Definitions.
Expand All @@ -84,7 +109,7 @@ Section 1 -- Definitions.
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.

c. BY-NC-SA Compatible License means a license listed at
c. BY-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.

Expand All @@ -108,7 +133,7 @@ Section 1 -- Definitions.

g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution, NonCommercial, and ShareAlike.
Public License are Attribution and ShareAlike.

h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
Expand All @@ -122,29 +147,21 @@ Section 1 -- Definitions.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.

k. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.

l. Share means to provide material to the public by any means or
k. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.

m. Sui Generis Database Rights means rights other than copyright
l. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.

n. You means the individual or entity exercising the Licensed Rights
m. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.


Expand All @@ -158,10 +175,9 @@ Section 2 -- Scope.
exercise the Licensed Rights in the Licensed Material to:

a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
in part; and

b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
b. produce, reproduce, and Share Adapted Material.

2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
Expand Down Expand Up @@ -229,9 +245,7 @@ Section 2 -- Scope.
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
reserves any right to collect such royalties.


Section 3 -- License Conditions.
Expand Down Expand Up @@ -276,6 +290,7 @@ following conditions.
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.

3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
Expand All @@ -287,7 +302,7 @@ following conditions.

1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-NC-SA Compatible License.
later, or a BY-SA Compatible License.

2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
Expand All @@ -307,15 +322,14 @@ apply to Your use of the Licensed Material:

a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
portion of the contents of the database;

b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and

including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.

Expand Down Expand Up @@ -415,6 +429,7 @@ Section 8 -- Interpretation.
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.


=======================================================================

Creative Commons is not a party to its public
Expand All @@ -435,3 +450,5 @@ the avoidance of doubt, this paragraph does not form part of the
public licenses.

Creative Commons may be contacted at creativecommons.org.

0Trackers
7 changes: 5 additions & 2 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ Please read [this guide](http://steamcommunity.com/sharedfiles/filedetails/?id=7
All current and past versions of this mod can be downloaded from [GitHub](https://github.com/FluffierThanThou/WorkTab/releases).

# License
This mod is licensed under the Creative Commons [by-nc-sa 4.0 Int](http://creativecommons.org/licenses/by-nc-sa/4.0/) license.
All original code in this mod is licensed under the [MIT license](https://opensource.org/licenses/MIT). Do what you want, but give me credit.
All original content (e.g. text, imagery, sounds) in this mod is licensed under the [CC-BY-SA 4.0 license](http://creativecommons.org/licenses/by-sa/4.0/).

Parts of the code in this mod, and some content may be licensed by their original authors. If this is the case, the original author & license will either be given in the source code, or be in a LICENSE file next to the content. Please do not decompile my mods, but use the original source code available on [GitHub](https://github.com/FluffierThanThou/WorkTab/), so license information in the source code is preserved.

# Version
This is version v0.16.1.8
This is version v0.16.1.9
15 changes: 15 additions & 0 deletions Source/Fluffy_Tabs/Core/Controller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@ namespace Fluffy_Tabs
public class Controller : ModBase
{
public override string ModIdentifier => "WorkTab";
private static ModLogger _logger;

public Controller() : base() { _logger = base.Logger; }

#region Overrides of ModBase

public override void DefsLoaded()
{
base.DefsLoaded();
WorldObject_Priorities.OnDefsLoaded();
}

#endregion

public new static ModLogger Logger => _logger;

public override void MapLoaded( Map map )
{
Expand Down
20 changes: 20 additions & 0 deletions Source/Fluffy_Tabs/Core/DefMap_Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Karel Kroeze
// DefMap_Extensions.cs
// 2017-02-07

using Verse;

namespace Fluffy_Tabs
{
public static class DefMap_Extensions
{
public static string GetIntString<T>( this DefMap<T, int> defMap ) where T : Def, new()
{
string[] msg = new string[defMap.Count];
for ( var i = 0; i < defMap.Count; i++ )
msg[i] = defMap[i].ToString();

return string.Join( "", msg );
}
}
}
1 change: 1 addition & 0 deletions Source/Fluffy_Tabs/Fluffy_Tabs.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Core\Controller.cs" />
<Compile Include="Core\DefMap_Extensions.cs" />
<Compile Include="Core\Widgets_UI_TextureChooser.cs" />
<Compile Include="Work\Detours_WorkSettings.cs" />
<Compile Include="Work\Dialog_CreateFavourite.cs" />
Expand Down
78 changes: 74 additions & 4 deletions Source/Fluffy_Tabs/Work/PawnPrioritiesTracker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using HugsLib.Utils;
using UnityEngine;
using Verse;
using static Fluffy_Tabs.Controller;

namespace Fluffy_Tabs
{
Expand All @@ -17,6 +19,9 @@ public class PawnPrioritiesTracker : IExposable
private DefMap<WorkGiverDef, bool> _timeDependentCache = new DefMap<WorkGiverDef, bool>();
private Dictionary<WorkGiverDef, string> _timeDependentTipCache = new Dictionary<WorkGiverDef, string>();
private List<DefMap<WorkGiverDef, int>> priorities = new List<DefMap<WorkGiverDef, int>>();
private bool newFormat = true;

private string _prioritiesScribeHelper;

#endregion Fields

Expand All @@ -36,6 +41,9 @@ public PawnPrioritiesTracker( Pawn pawn )

private void InitPriorityCache()
{
// create fresh list (just to be sure).
priorities = new List<DefMap<WorkGiverDef, int>>();

// initialize from vanilla priorities.
var vanillaPriorities = Detours_WorkSettings.GetVanillaPriorities( pawn );

Expand Down Expand Up @@ -70,15 +78,77 @@ public void AssignFavourite( WorkFavourite favourite )
public void ExposeData()
{
Scribe_References.LookReference( ref pawn, "pawn" );
Scribe_Collections.LookList( ref priorities, "priorities", LookMode.Deep );
Scribe_References.LookReference( ref currentFavourite, "currentFavourite" );

// handle priorities, first try to see what style the old save was in.
// note that while saving, newFormat is set to true. While loading,
// it defaults to false. The value of newFormat should be immediately available.
if ( Scribe.mode == LoadSaveMode.Saving )
newFormat = true;
Scribe_Values.LookValue( ref newFormat, "newFormat", false );
//Controller.Logger.Message( "Loading priorities from {1} format save: {0}", Scribe.mode,
// newFormat ? "NEW" : "OLD" );
if ( newFormat )
{
switch ( Scribe.mode )
{
case LoadSaveMode.Saving:
// this one is fairly straightforward, create string block that has one line per hour and just joins all the priorities
// note; this means a hard requirement for priorities to be single digits.
_prioritiesScribeHelper = priorities.Select(m => m.GetIntString()).Join("\n");
Scribe_Values.LookValue(ref _prioritiesScribeHelper, "priorities", string.Empty, true);
break;
case LoadSaveMode.LoadingVars:
// just read out the string block, we'll process it in the PostLoadInit
Scribe_Values.LookValue(ref _prioritiesScribeHelper, "priorities", string.Empty, true);
break;
case LoadSaveMode.PostLoadInit:
// create priorities data, and fill with defaults
InitPriorityCache();

// fill in saved priorities
LoadPrioritiesFromString();
break;
}
}
else
{
// fall back to old style
Scribe_Collections.LookList(ref priorities, "priorities", LookMode.Deep);
}

// clear tip cache so it gets rebuild after load
if ( Scribe.mode == LoadSaveMode.PostLoadInit )
foreach ( var workgiver in DefDatabase<WorkGiverDef>.AllDefsListForReading )
_cacheDirty[workgiver] = true;
}

private void LoadPrioritiesFromString()
{
// fetch priorities from the string block
List<List<int>> _priorities = _prioritiesScribeHelper
// first off, split the lines to get a string per hour
.Split( "\n".ToCharArray() )
// split lines into individual priorities
.Select( IntsFromString ).ToList();

// fill priority tracker
foreach ( WorkGiverDef workgiver in DefDatabase<WorkGiverDef>.AllDefsListForReading )
{
int savedWorkgiverIndex = WorldObject_Priorities.GetSavedWorkgiverIndex( workgiver );
if ( savedWorkgiverIndex >= 0 )
for ( int hour = 0; hour < GenDate.HoursPerDay; hour++ )
priorities[hour][workgiver] = _priorities[hour][savedWorkgiverIndex];
}
}

private List<int> IntsFromString( string line )
{
return line.ToCharArray() // break into individual characters
.Select( c => int.Parse( c.ToString() ) ) // parse as ints
.ToList();
}

public int GetPriority( WorkGiverDef workgiver )
{
return GetPriority( workgiver, GenLocalDate.HourOfDay( pawn.Map ) );
Expand All @@ -96,13 +166,13 @@ public int GetPriority( WorkGiverDef workgiver, int hour )

// force priority back to 0.
priority = 0;
SetPriority( workgiver, 0, hour );
SetPriority( workgiver, priority, hour );
}
return priority;
}
catch ( ArgumentOutOfRangeException )
{
// workgiver-priority defmap is really just and ordered list indexed by a dynamically generated workgiver index int
// workgiver-priority defmap is really just an ordered list indexed by a dynamically generated workgiver index int
// if the number of workgivers increases, this means errors.
Messages.Message( "WorkGiver database corrupted, resetting priorities for " + pawn.NameStringShort + ". Did you add mods during the game?", MessageSound.SeriousAlert );
priorities = new List<DefMap<WorkGiverDef, int>>();
Expand All @@ -115,7 +185,7 @@ public int GetPriority( WorkGiverDef workgiver, int hour )
public int GetPriority( WorkTypeDef worktype, int hour = -1 )
{
// get current hour if left default
// check if pawn has a registered Map we can use for the local time (99%) of cases.
// check if pawn has a registered Map we can use for the local time (99% of cases).
if ( hour < 0 && pawn?.Map != null )
hour = GenLocalDate.HourOfDay( pawn.Map );
// if not, try use the visible map
Expand Down
Loading

0 comments on commit b7cf412

Please sign in to comment.