Skip to content

Commit

Permalink
Improved project structure and bumped toc version
Browse files Browse the repository at this point in the history
  • Loading branch information
Koward committed Jan 11, 2020
1 parent 3843253 commit c201564
Show file tree
Hide file tree
Showing 12 changed files with 165 additions and 100 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
CreatureFactionInfo.lua
Factions.lua
enUS/FactionInfo.lua
__pycache__/
9 changes: 6 additions & 3 deletions Core.lua
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
local folderName, _ = ...
local folderName, L = ...
local addonName = folderName

function UnitFlavorFaction(unit)
Expand Down Expand Up @@ -63,15 +63,18 @@ GameTooltip:HookScript("OnTooltipSetUnit", function()
local type, _, _, _, _, _, _ = string.split("-", guid)
if type == "Creature" then
local factionID = UnitFlavorFaction(unitType)
if not factionID then
return
end
local faction = Factions[factionID] -- GetFactionInfoByID(factionID) does not work for enemy factions
if factionID and ShouldFactionBeAdded(faction) then
if faction and ShouldFactionBeAdded(faction) then
-- Find line that starts with "Level" and insert faction after
local levelIndex = FindLine(tooltip, function(line)
return string.sub(line, 1, #"Level") == "Level"
end)
local faction_color = TOOLTIP_DEFAULT_COLOR
if not levelIndex or levelIndex == tooltip:NumLines() then
tooltip:AddLine(faction.name, faction_color.r, faction_color.g, faction_color.b)
tooltip:AddLine(L[faction.name.."_Name"], faction_color.r, faction_color.g, faction_color.b)
else
local faction_index = levelIndex + 1
InsertLine(tooltip, faction_index, faction.name, faction_color.r, faction_color.g, faction_color.b)
Expand Down
4 changes: 2 additions & 2 deletions Factions.csv
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Leopard,,55,1,0
Scarlet Crusade,,56,0,0
Gnoll - Rothide,,57,0,0
Beast - Gorilla,,58,1,0
Thorium Brotherhood,The dwarves of the Thorium Brotherhood epitomize excellence in craftsmanship and are bent on unlocking the secrets of Blackrock Mountain.,59,0,0
Thorium Brotherhood,The dwarves of the Thorium Brotherhood epitomize excellence in craftsmanship and are bent on unlocking the secrets of Blackrock Mountain.,59,0,1
Naga,,60,0,0
Dalaran,,61,0,0
Forlorn Spirit,,62,1,0
Expand Down Expand Up @@ -158,7 +158,7 @@ Training Dummy,,679,1,0
Battleground Neutral,,709,1,0
Frostwolf Clan,The Frostwolf Clan seeks to drive out the dwarves of the Stormpike Expedition from Alterac Valley.,729,0,2
Stormpike Guard,"The Stormpike Dwarves have set up residence in Alterac Valley, where they're locked in battle with the Frostwolf Orcs.",730,0,3
Hydraxian Waterlords,These elementals have made their home on the islands east of Azshara. Sworn enemies of the armies of Ragnaros.,749,0,0
Hydraxian Waterlords,These elementals have made their home on the islands east of Azshara. Sworn enemies of the armies of Ragnaros.,749,0,1
Sulfuron Firelords,,750,0,0
Gizlock's Dummy,,769,1,0
Gizlock's Charm,,770,1,0
Expand Down
4 changes: 4 additions & 0 deletions FixesCreatureFactionInfo.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
ID,UnitName,FactionName,FactionID
3394,Barak Kodobane,"Centaur, Kolkar",90
3395,Verog the Dervish,"Centaur, Kolkar",90
3396,Hezrul Bloodmark,"Centaur, Kolkar",90
6 changes: 3 additions & 3 deletions FlavorFactions.toc
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
## Interface: 11303
## Title: FlavorFactions
## Notes: See all factions
## Version: 1.0
## Version: 1.0.1
## Author: Koward

Factions.lua
enUS/CustomFactionInfo.lua
frFR/CustomFactionInfo.lua
enUS/FactionInfo.lua
enUS/FixesFactionInfo.lua

CreatureFactionInfo.lua

Expand Down
26 changes: 26 additions & 0 deletions build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from FlavorFactions.common import merge_update_csv_files
from FlavorFactions.generate_CreatureFactionInfo import generate_creature_faction_info_lua
from FlavorFactions.generate_Factions import generate_factions_lua, generate_faction_info_lua, get_base_neutral_factions

# Base neutral factions (e.g Booty Bay) are always displayed for characters already.
# So no need to handle them ourselves => we can decrease AddOn size!
base_neutral_factions = get_base_neutral_factions('Factions.csv')

# Unfortunately, GetFactionInfoByGroupID does not return data for opposite faction reputations so we store them here.
factions_csv_files = [
'Factions.csv'
]
factions_df = merge_update_csv_files(factions_csv_files, 'ID')
factions_df.ID = factions_df.ID.astype(int)
factions_df = factions_df[~factions_df.ID.isin(base_neutral_factions)]
generate_factions_lua('Factions.lua', factions_df)
generate_faction_info_lua('enUS/FactionInfo.lua', factions_df)

creature_csv_files = [
'CreatureFactionInfo.csv',
'FixesCreatureFactionInfo.csv'
]
creature_faction_info_df = merge_update_csv_files(creature_csv_files, 'ID')
creature_faction_info_df.FactionID = creature_faction_info_df.FactionID.astype(int)
creature_faction_info_df = creature_faction_info_df[~creature_faction_info_df.FactionID.isin(base_neutral_factions)]
generate_creature_faction_info_lua('CreatureFactionInfo.lua', creature_faction_info_df)
29 changes: 29 additions & 0 deletions common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from _csv import register_dialect
from stat import S_IREAD, S_IRGRP, S_IROTH, S_IWUSR

import pandas as pd


class excel_backslash(csv.excel):
"""Standard excel dialect that support backslash character."""
Expand All @@ -13,9 +15,36 @@ class excel_backslash(csv.excel):


def unlock_file(filename):
"""Ensures the file can be written to."""
if os.path.exists(filename):
os.chmod(filename, S_IWUSR | S_IREAD)


def lock_file(filename):
"""Prevents file from being accidentally edited."""
os.chmod(filename, S_IREAD | S_IRGRP | S_IROTH)


def merge_update_csv_files(csv_files, primary_key):
"""
From multiple csv files, apply them on top of each other.
Based on primary key, matching entries are overriden while new ones are added.
:param csv_files: A list of CSV files paths.
:param primary_key: Primary key string used to match entries between themselves.
:return: Merged dataframe.
"""
final_df = None
for csv_path in csv_files:
# pd.read_csv seems to crash because of entries with backslashes, so this is a workaround
with open(csv_path, 'r', encoding='UTF-8-sig', newline='') as csv_file:
df = pd.DataFrame(csv.reader(csv_file, dialect="excel-backslash"))
# Set first row as column names
df.columns = df.iloc[0]
df = df[1:]

if final_df is None:
final_df = df
else:
final_df = pd.concat([final_df, df], keys=primary_key, sort=False).drop_duplicates(subset=primary_key,
keep="last")
return final_df
38 changes: 0 additions & 38 deletions enUS/CustomFactionInfo.lua

This file was deleted.

37 changes: 37 additions & 0 deletions enUS/FixesFactionInfo.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
local _, L = ...
-- Improved faction names that are consistent with already existing ones

L["Gnoll - Riverpaw_Name"] = "Riverpaw Gnolls"
L["Gnoll - Redridge_Name"] = "Redridge Gnolls"
L["Gnoll - Shadowhide_Name"] = "Shadowhide Gnolls"
L["Undead, Scourge_Name"] = "Scourge"
L["Troll, Bloodscalp_Name"] = "Bloodscalp Trolls"
L["Troll, Skullsplitter_Name"] = "Skullsplitter Trolls"
L["Troll, Frostmane_Name"] = "Frostmane Trolls"
L["Orc, Blackrock_Name"] = "Blackrock Clan"
L["Dragonflight, Green_Name"] = "Green Dragonflight"
L["Human, Night Watch_Name"] = "Night Watch"
L["Dragonflight, Red_Name"] = "Red Dragonflight"
L["Gnoll - Mosshide_Name"] = "Mosshide Gnolls"
L["Orc, Dragonmaw_Name"] = "Dragonmaw Clan"
L["Gnome - Leper_Name"] = "Leper Gnomes"
L["Gnoll - Rothide_Name"] = "Rothide Gnolls"
L["Gnoll - Mudsnout_Name"] = "Mudsnout Gnolls"
L["Dragonflight, Black_Name"] = "Black Dragonflight"
L["Troll, Witherbark_Name"] = "Witherbark Trolls"
L["Quilboar, Razormane_Name"] = "Razormane Quillboars"
L["Quilboar, Bristleback_Name"] = "Bristleback Quillboars"
L["Centaur, Kolkar_Name"] = "Kolkar Clan Centaur"
L["Centaur, Galak_Name"] = "Galak Clan Centaur"
L["Quilboar, Razorfen_Name"] = "Razorfen Quillboars"
L["Quilboar, Razormane 2_Name"] = "Razormane Quillboars"
L["Quilboar, Deathshead_Name"] = "Deathshead Quillboars"
L["Dragonflight, Bronze_Name"] = "Bronze Dragonflight"
L["Dragonflight, Blue_Name"] = "Blue Dragonflight"
L["Troll, Vilebranch_Name"] = "Vilebranch Trolls"






5 changes: 0 additions & 5 deletions frFR/CustomFactionInfo.lua

This file was deleted.

41 changes: 10 additions & 31 deletions generate_CreatureFactionInfo.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,18 @@
import csv
import pandas as pd

from FlavorFactions.common import unlock_file, lock_file

# Base neutral factions (e.g Booty Bay) are always displayed for characters already.
# So no need to handle them ourselves => we can decrease AddOn size!
base_neutral_factions = set()
with open('Factions.csv', 'r', encoding='UTF-8-sig', newline='') as csv_file:
reader = csv.DictReader(csv_file, dialect="excel-backslash")
for row in reader:
try:
faction_id = int(row['ID'])
if int(row['BaseFaction']) == 1:
base_neutral_factions.add(faction_id)
except ValueError:
print(f"Invalid row: {row}")

LUA_FILE_PATH = 'CreatureFactionInfo.lua'
def generate_creature_faction_info_lua(lua_file_path, creature_faction_info_df):
creature_faction_info_df = creature_faction_info_df.apply(lambda row: f"F[{row.ID}] = {row.FactionID}", axis=1)
pd.set_option("display.max_colwidth", 10000) # disable truncation

unlock_file(LUA_FILE_PATH)

with open(LUA_FILE_PATH, 'w', encoding='UTF-8') as lua_file:
luaHeader = """-- *** DO NOT EDIT. THIS IS A GENERATED FILE. ***
unlock_file(lua_file_path)
with open(lua_file_path, 'w', encoding='UTF-8') as lua_file:
lua_header = """-- *** DO NOT EDIT. THIS IS A GENERATED FILE. ***
--- Format: F[ID] = <factionID>
CreatureFactionInfo = {}
local F = CreatureFactionInfo\n"""
lua_file.write(luaHeader)
with open('CreatureFactionInfo.csv', 'r', encoding='UTF-8-sig', newline='') as csv_file:
reader = csv.DictReader(csv_file, dialect="excel-backslash")
for row in reader:
try:
unit_id = int(row['ID'])
faction_id = int(row['FactionID'])
if faction_id not in base_neutral_factions:
lua_file.write(f'F[{unit_id}] = {faction_id}\n')
except ValueError:
print(f"Invalid row: {row}")

lock_file(LUA_FILE_PATH)
lua_file.write(lua_header)
creature_faction_info_df.to_string(buf=lua_file, index=False)
lock_file(lua_file_path)
65 changes: 47 additions & 18 deletions generate_Factions.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,59 @@
import csv

import pandas as pd

from FlavorFactions.common import unlock_file, lock_file

# Unfortunately, GetFactionInfoByGroupID does not return data for opposite faction reputations so we store them here.

LUA_FILE_PATH = 'Factions.lua'
unlock_file(LUA_FILE_PATH)
def generate_factions_lua(lua_file_path, factions_df):
def lua_assignation(row):
return f'F[{row.ID}] = {{name="{row.Name_lang}", isGameplayOnly={"true" if row.GameplayOnly == "1" else "false"}, isBaseFaction={row.BaseFaction}}}'

factions_df = factions_df.apply(lua_assignation, axis=1)

unlock_file(lua_file_path)

with open(lua_file_path, 'w', encoding='UTF-8') as lua_file:
lua_header = """-- *** DO NOT EDIT. THIS IS A GENERATED FILE. ***
Factions = {}
local F = Factions\n"""
lua_file.write(lua_header)
pd.set_option("display.max_colwidth", 10000) # disable truncation
factions_df.to_string(buf=lua_file, index=False)

lock_file(lua_file_path)


with open(LUA_FILE_PATH, 'w', encoding='UTF-8') as lua_file:
luaHeader = """-- *** DO NOT EDIT. THIS IS A GENERATED FILE. ***
Factions = {}
local F = Factions\n"""
lua_file.write(luaHeader)
with open('Factions.csv', 'r', encoding='UTF-8-sig', newline='') as csv_file:
def generate_faction_info_lua(lua_file_path, factions_df):
names_df = factions_df[factions_df.Name_lang != ""].apply(
lambda row: f'L["{row.Name_lang}_Name"] = "{row.Name_lang}"', axis=1
)

unlock_file(lua_file_path)

with open(lua_file_path, 'w', encoding='UTF-8') as lua_file:
lua_header = """-- *** DO NOT EDIT. THIS IS A GENERATED FILE. ***
local _, L = ...\n"""
lua_file.write(lua_header)
pd.set_option("display.max_colwidth", 10000) # disable truncation
names_df.to_string(buf=lua_file, index=False)

lock_file(lua_file_path)


def get_base_neutral_factions(factions_csv_path):
"""
:param factions_csv_path: Path to CSV file with factions
:return: A set of integer faction IDs of neutral factions present in base World of Warcraft.
"""
factions = set()
with open(factions_csv_path, 'r', encoding='UTF-8-sig', newline='') as csv_file:
reader = csv.DictReader(csv_file, dialect="excel-backslash")
for row in reader:
try:
faction_id = int(row['ID'])
faction_name = row['Name_lang']
faction_description = row['Description_lang']
faction_gameplay_only = True if int(row["GameplayOnly"]) == 1 else False
faction_base_faction = int(row["BaseFaction"])
lua_file.write(f'F[{faction_id}] = {{name="{faction_name}", description="{faction_description}", '
f'isGameplayOnly={"true" if faction_gameplay_only else "false"}, isBaseFaction='
f'{faction_base_faction}}}\n')
if int(row['BaseFaction']) == 1:
factions.add(faction_id)
except ValueError:
print(f"Invalid row: {row}")

lock_file(LUA_FILE_PATH)
return factions

0 comments on commit c201564

Please sign in to comment.