Post the code written by you thread. :D

Discussion in 'Web development / Programming' started by raksmey1309, Dec 1, 2009.

  1. cottonvibes

    cottonvibes You're already dead... Emu Author

    Messages:
    5,473
    Likes Received:
    4
    ^ agreed
    I was going to mention the goto thing to him before, since i've seen him use it on other code too.

    also raksmey, i think you really need to work on your code formatting.
    you have the brackets mis-aligned, and you have empty lines of text on some if-statements, but not in others. its very sloppy (and its not just this sample, but all code you post is in a similar state).
  2. @ruantec

    @ruantec Crazy GFX coder Emu Author

    Messages:
    14,887
    Likes Received:
    1,076
    I think we will make Raks to stop coding hehehehehe. I guess he should try to take it serious in the first place... whatever he makes mistakes now or not is irrelevant as Long as he learn from those and improve itself over the time. The first Thing is try to master the Basics then move Forward with something more advanced. After that the best Thing is try to work in application design using Interfaces etc.
  3. cottonvibes

    cottonvibes You're already dead... Emu Author

    Messages:
    5,473
    Likes Received:
    4
    yeh i don't want to make him stop coding; but i hope that by pointing out his mistakes he can improve :D
  4. -Ashe-

    -Ashe- Member

    Messages:
    197
    Likes Received:
    0
    To me the main issue is the void main :p
  5. raksmey1309

    raksmey1309 I m meow desu! ^_^

    Messages:
    4,372
    Likes Received:
    77
    I am self studying every night ! you can imagine those book is full of English!!! O_O I have no longer have teacher at school to look for anymore. I've just read for about two weeks that's the point I try to write what I've learned so please forgive me even if it is very very very difficult and seem impossible I dont want to stop coding I will try to read more and get out of basic as much as I can!
    Well, the current book I read is Premiere C++ 5th edition!

    Thank you I will never stop coding even if I dont have much time to study... I have only a few hour to study at night. If you have what is the guide start where to start and what to do right code is really appreciate I will try to figure out!
  6. raksmey1309

    raksmey1309 I m meow desu! ^_^

    Messages:
    4,372
    Likes Received:
    77
    I try not to specify the size of vector but I run it give me error I can't figure out why :(
  7. cottonvibes

    cottonvibes You're already dead... Emu Author

    Messages:
    5,473
    Likes Received:
    4
    you're probably doing:
    Code:
    vector<string> product();
    when you should just do:
    Code:
    vector<string> product;
    in c++, when you want to use the default-constructor of an object, you leave out the parenthesis.

    (the reason for this is that the version with the parenthesis is indistinguishable from a function-prototype of a function named "product" which returns "vector<string>")
  8. raksmey1309

    raksmey1309 I m meow desu! ^_^

    Messages:
    4,372
    Likes Received:
    77
    I tried that but it always give me this error !
    I was wondering why it is out of range when there is no element in the vector and the ebook I am reading said the vector is flexible and we can add element to it later I cant figure it out the error.

    [​IMG]
  9. cottonvibes

    cottonvibes You're already dead... Emu Author

    Messages:
    5,473
    Likes Received:
    4
    oh okay thats a run-time error; i thought you were getting a compile-time error.

    Code:
    vector<string> product;
    product[0]="1-CoCa";
    product[1]="2-Pepsi";
    product[2]="3-Soda";
    ^ the issue here is that you have an empty vector and you're accessing the first element via "product[0]", which doesn't exist yet (because you haven't pushed any items to the vector yet).

    you need to change the code to:
    Code:
    vector<string> product;
    product.push_back("1-CoCa");
    product.push_back("2-Pepsi");
    product.push_back("3-Soda");
  10. raksmey1309

    raksmey1309 I m meow desu! ^_^

    Messages:
    4,372
    Likes Received:
    77
    Thank you that solve my problem I've been figure out. :thumb:
  11. @ruantec

    @ruantec Crazy GFX coder Emu Author

    Messages:
    14,887
    Likes Received:
    1,076
    Seems like i missed few things here after going to bed... glad to see that Raks got some help and is trying to take it serious... Keep it up!
  12. Dax

    Dax ライチュウ|タオ

    Messages:
    4,016
    Likes Received:
    20
    Here's an OpenGL renderer I'm working on for emulators in C#(it's still a WIP, so error checking isn't really implemented yet):

    Code:
    using System;
    using System.Drawing;
    using OpenTK.Graphics.OpenGL;
    using GL = OpenTK.Graphics.OpenGL.GL;
    
    namespace VideoRenderers
    {
        public class VideoGL
        {
            private int texture;
    
            public Size TextureSize
            {
                get;
                set;
            }
            public Size WindowSize
            {
                get;
                set;
            }
    
            public Size Scale
            {
                get;
                set;
            }
    
            public bool Initialized
            {
                get;
                set;
            }
    
            public bool VSync
            {
                get { return OpenTK.Graphics.GraphicsContext.CurrentContext.VSync; }
                set { OpenTK.Graphics.GraphicsContext.CurrentContext.VSync = value; }
            }
    
            public VideoGL() { }
    
            public void Init()
            {
                if (!Initialized)
                {
                    GL.ClearColor(Color.SkyBlue);
                    SetupViewport();
                    CreateTexture();
                    Initialized = true;
                }
            }
    
            private void CreateTexture()
            {
                GL.Enable(EnableCap.Texture2D);
    
                GL.GenTextures(1, out texture);
                if (texture != 0)
                {
                    GL.BindTexture(TextureTarget.Texture2D, texture);
                    GL.TexImage2D<byte>(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, TextureSize.Width, TextureSize.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, new byte[Size.Width * Size.Height * 4]);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
                }
                else throw new System.Exception("Unable to create texture. Exiting...");
            }
    
            public void SetupViewport()
            {
                GL.MatrixMode(MatrixMode.Projection);
                GL.PushMatrix();
                GL.LoadIdentity();
                GL.Ortho(0, WindowSize.Width, WindowSize.Height, 0, -1, 1);
                GL.Viewport(0, 0, WindowSize.Width, WindowSize.Height);
            }
    
            public void Render(ref byte[] data)
            {
                GL.TexImage2D<byte>(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, TextureSize.Width, TextureSize.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, data);
    
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
    
                GL.MatrixMode(MatrixMode.Modelview);
                GL.PushMatrix();
                GL.LoadIdentity();
    
                GL.Begin(BeginMode.Quads);
                {
                    GL.TexCoord2(0, 0); GL.Vertex2(0, 0);
    
                    GL.TexCoord2(1, 0); GL.Vertex2(TextureSize.Width * Scale.Width, 0);
    
    
                    GL.TexCoord2(1, 1); GL.Vertex2(TextureSize.Width * Scale.Width, TextureSize.Height * Scale.Height);
    
    
                    GL.TexCoord2(0, 1); GL.Vertex2(0, TextureSize.Height * TextureSize.Height);
    
                } GL.End();
            }
    
            public void SetPixel(int x, int y, int r, int g, int b, ref byte[] data)
            {
                if (x >= Size.Width)
                    x = Size.Width - 1;
    
                if (y >= Size.Height)
                    y = Size.Height - 1;
    
                int position = (x * 4) + (y * (Size.Height * 8));
    
                data[position++] = (byte) r;
                data[position++] = (byte) g;
                data[position++] = (byte) b;
                data[position]   = (byte) 255;
            }
    
    
            byte[] pixel = new byte[4];
            public byte[] GetPixel(int x, int y, ref byte[] data)
            {
                if (x >= Size.Width)
                    x = Size.Width - 1;
    
                if (y >= Size.Height)
                    y = Size.Height - 1;
    
                int position = (x * 4) + (y * (Size.Height * 8));
                
                for(int i = 0; i < pixel.Length; i++)
                    pixel[i] = data[position++];
                
                return pixel;
            }
    
            public void ClearScreen(ref byte[] data)
            {
                Array.Clear(data, 0, data.Length);
            }
        }
    }
    Simple, but it seems to work okay.

    Reasons I wrote an OpenGL and not DirectX renderer, even though it's C#:
    1. C# can run on stuff other than Windows(DirectX can with WINE, but meh) via Mono.
    2. I wanted to mess around with OpenGL for fun.
    Last edited: Apr 18, 2013
  13. @ruantec

    @ruantec Crazy GFX coder Emu Author

    Messages:
    14,887
    Likes Received:
    1,076
    Nice Dax!!! that is one of the things i love most about C# and that is the cleaness of the code as it usually doesn't look messy unless you start to write weird things ;)
  14. Dax

    Dax ライチュウ|タオ

    Messages:
    4,016
    Likes Received:
    20
    Thanks. I'll probably whip up a quick Space Invaders or Chip8 emu to test it eventually.
  15. -Ashe-

    -Ashe- Member

    Messages:
    197
    Likes Received:
    0
    Your getPixel has some issues though, and I'm not quite sure what the point of the whole thing might be, apart from rendering an "empty" texture...
  16. cottonvibes

    cottonvibes You're already dead... Emu Author

    Messages:
    5,473
    Likes Received:
    4
    Dax shouldn't this:
    Code:
    int position = (x * 4) + (y * (Size.Height * 8));
    be:
    Code:
    int position = (x + y * Size.Width) * 4;
    also what is the point of "byte[] pixel = new byte[4];" being declared as a class member instead of being declared inside GetPixel()?
  17. blueshogun96

    blueshogun96 Shadow of nothing... Staff Member Moderator Emu Author

    Messages:
    6,044
    Likes Received:
    50
    A C-based random number generator I put together. The code I based it off of is in the comments. I can't speak for you all, but I prefer to avoid using the C-standard rand() function when possible. This way, I can have different algorithms, seperate random number generators for different things so that the outcome won't be effected by something else that needs randomization, as well as getting a constant stream of predictable and customizable results.

    Code:
    #include <stdio.h>
    #include "rng.h"
    
    
    int master_seed = 0;    /* The master seed's value */
    int slave_seed;
    
    
    void setseed( int seed )
    {
        /* Set the master seed value */
        master_seed = seed;
    }
    
    void reseed()
    {
        /* Reset the slave seed to the master seed's value */
        slave_seed = master_seed;
    }
    
    
    /* http://www.daniweb.com/software-development/c/code/216329/construct-your-own-random-number-generator */
    
    int rand1( int lim )
    {
        if( slave_seed < 100000 )
            slave_seed += 100000;
        
        slave_seed = (slave_seed * 125) % 2796203;
        return ((slave_seed % lim) + 1);
    }
    
    int rand2( int lim )
    {
        slave_seed = (slave_seed * 32719 + 3) % 32749;
        return ((slave_seed % lim) + 1);
    }
    
    int rand3( int lim )
    {
        slave_seed = (((slave_seed * 214013L + 2531011L) >> 16) & 32767);
        return ((slave_seed % lim) + 1);
    }
    
    void rng_init( struct rng_t* rng, int (*rng_algorithm)(int) )
    {
        if( rng )
        {
            rng->setseed = setseed;
            rng->reseed = reseed;
            rng->random = rng_algorithm;
        }
    }
    
  18. cottonvibes

    cottonvibes You're already dead... Emu Author

    Messages:
    5,473
    Likes Received:
    4
    i think c++ would've been nicer for that.
    the use of function pointers also prevents inline optimization for the random number generators.

    also why is there +1 on all the sequences?
    "return ((slave_seed % lim) + 1);"

    doesn't it make more sense to have the range be [0, lim) instead of [1, lim]?


    you bring up a good point about the rand() that's included in the standard lib. since its range and implementation may be diff for each compiler/platform, it makes it unreliable.
    a custom routine is nicer for stability.

    i personally like RNG's based on linear feedback shift registers, because the algorithms are efficient bitwise operations, and its more intuitive to see how they work.
  19. blueshogun96

    blueshogun96 Shadow of nothing... Staff Member Moderator Emu Author

    Messages:
    6,044
    Likes Received:
    50
    I agree about the C++ part, but I used C because I was initially using this with a game I wrote in pure C, and was too lazy to change it to a real C++ class.

    When I was first using this RNG, I left that in there because I wanted the result to be at least 1 each time, but that's just how it was originally written and I was (once again) too lazy to edit or optimize that code.
  20. blueshogun96

    blueshogun96 Shadow of nothing... Staff Member Moderator Emu Author

    Messages:
    6,044
    Likes Received:
    50
    Old spline code. C-based, but still quite usable. For 3D splines, simply add the Z coordinate yourself and anywhere else where appropriate.

    spline.h
    Code:
    #pragma once
    
    /* Spline structure */
    struct spline_t
    {
    	struct Vector2* base_points;	/* The base points used to calculate this spline */
    	struct Vector2* points;			/* The actual points forming this spline (after tesselation) */
    	int num_base_points;			/* The number of base points */
    	int num_points;					/* The number of points (after tesselation) */
    	int tesselation;				/* Number of times this spline is to be tesselated */
    	int start_point;				/* The point in which the entity is moving from (in a given segment) */
    	int end_point;					/* The point in which the entity is moving to (in a given segment) */
    	float delta;					/* Used in movement calculation (from one segment to the next) */
    	float speed;					/* Speed of entity moving along this line (max 100) */
    };
    
    struct Vector2
    {
        float x, y;
    };
    
    /* Spline calulation and rendering functions */
    int create_spline( struct spline_t* s, struct Vector2* bp, int bp_count, int tess, float speed );
    void delete_spline( struct spline_t* s );
    void draw_spline( struct spline_t* s, float* colour );
    int move_position_on_spline( struct spline_t* s );
    void get_current_position_on_spline( struct spline_t* s, struct Vector2* vout );
    void get_next_position_on_spline( struct spline_t* s, struct Vector2* vout );
    int copy_spline( struct spline_t* dst, struct spline_t* src );
    
    spline.c
    Code:
    #include "platform.h"
    #include "spline.h"
    
    /* NOTES: The actual speed value is really divided by 100 to get a percentage.
    		  This dictates how far the position moves between one point to the next
    		  in the spline.  As the tesselation for the spline grows, the slower the
    		  entity will move as there are more and shorter line segments to traverse
    		  through.
    */
    
    void tesselate( struct spline_t** s )
    {
    	struct Vector2 first, last;
    	struct Vector2* temp;
    	int new_size = 1;
    	int i = 0, v = 1;
    
    	first.x = (*s)->points[0].x;
    	first.y = (*s)->points[0].y;
    	last.x = (*s)->points[(*s)->num_points-1].x;
    	last.y = (*s)->points[(*s)->num_points-1].y;
    
    	for( i = 0; i < (*s)->num_points-1; ++i )
    		new_size += 2;
    
    	new_size++;
    
    	temp = (struct Vector2*) malloc( sizeof( struct Vector2 ) * new_size );
    
    	temp[0].x = first.x;
    	temp[0].y = first.y;
    
    	for( i = 0; i < (*s)->num_points-1; ++i )
    	{
    		struct Vector2* p0 = &(*s)->points[i];
    		struct Vector2* p1 = &(*s)->points[i+1];
    		struct Vector2 Q, R;
    
    		Q.x = 0.75f*p0->x + 0.25f*p1->x;
    		Q.y = 0.75f*p0->y + 0.25f*p1->y;
    
    		R.x = 0.25f*p0->x + 0.75f*p1->x;
    		R.y = 0.25f*p0->y + 0.75f*p1->y;
    
    		temp[v].x = Q.x;
    		temp[v].y = Q.y;
    		v++;
    		temp[v].x = R.x;
    		temp[v].y = R.y;
    		v++;
    	}
    
    	temp[new_size-1].x = last.x;
    	temp[new_size-1].y = last.y;
    
    	free((*s)->points);
    	(*s)->points = (struct Vector2*) malloc( sizeof( struct Vector2 ) * new_size );
    	memcpy( (*s)->points, temp, sizeof( struct Vector2 ) * new_size );
    	free(temp);
    
    	(*s)->num_points = new_size;
    }
    
    int create_spline( struct spline_t* s, struct Vector2* bp, int bp_count, int tess, float speed )
    {
    	/* Sanity checks */
    	/* For a straight line, just a regular line segment to avoid wasting memory */
    	if( !s || !bp || bp_count < 3 )
    		return 0;
    
    
    	/* Copy the list of base points */
    	/* The copy of spline_t::base_points will be modfied during tesselation */
    	s->base_points = (struct Vector2*) malloc( sizeof( struct Vector2 ) * bp_count );
    	if( !s->base_points )
    		return 0;
    
    	s->points = (struct Vector2*) malloc( sizeof( struct Vector2 ) * bp_count );
    	if( !s->points )
    		return 0;
    
    	memcpy( s->base_points, bp, sizeof( struct Vector2 ) * bp_count );
    	memcpy( s->points, bp, sizeof( struct Vector2 ) * bp_count );
    
    	/* Set other important fields */
    	s->num_base_points = bp_count;
    	s->num_points = bp_count;
    	s->tesselation = tess;
    	s->speed = speed * 0.01f;
    	s->start_point = 0;
    	s->end_point = 1;
    	s->delta = 0.0f;
    
    	/* Tesselate the spline (if desired) */
    	while( tess > 0 )
    	{
    		tesselate( &s );
    		tess--;
    	}
    
    	return 1;
    }
    
    void delete_spline( struct spline_t* s )
    {
    	/* Delete allocated memory */
    	if(s->base_points)
    	{
    		free(s->base_points);
    		s->base_points = NULL;
    	}
    	if(s->points)
    	{
    		free(s->points);
    		s->points = NULL;
    	}
    }
    
    void draw_spline( struct spline_t* s, float* colour )
    {
    #if 0
    	/* Draw the spline (useful for debugging) */
    	glDisable( GL_TEXTURE_2D );
    	glColor4fv( colour );
    	glEnableClientState( GL_VERTEX_ARRAY );
    	glVertexPointer( 2, GL_FLOAT, 0, (float*) s->points );
    	glDrawArrays( GL_LINE_STRIP, 0, s->num_points );
    #if 1
    	glPointSize(5);
    	glVertexPointer( 2, GL_FLOAT, 0, (float*) s->base_points );
    	glDrawArrays( GL_POINTS, 0, s->num_base_points );
    	glPointSize(1);
    #endif
    	glDisableClientState( GL_VERTEX_ARRAY );
    	glEnable( GL_TEXTURE_2D );
    #endif
    }
    
    int move_position_on_spline( struct spline_t* s )
    {
    	/* Move the entity's position along this spline using the given speed
    	   settings.  When the entity reaches the end of the spline, this function
    	   will return a non-zero value. */
    
    	struct Vector2 pos;
    	struct Vector2 p1;
    	struct Vector2 p2;
    	int end_of_line = 0;
    
    	if( !s )
    		return 0;
    
    	memcpy( &p1, &s->points[s->start_point], sizeof( struct Vector2 ) );
    	memcpy( &p2, &s->points[s->end_point], sizeof( struct Vector2 ) );
    
    	pos.x = p1.x + s->delta * ( p2.x - p1.x );
    	pos.y = p1.y + s->delta * ( p2.y - p1.y );
    
    	s->delta += s->speed;
    
    	if( s->delta > 1.0f )
    	{
    		if( !end_of_line )
    			s->start_point++;
    
    		if( ++s->end_point > s->num_points-1 )
    		{
    		//	s->start_point = 0;
    		//	s->end_point = 1;
    
    			end_of_line = 1;
    		}
    
    		s->delta = 0.0f;
    	}
    
    	return end_of_line;
    }
    
    void get_current_position_on_spline( struct spline_t* s, struct Vector2* vout )
    {
    	/* Return the current position of the entity's movement on this spline */
    	struct Vector2 p1;
    	struct Vector2 p2;
    
    	if( !s )
    		return;
    
    	if( !vout )
    		return;
    
    	memcpy( &p1, &s->points[s->start_point], sizeof( struct Vector2 ) );
    	memcpy( &p2, &s->points[s->end_point], sizeof( struct Vector2 ) );
    
    	vout->x = p1.x + s->delta * ( p2.x - p1.x );
    	vout->y = p1.y + s->delta * ( p2.y - p1.y );
    }
    
    void get_next_position_on_spline( struct spline_t* s, struct Vector2* vout )
    {
    	/* Return the next position of the entity's movement on this spline */
        /* Predict movement by one increment. */
        
    	struct Vector2 p1;
    	struct Vector2 p2;
        float d = s->delta + s->speed;
        
    	if( !s )
    		return;
        
    	if( !vout )
    		return;
        
    	memcpy( &p1, &s->points[s->start_point], sizeof( struct Vector2 ) );
    	memcpy( &p2, &s->points[s->end_point], sizeof( struct Vector2 ) );
        
    	vout->x = p1.x + d * ( p2.x - p1.x );
    	vout->y = p1.y + d * ( p2.y - p1.y );
    }
    
    int copy_spline( struct spline_t* dst, struct spline_t* src )
    {
    	/* This function simply makes a copy of an existing spline and attempts to copy
    	   the data over to the new spline being created based on what data has already
    	   been provided. The caller is responsible for deallocating the copied spline. */
    
    	/* Before copying a darn thing, we need to verify that we have valid pointers */
    	if( !dst || !src )
    		return 0; /* fail */
    
    	/* We have valid spline pointers to work with. Create a new spline based on the
    	   original one. */
    	return create_spline( dst, src->base_points, src->num_base_points, src->tesselation, src->speed );
    }
    

Share This Page