I am trying to create a little drawing tool with processing. The final drawing should be exportable as a .svg file – so i thought this to be pretty easy… but actually it isnt…
I put the background function into setup – to be able to draw – the safed svg file unfortunately only contains a single frame – and not the whole drawing. :-(
What am I missing – how could I achieve that! I would be thankful for any kind of help!
This is my code so far:
import processing.svg.*;
boolean record;
void setup () {
size(1080, 1080);
background(255);
}
void draw() {
if (record) {
beginRecord(SVG, "frame-####.svg");
}
fill(255);
strokeWeight(1);
ellipse(mouseX, mouseY, 100, 100);
if (record) {
endRecord();
record = false;
}
}
void mousePressed() {
record = true;
}
Tried different things in organizing the code lines in different orders – but could not manage it…
Thank you!
That's because you're creating an image every time you beginRecord and endRecord. If you want to save the image as you see it, you can use save(fileName.png) instead. Here's a code snippet to demonstrate:
void setup() {
size(800, 600);
background(255);
fill(255);
strokeWeight(1);
}
void draw() {
ellipse(mouseX, mouseY, 100, 100);
}
void mousePressed() {
save("myImage.png");
}
If, on the other hand, you really want to use beginRecord, know that it'll save everything you draw between beginRecord and endRecord. You could programatically create an image file this way, as an example, but you cannot just add snapshots to an existing image (which is why you only see "one frame" with your current code). Every time you begin recording, you create a new image. I'm not especially familiar with this method, but one obvious way to do things would be to "save" whatever the user is doing and reproduce those instructions to save them. Here's an example which does this (it saves when you right-click, and I also took the liberty of drawing only when the left mouse button is down):
import processing.svg.*;
boolean record;
ArrayList<PVector> positionsList;
void setup() {
size(800, 600);
positionsList = new ArrayList<PVector>();
}
void draw() {
background(255);
fill(255);
strokeWeight(1);
for (PVector p : positionsList) {
ellipse(p.x, p.y, 100, 100);
}
ellipse(mouseX, mouseY, 100, 100);
if (record) {
positionsList.add(new PVector(mouseX, mouseY));
}
}
void mousePressed() {
record = mouseButton == LEFT;
if (mouseButton == RIGHT) {
beginRecord(SVG, "frame.svg");
fill(255);
strokeWeight(1);
for (PVector p : positionsList) {
ellipse(p.x, p.y, 100, 100);
}
endRecord();
}
}
void mouseReleased() {
record = false;
}
While drawing:
The file (as a png here but it was saved as a svg on my computer):
Hope it helps. Have fun!
import processing.pdf.*;
PShape shape;
void setup () {
size(1080, 1080);
beginRecord(PDF, "drawing.pdf");
shape = loadShape("shape.svg");
shapeMode(CENTER);
background(0,255,0);
}
void draw() {
shape.disableStyle();
fill(255);
strokeWeight(10);
shape(shape, mouseX, mouseY, 200, 200);
}
void keyPressed() {
if (key == 's') {
endRecord();
exit();
}
}
Related
I would like to implement some kind of eraser,so in my render method I make the upper layer transparent.
#Override
public void render () {
cam.update();
Gdx.gl.glClearColor(1, 1, 1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (Gdx.input.isTouched()) {
pos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
pixmap.setColor(new Color(1, 1, 1, 0.5f)); //transparency
pixmap.fillCircle((int)pos.x, (int)pos.y, 10);
}
texture3.draw(pixmap, 0, 0);
batch.begin();
batch.draw(texture, 0, 0);
batch.draw(texture3, 0, 0);
batch.end();
}
But I got points when make swipes. It requires to do very slow speed to make lines instead of dots.
So I expect continuous line instead of dots.
Can you advice something please?
Dots instead of line
This is caused because of the frequency at which the input state is updated, the solution here would be to manually calculate the missing points needed to make a line, you could do this with a linear interpolation between each pair of dots, additionally you could calculate how many extra dots are necessary depending on how far is the newest dot from the previous one, in my example I use an arbitrary number of extra dots (20) like so:
public class TestDraw extends Game {
private Pixmap pixmap;
private Texture texture;
private SpriteBatch batch;
private Vector2 lastPos;
#Override
public void create() {
pixmap = new Pixmap(1000, 1000, Pixmap.Format.RGBA8888);
texture = new Texture(pixmap);
batch = new SpriteBatch();
lastPos = new Vector2();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (Gdx.input.isTouched()) {
pixmap.setColor(new Color(1, 1, 1, 0.5f)); //transparency
int newX = Gdx.input.getX();
int newY = Gdx.input.getY();
pixmap.setColor(Color.RED);
pixmap.fillCircle(newX, newY, 10);
// If the distance is too far, fill with extra dots
if (lastPos.dst(newX, newY) > 10) { // Here far is 10, you can adjust as needed
int extraDots = 20; // How many extra dots to draw a line, I use 20, adjust as needed or calculate according to distance (for example lastPos.dst(newX,newY) * 5)
for (int i = 0; i < extraDots; i++) {
float progress = (1f / extraDots) * i;
int dotX = (int) MathUtils.lerp(lastPos.x, newX, progress);
int dotY = (int) MathUtils.lerp(lastPos.y, newY, progress);
pixmap.setColor(Color.BLUE);
pixmap.fillCircle(dotX, dotY, 10);
}
}
// Store last position for next render() call
lastPos.set(newX, newY);
}
texture.draw(pixmap, 0, 0);
batch.begin();
batch.draw(texture, 0, 0);
batch.end();
}
}
Adecuate to your code as needed, I didn't know what was texture3 so I didn't include in my example
Also another option which I don't like too much because of rendering and storage cost is using a Polygon to draw the lines.
I want to have a background texture with 3 rectangles and i want to create animation with them, - texture
But first rectangle cuts in a proper way and two others are cut in a dumb way
Proper way,
Dumb way #1,
Dumb way #2
Here is my code.
public class MainMenu implements Screen{
Texture background_main;
TextureRegion[] background_textures;
Animation background_animation;
SpriteBatch batch;
TextureRegion current_frame;
float stateTime;
BobDestroyer game;
OrthographicCamera camera;
public MainMenu(BobDestroyer game){
this.game = game;
}
#Override
public void show() {
camera = new OrthographicCamera();
camera.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch = new SpriteBatch();
background_main = new Texture(Gdx.files.internal("main_menu_screen/Background.png"));
background_textures = new TextureRegion[3];
for(int i = 0; i<3; i++){
background_textures[i] = new TextureRegion(background_main,0, 0+72*i, 128, 72+72*i);
}
background_animation = new Animation(2f,background_textures);
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
stateTime += Gdx.graphics.getDeltaTime();
current_frame = background_animation.getKeyFrame(stateTime, true);
batch.begin();
batch.draw(current_frame,0, 0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
batch.end();
}
}
If I understand you correctly, are you trying to create 3 TextureRegions of the same width/height? If yes, your issue may be with:
new TextureRegion(background_main,0, 0+72*i, 128, 72+72*i)
I think you'd want:
new TextureRegion(background_main,0, 0+72*i, 128, 72)
As the 128x72 is the width/height (not x/y positions) of your next TextureRegions, and do you not want them all the same height (72) as opposed to varying heights (72+72*i)?
I'm trying to create a program that shows two images at random locations and changes them every second. My problem however is when the image is redrawn I can still see the image in the previous position.
I'm using WTK 2.52 if that's relevant.
public void run()
{
while(true)
{
dVert = rand.nextInt(136);
dHorz = rand.nextInt(120);
rVert = 136 + rand.nextInt(136);
rHorz = 120 + rand.nextInt(120);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Error");
}
repaint();
}
}
public void paint(Graphics g)
{
int width = this.getWidth() / 2;
int height = this.getHeight() / 2;
g.drawImage(imgR, rVert, rHorz, g.TOP | g.LEFT);
g.drawImage(imgD,dVert,dHorz,g.TOP | g.LEFT);
//g.drawString(disp, width, 50, Graphics.TOP | Graphics.HCENTER);
//g.drawString(centerMsg,width, height, Graphics.TOP | Graphics.HCENTER);
System.out.println(width);
System.out.println(height);
}
Complete code
You clear the canvas like this:
g.setColor(0x000000); // Whatever color you wish to clear with
g.setClip(0,0,getWidth(),getHeight());
g.fillRect(0,0,getWidth(),getHeight());
So just insert those lines before drawing the images.
Background information
I have just started learning HLSL and decided to test what I have learned from the Internet by writing a simple 2D XNA 4.0 bullet-hell game.
I have written a pixel shader in order to change the color of bullets.
Here is the idea: the original texture of the bullet is mainly black, white and red. With the help of my pixel shader, bullets can be much more colorful.
But, I'm not sure how and when the shader is applied on spriteBatch in XNA 4.0, and when it ends. This may be the cause of problem.
There were pass.begin() and pass.end() in XNA 3.x, but pass.apply() in XNA 4.0 confuses me.
In addition, it is the first time for me to use renderTarget. It may cause problems.
Symptom
It works, but only if there are bullets of the same color in the bullet list.
If bullets of different colors are rendered, it produces wrong colors.
It seems that the pixel shader is not applied on the bullet texture, but applied on the renderTarget, which contains all the rendered bullets.
For an example:
Here I have some red bullets and blue bullets. The last created bullet is a blue one. It seems that the pixel shader have added blue color on the red ones, making them to be blue-violet.
If I continuously create bullets, the red bullets will appear to be switching between red and blue-violet. (I believe that the blue ones are also switching, but not obvious.)
Code
Since I am new to HLSL, I don't really know what I have to provide.
Here are all the things that I believe or don't know if they are related to the problem.
C# - Enemy bullet (or just Bullet):
protected SpriteBatch spriteBatch;
protected Texture2D texture;
protected Effect colorEffect;
protected Color bulletColor;
... // And some unrelated variables
public EnemyBullet(SpriteBatch spriteBatch, Texture2D texture, Effect colorEffect, BulletType bulletType, (and other data, like velocity)
{
this.spriteBatch = spriteBatch;
this.texture = texture;
this.colorEffect = colorEffect;
if(bulletType == BulletType.ARROW_S)
{
bulletColor = Color.Red; // The bullet will be either red
}
else
{
bulletColor = Color.Blue; // or blue.
}
}
public void Update()
{
... // Update positions and other properties, but not the color.
}
public void Draw()
{
colorEffect.Parameters["DestColor"].SetValue(bulletColor.ToVector4());
int l = colorEffect.CurrentTechnique.Passes.Count();
for (int i = 0; i < l; i++)
{
colorEffect.CurrentTechnique.Passes[i].Apply();
spriteBatch.Draw(texture, Position, sourceRectangle, Color.White, (float)Math.PI - rotation_randian, origin, Scale, SpriteEffects.None, 0.0f);
}
}
C# - Bullet manager:
private Texture2D bulletTexture;
private List<EnemyBullet> enemyBullets;
private const int ENEMY_BULLET_CAPACITY = 10000;
private RenderTarget2D bulletsRenderTarget;
private Effect colorEffect;
...
public EnemyBulletManager()
{
enemyBullets = new List<EnemyBullet>(ENEMY_BULLET_CAPACITY);
}
public void LoadContent(ContentManager content, SpriteBatch spriteBatch)
{
bulletTexture = content.Load<Texture2D>(#"Textures\arrow_red2");
bulletsRenderTarget = new RenderTarget2D(spriteBatch.GraphicsDevice, spriteBatch.GraphicsDevice.PresentationParameters.BackBufferWidth, spriteBatch.GraphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None);
colorEffect = content.Load<Effect>(#"Effects\ColorTransform");
colorEffect.Parameters["ColorMap"].SetValue(bulletTexture);
}
public void Update()
{
int l = enemyBullets.Count();
for (int i = 0; i < l; i++)
{
if (enemyBullets[i].IsAlive)
{
enemyBullets[i].Update();
}
else
{
enemyBullets.RemoveAt(i);
i--;
l--;
}
}
}
// This function is called before Draw()
public void PreDraw()
{
// spriteBatch.Begin() is called outside this class, for reference:
// spriteBatch.Begin(SpriteSortMode.Immediate, null);
spriteBatch.GraphicsDevice.SetRenderTarget(bulletsRenderTarget);
spriteBatch.GraphicsDevice.Clear(Color.Transparent);
int l = enemyBullets.Count();
for (int i = 0; i < l; i++)
{
if (enemyBullets[i].IsAlive)
{
enemyBullets[i].Draw();
}
}
spriteBatch.GraphicsDevice.SetRenderTarget(null);
}
public void Draw()
{
// Before this function is called,
// GraphicsDevice.Clear(Color.Black);
// is called outside.
spriteBatch.Draw(bulletsRenderTarget, Vector2.Zero, Color.White);
// spriteBatch.End();
}
// This function will be responsible for creating new bullets.
public EnemyBullet CreateBullet(EnemyBullet.BulletType bulletType, ...)
{
EnemyBullet eb = new EnemyBullet(spriteBatch, bulletTexture, colorEffect, bulletType, ...);
enemyBullets.Add(eb);
return eb;
}
HLSL - Effects\ColorTransform.fx
float4 DestColor;
texture2D ColorMap;
sampler2D ColorMapSampler = sampler_state
{
Texture = <ColorMap>;
};
struct PixelShaderInput
{
float2 TexCoord : TEXCOORD0;
};
float4 PixelShaderFunction(PixelShaderInput input) : COLOR0
{
float4 srcRGBA = tex2D(ColorMapSampler, input.TexCoord);
float fmax = max(srcRGBA.r, max(srcRGBA.g, srcRGBA.b));
float fmin = min(srcRGBA.r, min(srcRGBA.g, srcRGBA.b));
float delta = fmax - fmin;
float4 originalDestColor = float4(1, 0, 0, 1);
float4 deltaDestColor = originalDestColor - DestColor;
float4 finalRGBA = srcRGBA - (deltaDestColor * delta);
return finalRGBA;
}
technique Technique1
{
pass ColorTransform
{
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}
I would be appreciate if anyone can help solving the problem. (Or optimizing my shader. I really know very little about HLSL.)
In XNA 4 you should pass the effect directly to the SpriteBatch, as explained on Shawn Hargreaves' Blog.
That said, it seems to me like the problem is, that after rendering your bullets to bulletsRenderTarget, you then draw that RenderTarget using the same spriteBatch with the last effect still in action. That would explain why the entire image is painted blue.
A solution would be to use two Begin()/End() passes of SpriteBatch, one with the effect and the other without. Or just don't use a separate RenderTarget to begin with, which seems pointless in this case.
I'm also very much a beginner with pixel shaders so, just my 2c.
I want create a set of buttons with Painter. I wrote next code
class ListButton extends Button{
int id;
ListButton(int id, final Image unsel, final Image sel, final Image pres) {
this.id = id;
getUnselectedStyle().setBgTransparency(255);
getSelectedStyle().setBgTransparency(255);
getPressedStyle().setBgTransparency(255);
getUnselectedStyle().setAlignment(Component.LEFT);
getSelectedStyle().setAlignment(Component.LEFT);
getPressedStyle().setAlignment(Component.LEFT);
getUnselectedStyle().setBgPainter(new Painter(){
public void paint(Graphics graphics, Rectangle rectangle) {
graphics.drawImage(buttonBgImage, 0, 0);
int w= rectangle.getSize().getWidth();
int h= rectangle.getSize().getHeight();
graphics.drawImage(unsel, w- unsel.getWidth()-10, (h- unsel.getHeight())/2+ 3);
}
});
getSelectedStyle().setBgPainter(new Painter(){
public void paint(Graphics graphics, Rectangle rectangle) {
graphics.drawImage(buttonBgImage, 0, 0);
int w= rectangle.getSize().getWidth();
int h= rectangle.getSize().getHeight();
graphics.drawImage(sel, w- sel.getWidth()-10, (h- sel.getHeight())/2+ 3);
}
});
getPressedStyle().setBgPainter(new Painter(){
public void paint(Graphics graphics, Rectangle rectangle) {
graphics.drawImage(buttonBgImage, 0, 0);
int w= rectangle.getSize().getWidth();
int h= rectangle.getSize().getHeight();
graphics.drawImage(pres, w- pres.getWidth()-10, (h- pres.getHeight())/2+ 3);
}
});
}
}
If I insert 2 buttons into the Form only first button is showed well. Second button is without background image (buttonBgImage) and without icon (sel, unsel or pres). I found randomly that second button will be painted if it will be inserted in some Container. What the strange behavior? Sorry for my English.
List has a specific optimization for Renderers/Painters in place that breaks this. We generally recommend people stick with Styles and UIID manipulation and avoid using painters for tasks like these.
E.g. in Codename One/LWUIT we even have specific support in the GUI builder for pinstripe UI in the list renderer.
If you insist on this approach try using list.setMutableRendererBackgrounds(true); to disable this optimization.