I want to make my vertex array dynamic. So that values would be added after every mouse event. When user drags his mouse I register mouse location coordinates. Coordinates is named ‘loc’. And when user drags his mouse the ‘loc’ value is updated. So I want that when ‘loc’ is updated, coordinates would be added to vertex array. Still I can only do that when ‘loc’ is updated it rebuilds vertex array, so my vertex array always has only one coordinates (current ‘loc’ value).
My vertex array values are stored in GLfloat:
GLfloat vertexes[] = { loc.x, loc.y };
‘loc’ is registered in - (void) mouseDragged:(NSEvent *)event by:
loc = [self convertPoint: [event locationInWindow] fromView:self];
Vertex array is drawn in - (void) drawMyShape by:
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vertexes);
glPointSize(30);
glDrawArrays(GL_POINTS, 0, vertexCount);
glFlush();
glDisableClientState(GL_VERTEX_ARRAY);
- (void) drawMyShape is called after registering mouse events and adding them to GLfloat in - (void) mouseDragged:(NSEvent *)event by:
[self drawMyShape]
Current code:
in .h file:
NSMutableArray *vertices;
@property (nonatomic, retain) NSMutableArray *vertices;
in the beginning of .m file
@dynamic vertices;
in .m file in - (id)initWithCoder:(NSCoder *)coder
vertices = [[NSMutableArray alloc] init];
in .m file in - (void) mouseDragged:(NSEvent *)event
loc = [self convertPoint: [event locationInWindow] fromView:self];
NSValue *locationValue = [NSValue valueWithPoint:loc];
[vertices addObject:locationValue];`
[self addValuesToArray];
in .m file in - (void) addValuesToArray
int count = [vertices count] * 2;
NSLog(@"count: %d", count);
int currIndex = 0;
GLfloat GLVertices[] = {*(GLfloat *)malloc(count * sizeof(GLfloat))};
for (NSValue *locationValue in vertices) {
NSValue *locationValue = [vertices objectAtIndex:currIndex++];
CGPoint curLoc = locationValue.pointValue;
GLVertices[currIndex++] = curLoc.x;
GLVertices[currIndex++] = curLoc.y;
}
And it crashes on
NSValue *locationValue = [vertices objectAtIndex:i];
After crash in Log i see (removed some parts of log because they are not important I think):
sum: 2
*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]
sum: 3
*** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]
sum: 4
*** -[__NSArrayM objectAtIndex:]: index 4 beyond bounds [0 .. 3]
sum: 5
*** -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]
sum: 6
(lldb)
Use NSMutableArray to store your location objects dynamically.
Init the array at initialization phase :
Add vertices on mouse event :
Convert to
GLFloatarray before drawing :Now you can use the
glVerticesarray when drawing.