Example #1
5
 /// <summary>
 /// Создает на основе типа фильтр
 /// </summary>
 /// <param name="lib"></param>
 /// <param name="type"></param>
 public Filter(string lib, Type type)
 {
     libname = lib;
     if (type.BaseType == typeof(AbstractFilter))
     {
         Exception fullex = new Exception("");
         ConstructorInfo ci = type.GetConstructor(System.Type.EmptyTypes);
         filter = ci.Invoke(null);
         PropertyInfo everyprop;
         everyprop = type.GetProperty("Name");
         name = (string)everyprop.GetValue(filter, null);
         everyprop = type.GetProperty("Author");
         author = (string)everyprop.GetValue(filter, null);
         everyprop = type.GetProperty("Ver");
         version = (Version)everyprop.GetValue(filter, null);
         help = type.GetMethod("Help");
         MethodInfo[] methods = type.GetMethods();
         filtrations = new List<Filtration>();
         foreach (MethodInfo mi in methods)
             if (mi.Name == "Filter")
             {
                 try
                 {
                     filtrations.Add(new Filtration(mi));
                 }
                 catch (TypeLoadException)
                 {
                     //Не добавляем фильтрацию.
                 }
             }
         if (filtrations == null) throw new TypeIncorrectException("Класс " + name + " не содержит ни одной фильтрации");
     }
     else
         throw new TypeLoadException("Класс " + type.Name + " не наследует AbstractFilter");
 }
Example #2
1
        public void UpdateFiles()
        {
            try
            {
                WriteLine("Local version: " + Start.m_Version);

                WebClient wc = new WebClient();
                string versionstr;
                using(System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead(baseurl + "version.txt")))
                {
                    versionstr = sr.ReadLine();
                }
                Version remoteversion = new Version(versionstr);
                WriteLine("Remote version: " + remoteversion);

                if(Start.m_Version < remoteversion)
                {
                    foreach(string str in m_Files)
                    {
                        WriteLine("Updating: " + str);
                        wc.DownloadFile(baseurl + str, str);
                    }
                }
                wc.Dispose();
                WriteLine("Update complete");
            }
            catch(Exception e)
            {
                WriteLine("Update failed:");
                WriteLine(e);
            }
            this.Button_Ok.Enabled = true;
        }
Example #3
1
        public UpdateBarModel(Version version, string downloadUri)
        {
            if (version == null || downloadUri == null)
            {
                UpdateAvailable = false;
                return;
            }

            Version = version;
            var currentVersion = typeof(CertInspector).Assembly.GetName().Version;
            var closed = Fiddler.FiddlerApplication.Prefs.GetPref(PreferenceNames.HIDE_UPDATED_PREF, false);
            UpdateAvailable = version > currentVersion && !closed;
            Fiddler.FiddlerApplication.Log.LogString($"FiddlerCert Inspector: Current version is {currentVersion}, latest version is {version}.");
            _downloadCommand = new RelayCommand(_ =>
            {
                var uri = new Uri(downloadUri);
                if (uri?.Scheme == Uri.UriSchemeHttps)
                {
                    Process.Start(uri.AbsoluteUri);
                }
                else
                {
                    Fiddler.FiddlerApplication.Log.LogString("Refusing to open non-HTTPS page.");
                }
            });
            _closeCommand = new RelayCommand(_ =>
            {
                Fiddler.FiddlerApplication.Prefs.SetPref(PreferenceNames.HIDE_UPDATED_PREF, true);
                UpdateAvailable = false;
            });
        }
Example #4
0
        public VersionFeature(string name, Version version)
            : base(name)
        {
            Verify.Argument.IsNotNull(version, "version");

            _version = version;
        }
 public VersionClass(string version1, string version2)
 {
     StringProperty1 = "StringProperty1";
     Version1 = new Version(version1);
     Version2 = new Version(version2);
     StringProperty2 = "StringProperty2";
 }
        public override void Can_Upgrade_From_470_To_600()
        {
            var configuredVersion = new Version("4.11.0");
            var targetVersion = new Version("6.0.0");
            var provider = GetDatabaseProvider();
            var db = GetConfiguredDatabase();

            var fix = new PublishAfterUpgradeToVersionSixth();

            //Setup the MigrationRunner
            var migrationRunner = new MigrationRunner(configuredVersion, targetVersion, GlobalSettings.UmbracoMigrationName);
            bool upgraded = migrationRunner.Execute(db, provider, true);

            Assert.That(upgraded, Is.True);

            bool hasTabTable = db.TableExist("cmsTab");
            bool hasPropertyTypeGroupTable = db.TableExist("cmsPropertyTypeGroup");
            bool hasAppTreeTable = db.TableExist("umbracoAppTree");

            fix.Unsubscribe();

            Assert.That(hasTabTable, Is.False);
            Assert.That(hasPropertyTypeGroupTable, Is.True);
            Assert.That(hasAppTreeTable, Is.False);
        }
 internal static void WriteSkipLinkStart(HtmlTextWriter writer, Version renderingCompatibility, bool designMode, string skipLinkText, string spacerImageUrl, string clientID) {
     if (skipLinkText.Length != 0 && !designMode) {
         if (renderingCompatibility >= VersionUtil.Framework45) {
             writer.AddAttribute(HtmlTextWriterAttribute.Href, '#' + clientID + SkipLinkContentMark);
             writer.AddStyleAttribute(HtmlTextWriterStyle.Position, "absolute");
             writer.AddStyleAttribute(HtmlTextWriterStyle.Left, "-10000px");
             writer.AddStyleAttribute(HtmlTextWriterStyle.Top, "auto");
             writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "1px");
             writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "1px");
             writer.AddStyleAttribute(HtmlTextWriterStyle.Overflow, "hidden");
             writer.RenderBeginTag(HtmlTextWriterTag.A);
             writer.Write(skipLinkText);
             writer.RenderEndTag();
         }
         else {
             writer.AddAttribute(HtmlTextWriterAttribute.Href, '#' + clientID + SkipLinkContentMark);
             writer.RenderBeginTag(HtmlTextWriterTag.A);
             writer.AddAttribute(HtmlTextWriterAttribute.Alt, skipLinkText);
             writer.AddAttribute(HtmlTextWriterAttribute.Src, spacerImageUrl);
             writer.AddStyleAttribute(HtmlTextWriterStyle.BorderWidth, "0px");
             writer.AddAttribute(HtmlTextWriterAttribute.Width, "0");
             writer.AddAttribute(HtmlTextWriterAttribute.Height, "0");
             writer.RenderBeginTag(HtmlTextWriterTag.Img);
             writer.RenderEndTag();
             writer.RenderEndTag();
         }
     }
 }
 internal PersistenceVersion(bool enableEncryption, bool enableCompression)
 {
     StoreVersion = new Version(1, 0);
     CLRVersion = Environment.Version;
     EnableEncryption = enableEncryption;
     EnableCompression = enableCompression;
 }
        public SchedulerMigrator_1()
        {
            Version = new Version(0, 0, 1);
            MigrationName = "Scheduler";

            schema = new List<Rec<string, ColumnDefinition[]>>();

            AddSchema("scheduler", ColDefs(ColDef("id", ColumnTypes.String36, true),
                                                ColDef("fire_function", ColumnTypes.String128),
                                                ColDef("fire_params", ColumnTypes.String1024),
                                                ColDef("run_once", ColumnTypes.TinyInt1),
                                                ColDef("run_every", ColumnTypes.Integer30),
                                                ColDef("runs_next", ColumnTypes.Integer30, true),
                                                ColDef("keep_history", ColumnTypes.TinyInt1),
                                                ColDef("require_reciept", ColumnTypes.TinyInt1),
                                                ColDef("last_history_id", ColumnTypes.String36),
                                                ColDef("create_time", ColumnTypes.Integer30),
                                                ColDef("enabled", ColumnTypes.TinyInt1, true)
                                            ));

            AddSchema("scheduler_history", ColDefs(ColDef("id", ColumnTypes.String36, true),
                                                ColDef("scheduler_id", ColumnTypes.String36, true),
                                                ColDef("ran_time", ColumnTypes.Integer30),
                                                ColDef("run_time", ColumnTypes.Integer30),
                                                ColDef("reciept", ColumnTypes.String1024),
                                                ColDef("is_complete", ColumnTypes.TinyInt1),
                                                ColDef("complete_time", ColumnTypes.Integer30)
                                            ));
        }
        public UserAccountsMigrator_1()
        {
            Version = new Version(0, 0, 1);
            MigrationName = "UserAccounts";

            schema = new List<SchemaDefinition>();

            //Remove the old name
            this.RemoveSchema("UserAccounts");
            //Add the `Name` column
            AddSchema("useraccounts", ColDefs(
                ColDef("PrincipalID", ColumnTypes.Char36),
                ColDef("ScopeID", ColumnTypes.Char36),
                ColDef("FirstName", ColumnTypes.String64),
                ColDef("LastName", ColumnTypes.String64),
                ColDef("Email", ColumnTypes.String64),
                ColDef("ServiceURLs", ColumnTypes.Text),
                ColDef("Created", ColumnTypes.Integer11),
                ColDef("UserLevel", ColumnTypes.Integer11),
                ColDef("UserFlags", ColumnTypes.Integer11),
                ColDef("UserTitle", ColumnTypes.String64),
                ColDef("Name", ColumnTypes.String255)
                                          ), IndexDefs(
                                              IndexDef(new string[1] {"PrincipalID"}, IndexType.Primary)
                                                 ));
        }
 public HSPI()
 {
     int Major = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductMajorPart;
     int Minor = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductMinorPart;
     int Build = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductBuildPart;
     PLUGIN_VERSION = new Version(Major, Minor, Build);
 }
        /// <remarks>Internal for testing.</remarks>
        internal static void RetargetWithMetadataConverter(XDocument xdoc, Version targetSchemaVersion, MetadataConverterDriver converter)
        {
            Debug.Assert(xdoc != null, "xdoc != null");
            Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid target schema version");

            var inputXml = new XmlDocument { PreserveWhitespace = true };
            using (var reader = xdoc.CreateReader())
            {
                inputXml.Load(reader);
            }

            var outputXml = converter.Convert(inputXml, targetSchemaVersion);
            if (outputXml != null)
            {
                // Dev10 Bug 550594: There is a bug in XmlEditor that prevents from deleting the root node
                // unless the root node has previous sibling (like a comment or Xml declaration).
                if (xdoc.Root.PreviousNode == null)
                {
                    xdoc.Root.AddBeforeSelf(new XComment(""));
                }

                // update xml document with new root element
                xdoc.Root.Remove();
                using (var reader = new XmlNodeReader(outputXml))
                {
                    var newDoc = XDocument.Load(reader);
                    xdoc.Add(newDoc.Root);
                }

                // Do not reload artifact here
                // Until the transaction is commited, the XLinq representation of the parsed xml tree hasn't been generated yet.
            }
        }
    Test GetAssemblyTest(IAssemblyInfo assembly, Test parentTest, Version frameworkVersion, bool populateRecursively)
    {
      MachineAssemblyTest assemblyTest;
      if (!assemblyTests.TryGetValue(assembly, out assemblyTest))
      {
        assemblyTest = new MachineAssemblyTest(assembly.Name, assembly, frameworkVersion);
        assemblyTest.Kind = TestKinds.Assembly;

        ModelUtils.PopulateMetadataFromAssembly(assembly, assemblyTest.Metadata);

        string frameworkName = String.Format("Machine Specifications v{0}", frameworkVersion);
        assemblyTest.Metadata.SetValue(MetadataKeys.Framework, frameworkName);
        assemblyTest.Metadata.SetValue(MetadataKeys.File, assembly.Path);
        assemblyTest.Kind = TestKinds.Assembly;

        parentTest.AddChild(assemblyTest);
        assemblyTests.Add(assembly, assemblyTest);
      }

      if (populateRecursively)
      {
        AssemblyExplorer explorer = new AssemblyExplorer();
        Assembly resolvedAssembly = assembly.Resolve(false);

        assemblyTest.AssemblyContexts = explorer.FindAssemblyContextsIn( resolvedAssembly).ToList();
        assemblyTest.GlobalCleanup = explorer.FindAssemblyWideContextCleanupsIn(resolvedAssembly).ToList();
        assemblyTest.SpecificationSupplements = explorer.FindSpecificationSupplementsIn(resolvedAssembly).ToList();
        
        explorer.FindContextsIn(resolvedAssembly)
          .Select( context => GetContextTest( context))
          .Each( test => assemblyTest.AddChild( test));
      }

      return assemblyTest;
    }
 public override Version GetVersionPresent(object feature)
 {
     Version version = null;
     if (feature == LayeredWindows)
     {
         if ((Environment.OSVersion.Platform == PlatformID.Win32NT) && (Environment.OSVersion.Version.CompareTo(new Version(5, 0, 0, 0)) >= 0))
         {
             version = new Version(0, 0, 0, 0);
         }
         return version;
     }
     if (feature == Themes)
     {
         if (!themeSupportTested)
         {
             try
             {
                 SafeNativeMethods.IsAppThemed();
                 themeSupport = true;
             }
             catch
             {
                 themeSupport = false;
             }
             themeSupportTested = true;
         }
         if (themeSupport)
         {
             version = new Version(0, 0, 0, 0);
         }
     }
     return version;
 }
        protected override SymbolAndNodeAnalyzer GetAnalyzer(CompilationStartAnalysisContext context, CompilationSecurityTypes types, Version targetFrameworkVersion)
        {
            SymbolAndNodeAnalyzer analyzer = new SymbolAndNodeAnalyzer(types, CSharpSyntaxNodeHelper.Default, targetFrameworkVersion);
            context.RegisterSyntaxNodeAction(analyzer.AnalyzeNode, SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration);

            return analyzer;
        }
Example #16
0
        public void LoadExisting(Stream existing, byte[] masterKey)
        {
            if (existing == null) throw new ArgumentNullException("existing");
            if (masterKey == null) throw new ArgumentNullException("masterKey");

            var reader = new BinaryReader(existing);
            if (!FileFormat.Sign(reader))
            {
                throw new FormatException(
                    "Invalid format detected");
            }

            _version = FileFormat
                .ReadVersion(reader);

            _masterKey = masterKey;
            _headers = FileFormat
                .ReadHeaders(existing);

            _xmlWriter = new XmlWriter();

            using (var decrypt = FileFormat.Decrypt(
                existing, _headers, masterKey))
            {
                _xmlWriter.Load(decrypt);

                var crypto = CryptoSerializer
                    .Create(_headers);
                _xmlWriter.Decrypt(crypto);
            }
        }
 public void TestBuildInfo()
 {
     var versionZero = new Version(0, 0, 0, 0);
     var buildInfo = _server.BuildInfo;
     Assert.IsTrue(buildInfo.Bits == 32 || buildInfo.Bits == 64);
     Assert.AreNotEqual(versionZero, buildInfo.Version);
 }
 /// <summary>
 /// Reads the JSON representation of the object.
 /// </summary>
 /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
 /// <param name="objectType">Type of the object.</param>
 /// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
 /// <param name="serializer">The calling serializer.</param>
 /// <returns>The object value.</returns>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.Null)
     {
         return null;
     }
     else
     {
         if (reader.TokenType == JsonToken.String)
         {
             try
             {
                 Version v = new Version((string)reader.Value);
                 return v;
             }
             catch (Exception ex)
             {
                 throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex);
             }
         }
         else
         {
             throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
         }
     }
 }
        public UserAccountsMigrator_0()
        {
            Version = new Version(0, 0, 0);
            MigrationName = "UserAccounts";

            schema = new List<SchemaDefinition>();

            //
            // Change summery:
            //
            //   Force 'UserAccounts' to 'useraccounts'
            //     Note: we do multiple renames here as it doesn't
            //     always like just switching to lowercase (as in SQLite)
            //
            this.RenameSchema("UserAccounts", "useraccountslower");
            this.RenameSchema("useraccountslower", "useraccounts");

            //Remove the old name
            this.RemoveSchema("UserAccounts");
            //Add the new lowercase one
            AddSchema("useraccounts", ColDefs(
                ColDef("PrincipalID", ColumnTypes.Char36),
                ColDef("ScopeID", ColumnTypes.Char36),
                ColDef("FirstName", ColumnTypes.String64),
                ColDef("LastName", ColumnTypes.String64),
                ColDef("Email", ColumnTypes.String64),
                ColDef("ServiceURLs", ColumnTypes.Text),
                ColDef("Created", ColumnTypes.Integer11),
                ColDef("UserLevel", ColumnTypes.Integer11),
                ColDef("UserFlags", ColumnTypes.Integer11),
                ColDef("UserTitle", ColumnTypes.String64)
                                          ), IndexDefs(
                                              IndexDef(new string[1] {"PrincipalID"}, IndexType.Primary)
                                                 ));
        }
        public void IsBeforeDoesNotThrowNullReferenceExceptionWithNullAsInput()
        {
            Version v1 = new Version(1, 0);
            Version v2 = null;

            Check.That(v2).IsBefore(v1);
        }
        public static void CheckVersion()
        {
            try
            {
                var match =
                    new Regex(
                        @"\[assembly\: AssemblyVersion\(""(\d{1,})\.(\d{1,})\.(\d{1,})\.(\d{1,})""\)\]")
                        .Match(DownloadServerVersion());

                if (!match.Success) return;
                var gitVersion =
                    new Version(
                        string.Format(
                            "{0}.{1}.{2}.{3}",
                            match.Groups[1],
                            match.Groups[2],
                            match.Groups[3],
                            match.Groups[4]));
                if (gitVersion <= Assembly.GetExecutingAssembly().GetName().Version)
                {
                    ColoredConsoleWrite(ConsoleColor.Green, "Awesome! You have already got the newest version! " + Assembly.GetExecutingAssembly().GetName().Version);
                    return;
                }

                ColoredConsoleWrite(ConsoleColor.Red, "There is a new Version available: " + gitVersion);
                ColoredConsoleWrite(ConsoleColor.Red, "You can find it at https://github.com/DetectiveSquirrel/Pokemon-Go-Rocket-API");
            }
            catch (Exception)
            {
                ColoredConsoleWrite(ConsoleColor.Red, "Unable to check for updates now...");
            }
        }
        public void IsBeforeThrowsExceptionWhenFailing()
        {
            Version v1 = new Version(1, 0);
            Version v2 = new Version(2, 0);

            Check.That(v2).IsBefore(v1);
        }
Example #23
0
 protected Xsd(Version version)
     : this()
 {
     this.header = ValidHeaders[0];
     this.version = (int)version;
     this.setupLanguages();
 }
Example #24
0
        public AuthMigrator_3()
        {
            Version = new Version(0, 0, 3);
            MigrationName = "Auth";

            schema = new List<SchemaDefinition>();

            //
            // Change summery:
            //
            //   Make the password hash much longer to accommodate other types of passwords)
            //

            AddSchema("auth", ColDefs(
                ColDef("UUID", ColumnTypes.Char36),
                ColDef("passwordHash", ColumnTypes.String1024),
                ColDef("passwordSalt", ColumnTypes.String1024),
                ColDef("accountType", ColumnTypes.Char32)
            ), IndexDefs(
                IndexDef(new string[2]{ "UUID", "accountType" }, IndexType.Primary)
            ));

            AddSchema("tokens", ColDefs(
                ColDef("UUID", ColumnTypes.Char36),
                ColDef("token", ColumnTypes.String255),
                ColDef("validity", ColumnTypes.Date)
            ), IndexDefs(
                IndexDef(new string[2]{ "UUID", "token" }, IndexType.Primary)
            ));
        }
Example #25
0
		public void WriteSolutionVersionProperties(SolutionFormatVersion version, Version currVSVersion, Version minVSVersion)
		{
			if (version >= SolutionFormatVersion.VS2012) {
				writer.WriteLine("VisualStudioVersion = {0}", currVSVersion);
				writer.WriteLine("MinimumVisualStudioVersion = {0}", minVSVersion);
			}
		}
        public void CheckVersion()
        {
            try
            {
                var match =
                    new Regex(
                        @"\[assembly\: AssemblyVersion\(""(\d{1,})\.(\d{1,})\.(\d{1,})\.(\d{1,})""\)\]")
                        .Match(DownloadServerVersion());

                if (!match.Success) return;
                var gitVersion =
                    new Version(
                        string.Format(
                            "{0}.{1}.{2}.{3}",
                            match.Groups[1],
                            match.Groups[2],
                            match.Groups[3],
                            match.Groups[4]));
                // makes sense to display your version and say what the current one is on github
                ColoredConsoleWrite(Color.Green, "Your version is " + Assembly.GetExecutingAssembly().GetName().Version);
                ColoredConsoleWrite(Color.Green, "Github version is " + gitVersion);
                ColoredConsoleWrite(Color.Green, "You can find it at www.GitHub.com/DetectiveSquirrel/Pokemon-Go-Rocket-API");
            }
            catch (Exception)
            {
                ColoredConsoleWrite(Color.Red, "Unable to check for updates now...");
            }
        }
Example #27
0
 private static Version NormalizeVersionValue(Version version)
 {
     return new Version(version.Major,
                        version.Minor,
                        Math.Max(version.Build, 0),
                        Math.Max(version.Revision, 0));
 }
        public void IsBeforeDoesNotThrowNullReferenceExceptionWithNullAsAfterValue()
        {
            Version v1 = null;
            Version v2 = new Version(2, 0);

            Check.That(v2).IsBefore(v1);
        }
		public static void OnAppStart(Version version, LoginType loginType, bool isNew)
		{
			if(!Config.Instance.GoogleAnalytics)
				return;
			Google.TrackPageView($"/app/v{version.ToVersionString()}/{loginType.ToString().ToLower()}{(isNew ? "/new" : "")}", "");
			WritePoint(new InfluxPointBuilder("hdt_app_start").Tag("version", version.ToVersionString()).Tag("login_type", loginType).Tag("new", isNew).Build());
		}
        public bool IsSupported(Version cssVersion, ICssCompletionListEntry entry)
        {
            if (WESettings.GetBoolean(WESettings.Keys.ShowUnsupported))
                return entry.IsSupported(cssVersion);

            return entry.GetAttribute("browsers") != "none" || entry.DisplayText.Contains("gradient");
        }
 /// <summary>
 /// Looks up the commit that matches a specified version number.
 /// </summary>
 /// <param name="repo">The repository to search for a matching commit.</param>
 /// <param name="version">The version previously obtained from <see cref="GetIdAsVersion(Commit, string, int?)"/>.</param>
 /// <param name="repoRelativeProjectDirectory">
 /// The repo-relative project directory from which <paramref name="version"/> was originally calculated.
 /// </param>
 /// <returns>The matching commit, or <c>null</c> if no match is found.</returns>
 /// <exception cref="InvalidOperationException">
 /// Thrown in the very rare situation that more than one matching commit is found.
 /// </exception>
 public static Commit GetCommitFromVersion(this Repository repo, Version version, string repoRelativeProjectDirectory = null)
 {
     // Note we'll accept no match, or one match. But we throw if there is more than one match.
     return(GetCommitsFromVersion(repo, version, repoRelativeProjectDirectory).SingleOrDefault());
 }
    public override void OnInspectorGUI()
    {
        serializedObject.Update();


        //check if need to upgrade.
        System.Version myVer = new System.Version(Script.MyVersion);
        if (myVer <= new System.Version("4.4.0"))
        {
            DoPatch440(Script);
            EditorUtility.SetDirty(target);
        }

        XEditor.BeginCommonArea("xffect main config", Script.gameObject.name, this, true);

        EditorGUILayout.Space();


        if (EditorUtility.IsPersistent(target))
        {
            if (GUILayout.Button("Put To Scene"))
            {
                GameObject obj = PrefabUtility.InstantiatePrefab(Selection.activeObject as GameObject) as GameObject;
                Selection.activeGameObject = obj;
                if (obj != null)
                {
                    XffectComponent xobj = obj.GetComponent <XffectComponent>();
                    if (xobj != null)
                    {
                        xobj.EditView = true;
                        xobj.EnableEditView();
                    }
                }
            }
        }


        XEditor.DrawToggle("update in editor?", "", EditView);

        //EditView.boolValue = EditorGUILayout.Toggle("update in editor:", EditView.boolValue,GUILayout.Height(40f));


        //if (EditView.boolValue == true) {
        //if (!XffectComponent.IsActive(Script.gameObject)) {
        //EditView.boolValue = false;
        //Debug.Log ("you need to activate the xffect object: " + Script.gameObject.name + " before updating it in editor.");
        //}
        //}

        if (EditView.boolValue)
        {
            Script.EnableEditView();
        }
        else
        {
            Paused.boolValue = false;
            Script.DisableEditView();
        }

        if (EditView.boolValue)
        {
            PlaybackTime.floatValue = EditorGUILayout.FloatField("Playback time: ", PlaybackTime.floatValue);

            if (PlaybackTime.floatValue < 0f)
            {
                PlaybackTime.floatValue = 0f;
            }

            string disp = "Pause";
            if (Paused.boolValue)
            {
                disp = "Play";
            }
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button(disp))
            {
                Paused.boolValue = !Paused.boolValue;
            }

            if (GUILayout.Button("Reset"))
            {
                Paused.boolValue = false;
                Script.ResetEditScene();
            }
            EditorGUILayout.EndHorizontal();
        }

        XEditor.DrawSeparator();

        XEditor.DrawFloat("life(-1 means infinite):", "", LifeTime);
        XEditor.DrawToggle("ignore time scale?", "", IgnoreTimeScale);

        XEditor.DrawToggle("auto destroy?", "check on this option if you want this obj to be destroyed when finished, note this option only works in play mode.", AutoDestroy);

        XEditor.DrawToggle("merge same mesh?", "check on this option to merge the meshes with same material, can reduce drawcalls.", MergeSameMaterialMesh);

        XEditor.DrawToggle("update when offscreen?", "", UpdateWhenOffScreen);

        if (XEditor.DrawToggle("use with 2d sprite?", "", UseWith2DSprite))
        {
            XEditor.DrawText("sorting layer name:", "", SortingLayerName);
            XEditor.DrawInt("sorting order:", "", SortingOrder);
        }

        EditorGUILayout.Space();



        XEditor.DrawInt("Max Fps:", "", MaxFps);

        XEditor.DrawFloat("scale:", "change this Xffect's scale", Scale);



        if (!Mathf.Approximately(1f, Scale.floatValue))
        {
            XEditor.DrawInfo("note it's not recommended to use this function to change xffect's scale. if you encounter strange behavious, please change it back to 1.");
        }

        if (GUILayout.Button("Add Layer"))
        {
            GameObject  layer = new GameObject(LayerName);
            EffectLayer efl   = (EffectLayer)layer.AddComponent("EffectLayer");
            layer.transform.parent      = Selection.activeTransform;
            efl.transform.localPosition = Vector3.zero;
            //default to effect layer object.
            efl.ClientTransform  = efl.transform;
            efl.GravityObject    = efl.transform;
            efl.BombObject       = efl.transform;
            efl.TurbulenceObject = efl.transform;
            efl.AirObject        = efl.transform;
            efl.VortexObj        = efl.transform;
            //efl.DirCenter = efl.transform;
            efl.Material = AssetDatabase.LoadAssetAtPath(XEditorTool.GetXffectPath() + DefaultMatPath, typeof(Material)) as Material;

            efl.gameObject.layer = Script.gameObject.layer;

            efl.LineStartObj = efl.transform;

            Selection.activeGameObject = layer;
        }


        if (GUILayout.Button("Add Event"))
        {
            GameObject        obj    = new GameObject("_Event");
            XftEventComponent xevent = (XftEventComponent)obj.AddComponent("XftEventComponent");
            xevent.transform.parent        = Selection.activeTransform;
            xevent.transform.localPosition = Vector3.zero;
            xevent.RadialBlurShader        = Shader.Find("Xffect/PP/radial_blur");
            xevent.GlowCompositeShader     = Shader.Find("Xffect/PP/glow_compose");
            xevent.GlowDownSampleShader    = Shader.Find("Xffect/PP/glow_downsample");
            xevent.GlowBlurShader          = Shader.Find("Xffect/PP/glow_conetap");
            xevent.RadialBlurObj           = xevent.transform;
            xevent.ColorInverseShader      = Shader.Find("Xffect/PP/color_inverse");

            xevent.GlowPerObjBlendShader       = Shader.Find("Hidden/PP/Xffect/glow_per_obj/blend");
            xevent.GlowPerObjReplacementShader = Shader.Find("Hidden/PP/Xffect/glow_per_obj/replacement");
            xevent.gameObject.layer            = Script.gameObject.layer;

            Selection.activeGameObject = obj;
        }
        XEditor.EndXArea();

        DrawInfos();
        serializedObject.ApplyModifiedProperties();
    }
    public static void IncrementBuild(bool incBuild, bool incMinor, bool incMajor, bool incVersionCode)
    {
        var settingsPath = Path.GetDirectoryName(Application.dataPath);

        settingsPath = Path.Combine(settingsPath, "ProjectSettings");
        settingsPath = Path.Combine(settingsPath, "ProjectSettings.asset");

        if (!File.Exists(settingsPath))
        {
            Debug.LogError("Couldn't find project settings file.");
            return;
        }

        var lines = File.ReadAllLines(settingsPath);

        if (!lines[0].StartsWith("%YAML"))
        {
            Debug.LogError("Project settings file needs to be serialized as a text asset. (Check 'Project Settings->Editor')");
            return;
        }

        string pattern  = "bundleVersion";
        string pattern2 = "AndroidBundleVersionCode";
        bool   success  = false;

        System.Version version     = null;
        int            versionCode = PlayerSettings.Android.bundleVersionCode;



        for (int i = 0; i < lines.Length; i++)
        {
            var line = lines[i];

            if (line.Contains(pattern))
            {
                var match = line.Split(':');

                version = new System.Version(match[1].Split('#')[0]);

                var major = version.Major < 0 ? 0 : version.Major;
                var minor = version.Minor < 0 ? 0 : version.Minor;
                var build = version.Build < 0 ? 0 : version.Build;

                if (incMajor)
                {
                    major++;
                    minor = 0;
                    build = 0;
                }
                else if (incMinor)
                {
                    minor++;
                    build = 0;
                }
                else if (incBuild)
                {
                    build++;
                }

                version = new System.Version(major, minor, build);

                line = match[0] + ": " + version;

                lines[i] = line;
                success  = true;
            }
            else if (line.Contains(pattern2))
            {
                var match = line.Split(':');
                if (incVersionCode)
                {
                    versionCode++;
                    line     = match[0] + ": " + versionCode;
                    lines[i] = line;
                }
            }
        }

        PlayerSettings.bundleVersion             = version.ToString();
        PlayerSettings.Android.bundleVersionCode = versionCode;

        if (!success)
        {
            Debug.Log("Couldn't find bundle version in ProjectSettings.asset");
            return;
        }

        File.WriteAllLines(settingsPath, lines);

        Debug.Log("Build version: " + version + " Version code: " + versionCode);
    }
Example #34
0
    public void ShowMessage(string gameName, string currentVersion, System.Action <bool, string> callback)
    {
        restApi.ResourceAt(SConstants.CheckVersionUrl + gameName)
        .Get(response => {
            if (response != null && !response.HasError)
            {
                if (response.Resource != null)
                {
//						Hashtable data = (Hashtable)response.Resource["data"];

                    SMessageResult result = new SMessageResult(response.Resource);
                    if (result.ShouldShow)
                    {
                        switch (result.Condition)
                        {
                        case SMessageCondition.CheckVersion:
                            var ver1 = new System.Version(currentVersion);
                            var ver2 = new System.Version(result.Version);

                            var compareResult = ver2.CompareTo(ver1);


                            if (compareResult > 0)
                            {
                                MobileNativeDialog dialog = new MobileNativeDialog(result.Title, result.MessageDialog, "OK", "Cancel");
                                dialog.OnComplete        += OnDialogClose;

                                                                        #if UNITY_IOS
                                this.ActionURL = result.iOSAction;
                                                                        #elif UNITY_ANDROID
                                this.ActionURL = result.AndroidAction;
                                                                        #elif UNITY_WP8 || UNITY_WP8_1
                                this.ActionURL = result.WPAction;
                                                                        #endif

                                callback(true, "Show Message");
                            }
                            break;

                        case SMessageCondition.UnCheckVersion:

                            MobileNativeDialog dialogMessage = new MobileNativeDialog(result.Title, result.MessageDialog, "OK", "Cancel");
                            dialogMessage.OnComplete        += OnDialogClose;

                                                                #if UNITY_IOS
                            this.ActionURL = result.iOSAction;
                                                                #elif UNITY_ANDROID
                            this.ActionURL = result.AndroidAction;
                                                                #elif UNITY_WP8 || UNITY_WP8_1
                            this.ActionURL = result.WPAction;
                                                                #endif

                            callback(true, "Show Message");
                            break;
                        }
                    }
                    else
                    {
                        callback(false, "Not show popup.");
                    }
                }
                else
                {
                    callback(false, "Null response.");
                }
            }
            else
            {
                callback(false, "Cannot handle response.");
            }
        });
    }
 public static int StringBasedCompareTo(TrackedBundleVersionInfo info1, TrackedBundleVersionInfo info2)
 {
     System.Version v1 = new System.Version(info1.version);
     System.Version v2 = new System.Version(info2.version);
     return(v1.CompareTo(v2));
 }
 public static System.Version MaxVersion(System.Version a, System.Version b)
 {
     return((a.CompareTo(b) > 0) ? a : b);
 }
    public static void ExportPackage(GameObject gameObject, string path, string typeName, PackageJSON packageJSON)
    {
        if (exporting)
        {
            return;
        }
        string fileName        = Path.GetFileName(path);
        string folderPath      = Path.GetDirectoryName(path);
        string androidFileName = Path.GetFileNameWithoutExtension(path) + "_android";
        string pcFileName      = Path.GetFileNameWithoutExtension(path) + "_pc";

        string assetBundleScenePath = $"Assets/Editor/ExportScene.unity";

        string oldScenePath = gameObject.scene.path;

        if (oldScenePath != null)
        {
            EditorSceneManager.SaveScene(gameObject.scene);
        }
        try
        {
            // Disable scene checking because it'll be loading the scene to export
            SceneChecker.disabled = true;
            exporting             = true;

            Selection.activeObject = gameObject;
            MapDescriptor mapDescriptor = gameObject.GetComponent <MapDescriptor>();

            // Compute Required Versions
            System.Version pcRequiredVersion      = ComputePcVersion(mapDescriptor);
            System.Version androidRequiredVersion = ComputeAndroidVersion(mapDescriptor);

            if (!mapDescriptor.ExportLighting)
            {
                Lightmapping.Clear();
                Lightmapping.ClearLightingDataAsset();
            }

            //Check if editor folder exists just in case, since some people move it accidentally or something
            if (!AssetDatabase.IsValidFolder("Assets/Editor"))
            {
                Debug.LogWarning("The Editor folder does not exist. You may have installed the project incorrectly, or dragged the Editor folder into a subfolder.");
                Debug.LogWarning("If you experience problems with exporting, make sure your Editor folder is in the right place. If it still doesn't work, reinstall this unity project and make sure to follow the install instructions.");
                Debug.LogWarning("Trying to export anyways...");
                AssetDatabase.CreateFolder("Assets", "Editor");
            }
            EditorSceneManager.SaveScene(gameObject.scene, assetBundleScenePath, true);

            EditorSceneManager.OpenScene(assetBundleScenePath);

            // Destroy other maps that exist
            MapDescriptor[] descriptorList = Object.FindObjectsOfType <MapDescriptor>();
            foreach (MapDescriptor descriptor in descriptorList)
            {
                if (descriptor.MapName != mapDescriptor.MapName)
                {
                    Object.DestroyImmediate(descriptor.gameObject);
                }
                else
                {
                    mapDescriptor          = descriptor;
                    gameObject             = descriptor.gameObject;
                    Selection.activeObject = gameObject;
                }
            }

            // Move objects that aren't in the map parent to the map parent
            foreach (GameObject sceneRootObject in EditorSceneManager.GetActiveScene().GetRootGameObjects())
            {
                if (sceneRootObject != gameObject)
                {
                    sceneRootObject.transform.SetParent(gameObject.transform);
                }
            }

            // Unpack all prefabs
            foreach (GameObject subObject in GameObject.FindObjectsOfType <GameObject>())
            {
                if (PrefabUtility.GetPrefabInstanceStatus(subObject) != PrefabInstanceStatus.NotAPrefab)
                {
                    PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetOutermostPrefabInstanceRoot(subObject), PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
                }
            }

            // Skybox Stuff

            if (mapDescriptor.CustomSkybox != null)
            {
                // Create Fake Skybox
                GameObject skybox = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                skybox.name = "Skybox";
                skybox.transform.SetParent(gameObject.transform);
                skybox.transform.localScale    = new Vector3(1000, 1000, 1000);
                skybox.transform.localPosition = Vector3.zero;
                skybox.transform.localRotation = Quaternion.identity;
                Object.DestroyImmediate(skybox.GetComponent <Collider>());
                Material skyboxMaterial = new Material(Shader.Find("Bobbie/Outer"));
                skyboxMaterial.SetTexture("_Tex", mapDescriptor.CustomSkybox);
                skybox.GetComponent <Renderer>().material          = skyboxMaterial;
                skybox.GetComponent <Renderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            }
            else
            {
                // Create Fake Skybox that represents the game's
                GameObject skyboxObject = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/FakeSkybox.prefab", typeof(GameObject)) as GameObject;
                GameObject fakeSkybox   = PrefabUtility.InstantiatePrefab(skyboxObject) as GameObject;
                fakeSkybox.transform.SetParent(gameObject.transform);
                fakeSkybox.transform.localPosition = Vector3.zero;
            }

            // Remove meshes from prefabs/triggers
            if (!DebugPrefabs)
            {
                StripMeshes <ObjectTrigger>(gameObject);
                StripMeshes <Teleporter>(gameObject);
                StripMeshes <TagZone>(gameObject);
                foreach (Renderer renderer in gameObject.GetComponentsInChildren <Renderer>())
                {
                    if (renderer.sharedMaterial != null && renderer.sharedMaterial.name.StartsWith("Teleport Point"))
                    {
                        Object.DestroyImmediate(renderer);
                    }
                }
                StripMeshes <ObjectTrigger>(gameObject);
            }

            foreach (Renderer renderer in gameObject.GetComponentsInChildren <Renderer>())
            {
                if (renderer.sharedMaterial != null && renderer.sharedMaterial.name.StartsWith("Spawn Point"))
                {
                    bool foundTransform = false;
                    foreach (Transform spawnPoint in mapDescriptor.SpawnPoints)
                    {
                        if (spawnPoint == renderer.gameObject.transform)
                        {
                            foundTransform = true;
                        }
                    }
                    if (!foundTransform)
                    {
                        List <Transform> spawnPointArray = new List <Transform>(mapDescriptor.SpawnPoints);
                        spawnPointArray.Add(renderer.gameObject.transform);
                        mapDescriptor.SpawnPoints = spawnPointArray.ToArray();
                    }
                    if (!DebugPrefabs)
                    {
                        Collider spawnPointCollider = renderer.gameObject.GetComponent <Collider>();
                        if (spawnPointCollider)
                        {
                            Object.DestroyImmediate(spawnPointCollider);
                        }
                        Object.DestroyImmediate(renderer);
                    }
                }
            }

            if (mapDescriptor.SpawnPoints.Length == 0)
            {
                throw new System.Exception("No spawn points found! Add some spawn points to your map.");
            }

            // Take Screenshots with the thumbnail camera
            Camera thumbnailCamera = GameObject.Find("ThumbnailCamera")?.GetComponent <Camera>();
            if (thumbnailCamera != null)
            {
                // Normal Screenshot
                Texture2D screenshot    = CaptureScreenshot(thumbnailCamera, 512, 512);
                byte[]    screenshotPNG = ImageConversion.EncodeToPNG(screenshot);
                File.WriteAllBytes(Application.temporaryCachePath + "/preview.png", screenshotPNG);
                packageJSON.config.imagePath = "preview.png";

                // Cubemap Screenshot
                Texture2D screenshotCubemap    = CaptureCubemap(thumbnailCamera, 1024, 1024);
                byte[]    screenshotCubemapPNG = ImageConversion.EncodeToPNG(screenshotCubemap);
                File.WriteAllBytes(Application.temporaryCachePath + "/preview_cubemap.png", screenshotCubemapPNG);
                packageJSON.config.cubemapImagePath = "preview_cubemap.png";

                packageJSON.config.mapColor = AverageColor(screenshotCubemap);
            }
            else
            {
                throw new System.Exception("ThumbnailCamera is missing! Make sure to add a ThumbnailCamera to your map.");
            }
            Object.DestroyImmediate(thumbnailCamera.gameObject);

            // Pre-Process stuff for both platforms - PC and Android.
            GameObject spawnPointContainer = new GameObject("SpawnPointContainer");
            spawnPointContainer.transform.SetParent(gameObject.transform);
            spawnPointContainer.transform.localPosition = Vector3.zero;
            spawnPointContainer.transform.localRotation = Quaternion.identity;
            spawnPointContainer.transform.localScale    = Vector3.one;

            List <string> spawnPointNames = new List <string>();

            for (int i = 0; i < mapDescriptor.SpawnPoints.Length; i++)
            {
                Transform spawnPointTransform = mapDescriptor.SpawnPoints[i].gameObject.transform;
                Vector3   oldPos      = spawnPointTransform.position;
                var       oldRotation = spawnPointTransform.rotation;

                spawnPointTransform.SetParent(spawnPointContainer.transform);
                spawnPointTransform.rotation = oldRotation;
                spawnPointTransform.position = oldPos;

                string nameString = "SpawnPoint" + (i < 10 ? "0" + i : i.ToString());
                mapDescriptor.SpawnPoints[i].gameObject.name = nameString;
                spawnPointNames.Add(nameString);
            }
            packageJSON.config.spawnPoints = spawnPointNames.ToArray();


            // Replace tiling materials with baked versions
            foreach (Renderer renderer in gameObject.GetComponentsInChildren <Renderer>())
            {
                if (renderer.sharedMaterial != null && renderer.sharedMaterial.shader.name.Contains("Standard Tiling") && !renderer.sharedMaterial.shader.name.Contains("Baked"))
                {
                    renderer.sharedMaterial        = Object.Instantiate(renderer.sharedMaterial);
                    renderer.sharedMaterial.shader = Shader.Find("Standard Tiling Baked");
                    Transform rendererTransform = renderer.gameObject.transform;
                    Vector3   newVector         = RotatePointAroundPivot(rendererTransform.lossyScale, new Vector3(0, 0, 0), rendererTransform.rotation.eulerAngles);
                    renderer.sharedMaterial.SetVector("_ScaleVector", newVector);
                }
            }

            // Destroy all non-render cameras because people keep accidentally exporting them
            foreach (Camera camera in gameObject.GetComponentsInChildren <Camera>())
            {
                if (camera.targetTexture == null && camera.gameObject != null)
                {
                    Object.DestroyImmediate(camera.gameObject);
                }
            }

            //Destroy Audio listeners too since they can break sound
            foreach (AudioListener listener in gameObject.GetComponentsInChildren <AudioListener>())
            {
                if (listener != null)
                {
                    Object.DestroyImmediate(listener);
                }
            }

            // Lighting stuff. Make sure to set light stuff up and make it bigger, and bake
            if (mapDescriptor.ExportLighting)
            {
                foreach (Light light in Object.FindObjectsOfType <Light>())
                {
                    // needs to be redone, colors are inconsistent and can probably be made better
                    if (light.type == LightType.Directional)
                    {
                        light.intensity *= 11.54f;
                        light.color      = new Color(0.3215f, 0.3215f, 0.3215f);
                    }
                    else
                    {
                        light.intensity *= 10f;
                    }
                }

                bool baking = Lightmapping.BakeAsync();
                if (baking)
                {
                    Lightmapping.bakeCompleted -= PostBake;
                    Lightmapping.bakeCompleted += PostBake;
                }
                else
                {
                    throw new System.Exception("Couldn't start lightmapping.");
                }
            }
            else
            {
                foreach (Light light in Object.FindObjectsOfType <Light>())
                {
                    Object.DestroyImmediate(light);
                }
                Lightmapping.Clear();
                Lightmapping.ClearLightingDataAsset();
                PostBake();
            }

            void PostBake()
            {
                gameObject.transform.localPosition = new Vector3(0, 5000, 0);

                // Save as prefab and build
                // PrefabUtility.SaveAsPrefabAsset(Selection.activeObject as GameObject, $"Assets/_{typeName}.prefab");
                EditorSceneManager.SaveScene(gameObject.scene);
                AssetBundleBuild assetBundleBuild = default;

                assetBundleBuild.assetNames      = new string[] { assetBundleScenePath };
                assetBundleBuild.assetBundleName = pcFileName;

                // Build for PC

                BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { assetBundleBuild }, 0, BuildTarget.StandaloneWindows64);

                // Do Android specific stuff here. Stripping MonoBehaviours and converting them to TextAssets, etc.

                // first we need to redo this bit of code because sometimes gameObject unreferences itself
                MapDescriptor[] descriptorList2 = Object.FindObjectsOfType <MapDescriptor>();
                foreach (MapDescriptor descriptor in descriptorList2)
                {
                    if (descriptor.MapName != mapDescriptor.MapName)
                    {
                        Object.DestroyImmediate(descriptor.gameObject);
                    }
                    else
                    {
                        mapDescriptor          = descriptor;
                        gameObject             = descriptor.gameObject;
                        Selection.activeObject = gameObject;
                    }
                }

                StripPrefabsForQuest(gameObject);

                Object.DestroyImmediate(mapDescriptor);

                // Do it again for Android
                EditorSceneManager.SaveScene(gameObject.scene);
                // PrefabUtility.SaveAsPrefabAsset(Selection.activeObject as GameObject, $"Assets/_{typeName}.prefab"); // are these next 2 lines necessary? idk. probably test it.
                assetBundleBuild.assetNames      = new string[] { assetBundleScenePath };
                assetBundleBuild.assetBundleName = androidFileName;
                BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { assetBundleBuild }, 0, BuildTarget.Android);

                EditorPrefs.SetString("currentBuildingAssetBundlePath", folderPath);

                // JSON stuff
                packageJSON.androidFileName = androidFileName;
                packageJSON.pcFileName      = pcFileName;
                packageJSON.descriptor.pcRequiredVersion      = pcRequiredVersion.ToString();
                packageJSON.descriptor.androidRequiredVersion = androidRequiredVersion.ToString();
                string json = JsonUtility.ToJson(packageJSON, true);

                File.WriteAllText(Application.temporaryCachePath + "/package.json", json);
                // AssetDatabase.DeleteAsset($"Assets/_{typeName}.prefab");

                // Delete the zip if it already exists and re-zip
                List <string> files = new List <string> {
                    Application.temporaryCachePath + "/" + pcFileName,
                    Application.temporaryCachePath + "/" + androidFileName,
                    Application.temporaryCachePath + "/package.json",
                    Application.temporaryCachePath + "/preview.png",
                    Application.temporaryCachePath + "/preview_cubemap.png"
                };

                if (File.Exists(Application.temporaryCachePath + "/tempZip.zip"))
                {
                    File.Delete(Application.temporaryCachePath + "/tempZip.zip");
                }

                CreateZipFile(Application.temporaryCachePath + "/tempZip.zip", files);

                // After zipping, clear some assets from the temp folder
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                foreach (string file in files)
                {
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }
                }

                // Move the ZIP and finalize
                File.Move(Application.temporaryCachePath + "/tempZip.zip", path);
                //Object.DestroyImmediate(gameObject);
                AssetDatabase.Refresh();

                // Open scene again
                EditorSceneManager.OpenScene(oldScenePath);

                // Re-enable scene checking
                SceneChecker.disabled = false;
                exporting             = false;

                EditorUtility.DisplayDialog("Exportation Successful!", "Exportation Successful!", "OK");
                EditorUtility.RevealInFinder(path);
            }
        }
        catch (System.Exception e)
        {
            exporting             = false;
            SceneChecker.disabled = false;
            Debug.Log("Something went wrong... let's load the old scene.");
            EditorUtility.DisplayDialog("Error!", e.Message, "OK");
            if (oldScenePath != null)
            {
                EditorSceneManager.OpenScene(oldScenePath);
            }
            else
            {
                throw new System.Exception("Something went wrong and you don't have your work saved in a scene! PLEASE save your work in a scene before trying to export.");
            }
            throw e;
        }
    }
Example #38
0
 public override void VersionCheck(System.Version currentDataVersion)
 {
 }
Example #39
0
 private static bool VersionEquivalentTo(int major, int minor, int build, int revision, Version actualVersionId)
 {
     return((major == -1 || major == actualVersionId.Major) &&
            (minor == -1 || minor == actualVersionId.Minor) &&
            (build == -1 || build == actualVersionId.Build) &&
            (revision == -1 || revision == actualVersionId.Revision));
 }
Example #40
0
	private static void AttemptPluginUpdate(bool triggeredByAutoUpdate)
	{
		autoUpdateEnabled = true:

		PluginPackage bundledPluginPkg = GetBundledPluginPackage():
		List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages():

		PluginPackage enabledUtilsPluginPkg = null:
		PluginPackage newestUtilsPluginPkg = null:

		foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
		{
			if ((newestUtilsPluginPkg == null) || (pluginPkg.Version > newestUtilsPluginPkg.Version))
			{
				newestUtilsPluginPkg = pluginPkg:
			}

			if (pluginPkg.IsEnabled())
			{
				if ((enabledUtilsPluginPkg == null) || (pluginPkg.Version > enabledUtilsPluginPkg.Version))
				{
					enabledUtilsPluginPkg = pluginPkg:
				}
			}
		}

		PluginPackage targetPluginPkg = null:

		if ((newestUtilsPluginPkg != null) && (newestUtilsPluginPkg.Version > bundledPluginPkg.Version))
		{
			if ((enabledUtilsPluginPkg == null) || (enabledUtilsPluginPkg.Version != newestUtilsPluginPkg.Version))
			{
				targetPluginPkg = newestUtilsPluginPkg:
			}
		}
		else if ((enabledUtilsPluginPkg != null) && (enabledUtilsPluginPkg.Version < bundledPluginPkg.Version))
		{
			targetPluginPkg = bundledPluginPkg:
		}
         
		System.Version currentVersion = (enabledUtilsPluginPkg != null) ? enabledUtilsPluginPkg.Version : bundledPluginPkg.Version:

		if (targetPluginPkg == null)
		{
			if (!triggeredByAutoUpdate)
			{
				EditorUtility.DisplayDialog("Update Oculus Utilities Plugin", "OVRPlugin is already up to date.\n\nCurrent version: " + currentVersion + "\nBundled version: " + bundledPluginPkg.Version, "Ok", ""):
			}

			return: // No update necessary.
		}

		System.Version targetVersion = targetPluginPkg.Version:

		int dialogResult = EditorUtility.DisplayDialogComplex("Update Oculus Utilities Plugin", "Oculus Utilities has detected that a newer OVRPlugin is available. Using the newest version is recommended. Do you want to enable it?\n\nCurrent version: " + currentVersion + "\nAvailable version: " + targetVersion, "Yes", "No, Don't Ask Again", "No"):

		bool userAcceptsUpdate = false:

		switch (dialogResult)
		{
			case 0: // "Yes"
				userAcceptsUpdate = true:
				break:
			case 1: // "No, Don't Ask Again"
				autoUpdateEnabled = false:

				EditorUtility.DisplayDialog("Oculus Utilities OVRPlugin", "To manually update in the future, use the following menu option:\n\n[Tools -> Oculus -> Update OVR Utilities Plugin]", "Ok", ""):
				return:
			case 2: // "No"
				return:
		}

		if (userAcceptsUpdate)
		{
			DisableAllUtilitiesPluginPackages():

			if (!targetPluginPkg.IsBundledPluginPackage())
			{
				EnablePluginPackage(targetPluginPkg):
			}

			if (EditorUtility.DisplayDialog("Restart Unity", "OVRPlugin has been updated to " + targetPluginPkg.Version + ".\n\nPlease restart the Unity Editor to complete the update process. You may need to manually relaunch Unity if you are using Unity 5.6 and higher.", "Restart", "Not Now"))
			{
				RestartUnityEditor():
			}
		}
	}
 public static Commit GetCommitFromVersion(LibGit2Context context, Version version)
 {
     // Note we'll accept no match, or one match. But we throw if there is more than one match.
     return(GetCommitsFromVersion(context, version).SingleOrDefault());
 }
Example #42
0
 private static bool VersionEquivalentToOrHigher(int major, int minor, int build, int revision, Version actualVersionId)
 {
     return
         (VersionEquivalentTo(major, minor, build, revision, actualVersionId) ||
          (actualVersionId.Major > major ||
           (actualVersionId.Major == major && actualVersionId.Minor > minor ||
            (actualVersionId.Minor == minor && actualVersionId.Build > build ||
             (actualVersionId.Build == build && actualVersionId.Revision > revision ||
              (actualVersionId.Revision == revision))))));
 }
        /// <summary>
        /// Gets the number of commits in the longest single path between
        /// the specified commit and the most distant ancestor (inclusive)
        /// that set the version to the value at <paramref name="commit"/>.
        /// </summary>
        /// <param name="commit">The commit to measure the height of.</param>
        /// <param name="repoRelativeProjectDirectory">The repo-relative project directory for which to calculate the version.</param>
        /// <param name="baseVersion">Optional base version to calculate the height. If not specified, the base version will be calculated by scanning the repository.</param>
        /// <returns>The height of the commit. Always a positive integer.</returns>
        public static int GetVersionHeight(this Commit commit, string repoRelativeProjectDirectory = null, Version baseVersion = null)
        {
            Requires.NotNull(commit, nameof(commit));
            Requires.Argument(repoRelativeProjectDirectory == null || !Path.IsPathRooted(repoRelativeProjectDirectory), nameof(repoRelativeProjectDirectory), "Path should be relative to repo root.");

            if (baseVersion == null)
            {
                baseVersion = VersionFile.GetVersion(commit, repoRelativeProjectDirectory)?.Version?.Version ?? Version0;
            }

            int height = commit.GetHeight(c => CommitMatchesMajorMinorVersion(c, baseVersion, repoRelativeProjectDirectory));

            return(height);
        }
Example #44
0
    // Sets up ISPC build rules as custom pre-build step in the passed in target, and caches autogenerated rule details.
    public static void SetupISPCRules(TargetRules Target)
    {
        System.Version ISPCVersion = GetISPCVersion();
        if (ISPCVersion.Major < 0)
        {
            Log.WriteLine(LogEventType.Warning, "Could not determine the ISPC version");
        }
        else if (ISPCVersion < MinimumISPCVersion)
        {
            throw new System.Exception(string.Format("ISPC version {0} is not recent enough, a minimum of {1} is required",
                                                     ISPCVersion.ToString(), MinimumISPCVersion.ToString()));
        }

        string ModuleName = new StackFrame().GetMethod().DeclaringType.ToString();

        string PlatformIntermediateDir = Path.Combine
                                         (
            Target.ProjectFile.Directory.FullName,
            "Intermediate",
            "Build",
            Target.Platform.ToString(),
            /*UEBuildPlatform.GetBuildPlatform(Target.Platform).GetFolderNameForArchitecture*/ (Target.Architecture)
                                         );

        string ModuleSourceDirectory = Path.Combine
                                       (
            Target.ProjectFile.Directory.FullName,
            "Source",
            ModuleName
                                       );

        Debug.Assert(File.Exists(Path.Combine(ModuleSourceDirectory, ModuleName + ".Build.cs")), string.Format("`ModuleSourceDirectory` needs to point at the `Source` directory of module `{0}`", ModuleName));

        string ObjectDir = Path.Combine
                           (
            PlatformIntermediateDir,
            Target.Name,
            Target.Configuration.ToString(),
            ModuleName
                           );

        string HeaderDir = Path.Combine
                           (
            PlatformIntermediateDir,
            Target.Type == TargetType.Editor ? "UE4Editor" : "UE4",
            "Inc",
            ModuleName
                           );

        Directory.CreateDirectory(ObjectDir);
        Directory.CreateDirectory(HeaderDir);

        var Sources = GetISPCSources(ModuleSourceDirectory);

        bool bUseGNUMake = System.Environment.OSVersion.Platform == System.PlatformID.Unix || System.Environment.OSVersion.Platform == System.PlatformID.MacOSX;

        string MakefilePath = Path.Combine(ObjectDir, MakefileName);

        Log.WriteLine(LogEventType.Console, "Generating ISPC makefile {0}", MakefilePath);
        using (StreamWriter Makefile = new StreamWriter(MakefilePath))
        {
            Makefile.WriteLine("# Generated automatically by module rules, do not modify");
            Makefile.WriteLine();

            Makefile.WriteLine("ISPC=" + GetISPCExecutablePath());
            Makefile.WriteLine("ISPCFLAGS=" + GetISPCFlags(Target.Platform, Target.Configuration, bUseInstrumentation));
            Makefile.WriteLine("SOURCE_DIR=" + ModuleSourceDirectory);
            Makefile.WriteLine("HEADER_DIR=" + HeaderDir);
            Makefile.WriteLine();

            List <string> AbsoluteSources = new List <string>();
            List <string> Objects         = new List <string>();
            List <string> AbsoluteObjects = new List <string>();
            List <string> Headers         = new List <string>();
            List <string> Dependencies    = new List <string>();
            foreach (string RelativeSource in Sources)
            {
                string BaseName   = Path.GetFileName(RelativeSource);
                string Object     = BaseName.Replace(".ispc", ".ispc.o");
                string Header     = BaseName.Replace(".ispc", ".ispc.h");
                string Dependency = BaseName.Replace(".ispc", ".ispc.d");
                string AbsSource  = Path.Combine(ModuleSourceDirectory, RelativeSource);
                string AbsObject  = Path.Combine(ObjectDir, Object);
                string AbsHeader  = Path.Combine(HeaderDir, Header);

                AbsoluteSources.Add(AbsSource);
                Objects.Add(Object);
                AbsoluteObjects.Add(AbsObject);
                Headers.Add(AbsHeader);
                Dependencies.Add(Dependency);

                Makefile.WriteLine(bUseGNUMake ? "ifdef $(HAVE_DEPENDENCIES)" : "!IFDEF HAVE_DEPENDENCIES");

                Makefile.WriteLine("# ISPC object file.");
                Makefile.WriteLine("{0} {1}", bUseGNUMake ? "include" : "!INCLUDE", Dependency);
                Makefile.WriteLine("\t$(ISPC) \"$(SOURCE_DIR){0}\" -o $@ -h \"$(HEADER_DIR){1}\" $(ISPCFLAGS)",
                                   Path.DirectorySeparatorChar + RelativeSource,
                                   Path.DirectorySeparatorChar + Header);

                Makefile.WriteLine("# ISPC C++ autogenerated header. Actually built together with the object file, so consider this indirect dependency a hack.");
                Makefile.WriteLine("\"$(HEADER_DIR){0}\": {1}", Path.DirectorySeparatorChar + Header, Object);

                Makefile.WriteLine(bUseGNUMake ? "else" : "!ELSE");

                Makefile.WriteLine("# ISPC object dependency file.");
                Makefile.WriteLine("{0}: \"$(SOURCE_DIR){1}\"", Dependency, Path.DirectorySeparatorChar + RelativeSource);
                Makefile.WriteLine("\t$(ISPC) $? -M -MF $@ -MT {0} --wno-perf $(ISPCFLAGS)", Object);

                Makefile.WriteLine(bUseGNUMake ? "endif" : "!ENDIF");

                Makefile.WriteLine();
            }
            Makefile.WriteLine("# Phony target for building all dependency files.");
            Makefile.WriteLine("depend: " + string.Join(" ", Dependencies));
            Makefile.WriteLine("# Phony target for building all objects.");
            Makefile.WriteLine("all: " + string.Join(" ", Objects));

            _ISPCObjects = AbsoluteObjects.ToArray();
        }

        // Use /C to silence nmake's output because the copyright notice is emitted to stderr and UBT interprets that as error.
        string MakeCmdline = bUseGNUMake ? "make -f" : "nmake /C /F";
        string PreTarget   = "HAVE_DEPENDENCIES=1";
        string PostTarget  = "";

        if (bUseGNUMake)
        {
            PostTarget = PreTarget;
            PreTarget  = "";
        }

        Target.PreBuildSteps.Add(string.Format("pushd \"{0}\" && " +
                                               "echo Gathering ISPC dependencies && " +
                                               "{1} \"{2}\" depend && " +
                                               "echo Building ISPC kernels && " +
                                               "{1} \"{2}\" {3} all {4} &&" +
                                               "popd",
                                               ObjectDir,
                                               MakeCmdline,
                                               MakefileName,
                                               PreTarget,
                                               PostTarget
                                               ));

        bISPCHasBeenSetupInTarget = true;
    }
    public static string GetVersionDescription(System.Version version)
    {
        bool isVersionValid = (version != invalidVersion);

        return(isVersionValid ? version.ToString() : "(Unknown)");
    }
        /// <summary>
        /// Looks up the commits that match a specified version number.
        /// </summary>
        /// <param name="repo">The repository to search for a matching commit.</param>
        /// <param name="version">The version previously obtained from <see cref="GetIdAsVersion(Commit, string, int?)"/>.</param>
        /// <param name="repoRelativeProjectDirectory">The repo-relative project directory from which <paramref name="version"/> was originally calculated.</param>
        /// <returns>The matching commits, or an empty enumeration if no match is found.</returns>
        public static IEnumerable <Commit> GetCommitsFromVersion(this Repository repo, Version version, string repoRelativeProjectDirectory = null)
        {
            Requires.NotNull(repo, nameof(repo));
            Requires.NotNull(version, nameof(version));

            // The revision is a 16-bit unsigned integer, but is not allowed to be 0xffff.
            // So if the value is 0xfffe, consider that the actual last bit is insignificant
            // since the original git commit ID could have been either 0xffff or 0xfffe.
            ushort objectIdLeadingValue = (ushort)version.Revision;
            ushort objectIdMask         = (ushort)(version.Revision == MaximumBuildNumberOrRevisionComponent ? 0xfffe : 0xffff);

            var possibleCommits = from commit in GetCommitsReachableFromRefs(repo)
                                  where version.Revision == -1 || commit.Id.StartsWith(objectIdLeadingValue, objectIdMask)
                                  let buildNumberOffset = VersionFile.GetVersion(commit)?.BuildNumberOffset ?? 0
                                                          let versionHeight = commit.GetHeight(c => CommitMatchesMajorMinorVersion(c, version, repoRelativeProjectDirectory))
                                                                              where versionHeight == version.Build - buildNumberOffset
                                                                              select commit;

            return(possibleCommits);
        }
Example #47
0
        public static Configuration CheckPackageInstallation()
        {
            IS_INSTALLED = false;
            Config       = Configuration.Auto;

            if (PackageManager.packages == null)
            {
                PackageManager.RetreivePackageList();
            }

            foreach (UnityEditor.PackageManager.PackageInfo p in PackageManager.packages)
            {
                if (p.name == PACKAGE_ID)
                {
                    PPS_VERSION = p.version.Replace("-preview", string.Empty);
                    LATEST_COMPATIBLE_VERSION = p.versions.latestCompatible;

                    //Validate installed version against compatible range
                    System.Version curVersion    = new System.Version(PPS_VERSION);
                    System.Version minVersion    = new System.Version(MIN_PPS_VERSION);
                    System.Version maxVersion    = new System.Version(MAX_PPS_VERSION);
                    System.Version latestVersion = new System.Version(LATEST_COMPATIBLE_VERSION);

                    //Clamp to maximum compatible version
                    if (latestVersion > maxVersion)
                    {
                        latestVersion = maxVersion;
                    }

                    if (curVersion >= minVersion && curVersion <= maxVersion)
                    {
                        PPSVersionStatus = VersionStatus.Compatible;
                    }
                    if (curVersion < minVersion || curVersion < latestVersion)
                    {
                        PPSVersionStatus = VersionStatus.Outdated;
                    }
                    if (curVersion < minVersion || curVersion > maxVersion)
                    {
                        PPSVersionStatus = VersionStatus.InCompatible;
                    }
#if SCPE_DEV
                    Debug.Log("<b>CheckPPSInstallation</b> PPS version " + p.version + " Installed. Required: " + MIN_PPS_VERSION);
#endif

                    IS_INSTALLED = true;
                    Config       = Configuration.PackageManager;
                }
            }

            //PPS not installed
            if (IS_INSTALLED == false)
            {
#if UNITY_2019_3_OR_NEWER //URP is available and has integrated PP
                if (RenderPipelineInstallation.CurrentPipeline == RenderPipelineInstallation.Pipeline.URP && RenderPipelineInstallation.VersionStatus == RenderPipelineInstallation.Version.Compatible)
                {
                    IS_INSTALLED = true;
                    Config       = Configuration.Integrated;

                    PPSVersionStatus = VersionStatus.Compatible;

#if SCPE_DEV
                    Debug.Log("<b>CheckPPSInstallation</b> URP installed, integrated PP available");
#endif
                }
#else //On older versions, fetch latest compatible PSS package
                UnityEditor.PackageManager.Requests.SearchRequest r = Client.Search(PACKAGE_ID);
                while (r.Status == StatusCode.InProgress)
                {
                    //Waiting
                }
                if (r.IsCompleted)
                {
                    LATEST_COMPATIBLE_VERSION = r.Result[0].versions.latestCompatible;

                    //Clamp to maximum compatible version
                    System.Version maxVersion    = new System.Version(MAX_PPS_VERSION);
                    System.Version latestVersion = new System.Version(LATEST_COMPATIBLE_VERSION);
                    if (latestVersion > maxVersion)
                    {
                        LATEST_COMPATIBLE_VERSION = MAX_PPS_VERSION;
                    }
                }
#endif
            }

#if SCPE_DEV
            if (IS_INSTALLED)
            {
                Debug.Log("<b>PostProcessingInstallation</b> " + Config + " version is installed");
            }
            else
            {
                Debug.Log("<b>PostProcessingInstallation</b> Post Processing Stack is not installed");
            }
#endif
            return(Config);
        }
Example #48
0
 private static Version[] GetNewerVersions(Version[] versions, System.Version currentVersion)
 {
     return(versions.Where(v => v.GetVersionTag() > currentVersion).ToArray());
 }
Example #49
0
        internal override unsafe bool GetFileVersion(string dll, out int major, out int minor, out int revision, out int patch)
        {
            using FileStream stream = File.OpenRead(dll);
            MachOFileReader reader = new MachOFileReader(stream);

            MachOHeader64 header = reader.Read <MachOHeader64>();

            if (header.Magic != MachOHeader64.ExpectedMagic)
            {
                throw new NotSupportedException();
            }

            long dataOffset = 0;
            long dataSize   = 0;

            byte[] dataSegmentName = Encoding.ASCII.GetBytes("__DATA\0");
            byte[] dataSectionName = Encoding.ASCII.GetBytes("__data\0");
            for (int c = 0; c < header.NumberOfCommands; c++)
            {
                MachOCommand     command     = reader.Read <MachOCommand>();
                MachOCommandType commandType = command.Command;
                int commandSize = command.CommandSize;

                if (commandType == MachOCommandType.Segment64)
                {
                    long position = stream.Position;
                    MachOSegmentCommand64 segmentCommand = reader.Read <MachOSegmentCommand64>();
                    if (new ReadOnlySpan <byte>(segmentCommand.SegmentName, dataSegmentName.Length).SequenceEqual(dataSegmentName))
                    {
                        for (int s = 0; s < segmentCommand.NumberOfSections; s++)
                        {
                            MachOSection64 section = reader.Read <MachOSection64>();
                            if (new ReadOnlySpan <byte>(section.SectionName, dataSectionName.Length).SequenceEqual(dataSectionName))
                            {
                                dataOffset = section.Offset;
                                dataSize   = section.Size;
                                break;
                            }
                        }

                        break;
                    }

                    stream.Position = position;
                }

                stream.Seek(commandSize - sizeof(MachOCommand), SeekOrigin.Current);
            }

            Span <byte> buffer     = stackalloc byte[s_versionLength];
            long        address    = dataOffset;
            long        endAddress = address + dataSize;

            Span <byte> bytes = stackalloc byte[1];
            Span <char> chars = stackalloc char[1];

            while (address < endAddress)
            {
                int read = reader.Read(address, buffer);
                if (read < s_versionLength)
                {
                    break;
                }

                if (!buffer.SequenceEqual(s_versionString))
                {
                    address++;
                    continue;
                }

                address += s_versionLength;

                // TODO:  This should be cleaned up to not read byte by byte in the future.  Leaving it here
                // until we decide whether to rewrite the Linux coredumpreader or not.
                StringBuilder builder = new StringBuilder();
                while (address < endAddress)
                {
                    read = reader.Read(address, bytes);
                    if (read < bytes.Length)
                    {
                        break;
                    }

                    if (bytes[0] == '\0')
                    {
                        break;
                    }

                    if (bytes[0] == ' ')
                    {
                        try
                        {
                            System.Version v = System.Version.Parse(builder.ToString());
                            major    = v.Major;
                            minor    = v.Minor;
                            revision = v.Build;
                            patch    = v.Revision;
                            return(true);
                        }
                        catch (FormatException)
                        {
                            break;
                        }
                    }

                    fixed(byte *bytesPtr = &MemoryMarshal.GetReference(bytes))
                    fixed(char *charsPtr = &MemoryMarshal.GetReference(chars))
                    {
                        _ = Encoding.ASCII.GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length);
                    }

                    _ = builder.Append(chars[0]);
                    address++;
                }

                break;
            }

            major = minor = revision = patch = 0;
            return(false);
        }
        /// <include file='doc\StrongNameIdentityPermission.uex' path='docs/doc[@for="StrongNameIdentityPermission.StrongNameIdentityPermission1"]/*' />
        public StrongNameIdentityPermission(StrongNamePublicKeyBlob blob, String name, Version version)
        {
            if (blob == null)
            {
                throw new ArgumentNullException("blob");
            }

            m_publicKeyBlob = blob;
            m_name          = name;
            m_version       = version;
        }
Example #51
0
        //---------------------------------------------OnLoadingComplete----------------------------------------

        static void OnLoadingComplete(EventArgs args)
        {
            if (Player.BaseSkinName != CN)
            {
                Chat.Print("Sorry, you didn't pick " + CN + ", addon disabled"); return;
            }

            AssVersion = Assembly.GetExecutingAssembly().GetName().Version;
            SearchVersion();

            //-------------------------------------------------Items--------------------------------------------------

            R.AllowedCollisionCount = int.MaxValue;
            QSpeed = Player.Spellbook.GetSpell(SpellSlot.Q).SData.MissileSpeed;

            BOTRK      = new Item(3153, 550);
            Hextech    = new Item(3146, 700);
            Bilgewater = new Item(3144, 550);
            Hydra      = new Item(3074, 400);
            Tiamat     = new Item(3077, 400);
            GhostBlade = new Item(3142);
            Randuin    = new Item(3143, 500);
            Scimitar   = new Item(3139);
            QSS        = new Item(3140);
            Trinity    = new Item(ItemId.Trinity_Force);
            Sheen      = new Item(ItemId.Sheen);

            //-------------------------------------------------Smite--------------------------------------------------

            SpellDataInst smite = Player.Spellbook.Spells.Where(spell => spell.Name.Contains("smite")).Any() ? Player.Spellbook.Spells.Where(spell => spell.Name.Contains("smite")).First() : null;

            if (smite != null)
            {
                Smite = new Spell.Targeted(smite.Slot, 500);
            }

            //-------------------------------------------------Ignite--------------------------------------------------

            SpellDataInst dot = Player.Spellbook.Spells.Where(spell => spell.Name.Contains("dot")).Any() ? Player.Spellbook.Spells.Where(spell => spell.Name.Contains("dot")).First() : null;

            if (dot != null)
            {
                Ignite = new Spell.Targeted(dot.Slot, 600);
            }

            //---------------------------||   Menu   ||----------------------------

            Menu = MainMenu.AddMenu("Wu" + CN, "Wu" + CN);

            //------------------------------Combo-------------------------------

            Menu.AddGroupLabel("Combo");
            {
                Menu.Add("UseQCombo", new CheckBox("Use Q Combo"));
                Menu.Add("SmartQ", new CheckBox("Use SmartQ"));
                Menu.Add("QGapCloserCombo", new CheckBox("Use Q on units to gapclose to enemy"));
                Menu.Add("UseWCombo", new CheckBox("Use W Combo"));
                Menu.Add("UseWBeforeQCombo", new CheckBox("Use W Before Q"));
                Menu.Add("UseECombo", new CheckBox("Use E Combo"));
                Menu.Add("OnlyEStunCombo", new CheckBox("Only E for stun"));
                Menu.Add("UseRCombo", new CheckBox("Use R Combo"));
                Menu.Add("UseRSelfActived", new CheckBox("Use R just if it was actived by yourself"));
                Menu.Add("UseRGapCloser", new CheckBox("Use R on units to gapclose with Q"));
            }
            Menu.AddSeparator();

            //------------------------------Harass-------------------------------

            Menu.AddGroupLabel("Harass");
            {
                Menu.Add("UseQHarass", new CheckBox("Use Q Harass"));
                Menu.Add("UseWHarass", new CheckBox("Use W Harass"));
                Menu.Add("UseWBeforeQHarass", new CheckBox("Use W Before Q"));
                Menu.Add("UseEHarass", new CheckBox("Use E Harass"));
                Menu.Add("OnlyEStunHarass", new CheckBox("Only E for stun"));
                Menu.Add("Harass, Mana %", new Slider("Harass, Mana %", 30, 1, 100));
            }
            Menu.AddSeparator();

            //------------------------------LaneClear-------------------------------

            Menu.AddGroupLabel("LaneClear");
            {
                Menu.Add("UseQLaneClear", new CheckBox("Use Q LaneClear"));
                Menu.Add("UseWLaneClear", new CheckBox("Use W LaneClear"));
                Menu.Add("LaneClear, Mana %", new Slider("LaneClear, Mana %", 30, 1, 100));
            }
            Menu.AddSeparator();

            //------------------------------LastHit-------------------------------

            Menu.AddGroupLabel("LastHit");
            {
                Menu.Add("UseQLastHit", new CheckBox("Use Q LastHit"));
                Menu.Add("LastHit, Mana %", new Slider("LastHit, Mana %", 40, 1, 100));
            }
            Menu.AddSeparator();

            //------------------------------Smite Usage-------------------------------

            if (Smite != null)
            {
                Menu.AddGroupLabel("Smite Usage");
                {
                    Menu.Add("Use Smite?", new CheckBox("Use Smite?"));
                    Menu.AddSeparator();
                    Menu.Add("Red?", new CheckBox("Red?"));
                    Menu.Add("Blue?", new CheckBox("Blue?"));
                    Menu.Add("Wolf?", new CheckBox("Wolf?"));
                    Menu.Add("Gromp?", new CheckBox("Gromp?"));
                    Menu.Add("Raptor?", new CheckBox("Raptor?"));
                    Menu.Add("Krug?", new CheckBox("Krug?"));
                }
                Menu.AddSeparator();
            }

            //--------------------------------Flee---------------------------------

            Menu.AddGroupLabel("Flee");
            {
                Menu.Add("UseQFlee", new CheckBox("Use Q Flee"));
                Menu.Add("UseEFlee", new CheckBox("Use E Flee"));
                Menu.Add("UseRFlee", new CheckBox("Use R Flee"));
            }
            Menu.AddSeparator();

            //------------------------------Drawings-------------------------------

            Menu.AddGroupLabel("Drawings");
            {
                Menu.Add("DrawQ", new CheckBox("Draw Q"));
                Menu.Add("DrawE", new CheckBox("Draw E"));
                Menu.Add("DrawR", new CheckBox("Draw R"));
                if (Smite != null)
                {
                    Menu.Add("DrawSmite", new CheckBox("DrawSmite"));
                }
                Menu.Add("ComboDamage on HPBar", new CheckBox("ComboDamage on HPBar"));
            }
            Menu.AddSeparator();

            //------------------------------Other things-------------------------------

            Menu.AddGroupLabel("Other things");

            Menu.Add("KS", new CheckBox("KS"));
            Menu.Add("Interrupter", new CheckBox("Interrupter"));
            Menu.Add("Auto Ignite", new CheckBox("Auto Ignite"));
            Menu.Add("EnemyGapCloser", new CheckBox("Stun/Slow on enemy gapcloser"));
            Menu.Add("s", new KeyBind("s", false, KeyBind.BindTypes.HoldActive, 'J'));

            Menu.AddSeparator();

            Game.OnTick                      += Game_OnTick;
            Drawing.OnDraw                   += Drawing_OnDraw;
            Drawing.OnEndScene               += Drawing_OnEndScene;
            Gapcloser.OnGapcloser            += Gapcloser_OnGapcloser1;
            Obj_AI_Turret.OnBasicAttack      += Obj_AI_Turret_OnBasicAttack;
            Interrupter.OnInterruptableSpell += Interrupter_OnInterruptableSpell;

            Chat.Print("Wu" + CN + " Loaded, [By WujuSan] , Version: " + AssVersion);
        }
Example #52
0
        // check vive input utility version on github
        private static void CheckVersionAndSettings()
        {
            if (Application.isPlaying)
            {
                EditorApplication.update -= CheckVersionAndSettings;
                return;
            }

            InitializeSettins();

            // fetch new version info from github release site
            if (!completeCheckVersionFlow && VIUSettings.autoCheckNewVIUVersion)
            {
                if (webReq == null) // web request not running
                {
                    if (EditorPrefs.HasKey(nextVersionCheckTimeKey) && DateTime.UtcNow < UtcDateTimeFromStr(EditorPrefs.GetString(nextVersionCheckTimeKey)))
                    {
                        VersionCheckLog("Skipped");
                        completeCheckVersionFlow = true;
                        return;
                    }

                    webReq = GetUnityWebRequestAndSend(lastestVersionUrl);
                }

                if (!webReq.isDone)
                {
                    return;
                }

                // On Windows, PlaterSetting is stored at \HKEY_CURRENT_USER\Software\Unity Technologies\Unity Editor 5.x
                EditorPrefs.SetString(nextVersionCheckTimeKey, UtcDateTimeToStr(DateTime.UtcNow.AddMinutes(versionCheckIntervalMinutes)));

                if (UrlSuccess(webReq))
                {
                    latestRepoInfo = JsonUtility.FromJson <RepoInfo>(GetWebText(webReq));
                    VersionCheckLog("Fetched");
                }

                // parse latestVersion and ignoreThisVersionKey
                if (!string.IsNullOrEmpty(latestRepoInfo.tag_name))
                {
                    try
                    {
                        latestVersion        = new System.Version(Regex.Replace(latestRepoInfo.tag_name, "[^0-9\\.]", string.Empty));
                        ignoreThisVersionKey = string.Format(fmtIgnoreUpdateKey, latestVersion.ToString());
                    }
                    catch
                    {
                        latestVersion        = default(System.Version);
                        ignoreThisVersionKey = string.Empty;
                    }
                }

                webReq.Dispose();
                webReq = null;

                completeCheckVersionFlow = true;
            }

            VIUSettingsEditor.PackageManagerHelper.PreparePackageList();
            if (VIUSettingsEditor.PackageManagerHelper.isPreparingList)
            {
                return;
            }

            showNewVersion = !string.IsNullOrEmpty(ignoreThisVersionKey) && !VIUProjectSettings.HasIgnoreKey(ignoreThisVersionKey) && latestVersion > VIUVersion.current;

            UpdateIgnoredNotifiedSettingsCount(false);

            if (showNewVersion || notifiedSettingsCount > 0)
            {
                TryOpenRecommendedSettingWindow();
            }

            EditorApplication.update -= CheckVersionAndSettings;
        }
Example #53
0
        public int GenerateAllFiles(string folderName, IFolder folder, ProjectFileTreeNode parentNode, IScriptBaseObject thisLevelRootObject, string basePath, bool isTopLevel)
        {
            if (isTopLevel)
            {
                SharedData.IsBusyGenerating = true;
                _Project.StartNewFileGenerationRun();

                // Reset the Template before the File name validation run.
                _Loader.CallTemplateFunction(TemplateHelper.ClearTemplateCacheFunctionName);

                // Run the pre generation template function.

                //var data = new PreGenerationData { OutputFolder = _Project.ProjectSettings.OutputPath };

                //foreach (var uo in _Project.Options.Where(o => o.IsVirtualProperty == false))
                //{
                //    var optionValue = _Loader.GetUserOption(uo.VariableName);
                //    data.UserOptions.Add(uo.VariableName, optionValue);
                //}

                //foreach (var provider in _Project.Providers)
                //{
                //    ArchAngel.Interfaces.ProviderInfo[] otherProviders = new ProviderInfo[_Project.Providers.Count];
                //    _Project.Providers.CopyTo(otherProviders);
                //    data.OtherProviderInfos = otherProviders.ToList();
                //    data.OtherProviderInfos.Remove(provider);
                //    provider.InitialisePreGeneration(data);
                //    //_Loader.CallPreGenerationInitialisationFunction(provider, data);
                //}

                IEnumerable <FilenameInfo> duplicates;
                DuplicateFileNameChecker   checker = new DuplicateFileNameChecker(this, _Project, _Project.ProjectSettings.OutputPath);
                bool validates = checker.ValidateFileNames(folderName, folder, thisLevelRootObject, out duplicates);

                if (validates == false)
                {
                    _ProgressHelper.ReportProgress(100, new GenerateFilesProgress(0, new DuplicateFilesException(duplicates)));
                    return(0);
                }

                // Reset the Template again before the real template run.
                object[] parameters = new object[0];
                _Loader.CallTemplateFunction(TemplateHelper.ClearTemplateCacheFunctionName, ref parameters);

                //foreach (var provider in _Project.Providers)
                //{
                //    _Loader.CallPreGenerationInitialisationFunction(provider, data);
                //}
            }

            if (parentNode == null && isTopLevel)
            {
                addToProjectFileTree = false;
            }

            if (_Loader == null)
            {
                return(0);
            }

            if (addToProjectFileTree && parentNode is ProjectFileTree)
            {
                ((ProjectFileTree)parentNode).TreeRestructuring = true;
                ((ProjectFileTree)parentNode).Clear();
            }
            int fileCount = 0;

            try
            {
                CurrentRootObject = thisLevelRootObject;
                absoluteBasePath  = basePath;

                {
                    Version version         = new Version(_Loader.GetAssemblyVersionNumber());
                    Version expectedVersion = new Version(1, 1, 9, 49);
                    if (version < expectedVersion)
                    {
                        throw new OldVersionException("The template was compiled with an old version of ArchAngel, and cannot be used in this version of Workbench");
                    }
                }

                foreach (IFolder subFolder in folder.SubFolders)
                {
                    if (_ProgressHelper.IsCancellationPending())
                    {
                        _ProgressHelper.Cancel();
                        return(fileCount);
                    }

                    ProjectFileTreeNode folderNode = null;

                    if (addToProjectFileTree && parentNode != null && subFolder.Name != "ROOT")
                    {
                        folderNode          = parentNode.AddChildNode(subFolder.Name);
                        folderNode.IsFolder = true;
                    }

                    if (!string.IsNullOrEmpty(subFolder.IteratorName))
                    {
                        // The folder has an iterator
                        ProviderInfo provider;
                        Type         iteratorType = _Project.GetIteratorTypeFromProviders(subFolder.IteratorName, out provider);

                        if (_ProgressHelper.IsCancellationPending())
                        {
                            _ProgressHelper.Cancel();
                            return(fileCount);
                        }

                        object[] iteratorObjects;

                        if (thisLevelRootObject == null)
                        {
                            iteratorObjects = provider.GetAllObjectsOfType(iteratorType.FullName).ToArray();
                        }
                        else if (iteratorType.IsInstanceOfType(thisLevelRootObject))
                        {
                            iteratorObjects = new[] { thisLevelRootObject };
                        }
                        else
                        {
                            iteratorObjects = provider.GetAllObjectsOfType(iteratorType.FullName, thisLevelRootObject).ToArray();
                        }

                        if (iteratorObjects != null)
                        {
                            foreach (IScriptBaseObject iteratorObject in iteratorObjects)
                            {
                                if (_ProgressHelper.IsCancellationPending())
                                {
                                    _ProgressHelper.Cancel();
                                    return(fileCount);
                                }

                                CurrentRootObject = iteratorObject;

                                string subFolderName = UpdateScriptName(iteratorObject, subFolder);

                                if (folderNode != null)
                                {
                                    folderNode.Text = subFolderName;
                                }

                                subFolderName = Path.Combine(folderName, subFolderName);

                                fileCount += GenerateAllFiles(subFolderName, subFolder, folderNode, CurrentRootObject, basePath, false);
                            }
                        }
                    }
                    else
                    {
                        // The folder doesn't have an iterator
                        if (_ProgressHelper.IsCancellationPending())
                        {
                            _ProgressHelper.Cancel();
                            return(fileCount);
                        }
                        string subFolderName = UpdateScriptName(null, subFolder);

                        if (folderNode != null)
                        {
                            folderNode.Text = subFolderName;
                        }
                        subFolderName = Path.Combine(folderName, subFolderName);

                        fileCount += GenerateAllFiles(subFolderName, subFolder, folderNode, thisLevelRootObject, basePath, false);
                    }
                }

                foreach (IScript script in folder.Scripts)
                {
                    if (_ProgressHelper.IsCancellationPending())
                    {
                        _ProgressHelper.Cancel();
                        return(fileCount);
                    }
                    fileCount += CreateScriptFile(folderName, script, parentNode);
                }

                foreach (IFile file in folder.Files)
                {
                    if (_ProgressHelper.IsCancellationPending())
                    {
                        _ProgressHelper.Cancel();
                        return(fileCount);
                    }
                    fileCount += CreateStaticFile(folderName, file, parentNode);
                }
            }
            catch (Exception e)
            {
                _ProgressHelper.ReportProgress(100, new GenerateFilesProgress(fileCount, e));
                return(fileCount);
            }
            finally
            {
                if (addToProjectFileTree && parentNode is ProjectFileTree)
                {
                    ((ProjectFileTree)parentNode).TreeRestructuring = false;
                    parentNode.RaiseNodeChangedEvent(parentNode, true);
                }
            }

            if (isTopLevel)
            {
                SharedData.IsBusyGenerating = false;
            }

            _ProgressHelper.ReportProgress(50, new GenerateFilesProgress(fileCount));
            return(fileCount);
        }
        /// <summary>
        /// Main program.
        /// </summary>
        /// <param name="args">Input commandline arguments</param>
        /// <returns>Return code: 0 for correct exit, -1 for unexpected exit</returns>
        static Int32 Main(String[] args)
        {
            // Assumes that in AssemblyInfo.cs, the version is specified as 1.0.* or the like,
            // with only 2 numbers specified;  the next two are generated from the date.
            System.Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            // v.Build is days since Jan. 1, 2000, v.Revision*2 is seconds since local midnight
            Int32 buildYear = new DateTime(v.Build * TimeSpan.TicksPerDay + v.Revision * TimeSpan.TicksPerSecond * 2).AddYears(1999).Year;

            // Begin main code
            //Console.Clear();
            Console.WriteLine("-----------------------------------------------------");
            Console.WriteLine("   TI EMIF2.5 ECC Parity Generator for " + devString);
            Console.WriteLine("   (C) " + buildYear + ", Texas Instruments, Inc.");
            Console.WriteLine("   Ver. " + v.Major + "." + v.Minor.ToString("D2"));
            Console.WriteLine("-----------------------------------------------------");
            Console.Write("\n\n");

            // Parse the input command line parameters
            ProgramCmdParams cmdParams = ParseCmdLine(args);

            if (!cmdParams.valid)
            {
                DispHelp();
                return(-1);
            }

            // Create Reed Solomon ECC Object
            // Usage: ReedSolomonECC(Int32 msgSymbolCnt, Int32 maxCorrectibleErrorCnt, Byte symbolBitWidth)
            ReedSolomonECC rs = new ReedSolomonECC(512, 4, 10);

            // Create binary writer for saving ECC data to output file
            BinaryWriter bw = new BinaryWriter(new FileStream(cmdParams.outputFileName, FileMode.Create, FileAccess.Write));

            // Read input data from file
            Byte[] fileData = FileIO.GetFileData(cmdParams.inputfileName);

            Int32[] subArray = new Int32[512];
            Int32[] parityArray;

            for (int i = 0; i < fileData.Length; i += 512)
            {
                for (int j = 0; j < 512; j++)
                {
                    // Swap order of message data since this is apparently what the hardware does
                    // for its RS calculations
                    subArray[511 - j] = ((i + j) >= fileData.Length) ? (0xFF) : ((Int32)fileData[i + j]);
                }

                // Calculate parity of the message data
                parityArray = rs.GenerateParity(subArray);

                // Prep the parity data and output it to file
                if (cmdParams.verbose)
                {
                    Console.WriteLine("NAND operation #{0}", (i / 512) + 1);
                }
                for (int j = 0; j < 8; j += 2)
                {
                    if (cmdParams.verbose)
                    {
                        Console.WriteLine("\tNAND4BITECC{0} = {1:X8}", (j / 2 + 1), ((parityArray[j + 1] & 0x3FF) << 16) | (parityArray[j] & 0x3FF));
                    }
                    bw.Write(((parityArray[j + 1] & 0x3FF) << 16) | (parityArray[j] & 0x3FF));
                }
            }

            return(0);
        }
Example #55
0
        public static void VA_Init1(dynamic vaProxy)
        {
            Logging.Info("Initialising EDDI VoiceAttack plugin");
            EDDI.FromVA = true;

            try
            {
                GetEddiInstance(ref vaProxy);
                Logging.incrementLogs();
                App.StartRollbar();
                App.ApplyAnyOverrideCulture();
                EDDI.Instance.Start();

                // Set up our event responder
                VoiceAttackResponder.RaiseEvent += (s, theEvent) =>
                {
                    try
                    {
                        eventQueue.Enqueue(theEvent);
                        Thread eventHandler = new Thread(() => dequeueEvent(ref vaProxy))
                        {
                            Name         = "VoiceAttackEventHandler",
                            IsBackground = true
                        };
                        eventHandler.Start();
                        eventHandler.Join();
                    }
                    catch (ThreadAbortException tax)
                    {
                        Thread.ResetAbort();
                        Logging.Debug("Thread aborted", tax);
                    }
                    catch (Exception ex)
                    {
                        Dictionary <string, object> data = new Dictionary <string, object>
                        {
                            { "event", JsonConvert.SerializeObject(theEvent) },
                            { "exception", ex.Message },
                            { "stacktrace", ex.StackTrace }
                        };
                        Logging.Error("VoiceAttack failed to handle event.", data);
                    }
                };

                // Add notifiers for changes in variables we want to react to
                // (we can only use event handlers with classes which are always constructed - nullable objects will be updated via responder events)
                EDDI.Instance.State.CollectionChanged  += (s, e) => setDictionaryValues(EDDI.Instance.State, "state", ref vaProxy);
                SpeechService.Instance.PropertyChanged += (s, e) => setSpeaking(SpeechService.Instance.eddiSpeaking, ref vaProxy);

                CargoMonitor cargoMonitor = (CargoMonitor)EDDI.Instance.ObtainMonitor("Cargo monitor");
                cargoMonitor.InventoryUpdatedEvent += (s, e) =>
                {
                    lock (vaProxyLock)
                    {
                        setCargo(cargoMonitor, ref vaProxy);
                    }
                };

                ShipMonitor shipMonitor = (ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor");
                shipMonitor.ShipyardUpdatedEvent += (s, e) =>
                {
                    lock (vaProxyLock)
                    {
                        setShipValues(shipMonitor?.GetCurrentShip(), "Ship", ref vaProxy);
                        Task.Run(() => setShipyardValues(shipMonitor?.shipyard?.ToList(), ref vaProxy));
                    }
                };

                StatusMonitor statusMonitor = (StatusMonitor)EDDI.Instance.ObtainMonitor("Status monitor");
                statusMonitor.StatusUpdatedEvent += (s, e) =>
                {
                    lock (vaProxyLock)
                    {
                        setStatusValues(statusMonitor?.currentStatus, "Status", ref vaProxy);
                    }
                };

                // Display instance information if available
                if (EDDI.Instance.UpgradeRequired)
                {
                    vaProxy.WriteToLog("Please shut down VoiceAttack and run EDDI standalone to upgrade", "red");
                    string msg = Properties.VoiceAttack.run_eddi_standalone;
                    SpeechService.Instance.Say(((ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor")).GetCurrentShip(), msg, 0);
                }
                else if (EDDI.Instance.UpgradeAvailable)
                {
                    vaProxy.WriteToLog("Please shut down VoiceAttack and run EDDI standalone to upgrade", "orange");
                    string msg = Properties.VoiceAttack.run_eddi_standalone;
                    SpeechService.Instance.Say(((ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor")).GetCurrentShip(), msg, 0);
                }

                if (EDDI.Instance.Motd != null)
                {
                    vaProxy.WriteToLog("Message from EDDI: " + EDDI.Instance.Motd, "black");
                    string msg = String.Format(Eddi.Properties.EddiResources.msg_from_eddi, EDDI.Instance.Motd);
                    SpeechService.Instance.Say(((ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor")).GetCurrentShip(), msg, 0);
                }

                // Set the initial values from the main EDDI objects
                setStandardValues(ref vaProxy);

                vaProxy.WriteToLog("The EDDI plugin is fully operational.", "green");
                setStatus(ref vaProxy, "Operational");

                // Fire an event once the VA plugin is initialized
                Event @event = new VAInitializedEvent(DateTime.UtcNow);

                if (initEventEnabled(@event.type))
                {
                    EDDI.Instance.enqueueEvent(@event);
                }

                // Set a variable indicating the version of VoiceAttack in use
                System.Version v = vaProxy.VAVersion;
                EDDI.Instance.vaVersion = v.ToString();

                // Set a variable indicating whether EDDI is speaking
                try
                {
                    setSpeaking(SpeechService.Instance.eddiSpeaking, ref vaProxy);
                }
                catch (Exception ex)
                {
                    Logging.Error("Failed to set initial speaking status", ex);
                }
                Logging.Info("EDDI VoiceAttack plugin initialization complete");
            }
            catch (Exception e)
            {
                Logging.Error("Failed to initialize VoiceAttack plugin", e);
                vaProxy.WriteToLog("Unable to fully initialize EDDI. Some functions may not work.", "red");
            }
        }
Example #56
0
    private void Awake()
    {
        // Only allow one instance at runtime.
        if (instance != null)
        {
            enabled = false;
            DestroyImmediate(this);
            return;
        }

        instance = this;

        System.Version netVersion = OVRPlugin.wrapperVersion;
        System.Version ovrVersion = OVRPlugin.version;

        Debug.Log("Unity v" + Application.unityVersion + ", " +
                  "Oculus Integration v" + netVersion + ", " +
                  "OVRPlugin v" + ovrVersion + ".");

        // Detect whether this platform is a supported platform
        RuntimePlatform currPlatform = Application.platform;

        isSupportedPlatform |= currPlatform == RuntimePlatform.Android;
        isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer;
        isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor;
        isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer;
        isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor;
        isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer;
        if (!isSupportedPlatform)
        {
            Debug.LogWarning("This platform is unsupported");
            return;
        }

#if !UNITY_ANDROID || UNITY_EDITOR
        if (OVRUnityVersionChecker.hasBuiltInVR)
        {
            Debug.LogWarning("The Oculus Unity Legacy Integration is only supported in Unity 4.x releases. For Unity 5.x, please migrate to the Oculus Utilities for Unity package and use Unity's built-in VR support (available in Unity 5.1 and later).");
            isVRPresent = false;
        }
        else if (!ovrIsInitialized)
        {
            //HACK: For some reason, Unity doesn't call UnitySetGraphicsDevice until we make the first P/Invoke call.
            OVRPluginEvent.eventBase = OVRPluginEvent.eventBase;

#if !UNITY_ANDROID || UNITY_EDITOR
            //Handle all log messages
            OVR_FlushLog(OnLogMessage);
#endif

            // If unable to load the Oculus Runtime.
            if (!OVRPlugin.initialized)
            {
                bool isBadWinRenderer =
                    ((Application.platform == RuntimePlatform.WindowsEditor ||
                      Application.platform == RuntimePlatform.WindowsPlayer) &&
                     !SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11"));

                if (isBadWinRenderer)
                {
                    Debug.LogWarning("Only D3D11 is supported on Windows.");
                }
                else
                {
                    Debug.LogWarning("Runtime is not present or no Rift attached. Running without VR.");
                }

                // Runtime is not installed if ovr_Initialize() fails.
                isVRPresent = false;
                // Go monoscopic in response.
                monoscopic = true;
            }
            else
            {
                OVRPluginEvent.Issue(RenderEventType.InitRenderThread);

                isVRPresent = true;

#if UNITY_EDITOR
                if (!OVRUnityVersionChecker.hasEditorVRSupport)
                {
                    // Only allow VR in standalones.
                    isVRPresent = false;
                    Debug.LogWarning("VR rendering is not supported in the editor. Please update to 4.6.7p4 or build a stand-alone player.");
                }
#endif
                if (netVersion.Major > ovrVersion.Major || netVersion.Major == ovrVersion.Major && netVersion.Minor > ovrVersion.Minor)
                {
                    isVRPresent = false;
                    Debug.LogWarning("Version check failed. Please make sure you are using OVRPlugin " +
                                     Ovr.Hmd.OVR_VERSION_STRING + " or newer.");
                }

                OVRPlugin.queueAheadFraction = 0f;

                ovrIsInitialized = true;
            }
        }

        SetEditorPlay(Application.isEditor);
#else // UNITY_ANDROID && !UNITY_EDITOR: Start of Android init.
        // Android integration does not dynamically load its runtime.
        isVRPresent = true;

        // log the unity version
        Debug.Log("Unity Version: " + Application.unityVersion);

        // don't allow the application to run if orientation is not landscape left.
        if (Screen.orientation != ScreenOrientation.LandscapeLeft)
        {
            Debug.LogError("********************************************************************************\n");
            Debug.LogError("***** Default screen orientation must be set to landscape left for VR.\n" +
                           "***** Stopping application.\n");
            Debug.LogError("********************************************************************************\n");

            Debug.Break();
            Application.Quit();
        }

        // don't enable gyro, it is not used and triggers expensive display calls
        if (Input.gyro.enabled)
        {
            Debug.LogError("*** Auto-disabling Gyroscope ***");
            Input.gyro.enabled = false;
        }

        // NOTE: On Adreno Lollipop, it is an error to have antiAliasing set on the
        // main window surface with front buffer rendering enabled. The view will
        // render black.
        // On Adreno KitKat, some tiling control modes will cause the view to render
        // black.
        if (QualitySettings.antiAliasing > 1)
        {
            Debug.LogError("*** Antialiasing must be disabled for Gear VR ***");
        }

        // we sync in the TimeWarp, so we don't want unity
        // syncing elsewhere
        QualitySettings.vSyncCount = 0;

        // try to render at 60fps
        Application.targetFrameRate = 60;
        // don't allow the app to run in the background
        Application.runInBackground = false;
        // Disable screen dimming
        Screen.sleepTimeout = SleepTimeout.NeverSleep;

        if (!androidJavaInit)
        {
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            activity = unityPlayer.GetStatic <AndroidJavaObject>("currentActivity");
            // Prepare for the RenderThreadInit()
            SetInitVariables(activity.GetRawObject(), System.IntPtr.Zero);

#if USE_ENTITLEMENT_CHECK
            AndroidJavaObject entitlementChecker = new AndroidJavaObject("com.oculus.svclib.OVREntitlementChecker");
            entitlementChecker.CallStatic("doAutomatedCheck", activity);
#else
            Debug.Log("Inhibiting Entitlement Check!");
#endif

            androidJavaInit = true;
        }

        // We want to set up our touchpad messaging system
        OVRTouchpad.Create();

        InitVolumeController();

        // set an event delegate like this if you wish to handle events like "reorient".
        //SetVrApiEventDelegate( VrApiEventDefaultDelegate );
#endif // End of android init.

        prevEyeTextureAntiAliasing = OVRManager.instance.eyeTextureAntiAliasing;
        prevEyeTextureDepth        = OVRManager.instance.eyeTextureDepth;
        prevEyeTextureFormat       = OVRManager.instance.eyeTextureFormat;
        prevNativeTextureScale     = OVRManager.instance.nativeTextureScale;
        prevVirtualTextureScale    = OVRManager.instance.virtualTextureScale;
        prevMonoscopic             = OVRManager.instance.monoscopic;
        prevHdr = OVRManager.instance.hdr;

        if (tracker == null)
        {
            tracker = new OVRTracker();
        }

        if (display == null)
        {
            display = new OVRDisplay();
        }
        else
        {
            wasRecreated = true;
        }

        if (input == null)
        {
            input = new OVRInput();
        }

        if (resetTrackerOnLoad)
        {
            display.RecenterPose();
        }

#if !UNITY_ANDROID || UNITY_EDITOR
        // Except for D3D9, SDK rendering forces vsync unless you pass ovrHmdCap_NoVSync to Hmd.SetEnabledCaps().
        if (timeWarp)
        {
            bool useUnityVSync = SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9");
            QualitySettings.vSyncCount      = useUnityVSync ? 1 : 0;
            QualitySettings.maxQueuedFrames = 0;
        }
#endif

#if UNITY_STANDALONE_WIN
        if (!OVRUnityVersionChecker.hasD3D9ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9"))
        {
            MessageBox(0, "Direct3D 9 extended mode is not supported in this configuration. "
                       + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version."
                       , "VR Configuration Warning", 0);
        }

        if (!OVRUnityVersionChecker.hasD3D11ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11"))
        {
            MessageBox(0, "Direct3D 11 extended mode is not supported in this configuration. "
                       + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version."
                       , "VR Configuration Warning", 0);
        }
#endif
    }
Example #57
0
 private ModInfo(String guid, System.Version version, ConfigData configData)
 {
     this.guid       = guid;
     this.version    = version;
     this.configData = configData;
 }
Example #58
0
        public static System.Version GetVersionProperty(TestContext context, string parameter, System.Version defaultValue)
        {
            string value = (string)context.Properties[parameter];

            if (value == null)
            {
                return(defaultValue);
            }
            return(System.Version.Parse(value));
        }
Example #59
0
        public System.Version Versionize(bool dryrun                       = false,
                                         bool skipDirtyCheck               = false,
                                         bool skipCommit                   = false,
                                         string releaseVersion             = null,
                                         bool ignoreInsignificant          = false,
                                         bool includeAllCommitsInChangelog = false)
        {
            var workingDirectory = _directory.FullName;

            using (var repo = new Repository(workingDirectory))
            {
                var isDirty = repo.RetrieveStatus(new StatusOptions()).IsDirty;

                if (!skipDirtyCheck && isDirty)
                {
                    Exit($"Repository {workingDirectory} is dirty. Please commit your changes.", 1);
                }

                var projects = Projects.Discover(workingDirectory);

                if (projects.IsEmpty())
                {
                    Exit($"Could not find any projects files in {workingDirectory} that have a <Version> defined in their csproj file.", 1);
                }

                if (projects.HasInconsistentVersioning())
                {
                    Exit($"Some projects in {workingDirectory} have an inconsistent <Version> defined in their csproj file. Please update all versions to be consistent or remove the <Version> elements from projects that should not be versioned", 1);
                }

                Information($"Discovered {projects.GetProjectFiles().Count()} versionable projects");
                foreach (var project in projects.GetProjectFiles())
                {
                    Information($"  * {project}");
                }

                var versionTag       = repo.SelectVersionTag(projects.Version);
                var commitsInVersion = repo.GteCommitsSinceLastVersion(versionTag);

                var commitParser        = new ConventionalCommitParser();
                var conventionalCommits = commitParser.Parse(commitsInVersion);

                var versionIncrement = VersionIncrementStrategy.CreateFrom(conventionalCommits);

                var nextVersion = versionTag == null ? projects.Version : versionIncrement.NextVersion(projects.Version, ignoreInsignificant);

                if (ignoreInsignificant && nextVersion == projects.Version)
                {
                    Exit($"Version was not affected by commits since last release ({projects.Version}), since you specified to ignore insignificant changes, no action will be performed.", 0);
                }

                if (!string.IsNullOrWhiteSpace(releaseVersion))
                {
                    try
                    {
                        nextVersion = new System.Version(releaseVersion);
                    }
                    catch (Exception)
                    {
                        Exit($"Could not parse the specified release version {releaseVersion} as valid version", 1);
                    }
                }

                var versionTime = DateTimeOffset.Now;

                // Commit changelog and version source
                if (!dryrun && (nextVersion != projects.Version))
                {
                    projects.WriteVersion(nextVersion);

                    foreach (var projectFile in projects.GetProjectFiles())
                    {
                        Commands.Stage(repo, projectFile);
                    }
                }

                Step($"bumping version from {projects.Version} to {nextVersion} in projects");

                var changelog = Changelog.Discover(workingDirectory);

                if (!dryrun)
                {
                    var changelogLinkBuilder = ChangelogLinkBuilderFactory.CreateFor(repo);
                    changelog.Write(nextVersion, versionTime, changelogLinkBuilder, conventionalCommits, includeAllCommitsInChangelog);
                }

                Step($"updated CHANGELOG.md");

                if (!dryrun && !skipCommit)
                {
                    Commands.Stage(repo, changelog.FilePath);

                    foreach (var projectFile in projects.GetProjectFiles())
                    {
                        Commands.Stage(repo, projectFile);
                    }
                }

                if (!dryrun && !skipCommit)
                {
                    var author    = repo.Config.BuildSignature(versionTime);
                    var committer = author;

                    // TODO: Check if tag exists before commit
                    var releaseCommitMessage = $"chore(release): {nextVersion}";
                    var versionCommit        = repo.Commit(releaseCommitMessage, author, committer);
                    Step($"committed changes in projects and CHANGELOG.md");

                    repo.Tags.Add($"v{nextVersion}", versionCommit, author, $"{nextVersion}");
                    Step($"tagged release as {nextVersion}");

                    Information("");
                    Information($"i Run `git push --follow-tags origin master` to push all changes including tags");
                }
                else if (skipCommit)
                {
                    Information("");
                    Information($"i Commit and tagging of release was skipped. Tag this release as `v{nextVersion}` to make versionize detect the release");
                }

                return(nextVersion);
            }
        }
        public static IEnumerable <Commit> GetCommitsFromVersion(LibGit2Context context, Version version)
        {
            Requires.NotNull(context, nameof(context));
            Requires.NotNull(version, nameof(version));

            var tracker         = new GitWalkTracker(context);
            var possibleCommits = from commit in GetCommitsReachableFromRefs(context.Repository)
                                  let commitVersionOptions = tracker.GetVersion(commit)
                                                             where commitVersionOptions is not null
                                                             where !IsCommitIdMismatch(version, commitVersionOptions, commit)
                                                             where !IsVersionHeightMismatch(version, commitVersionOptions, commit, tracker)
                                                             select commit;

            return(possibleCommits);
        }