FramePrinter::FramePrinter(iObjectRegistry *object_reg) : 
  scfImplementationType (this),
  g3d(csQueryRegistry<iGraphics3D> (object_reg))
{
  csRef<iEventQueue> queue = csQueryRegistry<iEventQueue> (object_reg);
  queue->RegisterListener(this, csevFrame (object_reg));
}
bool psEntityLabels::Initialize(iObjectRegistry * object_reg, psCelClient * _celClient)
{
    celClient  = _celClient;
    
    vfs = psengine->GetVFS();
    CS_ASSERT(vfs);
    
    eventhandler.AttachNew(new EventHandler(this));

    eventQueue =  csQueryRegistry<iEventQueue> (object_reg);
    if(!eventQueue)
    {
        Error1("No iEventQueue found!");
        CS_ASSERT(eventQueue);
        return false;
    }

    csEventID esub[] = {
      csevFrame (object_reg),
      //csevMouseEvent (object_reg),
      CS_EVENTLIST_END
    };
    eventQueue->RegisterListener(eventhandler, esub);

    LoadFromFile();
    return true;
}
FrameBegin3DDraw::FrameBegin3DDraw (iObjectRegistry *obj_reg, 
	csRef<iView> &the_view) :
  scfImplementationType (this),
  object_reg (obj_reg),
  g3d (csQueryRegistry<iGraphics3D> (obj_reg)),
  engine (csQueryRegistry<iEngine> (obj_reg)),
  view (the_view)
{
  csRef<iEventQueue> queue = csQueryRegistry<iEventQueue> (object_reg);
  queue->RegisterListener(this, csevFrame (object_reg));
}
psMovementManager::psMovementManager(iEventNameRegistry* eventname_reg, psControlManager* controls)
{
    CS_ASSERT(eventname_reg);
    event_frame = csevFrame(eventname_reg);
    event_mousemove = csevMouseMove(eventname_reg,0);

    actor = NULL;
    this->controls = controls;

    ready = false;
    psengine->GetMsgHandler()->Subscribe(this,MSGTYPE_MOVEINFO);
    psengine->GetMsgHandler()->Subscribe(this,MSGTYPE_MOVELOCK);
    psengine->GetMsgHandler()->Subscribe(this,MSGTYPE_MOVEMOD);

    defaultmode = NULL;
    actormode = NULL;

    onGround = true;
    locked = false;
    activeMoves = 0;

    autoMove = false;
    toggleRun = false;
    mouseAutoMove = false;
    mouseLook = false;
    mouseLookCanAct = false;
    mouseZoom = false;
    mouseMove = false;
    sneaking = false;
    runToMarkerID = 0;
    lastDist = 0.0f;
    runToDiff = csVector3(0.0f);
    lastDeltaX = 0.0f;
    lastDeltaY = 0.0f;

    sensY = 1.0f;
    sensX = 1.0f;
    invertedMouse = true;
    
    activeModType = psMoveModMsg::NONE;

    forward = NULL;
    backward = NULL;
    run = NULL;
    walk = NULL;

    kbdRotate = 0;
}
const csHandlerID * 
FrameSignpost_ConsoleDebug::GenericSucc(csRef<iEventHandlerRegistry> &r1,
					csRef<iEventNameRegistry> &r2,
					csEventID e) const 
{
  if (e == csevFrame(r2))
  {
    static csHandlerID constraint[2] =
    { 
      FrameSignpost_ConsoleDebug::StaticID (r1), 
      CS_HANDLERLIST_END
    };
    return constraint;
  }
  return 0;
}
bool ClientMsgHandler::Initialize(NetBase* nb, iObjectRegistry* object_reg)
{
    // Create and register inbound queue
    if (!MsgHandler::Initialize(nb))
        return false;

    ClientMsgHandler::object_reg = object_reg;

    // This hooks our HandleEvent function into main application event loop
    csRef<iEventQueue> queue =  csQueryRegistry<iEventQueue> (object_reg);
    if (!queue)
        return false;
    scfiEventHandler = new EventHandler(this);

    csEventID esub[] = { 
      csevFrame (object_reg),
      CS_EVENTLIST_END 
    };
    queue->RegisterListener(scfiEventHandler, esub);

    return true;
}
Example #7
0
bool Simple::OnInitialize(int /*argc*/, char* /*argv*/ [])
{
  // RequestPlugins() will load all plugins we specify. In addition
  // it will also check if there are plugins that need to be loaded
  // from the config system (both the application config and CS or
  // global configs). In addition it also supports specifying plugins
  // on the commandline.
  if (!csInitializer::RequestPlugins(GetObjectRegistry(),
    CS_REQUEST_VFS,
    CS_REQUEST_OPENGL3D,
    CS_REQUEST_ENGINE,
    CS_REQUEST_FONTSERVER,
    CS_REQUEST_IMAGELOADER,
    CS_REQUEST_LEVELLOADER,
    CS_REQUEST_REPORTER,
    CS_REQUEST_REPORTERLISTENER,
    CS_REQUEST_PLUGIN( "crystalspace.script.python", iScript ),
    CS_REQUEST_END))
    return ReportError("Failed to initialize plugins!");

  // "Warm up" the event handler so it can interact with the world
  csBaseEventHandler::Initialize(GetObjectRegistry());

  // Now we need to register the event handler for our application.
  // Crystal Space is fully event-driven. Everything (except for this
  // initialization) happens in an event.
  // Rather than simply handling all events, we subscribe to the
  // particular events we're interested in.
  csEventID events[] = {
    csevFrame (GetObjectRegistry()),
    csevKeyboardEvent (GetObjectRegistry()),
    CS_EVENTLIST_END
  };
  if (!RegisterQueue(GetObjectRegistry(), events))
    return ReportError("Failed to set up event handler!");

  // Report success
  return true;
}
Example #8
0
int main (int argc, char *argv[])
{
  G2DTestSystemDriver System (argc, argv);
  Sys = &System;
  iObjectRegistry* object_reg = System.object_reg;

  if (!csInitializer::SetupEventHandler (object_reg, G2DEventHandler))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.g2dtest",
        "Unable to init app!");
    return false;
  }

  // Check for commandline help.
  if (csCommandLineHelper::CheckHelp (object_reg))
  {
    csCommandLineHelper::Help (object_reg);
    exit (0);
  }

  csRef<iPluginManager> plugin_mgr (
  	csQueryRegistry<iPluginManager> (object_reg));
  csRef<iCommandLineParser> cmdline (
  	csQueryRegistry<iCommandLineParser> (object_reg));

  System.myG3D = csQueryRegistry<iGraphics3D> (object_reg);
  // Now load the renderer plugin
  if (!System.myG3D)
  {
    csString canvas = cmdline->GetOption ("video");
    if (!canvas || !*canvas)
      canvas = "crystalspace.graphics3d.opengl";
    else if (strncmp ("crystalspace.", canvas, 13))
    {
      canvas = "crystalspace.graphics3d." + canvas;
    }
    System.myG3D = csLoadPlugin<iGraphics3D> (plugin_mgr, canvas);
    if (!object_reg->Register (System.myG3D, "iGraphics3D"))
    {
      csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	  "crystalspace.application.g2dtest",
	  "Unable to register renderer!");
      return -1;
    }
  }

  if (!System.myG3D)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.g2dtest",
	"Unable to load canvas driver!");
    return -1;
  }
  System.myG2D = System.myG3D->GetDriver2D ();
    
  System.SystemOpen = csevSystemOpen (object_reg);
  System.KeyboardDown = csevKeyboardDown (object_reg);
  System.Frame = csevFrame (object_reg);
  System.CanvasResize = csevCanvasResize (object_reg, System.myG2D);

  System.framePrinter.AttachNew (new FramePrinter (object_reg));

  if (!csInitializer::OpenApplication (object_reg))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.g2dtest",
        "Unable to open drivers!");
    return -1;
  }
  
  System.cursorPlugin = csQueryRegistry<iCursor> (object_reg);
  if (System.cursorPlugin)
  {
    csRef<iConfigManager> cfg (csQueryRegistry<iConfigManager> (object_reg));
    if (System.cursorPlugin->Setup (System.myG3D))
    {
      System.cursorPlugin->ParseConfigFile ((iConfigManager*)cfg);
    }
    else
      System.cursorPlugin = 0;
  }

  iNativeWindow* nw = System.myG2D->GetNativeWindow ();
  if (nw) nw->SetTitle (APP_TITLE);

  csDefaultRunLoop(object_reg);

  System.myG2D = 0;
  System.myG3D->Close();
  System.myG3D = 0;
  plugin_mgr = 0;
  cmdline = 0;

  return 0;
}
Example #9
0
bool csShaderManager::Initialize(iObjectRegistry *objreg)
{
  objectreg = objreg;
  vc = csQueryRegistry<iVirtualClock> (objectreg);
  txtmgr = csQueryRegistry<iTextureManager> (objectreg);

  csRef<iVerbosityManager> verbosemgr (
    csQueryRegistry<iVerbosityManager> (objectreg));
  if (verbosemgr) 
    do_verbose = verbosemgr->Enabled ("renderer.shader");
  else
    do_verbose = false;

  Frame = csevFrame(objectreg);
  SystemOpen = csevSystemOpen(objectreg);
  SystemClose = csevSystemClose(objectreg);

  csRef<iEventHandlerRegistry> handlerReg = 
    csQueryRegistry<iEventHandlerRegistry> (objectreg);
  //eventSucc[0] = handlerReg->GetGenericID ("crystalspace.graphics3d");

  csRef<iEventQueue> q = csQueryRegistry<iEventQueue> (objectreg);
  if (q)
  {
    csEventID events[] = { Frame, SystemOpen, SystemClose, 
			    CS_EVENTLIST_END };
    RegisterWeakListener (q, this, events, weakEventHandler);
  }

  csRef<iPluginManager> plugin_mgr = 
	csQueryRegistry<iPluginManager> (objectreg);

  strings = csQueryRegistryTagInterface<iStringSet> (
    objectreg, "crystalspace.shared.stringset");
  stringsSvName = csQueryRegistryTagInterface<iShaderVarStringSet> (
    objectreg, "crystalspace.shader.variablenameset");

  {
    csRef<csNullShader> nullShader;
    nullShader.AttachNew (new csNullShader (this));
    nullShader->SetName ("*null");
    RegisterShader (nullShader);
  }

  config.AddConfig (objectreg, "/config/shadermgr.cfg");

  csRef<iStringArray> classlist =
    iSCF::SCF->QueryClassList("crystalspace.graphics3d.shadercompiler.");
  size_t const nmatches = classlist.IsValid() ? classlist->GetSize() : 0;
  if (nmatches != 0)
  {
    size_t i;
    for (i = 0; i < nmatches; ++i)
    {
      const char* classname = classlist->Get(i);
      csRef<iShaderCompiler> plugin = 
	csLoadPluginCheck<iShaderCompiler> (plugin_mgr, classname);
      if (plugin)
      {
	if (do_verbose)
	  Report (CS_REPORTER_SEVERITY_NOTIFY,
	    "Loaded compiler plugin %s, compiler: %s", 
	    classname,plugin->GetName());
        RegisterCompiler(plugin);
      }
    }
  }
  else
  {
    Report (CS_REPORTER_SEVERITY_WARNING, "No shader plugins found!");
  }
  
  csString cfgKey;
  const csString keyPrefix ("Video.ShaderManager.Tags.");
  csSet<csString> knownKeys;
  csRef<iConfigIterator> it (config->Enumerate (keyPrefix));
  while (it->HasNext ())
  {
    it->Next();
    const char* key = it->GetKey (true);
    const char* dot = strrchr (key, '.');
    cfgKey.Clear ();
    cfgKey.Append (key, dot - key);

    if (knownKeys.In ((const char*)cfgKey)) continue;
    knownKeys.Add ((const char*)cfgKey);

    const char* tagName = config->GetStr (
      keyPrefix + cfgKey + ".TagName", cfgKey);
    const char* tagPresence = config->GetStr (
      keyPrefix + cfgKey + ".Presence", "Neutral");
    int tagPriority = config->GetInt (
      keyPrefix + cfgKey + ".Priority", 0);

    csShaderTagPresence presence;
    if (strcasecmp (tagPresence, "neutral") == 0)
    {
      presence = TagNeutral;
    }
    else if (strcasecmp (tagPresence, "forbidden") == 0)
    {
      presence = TagForbidden;
    }
    else if (strcasecmp (tagPresence, "required") == 0)
    {
      presence = TagRequired;
    }
    else
    {
      Report (CS_REPORTER_SEVERITY_WARNING, 
	"Unknown shader tag presence '%s' for tag config '%s'",
	tagPresence, (const char*)cfgKey);
      continue;
    }
    csStringID tagID = strings->Request (tagName);
    SetTagOptions (tagID, presence, tagPriority);
  }

  sv_time.AttachNew (new csShaderVariable (stringsSvName->Request ("standard time")));
  sv_time->SetValue (0.0f);
  
  if (config->GetBool ("Video.ShaderManager.EnableShaderCache", false))
  {
    bool redundantRemove =
      config->GetBool ("Video.ShaderManager.ShaderCache.RedundantRemove", true);
    shaderCache.AttachNew (new PlexHierarchicalCache (redundantRemove));
    
    csRef<CS::Utility::VfsHierarchicalCache> cache;
    const char* cachePath;
    
    cachePath = config->GetStr ("Video.ShaderManager.ShaderCachePath.User",
      "/shadercache/user");
    if (cachePath && *cachePath)
    {
      cache.AttachNew (new CS::Utility::VfsHierarchicalCache (objectreg,
	csString().Format ("%s/" CS_VERSION_MAJOR "." CS_VERSION_MINOR,
	cachePath)));
      shaderCache->AddSubShaderCache (cache, cachePriorityUser);
    }
    
    cachePath = config->GetStr ("Video.ShaderManager.ShaderCachePath.App",
      0);
    if (cachePath && *cachePath)
    {
      cache.AttachNew (new CS::Utility::VfsHierarchicalCache (objectreg,
	cachePath));
      cache->SetReadOnly (true);
      shaderCache->AddSubShaderCache (cache, cachePriorityApp);
    }
      
    cachePath = config->GetStr ("Video.ShaderManager.ShaderCachePath.Global",
      "/shadercache/global");
    if (cachePath && *cachePath)
    {
      cache.AttachNew (new CS::Utility::VfsHierarchicalCache (objectreg,
	cachePath));
      cache->SetReadOnly (true);
      shaderCache->AddSubShaderCache (cache, cachePriorityGlobal);
    }
  }

  return true;
}
Example #10
0
File: win32.cpp Project: garinh/cs
Win32Assistant::Win32Assistant (iObjectRegistry* r) 
  : scfImplementationType (this),
  ApplicationActive (true),
  ModuleHandle (0),
  console_window (false),  
  is_console_app(false),
  cmdline_help_wanted(false),
  EventOutlet (0),
  mouseButtons(0)
{
  ModuleHandle = GetModuleHandle(0);
  STARTUPINFO startupInfo;
  GetStartupInfo (&startupInfo);
  if (startupInfo.dwFlags & STARTF_USESHOWWINDOW)
    ApplicationShow = startupInfo.wShowWindow;
  else
    ApplicationShow = SW_SHOWNORMAL;

// Cygwin has problems with freopen()
#if defined(CS_DEBUG) || defined(__CYGWIN__)
  console_window = true;
#else
  console_window = false;
#endif

  use_own_message_loop = true;

  csRef<iCommandLineParser> cmdline (csQueryRegistry<iCommandLineParser> (r));
  console_window = cmdline->GetBoolOption ("console", console_window);

  cmdline_help_wanted = (cmdline->GetOption ("help") != 0);

  /*
     to determine if we are actually a console app we look up
     the subsystem field in the PE header.
   */
  PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)ModuleHandle;
  PIMAGE_NT_HEADERS NTheader = (PIMAGE_NT_HEADERS)((uint8*)dosHeader + dosHeader->e_lfanew);
  if (NTheader->Signature == 0x00004550) // check for PE sig
  {
    is_console_app = 
      (NTheader->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
  }

  /*
    - console apps won't do anything about their console... yet. 
    - GUI apps will open a console window if desired.
   */
  if (!is_console_app)
  {
    if (console_window || cmdline_help_wanted)
    {
      AllocConsole ();
      /* "Redirect" C runtime standard files to console, if not redirected 
       * by the user. */
      if (!IsStdHandleRedirected (STD_ERROR_HANDLE)) 
        freopen("CONOUT$", "a", stderr);
      if (!IsStdHandleRedirected (STD_OUTPUT_HANDLE)) 
        freopen("CONOUT$", "a", stdout);
      if (!IsStdHandleRedirected (STD_INPUT_HANDLE)) 
        freopen("CONIN$", "r", stdin);
    }
  }

  /*
    In case we're a console app, set up a control handler so
    console window closing, user logoff and system shutdown
    cause CS to properly shut down.
   */
  if (is_console_app || console_window || cmdline_help_wanted)
  {
    SetConsoleCtrlHandler (&ConsoleHandlerRoutine, TRUE);
  }

  // experimental UC stuff.
  // Retrieve old codepage.
  //oldCP = GetConsoleOutputCP ();
  // Try to set console codepage to UTF-8.
  // @@@ The drawback of UTF8 is that it requires a TrueType console
  // font to work properly. However, default is "raster font" :/
  // In this case, text output w/ non-ASCII chars will appear broken, tho
  // this is really a Windows issue. (see MS KB 99795)
  // @@@ Maybe a command line param to set a different con cp could be useful.
  // * Don't change the codepage, for now.
  //SetConsoleOutputCP (CP_UTF8);
  //

  registry = r;

  HICON appIcon;

  // try the app icon...
  appIcon = LoadIcon (ModuleHandle, MAKEINTRESOURCE (1));
  // not? maybe executable.ico?
  if (!appIcon) 
  {
    char apppath[MAX_PATH];
    GetModuleFileName (0, apppath, sizeof(apppath));

    char *dot = strrchr (apppath, '.');
    if (dot) 
    {
      strcpy (dot, ".ico");
    }
    else
    {
      strcat (apppath, ".ico");
    }
    appIcon = (HICON)LoadImageA (ModuleHandle, apppath, IMAGE_ICON,
      0, 0, LR_DEFAULTSIZE | LR_LOADFROMFILE);
  }
  // finally the default one
  if (!appIcon) appIcon = LoadIcon (0, IDI_APPLICATION);
  
  csString wndClass;
  wndClass.Format ("CrystalSpaceWin32_%p", (void*)this);

  bool bResult = false;
  HBRUSH backBrush = (HBRUSH)::GetStockObject (BLACK_BRUSH);
  if (cswinIsWinNT ())
  {
    WNDCLASSEXW wc;
    
    windowClass = new uint8[(wndClass.Length()+1) * sizeof (WCHAR)];
    csUnicodeTransform::UTF8toWC ((wchar_t*)windowClass,
      wndClass.Length()+1, (utf8_char*)(wndClass.GetData()), (size_t)-1);

    wc.cbSize	      = sizeof (wc);
    wc.hCursor        = 0;
    wc.hIcon          = appIcon;
    wc.lpszMenuName   = 0;
    wc.lpszClassName  = (WCHAR*)windowClass;
    wc.hbrBackground  = backBrush;
    wc.hInstance      = ModuleHandle;
    wc.style          = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc    = WindowProc;
    wc.cbClsExtra     = 0;
    wc.cbWndExtra     = 2*sizeof (LONG_PTR);
    wc.hIconSm	      = 0;
    bResult = RegisterClassExW (&wc) != 0;
  }
  else
  {
    WNDCLASSEXA wc;
    
    windowClass = new uint8[wndClass.Length()+1];
    strcpy ((char*)windowClass, wndClass);

    wc.cbSize	      = sizeof (wc);
    wc.hCursor        = 0;
    wc.hIcon          = appIcon;
    wc.lpszMenuName   = 0;
    wc.lpszClassName  = (char*)windowClass;
    wc.hbrBackground  = backBrush;
    wc.hInstance      = ModuleHandle;
    wc.style          = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc    = WindowProc;
    wc.cbClsExtra     = 0;
    wc.cbWndExtra     = 2*sizeof (LONG_PTR);
    wc.hIconSm	      = 0;
    bResult = RegisterClassExA (&wc) != 0;
  }

  if (!bResult)
  {
    SystemFatalError ("Failed to register window class!");
  }

  m_hCursor = LoadCursor (0, IDC_ARROW);

  csRef<iEventQueue> q (csQueryRegistry<iEventQueue> (registry));
  CS_ASSERT (q != 0);
  csEventID events[] = {
    csevFrame (registry),
    csevSystemOpen (registry),
    csevSystemClose (registry),
    csevCommandLineHelp (registry),
    CS_EVENTLIST_END
  };
  q->RegisterListener (this, events);
  CS_INITIALIZE_SYSTEM_EVENT_SHORTCUTS (registry);
  CS_INITIALIZE_FRAME_EVENT_SHORTCUTS (registry);
  Quit = csevQuit (registry);
  CommandLineHelp = csevCommandLineHelp (registry);
  FocusGained = csevFocusGained (registry);
  FocusLost = csevFocusLost (registry);
  //CanvasExposed = csevCanvasExposed (registry, "graph2d");
  //CanvasHidden = csevCanvasHidden (registry, "graph2d");

  // Put our own keyboard driver in place.
#include "csutil/custom_new_disable.h"
  kbdDriver.AttachNew (new csWin32KeyboardDriver (r));
  if (kbdDriver == 0)
  {
    SystemFatalError ("Failed to create keyboard driver!");
  }

  csRef<iBase> currentKbd = 
    csQueryRegistryTag (r, "iKeyboardDriver");
  if (currentKbd != 0)
  {
    // Bit hacky: remove old keyboard driver
    csRef<iEventHandler> eh =  
      scfQueryInterface<iEventHandler> (currentKbd);
    q->RemoveListener (eh);
    r->Unregister (currentKbd, "iKeyboardDriver");
  }
  r->Register (kbdDriver, "iKeyboardDriver");
}
Example #11
0
bool csWaterDemo::Initialize ()
{
  if (!csInitializer::SetupConfigManager (object_reg, 
    "/config/waterdemo.cfg"))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, 
      "crystalspace.application.waterdemo",
      "Failed to initialize config!");
    return false;
  }

  if (!csInitializer::RequestPlugins (object_reg,
  	CS_REQUEST_VFS,
        CS_REQUEST_PLUGIN ("crystalspace.graphics3d.opengl", iGraphics3D),
        CS_REQUEST_ENGINE,
	CS_REQUEST_IMAGELOADER,
	CS_REQUEST_FONTSERVER,
	CS_REQUEST_REPORTER,
	CS_REQUEST_REPORTERLISTENER,
        CS_REQUEST_CONSOLEOUT,
        CS_REQUEST_LEVELLOADER,
 	CS_REQUEST_END))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
	"Can't initialize plugins!");
    return false;
  }

  FocusGained = csevFocusGained (object_reg);
  FocusLost = csevFocusLost (object_reg);
  Frame = csevFrame (object_reg);
  KeyboardDown = csevKeyboardDown (object_reg);

  if (!csInitializer::SetupEventHandler (object_reg, SimpleEventHandler))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
	"Can't initialize event handler!");
    return false;
  }

  // Check for commandline help.
  if (csCommandLineHelper::CheckHelp (object_reg))
  {
    csCommandLineHelper::Help (object_reg);
    return false;
  }

  vc = csQueryRegistry<iVirtualClock> (object_reg);
  if (vc == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
    	"No iVirtualClock plugin!");
    return false;
  }

  vfs = csQueryRegistry<iVFS> (object_reg);
  if (vfs == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
    	"No iVFS plugin!");
    return false;
  }

  r3d = csQueryRegistry<iGraphics3D> (object_reg);
  if (r3d == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
    	"No iGraphics3D plugin!");
    return false;
  }

  font = r3d->GetDriver2D ()->GetFontServer()->LoadFont(CSFONT_LARGE);

  engine = csQueryRegistry<iEngine> (object_reg);
  if (engine == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
    	"No iEngine plugin!");
    return false;
  }

  kbd = csQueryRegistry<iKeyboardDriver> (object_reg);
  if (kbd == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
    	"No iKeyboardDriver plugin!");
    return false;
  }

  mouse = csQueryRegistry<iMouseDriver> (object_reg);
  if (mouse == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
    	"No iMouseDriver plugin!");
    return false;
  }

  csRef<iLoader> loader = csQueryRegistry<iLoader> (object_reg);
  if (loader == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
    	"No iLoader plugin!");
    return false;
  }

  vfs->ChDir ("/tmp");
  
  console = csQueryRegistry<iConsoleOutput> (object_reg);

  // Open the main system. This will open all the previously loaded plug-ins.
  if (!csInitializer::OpenApplication (object_reg))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.waterdemo",
    	"Error opening system!");
    return false;
  }

  csRef<iSector> room = engine->CreateSector ("room");

  view = csPtr<iView> (new csView (engine, r3d));
  view->GetCamera ()->SetSector (room);
  view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, 0));
  view->GetCamera ()->GetTransform ().LookAt (csVector3(5,-5,20), csVector3(0,1,0));
  csRef<iGraphics2D> g2d = r3d->GetDriver2D ();
  view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ());

  bool hasAccel;
  if (g2d->PerformExtension ("hardware_accelerated", &hasAccel))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,
      "crystalspace.application.waterdemo",
      "Hardware acceleration %s.\n",
      hasAccel ? "present" : "not present");
  }
  else
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,
      "crystalspace.application.waterdemo",
      "Hardware acceleration check not available.\n");
  }

  r3d->GetDriver2D ()->SetMouseCursor( csmcNone );

  csRef<iPluginManager> plugin_mgr (
    csQueryRegistry<iPluginManager> (object_reg));

  csRef<iStringSet> strings = 
    csQueryRegistryTagInterface<iStringSet> 
    (object_reg, "crystalspace.shared.stringset");

  csRef<iShaderVarStringSet> stringsSvName = 
    csQueryRegistryTagInterface<iShaderVarStringSet> 
    (object_reg, "crystalspace.shader.variablenameset");

  //get a custom renderloop
  csRef<iRenderLoop> rl = engine->GetRenderLoopManager ()->Create ();
  
  csRef<iRenderStepType> genType = csLoadPlugin<iRenderStepType> (
    plugin_mgr, "crystalspace.renderloop.step.generic.type");

  csRef<iRenderStepFactory> genFact = genType->NewFactory ();

  csRef<iRenderStep> step;
  csRef<iGenericRenderStep> genStep;

  step = genFact->Create ();
  rl->AddStep (step);
  genStep = scfQueryInterface<iGenericRenderStep> (step);

  genStep->SetShaderType ("general");
  genStep->SetZBufMode (CS_ZBUF_USE);
  genStep->SetZOffset (false);

  engine->GetRenderLoopManager ()->Register ("waterdemoRL", rl);
  engine->SetCurrentDefaultRenderloop (rl);

  // Load in lighting shaders
  csRef<iVFS> vfs (csQueryRegistry<iVFS> (object_reg));
  csRef<iFile> shaderFile = vfs->Open ("/shader/water.xml", VFS_FILE_READ);

  csRef<iDocumentSystem> docsys (
    csQueryRegistry<iDocumentSystem> (object_reg));
  csRef<iDocument> shaderDoc = docsys->CreateDocument ();
  shaderDoc->Parse (shaderFile, true);

  csRef<iShader> shader;
  csRef<iShaderManager> shmgr (csQueryRegistry<iShaderManager> (object_reg));
  csRef<iShaderCompiler> shcom (shmgr->GetCompiler ("XMLShader"));
  csRef<iLoaderContext> ldr_context = engine->CreateLoaderContext ();
  shader = shcom->CompileShader (ldr_context,
      shaderDoc->GetRoot ()->GetNode ("shader"));

  // setup the mesh 
  csRef<iMeshObjectType> gType = csLoadPluginCheck<iMeshObjectType> (
  	plugin_mgr, "crystalspace.mesh.object.genmesh");
  
  if (!gType)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.waterdemo",
        "Error loading genmesh baseobject!");
    return false;
  }

  
  gFact = gType->NewFactory ();
  csRef<iMeshFactoryWrapper> fw = engine->CreateMeshFactory (gFact, "waterFactory");
  gFactState = scfQueryInterface<iGeneralFactoryState> (gFact);

  gMesh = gFact->NewInstance ();
  gMeshState = scfQueryInterface<iGeneralMeshState> (gMesh);
  gMeshState->SetShadowCasting (false);
  gMeshState->SetShadowReceiving (false);

  //setup a wrapper too
  gMeshW = engine->CreateMeshWrapper (gMesh, "water", room);
  csMatrix3 m;
  m.Identity ();
  gMeshW->GetMovable ()->SetTransform (m);
  gMeshW->GetMovable ()->SetPosition (csVector3(0,-5,0));
  gMeshW->GetMovable ()->UpdateMove ();
  
  //setup a material
  csRef<iMaterial> mat = engine->CreateBaseMaterial (0);

  mat->SetShader (strings->Request ("general"), shader);

  csRef<iMaterialWrapper> matW = engine->GetMaterialList ()->NewMaterial (mat,
  	"waterMaterial");


  csRef<csImageCubeMapMaker> cubeMaker;
  cubeMaker.AttachNew (new csImageCubeMapMaker ());

  csRef<iImage> img = loader->LoadImage ("/lib/cubemap/cubemap_rt.jpg");
  cubeMaker->SetSubImage (0, img);
  img = loader->LoadImage ("/lib/cubemap/cubemap_lf.jpg");
  cubeMaker->SetSubImage (1, img);

  img = loader->LoadImage ("/lib/cubemap/cubemap_up.jpg");
  cubeMaker->SetSubImage (2, img);
  img = loader->LoadImage ("/lib/cubemap/cubemap_dn.jpg");
  cubeMaker->SetSubImage (3, img);

  img = loader->LoadImage ("/lib/cubemap/cubemap_fr.jpg");
  cubeMaker->SetSubImage (4, img);
  img = loader->LoadImage ("/lib/cubemap/cubemap_bk.jpg");
  cubeMaker->SetSubImage (5, img);


  csRef<iTextureHandle> tex = r3d->GetTextureManager ()->RegisterTexture (
    cubeMaker, CS_TEXTURE_3D | CS_TEXTURE_CLAMP | CS_TEXTURE_NOMIPMAPS);

  csRef<csShaderVariable> attvar (csPtr<csShaderVariable> (
    new csShaderVariable (stringsSvName->Request ("tex diffuse"))));
  attvar->SetValue (tex);
  mat->AddVariable (attvar);  


  gMesh->SetMaterialWrapper (matW);
  
  Width = Height = 64;

  water = new float[Width*Height];
  water1 = new float[Width*Height];
  water2 = new float[Width*Height];

  memset(water,0,Width*Height*sizeof(float));
  memset(water1,0,Width*Height*sizeof(float));
  memset(water2,0,Width*Height*sizeof(float));

  WaveSpeed = 0.3f;
  WaveLife = 0.1f;
  GridSize = 0.25f;
  TimeDelta = 0.12f;


  //setup the mesh
  gFactState->SetVertexCount (Width*Height);
  gFactState->SetTriangleCount (2*((Width-1)*(Height-1)));

  //setup ibuf
  int x, z, cnt=0,idx;
  csTriangle *ibuf=gFactState->GetTriangles ();
  for(x=0;x<(Height-1);x++)
  {
    for(z=0;z<(Width-1);z++)
    {
      idx = 2*(x*(Width-1)+z);
      ibuf[idx].a = x*Width+z;
      ibuf[idx].b = x*Width+z+1;
      ibuf[idx].c = (x+1)*Width+z;
      idx++;
      ibuf[idx].a = x*Width+z+1;
      ibuf[idx].b = (x+1)*Width+(z+1);
      ibuf[idx].c = (x+1)*Width+z;
    }
  }

  //setup our vbuf
  csVector3 *vbuf = gFactState->GetVertices ();
  cnt=0;
  for(x=0;x<Height;x++)
  {
    for(z=0;z<Width;z++)
    {
      idx = x*Width+z;
      vbuf[idx].x = x*GridSize;
      vbuf[idx].y = water[idx];
      vbuf[idx].z = z*GridSize;
    }
  }

  //setup texture
  csVector2 *tbuf = gFactState->GetTexels ();
  for(x=0;x<Height;x++)
  {
    for(z=0;z<Width;z++)
    {
      idx = x*Width+z;
      tbuf[idx].x = (float)x/(float)Height;
      tbuf[idx].y = (float)z/(float)Width;
    }
  }

  lastSimTime = nextSimTime = 0.0f;

  gFactState->Invalidate ();

  engine->Prepare ();

  console->SetVisible (false);
  hasfocus = true;
  int w = r3d->GetDriver2D ()->GetWidth()/2;
  int h = r3d->GetDriver2D ()->GetHeight()/2;
  r3d->GetDriver2D ()->SetMousePosition (w, h);

  printer.AttachNew (new FramePrinter (object_reg));

  return true;
}
Example #12
0
/*
 * iComponent interface
 */
bool csSndSysRendererOpenAL::Initialize (iObjectRegistry *obj_reg)
{
  if (!libopenal_is_present)
  {
    Report (CS_REPORTER_SEVERITY_WARNING, "OpenAL is not available (libopenal is missing)");
    return false;
  }
  
  // Save the object registry for later use
  m_ObjectRegistry = obj_reg;

  Report (CS_REPORTER_SEVERITY_DEBUG, "Initializing OpenAL sound system");

  // Read the config file
  m_Config.AddConfig (obj_reg, "/config/sound.cfg");

  // Get a list of OpenAL devices:
  // The spec says it's an ALCchar, but my headers include no such type.
  // The format is a series of strings separatrd by nulls, teminated by a
  // double null.
  Report (CS_REPORTER_SEVERITY_DEBUG, "Retrieving available devices.");
  const ALCchar *devices = alcGetString (0, ALC_DEVICE_SPECIFIER);
  // Loop while there is no second null
  while (*devices != 0) {
    Report (CS_REPORTER_SEVERITY_DEBUG, "Available OpenAL device: %s", devices);
    // Seek until the null
    while (*devices != 0)
      devices++;
    // Skip the null
    devices++;
  }

  // Report the default device.
  Report (CS_REPORTER_SEVERITY_DEBUG, "Default OpenAL device: %s", alcGetString (0, ALC_DEFAULT_DEVICE_SPECIFIER));

  // Check if a specific device is specified
  const ALCchar *device = m_Config->GetStr ("SndSys.OpenALDevice", 0);
  if (device == 0) {
    // The config did not contain a device to use
    Report (CS_REPORTER_SEVERITY_DEBUG, "No device specified");
  } else {
    // Attempt to open the spcified device
    m_Device = alcOpenDevice (device);
    if (m_Device == 0) {
      // Failed to open the device
      Report (CS_REPORTER_SEVERITY_WARNING, "Unable to open device %s", device);
    }
  }

  // If we still don't have a device, try the default:
  if (m_Device == 0) {
    Report (CS_REPORTER_SEVERITY_DEBUG, "Falling back on default device");
    m_Device = alcOpenDevice (0);
    if (m_Device == 0) {
      // Even that failed, give up.
      Report (CS_REPORTER_SEVERITY_ERROR, "Unable to open device");
      return false;
    }
  }

  // Check some OpenAL context attributes/capabilities
  // http://opensource.creative.com/pipermail/openal/2006-February/009337.html
  ALCenum err;
  ALCint attrSize = 0;
  ALCint *attributes;
  ALCint *data;
  alcGetIntegerv(m_Device, ALC_ATTRIBUTES_SIZE, sizeof(ALCint), &attrSize);
  err = alcGetError (m_Device);
  if (err == ALC_NO_ERROR)
  {
    attributes = (ALCint *)cs_malloc(attrSize * sizeof(ALCint));
    alcGetIntegerv(m_Device, ALC_ALL_ATTRIBUTES, attrSize, attributes);
    err = alcGetError (m_Device);
    if (err == ALC_NO_ERROR)
    {
      data = attributes;
      while (data < attributes + attrSize)
      {
	switch (*data)
	{
	  case ALC_FREQUENCY:
	    data += 1;
	    Report (CS_REPORTER_SEVERITY_DEBUG, "OpenAL context frequency: %d Hz",
	      *data);
	    break;
	  case ALC_REFRESH:
	    data += 1;
	    Report (CS_REPORTER_SEVERITY_DEBUG, "OpenAL context refresh: %d Hz",
	      *data);
	    break;
	  case ALC_SYNC:
	    data += 1;
	    Report (CS_REPORTER_SEVERITY_DEBUG,
	      "OpenAL context uses %s (%sthreaded) context",
	      *data ? "synchronous": "asynchronous", *data ? "non " : "");
	    break;
	  case ALC_MONO_SOURCES:
	    data += 1;
	    Report (CS_REPORTER_SEVERITY_DEBUG,
	      "OpenAL context should support %d mono sources", *data);
	    break;
	  case ALC_STEREO_SOURCES:
	    data += 1;
	    Report (CS_REPORTER_SEVERITY_DEBUG,
	      "OpenAL context should support %d stereo sources", *data);
	    break;
	  default:
	    break;
	}
	data += 1;
      }
    }
    else
      Report (CS_REPORTER_SEVERITY_DEBUG,
	"Can't retrieve attributes: OpenAL error %s",
	ALCErrors.StringForIdent (err));
    cs_free(attributes);
  }
  else
    Report (CS_REPORTER_SEVERITY_DEBUG,
      "Can't retrieve attributes size: OpenAL error %s",
      ALCErrors.StringForIdent (err));

  // Configure sound sources
  SndSysSourceOpenAL2D::Configure( m_Config );

  // Register for event callbacks.
  csRef<iEventQueue> q (csQueryRegistry<iEventQueue> (m_ObjectRegistry));
  evSystemOpen = csevSystemOpen(m_ObjectRegistry);
  evSystemClose = csevSystemClose(m_ObjectRegistry);
  evFrame = csevFrame(m_ObjectRegistry);
  if (q != 0) {
    csEventID subEvents[] = { evSystemOpen, evSystemClose, evFrame, CS_EVENTLIST_END };
    q->RegisterListener(this, subEvents);
  }

  return true;
}