Decompiled source of Doppel v2.0.2
Mods/DoppelV2.dll
Decompiled 3 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Speech.Recognition; using System.Text; using System.Text.Json; using System.Threading.Tasks; using BoneLib; using BoneLib.BoneMenu; using BoneLib.BoneMenu.UI; using BoneLib.Notifications; using DoppelV2; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSLZ.Bonelab; using Il2CppSLZ.Data; using Il2CppSLZ.Marrow; using Il2CppSLZ.Marrow.AI; using Il2CppSLZ.Marrow.Audio; using Il2CppSLZ.Marrow.Combat; using Il2CppSLZ.Marrow.Forklift.Model; using Il2CppSLZ.Marrow.Input; using Il2CppSLZ.Marrow.Interaction; using Il2CppSLZ.Marrow.Pool; using Il2CppSLZ.Marrow.Utilities; using Il2CppSLZ.Marrow.Warehouse; using Il2CppSLZ.VRMK; using Il2CppSystem; using Il2CppSystem.Reflection; using Il2CppTMPro; using MelonLoader; using MelonLoader.Preferences; using MelonLoader.Utils; using Microsoft.CodeAnalysis; using ThirdEyeBonelabMod.Tools; using UnityEngine; using UnityEngine.AI; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: MelonInfo(typeof(PublicMod), "Doppel v2", "2.0.2", "RUDYHILL", null)] [assembly: MelonGame("Stress Level Zero", "BONELAB")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("DoppelV2Core")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("DoppelV2Core")] [assembly: AssemblyTitle("DoppelV2Core")] [assembly: AssemblyVersion("1.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } } namespace DoppelV2 { public static class BotBody { public const string Name = "[RigManager (Ghost)]"; public static float SwappedAt = -100f; public static bool Is(RigManager rig) { if ((Object)(object)rig != (Object)null) { return ((Object)((Component)rig).gameObject).name == "[RigManager (Ghost)]"; } return false; } public static void Create(Vector3 pos, Quaternion rot, Action<RigManager> made) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) MarrowSettings runtimeInstance = MarrowSettings.RuntimeInstance; SpawnableCrate val = (((Object)(object)runtimeInstance != (Object)null && runtimeInstance.DefaultPlayerRig != null) ? ((CrateReferenceT<SpawnableCrate>)(object)runtimeInstance.DefaultPlayerRig).Crate : null); if ((Object)(object)val == (Object)null) { Mod.Say("the game's player rig could not be found"); return; } ((MarrowAssetT<GameObject>)(object)((GameObjectCrate)val).MainGameObject).LoadAsset(Action<GameObject>.op_Implicit((Action<GameObject>)delegate(GameObject asset) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) try { made(Make(asset, pos, rot)); } catch (Exception ex) { MelonLogger.Error("Doppel v2: the bot could not be made: " + ex); } })); } private static RigManager Make(GameObject asset, Vector3 pos, Quaternion rot) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) RigManager obj = (((Object)(object)asset != (Object)null) ? asset.GetComponentInChildren<RigManager>(true) : null); if ((Object)(object)obj == (Object)null) { throw new InvalidOperationException("the player rig has no RigManager"); } GameObject val = new GameObject("GhostHolder"); val.SetActive(false); GameObject obj2 = Object.Instantiate<GameObject>(((Component)obj).gameObject, val.transform); ((Object)obj2).name = "[RigManager (Ghost)]"; obj2.SetActive(false); obj2.transform.SetPositionAndRotation(pos, rot); RigManager component = obj2.GetComponent<RigManager>(); Strip(component); obj2.transform.parent = null; Object.Destroy((Object)(object)val); obj2.SetActive(true); Spatial(component); Hand[] array = (Hand[])(object)new Hand[2] { component.physicsRig.leftHand, component.physicsRig.rightHand }; foreach (Hand obj3 in array) { if (obj3 != null) { obj3.OnLevelLoad(); } } return component; } private static void Strip(RigManager rig) { OpenControllerRig val = ((Il2CppObjectBase)rig.ControllerRig).TryCast<OpenControllerRig>(); PhysicsRig physicsRig = rig.physicsRig; RemovePlayerTag(physicsRig.marrowEntity); foreach (MarrowBody componentsInChild in ((Component)val).GetComponentsInChildren<MarrowBody>(true)) { Object.DestroyImmediate((Object)(object)componentsInChild); } foreach (Tracker componentsInChild2 in ((Component)val).GetComponentsInChildren<Tracker>(true)) { Object.DestroyImmediate((Object)(object)((Component)componentsInChild2).gameObject); } foreach (Tracker componentsInChild3 in ((Component)physicsRig).GetComponentsInChildren<Tracker>(true)) { Object.DestroyImmediate((Object)(object)((Component)componentsInChild3).gameObject); } MarrowEntity component = ((Component)val).GetComponent<MarrowEntity>(); if ((Object)(object)component != (Object)null) { Object.DestroyImmediate((Object)(object)component); } Player_Health val2 = (((Object)(object)rig.health != (Object)null) ? ((Il2CppObjectBase)rig.health).TryCast<Player_Health>() : null); if ((Object)(object)val2 != (Object)null) { val2.reloadLevelOnDeath = false; val2.slowMoOnDeath = false; ((Health)val2).healthMode = (HealthMode)0; if ((Object)(object)val2.Vignetter != (Object)null) { GameObject val3 = Object.Instantiate<GameObject>(val2.Vignetter); SkinnedMeshRenderer component2 = val3.GetComponent<SkinnedMeshRenderer>(); if ((Object)(object)component2 != (Object)null) { ((Renderer)component2).enabled = false; } ((Object)val3).name = "GhostVignetter"; val3.SetActive(false); val2.Vignetter = val3; } } val.quickmenuEnabled = false; val._timeInput = false; rig.remapHeptaRig.doubleJump = false; Transform headset = val.headset; Blind(headset); val.cameras = new Il2CppReferenceArray<Camera>(0L); val.onLastCameraUpdate = null; ((Component)headset).tag = "Untagged"; PlayerAvatarArt componentInChildren = ((Component)rig).GetComponentInChildren<PlayerAvatarArt>(true); if ((Object)(object)componentInChildren != (Object)null) { Object.DestroyImmediate((Object)(object)componentInChildren); } BaseController[] array = (BaseController[])(object)new BaseController[2] { rig.ControllerRig.leftController, rig.ControllerRig.rightController }; foreach (BaseController val4 in array) { if (!((Object)(object)val4 == (Object)null)) { UIControllerInput component3 = ((Component)val4).GetComponent<UIControllerInput>(); if ((Object)(object)component3 != (Object)null) { Object.DestroyImmediate((Object)(object)component3); } Haptor haptor = val4.haptor; if ((Object)(object)haptor != (Object)null) { haptor.hapticsAllowed = false; ((Behaviour)haptor).enabled = false; } } } if ((Object)(object)((Component)physicsRig).GetComponent<Poolee>() == (Object)null) { ((Component)physicsRig).gameObject.AddComponent<Poolee>(); } } private static void RemovePlayerTag(MarrowEntity entity) { MarrowSettings runtimeInstance = MarrowSettings.RuntimeInstance; if ((Object)(object)entity == (Object)null || (Object)(object)runtimeInstance == (Object)null || runtimeInstance.PlayerTag == null || ((ScannableReference)runtimeInstance.PlayerTag).Barcode == (Barcode)null) { return; } string iD = ((ScannableReference)runtimeInstance.PlayerTag).Barcode.ID; TagList tags = entity.Tags; if (tags == null || tags.Tags == null) { return; } for (int num = tags.Tags.Count - 1; num >= 0; num--) { BoneTagReference val = tags.Tags[num]; if (val != null && ((ScannableReference)val).Barcode != (Barcode)null && ((ScannableReference)val).Barcode.ID == iD) { tags.Tags.RemoveAt(num); } } tags.UpdateCache(false); } private static int Blind(Transform root) { int num = 0; foreach (Camera componentsInChild in ((Component)root).GetComponentsInChildren<Camera>(true)) { foreach (Component component in ((Component)componentsInChild).GetComponents<Component>()) { if (!((Object)(object)component == (Object)null) && !(component is Transform) && !(component is Camera)) { Object.DestroyImmediate((Object)(object)component); } } try { Object.DestroyImmediate((Object)(object)componentsInChild); } catch (Exception) { ((Behaviour)componentsInChild).enabled = false; } num++; } foreach (AudioListener componentsInChild2 in ((Component)root).GetComponentsInChildren<AudioListener>(true)) { Object.DestroyImmediate((Object)(object)componentsInChild2); num++; } return num; } public static void Spatial(RigManager rig) { if ((Object)(object)rig == (Object)null) { return; } foreach (AudioSource componentsInChild in ((Component)rig).GetComponentsInChildren<AudioSource>(true)) { if ((Object)(object)componentsInChild != (Object)null) { componentsInChild.spatialBlend = 1f; } } } public static void UseAvatar(RigManager rig, string barcode, Vector3 scale, Action<bool> done) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown AvatarCrate crate = null; AssetWarehouse instance = AssetWarehouse.Instance; if ((Object)(object)rig == (Object)null || string.IsNullOrEmpty(barcode) || instance == null || !instance.TryGetCrate<AvatarCrate>(new Barcode(barcode), ref crate) || (Object)(object)crate == (Object)null) { done(obj: false); return; } ((MarrowAssetT<GameObject>)(object)((GameObjectCrate)crate).MainGameObject).LoadAsset(Action<GameObject>.op_Implicit((Action<GameObject>)delegate(GameObject asset) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Expected O, but got Unknown try { if ((Object)(object)rig == (Object)null || (Object)(object)asset == (Object)null) { done(obj: false); } else { GameObject val = new GameObject("GhostAvatarHolder"); val.SetActive(false); GameObject val2 = Object.Instantiate<GameObject>(asset, val.transform); val2.SetActive(false); ((Object)val2).name = ((Object)asset).name; Blind(val2.transform); val2.transform.localScale = scale; val2.transform.parent = ((Component)rig).transform; Object.Destroy((Object)(object)val); val2.transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity); Avatar componentInParent = val2.GetComponentInParent<Avatar>(true); if ((Object)(object)componentInParent == (Object)null) { Object.Destroy((Object)(object)val2); done(obj: false); } else { SwappedAt = Time.time; rig.SwapAvatar(componentInParent); rig._avatarCrate = new AvatarCrateReference(((Scannable)crate).Barcode); Spatial(rig); done(obj: true); } } } catch (Exception ex) { MelonLogger.Warning("Doppel v2: the bot could not take the avatar: " + ex.Message); done(obj: false); } })); } public static void CopyBody(RigManager from, RigManager to) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) try { BodyVitals val = (((Object)(object)PlayerRefs.Instance != (Object)null) ? PlayerRefs.Instance._bodyVitals : null); OpenControllerRig val2 = (((Object)(object)from != (Object)null) ? ((Il2CppObjectBase)from.ControllerRig).TryCast<OpenControllerRig>() : null); OpenControllerRig val3 = (((Object)(object)to != (Object)null) ? ((Il2CppObjectBase)to.ControllerRig).TryCast<OpenControllerRig>() : null); if ((Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null) { return; } val3.isRightHanded = val2.isRightHanded; val3.degreesPerSnap = val2.degreesPerSnap; val3.snapDegreesPerFrame = val2.snapDegreesPerFrame; val3.vrVertState = val2.vrVertState; val3.directionMode = val2.directionMode; val3.curveMode = val2.curveMode; if ((Object)(object)from.remapHeptaRig != (Object)null && (Object)(object)to.remapHeptaRig != (Object)null) { to.remapHeptaRig.jumpEnabled = from.remapHeptaRig.jumpEnabled; to.remapHeptaRig.vertState = from.remapHeptaRig.vertState; } RealHeptaAvatar player = val3._player; if ((Object)(object)val == (Object)null || (Object)(object)player == (Object)null || ((Avatar)player)._heightPercent <= 0f) { MelonLogger.Msg("Doppel v2: body calibration not copied (vitals " + ((Object)(object)val != (Object)null) + ", avatar " + ((Object)(object)player != (Object)null) + ")"); return; } float num = val.realWorldHeight / ((Avatar)player)._heightPercent; player.realWorldHeight = val.realWorldHeight; ((Avatar)player).SetTorsoFromCircumferences(val.chestCircumference / num, val.underbustCircumference / num, val.waistCircumference / num, val.hipsCircumference / num); val3.vrRoot.localScale = val2.vrRoot.localScale; int num2 = 0; if ((Object)(object)from.inventory != (Object)null && (Object)(object)to.inventory != (Object)null) { bool[] array = new bool[2] { false, true }; foreach (bool num3 in array) { Il2CppReferenceArray<SlotContainer> val4 = (num3 ? from.inventory.specialItems : from.inventory.bodySlots); Il2CppReferenceArray<SlotContainer> val5 = (num3 ? to.inventory.specialItems : to.inventory.bodySlots); int num4 = 0; while (val4 != null && val5 != null && num4 < ((Il2CppArrayBase<SlotContainer>)(object)val4).Length && num4 < ((Il2CppArrayBase<SlotContainer>)(object)val5).Length) { if (!((Object)(object)((Il2CppArrayBase<SlotContainer>)(object)val4)[num4] == (Object)null) && !((Object)(object)((Il2CppArrayBase<SlotContainer>)(object)val5)[num4] == (Object)null)) { ((Il2CppArrayBase<SlotContainer>)(object)val5)[num4].degreesFromCenter = ((Il2CppArrayBase<SlotContainer>)(object)val4)[num4].degreesFromCenter; ((Il2CppArrayBase<SlotContainer>)(object)val5)[num4].bodyRegion = ((Il2CppArrayBase<SlotContainer>)(object)val4)[num4].bodyRegion; num2++; } num4++; } } } MelonLogger.Msg("Doppel v2: body calibration copied (height " + val.realWorldHeight.ToString("0.00") + " m, " + num2 + " body slots laid out as yours)"); } catch (Exception ex) { MelonLogger.Warning("Doppel v2: body calibration not copied: " + ex.Message); } } public static void GuardCameras() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) if (Time.time - SwappedAt > 8f) { return; } RigManager rigManager = Player.RigManager; if ((Object)(object)rigManager == (Object)null || !((Component)rigManager).gameObject.activeInHierarchy) { return; } try { foreach (Camera item in (Il2CppArrayBase<Camera>)(object)Camera.allCameras) { if ((Object)(object)item == (Object)null || !((Behaviour)item).enabled || (Object)(object)item.targetTexture != (Object)null || (int)item.stereoTargetEye == 0) { continue; } RigManager componentInParent = ((Component)item).GetComponentInParent<RigManager>(); if ((Object)(object)componentInParent == (Object)null || (Object)(object)componentInParent == (Object)(object)rigManager) { continue; } ((Behaviour)item).enabled = false; AudioListener component = ((Component)item).GetComponent<AudioListener>(); if ((Object)(object)component != (Object)null) { ((Behaviour)component).enabled = false; } MelonLogger.Msg("Doppel v2: a second body (" + ((Object)componentInParent).name + ") had a headset camera on: switched off"); if (!Is(componentInParent)) { Poolee componentInParent2 = ((Component)componentInParent).GetComponentInParent<Poolee>(); if ((Object)(object)componentInParent2 != (Object)null) { componentInParent2.Despawn(); } else { Object.Destroy((Object)(object)((Component)componentInParent).gameObject); } } } } catch (Exception ex) { MelonLogger.Warning("Doppel v2 camera guard: " + ex.Message); } } } public static class Cost { private static readonly Stopwatch watch = new Stopwatch(); private static readonly double[] spent = new double[3]; private static double worst; private static int frames; private static float since = -1f; public static void Begin() { watch.Restart(); } public static void End(int what) { watch.Stop(); spent[what] += watch.Elapsed.TotalMilliseconds; } public static void Frame() { if (!Doppel.All.Any()) { since = -1f; return; } if (since < 0f) { since = Time.realtimeSinceStartup; frames = 0; spent[0] = (spent[1] = (spent[2] = (worst = 0.0))); return; } frames++; worst = Math.Max(worst, (double)Time.unscaledDeltaTime * 1000.0); float num = Time.realtimeSinceStartup - since; if (!(num < 10f)) { Log.Event("cost: Doppel's code " + ((spent[0] + spent[1] + spent[2]) / (double)frames).ToString("0.00") + " ms a frame (once a frame " + (spent[0] / (double)frames).ToString("0.00") + ", after " + (spent[1] / (double)frames).ToString("0.00") + ", its input " + (spent[2] / (double)frames).ToString("0.00") + "), " + ((float)frames / num).ToString("0") + " fps, slowest frame " + worst.ToString("0") + " ms, " + Doppel.All.Count() + " Doppel(s)"); since = Time.realtimeSinceStartup; frames = 0; spent[0] = (spent[1] = (spent[2] = (worst = 0.0))); } } } public static class Doppel { private static readonly List<DoppelBot> bots = new List<DoppelBot>(); public static IEnumerable<DoppelBot> All => bots; public static bool IsBot(OpenControllerRig c) { return Of(c) != null; } public static DoppelBot Of(RigManager r) { if ((Object)(object)r == (Object)null) { return null; } foreach (DoppelBot bot in bots) { if ((Object)(object)bot.Rig != (Object)null && (Object)(object)bot.Rig == (Object)(object)r) { return bot; } } return null; } private static DoppelBot Of(OpenControllerRig c) { if ((Object)(object)c == (Object)null) { return null; } foreach (DoppelBot bot in bots) { if ((Object)(object)bot.Rig != (Object)null && (Object)(object)((Rig)c).manager == (Object)(object)bot.Rig) { return bot; } } return null; } public static void Spawn() { Follow.Remove(); DoppelBot doppelBot = new DoppelBot(); bots.Add(doppelBot); if (!doppelBot.Spawn(bots.Count - 1)) { bots.Remove(doppelBot); } } public static void SpawnEnemy() { Follow.Remove(); DoppelBot doppelBot = new DoppelBot(); doppelBot.MakeEnemy(); bots.Add(doppelBot); if (!doppelBot.Spawn(bots.Count((DoppelBot x) => x.enemy) - 1)) { bots.Remove(doppelBot); } } public static void Remove() { foreach (DoppelBot item in bots.ToList()) { item.Remove(); } bots.Clear(); } public static void LevelGone() { foreach (DoppelBot bot in bots) { bot.LevelGone(); } bots.Clear(); } public static void SetMode(DoppelBot.Mode m) { foreach (DoppelBot bot in bots) { if (!bot.enemy) { bot.SetMode(m); } } Mod.Say(m switch { DoppelBot.Mode.Roam => "Doppel walks around on its own", DoppelBot.Mode.Follow => "Doppel follows you", _ => "Doppel stays", }); } public static void PlayClip(List<Pose> clip, Moves.Kind kind) { DoppelBot doppelBot = Nearest(); if (doppelBot == null || !doppelBot.Ready) { Mod.Say("Spawn Doppel first (and wait till it is ready)"); } else { doppelBot.PlayClip(clip, kind); } } public static DoppelBot Nearest() { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) Transform head = Player.Head; DoppelBot result = null; float num = float.MaxValue; foreach (DoppelBot bot in bots) { if (bot.Ready && !((Object)(object)bot.Head == (Object)null)) { float num2; if (!((Object)(object)head != (Object)null)) { num2 = 0f; } else { Vector3 val = bot.Head.position - head.position; num2 = ((Vector3)(ref val)).sqrMagnitude; } float num3 = num2; if (num3 < num) { num = num3; result = bot; } } } return result; } public static void Update() { foreach (DoppelBot item in bots.ToList()) { if (!item.Update()) { bots.Remove(item); if (item.BlewUp) { Spawn(); } } } } public static bool EarlyPrefix(OpenControllerRig c) { DoppelBot doppelBot = Of(c); if (doppelBot == null) { return false; } Cost.Begin(); Moves.Who = doppelBot.AvatarKey; doppelBot.MovesForWhatItHolds(); try { return doppelBot.EarlyPrefix(); } finally { Moves.Who = null; Moves.Prop = null; Cost.End(2); } } } public class DoppelBot { public enum Mode { Stay, Follow, StandAt, Away, Roam } public enum HandOrder { Keep, Bring, Toss, Use, Drop } public enum Posture { None, Up, Crouch } public enum DriveOrder { None, To, Over, Around, Board, Roam, Straight } private enum State { Off, Making, Settling, On } private class MoveCheck { private readonly Moves.Kind kind; private readonly List<float>[] cm = new List<float>[2] { new List<float>(), new List<float>() }; private readonly StringBuilder lines = new StringBuilder(); private readonly bool[] youHeld = new bool[2]; private readonly bool[] botHeld = new bool[2]; private bool first = true; public MoveCheck(Moves.Kind kind) { this.kind = kind; } public void Frame(float t, RigManager rig, Pose g) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)rig == (Object)null || (Object)(object)rig.physicsRig == (Object)null || !Pose.Frame(rig, out var at, out var yaw)) { return; } Quaternion inv = Quaternion.Inverse(Quaternion.Euler(0f, yaw, 0f)); Hand[] array = (Hand[])(object)new Hand[2] { rig.physicsRig.leftHand, rig.physicsRig.rightHand }; Vector3[] array2 = (Vector3[])(object)new Vector3[2] { g.leftPhys, g.rightPhys }; bool[] array3 = new bool[2] { g.leftHolds, g.rightHolds }; float[] array4 = new float[2] { g.leftHand[0], g.rightHand[0] }; InventoryAmmoReceiver componentInChildren = ((Component)rig).GetComponentInChildren<InventoryAmmoReceiver>(true); for (int i = 0; i < 2; i++) { if ((Object)(object)array[i] == (Object)null) { continue; } Pose.Physical(array[i], at, inv, out var pos, out var holds); Vector3 val = pos - array2[i]; cm[i].Add(((Vector3)(ref val)).magnitude * 100f); string value = ((i == 0) ? "left" : "right"); if (!first && array3[i] && !youHeld[i]) { StringBuilder stringBuilder = lines.Append(t.ToString("0.00")).Append(" s your ").Append(value) .Append(" hand closes on something: its hand off yours ") .Append((((Vector3)(ref val)).magnitude * 100f).ToString("0.0")) .Append(" cm (x ") .Append((val.x * 100f).ToString("0.0")) .Append(", y ") .Append((val.y * 100f).ToString("0.0")) .Append(", z ") .Append((val.z * 100f).ToString("0.0")) .Append("), it holds ") .Append(holds ? "something" : "nothing") .Append(", grip fed ") .Append(array4[i].ToString("0.00")) .Append(", its hand to its pouch "); object value2; if (!((Object)(object)componentInChildren != (Object)null)) { value2 = "(no pouch)"; } else { Vector3 val2 = ((Component)array[i]).transform.position - ((Component)componentInChildren).transform.position; value2 = (((Vector3)(ref val2)).magnitude * 100f).ToString("0") + " cm"; } stringBuilder.Append((string?)value2).Append('\n'); } if (!first && holds != botHeld[i]) { lines.Append(t.ToString("0.00")).Append(" s its ").Append(value) .Append(holds ? " hand takes hold" : " hand lets go") .Append('\n'); } youHeld[i] = array3[i]; botHeld[i] = holds; } first = false; } public string Done() { string text = kind.ToString() + " move: its hands off yours, left " + Stat(cm[0]) + ", right " + Stat(cm[1]); try { File.AppendAllText(Path.Combine(Mod.Folder, "doppel_moves.txt"), "== " + DateTime.Now.ToString("HH:mm:ss") + " " + text + "\n" + lines?.ToString() + "\n"); } catch (Exception) { } return text; static string Stat(List<float> v) { if (v.Count != 0) { return v.OrderBy((float x) => x).ElementAt(v.Count / 2).ToString("0.0") + " cm (most " + v.Max().ToString("0") + ")"; } return "?"; } } } private enum FightState { None, ToCover, Hidden, Peek, Flee, Up } private enum Drive { None, ToCar, Snap, Hands, Wait, Go, Out } public class Step { public string what = ""; public string thing = ""; public string on = ""; public string to = ""; public string at = ""; public string pose = ""; public string text = ""; public float seconds; public override string ToString() { return what + ((thing.Length > 0) ? (" " + thing) : "") + ((on.Length > 0) ? (" on " + on) : "") + ((to.Length > 0) ? (" to " + to) : "") + ((at.Length > 0) ? (" at " + at) : "") + ((pose.Length > 0) ? (" " + pose) : ""); } } public class TaskPlan { public string say = ""; public List<Step> steps = new List<Step>(); public Dictionary<string, Rigidbody> things; public Rigidbody chosen; public Vector3 there; public static TaskPlan Read(string json, Dictionary<string, Rigidbody> things, Rigidbody chosen, Vector3 there) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) try { using JsonDocument jsonDocument = JsonDocument.Parse(json); TaskPlan taskPlan = new TaskPlan { things = things, chosen = chosen, there = there }; if (jsonDocument.RootElement.TryGetProperty("say", out var value)) { taskPlan.say = value.GetString() ?? ""; } foreach (JsonElement item in jsonDocument.RootElement.GetProperty("steps").EnumerateArray()) { JsonElement e = item; Step step = new Step { what = S("do"), thing = S("thing"), on = S("on"), to = S("to"), at = S("at"), pose = S("pose"), text = S("text") }; if (e.TryGetProperty("seconds", out var value2) && value2.ValueKind == JsonValueKind.Number) { step.seconds = value2.GetSingle(); } taskPlan.steps.Add(step); string S(string n) { if (!e.TryGetProperty(n, out var value3) || value3.ValueKind != JsonValueKind.String) { return ""; } return value3.GetString() ?? ""; } } return taskPlan; } catch (Exception) { return null; } } } private enum GripOp { Move, Support, Release } private enum Sight { Open, Thing, Bot, New, You } private State state; private Mode mode = Mode.Follow; private RigManager rig; private OpenControllerRig controls; private readonly Feed feed = new Feed(); private readonly Navigator nav = new Navigator(); private readonly Holsters holsters = new Holsters(); private float since; private float made; private float blewSince = -1f; private bool holstersPending; private Vector3 standAt; private Vector3 headAt; private float lookYaw; private float lookPitch; private bool walking; private float walkSpeed; private float speedTimes; private Vector3 walkDir; private float crouch; private float crouchWant; private float jumpUntil = -10f; private float dropUntil = -10f; private List<Pose> baseClip; private Moves.Kind baseKind; private float baseStart; private int baseCursor; private List<Pose> move; private Moves.Kind moveKind; private float moveStart; private Quaternion moveTurn; private Vector3 moveShift; private int moveCursor; private MoveCheck check; private bool riseGate; private float moveUntil = float.MaxValue; private Action afterMove; private float riseHeadFrom; private float riseYoursFrom; private float riseHeld; private int riseCursor; private RoomInput lastOut; private RoomInput cutFrom; private bool wasAiming; private float cutAt = -10f; private float cutFor = -1f; private InventorySlotReceiver[] slots; private bool holstered; private float holsteredAt = -10f; private static float pointSince = -1f; private static float pointedAt = -100f; private static Vector3 pointPlace; private static int watchFrame = -1; private float pointSeen = -100f; private float stareSince = -1f; private float staredAt = -100f; private static Vector3 youStoodAt; private static float youStoodSince; private float cameOverAt = -1000f; private bool drawn; private float skill; private float quick; private float brave; private float coverLove; private float patience; private float strafe; private float giveUp; private Vector3 missBy; private static float furiousUntil = -10f; private FightState fighting; private float phaseAt; private float phaseFor; private float fleeAgainAt; private float lookedAt; private float lastHurt = -100f; private Vector3 coverAt; private Vector3 peekAt; private Vector3 fleeTo; private bool coverLow; private bool triedGiveUp; private int peeks; private readonly List<float> hits = new List<float>(); private static readonly Dictionary<DoppelBot, Vector3> coverTaken = new Dictionary<DoppelBot, Vector3>(); private float gaveUpAt; private float sparedFor; private float coverLookAt; private float strafeAt; private float strafeSide = 1f; private Drive drive; private DriveOrder driveOrder; private Transform car; private Transform driveTarget; private Rigidbody carBody; private Rigidbody wheel; private Seat seat; private string carKind = ""; private Vector3 drivePoint; private Vector3 driveHome; private Vector3 wheelPivotLocal; private Vector3 wheelAxisLocal; private Quaternion wheelRest; private bool driveBack; private bool goingHome; private bool driveFlat; private readonly Grip[] wheelGrips = (Grip[])(object)new Grip[2]; private readonly bool[] wheelHeld = new bool[2]; private readonly Vector3[] wheelHandPos = (Vector3[])(object)new Vector3[2]; private readonly Quaternion[] wheelHandRot = (Quaternion[])(object)new Quaternion[2]; private readonly Vector3[] fedHand = (Vector3[])(object)new Vector3[2]; private readonly Vector3[] reachFix = (Vector3[])(object)new Vector3[2]; private readonly Quaternion[] fedHandRot = (Quaternion[])(object)new Quaternion[2] { Quaternion.identity, Quaternion.identity }; private float driveSince; private float wheelFix; private float wheelWant; private float throttle; private float stuckSince = -1f; private float backUntil = -10f; private float overSince = -1f; private float pathAt; private float lastYaw; private float perDegree = 0.008f; private float topSpeed = 8f; private readonly NavMeshPath drivePath = new NavMeshPath(); private Vector3[] driveCorners = (Vector3[])(object)new Vector3[0]; private static Dictionary<string, float[]> cars; private Vector3 slideFrom; private Vector3 outSpot; private float slideStart; private bool outOfSeat; private readonly List<Vector3> cleanWay = new List<Vector3>(); private Vector3 cleanLast; private float backSide = 1f; private float carHalfWidth = -1f; private int stuckTimes; private Vector3 stuckAt; private bool running; private float runningSince; private float clickUntil = -10f; private float clickAt = -10f; private float ledgeJumpAt = -10f; private float runSaidAt = -10f; private Vector3 gazeAt; private Transform gazeFollow; private string gazeOn = ""; private float gazeUntil; private float gazeYawSpeed; private float gazePitchSpeed; private float gazeDrift; private Vector3 heardAt; private float heardTime = -100f; private readonly float born = Random.Range(0f, 100f); private DoppelBot giveTo; private DoppelBot givenBy; private HandOrder held; private HandOrder afterTake; private float heldUntil = -10f; private float useUntil = -10f; private int heldHand = 1; private int releaseHand = -1; private readonly float[] holdOut = new float[2]; private readonly Dictionary<int, Collider[]> heldShapes = new Dictionary<int, Collider[]>(); private float releaseUntil = -10f; private bool thrown; private int keepHeld; private float throwAt = -1f; private Rigidbody throwBody; private bool throwLet; private bool throwSent; public static float LastShotAt = -10f; private float hp = -1f; private float hurtAt = -100f; private float painAt = -10f; private float bluntAt = -10f; private bool downed; private bool rising; private bool limp; private bool reviving; private float downAt; private float downFor; private float riseAt; private float upAt = -10f; private float wakeAt = -1f; private float diedAt; private IntPtr fleshOf; private Rigidbody[] bodyParts; private static SurfaceData bloodData; private static bool bloodAsked; private float youOverSince = -1f; private DoppelBot rescuer; private DoppelBot rescuing; private float kneelSince = -1f; private Learn.Action doing; private Transform doBody; private Vector3 doSpot; private Vector3 doFrom; private Vector3 doBodyFrom; private Quaternion doBodyRot; private float doFace; private float doSince; private float doFeetFrom; private float climbLookAt = -10f; private float whyNotAt = -10f; private int doPhase = -1; private int doTries; private bool doClimb; private bool doParts; private Vector3 seqTop; private Vector3 seqIn; private float overAhead; private int seqCycle; private int seqDone; private List<(int frame, int hand, float t, float handOverHead)> seqGrabs; private static readonly Dictionary<string, List<(int, int, float, float)>> grabsOf = new Dictionary<string, List<(int, int, float, float)>>(); private Vector3 climbOrderAt; private float climbOrderUntil = -10f; private float climbOrderSince; private Transform strikeAt; private Vector3 strikePoint; private Vector3 strikeOffset; private bool strikeStab; private bool strikeTold; private float strikeUntil = -10f; private float strikeNext; private float strikeSaidAt = -10f; private Rigidbody takeBody; private Grip takeGrip; private int takeHand = 1; private bool takeFromYou; private float takeUntil = -10f; private Vector3 takeFix; private Grip takeGrip2; private Vector3 takeFix2; private float takeLean; private float takeClosed = -1f; private float takeOpenUntil; private float takeHadAt = -1f; private int takeFails; private Rigidbody keepBody; private Rigidbody takenBody; private float keepLostAt = -1f; private List<Pose> takeHold; private readonly Quaternion[] takeRot = (Quaternion[])(object)new Quaternion[2] { Quaternion.identity, Quaternion.identity }; private readonly float[] reachFrom = new float[2] { -1f, -1f }; private readonly HashSet<int> takeTried = new HashSet<int>(); private bool brawlAuto; private static readonly Dictionary<string, float> reaches = new Dictionary<string, float>(); private readonly Dictionary<int, List<Collider>> surfacesOf = new Dictionary<int, List<Collider>>(); private TaskPlan plan; private int planStep; private float stepAt; private bool stepBegun; private Rigidbody stepBody; private string holdPose = ""; private readonly List<(GripOp op, int hand)> regrip = new List<(GripOp, int)>(); private List<Pose> regripClip; private int regripFrame; private Rigidbody regripBody; private float opStart; private float regripUntil; private float regripNext; private float closeAt = -1f; private int opTries; private bool cmdSet; private Vector3 cmdPos; private Quaternion cmdRot; private Vector3 supportOn; private readonly Vector3[] stillAt = (Vector3[])(object)new Vector3[2]; private readonly Quaternion[] stillRot = (Quaternion[])(object)new Quaternion[2]; private int sessionKey = -1; private int sessionTries; private float stallSince; private float stallBest; private string regripProp = ""; private static readonly Dictionary<string, (Vector3 pos, Quaternion rot)> gripFix = new Dictionary<string, (Vector3, Quaternion)>(); private static bool gripFixRead; private int holdStyle; private int holdStyleOf; private static readonly Dictionary<List<Pose>, (int frame, int mask)> holdOf = new Dictionary<List<Pose>, (int, int)>(); private bool learned; private bool regripJustDone; private float closedCm; private float closedDeg; private bool planOn; private bool planThinking; private bool planRun; private bool viaOn; private bool onDetour; private Sight planSight; private Sight lastSight = Sight.New; private string planWhy = ""; private Vector3 planPlace; private Vector3 planLook; private Vector3 viaPlace; private Vector3 detourFor; private Vector3 roamHeading; private float planPace = 0.6f; private float thinkUntil; private float pauseUntil; private float pauseNext; private float stayUntil; private int detours; private readonly HashSet<long> visited = new HashSet<long>(); private readonly Dictionary<long, int> badAt = new Dictionary<long, int>(); private static string stanceKey; private static bool hasStance; private static Quaternion stanceHead; private static Vector3 stanceLeft; private static Vector3 stanceRight; private static Quaternion stanceLeftRot; private static Quaternion stanceRightRot; private static float[] stanceLeftHand = new float[7]; private static float[] stanceRightHand = new float[7]; private static float shotGap = 0.4f; private bool aiming; private Vector3 aimPoint; private Transform aimAt; private Vector3 aimOffset; private string aimWhat = ""; private float aimYaw; private float aimPitch; private float biasYaw; private float biasPitch; private float aimYawSpeed; private float aimPitchSpeed; private float onTargetSince = -1f; private float triggerUntil = -10f; private float nextShotAt; private float drawAskedAt = -10f; private float reloadAskedAt = -10f; private float pickAt; private int dryPulls; private Transform toldAt; private Vector3 toldPoint; private float toldUntil = -10f; private float fightOffUntil = -10f; private static AIBrain[] brains = (AIBrain[])(object)new AIBrain[0]; private static float brainsAt = -10f; private static readonly Dictionary<string, (bool, Quaternion, Vector3, Vector3, Quaternion, Quaternion, float[], float[], float)> stances = new Dictionary<string, (bool, Quaternion, Vector3, Vector3, Quaternion, Quaternion, float[], float[], float)>(); private int edge; private float edgeAt = -10f; private Vector3 lastSeenYou; private float lastSeenYouAt = -100f; public bool BlewUp { get; private set; } public RigManager Rig => rig; public string AvatarKey { get; private set; } = "default"; public bool Ready => state == State.On; public Transform Head { get { if (!((Object)(object)rig != (Object)null) || !((Object)(object)rig.physicsRig != (Object)null)) { return null; } return ((Rig)rig.physicsRig).m_head; } } public Vector3 FeetAt { get { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)rig != (Object)null) || !Pose.Frame(rig, out var at, out var _)) { return Vector3.zero; } return at; } } public bool HoldsSomething { get { if (!Holding(0)) { return Holding(1); } return true; } } public bool CanShoot { get { if (!HoldsGun()) { return HasHolstered(); } return true; } } private static float YouStoodFor => Time.time - youStoodSince; public bool surrendered => fighting == FightState.Up; private float HpLeft { get { if (!(hp < 0f)) { return Mathf.Clamp01(hp / MaxHp); } return 1f; } } public bool InCar { get { if (drive != Drive.Snap && drive != Drive.Hands && drive != Drive.Wait && drive != Drive.Go) { return drive == Drive.Out; } return true; } } public bool Driving2 => InCar; public bool Riding => false; public bool DrivingNow => drive == Drive.Go; public bool dead { get; private set; } public bool Puppet => false; public bool Down { get { if (!downed && !rising) { return dead; } return true; } } private float MaxHp => (((Object)(object)rig != (Object)null && (Object)(object)rig.health != (Object)null && rig.health.max_Health > 0f) ? rig.health.max_Health : 10f) * Tuning.F("bot.hp", 1.44f); public bool Doing => doPhase >= 0; public object DoingWhat => doing; private bool Brawling { get { if (!(Time.time < strikeUntil)) { return brawlAuto; } return true; } } private static string GripFixFile => Path.Combine(Mod.Folder, "grip_fixes.txt"); public bool enemy { get; private set; } public void MovesForWhatItHolds() { string name = ""; string text = ""; try { if ((Object)(object)GunInHand(out var hand) != (Object)null) { text = Moves.HeldProp((hand == 0) ? rig.physicsRig.leftHand : rig.physicsRig.rightHand, out name); } if (text.Length == 0 && (Object)(object)rig != (Object)null && (Object)(object)rig.physicsRig != (Object)null) { text = Moves.HeldProp(rig.physicsRig.rightHand, out name); } if (text.Length == 0 && (Object)(object)rig != (Object)null && (Object)(object)rig.physicsRig != (Object)null) { text = Moves.HeldProp(rig.physicsRig.leftHand, out name); } } catch (Exception) { } Moves.Prop = text; Moves.PropName = name; } public bool Spawn(int index) { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) RigManager player = Player.RigManager; XRApi xr = MarrowGame.xr; if ((Object)(object)player == (Object)null || xr == null || xr.HMD == null || !Pose.Frame(player, out var at, out var yaw)) { Mod.Say("no player rig"); return false; } float num = Moves.Pick(Moves.Kind.Idle)?[0].headRaw.y ?? ((XRDevice)xr.HMD)._Position_k__BackingField.y; headAt = new Vector3(0f, Mathf.Max(num, 1f), 0f); Quaternion val = Quaternion.Euler(0f, yaw, 0f); Vector3 pos = at + val * new Vector3(((index % 2 == 0) ? 1f : (-1f)) * (float)((index + 1) / 2) * 1.2f, 0f, enemy ? Tuning.F("enemy.spawn.far", 10f) : 2f); state = State.Making; since = (made = Time.time); Log.Event(enemy ? ("making an enemy Doppel " + Tuning.F("enemy.spawn.far", 10f) + " m in front of you") : "making Doppel 2 m in front of you"); BotBody.Create(pos, val * Quaternion.Euler(0f, 180f, 0f), delegate(RigManager made) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) rig = made; controls = ((Il2CppObjectBase)rig.ControllerRig).TryCast<OpenControllerRig>(); string text = ""; try { text = ((player.AvatarCrate != null) ? ((ScannableReference)player.AvatarCrate).Barcode.ID : ""); AvatarKey = ((text.Length > 0) ? text : "default"); } catch (Exception) { } Vector3 scale = (((Object)(object)player.avatar != (Object)null) ? ((Component)player.avatar).transform.localScale : Vector3.one); BotBody.UseAvatar(rig, text, scale, delegate(bool ok) { if (!ok) { Mod.Say("your avatar could not be put on Doppel: it wears the default one"); } BotBody.CopyBody(Player.RigManager, rig); string ghostFile = Path.Combine(Mod.Folder, "doppel_spawn.csv"); try { Holsters.Save(ghostFile, Player.RigManager); int num2 = holsters.Fill(ghostFile, rig); holstersPending = num2 > 0; if (num2 > 0) { Log.Event("giving Doppel your " + num2 + " holstered things"); } } catch (Exception ex2) { MelonLogger.Warning("Doppel: holsters not filled: " + ex2.Message); } state = State.Settling; since = Time.time; }); }); return true; } public void Remove() { holsters.Clear(); Feed.Restore(); state = State.Off; if ((Object)(object)rig != (Object)null) { try { Mod.BotGoing(rig); Object.Destroy((Object)(object)((Component)rig).gameObject); } catch (Exception) { } } rig = null; controls = null; } public void LevelGone() { drive = Drive.None; car = null; seat = null; Feed.Restore(); state = State.Off; rig = null; controls = null; } public void SetMode(Mode m) { mode = m; planOn = false; stayUntil = 0f; if (m == Mode.Stay || m == Mode.Follow || m == Mode.Roam) { nav.Clear(); } } public bool Update() { if (state == State.Off) { return false; } if ((Object)(object)rig == (Object)null && state != State.Making) { Mod.Say("a Doppel is gone"); LevelGone(); return false; } if ((state == State.Making || state == State.Settling) && Time.time - since > 20f) { Mod.Say("Doppel was not ready after 20 s: removed"); Remove(); return false; } if (state == State.Settling) { BotBody.Spatial(rig); state = State.On; Log.Event("Doppel is ready (" + (Time.time - made).ToString("0.0") + " s)"); } if (holstersPending && holsters.Ready()) { holstersPending = false; } if (state == State.On && Speed(rig) > Tuning.F("blewup.speed", 40f)) { if (blewSince < 0f) { blewSince = Time.time; } if (Time.time - blewSince > 0.4f) { Log.Event("its body blew up (" + Speed(rig).ToString("0") + " m/s) - made again"); Mod.Say("Doppel's body glitched - making it again"); BlewUp = true; WallGrab.DropAll(); Remove(); return false; } } else { blewSince = -1f; } return true; } public bool Play(Moves.Kind kind) { string who = Moves.Who; string prop = Moves.Prop; string propName = Moves.PropName; Moves.Who = AvatarKey; MovesForWhatItHolds(); List<Pose> list = Moves.Pick(kind); Moves.Who = who; Moves.Prop = prop; Moves.PropName = propName; if (list == null) { Mod.Say("no " + kind.ToString() + " move recorded yet (Doppel v2, Moves)"); return false; } return PlayClip(list, kind); } public bool PlayClip(List<Pose> clip, Moves.Kind kind, float? faceWorldYaw = null, Vector3? handAt = null, int handFrame = -1, int handSide = 1, float from = 0f, float until = float.MaxValue) { //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_0280: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02cc: Unknown result type (might be due to invalid IL or missing references) //IL_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02d6: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) moveUntil = until; afterMove = null; keepHeld = 0; if (state != State.On || clip == null || clip.Count < 2) { return false; } int cursor = 0; Pose pose = ((from > 0f) ? (Sample(clip, from / Moves.SpeedOf(clip), ref cursor) ?? clip[0]) : clip[0]); Transform vrRoot = controls.vrRoot; float num = (((Object)(object)vrRoot != (Object)null) ? Mathf.Max(0.01f, vrRoot.lossyScale.x) : 1f); float num2 = Mathf.DeltaAngle(YawOf(pose.headRot), YawOf(pose.headRawRot)); Vector3 val = pose.headRaw - Quaternion.Euler(0f, num2, 0f) * (pose.head / num); if ((Object)(object)vrRoot != (Object)null && Pose.Frame(rig, out var at, out var yaw)) { float num3 = Mathf.DeltaAngle(vrRoot.eulerAngles.y, faceWorldYaw ?? yaw); Vector3 val2 = vrRoot.InverseTransformPoint(at); moveTurn = Quaternion.Euler(0f, Mathf.DeltaAngle(num2, num3), 0f); moveShift = val2 - moveTurn * val; moveShift.y = 0f; if (handAt.HasValue && handFrame >= 0 && handFrame < clip.Count) { Pose pose2 = clip[handFrame]; Vector3 val3 = vrRoot.TransformPoint(moveTurn * ((handSide == 0) ? pose2.leftRaw : pose2.rightRaw) + moveShift); Vector3 val4 = handAt.Value - val3; Vector3 val5 = Vector3.ClampMagnitude(Flat(val4), Tuning.F("pick.shift", 0.6f)); ((Vector3)(ref val4))..ctor(val5.x, Mathf.Clamp(val4.y, 0f - Tuning.F("pick.lower", 0.35f), Tuning.F("pick.lower", 0.35f)), val5.z); moveShift += vrRoot.InverseTransformVector(val4); } } else { moveTurn = Quaternion.Euler(0f, Mathf.DeltaAngle(YawOf(pose.headRawRot), lookYaw), 0f); moveShift = new Vector3(headAt.x, 0f, headAt.z) - moveTurn * new Vector3(pose.headRaw.x, 0f, pose.headRaw.z); } Cut(); move = clip; riseGate = false; moveKind = kind; moveStart = Time.time - from / Moves.SpeedOf(clip); moveCursor = 0; check = new MoveCheck(kind); Log.Event("plays a " + kind.ToString() + " move (" + ((clip[clip.Count - 1].time - clip[0].time) / Moves.SpeedOf(clip)).ToString("0.0") + " s, at " + Moves.SpeedOf(clip).ToString("0.0") + "x)"); return true; } public void VoiceFollow() { GetOut(); SetMode(Mode.Follow); } public void VoiceStop(bool getOut) { HoldFire(); strikeUntil = -10f; climbOrderUntil = -10f; takeBody = null; held = HandOrder.Keep; crouchWant = 0f; if (InCar) { if (getOut) { GetOut(); } else { Park(); } } else { SetMode(Mode.Stay); } } public void VoiceStand(Vector3 at) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) standAt = at; mode = Mode.StandAt; nav.Clear(); } public void VoiceAway() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) Transform head = Player.Head; if (Navigator.RandomPlace(((Object)(object)head != (Object)null) ? head.position : FeetAt, 8f, 14f, out var place)) { VoiceStand(place); } else { SetMode(Mode.Stay); } } public void VoicePosture(Posture p) { switch (p) { case Posture.Crouch: crouchWant = 1f; break; case Posture.Up: crouchWant = 0f; break; } } public void VoiceJump() { if (Moves.Count(Moves.Kind.Jump) <= 0 || !Play(Moves.Kind.Jump)) { jumpUntil = Time.time + 0.15f; } } public void VoiceSpeed(float times) { speedTimes = times; } public bool VoiceHolster(bool draw) { if (draw) { if (!HoldsSomething && HasHolstered()) { return Play(Moves.Kind.Draw); } return false; } if (HoldsSomething) { return Play(Moves.Kind.Holster); } return false; } public bool VoiceHeld(HandOrder what) { if (what == HandOrder.Drop || what == HandOrder.Toss || what == HandOrder.Bring) { keepBody = null; holdPose = ""; } if (what == HandOrder.Drop) { if (!HoldsSomething) { return false; } dropUntil = Time.time + 0.6f; return true; } return HeldOrder(what); } public bool VoiceReload() { if (HoldsGun()) { return Play(Moves.Kind.Reload); } return false; } public bool VoiceWave() { return Play(Moves.Kind.Wave); } public bool EarlyPrefix() { if (state == State.Off || (Object)(object)controls == (Object)null) { return false; } try { float deltaTime = Time.deltaTime; crouch = Mathf.MoveTowards(crouch, crouchWant, deltaTime * 2.5f); if (state == State.On) { PlanTick(); } if (move != null && keepHeld != 0 && (((keepHeld & 1) != 0 && !Holding(0)) || ((keepHeld & 2) != 0 && !Holding(1)))) { Log.Event("dropped what it was using - the " + moveKind.ToString() + " move stopped"); move = null; afterMove = null; keepHeld = 0; Cut(); } RoomInput roomInput = ((move != null) ? MoveInput() : null); if (roomInput == null) { if (state == State.On) { Think(deltaTime); } roomInput = OwnInput(); } feed.Put(controls, Smooth(roomInput)); return true; } catch (Exception ex) { MelonLogger.Warning("Doppel: a frame failed: " + ex); Feed.Restore(); return false; } } private void Think(float dt) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_030d: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_0332: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_03a6: Unknown result type (might be due to invalid IL or missing references) //IL_03ab: Unknown result type (might be due to invalid IL or missing references) //IL_03ac: Unknown result type (might be due to invalid IL or missing references) //IL_03b1: Unknown result type (might be due to invalid IL or missing references) //IL_03b6: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_040c: Unknown result type (might be due to invalid IL or missing references) //IL_03f7: Unknown result type (might be due to invalid IL or missing references) //IL_03f8: Unknown result type (might be due to invalid IL or missing references) //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_03d8: Unknown result type (might be due to invalid IL or missing references) //IL_0430: Unknown result type (might be due to invalid IL or missing references) //IL_05b7: Unknown result type (might be due to invalid IL or missing references) //IL_05df: Unknown result type (might be due to invalid IL or missing references) //IL_05e1: Unknown result type (might be due to invalid IL or missing references) //IL_0479: Unknown result type (might be due to invalid IL or missing references) //IL_0452: Unknown result type (might be due to invalid IL or missing references) //IL_0453: Unknown result type (might be due to invalid IL or missing references) //IL_045d: Unknown result type (might be due to invalid IL or missing references) //IL_0462: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_0487: Unknown result type (might be due to invalid IL or missing references) //IL_0488: Unknown result type (might be due to invalid IL or missing references) //IL_0495: Unknown result type (might be due to invalid IL or missing references) //IL_049a: Unknown result type (might be due to invalid IL or missing references) //IL_04a3: Unknown result type (might be due to invalid IL or missing references) //IL_04a8: Unknown result type (might be due to invalid IL or missing references) //IL_04c2: Unknown result type (might be due to invalid IL or missing references) //IL_04c7: Unknown result type (might be due to invalid IL or missing references) //IL_04c8: Unknown result type (might be due to invalid IL or missing references) //IL_04cd: Unknown result type (might be due to invalid IL or missing references) //IL_04d2: Unknown result type (might be due to invalid IL or missing references) //IL_057c: Unknown result type (might be due to invalid IL or missing references) //IL_0587: Unknown result type (might be due to invalid IL or missing references) RigManager rigManager = Player.RigManager; Transform vrRoot = controls.vrRoot; if ((Object)(object)rigManager == (Object)null || (Object)(object)vrRoot == (Object)null || (Object)(object)rig.physicsRig == (Object)null || !Pose.Frame(rig, out var at, out var yaw) || DownStep(dt)) { return; } Pose.Frame(rigManager, out var at2, out var _); Vector3 position = controls.headset.position; OpenControllerRig obj = ((Il2CppObjectBase)rigManager.ControllerRig).TryCast<OpenControllerRig>(); Transform you = ((obj != null) ? obj.headset : null); Vector3 val = Flat(at2 - at); float magnitude = ((Vector3)(ref val)).magnitude; if (DriveThink(at, dt)) { return; } Aware(you, at, position); if (RescueStep(at, dt) || DoStep(at, dt) || ClimbOrder(at, dt)) { return; } KeepHold(); if (RegripStep()) { Gaze(dt, vrRoot, at, yaw, position, you); return; } if ((Object)(object)keepBody != (Object)null && (Object)(object)takeBody == (Object)null && !Doing) { if (HoldsBody(0, keepBody) || HoldsBody(1, keepBody)) { keepLostAt = -1f; } else { if (((Component)keepBody).gameObject.activeInHierarchy) { val = Flat(keepBody.position - at); if (!(((Vector3)(ref val)).magnitude > Tuning.F("keep.far", 8f)) && !HeldByAnyone(((Component)keepBody).transform.root)) { if (keepLostAt < 0f) { keepLostAt = Time.time; } else if (Time.time - keepLostAt > Tuning.F("keep.wait", 0.6f)) { val = keepBody.velocity; if (((Vector3)(ref val)).magnitude < 2f) { Rigidbody val2 = keepBody; keepLostAt = -1f; Log.Event("dropped the " + ((Object)val2).name + " - picks it up again"); Mod.Say(Voice.NameOf(this) + ": dropped it, picking it up"); afterTake = HandOrder.Keep; if (!StartTake(val2, fromYou: false)) { keepBody = null; } } } goto IL_0269; } } keepBody = null; } } goto IL_0269; IL_0269: if (ReceiveStep(at, dt)) { Gaze(dt, vrRoot, at, yaw, position, you); } else if (TakeStep(at, dt)) { SprintClick(); } else { if (HeldStep(at, dt) || (Time.time < strikeUntil && Brawl(at, position, dt))) { return; } strikeTold = false; if (CombatStep(at, position, dt)) { Gaze(dt, vrRoot, at, yaw, position, you); } else if (Fight(at, position)) { if (!CoverFeet(at, dt)) { FightFeet(at, dt); Strafe(at); } } else { if (Brawl(at, position, dt)) { return; } if (HuntStep(at, at2, dt)) { Gaze(dt, vrRoot, at, yaw, position, you); } else { if (mode == Mode.Follow && ClimbToYou(at, at2)) { return; } Vector3? val3 = null; float pace = 0f; float num = Tuning.F("doppel.stop", 1.6f); float num2 = Tuning.F("doppel.go", 2.6f); if (mode == Mode.Follow && magnitude > (walking ? num : num2)) { val3 = at2; } else if (mode == Mode.StandAt || mode == Mode.Away) { val = Flat(standAt - at); if (((Vector3)(ref val)).magnitude > (walking ? 0.4f : 0.8f)) { val3 = standAt; } else { mode = Mode.Stay; } } else if (mode == Mode.Roam) { val3 = RoamGoal(at, position, yaw, you, out pace); } walkDir = Vector3.zero; walkSpeed = 0f; if (val3.HasValue) { nav.SetGoal(val3.Value); Vector3 chest = (((Object)(object)((Rig)rig.physicsRig).m_chest != (Object)null) ? ((Rig)rig.physicsRig).m_chest.position : (at + Vector3.up * 1.2f)); walkDir = nav.Steer(at, chest, Flat(controls.headset.forward), out var rise, out var drop); float num3; if (mode != Mode.Roam) { if (mode != Mode.Follow) { val = Flat(val3.Value - at); num3 = StandPace(((Vector3)(ref val)).magnitude); } else { num3 = FollowPace(magnitude, num); } } else { num3 = pace; } float num4 = num3; if (mode == Mode.Roam) { running = pace >= 1f; } if (speedTimes > 1f) { running = true; } else if (speedTimes > 0f && speedTimes < 1f) { running = false; } walkSpeed = (running ? 1f : Mathf.Clamp01(num4 * ((speedTimes > 0f) ? speedTimes : 1f))); Footing(at, rise, drop, nav.CheckStuck(at, walkSpeed, dt)); } else { running = false; if (mode != Mode.Roam) { nav.Clear(); } } AsideForYou(position); walking = ((Vector3)(ref walkDir)).sqrMagnitude > 0.01f; SprintClick(); Gaze(dt, vrRoot, at, yaw, position, you); } } } } private void GateRise(int grabFrame) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (move != null && grabFrame >= 0 && grabFrame < move.Count) { riseGate = true; riseHeadFrom = controls.headset.position.y; riseYoursFrom = move[grabFrame].at.y + move[grabFrame].head.y; riseHeld = 0f; riseCursor = 0; } } private RoomInput MoveInput() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_02ec: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_0308: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0313: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Unknown result type (might be due to invalid IL or missing references) //IL_0325: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_0336: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Unknown result type (might be due to invalid IL or missing references) //IL_0346: Unknown result type (might be due to invalid IL or missing references) if (riseGate) { Pose pose = Sample(move, Time.time - moveStart, ref riseCursor); if (pose != null) { float num = pose.at.y + pose.head.y - riseYoursFrom; float num2 = controls.headset.position.y - riseHeadFrom; if (num2 < num - Tuning.F("climb.rise.slack", 0.25f) && riseHeld < Tuning.F("climb.rise.wait", 2f)) { moveStart += Time.deltaTime; riseHeld += Time.deltaTime; } else if (num2 >= num - Tuning.F("climb.rise.slack", 0.25f)) { riseHeld = 0f; } } } Pose pose2 = (((Time.time - moveStart) * Moves.SpeedOf(move) > moveUntil) ? null : Sample(move, Time.time - moveStart, ref moveCursor)); if (pose2 == null) { Pose pose3 = pose2 ?? Sample(move, Mathf.Min(moveUntil, move[move.Count - 1].time - move[0].time) / Moves.SpeedOf(move), ref moveCursor) ?? move[move.Count - 1]; Vector3 val = moveTurn * pose3.headRaw + moveShift; headAt = new Vector3(val.x, headAt.y, val.z); lookYaw = YawOf(moveTurn * pose3.headRawRot); Log.Event("the " + moveKind.ToString() + " move is done: " + check?.Done()); move = null; keepHeld = 0; if (afterMove != null) { Action action = afterMove; afterMove = null; action(); if (move != null) { return MoveInput(); } } Cut(); return null; } check?.Frame(Time.time - moveStart, rig, pose2); RoomInput roomInput = RoomInput.Of(pose2); roomInput.head = moveTurn * roomInput.head + moveShift; roomInput.left = moveTurn * roomInput.left + moveShift; roomInput.right = moveTurn * roomInput.right + moveShift; roomInput.headRot = moveTurn * roomInput.headRot; roomInput.leftRot = moveTurn * roomInput.leftRot; roomInput.rightRot = moveTurn * roomInput.rightRot; if ((keepHeld & 1) != 0 && Holding(0)) { roomInput.leftHand[0] = 1f; } if ((keepHeld & 2) != 0 && Holding(1)) { roomInput.rightHand[0] = 1f; } return roomInput; } private RoomInput OwnInput() { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02ee: Unknown result type (might be due to invalid IL or missing references) //IL_02f3: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_0304: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Unknown result type (might be due to invalid IL or missing references) //IL_0319: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0323: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0344: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_0347: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_043d: Unknown result type (might be due to invalid IL or missing references) //IL_0448: Unknown result type (might be due to invalid IL or missing references) //IL_044d: Unknown result type (might be due to invalid IL or missing references) if (aiming != wasAiming) { wasAiming = aiming; Cut(); } if (aiming) { return AimInput(); } if (InCar && (Object)(object)car != (Object)null && (Object)(object)seat != (Object)null) { return DriveInput(); } RoomInput roomInput = new RoomInput(); Quaternion val = Quaternion.Euler(0f, lookYaw, 0f); Vector3 val2 = default(Vector3); ((Vector3)(ref val2))..ctor(headAt.x, 0f, headAt.z); Vector3 val3 = Vector3.down * crouch * Tuning.F("doppel.crouch", 0.55f); Pose pose = BaseFrame(); if (pose != null) { Quaternion val4 = val * Quaternion.Inverse(Quaternion.Euler(0f, YawOf(pose.headRawRot), 0f)); Vector3 val5 = default(Vector3); ((Vector3)(ref val5))..ctor(pose.headRaw.x, 0f, pose.headRaw.z); roomInput.head = val2 + val4 * (pose.headRaw - val5) + val3; roomInput.headRot = val * Quaternion.Euler(lookPitch, 0f, 0f); Quaternion val6 = val4; if ((HoldsSomething || (Object)(object)takeBody != (Object)null) && Pose.Frame(rig, out var _, out var yaw)) { float num = Mathf.DeltaAngle(Mathf.DeltaAngle(controls.vrRoot.eulerAngles.y, yaw), lookYaw); float num2 = Tuning.F("hold.ahead", 25f); if (Mathf.Abs(num) > num2) { val6 = Quaternion.Euler(0f, 0f - (num - Mathf.Sign(num) * num2), 0f) * val4; } } roomInput.left = val2 + val6 * (pose.leftRaw - val5) + val3; roomInput.right = val2 + val6 * (pose.rightRaw - val5) + val3; roomInput.leftRot = val6 * pose.leftRawRot; roomInput.rightRot = val6 * pose.rightRawRot; roomInput.leftHand = (float[])pose.leftHand.Clone(); roomInput.rightHand = (float[])pose.rightHand.Clone(); } else { roomInput.head = headAt + val3; roomInput.headRot = val * Quaternion.Euler(lookPitch, 0f, 0f); roomInput.left = roomInput.head + val * new Vector3(-0.2f, -0.62f, 0.12f); roomInput.right = roomInput.head + val * new Vector3(0.2f, -0.62f, 0.12f); roomInput.leftRot = (roomInput.rightRot = val * Quaternion.Euler(60f, 0f, 0f)); } bool flag = Time.time < dropUntil; bool flag2 = baseKind == Moves.Kind.PunchIdle && pose != null; roomInput.leftHand[0] = ((Holding(0) && !flag) ? 1f : ((flag2 && !Holding(0)) ? pose.leftHand[0] : 0f)); roomInput.rightHand[0] = ((Holding(1) && !flag) ? 1f : ((flag2 && !Holding(1)) ? pose.rightHand[0] : 0f)); roomInput.leftHand[1] = ((flag2 && !Holding(0)) ? pose.leftHand[1] : 0f); roomInput.rightHand[1] = ((flag2 && !Holding(1)) ? pose.rightHand[1] : 0f); if (walking) { roomInput.leftStick = Stick(walkDir, walkSpeed); } TakeHand(roomInput); HeldHands(roomInput); RegripHands(roomInput); HoldPoseHands(roomInput); HandsUp(roomInput); if (Time.time < jumpUntil) { roomInput.rightButtons |= 2; } if (Time.time < clickUntil) { roomInput.leftButtons |= 1; } return roomInput; } private void Cut() { if (lastOut != null) { cutFrom = lastOut; cutAt = Time.time; cutFor = -1f; } } private RoomInput Smooth(RoomInput target) { float num = (Time.time - cutAt) / Mathf.Max(0.05f, (cutFor > 0f) ? cutFor : Tuning.F("doppel.blend", 0.4f)); if (cutFrom != null && num < 1f) { target = RoomInput.Blend(cutFrom, target, num * num * (3f - 2f * num)); } lastOut = target; return target; } private Vector2 Stick(Vector3 dir, float speed) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)controls == (Object)null) { return Vector2.zero; } Transform val = (((int)controls.directionMode == 0 && (Object)(object)((ControllerRig)controls).leftController != (Object)null) ? ((Component)((ControllerRig)controls).leftController).transform : controls.headset); if ((Object)(object)val == (Object)null) { return Vector2.zero; } Vector3 val2 = Flat(val.forward); float num = Mathf.DeltaAngle(YawOf(Quaternion.LookRotation((((Vector3)(ref val2)).sqrMagnitude > 1E-06f) ? Flat(val.forward) : Vector3.forward, Vector3.up)), YawOf(Quaternion.LookRotation(dir, Vector3.up))) * ((float)Math.PI / 180f); return new Vector2(Mathf.Sin(num), Mathf.Cos(num)) * speed; } private Pose BaseFrame() { int num; if (HoldsGun()) { num = ((Moves.Count(Moves.Kind.GunIdle) > 0) ? 1 : 0); if (num != 0) { goto IL_0034; } } else { num = 0; } if (!HoldsSomething || HoldsGun()) { goto IL_0034; } int num2 = ((Moves.Count(Moves.Kind.MeleeIdle) > 0) ? 1 : 0); goto IL_0035; IL_0034: num2 = 0; goto IL_0035; IL_0035: bool flag = (byte)num2 != 0; bool flag2 = num == 0 && !flag && Brawling && !HoldsSomething && Moves.Count(Moves.Kind.PunchIdle) > 0; Moves.Kind kind = ((num != 0) ? Moves.Kind.GunIdle : (flag ? Moves.Kind.MeleeIdle : (flag2 ? Moves.Kind.PunchIdle : (walking ? Moves.Kind.Walk : Moves.Kind.Idle)))); if (baseClip == null || kind != baseKind) { Cut(); baseClip = ((kind == Moves.Kind.MeleeIdle) ? PickHeld(kind) : Moves.Pick(kind)) ?? Moves.Pick((kind != Moves.Kind.Walk) ? Moves.Kind.Walk : Moves.Kind.Idle); baseKind = kind; baseStart = Time.time; baseCursor = 0; } if (baseClip == null) { return null; } Pose pose = Sample(baseClip, Time.time - baseStart, ref baseCursor); if (pose == null) { baseClip = ((baseKind == Moves.Kind.MeleeIdle) ? PickHeld(baseKind, baseClip) : Moves.Pick(baseKind, baseClip)) ?? baseClip; Cut(); baseStart = Time.time; baseCursor = 0; pose = Sample(baseClip, 0f, ref baseCursor); } return pose; } private bool Holding(int hand) { try { Hand val = ((!((Object)(object)rig != (Object)null) || !((Object)(object)rig.physicsRig != (Object)null)) ? null : ((hand == 0) ? rig.physicsRig.leftHand : rig.physicsRig.rightHand)); return (Object)(object)val != (Object)null && (Object)(object)val.m_CurrentAttachedGO != (Object)null; } catch (Exception) { return false; } } private bool HoldsGun() { Hand[] array = new Hand[2]; RigManager obj = rig; object obj2; if (obj == null) { obj2 = null; } else { PhysicsRig physicsRig = obj.physicsRig; obj2 = ((physicsRig != null) ? physicsRig.leftHand : null); } array[0] = (Hand)obj2; RigManager obj3 = rig; object obj4; if (obj3 == null) { obj4 = null; } else { PhysicsRig physicsRig2 = obj3.physicsRig; obj4 = ((physicsRig2 != null) ? physicsRig2.rightHand : null); } array[1] = (Hand)obj4; Hand[] array2 = (Hand[])(object)array; foreach (Hand val in array2) { try { if ((Object)(object)val != (Object)null && (Object)(object)val.m_CurrentAttachedGO != (Object)null && (Object)(object)val.m_CurrentAttachedGO.GetComponentInParent<Gun>() != (Object)null) { return true; } } catch (Exception) { } } return false; } private bool HasHolstered() { if (Time.time - holsteredAt < 0.5f) { return holstered; } holsteredAt = Time.time; holstered = false; try { if (slots == null || slots.Length == 0 || (Object)(object)slots[0] == (Object)null) { slots = Il2CppArrayBase<InventorySlotReceiver>.op_Implicit(((Component)rig.physicsRig).GetComponentsInChildren<InventorySlotReceiver>(true)); } InventorySlotReceiver[] array = slots; foreach (InventorySlotReceiver val in array) { if ((Object)(object)val != (Object)null && (Object)(object)val._slottedWeapon != (Object)null) { holstered = true; } } } catch (Exception) { slots = null; } return holstered; } private static Pose Sample(List<Pose> clip, float t, ref int cursor) { t *= Moves.SpeedOf(clip); float num = clip[0].time + t; if (num > clip[clip.Count - 1].time) { return null; } if (cursor >= clip.Count || clip[cursor].time > num) { cursor = 0; } while (cursor + 1 < clip.Count && clip[cursor + 1].time <= num) { cursor++; } Pose pose = clip[cursor]; Pose pose2 = clip[Math.Min(cursor + 1, clip.Count - 1)]; float num2 = pose2.time - pose.time; return Pose.Blend(pose, pose2, (num2 > 1E-05f) ? Mathf.Clamp01((num - pose.time) / num2) : 0f, t); } private static float YawOf(Quaternion q) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Flat(q * Vector3.forward); if (!(((Vector3)(ref val)).sqrMagnitude > 1E-06f)) { return 0f; } Quaternion val2 = Quaternion.LookRotation(val, Vector3.up); return ((Quaternion)(ref val2)).eulerAngles.y; } private static Vector3 Flat(Vector3 v) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) v.y = 0f; return v; } private static void WatchYou(Transform you) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL
UserLibs/System.Speech.dll
Decompiled 3 weeks ago
The result has been truncated due to the large size, download it to view full contents!
#define TRACE using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Speech.AudioFormat; using System.Speech.Internal; using System.Speech.Internal.GrammarBuilding; using System.Speech.Internal.ObjectTokens; using System.Speech.Internal.SapiInterop; using System.Speech.Internal.SrgsCompiler; using System.Speech.Internal.SrgsParser; using System.Speech.Internal.Synthesis; using System.Speech.Recognition; using System.Speech.Recognition.SrgsGrammar; using System.Speech.Synthesis; using System.Speech.Synthesis.TtsEngine; using System.Text; using System.Threading; using System.Xml; using System.Xml.XPath; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("System.Speech")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Internal implementation package not meant for direct consumption. Please do not reference directly. \nProvides types to perform speech synthesis and speech recognition.\r\n\r\nCommonly Used Types\r\nSystem.Speech.Synthesis.SpeechSynthesizer\r\nSystem.Speech.Recognition.SpeechRecognizer")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Speech")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: TargetPlatform("Windows7.0")] [assembly: SupportedOSPlatform("Windows")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] namespace System.Speech { internal static class SR { private static ResourceManager s_resourceManager = new ResourceManager("ExceptionStringTable", typeof(SR).Assembly); internal static string Get(SRID id, params object[] args) { string text = s_resourceManager.GetString(id.ToString()); if (string.IsNullOrEmpty(text)) { text = s_resourceManager.GetString("Unavailable"); } else if (args != null && args.Length != 0) { text = string.Format(text, args); } return text; } } internal enum SRID { NullParamIllegal, ArrayOfNullIllegal, ParamsEntryNullIllegal, Unavailable, UnexpectedError, CollectionReadOnly, StringCanNotBeEmpty, EnumInvalid, NotSupportedWithThisVersionOfSAPI, NotSupportedWithThisVersionOfSAPI2, NotSupportedWithThisVersionOfSAPIBaseUri, NotSupportedWithThisVersionOfSAPITagFormat, NotSupportedWithThisVersionOfSAPICompareOption, MustBeGreaterThanZero, InvalidXml, OperationAborted, InvariantCultureInfo, DuplicatedEntry, StreamMustBeReadable, StreamMustBeWriteable, StreamMustBeSeekable, StreamEndedUnexpectedly, CannotReadFromDirectory, UnknownMimeFormat, CannotLoadResourceFromManifest, TokenInUse, TokenDeleted, TokenUninitialized, InvalidTokenId, NotFound, NoBackSlash, InvalidRegistryEntry, TokenCannotCreateInstance, InvalidXmlFormat, IncorrectAttributeValue, MissingRequiredAttribute, InvalidRuleRefSelf, InvalidDynamicExport, InvalidToken, MetaNameHTTPEquiv, EmptyRule, InvalidTokenString, InvalidQuotedString, ExportDynamicRule, EmptyDisplayString, EmptyPronunciationString, InvalidPhoneme, MuliplePronunciationString, MultipleDisplayString, RuleRedefinition, EmptyOneOf, InvalidGrammarOrdering, MinMaxOutOfRange, InvalidExampleOrdering, GrammarDefTwice, UnsupportedFormat, InvalidImport, DuplicatedRuleName, RootRuleAlreadyDefined, RuleNameIdConflict, RuleNotDynamic, StateWithNoArcs, NoTerminatingRulePath, RuleRefNoUri, UnavailableProperty, MinGreaterThanMax, ReqConfidenceNotSupported, SapiPropertiesAndSemantics, InvalidAttributeDefinedTwice, GrammarCompilerError, RuleScriptNotFound, DynamicRuleNotFound, RuleScriptInvalidParameters, RuleScriptInvalidReturnType, NoClassname, EmbeddedClassLibraryFailed, CannotFindClass, StrongTypedGrammarNotAGrammar, NoScriptsForRules, ClassNotPublic, MethodNotPublic, IncompatibleLanguageProperties, IncompatibleNamespaceProperties, IncompatibleDebugProperties, CannotLoadDotNetSemanticCode, InvalidSemanticProcessingType, InvalidScriptDefinition, InvalidMethodName, ConstructorNotAllowed, OverloadNotAllowed, OnInitOnPublicRule, ArgumentMismatch, CantGetPropertyFromSerializedInfo, CantFindAConstructor, TooManyArcs, TooManyRulesWithSemanticsGlobals, MaxTransitionsCount, UnknownElement, CircularRuleRef, InvalidFlagsSet, RuleDefinedMultipleTimes, RuleDefinedMultipleTimes2, RuleNotDefined, RootNotDefined, InvalidLanguage, InvalidRuleId, InvalidRepeatProbability, InvalidConfidence, InvalidMinRepeat, InvalidMaxRepeat, InvalidWeight, InvalidName, InvalidValueType, TagFormatNotSet, NoName, NoName1, InvalidSpecialRuleRef, InvalidRuleRef, InvalidNotEmptyElement, InvalidEmptyElement, InvalidEmptyRule, UndefRuleRef, UnsupportedLanguage, UnsupportedPhoneticAlphabet, UnsupportedLexicon, InvalidScriptAttribute, NoLanguageSet, MethodAttributeDefinedMultipeTimes, RuleAttributeDefinedMultipeTimes, InvalidAssemblyReferenceAttribute, InvalidImportNamespaceAttribute, NoUriForSpecialRuleRef, NoAliasForSpecialRuleRef, NoSmlData, InvalidNameValueProperty, InvalidTagInAnEmptyItem, InvalidSrgs, InvalidSrgsNamespace, Line, Position, InvalidVersion, InvalidTagFormat, MissingTagFormat, InvalidGrammarMode, InvalidGrammarAttribute, InvalidRuleAttribute, InvalidRulerefAttribute, InvalidOneOfAttribute, InvalidItemAttribute, InvalidTokenAttribute, InvalidItemRepeatAttribute, InvalidReqConfAttribute, InvalidTagAttribute, InvalidLexiconAttribute, InvalidMetaAttribute, InvalidItemAttribute2, InvalidElement, InvalidRuleScope, InvalidDynamicSetting, InvalidSubsetAttribute, InvalidVoiceElementInPromptOutput, NoRuleId, PromptBuilderInvalideState, PromptBuilderStateEnded, PromptBuilderStateSentence, PromptBuilderStateParagraph, PromptBuilderStateVoice, PromptBuilderStateStyle, PromptBuilderAgeOutOfRange, PromptBuilderMismatchStyle, PromptBuilderMismatchVoice, PromptBuilderMismatchParagraph, PromptBuilderMismatchSentence, PromptBuilderNestedParagraph, PromptBuilderNestedSentence, PromptBuilderInvalidAttribute, PromptBuilderInvalidElement, PromptBuilderInvalidVariant, PromptBuilderDatabaseName, PromptAsyncOperationCancelled, SynthesizerPauseResumeMismatched, SynthesizerInvalidMediaType, SynthesizerUnknownMediaType, SynthesizerSpeakError, SynthesizerInvalidWaveFile, SynthesizerPromptInUse, SynthesizerUnknownPriority, SynthesizerUnknownEvent, SynthesizerVoiceFailed, SynthesizerSetVoiceNoMatch, SynthesizerNoCulture, SynthesizerSyncSpeakWhilePaused, SynthesizerSyncSetOutputWhilePaused, SynthesizerNoCulture2, SynthesizerNoSpeak, SynthesizerSetOutputSpeaking, InvalidSpeakAttribute, UnsupportedAlphabet, GrammarInvalidWeight, GrammarInvalidPriority, DictationInvalidTopic, DictationTopicNotFound, RecognizerGrammarNotFound, RecognizerRuleNotFound, RecognizerInvalidBinaryGrammar, RecognizerRuleNotFoundStream, RecognizerNoRootRuleToActivate, RecognizerNoRootRuleToActivate1, RecognizerRuleActivationFailed, RecognizerAlreadyRecognizing, RecognizerHasNoGrammar, NegativeTimesNotSupported, AudioDeviceFormatError, AudioDeviceError, AudioDeviceInternalError, RecognizerNotFound, RecognizerNotEnabled, RecognitionNotSupported, RecognitionNotSupportedOn64bit, GrammarAlreadyLoaded, RecognizerNoInputSource, GrammarNotLoaded, GrammarLoadingInProgress, GrammarLoadFailed, GrammarWrongRecognizer, NotSupportedOnDictationGrammars, LocalFilesOnly, NotValidAudioFile, NotValidAudioStream, FileNotFound, CannotSetPriorityOnDictation, RecognizerUpdateTableTooLarge, MaxAlternatesInvalid, RecognizerSettingGetError, RecognizerSettingUpdateError, RecognizerSettingNotSupported, ResourceUsageOutOfRange, RateOutOfRange, EndSilenceOutOfRange, RejectionThresholdOutOfRange, ReferencedGrammarNotFound, SapiErrorRuleNotFound2, NoAudioAvailable, ResultNotGrammarAvailable, ResultInvalidFormat, UnhandledVariant, DupSemanticKey, DupSemanticValue, CannotUseCustomFormat, NoPromptEngine, NoPromptEngineInterface, SeekNotSupported, ExtraDataNotPresent, BitsPerSampleInvalid, DataBlockSizeInvalid, NotWholeNumberBlocks, BlockSignatureInvalid, NumberOfSamplesInvalid, SapiErrorUninitialized, SapiErrorAlreadyInitialized, SapiErrorNotSupportedFormat, SapiErrorInvalidFlags, SapiErrorEndOfStream, SapiErrorDeviceBusy, SapiErrorDeviceNotSupported, SapiErrorDeviceNotEnabled, SapiErrorNoDriver, SapiErrorFileMustBeUnicode, InsufficientData, SapiErrorInvalidPhraseID, SapiErrorBufferTooSmall, SapiErrorFormatNotSpecified, SapiErrorAudioStopped0, AudioPaused, SapiErrorRuleNotFound, SapiErrorTTSEngineException, SapiErrorTTSNLPException, SapiErrorEngineBUSY, AudioConversionEnabled, NoHypothesisAvailable, SapiErrorCantCreate, AlreadyInLex, SapiErrorNotInLex, LexNothingToSync, SapiErrorLexVeryOutOfSync, SapiErrorUndefinedForwardRuleRef, SapiErrorEmptyRule, SapiErrorGrammarCompilerInternalError, SapiErrorRuleNotDynamic, SapiErrorDuplicateRuleName, SapiErrorDuplicateResourceName, SapiErrorTooManyGrammars, SapiErrorCircularReference, SapiErrorInvalidImport, SapiErrorInvalidWAVFile, RequestPending, SapiErrorAllWordsOptional, SapiErrorInstanceChangeInvalid, SapiErrorRuleNameIdConflict, SapiErrorNoRules, SapiErrorCircularRuleRef, NoParseFound, SapiErrorInvalidHandle, SapiErrorRemoteCallTimedout, SapiErrorAudioBufferOverflow, SapiErrorNoAudioData, SapiErrorDeadAlternate, SapiErrorHighLowConfidence, SapiErrorInvalidFormatString, SPNotSupportedOnStreamInput, SapiErrorAppLexReadOnly, SapiErrorNoTerminatingRulePath, WordExistsWithoutPronunciation, SapiErrorStreamClosed, SapiErrorNoMoreItems, SapiErrorNotFound, SapiErrorInvalidAudioState, SapiErrorGenericMMSYS, SapiErrorMarshalerException, SapiErrorNotDynamicGrammar, SapiErrorAmbiguousProperty, SapiErrorInvalidRegistrykey, SapiErrorInvalidTokenId, SapiErrorXMLBadSyntax, SapiErrorXMLResourceNotFound, SapiErrorTokenInUse, SapiErrorTokenDeleted, SapiErrorMultilingualNotSupported, SapiErrorExportDynamicRule, SapiErrorSTGF, SapiErrorWordFormat, SapiErrorStreamNotActive, SapiErrorEngineResponseInvalid, SapiErrorSREngineException, SapiErrorStreamPosInvalid, SapiErrorRecognizerInactive, SapiErrorRemoteCallOnWrongThread, SapiErrorRemoteProcessTerminated, SapiErrorRemoteProcessAlreadyRunning, SapiErrorLangIdMismatch, SapiErrorPartialParseFound, SapiErrorNotTopLevelRule, SapiErrorNoRuleActive, SapiErrorLexRequiresCookie, SapiErrorStreamUninitialized, SapiErrorUnused0, SapiErrorNotSupportedLang, SapiErrorVoicePaused, SapiErrorAudioBufferUnderflow, SapiErrorAudioStoppedUnexpectedly, SapiErrorNoWordPronunciation, SapiErrorAlternatesWouldBeInconsistent, SapiErrorNotSupportedForSharedRecognizer, SapiErrorTimeOut, SapiErrorReenterSynchronize, SapiErrorStateWithNoArcs, SapiErrorNotActiveSession, SapiErrorAlreadyDeleted, SapiErrorAudioStopped, SapiErrorRecoXMLGenerationFail, SapiErrorSMLGenerationFail, SapiErrorNotPromptVoice, SapiErrorRootRuleAlreadyDefined, SapiErrorUnused1, SapiErrorUnused2, SapiErrorUnused3, SapiErrorUnused4, SapiErrorUnused5, SapiErrorUnused6, SapiErrorScriptDisallowed, SapiErrorRemoteCallTimedOutStart, SapiErrorRemoteCallTimedOutConnect, SapiErrorSecMgrChangeNotAllowed, SapiErrorCompleteButExtendable, SapiErrorFailedToDeleteFile, SapiErrorSharedEngineDisabled, SapiErrorRecognizerNotFound, SapiErrorAudioNotFound, SapiErrorNoVowel, SapiErrorNotSupportedPhoneme, SapiErrorNoRulesToActivate, SapiErrorNoWordEntryNotification, SapiErrorWordNeedsNormalization, SapiErrorCannotNormalize, LimitReached, NotSupported, SapiErrorTopicNotAdaptable, SapiErrorPhonemeConversion, SapiErrorNotSupportedForInprocRecognizer, SapiErrorOverload, SapiLexInvalidData, SapiConfigInvalidData, SapiLexUnexpectedFormat, SapiStringTooLong, SapiStringEmpty, SapiErrorUnused7, SapiErrorUnused8, SapiErrorUnused9, SapiErrorUnused10, SapiErrorUnused11, SapiErrorUnused12, SapiNonWordTransition, SapiSisrAttributesNotAllowed, SapiSisrMixedNotAllowed, SapiVoiceNotFound } } namespace System.Speech.Synthesis { public class BookmarkReachedEventArgs : PromptEventArgs { private string _bookmark; private TimeSpan _audioPosition; public string Bookmark => _bookmark; public TimeSpan AudioPosition => _audioPosition; internal BookmarkReachedEventArgs(Prompt prompt, string bookmark, TimeSpan audioPosition) : base(prompt) { _bookmark = bookmark; _audioPosition = audioPosition; } } [DebuggerDisplay("{_text}")] public class FilePrompt : Prompt { public FilePrompt(string path, SynthesisMediaType media) : this(new Uri(path, UriKind.Relative), media) { } public FilePrompt(Uri promptFile, SynthesisMediaType media) : base(promptFile, media) { } } [DebuggerDisplay("{VoiceInfo.Name} [{Enabled ? \"Enabled\" : \"Disabled\"}]")] public class InstalledVoice { private VoiceInfo _voice; private bool _enabled; private VoiceSynthesis _voiceSynthesizer; public VoiceInfo VoiceInfo => _voice; public bool Enabled { get { return _enabled; } set { SetEnabledFlag(value, switchContext: true); } } internal InstalledVoice(VoiceSynthesis voiceSynthesizer, VoiceInfo voice) { _voiceSynthesizer = voiceSynthesizer; _voice = voice; _enabled = true; } public override bool Equals(object obj) { if (!(obj is InstalledVoice installedVoice)) { return false; } if (VoiceInfo.Name == installedVoice.VoiceInfo.Name && VoiceInfo.Age == installedVoice.VoiceInfo.Age && VoiceInfo.Gender == installedVoice.VoiceInfo.Gender) { return VoiceInfo.Culture.Equals(installedVoice.VoiceInfo.Culture); } return false; } public override int GetHashCode() { return VoiceInfo.Name.GetHashCode(); } internal static InstalledVoice Find(List<InstalledVoice> list, VoiceInfo voiceId) { foreach (InstalledVoice item in list) { if (item.Enabled && item.VoiceInfo.Equals(voiceId)) { return item; } } return null; } internal static InstalledVoice FirstEnabled(List<InstalledVoice> list, CultureInfo culture) { InstalledVoice installedVoice = null; foreach (InstalledVoice item in list) { if (item.Enabled) { if (Helpers.CompareInvariantCulture(item.VoiceInfo.Culture, culture)) { return item; } if (installedVoice == null) { installedVoice = item; } } } return installedVoice; } internal void SetEnabledFlag(bool value, bool switchContext) { try { if (_enabled == value) { return; } _enabled = value; if (!_enabled) { if (_voice.Equals(_voiceSynthesizer.CurrentVoice(switchContext).VoiceInfo)) { _voiceSynthesizer.Voice = null; } } else { _voiceSynthesizer.Voice = null; } } catch (InvalidOperationException) { _voiceSynthesizer.Voice = null; } } } public class PhonemeReachedEventArgs : PromptEventArgs { private string _currentPhoneme; private TimeSpan _audioPosition; private TimeSpan _duration; private SynthesizerEmphasis _emphasis; private string _nextPhoneme; public string Phoneme => _currentPhoneme; public TimeSpan AudioPosition => _audioPosition; public TimeSpan Duration => _duration; public SynthesizerEmphasis Emphasis => _emphasis; public string NextPhoneme => _nextPhoneme; internal PhonemeReachedEventArgs(Prompt prompt, string currentPhoneme, TimeSpan audioPosition, TimeSpan duration, SynthesizerEmphasis emphasis, string nextPhoneme) : base(prompt) { _currentPhoneme = currentPhoneme; _audioPosition = audioPosition; _duration = duration; _emphasis = emphasis; _nextPhoneme = nextPhoneme; } } [DebuggerDisplay("{_text}")] public class Prompt { internal string _text; internal Uri _audio; internal SynthesisMediaType _media; internal bool _syncSpeak; private bool _completed; private object _synthesizer; private static ResourceLoader s_resourceLoader = new ResourceLoader(); public bool IsCompleted { get { return _completed; } internal set { _completed = value; } } internal object Synthesizer { set { if (value != null && (_synthesizer != null || _completed)) { throw new ArgumentException(SR.Get(SRID.SynthesizerPromptInUse), "value"); } _synthesizer = value; } } internal Exception Exception { get; set; } public Prompt(string textToSpeak) : this(textToSpeak, SynthesisTextFormat.Text) { } public Prompt(PromptBuilder promptBuilder) { Helpers.ThrowIfNull(promptBuilder, "promptBuilder"); _text = promptBuilder.ToXml(); _media = SynthesisMediaType.Ssml; } public Prompt(string textToSpeak, SynthesisTextFormat media) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); if ((uint)(_media = (SynthesisMediaType)media) <= 1u) { _text = textToSpeak; return; } throw new ArgumentException(SR.Get(SRID.SynthesizerUnknownMediaType), "media"); } internal Prompt(Uri promptFile, SynthesisMediaType media) { Helpers.ThrowIfNull(promptFile, "promptFile"); switch (_media = media) { case SynthesisMediaType.Text: case SynthesisMediaType.Ssml: { string mimeType; Uri baseUri; string localPath; using Stream stream = s_resourceLoader.LoadFile(promptFile, out mimeType, out baseUri, out localPath); try { using TextReader textReader = new StreamReader(stream); _text = textReader.ReadToEnd(); break; } finally { s_resourceLoader.UnloadFile(localPath); } } case SynthesisMediaType.WaveAudio: _text = promptFile.ToString(); _audio = promptFile; break; default: throw new ArgumentException(SR.Get(SRID.SynthesizerUnknownMediaType), "media"); } } } public enum SynthesisMediaType { Text, Ssml, WaveAudio } public enum SynthesisTextFormat { Text, Ssml } [Serializable] public class PromptBuilder { internal enum SsmlState { Header = 1, Paragraph = 2, Sentence = 4, StyleEmphasis = 8, StyleProsody = 0x10, Voice = 0x20, Ended = 0x40 } [Serializable] private struct StackElement { internal SsmlElement _possibleChildren; internal SsmlState _state; internal CultureInfo _culture; internal StackElement(SsmlElement possibleChildren, SsmlState state, CultureInfo culture) { _possibleChildren = possibleChildren; _state = state; _culture = culture; } } private enum ElementType { Prosody, Emphasis, SayAs, Phoneme, Sub, Break, Audio, Bookmark, StartVoice, StartParagraph, StartSentence, EndSentence, EndParagraph, StartStyle, EndStyle, EndVoice, Text, SsmlMarkup } [Serializable] private struct AttributeItem { internal string _key; internal string _value; internal string _namespace; internal AttributeItem(string key, string value) { _key = key; _value = value; _namespace = null; } internal AttributeItem(string ns, string key, string value) : this(key, value) { _namespace = ns; } } [Serializable] private sealed class Element { internal ElementType _type; internal string _text; internal Collection<AttributeItem> _attributes; internal Element(ElementType type) { _type = type; } internal Element(ElementType type, string text) : this(type) { _text = text; } } private Stack<StackElement> _elementStack = new Stack<StackElement>(); private CultureInfo _culture; private List<Element> _elements = new List<Element>(); private static ResourceLoader s_resourceLoader = new ResourceLoader(); private const string _xmlnsDefault = "http://www.w3.org/2001/10/synthesis"; private static readonly string[] s_promptBuilderElementName = new string[11] { "prosody", "emphasis", "say-as", "phoneme", "sub", "break", "audio", "mark", "voice", "p", "s" }; public bool IsEmpty => _elements.Count == 0; public CultureInfo Culture { get { return _culture; } set { if (value == null) { throw new ArgumentNullException("value"); } _culture = value; } } public PromptBuilder() : this(CultureInfo.CurrentUICulture) { } public PromptBuilder(CultureInfo culture) { Helpers.ThrowIfNull(culture, "culture"); if (culture.Equals(CultureInfo.InvariantCulture)) { throw new ArgumentException(SR.Get(SRID.InvariantCultureInfo), "culture"); } _culture = culture; ClearContent(); } public void ClearContent() { _elements.Clear(); _elementStack.Push(new StackElement(SsmlElement.AudioMarkTextWithStyle | SsmlElement.ParagraphOrSentence | SsmlElement.Lexicon | SsmlElement.Meta | SsmlElement.MetaData, SsmlState.Header, _culture)); } public void AppendText(string textToSpeak) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); ValidateElement(_elementStack.Peek(), SsmlElement.Text); _elements.Add(new Element(ElementType.Text, textToSpeak)); } public void AppendText(string textToSpeak, PromptRate rate) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); if (rate < PromptRate.NotSet || rate > PromptRate.ExtraSlow) { throw new ArgumentOutOfRangeException("rate"); } ValidateElement(_elementStack.Peek(), SsmlElement.Text); Element element = new Element(ElementType.Prosody, textToSpeak); _elements.Add(element); string value = null; switch (rate) { case PromptRate.ExtraFast: value = "x-fast"; break; case PromptRate.ExtraSlow: value = "x-slow"; break; default: value = rate.ToString().ToLowerInvariant(); break; case PromptRate.NotSet: break; } if (!string.IsNullOrEmpty(value)) { element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("rate", value)); } } public void AppendText(string textToSpeak, PromptVolume volume) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); if (volume < PromptVolume.NotSet || volume > PromptVolume.Default) { throw new ArgumentOutOfRangeException("volume"); } ValidateElement(_elementStack.Peek(), SsmlElement.Text); Element element = new Element(ElementType.Prosody, textToSpeak); _elements.Add(element); string value = null; switch (volume) { case PromptVolume.ExtraSoft: value = "x-soft"; break; case PromptVolume.ExtraLoud: value = "x-loud"; break; default: value = volume.ToString().ToLowerInvariant(); break; case PromptVolume.NotSet: break; } if (!string.IsNullOrEmpty(value)) { element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("volume", value)); } } public void AppendText(string textToSpeak, PromptEmphasis emphasis) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); if (emphasis < PromptEmphasis.NotSet || emphasis > PromptEmphasis.Reduced) { throw new ArgumentOutOfRangeException("emphasis"); } ValidateElement(_elementStack.Peek(), SsmlElement.Text); Element element = new Element(ElementType.Emphasis, textToSpeak); _elements.Add(element); if (emphasis != PromptEmphasis.NotSet) { element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("level", emphasis.ToString().ToLowerInvariant())); } } public void StartStyle(PromptStyle style) { Helpers.ThrowIfNull(style, "style"); StackElement stackElement = _elementStack.Peek(); ValidateElement(stackElement, SsmlElement.Prosody); SsmlState ssmlState = (SsmlState)0; SsmlElement possibleChildren = stackElement._possibleChildren; _elements.Add(new Element(ElementType.StartStyle)); if (style.Emphasis != PromptEmphasis.NotSet) { Element element = new Element(ElementType.Emphasis); _elements.Add(element); element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("level", style.Emphasis.ToString().ToLowerInvariant())); possibleChildren = SsmlElement.AudioMarkTextWithStyle; ssmlState = SsmlState.StyleEmphasis; } if (style.Rate != PromptRate.NotSet || style.Volume != PromptVolume.NotSet) { if (ssmlState != 0) { _elements.Add(new Element(ElementType.StartStyle)); } Element element2 = new Element(ElementType.Prosody); _elements.Add(element2); if (style.Rate != PromptRate.NotSet) { string value = style.Rate switch { PromptRate.ExtraFast => "x-fast", PromptRate.ExtraSlow => "x-slow", _ => style.Rate.ToString().ToLowerInvariant(), }; element2._attributes = new Collection<AttributeItem>(); element2._attributes.Add(new AttributeItem("rate", value)); } if (style.Volume != PromptVolume.NotSet) { string value2 = style.Volume switch { PromptVolume.ExtraSoft => "x-soft", PromptVolume.ExtraLoud => "x-loud", _ => style.Volume.ToString().ToLowerInvariant(), }; if (element2._attributes == null) { element2._attributes = new Collection<AttributeItem>(); } element2._attributes.Add(new AttributeItem("volume", value2)); } possibleChildren = SsmlElement.AudioMarkTextWithStyle | SsmlElement.ParagraphOrSentence; ssmlState |= SsmlState.StyleProsody; } _elementStack.Push(new StackElement(possibleChildren, ssmlState, stackElement._culture)); } public void EndStyle() { StackElement stackElement = _elementStack.Pop(); if (stackElement._state != 0) { if ((stackElement._state & (SsmlState)24) == 0) { throw new InvalidOperationException(SR.Get(SRID.PromptBuilderMismatchStyle)); } _elements.Add(new Element(ElementType.EndStyle)); if (stackElement._state == (SsmlState)24) { _elements.Add(new Element(ElementType.EndStyle)); } } } public void StartVoice(VoiceInfo voice) { Helpers.ThrowIfNull(voice, "voice"); if (!VoiceInfo.ValidateGender(voice.Gender)) { throw new ArgumentException(SR.Get(SRID.EnumInvalid, "VoiceGender"), "voice"); } if (!VoiceInfo.ValidateAge(voice.Age)) { throw new ArgumentException(SR.Get(SRID.EnumInvalid, "VoiceAge"), "voice"); } StackElement stackElement = _elementStack.Peek(); ValidateElement(stackElement, SsmlElement.Voice); CultureInfo culture = ((voice.Culture == null) ? stackElement._culture : voice.Culture); Element element = new Element(ElementType.StartVoice); element._attributes = new Collection<AttributeItem>(); _elements.Add(element); if (!string.IsNullOrEmpty(voice.Name)) { element._attributes.Add(new AttributeItem("name", voice.Name)); } if (voice.Culture != null) { element._attributes.Add(new AttributeItem("xml", "lang", voice.Culture.Name)); } if (voice.Gender != VoiceGender.NotSet) { element._attributes.Add(new AttributeItem("gender", voice.Gender.ToString().ToLowerInvariant())); } if (voice.Age != VoiceAge.NotSet) { element._attributes.Add(new AttributeItem("age", ((int)voice.Age).ToString(CultureInfo.InvariantCulture))); } if (voice.Variant >= 0) { element._attributes.Add(new AttributeItem("variant", voice.Variant.ToString(CultureInfo.InvariantCulture))); } _elementStack.Push(new StackElement(SsmlElement.AudioMarkTextWithStyle | SsmlElement.Sentence, SsmlState.Voice, culture)); } public void StartVoice(string name) { Helpers.ThrowIfEmptyOrNull(name, "name"); StartVoice(new VoiceInfo(name)); } public void StartVoice(VoiceGender gender) { StartVoice(new VoiceInfo(gender)); } public void StartVoice(VoiceGender gender, VoiceAge age) { StartVoice(new VoiceInfo(gender, age)); } public void StartVoice(VoiceGender gender, VoiceAge age, int voiceAlternate) { StartVoice(new VoiceInfo(gender, age, voiceAlternate)); } public void StartVoice(CultureInfo culture) { StartVoice(new VoiceInfo(culture)); } public void EndVoice() { if (_elementStack.Pop()._state != SsmlState.Voice) { throw new InvalidOperationException(SR.Get(SRID.PromptBuilderMismatchVoice)); } _elements.Add(new Element(ElementType.EndVoice)); } public void StartParagraph() { StartParagraph(null); } public void StartParagraph(CultureInfo culture) { StackElement stackElement = _elementStack.Peek(); ValidateElement(stackElement, SsmlElement.Paragraph); Element element = new Element(ElementType.StartParagraph); _elements.Add(element); if (culture != null) { if (culture.Equals(CultureInfo.InvariantCulture)) { throw new ArgumentException(SR.Get(SRID.InvariantCultureInfo), "culture"); } element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("xml", "lang", culture.Name)); } else { culture = stackElement._culture; } _elementStack.Push(new StackElement(SsmlElement.AudioMarkTextWithStyle | SsmlElement.Sentence, SsmlState.Paragraph, culture)); } public void EndParagraph() { if (_elementStack.Pop()._state != SsmlState.Paragraph) { throw new InvalidOperationException(SR.Get(SRID.PromptBuilderMismatchParagraph)); } _elements.Add(new Element(ElementType.EndParagraph)); } public void StartSentence() { StartSentence(null); } public void StartSentence(CultureInfo culture) { StackElement stackElement = _elementStack.Peek(); ValidateElement(stackElement, SsmlElement.Sentence); Element element = new Element(ElementType.StartSentence); _elements.Add(element); if (culture != null) { if (culture.Equals(CultureInfo.InvariantCulture)) { throw new ArgumentException(SR.Get(SRID.InvariantCultureInfo), "culture"); } element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("xml", "lang", culture.Name)); } else { culture = stackElement._culture; } _elementStack.Push(new StackElement(SsmlElement.AudioMarkTextWithStyle, SsmlState.Sentence, culture)); } public void EndSentence() { if (_elementStack.Pop()._state != SsmlState.Sentence) { throw new InvalidOperationException(SR.Get(SRID.PromptBuilderMismatchSentence)); } _elements.Add(new Element(ElementType.EndSentence)); } public void AppendTextWithHint(string textToSpeak, SayAs sayAs) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); if (sayAs < SayAs.SpellOut || sayAs > SayAs.Text) { throw new ArgumentOutOfRangeException("sayAs"); } ValidateElement(_elementStack.Peek(), SsmlElement.Text); if (sayAs != SayAs.Text) { Element element = new Element(ElementType.SayAs, textToSpeak); _elements.Add(element); element._attributes = new Collection<AttributeItem>(); string value = null; string value2 = null; switch (sayAs) { case SayAs.SpellOut: value = "characters"; break; case SayAs.NumberOrdinal: value = "ordinal"; break; case SayAs.NumberCardinal: value = "cardinal"; break; case SayAs.Date: value = "date"; break; case SayAs.DayMonthYear: value = "date"; value2 = "dmy"; break; case SayAs.MonthDayYear: value = "date"; value2 = "mdy"; break; case SayAs.YearMonthDay: value = "date"; value2 = "ymd"; break; case SayAs.YearMonth: value = "date"; value2 = "ym"; break; case SayAs.MonthYear: value = "date"; value2 = "my"; break; case SayAs.MonthDay: value = "date"; value2 = "md"; break; case SayAs.DayMonth: value = "date"; value2 = "dm"; break; case SayAs.Year: value = "date"; value2 = "y"; break; case SayAs.Month: value = "date"; value2 = "m"; break; case SayAs.Day: value = "date"; value2 = "d"; break; case SayAs.Time: value = "time"; break; case SayAs.Time24: value = "time"; value2 = "hms24"; break; case SayAs.Time12: value = "time"; value2 = "hms12"; break; case SayAs.Telephone: value = "telephone"; break; } element._attributes.Add(new AttributeItem("interpret-as", value)); if (!string.IsNullOrEmpty(value2)) { element._attributes.Add(new AttributeItem("format", value2)); } } else { AppendText(textToSpeak); } } public void AppendTextWithHint(string textToSpeak, string sayAs) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); Helpers.ThrowIfEmptyOrNull(sayAs, "sayAs"); ValidateElement(_elementStack.Peek(), SsmlElement.Text); Element element = new Element(ElementType.SayAs, textToSpeak); _elements.Add(element); element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("interpret-as", sayAs)); } public void AppendTextWithPronunciation(string textToSpeak, string pronunciation) { Helpers.ThrowIfEmptyOrNull(textToSpeak, "textToSpeak"); Helpers.ThrowIfEmptyOrNull(pronunciation, "pronunciation"); ValidateElement(_elementStack.Peek(), SsmlElement.Text); PhonemeConverter.ValidateUpsIds(pronunciation); Element element = new Element(ElementType.Phoneme, textToSpeak); _elements.Add(element); element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("ph", pronunciation)); } public void AppendTextWithAlias(string textToSpeak, string substitute) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); Helpers.ThrowIfNull(substitute, "substitute"); ValidateElement(_elementStack.Peek(), SsmlElement.Text); Element element = new Element(ElementType.Sub, textToSpeak); _elements.Add(element); element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("alias", substitute)); } public void AppendBreak() { ValidateElement(_elementStack.Peek(), SsmlElement.Break); _elements.Add(new Element(ElementType.Break)); } public void AppendBreak(PromptBreak strength) { ValidateElement(_elementStack.Peek(), SsmlElement.Break); Element element = new Element(ElementType.Break); _elements.Add(element); string text = null; text = strength switch { PromptBreak.None => "none", PromptBreak.ExtraSmall => "x-weak", PromptBreak.Small => "weak", PromptBreak.Medium => "medium", PromptBreak.Large => "strong", PromptBreak.ExtraLarge => "x-strong", _ => throw new ArgumentNullException("strength"), }; element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("strength", text)); } public void AppendBreak(TimeSpan duration) { ValidateElement(_elementStack.Peek(), SsmlElement.Break); if (duration.Ticks < 0) { throw new ArgumentOutOfRangeException("duration"); } Element element = new Element(ElementType.Break); _elements.Add(element); element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("time", duration.TotalMilliseconds + "ms")); } public void AppendAudio(string path) { Helpers.ThrowIfEmptyOrNull(path, "path"); Uri audioFile; try { audioFile = new Uri(path, UriKind.RelativeOrAbsolute); } catch (UriFormatException ex) { throw new ArgumentException(ex.Message, path, ex); } ValidateElement(_elementStack.Peek(), SsmlElement.Audio); AppendAudio(audioFile); } public void AppendAudio(Uri audioFile) { Helpers.ThrowIfNull(audioFile, "audioFile"); ValidateElement(_elementStack.Peek(), SsmlElement.Audio); Element element = new Element(ElementType.Audio); _elements.Add(element); element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("src", audioFile.ToString())); } public void AppendAudio(Uri audioFile, string alternateText) { Helpers.ThrowIfNull(audioFile, "audioFile"); Helpers.ThrowIfNull(alternateText, "alternateText"); ValidateElement(_elementStack.Peek(), SsmlElement.Audio); Element element = new Element(ElementType.Audio, alternateText); _elements.Add(element); element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("src", audioFile.ToString())); } public void AppendBookmark(string bookmarkName) { Helpers.ThrowIfEmptyOrNull(bookmarkName, "bookmarkName"); ValidateElement(_elementStack.Peek(), SsmlElement.Mark); Element element = new Element(ElementType.Bookmark); _elements.Add(element); element._attributes = new Collection<AttributeItem>(); element._attributes.Add(new AttributeItem("name", bookmarkName)); } public void AppendPromptBuilder(PromptBuilder promptBuilder) { Helpers.ThrowIfNull(promptBuilder, "promptBuilder"); StringReader stringReader = new StringReader(promptBuilder.ToXml()); XmlTextReader xmlTextReader = new XmlTextReader(stringReader); AppendSsml(xmlTextReader); xmlTextReader.Close(); stringReader.Close(); } public void AppendSsml(string path) { Helpers.ThrowIfEmptyOrNull(path, "path"); AppendSsml(new Uri(path, UriKind.Relative)); } public void AppendSsml(Uri ssmlFile) { Helpers.ThrowIfNull(ssmlFile, "ssmlFile"); string localPath; Uri redirectedUri; using Stream input = s_resourceLoader.LoadFile(ssmlFile, out localPath, out redirectedUri); try { AppendSsml(new XmlTextReader(input)); } finally { s_resourceLoader.UnloadFile(localPath); } } public void AppendSsml(XmlReader ssmlFile) { Helpers.ThrowIfNull(ssmlFile, "ssmlFile"); AppendSsmlInternal(ssmlFile); } [EditorBrowsable(EditorBrowsableState.Advanced)] public void AppendSsmlMarkup(string ssmlMarkup) { Helpers.ThrowIfEmptyOrNull(ssmlMarkup, "ssmlMarkup"); _elements.Add(new Element(ElementType.SsmlMarkup, ssmlMarkup)); } public string ToXml() { using StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); using XmlTextWriter writer = new XmlTextWriter(stringWriter); WriteXml(writer); SsmlState state = _elementStack.Peek()._state; if (state != SsmlState.Header) { string text = SR.Get(SRID.PromptBuilderInvalideState); switch (state) { case SsmlState.Ended: text += SR.Get(SRID.PromptBuilderStateEnded); break; case SsmlState.Sentence: text += SR.Get(SRID.PromptBuilderStateSentence); break; case SsmlState.Paragraph: text += SR.Get(SRID.PromptBuilderStateParagraph); break; case SsmlState.StyleEmphasis: case SsmlState.StyleProsody: case (SsmlState)24: text += SR.Get(SRID.PromptBuilderStateStyle); break; case SsmlState.Voice: text += SR.Get(SRID.PromptBuilderStateVoice); break; default: throw new NotSupportedException(); } throw new InvalidOperationException(text); } return stringWriter.ToString(); } private void WriteXml(XmlTextWriter writer) { writer.WriteStartElement("speak"); writer.WriteAttributeString("version", "1.0"); writer.WriteAttributeString("xmlns", "http://www.w3.org/2001/10/synthesis"); writer.WriteAttributeString("xml", "lang", null, _culture.Name); bool flag = false; foreach (Element element in _elements) { flag = flag || element._type == ElementType.StartSentence || element._type == ElementType.StartParagraph || element._type == ElementType.StartStyle || element._type == ElementType.StartVoice; switch (element._type) { case ElementType.Text: writer.WriteString(element._text); break; case ElementType.SsmlMarkup: writer.WriteRaw(element._text); break; case ElementType.Prosody: case ElementType.Emphasis: case ElementType.SayAs: case ElementType.Phoneme: case ElementType.Sub: case ElementType.Break: case ElementType.Audio: case ElementType.Bookmark: case ElementType.StartVoice: case ElementType.StartParagraph: case ElementType.StartSentence: writer.WriteStartElement(s_promptBuilderElementName[(int)element._type]); if (element._attributes != null) { foreach (AttributeItem attribute in element._attributes) { if (attribute._namespace == null) { writer.WriteAttributeString(attribute._key, attribute._value); } else { writer.WriteAttributeString(attribute._namespace, attribute._key, null, attribute._value); } } } if (element._text != null) { writer.WriteString(element._text); } if (!flag) { writer.WriteEndElement(); } flag = false; break; case ElementType.EndSentence: case ElementType.EndParagraph: case ElementType.EndStyle: case ElementType.EndVoice: writer.WriteEndElement(); break; default: throw new NotSupportedException(); case ElementType.StartStyle: break; } } writer.WriteEndElement(); } private static void ValidateElement(StackElement stackElement, SsmlElement currentElement) { if ((stackElement._possibleChildren & currentElement) == 0) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Get(SRID.PromptBuilderInvalidElement), currentElement.ToString(), stackElement._state.ToString())); } } private void AppendSsmlInternal(XmlReader ssmlFile) { StackElement stackElement = _elementStack.Peek(); ValidateElement(_elementStack.Peek(), SsmlElement.Voice); using StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); using (XmlTextWriter writer = new XmlTextWriter(stringWriter)) { TextWriterEngine engine = new TextWriterEngine(writer, stackElement._culture); SsmlParser.Parse(ssmlFile, engine, null); } _elements.Add(new Element(ElementType.SsmlMarkup, stringWriter.ToString())); } } public abstract class PromptEventArgs : AsyncCompletedEventArgs { private Prompt _prompt; public Prompt Prompt => _prompt; internal PromptEventArgs(Prompt prompt) : base(prompt.Exception, prompt.Exception != null, prompt) { _prompt = prompt; } } public class SpeakStartedEventArgs : PromptEventArgs { internal SpeakStartedEventArgs(Prompt prompt) : base(prompt) { } } [Serializable] public class PromptStyle { private PromptRate _rate; private PromptVolume _volume; private PromptEmphasis _emphasis; public PromptRate Rate { get { return _rate; } set { _rate = value; } } public PromptVolume Volume { get { return _volume; } set { _volume = value; } } public PromptEmphasis Emphasis { get { return _emphasis; } set { _emphasis = value; } } public PromptStyle() { } public PromptStyle(PromptRate rate) { Rate = rate; } public PromptStyle(PromptVolume volume) { Volume = volume; } public PromptStyle(PromptEmphasis emphasis) { Emphasis = emphasis; } } public enum SayAs { SpellOut, NumberOrdinal, NumberCardinal, Date, DayMonthYear, MonthDayYear, YearMonthDay, YearMonth, MonthYear, MonthDay, DayMonth, Year, Month, Day, Time, Time24, Time12, Telephone, Text } public enum VoiceGender { NotSet, Male, Female, Neutral } public enum VoiceAge { NotSet = 0, Child = 10, Teen = 15, Adult = 30, Senior = 65 } public enum PromptRate { NotSet, ExtraFast, Fast, Medium, Slow, ExtraSlow } public enum PromptVolume { NotSet, Silent, ExtraSoft, Soft, Medium, Loud, ExtraLoud, Default } public enum PromptEmphasis { NotSet, Strong, Moderate, None, Reduced } public enum PromptBreak { None, ExtraSmall, Small, Medium, Large, ExtraLarge } public class SpeakCompletedEventArgs : PromptEventArgs { internal SpeakCompletedEventArgs(Prompt prompt) : base(prompt) { } } public class SpeakProgressEventArgs : PromptEventArgs { private TimeSpan _audioPosition; private int _iWordPos; private int _cWordLen; private string _word; public TimeSpan AudioPosition => _audioPosition; public int CharacterPosition => _iWordPos; public int CharacterCount { get { return _cWordLen; } internal set { _cWordLen = value; } } public string Text { get { return _word; } internal set { _word = value; } } internal SpeakProgressEventArgs(Prompt prompt, TimeSpan audioPosition, int iWordPos, int cWordLen) : base(prompt) { _audioPosition = audioPosition; _iWordPos = iWordPos; _cWordLen = cWordLen; } } public sealed class SpeechSynthesizer : IDisposable { private VoiceSynthesis _voiceSynthesis; private bool _isDisposed; private bool _paused; private Stream _outputStream; private bool _closeStreamOnExit; public SynthesizerState State => VoiceSynthesizer.State; public int Rate { get { return VoiceSynthesizer.Rate; } set { if (value < -10 || value > 10) { throw new ArgumentOutOfRangeException("value", SR.Get(SRID.RateOutOfRange)); } VoiceSynthesizer.Rate = value; } } public int Volume { get { return VoiceSynthesizer.Volume; } set { if (value < 0 || value > 100) { throw new ArgumentOutOfRangeException("value", SR.Get(SRID.ResourceUsageOutOfRange)); } VoiceSynthesizer.Volume = value; } } public VoiceInfo Voice => VoiceSynthesizer.CurrentVoice(switchContext: true).VoiceInfo; private VoiceSynthesis VoiceSynthesizer { get { if (_voiceSynthesis == null && _isDisposed) { throw new ObjectDisposedException("SpeechSynthesizer"); } if (_voiceSynthesis == null) { WeakReference speechSynthesizer = new WeakReference(this); _voiceSynthesis = new VoiceSynthesis(speechSynthesizer); } return _voiceSynthesis; } } public event EventHandler<SpeakStartedEventArgs> SpeakStarted { [MethodImpl(MethodImplOptions.Synchronized)] add { Helpers.ThrowIfNull(value, "value"); VoiceSynthesis voiceSynthesizer = VoiceSynthesizer; voiceSynthesizer._speakStarted = (EventHandler<SpeakStartedEventArgs>)Delegate.Combine(voiceSynthesizer._speakStarted, value); } [MethodImpl(MethodImplOptions.Synchronized)] remove { Helpers.ThrowIfNull(value, "value"); VoiceSynthesis voiceSynthesizer = VoiceSynthesizer; voiceSynthesizer._speakStarted = (EventHandler<SpeakStartedEventArgs>)Delegate.Remove(voiceSynthesizer._speakStarted, value); } } public event EventHandler<SpeakCompletedEventArgs> SpeakCompleted { [MethodImpl(MethodImplOptions.Synchronized)] add { Helpers.ThrowIfNull(value, "value"); VoiceSynthesis voiceSynthesizer = VoiceSynthesizer; voiceSynthesizer._speakCompleted = (EventHandler<SpeakCompletedEventArgs>)Delegate.Combine(voiceSynthesizer._speakCompleted, value); } [MethodImpl(MethodImplOptions.Synchronized)] remove { Helpers.ThrowIfNull(value, "value"); VoiceSynthesis voiceSynthesizer = VoiceSynthesizer; voiceSynthesizer._speakCompleted = (EventHandler<SpeakCompletedEventArgs>)Delegate.Remove(voiceSynthesizer._speakCompleted, value); } } public event EventHandler<SpeakProgressEventArgs> SpeakProgress { [MethodImpl(MethodImplOptions.Synchronized)] add { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.AddEvent(TtsEventId.WordBoundary, ref VoiceSynthesizer._speakProgress, value); } [MethodImpl(MethodImplOptions.Synchronized)] remove { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.RemoveEvent(TtsEventId.WordBoundary, ref VoiceSynthesizer._speakProgress, value); } } public event EventHandler<BookmarkReachedEventArgs> BookmarkReached { [MethodImpl(MethodImplOptions.Synchronized)] add { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.AddEvent(TtsEventId.Bookmark, ref VoiceSynthesizer._bookmarkReached, value); } [MethodImpl(MethodImplOptions.Synchronized)] remove { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.RemoveEvent(TtsEventId.Bookmark, ref VoiceSynthesizer._bookmarkReached, value); } } public event EventHandler<VoiceChangeEventArgs> VoiceChange { [MethodImpl(MethodImplOptions.Synchronized)] add { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.AddEvent(TtsEventId.VoiceChange, ref VoiceSynthesizer._voiceChange, value); } [MethodImpl(MethodImplOptions.Synchronized)] remove { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.RemoveEvent(TtsEventId.VoiceChange, ref VoiceSynthesizer._voiceChange, value); } } public event EventHandler<PhonemeReachedEventArgs> PhonemeReached { [MethodImpl(MethodImplOptions.Synchronized)] add { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.AddEvent(TtsEventId.Phoneme, ref VoiceSynthesizer._phonemeReached, value); } [MethodImpl(MethodImplOptions.Synchronized)] remove { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.RemoveEvent(TtsEventId.Phoneme, ref VoiceSynthesizer._phonemeReached, value); } } public event EventHandler<VisemeReachedEventArgs> VisemeReached { [MethodImpl(MethodImplOptions.Synchronized)] add { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.AddEvent(TtsEventId.Viseme, ref VoiceSynthesizer._visemeReached, value); } [MethodImpl(MethodImplOptions.Synchronized)] remove { Helpers.ThrowIfNull(value, "value"); VoiceSynthesizer.RemoveEvent(TtsEventId.Viseme, ref VoiceSynthesizer._visemeReached, value); } } public event EventHandler<StateChangedEventArgs> StateChanged { [MethodImpl(MethodImplOptions.Synchronized)] add { Helpers.ThrowIfNull(value, "value"); VoiceSynthesis voiceSynthesizer = VoiceSynthesizer; voiceSynthesizer._stateChanged = (EventHandler<StateChangedEventArgs>)Delegate.Combine(voiceSynthesizer._stateChanged, value); } [MethodImpl(MethodImplOptions.Synchronized)] remove { Helpers.ThrowIfNull(value, "value"); VoiceSynthesis voiceSynthesizer = VoiceSynthesizer; voiceSynthesizer._stateChanged = (EventHandler<StateChangedEventArgs>)Delegate.Remove(voiceSynthesizer._stateChanged, value); } } ~SpeechSynthesizer() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public void SelectVoice(string name) { Helpers.ThrowIfEmptyOrNull(name, "name"); TTSVoice engine = VoiceSynthesizer.GetEngine(name, CultureInfo.CurrentUICulture, VoiceGender.NotSet, VoiceAge.NotSet, 1, switchContext: true); if (engine == null || name != engine.VoiceInfo.Name) { throw new ArgumentException(SR.Get(SRID.SynthesizerSetVoiceNoMatch)); } VoiceSynthesizer.Voice = engine; } public void SelectVoiceByHints(VoiceGender gender) { SelectVoiceByHints(gender, VoiceAge.NotSet, 1, CultureInfo.CurrentUICulture); } public void SelectVoiceByHints(VoiceGender gender, VoiceAge age) { SelectVoiceByHints(gender, age, 1, CultureInfo.CurrentUICulture); } public void SelectVoiceByHints(VoiceGender gender, VoiceAge age, int voiceAlternate) { SelectVoiceByHints(gender, age, voiceAlternate, CultureInfo.CurrentUICulture); } public void SelectVoiceByHints(VoiceGender gender, VoiceAge age, int voiceAlternate, CultureInfo culture) { Helpers.ThrowIfNull(culture, "culture"); if (voiceAlternate < 0) { throw new ArgumentOutOfRangeException("voiceAlternate", SR.Get(SRID.PromptBuilderInvalidVariant)); } if (!VoiceInfo.ValidateGender(gender)) { throw new ArgumentException(SR.Get(SRID.EnumInvalid, "VoiceGender"), "gender"); } if (!VoiceInfo.ValidateAge(age)) { throw new ArgumentException(SR.Get(SRID.EnumInvalid, "VoiceAge"), "age"); } TTSVoice engine = VoiceSynthesizer.GetEngine(null, culture, gender, age, voiceAlternate, switchContext: true); if (engine == null) { throw new InvalidOperationException(SR.Get(SRID.SynthesizerSetVoiceNoMatch)); } VoiceSynthesizer.Voice = engine; } public Prompt SpeakAsync(string textToSpeak) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); Prompt prompt = new Prompt(textToSpeak, SynthesisTextFormat.Text); SpeakAsync(prompt); return prompt; } public void SpeakAsync(Prompt prompt) { Helpers.ThrowIfNull(prompt, "prompt"); prompt.Synthesizer = this; VoiceSynthesizer.SpeakAsync(prompt); } public Prompt SpeakSsmlAsync(string textToSpeak) { Helpers.ThrowIfNull(textToSpeak, "textToSpeak"); Prompt prompt = new Prompt(textToSpeak, SynthesisTextFormat.Ssml); SpeakAsync(prompt); return prompt; } public Prompt SpeakAsync(PromptBuilder promptBuilder) { Helpers.ThrowIfNull(promptBuilder, "promptBuilder"); Prompt prompt = new Prompt(promptBuilder); SpeakAsync(prompt); return prompt; } public void Speak(string textToSpeak) { Speak(new Prompt(textToSpeak, SynthesisTextFormat.Text)); } public void Speak(Prompt prompt) { Helpers.ThrowIfNull(prompt, "prompt"); if (State == SynthesizerState.Paused) { throw new InvalidOperationException(SR.Get(SRID.SynthesizerSyncSpeakWhilePaused)); } prompt.Synthesizer = this; prompt._syncSpeak = true; VoiceSynthesizer.Speak(prompt); } public void Speak(PromptBuilder promptBuilder) { Speak(new Prompt(promptBuilder)); } public void SpeakSsml(string textToSpeak) { Speak(new Prompt(textToSpeak, SynthesisTextFormat.Ssml)); } public void Pause() { if (!_paused) { VoiceSynthesizer.Pause(); _paused = true; } } public void Resume() { if (_paused) { VoiceSynthesizer.Resume(); _paused = false; } } public void SpeakAsyncCancel(Prompt prompt) { Helpers.ThrowIfNull(prompt, "prompt"); VoiceSynthesizer.Abort(prompt); } public void SpeakAsyncCancelAll() { VoiceSynthesizer.Abort(); } public void SetOutputToWaveFile(string path) { Helpers.ThrowIfEmptyOrNull(path, "path"); SetOutputToNull(); SetOutputStream(new FileStream(path, FileMode.Create, FileAccess.Write), null, headerInfo: true, closeStreamOnExit: true); } public void SetOutputToWaveFile(string path, SpeechAudioFormatInfo formatInfo) { Helpers.ThrowIfEmptyOrNull(path, "path"); Helpers.ThrowIfNull(formatInfo, "formatInfo"); SetOutputToNull(); SetOutputStream(new FileStream(path, FileMode.Create, FileAccess.Write), formatInfo, headerInfo: true, closeStreamOnExit: true); } public void SetOutputToWaveStream(Stream audioDestination) { Helpers.ThrowIfNull(audioDestination, "audioDestination"); SetOutputStream(audioDestination, null, headerInfo: true, closeStreamOnExit: false); } public void SetOutputToAudioStream(Stream audioDestination, SpeechAudioFormatInfo formatInfo) { Helpers.ThrowIfNull(audioDestination, "audioDestination"); Helpers.ThrowIfNull(formatInfo, "formatInfo"); SetOutputStream(audioDestination, formatInfo, headerInfo: false, closeStreamOnExit: false); } public void SetOutputToDefaultAudioDevice() { SetOutputStream(null, null, headerInfo: true, closeStreamOnExit: false); } public void SetOutputToNull() { if (_outputStream != Stream.Null) { VoiceSynthesizer.SetOutput(Stream.Null, null, headerInfo: true); } if (_outputStream != null && _closeStreamOnExit) { _outputStream.Close(); } _outputStream = Stream.Null; } public Prompt GetCurrentlySpokenPrompt() { return VoiceSynthesizer.Prompt; } public ReadOnlyCollection<InstalledVoice> GetInstalledVoices() { return VoiceSynthesizer.GetInstalledVoices(null); } public ReadOnlyCollection<InstalledVoice> GetInstalledVoices(CultureInfo culture) { Helpers.ThrowIfNull(culture, "culture"); if (culture.Equals(CultureInfo.InvariantCulture)) { throw new ArgumentException(SR.Get(SRID.InvariantCultureInfo), "culture"); } return VoiceSynthesizer.GetInstalledVoices(culture); } public void AddLexicon(Uri uri, string mediaType) { Helpers.ThrowIfNull(uri, "uri"); VoiceSynthesizer.AddLexicon(uri, mediaType); } public void RemoveLexicon(Uri uri) { Helpers.ThrowIfNull(uri, "uri"); VoiceSynthesizer.RemoveLexicon(uri); } private void SetOutputStream(Stream stream, SpeechAudioFormatInfo formatInfo, bool headerInfo, bool closeStreamOnExit) { SetOutputToNull(); _outputStream = stream; _closeStreamOnExit = closeStreamOnExit; VoiceSynthesizer.SetOutput(stream, formatInfo, headerInfo); } private void Dispose(bool disposing) { if (!_isDisposed && disposing && _voiceSynthesis != null) { _isDisposed = true; SpeakAsyncCancelAll(); if (_outputStream != null) { if (_closeStreamOnExit) { _outputStream.Close(); } else { _outputStream.Flush(); } _outputStream = null; } } if (_voiceSynthesis != null) { _voiceSynthesis.Dispose(); _voiceSynthesis = null; } _isDisposed = true; } } public enum SynthesizerState { Ready, Speaking, Paused } [Flags] public enum SynthesizerEmphasis { Stressed = 1, Emphasized = 2 } public class StateChangedEventArgs : EventArgs { private SynthesizerState _state; private SynthesizerState _previousState; public SynthesizerState State => _state; public SynthesizerState PreviousState => _previousState; internal StateChangedEventArgs(SynthesizerState state, SynthesizerState previousState) { _state = state; _previousState = previousState; } } public class VisemeReachedEventArgs : PromptEventArgs { private int _currentViseme; private TimeSpan _audioPosition; private TimeSpan _duration; private SynthesizerEmphasis _emphasis; private int _nextViseme; public int Viseme => _currentViseme; public TimeSpan AudioPosition => _audioPosition; public TimeSpan Duration => _duration; public SynthesizerEmphasis Emphasis => _emphasis; public int NextViseme => _nextViseme; internal VisemeReachedEventArgs(Prompt speakPrompt, int currentViseme, TimeSpan audioPosition, TimeSpan duration, SynthesizerEmphasis emphasis, int nextViseme) : base(speakPrompt) { _currentViseme = currentViseme; _audioPosition = audioPosition; _duration = duration; _emphasis = emphasis; _nextViseme = nextViseme; } } public class VoiceChangeEventArgs : PromptEventArgs { private VoiceInfo _voice; public VoiceInfo Voice => _voice; internal VoiceChangeEventArgs(Prompt prompt, VoiceInfo voice) : base(prompt) { _voice = voice; } } [Serializable] [DebuggerDisplay("{(_name != null ? \"'\" + _name + \"' \" : \"\") + (_culture != null ? \" '\" + _culture.ToString () + \"' \" : \"\") + (_gender != VoiceGender.NotSet ? \" '\" + _gender.ToString () + \"' \" : \"\") + (_age != VoiceAge.NotSet ? \" '\" + _age.ToString () + \"' \" : \"\") + (_variant > 0 ? \" \" + _variant.ToString () : \"\")}")] public class VoiceInfo { private string _name; private CultureInfo _culture; private VoiceGender _gender; private VoiceAge _age; private int _variant = -1; [NonSerialized] private string _id; [NonSerialized] private string _registryKeyPath; [NonSerialized] private string _assemblyName; [NonSerialized] private string _clsid; [NonSerialized] private string _description; [NonSerialized] private ReadOnlyDictionary<string, string> _attributes; [NonSerialized] private ReadOnlyCollection<SpeechAudioFormatInfo> _audioFormats; public VoiceGender Gender => _gender; public VoiceAge Age => _age; public string Name => _name; public CultureInfo Culture => _culture; public string Id => _id; public string Description { get { if (_description == null) { return string.Empty; } return _description; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public ReadOnlyCollection<SpeechAudioFormatInfo> SupportedAudioFormats => _audioFormats; [EditorBrowsable(EditorBrowsableState.Advanced)] public IDictionary<string, string> AdditionalInfo { get { if (_attributes == null) { _attributes = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>(0)); } return _attributes; } } internal int Variant => _variant; internal string AssemblyName => _assemblyName; internal string Clsid => _clsid; internal string RegistryKeyPath => _registryKeyPath; internal VoiceInfo(string name) { Helpers.ThrowIfEmptyOrNull(name, "name"); _name = name; } internal VoiceInfo(CultureInfo culture) { Helpers.ThrowIfNull(culture, "culture"); if (culture.Equals(CultureInfo.InvariantCulture)) { throw new ArgumentException(SR.Get(SRID.InvariantCultureInfo), "culture"); } _culture = culture; } internal VoiceInfo(ObjectToken token) { _registryKeyPath = token._sKeyId; _id = token.Name; _description = token.Description; _name = token.TokenName(); SsmlParserHelpers.TryConvertAge(token.Age.ToLowerInvariant(), out _age); SsmlParserHelpers.TryConvertGender(token.Gender.ToLowerInvariant(), out _gender); if (token.Attributes.TryGetString("Language", out var value)) { _culture = SapiAttributeParser.GetCultureInfoFromLanguageString(value); } if (token.TryGetString("Assembly", out var value2)) { _assemblyName = value2; } if (token.TryGetString("CLSID", out var value3)) { _clsid = value3; } if (token.Attributes != null) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); string[] valueNames = token.Attributes.GetValueNames(); foreach (string text in valueNames) { if (token.Attributes.TryGetString(text, out var value4)) { dictionary.Add(text, value4); } } _attributes = new ReadOnlyDictionary<string, string>(dictionary); } if (token.Attributes != null && token.Attributes.TryGetString("AudioFormats", out var value5)) { _audioFormats = new ReadOnlyCollection<SpeechAudioFormatInfo>(SapiAttributeParser.GetAudioFormatsFromString(value5)); } else { _audioFormats = new ReadOnlyCollection<SpeechAudioFormatInfo>(new List<SpeechAudioFormatInfo>()); } } internal VoiceInfo(VoiceGender gender) { _gender = gender; } internal VoiceInfo(VoiceGender gender, VoiceAge age) { _gender = gender; _age = age; } internal VoiceInfo(VoiceGender gender, VoiceAge age, int voiceAlternate) { if (voiceAlternate < 0) { throw new ArgumentOutOfRangeException("voiceAlternate", SR.Get(SRID.PromptBuilderInvalidVariant)); } _gender = gender; _age = age; _variant = voiceAlternate + 1; } public override bool Equals(object obj) { if (obj is VoiceInfo voiceInfo && _name == voiceInfo._name && (_age == voiceInfo._age || _age == VoiceAge.NotSet || voiceInfo._age == VoiceAge.NotSet) && (_gender == voiceInfo._gender || _gender == VoiceGender.NotSet || voiceInfo._gender == VoiceGender.NotSet)) { if (_culture != null && voiceInfo._culture != null) { return _culture.Equals(voiceInfo._culture); } return true; } return false; } public override int GetHashCode() { return _name.GetHashCode(); } internal static bool ValidateGender(VoiceGender gender) { if (gender != VoiceGender.Female && gender != VoiceGender.Male && gender != VoiceGender.Neutral) { return gender == VoiceGender.NotSet; } return true; } internal static bool ValidateAge(VoiceAge age) { if (age != VoiceAge.Adult && age != VoiceAge.Child && age != VoiceAge.NotSet && age != VoiceAge.Senior) { return age == VoiceAge.Teen; } return true; } } } namespace System.Speech.Synthesis.TtsEngine { [ComImport] [Guid("A74D7C8E-4CC5-4F2F-A6EB-804DEE18500E")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ITtsEngine { [PreserveSig] void Speak(SPEAKFLAGS dwSpeakFlags, ref Guid rguidFormatId, IntPtr pWaveFormatEx, IntPtr pTextFragList, IntPtr pOutputSite); [PreserveSig] void GetOutputFormat(ref Guid pTargetFmtId, IntPtr pTargetWaveFormatEx, out Guid pOutputFormatId, out IntPtr ppCoMemOutputWaveFormatEx); } [StructLayout(LayoutKind.Sequential)] internal class SPVTEXTFRAG { public IntPtr pNext; public SPVSTATE State; public IntPtr pTextStart; public int ulTextLen; public int ulTextSrcOffset; public GCHandle gcText; public GCHandle gcNext; public GCHandle gcPhoneme; public GCHandle gcSayAsCategory; } [ComConversionLoss] [TypeLibType(16)] internal struct SPVSTATE { public SPVACTIONS eAction; public short LangID; public short wReserved; public int EmphAdj; public int RateAdj; public int Volume; public SPVPITCH PitchAdj; public int SilenceMSecs; public IntPtr pPhoneIds; public SPPARTOFSPEECH ePartOfSpeech; public SPVCONTEXT Context; } [TypeLibType(16)] internal struct SPVCONTEXT { public IntPtr pCategory; public IntPtr pBefore; public IntPtr pAfter; } [TypeLibType(16)] internal struct SPVPITCH { public int MiddleAdj; public int RangeAdj; } internal static class SAPIGuids { internal static readonly Guid SPDFID_WaveFormatEx = new Guid("C31ADBAE-527F-4ff5-A230-F62BB61FF70C"); } [Flags] internal enum SPEAKFLAGS { SPF_DEFAULT = 0, SPF_ASYNC = 1, SPF_PURGEBEFORESPEAK = 2, SPF_IS_FILENAME = 4, SPF_IS_XML = 8, SPF_IS_NOT_XML = 0x10, SPF_PERSIST_XML = 0x20, SPF_NLP_SPEAK_PUNC = 0x40, SPF_PARSE_SAPI = 0x80, SPF_PARSE_SSML = 0x100 } [Flags] internal enum SPVESACTIONS { SPVES_CONTINUE = 0, SPVES_ABORT = 1, SPVES_SKIP = 2, SPVES_RATE = 4, SPVES_VOLUME = 8 } [TypeLibType(16)] internal enum SPVACTIONS { SPVA_Speak, SPVA_Silence, SPVA_Pronounce, SPVA_Bookmark, SPVA_SpellOut, SPVA_Section, SPVA_ParseUnknownTag } [TypeLibType(16)] internal enum SPPARTOFSPEECH { SPPS_NotOverriden = -1, SPPS_Unknown = 0, SPPS_Noun = 4096, SPPS_Verb = 8192, SPPS_Modifier = 12288, SPPS_Function = 16384, SPPS_Interjection = 20480, SPPS_SuppressWord = 61440 } public abstract class TtsEngineSsml { protected TtsEngineSsml(string registryKey) { } public abstract IntPtr GetOutputFormat(SpeakOutputFormat speakOutputFormat, IntPtr targetWaveFormat); public abstract void AddLexicon(Uri uri, string mediaType, ITtsEngineSite site); public abstract void RemoveLexicon(Uri uri, ITtsEngineSite site); public abstract void Speak(TextFragment[] fragment, IntPtr waveHeader, ITtsEngineSite site); } [ImmutableObject(true)] public struct SpeechEventInfo : IEquatable<SpeechEventInfo> { private short _eventId; private short _parameterType; private int _param1; private IntPtr _param2; public short EventId { get { return _eventId; } internal set { _eventId = value; } } public short ParameterType { get { return _parameterType; } internal set { _parameterType = value; } } public int Param1 { get { return _param1; } internal set { _param1 = value; } } public IntPtr Param2 { get { return _param2; } internal set { _param2 = value; } } public SpeechEventInfo(short eventId, short parameterType, int param1, IntPtr param2) { _eventId = eventId; _parameterType = parameterType; _param1 = param1; _param2 = param2; } public static bool operator ==(SpeechEventInfo event1, SpeechEventInfo event2) { if (event1.EventId == event2.EventId && event1.ParameterType == event2.ParameterType && event1.Param1 == event2.Param1) { return event1.Param2 == event2.Param2; } return false; } public static bool operator !=(SpeechEventInfo event1, SpeechEventInfo event2) { return !(event1 == event2); } public bool Equals(SpeechEventInfo other) { return this == other; } public override bool Equals(object obj) { if (!(obj is SpeechEventInfo)) { return false; } return Equals((SpeechEventInfo)obj); } public override int GetHashCode() { return base.GetHashCode(); } } public interface ITtsEngineSite { int EventInterest { get; } int Actions { get; } int Rate { get; } int Volume { get; } void AddEvents(SpeechEventInfo[] events, int count); int Write(IntPtr data, int count); SkipInfo GetSkipInfo(); void CompleteSkip(int skipped); Stream LoadResource(Uri uri, string mediaType); } public class SkipInfo { private int _type; private int _count; public int Type { get { return _type; } set { _type = value; } } public int Count { get { return _count; } set { _count = value; } } internal SkipInfo(int type, int count) { _type = type; _count = count; } public SkipInfo() { } } [StructLayout(LayoutKind.Sequential)] [DebuggerDisplay("{State.Action} {TextToSpeak!=null?TextToSpeak:\"\"}")] public class TextFragment { private FragmentState _state; [MarshalAs(UnmanagedType.LPWStr)] private string _textToSpeak = string.Empty; private int _textOffset; private int _textLength; public FragmentState State { get { return _state; } set { _state = value; } } public string TextToSpeak { get { return _textToSpeak; } set { Helpers.ThrowIfEmptyOrNull(value, "value"); _textToSpeak = value; } } public int TextOffset { get { return _textOffset; } set { _textOffset = value; } } public int TextLength { get { return _textLength; } set { _textLength = value; } } public TextFragment() { } internal TextFragment(FragmentState fragState) : this(fragState, null, null, 0, 0) { } internal TextFragment(FragmentState fragState, string textToSpeak) : this(fragState, textToSpeak, textToSpeak, 0, textToSpeak.Length) { } internal TextFragment(FragmentState fragState, string textToSpeak, string textFrag, int offset, int length) { if (fragState.Action == TtsEngineAction.Speak || fragState.Action == TtsEngineAction.Pronounce) { textFrag = textToSpeak; } if (!string.IsNullOrEmpty(textFrag)) { TextToSpeak = textFrag; } State = fragState; TextOffset = offset; TextLength = length; } } [ImmutableObject(true)] public struct FragmentState : IEquatable<FragmentState> { private TtsEngineAction _action; private int _langId; private int _emphasis; private int _duration; private SayAs _sayAs; private Prosody _prosody; private char[] _phoneme; public TtsEngineAction Action { get { return _action; } internal set { _action = value; } } public int LangId { get { return _langId; } internal set { _langId = value; } } public int Emphasis { get { return _emphasis; } internal set { _emphasis = value; } } public int Duration { get { return _duration; } internal set { _duration = value; } } public SayAs SayAs { get { return _sayAs; } internal set { Helpers.ThrowIfNull(value, "value"); _sayAs = value; } } public Prosody Prosody { get { return _prosody; } internal set { Helpers.ThrowIfNull(value, "value"); _prosody = value; } } public char[] Phoneme { get { return _phoneme; } internal set { Helpers.ThrowIfNull(value, "value"); _phoneme = value; } } public FragmentState(TtsEngineAction action, int langId, int emphasis, int duration, SayAs sayAs, Prosody prosody, char[] phonemes) { _action = action; _langId = langId; _emphasis = emphasis; _duration = duration; _sayAs = sayAs; _prosody = prosody; _phoneme = phonemes; } public static bool operator ==(FragmentState state1, FragmentState state2) { if (state1.Action == state2.Action && state1.LangId == state2.LangId && state1.Emphasis == state2.Emphasis && state1.Duration == state2.Duration && state1.SayAs == state2.SayAs && state1.Prosody == state2.Prosody) { return object.Equals(state1.Phoneme, state2.Phoneme); } return false; } public static bool operator !=(FragmentState state1, FragmentState state2) { return !(state1 == state2); } public bool Equals(FragmentState other) { return this == other; } public override bool Equals(object obj) { if (!(obj is FragmentState)) { return false; } return Equals((FragmentState)obj); } public override int GetHashCode() { return base.GetHashCode(); } } [StructLayout(LayoutKind.Sequential)] public class Prosody { internal ProsodyNumber _pitch; internal ProsodyNumber _range; internal ProsodyNumber _rate; internal int _duration; internal ProsodyNumber _volume; internal ContourPoint[] _contourPoints; public ProsodyNumber Pitch { get { return _pitch; } set { _pitch = value; } } public ProsodyNumber Range { get { return _range; } set { _range = value; } } public ProsodyNumber Rate { get { return _rate; } set { _rate = value; } } public int Duration { get { return _duration; } set { _duration = value; } } public ProsodyNumber Volume { get { return _volume; } set { _volume = value; } } public ContourPoint[] GetContourPoints() { return _contourPoints; } public void SetContourPoints(ContourPoint[] points) { Helpers.ThrowIfNull(points, "points"); _contourPoints = (ContourPoint[])points.Clone(); } public Prosody() { Pitch = new ProsodyNumber(0); Range = new ProsodyNumber(0); Rate = new ProsodyNumber(0); Volume = new ProsodyNumber(-1); } internal Prosody Clone() { Prosody prosody = new Prosody(); prosody._pitch = _pitch; prosody._range = _range; prosody._rate = _rate; prosody._duration = _duration; prosody._volume = _volume; return prosody; } } [ImmutableObject(true)] public struct ContourPoint : IEquatable<ContourPoint> { private float _start; private float _change; private ContourPointChangeType _changeType; public float Start => _start; public float Change => _change; public ContourPointChangeType ChangeType => _changeType; public ContourPoint(float start, float change, ContourPointChangeType changeType) { _start = start; _change = change; _changeType = changeType; } public static bool operator ==(ContourPoint point1, ContourPoint point2) { if (point1.Start.Equals(point2.Start) && point1.Change.Equals(point2.Change)) { return point1.ChangeType.Equals(point2.ChangeType); } return false; } public static bool operator !=(ContourPoint point1, ContourPoint point2) { return !(point1 == point2); } public bool Equals(ContourPoint other) { return this == other; } public override bool Equals(object obj) { if (!(obj is ContourPoint)) { return false; } return Equals((ContourPoint)obj); } public override int GetHashCode() { return base.GetHashCode(); } } [ImmutableObject(true)] public struct ProsodyNumber : IEquatable<ProsodyNumber> { public const int AbsoluteNumber = int.MaxValue; private int _ssmlAttributeId; private bool _isPercent; private float _number; private ProsodyUnit _unit; public int SsmlAttributeId { get { return _ssmlAttributeId; } internal set { _ssmlAttributeId = value; } } public bool IsNumberPercent { get { return _isPercent; } internal set { _isPercent = value; } } public float Number { get { return _number; } internal set { _number = value; } } public ProsodyUnit Unit { get { return _unit; } internal set { _unit = value; } } public ProsodyNumber(int ssmlAttributeId) { _ssmlAttributeId = ssmlAttributeId; _number = 1f; _isPercent = true; _unit = ProsodyUnit.Default; } public ProsodyNumber(float number) { _ssmlAttributeId = int.MaxValue; _number = number; _isPercent = false; _unit = ProsodyUnit.Default; } public static bool operator ==(ProsodyNumber prosodyNumber1, ProsodyNumber prosodyNumber2) { if (prosodyNumber1._ssmlAttributeId == prosodyNumber2._ssmlAttributeId && prosodyNumber1.Number.Equals(prosodyNumber2.Number) && prosodyNumber1.IsNumberPercent == prosodyNumber2.IsNumberPercent) { return prosodyNumber1.Unit == prosodyNumber2.Unit; } return false; } public static bool operator !=(ProsodyNumber prosodyNumber1, ProsodyNumber prosodyNumber2) { return !(prosodyNumber1 == prosodyNumber2); } public bool Equals(ProsodyNumber other) { return this == other; } public override bool Equals(object obj) { if (!(obj is ProsodyNumber)) { return false; } return Equals((ProsodyNumber)obj); } public override int GetHashCode() { return base.GetHashCode(); } } [StructLayout(LayoutKind.Sequential)] public class SayAs { [MarshalAs(UnmanagedType.LPWStr)] private string _interpretAs; [MarshalAs(UnmanagedType.LPWStr)] private string _format; [MarshalAs(UnmanagedType.LPWStr)] private string _detail; public string InterpretAs { get { return _interpretAs; } set { Helpers.ThrowIfEmptyOrNull(value, "value"); _interpretAs = value; } } public string Format { get { return _format; } set { Helpers.ThrowIfEmptyOrNull(value, "value"); _format = value; } } public string Detail { get { return _detail; } set { Helpers.ThrowIfEmptyOrNull(value, "value"); _detail = value; } } } public enum TtsEngineAction { Speak, Silence, Pronounce, Bookmark, SpellOut, StartSentence, StartParagraph, ParseUnknownTag } public enum EmphasisWord { Default, Strong, Moderate, None, Reduced } public enum EmphasisBreak { None = -1, ExtraWeak = -2, Weak = -3, Medium = -4, Strong = -5, ExtraStrong = -6, Default = -7 } public enum ProsodyPitch { Default, ExtraLow, Low, Medium, High, ExtraHigh } public enum ProsodyRange { Default, ExtraLow, Low, Medium, High, ExtraHigh } public enum ProsodyRate { Default, ExtraSlow, Slow, Medium, Fast, ExtraFast } public enum ProsodyVolume { Default = -1, Silent = -2, ExtraSoft = -3, Soft = -4, Medium = -5, Loud = -6, ExtraLoud = -7 } public enum ProsodyUnit { Default, Hz, Semitone } public enum TtsEventId { StartInputStream = 1, EndInputStream, VoiceChange, Bookmark, WordBoundary, Phoneme, SentenceBoundary, Viseme, AudioLevel } public enum EventParameterType { Undefined, Token, Object, Pointer, String } public enum SpeakOutputFormat { WaveFormat, Text } public enum ContourPointChangeType { Hz, Percentage } } namespace System.Speech.Recognition { public class AudioLevelUpdatedEventArgs : EventArgs { private int _audioLevel; public int AudioLevel => _audioLevel; internal AudioLevelUpdatedEventArgs(int audioLevel) { _audioLevel = audioLevel; } } public enum AudioSignalProblem { None, TooNoisy, NoSignal, TooLoud, TooSoft, TooFast, TooSlow } public class AudioSignalProblemOccurredEventArgs : EventArgs { private AudioSignalProblem _audioSignalProblem; private TimeSpan _recognizerPosition; private TimeSpan _audioPosition; private int _audioLevel; public AudioSignalProblem AudioSignalProblem => _audioSignalProblem; public int AudioLevel => _audioLevel; public TimeSpan AudioPosition => _audioPosition; public TimeSpan RecognizerAudioPosition => _recognizerPosition; internal AudioSignalProblemOccurredEventArgs(AudioSignalProblem audioSignalProblem, int audioLevel, TimeSpan audioPosition, TimeSpan recognizerPosition) { _audioSignalProblem = audioSignalProblem; _audioLevel = audioLevel; _audioPosition = audioPosition; _recognizerPosition = recognizerPosition; } } public enum AudioState { Stopped, Silence, Speech } public class AudioStateChangedEventArgs : EventArgs { private AudioState _audioState; public AudioState AudioState => _audioState; internal AudioStateChangedEventArgs(AudioState audioState) { _audioState = audioState; } } [DebuggerDisplay("{_oneOf.DebugSummary}")] public class Choices { private OneOfElement _oneOf = new OneOfElement(); internal OneOfElement OneOf => _oneOf; public Choices() { } public Choices(params string[] phrases) { Helpers.ThrowIfNull(phrases, "phrases"); Add(phrases); } public Choices(params GrammarBuilder[] alternateChoices) { Helpers.ThrowIfNull(alternateChoices, "alternateChoices"); Add(alternateChoices); } public void Add(params string[] phrases) { Helpers.ThrowIfNull(phrases, "phrases"); foreach (string text in phrases) { Helpers.ThrowIfEmptyOrNull(text, "phrase"); _oneOf.Add(text); } } public void Add(params GrammarBuilder[] alternateChoices) { Helpers.ThrowIfNull(alternateChoices, "alternateChoices"); foreach (GrammarBuilder grammarBuilder in alternateChoices) { Helpers.ThrowIfNull(grammarBuilder, "alternateChoice"); _oneOf.Items.Add(new ItemElement(grammarBuilder)); } } public GrammarBuilder ToGrammarBuilder() { return new GrammarBuilder(this); } } public class DictationGrammar : Grammar { private static Uri s_defaultDictationUri = new Uri("grammar:dictation"); public DictationGrammar() : base(s_defaultDictationUri, null, null) { } public DictationGrammar(string topic) : base(new Uri(topic, UriKind.RelativeOrAbsolute), null, null) { } public void SetDictationContext(string precedingText, string subsequentText) { if (base.State != GrammarState.Loaded) { throw new InvalidOperationException(SR.Get(SRID.GrammarNotLoaded)); } base.Recognizer.SetDictationContext(this, precedingText, subsequentText); } } public class EmulateRecognizeCompletedEventArgs : AsyncCompletedEventArgs { private RecognitionResult _result; public RecognitionResult Result => _result; internal EmulateRecognizeCompletedEventArgs(RecognitionResult result, Exception error, bool cancelled, object userState) : base(error, cancelled, userState) { _result = result; } } [DebuggerDisplay("Grammar: {(_uri != null ? \"uri=\" + _uri.ToString () + \" \" : \"\") + \"rule=\" + _ruleName }")] public class Grammar { private struct NameValuePair { internal string _name; internal string _value; } internal GrammarOptions _semanticTag; internal AppDomainGrammarProxy _proxy; internal ScriptRef[] _scripts; private byte[] _cfgData; private Stream _appStream; private bool _isSrgsDocument; private SrgsDocument _srgsDocument; private GrammarBuilder _grammarBuilder; private IRecognizerInternal _recognizer; private GrammarState _grammarState; private Exception _loadException; private Uri _uri; private Uri _baseUri; private string _ruleName; private string _resources; private object[] _parameters; private string _onInitParameters; private bool _enabled = true; private bool _isStg; private bool _sapi53Only; private uint _sapiGrammarId; private float _weight = 1f; private int _priority; private InternalGrammarData _internalData; private string _grammarName = string.Empty; private Collection<Grammar> _ruleRefs; private static ResourceLoader s_resourceLoader = new ResourceLoader(); public bool Enabled { get { return _enabled; } set { if (_grammarState != GrammarState.Unloaded && _enabled != value) { _recognizer.SetGrammarState(this, value); } _enabled = value; } } public float Weight { get { return _weight; } set { if ((double)value < 0.0 || (double)value > 1.0) { throw new ArgumentOutOfRangeException("value", SR.Get(SRID.GrammarInvalidWeight)); } if (_grammarState != GrammarState.Unloaded && !_weight.Equals(value)) { _recognizer.SetGrammarWeight(this, value); } _weight = value; } } public int Priority { get { return _priority; } set { if (value < -128 || value > 127) { throw new ArgumentOutOfRangeException("value", SR.Get(SRID.GrammarInvalidPriority)); } if (_grammarState != GrammarState.Unloaded && _priority != value) { _recognizer.SetGrammarPriority(this, value); } _priority = value; } } public string Name { get { return _grammarName; } set { if (value == null) { value = string.Empty; } _grammarName = value; } } public string RuleName => _ruleName; public bool Loaded => _grammarState == GrammarState.Loaded; internal Uri Uri => _uri; internal IRecognizerInternal Recognizer { get { return _recognizer; } set { _recognizer = value; } } internal GrammarState State { get { return _grammarState; } set { switch (value) { case GrammarState.Unloaded: _loadException = null; _recognizer = null; break; default: _ = 3; break; case GrammarState.Loaded: break; } _grammarState = value; } } internal Exception LoadException { get { return _loadException; } set { _loadException = value; } } internal byte[] CfgData => _cfgData; internal Uri BaseUri => _baseUri; internal bool Sapi53Only => _sapi53Only; internal uint SapiGrammarId { get { return _sapiGrammarId; } set { _sapiGrammarId = value; } } protected internal virtual bool IsStg => _isStg; internal bool IsSrgsDocument => _isSrgsDocument; internal InternalGrammarData InternalData { get { return _internalData; } set { _internalData = value; } } protected string ResourceName { get { return _resources; } set { Helpers.ThrowIfEmptyOrNull(value, "value"); _resources = value; } } public event EventHandler<SpeechRecognizedEventArgs> SpeechRecognized; internal Grammar(Uri uri, string ruleName, object[] parameters) { Helpers.ThrowIfNull(uri, "uri"); _uri = uri; InitialGrammarLoad(ruleName, parameters, isImportedGrammar: false); } public Grammar(string path) : this(path, (string)null, (object[])null) { } public Grammar(string path, string ruleName) : this(path, ruleName, null) { } public Grammar(string path, string ruleName, object[] parameters) { try { _uri = new Uri(path, UriKind.Relative); } catch (UriFormatException innerException) { throw new ArgumentException(SR.Get(SRID.RecognizerGrammarNotFound), "path", innerException); } InitialGrammarLoad(ruleName, parameters, isImportedGrammar: false); } public Grammar(SrgsDocument srgsDocument) : this(srgsDocument, null, null, null) { } public Grammar(SrgsDocument srgsDocument, string ruleName) : this(srgsDocument, ruleName, null, null) { } public Grammar(SrgsDocument srgsDocument, string ruleName, object[] parameters) : this(srgsDocument, ruleName, null, parameters) { } [EditorBrowsable(EditorBrowsableState.Advanced)] public Grammar(SrgsDocument srgsDocument, string ruleName, Uri baseUri) : this(srgsDocument, ruleName, baseUri, null) { } [EditorBrowsable(EditorBrowsableState.Advanced)] public Grammar(SrgsDocument srgsDocument, string ruleName, Uri baseUri, object[] parameters) { Helpers.ThrowIfNull(srgsDocument, "srgsDocument"); _srgsDocument = srgsDocument; _isSrgsDocument = srgsDocument != null; _baseUri = baseUri; InitialGrammarLoad(ruleName, parameters, isImportedGrammar: false); } public Grammar(Stream stream) : this(stream, null, null, null) { } public Grammar(Stream stream, string ruleName) : this(stream, ruleName, null, null) { } public Grammar(Stream stream, string ruleName, object[] parameters) : this(stream, ruleName, null, parameters) { } [EditorBrowsable(EditorBrowsableState.Advanced)] public Grammar(Stream stream, string ruleName, Uri baseUri) : this(stream, ruleName, baseUri, null) { } [EditorBrowsable(EditorBrowsableState.Advanced)] public Grammar(Stream stream, string ruleName, Uri baseUri, object[] parameters) { Helpers.ThrowIfNull(stream, "stream"); if (!stream.CanRead) { throw new ArgumentException(SR.Get(SRID.StreamMustBeReadable), "stream"); } _appStream = stream; _baseUri = baseUri; InitialGrammarLoad(ruleName, parameters, isImportedGrammar: false); } public Grammar(GrammarBuilder builder) { Helpers.ThrowIfNull(builder, "builder"); _grammarBuilder = builder; InitialGrammarLoad(null, null, isImportedGrammar: false); } private Grammar(string onInitParameters, Stream stream, string ruleName) { _appStream = stream; _onInitParameters = onInitParameters; InitialGrammarLoad(ruleName, null, isImportedGrammar: true); } protected Grammar() { } protected void StgInit(object[] parameters) { _parameters = parameters; LoadAndCompileCfgData(isImportedGrammar: false, stgInit: true); } public static Grammar LoadLocalizedGrammarFromType(Type type, params object[] onInitParameters) { Helpers.ThrowIfNull(type, "type"); if (type == typeof(Grammar) || !type.IsSubclassOf(typeof(Grammar))) { throw new ArgumentException(SR.Get(SRID.StrongTypedGrammarNotAGrammar), "type"); } Assembly assembly = Assembly.GetAssembly(type); Type[] types = assembly.GetTypes(); foreach (Type type2 in types) { string s = null; if ((!(type2 == type) && !type2.IsSubclassOf(type)) || !(type2.GetField("__cultureId") != null)) { continue; } try { s = (string)type2.InvokeMember("__cultureId", BindingFlags.GetField, null, null, null, null); } catch (Exception ex) { if (!(ex is MissingFieldException)) { throw; } } if (Helpers.CompareInvariantCulture(new CultureInfo(int.Parse(s, CultureInfo.InvariantCulture)), CultureInfo.CurrentUICulture)) { try { return (Grammar)assembly.CreateInstance(type2.FullName, ignoreCase: false, BindingFlags.CreateInstance, null, onInitParameters, null, null); } catch (MissingMemberException) { throw new ArgumentException(SR.Get(SRID.RuleScriptInvalidParameters, type2.Name, type2.Name)); } } } return null; } internal static Grammar Create(string grammarName, string ruleName, string onInitParameter, out Uri redirectUri) { redirectUri = null; grammarName = grammarName.Trim(); Uri result; bool flag = Uri.TryCreate(grammarName, UriKind.Absolute, out result); int num = grammarName.IndexOf(".dll", StringComparison.OrdinalIgnoreCase); if (!flag || (num > 0 && num == grammarName.Length - 4)) { Assembly assembly; if (flag) { if (!result.IsFile) { throw new InvalidOperationException(); } assembly = Assembly.LoadFrom(result.LocalPath); } else { assembly = Assembly.Load(grammarName); } return LoadGrammarFromAssembly(assembly, ruleName, onInitParameter); } try { string localPath; using Stream stream = s_resourceLoader.LoadFile(result, out localPath, out redirectUri); try { return new Grammar(onInitParameter, stream, ruleName); } finally { s_resourceLoader.UnloadFile(localPath); } } catch { Assembly assembly2 = Assembly.LoadFrom(grammarName); return LoadGrammarFromAssembly(assembly2, ruleName, onInitParameter); } } internal void OnRecognitionInternal(SpeechRecognizedEventArgs eventArgs) { this.SpeechRecognized?.Invoke(this, eventArgs); } internal static bool IsDictationGrammar(Uri uri) { if (uri == null || !uri.IsAbsoluteUri || uri.Scheme != "grammar" || !string.IsNullOrEmpty(uri.Host) || !string.IsNullOrEmpty(uri.Authority) || !string.IsNullOrEmpty(uri.Query) || uri.PathAndQuery != "dictation") { return false; } return true; } internal bool IsDictation(Uri uri) { bool flag = IsDictationGrammar(uri); if (!flag && this is DictationGrammar) { throw new ArgumentException(SR.Get(SRID.DictationInvalidTopic), "uri"); } return flag; } internal Grammar Find(long grammarId) { if (_ruleRefs != null) { foreach (Grammar ruleRef in _ruleRefs) { if (grammarId == ruleRef._sapiGrammarId) { return ruleRef; } Grammar result; if ((result = ruleRef.Find(grammarId)) != null) { return result; } } } return null; } internal Grammar Find(string ruleName) { if (_ruleRefs != null) { foreach (Grammar ruleRef in _ruleRefs) { if (ruleName == ruleRef.RuleName) { return ruleRef; } Grammar result; if ((result = ruleRef.Find(ruleName)) != null) { return result; } } } return null; } internal void AddRuleRef(Grammar ruleRef, uint grammarId) { if (_ruleRefs == null) { _ruleRefs = new Collection<Grammar>(); } _ruleRefs.Add(ruleRef); _sapiGrammarId = grammarId; } internal MethodInfo MethodInfo(string method) { return GetType().GetMethod(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } private void LoadAndCompileCfgData(bool isImportedGrammar, bool stgInit) { Stream stream = (IsStg ? LoadCfgFromResource(stgInit) : LoadCfg(isImportedGrammar, stgInit)); SrgsRule[] array = RunOnInit(IsStg); if (array != null) { MemoryStream memoryStream = CombineCfg(_ruleName, stream, array); stream.Close(); stream = memoryStream; } _cfgData = Helpers.ReadStreamToByteArray(stream, (int)stream.Length); stream.Close(); _srgsDocument = null; _appStream = null; } private MemoryStream LoadCfg(bool isImportedGrammar, bool stgInit) { Uri uri = Uri; MemoryStream memoryStream = new MemoryStream(); if (uri != null) { throw new PlatformNotSupportedException(); } if (_srgsDocument != null) { SrgsGrammarCompiler.Compile(_srgsDocument, memoryStream); if (_baseUri == null && _srgsDocument.BaseUri != null) { _baseUri = _srgsDocument.BaseUri; } } else if (_grammarBuilder != null) { _grammarBuilder.Compile(memoryStream); } else { SrgsGrammarCompiler.CompileXmlOrCopyCfg(_appStream, memoryStream, null); } memoryStream.Position = 0L; _ruleName = CheckRuleName(memoryStream, _ruleName, isImportedGrammar, stgInit, out _sapi53Only, out _semanticTag); CreateSandbox(memoryStream); memoryStream.Position = 0L; return memoryStream; } private static Grammar LoadGrammarFromAssembly(Assembly assembly, string ruleName, string onInitParameters) { Type typeFromHandle = typeof(Grammar); Type type = null; Type[] types = assembly.GetTypes(); foreach (Type type2 in types) { if (!type2.IsSubclassOf(typeFromHandle)) { continue; } string s = null; if (type2.Name == ruleName) { type = type2; } if ((!(type2 == type) && (!(type != null) || !type2.IsSubclassOf(type))) || !(type2.GetField("__cultureId") != null)) { continue; } try { s = (string)type2.InvokeMember("__cultureId", BindingFlags.GetField, null, null, null, null); } catch (Exception ex) { if (!(ex is MissingFieldException)) { throw; } } if (Helpers.CompareInvariantCulture(new CultureInfo(int.Parse(s, CultureInfo.InvariantCulture)), CultureInfo.CurrentUICulture)) { try { object[] args = MatchInitParameters(type2, onInitParameters, assembly.GetName().Name, ruleName); return (Grammar)assembly.CreateInstance(type2.FullName, ignoreCase: false, BindingFlags.CreateInstance, null, args, null, null); } catch (MissingMemberException) { throw new ArgumentException(SR.Get(SRID.RuleScriptInvalidParameters, type2.Name, type2.Name)); } } } return null; } private static object[] MatchInitParameters(Type type, string onInitParameters, string grammar, string rule) { ConstructorInfo[] constructors = type.GetConstructors(); NameValuePair[] array = ParseInitParams(onInitParameters); object[] array2 = new object[array.Length]; bool flag = false; for (int i = 0; i < constructors.Length; i++) { if (flag) { break; } ParameterInfo[] parameters = constructors[i].GetParameters(); if (parameters.Length > array.Length) { continue; } flag = true; for (int j = 0; j < array.Length && flag; j++) { NameValuePair nameValuePair = array[j]; if (nameValuePair._name == null) { array2[j] = nameValuePair._value; continue; } bool flag2 = false; for (int k = 0; k < parameters.Length; k++) { if (parameters[k].Name == nameValuePair._name) { array2[k] = ParseValue(parameters[k].ParameterType, nameValuePair._value); flag2 = true; break; } } if (!flag2) { flag = false; } } } if (!flag) { throw new FormatException(SR.Get(SRID.CantFindAConstructor, grammar, rule, FormatConstructorParameters(constructors))); } return array2; } private static object ParseValue(Type type, string value) { if (type == typeof(string)) { return value; } return type.InvokeMember("Parse", BindingFlags.InvokeMethod, null, null, new object[1] { value }, CultureInfo.InvariantCulture); } private static string FormatConstructorParameters(ConstructorInfo[] cis) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < cis.Length; i++) { stringBuilder.Append((i > 0) ? " or sapi:parms=\"" : "sapi:parms=\""); ParameterInfo[] parameters = cis[i].GetParameters(); for (int j = 0; j < parameters.Length; j++) { if (j > 0) { stringBuilder.Append(';'); } ParameterInfo parameterInfo = parameters[j]; stringBuilder.Append(parameterInfo.Name); stringBuilder.Append(':'); stringBuilder.Append(parameterInfo.ParameterType.Name); } stringBuilder.Append('"'); } return stringBuilder.ToString(); } private static NameValuePair[] ParseInitParams(string initParameters) { if (string.IsNullOrEmpty(initParameters)) { return Array.Empty<NameValuePair>(); } string[] array = initParameters.Split(new char[1] { ';' }, StringSplitOptions.None); NameValuePair[] array2 = new NameValuePair[array.Length]; for (int i = 0; i < array.Length; i++) { string text = array[i]; int num = text.IndexOf(':'); if (num >= 0) { array2[i]._name = text.Substring(0, num); array2[i]._value = text.Substring(num + 1); } else { array2[i]._value = text; } } return array2; } private void InitialGrammarLoad(string ruleName, object[] parameters, bool isImportedGrammar) { _ruleName = ruleName; _parameters = parameters; if (!IsDictation(_uri)) { LoadAndCompileCfgData(isImportedGrammar, stgInit: false); } } private void CreateSandbox(MemoryStream stream) { stream.Position = 0L; if (CfgGrammar.LoadIL(stream, out var assemblyContent, out var assemblyDebugSymbols, out var scripts)) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); _proxy = new AppDomainGrammarProxy(); _proxy.In