Getting an unexpected trace for getpixel32. Can anybody see why? - actionscript-3

When running the following code, "-2" is being traced and I am wrecking my head trying to understand why.
var bmd:BitmapData = new BitmapData(1,1,true,0xFFFFFFFF);
bmd.setPixel32(0,0, 0x32FF6B45);
trace(0x32FF6B45-bmd.getPixel32(0,0));
As far as I can tell, it should trace 0. 0x32FF6B45 is initially assigned to the pixel at coords 0,0. That value should be returned in bmd.getPixel32(0,0) and then, when it's subtracted from 0x32FF6B45, it should result in 0. Why the heck am I getting -2?
EDIT:
I've traced out the values individually and it makes sense that the operation in the trace above results in -2 because tracing out 0x32FF6B45 results in 855599941 and tracing out bmd.getPixel32(0,0) results in 855599943. The question now is why the heck are those values different? Whey doesn't bmd.getPixel32(0,0) also trace out 855599941?

I have the same problem, and I believe it is related to premultiplied alpha, as described here. In my code I was setting a pixel to 0xa08800ff and getting back 0xa08700ff. If you need alphas other than 0xff, then unfortunately it may be necessary to simultaneously store all your pixel values in a separate data structure too.

That is expected.
getPixel
This will return a value: #RRGGBB (rgb / red, green, blue)
getPixel32
This will return a value: #AARRGGBB (argb / alpha, red, green, blue)
Example:
trace('test 0x32FF6B45: '+0x32FF6B45);
var bmd:BitmapData = new BitmapData(1,1,true,0xFFFFFFFF);
trace('setting 0,0 to 0x32FF6B45');
bmd.setPixel32(0,0, 0x32FF6B45);
var color:* = bmd.getPixel32(0,0)
trace('0,0: '+color);
trace(color-bmd.getPixel32(0,0));
Results:
test 0x32FF6B45: 855599941
setting 0,0 to 0x32FF6B45
0,0: 855599943
0
From what I can tell, you're using a color that is out-of-bounds to Flash. I'm not sure of the color range, but I know in previous experiences when taking photoshop elements with many colors, sometimes objects failed to import because the color value was out of bounds.
#Jari is also correct about the transparency.

Related

Cesium: Is it possible to make the trailing path thinner?

I'm using the Cesium library to simulate the satellite motion. This code is used to show the path:
path:{
leadTime:data.data_list[0].period/2,
trailTime:data.data_list[0].period/2,
width:1.5,
material: color
}
Is there a way to make the trailing path thinner?
As an example, the SpaceX video: http://youtu.be/rQEqKZ7CJlk?t=47m40s
Couple of comments here. First, with a width of only 1.5, altering the width is likely not the effect you want. Try using a solid color vs a faded color, such as by changing the alpha value. This should be more similar to what you're seeing in that video link.
But, currently Cesium does not support separate path materials for lead and trail times. If you really need both lead and trail paths shown with different colors/widths/etc, you have to insert a duplicate entity in your CZML (whose position can just be a reference to the primary entity position), such that one entity can have only a leadtime and the other has only a trailtime, and they use different path materials.
But if you have a satellite in a stable orbit, you there's a different approach you can take, because the thing keeps circling around the same path. You can use the StripeMaterial to make the orbit line fade from one side to the other.
Here's a live demo that loads simple.czml and replaces the Molniya's yellow orbit with a faded line. The solid part is the most recent trail of the satellite, and the faded part is much further back but serves to show where the satellite is headed next.
Cesium.Camera.DEFAULT_VIEW_FACTOR = 5.5;
var viewer = new Cesium.Viewer('cesiumContainer', {
shouldAnimate : true
});
Cesium.CzmlDataSource.load('../../../../Apps/SampleData/simple.czml').then(function(dataSource) {
viewer.dataSources.add(dataSource);
viewer.camera.flyHome(0);
viewer.clock.multiplier = 1800;
var entity = dataSource.entities.getById('Satellite/Molniya_1-92');
var fadedLine = new Cesium.StripeMaterialProperty({
// The newest part of the line is bright yellow.
evenColor: Cesium.Color.YELLOW,
// The oldest part of the line is yellow with a low alpha value.
oddColor: Cesium.Color.YELLOW.withAlpha(0.2),
repeat: 1,
offset: 0.25,
orientation: Cesium.StripeOrientation.VERTICAL
});
entity.path.material = fadedLine;
entity.path.leadTime = new Cesium.ConstantProperty(0);
entity.path.trailTime = new Cesium.ConstantProperty(3600 * 12);
});
Here you can play with the color, of course, but I would recommend keeping the same base color for even and odd. The withAlpha value of 0.2 on the oddColor here controls how faded the line gets, range is 0 to 1. The offsetvalue here can also be tweaked, to control the placement of the fade range. leadTime should be zero, and trailTime should be the orbit's period.

libgdx/box2d lights: change blur of lights

I was wondering whether it is possible to change the rate at which a lights intensity decareases over distance.
something like this:
So I finally figuered it out.
You have to write a custom shader that is essetially the same as the default one, but change the line that takes care of the interpolation:
"v_color = s*quad_colors;\n"
for example:
"v_color = s*2*quad_colors;\n"
halves the dropoff rate, while:
"v_color = (s*0)+quad_colors;\n"
gets rid of any blur (leaving out the "s" completely out won't work)
I have the "v_color = squad_colors;\n" its in the vertex shader of the light source. See https://github.com/libgdx/box2dlights/blob/master/src/shaders/LightShader.java. However the above didn't work for me, the number you use must be a float. E.g."v_color = (s0.0)+quad_colors;\n"

Best and most performant implementation of dynamic shapes in cesium

I am currently working an application that is using a Cesium Viewer. I need to be able to display a collection of shapes that will be updated dynamically. I am having trouble understanding the best way to do this.
I currently am using Entities and using CallbackProperties to allow for the updating of shapes.
You can through this into a sandcastle to get an idea of how I am doing this. There is a polygon object that is being used as the basis for the cesiumCallback, and it is getting edited by another piece of code. (simulated with the setTimeout)
var viewer = new Cesium.Viewer('cesiumContainer', {});
var polygon = {};
polygon.coordinates = [
{longitude: 0, latitude: 0, altitude: 0},
{longitude: 10, latitude: 10, altitude: 0},
{longitude: 10, latitude: 0, altitude: 0}
];
// converts generic style options to cesium one (aka color -> material)
var polOpts = {};
// function for getting location
polOpts.hierarchy = new Cesium.CallbackProperty(function() {
var hierarchy = [];
for (var i = 0; i < polygon.coordinates.length; i++) {
var coordinate = polygon.coordinates[i];
hierarchy.push(Cesium.Cartesian3.fromDegrees(coordinate.longitude, coordinate.latitude, coordinate.altitude));
}
return hierarchy;
}, false);
viewer.entities.add({polygon: polOpts});
setInterval(function(polygon){
polygon.coordinates[0].longitude--;
}.bind(this, polygon), 1000);
The polygon being passed in is a class that generically describes a polygon, so it has an array of coordinates and style options, as well as a render method that calls this method renderPolygon passing in itself.
This method of rendering shapes works for everything I need it to, but it is not very performant. There are two cases for shapes updating, one type of shape will be updated over a long period of time, as a slow rate like once every few seconds. The other is shapes that will will get updated many times, like thousands, in a few seconds, then not change again for a long time, if ever.
I had two ideas for how to fix this.
Idea 1:
Have two methods, a renderDynamicPolygon and a renderStaticPolygon.
The renderDynamicPolygon method would do the above functionality, using the cesiumCallbackProperties. This would be used for shapes that are getting updated many times during the short time they are being updated.
The renderStaticPolygon method would replace the entities properties that are using callbackProperties with constant values, once the updating is done.
This creates a lot of other work to make sure shapes are in the right state, and doesn't help the shapes that are being updated slowly over a long period of time.
Idea 2:
Similarly to how the primitives work, I tried removing the old entity and adding it again with its updated properties each time its need to be updated, but this resulted in flickering, and unlike primitives, i could not find a async property for entities.
I also tried using primitives. It worked great for polylines, I would simply remove the old one and add a new one with the updated properties. I was also using the async = false to ensure there was no flickering. This issue I ran into here was not all shapes can be created using primitives. (Is this true?)
The other thing I tried was using the geometry instance using the geometry and appearance. After going through the tutorial on the cesium website I was able to render a few shapes, and could update the appearance, but found it close to impossible to figure out how to update the shapes correctly, and also have a very hard time getting them to look correct. Shapes need to have the right shape, a fill color and opacity and a stroke color, opacity and weight. I tried to use the polygonOutlineGeometry, but had not luck.
What would be the best way to implement this? Are one of these options headed the right way or is there some other method of doing this I have not uncovered yet?
[Edit] I added an answer of where I have gotten, but still not complete and looking for answers.
I have came up with a pretty good solution to this, but it still has one small issue.
I made too ways of showing entities. I am calling one render and one paint. Render uses the the Cesium.CallbackProperty with the isConstant property true, and paint with the isConstantProperty false.
Then I created a function to change the an entity from render to paint and vice vera. It goes through the entities callback properties an uses the setCallback property to overwrite the property with a the correct function and isConstant value.
Example:
I create a ellipse based on a circle object I have defined.
// isConst is True if it is being "painted" and false if it is being "rendered"
ellipse: lenz.util.extend(this._getStyleOptions(circle), {
semiMinorAxis: new Cesium.CallbackProperty(
this._getRadius.bind(this, circle),
isConst
),
semiMajorAxis: new Cesium.CallbackProperty(
this._getRadius.bind(this, circle),
isConst
),
})
So when the shape is being updated (while the user is drawing a shape) the shape is rendered with the isConstant being false.
Then when the drawing is complete it is converted to the painted version using some code like this:
existingEntity.ellipse.semiMinorAxis.setCallback(
this._getRadius.bind(this, circle),
isConst
);
existingEntity.ellipse.semiMajorAxis.setCallback(
this._getRadius.bind(this, circle, 1),
isConst
);
This works great performance wise. I am able to draw hundreds of shapes without the frame dropping much at all. I have attached a screen shot of the cesium map with 612 entities before and after my changes, the frame rate is in the upper right using the chrome render tool.
Before: Locked up at fps 0.9
Note: I redacted the rest of the ui, witch makes the globe look cut off, sorry
And after the changes: The fps remains at 59.9, almost perfect!
Whenever the entity is 'converted' from using constant to not constant callback properties, it and all other entities of the same type flash off then on again. I cannot find a better way to do this conversion. I feel as thought there must still be some thing I am missing.
You could try using a PositionPropertyArray as the polygon's hierarchy with SampledPositionProperty for any dynamic positions and ConstantPositionProperty for any static positions. I'm not sure if it would perform any better than your solution, but it might be worth testing. Here is an example of how it might work that you can paste into the Cesium Sandcastle:
var viewer = new Cesium.Viewer('cesiumContainer', {});
// required if you want no interpolation of position between times
var noInterpolation = {
type: 'No Interpolation',
getRequiredDataPoints: function (degree) {
return 2;
},
interpolateOrderZero: function (x, xTable, yTable, yStride, result) {
if (!Cesium.defined(result)) {
result = new Array(yStride);
}
for (var i = 0; i < yStride; i++) {
result[i] = yTable[i];
}
return result;
}
};
var start = viewer.clock.currentTime;
// set up the sampled position property
var sampledPositionProperty = new Cesium.SampledPositionProperty();
sampledPositionProperty.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD;
sampledPositionProperty.addSample(start, new Cesium.Cartesian3.fromDegrees(0, 0)); // initial position
sampledPositionProperty.setInterpolationOptions({
interpolationAlgorithm: noInterpolation
});
// set up the sampled position property array
var positions = [
sampledPositionProperty,
new Cesium.ConstantPositionProperty(new Cesium.Cartesian3.fromDegrees(10, 10)),
new Cesium.ConstantPositionProperty(new Cesium.Cartesian3.fromDegrees(10, 0))
];
// add the polygon to Cesium viewer
var polygonEntity = new Cesium.Entity({
polygon: {
hierarchy: new Cesium.PositionPropertyArray(positions)
}
});
viewer.zoomTo(viewer.entities.add(polygonEntity));
// add a sample every second
var counter = 1;
setInterval(function(positionArray) {
var time = new Cesium.JulianDate.addSeconds(start, counter, new Cesium.JulianDate());
var position = new Cesium.Cartesian3.fromDegrees(-counter, 0);
positionArray[0].addSample(time, position);
counter++;
}.bind(this, positions), 1000);
One nice thing about this is you can set the timeline start/end time to a reasonable range and use it to see your polygon at any time within the sample range so you can see the history of your polygons through time (See here for how to change the timeline start/end time). Additionally, you don't need to use timers to set the positions, the time is built in to the SampledPositionProperty (although you can still add samples asynchronously).
However, this also means that the position depends on the current time in the timeline instead of a real-time array value. And you might need to keep track of a time somewhere if you aren't adding all the samples at once.
I've also never done this using ellipses before, but the semiMinorAxis and semiMajorAxis are properties, so you might still be able to use a SampledProperty.
Of course, this doesn't really matter if there are still performance issues. Hopefully it will improve as you don't need to recreate the array from scratch each callback and, depending on how you're getting the data to update the polygons, you might be able to add multiple samples at once. This is just speculation, but it's something to consider.
EDIT
Cesium can handle quite a bit of samples added to a sampled position, for example in the above code if you add a million samples to the position it takes a few seconds to load them all, but renders the polygon at any time without any performance issues. To test this, instead of adding samples using a timer, just add them all directly to the property.
for (var i = 0; i < 1000000; i++) {
var time = new Cesium.JulianDate.addSeconds(start, i, new Cesium.JulianDate());
var position = new Cesium.Cartesian3.fromDegrees(-(i % 2), 0);
positions[0].addSample(time, position);
}
However, if you run into memory problems currently there is no way to remove samples from a position property without accessing private variables. A work around would be to periodically create a new array containing new position properties and use the previous position property array's setValue() method to clear previous values or perhaps to use a TimeIntervalCollectionProperty as in this answer and remove time intervals with the removeInterval method.

How do I HitTest two rotating objects properly? (A way to avoid bounding boxes)

I took an intro level flash course in college this semester and our final task was to make a mini-flash game.
I had to make a pipe-dream type game where there are a number of levels, and in each level you have to align the pipes so that the water flows and then you can pass to the next level.
I successfully made the first level, but upon making the second level,
where I placed a lot of curved pipes (by curved pipes I mean the attached image: ![Curved Pipe]: (http://imgur.com/mwpXAMn) )
I discovered that the method I use to decide when a level is complete is not working properly.
I was using HitTestObject, basically, I was testing whether 2 objects, Pipe_1, and Pipe_2, were intersecting. If all pipes intersected in the correct way, then procession to the next level is granted.
The problem with this I discovered is that flash has bounding boxes for movie clips you make, and that HitestObject uses bounding boxes to test for hits. Therefore, when you rotate a leftpipe so that it does not touch a straight pipe on screen, the bounding boxes still touch and it returns "collision" when in fact it is not actually touching on screen.
I looked up and found that you can use HitTestPoint but I can't figure out how to somehow make dynamic variables (that change upon rotation of object) that store one or two specific points on the leftpipe, say the two ends of it.
Once If I figure out how to get these values into a variable correctly, then I can figure out how to do HitTestpoint.
Also, I know of the LocaltoGlobal function but no matter what I try it keeps coming up with:
"Scene 1, Layer 'Layer 1', Frame 1, Line 30 1118: Implicit coercion of a value with static type Object to a possibly unrelated type flash.geom:Point."
meaning I don't know the correct code to store an x and a y coordinate as dynamic variables.
edit: ok since a person asked, I hunted this piece of code off the web and this is the one I was trying to play around with but to no avail:
How to use HitTest for 2 rectangles, r1 is rectangle 1 r2 is rectangle 2.
var r1width:Number = 135.0; //width of retangle 1 whith rotation 0
var r2width:Number = 93.0; //width of retangle 2 whith rotation 0
var p1:Object = {x:(r1width/2), y:(r1width/2)};
var p2:Object = {x:(-r1width/2), y:(r1width/2)};
var p3:Object = {x:(-r1width/2), y:(-r1width/2)};
var p4:Object = {x:(r1width/2), y:(-r1width/2)};
r1.localToGlobal(p1);
r1.localToGlobal(p2);
r1.localToGlobal(p3);
r1.localToGlobal(p4);
var p5:Object = {x:(r2width/2), y:(r2width/2)};
var p6:Object = {x:(-r2width/2), y:(r2width/2)};
var p7:Object = {x:(-r2width/2), y:(-r2width/2)};
var p8:Object = {x:(r2width/2), y:(-r2width/2)};
r2.localToGlobal(p5);
r2.localToGlobal(p6);
r2.localToGlobal(p7);
r2.localToGlobal(p8);
if((r2.hitTest(p1.x, p1.y, true))||(r2.hitTest(p2.x, p2.y, true))||(r2.hitTest(p3.x,
p3.y, true))||(r2.hitTest(p4.x, p4.y, true)))
{
trace('collision');
}
if((r1.hitTest(p5.x, p5.y, true))||(r1.hitTest(p6.x, p6.y, true))||(r1.hitTest(p7.x,
p7.y, true))||(r1.hitTest(p8.x, p8.y, true)))
{
trace('collision');
}
I did not write this code and it does not work. I'm not sure what "Object" is because I've never used it before, I'm assuming in this case it's sort of acting like a coordinate pair.
Also, this code is to hittest 2 rectangles, whereas I'm using an L-shaped pipe, so the x/y calculation would be quite different I imagine.
This code above gives the same error that I posted before:
Implicit coercion of a value with static type Object to a possibly unrelated type flash.geom:Point.
and it gives it first on line r1.localToGlobal(p1);
Instead of using Object, you need to use Point like so:
var p1:Point = new Point(r1width/2, r1width/2);

AS3 BitmapData CopyPixels with alpha

I am trying to copy the pixels of a bitmap into BitmapData at a transparency of lets say .5 but i can't seem to find any reference to this anywhere on google or here!
i have my standard copy pixel code
_bitmapData.copyPixels(_bitmaps.vault[BitmapNames.BITMAPNAME], SCREENRECT, _drawPoint, null, null, true);
I can see that the first null value i pass is a BitmapData labelled alphaBitmapData:BitmapData so i'm assuming it has something to do with that, but i cant work it out!
Any help would be appreciated, cheers!
Following this link you will find some explanation about the variables.
In short, when you set the last parameter (mergeAlpha:Boolean) to true, the function will take the 4th parameter (alphaBitmap:BitmapData) into account when copying the pixels, effectively using the alpha of the alphaBitmap to merge the copied pixels. So you should pass the same bitmap you use for the first parameter to the 4th parameter, set the 5th parameter (alphaPoint:Point) accordingly and set the last parameter to true.
I have accepted Will Kru's answer as the answer (though only theory based) below is the code used to put the method behind the madness!!
var alphaBitmap:BitmapData = new BitmapData(width, height, true, toARGB(0x000000, (.5 * 255)));
_bitmapData.copyPixels(_bitmaps.vault[BitmapNames.BITMAP], _drawRect, _drawPoint, alphaBitmap, null, true);
toARGB function found here alpha + RGB -> ARGB?