Example #1
0
boolean Floor::display_region() {
#if TT_DEBUG_ON
	if (tt_debug_mode == 250404) {
		tt_error_file() << "Displaying floor on frame " << tt_frame_number << endl;
	};
#endif
   boolean result = FALSE;
	int background_index;
	if (body_cubby == NULL) {
		background_index = floor_id;
	} else {
		background_index = THOUGHT_BUBBLE_BACKGROUND;
	};
   if (tt_toolbox == NULL || tt_toolbox->gone()) { // gone test new on 120704
      background(background_index)->display();
   } else {
	   switch(toolbox_status) {
		   case TOOLBOX_CACHE_INVALID:
//			   play_sound(POP_SOUND,8);
//			   load_background(background_index);
			   if (tt_toolbox != NULL) tt_toolbox->set_background_cached(FALSE);
			   // and do the following
		   case TOOLBOX_NOT_READY_TO_CACHE:
         case TOOLBOX_CACHE_STATUS_UNINITIALIZED:
			   background(background_index)->display();
//			   screen->display_background(background_index);
			   result = TRUE; // background will only last one frame
            break;
		   case TOOLBOX_CACHE_VALID:
			   display_background_cache();
            return(result);
		   case TOOLBOX_READY_TO_CACHE:
//			   play_sound(PLOP_SOUND,8);
			   background(background_index)->display();
            display_walls(); // moved here on 250402 since otherwise this can obscure part of Tooly
//			   screen->display_background(background_index);
            tt_postpone_dirty_displays = FALSE;
			   if (!tt_toolbox->gone()) {
//#if TT_DEBUG_ON
//					if (tt_toolbox->is_background_cached()) {
//						log("debug this");
//					};
//#endif
					tt_toolbox->just_set_background_cached(FALSE); // new on 061003 since time travel can confuse this caching
//					tt_screen->display_layers_below(tt_toolbox); // new on 111204
				   tt_toolbox->display();
			   };
			   cache_background();
			   tt_toolbox->set_background_cached(TRUE);
            return(result);
      };
	};
   if (background_index == THOUGHT_BUBBLE_BACKGROUND) {
      string steps_left = initial_robot->steps_left_string();
      if (steps_left != NULL) {
BEGIN_GDI
	      tt_screen->text_out(steps_left,_tcslen(steps_left),
                             steps_left_counter_llx,steps_left_counter_lly,
							        steps_left_counter_font_width,steps_left_counter_font_height,TRUE,FALSE,TRUE);
END_GDI
         delete [] steps_left;
      };
   };
   display_walls();
   return(result);
};
Example #2
0
QColor ColorScheme::shade(ShadeRole role) const {
      return shade(background().color(), role, d->contrast());
      }
Example #3
0
Double_t fitFunction(Double_t *dim, Double_t *par){

   return photo_peak(dim, par) + step_function(dim,par) + background(dim,&par[6]);
}
Example #4
0
int main(int argc, char *argv[])
#endif
{
	char *temp, *message;
	unsigned long t1 = 0, t2 = 0, xid = 0;
	unsigned long start = 0, lease;
	fd_set rfds;
	int fd, retval;
	struct timeval tv;
	int c, len;
	struct ifreq ifr;
	struct dhcpMessage packet;
	struct in_addr temp_addr;
	int pid_fd;

	static struct option options[] = {
		{"clientid",	required_argument,	0, 'c'},
		{"foreground",	no_argument,		0, 'f'},
		{"hostname",	required_argument,	0, 'H'},
		{"help",	no_argument,		0, 'h'},
		{"interface",	required_argument,	0, 'i'},
		{"now", 	no_argument,		0, 'n'},
		{"pidfile",	required_argument,	0, 'p'},
		{"quit",	no_argument,		0, 'q'},
		{"request",	required_argument,	0, 'r'},
		{"script",	required_argument,	0, 's'},
		{"version",	no_argument,		0, 'v'},
		{0, 0, 0, 0}
	};

	/* get options */
	while (1) {
		int option_index = 0;
// brcm
		c = getopt_long(argc, argv, "c:fH:hi:np:qr:s:d:v", options, &option_index);
		if (c == -1) break;
		
		switch (c) {
		case 'c':
			len = strlen(optarg) > 255 ? 255 : strlen(optarg);
			if (client_config.clientid) free(client_config.clientid);
			client_config.clientid = malloc(len + 2);
			client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
			client_config.clientid[OPT_LEN] = len;
			strncpy(client_config.clientid + 2, optarg, len);
			break;
		case 'f':
			client_config.foreground = 1;
			break;
		case 'H':
			len = strlen(optarg) > 255 ? 255 : strlen(optarg);
			if (client_config.hostname) free(client_config.hostname);
			client_config.hostname = malloc(len + 2);
			client_config.hostname[OPT_CODE] = DHCP_HOST_NAME;
			client_config.hostname[OPT_LEN] = len;
			strncpy(client_config.hostname + 2, optarg, len);
			break;
		case 'h':
			print_usage();
			return 0;
		case 'i':
			client_config.interface =  optarg;
// brcm
			strcpy(session_path, optarg);
			break;
		case 'n':
			client_config.abort_if_no_lease = 1;
			break;
		case 'p':
			client_config.pidfile = optarg;
			break;
		case 'q':
			client_config.quit_after_lease = 1;
			break;
		case 'r':
			requested_ip = inet_addr(optarg);
			break;
// brcm
		case 'd':
			strcpy(vendor_class_id, optarg);
			break;
		case 's':
			client_config.script = optarg;
			break;
		case 'v':
			printf("udhcpcd, version %s\n\n", VERSION);
			break;
		}
	}

	// brcm
        if (strlen(session_path) > 0) {
	    sprintf(status_path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_MSG);
	    sprintf(pid_path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_PID);
	}

	OPEN_LOG("udhcpc");
	LOG(LOG_INFO, "udhcp client (v%s) started", VERSION);

	pid_fd = pidfile_acquire(client_config.pidfile);
	pidfile_write_release(pid_fd);

	if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) >= 0) {
		strcpy(ifr.ifr_name, client_config.interface);
		if (ioctl(fd, SIOCGIFINDEX, &ifr) == 0) {
			DEBUG(LOG_INFO, "adapter index %d", ifr.ifr_ifindex);
			client_config.ifindex = ifr.ifr_ifindex;
		} else {
			LOG(LOG_ERR, "SIOCGIFINDEX failed! %s", strerror(errno));
			exit_client(1);
		}
		if (ioctl(fd, SIOCGIFHWADDR, &ifr) == 0) {
			memcpy(client_config.arp, ifr.ifr_hwaddr.sa_data, 6);
			DEBUG(LOG_INFO, "adapter hardware address %02x:%02x:%02x:%02x:%02x:%02x",
				client_config.arp[0], client_config.arp[1], client_config.arp[2], 
				client_config.arp[3], client_config.arp[4], client_config.arp[5]);
		} else {
			LOG(LOG_ERR, "SIOCGIFHWADDR failed! %s", strerror(errno));
			exit_client(1);
		}
	} else {
		LOG(LOG_ERR, "socket failed! %s", strerror(errno));
		exit_client(1);
	}
	close(fd);
	fd = -1;

	/* setup signal handlers */
	signal(SIGUSR1, renew_requested);
	signal(SIGUSR2, release_requested);
	signal(SIGTERM, terminate);
	
	state = INIT_SELECTING;
	// brcm
	// run_script(NULL, "deconfig");

	// brcm
	setStatus(0);

	for (;;) {

		// brcm
		if ((old_mode != listen_mode) || (fd == -1)) {
		    old_mode = listen_mode;
		
		    if (fd > 0) {
			    close(fd);
			    fd = -1;
		    }
		
		    if (listen_mode == LISTEN_RAW) {
			    if ((fd = raw_socket(client_config.ifindex)) < 0) {
				    LOG(LOG_ERR, "couldn't create raw socket -- au revoir");
				    exit_client(0);
			    }
		    }
		    else if (listen_mode == LISTEN_KERNEL) {
			    if ((fd = listen_socket(INADDR_ANY, CLIENT_PORT, client_config.interface)) < 0) {
				    LOG(LOG_ERR, "couldn't create server socket -- au revoir");
				    exit_client(0);
			    }			
		    } else 
			fd = -1;
		}

		tv.tv_sec = timeout - time(0);
		tv.tv_usec = 0;
		FD_ZERO(&rfds);
		if (listen_mode) FD_SET(fd, &rfds);
		
		if (tv.tv_sec > 0) {
			retval = select(fd + 1, &rfds, NULL, NULL, &tv);
		} else retval = 0; /* If we already timed out, fall through */
		
		if (retval == 0) {
			/* timeout dropped to zero */
			switch (state) {
			case INIT_SELECTING:
				// brcm
				setStatus(0);
				if (packet_num < 3) {
					if (packet_num == 0)
						xid = random_xid();

					/* send discover packet */
					send_discover(xid, requested_ip); /* broadcast */
					
					timeout = time(0) + ((packet_num == 2) ? 10 : 2);
					packet_num++;
				} else {
					if (client_config.abort_if_no_lease) {
						LOG(LOG_INFO,
						    "No lease, failing.");
						exit_client(1);
				  	}
					/* wait to try again */
					packet_num = 0;
					timeout = time(0) + 60;
				}
				break;
			case RENEW_REQUESTED:
			case REQUESTING:
				if (packet_num < 3) {
					/* send request packet */
					if (state == RENEW_REQUESTED)
						send_renew(xid, server_addr, requested_ip); /* unicast */
					else send_selecting(xid, server_addr, requested_ip); /* broadcast */
					
					timeout = time(0) + ((packet_num == 2) ? 10 : 2);
					packet_num++;
				} else {
					/* timed out, go back to init state */
					state = INIT_SELECTING;
					timeout = time(0);
					packet_num = 0;
					listen_mode = LISTEN_RAW;
					
				}
				break;
			case BOUND:
				/* Lease is starting to run out, time to enter renewing state */
				state = RENEWING;
				listen_mode = LISTEN_KERNEL;
				DEBUG(LOG_INFO, "Entering renew state");
				/* fall right through */
			case RENEWING:
				/* Either set a new T1, or enter REBINDING state */
				if ((t2 - t1) <= (lease / 14400 + 1)) {
					/* timed out, enter rebinding state */
					state = REBINDING;
					timeout = time(0) + (t2 - t1);
					DEBUG(LOG_INFO, "Entering rebinding state");
				} else {
					/* send a request packet */
					send_renew(xid, server_addr, requested_ip); /* unicast */
					
					t1 = (t2 - t1) / 2 + t1;
					timeout = t1 + start;
				}
				break;
			case REBINDING:
				/* Either set a new T2, or enter INIT state */
				if ((lease - t2) <= (lease / 14400 + 1)) {
					/* timed out, enter init state */
					state = INIT_SELECTING;
					LOG(LOG_INFO, "Lease lost, entering init state");
					run_script(NULL, "deconfig");
					timeout = time(0);
					packet_num = 0;
					listen_mode = LISTEN_RAW;
				} else {
					/* send a request packet */
					send_renew(xid, 0, requested_ip); /* broadcast */

					t2 = (lease - t2) / 2 + t2;
					timeout = t2 + start;
				}
				break;
			case RELEASED:
				/* yah, I know, *you* say it would never happen */
				timeout = 0xffffffff;
				break;
			}
		} else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) {
			/* a packet is ready, read it */
			
			if (listen_mode == LISTEN_KERNEL) {
				if (get_packet(&packet, fd) < 0) continue;
			} else {
				if (get_raw_packet(&packet, fd) < 0) continue;
			} 
			
			if (packet.xid != xid) {
				DEBUG(LOG_INFO, "Ignoring XID %lx (our xid is %lx)",
					(unsigned long) packet.xid, xid);
				continue;
			}
			
			if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) {
				DEBUG(LOG_ERR, "couldnt get option from packet -- ignoring");
				continue;
			}
			
			switch (state) {
			case INIT_SELECTING:
				/* Must be a DHCPOFFER to one of our xid's */
				if (*message == DHCPOFFER) {
					if ((temp = get_option(&packet, DHCP_SERVER_ID))) {
						memcpy(&server_addr, temp, 4);
						xid = packet.xid;
						requested_ip = packet.yiaddr;
						
						/* enter requesting state */
						state = REQUESTING;
						timeout = time(0);
						packet_num = 0;
					} else {
						DEBUG(LOG_ERR, "No server ID in message");
					}
				}
				break;
			case RENEW_REQUESTED:
			case REQUESTING:
			case RENEWING:
			case REBINDING:
				if (*message == DHCPACK) {
					if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) {
						LOG(LOG_ERR, "No lease time with ACK, using 1 hour lease");
						lease = 60*60;
					} else {
						memcpy(&lease, temp, 4);
						lease = ntohl(lease);
					}
						
					/* enter bound state */
					t1 = lease / 2;
					
					/* little fixed point for n * .875 */
					t2 = (lease * 0x7) >> 3;
					temp_addr.s_addr = packet.yiaddr;
					LOG(LOG_INFO, "Lease of %s obtained, lease time %ld", 
						inet_ntoa(temp_addr), lease);
					start = time(0);
					timeout = t1 + start;
					requested_ip = packet.yiaddr;
					run_script(&packet,
						   ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));

					state = BOUND;
					listen_mode = LISTEN_NONE;
					
					// brcm
					setStatus(1);
					background();
					
				} else if (*message == DHCPNAK) {
					/* return to init state */
					LOG(LOG_INFO, "Received DHCP NAK");
					if (state != REQUESTING)
						run_script(NULL, "deconfig");
					state = INIT_SELECTING;
					timeout = time(0);
					requested_ip = 0;
					packet_num = 0;
					listen_mode = LISTEN_RAW;

					// brcm
					setStatus(0);
				}
				break;
			case BOUND:
			case RELEASED:
				/* ignore all packets */
				break;
			}					
		} else if (retval == -1 && errno == EINTR) {
Example #5
0
void BuddyEditor::updateBackground()
{
    if (m_updating || background() == 0)
        return;
    ConnectionEdit::updateBackground();

    m_updating = true;
    QList<Connection *> newList;
    const LabelList label_list = background()->findChildren<QLabel*>();
    foreach (QLabel *label, label_list) {
        const QString buddy_name = buddy(label, m_formWindow->core());
        if (buddy_name.isEmpty())
            continue;

        const QList<QWidget *> targets = background()->findChildren<QWidget*>(buddy_name);
        if (targets.isEmpty())
            continue;

        QWidget *target = 0;

        QListIterator<QWidget *> it(targets);
        while (it.hasNext()) {
            QWidget *widget = it.next();
            if (widget && !widget->isHidden()) {
                target = widget;
                break;
            }
        }

        if (target == 0)
            continue;

        Connection *con = new Connection(this);
        con->setEndPoint(EndPoint::Source, label, widgetRect(label).center());
        con->setEndPoint(EndPoint::Target, target, widgetRect(target).center());
        newList.append(con);
    }

    QList<Connection *> toRemove;

    const int c = connectionCount();
    for (int i = 0; i < c; i++) {
        Connection *con = connection(i);
        QObject *source = con->object(EndPoint::Source);
        QObject *target = con->object(EndPoint::Target);
        bool found = false;
        QListIterator<Connection *> it(newList);
        while (it.hasNext()) {
            Connection *newConn = it.next();
            if (newConn->object(EndPoint::Source) == source && newConn->object(EndPoint::Target) == target) {
                found = true;
                break;
            }
        }
        if (found == false)
            toRemove.append(con);
    }
    if (!toRemove.isEmpty()) {
        DeleteConnectionsCommand command(this, toRemove);
        command.redo();
        foreach (Connection *con, toRemove)
            delete takeConnection(con);
    }

    QListIterator<Connection *> it(newList);
    while (it.hasNext()) {
        Connection *newConn = it.next();

        bool found = false;
        const int c = connectionCount();
        for (int i = 0; i < c; i++) {
            Connection *con = connection(i);
            if (con->object(EndPoint::Source) == newConn->object(EndPoint::Source) &&
                            con->object(EndPoint::Target) == newConn->object(EndPoint::Target)) {
                found = true;
                break;
            }
        }
        if (found == false) {
            AddConnectionCommand command(this, newConn);
            command.redo();
        } else {
            delete newConn;
        }
    }
    m_updating = false;
}
void setup() {
	size(640, 360);
	background(204);
	x = width / 2;
	y = height / 2;
}
Example #7
0
void main_menu_dlg::on_init_dialog()
{
	h_screen_paradigm scr_paradigm = get_framework()->get_screen_paradigm();
	h_string suffix = get_framework()->get_screen_paradigm_suffix(scr_paradigm);

	scene_manager* scene_manager = get_ctrl()->get_scene_manager();

	int w_scr = get_framework()->get_display_settings().width;
	int h_scr = get_framework()->get_display_settings().height;
	set_size(h_vector((float)w_scr, (float)h_scr));

	h_scene_object_base_ptr background(new h_scene_object_base("background_panel"));
	add_child(background);
	background->add_sprite("/images/menu/dlg_base" + suffix, "background_panel");
	background->set_pos(scene_manager->get_scene_center() - background->get_size() / 2);

	//scene_manager* scene_manager = get_ctrl()->get_scene_manager();

	static const float height_button_t0[3] = { 43, 73, 86 };
	static const float height_button_t1[3] = { 65, 111, 130 };

	static const float width_button[3] = { 165, 280, 329 };

	h_button_ptr button_sel_tree;
	h_button_ptr button_sel_background;
	h_button_ptr button_share_social;
	h_button_ptr button_email;
	h_button_ptr button_to_img;
	h_button_ptr button_clear;


	h_vector offset_img(0, 0);
	// select tree..
	{
		/*button_sel_tree.reset(new h_button("select_tree"));
		add_child(button_sel_tree); 

		h_vector pos_coord_img_tl = h_vector(0, 0) + offset_img;
		h_vector pos_coord_img_br = h_vector(width_button[scr_paradigm], height_button_t0[scr_paradigm]) + offset_img;
		button_sel_tree->load_images("/images/menu/menu_buttons_0" + suffix, 
									 pos_coord_img_tl, pos_coord_img_br,
									 pos_coord_img_tl, pos_coord_img_br);
		button_sel_tree->set_action(std::tr1::bind(&scene_manager::on_change_tree, 
													get_ctrl()->get_scene_manager()));
		offset_img += h_vector(0, height_button_t0[scr_paradigm]);*/
	}
	 
	// select background..
	{

		button_sel_background.reset(new h_button("select_background"));
		background->add_child(button_sel_background); 

		h_vector pos_coord_img_tl = h_vector(0, 0) + offset_img;
		h_vector pos_coord_img_br = h_vector(width_button[scr_paradigm], height_button_t0[scr_paradigm]) + offset_img;
		button_sel_background->load_images("/images/menu/menu_buttons_0" + suffix, 
									 pos_coord_img_tl, pos_coord_img_br,
									 pos_coord_img_tl, pos_coord_img_br);
		button_sel_background->set_action(std::tr1::bind(&scene_manager::on_change_background, 
												   get_ctrl()->get_scene_manager()));
		offset_img += h_vector(0, height_button_t0[scr_paradigm]);
	}

	// share to social..
	{

		//button_share_social.reset(new h_button("share_social"));
		//background->add_child(button_share_social); 

		//h_vector pos_coord_img_tl = h_vector(0, 0) + offset_img;
		//h_vector pos_coord_img_br = h_vector(width_button[scr_paradigm], height_button_t1[scr_paradigm]) + offset_img;
		//button_share_social->load_images("/images/menu/menu_buttons_0" + suffix, 
		//							 pos_coord_img_tl, pos_coord_img_br,
		//							 pos_coord_img_tl, pos_coord_img_br);
		////button_sel_tree->set_action(std::tr1::bind(&scene_manager::on_select_toys_dlg, 
		////							get_ctrl()->get_scene_manager(), dlg_balls));
		//offset_img += h_vector(0, height_button_t1[scr_paradigm]);
	}


	// export to image..
	{

		button_to_img.reset(new h_button("to_img"));
		background->add_child(button_to_img); 

		h_vector pos_coord_img_tl = h_vector(0, 0) + offset_img;
		h_vector pos_coord_img_br = h_vector(width_button[scr_paradigm], height_button_t1[scr_paradigm]) + offset_img;
		button_to_img->load_images("/images/menu/menu_buttons_0" + suffix, 
									 pos_coord_img_tl, pos_coord_img_br,
									 pos_coord_img_tl, pos_coord_img_br);
		button_to_img->set_action(std::tr1::bind(&scene_manager::on_export_image, 
									get_ctrl()->get_scene_manager()));
		offset_img += h_vector(0, height_button_t1[scr_paradigm]);
	}

	// send..
	{

		button_email.reset(new h_button("email"));
		background->add_child(button_email); 

		h_vector pos_coord_img_tl = h_vector(0, 0) + offset_img;
		h_vector pos_coord_img_br = h_vector(width_button[scr_paradigm], height_button_t0[scr_paradigm]) + offset_img;
		button_email->load_images("/images/menu/menu_buttons_0" + suffix, 
									 pos_coord_img_tl, pos_coord_img_br,
									 pos_coord_img_tl, pos_coord_img_br);
		button_email->set_action(std::tr1::bind(&scene_manager::send_email, 
									get_ctrl()->get_scene_manager()));
		offset_img += h_vector(0, height_button_t0[scr_paradigm]);
	}


	// clear..
	{
		button_clear.reset(new h_button("clear"));
		background->add_child(button_clear); 

		h_vector pos_coord_img_tl = h_vector(0, 0) + offset_img;
		h_vector pos_coord_img_br = h_vector(width_button[scr_paradigm], height_button_t0[scr_paradigm]) + offset_img;
		button_clear->load_images("/images/menu/menu_buttons_0" + suffix, 
									 pos_coord_img_tl, pos_coord_img_br,
									 pos_coord_img_tl, pos_coord_img_br);
		button_clear->set_action(std::tr1::bind(&scene_manager::on_clear, 
									get_ctrl()->get_scene_manager()));
		//offset_img += h_vector(0, height_button_t0[scr_paradigm]);
	}
	h_scene_object_ptr buttons[g_num_buttons] = { button_sel_background, 
												  button_to_img,
												  button_email,
												  button_clear };
	float height_all_buttons = 0;
	for (int i = 0; i < g_num_buttons; i++)	{
		height_all_buttons += buttons[i]->get_size().y;
		buttons[i]->get_sprites()->get_sprite(0)->set_filter(true);
	}

	float w = buttons[0]->get_size().x;

	float menu_height = background->get_size().y;
	float v = menu_height - height_all_buttons;
	float vx = background->get_size().x - w;

	float seg = v / (g_num_buttons + 1);
	float y_offset = background->get_size().y;
	for (int i = 0; i < g_num_buttons; i++)
	{
		float height = buttons[i]->get_size().y;
		y_offset += -height;//seg; 
		buttons[i]->set_pos(h_vector(vx / 2, y_offset - v / 2));
	}
	
	h_vector center = scene_manager->get_scene_center() - get_size() / 2;
	h_vector start_pos = h_vector(center.x, -get_size().y);
	h_vector end_pos(center);
	//static const float offset_from_center[3] = { 35, 70, 0 };
	//offset_pos(h_vector(0, offset_from_center[scr_paradigm]));

	h_transition_ptr trans(new h_transition_position(start_pos, end_pos, 170));
	add_transition(trans, true);
	trans->start();
}
void Heroes::MeetingDialog(Heroes & heroes2)
{
    if(Settings::Get().QVGA()) return PocketPC::HeroesMeeting(*this, heroes2);

    Display & display = Display::Get();

    // cursor
    Cursor & cursor = Cursor::Get();
    cursor.Hide();
    cursor.SetThemes(cursor.POINTER);

    const Sprite &backSprite = AGG::GetICN(ICN::SWAPWIN, 0);
    const Point cur_pt((display.w() - backSprite.w()) / 2, (display.h() - backSprite.h()) / 2);
    SpriteBack background(Rect(cur_pt, backSprite.w(), backSprite.h()));
    Point dst_pt(cur_pt);
    std::string message;

    Rect src_rt(0, 0, 640, 480);

    // background
    dst_pt.x = cur_pt.x;
    dst_pt.y = cur_pt.y;
    backSprite.Blit(src_rt, dst_pt);

    // header
    message = _("%{name1} meets %{name2}");
    StringReplace(message, "%{name1}", GetName());
    StringReplace(message, "%{name2}", heroes2.GetName());
    Text text(message, Font::BIG);
    text.Blit(cur_pt.x + 320 - text.w() / 2, cur_pt.y + 26);

    // portrait
    dst_pt.x = cur_pt.x + 93;
    dst_pt.y = cur_pt.y + 72;
    PortraitRedraw(dst_pt.x, dst_pt.y, PORT_BIG, display);

    dst_pt.x = cur_pt.x + 445;
    dst_pt.y = cur_pt.y + 72;
    heroes2.PortraitRedraw(dst_pt.x, dst_pt.y, PORT_BIG, display);

    dst_pt.x = cur_pt.x + 34;
    dst_pt.y = cur_pt.y + 75;
    MoraleIndicator moraleIndicator1(*this);
    moraleIndicator1.SetPos(dst_pt);
    moraleIndicator1.Redraw();

    dst_pt.x = cur_pt.x + 34;
    dst_pt.y = cur_pt.y + 115;
    LuckIndicator luckIndicator1(*this);
    luckIndicator1.SetPos(dst_pt);
    luckIndicator1.Redraw();

    dst_pt.x = cur_pt.x + 566;
    dst_pt.y = cur_pt.y + 75;
    MoraleIndicator moraleIndicator2(heroes2);
    moraleIndicator2.SetPos(dst_pt);
    moraleIndicator2.Redraw();

    dst_pt.x = cur_pt.x + 566;
    dst_pt.y = cur_pt.y + 115;
    LuckIndicator luckIndicator2(heroes2);
    luckIndicator2.SetPos(dst_pt);
    luckIndicator2.Redraw();

    // primary skill
    SpriteBack backPrimary(Rect(cur_pt.x + 255, cur_pt.y + 50, 130, 135));

    PrimarySkillsBar primskill_bar1(this, true);
    primskill_bar1.SetColRows(1, 4);
    primskill_bar1.SetVSpace(-1);
    primskill_bar1.SetTextOff(70, -25);
    primskill_bar1.SetPos(cur_pt.x + 216, cur_pt.y + 51);

    PrimarySkillsBar primskill_bar2(&heroes2, true);
    primskill_bar2.SetColRows(1, 4);
    primskill_bar2.SetVSpace(-1);
    primskill_bar2.SetTextOff(-70, -25);
    primskill_bar2.SetPos(cur_pt.x + 389, cur_pt.y + 51);

    RedrawPrimarySkillInfo(cur_pt, &primskill_bar1, &primskill_bar2);

    // secondary skill
    SecondarySkillsBar secskill_bar1;
    secskill_bar1.SetColRows(8, 1);
    secskill_bar1.SetHSpace(-1);
    secskill_bar1.SetContent(secondary_skills);
    secskill_bar1.SetPos(cur_pt.x + 22, cur_pt.y + 199);
    secskill_bar1.Redraw();

    SecondarySkillsBar secskill_bar2;
    secskill_bar2.SetColRows(8, 1);
    secskill_bar2.SetHSpace(-1);
    secskill_bar2.SetContent(heroes2.GetSecondarySkills());
    secskill_bar2.SetPos(cur_pt.x + 353, cur_pt.y + 199);
    secskill_bar2.Redraw();

    // army
    dst_pt.x = cur_pt.x + 36;
    dst_pt.y = cur_pt.y + 267;

    ArmyBar selectArmy1(&GetArmy(), true, false);
    selectArmy1.SetColRows(5, 1);
    selectArmy1.SetPos(dst_pt.x, dst_pt.y);
    selectArmy1.SetHSpace(2);
    selectArmy1.Redraw();

    dst_pt.x = cur_pt.x + 381;
    dst_pt.y = cur_pt.y + 267;

    ArmyBar selectArmy2(&heroes2.GetArmy(), true, false);
    selectArmy2.SetColRows(5, 1);
    selectArmy2.SetPos(dst_pt.x, dst_pt.y);
    selectArmy2.SetHSpace(2);
    selectArmy2.Redraw();

    // artifact
    dst_pt.x = cur_pt.x + 23;
    dst_pt.y = cur_pt.y + 347;

    ArtifactsBar selectArtifacts1(this, true, false);
    selectArtifacts1.SetColRows(7, 2);
    selectArtifacts1.SetHSpace(2);
    selectArtifacts1.SetVSpace(2);
    selectArtifacts1.SetContent(GetBagArtifacts());
    selectArtifacts1.SetPos(dst_pt.x, dst_pt.y);
    selectArtifacts1.Redraw();

    dst_pt.x = cur_pt.x + 367;
    dst_pt.y = cur_pt.y + 347;

    ArtifactsBar selectArtifacts2(&heroes2, true, false);
    selectArtifacts2.SetColRows(7, 2);
    selectArtifacts2.SetHSpace(2);
    selectArtifacts2.SetVSpace(2);
    selectArtifacts2.SetContent(heroes2.GetBagArtifacts());
    selectArtifacts2.SetPos(dst_pt.x, dst_pt.y);
    selectArtifacts2.Redraw();

    // button exit
    dst_pt.x = cur_pt.x + 280;
    dst_pt.y = cur_pt.y + 428;
    Button buttonExit(dst_pt.x, dst_pt.y, ICN::SWAPBTN, 0, 1);

    buttonExit.Draw();

    cursor.Show();
    display.Flip();

    MovePointsScaleFixed();
    heroes2.MovePointsScaleFixed();

    // scholar action
    if(Settings::Get().ExtWorldEyeEagleAsScholar())
	Heroes::ScholarAction(*this, heroes2);

    LocalEvent & le = LocalEvent::Get();

    // message loop
    while(le.HandleEvents())
    {
        le.MousePressLeft(buttonExit) ? buttonExit.PressDraw() : buttonExit.ReleaseDraw();
        if(le.MouseClickLeft(buttonExit) || HotKeyCloseWindow) break;

	// selector troops event
	if((le.MouseCursor(selectArmy1.GetArea()) &&
    	    selectArmy1.QueueEventProcessing(selectArmy2)) ||
	   (le.MouseCursor(selectArmy2.GetArea()) &&
    	    selectArmy2.QueueEventProcessing(selectArmy1)))
	{
	    cursor.Hide();

	    if(selectArtifacts1.isSelected()) selectArtifacts1.ResetSelected();
	    else
	    if(selectArtifacts2.isSelected()) selectArtifacts2.ResetSelected();

	    selectArmy1.Redraw();
	    selectArmy2.Redraw();

	    moraleIndicator1.Redraw();
	    moraleIndicator2.Redraw();
	    luckIndicator1.Redraw();
	    luckIndicator2.Redraw();
	    cursor.Show();
	    display.Flip();
	}

	// selector artifacts event
	if((le.MouseCursor(selectArtifacts1.GetArea()) &&
    	    selectArtifacts1.QueueEventProcessing(selectArtifacts2)) ||
	   (le.MouseCursor(selectArtifacts2.GetArea()) &&
    	    selectArtifacts2.QueueEventProcessing(selectArtifacts1)))
	{
	    cursor.Hide();

	    if(selectArmy1.isSelected()) selectArmy1.ResetSelected();
	    else
	    if(selectArmy2.isSelected()) selectArmy2.ResetSelected();

	    selectArtifacts1.Redraw();
	    selectArtifacts2.Redraw();

	    backPrimary.Restore();
	    RedrawPrimarySkillInfo(cur_pt, &primskill_bar1, &primskill_bar2);
	    moraleIndicator1.Redraw();
	    moraleIndicator2.Redraw();
	    luckIndicator1.Redraw();
	    luckIndicator2.Redraw();
	    cursor.Show();
	    display.Flip();
	}

        if((le.MouseCursor(primskill_bar1.GetArea()) && primskill_bar1.QueueEventProcessing()) ||
           (le.MouseCursor(primskill_bar2.GetArea()) && primskill_bar2.QueueEventProcessing()) ||
           (le.MouseCursor(secskill_bar1.GetArea()) && secskill_bar1.QueueEventProcessing()) ||
           (le.MouseCursor(secskill_bar2.GetArea()) && secskill_bar2.QueueEventProcessing()))
	{
	    cursor.Show();
	    display.Flip();
	}

        if(le.MouseCursor(moraleIndicator1.GetArea())) MoraleIndicator::QueueEventProcessing(moraleIndicator1);
        else
        if(le.MouseCursor(moraleIndicator2.GetArea())) MoraleIndicator::QueueEventProcessing(moraleIndicator2);
	else
        if(le.MouseCursor(luckIndicator1.GetArea())) LuckIndicator::QueueEventProcessing(luckIndicator1);
        else
        if(le.MouseCursor(luckIndicator2.GetArea())) LuckIndicator::QueueEventProcessing(luckIndicator2);
    }

    if(Settings::Get().ExtHeroRecalculateMovement())
    {
	RecalculateMovePoints();
	heroes2.RecalculateMovePoints();
    }

    cursor.Hide();
    background.Restore();
    cursor.Show();
    display.Flip();
}
Example #9
0
int App::start(const std::vector<CL_String> &args)
{
	CL_OpenGLWindowDescription description;
	description.set_title("NightVision Shader");
	description.set_size(CL_Size(1024, 768), true);

	CL_DisplayWindow window(description);
	CL_InputDevice keyboard = window.get_ic().get_keyboard();
	CL_GraphicContext gc = window.get_gc();

	CL_Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &App::on_input_up);

	CL_Slot slot_window_close = window.sig_window_close().connect(this, &App::window_close);

	// Create offscreen texture
	CL_Texture texture_offscreen(gc, gc.get_width(), gc.get_height());
	texture_offscreen.set_min_filter(cl_filter_nearest);
	texture_offscreen.set_mag_filter(cl_filter_nearest);

	CL_Texture texture_mask(gc, gc.get_width(), gc.get_height());
	texture_mask.set_min_filter(cl_filter_nearest);
	texture_mask.set_mag_filter(cl_filter_nearest);

	// Create offscreen framebuffer
	CL_FrameBuffer framebuffer_offscreen(gc);
	framebuffer_offscreen.attach_color_buffer(0, texture_offscreen);

	CL_FrameBuffer framebuffer_mask(gc);
	framebuffer_mask.attach_color_buffer(0, texture_mask);

	CL_Image background(gc, "../PostProcessing/Resources/background.png");
	CL_Image ball(gc, "../PostProcessing/Resources/ball.png");
	ball.set_alignment(origin_center);
	CL_Texture noise_texture(gc, "Resources/noise_texture_0001.png");
	noise_texture.set_wrap_mode(cl_wrap_repeat, cl_wrap_repeat);

	// Load and link shaders
	CL_ProgramObject shader = CL_ProgramObject::load(gc, "Resources/vertex_shader.glsl", "Resources/fragment_shader.glsl");
	shader.bind_attribute_location(0, "Position");
	shader.bind_attribute_location(2, "TexCoord0");
	if (!shader.link())
		throw CL_Exception("Unable to link shader program: Error:" + shader.get_info_log());

	quit = false;

	float amount = 0.0f;
	float timer = 0.0f;

	float scale = 1.0f;

	CL_Font font(gc, "tahoma", 32);

	// Shader based on: http://www.geeks3d.com/20091009/shader-library-night-vision-post-processing-filter-glsl/

	elapsedTime = 0.0f; // seconds
	luminanceThreshold = 0.2f;
	colorAmplification = 4.0f;
	effectCoverage = 0.65f;

	// Render the mask
	gc.set_frame_buffer(framebuffer_mask);
	gc.clear();
	for (float offset=0.0f; offset<=1.0f; offset+=0.01f)
	{
		CL_Draw::circle(gc, gc.get_width() / 2.0f,  gc.get_height() / 2.0f, 400.0f - offset * 64.0f, CL_Colorf(offset, offset, offset, 1.0f));
	}
	gc.reset_frame_buffer();

	unsigned int startTime = CL_System::get_time();

	while (!quit)
	{
		timer = (CL_System::get_time() - startTime) / 1000.0f;

		elapsedTime = timer;

		// Render standard image to offscreen buffer
		gc.set_frame_buffer(framebuffer_offscreen);
		background.draw(gc, 0, 0);
		ball.draw(gc, gc.get_width() / 2 + 200 * sinf(timer / 2.0f), gc.get_height() / 2 + 200 * cosf(timer / 2.0f));
		gc.reset_frame_buffer();

		render_night_vision(gc, texture_offscreen, texture_mask, noise_texture, shader);

		const int gap = 32;
		font.draw_text(gc, 10, 64+gap*0, CL_String("luminanceThreshold : " + CL_StringHelp::float_to_text(luminanceThreshold) + " (Press Q,W)" ));
		font.draw_text(gc, 10, 64+gap*1, CL_String("colorAmplification : " + CL_StringHelp::float_to_text(colorAmplification) + " (Press A,S)" ));
		font.draw_text(gc, 10, 64+gap*2, CL_String("effectCoverage : " + CL_StringHelp::float_to_text(effectCoverage) + " (Press Z,X)" ));

		window.flip();

		CL_System::sleep(10);

		CL_KeepAlive::process();
	}

	return 0;
}
//----------------------------------------------------------
void ofCairoRenderer::background(float brightness) {
	background(ofColor(brightness));
}
/**
 * Parse a given XmlReader objest that represents the map.
 *
 * @param reader Reference to a XmlReader object representing a given XML file.
 */
void
Window::parse(XmlReader& reader)
{
    // parse attributes...
    XmlReader::AttributeIterator iter(reader);
    while(iter.next()) {
        const char* name = (const char*) iter.getName();
        const char* value = (const char*) iter.getValue();

        if(parseAttribute(name, value)) {
            continue;
        } else if(strcmp(name, "width") == 0) {
            if(sscanf(value, "%f", &width) != 1) {
                std::stringstream msg;
                msg << "Couldn't parse width attribute (" << value << ").";
                throw std::runtime_error(msg.str());
            }
        } else if(strcmp(name, "height") == 0) {
            if(sscanf(value, "%f", &height) != 1) {
                std::stringstream msg;
                msg << "Couldn't parse height attribute (" << value << ").";
                throw std::runtime_error(msg.str());
            }
        } else if(strcmp(name, "border") == 0) {
            if(sscanf(value, "%f", &border) != 1) {
                std::stringstream msg;
                msg << "Couldn't parse border attribute (" << value << ").";
                throw std::runtime_error(msg.str());
            }
        } else if(strcmp(name, "titlesize") == 0) {
            if(sscanf(value, "%f", &titlesize) != 1) {
                std::stringstream msg;
                msg << "Couldn't parse titlesize attribute (" << value << ").";
                throw std::runtime_error(msg.str());
            }
        } else {
            std::cerr << "Unknown attribute '" << name << "' skipped.\n";
        }
    }
    if(width <= 0 || height <= 0)
        throw std::runtime_error("Width or Height invalid");

    childs.assign(5, Child());

    int depth = reader.getDepth();
    while(reader.read() && reader.getDepth() > depth) {
        if(reader.getNodeType() == XML_READER_TYPE_ELEMENT) {
            std::string element = (const char*) reader.getName();
            if(element == "title") {
                resetChild(title(), parseEmbeddedComponent(reader));
            } else if(element == "closebutton") {
                std::auto_ptr<Button> button (new Button());
                button->parse(reader);
                resetChild(closeButton(), button.release());
            } else if(element == "contents") {
                resetChild(contents(), parseEmbeddedComponent(reader));
            } else if(element == "background") {
                resetChild(background(), parseEmbeddedComponent(reader));
            } else if(element == "title-background") {
                resetChild(title_background(), parseEmbeddedComponent(reader));
            } else {
                std::cerr << "Skipping unknown element '"
                    << element << "'.\n";
                reader.nextNode();
            }
        }
    }

    // layout
    float closeButtonHeight = 0;
    float closeButtonWidth = 0;
    float closeButtonBorder = 0;
    if(closeButton().getComponent() != 0) {
        closeButtonHeight = closeButton().getComponent()->getHeight();
        if(titlesize < closeButtonHeight) {
            titlesize = closeButtonHeight;
        }

        closeButtonWidth = closeButton().getComponent()->getWidth();
        closeButtonBorder = (titlesize - closeButtonHeight) / 2;
        closeButtonWidth += 2*closeButtonBorder;
        closeButtonHeight += 2*closeButtonBorder;
    }

    float compWidth = width - 2*border;
    float compHeight = height - 2*border;
    title().setPos(Vector2(border, border));
    title().getComponent()->resize(compWidth - closeButtonWidth, titlesize);
    if(title_background().getComponent() != 0) {
        title_background().setPos(title().getPos());
        title_background().getComponent()->resize(
                compWidth - closeButtonWidth, titlesize);
    }
    if(closeButton().getComponent() != 0) {
        closeButton().setPos(Vector2(
                    border + compWidth - closeButtonWidth + closeButtonBorder,
                    border + closeButtonBorder));
    }
    contents().setPos(Vector2(border, border + titlesize));
    contents().getComponent()->resize(compWidth, compHeight - titlesize);
    if(background().getComponent() != 0) {
        background().setPos(Vector2(0, 0));
        background().getComponent()->resize(width, height);
    }

    // connect signals...
    if(closeButton().getComponent() != 0) {
        Button* button = (Button*) closeButton().getComponent();
        button->clicked.connect(
                makeCallback(*this, &Window::closeButtonClicked));
    }
}
Example #12
0
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
    // Request a 24-bits depth buffer when creating the window
    sf::ContextSettings contextSettings;
    contextSettings.depthBits = 24;

    // Create the main window
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML graphics with OpenGL", sf::Style::Default, contextSettings);
    window.setVerticalSyncEnabled(true);

    // Create a sprite for the background
    sf::Texture backgroundTexture;
    if (!backgroundTexture.loadFromFile("resources/background.jpg"))
        return EXIT_FAILURE;
    sf::Sprite background(backgroundTexture);

    // Create some text to draw on top of our OpenGL object
    sf::Font font;
    if (!font.loadFromFile("resources/sansation.ttf"))
        return EXIT_FAILURE;
    sf::Text text("SFML / OpenGL demo", font);
    text.setColor(sf::Color(255, 255, 255, 170));
    text.setPosition(250.f, 450.f);

    // Make the window the active target for OpenGL calls
    // Note: If using sf::Texture or sf::Shader with OpenGL,
    // be sure to call sf::Texture::getMaximumSize() and/or
    // sf::Shader::isAvailable() at least once before calling
    // setActive(), as those functions will cause a context switch
    window.setActive();

    // Load an OpenGL texture.
    // We could directly use a sf::Texture as an OpenGL texture (with its Bind() member function),
    // but here we want more control on it (generate mipmaps, ...) so we create a new one from an image
    GLuint texture = 0;
    {
        sf::Image image;
        if (!image.loadFromFile("resources/texture.jpg"))
            return EXIT_FAILURE;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    }

    // Enable Z-buffer read and write
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
    glClearDepth(1.f);

    // Disable lighting
    glDisable(GL_LIGHTING);

    // Configure the viewport (the same size as the window)
    glViewport(0, 0, window.getSize().x, window.getSize().y);

    // Setup a perspective projection
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    GLfloat ratio = static_cast<float>(window.getSize().x) / window.getSize().y;
    glFrustum(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);

    // Bind the texture
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);

    // Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices)
    static const GLfloat cube[] =
    {
        // positions    // texture coordinates
        -20, -20, -20,  0, 0,
        -20,  20, -20,  1, 0,
        -20, -20,  20,  0, 1,
        -20, -20,  20,  0, 1,
        -20,  20, -20,  1, 0,
        -20,  20,  20,  1, 1,

         20, -20, -20,  0, 0,
         20,  20, -20,  1, 0,
         20, -20,  20,  0, 1,
         20, -20,  20,  0, 1,
         20,  20, -20,  1, 0,
         20,  20,  20,  1, 1,

        -20, -20, -20,  0, 0,
         20, -20, -20,  1, 0,
        -20, -20,  20,  0, 1,
        -20, -20,  20,  0, 1,
         20, -20, -20,  1, 0,
         20, -20,  20,  1, 1,

        -20,  20, -20,  0, 0,
         20,  20, -20,  1, 0,
        -20,  20,  20,  0, 1,
        -20,  20,  20,  0, 1,
         20,  20, -20,  1, 0,
         20,  20,  20,  1, 1,

        -20, -20, -20,  0, 0,
         20, -20, -20,  1, 0,
        -20,  20, -20,  0, 1,
        -20,  20, -20,  0, 1,
         20, -20, -20,  1, 0,
         20,  20, -20,  1, 1,

        -20, -20,  20,  0, 0,
         20, -20,  20,  1, 0,
        -20,  20,  20,  0, 1,
        -20,  20,  20,  0, 1,
         20, -20,  20,  1, 0,
         20,  20,  20,  1, 1
    };

    // Enable position and texture coordinates vertex components
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glVertexPointer(3, GL_FLOAT, 5 * sizeof(GLfloat), cube);
    glTexCoordPointer(2, GL_FLOAT, 5 * sizeof(GLfloat), cube + 3);

    // Disable normal and color vertex components
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);

    // Create a clock for measuring the time elapsed
    sf::Clock clock;

    // Start game loop
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close window: exit
            if (event.type == sf::Event::Closed)
                window.close();

            // Escape key: exit
            if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
                window.close();

            // Adjust the viewport when the window is resized
            if (event.type == sf::Event::Resized)
                glViewport(0, 0, event.size.width, event.size.height);
        }

        // Draw the background
        window.pushGLStates();
        window.draw(background);
        window.popGLStates();

        // Clear the depth buffer
        glClear(GL_DEPTH_BUFFER_BIT);

        // We get the position of the mouse cursor, so that we can move the box accordingly
        float x =  sf::Mouse::getPosition(window).x * 200.f / window.getSize().x - 100.f;
        float y = -sf::Mouse::getPosition(window).y * 200.f / window.getSize().y + 100.f;

        // Apply some transformations
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glTranslatef(x, y, -100.f);
        glRotatef(clock.getElapsedTime().asSeconds() * 50.f, 1.f, 0.f, 0.f);
        glRotatef(clock.getElapsedTime().asSeconds() * 30.f, 0.f, 1.f, 0.f);
        glRotatef(clock.getElapsedTime().asSeconds() * 90.f, 0.f, 0.f, 1.f);

        // Draw the cube
        glDrawArrays(GL_TRIANGLES, 0, 36);

        // Draw some text on top of our OpenGL object
        window.pushGLStates();
        window.draw(text);
        window.popGLStates();

        // Finally, display the rendered frame on screen
        window.display();
    }

    // Don't forget to destroy our texture
    glDeleteTextures(1, &texture);

    return EXIT_SUCCESS;
}
int main()
{
  try {
    vpHomogeneousMatrix cdMo(0, 0, 0.75, 0, 0, 0);
    vpHomogeneousMatrix cMo(0.15, -0.1, 1., vpMath::rad(10), vpMath::rad(-10), vpMath::rad(50));

    // Define the target as 4 points
    vpPoint point[4] ;
    point[0].setWorldCoordinates(-0.1,-0.1, 0);
    point[1].setWorldCoordinates( 0.1,-0.1, 0);
    point[2].setWorldCoordinates( 0.1, 0.1, 0);
    point[3].setWorldCoordinates(-0.1, 0.1, 0);

#if defined(VISP_HAVE_OGRE)
    // Color image used as background texture.
    vpImage<unsigned char> background(480, 640, 255);

    // Parameters of our camera
    vpCameraParameters cam(840, 840, background.getWidth()/2, background.getHeight()/2);

    // Our object
    // A simulator with the camera parameters defined above,
    // and the background image size
    vpAROgre ogre;
    ogre.setShowConfigDialog(false);
    ogre.setCameraParameters(cam);
    ogre.addResource("./"); // Add the path to the Sphere.mesh resource
    ogre.init(background, false, true);

    // Create the scene that contains 4 spheres
    // Sphere.mesh contains a sphere with 1 meter radius
    std::vector<std::string> name(4);
    for (unsigned int i=0; i<4; i++) {
      std::ostringstream s; s << "Sphere" <<  i; name[i] = s.str();
      ogre.load(name[i], "Sphere.mesh");
      ogre.setScale(name[i], 0.02f, 0.02f, 0.02f); // Rescale the sphere to 2 cm radius
      // Set the position of each sphere in the object frame
      ogre.setPosition(name[i], vpTranslationVector(point[i].get_oX(), point[i].get_oY(), point[i].get_oZ()));
    }

    // Add an optional point light source
    Ogre::Light * light = ogre.getSceneManager()->createLight();
    light->setDiffuseColour(1, 1, 1); // scaled RGB values
    light->setSpecularColour(1, 1, 1); // scaled RGB values
    light->setPosition((Ogre::Real)cdMo[0][3], (Ogre::Real)cdMo[1][3], (Ogre::Real)(-cdMo[2][3]));
    light->setType(Ogre::Light::LT_POINT);
#endif

    vpServo task ;
    task.setServo(vpServo::EYEINHAND_CAMERA);
    task.setInteractionMatrixType(vpServo::CURRENT);
    task.setLambda(0.5);

    vpFeaturePoint p[4], pd[4] ;
    for (int i = 0 ; i < 4 ; i++) {
      point[i].track(cdMo);
      vpFeatureBuilder::create(pd[i], point[i]);
      point[i].track(cMo);
      vpFeatureBuilder::create(p[i], point[i]);
      task.addFeature(p[i], pd[i]);
    }

    vpHomogeneousMatrix wMc, wMo;
    vpSimulatorCamera robot;
    robot.setSamplingTime(0.040);
    robot.getPosition(wMc);
    wMo = wMc * cMo;

    for (unsigned int iter=0; iter < 150; iter ++) {
      robot.getPosition(wMc);
      cMo = wMc.inverse() * wMo;
      for (int i = 0 ; i < 4 ; i++) {
        point[i].track(cMo);
        vpFeatureBuilder::create(p[i], point[i]);
      }
#if defined(VISP_HAVE_OGRE)
      // Update the scene from the new camera position
      ogre.display(background, cMo);
#endif
      vpColVector v = task.computeControlLaw();
      robot.setVelocity(vpRobot::CAMERA_FRAME, v);
      vpTime::wait( robot.getSamplingTime() * 1000);
    }
    task.kill();
  }
  catch(vpException &e) {
    std::cout << "Catch an exception: " << e << std::endl;
  }
  catch(...) {
    std::cout << "Catch an exception " << std::endl;
  }
}
Example #14
0
void MSTableColumn::updateBackground(unsigned long oldbg_)
{
  MSWidget::updateBackground(oldbg_);
  textMSGC().foreground(background());
  redraw();
}
Example #15
0
void *TextEdit::processEvent(Event *e)
{
    if (m_param == NULL)
        return NULL;
    if (e->type() == EventCheckState){
        CommandDef *cmd = (CommandDef*)(e->param());
        if (cmd->param != m_param)
            return NULL;
        switch (cmd->id){
        case CmdBgColor:
        case CmdFgColor:
        case CmdBold:
        case CmdItalic:
        case CmdUnderline:
        case CmdFont:
            if ((textFormat() == RichText) && !isReadOnly()){
                cmd->flags &= ~BTN_HIDE;
            }else{
                cmd->flags |= BTN_HIDE;
            }
            return e->param();
        default:
            return NULL;
        }
    }
    if (e->type() == EventCommandExec){
        CommandDef *cmd = (CommandDef*)(e->param());
        if (cmd->param != m_param)
            return NULL;
        switch (cmd->id){
        case CmdBgColor:{
                Event eWidget(EventCommandWidget, cmd);
                CToolButton *btnBg = (CToolButton*)(eWidget.process());
                if (btnBg){
                    ColorPopup *popup = new ColorPopup(this, background());
                    popup->move(CToolButton::popupPos(btnBg, popup));
                    connect(popup, SIGNAL(colorChanged(QColor)), this, SLOT(bgColorChanged(QColor)));
                    popup->show();
                }
                return e->param();
            }
        case CmdFgColor:{
                Event eWidget(EventCommandWidget, cmd);
                CToolButton *btnFg = (CToolButton*)(eWidget.process());
                if (btnFg){
                    ColorPopup *popup = new ColorPopup(this, foreground());
                    popup->move(CToolButton::popupPos(btnFg, popup));
                    connect(popup, SIGNAL(colorChanged(QColor)), this, SLOT(fgColorChanged(QColor)));
                    popup->show();
                }
                return e->param();
            }
        case CmdBold:
            if (!m_bChanged){
                m_bSelected = true;
                setBold((cmd->flags & COMMAND_CHECKED) != 0);
            }
            return e->param();
        case CmdItalic:
            if (!m_bChanged){
                m_bSelected = true;
                setItalic((cmd->flags & COMMAND_CHECKED) != 0);
            }
            return e->param();
        case CmdUnderline:
            if (!m_bChanged){
                m_bSelected = true;
                setUnderline((cmd->flags & COMMAND_CHECKED) != 0);
            }
            return e->param();
        case CmdFont:{
#ifdef USE_KDE
                QFont f = font();
                if (KFontDialog::getFont(f, false, topLevelWidget()) != KFontDialog::Accepted)
                    break;
#else
                bool ok = false;
                QFont f = QFontDialog::getFont(&ok, font(), topLevelWidget());
                if (!ok)
                    break;
#endif
                m_bSelected = true;
                setCurrentFont(f);
                break;
            }
        default:
            return NULL;
        }
    }
    return NULL;
}
Example #16
0
/*******************************************************************************************

  > BOOL BitmapPreviewData::GenerateHTMLStub(BrowserPreviewOptions BrowserOptions)
  
	Author: 	Stefan_Stoykov (Xara Group Ltd) <[email protected]> 
	Created:	24/6/97
	Inputs: 	BrowserOptions - the options for generating the html page
	Purpose:	Generate a html file which includes our bitmap, together with some other optional 
				stuff. Used for browser preview.
				
*******************************************************************************************/
BOOL BitmapPreviewData::GenerateHTMLStub(BrowserPreviewOptions BrowserOptions)
{
PORTNOTE("other","Removed _R(IDD_TIMAPOPTIONS) - isn't wanted yet")
#ifndef EXCLUDE_FROM_XARALX
	// sanity checks
	
	// check for export options
	
	ERROR3IF(m_pOptions == NULL, "BitmapPreviewData::GenerateHTMLStub - need export options");
	if (m_pOptions == NULL) // we need export options
		return FALSE;
	
	// get the path for the exported bitmap from the options
	PathName TempPath = m_pOptions->GetPathName();
	
	// check for exported bitmap
	ERROR3IF((m_pOptions->HasTempFile() == FALSE) || (TempPath.IsValid() == FALSE), 
		"BitmapPreviewData::GenerateHTMLStub - need exported bitmap");
	if ((m_pOptions->HasTempFile() == FALSE) || (TempPath.IsValid() == FALSE)) 
		return FALSE;
	
	// delete the previous temp file, if any
	if (m_pTempHTMLPath != NULL)
		FileUtil::DeleteFile(m_pTempHTMLPath);
	else
		m_pTempHTMLPath = new PathName;
	
	// safety check
	if (m_pTempHTMLPath == NULL)
		return FALSE;
	
	// create a new temp file 
	if (FileUtil::GetTemporaryPathName( _T("htm"),m_pTempHTMLPath) == FALSE)
	{
		delete m_pTempHTMLPath;
		m_pTempHTMLPath = NULL;
		
		return FALSE;
	}
	
	// start creating the html page
	
	// create a disk file
	CCDiskFile TempDiskFile(1024, FALSE, TRUE);
	
	// get path name to server, so we can find the logo bitmaps
	CString str;
	AfxGetModuleShortFileName(AfxGetInstanceHandle(), str);
	String_256 strPathName(str.GetBuffer(0));
	
	// create a path name object from the program name
	PathName ProgramPath(strPathName);
	
	try
	{
		// open it for reading
		if (!TempDiskFile.open(*m_pTempHTMLPath, ios::out))
			return FALSE;
		
		// output header
		String_256 s(_R(IDS_HTML_HEAD));
		TempDiskFile.write(s);
		
		// set the background attributes
		switch (BrowserOptions.m_Background)
		{
		case BROWSER_BGR_DOC:
			{
				// set the background from the document page
				if (!SetBackgroundFromPage(TempDiskFile, BrowserOptions.m_pSpread))
					ERROR3("Setting the html background from the document page failed\n");
			}
			break;
			
		case BROWSER_BGR_CHECKER:
			{
				// display the checkered bitmap as background
				
				// get the checkered bitmap name
				String_256 Checker(_R(IDS_HTML_CHECKER));
				
				// set it in the path
				ProgramPath.SetFileNameAndType(Checker);
				
				// set the checkered bitmap as background image
				s.MakeMsg(_R(IDS_CHECK_BACK), (TCHAR *)ProgramPath.GetWebAddress());
				TempDiskFile.write(s);
			}
			break;
			
		case BROWSER_BGR_BITMAP:
			{
				// set our bitmap as background image
				s.MakeMsg(_R(IDS_BITMAPED_BACKGROUND), (TCHAR *)TempPath.GetWebAddress());
				TempDiskFile.write(s);
				
				
			}
			break;
			
		case BROWSER_BGR_NONE:
			{
				String_256 background(_R(IDS_PLAIN_BACKGROUND));
				TempDiskFile.write(background);
			}
			
			break;
			
		default:
			ERROR3("Unknown type of BrowserOptions.m_Background");
			break;
		} // end of switch(BrowserOptions.m_Background) block
		
		// Get a pointer to the actual bitmap so that we can get some details from it.
		//		OILBitmap *pOilBitmap = m_pBitmap->ActualBitmap;
		//		ERROR3IF(pOilBitmap == NULL,"BitmapPreviewData::GenerateBitmapInfoStrings NULL oil bitmap pointer");
		
		// Get the details from the specified bitmap
		//		BitmapInfo BmInfo;
		//		pOilBitmap->GetInfo(&BmInfo);
		
		// output our bitmap, but only if it wasn't already set as background
		String_256 s2(_R(IDS_PAGE_TITLE));
		TempDiskFile.write(s2);
		
		if (BrowserOptions.m_Background != BROWSER_BGR_BITMAP)
		{
			// output the bitmap
			
			if (m_pOptions->GetFilterType() == MAKE_BITMAP_FILTER)
			{
				// GIF animation
				s.MakeMsg(_R(IDS_DISPLAY_PIC), (const TCHAR *)TempPath.GetFileName());
			}
			else
			{
				if( m_pOptions->GetFilterNameStrID() == _R(IDN_FILTERNAME_GIF) ||
					m_pOptions->GetFilterNameStrID() == _R(IDS_JPG_EXP_FILTERNAME) ||
					m_pOptions->GetFilterNameStrID() == _R(IDT_FILTERNAME_BMP) )
				{
					s.MakeMsg(_R(IDS_DISPLAY_BMP), (const TCHAR *)TempPath.GetFileName());
				}
				else
				if( m_pOptions->GetFilterNameStrID() == _R(IDS_FILTERNAME_PNG) )
					s.MakeMsg(_R(IDS_DISPLAY_PNG), (const TCHAR *)TempPath.GetFileName());
			}	
			
			TempDiskFile.write(s);
		}
		else
		{
			s.MakeMsg(_R(IDS_EMPTY_BOX));
			TempDiskFile.write(s);
			
		}
		
		switch (m_pOptions->GetFilterNameStrID())
		{
		case _R(IDT_FILTERNAME_BMP):
			s2.MakeMsg(_R(IDS_BMP_MESSAGE));
			s.MakeMsg(_R(IDS_WARNING_BOX), (TCHAR *)s2);
			TempDiskFile.write(s);
			break;
		case _R(IDS_FILTERNAME_PNG):
			s2.MakeMsg(_R(IDS_PNG_MESSAGE));
			s.MakeMsg(_R(IDS_WARNING_BOX), (TCHAR *)s2);
			TempDiskFile.write(s);
			break;
		} // end of switch(m_pOptions->GetFilterNameStrID())
		
		s.MakeMsg(_R(IDS_DETAILS_BUILD));
		TempDiskFile.write(s);
		
		// output the bitmap info, if requested
		if (BrowserOptions.m_bInfo != FALSE)
		{
			String_64 ImageSize;
			String_64 FileSize;
			BOOL m_bTransparent = FALSE;
			INT32 count;
			count=0;
			// generate the info strings
			
			if (m_pOptions->GetFilterType() == MAKE_BITMAP_FILTER)
			{
				// This is actually the export animated GIF using the frame gallery system
				MakeBitmapExportOptions* pMkBOptions = (MakeBitmapExportOptions*)m_pOptions;
				ERROR3IF(!pMkBOptions->IS_KIND_OF(MakeBitmapExportOptions), "pMkBOptions isn't");
				
				PALETTE Palette = PAL_OPTIMISED;
				DITHER DitherType;
				UINT32 colDepth;
				String_64 sPalette;
				String_64 Dither;
				UINT32 NoOfColours;
				
				NoOfColours=m_pOptions->GetNumColsInPalette();
				//						Palette = pMkBOptions->GetPalette();
				DitherType = pMkBOptions->GetDither();
				colDepth = pMkBOptions->GetDepth();
				
				s2.MakeMsg(_R(IDS_ANIMATED_GIF));
				
				if (pMkBOptions->WantTransparent())
				{
					s2.MakeMsg(_R(IDS_TRANSPARENT),"animated GIF");
				}
				
				s.MakeMsg(_R(IDS_TEXTLINE_BR),(const TCHAR*)s2);
				TempDiskFile.write(s);
				
				switch (Palette)
				{
				case PAL_OPTIMISED:
					sPalette.MakeMsg(_R(IDS_OPTIMISED_PAL));
					break;
				case PAL_BROWSER:
				case PAL_STANDARD:
					sPalette.MakeMsg(_R(IDS_BROWSER_PAL));
					break;
				case PAL_GLOBALOPTIMISED:
					sPalette.MakeMsg(_R(IDS_GLOBAL_OPT));
					break;
					
				}
				
				if (colDepth == 8 && (Palette == PAL_STANDARD || Palette == PAL_BROWSER) )
				{
					NoOfColours = 216;
				}
				
				switch (colDepth)
				{
				case 32:
				case 24:
					s2.MakeMsg(_R(IDS_TRUECOLOUR),colDepth);
					break;
				case 8:
					{
						// Include the transparent colour in the colour depth check
						UINT32 RealNumberOfColours = NoOfColours;
						if (colDepth <= 8 && pMkBOptions->WantTransparent())
						{
							UINT32 MaxColours = UINT32(pow(2,colDepth));
							RealNumberOfColours++;
							if (RealNumberOfColours > MaxColours)
								RealNumberOfColours = MaxColours;
						}
						// We say 8 but we really mean the number of colours deep
						// We cannot say 2 colours = 2bpp as we save it as 10 colours due
						// to having 1 transparent colour and the usual lets pick 10 as the
						// transparent colour. Cannot allow the user to choose 1 as the code
						// then outputs 8bpp as GRenderOptPalette::GetOptimisedPalette has the
						// test if (ReservedColours < NumColours), which fails.
						/* if (RealNumberOfColours <= 2)
						s2.MakeMsg(_R(IDS_PALETTEINFO),2,NoOfColours,(const TCHAR*)sPalette);
						else */
						if (RealNumberOfColours <= 16)
							s2.MakeMsg(_R(IDS_PALETTEINFO),4,NoOfColours,(const TCHAR*)sPalette);
						else
							s2.MakeMsg(_R(IDS_AN_PALINFO),colDepth,NoOfColours,(const TCHAR*)sPalette);
						break;
					}
				case 1:
					s2.MakeMsg(_R(IDS_MONO),colDepth);
					break;
				case 4:
				default:
					s2.MakeMsg(_R(IDS_PALETTEINFO),colDepth,NoOfColours,(const TCHAR*)sPalette);					
					break;
				}
				
				TempDiskFile.write(s2); 				
				
				s.MakeMsg(_R(IDS_NODITHER));
				switch (DitherType)
				{
				case XARADITHER_ORDERED:
				case XARADITHER_ORDERED_GREY:
					Dither.MakeMsg(_R(IDS_DITH_ORDER));
					s.MakeMsg(_R(IDS_DITHERING),(const TCHAR*) Dither);
					break;
				case XARADITHER_ERROR_DIFFUSION:
				case XARADITHER_SIMPLE:
					Dither.MakeMsg(_R(IDS_DITH_ERROR));
					s.MakeMsg(_R(IDS_DITHERING),(const TCHAR*) Dither);
					break;
				case XARADITHER_NONE:
					s.MakeMsg(_R(IDS_NODITHER));
					break;
				}
				
				TempDiskFile.write(s);
			} // if (m_pOptions->GetFilterType() == MAKE_BITMAP_FILTER) block ends
			else
			{
				switch (m_pOptions->GetFilterNameStrID())
				{
				case _R(IDN_FILTERNAME_GIF):
					{
						GIFExportOptions* pGIFOptions = (GIFExportOptions*)m_pOptions;
						ERROR3IF(!pGIFOptions->IS_KIND_OF(GIFExportOptions), "pGIFOptions isn't");
						PALETTE Palette = PAL_OPTIMISED;
						DITHER DitherType;
						UINT32 colDepth;
						String_64 sPalette;
						String_64 Dither;
						UINT32 NoOfColours;
						
						NoOfColours=m_pOptions->GetNumColsInPalette();
						//						Palette = pGIFOptions->GetPalette();
						DitherType = pGIFOptions->GetDither();
						colDepth = pGIFOptions->GetDepth();
						
						
						if (pGIFOptions->WantTransparent())
							count=count+1;
						
						if (pGIFOptions->WantInterlaced())
							count=count+2;
						
						s.MakeMsg(_R(IDS_GIF));
						s2.MakeMsg(_R(IDS_A), (const TCHAR*)s);
						
						switch (count)
						{
						case 1:
							s2.MakeMsg(_R(IDS_TRANSPARENT),"GIF");
							break;
						case 2:
							s2.MakeMsg(_R(IDS_INTERLACED),"GIF");
							break;
						case 3:
							s2.MakeMsg(_R(IDS_INTER_TRANS),"GIF");
							break;
						case 0:
							break;
						}
						
						s.MakeMsg(_R(IDS_TEXTLINE_BR),(const TCHAR*)s2);
						TempDiskFile.write(s);
						
						switch (Palette)
						{
						case PAL_OPTIMISED:
							sPalette.MakeMsg(_R(IDS_OPTIMISED_PAL));
							break;
						case PAL_BROWSER:
						case PAL_STANDARD:
							sPalette.MakeMsg(_R(IDS_BROWSER_PAL));
							break;
						case PAL_GLOBALOPTIMISED:
							sPalette.MakeMsg(_R(IDS_GLOBAL_OPT));
							break;
							
						}
						
						if (colDepth == 8 && (Palette == PAL_STANDARD || Palette == PAL_BROWSER) )
						{
							NoOfColours = 216;
						}
						
						s2.MakeMsg(_R(IDS_PALETTEINFO),colDepth,NoOfColours,(const TCHAR*)sPalette);					
						
						if (colDepth == 8)
							s2.MakeMsg(_R(IDS_AN_PALINFO),colDepth,NoOfColours,(const TCHAR*)sPalette);
						
						if (colDepth == 1)
							s2.MakeMsg(_R(IDS_MONO),colDepth);
						
						if (colDepth > 8)
							s2.MakeMsg(_R(IDS_TRUECOLOUR),colDepth);
						
						TempDiskFile.write(s2); 				
						
						s.MakeMsg(_R(IDS_NODITHER));
						switch (DitherType)
						{
						case XARADITHER_ORDERED:
						case XARADITHER_ORDERED_GREY:
							Dither.MakeMsg(_R(IDS_DITH_ORDER));
							s.MakeMsg(_R(IDS_DITHERING),(const TCHAR*) Dither);
							break;
						case XARADITHER_ERROR_DIFFUSION:
						case XARADITHER_SIMPLE:
							Dither.MakeMsg(_R(IDS_DITH_ERROR));
							s.MakeMsg(_R(IDS_DITHERING),(const TCHAR*) Dither);
							break;
						case XARADITHER_NONE:
							s.MakeMsg(_R(IDS_NODITHER));
							break;
						}
						
						TempDiskFile.write(s);
						
						
					} // end case _R(IDN_FILTERNAME_GIF)
					break;
				case _R(IDS_JPG_EXP_FILTERNAME): 
					{
						JPEGExportOptions* pJPEGOptions = (JPEGExportOptions *)m_pOptions;
						ERROR3IF(!pJPEGOptions->IS_KIND_OF(JPEGExportOptions), "pJPEGOptions isn't");
						INT32 Quality = pJPEGOptions->GetQuality();	// Default Quality
						BOOL Progressive = pJPEGOptions->DoAsProgressive();
						if (Quality > 100)
							Quality = 100;
						
						
						s.MakeMsg(_R(IDS_JPEG));
						s2.MakeMsg(_R(IDS_A), (const TCHAR*)s);
						
						if (Progressive)
							s2.MakeMsg(_R(IDS_PROGRESSIVE));
						
						s.MakeMsg(_R(IDS_TEXTLINE_BR),(const TCHAR*)s2);
						TempDiskFile.write(s);
						
						
						s.MakeMsg(_R(IDS_JCOMPRESSION),Quality);
						TempDiskFile.write(s);					
					} // end case _R(IDS_JPG_EXP_FILTERNAME)
					break;
					
				case _R(IDT_FILTERNAME_BMP):
					{
						BMPExportOptions* pBMPOptions = (BMPExportOptions*)m_pOptions;
						ERROR3IF(!pBMPOptions->IS_KIND_OF(BMPExportOptions), "pBMPOptions isn't");
						PALETTE Palette;
						DITHER DitherType;
						UINT32 colDepth;
						String_64 sPalette;
						String_64 Dither;
						UINT32 NoOfColours;
						
						NoOfColours=m_pOptions->GetNumColsInPalette();
						Palette = pBMPOptions->GetPalette();
						DitherType = pBMPOptions->GetDither();
						colDepth = pBMPOptions->GetDepth();
						
						s.MakeMsg(_R(IDS_BMP));
						s2.MakeMsg(_R(IDS_A), (const TCHAR*)s);
						
						s.MakeMsg(_R(IDS_TEXTLINE_BR),(const TCHAR*)s2);
						TempDiskFile.write(s);
						
						switch (Palette)
						{
						case PAL_OPTIMISED:
							sPalette.MakeMsg(_R(IDS_OPTIMISED_PAL));
							break;
						case PAL_BROWSER:
						case PAL_STANDARD:
							sPalette.MakeMsg(_R(IDS_BROWSER_PAL));
							break;
						case PAL_GLOBALOPTIMISED:
							sPalette.MakeMsg(_R(IDS_GLOBAL_OPT));
							break;
						}
						
						if (colDepth == 8 && (Palette == PAL_STANDARD || Palette == PAL_BROWSER) )
						{
							NoOfColours = 216;
						}
						
						if (colDepth == 8 && NoOfColours > 256)
							NoOfColours = 256;
						
						s2.MakeMsg(_R(IDS_PALETTEINFO),colDepth,NoOfColours,(const TCHAR*)sPalette);					
						
						if (colDepth == 8)
							s2.MakeMsg(_R(IDS_AN_PALINFO),colDepth,NoOfColours,(const TCHAR*)sPalette);
						
						if (colDepth == 1)
							s2.MakeMsg(_R(IDS_MONO),colDepth);
						
						if (colDepth > 8)
							s2.MakeMsg(_R(IDS_TRUECOLOUR),colDepth);
						
						TempDiskFile.write(s2); 				
						
						s.MakeMsg(_R(IDS_NODITHER));
						switch (DitherType)
						{
						case XARADITHER_ORDERED:
						case XARADITHER_ORDERED_GREY:
							Dither.MakeMsg(_R(IDS_DITH_ORDER));
							s.MakeMsg(_R(IDS_DITHERING),(const TCHAR*) Dither);
							break;
						case XARADITHER_ERROR_DIFFUSION:
						case XARADITHER_SIMPLE:
							Dither.MakeMsg(_R(IDS_DITH_ERROR));
							s.MakeMsg(_R(IDS_DITHERING),(const TCHAR*) Dither);
							break;
						case XARADITHER_NONE:
							s.MakeMsg(_R(IDS_NODITHER));
							break;
						}
						
						TempDiskFile.write(s);
					} // end case _R(IDT_FILTERNAME_BMP)
					break;
					
				case _R(IDS_FILTERNAME_PNG):
					{
						PNGExportOptions* pPNGOptions = (PNGExportOptions*)m_pOptions;
						ERROR3IF(!pPNGOptions->IS_KIND_OF(PNGExportOptions), "pPNGOptions isn't");
						PALETTE Palette = PAL_OPTIMISED;
						DITHER DitherType;
						UINT32 colDepth;
						String_64 sPalette;
						String_64 Dither;
						UINT32 NoOfColours;
						
						NoOfColours=m_pOptions->GetNumColsInPalette();
						
						//						Palette = pPNGOptions->GetPalette();
						DitherType = pPNGOptions->GetDither();
						colDepth = pPNGOptions->GetDepth();
						
						
						if (pPNGOptions->WantTransparent())
							count=count+1;
						
						if (pPNGOptions->WantInterlaced())
							count=count+2;
						
						s.MakeMsg(_R(IDS_PNG));
						s2.MakeMsg(_R(IDS_A), (const TCHAR*)s);
						
						switch (count)
						{
						case 1:
							s2.MakeMsg(_R(IDS_TRANSPARENT),"PNG");
							break;
						case 2:
							s2.MakeMsg(_R(IDS_INTERLACED),"PNG");
							break;
						case 3:
							s2.MakeMsg(_R(IDS_INTER_TRANS),"PNG");
							break;
						case 0:
							break;
						}
						
						s.MakeMsg(_R(IDS_TEXTLINE_BR),(const TCHAR*)s2);
						TempDiskFile.write(s);
						
						switch (Palette)
						{
						case PAL_OPTIMISED:
							sPalette.MakeMsg(_R(IDS_OPTIMISED_PAL));
							break;
						case PAL_BROWSER:
						case PAL_STANDARD:
							sPalette.MakeMsg(_R(IDS_BROWSER_PAL));
							break;
						case PAL_GLOBALOPTIMISED:
							sPalette.MakeMsg(_R(IDS_GLOBAL_OPT));
							break;
						}
						
						if (colDepth == 8 && (Palette == PAL_STANDARD || Palette == PAL_BROWSER) )
						{
							NoOfColours = 216;
						}
						
						s2.MakeMsg(_R(IDS_PALETTEINFO),colDepth,NoOfColours,(const TCHAR*)sPalette);					
						
						if (colDepth == 8)
							s2.MakeMsg(_R(IDS_AN_PALINFO),colDepth,NoOfColours,(const TCHAR*)sPalette);
						
						if (colDepth == 1)
							s2.MakeMsg(_R(IDS_MONO),colDepth);
						
						if (colDepth > 8)
							s2.MakeMsg(_R(IDS_TRUECOLOUR),colDepth);
						
						TempDiskFile.write(s2); 				
						
						s.MakeMsg(_R(IDS_NODITHER));
						switch (DitherType)
						{
						case XARADITHER_ORDERED:
						case XARADITHER_ORDERED_GREY:
							Dither.MakeMsg(_R(IDS_DITH_ORDER));
							s.MakeMsg(_R(IDS_DITHERING),(const TCHAR*) Dither);
							break;
						case XARADITHER_ERROR_DIFFUSION:
						case XARADITHER_SIMPLE:
							Dither.MakeMsg(_R(IDS_DITH_ERROR));
							s.MakeMsg(_R(IDS_DITHERING),(const TCHAR*) Dither);
							break;
						case XARADITHER_NONE:
							s.MakeMsg(_R(IDS_NODITHER));
							break;
						}
						
						TempDiskFile.write(s);
					} // end case _R(IDS_FILTERNAME_PNG)
					
					break;
				} // end switch (m_pOptions->GetFilterNameStrID())
			} // end else block
			
			GenerateBitmapInfoStrings(ImageSize, FileSize);
			
			// output the bitmap info
			s.MakeMsg(_R(IDS_HTML_INFO1), (TCHAR *)ImageSize);
			TempDiskFile.write(s);
			
			// output the bitmap file size info
			s.MakeMsg(_R(IDS_HTML_INFO2), (TCHAR *)FileSize);
			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_CLOSE_CENTER));
			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_TDTR_CLOSE));
			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_BANNER_BOX));
			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_SPEED_BUILD));
			TempDiskFile.write(s);
			//			s.MakeMsg(_R(IDS_SPEED_BUILD2));
			//			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_ES_TR));
			TempDiskFile.write(s);
			
			String_64 times;
			
			s.MakeMsg(_R(IDS_TIME_ENTRY),"14.4k");
			TempDiskFile.write(s);
			CalculateTime(times,14400.0);
			TempDiskFile.write(times);
			s.MakeMsg(_R(IDS_ES_TR));
			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_TIME_ENTRY),"28.8k");
			TempDiskFile.write(s);
			CalculateTime(times,28800.0);
			TempDiskFile.write(times);
			s.MakeMsg(_R(IDS_ES_TR));
			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_TIME_ENTRY),"33.6k");
			TempDiskFile.write(s);
			CalculateTime(times,33600.0);
			TempDiskFile.write(times);
			s.MakeMsg(_R(IDS_ES_TR));
			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_TIME_ENTRY),"57.6k");
			TempDiskFile.write(s);
			CalculateTime(times,57600.0);
			TempDiskFile.write(times);
			s.MakeMsg(_R(IDS_ES_TR));
			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_TIME_ENTRY),"64k");
			TempDiskFile.write(s);
			CalculateTime(times,65536.0);
			TempDiskFile.write(times);
			s.MakeMsg(_R(IDS_ES_TR));
			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_TIME_ENTRY),"128k");
			TempDiskFile.write(s);
			CalculateTime(times,131072.0);
			TempDiskFile.write(times);
			
			//			s.MakeMsg(_R(IDS_ES_TR));
			//			TempDiskFile.write(s);
			
			s.MakeMsg(_R(IDS_SPEED_END));
			TempDiskFile.write(s);
			
			TRACE( _T("m_FileSize = %d"), m_FileSize);
		} // end of if (BrowserOptions.m_bInfo != FALSE)
		
		String_64 webaddy(_R(IDS_HTML_URL_PROGRAM));
		//Mark Howitt, 29/10/97. Setup the _R(IDS_HTML_URL_VISITMSG) To be a TCHAR* Also. It likes it that way!
		String_64 webvmess(_R(IDS_HTML_URL_VISITMSG));
		
		s.MakeMsg(_R(IDS_LINK_BOX),(TCHAR *)webaddy,(TCHAR *)webvmess);
		TempDiskFile.write(s);
		
		//end of my stuff
		
		s.MakeMsg(_R(IDS_END_TABLE));
		TempDiskFile.write(s);
		
		s.MakeMsg(_R(IDS_CLOSE_CENTER));
		TempDiskFile.write(s);
		
		// output the "Exported from" string
		
		// get the xara logo file name
		String_256 Logo(_R(IDS_HTML_XARALOGO));
		
		// set it in the path
		ProgramPath.SetFileNameAndType(Logo);
		
		// get the xara link
		String_256 URL(_R(IDS_HTML_URL_XARA));
		
		// output the xara link and the xara logo
		s.MakeMsg(_R(IDS_HTML_XARA), (TCHAR *)URL, (TCHAR *)ProgramPath.GetWebAddress());
		TempDiskFile.write(s);
		
		// Do not display the Xara X logo bottom right...
		/*
		// get the program logo file name
		Logo.Load(_R(IDS_HTML_PROGRAMLOGO));
		
		// set it in the path
		ProgramPath.SetFileNameAndType(Logo);
		
		// output the program link
		URL.Load(_R(IDS_HTML_URL_PROGRAM));
		s.MakeMsg(_R(IDS_HTML_PROGRAM), (TCHAR *)URL, (TCHAR *)ProgramPath.GetWebAddress());
		TempDiskFile.write(s);
		*/
		
		// output the end of the file
		s.Load(_R(IDS_HTML_END));
		TempDiskFile.write(s);
		
		// close the file
		TempDiskFile.close();
		
		// now export the image map, if the option for that is set
		if (BrowserOptions.m_bImagemap != FALSE)
		{
			// export the image map
			ExportImagemap( TempDiskFile, 
				m_pTempHTMLPath, 
				m_pOptions->GetSelectionType(), 
				m_pOptions->GetDPI(),
				BrowserOptions.m_ifoImagemapOptions);
		}
		
		TCHAR *FileWebAddress =  m_pTempHTMLPath->GetWebAddress();
		
		//Graham 17/9/97
		ProgramPath.SetFileNameAndType(PRODUCT_WEBLINKEXENAME);
		
		const TCHAR *PathToWebLink = (const TCHAR *)ProgramPath.GetPath();
		
		String_256 CmdLine = PathToWebLink + String_256(" -f ") + FileWebAddress;
		//TCHAR *CommandLine = (TCHAR *)CmdLine;
		
		if (!InvokeWeblink(CmdLine))
			return FALSE;
		
	} // end of TRY block
	
	catch( CFileException )
	{
		// any disk problems - come here
		
		// not much we can do really - just close the file and return FALSE
		if (TempDiskFile.isOpen())
			TempDiskFile.close();
		
		return FALSE;
	}
#endif
		
	return TRUE;
}
Example #17
0
//----------------------------------------------------------
void ofGLRenderer::background(const ofColor & c){
	background ( c.r, c.g, c.b, c.a );
}
Example #18
0
void QoccHarnessWindow::createActions()
{
    newAction = new QAction(tr("&New"), this);
    newAction->setShortcut(tr("Ctrl+N"));
    newAction->setStatusTip(tr("Create a new file"));
    connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));

    openAction = new QAction(tr("&Open..."), this);
    openAction->setShortcut(tr("Ctrl+O"));
    openAction->setStatusTip(tr("Open an existing file"));
    connect(openAction, SIGNAL(triggered()), this, SLOT(open()));

    saveAction = new QAction(tr("&Save"), this);
    saveAction->setShortcut(tr("Ctrl+S"));
    saveAction->setStatusTip(tr("Save the document to disk"));
    connect(saveAction, SIGNAL(triggered()), this, SLOT(save()));

    printAction = new QAction(tr("&Print..."), this);
    printAction->setShortcut(tr("Ctrl+P"));
    printAction->setStatusTip(tr("Print the document"));
    connect(printAction, SIGNAL(triggered()), this, SLOT(print()));

    exitAction = new QAction(tr("E&xit"), this);
    exitAction->setShortcut(tr("Ctrl+X"));
    exitAction->setStatusTip(tr("Exit the application"));
    connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));

    undoAction = new QAction(tr("&Undo"), this);
    undoAction->setShortcut(tr("Ctrl+Z"));
    undoAction->setStatusTip(tr("Undo the last operation"));
    connect(undoAction, SIGNAL(triggered()), this, SLOT(undo()));

    redoAction = new QAction(tr("&Redo"), this);
    redoAction->setShortcut(tr("Ctrl+Y"));
    redoAction->setStatusTip(tr("Redo the last operation"));
    connect(redoAction, SIGNAL(triggered()), this, SLOT(redo()));

    cutAction = new QAction(tr("Cu&t"), this);
    cutAction->setShortcut(tr("Ctrl+X"));
    cutAction->setStatusTip(tr("Cut the current selection's contents to the clipboard"));
    connect(cutAction, SIGNAL(triggered()), this, SLOT(cut()));

    copyAction = new QAction(tr("&Copy"), this);
    copyAction->setShortcut(tr("Ctrl+C"));
    copyAction->setStatusTip(tr("Copy the current selection's contents to the clipboard"));
    connect(copyAction, SIGNAL(triggered()), this, SLOT(copy()));

    pasteAction = new QAction(tr("&Paste"), this);
    pasteAction->setShortcut(tr("Ctrl+V"));
    pasteAction->setStatusTip(tr("Paste the clipboard's contents into the current selection"));
    connect(pasteAction, SIGNAL(triggered()), this, SLOT(paste()));

    aboutAction = new QAction(tr("&About"), this);
    aboutAction->setStatusTip(tr("Show the application's About box"));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));

    aboutQtAction = new QAction(tr("About &Qt"), this);
    aboutQtAction->setStatusTip(tr("Show the Qt library's About box"));
    connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(aboutQt()));

	// Now for the QtOCCViewWidget slots.
/*
	fitAction = new QAction(tr("&Fit Window"), this);
	fitAction->setShortcut(tr("Ctrl+F"));
    fitAction->setStatusTip(tr("Fit to window"));
    connect(fitAction, SIGNAL(triggered()), myOCC, SLOT(fitExtents()));
*/
	fitAllAction = new QAction(tr("&Fit All"), this);
	fitAllAction->setShortcut(tr("Ctrl+F"));
    fitAllAction->setStatusTip(tr("Fit contents to viewport"));
    connect(fitAllAction, SIGNAL(triggered()), myOCC, SLOT(fitAll()));

	zoomAction = new QAction(tr("&Zoom"), this);
	zoomAction->setStatusTip(tr("Zoom in window"));
    connect(zoomAction, SIGNAL(triggered()), myOCC, SLOT(fitArea()));

	panAction = new QAction(tr("&Pan"), this);
    panAction->setStatusTip(tr("Window panning"));
    connect(panAction, SIGNAL(triggered()), myOCC, SLOT(pan()));

	rotAction = new QAction(tr("&Rotate"), this);
	rotAction->setShortcut(tr("Ctrl+R"));
    rotAction->setStatusTip(tr("Window rotation"));
    connect(rotAction, SIGNAL(triggered()), myOCC, SLOT(rotation()));

	gridToggleAction = new QAction(tr("Toggle &Grid"), this);
	gridToggleAction->setShortcut(tr("Ctrl+G"));
    gridToggleAction->setStatusTip(tr("Turn the grid on or off"));
    connect(gridToggleAction, SIGNAL(triggered()), myVC, SLOT(gridToggle()));

/*	gridOffAction = new QAction(tr("Gri&d Off"), this);
	gridOffAction->setShortcut(tr("Ctrl+D"));
    gridOffAction->setStatusTip(tr("Turn the grid on"));
    connect(gridOffAction, SIGNAL(triggered()), myVC, SLOT(gridOff()));
*/
	gridXYAction = new QAction(tr("XY Grid"), this);
    gridXYAction->setStatusTip(tr("Grid on XY Plane"));
	//gridOffAction->setShortcut(tr("Ctrl+Z"));
    connect(gridXYAction, SIGNAL(triggered()), myVC, SLOT(gridXY()));

	gridXZAction = new QAction(tr("XZ Grid"), this);
    gridXZAction->setStatusTip(tr("Grid on XZ Plane"));
	//gridXZAction->setShortcut(tr("Ctrl+Y"));
    connect(gridXZAction, SIGNAL(triggered()), myVC, SLOT(gridXZ()));

	gridYZAction = new QAction(tr("YZ Grid"), this);
	gridYZAction->setStatusTip(tr("Grid on YZ Plane"));
	//gridOffAction->setShortcut(tr("Ctrl+Z"));
    connect(gridYZAction, SIGNAL(triggered()), myVC, SLOT(gridYZ()));

	gridRectAction = new QAction(tr("Rectangular"), this);
	gridRectAction->setStatusTip(tr("Retangular grid"));
	//gridOffAction->setShortcut(tr("Ctrl+Z"));
    connect(gridRectAction, SIGNAL(triggered()), myVC, SLOT(gridRect()));

	gridCircAction = new QAction(tr("Circular"), this);
	gridCircAction->setStatusTip(tr("Circular grid"));
	//gridOffAction->setShortcut(tr("Ctrl+Z"));
    connect(gridCircAction, SIGNAL(triggered()), myVC, SLOT(gridCirc()));

	// Standard View

	viewFrontAction = new QAction(tr("Front"), this);
	viewFrontAction->setStatusTip(tr("View From Front"));
    connect(viewFrontAction, SIGNAL(triggered()), myOCC, SLOT(viewFront()));

	viewBackAction = new QAction(tr("Back"), this);
	viewBackAction->setStatusTip(tr("View From Back"));
    connect(viewBackAction, SIGNAL(triggered()), myOCC, SLOT(viewBack()));

	viewTopAction = new QAction(tr("Top"), this);
	viewTopAction->setStatusTip(tr("View From Top"));
    connect(viewTopAction, SIGNAL(triggered()), myOCC, SLOT(viewTop()));

	viewBottomAction = new QAction(tr("Bottom"), this);
	viewBottomAction->setStatusTip(tr("View From Bottom"));
    connect(viewBottomAction, SIGNAL(triggered()), myOCC, SLOT(viewBottom()));

	viewLeftAction = new QAction(tr("Left"), this);
	viewLeftAction->setStatusTip(tr("View From Left"));
    connect(viewLeftAction, SIGNAL(triggered()), myOCC, SLOT(viewLeft()));

	viewRightAction = new QAction(tr("Right"), this);
	viewRightAction->setStatusTip(tr("View From Right"));
    connect(viewRightAction, SIGNAL(triggered()), myOCC, SLOT(viewRight()));

	viewAxoAction = new QAction(tr("&Axonometric Fit"), this);
	viewAxoAction->setStatusTip(tr("Axonometric view and fit all"));
    viewAxoAction->setShortcut(tr("Ctrl+A"));
    connect(viewAxoAction, SIGNAL(triggered()), myOCC, SLOT(viewAxo()));

	viewGridAction = new QAction(tr("Grid"), this);
	viewGridAction->setStatusTip(tr("View from grid"));
    connect(viewGridAction, SIGNAL(triggered()), myOCC, SLOT(viewGrid()));

	viewResetAction = new QAction(tr("Reset"), this);
	viewResetAction->setStatusTip(tr("Reset the view"));
    connect(viewResetAction, SIGNAL(triggered()), myOCC, SLOT(viewReset()));

	backgroundAction = new QAction( tr("&Background"), this );
	backgroundAction->setStatusTip(tr("Change the background colour"));
	connect(backgroundAction, SIGNAL(triggered()), myOCC, SLOT(background()));

	// The co-ordinates from the view
	connect( myOCC, SIGNAL(mouseMoved(V3d_Coordinate,V3d_Coordinate,V3d_Coordinate)),
		     this,   SLOT(xyzPosition(V3d_Coordinate,V3d_Coordinate,V3d_Coordinate)) );

	// Add a point from the view
	connect( myOCC, SIGNAL(pointClicked(V3d_Coordinate,V3d_Coordinate,V3d_Coordinate)),
		     this,   SLOT (addPoint    (V3d_Coordinate,V3d_Coordinate,V3d_Coordinate)) );

	connect( myOCC, SIGNAL(sendStatus(const QString)),
		     this,  SLOT  (statusMessage(const QString)) );

	// And the bottle example

	bottleAction = new QAction(tr("Load &Bottle"), this);
	bottleAction->setShortcut(tr("Ctrl+B"));
    bottleAction->setStatusTip(tr("Bottle sample."));
    connect(bottleAction, SIGNAL(triggered()), this, SLOT(bottle()));

}
Example #19
0
static void client_background(void)
{
	background(client_config.pidfile);
	client_config.foreground = 1; /* Do not fork again. */
	client_config.background_if_no_lease = 0;
}
Example #20
0
void draw_scene(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glDisable(GL_DEPTH_TEST);
    background();
    glEnable(GL_DEPTH_TEST);
    glClear(GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    gluPerspective(45.0f, (GLfloat)window_width / (GLfloat)window_height, 1.0f, 15500.0f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    /*glLightfv(GL_LIGHT0, GL_SPECULAR, whiteSpecularLight);
    glLightfv(GL_LIGHT0, GL_AMBIENT, blackAmbientLight);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, whiteDiffuseLight);*/



    glPushMatrix();
    glTranslatef(0,0,-5);
    print_collected_coins(3.0,1.9,GLUT_BITMAP_HELVETICA_18,"Score:");
    glPopMatrix();

    glPushMatrix();
    glRotatef(rot_x,1,0,0);
    glRotatef(rot_y,0,1,0);
    glRotatef(rot_z,0,0,1);

    glTranslatef(0,0,-85);
    select_camera();

    glPushMatrix();

    make_world();

    //display_powers();
    //display_obstacles();

    glPushMatrix();
    if(!falling && !change_lane)
    {
        r_z += robot_velocity;
        robot_motion = robot_slide?0:1;
    }

    glPushMatrix();
    make_humanoid();
    glPopMatrix();

    /*glPushMatrix();
    glTranslatef(humanoid.loc_x/2.0,20,humanoid.loc_z/2.0 + 20);
    test(1,1,10);
    glPopMatrix();*/

    //spot(humanoid.loc_x/2.0,30,humanoid.loc_z/2.0,0,-1,0);

    //make_spotlight();

    glPopMatrix();

    glPopMatrix();

    glPopMatrix();
    glFlush();
    glutSwapBuffers();
}
//----------------------------------------------------------
void ofGLRenderer::background(float brightness) {
	background(brightness);
}
Example #22
0
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
    // Create the main window
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML OpenGL", sf::Style::Default, sf::ContextSettings(32));
    window.setVerticalSyncEnabled(true);

    // Create a sprite for the background
    sf::Texture backgroundTexture;
    if (!backgroundTexture.loadFromFile("resources/background.jpg"))
        return EXIT_FAILURE;
    sf::Sprite background(backgroundTexture);

    // Load an OpenGL texture.
    // We could directly use a sf::Texture as an OpenGL texture (with its Bind() member function),
    // but here we want more control on it (generate mipmaps, ...) so we create a new one from an image
    GLuint texture = 0;
    {
        sf::Image image;
        if (!image.loadFromFile("resources/texture.jpg"))
            return EXIT_FAILURE;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getSize().x, image.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    }

    // Enable Z-buffer read and write
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
    glClearDepth(1.f);

    // Setup a perspective projection
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(90.f, 1.f, 1.f, 500.f);

    // Bind our texture
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);
    glColor4f(1.f, 1.f, 1.f, 1.f);

    // Create a clock for measuring the time elapsed
    sf::Clock clock;

    // Start game loop
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close window : exit
            if (event.type == sf::Event::Closed)
                window.close();

            // Escape key : exit
            if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
                window.close();

            // Adjust the viewport when the window is resized
            if (event.type == sf::Event::Resized)
                glViewport(0, 0, event.size.width, event.size.height);
        }

        // Draw the background
        window.pushGLStates();
        window.draw(background);
        window.popGLStates();

        // Activate the window before using OpenGL commands.
        // This is useless here because we have only one window which is
        // always the active one, but don't forget it if you use multiple windows
        window.setActive();

        // Clear the depth buffer
        glClear(GL_DEPTH_BUFFER_BIT);

        // We get the position of the mouse cursor, so that we can move the box accordingly
        float x =  sf::Mouse::getPosition(window).x * 200.f / window.getSize().x - 100.f;
        float y = -sf::Mouse::getPosition(window).y * 200.f / window.getSize().y + 100.f;

        // Apply some transformations
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glTranslatef(x, y, -100.f);
        glRotatef(clock.getElapsedTime().asSeconds() * 50.f, 1.f, 0.f, 0.f);
        glRotatef(clock.getElapsedTime().asSeconds() * 30.f, 0.f, 1.f, 0.f);
        glRotatef(clock.getElapsedTime().asSeconds() * 90.f, 0.f, 0.f, 1.f);

        // Draw a cube
        float size = 20.f;
        glBegin(GL_QUADS);

            glTexCoord2f(0, 0); glVertex3f(-size, -size, -size);
            glTexCoord2f(0, 1); glVertex3f(-size,  size, -size);
            glTexCoord2f(1, 1); glVertex3f( size,  size, -size);
            glTexCoord2f(1, 0); glVertex3f( size, -size, -size);

            glTexCoord2f(0, 0); glVertex3f(-size, -size, size);
            glTexCoord2f(0, 1); glVertex3f(-size,  size, size);
            glTexCoord2f(1, 1); glVertex3f( size,  size, size);
            glTexCoord2f(1, 0); glVertex3f( size, -size, size);

            glTexCoord2f(0, 0); glVertex3f(-size, -size, -size);
            glTexCoord2f(0, 1); glVertex3f(-size,  size, -size);
            glTexCoord2f(1, 1); glVertex3f(-size,  size,  size);
            glTexCoord2f(1, 0); glVertex3f(-size, -size,  size);

            glTexCoord2f(0, 0); glVertex3f(size, -size, -size);
            glTexCoord2f(0, 1); glVertex3f(size,  size, -size);
            glTexCoord2f(1, 1); glVertex3f(size,  size,  size);
            glTexCoord2f(1, 0); glVertex3f(size, -size,  size);

            glTexCoord2f(0, 1); glVertex3f(-size, -size,  size);
            glTexCoord2f(0, 0); glVertex3f(-size, -size, -size);
            glTexCoord2f(1, 0); glVertex3f( size, -size, -size);
            glTexCoord2f(1, 1); glVertex3f( size, -size,  size);

            glTexCoord2f(0, 1); glVertex3f(-size, size,  size);
            glTexCoord2f(0, 0); glVertex3f(-size, size, -size);
            glTexCoord2f(1, 0); glVertex3f( size, size, -size);
            glTexCoord2f(1, 1); glVertex3f( size, size,  size);

        glEnd();

        // Draw some text on top of our OpenGL object
        window.pushGLStates();
        sf::Text text("SFML / OpenGL demo");
        text.setColor(sf::Color(255, 255, 255, 170));
        text.setPosition(250.f, 450.f);
        window.draw(text);
        window.popGLStates();

        // Finally, display the rendered frame on screen
        window.display();
    }

    // Don't forget to destroy our texture
    glDeleteTextures(1, &texture);

    return EXIT_SUCCESS;
}
Example #23
0
File: upslog.c Project: alezz/nut
int main(int argc, char **argv)
{
	int	interval = 30, i;
	const char	*prog = xbasename(argv[0]);
	time_t	now, nextpoll = 0;
	const char	*user = NULL;
	struct passwd	*new_uid = NULL;
	const char	*pidfilebase = prog;

	logformat = DEFAULT_LOGFORMAT;
	user = RUN_AS_USER;

	printf("Network UPS Tools %s %s\n", prog, UPS_VERSION);

	 while ((i = getopt(argc, argv, "+hs:l:i:f:u:Vp:")) != -1) {
		switch(i) {
			case 'h':
				help(prog);
				break;

			case 's':
				monhost = optarg;
				break;

			case 'l':
				logfn = optarg;
				break;

			case 'i':
				interval = atoi(optarg);
				break;

			case 'f':
				logformat = optarg;
				break;

			case 'u':
				user = optarg;
				break;

			case 'V':
				exit(EXIT_SUCCESS);

			case 'p':
				pidfilebase = optarg;
				break;
		}
	}

	argc -= optind;
	argv += optind;

	/* not enough args for the old way? */
	if ((argc == 1) || (argc == 2))
		help(prog);

	/* see if it's being called in the old style - 3 or 4 args */

	/* <system> <logfn> <interval> [<format>] */

	if (argc >= 3) {
		monhost = argv[0];
		logfn = argv[1];
		interval = atoi(argv[2]);
	}

	if (argc >= 4) {
		/* read out the remaining argv entries to the format string */

		logformat = xmalloc(LARGEBUF);
		memset(logformat, '\0', LARGEBUF);

		for (i = 3; i < argc; i++)
			snprintfcat(logformat, LARGEBUF, "%s ", argv[i]);
	}

	if (!monhost)
		fatalx(EXIT_FAILURE, "No UPS defined for monitoring - use -s <system>");

	if (!logfn)
		fatalx(EXIT_FAILURE, "No filename defined for logging - use -l <file>");

	/* shouldn't happen */
	if (!logformat)
		fatalx(EXIT_FAILURE, "No format defined - but this should be impossible");

	printf("logging status of %s to %s (%is intervals)\n", 
		monhost, logfn, interval);

	if (upscli_splitname(monhost, &upsname, &hostname, &port) != 0) {
		fatalx(EXIT_FAILURE, "Error: invalid UPS definition.  Required format: upsname[@hostname[:port]]\n");
	}

	if (upscli_connect(&ups, hostname, port, UPSCLI_CONN_TRYSSL) < 0)
		fprintf(stderr, "Warning: initial connect failed: %s\n", 
			upscli_strerror(&ups));

	if (strcmp(logfn, "-") == 0)
		logfile = stdout;
	else
		logfile = fopen(logfn, "a");

	if (logfile == NULL)
		fatal_with_errno(EXIT_FAILURE, "could not open logfile %s", logfn);

	/* now drop root if we have it */
	new_uid = get_user_pwent(user);

	open_syslog(prog); 

	if (logfile != stdout)
		background();

	setup_signals();

	writepid(pidfilebase);

	become_user(new_uid);

	compile_format();

	while (exit_flag == 0) {
		time(&now);

		if (nextpoll > now) {
			/* there is still time left, so sleep it off */
			sleep(difftime(nextpoll, now));
			nextpoll += interval;
		} else {
			/* we spent more time in polling than the interval allows */
			nextpoll = now + interval;
		}

		if (reopen_flag) {
			upslogx(LOG_INFO, "Signal %d: reopening log file", 
				reopen_flag);
			reopen_log();
			reopen_flag = 0;
		}

		/* reconnect if necessary */
		if (upscli_fd(&ups) < 0) {
			upscli_connect(&ups, hostname, port, 0);
		}

		run_flist();

		/* don't keep connection open if we don't intend to use it shortly */
		if (interval > 30) {
			upscli_disconnect(&ups);
		}
	}

	upslogx(LOG_INFO, "Signal %d: exiting", exit_flag);

	if (logfile != stdout)
		fclose(logfile);

	upscli_disconnect(&ups);
	
	exit(EXIT_SUCCESS);
}
Example #24
0
int App::start(const std::vector<std::string> &args)
{
	clan::DisplayWindowDescription description;
	description.set_title("NightVision Shader");
	description.set_size(clan::Size(1024, 768), true);

	clan::DisplayWindow window(description);
	clan::InputDevice keyboard = window.get_ic().get_keyboard();
	clan::Canvas canvas(window);
    clan::SlotContainer cc;

	cc.connect(window.get_ic().get_keyboard().sig_key_up(), clan::bind_member(this, &App::on_input_up));
	cc.connect(window.sig_window_close(), clan::bind_member(this, &App::window_close));

	// Create offscreen texture
	clan::Texture2D texture_offscreen(canvas, canvas.get_width(), canvas.get_height());
	texture_offscreen.set_min_filter(clan::filter_nearest);
	texture_offscreen.set_mag_filter(clan::filter_nearest);

	clan::Texture2D texture_mask(canvas, canvas.get_width(), canvas.get_height());
	texture_mask.set_min_filter(clan::filter_nearest);
	texture_mask.set_mag_filter(clan::filter_nearest);

	// Create offscreen framebuffer
	clan::FrameBuffer framebuffer_offscreen(canvas);
	framebuffer_offscreen.attach_color(0, texture_offscreen);
	clan::Canvas canvas_offscreen(canvas, framebuffer_offscreen);

	clan::FrameBuffer framebuffer_mask(canvas);
	framebuffer_mask.attach_color(0, texture_mask);
	clan::Canvas canvas_mask(canvas, framebuffer_mask);

	clan::Image background(canvas, "../PostProcessing/Resources/background.png");
	clan::Image ball(canvas, "../PostProcessing/Resources/ball.png");
	ball.set_alignment(clan::origin_center);
	clan::Texture2D noise_texture(canvas, "Resources/noise_texture_0001.png");
	noise_texture.set_wrap_mode(clan::wrap_repeat, clan::wrap_repeat);

	// Load and link shaders
	clan::ProgramObject shader = clan::ProgramObject::load(canvas, "Resources/vertex_shader.glsl", "Resources/fragment_shader.glsl");
	shader.bind_attribute_location(0, "Position");
	shader.bind_attribute_location(1, "TexCoord0");
	shader.bind_frag_data_location(0, "cl_FragColor");
	if (!shader.link())
		throw clan::Exception("Unable to link shader program: Error:" + shader.get_info_log());
	shader.set_uniform1i("sceneBuffer", 0);
	shader.set_uniform1i("noiseTex", 1);
	shader.set_uniform1i("maskTex", 2);

	quit = false;

	float amount = 0.0f;
	float timer = 0.0f;

	float scale = 1.0f;

	clan::Font font(canvas, "tahoma", 32);

	// Shader based on: http://www.geeks3d.com/20091009/shader-library-night-vision-post-processing-filter-glsl/

	gpu_positions = clan::VertexArrayVector<clan::Vec2f>(canvas, 6);
	gpu_tex1_coords = clan::VertexArrayVector<clan::Vec2f>(canvas, 6);
	gpu_uniforms = clan::UniformVector<ProgramUniforms>(canvas, 1);
	gpu_primitives_array = clan::PrimitivesArray(canvas);
	gpu_primitives_array.set_attributes(0, gpu_positions);
	gpu_primitives_array.set_attributes(1, gpu_tex1_coords);

	uniforms.elapsedTime = 0.0f; // seconds
	uniforms.luminanceThreshold = 0.2f;
	uniforms.colorAmplification = 4.0f;
	uniforms.effectCoverage = 0.65f;

	// Render the mask
	canvas_mask.clear();
	for (float offset=0.0f; offset<=1.0f; offset+=0.01f)
	{
		canvas_mask.fill_circle(canvas.get_width() / 2.0f,  canvas.get_height() / 2.0f, 400.0f - offset * 64.0f, clan::Colorf(offset, offset, offset, 1.0f));
	}
	canvas_mask.flush();

	clan::ubyte64 startTime = clan::System::get_time();

	while (!quit)
	{
		timer = (clan::System::get_time() - startTime) / 1000.0f;

		uniforms.elapsedTime = timer;

		// Render standard image to offscreen buffer
		background.draw(canvas_offscreen, 0, 0);
		ball.draw(canvas_offscreen, canvas.get_width() / 2 + 200 * sinf(timer / 2.0f), canvas.get_height() / 2 + 200 * cosf(timer / 2.0f));
		canvas_offscreen.flush();

		render_night_vision(canvas, texture_offscreen, texture_mask, noise_texture, shader);

		const int gap = 32;
		font.draw_text(canvas, 10, 64+gap*0, std::string("luminanceThreshold : " + clan::StringHelp::float_to_text(uniforms.luminanceThreshold) + " (Press Q,W)" ));
		font.draw_text(canvas, 10, 64+gap*1, std::string("colorAmplification : " + clan::StringHelp::float_to_text(uniforms.colorAmplification) + " (Press A,S)" ));
		font.draw_text(canvas, 10, 64+gap*2, std::string("effectCoverage : " + clan::StringHelp::float_to_text(uniforms.effectCoverage) + " (Press Z,X)" ));

		window.flip();

		clan::System::sleep(10);

		clan::KeepAlive::process();
	}

	return 0;
}
Example #25
0
File: dhcpc.c Project: foxwolf/yjd
int main(int argc, char *argv[])
#endif
{
	unsigned char *temp, *message;
	unsigned long t1 = 0, t2 = 0, xid = 0;
	unsigned long start = 0, lease;
	fd_set rfds;
	int retval;
	struct timeval tv;
	int c, len;
	struct dhcpMessage packet;
	struct in_addr temp_addr;
	int pid_fd;
	time_t now;
	int max_fd;
	int sig;

	static struct option arg_options[] = {
		{"clientid",	required_argument,	0, 'c'},
		{"foreground",	no_argument,		0, 'f'},
		{"background",	no_argument,		0, 'b'},
		{"hostname",	required_argument,	0, 'H'},
		{"hostname",    required_argument,      0, 'h'},
		{"interface",	required_argument,	0, 'i'},
		{"now", 	no_argument,		0, 'n'},
		{"pidfile",	required_argument,	0, 'p'},
		{"quit",	no_argument,		0, 'q'},
		{"request",	required_argument,	0, 'r'},
		{"script",	required_argument,	0, 's'},
		{"version",	no_argument,		0, 'v'},
		{"help",	no_argument,		0, '?'},
		{0, 0, 0, 0}
	};

	/* get options */
	while (1) {
		int option_index = 0;
		c = getopt_long(argc, argv, "c:fbH:h:i:np:qr:s:v", arg_options, &option_index);
		if (c == -1) break;
		
		switch (c) {
		case 'c':
			len = strlen(optarg) > 255 ? 255 : strlen(optarg);
			if (client_config.clientid) free(client_config.clientid);
			client_config.clientid = xmalloc(len + 2);
			client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
			client_config.clientid[OPT_LEN] = len;
			client_config.clientid[OPT_DATA] = '\0';
			strncpy(client_config.clientid + OPT_DATA, optarg, len);
			break;
		case 'f':
			client_config.foreground = 1;
			break;
		case 'b':
			client_config.background_if_no_lease = 1;
			break;
		case 'h':
		case 'H':
			len = strlen(optarg) > 255 ? 255 : strlen(optarg);
			if (client_config.hostname) free(client_config.hostname);
			client_config.hostname = xmalloc(len + 2);
			client_config.hostname[OPT_CODE] = DHCP_HOST_NAME;
			client_config.hostname[OPT_LEN] = len;
			strncpy(client_config.hostname + 2, optarg, len);
			break;
		case 'i':
			client_config.interface =  optarg;
			break;
		case 'n':
			client_config.abort_if_no_lease = 1;
			break;
		case 'p':
			client_config.pidfile = optarg;
			break;
		case 'q':
			client_config.quit_after_lease = 1;
			break;
		case 'r':
			requested_ip = inet_addr(optarg);
			break;
		case 's':
			client_config.script = optarg;
			break;
		case 'v':
			printf("udhcpcd, version %s\n\n", VERSION);
			exit_client(0);
			break;
		default:
			show_usage();
		}
	}

	OPEN_LOG("udhcpc");
	LOG(LOG_INFO, "udhcp client (v%s) started", VERSION);

	pid_fd = pidfile_acquire(client_config.pidfile);
	pidfile_write_release(pid_fd);

	if (read_interface(client_config.interface, &client_config.ifindex, 
			   NULL, client_config.arp) < 0)
		exit_client(1);
		
	if (!client_config.clientid) {
		client_config.clientid = xmalloc(6 + 3);
		client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
		client_config.clientid[OPT_LEN] = 7;
		client_config.clientid[OPT_DATA] = 1;
		memcpy(client_config.clientid + 3, client_config.arp, 6);
	}

	/* setup signal handlers */
	socketpair(AF_UNIX, SOCK_STREAM, 0, signal_pipe);
	signal(SIGUSR1, signal_handler);
	signal(SIGUSR2, signal_handler);
	signal(SIGTERM, signal_handler);
	
	state = INIT_SELECTING;
	run_script(NULL, "deconfig");
	change_mode(LISTEN_RAW);

	for (;;) {

		tv.tv_sec = timeout - time(0);
		tv.tv_usec = 0;
		FD_ZERO(&rfds);

		if (listen_mode != LISTEN_NONE && fd < 0) {
			if (listen_mode == LISTEN_KERNEL)
				fd = listen_socket(INADDR_ANY, CLIENT_PORT, client_config.interface);
			else
				fd = raw_socket(client_config.ifindex);
			if (fd < 0) {
				LOG(LOG_ERR, "FATAL: couldn't listen on socket, %s", strerror(errno));
				exit_client(0);
			}
		}
		if (fd >= 0) FD_SET(fd, &rfds);
		FD_SET(signal_pipe[0], &rfds);		

		if (tv.tv_sec > 0) {
			DEBUG(LOG_INFO, "Waiting on select...\n");
			max_fd = signal_pipe[0] > fd ? signal_pipe[0] : fd;
			retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
		} else retval = 0; /* If we already timed out, fall through */

		now = time(0);
		if (retval == 0) {
			/* timeout dropped to zero */
			switch (state) {
			case INIT_SELECTING:
				if (packet_num < 3) {
					if (packet_num == 0)
						xid = random_xid();

					/* send discover packet */
					send_discover(xid, requested_ip); /* broadcast */
					
					timeout = now + ((packet_num == 2) ? 4 : 2);
					packet_num++;
				} else {
					if (client_config.background_if_no_lease) {
						LOG(LOG_INFO, "No lease, forking to background.");
						background();
					} else if (client_config.abort_if_no_lease) {
						LOG(LOG_INFO, "No lease, failing.");
						exit_client(1);
				  	}
					/* wait to try again */
					packet_num = 0;
					timeout = now + 60;
				}
				break;
			case RENEW_REQUESTED:
			case REQUESTING:
				if (packet_num < 3) {
					/* send request packet */
					if (state == RENEW_REQUESTED)
						send_renew(xid, server_addr, requested_ip); /* unicast */
					else send_selecting(xid, server_addr, requested_ip); /* broadcast */
					
					timeout = now + ((packet_num == 2) ? 10 : 2);
					packet_num++;
				} else {
					/* timed out, go back to init state */
					if (state == RENEW_REQUESTED) run_script(NULL, "deconfig");
					state = INIT_SELECTING;
					timeout = now;
					packet_num = 0;
					change_mode(LISTEN_RAW);
				}
				break;
			case BOUND:
				/* Lease is starting to run out, time to enter renewing state */
				state = RENEWING;
				change_mode(LISTEN_KERNEL);
				DEBUG(LOG_INFO, "Entering renew state");
				/* fall right through */
			case RENEWING:
				/* Either set a new T1, or enter REBINDING state */
				if ((t2 - t1) <= (lease / 14400 + 1)) {
					/* timed out, enter rebinding state */
					state = REBINDING;
					timeout = now + (t2 - t1);
					DEBUG(LOG_INFO, "Entering rebinding state");
				} else {
					/* send a request packet */
					send_renew(xid, server_addr, requested_ip); /* unicast */
					
					t1 = (t2 - t1) / 2 + t1;
					timeout = t1 + start;
				}
				break;
			case REBINDING:
				/* Either set a new T2, or enter INIT state */
				if ((lease - t2) <= (lease / 14400 + 1)) {
					/* timed out, enter init state */
					state = INIT_SELECTING;
					LOG(LOG_INFO, "Lease lost, entering init state");
					run_script(NULL, "deconfig");
					timeout = now;
					packet_num = 0;
					change_mode(LISTEN_RAW);
				} else {
					/* send a request packet */
					send_renew(xid, 0, requested_ip); /* broadcast */

					t2 = (lease - t2) / 2 + t2;
					timeout = t2 + start;
				}
				break;
			case RELEASED:
				/* yah, I know, *you* say it would never happen */
				timeout = 0x7fffffff;
				break;
			}
		} else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) {
			/* a packet is ready, read it */
			
			if (listen_mode == LISTEN_KERNEL)
				len = get_packet(&packet, fd);
			else len = get_raw_packet(&packet, fd);
			
			if (len == -1 && errno != EINTR) {
				DEBUG(LOG_INFO, "error on read, %s, reopening socket", strerror(errno));
				change_mode(listen_mode); /* just close and reopen */
			}
			if (len < 0) continue;
			
			if (packet.xid != xid) {
				DEBUG(LOG_INFO, "Ignoring XID %lx (our xid is %lx)",
					(unsigned long) packet.xid, xid);
				continue;
			}
			
			if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) {
				DEBUG(LOG_ERR, "couldnt get option from packet -- ignoring");
				continue;
			}
			
			switch (state) {
			case INIT_SELECTING:
				/* Must be a DHCPOFFER to one of our xid's */
				if (*message == DHCPOFFER) {
					if ((temp = get_option(&packet, DHCP_SERVER_ID))) {
						memcpy(&server_addr, temp, 4);
						xid = packet.xid;
						requested_ip = packet.yiaddr;
						
						/* enter requesting state */
						state = REQUESTING;
						timeout = now;
						packet_num = 0;
					} else {
						DEBUG(LOG_ERR, "No server ID in message");
					}
				}
				break;
			case RENEW_REQUESTED:
			case REQUESTING:
			case RENEWING:
			case REBINDING:
				if (*message == DHCPACK) {
					if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) {
						LOG(LOG_ERR, "No lease time with ACK, using 1 hour lease");
						lease = 60 * 60;
					} else {
						memcpy(&lease, temp, 4);
						lease = ntohl(lease);
					}
						
					/* enter bound state */
					t1 = lease / 2;
					
					/* little fixed point for n * .875 */
					t2 = (lease * 0x7) >> 3;
					temp_addr.s_addr = packet.yiaddr;
					LOG(LOG_INFO, "Lease of %s obtained, lease time %ld", 
						inet_ntoa(temp_addr), lease);
					start = now;
					timeout = t1 + start;
					requested_ip = packet.yiaddr;
					run_script(&packet,
						   ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));

					state = BOUND;
					change_mode(LISTEN_NONE);
					if (client_config.quit_after_lease) 
						exit_client(0);
					if (!client_config.foreground)
						background();

				} else if (*message == DHCPNAK) {
					/* return to init state */
					LOG(LOG_INFO, "Received DHCP NAK");
					run_script(&packet, "nak");
					if (state != REQUESTING)
						run_script(NULL, "deconfig");
					state = INIT_SELECTING;
					timeout = now;
					requested_ip = 0;
					packet_num = 0;
					change_mode(LISTEN_RAW);
					sleep(3); /* avoid excessive network traffic */
				}
				break;
			/* case BOUND, RELEASED: - ignore all packets */
			}	
		} else if (retval > 0 && FD_ISSET(signal_pipe[0], &rfds)) {
Example #26
0
void TextCharacters::drawText(MonitorDevice *const pMonitorDevice,
                              const u_color textColor, const uint8_t shiftX, const uint8_t shiftY,
                              const int16_t horizontalShift)
{
    if (m_size.width == 0 || m_size.height == 0)
        return;

    int16_t vAlign;
    if (align & Alignment::Bottom)
        vAlign = m_size.height - font().height;
    else if (align & Alignment::VCenter)
        vAlign = (m_size.height - font().height) / 2 ;
    else // if (align & Alignment::Top)
        vAlign = 0;

    int16_t hAlign;
    if (align & Alignment::Right)
        hAlign = m_size.width - m_pxTextWidth;
    else if (align & Alignment::HCenter)
        hAlign = (m_size.width - m_pxTextWidth) / 2 ;
    else // if (align & Alignment::Left)
        hAlign = 0;
    hAlign += horizontalShift;


    const uint8_t vAlignPos = vAlign < 0 ? abs(vAlign) : 0;
    int16_t posX = new_textAbsPosition.x + hAlign + shiftX;

    const int16_t cx = new_textAbsPosition.x + m_size.width;
    const int16_t cy = new_textAbsPosition.y + m_size.height;

    for (size_t n = 0; n < m_text.length(); ++n)
    {
        const IFont::CHAR_INFO *pDescriptor = descriptor(m_text.at(n));
        const int8_t _yPos = vAlignPos - pDescriptor->fstRow;
        const uint8_t yPos = _yPos < 0 ? 0 : _yPos;

        const uint8_t *pBitmaps = &font().bitmaps()[pDescriptor->position + yPos *
                                  (IFont::Mode::Bitmap == font().mode ? pDescriptor->width / 8 : pDescriptor->width)];
        const int16_t posY = new_textAbsPosition.y + vAlign + pDescriptor->fstRow + shiftY;

        const int16_t yMax = std::min(cy, int16_t(pDescriptor->sizeRow + posY));
        for (uint16_t y = posY + yPos; y < yMax; ++y)
        {
            uint8_t pt = 0;
            int16_t x = posX;
            for (uint8_t width = 0; width < pDescriptor->width; ++width)
            {
                if (IFont::Mode::Bitmap == font().mode)
                {
                    if (x >= cx)
                    {
                        pBitmaps += (pDescriptor->width - width) / 8;
                        break;
                    }

                    const uint8_t nBit = 7 - (width % 8);
                    if (nBit == 7)
                        pt = *(pBitmaps++);
                    if ( x >= new_textAbsPosition.x)
                    {
                        const bool px = pt >> nBit & 0x01;
                        if (!px)
                            pMonitorDevice->drawPoint(x, y, textColor);
                    }
                }
                else  // IFont::Mode::Antialias
                {
                    if (x >= cx)
                    {
                        pBitmaps += pDescriptor->width - width;
                        break;
                    }

                    const uint8_t pt = *(pBitmaps++);
                    if (pt != 0xFFU && x >= new_textAbsPosition.x)
                    {
                        u_color foreground(textColor);
#ifdef RGB888
                        foreground.argb.A = 255 - pt;
                        foreground = pMonitorDevice->alphaBlending(foreground, background());
#elif  RGB565
                        foreground = pMonitorDevice->alphaBlending(foreground, background(), 255 - pt);
#endif
                        pMonitorDevice->drawPoint(x, y, foreground);
                    }
                }
                x++;
            }
        }
        posX += pDescriptor->width;
    }
Example #27
0
void Application::run() {
  sf::RenderWindow window(sf::VideoMode(800, 600), "Asteroids", sf::Style::Close);
  window.setVerticalSyncEnabled(true);

  sf::Texture backgroundTexture;
  backgroundTexture.loadFromFile("data/Background.png");
  sf::Sprite background(backgroundTexture);

  sf::Font agencyFont;
  agencyFont.loadFromFile("data/AGENCYR.TTF");
  sf::Text fpsText("", agencyFont, 20u);

  sf::Time elapsedTimed;
  sf::Clock clock;
  const float fpsUpdateInterval = 0.5f;
  float fpsUpdateTimer = fpsUpdateInterval;
  std::string fpsString;
  sf::String test;
  fpsString.reserve(10);

  // initial GameState is the main menu
  GameState* currentGameState = new MainMenu(window, agencyFont);

  // Mainloop
  while (window.isOpen()) {
    elapsedTimed = clock.restart();

    // Event polling
    sf::Event event;
    while (window.pollEvent(event)) {
      switch (event.type) {
      case sf::Event::Closed:
        window.close();
        break;
      default:
        break;
      }
    }

    fpsUpdateTimer += elapsedTimed.asSeconds();
    if (fpsUpdateTimer >= fpsUpdateInterval) {
      int fps = static_cast<int> (1.0f / elapsedTimed.asSeconds());
      fpsString.clear();
      fpsString.append(std::to_string(fps)).append(" FPS");
      fpsText.setString(fpsString);

      fpsUpdateTimer = 0.0f;
    }

    // polling every frame is bad :(
    if (currentGameState->hasNextState()) {
      // with a loading screen: switch to loading screen state and pass the new state ID to a
      // function of the loading screen state and let it construct the new state in another thread
      // and return the new state somehow (...) when finished

      GameState* nextGameState = nullptr;

      switch (currentGameState->getNextGameStateID()) {
      case GSID_MAINMENU:
        nextGameState = new MainMenu(window, agencyFont);
        break;
      case GSID_OPTIONS:
        nextGameState = new Options(window, agencyFont);
        break;
      case GSID_GAME:
        nextGameState = new Game(window, agencyFont);
        break;
      default:
        nextGameState = new MainMenu(window, agencyFont);
        break;
      }

      if (nextGameState) {
        delete currentGameState;
        currentGameState = nextGameState;
      }
    }

    currentGameState->update(elapsedTimed);

    window.clear(sf::Color::Magenta);
    window.draw(background);
    currentGameState->render();
    window.draw(fpsText);
    window.display();
  }

  delete currentGameState;
}
Example #28
0
void gMainWindow::reparent(gContainer *newpr, int x, int y)
{
	GtkWidget *new_border;
	int w, h;
	gColor fg, bg;
	
	if (_xembed)
		return;
	
	bg = background();
	fg = foreground();
	
	if (isTopLevel() && newpr)
	{
		gtk_window_remove_accel_group(GTK_WINDOW(topLevel()->border), accel);
		
		new_border = gtk_event_box_new();
		gtk_widget_reparent(widget, new_border);
		embedMenuBar(new_border);
		_no_delete = true;
		gtk_widget_destroy(border);
		_no_delete = false;
		
		border = new_border;
		registerControl();
		setCanFocus(false);

		setParent(newpr);
		connectParent();
		borderSignals();
		initWindow();	
		
		setBackground(bg);
		setForeground(fg);
		setFont(font());
		
		checkMenuBar();
		
		bufX = bufY = 0;
		move(x, y);
		gtk_widget_set_size_request(border, width(), height());
		
		// Hidden children are incorrectly shown. Fix that!
		hideHiddenChildren();
	}
	else if ((!isTopLevel() && !newpr)
	         || (isTopLevel() && isPopup()))
	         //|| (isTopLevel() && (isPopup() ^ (type == GTK_WINDOW_POPUP))))
	{
		gtk_window_remove_accel_group(GTK_WINDOW(topLevel()->border), accel);
		// TODO: test that
		new_border = gtk_window_new(GTK_WINDOW_TOPLEVEL);
		gtk_widget_reparent(widget, new_border);
		embedMenuBar(new_border);
		_no_delete = true;
		gtk_widget_destroy(border);
		_no_delete = false;

		border = new_border;
		registerControl();
		setCanFocus(true);

		if (parent())
		{
			parent()->remove(this);
			parent()->arrange();
			setParent(NULL);
		}
		initWindow();	
		borderSignals();
		setBackground(bg);
		setForeground(fg);
		setFont(font());
		
		move(x, y);
		w = width();
		h = height();
		bufW = bufH = -1;
		gtk_widget_set_size_request(border, 1, 1);
		resize(w, h);
		
		hideHiddenChildren();
		_popup = false; //type == GTK_WINDOW_POPUP;
	}
	else
	{
		gContainer::reparent(newpr, x, y);	
	}
}
Example #29
0
static int
daemon_mode(void)
{
  int bgpid;

#ifdef HAVE_SIGACTION
  struct sigaction sa, osa;

  memset(&sa, 0, sizeof(sa));
  sa.sa_handler = parent_exit;
  sa.sa_flags = 0;
  sigemptyset(&(sa.sa_mask));
  sigaddset(&(sa.sa_mask), SIGQUIT);
  sigaction(SIGQUIT, &sa, &osa);
#else /* not HAVE_SIGACTION */
  signal(SIGQUIT, parent_exit);
#endif /* not HAVE_SIGACTION */

  bgpid = background();

  if (bgpid != 0) {
    /*
     * Now wait for the automount points to
     * complete.
     */
    for (;;)
      pause();
    /* should never reach here */
  }
#ifdef HAVE_SIGACTION
  sigaction(SIGQUIT, &osa, NULL);
#else /* not HAVE_SIGACTION */
  signal(SIGQUIT, SIG_DFL);
#endif /* not HAVE_SIGACTION */

  /*
   * Record our pid to make it easier to kill the correct amd.
   */
  if (gopt.flags & CFM_PRINT_PID) {
    if (STREQ(gopt.pid_file, "/dev/stdout")) {
      printf("%ld\n", (long) am_mypid);
      /* flush stdout, just in case */
      fflush(stdout);
    } else {
      FILE *f;
      mode_t prev_umask = umask(0022); /* set secure temporary umask */

      f = fopen(gopt.pid_file, "w");
      if (f) {
	fprintf(f, "%ld\n", (long) am_mypid);
	(void) fclose(f);
      } else {
	fprintf(stderr, "cannot open %s (errno=%d)\n", gopt.pid_file, errno);
      }
      umask(prev_umask);	/* restore umask */
    }
  }

  /*
   * Pretend we are in the foreground again
   */
  foreground = 1;

  /*
   * Dissociate from the controlling terminal
   */
  amu_release_controlling_tty();

  return getppid();
}
Example #30
0
int main()
{
    int i,ic; //variables for incrementing in for loops
    int lives=5, level=1; //initialize lives and level
    int fgx=12, fgy=11, *frogx=&fgx, *frogy=&fgy; //initialize frog position
    int row=12,col=25,board[row][col]; //dimensions for board
    char play; //declare play character
    int x[19]= {5-width/4,width+5,10-width/4,15-width/4,width+10,5-width/2,1.2*width,10-width/2,15-width/2,1.2*width,5-width,1.5*width,10-width,15-width,1.5*width,width+5,5-width,width+10,10-width/2}; //array of starting positions of moving objects

    //initialize board
    for(i=0; i<6; i++)
        for(ic=0; ic<col; ic++)
            board[i][ic]=0;
    for(i=6; i<row; i++)
        for(ic=0; ic<col; ic++)
            board[i][ic]=1;
    for(i=2; i<col; i+=4)
        board[0][i]=2;

    gfx_open(width,height,"Frogger"); //open graphics window

    play=welcome(); //begin game

    while(play!='q') { //while user wants to play the game and not quit
        background(level);
        draw_lives(lives);
        draw(col,board,level,x,frogx,frogy);
        drawfrog(*frogx,*frogy,play);
        gfx_flush();
        usleep(100000);
        /*
            for(i=0;i<row;i++){ //prints board in terminal
            	for(ic=0;ic<col;ic++)
            		printf("%d",board[i][ic]);
            	printf("\n");
            } //end for(i=0;i<row;i++)
            printf("\n");
        */
        if (gfx_event_waiting()) { //if user tries to move frog
            play = hopper(frogx,frogy,row,col); //move frog according to input if valid
        } //end if (gfx_event_waiting())

        switch(board[*frogy][*frogx]) {
        case 0: //frog dies in this location
            lives--; //lose a life
            *frogx=12;
            *frogy=11;
            if(lives==0) {
                play=blood(); //game over, play again or end
                lives=5;
                level=1;
            } //end if(lives==0)
            break;

        case 1: //frog can be in this location and game continues
            break;

        case 2: //frog made it to lilly pad
            level++; //level up
            *frogx=12;
            *frogy=11;
            if (level>5) {
                play=win();//you won!
                level = 1;
                lives = 5;
            } //end if (level>5)
            break;

        } //end switch(board[*frogx][*frogy])

    } //end while(play!='q')

} //end main