Texturing a terrain causes Windows Phone to crash (without an exception) or Models are not drawn afterwards - xna-4.0

I call this method on LoadContent() - after loading heightMap texture:
private void setEffect(Texture2D heightMap)
{
m_BasicEffect = new BasicEffect(this.GraphicsDevice);
m_BasicEffect.EnableDefaultLighting();
m_BasicEffect.FogEnabled = true;
m_BasicEffect.FogStart = 300f;
m_BasicEffect.FogEnd = 1000f;
m_BasicEffect.FogColor = Color.Black.ToVector3();
m_BasicEffect.TextureEnabled = true;
m_BasicEffect.World = Matrix.Identity;
m_BasicEffect.Texture = heightMap;
}
Now, if I change the "m_BasicEffect.TextureEnabled = true;" to "m_BasicEffect.TextureEnabled = false;" it works, but the texture (of course) doesn't show.
Draw method looks like this:
public override void Draw(Microsoft.Xna.Framework.GameTime i_GameTime)
{
Matrix worldMatrix = Matrix.CreateTranslation(-m_TerrainWidth / 2.0f, 0, m_TerrainHeight / 2.0f) * Matrix.CreateRotationY(m_Angle);
m_BasicEffect.View = MyCamera.View;
m_BasicEffect.Projection = MyCamera.Projection;
m_BasicEffect.World = worldMatrix;
foreach (EffectPass pass in m_BasicEffect.CurrentTechnique.Passes)
{
pass.Apply();
Game.GraphicsDevice.Indices = myIndexBuffer;
Game.GraphicsDevice.SetVertexBuffer(myVertexBuffer);
Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, m_VerticesNormalLength, 0, m_IndicesLength / 3);
}
}
Moreover, if I try to draw Models afterwords, it throws an exception:
"The current vertex declaration does not include all the elements required by the current vertex shader."
The way I try to draw the Models:
public override void Draw(GameTime i_GameTime)
{
Matrix[] transforms = new Matrix[MyModel.Bones.Count];
MyModel.CopyAbsoluteBoneTransformsTo(transforms);
foreach (ModelMesh mesh in MyModel.Meshes)
{
foreach (BasicEffect be in mesh.Effects)
{
be.EnableDefaultLighting();
be.Projection = MyCamera.Projection;
be.View = MyCamera.View;
be.World = GetWorld() * mesh.ParentBone.Transform;
}
mesh.Draw();
}
}
What do you think about it?
Thanks in advance.

Related

Autonomous Agents steering an object

I am attempting to apply steering forces based on Nature of Code's first Autonomous Agents example, but I'm missing something. I did get desired/steer vectors to update, but then the object simply moves to the lower right and checkEdges() stops working. I've put various x,y values in the target variable, but nothing seems to work right. I've tried calling seek() in sketch.js, but then I thought maybe to put it in update(). What am I doing wrong?
My goal is to get it to move to a changing mouseX,mouseY target, like in Dan's example, but I've hard coded x,y values just to debug.
Here is my Person class:
class Person {
constructor(){
this.location = createVector(random(width),random(height));
this.velocity = createVector(random(-1,1), random(-1,1));
this.acceleration = createVector(-0.01,0.001);
this.maxspeed = 2;
this.maxforce = 0.01;
this.desired = createVector();
this.steer = createVector();
this.target = createVector(200,200);
}
update() {
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxspeed);
this.location.add(this.velocity);
this.acceleration.mult(0);
this.seek();
}
display() {
fill(0);
stroke(255);
strokeWeight(2);
ellipse(this.location.x, this.location.y, 10, 10);
text(this.target,this.location.x, this.location.y);
}
applyForce(force) {
this.acceleration.add(force);
}
seek() {
this.desired = this.desired.sub(this.target,this.location);
this.desired.normalize();
this.desired.mult(this.maxspeed);
this.steer = this.steer.sub(this.desired,this.velocity);
this.applyForce(this.steer);
this.steer.limit(this.maxforce);
}
checkEdges() {
if ((this.location.x > width) || (this.location.x < 0)) {
this.velocity.x = this.velocity.x * -1;
}
if ((this.location.y > width) || (this.location.y < 0)) {
this.velocity.y = this.velocity.y * -1;
}
}
}
Here is sketch.js:
let people = [];
function setup() {
createCanvas(400, 400);
let p1 = new Person();
people.push(p1);
}
function draw() {
background(0);
people.forEach((p) => {
p.update();
p.checkEdges();
p.display();
});
}
Live code: https://editor.p5js.org/OMTI/sketches/sgGe8CaZH
In your seek() function, use p5.Vector.sub() instead of this.desired.sub() and this.steer.sub().

How to remove a selected part of an image in Flutter?

I want to send an image to backend, but before sending user can select some part of it. And I need to remove unwanted part. Below I attached some screenshots.
After three days of working on it I finally found out, how to work around.
So if it's not an eraser I'm just drawing as always but if an eraser I'm replacing Paint with shader wich is my image from background.
if (!_eraser) {
paint = new Paint()
..style = PaintingStyle.fill
..strokeCap = StrokeCap.round
..color = selectedColor
..strokeWidth = strokeWidth;
} else {
final Float64List deviceTransform = new Float64List(16)
..[0] = devicePixelRatio
..[5] = devicePixelRatio
..[10] = 1.0
..[15] = 2.0;
paint = new Paint()
..style = PaintingStyle.fill
..strokeCap = StrokeCap.round
..shader = ImageShader(image, TileMode.repeated, TileMode.repeated, deviceTransform)
..strokeWidth = strokeWidth;
Painting Class
#override
void paint(Canvas canvas, Size size) {
canvas.drawImage(image, Offset.zero, new Paint());
for (int i = 0; i < pointsList.length - 1; i++) {
if (pointsList[i] != null && pointsList[i + 1] != null) {
canvas.drawLine(pointsList[i].points, pointsList[i + 1].points, pointsList[i].paint);
} else if (pointsList[i] != null && pointsList[i + 1] == null) {
offsetPoints.clear();
offsetPoints.add(pointsList[i].points);
offsetPoints.add(Offset(pointsList[i].points.dx + 0.1, pointsList[i].points.dy + 0.1));
canvas.drawCircle(pointsList[i].points, pointsList[i].paint.strokeWidth / 2, pointsList[i].paint);
}
}
}
If you want to crop the image basic on some user input that you already have, you could use the copyCrop function from the image library.

dynamically change an image via c# script in Xamarin forms

I have a cross platform app which I need to show a set of images when the user clic in a button, so, I put these image files named as "img000.png" to "img029.png" in a folder in the PCL solution and make al these images as "EmbeddedResource", after,I fill a List with all these images and its work fine at now, i.e. the image is shown like I want, but when I click in the button to show the next image in the list the image don't go to the next.
I have this:
//...
public class ImageSetPage : BasePage
// BasePage encapsule a ContentPage...
{
private string directory = "MyApp.Assets.";
private int idx = 0;
protected StackLayout _mainLayout;
protected StackLayout _buttonStack;
protected Image _btnPrevI;
protected Label _displayName;
protected Image _btnNestI;
protected Image _image;
protected List<Image> _Images;
public ImageSetPage()
{
this._Images = getImages();
var prevI_Tap = new TapGestureRecognizer();
prevI_Tap.Tapped += (s, e) =>
{
onClick("pvi");
};
var nextI_Tap = new TapGestureRecognizer();
nextI_Tap.Tapped += (s, e) =>
{
onClick("nti");
};
/// begin layout
base.Title = "set of Images";
this._mainLayout = new StackLayout()
{
Orientation = StackOrientation.Vertical,
BackgroundColor = Color.Black,
Padding = new Thickness(0, 10, 0, 0)
};
this._btnPrevI = new Image()
{
Aspect = Aspect.AspectFill,
Source = ImageSource.FromResource(directory+"prevbtn.png")
};
_btnPrevI.GestureRecognizers.Add(prevI_Tap);
this._displayName = new Label()
{
Style = Device.Styles.SubtitleStyle,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
TextColor = Color.White,
};
this._btnNextI = new Image()
{
Aspect = Aspect.AspectFill,
Source = ImageSource.FromResource(directory + "nextbtn.png")
};
_btnNextI.GestureRecognizers.Add(nextI_Tap);
this._buttonStack.Children.Add(_btnPrevI);
this._buttonStack.Children.Add(_displayName);
this._buttonStack.Children.Add(_btnNextI);
this._mainLayout.Children.Add(_buttonStack);
FillImage(idx);
this._mainLayout.Children.Add(this._image);
this.Content = this._mainLayout;
}
private void FillImage(int i)
{
this._displayName.Text = "Image n# " + FillWithZeroes(i);
// [EDIT 1] cemented these lines ...
// this._image = null;
// mi = _images[i];
// this._image = mi;
// [EDIT 2] the new try
string f = directory + "imgs.img0" + FillWithZeroes(i) + ".png";
this._image = new Image() {
VerticalOptions = LayoutOptions.Center,
Soruce = ImageSource.FromResource(f)
};
// In this way the image show and don't change when click
// this Fking* code is a big S_OF_THE_B*
// The Xamarin and the C# is brothers of this FKing* code
}
private void onClick(string v)
{
string vw = v;
if (vw.Equals("pvi")) idx--;
if (vw.Equals("nti")) idx++;
if (idx <= 0) idx = 29;
if (idx >= 29) idx = 0;
FillImage(idx);
vw = "";
}
private string FillWithZeroes(int v)
{
string s = v.ToString();
string r = "";
if (s.Length == 1) { r = "0" + s; } else { r = s; }
return r;
}
// to fill a list of Images with files in a PCL folder
private List<Image> getImages()
{
string directory = "MyApp.Assets.";
List<Image> imgCards = new List<Image>();
int c = 0;
for (c = 0; c < 30;c++) {
string f = directory + "imgs.img0" + FillWithZeroes(c) + ".png";
Image img = new Image();
img.Source = ImageSource.FromResource(f);
imgCards.Add(img);
}
return imgCards;
}
// ...
}
but the image don't change, i.e. change, like I see in debug, but don't show in the Layout when I click in the buttons.
Maybe I'm doing it wrong.
Can someone here help me?
thanks in advance

Implementing circle progress bar in libGDX

I want to create a circle progress bar, that will look like this using libgdx library. For now on I've created simple horizontal progressbar using different Images as layers overlapping themselfs and one of them resizing to simulate progress. I found this example, how to draw circle progress bar, but I don't understand how to use this implementation and how can I handle it. The textureRegion in constructor is the progress indicator? and I could not find the method responsible to set the actual progress.
EDIT: I've made my solution basic on this implementation. I put 3 layers which overlapping themselfs and whenever the middle layer swipe's the progress is showed. But Ive have a problem: whenever I try to resize my ProgressCircle instance it move down below the background layer.
public class ProgressCircle extends Image {
public enum IntersectAt {
NONE, TOP, BOTTOM, LEFT, RIGHT;
}
TextureRegion texture;
PolygonSpriteBatch polyBatch;
Vector2 center;
Vector2 centerTop;
Vector2 leftTop;
Vector2 leftBottom;
Vector2 rightBottom;
Vector2 rightTop;
Vector2 progressPoint;
float[] fv;
IntersectAt intersectAt;
private float PROGRESS_WIDTH=0f;
private float PROGRESS_HEIGHT=0f;
private float posX,posY;
public ProgressCircle(TextureRegion region, PolygonSpriteBatch polyBatch,float width,float height,float posX,float posY) {
super(region);
PROGRESS_WIDTH=width;
PROGRESS_HEIGHT=height;
this.posX=posX;
this.posY=posY;
this.texture = region;
this.polyBatch = polyBatch;
center = new Vector2(this.getWidth() / 2, this.getHeight() / 2);
centerTop = new Vector2(this.getWidth() / 2, this.getHeight());
leftTop = new Vector2(0, this.getHeight());
leftBottom = new Vector2(0, 0);
rightBottom = new Vector2(this.getWidth(), 0);
rightTop = new Vector2(this.getWidth(), this.getHeight());
progressPoint = new Vector2(this.getWidth() / 2, this.getHeight() / 2);
setPercentage(0);
}
private Vector2 IntersectPoint(Vector2 line) {
Vector2 v = new Vector2();
boolean isIntersect;
//check top
isIntersect = Intersector.intersectSegments(leftTop, rightTop, center, line, v);
//check bottom
if (isIntersect) {
intersectAt = IntersectAt.TOP;
return v;
} else
isIntersect = Intersector.intersectSegments(leftBottom, rightBottom, center, line, v);
//check left
if (isIntersect) {
intersectAt = IntersectAt.BOTTOM;
return v;
} else isIntersect = Intersector.intersectSegments(leftTop, leftBottom, center, line, v);
//check bottom
if (isIntersect) {
intersectAt = IntersectAt.LEFT;
return v;
} else isIntersect = Intersector.intersectSegments(rightTop, rightBottom, center, line, v);
if (isIntersect) {
intersectAt = IntersectAt.RIGHT;
return v;
} else {
intersectAt = IntersectAt.NONE;
return null;
}
}
public void setPercentage(float percent) {
//100 % = 360 degree
float angle = convertToRadians(90);
angle -= convertToRadians(percent * 360 / 100);
float len = this.getWidth() > this.getHeight() ? this.getWidth() : this.getHeight();
float dy = (float) (Math.sin(angle) * len);
float dx = (float) (Math.cos(angle) * len);
Vector2 line = new Vector2(center.x + dx, center.y + dy);
Vector2 v = IntersectPoint(line);
if (intersectAt == IntersectAt.TOP) {
if (v.x >= this.getWidth() / 2) {
fv = new float[]{
center.x,
center.y,
centerTop.x,
centerTop.y,
leftTop.x,
leftTop.y,
leftBottom.x,
leftBottom.y,
rightBottom.x,
rightBottom.y,
rightTop.x,
rightTop.y,
v.x,
v.y
};
} else {
fv = new float[]{
center.x,
center.y,
centerTop.x,
centerTop.y,
v.x,
v.y
};
}
} else if (intersectAt == IntersectAt.BOTTOM) {
fv = new float[]{
center.x,
center.y,
centerTop.x,
centerTop.y,
leftTop.x,
leftTop.y,
leftBottom.x,
leftBottom.y,
v.x,
v.y
};
} else if (intersectAt == IntersectAt.LEFT) {
fv = new float[]{
center.x,
center.y,
centerTop.x,
centerTop.y,
leftTop.x,
leftTop.y,
v.x,
v.y
};
} else if (intersectAt == IntersectAt.RIGHT) {
fv = new float[]{
center.x,
center.y,
centerTop.x,
centerTop.y,
leftTop.x,
leftTop.y,
leftBottom.x,
leftBottom.y,
rightBottom.x,
rightBottom.y,
v.x,
v.y
};
} else // if (intersectAt == IntersectAt.NONE)
{
fv = null;
}
}
#Override
public void draw(Batch batch, float parentAlpha) {
if (fv == null) return;
batch.end();
drawMe();
batch.begin();
}
public void drawMe() {
EarClippingTriangulator e = new EarClippingTriangulator();
ShortArray sv = e.computeTriangles(fv);
PolygonRegion polyReg = new PolygonRegion(texture, fv, sv.toArray());
PolygonSprite poly = new PolygonSprite(polyReg);
poly.setSize(PROGRESS_WIDTH,PROGRESS_HEIGHT);
poly.setPosition(posX,posY);
poly.setOrigin(poly.getOriginX(), poly.getOriginY());
poly.setRotation(this.getRotation());
poly.setColor(Color.GREEN);
polyBatch.begin();
poly.draw(polyBatch);
polyBatch.end();
}
float convertToDegrees(float angleInRadians) {
float angleInDegrees = angleInRadians * 57.2957795f;
return angleInDegrees;
}
float convertToRadians(float angleInDegrees) {
float angleInRadians = angleInDegrees * 0.0174532925f;
return angleInRadians;
}
}
and my init function:
ProgressCircle sprite;
private void initCircleProgress() {
Group group = new Group();
Image downBackground = new Image(atlas.findRegion("progressBackground"));
downBackground.setColor(Color.BLUE);
downBackground.setSize(USER_SCREEN_SIZE_WIDTH/5,USER_SCREEN_SIZE_WIDTH/5);
downBackground.setPosition(10,USER_SCREEN_SIZE_HEIGHT-(2*downBackground.getHeight()+20));
sprite = new ProgressCircle(atlas.findRegion("progressBackground"), pbatch,
downBackground.getWidth(),downBackground.getHeight(),downBackground.getX(),downBackground.getY());
sprite.setSize(downBackground.getWidth(),downBackground.getHeight());
sprite.setSize(downBackground.getX(),downBackground.getY());
Image label = new Image(atlas.findRegion("progressBackground"));
label.setSize(downBackground.getWidth()*0.8f,downBackground.getHeight()*0.8f);
label.setPosition(downBackground.getX()+(downBackground.getWidth()-label.getWidth())/2,
downBackground.getY()+(downBackground.getHeight()-label.getHeight())/2);
label.setColor(Color.WHITE);
group.addActor(downBackground);
group.addActor(sprite);
group.addActor(label);
group.setPosition(10,GAME_SIZE_HEIGHT-(group.getHeight()+20));
stage.addActor(group);
}
You need a circular gradient to mask out the desired parts.
Incrementing the masking values over time will result in a circular motion.
As you can see in the link to masking there are several methods to achieve this. A stencil buffer would be a good choice but can result in jaggy edges. Writing your own shader would be perfect but kinda hard if you never wrote a shader. You can also try to parse both pix maps and decide what pixels to draw while looping through both pixmaps. If the masking image and your source have equal texture space you can do this in one loop so it would not be that much slower then a shader and whatever works for you is a good solution, you can always optimize later.

Flash AS2 - grouping enemies

So I have a Flash ActionScript 2 code, which creates a preset amount of enemies, gives enemies stats, and makes them move around randomly. Code:
//Settings
var mapWidth:Number = 550;
var mapHeight:Number = 400;
var enemiesArray:Array = new Array();
var totalEnemies:Number;
var eClip:MovieClip;
//Math functions
function getdistance(x, y, x1, y1)
{
run = x1-x;
rise = y1-y;
return (hyp(run, rise));
}
function hyp(a, b)
{
return (Math.sqrt(a*a+b*b));
}
function resetDirection(mc:MovieClip)
{
mc.roamTime = random(50);
mc.t = mc.roamTime;
mc.roamDistance = random(60)+25;
mc.randomRoamDistanceX = (Math.random()*mc.roamDistance)+mc.xx-(mc.roamDistance/2);
mc.randomRoamDistanceY = (Math.random()*mc.roamDistance)+mc.yy-(mc.roamDistance/2);
mc.newRoamDistance = getdistance(mc._x, mc._y, mc.randomRoamDistanceX, mc.randomRoamDistanceY);
mc.norm = mc.roamSpeed/mc.newRoamDistance;
mc.finalRoamDistanceX = (mc.randomRoamDistanceX-mc.xx)*mc.norm;
mc.finalRoamDistanceY = (mc.randomRoamDistanceY-mc.yy)*mc.norm;
}
//function to move enemies
function moveIt(mc:MovieClip)
{
//reduce roamTime;
mc.t--;
//move enemy to new position
if (getdistance(mc._x, mc._y, mc.randomRoamDistanceX, mc.randomRoamDistanceY)>mc.roamSpeed) {
mc._x += mc.finalRoamDistanceX;
mc._y += mc.finalRoamDistanceY;
}
//rotate enemy
XXXdiff = mc.xx-mc.randomRoamDistanceX;
YYYdiff = -(mc.yy-mc.randomRoamDistanceY);
rrradAngle = Math.atan(YYYdiff/XXXdiff);
if (XXXdiff<0) {
cccorrFactor = 270;
} else {
cccorrFactor = 90;
}
//
mc.ship_mc._rotation = -(rrradAngle*360/(2*Math.PI)+cccorrFactor);
//check if time to reset, based on roamTime
if (mc.t<=0) {
resetDirection(mc);
}
}
//
// Generate Enemies
//
// set and save enemy stats
//
//
// createEnemies(number of enemies you want, movieclip where you want to create the enemies);
//
function createEnemies(amount:Number, targetLocation:MovieClip) {
trace("createEnemies: "+amount);
for (var i = 0; i<amount; i++) {
randomXpos = Math.round(Math.random()*mapWidth);
randomYpos = Math.round(Math.random()*mapHeight);
//add new enemy to map
var newEnemy:MovieClip = targetLocation.attachMovie("enemy1", "enemy1_"+i, targetLocation.getNextHighestDepth());
enemiesArray.push(newEnemy);
//
//set enemy stats
newEnemy.id = i;
newEnemy._x = randomXpos;
newEnemy._y = randomYpos;
//save x and y position
newEnemy.xx = newEnemy._x;
newEnemy.yy = newEnemy._y;
//
newEnemy.roamSpeed = 2
newEnemy.roamTime = random(50);
newEnemy.roamDistance = random(60)+25;
newEnemy.t = 0;
//
newEnemy.myHealth = 10;
newEnemy.myName = "Small Scout";
//
resetDirection(newEnemy);
//target enemy
newEnemy.onPress = function() {
trace("Enemy: "+this.tName+" "+this.id);
target_txt.text = this.myName+": "+this.id+" Health: "+this.myHealth;
};
newEnemy.onEnterFrame = function() {
moveIt(this);
};
}
}
start_btn.onRelease = function() {
if (start_txt.text == "Start") {
//run the create enemies function to start the engine
createEnemies(box_mc.numberOfEnemies.text, map_mc);
//hide start button
start_txt._visible =false;
this._visible = false;
box_mc._visible = false;
}
};
I want program enemies to be grouped (based on fireflies algorithm). My idea is write for loop to define attractiveness, but I don't know how to make my objects move to the most attractiveness. Maybe someone would help me with this problem?
I change this line:
newEnemy.myHealth = 10;
on this
newEnemy.myHealth = Math.round(random(9)+1);
myHealth would be responsible for attractiveness. I try to use code from this site and modificate code to let objects with low attractiveness follow objects with large attractiveness. Also, I want to stop algorith, when they are in the groups.

Resources