int main(int argc, char** argv) { sipua_t* sipua = NULL; sipua_uas_t* uas = NULL; module_catalog_t *mod_cata = NULL; /* phonebook loading test { sipua_load_user("heming", "heming", "hello", 5); exit(0); } */ clie_log (("main: modules in dir:'%s'\n", MOD_DIR)); mod_cata = catalog_new( "mediaformat" ); catalog_scan_modules ( mod_cata, OGMP_VERSION, MOD_DIR ); uas = client_new_uas(mod_cata, "eXosipua"); if(!uas) clie_log (("main: fail to create sipua server!\n")); if(uas && uas->init(uas, 5070, "IN", "IP4", NULL, NULL) >= UA_OK) { sipua = client_new("cursesui", uas, mod_cata, 64*1024); if(sipua) client_start(sipua); else clie_log (("main: fail to create sipua!\n")); } return 0; }
void muta_connect(libmuta_processing_callback f, void *priv) { struct sockaddr_storage addr_storage; struct sockaddr *addr = NULL; uint32_t addrlen = 0; memset(&addr_storage, 0, sizeof(addr_storage)); addr = (struct sockaddr *)&addr_storage; addrlen = sizeof(addr_storage); pomp_addr_parse(LIBMUTA_IMAGE_SOCKET, addr, &addrlen); s_app.ctx = pomp_ctx_new(client_event_cb, f); s_app.loop = pomp_ctx_get_loop(s_app.ctx); client_start(addr, addrlen); s_app.stop = 0; s_app.priv = priv; s_app.process = f; while (!s_app.stop) { pomp_loop_wait_and_process(s_app.loop, -1); } if (s_app.ctx != NULL) { pomp_ctx_stop(s_app.ctx); pomp_ctx_destroy(s_app.ctx); } }
/** * Entry point for the plugin. */ void * LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls) { struct GNUNET_TRANSPORT_PluginEnvironment *env = cls; struct GNUNET_TRANSPORT_PluginFunctions *api; struct HTTP_Client_Plugin *plugin; if (NULL == env->receive) { /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully initialze the plugin or the API */ api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions)); api->cls = NULL; api->address_to_string = &http_common_plugin_address_to_string; api->string_to_address = &http_common_plugin_string_to_address; api->address_pretty_printer = &http_common_plugin_address_pretty_printer; return api; } plugin = GNUNET_malloc (sizeof (struct HTTP_Client_Plugin)); p = plugin; plugin->env = env; api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions)); api->cls = plugin; api->send = &http_client_plugin_send; api->disconnect = &http_client_plugin_disconnect; api->check_address = &http_client_plugin_address_suggested; api->get_session = &http_client_plugin_get_session; api->address_to_string = &http_common_plugin_address_to_string; api->string_to_address = &http_common_plugin_string_to_address; api->address_pretty_printer = &http_common_plugin_address_pretty_printer; #if BUILD_HTTPS plugin->name = "transport-https_client"; plugin->protocol = "https"; #else plugin->name = "transport-http_client"; plugin->protocol = "http"; #endif plugin->last_tag = 1; if (GNUNET_SYSERR == client_configure_plugin (plugin)) { LIBGNUNET_PLUGIN_TRANSPORT_DONE (api); return NULL; } /* Start client */ if (GNUNET_SYSERR == client_start (plugin)) { LIBGNUNET_PLUGIN_TRANSPORT_DONE (api); return NULL; } return api; }
/* Caller owns a reference to the NMDHCPClient on return */ NMDHCPClient * nm_dhcp_manager_start_ip6 (NMDHCPManager *self, const char *iface, const char *uuid, NMSettingIP6Config *s_ip6, guint32 timeout, guint8 *dhcp_anycast_addr, gboolean info_only) { return client_start (self, iface, uuid, TRUE, NULL, s_ip6, timeout, dhcp_anycast_addr, NULL, info_only); }
// 客户端初始化函数 int database_init(const char* server_host, const char* sql_username, const char* sql_password, const char* db_name){ if(!client_start()) return 0; mypid=getpid(); work_file=(FILE *)0; traininfo_num=0; traininfo_index=0; orders_num=0; orders_index=0; return 1; }
int main(int argc, char **argv) { enum start_mode mode = NONE; while (1) { int index, c; c = getopt_long(argc, argv, short_options, long_options, &index); if (c == -1) break; switch (c) { case 0: break; case 'd': debug = 1; break; case 'm': if (strcmp(optarg, "server") == 0) mode = SERVER; else if (strcmp(optarg, "client") == 0) mode = CLIENT; break; case 'h': usage(stdout, argv); exit(EXIT_SUCCESS); default: usage(stderr, argv); exit(EXIT_FAILURE); } } switch (mode) { case CLIENT: client_start(); break; case SERVER: server_start(); break; case NONE: usage(stderr, argv); exit(EXIT_FAILURE); } return 0; }
/* Test grpc_fd. Start an upload server and client, upload a stream of bytes from the client to the server, and verify that the total number of sent bytes is equal to the total number of received bytes. */ static void test_grpc_fd(void) { server sv; client cl; int port; server_init(&sv); port = server_start(&sv); client_init(&cl); client_start(&cl, port); client_wait_and_shutdown(&cl); server_wait_and_shutdown(&sv); GPR_ASSERT(sv.read_bytes_total == cl.write_bytes_total); gpr_log(GPR_INFO, "Total read bytes %d", sv.read_bytes_total); }
int main(int argc, char **argv) { if (argc > 1 && !strcmp(argv[1], "--server")) { if (argc > 2 && !strcmp(argv[2], "--pc")) server_start(PLAYER_PC); else server_start(PLAYER_HUMAN); } else if (argc > 1 && !strcmp(argv[1], "--client")) { if (argc > 2 && !strcmp(argv[2], "--pc")) client_start(PLAYER_PC); else client_start(PLAYER_HUMAN); } else { printf("Usage:\n"); printf(" %s --server Start Server (Player 1)\n", argv[0]); printf(" %s --client Start Client (Player 2)\n", argv[0]); printf(" %s [......] --pc Start as PC Player\n", argv[0]); } return 0; }
/* Caller owns a reference to the NMDHCPClient on return */ NMDHCPClient * nm_dhcp_manager_start_ip4 (NMDHCPManager *self, const char *iface, const char *uuid, NMSettingIP4Config *s_ip4, guint32 timeout, guint8 *dhcp_anycast_addr) { NMDHCPManagerPrivate *priv; NMDHCPClient *client = NULL; const char *hostname = NULL; g_return_val_if_fail (self, NULL); g_return_val_if_fail (NM_IS_DHCP_MANAGER (self), NULL); priv = NM_DHCP_MANAGER_GET_PRIVATE (self); if (s_ip4) { const char *method = nm_setting_ip4_config_get_method (s_ip4); if (method) { /* Method must be 'auto' */ g_return_val_if_fail (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0, NULL); } /* If we're asked to send the hostname to DHCP server, and the hostname * isn't specified, and a hostname provider is registered: use that */ if (nm_setting_ip4_config_get_dhcp_send_hostname (s_ip4)) { hostname = nm_setting_ip4_config_get_dhcp_hostname (s_ip4); /* If we're supposed to send the hostname to the DHCP server but * the user didn't specify one, use the persistent hostname. */ if (!hostname && priv->hostname_provider) { hostname = nm_hostname_provider_get_hostname (priv->hostname_provider); if ( hostname && (!strcmp (hostname, "localhost.localdomain") || !strcmp (hostname, "localhost6.localdomain6"))) hostname = NULL; } } } client = client_start (self, iface, uuid, FALSE, s_ip4, NULL, timeout, dhcp_anycast_addr, hostname, FALSE); return client; }
static int client_timeout_expire(sd_event_source *s, uint64_t usec, void *userdata) { sd_dhcp_client *client = userdata; log_dhcp_client(client, "EXPIRED"); client = client_notify(client, DHCP_EVENT_EXPIRED); /* lease was lost, start over if not freed or stopped in callback */ if (client && client->state != DHCP_STATE_STOPPED) { client_initialize(client); client_start(client); } return 0; }
/* Test grpc_fd. Start an upload server and client, upload a stream of bytes from the client to the server, and verify that the total number of sent bytes is equal to the total number of received bytes. */ static void test_grpc_fd(void) { server sv; client cl; int port; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; server_init(&sv); port = server_start(&exec_ctx, &sv); client_init(&cl); client_start(&exec_ctx, &cl, port); grpc_exec_ctx_finish(&exec_ctx); client_wait_and_shutdown(&cl); server_wait_and_shutdown(&sv); GPR_ASSERT(sv.read_bytes_total == cl.write_bytes_total); gpr_log(GPR_INFO, "Total read bytes %" PRIdPTR, sv.read_bytes_total); }
/* For standalone sipua */ int main(int argc, char** argv) { sipua_t* sipua = NULL; sipua_uas_t* uas = NULL; module_catalog_t *mod_cata = NULL; char *realm = NULL; int sip_port; if(argc == 1) { sip_port = 5060; } else if(argc == 2) { sip_port = strtol(argv[1], NULL, 10); } else if(argc == 3) { sip_port = strtol(argv[1], NULL, 10); realm = argv[2]; } printf("main: sip port is %d\n", sip_port); printf("main: modules in dir:'%s'\n", OGMP_MODULEDIR); mod_cata = catalog_new( "mediaformat" ); catalog_scan_modules (mod_cata, OGMP_VERSION, OGMP_MODULEDIR); uas = client_new_uas(mod_cata, "eXosipua"); if(!uas) printf("main: fail to create sipua server!\n"); if(uas && uas->init(uas, sip_port, "IN", "IP4", NULL, NULL) >= UA_OK) { sipua = client_new("cursesui", uas, realm, mod_cata, 64*1024); if(sipua) client_start(sipua); else printf("main: fail to create sipua!\n"); } return 0; }
void csiebox_client_init( csiebox_client** client, int argc, char** argv) { csiebox_client* tmp = (csiebox_client*)malloc(sizeof(csiebox_client)); if (!tmp) { fprintf(stderr, "client malloc fail\n"); return; } memset(tmp, 0, sizeof(csiebox_client)); if (!parse_arg(tmp, argc, argv)) { fprintf(stderr, "Usage: %s [config file]\n", argv[0]); free(tmp); return; } int fd = client_start(tmp->arg.name, tmp->arg.server); if (fd < 0) { fprintf(stderr, "connect fail\n"); free(tmp); return; } tmp->conn_fd = fd; fd = inotify_init(); if (fd < 0) { fprintf(stderr, "inotify fail\n"); close(tmp->conn_fd); free(tmp); return; } tmp->inotify_fd = fd; if (!init_hash(&(tmp->inotify_hash), 100)) { destroy_hash(&(tmp->inotify_hash)); fprintf(stderr, "hash fail\n"); close(tmp->conn_fd); close(tmp->inotify_fd); free(tmp); } memset(tmp->root, 0, PATH_MAX); realpath(tmp->arg.path, tmp->root); *client = tmp; }
/* Caller owns a reference to the NMDhcpClient on return */ NMDhcpClient * nm_dhcp_manager_start_ip6 (NMDhcpManager *self, const char *iface, int ifindex, const GByteArray *hwaddr, const char *uuid, guint32 priority, gboolean send_hostname, const char *dhcp_hostname, guint32 timeout, const char *dhcp_anycast_addr, gboolean info_only, NMSettingIP6ConfigPrivacy privacy) { const char *hostname = NULL; g_return_val_if_fail (NM_IS_DHCP_MANAGER (self), NULL); if (send_hostname) hostname = get_send_hostname (self, dhcp_hostname); return client_start (self, iface, ifindex, hwaddr, uuid, priority, TRUE, NULL, timeout, dhcp_anycast_addr, hostname, info_only, privacy, NULL); }
/* Caller owns a reference to the NMDhcpClient on return */ NMDhcpClient * nm_dhcp_manager_start_ip4 (NMDhcpManager *self, const char *iface, int ifindex, const GByteArray *hwaddr, const char *uuid, guint32 priority, gboolean send_hostname, const char *dhcp_hostname, const char *dhcp_client_id, guint32 timeout, const char *dhcp_anycast_addr, const char *last_ip_address) { const char *hostname = NULL; g_return_val_if_fail (NM_IS_DHCP_MANAGER (self), NULL); if (send_hostname) hostname = get_send_hostname (self, dhcp_hostname); return client_start (self, iface, ifindex, hwaddr, uuid, priority, FALSE, dhcp_client_id, timeout, dhcp_anycast_addr, hostname, FALSE, 0, last_ip_address); }
int main(int argc, const char** argv) { struct client cli; // Set default hostname. strcpy(cli.host, DEFAULT_HOST); // Set def. port & time. cli.port = DEFAULT_PORT; cli.time = DEFAULT_TIME; // Process user arguments. process_args(&cli, argv, argc); printf("Connecting to %s:%d\n", cli.host, cli.port); if (client_init(&cli, cli.host, cli.port) == -1) { return EXIT_FAILURE; } client_start(&cli); client_stop(&cli); return EXIT_SUCCESS; }
static int client_timeout_resend(sd_event_source *s, uint64_t usec, void *userdata) { sd_dhcp_client *client = userdata; usec_t next_timeout = 0; uint64_t time_now; uint32_t time_left; int r; assert(s); assert(client); assert(client->event); r = sd_event_now(client->event, CLOCK_MONOTONIC, &time_now); if (r < 0) goto error; switch (client->state) { case DHCP_STATE_RENEWING: time_left = (client->lease->t2 - client->lease->t1) / 2; if (time_left < 60) time_left = 60; next_timeout = time_now + time_left * USEC_PER_SEC; break; case DHCP_STATE_REBINDING: time_left = (client->lease->lifetime - client->lease->t2) / 2; if (time_left < 60) time_left = 60; next_timeout = time_now + time_left * USEC_PER_SEC; break; case DHCP_STATE_REBOOTING: /* start over as we did not receive a timely ack or nak */ r = client_initialize(client); if (r < 0) goto error; r = client_start(client); if (r < 0) goto error; else { log_dhcp_client(client, "REBOOTED"); return 0; } case DHCP_STATE_INIT: case DHCP_STATE_INIT_REBOOT: case DHCP_STATE_SELECTING: case DHCP_STATE_REQUESTING: case DHCP_STATE_BOUND: if (client->attempt < 64) client->attempt *= 2; next_timeout = time_now + (client->attempt - 1) * USEC_PER_SEC; break; case DHCP_STATE_STOPPED: r = -EINVAL; goto error; } next_timeout += (random_u32() & 0x1fffff); client->timeout_resend = sd_event_source_unref(client->timeout_resend); r = sd_event_add_time(client->event, &client->timeout_resend, CLOCK_MONOTONIC, next_timeout, 10 * USEC_PER_MSEC, client_timeout_resend, client); if (r < 0) goto error; r = sd_event_source_set_priority(client->timeout_resend, client->event_priority); if (r < 0) goto error; switch (client->state) { case DHCP_STATE_INIT: r = client_send_discover(client); if (r >= 0) { client->state = DHCP_STATE_SELECTING; client->attempt = 1; } else { if (client->attempt >= 64) goto error; } break; case DHCP_STATE_SELECTING: r = client_send_discover(client); if (r < 0 && client->attempt >= 64) goto error; break; case DHCP_STATE_INIT_REBOOT: case DHCP_STATE_REQUESTING: case DHCP_STATE_RENEWING: case DHCP_STATE_REBINDING: r = client_send_request(client); if (r < 0 && client->attempt >= 64) goto error; if (client->state == DHCP_STATE_INIT_REBOOT) client->state = DHCP_STATE_REBOOTING; client->request_sent = time_now; break; case DHCP_STATE_REBOOTING: case DHCP_STATE_BOUND: break; case DHCP_STATE_STOPPED: r = -EINVAL; goto error; } return 0; error: client_stop(client, r); /* Errors were dealt with when stopping the client, don't spill errors into the event loop handler */ return 0; }
static int client_receive_message_raw(sd_event_source *s, int fd, uint32_t revents, void *userdata) { sd_dhcp_client *client = userdata; _cleanup_free_ DHCPPacket *packet = NULL; uint8_t cmsgbuf[CMSG_LEN(sizeof(struct tpacket_auxdata))]; struct iovec iov = {}; struct msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1, .msg_control = cmsgbuf, .msg_controllen = sizeof(cmsgbuf), }; struct cmsghdr *cmsg; bool checksum = true; int buflen = 0, len, r; assert(s); assert(client); r = ioctl(fd, FIONREAD, &buflen); if (r < 0 || buflen <= 0) buflen = sizeof(DHCPPacket) + DHCP_MIN_OPTIONS_SIZE; packet = malloc0(buflen); if (!packet) return -ENOMEM; iov.iov_base = packet; iov.iov_len = buflen; len = recvmsg(fd, &msg, 0); if (len < 0) { log_dhcp_client(client, "could not receive message from raw " "socket: %s", strerror(errno)); return 0; } else if ((size_t)len < sizeof(DHCPPacket)) return 0; for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) { if (cmsg->cmsg_level == SOL_PACKET && cmsg->cmsg_type == PACKET_AUXDATA && cmsg->cmsg_len == CMSG_LEN(sizeof(struct tpacket_auxdata))) { struct tpacket_auxdata *aux = (struct tpacket_auxdata*)CMSG_DATA(cmsg); checksum = !(aux->tp_status & TP_STATUS_CSUMNOTREADY); break; } } r = dhcp_packet_verify_headers(packet, len, checksum); if (r < 0) return 0; len -= DHCP_IP_UDP_SIZE; return client_handle_message(client, &packet->dhcp, len); } int sd_dhcp_client_start(sd_dhcp_client *client) { int r; assert_return(client, -EINVAL); r = client_initialize(client); if (r < 0) return r; if (client->last_addr) client->state = DHCP_STATE_INIT_REBOOT; r = client_start(client); if (r >= 0) log_dhcp_client(client, "STARTED on ifindex %u with address %s", client->index, ether_ntoa(&client->client_id.mac_addr)); return r; }
static int client_handle_message(sd_dhcp_client *client, DHCPMessage *message, int len) { int r = 0, notify_event = 0; assert(client); assert(client->event); assert(message); if (be32toh(message->magic) != DHCP_MAGIC_COOKIE) { log_dhcp_client(client, "not a DHCP message: ignoring"); return 0; } if (message->op != BOOTREPLY) { log_dhcp_client(client, "not a BOOTREPLY message: ignoring"); return 0; } if (be32toh(message->xid) != client->xid) { log_dhcp_client(client, "received xid (%u) does not match " "expected (%u): ignoring", be32toh(message->xid), client->xid); return 0; } if (message->htype != ARPHRD_ETHER || message->hlen != ETHER_ADDR_LEN) { log_dhcp_client(client, "not an ethernet packet"); return 0; } if (memcmp(&message->chaddr[0], &client->client_id.mac_addr, ETH_ALEN)) { log_dhcp_client(client, "received chaddr does not match " "expected: ignoring"); return 0; } switch (client->state) { case DHCP_STATE_SELECTING: r = client_handle_offer(client, message, len); if (r >= 0) { client->timeout_resend = sd_event_source_unref(client->timeout_resend); client->state = DHCP_STATE_REQUESTING; client->attempt = 1; r = sd_event_add_time(client->event, &client->timeout_resend, CLOCK_MONOTONIC, 0, 0, client_timeout_resend, client); if (r < 0) goto error; r = sd_event_source_set_priority(client->timeout_resend, client->event_priority); if (r < 0) goto error; } else if (r == -ENOMSG) /* invalid message, let's ignore it */ return 0; break; case DHCP_STATE_REBOOTING: case DHCP_STATE_REQUESTING: case DHCP_STATE_RENEWING: case DHCP_STATE_REBINDING: r = client_handle_ack(client, message, len); if (r == DHCP_EVENT_NO_LEASE) { client->timeout_resend = sd_event_source_unref(client->timeout_resend); if (client->state == DHCP_STATE_REBOOTING) { r = client_initialize(client); if (r < 0) goto error; r = client_start(client); if (r < 0) goto error; log_dhcp_client(client, "REBOOTED"); } goto error; } else if (r >= 0) { client->timeout_resend = sd_event_source_unref(client->timeout_resend); if (IN_SET(client->state, DHCP_STATE_REQUESTING, DHCP_STATE_REBOOTING)) notify_event = DHCP_EVENT_IP_ACQUIRE; else if (r != DHCP_EVENT_IP_ACQUIRE) notify_event = r; client->state = DHCP_STATE_BOUND; client->attempt = 1; client->last_addr = client->lease->address; r = client_set_lease_timeouts(client); if (r < 0) goto error; if (notify_event) { client = client_notify(client, notify_event); if (!client || client->state == DHCP_STATE_STOPPED) return 0; } client->receive_message = sd_event_source_unref(client->receive_message); client->fd = asynchronous_close(client->fd); } else if (r == -ENOMSG) /* invalid message, let's ignore it */ return 0; break; case DHCP_STATE_INIT: case DHCP_STATE_INIT_REBOOT: case DHCP_STATE_BOUND: break; case DHCP_STATE_STOPPED: r = -EINVAL; goto error; } error: if (r < 0 || r == DHCP_EVENT_NO_LEASE) client_stop(client, r); return r; }
/** * Entry point for the plugin. */ void * LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls) { struct GNUNET_TRANSPORT_PluginEnvironment *env = cls; struct GNUNET_TRANSPORT_PluginFunctions *api; struct Plugin *plugin; int res; if (NULL == env->receive) { /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully initialze the plugin or the API */ api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions)); api->cls = NULL; api->address_pretty_printer = &http_plugin_address_pretty_printer; api->address_to_string = &http_plugin_address_to_string; api->string_to_address = &http_string_to_address; return api; } plugin = GNUNET_malloc (sizeof (struct Plugin)); plugin->env = env; plugin->outbound_sessions = 0; plugin->inbound_sessions = 0; api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions)); api->cls = plugin; api->disconnect = &http_plugin_disconnect; api->address_pretty_printer = &http_plugin_address_pretty_printer; api->check_address = &http_plugin_address_suggested; api->address_to_string = &http_plugin_address_to_string; api->string_to_address = &http_string_to_address; api->get_session = &http_get_session; api->send = &http_plugin_send; #if BUILD_HTTPS plugin->name = "transport-https"; plugin->protocol = "https"; #else plugin->name = "transport-http"; plugin->protocol = "http"; #endif /* Configure plugin from configuration */ res = configure_plugin (plugin); if (res == GNUNET_SYSERR) { GNUNET_free_non_null (plugin->server_addr_v4); GNUNET_free_non_null (plugin->server_addr_v6); GNUNET_free (plugin); GNUNET_free (api); return NULL; } /* checking IPv6 support */ http_check_ipv6 (plugin); /* Start client */ res = client_start (plugin); if (res == GNUNET_SYSERR) { GNUNET_free_non_null (plugin->server_addr_v4); GNUNET_free_non_null (plugin->server_addr_v6); GNUNET_free (plugin); GNUNET_free (api); return NULL; } /* Start server */ if (plugin->client_only == GNUNET_NO) { res = server_start (plugin); if (res == GNUNET_SYSERR) { server_stop (plugin); client_stop (plugin); GNUNET_free_non_null (plugin->server_addr_v4); GNUNET_free_non_null (plugin->server_addr_v6); GNUNET_free (plugin); GNUNET_free (api); return NULL; } } /* Report addresses to transport service */ start_report_addresses (plugin); GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name, "Plugin `%s' loaded\n", plugin->name); return api; }
void client(client_t* client_dat,int client_sock_fd){ // The account of the active client account_t* client_account = NULL; // Set up parameters for select struct timeval timeout ={ TIME_OUT, 0 }; // Timeout after 5000 seconds fd_set read_fd_set; FD_ZERO(&read_fd_set); FD_SET(client_sock_fd, &read_fd_set); int active_sockets; request_t request; response_t response; while((active_sockets = select(client_sock_fd+1,&read_fd_set,NULL,NULL, &timeout))>0){ int byte_read = listen_request(&request,client_sock_fd); if(byte_read == 0){ // Client closed connection unexpectedly. (not manually) if(client_account != NULL){ set_not_in_session(client_account); client_account = NULL; } break; } if(client_account == NULL || !account_is_in_session(client_account)){ // Current client did not open the switch(request.code){ case OPEN: client_open(&response,client_dat,request.message.name); break; case START: client_start(&response,client_dat,&client_account ,request.message.name,client_sock_fd); break; case EXIT: form_response(&response,ACCOUNT_EXIT,"Exit acknowledged."); break; default: form_response(&response,CLIENT_NOT_IN_SESSION,"Please "\ "start an account before doing the transaction."); break; } }else{ switch(request.code){ case OPEN: form_response(&response,CANNOT_OPEN,"Please finish this"\ " account session first."); break; case START: form_response(&response,CANNOT_START,"Please finish this"\ " account session first."); break; case DEBIT: client_debit(&response,client_account,request.message.amount); break; case CREDIT: client_credit(&response,client_account,request.message.amount); break; case BALANCE: form_response(&response,SUCCESS,""); sprintf(response.message,"Account: %s.\nYour balance is %.2f.", client_account->name,client_account->balance); break; case FINISH: set_not_in_session(client_account); form_response(&response,SUCCESS,"Account session closed."); client_account = NULL; break; case EXIT: set_not_in_session(client_account); form_response(&response,ACCOUNT_EXIT,"Exit acknowledged and "\ "account session closed."); client_account = NULL; break; default: form_response(&response,SUCCESS,"Not a valid request."); break; } } // Send the response to the client without failing! while(write(client_sock_fd,&response,sizeof(response_t))<0){ continue; } if(request.code == EXIT){ break; } } if(active_sockets == 0 ){ if (client_account!=NULL){ set_not_in_session(client_account); client_account = NULL; } form_response(&response, CONNECTION_TIME_OUT,"Connection time out."); write(client_sock_fd, &response,sizeof(response_t)); } exit(EXIT_SUCCESS); }
int main(int argc, char* argv[]) { parse_args(argc, argv); // Done differently depending on application nbody_init(num_bodies); gui_init("nbody1"); /* // Make some clumped bodies with initial velocity for a more interesting simulation for(i = 0; i < num_bodies/4; ++i) { body[i].pos.x = -50 + rand() % 20; body[i].pos.y = -50 + rand() % 20; body[i].pos.z = -50 + rand() % 20; body[i].vel.x = 0.05; } for(i = num_bodies/4; i < num_bodies/2; ++i) { body[i].pos.x = 30 + rand() % 20; body[i].pos.y = 30 + rand() % 20; body[i].pos.z = 30 + rand() % 20; body[i].vel.x = -0.05; }*/ float delta = 0.f; clock_t start = times(NULL); client_start(); int iterations = 0; while(gui_update()) { // simulate stuff delta += turbo; while(delta >= 1.f) { // random mass flip //if(allow_negative) // body[rand() % num_bodies].mass *= -1.f; calc_forces(); add_velocity(); delta -= 1.f; ++iterations; } // if there's a limit, count down and break if reached if(num_steps > 0 && (--num_steps == 0)) break; } clock_t stop = times(NULL); fputs(argv[0], stdout); int i; for(i = 1; i < argc; ++i) { fputc(' ', stdout); fputs(argv[i], stdout); } long ticks_per_sec = sysconf(_SC_CLK_TCK); printf("\n%d iterations.\n", iterations); clock_t time = stop - start; printf("elapsed: %f seconds.\navg: %f seconds per iteration.\n", ((float)(time))/ticks_per_sec, ((float)(time))/ticks_per_sec/iterations); client_exit(); gui_quit(); free(body); return 0; }
int main(int argc, char **argv) { srand(time(NULL)); rand(); if (argc == 2 || argc == 3) { char *hostname = argv[1]; int port = DEFAULT_PORT; if (argc == 3) { port = atoi(argv[2]); } db_disable(); client_enable(); client_connect(hostname, port); client_start(); } if (!glfwInit()) { return -1; } create_window(); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSwapInterval(VSYNC); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetKeyCallback(window, on_key); glfwSetMouseButtonCallback(window, on_mouse_button); glfwSetScrollCallback(window, on_scroll); #ifndef __APPLE__ if (glewInit() != GLEW_OK) { return -1; } #endif if (db_init()) { return -1; } glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_LINE_SMOOTH); glLogicOp(GL_INVERT); glClearColor(0.53, 0.81, 0.92, 1.00); GLuint texture; glGenTextures(1, &texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); load_png_texture("texture.png"); GLuint block_program = load_program( "shaders/block_vertex.glsl", "shaders/block_fragment.glsl"); GLuint matrix_loc = glGetUniformLocation(block_program, "matrix"); GLuint camera_loc = glGetUniformLocation(block_program, "camera"); GLuint sampler_loc = glGetUniformLocation(block_program, "sampler"); GLuint timer_loc = glGetUniformLocation(block_program, "timer"); GLuint position_loc = glGetAttribLocation(block_program, "position"); GLuint normal_loc = glGetAttribLocation(block_program, "normal"); GLuint uv_loc = glGetAttribLocation(block_program, "uv"); GLuint line_program = load_program( "shaders/line_vertex.glsl", "shaders/line_fragment.glsl"); GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix"); GLuint line_position_loc = glGetAttribLocation(line_program, "position"); GLuint item_position_buffer = 0; GLuint item_normal_buffer = 0; GLuint item_uv_buffer = 0; int previous_block_type = 0; Chunk chunks[MAX_CHUNKS]; int chunk_count = 0; Player players[MAX_PLAYERS]; int player_count = 0; FPS fps = {0, 0}; float matrix[16]; float x = (rand_double() - 0.5) * 10000; float z = (rand_double() - 0.5) * 10000; float y = 0; float dy = 0; float rx = 0; float ry = 0; double px = 0; double py = 0; int loaded = db_load_state(&x, &y, &z, &rx, &ry); ensure_chunks(chunks, &chunk_count, floorf(roundf(x) / CHUNK_SIZE), floorf(roundf(z) / CHUNK_SIZE), 1); if (!loaded) { y = highest_block(chunks, chunk_count, x, z) + 2; } glfwGetCursorPos(window, &px, &py); double previous = glfwGetTime(); while (!glfwWindowShouldClose(window)) { update_fps(&fps, SHOW_FPS); double now = glfwGetTime(); double dt = MIN(now - previous, 0.2); previous = now; if (exclusive && (px || py)) { double mx, my; glfwGetCursorPos(window, &mx, &my); float m = 0.0025; rx += (mx - px) * m; ry -= (my - py) * m; if (rx < 0) { rx += RADIANS(360); } if (rx >= RADIANS(360)){ rx -= RADIANS(360); } ry = MAX(ry, -RADIANS(90)); ry = MIN(ry, RADIANS(90)); px = mx; py = my; } else { glfwGetCursorPos(window, &px, &py); } int sz = 0; int sx = 0; ortho = glfwGetKey(window, 'F'); fov = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) ? 15.0 : 65.0; if (glfwGetKey(window, 'Q')) break; if (glfwGetKey(window, 'W')) sz--; if (glfwGetKey(window, 'S')) sz++; if (glfwGetKey(window, 'A')) sx--; if (glfwGetKey(window, 'D')) sx++; float m = dt * 1.0; if (glfwGetKey(window, GLFW_KEY_LEFT)) rx -= m; if (glfwGetKey(window, GLFW_KEY_RIGHT)) rx += m; if (glfwGetKey(window, GLFW_KEY_UP)) ry += m; if (glfwGetKey(window, GLFW_KEY_DOWN)) ry -= m; float vx, vy, vz; get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz); if (glfwGetKey(window, GLFW_KEY_SPACE)) { if (flying) { vy = 1; } else if (dy == 0) { dy = 8; } } if (glfwGetKey(window, 'Z')) { vx = -1; vy = 0; vz = 0; } if (glfwGetKey(window, 'X')) { vx = 1; vy = 0; vz = 0; } if (glfwGetKey(window, 'C')) { vx = 0; vy = -1; vz = 0; } if (glfwGetKey(window, 'V')) { vx = 0; vy = 1; vz = 0; } if (glfwGetKey(window, 'B')) { vx = 0; vy = 0; vz = -1; } if (glfwGetKey(window, 'N')) { vx = 0; vy = 0; vz = 1; } float speed = flying ? 20 : 5; int step = 8; float ut = dt / step; vx = vx * ut * speed; vy = vy * ut * speed; vz = vz * ut * speed; for (int i = 0; i < step; i++) { if (flying) { dy = 0; } else { dy -= ut * 25; dy = MAX(dy, -250); } x += vx; y += vy + dy * ut; z += vz; if (collide(chunks, chunk_count, 2, &x, &y, &z)) { dy = 0; } } if (y < 0) { y = highest_block(chunks, chunk_count, x, z) + 2; } for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; chunk->dirty = 0; } if (left_click) { left_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (hy > 0 && is_destructable(hw)) { set_block(chunks, chunk_count, hx, hy, hz, 0, 1); } } if (right_click) { right_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 1, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { if (!player_intersects_block(2, x, y, z, hx, hy, hz)) { set_block(chunks, chunk_count, hx, hy, hz, block_type, 1); } } } if (middle_click) { middle_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (is_selectable(hw)) { block_type = hw; } } if (teleport) { teleport = 0; if (player_count) { int index = rand_int(player_count); Player *player = players + index; x = player->x; y = player->y; z = player->z; rx = player->rx; ry = player->ry; ensure_chunks(chunks, &chunk_count, floorf(roundf(x) / CHUNK_SIZE), floorf(roundf(z) / CHUNK_SIZE), 1); } } client_position(x, y, z, rx, ry); char buffer[RECV_BUFFER_SIZE]; while (client_recv(buffer, RECV_BUFFER_SIZE)) { float ux, uy, uz, urx, ury; if (sscanf(buffer, "U,%*d,%f,%f,%f,%f,%f", &ux, &uy, &uz, &urx, &ury) == 5) { x = ux; y = uy; z = uz; rx = urx; ry = ury; ensure_chunks(chunks, &chunk_count, floorf(roundf(x) / CHUNK_SIZE), floorf(roundf(z) / CHUNK_SIZE), 1); y = highest_block(chunks, chunk_count, x, z) + 2; } int bx, by, bz, bw; if (sscanf(buffer, "B,%*d,%*d,%d,%d,%d,%d", &bx, &by, &bz, &bw) == 4) { set_block(chunks, chunk_count, bx, by, bz, bw, 0); if ((int)roundf(x) == bx && (int)roundf(z) == bz) { y = highest_block(chunks, chunk_count, x, z) + 2; } } int pid; float px, py, pz, prx, pry; if (sscanf(buffer, "P,%d,%f,%f,%f,%f,%f", &pid, &px, &py, &pz, &prx, &pry) == 6) { Player *player = find_player(players, player_count, pid); if (!player && player_count < MAX_PLAYERS) { player = players + player_count; player_count++; player->id = pid; player->position_buffer = 0; player->normal_buffer = 0; player->uv_buffer = 0; printf("%d other players are online\n", player_count); } if (player) { update_player(player, px, py, pz, prx, pry); } } if (sscanf(buffer, "D,%d", &pid) == 1) { delete_player(players, &player_count, pid); printf("%d other players are online\n", player_count); } } for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; if (chunk->dirty) { update_chunk(chunk); } } int p = floorf(roundf(x) / CHUNK_SIZE); int q = floorf(roundf(z) / CHUNK_SIZE); ensure_chunks(chunks, &chunk_count, p, q, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); update_matrix_3d(matrix, x, y, z, rx, ry); // render chunks glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, x, y, z); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) { continue; } if (!chunk_visible(chunk, matrix)) { continue; } draw_chunk(chunk, position_loc, normal_loc, uv_loc); } // render players for (int i = 0; i < player_count; i++) { Player *player = players + i; draw_player(player, position_loc, normal_loc, uv_loc); } // render focused block wireframe int hx, hy, hz; int hw = hit_test( chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { glUseProgram(line_program); glLineWidth(1); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint cube_buffer = make_cube_buffer(hx, hy, hz, 0.51); draw_lines(cube_buffer, line_position_loc, 3, 48); glDeleteBuffers(1, &cube_buffer); glDisable(GL_COLOR_LOGIC_OP); } update_matrix_2d(matrix); // render crosshairs glUseProgram(line_program); glLineWidth(4); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint line_buffer = make_line_buffer(); draw_lines(line_buffer, line_position_loc, 2, 4); glDeleteBuffers(1, &line_buffer); glDisable(GL_COLOR_LOGIC_OP); // render selected item update_matrix_item(matrix); if (block_type != previous_block_type) { previous_block_type = block_type; make_single_cube( &item_position_buffer, &item_normal_buffer, &item_uv_buffer, 0, 0, 0, 0.5, block_type); } glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, 0, 0, 5); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); glDisable(GL_DEPTH_TEST); draw_single_cube( item_position_buffer, item_normal_buffer, item_uv_buffer, position_loc, normal_loc, uv_loc); glEnable(GL_DEPTH_TEST); glfwSwapBuffers(window); glfwPollEvents(); } client_stop(); db_save_state(x, y, z, rx, ry); db_close(); glfwTerminate(); return 0; }
/** * @TEST Params (Testing purpose only) * @ server 3590 * @ client 127.0.0.1 3590 /home/santiago/workspace/tp1_new/Debug/ejemplo1 /home/santiago/workspace/tp1_new/Debug/outputFile /home/santiago/workspace/tp1_new/Debug/ejemplo2 4 * TODO Document the new and changed stuff */ int main(int argc, char *argv[]) { //Initialize our app state APP_STATE state = APP_STATE_UNDEFINED; /** * If we have at least the type parameter (this means client/server) * then we should at least be able to operate and let the app flow handle * the result. * Which is pretty obvious it will fail since theres nothing to pull * from the server. * @Refactor maybe ? */ if (argc > 1) { //Initialize a socket we will be using socket_t mSocket; socket_init(&mSocket); //If client if (!strcmp(argv[1], HOST_CLIENT)) { client_t mClient; client_init(&mClient, &mSocket, argv[4], argv[5], argv[6]); int chunkSize = atoi(argv[7]); /** * This is the core of the client. * Here it will connect the socket with the given params, * Send the server the specifications of the pull, * Parse its src file in checksums, send the list and * listen for the remote changes, while writing them to the * ouput file. */ client_start(&mClient, argv[2], argv[3], &chunkSize, &state); client_destroy(&mClient); } //If server /** * @note: I have done them like this (and not in if/else) * since its not specified how the app should react to * a random param name (eg ./app random). In this case, it just closes * and nothing happens */ if (!strcmp(argv[1], HOST_SERVER)) { server_t mServer; server_init(&mServer, &mSocket); /** * This is the core of the server. * Here it will bind and listen to the supplied port, * Receive the specifications of the pull and the checksum list * Iterate through its own updated file while looking for differences * sending them to the client, so contents are identical */ server_start(&mServer, argv[2], &state); server_destroy(&mServer); } //Close the file descriptor socket_close(&mSocket); } else { //Notify about usage if no args passed printf("Fail to receive arguments\n"); printf("For client use: \"client\" @host @port"); printf("@src @dst @remote @chunkSize\n"); printf("For server use: \"server\" @port"); state = APP_STATE_ERROR; } return state; }
int main(int argc, char **argv) { srand(time(NULL)); rand(); if (argc == 2 || argc == 3) { char *hostname = argv[1]; int port = DEFAULT_PORT; if (argc == 3) { port = atoi(argv[2]); } db_disable(); client_enable(); client_connect(hostname, port); client_start(); } if (!glfwInit()) { return -1; } create_window(); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSwapInterval(VSYNC); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetKeyCallback(window, on_key); glfwSetCharCallback(window, on_char); glfwSetMouseButtonCallback(window, on_mouse_button); glfwSetScrollCallback(window, on_scroll); #ifndef __APPLE__ if (glewInit() != GLEW_OK) { return -1; } #endif if (db_init()) { return -1; } glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_LINE_SMOOTH); glLogicOp(GL_INVERT); glClearColor(0.53, 0.81, 0.92, 1.00); GLuint texture; glGenTextures(1, &texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); load_png_texture("texture.png"); GLuint font; glGenTextures(1, &font); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, font); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); load_png_texture("font.png"); GLuint block_program = load_program( "shaders/block_vertex.glsl", "shaders/block_fragment.glsl"); GLuint matrix_loc = glGetUniformLocation(block_program, "matrix"); GLuint camera_loc = glGetUniformLocation(block_program, "camera"); GLuint sampler_loc = glGetUniformLocation(block_program, "sampler"); GLuint timer_loc = glGetUniformLocation(block_program, "timer"); GLuint position_loc = glGetAttribLocation(block_program, "position"); GLuint normal_loc = glGetAttribLocation(block_program, "normal"); GLuint uv_loc = glGetAttribLocation(block_program, "uv"); GLuint line_program = load_program( "shaders/line_vertex.glsl", "shaders/line_fragment.glsl"); GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix"); GLuint line_position_loc = glGetAttribLocation(line_program, "position"); GLuint text_program = load_program( "shaders/text_vertex.glsl", "shaders/text_fragment.glsl"); GLuint text_matrix_loc = glGetUniformLocation(text_program, "matrix"); GLuint text_sampler_loc = glGetUniformLocation(text_program, "sampler"); GLuint text_position_loc = glGetAttribLocation(text_program, "position"); GLuint text_uv_loc = glGetAttribLocation(text_program, "uv"); GLuint item_position_buffer = 0; GLuint item_normal_buffer = 0; GLuint item_uv_buffer = 0; int previous_block_type = 0; char messages[MAX_MESSAGES][TEXT_BUFFER_SIZE] = {0}; int message_index = 0; Chunk chunks[MAX_CHUNKS]; int chunk_count = 0; Player players[MAX_PLAYERS]; int player_count = 0; FPS fps = {0, 0}; float matrix[16]; float x = (rand_double() - 0.5) * 10000; float z = (rand_double() - 0.5) * 10000; float y = 0; float dy = 0; float rx = 0; float ry = 0; double px = 0; double py = 0; int loaded = db_load_state(&x, &y, &z, &rx, &ry); ensure_chunks(chunks, &chunk_count, x, y, z, 1); if (!loaded) { y = highest_block(chunks, chunk_count, x, z) + 2; } glfwGetCursorPos(window, &px, &py); double previous = glfwGetTime(); while (!glfwWindowShouldClose(window)) { int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); update_fps(&fps, SHOW_FPS); double now = glfwGetTime(); double dt = MIN(now - previous, 0.2); previous = now; if (exclusive && (px || py)) { double mx, my; glfwGetCursorPos(window, &mx, &my); float m = 0.0025; rx += (mx - px) * m; ry -= (my - py) * m; if (rx < 0) { rx += RADIANS(360); } if (rx >= RADIANS(360)){ rx -= RADIANS(360); } ry = MAX(ry, -RADIANS(90)); ry = MIN(ry, RADIANS(90)); px = mx; py = my; } else { glfwGetCursorPos(window, &px, &py); } int sz = 0; int sx = 0; if (!typing) { float m = dt * 1.0; ortho = glfwGetKey(window, CRAFT_KEY_ORTHO); fov = glfwGetKey(window, CRAFT_KEY_ZOOM) ? 15.0 : 65.0; if (glfwGetKey(window, CRAFT_KEY_QUIT)) break; if (glfwGetKey(window, CRAFT_KEY_FORWARD)) sz--; if (glfwGetKey(window, CRAFT_KEY_BACKWARD)) sz++; if (glfwGetKey(window, CRAFT_KEY_LEFT)) sx--; if (glfwGetKey(window, CRAFT_KEY_RIGHT)) sx++; if (glfwGetKey(window, GLFW_KEY_LEFT)) rx -= m; if (glfwGetKey(window, GLFW_KEY_RIGHT)) rx += m; if (glfwGetKey(window, GLFW_KEY_UP)) ry += m; if (glfwGetKey(window, GLFW_KEY_DOWN)) ry -= m; } float vx, vy, vz; get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz); if (!typing) { if (glfwGetKey(window, CRAFT_KEY_JUMP)) { if (flying) { vy = 1; } else if (dy == 0) { dy = 8; } } if (glfwGetKey(window, CRAFT_KEY_XM)) { vx = -1; vy = 0; vz = 0; } if (glfwGetKey(window, CRAFT_KEY_XP)) { vx = 1; vy = 0; vz = 0; } if (glfwGetKey(window, CRAFT_KEY_YM)) { vx = 0; vy = -1; vz = 0; } if (glfwGetKey(window, CRAFT_KEY_YP)) { vx = 0; vy = 1; vz = 0; } if (glfwGetKey(window, CRAFT_KEY_ZM)) { vx = 0; vy = 0; vz = -1; } if (glfwGetKey(window, CRAFT_KEY_ZP)) { vx = 0; vy = 0; vz = 1; } } float speed = flying ? 20 : 5; int step = 8; float ut = dt / step; vx = vx * ut * speed; vy = vy * ut * speed; vz = vz * ut * speed; for (int i = 0; i < step; i++) { if (flying) { dy = 0; } else { dy -= ut * 25; dy = MAX(dy, -250); } x += vx; y += vy + dy * ut; z += vz; if (collide(chunks, chunk_count, 2, &x, &y, &z)) { dy = 0; } } if (y < 0) { y = highest_block(chunks, chunk_count, x, z) + 2; } if (left_click) { left_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (hy > 0 && is_destructable(hw)) { set_block(chunks, chunk_count, hx, hy, hz, 0); int above = get_block(chunks, chunk_count, hx, hy + 1, hz); if (is_plant(above)) { set_block(chunks, chunk_count, hx, hy + 1, hz, 0); } } } if (right_click) { right_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 1, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { if (!player_intersects_block(2, x, y, z, hx, hy, hz)) { set_block(chunks, chunk_count, hx, hy, hz, block_type); } } } if (middle_click) { middle_click = 0; int hx, hy, hz; int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (is_selectable(hw)) { block_type = hw; } } if (teleport) { teleport = 0; if (player_count) { int index = rand_int(player_count); Player *player = players + index; x = player->x; y = player->y; z = player->z; rx = player->rx; ry = player->ry; ensure_chunks(chunks, &chunk_count, x, y, z, 1); } } client_position(x, y, z, rx, ry); char buffer[RECV_BUFFER_SIZE]; while (client_recv(buffer, RECV_BUFFER_SIZE)) { float ux, uy, uz, urx, ury; if (sscanf(buffer, "U,%*d,%f,%f,%f,%f,%f", &ux, &uy, &uz, &urx, &ury) == 5) { x = ux; y = uy; z = uz; rx = urx; ry = ury; ensure_chunks(chunks, &chunk_count, x, y, z, 1); y = highest_block(chunks, chunk_count, x, z) + 2; } int bp, bq, bx, by, bz, bw; if (sscanf(buffer, "B,%d,%d,%d,%d,%d,%d", &bp, &bq, &bx, &by, &bz, &bw) == 6) { _set_block(chunks, chunk_count, bp, bq, bx, by, bz, bw); if (player_intersects_block(2, x, y, z, bx, by, bz)) { y = highest_block(chunks, chunk_count, x, z) + 2; } } int pid; float px, py, pz, prx, pry; if (sscanf(buffer, "P,%d,%f,%f,%f,%f,%f", &pid, &px, &py, &pz, &prx, &pry) == 6) { Player *player = find_player(players, player_count, pid); if (!player && player_count < MAX_PLAYERS) { player = players + player_count; player_count++; player->id = pid; player->position_buffer = 0; player->normal_buffer = 0; player->uv_buffer = 0; } if (player) { update_player(player, px, py, pz, prx, pry); } } if (sscanf(buffer, "D,%d", &pid) == 1) { delete_player(players, &player_count, pid); } if (buffer[0] == 'T' && buffer[1] == ',') { char *text = buffer + 2; printf("%s\n", text); snprintf( messages[message_index], TEXT_BUFFER_SIZE, "%s", text); message_index = (message_index + 1) % MAX_MESSAGES; } } int p = chunked(x); int q = chunked(z); ensure_chunks(chunks, &chunk_count, x, y, z, 0); // RENDER 3-D SCENE // glClear(GL_COLOR_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT); set_matrix_3d(matrix, width, height, x, y, z, rx, ry, fov, ortho); // render chunks glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, x, y, z); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); for (int i = 0; i < chunk_count; i++) { Chunk *chunk = chunks + i; if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) { continue; } if (y < 100 && !chunk_visible(chunk, matrix)) { continue; } draw_chunk(chunk, position_loc, normal_loc, uv_loc); } // render players for (int i = 0; i < player_count; i++) { Player *player = players + i; draw_player(player, position_loc, normal_loc, uv_loc); } // render focused block wireframe int hx, hy, hz; int hw = hit_test( chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz); if (is_obstacle(hw)) { glUseProgram(line_program); glLineWidth(1); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint wireframe_buffer = gen_wireframe_buffer(hx, hy, hz, 0.51); draw_lines(wireframe_buffer, line_position_loc, 3, 48); glDeleteBuffers(1, &wireframe_buffer); glDisable(GL_COLOR_LOGIC_OP); } // RENDER 2-D HUD PARTS // glClear(GL_DEPTH_BUFFER_BIT); set_matrix_2d(matrix, width, height); // render crosshairs glUseProgram(line_program); glLineWidth(4); glEnable(GL_COLOR_LOGIC_OP); glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix); GLuint crosshair_buffer = gen_crosshair_buffer(width, height); draw_lines(crosshair_buffer, line_position_loc, 2, 4); glDeleteBuffers(1, &crosshair_buffer); glDisable(GL_COLOR_LOGIC_OP); // render text glUseProgram(text_program); glUniformMatrix4fv(text_matrix_loc, 1, GL_FALSE, matrix); glUniform1i(text_sampler_loc, 1); char text_buffer[1024]; float ts = 12; float tx = ts / 2; float ty = height - ts; snprintf( text_buffer, 1024, "%d, %d, %.2f, %.2f, %.2f [%d, %d]", p, q, x, y, z, player_count, chunk_count); print( text_position_loc, text_uv_loc, tx, ty, ts, text_buffer); for (int i = 0; i < MAX_MESSAGES; i++) { int index = (message_index + i) % MAX_MESSAGES; if (strlen(messages[index])) { ty -= ts * 2; print( text_position_loc, text_uv_loc, tx, ty, ts, messages[index]); } } if (typing) { ty -= ts * 2; snprintf(text_buffer, 1024, "> %s", typing_buffer); print( text_position_loc, text_uv_loc, tx, ty, ts, text_buffer); } // RENDER 3-D HUD PARTS // set_matrix_item(matrix, width, height); // render selected item if (block_type != previous_block_type) { previous_block_type = block_type; if (is_plant(block_type)) { gen_plant_buffers( &item_position_buffer, &item_normal_buffer, &item_uv_buffer, 0, 0, 0, 0.5, block_type); } else { gen_cube_buffers( &item_position_buffer, &item_normal_buffer, &item_uv_buffer, 0, 0, 0, 0.5, block_type); } } glUseProgram(block_program); glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix); glUniform3f(camera_loc, 0, 0, 5); glUniform1i(sampler_loc, 0); glUniform1f(timer_loc, glfwGetTime()); if (is_plant(block_type)) { draw_plant( item_position_buffer, item_normal_buffer, item_uv_buffer, position_loc, normal_loc, uv_loc); } else { draw_cube( item_position_buffer, item_normal_buffer, item_uv_buffer, position_loc, normal_loc, uv_loc); } // swap buffers glfwSwapBuffers(window); glfwPollEvents(); } client_stop(); db_save_state(x, y, z, rx, ry); db_close(); glfwTerminate(); return 0; }