repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; public class PurchasePage : MonoBehaviour { [SerializeField] private Button _loadProductsBtn; [SerializeField] private Button _loadPurchasesBtn; [SerializeField] private GameObject _productRowPrefab; [SerializeField] private Transform _productScrollTransform; [SerializeField] private GameObject _purchaseRowPrefab; [SerializeField] private Transform _purchaseScrollTransform; private LogScroller _logScroller; private IList<Product> _products = new List<Product>(); private void Awake () { _logScroller = transform.root.GetComponent<UIState>().logScroller; } public void CheckReady () { LogText("Checking Ready"); FBGamingServices.OnIAPReady(delegate(IIAPReadyResult result) { if (result.Error == null && result.ResultDictionary != null) { _loadProductsBtn.interactable = true; _loadPurchasesBtn.interactable = true; LogText("IAP Ready"); } else { LogText("ERR: IAP not ready" + result.Error.ToString()); } }); } public void ConsumePurchase (Purchase purchase, Action<bool> callback) { LogText("Consuming " + purchase.PurchaseToken + " : " + purchase.ProductID); callback(true); FBGamingServices.ConsumePurchase(purchase.PurchaseToken, delegate (IConsumePurchaseResult result) { if (result.Error == null && result.ResultDictionary != null) { LogText("Consumed purchase " + purchase.PurchaseToken + " : " + purchase.ProductID); callback(true); } else { LogText(string.Format("ERR: Failed to consume purchase {0} : {1}\n{2}", purchase.PurchaseToken, purchase.ProductID, result.Error.ToString())); callback(false); } }); } public void LoadProducts () { LogText("Loading Products"); foreach (Transform child in _productScrollTransform) { Destroy(child.gameObject); } FBGamingServices.GetCatalog(delegate (ICatalogResult result) { if (result.Error == null && result.ResultDictionary != null) { _products = result.Products; // nullable? LogText(string.Format("Got {0} products", result.Products.Count)); foreach (Product product in _products) { GameObject productRow = Instantiate(_productRowPrefab, _productScrollTransform); productRow.GetComponent<ProductRowPrefab>().Initialize(this, _logScroller, product); } } else { LogText(string.Format("ERR: Failed to get products\n{0}", result.Error)); } }); } public void LoadPurchases () { LogText("Loading Purchases"); foreach (Transform child in _purchaseScrollTransform) { Destroy(child.gameObject); } FBGamingServices.GetPurchases(delegate (IPurchasesResult result) { if (result.Error == null && result.ResultDictionary != null) { LogText(string.Format("Got {0} purchases", result.Purchases.Count)); foreach (Purchase purchase in result.Purchases) { AddPurchase(purchase, false); } } else { LogText("ERR: Failed to get purchases\n" + result.Error); } }); } public void MakePurchase (Product product) { LogText("Purchasing " + product.ProductID); FBGamingServices.Purchase(product.ProductID, delegate (IPurchaseResult result) { if (result.Error == null && result.ResultDictionary != null) { // ConsumePurchase(result.Purchase); LogText(string.Format("Purchased {0} | {1}", result.Purchase.ProductID, result.Purchase.PurchaseToken)); AddPurchase(result.Purchase, true); } else if (result.Cancelled) { LogText("Cancelled purchase"); } else { LogText(string.Format("ERR: Failed to purchase {0}\n{1}", product.ProductID, result.Error.ToString())); } }); } public void ToggleShowConsumedClicked (bool show) { foreach (Transform child in _purchaseScrollTransform) { child.gameObject.SetActive(show); } } // private private void AddPurchase (Purchase purchase, bool setToTop) { GameObject purchaseRow = Instantiate(_purchaseRowPrefab, _purchaseScrollTransform); purchaseRow.GetComponent<PurchaseRowPrefab>().Initialize(this, _logScroller, purchase); if (setToTop) { purchaseRow.transform.SetSiblingIndex(0); } } private void LogText (string text) { _logScroller.Log(text); } }
151
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using UnityEngine; using UnityEngine.UI; public class SavePage : MonoBehaviour { [SerializeField] private Button _saveLogBtn; [SerializeField] private InputField _customInputField; [SerializeField] private Button _appendDataBtn; private string LOGS_FOLDER_PATH; private string PLAYER_PREFS_PATH; private string SAVE_FILE_PATH; private LogScroller _logScroller; private void Awake() { LOGS_FOLDER_PATH = string.Format("{0}/Logs", Application.persistentDataPath); PLAYER_PREFS_PATH = string.Format("/data/data/{0}/shared_prefs/{0}.v2.playerprefs.xml", Application.identifier); // Path that you would input under save file paths when uploading binary to Facebook Developer App SAVE_FILE_PATH = Application.persistentDataPath + "/savefile.txt"; _logScroller = transform.root.GetComponent<UIState>().logScroller; } // player prefs public void OnLogPlayerPrefsBtnClick () { int mutedState = PlayerPrefs.GetInt("muted"); // Debug.Log(mutedState); _logScroller.Log("muted: " + mutedState); } public void OnSavePlayerPrefsBtnClick () { _logScroller.Log("PlayerPrefs Saved\n" + PLAYER_PREFS_PATH); PlayerPrefs.Save(); } // log files public void OnDeleteLogFilesBtnClick () { Directory.Delete(LOGS_FOLDER_PATH, true); _logScroller.Log("All Logs Deleted"); } public void OnSaveLogsBtnClick () { _logScroller.Log("Saving Logs to Disk"); if (!Directory.Exists(LOGS_FOLDER_PATH)) { Directory.CreateDirectory(LOGS_FOLDER_PATH); } string filePath = string.Format("{0}/{1}.txt", LOGS_FOLDER_PATH, DateTimeOffset.Now.ToUnixTimeSeconds()); try { File.AppendAllLines(filePath, _logScroller.texts); _logScroller.Log("Logs saved to " + filePath); } catch (Exception err) { _logScroller.Log("ERR: Failed to save logs\n" + err.Message); } } // save file public void OnAppendSaveFileBtnClick () { _logScroller.Log("Appending to Save File"); try { File.AppendAllText(SAVE_FILE_PATH, _customInputField.text + "\n"); _customInputField.text = ""; _logScroller.Log("Appended to\n" + SAVE_FILE_PATH); } catch (Exception err) { _logScroller.Log("ERR: Failed to append to save file\n" + err.Message); } } public void OnDeleteSaveFileBtnClick () { File.Delete(SAVE_FILE_PATH); _logScroller.Log("Save File Deleted"); } public void OnLogSaveFileBtnClick () { _logScroller.Log("Loading Save File"); try { string[] lines = File.ReadAllLines(SAVE_FILE_PATH); _logScroller.Log(string.Format("Save file has {0} lines:\n\n{1}", lines.Length, String.Join("\n", lines))); } catch (Exception err) { _logScroller.Log("ERR: Failed to load from save file\n" + err.Message); } } public void OnLogSaveFilePathBtnClick () { _logScroller.Log("Save file path\n" + SAVE_FILE_PATH); } }
113
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class SettingsMenu : MonoBehaviour { private bool showSettings = false; public void ToggleActive () { showSettings = !showSettings; gameObject.SetActive(showSettings); } }
32
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIState : MonoBehaviour { public LogScroller logScroller; }
28
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class Utility { private static Dictionary<string, Texture> _textures = new Dictionary<string, Texture>(); // TODO check if loading a texture already for an id and wait for that instead of redoing the work public static IEnumerator GetTexture(string id, string url, System.Action<Texture> callback) { if (_textures.ContainsKey(id)) { callback(_textures[id]); yield break; } UnityWebRequest www = UnityWebRequestTexture.GetTexture(url); yield return www.SendWebRequest(); if (www.responseCode != 200) { Debug.Log(www.error); } else { // Texture texture = ((DownloadHandlerTexture)www.downloadHandler).texture; Texture texture = DownloadHandlerTexture.GetContent(www); callback(texture); } } }
49
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.SceneManagement; internal class ConsoleBase : MonoBehaviour { private const int DpiScalingFactor = 160; private static Stack<string> menuStack = new Stack<string>(); private string status = "Ready"; private string lastResponse = string.Empty; private Vector2 scrollPosition = Vector2.zero; // DPI scaling private float? scaleFactor; private GUIStyle textStyle; private GUIStyle buttonStyle; private GUIStyle textInputStyle; private GUIStyle labelStyle; protected static int ButtonHeight { get { return Constants.IsMobile ? 60 : 24; } } protected static int MainWindowWidth { get { return Constants.IsMobile ? Screen.width - 30 : 700; } } protected static int MainWindowFullWidth { get { return Constants.IsMobile ? Screen.width : 760; } } protected static int MarginFix { get { return Constants.IsMobile ? 0 : 48; } } protected static Stack<string> MenuStack { get { return ConsoleBase.menuStack; } set { ConsoleBase.menuStack = value; } } protected string Status { get { return this.status; } set { this.status = value; } } protected Texture2D LastResponseTexture { get; set; } protected string LastResponse { get { return this.lastResponse; } set { this.lastResponse = value; } } protected Vector2 ScrollPosition { get { return this.scrollPosition; } set { this.scrollPosition = value; } } // Note we assume that these styles will be accessed from OnGUI otherwise the // unity APIs will fail. protected float ScaleFactor { get { if (!this.scaleFactor.HasValue) { this.scaleFactor = Screen.dpi / ConsoleBase.DpiScalingFactor; } return this.scaleFactor.Value; } } protected int FontSize { get { return (int)Math.Round(this.ScaleFactor * 16); } } protected GUIStyle TextStyle { get { if (this.textStyle == null) { this.textStyle = new GUIStyle(GUI.skin.textArea); this.textStyle.alignment = TextAnchor.UpperLeft; this.textStyle.wordWrap = true; this.textStyle.padding = new RectOffset(10, 10, 10, 10); this.textStyle.stretchHeight = true; this.textStyle.stretchWidth = false; this.textStyle.fontSize = this.FontSize; } return this.textStyle; } } protected GUIStyle ButtonStyle { get { if (this.buttonStyle == null) { this.buttonStyle = new GUIStyle(GUI.skin.button); this.buttonStyle.fontSize = this.FontSize; } return this.buttonStyle; } } protected GUIStyle TextInputStyle { get { if (this.textInputStyle == null) { this.textInputStyle = new GUIStyle(GUI.skin.textField); this.textInputStyle.fontSize = this.FontSize; } return this.textInputStyle; } } protected GUIStyle LabelStyle { get { if (this.labelStyle == null) { this.labelStyle = new GUIStyle(GUI.skin.label); this.labelStyle.fontSize = this.FontSize; } return this.labelStyle; } } protected virtual void Awake() { // Limit the framerate to 60 to keep device from burning through cpu Application.targetFrameRate = 60; } protected bool Button(string label) { return GUILayout.Button( label, this.ButtonStyle, GUILayout.MinHeight(ConsoleBase.ButtonHeight * this.ScaleFactor), GUILayout.MaxWidth(ConsoleBase.MainWindowWidth)); } protected void LabelAndTextField(string label, ref string text) { GUILayout.BeginHorizontal(); GUILayout.Label(label, this.LabelStyle, GUILayout.MaxWidth(200 * this.ScaleFactor)); text = GUILayout.TextField( text, this.TextInputStyle, GUILayout.MaxWidth(ConsoleBase.MainWindowWidth - 150)); GUILayout.EndHorizontal(); } protected bool IsHorizontalLayout() { #if UNITY_IOS || UNITY_ANDROID return Screen.orientation == ScreenOrientation.LandscapeLeft; #else return true; #endif } protected void SwitchMenu(Type menuClass) { ConsoleBase.menuStack.Push(this.GetType().Name); SceneManager.LoadScene(menuClass.Name); } protected void GoBack() { if (ConsoleBase.menuStack.Any()) { SceneManager.LoadScene(ConsoleBase.menuStack.Pop()); } } } }
264
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System; using System.Collections.Generic; using System.Linq; using UnityEngine; internal class LogView : ConsoleBase { private static string datePatt = @"M/d/yyyy hh:mm:ss tt"; private static IList<string> events = new List<string>(); public static void AddLog(string log) { events.Insert(0, string.Format("{0}\n{1}\n", DateTime.Now.ToString(datePatt), log)); } protected void OnGUI() { GUILayout.BeginVertical(); GUILayout.Space(Screen.safeArea.yMin + 10); if (this.Button("Back")) { this.GoBack(); } #if UNITY_IOS || UNITY_ANDROID || UNITY_WP8 if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) { Vector2 scrollPosition = this.ScrollPosition; scrollPosition.y += Input.GetTouch(0).deltaPosition.y; this.ScrollPosition = scrollPosition; } #endif this.ScrollPosition = GUILayout.BeginScrollView( this.ScrollPosition, GUILayout.MinWidth(ConsoleBase.MainWindowFullWidth)); GUILayout.TextArea( string.Join("\n", events.ToArray()), this.TextStyle, GUILayout.ExpandHeight(true), GUILayout.MaxWidth(ConsoleBase.MainWindowWidth)); GUILayout.EndScrollView(); GUILayout.EndVertical(); } } }
72
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System; using System.Linq; using UnityEngine; internal abstract class MenuBase : ConsoleBase { private static ShareDialogMode shareDialogMode; protected abstract void GetGui(); protected virtual bool ShowDialogModeSelector() { return false; } protected virtual bool ShowBackButton() { return true; } protected void HandleResult(IResult result) { if (result == null) { this.LastResponse = "Null Response\n"; LogView.AddLog(this.LastResponse); return; } this.LastResponseTexture = null; // Some platforms return the empty string instead of null. if (!string.IsNullOrEmpty(result.Error)) { this.Status = "Error - Check log for details"; this.LastResponse = "Error Response:\n" + result.Error; } else if (result.Cancelled) { this.Status = "Cancelled - Check log for details"; this.LastResponse = "Cancelled Response:\n" + result.RawResult; } else if (!string.IsNullOrEmpty(result.RawResult)) { this.Status = "Success - Check log for details"; this.LastResponse = "Success Response:\n" + result.RawResult; } else { this.LastResponse = "Empty Response\n"; } LogView.AddLog(result.ToString()); } protected void HandleLimitedLoginResult(IResult result) { if (result == null) { this.LastResponse = "Null Response\n"; LogView.AddLog(this.LastResponse); return; } this.LastResponseTexture = null; // Some platforms return the empty string instead of null. if (!string.IsNullOrEmpty(result.Error)) { this.Status = "Error - Check log for details"; this.LastResponse = "Error Response:\n" + result.Error; } else if (result.Cancelled) { this.Status = "Cancelled - Check log for details"; this.LastResponse = "Cancelled Response:\n" + result.RawResult; } else if (!string.IsNullOrEmpty(result.RawResult)) { this.Status = "Success - Check log for details"; this.LastResponse = "Success Response:\n" + result.RawResult; } else { this.LastResponse = "Empty Response\n"; } String resultSummary = "Limited login results\n\n"; var profile = FB.Mobile.CurrentProfile(); resultSummary += "name: " + profile.Name + "\n"; resultSummary += "id: " + profile.UserID + "\n"; resultSummary += "email: " + profile.Email + "\n"; resultSummary += "pic URL: " + profile.ImageURL + "\n"; resultSummary += "birthday: " + profile.Birthday + "\n"; resultSummary += "age range: " + profile.AgeRange + "\n"; resultSummary += "first name: " + profile.FirstName + "\n"; resultSummary += "middle name: " + profile.MiddleName + "\n"; resultSummary += "last name: " + profile.LastName + "\n"; resultSummary += "friends: " + String.Join(",", profile.FriendIDs) + "\n"; if (profile.Hometown!=null){ resultSummary += "hometown: " + profile.Hometown.Name + "\n"; } if (profile.Location!=null){ resultSummary += "location: " + profile.Location.Name + "\n"; } resultSummary += "gender: " + profile.Gender + "\n"; LogView.AddLog(resultSummary); } protected void OnGUI() { if (this.IsHorizontalLayout()) { GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); } GUILayout.Space(Screen.safeArea.yMin + 10); GUILayout.Label(this.GetType().Name, this.LabelStyle); this.AddStatus(); #if UNITY_IOS || UNITY_ANDROID || UNITY_WP8 if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) { Vector2 scrollPosition = this.ScrollPosition; scrollPosition.y += Input.GetTouch(0).deltaPosition.y; this.ScrollPosition = scrollPosition; } #endif this.ScrollPosition = GUILayout.BeginScrollView( this.ScrollPosition, GUILayout.MinWidth(ConsoleBase.MainWindowFullWidth)); GUILayout.BeginHorizontal(); if (this.ShowBackButton()) { this.AddBackButton(); } this.AddLogButton(); if (this.ShowBackButton()) { // Fix GUILayout margin issues GUILayout.Label(GUIContent.none, GUILayout.MinWidth(ConsoleBase.MarginFix)); } GUILayout.EndHorizontal(); if (this.ShowDialogModeSelector()) { this.AddDialogModeButtons(); } GUILayout.BeginVertical(); // Add the ui from decendants this.GetGui(); GUILayout.Space(10); GUILayout.EndVertical(); GUILayout.EndScrollView(); } private void AddStatus() { GUILayout.Space(5); GUILayout.Box("Status: " + this.Status, this.TextStyle, GUILayout.MinWidth(ConsoleBase.MainWindowWidth)); } private void AddBackButton() { GUI.enabled = ConsoleBase.MenuStack.Any(); if (this.Button("Back")) { this.GoBack(); } GUI.enabled = true; } private void AddLogButton() { if (this.Button("Log")) { this.SwitchMenu(typeof(LogView)); } } private void AddDialogModeButtons() { GUILayout.BeginHorizontal(); foreach (var value in Enum.GetValues(typeof(ShareDialogMode))) { this.AddDialogModeButton((ShareDialogMode)value); } GUILayout.EndHorizontal(); } private void AddDialogModeButton(ShareDialogMode mode) { bool enabled = GUI.enabled; GUI.enabled = enabled && (mode != shareDialogMode); if (this.Button(mode.ToString())) { shareDialogMode = mode; FB.Mobile.ShareDialogMode = mode; } GUI.enabled = enabled; } } }
239
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using UnityEngine; using UnityEngine.EventSystems; using Facebook.Unity; public class UIInputHelper : MonoBehaviour { private FBSDKEventBindingManager eventBindingManager { get; set; } private Boolean isOldEventSystem { get; set; } = false; private void Start() { EventSystem sceneEventSystem = FindObjectOfType<EventSystem>(); isOldEventSystem = !(sceneEventSystem == null); if (!isOldEventSystem) { var eventSystem = new GameObject("EventSystem", typeof(EventSystem), typeof(StandaloneInputModule)); DontDestroyOnLoad(eventSystem); } } void Update() { if (isOldEventSystem) { if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)) { try { if (EventSystem.current.IsPointerOverGameObject() || (Input.touchCount > 0 && EventSystem.current.IsPointerOverGameObject(Input.touches[0].fingerId)) ) { if (null != EventSystem.current.currentSelectedGameObject) { string name = EventSystem.current.currentSelectedGameObject.name; GameObject go = EventSystem.current.currentSelectedGameObject; if (null != go.GetComponent<UnityEngine.UI.Button>() && null != eventBindingManager) { var eventBindings = eventBindingManager.eventBindings; FBSDKEventBinding matchedBinding = null; if (null != eventBindings) { foreach (var eventBinding in eventBindings) { if (FBSDKViewHiearchy.CheckGameObjectMatchPath(go, eventBinding.path)) { matchedBinding = eventBinding; break; } } } if (null != matchedBinding) { FB.LogAppEvent(matchedBinding.eventName); } } } } } catch (Exception) { return; } } } } }
92
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { internal class AccessTokenMenu : MenuBase { protected override void GetGui() { if (this.Button("Refresh Access Token")) { FB.Mobile.RefreshCurrentAccessToken(this.HandleResult); } } } }
34
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System.Collections.Generic; internal class AppEvents : MenuBase { protected override void GetGui() { if (this.Button("Log FB App Event")) { this.Status = "Logged FB.AppEvent"; FB.LogAppEvent( AppEventName.UnlockedAchievement, null, new Dictionary<string, object>() { { AppEventParameterName.Description, "Clicked 'Log AppEvent' button" } }); LogView.AddLog( "You may see results showing up at https://www.facebook.com/analytics/" + FB.AppId); } } } }
46
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { internal class AppLinks : MenuBase { protected override void GetGui() { if (this.Button("Get App Link")) { FB.GetAppLink(this.HandleResult); } if (Constants.IsMobile && this.Button("Fetch Deferred App Link")) { FB.Mobile.FetchDeferredAppLinkData(this.HandleResult); } } } }
39
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System.Collections.Generic; using System.Linq; using UnityEngine; internal class AppRequests : MenuBase { private string requestMessage = string.Empty; private string requestTo = string.Empty; private string requestFilter = string.Empty; private string requestExcludes = string.Empty; private string requestMax = string.Empty; private string requestData = string.Empty; private string requestTitle = string.Empty; private string requestObjectID = string.Empty; private int selectedAction = 0; private string[] actionTypeStrings = { "NONE", OGActionType.SEND.ToString(), OGActionType.ASKFOR.ToString(), OGActionType.TURN.ToString() }; protected override void GetGui() { if (this.Button("Select - Filter None")) { FB.AppRequest("Test Message", callback: this.HandleResult); } if (this.Button("Select - Filter app_users")) { List<object> filter = new List<object>() { "app_users" }; // workaround for mono failing with named parameters FB.AppRequest("Test Message", null, filter, null, 0, string.Empty, string.Empty, this.HandleResult); } if (this.Button("Select - Filter app_non_users")) { List<object> filter = new List<object>() { "app_non_users" }; FB.AppRequest("Test Message", null, filter, null, 0, string.Empty, string.Empty, this.HandleResult); } // Custom options this.LabelAndTextField("Message: ", ref this.requestMessage); this.LabelAndTextField("To (optional): ", ref this.requestTo); this.LabelAndTextField("Filter (optional): ", ref this.requestFilter); this.LabelAndTextField("Exclude Ids (optional): ", ref this.requestExcludes); this.LabelAndTextField("Filters: ", ref this.requestExcludes); this.LabelAndTextField("Max Recipients (optional): ", ref this.requestMax); this.LabelAndTextField("Data (optional): ", ref this.requestData); this.LabelAndTextField("Title (optional): ", ref this.requestTitle); GUILayout.BeginHorizontal(); GUILayout.Label( "Request Action (optional): ", this.LabelStyle, GUILayout.MaxWidth(200 * this.ScaleFactor)); this.selectedAction = GUILayout.Toolbar( this.selectedAction, this.actionTypeStrings, this.ButtonStyle, GUILayout.MinHeight(ConsoleBase.ButtonHeight * this.ScaleFactor), GUILayout.MaxWidth(ConsoleBase.MainWindowWidth - 150)); GUILayout.EndHorizontal(); this.LabelAndTextField("Request Object ID (optional): ", ref this.requestObjectID); if (this.Button("Custom App Request")) { OGActionType? action = this.GetSelectedOGActionType(); if (action != null) { FB.AppRequest( this.requestMessage, action.Value, this.requestObjectID, string.IsNullOrEmpty(this.requestTo) ? null : this.requestTo.Split(','), this.requestData, this.requestTitle, this.HandleResult); } else { FB.AppRequest( this.requestMessage, string.IsNullOrEmpty(this.requestTo) ? null : this.requestTo.Split(','), string.IsNullOrEmpty(this.requestFilter) ? null : this.requestFilter.Split(',').OfType<object>().ToList(), string.IsNullOrEmpty(this.requestExcludes) ? null : this.requestExcludes.Split(','), string.IsNullOrEmpty(this.requestMax) ? 0 : int.Parse(this.requestMax), this.requestData, this.requestTitle, this.HandleResult); } } } private OGActionType? GetSelectedOGActionType() { string actionString = this.actionTypeStrings[this.selectedAction]; if (actionString == OGActionType.SEND.ToString()) { return OGActionType.SEND; } else if (actionString == OGActionType.ASKFOR.ToString()) { return OGActionType.ASKFOR; } else if (actionString == OGActionType.TURN.ToString()) { return OGActionType.TURN; } else { return null; } } } }
144
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; internal class DialogShare : MenuBase { // Custom Share Link private string shareLink = "https://developers.facebook.com/"; private string shareTitle = "Link Title"; private string shareDescription = "Link Description"; private string shareImage = "http://i.imgur.com/j4M7vCO.jpg"; // Custom Feed Share private string feedTo = string.Empty; private string feedLink = "https://developers.facebook.com/"; private string feedTitle = "Test Title"; private string feedCaption = "Test Caption"; private string feedDescription = "Test Description"; private string feedImage = "http://i.imgur.com/zkYlB.jpg"; private string feedMediaSource = string.Empty; protected override bool ShowDialogModeSelector() { #if !UNITY_EDITOR && (UNITY_IOS || UNITY_ANDROID) return true; #else return false; #endif } protected override void GetGui() { bool enabled = GUI.enabled; if (this.Button("Share - Link")) { FB.ShareLink(new Uri("https://developers.facebook.com/"), callback: this.HandleResult); } // Note: Web dialog doesn't support photo urls. if (this.Button("Share - Link Photo")) { FB.ShareLink( new Uri("https://developers.facebook.com/"), "Link Share", "Look I'm sharing a link", new Uri("http://i.imgur.com/j4M7vCO.jpg"), callback: this.HandleResult); } this.LabelAndTextField("Link", ref this.shareLink); this.LabelAndTextField("Title", ref this.shareTitle); this.LabelAndTextField("Description", ref this.shareDescription); this.LabelAndTextField("Image", ref this.shareImage); if (this.Button("Share - Custom")) { FB.ShareLink( new Uri(this.shareLink), this.shareTitle, this.shareDescription, new Uri(this.shareImage), this.HandleResult); } GUI.enabled = enabled && (!Constants.IsEditor || (Constants.IsEditor && FB.IsLoggedIn)); if (this.Button("Feed Share - No To")) { FB.FeedShare( string.Empty, new Uri("https://developers.facebook.com/"), "Test Title", "Test caption", "Test Description", new Uri("http://i.imgur.com/zkYlB.jpg"), string.Empty, this.HandleResult); } this.LabelAndTextField("To", ref this.feedTo); this.LabelAndTextField("Link", ref this.feedLink); this.LabelAndTextField("Title", ref this.feedTitle); this.LabelAndTextField("Caption", ref this.feedCaption); this.LabelAndTextField("Description", ref this.feedDescription); this.LabelAndTextField("Image", ref this.feedImage); this.LabelAndTextField("Media Source", ref this.feedMediaSource); if (this.Button("Feed Share - Custom")) { FB.FeedShare( this.feedTo, string.IsNullOrEmpty(this.feedLink) ? null : new Uri(this.feedLink), this.feedTitle, this.feedCaption, this.feedDescription, string.IsNullOrEmpty(this.feedImage) ? null : new Uri(this.feedImage), this.feedMediaSource, this.HandleResult); } GUI.enabled = enabled; } } }
126
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System.Collections; using UnityEngine; internal class GraphRequest : MenuBase { private string apiQuery = string.Empty; private Texture2D profilePic; protected override void GetGui() { bool enabled = GUI.enabled; GUI.enabled = enabled && FB.IsLoggedIn; if (this.Button("Basic Request - Me")) { FB.API("/me", HttpMethod.GET, this.HandleResult); } if (this.Button("Retrieve Profile Photo")) { FB.API("/me/picture", HttpMethod.GET, this.ProfilePhotoCallback); } if (this.Button("Take and Upload screenshot")) { this.StartCoroutine(this.TakeScreenshot()); } this.LabelAndTextField("Request", ref this.apiQuery); if (this.Button("Custom Request")) { FB.API(this.apiQuery, HttpMethod.GET, this.HandleResult); } if (this.profilePic != null) { GUILayout.Box(this.profilePic); } GUI.enabled = enabled; } private void ProfilePhotoCallback(IGraphResult result) { if (string.IsNullOrEmpty(result.Error) && result.Texture != null) { this.profilePic = result.Texture; } this.HandleResult(result); } private IEnumerator TakeScreenshot() { yield return new WaitForEndOfFrame(); var width = Screen.width; var height = Screen.height; var tex = new Texture2D(width, height, TextureFormat.RGB24, false); // Read screen contents into the texture tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); tex.Apply(); byte[] screenshot = tex.EncodeToPNG(); var wwwForm = new WWWForm(); wwwForm.AddBinaryData("image", screenshot, "InteractiveConsole.png"); wwwForm.AddField("message", "herp derp. I did a thing! Did I do this right?"); FB.API("me/photos", HttpMethod.POST, this.HandleResult, wwwForm); } } }
94
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System.Collections.Generic; using System.Linq; using UnityEngine; internal sealed class MainMenu : MenuBase { enum Scope { PublicProfile = 1, UserFriends = 2, UserBirthday = 3, UserAgeRange = 4, PublishActions = 5, UserLocation = 6, UserHometown = 7, UserGender = 8, }; protected override bool ShowBackButton() { return false; } protected override void GetGui() { GUILayout.BeginVertical(); bool enabled = GUI.enabled; if (this.Button("FB.Init")) { FB.Init(this.OnInitComplete, this.OnHideUnity); this.Status = "FB.Init() called with " + FB.AppId; } GUILayout.BeginHorizontal(); GUI.enabled = enabled && FB.IsInitialized; if (this.Button("Classic login")) { this.CallFBLogin(LoginTracking.ENABLED, new HashSet<Scope> { Scope.PublicProfile }); this.Status = "Classic login called"; } if (this.Button("Get publish_actions")) { this.CallFBLoginForPublish(); this.Status = "Login (for publish_actions) called"; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (this.Button("Limited login")) { this.CallFBLogin(LoginTracking.LIMITED, new HashSet<Scope> { Scope.PublicProfile }); this.Status = "Limited login called"; } if (this.Button("Limited login +friends")) { this.CallFBLogin(LoginTracking.LIMITED, new HashSet<Scope> { Scope.PublicProfile, Scope.UserFriends }); this.Status = "Limited login +friends called"; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (this.Button("Limited Login+bday")) { this.CallFBLogin(LoginTracking.LIMITED, new HashSet<Scope> { Scope.PublicProfile, Scope.UserBirthday }); this.Status = "Limited login +bday called"; } if (this.Button("Limited Login+agerange")) { this.CallFBLogin(LoginTracking.LIMITED, new HashSet<Scope> { Scope.PublicProfile, Scope.UserAgeRange }); this.Status = "Limited login +agerange called"; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (this.Button("Limited Login + location")) { this.CallFBLogin(LoginTracking.LIMITED, new HashSet<Scope> { Scope.PublicProfile, Scope.UserLocation }); } if (this.Button("Limited Login + Hometown")) { this.CallFBLogin(LoginTracking.LIMITED, new HashSet<Scope> { Scope.PublicProfile, Scope.UserHometown }); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (this.Button("Limited Login + Gender")) { this.CallFBLogin(LoginTracking.LIMITED, new HashSet<Scope> { Scope.PublicProfile, Scope.UserGender }); } GUI.enabled = FB.IsLoggedIn; // Fix GUILayout margin issues GUILayout.Label(GUIContent.none, GUILayout.MinWidth(ConsoleBase.MarginFix)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); // Fix GUILayout margin issues GUILayout.Label(GUIContent.none, GUILayout.MinWidth(ConsoleBase.MarginFix)); GUILayout.EndHorizontal(); #if !UNITY_WEBGL if (this.Button("Logout")) { CallFBLogout(); this.Status = "Logout called"; } #endif GUI.enabled = enabled && FB.IsInitialized; if (this.Button("Share Dialog")) { this.SwitchMenu(typeof(DialogShare)); } if (this.Button("App Requests")) { this.SwitchMenu(typeof(AppRequests)); } if (this.Button("Graph Request")) { this.SwitchMenu(typeof(GraphRequest)); } if (Constants.IsWeb && this.Button("Pay")) { this.SwitchMenu(typeof(Pay)); } if (this.Button("App Events")) { this.SwitchMenu(typeof(AppEvents)); } if (this.Button("App Links")) { this.SwitchMenu(typeof(AppLinks)); } if (this.Button("Tournaments")) { this.SwitchMenu(typeof(TournamentsMenu)); } if (Constants.IsMobile && this.Button("Access Token")) { this.SwitchMenu(typeof(AccessTokenMenu)); } if (this.Button("UploadToMediaLibrary")) { this.SwitchMenu(typeof(UploadToMediaLibrary)); } if (Constants.IsWeb && this.Button("Subscription")) { this.SwitchMenu(typeof(Subscription)); } GUILayout.EndVertical(); GUI.enabled = enabled; } private void CallFBLogin(LoginTracking mode, HashSet<Scope> scope) { List<string> scopes = new List<string>(); if(scope.Contains(Scope.PublicProfile)) { scopes.Add("public_profile"); } if(scope.Contains(Scope.UserFriends)) { scopes.Add("user_friends"); } if(scope.Contains(Scope.UserBirthday)) { scopes.Add("user_birthday"); } if(scope.Contains(Scope.UserAgeRange)) { scopes.Add("user_age_range"); } if(scope.Contains(Scope.UserLocation)) { scopes.Add("user_location"); } if(scope.Contains(Scope.UserHometown)) { scopes.Add("user_hometown"); } if(scope.Contains(Scope.UserGender)) { scopes.Add("user_gender"); } if (Constants.IsWeb && this.Button("Subscription")) { this.SwitchMenu(typeof(Subscription)); } if (mode == LoginTracking.ENABLED) { if (Constants.CurrentPlatform == FacebookUnityPlatform.IOS) { FB.Mobile.LoginWithTrackingPreference(LoginTracking.ENABLED, scopes, "classic_nonce123", this.HandleResult); } else { FB.LogInWithReadPermissions(scopes, this.HandleResult); } } else // mode == loginTracking.LIMITED { FB.Mobile.LoginWithTrackingPreference(LoginTracking.LIMITED, scopes, "limited_nonce123", this.HandleLimitedLoginResult); } } private void CallFBLoginForPublish() { // It is generally good behavior to split asking for read and publish // permissions rather than ask for them all at once. // // In your own game, consider postponing this call until the moment // you actually need it. FB.LogInWithPublishPermissions(new List<string>() { "publish_actions" }, this.HandleResult); } private void CallFBLogout() { FB.LogOut(); } private void OnInitComplete() { this.Status = "Success - Check log for details"; this.LastResponse = "Success Response: OnInitComplete Called\n"; string logMessage = string.Format( "OnInitCompleteCalled IsLoggedIn='{0}' IsInitialized='{1}'", FB.IsLoggedIn, FB.IsInitialized); LogView.AddLog(logMessage); if (AccessToken.CurrentAccessToken != null) { LogView.AddLog(AccessToken.CurrentAccessToken.ToString()); } } private void OnHideUnity(bool isGameShown) { this.Status = "Success - Check log for details"; this.LastResponse = string.Format("Success Response: OnHideUnity Called {0}\n", isGameShown); LogView.AddLog("Is game shown: " + isGameShown); } } }
298
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using UnityEngine; internal class Pay : MenuBase { private string payProduct = string.Empty; protected override void GetGui() { this.LabelAndTextField("Product: ", ref this.payProduct); if (this.Button("Call Pay")) { this.CallFBPay(); } GUILayout.Space(10); } private void CallFBPay() { FB.Canvas.Pay(this.payProduct, callback: this.HandleResult); } } }
46
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using UnityEngine; internal class Subscription : MenuBase { private string subscriptionProductId = string.Empty; private string cancelSubscriptionProductId = string.Empty; protected override void GetGui() { if (this.Button("Call Get Subscribable Catalog")) { this.CallGetSubscribableCatalog(); } GUILayout.Space(10); this.LabelAndTextField("Purchase Subscription Product Id: ", ref this.subscriptionProductId); if (this.Button("Call Purchase Subscription")) { this.CallPurchaseSubscription(); } GUILayout.Space(10); if (this.Button("Call Get Subscriptions")) { this.CallGetSubscriptions(); } GUILayout.Space(10); this.LabelAndTextField("Cancel Subscription Id: ", ref this.cancelSubscriptionProductId); if (this.Button("Call Cancel Subscription")) { this.CallCancelSubscription(); } GUILayout.Space(10); } private void CallGetSubscribableCatalog() { FB.GetSubscribableCatalog(this.HandleResult); } private void CallPurchaseSubscription() { FB.PurchaseSubscription(this.subscriptionProductId, this.HandleResult); } private void CallGetSubscriptions() { FB.GetSubscriptions(this.HandleResult); } private void CallCancelSubscription() { FB.CancelSubscription(this.cancelSubscriptionProductId, this.HandleResult); } } }
87
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System; using System.Collections.Generic; using UnityEngine; internal class TournamentsMenu : MenuBase { private string score = string.Empty; private string tournamentID = string.Empty; protected override void GetGui() { bool enabled = GUI.enabled; GUI.enabled = enabled && FB.IsLoggedIn; if (this.Button("Get Tournament")) { FB.Mobile.GetTournaments(this.GetTournamentsHandleResult); } GUILayout.Space(24); this.LabelAndTextField("Score:", ref this.score); this.LabelAndTextField("TournamentID:", ref this.tournamentID); if (this.Button("Post Score to Tournament")) { FB.Mobile.UpdateTournament(tournamentID, int.Parse(score), this.HandleResult); } if (this.Button("Update Tournament and Share")) { FB.Mobile.UpdateAndShareTournament(tournamentID, int.Parse(score), this.HandleResult); } if (this.Button("Create Tournament and Share")) { FB.Mobile.CreateAndShareTournament( int.Parse(score), "Unity Tournament", TournamentSortOrder.HigherIsBetter, TournamentScoreFormat.Numeric, DateTime.UtcNow.AddHours(2), "Unity SDK Tournament", this.HandleResult ); } GUI.enabled = enabled; } private void GetTournamentsHandleResult(IGetTournamentsResult result) { LogView.AddLog("Getting first tournament id..."); if (result == null) { this.tournamentID = "Empty result"; LogView.AddLog("NULL result"); return; } if (result.ResultDictionary != null) { string dic; result.ResultDictionary.TryGetValue("0", out dic); if (dic != null) { LogView.AddLog("ResultDictionary"); TournamentResult tournament = new TournamentResult(new ResultContainer(dic)); if (tournament != null) { LogView.AddLog("Tournament info ready"); this.tournamentID = tournament.TournamentId; LogView.AddLog("First id: " + this.tournamentID + " / " + tournament.TournamentTitle); } else { LogView.AddLog("No tournament info"); } } else { LogView.AddLog("No TryGetValue data"); } } else { this.tournamentID = "Empty result"; LogView.AddLog("Empty result"); } this.HandleResult(result); } } }
117
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Example { using System; using System.IO; using UnityEngine; using UnityEngine.Networking; internal class UploadToMediaLibrary : MenuBase { private bool imageShouldLaunchMediaDialog = true; private string imageCaption = "Image Caption"; private string imageFile = "meta-logo.png"; private bool videoShouldLaunchMediaDialog = true; private string videoCaption = "Video Caption"; private string videoFile = "meta.mp4"; protected override void GetGui() { bool enabled = GUI.enabled; GUI.enabled = enabled && FB.IsLoggedIn; GUILayout.Space(24); this.LabelAndTextField("Image caption:", ref this.imageCaption); if (this.Button("Image Dialog: " + imageShouldLaunchMediaDialog.ToString())) { imageShouldLaunchMediaDialog = !imageShouldLaunchMediaDialog; } GUILayout.Space(24); string imagePath = GetPath(imageFile); if (File.Exists(imagePath)) { if (this.Button("Upload Image to media library")) { FBGamingServices.UploadImageToMediaLibrary(imageCaption, new Uri(imagePath), imageShouldLaunchMediaDialog, this.HandleResult); } } else { GUILayout.Label("Image does not exist: " + imagePath); } GUILayout.Space(24); this.LabelAndTextField("Video caption:", ref this.videoCaption); if (this.Button("Video Dialog: " + videoShouldLaunchMediaDialog.ToString())) { videoShouldLaunchMediaDialog = !videoShouldLaunchMediaDialog; } GUILayout.Space(24); string videoPath = GetPath(videoFile); if (File.Exists(videoPath)) { if (this.Button("Upload Video to media library")) { FBGamingServices.UploadVideoToMediaLibrary(videoCaption, new Uri(videoPath), videoShouldLaunchMediaDialog, this.HandleResult); } } else { GUILayout.Label("Video does not exist: " + videoPath); } } private string GetPath(string filename) { string path = Path.Combine(Application.streamingAssetsPath, filename); // Android cannot access StreamingAssets directly because they are packaged into an `apk` #if UNITY_ANDROID byte[] data = null; // Retrieve packaged data via `UnityWebRequest` var request = UnityWebRequest.Get(path); request.SendWebRequest(); while (!request.isDone) { if (request.isNetworkError || request.isHttpError) { break; } } data = request.downloadHandler.data; // Write the data so it can be uploaded path = Path.Combine(Application.persistentDataPath, filename); System.IO.File.WriteAllBytes(path, data); #endif return path; } } }
114
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; public class FBWindowsA2UNotificationsManager : MonoBehaviour { public FBWindowsLogsManager Logger; public InputField TitleText; public InputField BodyText; public InputField MediaText; public InputField PayloadText; public InputField TimeIntervalText; public void ScheduleButton () { Logger.DebugLog("Scheduling notification ..."); FB.ScheduleAppToUserNotification(TitleText.text, BodyText.text, new System.Uri(MediaText.text), int.Parse(TimeIntervalText.text), PayloadText.text, A2UNotificationCallback); } private void A2UNotificationCallback(IScheduleAppToUserNotificationResult result) { if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("Notification scheduled correctly."); } } }
55
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; using System; public class FBWindowsADSManager : MonoBehaviour { public FBWindowsLogsManager Logger; public InputField InputInterstitialAd; public InputField InputRewardedVideo; public void LoadRewardedVideo(string placementID) { Logger.DebugLog("Loading Rewarded Video"); FB.LoadRewardedVideo(placementID, delegate (IRewardedVideoResult rewardedVideoResult) { if (rewardedVideoResult.Error != null) { Logger.DebugErrorLog(rewardedVideoResult.Error); } else { Logger.DebugLog("Rewarded Video "+ placementID + " loaded correctly!"); } }); } public void ShowRewardedVideo(string placementID) { Logger.DebugLog("Showing Rewarded Video"); FB.ShowRewardedVideo(placementID, delegate (IRewardedVideoResult rewardedVideoResult) { if (rewardedVideoResult.Error != null) { Logger.DebugErrorLog(rewardedVideoResult.Error); } else { Logger.DebugLog("Rewarded Video " + placementID + " showed correctly!"); Logger.DebugLog("Here you can give a reward."); } }); } public void LoadInterstitialAd(string placementID) { Logger.DebugLog("Loading Interstitial AD"); FB.LoadInterstitialAd(placementID, delegate (IInterstitialAdResult interstitialAdResult) { if (interstitialAdResult.Error != null) { Logger.DebugErrorLog(interstitialAdResult.Error); } else { Logger.DebugLog("Interstitial AD " + placementID + " loaded correctly!"); } }); } public void ShowInterstitialAd(string placementID) { Logger.DebugLog("Showing Interstitial AD"); FB.ShowInterstitialAd(placementID, delegate (IInterstitialAdResult interstitialAdResult) { if (interstitialAdResult.Error != null) { Logger.DebugErrorLog(interstitialAdResult.Error); } else { Logger.DebugLog("Interstitial AD " + placementID + " showed correctly!"); } }); } public void OnButtonLoadInterstitialAd() { if (!String.IsNullOrEmpty(InputInterstitialAd.text)) { LoadInterstitialAd(InputInterstitialAd.text); } else { Logger.DebugWarningLog("Please, insert interstitial placement ID code."); } } public void OnButtonShowInterstitialAd() { if (!String.IsNullOrEmpty(InputInterstitialAd.text)) { ShowInterstitialAd(InputInterstitialAd.text); } else { Logger.DebugWarningLog("Please, insert interstitial placement ID code."); } } public void OnButtonLoadRewardedVideo() { if (!String.IsNullOrEmpty(InputRewardedVideo.text)) { LoadRewardedVideo(InputRewardedVideo.text); } else { Logger.DebugWarningLog("Please, insert rewarded video placement ID code."); } } public void OnButtonShowRewardedVideo() { if (!String.IsNullOrEmpty(InputRewardedVideo.text)) { ShowRewardedVideo(InputRewardedVideo.text); } else { Logger.DebugWarningLog("Please, insert rewarded video placement ID code."); } } }
149
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class FBWindowsExampleTabsManager : MonoBehaviour { public GameObject[] sections; void Start() { ShowTab(0); } public void ShowTab(int id) { foreach (GameObject section in sections) { section.SetActive(false); } sections[id].SetActive(true); } }
43
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; using System; public class FBWindowsFriendsManager : MonoBehaviour { public FBWindowsLogsManager Logger; public Transform ReceivedInvitationsPanelTransform; public GameObject ShowReceivedInvitation; public void Button_OpenReceivedInvitations() { if (FB.IsLoggedIn) { FB.OpenFriendFinderDialog(OpenFriendsDialogCallBack); } else { Logger.DebugWarningLog("Login First"); } } private void OpenFriendsDialogCallBack(IGamingServicesFriendFinderResult result) { if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("Friends Dialog openned succesflly"); } } public void Button_GetFriendFinderInvitations() { if (FB.IsLoggedIn) { FB.GetFriendFinderInvitations(GetFriendFinderInvitationsCallback); } else { Logger.DebugWarningLog("Login First"); } } private void GetFriendFinderInvitationsCallback(IFriendFinderInvitationResult receivedInvitations) { Logger.DebugLog("Processing received invitations..."); if (FB.IsLoggedIn) { foreach (Transform child in ReceivedInvitationsPanelTransform) { Destroy(child.gameObject); } if (receivedInvitations.Error != null) { Logger.DebugErrorLog(receivedInvitations.Error); } else { if (receivedInvitations.Invitations.Count <= 0) { Logger.DebugLog("No invitations received."); } else { foreach (FriendFinderInviation item in receivedInvitations.Invitations) { GameObject obj = (GameObject)Instantiate(ShowReceivedInvitation); obj.transform.SetParent(ReceivedInvitationsPanelTransform, false); obj.transform.localScale = new Vector3(1, 1, 1); Button button = obj.GetComponent<Button>(); button.onClick.AddListener(() => { button.interactable = false; FB.DeleteFriendFinderInvitation(item.Id, DeleteFriendFinderInvitationCallback); }); Text textComponent = obj.GetComponentInChildren<Text>(); textComponent.text = "ApplicationName: " + item.ApplicationName + "\nFrom: " + item.FromName + "\nTo: " + item.ToName + "\nMessage: " + item.Message + "\nTime: " + item.CreatedTime; } } } } else { Logger.DebugWarningLog("Login First"); } } private void DeleteFriendFinderInvitationCallback(IFriendFinderInvitationResult receivedInvitations) { if (receivedInvitations.Error != null) { Logger.DebugErrorLog(receivedInvitations.Error); } else { Logger.DebugLog("Inviation deleted succesfully. Give a reward at this point if you want."); } Button_GetFriendFinderInvitations(); } }
126
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; public class FBWindowsGraphAPIManager : MonoBehaviour { public FBWindowsLogsManager Logger; public InputField QueryText; public Dropdown QueryType; public InputField GraphAPIVersionText; public Text GraphAPIVersion; private IDictionary<string, string> formData = null; void Start() { GraphAPIVersionText.text = Constants.GraphApiVersion; } void OnEnable() { GraphAPIVersion.text = " Current Graph API version: " + FB.GraphApiVersion + "\n SDK Graph API version: " + Constants.GraphApiVersion; } public void GraphAPI() { HttpMethod typeQuery = (HttpMethod)Enum.Parse(typeof(HttpMethod), QueryType.options[QueryType.value].text); FB.API(QueryText.text, typeQuery, (result) => { Logger.DebugLog(result.RawResult); }, formData); } public void SetGraphAPiVersion() { if (GraphAPIVersionText.text != "") { FB.GraphApiVersion = GraphAPIVersionText.text; } OnEnable(); } }
64
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using Facebook.Unity; public class FBWindowsInitManager : MonoBehaviour { public FBWindowsLogsManager Logger; public void InitButton() { if (!FB.IsInitialized) { FB.Init(InitCallback, OnHideUnity); } else { FB.ActivateApp(); } } private void InitCallback() { if (FB.IsInitialized) { Logger.DebugLog("SDK correctly initializated: " + FB.FacebookImpl.SDKUserAgent); FB.ActivateApp(); } else { Logger.DebugErrorLog("Failed to Initialize the Facebook SDK"); } } private void OnHideUnity(bool isGameShown) { if (!isGameShown) { // Pause the game - we will need to hide Time.timeScale = 0; } else { // Resume the game - we're getting focus again Time.timeScale = 1; } } }
70
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; using System; public class FBWindowsLoginManager : MonoBehaviour { public FBWindowsLogsManager Logger; public InputField Permissions; public RawImage UserImage; public Text UserName; public void LogInReadButton() { if (FB.IsInitialized) { FB.LogInWithReadPermissions(Permissions.text.Split(','), AuthCallback); } else { Logger.DebugWarningLog("Not Init"); } } public void LogInPublishButton() { if (FB.IsInitialized) { FB.LogInWithPublishPermissions(Permissions.text.Split(','), AuthCallback); } else { Logger.DebugWarningLog("Not Init"); } } public void LogOutButton() { if (FB.IsLoggedIn) { FB.LogOut(); Logger.DebugLog("Logged out"); } else { Logger.DebugWarningLog("Login First"); } } private void AuthCallback(ILoginResult result) { if (result.Error != null) { Logger.DebugErrorLog("Error: " + result.Error); } else { if (FB.IsLoggedIn) { // AccessToken class will have session details var aToken = Facebook.Unity.AccessToken.CurrentAccessToken; // Print current access token's User ID Logger.DebugLog("aToken.UserId: " + aToken.UserId); // Print current access token's granted permissions foreach (string perm in aToken.Permissions) { Logger.DebugLog("perm: " + perm); } //get current profile data GetCurrentProfile(); } else { Logger.DebugWarningLog("User cancelled login"); } } } public void GetCurrentProfile() { Logger.DebugLog("Getting current user profile ..."); FB.CurrentProfile((IProfileResult result) => { if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("UserID: " + result.CurrentProfile.UserID); Logger.DebugLog("Name: " + result.CurrentProfile.Name); Logger.DebugLog("First Name: " + result.CurrentProfile.FirstName); Logger.DebugLog("Email: " + result.CurrentProfile.Email); Logger.DebugLog("ImageURL: " + result.CurrentProfile.ImageURL); GetUserLocale(); UserName.text = result.CurrentProfile.Name + " " + result.CurrentProfile.LastName; if (result.CurrentProfile.ImageURL != "" && result.CurrentProfile.ImageURL != null) { StartCoroutine(LoadPictureFromUrl(result.CurrentProfile.ImageURL, UserImage)); } } }); } public void GetUserLocale() { FB.GetUserLocale((ILocaleResult result) => { if (result.Error != null) { Logger.DebugErrorLog("Error getting user locale: " + result.Error); } else { Logger.DebugLog("User Locale: " + result.Locale); } }); } IEnumerator LoadPictureFromUrl(string url, RawImage itemImage) { Texture2D UserPicture = new Texture2D(32, 32); WWW www = new WWW(url); yield return www; www.LoadImageIntoTexture(UserPicture); www.Dispose(); www = null; itemImage.texture = UserPicture; } }
159
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using UnityEngine; using UnityEngine.UI; #if UNITY_EDITOR using UnityEditor; #endif public class FBWindowsLogsManager : MonoBehaviour { public Text LogText; public ScrollRect ScrollView; void Awake() { #if !UNITY_EDITOR_WIN Debug.Log("This example is only for Windows devices."); #else if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.StandaloneWindows && EditorUserBuildSettings.activeBuildTarget != BuildTarget.StandaloneWindows64) { Debug.Log("This example is only for Windows build target (x86 or x84)."); } #endif } public void DebugLog(string message) { LogText.text += "<color=white>" + message + "</color> \n"; ScrollToTheBottom(); } public void DebugErrorLog(string message) { LogText.text += "<color=red>" + message + "</color> \n"; ScrollToTheBottom(); } public void DebugWarningLog(string message) { LogText.text += "<color=yellow>" + message + "</color> \n"; ScrollToTheBottom(); } public void DebugClean() { LogText.text = ""; } private void ScrollToTheBottom() { ScrollView.verticalNormalizedPosition = 0; Canvas.ForceUpdateCanvases(); } }
74
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using UnityEngine; using UnityEngine.UI; #if (UNITY_STANDALONE_WIN || UNTIY_EDITOR_WIN) && !UNITY_WEBGL using XInputDotNetPure; #endif public class FBWindowsPhysicalGamepadManager : MonoBehaviour { public Text displayGamepadInputText; #if (UNITY_STANDALONE_WIN || UNTIY_EDITOR_WIN) && !UNITY_WEBGL public GamePadState state; void Update() { state = GamePad.GetState(0); displayGamepadInputText.text = ""; displayGamepadInputText.text += "--- Sticks ---\n"; displayGamepadInputText.text += string.Format("Left X: {0}\nLeft Y: {1}\nRight X: {2}\nRight Y: {3}\n", state.ThumbSticks.Left.X, state.ThumbSticks.Left.Y, state.ThumbSticks.Right.X, state.ThumbSticks.Right.Y); displayGamepadInputText.text += "\n--- Buttons ---\n"; displayGamepadInputText.text += string.Format("Start: {0} | Back: {1}\n", state.Buttons.Start, state.Buttons.Back); displayGamepadInputText.text += string.Format("A: {0} | B: {1} | X: {2} | Y: {3}\n", state.Buttons.A, state.Buttons.B, state.Buttons.X, state.Buttons.Y); displayGamepadInputText.text += string.Format("LeftShoulder: {0} | RightShoulder: {1}\n", state.Buttons.LeftShoulder, state.Buttons.RightShoulder); displayGamepadInputText.text += string.Format("LeftStick: {0} | RightStick: {1}\n", state.Buttons.LeftStick, state.Buttons.RightStick); displayGamepadInputText.text += "\n--- Triggers ---\n"; displayGamepadInputText.text += string.Format("Left Trigger: {0}\nRightTrigger: {1}\n", state.Triggers.Left, state.Triggers.Right); displayGamepadInputText.text += "\n--- D-Pad ---\n"; displayGamepadInputText.text += string.Format("Up: {0} | Right: {1} | Down: {2} | Left: {3}\n", state.DPad.Up, state.DPad.Right, state.DPad.Down, state.DPad.Left); } #else void Start() { displayGamepadInputText.text = "Run this example in a Windows device."; } #endif }
56
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; public class FBWindowsPurchaseManager : MonoBehaviour { public FBWindowsLogsManager Logger; public GameObject ProductGameObject; public Transform CatalogPanelTarnsform; public Transform PurchasesPanelTarnsform; // IN APP PURCHASES CATALOG FUNCTIONS ---------------------------------------------------------------------------------------------------------- public void GetCatalogButton() { if (FB.IsLoggedIn) { Logger.DebugLog("GetCatalog"); FB.GetCatalog(ProcessGetCatalog); } else { Logger.DebugWarningLog("Login First"); } } private void ProcessGetCatalog(ICatalogResult result) { foreach (Transform child in CatalogPanelTarnsform) { Destroy(child.gameObject); } if (FB.IsLoggedIn) { Logger.DebugLog("Processing Catalog"); if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { foreach (Product item in result.Products) { string itemInfo = item.Title + "\n"; itemInfo += item.Description + "\n"; itemInfo += item.Price; GameObject newProduct = Instantiate(ProductGameObject, CatalogPanelTarnsform); newProduct.GetComponentInChildren<Text>().text = itemInfo; newProduct.GetComponentInChildren<Button>().onClick.AddListener(() => FB.Purchase(item.ProductID, ProcessPurchase, "FB_PayLoad")); if (item.ImageURI != "") { StartCoroutine(LoadPictureFromUrl(item.ImageURI, newProduct.GetComponentInChildren<RawImage>())); } } } } else { Logger.DebugWarningLog("Login First"); } } IEnumerator LoadPictureFromUrl(string url, RawImage itemImage) { Texture2D UserPicture = new Texture2D(32, 32); WWW www = new WWW(url); yield return www; www.LoadImageIntoTexture(UserPicture); www.Dispose(); www = null; itemImage.texture = UserPicture; } private void ProcessPurchase(IPurchaseResult result) { Logger.DebugLog("Purchase result"); if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("Product Purchased: " + result.Purchase.ProductID); Logger.DebugLog("----------------------------------"); Logger.DebugLog("ProductID: " + result.Purchase.ProductID); Logger.DebugLog("IsConsumed: " + result.Purchase.IsConsumed); Logger.DebugLog("DeveloperPayload: " + result.Purchase.DeveloperPayload); Logger.DebugLog("PaymentID: " + result.Purchase.PaymentID); Logger.DebugLog("PaymentActionType: " + result.Purchase.PaymentActionType); Logger.DebugLog("PurchasePlatform: " + result.Purchase.PurchasePlatform); Logger.DebugLog("PurchasePrice.Amount: " + result.Purchase.PurchasePrice.Amount); Logger.DebugLog("PurchasePrice.Currency: " + result.Purchase.PurchasePrice.Currency); Logger.DebugLog("PurchaseTime: " + result.Purchase.PurchaseTime); Logger.DebugLog("PurchaseToken: " + result.Purchase.PurchaseToken); Logger.DebugLog("SignedRequest: " + result.Purchase.SignedRequest); Logger.DebugLog("----------------------------------"); } GetPurchases(); } // IN APP PURCHASES PURCHASES FUNCTIONS ---------------------------------------------------------------------------------------------------------- public void GetPurchases() { Logger.DebugLog("Getting purchases..."); FB.GetPurchases(processPurchases); } private void processPurchases(IPurchasesResult result) { foreach (Transform child in PurchasesPanelTarnsform) { Destroy(child.gameObject); } if (FB.IsLoggedIn) { Logger.DebugLog("Processing Purchases..."); if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { if (result.Purchases != null) { foreach (Purchase item in result.Purchases) { string itemInfo = item.ProductID + "\n"; itemInfo += item.PurchasePlatform + "\n"; itemInfo += item.PurchaseToken; GameObject newProduct = Instantiate(ProductGameObject, PurchasesPanelTarnsform); newProduct.GetComponentInChildren<Text>().text = itemInfo; newProduct.GetComponentInChildren<Button>().onClick.AddListener(() => { FB.ConsumePurchase(item.PurchaseToken, delegate (IConsumePurchaseResult consumeResult) { if (consumeResult.Error != null) { Logger.DebugErrorLog(consumeResult.Error); } else { Logger.DebugLog("Product consumed correctly! ProductID:" + item.ProductID); } GetPurchases(); }); }); } } else { Logger.DebugLog("No purchases"); } } } else { Logger.DebugWarningLog("Login First"); } } }
192
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using Facebook.Unity; using System; using UnityEngine; using UnityEngine.UI; public class FBWindowsReferralsManager : MonoBehaviour { public FBWindowsLogsManager Logger; public InputField Payload; public InputField ReferralLinks; private string _referral_example_payload = "{\"worldID\": \"vxrvgq7d8\",\"giftID\": \"sword_gmewvn3qe8\"}"; private void OnEnable() { Payload.text = _referral_example_payload; } public void CreateReferral() { Logger.DebugLog("Creating Referral link ..."); FB.Windows.CreateReferral(Payload.text, CallbackReferralsCreate); } private void CallbackReferralsCreate(IReferralsCreateResult result) { if (result.Error != null) { Logger.DebugErrorLog("Error Debug print call: " + result.RawResult); Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("Referral raw result: " + result.Raw); Logger.DebugLog("Referral link: " + result.ReferralLink); ReferralLinks.text = result.ReferralLink; } } public void GetDataReferral() { Logger.DebugLog("Getting Referral data ..."); FB.Windows.GetDataReferral(CallbackReferralsGetData); } private void CallbackReferralsGetData(IReferralsGetDataResult result) { if (result.Error != null) { Logger.DebugErrorLog("Error Debug print call: " + result.RawResult); Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("Referral raw result: " + result.Raw); Logger.DebugLog("Referral payload: " + result.Payload); } } }
81
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; using Facebook.MiniJSON; using System; using System.IO; public class FBWindowsShareManager : MonoBehaviour { public FBWindowsLogsManager Logger; public InputField Caption; public InputField ImageFile; public InputField VideoFile; public InputField TravelID; public Toggle ShouldShowDialog; public Button ImageUploadButton; public Button VideoUploadButton; public void Button_UploadImage() { string imagePath = Path.GetFullPath(Application.streamingAssetsPath + "/" + ImageFile.text); ImageUploadButton.interactable = false; Logger.DebugLog("Uploading image file [" + imagePath + "] to media library"); FB.UploadImageToMediaLibrary(Caption.text, new Uri(imagePath), ShouldShowDialog.isOn, TravelID.text, CallbackUploadImage); } public void Button_UploadVideo() { string videoPath = Path.GetFullPath(Application.streamingAssetsPath + "/" + VideoFile.text); VideoUploadButton.interactable = false; Logger.DebugLog("Uploading video file [" + videoPath + "] to media library"); FB.UploadVideoToMediaLibrary(Caption.text, new Uri(videoPath), ShouldShowDialog.isOn, TravelID.text, CallbackUploadVideo); } private void CallbackUploadImage(IMediaUploadResult result) { ImageUploadButton.interactable = true; if (result.Error != null) { Logger.DebugErrorLog("Image upload error: " + result.RawResult); Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("Image uploaded. ID: " + result.MediaId); } } private void CallbackUploadVideo(IMediaUploadResult result) { VideoUploadButton.interactable = true; if (result.Error != null) { Logger.DebugErrorLog("Video upload error: " + result.RawResult); Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("Video uploaded. ID: " + result.MediaId); } } }
87
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using Facebook.Unity; using System; using UnityEngine; using UnityEngine.UI; public class FBWindowsSoftKeyboardManager : MonoBehaviour { public FBWindowsLogsManager Logger; public void SetSoftKeyboardOpenButton() { Logger.DebugLog("Setting Soft Keyboard Open"); FB.Windows.SetSoftKeyboardOpen(true, CallbackSetSoftKeyboardOpen); } private void CallbackSetSoftKeyboardOpen(ISoftKeyboardOpenResult result) { if (result.Error != null) { Logger.DebugErrorLog("Error setting Soft Keyboard Open: " + result.RawResult); Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("Soft Keyboard Open set: " + result.Success); } } }
49
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.UI; using Facebook.Unity; using Facebook.MiniJSON; public class FBWindowsTournamentsManager : MonoBehaviour { public FBWindowsLogsManager Logger; public InputField Title; public InputField Image; public Dropdown SortOrder; public Dropdown ScoreFormat; public InputField Data; public InputField InitialScore; public InputField Score; public InputField ShareData; private Dictionary<string, string> ConvertDataToDict(string UTF8String) { Encoding unicode = Encoding.Unicode; var unicodeData = Encoding.Convert(Encoding.UTF8, unicode, Encoding.UTF8.GetBytes(UTF8String)); char[] unicodeDataChars = new char[unicode.GetCharCount(unicodeData, 0, unicodeData.Length)]; Encoding.Unicode.GetChars(unicodeData, 0, unicodeData.Length, unicodeDataChars, 0); var data = Json.Deserialize(new string(unicodeDataChars)) as Dictionary<string, object>; Dictionary<string, string> result = new Dictionary<string, string>(); if (data != null) { foreach (KeyValuePair<string, object> keyValuePair in data) { result.Add(keyValuePair.Key, keyValuePair.Value == null ? "" : keyValuePair.Value.ToString()); } } else { Debug.LogError("Wrong Data Json"); } return result; } public void Button_CreateTournament() { FB.CreateTournament( int.Parse(InitialScore.text), Title.text, Image.text, SortOrder.options[SortOrder.value].text, ScoreFormat.options[ScoreFormat.value].text, ConvertDataToDict(Data.text), CallbackCreateTournament ); } private void CallbackCreateTournament(ITournamentResult result) { if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog(result.RawResult); } } public void Button_PostSessionScore() { FB.PostSessionScore(int.Parse(Score.text), CallbackPostSessionScore); } private void CallbackPostSessionScore(ISessionScoreResult result) { if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog(result.RawResult); } } public void Button_PostTournamentScore() { FB.PostTournamentScore(int.Parse(Score.text), CallbackPostTournamentScore); } private void CallbackPostTournamentScore(ITournamentScoreResult result) { if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog(result.RawResult); } } public void Button_ShareTournament() { FB.ShareTournament(int.Parse(Score.text), ConvertDataToDict(ShareData.text), CallbackShareTournament); } private void CallbackShareTournament(ITournamentScoreResult result) { if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog(result.RawResult); } } public void Button_GetTournament() { FB.GetTournament(CallbackGetTournament); } private void CallbackGetTournament(ITournamentResult result) { if (result.Error != null) { Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog(result.RawResult); } } }
159
facebook-sdk-for-unity
facebook
C#
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using Facebook.Unity; using System; using UnityEngine; using UnityEngine.UI; public class FBWindowsVirtualGamepadManager : MonoBehaviour { public FBWindowsLogsManager Logger; public InputField NewVirtualGamepadLayout; public void SetVirtualGamepadLayout() { Logger.DebugLog("Setting Virtual Gamepad Layout to " + NewVirtualGamepadLayout.text); FB.Windows.SetVirtualGamepadLayout(NewVirtualGamepadLayout.text, CallbackSetVirtualGamepadLayout); } private void CallbackSetVirtualGamepadLayout(IVirtualGamepadLayoutResult result) { if (result.Error != null) { Logger.DebugErrorLog("Error setting Virtual Gamepad Layout: " + result.RawResult); Logger.DebugErrorLog(result.Error); } else { Logger.DebugLog("Virtual Gamepad Layout set: " + result.Success); } } }
50
SPIRV-Headers
facebook
C#
// Copyright (c) 2014-2018 The Khronos Group Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and/or associated documentation files (the "Materials"), // to deal in the Materials without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Materials, and to permit persons to whom the // Materials are furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Materials. // // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS // STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND // HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ // // THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS // IN THE MATERIALS. // This header is automatically generated by the same tool that creates // the Binary Section of the SPIR-V specification. // Enumeration tokens for SPIR-V, in various styles: // C, C++, C++11, JSON, Lua, Python, C# // // - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL // - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL // - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL // - Lua will use tables, e.g.: spv.SourceLanguage.GLSL // - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] // - C# will use enum classes in the Specification class located in the "Spv" namespace, e.g.: Spv.Specification.SourceLanguage.GLSL // // Some tokens act like mask values, which can be OR'd together, // while others are mutually exclusive. The mask-like ones have // "Mask" in their name, and a parallel enum that has the shift // amount (1 << x) for each corresponding enumerant. namespace Spv { public static class Specification { public const uint MagicNumber = 0x07230203; public const uint Version = 0x00010000; public const uint Revision = 12; public const uint OpCodeMask = 0xffff; public const uint WordCountShift = 16; public enum SourceLanguage { Unknown = 0, ESSL = 1, GLSL = 2, OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, } public enum ExecutionModel { Vertex = 0, TessellationControl = 1, TessellationEvaluation = 2, Geometry = 3, Fragment = 4, GLCompute = 5, Kernel = 6, } public enum AddressingModel { Logical = 0, Physical32 = 1, Physical64 = 2, } public enum MemoryModel { Simple = 0, GLSL450 = 1, OpenCL = 2, } public enum ExecutionMode { Invocations = 0, SpacingEqual = 1, SpacingFractionalEven = 2, SpacingFractionalOdd = 3, VertexOrderCw = 4, VertexOrderCcw = 5, PixelCenterInteger = 6, OriginUpperLeft = 7, OriginLowerLeft = 8, EarlyFragmentTests = 9, PointMode = 10, Xfb = 11, DepthReplacing = 12, DepthGreater = 14, DepthLess = 15, DepthUnchanged = 16, LocalSize = 17, LocalSizeHint = 18, InputPoints = 19, InputLines = 20, InputLinesAdjacency = 21, Triangles = 22, InputTrianglesAdjacency = 23, Quads = 24, Isolines = 25, OutputVertices = 26, OutputPoints = 27, OutputLineStrip = 28, OutputTriangleStrip = 29, VecTypeHint = 30, ContractionOff = 31, PostDepthCoverage = 4446, StencilRefReplacingEXT = 5027, } public enum StorageClass { UniformConstant = 0, Input = 1, Uniform = 2, Output = 3, Workgroup = 4, CrossWorkgroup = 5, Private = 6, Function = 7, Generic = 8, PushConstant = 9, AtomicCounter = 10, Image = 11, StorageBuffer = 12, } public enum Dim { Dim1D = 0, Dim2D = 1, Dim3D = 2, Cube = 3, Rect = 4, Buffer = 5, SubpassData = 6, } public enum SamplerAddressingMode { None = 0, ClampToEdge = 1, Clamp = 2, Repeat = 3, RepeatMirrored = 4, } public enum SamplerFilterMode { Nearest = 0, Linear = 1, } public enum ImageFormat { Unknown = 0, Rgba32f = 1, Rgba16f = 2, R32f = 3, Rgba8 = 4, Rgba8Snorm = 5, Rg32f = 6, Rg16f = 7, R11fG11fB10f = 8, R16f = 9, Rgba16 = 10, Rgb10A2 = 11, Rg16 = 12, Rg8 = 13, R16 = 14, R8 = 15, Rgba16Snorm = 16, Rg16Snorm = 17, Rg8Snorm = 18, R16Snorm = 19, R8Snorm = 20, Rgba32i = 21, Rgba16i = 22, Rgba8i = 23, R32i = 24, Rg32i = 25, Rg16i = 26, Rg8i = 27, R16i = 28, R8i = 29, Rgba32ui = 30, Rgba16ui = 31, Rgba8ui = 32, R32ui = 33, Rgb10a2ui = 34, Rg32ui = 35, Rg16ui = 36, Rg8ui = 37, R16ui = 38, R8ui = 39, } public enum ImageChannelOrder { R = 0, A = 1, RG = 2, RA = 3, RGB = 4, RGBA = 5, BGRA = 6, ARGB = 7, Intensity = 8, Luminance = 9, Rx = 10, RGx = 11, RGBx = 12, Depth = 13, DepthStencil = 14, sRGB = 15, sRGBx = 16, sRGBA = 17, sBGRA = 18, ABGR = 19, } public enum ImageChannelDataType { SnormInt8 = 0, SnormInt16 = 1, UnormInt8 = 2, UnormInt16 = 3, UnormShort565 = 4, UnormShort555 = 5, UnormInt101010 = 6, SignedInt8 = 7, SignedInt16 = 8, SignedInt32 = 9, UnsignedInt8 = 10, UnsignedInt16 = 11, UnsignedInt32 = 12, HalfFloat = 13, Float = 14, UnormInt24 = 15, UnormInt101010_2 = 16, } public enum ImageOperandsShift { Bias = 0, Lod = 1, Grad = 2, ConstOffset = 3, Offset = 4, ConstOffsets = 5, Sample = 6, MinLod = 7, } public enum ImageOperandsMask { MaskNone = 0, Bias = 0x00000001, Lod = 0x00000002, Grad = 0x00000004, ConstOffset = 0x00000008, Offset = 0x00000010, ConstOffsets = 0x00000020, Sample = 0x00000040, MinLod = 0x00000080, } public enum FPFastMathModeShift { NotNaN = 0, NotInf = 1, NSZ = 2, AllowRecip = 3, Fast = 4, } public enum FPFastMathModeMask { MaskNone = 0, NotNaN = 0x00000001, NotInf = 0x00000002, NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, } public enum FPRoundingMode { RTE = 0, RTZ = 1, RTP = 2, RTN = 3, } public enum LinkageType { Export = 0, Import = 1, } public enum AccessQualifier { ReadOnly = 0, WriteOnly = 1, ReadWrite = 2, } public enum FunctionParameterAttribute { Zext = 0, Sext = 1, ByVal = 2, Sret = 3, NoAlias = 4, NoCapture = 5, NoWrite = 6, NoReadWrite = 7, } public enum Decoration { RelaxedPrecision = 0, SpecId = 1, Block = 2, BufferBlock = 3, RowMajor = 4, ColMajor = 5, ArrayStride = 6, MatrixStride = 7, GLSLShared = 8, GLSLPacked = 9, CPacked = 10, BuiltIn = 11, NoPerspective = 13, Flat = 14, Patch = 15, Centroid = 16, Sample = 17, Invariant = 18, Restrict = 19, Aliased = 20, Volatile = 21, Constant = 22, Coherent = 23, NonWritable = 24, NonReadable = 25, Uniform = 26, SaturatedConversion = 28, Stream = 29, Location = 30, Component = 31, Index = 32, Binding = 33, DescriptorSet = 34, Offset = 35, XfbBuffer = 36, XfbStride = 37, FuncParamAttr = 38, FPRoundingMode = 39, FPFastMathMode = 40, LinkageAttributes = 41, NoContraction = 42, InputAttachmentIndex = 43, Alignment = 44, ExplicitInterpAMD = 4999, OverrideCoverageNV = 5248, PassthroughNV = 5250, ViewportRelativeNV = 5252, SecondaryViewportRelativeNV = 5256, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, } public enum BuiltIn { Position = 0, PointSize = 1, ClipDistance = 3, CullDistance = 4, VertexId = 5, InstanceId = 6, PrimitiveId = 7, InvocationId = 8, Layer = 9, ViewportIndex = 10, TessLevelOuter = 11, TessLevelInner = 12, TessCoord = 13, PatchVertices = 14, FragCoord = 15, PointCoord = 16, FrontFacing = 17, SampleId = 18, SamplePosition = 19, SampleMask = 20, FragDepth = 22, HelperInvocation = 23, NumWorkgroups = 24, WorkgroupSize = 25, WorkgroupId = 26, LocalInvocationId = 27, GlobalInvocationId = 28, LocalInvocationIndex = 29, WorkDim = 30, GlobalSize = 31, EnqueuedWorkgroupSize = 32, GlobalOffset = 33, GlobalLinearId = 34, SubgroupSize = 36, SubgroupMaxSize = 37, NumSubgroups = 38, NumEnqueuedSubgroups = 39, SubgroupId = 40, SubgroupLocalInvocationId = 41, VertexIndex = 42, InstanceIndex = 43, SubgroupEqMaskKHR = 4416, SubgroupGeMaskKHR = 4417, SubgroupGtMaskKHR = 4418, SubgroupLeMaskKHR = 4419, SubgroupLtMaskKHR = 4420, BaseVertex = 4424, BaseInstance = 4425, DrawIndex = 4426, DeviceIndex = 4438, ViewIndex = 4440, BaryCoordNoPerspAMD = 4992, BaryCoordNoPerspCentroidAMD = 4993, BaryCoordNoPerspSampleAMD = 4994, BaryCoordSmoothAMD = 4995, BaryCoordSmoothCentroidAMD = 4996, BaryCoordSmoothSampleAMD = 4997, BaryCoordPullModelAMD = 4998, FragStencilRefEXT = 5014, ViewportMaskNV = 5253, SecondaryPositionNV = 5257, SecondaryViewportMaskNV = 5258, PositionPerViewNV = 5261, ViewportMaskPerViewNV = 5262, } public enum SelectionControlShift { Flatten = 0, DontFlatten = 1, } public enum SelectionControlMask { MaskNone = 0, Flatten = 0x00000001, DontFlatten = 0x00000002, } public enum LoopControlShift { Unroll = 0, DontUnroll = 1, } public enum LoopControlMask { MaskNone = 0, Unroll = 0x00000001, DontUnroll = 0x00000002, } public enum FunctionControlShift { Inline = 0, DontInline = 1, Pure = 2, Const = 3, } public enum FunctionControlMask { MaskNone = 0, Inline = 0x00000001, DontInline = 0x00000002, Pure = 0x00000004, Const = 0x00000008, } public enum MemorySemanticsShift { Acquire = 1, Release = 2, AcquireRelease = 3, SequentiallyConsistent = 4, UniformMemory = 6, SubgroupMemory = 7, WorkgroupMemory = 8, CrossWorkgroupMemory = 9, AtomicCounterMemory = 10, ImageMemory = 11, } public enum MemorySemanticsMask { MaskNone = 0, Acquire = 0x00000002, Release = 0x00000004, AcquireRelease = 0x00000008, SequentiallyConsistent = 0x00000010, UniformMemory = 0x00000040, SubgroupMemory = 0x00000080, WorkgroupMemory = 0x00000100, CrossWorkgroupMemory = 0x00000200, AtomicCounterMemory = 0x00000400, ImageMemory = 0x00000800, } public enum MemoryAccessShift { Volatile = 0, Aligned = 1, Nontemporal = 2, } public enum MemoryAccessMask { MaskNone = 0, Volatile = 0x00000001, Aligned = 0x00000002, Nontemporal = 0x00000004, } public enum Scope { CrossDevice = 0, Device = 1, Workgroup = 2, Subgroup = 3, Invocation = 4, } public enum GroupOperation { Reduce = 0, InclusiveScan = 1, ExclusiveScan = 2, } public enum KernelEnqueueFlags { NoWait = 0, WaitKernel = 1, WaitWorkGroup = 2, } public enum KernelProfilingInfoShift { CmdExecTime = 0, } public enum KernelProfilingInfoMask { MaskNone = 0, CmdExecTime = 0x00000001, } public enum Capability { Matrix = 0, Shader = 1, Geometry = 2, Tessellation = 3, Addresses = 4, Linkage = 5, Kernel = 6, Vector16 = 7, Float16Buffer = 8, Float16 = 9, Float64 = 10, Int64 = 11, Int64Atomics = 12, ImageBasic = 13, ImageReadWrite = 14, ImageMipmap = 15, Pipes = 17, Groups = 18, DeviceEnqueue = 19, LiteralSampler = 20, AtomicStorage = 21, Int16 = 22, TessellationPointSize = 23, GeometryPointSize = 24, ImageGatherExtended = 25, StorageImageMultisample = 27, UniformBufferArrayDynamicIndexing = 28, SampledImageArrayDynamicIndexing = 29, StorageBufferArrayDynamicIndexing = 30, StorageImageArrayDynamicIndexing = 31, ClipDistance = 32, CullDistance = 33, ImageCubeArray = 34, SampleRateShading = 35, ImageRect = 36, SampledRect = 37, GenericPointer = 38, Int8 = 39, InputAttachment = 40, SparseResidency = 41, MinLod = 42, Sampled1D = 43, Image1D = 44, SampledCubeArray = 45, SampledBuffer = 46, ImageBuffer = 47, ImageMSArray = 48, StorageImageExtendedFormats = 49, ImageQuery = 50, DerivativeControl = 51, InterpolationFunction = 52, TransformFeedback = 53, GeometryStreams = 54, StorageImageReadWithoutFormat = 55, StorageImageWriteWithoutFormat = 56, MultiViewport = 57, SubgroupBallotKHR = 4423, DrawParameters = 4427, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, StorageUniform16 = 4434, UniformAndStorageBuffer16BitAccess = 4434, StoragePushConstant16 = 4435, StorageInputOutput16 = 4436, DeviceGroup = 4437, MultiView = 4439, VariablePointersStorageBuffer = 4441, VariablePointers = 4442, AtomicStorageOps = 4445, SampleMaskPostDepthCoverage = 4447, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, StencilExportEXT = 5013, ImageReadWriteLodAMD = 5015, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, ShaderViewportIndexLayerNV = 5254, ShaderViewportMaskNV = 5255, ShaderStereoViewNV = 5259, PerViewAttributesNV = 5260, SubgroupShuffleINTEL = 5568, SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, } public enum Op { OpNop = 0, OpUndef = 1, OpSourceContinued = 2, OpSource = 3, OpSourceExtension = 4, OpName = 5, OpMemberName = 6, OpString = 7, OpLine = 8, OpExtension = 10, OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, OpTypeVector = 23, OpTypeMatrix = 24, OpTypeImage = 25, OpTypeSampler = 26, OpTypeSampledImage = 27, OpTypeArray = 28, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypeOpaque = 31, OpTypePointer = 32, OpTypeFunction = 33, OpTypeEvent = 34, OpTypeDeviceEvent = 35, OpTypeReserveId = 36, OpTypeQueue = 37, OpTypePipe = 38, OpTypeForwardPointer = 39, OpConstantTrue = 41, OpConstantFalse = 42, OpConstant = 43, OpConstantComposite = 44, OpConstantSampler = 45, OpConstantNull = 46, OpSpecConstantTrue = 48, OpSpecConstantFalse = 49, OpSpecConstant = 50, OpSpecConstantComposite = 51, OpSpecConstantOp = 52, OpFunction = 54, OpFunctionParameter = 55, OpFunctionEnd = 56, OpFunctionCall = 57, OpVariable = 59, OpImageTexelPointer = 60, OpLoad = 61, OpStore = 62, OpCopyMemory = 63, OpCopyMemorySized = 64, OpAccessChain = 65, OpInBoundsAccessChain = 66, OpPtrAccessChain = 67, OpArrayLength = 68, OpGenericPtrMemSemantics = 69, OpInBoundsPtrAccessChain = 70, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, OpGroupDecorate = 74, OpGroupMemberDecorate = 75, OpVectorExtractDynamic = 77, OpVectorInsertDynamic = 78, OpVectorShuffle = 79, OpCompositeConstruct = 80, OpCompositeExtract = 81, OpCompositeInsert = 82, OpCopyObject = 83, OpTranspose = 84, OpSampledImage = 86, OpImageSampleImplicitLod = 87, OpImageSampleExplicitLod = 88, OpImageSampleDrefImplicitLod = 89, OpImageSampleDrefExplicitLod = 90, OpImageSampleProjImplicitLod = 91, OpImageSampleProjExplicitLod = 92, OpImageSampleProjDrefImplicitLod = 93, OpImageSampleProjDrefExplicitLod = 94, OpImageFetch = 95, OpImageGather = 96, OpImageDrefGather = 97, OpImageRead = 98, OpImageWrite = 99, OpImage = 100, OpImageQueryFormat = 101, OpImageQueryOrder = 102, OpImageQuerySizeLod = 103, OpImageQuerySize = 104, OpImageQueryLod = 105, OpImageQueryLevels = 106, OpImageQuerySamples = 107, OpConvertFToU = 109, OpConvertFToS = 110, OpConvertSToF = 111, OpConvertUToF = 112, OpUConvert = 113, OpSConvert = 114, OpFConvert = 115, OpQuantizeToF16 = 116, OpConvertPtrToU = 117, OpSatConvertSToU = 118, OpSatConvertUToS = 119, OpConvertUToPtr = 120, OpPtrCastToGeneric = 121, OpGenericCastToPtr = 122, OpGenericCastToPtrExplicit = 123, OpBitcast = 124, OpSNegate = 126, OpFNegate = 127, OpIAdd = 128, OpFAdd = 129, OpISub = 130, OpFSub = 131, OpIMul = 132, OpFMul = 133, OpUDiv = 134, OpSDiv = 135, OpFDiv = 136, OpUMod = 137, OpSRem = 138, OpSMod = 139, OpFRem = 140, OpFMod = 141, OpVectorTimesScalar = 142, OpMatrixTimesScalar = 143, OpVectorTimesMatrix = 144, OpMatrixTimesVector = 145, OpMatrixTimesMatrix = 146, OpOuterProduct = 147, OpDot = 148, OpIAddCarry = 149, OpISubBorrow = 150, OpUMulExtended = 151, OpSMulExtended = 152, OpAny = 154, OpAll = 155, OpIsNan = 156, OpIsInf = 157, OpIsFinite = 158, OpIsNormal = 159, OpSignBitSet = 160, OpLessOrGreater = 161, OpOrdered = 162, OpUnordered = 163, OpLogicalEqual = 164, OpLogicalNotEqual = 165, OpLogicalOr = 166, OpLogicalAnd = 167, OpLogicalNot = 168, OpSelect = 169, OpIEqual = 170, OpINotEqual = 171, OpUGreaterThan = 172, OpSGreaterThan = 173, OpUGreaterThanEqual = 174, OpSGreaterThanEqual = 175, OpULessThan = 176, OpSLessThan = 177, OpULessThanEqual = 178, OpSLessThanEqual = 179, OpFOrdEqual = 180, OpFUnordEqual = 181, OpFOrdNotEqual = 182, OpFUnordNotEqual = 183, OpFOrdLessThan = 184, OpFUnordLessThan = 185, OpFOrdGreaterThan = 186, OpFUnordGreaterThan = 187, OpFOrdLessThanEqual = 188, OpFUnordLessThanEqual = 189, OpFOrdGreaterThanEqual = 190, OpFUnordGreaterThanEqual = 191, OpShiftRightLogical = 194, OpShiftRightArithmetic = 195, OpShiftLeftLogical = 196, OpBitwiseOr = 197, OpBitwiseXor = 198, OpBitwiseAnd = 199, OpNot = 200, OpBitFieldInsert = 201, OpBitFieldSExtract = 202, OpBitFieldUExtract = 203, OpBitReverse = 204, OpBitCount = 205, OpDPdx = 207, OpDPdy = 208, OpFwidth = 209, OpDPdxFine = 210, OpDPdyFine = 211, OpFwidthFine = 212, OpDPdxCoarse = 213, OpDPdyCoarse = 214, OpFwidthCoarse = 215, OpEmitVertex = 218, OpEndPrimitive = 219, OpEmitStreamVertex = 220, OpEndStreamPrimitive = 221, OpControlBarrier = 224, OpMemoryBarrier = 225, OpAtomicLoad = 227, OpAtomicStore = 228, OpAtomicExchange = 229, OpAtomicCompareExchange = 230, OpAtomicCompareExchangeWeak = 231, OpAtomicIIncrement = 232, OpAtomicIDecrement = 233, OpAtomicIAdd = 234, OpAtomicISub = 235, OpAtomicSMin = 236, OpAtomicUMin = 237, OpAtomicSMax = 238, OpAtomicUMax = 239, OpAtomicAnd = 240, OpAtomicOr = 241, OpAtomicXor = 242, OpPhi = 245, OpLoopMerge = 246, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, OpBranchConditional = 250, OpSwitch = 251, OpKill = 252, OpReturn = 253, OpReturnValue = 254, OpUnreachable = 255, OpLifetimeStart = 256, OpLifetimeStop = 257, OpGroupAsyncCopy = 259, OpGroupWaitEvents = 260, OpGroupAll = 261, OpGroupAny = 262, OpGroupBroadcast = 263, OpGroupIAdd = 264, OpGroupFAdd = 265, OpGroupFMin = 266, OpGroupUMin = 267, OpGroupSMin = 268, OpGroupFMax = 269, OpGroupUMax = 270, OpGroupSMax = 271, OpReadPipe = 274, OpWritePipe = 275, OpReservedReadPipe = 276, OpReservedWritePipe = 277, OpReserveReadPipePackets = 278, OpReserveWritePipePackets = 279, OpCommitReadPipe = 280, OpCommitWritePipe = 281, OpIsValidReserveId = 282, OpGetNumPipePackets = 283, OpGetMaxPipePackets = 284, OpGroupReserveReadPipePackets = 285, OpGroupReserveWritePipePackets = 286, OpGroupCommitReadPipe = 287, OpGroupCommitWritePipe = 288, OpEnqueueMarker = 291, OpEnqueueKernel = 292, OpGetKernelNDrangeSubGroupCount = 293, OpGetKernelNDrangeMaxSubGroupSize = 294, OpGetKernelWorkGroupSize = 295, OpGetKernelPreferredWorkGroupSizeMultiple = 296, OpRetainEvent = 297, OpReleaseEvent = 298, OpCreateUserEvent = 299, OpIsValidEvent = 300, OpSetUserEventStatus = 301, OpCaptureEventProfilingInfo = 302, OpGetDefaultQueue = 303, OpBuildNDRange = 304, OpImageSparseSampleImplicitLod = 305, OpImageSparseSampleExplicitLod = 306, OpImageSparseSampleDrefImplicitLod = 307, OpImageSparseSampleDrefExplicitLod = 308, OpImageSparseSampleProjImplicitLod = 309, OpImageSparseSampleProjExplicitLod = 310, OpImageSparseSampleProjDrefImplicitLod = 311, OpImageSparseSampleProjDrefExplicitLod = 312, OpImageSparseFetch = 313, OpImageSparseGather = 314, OpImageSparseDrefGather = 315, OpImageSparseTexelsResident = 316, OpNoLine = 317, OpAtomicFlagTestAndSet = 318, OpAtomicFlagClear = 319, OpImageSparseRead = 320, OpDecorateId = 332, OpSubgroupBallotKHR = 4421, OpSubgroupFirstInvocationKHR = 4422, OpSubgroupAllKHR = 4428, OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, OpGroupIAddNonUniformAMD = 5000, OpGroupFAddNonUniformAMD = 5001, OpGroupFMinNonUniformAMD = 5002, OpGroupUMinNonUniformAMD = 5003, OpGroupSMinNonUniformAMD = 5004, OpGroupFMaxNonUniformAMD = 5005, OpGroupUMaxNonUniformAMD = 5006, OpGroupSMaxNonUniformAMD = 5007, OpFragmentMaskFetchAMD = 5011, OpFragmentFetchAMD = 5012, OpSubgroupShuffleINTEL = 5571, OpSubgroupShuffleDownINTEL = 5572, OpSubgroupShuffleUpINTEL = 5573, OpSubgroupShuffleXorINTEL = 5574, OpSubgroupBlockReadINTEL = 5575, OpSubgroupBlockWriteINTEL = 5576, OpSubgroupImageBlockReadINTEL = 5577, OpSubgroupImageBlockWriteINTEL = 5578, OpDecorateStringGOOGLE = 5632, OpMemberDecorateStringGOOGLE = 5633, } } }
994
SPIRV-Headers
facebook
C#
// Copyright (c) 2014-2018 The Khronos Group Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and/or associated documentation files (the "Materials"), // to deal in the Materials without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Materials, and to permit persons to whom the // Materials are furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Materials. // // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS // STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND // HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ // // THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS // IN THE MATERIALS. // This header is automatically generated by the same tool that creates // the Binary Section of the SPIR-V specification. // Enumeration tokens for SPIR-V, in various styles: // C, C++, C++11, JSON, Lua, Python, C# // // - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL // - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL // - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL // - Lua will use tables, e.g.: spv.SourceLanguage.GLSL // - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] // - C# will use enum classes in the Specification class located in the "Spv" namespace, e.g.: Spv.Specification.SourceLanguage.GLSL // // Some tokens act like mask values, which can be OR'd together, // while others are mutually exclusive. The mask-like ones have // "Mask" in their name, and a parallel enum that has the shift // amount (1 << x) for each corresponding enumerant. namespace Spv { public static class Specification { public const uint MagicNumber = 0x07230203; public const uint Version = 0x00010100; public const uint Revision = 8; public const uint OpCodeMask = 0xffff; public const uint WordCountShift = 16; public enum SourceLanguage { Unknown = 0, ESSL = 1, GLSL = 2, OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, } public enum ExecutionModel { Vertex = 0, TessellationControl = 1, TessellationEvaluation = 2, Geometry = 3, Fragment = 4, GLCompute = 5, Kernel = 6, } public enum AddressingModel { Logical = 0, Physical32 = 1, Physical64 = 2, } public enum MemoryModel { Simple = 0, GLSL450 = 1, OpenCL = 2, } public enum ExecutionMode { Invocations = 0, SpacingEqual = 1, SpacingFractionalEven = 2, SpacingFractionalOdd = 3, VertexOrderCw = 4, VertexOrderCcw = 5, PixelCenterInteger = 6, OriginUpperLeft = 7, OriginLowerLeft = 8, EarlyFragmentTests = 9, PointMode = 10, Xfb = 11, DepthReplacing = 12, DepthGreater = 14, DepthLess = 15, DepthUnchanged = 16, LocalSize = 17, LocalSizeHint = 18, InputPoints = 19, InputLines = 20, InputLinesAdjacency = 21, Triangles = 22, InputTrianglesAdjacency = 23, Quads = 24, Isolines = 25, OutputVertices = 26, OutputPoints = 27, OutputLineStrip = 28, OutputTriangleStrip = 29, VecTypeHint = 30, ContractionOff = 31, Initializer = 33, Finalizer = 34, SubgroupSize = 35, SubgroupsPerWorkgroup = 36, PostDepthCoverage = 4446, StencilRefReplacingEXT = 5027, } public enum StorageClass { UniformConstant = 0, Input = 1, Uniform = 2, Output = 3, Workgroup = 4, CrossWorkgroup = 5, Private = 6, Function = 7, Generic = 8, PushConstant = 9, AtomicCounter = 10, Image = 11, StorageBuffer = 12, } public enum Dim { Dim1D = 0, Dim2D = 1, Dim3D = 2, Cube = 3, Rect = 4, Buffer = 5, SubpassData = 6, } public enum SamplerAddressingMode { None = 0, ClampToEdge = 1, Clamp = 2, Repeat = 3, RepeatMirrored = 4, } public enum SamplerFilterMode { Nearest = 0, Linear = 1, } public enum ImageFormat { Unknown = 0, Rgba32f = 1, Rgba16f = 2, R32f = 3, Rgba8 = 4, Rgba8Snorm = 5, Rg32f = 6, Rg16f = 7, R11fG11fB10f = 8, R16f = 9, Rgba16 = 10, Rgb10A2 = 11, Rg16 = 12, Rg8 = 13, R16 = 14, R8 = 15, Rgba16Snorm = 16, Rg16Snorm = 17, Rg8Snorm = 18, R16Snorm = 19, R8Snorm = 20, Rgba32i = 21, Rgba16i = 22, Rgba8i = 23, R32i = 24, Rg32i = 25, Rg16i = 26, Rg8i = 27, R16i = 28, R8i = 29, Rgba32ui = 30, Rgba16ui = 31, Rgba8ui = 32, R32ui = 33, Rgb10a2ui = 34, Rg32ui = 35, Rg16ui = 36, Rg8ui = 37, R16ui = 38, R8ui = 39, } public enum ImageChannelOrder { R = 0, A = 1, RG = 2, RA = 3, RGB = 4, RGBA = 5, BGRA = 6, ARGB = 7, Intensity = 8, Luminance = 9, Rx = 10, RGx = 11, RGBx = 12, Depth = 13, DepthStencil = 14, sRGB = 15, sRGBx = 16, sRGBA = 17, sBGRA = 18, ABGR = 19, } public enum ImageChannelDataType { SnormInt8 = 0, SnormInt16 = 1, UnormInt8 = 2, UnormInt16 = 3, UnormShort565 = 4, UnormShort555 = 5, UnormInt101010 = 6, SignedInt8 = 7, SignedInt16 = 8, SignedInt32 = 9, UnsignedInt8 = 10, UnsignedInt16 = 11, UnsignedInt32 = 12, HalfFloat = 13, Float = 14, UnormInt24 = 15, UnormInt101010_2 = 16, } public enum ImageOperandsShift { Bias = 0, Lod = 1, Grad = 2, ConstOffset = 3, Offset = 4, ConstOffsets = 5, Sample = 6, MinLod = 7, } public enum ImageOperandsMask { MaskNone = 0, Bias = 0x00000001, Lod = 0x00000002, Grad = 0x00000004, ConstOffset = 0x00000008, Offset = 0x00000010, ConstOffsets = 0x00000020, Sample = 0x00000040, MinLod = 0x00000080, } public enum FPFastMathModeShift { NotNaN = 0, NotInf = 1, NSZ = 2, AllowRecip = 3, Fast = 4, } public enum FPFastMathModeMask { MaskNone = 0, NotNaN = 0x00000001, NotInf = 0x00000002, NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, } public enum FPRoundingMode { RTE = 0, RTZ = 1, RTP = 2, RTN = 3, } public enum LinkageType { Export = 0, Import = 1, } public enum AccessQualifier { ReadOnly = 0, WriteOnly = 1, ReadWrite = 2, } public enum FunctionParameterAttribute { Zext = 0, Sext = 1, ByVal = 2, Sret = 3, NoAlias = 4, NoCapture = 5, NoWrite = 6, NoReadWrite = 7, } public enum Decoration { RelaxedPrecision = 0, SpecId = 1, Block = 2, BufferBlock = 3, RowMajor = 4, ColMajor = 5, ArrayStride = 6, MatrixStride = 7, GLSLShared = 8, GLSLPacked = 9, CPacked = 10, BuiltIn = 11, NoPerspective = 13, Flat = 14, Patch = 15, Centroid = 16, Sample = 17, Invariant = 18, Restrict = 19, Aliased = 20, Volatile = 21, Constant = 22, Coherent = 23, NonWritable = 24, NonReadable = 25, Uniform = 26, SaturatedConversion = 28, Stream = 29, Location = 30, Component = 31, Index = 32, Binding = 33, DescriptorSet = 34, Offset = 35, XfbBuffer = 36, XfbStride = 37, FuncParamAttr = 38, FPRoundingMode = 39, FPFastMathMode = 40, LinkageAttributes = 41, NoContraction = 42, InputAttachmentIndex = 43, Alignment = 44, MaxByteOffset = 45, ExplicitInterpAMD = 4999, OverrideCoverageNV = 5248, PassthroughNV = 5250, ViewportRelativeNV = 5252, SecondaryViewportRelativeNV = 5256, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, } public enum BuiltIn { Position = 0, PointSize = 1, ClipDistance = 3, CullDistance = 4, VertexId = 5, InstanceId = 6, PrimitiveId = 7, InvocationId = 8, Layer = 9, ViewportIndex = 10, TessLevelOuter = 11, TessLevelInner = 12, TessCoord = 13, PatchVertices = 14, FragCoord = 15, PointCoord = 16, FrontFacing = 17, SampleId = 18, SamplePosition = 19, SampleMask = 20, FragDepth = 22, HelperInvocation = 23, NumWorkgroups = 24, WorkgroupSize = 25, WorkgroupId = 26, LocalInvocationId = 27, GlobalInvocationId = 28, LocalInvocationIndex = 29, WorkDim = 30, GlobalSize = 31, EnqueuedWorkgroupSize = 32, GlobalOffset = 33, GlobalLinearId = 34, SubgroupSize = 36, SubgroupMaxSize = 37, NumSubgroups = 38, NumEnqueuedSubgroups = 39, SubgroupId = 40, SubgroupLocalInvocationId = 41, VertexIndex = 42, InstanceIndex = 43, SubgroupEqMaskKHR = 4416, SubgroupGeMaskKHR = 4417, SubgroupGtMaskKHR = 4418, SubgroupLeMaskKHR = 4419, SubgroupLtMaskKHR = 4420, BaseVertex = 4424, BaseInstance = 4425, DrawIndex = 4426, DeviceIndex = 4438, ViewIndex = 4440, BaryCoordNoPerspAMD = 4992, BaryCoordNoPerspCentroidAMD = 4993, BaryCoordNoPerspSampleAMD = 4994, BaryCoordSmoothAMD = 4995, BaryCoordSmoothCentroidAMD = 4996, BaryCoordSmoothSampleAMD = 4997, BaryCoordPullModelAMD = 4998, FragStencilRefEXT = 5014, ViewportMaskNV = 5253, SecondaryPositionNV = 5257, SecondaryViewportMaskNV = 5258, PositionPerViewNV = 5261, ViewportMaskPerViewNV = 5262, } public enum SelectionControlShift { Flatten = 0, DontFlatten = 1, } public enum SelectionControlMask { MaskNone = 0, Flatten = 0x00000001, DontFlatten = 0x00000002, } public enum LoopControlShift { Unroll = 0, DontUnroll = 1, DependencyInfinite = 2, DependencyLength = 3, } public enum LoopControlMask { MaskNone = 0, Unroll = 0x00000001, DontUnroll = 0x00000002, DependencyInfinite = 0x00000004, DependencyLength = 0x00000008, } public enum FunctionControlShift { Inline = 0, DontInline = 1, Pure = 2, Const = 3, } public enum FunctionControlMask { MaskNone = 0, Inline = 0x00000001, DontInline = 0x00000002, Pure = 0x00000004, Const = 0x00000008, } public enum MemorySemanticsShift { Acquire = 1, Release = 2, AcquireRelease = 3, SequentiallyConsistent = 4, UniformMemory = 6, SubgroupMemory = 7, WorkgroupMemory = 8, CrossWorkgroupMemory = 9, AtomicCounterMemory = 10, ImageMemory = 11, } public enum MemorySemanticsMask { MaskNone = 0, Acquire = 0x00000002, Release = 0x00000004, AcquireRelease = 0x00000008, SequentiallyConsistent = 0x00000010, UniformMemory = 0x00000040, SubgroupMemory = 0x00000080, WorkgroupMemory = 0x00000100, CrossWorkgroupMemory = 0x00000200, AtomicCounterMemory = 0x00000400, ImageMemory = 0x00000800, } public enum MemoryAccessShift { Volatile = 0, Aligned = 1, Nontemporal = 2, } public enum MemoryAccessMask { MaskNone = 0, Volatile = 0x00000001, Aligned = 0x00000002, Nontemporal = 0x00000004, } public enum Scope { CrossDevice = 0, Device = 1, Workgroup = 2, Subgroup = 3, Invocation = 4, } public enum GroupOperation { Reduce = 0, InclusiveScan = 1, ExclusiveScan = 2, } public enum KernelEnqueueFlags { NoWait = 0, WaitKernel = 1, WaitWorkGroup = 2, } public enum KernelProfilingInfoShift { CmdExecTime = 0, } public enum KernelProfilingInfoMask { MaskNone = 0, CmdExecTime = 0x00000001, } public enum Capability { Matrix = 0, Shader = 1, Geometry = 2, Tessellation = 3, Addresses = 4, Linkage = 5, Kernel = 6, Vector16 = 7, Float16Buffer = 8, Float16 = 9, Float64 = 10, Int64 = 11, Int64Atomics = 12, ImageBasic = 13, ImageReadWrite = 14, ImageMipmap = 15, Pipes = 17, Groups = 18, DeviceEnqueue = 19, LiteralSampler = 20, AtomicStorage = 21, Int16 = 22, TessellationPointSize = 23, GeometryPointSize = 24, ImageGatherExtended = 25, StorageImageMultisample = 27, UniformBufferArrayDynamicIndexing = 28, SampledImageArrayDynamicIndexing = 29, StorageBufferArrayDynamicIndexing = 30, StorageImageArrayDynamicIndexing = 31, ClipDistance = 32, CullDistance = 33, ImageCubeArray = 34, SampleRateShading = 35, ImageRect = 36, SampledRect = 37, GenericPointer = 38, Int8 = 39, InputAttachment = 40, SparseResidency = 41, MinLod = 42, Sampled1D = 43, Image1D = 44, SampledCubeArray = 45, SampledBuffer = 46, ImageBuffer = 47, ImageMSArray = 48, StorageImageExtendedFormats = 49, ImageQuery = 50, DerivativeControl = 51, InterpolationFunction = 52, TransformFeedback = 53, GeometryStreams = 54, StorageImageReadWithoutFormat = 55, StorageImageWriteWithoutFormat = 56, MultiViewport = 57, SubgroupDispatch = 58, NamedBarrier = 59, PipeStorage = 60, SubgroupBallotKHR = 4423, DrawParameters = 4427, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, StorageUniform16 = 4434, UniformAndStorageBuffer16BitAccess = 4434, StoragePushConstant16 = 4435, StorageInputOutput16 = 4436, DeviceGroup = 4437, MultiView = 4439, VariablePointersStorageBuffer = 4441, VariablePointers = 4442, AtomicStorageOps = 4445, SampleMaskPostDepthCoverage = 4447, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, StencilExportEXT = 5013, ImageReadWriteLodAMD = 5015, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, ShaderViewportIndexLayerNV = 5254, ShaderViewportMaskNV = 5255, ShaderStereoViewNV = 5259, PerViewAttributesNV = 5260, SubgroupShuffleINTEL = 5568, SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, } public enum Op { OpNop = 0, OpUndef = 1, OpSourceContinued = 2, OpSource = 3, OpSourceExtension = 4, OpName = 5, OpMemberName = 6, OpString = 7, OpLine = 8, OpExtension = 10, OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, OpTypeVector = 23, OpTypeMatrix = 24, OpTypeImage = 25, OpTypeSampler = 26, OpTypeSampledImage = 27, OpTypeArray = 28, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypeOpaque = 31, OpTypePointer = 32, OpTypeFunction = 33, OpTypeEvent = 34, OpTypeDeviceEvent = 35, OpTypeReserveId = 36, OpTypeQueue = 37, OpTypePipe = 38, OpTypeForwardPointer = 39, OpConstantTrue = 41, OpConstantFalse = 42, OpConstant = 43, OpConstantComposite = 44, OpConstantSampler = 45, OpConstantNull = 46, OpSpecConstantTrue = 48, OpSpecConstantFalse = 49, OpSpecConstant = 50, OpSpecConstantComposite = 51, OpSpecConstantOp = 52, OpFunction = 54, OpFunctionParameter = 55, OpFunctionEnd = 56, OpFunctionCall = 57, OpVariable = 59, OpImageTexelPointer = 60, OpLoad = 61, OpStore = 62, OpCopyMemory = 63, OpCopyMemorySized = 64, OpAccessChain = 65, OpInBoundsAccessChain = 66, OpPtrAccessChain = 67, OpArrayLength = 68, OpGenericPtrMemSemantics = 69, OpInBoundsPtrAccessChain = 70, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, OpGroupDecorate = 74, OpGroupMemberDecorate = 75, OpVectorExtractDynamic = 77, OpVectorInsertDynamic = 78, OpVectorShuffle = 79, OpCompositeConstruct = 80, OpCompositeExtract = 81, OpCompositeInsert = 82, OpCopyObject = 83, OpTranspose = 84, OpSampledImage = 86, OpImageSampleImplicitLod = 87, OpImageSampleExplicitLod = 88, OpImageSampleDrefImplicitLod = 89, OpImageSampleDrefExplicitLod = 90, OpImageSampleProjImplicitLod = 91, OpImageSampleProjExplicitLod = 92, OpImageSampleProjDrefImplicitLod = 93, OpImageSampleProjDrefExplicitLod = 94, OpImageFetch = 95, OpImageGather = 96, OpImageDrefGather = 97, OpImageRead = 98, OpImageWrite = 99, OpImage = 100, OpImageQueryFormat = 101, OpImageQueryOrder = 102, OpImageQuerySizeLod = 103, OpImageQuerySize = 104, OpImageQueryLod = 105, OpImageQueryLevels = 106, OpImageQuerySamples = 107, OpConvertFToU = 109, OpConvertFToS = 110, OpConvertSToF = 111, OpConvertUToF = 112, OpUConvert = 113, OpSConvert = 114, OpFConvert = 115, OpQuantizeToF16 = 116, OpConvertPtrToU = 117, OpSatConvertSToU = 118, OpSatConvertUToS = 119, OpConvertUToPtr = 120, OpPtrCastToGeneric = 121, OpGenericCastToPtr = 122, OpGenericCastToPtrExplicit = 123, OpBitcast = 124, OpSNegate = 126, OpFNegate = 127, OpIAdd = 128, OpFAdd = 129, OpISub = 130, OpFSub = 131, OpIMul = 132, OpFMul = 133, OpUDiv = 134, OpSDiv = 135, OpFDiv = 136, OpUMod = 137, OpSRem = 138, OpSMod = 139, OpFRem = 140, OpFMod = 141, OpVectorTimesScalar = 142, OpMatrixTimesScalar = 143, OpVectorTimesMatrix = 144, OpMatrixTimesVector = 145, OpMatrixTimesMatrix = 146, OpOuterProduct = 147, OpDot = 148, OpIAddCarry = 149, OpISubBorrow = 150, OpUMulExtended = 151, OpSMulExtended = 152, OpAny = 154, OpAll = 155, OpIsNan = 156, OpIsInf = 157, OpIsFinite = 158, OpIsNormal = 159, OpSignBitSet = 160, OpLessOrGreater = 161, OpOrdered = 162, OpUnordered = 163, OpLogicalEqual = 164, OpLogicalNotEqual = 165, OpLogicalOr = 166, OpLogicalAnd = 167, OpLogicalNot = 168, OpSelect = 169, OpIEqual = 170, OpINotEqual = 171, OpUGreaterThan = 172, OpSGreaterThan = 173, OpUGreaterThanEqual = 174, OpSGreaterThanEqual = 175, OpULessThan = 176, OpSLessThan = 177, OpULessThanEqual = 178, OpSLessThanEqual = 179, OpFOrdEqual = 180, OpFUnordEqual = 181, OpFOrdNotEqual = 182, OpFUnordNotEqual = 183, OpFOrdLessThan = 184, OpFUnordLessThan = 185, OpFOrdGreaterThan = 186, OpFUnordGreaterThan = 187, OpFOrdLessThanEqual = 188, OpFUnordLessThanEqual = 189, OpFOrdGreaterThanEqual = 190, OpFUnordGreaterThanEqual = 191, OpShiftRightLogical = 194, OpShiftRightArithmetic = 195, OpShiftLeftLogical = 196, OpBitwiseOr = 197, OpBitwiseXor = 198, OpBitwiseAnd = 199, OpNot = 200, OpBitFieldInsert = 201, OpBitFieldSExtract = 202, OpBitFieldUExtract = 203, OpBitReverse = 204, OpBitCount = 205, OpDPdx = 207, OpDPdy = 208, OpFwidth = 209, OpDPdxFine = 210, OpDPdyFine = 211, OpFwidthFine = 212, OpDPdxCoarse = 213, OpDPdyCoarse = 214, OpFwidthCoarse = 215, OpEmitVertex = 218, OpEndPrimitive = 219, OpEmitStreamVertex = 220, OpEndStreamPrimitive = 221, OpControlBarrier = 224, OpMemoryBarrier = 225, OpAtomicLoad = 227, OpAtomicStore = 228, OpAtomicExchange = 229, OpAtomicCompareExchange = 230, OpAtomicCompareExchangeWeak = 231, OpAtomicIIncrement = 232, OpAtomicIDecrement = 233, OpAtomicIAdd = 234, OpAtomicISub = 235, OpAtomicSMin = 236, OpAtomicUMin = 237, OpAtomicSMax = 238, OpAtomicUMax = 239, OpAtomicAnd = 240, OpAtomicOr = 241, OpAtomicXor = 242, OpPhi = 245, OpLoopMerge = 246, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, OpBranchConditional = 250, OpSwitch = 251, OpKill = 252, OpReturn = 253, OpReturnValue = 254, OpUnreachable = 255, OpLifetimeStart = 256, OpLifetimeStop = 257, OpGroupAsyncCopy = 259, OpGroupWaitEvents = 260, OpGroupAll = 261, OpGroupAny = 262, OpGroupBroadcast = 263, OpGroupIAdd = 264, OpGroupFAdd = 265, OpGroupFMin = 266, OpGroupUMin = 267, OpGroupSMin = 268, OpGroupFMax = 269, OpGroupUMax = 270, OpGroupSMax = 271, OpReadPipe = 274, OpWritePipe = 275, OpReservedReadPipe = 276, OpReservedWritePipe = 277, OpReserveReadPipePackets = 278, OpReserveWritePipePackets = 279, OpCommitReadPipe = 280, OpCommitWritePipe = 281, OpIsValidReserveId = 282, OpGetNumPipePackets = 283, OpGetMaxPipePackets = 284, OpGroupReserveReadPipePackets = 285, OpGroupReserveWritePipePackets = 286, OpGroupCommitReadPipe = 287, OpGroupCommitWritePipe = 288, OpEnqueueMarker = 291, OpEnqueueKernel = 292, OpGetKernelNDrangeSubGroupCount = 293, OpGetKernelNDrangeMaxSubGroupSize = 294, OpGetKernelWorkGroupSize = 295, OpGetKernelPreferredWorkGroupSizeMultiple = 296, OpRetainEvent = 297, OpReleaseEvent = 298, OpCreateUserEvent = 299, OpIsValidEvent = 300, OpSetUserEventStatus = 301, OpCaptureEventProfilingInfo = 302, OpGetDefaultQueue = 303, OpBuildNDRange = 304, OpImageSparseSampleImplicitLod = 305, OpImageSparseSampleExplicitLod = 306, OpImageSparseSampleDrefImplicitLod = 307, OpImageSparseSampleDrefExplicitLod = 308, OpImageSparseSampleProjImplicitLod = 309, OpImageSparseSampleProjExplicitLod = 310, OpImageSparseSampleProjDrefImplicitLod = 311, OpImageSparseSampleProjDrefExplicitLod = 312, OpImageSparseFetch = 313, OpImageSparseGather = 314, OpImageSparseDrefGather = 315, OpImageSparseTexelsResident = 316, OpNoLine = 317, OpAtomicFlagTestAndSet = 318, OpAtomicFlagClear = 319, OpImageSparseRead = 320, OpSizeOf = 321, OpTypePipeStorage = 322, OpConstantPipeStorage = 323, OpCreatePipeFromPipeStorage = 324, OpGetKernelLocalSizeForSubgroupCount = 325, OpGetKernelMaxNumSubgroups = 326, OpTypeNamedBarrier = 327, OpNamedBarrierInitialize = 328, OpMemoryNamedBarrier = 329, OpModuleProcessed = 330, OpDecorateId = 332, OpSubgroupBallotKHR = 4421, OpSubgroupFirstInvocationKHR = 4422, OpSubgroupAllKHR = 4428, OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, OpGroupIAddNonUniformAMD = 5000, OpGroupFAddNonUniformAMD = 5001, OpGroupFMinNonUniformAMD = 5002, OpGroupUMinNonUniformAMD = 5003, OpGroupSMinNonUniformAMD = 5004, OpGroupFMaxNonUniformAMD = 5005, OpGroupUMaxNonUniformAMD = 5006, OpGroupSMaxNonUniformAMD = 5007, OpFragmentMaskFetchAMD = 5011, OpFragmentFetchAMD = 5012, OpSubgroupShuffleINTEL = 5571, OpSubgroupShuffleDownINTEL = 5572, OpSubgroupShuffleUpINTEL = 5573, OpSubgroupShuffleXorINTEL = 5574, OpSubgroupBlockReadINTEL = 5575, OpSubgroupBlockWriteINTEL = 5576, OpSubgroupImageBlockReadINTEL = 5577, OpSubgroupImageBlockWriteINTEL = 5578, OpDecorateStringGOOGLE = 5632, OpMemberDecorateStringGOOGLE = 5633, } } }
1,016
SPIRV-Headers
facebook
C#
// Copyright (c) 2014-2018 The Khronos Group Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and/or associated documentation files (the "Materials"), // to deal in the Materials without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Materials, and to permit persons to whom the // Materials are furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Materials. // // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS // STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND // HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ // // THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS // IN THE MATERIALS. // This header is automatically generated by the same tool that creates // the Binary Section of the SPIR-V specification. // Enumeration tokens for SPIR-V, in various styles: // C, C++, C++11, JSON, Lua, Python, C# // // - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL // - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL // - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL // - Lua will use tables, e.g.: spv.SourceLanguage.GLSL // - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] // - C# will use enum classes in the Specification class located in the "Spv" namespace, e.g.: Spv.Specification.SourceLanguage.GLSL // // Some tokens act like mask values, which can be OR'd together, // while others are mutually exclusive. The mask-like ones have // "Mask" in their name, and a parallel enum that has the shift // amount (1 << x) for each corresponding enumerant. namespace Spv { public static class Specification { public const uint MagicNumber = 0x07230203; public const uint Version = 0x00010200; public const uint Revision = 2; public const uint OpCodeMask = 0xffff; public const uint WordCountShift = 16; public enum SourceLanguage { Unknown = 0, ESSL = 1, GLSL = 2, OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, } public enum ExecutionModel { Vertex = 0, TessellationControl = 1, TessellationEvaluation = 2, Geometry = 3, Fragment = 4, GLCompute = 5, Kernel = 6, } public enum AddressingModel { Logical = 0, Physical32 = 1, Physical64 = 2, } public enum MemoryModel { Simple = 0, GLSL450 = 1, OpenCL = 2, } public enum ExecutionMode { Invocations = 0, SpacingEqual = 1, SpacingFractionalEven = 2, SpacingFractionalOdd = 3, VertexOrderCw = 4, VertexOrderCcw = 5, PixelCenterInteger = 6, OriginUpperLeft = 7, OriginLowerLeft = 8, EarlyFragmentTests = 9, PointMode = 10, Xfb = 11, DepthReplacing = 12, DepthGreater = 14, DepthLess = 15, DepthUnchanged = 16, LocalSize = 17, LocalSizeHint = 18, InputPoints = 19, InputLines = 20, InputLinesAdjacency = 21, Triangles = 22, InputTrianglesAdjacency = 23, Quads = 24, Isolines = 25, OutputVertices = 26, OutputPoints = 27, OutputLineStrip = 28, OutputTriangleStrip = 29, VecTypeHint = 30, ContractionOff = 31, Initializer = 33, Finalizer = 34, SubgroupSize = 35, SubgroupsPerWorkgroup = 36, SubgroupsPerWorkgroupId = 37, LocalSizeId = 38, LocalSizeHintId = 39, PostDepthCoverage = 4446, StencilRefReplacingEXT = 5027, } public enum StorageClass { UniformConstant = 0, Input = 1, Uniform = 2, Output = 3, Workgroup = 4, CrossWorkgroup = 5, Private = 6, Function = 7, Generic = 8, PushConstant = 9, AtomicCounter = 10, Image = 11, StorageBuffer = 12, } public enum Dim { Dim1D = 0, Dim2D = 1, Dim3D = 2, Cube = 3, Rect = 4, Buffer = 5, SubpassData = 6, } public enum SamplerAddressingMode { None = 0, ClampToEdge = 1, Clamp = 2, Repeat = 3, RepeatMirrored = 4, } public enum SamplerFilterMode { Nearest = 0, Linear = 1, } public enum ImageFormat { Unknown = 0, Rgba32f = 1, Rgba16f = 2, R32f = 3, Rgba8 = 4, Rgba8Snorm = 5, Rg32f = 6, Rg16f = 7, R11fG11fB10f = 8, R16f = 9, Rgba16 = 10, Rgb10A2 = 11, Rg16 = 12, Rg8 = 13, R16 = 14, R8 = 15, Rgba16Snorm = 16, Rg16Snorm = 17, Rg8Snorm = 18, R16Snorm = 19, R8Snorm = 20, Rgba32i = 21, Rgba16i = 22, Rgba8i = 23, R32i = 24, Rg32i = 25, Rg16i = 26, Rg8i = 27, R16i = 28, R8i = 29, Rgba32ui = 30, Rgba16ui = 31, Rgba8ui = 32, R32ui = 33, Rgb10a2ui = 34, Rg32ui = 35, Rg16ui = 36, Rg8ui = 37, R16ui = 38, R8ui = 39, } public enum ImageChannelOrder { R = 0, A = 1, RG = 2, RA = 3, RGB = 4, RGBA = 5, BGRA = 6, ARGB = 7, Intensity = 8, Luminance = 9, Rx = 10, RGx = 11, RGBx = 12, Depth = 13, DepthStencil = 14, sRGB = 15, sRGBx = 16, sRGBA = 17, sBGRA = 18, ABGR = 19, } public enum ImageChannelDataType { SnormInt8 = 0, SnormInt16 = 1, UnormInt8 = 2, UnormInt16 = 3, UnormShort565 = 4, UnormShort555 = 5, UnormInt101010 = 6, SignedInt8 = 7, SignedInt16 = 8, SignedInt32 = 9, UnsignedInt8 = 10, UnsignedInt16 = 11, UnsignedInt32 = 12, HalfFloat = 13, Float = 14, UnormInt24 = 15, UnormInt101010_2 = 16, } public enum ImageOperandsShift { Bias = 0, Lod = 1, Grad = 2, ConstOffset = 3, Offset = 4, ConstOffsets = 5, Sample = 6, MinLod = 7, } public enum ImageOperandsMask { MaskNone = 0, Bias = 0x00000001, Lod = 0x00000002, Grad = 0x00000004, ConstOffset = 0x00000008, Offset = 0x00000010, ConstOffsets = 0x00000020, Sample = 0x00000040, MinLod = 0x00000080, } public enum FPFastMathModeShift { NotNaN = 0, NotInf = 1, NSZ = 2, AllowRecip = 3, Fast = 4, } public enum FPFastMathModeMask { MaskNone = 0, NotNaN = 0x00000001, NotInf = 0x00000002, NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, } public enum FPRoundingMode { RTE = 0, RTZ = 1, RTP = 2, RTN = 3, } public enum LinkageType { Export = 0, Import = 1, } public enum AccessQualifier { ReadOnly = 0, WriteOnly = 1, ReadWrite = 2, } public enum FunctionParameterAttribute { Zext = 0, Sext = 1, ByVal = 2, Sret = 3, NoAlias = 4, NoCapture = 5, NoWrite = 6, NoReadWrite = 7, } public enum Decoration { RelaxedPrecision = 0, SpecId = 1, Block = 2, BufferBlock = 3, RowMajor = 4, ColMajor = 5, ArrayStride = 6, MatrixStride = 7, GLSLShared = 8, GLSLPacked = 9, CPacked = 10, BuiltIn = 11, NoPerspective = 13, Flat = 14, Patch = 15, Centroid = 16, Sample = 17, Invariant = 18, Restrict = 19, Aliased = 20, Volatile = 21, Constant = 22, Coherent = 23, NonWritable = 24, NonReadable = 25, Uniform = 26, SaturatedConversion = 28, Stream = 29, Location = 30, Component = 31, Index = 32, Binding = 33, DescriptorSet = 34, Offset = 35, XfbBuffer = 36, XfbStride = 37, FuncParamAttr = 38, FPRoundingMode = 39, FPFastMathMode = 40, LinkageAttributes = 41, NoContraction = 42, InputAttachmentIndex = 43, Alignment = 44, MaxByteOffset = 45, AlignmentId = 46, MaxByteOffsetId = 47, ExplicitInterpAMD = 4999, OverrideCoverageNV = 5248, PassthroughNV = 5250, ViewportRelativeNV = 5252, SecondaryViewportRelativeNV = 5256, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, } public enum BuiltIn { Position = 0, PointSize = 1, ClipDistance = 3, CullDistance = 4, VertexId = 5, InstanceId = 6, PrimitiveId = 7, InvocationId = 8, Layer = 9, ViewportIndex = 10, TessLevelOuter = 11, TessLevelInner = 12, TessCoord = 13, PatchVertices = 14, FragCoord = 15, PointCoord = 16, FrontFacing = 17, SampleId = 18, SamplePosition = 19, SampleMask = 20, FragDepth = 22, HelperInvocation = 23, NumWorkgroups = 24, WorkgroupSize = 25, WorkgroupId = 26, LocalInvocationId = 27, GlobalInvocationId = 28, LocalInvocationIndex = 29, WorkDim = 30, GlobalSize = 31, EnqueuedWorkgroupSize = 32, GlobalOffset = 33, GlobalLinearId = 34, SubgroupSize = 36, SubgroupMaxSize = 37, NumSubgroups = 38, NumEnqueuedSubgroups = 39, SubgroupId = 40, SubgroupLocalInvocationId = 41, VertexIndex = 42, InstanceIndex = 43, SubgroupEqMaskKHR = 4416, SubgroupGeMaskKHR = 4417, SubgroupGtMaskKHR = 4418, SubgroupLeMaskKHR = 4419, SubgroupLtMaskKHR = 4420, BaseVertex = 4424, BaseInstance = 4425, DrawIndex = 4426, DeviceIndex = 4438, ViewIndex = 4440, BaryCoordNoPerspAMD = 4992, BaryCoordNoPerspCentroidAMD = 4993, BaryCoordNoPerspSampleAMD = 4994, BaryCoordSmoothAMD = 4995, BaryCoordSmoothCentroidAMD = 4996, BaryCoordSmoothSampleAMD = 4997, BaryCoordPullModelAMD = 4998, FragStencilRefEXT = 5014, ViewportMaskNV = 5253, SecondaryPositionNV = 5257, SecondaryViewportMaskNV = 5258, PositionPerViewNV = 5261, ViewportMaskPerViewNV = 5262, } public enum SelectionControlShift { Flatten = 0, DontFlatten = 1, } public enum SelectionControlMask { MaskNone = 0, Flatten = 0x00000001, DontFlatten = 0x00000002, } public enum LoopControlShift { Unroll = 0, DontUnroll = 1, DependencyInfinite = 2, DependencyLength = 3, } public enum LoopControlMask { MaskNone = 0, Unroll = 0x00000001, DontUnroll = 0x00000002, DependencyInfinite = 0x00000004, DependencyLength = 0x00000008, } public enum FunctionControlShift { Inline = 0, DontInline = 1, Pure = 2, Const = 3, } public enum FunctionControlMask { MaskNone = 0, Inline = 0x00000001, DontInline = 0x00000002, Pure = 0x00000004, Const = 0x00000008, } public enum MemorySemanticsShift { Acquire = 1, Release = 2, AcquireRelease = 3, SequentiallyConsistent = 4, UniformMemory = 6, SubgroupMemory = 7, WorkgroupMemory = 8, CrossWorkgroupMemory = 9, AtomicCounterMemory = 10, ImageMemory = 11, } public enum MemorySemanticsMask { MaskNone = 0, Acquire = 0x00000002, Release = 0x00000004, AcquireRelease = 0x00000008, SequentiallyConsistent = 0x00000010, UniformMemory = 0x00000040, SubgroupMemory = 0x00000080, WorkgroupMemory = 0x00000100, CrossWorkgroupMemory = 0x00000200, AtomicCounterMemory = 0x00000400, ImageMemory = 0x00000800, } public enum MemoryAccessShift { Volatile = 0, Aligned = 1, Nontemporal = 2, } public enum MemoryAccessMask { MaskNone = 0, Volatile = 0x00000001, Aligned = 0x00000002, Nontemporal = 0x00000004, } public enum Scope { CrossDevice = 0, Device = 1, Workgroup = 2, Subgroup = 3, Invocation = 4, } public enum GroupOperation { Reduce = 0, InclusiveScan = 1, ExclusiveScan = 2, } public enum KernelEnqueueFlags { NoWait = 0, WaitKernel = 1, WaitWorkGroup = 2, } public enum KernelProfilingInfoShift { CmdExecTime = 0, } public enum KernelProfilingInfoMask { MaskNone = 0, CmdExecTime = 0x00000001, } public enum Capability { Matrix = 0, Shader = 1, Geometry = 2, Tessellation = 3, Addresses = 4, Linkage = 5, Kernel = 6, Vector16 = 7, Float16Buffer = 8, Float16 = 9, Float64 = 10, Int64 = 11, Int64Atomics = 12, ImageBasic = 13, ImageReadWrite = 14, ImageMipmap = 15, Pipes = 17, Groups = 18, DeviceEnqueue = 19, LiteralSampler = 20, AtomicStorage = 21, Int16 = 22, TessellationPointSize = 23, GeometryPointSize = 24, ImageGatherExtended = 25, StorageImageMultisample = 27, UniformBufferArrayDynamicIndexing = 28, SampledImageArrayDynamicIndexing = 29, StorageBufferArrayDynamicIndexing = 30, StorageImageArrayDynamicIndexing = 31, ClipDistance = 32, CullDistance = 33, ImageCubeArray = 34, SampleRateShading = 35, ImageRect = 36, SampledRect = 37, GenericPointer = 38, Int8 = 39, InputAttachment = 40, SparseResidency = 41, MinLod = 42, Sampled1D = 43, Image1D = 44, SampledCubeArray = 45, SampledBuffer = 46, ImageBuffer = 47, ImageMSArray = 48, StorageImageExtendedFormats = 49, ImageQuery = 50, DerivativeControl = 51, InterpolationFunction = 52, TransformFeedback = 53, GeometryStreams = 54, StorageImageReadWithoutFormat = 55, StorageImageWriteWithoutFormat = 56, MultiViewport = 57, SubgroupDispatch = 58, NamedBarrier = 59, PipeStorage = 60, SubgroupBallotKHR = 4423, DrawParameters = 4427, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, StorageUniform16 = 4434, UniformAndStorageBuffer16BitAccess = 4434, StoragePushConstant16 = 4435, StorageInputOutput16 = 4436, DeviceGroup = 4437, MultiView = 4439, VariablePointersStorageBuffer = 4441, VariablePointers = 4442, AtomicStorageOps = 4445, SampleMaskPostDepthCoverage = 4447, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, StencilExportEXT = 5013, ImageReadWriteLodAMD = 5015, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, ShaderViewportIndexLayerNV = 5254, ShaderViewportMaskNV = 5255, ShaderStereoViewNV = 5259, PerViewAttributesNV = 5260, SubgroupShuffleINTEL = 5568, SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, } public enum Op { OpNop = 0, OpUndef = 1, OpSourceContinued = 2, OpSource = 3, OpSourceExtension = 4, OpName = 5, OpMemberName = 6, OpString = 7, OpLine = 8, OpExtension = 10, OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, OpTypeVector = 23, OpTypeMatrix = 24, OpTypeImage = 25, OpTypeSampler = 26, OpTypeSampledImage = 27, OpTypeArray = 28, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypeOpaque = 31, OpTypePointer = 32, OpTypeFunction = 33, OpTypeEvent = 34, OpTypeDeviceEvent = 35, OpTypeReserveId = 36, OpTypeQueue = 37, OpTypePipe = 38, OpTypeForwardPointer = 39, OpConstantTrue = 41, OpConstantFalse = 42, OpConstant = 43, OpConstantComposite = 44, OpConstantSampler = 45, OpConstantNull = 46, OpSpecConstantTrue = 48, OpSpecConstantFalse = 49, OpSpecConstant = 50, OpSpecConstantComposite = 51, OpSpecConstantOp = 52, OpFunction = 54, OpFunctionParameter = 55, OpFunctionEnd = 56, OpFunctionCall = 57, OpVariable = 59, OpImageTexelPointer = 60, OpLoad = 61, OpStore = 62, OpCopyMemory = 63, OpCopyMemorySized = 64, OpAccessChain = 65, OpInBoundsAccessChain = 66, OpPtrAccessChain = 67, OpArrayLength = 68, OpGenericPtrMemSemantics = 69, OpInBoundsPtrAccessChain = 70, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, OpGroupDecorate = 74, OpGroupMemberDecorate = 75, OpVectorExtractDynamic = 77, OpVectorInsertDynamic = 78, OpVectorShuffle = 79, OpCompositeConstruct = 80, OpCompositeExtract = 81, OpCompositeInsert = 82, OpCopyObject = 83, OpTranspose = 84, OpSampledImage = 86, OpImageSampleImplicitLod = 87, OpImageSampleExplicitLod = 88, OpImageSampleDrefImplicitLod = 89, OpImageSampleDrefExplicitLod = 90, OpImageSampleProjImplicitLod = 91, OpImageSampleProjExplicitLod = 92, OpImageSampleProjDrefImplicitLod = 93, OpImageSampleProjDrefExplicitLod = 94, OpImageFetch = 95, OpImageGather = 96, OpImageDrefGather = 97, OpImageRead = 98, OpImageWrite = 99, OpImage = 100, OpImageQueryFormat = 101, OpImageQueryOrder = 102, OpImageQuerySizeLod = 103, OpImageQuerySize = 104, OpImageQueryLod = 105, OpImageQueryLevels = 106, OpImageQuerySamples = 107, OpConvertFToU = 109, OpConvertFToS = 110, OpConvertSToF = 111, OpConvertUToF = 112, OpUConvert = 113, OpSConvert = 114, OpFConvert = 115, OpQuantizeToF16 = 116, OpConvertPtrToU = 117, OpSatConvertSToU = 118, OpSatConvertUToS = 119, OpConvertUToPtr = 120, OpPtrCastToGeneric = 121, OpGenericCastToPtr = 122, OpGenericCastToPtrExplicit = 123, OpBitcast = 124, OpSNegate = 126, OpFNegate = 127, OpIAdd = 128, OpFAdd = 129, OpISub = 130, OpFSub = 131, OpIMul = 132, OpFMul = 133, OpUDiv = 134, OpSDiv = 135, OpFDiv = 136, OpUMod = 137, OpSRem = 138, OpSMod = 139, OpFRem = 140, OpFMod = 141, OpVectorTimesScalar = 142, OpMatrixTimesScalar = 143, OpVectorTimesMatrix = 144, OpMatrixTimesVector = 145, OpMatrixTimesMatrix = 146, OpOuterProduct = 147, OpDot = 148, OpIAddCarry = 149, OpISubBorrow = 150, OpUMulExtended = 151, OpSMulExtended = 152, OpAny = 154, OpAll = 155, OpIsNan = 156, OpIsInf = 157, OpIsFinite = 158, OpIsNormal = 159, OpSignBitSet = 160, OpLessOrGreater = 161, OpOrdered = 162, OpUnordered = 163, OpLogicalEqual = 164, OpLogicalNotEqual = 165, OpLogicalOr = 166, OpLogicalAnd = 167, OpLogicalNot = 168, OpSelect = 169, OpIEqual = 170, OpINotEqual = 171, OpUGreaterThan = 172, OpSGreaterThan = 173, OpUGreaterThanEqual = 174, OpSGreaterThanEqual = 175, OpULessThan = 176, OpSLessThan = 177, OpULessThanEqual = 178, OpSLessThanEqual = 179, OpFOrdEqual = 180, OpFUnordEqual = 181, OpFOrdNotEqual = 182, OpFUnordNotEqual = 183, OpFOrdLessThan = 184, OpFUnordLessThan = 185, OpFOrdGreaterThan = 186, OpFUnordGreaterThan = 187, OpFOrdLessThanEqual = 188, OpFUnordLessThanEqual = 189, OpFOrdGreaterThanEqual = 190, OpFUnordGreaterThanEqual = 191, OpShiftRightLogical = 194, OpShiftRightArithmetic = 195, OpShiftLeftLogical = 196, OpBitwiseOr = 197, OpBitwiseXor = 198, OpBitwiseAnd = 199, OpNot = 200, OpBitFieldInsert = 201, OpBitFieldSExtract = 202, OpBitFieldUExtract = 203, OpBitReverse = 204, OpBitCount = 205, OpDPdx = 207, OpDPdy = 208, OpFwidth = 209, OpDPdxFine = 210, OpDPdyFine = 211, OpFwidthFine = 212, OpDPdxCoarse = 213, OpDPdyCoarse = 214, OpFwidthCoarse = 215, OpEmitVertex = 218, OpEndPrimitive = 219, OpEmitStreamVertex = 220, OpEndStreamPrimitive = 221, OpControlBarrier = 224, OpMemoryBarrier = 225, OpAtomicLoad = 227, OpAtomicStore = 228, OpAtomicExchange = 229, OpAtomicCompareExchange = 230, OpAtomicCompareExchangeWeak = 231, OpAtomicIIncrement = 232, OpAtomicIDecrement = 233, OpAtomicIAdd = 234, OpAtomicISub = 235, OpAtomicSMin = 236, OpAtomicUMin = 237, OpAtomicSMax = 238, OpAtomicUMax = 239, OpAtomicAnd = 240, OpAtomicOr = 241, OpAtomicXor = 242, OpPhi = 245, OpLoopMerge = 246, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, OpBranchConditional = 250, OpSwitch = 251, OpKill = 252, OpReturn = 253, OpReturnValue = 254, OpUnreachable = 255, OpLifetimeStart = 256, OpLifetimeStop = 257, OpGroupAsyncCopy = 259, OpGroupWaitEvents = 260, OpGroupAll = 261, OpGroupAny = 262, OpGroupBroadcast = 263, OpGroupIAdd = 264, OpGroupFAdd = 265, OpGroupFMin = 266, OpGroupUMin = 267, OpGroupSMin = 268, OpGroupFMax = 269, OpGroupUMax = 270, OpGroupSMax = 271, OpReadPipe = 274, OpWritePipe = 275, OpReservedReadPipe = 276, OpReservedWritePipe = 277, OpReserveReadPipePackets = 278, OpReserveWritePipePackets = 279, OpCommitReadPipe = 280, OpCommitWritePipe = 281, OpIsValidReserveId = 282, OpGetNumPipePackets = 283, OpGetMaxPipePackets = 284, OpGroupReserveReadPipePackets = 285, OpGroupReserveWritePipePackets = 286, OpGroupCommitReadPipe = 287, OpGroupCommitWritePipe = 288, OpEnqueueMarker = 291, OpEnqueueKernel = 292, OpGetKernelNDrangeSubGroupCount = 293, OpGetKernelNDrangeMaxSubGroupSize = 294, OpGetKernelWorkGroupSize = 295, OpGetKernelPreferredWorkGroupSizeMultiple = 296, OpRetainEvent = 297, OpReleaseEvent = 298, OpCreateUserEvent = 299, OpIsValidEvent = 300, OpSetUserEventStatus = 301, OpCaptureEventProfilingInfo = 302, OpGetDefaultQueue = 303, OpBuildNDRange = 304, OpImageSparseSampleImplicitLod = 305, OpImageSparseSampleExplicitLod = 306, OpImageSparseSampleDrefImplicitLod = 307, OpImageSparseSampleDrefExplicitLod = 308, OpImageSparseSampleProjImplicitLod = 309, OpImageSparseSampleProjExplicitLod = 310, OpImageSparseSampleProjDrefImplicitLod = 311, OpImageSparseSampleProjDrefExplicitLod = 312, OpImageSparseFetch = 313, OpImageSparseGather = 314, OpImageSparseDrefGather = 315, OpImageSparseTexelsResident = 316, OpNoLine = 317, OpAtomicFlagTestAndSet = 318, OpAtomicFlagClear = 319, OpImageSparseRead = 320, OpSizeOf = 321, OpTypePipeStorage = 322, OpConstantPipeStorage = 323, OpCreatePipeFromPipeStorage = 324, OpGetKernelLocalSizeForSubgroupCount = 325, OpGetKernelMaxNumSubgroups = 326, OpTypeNamedBarrier = 327, OpNamedBarrierInitialize = 328, OpMemoryNamedBarrier = 329, OpModuleProcessed = 330, OpExecutionModeId = 331, OpDecorateId = 332, OpSubgroupBallotKHR = 4421, OpSubgroupFirstInvocationKHR = 4422, OpSubgroupAllKHR = 4428, OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, OpGroupIAddNonUniformAMD = 5000, OpGroupFAddNonUniformAMD = 5001, OpGroupFMinNonUniformAMD = 5002, OpGroupUMinNonUniformAMD = 5003, OpGroupSMinNonUniformAMD = 5004, OpGroupFMaxNonUniformAMD = 5005, OpGroupUMaxNonUniformAMD = 5006, OpGroupSMaxNonUniformAMD = 5007, OpFragmentMaskFetchAMD = 5011, OpFragmentFetchAMD = 5012, OpSubgroupShuffleINTEL = 5571, OpSubgroupShuffleDownINTEL = 5572, OpSubgroupShuffleUpINTEL = 5573, OpSubgroupShuffleXorINTEL = 5574, OpSubgroupBlockReadINTEL = 5575, OpSubgroupBlockWriteINTEL = 5576, OpSubgroupImageBlockReadINTEL = 5577, OpSubgroupImageBlockWriteINTEL = 5578, OpDecorateStringGOOGLE = 5632, OpMemberDecorateStringGOOGLE = 5633, } } }
1,022
SPIRV-Headers
facebook
C#
// Copyright (c) 2014-2020 The Khronos Group Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and/or associated documentation files (the "Materials"), // to deal in the Materials without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Materials, and to permit persons to whom the // Materials are furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Materials. // // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS // STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND // HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ // // THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS // IN THE MATERIALS. // This header is automatically generated by the same tool that creates // the Binary Section of the SPIR-V specification. // Enumeration tokens for SPIR-V, in various styles: // C, C++, C++11, JSON, Lua, Python, C#, D, Beef // // - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL // - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL // - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL // - Lua will use tables, e.g.: spv.SourceLanguage.GLSL // - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] // - C# will use enum classes in the Specification class located in the "Spv" namespace, // e.g.: Spv.Specification.SourceLanguage.GLSL // - D will have tokens under the "spv" module, e.g: spv.SourceLanguage.GLSL // - Beef will use enum classes in the Specification class located in the "Spv" namespace, // e.g.: Spv.Specification.SourceLanguage.GLSL // // Some tokens act like mask values, which can be OR'd together, // while others are mutually exclusive. The mask-like ones have // "Mask" in their name, and a parallel enum that has the shift // amount (1 << x) for each corresponding enumerant. namespace Spv { public static class Specification { public const uint MagicNumber = 0x07230203; public const uint Version = 0x00010600; public const uint Revision = 1; public const uint OpCodeMask = 0xffff; public const uint WordCountShift = 16; public enum SourceLanguage { Unknown = 0, ESSL = 1, GLSL = 2, OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, CPP_for_OpenCL = 6, SYCL = 7, HERO_C = 8, } public enum ExecutionModel { Vertex = 0, TessellationControl = 1, TessellationEvaluation = 2, Geometry = 3, Fragment = 4, GLCompute = 5, Kernel = 6, TaskNV = 5267, MeshNV = 5268, RayGenerationKHR = 5313, RayGenerationNV = 5313, IntersectionKHR = 5314, IntersectionNV = 5314, AnyHitKHR = 5315, AnyHitNV = 5315, ClosestHitKHR = 5316, ClosestHitNV = 5316, MissKHR = 5317, MissNV = 5317, CallableKHR = 5318, CallableNV = 5318, TaskEXT = 5364, MeshEXT = 5365, } public enum AddressingModel { Logical = 0, Physical32 = 1, Physical64 = 2, PhysicalStorageBuffer64 = 5348, PhysicalStorageBuffer64EXT = 5348, } public enum MemoryModel { Simple = 0, GLSL450 = 1, OpenCL = 2, Vulkan = 3, VulkanKHR = 3, } public enum ExecutionMode { Invocations = 0, SpacingEqual = 1, SpacingFractionalEven = 2, SpacingFractionalOdd = 3, VertexOrderCw = 4, VertexOrderCcw = 5, PixelCenterInteger = 6, OriginUpperLeft = 7, OriginLowerLeft = 8, EarlyFragmentTests = 9, PointMode = 10, Xfb = 11, DepthReplacing = 12, DepthGreater = 14, DepthLess = 15, DepthUnchanged = 16, LocalSize = 17, LocalSizeHint = 18, InputPoints = 19, InputLines = 20, InputLinesAdjacency = 21, Triangles = 22, InputTrianglesAdjacency = 23, Quads = 24, Isolines = 25, OutputVertices = 26, OutputPoints = 27, OutputLineStrip = 28, OutputTriangleStrip = 29, VecTypeHint = 30, ContractionOff = 31, Initializer = 33, Finalizer = 34, SubgroupSize = 35, SubgroupsPerWorkgroup = 36, SubgroupsPerWorkgroupId = 37, LocalSizeId = 38, LocalSizeHintId = 39, NonCoherentColorAttachmentReadEXT = 4169, NonCoherentDepthAttachmentReadEXT = 4170, NonCoherentStencilAttachmentReadEXT = 4171, SubgroupUniformControlFlowKHR = 4421, PostDepthCoverage = 4446, DenormPreserve = 4459, DenormFlushToZero = 4460, SignedZeroInfNanPreserve = 4461, RoundingModeRTE = 4462, RoundingModeRTZ = 4463, EarlyAndLateFragmentTestsAMD = 5017, StencilRefReplacingEXT = 5027, StencilRefUnchangedFrontAMD = 5079, StencilRefGreaterFrontAMD = 5080, StencilRefLessFrontAMD = 5081, StencilRefUnchangedBackAMD = 5082, StencilRefGreaterBackAMD = 5083, StencilRefLessBackAMD = 5084, OutputLinesEXT = 5269, OutputLinesNV = 5269, OutputPrimitivesEXT = 5270, OutputPrimitivesNV = 5270, DerivativeGroupQuadsNV = 5289, DerivativeGroupLinearNV = 5290, OutputTrianglesEXT = 5298, OutputTrianglesNV = 5298, PixelInterlockOrderedEXT = 5366, PixelInterlockUnorderedEXT = 5367, SampleInterlockOrderedEXT = 5368, SampleInterlockUnorderedEXT = 5369, ShadingRateInterlockOrderedEXT = 5370, ShadingRateInterlockUnorderedEXT = 5371, SharedLocalMemorySizeINTEL = 5618, RoundingModeRTPINTEL = 5620, RoundingModeRTNINTEL = 5621, FloatingPointModeALTINTEL = 5622, FloatingPointModeIEEEINTEL = 5623, MaxWorkgroupSizeINTEL = 5893, MaxWorkDimINTEL = 5894, NoGlobalOffsetINTEL = 5895, NumSIMDWorkitemsINTEL = 5896, SchedulerTargetFmaxMhzINTEL = 5903, StreamingInterfaceINTEL = 6154, RegisterMapInterfaceINTEL = 6160, NamedBarrierCountINTEL = 6417, } public enum StorageClass { UniformConstant = 0, Input = 1, Uniform = 2, Output = 3, Workgroup = 4, CrossWorkgroup = 5, Private = 6, Function = 7, Generic = 8, PushConstant = 9, AtomicCounter = 10, Image = 11, StorageBuffer = 12, TileImageEXT = 4172, CallableDataKHR = 5328, CallableDataNV = 5328, IncomingCallableDataKHR = 5329, IncomingCallableDataNV = 5329, RayPayloadKHR = 5338, RayPayloadNV = 5338, HitAttributeKHR = 5339, HitAttributeNV = 5339, IncomingRayPayloadKHR = 5342, IncomingRayPayloadNV = 5342, ShaderRecordBufferKHR = 5343, ShaderRecordBufferNV = 5343, PhysicalStorageBuffer = 5349, PhysicalStorageBufferEXT = 5349, HitObjectAttributeNV = 5385, TaskPayloadWorkgroupEXT = 5402, CodeSectionINTEL = 5605, DeviceOnlyINTEL = 5936, HostOnlyINTEL = 5937, } public enum Dim { Dim1D = 0, Dim2D = 1, Dim3D = 2, Cube = 3, Rect = 4, Buffer = 5, SubpassData = 6, TileImageDataEXT = 4173, } public enum SamplerAddressingMode { None = 0, ClampToEdge = 1, Clamp = 2, Repeat = 3, RepeatMirrored = 4, } public enum SamplerFilterMode { Nearest = 0, Linear = 1, } public enum ImageFormat { Unknown = 0, Rgba32f = 1, Rgba16f = 2, R32f = 3, Rgba8 = 4, Rgba8Snorm = 5, Rg32f = 6, Rg16f = 7, R11fG11fB10f = 8, R16f = 9, Rgba16 = 10, Rgb10A2 = 11, Rg16 = 12, Rg8 = 13, R16 = 14, R8 = 15, Rgba16Snorm = 16, Rg16Snorm = 17, Rg8Snorm = 18, R16Snorm = 19, R8Snorm = 20, Rgba32i = 21, Rgba16i = 22, Rgba8i = 23, R32i = 24, Rg32i = 25, Rg16i = 26, Rg8i = 27, R16i = 28, R8i = 29, Rgba32ui = 30, Rgba16ui = 31, Rgba8ui = 32, R32ui = 33, Rgb10a2ui = 34, Rg32ui = 35, Rg16ui = 36, Rg8ui = 37, R16ui = 38, R8ui = 39, R64ui = 40, R64i = 41, } public enum ImageChannelOrder { R = 0, A = 1, RG = 2, RA = 3, RGB = 4, RGBA = 5, BGRA = 6, ARGB = 7, Intensity = 8, Luminance = 9, Rx = 10, RGx = 11, RGBx = 12, Depth = 13, DepthStencil = 14, sRGB = 15, sRGBx = 16, sRGBA = 17, sBGRA = 18, ABGR = 19, } public enum ImageChannelDataType { SnormInt8 = 0, SnormInt16 = 1, UnormInt8 = 2, UnormInt16 = 3, UnormShort565 = 4, UnormShort555 = 5, UnormInt101010 = 6, SignedInt8 = 7, SignedInt16 = 8, SignedInt32 = 9, UnsignedInt8 = 10, UnsignedInt16 = 11, UnsignedInt32 = 12, HalfFloat = 13, Float = 14, UnormInt24 = 15, UnormInt101010_2 = 16, } public enum ImageOperandsShift { Bias = 0, Lod = 1, Grad = 2, ConstOffset = 3, Offset = 4, ConstOffsets = 5, Sample = 6, MinLod = 7, MakeTexelAvailable = 8, MakeTexelAvailableKHR = 8, MakeTexelVisible = 9, MakeTexelVisibleKHR = 9, NonPrivateTexel = 10, NonPrivateTexelKHR = 10, VolatileTexel = 11, VolatileTexelKHR = 11, SignExtend = 12, ZeroExtend = 13, Nontemporal = 14, Offsets = 16, } public enum ImageOperandsMask { MaskNone = 0, Bias = 0x00000001, Lod = 0x00000002, Grad = 0x00000004, ConstOffset = 0x00000008, Offset = 0x00000010, ConstOffsets = 0x00000020, Sample = 0x00000040, MinLod = 0x00000080, MakeTexelAvailable = 0x00000100, MakeTexelAvailableKHR = 0x00000100, MakeTexelVisible = 0x00000200, MakeTexelVisibleKHR = 0x00000200, NonPrivateTexel = 0x00000400, NonPrivateTexelKHR = 0x00000400, VolatileTexel = 0x00000800, VolatileTexelKHR = 0x00000800, SignExtend = 0x00001000, ZeroExtend = 0x00002000, Nontemporal = 0x00004000, Offsets = 0x00010000, } public enum FPFastMathModeShift { NotNaN = 0, NotInf = 1, NSZ = 2, AllowRecip = 3, Fast = 4, AllowContractFastINTEL = 16, AllowReassocINTEL = 17, } public enum FPFastMathModeMask { MaskNone = 0, NotNaN = 0x00000001, NotInf = 0x00000002, NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, AllowContractFastINTEL = 0x00010000, AllowReassocINTEL = 0x00020000, } public enum FPRoundingMode { RTE = 0, RTZ = 1, RTP = 2, RTN = 3, } public enum LinkageType { Export = 0, Import = 1, LinkOnceODR = 2, } public enum AccessQualifier { ReadOnly = 0, WriteOnly = 1, ReadWrite = 2, } public enum FunctionParameterAttribute { Zext = 0, Sext = 1, ByVal = 2, Sret = 3, NoAlias = 4, NoCapture = 5, NoWrite = 6, NoReadWrite = 7, RuntimeAlignedINTEL = 5940, } public enum Decoration { RelaxedPrecision = 0, SpecId = 1, Block = 2, BufferBlock = 3, RowMajor = 4, ColMajor = 5, ArrayStride = 6, MatrixStride = 7, GLSLShared = 8, GLSLPacked = 9, CPacked = 10, BuiltIn = 11, NoPerspective = 13, Flat = 14, Patch = 15, Centroid = 16, Sample = 17, Invariant = 18, Restrict = 19, Aliased = 20, Volatile = 21, Constant = 22, Coherent = 23, NonWritable = 24, NonReadable = 25, Uniform = 26, UniformId = 27, SaturatedConversion = 28, Stream = 29, Location = 30, Component = 31, Index = 32, Binding = 33, DescriptorSet = 34, Offset = 35, XfbBuffer = 36, XfbStride = 37, FuncParamAttr = 38, FPRoundingMode = 39, FPFastMathMode = 40, LinkageAttributes = 41, NoContraction = 42, InputAttachmentIndex = 43, Alignment = 44, MaxByteOffset = 45, AlignmentId = 46, MaxByteOffsetId = 47, NoSignedWrap = 4469, NoUnsignedWrap = 4470, WeightTextureQCOM = 4487, BlockMatchTextureQCOM = 4488, ExplicitInterpAMD = 4999, OverrideCoverageNV = 5248, PassthroughNV = 5250, ViewportRelativeNV = 5252, SecondaryViewportRelativeNV = 5256, PerPrimitiveEXT = 5271, PerPrimitiveNV = 5271, PerViewNV = 5272, PerTaskNV = 5273, PerVertexKHR = 5285, PerVertexNV = 5285, NonUniform = 5300, NonUniformEXT = 5300, RestrictPointer = 5355, RestrictPointerEXT = 5355, AliasedPointer = 5356, AliasedPointerEXT = 5356, HitObjectShaderRecordBufferNV = 5386, BindlessSamplerNV = 5398, BindlessImageNV = 5399, BoundSamplerNV = 5400, BoundImageNV = 5401, SIMTCallINTEL = 5599, ReferencedIndirectlyINTEL = 5602, ClobberINTEL = 5607, SideEffectsINTEL = 5608, VectorComputeVariableINTEL = 5624, FuncParamIOKindINTEL = 5625, VectorComputeFunctionINTEL = 5626, StackCallINTEL = 5627, GlobalVariableOffsetINTEL = 5628, CounterBuffer = 5634, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, UserSemantic = 5635, UserTypeGOOGLE = 5636, FunctionRoundingModeINTEL = 5822, FunctionDenormModeINTEL = 5823, RegisterINTEL = 5825, MemoryINTEL = 5826, NumbanksINTEL = 5827, BankwidthINTEL = 5828, MaxPrivateCopiesINTEL = 5829, SinglepumpINTEL = 5830, DoublepumpINTEL = 5831, MaxReplicatesINTEL = 5832, SimpleDualPortINTEL = 5833, MergeINTEL = 5834, BankBitsINTEL = 5835, ForcePow2DepthINTEL = 5836, BurstCoalesceINTEL = 5899, CacheSizeINTEL = 5900, DontStaticallyCoalesceINTEL = 5901, PrefetchINTEL = 5902, StallEnableINTEL = 5905, FuseLoopsInFunctionINTEL = 5907, MathOpDSPModeINTEL = 5909, AliasScopeINTEL = 5914, NoAliasINTEL = 5915, InitiationIntervalINTEL = 5917, MaxConcurrencyINTEL = 5918, PipelineEnableINTEL = 5919, BufferLocationINTEL = 5921, IOPipeStorageINTEL = 5944, FunctionFloatingPointModeINTEL = 6080, SingleElementVectorINTEL = 6085, VectorComputeCallableFunctionINTEL = 6087, MediaBlockIOINTEL = 6140, LatencyControlLabelINTEL = 6172, LatencyControlConstraintINTEL = 6173, ConduitKernelArgumentINTEL = 6175, RegisterMapKernelArgumentINTEL = 6176, MMHostInterfaceAddressWidthINTEL = 6177, MMHostInterfaceDataWidthINTEL = 6178, MMHostInterfaceLatencyINTEL = 6179, MMHostInterfaceReadWriteModeINTEL = 6180, MMHostInterfaceMaxBurstINTEL = 6181, MMHostInterfaceWaitRequestINTEL = 6182, StableKernelArgumentINTEL = 6183, } public enum BuiltIn { Position = 0, PointSize = 1, ClipDistance = 3, CullDistance = 4, VertexId = 5, InstanceId = 6, PrimitiveId = 7, InvocationId = 8, Layer = 9, ViewportIndex = 10, TessLevelOuter = 11, TessLevelInner = 12, TessCoord = 13, PatchVertices = 14, FragCoord = 15, PointCoord = 16, FrontFacing = 17, SampleId = 18, SamplePosition = 19, SampleMask = 20, FragDepth = 22, HelperInvocation = 23, NumWorkgroups = 24, WorkgroupSize = 25, WorkgroupId = 26, LocalInvocationId = 27, GlobalInvocationId = 28, LocalInvocationIndex = 29, WorkDim = 30, GlobalSize = 31, EnqueuedWorkgroupSize = 32, GlobalOffset = 33, GlobalLinearId = 34, SubgroupSize = 36, SubgroupMaxSize = 37, NumSubgroups = 38, NumEnqueuedSubgroups = 39, SubgroupId = 40, SubgroupLocalInvocationId = 41, VertexIndex = 42, InstanceIndex = 43, CoreIDARM = 4160, CoreCountARM = 4161, CoreMaxIDARM = 4162, WarpIDARM = 4163, WarpMaxIDARM = 4164, SubgroupEqMask = 4416, SubgroupEqMaskKHR = 4416, SubgroupGeMask = 4417, SubgroupGeMaskKHR = 4417, SubgroupGtMask = 4418, SubgroupGtMaskKHR = 4418, SubgroupLeMask = 4419, SubgroupLeMaskKHR = 4419, SubgroupLtMask = 4420, SubgroupLtMaskKHR = 4420, BaseVertex = 4424, BaseInstance = 4425, DrawIndex = 4426, PrimitiveShadingRateKHR = 4432, DeviceIndex = 4438, ViewIndex = 4440, ShadingRateKHR = 4444, BaryCoordNoPerspAMD = 4992, BaryCoordNoPerspCentroidAMD = 4993, BaryCoordNoPerspSampleAMD = 4994, BaryCoordSmoothAMD = 4995, BaryCoordSmoothCentroidAMD = 4996, BaryCoordSmoothSampleAMD = 4997, BaryCoordPullModelAMD = 4998, FragStencilRefEXT = 5014, ViewportMaskNV = 5253, SecondaryPositionNV = 5257, SecondaryViewportMaskNV = 5258, PositionPerViewNV = 5261, ViewportMaskPerViewNV = 5262, FullyCoveredEXT = 5264, TaskCountNV = 5274, PrimitiveCountNV = 5275, PrimitiveIndicesNV = 5276, ClipDistancePerViewNV = 5277, CullDistancePerViewNV = 5278, LayerPerViewNV = 5279, MeshViewCountNV = 5280, MeshViewIndicesNV = 5281, BaryCoordKHR = 5286, BaryCoordNV = 5286, BaryCoordNoPerspKHR = 5287, BaryCoordNoPerspNV = 5287, FragSizeEXT = 5292, FragmentSizeNV = 5292, FragInvocationCountEXT = 5293, InvocationsPerPixelNV = 5293, PrimitivePointIndicesEXT = 5294, PrimitiveLineIndicesEXT = 5295, PrimitiveTriangleIndicesEXT = 5296, CullPrimitiveEXT = 5299, LaunchIdKHR = 5319, LaunchIdNV = 5319, LaunchSizeKHR = 5320, LaunchSizeNV = 5320, WorldRayOriginKHR = 5321, WorldRayOriginNV = 5321, WorldRayDirectionKHR = 5322, WorldRayDirectionNV = 5322, ObjectRayOriginKHR = 5323, ObjectRayOriginNV = 5323, ObjectRayDirectionKHR = 5324, ObjectRayDirectionNV = 5324, RayTminKHR = 5325, RayTminNV = 5325, RayTmaxKHR = 5326, RayTmaxNV = 5326, InstanceCustomIndexKHR = 5327, InstanceCustomIndexNV = 5327, ObjectToWorldKHR = 5330, ObjectToWorldNV = 5330, WorldToObjectKHR = 5331, WorldToObjectNV = 5331, HitTNV = 5332, HitKindKHR = 5333, HitKindNV = 5333, CurrentRayTimeNV = 5334, HitTriangleVertexPositionsKHR = 5335, IncomingRayFlagsKHR = 5351, IncomingRayFlagsNV = 5351, RayGeometryIndexKHR = 5352, WarpsPerSMNV = 5374, SMCountNV = 5375, WarpIDNV = 5376, SMIDNV = 5377, CullMaskKHR = 6021, } public enum SelectionControlShift { Flatten = 0, DontFlatten = 1, } public enum SelectionControlMask { MaskNone = 0, Flatten = 0x00000001, DontFlatten = 0x00000002, } public enum LoopControlShift { Unroll = 0, DontUnroll = 1, DependencyInfinite = 2, DependencyLength = 3, MinIterations = 4, MaxIterations = 5, IterationMultiple = 6, PeelCount = 7, PartialCount = 8, InitiationIntervalINTEL = 16, MaxConcurrencyINTEL = 17, DependencyArrayINTEL = 18, PipelineEnableINTEL = 19, LoopCoalesceINTEL = 20, MaxInterleavingINTEL = 21, SpeculatedIterationsINTEL = 22, NoFusionINTEL = 23, LoopCountINTEL = 24, MaxReinvocationDelayINTEL = 25, } public enum LoopControlMask { MaskNone = 0, Unroll = 0x00000001, DontUnroll = 0x00000002, DependencyInfinite = 0x00000004, DependencyLength = 0x00000008, MinIterations = 0x00000010, MaxIterations = 0x00000020, IterationMultiple = 0x00000040, PeelCount = 0x00000080, PartialCount = 0x00000100, InitiationIntervalINTEL = 0x00010000, MaxConcurrencyINTEL = 0x00020000, DependencyArrayINTEL = 0x00040000, PipelineEnableINTEL = 0x00080000, LoopCoalesceINTEL = 0x00100000, MaxInterleavingINTEL = 0x00200000, SpeculatedIterationsINTEL = 0x00400000, NoFusionINTEL = 0x00800000, LoopCountINTEL = 0x01000000, MaxReinvocationDelayINTEL = 0x02000000, } public enum FunctionControlShift { Inline = 0, DontInline = 1, Pure = 2, Const = 3, OptNoneINTEL = 16, } public enum FunctionControlMask { MaskNone = 0, Inline = 0x00000001, DontInline = 0x00000002, Pure = 0x00000004, Const = 0x00000008, OptNoneINTEL = 0x00010000, } public enum MemorySemanticsShift { Acquire = 1, Release = 2, AcquireRelease = 3, SequentiallyConsistent = 4, UniformMemory = 6, SubgroupMemory = 7, WorkgroupMemory = 8, CrossWorkgroupMemory = 9, AtomicCounterMemory = 10, ImageMemory = 11, OutputMemory = 12, OutputMemoryKHR = 12, MakeAvailable = 13, MakeAvailableKHR = 13, MakeVisible = 14, MakeVisibleKHR = 14, Volatile = 15, } public enum MemorySemanticsMask { MaskNone = 0, Acquire = 0x00000002, Release = 0x00000004, AcquireRelease = 0x00000008, SequentiallyConsistent = 0x00000010, UniformMemory = 0x00000040, SubgroupMemory = 0x00000080, WorkgroupMemory = 0x00000100, CrossWorkgroupMemory = 0x00000200, AtomicCounterMemory = 0x00000400, ImageMemory = 0x00000800, OutputMemory = 0x00001000, OutputMemoryKHR = 0x00001000, MakeAvailable = 0x00002000, MakeAvailableKHR = 0x00002000, MakeVisible = 0x00004000, MakeVisibleKHR = 0x00004000, Volatile = 0x00008000, } public enum MemoryAccessShift { Volatile = 0, Aligned = 1, Nontemporal = 2, MakePointerAvailable = 3, MakePointerAvailableKHR = 3, MakePointerVisible = 4, MakePointerVisibleKHR = 4, NonPrivatePointer = 5, NonPrivatePointerKHR = 5, AliasScopeINTELMask = 16, NoAliasINTELMask = 17, } public enum MemoryAccessMask { MaskNone = 0, Volatile = 0x00000001, Aligned = 0x00000002, Nontemporal = 0x00000004, MakePointerAvailable = 0x00000008, MakePointerAvailableKHR = 0x00000008, MakePointerVisible = 0x00000010, MakePointerVisibleKHR = 0x00000010, NonPrivatePointer = 0x00000020, NonPrivatePointerKHR = 0x00000020, AliasScopeINTELMask = 0x00010000, NoAliasINTELMask = 0x00020000, } public enum Scope { CrossDevice = 0, Device = 1, Workgroup = 2, Subgroup = 3, Invocation = 4, QueueFamily = 5, QueueFamilyKHR = 5, ShaderCallKHR = 6, } public enum GroupOperation { Reduce = 0, InclusiveScan = 1, ExclusiveScan = 2, ClusteredReduce = 3, PartitionedReduceNV = 6, PartitionedInclusiveScanNV = 7, PartitionedExclusiveScanNV = 8, } public enum KernelEnqueueFlags { NoWait = 0, WaitKernel = 1, WaitWorkGroup = 2, } public enum KernelProfilingInfoShift { CmdExecTime = 0, } public enum KernelProfilingInfoMask { MaskNone = 0, CmdExecTime = 0x00000001, } public enum Capability { Matrix = 0, Shader = 1, Geometry = 2, Tessellation = 3, Addresses = 4, Linkage = 5, Kernel = 6, Vector16 = 7, Float16Buffer = 8, Float16 = 9, Float64 = 10, Int64 = 11, Int64Atomics = 12, ImageBasic = 13, ImageReadWrite = 14, ImageMipmap = 15, Pipes = 17, Groups = 18, DeviceEnqueue = 19, LiteralSampler = 20, AtomicStorage = 21, Int16 = 22, TessellationPointSize = 23, GeometryPointSize = 24, ImageGatherExtended = 25, StorageImageMultisample = 27, UniformBufferArrayDynamicIndexing = 28, SampledImageArrayDynamicIndexing = 29, StorageBufferArrayDynamicIndexing = 30, StorageImageArrayDynamicIndexing = 31, ClipDistance = 32, CullDistance = 33, ImageCubeArray = 34, SampleRateShading = 35, ImageRect = 36, SampledRect = 37, GenericPointer = 38, Int8 = 39, InputAttachment = 40, SparseResidency = 41, MinLod = 42, Sampled1D = 43, Image1D = 44, SampledCubeArray = 45, SampledBuffer = 46, ImageBuffer = 47, ImageMSArray = 48, StorageImageExtendedFormats = 49, ImageQuery = 50, DerivativeControl = 51, InterpolationFunction = 52, TransformFeedback = 53, GeometryStreams = 54, StorageImageReadWithoutFormat = 55, StorageImageWriteWithoutFormat = 56, MultiViewport = 57, SubgroupDispatch = 58, NamedBarrier = 59, PipeStorage = 60, GroupNonUniform = 61, GroupNonUniformVote = 62, GroupNonUniformArithmetic = 63, GroupNonUniformBallot = 64, GroupNonUniformShuffle = 65, GroupNonUniformShuffleRelative = 66, GroupNonUniformClustered = 67, GroupNonUniformQuad = 68, ShaderLayer = 69, ShaderViewportIndex = 70, UniformDecoration = 71, CoreBuiltinsARM = 4165, TileImageColorReadAccessEXT = 4166, TileImageDepthReadAccessEXT = 4167, TileImageStencilReadAccessEXT = 4168, FragmentShadingRateKHR = 4422, SubgroupBallotKHR = 4423, DrawParameters = 4427, WorkgroupMemoryExplicitLayoutKHR = 4428, WorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, WorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, StorageUniform16 = 4434, UniformAndStorageBuffer16BitAccess = 4434, StoragePushConstant16 = 4435, StorageInputOutput16 = 4436, DeviceGroup = 4437, MultiView = 4439, VariablePointersStorageBuffer = 4441, VariablePointers = 4442, AtomicStorageOps = 4445, SampleMaskPostDepthCoverage = 4447, StorageBuffer8BitAccess = 4448, UniformAndStorageBuffer8BitAccess = 4449, StoragePushConstant8 = 4450, DenormPreserve = 4464, DenormFlushToZero = 4465, SignedZeroInfNanPreserve = 4466, RoundingModeRTE = 4467, RoundingModeRTZ = 4468, RayQueryProvisionalKHR = 4471, RayQueryKHR = 4472, RayTraversalPrimitiveCullingKHR = 4478, RayTracingKHR = 4479, TextureSampleWeightedQCOM = 4484, TextureBoxFilterQCOM = 4485, TextureBlockMatchQCOM = 4486, Float16ImageAMD = 5008, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, StencilExportEXT = 5013, ImageReadWriteLodAMD = 5015, Int64ImageEXT = 5016, ShaderClockKHR = 5055, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, ShaderViewportIndexLayerNV = 5254, ShaderViewportMaskNV = 5255, ShaderStereoViewNV = 5259, PerViewAttributesNV = 5260, FragmentFullyCoveredEXT = 5265, MeshShadingNV = 5266, ImageFootprintNV = 5282, MeshShadingEXT = 5283, FragmentBarycentricKHR = 5284, FragmentBarycentricNV = 5284, ComputeDerivativeGroupQuadsNV = 5288, FragmentDensityEXT = 5291, ShadingRateNV = 5291, GroupNonUniformPartitionedNV = 5297, ShaderNonUniform = 5301, ShaderNonUniformEXT = 5301, RuntimeDescriptorArray = 5302, RuntimeDescriptorArrayEXT = 5302, InputAttachmentArrayDynamicIndexing = 5303, InputAttachmentArrayDynamicIndexingEXT = 5303, UniformTexelBufferArrayDynamicIndexing = 5304, UniformTexelBufferArrayDynamicIndexingEXT = 5304, StorageTexelBufferArrayDynamicIndexing = 5305, StorageTexelBufferArrayDynamicIndexingEXT = 5305, UniformBufferArrayNonUniformIndexing = 5306, UniformBufferArrayNonUniformIndexingEXT = 5306, SampledImageArrayNonUniformIndexing = 5307, SampledImageArrayNonUniformIndexingEXT = 5307, StorageBufferArrayNonUniformIndexing = 5308, StorageBufferArrayNonUniformIndexingEXT = 5308, StorageImageArrayNonUniformIndexing = 5309, StorageImageArrayNonUniformIndexingEXT = 5309, InputAttachmentArrayNonUniformIndexing = 5310, InputAttachmentArrayNonUniformIndexingEXT = 5310, UniformTexelBufferArrayNonUniformIndexing = 5311, UniformTexelBufferArrayNonUniformIndexingEXT = 5311, StorageTexelBufferArrayNonUniformIndexing = 5312, StorageTexelBufferArrayNonUniformIndexingEXT = 5312, RayTracingPositionFetchKHR = 5336, RayTracingNV = 5340, RayTracingMotionBlurNV = 5341, VulkanMemoryModel = 5345, VulkanMemoryModelKHR = 5345, VulkanMemoryModelDeviceScope = 5346, VulkanMemoryModelDeviceScopeKHR = 5346, PhysicalStorageBufferAddresses = 5347, PhysicalStorageBufferAddressesEXT = 5347, ComputeDerivativeGroupLinearNV = 5350, RayTracingProvisionalKHR = 5353, CooperativeMatrixNV = 5357, FragmentShaderSampleInterlockEXT = 5363, FragmentShaderShadingRateInterlockEXT = 5372, ShaderSMBuiltinsNV = 5373, FragmentShaderPixelInterlockEXT = 5378, DemoteToHelperInvocation = 5379, DemoteToHelperInvocationEXT = 5379, RayTracingOpacityMicromapEXT = 5381, ShaderInvocationReorderNV = 5383, BindlessTextureNV = 5390, RayQueryPositionFetchKHR = 5391, SubgroupShuffleINTEL = 5568, SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, SubgroupImageMediaBlockIOINTEL = 5579, RoundToInfinityINTEL = 5582, FloatingPointModeINTEL = 5583, IntegerFunctions2INTEL = 5584, FunctionPointersINTEL = 5603, IndirectReferencesINTEL = 5604, AsmINTEL = 5606, AtomicFloat32MinMaxEXT = 5612, AtomicFloat64MinMaxEXT = 5613, AtomicFloat16MinMaxEXT = 5616, VectorComputeINTEL = 5617, VectorAnyINTEL = 5619, ExpectAssumeKHR = 5629, SubgroupAvcMotionEstimationINTEL = 5696, SubgroupAvcMotionEstimationIntraINTEL = 5697, SubgroupAvcMotionEstimationChromaINTEL = 5698, VariableLengthArrayINTEL = 5817, FunctionFloatControlINTEL = 5821, FPGAMemoryAttributesINTEL = 5824, FPFastMathModeINTEL = 5837, ArbitraryPrecisionIntegersINTEL = 5844, ArbitraryPrecisionFloatingPointINTEL = 5845, UnstructuredLoopControlsINTEL = 5886, FPGALoopControlsINTEL = 5888, KernelAttributesINTEL = 5892, FPGAKernelAttributesINTEL = 5897, FPGAMemoryAccessesINTEL = 5898, FPGAClusterAttributesINTEL = 5904, LoopFuseINTEL = 5906, FPGADSPControlINTEL = 5908, MemoryAccessAliasingINTEL = 5910, FPGAInvocationPipeliningAttributesINTEL = 5916, FPGABufferLocationINTEL = 5920, ArbitraryPrecisionFixedPointINTEL = 5922, USMStorageClassesINTEL = 5935, RuntimeAlignedAttributeINTEL = 5939, IOPipesINTEL = 5943, BlockingPipesINTEL = 5945, FPGARegINTEL = 5948, DotProductInputAll = 6016, DotProductInputAllKHR = 6016, DotProductInput4x8Bit = 6017, DotProductInput4x8BitKHR = 6017, DotProductInput4x8BitPacked = 6018, DotProductInput4x8BitPackedKHR = 6018, DotProduct = 6019, DotProductKHR = 6019, RayCullMaskKHR = 6020, BitInstructions = 6025, GroupNonUniformRotateKHR = 6026, AtomicFloat32AddEXT = 6033, AtomicFloat64AddEXT = 6034, LongConstantCompositeINTEL = 6089, OptNoneINTEL = 6094, AtomicFloat16AddEXT = 6095, DebugInfoModuleINTEL = 6114, BFloat16ConversionINTEL = 6115, SplitBarrierINTEL = 6141, FPGAKernelAttributesv2INTEL = 6161, FPGALatencyControlINTEL = 6171, FPGAArgumentInterfacesINTEL = 6174, GroupUniformArithmeticKHR = 6400, } public enum RayFlagsShift { OpaqueKHR = 0, NoOpaqueKHR = 1, TerminateOnFirstHitKHR = 2, SkipClosestHitShaderKHR = 3, CullBackFacingTrianglesKHR = 4, CullFrontFacingTrianglesKHR = 5, CullOpaqueKHR = 6, CullNoOpaqueKHR = 7, SkipTrianglesKHR = 8, SkipAABBsKHR = 9, ForceOpacityMicromap2StateEXT = 10, } public enum RayFlagsMask { MaskNone = 0, OpaqueKHR = 0x00000001, NoOpaqueKHR = 0x00000002, TerminateOnFirstHitKHR = 0x00000004, SkipClosestHitShaderKHR = 0x00000008, CullBackFacingTrianglesKHR = 0x00000010, CullFrontFacingTrianglesKHR = 0x00000020, CullOpaqueKHR = 0x00000040, CullNoOpaqueKHR = 0x00000080, SkipTrianglesKHR = 0x00000100, SkipAABBsKHR = 0x00000200, ForceOpacityMicromap2StateEXT = 0x00000400, } public enum RayQueryIntersection { RayQueryCandidateIntersectionKHR = 0, RayQueryCommittedIntersectionKHR = 1, } public enum RayQueryCommittedIntersectionType { RayQueryCommittedIntersectionNoneKHR = 0, RayQueryCommittedIntersectionTriangleKHR = 1, RayQueryCommittedIntersectionGeneratedKHR = 2, } public enum RayQueryCandidateIntersectionType { RayQueryCandidateIntersectionTriangleKHR = 0, RayQueryCandidateIntersectionAABBKHR = 1, } public enum FragmentShadingRateShift { Vertical2Pixels = 0, Vertical4Pixels = 1, Horizontal2Pixels = 2, Horizontal4Pixels = 3, } public enum FragmentShadingRateMask { MaskNone = 0, Vertical2Pixels = 0x00000001, Vertical4Pixels = 0x00000002, Horizontal2Pixels = 0x00000004, Horizontal4Pixels = 0x00000008, } public enum FPDenormMode { Preserve = 0, FlushToZero = 1, } public enum FPOperationMode { IEEE = 0, ALT = 1, } public enum QuantizationModes { TRN = 0, TRN_ZERO = 1, RND = 2, RND_ZERO = 3, RND_INF = 4, RND_MIN_INF = 5, RND_CONV = 6, RND_CONV_ODD = 7, } public enum OverflowModes { WRAP = 0, SAT = 1, SAT_ZERO = 2, SAT_SYM = 3, } public enum PackedVectorFormat { PackedVectorFormat4x8Bit = 0, PackedVectorFormat4x8BitKHR = 0, } public enum Op { OpNop = 0, OpUndef = 1, OpSourceContinued = 2, OpSource = 3, OpSourceExtension = 4, OpName = 5, OpMemberName = 6, OpString = 7, OpLine = 8, OpExtension = 10, OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, OpTypeVector = 23, OpTypeMatrix = 24, OpTypeImage = 25, OpTypeSampler = 26, OpTypeSampledImage = 27, OpTypeArray = 28, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypeOpaque = 31, OpTypePointer = 32, OpTypeFunction = 33, OpTypeEvent = 34, OpTypeDeviceEvent = 35, OpTypeReserveId = 36, OpTypeQueue = 37, OpTypePipe = 38, OpTypeForwardPointer = 39, OpConstantTrue = 41, OpConstantFalse = 42, OpConstant = 43, OpConstantComposite = 44, OpConstantSampler = 45, OpConstantNull = 46, OpSpecConstantTrue = 48, OpSpecConstantFalse = 49, OpSpecConstant = 50, OpSpecConstantComposite = 51, OpSpecConstantOp = 52, OpFunction = 54, OpFunctionParameter = 55, OpFunctionEnd = 56, OpFunctionCall = 57, OpVariable = 59, OpImageTexelPointer = 60, OpLoad = 61, OpStore = 62, OpCopyMemory = 63, OpCopyMemorySized = 64, OpAccessChain = 65, OpInBoundsAccessChain = 66, OpPtrAccessChain = 67, OpArrayLength = 68, OpGenericPtrMemSemantics = 69, OpInBoundsPtrAccessChain = 70, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, OpGroupDecorate = 74, OpGroupMemberDecorate = 75, OpVectorExtractDynamic = 77, OpVectorInsertDynamic = 78, OpVectorShuffle = 79, OpCompositeConstruct = 80, OpCompositeExtract = 81, OpCompositeInsert = 82, OpCopyObject = 83, OpTranspose = 84, OpSampledImage = 86, OpImageSampleImplicitLod = 87, OpImageSampleExplicitLod = 88, OpImageSampleDrefImplicitLod = 89, OpImageSampleDrefExplicitLod = 90, OpImageSampleProjImplicitLod = 91, OpImageSampleProjExplicitLod = 92, OpImageSampleProjDrefImplicitLod = 93, OpImageSampleProjDrefExplicitLod = 94, OpImageFetch = 95, OpImageGather = 96, OpImageDrefGather = 97, OpImageRead = 98, OpImageWrite = 99, OpImage = 100, OpImageQueryFormat = 101, OpImageQueryOrder = 102, OpImageQuerySizeLod = 103, OpImageQuerySize = 104, OpImageQueryLod = 105, OpImageQueryLevels = 106, OpImageQuerySamples = 107, OpConvertFToU = 109, OpConvertFToS = 110, OpConvertSToF = 111, OpConvertUToF = 112, OpUConvert = 113, OpSConvert = 114, OpFConvert = 115, OpQuantizeToF16 = 116, OpConvertPtrToU = 117, OpSatConvertSToU = 118, OpSatConvertUToS = 119, OpConvertUToPtr = 120, OpPtrCastToGeneric = 121, OpGenericCastToPtr = 122, OpGenericCastToPtrExplicit = 123, OpBitcast = 124, OpSNegate = 126, OpFNegate = 127, OpIAdd = 128, OpFAdd = 129, OpISub = 130, OpFSub = 131, OpIMul = 132, OpFMul = 133, OpUDiv = 134, OpSDiv = 135, OpFDiv = 136, OpUMod = 137, OpSRem = 138, OpSMod = 139, OpFRem = 140, OpFMod = 141, OpVectorTimesScalar = 142, OpMatrixTimesScalar = 143, OpVectorTimesMatrix = 144, OpMatrixTimesVector = 145, OpMatrixTimesMatrix = 146, OpOuterProduct = 147, OpDot = 148, OpIAddCarry = 149, OpISubBorrow = 150, OpUMulExtended = 151, OpSMulExtended = 152, OpAny = 154, OpAll = 155, OpIsNan = 156, OpIsInf = 157, OpIsFinite = 158, OpIsNormal = 159, OpSignBitSet = 160, OpLessOrGreater = 161, OpOrdered = 162, OpUnordered = 163, OpLogicalEqual = 164, OpLogicalNotEqual = 165, OpLogicalOr = 166, OpLogicalAnd = 167, OpLogicalNot = 168, OpSelect = 169, OpIEqual = 170, OpINotEqual = 171, OpUGreaterThan = 172, OpSGreaterThan = 173, OpUGreaterThanEqual = 174, OpSGreaterThanEqual = 175, OpULessThan = 176, OpSLessThan = 177, OpULessThanEqual = 178, OpSLessThanEqual = 179, OpFOrdEqual = 180, OpFUnordEqual = 181, OpFOrdNotEqual = 182, OpFUnordNotEqual = 183, OpFOrdLessThan = 184, OpFUnordLessThan = 185, OpFOrdGreaterThan = 186, OpFUnordGreaterThan = 187, OpFOrdLessThanEqual = 188, OpFUnordLessThanEqual = 189, OpFOrdGreaterThanEqual = 190, OpFUnordGreaterThanEqual = 191, OpShiftRightLogical = 194, OpShiftRightArithmetic = 195, OpShiftLeftLogical = 196, OpBitwiseOr = 197, OpBitwiseXor = 198, OpBitwiseAnd = 199, OpNot = 200, OpBitFieldInsert = 201, OpBitFieldSExtract = 202, OpBitFieldUExtract = 203, OpBitReverse = 204, OpBitCount = 205, OpDPdx = 207, OpDPdy = 208, OpFwidth = 209, OpDPdxFine = 210, OpDPdyFine = 211, OpFwidthFine = 212, OpDPdxCoarse = 213, OpDPdyCoarse = 214, OpFwidthCoarse = 215, OpEmitVertex = 218, OpEndPrimitive = 219, OpEmitStreamVertex = 220, OpEndStreamPrimitive = 221, OpControlBarrier = 224, OpMemoryBarrier = 225, OpAtomicLoad = 227, OpAtomicStore = 228, OpAtomicExchange = 229, OpAtomicCompareExchange = 230, OpAtomicCompareExchangeWeak = 231, OpAtomicIIncrement = 232, OpAtomicIDecrement = 233, OpAtomicIAdd = 234, OpAtomicISub = 235, OpAtomicSMin = 236, OpAtomicUMin = 237, OpAtomicSMax = 238, OpAtomicUMax = 239, OpAtomicAnd = 240, OpAtomicOr = 241, OpAtomicXor = 242, OpPhi = 245, OpLoopMerge = 246, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, OpBranchConditional = 250, OpSwitch = 251, OpKill = 252, OpReturn = 253, OpReturnValue = 254, OpUnreachable = 255, OpLifetimeStart = 256, OpLifetimeStop = 257, OpGroupAsyncCopy = 259, OpGroupWaitEvents = 260, OpGroupAll = 261, OpGroupAny = 262, OpGroupBroadcast = 263, OpGroupIAdd = 264, OpGroupFAdd = 265, OpGroupFMin = 266, OpGroupUMin = 267, OpGroupSMin = 268, OpGroupFMax = 269, OpGroupUMax = 270, OpGroupSMax = 271, OpReadPipe = 274, OpWritePipe = 275, OpReservedReadPipe = 276, OpReservedWritePipe = 277, OpReserveReadPipePackets = 278, OpReserveWritePipePackets = 279, OpCommitReadPipe = 280, OpCommitWritePipe = 281, OpIsValidReserveId = 282, OpGetNumPipePackets = 283, OpGetMaxPipePackets = 284, OpGroupReserveReadPipePackets = 285, OpGroupReserveWritePipePackets = 286, OpGroupCommitReadPipe = 287, OpGroupCommitWritePipe = 288, OpEnqueueMarker = 291, OpEnqueueKernel = 292, OpGetKernelNDrangeSubGroupCount = 293, OpGetKernelNDrangeMaxSubGroupSize = 294, OpGetKernelWorkGroupSize = 295, OpGetKernelPreferredWorkGroupSizeMultiple = 296, OpRetainEvent = 297, OpReleaseEvent = 298, OpCreateUserEvent = 299, OpIsValidEvent = 300, OpSetUserEventStatus = 301, OpCaptureEventProfilingInfo = 302, OpGetDefaultQueue = 303, OpBuildNDRange = 304, OpImageSparseSampleImplicitLod = 305, OpImageSparseSampleExplicitLod = 306, OpImageSparseSampleDrefImplicitLod = 307, OpImageSparseSampleDrefExplicitLod = 308, OpImageSparseSampleProjImplicitLod = 309, OpImageSparseSampleProjExplicitLod = 310, OpImageSparseSampleProjDrefImplicitLod = 311, OpImageSparseSampleProjDrefExplicitLod = 312, OpImageSparseFetch = 313, OpImageSparseGather = 314, OpImageSparseDrefGather = 315, OpImageSparseTexelsResident = 316, OpNoLine = 317, OpAtomicFlagTestAndSet = 318, OpAtomicFlagClear = 319, OpImageSparseRead = 320, OpSizeOf = 321, OpTypePipeStorage = 322, OpConstantPipeStorage = 323, OpCreatePipeFromPipeStorage = 324, OpGetKernelLocalSizeForSubgroupCount = 325, OpGetKernelMaxNumSubgroups = 326, OpTypeNamedBarrier = 327, OpNamedBarrierInitialize = 328, OpMemoryNamedBarrier = 329, OpModuleProcessed = 330, OpExecutionModeId = 331, OpDecorateId = 332, OpGroupNonUniformElect = 333, OpGroupNonUniformAll = 334, OpGroupNonUniformAny = 335, OpGroupNonUniformAllEqual = 336, OpGroupNonUniformBroadcast = 337, OpGroupNonUniformBroadcastFirst = 338, OpGroupNonUniformBallot = 339, OpGroupNonUniformInverseBallot = 340, OpGroupNonUniformBallotBitExtract = 341, OpGroupNonUniformBallotBitCount = 342, OpGroupNonUniformBallotFindLSB = 343, OpGroupNonUniformBallotFindMSB = 344, OpGroupNonUniformShuffle = 345, OpGroupNonUniformShuffleXor = 346, OpGroupNonUniformShuffleUp = 347, OpGroupNonUniformShuffleDown = 348, OpGroupNonUniformIAdd = 349, OpGroupNonUniformFAdd = 350, OpGroupNonUniformIMul = 351, OpGroupNonUniformFMul = 352, OpGroupNonUniformSMin = 353, OpGroupNonUniformUMin = 354, OpGroupNonUniformFMin = 355, OpGroupNonUniformSMax = 356, OpGroupNonUniformUMax = 357, OpGroupNonUniformFMax = 358, OpGroupNonUniformBitwiseAnd = 359, OpGroupNonUniformBitwiseOr = 360, OpGroupNonUniformBitwiseXor = 361, OpGroupNonUniformLogicalAnd = 362, OpGroupNonUniformLogicalOr = 363, OpGroupNonUniformLogicalXor = 364, OpGroupNonUniformQuadBroadcast = 365, OpGroupNonUniformQuadSwap = 366, OpCopyLogical = 400, OpPtrEqual = 401, OpPtrNotEqual = 402, OpPtrDiff = 403, OpColorAttachmentReadEXT = 4160, OpDepthAttachmentReadEXT = 4161, OpStencilAttachmentReadEXT = 4162, OpTerminateInvocation = 4416, OpSubgroupBallotKHR = 4421, OpSubgroupFirstInvocationKHR = 4422, OpSubgroupAllKHR = 4428, OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpGroupNonUniformRotateKHR = 4431, OpSubgroupReadInvocationKHR = 4432, OpTraceRayKHR = 4445, OpExecuteCallableKHR = 4446, OpConvertUToAccelerationStructureKHR = 4447, OpIgnoreIntersectionKHR = 4448, OpTerminateRayKHR = 4449, OpSDot = 4450, OpSDotKHR = 4450, OpUDot = 4451, OpUDotKHR = 4451, OpSUDot = 4452, OpSUDotKHR = 4452, OpSDotAccSat = 4453, OpSDotAccSatKHR = 4453, OpUDotAccSat = 4454, OpUDotAccSatKHR = 4454, OpSUDotAccSat = 4455, OpSUDotAccSatKHR = 4455, OpTypeRayQueryKHR = 4472, OpRayQueryInitializeKHR = 4473, OpRayQueryTerminateKHR = 4474, OpRayQueryGenerateIntersectionKHR = 4475, OpRayQueryConfirmIntersectionKHR = 4476, OpRayQueryProceedKHR = 4477, OpRayQueryGetIntersectionTypeKHR = 4479, OpImageSampleWeightedQCOM = 4480, OpImageBoxFilterQCOM = 4481, OpImageBlockMatchSSDQCOM = 4482, OpImageBlockMatchSADQCOM = 4483, OpGroupIAddNonUniformAMD = 5000, OpGroupFAddNonUniformAMD = 5001, OpGroupFMinNonUniformAMD = 5002, OpGroupUMinNonUniformAMD = 5003, OpGroupSMinNonUniformAMD = 5004, OpGroupFMaxNonUniformAMD = 5005, OpGroupUMaxNonUniformAMD = 5006, OpGroupSMaxNonUniformAMD = 5007, OpFragmentMaskFetchAMD = 5011, OpFragmentFetchAMD = 5012, OpReadClockKHR = 5056, OpHitObjectRecordHitMotionNV = 5249, OpHitObjectRecordHitWithIndexMotionNV = 5250, OpHitObjectRecordMissMotionNV = 5251, OpHitObjectGetWorldToObjectNV = 5252, OpHitObjectGetObjectToWorldNV = 5253, OpHitObjectGetObjectRayDirectionNV = 5254, OpHitObjectGetObjectRayOriginNV = 5255, OpHitObjectTraceRayMotionNV = 5256, OpHitObjectGetShaderRecordBufferHandleNV = 5257, OpHitObjectGetShaderBindingTableRecordIndexNV = 5258, OpHitObjectRecordEmptyNV = 5259, OpHitObjectTraceRayNV = 5260, OpHitObjectRecordHitNV = 5261, OpHitObjectRecordHitWithIndexNV = 5262, OpHitObjectRecordMissNV = 5263, OpHitObjectExecuteShaderNV = 5264, OpHitObjectGetCurrentTimeNV = 5265, OpHitObjectGetAttributesNV = 5266, OpHitObjectGetHitKindNV = 5267, OpHitObjectGetPrimitiveIndexNV = 5268, OpHitObjectGetGeometryIndexNV = 5269, OpHitObjectGetInstanceIdNV = 5270, OpHitObjectGetInstanceCustomIndexNV = 5271, OpHitObjectGetWorldRayDirectionNV = 5272, OpHitObjectGetWorldRayOriginNV = 5273, OpHitObjectGetRayTMaxNV = 5274, OpHitObjectGetRayTMinNV = 5275, OpHitObjectIsEmptyNV = 5276, OpHitObjectIsHitNV = 5277, OpHitObjectIsMissNV = 5278, OpReorderThreadWithHitObjectNV = 5279, OpReorderThreadWithHintNV = 5280, OpTypeHitObjectNV = 5281, OpImageSampleFootprintNV = 5283, OpEmitMeshTasksEXT = 5294, OpSetMeshOutputsEXT = 5295, OpGroupNonUniformPartitionNV = 5296, OpWritePackedPrimitiveIndices4x8NV = 5299, OpReportIntersectionKHR = 5334, OpReportIntersectionNV = 5334, OpIgnoreIntersectionNV = 5335, OpTerminateRayNV = 5336, OpTraceNV = 5337, OpTraceMotionNV = 5338, OpTraceRayMotionNV = 5339, OpRayQueryGetIntersectionTriangleVertexPositionsKHR = 5340, OpTypeAccelerationStructureKHR = 5341, OpTypeAccelerationStructureNV = 5341, OpExecuteCallableNV = 5344, OpTypeCooperativeMatrixNV = 5358, OpCooperativeMatrixLoadNV = 5359, OpCooperativeMatrixStoreNV = 5360, OpCooperativeMatrixMulAddNV = 5361, OpCooperativeMatrixLengthNV = 5362, OpBeginInvocationInterlockEXT = 5364, OpEndInvocationInterlockEXT = 5365, OpDemoteToHelperInvocation = 5380, OpDemoteToHelperInvocationEXT = 5380, OpIsHelperInvocationEXT = 5381, OpConvertUToImageNV = 5391, OpConvertUToSamplerNV = 5392, OpConvertImageToUNV = 5393, OpConvertSamplerToUNV = 5394, OpConvertUToSampledImageNV = 5395, OpConvertSampledImageToUNV = 5396, OpSamplerImageAddressingModeNV = 5397, OpSubgroupShuffleINTEL = 5571, OpSubgroupShuffleDownINTEL = 5572, OpSubgroupShuffleUpINTEL = 5573, OpSubgroupShuffleXorINTEL = 5574, OpSubgroupBlockReadINTEL = 5575, OpSubgroupBlockWriteINTEL = 5576, OpSubgroupImageBlockReadINTEL = 5577, OpSubgroupImageBlockWriteINTEL = 5578, OpSubgroupImageMediaBlockReadINTEL = 5580, OpSubgroupImageMediaBlockWriteINTEL = 5581, OpUCountLeadingZerosINTEL = 5585, OpUCountTrailingZerosINTEL = 5586, OpAbsISubINTEL = 5587, OpAbsUSubINTEL = 5588, OpIAddSatINTEL = 5589, OpUAddSatINTEL = 5590, OpIAverageINTEL = 5591, OpUAverageINTEL = 5592, OpIAverageRoundedINTEL = 5593, OpUAverageRoundedINTEL = 5594, OpISubSatINTEL = 5595, OpUSubSatINTEL = 5596, OpIMul32x16INTEL = 5597, OpUMul32x16INTEL = 5598, OpConstantFunctionPointerINTEL = 5600, OpFunctionPointerCallINTEL = 5601, OpAsmTargetINTEL = 5609, OpAsmINTEL = 5610, OpAsmCallINTEL = 5611, OpAtomicFMinEXT = 5614, OpAtomicFMaxEXT = 5615, OpAssumeTrueKHR = 5630, OpExpectKHR = 5631, OpDecorateString = 5632, OpDecorateStringGOOGLE = 5632, OpMemberDecorateString = 5633, OpMemberDecorateStringGOOGLE = 5633, OpVmeImageINTEL = 5699, OpTypeVmeImageINTEL = 5700, OpTypeAvcImePayloadINTEL = 5701, OpTypeAvcRefPayloadINTEL = 5702, OpTypeAvcSicPayloadINTEL = 5703, OpTypeAvcMcePayloadINTEL = 5704, OpTypeAvcMceResultINTEL = 5705, OpTypeAvcImeResultINTEL = 5706, OpTypeAvcImeResultSingleReferenceStreamoutINTEL = 5707, OpTypeAvcImeResultDualReferenceStreamoutINTEL = 5708, OpTypeAvcImeSingleReferenceStreaminINTEL = 5709, OpTypeAvcImeDualReferenceStreaminINTEL = 5710, OpTypeAvcRefResultINTEL = 5711, OpTypeAvcSicResultINTEL = 5712, OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = 5713, OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = 5714, OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL = 5715, OpSubgroupAvcMceSetInterShapePenaltyINTEL = 5716, OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = 5717, OpSubgroupAvcMceSetInterDirectionPenaltyINTEL = 5718, OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = 5719, OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = 5720, OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = 5721, OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = 5722, OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = 5723, OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL = 5724, OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = 5725, OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = 5726, OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = 5727, OpSubgroupAvcMceSetAcOnlyHaarINTEL = 5728, OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = 5729, OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = 5730, OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = 5731, OpSubgroupAvcMceConvertToImePayloadINTEL = 5732, OpSubgroupAvcMceConvertToImeResultINTEL = 5733, OpSubgroupAvcMceConvertToRefPayloadINTEL = 5734, OpSubgroupAvcMceConvertToRefResultINTEL = 5735, OpSubgroupAvcMceConvertToSicPayloadINTEL = 5736, OpSubgroupAvcMceConvertToSicResultINTEL = 5737, OpSubgroupAvcMceGetMotionVectorsINTEL = 5738, OpSubgroupAvcMceGetInterDistortionsINTEL = 5739, OpSubgroupAvcMceGetBestInterDistortionsINTEL = 5740, OpSubgroupAvcMceGetInterMajorShapeINTEL = 5741, OpSubgroupAvcMceGetInterMinorShapeINTEL = 5742, OpSubgroupAvcMceGetInterDirectionsINTEL = 5743, OpSubgroupAvcMceGetInterMotionVectorCountINTEL = 5744, OpSubgroupAvcMceGetInterReferenceIdsINTEL = 5745, OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = 5746, OpSubgroupAvcImeInitializeINTEL = 5747, OpSubgroupAvcImeSetSingleReferenceINTEL = 5748, OpSubgroupAvcImeSetDualReferenceINTEL = 5749, OpSubgroupAvcImeRefWindowSizeINTEL = 5750, OpSubgroupAvcImeAdjustRefOffsetINTEL = 5751, OpSubgroupAvcImeConvertToMcePayloadINTEL = 5752, OpSubgroupAvcImeSetMaxMotionVectorCountINTEL = 5753, OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL = 5754, OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = 5755, OpSubgroupAvcImeSetWeightedSadINTEL = 5756, OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL = 5757, OpSubgroupAvcImeEvaluateWithDualReferenceINTEL = 5758, OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = 5759, OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = 5760, OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = 5761, OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = 5762, OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = 5763, OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = 5764, OpSubgroupAvcImeConvertToMceResultINTEL = 5765, OpSubgroupAvcImeGetSingleReferenceStreaminINTEL = 5766, OpSubgroupAvcImeGetDualReferenceStreaminINTEL = 5767, OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL = 5768, OpSubgroupAvcImeStripDualReferenceStreamoutINTEL = 5769, OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = 5770, OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = 5771, OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = 5772, OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = 5773, OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = 5774, OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = 5775, OpSubgroupAvcImeGetBorderReachedINTEL = 5776, OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL = 5777, OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = 5778, OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = 5779, OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = 5780, OpSubgroupAvcFmeInitializeINTEL = 5781, OpSubgroupAvcBmeInitializeINTEL = 5782, OpSubgroupAvcRefConvertToMcePayloadINTEL = 5783, OpSubgroupAvcRefSetBidirectionalMixDisableINTEL = 5784, OpSubgroupAvcRefSetBilinearFilterEnableINTEL = 5785, OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL = 5786, OpSubgroupAvcRefEvaluateWithDualReferenceINTEL = 5787, OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL = 5788, OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = 5789, OpSubgroupAvcRefConvertToMceResultINTEL = 5790, OpSubgroupAvcSicInitializeINTEL = 5791, OpSubgroupAvcSicConfigureSkcINTEL = 5792, OpSubgroupAvcSicConfigureIpeLumaINTEL = 5793, OpSubgroupAvcSicConfigureIpeLumaChromaINTEL = 5794, OpSubgroupAvcSicGetMotionVectorMaskINTEL = 5795, OpSubgroupAvcSicConvertToMcePayloadINTEL = 5796, OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL = 5797, OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = 5798, OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = 5799, OpSubgroupAvcSicSetBilinearFilterEnableINTEL = 5800, OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL = 5801, OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL = 5802, OpSubgroupAvcSicEvaluateIpeINTEL = 5803, OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL = 5804, OpSubgroupAvcSicEvaluateWithDualReferenceINTEL = 5805, OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL = 5806, OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = 5807, OpSubgroupAvcSicConvertToMceResultINTEL = 5808, OpSubgroupAvcSicGetIpeLumaShapeINTEL = 5809, OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL = 5810, OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL = 5811, OpSubgroupAvcSicGetPackedIpeLumaModesINTEL = 5812, OpSubgroupAvcSicGetIpeChromaModeINTEL = 5813, OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, OpSubgroupAvcSicGetInterRawSadsINTEL = 5816, OpVariableLengthArrayINTEL = 5818, OpSaveMemoryINTEL = 5819, OpRestoreMemoryINTEL = 5820, OpArbitraryFloatSinCosPiINTEL = 5840, OpArbitraryFloatCastINTEL = 5841, OpArbitraryFloatCastFromIntINTEL = 5842, OpArbitraryFloatCastToIntINTEL = 5843, OpArbitraryFloatAddINTEL = 5846, OpArbitraryFloatSubINTEL = 5847, OpArbitraryFloatMulINTEL = 5848, OpArbitraryFloatDivINTEL = 5849, OpArbitraryFloatGTINTEL = 5850, OpArbitraryFloatGEINTEL = 5851, OpArbitraryFloatLTINTEL = 5852, OpArbitraryFloatLEINTEL = 5853, OpArbitraryFloatEQINTEL = 5854, OpArbitraryFloatRecipINTEL = 5855, OpArbitraryFloatRSqrtINTEL = 5856, OpArbitraryFloatCbrtINTEL = 5857, OpArbitraryFloatHypotINTEL = 5858, OpArbitraryFloatSqrtINTEL = 5859, OpArbitraryFloatLogINTEL = 5860, OpArbitraryFloatLog2INTEL = 5861, OpArbitraryFloatLog10INTEL = 5862, OpArbitraryFloatLog1pINTEL = 5863, OpArbitraryFloatExpINTEL = 5864, OpArbitraryFloatExp2INTEL = 5865, OpArbitraryFloatExp10INTEL = 5866, OpArbitraryFloatExpm1INTEL = 5867, OpArbitraryFloatSinINTEL = 5868, OpArbitraryFloatCosINTEL = 5869, OpArbitraryFloatSinCosINTEL = 5870, OpArbitraryFloatSinPiINTEL = 5871, OpArbitraryFloatCosPiINTEL = 5872, OpArbitraryFloatASinINTEL = 5873, OpArbitraryFloatASinPiINTEL = 5874, OpArbitraryFloatACosINTEL = 5875, OpArbitraryFloatACosPiINTEL = 5876, OpArbitraryFloatATanINTEL = 5877, OpArbitraryFloatATanPiINTEL = 5878, OpArbitraryFloatATan2INTEL = 5879, OpArbitraryFloatPowINTEL = 5880, OpArbitraryFloatPowRINTEL = 5881, OpArbitraryFloatPowNINTEL = 5882, OpLoopControlINTEL = 5887, OpAliasDomainDeclINTEL = 5911, OpAliasScopeDeclINTEL = 5912, OpAliasScopeListDeclINTEL = 5913, OpFixedSqrtINTEL = 5923, OpFixedRecipINTEL = 5924, OpFixedRsqrtINTEL = 5925, OpFixedSinINTEL = 5926, OpFixedCosINTEL = 5927, OpFixedSinCosINTEL = 5928, OpFixedSinPiINTEL = 5929, OpFixedCosPiINTEL = 5930, OpFixedSinCosPiINTEL = 5931, OpFixedLogINTEL = 5932, OpFixedExpINTEL = 5933, OpPtrCastToCrossWorkgroupINTEL = 5934, OpCrossWorkgroupCastToPtrINTEL = 5938, OpReadPipeBlockingINTEL = 5946, OpWritePipeBlockingINTEL = 5947, OpFPGARegINTEL = 5949, OpRayQueryGetRayTMinKHR = 6016, OpRayQueryGetRayFlagsKHR = 6017, OpRayQueryGetIntersectionTKHR = 6018, OpRayQueryGetIntersectionInstanceCustomIndexKHR = 6019, OpRayQueryGetIntersectionInstanceIdKHR = 6020, OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR = 6021, OpRayQueryGetIntersectionGeometryIndexKHR = 6022, OpRayQueryGetIntersectionPrimitiveIndexKHR = 6023, OpRayQueryGetIntersectionBarycentricsKHR = 6024, OpRayQueryGetIntersectionFrontFaceKHR = 6025, OpRayQueryGetIntersectionCandidateAABBOpaqueKHR = 6026, OpRayQueryGetIntersectionObjectRayDirectionKHR = 6027, OpRayQueryGetIntersectionObjectRayOriginKHR = 6028, OpRayQueryGetWorldRayDirectionKHR = 6029, OpRayQueryGetWorldRayOriginKHR = 6030, OpRayQueryGetIntersectionObjectToWorldKHR = 6031, OpRayQueryGetIntersectionWorldToObjectKHR = 6032, OpAtomicFAddEXT = 6035, OpTypeBufferSurfaceINTEL = 6086, OpTypeStructContinuedINTEL = 6090, OpConstantCompositeContinuedINTEL = 6091, OpSpecConstantCompositeContinuedINTEL = 6092, OpConvertFToBF16INTEL = 6116, OpConvertBF16ToFINTEL = 6117, OpControlBarrierArriveINTEL = 6142, OpControlBarrierWaitINTEL = 6143, OpGroupIMulKHR = 6401, OpGroupFMulKHR = 6402, OpGroupBitwiseAndKHR = 6403, OpGroupBitwiseOrKHR = 6404, OpGroupBitwiseXorKHR = 6405, OpGroupLogicalAndKHR = 6406, OpGroupLogicalOrKHR = 6407, OpGroupLogicalXorKHR = 6408, } } }
2,000
ThreatExchange
facebook
C#
// Copyright (c) Meta Platforms, Inc. and affiliates. // See https://aka.ms/new-console-template for more information //create object of chrome options using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using WebAssemblySeleniumWebDriver.Services; using WebDriverManager; using WebDriverManager.DriverConfigs.Impl; Boolean runInChrome = true; Boolean isPDQMD5 = true; String csvFilePath = String.Empty; String siteUrl = String.Empty; // Check if command line arguments are passed. if (args == null || args.Length < 1) { Console.WriteLine("Please pass all the required command line arguments"); return; } runInChrome = args[0].ToLower() == "chrome"; isPDQMD5 = args[1].ToLower() == "pdqmd5"; // Validate if all required parameters are passed. if ((isPDQMD5 && args?.Length < 3) || (!isPDQMD5 && args?.Length < 4)) { Console.WriteLine("Please pass all the required command line arguments"); return; } csvFilePath = args!=null ? args[2]:""; if (isPDQMD5) { siteUrl = args?.Length > 3 ? args[3] : "http://localhost:9093"; } try { IWebDriver driver; if (runInChrome) { new DriverManager().SetUpDriver(new ChromeConfig()); ChromeOptions options = new ChromeOptions(); // Set the options to run chrome browser in headless mode . For both PDQ and TMK hash testing we will be running browser in // headless mode. options.AddArguments("headless"); driver = new ChromeDriver(options); } else { //new DriverManager().SetUpDriver(new FirefoxConfig()); FirefoxOptions options = new FirefoxOptions(); // Set the options to run chrome browser in headless mode . For both PDQ and TMK hash testing we will be running browser in // headless mode. options.AddArguments("--headless"); driver = new FirefoxDriver($"{Environment.CurrentDirectory}/Resources/Drivers/Firefox",options); } if (isPDQMD5) { PDQMD5Hashing.GetHash(driver,csvFilePath,siteUrl); } else { Console.WriteLine("Please verify the command line arguments values are passed in correctly."); } // Quits the driver instance to close the webdriver session driver.Quit(); } catch (Exception ex) { Console.WriteLine($"Error occured while executing program execution. Error Message : {ex.Message}"); }
73
ThreatExchange
facebook
C#
// Copyright (c) Meta Platforms, Inc. and affiliates. using OpenQA.Selenium; namespace WebAssemblySeleniumWebDriver.Services { public class PDQMD5Hashing { /// <summary> /// This method is used for passing the filenames whose PDQ/MD5 hash needs to be generated by reading the information from the CSV file. /// </summary> /// <param name="driver"></param> /// <param name="csvFilePath"></param> /// <param name="siteUrl"></param> public static void GetHash(IWebDriver driver,string csvFilePath,string siteUrl) { if (String.IsNullOrWhiteSpace(csvFilePath) || String.IsNullOrWhiteSpace(siteUrl)) { Console.WriteLine("Some of the required parameters of GetHash method are missing"); return; } try { driver.Navigate().GoToUrl(siteUrl); // Verify if a proper csv filepath which contains the file with hash information is passed. if (!File.Exists(csvFilePath)) { Console.WriteLine($"{csvFilePath} path doesn't exist in the system. Please pass in a valid csv file path."); return; } // Added a forceful delay of 10 seconds to avoid errors . Thread.Sleep(10000); StreamReader reader = new StreamReader(csvFilePath); string? line = String.Empty; string[] columns = new string[2]; String filePath = String.Empty; reader.ReadLine(); // skip first int csvFileLineCount = 0; int filesSentForProcessing = 0; Dictionary<string,string> fileInfo = new Dictionary<string,string>(); while ((line = reader.ReadLine()) != null) { columns = line.Split(','); csvFileLineCount++; if (columns.Length < 2) { Console.WriteLine($"Please verify all the required details are entered for item no {csvFileLineCount} in {csvFilePath}."); continue; } filePath = columns[0]; // Check if the file path specified is absolute path , if not get the relative path specified in the file with respect to the current working directory. if (!Path.IsPathRooted(filePath)) { filePath = Path.GetFullPath(Path.Combine(new DirectoryInfo(Environment.CurrentDirectory).FullName ?? String.Empty,filePath)); } if (!File.Exists(filePath)) { Console.WriteLine($"{filePath} filepath doesn't exists in the system.Please specify a valid file path in the csv file."); continue; } var element = driver.FindElement(By.Id("myfile")); element.SendKeys(filePath); filesSentForProcessing++; if (!fileInfo.ContainsKey(Path.GetFileName(filePath))) { fileInfo.Add(Path.GetFileName(filePath),columns[1]); } } var rows = driver.FindElements(By.CssSelector("tbody tr")); int rws_cnt = rows.Count; int attempts = 0; // Loop through until all the files are processed and the hashes are displayed. while((rws_cnt < filesSentForProcessing) && attempts<5000) { rows = driver.FindElements(By.CssSelector("tbody tr")); rws_cnt = rows.Count; attempts++; } //Iterate rows of table for (int i = 0; i < rws_cnt; i++) { var cols = rows[i].FindElements(By.TagName("td")); if (cols.Count > 2) { if (String.Equals(fileInfo[cols[0].Text],cols[1].Text,StringComparison.OrdinalIgnoreCase)) { Console.WriteLine($"Generated Hash for file {cols[0].Text} is {cols[1].Text} and is matching with the Hash value specified in CSV file."); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Generated Hash for file {cols[0].Text} is {cols[1].Text} and is not matching with the Hash value specified in CSV file."); Console.ResetColor(); } } else if (cols.Count == 1) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{cols[0].Text}."); Console.ResetColor(); } } } catch (Exception ex) { Console.WriteLine($"Error in GetHash method. Error Message - {ex.Message} , csvFilePath - {csvFilePath}, siteUrl - {siteUrl}"); } } } }
109
ThreatExchange
facebook
C#
// Copyright (c) Meta Platforms, Inc. and affiliates. namespace WebAssemblySeleniumWebDriver.Utils { public class FileUtils { // This method accepts two strings the represent two files to // compare. A return value of 0 indicates that the contents of the files // are the same. A return value of any other value indicates that the // files are not the same. public static bool FileCompare(string file1,string file2) { int file1byte; int file2byte; FileStream fs1; FileStream fs2; // Determine if the same file was referenced two times. if (file1 == file2) { // Return true to indicate that the files are the same. return true; } // Open the two files. fs1 = new FileStream(file1,FileMode.Open); fs2 = new FileStream(file2,FileMode.Open); // Check the file sizes. If they are not the same, the files // are not the same. if (fs1.Length != fs2.Length) { // Close the file fs1.Close(); fs2.Close(); // Return false to indicate files are different return false; } // Read and compare a byte from each file until either a // non-matching set of bytes is found or until the end of // file1 is reached. do { // Read one byte from each file. file1byte = fs1.ReadByte(); file2byte = fs2.ReadByte(); } while ((file1byte == file2byte) && (file1byte != -1)); // Close the files. fs1.Close(); fs2.Close(); // Return the success of the comparison. "file1byte" is // equal to "file2byte" at this point only if the files are // the same. return ((file1byte - file2byte) == 0); } } }
57
ml-agents
openai
C#
using UnityEngine; using UnityEditor; namespace MLAgents { /* This code is meant to modify the behavior of the inspector on Brain Components. Depending on the type of brain that is used, the available fields will be modified in the inspector accordingly. */ [CustomEditor(typeof(Agent), true)] [CanEditMultipleObjects] public class AgentEditor : Editor { public override void OnInspectorGUI() { var serializedAgent = serializedObject; serializedAgent.Update(); var brain = serializedAgent.FindProperty("brain"); var actionsPerDecision = serializedAgent.FindProperty( "agentParameters.numberOfActionsBetweenDecisions"); var maxSteps = serializedAgent.FindProperty( "agentParameters.maxStep"); var isResetOnDone = serializedAgent.FindProperty( "agentParameters.resetOnDone"); var isOdd = serializedAgent.FindProperty( "agentParameters.onDemandDecision"); var cameras = serializedAgent.FindProperty( "agentParameters.agentCameras"); var renderTextures = serializedAgent.FindProperty( "agentParameters.agentRenderTextures"); EditorGUILayout.PropertyField(brain); if (cameras.arraySize > 0 && renderTextures.arraySize > 0) { EditorGUILayout.HelpBox("Brain visual observations created by first getting all cameras then all render textures.", MessageType.Info); } EditorGUILayout.LabelField("Agent Cameras"); for (var i = 0; i < cameras.arraySize; i++) { EditorGUILayout.PropertyField( cameras.GetArrayElementAtIndex(i), new GUIContent("Camera " + (i + 1) + ": ")); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add Camera", EditorStyles.miniButton)) { cameras.arraySize++; } if (GUILayout.Button("Remove Camera", EditorStyles.miniButton)) { cameras.arraySize--; } EditorGUILayout.EndHorizontal(); EditorGUILayout.LabelField("Agent RenderTextures"); for (var i = 0; i < renderTextures.arraySize; i++) { EditorGUILayout.PropertyField( renderTextures.GetArrayElementAtIndex(i), new GUIContent("RenderTexture " + (i + 1) + ": ")); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add RenderTextures", EditorStyles.miniButton)) { renderTextures.arraySize++; } if (GUILayout.Button("Remove RenderTextures", EditorStyles.miniButton)) { renderTextures.arraySize--; } EditorGUILayout.EndHorizontal(); EditorGUILayout.PropertyField( maxSteps, new GUIContent( "Max Step", "The per-agent maximum number of steps.")); EditorGUILayout.PropertyField( isResetOnDone, new GUIContent( "Reset On Done", "If checked, the agent will reset on done. Else, AgentOnDone() will be called.")); EditorGUILayout.PropertyField( isOdd, new GUIContent( "On Demand Decisions", "If checked, you must manually request decisions.")); if (!isOdd.boolValue) { EditorGUILayout.PropertyField( actionsPerDecision, new GUIContent( "Decision Interval", "The agent will automatically request a decision every X" + " steps and perform an action at every step.")); actionsPerDecision.intValue = Mathf.Max(1, actionsPerDecision.intValue); } serializedAgent.ApplyModifiedProperties(); EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); base.OnInspectorGUI(); } } }
115
ml-agents
openai
C#
using UnityEngine; using UnityEditor; namespace MLAgents { /// <summary> /// CustomEditor for the Brain base class. Defines the default Inspector view for a Brain. /// Shows the BrainParameters of the Brain and expose a tool to deep copy BrainParameters /// between brains. /// </summary> [CustomEditor(typeof(Brain))] public class BrainEditor : Editor { public override void OnInspectorGUI() { var brain = (Brain)target; var brainToCopy = EditorGUILayout.ObjectField( "Copy Brain Parameters from : ", null, typeof(Brain), false) as Brain; if (brainToCopy != null) { brain.brainParameters = brainToCopy.brainParameters.Clone(); EditorUtility.SetDirty(brain); AssetDatabase.SaveAssets(); return; } var serializedBrain = serializedObject; serializedBrain.Update(); EditorGUILayout.PropertyField(serializedBrain.FindProperty("brainParameters"), true); serializedBrain.ApplyModifiedProperties(); // Draws a horizontal thick line EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); } } }
37
ml-agents
openai
C#
using UnityEngine; using UnityEditor; namespace MLAgents { /// <summary> /// PropertyDrawer for BrainParameters. Defines how BrainParameters are displayed in the /// Inspector. /// </summary> [CustomPropertyDrawer(typeof(BrainParameters))] public class BrainParametersDrawer : PropertyDrawer { // The height of a line in the Unity Inspectors private const float k_LineHeight = 17f; private const int k_VecObsNumLine = 3; private const string k_CamResPropName = "cameraResolutions"; private const string k_ActionSizePropName = "vectorActionSize"; private const string k_ActionTypePropName = "vectorActionSpaceType"; private const string k_ActionDescriptionPropName = "vectorActionDescriptions"; private const string k_VecObsPropName = "vectorObservationSize"; private const string k_NumVecObsPropName = "numStackedVectorObservations"; private const string k_CamWidthPropName = "width"; private const string k_CamHeightPropName = "height"; private const string k_CamGrayPropName = "blackAndWhite"; private const int k_DefaultCameraWidth = 84; private const int k_DefaultCameraHeight = 84; private const bool k_DefaultCameraGray = false; /// <inheritdoc /> public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { if (property.isExpanded) { return k_LineHeight + GetHeightDrawVectorObservation() + GetHeightDrawVisualObservation(property) + GetHeightDrawVectorAction(property) + GetHeightDrawVectorActionDescriptions(property); } return k_LineHeight; } /// <inheritdoc /> public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; position.height = k_LineHeight; property.isExpanded = EditorGUI.Foldout(position, property.isExpanded, label); position.y += k_LineHeight; if (property.isExpanded) { EditorGUI.BeginProperty(position, label, property); EditorGUI.indentLevel++; // Vector Observations DrawVectorObservation(position, property); position.y += GetHeightDrawVectorObservation(); //Visual Observations DrawVisualObservations(position, property); position.y += GetHeightDrawVisualObservation(property); // Vector Action DrawVectorAction(position, property); position.y += GetHeightDrawVectorAction(property); // Vector Action Descriptions DrawVectorActionDescriptions(position, property); position.y += GetHeightDrawVectorActionDescriptions(property); EditorGUI.EndProperty(); } EditorGUI.indentLevel = indent; } /// <summary> /// Draws the Vector Observations for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> private static void DrawVectorObservation(Rect position, SerializedProperty property) { EditorGUI.LabelField(position, "Vector Observation"); position.y += k_LineHeight; EditorGUI.indentLevel++; EditorGUI.PropertyField(position, property.FindPropertyRelative(k_VecObsPropName), new GUIContent("Space Size", "Length of state " + "vector for brain (In Continuous state space)." + "Or number of possible values (in Discrete state space).")); position.y += k_LineHeight; EditorGUI.PropertyField(position, property.FindPropertyRelative(k_NumVecObsPropName), new GUIContent("Stacked Vectors", "Number of states that will be stacked before " + "being fed to the neural network.")); position.y += k_LineHeight; EditorGUI.indentLevel--; } /// <summary> /// The Height required to draw the Vector Observations paramaters /// </summary> /// <returns>The height of the drawer of the Vector Observations </returns> private static float GetHeightDrawVectorObservation() { return k_VecObsNumLine * k_LineHeight; } /// <summary> /// Draws the Visual Observations parameters for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> private static void DrawVisualObservations(Rect position, SerializedProperty property) { EditorGUI.LabelField(position, "Visual Observations"); position.y += k_LineHeight; var quarter = position.width / 4; var resolutions = property.FindPropertyRelative(k_CamResPropName); DrawVisualObsButtons(position, resolutions); position.y += k_LineHeight; // Display the labels for the columns : Index, Width, Height and Gray var indexRect = new Rect(position.x, position.y, quarter, position.height); var widthRect = new Rect(position.x + quarter, position.y, quarter, position.height); var heightRect = new Rect(position.x + 2 * quarter, position.y, quarter, position.height); var bwRect = new Rect(position.x + 3 * quarter, position.y, quarter, position.height); EditorGUI.indentLevel++; if (resolutions.arraySize > 0) { EditorGUI.LabelField(indexRect, "Index"); indexRect.y += k_LineHeight; EditorGUI.LabelField(widthRect, "Width"); widthRect.y += k_LineHeight; EditorGUI.LabelField(heightRect, "Height"); heightRect.y += k_LineHeight; EditorGUI.LabelField(bwRect, "Gray"); bwRect.y += k_LineHeight; } // Iterate over the resolutions for (var i = 0; i < resolutions.arraySize; i++) { EditorGUI.LabelField(indexRect, "Obs " + i); indexRect.y += k_LineHeight; var res = resolutions.GetArrayElementAtIndex(i); var w = res.FindPropertyRelative("width"); w.intValue = EditorGUI.IntField(widthRect, w.intValue); widthRect.y += k_LineHeight; var h = res.FindPropertyRelative("height"); h.intValue = EditorGUI.IntField(heightRect, h.intValue); heightRect.y += k_LineHeight; var bw = res.FindPropertyRelative("blackAndWhite"); bw.boolValue = EditorGUI.Toggle(bwRect, bw.boolValue); bwRect.y += k_LineHeight; } EditorGUI.indentLevel--; } /// <summary> /// Draws the buttons to add and remove the visual observations parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="resolutions">The SerializedProperty of the resolution array /// to make the custom GUI for.</param> private static void DrawVisualObsButtons(Rect position, SerializedProperty resolutions) { var widthEighth = position.width / 8; var addButtonRect = new Rect(position.x + widthEighth, position.y, 3 * widthEighth, position.height); var removeButtonRect = new Rect(position.x + 4 * widthEighth, position.y, 3 * widthEighth, position.height); if (resolutions.arraySize == 0) { addButtonRect.width *= 2; } // Display the buttons if (GUI.Button(addButtonRect, "Add New", EditorStyles.miniButton)) { resolutions.arraySize += 1; var newRes = resolutions.GetArrayElementAtIndex(resolutions.arraySize - 1); newRes.FindPropertyRelative(k_CamWidthPropName).intValue = k_DefaultCameraWidth; newRes.FindPropertyRelative(k_CamHeightPropName).intValue = k_DefaultCameraHeight; newRes.FindPropertyRelative(k_CamGrayPropName).boolValue = k_DefaultCameraGray; } if (resolutions.arraySize > 0) { if (GUI.Button(removeButtonRect, "Remove Last", EditorStyles.miniButton)) { resolutions.arraySize -= 1; } } } /// <summary> /// The Height required to draw the Visual Observations parameters /// </summary> /// <returns>The height of the drawer of the Visual Observations </returns> private static float GetHeightDrawVisualObservation(SerializedProperty property) { var visObsSize = property.FindPropertyRelative(k_CamResPropName).arraySize + 2; if (property.FindPropertyRelative(k_CamResPropName).arraySize > 0) { visObsSize += 1; } return k_LineHeight * visObsSize; } /// <summary> /// Draws the Vector Actions parameters for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> private static void DrawVectorAction(Rect position, SerializedProperty property) { EditorGUI.LabelField(position, "Vector Action"); position.y += k_LineHeight; EditorGUI.indentLevel++; var bpVectorActionType = property.FindPropertyRelative(k_ActionTypePropName); EditorGUI.PropertyField( position, bpVectorActionType, new GUIContent("Space Type", "Corresponds to whether state vector contains a single integer (Discrete) " + "or a series of real-valued floats (Continuous).")); position.y += k_LineHeight; if (bpVectorActionType.enumValueIndex == 1) { DrawContinuousVectorAction(position, property); } else { DrawDiscreteVectorAction(position, property); } } /// <summary> /// Draws the Continuous Vector Actions parameters for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> private static void DrawContinuousVectorAction(Rect position, SerializedProperty property) { var vecActionSize = property.FindPropertyRelative(k_ActionSizePropName); vecActionSize.arraySize = 1; var continuousActionSize = vecActionSize.GetArrayElementAtIndex(0); EditorGUI.PropertyField( position, continuousActionSize, new GUIContent("Space Size", "Length of continuous action vector.")); } /// <summary> /// Draws the Discrete Vector Actions parameters for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> private static void DrawDiscreteVectorAction(Rect position, SerializedProperty property) { var vecActionSize = property.FindPropertyRelative(k_ActionSizePropName); vecActionSize.arraySize = EditorGUI.IntField( position, "Branches Size", vecActionSize.arraySize); position.y += k_LineHeight; position.x += 20; position.width -= 20; for (var branchIndex = 0; branchIndex < vecActionSize.arraySize; branchIndex++) { var branchActionSize = vecActionSize.GetArrayElementAtIndex(branchIndex); EditorGUI.PropertyField( position, branchActionSize, new GUIContent("Branch " + branchIndex + " Size", "Number of possible actions for the branch number " + branchIndex + ".")); position.y += k_LineHeight; } } /// <summary> /// The Height required to draw the Vector Action parameters /// </summary> /// <returns>The height of the drawer of the Vector Action </returns> private static float GetHeightDrawVectorAction(SerializedProperty property) { var actionSize = 2 + property.FindPropertyRelative(k_ActionSizePropName).arraySize; if (property.FindPropertyRelative(k_ActionTypePropName).enumValueIndex == 0) { actionSize += 1; } return actionSize * k_LineHeight; } /// <summary> /// Draws the Vector Actions descriptions for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> private static void DrawVectorActionDescriptions(Rect position, SerializedProperty property) { var bpVectorActionType = property.FindPropertyRelative(k_ActionTypePropName); var vecActionSize = property.FindPropertyRelative(k_ActionSizePropName); var numberOfDescriptions = 0; if (bpVectorActionType.enumValueIndex == 1) { numberOfDescriptions = vecActionSize.GetArrayElementAtIndex(0).intValue; } else { numberOfDescriptions = vecActionSize.arraySize; } EditorGUI.indentLevel++; var vecActionDescriptions = property.FindPropertyRelative(k_ActionDescriptionPropName); vecActionDescriptions.arraySize = numberOfDescriptions; if (bpVectorActionType.enumValueIndex == 1) { //Continuous case : EditorGUI.PropertyField( position, vecActionDescriptions, new GUIContent("Action Descriptions", "A list of strings used to name the available actionsm for the Brain."), true); position.y += k_LineHeight; } else { // Discrete case : EditorGUI.PropertyField( position, vecActionDescriptions, new GUIContent("Branch Descriptions", "A list of strings used to name the available branches for the Brain."), true); position.y += k_LineHeight; } } /// <summary> /// The Height required to draw the Action Descriptions /// </summary> /// <returns>The height of the drawer of the Action Descriptions </returns> private static float GetHeightDrawVectorActionDescriptions(SerializedProperty property) { var descriptionSize = 1; if (property.FindPropertyRelative(k_ActionDescriptionPropName).isExpanded) { var descriptions = property.FindPropertyRelative(k_ActionDescriptionPropName); descriptionSize += descriptions.arraySize + 1; } return descriptionSize * k_LineHeight; } } }
370
ml-agents
openai
C#
using UnityEngine; using UnityEditor; using System; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; namespace MLAgents { /// <summary> /// PropertyDrawer for BroadcastHub. Used to display the BroadcastHub in the Inspector. /// </summary> [CustomPropertyDrawer(typeof(BroadcastHub))] public class BroadcastHubDrawer : PropertyDrawer { private BroadcastHub m_Hub; // The height of a line in the Unity Inspectors private const float k_LineHeight = 17f; // The vertical space left below the BroadcastHub UI. private const float k_ExtraSpaceBelow = 10f; // The horizontal size of the Control checkbox private const int k_ControlSize = 80; /// <summary> /// Computes the height of the Drawer depending on the property it is showing /// </summary> /// <param name="property">The property that is being drawn.</param> /// <param name="label">The label of the property being drawn.</param> /// <returns>The vertical space needed to draw the property.</returns> public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { LazyInitializeHub(property); var numLines = m_Hub.Count + 2 + (m_Hub.Count > 0 ? 1 : 0); return (numLines) * k_LineHeight + k_ExtraSpaceBelow; } /// <inheritdoc /> public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { LazyInitializeHub(property); position.height = k_LineHeight; EditorGUI.LabelField(position, new GUIContent(label.text, "The Broadcast Hub helps you define which Brains you want to expose to " + "the external process")); position.y += k_LineHeight; EditorGUI.BeginProperty(position, label, property); EditorGUI.indentLevel++; DrawAddRemoveButtons(position); position.y += k_LineHeight; // This is the labels for each columns var brainWidth = position.width - k_ControlSize; var brainRect = new Rect( position.x, position.y, brainWidth, position.height); var controlRect = new Rect( position.x + brainWidth, position.y, k_ControlSize, position.height); if (m_Hub.Count > 0) { EditorGUI.LabelField(brainRect, "Brains"); brainRect.y += k_LineHeight; EditorGUI.LabelField(controlRect, "Control"); controlRect.y += k_LineHeight; controlRect.x += 15; } DrawBrains(brainRect, controlRect); EditorGUI.indentLevel--; EditorGUI.EndProperty(); } /// <summary> /// Draws the Add and Remove buttons. /// </summary> /// <param name="position">The position at which to draw.</param> private void DrawAddRemoveButtons(Rect position) { // This is the rectangle for the Add button var addButtonRect = position; addButtonRect.x += 20; if (m_Hub.Count > 0) { addButtonRect.width /= 2; addButtonRect.width -= 24; var buttonContent = new GUIContent( "Add New", "Add a new Brain to the Broadcast Hub"); if (GUI.Button(addButtonRect, buttonContent, EditorStyles.miniButton)) { MarkSceneAsDirty(); AddBrain(); } // This is the rectangle for the Remove button var removeButtonRect = position; removeButtonRect.x = position.width / 2 + 15; removeButtonRect.width = addButtonRect.width - 18; buttonContent = new GUIContent( "Remove Last", "Remove the last Brain from the Broadcast Hub"); if (GUI.Button(removeButtonRect, buttonContent, EditorStyles.miniButton)) { MarkSceneAsDirty(); RemoveLastBrain(); } } else { addButtonRect.width -= 50; var buttonContent = new GUIContent( "Add Brain to Broadcast Hub", "Add a new Brain to the Broadcast Hub"); if (GUI.Button(addButtonRect, buttonContent, EditorStyles.miniButton)) { MarkSceneAsDirty(); AddBrain(); } } } /// <summary> /// Draws the Brain and Control checkbox for the brains contained in the BroadCastHub. /// </summary> /// <param name="brainRect">The Rect to draw the Brains.</param> /// <param name="controlRect">The Rect to draw the control checkbox.</param> private void DrawBrains(Rect brainRect, Rect controlRect) { for (var index = 0; index < m_Hub.Count; index++) { var exposedBrains = m_Hub.broadcastingBrains; var brain = exposedBrains[index]; // This is the rectangle for the brain EditorGUI.BeginChangeCheck(); var newBrain = EditorGUI.ObjectField( brainRect, brain, typeof(Brain), true) as Brain; brainRect.y += k_LineHeight; if (EditorGUI.EndChangeCheck()) { MarkSceneAsDirty(); m_Hub.broadcastingBrains.RemoveAt(index); var brainToInsert = exposedBrains.Contains(newBrain) ? null : newBrain; exposedBrains.Insert(index, brainToInsert); break; } // This is the Rectangle for the control checkbox EditorGUI.BeginChangeCheck(); if (brain is LearningBrain) { var isTraining = m_Hub.IsControlled(brain); isTraining = EditorGUI.Toggle(controlRect, isTraining); m_Hub.SetControlled(brain, isTraining); } controlRect.y += k_LineHeight; if (EditorGUI.EndChangeCheck()) { MarkSceneAsDirty(); } } } /// <summary> /// Lazy initializes the Drawer with the property to be drawn. /// </summary> /// <param name="property">The SerializedProperty of the BroadcastHub /// to make the custom GUI for.</param> private void LazyInitializeHub(SerializedProperty property) { if (m_Hub != null) { return; } var target = property.serializedObject.targetObject; m_Hub = fieldInfo.GetValue(target) as BroadcastHub; if (m_Hub == null) { m_Hub = new BroadcastHub(); fieldInfo.SetValue(target, m_Hub); } } /// <summary> /// Signals that the property has been modified and requires the scene to be saved for /// the changes to persist. Only works when the Editor is not playing. /// </summary> private static void MarkSceneAsDirty() { if (!EditorApplication.isPlaying) { EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); } } /// <summary> /// Removes the last Brain from the BroadcastHub /// </summary> private void RemoveLastBrain() { if (m_Hub.Count > 0) { m_Hub.broadcastingBrains.RemoveAt(m_Hub.broadcastingBrains.Count - 1); } } /// <summary> /// Adds a new Brain to the BroadcastHub. The value of this brain will not be initialized. /// </summary> private void AddBrain() { m_Hub.broadcastingBrains.Add(null); } } }
208
ml-agents
openai
C#
#if UNITY_CLOUD_BUILD namespace MLAgents { public static class Builder { public static void PreExport() { BuilderUtils.SwitchAllLearningBrainToControlMode(); } } } #endif
15
ml-agents
openai
C#
#if UNITY_CLOUD_BUILD using System.Linq; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using System.IO; namespace MLAgents { public static class BuilderUtils { public static void SwitchAllLearningBrainToControlMode() { Debug.Log("The Switching to control mode function is triggered"); string[] scenePaths = Directory.GetFiles("Assets/ML-Agents/Examples/", "*.unity", SearchOption.AllDirectories); foreach (string scenePath in scenePaths) { var curScene = EditorSceneManager.OpenScene(scenePath); var aca = SceneAsset.FindObjectOfType<Academy>(); if (aca != null) { var learningBrains = aca.broadcastHub.broadcastingBrains.Where( x => x != null && x is LearningBrain); foreach (Brain brain in learningBrains) { if (!aca.broadcastHub.IsControlled(brain)) { Debug.Log("Switched brain in scene " + scenePath); aca.broadcastHub.SetControlled(brain, true); } } EditorSceneManager.SaveScene(curScene); } else { Debug.Log("scene " + scenePath + " doesn't have a Academy in it"); } } } } } #endif
45
ml-agents
openai
C#
using System.Text; using MLAgents; using UnityEditor; /// <summary> /// Renders a custom UI for Demonstration Scriptable Object. /// </summary> [CustomEditor(typeof(Demonstration))] [CanEditMultipleObjects] public class DemonstrationEditor : Editor { SerializedProperty m_BrainParameters; SerializedProperty m_DemoMetaData; void OnEnable() { m_BrainParameters = serializedObject.FindProperty("brainParameters"); m_DemoMetaData = serializedObject.FindProperty("metaData"); } /// <summary> /// Renders Inspector UI for Demonstration metadata. /// </summary> void MakeMetaDataProperty(SerializedProperty property) { var nameProp = property.FindPropertyRelative("demonstrationName"); var expProp = property.FindPropertyRelative("numberExperiences"); var epiProp = property.FindPropertyRelative("numberEpisodes"); var rewProp = property.FindPropertyRelative("meanReward"); var nameLabel = nameProp.displayName + ": " + nameProp.stringValue; var expLabel = expProp.displayName + ": " + expProp.intValue; var epiLabel = epiProp.displayName + ": " + epiProp.intValue; var rewLabel = rewProp.displayName + ": " + rewProp.floatValue; EditorGUILayout.LabelField(nameLabel); EditorGUILayout.LabelField(expLabel); EditorGUILayout.LabelField(epiLabel); EditorGUILayout.LabelField(rewLabel); } /// <summary> /// Constructs label for action size array. /// </summary> static string BuildActionArrayLabel(SerializedProperty actionSizeProperty) { var actionSize = actionSizeProperty.arraySize; var actionLabel = new StringBuilder("[ "); for (var i = 0; i < actionSize; i++) { actionLabel.Append(actionSizeProperty.GetArrayElementAtIndex(i).intValue); if (i < actionSize - 1) { actionLabel.Append(", "); } } actionLabel.Append(" ]"); return actionLabel.ToString(); } /// <summary> /// Constructs complex label for each CameraResolution object. /// An example of this could be `[ 84 X 84 ]` /// for a single camera with 84 pixels height and width. /// </summary> private static string BuildCameraResolutionLabel(SerializedProperty cameraArray) { var numCameras = cameraArray.arraySize; var cameraLabel = new StringBuilder("[ "); for (var i = 0; i < numCameras; i++) { var camHeightPropName = cameraArray.GetArrayElementAtIndex(i).FindPropertyRelative("height"); cameraLabel.Append(camHeightPropName.intValue); cameraLabel.Append(" X "); var camWidthPropName = cameraArray.GetArrayElementAtIndex(i).FindPropertyRelative("width"); cameraLabel.Append(camWidthPropName.intValue); if (i < numCameras - 1) { cameraLabel.Append(", "); } } cameraLabel.Append(" ]"); return cameraLabel.ToString(); } /// <summary> /// Renders Inspector UI for Brain Parameters of Demonstration. /// </summary> void MakeBrainParametersProperty(SerializedProperty property) { var vecObsSizeProp = property.FindPropertyRelative("vectorObservationSize"); var numStackedProp = property.FindPropertyRelative("numStackedVectorObservations"); var actSizeProperty = property.FindPropertyRelative("vectorActionSize"); var camResProp = property.FindPropertyRelative("cameraResolutions"); var actSpaceTypeProp = property.FindPropertyRelative("vectorActionSpaceType"); var vecObsSizeLabel = vecObsSizeProp.displayName + ": " + vecObsSizeProp.intValue; var numStackedLabel = numStackedProp.displayName + ": " + numStackedProp.intValue; var vecActSizeLabel = actSizeProperty.displayName + ": " + BuildActionArrayLabel(actSizeProperty); var camResLabel = camResProp.displayName + ": " + BuildCameraResolutionLabel(camResProp); var actSpaceTypeLabel = actSpaceTypeProp.displayName + ": " + (SpaceType)actSpaceTypeProp.enumValueIndex; EditorGUILayout.LabelField(vecObsSizeLabel); EditorGUILayout.LabelField(numStackedLabel); EditorGUILayout.LabelField(vecActSizeLabel); EditorGUILayout.LabelField(camResLabel); EditorGUILayout.LabelField(actSpaceTypeLabel); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.LabelField("Meta Data", EditorStyles.boldLabel); MakeMetaDataProperty(m_DemoMetaData); EditorGUILayout.LabelField("Brain Parameters", EditorStyles.boldLabel); MakeBrainParametersProperty(m_BrainParameters); serializedObject.ApplyModifiedProperties(); } }
126
ml-agents
openai
C#
using System; using System.IO; using MLAgents.CommunicatorObjects; using UnityEditor; using UnityEngine; using UnityEditor.Experimental.AssetImporters; namespace MLAgents { /// <summary> /// Asset Importer used to parse demonstration files. /// </summary> [ScriptedImporter(1, new[] {"demo"})] public class DemonstrationImporter : ScriptedImporter { private const string k_IconPath = "Assets/ML-Agents/Resources/DemoIcon.png"; public override void OnImportAsset(AssetImportContext ctx) { var inputType = Path.GetExtension(ctx.assetPath); if (inputType == null) { throw new Exception("Demonstration import error."); } try { // Read first two proto objects containing metadata and brain parameters. Stream reader = File.OpenRead(ctx.assetPath); var metaDataProto = DemonstrationMetaProto.Parser.ParseDelimitedFrom(reader); var metaData = new DemonstrationMetaData(metaDataProto); reader.Seek(DemonstrationStore.MetaDataBytes + 1, 0); var brainParamsProto = BrainParametersProto.Parser.ParseDelimitedFrom(reader); var brainParameters = new BrainParameters(brainParamsProto); reader.Close(); var demonstration = ScriptableObject.CreateInstance<Demonstration>(); demonstration.Initialize(brainParameters, metaData); userData = demonstration.ToString(); var texture = (Texture2D) AssetDatabase.LoadAssetAtPath(k_IconPath, typeof(Texture2D)); #if UNITY_2017_3_OR_NEWER ctx.AddObjectToAsset(ctx.assetPath, demonstration, texture); ctx.SetMainObject(demonstration); #else ctx.SetMainAsset(ctx.assetPath, demonstration); #endif } catch { // ignored } } } }
61
ml-agents
openai
C#
using UnityEngine; using UnityEditor; namespace MLAgents { /// <summary> /// CustomEditor for the Heuristic Brain class. Defines the default Inspector view for a /// HeuristicBrain. /// Shows the BrainParameters of the Brain and expose a tool to deep copy BrainParameters /// between brains. Provides a drag box for a Decision Monoscript that will be used by /// the Heuristic Brain. /// </summary> [CustomEditor(typeof(HeuristicBrain))] public class HeuristicBrainEditor : BrainEditor { public override void OnInspectorGUI() { EditorGUILayout.LabelField("Heuristic Brain", EditorStyles.boldLabel); var brain = (HeuristicBrain)target; base.OnInspectorGUI(); // Expose the Heuristic Brain's Monoscript for decision in a drag and drop box. brain.decisionScript = EditorGUILayout.ObjectField( "Decision Script", brain.decisionScript, typeof(MonoScript), true) as MonoScript; CheckIsDecision(brain); // Draw an error box if the Decision is not set. if (brain.decisionScript == null) { EditorGUILayout.HelpBox("You need to add a 'Decision' component to this Object", MessageType.Error); } } /// <summary> /// Ensures tht the Monoscript for the decision of the HeuristicBrain is either null or /// an implementation of Decision. If the Monoscript is not an implementation of /// Decision, it will be set to null. /// </summary> /// <param name="brain">The HeuristicBrain with the decision script attached</param> private static void CheckIsDecision(HeuristicBrain brain) { if (brain.decisionScript != null) { var decisionInstance = (CreateInstance(brain.decisionScript.name) as Decision); if (decisionInstance == null) { Debug.LogError( "Instance of " + brain.decisionScript.name + " couldn't be created. " + "The script class needs to derive from Decision."); brain.decisionScript = null; } } } } }
57
ml-agents
openai
C#
using UnityEngine; using UnityEditor; namespace MLAgents { /// <summary> /// CustomEditor for the LearningBrain class. Defines the default Inspector view for a /// LearningBrain. /// Shows the BrainParameters of the Brain and expose a tool to deep copy BrainParameters /// between brains. Also exposes a drag box for the Model that will be used by the /// LearningBrain. /// </summary> [CustomEditor(typeof(LearningBrain))] public class LearningBrainEditor : BrainEditor { private const string k_ModelPropName = "model"; private const string k_InferenceDevicePropName = "inferenceDevice"; private const float k_TimeBetweenModelReloads = 2f; // Time since the last reload of the model private float m_TimeSinceModelReload; // Whether or not the model needs to be reloaded private bool m_RequireReload; /// <summary> /// Called when the user opens the Inspector for the LearningBrain /// </summary> public void OnEnable() { m_RequireReload = true; EditorApplication.update += IncreaseTimeSinceLastModelReload; } /// <summary> /// Called when the user leaves the Inspector for the LearningBrain /// </summary> public void OnDisable() { EditorApplication.update -= IncreaseTimeSinceLastModelReload; } public override void OnInspectorGUI() { EditorGUILayout.LabelField("Learning Brain", EditorStyles.boldLabel); var brain = (LearningBrain)target; var serializedBrain = serializedObject; EditorGUI.BeginChangeCheck(); base.OnInspectorGUI(); serializedBrain.Update(); var tfGraphModel = serializedBrain.FindProperty(k_ModelPropName); EditorGUILayout.ObjectField(tfGraphModel); var inferenceDevice = serializedBrain.FindProperty(k_InferenceDevicePropName); EditorGUILayout.PropertyField(inferenceDevice); serializedBrain.ApplyModifiedProperties(); if (EditorGUI.EndChangeCheck()) { m_RequireReload = true; } if (m_RequireReload && m_TimeSinceModelReload > k_TimeBetweenModelReloads) { brain.ReloadModel(); m_RequireReload = false; m_TimeSinceModelReload = 0; } // Display all failed checks var failedChecks = brain.GetModelFailedChecks(); foreach (var check in failedChecks) { if (check != null) { EditorGUILayout.HelpBox(check, MessageType.Warning); } } } /// <summary> /// Increases the time since last model reload by the deltaTime since the last Update call /// from the UnityEditor /// </summary> private void IncreaseTimeSinceLastModelReload() { m_TimeSinceModelReload += Time.deltaTime; } } }
85
ml-agents
openai
C#
using UnityEngine; using UnityEditor; namespace MLAgents { /// <summary> /// CustomEditor for the PlayerBrain class. Defines the default Inspector view for a /// PlayerBrain. /// Shows the BrainParameters of the Brain and expose a tool to deep copy BrainParameters /// between brains. Also exposes the key mappings for either continuous or discrete control /// depending on the Vector Action Space Type of the Brain Parameter. These mappings are the /// ones that will be used by the PlayerBrain. /// </summary> [CustomEditor(typeof(PlayerBrain))] public class PlayerBrainEditor : BrainEditor { private const string k_KeyContinuousPropName = "keyContinuousPlayerActions"; private const string k_KeyDiscretePropName = "discretePlayerActions"; private const string k_AxisContinuousPropName = "axisContinuousPlayerActions"; public override void OnInspectorGUI() { EditorGUILayout.LabelField("Player Brain", EditorStyles.boldLabel); var brain = (PlayerBrain)target; var serializedBrain = serializedObject; base.OnInspectorGUI(); serializedBrain.Update(); if (brain.brainParameters.vectorActionSpaceType == SpaceType.Continuous) { DrawContinuousKeyMapping(serializedBrain, brain); } else { DrawDiscreteKeyMapping(serializedBrain); } serializedBrain.ApplyModifiedProperties(); } /// <summary> /// Draws the UI for continuous control key mapping to actions. /// </summary> /// <param name="serializedBrain"> The SerializedObject corresponding to the brain. </param> /// <param name="brain"> The Brain of which properties are displayed. </param> private static void DrawContinuousKeyMapping( SerializedObject serializedBrain, PlayerBrain brain) { GUILayout.Label("Edit the continuous inputs for your actions", EditorStyles.boldLabel); var keyActionsProp = serializedBrain.FindProperty(k_KeyContinuousPropName); var axisActionsProp = serializedBrain.FindProperty(k_AxisContinuousPropName); EditorGUILayout.PropertyField(keyActionsProp , true); EditorGUILayout.PropertyField(axisActionsProp, true); var keyContinuous = brain.keyContinuousPlayerActions; var axisContinuous = brain.axisContinuousPlayerActions; var brainParams = brain.brainParameters; if (keyContinuous == null) { keyContinuous = new PlayerBrain.KeyContinuousPlayerAction[0]; } if (axisContinuous == null) { axisContinuous = new PlayerBrain.AxisContinuousPlayerAction[0]; } foreach (var action in keyContinuous) { if (action.index >= brainParams.vectorActionSize[0]) { EditorGUILayout.HelpBox( $"Key {action.key.ToString()} is assigned to index " + $"{action.index.ToString()} but the action size is only of size " + $"{brainParams.vectorActionSize}", MessageType.Error); } } foreach (var action in axisContinuous) { if (action.index >= brainParams.vectorActionSize[0]) { EditorGUILayout.HelpBox( $"Axis {action.axis} is assigned to index {action.index.ToString()} " + $"but the action size is only of size {brainParams.vectorActionSize}", MessageType.Error); } } GUILayout.Label("You can change axis settings from Edit->Project Settings->Input", EditorStyles.helpBox); } /// <summary> /// Draws the UI for discrete control key mapping to actions. /// </summary> /// <param name="serializedBrain"> The SerializedObject corresponding to the brain. </param> private static void DrawDiscreteKeyMapping(SerializedObject serializedBrain) { GUILayout.Label("Edit the discrete inputs for your actions", EditorStyles.boldLabel); var dhas = serializedBrain.FindProperty(k_KeyDiscretePropName); serializedBrain.Update(); EditorGUILayout.PropertyField(dhas, true); } } }
104
ml-agents
openai
C#
using UnityEngine; using UnityEditor; using System; using System.Linq; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; namespace MLAgents { /// <summary> /// PropertyDrawer for ResetParameters. Defines how ResetParameters are displayed in the /// Inspector. /// </summary> [CustomPropertyDrawer(typeof(ResetParameters))] public class ResetParameterDrawer : PropertyDrawer { private ResetParameters m_Parameters; // The height of a line in the Unity Inspectors private const float k_LineHeight = 17f; // This is the prefix for the key when you add a reset parameter private const string k_NewKeyPrefix = "Param-"; /// <summary> /// Computes the height of the Drawer depending on the property it is showing /// </summary> /// <param name="property">The property that is being drawn.</param> /// <param name="label">The label of the property being drawn.</param> /// <returns>The vertical space needed to draw the property.</returns> public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { LazyInitializeParameters(property); return (m_Parameters.Count + 2) * k_LineHeight; } /// <inheritdoc /> public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { LazyInitializeParameters(property); position.height = k_LineHeight; EditorGUI.LabelField(position, label); position.y += k_LineHeight; var width = position.width / 2 - 24; var keyRect = new Rect(position.x + 20, position.y, width, position.height); var valueRect = new Rect(position.x + width + 30, position.y, width, position.height); DrawAddRemoveButtons(keyRect, valueRect); EditorGUI.BeginProperty(position, label, property); foreach (var parameter in m_Parameters) { var key = parameter.Key; var value = parameter.Value; keyRect.y += k_LineHeight; valueRect.y += k_LineHeight; EditorGUI.BeginChangeCheck(); var newKey = EditorGUI.TextField(keyRect, key); if (EditorGUI.EndChangeCheck()) { MarkSceneAsDirty(); try { m_Parameters.Remove(key); m_Parameters.Add(newKey, value); } catch (Exception e) { Debug.Log(e.Message); } break; } EditorGUI.BeginChangeCheck(); value = EditorGUI.FloatField(valueRect, value); if (EditorGUI.EndChangeCheck()) { MarkSceneAsDirty(); m_Parameters[key] = value; break; } } EditorGUI.EndProperty(); } /// <summary> /// Draws the Add and Remove buttons. /// </summary> /// <param name="addRect">The rectangle for the Add New button.</param> /// <param name="removeRect">The rectangle for the Remove Last button.</param> private void DrawAddRemoveButtons(Rect addRect, Rect removeRect) { // This is the Add button if (m_Parameters.Count == 0) { addRect.width *= 2; } if (GUI.Button(addRect, new GUIContent("Add New", "Add a new item to the default reset parameters"), EditorStyles.miniButton)) { MarkSceneAsDirty(); AddParameter(); } // If there are no items in the ResetParameters, Hide the Remove button if (m_Parameters.Count == 0) { return; } // This is the Remove button if (GUI.Button(removeRect, new GUIContent( "Remove Last", "Remove the last item from the default reset parameters"), EditorStyles.miniButton)) { MarkSceneAsDirty(); RemoveLastParameter(); } } /// <summary> /// Signals that the property has been modified and requires the scene to be saved for /// the changes to persist. Only works when the Editor is not playing. /// </summary> private static void MarkSceneAsDirty() { if (!EditorApplication.isPlaying) { EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); } } /// <summary> /// Ensures that the state of the Drawer is synchronized with the property. /// </summary> /// <param name="property">The SerializedProperty of the ResetParameters /// to make the custom GUI for.</param> private void LazyInitializeParameters(SerializedProperty property) { if (m_Parameters != null) { return; } var target = property.serializedObject.targetObject; m_Parameters = fieldInfo.GetValue(target) as ResetParameters; if (m_Parameters == null) { m_Parameters = new ResetParameters(); fieldInfo.SetValue(target, m_Parameters); } } /// <summary> /// Removes the last ResetParameter from the ResetParameters /// </summary> private void RemoveLastParameter() { if (m_Parameters.Count > 0) { var key = m_Parameters.Keys.ToList()[m_Parameters.Count - 1]; m_Parameters.Remove(key); } } /// <summary> /// Adds a new ResetParameter to the ResetParameters with a default name. /// </summary> private void AddParameter() { var key = k_NewKeyPrefix + m_Parameters.Count; var value = default(float); try { m_Parameters.Add(key, value); } catch (Exception e) { Debug.Log(e.Message); } } } }
180
ml-agents
openai
C#
using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using System.IO.Abstractions.TestingHelpers; namespace MLAgents.Tests { public class DemonstrationTests : MonoBehaviour { private const string k_DemoDirecory = "Assets/Demonstrations/"; private const string k_ExtensionType = ".demo"; private const string k_DemoName = "Test"; [Test] public void TestSanitization() { const string dirtyString = "abc1234567&!@"; const string knownCleanString = "abc123"; var cleanString = DemonstrationRecorder.SanitizeName(dirtyString, 6); Assert.AreNotEqual(dirtyString, cleanString); Assert.AreEqual(cleanString, knownCleanString); } [Test] public void TestStoreInitalize() { var fileSystem = new MockFileSystem(); var demoStore = new DemonstrationStore(fileSystem); Assert.IsFalse(fileSystem.Directory.Exists(k_DemoDirecory)); var brainParameters = new BrainParameters { vectorObservationSize = 3, numStackedVectorObservations = 2, cameraResolutions = new[] {new Resolution()}, vectorActionDescriptions = new[] {"TestActionA", "TestActionB"}, vectorActionSize = new[] {2, 2}, vectorActionSpaceType = SpaceType.Discrete }; demoStore.Initialize(k_DemoName, brainParameters, "TestBrain"); Assert.IsTrue(fileSystem.Directory.Exists(k_DemoDirecory)); Assert.IsTrue(fileSystem.FileExists(k_DemoDirecory + k_DemoName + k_ExtensionType)); var agentInfo = new AgentInfo { reward = 1f, visualObservations = new List<Texture2D>(), actionMasks = new[] {false, true}, done = true, id = 5, maxStepReached = true, memories = new List<float>(), stackedVectorObservation = new List<float>() {1f, 1f, 1f}, storedTextActions = "TestAction", storedVectorActions = new[] {0f, 1f}, textObservation = "TestAction", }; demoStore.Record(agentInfo); demoStore.Close(); } } }
67
ml-agents
openai
C#
using System; using Barracuda; using NUnit.Framework; using UnityEngine; using MLAgents.InferenceBrain; using MLAgents.InferenceBrain.Utils; namespace MLAgents.Tests { public class DiscreteActionOutputApplierTest { [Test] public void TestEvalP() { var m = new Multinomial(2018); var src = new TensorProxy { data = new Tensor(1, 3, new[] {0.1f, 0.2f, 0.7f}), valueType = TensorProxy.TensorType.FloatingPoint }; var dst = new TensorProxy { data = new Tensor(1, 3), valueType = TensorProxy.TensorType.FloatingPoint }; DiscreteActionOutputApplier.Eval(src, dst, m); float[] reference = {2, 2, 1}; for (var i = 0; i < dst.data.length; i++) { Assert.AreEqual(reference[i], dst.data[i]); ++i; } } [Test] public void TestEvalLogits() { var m = new Multinomial(2018); var src = new TensorProxy { data = new Tensor( 1, 3, new[] { Mathf.Log(0.1f) - 50, Mathf.Log(0.2f) - 50, Mathf.Log(0.7f) - 50 }), valueType = TensorProxy.TensorType.FloatingPoint }; var dst = new TensorProxy { data = new Tensor(1, 3), valueType = TensorProxy.TensorType.FloatingPoint }; DiscreteActionOutputApplier.Eval(src, dst, m); float[] reference = {2, 2, 2}; for (var i = 0; i < dst.data.length; i++) { Assert.AreEqual(reference[i], dst.data[i]); ++i; } } [Test] public void TestEvalBatching() { var m = new Multinomial(2018); var src = new TensorProxy { data = new Tensor(2, 3, new[] { Mathf.Log(0.1f) - 50, Mathf.Log(0.2f) - 50, Mathf.Log(0.7f) - 50, Mathf.Log(0.3f) - 25, Mathf.Log(0.4f) - 25, Mathf.Log(0.3f) - 25 }), valueType = TensorProxy.TensorType.FloatingPoint }; var dst = new TensorProxy { data = new Tensor(2, 3), valueType = TensorProxy.TensorType.FloatingPoint }; DiscreteActionOutputApplier.Eval(src, dst, m); float[] reference = {2, 2, 2, 0, 1, 0}; for (var i = 0; i < dst.data.length; i++) { Assert.AreEqual(reference[i], dst.data[i]); ++i; } } [Test] public void TestSrcInt() { var m = new Multinomial(2018); var src = new TensorProxy { valueType = TensorProxy.TensorType.Integer }; Assert.Throws<NotImplementedException>( () => DiscreteActionOutputApplier.Eval(src, null, m)); } [Test] public void TestDstInt() { var m = new Multinomial(2018); var src = new TensorProxy { valueType = TensorProxy.TensorType.FloatingPoint }; var dst = new TensorProxy { valueType = TensorProxy.TensorType.Integer }; Assert.Throws<ArgumentException>( () => DiscreteActionOutputApplier.Eval(src, dst, m)); } [Test] public void TestSrcDataNull() { var m = new Multinomial(2018); var src = new TensorProxy { valueType = TensorProxy.TensorType.FloatingPoint }; var dst = new TensorProxy { valueType = TensorProxy.TensorType.FloatingPoint }; Assert.Throws<ArgumentNullException>( () => DiscreteActionOutputApplier.Eval(src, dst, m)); } [Test] public void TestDstDataNull() { var m = new Multinomial(2018); var src = new TensorProxy { valueType = TensorProxy.TensorType.FloatingPoint, data = new Tensor(0, 1) }; var dst = new TensorProxy { valueType = TensorProxy.TensorType.FloatingPoint }; Assert.Throws<ArgumentNullException>( () => DiscreteActionOutputApplier.Eval(src, dst, m)); } [Test] public void TestUnequalBatchSize() { var m = new Multinomial(2018); var src = new TensorProxy { valueType = TensorProxy.TensorType.FloatingPoint, data = new Tensor(1, 1) }; var dst = new TensorProxy { valueType = TensorProxy.TensorType.FloatingPoint, data = new Tensor(2, 1) }; Assert.Throws<ArgumentException>( () => DiscreteActionOutputApplier.Eval(src, dst, m)); } } }
194
ml-agents
openai
C#
using NUnit.Framework; namespace MLAgents.Tests { public class EditModeTestActionMasker { [Test] public void Contruction() { var bp = new BrainParameters(); var masker = new ActionMasker(bp); Assert.IsNotNull(masker); } [Test] public void FailsWithContinuous() { var bp = new BrainParameters(); bp.vectorActionSpaceType = SpaceType.Continuous; bp.vectorActionSize = new[] {4}; var masker = new ActionMasker(bp); masker.SetActionMask(0, new[] {0}); Assert.Catch<UnityAgentsException>(() => masker.GetMask()); } [Test] public void NullMask() { var bp = new BrainParameters(); bp.vectorActionSpaceType = SpaceType.Discrete; var masker = new ActionMasker(bp); var mask = masker.GetMask(); Assert.IsNull(mask); } [Test] public void FirstBranchMask() { var bp = new BrainParameters(); bp.vectorActionSpaceType = SpaceType.Discrete; bp.vectorActionSize = new[] {4, 5, 6}; var masker = new ActionMasker(bp); var mask = masker.GetMask(); Assert.IsNull(mask); masker.SetActionMask(0, new[] {1, 2, 3}); mask = masker.GetMask(); Assert.IsFalse(mask[0]); Assert.IsTrue(mask[1]); Assert.IsTrue(mask[2]); Assert.IsTrue(mask[3]); Assert.IsFalse(mask[4]); Assert.AreEqual(mask.Length, 15); } [Test] public void SecondBranchMask() { var bp = new BrainParameters { vectorActionSpaceType = SpaceType.Discrete, vectorActionSize = new[] { 4, 5, 6 } }; var masker = new ActionMasker(bp); masker.SetActionMask(1, new[] {1, 2, 3}); var mask = masker.GetMask(); Assert.IsFalse(mask[0]); Assert.IsFalse(mask[4]); Assert.IsTrue(mask[5]); Assert.IsTrue(mask[6]); Assert.IsTrue(mask[7]); Assert.IsFalse(mask[8]); Assert.IsFalse(mask[9]); } [Test] public void MaskReset() { var bp = new BrainParameters { vectorActionSpaceType = SpaceType.Discrete, vectorActionSize = new[] { 4, 5, 6 } }; var masker = new ActionMasker(bp); masker.SetActionMask(1, new[] {1, 2, 3}); masker.ResetMask(); var mask = masker.GetMask(); for (var i = 0; i < 15; i++) { Assert.IsFalse(mask[i]); } } [Test] public void ThrowsError() { var bp = new BrainParameters { vectorActionSpaceType = SpaceType.Discrete, vectorActionSize = new[] { 4, 5, 6 } }; var masker = new ActionMasker(bp); Assert.Catch<UnityAgentsException>( () => masker.SetActionMask(0, new[] {5})); Assert.Catch<UnityAgentsException>( () => masker.SetActionMask(1, new[] {5})); masker.SetActionMask(2, new[] {5}); Assert.Catch<UnityAgentsException>( () => masker.SetActionMask(3, new[] {1})); masker.GetMask(); masker.ResetMask(); masker.SetActionMask(0, new[] {0, 1, 2, 3}); Assert.Catch<UnityAgentsException>( () => masker.GetMask()); } [Test] public void MultipleMaskEdit() { var bp = new BrainParameters(); bp.vectorActionSpaceType = SpaceType.Discrete; bp.vectorActionSize = new[] {4, 5, 6}; var masker = new ActionMasker(bp); masker.SetActionMask(0, new[] {0, 1}); masker.SetActionMask(0, new[] {3}); masker.SetActionMask(2, new[] {1}); var mask = masker.GetMask(); for (var i = 0; i < 15; i++) { if ((i == 0) || (i == 1) || (i == 3) || (i == 10)) { Assert.IsTrue(mask[i]); } else { Assert.IsFalse(mask[i]); } } } } }
142
ml-agents
openai
C#
using System.Collections.Generic; using System.Linq; using NUnit.Framework; using UnityEngine; using System.Reflection; using Barracuda; using MLAgents.InferenceBrain; namespace MLAgents.Tests { public class EditModeTestInternalBrainTensorApplier { private class TestAgent : Agent { public AgentAction GetAction() { var f = typeof(Agent).GetField( "m_Action", BindingFlags.Instance | BindingFlags.NonPublic); return (AgentAction)f.GetValue(this); } } private Dictionary<Agent, AgentInfo> GetFakeAgentInfos() { var goA = new GameObject("goA"); var agentA = goA.AddComponent<TestAgent>(); var infoA = new AgentInfo(); var goB = new GameObject("goB"); var agentB = goB.AddComponent<TestAgent>(); var infoB = new AgentInfo(); return new Dictionary<Agent, AgentInfo>(){{agentA, infoA}, {agentB, infoB}}; } [Test] public void Construction() { var bp = new BrainParameters(); var alloc = new TensorCachingAllocator(); var tensorGenerator = new TensorApplier(bp, 0, alloc); Assert.IsNotNull(tensorGenerator); alloc.Dispose(); } [Test] public void ApplyContinuousActionOutput() { var inputTensor = new TensorProxy() { shape = new long[] {2, 3}, data = new Tensor(2, 3, new float[] {1, 2, 3, 4, 5, 6}) }; var agentInfos = GetFakeAgentInfos(); var applier = new ContinuousActionOutputApplier(); applier.Apply(inputTensor, agentInfos); var agents = agentInfos.Keys.ToList(); var agent = agents[0] as TestAgent; Assert.NotNull(agent); var action = agent.GetAction(); Assert.AreEqual(action.vectorActions[0], 1); Assert.AreEqual(action.vectorActions[1], 2); Assert.AreEqual(action.vectorActions[2], 3); agent = agents[1] as TestAgent; Assert.NotNull(agent); action = agent.GetAction(); Assert.AreEqual(action.vectorActions[0], 4); Assert.AreEqual(action.vectorActions[1], 5); Assert.AreEqual(action.vectorActions[2], 6); } [Test] public void ApplyDiscreteActionOutput() { var inputTensor = new TensorProxy() { shape = new long[] {2, 5}, data = new Tensor( 2, 5, new[] {0.5f, 22.5f, 0.1f, 5f, 1f, 4f, 5f, 6f, 7f, 8f}) }; var agentInfos = GetFakeAgentInfos(); var alloc = new TensorCachingAllocator(); var applier = new DiscreteActionOutputApplier(new[] {2, 3}, 0, alloc); applier.Apply(inputTensor, agentInfos); var agents = agentInfos.Keys.ToList(); var agent = agents[0] as TestAgent; Assert.NotNull(agent); var action = agent.GetAction(); Assert.AreEqual(action.vectorActions[0], 1); Assert.AreEqual(action.vectorActions[1], 1); agent = agents[1] as TestAgent; Assert.NotNull(agent); action = agent.GetAction(); Assert.AreEqual(action.vectorActions[0], 1); Assert.AreEqual(action.vectorActions[1], 2); alloc.Dispose(); } [Test] public void ApplyMemoryOutput() { var inputTensor = new TensorProxy() { shape = new long[] {2, 5}, data = new Tensor( 2, 5, new[] {0.5f, 22.5f, 0.1f, 5f, 1f, 4f, 5f, 6f, 7f, 8f}) }; var agentInfos = GetFakeAgentInfos(); var applier = new MemoryOutputApplier(); applier.Apply(inputTensor, agentInfos); var agents = agentInfos.Keys.ToList(); var agent = agents[0] as TestAgent; Assert.NotNull(agent); var action = agent.GetAction(); Assert.AreEqual(action.memories[0], 0.5f); Assert.AreEqual(action.memories[1], 22.5f); agent = agents[1] as TestAgent; Assert.NotNull(agent); action = agent.GetAction(); Assert.AreEqual(action.memories[2], 6); Assert.AreEqual(action.memories[3], 7); } [Test] public void ApplyValueEstimate() { var inputTensor = new TensorProxy() { shape = new long[] {2, 1}, data = new Tensor(2, 1, new[] {0.5f, 8f}) }; var agentInfos = GetFakeAgentInfos(); var applier = new ValueEstimateApplier(); applier.Apply(inputTensor, agentInfos); var agents = agentInfos.Keys.ToList(); var agent = agents[0] as TestAgent; Assert.NotNull(agent); var action = agent.GetAction(); Assert.AreEqual(action.value, 0.5f); agent = agents[1] as TestAgent; Assert.NotNull(agent); action = agent.GetAction(); Assert.AreEqual(action.value, 8); } } }
161
ml-agents
openai
C#
using System.Collections.Generic; using System.Linq; using Barracuda; using NUnit.Framework; using UnityEngine; using MLAgents.InferenceBrain; namespace MLAgents.Tests { public class EditModeTestInternalBrainTensorGenerator { private class TestAgent : Agent { } private Dictionary<Agent, AgentInfo> GetFakeAgentInfos() { var goA = new GameObject("goA"); var agentA = goA.AddComponent<TestAgent>(); var infoA = new AgentInfo() { stackedVectorObservation = (new[] {1f, 2f, 3f}).ToList(), memories = null, storedVectorActions = new[] {1f, 2f}, actionMasks = null, }; var goB = new GameObject("goB"); var agentB = goB.AddComponent<TestAgent>(); var infoB = new AgentInfo() { stackedVectorObservation = (new[] {4f, 5f, 6f}).ToList(), memories = (new[] {1f, 1f, 1f}).ToList(), storedVectorActions = new[] {3f, 4f}, actionMasks = new[] {true, false, false, false, false}, }; return new Dictionary<Agent, AgentInfo>(){{agentA, infoA}, {agentB, infoB}}; } [Test] public void Construction() { var bp = new BrainParameters(); var alloc = new TensorCachingAllocator(); var tensorGenerator = new TensorGenerator(bp, 0, alloc); Assert.IsNotNull(tensorGenerator); alloc.Dispose(); } [Test] public void GenerateBatchSize() { var inputTensor = new TensorProxy(); var alloc = new TensorCachingAllocator(); const int batchSize = 4; var generator = new BatchSizeGenerator(alloc); generator.Generate(inputTensor, batchSize, null); Assert.IsNotNull(inputTensor.data); Assert.AreEqual(inputTensor.data[0], batchSize); alloc.Dispose(); } [Test] public void GenerateSequenceLength() { var inputTensor = new TensorProxy(); var alloc = new TensorCachingAllocator(); const int batchSize = 4; var generator = new SequenceLengthGenerator(alloc); generator.Generate(inputTensor, batchSize, null); Assert.IsNotNull(inputTensor.data); Assert.AreEqual(inputTensor.data[0], 1); alloc.Dispose(); } [Test] public void GenerateVectorObservation() { var inputTensor = new TensorProxy() { shape = new long[] {2, 3} }; const int batchSize = 4; var agentInfos = GetFakeAgentInfos(); var alloc = new TensorCachingAllocator(); var generator = new VectorObservationGenerator(alloc); generator.Generate(inputTensor, batchSize, agentInfos); Assert.IsNotNull(inputTensor.data); Assert.AreEqual(inputTensor.data[0, 0], 1); Assert.AreEqual(inputTensor.data[0, 2], 3); Assert.AreEqual(inputTensor.data[1, 0], 4); Assert.AreEqual(inputTensor.data[1, 2], 6); alloc.Dispose(); } [Test] public void GenerateRecurrentInput() { var inputTensor = new TensorProxy() { shape = new long[] {2, 5} }; const int batchSize = 4; var agentInfos = GetFakeAgentInfos(); var alloc = new TensorCachingAllocator(); var generator = new RecurrentInputGenerator(alloc); generator.Generate(inputTensor, batchSize, agentInfos); Assert.IsNotNull(inputTensor.data); Assert.AreEqual(inputTensor.data[0, 0], 0); Assert.AreEqual(inputTensor.data[0, 4], 0); Assert.AreEqual(inputTensor.data[1, 0], 1); Assert.AreEqual(inputTensor.data[1, 4], 0); alloc.Dispose(); } [Test] public void GeneratePreviousActionInput() { var inputTensor = new TensorProxy() { shape = new long[] {2, 2}, valueType = TensorProxy.TensorType.Integer }; const int batchSize = 4; var agentInfos = GetFakeAgentInfos(); var alloc = new TensorCachingAllocator(); var generator = new PreviousActionInputGenerator(alloc); generator.Generate(inputTensor, batchSize, agentInfos); Assert.IsNotNull(inputTensor.data); Assert.AreEqual(inputTensor.data[0, 0], 1); Assert.AreEqual(inputTensor.data[0, 1], 2); Assert.AreEqual(inputTensor.data[1, 0], 3); Assert.AreEqual(inputTensor.data[1, 1], 4); alloc.Dispose(); } [Test] public void GenerateActionMaskInput() { var inputTensor = new TensorProxy() { shape = new long[] {2, 5}, valueType = TensorProxy.TensorType.FloatingPoint }; const int batchSize = 4; var agentInfos = GetFakeAgentInfos(); var alloc = new TensorCachingAllocator(); var generator = new ActionMaskInputGenerator(alloc); generator.Generate(inputTensor, batchSize, agentInfos); Assert.IsNotNull(inputTensor.data); Assert.AreEqual(inputTensor.data[0, 0], 1); Assert.AreEqual(inputTensor.data[0, 4], 1); Assert.AreEqual(inputTensor.data[1, 0], 0); Assert.AreEqual(inputTensor.data[1, 4], 1); alloc.Dispose(); } } }
160
ml-agents
openai
C#
using UnityEngine; using NUnit.Framework; using System.Reflection; namespace MLAgents.Tests { public class TestAcademy : Academy { public int initializeAcademyCalls; public int AcademyStepCalls; public override void InitializeAcademy() { initializeAcademyCalls += 1; } public override void AcademyReset() { } public override void AcademyStep() { AcademyStepCalls += 1; } } public class TestAgent : Agent { public int initializeAgentCalls; public int collectObservationsCalls; public int agentActionCalls; public int agentResetCalls; public int agentOnDoneCalls; public override void InitializeAgent() { initializeAgentCalls += 1; } public override void CollectObservations() { collectObservationsCalls += 1; } public override void AgentAction(float[] vectorAction, string textAction) { agentActionCalls += 1; AddReward(0.1f); } public override void AgentReset() { agentResetCalls += 1; } public override void AgentOnDone() { agentOnDoneCalls += 1; } } // This is an empty class for testing the behavior of agents and academy // It is left empty because we are not testing any brain behavior public class TestBrain : Brain { public int numberOfCallsToInitialize; public int numberOfCallsToDecideAction; public static TestBrain Instantiate() { return CreateInstance<TestBrain>(); } protected override void Initialize() { numberOfCallsToInitialize++; } protected override void DecideAction() { numberOfCallsToDecideAction++; m_AgentInfos.Clear(); } } public class EditModeTestGeneration { [Test] public void TestAcademy() { // Use the Assert class to test conditions. var acaGo = new GameObject("TestAcademy"); acaGo.AddComponent<TestAcademy>(); var aca = acaGo.GetComponent<TestAcademy>(); Assert.AreNotEqual(null, aca); Assert.AreEqual(0, aca.initializeAcademyCalls); Assert.AreEqual(0, aca.GetEpisodeCount()); Assert.AreEqual(0, aca.GetStepCount()); } [Test] public void TestAgent() { var agentGo = new GameObject("TestAgent"); agentGo.AddComponent<TestAgent>(); var agent = agentGo.GetComponent<TestAgent>(); Assert.AreNotEqual(null, agent); Assert.AreEqual(0, agent.initializeAgentCalls); } } public class EditModeTestInitialization { [Test] public void TestAcademy() { var acaGo = new GameObject("TestAcademy"); acaGo.AddComponent<TestAcademy>(); var aca = acaGo.GetComponent<TestAcademy>(); Assert.AreEqual(0, aca.initializeAcademyCalls); Assert.AreEqual(0, aca.GetStepCount()); Assert.AreEqual(0, aca.GetEpisodeCount()); //This will call the method even though it is private var academyInitializeMethod = typeof(Academy).GetMethod("InitializeEnvironment", BindingFlags.Instance | BindingFlags.NonPublic); academyInitializeMethod?.Invoke(aca, new object[] { }); Assert.AreEqual(1, aca.initializeAcademyCalls); Assert.AreEqual(0, aca.GetEpisodeCount()); Assert.AreEqual(0, aca.GetStepCount()); Assert.AreEqual(0, aca.AcademyStepCalls); } [Test] public void TestAgent() { var agentGo1 = new GameObject("TestAgent"); agentGo1.AddComponent<TestAgent>(); var agent1 = agentGo1.GetComponent<TestAgent>(); var agentGo2 = new GameObject("TestAgent"); agentGo2.AddComponent<TestAgent>(); var agent2 = agentGo2.GetComponent<TestAgent>(); var acaGo = new GameObject("TestAcademy"); acaGo.AddComponent<TestAcademy>(); var aca = acaGo.GetComponent<TestAcademy>(); var brain = TestBrain.Instantiate(); brain.brainParameters = new BrainParameters(); brain.brainParameters.vectorObservationSize = 0; agent1.GiveBrain(brain); agent2.GiveBrain(brain); Assert.AreEqual(false, agent1.IsDone()); Assert.AreEqual(false, agent2.IsDone()); Assert.AreEqual(0, agent1.agentResetCalls); Assert.AreEqual(0, agent2.agentResetCalls); Assert.AreEqual(0, agent1.initializeAgentCalls); Assert.AreEqual(0, agent2.initializeAgentCalls); Assert.AreEqual(0, agent1.agentActionCalls); Assert.AreEqual(0, agent2.agentActionCalls); var agentEnableMethod = typeof(Agent).GetMethod("OnEnableHelper", BindingFlags.Instance | BindingFlags.NonPublic); var academyInitializeMethod = typeof(Academy).GetMethod("InitializeEnvironment", BindingFlags.Instance | BindingFlags.NonPublic); agentEnableMethod?.Invoke(agent2, new object[] { aca }); academyInitializeMethod?.Invoke(aca, new object[] { }); agentEnableMethod?.Invoke(agent1, new object[] { aca }); Assert.AreEqual(false, agent1.IsDone()); Assert.AreEqual(false, agent2.IsDone()); // agent1 was not enabled when the academy started // The agents have been initialized Assert.AreEqual(0, agent1.agentResetCalls); Assert.AreEqual(0, agent2.agentResetCalls); Assert.AreEqual(1, agent1.initializeAgentCalls); Assert.AreEqual(1, agent2.initializeAgentCalls); Assert.AreEqual(0, agent1.agentActionCalls); Assert.AreEqual(0, agent2.agentActionCalls); } } public class EditModeTestStep { [Test] public void TestAcademy() { var acaGo = new GameObject("TestAcademy"); acaGo.AddComponent<TestAcademy>(); var aca = acaGo.GetComponent<TestAcademy>(); var academyInitializeMethod = typeof(Academy).GetMethod("InitializeEnvironment", BindingFlags.Instance | BindingFlags.NonPublic); academyInitializeMethod?.Invoke(aca, new object[] { }); var academyStepMethod = typeof(Academy).GetMethod("EnvironmentStep", BindingFlags.Instance | BindingFlags.NonPublic); var numberReset = 0; for (var i = 0; i < 10; i++) { Assert.AreEqual(1, aca.initializeAcademyCalls); Assert.AreEqual(numberReset, aca.GetEpisodeCount()); Assert.AreEqual(i, aca.GetStepCount()); Assert.AreEqual(i, aca.AcademyStepCalls); // The reset happens at the beginning of the first step if (i == 0) { numberReset += 1; } academyStepMethod?.Invoke(aca, new object[] { }); } } [Test] public void TestAgent() { var agentGo1 = new GameObject("TestAgent"); agentGo1.AddComponent<TestAgent>(); var agent1 = agentGo1.GetComponent<TestAgent>(); var agentGo2 = new GameObject("TestAgent"); agentGo2.AddComponent<TestAgent>(); var agent2 = agentGo2.GetComponent<TestAgent>(); var acaGo = new GameObject("TestAcademy"); acaGo.AddComponent<TestAcademy>(); var aca = acaGo.GetComponent<TestAcademy>(); var brain = TestBrain.Instantiate(); var agentEnableMethod = typeof(Agent).GetMethod( "OnEnableHelper", BindingFlags.Instance | BindingFlags.NonPublic); var academyInitializeMethod = typeof(Academy).GetMethod( "InitializeEnvironment", BindingFlags.Instance | BindingFlags.NonPublic); agent1.agentParameters = new AgentParameters(); agent2.agentParameters = new AgentParameters(); brain.brainParameters = new BrainParameters(); // We use event based so the agent will now try to send anything to the brain agent1.agentParameters.onDemandDecision = false; agent1.agentParameters.numberOfActionsBetweenDecisions = 2; // agent1 will take an action at every step and request a decision every 2 steps agent2.agentParameters.onDemandDecision = true; // agent2 will request decisions only when RequestDecision is called brain.brainParameters.vectorObservationSize = 0; brain.brainParameters.cameraResolutions = new Resolution[0]; agent1.GiveBrain(brain); agent2.GiveBrain(brain); agentEnableMethod?.Invoke(agent1, new object[] { aca }); academyInitializeMethod?.Invoke(aca, new object[] { }); var academyStepMethod = typeof(Academy).GetMethod( "EnvironmentStep", BindingFlags.Instance | BindingFlags.NonPublic); var numberAgent1Reset = 0; var numberAgent2Initialization = 0; var requestDecision = 0; var requestAction = 0; for (var i = 0; i < 50; i++) { Assert.AreEqual(numberAgent1Reset, agent1.agentResetCalls); // Agent2 is never reset since initialized after academy Assert.AreEqual(0, agent2.agentResetCalls); Assert.AreEqual(1, agent1.initializeAgentCalls); Assert.AreEqual(numberAgent2Initialization, agent2.initializeAgentCalls); Assert.AreEqual(i, agent1.agentActionCalls); Assert.AreEqual(requestAction, agent2.agentActionCalls); Assert.AreEqual((i + 1) / 2, agent1.collectObservationsCalls); Assert.AreEqual(requestDecision, agent2.collectObservationsCalls); // Agent 1 resets at the first step if (i == 0) { numberAgent1Reset += 1; } //Agent 2 is only initialized at step 2 if (i == 2) { agentEnableMethod?.Invoke(agent2, new object[] { aca }); numberAgent2Initialization += 1; } // We are testing request decision and request actions when called // at different intervals if ((i % 3 == 0) && (i > 2)) { //Every 3 steps after agent 2 is initialized, request decision requestDecision += 1; requestAction += 1; agent2.RequestDecision(); } else if ((i % 5 == 0) && (i > 2)) { // Every 5 steps after agent 2 is initialized, request action requestAction += 1; agent2.RequestAction(); } academyStepMethod?.Invoke(aca, new object[] { }); } } } public class EditModeTestReset { [Test] public void TestAcademy() { var acaGo = new GameObject("TestAcademy"); acaGo.AddComponent<TestAcademy>(); var aca = acaGo.GetComponent<TestAcademy>(); var academyInitializeMethod = typeof(Academy).GetMethod( "InitializeEnvironment", BindingFlags.Instance | BindingFlags.NonPublic); academyInitializeMethod?.Invoke(aca, new object[] { }); var academyStepMethod = typeof(Academy).GetMethod( "EnvironmentStep", BindingFlags.Instance | BindingFlags.NonPublic); var numberReset = 0; var stepsSinceReset = 0; for (var i = 0; i < 50; i++) { Assert.AreEqual(stepsSinceReset, aca.GetStepCount()); Assert.AreEqual(1, aca.initializeAcademyCalls); Assert.AreEqual(numberReset, aca.GetEpisodeCount()); Assert.AreEqual(i, aca.AcademyStepCalls); // Academy resets at the first step if (i == 0) { numberReset += 1; } stepsSinceReset += 1; academyStepMethod.Invoke((object)aca, new object[] { }); } } [Test] public void TestAgent() { var agentGo1 = new GameObject("TestAgent"); agentGo1.AddComponent<TestAgent>(); var agent1 = agentGo1.GetComponent<TestAgent>(); var agentGo2 = new GameObject("TestAgent"); agentGo2.AddComponent<TestAgent>(); var agent2 = agentGo2.GetComponent<TestAgent>(); var acaGo = new GameObject("TestAcademy"); acaGo.AddComponent<TestAcademy>(); var aca = acaGo.GetComponent<TestAcademy>(); var brain = TestBrain.Instantiate(); var agentEnableMethod = typeof(Agent).GetMethod( "OnEnableHelper", BindingFlags.Instance | BindingFlags.NonPublic); var academyInitializeMethod = typeof(Academy).GetMethod( "InitializeEnvironment", BindingFlags.Instance | BindingFlags.NonPublic); var academyStepMethod = typeof(Academy).GetMethod( "EnvironmentStep", BindingFlags.Instance | BindingFlags.NonPublic); agent1.agentParameters = new AgentParameters(); agent2.agentParameters = new AgentParameters(); brain.brainParameters = new BrainParameters(); // We use event based so the agent will now try to send anything to the brain agent1.agentParameters.onDemandDecision = false; agent1.agentParameters.numberOfActionsBetweenDecisions = 2; // agent1 will take an action at every step and request a decision every 2 steps agent2.agentParameters.onDemandDecision = true; // agent2 will request decisions only when RequestDecision is called brain.brainParameters.vectorObservationSize = 0; brain.brainParameters.cameraResolutions = new Resolution[0]; agent1.GiveBrain(brain); agent2.GiveBrain(brain); agentEnableMethod?.Invoke(agent2, new object[] { aca }); academyInitializeMethod?.Invoke(aca, new object[] { }); var numberAgent1Reset = 0; var numberAgent2Reset = 0; var numberAcaReset = 0; var acaStepsSinceReset = 0; var agent2StepSinceReset = 0; for (var i = 0; i < 5000; i++) { Assert.AreEqual(acaStepsSinceReset, aca.GetStepCount()); Assert.AreEqual(1, aca.initializeAcademyCalls); Assert.AreEqual(numberAcaReset, aca.GetEpisodeCount()); Assert.AreEqual(i, aca.AcademyStepCalls); Assert.AreEqual(agent2StepSinceReset, agent2.GetStepCount()); Assert.AreEqual(numberAgent1Reset, agent1.agentResetCalls); Assert.AreEqual(numberAgent2Reset, agent2.agentResetCalls); // Agent 2 and academy reset at the first step if (i == 0) { numberAcaReset += 1; numberAgent2Reset += 1; } //Agent 1 is only initialized at step 2 if (i == 2) { agentEnableMethod?.Invoke(agent1, new object[] { aca }); } // Set agent 1 to done every 11 steps to test behavior if (i % 11 == 5) { agent1.Done(); } // Resetting agent 2 regularly if (i % 13 == 3) { if (!(agent2.IsDone())) { // If the agent was already reset before the request decision // We should not reset again agent2.Done(); numberAgent2Reset += 1; agent2StepSinceReset = 0; } } // Request a decision for agent 2 regularly if (i % 3 == 2) { agent2.RequestDecision(); } else if (i % 5 == 1) { // Request an action without decision regularly agent2.RequestAction(); } if (agent1.IsDone() && (((acaStepsSinceReset) % agent1.agentParameters.numberOfActionsBetweenDecisions == 0))) { numberAgent1Reset += 1; } acaStepsSinceReset += 1; agent2StepSinceReset += 1; //Agent 1 is only initialized at step 2 if (i < 2) { } academyStepMethod?.Invoke(aca, new object[] { }); } } } public class EditModeTestMiscellaneous { [Test] public void TestResetOnDone() { var agentGo1 = new GameObject("TestAgent"); agentGo1.AddComponent<TestAgent>(); var agent1 = agentGo1.GetComponent<TestAgent>(); var agentGo2 = new GameObject("TestAgent"); agentGo2.AddComponent<TestAgent>(); var agent2 = agentGo2.GetComponent<TestAgent>(); var acaGo = new GameObject("TestAcademy"); acaGo.AddComponent<TestAcademy>(); var aca = acaGo.GetComponent<TestAcademy>(); var brain = TestBrain.Instantiate(); var agentEnableMethod = typeof(Agent).GetMethod( "OnEnableHelper", BindingFlags.Instance | BindingFlags.NonPublic); var academyInitializeMethod = typeof(Academy).GetMethod( "InitializeEnvironment", BindingFlags.Instance | BindingFlags.NonPublic); var academyStepMethod = typeof(Academy).GetMethod( "EnvironmentStep", BindingFlags.Instance | BindingFlags.NonPublic); agent1.agentParameters = new AgentParameters(); agent2.agentParameters = new AgentParameters(); brain.brainParameters = new BrainParameters(); // We use event based so the agent will now try to send anything to the brain agent1.agentParameters.onDemandDecision = false; // agent1 will take an action at every step and request a decision every steps agent1.agentParameters.numberOfActionsBetweenDecisions = 1; // agent2 will request decisions only when RequestDecision is called agent2.agentParameters.onDemandDecision = true; agent1.agentParameters.maxStep = 20; //Here we specify that the agent does not reset when done agent1.agentParameters.resetOnDone = false; agent2.agentParameters.resetOnDone = false; brain.brainParameters.vectorObservationSize = 0; brain.brainParameters.cameraResolutions = new Resolution[0]; agent1.GiveBrain(brain); agent2.GiveBrain(brain); agentEnableMethod?.Invoke(agent2, new object[] { aca }); academyInitializeMethod?.Invoke(aca, new object[] { }); agentEnableMethod?.Invoke(agent1, new object[] { aca }); var agent1ResetOnDone = 0; var agent2ResetOnDone = 0; var agent1StepSinceReset = 0; var agent2StepSinceReset = 0; for (var i = 0; i < 50; i++) { Assert.AreEqual(i, aca.AcademyStepCalls); Assert.AreEqual(agent1StepSinceReset, agent1.GetStepCount()); Assert.AreEqual(agent2StepSinceReset, agent2.GetStepCount()); Assert.AreEqual(agent1ResetOnDone, agent1.agentOnDoneCalls); Assert.AreEqual(agent2ResetOnDone, agent2.agentOnDoneCalls); // we request a decision at each step agent2.RequestDecision(); if (agent1ResetOnDone == 0) agent1StepSinceReset += 1; if (agent2ResetOnDone == 0) agent2StepSinceReset += 1; if ((i > 2) && (i % 21 == 0)) { agent1ResetOnDone = 1; } if (i == 31) { agent2ResetOnDone = 1; agent2.Done(); } academyStepMethod?.Invoke(aca, new object[] { }); } } [Test] public void TestCumulativeReward() { var agentGo1 = new GameObject("TestAgent"); agentGo1.AddComponent<TestAgent>(); var agent1 = agentGo1.GetComponent<TestAgent>(); var agentGo2 = new GameObject("TestAgent"); agentGo2.AddComponent<TestAgent>(); var agent2 = agentGo2.GetComponent<TestAgent>(); var acaGo = new GameObject("TestAcademy"); acaGo.AddComponent<TestAcademy>(); var aca = acaGo.GetComponent<TestAcademy>(); var brain = TestBrain.Instantiate(); var agentEnableMethod = typeof(Agent).GetMethod( "OnEnableHelper", BindingFlags.Instance | BindingFlags.NonPublic); var academyInitializeMethod = typeof(Academy).GetMethod( "InitializeEnvironment", BindingFlags.Instance | BindingFlags.NonPublic); var academyStepMethod = typeof(Academy).GetMethod( "EnvironmentStep", BindingFlags.Instance | BindingFlags.NonPublic); agent1.agentParameters = new AgentParameters(); agent2.agentParameters = new AgentParameters(); brain.brainParameters = new BrainParameters(); // We use event based so the agent will now try to send anything to the brain agent1.agentParameters.onDemandDecision = false; agent1.agentParameters.numberOfActionsBetweenDecisions = 3; // agent1 will take an action at every step and request a decision every 2 steps agent2.agentParameters.onDemandDecision = true; // agent2 will request decisions only when RequestDecision is called agent1.agentParameters.maxStep = 20; brain.brainParameters.vectorObservationSize = 0; brain.brainParameters.cameraResolutions = new Resolution[0]; agent1.GiveBrain(brain); agent2.GiveBrain(brain); agentEnableMethod?.Invoke(agent2, new object[] { aca }); academyInitializeMethod?.Invoke(aca, new object[] { }); agentEnableMethod?.Invoke(agent1, new object[] { aca }); var j = 0; for (var i = 0; i < 500; i++) { agent2.RequestAction(); Assert.LessOrEqual(Mathf.Abs(j * 0.1f + j * 10f - agent1.GetCumulativeReward()), 0.05f); Assert.LessOrEqual(Mathf.Abs(i * 0.1f - agent2.GetCumulativeReward()), 0.05f); academyStepMethod?.Invoke(aca, new object[] { }); agent1.AddReward(10f); if ((i % 21 == 0) && (i > 0)) { j = 0; } j++; } } } }
592
ml-agents
openai
C#
using NUnit.Framework; using MLAgents.InferenceBrain.Utils; namespace MLAgents.Tests { public class MultinomialTest { [Test] public void TestDim1() { var m = new Multinomial(2018); var cdf = new[] {1f}; Assert.AreEqual(0, m.Sample(cdf)); Assert.AreEqual(0, m.Sample(cdf)); Assert.AreEqual(0, m.Sample(cdf)); } [Test] public void TestDim1Unscaled() { var m = new Multinomial(2018); var cdf = new[] {0.1f}; Assert.AreEqual(0, m.Sample(cdf)); Assert.AreEqual(0, m.Sample(cdf)); Assert.AreEqual(0, m.Sample(cdf)); } [Test] public void TestDim3() { var m = new Multinomial(2018); var cdf = new[] {0.1f, 0.3f, 1.0f}; Assert.AreEqual(2, m.Sample(cdf)); Assert.AreEqual(2, m.Sample(cdf)); Assert.AreEqual(2, m.Sample(cdf)); Assert.AreEqual(1, m.Sample(cdf)); } [Test] public void TestDim3Unscaled() { var m = new Multinomial(2018); var cdf = new[] {0.05f, 0.15f, 0.5f}; Assert.AreEqual(2, m.Sample(cdf)); Assert.AreEqual(2, m.Sample(cdf)); Assert.AreEqual(2, m.Sample(cdf)); Assert.AreEqual(1, m.Sample(cdf)); } } }
55
ml-agents
openai
C#
using System; using NUnit.Framework; using MLAgents.InferenceBrain.Utils; namespace MLAgents.Tests { public class RandomNormalTest { private const float k_FirstValue = -1.19580f; private const float k_SecondValue = -0.97345f; private const double k_Epsilon = 0.0001; [Test] public void RandomNormalTestTwoDouble() { var rn = new RandomNormal(2018); Assert.AreEqual(k_FirstValue, rn.NextDouble(), k_Epsilon); Assert.AreEqual(k_SecondValue, rn.NextDouble(), k_Epsilon); } [Test] public void RandomNormalTestWithMean() { var rn = new RandomNormal(2018, 5.0f); Assert.AreEqual(k_FirstValue + 5.0, rn.NextDouble(), k_Epsilon); Assert.AreEqual(k_SecondValue + 5.0, rn.NextDouble(), k_Epsilon); } [Test] public void RandomNormalTestWithStddev() { var rn = new RandomNormal(2018, 0.0f, 4.2f); Assert.AreEqual(k_FirstValue * 4.2, rn.NextDouble(), k_Epsilon); Assert.AreEqual(k_SecondValue * 4.2, rn.NextDouble(), k_Epsilon); } [Test] public void RandomNormalTestWithMeanStddev() { const float mean = -3.2f; const float stddev = 2.2f; var rn = new RandomNormal(2018, mean, stddev); Assert.AreEqual(k_FirstValue * stddev + mean, rn.NextDouble(), k_Epsilon); Assert.AreEqual(k_SecondValue * stddev + mean, rn.NextDouble(), k_Epsilon); } [Test] public void RandomNormalTestDistribution() { const float mean = -3.2f; const float stddev = 2.2f; var rn = new RandomNormal(2018, mean, stddev); const int numSamples = 100000; // Adapted from https://www.johndcook.com/blog/standard_deviation/ // Computes stddev and mean without losing precision double oldM = 0.0, newM = 0.0, oldS = 0.0, newS = 0.0; for (var i = 0; i < numSamples; i++) { var x = rn.NextDouble(); if (i == 0) { oldM = newM = x; oldS = 0.0; } else { newM = oldM + (x - oldM) / i; newS = oldS + (x - oldM) * (x - newM); // set up for next iteration oldM = newM; oldS = newS; } } var sampleMean = newM; var sampleVariance = newS / (numSamples - 1); var sampleStddev = Math.Sqrt(sampleVariance); // Note a larger epsilon here. We could get closer to the true values with more samples. Assert.AreEqual(mean, sampleMean, 0.01); Assert.AreEqual(stddev, sampleStddev, 0.01); } } }
92
ml-agents
openai
C#
using UnityEngine; using NUnit.Framework; namespace MLAgents.Tests { public class RayPerceptionTests : MonoBehaviour { [Test] public void TestPerception3D() { var angles = new[] {0f, 90f, 180f}; var tags = new[] {"test", "test_1"}; var go = new GameObject("MyGameObject"); var rayPer3D = go.AddComponent<RayPerception3D>(); var result = rayPer3D.Perceive(1f, angles , tags, 0f, 0f); Debug.Log(result.Count); Assert.IsTrue(result.Count == angles.Length * (tags.Length + 2)); } [Test] public void TestPerception2D() { var angles = new[] {0f, 90f, 180f}; var tags = new[] {"test", "test_1"}; var go = new GameObject("MyGameObject"); var rayPer2D = go.AddComponent<RayPerception2D>(); var result = rayPer2D.Perceive(1f, angles, tags); Assert.IsTrue(result.Count == angles.Length * (tags.Length + 2)); } } }
37
ml-agents
openai
C#
using System; using Barracuda; using MLAgents.InferenceBrain; using MLAgents.InferenceBrain.Utils; using NUnit.Framework; namespace MLAgents.Tests { public class TensorUtilsTest { [Test] public void RandomNormalTestTensorInt() { var rn = new RandomNormal(1982); var t = new TensorProxy { valueType = TensorProxy.TensorType.Integer }; Assert.Throws<NotImplementedException>( () => TensorUtils.FillTensorWithRandomNormal(t, rn)); } [Test] public void RandomNormalTestDataNull() { var rn = new RandomNormal(1982); var t = new TensorProxy { valueType = TensorProxy.TensorType.FloatingPoint }; Assert.Throws<ArgumentNullException>( () => TensorUtils.FillTensorWithRandomNormal(t, rn)); } [Test] public void RandomNormalTestTensor() { var rn = new RandomNormal(1982); var t = new TensorProxy { valueType = TensorProxy.TensorType.FloatingPoint, data = new Tensor(1, 3, 4, 2) }; TensorUtils.FillTensorWithRandomNormal(t, rn); var reference = new[] { -0.4315872f, -1.11074f, 0.3414804f, -1.130287f, 0.1413168f, -0.5105762f, -0.3027347f, -0.2645015f, 1.225356f, -0.02921959f, 0.3716498f, -1.092338f, 0.9561074f, -0.5018106f, 1.167787f, -0.7763879f, -0.07491868f, 0.5396146f, -0.1377991f, 0.3331701f, 0.06144788f, 0.9520947f, 1.088157f, -1.177194f, }; for (var i = 0; i < t.data.length; i++) { Assert.AreEqual(t.data[i], reference[i], 0.0001); } } } }
84
ml-agents
openai
C#
using NUnit.Framework; namespace MLAgents.Tests { public class UtilitiesTests { [Test] public void TestCumSum() { var output = Utilities.CumSum(new[] {1, 2, 3, 10}); CollectionAssert.AreEqual(output, new[] {0, 1, 3, 6, 16}); output = Utilities.CumSum(new int[0]); CollectionAssert.AreEqual(output, new[] {0}); output = Utilities.CumSum(new[] {100}); CollectionAssert.AreEqual(output, new[] {0, 100}); output = Utilities.CumSum(new[] {-1, 10}); CollectionAssert.AreEqual(output, new[] {0, -1, 9}); } } }
24
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class Ball3DAcademy : Academy { public override void AcademyReset() { Physics.gravity = new Vector3(0, -resetParameters["gravity"], 0); } public override void AcademyStep() { } }
15
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class Ball3DAgent : Agent { [Header("Specific to Ball3D")] public GameObject ball; private Rigidbody m_BallRb; private ResetParameters m_ResetParams; public override void InitializeAgent() { m_BallRb = ball.GetComponent<Rigidbody>(); var academy = FindObjectOfType<Academy>(); m_ResetParams = academy.resetParameters; SetResetParameters(); } public override void CollectObservations() { AddVectorObs(gameObject.transform.rotation.z); AddVectorObs(gameObject.transform.rotation.x); AddVectorObs(ball.transform.position - gameObject.transform.position); AddVectorObs(m_BallRb.velocity); } public override void AgentAction(float[] vectorAction, string textAction) { if (brain.brainParameters.vectorActionSpaceType == SpaceType.Continuous) { var actionZ = 2f * Mathf.Clamp(vectorAction[0], -1f, 1f); var actionX = 2f * Mathf.Clamp(vectorAction[1], -1f, 1f); if ((gameObject.transform.rotation.z < 0.25f && actionZ > 0f) || (gameObject.transform.rotation.z > -0.25f && actionZ < 0f)) { gameObject.transform.Rotate(new Vector3(0, 0, 1), actionZ); } if ((gameObject.transform.rotation.x < 0.25f && actionX > 0f) || (gameObject.transform.rotation.x > -0.25f && actionX < 0f)) { gameObject.transform.Rotate(new Vector3(1, 0, 0), actionX); } } if ((ball.transform.position.y - gameObject.transform.position.y) < -2f || Mathf.Abs(ball.transform.position.x - gameObject.transform.position.x) > 3f || Mathf.Abs(ball.transform.position.z - gameObject.transform.position.z) > 3f) { Done(); SetReward(-1f); } else { SetReward(0.1f); } } public override void AgentReset() { gameObject.transform.rotation = new Quaternion(0f, 0f, 0f, 0f); gameObject.transform.Rotate(new Vector3(1, 0, 0), Random.Range(-10f, 10f)); gameObject.transform.Rotate(new Vector3(0, 0, 1), Random.Range(-10f, 10f)); m_BallRb.velocity = new Vector3(0f, 0f, 0f); ball.transform.position = new Vector3(Random.Range(-1.5f, 1.5f), 4f, Random.Range(-1.5f, 1.5f)) + gameObject.transform.position; //Reset the parameters when the Agent is reset. SetResetParameters(); } public void SetBall() { //Set the attributes of the ball by fetching the information from the academy m_BallRb.mass = m_ResetParams["mass"]; var scale = m_ResetParams["scale"]; ball.transform.localScale = new Vector3(scale, scale, scale); } public void SetResetParameters() { SetBall(); } }
84
ml-agents
openai
C#
using System.Collections.Generic; using UnityEngine; using MLAgents; public class Ball3DDecision : Decision { public float rotationSpeed = 2f; public override float[] Decide( List<float> vectorObs, List<Texture2D> visualObs, float reward, bool done, List<float> memory) { if (brainParameters.vectorActionSpaceType == SpaceType.Continuous) { var act = new List<float>(); // state[5] is the velocity of the ball in the x orientation. // We use this number to control the Platform's z axis rotation speed, // so that the Platform is tilted in the x orientation correspondingly. act.Add(vectorObs[5] * rotationSpeed); // state[7] is the velocity of the ball in the z orientation. // We use this number to control the Platform's x axis rotation speed, // so that the Platform is tilted in the z orientation correspondingly. act.Add(-vectorObs[7] * rotationSpeed); return act.ToArray(); } // If the vector action space type is discrete, then we don't do anything. return new[] { 1f }; } public override List<float> MakeMemory( List<float> vectorObs, List<Texture2D> visualObs, float reward, bool done, List<float> memory) { return new List<float>(); } }
47
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class Ball3DHardAgent : Agent { [Header("Specific to Ball3DHard")] public GameObject ball; private Rigidbody m_BallRb; private ResetParameters m_ResetParams; public override void InitializeAgent() { m_BallRb = ball.GetComponent<Rigidbody>(); var academy = FindObjectOfType<Academy>(); m_ResetParams = academy.resetParameters; SetResetParameters(); } public override void CollectObservations() { AddVectorObs(gameObject.transform.rotation.z); AddVectorObs(gameObject.transform.rotation.x); AddVectorObs((ball.transform.position - gameObject.transform.position)); } public override void AgentAction(float[] vectorAction, string textAction) { if (brain.brainParameters.vectorActionSpaceType == SpaceType.Continuous) { var actionZ = 2f * Mathf.Clamp(vectorAction[0], -1f, 1f); var actionX = 2f * Mathf.Clamp(vectorAction[1], -1f, 1f); if ((gameObject.transform.rotation.z < 0.25f && actionZ > 0f) || (gameObject.transform.rotation.z > -0.25f && actionZ < 0f)) { gameObject.transform.Rotate(new Vector3(0, 0, 1), actionZ); } if ((gameObject.transform.rotation.x < 0.25f && actionX > 0f) || (gameObject.transform.rotation.x > -0.25f && actionX < 0f)) { gameObject.transform.Rotate(new Vector3(1, 0, 0), actionX); } } if ((ball.transform.position.y - gameObject.transform.position.y) < -2f || Mathf.Abs(ball.transform.position.x - gameObject.transform.position.x) > 3f || Mathf.Abs(ball.transform.position.z - gameObject.transform.position.z) > 3f) { Done(); SetReward(-1f); } else { SetReward(0.1f); } } public override void AgentReset() { gameObject.transform.rotation = new Quaternion(0f, 0f, 0f, 0f); gameObject.transform.Rotate(new Vector3(1, 0, 0), Random.Range(-10f, 10f)); gameObject.transform.Rotate(new Vector3(0, 0, 1), Random.Range(-10f, 10f)); m_BallRb.velocity = new Vector3(0f, 0f, 0f); ball.transform.position = new Vector3(Random.Range(-1.5f, 1.5f), 4f, Random.Range(-1.5f, 1.5f)) + gameObject.transform.position; } public void SetBall() { //Set the attributes of the ball by fetching the information from the academy m_BallRb.mass = m_ResetParams["mass"]; var scale = m_ResetParams["scale"]; ball.transform.localScale = new Vector3(scale, scale, scale); } public void SetResetParameters() { SetBall(); } }
81
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class BasicAcademy : Academy { public override void AcademyReset() { } public override void AcademyStep() { } }
14
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class BasicAgent : Agent { [Header("Specific to Basic")] private BasicAcademy m_Academy; public float timeBetweenDecisionsAtInference; private float m_TimeSinceDecision; int m_Position; int m_SmallGoalPosition; int m_LargeGoalPosition; public GameObject largeGoal; public GameObject smallGoal; int m_MinPosition; int m_MaxPosition; public override void InitializeAgent() { m_Academy = FindObjectOfType(typeof(BasicAcademy)) as BasicAcademy; } public override void CollectObservations() { AddVectorObs(m_Position, 20); } public override void AgentAction(float[] vectorAction, string textAction) { var movement = (int)vectorAction[0]; var direction = 0; switch (movement) { case 1: direction = -1; break; case 2: direction = 1; break; } m_Position += direction; if (m_Position < m_MinPosition) { m_Position = m_MinPosition; } if (m_Position > m_MaxPosition) { m_Position = m_MaxPosition; } gameObject.transform.position = new Vector3(m_Position - 10f, 0f, 0f); AddReward(-0.01f); if (m_Position == m_SmallGoalPosition) { Done(); AddReward(0.1f); } if (m_Position == m_LargeGoalPosition) { Done(); AddReward(1f); } } public override void AgentReset() { m_Position = 10; m_MinPosition = 0; m_MaxPosition = 20; m_SmallGoalPosition = 7; m_LargeGoalPosition = 17; smallGoal.transform.position = new Vector3(m_SmallGoalPosition - 10f, 0f, 0f); largeGoal.transform.position = new Vector3(m_LargeGoalPosition - 10f, 0f, 0f); } public override void AgentOnDone() { } public void FixedUpdate() { WaitTimeInference(); } private void WaitTimeInference() { if (!m_Academy.GetIsInference()) { RequestDecision(); } else { if (m_TimeSinceDecision >= timeBetweenDecisionsAtInference) { m_TimeSinceDecision = 0f; RequestDecision(); } else { m_TimeSinceDecision += Time.fixedDeltaTime; } } } }
105
ml-agents
openai
C#
using System.Collections.Generic; using UnityEngine; using MLAgents; public class BasicDecision : Decision { public override float[] Decide( List<float> vectorObs, List<Texture2D> visualObs, float reward, bool done, List<float> memory) { return new[] { 1f }; } public override List<float> MakeMemory( List<float> vectorObs, List<Texture2D> visualObs, float reward, bool done, List<float> memory) { return new List<float>(); } }
27
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class BouncerAcademy : Academy { public float gravityMultiplier = 1f; public override void InitializeAcademy() { Physics.gravity = new Vector3(0, -9.8f * gravityMultiplier, 0); } public override void AcademyReset() { } public override void AcademyStep() { } }
21
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class BouncerAgent : Agent { [Header("Bouncer Specific")] public GameObject target; public GameObject bodyObject; Rigidbody m_Rb; Vector3 m_LookDir; public float strength = 10f; float m_JumpCooldown; int m_NumberJumps = 20; int m_JumpLeft = 20; ResetParameters m_ResetParams; public override void InitializeAgent() { m_Rb = gameObject.GetComponent<Rigidbody>(); m_LookDir = Vector3.zero; var academy = FindObjectOfType<Academy>(); m_ResetParams = academy.resetParameters; SetResetParameters(); } public override void CollectObservations() { AddVectorObs(gameObject.transform.localPosition); AddVectorObs(target.transform.localPosition); } public override void AgentAction(float[] vectorAction, string textAction) { for (var i = 0; i < vectorAction.Length; i++) { vectorAction[i] = Mathf.Clamp(vectorAction[i], -1f, 1f); } var x = vectorAction[0]; var y = ScaleAction(vectorAction[1], 0, 1); var z = vectorAction[2]; m_Rb.AddForce(new Vector3(x, y + 1, z) * strength); AddReward(-0.05f * ( vectorAction[0] * vectorAction[0] + vectorAction[1] * vectorAction[1] + vectorAction[2] * vectorAction[2]) / 3f); m_LookDir = new Vector3(x, y, z); } public override void AgentReset() { gameObject.transform.localPosition = new Vector3( (1 - 2 * Random.value) * 5, 2, (1 - 2 * Random.value) * 5); m_Rb.velocity = default(Vector3); var environment = gameObject.transform.parent.gameObject; var targets = environment.GetComponentsInChildren<BouncerTarget>(); foreach (var t in targets) { t.Respawn(); } m_JumpLeft = m_NumberJumps; SetResetParameters(); } public override void AgentOnDone() { } private void FixedUpdate() { if (Physics.Raycast(transform.position, new Vector3(0f, -1f, 0f), 0.51f) && m_JumpCooldown <= 0f) { RequestDecision(); m_JumpLeft -= 1; m_JumpCooldown = 0.1f; m_Rb.velocity = default(Vector3); } m_JumpCooldown -= Time.fixedDeltaTime; if (gameObject.transform.position.y < -1) { AddReward(-1); Done(); return; } if (gameObject.transform.localPosition.x < -19 || gameObject.transform.localPosition.x > 19 || gameObject.transform.localPosition.z < -19 || gameObject.transform.localPosition.z > 19) { AddReward(-1); Done(); return; } if (m_JumpLeft == 0) { Done(); } } private void Update() { if (m_LookDir.magnitude > float.Epsilon) { bodyObject.transform.rotation = Quaternion.Lerp(bodyObject.transform.rotation, Quaternion.LookRotation(m_LookDir), Time.deltaTime * 10f); } } public void SetTargetScale() { var targetScale = m_ResetParams["target_scale"]; target.transform.localScale = new Vector3(targetScale, targetScale, targetScale); } public void SetResetParameters() { SetTargetScale(); } }
128
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class BouncerTarget : MonoBehaviour { // Update is called once per frame void FixedUpdate() { gameObject.transform.Rotate(new Vector3(1, 0, 0), 0.5f); } private void OnTriggerEnter(Collider collision) { var agent = collision.gameObject.GetComponent<Agent>(); if (agent != null) { agent.AddReward(1f); Respawn(); } } public void Respawn() { gameObject.transform.localPosition = new Vector3( (1 - 2 * Random.value) * 5f, 2f + Random.value * 5f, (1 - 2 * Random.value) * 5f); } }
31
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class CrawlerAcademy : Academy { public override void InitializeAcademy() { Monitor.verticalOffset = 1f; Physics.defaultSolverIterations = 12; Physics.defaultSolverVelocityIterations = 12; Time.fixedDeltaTime = 0.01333f; // (75fps). default is .2 (60fps) Time.maximumDeltaTime = .15f; // Default is .33 } public override void AcademyReset() { } public override void AcademyStep() { } }
23
ml-agents
openai
C#
using UnityEngine; using MLAgents; [RequireComponent(typeof(JointDriveController))] // Required to set joint forces public class CrawlerAgent : Agent { [Header("Target To Walk Towards")][Space(10)] public Transform target; public Transform ground; public bool detectTargets; public bool targetIsStatic = false; public bool respawnTargetWhenTouched; public float targetSpawnRadius; [Header("Body Parts")][Space(10)] public Transform body; public Transform leg0Upper; public Transform leg0Lower; public Transform leg1Upper; public Transform leg1Lower; public Transform leg2Upper; public Transform leg2Lower; public Transform leg3Upper; public Transform leg3Lower; [Header("Joint Settings")][Space(10)] JointDriveController m_JdController; Vector3 m_DirToTarget; float m_MovingTowardsDot; float m_FacingDot; [Header("Reward Functions To Use")][Space(10)] public bool rewardMovingTowardsTarget; // Agent should move towards target public bool rewardFacingTarget; // Agent should face the target public bool rewardUseTimePenalty; // Hurry up [Header("Foot Grounded Visualization")][Space(10)] public bool useFootGroundedVisualization; public MeshRenderer foot0; public MeshRenderer foot1; public MeshRenderer foot2; public MeshRenderer foot3; public Material groundedMaterial; public Material unGroundedMaterial; bool m_IsNewDecisionStep; int m_CurrentDecisionStep; Quaternion m_LookRotation; Matrix4x4 m_TargetDirMatrix; public override void InitializeAgent() { m_JdController = GetComponent<JointDriveController>(); m_CurrentDecisionStep = 1; m_DirToTarget = target.position - body.position; //Setup each body part m_JdController.SetupBodyPart(body); m_JdController.SetupBodyPart(leg0Upper); m_JdController.SetupBodyPart(leg0Lower); m_JdController.SetupBodyPart(leg1Upper); m_JdController.SetupBodyPart(leg1Lower); m_JdController.SetupBodyPart(leg2Upper); m_JdController.SetupBodyPart(leg2Lower); m_JdController.SetupBodyPart(leg3Upper); m_JdController.SetupBodyPart(leg3Lower); } /// <summary> /// We only need to change the joint settings based on decision freq. /// </summary> public void IncrementDecisionTimer() { if (m_CurrentDecisionStep == agentParameters.numberOfActionsBetweenDecisions || agentParameters.numberOfActionsBetweenDecisions == 1) { m_CurrentDecisionStep = 1; m_IsNewDecisionStep = true; } else { m_CurrentDecisionStep++; m_IsNewDecisionStep = false; } } /// <summary> /// Add relevant information on each body part to observations. /// </summary> public void CollectObservationBodyPart(BodyPart bp) { var rb = bp.rb; AddVectorObs(bp.groundContact.touchingGround ? 1 : 0); // Whether the bp touching the ground var velocityRelativeToLookRotationToTarget = m_TargetDirMatrix.inverse.MultiplyVector(rb.velocity); AddVectorObs(velocityRelativeToLookRotationToTarget); var angularVelocityRelativeToLookRotationToTarget = m_TargetDirMatrix.inverse.MultiplyVector(rb.angularVelocity); AddVectorObs(angularVelocityRelativeToLookRotationToTarget); if (bp.rb.transform != body) { var localPosRelToBody = body.InverseTransformPoint(rb.position); AddVectorObs(localPosRelToBody); AddVectorObs(bp.currentXNormalizedRot); // Current x rot AddVectorObs(bp.currentYNormalizedRot); // Current y rot AddVectorObs(bp.currentZNormalizedRot); // Current z rot AddVectorObs(bp.currentStrength / m_JdController.maxJointForceLimit); } } public override void CollectObservations() { m_JdController.GetCurrentJointForces(); // Update pos to target m_DirToTarget = target.position - body.position; m_LookRotation = Quaternion.LookRotation(m_DirToTarget); m_TargetDirMatrix = Matrix4x4.TRS(Vector3.zero, m_LookRotation, Vector3.one); RaycastHit hit; if (Physics.Raycast(body.position, Vector3.down, out hit, 10.0f)) { AddVectorObs(hit.distance); } else AddVectorObs(10.0f); // Forward & up to help with orientation var bodyForwardRelativeToLookRotationToTarget = m_TargetDirMatrix.inverse.MultiplyVector(body.forward); AddVectorObs(bodyForwardRelativeToLookRotationToTarget); var bodyUpRelativeToLookRotationToTarget = m_TargetDirMatrix.inverse.MultiplyVector(body.up); AddVectorObs(bodyUpRelativeToLookRotationToTarget); foreach (var bodyPart in m_JdController.bodyPartsDict.Values) { CollectObservationBodyPart(bodyPart); } } /// <summary> /// Agent touched the target /// </summary> public void TouchedTarget() { AddReward(1f); if (respawnTargetWhenTouched) { GetRandomTargetPos(); } } /// <summary> /// Moves target to a random position within specified radius. /// </summary> public void GetRandomTargetPos() { var newTargetPos = Random.insideUnitSphere * targetSpawnRadius; newTargetPos.y = 5; target.position = newTargetPos + ground.position; } public override void AgentAction(float[] vectorAction, string textAction) { if (detectTargets) { foreach (var bodyPart in m_JdController.bodyPartsDict.Values) { if (bodyPart.targetContact && !IsDone() && bodyPart.targetContact.touchingTarget) { TouchedTarget(); } } } // If enabled the feet will light up green when the foot is grounded. // This is just a visualization and isn't necessary for function if (useFootGroundedVisualization) { foot0.material = m_JdController.bodyPartsDict[leg0Lower].groundContact.touchingGround ? groundedMaterial : unGroundedMaterial; foot1.material = m_JdController.bodyPartsDict[leg1Lower].groundContact.touchingGround ? groundedMaterial : unGroundedMaterial; foot2.material = m_JdController.bodyPartsDict[leg2Lower].groundContact.touchingGround ? groundedMaterial : unGroundedMaterial; foot3.material = m_JdController.bodyPartsDict[leg3Lower].groundContact.touchingGround ? groundedMaterial : unGroundedMaterial; } // Joint update logic only needs to happen when a new decision is made if (m_IsNewDecisionStep) { // The dictionary with all the body parts in it are in the jdController var bpDict = m_JdController.bodyPartsDict; var i = -1; // Pick a new target joint rotation bpDict[leg0Upper].SetJointTargetRotation(vectorAction[++i], vectorAction[++i], 0); bpDict[leg1Upper].SetJointTargetRotation(vectorAction[++i], vectorAction[++i], 0); bpDict[leg2Upper].SetJointTargetRotation(vectorAction[++i], vectorAction[++i], 0); bpDict[leg3Upper].SetJointTargetRotation(vectorAction[++i], vectorAction[++i], 0); bpDict[leg0Lower].SetJointTargetRotation(vectorAction[++i], 0, 0); bpDict[leg1Lower].SetJointTargetRotation(vectorAction[++i], 0, 0); bpDict[leg2Lower].SetJointTargetRotation(vectorAction[++i], 0, 0); bpDict[leg3Lower].SetJointTargetRotation(vectorAction[++i], 0, 0); // Update joint strength bpDict[leg0Upper].SetJointStrength(vectorAction[++i]); bpDict[leg1Upper].SetJointStrength(vectorAction[++i]); bpDict[leg2Upper].SetJointStrength(vectorAction[++i]); bpDict[leg3Upper].SetJointStrength(vectorAction[++i]); bpDict[leg0Lower].SetJointStrength(vectorAction[++i]); bpDict[leg1Lower].SetJointStrength(vectorAction[++i]); bpDict[leg2Lower].SetJointStrength(vectorAction[++i]); bpDict[leg3Lower].SetJointStrength(vectorAction[++i]); } // Set reward for this step according to mixture of the following elements. if (rewardMovingTowardsTarget) { RewardFunctionMovingTowards(); } if (rewardFacingTarget) { RewardFunctionFacingTarget(); } if (rewardUseTimePenalty) { RewardFunctionTimePenalty(); } IncrementDecisionTimer(); } /// <summary> /// Reward moving towards target & Penalize moving away from target. /// </summary> void RewardFunctionMovingTowards() { m_MovingTowardsDot = Vector3.Dot(m_JdController.bodyPartsDict[body].rb.velocity, m_DirToTarget.normalized); AddReward(0.03f * m_MovingTowardsDot); } /// <summary> /// Reward facing target & Penalize facing away from target /// </summary> void RewardFunctionFacingTarget() { m_FacingDot = Vector3.Dot(m_DirToTarget.normalized, body.forward); AddReward(0.01f * m_FacingDot); } /// <summary> /// Existential penalty for time-contrained tasks. /// </summary> void RewardFunctionTimePenalty() { AddReward(-0.001f); } /// <summary> /// Loop over body parts and reset them to initial conditions. /// </summary> public override void AgentReset() { if (m_DirToTarget != Vector3.zero) { transform.rotation = Quaternion.LookRotation(m_DirToTarget); } transform.Rotate(Vector3.up, Random.Range(0.0f, 360.0f)); foreach (var bodyPart in m_JdController.bodyPartsDict.Values) { bodyPart.Reset(bodyPart); } if (!targetIsStatic) { GetRandomTargetPos(); } m_IsNewDecisionStep = true; m_CurrentDecisionStep = 1; } }
293
ml-agents
openai
C#
using UnityEngine; using UnityEngine.UI; using MLAgents; public class FoodCollectorAcademy : Academy { [HideInInspector] public GameObject[] agents; [HideInInspector] public FoodCollectorArea[] listArea; public int totalScore; public Text scoreText; public override void AcademyReset() { ClearObjects(GameObject.FindGameObjectsWithTag("food")); ClearObjects(GameObject.FindGameObjectsWithTag("badFood")); agents = GameObject.FindGameObjectsWithTag("agent"); listArea = FindObjectsOfType<FoodCollectorArea>(); foreach (var fa in listArea) { fa.ResetFoodArea(agents); } totalScore = 0; } void ClearObjects(GameObject[] objects) { foreach (var food in objects) { Destroy(food); } } public override void AcademyStep() { scoreText.text = string.Format(@"Score: {0}", totalScore); } }
42
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class FoodCollectorAgent : Agent { private FoodCollectorAcademy m_MyAcademy; public GameObject area; FoodCollectorArea m_MyArea; bool m_Frozen; bool m_Poisoned; bool m_Satiated; bool m_Shoot; float m_FrozenTime; float m_EffectTime; Rigidbody m_AgentRb; private float m_LaserLength; // Speed of agent rotation. public float turnSpeed = 300; // Speed of agent movement. public float moveSpeed = 2; public Material normalMaterial; public Material badMaterial; public Material goodMaterial; public Material frozenMaterial; public GameObject myLaser; public bool contribute; private RayPerception3D m_RayPer; public bool useVectorObs; public override void InitializeAgent() { base.InitializeAgent(); m_AgentRb = GetComponent<Rigidbody>(); Monitor.verticalOffset = 1f; m_MyArea = area.GetComponent<FoodCollectorArea>(); m_RayPer = GetComponent<RayPerception3D>(); m_MyAcademy = FindObjectOfType<FoodCollectorAcademy>(); SetResetParameters(); } public override void CollectObservations() { if (useVectorObs) { const float rayDistance = 50f; float[] rayAngles = { 20f, 90f, 160f, 45f, 135f, 70f, 110f }; string[] detectableObjects = { "food", "agent", "wall", "badFood", "frozenAgent" }; AddVectorObs(m_RayPer.Perceive(rayDistance, rayAngles, detectableObjects, 0f, 0f)); var localVelocity = transform.InverseTransformDirection(m_AgentRb.velocity); AddVectorObs(localVelocity.x); AddVectorObs(localVelocity.z); AddVectorObs(System.Convert.ToInt32(m_Frozen)); AddVectorObs(System.Convert.ToInt32(m_Shoot)); } } public Color32 ToColor(int hexVal) { var r = (byte)((hexVal >> 16) & 0xFF); var g = (byte)((hexVal >> 8) & 0xFF); var b = (byte)(hexVal & 0xFF); return new Color32(r, g, b, 255); } public void MoveAgent(float[] act) { m_Shoot = false; if (Time.time > m_FrozenTime + 4f && m_Frozen) { Unfreeze(); } if (Time.time > m_EffectTime + 0.5f) { if (m_Poisoned) { Unpoison(); } if (m_Satiated) { Unsatiate(); } } var dirToGo = Vector3.zero; var rotateDir = Vector3.zero; if (!m_Frozen) { var shootCommand = false; if (brain.brainParameters.vectorActionSpaceType == SpaceType.Continuous) { dirToGo = transform.forward * Mathf.Clamp(act[0], -1f, 1f); rotateDir = transform.up * Mathf.Clamp(act[1], -1f, 1f); shootCommand = Mathf.Clamp(act[2], -1f, 1f) > 0.5f; } else { var forwardAxis = (int)act[0]; var rightAxis = (int)act[1]; var rotateAxis = (int)act[2]; var shootAxis = (int)act[3]; switch (forwardAxis) { case 1: dirToGo = transform.forward; break; case 2: dirToGo = -transform.forward; break; } switch (rightAxis) { case 1: dirToGo = transform.right; break; case 2: dirToGo = -transform.right; break; } switch (rotateAxis) { case 1: rotateDir = -transform.up; break; case 2: rotateDir = transform.up; break; } switch (shootAxis) { case 1: shootCommand = true; break; } } if (shootCommand) { m_Shoot = true; dirToGo *= 0.5f; m_AgentRb.velocity *= 0.75f; } m_AgentRb.AddForce(dirToGo * moveSpeed, ForceMode.VelocityChange); transform.Rotate(rotateDir, Time.fixedDeltaTime * turnSpeed); } if (m_AgentRb.velocity.sqrMagnitude > 25f) // slow it down { m_AgentRb.velocity *= 0.95f; } if (m_Shoot) { var myTransform = transform; myLaser.transform.localScale = new Vector3(1f, 1f, m_LaserLength); var position = myTransform.TransformDirection(RayPerception3D.PolarToCartesian(25f, 90f)); Debug.DrawRay(myTransform.position, position, Color.red, 0f, true); RaycastHit hit; if (Physics.SphereCast(transform.position, 2f, position, out hit, 25f)) { if (hit.collider.gameObject.CompareTag("agent")) { hit.collider.gameObject.GetComponent<FoodCollectorAgent>().Freeze(); } } } else { myLaser.transform.localScale = new Vector3(0f, 0f, 0f); } } void Freeze() { gameObject.tag = "frozenAgent"; m_Frozen = true; m_FrozenTime = Time.time; gameObject.GetComponentInChildren<Renderer>().material = frozenMaterial; } void Unfreeze() { m_Frozen = false; gameObject.tag = "agent"; gameObject.GetComponentInChildren<Renderer>().material = normalMaterial; } void Poison() { m_Poisoned = true; m_EffectTime = Time.time; gameObject.GetComponentInChildren<Renderer>().material = badMaterial; } void Unpoison() { m_Poisoned = false; gameObject.GetComponentInChildren<Renderer>().material = normalMaterial; } void Satiate() { m_Satiated = true; m_EffectTime = Time.time; gameObject.GetComponentInChildren<Renderer>().material = goodMaterial; } void Unsatiate() { m_Satiated = false; gameObject.GetComponentInChildren<Renderer>().material = normalMaterial; } public override void AgentAction(float[] vectorAction, string textAction) { MoveAgent(vectorAction); } public override void AgentReset() { Unfreeze(); Unpoison(); Unsatiate(); m_Shoot = false; m_AgentRb.velocity = Vector3.zero; myLaser.transform.localScale = new Vector3(0f, 0f, 0f); transform.position = new Vector3(Random.Range(-m_MyArea.range, m_MyArea.range), 2f, Random.Range(-m_MyArea.range, m_MyArea.range)) + area.transform.position; transform.rotation = Quaternion.Euler(new Vector3(0f, Random.Range(0, 360))); SetResetParameters(); } void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("food")) { Satiate(); collision.gameObject.GetComponent<FoodLogic>().OnEaten(); AddReward(1f); if (contribute) { m_MyAcademy.totalScore += 1; } } if (collision.gameObject.CompareTag("badFood")) { Poison(); collision.gameObject.GetComponent<FoodLogic>().OnEaten(); AddReward(-1f); if (contribute) { m_MyAcademy.totalScore -= 1; } } } public override void AgentOnDone() { } public void SetLaserLengths() { m_LaserLength = m_MyAcademy.resetParameters.TryGetValue("laser_length", out m_LaserLength) ? m_LaserLength : 1.0f; } public void SetAgentScale() { float agentScale; agentScale = m_MyAcademy.resetParameters.TryGetValue("agent_scale", out agentScale) ? agentScale : 1.0f; gameObject.transform.localScale = new Vector3(agentScale, agentScale, agentScale); } public void SetResetParameters() { SetLaserLengths(); SetAgentScale(); } }
288
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class FoodCollectorArea : Area { public GameObject food; public GameObject badFood; public int numFood; public int numBadFood; public bool respawnFood; public float range; void CreateFood(int num, GameObject type) { for (int i = 0; i < num; i++) { GameObject f = Instantiate(type, new Vector3(Random.Range(-range, range), 1f, Random.Range(-range, range)) + transform.position, Quaternion.Euler(new Vector3(0f, Random.Range(0f, 360f), 90f))); f.GetComponent<FoodLogic>().respawn = respawnFood; f.GetComponent<FoodLogic>().myArea = this; } } public void ResetFoodArea(GameObject[] agents) { foreach (GameObject agent in agents) { if (agent.transform.parent == gameObject.transform) { agent.transform.position = new Vector3(Random.Range(-range, range), 2f, Random.Range(-range, range)) + transform.position; agent.transform.rotation = Quaternion.Euler(new Vector3(0f, Random.Range(0, 360))); } } CreateFood(numFood, food); CreateFood(numBadFood, badFood); } public override void ResetArea() { } }
46
ml-agents
openai
C#
using UnityEngine; public class FoodLogic : MonoBehaviour { public bool respawn; public FoodCollectorArea myArea; public void OnEaten() { if (respawn) { transform.position = new Vector3(Random.Range(-myArea.range, myArea.range), 3f, Random.Range(-myArea.range, myArea.range)) + myArea.transform.position; } else { Destroy(gameObject); } } }
22
ml-agents
openai
C#
using System.Collections.Generic; using UnityEngine; using System.Linq; using MLAgents; public class GridAcademy : Academy { [HideInInspector] public List<GameObject> actorObjs; [HideInInspector] public int[] players; public GameObject trueAgent; public int gridSize; public GameObject camObject; Camera m_Cam; Camera m_AgentCam; public GameObject agentPref; public GameObject goalPref; public GameObject pitPref; GameObject[] m_Objects; GameObject m_Plane; GameObject m_Sn; GameObject m_Ss; GameObject m_Se; GameObject m_Sw; public override void InitializeAcademy() { gridSize = (int)resetParameters["gridSize"]; m_Cam = camObject.GetComponent<Camera>(); m_Objects = new[] {agentPref, goalPref, pitPref}; m_AgentCam = GameObject.Find("agentCam").GetComponent<Camera>(); actorObjs = new List<GameObject>(); m_Plane = GameObject.Find("Plane"); m_Sn = GameObject.Find("sN"); m_Ss = GameObject.Find("sS"); m_Sw = GameObject.Find("sW"); m_Se = GameObject.Find("sE"); } public void SetEnvironment() { m_Cam.transform.position = new Vector3(-((int)resetParameters["gridSize"] - 1) / 2f, (int)resetParameters["gridSize"] * 1.25f, -((int)resetParameters["gridSize"] - 1) / 2f); m_Cam.orthographicSize = ((int)resetParameters["gridSize"] + 5f) / 2f; var playersList = new List<int>(); for (var i = 0; i < (int)resetParameters["numObstacles"]; i++) { playersList.Add(2); } for (var i = 0; i < (int)resetParameters["numGoals"]; i++) { playersList.Add(1); } players = playersList.ToArray(); m_Plane.transform.localScale = new Vector3(gridSize / 10.0f, 1f, gridSize / 10.0f); m_Plane.transform.position = new Vector3((gridSize - 1) / 2f, -0.5f, (gridSize - 1) / 2f); m_Sn.transform.localScale = new Vector3(1, 1, gridSize + 2); m_Ss.transform.localScale = new Vector3(1, 1, gridSize + 2); m_Sn.transform.position = new Vector3((gridSize - 1) / 2f, 0.0f, gridSize); m_Ss.transform.position = new Vector3((gridSize - 1) / 2f, 0.0f, -1); m_Se.transform.localScale = new Vector3(1, 1, gridSize + 2); m_Sw.transform.localScale = new Vector3(1, 1, gridSize + 2); m_Se.transform.position = new Vector3(gridSize, 0.0f, (gridSize - 1) / 2f); m_Sw.transform.position = new Vector3(-1, 0.0f, (gridSize - 1) / 2f); m_AgentCam.orthographicSize = (gridSize) / 2f; m_AgentCam.transform.position = new Vector3((gridSize - 1) / 2f, gridSize + 1f, (gridSize - 1) / 2f); } public override void AcademyReset() { foreach (var actor in actorObjs) { DestroyImmediate(actor); } SetEnvironment(); actorObjs.Clear(); var numbers = new HashSet<int>(); while (numbers.Count < players.Length + 1) { numbers.Add(Random.Range(0, gridSize * gridSize)); } var numbersA = Enumerable.ToArray(numbers); for (var i = 0; i < players.Length; i++) { var x = (numbersA[i]) / gridSize; var y = (numbersA[i]) % gridSize; var actorObj = Instantiate(m_Objects[players[i]]); actorObj.transform.position = new Vector3(x, -0.25f, y); actorObjs.Add(actorObj); } var xA = (numbersA[players.Length]) / gridSize; var yA = (numbersA[players.Length]) % gridSize; trueAgent.transform.position = new Vector3(xA, -0.25f, yA); } public override void AcademyStep() { } }
121
ml-agents
openai
C#
using System; using UnityEngine; using System.Linq; using MLAgents; public class GridAgent : Agent { [Header("Specific to GridWorld")] private GridAcademy m_Academy; public float timeBetweenDecisionsAtInference; private float m_TimeSinceDecision; [Tooltip("Because we want an observation right before making a decision, we can force " + "a camera to render before making a decision. Place the agentCam here if using " + "RenderTexture as observations.")] public Camera renderCamera; [Tooltip("Selecting will turn on action masking. Note that a model trained with action " + "masking turned on may not behave optimally when action masking is turned off.")] public bool maskActions = true; private const int k_NoAction = 0; // do nothing! private const int k_Up = 1; private const int k_Down = 2; private const int k_Left = 3; private const int k_Right = 4; public override void InitializeAgent() { m_Academy = FindObjectOfType(typeof(GridAcademy)) as GridAcademy; } public override void CollectObservations() { // There are no numeric observations to collect as this environment uses visual // observations. // Mask the necessary actions if selected by the user. if (maskActions) { SetMask(); } } /// <summary> /// Applies the mask for the agents action to disallow unnecessary actions. /// </summary> private void SetMask() { // Prevents the agent from picking an action that would make it collide with a wall var positionX = (int)transform.position.x; var positionZ = (int)transform.position.z; var maxPosition = m_Academy.gridSize - 1; if (positionX == 0) { SetActionMask(k_Left); } if (positionX == maxPosition) { SetActionMask(k_Right); } if (positionZ == 0) { SetActionMask(k_Down); } if (positionZ == maxPosition) { SetActionMask(k_Up); } } // to be implemented by the developer public override void AgentAction(float[] vectorAction, string textAction) { AddReward(-0.01f); var action = Mathf.FloorToInt(vectorAction[0]); var targetPos = transform.position; switch (action) { case k_NoAction: // do nothing break; case k_Right: targetPos = transform.position + new Vector3(1f, 0, 0f); break; case k_Left: targetPos = transform.position + new Vector3(-1f, 0, 0f); break; case k_Up: targetPos = transform.position + new Vector3(0f, 0, 1f); break; case k_Down: targetPos = transform.position + new Vector3(0f, 0, -1f); break; default: throw new ArgumentException("Invalid action value"); } var hit = Physics.OverlapBox( targetPos, new Vector3(0.3f, 0.3f, 0.3f)); if (hit.Where(col => col.gameObject.CompareTag("wall")).ToArray().Length == 0) { transform.position = targetPos; if (hit.Where(col => col.gameObject.CompareTag("goal")).ToArray().Length == 1) { Done(); SetReward(1f); } if (hit.Where(col => col.gameObject.CompareTag("pit")).ToArray().Length == 1) { Done(); SetReward(-1f); } } } // to be implemented by the developer public override void AgentReset() { m_Academy.AcademyReset(); } public void FixedUpdate() { WaitTimeInference(); } private void WaitTimeInference() { if (renderCamera != null) { renderCamera.Render(); } if (!m_Academy.GetIsInference()) { RequestDecision(); } else { if (m_TimeSinceDecision >= timeBetweenDecisionsAtInference) { m_TimeSinceDecision = 0f; RequestDecision(); } else { m_TimeSinceDecision += Time.fixedDeltaTime; } } } }
159
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class HallwayAcademy : Academy { public float agentRunSpeed; public float agentRotationSpeed; public Material goalScoredMaterial; // when a goal is scored the ground will use this material for a few seconds. public Material failMaterial; // when fail, the ground will use this material for a few seconds. public float gravityMultiplier; // use ~3 to make things less floaty public override void InitializeAcademy() { Physics.gravity *= gravityMultiplier; } public override void AcademyReset() { } }
21
ml-agents
openai
C#
using System.Collections; using UnityEngine; using MLAgents; public class HallwayAgent : Agent { public GameObject ground; public GameObject area; public GameObject symbolOGoal; public GameObject symbolXGoal; public GameObject symbolO; public GameObject symbolX; public bool useVectorObs; RayPerception m_RayPer; Rigidbody m_AgentRb; Material m_GroundMaterial; Renderer m_GroundRenderer; HallwayAcademy m_Academy; int m_Selection; public override void InitializeAgent() { base.InitializeAgent(); m_Academy = FindObjectOfType<HallwayAcademy>(); m_RayPer = GetComponent<RayPerception>(); m_AgentRb = GetComponent<Rigidbody>(); m_GroundRenderer = ground.GetComponent<Renderer>(); m_GroundMaterial = m_GroundRenderer.material; } public override void CollectObservations() { if (useVectorObs) { var rayDistance = 12f; float[] rayAngles = { 20f, 60f, 90f, 120f, 160f }; string[] detectableObjects = { "symbol_O_Goal", "symbol_X_Goal", "symbol_O", "symbol_X", "wall" }; AddVectorObs(GetStepCount() / (float)agentParameters.maxStep); AddVectorObs(m_RayPer.Perceive(rayDistance, rayAngles, detectableObjects, 0f, 0f)); } } IEnumerator GoalScoredSwapGroundMaterial(Material mat, float time) { m_GroundRenderer.material = mat; yield return new WaitForSeconds(time); m_GroundRenderer.material = m_GroundMaterial; } public void MoveAgent(float[] act) { var dirToGo = Vector3.zero; var rotateDir = Vector3.zero; if (brain.brainParameters.vectorActionSpaceType == SpaceType.Continuous) { dirToGo = transform.forward * Mathf.Clamp(act[0], -1f, 1f); rotateDir = transform.up * Mathf.Clamp(act[1], -1f, 1f); } else { var action = Mathf.FloorToInt(act[0]); switch (action) { case 1: dirToGo = transform.forward * 1f; break; case 2: dirToGo = transform.forward * -1f; break; case 3: rotateDir = transform.up * 1f; break; case 4: rotateDir = transform.up * -1f; break; } } transform.Rotate(rotateDir, Time.deltaTime * 150f); m_AgentRb.AddForce(dirToGo * m_Academy.agentRunSpeed, ForceMode.VelocityChange); } public override void AgentAction(float[] vectorAction, string textAction) { AddReward(-1f / agentParameters.maxStep); MoveAgent(vectorAction); } void OnCollisionEnter(Collision col) { if (col.gameObject.CompareTag("symbol_O_Goal") || col.gameObject.CompareTag("symbol_X_Goal")) { if ((m_Selection == 0 && col.gameObject.CompareTag("symbol_O_Goal")) || (m_Selection == 1 && col.gameObject.CompareTag("symbol_X_Goal"))) { SetReward(1f); StartCoroutine(GoalScoredSwapGroundMaterial(m_Academy.goalScoredMaterial, 0.5f)); } else { SetReward(-0.1f); StartCoroutine(GoalScoredSwapGroundMaterial(m_Academy.failMaterial, 0.5f)); } Done(); } } public override void AgentReset() { var agentOffset = -15f; var blockOffset = 0f; m_Selection = Random.Range(0, 2); if (m_Selection == 0) { symbolO.transform.position = new Vector3(0f + Random.Range(-3f, 3f), 2f, blockOffset + Random.Range(-5f, 5f)) + ground.transform.position; symbolX.transform.position = new Vector3(0f, -1000f, blockOffset + Random.Range(-5f, 5f)) + ground.transform.position; } else { symbolO.transform.position = new Vector3(0f, -1000f, blockOffset + Random.Range(-5f, 5f)) + ground.transform.position; symbolX.transform.position = new Vector3(0f, 2f, blockOffset + Random.Range(-5f, 5f)) + ground.transform.position; } transform.position = new Vector3(0f + Random.Range(-3f, 3f), 1f, agentOffset + Random.Range(-5f, 5f)) + ground.transform.position; transform.rotation = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f); m_AgentRb.velocity *= 0f; var goalPos = Random.Range(0, 2); if (goalPos == 0) { symbolOGoal.transform.position = new Vector3(7f, 0.5f, 22.29f) + area.transform.position; symbolXGoal.transform.position = new Vector3(-7f, 0.5f, 22.29f) + area.transform.position; } else { symbolXGoal.transform.position = new Vector3(7f, 0.5f, 22.29f) + area.transform.position; symbolOGoal.transform.position = new Vector3(-7f, 0.5f, 22.29f) + area.transform.position; } } }
151
ml-agents
openai
C#
//Detect when the orange block has touched the goal. //Detect when the orange block has touched an obstacle. //Put this script onto the orange block. There's nothing you need to set in the editor. //Make sure the goal is tagged with "goal" in the editor. using UnityEngine; public class GoalDetect : MonoBehaviour { /// <summary> /// The associated agent. /// This will be set by the agent script on Initialization. /// Don't need to manually set. /// </summary> [HideInInspector] public PushAgentBasic agent; // void OnCollisionEnter(Collision col) { // Touched goal. if (col.gameObject.CompareTag("goal")) { agent.ScoredAGoal(); } } }
27
ml-agents
openai
C#
//Put this script on your blue cube. using System.Collections; using UnityEngine; using MLAgents; public class PushAgentBasic : Agent { /// <summary> /// The ground. The bounds are used to spawn the elements. /// </summary> public GameObject ground; public GameObject area; /// <summary> /// The area bounds. /// </summary> [HideInInspector] public Bounds areaBounds; PushBlockAcademy m_Academy; /// <summary> /// The goal to push the block to. /// </summary> public GameObject goal; /// <summary> /// The block to be pushed to the goal. /// </summary> public GameObject block; /// <summary> /// Detects when the block touches the goal. /// </summary> [HideInInspector] public GoalDetect goalDetect; public bool useVectorObs; Rigidbody m_BlockRb; //cached on initialization Rigidbody m_AgentRb; //cached on initialization Material m_GroundMaterial; //cached on Awake() RayPerception m_RayPer; float[] m_RayAngles = { 0f, 45f, 90f, 135f, 180f, 110f, 70f }; string[] m_DetectableObjects = { "block", "goal", "wall" }; /// <summary> /// We will be changing the ground material based on success/failue /// </summary> Renderer m_GroundRenderer; void Awake() { m_Academy = FindObjectOfType<PushBlockAcademy>(); //cache the academy } public override void InitializeAgent() { base.InitializeAgent(); goalDetect = block.GetComponent<GoalDetect>(); goalDetect.agent = this; m_RayPer = GetComponent<RayPerception>(); // Cache the agent rigidbody m_AgentRb = GetComponent<Rigidbody>(); // Cache the block rigidbody m_BlockRb = block.GetComponent<Rigidbody>(); // Get the ground's bounds areaBounds = ground.GetComponent<Collider>().bounds; // Get the ground renderer so we can change the material when a goal is scored m_GroundRenderer = ground.GetComponent<Renderer>(); // Starting material m_GroundMaterial = m_GroundRenderer.material; SetResetParameters(); } public override void CollectObservations() { if (useVectorObs) { var rayDistance = 12f; AddVectorObs(m_RayPer.Perceive(rayDistance, m_RayAngles, m_DetectableObjects, 0f, 0f)); AddVectorObs(m_RayPer.Perceive(rayDistance, m_RayAngles, m_DetectableObjects, 1.5f, 0f)); } } /// <summary> /// Use the ground's bounds to pick a random spawn position. /// </summary> public Vector3 GetRandomSpawnPos() { var foundNewSpawnLocation = false; var randomSpawnPos = Vector3.zero; while (foundNewSpawnLocation == false) { var randomPosX = Random.Range(-areaBounds.extents.x * m_Academy.spawnAreaMarginMultiplier, areaBounds.extents.x * m_Academy.spawnAreaMarginMultiplier); var randomPosZ = Random.Range(-areaBounds.extents.z * m_Academy.spawnAreaMarginMultiplier, areaBounds.extents.z * m_Academy.spawnAreaMarginMultiplier); randomSpawnPos = ground.transform.position + new Vector3(randomPosX, 1f, randomPosZ); if (Physics.CheckBox(randomSpawnPos, new Vector3(2.5f, 0.01f, 2.5f)) == false) { foundNewSpawnLocation = true; } } return randomSpawnPos; } /// <summary> /// Called when the agent moves the block into the goal. /// </summary> public void ScoredAGoal() { // We use a reward of 5. AddReward(5f); // By marking an agent as done AgentReset() will be called automatically. Done(); // Swap ground material for a bit to indicate we scored. StartCoroutine(GoalScoredSwapGroundMaterial(m_Academy.goalScoredMaterial, 0.5f)); } /// <summary> /// Swap ground material, wait time seconds, then swap back to the regular material. /// </summary> IEnumerator GoalScoredSwapGroundMaterial(Material mat, float time) { m_GroundRenderer.material = mat; yield return new WaitForSeconds(time); // Wait for 2 sec m_GroundRenderer.material = m_GroundMaterial; } /// <summary> /// Moves the agent according to the selected action. /// </summary> public void MoveAgent(float[] act) { var dirToGo = Vector3.zero; var rotateDir = Vector3.zero; var action = Mathf.FloorToInt(act[0]); // Goalies and Strikers have slightly different action spaces. switch (action) { case 1: dirToGo = transform.forward * 1f; break; case 2: dirToGo = transform.forward * -1f; break; case 3: rotateDir = transform.up * 1f; break; case 4: rotateDir = transform.up * -1f; break; case 5: dirToGo = transform.right * -0.75f; break; case 6: dirToGo = transform.right * 0.75f; break; } transform.Rotate(rotateDir, Time.fixedDeltaTime * 200f); m_AgentRb.AddForce(dirToGo * m_Academy.agentRunSpeed, ForceMode.VelocityChange); } /// <summary> /// Called every step of the engine. Here the agent takes an action. /// </summary> public override void AgentAction(float[] vectorAction, string textAction) { // Move the agent using the action. MoveAgent(vectorAction); // Penalty given each step to encourage agent to finish task quickly. AddReward(-1f / agentParameters.maxStep); } /// <summary> /// Resets the block position and velocities. /// </summary> void ResetBlock() { // Get a random position for the block. block.transform.position = GetRandomSpawnPos(); // Reset block velocity back to zero. m_BlockRb.velocity = Vector3.zero; // Reset block angularVelocity back to zero. m_BlockRb.angularVelocity = Vector3.zero; } /// <summary> /// In the editor, if "Reset On Done" is checked then AgentReset() will be /// called automatically anytime we mark done = true in an agent script. /// </summary> public override void AgentReset() { var rotation = Random.Range(0, 4); var rotationAngle = rotation * 90f; area.transform.Rotate(new Vector3(0f, rotationAngle, 0f)); ResetBlock(); transform.position = GetRandomSpawnPos(); m_AgentRb.velocity = Vector3.zero; m_AgentRb.angularVelocity = Vector3.zero; SetResetParameters(); } public void SetGroundMaterialFriction() { var resetParams = m_Academy.resetParameters; var groundCollider = ground.GetComponent<Collider>(); groundCollider.material.dynamicFriction = resetParams["dynamic_friction"]; groundCollider.material.staticFriction = resetParams["static_friction"]; } public void SetBlockProperties() { var resetParams = m_Academy.resetParameters; //Set the scale of the block m_BlockRb.transform.localScale = new Vector3(resetParams["block_scale"], 0.75f, resetParams["block_scale"]); // Set the drag of the block m_BlockRb.drag = resetParams["block_drag"]; } public void SetResetParameters() { SetGroundMaterialFriction(); SetBlockProperties(); } }
249
ml-agents
openai
C#
//Every scene needs an academy script. //Create an empty gameObject and attach this script. //The brain needs to be a child of the Academy gameObject. using UnityEngine; using MLAgents; public class PushBlockAcademy : Academy { /// <summary> /// The "walking speed" of the agents in the scene. /// </summary> public float agentRunSpeed; /// <summary> /// The agent rotation speed. /// Every agent will use this setting. /// </summary> public float agentRotationSpeed; /// <summary> /// The spawn area margin multiplier. /// ex: .9 means 90% of spawn area will be used. /// .1 margin will be left (so players don't spawn off of the edge). /// The higher this value, the longer training time required. /// </summary> public float spawnAreaMarginMultiplier; /// <summary> /// When a goal is scored the ground will switch to this /// material for a few seconds. /// </summary> public Material goalScoredMaterial; /// <summary> /// When an agent fails, the ground will turn this material for a few seconds. /// </summary> public Material failMaterial; /// <summary> /// The gravity multiplier. /// Use ~3 to make things less floaty /// </summary> public float gravityMultiplier; void State() { Physics.gravity *= gravityMultiplier; } }
51
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class PyramidAcademy : Academy { public override void AcademyReset() { } public override void AcademyStep() { } }
14
ml-agents
openai
C#
using System; using System.Linq; using UnityEngine; using Random = UnityEngine.Random; using MLAgents; public class PyramidAgent : Agent { public GameObject area; private PyramidArea m_MyArea; private Rigidbody m_AgentRb; private RayPerception m_RayPer; private PyramidSwitch m_SwitchLogic; public GameObject areaSwitch; public bool useVectorObs; public override void InitializeAgent() { base.InitializeAgent(); m_AgentRb = GetComponent<Rigidbody>(); m_MyArea = area.GetComponent<PyramidArea>(); m_RayPer = GetComponent<RayPerception>(); m_SwitchLogic = areaSwitch.GetComponent<PyramidSwitch>(); } public override void CollectObservations() { if (useVectorObs) { const float rayDistance = 35f; float[] rayAngles = {20f, 90f, 160f, 45f, 135f, 70f, 110f}; float[] rayAngles1 = {25f, 95f, 165f, 50f, 140f, 75f, 115f}; float[] rayAngles2 = {15f, 85f, 155f, 40f, 130f, 65f, 105f}; string[] detectableObjects = {"block", "wall", "goal", "switchOff", "switchOn", "stone"}; AddVectorObs(m_RayPer.Perceive(rayDistance, rayAngles, detectableObjects, 0f, 0f)); AddVectorObs(m_RayPer.Perceive(rayDistance, rayAngles1, detectableObjects, 0f, 5f)); AddVectorObs(m_RayPer.Perceive(rayDistance, rayAngles2, detectableObjects, 0f, 10f)); AddVectorObs(m_SwitchLogic.GetState()); AddVectorObs(transform.InverseTransformDirection(m_AgentRb.velocity)); } } public void MoveAgent(float[] act) { var dirToGo = Vector3.zero; var rotateDir = Vector3.zero; if (brain.brainParameters.vectorActionSpaceType == SpaceType.Continuous) { dirToGo = transform.forward * Mathf.Clamp(act[0], -1f, 1f); rotateDir = transform.up * Mathf.Clamp(act[1], -1f, 1f); } else { var action = Mathf.FloorToInt(act[0]); switch (action) { case 1: dirToGo = transform.forward * 1f; break; case 2: dirToGo = transform.forward * -1f; break; case 3: rotateDir = transform.up * 1f; break; case 4: rotateDir = transform.up * -1f; break; } } transform.Rotate(rotateDir, Time.deltaTime * 200f); m_AgentRb.AddForce(dirToGo * 2f, ForceMode.VelocityChange); } public override void AgentAction(float[] vectorAction, string textAction) { AddReward(-1f / agentParameters.maxStep); MoveAgent(vectorAction); } public override void AgentReset() { var enumerable = Enumerable.Range(0, 9).OrderBy(x => Guid.NewGuid()).Take(9); var items = enumerable.ToArray(); m_MyArea.CleanPyramidArea(); m_AgentRb.velocity = Vector3.zero; m_MyArea.PlaceObject(gameObject, items[0]); transform.rotation = Quaternion.Euler(new Vector3(0f, Random.Range(0, 360))); m_SwitchLogic.ResetSwitch(items[1], items[2]); m_MyArea.CreateStonePyramid(1, items[3]); m_MyArea.CreateStonePyramid(1, items[4]); m_MyArea.CreateStonePyramid(1, items[5]); m_MyArea.CreateStonePyramid(1, items[6]); m_MyArea.CreateStonePyramid(1, items[7]); m_MyArea.CreateStonePyramid(1, items[8]); } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("goal")) { SetReward(2f); Done(); } } public override void AgentOnDone() { } }
116
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class PyramidArea : Area { public GameObject pyramid; public GameObject stonePyramid; public GameObject[] spawnAreas; public int numPyra; public float range; public void CreatePyramid(int numObjects, int spawnAreaIndex) { CreateObject(numObjects, pyramid, spawnAreaIndex); } public void CreateStonePyramid(int numObjects, int spawnAreaIndex) { CreateObject(numObjects, stonePyramid, spawnAreaIndex); } private void CreateObject(int numObjects, GameObject desiredObject, int spawnAreaIndex) { for (var i = 0; i < numObjects; i++) { var newObject = Instantiate(desiredObject, Vector3.zero, Quaternion.Euler(0f, 0f, 0f), transform); PlaceObject(newObject, spawnAreaIndex); } } public void PlaceObject(GameObject objectToPlace, int spawnAreaIndex) { var spawnTransform = spawnAreas[spawnAreaIndex].transform; var xRange = spawnTransform.localScale.x / 2.1f; var zRange = spawnTransform.localScale.z / 2.1f; objectToPlace.transform.position = new Vector3(Random.Range(-xRange, xRange), 2f, Random.Range(-zRange, zRange)) + spawnTransform.position; } public void CleanPyramidArea() { foreach (Transform child in transform) if (child.CompareTag("pyramid")) { Destroy(child.gameObject); } } public override void ResetArea() { } }
55
ml-agents
openai
C#
using UnityEngine; public class PyramidSwitch : MonoBehaviour { public Material onMaterial; public Material offMaterial; public GameObject myButton; private bool m_State; private GameObject m_Area; private PyramidArea m_AreaComponent; private int m_PyramidIndex; public bool GetState() { return m_State; } private void Start() { m_Area = gameObject.transform.parent.gameObject; m_AreaComponent = m_Area.GetComponent<PyramidArea>(); } public void ResetSwitch(int spawnAreaIndex, int pyramidSpawnIndex) { m_AreaComponent.PlaceObject(gameObject, spawnAreaIndex); m_State = false; m_PyramidIndex = pyramidSpawnIndex; tag = "switchOff"; transform.rotation = Quaternion.Euler(0f, 0f, 0f); myButton.GetComponent<Renderer>().material = offMaterial; } private void OnCollisionEnter(Collision other) { if (other.gameObject.CompareTag("agent") && m_State == false) { myButton.GetComponent<Renderer>().material = onMaterial; m_State = true; m_AreaComponent.CreatePyramid(1, m_PyramidIndex); tag = "switchOn"; } } }
45
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class ReacherAcademy : Academy { public override void AcademyReset() { Physics.gravity = new Vector3(0, -resetParameters["gravity"], 0); } public override void AcademyStep() { } }
15
ml-agents
openai
C#
using UnityEngine; using MLAgents; public class ReacherAgent : Agent { public GameObject pendulumA; public GameObject pendulumB; public GameObject hand; public GameObject goal; private ReacherAcademy m_MyAcademy; float m_GoalDegree; private Rigidbody m_RbA; private Rigidbody m_RbB; // speed of the goal zone around the arm (in radians) private float m_GoalSpeed; // radius of the goal zone private float m_GoalSize; // Magnitude of sinusoidal (cosine) deviation of the goal along the vertical dimension private float m_Deviation; // Frequency of the cosine deviation of the goal along the vertical dimension private float m_DeviationFreq; /// <summary> /// Collect the rigidbodies of the reacher in order to resue them for /// observations and actions. /// </summary> public override void InitializeAgent() { m_RbA = pendulumA.GetComponent<Rigidbody>(); m_RbB = pendulumB.GetComponent<Rigidbody>(); m_MyAcademy = GameObject.Find("Academy").GetComponent<ReacherAcademy>(); SetResetParameters(); } /// <summary> /// We collect the normalized rotations, angularal velocities, and velocities of both /// limbs of the reacher as well as the relative position of the target and hand. /// </summary> public override void CollectObservations() { AddVectorObs(pendulumA.transform.localPosition); AddVectorObs(pendulumA.transform.rotation); AddVectorObs(m_RbA.angularVelocity); AddVectorObs(m_RbA.velocity); AddVectorObs(pendulumB.transform.localPosition); AddVectorObs(pendulumB.transform.rotation); AddVectorObs(m_RbB.angularVelocity); AddVectorObs(m_RbB.velocity); AddVectorObs(goal.transform.localPosition); AddVectorObs(hand.transform.localPosition); AddVectorObs(m_GoalSpeed); } /// <summary> /// The agent's four actions correspond to torques on each of the two joints. /// </summary> public override void AgentAction(float[] vectorAction, string textAction) { m_GoalDegree += m_GoalSpeed; UpdateGoalPosition(); var torqueX = Mathf.Clamp(vectorAction[0], -1f, 1f) * 150f; var torqueZ = Mathf.Clamp(vectorAction[1], -1f, 1f) * 150f; m_RbA.AddTorque(new Vector3(torqueX, 0f, torqueZ)); torqueX = Mathf.Clamp(vectorAction[2], -1f, 1f) * 150f; torqueZ = Mathf.Clamp(vectorAction[3], -1f, 1f) * 150f; m_RbB.AddTorque(new Vector3(torqueX, 0f, torqueZ)); } /// <summary> /// Used to move the position of the target goal around the agent. /// </summary> void UpdateGoalPosition() { var radians = m_GoalDegree * Mathf.PI / 180f; var goalX = 8f * Mathf.Cos(radians); var goalY = 8f * Mathf.Sin(radians); var goalZ = m_Deviation * Mathf.Cos(m_DeviationFreq * radians); goal.transform.position = new Vector3(goalY, goalZ, goalX) + transform.position; } /// <summary> /// Resets the position and velocity of the agent and the goal. /// </summary> public override void AgentReset() { pendulumA.transform.position = new Vector3(0f, -4f, 0f) + transform.position; pendulumA.transform.rotation = Quaternion.Euler(180f, 0f, 0f); m_RbA.velocity = Vector3.zero; m_RbA.angularVelocity = Vector3.zero; pendulumB.transform.position = new Vector3(0f, -10f, 0f) + transform.position; pendulumB.transform.rotation = Quaternion.Euler(180f, 0f, 0f); m_RbB.velocity = Vector3.zero; m_RbB.angularVelocity = Vector3.zero; m_GoalDegree = Random.Range(0, 360); UpdateGoalPosition(); SetResetParameters(); goal.transform.localScale = new Vector3(m_GoalSize, m_GoalSize, m_GoalSize); } public void SetResetParameters() { m_GoalSize = m_MyAcademy.resetParameters["goal_size"]; m_GoalSpeed = Random.Range(-1f, 1f) * m_MyAcademy.resetParameters["goal_speed"]; m_Deviation = m_MyAcademy.resetParameters["deviation"]; m_DeviationFreq = m_MyAcademy.resetParameters["deviation_freq"]; } }
119
ml-agents
openai
C#
using System.Collections.Generic; using UnityEngine; using MLAgents; public class ReacherDecision : Decision { public override float[] Decide(List<float> state, List<Texture2D> observation, float reward, bool done, List<float> memory) { var action = new float[4]; for (var i = 0; i < 4; i++) { action[i] = Random.Range(-1f, 1f); } return action; } public override List<float> MakeMemory(List<float> state, List<Texture2D> observation, float reward, bool done, List<float> memory) { return new List<float>(); } }
22
ml-agents
openai
C#
using UnityEngine; public class ReacherGoal : MonoBehaviour { public GameObject agent; public GameObject hand; public GameObject goalOn; private void OnTriggerEnter(Collider other) { if (other.gameObject == hand) { goalOn.transform.localScale = new Vector3(1f, 1f, 1f); } } private void OnTriggerExit(Collider other) { if (other.gameObject == hand) { goalOn.transform.localScale = new Vector3(0f, 0f, 0f); } } private void OnTriggerStay(Collider other) { if (other.gameObject == hand) { agent.GetComponent<ReacherAgent>().AddReward(0.01f); } } }
33
ml-agents
openai
C#
//This script lets you change time scale during training. It is not a required script for this demo to function using UnityEngine; namespace MLAgents { public class AdjustTrainingTimescale : MonoBehaviour { // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Alpha1)) { Time.timeScale = 1f; } if (Input.GetKeyDown(KeyCode.Alpha2)) { Time.timeScale = 2f; } if (Input.GetKeyDown(KeyCode.Alpha3)) { Time.timeScale = 3f; } if (Input.GetKeyDown(KeyCode.Alpha4)) { Time.timeScale = 4f; } if (Input.GetKeyDown(KeyCode.Alpha5)) { Time.timeScale = 5f; } if (Input.GetKeyDown(KeyCode.Alpha6)) { Time.timeScale = 6f; } if (Input.GetKeyDown(KeyCode.Alpha7)) { Time.timeScale = 7f; } if (Input.GetKeyDown(KeyCode.Alpha8)) { Time.timeScale = 8f; } if (Input.GetKeyDown(KeyCode.Alpha9)) { Time.timeScale = 9f; } if (Input.GetKeyDown(KeyCode.Alpha0)) { Time.timeScale *= 2f; } } } }
55
ml-agents
openai
C#
using UnityEngine; namespace MLAgents { public class Area : MonoBehaviour { public virtual void ResetArea() { } } }
12
ml-agents
openai
C#
using UnityEngine; namespace MLAgents { public class CameraFollow : MonoBehaviour { public Transform target; Vector3 m_Offset; // Use this for initialization void Start() { m_Offset = gameObject.transform.position - target.position; } // Update is called once per frame void Update() { // gameObject.transform.position = target.position + offset; var newPosition = new Vector3(target.position.x + m_Offset.x, transform.position.y, target.position.z + m_Offset.z); gameObject.transform.position = newPosition; } } }
26
ml-agents
openai
C#
using UnityEngine; namespace MLAgents { public class FlyCamera : MonoBehaviour { /* wasd : basic movement shift : Makes camera accelerate space : Moves camera on X and Z axis only. So camera doesn't gain any height*/ public float mainSpeed = 100.0f; // regular speed public float shiftAdd = 250.0f; // multiplied by how long shift is held. Basically running public float maxShift = 1000.0f; // Maximum speed when holdin gshift public float camSens = 0.25f; // How sensitive it with mouse public bool rotateOnlyIfMousedown = true; public bool movementStaysFlat = true; private Vector3 m_LastMouse = new Vector3(255, 255, 255); // kind of in the middle of the screen, rather than at the top (play) private float m_TotalRun = 1.0f; void Awake() { Debug.Log("FlyCamera Awake() - RESETTING CAMERA POSITION"); // nop? // nop: // transform.position.Set(0,8,-32); // transform.rotation.Set(15,0,0,1); transform.position = new Vector3(0, 8, -32); transform.rotation = Quaternion.Euler(25, 0, 0); } void Update() { if (Input.GetMouseButtonDown(1)) { m_LastMouse = Input.mousePosition; // $CTK reset when we begin } if (!rotateOnlyIfMousedown || (rotateOnlyIfMousedown && Input.GetMouseButton(1))) { m_LastMouse = Input.mousePosition - m_LastMouse; m_LastMouse = new Vector3(-m_LastMouse.y * camSens, m_LastMouse.x * camSens, 0); m_LastMouse = new Vector3(transform.eulerAngles.x + m_LastMouse.x, transform.eulerAngles.y + m_LastMouse.y, 0); transform.eulerAngles = m_LastMouse; m_LastMouse = Input.mousePosition; // Mouse camera angle done. } // Keyboard commands var p = GetBaseInput(); if (Input.GetKey(KeyCode.LeftShift)) { m_TotalRun += Time.deltaTime; p = shiftAdd * m_TotalRun * p; p.x = Mathf.Clamp(p.x, -maxShift, maxShift); p.y = Mathf.Clamp(p.y, -maxShift, maxShift); p.z = Mathf.Clamp(p.z, -maxShift, maxShift); } else { m_TotalRun = Mathf.Clamp(m_TotalRun * 0.5f, 1f, 1000f); p = p * mainSpeed; } p = p * Time.deltaTime; var newPosition = transform.position; if (Input.GetKey(KeyCode.Space) || (movementStaysFlat && !(rotateOnlyIfMousedown && Input.GetMouseButton(1)))) { // If player wants to move on X and Z axis only transform.Translate(p); newPosition.x = transform.position.x; newPosition.z = transform.position.z; transform.position = newPosition; } else { transform.Translate(p); } } private Vector3 GetBaseInput() { // returns the basic values, if it's 0 than it's not active. var pVelocity = new Vector3(); if (Input.GetKey(KeyCode.W)) { pVelocity += new Vector3(0, 0, 1); } if (Input.GetKey(KeyCode.S)) { pVelocity += new Vector3(0, 0, -1); } if (Input.GetKey(KeyCode.A)) { pVelocity += new Vector3(-1, 0, 0); } if (Input.GetKey(KeyCode.D)) { pVelocity += new Vector3(1, 0, 0); } return pVelocity; } } }
117