暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SteamIGAConverter.cs 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. #if UNITY_EDITOR && UNITY_ENABLE_STEAM_CONTROLLER_SUPPORT
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using UnityEditor;
  8. using UnityEngine.InputSystem.Controls;
  9. using UnityEngine.InputSystem.Editor;
  10. using UnityEngine.InputSystem.Utilities;
  11. ////TODO: motion data support
  12. ////TODO: haptics support
  13. ////TODO: ensure that no two actions have the same name even between maps
  14. ////TODO: also need to build a layout based on SteamController that has controls representing the current set of actions
  15. //// (might need this in the runtime)
  16. ////TODO: localization support (allow loading existing VDF file and preserving localization strings)
  17. ////TODO: allow having actions that are ignored by Steam VDF export
  18. ////TODO: support for getting displayNames/glyphs from Steam
  19. ////TODO: polling in background
  20. namespace UnityEngine.InputSystem.Steam.Editor
  21. {
  22. /// <summary>
  23. /// Converts input actions to and from Steam IGA file format.
  24. /// </summary>
  25. /// <remarks>
  26. /// The idea behind this converter is to enable users to use Unity's action editor to set up actions
  27. /// for their game and the be able, when targeting desktops through Steam, to convert the game's actions
  28. /// to a Steam VDF file that allows using the Steam Controller API with the game.
  29. ///
  30. /// The generated VDF file is meant to allow editing by hand in order to add localization strings or
  31. /// apply Steam-specific settings that cannot be inferred from Unity input actions.
  32. /// </remarks>
  33. public static class SteamIGAConverter
  34. {
  35. /// <summary>
  36. /// Generate C# code for an <see cref="InputDevice"/> derived class that exposes the controls
  37. /// for the actions found in the given Steam IGA description.
  38. /// </summary>
  39. /// <param name="vdf"></param>
  40. /// <param name="namespaceAndClassName"></param>
  41. /// <returns></returns>
  42. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1809:AvoidExcessiveLocals", Justification = "TODO: Refactor later.")]
  43. public static string GenerateInputDeviceFromSteamIGA(string vdf, string namespaceAndClassName)
  44. {
  45. if (string.IsNullOrEmpty(vdf))
  46. throw new ArgumentNullException("vdf");
  47. if (string.IsNullOrEmpty(namespaceAndClassName))
  48. throw new ArgumentNullException("namespaceAndClassName");
  49. // Parse VDF.
  50. var parsedVdf = ParseVDF(vdf);
  51. var actions = (Dictionary<string, object>)((Dictionary<string, object>)parsedVdf["In Game Actions"])["actions"];
  52. // Determine class and namespace name.
  53. var namespaceName = "";
  54. var className = "";
  55. var indexOfLastDot = namespaceAndClassName.LastIndexOf('.');
  56. if (indexOfLastDot != -1)
  57. {
  58. namespaceName = namespaceAndClassName.Substring(0, indexOfLastDot);
  59. className = namespaceAndClassName.Substring(indexOfLastDot + 1);
  60. }
  61. else
  62. {
  63. className = namespaceAndClassName;
  64. }
  65. var stateStructName = className + "State";
  66. var builder = new StringBuilder();
  67. builder.Append("// THIS FILE HAS BEEN AUTO-GENERATED\n");
  68. builder.Append("#if (UNITY_EDITOR || UNITY_STANDALONE) && UNITY_ENABLE_STEAM_CONTROLLER_SUPPORT\n");
  69. builder.Append("using UnityEngine;\n");
  70. builder.Append("using UnityEngine.InputSystem;\n");
  71. builder.Append("using UnityEngine.InputSystem.Controls;\n");
  72. builder.Append("using UnityEngine.InputSystem.Layouts;\n");
  73. builder.Append("using UnityEngine.InputSystem.LowLevel;\n");
  74. builder.Append("using UnityEngine.InputSystem.Utilities;\n");
  75. builder.Append("using UnityEngine.InputSystem.Steam;\n");
  76. builder.Append("#if UNITY_EDITOR\n");
  77. builder.Append("using UnityEditor;\n");
  78. builder.Append("#endif\n");
  79. builder.Append("\n");
  80. if (!string.IsNullOrEmpty(namespaceName))
  81. {
  82. builder.Append("namespace ");
  83. builder.Append(namespaceName);
  84. builder.Append("\n{\n");
  85. }
  86. // InitializeOnLoad attribute.
  87. builder.Append("#if UNITY_EDITOR\n");
  88. builder.Append("[InitializeOnLoad]\n");
  89. builder.Append("#endif\n");
  90. // Control layout attribute.
  91. builder.Append("[InputControlLayout(stateType = typeof(");
  92. builder.Append(stateStructName);
  93. builder.Append("))]\n");
  94. // Class declaration.
  95. builder.Append("public class ");
  96. builder.Append(className);
  97. builder.Append(" : SteamController\n");
  98. builder.Append("{\n");
  99. // Device matcher.
  100. builder.Append(" private static InputDeviceMatcher deviceMatcher\n");
  101. builder.Append(" {\n");
  102. builder.Append(" get { return new InputDeviceMatcher().WithInterface(\"Steam\").WithProduct(\"");
  103. builder.Append(className);
  104. builder.Append("\"); }\n");
  105. builder.Append(" }\n");
  106. // Static constructor.
  107. builder.Append('\n');
  108. builder.Append("#if UNITY_EDITOR\n");
  109. builder.Append(" static ");
  110. builder.Append(className);
  111. builder.Append("()\n");
  112. builder.Append(" {\n");
  113. builder.Append(" InputSystem.RegisterLayout<");
  114. builder.Append(className);
  115. builder.Append(">(matches: deviceMatcher);\n");
  116. builder.Append(" }\n");
  117. builder.Append("#endif\n");
  118. // RuntimeInitializeOnLoadMethod.
  119. // NOTE: Not relying on static ctor here. See il2cpp bug 1014293.
  120. builder.Append('\n');
  121. builder.Append(" [RuntimeInitializeOnLoadMethod(loadType: RuntimeInitializeLoadType.BeforeSceneLoad)]\n");
  122. builder.Append(" private static void RuntimeInitializeOnLoad()\n");
  123. builder.Append(" {\n");
  124. builder.Append(" InputSystem.RegisterLayout<");
  125. builder.Append(className);
  126. builder.Append(">(matches: deviceMatcher);\n");
  127. builder.Append(" }\n");
  128. // Control properties.
  129. builder.Append('\n');
  130. foreach (var setEntry in actions)
  131. {
  132. var setEntryProperties = (Dictionary<string, object>)setEntry.Value;
  133. // StickPadGyros.
  134. var stickPadGyros = (Dictionary<string, object>)setEntryProperties["StickPadGyro"];
  135. foreach (var entry in stickPadGyros)
  136. {
  137. var entryProperties = (Dictionary<string, object>)entry.Value;
  138. var isStick = entryProperties.ContainsKey("input_mode") && (string)entryProperties["input_mode"] == "joystick_move";
  139. builder.Append(" [InputControl]\n");
  140. builder.Append(
  141. $" public {(isStick ? "StickControl" : "Vector2Control")} {CSharpCodeHelpers.MakeIdentifier(entry.Key)} {{ get; protected set; }}\n");
  142. }
  143. // Buttons.
  144. var buttons = (Dictionary<string, object>)setEntryProperties["Button"];
  145. foreach (var entry in buttons)
  146. {
  147. builder.Append(" [InputControl]\n");
  148. builder.Append(
  149. $" public ButtonControl {CSharpCodeHelpers.MakeIdentifier(entry.Key)} {{ get; protected set; }}\n");
  150. }
  151. // AnalogTriggers.
  152. var analogTriggers = (Dictionary<string, object>)setEntryProperties["AnalogTrigger"];
  153. foreach (var entry in analogTriggers)
  154. {
  155. builder.Append(" [InputControl]\n");
  156. builder.Append(
  157. $" public AxisControl {CSharpCodeHelpers.MakeIdentifier(entry.Key)} {{ get; protected set; }}\n");
  158. }
  159. }
  160. // FinishSetup method.
  161. builder.Append('\n');
  162. builder.Append(" protected override void FinishSetup()\n");
  163. builder.Append(" {\n");
  164. builder.Append(" base.FinishSetup();\n");
  165. foreach (var setEntry in actions)
  166. {
  167. var setEntryProperties = (Dictionary<string, object>)setEntry.Value;
  168. // StickPadGyros.
  169. var stickPadGyros = (Dictionary<string, object>)setEntryProperties["StickPadGyro"];
  170. foreach (var entry in stickPadGyros)
  171. {
  172. var entryProperties = (Dictionary<string, object>)entry.Value;
  173. var isStick = entryProperties.ContainsKey("input_mode") && (string)entryProperties["input_mode"] == "joystick_move";
  174. builder.Append(
  175. $" {CSharpCodeHelpers.MakeIdentifier(entry.Key)} = GetChildControl<{(isStick ? "StickControl" : "Vector2Control")}>(\"{entry.Key}\");\n");
  176. }
  177. // Buttons.
  178. var buttons = (Dictionary<string, object>)setEntryProperties["Button"];
  179. foreach (var entry in buttons)
  180. {
  181. builder.Append(
  182. $" {CSharpCodeHelpers.MakeIdentifier(entry.Key)} = GetChildControl<ButtonControl>(\"{entry.Key}\");\n");
  183. }
  184. // AnalogTriggers.
  185. var analogTriggers = (Dictionary<string, object>)setEntryProperties["AnalogTrigger"];
  186. foreach (var entry in analogTriggers)
  187. {
  188. builder.Append(
  189. $" {CSharpCodeHelpers.MakeIdentifier(entry.Key)} = GetChildControl<AxisControl>(\"{entry.Key}\");\n");
  190. }
  191. }
  192. builder.Append(" }\n");
  193. // ResolveSteamActions method.
  194. builder.Append('\n');
  195. builder.Append(" protected override void ResolveSteamActions(ISteamControllerAPI api)\n");
  196. builder.Append(" {\n");
  197. foreach (var setEntry in actions)
  198. {
  199. var setEntryProperties = (Dictionary<string, object>)setEntry.Value;
  200. // Set handle.
  201. builder.Append(
  202. $" {CSharpCodeHelpers.MakeIdentifier(setEntry.Key)}SetHandle = api.GetActionSetHandle(\"{setEntry.Key}\");\n");
  203. // StickPadGyros.
  204. var stickPadGyros = (Dictionary<string, object>)setEntryProperties["StickPadGyro"];
  205. foreach (var entry in stickPadGyros)
  206. {
  207. builder.Append(
  208. $" {CSharpCodeHelpers.MakeIdentifier(entry.Key)}Handle = api.GetAnalogActionHandle(\"{entry.Key}\");\n");
  209. }
  210. // Buttons.
  211. var buttons = (Dictionary<string, object>)setEntryProperties["Button"];
  212. foreach (var entry in buttons)
  213. {
  214. builder.Append(
  215. $" {CSharpCodeHelpers.MakeIdentifier(entry.Key)}Handle = api.GetDigitalActionHandle(\"{entry.Key}\");\n");
  216. }
  217. // AnalogTriggers.
  218. var analogTriggers = (Dictionary<string, object>)setEntryProperties["AnalogTrigger"];
  219. foreach (var entry in analogTriggers)
  220. {
  221. builder.Append(
  222. $" {CSharpCodeHelpers.MakeIdentifier(entry.Key)}Handle = api.GetAnalogActionHandle(\"{entry.Key}\");\n");
  223. }
  224. }
  225. builder.Append(" }\n");
  226. // Handle cache fields.
  227. builder.Append('\n');
  228. foreach (var setEntry in actions)
  229. {
  230. var setEntryProperties = (Dictionary<string, object>)setEntry.Value;
  231. // Set handle.
  232. builder.Append(
  233. $" public SteamHandle<InputActionMap> {CSharpCodeHelpers.MakeIdentifier(setEntry.Key)}SetHandle {{ get; private set; }}\n");
  234. // StickPadGyros.
  235. var stickPadGyros = (Dictionary<string, object>)setEntryProperties["StickPadGyro"];
  236. foreach (var entry in stickPadGyros)
  237. {
  238. builder.Append(
  239. $" public SteamHandle<InputAction> {CSharpCodeHelpers.MakeIdentifier(entry.Key)}Handle {{ get; private set; }}\n");
  240. }
  241. // Buttons.
  242. var buttons = (Dictionary<string, object>)setEntryProperties["Button"];
  243. foreach (var entry in buttons)
  244. {
  245. builder.Append(
  246. $" public SteamHandle<InputAction> {CSharpCodeHelpers.MakeIdentifier(entry.Key)}Handle {{ get; private set; }}\n");
  247. }
  248. // AnalogTriggers.
  249. var analogTriggers = (Dictionary<string, object>)setEntryProperties["AnalogTrigger"];
  250. foreach (var entry in analogTriggers)
  251. {
  252. builder.Append(
  253. $" public SteamHandle<InputAction> {CSharpCodeHelpers.MakeIdentifier(entry.Key)}Handle {{ get; private set; }}\n");
  254. }
  255. }
  256. // steamActionSets property.
  257. builder.Append('\n');
  258. builder.Append(" private SteamActionSetInfo[] m_ActionSets;\n");
  259. builder.Append(" public override ReadOnlyArray<SteamActionSetInfo> steamActionSets\n");
  260. builder.Append(" {\n");
  261. builder.Append(" get\n");
  262. builder.Append(" {\n");
  263. builder.Append(" if (m_ActionSets == null)\n");
  264. builder.Append(" m_ActionSets = new[]\n");
  265. builder.Append(" {\n");
  266. foreach (var setEntry in actions)
  267. {
  268. builder.Append(string.Format(
  269. " new SteamActionSetInfo {{ name = \"{0}\", handle = {1}SetHandle }},\n",
  270. setEntry.Key,
  271. CSharpCodeHelpers.MakeIdentifier(setEntry.Key)));
  272. }
  273. builder.Append(" };\n");
  274. builder.Append(" return new ReadOnlyArray<SteamActionSetInfo>(m_ActionSets);\n");
  275. builder.Append(" }\n");
  276. builder.Append(" }\n");
  277. // Update method.
  278. builder.Append('\n');
  279. builder.Append(" protected override unsafe void Update(ISteamControllerAPI api)\n");
  280. builder.Append(" {\n");
  281. builder.Append($" {stateStructName} state;\n");
  282. var currentButtonBit = 0;
  283. foreach (var setEntry in actions)
  284. {
  285. var setEntryProperties = (Dictionary<string, object>)setEntry.Value;
  286. // StickPadGyros.
  287. var stickPadGyros = (Dictionary<string, object>)setEntryProperties["StickPadGyro"];
  288. foreach (var entry in stickPadGyros)
  289. {
  290. builder.Append(string.Format(" state.{0} = api.GetAnalogActionData(steamControllerHandle, {0}Handle).position;\n",
  291. CSharpCodeHelpers.MakeIdentifier(entry.Key)));
  292. }
  293. // Buttons.
  294. var buttons = (Dictionary<string, object>)setEntryProperties["Button"];
  295. foreach (var entry in buttons)
  296. {
  297. builder.Append(
  298. $" if (api.GetDigitalActionData(steamControllerHandle, {CSharpCodeHelpers.MakeIdentifier(entry.Key)}Handle).pressed)\n");
  299. builder.Append($" state.buttons[{currentButtonBit / 8}] |= {currentButtonBit % 8};\n");
  300. ++currentButtonBit;
  301. }
  302. // AnalogTriggers.
  303. var analogTriggers = (Dictionary<string, object>)setEntryProperties["AnalogTrigger"];
  304. foreach (var entry in analogTriggers)
  305. {
  306. builder.Append(string.Format(" state.{0} = api.GetAnalogActionData(steamControllerHandle, {0}Handle).position.x;\n",
  307. CSharpCodeHelpers.MakeIdentifier(entry.Key)));
  308. }
  309. }
  310. builder.Append(" InputSystem.QueueStateEvent(this, state);\n");
  311. builder.Append(" }\n");
  312. builder.Append("}\n");
  313. if (!string.IsNullOrEmpty(namespaceName))
  314. builder.Append("}\n");
  315. // State struct.
  316. builder.Append("public unsafe struct ");
  317. builder.Append(stateStructName);
  318. builder.Append(" : IInputStateTypeInfo\n");
  319. builder.Append("{\n");
  320. builder.Append(" public FourCC format\n");
  321. builder.Append(" {\n");
  322. builder.Append(" get {\n");
  323. ////TODO: handle class names that are shorter than 4 characters
  324. ////TODO: uppercase characters
  325. builder.Append(
  326. $" return new FourCC('{className[0]}', '{className[1]}', '{className[2]}', '{className[3]}');\n");
  327. builder.Append(" }\n");
  328. builder.Append(" }\n");
  329. builder.Append("\n");
  330. var totalButtonCount = 0;
  331. foreach (var setEntry in actions)
  332. {
  333. var setEntryProperties = (Dictionary<string, object>)setEntry.Value;
  334. // Buttons.
  335. var buttons = (Dictionary<string, object>)setEntryProperties["Button"];
  336. var buttonCount = buttons.Count;
  337. if (buttonCount > 0)
  338. {
  339. foreach (var entry in buttons)
  340. {
  341. builder.Append(
  342. $" [InputControl(name = \"{entry.Key}\", layout = \"Button\", bit = {totalButtonCount})]\n");
  343. ++totalButtonCount;
  344. }
  345. }
  346. }
  347. if (totalButtonCount > 0)
  348. {
  349. var byteCount = (totalButtonCount + 7) / 8;
  350. builder.Append(" public fixed byte buttons[");
  351. builder.Append(byteCount.ToString());
  352. builder.Append("];\n");
  353. }
  354. foreach (var setEntry in actions)
  355. {
  356. var setEntryProperties = (Dictionary<string, object>)setEntry.Value;
  357. // StickPadGyros.
  358. var stickPadGyros = (Dictionary<string, object>)setEntryProperties["StickPadGyro"];
  359. foreach (var entry in stickPadGyros)
  360. {
  361. var entryProperties = (Dictionary<string, object>)entry.Value;
  362. var isStick = entryProperties.ContainsKey("input_mode") && (string)entryProperties["input_mode"] == "joystick_move";
  363. builder.Append(
  364. $" [InputControl(name = \"{entry.Key}\", layout = \"{(isStick ? "Stick" : "Vector2")}\")]\n");
  365. builder.Append($" public Vector2 {CSharpCodeHelpers.MakeIdentifier(entry.Key)};\n");
  366. }
  367. // AnalogTriggers.
  368. var analogTriggers = (Dictionary<string, object>)setEntryProperties["AnalogTrigger"];
  369. foreach (var entry in analogTriggers)
  370. {
  371. builder.Append($" [InputControl(name = \"{entry.Key}\", layout = \"Axis\")]\n");
  372. builder.Append($" public float {CSharpCodeHelpers.MakeIdentifier(entry.Key)};\n");
  373. }
  374. }
  375. builder.Append("}\n");
  376. builder.Append("#endif\n");
  377. return builder.ToString();
  378. }
  379. /// <summary>
  380. /// Convert an .inputactions asset to Steam VDF format.
  381. /// </summary>
  382. /// <param name="asset"></param>
  383. /// <param name="locale"></param>
  384. /// <returns>A string in Steam VDF format describing "In Game Actions" corresponding to the actions in
  385. /// <paramref name="asset"/>.</returns>
  386. /// <exception cref="ArgumentNullException"><paramref name="asset"/> is null.</exception>
  387. public static string ConvertInputActionsToSteamIGA(InputActionAsset asset, string locale = "english")
  388. {
  389. if (asset == null)
  390. throw new ArgumentNullException("asset");
  391. return ConvertInputActionsToSteamIGA(asset.actionMaps, locale: locale);
  392. }
  393. public static string ConvertInputActionsToSteamIGA(IEnumerable<InputActionMap> actionMaps, string locale = "english")
  394. {
  395. if (actionMaps == null)
  396. throw new ArgumentNullException("actionMaps");
  397. var localizationStrings = new Dictionary<string, string>();
  398. var builder = new StringBuilder();
  399. builder.Append("\"In Game Actions\"\n");
  400. builder.Append("{\n");
  401. // Add actions.
  402. builder.Append("\t\"actions\"\n");
  403. builder.Append("\t{\n");
  404. // Add each action map.
  405. foreach (var actionMap in actionMaps)
  406. {
  407. var actionMapName = actionMap.name;
  408. var actionMapIdentifier = CSharpCodeHelpers.MakeIdentifier(actionMapName);
  409. builder.Append("\t\t\"");
  410. builder.Append(actionMapName);
  411. builder.Append("\"\n");
  412. builder.Append("\t\t{\n");
  413. // Title.
  414. builder.Append("\t\t\t\"title\"\t\"#Set_");
  415. builder.Append(actionMapIdentifier);
  416. builder.Append("\"\n");
  417. localizationStrings["Set_" + actionMapIdentifier] = actionMapName;
  418. // StickPadGyro actions.
  419. builder.Append("\t\t\t\"StickPadGyro\"\n");
  420. builder.Append("\t\t\t{\n");
  421. foreach (var action in actionMap.actions.Where(x => GetSteamControllerInputType(x) == "StickPadGyro"))
  422. ConvertInputActionToVDF(action, builder, localizationStrings);
  423. builder.Append("\t\t\t}\n");
  424. // AnalogTrigger actions.
  425. builder.Append("\t\t\t\"AnalogTrigger\"\n");
  426. builder.Append("\t\t\t{\n");
  427. foreach (var action in actionMap.actions.Where(x => GetSteamControllerInputType(x) == "AnalogTrigger"))
  428. ConvertInputActionToVDF(action, builder, localizationStrings);
  429. builder.Append("\t\t\t}\n");
  430. // Button actions.
  431. builder.Append("\t\t\t\"Button\"\n");
  432. builder.Append("\t\t\t{\n");
  433. foreach (var action in actionMap.actions.Where(x => GetSteamControllerInputType(x) == "Button"))
  434. ConvertInputActionToVDF(action, builder, localizationStrings);
  435. builder.Append("\t\t\t}\n");
  436. builder.Append("\t\t}\n");
  437. }
  438. builder.Append("\t}\n");
  439. // Add localizations.
  440. builder.Append("\t\"localization\"\n");
  441. builder.Append("\t{\n");
  442. builder.Append("\t\t\"");
  443. builder.Append(locale);
  444. builder.Append("\"\n");
  445. builder.Append("\t\t{\n");
  446. foreach (var entry in localizationStrings)
  447. {
  448. builder.Append("\t\t\t\"");
  449. builder.Append(entry.Key);
  450. builder.Append("\"\t\"");
  451. builder.Append(entry.Value);
  452. builder.Append("\"\n");
  453. }
  454. builder.Append("\t\t}\n");
  455. builder.Append("\t}\n");
  456. builder.Append("}\n");
  457. return builder.ToString();
  458. }
  459. private static void ConvertInputActionToVDF(InputAction action, StringBuilder builder, Dictionary<string, string> localizationStrings)
  460. {
  461. builder.Append("\t\t\t\t\"");
  462. builder.Append(action.name);
  463. var mapIdentifier = CSharpCodeHelpers.MakeIdentifier(action.actionMap.name);
  464. var actionIdentifier = CSharpCodeHelpers.MakeIdentifier(action.name);
  465. var titleId = "Action_" + mapIdentifier + "_" + actionIdentifier;
  466. localizationStrings[titleId] = action.name;
  467. // StickPadGyros are objects. Everything else is just strings.
  468. var inputType = GetSteamControllerInputType(action);
  469. if (inputType == "StickPadGyro")
  470. {
  471. builder.Append("\"\n");
  472. builder.Append("\t\t\t\t{\n");
  473. // Title.
  474. builder.Append("\t\t\t\t\t\"title\"\t\"#");
  475. builder.Append(titleId);
  476. builder.Append("\"\n");
  477. // Decide on "input_mode". Assume "absolute_mouse" by default and take
  478. // anything built on StickControl as "joystick_move".
  479. var inputMode = "absolute_mouse";
  480. var controlType = EditorInputControlLayoutCache.TryGetLayout(action.expectedControlType).type;
  481. if (typeof(StickControl).IsAssignableFrom(controlType))
  482. inputMode = "joystick_move";
  483. builder.Append("\t\t\t\t\t\"input_mode\"\t\"");
  484. builder.Append(inputMode);
  485. builder.Append("\"\n");
  486. builder.Append("\t\t\t\t}\n");
  487. }
  488. else
  489. {
  490. builder.Append("\"\t\"");
  491. builder.Append(titleId);
  492. builder.Append("\"\n");
  493. }
  494. }
  495. public static string GetSteamControllerInputType(InputAction action)
  496. {
  497. if (action == null)
  498. throw new ArgumentNullException("action");
  499. // Make sure we have an expected control layout.
  500. var expectedControlLayout = action.expectedControlType;
  501. if (string.IsNullOrEmpty(expectedControlLayout))
  502. throw new ArgumentException($"Cannot determine Steam input type for action '{action}' that has no associated expected control layout",
  503. nameof(action));
  504. // Try to fetch the layout.
  505. var layout = EditorInputControlLayoutCache.TryGetLayout(expectedControlLayout);
  506. if (layout == null)
  507. throw new ArgumentException($"Cannot determine Steam input type for action '{action}'; cannot find layout '{expectedControlLayout}'", nameof(action));
  508. // Map our supported control types.
  509. var controlType = layout.type;
  510. if (typeof(ButtonControl).IsAssignableFrom(controlType))
  511. return "Button";
  512. if (typeof(InputControl<float>).IsAssignableFrom(controlType))
  513. return "AnalogTrigger";
  514. if (typeof(Vector2Control).IsAssignableFrom(controlType))
  515. return "StickPadGyro";
  516. // Everything else throws.
  517. throw new ArgumentException($"Cannot determine Steam input type for action '{action}'; layout '{expectedControlLayout}' with control type '{ controlType.Name}' has no known representation in the Steam controller API", nameof(action));
  518. }
  519. public static Dictionary<string, object> ParseVDF(string vdf)
  520. {
  521. var parser = new VDFParser(vdf);
  522. return parser.Parse();
  523. }
  524. private struct VDFParser
  525. {
  526. public string vdf;
  527. public int length;
  528. public int position;
  529. public VDFParser(string vdf)
  530. {
  531. this.vdf = vdf;
  532. length = vdf.Length;
  533. position = 0;
  534. }
  535. public Dictionary<string, object> Parse()
  536. {
  537. var result = new Dictionary<string, object>();
  538. ParseKeyValuePair(result);
  539. SkipWhitespace();
  540. if (position < length)
  541. throw new InvalidOperationException($"Parse error at {position} in '{vdf}'; not expecting any more input");
  542. return result;
  543. }
  544. private bool ParseKeyValuePair(Dictionary<string, object> result)
  545. {
  546. var key = ParseString();
  547. if (key.isEmpty)
  548. return false;
  549. SkipWhitespace();
  550. if (position == length)
  551. throw new InvalidOperationException($"Expecting value or object at position {position} in '{vdf}'");
  552. var nextChar = vdf[position];
  553. if (nextChar == '"')
  554. {
  555. var value = ParseString();
  556. result[key.ToString()] = value.ToString();
  557. }
  558. else if (nextChar == '{')
  559. {
  560. var value = ParseObject();
  561. result[key.ToString()] = value;
  562. }
  563. else
  564. {
  565. throw new InvalidOperationException($"Expecting value or object at position {position} in '{vdf}'");
  566. }
  567. return true;
  568. }
  569. private Substring ParseString()
  570. {
  571. SkipWhitespace();
  572. if (position == length || vdf[position] != '"')
  573. return new Substring();
  574. ++position;
  575. var startPos = position;
  576. while (position < length && vdf[position] != '"')
  577. ++position;
  578. var endPos = position;
  579. if (position < length)
  580. ++position;
  581. return new Substring(vdf, startPos, endPos - startPos);
  582. }
  583. private Dictionary<string, object> ParseObject()
  584. {
  585. SkipWhitespace();
  586. if (position == length || vdf[position] != '{')
  587. return null;
  588. var result = new Dictionary<string, object>();
  589. ++position;
  590. while (position < length)
  591. {
  592. if (!ParseKeyValuePair(result))
  593. break;
  594. }
  595. SkipWhitespace();
  596. if (position == length || vdf[position] != '}')
  597. throw new InvalidOperationException($"Expecting '}}' at position {position} in '{vdf}'");
  598. ++position;
  599. return result;
  600. }
  601. private void SkipWhitespace()
  602. {
  603. while (position < length && char.IsWhiteSpace(vdf[position]))
  604. ++position;
  605. }
  606. }
  607. [MenuItem("Assets/Steam/Export to Steam In-Game Actions File...", true)]
  608. private static bool IsExportContextMenuItemEnabled()
  609. {
  610. return Selection.activeObject is InputActionAsset;
  611. }
  612. [MenuItem("Assets/Steam/Export to Steam In-Game Actions File...")]
  613. private static void ExportContextMenuItem()
  614. {
  615. var selectedAsset = (InputActionAsset)Selection.activeObject;
  616. // Determine default .vdf file name.
  617. var defaultVDFName = "";
  618. var directory = "";
  619. var assetPath = AssetDatabase.GetAssetPath(selectedAsset);
  620. if (!string.IsNullOrEmpty(assetPath))
  621. {
  622. defaultVDFName = Path.GetFileNameWithoutExtension(assetPath) + ".vdf";
  623. directory = Path.GetDirectoryName(assetPath);
  624. }
  625. // Ask for save location.
  626. var fileName = EditorUtility.SaveFilePanel("Export Steam In-Game Actions File", directory, defaultVDFName, "vdf");
  627. if (!string.IsNullOrEmpty(fileName))
  628. {
  629. var text = ConvertInputActionsToSteamIGA(selectedAsset);
  630. File.WriteAllText(fileName, text);
  631. AssetDatabase.Refresh();
  632. }
  633. }
  634. [MenuItem("Assets/Steam/Generate Unity Input Device...", true)]
  635. private static bool IsGenerateContextMenuItemEnabled()
  636. {
  637. // VDF files have no associated importer and so come in as DefaultAssets.
  638. if (!(Selection.activeObject is DefaultAsset))
  639. return false;
  640. var assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
  641. if (!string.IsNullOrEmpty(assetPath) && Path.GetExtension(assetPath) == ".vdf")
  642. return true;
  643. return false;
  644. }
  645. ////TODO: support setting class and namespace name
  646. [MenuItem("Assets/Steam/Generate Unity Input Device...")]
  647. private static void GenerateContextMenuItem()
  648. {
  649. var selectedAsset = Selection.activeObject;
  650. var assetPath = AssetDatabase.GetAssetPath(selectedAsset);
  651. if (string.IsNullOrEmpty(assetPath))
  652. {
  653. Debug.LogError("Cannot determine source asset path");
  654. return;
  655. }
  656. var defaultClassName = Path.GetFileNameWithoutExtension(assetPath);
  657. var defaultFileName = defaultClassName + ".cs";
  658. var defaultDirectory = Path.GetDirectoryName(assetPath);
  659. // Ask for save location.
  660. var fileName = EditorUtility.SaveFilePanel("Generate C# Input Device Class", defaultDirectory, defaultFileName, "cs");
  661. if (string.IsNullOrEmpty(fileName))
  662. return;
  663. // Load VDF file text.
  664. var vdf = File.ReadAllText(assetPath);
  665. // Generate and write output.
  666. var className = Path.GetFileNameWithoutExtension(fileName);
  667. var text = GenerateInputDeviceFromSteamIGA(vdf, className);
  668. File.WriteAllText(fileName, text);
  669. AssetDatabase.Refresh();
  670. }
  671. }
  672. }
  673. #endif // UNITY_EDITOR && UNITY_ENABLE_STEAM_CONTROLLER_SUPPORT