コード例 #1
0
ファイル: SimulationManager.cs プロジェクト: Redxgit/AICar
    void Start()
    {
        gos = new GameObject[numberOfSimulations];

        if (ResetOnStart)
        {
            cont.ResetData();
        }

        for (int i = 0; i < numberOfSimulations; i++)
        {
            GameObject       go = Instantiate(evolutionPrefab, Vector3.zero, Quaternion.identity, transform);
            EvolutionManager mn = go.GetComponentInChildren <EvolutionManager>();
            //mn.smthHappened += ProcessCarEnded;
            mn.sm = this;
            //cf.target = go.transform.GetChild(0);
            //cf.enabled = true;
            gos[i] = go;


            carsSpawne++;
        }

        carsSpawned.text = carsSpawne.ToString();
        Time.timeScale   = targetTimeScale;
    }
コード例 #2
0
ファイル: Enemy0.cs プロジェクト: macky90078/ludumdare
    private void Awake()
    {
        m_rb = GetComponent <Rigidbody2D>();

        m_evolutionManager = GameObject.FindGameObjectWithTag("EvolutionManager").GetComponent <EvolutionManager>();

        m_moveDirection = Quaternion.AngleAxis(Random.Range(0, 360), Vector3.forward) * Vector3.right;
    }
コード例 #3
0
    public void Awake()
    {
        GameObject go = GameObject.Find("GlobalScripts");

        if (go != null)
        {
            MLSNetManager = go.GetComponent(typeof(LSNetManager)) as LSNetManager;
            MGSNetManager = go.GetComponent(typeof(GSNetManager)) as GSNetManager;

            MDataTableManager = go.GetComponent(typeof(DataTableManager)) as DataTableManager;
            MGameDataManager  = go.GetComponent(typeof(GameDataManager)) as GameDataManager;
            MHQGeneralManager = go.GetComponent(typeof(HQGeneralManager)) as HQGeneralManager;

            MGUIManager       = go.GetComponent(typeof(GUIManager)) as GUIManager;
            MGUILayoutManager = go.GetComponent(typeof(GUILayoutManager)) as GUILayoutManager;

            MSceneManager = go.GetComponent(typeof(SceneManager)) as SceneManager;

            MPlayerManager = go.GetComponent(typeof(PlayerManager)) as PlayerManager;
            MNpcManager    = go.GetComponent(typeof(NpcManager)) as NpcManager;
            MSkillManager  = go.GetComponent(typeof(SkillManager)) as SkillManager;

            MTaskManager = go.GetComponent <TaskManager>() as TaskManager;

            M3DItemManager = go.GetComponent <EZ3DItemManager>() as EZ3DItemManager;

            MConnectManager      = go.GetComponent <NativeConnectManager>() as NativeConnectManager;
            MRepeateEventManager = go.GetComponent <RepeateEventManager>() as RepeateEventManager;

            MAffectorManager = go.GetComponent <AffectorManager>() as AffectorManager;
            MEffectManager   = go.GetComponent(typeof(EffectManager)) as EffectManager;
            MSoundManager    = go.GetComponent(typeof(SoundManager)) as SoundManager;

            MCopySweepManager = go.GetComponent(typeof(CopySweepManager)) as CopySweepManager;

            MFingerEvent        = go.GetComponent <FingerEvent>() as FingerEvent;
            MCameraController   = go.GetComponentInChildren <CameraController>() as CameraController;
            MCamTrackController = go.GetComponentInChildren <CameraTrackController>() as CameraTrackController;

            MTeachManager    = go.GetComponent(typeof(TeachManager)) as TeachManager;
            MGUIDataManager  = go.GetComponent(typeof(GUIDataManager)) as GUIDataManager;
            MPushDataManager = go.GetComponent(typeof(PushDataManager)) as PushDataManager;

            MBundleManager      = go.GetComponent(typeof(BundleManager)) as BundleManager;
            MResourceManager    = go.GetComponent <ResourceMgr>() as ResourceMgr;
            MPortDefenseManager = go.GetComponent <PortDefenseManager>() as PortDefenseManager;
            MPortVieManager     = go.GetComponent <PortVieManager>() as PortVieManager;
            MJunHunManager      = go.GetComponent <JunHunManager>() as JunHunManager;
            MJobManager         = go.GetComponent <JobManager>() as JobManager;
            mArenaInfoManager   = go.GetComponent <ArenaInfoManager> () as ArenaInfoManager;
            mProduceManager     = go.GetComponent <ProduceManager>() as ProduceManager;
            mEvolutionManager   = go.GetComponent <EvolutionManager>() as EvolutionManager;
            mShopDataManager    = go.GetComponent <ShopDataManager>() as ShopDataManager;
            MStarter            = go.GetComponent <Starter>();
        }
    }
コード例 #4
0
    private void Start()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        BestNeuralNetwork = new NeuralNetwork(6, 4, 3, 2);

        StartGeneration();
    }
コード例 #5
0
ファイル: SeekerEnemy.cs プロジェクト: macky90078/ludumdare
    private void Awake()
    {
        m_rb = GetComponent <Rigidbody2D>();

        m_evolutionManager = GameObject.FindGameObjectWithTag("EvolutionManager").GetComponent <EvolutionManager>();

        m_soundEffect = GetComponent <AudioSource>();
        m_soundEffect.PlayOneShot(m_SpawnSound);

        m_target = GameObject.FindGameObjectWithTag("Player");
    }
コード例 #6
0
 private void Awake()
 {
     if (Instance == null)
     {
         Instance = this;
     }
     else
     {
         Destroy(gameObject);
     }
 }
コード例 #7
0
 public void OnEvolutionChange(bool evolution)
 {
     if (evolution)
     {
         EvolutionManager.StartNewEvolution(transform.position, transform.rotation);
     }
     else
     {
         EvolutionManager.Instance.StopEvolution();
     }
 }
コード例 #8
0
ファイル: MainForm.cs プロジェクト: TheDawnCc/TypingMonkey
        private void GuideEvolution()
        {
            // Instatiate Evolution Manager - setup Evolution.
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            string sourceStr = InputBox.Text;

            sourceStr = StringHelper.ClearRedundantChar(sourceStr);

            TypingCharacters.GetCharacterSet(sourceStr);

            this.evolutionManager = new EvolutionManager((int)this.PopSizeNumUpDown.Value, sourceStr);

            stopwatch.Stop();
            Debug.WriteLine($"Init time is : {stopwatch.Elapsed}");

            IPrey mostFit = this.evolutionManager.GetMostFit();


            while ((mostFit != null) && (mostFit.ToString() != sourceStr))
            {
                stopwatch.Reset();
                stopwatch.Start();

                int generationNo = this.evolutionManager.IterationCount;

                this.PrintToOutputConsole($"Best: {mostFit.ToString()} ({generationNo})");

                // Evolve next generation.
                mostFit = this.evolutionManager.EvolveGeneration();

                this.ScrollOutputConsoleToEnd();

                // Necessary Evil!
                Application.DoEvents();

                stopwatch.Stop();
                Debug.WriteLine($"OneTime : {stopwatch.Elapsed}");
            }

            if (mostFit != null)
            {
                // Final result.
                this.PrintToOutputConsole($"Best: {mostFit.ToString()} ({this.evolutionManager.IterationCount})");
            }
            else
            {
                // Generation Limit Reached.
                this.PrintToOutputConsole($"Generation Limit Reached: {this.evolutionManager.IterationCount}");
            }
        }
コード例 #9
0
ファイル: GameManager.cs プロジェクト: bi3mer/ScaryFlock
    public void Reset()
    {
        time          = 0f;
        Score         = 0;
        PredatorCount = startingPredatorCount;

        if (!isMainMenu)
        {
            FlockManager.Instance.Reset();
            EvolutionManager.Reset();
        }
    }
コード例 #10
0
    // Update is called once per frame
    void Update()
    {
        var evolution = EvolutionManager.VerifyEvolution();

        if (evolutionType != evolution)
        {
            evolutionType = evolution;

            switch (evolutionType)
            {
            case EvolutionType.Crianca:
                SetEvolution(Crianca);
                break;

            case EvolutionType.AdultoEmpresario:
                SetEvolution(AdultoEmpresario);
                break;

            case EvolutionType.AdultoHippie:
                SetEvolution(AdultoHippie);
                break;

            case EvolutionType.AdultoPunk:
                SetEvolution(AdultoPunk);
                break;

            case EvolutionType.AdultoNormal:
                SetEvolution(AdultoNormal);
                break;

            case EvolutionType.VelhoAtleta:
                SetEvolution(VelhoAtleta);
                break;

            case EvolutionType.VelhoCadeirante:
                SetEvolution(VelhoCadeirante);
                break;

            case EvolutionType.VelhoZen:
                SetEvolution(VelhoZen);
                break;

            case EvolutionType.VelhoNormal:
                SetEvolution(VelhoNormal);
                break;

            default:
                print("ERRO BIZARRO");
                break;
            }
        }
    }
コード例 #11
0
    }                                                                   //< Singleton instance

    /**
     * Awake is called after the initialization of gameobjects prior to the start of the game. This is used as an Initialization function
     */
    private void Awake()
    {
        // Handle singleton instance
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Debug.LogError("More than one EvolutionManager in the scene! Deleting...");
            Destroy(this);
        }
    }
コード例 #12
0
ファイル: EvolutionManager.cs プロジェクト: Arcant1/Genetic
    // On Start
    private void Start()
    {
        if (Singleton == null) // If no other instances were created
        {
            Singleton = this;  // Make the only instance this one
        }
        else
        {
            gameObject.SetActive(false);                        // There is another instance already in place. Make this one inactive.
        }
        BestNeuralNetwork = new NeuralNetwork(Car.NextNetwork); // Set the BestNeuralNetwork to a random new network

        StartGeneration();
    }
コード例 #13
0
        public GeneticNeuronGenerator(
            INeuronActivator neuronActivator,
            int populationSize,
            int[] topology,
            params IGenerationUpdater[] generationUpdaters)
        {
            _neuralNetworkTopology = topology;
            _genotypeGenesAmount   = NeuralNetwork.CalculateWeightCount(topology);

            _currentPopulation = new GeneticNeuron[populationSize];
            EvolutionManager   = new EvolutionManager(_genotypeGenesAmount, populationSize, generationUpdaters);

            _neuronActivator = neuronActivator;
        }
コード例 #14
0
    private void OnTriggerEnter2D(Collider2D col)
    {
        if (!col.gameObject.tag.Equals(Tag.Predator))
        {
            bool playerInvolved = col.gameObject.tag.Equals(Tag.Player, StringComparison.Ordinal) ||
                                  gameObject.tag.Equals(Tag.Player, StringComparison.Ordinal);

            EvolutionManager.RegisterContact(name, col.name, playerInvolved);

            if (isPlayer)
            {
                GameManager.Instance.UpdateScore();
            }
        }
    }
コード例 #15
0
    /* * * * * * * * * * * * * * * * *
     * DATA TO TRACK
     * * * * * * * * * * * * * * * * *
     * winner
     * NN_averagePoints
     * AI_averagePoints
     * NN_totalPoints
     * AI_totalPoints
     * * * * * * * * * * * * * * * * *
     * tyoe
     * points
     * player
     * * * * * * * * * * * * * * * * * */

    /// <summary>
    /// Intiialize the critical variables for the class.
    /// </summary>
    void Awake()
    {
        Application.targetFrameRate = 60;
        Time.timeScale = 1;

        _units = new List <Unit>(ConstHolder.MAX_AGENTS);

        _regions = new Dictionary <RegionOrder, Region>();

        _particles = new List <ParticleSystem>(ConstHolder.MAX_AGENTS);

        _camera           = Camera.main.GetComponent <CameraLogic>();
        _evolutionManager = GetComponent <EvolutionManager>();

        _testsRan           = 0;
        _checkForTransition = false;
        _transitionPanel.Initialize();
    }
コード例 #16
0
    void Awake()
    {
        if (main == null)
        {
            main = this;
            DontDestroyOnLoad(gameObject);
            StartEvolution();
            System.DateTime theTime = System.DateTime.Now;
            path = '/' + theTime.ToString("yyyy-MM-dd-HH-mm-ss") + ".txt";
            System.IO.File.WriteAllText(Application.dataPath + path, "");


            //print(Node.RandomBT().ToS());
            //currentGen = new List<Node> { new Selector(new List<Node> { new Sequence(new List<Node> { new FaceToAngle(90) }), new ArmDown() }), new Selector(new List<Node> { new ArmUp() }) };
        }
        else
        {
            Destroy(gameObject);
        }
    }
コード例 #17
0
ファイル: EvolutionManager.cs プロジェクト: Arcant1/Genetic
 // On Start
 private void Start()
 {
     if (Singleton == null) // If no other instances were created
     {
         Singleton = this;  // Make the only instance this one
     }
     else
     {
         gameObject.SetActive(false); // There is another instance already in place. Make this one inactive.
     }
     if (TrackGenerator.isSeguidorDeLinea)
     {
         BestNeuralNetwork = new NeuralNetwork(Car.NeuralNetworkSeguidor); // Set the BestNeuralNetwork to a random new network
     }
     else
     {
         BestNeuralNetwork = new NeuralNetwork(Car.NeuralNetworkPowerUps);
     }
     StartGeneration();
 }
コード例 #18
0
ファイル: Multiobjective.cs プロジェクト: afcarl/IESoR
        //add an existing population from hypersharpNEAT to the multiobjective population maintained in
        //this class, step taken before evaluating multiobjective population through the rank function
        public void addPopulation(Population p)
        {
            EvolutionManager em = EvolutionManager.SharedEvolutionManager;

            for (int i = 0; i < p.GenomeList.Count; i++)
            {
                bool blacklist = false;
                for (int j = 0; j < population.Count; j++)
                {
                    if (distance(p.GenomeList[i].Behavior.objectives, population[j].objectives) < 0.01)
                    {
                        blacklist = true;                        //reject a genome if it is very similar to existing genomes in pop
                    }
                }
                if (!blacklist)                  //add genome if it is unique
                //we might not need to make copies
                {
                    NeatGenome.NeatGenome copy = (NeatGenome.NeatGenome)em.getGenomeFromID(p.GenomeList[i].GenomeId); //new NeatGenome.NeatGenome((NeatGenome.NeatGenome)p.GenomeList[i], p.GenomeList[i].GenomeId);
                    copy.objectives = (double[])p.GenomeList[i].Behavior.objectives.Clone();
                    population.Add(copy);
                }
            }
        }
コード例 #19
0
    // ----------------------------------------------------------------------------------------------------------------------------------------------------------------
    // Initialisation
    // ----------------------------------------------------------------------------------------------------------------------------------------------------------------

    public void initialise_stage(Texture original_image, RenderTexture clear_with_base, Compute_Shaders shaders, bool is_black_white, uint stage_id, EvolutionManager evl_man_lazy_ref)
    {
        fitness_data = new FitnessData();

        // ____________________________________________________________________________________________________
        // Initializing Parameter passed from Evolution Manager

        ImageToReproduce = original_image;
        compute_shaders  = shaders;
        scale_stage_id   = stage_id;

        // ____________________________________________________________________________________________________
        // Compute Resources Initialization
        compute_resources = new Compute_Resources();
        compute_resources.Consruct_Buffers(ImageToReproduce, clear_with_base, evolution_settings);

        // ____________________________________________________________________________________________________
        // Materials

        rendering_material = new Material(Shader.Find("Unlit/PopulationShader"));
        if (!rendering_material)
        {
            Debug.LogError("Couldnt find the population shader");
        }

        rendering_material.SetTexture("_MainTex", evolution_settings.brushTexture);

        fittest_rendering_material = new Material(Shader.Find("Unlit/FittestRenderShader"));
        if (!fittest_rendering_material)
        {
            Debug.LogError("could not find the sahder for rendering the fittest population member");
        }

        fittest_rendering_material.SetInt("_genes_number_per_member", (int)evolution_settings.maximumNumberOfBrushStrokes);
        fittest_rendering_material.SetTexture("_MainTex", evolution_settings.brushTexture);

        rendering_material.SetBuffer("_population_pool", compute_resources.population_pool_buffer);
        rendering_material.SetBuffer("_population_pool", compute_resources.population_pool_buffer);
        fittest_rendering_material.SetBuffer("_population_pool", compute_resources.population_pool_buffer);
        fittest_rendering_material.SetBuffer("_fittest_member", compute_resources.fittest_member_buffer);
        // ____________________________________________________________________________________________________
        // Compute Shader Bindings


        compute_shaders.Bind_Compute_Resources(ImageToReproduce, compute_resources, evolution_settings);

        UpdateBalancingParameters(0); // so that the parameters for the sobel/ gaussian and position search domain is set here

        // ____________________________________________________________________________________________________
        // Procesing the orignal Image

        if (fitness_settings.costume_mask == null)                                                                                                // Only calculate the gaussian sobel mask for this stage, if the user is not providing a hand made one
        {
            compute_shaders.gaussian_compute.Dispatch(compute_shaders.gaussian_horizontal_handel,
                                                      original_image.width / 8, original_image.height / 8, 1);

            Graphics.Blit(compute_resources.gaussian_out, compute_resources.original_image_blured);

            compute_shaders.gaussian_compute.Dispatch(compute_shaders.gaussian_vertical_handel,
                                                      original_image.width / 8, original_image.height / 8, 1);
            Graphics.Blit(compute_resources.gaussian_out, compute_resources.original_image_blured);

            compute_shaders.sobel_compute_original.Dispatch(compute_shaders.sobel_handel_original,                                               // Apply sobel effect on the image once. This doesnt need to be on the loop and only happens once per stage
                                                            original_image.width / 32, original_image.height / 32, 1);

            Graphics.Blit(compute_resources.sobel_out, compute_resources.original_image_gradient);                                               // Copying over the results in a new read only texture. Random access resource types are not compatible with samplers. So I have to make this copy
        }
        else
        {
            Graphics.Blit(fitness_settings.costume_mask, compute_resources.original_image_gradient);
        }

        compute_shaders.construct_position_domain_compute.Dispatch(compute_shaders.Debug_Position_Domain_to_Texture_handel,
                                                                   original_image.width / 8, original_image.height / 8, 1);

        Graphics.Blit(compute_resources.debug_texture, evl_man_lazy_ref.current_search_domain_visualisation);

        compute_shaders.construct_position_domain_compute.Dispatch(compute_shaders.Construct_Position_Domain_handel,
                                                                   original_image.width / 8, original_image.height / 8, 1);


        ComputeBuffer.CopyCount(compute_resources.position_domain_buffer, compute_resources.positon_domain_arguments_buffer, 0);

        int[] counter = new int[4];

        compute_resources.positon_domain_arguments_buffer.GetData(counter);

        Debug.Log(string.Format("The number of pixels in the position domains is: {0}", counter[0]));


        // ____________________________________________________________________________________________________
        // CPU Arrays initalization

        // -----------------------
        // Population Pool first gen initialization

        int total_number_of_genes = (int)(evolution_settings.populationPoolNumber * evolution_settings.maximumNumberOfBrushStrokes);

        if (total_number_of_genes % 32 != 0)
        {
            Debug.LogError("Total number of genes is not a multply of 128. Either change the compute dispatches in " +
                           "script, or make sure the Population pool number times the maximum brush strokes number is a multiple of 128");
        }

        if (!is_black_white)
        {
            compute_shaders.compute_selection_functions.Dispatch(                                                                             // Generates the first batch of genes (brush strokes)
                compute_shaders.populate_population, total_number_of_genes / 128, 1, 1);
        }
        else
        {
            compute_shaders.compute_selection_functions.Dispatch(                                                                             // does the same but it only does it in black and white
                compute_shaders.populate_population_BW, total_number_of_genes / 128, 1, 1);
        }


        // ____________________________________________________________________________________________________
        // Command Buffer Generation

        stage_command_buffer = new CommandBuffer
        {
            name = string.Format("Stage_{0}_Command_Buffer", scale_stage_id.ToString()),
        };

        ClearAllRenderTargets(ref stage_command_buffer, true, true, Color.white);

        if (ImageToReproduce.width % 32 != 0 || ImageToReproduce.height % 32 != 0)
        {
            Debug.LogError("image is not multiply of 32. Either change the image dimensions or" +
                           "The threadnumbers set up in the compute shaders!");
        }

        // -----------------------
        // Command Buffer Recording

        uint shader_population_member_begining_index = 0;

        for (int i = 0; i < evolution_settings.populationPoolNumber; i++)
        {
            stage_command_buffer.SetGlobalInt("_memember_begin_stride", (int)shader_population_member_begining_index);                         // This is used in the PopulationShader to sample the currect population member (brush stroke) from the population pool list. It is baisicly population_member_index * genes_number_per_population
            shader_population_member_begining_index += evolution_settings.maximumNumberOfBrushStrokes;                                         // add the genes number (stride) in every loop iteration instead of caculating  population_member_index * genes_number_per_population every time

            // -----------------------
            // Draw Population Pool Member

            ClearAllRenderTargets(ref stage_command_buffer, true, true, Color.white);                                                          // Each stage paints on top of the result of the previus stage, this is where the result of the preveus stage is first blitted on the screen
            stage_command_buffer.DrawProcedural(Matrix4x4.identity, rendering_material, 0,                                                     // Actual drawing happens here. The population is drawn to a render target for further assement down the pipeline
                                                MeshTopology.Triangles, (int)evolution_settings.maximumNumberOfBrushStrokes * 6);

            // -----------------------
            // Copy results for compute

            stage_command_buffer.CopyTexture(compute_resources.active_texture_target, compute_resources.compute_forged_in_render_texture);     // Without copying the rendering results to a new buffer, I was getting weird results after the rendering of the first population member. Seemed like unity unbinds this buffer since it thinks another operation is writing to it and binds a compeletly different buffer as input (auto generated one). The problem is gone if you copy the buffer


            // -----------------------
            //Compute Fitness
            stage_command_buffer.SetGlobalInt("_population_id_handel", i);                                                                     // the id is used in compute to know which of the populatioin members are currently being dealt with.

            // thread groups are made up 32 in 32 threads. The image should be a multiply of 32.
            // so ideally padded to a power of 2. For other image dimensions, the threadnums
            // should be changed in the compute shader for the kernels as well as here the
            // height or width divided by 32. Change it only if you know what you are doing
            stage_command_buffer.DispatchCompute(compute_shaders.compute_fitness_function, compute_shaders.per_pixel_fitness_kernel_handel,    // Compute the fittness of each individual pixel
                                                 ImageToReproduce.width / 32, ImageToReproduce.height / 32, 1);

            // dispatch one compute per row in groups of 64
            stage_command_buffer.DispatchCompute(compute_shaders.compute_fitness_function, compute_shaders.sun_rows_kernel_handel,             // Sum up each row to a single value. So a new array will come out of this which is a single column that has as many member as the height of the image
                                                 ImageToReproduce.height / 32, 1, 1);

            // dispatch a single thread
            stage_command_buffer.DispatchCompute(compute_shaders.compute_fitness_function, compute_shaders.sun_column_kernel_handel,           // sums up all the values of the column which are holding the entire contribution of the row in one float. This float is the sum of the fitness of the entire image
                                                 1, 1, 1);
        }

        // -----------------------
        // Convert Fitness to accumlative weighted probablities

        // Dispatch single thread.
        stage_command_buffer.DispatchCompute(compute_shaders.compute_selection_functions,                                                      // dispatching only a single thread is a waste of a wave front and generally gpu resrources. There  are better reduction algorithmns designed for GPU, have a look at those
                                             compute_shaders.trans_fitness_to_prob_handel, 1, 1, 1);

        // -----------------------
        // Redraw The Fittest of the Population Members
        ClearAllRenderTargets(ref stage_command_buffer, true, true, Color.white);

        stage_command_buffer.DrawProcedural(Matrix4x4.identity, fittest_rendering_material, 0,
                                            MeshTopology.Triangles, (int)evolution_settings.maximumNumberOfBrushStrokes * 6);
        stage_command_buffer.Blit(compute_resources.active_texture_target, BuiltinRenderTextureType.CameraTarget);                             // This is done for the visualisation porpuses, so that you can see the result of the descend real time

        if (evolution_settings.populationPoolNumber % 16 != 0)
        {
            Debug.LogError("The population pool number is set to" + evolution_settings.populationPoolNumber +
                           "Which is not multiple of 32. Either change this number or numThreads in the compute shader!");
        }

        // -----------------------
        // Select parents for each member of the second generation pool based on the fitness of each member

        stage_command_buffer.DispatchCompute(compute_shaders.compute_selection_functions,
                                             compute_shaders.parent_selection_handel, (int)evolution_settings.populationPoolNumber / 16, 1, 1);

        if (total_number_of_genes % 128 != 0)
        {
            Debug.LogError(string.Format("Total number of genes in the population pool is: {0}, which is not a factor of 128. " +
                                         "Either change this number to a factor of 128 or change the numThreads in the compute shader"));
        }

        // -----------------------
        // Create each member of the second generation by combining the genes of the parents

        stage_command_buffer.DispatchCompute(compute_shaders.compute_selection_functions,
                                             compute_shaders.cross_over_handel, total_number_of_genes / 128, 1, 1);

        if (!is_black_white)
        {
            stage_command_buffer.DispatchCompute(compute_shaders.compute_selection_functions,                                                  // This copies the cross overed genes from second gen to the main buffer for rendering in next frame and also mutates some of them
                                                 compute_shaders.mutation_and_copy_handel, total_number_of_genes / 128, 1, 1);
        }
        else
        {
            stage_command_buffer.DispatchCompute(compute_shaders.compute_selection_functions,                                                  // This copies the cross overed genes from second gen to the main buffer for rendering in next frame and also mutates some of them. However mutation is in black and white
                                                 compute_shaders.mutation_and_copy_BW_handel, total_number_of_genes / 128, 1, 1);
        }

        Camera.main.AddCommandBuffer(CameraEvent.AfterEverything, stage_command_buffer);                                                       // Evolution Master has already checked that the Camera main is valid. Dispatch the Command buffer after everything
    }
コード例 #20
0
 public static void StartNewEvolution(Vector2 position, Quaternion rotation)
 {
     Instance = Instantiate(GameManager.Instance.EvolutionManagerPrefab, position, rotation).GetComponent <EvolutionManager>();
     UI.Instance.EvolutionUI.SetActive(true);
 }
コード例 #21
0
 public void StopEvolution()
 {
     Destroy(gameObject);
     Instance = null;
     UI.Instance.EvolutionUI.SetActive(false);
 }
コード例 #22
0
ファイル: SimpleCommunicator.cs プロジェクト: afcarl/IESoR
        public void Execute(bool startNovelty = false)
        {
            Console.WriteLine("Starting TestSocketIOClient Example...");

            socket = new Client("http://localhost:3000/"); // url to the nodejs / socket.io instance

            socket.Opened += SocketOpened;


            socket.Message += SocketMessage;
            socket.SocketConnectionClosed += SocketConnectionClosed;


            socket.Error += SocketError;

            // register for 'connect' event with io server
            socket.On("connect", (fn) =>
            {
                Console.WriteLine("\r\nConnected event...\r\n");
                Console.WriteLine("Connected To Socket Object");

                //begin our threaded novelty evaluations on connect
                if (startNovelty)
                {
                    simpleExperiment.StartNoveltyEvaluations();
                }
            });

            socket.On("toggleNetwork", (fn) =>
            {
                print.WriteLine("Incoming select: " + fn.Json.ToJsonString());

                //we see an incoming request for selection
                long selectionID = (long)fn.Json.Args[0];

                //we have the ID, now we must do some toggling
                //we could call the evolution manager directly, but perhaps it's best to separate these objects? In case there are many experiements or someting?
                //or maybe the experiment wants to not the selection information
                bool toggle = simpleExperiment.toggleNetwork(selectionID);

                if (toggle)
                {
                    print.WriteLine("Successful toggle, as suspected");
                }

                EvolutionManager eManager = EvolutionManager.SharedEvolutionManager;


                string isSelected = string.Format("{0}:::{1}+[{2}]", (int)SocketIOMessageTypes.ACK, fn.AckId, JsonConvert.SerializeObject(eManager.isSelected(selectionID)));

                print.WriteLine("Responding to toggleNetwork with: " + JsonConvert.SerializeObject(eManager.isSelected(selectionID)));

                socket.Send(isSelected);
            });
            //you simply make a request for the next body, no
            socket.On("getBodies", (fn) =>
            {
                if (fn.Json.Args.Length > 0)
                {
                    //we accept a parameter describing the number of desired bodies
                    int numberOfBodies = (int)fn.Json.Args[0];

                    //We must generate our collection of bodies and send them back in a JSON object
                    string[] bodies = simpleExperiment.fetchBodies(numberOfBodies);

                    //we have all of our bodies, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(bodies));

                    //now return information to our socket
                    socket.Send(bodiesMessage);
                }
            });
            socket.On("getGenomes", (fn) =>
            {
                if (fn.Json.Args.Length > 0)
                {
                    //we accept a parameter describing the number of desired bodies
                    JArray con = (JArray)fn.Json.Args[0];

                    List <long> genomeIDs = new List <long>();

                    foreach (var idString in con)
                    {
                        long genomeID;

                        if (long.TryParse(idString.ToString(), out genomeID))
                        {
                            //Console.WriteLine("Genomeid: " + genomeID);
                            genomeIDs.Add(genomeID);
                        }
                        else
                        {
                            throw new Exception("Failure to send appropriate genomeID");
                        }
                    }

                    try
                    {
                        //We must find our collection of bodies and send them back in a JSON object
                        Dictionary <long, string> bodies = simpleExperiment.fetchBodiesFromIDs(genomeIDs);

                        //we have all of our bodies, we must send them back now!
                        string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(bodies));

                        print.WriteLine("Sending bodies: " + JsonConvert.SerializeObject(bodies.Keys));

                        //now return information to our socket
                        socket.Send(bodiesMessage);
                    }
                    catch (Exception e)
                    {
                        //we failed to fetch the bodies, throw an error, this is some serious stuff!
                        Console.WriteLine("Failed to fetch bodies and send response");
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                        throw e;
                    }
                }
            });
            socket.On("getBest", (fn) =>
            {
                if (fn.Json.Args.Length > 0)
                {
                    long lastQueryTime = (long)fn.Json.Args[0];
                    //long.TryParse(fn.Json.Args[0], out lastQueryTime);

                    //get our best bodies
                    var bodyAndTime = simpleExperiment.fetchBestBodies(lastQueryTime);

                    //we have all of our bodies, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(bodyAndTime));

                    print.WriteLine("Sending best: " + JsonConvert.SerializeObject(bodyAndTime.Second.Keys));

                    //now return information to our socket
                    socket.Send(bodiesMessage);
                }
            });
            socket.On("ping", (fn) =>
            {
                print.WriteLine("Incoming Ping: " + fn.Json.ToJsonString());

                int value = (int)fn.Json.Args[0];

                value = value + 1;

                //string jSon = SimpleJson.SimpleJson.SerializeObject(net);

                string jSon = simpleExperiment.fetchNextBodyJSON();

                //Dictionary<string, object> stuff =new Dictionary<string,object>();
                //stuff.Add("c#says", "pong");
                //stuff.Add("valuePlusOne", value);
                //string data = SimpleJson.SimpleJson.SerializeObject(stuff);

                //string.Format("{\"{0}\": \"{1}\", \"{2}\": {3} }", "c#Says", "pong", "value", value);

                string tosend = string.Format("{0}:::{1}+[{2}]", (int)SocketIOMessageTypes.ACK, fn.AckId, jSon);

                print.WriteLine("Responding to ping with: " + jSon);
                socket.Send(tosend);//new AckMessage() { AckId = fn.AckId, MessageText = "pong" });
            });
            socket.On("runFullPCA", (fn) =>
            {
                int xBins, yBins, genomeSelector;
                double topPercent;
                bool firstBehavior;
                bool.TryParse(fn.Json.Args[0], out firstBehavior);
                int.TryParse(fn.Json.Args[1], out xBins);
                int.TryParse(fn.Json.Args[2], out yBins);
                int.TryParse(fn.Json.Args[3], out genomeSelector);
                double.TryParse(fn.Json.Args[4], out topPercent);

                //want to send in custom params for selecting what method to grab genomes (or to send a genome array)

                //if (fn.Json.Args.Length > 0)
                //{
                //    //we accept a parameter describing the number of desired bodies
                //    JArray con = (JArray)fn.Json.Args[3];


                // Create new stopwatch
                Stopwatch stopwatch = new Stopwatch();

                // Begin timing
                stopwatch.Start();

                //grab ALL of our saved genomes, and make sure they are unique individuals
                //we group them by a genome ID, then we select the first object in the group, voila, distinct!
                List <NeatGenome> allGenomes;

                switch (genomeSelector)
                {
                case 0:
                    allGenomes = simpleExperiment.fetchAllGenomes().GroupBy(g => g.GenomeId).Select(group => group.First()).ToList();
                    break;

                case 1:
                    allGenomes = simpleExperiment.fetchBestGenomes(topPercent).GroupBy(g => g.GenomeId).Select(group => group.First()).ToList();
                    break;

                default:
                    allGenomes = simpleExperiment.fetchAllGenomes().GroupBy(g => g.GenomeId).Select(group => group.First()).ToList();
                    break;
                }


                EvolutionManager.SharedEvolutionManager.saveGenomes(allGenomes);


                // Begin timing
                stopwatch.Stop();

                Console.WriteLine("Fetch Genomes: " + stopwatch.ElapsedMilliseconds);



                var uidAndPoints = runPCA(allGenomes, firstBehavior, xBins, yBins);

                try
                {
                    //we have all of our bodies, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(uidAndPoints));

                    print.WriteLine("Sending pca analysis for IDs: " + JsonConvert.SerializeObject(uidAndPoints));

                    //now return information to our socket
                    socket.Send(bodiesMessage);
                }
                catch (Exception e)
                {
                    //we failed to fetch the bodies, throw an error, this is some serious stuff!
                    Console.WriteLine("Failed to fetch bodies and send response");
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    throw e;
                }
            });
            socket.On("runPCA", (empty) =>
            {
                //we accept a parameter describing the number of desired bodies
                //JArray con = (JArray)fn.Json.Args[0];


                //grab the best individuals (already having been evaluated, we grab their behavior and PCA

                //get our best bodies
                List <NeatGenome> topBodyAndTime = simpleExperiment.fetchBestGenomes(.1);

                var uidAndPoints = runPCA(topBodyAndTime);

                try{
                    //we have all of our bodies, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(empty.AckId, JsonConvert.SerializeObject(uidAndPoints));

                    print.WriteLine("Sending pca analysis for IDs: " + JsonConvert.SerializeObject(uidAndPoints));

                    //now return information to our socket
                    socket.Send(bodiesMessage);
                }
                catch (Exception e)
                {
                    //we failed to fetch the bodies, throw an error, this is some serious stuff!
                    Console.WriteLine("Failed to fetch bodies and send response");
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    throw e;
                }
            });

            //socket.On("evaluateGenomes", (data) =>
            //{
            //    print.WriteLine(data);
            //    //Console.WriteLine("  raw message:      {0}", data.RawMessage);
            //    //Console.WriteLine("  string message:   {0}", data.MessageText);
            //    //Console.WriteLine("  json data string: {0}", data.Json.ToJsonString());
            //    //Console.WriteLine("  json raw:         {0}", data.Json.Args[0]);

            //});


            // register for 'update' events - message is a json 'Part' object
            socket.On("update", (data) =>
            {
                print.WriteLine("recv [socket].[update] event");
                //Console.WriteLine("  raw message:      {0}", data.RawMessage);
                //Console.WriteLine("  string message:   {0}", data.MessageText);
                //Console.WriteLine("  json data string: {0}", data.Json.ToJsonString());
                //Console.WriteLine("  json raw:         {0}", data.Json.Args[0]);
            });

            // register for 'update' events - message is a json 'Part' object
            socket.On("getArchiveIDs", (data) =>
            {
                //let's go fetch our novelty ids!
                List <long> archiveIDs = simpleExperiment.GetNoveltyArchive();

                if (archiveIDs != null)
                {
                    //we have all of our ids, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(data.AckId, JsonConvert.SerializeObject(archiveIDs));

                    socket.Send(bodiesMessage);
                }
            });

            // Grabs the current generation ids for viewing purposes!
            socket.On("getCurrentIDs", (data) =>
            {
                //let's go fetch our novelty ids!
                List <long> currentIDs = simpleExperiment.GetMultiCurrentGeneration();

                if (currentIDs != null)
                {
                    //we have all of our ids, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(data.AckId, JsonConvert.SerializeObject(currentIDs));

                    socket.Send(bodiesMessage);
                }
            });


            // make the socket.io connection
            socket.Connect();
        }
コード例 #23
0
 // Get Cars Array, neural Networks of said cars and EvolutionManager.cs
 void GetReferences()
 {
     cars        = GameObject.FindGameObjectsWithTag("Player");
     carsNetwork = new NeuralNetwork[cars.Length];
     evoManager  = GameObject.Find("EvolutionManager").GetComponent <EvolutionManager>();
 }