Shape not rendering on HTML 5 canvas when using non-hardcoded parameters - html

I'm trying to create a basic HTML 5 game using typescript but I have run into trouble with rendering a circle of a size that is non hard-coded.
My code so far:
Circle.ts
import { IDrawable } from './../Interfaces/IDrawable';
import {BaseShape} from "./BaseShape";
export class Circle extends BaseShape implements IDrawable{
private _radius : number;
public get radius(){
return this._radius;
}
public set radius(val : number){
this._radius = val;
}
constructor(context : CanvasRenderingContext2D,radius : number, x : number, y : number, color : string = "red", lineWidth : number = 2) {
super(context , x, y, color, lineWidth);
}
public draw = () : void => {
this.context.save();
this.context.beginPath();
this.context.strokeStyle = this.color;
this.context.lineWidth = this.lineWidth;
this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
this.context.stroke();
this.context.restore();
}
}
Game.ts
import { Circle } from './Shapes/Circle';
export default class Game{
private circle : Circle;
constructor(private ctx : CanvasRenderingContext2D ){
this.circle = new Circle(ctx, 200, 300, 50, "blue", 5);
}
public Start() : void{
requestAnimationFrame(() => this.Start());
this.ctx.fillStyle = "black";
this.ctx.fillRect(0, 0, 1280, 720);
this.circle.draw();
}
}
The background renders fine but the circle won't render at all unless I change the line:
this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
and hard-code the parameters.
Not sure what the problem is, tried both using an arrow function for draw() and using a normal method, also tried supplying the context as a method parameter for draw() with the same result.

The problem is that you are passing wrong argument to constructor of Circle. Se parameters of constructor and values you pass.
context: CanvasRenderingContext2D ctx
radius: number 200
x: number 300
y: number 50
color: string "blue"
lineWidth: number 5
I think you have switched the order of radius and coordinates parameter.

Related

How do i update text graphics in flashpunk?

Here is a class i made that will be used to make the items for a menu i'm working on.
package
{
import net.flashpunk.Entity;
import net.flashpunk.graphics.Graphiclist;
import net.flashpunk.graphics.Stamp;
import net.flashpunk.graphics.Text
import net.flashpunk.FP;
import net.flashpunk.utils.Input;
public class MenuItem extends Entity
{
public var label:Text; //public text var to display label
public var amount:Text;
public var amountText:String;
public function MenuItem(x:Number=0, y:Number=0, text:String = "", amnt:Number = 0)
{
super(x, y);
label = new Text(text, 10, 10, { size: 20, color: 0xFFFFFF, width: 111, wordWrap: false, align: "center" } ); //format text
label.y = 25; //place text
label.x = 0; // place text
amountText = amnt.toString();
amount = new Text(amountText, 10, 10, { size: 20, color: 0xFFFFFF, width: 111, wordWrap: false, align: "center" } );
amount.y = 25;
amount.x = 50;
graphic = new Graphiclist(label, amount); //set graphic list (png and text)
setHitbox(110, 70, 0, 0);
}
override public function update():void
{
}
}
}
What i'm looking for is how to update the amnt using the update function.
But my knowledge of flashpunk is not great and i;m not sure how i would go about doing this exactly. please and thank you! if what i'm asking is unclear please contact me so i can specify whatever is needed.

Libgdx custom shader per-vertex attribute

After several days of struggling I came here. I'm trying to pass a custom per-vertex vec3 attribute to a custom shader based on this tutorial. The tutorial describes how to pass a custom uniform which actually works fine. However when I'm trying to modify the code to pass my custom per-vertex attribute it seems that nothing is transferred to vertex shader and I can't figure out how to make it to work.
So far I've done the following:
I've created several boxes with modelBuilder.createBox() (so I know for sure every model has 24 vertexes)
Then I'v generated a FloatBuffer containing actual attribute data like this:
int[] data = new int[]{x1, y1, z1, x1, y1, z1, ...}
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(data.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
mAttributeBuffer = byteBuffer.asFloatBuffer();
mAttributeBuffer.put(data);
mAttributeBuffer.position(0);
Then I'm initializing the corresponding attribute location variable (successfully, a_coord >= 0):
a_coord = program.getAttributeLocation("a_coord");
After that on libgdx side in custom shader's render(Renderable) method I'm passing the buffer to OpenGL like this:
program.setVertexAttribute(a_coord, 3, Gdx.gl20.GL_FLOAT, false, 0, mAttributeBuffer);
My custom vertex shader is as the following:
attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec2 a_texCoord0;
uniform mat4 u_worldTrans;
uniform mat4 u_projTrans;
varying vec2 v_texCoord0;
//my custom attribute
attribute vec2 a_coord;
void main() {
v_texCoord0 = a_texCoord0;
float posY = a_position.y + a_coord.y;
gl_Position = u_projTrans * u_worldTrans * vec4(a_position.x, posY, a_position.z, 1.0);
}
The problem
At the moment a_coord is 0 for every vertex. What am I missing and how to correctly pass custom attribute to vertex shader?
I'm guessing the problem is somewhere in VBO field and the way libGDX passes attribute data to vertexes but I still can't figure out how to make it work.
I'll be glad if anyone can point me in the right direction on this question.
Complete code:
Main AplicationListener class:
public class ProtoGame implements ApplicationListener {
public ProtoGame()
{
super();
}
public PerspectiveCamera cam;
public CameraInputController camController;
public Model model;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public ModelBatch modelBatch;
#Override
public void create () {
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 8f, 8f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createBox(1f, 1f, 1f,
new Material(),
VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal | VertexAttributes.Usage.TextureCoordinates);
Color colorU = new Color(), colorV = new Color();
for (int x = -5; x <= 5; x+=2) {
for (int z = -5; z<=5; z+=2) {
ModelInstance instance = new ModelInstance(model, x, 0, z);
//this is where I'll put per-vertex attribute data for every instance
//but for now it's hardcoded in the Shader class so the data is the same across instances
TestShader.DoubleColorAttribute attr = new TestShader.DoubleColorAttribute(TestShader.DoubleColorAttribute.DiffuseUV,
colorU.set((x+5f)/10f, 1f - (z+5f)/10f, 0, 1),
colorV.set(1f - (x+5f)/10f, 0, (z+5f)/10f, 1));
instance.materials.get(0).set(attr);
instances.add(instance);
}
}
modelBatch = new ModelBatch(new BaseShaderProvider() {
#Override
protected Shader createShader(Renderable renderable) {
return new TestShader();
}
});
}
#Override
public void render () {
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
for (ModelInstance instance : instances)
modelBatch.render(instance);
modelBatch.end();
}
#Override
public void dispose () {
model.dispose();
modelBatch.dispose();
}
}
Custom libgdx shader class:
public class TestShader implements Shader {
private FloatBuffer mAttributeBuffer;
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_colorU;
int u_colorV;
int a_coord;
private static String getCustomVertexShader() {
return Gdx.files.internal("shader/test.vertex.glsl").readString();
}
private static String getCustomFragmentShader() {
return Gdx.files.internal("shader/test.fragment.glsl").readString();
}
#Override
public void init() {
program = new ShaderProgram(getCustomVertexShader(), getCustomFragmentShader());
if (!program.isCompiled())
throw new GdxRuntimeException(program.getLog());
//tutorial's logic to init custom uniform locations
u_projTrans = program.getUniformLocation("u_projTrans");
u_worldTrans = program.getUniformLocation("u_worldTrans");
u_colorU = program.getUniformLocation("u_colorU");
u_colorV = program.getUniformLocation("u_colorV");
//initing custom attribute location
a_coord = program.getAttributeLocation("a_coord");
//generating data and passing it to nio Buffer
float data[] = generateData();
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(data.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
mAttributeBuffer = byteBuffer.asFloatBuffer();
mAttributeBuffer.put(data);
mAttributeBuffer.position(0);
}
private float[] generateData() {
Vector3[] dataArray = new Vector3[1];
dataArray[0] = new Vector3(2, 2, 2);
int components = 3;
int vertexPerModel = 24;
float[] data = new float[dataArray.length * components * vertexPerModel];
for(int i = 0; i < dataArray.length; ++i){
int i3 = i * components;
for(int j = 0; j < vertexPerModel; ++j) {
int j3 = j * components;
data[i3 + 0 + j3] = dataArray[i].x;
data[i3 + 1 + j3] = dataArray[i].y;
data[i3 + 2 + j3] = dataArray[i].z;
}
}
return data;
}
#Override
public void dispose() {
program.dispose();
}
#Override
public void begin(Camera camera, RenderContext context) {
this.camera = camera;
this.context = context;
program.begin();
program.setUniformMatrix(u_projTrans, camera.combined);
context.setDepthTest(GL20.GL_LEQUAL);
context.setCullFace(GL20.GL_BACK);
}
#Override
public void render(Renderable renderable) {
program.setUniformMatrix(u_worldTrans, renderable.worldTransform);
//tutorial's logic to pass uniform
DoubleColorAttribute attribute = ((DoubleColorAttribute) renderable.material.get(DoubleColorAttribute.DiffuseUV));
program.setUniformf(u_colorU, attribute.color1.r, attribute.color1.g, attribute.color1.b);
program.setUniformf(u_colorV, attribute.color2.r, attribute.color2.g, attribute.color2.b);
//passing my custom attributes to the vertex shader
program.setVertexAttribute(a_coord, 3, Gdx.gl20.GL_FLOAT, false, 0, mAttributeBuffer);
renderable.mesh.render(program, renderable.primitiveType,
renderable.meshPartOffset, renderable.meshPartSize);
}
#Override
public void end() {
program.end();
}
#Override
public int compareTo(Shader other) {
return 0;
}
#Override
public boolean canRender(Renderable renderable) {
return renderable.material.has(DoubleColorAttribute.DiffuseUV);
}
}
Finally I was able to pass a custom attribute to vertex shader! Thanks a lot to #Xoppa for pointing me in the right direction.
This is the working solution I've got so far (I'm open for any further advices on how to implement it in a more elegant way):
First of all, as Xoppa stated in the comment it's required to create a model providing custom vertex structure while building it. So model creation may look like this:
VertexAttribute posAttr = new VertexAttribute(VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE);
...
VertexAttribute customVertexAttr = new VertexAttribute(512, 3, "a_custom");
VertexAttributes vertexAttributes = new VertexAttributes(
posAttr,
...
customVertexAttr);
ModelBuilder modelBuilder = new ModelBuilder();
modelBuilder.begin();
modelBuilder.
part("box", GL20.GL_TRIANGLES, vertexAttributes, new Material()).
box(1f, 1f, 1f);
model = modelBuilder.end();
Or the same with MeshBuilder:
MeshBuilder meshBuilder = new MeshBuilder();
VertexAttributes vertexAttributes = new VertexAttributes(...);
meshBuilder.begin(vertexAttributes);
meshBuilder.part("box", GL20.GL_TRIANGLES);
meshBuilder.setColor(color);
meshBuilder.box(1f, 1f, 1f);
Mesh mesh = meshBuilder.end();
This code will create model with vertices containing additional data according to the provided attributes. It's time to fill the corresponding vertex array. You need a mesh for this - it stores vertices array - a flat array of packed attributes one after another vertex by vertex. So what you need is a number of attributes per vertex as well as an offset for attribute which needs to be modified. Mesh stores all that data:
Mesh mesh = model.meshes.get(0);
int numVertices = mesh.getNumVertices();
// vertex size and offset are in byte so we need to divide it by 4
int vertexSize = mesh.getVertexAttributes().vertexSize / 4;
//it's possible to use usage int here passed previously to VertexAttribute constructor.
VertexAttribute customAttribute = mesh.getVertexAttribute(512)
int offset = customAttribute.offset / 4;
float[] vertices = new float[numVertices * vertexSize];
mesh.getVertices(vertices);
We are ready to pass the data:
List<Vector3> customData ...
for(int i = 0; i < numVertices; ++i){
int index = i * vertexSize + offset;
vertices[index + 0] = customData.get(i).x;
vertices[index + 1] = customData.get(i).y;
vertices[index + 2] = customData.get(i).z;
}
And don't forget to pass the updated vertices array back to the mesh:
mesh.updateVertices(0, vertices);
That's it.
Here's also an implementation of a helper method to create a mix of default attributes using Usage flags alongside with custom attributes:
private VertexAttributes createMixedVertexAttribute(int defaultAtributes, List<VertexAttribute> customAttributes){
VertexAttributes defaultAttributes = MeshBuilder.createAttributes(defaultAtributes);
List<VertexAttribute> attributeList = new ArrayList<VertexAttribute>();
for(VertexAttribute attribute: defaultAttributes){
attributeList.add(attribute);
}
attributeList.addAll(customAttributes);
VertexAttribute[] typeArray = new VertexAttribute[0];
VertexAttributes mixedVertexAttributes = new VertexAttributes(attributeList.toArray(typeArray));
return mixedVertexAttributes;
}
The full source:
public class ProtoGame implements ApplicationListener {
private static final int CUSTOM_ATTRIBUTE_USAGE = 512;
public ProtoGame()
{
super();
}
public PerspectiveCamera cam;
public CameraInputController camController;
public Model model;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public ModelBatch modelBatch;
#Override
public void create () {
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 8f, 8f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
Model model = createModelWithCustomAttributes();
Mesh mesh = model.meshes.get(0);
setCustomAttributeData(mesh);
Color colorU = new Color(), colorV = new Color();
for (int x = -5; x <= 5; x+=2) {
for (int z = -5; z<=5; z+=2) {
ModelInstance instance = new ModelInstance(model, x, 0, z);
TestShader.DoubleColorAttribute attr = new TestShader.DoubleColorAttribute(TestShader.DoubleColorAttribute.DiffuseUV,
colorU.set((x+5f)/10f, 1f - (z+5f)/10f, 0, 1),
colorV.set(1f - (x+5f)/10f, 0, (z+5f)/10f, 1));
instance.materials.get(0).set(attr);
instances.add(instance);
}
}
modelBatch = new ModelBatch(new BaseShaderProvider() {
#Override
protected Shader createShader(Renderable renderable) {
return new TestShader();
}
});
}
#Override
public void render () {
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
for (ModelInstance instance : instances)
modelBatch.render(instance);
modelBatch.end();
}
private Model createModelWithCustomAttributes() {
int defaultAttributes = VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal | VertexAttributes.Usage.TextureCoordinates;
VertexAttribute customVertexAttr = new VertexAttribute(CUSTOM_ATTRIBUTE_USAGE, 3, "a_custom");
List<VertexAttribute> customAttributeList = new ArrayList<VertexAttribute>();
customAttributeList.add(customVertexAttr);
VertexAttributes vertexAttributes = createMixedVertexAttribute(defaultAttributes, customAttributeList);
ModelBuilder modelBuilder = new ModelBuilder();
modelBuilder.begin();
modelBuilder.
part("box", GL20.GL_TRIANGLES, vertexAttributes, new Material()).
box(1f, 1f, 1f);
return modelBuilder.end();
}
private void setCustomAttributeData(Mesh mesh) {
int numVertices = mesh.getNumVertices();
int vertexSize = mesh.getVertexAttributes().vertexSize / 4;
int offset = mesh.getVertexAttribute(CUSTOM_ATTRIBUTE_USAGE).offset / 4;
float[] vertices = new float[numVertices * vertexSize];
mesh.getVertices(vertices);
for(int i = 0; i < numVertices; ++i){
int index = i * vertexSize + offset;
vertices[index + 0] = i;
vertices[index + 1] = i;
vertices[index + 2] = i;
}
mesh.updateVertices(0, vertices);
}
#Override
public void dispose () {
model.dispose();
modelBatch.dispose();
}
private VertexAttributes createMixedVertexAttribute(int defaultAtributes, List<VertexAttribute> customAttributes){
VertexAttributes defaultAttributes = MeshBuilder.createAttributes(defaultAtributes);
List<VertexAttribute> attributeList = new ArrayList<VertexAttribute>();
for(VertexAttribute attribute: defaultAttributes){
attributeList.add(attribute);
}
attributeList.addAll(customAttributes);
VertexAttribute[] typeArray = new VertexAttribute[0];
VertexAttributes mixedVertexAttributes = new VertexAttributes(attributeList.toArray(typeArray));
return mixedVertexAttributes;
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
Vertex shader:
attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec2 a_texCoord0;
uniform mat4 u_worldTrans;
uniform mat4 u_projTrans;
varying vec2 v_texCoord0;
attribute vec3 a_custom;
void main() {
v_texCoord0 = a_texCoord0;
float posX = a_position.x + a_custom.x;
float posY = a_position.y + a_custom.y;
float posZ = a_position.z + a_custom.z;
gl_Position = u_projTrans * u_worldTrans * vec4(posX, posY, posZ, 1.0);
}
Fragment shader
#ifdef GL_ES
precision mediump float;
#endif
uniform vec3 u_colorU;
uniform vec3 u_colorV;
varying vec2 v_texCoord0;
void main() {
gl_FragColor = vec4(v_texCoord0.x * u_colorU + v_texCoord0.y * u_colorV, 1.0);
}
Based on Xoppa's comment, I managed to get custom attributes working. It's actually so simple! Here is an ES 3.0 example:
#version 300 es
//v30.glsl
in vec3 vertexPosition;
in vec3 vertexColor;
out vec3 outColor;
void main()
{
outColor = vertexColor;
gl_Position = vec4(vertexPosition, 1.0);
}
fragment shader:
#version 300 es
//f30.glsl
precision mediump float;
in vec3 outColor;
out vec4 fragColor;
void main()
{
fragColor = vec4(outColor, 1.0);
}
Gl30Mesh.java
package com.example.jgles;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
public class Gl30Mesh extends ApplicationAdapter
{
private Mesh triangleMesh;
private ShaderProgram passShader;
#Override
public void create()
{
final float [] combinedData = {
-0.8f, -0.8f, 0.0f, 1.0f, 0.0f, 0.0f,
0.8f, -0.8f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 1.0f
};
VertexAttribute vertexChannel = new VertexAttribute(VertexAttributes.Usage.Generic, 3, "vertexPosition");
VertexAttribute colorChannel = new VertexAttribute(VertexAttributes.Usage.Generic, 3, "vertexColor");
String vertexShader = Gdx.files.internal("v30.glsl").readString();
String fragmentShader = Gdx.files.internal("f30.glsl").readString();
passShader = new ShaderProgram(vertexShader, fragmentShader);
if (!passShader.isCompiled()){
throw new IllegalStateException(passShader.getLog());
}
passShader.bind();
triangleMesh = new Mesh(true, 3, 0, vertexChannel, colorChannel);
triangleMesh.setVertices(combinedData);
}
#Override
public void render()
{
Gdx.gl.glViewport(0, 0, 640, 480);
Gdx.gl.glClearColor(0, 0, 1.0f, 0);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
triangleMesh.render(passShader, GL30.GL_TRIANGLES);
}
}
It seems to me when you are already using custom shaders, you use whatever is named in your shaders instead of POSITION_ATTRIBUTE, NORMAL_ATTRIBUTE etc. And as Xoppa said, ShaderProgram.setVertexAttribute simply won't work.
Actually it is possible to call setVertexAttributes directly and have it work without needing a mesh. Just need to extend ShaderProgram like so
public class ShaderProgramExtended extends ShaderProgram {
public ShaderProgramExtended(String v, String f){
super(v,f);
}
/*
This is VERY NAUGHTY. Mario and Nathan probably made it private for a reason
*/
public int getProgram(){
int result;
try{
Field field = ShaderProgram.class.getDeclaredField("program");
field.setAccessible(true);
Object value = field.get(this);
field.setAccessible(false);
if (value == null) {
result = 0;
}else{
result = (Integer) value;
}
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return result;
}
public void begin(int program){
Gdx.gl20.glUseProgram(program);
}
public void draw(int mode, int first, int count){
Gdx.gl20.glDrawArrays(mode,first,count);
}
}
And then call it as you would normally with the "minor" change of sending the shader object integer to the new begin method
public class TestlibGDXv2 extends ApplicationAdapter {
private final String tag = (this).getClass().getSimpleName();
String message = "";
private static final int FLOAT_BYTES = 4;
FloatBuffer vertexData;
FloatBuffer colorData;
ShaderProgramExtended shader;
private static final String COLOR_ATTRIBUTE = ShaderProgram.COLOR_ATTRIBUTE;
private int aColourLocation;
private static final String POSITION_ATTRIBUTE = ShaderProgram.POSITION_ATTRIBUTE;
private int aPositionLocation;
/*
Anti-clockwise winding order. Note, we could share two of the vertices. Haven't for clarity.
*/
float[] vertices = {
-0.5f, -0.5f,
0.5f, -0.5f,
-0.5f, 0.5f,
-0.5f, 0.5f,
0.5f, -0.5f,
0.5f, 0.5f
};
/*
Need to colour each vertex, so need 6.
*/
float[] colors = {1.0f, 0.0f, 0.0f, 1.0f,
0.0f,1.0f,0.0f,1.0f,
0.0f,0.0f,1.0f,1.0f,
0.0f,0.0f,1.0f,1.0f,
0.0f,1.0f,0.0f,1.0f,
1.0f,0.0f,0.0f,1.0f
};
#Override
public void create() {
/*
Convert from Dalvik VM to OpenGL native
*/
vertexData = ByteBuffer.allocateDirect(vertices.length * FLOAT_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
colorData = ByteBuffer.allocateDirect(colors.length * FLOAT_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
vertexData.put(vertices).position(0);
colorData.put(colors).position(0);
initialiseShaders();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shader.begin(shader.getProgram());
shader.setVertexAttribute(aPositionLocation, 2, GL20.GL_FLOAT, false, 0, vertexData);
shader.enableVertexAttribute(aPositionLocation);
shader.setVertexAttribute(aColourLocation, 4, GL20.GL_FLOAT, false, 0, colorData);
shader.enableVertexAttribute(aColourLocation);
shader.draw(GL20.GL_TRIANGLES, 0, 6);
shader.end();
}
private void initialiseShaders() {
String vertexShaderSource =
"#version 130\n" +
"attribute vec4 " + POSITION_ATTRIBUTE + ";\n" + // x,y,z and w
"attribute vec4 " + COLOR_ATTRIBUTE + ";\n" + // r,g,b and a
"varying vec4 v_color;\n" + // pass to fragment shader
"void main(){\n" +
" v_color = "+ COLOR_ATTRIBUTE + ";\n" +
" gl_Position = " + POSITION_ATTRIBUTE + ";\n" +
"}";
String fragmentShaderSource =
"#version 130\n" +
"#ifdef GL_ES\n" +
" precision mediump float;\n" + // medium a good balance between speed and quality
"#endif\n" +
"varying vec4 v_color;\n" + // incoming from vertex shader
"void main(){\n" +
" gl_FragColor = v_color;\n" +
"}";
shader = new ShaderProgramExtended(vertexShaderSource,fragmentShaderSource);
aPositionLocation = shader.getAttributeLocation(POSITION_ATTRIBUTE);
aColourLocation = shader.getAttributeLocation(COLOR_ATTRIBUTE);
}
}
The attribute "a_color" (from ShaderProgram.COLOR_ATTRIBUTE) could just as easily have been "a_custom".
I used this method when I was trying to learn OpenGL ES from WebGL books - there are a lot more of them than libGDX OpenGL books. However, only use the above for learning, the shader is now no longer being managed by libGDX and so will not work nicely on Android when context is lost. OK for desktop, though.
Cheers
John

Distance field font in libgdx

I'm trying to rendering smooth scalable bitmap fonts. After checking this question one of the answers mentioned using distance field fonts.
I'm doing exactly as mentioned in LibGDX wiki article about distance filed fonts. However I can't get it working. Fonts are rendered hazy.
Here's the code I used to generate this output
public class FontRenderTest implements ApplicationListener {
private Texture texture;
private SpriteBatch spriteBatch;
private BitmapFont font;
#Override
public void create() {
spriteBatch = new SpriteBatch();
Texture texture = new Texture(Gdx.files.internal("Raleway.png"), true); // true enables mipmaps
texture.setFilter(TextureFilter.MipMapLinearNearest, TextureFilter.Linear); // linear filtering in nearest mipmap image
font = new BitmapFont(Gdx.files.internal("Raleway.fnt"), new TextureRegion(texture), false);
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
font.draw(spriteBatch, "This is hazy !!", 100, 150);
spriteBatch.end();
}
}
I'm not sure if I properly understand the function of distance field font. If anyone could explain how to render font smooth.
I think it needs a shader and if I recall right the shaders require GL20. As it said in the wiki you would need .frag and .vert files. I modified your code with the help from this Libgdx test: http://git.io/-yAmNg .
It looks like this with different smoothing.
public class FontRenderTest implements ApplicationListener {
private Texture texture;
private SpriteBatch spriteBatch;
private BitmapFont font;
private DistanceFieldShader distanceFieldShader;
private static class DistanceFieldShader extends ShaderProgram {
public DistanceFieldShader () {
// The vert and frag files are copied from http://git.io/yK63lQ (vert) and http://git.io/hAcw9Q (the frag)
super(Gdx.files.internal("data/shaders/distancefield.vert"), Gdx.files.internal("data/shaders/distancefield.frag"));
if (!isCompiled()) {
throw new RuntimeException("Shader compilation failed:\n" + getLog());
}
}
/** #param smoothing a value between 0 and 1 */
public void setSmoothing (float smoothing) {
float delta = 0.5f * MathUtils.clamp(smoothing, 0, 1);
setUniformf("u_lower", 0.5f - delta);
setUniformf("u_upper", 0.5f + delta);
}
}
#Override
public void create() {
spriteBatch = new SpriteBatch();
Texture texture = new Texture(Gdx.files.internal("hiero.png"), true); // true enables mipmaps
texture.setFilter(TextureFilter.MipMapLinearNearest, TextureFilter.Linear); // linear filtering in nearest mipmap image
font = new BitmapFont(Gdx.files.internal("hiero.fnt"), new TextureRegion(texture), false);
distanceFieldShader = new DistanceFieldShader();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
spriteBatch.setShader(distanceFieldShader);
font.draw(spriteBatch, "This is pretty sharp !!", 100, 120);
distanceFieldShader.setSmoothing(0f);
spriteBatch.setShader(distanceFieldShader);
font.draw(spriteBatch, "This is hazy !!", 100, 150);
distanceFieldShader.setSmoothing(1f);
spriteBatch.setShader(distanceFieldShader);
font.draw(spriteBatch, "This is pretty smooth !!", 100, 180);
distanceFieldShader.setSmoothing(1/2f);
spriteBatch.end();
}
Use the shader created by DistanceFieldFont.createDistanceFieldShader.

Recieveing Error : undefined property bitmapfilter type AS3

I'm working on a tutorial for a pong clone and am currently trying to add a BevelFilter to a ball image. When I type in the code it returns an error saying
undefined property bitmapfilter type
I checked on live docs and it should be valid. I marked the line with two *'s
package
{
import flash.display.Sprite;
import flash.display.Graphics;
import flash.events.Event;
import flash.filters.BevelFilter;
import flash.filters.GlowFilter;
public class Ball extends Sprite
{
private const RADIUS:int = 12;
private const COLOR:uint = 0x01A6B2;
private const COLOR2:uint = 0x45FCFF;
** private const BEVEL:BevelFilter = new BevelFilter(4, 90, COLOR2, 1, COLOR2, 1, 10, 10, 1, 1, BitmapFilterType.Inner, true);
private const GLOW:GlowFilter = new GlowFilter(0xFFFFFF, .6, 0, 0, 5, 1, true);
public function Ball():void {
addEventListener(Event.ADDED_TO_STAGE, go);
}
private function go(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, go);
graphics.lineStyle(2, COLOR, 1);
graphics.beginFill(COLOR);
graphics.drawCircle(0, 0, RADIUS);
filters = [BEVEL, GLOW];
}
}
}
Thanks!
I use these on a regular basis. Your code should look like this...
private const BEVEL:BevelFilter = new BevelFilter(4, 90, COLOR2, 1, COLOR2, 1, 10, 10, 1, 1, "inner", true);
That second-to-last argument accepts a string.
Not sure why the docs represent it differently. This was off of the code hints for Adobe Flash CS6, and I know this should work.

ActionScript Read Sprite's Graphics?

how can i retrieve the set graphics properties of a sprite? for example, in the code below, i'd like to get the color of the sprite, also it's rounded corners setting and other graphics attributes.
var sp:Sprite = new Sprite();
sp.graphics.beginFill(0xFF0000, 0.75);
sp.graphics.drawRoundRect(0, 0, 300, 50, 10, 10);
sp.graphics.endFill();
addChild(sp);
trace(sp.graphics.color); //pseudo trace - this doesn't work
I am almost certain this is not possible. However, there are certainly other ways to do this. What about having a valueObject for each property that stores the values used. Then you could have a GraphicalDisplayObject that you either inherit from or use via composition. For instance:
package {
class FillVO extends Object {
public var fill_color:Number = 0xFF0000;
public var fill_opacity:Number = 0.75;
}
}
package {
import FillVO;
class GraphicalDisplayObject extends Sprite {
public var fill_vo:FillVO;
public function beginFill($vo:FillVO) {
graphics.beginFill($vo.fill_color, $vo.fill_opacity);
}
...
}
}
package {
import GraphicalDisplayObject;
class ObjectWithGraphicalProperties extends Sprite {
public var gfx:GraphicalDisplayObject;
public function ObjectWithGraphicalProperties() {
gfx = new GraphicalDisplayObject();
addChild(gfx);
}
public function beginFill($color:Number, $opactity:Number) {
var fill_vo:FillVO = new FillVO();
fill_vo.fill_color = $color;
fill_vo.fill_opacity = $opacity;
gfx.beginFill(fill_vo);
}
...
}
}
Then to use it...
var obj:ObjectWithGraphicalProperties = new ObjectWithGraphicalProperties();
addChild(obj);
obj.beginFill(0xffff00, .2);
...
...
trace(obj.gfx.fill_vo.fill_color);
This is obviously via composition, and you would need to write the additional proxied methods and corresponding valueObjects... but it should work.