Point distance program written without a framework The Next CEO of Stack OverflowOptimize sorting of Array according to Distance (CLLocation)Review my file-searching programCreating a Playlist programFirst simple program; counting button pressesA flashing ! exclamation ! point ! barGame Achievements without Singleton“Silly program” for moving the mouse and doing other thingsLaunching links to a chat room - Invitation ProgramCopying a file hash to clipboard without PowerShellBatch file to delete calling program and then itself

Where do students learn to solve polynomial equations these days?

Can this note be analyzed as a non-chord tone?

Is it ok to trim down a tube patch?

how one can write a nice vector parser, something that does pgfvecparseA=B-C; D=E x F;

Towers in the ocean; How deep can they be built?

How to Implement Deterministic Encryption Safely in .NET

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

free fall ellipse or parabola?

The Ultimate Number Sequence Puzzle

Point distance program written without a framework

Reference request: Grassmannian and Plucker coordinates in type B, C, D

Do scriptures give a method to recognize a truly self-realized person/jivanmukta?

Is a distribution that is normal, but highly skewed, considered Gaussian?

Calculate the Mean mean of two numbers

What is the process for purifying your home if you believe it may have been previously used for pagan worship?

In the "Harry Potter and the Order of the Phoenix" video game, what potion is used to sabotage Umbridge's speakers?

How to find image of a complex function with given constraints?

Why don't programming languages automatically manage the synchronous/asynchronous problem?

Film where the government was corrupt with aliens, people sent to kill aliens are given rigged visors not showing the right aliens

Aggressive Under-Indexing and no data for missing index

What happened in Rome, when the western empire "fell"?

What difference does it make using sed with/without whitespaces?

Is it professional to write unrelated content in an almost-empty email?

Easy to read palindrome checker



Point distance program written without a framework



The Next CEO of Stack OverflowOptimize sorting of Array according to Distance (CLLocation)Review my file-searching programCreating a Playlist programFirst simple program; counting button pressesA flashing ! exclamation ! point ! barGame Achievements without Singleton“Silly program” for moving the mouse and doing other thingsLaunching links to a chat room - Invitation ProgramCopying a file hash to clipboard without PowerShellBatch file to delete calling program and then itself










2












$begingroup$


I have been developing a cross-platform game based on open C libraries (mainly glfw) with a direct focus on Windows development. The beginning of my programming career taught me familiarity in Objective-C, however I've been using pure C for the past few years in embedded applications.



Now that I'm trying to return to proper desktop program development, I'm wondering if it's a good idea to transfer my Objective-C skills to Windows in order to tidy up my C code. My current way of programming is creating a struct for data that I need and then creating functions around those structs: struct Point int x, int y; and then float Point_calculateDistance(struct Point *obj1, struct Point *obj2). This approach to me seemed very redundant and too object-oriented to write all in C. It would make more sense to me to write an Objective-C class to do this where everything can be more encapsulated.



I prefer not to use any framework for my code to increase the portability. I'm currently using VS Code and MSYS2 (mingw64) with GCC 8.3.0. I threw together a working example that demonstrates how I attempt to build a simple class. Does my code look reasonable? Am I performing any bad habits (within reason considering that I'm not using a framework)? Does this currently leak memory? Let me know what you think.



#include <objc/objc.h>
#include <objc/runtime.h>
#include <objc/Object.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>


@interface Point : Object
float x;
float y;


@property float x;
@property float y;

-(id)initWithX: (float)xval AndY: (float)yval;
-(float)calculateDistance: (Point *)other;

@end

@implementation Point

@synthesize x;
@synthesize y;

+(id)alloc
id obj = malloc(class_getInstanceSize(self));
object_setClass(obj, self);
return obj;


-(void)dealloc
free(self);


-(id)init
x = 0.0;
y = 0.0;
return self;


-(id)initWithX: (float)xval AndY: (float)yval
x = xval;
y = yval;
return self;


-(float)calculateDistance: (Point *)other
return sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));


@end

int main(int argc, char **argv)
Point *point1 = [[Point alloc] init];
Point *point2 = [[Point alloc] initWithX: 1.5 AndY: 1.5];

printf("Distance is %f.n", [point1 calculateDistance: point2]);

[point1 dealloc];
[point2 dealloc];
return EXIT_SUCCESS;











share|improve this question











$endgroup$











  • $begingroup$
    where is the [super init]?
    $endgroup$
    – E.Coms
    2 hours ago










  • $begingroup$
    @E.Coms The base class Object only has the variable isa and the methods class and isEqual: so calling [super init] causes a seg. fault.
    $endgroup$
    – dylanweber
    2 hours ago










  • $begingroup$
    I use Xcode and not familiar with Object. I use NSObject and found it runs well at least in grammar. Without super. it just looks missing Root Object.
    $endgroup$
    – E.Coms
    2 hours ago











  • $begingroup$
    @E.Coms NSObject is a piece of Foundation.h which is written by Apple. Finding a class that does something similar would require writing my own or using a framework like GNUStep, both of which are overkill for my uses.
    $endgroup$
    – dylanweber
    2 hours ago










  • $begingroup$
    how about subclass of Point, will you still miss super?
    $endgroup$
    – E.Coms
    2 hours ago
















2












$begingroup$


I have been developing a cross-platform game based on open C libraries (mainly glfw) with a direct focus on Windows development. The beginning of my programming career taught me familiarity in Objective-C, however I've been using pure C for the past few years in embedded applications.



Now that I'm trying to return to proper desktop program development, I'm wondering if it's a good idea to transfer my Objective-C skills to Windows in order to tidy up my C code. My current way of programming is creating a struct for data that I need and then creating functions around those structs: struct Point int x, int y; and then float Point_calculateDistance(struct Point *obj1, struct Point *obj2). This approach to me seemed very redundant and too object-oriented to write all in C. It would make more sense to me to write an Objective-C class to do this where everything can be more encapsulated.



I prefer not to use any framework for my code to increase the portability. I'm currently using VS Code and MSYS2 (mingw64) with GCC 8.3.0. I threw together a working example that demonstrates how I attempt to build a simple class. Does my code look reasonable? Am I performing any bad habits (within reason considering that I'm not using a framework)? Does this currently leak memory? Let me know what you think.



#include <objc/objc.h>
#include <objc/runtime.h>
#include <objc/Object.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>


@interface Point : Object
float x;
float y;


@property float x;
@property float y;

-(id)initWithX: (float)xval AndY: (float)yval;
-(float)calculateDistance: (Point *)other;

@end

@implementation Point

@synthesize x;
@synthesize y;

+(id)alloc
id obj = malloc(class_getInstanceSize(self));
object_setClass(obj, self);
return obj;


-(void)dealloc
free(self);


-(id)init
x = 0.0;
y = 0.0;
return self;


-(id)initWithX: (float)xval AndY: (float)yval
x = xval;
y = yval;
return self;


-(float)calculateDistance: (Point *)other
return sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));


@end

int main(int argc, char **argv)
Point *point1 = [[Point alloc] init];
Point *point2 = [[Point alloc] initWithX: 1.5 AndY: 1.5];

printf("Distance is %f.n", [point1 calculateDistance: point2]);

[point1 dealloc];
[point2 dealloc];
return EXIT_SUCCESS;











share|improve this question











$endgroup$











  • $begingroup$
    where is the [super init]?
    $endgroup$
    – E.Coms
    2 hours ago










  • $begingroup$
    @E.Coms The base class Object only has the variable isa and the methods class and isEqual: so calling [super init] causes a seg. fault.
    $endgroup$
    – dylanweber
    2 hours ago










  • $begingroup$
    I use Xcode and not familiar with Object. I use NSObject and found it runs well at least in grammar. Without super. it just looks missing Root Object.
    $endgroup$
    – E.Coms
    2 hours ago











  • $begingroup$
    @E.Coms NSObject is a piece of Foundation.h which is written by Apple. Finding a class that does something similar would require writing my own or using a framework like GNUStep, both of which are overkill for my uses.
    $endgroup$
    – dylanweber
    2 hours ago










  • $begingroup$
    how about subclass of Point, will you still miss super?
    $endgroup$
    – E.Coms
    2 hours ago














2












2








2





$begingroup$


I have been developing a cross-platform game based on open C libraries (mainly glfw) with a direct focus on Windows development. The beginning of my programming career taught me familiarity in Objective-C, however I've been using pure C for the past few years in embedded applications.



Now that I'm trying to return to proper desktop program development, I'm wondering if it's a good idea to transfer my Objective-C skills to Windows in order to tidy up my C code. My current way of programming is creating a struct for data that I need and then creating functions around those structs: struct Point int x, int y; and then float Point_calculateDistance(struct Point *obj1, struct Point *obj2). This approach to me seemed very redundant and too object-oriented to write all in C. It would make more sense to me to write an Objective-C class to do this where everything can be more encapsulated.



I prefer not to use any framework for my code to increase the portability. I'm currently using VS Code and MSYS2 (mingw64) with GCC 8.3.0. I threw together a working example that demonstrates how I attempt to build a simple class. Does my code look reasonable? Am I performing any bad habits (within reason considering that I'm not using a framework)? Does this currently leak memory? Let me know what you think.



#include <objc/objc.h>
#include <objc/runtime.h>
#include <objc/Object.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>


@interface Point : Object
float x;
float y;


@property float x;
@property float y;

-(id)initWithX: (float)xval AndY: (float)yval;
-(float)calculateDistance: (Point *)other;

@end

@implementation Point

@synthesize x;
@synthesize y;

+(id)alloc
id obj = malloc(class_getInstanceSize(self));
object_setClass(obj, self);
return obj;


-(void)dealloc
free(self);


-(id)init
x = 0.0;
y = 0.0;
return self;


-(id)initWithX: (float)xval AndY: (float)yval
x = xval;
y = yval;
return self;


-(float)calculateDistance: (Point *)other
return sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));


@end

int main(int argc, char **argv)
Point *point1 = [[Point alloc] init];
Point *point2 = [[Point alloc] initWithX: 1.5 AndY: 1.5];

printf("Distance is %f.n", [point1 calculateDistance: point2]);

[point1 dealloc];
[point2 dealloc];
return EXIT_SUCCESS;











share|improve this question











$endgroup$




I have been developing a cross-platform game based on open C libraries (mainly glfw) with a direct focus on Windows development. The beginning of my programming career taught me familiarity in Objective-C, however I've been using pure C for the past few years in embedded applications.



Now that I'm trying to return to proper desktop program development, I'm wondering if it's a good idea to transfer my Objective-C skills to Windows in order to tidy up my C code. My current way of programming is creating a struct for data that I need and then creating functions around those structs: struct Point int x, int y; and then float Point_calculateDistance(struct Point *obj1, struct Point *obj2). This approach to me seemed very redundant and too object-oriented to write all in C. It would make more sense to me to write an Objective-C class to do this where everything can be more encapsulated.



I prefer not to use any framework for my code to increase the portability. I'm currently using VS Code and MSYS2 (mingw64) with GCC 8.3.0. I threw together a working example that demonstrates how I attempt to build a simple class. Does my code look reasonable? Am I performing any bad habits (within reason considering that I'm not using a framework)? Does this currently leak memory? Let me know what you think.



#include <objc/objc.h>
#include <objc/runtime.h>
#include <objc/Object.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>


@interface Point : Object
float x;
float y;


@property float x;
@property float y;

-(id)initWithX: (float)xval AndY: (float)yval;
-(float)calculateDistance: (Point *)other;

@end

@implementation Point

@synthesize x;
@synthesize y;

+(id)alloc
id obj = malloc(class_getInstanceSize(self));
object_setClass(obj, self);
return obj;


-(void)dealloc
free(self);


-(id)init
x = 0.0;
y = 0.0;
return self;


-(id)initWithX: (float)xval AndY: (float)yval
x = xval;
y = yval;
return self;


-(float)calculateDistance: (Point *)other
return sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));


@end

int main(int argc, char **argv)
Point *point1 = [[Point alloc] init];
Point *point2 = [[Point alloc] initWithX: 1.5 AndY: 1.5];

printf("Distance is %f.n", [point1 calculateDistance: point2]);

[point1 dealloc];
[point2 dealloc];
return EXIT_SUCCESS;








objective-c windows






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 hours ago









Jamal

30.5k11121227




30.5k11121227










asked 3 hours ago









dylanweberdylanweber

19410




19410











  • $begingroup$
    where is the [super init]?
    $endgroup$
    – E.Coms
    2 hours ago










  • $begingroup$
    @E.Coms The base class Object only has the variable isa and the methods class and isEqual: so calling [super init] causes a seg. fault.
    $endgroup$
    – dylanweber
    2 hours ago










  • $begingroup$
    I use Xcode and not familiar with Object. I use NSObject and found it runs well at least in grammar. Without super. it just looks missing Root Object.
    $endgroup$
    – E.Coms
    2 hours ago











  • $begingroup$
    @E.Coms NSObject is a piece of Foundation.h which is written by Apple. Finding a class that does something similar would require writing my own or using a framework like GNUStep, both of which are overkill for my uses.
    $endgroup$
    – dylanweber
    2 hours ago










  • $begingroup$
    how about subclass of Point, will you still miss super?
    $endgroup$
    – E.Coms
    2 hours ago

















  • $begingroup$
    where is the [super init]?
    $endgroup$
    – E.Coms
    2 hours ago










  • $begingroup$
    @E.Coms The base class Object only has the variable isa and the methods class and isEqual: so calling [super init] causes a seg. fault.
    $endgroup$
    – dylanweber
    2 hours ago










  • $begingroup$
    I use Xcode and not familiar with Object. I use NSObject and found it runs well at least in grammar. Without super. it just looks missing Root Object.
    $endgroup$
    – E.Coms
    2 hours ago











  • $begingroup$
    @E.Coms NSObject is a piece of Foundation.h which is written by Apple. Finding a class that does something similar would require writing my own or using a framework like GNUStep, both of which are overkill for my uses.
    $endgroup$
    – dylanweber
    2 hours ago










  • $begingroup$
    how about subclass of Point, will you still miss super?
    $endgroup$
    – E.Coms
    2 hours ago
















$begingroup$
where is the [super init]?
$endgroup$
– E.Coms
2 hours ago




$begingroup$
where is the [super init]?
$endgroup$
– E.Coms
2 hours ago












$begingroup$
@E.Coms The base class Object only has the variable isa and the methods class and isEqual: so calling [super init] causes a seg. fault.
$endgroup$
– dylanweber
2 hours ago




$begingroup$
@E.Coms The base class Object only has the variable isa and the methods class and isEqual: so calling [super init] causes a seg. fault.
$endgroup$
– dylanweber
2 hours ago












$begingroup$
I use Xcode and not familiar with Object. I use NSObject and found it runs well at least in grammar. Without super. it just looks missing Root Object.
$endgroup$
– E.Coms
2 hours ago





$begingroup$
I use Xcode and not familiar with Object. I use NSObject and found it runs well at least in grammar. Without super. it just looks missing Root Object.
$endgroup$
– E.Coms
2 hours ago













$begingroup$
@E.Coms NSObject is a piece of Foundation.h which is written by Apple. Finding a class that does something similar would require writing my own or using a framework like GNUStep, both of which are overkill for my uses.
$endgroup$
– dylanweber
2 hours ago




$begingroup$
@E.Coms NSObject is a piece of Foundation.h which is written by Apple. Finding a class that does something similar would require writing my own or using a framework like GNUStep, both of which are overkill for my uses.
$endgroup$
– dylanweber
2 hours ago












$begingroup$
how about subclass of Point, will you still miss super?
$endgroup$
– E.Coms
2 hours ago





$begingroup$
how about subclass of Point, will you still miss super?
$endgroup$
– E.Coms
2 hours ago











1 Answer
1






active

oldest

votes


















2












$begingroup$

It's an interesting idea to write Windows code in Objective-C. If you were using NeXTStep frameworks (or GNUStep) it would make a little more sense. I don't understand your desire to avoid frameworks, which tend to be force multipliers saving you time and effort. (And of course, you are using OpenGL and GLFW, so this seems like an arbitrary choice.) Regardless, given those constraints, here are my thoughts.



Language



In my opinion Objective-C is the wrong choice for this particular project. I say that as someone who makes a living programming largely in Objective-C. The problem, as I see it, is that you lose 2 important things that you would get from other languages:



  1. The ability to use objects or structs for doing your work and passing them directly to OpenGL/GLFW.

  2. The ability to use operator overloading.

OpenGL expects to receive geometry as an array of vertex attributes (or several different arrays – one for each attribute). That's going to be impossible using the class as you've written it. Each Objective-C object is its own entity on the heap. If you have an array of them, it's really just an array of pointers to the objects, which may or may not be contiguous in memory. You won't be able to just call glVertexAttribPointer() or other similar functions and pass a pointer to the array since the array will just be an array of other pointers. In C you'd have an array of Point structs either on the stack or the heap and could just pass the address of the first element to the above function. Likewise with something like a C++ std::vector<Point> you'd be able to pass the address of the first element (assuming Point had no v-table). In addition to making it harder to send the data to the GPU, it also makes processing the data on the CPU slower because you lose cache coherency when the data isn't contiguous.



You'll also want to do math on your Point objects. While you can write methods on your Objective-C class to add, subtract, etc., it's not as natural as using a language that allows you to overload operators. In particular, C++ and Swift both allow this and it makes writing graphics code feel much more natural.



Class



This class is rather thin. It doesn't do very much that's useful. What it does do, it appears to do correctly. It might be useful to swap the sqrt() call with a call to hypot(x,y) instead.



At a minimum, if you're doing 2D graphics, you'll probably want to add the following methods:



- (void)add:(Point*)p;
- (void)subtract:(Point*)p;
- (float)dotProduct:(Point*)p;
- (void)normalize;
- (void)multiplyScalar:(float)s;
- (void)multiplyVector:(Point*)p;
- (void)divideScalar:(float)s;
- (void)divideVector:(Point*)p;


And eventually, you'll probably want a Matrix class for things like scaling and rotation operations.






share|improve this answer









$endgroup$












  • $begingroup$
    Thank you for the comments, but perhaps I didn't make my intentions completely clear. I was really just using the Point example to demonstrate a functioning, compiling class more than something I would use to interact directly with OpenGL. If I were storing vertices, I would probably make a Point_3D struct with a float x, y, z and then perhaps implement it in an array as an instance variable of a larger object class (along with things like textures and shaders).
    $endgroup$
    – dylanweber
    2 hours ago











Your Answer





StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");

StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216611%2fpoint-distance-program-written-without-a-framework%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2












$begingroup$

It's an interesting idea to write Windows code in Objective-C. If you were using NeXTStep frameworks (or GNUStep) it would make a little more sense. I don't understand your desire to avoid frameworks, which tend to be force multipliers saving you time and effort. (And of course, you are using OpenGL and GLFW, so this seems like an arbitrary choice.) Regardless, given those constraints, here are my thoughts.



Language



In my opinion Objective-C is the wrong choice for this particular project. I say that as someone who makes a living programming largely in Objective-C. The problem, as I see it, is that you lose 2 important things that you would get from other languages:



  1. The ability to use objects or structs for doing your work and passing them directly to OpenGL/GLFW.

  2. The ability to use operator overloading.

OpenGL expects to receive geometry as an array of vertex attributes (or several different arrays – one for each attribute). That's going to be impossible using the class as you've written it. Each Objective-C object is its own entity on the heap. If you have an array of them, it's really just an array of pointers to the objects, which may or may not be contiguous in memory. You won't be able to just call glVertexAttribPointer() or other similar functions and pass a pointer to the array since the array will just be an array of other pointers. In C you'd have an array of Point structs either on the stack or the heap and could just pass the address of the first element to the above function. Likewise with something like a C++ std::vector<Point> you'd be able to pass the address of the first element (assuming Point had no v-table). In addition to making it harder to send the data to the GPU, it also makes processing the data on the CPU slower because you lose cache coherency when the data isn't contiguous.



You'll also want to do math on your Point objects. While you can write methods on your Objective-C class to add, subtract, etc., it's not as natural as using a language that allows you to overload operators. In particular, C++ and Swift both allow this and it makes writing graphics code feel much more natural.



Class



This class is rather thin. It doesn't do very much that's useful. What it does do, it appears to do correctly. It might be useful to swap the sqrt() call with a call to hypot(x,y) instead.



At a minimum, if you're doing 2D graphics, you'll probably want to add the following methods:



- (void)add:(Point*)p;
- (void)subtract:(Point*)p;
- (float)dotProduct:(Point*)p;
- (void)normalize;
- (void)multiplyScalar:(float)s;
- (void)multiplyVector:(Point*)p;
- (void)divideScalar:(float)s;
- (void)divideVector:(Point*)p;


And eventually, you'll probably want a Matrix class for things like scaling and rotation operations.






share|improve this answer









$endgroup$












  • $begingroup$
    Thank you for the comments, but perhaps I didn't make my intentions completely clear. I was really just using the Point example to demonstrate a functioning, compiling class more than something I would use to interact directly with OpenGL. If I were storing vertices, I would probably make a Point_3D struct with a float x, y, z and then perhaps implement it in an array as an instance variable of a larger object class (along with things like textures and shaders).
    $endgroup$
    – dylanweber
    2 hours ago















2












$begingroup$

It's an interesting idea to write Windows code in Objective-C. If you were using NeXTStep frameworks (or GNUStep) it would make a little more sense. I don't understand your desire to avoid frameworks, which tend to be force multipliers saving you time and effort. (And of course, you are using OpenGL and GLFW, so this seems like an arbitrary choice.) Regardless, given those constraints, here are my thoughts.



Language



In my opinion Objective-C is the wrong choice for this particular project. I say that as someone who makes a living programming largely in Objective-C. The problem, as I see it, is that you lose 2 important things that you would get from other languages:



  1. The ability to use objects or structs for doing your work and passing them directly to OpenGL/GLFW.

  2. The ability to use operator overloading.

OpenGL expects to receive geometry as an array of vertex attributes (or several different arrays – one for each attribute). That's going to be impossible using the class as you've written it. Each Objective-C object is its own entity on the heap. If you have an array of them, it's really just an array of pointers to the objects, which may or may not be contiguous in memory. You won't be able to just call glVertexAttribPointer() or other similar functions and pass a pointer to the array since the array will just be an array of other pointers. In C you'd have an array of Point structs either on the stack or the heap and could just pass the address of the first element to the above function. Likewise with something like a C++ std::vector<Point> you'd be able to pass the address of the first element (assuming Point had no v-table). In addition to making it harder to send the data to the GPU, it also makes processing the data on the CPU slower because you lose cache coherency when the data isn't contiguous.



You'll also want to do math on your Point objects. While you can write methods on your Objective-C class to add, subtract, etc., it's not as natural as using a language that allows you to overload operators. In particular, C++ and Swift both allow this and it makes writing graphics code feel much more natural.



Class



This class is rather thin. It doesn't do very much that's useful. What it does do, it appears to do correctly. It might be useful to swap the sqrt() call with a call to hypot(x,y) instead.



At a minimum, if you're doing 2D graphics, you'll probably want to add the following methods:



- (void)add:(Point*)p;
- (void)subtract:(Point*)p;
- (float)dotProduct:(Point*)p;
- (void)normalize;
- (void)multiplyScalar:(float)s;
- (void)multiplyVector:(Point*)p;
- (void)divideScalar:(float)s;
- (void)divideVector:(Point*)p;


And eventually, you'll probably want a Matrix class for things like scaling and rotation operations.






share|improve this answer









$endgroup$












  • $begingroup$
    Thank you for the comments, but perhaps I didn't make my intentions completely clear. I was really just using the Point example to demonstrate a functioning, compiling class more than something I would use to interact directly with OpenGL. If I were storing vertices, I would probably make a Point_3D struct with a float x, y, z and then perhaps implement it in an array as an instance variable of a larger object class (along with things like textures and shaders).
    $endgroup$
    – dylanweber
    2 hours ago













2












2








2





$begingroup$

It's an interesting idea to write Windows code in Objective-C. If you were using NeXTStep frameworks (or GNUStep) it would make a little more sense. I don't understand your desire to avoid frameworks, which tend to be force multipliers saving you time and effort. (And of course, you are using OpenGL and GLFW, so this seems like an arbitrary choice.) Regardless, given those constraints, here are my thoughts.



Language



In my opinion Objective-C is the wrong choice for this particular project. I say that as someone who makes a living programming largely in Objective-C. The problem, as I see it, is that you lose 2 important things that you would get from other languages:



  1. The ability to use objects or structs for doing your work and passing them directly to OpenGL/GLFW.

  2. The ability to use operator overloading.

OpenGL expects to receive geometry as an array of vertex attributes (or several different arrays – one for each attribute). That's going to be impossible using the class as you've written it. Each Objective-C object is its own entity on the heap. If you have an array of them, it's really just an array of pointers to the objects, which may or may not be contiguous in memory. You won't be able to just call glVertexAttribPointer() or other similar functions and pass a pointer to the array since the array will just be an array of other pointers. In C you'd have an array of Point structs either on the stack or the heap and could just pass the address of the first element to the above function. Likewise with something like a C++ std::vector<Point> you'd be able to pass the address of the first element (assuming Point had no v-table). In addition to making it harder to send the data to the GPU, it also makes processing the data on the CPU slower because you lose cache coherency when the data isn't contiguous.



You'll also want to do math on your Point objects. While you can write methods on your Objective-C class to add, subtract, etc., it's not as natural as using a language that allows you to overload operators. In particular, C++ and Swift both allow this and it makes writing graphics code feel much more natural.



Class



This class is rather thin. It doesn't do very much that's useful. What it does do, it appears to do correctly. It might be useful to swap the sqrt() call with a call to hypot(x,y) instead.



At a minimum, if you're doing 2D graphics, you'll probably want to add the following methods:



- (void)add:(Point*)p;
- (void)subtract:(Point*)p;
- (float)dotProduct:(Point*)p;
- (void)normalize;
- (void)multiplyScalar:(float)s;
- (void)multiplyVector:(Point*)p;
- (void)divideScalar:(float)s;
- (void)divideVector:(Point*)p;


And eventually, you'll probably want a Matrix class for things like scaling and rotation operations.






share|improve this answer









$endgroup$



It's an interesting idea to write Windows code in Objective-C. If you were using NeXTStep frameworks (or GNUStep) it would make a little more sense. I don't understand your desire to avoid frameworks, which tend to be force multipliers saving you time and effort. (And of course, you are using OpenGL and GLFW, so this seems like an arbitrary choice.) Regardless, given those constraints, here are my thoughts.



Language



In my opinion Objective-C is the wrong choice for this particular project. I say that as someone who makes a living programming largely in Objective-C. The problem, as I see it, is that you lose 2 important things that you would get from other languages:



  1. The ability to use objects or structs for doing your work and passing them directly to OpenGL/GLFW.

  2. The ability to use operator overloading.

OpenGL expects to receive geometry as an array of vertex attributes (or several different arrays – one for each attribute). That's going to be impossible using the class as you've written it. Each Objective-C object is its own entity on the heap. If you have an array of them, it's really just an array of pointers to the objects, which may or may not be contiguous in memory. You won't be able to just call glVertexAttribPointer() or other similar functions and pass a pointer to the array since the array will just be an array of other pointers. In C you'd have an array of Point structs either on the stack or the heap and could just pass the address of the first element to the above function. Likewise with something like a C++ std::vector<Point> you'd be able to pass the address of the first element (assuming Point had no v-table). In addition to making it harder to send the data to the GPU, it also makes processing the data on the CPU slower because you lose cache coherency when the data isn't contiguous.



You'll also want to do math on your Point objects. While you can write methods on your Objective-C class to add, subtract, etc., it's not as natural as using a language that allows you to overload operators. In particular, C++ and Swift both allow this and it makes writing graphics code feel much more natural.



Class



This class is rather thin. It doesn't do very much that's useful. What it does do, it appears to do correctly. It might be useful to swap the sqrt() call with a call to hypot(x,y) instead.



At a minimum, if you're doing 2D graphics, you'll probably want to add the following methods:



- (void)add:(Point*)p;
- (void)subtract:(Point*)p;
- (float)dotProduct:(Point*)p;
- (void)normalize;
- (void)multiplyScalar:(float)s;
- (void)multiplyVector:(Point*)p;
- (void)divideScalar:(float)s;
- (void)divideVector:(Point*)p;


And eventually, you'll probably want a Matrix class for things like scaling and rotation operations.







share|improve this answer












share|improve this answer



share|improve this answer










answered 2 hours ago









user1118321user1118321

10.9k11145




10.9k11145











  • $begingroup$
    Thank you for the comments, but perhaps I didn't make my intentions completely clear. I was really just using the Point example to demonstrate a functioning, compiling class more than something I would use to interact directly with OpenGL. If I were storing vertices, I would probably make a Point_3D struct with a float x, y, z and then perhaps implement it in an array as an instance variable of a larger object class (along with things like textures and shaders).
    $endgroup$
    – dylanweber
    2 hours ago
















  • $begingroup$
    Thank you for the comments, but perhaps I didn't make my intentions completely clear. I was really just using the Point example to demonstrate a functioning, compiling class more than something I would use to interact directly with OpenGL. If I were storing vertices, I would probably make a Point_3D struct with a float x, y, z and then perhaps implement it in an array as an instance variable of a larger object class (along with things like textures and shaders).
    $endgroup$
    – dylanweber
    2 hours ago















$begingroup$
Thank you for the comments, but perhaps I didn't make my intentions completely clear. I was really just using the Point example to demonstrate a functioning, compiling class more than something I would use to interact directly with OpenGL. If I were storing vertices, I would probably make a Point_3D struct with a float x, y, z and then perhaps implement it in an array as an instance variable of a larger object class (along with things like textures and shaders).
$endgroup$
– dylanweber
2 hours ago




$begingroup$
Thank you for the comments, but perhaps I didn't make my intentions completely clear. I was really just using the Point example to demonstrate a functioning, compiling class more than something I would use to interact directly with OpenGL. If I were storing vertices, I would probably make a Point_3D struct with a float x, y, z and then perhaps implement it in an array as an instance variable of a larger object class (along with things like textures and shaders).
$endgroup$
– dylanweber
2 hours ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216611%2fpoint-distance-program-written-without-a-framework%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

На ростанях Змест Гісторыя напісання | Месца дзеяння | Час дзеяння | Назва | Праблематыка трылогіі | Аўтабіяграфічнасць | Трылогія ў тэатры і кіно | Пераклады | У культуры | Зноскі Літаратура | Спасылкі | НавігацыяДагледжаная версіяправерана1 зменаДагледжаная версіяправерана1 зменаАкадэмік МІЦКЕВІЧ Канстанцін Міхайлавіч (Якуб Колас) Прадмова М. І. Мушынскага, доктара філалагічных навук, члена-карэспандэнта Нацыянальнай акадэміі навук Рэспублікі Беларусь, прафесараНашаніўцы ў трылогіі Якуба Коласа «На ростанях»: вобразы і прататыпы125 лет Янке МавруКнижно-документальная выставка к 125-летию со дня рождения Якуба Коласа (1882—1956)Колас Якуб. Новая зямля (паэма), На ростанях (трылогія). Сулкоўскі Уладзімір. Радзіма Якуба Коласа (серыял жывапісных палотнаў)Вокладка кнігіІлюстрацыя М. С. БасалыгіНа ростаняхАўдыёверсія трылогііВ. Жолтак У Люсiнскай школе 1959

Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп