I am making a game in which i am making arcs using ShapeRenderer, As i needed to rotate those arcs around the center so i wrote that code only begin and end in render method, I am initializing them in create method,
But as the number of arcs increases the game gets slower and slower. I have maximum of 13 arcs and minimum 2 arcs.
It running fine till few say 8 arcs and after that it gets slower.
Please any one out there if he/she can help, please help...
thanks in advance.
Render Method is having 5 loops, I don't have any choice to get rid of them.
this is in create:
for (int i = 0; i < 13; i++) {
random = randomGenerator.nextInt(5);
a[i] = new Arc(arcColors[random]);
arcs_visible[i] = 1;
pointercolor[i] = a[i].getArcColor();
a[i].begin(ShapeRenderer.ShapeType.Line);
}
this is in render:
private void draw_one_arc(int i, double radius, float startangle, float sweep) {
if (arcs_visible[i] == 1 && collides[i] == false) {
a[i].arc(pointerorigin.x + pointer.getWidth() / 2, pointerorigin.y + pointer.getWidth() / 2, (float) radius, startangle, sweep, 100);
}
}
`
I need a way to find the coordinates of each pixel that have a specific color. I could loop through every pixel in the entire image and check if that matches, but that doesn't seem very efficient. Is there a better way?
You will have to loop through the array as that is the only way to evaluate all the pixels in the canvas.
However, you can use 32-bit integer (typed) array instead of the standard 8-bit array - that will be many times faster:
var idata = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height),
buffer32 = new Uint32Array(idata.data.buffer),
len = buffer32.length,
i = 0, x, y,
color = 0xffffffff; /// white color (ABGR format on little-endian systems)
for(; i < len; i++) {
if (buffer32[i] === color) {
/// convert i to x/y position here
x = i % idata.width;
y = (i / idata.height)|0;
}
}
I am trying to display multiple random grass tile images across the 1200 pixel width window. I am using a method called placeGrass which takes an image, an x coordinate, a y coordinate, and then displays the object at that given coordinate. This works correctly if I use my method getRandomGrass() (which returns a random grass tile image) and type in each coordinate by hand. However, when I try and use a method I made called printGrass(), the flash application fails to boot up.
Here is my attempt at the printGrass() method.
public function printGrass():void
{
var grass:Grass = new Grass(play);
for(var i:int = 0; i < 1200; i + 64)
{
grass.placeGrass(grass.getRandomGrass(), i, 800);
}
}
Where as my manual attempts below work correctly.
var test:Grass = new Grass(play);
test.placeGrass(test.getRandomGrass(), 0, 800);
var test2:Grass = new Grass(play);
test2.placeGrass(test2.getRandomGrass(), 64, 800);
I believe the for statement is never terminated because the counter does not increment the i variable.
for(var i:int = 0; i < 1200; i + 64)
should read
for(var i:int = 0; i < 1200; i += 64)
i + 64 will just return 64 each time where i += 64 will increment i each time.
I hope this helps.
Im using a very big BitmapData as a pathing map for my platformer game, however I only use pixels for 4 particular values, instead of, well 4294967295.
Would converting this Bitmapdata as 2 2D Vectors of Boolean save me some memory ?
And if it does, what about performance, would it be faster or slower to do something like:
MapGetPixel(x:int, y:int):int
{
return MapBoolFirst[x][y] + MapBoolSecond[x][y]*2;
}
instead of the bitmapdata class getPixel32(x:int, y:int):uint ?
In short im looking for a way to reduce the size and/or optimize my 4 colors bitmapdata.
Edit :
Using my boolean method apparently consumes 2 times more memory than the bitmapdata one.
I guess a boolean takes more than one bit in memory, else that would be too easy. So im thinking about bitshifting ints and thus have an int store the value for several pixels, but im not sure about this…
Edit 2 :
Using int bitshifts I can manage the data of 16 pixels into a single int, this trick should work to save some memory, even if it'll probably hit performance a bit.
Bitshifting will be the most memory-optimized way of handling it. Performance wise, that shouldn't be too big of an issue unless you need to poll a lot of asks each frame. The issue with AS is that booleans are 4bits :(
As I see it you can handle it in different cases:
1) Create a lower res texture for the hit detections, usually it is okay to shrink it 4 times (256x256 --> 64x64)
2) Use some kind of technique of saving that data into some kind of storage (bool is easiest, but if that is too big, then you need to find another solution for it)
3) Do the integer-solution (I haven't worked with bit-shifting before, so I thought it would be a fun challenge, here's the result of that)
And that solution is way smaller than the one used for boolean, and also way harder to understand :/
public class Foobar extends MovieClip {
const MAX_X:int = 32;
const MAX_Y:int = 16;
var _itemPixels:Vector.<int> = new Vector.<int>(Math.ceil(MAX_X * MAX_Y / 32));
public function Foobar() {
var pre:Number = System.totalMemory;
init();
trace("size=" + _itemPixels.length);
for (var i = 0; i < MAX_Y; ++i) {
for (var j = 0; j < MAX_X; ++j) {
trace("item=" + (i*MAX_X+j) + "=" + isWalkablePixel(j, i));
}
}
trace("memory preInit=" + pre);
trace("memory postInit=" + System.totalMemory);
}
public function init() {
var MAX_SIZE:int = MAX_X * MAX_Y;
var id:int = 0;
var val:int = 0;
var b:Number = 0;
for(var y=0; y < MAX_Y; ++y) {
for (var x = 0; x < MAX_X; ++x) {
b = Math.round(Math.random()); //lookup the pixel from some kind of texture or however you expose the items
if (b == 1) {
id = Math.floor((y * MAX_X + x) / 32);
val = _itemPixels[id];
var it:uint = (y * MAX_X + x) % 32;
b = b << it;
val |= b;
_itemPixels[id] = val;
}
}
}
}
public function isWalkablePixel(x, y):Boolean {
var val:int = _itemPixels[Math.floor((y * MAX_X + x) / 32)];
var it:uint = 1 << (y * MAX_X + x) % 32;
return (val & it) != 0;
}
}
One simple improvement is to use a ByteArray instead of BitmapData. That means each "pixel" only takes up 1 byte instead of 4. This is still a bit wasteful since you're only needing 2 bits per pixel and not 8, but it's a lot less than using BitmapData. It also gives you some "room to grow" without having to change anything significant later if you need to store more than 4 values per pixel.
ByteArray.readByte()/ByteArray.writeByte() works with integers, so it's really convenient to use. Of course, only the low 8 bits of the integer is written when calling writeByte().
You set ByteArray.position to the point (0-based index) where you want the next read or write to start from.
To sum up: Think of the ByteArray as a one dimensional Array of integers valued 0-255.
Here are the results, I was using an imported 8 bit colored .png by the way, not sure if it changes anything when he gets converted into a
BitmapData.
Memory usage :
BitmapData : 100%
Double Boolean vectors : 200%
Int Bitshifting : 12%
So int bitshifting win hands down, it works pretty much the same way as hexadecimal color components, however in that case I store 16 components (pixel values in 2 bits) not the 4 ARGB:
var pixels:int = -1;// in binary full of 1
for (var i:int = 0; i < 16; i++)
trace("pixel " + (i + 1) +" value : " + (pixels >> i * 2 & 3));
outputs as expected :
"pixel i value : 3"
i've come across this ActionScript sample, which demonstrates drawing of the color spectrum, one line at a time via a loop, using waveforms.
however, the waveform location of each RGB channel create a color spectrum that is missing colors (pure yellow, cyan and magenta) and therefore the spectrum is incomplete.
how can i remedy this problem so that the drawn color spectrum will exhibit all colors?
// Loop through all of the pixels from '0' to the specified width.
for(var i:int = 0; i < nWidth; i++)
{
// Calculate the color percentage based on the current pixel.
nColorPercent = i / nWidth;
// Calculate the radians of the angle to use for rotating color values.
nRadians = (-360 * nColorPercent) * (Math.PI / 180);
// Calculate the RGB channels based on the angle.
nR = Math.cos(nRadians) * 127 + 128 << 16;
nG = Math.cos(nRadians + 2 * Math.PI / 3) * 127 + 128 << 8;
nB = Math.cos(nRadians + 4 * Math.PI / 3) * 127 + 128;
// OR the individual color channels together.
nColor = nR | nG | nB;
}
UPDATED SOLUTION
for anyone interested, below is the solution i wrote to address the above problem. RGB waveforms are not used to create the full color spectrum. also, the code is flexible so you can assign your own size and color variables for the produced sprite. the color variables in this example are red, yellow, green, cyan, blue, magenta, red to produce the complete color spectrum
/*
//SpectrumGradient Object Call
var spectrum:SpectrumGradient = new SpectrumGradient(stage.stageWidth, stage.stageHeight, 0xFF0000, 0xFFFF00, 0x00FF00, 0x00FFFF, 0x0000FF, 0xFF00FF, 0xFF0000);
this.addChild(spectrum);
*/
package
{
import flash.display.BitmapData;
import flash.display.CapsStyle;
import flash.display.GradientType;
import flash.display.LineScaleMode;
import flash.display.Sprite;
import flash.geom.Matrix;
public class SpectrumGradient extends Sprite
{
public function SpectrumGradient(spriteWidth:Number, spriteHeight:Number, ...spriteColors)
{
//Setup spectrum sprite
var spectrum:Sprite = new Sprite();
var spectrumAlphas:Array = new Array();
var spectrumRatios:Array = new Array();
var spectrumPartition:Number = 255 / (spriteColors.length - 1);
for (var pushLoop:int = 0; pushLoop < spriteColors.length; pushLoop++)
{
spectrumAlphas.push(1);
spectrumRatios.push(pushLoop * spectrumPartition);
}
//Create spectrum sprite as evenly distributed linear gradient using supplied spriteColors
var spectrumMatrix:Matrix = new Matrix();
spectrumMatrix.createGradientBox(spriteWidth, spriteHeight);
spectrum.graphics.lineStyle();
spectrum.graphics.beginGradientFill(GradientType.LINEAR, spriteColors, spectrumAlphas, spectrumRatios, spectrumMatrix);
spectrum.graphics.drawRect(0, 0, spriteWidth, 1);
spectrum.graphics.endFill();
//Assign bitmapData to the spectrum sprite
var bitmapData:BitmapData = new BitmapData(spectrum.width, spectrum.height, true, 0);
bitmapData.draw(spectrum);
var pixelColor:Number;
for (var i:int = 0; i < spriteWidth; i++)
{
//Retrieve the color number for each pixel of the spectrum sprite
pixelColor = bitmapData.getPixel(i, 0);
//Create new matrices for the white and black gradient lines
var matrixWhite:Matrix = new Matrix();
matrixWhite.createGradientBox(1, spriteHeight / 2, Math.PI * 0.5, 0, 0);
var matrixBlack = new Matrix();
matrixBlack.createGradientBox(1, spriteHeight / 2, Math.PI * 0.5, 0, spriteHeight / 2);
//Each slice of the sprite is composed of two vertical lines: the first fades from white to the pixelColor, the second fades from pixelColor to black
graphics.lineStyle(1, 0, 1, false, LineScaleMode.NONE, CapsStyle.NONE);
graphics.lineGradientStyle(GradientType.LINEAR, [0xFFFFFF, pixelColor], [100, 100], [0, 255], matrixWhite);
graphics.moveTo(i, 0);
graphics.lineTo(i, spriteHeight / 2);
graphics.lineGradientStyle(GradientType.LINEAR, [pixelColor, 0], [100, 100], [0, 255], matrixBlack);
graphics.moveTo(i, spriteHeight / 2);
graphics.lineTo(i, spriteHeight);
}
}
}
}
you can't have all colors at once. all RGB colors, that's 256 x 256 x 256, so you'd need 4096 x 4096 pixels for showing all of them.
Also, there is no "natural"/sensible way of displaying them all. At least until now, nobody has come up with a 2 dimensional color space that really makes sense. For displaying colors, you'll always have to pick 2. That's why common color choosers either use a hue slider and a lightness/saturation plane or a hue/saturation plane and a lightness slider.
please also note that the first (rectangular) spectrum can be easily drawn with 2 superposed gradients. a horizontal one for the hue, and a vertical (semitransparent) for lightness. its faster and completely smooth (if you zoom you don't see the individual lines).
edit: here's a working example of how this can be achieved with a single gradient, which is preferable for obvious reasons:
package {
import flash.display.*;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Matrix;
public class GradientTest extends Sprite {
public function GradientTest() {
var colors:Array = [0xFF0000, 0xFFFF00, 0x00FF00, 0x00FFFF, 0x0000FF, 0xFF00FF, 0xFF0000];
var part:Number = 0xFF / (colors.length-1);
var ratios:Array = [], alphas:Array = [];
var m:Matrix = new Matrix();
m.createGradientBox(500, 20);
for (var i:int = 0; i < colors.length; i++) {
ratios.push(part * i);
alphas.push(100);
}
this.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, m);
this.graphics.drawRect(0, 0, 500, 20);
//just to get the RGB values under the mouse:
var b:BitmapData = new BitmapData(this.width, this.height, true, 0);
b.draw(this);
stage.addEventListener(MouseEvent.MOUSE_MOVE, function (e:Event):void {
if (hitTestPoint(mouseX, mouseY)) {
var s:String = b.getPixel(mouseX, mouseY).toString(16);
while (s.length < 6) s = "0" + s;
trace("#" + s);
}
});
}
}
}
the approach using waveforms is a bit like a hammer in search of a nail. just because bit operations and trigonometry are great tools, doesn't mean you should prefer them to a solution that is much simpler.