Word Gems

A personal interest blog about computergraphics, rendering and usefull C++ and Python stuff.

Datafox 2000 Kluppe auf 64bit Windows 7, 8, 10 und Linux

Die Kluppe Datafox 2000 der Firma PAV-Präzisions Apparatebau Vaduz AG verfügt über die Möglichkeit Messdaten über eine serielle Schnittstelle (COM-Port) auf den PC zu übertragen. Eine Übertragungssoftware die auch mit Windows 7, 8 und 10 sowie unter Linux funktioniert können sie bei mir für 50 Euro erwerben. Die Software funktioniert auch mit USB-COM-Port Adaptern. Bei Interesse senden sie eine eMail andatafox

Auch wenn sie Probleme mit anderen Geräten, die über einen COM-Port ausgelesen werden haben, schreiben sie mir. Vielleicht kann ich eine Lösung für sie erarbeiten. So müssen sie nicht in neue Geräte investieren, wenn für die vorhandenen bloß die richtige Software fehlt.Datafox 2000 Kluppe

Filed under: Software, , ,

OpenCV with Visual Studio 2010

If you try to get OpenCV to work with Visual Studio 2010 and get an “Unhandled Exception” while trying out a simple example make sure your program links against the correct .dll!

Make sure you added the path to the folder containing the dll’s build with VS 2010 to your path-enviroment variable, not any other version of Visual Studio, it wont work!

Filed under: C++, Computergraphics, OpenCV

Using Magick++ under Visual Studio 2010

If you try to use Magick++ in your Visual Studio 2010 project you will get all kinds of odd errors.

The reason is not at all obvious, and took me a while to find. ImageMagick, (Magick++) uses STL types in the library interface. Since the implementation of STL container types etc. are compiler-specific, they are not neccessarily compatible between different compilers (not even between compiler versions).

To get the whole thing to fly you got to build ImageMagick with the same compiler as your project. How to build ImageMagick from source is described here http://www.imagemagick.org/script/advanced-windows-installation.php in detail.

Update: After I came back to this topic I found some notes on the imagemagick website concerning the problem:

Note that the DLLs and libraries are built using Visual C++ 7.0 (.net). In order to use Magick++, you must either use the same compiler version used to build the distribution, or download the Windows source package and build everything yourself.

Filed under: C++, ImageMagick

DLL Injection using CreateRemoteThread on 64 Bit Win 7

Have you ever tried to inject a DLL into another process on a 64 bit Windows? Well I tried and failed. CreateRemoteThread returned NULL and GetLastError returned error 5, which means ACCESS DENIED. That didn’t make any sense to me because I made sure to change my privilege token to include SE_PRIVILEGE_ENABLED, which means debugging rights.

Finally I used Process Explorer to find out that the process I was trying to inject was a 64 bit process, other than my injecting process, which was 32 bit. Obviously its impossible to inject a 32 bit dll into a 64 bit process.

Since I couldn’t find any forum posts suggesting this could ahve been the problem, I post it here to save you some time!

And a suggestion to Microsoft: That error message didn’t say what was actually wrong! It could throw a more informative message.

Filed under: Windows API

Intercepting network traffic using Wireshark

Have you ever wondered what any specific application was sending over your network? If you want to know that, or even want to find out how a proprietary protocol works, you should give Wireshark (www.wireshark.org) a try! Today i’m going to peek into the network traffic of my email client. First I have to check the ip of the mailserver i’m using. I am going to use the ip to filter out network traffic which is send to or received from that specific server.

As we can clearly see by using ping, the ip is 212.227.17.185, so lets fire up Wireshark. Lucky for us that Wireshark brings some very mighty, built in protocol parsing features. Lets just select the pop-protocol, which is used to transfer the emails from the server to my client.

Additionally we want to fitler by the servers ip, which is possible by further specifying the filter expression.

Now lets select the network interface of my wlan stick, which is the second one. If you can’t tell the interfaces apart just click on “details” to get some hints. Click start to start the capturing of packets.

After you started capturing packets you should, of course, generate some traffic to be captured by triggering a network event. I let Thunderbird check if I received a new email and expectet to see some packets flowing back. But what happend is: Nothing! The packet list stays empty. Maybe the ip was wrong? Let’s send another ping.

Well thats interesting! I get different ip’s for the same hostname. Looks like the mail hoster is distributing the clients over different servers by just returning different ip’s. Lets just filter all traffic coming from any ip in that range by changing the filter to be “pop and ip.src==212.227.17.0/8”. Apply the changes an suddenly I can see all the packets which were received from the sever. To see the packets send from my client to the server just change “ip.src” to be “ip.dst”.

The second request send to the server is “STLS”, which asks the server to start an encrypted TLS or SSL connection. And it looks like the request was succesfull since the following packets are encrypted. If that wouldn’t be the case I could see my email account and password being send to the server. Since I’m using a wlan to transmit my network traffic everybody else using the network can see the exact same packts i’m seeing now. Good to know the encrpytion of my email client works as expected. But what about usernames and passwords I enter on websites? As you can guess by now, they are send in clear text if i’m not using https, which is the encrypted equivilant of http protocol.

Filed under: Network

Using jpcap under win 7 (x64)

While using the jpcap project unter Windows 7 I stumbled upon this error:

Exception in thread “main” java.lang.UnsatisfiedLinkError: no jpcap in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1738)
    at java.lang.Runtime.loadLibrary0(Runtime.java:823)
    at java.lang.System.loadLibrary(System.java:1028)
    at jpcap.JpcapCaptor.<clinit>(JpcapCaptor.java:251)
    at PacketReceiver.run(PacketReceiver.java:19)
    at Main.main(Main.java:16)

It was caused by using the 64 bit java JDK. I installed the x86 version of the JDK and set it in the Eclipse preferences. That fixed the linking error and should help anybody having the same problem.

Eclipse Preferences

The newest JRE and JDK can be found here: http://www.oracle.com/technetwork/java/javase/downloads/

Filed under: Java, jpcap, Network

Abaqus Python Script

A friend asked me to write a python script to control the FEM software Abaqus. He wanted to simulate a compound material consisting of a material block with small spheres of a diffrent material inserted. It was the first time I ever saw Abaqus, but got the hang of it quite fast.

The resulting script produces a block of material, generates n spheres wich are distributed randomly and not overlapping inside the block. The radius of the spheres is controled by their number. It is choosen in a way that the n spheres make up 20% of the volume of the block.
Sphere Positions and radii are written out into a file. Im looking forward to his simulation results.

from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from job import *
from sketch import *
from visualization import *
from connectorBehavior import *
import random
import math

#Euclidean Distance Measure
def euclidean_py(x, y):
    # lightly modified from implementation by Thomas Sicheritz-Ponten.
    # This works faster than the Numeric implementation on shorter
    # vectors.
    if len(x) != len(y):
        raise ValueError, "vectors must be same length"
    sum = 0
    for i in range(len(x)):
        sum += (x[i]-y[i])**2
    return math.sqrt(sum)

#Create Cube
mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=200.0)
mdb.models['Model-1'].sketches['__profile__'].rectangle(point1=(0.0, 0.0), point2=(1.0, 1.0))
mdb.models['Model-1'].Part(dimensionality=THREE_D, name='Part-1', type=DEFORMABLE_BODY)
mdb.models['Model-1'].parts['Part-1'].BaseSolidExtrude(depth=1.0, sketch=mdb.models['Model-1'].sketches['__profile__'])
del mdb.models['Model-1'].sketches['__profile__']

#Instantiate cube
mdb.models['Model-1'].rootAssembly.Instance(dependent=ON, name='tmpCube', part=mdb.models['Model-1'].parts['Part-1'])

#File Output
text_file = open("c:\Sphere_Positions.txt", "w")

#Number of Spheres
n = 10
text_file.write("Number of Spheres: " + str(n) + "\n")

#Radius of one sphere
r = (3*0.20)/(4*math.pi*n)
r = r**(1.0/3.0)
print "Sphere Radius is " + str(r)
text_file.write("Sphere Radius is " + str(r) + "\n")

#Create Sphere
mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=200.0)
mdb.models['Model-1'].sketches['__profile__'].ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0))
mdb.models['Model-1'].sketches['__profile__'].FixedConstraint(entity=mdb.models['Model-1'].sketches['__profile__'].geometry[2])
mdb.models['Model-1'].sketches['__profile__'].ArcByCenterEnds(center=(0.0, 0.0), direction=CLOCKWISE, point1=(0.0, -r), point2=(0.0, r))
mdb.models['Model-1'].sketches['__profile__'].Line(point1=(0.0, -r), point2=(0.0, r))
mdb.models['Model-1'].sketches['__profile__'].VerticalConstraint(entity=mdb.models['Model-1'].sketches['__profile__'].geometry[4])
mdb.models['Model-1'].Part(dimensionality=THREE_D, name='Part-2', type=DEFORMABLE_BODY)
mdb.models['Model-1'].parts['Part-2'].BaseSolidRevolve(angle=360.0, flipRevolveDirection=OFF, sketch=mdb.models['Model-1'].sketches['__profile__'])
del mdb.models['Model-1'].sketches['__profile__']

#List of Spheres
sphereList = []
sphereInstancesList = []

#Create n instances of the sphere
for i in range(1, n+1):
	InstanceName = 'Sphere_' + str(i)
	print InstanceName
	text_file.write(InstanceName)

	#Maximum tries to distribute sphere
	maxTries = 1000

	while len(sphereList) < i:
		maxTries -= 1
		if maxTries < 1:
			print "Maximum Distribution tries exceded. Error! Restart the Script!"
			break;

		#Make sure Spheres dont cut cube sides
		vecPosition = [r+(random.random()*(1.0-r-r)),r+(random.random()*(1.0-r-r)),r+(random.random()*(1.0-r-r))]
		for pos in sphereList:
			if euclidean_py(pos, vecPosition) < 2*r:
				break
		else:
			sphereList.append(vecPosition)
			print vecPosition
			text_file.write("\t" + str(vecPosition) + "\n")
			#Instantiate Sphere
			mdb.models['Model-1'].rootAssembly.Instance(dependent=ON, name=InstanceName, part=mdb.models['Model-1'].parts['Part-2'])
			#Translate Instance of Sphere
			mdb.models['Model-1'].rootAssembly.translate(instanceList=(InstanceName, ), vector=vecPosition)
			sphereInstancesList.append(mdb.models['Model-1'].rootAssembly.instances[InstanceName])

print "Sphere Radius is " + str(r)

#Cut all spheres with cube
mdb.models['Model-1'].rootAssembly.PartFromBooleanCut(cuttingInstances=(
sphereInstancesList ),
instanceToBeCut=mdb.models['Model-1'].rootAssembly.instances['tmpCube'],
name='Part-3')

#Intantiate Cut Object
mdb.models['Model-1'].rootAssembly.Instance(dependent=ON, name='Cube',
part=mdb.models['Model-1'].parts['Part-3'])

#Delete temporary cube
del mdb.models['Model-1'].rootAssembly.instances['tmpCube']

text_file.close()

Filed under: Abaqus, Python

Gray Hat Python (error 50 on 64 bit)

The great Book “Gray Hat Python – Python Programming for Hackers and Reverse Engineers” by Justin Seitz includes some great sample code to build your own debugger using only Python, ctypes and the win32 api. The exmple source code is freely available on the book website at nostarch press: http://nostarch.com/ghpython.htm

Unfortunatly the Windows Debugging Tools, namly the API functions don’t work for 64 bit versions of Windows. So be prepared if  the DebugActiveProcess call does return Null.

To check if the failed function call is caused by API problems insert the following just behind the “else” which indicates the failed attachment to the debug process:

print "[*] Unable to attach to the process. %s" % FormatError(kernel32.GetLastError())

The resulting error has the error code 50 (ERROR_NOT_SUPPORTED). The text of the message varies depending your OS language. In german it would be “Die Anforderung wird nicht unterstützt.”, in english “The request is not supported.”.

A solutions to get the examples running would be to use the Windows XP Mode bundled with Win 7 or any other virtual 32 bit machine.

Filed under: Python

Quick & Dirty *.pfm Reader & Writer

This is a simple, quick and dirty portable float map reader and writer I made. Fell free to use it for whatever purpose, but beware: Its not production code, just a quick research implementation.


typedef struct {
 float r;
 float g;
 float b;
} COLOR;

COLOR * data;

void HDRImage::setSize(int x, int y)
{
 if(mSizeX==x && mSizeY==y)
 return;
 mSizeX = x;
 mSizeY = y;
 if (data)
 delete[] data;
 data = new COLOR[mSizeX* mSizeY];
}

void HDRImage::loadPfm(const char * filename)
{

	char strPF[3];
	unsigned int SizeX;
	unsigned int SizeY;
	float dummy;
	int dummyC;

	FILE * file = fopen(filename, "rb");

	if (file == NULL) {
		printf("PFM-File not found!\n");
		return;
	}

	fscanf(file, "%s\n%u %u\n", strPF, &SizeX, &SizeY);
	dummyC = fgetc(file);
	fscanf(file, "\n%f\n", &dummy);

	//DEBUG Ausgabe
	printf("Keyword: %s\n",strPF);
	printf("Size X: %d\n", SizeX);
	printf("Size Y: %d\n", SizeY);
	printf("dummy: %f\n", dummy);
	// ENDE Debug Ausgabe

	this->setSize(SizeX, SizeY);

	int result;
	int lSize;
	lSize = mSizeX*3;
	for(int y=mSizeY-1; y>=0; y--)
	{
		result = fread(data+1+mSizeX*y, sizeof(float), lSize, file);
		if (result != lSize) {
			printf("Error reading PFM-File. %d Bytes read.\n", result);
		}
	}

	fclose(file);
}

void HDRImage::writePfm(const char * filename)
{

 char sizes[256];
 FILE * file = fopen(filename, "wb");

 fwrite("PF\n",sizeof(char), 3, file);
 sprintf(sizes, "%d %d\n", mSizeX, mSizeY);

 fwrite(sizes,sizeof(char), strlen(sizes)+1, file);
 fwrite("\n",sizeof(char),1, file);
 fwrite("-1.000000\n",sizeof(char),10, file);

 for(int y=mSizeY-1; y>=0; y--)
 fwrite(data+1+mSizeX*y, sizeof(float), mSizeX*3, file);

 fclose(file);
}

Filed under: Computergraphics,

Stochastic Progressive Photon Mapping

An picture I rendered with my Stochastic Progressive Photon Mapper. There is diffuse, specular and half diffuse/specular material in the Scene. The bust is “Otto von Guericke”, the inventor of the vacuum pump. The clock was kindly provided by Toshiya Hachisuka. I saved extensive statistics while the rendering was running.

You can get the logfile.txt from <link down, sorry>

The original HDR-File is available as portable float map <link down, sorry>

The scene description file is available in a text format similar to pbrt <link down, sorry>

The Otto bust is available as zipped obj-file <link down, sorry>

Filed under: Computergraphics,