Search Results

Search found 2566 results on 103 pages for 'struct'.

Page 26/103 | < Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >

  • Writing a printList method for a Scheme interpreter in C

    - by Rehan Rasool
    I am new to C and working on making an interpreter for Scheme. I am trying to get a suitable printList method to traverse through the structure. The program takes in an input like: (a (b c)) and internally represent it as: [""][ ][ ]--> [""][ ][/] | | ["A"][/][/] [""][ ][ ]--> [""][ ][/] | | ["B"][/][/] ["C"][/][/] Right now, I just want the program to take in the input, make the appropriate cell structure internally and print out the cell structure, thereby getting (a (b c)) at the end. Here is my struct: typedef struct conscell *List; struct conscell { char symbol; struct conscell *first; struct conscell *rest; }; void printList(char token[20]){ List current = S_Expression(token, 0); printf("("); printf("First Value? %c \n", current->first->symbol); printf("Second value? %c \n", current->rest->first->first->symbol); printf("Third value? %c \n", current->rest->first->rest->first->symbol); printf(")"); } In the main method, I get the first token and call: printList(token); I tested the values again for the sublists and I think it is working. However, I will need a method to traverse through the whole structure. Please look at my printList code again. The print calls are what I have to type, to manually get the (a (b c)) list values. So I get this output: First value? a First value? b First value? c It is what I want, but I want a method to do it using a loop, no matter how complex the structure is, also adding brackets where appropriate, so in the end, I should get: (a (b c)) which is the same as the input. Can anyone please help me with this?

    Read the article

  • C++, generic programming and virtual functions. How do I get what I want?

    - by carleeto
    This is what I would like to do using templates: struct op1 { virtual void Method1() = 0; } ... struct opN { virtual void MethodN() = 0; } struct test : op1, op2, op3, op4 { virtual void Method1(){/*do work1*/}; virtual void Method2(){/*do work2*/}; virtual void Method3(){/*do work3*/}; virtual void Method4(){/*do work4*/}; } I would like to have a class that simply derives from a template class that provides these method declarations while at the same time making them virtual. This is what I've managed to come up with: #include <iostream> template< size_t N > struct ops : ops< N - 1 > { protected: virtual void DoStuff(){ std::cout<<N<<std::endl; }; public: template< size_t i > void Method() { if( i < N ) ops<i>::DoStuff(); } //leaving out compile time asserts for brevity } struct test : ops<6> { }; int main( int argc, char ** argv ) { test obj; obj.Method<3>(); //prints 3 return 0; } However, as you've probably guessed, I am unable to override any of the 6 methods I have inherited. I'm obviously missing something here. What is my error? No, this isn't homework. This is curiosity.

    Read the article

  • Split text files Accross threads

    - by Kevin
    The problem: I have a few text files (10) with numbers in them on every line. I need to have them split across some threads I create using the pthread library. these threads that are created (worker threads) are to find the largest prime number that gets sent to them (and over all the largest prime from all of the text files). My current thoughts on solutions: I am thinking myself to have two arrays and all of the text files in one array and the other array will contain a binary file that I can read say 1000 lines and send the pointer to the index of that binary file in a struct that contains the id, file pointer, and file position and let it crank through that. a little bit of what I am talking about pthread_create(&threads[index],NULL,calc_sqrt,(void *)threadFields[index]);//Pass struct to each worker Struct: typedef struct threadFields{ int *id, *position; FILE *Fin; }tField; If anyone has any insight or a better solution it would be greatly appreciated Thanks

    Read the article

  • Nullable type conversion in C#?

    - by dinesh
    Hi can we assign null value to struct type of variable? struct MyStruct { } MyStruct var = null; is this is possible in C# .net? if not ? then how C# is allowing Nullable < T struct type of variable can be assigned as null?

    Read the article

  • C++ Template const char array to int

    - by Levi Schuck
    So, I'm wishing to be able to have a static const compile time struct that holds some value based on a string by using templates. I only desire up to four characters. I know that the type of 'abcd' is int, and so is 'ab','abc', and although 'a' is of type char, it works out for a template<int v> struct What I wish to do is take sizes of 2,3,4,5 of some const char, "abcd" and have the same functionality as if they used 'abcd'. Note that I do not mean 1,2,3, or 4 because I expect the null terminator. cout << typeid("abcd").name() << endl; tells me that the type for this hard coded string is char const [5], which includes the null terminator on the end. I understand that I will need to twiddle the values as characters, so they are represented as an integer. I cannot use constexpr since VS10 does not support it (VS11 doesn't either..) So, for example with somewhere this template defined, and later the last line template <int v> struct something { static const int value = v; }; //Eventually in some method cout << typeid(something<'abcd'>::value).name() << endl; works just fine. I've tried template<char v[5]> struct something2 { static const int value = v[0]; } template<char const v[5]> struct something2 { static const int value = v[0]; } template<const char v[5]> struct something2 { static const int value = v[0]; } All of them build individually, though when I throw in my test, cout << typeid(something2<"abcd">::value).name() << endl; I get 'something2' : invalid expression as a template argument for 'v' 'something2' : use of class template requires template argument list Is this not feasible or am I misunderstanding something?

    Read the article

  • How to filter and intercept Linux packets by using net_dev_add() API?

    - by Khajavi
    I'm writing ethernet network driver for linux. I want to receive packets, edit and resend them. I know how to edit the packet in packet_interceptor function, but how can I drop incoming packets in this function?? #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/ip.h> #include <net/sock.h> struct packet_type my_proto; int packet_interceptor(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { // I dont want certain packets go to upper in net_devices for further processing. // How can I drop sk_buff here?! return 0; } static int hello_init( void ) { printk(KERN_INFO "Hello, world!\n"); my_proto.type = htons(ETH_P_ALL); my_proto.dev = NULL; my_proto.func = packet_interceptor; dev_add_pack(&my_proto); return 0; } static void hello_exit(void) { dev_remove_pack(&my_proto); printk(KERN_INFO "Bye, world\n"); } module_init(hello_init); module_exit(hello_exit);

    Read the article

  • How to default-initialize local variables of built-in types in C++?

    - by sharptooth
    How do I default-initialize a local variable of primitive type in C++? For example if a have a typedef: typedef unsigned char boolean;//that's Microsoft RPC runtime typedef I'd like to change the following line: boolean variable = 0; //initialize to some value to ensure reproduceable behavior retrieveValue( &variable ); // do actual job into something that would automagically default-initialize the variable - I don't need to assign a specific value to it, but instead I only need it to be intialized to the same value each time the program runs - the same stuff as with a constructor initializer list where I can have: struct Struct { int Value; Struct() : Value() {} }; and the Struct::Value will be default-initialized to the same value every time an instance is cinstructed, but I never write the actual value in the code. How can I get the same behavior for local variables?

    Read the article

  • Sockets: Transport endpoint is not connected on send

    - by TheoretiCAL
    I'm trying to learn socket programming from http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html and am attempting to build a SOCK_STREAM client/server. My client: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #define SERVERPORT "4951" // the port users will be connecting to int main(int argc, char *argv[]) { int sockfd; struct addrinfo hints, *servinfo, *p; int rv; int numbytes; if (argc != 3) { fprintf(stderr,"usage: talker hostname message\n"); exit(1); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(argv[1], SERVERPORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and make a socket for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("talker: socket"); continue; if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } } break; } if (p == NULL) { fprintf(stderr, "talker: failed to bind socket\n"); return 2; } if ((numbytes = send(sockfd, argv[2], strlen(argv[2]), 0) == -1)) { perror("talker: send"); exit(1); } freeaddrinfo(servinfo); printf("talker: sent %d bytes to %s\n", numbytes, argv[1]); close(sockfd); return 0; } Server: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #define MYPORT "4951" // the port users will be connecting to #define MAXBUFLEN 100 static int backlog = 10; // get sockaddr, IPv4 or IPv6: void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } int main(void) { int sockfd; struct addrinfo hints, *servinfo, *p; int rv; int numbytes; int new_fd; socklen_t addr_size; struct sockaddr_storage their_addr; char buf[MAXBUFLEN]; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4 hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("listener: socket"); continue; } int yes=1; // lose the pesky "Address already in use" error message if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("listener: bind"); continue; } if (listen(sockfd,backlog) == -1){ close(sockfd); perror("listener:listen"); continue; } break; } if (p == NULL) { fprintf(stderr, "listener: failed to bind socket\n"); return 2; } freeaddrinfo(servinfo); printf("listener: waiting to recv..\n"); while(1){ addr_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size))==-1){ perror("accept"); exit(1); } if ((numbytes = recv(new_fd, buf, MAXBUFLEN-1 , 0) == -1)) { perror("recv"); exit(1); } printf("listener: got packet from %s\n", inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s)); printf("listener: packet is %d bytes long\n", numbytes); buf[numbytes] = '\0'; printf("listener: packet contains \"%s\"\n", buf); close(sockfd); } return 0; } Upon executing the client, I get " send: Transport endpoint is not connected" and I'm not sure where I went wrong. Thanks.

    Read the article

  • c# marshaling dynamic-length string

    - by mitsky
    i have a struct with dynamic length [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PktAck { public Int32 code; [MarshalAs(UnmanagedType.LPStr)] public string text; } when i'm converting bytes[] to struct by: GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); stru = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); i have a error, because size of struct less than size of bytes[] and "string text" is pointer to string... how can i use dynamic strings? or i can use only this: [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]

    Read the article

  • How to determine IP used by client connecting to INADDR_ANY listener socket in C

    - by codebox_rob
    I have a network server application written in C, the listener is bound using INADDR_ANY so it can accept connections via any of the IP addresses of the host on which it is installed. I need to determine which of the server's IP addresses the client used when establishing its connection - actually I just need to know whether they connected via the loopback address 127.0.0.1 or not. Partial code sample as follows (I can post the whole thing if it helps): static struct sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_port = htons(port); bind(listener, (struct sockaddr *) &serverAddress, sizeof(serverAddress)); listen(listener, CONNECTION_BACKLOG); SOCKET socketfd; static struct sockaddr_in clientAddress; ... socketfd = accept(listener, (struct sockaddr *) &clientAddress, &length);

    Read the article

  • Insert a transformed integer_sequence into a variadic template argument?

    - by coderforlife
    How do you insert a transformed integer_sequence (or similar since I am targeting C++11) into a variadic template argument? For example I have a class that represents a set of bit-wise flags (shown below). It is made using a nested-class because you cannot have two variadic template arguments for the same class. It would be used like typedef Flags<unsigned char, FLAG_A, FLAG_B, FLAG_C>::WithValues<0x01, 0x02, 0x04> MyFlags. Typically, they will be used with the values that are powers of two (although not always, in some cases certain combinations would be made, for example one could imagine a set of flags like Read=0x1, Write=0x2, and ReadWrite=0x3=0x1|0x2). I would like to provide a way to do typedef Flags<unsigned char, FLAG_A, FLAG_B, FLAG_C>::WithDefaultValues MyFlags. template<class _B, template <class,class,_B> class... _Fs> class Flags { public: template<_B... _Vs> class WithValues : public _Fs<_B, Flags<_B,_Fs...>::WithValues<_Vs...>, _Vs>... { // ... }; }; I have tried the following without success (placed inside the Flags class, outside the WithValues class): private: struct _F { // dummy class which can be given to a flag-name template template <_B _V> inline constexpr explicit _F(std::integral_constant<_B, _V>) { } }; // we count the flags, but only in a dummy way static constexpr unsigned _count = sizeof...(_Fs<_B, _F, 1>); static inline constexpr _B pow2(unsigned exp, _B base = 2, _B result = 1) { return exp < 1 ? result : pow2(exp/2, base*base, (exp % 2) ? result*base : result); } template <_B... _Is> struct indices { using next = indices<_Is..., sizeof...(_Is)>; using WithPow2Values = WithValues<pow2(_Is)...>; }; template <unsigned N> struct build_indices { using type = typename build_indices<N-1>::type::next; }; template <> struct build_indices<0> { using type = indices<>; }; //// Another attempt //template < _B... _Is> struct indices { // using WithPow2Values = WithValues<pow2(_Is)...>; //}; //template <unsigned N, _B... _Is> struct build_indices // : build_indices<N-1, N-1, _Is...> { }; //template < _B... _Is> struct build_indices<0, _Is...> // : indices<_Is...> { }; public: using WithDefaultValues = typename build_indices<_count>::type::WithPow2Values; Of course, I would be willing to have any other alternatives to the whole situation (supporting both flag names and values in the same template set, etc). I have included a "working" example at ideone: http://ideone.com/NYtUrg - by "working" I mean compiles fine without using default values but fails with default values (there is a #define to switch between them). Thanks!

    Read the article

  • C++ Bubble Sorting for Singly Linked List [closed]

    - by user1119900
    I have implemented a simple word frequency program in C++. Everything but the sorting is OK, but the sorting in the following script does not work. Any emergent help will be great.. #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <iostream> #include <fstream> #include <cstdio> using namespace std; #include "ProcessLines.h" struct WordCounter { char *word; int word_count; struct WordCounter *pNext; // pointer to the next word counter in the list }; /* pointer to first word counter in the list */ struct WordCounter *pStart = NULL; /* pointer to a word counter */ struct WordCounter *pCounter = NULL; /* Print statistics and words */ void PrintWords() { ... pCounter = pStart; bubbleSort(pCounter); ... } //end-PrintWords void bubbleSort(struct WordCounter *ptr) { WordCounter *temp = ptr; WordCounter *curr; for (bool didSwap = true; didSwap;) { didSwap = false; for (curr = ptr; curr->pNext != NULL; curr = curr->pNext) { if (curr->word > curr->pNext->word) { temp->word = curr->word; curr->word = curr->pNext->word; curr->pNext->word = temp->word; didSwap = true; } } } }

    Read the article

  • unused memory using 32 bit integer in C

    - by endmade
    I have the folowing struct of integers (32 bit environment): struct rgb { int r; int g; int b; }; Am I correct in saying that, since rgb component values (0-255) only require 8-bits(1 byte) to be represented, I am only using 1 byte of memory and leaving 3 bytes unused for each component? Also, if I instead did the following: struct rgb{ unsigned int r:8; unsigned int g:8; unsigned int b:8; }; Assuming that what I said above is correct, would using this new struct reduce the number of unused bytes to 1?

    Read the article

  • C# how to sort a list without implementing IComparable manually?

    - by JL
    I have a fairly complex scenario and I need to ensure items I have in a list are sorted. Firstly the items in the list are based on a struct that contains a sub struct. For example: public struct topLevelItem { public custStruct subLevelItem; } public struct custStruct { public string DeliveryTime; } Now I have a list comprised of topLevelItems for example: var items = new List<topLevelItem>(); I need a way to sort on the DeliveryTime ASC. What also adds to the complexity is that the DeliveryTime field is a string. Since these structs are part of a reusable API, I can't modify that field to a DateTime, neither can I implement IComparable in the topLevelItem class. Any ideas how this can be done? Thank you

    Read the article

  • C++ dynamic type construction and detection

    - by KneLL
    There was an interesting problem in C++, but it concerns more likely architecture. There are many (10, 20, 40, etc) classes that describe some characteristics (mix-in classes), for exmaple: struct Base { virtual ~Base() {} }; struct A : virtual public Base { int size; }; struct B : virtual public Base { float x, y; }; struct C : virtual public Base { bool some_bool_state; }; struct D : virtual public Base { string str; } // .... Primary module declares and exports a function (for simplicity just function declarations without classes): // .h file void operate(Base *pBase); // .cpp file void operate(Base *pBase) { // .... } Any other module can has a code like this: #include "mixins.h" #include "primary.h" class obj1_t : public A, public C, public D {}; class obj2_t : public B, public D {}; // ... void Pass() { obj1_t obj1; obj2_t obj2; operate(&obj1); operate(&obj2); } The question is how to know what the real type of given object in operate() without dynamic_cast and any type information in classes (constants, etc)? Function operate() is used with big array of objects in small time periods and dynamic_cast is too slow for it. And I don't want to include constants (enum obj_type { ... }) because this is not OOP-way. // module operate.cpp void some_operate(Base *pBase) { processA(pBase); processB(pBase); } void processA(A *pA) { } void processB(B *pB) { } I cannot directly pass a pBase to these functions. And it's impossible to have all possible combinations of classes, because I can add new classes just by including new .h files. As one of solutions that comed to mind, in editor application I can use a composite container: struct CompositeObject { vector<Base *pBase> parts; }; But editor does not need a time optimization and can use dynamic_cast for parts to determine the exact type. In operate() I cannot use this solution. So, is it possible to not use a dynamic_cast and type information to solve this problem? Or maybe I should use another architecture?

    Read the article

  • Why is this simple hello world code segfaulting?

    - by socks
    Excuse the beginner level of this question. I have the following simple code, but it does not seem to run. It gets a segmentation fault. If I replace the pointer with a simple call to the actual variable, it runs fine... I'm not sure why. struct node { int x; struct node *left; struct node *right; }; int main() { struct node *root; root->x = 42; printf("Hello world. %d", root->x); getchar(); return 0; } What is wrong with this code?

    Read the article

  • Doubt regarding usage of array as a pointer in C

    - by Som
    For eg. I have an array of structs 'a' as below: struct mystruct{ int b int num; }; struct bigger_struct { struct my_struct a[10]; } struct bigger_struct *some_var; i know that the name of an array when used as a value implicitly refers to the address of the first element of the array.(Which is how the array subscript operator works at-least) Can i know do the other way around i.e if i do: some_var->a->b, it should be equivalent to some_var->a[0]->b, am i right? I have tested this and it seems to work , but is this semantically 100% correct?

    Read the article

  • Writting a getter for a pointer to a function .

    - by nomemory
    I have the following problem: "list.c" struct nmlist_element_s { void *data; struct nmlist_element_s *next; }; struct nmlist_s { nmlist_element *head; nmlist_element *tail; unsigned int size; void (*destructor)(void *data); int (*match)(const void *e1, const void *e2); }; /*** Other code ***/ What will be the signature for a function that returns 'destructor' ?

    Read the article

  • Hi, i have a c programming doubt? I want to know the difference between the two and where one is use

    - by aks
    Hi, i have a c programming doubt? I want to know the difference between the two and where one is useful over other? suppose i have a struct called employee as below: struct emp{ char first_name[10]; char last_name[10]; char key[10]; }; Now, i want to store the table of employee records, then which method should i use: struct emp e1[100]; // Or struct emp * e1[100]; I know the two are not same but would like to know a use case where second declaration would be of interest and more advantageous to use? Can someone clarify?

    Read the article

  • 'table' undeclared (first use this in a function)

    - by user2318083
    So I'm not sure why this isn't working, I'm creating a new table and setting it to the variable 'table' Is there something I'm doing wrong? This is the error I get when trying to run it: src/simpleshell.c:19:3: error: ‘table’ undeclared (first use in this function) src/simpleshell.c:19:3: note: each undeclared identifier is reported only once for each function it appears in My code is as follows: #include "parser.h" #include "hash_table.h" #include "variables.h" #include "shell.h" #include <stdio.h> int main(void) { char input[MAXINPUTLINE]; table = Table_create(); signal_c_init(); printf("\nhlsh$ "); while(fgets(input, sizeof(input), stdin)){ stripcrlf(input); parse(input); printf("\nhlsh$ "); } Table_free(table); return 0; } Then this is my create a table in the hash_table file: struct Table *Table_create(void){ struct Table *t; t = (struct Table*)calloc(1, sizeof(struct Table)); return t; } From the hash_table.c: #include "hash_table.h" #include "parser.h" #include "shell.h" #include "variables.h" #include <stdio.h> #include <sys/resource.h> #include <sys/wait.h> #include <sys/types.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pwd.h> #include <fcntl.h> #include <limits.h> #include <signal.h> struct Table *table; unsigned int hash(const char *x){ int i; unsigned int h = 0U; for (i=0; x[i]!='\0'; i++){ h = h * 65599 + (unsigned char)x[i]; } return h % 1024; }

    Read the article

  • Multiple render targets and pixel shader outputs terminology

    - by Rei Miyasaka
    I'm a little confused on the jargon: does Multiple Render Targets (MRT) refer to outputting from a pixel shader to multiple elements in a struct? That is, when one says "MRT is to write to multiple textures", are multiple elements interleaved in a single output texture, or do you specify multiple discrete output textures? By the way, from what I understand, at least for DX9, all the elements of this struct need to be of the same size. Does this restriction still apply to DX11?

    Read the article

  • Finding Z given X & Y coordinates on terrain?

    - by mrky
    I need to know what the most efficient way of finding Z given X & Y coordinates on terrain. My terrain is set up as a grid, each grid block consisting of two triangles, which may be flipped in any direction. I want to move game objects smoothly along the floor of the terrain without "stepping." I'm currently using the following method with unexpected results: double mapClass::getZ(double x, double y) { int vertexIndex = ((floor(y))*width*2)+((floor(x))*2); vec3ray ray = {glm::vec3(x, y, 2), glm::vec3(x, y, 0)}; vec3triangle tri1 = { glmFrom(vertices[vertexIndex].v1), glmFrom(vertices[vertexIndex].v2), glmFrom(vertices[vertexIndex].v3) }; vec3triangle tri2 = { glmFrom(vertices[vertexIndex+1].v1), glmFrom(vertices[vertexIndex+1].v2), glmFrom(vertices[vertexIndex+1].v3) }; glm::vec3 intersect; if (!intersectRayTriangle(tri1, ray, intersect)) { intersectRayTriangle(tri2, ray, intersect); } return intersect.z; } intersectRayTriangle() and glmFrom() are as follows: bool intersectRayTriangle(vec3triangle tri, vec3ray ray, glm::vec3 &worldIntersect) { glm::vec3 barycentricIntersect; if (glm::intersectLineTriangle(ray.origin, ray.direction, tri.p0, tri.p1, tri.p2, barycentricIntersect)) { // Convert barycentric to world coordinates double u, v, w; u = barycentricIntersect.x; v = barycentricIntersect.y; w = 1 - (u+v); worldIntersect.x = (u * tri.p0.x + v * tri.p1.x + w * tri.p2.x); worldIntersect.y = (u * tri.p0.y + v * tri.p1.y + w * tri.p2.y); worldIntersect.z = (u * tri.p0.z + v * tri.p1.z + w * tri.p2.z); return true; } else { return false; } } glm::vec3 glmFrom(s_point3f point) { return glm::vec3(point.x, point.y, point.z); } My convenience structures are defined as: struct s_point3f { GLfloat x, y, z; }; struct s_triangle3f { s_point3f v1, v2, v3; }; struct vec3ray { glm::vec3 origin, direction; }; struct vec3triangle { glm::vec3 p0, p1, p2; }; vertices is defined as: std::vector<s_triangle3f> vertices; Basically, I'm trying to get the intersect of a ray (which is positioned at the x, and y coordinates specified facing pointing downwards toward the terrain) and one of the two triangles on the grid. getZ() rarely returns anything but 0. Other times, the numbers it generates seem to be completely off. Am I taking the wrong approach? Can anyone see a problem with my code? Any help or critique is appreciated!

    Read the article

  • Handling bugs, quirks, or annoyances in vendor-supplied headers

    - by supercat
    If the header file supplied by a vendor of something with whom one's code must interact is deficient in some way, in what cases is it better to: Work around the header's deficiencies in the main code Copy the header file to the local project and fix it Fix the header file in the spot where it's stored as a vendor-supplied tool Fix the header file in the central spot, but also make a local copy and try to always have the two match Do something else As an example, the header file supplied by ST Micro for the STM320LF series contains the lines: typedef struct { __IO uint32_t MODER; __IO uint16_t OTYPER; uint16_t RESERVED0; .... __IO uint16_t BSRRL; /* BSRR register is split to 2 * 16-bit fields BSRRL */ __IO uint16_t BSRRH; /* BSRR register is split to 2 * 16-bit fields BSRRH */ .... } GPIO_TypeDef; In the hardware, and in the hardware documentation, BSRR is described as a single 32-bit register. About 98% of the time one wants to write to BSRR, one will only be interested in writing the upper half or the lower half; it is thus convenient to be able to use BSSRH and BSSRL as a means of writing half the register. On the other hand, there are occasions when it is necessary that the entire 32-bit register be written as a single atomic operation. The "optimal" way to write it (setting aside white-spacing issues) would be: typedef struct { __IO uint32_t MODER; __IO uint16_t OTYPER; uint16_t RESERVED0; .... union // Allow BSRR access as 32-bit register or two 16-bit registers { __IO uint32_t BSRR; // 32-bit BSSR register as a whole struct { __IO uint16_t BSRRL, BSRRH; };// Two 16-bit parts }; .... } GPIO_TypeDef; If the struct were defined that way, code could use BSRR when necessary to write all 32 bits, or BSRRH/BSRRL when writing 16 bits. Given that the header isn't that way, would better practice be to use the header as-is, but apply an icky typecast in the main code writing what would be idiomatically written as thePort->BSRR = 0x12345678; as *((uint32_t)&(thePort->BSSRH)) = 0x12345678;, or would be be better to use a patched header file? If the latter, where should the patched file me stored and how should it be managed?

    Read the article

< Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >