Essential Cygwin Development Packages

Whenever I want to do a new Cygwin install on Windows, I’d have to just keep scrolling the Cygwin installer window to find the packages that I use frequently. I decided to compile a list of packages I use and put them here so that I wouldn’t have to waste time on it again in the future.

  • Devel:
    1. cmake
    2. cmake-gui
    3. gcc-core
    4. gcc-g++
    5. gdb
    6. git
    7. make
  • Libs:
    1. libboost-devel
  • Python:
    1. python3
  • Shells:
    1. chere (for shell integration)
  • X11: (Needed for cmake-gui)
    1. gnu-free-fonts
    2. xinit

Additionally, I let Cygwin’s installer to auto-install additional required packages. These packages should be sufficient for compiling C/C++ code under Windows. In order to enable shell integration for bringing up a Cygwin terminal, this command should be executed from Cygwin terminal (using administrator privileges) after installation:

chere -i -t mintty

“sys/time.h” Replacement for Windows

Some C/C++ code targeted for GNU family compilers fail to compile under Windows due to the dependency on sys/time.h header file. The repository here has provided a neat implementation for it. Basically you need these three files: time.h, times.h and times.cpp. I have included them here (in case the repository ever went dead). Note that this is not my code and the original license of the code was LGPL.

sys/time.h:

#pragma once

#ifndef _TIMES_H

#include "sys/times.h"

#endif

sys/times.h:

#ifndef _TIMES_H
#define _TIMES_H

#ifdef _WIN32
#include <sys/timeb.h>
#include <sys/types.h>
#include <winsock2.h>

int gettimeofday(struct timeval* t,void* timezone);

// from linux's sys/times.h

//#include <features.h>

#define __need_clock_t
#include <time.h>


/* Structure describing CPU time used by a process and its children.  */
struct tms
  {
    clock_t tms_utime;          /* User CPU time.  */
    clock_t tms_stime;          /* System CPU time.  */

    clock_t tms_cutime;         /* User CPU time of dead children.  */
    clock_t tms_cstime;         /* System CPU time of dead children.  */
  };

/* Store the CPU time used by this process and all its
   dead children (and their dead children) in BUFFER.
   Return the elapsed real time, or (clock_t) -1 for errors.
   All times are in CLK_TCKths of a second.  */
clock_t times (struct tms *__buffer);

typedef long long suseconds_t ;

#endif
#endif

sys/time.cpp:

#include "sys/times.h"

int gettimeofday(struct timeval* t,void* timezone)
{       struct _timeb timebuffer;
        _ftime( &timebuffer );
        t->tv_sec=timebuffer.time;
        t->tv_usec=1000*timebuffer.millitm;
		return 0;
}

clock_t times (struct tms *__buffer) {

	__buffer->tms_utime = clock();
	__buffer->tms_stime = 0;
	__buffer->tms_cstime = 0;
	__buffer->tms_cutime = 0;
	return __buffer->tms_utime;
}

 

 

 

CheckedListBox throws “Out of Memory Exception” When Adding New Items

I was using WinForm’s CheckedListBox control a few minutes ago and my application was crashing with an out of memory exception. This was happening on the line where new items were being added to the CheckedListBox. It did not make any sense at all, since I was only adding the second item to the control. Also, I was pretty sure I wasn’t being even close to running out of memory! 😀

By some happy coincidence, I figured out what the problem was. Some of the items I was adding to the list would return null in their ToString() method. Turned out that was what was causing the exception. I simply made sure that ToString() would not return null values and that solved the issue. .NET can sometimes be stupid 😀

I guess it is advisable to always write the ToString() methods with a blank string as the starting point (eg. return "" + this.ID so that it wouldn’t break in case ID is null).

“Unresolved external symbol” Errors when Compiling CGAL 4.7 Under Windows with Visual Studio 2013

I spent hours trying to compile CGAL 4.7 with Visual Studio 2013. Everything compiled on the first try with Visual Studio 2010 but for some reason I was unable to get it working with VS2013. CMake would create the solution files just fine and was able to resolve everything. However, when I attempted to build the confiugured solution I would get lots of “unresolved external” errors like this:

unresolved external symbol "__declspec(dllimport) class boost::system::error_category const & __cdecl boost::system::generic_category(void)

I followed this guide to the letter. I was sure Boost was being discovered just fine. I had everything in my PATH. After a while I figured out what my problem was! Although I wanted to build 64-bit binaries, I was selecting Visual Studio 12 2013 as my generator!! I was skimming every time I was selecting it so I wasn’t paying attention! I should’ve in fact selected Visual Studio 12 2013 Win64 as my generator. Doing that solved the problems.

Rendering Multiple OpenGL 2D Textures, Only the First One Is Rendered

Exactly a month ago I was dealing with the problem of rendering some text on the screen using the font + texture rendering method. The problem I had was only the first text block was rendered to the screen. After a little bit of digging around I found this question on StackOverflow. Although the answers there did not solve my problem, I realized that the problem was caused by having depth testing enabled while rendering the 2D blocks. All I had to do was place a call to glDisable(GL_DEPTH_TEST).

Linux Cheat Sheet

NOTE: MORE ITEMS WILL BE ADDED TO THIS LIST

Today I decided to keep a Linux cheat sheet around to avoid looking up some common tasks on Google. I keep forgetting some commands and I feel like I should get them tattooed somewhere on the back of my hand so that I wouldn’t forget them. Although this list is currently very short, I will keep adding new stuff to it.

Program Specific:

     Git:

Update a submodule to the latest remote commit: git submodule update --remote --merge

     Screen:

Start a named session: screen -S [SESSION NAME]
Rename the session currently attached to: Ctrl + A ; :sessionname [NEW SESSION NAME]
List all sessions: screen -ls
Attach to a session screen -r [SESSION NAME]
Detach from window: Ctrl + A ; D
Exit screen: Ctrl + A ; \

     nvidia-xconfig:

Create a complete xorg.conf file: sudo nvidia-xconfig --enable-all-gpus
Enable overclicking: sudo nvidia-xconfig --cool-bits=28

     Fail2ban:

Unban an IP address: fail2ban-client set [JAIL NAME] unbanip [IP ADDRESS]

Script Related:

Autostart program:
  1. Put the script/command in /etc/rc.local
  2. Put the script/command in /etc/crontab with @reboot [USERNAME] [COMMAND]
Dump output to file (with stderr rerouting): [PROGRAM]  |& tee output.txt

Commands:

     File and Directory Management:

Create symbolic link: ln -s [TARGET] [LINK NAME]
Change to last working directory: cd -
Copy from remote to local rsync -az --progress [USERNAME]@[REMOTE HOST]:[REMOTE PATH] [LOCAL PATH]

     Searching:

Find a specific file:  find [START PATH] -name [NAME OF FILE]
Find a directory:  find [START PATH] -type d -name [NAME OF DIRECTORY]
Find text if files: grep -Ril "[TEXT TO FIND]" [START PATH]

     User Management:

List the groups that a user belongs to: groups
Add user to the list of sudoers: sudo adduser [USERNAME] sudo
Run program as another user: su [USERNAME] -c "[COMMAND TO RUN]"

Distinguish Between Touch/Pen and Mouse Input in WinForms

In WinForms, mouse events are raised regardless of the original source of the mouse. If you click a button with the stylus for instance, you’d still get the MouseClick event. This MSDN page explains how to distinguish between the sources of the event. To make the long story short, you’d have to place an API call to the GetMessageExtraInfo() function and check the returned value. The following C# code snippet performs the checking:

/// <summary>
/// The sources of the input event that is raised and is generally
/// recognized as mouse events.
/// </summary>
public enum MouseEventSource
{
    /// <summary>
    /// Events raised by the mouse
    /// </summary>
    Mouse,

    /// <summary>
    /// Events raised by a stylus
    /// </summary>
    Pen,

    /// <summary>
    /// Events raised by touching the screen
    /// </summary>
    Touch
}

/// <summary>
/// Gets the extra information for the mouse event.
/// </summary>
/// <returns>The extra information provided by Windows API</returns>
[DllImport("user32.dll")]
private static extern uint GetMessageExtraInfo();

/// <summary>
/// Determines what input device triggered the mouse event.
/// </summary>
/// <returns>
/// A result indicating whether the last mouse event was triggered
/// by a touch, pen or the mouse.
/// </returns>
public static MouseEventSource GetMouseEventSource()
{
    uint extra = GetMessageExtraInfo();
    bool isTouchOrPen = ((extra & 0xFFFFFF00) == 0xFF515700);

    if (!isTouchOrPen)
        return MouseEventSource.Mouse;

    bool isTouch = ((extra & 0x00000080) == 0x00000080);

    return isTouch ? MouseEventSource.Touch : MouseEventSource.Pen;
}

 

Git: Merge Specific Commit from Another Branch to Main Branch

Let’s say that in your git repository, you have a master branch and an experimental branch. You’ve fixed a bug on file A on the experimental branch and you would like to commit that fix to the master branch. This is possible using the git cherry-pick command.

First, switch to the experimental branch and execute git log. Take note of the ID of the commit you’d like to merge into the master branch. Now switch to the master branch and use the command git cherry-pick ID where ID is the ID of the commit you noted earlier. This will merge the selected commit into the master branch.

3D Line Fitting in 5 Easy Steps with SVD

Least squares fit is used for 2D line fitting. In 3D space, the line is called 3D Orthogonal Distance Regression (ODR) line. The line can be easily found in 3D using SVD (singular value decomposition).

Assuming that we have a bunch of 3D points (x0, y0, z0) to (xn, yn, zn), the algorithm (in MATLAB) is as follows:

% Step 1: arrange points in a matrix format
points = [x0 y0 z0 ; 
          x1 y1 z1 ;
            ....   ;
          xn yn zn];

% Step 2: find the mean of the points
avg = mean(points, 1);

% Step 3: subtract the mean from all points
subtracted = bsxfun(@minus, points, avg);

% Step 4 : perform SVD
[~, ~, V] = svd(subtracted);

% Step 5: find the direction vector 
%        (which is the right singular vector corresponding to the largest singular value)
direction = V(:, 1);

% Line is 'avg' and 'direction'
p0 = avg;
d = direction;

% Parametric equation: P = p0 + t*d

 

Intersection of a Ray and a Line Segment in 3D

This page contains methods for performing various intersection tests. Although it does not have an entry for ray vs. line segment intersection, I tried the suggested ray vs. ray intersection test (page 782 of Real-Time Rendering 3rd Edition) and it did not work in my case.

I looked around quite a bit and based on an adaptation of this answer, I finally found a method that works fine. Given a ray (with a start point, an end point and direction) and a line segment with the defined start and end points, we perform the 3D line intersection test. However, note that in various graphics APIs, there is always some error when converting screen points to lines (because there is no 1-1 mapping from screen pixels to exact 3D points in space). Therefore, when performing intersection tests, some degree of tolerance must be considered. This is especially important in the early rejection step of the intersection test algorithm. The early rejection test, checks to see whether the two 3D lines are co-planer. If they aren’t, then no intersection will be reported.

After finding the intersection point, we must check and see if this point lies between the start and end points of the line segment. This can be done by comparing the length of the line segment with the sum of distances of the intersection point from the start point and end point of the line segment respectively. If the length is “almost” equal, then it means that the original ray will intersect with the line segment.

Here is the pseudo-code of the described process (adapted from the original answer):

const double coPlanerThreshold = 0.7; // Some threshold value that is application dependent
const double lengthErrorThreshold = 1e-3;

bool intersection(Ray ray, LineSegment segment)
{
	Vector3 da = ray.End - ray.Origin;	// Unnormalized direction of the ray
	Vector3 db = segment.End - segment.Start;
	Vector3 dc = segment.Start - ray.Origin;
	
	if (Math.Abs(dc.Dot(da.Cross(db))) >= coPlanerThreshold) // Lines are not coplanar
		return false;
		
	double s = dc.Cross(db).Dot(da.Cross(db)) / da.Cross(db).LengthSquared;

	if (s >= 0.0 && s <= 1.0)	// Means we have an intersection
	{
		Vector3 intersection = ray.Origin + s * da;
		
		// See if this lies on the segment
		if ((intersection - segment.Start).LengthSquared + (intersection - segment.End).LengthSquared <= segment.LengthSquared + lengthErrorThreshold)
		return true;
	}

	return false;
}