示例#1
0
        /// <summary>
        /// Method to parsing one sentence of given text
        /// </summary>
        /// <param name="sentence">Sentence to parse</param>
        /// <returns>List of parsed elements</returns>
        public SentenceGraph ParseSentence(string sentence)
        {
            Dictionary <int, List <IProcessable> > dependencyTree;
            SentenceGraph graph = new SentenceGraph();

            // recreating dependency tree given as REST API response from UDPipe
            var validLines = this.Client.GetResponse(sentence);

            dependencyTree = GetDependencyTree(validLines);

            // new root element
            var root = this.ElementFactory.CreateRoot(sentence);

            // compressing dependency tree into graph
            this.Comparer.Tree = dependencyTree;
            IProcessable element = CompressDependencyTree(dependencyTree, graph, root).FinalizeProcessing(graph);

            // Clear graph if nothing were found for safety
            if (element is Root)
            {
                graph.Clear();
            }

            // Adding last processed vertex (is added only if its only vertex in sentence)
            if (element is IDrawable drawable)
            {
                graph.AddVertex(drawable);
            }

            return(graph);
        }
示例#2
0
        private IProcessable ProcessElement(Numeral num, ISentenceGraph graph)
        {
            num.DependencyType    = this.DependencyType;
            this.DependingNumeral = num;

            return(this);
        }
示例#3
0
        protected override IProcessable ProcessElement(IProcessable element, ISentenceGraph graph)
        {
            switch (element)
            {
            case Adjective adj: return(this.ProcessElement(adj, graph));

            case Noun noun: return(this.ProcessElement(noun, graph));

            case NounSet nounSet: return(this.ProcessElement(nounSet, graph));

            case Adposition adp: return(this.ProcessElement(adp, graph));

            case Numeral num: return(this.ProcessElement(num, graph));

            case Verb verb: return(this.ProcessElement(verb, graph));

            case Adverb adv: return(this.ProcessElement(adv, graph));

            case Coordination cor: return(this.ProcessCoordination(cor));

            default: break;
            }

            return(this);
        }
示例#4
0
        private IProcessable ProcessElement(Verb verb, ISentenceGraph graph)
        {
            // Skip copula
            if (this.DependencyTypeHelper.IsCopula(verb.DependencyType))
            {
                return(this);
            }

            IProcessable processElement = this;

            // Process all depending drawables of the verb
            if (verb.DependingDrawables.Count != 0)
            {
                verb.DependingDrawables.ForEach(dd => processElement = processElement.Process(dd, graph));
                verb.DependingDrawables.Clear();
            }

            // Process all related actions
            verb.RelatedActions.ForEach(ra => processElement.Process(ra, graph));
            verb.RelatedActions.Clear();

            // Process non used adposition
            if (verb.DrawableAdposition != null)
            {
                processElement.Process(verb.DrawableAdposition, graph);
                verb.DrawableAdposition = null;
            }

            // Replace verb object in the graph
            if (verb.Object != null)
            {
                if (verb.Object is NounSet)
                {
                    ((NounSet)verb.Object).Nouns.ForEach(n =>
                    {
                        if (graph.Vertices.Contains(n))
                        {
                            graph.ReplaceVertex((IDrawable)processElement, n);
                        }
                    });
                }

                if (graph.Vertices.Contains((IDrawable)verb.Object))
                {
                    graph.ReplaceVertex((IDrawable)processElement, (IDrawable)verb.Object);
                }
            }

            // Process only non negated verbs
            if (!verb.IsNegated && processElement == this)
            {
                foreach (var noun in this.Nouns)
                {
                    noun.Process(verb, graph);
                }
            }

            return(processElement);
        }
示例#5
0
 static private ProcessType SafeProcTypeGet(IProcessable aObject, ProcessType aNeededProcessType)
 {
     if (aObject.State != AnalysisState.Processed)
     {
         return(ProcessType.ProcessFull);
     }
     return(aNeededProcessType);
 }
 private void HandleEndProcessing()
 {
     currentlyProcessing.currentState |= stateModifier;
     isProcessing = false;
     currentTaskHandler.OnTaksEnded();
     MixSalad(currentlyProcessing);
     currentlyProcessing = null;
 }
 private void AssertProcessableBasic(IProcessable processable, Type t, int id = DEFAULT_ID, string dependency = "_", bool isNegated = false)
 {
     Assert.IsNotNull(processable);
     Assert.IsInstanceOfType(processable, t);
     Assert.AreEqual(processable.Id, id);
     Assert.AreEqual(processable.DependencyType, dependency);
     Assert.AreEqual(processable.IsNegated, isNegated);
 }
        public ProcessableProgressBar(IProcessable processable, Action processAction) : this()
        {
            ProcessableBusiness = processable;
            ProcessAction       = processAction;

            ProcessableBusiness.OnStart    += ProcessableBusiness_OnStart;
            ProcessableBusiness.OnUpdate   += ProcessableBusiness_OnUpdate;
            ProcessableBusiness.OnFinished += ProcessableBusiness_OnFinished;
        }
示例#9
0
    private object AsyncProcess(IProcessable c, string tag, int thread)
    {
        var container = c as VoxelContainer;
        Dictionary <long, int> Voxels = null;

        if (tag == "Terrain")
        {
            Voxels = container.Solid;
        }
        else if (tag == "Liquid")
        {
            Voxels = container.Liquid;
        }

        if (Voxels.Count == 0)
        {
            return(null);
        }

        int vcount = 0;
        int icount = 0;
        int texw   = 0;
        int texh   = 0;

        var keys = Voxels.Keys.ToArray();
        var vals = Voxels.Values.ToArray();
        var data = datas[thread];

        Stopwatch watch = new Stopwatch();

        watch.Start();
        Mesher.MeshVoxels(Voxels.Count, keys, vals,
                          data.Vertices, data.Normals, data.UVs, data.Tris, ref vcount, ref icount, data.Tex, ref texw, ref texh, tag == "Liquid");
        watch.Stop();
        UnityEngine.Debug.Log(watch.Elapsed);

        if (tag == "Terrain")
        {
            var cs = WorldGenerator.ChunkSize;
            container.aocol = new Color[cs * cs * cs];
            for (int la = 0; la < cs * cs * cs; la++)
            {
                int x = la % cs;
                int y = (la / cs) % cs;
                int z = (la / (cs * cs));

                float val = container.CalcAO(x, y, z);
                //float val = 1;
                //val = z/15f;
                //float val = (x == 0 && y == 0 && z == 0) || (x == 1 && y==1 && z==1) ? 1 : 0;
                container.aocol[la] = new Color(val, val, val);
            }
        }

        return(new object[] { data.GetVertices(vcount), data.GetNormals(vcount), data.GetUVs(vcount), data.GetTris(icount), texw, texh, data.GetTex(texw, texh) });
    }
示例#10
0
        private IProcessable ProcessElement(Verb verb, ISentenceGraph graph)
        {
            // skip copula
            if (this.DependencyHelper.IsCopula(verb.DependencyType))
            {
                return(this);
            }

            IProcessable processElement = this;

            // Don't process negated verb
            if (!verb.IsNegated)
            {
                this.Actions.Add(verb);
            }

            // Process all depending drawables
            if (verb.DependingDrawables.Count != 0)
            {
                verb.DependingDrawables.ForEach(dd => processElement = processElement.Process(dd, graph));
                verb.DependingDrawables.Clear();
            }

            // Process all related actions
            verb.RelatedActions.ForEach(ra => processElement.Process(ra, graph));
            verb.RelatedActions.Clear();

            // Process unprocessed adposition
            if (verb.DrawableAdposition != null)
            {
                processElement.Process(verb.DrawableAdposition, graph);
            }

            // Replace verb object in the graph
            if (verb.Object != null)
            {
                if (verb.Object is NounSet ns)
                {
                    ns.Nouns.ForEach(n =>
                    {
                        if (graph.Vertices.Contains(n))
                        {
                            graph.ReplaceVertex((IDrawable)processElement, n);
                        }
                    });
                }

                if (graph.Vertices.Contains((IDrawable)verb.Object))
                {
                    graph.ReplaceVertex((IDrawable)processElement, (IDrawable)verb.Object);
                }
            }

            return(processElement);
        }
示例#11
0
        //
        // DO NOT USE ConfigureAwait(false) WITH ProcessAsync() unless ensuring ProcessAsync() implementation is cross-thread compatible
        // ProcessAsync() often does a lot with forms in the UI context
        //


        /// <summary>Process the first valid product. Create default context</summary>
        /// <returns>Returns either the status handler from the process, or null if all books have been processed</returns>
        public static async Task <StatusHandler> ProcessFirstValidAsync(this IProcessable processable)
        {
            var libraryBook = processable.getNextValidBook();

            if (libraryBook == null)
            {
                return(null);
            }

            return(await processBookAsync(processable, libraryBook));
        }
示例#12
0
 public void Process(IProcessable process, Action action)
 {
     ProgressBar             = new ProcessableProgressBar(process, action);
     ProgressBar.OnStart    += OnStart;
     ProgressBar.OnUpdate   += OnUpdate;
     ProgressBar.OnFinished += OnFinished;
     processing              = new ThreadStart(action);
     ProcessingThread        = new Thread(processing);
     ProcessingThread.Start();
     ShowDialog();
 }
示例#13
0
        public static async Task <StatusHandler> ProcessSingleAsync(this IProcessable processable, LibraryBook libraryBook)
        {
            if (!processable.Validate(libraryBook))
            {
                return new StatusHandler {
                           "Validation failed"
                }
            }
            ;

            return(await processable.ProcessBookAsync_NoValidation(libraryBook));
        }
        /// <summary>
        /// Set process state from input IProcessable
        /// </summary>
        private void SetProcessValue(IProcessable processable)
        {
            if (OperationTypesDataSource != null)
            {
                var currentType = OperationTypesDataSource.FirstOrDefault(x => x.Index == processable.Index);

                if (currentType != null)
                {
                    currentType.Process = processable.GetProcessed();
                }
            }
        }
示例#15
0
        private void ManufacturerInitializeComputersFromInput()
        {
            var manufacturerName = Console.ReadLine();

            ManufacturerFactory manufacturerCreator = new ManufacturerFactory();

            ComputersFactory manufacturer = manufacturerCreator.CreateManufacturer(manufacturerName);

            this.pc     = manufacturer.CreatePc();
            this.laptop = manufacturer.CreateLaptop();
            this.server = manufacturer.CreateServer();
        }
示例#16
0
        private void ManufacturerInitializeComputersFromInput()
        {
            var manufacturerName = Console.ReadLine();

            ManufacturerFactory manufacturerCreator = new ManufacturerFactory();

            ComputersFactory manufacturer = manufacturerCreator.CreateManufacturer(manufacturerName);

            this.pc = manufacturer.CreatePc();
            this.laptop = manufacturer.CreateLaptop();
            this.server = manufacturer.CreateServer();
        }
示例#17
0
        /// <summary>
        /// Interface overriden method
        /// </summary>
        /// <param name="element">Element to process</param>
        /// <param name="graph">Sentence graph</param>
        /// <returns>Processed element</returns>
        public IProcessable Process(IProcessable element, ISentenceGraph graph)
        {
            if (element == null)
            {
                return(this);
            }

            if (element is Negation)
            {
                return(this.ProcessNegation((Negation)element));
            }

            if (element.IsNegated && !(this is Noun) && !(element is Verb))
            {
                if (element is IDrawable drawable)
                {
                    graph.RemoveVertex(drawable, true);
                }

                return(this);
            }

            if (this.IsNegated && this.DependencyHelper.IsSubject(element.DependencyType))
            {
                if (this is Verb verb)
                {
                    this.ProcessableHelper.RemoveVerbFromGraph(verb, graph);
                }

                return(element);
            }


            if (!this.CoordinationTypeHelper.IsAllowedCoordination(this.CoordinationType) && this.DependencyHelper.IsConjuction(element.DependencyType))
            {
                this.CoordinationType = CoordinationType.AND;
                if (element is IDrawable drawable)
                {
                    graph.RemoveVertex(drawable, true);
                }

                if (element is Verb verb)
                {
                    this.ProcessableHelper.RemoveVerbFromGraph(verb, graph);
                }

                return(this);
            }

            var returnElement = this.ProcessElement(element, graph);

            return(returnElement.IsNegated && returnElement != this ? this : returnElement);
        }
示例#18
0
        public InjectionConfigurationViewModel(
            DomainActionBuilder actionBuilder,
            ComponentViewModelFactory componentViewModelFactory,
            IFindFirstLaunchTimeQuery findFirstLaunchTimeQuery,
            IFindGamePackageByIdQuery findGamePackageByIdQuery,
            IFindGamesQuery findGamesQuery,
            IFindLastEditedGamePackageQuery findLastEditedGamePackageQuery,
            IDirectoryPicker directoryPicker,
            IEqualityComparer <ProxySettings> stateEqualityComparer,
            IEventPublisher publisher,
            IFilePicker filePicker,
            IPluginFactory pluginFactory,
            INavigationService navigationService,
            IProcessable processable,
            ITaskRunner runner)
        {
            _actionBuilder                  = actionBuilder;
            _componentViewModelFactory      = componentViewModelFactory;
            _findFirstLaunchTimeQuery       = findFirstLaunchTimeQuery;
            _findGamePackageByIdQuery       = findGamePackageByIdQuery;
            _findGamesQuery                 = findGamesQuery;
            _findLastEditedGamePackageQuery = findLastEditedGamePackageQuery;
            _directoryPicker                = directoryPicker;
            _stateEqualityComparer          = stateEqualityComparer;
            _publisher         = publisher;
            _filePicker        = filePicker;
            _pluginFactory     = pluginFactory;
            _navigationService = navigationService;
            _processable       = processable;
            _runner            = runner;

            _publisher.Register <ApplicationActionEvent>(this);
            _publisher.Register <ApplicationMinimizedEvent>(this);
            _publisher.Register <ApplicationRestoredEvent>(this);

            ActionCommand             = new ActionCommand(() => _queue.QueueTask(ExecuteActionAsync), IsActionEnabled);
            ActivationState           = new StateViewModel(_runner);
            AddGameProfileCommand     = new ActionCommand(() => _queue.QueueTask(AddGameProfileAsync), () => true);
            ChangedCommand            = new ActionCommand(async() => await UpdateGameProfileAsync(), () => true);
            ClearGameFilePathCommand  = new ActionCommand(async() => await ClearApplicationFilePathAsync(), () => !GameFilePath.IsNullOrEmpty());
            EditGameProfileCommand    = new ActionCommand(() => _queue.QueueAction(EditPluginMainSettings), () => true);
            MoveToGameFilePathCommand = new ActionCommand(MoveToApplicationPath, () => !GameFilePath.IsNullOrEmpty());
            MoveToConfigurationDirectoryPathCommand = new ActionCommand(MoveToConfigurationDirectoryPath, () => !GameFilePath.IsNullOrEmpty());
            MoveToLogsDirectoryPathCommand          = new ActionCommand(MoveToLogsDirectoryPath, () => !GameFilePath.IsNullOrEmpty());
            SwitchModeCommand                 = new ActionCommand(async() => await SwapModeAsync(), () => true);
            PickGameFilePathCommand           = new ActionCommand(async() => await PickApplicationFilePathAsync(), () => true);
            PickPluginSettingsEditViewCommand = new GenericActionCommand <IComponentViewModel>(EditPluginComponent, () => true);
            RemoveGameProfileCommand          = new ActionCommand(async() => await RemoveGameProfileAsync(), () => _package?.Game.Profiles.Count > 1);
            RenameGameProfileCommand          = new ActionCommand(async() => await RenameGameProfileAsync(), () => true);
            ValidationTriggeredCommand        = new GenericActionCommand <ValidationResultEventArgs>(eventArgs => _queue.QueueAction(Validate), () => true);
        }
示例#19
0
        private IProcessable ProcessElement(Numeral num, ISentenceGraph graph)
        {
            IProcessable processElem = this;

            num.DependingDrawables.ForEach(dd => processElem = processElem.Process(dd, graph));
            num.DependingActions.ForEach(da => processElem   = processElem.Process(da, graph));
            this.Process(num.DependingNumeral, graph);

            // Process appositional
            if (this.DependencyHelper.IsAppositional(num.DependencyType))
            {
                return(processElem);
            }

            // Process numeral expressing part of noun phrase
            if (this.DependencyHelper.IsNounPhrase(this.DependencyType) || this.DependencyHelper.IsCompound(this.DependencyType))
            {
                this.Extensions.Add(num);
                return(processElem);
            }

            // We don't process time
            if (this.DependencyHelper.IsTime(num.DependencyType))
            {
                return(processElem);
            }

            // Add extension if numeral is not modifying number of instances
            if (!this.DependencyHelper.IsNumeralModifier(num.DependencyType))
            {
                if (num.Id > this.Id)
                {
                    this.Suffixes.Add(num);
                }
                else
                {
                    this.Extensions.Add(num);
                }

                return(processElem);
            }

            // no need to create noun set
            if (num.GetValue() <= 1)
            {
                return(processElem);
            }

            // Create new noun with given number of values
            return(new NounSet(this.ElementFactory, this.EdgeFactory, this, num.GetValue()));
        }
示例#20
0
    private void SyncGenerate(IProcessable c, string tag, object d)
    {
        var crd = d as int[];
        int vx, vy, vz;

        Utils.CoordChunkToVoxel(crd[0], 0, crd[1], out vx, out vy, out vz);
        for (int la = 0; la < 16; la++)
        {
            for (int lb = 0; lb < 16; lb++)
            {
                Generator.GenerateVoxelsForCoord(vx + la, vz + lb);
            }
        }
    }
示例#21
0
        private static LibraryBook getNextValidBook(this IProcessable processable)
        {
            var libraryBooks = DbContexts.GetContext().GetLibrary_Flat_NoTracking();

            foreach (var libraryBook in libraryBooks)
            {
                if (processable.Validate(libraryBook))
                {
                    return(libraryBook);
                }
            }

            return(null);
        }
示例#22
0
        /// <summary>
        /// Adds the object into the pool.
        /// </summary>
        /// <param name="obj">The object to add.</param>
        public void Add(IProcessable obj)
        {
            // Make sure that the object is not null
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            // Otherwise, add it to the general pool
            if (objects.Contains(obj))
            {
                throw new InvalidOperationException("The object is already part of this pool.");
            }
            objects.Add(obj);
        }
示例#23
0
 private void SetProcessEngine()
 {
     if (_simulationEngine.Configuration.IsRecrystallization)
     {
         _processEngine = _recrystallizationEngine;
     }
     else if (_simulationEngine.Configuration.IsMC)
     {
         _processEngine = _MCEngine;
     }
     else
     {
         _processEngine = _CAEngine;
     }
 }
        /// <summary>
        /// Method for creating new text elements
        /// </summary>
        /// <param name="parts">UDPipe service response line</param>
        /// <returns>New text element</returns>
        public IProcessable Create(string[] parts)
        {
            // Map known cases
            this.MapKnownCases(parts[2], ref parts[3]);

            IProcessable part = null;

            switch (parts[3])
            {
            case "PROPN":
            case "NOUN":
                part = this.ProcessNoun(parts);
                break;

            case "ADJ":
                part = this.ProcessAdj(parts);
                break;

            case "ADP":
                part = new Adposition(int.Parse(parts[0]), parts[2], parts[7]);
                break;

            case "NUM":
                part = new Numeral(int.Parse(parts[0]), parts[2], parts[7]);
                break;

            case "VERB":
                part = this.ProcessVerb(parts);
                break;

            case "ADV":
                part = new Adverb(int.Parse(parts[0]), parts[2], parts[7]);
                break;

            case "CONJ":
                part = new Coordination(int.Parse(parts[0]), parts[2], parts[7]);
                break;

            case "NEG":
                part = new Negation(int.Parse(parts[0]), parts[2], parts[7]);
                break;

            default:
                break;
            }

            return(part);
        }
示例#25
0
        static void Main(string[] args)
        {
            using (IDbConnection connection = ConnectionFactory.CreateConnection())
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("ERROR: an argument must be given.");
                    return;
                }
                int          jobId        = Convert.ToInt32(args[0]);
                ProcessingVO processingVO = processingDAO.Get(jobId);

                processingBO = CreateProcessing(processingVO);
                processingBO?.Process();
            }
        }
示例#26
0
        private static void LoadProcessingDefinitions(int jobId, ProgramLoadMode loadMode)
        {
            switch (loadMode)
            {
            case ProgramLoadMode.Database:
                processingBO = LoadFromDatabase(jobId);
                break;

            case ProgramLoadMode.XmlFile:
                processingBO = LoadFromXmlFile(jobId);
                break;

            default:
                break;
            }
        }
示例#27
0
        private static async Task runSingleBackupAsync(IProcessable processable, AutomatedBackupsForm automatedBackupsForm, string productId)
        {
            automatedBackupsForm.Show();

            try
            {
                var statusHandler = await processable.ProcessSingleAsync(productId);

                validateStatus(statusHandler, automatedBackupsForm);
            }
            catch (Exception ex)
            {
                automatedBackupsForm.AppendError(ex);
            }

            automatedBackupsForm.FinalizeUI();
        }
 public void Process(IProcessable veggie, ITaskHandler taskHandler)
 {
     if (!isProcessing)
     {
         currentlyProcessing = veggie;
         isProcessing        = true;
         taskCompletionTime  = veggie.processingTime;
         taskTimeElapsed     = 0;
         progress            = 0;
         currentTaskHandler  = taskHandler;
         taskHandler.OnStartedTask();
     }
     else
     {
         Debug.LogError("This processor is busy processing.");
     }
 }
示例#29
0
        public static async Task <StatusHandler> ProcessBookAsync_NoValidation(this IProcessable processable, LibraryBook libraryBook)
        {
            Serilog.Log.Logger.Information("Begin " + nameof(ProcessBookAsync_NoValidation) + " {@DebugInfo}", new
            {
                libraryBook.Book.Title,
                libraryBook.Book.AudibleProductId,
                libraryBook.Book.Locale,
                Account = libraryBook.Account?.ToMask() ?? "[empty]"
            });

            var status
                = (await processable.ProcessAsync(libraryBook))
                  ?? new StatusHandler {
                "Processable should never return a null status"
                };

            return(status);
        }
示例#30
0
 public InjectionConfigurationViewModel Create(IProcessable processable)
 {
     return(new InjectionConfigurationViewModel(
                _actionBuilder,
                _componentViewModelFactory,
                _findFirstLaunchTimeQuery,
                _findGamePackageByIdQuery,
                _findGamesQuery,
                _findLastEditedGamePackageQuery,
                _directoryPicker,
                _stateEqualityComparer,
                _eventPublisher,
                _filePicker,
                _pluginFactory,
                _navigationService,
                processable,
                _runner));
 }
    private void ProcessNode(IProcessable processor, float delta, float inverseDelta)
    {
        if (processor == null)
        {
            GD.PrintErr("A node has been put in the process group " +
                        "but it isn't derived from IProcessable");
            return;
        }

        var bag = processor.ProcessCompoundStorage;

        // Set all compounds to not be useful, when some compound is
        // used it will be marked useful
        bag.ClearUseful();

        var processStatistics = processor.ProcessStatistics;

        processStatistics?.MarkAllUnused();

        foreach (TweakedProcess process in processor.ActiveProcesses)
        {
            // If rate is 0 dont do it
            // The rate specifies how fast fraction of the specified process
            // numbers this cell can do
            // TODO: would be nice still to report these to process statistics
            if (process.Rate <= 0.0f)
            {
                continue;
            }

            var processData = process.Process;

            var currentProcessStatistics = processStatistics?.GetAndMarkUsed(process);
            currentProcessStatistics?.BeginFrame(delta);

            RunProcess(delta, processData, bag, process, currentProcessStatistics, inverseDelta);
        }

        bag.ClampNegativeCompoundAmounts();

        processStatistics?.RemoveUnused();
    }
示例#32
0
 /// <summary>
 /// Enqueue's a processable message
 /// </summary>
 /// <param name="message"></param>
 public void enqueueMessage(IProcessable message)
 {
     Logging.LogMessage("Enqueing message long running is " + message.isLongRunTask());
     if (message.isLongRunTask())
     {
         longRunningProcessing(message);
     }
     else
     {
         TaskHandeler lowestHandeler = queues[0];
         int lowestProcesTime = queues[0].procesTime;
         for (int i = 1; i < queues.Length; i++)
         {
             if (queues[i].procesTime < lowestProcesTime)
             {
                 lowestHandeler = queues[i];
                 lowestProcesTime = queues[i].procesTime;
             }
         }
         lowestHandeler.enqueueMessages(message);
     }
 }
示例#33
0
    private void SyncProcess(IProcessable c, string tag, object d)
    {
        if (d == null) return;

        var container = c as VoxelContainer;
        if (container == null) return;

        var data = d as object[];
        if (data == null) return;

        if (tag == "Liquid")
        {
            foreach (Transform t in container.transform)
            {
                Destroy(t.gameObject);
            }

            GameObject liGo = new GameObject("Liquid");
            liGo.isStatic = true;
            liGo.transform.parent = container.transform;
            liGo.transform.localPosition = Vector3.zero;

            var vertList = data[0] as Vector3[];
            var nrmList = data[1] as Vector3[];
            var uvList = data[2] as Vector2[];
            var indList = data[3] as int[];
            var texW = (int)data[4];
            var texH = (int)data[5];
            var itex = data[6] as int[];

            var mesh = new Mesh();
            mesh.vertices = vertList;
            mesh.normals = nrmList;
            mesh.uv = uvList;
            mesh.triangles = indList;
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();
            mesh.Optimize();

            var mf = liGo.AddComponent<MeshFilter>();
            mf.mesh = mesh;

            //Debug.Log(texW + " " + texH);
            var tex = new Texture2D(texW, texH);
            tex.filterMode = FilterMode.Point;
            tex.wrapMode = TextureWrapMode.Clamp;

            var tdata = new Color32[texW * texH];
            var handle = GCHandle.Alloc(tdata, GCHandleType.Pinned);
            Marshal.Copy(itex, 0, handle.AddrOfPinnedObject(), itex.Length);
            handle.Free();
            ////Debug.Log(String.Format("{0}:{1}:{2}:{3}", tdata[0].r, tdata[0].g, tdata[0].b, tdata[0].a));
            tex.SetPixels32(tdata);
            tex.Apply();

            liGo.AddComponent<MeshRenderer>();

            //container.renderer.material = new Material(container.Shader);
            liGo.renderer.material = new Material(LiquidShader);
            if (liGo.renderer.material.mainTexture != null)
            {
                Destroy(liGo.renderer.material.mainTexture);
            }
            liGo.renderer.material.mainTexture = tex;
            liGo.renderer.material.SetTexture("_TopSkin", container.TopTexture);
            liGo.renderer.material.SetTexture("_SideSkin", container.SideTexture);
            liGo.renderer.material.SetTexture("_BottomSkin", container.BottomTexture);
            liGo.renderer.material.SetTexture("_AO", container.AOTexture);
        }
        else if (tag == "Terrain")
        {
            var vertList = data[0] as Vector3[];
            var nrmList = data[1] as Vector3[];
            var uvList = data[2] as Vector2[];
            var indList = data[3] as int[];
            var texW = (int) data[4];
            var texH = (int) data[5];
            var itex = data[6] as int[];

            var mesh = new Mesh();
            mesh.vertices = vertList;
            mesh.normals = nrmList;
            mesh.uv = uvList;
            mesh.triangles = indList;
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();
            mesh.Optimize();

            var mf = container.GetComponent<MeshFilter>();
            mf.mesh = mesh;

            //Debug.Log(texW + " " + texH);
            var tex = new Texture2D(texW, texH);
            tex.filterMode = FilterMode.Point;
            tex.wrapMode = TextureWrapMode.Clamp;

            var tdata = new Color32[texW*texH];
            var handle = GCHandle.Alloc(tdata, GCHandleType.Pinned);
            Marshal.Copy(itex, 0, handle.AddrOfPinnedObject(), itex.Length);
            handle.Free();
            ////Debug.Log(String.Format("{0}:{1}:{2}:{3}", tdata[0].r, tdata[0].g, tdata[0].b, tdata[0].a));
            tex.SetPixels32(tdata);
            tex.Apply();

            if (container.AOTexture != null)
            {
                Destroy(container.AOTexture);
            }
            var cs = WorldGenerator.ChunkSize;
            container.AOTexture = new Texture3D(cs, cs, cs, TextureFormat.ARGB32, false);
            container.AOTexture.filterMode = FilterMode.Trilinear;
            container.AOTexture.wrapMode = TextureWrapMode.Clamp;
            container.AOTexture.SetPixels(aocol);
            container.AOTexture.Apply();

            //container.renderer.material = new Material(container.Shader);
            container.renderer.material = new Material(Shader);
            if (container.renderer.material.mainTexture != null)
            {
                Destroy(container.renderer.material.mainTexture);
            }
            container.renderer.material.mainTexture = tex;
            container.renderer.material.SetTexture("_TopSkin", container.TopTexture);
            container.renderer.material.SetTexture("_SideSkin", container.SideTexture);
            container.renderer.material.SetTexture("_BottomSkin", container.BottomTexture);
            container.renderer.material.SetTexture("_AO", container.AOTexture);
            container.renderer.material.SetVector("_ChunkPos", new Vector4(VX, VY, VZ));
            container.renderer.material.SetTexture("_Break", container.BreakTexture);
            container.renderer.material.SetTexture("_BreakCoords", container.breakCoords);
        }
    }
示例#34
0
 /// <summary>
 /// Enqueue's a message so it will be handeled
 /// </summary>
 /// <param name="information">The message information which needs to be enqueued</param>
 public void enqueueMessages(IProcessable information)
 {
     messageQueue.Enqueue(information);
 }
示例#35
0
 /// <summary>
 /// Creates a long running processer
 /// </summary>
 /// <param name="message"></param>
 private void longRunningProcessing(IProcessable message)
 {
     //ImmidiateTaskProcessor processor = new ImmidiateTaskProcessor(message);
     //processor.processMessage();
 }
示例#36
0
    private object AsyncProcess(IProcessable c, string tag, int thread)
    {
        var container = c as VoxelContainer;
        Dictionary<long, int> Voxels = null;
        if (tag == "Terrain")
        {
            Voxels = container.Solid;
        }
        else if (tag == "Liquid")
        {
            Voxels = container.Liquid;
        }

        if (Voxels.Count == 0) return null;

        int vcount = 0;
        int icount = 0;
        int texw = 0;
        int texh = 0;

        var keys = Voxels.Keys.ToArray();
        var vals = Voxels.Values.ToArray();
        var data = datas[thread];

        Stopwatch watch = new Stopwatch();
        watch.Start();
        Mesher.MeshVoxels(Voxels.Count, keys, vals,
            data.Vertices, data.Normals, data.UVs, data.Tris, ref vcount, ref icount, data.Tex, ref texw, ref texh, tag=="Liquid");
        watch.Stop();
        UnityEngine.Debug.Log(watch.Elapsed);

        if (tag == "Terrain")
        {
            var cs = WorldGenerator.ChunkSize;
            container.aocol = new Color[cs*cs*cs];
            for (int la = 0; la < cs*cs*cs; la++)
            {
                int x = la%cs;
                int y = (la/cs)%cs;
                int z = (la/(cs*cs));

                float val = container.CalcAO(x, y, z);
                //float val = 1;
                //val = z/15f;
                //float val = (x == 0 && y == 0 && z == 0) || (x == 1 && y==1 && z==1) ? 1 : 0;
                container.aocol[la] = new Color(val, val, val);
            }
        }

        return new object[] { data.GetVertices(vcount), data.GetNormals(vcount), data.GetUVs(vcount), data.GetTris(icount), texw, texh, data.GetTex(texw, texh) };
    }
示例#37
0
 internal static void processMessage(IProcessable information)
 {
     information.ProcessLogic();
 }
示例#38
0
 private void SyncGenerate(IProcessable c, string tag, object d)
 {
     var crd = d as int[];
     int vx, vy, vz;
     Utils.CoordChunkToVoxel(crd[0], 0, crd[1], out vx, out vy, out vz);
     for (int la = 0; la < 16; la++)
     {
         for (int lb = 0; lb < 16; lb++)
         {
             Generator.GenerateVoxelsForCoord(vx + la, vz + lb);
         }
     }
 }