Skip to content

Commit

Permalink
Dialogue graph data now exportable in single csv
Browse files Browse the repository at this point in the history
  • Loading branch information
BDeshiDev committed Aug 1, 2024
1 parent 8f3d689 commit bd0d091
Show file tree
Hide file tree
Showing 3 changed files with 174 additions and 70 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using CsvHelper;
using Studio23.SS2.DialogueSystem.Data;
using UnityEditor.Localization;
using UnityEditor.Localization.Plugins.CSV.Columns;
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.Localization.Metadata;
using UnityEngine.Localization.Tables;


/// <summary>
/// Writes custom DialogueGraph Fields <see cref="StringTable"/>.
/// </summary>
[Serializable]
public class DialogueGraphCustomColumns : CsvColumns, ISerializationCallbackReceiver
{
private Dictionary<long, DialogueLineNodeBase> IdToDialogueLineMap;

private List<string> ColNames = new()
{
"SpeakerName",
"Expression"
};

public DialogueGraphCustomColumns(Dictionary<long, DialogueLineNodeBase> idToDialogueLineMap)
{
IdToDialogueLineMap = idToDialogueLineMap;
}

/// <inheritdoc/>
public override void WriteBegin(StringTableCollection collection, CsvWriter csvWriter)
{
var tables = collection.StringTables;

foreach (var colName in ColNames)
{
csvWriter.WriteField(colName);
}
}

/// <inheritdoc/>
public override void ReadBegin(StringTableCollection collection, CsvReader csvReader)
{
//do nothing
}

/// <inheritdoc/>
public override void ReadEnd(StringTableCollection collection)
{
//do nothing
}

/// <inheritdoc/>
public override void ReadRow(SharedTableData.SharedTableEntry keyEntry, CsvReader reader)
{
//do nothing
}

/// <inheritdoc/>
public override void WriteRow(SharedTableData.SharedTableEntry keyEntry, IList<StringTableEntry> tableEntries,
CsvWriter writer)
{
if (IdToDialogueLineMap.TryGetValue(keyEntry.Id, out var dialogueLineNodeBase))
{
if (dialogueLineNodeBase.SpeakerData.Character != null)
{
writer.WriteField(dialogueLineNodeBase.SpeakerData.Character.CharacterName);
}
else
{
writer.WriteField("");
}

if (dialogueLineNodeBase.SpeakerData.Expression != null)
{
writer.WriteField(dialogueLineNodeBase.SpeakerData.Expression.ExpressionName);
}
else
{
writer.WriteField("");
}
}
else
{
//write empty
foreach (var colName in ColNames)
{
writer.WriteField("");
}
}
}

/// <summary>
/// Sets the field names to their default values.
/// The default values are <see cref="LocaleIdentifier.ToString"/> for <see cref="FieldName"/>
/// and <see cref="FieldName"/> + " Comments" for <see cref="CommentFieldName"/>.
/// </summary>
public void OnBeforeSerialize()
{
//do nothing
}

public void OnAfterDeserialize()
{
//do nothing
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ public class DialogueGraphExportWindow: EditorWindow
{
private DialogueGraph dialogueGraph;
private List<DialogueLineNodeBase> traversedLinesCache = new();

private bool ShouldExportGraphs = true;
private bool ShouldExportSpeakerData = false;
private bool ExportNodeData = true;

[MenuItem("Studio-23/Dialogue-System/Dialogue Graph Export")]
public static void ShowWindow()
Expand All @@ -40,8 +38,8 @@ private void OnGUI()
GUILayout.Label("Dialogue Graph Editor", EditorStyles.boldLabel);

dialogueGraph = (DialogueGraph)EditorGUILayout.ObjectField("Dialogue Graph", dialogueGraph, typeof(DialogueGraph), false);
ShouldExportGraphs = EditorGUILayout.Toggle("Should Export Graphs", ShouldExportGraphs);
ShouldExportSpeakerData = EditorGUILayout.Toggle("Should Export Speaker Data", ShouldExportSpeakerData);
ExportNodeData = EditorGUILayout.Toggle("Export Node Data", ExportNodeData);

if (GUILayout.Button("Export graph"))
{
ExportSingleGraphToCSV(dialogueGraph);
Expand All @@ -65,21 +63,40 @@ private void ExportSelected()
{
if (o is DialogueGraph graph)
{
var filePath = Path.Combine(folderPath , $"{graph.name}.csv");
ExportToCSV(graph, filePath);
try
{
var filePath = Path.Combine(folderPath , GetGraphCSVName(graph));
ExportToCSV(graph, filePath);
}
catch (Exception e)
{
Debug.LogError($"Error Exporting graph {graph} \n {e}", graph);
}
}
}
}

private static string GetGraphCSVName(DialogueGraph graph)
{
return $"{graph.name}.csv";
}

private void ExportAll()
{
string folderPath = EditorUtility.OpenFolderPanel("Export graph", "", "");
if (string.IsNullOrEmpty(folderPath))
return;
foreach (var graph in GetAllGraphs())
{
var filePath = Path.Combine(folderPath , $"{graph.name}.csv");
ExportToCSV(graph, filePath);
try
{
var filePath = Path.Combine(folderPath , GetGraphCSVName(graph));
ExportToCSV(graph, filePath);
}
catch (Exception e)
{
Debug.LogError($"Error Exporting graph {graph} \n {e}", graph);
}
}
}

Expand All @@ -97,7 +114,7 @@ public List<DialogueGraph> GetAllGraphs()
}
private void ExportSingleGraphToCSV(DialogueGraph graph)
{
string filePath = EditorUtility.SaveFilePanel("Export graph", "", $"{graph.name}.csv", "csv");
string filePath = EditorUtility.SaveFilePanel("Export graph", "", GetGraphCSVName(graph), "csv");
if (string.IsNullOrEmpty(filePath))
return;
ExportToCSV(graph, filePath);
Expand All @@ -108,24 +125,13 @@ private void ExportToCSV(DialogueGraph graph, string filePath)
{
TraverseNodes(graph, HandleDialogueLineNodeTraversed);
string folderPath = Path.GetDirectoryName(filePath);
if (ShouldExportGraphs)
if (File.Exists(filePath))
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}


if (traversedLinesCache.Count > 0)
{
ExportToCSV(graph,filePath, traversedLinesCache);
}
File.Delete(filePath);
}

if (ShouldExportSpeakerData)
if (traversedLinesCache.Count > 0)
{
var speakerPath = Path.Combine(folderPath, $"{graph.name}_SpeakerData.csv");
ExportSpeakerData(traversedLinesCache, speakerPath);
ExportToCSV(graph,filePath, traversedLinesCache);
}
}

Expand All @@ -137,25 +143,45 @@ private static SharedTableData.SharedTableEntry GetTableEntry(DialogueLineNodeBa
return table.SharedData.GetEntryFromReference(dialogue.DialogueLocalizedString.TableEntryReference);
}

public static void ExportToCSV(DialogueGraph graph, string filePath, List<DialogueLineNodeBase> dialogueLinesInOrder)
public void ExportToCSV(DialogueGraph graph, string filePath, List<DialogueLineNodeBase> dialogueLinesInOrder)
{
ExportStringTable(graph, filePath, dialogueLinesInOrder);
}

private static void ExportStringTable(DialogueGraph graph, string path, List<DialogueLineNodeBase> dialogueLinesInOrder)
private void ExportStringTable(DialogueGraph graph, string path, List<DialogueLineNodeBase> dialogueLinesInOrder)
{
var dialogueGraphLineIds = dialogueLinesInOrder
.Where(l=> GetTableEntry(l) != null)
.Select(l => GetTableEntry(l).Id)
.ToHashSet();
var dialogueGraphLineIds = new HashSet<long>();
foreach (var dialogueLineNodeBase in dialogueLinesInOrder)
{
var entry = GetTableEntry(dialogueLineNodeBase);
if (entry != null)
{
dialogueGraphLineIds.Add(entry.Id);
}
}

// var csvColumnsList = ColumnMapping.CreateDefaultMapping();
var columnMappings = new List<CsvColumns>();

columnMappings.Add(new KeyIdColumns
{
IncludeId = true, // Include the Id column field.
IncludeSharedComments = false, // Include Shared comments.
});

if (ExportNodeData)
{
var idToDialogueLineGraphMap = new Dictionary<long, DialogueLineNodeBase>();
foreach (var dialogueLineNodeBase in dialogueLinesInOrder)
{
var entry = GetTableEntry(dialogueLineNodeBase);
if (entry != null)
{
idToDialogueLineGraphMap.TryAdd(entry.Id, dialogueLineNodeBase);
}
}
columnMappings.Add(new DialogueGraphCustomColumns(idToDialogueLineGraphMap));
}

foreach (var locale in LocalizationSettings.AvailableLocales.Locales)
{
Expand All @@ -175,44 +201,10 @@ private static void ExportStringTable(DialogueGraph graph, string path, List<Dia
var collection = LocalizationEditorSettings.GetStringTableCollection(tableReference.TableCollectionName);
using (var stream = new StreamWriter(path, false, new UTF8Encoding(false)))
{
ExportStringTable(stream, collection, columnMappings, dialogueLinesInOrder, dialogueGraphLineIds);
ExportStringTable(graph, stream, collection, columnMappings, dialogueLinesInOrder, dialogueGraphLineIds);
}
}

/// <summary>
/// #TODO temporary measure till I figure out columnmapping
/// </summary>
/// <param name="dialogueLinesInOrder"></param>
/// <param name="path"></param>
public void ExportSpeakerData(List<DialogueLineNodeBase> dialogueLinesInOrder, string path)
{
// StringBuilder to construct the CSV content
StringBuilder csvContent = new StringBuilder();

// Append the header
csvContent.AppendLine("Id,Speaker, Expression");

// Append each dialogue line
foreach (var line in dialogueLinesInOrder)
{
var entry = GetTableEntry(line);
if (entry != null)
{
if (line.SpeakerData.Character != null)
{
csvContent.AppendLine($"{entry.Id},{line.SpeakerData.Character.CharacterName}, {line.SpeakerData.Expression.name}");
}
else
{
csvContent.AppendLine($"{entry.Id},,");
}
}
}

// Write the content to the file
File.WriteAllText(path, csvContent.ToString());
}

/// <summary>
/// Basically a clone of Unity's CSV Exporter
/// We need to mimic it because our exported csv's
Expand All @@ -225,7 +217,7 @@ public void ExportSpeakerData(List<DialogueLineNodeBase> dialogueLinesInOrder, s
/// <param name="collection"></param>
/// <param name="columnMappings"></param>
/// <exception cref="ArgumentNullException"></exception>
public static void ExportStringTable(TextWriter writer, StringTableCollection collection, IList<CsvColumns> columnMappings, List<DialogueLineNodeBase> dialigueLinesInOrder, HashSet<long> allowedIds)
public static void ExportStringTable(DialogueGraph graph, TextWriter writer, StringTableCollection collection, IList<CsvColumns> columnMappings, List<DialogueLineNodeBase> dialigueLinesInOrder, HashSet<long> allowedIds)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
Expand All @@ -236,7 +228,7 @@ public static void ExportStringTable(TextWriter writer, StringTableCollection co
{
try
{
Debug.Log("Writing Headers");
Debug.Log($"Writing Headers: {graph}", graph);
foreach (var cell in columnMappings)
{
cell.WriteBegin(collection, csvWriter);
Expand Down Expand Up @@ -280,7 +272,7 @@ public static void ExportStringTable(TextWriter writer, StringTableCollection co
rows.Sort(
(r1, r2) => IdToOrderMap[r1.KeyEntry.Id].CompareTo(IdToOrderMap[r2.KeyEntry.Id])
);
Debug.Log($"Writing Contents: {rows.Count()} lines");
Debug.Log($"Writing Contents({rows.Count()} lines): {graph} ", graph);
foreach (var row in rows)
{
csvWriter.NextRecord();
Expand All @@ -300,7 +292,7 @@ public static void ExportStringTable(TextWriter writer, StringTableCollection co
}
catch (Exception e)
{
Debug.Log("Failed Exporting.\n" + e.Message);
Debug.LogError($"Failed Exporting. {graph}\n" + e.Message, graph);
throw;
}
}
Expand Down

0 comments on commit bd0d091

Please sign in to comment.