Exemplo n.º 1
0
 public MethodsGenerator(GeneratorData data, Translator translator, CodeTypeDeclaration type, Smoke.Class *klass)
 {
     this.data       = data;
     this.translator = translator;
     this.type       = type;
     this.smokeClass = klass;
 }
Exemplo n.º 2
0
        public async Task Serialize()
        {
            if (!Directory.Exists(Application.streamingAssetsPath))
            {
                Directory.CreateDirectory(Application.streamingAssetsPath);
            }
            var        data = new GeneratorData(this);
            FileStream fs   = null;
            var        sw   = System.Diagnostics.Stopwatch.StartNew();

            serializing = true;
            try
            {
                fs = new FileStream(Application.streamingAssetsPath + "/" + SceneManager.GetActiveScene().name + "_" + gameObject.name + ".nodes", FileMode.Create, FileAccess.Write, FileShare.None, 128000);
                await Task.Run(() => MessagePackSerializer.SerializeAsync(fs, data, options));

                //MessagePackSerializer.Serialize(fs, data, options);
            }
            catch (System.Exception e)
            {
                print(e);
            }
            finally
            {
                fs?.Close();
                serializing = false;
                print("Saved, " + sw.Elapsed.TotalSeconds + "s");
                sw.Stop();
            }
        }
Exemplo n.º 3
0
    public override void Load(ObjectData dataToUse)
    {
        base.Load(dataToUse);

        GeneratorData data = (GeneratorData)dataToUse;

        blackout       = data.blackout;
        totalPower     = data.totalPower;
        availablePower = data.availablePower;
        connected      = new List <Electronic>();

        //Grab the references from their positions
        for (int i = 0; i < data.connected.Count; i++)
        {
            Vector3Int pos = Vector3Int.FloorToInt(data.connected[i]) - GameManager.manager.tileManager.worldOrigin;
            if (GameManager.manager.tileManager.utilityObjects[pos.x, pos.y] != null)
            {
                connected.Add(GameManager.manager.tileManager.utilityObjects[pos.x, pos.y].GetComponent <Electronic>());
            }
            else
            {
                connected.Add(GameManager.manager.tileManager.objects[pos.x, pos.y].GetComponent <Electronic>());
            }
        }
    }
Exemplo n.º 4
0
    public PropertyGenerator(GeneratorData data, Translator translator, Dictionary <CodeTypeDeclaration, List <string> > documentation)
    {
        this.data = data;

        this.translator    = translator;
        this.documentation = documentation;
    }
Exemplo n.º 5
0
    //Get all the generator data for a given block type
    public virtual GeneratorData[] getBlockGenerationData(BlockType blockType)
    {
        //If the block isn't used to generate features in the biome, return null
        if (!blockTypes.Contains(blockType))
        {
            return(null);
        }
        //Make an empty list of all the generator data that the block has
        List <GeneratorData> generatorData = new List <GeneratorData>();

        //Iterate over all blocks that the biome generates for
        for (int i = 0; i < blockTypes.Count; i++)
        {
            //Get the block type that is generated for
            BlockType type = blockTypes[i];
            //If this blockType is the blockType we are looking for, add it's generatorData to the list
            if (type == blockType)
            {
                GeneratorData blockData = blockGeneratorData[i];
                generatorData.Add(blockData);
            }
        }
        //return the list of generator data as an array
        return(generatorData.ToArray());
    }
Exemplo n.º 6
0
 static void dumpGenerator(GeneratorData gd)
 {
     Console.WriteLine("			,'generator': {");
     Console.WriteLine("				'ArpChord': '"+ gd.ArpChord + "'");
     Console.WriteLine("				,'ArpDir': '"+ gd.ArpDir + "'");
     Console.WriteLine("				,'ArpGate': '"+ gd.ArpGate + "'");
     Console.WriteLine("				,'ArpRange': '"+ gd.ArpRange + "'");
     Console.WriteLine("				,'ArpRepeat': '"+ gd.ArpRepeat + "'");
     Console.WriteLine("				,'ArpSlide': '"+ gd.ArpSlide + "'");
     Console.WriteLine("				,'ArpTime': '"+ gd.ArpTime + "'");
     Console.WriteLine("				,'BaseNote': '"+ gd.BaseNote + "'");
     Console.WriteLine("				,'GeneratorName': '"+ gd.GeneratorName + "'");
     Console.WriteLine("				,'Insert': '"+ gd.Insert + "'");
     Console.WriteLine("				,'LayerParent': '"+ gd.LayerParent + "'");
     Console.WriteLine("				,'Panning': '"+ gd.Panning + "'");
     dumpPlugin(gd.Plugin);
     Console.WriteLine("				,'PluginSettings': '"+ gd.PluginSettings + "'");
     Console.WriteLine("				,'SampleAmp': '"+ gd.SampleAmp + "'");
     Console.WriteLine("				,'SampleFileName': '"+ gd.SampleFileName + "'");
     Console.WriteLine("				,'SampleReversed': '"+ gd.SampleReversed + "'");
     Console.WriteLine("				,'SampleReverseStereo': '"+ gd.SampleReverseStereo + "'");
     Console.WriteLine("				,'SampleUseLoopPoints': '"+ gd.SampleUseLoopPoints + "'");
     Console.WriteLine("				,'Volume ': '"+ gd.Volume + "'");
     Console.WriteLine("				}");
 }
Exemplo n.º 7
0
        public VirtualMachine(GeneratorData data, VariablesStatusLog variablesStatusLog)
            : base(null, data)
        {
            Machine         = new List <Machine>();
            variablesStatus = variablesStatusLog;

            foreach (IBasicGlobal ibg in Data.GlobalObjects)
            {
                switch (ibg)
                {
                case BasicObjectsTree tree:
                    Machine.Add(new MachineStatus(Data, tree, tree));
                    Data.Store[Util.CounterName(tree.Name)] = 0;
                    foreach (BasicMachine mach in tree.SuperStatesList())
                    {
                        Data.Store[Util.CounterName(mach.Name)] = 0;
                    }
                    break;

                case BasicRelation bindir:
                    Machine.Add(new MachineRelation(Data, bindir));
                    break;

                case BasicEquation beq:
                    Machine.Add(new MachineEquation(Data, beq));
                    break;
                }
            }
        }
Exemplo n.º 8
0
    public static int[,,] GenerateGameBoard(GeneratorData _data)
    {
        int[,,] matrix = new int[_data.LengthX, _data.LengthY, _data.LengthZ];

        //Игровое поле, объекты
        for (int x = 0; x < _data.LengthX; x++)
        {
            for (int y = 0; y < _data.LengthY; y++)
            {
                for (int z = 0; z < _data.LengthZ; z++)
                {
                    float random = Random.Range(0.0f, 100.0f);

                    if (random <= _data.PercentBox)
                    {
                        random = (float)EnumSpaceObject.Box;
                    }

                    /*else if (random <= percentCube + percentEnemies + (countSectors / 100.0f))
                     *  random = (float)EnumSpaceObject.Enemy;*/
                    else
                    {
                        random = (float)EnumSpaceObject.Void;
                    }

                    matrix[x, y, z] = random.ToInt();
                }
            }
        }

        return(matrix);
    }
Exemplo n.º 9
0
 public PropertyGenerator(GeneratorData data, Translator translator, Documentation documentation)
 {
     this.data = data;
     this.translator = translator;
     this.documentation = documentation;
     this.PropertyMethods = new List<IntPtr>();
 }
Exemplo n.º 10
0
        public GeneratorInfo(GeneratorInfoSave save, GeneratorData data, GeneratorLocalData localData)
        {
            save.Guard();
            this.Data                = data;
            this.LocalData           = localData;
            this.GeneratorId         = save.generatorId;
            this.IsResearched        = save.isResearched;
            this.IsEnhanced          = save.isEnhanced;
            this.GenerateTimer       = save.generateTimer;
            this.isGenerationStarted = save.isGenerationStarted;
            this.IsAutomatic         = save.isAutomatic;
            this.State               = (GeneratorState)save.state;
            this.BuyCountButtonState = save.buyCountButtonState;
            this.ProfitBoosts.Load(save.profitBoosts);
            this.TimeBoosts.Load(save.timeBoosts);

            if (GeneratorId.IsRickshawOrTaxi())
            {
                IsResearched = true;
            }
            if (IsEnhanced)
            {
                AddTimeBoost(BoostInfo.CreateTemp(kEnhanceBoostName, 10));
            }
        }
Exemplo n.º 11
0
        public override void LoadSave(object obj)
        {
            try {
                GenerationServiceSave save = obj as GenerationServiceSave;

                if (save != null)
                {
                    save.Guard();

                    if (save.generators != null)
                    {
                        Generators.ClearGenerators();
                        foreach (var item in save.generators)
                        {
                            GeneratorData      generatorData = Services.ResourceService.Generators.GetGeneratorData(item.generatorId);
                            GeneratorLocalData localData     = Services.ResourceService.GeneratorLocalData.GetLocalData(item.generatorId);
                            Generators.AddGeneratorInner(new GeneratorInfo(item, generatorData, localData));
                        }
                    }

                    Generators.ProfitBoosts.Load(save.profitSave);
                    Generators.TimeBoosts.Load(save.timeSave);
                    IsLoaded = true;
                }
                else
                {
                    LoadDefaults();
                }
            } catch (Exception exception) {
                UnityEngine.Debug.LogException(exception);
                LoadDefaults();
            }
        }
Exemplo n.º 12
0
        public ManagerInfo GetManager(int id)
        {
            ManagerData   managerData   = GameServices.Instance.ResourceService.Managers.GetManagerData(id);
            GeneratorData generatorData = GameServices.Instance.ResourceService.Generators.GetGeneratorData(id);

            return(new ManagerInfo(managerData, generatorData));
        }
Exemplo n.º 13
0
        public async Task Deserialize()
        {
            FileStream    fs   = null;
            GeneratorData data = null;

            deserializing = true;

            var sw = System.Diagnostics.Stopwatch.StartNew();

            try
            {
                if (Application.platform == RuntimePlatform.Android)
                {
                    UnityWebRequest www = new UnityWebRequest(Application.streamingAssetsPath + "/" + SceneManager.GetActiveScene().name + "_" + gameObject.name + ".nodes")
                    {
                        downloadHandler = new DownloadHandlerBuffer()
                    };
                    www.SendWebRequest();
                    while (!www.isDone)
                    {
                        await Task.Delay(10);
                    }
                    data = MessagePackSerializer.Deserialize <GeneratorData>(www.downloadHandler.data, options);
                }
                else
                {
                    fs   = new FileStream(Application.streamingAssetsPath + "/" + SceneManager.GetActiveScene().name + "_" + gameObject.name + ".nodes", FileMode.Open, FileAccess.Read, FileShare.None, 128000);
                    data = await Task.Run(() => MessagePackSerializer.DeserializeAsync <GeneratorData>(fs, options)).Result;

                    //data = MessagePackSerializer.Deserialize<GeneratorData>(fs, options);
                }
            }
            catch
            {
                //print(e);
            }
            finally
            {
                fs?.Close();
                deserializing = false;
                if (data != null)
                {
                    print("Loaded, " + sw.Elapsed.TotalSeconds + "s");
                    sw.Restart();
                    for (int i = 0; i < data.chunkData.Length; i++)
                    {
                        chunks[i].Deserialize(data.chunkData[i]);
                    }
                    if (pathfindingType != PathfindingType.navmeshOnly)
                    {
                        MarchCubes();
                    }
                    AssignNeighbours();
                    print("Init, " + sw.Elapsed.TotalSeconds);
                    sw.Stop();
                    OnInitialize?.Invoke();
                }
            }
        }
Exemplo n.º 14
0
 public IEnumerable <MemberDeclarationSyntax> Apply(GeneratorData item)
 {
     if (item is not RequestItem requestItem)
     {
         yield break;
     }
     if (requestItem is not {
         LspAttributes : { Resolver : { } }
     })
Exemplo n.º 15
0
        //public void UpdateData(GeneratorData data ) {
        //    Data = data;
        //}

        #region constructors


        public GeneratorInfo(GeneratorData data, GeneratorLocalData localData)
        {
            this.GeneratorId    = data.Id;
            IsEnhanced          = false;
            Data                = data;
            LocalData           = localData;
            GenerateTimer       = 0f;
            BuyCountButtonState = 1;
            IsResearched        = GeneratorId.IsRickshawOrTaxi();
        }
Exemplo n.º 16
0
    public static void SaveGenerator(GameObject generator)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string          path      = Application.persistentDataPath + "/" + generator.name + ".orb";
        FileStream      stream    = new FileStream(path, FileMode.Create);

        GeneratorData data = new GeneratorData(generator);

        formatter.Serialize(stream, data);
        stream.Close();
    }
Exemplo n.º 17
0
 public IEnumerable <MemberDeclarationSyntax> Apply(GeneratorData item)
 {
     return(item.JsonRpcAttributes.RequestProxies
            .Select(
                registry => new ExtensionMethodContext(
                    item.JsonRpcAttributes.GenerateRequestMethods !.Data, item.TypeDeclaration, item.TypeSymbol, registry, item.JsonRpcAttributes.RequestProxies,
                    item.Context
                    )
     {
         IsProxy = true
     }
Exemplo n.º 18
0
        public void getRecordsTest()
        {
            //Arrange
            string        appDataPath = Environment.CurrentDirectory;
            GeneratorData gd          = new GeneratorData(appDataPath);

            //Act
            List <Addres> adr = gd.getRecords(56);

            //Assert
            Assert.AreEqual(adr.Count, 56);
        }
Exemplo n.º 19
0
        public void Execute(object parameter)
        {
            AddGeneratorView view = new AddGeneratorView();
            var dataContext       = new GeneratorData(_solutionDirectory);

            view.DataContext = dataContext;

            if (view.ShowDialog() == true)
            {
                _viewModel.ConfigData.Generators.Add(dataContext);
            }
        }
Exemplo n.º 20
0
        public void getOneRecordTest()
        {
            //Arrange
            string        appDataPath = Environment.CurrentDirectory;
            GeneratorData gd          = new GeneratorData(appDataPath);

            //Act
            Addres adr = gd.getOneRecord();

            //Assert
            Assert.IsNotNull(adr);
        }
Exemplo n.º 21
0
        public void getRecordsTestToStreet()
        {
            //Arrange
            string        appDataPath = Environment.CurrentDirectory;
            GeneratorData gd          = new GeneratorData(appDataPath);

            //Act
            List <Addres> adr = gd.getRecords(2);

            //Assert
            Assert.AreNotEqual(adr[1].Street, "");
        }
Exemplo n.º 22
0
        internal CottleEditor(string rootPath, string source, string destFile, RenderingContext context)
        {
            RootPath = rootPath;
            Context  = context;
            Data     = context.Objects.Data;
            Source   = source;
            DestFile = destFile;
            project  = new Project(Data, RootPath);

            InitializeComponent();

            dualTextBox1.SourceFormat.Color = Color.DarkGreen;
            dualTextBox1.SourceFormat.Style = FontStyle.Regular;

            // Declaring and intializing object of Type
            Type objType = typeof(MacroTokens);

            //string[] macros_keywords = { "Project", "Machine" };
            string[] macros_keywords = typeof(MacroTokens)
                                       .GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
                                       .ToList()
                                       .FindAll(fi => !fi.IsLiteral && fi.IsInitOnly)
                                       .ConvertAll(fi => ((MacroToken)fi.GetValue(null)).Name.Replace("(", ""))
                                       .ToArray();

            var macros = dualTextBox1.SourceFormat.AddGroup("macros", Data.Profile.Properties.MacroBegin + @"([A-Za-z]+\(?)|" + Data.Profile.Properties.MacroBegin + @"\)", Color.Brown, FontStyle.Bold, false);

            macros.AddKeywords(macros_keywords, Color.Brown, FontStyle.Bold | FontStyle.Italic);

            string[] cottle_keywords  = { "echo", "if", "for", "set", "while", "dump" };
            string[] cottle_functions = { "and",  "cmp",    "default", "defined", "eq",  "ge",    "gt",    "has",   "le",  "lt",  "ne",  "not",  "or",    "xor", "when",
                                          "abs",  "add",    "ceil",    "cos",     "div", "floor", "max",   "min",   "mod", "mul", "pow", "rand", "round", "sin", "sub",
                                          "char", "format", "lcase",   "match",   "ord", "split", "token", "ucase",
                                          "cast", "type",   "call" };

            var cottle_code = dualTextBox1.SourceFormat.AddGroup("cottle", @"\{\{[^:\n]*:|\{\{[^\}:]*\}\}|\}\}", Color.Black, FontStyle.Regular);

            cottle_code.AddKeywords(cottle_keywords, Color.Blue, FontStyle.Bold);
            cottle_code.AddKeywords(cottle_functions, Color.Brown, FontStyle.Bold);

            string[] c_keywords = { "typedef", "void", "union", "static", "enum", "const", "extern", "int", "short", "char", "bool", "unsigned", "signed", "long" };
            dualTextBox1.ResultFormat.AddGroup("macro_processor", @"^#\w+", Color.Brown, FontStyle.Bold);
            dualTextBox1.ResultFormat.AddGroup("doc", @"\/\*\*(\*(?!\/)|[^*])*\*\/", Color.SteelBlue, FontStyle.Regular);
            dualTextBox1.ResultFormat.AddGroup("line_comment", @"\/\/[^\n\r]+?(?:\*\)|[\n\r])", Color.Green, FontStyle.Regular);
            dualTextBox1.ResultFormat.AddKeywords(c_keywords, Color.Blue, FontStyle.Bold);

            dualTextBox1.ProcessText += DualTextBox1_ProcessText;
            dualTextBox1.SetText(File.ReadAllText(Source));

            lbScriptName.Text = Path.GetFileName(source);
            lbFileName.Text   = destFile;
        }
Exemplo n.º 23
0
 public Translator(GeneratorData data, IEnumerable <ICustomTranslator> customTranslators)
 {
     this.data = data;
     foreach (ICustomTranslator translator in customTranslators)
     {
         this.typeMap.AddRange(translator.TypeMap);
         this.typeStringMap.AddRange(translator.TypeStringMap);
         this.typeCodeMap.AddRange(translator.TypeCodeMap);
         this.InterfaceClasses.AddRange(translator.InterfaceClasses);
         this.ExcludedMethods.AddRange(translator.ExcludedMethods);
         this.NamespacesAsClasses.AddRange(translator.NamespacesAsClasses);
     }
 }
Exemplo n.º 24
0
    public static GeneratorData createGeneratorData(GeneratorType type)
    {
        ItemQuality quality = randQuality();
        float       level   = randLevel();

        int maxEnergy = Mathf.RoundToInt(type.maxEnergy() * level * qualityMultiplier(quality));

        GeneratorData data = new GeneratorData(quality, level, type, maxEnergy);

        data.initCommons(calculateCost(data), calculateEnergy(data));

        return(data);
    }
Exemplo n.º 25
0
    public int addGenerator(ushort _itemId)
    {
        // when we create a new generator, it should claim a space in the endStates array as indicated by the index 'generators[i].idxInOutputStateArray'.
        int ret = generatorCount;

        generatorCount++;
        //generators.Add(new GeneratorData());
        GeneratorData gen = generators[ret];

        gen.init(_itemId, 2f, 9999);
        gen.start();
        generators[ret] = gen;
        return(ret);
    }
Exemplo n.º 26
0
 internal CodeGeneratorConfig(GeneratorData generatorData, string configPath = "")
 {
     gData = generatorData;
     InitializeComponent();
     if (!string.IsNullOrEmpty(configPath))
     {
         string filePath = Path.Combine(configPath, "cottle.ini");
         if (File.Exists(filePath))
         {
             LoadConfiguration(filePath);
         }
     }
     treeView.NodeMouseClick += (sender, args) => treeView.SelectedNode = args.Node;
 }
        public void Initialize(IncrementalGeneratorInitializationContext context)
        {
            var _attributes    = "GenerateHandler,GenerateRequestMethods,GenerateHandlerMethods";
            var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider(
                (syntaxNode, _) =>
                syntaxNode is TypeDeclarationSyntax tds
                and(ClassDeclarationSyntax or RecordDeclarationSyntax or InterfaceDeclarationSyntax) &&
                tds.AttributeLists.ContainsAttribute(_attributes), (syntaxContext, _) => syntaxContext
                )
                                 .Combine(context.CompilationProvider)
                                 .Select(
                (tuple, _) =>
            {
                var(syntaxContext, compilaiton) = tuple;
                var additionalUsings            = new HashSet <string>
                {
                    "System",
                    "System.Collections.Generic",
                    "System.Threading",
                    "System.Threading.Tasks",
                    "MediatR",
                    "Microsoft.Extensions.DependencyInjection"
                };

                GeneratorData?actionItem = null;
                Diagnostic?diagnostic    = null;

                try
                {
                    actionItem = GeneratorData.Create(
                        compilaiton, (TypeDeclarationSyntax)syntaxContext.Node, syntaxContext.SemanticModel, additionalUsings
                        );
                }
                catch (Exception e)
                {
                    diagnostic = Diagnostic.Create(
                        GeneratorDiagnostics.Exception, syntaxContext.Node.GetLocation(), e.Message,
                        e.StackTrace ?? string.Empty
                        );
                    Debug.WriteLine(e);
                    Debug.WriteLine(e.StackTrace);
                }

                return(actionItem, diagnostic, additionalUsings);
            }
                );

            context.RegisterSourceOutput(syntaxProvider, GenerateHandlerMethods);
            context.RegisterSourceOutput(
                syntaxProvider.Where(z => z.actionItem is { }).SelectMany((z, _) => z.actionItem !.AssemblyJsonRpcHandlersAttributeArguments).Collect(),
Exemplo n.º 28
0
        private double GeneratorUnitBuyKoefficient(GeneratorData data)
        {
            //UnityEngine.Debug.Log($"current planet => {Services.PlanetService.CurrentPlanet.Id} generator increment factor => {data.IncrementFactor}");
            double buyKoeff = (PlanetService?.CurrentPlanet?.Data?.TransportUnityPriceMult ?? 1.0) * data.IncrementFactor;

            //UnityEngine.Debug.Log($"GeneratorUnitBuyCoefficitent(), transport unit mult ={Services.PlanetService.CurrentPlanet.Data.TransportUnityPriceMult}," +
            //$"coef => {buyKoeff}");

            //only for debug output
            //if (data.Id == 0 ) {
            //    UDebug.Log($"GeneratorUnitBuyKoefficient() => planet coeff {Planets.CurrentPlanet.Data.TransportUnityPriceMult} * gen increment factor: {data.IncrementFactor}, result: {Planets.CurrentPlanet.Data.TransportUnityPriceMult * data.IncrementFactor}");
            //}
            return(buyKoeff);
        }
Exemplo n.º 29
0
    public static Vector3Int GeneratePlayerPosition(GeneratorData _data)
    {
        var result = new Vector3Int();

        int halfX   = _data.LengthX / 2;
        int halfY   = _data.LengthY / 2;
        int beyondZ = ConstantsGameSettings.BEYOND_BORDERS.ToInt();

        int playerX = Random.Range(halfX - 2, halfX + 3);
        int playerY = Random.Range(halfY - 2, halfY + 3);
        int playerZ = Random.Range(-Mathf.Max(beyondZ - 2, 4), (int)-3);

        result.Set(playerX, playerY, playerZ);
        return(result);
    }
Exemplo n.º 30
0
    public Nether() : base()
    {
        //This biome only generates terrain of one type for one block
        GeneratorData[] blockGenerationData = new GeneratorData[1];
        //Create generator Data for Netherrack, it has a minimum height of 10, a peak distance of 1/0.04 ~= 25 & each peak
        //is ~= 5 blocks tall
        GeneratorData netherData = new GeneratorData(BlockType.NETHERRACK, 10, 0.04f, 5);

        //Set the generator data to the array
        blockGenerationData[0] = netherData;
        //set the generator data
        setGeneratorData(blockGenerationData);
        //set the cave size and frequency
        setCaveFrequency(0.5f);
        setCaveSize(15);
    }
Exemplo n.º 31
0
        private bool UpdateBroke(float deltaTime)
        {
            bool isWasBroked = false;

            if (IsLoaded && Services.ResourceService.IsLoaded && Services.GameModeService.IsGame)
            {
                if (MechanicService != null)
                {
                    foreach (var kvp in Units)
                    {
                        GeneratorData generatorData = Services.ResourceService.Generators.GetGeneratorData(kvp.Key);

                        if (generatorData.Type == GeneratorType.Normal)
                        {
                            if (Services.ManagerService.IsHired(kvp.Key))
                            {
                                MechanicData mechanicData            = ResourceService.MechanicDataRepository.GetMechanicData(kvp.Key);
                                int          mechanicCount           = MechanicService.GetMechanicCount(kvp.Key);
                                int          unitsWhichCanBrokeCount = GetUnitsWhichCanBroke(kvp.Key, mechanicData, mechanicCount);
                                if (unitsWhichCanBrokeCount > 0)
                                {
                                    int minLiveCount = MechanicService.GetServicedUnitCount(generatorData.Id);

                                    int totalUnitCount = GetUnitTotalCount(generatorData.Id);

                                    float speed = GetUnitBrokenSpeed(mechanicData, totalUnitCount);

                                    bool isManagerHired = Services.ManagerService.IsHired(kvp.Key);
                                    bool isBrokeAllowed = Services.MechanicService.IsUnlocked;

                                    if (isManagerHired && isBrokeAllowed)
                                    {
                                        if (kvp.Value.UpdateBroke(deltaTime, speed, minLiveCount, Services))
                                        {
                                            isWasBroked = true;
                                            GameEvents.OnGeneratorUnitsCountChanged(kvp.Value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //UDebug.Log($"was broked => {isWasBroked}");
            }
            return(isWasBroked);
        }
Exemplo n.º 32
0
    public static unsafe int Main(string[] args)
    {
        string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        string pluginDirectory;
        if (baseDirectory.EndsWith("bin"))
        {
            // Windows
            pluginDirectory = Path.GetFullPath(Path.Combine(baseDirectory, "..\\lib\\plugins"));
        }
        else
        {
            // *nix
            pluginDirectory = Path.Combine(baseDirectory, "plugins");
        }

        List<string> codeFiles = new List<string>();
        List<CodeCompileUnit> codeSnippets = new List<CodeCompileUnit>();
        List<Assembly> references = new List<Assembly>();
        List<string> imports = new List<string>();
        StringBuilder compilerOptions = new StringBuilder();
        bool codeOnly = false;
        string codeFile = string.Empty;
        string assemblyFile = "out.dll";
        int warnLevel = 0;
        string smokeLib = null;
        string defaultNamespace = "Qyoto";
        string globalClass = "Global";
        string destination = string.Empty;
        string docs = string.Empty;

        List<Assembly> plugins = new List<Assembly>();

        foreach (string arg in args)
        {
            if (arg == "-help" || arg == "--help" || arg == "-h")
            {
                PrintHelp();
                return 0;
            }
            if (arg == "-verbose")
            {
                Debug.Listeners.Add(new ConsoleTraceListener(true));
                continue;
            }
            if (arg == "-code-only")
            {
                codeOnly = true;
                continue;
            }
            if (arg.StartsWith("-code-file:"))
            {
                codeFile = arg.Substring(11);
                continue;
            }
            if (arg.StartsWith("-out:"))
            {
                assemblyFile = arg.Substring(5);
                continue;
            }
            if (arg.StartsWith("-warn:"))
            {
                warnLevel = int.Parse(arg.Substring(6));
                continue;
            }
            if (arg.StartsWith("-r:"))
            {
                references.Add(Assembly.LoadFrom(arg.Substring(3)));
                continue;
            }
            if (arg.StartsWith("-reference:"))
            {
                references.Add(Assembly.LoadFrom(arg.Substring(11)));
                continue;
            }
            if (arg.StartsWith("-global-class:"))
            {
                globalClass = arg.Substring(14);
                continue;
            }
            if (arg.StartsWith("-namespace:"))
            {
                defaultNamespace = arg.Substring(11);
                continue;
            }
            if (arg.StartsWith("-dest:"))
            {
                destination = arg.Substring("-dest:".Length);
                continue;
            }
            if (arg.StartsWith("-import:"))
            {
                imports.AddRange(arg.Substring(8).Split(','));
                continue;
            }
            if (arg.StartsWith("-docs:"))
            {
                docs = arg.Substring("-docs:".Length);
                continue;
            }
            if (arg.StartsWith("-plugins:"))
            {
                foreach (string str in arg.Substring(9).Split(','))
                {
                    Assembly a;
                    try
                    {
                        a = Assembly.LoadFrom(str);
                    }
                    catch (FileNotFoundException)
                    {
                        a = Assembly.LoadFrom(Path.Combine(pluginDirectory, str));
                    }
                    plugins.Add(a);
                }
                continue;
            }
            if (arg.StartsWith("-"))
            {
                compilerOptions.Append(" /");
                compilerOptions.Append(arg.Substring(1));
                continue;
            }

            if (smokeLib == null)
            {
                smokeLib = arg;
                continue;
            }

            codeFiles.Add(arg);
            FileStream fs = new FileStream(arg, FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            codeSnippets.Add(new CodeSnippetCompileUnit(sr.ReadToEnd()));
            sr.Close();
            fs.Close();
        }
        if (!string.IsNullOrEmpty(docs))
        {
            compilerOptions.Append(" /doc:" + Path.ChangeExtension(Path.GetFileName(assemblyFile), ".xml"));
        }

        compilerOptions.Append(" -debug");

        if (smokeLib == null)
        {
            PrintHelp();
            return 1;
        }

        Smoke* smoke = InitSmoke(smokeLib);
        if (smoke == (Smoke*) 0)
        {
            return SmokeLoadingFailure;
        }

        List<ICustomTranslator> customTranslators = (from plugin in plugins
                                                     from type in plugin.GetTypes()
                                                     from iface in type.GetInterfaces()
                                                     where iface == typeof(ICustomTranslator)
                                                     select (ICustomTranslator) Activator.CreateInstance(type)).ToList();

        GeneratorData data = new GeneratorData(smoke, defaultNamespace, imports, references, destination, docs);
        data.GlobalSpaceClassName = globalClass;
        Translator translator = new Translator(data, customTranslators);

        foreach (IHookProvider provider in from type in plugins.SelectMany(plugin => plugin.GetTypes())
                                           where type.GetInterfaces().Any(iface => iface == typeof(IHookProvider))
                                           select (IHookProvider) Activator.CreateInstance(type))
        {
            provider.Translator = translator;
            provider.Data = data;
            provider.RegisterHooks();
        }

        ClassesGenerator classgen = new ClassesGenerator(data, translator);
        Console.Error.WriteLine("Generating CodeCompileUnit...");
        classgen.Run();
        DestroySmoke((IntPtr) smoke);

        Dictionary<string, string> providerOptions = new Dictionary<string, string>();
        providerOptions.Add("CompilerVersion", "v4.0");
        CodeDomProvider csharp = new CSharpCodeProvider(providerOptions);
        if (codeFile != string.Empty)
        {
            FileStream fs = new FileStream(codeFile, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);

            Console.Error.WriteLine("Generating code...");
            CodeGeneratorOptions cgo = new CodeGeneratorOptions();
            csharp.GenerateCodeFromCompileUnit(data.CompileUnit, sw, cgo);
            sw.Close();
            fs.Close();
            codeFiles.Add(codeFile);
        }

        if (codeOnly)
        {
            if (codeFile == string.Empty)
            {
                Console.Error.WriteLine("Missing output filename. Use the -code-file:<file> option.");
                return MissingOptionError;
            }
            return NoError;
        }

        codeSnippets.Add(data.CompileUnit);

        Console.Error.WriteLine("Compiling assembly...");
        CompilerParameters cp = new CompilerParameters();
        cp.GenerateExecutable = false;
        cp.TreatWarningsAsErrors = false;
        cp.OutputAssembly = assemblyFile;
        cp.GenerateInMemory = false;
        cp.WarningLevel = warnLevel;
        cp.CompilerOptions = compilerOptions.ToString();
        cp.ReferencedAssemblies.Add(typeof(Regex).Assembly.Location);
        cp.ReferencedAssemblies.Add(typeof(ExtensionAttribute).Assembly.Location);
        foreach (Assembly assembly in references)
        {
            cp.ReferencedAssemblies.Add(assembly.Location);
        }
        CompilerResults cr;

        if(codeFile == null)
        {
            cr = csharp.CompileAssemblyFromDom(cp, codeSnippets.ToArray());
        }
        else
        {
            cr = csharp.CompileAssemblyFromFile(cp, codeFiles.ToArray());
        }

        bool errorsOccured = false;
        foreach (CompilerError error in cr.Errors)
        {
            if (!error.IsWarning)
                errorsOccured = true;
            Console.Error.WriteLine(error);
        }

        if (errorsOccured)
        {
            Console.Error.WriteLine("Errors occured. No assembly was generated.");
            return CompilationError;
        }
        Console.Error.WriteLine("Done.");
        return NoError;
    }
Exemplo n.º 33
0
 public Documentation(GeneratorData data, Translator translator)
 {
     this.data = data;
     this.translator = translator;
     this.GatherDocs();
 }
Exemplo n.º 34
0
 public PropertyGenerator(GeneratorData data, Translator translator, Dictionary<CodeTypeDeclaration, List<string>> documentation)
 {
     this.data = data;
     this.translator = translator;
     this.documentation = documentation;
 }
Exemplo n.º 35
0
 public ClassesGenerator(GeneratorData data, Translator translator)
 {
     this.data = data;
     this.translator = translator;
     eg = new EnumGenerator(data);
 }
Exemplo n.º 36
0
 public MethodsGenerator(GeneratorData data, Translator translator, CodeTypeDeclaration type, Smoke.Class* klass)
 {
     this.data = data;
     this.translator = translator;
     this.type = type;
     this.smokeClass = klass;
 }
Exemplo n.º 37
0
 public AttributeGenerator(GeneratorData data, Translator translator, CodeTypeDeclaration type)
 {
     this.data = data;
     this.translator = translator;
     this.type = type;
 }
Exemplo n.º 38
0
 public ClassInterfacesGenerator(GeneratorData data, Translator translator)
 {
     this.data = data;
     this.translator = translator;
 }
Exemplo n.º 39
0
 public EnumGenerator(GeneratorData data)
 {
     this.data = data;
 }