Пример #1
0
        public override UILayout Cook(CookingContext context)
        {
            PhotoshopDocument input = Input.Cook(context);

            Vector2 windowSize = Vector2.Zero;

            windowSize.X = (float)input.Width;
            windowSize.Y = (float)input.Height;
            UIWindow rootWindow = new UIWindow()
            {
                XMode      = UIPositionMode.Undefined,
                YMode      = UIPositionMode.Undefined,
                WidthMode  = UISizeMode.Absolute,
                HeightMode = UISizeMode.Absolute,
                Width      = windowSize.X,
                Height     = windowSize.Y,
            };

            foreach (var item in input.Layers)
            {
                AddChildTo(rootWindow, item);
            }

            return(new UILayout(rootWindow));
        }
Пример #2
0
        public override SpriteSet Cook(CookingContext context)
        {
            string actualPath = Path.Combine(context.BaseDirectory, context.Directory, context.ExpandVariables(Input));

            var items = new Dictionary <string, Sprite>();

            foreach (var item in Directory.GetFiles(actualPath))
            {
                string name      = Path.GetFileNameWithoutExtension(item);
                string extension = Path.GetExtension(item);
                Sprite sprite    = null;
                switch (extension.ToLower())
                {
                case ".strip":
                    sprite = CreateFromStrip(context, item);
                    break;

                case ".celanim":
                    sprite = CreateFromCelAnimation(context, item);
                    break;

                default:
                    sprite = null;
                    break;
                }

                if (sprite != null)
                {
                    context.AddDependency(item);
                    items.Add(name, sprite);
                }
            }

            return(new SpriteSet(items));
        }
Пример #3
0
        public sealed override ShaderEffect Cook(CookingContext context)
        {
            string assetPath = Path.Combine(context.Directory, context.ExpandVariables(Input));
            string input     = Path.Combine(context.BaseDirectory, assetPath);

            if (File.Exists(input) == false)
            {
                throw new FileNotFoundException(string.Empty, input);
            }

            context.AddDependency(input);

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

            using (var inputStream = new FileStream(input, FileMode.Open, FileAccess.Read))
            {
                var reader = new StreamReader(inputStream);
                while (reader.EndOfStream == false)
                {
                    codeLines.Add(reader.ReadLine());
                }
            }

            string code     = Preprocess(defines, codeLines);
            var    result   = Compile(code);
            var    byteCode = result.Item1;
            var    extra    = result.Item2;

            return(new ShaderEffect(null)
            {
                Tag = new ShaderEffectCookingTag(byteCode, extra)
            });
        }
Пример #4
0
        protected override void Export(CookingContext context, ParticleSystemSet input)
        {
            var particleBitmaps = new Dictionary <Bitmap, ParticleSystem>();

            foreach (var item in input.ParticleSystems)
            {
                var tag = (ImageCookingTag)item.Value.Image.Tag;
                particleBitmaps.Add(tag.Bitmap, item.Value);
            }

            using (var bitmapSheet = BitmapSheet.Create(particleBitmaps.Keys,
                                                        BitmapSheetSize.Width, BitmapSheetSize.Height,
                                                        BitmapSheetClusterSize.Width, BitmapSheetClusterSize.Height,
                                                        BitmapSheet.Options.PowerOfTwoSize | BitmapSheet.Options.RotatableMerging))
            {
                ExportImageSet.SaveTextureAssets(context, bitmapSheet, TextureOutput, (source, textureURI, clippingRectangle, appliedTransform) =>
                {
                    ParticleSystem value = null;
                    if (particleBitmaps.TryGetValue(source, out value))
                    {
                        value.Image.TextureURI        = textureURI;
                        value.Image.ClippingRectangle = clippingRectangle;
                        value.Image.AppliedTransform  = appliedTransform;
                    }
                });
            }
        }
Пример #5
0
        public override ImageSet Cook(CookingContext context)
        {
            string actualPath = Path.Combine(context.BaseDirectory, context.Directory, context.ExpandVariables(Input));

            Dictionary <string, Image> items = new Dictionary <string, Image>();

            foreach (var item in Directory.GetFiles(actualPath))
            {
                string name   = Path.GetFileNameWithoutExtension(item);
                Bitmap bitmap = BitmapExtension.CreateOne(item);
                if (bitmap == null)
                {
                    continue;
                }

                if (UniformSize.IsEmpty == false)
                {
                    bitmap = bitmap.ResizeAndDispose(UniformSize.Width, UniformSize.Height);
                }

                items.Add(name, new Image(string.Empty, Rectangle.Empty)
                {
                    Tag = new ImageCookingTag(bitmap)
                });
            }

            return(new ImageSet(items));
        }
Пример #6
0
        private Sprite CreateFromStrip(CookingContext context, string path)
        {
            var    name        = Path.GetFileNameWithoutExtension(path);
            var    directory   = Path.GetDirectoryName(path);
            var    bitmapPath1 = Path.Combine(directory, string.Format("{0}.png", name));
            var    bitmapPath2 = Path.Combine(directory, string.Format("{0}.bmp", name));
            var    bitmapPath3 = Path.Combine(directory, string.Format("{0}.jpg", name));
            Bitmap bitmap      = BitmapExtension.CreateOne(bitmapPath1, bitmapPath2, bitmapPath3);

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

            context.AddDependency(bitmapPath1);
            context.AddDependency(bitmapPath2);
            context.AddDependency(bitmapPath3);

            var data   = JsonSerializer.DeserializeDataFromFile(path) as Dictionary <string, object>;
            var frames = data.Get("frames", 0);
            var size   = data.Get("size", Size.Empty);
            var sprite = CreateSprite(EnumerateStrip(bitmap, frames, size), data);

            bitmap.Dispose();

            return(sprite);
        }
Пример #7
0
        private void ExportAllMasks(CookingContext context, ICollection <UIImage> images)
        {
            int    maskNumber       = 0;
            string maskOutputFormat = context.ExpandVariables(MaskOutput);

            var readMask   = new ReadGameAsset();
            var maskRecipe = new GameAssetRecipe()
            {
                Cook    = readMask,
                Author  = GetType().FullName,
                Comment = "Automatically generated.",
            };

            var masks = new List <BitMask>(images.Count);

            foreach (var item in images)
            {
                if (item.Mask == null)
                {
                    continue;
                }

                string path = string.Format(maskOutputFormat, maskNumber++);

                readMask.Input = item.Mask;

                JsonSerializer.Instance.Serialize(Path.Combine(context.BaseDirectory, context.Directory, Path.ChangeExtension(path, "asset")), maskRecipe);
                context.Store(Path.Combine(context.Directory, Path.ChangeExtension(path, null)), item.Mask);
            }
        }
Пример #8
0
    /// <summary>
    /// Update existing entity using object as a new state.
    /// </summary>
    /// <param name="entity">New state of existing entity.</param>
    /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
    public async Task UpdateAsync(T entity)
    {
        await using CookingContext context = ContextFactory.Create();
        T existing = await GetFullGraph(context.Set <T>()).FirstAsync(x => x.ID == entity.ID);

        Mapper.Map(entity, existing);
        await context.SaveChangesAsync();
    }
Пример #9
0
    /// <summary>
    /// Update existing entity using object as a new state.
    /// </summary>
    /// <typeparam name="TProjection">Projection containing part of new state for entity.</typeparam>
    /// <param name="entity">New state of existing entity.</param>
    /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
    public async Task UpdateAsync <TProjection>(TProjection entity)
        where TProjection : Entity
    {
        await using CookingContext context = ContextFactory.Create();

        T existing = Get(entity.ID, context, isTracking: true);

        Mapper.Map(entity, existing);
        await context.SaveChangesAsync();
    }
Пример #10
0
    /// <summary>
    /// Get entry, projected from <typeparamref name="T" />.
    /// </summary>
    /// <typeparam name="TProjection">Type of entry to project to.</typeparam>
    /// <param name="id">ID of entity to find and project.</param>
    /// <returns>Found projected entity.</returns>
    public TProjection GetProjected <TProjection>(Guid id)
        where TProjection : Entity
    {
        using CookingContext context = ContextFactory.Create();
        TProjection?entryProjected = Mapper.ProjectTo <TProjection>(context.Set <T>())
                                     .AsNoTracking()
                                     .FirstOrDefault(x => x.ID == id);

        return(Mapper.Map <TProjection>(entryProjected));
    }
Пример #11
0
    /// <summary>
    /// Remove entity from database.
    /// </summary>
    /// <param name="id">Id of entity to delete.</param>
    /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
    public virtual async Task DeleteAsync(Guid id)
    {
        using CookingContext context = ContextFactory.Create();

        // Remove entity without loading it, using stub object.
        context.Set <T>().Remove(new T {
            ID = id
        });
        await context.SaveChangesAsync();
    }
Пример #12
0
    /// <summary>
    /// Create new entity in database.
    /// </summary>
    /// <param name="entity">Entity to insert into database.</param>
    /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
    public async Task <Guid> CreateAsync(T entity)
    {
        await using CookingContext context = ContextFactory.Create();
        entity.Culture = GetCurrentCulture();
        await context.Set <T>().AddAsync(entity);

        await context.SaveChangesAsync();

        return(entity.ID);
    }
Пример #13
0
        public override Bitmap Cook(CookingContext context)
        {
            PhotoshopDocument input = Input.Cook(context);

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

            return(input.MergedBitmap);
        }
Пример #14
0
    private T Get(Guid id, CookingContext context, bool isTracking = false)
    {
        IQueryable <T> set     = context.Set <T>();
        IQueryable <T> fullSet = GetFullGraph(set);

        if (!isTracking)
        {
            fullSet = fullSet.AsNoTracking();
        }

        return(fullSet.AsSplitQuery().Single(x => x.ID == id));
    }
Пример #15
0
    /// <summary>
    /// Get a list of required properties for all objects matching filter.
    /// </summary>
    /// <typeparam name="TProperty">Type of property.</typeparam>
    /// <param name="propertySelector">Selector for a required property.</param>
    /// <param name="filter">Filter of objects to retrieve.</param>
    /// <returns>List of required properties for all objects matching filter.</returns>
    public List <TProperty> GetProperty <TProperty>(Expression <Func <T, TProperty> > propertySelector, Expression <Func <T, bool> >?filter = null)
    {
        using CookingContext context = ContextFactory.Create();
        IQueryable <T> cultureSpecificSet = context.Set <T>().AsNoTracking();

        if (filter != null)
        {
            cultureSpecificSet = cultureSpecificSet.Where(filter);
        }

        return(cultureSpecificSet.Select(propertySelector).ToList());
    }
Пример #16
0
        public sealed override StreamingGameAsset Cook(CookingContext context)
        {
            var binaryData = new byte[Data.Length / 2];

            for (int i = 0, k = 0; i < Data.Length; i += 2, k++)
            {
                int upper = Convert(Data[i + 0]);
                int lower = Convert(Data[i + 1]);
                binaryData[k] = (byte)(((upper << 4) & 0xF0) | ((lower << 0) & 0x0F));
            }

            return(new StreamingGameAsset(binaryData));
        }
Пример #17
0
        public override PhotoshopDocument Cook(CookingContext context)
        {
            using (var stream = Input.Cook(context))
            {
                var document = new PhotoshopDocument(stream, IgnoreImageResources, IgnoreLayers, false, IgnoreMergedBitmap);
                if (Scale != 1.0)
                {
                    document.Scale(Scale, Scale);
                }

                return(document);
            }
        }
Пример #18
0
        public override ImageSet Cook(CookingContext context)
        {
            PhotoshopDocument input = Input.Cook(context);

            Dictionary <string, Image> items = new Dictionary <string, Image>();

            foreach (PhotoshopDocument.Layer item in input.Layers)
            {
                CollectImages(items, item);
            }

            return(new ImageSet(items));
        }
Пример #19
0
        public static void SaveTextureAssets(CookingContext context, BitmapSheet bitmapSheet, string textureOutput, Action <Bitmap, string, Rectangle, Image.Transform> f)
        {
            SaveTextureAssets(context, bitmapSheet.Sheets, textureOutput, true);

            foreach (BitmapSheet.Element item in bitmapSheet.Elements)
            {
                string textureURI        = Path.Combine(context.Directory, Path.ChangeExtension((string)item.Sheet.Tag, null));
                var    clippingRectangle = new Rectangle(item.Bounds.X, item.Bounds.Y,
                                                         item.Bounds.Width, item.Bounds.Height);
                var appliedTransform = item.AppliedTransform;

                f(item.Source, textureURI, clippingRectangle, appliedTransform);
            }
        }
Пример #20
0
    /// <summary>
    /// Get all entities for a type.
    /// </summary>
    /// <param name="predicate">Predicate to filter.</param>
    /// <returns>All entities for type <typeparamref name="T" />.</returns>
    public List <T> GetAll(Expression <Func <T, bool> >?predicate = null)
    {
        using CookingContext context = ContextFactory.Create();
        IQueryable <T>?fullSet = GetFullGraph(context.Set <T>());

        if (predicate != null)
        {
            fullSet = fullSet.Where(predicate);
        }

        return(fullSet.AsNoTracking()
               .AsSplitQuery()
               .ToList());
    }
Пример #21
0
        private Sprite CreateFromCelAnimation(CookingContext context, string path)
        {
            var name      = Path.GetFileNameWithoutExtension(path);
            var directory = Path.GetDirectoryName(path);
            var celsPath  = Path.Combine(directory, name);

            if (Directory.Exists(celsPath) == false)
            {
                return(null);
            }

            var data = JsonSerializer.DeserializeDataFromFile(path) as Dictionary <string, object>;

            return(CreateSprite(EnumerateCels(celsPath), data));
        }
Пример #22
0
        public override Stream Cook(CookingContext context)
        {
            string[] paths = { Input1, Input2, Input3, Input4 };
            foreach (string item in paths)
            {
                string actualPath = Path.Combine(context.BaseDirectory, context.Directory, context.ExpandVariables(item));

                if (File.Exists(actualPath))
                {
                    context.AddDependency(actualPath);
                    return(new FileStream(actualPath, FileMode.Open, FileAccess.Read));
                }
            }

            return(null);
        }
Пример #23
0
    /// <summary>
    /// Create inmemory Sqlite databae mock.
    /// </summary>
    /// <returns>Inmemory database mock.</returns>
    protected Mock <IContextFactory> CreateInmemoryDatabase()
    {
        var keepAliveConnection = new SqliteConnection("DataSource=:memory:");

        keepAliveConnection.Open();

        var factoryMock = new Mock <IContextFactory>();

        factoryMock.Setup(x => x.Create()).Returns(() =>
        {
            var teste = new CookingContext(keepAliveConnection, "ru-RU");
            teste.Database.EnsureCreated();
            return(teste);
        });

        return(factoryMock);
    }
Пример #24
0
    public async Task <IEnumerable <Recipe> > WeatherForecasts()
    {
        List <Recipe> result;

        using (var context = new CookingContext(Database))
        {
            result = await context.Recipies.OrderBy(x => x.Name).ToListAsync().ConfigureAwait(false);
        }

        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        foreach (Recipe res in result.Where(x => x.Description != null))
        {
            res.Description = Rtf.ToHtml(res.Description);
        }

        return(result);
    }
Пример #25
0
        protected override void Export(CookingContext context, SpriteSet input)
        {
            var spriteBitmaps = new Dictionary <Bitmap, List <Tuple <Sprite, int> > >();

            foreach (var item in input.Sprites)
            {
                var tag = (SpriteCookingTag)item.Value.Tag;
                for (int i = 0; i < tag.Bitmaps.Count; i++)
                {
                    Bitmap bitmap = tag.Bitmaps[i];
                    List <Tuple <Sprite, int> > values = null;
                    if (spriteBitmaps.TryGetValue(bitmap, out values))
                    {
                        values.Add(Tuple.Create(item.Value, i));
                    }
                    else
                    {
                        values = new List <Tuple <Sprite, int> >();
                        values.Add(Tuple.Create(item.Value, i));
                        spriteBitmaps.Add(bitmap, values);
                    }
                }
            }

            using (var bitmapSheet = BitmapSheet.Create(spriteBitmaps.Keys,
                                                        BitmapSheetSize.Width, BitmapSheetSize.Height,
                                                        BitmapSheetClusterSize.Width, BitmapSheetClusterSize.Height,
                                                        BitmapSheet.Options.PowerOfTwoSize | BitmapSheet.Options.RotatableMerging))
            {
                ExportImageSet.SaveTextureAssets(context, bitmapSheet, TextureOutput, (source, textureURI, clippingRectangle, appliedTransform) =>
                {
                    List <Tuple <Sprite, int> > values = null;
                    if (spriteBitmaps.TryGetValue(source, out values))
                    {
                        foreach (var item in values)
                        {
                            item.Item1.Keyframes[item.Item2].TextureURI        = textureURI;
                            item.Item1.Keyframes[item.Item2].ClippingRectangle = clippingRectangle;
                            item.Item1.Keyframes[item.Item2].AppliedTransform  = appliedTransform;
                        }
                    }
                });
            }
        }
Пример #26
0
    /// <summary>
    /// Get reipe list filtered by optional parameters.
    /// </summary>
    /// <typeparam name="T">Type of required projection.</typeparam>
    /// <param name="requiredTags">Filter reipies by tags.</param>
    /// <param name="requiredCalorieTypes">Filter reipies by calorie types.</param>
    /// <param name="maxComplexity">Filter reipies by maximal complexity.</param>
    /// <param name="minRating">Filter reipies by minimal rating.</param>
    /// <param name="onlyNew">Filter out reipies which already was cooked.</param>
    /// <returns>List of filtered recipies.</returns>
    public List <T> GetRecipiesByParametersProjected <T>(List <Guid>?requiredTags = null,
                                                         List <CalorieType>?requiredCalorieTypes = null,
                                                         int?maxComplexity = null,
                                                         int?minRating     = null,
                                                         bool?onlyNew      = false)
        where T : Entity
    {
        using CookingContext context = ContextFactory.Create();
        IQueryable <Recipe> query = context.Set <Recipe>()
                                    .Include(x => x.Garnishes)
                                    .Include(x => x.Tags)
                                    .AsNoTracking()
                                    .AsQueryable();

        if (requiredTags?.Count > 0)
        {
            query = query.Where(x => x.Tags !.Any(t => requiredTags.Contains(t.ID)));
        }

        if (requiredCalorieTypes?.Count > 0)
        {
            query = query.Where(x => requiredCalorieTypes.Contains(x.CalorieType));
        }

        if (maxComplexity.HasValue)
        {
            query = query.Where(x => x.Difficulty <= maxComplexity.Value);
        }

        if (minRating.HasValue)
        {
            query = query.Where(x => x.Rating >= minRating.Value);
        }

        var queryResult = Mapper.ProjectTo <T>(query).ToList();

        // Client filtration
        if (onlyNew.HasValue && onlyNew.Value)
        {
            queryResult = queryResult.Where(x => dayService.GetLastCookedDate(x.ID) == null).ToList();
        }

        return(queryResult.OrderByDescending(x => DaysFromLasCook(x.ID)).ToList());
    }
Пример #27
0
        public override SpriteSet Cook(CookingContext context)
        {
            PhotoshopDocument input = Input.Cook(context);
            var items = new Dictionary <string, Sprite>();

            foreach (var item in input.Layers)
            {
                if (item.IsGroup)
                {
                    Process(items, item, string.Empty);
                }
                else
                {
                    // 최상위 Layer에서 그룹이 아닌 레이어는 무시합니다.
                }
            }

            return(new SpriteSet(items));
        }
Пример #28
0
        public static void Export(CookingContext context, ImageSet input, Size bitmapSheetSize, Size bitmapSheetClusterSize, string textureOutput)
        {
            var imageBitmaps = new Dictionary <Bitmap, List <Image> >();

            foreach (var item in input.Images)
            {
                var tag = (ImageCookingTag)item.Value.Tag;

                List <Image> values = null;
                if (imageBitmaps.TryGetValue(tag.Bitmap, out values))
                {
                    values.Add(item.Value);
                }
                else
                {
                    values = new List <Image>();
                    values.Add(item.Value);
                    imageBitmaps.Add(tag.Bitmap, values);
                }
            }

            using (var bitmapSheet = BitmapSheet.Create(imageBitmaps.Keys,
                                                        bitmapSheetSize.Width, bitmapSheetSize.Height,
                                                        bitmapSheetClusterSize.Width, bitmapSheetClusterSize.Height,
                                                        BitmapSheet.Options.PowerOfTwoSize | BitmapSheet.Options.RotatableMerging))
            {
                SaveTextureAssets(context, bitmapSheet, textureOutput, (source, textureURI, clippingRectangle, appliedTransform) =>
                {
                    List <Image> values = null;
                    if (imageBitmaps.TryGetValue(source, out values))
                    {
                        foreach (Image image in values)
                        {
                            image.TextureURI        = textureURI;
                            image.ClippingRectangle = clippingRectangle;
                            image.AppliedTransform  = appliedTransform;
                        }
                    }
                });
            }
        }
Пример #29
0
        public sealed override StreamingGameAsset Cook(CookingContext context)
        {
            string assetPath = Path.Combine(context.Directory, context.ExpandVariables(Input));
            string input     = Path.Combine(context.BaseDirectory, assetPath);

            if (File.Exists(input) == false)
            {
                throw new FileNotFoundException(string.Empty, input);
            }

            context.AddDependency(input);

            byte[] buffer = null;
            using (var fs = new FileStream(input, FileMode.Open, FileAccess.Read))
            {
                BinaryReader reader = new BinaryReader(fs);
                buffer = reader.ReadBytes((int)fs.Length);
            }

            return(new StreamingGameAsset(buffer));
        }
Пример #30
0
        public sealed override T Cook(CookingContext context)
        {
            if (BitmapSheetSize.IsEmpty)
            {
                throw new InvalidOperationException("BitmapSheetSize is empty.");
            }
            if (string.IsNullOrEmpty(TextureOutput))
            {
                throw new InvalidOperationException("TextureOutput is null.");
            }
            if (TextureOutput.Contains("{0}") == false)
            {
                throw new InvalidOperationException("TextureOutput not exists {0}.");
            }

            var input = Input.Cook(context);

            Export(context, input);

            return(input);
        }