Exemple #1
0
        //[TestCase(Description = "Test for restoring context with references.")]
        //public void DataRestoreContextTest()
        //{
        //    var f = new GenDataDef();
        //    f.AddSubClass("", "Parent");
        //    f.Classes[f.GetClassId("Parent")].AddInstanceProperty("Name");
        //    f.AddSubClass("Parent", "Class", "Definition");

        //    var d = new GenData(f);

        //    CreateGenObject(d, "", "Parent", "Minimal");
        //    ((SubClassReference)d.Context[1].GenObject.SubClass[0]).Reference = "Minimal";
        //    CreateGenObject(d, "", "Parent", "Basic");
        //    ((SubClassReference)d.Context[1].GenObject.SubClass[0]).Reference = "Basic";
        //    CreateGenObject(d, "", "Parent", "Definition");
        //    ((SubClassReference)d.Context[1].GenObject.SubClass[0]).Reference = "Definition";

        //    d.First(1);
        //    var o = d.Context[4].GenObject;
        //    var sc = d.SaveContext(4);
        //    Assert.AreEqual("minimal", o.GenDataBase.ToString());
        //    Assert.AreEqual("Minimal", d.Context[4].Reference);
        //    Assert.AreEqual("Minimal", d.Context[3].Reference);
        //    Assert.AreEqual("Minimal", d.Context[2].Reference);
        //    Assert.AreEqual("", d.Context[1].Reference);
        //    d.Last(1);
        //    Assert.AreEqual("definition", d.Context[4].GenObject.GenDataBase.ToString());
        //    Assert.AreEqual("Definition", d.Context[4].Reference);
        //    Assert.AreEqual("Definition", d.Context[3].Reference);
        //    Assert.AreEqual("Definition", d.Context[2].Reference);
        //    Assert.AreEqual("", d.Context[1].Reference);
        //    sc.EstablishContext();
        //    Assert.AreSame(o, d.Context[4].GenObject);
        //    Assert.AreEqual("Minimal", d.Context[4].Reference);
        //    Assert.AreEqual("Minimal", d.Context[3].Reference);
        //    Assert.AreEqual("Minimal", d.Context[2].Reference);
        //    Assert.AreEqual("", d.Context[1].Reference);
        //}

        private static void Navigate(GenData d, int classId)
        {
            d.First(classId);
            while (!d.Eol(classId))
            {
                foreach (GenDataDefSubClass subClass in d.Context[classId].DefClass.SubClasses)
                {
                    Navigate(d, subClass.SubClass.ClassId);
                }
                d.Next(classId);
            }
        }
        private static void GenerateSurfPoint(object obj)
        {
            GenData data = (GenData)obj;

            if (data.storeState.manager.Cancelled)
            {
                return;
            }
            //Debug.Log("Starting point: " + data.altitude + "/" + data.speed);
            EnvelopePoint result = new EnvelopePoint(data.vessel, data.conditions.body, data.altitude, data.speed, data.AoA_guess, data.maxA_guess, data.pitchI_guess);

            //Debug.Log("Point solved: " + data.altitude + "/" + data.speed);

            data.storeState.StoreResult(result);
        }
        private static void ContinueInBackground(object obj)
        {
            object[] inObj    = (object[])obj;
            GenData  rootData = (GenData)inObj[0];

            CalculationManager.State[,] results = (CalculationManager.State[, ])inObj[1];
            CalculationManager manager = rootData.storeState.manager;

            GenerateLevel(rootData.conditions, manager, ref results, rootData.vessel);
            if (rootData.storeState.manager.Cancelled)
            {
                return;
            }
            rootData.storeState.StoreResult(results);
        }
        private static void GenerateLevel(Conditions conditions, CalculationManager manager, ref CalculationManager.State[,] results, AeroPredictor vessel, Conditions basisConditions = new Conditions(), EnvelopePoint[,] resultPoints = null)
        {
            float[,] AoAs_guess = null, maxAs_guess = null, pitchIs_guess = null;
            if (resultPoints != null)
            {
                AoAs_guess    = resultPoints.SelectToArray(pt => pt.AoA_level);
                maxAs_guess   = resultPoints.SelectToArray(pt => pt.AoA_max);
                pitchIs_guess = resultPoints.SelectToArray(pt => pt.pitchInput);
            }
            else if (results != null)
            {
                AoAs_guess    = results.SelectToArray(pt => ((EnvelopePoint)pt.Result).AoA_level);
                maxAs_guess   = results.SelectToArray(pt => ((EnvelopePoint)pt.Result).AoA_max);
                pitchIs_guess = results.SelectToArray(pt => ((EnvelopePoint)pt.Result).pitchInput);
                resultPoints  = results.SelectToArray(pt => (EnvelopePoint)pt.Result);
            }
            int   numPtsX   = (int)Math.Ceiling((conditions.upperBoundSpeed - conditions.lowerBoundSpeed) / conditions.stepSpeed);
            int   numPtsY   = (int)Math.Ceiling((conditions.upperBoundAltitude - conditions.lowerBoundAltitude) / conditions.stepAltitude);
            float trueStepX = (conditions.upperBoundSpeed - conditions.lowerBoundSpeed) / numPtsX;
            float trueStepY = (conditions.upperBoundAltitude - conditions.lowerBoundAltitude) / numPtsY;

            results = new CalculationManager.State[numPtsX + 1, numPtsY + 1];

            for (int j = 0; j <= numPtsY; j++)
            {
                for (int i = 0; i <= numPtsX; i++)
                {
                    if (manager.Cancelled)
                    {
                        return;
                    }
                    float x         = (float)i / numPtsX;
                    float y         = (float)j / numPtsY;
                    float aoa_guess = AoAs_guess != null?AoAs_guess.Lerp2(x, y) : float.NaN;

                    float maxA_guess = maxAs_guess != null?maxAs_guess.Lerp2(x, y) : float.NaN;

                    float pi_guess = pitchIs_guess != null?pitchIs_guess.Lerp2(x, y) : float.NaN;

                    float   speed    = conditions.lowerBoundSpeed + trueStepX * i;
                    float   altitude = conditions.lowerBoundAltitude + trueStepY * j;
                    GenData genData  = new GenData(vessel, conditions, speed, altitude, manager, aoa_guess, maxA_guess, pi_guess);
                    results[i, j] = genData.storeState;
                    if (!basisConditions.Equals(Conditions.Blank) && !basisConditions.Equals(new Conditions()) &&
                        basisConditions.Contains(speed, altitude, out int ii, out int jj))
                    {
                        results[i, j].StoreResult(resultPoints[ii, jj]);
                    }
Exemple #5
0
        private void GenerateRegion(object o)
        {
            GenData genData = o as GenData;

            for (int y = genData.Area.Top; y < genData.Area.Bottom; ++y)
            {
                for (int x = genData.Area.Left; x < genData.Area.Right; ++x)
                {
                    float height = GenerateHeight(x, y);

                    Data[x, y] = new MapData(height);
                }
            }

            genData.Generated = true;
        }
        private IEnumerator Processing(CalculationManager manager, Conditions conditions, AeroPredictor vessel)
        {
            int numPtsX = (int)Math.Ceiling((conditions.upperBoundSpeed - conditions.lowerBoundSpeed) / conditions.stepSpeed);
            int numPtsY = (int)Math.Ceiling((conditions.upperBoundAltitude - conditions.lowerBoundAltitude) / conditions.stepAltitude);

            EnvelopePoint[,] newEnvelopePoints = new EnvelopePoint[numPtsX + 1, numPtsY + 1];

            GenData rootData = new GenData(vessel, conditions, 0, 0, manager);

            //System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            //timer.Start();
            ThreadPool.QueueUserWorkItem(SetupInBackground, rootData, true);

            while (!manager.Completed)
            {
                //Debug.Log(manager.PercentComplete + "% done calculating...");
                if (manager.Status == CalculationManager.RunStatus.Cancelled)
                {
                    yield break;
                }
                yield return(0);
            }
            //timer.Stop();
            //Debug.Log("Time taken: " + timer.ElapsedMilliseconds / 1000f);

            newEnvelopePoints = ((CalculationManager.State[, ])rootData.storeState.Result)
                                .SelectToArray(pt => (EnvelopePoint)pt.Result);

            AddToCache(conditions, newEnvelopePoints);
            if (!manager.Cancelled)
            {
                envelopePoints    = newEnvelopePoints;
                currentConditions = conditions;
                UpdateGraphs();
                CalculateOptimalLines(vessel, conditions, WindTunnelWindow.Instance.TargetSpeed, WindTunnelWindow.Instance.TargetAltitude, 0, 0);

                valuesSet = true;
            }
            yield return(0);

            if (!manager.Cancelled)
            {
                Conditions nextConditions = conditions.Modify(stepSpeed: conditions.stepSpeed / 2, stepAltitude: conditions.stepAltitude / 2);
                WindTunnel.Instance.StartCoroutine(RefinementProcessing(calculationManager, nextConditions, vessel, newEnvelopePoints, conditions));
            }
        }
Exemple #7
0
        private static string SetZipTemplate(string starterTemplate, GenData genData)
        {
            string ZIPHEAD = "//#ZIPHEAD";
            string ZIPBODY = "//#ZIPBODY";
            string head    = genData.CompressProvider.Provider.GetHeadTemplate();
            string body    = genData.CompressProvider.Provider.GetBodyTemplate();

            if (head != null)
            {
                starterTemplate = starterTemplate.Replace(ZIPHEAD, head);
            }
            if (body != null)
            {
                starterTemplate = starterTemplate.Replace(ZIPBODY, body);
            }
            return(starterTemplate);
        }
        private static void ContinueInBackground(object obj)
        {
            object[] inObj    = (object[])obj;
            GenData  rootData = (GenData)inObj[0];

            CalculationManager.State[,] results = (CalculationManager.State[, ])inObj[1];
            EnvelopePoint[,] basisData          = inObj.Length > 2 ? (EnvelopePoint[, ])inObj[2] : null;
            Conditions         basisConditions = inObj.Length > 3 ? (Conditions)inObj[3] : new Conditions();
            CalculationManager manager         = rootData.storeState.manager;

            GenerateLevel(rootData.conditions, manager, ref results, rootData.vessel, basisConditions, basisData);
            if (rootData.storeState.manager.Cancelled)
            {
                return;
            }
            rootData.storeState.StoreResult(results);
        }
        private IEnumerator RefinementProcessing(CalculationManager manager, Conditions conditions, AeroPredictor vessel, EnvelopePoint[,] basisData, Conditions basisConditions = new Conditions(), Queue <Conditions> followOnConditions = null, bool forcePushToGraph = false)
        {
            int numPtsX = (int)Math.Ceiling((conditions.upperBoundSpeed - conditions.lowerBoundSpeed) / conditions.stepSpeed);
            int numPtsY = (int)Math.Ceiling((conditions.upperBoundAltitude - conditions.lowerBoundAltitude) / conditions.stepAltitude);

            EnvelopePoint[,] newEnvelopePoints = new EnvelopePoint[numPtsX + 1, numPtsY + 1];

            CalculationManager backgroundManager = new CalculationManager();

            manager.OnCancelCallback           += backgroundManager.Cancel;
            CalculationManager.State[,] results = new CalculationManager.State[numPtsX + 1, numPtsY + 1];
            GenData rootData = new GenData(vessel, conditions, 0, 0, backgroundManager);

            ThreadPool.QueueUserWorkItem(ContinueInBackground, new object[] { rootData, results, basisData, basisConditions });
            while (!backgroundManager.Completed)
            {
                if (manager.Status == CalculationManager.RunStatus.Cancelled)
                {
                    backgroundManager.Cancel();
                    yield break;
                }
                yield return(0);
            }
            manager.OnCancelCallback -= backgroundManager.Cancel;

            newEnvelopePoints = ((CalculationManager.State[, ])rootData.storeState.Result)
                                .SelectToArray(pt => (EnvelopePoint)pt.Result);

            AddToCache(conditions, newEnvelopePoints);
            if (currentConditions.Equals(conditions) || (forcePushToGraph && !backgroundManager.Cancelled))
            {
                envelopePoints    = newEnvelopePoints;
                currentConditions = conditions;
                UpdateGraphs();
                valuesSet = true;
            }
            backgroundManager.Dispose();
            if (!manager.Cancelled && followOnConditions != null && followOnConditions.Count > 0)
            {
                yield return(0);

                Conditions nextConditions = followOnConditions.Dequeue();
                WindTunnel.Instance.StartCoroutine(RefinementProcessing(manager, nextConditions, vessel, newEnvelopePoints, conditions, followOnConditions, forcePushToGraph));
            }
        }
Exemple #10
0
            public async Task Should_return_empty_kind_does_not_exist()
            {
                //Arrange
                GenData.RepeatCount = 3;
                List <Video> expectedVideos = new List <Video>(GenData.RepeatCount);

                GenData.AddManyTo(expectedVideos, TestDataFactory.CreateVideo);

                using (VODContext context = ContextFactory.CreateContext())
                {
                    context.Videos.AddRange(expectedVideos);
                    context.SaveChanges();
                }

                //Act
                IEnumerable <Video> result = await RepoUnderTest.GetVideosByKindIdAsync(Guid.NewGuid());

                //Assert
                Assert.Empty(result);
            }
Exemple #11
0
            public async Task Should_return_all_genres()
            {
                //Arrange
                GenData.RepeatCount = 3;
                List <Genre> expectedGenres = new List <Genre>(GenData.RepeatCount);

                GenData.AddManyTo(expectedGenres, TestDataFactory.CreateGenre);

                using (VODContext context = ContextFactory.CreateContext())
                {
                    context.Genres.AddRange(expectedGenres);
                    context.SaveChanges();
                }

                //Act
                IEnumerable <Genre> result = await RepoUnderTest.GetAsync();

                //Assert
                result.Should().BeEquivalentTo(expectedGenres);
            }
Exemple #12
0
        private IEnumerator Processing(CalculationManager manager, Conditions conditions, AeroPredictor vessel)
        {
            int numPts = (int)Math.Ceiling((conditions.upperBound - conditions.lowerBound) / conditions.step);

            AoAPoint[] newAoAPoints = new AoAPoint[numPts + 1];
            float      trueStep     = (conditions.upperBound - conditions.lowerBound) / numPts;

            CalculationManager.State[] results = new CalculationManager.State[numPts + 1];

            for (int i = 0; i <= numPts; i++)
            {
                //newAoAPoints[i] = new AoAPoint(vessel, conditions.body, conditions.altitude, conditions.speed, conditions.lowerBound + trueStep * i);
                GenData genData = new GenData(vessel, conditions, conditions.lowerBound + trueStep * i, manager);
                results[i] = genData.storeState;
                ThreadPool.QueueUserWorkItem(GenerateAoAPoint, genData);
            }

            while (!manager.Completed)
            {
                if (manager.Status == CalculationManager.RunStatus.Cancelled)
                {
                    yield break;
                }
                yield return(0);
            }

            for (int i = 0; i <= numPts; i++)
            {
                newAoAPoints[i] = (AoAPoint)results[i].Result;
            }
            if (!manager.Cancelled)
            {
                cache.Add(conditions, newAoAPoints);
                AoAPoints         = newAoAPoints;
                AverageLiftSlope  = AoAPoints.Select(pt => pt.dLift / pt.dynamicPressure).Where(v => !float.IsNaN(v) && !float.IsInfinity(v)).Average();
                currentConditions = conditions;
                UpdateGraphs();
                valuesSet = true;
            }
        }
Exemple #13
0
    public static string Print(this GenData target, bool simple = true)
    {
        if (simple)
        {
            PrintCount++;
            GenTile[,] tile = target.TileMap;
            StringBuilder sb = new StringBuilder();

            for (int y = 0; y < tile.GetLength(1); y++)
            {
                for (int x = 0; x < tile.GetLength(0); x++)
                {
                    if (tile[x, y] == null)
                    {
                        sb.Append(' ');
                        continue;
                    }
                    int       max    = tile[x, y].Details.Max(d => d.Priority);
                    GenDetail toDraw = tile[x, y].Details.Where(d => d.Priority == max).First();

                    sb.Append(toDraw.Char);
                }
                //sb.Append('\n');
            }

            return(sb.ToString());
        }
        else
        {
            GenTile[,] work = new GenTile[target.Width, target.Height];

            foreach (var room in target.Rooms)
            {
                work.Place(room.PosX, room.PosY, room.Data);
            }

            target.TileMap = work;
            return(Print(target));
        }
    }
Exemple #14
0
            public async Task Should_return_all_videos()
            {
                //Arrange
                GenData.RepeatCount = 3;
                List <Video> expectedVideos = new List <Video>(GenData.RepeatCount);

                GenData.AddManyTo(expectedVideos, TestDataFactory.CreateVideo);

                using (VODContext context = ContextFactory.CreateContext())
                {
                    context.Videos.AddRange(expectedVideos);
                    context.SaveChanges();
                }

                //Act
                IEnumerable <Video> result = await RepoUnderTest.GetAsync();

                //Assert
                result.Should().BeEquivalentTo(expectedVideos, o =>
                                               o.Excluding(x => x.Kind)
                                               .Excluding(x => x.Genre));
            }
Exemple #15
0
        private IEnumerator Processing(CalculationManager manager, Conditions conditions, AeroPredictor vessel)
        {
            int numPts = (int)Math.Ceiling((conditions.upperBound - conditions.lowerBound) / conditions.step);

            VelPoint[] newVelPoints = new VelPoint[numPts + 1];
            float      trueStep     = (conditions.upperBound - conditions.lowerBound) / numPts;

            CalculationManager.State[] results = new CalculationManager.State[numPts + 1];

            for (int i = 0; i <= numPts; i++)
            {
                //newAoAPoints[i] = new AoAPoint(vessel, conditions.body, conditions.altitude, conditions.speed, conditions.lowerBound + trueStep * i);
                GenData genData = new GenData(vessel, conditions, conditions.lowerBound + trueStep * i, manager);
                results[i] = genData.storeState;
                ThreadPool.QueueUserWorkItem(GenerateVelPoint, genData);
            }

            while (!manager.Completed)
            {
                if (manager.Status == CalculationManager.RunStatus.Cancelled)
                {
                    yield break;
                }
                yield return(0);
            }

            for (int i = 0; i <= numPts; i++)
            {
                newVelPoints[i] = (VelPoint)results[i].Result;
            }
            if (!manager.Cancelled)
            {
                cache.Add(conditions, newVelPoints);
                VelPoints         = newVelPoints;
                currentConditions = conditions;
                GenerateGraphs();
                valuesSet = true;
            }
        }
Exemple #16
0
    public IEnumerator CornerCheck()
    {
        GenData dat = new GenData(20, 15);

        GenRoom r1 = GenRoom.Sized(8, 8);

        r1.FillFloor('.');
        r1.SpacePriority = 2;
        dat.PlaceRoom(0, 0, r1);

        GenRoom r2 = GenRoom.Sized(10, 7);

        r2.FillFloor('.');
        r2.SpacePriority = 1;
        dat.PlaceRoom(5, 4, r2);

        dat.FixOverlap();
        dat.EdgeWalls('#');

        TestDrawer.text = dat.Print(false);
        yield return(new WaitForSeconds(0.5f));

        for (int x = 0; x < 20; x++)
        {
            for (int y = 0; y < 15; y++)
            {
                if (dat.IsCornerG(x, y))
                {
                    GenRoom corner = GenRoom.Sized(1, 1);
                    corner.FillFloor('X');
                    dat.PlaceRoom(x, y, corner);

                    TestDrawer.text = dat.Print(false);
                    yield return(new WaitForSeconds(0.25f));
                }
            }
        }
    }
        private static void GenerateLevel(Conditions conditions, CalculationManager manager, ref CalculationManager.State[,] results, AeroPredictor vessel)
        {
            float[,] AoAs_guess = null, maxAs_guess = null, pitchIs_guess = null;
            if (results != null)
            {
                AoAs_guess    = results.SelectToArray(pt => ((EnvelopePoint)pt.Result).AoA_level);
                maxAs_guess   = results.SelectToArray(pt => ((EnvelopePoint)pt.Result).AoA_max);
                pitchIs_guess = results.SelectToArray(pt => ((EnvelopePoint)pt.Result).pitchInput);
            }
            int   numPtsX   = (int)Math.Ceiling((conditions.upperBoundSpeed - conditions.lowerBoundSpeed) / conditions.stepSpeed);
            int   numPtsY   = (int)Math.Ceiling((conditions.upperBoundAltitude - conditions.lowerBoundAltitude) / conditions.stepAltitude);
            float trueStepX = (conditions.upperBoundSpeed - conditions.lowerBoundSpeed) / numPtsX;
            float trueStepY = (conditions.upperBoundAltitude - conditions.lowerBoundAltitude) / numPtsY;

            results = new CalculationManager.State[numPtsX + 1, numPtsY + 1];

            for (int j = 0; j <= numPtsY; j++)
            {
                for (int i = 0; i <= numPtsX; i++)
                {
                    if (manager.Cancelled)
                    {
                        return;
                    }
                    float x         = (float)i / numPtsX;
                    float y         = (float)j / numPtsY;
                    float aoa_guess = AoAs_guess != null?AoAs_guess.Lerp2(x, y) : float.NaN;

                    float maxA_guess = maxAs_guess != null?maxAs_guess.Lerp2(x, y) : float.NaN;

                    float pi_guess = pitchIs_guess != null?pitchIs_guess.Lerp2(x, y) : float.NaN;

                    GenData genData = new GenData(vessel, conditions, conditions.lowerBoundSpeed + trueStepX * i, conditions.lowerBoundAltitude + trueStepY * j, manager, aoa_guess, maxA_guess, pi_guess);
                    results[i, j] = genData.storeState;
                    ThreadPool.QueueUserWorkItem(GenerateSurfPoint, genData);
                }
            }
        }
        private static void SetupInBackground(object obj)
        {
            GenData            rootData    = (GenData)obj;
            Conditions         conditions  = rootData.conditions;
            CalculationManager manager     = rootData.storeState.manager;
            CalculationManager seedManager = new CalculationManager();

            CalculationManager.State[,] results = null;

            Conditions seedConditions = new Conditions(conditions.body, conditions.lowerBoundSpeed, conditions.upperBoundSpeed, 10, conditions.lowerBoundAltitude, conditions.upperBoundAltitude, 10);

            GenerateLevel(seedConditions, seedManager, ref results, rootData.vessel);

            seedManager.WaitForCompletion();

            GenerateLevel(conditions, manager, ref results, rootData.vessel);

            if (rootData.storeState.manager.Cancelled)
            {
                return;
            }
            rootData.storeState.StoreResult(results);
        }
Exemple #19
0
            public async Task Should_return_empty_collection()
            {
                //Arrange
                Genre notIncludedGenre = TestDataFactory.CreateGenre();

                GenData.RepeatCount = 3;
                List <Video> videos = new List <Video>(GenData.RepeatCount);

                GenData.AddManyTo(videos, TestDataFactory.CreateVideo);

                using (VODContext context = ContextFactory.CreateContext())
                {
                    context.Videos.AddRange(videos);
                    context.Genres.Add(notIncludedGenre);
                    context.SaveChanges();
                }

                //Act
                IEnumerable <Video> result = await RepoUnderTest.GetVideosByGenreIdAsync(notIncludedGenre.Id);

                //Assert
                Assert.Empty(result);
            }
Exemple #20
0
            public async Task Should_not_return_inactive_videos()
            {
                //Arrange
                GenData.RepeatCount = 3;
                List <Video> videos = new List <Video>(GenData.RepeatCount);

                GenData.AddManyTo(videos, TestDataFactory.CreateVideo);
                videos.Last().IsInactive = true;

                using (VODContext context = ContextFactory.CreateContext())
                {
                    context.Videos.AddRange(videos);
                    context.SaveChanges();
                }

                List <Video> expectedVideos = videos.Take(2).ToList();

                //Act
                IEnumerable <Video> result = await RepoUnderTest.GetAsync();

                //Assert
                result.Any(x => x.IsInactive).Should().BeFalse();
            }
Exemple #21
0
            public async Task Should_return_videos_with_specified_title()
            {
                //Arrange
                string expectedTitle = "Expected Title";
                string titleToSearch = "EXPected";

                Video expectedVideo0 = TestDataFactory.CreateVideo();

                expectedVideo0.Title = expectedTitle;
                Video expectedVideo1 = TestDataFactory.CreateVideo();

                expectedVideo1.Title = expectedTitle;
                List <Video> videos = new List <Video>(2)
                {
                    expectedVideo0,
                    expectedVideo1
                };

                GenData.RepeatCount = 3;
                GenData.AddManyTo(videos, () => TestDataFactory.CreateVideo());

                using (VODContext context = ContextFactory.CreateContext())
                {
                    context.Videos.AddRange(videos);
                    context.SaveChanges();
                }

                List <Video> expectedVideos = videos.Take(2).ToList();

                //Act
                IEnumerable <Video> result = await RepoUnderTest.GetVideosContainTitleAsync(titleToSearch);

                //Assert
                result.Should().BeEquivalentTo(expectedVideos, o =>
                                               o.Excluding(x => x.Kind)
                                               .Excluding(x => x.Genre));
            }
Exemple #22
0
 public static GenTile GetTileAtG(int gx, int gy, GenData data)
 {
     return(GetTileAtG(gx, gy, data.Rooms.ToArray()));
 }
        void SetRegistry()
        {
            Registry registry = Registry.Instance;

            registry.Add(new Ping(), Ping.Parser, (int)PacketType.Ping,
                         (IMessage message) => {
                Ping ping = (Ping)message;
                client.Send(ping);
            });
            registry.Add(new RegistrationViewerRequest(), RegistrationViewerRequest.Parser, (int)PacketType.RegistrationViewerRequest, null);
            registry.Add(new RegistrationViewerResponse(), RegistrationViewerResponse.Parser, (int)PacketType.RegistrationViewerResponse,
                         (IMessage message) => {
                RegistrationViewerResponse res = (RegistrationViewerResponse)message;
                if (res.Result == Result.Success)
                {
                    Console.WriteLine("Registration Viewer success");

                    StreamingStartRequest req = new StreamingStartRequest()
                    {
                        AccessToken = "access_token",
                        Serial      = "office",
                        Uts         = 0
                    };
                    client.Send(req);
                }
                else
                {
                    Console.WriteLine("Registration Viewer failed, " + res.Result);
                }
            });
            registry.Add(new StreamingStartRequest(), StreamingStartRequest.Parser, (int)PacketType.StreamingStartRequest, null);
            registry.Add(new StreamingStartResponse(), StreamingStartResponse.Parser, (int)PacketType.StreamingStartResponse,
                         (IMessage message) => {
                StreamingStartResponse res = (StreamingStartResponse)message;
                if (res.Result == Result.Success)
                {
                    Console.WriteLine("streaming start success");
                }
                else
                {
                    Console.WriteLine("streaming start failed, " + res.Result);
                }
            });
            registry.Add(new StreamingStopRequest(), StreamingStopRequest.Parser, (int)PacketType.StreamingStopRequest, null);
            registry.Add(new StreamingStopResponse(), StreamingStopResponse.Parser, (int)PacketType.StreamingStopResponse,
                         (IMessage message) => {
                StreamingStopResponse res = (StreamingStopResponse)message;
                Console.WriteLine("StreamingStopResponse() called. " + res.Result);
            });
            registry.Add(new VideoInitFrame(), VideoInitFrame.Parser, (int)PacketType.VideoInitFrame,
                         (IMessage message) => {
                VideoInitFrame videoInitFrame = (VideoInitFrame)message;

                Int32 width   = (Int32)videoInitFrame.Width;
                Int32 height  = (Int32)videoInitFrame.Height;
                Int32 fps     = (Int32)videoInitFrame.FramePerSecond;
                byte[] spspps = videoInitFrame.Spspps.ToByteArray();

                Console.WriteLine(spspps.Length);
                if (recentWidth != width || recentHeight != height)
                {
                    FFMpegCodecDecInit(1, width, height);
                    recentWidth  = width;
                    recentHeight = height;
                }

                FFMpegCodecDecExecute(1, spspps, spspps.Length);

                Console.WriteLine("VideoInitFrame. uts=" + videoInitFrame.UtsMs);
            });
            registry.Add(new VideoFrame(), VideoFrame.Parser, (int)PacketType.VideoFrame,
                         (IMessage message) => {
                VideoFrame videoFrame = (VideoFrame)message;
                Console.WriteLine("VideoFrame. uts=" + videoFrame.UtsMs);

                byte[] frame = videoFrame.Frame.ToByteArray();
                Console.WriteLine(frame.Length);
                if (recentWidth != 0 && recentHeight != 0)
                {
                    IntPtr RGB24 = FFMpegCodecDecExecute(1, frame, frame.Length);
                    int length   = 1280 * 720 * 3 + 54;
                    if (RGB24 != IntPtr.Zero)
                    {
                        lock (mList) {
                            mList.Add(new FrameData(1, RGB24, length));
                        }
                    }
                }
            });
            registry.Add(new GenData(), GenData.Parser, (int)PacketType.GenData,
                         (IMessage message) => {
                GenData data = (GenData)message;
                Console.WriteLine("GenData() called" + data.ToString());
            });
            registry.Add(new GenDataStartRequest(), GenDataStartRequest.Parser, (int)PacketType.GenDataStartRequest, null);
            registry.Add(new GenDataStartResponse(), GenDataStartResponse.Parser, (int)PacketType.GenDataStartResponse,
                         (IMessage message) => {
                GenDataStartResponse res = (GenDataStartResponse)message;
            });
            registry.Add(new GenDataStopRequest(), GenDataStopRequest.Parser, (int)PacketType.GenDataStopRequest, null);
            registry.Add(new GenDataStopResponse(), GenDataStopResponse.Parser, (int)PacketType.GenDataStopResponse,
                         (IMessage message) => {
                GenDataStopResponse res = (GenDataStopResponse)message;
            });
        }
Exemple #24
0
        public void ConsecutiveDataLoadTest()
        {
            var f = new GenDataDef();

            f.AddSubClass("", "Parent");
            f.AddClassInstanceProperty(f.GetClassId("Parent"), "Name");
            f.AddSubClass("Parent", "Class", "Definition");

            var d       = new GenData(f);
            var minimal = LoadGenData("Minimal");

            minimal.Last(1);
            Assert.AreEqual("Property", minimal.Context[1].GenObject.Attributes[0]);
            Assert.AreEqual(1, minimal.Context[3].Count);
            var basic = LoadGenData("Basic");

            basic.Last(1);
            Assert.AreEqual("Property", basic.Context[1].GenObject.Attributes[0]);
            Assert.AreEqual(2, basic.Context[3].Count);
            var definition = LoadGenData("Definition");

            definition.Last(1);
            Assert.AreEqual("Property", definition.Context[1].GenObject.Attributes[0]);
            Assert.AreEqual(7, definition.Context[3].Count);
            Assert.AreSame(minimal, d.Cache.Internal("definition", "Minimal", minimal));
            Assert.AreSame(basic, d.Cache.Internal("definition", "Basic", basic));
            var newDefinition = d.Cache.Internal("definition", "Definition", definition);

            Assert.AreNotSame(definition, newDefinition);
            Assert.AreSame(minimal, d.Cache.Internal("definition", "Minimal", minimal));
            Assert.AreSame(basic, d.Cache.Internal("definition", "Basic", basic));
            Assert.AreSame(newDefinition, d.Cache.Internal("definition", "Definition", definition));
            Assert.AreSame(minimal, d.Cache["Minimal"]);
            Assert.AreSame(basic, d.Cache["Basic"]);
            Assert.AreSame(newDefinition, d.Cache["Definition"]);
            d.Cache.Merge();

            CreateGenObject(d, d.Root, "Parent", "Minimal");
            ((SubClassReference)d.Context[1].GenObject.SubClass[0]).Reference = "Minimal";
            CreateGenObject(d, d.Root, "Parent", "Basic");
            ((SubClassReference)d.Context[1].GenObject.SubClass[0]).Reference = "Basic";
            CreateGenObject(d, d.Root, "Parent", "Definition");
            ((SubClassReference)d.Context[1].GenObject.SubClass[0]).Reference = "Definition";

            d.First(1);
            Assert.AreEqual("Minimal", d.Context[2].Reference);
            Assert.AreSame(minimal.GenDataBase, d.Context[2].GenObject.GenDataBase);
            d.Last(2);
            Assert.AreEqual("Property", d.Context[2].GenObject.Attributes[0]);
            Assert.AreEqual(1, d.Context[4].Count);
            d.Next(1);
            Assert.AreEqual("Basic", d.Context[2].Reference);
            Assert.AreSame(basic.GenDataBase, d.Context[2].GenObject.GenDataBase);
            d.Last(2);
            Assert.AreEqual("Property", d.Context[2].GenObject.Attributes[0]);
            Assert.AreEqual(2, d.Context[4].Count);
            d.Next(1);
            Assert.AreEqual("Definition", d.Context[2].Reference);
            Assert.AreSame(newDefinition.GenDataBase, d.Context[2].GenObject.GenDataBase);
            d.Last(2);
            Assert.AreEqual("Property", d.Context[2].GenObject.Attributes[0]);
            Assert.AreEqual(7, d.Context[4].Count);
            d.First(0);
        }
Exemple #25
0
 public StarterGen(GenData genData)
 {
     this.genData = genData;
 }
Exemple #26
0
    public IEnumerator RunGenerationTest()
    {
        GenUtil.PrintCount = 0;
        GenData sym = new GenData(20, 15);

        GenRoom Hallway = GenRoom.Sized(15, 5);

        Hallway.FillFloor('.');
        Hallway.SpacePriority = 2;
        sym.PlaceRoom(1, 1, Hallway);

        TestDrawer.text = sym.Print(false);
        yield return(new WaitForSeconds(1f));


        GenRoom OtherRooom = GenRoom.Sized(8, 10);

        OtherRooom.FillFloor('.');
        OtherRooom.SpacePriority = 3;
        sym.PlaceRoom(11, 3, OtherRooom);

        TestDrawer.text = sym.Print(false);
        yield return(new WaitForSeconds(1f));

        sym.EdgeWalls('#');

        TestDrawer.text = sym.Print(false);
        yield return(new WaitForSeconds(1f));

        OtherRooom.SpacePriority = 1;
        sym.FixOverlap();

        TestDrawer.text = sym.Print(false);
        yield return(new WaitForSeconds(1f));



        int wantX = 3;
        int wantY = 2;

        bool done = false;

        while (!done)
        {
            var got = Hallway.GetAtWorldspaceG(wantX, wantY);

            if (!sym.IsInsideRoom(wantX, wantY))
            {
                done = true;
            }
            else
            {
                GenTile tile = GenTile.GetEmpty();
                tile.Details.Add(new GenDetail()
                {
                    Type = GenDetail.DetailType.Decoration, Char = 'O'
                });
                GenTile[,] feature = new GenTile[, ]
                {
                    { tile }
                };

                int fposX = wantX;
                int fposY = wantY;

                GenTile[,] final = GenUtil.GetSymetry(feature, ref fposX, ref fposY, Hallway, GenUtil.Axis.Vertical);

                Hallway.SetTilesAtG(fposX, fposY, final);

                TestDrawer.text = sym.Print(false);
                yield return(new WaitForSeconds(0.5f));


                wantX += 2;
            }
        }

        for (int x = 0; x < 20; x++)
        {
            for (int y = 0; y < 15; y++)
            {
                if (sym.IsCornerG(x, y, GenDetail.DetailType.Wall, GenDetail.DetailType.Decoration))
                {
                    GenRoom corner = GenRoom.Sized(1, 1);
                    corner.FillFloor('X');
                    sym.PlaceRoom(x, y, corner);

                    TestDrawer.text = sym.Print(false);
                    yield return(new WaitForSeconds(0.25f));
                }
            }
        }



        /*
         * GenData data = new GenData(40, 20);
         *
         * GenRoom startRoom = GenRoom.Sized(5,8,true);
         * startRoom.SpacePriority = 0;
         *
         * GenRoom room2 = GenRoom.Sized(8, 8, true);
         * room2.FillFloor('a');
         *
         * GenRoom room3 = GenRoom.Sized(5, 5, true);
         * room3.FillFloor('b');
         * room3.SpacePriority = 2;
         *
         * GenRoom room4 = GenRoom.Sized(10, 10, true);
         * room4.FillFloor('c');
         *
         * data.PlaceRoom(1, 0, startRoom);
         * data.PlaceRoom(4, 1, room2);
         * data.PlaceRoom(25, 11, room3);
         * data.PlaceRoom(23, 3, room4);
         *
         * data.FixOverlap();
         * data.EdgeWalls('#');
         *
         * data.Print(false);
         */
    }
        private IEnumerator Processing(CalculationManager manager, Conditions conditions, AeroPredictor vessel)
        {
            int numPtsX = (int)Math.Ceiling((conditions.upperBoundSpeed - conditions.lowerBoundSpeed) / conditions.stepSpeed);
            int numPtsY = (int)Math.Ceiling((conditions.upperBoundAltitude - conditions.lowerBoundAltitude) / conditions.stepAltitude);

            EnvelopePoint[,] newEnvelopePoints = new EnvelopePoint[numPtsX + 1, numPtsY + 1];

            GenData rootData = new GenData(vessel, conditions, 0, 0, manager);

            ThreadPool.QueueUserWorkItem(SetupInBackground, rootData);

            while (!manager.Completed)
            {
                //Debug.Log(manager.PercentComplete + "% done calculating...");
                if (manager.Status == CalculationManager.RunStatus.Cancelled)
                {
                    yield break;
                }
                yield return(0);
            }

            newEnvelopePoints = ((CalculationManager.State[, ])rootData.storeState.Result)
                                .SelectToArray(pt => (EnvelopePoint)pt.Result);

            if (!manager.Cancelled)
            {
                //cache.Add(conditions, newEnvelopePoints);
                AddToCache(conditions, newEnvelopePoints);
                envelopePoints    = newEnvelopePoints;
                currentConditions = conditions;
                GenerateGraphs();
                valuesSet = true;
            }

            float stepSpeed = conditions.stepSpeed, stepAltitude = conditions.stepAltitude;

            for (int i = 2; i <= 2; i++)
            {
                yield return(0);

                CalculationManager backgroundManager = new CalculationManager();
                manager.OnCancelCallback += backgroundManager.Cancel;
                conditions = new Conditions(conditions.body, conditions.lowerBoundSpeed, conditions.upperBoundSpeed,
                                            stepSpeed / i, conditions.lowerBoundAltitude, conditions.upperBoundAltitude, stepAltitude / i);
                CalculationManager.State[,] prevResults = ((CalculationManager.State[, ])rootData.storeState.Result).SelectToArray(p => p);
                rootData = new GenData(vessel, conditions, 0, 0, backgroundManager);
                ThreadPool.QueueUserWorkItem(ContinueInBackground, new object[] { rootData, prevResults });
                while (!backgroundManager.Completed)
                {
                    if (manager.Status == CalculationManager.RunStatus.Cancelled)
                    {
                        backgroundManager.Cancel();
                        yield break;
                    }
                    yield return(0);
                }

                newEnvelopePoints = ((CalculationManager.State[, ])rootData.storeState.Result)
                                    .SelectToArray(pt => (EnvelopePoint)pt.Result);

                if (!manager.Cancelled)
                {
                    //cache.Add(conditions, newEnvelopePoints);
                    AddToCache(conditions, newEnvelopePoints);
                    envelopePoints    = newEnvelopePoints;
                    currentConditions = conditions;
                    UpdateGraphs();
                    valuesSet = true;
                }
            }
        }
Exemple #28
0
    public IEnumerator GrowTest()
    {
        TestDrawer.text    = "Grow Test";
        GenUtil.PrintCount = 0;

        GenData growArea = new GenData(40, 25);

        GenRoom left = GenRoom.Sized(10, 15);

        left.FillFloor('.');
        growArea.PlaceRoom(0, 0, left);


        GenRoom right = GenRoom.Sized(10, 15);

        right.FillFloor('.');
        growArea.PlaceRoom(11, 0, right);

        growArea.EdgeWalls('#');


        TestDrawer.text = growArea.Print(false);
        yield return(new WaitForSeconds(1f));



        for (int x = 0; x < 8; x++)
        {
            for (int y = 0; y < 13; y++)
            {
                {
                    TestDrawer.text = growArea.Print(false);
                    //yield return new WaitForSeconds(0.05f);

                    bool sucL = growArea.TryGrowRect(1 + x, 1 + y, 5, 6, out GenRect oL, true);

                    GenRoom resultL = GenRoom.Sized(oL.WidthT, oL.HeightT);
                    resultL.FillFloor('O');
                    growArea.PlaceRoom(oL.MinX, oL.MinY, resultL);
                    growArea.EdgeWalls('#');


                    bool sucR = growArea.TryGrowRect(12 + x, 1 + y, 5, 6, out GenRect oR, false);

                    GenRoom resultR = GenRoom.Sized(oR.WidthT, oR.HeightT);
                    resultR.FillFloor('O');
                    growArea.PlaceRoom(oR.MinX, oR.MinY, resultR);
                    growArea.EdgeWalls('#');



                    GenRoom dotL = GenRoom.Sized(1, 1);
                    dotL.FillFloor('+');
                    growArea.PlaceRoom(1 + x, 1 + y, dotL);

                    GenRoom dotR = GenRoom.Sized(1, 1);
                    dotR.FillFloor('X');
                    growArea.PlaceRoom(12 + x, 1 + y, dotR);


                    TestDrawer.text = growArea.Print(false);
                    yield return(new WaitForSeconds(0.50f));



                    growArea.Rooms.Remove(dotR);
                    growArea.Rooms.Remove(dotL);
                    growArea.Rooms.Remove(resultL);
                    growArea.Rooms.Remove(resultR);
                }
            }
        }

        /*
         * for (int x = 0; x < 8; x++)
         * {
         *  for (int y = 0; y < 13; y++)
         *  {
         *
         *      {
         *          TestDrawer.text = growArea.Print(false);
         *          //yield return new WaitForSeconds(0.05f);
         *
         *          bool suc = growArea.TryGrowRect(3 + x, 3 + y, 5, 6, out GenRect o, false);
         *
         *          GenRoom result = GenRoom.Sized(o.WidthT, o.HeightT);
         *          result.FillFloor('O');
         *          growArea.PlaceRoom(o.MinX, o.MinY, result);
         *          growArea.EdgeWalls('#');
         *
         *          GenRoom dot = GenRoom.Sized(1, 1);
         *          dot.FillFloor('X');
         *          growArea.PlaceRoom(3 + x, 3 + y, dot);
         *
         *          TestDrawer.text = growArea.Print(false);
         *          yield return new WaitForSeconds(0.50f);
         *
         *          growArea.Rooms.Remove(dot);
         *          growArea.Rooms.Remove(result);
         *      }
         *  }
         * }
         *
         */
    }
Exemple #29
0
    public static IEnumerator GetSimpleTemple()
    {
        GenData temple = new GenData(Random.Range(TempleWidth.start, TempleWidth.end), Random.Range(TempleHeight.start, TempleHeight.end));

        List <GenRoom> AutoFillRoom = new List <GenRoom>();

        // list of all rooms that are not allowed to be used for door placement
        List <GenRoom> NoAutoDoor  = new List <GenRoom>();
        List <GenRoom> SecretRooms = new List <GenRoom>();

        GenTile Chest = GenTile.GetEmpty();

        Chest.Details.Add(new GenDetail()
        {
            Char = '=', Type = GenDetail.DetailType.Entity, Entity = GenDetail.EntityType.Chest
        });

        GenTile pillar = GenTile.GetEmpty();

        //pillar.Details.Add(new GenDetail() { Char = '\u01C1', Type = GenDetail.DetailType.Decoration });
        pillar.Details.Add(new GenDetail()
        {
            Char = 'O', Type = GenDetail.DetailType.Decoration
        });

        GenTile[,] pillars = new GenTile[, ]
        {
            { GenTile.Copy(pillar), GenTile.Copy(pillar) },
            { GenTile.Copy(pillar), GenTile.Copy(pillar) }
        };

        GenTile Door = GenTile.GetEmpty();

        Door.Details.Add(new GenDetail()
        {
            Char = '+', Type = GenDetail.DetailType.Door, Entity = GenDetail.EntityType.Door
        });


        GenRoom outer = GenRoom.Sized(temple.Width, temple.Height);

        outer.FillFloor('+');
        outer.SpacePriority = -2;
        temple.PlaceRoom(0, 0, outer);
        temple.EdgeWalls('#', outer);


        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------


        int w = Random.Range(9, 12);
        int h = Random.Range(10, 16);

        // EntryHall
        temple.TryGrowRect(1, outer.Outer.GetCenter().y, w, h, out GenRect EntrySize, false);
        GenRoom EntryHall = GenRoom.At(EntrySize.MinX, EntrySize.MinY, EntrySize.WidthT, EntrySize.HeightT);

        EntryHall.FillFloor('.');
        temple.PlaceRoom(EntrySize.MinX, EntrySize.MinY, EntryHall);
        temple.EdgeWalls('#');
        EntryHall.GetAtWorldspaceG(
            EntrySize.MinX + 1, EntrySize.GetCenter().y)
        .Details
        .Add(new GenDetail()
        {
            Char = '>', Type = GenDetail.DetailType.Entity, Entity = GenDetail.EntityType.StairsDown
        });


        int posX = EntrySize.MinX + 2;
        int posy = EntrySize.MinY + 2;

        GenTile[,] sym = GenUtil.GetSymetry(pillars.GetCopy(), ref posX, ref posy, EntryHall, GenUtil.Axis.Horizontal | GenUtil.Axis.Vertical);

        EntryHall.PlaceDetailsAt(posX, posy, sym);
        temple.FixOverlap();

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // hall to big thing
        int whall = Random.Range(10, 25);
        int hhall = Random.Range(5, 7);
        int space = Random.Range(2, 4);

        temple.TryGrowRect(EntrySize.MaxX + 1, EntrySize.GetCenter().y, whall, hhall, out GenRect HallSize);
        GenRoom PillarHall = GenRoom.Sized(HallSize.WidthT, HallSize.HeightT);

        PillarHall.FillFloor('.');
        PillarHall.SpacePriority = 3;
        temple.PlaceRoom(HallSize.MinX, HallSize.MinY, PillarHall);
        temple.EdgeWalls('#', PillarHall);

        NoAutoDoor.Add(PillarHall);

        // place doors to the entry
        if (hhall == 5)
        {
            // a single door in the middle
            PillarHall.AddDetails(HallSize.MinX, HallSize.MinY + 2, GenTile.Copy(Door));
            PillarHall.AddDetails(HallSize.MaxX, HallSize.MinY + 2, GenTile.Copy(Door));
        }
        else
        {
            // place symetric doors
            PillarHall.AddDetails(HallSize.MinX, HallSize.MinY + 2, GenTile.Copy(Door));
            PillarHall.AddDetails(HallSize.MinX, HallSize.MinY + 3, GenTile.Copy(Door));

            PillarHall.AddDetails(HallSize.MaxX, HallSize.MinY + 2, GenTile.Copy(Door));
            PillarHall.AddDetails(HallSize.MaxX, HallSize.MinY + 3, GenTile.Copy(Door));
        }

        int currBar = HallSize.MinX + space;

        GenTile[,] singlePillar = new GenTile[, ] {
            { GenTile.Copy(pillar) }
        };
        while (temple.IsInsideRoom(currBar, HallSize.MinY + 1, PillarHall))
        {
            int fx = currBar;
            int fy = HallSize.MinY + 1;
            GenTile[,] feature = GenUtil.GetSymetry(singlePillar, ref fx, ref fy, PillarHall, GenUtil.Axis.Vertical);
            PillarHall.PlaceDetailsAt(fx, fy, feature);
            currBar += space;
        }
        temple.FixOverlap();

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // holy water or something

        int waterHeight      = Random.Range(2, 4);
        int waterWidth       = Random.Range(2, 4);
        int waterPillarWidth = Random.Range(2, 3);

        int waterRoomHeight = waterHeight + 4 + waterPillarWidth * 2;
        int waterRoomWidth  = waterWidth + 6 + waterPillarWidth * 2;

        temple.TryGrowRect(HallSize.MaxX + 1, HallSize.GetCenter().y, waterRoomWidth, waterRoomHeight, out GenRect WaterSize, false, GenUtil.Direction4.Top);

        GenRoom waterRoom = GenRoom.Sized(WaterSize.WidthT, WaterSize.HeightT);

        waterRoom.FillFloor();
        waterRoom.SpacePriority = 2;
        temple.PlaceRoom(WaterSize.MinX, WaterSize.MinY, waterRoom);
        temple.EdgeWalls('#', waterRoom);


        int BackDoorWater = Random.Range(1, waterRoom.Height / 2);

        waterRoom.AddDetails(WaterSize.MaxX, WaterSize.MinY + BackDoorWater, GenTile.Copy(Door));
        waterRoom.AddDetails(WaterSize.MaxX, WaterSize.MaxY - BackDoorWater, GenTile.Copy(Door));


        GenTile waterSingle = GenTile.GetEmpty();

        waterSingle.Details.Add(new GenDetail()
        {
            Char = '~', Type = GenDetail.DetailType.Background
        });
        GenTile[,] water = GenUtil.Fill(waterWidth, waterHeight, waterSingle);

        waterRoom.PlaceDetailsAt(WaterSize.MinX + 3 + waterPillarWidth, WaterSize.MinY + 2 + waterPillarWidth, water);

        int waterPX = WaterSize.MinX + 3;
        int waterPY = WaterSize.MinY + 2;

        GenTile[,] waterPillarPlace = GenUtil.GetSymetry(pillars.GetCopy(), ref waterPX, ref waterPY, waterRoom, GenUtil.Axis.Horizontal | GenUtil.Axis.Vertical);
        waterRoom.PlaceDetailsAt(waterPX, waterPY, waterPillarPlace);


        temple.FixOverlap();

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // pillar spam
        int spamWidth  = Random.Range(10, 20);
        int spamHeight = WaterSize.HeightT + Random.Range(8, 15);

        temple.TryGrowRect(WaterSize.MaxX + 1, WaterSize.GetCenter().y, spamWidth, spamHeight, out GenRect SpamSize, true, GenUtil.Direction4.Top);
        GenRoom Spam = GenRoom.Sized(SpamSize.WidthT, SpamSize.HeightT);

        Spam.FillFloor();
        Spam.SpacePriority = 1;
        temple.PlaceRoom(SpamSize.MinX, SpamSize.MinY, Spam);
        temple.EdgeWalls('#', Spam);

        int spamPX = SpamSize.MinX + 2;
        int spamPY = SpamSize.MinY + 2;

        for (int x = spamPX; temple.IsInsideRoom(x, spamPY, Spam); x += 2)
        {
            for (int y = spamPY; temple.IsInsideRoom(x, y, Spam); y += 2)
            {
                GenTile p = GenTile.Copy(pillar);
                Spam.AddDetails(x, y, p);
            }
        }
        Spam.AddDetail(
            SpamSize.MaxX - 1,
            SpamSize.GetCenter().y,
            new GenDetail()
        {
            Char = '<', Type = GenDetail.DetailType.Entity, Entity = GenDetail.EntityType.StairsUp
        });

        temple.FixOverlap();

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        //temple.Rooms.Remove(outer); // we dont have boundries
        for (int x = outer.Inner.MinX; x < outer.Outer.MaxX; x++)
        {
            for (int y = outer.Inner.MinY; y < outer.Outer.MaxY; y++)
            {
                outer.RemoveTileAtG(x, y);
            }
        }


        //GenRoom Mark = GenRoom.Sized(0, 0);
        //Mark.FillFloor('X');
        //Mark.SpacePriority = 100;


        // lets go ham with randomly sized rooms
        int spawnAttemptsRemaining = 1000;

        while (spawnAttemptsRemaining-- > 0)// lol the arrow
        {
            int rWidth  = Random.Range(RandomWidth.start, RandomWidth.end);
            int rHeight = Random.Range(RandomHeight.start, RandomHeight.end);

            int     rX        = Random.Range(2, temple.Width - 2);
            int     rY        = Random.Range(2, temple.Height - 2);
            GenRect rHopeSize = new GenRect(rX, rX + rWidth + 1, rY, rY + rWidth - 1);


            if (temple.IsInsideRoom(rX, rY) || temple.GetTile(rX, rY) != null)
            {
                continue;
            }

            temple.TryGrowRect(rX, rY, rWidth, rHeight, out GenRect rSize, true);

            GenRoom add = GenRoom.Sized(rSize.WidthT, rSize.HeightT);
            add.FillFloor();
            add.SpacePriority = 01;

            temple.PlaceRoom(rSize.MinX, rSize.MinY, add);

            AutoFillRoom.Add(add);

            temple.EdgeWalls('#', add);

            temple.FixOverlap();

            /*
             * if (rWidth * 2 < rHeight || rHeight * 2 < rWidth)
             * {
             *  if (Random.Range(0,10)>4)
             *  {
             *      // we are making a hallway
             *
             *      //TODO: hallway
             *
             *      temple.PlaceRoom(rX, rY, Mark);
             *      Log(temple);
             *      if (Logging!=null)
             *  {
             *      yield return new WaitForSeconds(0.25f);
             *  }
             *      temple.Rooms.Remove(Mark);
             *      continue;
             *  }
             * }
             */

            /*
             * int randomChance = Random.Range(0, 4);
             * switch (randomChance)
             * {
             *  case 0:
             *      // random pillars in the room
             *
             *      for (int i = 0; i < 7 + (rSize.WidthT + rSize.HeightT)/5; i++)
             *      {
             *          int px = Random.Range(rSize.MinX + 1, rSize.MaxX);
             *          int py = Random.Range(rSize.MinY + 1, rSize.MaxY);
             *          add.AddDetails(px, py, pillar);
             *      }
             *
             *      break;
             *  case 1:
             *      // random water
             *      for (int i = 0; i < 15 + (rSize.WidthT + rSize.HeightT)/3; i++)
             *      {
             *          int px = Random.Range(rSize.MinX + 1, rSize.MaxX);
             *          int py = Random.Range(rSize.MinY + 1, rSize.MaxY);
             *          GenDetail littleWater= new GenDetail() { Char = '~', Type = GenDetail.DetailType.Background};
             *          add.AddDetail(px, py, littleWater);
             *      }
             *      break;
             *  case 2:
             *      // random room inside if possible else empty
             *      if (rSize.WidthT>=7&& rSize.HeightT >= 7)
             *      {
             *          int insideX = rSize.GetCenter().x;
             *          int insideY = rSize.GetCenter().y;
             *
             *          temple.TryGrowRect(insideX, insideY, 100, 100, out GenRect insideSize, false);
             *          GenRoom inside = GenRoom.Sized(insideSize.WidthT, insideSize.HeightT);
             *          inside.FillFloor();
             *          inside.SpacePriority = 2;
             *          temple.PlaceRoom(insideSize.MinX, insideSize.MinY, inside);
             *          temple.EdgeWalls('#',inside);
             *          temple.FixOverlap();
             *
             *      }
             *      else
             *      {
             *          for (int i = 0; i < 7; i++)
             *          {
             *              int px = Random.Range(rSize.MinX + 1, rSize.MaxX);
             *              int py = Random.Range(rSize.MinY + 1, rSize.MaxY);
             *              add.AddDetails(px, py, pillar);
             *          }
             *      }
             *      break;
             *  default:
             *      break;
             * }
             *
             * Log(temple);
             * if (Logging!=null)
             *  {
             *      yield return new WaitForSeconds(0.25f);
             *  }
             */
        }

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // now fill the rooms with things

        var adjList = temple.GetAdjacentRoomMap();
        // remove any Room that is too small and have no connections

        List <GenRoom> tooSmall = new List <GenRoom>();

        foreach (var room in temple.Rooms)
        {
            if (room.Width >= 5 && room.Height == 3)
            {
                tooSmall.Add(room);
                continue;
            }
            if (room.Height >= 5 && room.Width == 3)
            {
                tooSmall.Add(room);
                continue;
            }
            if (room.Height <= 3 && room.Width <= 3)
            {
                tooSmall.Add(room);
                continue;
            }
            if (adjList[room].Count == 0)
            {
                tooSmall.Add(room);
                continue;
            }
        }
        foreach (var room in tooSmall)
        {
            temple.Rooms.Remove(room);
        }

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        List <GenRoom> PotentialSecret = new List <GenRoom>();

        foreach (var room in temple.Rooms)
        {
            if (room.Width + room.Height <= 12)
            {
                PotentialSecret.Add(room);
            }
        }

        Debug.Log("potential " + PotentialSecret.Count + "Secret rooms");

        // 1 room --> 0,1,2,3
        // 2 room --> 4,5
        int SecretCount = Mathf.Min(Mathf.FloorToInt(Mathf.Sqrt(Random.Range(1, 6))), PotentialSecret.Count); // this goes to 5

        Debug.Log(SecretCount + " Secret rooms chosen");
        foreach (var secret in PotentialSecret.GetRandom(SecretCount))
        {
            // we get random door
            // add a chest
            // remove it from door spawn
            GenPositionTile entry = temple.GetDoorableTiles(secret.GetAllTiles()).GetRandom();
            secret.AddDetail(entry.PositionG.x, entry.PositionG.y,
                             new GenDetail()
            {
                Char = '*', Entity = GenDetail.EntityType.Door, Type = GenDetail.DetailType.Door
            });

            GenPositionTile myChest = secret
                                      .GetAllTiles()
                                      .Where(t => temple.IsInsideRoom(t.PositionG.x, t.PositionG.y, secret) && temple.IsCornerGR(t.PositionG.x, t.PositionG.y, secret))
                                      .ToList()
                                      .GetRandom();
            secret.AddDetails(myChest.PositionG.x, myChest.PositionG.y, GenTile.Copy(Chest));

            AutoFillRoom.Remove(secret);
            SecretRooms.Add(secret);
            NoAutoDoor.Add(secret);
        }
        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // go through all other rooms and determin what they are

        foreach (GenRoom room in AutoFillRoom)
        {
            // -----------
            Log(temple);
            if (Logging != null)
            {
                yield return(new WaitForSeconds(0.25f));
            }
            // -----------

            // pillar hallway
            if (room.Height <= 7 && room.Height >= 5 && room.Width > 6)
            {
                // potential horizontal hallway
                if (Random.value < 0.4f)
                {
                    // hallway confirmed
                    // left to right

                    GenTile[,] p = new GenTile[, ]
                    {
                        { GenTile.Copy(pillar) }
                    };
                    int spacing = Random.Range(2, 5);

                    int tmpX = room.Outer.MinX + spacing;
                    int tmpY = room.Outer.MinY + 1;


                    p = GenUtil.GetSymetry(p, ref tmpX, ref tmpY, room, GenUtil.Axis.Vertical);

                    while (temple.IsInsideRoom(tmpX, tmpY, room))
                    {
                        room.PlaceDetailsAt(tmpX, tmpY, p);

                        tmpX = tmpX + spacing;
                    }
                    int enemyCount = Random.Range(0, 4);
                    for (int i = 0; i < enemyCount; i++)
                    {
                        SpawnEnemy(temple, room);
                    }
                    int itemCount = Random.Range(-1, 3);
                    for (int i = 0; i < itemCount; i++)
                    {
                        SpawnItem(temple, room, true);
                    }
                    int chestCount = Random.Range(-2, 2);
                    for (int i = 0; i < chestCount; i++)
                    {
                        SpawnChest(temple, room, true);
                    }
                    continue;
                }
            }
            if (room.Width <= 7 && room.Width >= 5 && room.Height > 6)
            {
                // potential horizontal hallway
                if (Random.value < 0.4f)
                {
                    // hallway confirmed
                    // left to right

                    GenTile[,] p = new GenTile[, ]
                    {
                        { GenTile.Copy(pillar) }
                    };
                    int spacing = Random.Range(2, 5);

                    int tmpX = room.Outer.MinX + 1;
                    int tmpY = room.Outer.MinY + spacing;


                    p = GenUtil.GetSymetry(p, ref tmpX, ref tmpY, room, GenUtil.Axis.Horizontal);

                    while (temple.IsInsideRoom(tmpX, tmpY, room))
                    {
                        room.PlaceDetailsAt(tmpX, tmpY, p);

                        tmpY = tmpY + spacing;
                    }
                    int enemyCount = Random.Range(0, 4);
                    for (int i = 0; i < enemyCount; i++)
                    {
                        SpawnEnemy(temple, room);
                    }
                    int itemCount = Random.Range(-1, 3);
                    for (int i = 0; i < itemCount; i++)
                    {
                        SpawnItem(temple, room, true);
                    }
                    int chestCount = Random.Range(-2, 2);
                    for (int i = 0; i < chestCount; i++)
                    {
                        SpawnChest(temple, room, true);
                    }
                    continue;
                }
            }

            if (room.Height >= 8 && room.Width >= 8)
            {
                // can either be pillar spam or room in room

                if (Random.value < 0.6f)
                {
                    if (Random.value < 0.7f && room.Width % 2 == 1 && room.Height % 2 == 1)
                    {
                        // pillar spam

                        for (int x = 2; x < room.Width - 2; x += 2)
                        {
                            for (int y = 2; y < room.Height - 2; y += 2)
                            {
                                room.AddDetails(room.PosX + x, room.PosY + y, GenTile.Copy(pillar));
                            }
                        }
                        int enemyCount = Random.Range(0, 5);
                        for (int i = 0; i < enemyCount; i++)
                        {
                            SpawnEnemy(temple, room);
                        }
                        int itemCount = Random.Range(-1, 3);
                        for (int i = 0; i < itemCount; i++)
                        {
                            SpawnItem(temple, room, true);
                        }
                        int chestCount = Random.Range(-3, 3);
                        for (int i = 0; i < chestCount; i++)
                        {
                            SpawnChest(temple, room, true);
                        }
                    }
                    else
                    {
                        // room in room

                        // find where to put the inner room
                        temple.TryGrowRect(room.Inner.GetCenter().x, room.Inner.GetCenter().y, 100, 100, out GenRect InnerSize);


                        if (InnerSize.WidthT >= 4 && InnerSize.HeightT >= 4)
                        {
                            if (InnerSize.WidthT >= 10 || InnerSize.HeightT >= 10)
                            {
                                if (Mathf.Abs(InnerSize.WidthT - InnerSize.HeightT) > 3)
                                {
                                    // we want to divide
                                    if (InnerSize.WidthT > InnerSize.HeightT)
                                    {
                                        // divide left and right
                                        int singleWidth = InnerSize.WidthT / 2 - 2;
                                        // left
                                        GenRect LeftRoom = new GenRect(InnerSize.MinX, InnerSize.MinX + singleWidth, InnerSize.MinY, InnerSize.MaxY);
                                        // right
                                        GenRect RightRoom = new GenRect(InnerSize.MaxX - singleWidth, InnerSize.MaxX, InnerSize.MinY, InnerSize.MaxY);

                                        GenRoom left = GenRoom.Sized(LeftRoom.WidthT, LeftRoom.HeightT);
                                        left.FillFloor();
                                        left.SpacePriority = 4;
                                        GenRoom right = GenRoom.Sized(RightRoom.WidthT, RightRoom.HeightT);
                                        right.FillFloor();
                                        right.SpacePriority = 4;
                                        temple.PlaceRoom(LeftRoom.MinX, LeftRoom.MinY, left);
                                        temple.PlaceRoom(RightRoom.MinX, RightRoom.MinY, right);

                                        NoAutoDoor.Add(left);
                                        NoAutoDoor.Add(right);

                                        temple.EdgeWalls('#', left);
                                        temple.EdgeWalls('#', right);

                                        temple.FixOverlap();
                                        // -----------
                                        Log(temple);
                                        if (Logging != null)
                                        {
                                            yield return(new WaitForSeconds(0.25f));
                                        }
                                        // -----------

                                        var leftDoor  = temple.GetDoorableTiles(left.GetAllTiles()).GetRandom(1);
                                        var rightDoor = temple.GetDoorableTiles(right.GetAllTiles()).GetRandom(1);

                                        for (int i = 0; i < leftDoor.Count; i++)
                                        {
                                            left.AddDetails(leftDoor[i].PositionG.x, leftDoor[i].PositionG.y, GenTile.Copy(Door));
                                        }
                                        for (int i = 0; i < rightDoor.Count; i++)
                                        {
                                            right.AddDetails(rightDoor[i].PositionG.x, rightDoor[i].PositionG.y, GenTile.Copy(Door));
                                        }
                                        SpawnItem(temple, left);
                                        SpawnItem(temple, right);
                                        if (Random.value < 0.4f)
                                        {
                                            SpawnItem(temple, right);
                                        }
                                        if (Random.value < 0.4f)
                                        {
                                            SpawnItem(temple, left);
                                        }
                                        if (Random.value < 0.2f)
                                        {
                                            SpawnChest(temple, left, true);
                                        }
                                        if (Random.value < 0.2f)
                                        {
                                            SpawnChest(temple, left, true);
                                        }
                                    }
                                    else
                                    {
                                        // divide top bot
                                        Debug.Log("currently not implemented, sorry");
                                    }
                                }
                            }
                            else
                            {
                                // one single room
                                if (InnerSize.WidthT > 5)
                                {
                                    InnerSize = InnerSize.Transform(-1, 0, -1, 0);
                                }
                                if (InnerSize.HeightT > 5)
                                {
                                    InnerSize = InnerSize.Transform(0, -1, 0, -1);
                                }

                                Debug.Log("HERE");

                                GenRoom single = GenRoom.Sized(InnerSize.WidthT, InnerSize.HeightT);
                                single.SpacePriority = 4;
                                single.FillFloor();
                                NoAutoDoor.Add(single);

                                temple.PlaceRoom(InnerSize.MinX, InnerSize.MinY, single);
                                temple.EdgeWalls('#', single);
                                temple.FixOverlap();
                                // -----------
                                Log(temple);
                                if (Logging != null)
                                {
                                    yield return(new WaitForSeconds(0.25f));
                                }
                                // -----------



                                // double doors
                                var doorables = single.GetAllTiles();// single.GetEdge().ToList();
                                var theDoors  = temple.GetDoorableTiles(doorables).GetRandom(2);

                                for (int i = 0; i < theDoors.Count; i++)
                                {
                                    single.AddDetails(theDoors[i].PositionG.x, theDoors[i].PositionG.y, GenTile.Copy(Door));
                                }

                                SpawnItem(temple, single);

                                if (Random.value < 0.2f)
                                {
                                    SpawnChest(temple, single, true);
                                }
                                if (Random.value < 0.2f)
                                {
                                    SpawnChest(temple, single, true);
                                }
                            }
                        }

                        SpawnEnemy(temple, room);
                        if (Random.value < 0.5f)
                        {
                            SpawnEnemy(temple, room);
                        }
                        if (Random.value < 0.2f)
                        {
                            SpawnEnemy(temple, room);
                        }
                    }
                    continue;
                }
            }
            // something random
            //room.FillFloor('~');

            SpawnEnemy(temple, room);
            SpawnEnemy(temple, room);

            if (Random.value < 0.5f)
            {
                SpawnEnemy(temple, room);
            }
            if (Random.value < 0.2f)
            {
                SpawnEnemy(temple, room);
            }
            SpawnItem(temple, room);
            if (Random.value < 0.3f)
            {
                SpawnItem(temple, room);
            }
            if (Random.value < 0.3f)
            {
                SpawnItem(temple, room);
            }
            if (Random.value < 0.4f)
            {
                SpawnChest(temple, room);
            }
            if (Random.value < 0.1f)
            {
                SpawnChest(temple, room);
            }
        }


        List <GenRoom> RequireDoor = new List <GenRoom>(temple.Rooms);

        foreach (var doo in NoAutoDoor)
        {
            RequireDoor.Remove(doo);
        }
        List <GenRoom> DoorIteration = new List <GenRoom>(RequireDoor);
        GenRoom        start         = EntryHall;

        Dictionary <GenRoom, List <GenRoom> > adj = temple.GetAdjacentRoomMap();

        void RandomDoorTo(GenRoom a, GenRoom b)
        {
            var tiles    = temple.GetDoorableTiles(temple.GetConnectingTiles(a, b));
            var location = tiles.GetRandom();

            a.AddDetails(location.PositionG.x, location.PositionG.y, GenTile.Copy(Door));
        }

        while (RequireDoor.Count > 0)
        {
            DoorIteration.Clear();
            DoorIteration.AddRange(RequireDoor);
            foreach (var room in DoorIteration)
            {
                if (temple.IsReachable(start, room))
                {
                    // reachable so we dont have to do a thing
                    RequireDoor.Remove(room);
                }
                else
                {
                    // place random door
                    var available = adj[room];
                    RandomDoorTo(room, available.GetRandom());
                }
                // -----------
                Log(temple);
                if (Logging != null)
                {
                    yield return(new WaitForSeconds(0.1f));
                }

                // -----------
            }
        }


        foreach (var room in adj[Spam].GetRandom(2))
        {
            RandomDoorTo(Spam, room);
        }

        Log(temple);
        Debug.Log("Done");


        LastOutput = GenUtil.Print(temple, false);
        Done?.Invoke();
    }
		public StarterGen(GenData genData)
		{
			this.genData = genData;
		}
		private static string SetZipTemplate(string starterTemplate, GenData genData)
		{
			string ZIPHEAD = "//#ZIPHEAD";
			string ZIPBODY = "//#ZIPBODY";
			string head = genData.CompressProvider.Provider.GetHeadTemplate();
			string body = genData.CompressProvider.Provider.GetBodyTemplate();
			if(head != null) starterTemplate = starterTemplate.Replace(ZIPHEAD, head);
			if(body != null) starterTemplate = starterTemplate.Replace(ZIPBODY, body);
			return starterTemplate;
		}
Exemple #32
0
 static void initOpMap()
 {
     opmap = new Dictionary<string, OpCodeParser>();
     //deprecated opmap["add"] = new GenAdd();
     //deprecated opmap["sub"] = new GenSub();
     opmap["add.u"] = new GenAdd(false);
     opmap["sub.u"] = new GenSub(false);
     opmap["add.s"] = new GenAdd(true);
     opmap["sub.s"] = new GenSub(true);
     opmap["addi"] = new GenAddI();
     opmap["subi"] = new GenSubI();
     //deprecated opmap["addi.u"] = new GenAddI();
     //deprecated opmap["subi.u"] = new GenSubI();
     opmap["or"] = new GenOr();
     opmap["and"] = new GenAnd();
     opmap["xor"] = new GenXor();
     opmap["not"] = new GenNot();
     opmap["sl"] = new GenShift(true);
     opmap["sr"] = new GenShift(false);
     opmap["shl"] = new GenShift(true);
     opmap["shr"] = new GenShift(false);
     opmap["load.l"] = new GenLoad(true);
     opmap["load.h"] = new GenLoad(false);
     opmap["cmp.u"] = new GenCmp(false);
     opmap["cmp.s"] = new GenCmp(true);
     opmap["biro"] = new GenJmpImm();
     opmap["br"] = new GenJmpReg();
     opmap["br.eq"] = new GenCndJmp(BranchCondition.EQ);
     opmap["br.az"] = new GenCndJmp(BranchCondition.AZ);
     opmap["br.bz"] = new GenCndJmp(BranchCondition.BZ);
     opmap["br.anz"] = new GenCndJmp(BranchCondition.ANZ);
     opmap["br.bnz"] = new GenCndJmp(BranchCondition.BNZ);
     opmap["br.lt"] = new GenCndJmp(BranchCondition.ALB);
     opmap["br.gt"] = new GenCndJmp(BranchCondition.AGB);
     opmap["bro.eq"] = new GenCndJmpRO(BranchCondition.EQ);
     opmap["bro.az"] = new GenCndJmpRO(BranchCondition.AZ);
     opmap["bro.bz"] = new GenCndJmpRO(BranchCondition.BZ);
     opmap["bro.anz"] = new GenCndJmpRO(BranchCondition.ANZ);
     opmap["bro.bnz"] = new GenCndJmpRO(BranchCondition.BNZ);
     opmap["bro.lt"] = new GenCndJmpRO(BranchCondition.ALB);
     opmap["bro.gt"] = new GenCndJmpRO(BranchCondition.AGB);
     //deprecated opmap["read"] = new GenRead();
     //deprecated opmap["write"] = new GenWrite();
     opmap["read.w"] = new GenRead();
     opmap["write.w"] = new GenWrite();
     opmap["read.b"] = new GenRead(true);
     opmap["write.b"] = new GenWrite(true);
     opmap["dw"] = new GenData();
     opmap["spc"] = new GenSpecialAssign(SpecialAssign.SAVE_PC);
     opmap["sstatus"] = new GenSpecialAssign(SpecialAssign.SAVE_STATUS);
     opmap["gief"] = new GenSpecialAssign(SpecialAssign.GIEF);
     opmap["bbi"] = new GenSpecialAssign(SpecialAssign.BBI);
     opmap["ei"] = new GenSpecialAssign(SpecialAssign.EI);
     opmap["di"] = new GenSpecialAssign(SpecialAssign.DI);
     opmap["int"] = new GenSpecialAssign(SpecialAssign.INT);
     //deprecated opmap["data"] = new GenData();
 }