1 /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2013 Robert Osfield 2 * 3 * This library is open source and may be redistributed and/or modified under 4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 5 * (at your option) any later version. The full license is in LICENSE file 6 * included with this distribution, and on the openscenegraph.org website. 7 * 8 * This library is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * OpenSceneGraph Public License for more details. 12 */ 13 14 #include <osgDB/FileNameUtils> 15 #include <osgDB/FileUtils> 16 #include <osgDB/Registry> 17 18 #include "V8ScriptEngine.h" 19 20 class ReaderWriterV8 : public osgDB::ReaderWriter 21 { 22 public: 23 ReaderWriterV8()24 ReaderWriterV8() 25 { 26 supportsExtension("v8","JavaScript"); 27 supportsExtension("js","JavaScript"); 28 } 29 className() const30 virtual const char* className() const { return "V8 JavaScript ScriptEngine plugin"; } 31 readObject(std::istream & fin,const osgDB::ReaderWriter::Options * options=NULL) const32 virtual ReadResult readObject(std::istream& fin, const osgDB::ReaderWriter::Options* options =NULL) const 33 { 34 return readScript(fin, options); 35 } 36 readObject(const std::string & file,const osgDB::ReaderWriter::Options * options=NULL) const37 virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options =NULL) const 38 { 39 if (file=="ScriptEngine.V8") return new v8::V8ScriptEngine(); 40 if (file=="ScriptEngine.js") return new v8::V8ScriptEngine(); 41 42 return readScript(file); 43 } 44 readScript(std::istream & fin,const osgDB::ReaderWriter::Options * options=NULL) const45 virtual ReadResult readScript(std::istream& fin,const osgDB::ReaderWriter::Options* options =NULL) const 46 { 47 osg::ref_ptr<osg::Script> script = new osg::Script; 48 script->setLanguage("js"); 49 50 std::string str; 51 while(fin) 52 { 53 int c = fin.get(); 54 if (c>=0 && c<=255) 55 { 56 str.push_back(c); 57 } 58 } 59 script->setScript(str); 60 61 return script.release(); 62 } 63 readScript(const std::string & file,const osgDB::ReaderWriter::Options * options=NULL) const64 virtual ReadResult readScript(const std::string& file, const osgDB::ReaderWriter::Options* options =NULL) const 65 { 66 std::string ext = osgDB::getLowerCaseFileExtension(file); 67 if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; 68 69 std::string fileName = osgDB::findDataFile( file, options ); 70 if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; 71 72 osgDB::ifstream istream(fileName.c_str(), std::ios::in); 73 if(!istream) return ReadResult::FILE_NOT_HANDLED; 74 75 return readScript(istream, options); 76 } 77 }; 78 79 // now register with Registry to instantiate the above 80 // reader/writer. 81 REGISTER_OSGPLUGIN(v8, ReaderWriterV8) 82