OSG+Python

时间:2024-01-13 09:08:38
测试平台
(1)Fedora19 x86
  
[cc@localhost ~]$ lspci | grep VGA
:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev )
:00.0 VGA compatible controller: NVIDIA Corporation GK107M [GeForce GT 645M] (rev a1)
(2)Python 2.7
(3)Osg 3.2.0
(4)cmake 2.8
(5)gcc 4.8.2
#include <Python.h>
#include <iostream>
#include <string>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>

PyObject * pModule;
double CallPythonTest()
{
PyObject * pFunc=PyObject_GetAttrString(pModule, "test");
PyObject * value = PyObject_CallFunction(pFunc,"ff", -15.0f, -20.0f); //通过函数对象执行函数
double a = PyFloat_AsDouble(value);
std::cout << a << std::endl;
return a;
} class MyEventHandler : public osgGA::GUIEventHandler
{
public:
MyEventHandler()
{
} virtual bool handle(const osgGA::GUIEventAdapter & ea, osgGA::GUIActionAdapter & aa)
{
osgViewer::Viewer * viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
osg::Camera * camera = viewer->getCamera();
switch (ea.getEventType())
{
case osgGA::GUIEventAdapter::FRAME:
{
double a = CallPythonTest();
camera->setViewMatrixAsLookAt(osg::Vec3(0.0, a, ), osg::Vec3(0.0, 0.0, 0.0), osg::Vec3(0.0, 0.0, 1.0));
break;
}
default:
break;
} return false;
}
}; int main() {
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("import random");
PyRun_SimpleString("sys.path.append('../PythonTest/')");
pModule = PyImport_ImportModule("Test");
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
viewer->getCamera()->setViewMatrixAsLookAt(osg::Vec3(0.0, -20.0, 0.0), osg::Vec3(0.0, 0.0, 0.0), osg::Vec3(0.0,0.0, 1.0));
viewer->setSceneData(osgDB::readNodeFile("cow.osg"));
viewer->addEventHandler(new MyEventHandler);
viewer->setUpViewInWindow(, , , );
while (!viewer->done())
{
viewer->frame();
}
Py_Finalize();
return ;
}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
def test(a,b):
return random.uniform(a, b)


project(PythonTest)
cmake_minimum_required(VERSION 2.8)
set(PythonSRC Person.py)
set(CMAKE_BUILD_TYPE Debug)
aux_source_directory(. SRC_LIST)
find_package(PythonLibs REQUIRED)
find_package(OpenSceneGraph 3.2. REQUIRED osg osgDB osgViewer osgGA)
include_directories(${PYTHON_INCLUDE_DIRS})
add_executable(${PROJECT_NAME} ${SRC_LIST} ${PythonSRC})
target_link_libraries(${PROJECT_NAME} ${PYTHON_LIBRARIES} ${OPENSCENEGRAPH_LIBRARIES})

 

测试结果:

  只是验证下效果,把改变位置的调用放在了每帧中,帧速太快。导致如图所示。

OSG+Python

相关文章