Search Results

Search found 3545 results on 142 pages for 'arrays'.

Page 12/142 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • C++ simple arrays and pointers question

    - by nashmaniac
    So here's the confusion, let's say I declare an array of characters char name[3] = "Sam"; and then I declare another array but this time using pointers char * name = "Sam"; What's the difference between the two? I mean they work the same way in a program. Also how does the latter store the size of the stuff that someone puts in it, in this case 3 characters? Also how is it different from char * name = new char[3]; If those three are different where should they be used I mean in what circumstances?

    Read the article

  • libgdx arrays onTouch() method and delays for objects

    - by johnny-b
    i am trying to create random bullets but it is not working for some reason. also how can i make a delay so the bullets come every 30 seconds or 1 minute???? also the onTouch method does not work and it is not taking the bullet away???? shall i put the array in the GameRender class? thanks public class GameWorld { public static Ball ball; private Bullet bullet1; private ScrollHandler scroller; private Array<Bullet> bullets = new Array<Bullet>(); public GameWorld() { ball = new Ball(280, 273, 32, 32); bullet = new Bullet(-300, 200); scroller = new ScrollHandler(0); bullets.add(new Bullet(bullet.getX(), bullet.getY())); bullets = new Array<Bullet>(); Bullet bullet = null; float bulletX = 0.0f; float bulletY = 0.0f; for (int i=0; i < 10; i++) { bulletX = MathUtils.random(-10, 10); bulletY = MathUtils.random(-10, 10); bullet = new Bullet(bulletX, bulletY); bullets.add(bullet); } } public void update(float delta) { ball.update(delta); bullet.update(delta); scroller.update(delta); } public static Ball getBall() { return ball; } public ScrollHandler getScroller() { return scroller; } public Bullet getBullet1() { return bullet1; } } i also tried this and it is not working, i used this in the GameRender class Array<Bullet> enemies=new Array<Bullet>(); //in the constructor of the class enemies.add(new Bullet(bullet.getX(), bullet.getY())); // this throws an exception for some reason??? this is in the render method for(int i=0; i<bullet.size; i++) bullet.get(i).draw(batcher); //this i am using in any method that will allow me from the constructor to update to render for(int i=0; i<bullet.size; i++) bullet.get(i).update(delta); this is not taking the bullet out @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { for(int i=0; i<bullet.size; i++) if(bullet.get(i).getBounds().contains(screenX,screenY)) bullet.removeIndex(i--); return false; } thanks for the help anyone.

    Read the article

  • Creating a voxel world with 3D arrays using threads

    - by Sean M.
    I am making a voxel game (a bit like Minecraft) in C++(11), and I've come across an issue with creating a world efficiently. In my program, I have a World class, which holds a 3D array of Region class pointers. When I initialize the world, I give it a width, height, and depth so it knows how large of a world to create. Each Region is split up into a 32x32x32 area of blocks, so as you may guess, it takes a while to initialize the world once the world gets to be above 8x4x8 Regions. In order to alleviate this issue, I thought that using threads to generate different levels of the world concurrently would make it go faster. Having not used threads much before this, and being still relatively new to C++, I'm not entirely sure how to go about implementing one thread per level (level being a xz plane with a height of 1), when there is a variable number of levels. I tried this: for(int i = 0; i < height; i++) { std::thread th(std::bind(&World::load, this, width, height, depth)); th.join(); } Where load() just loads all Regions at height "height". But that executes the threads one at a time (which makes sense, looking back), and that of course takes as long as generating all Regions in one loop. I then tried: std::thread t1(std::bind(&World::load, this, w, h1, h2 - 1, d)); std::thread t2(std::bind(&World::load, this, w, h2, h3 - 1, d)); std::thread t3(std::bind(&World::load, this, w, h3, h4 - 1, d)); std::thread t4(std::bind(&World::load, this, w, h4, h - 1, d)); t1.join(); t2.join(); t3.join(); t4.join(); This works in that the world loads about 3-3.5 times faster, but this forces the height to be a multiple of 4, and it also gives the same exact VAO object to every single Region, which need individual VAOs in order to render properly. The VAO of each Region is set in the constructor, so I'm assuming that somehow the VAO number is not thread safe or something (again, unfamiliar with threads). So basically, my question is two one-part: How to I implement a variable number of threads that all execute at the same time, and force the main thread to wait for them using join() without stopping the other threads? How do I make the VAO objects thread safe, so when a bunch of Regions are being created at the same time across multiple threads, they don't all get the exact same VAO? Turns out it has to do with GL contexts not working across multiple threads. I moved the VAO/VBO creation back to the main thread. Fixed! Here is the code for block.h/.cpp, region.h/.cpp, and CVBObject.h/.cpp which controls VBOs and VAOs, in case you need it. If you need to see anything else just ask. EDIT: Also, I'd prefer not to have answers that are like "you should have used boost". I'm trying to do this without boost to get used to threads before moving onto other libraries.

    Read the article

  • Matrices: Arrays or separate member variables?

    - by bjz
    I'm teaching myself 3D maths and in the process building my own rudimentary engine (of sorts). I was wondering what would be the best way to structure my matrix class. There are a few options: Separate member variables: struct Mat4 { float m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44; // methods } A multi-dimensional array: struct Mat4 { float[4][4] m; // methods } An array of vectors struct Mat4 { Vec4[4] m; // methods } I'm guessing there would be positives and negatives to each. From 3D Math Primer for Graphics and Game Development, 2nd Edition p.155: Matrices use 1-based indices, so the first row and column are numbered 1. For example, a12 (read “a one two,” not “a twelve”) is the element in the first row, second column. Notice that this is different from programming languages such as C++ and Java, which use 0-based array indices. A matrix does not have a column 0 or row 0. This difference in indexing can cause some confusion if matrices are stored using an actual array data type. For this reason, it’s common for classes that store small, fixed size matrices of the type used for geometric purposes to give each element its own named member variable, such as float a11, instead of using the language’s native array support with something like float elem[3][3]. So that's one vote for method one. Is this really the accepted way to do things? It seems rather unwieldy if the only benefit would be sticking with the conventional math notation.

    Read the article

  • How do you format arrays within parameters?

    - by joslinm
    I'm talking about something like this: echo $form->input('general_addresss', array( 'label' => 'Where will you go today?' 'format' => array('before', 'input', 'after', 'label', 'after', 'error') )); Do you start with one array parameter, then break a line? If it can't fit on a line, do you immediately break a line? After of which, do you do a set number of tabs over? What happens if an array within an array has lots of properties? Is there any particular guide you follow?

    Read the article

  • BlockingCollection having issues with byte arrays

    - by MJLaukala
    I am having an issue where an object with a byte[20] is being passed into a BlockingCollection on one thread and another thread returning the object with a byte[0] using BlockingCollection.Take(). I think this is a threading issue but I do not know where or why this is happening considering that BlockingCollection is a concurrent collection. Sometimes on thread2, myclass2.mybytes equals byte[0]. Any information on how to fix this is greatly appreciated. MessageBuffer.cs public class MessageBuffer : BlockingCollection<Message> { } In the class that has Listener() and ReceivedMessageHandler(object messageProcessor) private MessageBuffer RecievedMessageBuffer; On Thread1 private void Listener() { while (this.IsListening) { try { Message message = Message.ReadMessage(this.Stream, this); if (message != null) { this.RecievedMessageBuffer.Add(message); } } catch (IOException ex) { if (!this.Client.Connected) { this.OnDisconnected(); } else { Logger.LogException(ex.ToString()); this.OnDisconnected(); } } catch (Exception ex) { Logger.LogException(ex.ToString()); this.OnDisconnected(); } } } Message.ReadMessage(NetworkStream stream, iTcpConnectClient client) public static Message ReadMessage(NetworkStream stream, iTcpConnectClient client) { int ClassType = -1; Message message = null; try { ClassType = stream.ReadByte(); if (ClassType == -1) { return null; } if (!Message.IDTOCLASS.ContainsKey((byte)ClassType)) { throw new IOException("Class type not found"); } message = Message.GetNewMessage((byte)ClassType); message.Client = client; message.ReadData(stream); if (message.Buffer.Length < message.MessageSize + Message.HeaderSize) { return null; } } catch (IOException ex) { Logger.LogException(ex.ToString()); throw ex; } catch (Exception ex) { Logger.LogException(ex.ToString()); //throw ex; } return message; } On Thread2 private void ReceivedMessageHandler(object messageProcessor) { if (messageProcessor != null) { while (this.IsListening) { Message message = this.RecievedMessageBuffer.Take(); message.Reconstruct(); message.HandleMessage(messageProcessor); } } else { while (this.IsListening) { Message message = this.RecievedMessageBuffer.Take(); message.Reconstruct(); message.HandleMessage(); } } } PlayerStateMessage.cs public class PlayerStateMessage : Message { public GameObject PlayerState; public override int MessageSize { get { return 12; } } public PlayerStateMessage() : base() { this.PlayerState = new GameObject(); } public PlayerStateMessage(GameObject playerState) { this.PlayerState = playerState; } public override void Reconstruct() { this.PlayerState.Poisiton = this.GetVector2FromBuffer(0); this.PlayerState.Rotation = this.GetFloatFromBuffer(8); base.Reconstruct(); } public override void Deconstruct() { this.CreateBuffer(); this.AddToBuffer(this.PlayerState.Poisiton, 0); this.AddToBuffer(this.PlayerState.Rotation, 8); base.Deconstruct(); } public override void HandleMessage(object messageProcessor) { ((MessageProcessor)messageProcessor).ProcessPlayerStateMessage(this); } } Message.GetVector2FromBuffer(int bufferlocation) This is where the exception is thrown because this.Buffer is byte[0] when it should be byte[20]. public Vector2 GetVector2FromBuffer(int bufferlocation) { return new Vector2( BitConverter.ToSingle(this.Buffer, Message.HeaderSize + bufferlocation), BitConverter.ToSingle(this.Buffer, Message.HeaderSize + bufferlocation + 4)); }

    Read the article

  • Factory for arrays of objects in python

    - by Vorac
    Ok, the title might be a little misleading. I have a Window class that draws widgets inside itself in the constructor. The widgets are all of the same type. So I pass a list of dictionaries, which contain the parameters for each widget. This works quite nicely, but I am worried that the interface to callers is obfuscated. That is, in order to use Window, one has to study the class, construct a correct list of dictionaries, and then call the constructor with only one parameter - widgets_params. Is this good or bad design? What alternatives does the python syntax provide?

    Read the article

  • Traversing Java Object Arrays [migrated]

    - by Sundi
    Please Help. Program does not read Array rentBooks[] in the for() loop this option is selected when choosing option 2 then option 4 in the menu The Array reads perfectly when reading the items after the setBook() Method import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.io.*; import java.util.Locale; import java.text.SimpleDateFormat ; class Library { protected static String Author; protected static String Title; SimpleDateFormat PublicationDate; int itemCode; int available = 1; } class Book extends Library { protected static String PublisherName; protected static String Edition; static Book[] rentBooks = new Book[5]; //Book[] rentBooks = new Book[5]; int count = 0; public Book() { String start= "start"; showBook.main(anza); } public void setBook( String Auth, String Titl, String PublishName) { this.Author = Auth; this.Title = Titl; this.PublisherName = PublishName; } public void getBook() { //System.out.println("*************BOOKS*************************"); System.out.println( "\n\nThe Author of the first Book is "+ this.Author ); System.out.println( "The Title of the book is "+ this.Title); System.out.println( "The Publisher of the book is "+ this.PublisherName ); // System.out.println( "The Edition of the book is "+ Edition ); } } class showBook{ static Book[] rentBooks = new Book[5]; static Book[] rentBooks2 = new Book[5]; static int a,b; //for ( a=0; a < 5; a++ ) //rentBooks2[a] = new Book(); public static void main(String[] args) { File file = new File("Book2.txt"); //Book libraryBooks = new Book(); int j; //initialise Array Class Objects for( j = 0; j < 5; j++) { rentBooks[j] = new Book(); } int i = 0; try{ Scanner scanner = new Scanner(file); scanner.useDelimiter(","); String loan=""; int loan2; while( scanner.hasNextLine()) { //Should the Books be Stored in An Array? // At the moment you have separate objects stored in unknown location String Author = scanner.next(); String Title = scanner.next(); String PublisherName = scanner.next(); if ( i < 4) { System.out.println(i); rentBooks[i].setBook(Author, Title, PublisherName); rentBooks[i].getBook(); // MEMBERS SHOWN i++; } public class readBook4{ public static void main(String[] args) { int number =0; System.out.println( "Please select one of the choices below " ); System.out.println( "Select option 1 to list all items in the library "); System.out.println( "Select option 2 to list the items by category"); System.out.println( "Select option 3 to choose item available in the library "); System.out.println( "Select option 7 to exit " ); InputStreamReader isr = new InputStreamReader( System.in); BufferedReader buffer = new BufferedReader( isr); String input = ""; try { input = buffer.readLine(); number = Integer.parseInt(input); //int number = Integer.parseInt( Edition); if ( number == 1 ) { System.out.println( " \nThanks you are reading "+ input); //showStudent.main(args); showPeriodical.main(args); showDVD.main(args); // showBook.main(args); } if ( number == 2 ) { //jht.cls(); int number2; System.out.println( "Please select one of the choices below " ); System.out.println( "Select option 4 to list Books only "); System.out.println( "Select option 5 to list the Periodicals only"); System.out.println( "Select option 6 to list DVDs only"); InputStreamReader isr2 = new InputStreamReader(System.in); BufferedReader buffer2 = new BufferedReader(isr2); String input2 = ""; try { input2 = buffer2.readLine(); buffer.close(); } catch(IOException e) { System.out.println("An input error has occured"); } //System.out.println("Thanks, you are reading" + input2); number2 = Integer.parseInt(input2); if ( number2 == 4 ) { showBook.main(args); } if ( number2 == 5 ) { showPeriodical.main(args); } if ( number2 == 6 ) { showDVD.main(args); } // readBook4.main(args); } if( number == 3 ) { //showBook.main(args); showBook.availableBooks(); showDVD.availableDVD(); showPeriodical.availablePeriodical(); } if ( number == 7 ) { showStudent.main(args); } buffer.close(); } catch( IOException e ) { System.out.println( " An input error has occured "); } //System.out.println( " \nThanks you are reading "+ input); } } } //buffer.close(); scanner.close(); } catch( FileNotFoundException e) { System.out.println("File not Found"); } for ( i=0; i < 5; i++ ) rentBooks[i].getBook(); //ARRAY NOT SHOWN } }

    Read the article

  • redimension multidimensional arrays in Excel VBA [migrated]

    - by user147178
    Take a look at the following code. What my problem is is that I can't figure out how to redimension the n integer and the b integer. What I'm doing is the array sent1 is already working and it is populated with about 4 sentences. I need to go through each sentence and work on it but I'm having trouble. dim sent1() dim sent2() dim n as integer, b as integer, x as integer dim temp_sent as string b = 0 For n = 1 to ubound(sent1) temp_sent = sent1(n) for x = 1 to len(temp_sent1) code if a then b = b + 1 THIS IS THE PART OF THE CODE THAT IS NOT WORKING redim preserve sent2(1 to ubound(sent1), b) sent2(n,b) = [code] next next

    Read the article

  • Arrays and For Loop [closed]

    - by java
    I wrote this code: import java.io.*; public class dictionary { public static void main(String args[]) { String[] MyArrayE=new String[5]; String[] MyArrayS=new String[5]; String[] MyArrayA=new String[5]; MyArrayE[0]="Language"; MyArrayE[1]="Computer"; MyArrayE[2]="Engineer"; MyArrayE[3]="Home"; MyArrayE[4]="Table"; MyArrayS[0]="Lingua"; MyArrayS[1]="Computador"; MyArrayS[2]="Ing."; MyArrayS[3]="Casa"; MyArrayS[4]="Mesa"; System.out.println("Please enter a word"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String word= null; try { word= br.readLine(); } catch (IOException e) { System.out.println("Error!"); System.exit(1); } System.out.println("Your word is " + word); for(int i=0; i<MyArrayA.length; i++) { if(word.equals(MyArrayS[i])) { System.out.println(MyArrayE[i]); } } } } My Question: What about if the user inputs a word not in MyArrayS, I want to check that and print a statement like "Word does not exist". I think that it might look like: if(word!=MyArrayS) { System.out.println("Word does not exist"); }

    Read the article

  • PHP: Extending static member arrays

    - by tstenner
    I'm having the following scenario: class A { public static $arr=array(1,2); } class B extends A { public static $arr=array(3,4); } Is there any way to combine these 2 arrays so B::$arr is 1,2,3,4? I don't need to alter these arrays, but I can't declare them als const, as PHP doesn't allow const arrays.http://stackoverflow.com/questions/ask The PHP manual states, that I can only assign strings and constants, so parent::$arr + array(1,2) won't work, but I think it should be possible to do this.

    Read the article

  • How to implement arrays in an interpreter?

    - by Ray
    I have managed to write several interpreters including Tokenizing Parsing, including more complicated expressions such as ((x+y)*z)/2 Building bytecode from syntax trees Actual bytecode execution What I didn't manage: Implementation of dictionaries/lists/arrays. I always got stuck with getting multiple values into one variable. My value structure (used for all values passed around, including variables) looks like this, for example: class Value { public: ValueType type; int integerValue; string stringValue; } Works fine with integers and strings, but how could I implement arrays? (From now on with array I mean arrays in my experimental language, not in C++) How can I fit the array concept into the Value class above? Is it possible? How should I make arrays able to be passed around just as you could pass around integers and strings in my language, using the class above? Accessing array elements or memory allocation wouldn't be the problem, I just don't know how to store them.

    Read the article

  • C# Custom Control Properties load before Load and arrays are empties

    - by Wildhorn
    Hello, I made a custom control with custom properties. When I modify these properties in the "Form.cs [Design]", I need stuff to happens (it fill some arrays and modify the look of the control), so I call a function within the "set" of the property. All of this works good. My problem is that when I run the program with my custom control, it seems that properties "set" is called, which will call the function, but then, my arrays seems now to have lost all their values and the function use these arrays, but now because they are all empty, it crashes due to NullException blahblahblah. It also seems that properties "set" is called before the control Load (which I guess is called only when it is added to my Form, and not when the Form load). So question is, why does my arrays become empty once I try to run the Form and is there an event that is called before that when the Form load? Thanks

    Read the article

  • Array of Arrays - writing to File problem

    - by iFloh
    Hi, and again my array of arrays ... I try to improve my app performance by buffering arrays on file for later reuse. I have an NSMutableArray that contains about 30 NSMutableArrays with NSNumber, NSDate and NSString Objects. I try to write the file using this call: bool result = [myArray writeToFile:[fileMethods getFullPath:[NSString stringWithFormat:@"iEts%@.arr", [aDate shortDateString]]] atomically:NO]; = result = FALSE. The Path method is: + (NSString *) getFullPath:(NSString *)forFileName { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:forFileName]; } and the aDate call returns a shortDateString with ddMMyy. The NSLog NSLog(@"%@", [fileMethods getFullPath:[NSString stringWithFormat:@"iEts%@.arr", [aDate shortDateString]]]); on the path generation returns: /Users/me/Library/Application Support/iPhone Simulator/User/Applications/86729620-EC1D-4C10-A799-0C638BB27933/Documents/iEts010510.arr FURTHER: It must have something to do with the Array of Arrays, since I also write 3 further simple arrays (containing NSStrings) that all succeed. The Array of Arrays gets generated using the addObject method Any ideas what could cause the trouble?

    Read the article

  • Three 1D Arrays to One 2D Array

    - by Steven
    I have a function which accepts a 2D array, but my data is in three 1D arrays. How do I create a 2D array consisting of the three arrays to pass to the subroutine? Dim Y0(32) As Double Dim Y1(32) As Double Dim Y2(32) As Double 'Code to fill arrays' 'Attempting to call:' Sub PlotYMult(YData(,) as Double)

    Read the article

  • Java: How do I implement a method that takes 2 arrays and returns 2 arrays?

    - by HansDampf
    Okay, here is what I want to do: I want to implement a crossover method for arrays. It is supposed to take 2 arrays of same size and return two new arrays that are a kind of mix of the two input arrays. as in [a,a,a,a] [b,b,b,b] ------ [a,a,b,b] [b,b,a,a]. Now I wonder what would be the suggested way to do that in Java, since I cannot return more than one value. My ideas are: - returning a Collection(or array) containing both new arrays. I dont really like that one because it think would result in a harder to understand code. - avoiding the need to return two results by calling the method for each case but only getting one of the results each time. I dont like that one either, because there would be no natural order about which solution should be returned. This would need to be specified, though resulting in harder to understand code. Plus, this will work only for this basic case, but I will want to shuffle the array before the crossover and reverse that afterwards. I cannot do the shuffling isolated from the crossover since I wont want to actually do the operation, instead I want to use the information about the permutation while doing the crossover, which will be a more efficient way I think.

    Read the article

  • SFML: Generate a background image

    - by BlackMamba
    I want to generate a background, which is used in the game, on every instance of the game based on certain conditions. To do so, I'm using a sf::RenderTexture and a sf::Texture like this: sf::RenderTexture image; std::vector<sf::Texture> textures; sf::Texture texture; // instantiating the vector of textures and the image not shown here for (int i = 0; i < certainSize; ++i) { if(certainContition) { texture.setTexture("file"); texture.setPosition(pos1, pos2); } else { ... } image.draw(texture); } The point here is that I draw single textures on a sf::RenderTexture, but because textures always are on the graphic cards memory, I can't exceed a certain map size which I have to. I also considered using an sf::Image, but I can't find a way to draw an image (i.e. a texture) to it. The third way I found was using an sf::VertexArray, but this seems to be a bit too low-level for my rather simple purposes. So is there a common way to dynamically generate a background image based on other existing images?

    Read the article

  • What is a better abstraction layer for D3D9 and OpenGL vertex data management?

    - by Sam Hocevar
    My rendering code has always been OpenGL. I now need to support a platform that does not have OpenGL, so I have to add an abstraction layer that wraps OpenGL and Direct3D 9. I will support Direct3D 11 later. TL;DR: the differences between OpenGL and Direct3D cause redundancy for the programmer, and the data layout feels flaky. For now, my API works a bit like this. This is how a shader is created: Shader *shader = Shader::Create( " ... GLSL vertex shader ... ", " ... GLSL pixel shader ... ", " ... HLSL vertex shader ... ", " ... HLSL pixel shader ... "); ShaderAttrib a1 = shader->GetAttribLocation("Point", VertexUsage::Position, 0); ShaderAttrib a2 = shader->GetAttribLocation("TexCoord", VertexUsage::TexCoord, 0); ShaderAttrib a3 = shader->GetAttribLocation("Data", VertexUsage::TexCoord, 1); ShaderUniform u1 = shader->GetUniformLocation("WorldMatrix"); ShaderUniform u2 = shader->GetUniformLocation("Zoom"); There is already a problem here: once a Direct3D shader is compiled, there is no way to query an input attribute by its name; apparently only the semantics stay meaningful. This is why GetAttribLocation has these extra arguments, which get hidden in ShaderAttrib. Now this is how I create a vertex declaration and two vertex buffers: VertexDeclaration *decl = VertexDeclaration::Create( VertexStream<vec3,vec2>(VertexUsage::Position, 0, VertexUsage::TexCoord, 0), VertexStream<vec4>(VertexUsage::TexCoord, 1)); VertexBuffer *vb1 = new VertexBuffer(NUM * (sizeof(vec3) + sizeof(vec2)); VertexBuffer *vb2 = new VertexBuffer(NUM * sizeof(vec4)); Another problem: the information VertexUsage::Position, 0 is totally useless to the OpenGL/GLSL backend because it does not care about semantics. Once the vertex buffers have been filled with or pointed at data, this is the rendering code: shader->Bind(); shader->SetUniform(u1, GetWorldMatrix()); shader->SetUniform(u2, blah); decl->Bind(); decl->SetStream(vb1, a1, a2); decl->SetStream(vb2, a3); decl->DrawPrimitives(VertexPrimitive::Triangle, NUM / 3); decl->Unbind(); shader->Unbind(); You see that decl is a bit more than just a D3D-like vertex declaration, it kinda takes care of rendering as well. Does this make sense at all? What would be a cleaner design? Or a good source of inspiration?

    Read the article

  • How to create per-vertex normals when reusing vertex data?

    - by Chris Smith
    I am displaying a cube using a vertex buffer object (gl.ELEMENT_ARRAY_BUFFER). This allows me to specify vertex indicies, rather than having duplicate vertexes. In the case of displaying a simple cube, this means I only need to have eight vertices total. Opposed to needing three vertices per triangle, times two triangles per face, times six faces. Sound correct so far? My question is, how do I now deal with vertex attribute data such as color, texture coordinates, and normals when reusing vertices using the vertex buffer object? If I am reusing the same vertex data in my indexed vertex buffer, how can I differentiate when vertex X is used as part of the cube's front face versus the cube's left face? In both cases I would like the surface normal and texture coordinates to be different. I understand I could average the surface normal, however I would like to render a cube. Also, this still doesn't work for texture coordinates. Is there a way to save memory using a vertex buffer object while being able to provide different vertex attribute data based on context? (Per-triangle would be idea.) Or should I just duplicate each vertex for each context in which it gets rendered. (So there is a one-to-one mapping between vertex, normal, color, etc.) Note: I'm using OpenGL ES.

    Read the article

  • Loading Wavefront Data into VAO and Render It

    - by Jordan LaPrise
    I have successfully loaded a triangulated wavefront(.obj) into 6 vectors, the first 3 vectors contain the locations for vertices, uv coords, and normals. The last three have the indices stored for each of the faces. I have been looking into using VAO's and VBO's to render, and I'm not quite sure how to load and render the data. One of my biggest concerns is the fact that indexed rendering only allows you to have one array of indices, meaning I somehow have to make all of the first three vectors the same size, the only way I thought of doing this, is to make 3 new vertex's of equal size, and load in the data for each face, but that would completely defeat the purpose of indexing. Any help would be appreciated. Thanks in advance, Jordan

    Read the article

  • Generating geometry when using VBO

    - by onedayitwillmake
    Currently I am working on a project in which I generate geometry based on the players movement. A glorified very long trail, composed of quads. I am doing this by storing a STD::Vector, and removing the oldest verticies once enough exist, and then calling glDrawArrays. I am interested in switching to a shader based model, usually examples I see the VBO is generated at start and then that's basically it. What is the best route to go about creating geometry in real time, using shader / VBO approach

    Read the article

  • how can I specify interleaved vertex attributes and vertex indices

    - by freefallr
    I'm writing a generic ShaderProgram class that compiles a set of Shader objects, passes args to the shader (like vertex position, vertex normal, tex coords etc), then links the shader components into a shader program, for use with glDrawArrays. My vertex data already exists in a VertexBufferObject that uses the following data structure to create a vertex buffer: class CustomVertex { public: float m_Position[3]; // x, y, z // offset 0, size = 3*sizeof(float) float m_TexCoords[2]; // u, v // offset 3*sizeof(float), size = 2*sizeof(float) float m_Normal[3]; // nx, ny, nz; float colour[4]; // r, g, b, a float padding[20]; // padded for performance }; I've already written a working VertexBufferObject class that creates a vertex buffer object from an array of CustomVertex objects. This array is said to be interleaved. It renders successfully with the following code: void VertexBufferObject::Draw() { if( ! m_bInitialized ) return; glBindBuffer( GL_ARRAY_BUFFER, m_nVboId ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_nVboIdIndex ); glEnableClientState( GL_VERTEX_ARRAY ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glEnableClientState( GL_NORMAL_ARRAY ); glEnableClientState( GL_COLOR_ARRAY ); glVertexPointer( 3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 0) ); glTexCoordPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 12)); glNormalPointer(GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 20)); glColorPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 32)); glDrawElements( GL_TRIANGLES, m_nNumIndices, GL_UNSIGNED_INT, ((char*)NULL + 0) ); glDisableClientState( GL_VERTEX_ARRAY ); glDisableClientState( GL_TEXTURE_COORD_ARRAY ); glDisableClientState( GL_NORMAL_ARRAY ); glDisableClientState( GL_COLOR_ARRAY ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); } Back to the Vertex Array Object though. My code for creating the Vertex Array object is as follows. This is performed before the ShaderProgram runtime linking stage, and no glErrors are reported after its steps. // Specify the shader arg locations (e.g. their order in the shader code) for( int n = 0; n < vShaderArgs.size(); n ++) glBindAttribLocation( m_nProgramId, n, vShaderArgs[n].sFieldName.c_str() ); // Create and bind to a vertex array object, which stores the relationship between // the buffer and the input attributes glGenVertexArrays( 1, &m_nVaoHandle ); glBindVertexArray( m_nVaoHandle ); // Enable the vertex attribute array (we're using interleaved array, since its faster) glBindBuffer( GL_ARRAY_BUFFER, vShaderArgs[0].nVboId ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vShaderArgs[0].nVboIndexId ); // vertex data for( int n = 0; n < vShaderArgs.size(); n ++ ) { glEnableVertexAttribArray(n); glVertexAttribPointer( n, vShaderArgs[n].nFieldSize, GL_FLOAT, GL_FALSE, vShaderArgs[n].nStride, (GLubyte *) NULL + vShaderArgs[n].nFieldOffset ); AppLog::Ref().OutputGlErrors(); } This doesn't render correctly at all. I get a pattern of white specks onscreen, in the shape of the terrain rectangle, but there are no regular lines etc. Here's the code I use for rendering: void ShaderProgram::Draw() { using namespace AntiMatter; if( ! m_nShaderProgramId || ! m_nVaoHandle ) { AppLog::Ref().LogMsg("ShaderProgram::Draw() Couldn't draw object, as initialization of ShaderProgram is incomplete"); return; } glUseProgram( m_nShaderProgramId ); glBindVertexArray( m_nVaoHandle ); glDrawArrays( GL_TRIANGLES, 0, m_nNumTris ); glBindVertexArray(0); glUseProgram(0); } Can anyone see errors or omissions in either the VAO creation code or rendering code? thanks!

    Read the article

  • Lighting with VBO

    - by nkint
    I'm using a Java JOGL wrapper called processing.org. I have coded some enviroment on it and I'm quite proud of it even if it has some ready stuffs that I didn't know anything about it (==LIGHTS). Then, for some geometry, I've decided to use a VBO. I had to pass in the hard way and recode all lights. But I can't achieve the same result. This is the original light system: And this with VBO: With this code: Vec3D l; gl.glEnable(GL.GL_LIGHTING); gl.glEnable(GL.GL_LIGHT0); gl.glEnable(GL.GL_COLOR_MATERIAL); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, new float[]{0.8f,0f,0f}, 0); l = new Vec3D(0,0,-10); gl.glColor3f(0.8f,0f,0f); gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, new float[] { l.x, l.y, l.z, 0 }, 0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPOT_DIRECTION, new float[] { 1, 1, 1, 1 }, 0); I can't achive the same light, the same color material, and the same wireframe stuffs. If needed I can also post the code I use for VBO, but it is quite standard vertex array grabbed on the net that uses glDrawArrays

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >