RU2405205C1 - Method for generation of sprite - Google Patents

Method for generation of sprite Download PDF

Info

Publication number
RU2405205C1
RU2405205C1 RU2009123307/09A RU2009123307A RU2405205C1 RU 2405205 C1 RU2405205 C1 RU 2405205C1 RU 2009123307/09 A RU2009123307/09 A RU 2009123307/09A RU 2009123307 A RU2009123307 A RU 2009123307A RU 2405205 C1 RU2405205 C1 RU 2405205C1
Authority
RU
Russia
Prior art keywords
pixel
sprite
color
specified
data structure
Prior art date
Application number
RU2009123307/09A
Other languages
Russian (ru)
Inventor
Александр Иванович Алчинов (RU)
Александр Иванович Алчинов
Анатолий Борисович Подловченко (RU)
Анатолий Борисович Подловченко
Анатолий Витальевич Иванов (RU)
Анатолий Витальевич Иванов
Original Assignee
Учреждение Российской академии наук Институт проблем управления им. В.А. Трапезникова РАН
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Учреждение Российской академии наук Институт проблем управления им. В.А. Трапезникова РАН filed Critical Учреждение Российской академии наук Институт проблем управления им. В.А. Трапезникова РАН
Priority to RU2009123307/09A priority Critical patent/RU2405205C1/en
Application granted granted Critical
Publication of RU2405205C1 publication Critical patent/RU2405205C1/en

Links

Images

Landscapes

  • Controls And Circuits For Display Device (AREA)
  • Processing Or Creating Images (AREA)

Abstract

FIELD: information technologies.
SUBSTANCE: sprite represents images of irregular shape overlaid over background images, preferably online. Generated sprite has specified first multitude of possible values of non-transparent colours of pixels and at least one value of pixel colours identifying transparent colour of pixel. Sprite is generated using initial data, including the first data structure specifying colour image with specified second multitude of possible colours of pixels, and the second data structure specifying non-transparent part of specified sprite. Compliance of colours of the first data structure and possible non-transparent colours of sprite is partial projection of the specified second multitude into the specified first multitude, where augmentation of area of identification of specified partial projection to the specified second multitude is the multitude, capacity of which is considerably lower than capacity of the specified second capacity, besides to identify the value of colours included into the specified first multitude and complying with colour of pixel from the first data structure, the following actions are taken: if pixel of the first data structure has colour that does not belong to the specified area of identification, then value of this pixel is established as equal to colour being one of nearest to initial colour of pixel and included in the specified area of identification; specified partial projection is applied to colour of pixel of the first data structure.
EFFECT: improving sprite generation reliability.
5 cl, 2 dwg

Description

Изобретение относится к способам создания спрайтов, представляющих собой изображения неправильной формы и накладываемых на фоновые изображения, предпочтительно в реальном времени. Изобретение может быть использовано при формировании оверлейных изображений с заданным цветовым ключом в реальном времени.The invention relates to methods for creating sprites that are irregularly shaped images and superimposed on background images, preferably in real time. The invention can be used in the formation of overlay images with a given color key in real time.

В [http://www.xserver.ru/computer/langprogr/razn/36/10.shtml] плоские растровые изображения неправильной формы называются спрайтами. В документации к DirectX 2 SDK они называются декадами. Спрайт можно представить себе в виде фигурки, вырезанной из картона и установленной в определенной точке макета.In [http://www.xserver.ru/computer/langprogr/razn/36/10.shtml] flat raster images of irregular shape are called sprites. They are called decades in the DirectX 2 SDK documentation. The sprite can be imagined as a figure cut out of cardboard and installed at a certain point in the layout.

В [http://www.delphisources.ru/pages/faq/base/sprites_work.html] со ссылкой на книгу Андрэ Ла Мота спрайтами называются «маленькие объектики, которые находятся на игровом поле и могут двигаться. Этот термин прижился с легкой руки программистов фирмы Atari и Apple в середине 70-х годов. Спрайты - это персонажи в играх для ПК, которые могут без труда перемещаться по экрану, изменять цвет и размер». Другими словами, спрайт - это персонаж игры. Можно сказать, что спрайт - это массив из цветов; для простоты представим его как BMP файл или TBitmap, тем более, что этот формат поддерживается Windows и не содержит компрессии. Что нам: нужно от спрайта - заставить его появляться на экране и образовывать анимацию. Анимация - это не только смена координаты спрайта, но и изменение самого изображения. Следовательно, спрайт может иметь не одно изображение, а несколько. Смена их и приводит к анимации.In [http://www.delphisources.ru/pages/faq/base/sprites_work.html] with reference to the book by Andre La Mota, sprites are called "small objects that are on the playing field and can move. This term took root with the light hand of Atari and Apple programmers in the mid-70s. Sprites are characters in PC games that can easily move around the screen, change color and size. ” In other words, a sprite is a character in a game. We can say that a sprite is an array of flowers; for simplicity, imagine it as a BMP file or TBitmap, especially since this format is supported by Windows and does not contain compression. What we need: from the sprite - make it appear on the screen and form an animation. Animation is not only a change in the coordinate of a sprite, but also a change in the image itself. Therefore, a sprite can have not one image, but several. Changing them leads to animation.

В [http://durus.ru/content/view/292/59/] спрайтом называется изображение в прямоугольной области, заполненной цветовым ключом, где цветовой ключ - это один или несколько цветов, предназначенных для изображения "прозрачного" цвета. Пиксели, окрашенные этим цветом, не копируются при блиттинге. Это позволяет создавать иллюзию непрямоугольного изображения, хотя при блиттинге копируются только прямоугольные области.In [http://durus.ru/content/view/292/59/] a sprite refers to an image in a rectangular area filled with a color key, where the color key is one or more colors intended for the image of a "transparent" color. Pixels painted with this color are not copied when blitting. This allows you to create the illusion of a non-rectangular image, although only rectangular areas are copied when blitting.

В [http:/www.mobilab.ru/artictes/53/] спрайт - это частично прозрачное изображение или набор изображений, который может накладываться и перемещаться по заднему плану или по другому спрайту без необходимости перерисовывать все основное окно. Другими словами спрайт - это перемещаемый игровой объект.In [http: /www.mobilab.ru/artictes/53/] a sprite is a partially transparent image or a set of images that can be superimposed and moved in the background or in another sprite without the need to redraw the entire main window. In other words, a sprite is a roaming game object.

В [http://silencer.times.lv/tools_articles_1.htm] спрайты - это по сути то же самое, что и битмапы, но с одной отличительной особенностью - они имеют области с прозрачным цветом, который в процессе отрисовки просто игнорируется и не выводится. Термином «спрайт» еще иногда пользуются, чтобы указать на анимированный битмап. Современные спрайты состоят обычно из нескольких кадров анимации, это сделано для того, например, чтобы достичь эффекта летящего корабля, идущего человека и т.д.In [http://silencer.times.lv/tools_articles_1.htm] sprites are essentially the same as bitmaps, but with one distinctive feature - they have areas with a transparent color, which is simply ignored during rendering and not is displayed. The term "sprite" is still sometimes used to indicate an animated bitmap. Modern sprites usually consist of several frames of animation, this is done in order, for example, to achieve the effect of a flying ship, a walking person, etc.

В [http://computers.plib.ru/programming/SVGA/Glava%203/Index13.htm] спрайтами называются рисунки, для которых маска формируется динамически, в зависимости от значений кодов точек рисунка, но в любом случае маскировка преследует одну цель. Какой бы формы не был сам рисунок, например треугольник, стрелка, песочные часы и т.д., его образ всегда дополняется до прямоугольника, для того чтобы все строки имели одинаковый размер. Это существенно упрощает хранение и воспроизведение рисунков и одновременно вынуждает применять маскировку, исключающую вывод на экран той части прямоугольной области, которая не относится к рисунку. За счет наложения маски на экране показывается, например, изображение стрелки курсора, а не черный прямоугольник, на фоне которого она нарисована.In [http://computers.plib.ru/programming/SVGA/Glava%203/Index13.htm] sprites are called patterns for which the mask is formed dynamically, depending on the values of the code points of the picture, but in any case, the mask has the same purpose . Regardless of the shape of the drawing itself, for example, a triangle, an arrow, an hourglass, etc., its image is always supplemented to a rectangle so that all lines have the same size. This greatly simplifies the storage and reproduction of drawings and at the same time forces them to apply masking, which excludes the display on the screen of that part of the rectangular region that is not related to the picture. By applying a mask, for example, the image of the cursor arrow is shown on the screen, and not the black rectangle against which it is drawn.

В соответствии с [http://www.255.ru/index.php?newsid=636] спрайт - небольшое изображение, свободно перемещающееся по монитору. В первоначальном смысле слова этот термин применялся только для аппаратно выводимых изображений. Собственно, лишь один настоящий спрайт можно встретить на IBM PC - аппаратный курсор мыши. При архитектуре ×86 под спрайтом принято понимать программно выводимое изображение, которое может иметь сложную форму и передвигаться поверх фона, не затирая его.In accordance with [http://www.255.ru/index.php?newsid=636], a sprite is a small image that moves freely around the monitor. In the original sense of the word, this term was applied only to hardware-output images. Actually, only one real sprite can be found on an IBM PC - a hardware mouse cursor. With the architecture of × 86, it is customary to understand a sprite as a programmatically displayed image that can have a complex shape and move over the background without overwriting it.

В патенте США 6337701 спрайтами называются графические объекты, которые перемещаются по экрану дисплея перед любыми другими объектами.In US Pat. No. 6,337,701, sprites are called graphic objects that move across the display screen in front of any other objects.

В случае, когда используется 4-байтовое представление цветов пикселей, один из байтов отводится под так называемый альфа-канал, указывающий степень прозрачности пикселя. В этом случае никаких проблем с созданием спрайтов не возникает. Однако широко используются и форматы представления цвета, не содержащие альфа-канала. В этом случае для кодирования областей прозрачности используют специально выделяемые для этой цели цвета, совокупность которых определяет цветовой ключ.In the case when a 4-byte representation of the colors of the pixels is used, one of the bytes is allocated to the so-called alpha channel, indicating the degree of transparency of the pixel. In this case, there are no problems with creating sprites. However, color representation formats that do not contain an alpha channel are widely used. In this case, for coding transparency regions, colors specially allocated for this purpose are used, the combination of which determines the color key.

В [http://www.xserver.ru/computer/langprogr/razn/36/10.shtml] предложен способ создания спрайта, при котором удаляют все посторонние детали, чтобы оставить чистое изображение фигуры, и заполняют окружающий фон черным (прозрачным) цветом, при этом если исходное изображение содержит черные участки, заменяют черный цвет в изображении другим оттенком (например, вместо RGB: 0, 0, 0 можно использовать RGB: 0, 0, 1). Далее используют Microsoft Imager, чтобы сократить количество цветов с 256 до 8. Недостатком этого способа является то, что он предназначен только для создания спрайтов в палитровом режиме отображения, а также то, что он не предназначен для использования в реальном времени.In [http://www.xserver.ru/computer/langprogr/razn/36/10.shtml] a method for creating a sprite is proposed, in which all extraneous details are deleted to leave a clean image of the figure, and the surrounding background is filled with black (transparent) color, and if the original image contains black areas, replace the black color in the image with a different shade (for example, instead of RGB: 0, 0, 0, you can use RGB: 0, 0, 1). Then they use Microsoft Imager to reduce the number of colors from 256 to 8. The disadvantage of this method is that it is intended only for creating sprites in a palette display mode, and also that it is not intended for use in real time.

В [http://durus.ru/content/view/292/59/] предложен способ создания спрайта, при котором создают изображение, ограниченное прямоугольной областью, причем все пиксели этой прямоугольной области, которые не относятся к изображению, закрашивают особым цветом, который не использовался в самом изображении, и этот особый цвет назначают в качестве цветового ключа. При блиттинге он не будет копироваться, и вместо пикселей, окрашенных этим цветом, останутся пиксели фона - возникнет иллюзия прозрачности. Недостатком этого способа является то, что определение цвета, который не использовался в самом изображении, является весьма трудоемкой операцией, и поэтому весьма проблематичным является использование этого способа при создании спрайтов в реальном времени, особенно на маломощных компьютерах.In [http://durus.ru/content/view/292/59/] a method for creating a sprite is proposed, in which an image limited to a rectangular area is created, and all the pixels of this rectangular area that are not related to the image are painted with a special color, which was not used in the image itself, and this particular color is assigned as the color key. During blitting, it will not be copied, and instead of pixels colored with this color, background pixels will remain - an illusion of transparency will appear. The disadvantage of this method is that determining the color that was not used in the image itself is a very time-consuming operation, and therefore it is very problematic to use this method to create sprites in real time, especially on low-power computers.

В патенте США 6337701 (прототип) предложен способ порождения спрайта с заданным первым множеством возможных цветов пикселей по первой структуре данных, задающей цветное изображение с заданным вторым множеством возможных цветов пикселей, и по второй структуре данных, определяющей форму указанного спрайта. Для получения значения каждого пикселя спрайта определяют по второй структуре данных, входит ли указанный пиксель в непрозрачную часть указанного спрайта, и если да, то устанавливают значение цвета текущего пикселя спрайта равным значению из указанного первого множества цветов, соответствующему цвету пикселя из первой структуры данных, а если нет, то устанавливают значение цвета текущего пикселя спрайта равным значению, определяющему прозрачный цвет пикселя. Определение того, входит ли пиксель в непрозрачную часть указанного спрайта, производят путем определения, имеет ли соответствующий элемент второй структуры данных заранее определенное значение. При этом в качестве спрайта рассматривается цветной курсор, а формирование и вывод спрайта производят только в том случае, если число разных цветов в структуре цветовых данных изображения не превосходит числа доступных цветов в аппаратном спрайте. Недостатком этого способа является его низкая надежность, обусловленная тем, что вывод спрайта происходит, только когда число разных цветов в структуре цветовых данных изображения не превосходит числа доступных цветов в аппаратном спрайте. Это является следствием того, что в способе, являющемся прототипом, не производят никаких попыток скорректировать цвета в исходном изображении, чтобы удовлетворить аппаратным ограничениям на количество доступных цветов.US Pat. No. 6,337,701 (prototype) proposes a method for generating a sprite with a given first set of possible pixel colors from a first data structure that defines a color image with a given second set of possible pixel colors and a second data structure that determines the shape of the specified sprite. To obtain the value of each pixel of the sprite, it is determined by the second data structure whether the specified pixel is included in the opaque part of the specified sprite, and if so, then set the color value of the current sprite pixel to the value from the specified first set of colors, corresponding to the color of the pixel from the first data structure, and if not, set the color value of the current pixel of the sprite to a value that defines the transparent color of the pixel. The determination of whether a pixel is included in the opaque part of the specified sprite is made by determining whether the corresponding element of the second data structure has a predetermined value. In this case, the color cursor is considered as a sprite, and the formation and output of the sprite is performed only if the number of different colors in the structure of the color data of the image does not exceed the number of available colors in the hardware sprite. The disadvantage of this method is its low reliability, due to the fact that the output of the sprite occurs only when the number of different colors in the structure of the color data of the image does not exceed the number of available colors in the hardware sprite. This is a consequence of the fact that in the prototype method, no attempt is made to adjust the colors in the original image to satisfy the hardware limitations on the number of available colors.

С учетом изложенного, актуальной является разработка способа порождения спрайта, имеющего заданное первое множество возможных значений непрозрачных цветов пикселей и по меньшей мере одно заданное значение цвета пикселей, определяющее прозрачный цвет пикселя, при котором спрайт порождают по исходным данным, включающим в себя первую структуру данных, задающую цветное изображение с заданным вторым множеством возможных цветов пикселей, и вторую структуру данных, определяющую непрозрачную часть указанного спрайта. При этом способ должен обеспечивать порождение спрайта даже в том случае, когда количество разных цветов в структуре цветовых данных изображения превосходит количество доступных цветов, обусловленное аппаратными ограничениями, чтобы не приводить к ситуации, когда невозможно создать спрайт.In view of the foregoing, it is urgent to develop a method for generating a sprite having a predetermined first set of possible values of opaque pixel colors and at least one predetermined pixel color value defining a transparent pixel color, in which the sprite is generated from the source data including the first data structure, defining a color image with a given second set of possible pixel colors, and a second data structure defining an opaque part of the specified sprite. In this case, the method should ensure that the sprite is generated even when the number of different colors in the structure of the color image data exceeds the number of available colors due to hardware limitations so as not to lead to a situation where it is impossible to create a sprite.

Это достигается за счет того, что для получения значения каждого пикселя спрайта определяют по второй структуре данных, входит ли указанный пиксель в непрозрачную часть указанного спрайта, и если да, то устанавливают значение цвета текущего пикселя спрайта равным значению из указанного первого множества цветов, соответствующему цвету пикселя из первой структуры данных, а если нет, то устанавливают значение цвета текущего пикселя спрайта равным значению, определяющему прозрачный цвет пикселя. При этом в отличие от прототипа соответствие цветов первой структуры данных и возможных непрозрачных цветов спрайта является частичным отображением указанного второго множества в указанное первое множество. Дополнение области определения указанного частичного отображения до указанного второго множества является множеством, мощность которого существенно меньше мощности указанного второго множества. Для определения значения, входящего в указанное первое множество цветов и соответствующего цвету пикселя из первой структуры данных, выполняют следующие действия:This is achieved due to the fact that to obtain the values of each pixel of the sprite, it is determined from the second data structure whether the specified pixel is included in the opaque part of the specified sprite, and if so, then set the color value of the current sprite pixel to the value from the specified first set of colors corresponding to the color pixels from the first data structure, and if not, then set the color value of the current sprite pixel to a value that defines the transparent color of the pixel. Moreover, unlike the prototype, the correspondence of the colors of the first data structure and the possible opaque colors of the sprite is a partial mapping of the specified second set to the specified first set. Supplementing the definition domain of said partial mapping to said second set is a set whose power is substantially less than the power of said second set. To determine the value included in the specified first set of colors and corresponding to the color of the pixel from the first data structure, perform the following steps:

если пиксель первой структуры данных имеет цвет, не принадлежащий указанной области определения, то значение этого пикселя устанавливают равным цвету, являющемуся одним из ближайших к исходному цвету пикселя и входящим в указанную область определения;if the pixel of the first data structure has a color that does not belong to the specified definition area, then the value of this pixel is set to a color that is one of the pixels closest to the original color and is included in the specified definition area;

применяют к цвету пикселя первой структуры данных указанное частичное отображение.the specified partial mapping is applied to the pixel color of the first data structure.

За счет коррекции значений пикселей первой структуры данных и использования частичного отображения второго множества в указанное первое множество, т.е. множества всех цветов изображения в множество допустимых непрозрачных цветов спрайта, достигается основной технический результат, состоящий в повышении надежности способа порождения спрайта, поскольку в отличие от прототипа порождение спрайта оказывается возможно в любом случае. При этом возможно некоторое снижение качества спрайта, связанное с искажением значений некоторых цветов исходного изображения. Однако в большинстве случаев область определения частичного отображения выбирают таким образом, что максимальное расстояние от точек дополнения до области определения является очень небольшим, и тем самым указанное искажение оказывается практически незаметным.By correcting the pixel values of the first data structure and using a partial mapping of the second set to the specified first set, i.e. the set of all colors of the image into the set of acceptable opaque colors of the sprite, the main technical result is achieved, which consists in increasing the reliability of the method of generating the sprite, because, unlike the prototype, the generation of the sprite is possible in any case. In this case, a slight decrease in the quality of the sprite is possible due to the distortion of the values of some colors of the original image. However, in most cases, the partial display definition area is chosen so that the maximum distance from the points of addition to the definition area is very small, and thus the specified distortion is almost imperceptible.

Изобретение поясняется чертежами, гдеThe invention is illustrated by drawings, where

Фиг.1. Формирование спрайта по двум структурам исходных данных.Figure 1. Formation of a sprite using two input data structures.

Фиг.2. Структура частичного отображения φ0.Figure 2. Partial mapping structure φ 0 .

Осуществление изобретенияThe implementation of the invention

1. Общее описание1. General description

Основное требование к порождаемому спрайту состоит в том, что цвета пикселей спрайта должны принадлежать заданному первому множеству возможных значений непрозрачных цветов пикселей, из которого исключены значения, определяющие прозрачный цвет пикселей. При этом как указанное первое множество возможных значений непрозрачных цветов пикселей, так и значения, определяющие прозрачный цвет пикселей, являются подмножеством пространства возможных аппаратно реализуемых цветов. Графическая система компьютера при наложении (оверлее) спрайта на фоновое изображение будет заменять значения пикселей фонового изображения соответствующими значениями пикселей спрайта, если они соответствуют непрозрачным цветам пикселей, и оставлять значения пикселей фонового изображения неизменными, если соответствующие пиксели спрайта имеют значения, определяющие прозрачный цвет пикселя. При этом очень важно, чтобы никакой пиксель спрайта внутри области, соответствующей непрозрачной части, не имел значения, соответствующего прозрачному цвету. В противном случае в таких пикселях вместо цвета изображения спрайта наблюдатель будет видеть цвет фона, на который наложен спрайт, а сам спрайт будет казаться имеющим «дырку».The main requirement for the generated sprite is that the colors of the sprite pixels must belong to a given first set of possible values of opaque pixel colors, from which the values defining the transparent color of the pixels are excluded. Moreover, both the indicated first set of possible values of the opaque pixel colors and the values defining the transparent color of the pixels are a subset of the space of possible hardware-implemented colors. When overlaying a sprite on a background image, the computer graphics system will replace the pixel values of the background image with the corresponding pixel values of the sprite, if they correspond to opaque pixel colors, and leave the pixel values of the background image unchanged if the corresponding sprite pixels have values that define the transparent color of the pixel. It is very important that no sprite pixel inside the area corresponding to the opaque part has a value corresponding to a transparent color. Otherwise, in such pixels, instead of the color of the sprite image, the observer will see the background color on which the sprite is superimposed, and the sprite itself will appear to have a “hole”.

При выводе спрайта на экран компьютера в виде оверлея множество прозрачных цветов задается цветовым ключом. Для оверлейной поверхности устанавливают цветовой ключ источника, задающий диапазон прозрачных цветов. В соответствии с [http://www.bringyou.to/games/ddraw.PDF, p.36] цветовой ключ используется при вызове метода IDirectDrawSurface::UpdateOverlay для управления тем, какая часть оверлейной поверхности будет видна над первичной поверхностью, а какая часть оверлейной поверхности будет прозрачной. Цветовые ключи оверлея могут быть связаны как с источником, так и с приемником, что устанавливается методом IDirectDrawSurface::SetColorKey. При выводе спрайтов в виде оверлея используют цветовой ключ источника, для чего выставляют флаг DDCKEY_SRCOVERLAY в первом параметре dwFlags этого метода. Метод IDirectDrawSurface::UpdateOverlay использует цветовой ключ источника, чтобы определить, какие пиксели спрайта на оверлейной поверхности следует рассматривать как прозрачные, дающие возможность видеть через них первичную поверхность. Формирование цветового ключа может производиться разными способами, которые рассматриваются в п.2.When a sprite is displayed on the computer screen as an overlay, many transparent colors are set with a color key. For the overlay surface, set the color key of the source, which sets the range of transparent colors. According to [http://www.bringyou.to/games/ddraw.PDF, p.36], the color key is used when calling the IDirectDrawSurface :: UpdateOverlay method to control which part of the overlay surface will be visible above the primary surface and which part of the overlay surface will be transparent. Overlay color keys can be associated with either a source or a receiver, which is set using the IDirectDrawSurface :: SetColorKey method. When displaying sprites in the form of an overlay, the source color key is used, for which the DDCKEY_SRCOVERLAY flag is set in the first dwFlags parameter of this method. The IDirectDrawSurface :: UpdateOverlay method uses the source color key to determine which sprite pixels on the overlay surface should be considered transparent, making it possible to see the primary surface through them. The formation of the color key can be done in different ways, which are discussed in paragraph 2.

Исходные данные для порождения спрайта включают в себя две структуры данных, где первая структура данных задает цветное изображение с заданным вторым множеством возможных цветов пикселей, а вторая структура данных определяет непрозрачную часть указанного спрайта (см. фиг.1).The initial data for generating the sprite includes two data structures, where the first data structure defines a color image with a given second set of possible pixel colors, and the second data structure defines the opaque part of the specified sprite (see FIG. 1).

В качестве первой структуры данных, которая задает цветное изображение с заданным вторым множеством возможных цветов пикселей, может использоваться любое изображение в одном из стандартных форматов, таких как BMP, TIFF и т.п. При этом пространство V возможных цветов пикселей такого исходного изображения может как совпадать с пространством W возможных аппаратно реализуемых цветов спрайта, так и отличаться от него. В любом случае при блиттинге исходного изображения в поверхность спрайта происходит аппаратное преобразование цветов исходного изображения в аппаратно реализуемые цвета. Это преобразование определяет отображение φ:V→W. Пространство возможных непрозрачных цветов спрайта является подмножеством W0⊂W множества всех аппаратно реализуемых цветов, из которого удалены все цвета, которые определяют прозрачный цвет пикселей спрайта. Эти цвета обычно определяются значением цветового ключа и составляют параллелепипед K в пространстве W всех аппаратно реализуемых цветов. Тем самым имеет место частичное отображение φ0: V→W0, имеющее область определения φ0-1(W0)=φ-1(W0)=V/φ-1(K) (см. фиг.2). Таким образом, соответствие цветов первой структуры данных и возможных непрозрачных цветов спрайта является частичным отображением указанного второго множества в указанное первое множество.As the first data structure that defines a color image with a given second set of possible pixel colors, any image in one of the standard formats, such as BMP, TIFF, etc., can be used. At the same time, the space V of possible pixel colors of such an initial image can both coincide with the space W of possible hardware-implemented sprite colors and be different from it. In any case, when blitting the original image into the sprite surface, the hardware converts the colors of the original image into hardware-implemented colors. This transformation defines a map φ: V → W. The space of possible opaque sprite colors is a subset of W 0 ⊂ W of the set of all hardware-implemented colors, from which all colors that define the transparent color of the sprite pixels are removed. These colors are usually determined by the value of the color key and constitute the box K in the space W of all hardware-implemented colors. Thus, there is a partial mapping φ 0 : V → W 0 having a domain of definition φ 0 -1 (W 0 ) = φ -1 (W 0 ) = V / φ -1 (K) (see Fig. 2). Thus, the correspondence of the colors of the first data structure and the possible opaque colors of the sprite is a partial mapping of the specified second set to the specified first set.

Дополнение φ-1(K) области определения указанного частичного отображения до указанного второго множества является множеством, мощность которого существенно меньше мощности указанного второго множества. Действительно, как будет видно из п.2, мощность множества K существенно меньше мощности множества W всех аппаратно реализуемых цветов. Кроме того, в реальных ситуациях блиттинга исходного изображения в спрайт число цветов исходного изображения, которые могут переходить в один цвет спрайта, является очень небольшим, иначе качество изображения будет неизбежно испорчено при блиттинге. Отсюда следует, что мощность множества φ-1(K) существенно меньше мощности указанного второго множества, причем для каждой точки из множества φ-1(K) найдется близкая к ней точка из области определения V/φ-1(K) (см. фиг.2).The complement φ -1 (K) of the domain of the indicated partial mapping to the specified second set is a set whose power is substantially less than the power of the specified second set. Indeed, as will be seen from Section 2, the power of the set K is significantly less than the power of the set W of all hardware-implemented colors. In addition, in real situations when blitting an original image into a sprite, the number of colors in the original image that can turn into a single sprite color is very small, otherwise the image quality will inevitably be corrupted when blitting. It follows that the cardinality of the set φ -1 (K) is significantly less than the cardinality of the specified second set, and for each point from the set φ -1 (K) there is a point close to it from the domain V / φ -1 (K) (see figure 2).

Возможно несколько вариантов второй структуры данных, определяющей непрозрачную часть формируемого спрайта. В любом случае такая структура данных должна позволять для каждого пикселя формируемого спрайта определять, должен этот пиксель входить в непрозрачную часть спрайта и иметь цвет, соответствующий цвету пикселя исходного изображения, или должен иметь прозрачный цвет. Широко используются по крайней мере три типа структур данных для задания непрозрачной части спрайта: битовая маска, набор горизонтальных отрезков пикселей и векторное задание границы непрозрачной части спрайта.There are several options for the second data structure that defines the opaque part of the generated sprite. In any case, such a data structure should allow for each pixel of the generated sprite to determine whether this pixel should be part of the opaque part of the sprite and have a color that matches the pixel color of the original image, or should have a transparent color. At least three types of data structures are widely used for defining an opaque part of a sprite: a bit mask, a set of horizontal segments of pixels, and vector defining the border of an opaque part of a sprite.

Порождение спрайта производят следующим образом. Прежде всего, для каждого цвета С из множества φ-1(K) определяют заменяющей его цвет C', являющийся ближайшим к цвету С из всех цветов, не входящих в множество φ-1(K). После этого составляют список всех таких пар (С, С') и упорядочивают множество всех таких пар по возрастанию С. Эти действия могут быть произведены один раз перед началом работы приложения, использующего формирование спрайтов. При необходимости построить спрайт по вышеуказанным исходным данным для получения значения каждого пикселя спрайта определяют по второй структуре данных, входит ли указанный пиксель в непрозрачную часть указанного спрайта. Если пиксель входит в непрозрачную часть спрайта, то проверяют, совпадает ли цвет пикселя с одним из цветов С из имеющегося списка пар (С, С'), и если да, то заменяют цвет пикселя С соответствующим цветом С'. В противном случае никакой замены цвета пикселя не производят. После этого устанавливают значение цвета текущего пикселя спрайта равным значению, входящему в указанное первое множество цветов и соответствующему цвету пикселя из первой структуре данных, применяя отображение φ. Если пиксель не входит в непрозрачную часть спрайта, то устанавливают значение цвета текущего пикселя спрайта равным значению, определяющему прозрачный цвет пикселя.Sprite generation is as follows. First of all, for each color C from the set φ -1 (K), the color C 'replacing it is determined, which is the closest to the color C from all the colors not included in the set φ -1 (K). After that, make a list of all such pairs (C, C ') and arrange the set of all such pairs in ascending order C. These actions can be performed once before starting an application using sprite generation. If necessary, build a sprite from the above source data to obtain the value of each pixel of the sprite is determined by the second data structure, whether the specified pixel is included in the opaque part of the specified sprite. If the pixel is included in the opaque part of the sprite, then check whether the pixel color matches one of the colors C from the existing list of pairs (C, C '), and if so, then replace the color of the pixel C with the corresponding color C'. Otherwise, no pixel color change is performed. After that, set the color value of the current pixel of the sprite equal to the value included in the specified first set of colors and the corresponding color of the pixel from the first data structure, using the mapping φ. If the pixel is not included in the opaque part of the sprite, then set the color value of the current pixel of the sprite to a value that defines the transparent color of the pixel.

2. Формирование цветового ключа2. Formation of a color key

Цветовой ключ оверлея для вывода спрайтов удобнее всего формировать таким образом, чтобы значение верхней границы диапазона цветового ключа совпадало со значением нижней границы диапазона цветового ключа. Тем самым набор цветов, принадлежащих диапазону цветов цветового ключа, будет состоять только из одного цвета, называемого ключевым цветом. Выбор ключевого цвета зависит от глубины цвета пикселей. Чаще всего в качестве ключевого цвета выбирают фиксированный цвет, который реже всего встречается на реальных изображениях. Приемлемыми являются, например, черный цвет [http://progma.narod.ru/directdraw.html], синий цвет [http://jack.kiev.ua/linuxjournal/LJ/0081/4401.html], красно-синий цвет [http://mini-stalker.googlecode.com/svn-history/r29/trunk/Mini_STALKER/animation.h], фуксин [http://www.gamasutra.com/features/20010629/geczy_02.htm].It is most convenient to form the overlay color key for sprite output so that the value of the upper border of the color key range coincides with the value of the lower border of the color key range. Thus, the set of colors belonging to the color key color range will consist of only one color, called the key color. The choice of key color depends on the color depth of the pixels. Most often, a fixed color is chosen as the key color, which is least likely to be found in real images. Acceptable are, for example, black [http://progma.narod.ru/directdraw.html], blue [http://jack.kiev.ua/linuxjournal/LJ/0081/4401.html], red-blue color [http://mini-stalker.googlecode.com/svn-history/r29/trunk/Mini_STALKER/animation.h], fuchsin [http://www.gamasutra.com/features/20010629/geczy_02.htm].

Иногда встречается ситуация, когда в качестве цветового ключа используют не один цвет, а множество цветов, представляющих собой параллелепипед в пространстве цветов. Например, в известной технологии «голубого экрана» с целью формирования спрайта производят съемку реальной сцены, например, диктора телевизионной программы, на фоне голубого задника, после чего вырезают только ту часть изображения, которая соответствует реальной сцене. В этом случае в качестве цветового ключа удобно использовать минимальный параллелепипед в пространстве цветов, содержащий цвета всех пикселей изображения, соответствующие заднику.Sometimes a situation occurs when not one color is used as a color key, but many colors representing a parallelepiped in the color space. For example, in the well-known blue screen technology, in order to form a sprite, a real scene, for example, an announcer of a television program, is shot against a blue backdrop, after which only that part of the image that corresponds to the real scene is cut out. In this case, it is convenient to use the minimum box in the color space as the color key, which contains the colors of all image pixels corresponding to the backdrop.

В любом случае множество цветов, входящих в цветовой ключ, имеет мощность, существенно меньшую мощности всех возможных цветов изображения.In any case, the set of colors included in the color key has a power significantly less than the power of all possible colors of the image.

Если исходное изображение, задаваемое первой структурой данных, имеет глубину цвета, совпадающую с глубиной цвета спрайтов, то значение ключевого цвета можно выбрать так, чтобы при конвертировании формата цвета пикселей исходного изображения самое большее один цвет пикселей любого такого исходного изображения при конвертировании принимал значение ключевого цвета. В самом деле, рассмотрим отображение φ цветового пространства исходного изображения в цветовое пространство спрайтов. Поскольку эти два цветовых пространства имеют одинаковую глубину цвета, то мощности двух цветовых пространств совпадают. Следовательно, либо отображение φ биективно, либо не является сюръективным. В первом случае при любом выборе значения ключевого цвета при конвертировании формата цвета пикселей исходного изображения самое большее один цвет пикселей любого такого исходного изображения при конвертировании может принять значение ключевого цвета. Во втором случае в цветовом пространстве оверлейной поверхности существует такое значение цвета, которое лежит вне образа отображения φ. Если это значение взять в качестве ключевого цвета, то при конвертировании формата цвета пикселей исходного изображения ни один цвет пикселей любого такого исходного изображения при конвертировании не сможет принять значение ключевого цвета. Способ реализации такого выбора ключевого цвета очевиден: достаточно конвертировать массив всех цветов цветового пространства исходных изображений в цветовое пространство спрайтов, упорядочить полученные значения по возрастанию и в качестве ключевого цвета выбрать любое значение, пропущенное в полученном массиве цветов. Если пропущенных значений нет, то отображение φ является биективным, и в качестве ключевого цвета можно взять любой цвет.If the original image specified by the first data structure has a color depth that matches the color depth of the sprites, then the key color value can be chosen so that when converting the pixel color format of the source image, at most one pixel color of any such source image when converted takes the key color value . In fact, we consider the mapping φ of the color space of the original image into the color space of sprites. Since these two color spaces have the same color depth, the powers of the two color spaces coincide. Therefore, either the map φ is bijective or not surjective. In the first case, at any choice of the key color value when converting the pixel color format of the source image, at most one pixel color of any such source image during conversion can take the key color value. In the second case, in the color space of the overlay surface, there is a color value that lies outside the image of the mapping φ. If this value is taken as the key color, then when converting the pixel color format of the source image, no pixel color of any such source image will be able to take the key color value when converting. The way to implement this choice of key color is obvious: it is enough to convert an array of all the colors in the color space of the source images into the color space of the sprites, arrange the obtained values in ascending order and select any value that is missing in the resulting color array as the key color. If there are no missing values, then the mapping φ is bijective, and any color can be taken as the key color.

Claims (5)

1. Способ порождения спрайта, имеющего заданное первое множество возможных значений непрозрачных цветов пикселей и по меньшей мере одно заданное значение цвета пикселей, определяющее прозрачный цвет пикселя, при котором спрайт порождают по исходным данным, включающим в себя первую структуру данных, задающую цветное изображение с заданным вторым множеством возможных цветов пикселей, и вторую структуру данных, определяющую непрозрачную часть указанного спрайта, при котором для получения значения каждого пикселя спрайта определяют по второй структуре данных входит ли указанный пиксель в непрозрачную часть указанного спрайта, и если да, то устанавливают значение цвета текущего пикселя спрайта равным значению из указанного первого множества цветов, соответствующему цвету пикселя из первой структуры данных, а если нет, то устанавливают значение цвета текущего пикселя спрайта равным значению, определяющему прозрачный цвет пикселя, отличающийся тем, что соответствие цветов первой структуры данных и возможных непрозрачных цветов спрайта является частичным отображением указанного второго множества в указанное первое множество, где дополнение области определения указанного частичного отображения до указанного второго множества является множеством, мощность которого существенно меньше мощности указанного второго множества, причем для определения значения, входящего в указанное первое множество цветов и соответствующего цвету пикселя из первой структуры данных, выполняют следующие действия: если пиксель первой структуры данных имеет цвет, не принадлежащий указанной области определения, то значение этого пикселя устанавливают равным цвету, являющемуся одним из ближайших к исходному цвету пикселя и входящим в указанную область определения; применяют к цвету пикселя первой структуры данных указанное частичное отображение.1. A method of generating a sprite having a predetermined first set of possible values of opaque pixel colors and at least one predetermined pixel color value defining a transparent pixel color, in which a sprite is generated from source data including a first data structure defining a color image with a given the second set of possible pixel colors, and a second data structure that defines the opaque part of the specified sprite, in which to obtain the values of each pixel of the sprite is determined by W In the next data structure, does the specified pixel enter the opaque part of the specified sprite, and if so, set the color value of the current pixel of the sprite to the value from the specified first set of colors, the corresponding color of the pixel from the first data structure, and if not, set the color value of the current pixel sprite equal to the value that defines the transparent color of the pixel, characterized in that the correspondence of the colors of the first data structure and the possible opaque colors of the sprite is a partial display of of said second set to said first set, where the addition of the definition region of said partial display to said second set is a set whose power is substantially less than the power of said second set, and for determining a value included in said first set of colors and corresponding to a pixel color from the first data structure , perform the following steps: if the pixel of the first data structure has a color that does not belong to the specified definition area, then the value of the pixel is set equal to the color, which is one of the closest to the original color of the pixel and included in the specified domain; the specified partial mapping is applied to the pixel color of the first data structure. 2. Способ по п.1, отличающийся тем, что множество прозрачных цветов состоит только из одного элемента.2. The method according to claim 1, characterized in that the set of transparent colors consists of only one element. 3. Способ по п.1, отличающийся тем, что множество прозрачных цветов является параллелепипедом в пространстве цветов спрайта.3. The method according to claim 1, characterized in that the set of transparent colors is a parallelepiped in the color space of the sprite. 4. Способ по п.1, отличающийся тем, что дополнение области определения указанного частичного отображения до указанного второго множества является прообразом цветового ключа при операции блиттинга указанной первой структуры данных в пространство спрайтов.4. The method according to claim 1, characterized in that the addition of the definition area of the specified partial display to the specified second set is a prototype of the color key during the blitting operation of the specified first data structure into the sprite space. 5. Способ по п.1, отличающийся тем, что дополнение области определения указанного частичного отображения до указанного второго множества является множеством из самое большее одного элемента. 5. The method according to claim 1, characterized in that the addition of the definition area of the specified partial display to the specified second set is a set of at most one element.
RU2009123307/09A 2009-06-19 2009-06-19 Method for generation of sprite RU2405205C1 (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
RU2009123307/09A RU2405205C1 (en) 2009-06-19 2009-06-19 Method for generation of sprite

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2009123307/09A RU2405205C1 (en) 2009-06-19 2009-06-19 Method for generation of sprite

Publications (1)

Publication Number Publication Date
RU2405205C1 true RU2405205C1 (en) 2010-11-27

Family

ID=44057697

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2009123307/09A RU2405205C1 (en) 2009-06-19 2009-06-19 Method for generation of sprite

Country Status (1)

Country Link
RU (1) RU2405205C1 (en)

Non-Patent Citations (1)

* Cited by examiner, † Cited by third party
Title
Dave Shea, CSS Sprites: Image Slicing's Kiss of Death, March 5, 2004, найдено в Интернет на http://www.alistapart.com/articles/sprites. XNA 101.Net, Lesson 10-12, Sprite Color, Sprite Scaling, Transparent Sprites, 11.11.2008, найдено в Интернет на http://www.bluerosegames.com/xna101/archive.aspx. Программное обеспечение Sprite Explorer 2.0, 06 июня 2009, найдено в Интернет на http://makemap.ru/programs/spritevi/24-sprite-explorer-20.html. *

Similar Documents

Publication Publication Date Title
JP4680407B2 (en) Coding with variable bit field
US6971071B1 (en) System and method for implementing an image ancillary to a cursor
US20020149600A1 (en) Method of blending digital pictures
RU2312404C2 (en) Hardware acceleration of graphical operations during construction of images based on pixel sub-components
US7688317B2 (en) Texture mapping 2-D text properties to 3-D text
US20060232602A1 (en) Font generation system
CN109118556B (en) Method, system and storage medium for realizing animation transition effect of UI (user interface)
JP4075039B2 (en) Texture mapping method, program and apparatus
US7342585B2 (en) Use of an input overscaled bitmap to generate emboldened overscaled bitmap
WO2007038141A2 (en) Method and apparatus for superimposing characters on video
CN110149550B (en) Image data processing method and device and storage medium
JP2006332908A (en) Color image display apparatus, color image display method, program, and recording medium
JP7160495B2 (en) Image preprocessing method, device, electronic device and storage medium
CN112204619A (en) Method and device for processing image layer
US9092911B2 (en) Subpixel shape smoothing based on predicted shape background information
US7969441B2 (en) Adaptive contextual filtering based on typographical characteristics
RU2405205C1 (en) Method for generation of sprite
JP4174133B2 (en) Image generation method
JP2001070634A (en) Game machine and its playing method
JPH11232438A (en) Information processor and information recording medium
JPH11272846A (en) Graphic display
Packard Translucent windows in x
JP4617501B2 (en) Texture mapping method, program and apparatus
Anholt High Performance X Servers in the Kdrive Architecture.
KR20050009919A (en) Method for displaying graphic image

Legal Events

Date Code Title Description
MM4A The patent is invalid due to non-payment of fees

Effective date: 20180620