Sunday, December 30, 2012

WebGL: creating a plane


function initQuadBuffer(){
triangleVertexPositionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
    var vertices = initPlaneArray(1, 1, 10, 10);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 3; // (x, y, z)
    triangleVertexPositionBuffer.numItems = 6*10*10; // number of vertices
}
function initPlaneArray(w, h, rows, cols){
var vertices = new Array();
var dx = w / cols;
var dy = h / rows;
var idx = 0;
var x = 0, y = 0;
for(var k = 0; k < rows; k++){
x = 0;
for(var i = 0; i<cols; i++){

vertices[idx] = x;  vertices[idx+1] = y;  vertices[idx+2] = 0.0;
vertices[idx+3] = x+dx;  vertices[idx+4] = y+dy;  vertices[idx+5] = 0.0;
vertices[idx+6] = x;  vertices[idx+7] = y+dy;  vertices[idx+8] = 0.0;

vertices[idx+9] = x;  vertices[idx+10] = y;  vertices[idx+11] = 0.0;
vertices[idx+12] = x+dx;  vertices[idx+13] = y;  vertices[idx+14] = 0.0;
vertices[idx+15] = x+dx;  vertices[idx+16] = y+dy;  vertices[idx+17] = 0.0;

idx += 18;
x += dx;
}
y += dy;
}

return vertices;
}

Friday, December 28, 2012

Mac OS X: pyglet


installed pyglet
tried a simple app and run, get the following error:

OSError: dlopen(/System/Library/Frameworks/QuickTime.framework/QuickTime, 6): no suitable image found.  Did find:
 /System/Library/Frameworks/QuickTime.framework/QuickTime: mach-o, but wrong architecture
 /System/Library/Frameworks/QuickTime.framework/QuickTime: mach-o, but wrong architecture

found a link: https://groups.google.com/forum/?fromgroups=#!topic/pyglet-users/mvvIo7NotBo

so run the command in Terminal: "defaults write com.apple.versioner.python Prefer-32-Bit -bool yes"
to set python to run in 32 bit mode
and then compile app again. no problem.

Monday, December 10, 2012

FlasCC: 1st experience

1) Download and extract FlasCC zip
2) try making the Hello sample. eg.: ..\..\sdk\usr\bin\make FLASCC="../../sdk" FLEX="../../../flex_sdk_4.6"
3) error
"-------- Sample 1 --------

First let's compile it as a projector:
"../../sdk/usr/bin/gcc" -Werror -Wno-write-strings -Wno-trigraphs hello.c -o hel
lo.exe
cc1: error in backend: Failed to run /cygdrive/c/Program Files/Git/bin/which wit
h args: java
Error:
/cygdrive/c/Program Files/Git/bin/which: line 7: $'\r': command not found

make: *** [T01] Error 1"

4) use dosunix on the "which" in Git\bin

5) then run again, another error
"LLVM ERROR: Error: Unable to launch the Java Virtual Machine.
This usually means you have a 32bit JVM installed or have set your Java heap siz
e too large.
Try lowering the Java heap size by passing "-jvmopt=-Xmx1G" to gcc/g++.
Stack dump: [blah blah ....]

make: *** [T01] Error 1"

6) added '-jvmopt="-Xmx1G"' to Makefile
"T01: check
@echo "-------- Sample 1 --------"
@echo && echo "First let's compile it as a projector:"
"$(FLASCC)/usr/bin/gcc" $(BASE_CFLAGS) -jvmopt="-Xmx1G" hello.c -o hello.exe

@echo && echo "Now lets compile it as a SWF:"
"$(FLASCC)/usr/bin/gcc" $(BASE_CFLAGS) -jvmopt="-Xmx1G" hello.c -emit-swf -swf-size=200x200 -o hello.swf

include ../Makefile.common

clean:
rm -f hello.swf hello *.bc *.exe"

7) finally no error and EXE and SWF generated.

Sunday, December 02, 2012

WebGL start

Reference: http://learningwebgl.com/blog/?p=28

download js matrix library: https://github.com/toji/gl-matrix/downloads

write the shader source code in a <script></script> tags

<script id="shader-fs" type="x-shader/x-fragment">
  precision mediump float;

  void main(void) {
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
  }
</script>

<script id="shader-vs" type="x-shader/x-vertex">
  attribute vec3 aVertexPosition;

  uniform mat4 uMVMatrix;
  uniform mat4 uPMatrix;

  void main(void) {
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
  }
</script>

variables needed in the javascript code

var triangleVertexPositionBuffer;
var squareVertexPositionBuffer;
var gl;
var shaderProgram;
var mvMatrix = mat4.create();
var pMatrix = mat4.create();

function webGLStart() {
    var canvas = document.getElementById("mycanvas");
    initGL(canvas);
    initShaders();
    initBuffers();

    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.enable(gl.DEPTH_TEST);

    drawScene();
}

function initGL(canvas) {
  try {
    gl = canvas.getContext("experimental-webgl");
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
  } catch(e) {
  }
  if (!gl) {
    alert("Could not initialise WebGL, sorry :-(");
  }
}

function initShaders() {
  var fragmentShader = getShader(gl, "shader-fs");
  var vertexShader = getShader(gl, "shader-vs");

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
    alert("Could not initialise shaders");
  }

  gl.useProgram(shaderProgram);
  
  shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
  gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
  
  shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
  shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
}
function getShader(gl, id) {
    var shaderScript = document.getElementById(id);
    if (!shaderScript) {
        return null;
    }

    var str = "";
    var k = shaderScript.firstChild;
    while (k) {
        if (k.nodeType == 3)
            str += k.textContent;
        k = k.nextSibling;
    }

    var shader;
    if (shaderScript.type == "x-shader/x-fragment") {
        shader = gl.createShader(gl.FRAGMENT_SHADER);
    } else if (shaderScript.type == "x-shader/x-vertex") {
        shader = gl.createShader(gl.VERTEX_SHADER);
    } else {
        return null;
    }

    gl.shaderSource(shader, str);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(shader));
        return null;
    }

    return shader;
}

function initBuffers() {
    triangleVertexPositionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
    var vertices = [
                    0.0,  1.0,  0.0,
                   -1.0, -1.0,  0.0,
                    1.0, -1.0,  0.0
               ];
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 3; // number of component to represent a vertex = 3; (x, y, z)
    triangleVertexPositionBuffer.numItems = 3; // number of vertices
}

function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix); mat4.identity(mvMatrix); mat4.translate(mvMatrix, [0, 0.0, -5.0]); gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer); gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); setMatrixUniforms(); gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);
}

function setMatrixUniforms() {
    gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
    gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
}

HTML
<body onload="webGLStart()">
<canvas id="mycanvas" style="border: none;" width="500" height="500"></canvas>
</body>


Saturday, December 01, 2012

PyQT - OpenGL - Timer


import sys
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtOpenGL import *
from PyQt4 import uic

class MyOGLWidget(QGLWidget):
    def __init__(self, parent=None):      
        QGLWidget.__init__(self, parent)
        self.spin = 0
             

    def initializeGL(self):
        print "init GL"
        glClearColor(0.0, 0.0, 0.0, 0.0);
        glShadeModel (GL_FLAT)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.spinDisplay)
        self.timer.start(40)
        print self.timer
     

    def resizeGL(self, w, h):
        print "resize: " + str(w ) + " x " +str(h)
        glViewport(0, 0, w, h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);

    def paintGL(self):
        print "paint GL"
        glClear (GL_COLOR_BUFFER_BIT );
        glPushMatrix()
        glRotatef(self.spin, 0, 0, 1)
        glColor3f (1.0, 1.0, 1.0);
        glRectf(-25.0, -25.0, 25.0, 25.0);
        glPopMatrix()
        glFlush();
     
    def spinDisplay(self):
        # print "spin display"
        self.spin = self.spin + 2
        self.spin = self.spin % 360
        # print self.spin
        #glutSwapBuffers()
        self.updateGL()
   
app = QApplication(sys.argv)
window = MyOGLWidget()
window.resize(300, 300)
window.setWindowTitle("Testing OpenGL in PyQT")
window.show()

sys.exit(app.exec_())


PyQt - OpenGL

install PyOpenGL - http://pyopengl.sourceforge.net/
install QT - http://qt-project.org/downloads
install PyQT- http://www.riverbankcomputing.com/software/pyqt/download
for Mac OS X, install PyQTX - http://sourceforge.net/projects/pyqtx/files/

import sys
from OpenGL.GL import *
from OpenGL.GLU import *
from PyQt4.QtGui import *
from PyQt4.QtOpenGL import *
from PyQt4 import uic

class MyOGLWidget(QGLWidget):
    def __init__(self, parent=None):
        QGLWidget.__init__(self, parent)      
 
    def initializeGL(self):
        print "init GL"
        glClearColor(0.0, 0.0, 0.0, 0.0);
        glShadeModel (GL_FLAT)
 
    def resizeGL(self, w, h):
        print "resize: " + str(w ) + " x " +str(h)
        glViewport(0, 0, w, h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);
 
    def paintGL(self):
        print "paint GL"
        glClear (GL_COLOR_BUFFER_BIT );
        glColor3f (1.0, 1.0, 1.0);
        glRectf(-25.0, -25.0, 25.0, 25.0);
        glFlush();
     
app = QApplication(sys.argv)
window = MyOGLWidget()
window.resize(300, 300)
window.setWindowTitle("Testing OpenGL in PyQT")
window.show()

sys.exit(app.exec_())



QT designer ui in python PyQT - event


import sys
from PyQt4.QtGui import QApplication, QDialog
from PyQt4 import uic

# a sample event listener
def handle():
    print "clicked"
    # get text in QTextEdit to display in QLabel
    ui.label.setText("hello " + ui.textEdit.toPlainText())

app = QApplication(sys.argv)
window = QDialog()
# dialog.ui is an xml file generated by QT designer
ui = uic.loadUi("dialog.ui")

# set text of QTextEdit
ui.textEdit.setText("hello")
# set text with HTML
ui.textEdit.setHtml("bolditalic")
# connect an event to a listener
ui.pushButton.clicked.connect(handle)

ui.show()

sys.exit(app.exec_())


QT .UI XML

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <widget class="QDialogButtonBox" name="buttonBox">
   <property name="geometry">
    <rect>
     <x>30</x>
     <y>240</y>
     <width>341</width>
     <height>32</height>
    </rect>
   </property>
   <property name="orientation">
    <enum>Qt::Horizontal</enum>
   </property>
   <property name="standardButtons">
    <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
   </property>
  </widget>
  <widget class="QLabel" name="label">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>10</y>
     <width>200</width>
     <height>13</height>
    </rect>
   </property>
   <property name="text">
    <string>TextLabel</string>
   </property>
  </widget>
  <widget class="QTextEdit" name="textEdit">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>30</y>
     <width>231</width>
     <height>50</height>
    </rect>
   </property>
  </widget>
  <widget class="QPushButton" name="pushButton">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>110</y>
     <width>75</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>PushButton</string>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>buttonBox</sender>
   <signal>accepted()</signal>
   <receiver>Dialog</receiver>
   <slot>accept()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>248</x>
     <y>254</y>
    </hint>
    <hint type="destinationlabel">
     <x>157</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>buttonBox</sender>
   <signal>rejected()</signal>
   <receiver>Dialog</receiver>
   <slot>reject()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>316</x>
     <y>260</y>
    </hint>
    <hint type="destinationlabel">
     <x>286</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>