branch_name
stringclasses
22 values
content
stringlengths
18
81.8M
directory_id
stringlengths
40
40
languages
sequence
num_files
int64
1
7.38k
repo_language
stringlengths
1
23
repo_name
stringlengths
7
101
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>const express = require("express"); const server = express(); const PORT = 3000; const HOST = "http://localhost"; //set path to server static files (public) server.use(express.static("public")); server.get("/", (req, res) => { //NOTE: This will NOT override the (index) file in the public directory res.send( JSON.stringify({ status: "ok", }), ); }); server.listen(PORT, () => { console.log(`Example app listening on port ${HOST}:${PORT}!`); }); <file_sep>//command line playground import webpackConfig from "laravel-mix/setup/webpack.config"; console.log(webpackConfig, {}); <file_sep>### Browser View plugin for Visual Studio Code (VSC) <file_sep><template> <div class="component-editor w-full"> <h2 class="mb-2">Hot Module Reloading works fine.</h2> <p class="mb-2"> try to edit the source in <code>src/js/components/Example.vue</code></p> <p> <strong>{{ count }}</strong> <button class="bg-white px-2 rounded" @click="increment">+</button> </p> </div> </template> <script> export default { data() { return { count: 0 }; }, mounted() { console.log("Component mounted."); }, methods: { increment: function() { this.count += 1; } } }; </script> <style> </style>
5e06af96d4e929d40eb8d6a964ef2ca1ba987b77
[ "Markdown", "Vue", "JavaScript" ]
4
Markdown
moealmaw/vscode-browser-view
3911b1fbff6da0d8cfed6451fddafa8dc4ac99b2
1d447e46c0b87ddfeb2014fbab60184494607b96
refs/heads/master
<repo_name>demmonic/BetBot<file_sep>/src/demmonic/bot/util/StringUtils.java package demmonic.bot.util; import java.util.HashMap; /** * A set of string utilities * @author Demmonic * */ public final class StringUtils { private StringUtils() { } private static final HashMap<Character, Character> UNDETECABLE_MAP = new HashMap<Character, Character>(); static { UNDETECABLE_MAP.put('A', 'Α'); UNDETECABLE_MAP.put('B', 'Β'); } /** * @param s * @return A copy of the provided string that's undetectable by night bot */ public static String makeUndetectable(String s) { for (Character c : UNDETECABLE_MAP.keySet()) { s.replace(c, UNDETECABLE_MAP.get(c)); } return s; } } <file_sep>/src/demmonic/bot/core/blocking/BlockingBot.java package demmonic.bot.core.blocking; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.jibble.pircbot.PircBot; import demmonic.bot.core.IRCMessageEnvelope; import demmonic.bot.core.IRCMessageListener; /** * Represents a {@link PircBot} that blocks on a thread until a message is received, and then dispatches the message * to a list of {@link IRCMessageListener}s * @author Demmonic * */ public abstract class BlockingBot extends PircBot implements Runnable { private final BlockingQueue<IRCMessageEnvelope> blockingQueue = new ArrayBlockingQueue<IRCMessageEnvelope>(1); private final List<IRCMessageListener> listeners = new LinkedList<IRCMessageListener>(); @Override public final void onMessage(String channel, String sender, String login, String hostname, String message) { blockingQueue.add(new IRCMessageEnvelope(channel, sender, login, hostname, message)); } /** * Registers a new message listener to the blocking thread * @param l */ public final void registerListener(IRCMessageListener l) { this.listeners.add(l); } @Override public final void run() { while (true) { try { IRCMessageEnvelope message = blockingQueue.take(); if (message == null) continue; for (IRCMessageListener l : listeners) { l.onMessage(message); } } catch (InterruptedException e) { e.printStackTrace(); } } } } <file_sep>/data/launch_config.ini # Launch configuration file for https://github.com/demmonic/BetBot # Author: demmonic # The username to connect to twitch's server with username=x # The oauth to connect to twitch's server with # can be generated at http://www.twitchapps.com/tmi/ oauth=oauth:x # The channel that the bot will join on start channel=#sataniic # The path to store the point database at db=./data/db/points.odb<file_sep>/src/demmonic/bot/impl/GamblingBot.java package demmonic.bot.impl; import java.util.ArrayList; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; import demmonic.bot.core.IRCMessageEnvelope; import demmonic.bot.core.IRCMessageListener; import demmonic.bot.core.objectdb.ObjectDatabaseBot; import demmonic.bot.impl.command.AddCommandParser; import demmonic.bot.impl.command.BetCommandParser; import demmonic.bot.impl.command.PointsCommandParser; /** * * Represents an IRC bot that processes commands related to gambling (!add, !bet, etc) * @author Demmonic * */ public final class GamblingBot extends ObjectDatabaseBot implements IRCMessageListener { private static final ArrayList<GambleMessageParser> commands = new ArrayList<GambleMessageParser>(); static { commands.add(new AddCommandParser()); commands.add(new BetCommandParser()); commands.add(new PointsCommandParser()); } /** * @param username * @param oauth * @param factory */ public GamblingBot(String username, String oauth, EntityManagerFactory factory) { super(username, oauth, factory); super.registerListener(this); getEntityManager().getTransaction().begin(); getEntityManager().persist(new GamblingUserEntry("")); getEntityManager().getTransaction().commit(); } @Override public void onMessage(IRCMessageEnvelope ircMessage) { String channel = ircMessage.getChannel(); String sender = ircMessage.getSender(); String message = ircMessage.getMessage(); String[] parts = message.split(" "); String identifier = parts[0].replace("!", ""); if (message.startsWith("!")) { for (GambleMessageParser c : commands) { if (c.getIdentifier().equals(identifier)) { getEntityManager().getTransaction().begin(); Query query = getEntityManager().createQuery( "SELECT c FROM GamblingUserEntry c WHERE c.name = '" + sender + "'"); GamblingUserEntry user = null; if (query.getResultList().size() > 0) { user = (GamblingUserEntry)query.getSingleResult(); } if (user == null) { user = new GamblingUserEntry(sender); getEntityManager().persist(user); } c.parse(this, channel, user, message); getEntityManager().getTransaction().commit(); } } } } } <file_sep>/src/demmonic/bot/core/TwitchBot.java package demmonic.bot.core; import java.io.IOException; import org.jibble.pircbot.IrcException; import org.jibble.pircbot.NickAlreadyInUseException; import demmonic.bot.core.blocking.BlockingBot; /** * Represents an IRC bot that interacts with the twitch IRC channels * @author Demmonic * */ public abstract class TwitchBot extends BlockingBot { private static final String IRC_IP = "irc.twitch.tv"; private static final int IRC_PORT = 6667; private final String username, oauth; private long lastSent = 0; /** * @param username * @param oauth */ public TwitchBot(String username, String oauth) { this.username = username; this.oauth = oauth; } /** * Sends a message to the provided channel if the last message was sent over 2 seconds ago * @param channel * The channel to send the message to * @param message * The message to send */ public final void sendLimitedMessage(String channel, String message) { long timeSince = System.currentTimeMillis() - lastSent; if (timeSince >= 2000) { lastSent = System.currentTimeMillis(); super.sendMessage(channel, message); } } /** * Attempts to connect to the twitch IRC server using the provided username and oauth, and starts the blocking * message thread * @throws IrcException * @throws IOException * @throws NickAlreadyInUseException */ public final void connectToTwitch() throws NickAlreadyInUseException, IOException, IrcException { super.setName(username); super.connect(IRC_IP, IRC_PORT, oauth); Thread t = new Thread(this); t.start(); } } <file_sep>/src/demmonic/bot/util/RandomUtils.java package demmonic.bot.util; import java.util.Random; /** * A set of {@link Random} utilities * @author Demmonic * */ public final class RandomUtils { private RandomUtils() { } private static final Random RANDOM = new Random(); public static int nextInt(int max) { return RANDOM.nextInt(max); } }
7270ddf1f9690bfd32ec3aa5789d4de6d66b99d5
[ "Java", "INI" ]
6
Java
demmonic/BetBot
1cbd6e2642350f0c21c4f74c3979b84d7a82b240
93a8c113d383efd13c9620415fd475c57d387bf7
refs/heads/master
<file_sep>// // MGRouter.swift // last_fm_search // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation public struct MGRouter { static var debug = false static let encodingStratagy = JSONEncoder.KeyEncodingStrategy.useDefaultKeys static let decodingStratagy = JSONDecoder.KeyDecodingStrategy.useDefaultKeys /// urlsession data task static var task: URLSessionDataTask? static var session: MGSessionProtocol = MGSession.shared var input: MGRouterInputProtocol var baseUrl: String { return input.host } /// custom headers var headers: [String: String] { return input.headers } var method: String { return input.method.rawValue } var timeout: TimeInterval { return TimeInterval(input.timeout) } var body: Data? { return input.body } /// final url var url: URL { let strUrl = String(format: "%@%@", baseUrl, input.endpoint) return URL(string: strUrl)! } var request: URLRequest { var request: URLRequest = URLRequest(url: url) request.httpMethod = method request.timeoutInterval = timeout request.httpBody = body for (key, value) in headers { request.addValue(value, forHTTPHeaderField: key) } return request } } extension MGRouter { public func call<T: Decodable>(callback: @escaping (Result<T?, Error>) -> Void) { self.apiCall(callback: callback) } /// make network api calls /// - Parameter callback: callback blocak internal func apiCall<T: Decodable>(callback: @escaping (Result<T?, Error>) -> Void) { MGRouter.task = MGRouter.session.session!.dataTask(with: request) { (data, response, error) in let responseStatusCode = (response as? HTTPURLResponse)?.statusCode ?? 0 if let error = error { DispatchQueue.main.async { callback(.failure(error)) } return } guard let data = data, error == nil else { DispatchQueue.main.async { let error = NSError(domain: "com.moin.error", code: responseStatusCode, userInfo: ["description": "Invalid data"]) callback(.failure(error)) } return } if data.isEmpty { DispatchQueue.main.async { let error = NSError(domain: "com.moin.error", code: responseStatusCode, userInfo: ["description": "Empty response"]) callback(.failure(error)) } return } if MGRouter.debug { print("=================\nREQUEST\n=================") print("URL: \(self.url)") print("-----------------\nMETHOD:\(self.method)\n-----------------") if let body = self.body { print("BODY: \(String(data: body, encoding: .utf8)!)\n-----------------") } print("HEADERS: \(self.request.allHTTPHeaderFields!)") print("=================\nRESPONSE\n=================") } switch responseStatusCode { case 200, 201: if T.self == Data.self { DispatchQueue.main.async { callback(.success(data as? T)) } } else { self.decode(data: data, callback: callback) } default: print("RESPONSE STATUS CODE: \(responseStatusCode)") print("STRING FROM SERVER:\(String(data: data, encoding: .utf8) ?? "Binary data")\n-----------------") DispatchQueue.main.async { let error = NSError(domain: "com.moin.error", code: responseStatusCode, userInfo: ["description": "Response error", "data": data]) callback(.failure(error)) } } } MGRouter.task?.taskDescription = NSStringFromClass(type(of: input)) MGRouter.task?.resume() } /// decode data to required output /// - Parameters: /// - data: response data /// - callback: callback block after data conversion internal func decode<T: Decodable>(data: Data, callback: @escaping (Result<T?, Error>) -> Void) { let decoder = JSONDecoder() decoder.keyDecodingStrategy = MGRouter.decodingStratagy do { let responseData = try decoder.decode(T.self, from: data) if MGRouter.debug { print("\(responseData)\n=================") } DispatchQueue.main.async { callback(.success(responseData)) } } catch { if MGRouter.debug { print("\(error)\n=================") } DispatchQueue.main.async { callback(.failure(error)) } } } } <file_sep>// // MGImageView.swift // last_fm_search // // Created by <NAME> on 23/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit extension UIImage { static func getImage(url: String, onLoad: @escaping (UIImage?) -> ()) { if let img = ImageCacheManager.shared.getImage(for: url) { return onLoad(img) } else { DispatchQueue.global(qos: .background).async { do { guard let imageUrl = URL(string: url) else { DispatchQueue.main.async { onLoad(nil) } return } let data = try Data(contentsOf: imageUrl) ImageCacheManager.shared.cacheImage(imageData: data, key: url) let img = ImageCacheManager.shared.getImage(for:url) DispatchQueue.main.async { onLoad(img) } } catch { print(error) DispatchQueue.main.async { onLoad(nil) } } } } } } class MGImageView: UIImageView { private let loader: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView(style: .large) indicator.translatesAutoresizingMaskIntoConstraints = false indicator.startAnimating() indicator.hidesWhenStopped = true indicator.color = .lightGray return indicator }() required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { self.addSubview(loader) self.layer.borderWidth = 2 self.layer.borderColor = #colorLiteral(red: 0.8, green: 0.8, blue: 0.8, alpha: 1) self.layer.masksToBounds = true loader.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true loader.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0).isActive = true } func setImage(url: String) { loader.startAnimating() UIImage.getImage(url: url) { [weak self] (image) in self?.image = image self?.loader.stopAnimating() } } } class ImageCacheManager: NSObject { static let shared: ImageCacheManager = { return ImageCacheManager() }() private override init() { super.init() } private let cache = NSCache<AnyObject, AnyObject>() func cacheImage(imageData: Data, key: String) { cache.setObject(imageData as AnyObject, forKey: key as AnyObject) } func getImage(for key: String) -> UIImage? { if let imgData = cache.object(forKey: key as AnyObject) as? Data { return UIImage(data: imgData) } else { return nil } } } <file_sep>// // AlbumInfoViewController.swift // last_fm_search // // Created by <NAME> on 23/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class AlbumInfoViewController: BaseViewController { @IBOutlet weak var imgAlbum: MGImageView! @IBOutlet weak var lblName: UILabel! @IBOutlet weak var lblArtistName: UILabel! @IBOutlet weak var lblSortDesc: UILabel! @IBOutlet weak var tblTracks: UITableView! var mbid: String? var album: Album? { didSet { if isViewLoaded && (self.storyboard != nil){ setData() } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) getAlbum(mbid: mbid!) } /// get albun information /// - Parameter mbid: album mbid string func getAlbum(mbid: String) { showLoader() MGRouter.task?.cancel() let input = MGRouterGetAlbumInput(urlParams: ["mbid": mbid]) MGRouter(input: input).apiCall { [weak self] (result: Result<AlbumResponse?, Error>) in guard let `self` = self else {return} switch result { case let .success(response): self.album = response!.album case let .failure(error): self.showAlert(message: error.localizedDescription) } self.hideLoader() } } /// set album data func setData() { lblArtistName.text = album?.artist lblName.text = album?.name lblSortDesc.text = album?.wiki?.summary imgAlbum.setImage(url: album!.lagreImage) tblTracks.reloadData() } } extension AlbumInfoViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return album?.tracks?.track.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TrackTableViewCell") as! TrackTableViewCell cell.loadData(track: album!.tracks!.track[indexPath.row]) return cell } } <file_sep>// // BaseViewController.swift // last_fm_search // // Created by <NAME> on 23/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class BaseViewController: UIViewController { var loader: UIActivityIndicatorView = { let loader = UIActivityIndicatorView(style: .large) loader.color = .black loader.startAnimating() loader.hidesWhenStopped = true return loader }() let loaderView: UIView = { let view = UIView(frame: UIScreen.main.bounds) view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) return view }() override func viewDidLoad() { super.viewDidLoad() loader.center = view.center loaderView.addSubview(loader) // Do any additional setup after loading the view. } func showLoader() { self.view.addSubview(loaderView) } func hideLoader() { loaderView.removeFromSuperview() } /// show alert message /// - Parameter message: message string. func showAlert(message: String) { let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } <file_sep>// // MGSessionProtocol.swift // last_fm_search // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation public protocol MGSessionProtocol: class { static var shared: MGSessionProtocol { get } static var sharedSession: URLSession? { get } var session: URLSession? {get set} var bundle: Bundle {get set} } <file_sep>// // last_fm_searchTests.swift // last_fm_searchTests // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import XCTest @testable import last_fm_search class last_fm_searchTests: XCTestCase { override func setUpWithError() throws { MGMockSession.shared.bundle = Bundle(for: last_fm_searchTests.self) MGRouter.session = MGMockSession.shared // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testModels() { convertFileToModel(fileName: "albums") { (result: AlbumsResponse?) in validateAlbumsResponse(model: result!) } convertFileToModel(fileName: "album") { (result: AlbumResponse?) in validateAlbumResponse(model: result!) } } func testAlbumsApi() { let albumsVC = AlbumsViewController() albumsVC.getAlbums(query: "Aa") let expectAlbums = expectation(description: "getAlbums") DispatchQueue.main.asyncAfter(deadline: .now() + 1) { expectAlbums.fulfill() } wait(for: [expectAlbums], timeout: 2) XCTAssert(!albumsVC.arrAlbums.isEmpty) } func testAlbumApi() { let albumVC = AlbumInfoViewController() albumVC.getAlbum(mbid: "9f80e404-9436-307a-a369-e93a2fdd6751") let expectAlbum = expectation(description: "getAlbum") DispatchQueue.main.asyncAfter(deadline: .now() + 1) { expectAlbum.fulfill() } wait(for: [expectAlbum], timeout: 2) XCTAssertNotNil(albumVC.album) validateAlbum(album:albumVC.album!) } func testTrackDurationLogic() { var track = Track(name: "123", duration: "49", artist: Artist(name: "artist", mbid: "1234")) XCTAssertEqual(track.formatedDuration, "00:49") track.duration = "109" XCTAssertEqual(track.formatedDuration, "01:49") track.duration = "3709" XCTAssertEqual(track.formatedDuration, "01:01:49") } func convertFileToJson(fileName: String, withBody: Bool = true) -> Any? { let bundle = Bundle(for: last_fm_searchTests.self) if let path = bundle.path(forResource: fileName, ofType: "json") { let fileUrl = URL(fileURLWithPath: path) do { let data = try Data(contentsOf: fileUrl) let json = try JSONSerialization.jsonObject(with: data, options: .init(rawValue: 0)) return json } catch { return nil } } return nil } func convertFileToModel<T: Codable>(fileName: String, onComplete:(T?) -> Void) { let bundle = Bundle(for: last_fm_searchTests.self) if let path = bundle.path(forResource: fileName, ofType: "json") { let fileUrl = URL(fileURLWithPath: path) do { let data = try Data(contentsOf: fileUrl) let decoder = JSONDecoder() let obj = try decoder.decode(T.self, from: data) onComplete(obj) } catch { print(error) onComplete(nil) } } } func validateAlbumsResponse(model: AlbumsResponse) { let album = model.results.albummatches.album.first XCTAssertNotNil(album, "no album found") XCTAssertEqual(album?.artist, "Phoenix") XCTAssertEqual(album?.name, "<NAME>") XCTAssertEqual(album?.mbid, "9f80e404-9436-307a-a369-e93a2fdd6751") XCTAssertEqual(album?.image.count, 4) XCTAssertEqual(model.results.albummatches.album.count, 50) } func validateAlbumResponse(model: AlbumResponse) { let album = model.album validateAlbum(album: album) } func validateAlbum(album: Album) { XCTAssertNotNil(album, "no album found") XCTAssertEqual(album.artist, "Phoenix") XCTAssertEqual(album.name, "<NAME>") XCTAssertEqual(album.mbid, "9f80e404-9436-307a-a369-e93a2fdd6751") XCTAssertEqual(album.image.count, 6) XCTAssertEqual(album.tracks?.track.count, 10) let track = album.tracks?.track.first XCTAssertNotNil(track) XCTAssertEqual(track?.artist.name, "Phoenix") XCTAssertEqual(track?.name, "Lisztomania") } } <file_sep>// // AlbumsViewController.swift // last_fm_search // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class AlbumsViewController: BaseViewController { @IBOutlet weak var tblAlbum: UITableView! @IBOutlet weak var searchBar: UISearchBar! var arrAlbums = [Album]() { didSet { if isViewLoaded && (self.storyboard != nil) { tblAlbum.reloadData() tblAlbum.isHidden = false } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } extension AlbumsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrAlbums.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AlbumTableViewCell") as! AlbumTableViewCell cell.loadData(data: arrAlbums[indexPath.row]) return cell } } extension AlbumsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let mbid = arrAlbums[indexPath.row].mbid if mbid.isEmpty { showAlert(message: "mbid does not availabe for \(arrAlbums[indexPath.row].name.uppercased()) album.") } else { let albumInfoVC = self.storyboard?.instantiateViewController(identifier: "AlbumInfoViewController") as! AlbumInfoViewController albumInfoVC.mbid = mbid self.navigationController?.pushViewController(albumInfoVC, animated: true) } } } extension AlbumsViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { tblAlbum.isHidden = true } else { getAlbums(query: searchText) } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } /// get ablum based on query /// - Parameter query: search query string func getAlbums(query: String) { MGRouter.task?.cancel() let input = MGRouterSearchAlbumsInput(urlParams: ["album": query]) MGRouter(input: input).apiCall { (result: Result<AlbumsResponse?, Error>) in switch result { case let .success(response): self.arrAlbums = response!.results.albummatches.album case let .failure(error): print(error) } } } } <file_sep>// // Constants.swift // last_fm_search // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct Constants { static var APIKey: String { return "207d9906a556e2e31ce96c7f609ee112" } static var host: String { return "http://ws.audioscrobbler.com/2.0/" } static var methodSearchAlbum: String { return "album.search" } static var methodGetAlbum: String { return "album.getInfo" } static var responseForamte: String { return "json" } } <file_sep>// // AlbumTableViewCell.swift // last_fm_search // // Created by <NAME> on 23/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class AlbumTableViewCell: UITableViewCell { @IBOutlet weak var imgAlbum: MGImageView! @IBOutlet weak var lblAlbumName: UILabel! @IBOutlet weak var lblAlbumDesc: UILabel! var album: Album! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } /// loead album data to cell /// - Parameter data: album object func loadData(data: Album) { self.album = data imgAlbum.setImage(url: album.mediumImage) lblAlbumName.text = album.name lblAlbumDesc.text = album.artist } override func prepareForReuse() { imgAlbum.image = nil } } <file_sep>// // MGSession.swift // last_fm_search // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation /// Session class. main purpose to create class is to make singalton object of URLSession. shaed object of URLSesion does not allow to cusomize configuration so neds to create custom URLSession oject and set configuration. public class MGSession: NSObject, URLSessionDataDelegate, MGSessionProtocol { public var bundle: Bundle = Bundle.main private static let serialQueue = DispatchQueue(label: "com.moin.girach.serial") public static let shared: MGSessionProtocol = { return serialQueue.sync { return MGSession() } }() public static var sharedSession: URLSession? { return shared.session } public var session: URLSession? private override init() { super.init() /// Custom cach implmented for all request so urlCache does not required and disabling all urlCache let config = URLSessionConfiguration.default /// ignores all local and remote chache data config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData /// set urlCache nil, custom urlCache implemented so default url cache does not required. config.urlCache = nil session = URLSession(configuration: config) } } <file_sep>// // MGMockSession.swift // last_fm_searchUITests // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation @testable import last_fm_search public class MGMockSession: NSObject, URLSessionDataDelegate, MGSessionProtocol { public var bundle: Bundle = Bundle(for: MGMockSession.self) public static var sharedSession: URLSession? { return shared.session } public var session: URLSession? private static let serialQueue = DispatchQueue(label: "com.Demo.MGMockSession.serial") public static let shared: MGSessionProtocol = { return serialQueue.sync { return MGMockSession() } }() private override init() { super.init() /// Custom cach implmented for all request so urlCache does not required and disabling all urlCache let config = URLSessionConfiguration.default /// ignores all local and remote chache data config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData /// set urlCache nil, custom urlCache implemented so default url cache does not required. config.urlCache = nil session = MGMockUrlSession() } } class MGMockUrlSession: URLSession { override var configuration: URLSessionConfiguration { return URLSessionConfiguration.ephemeral } override func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { let response = HTTPURLResponse(url: URL(string: "http://localhost/")!, statusCode: 200, httpVersion: nil, headerFields: nil) return MGMockTask(request: request, response: response, completionHandler: completionHandler) } } class MGMockTask: URLSessionDataTask { var desc: String? override var taskDescription: String? { set { desc = newValue } get { return desc } } let request: URLRequest? override var currentRequest: URLRequest? { return request } override var originalRequest: URLRequest? { return request } typealias Response = (data: Data?, urlResponse: URLResponse?, error: Error?) let completionHandler: ((Response) -> Void)? var mockResponse: HTTPURLResponse? init(request: URLRequest?, response: URLResponse?, completionHandler:((Response) -> Void)?) { self.completionHandler = completionHandler self.request = request self.mockResponse = response as? HTTPURLResponse } override func resume() { let response = HTTPURLResponse(url: URL(string: "http://localhost/")!, statusCode: 200, httpVersion: nil, headerFields: getHeaderFromUrl()) let data = getDataFromUrl() completionHandler?((data.0, response, data.1)) } func getMockfileUrl() -> URL { var file: String = "" let bundle = MGMockSession.shared.bundle file = MockConfiguration.getFilePath(forKey: self.taskDescription!) if file.isEmpty { return URL(fileURLWithPath: file) } else { if let path = bundle.path(forResource: file, ofType: "json") { return URL(fileURLWithPath: path) } else { return URL(fileURLWithPath: file) } } } func getDataFromUrl() -> (Data?, Error?) { let url = getMockfileUrl() do { return (try Data(contentsOf: url), nil) } catch { return (nil, error) } } func getHeaderFromUrl() -> [String: String]? { let url = getMockfileUrl() let lastPath = url.deletingPathExtension().lastPathComponent let lastPathExtension = url.pathExtension let headerUrl = url.deletingLastPathComponent().appendingPathComponent("\(lastPath)_header.\(lastPathExtension)") do { let data = try Data(contentsOf: headerUrl) let jsonData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: String] return jsonData } catch { return nil } } } <file_sep>// // Album.swift // last_fm_search // // Created by <NAME> on 23/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct AlbumsResponse: Codable { var results: AlbumResults } struct AlbumResponse: Codable { var album: Album } struct AlbumResults: Codable { var albummatches: AlbumMatches } struct AlbumMatches: Codable { var album: [Album] } struct Album: Codable { var name: String var artist: String var image: [Image] var mbid: String var tracks: Tracks? var wiki: Wiki? var mediumImage: String { return image.filter {$0.size == "medium"}.first!.text } var lagreImage: String { return image.filter {$0.size == "large"}.first!.text } } struct Image: Codable { var text: String var size: String enum CodingKeys: String, CodingKey { case text = "#text" case size } } struct Tracks: Codable { var track: [Track] } struct Track: Codable { var name: String var duration: String var artist: Artist var formatedDuration: String { let intDuration = Int(duration) ?? 0 var hour = 0 var min = 0 var sec = 0 if intDuration < 60 { sec = intDuration return String(format: "%02d:%02d", min, sec) } else if intDuration < 3600 { sec = intDuration % 60 min = (intDuration - sec) / 60 return String(format: "%02d:%02d", min, sec) } else { sec = intDuration % 60 min = ((intDuration - sec) / 60) % 60 hour = (((intDuration - sec) / 60) - min) / 60 return String(format: "%02d:%02d:%02d", hour, min, sec) } } } struct Artist: Codable { var name: String var mbid: String } struct Wiki: Codable { var published: String var summary: String } <file_sep>// // last_fm_searchUITests.swift // last_fm_searchUITests // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import XCTest class last_fm_searchUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() app.searchFields.firstMatch.tap() app.keyboards.buttons["Search"].tap() app.searchFields.firstMatch.tap() app.keyboards.keys["A"].tap() app.keyboards.keys["a"].tap() let table = app.tables.firstMatch wait(element: table, type: "exist", duration: 5) let albumNameExists = app.tables.cells.firstMatch.staticTexts["Wolfgang Amadeus Phoenix"].exists XCTAssert(albumNameExists, "Albun does not exist") let artistNameExist = app.tables.cells.firstMatch.staticTexts["Phoenix"].exists XCTAssert(artistNameExist, "Artist does not exist") table.cells.firstMatch.tap() XCTAssert(albumNameExists, "Albun does not exist") XCTAssert(artistNameExist, "Artist does not exist") // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } @discardableResult func wait(element:XCUIElement, type: String, duration: Int) -> Bool { let predicate = NSPredicate(format: "\(type) == true") let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element) let result = XCTWaiter().wait(for: [expectation], timeout: TimeInterval(duration)) switch result { case .completed: return true default: return false } } } <file_sep>// // MGRouterInput.swift // last_fm_search // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation public enum RouterMethod: String { case get = "GET" case post = "POST" } public protocol MGRouterInputProtocol: class { var host: String {get set} var endpoint: String {get set} var body: Data? {get set} var headers: [String: String] {get set} var timeout: Int {get set} var method: RouterMethod {get set} var cacheResponse: Bool {get set} var mockFile:String? {get set} } public protocol DataConvertable { var data:Data? {get} } public class MGRouterInput: MGRouterInputProtocol { public var host: String = Constants.host /// api endpoint public var endpoint: String /// request body public var body: Data? /// request headers public var headers: [String : String] = [:] /// timeout interval public var timeout: Int /// HttpMethod public var method: RouterMethod /// true if responce needs to be cached public var cacheResponse: Bool = false public var mockFile: String? /// initialize router input /// - Parameters: /// - endpoint: enpoint string /// - urlParams: url query params /// - body: request body data in case of post or put methods /// - method: Http request method /// - timeout: response time out /// - arguments: url parameters init(endpoint: String, urlParams: [String: Any] = [:], body: DataConvertable? = nil, method: RouterMethod = .get, timeout: Int = 30 , arguments: [CVarArg] = []) { self.body = body?.data self.timeout = timeout self.method = method var endpointWitArgs = endpoint if !arguments.isEmpty { endpointWitArgs = String(format: endpoint, arguments: arguments) } if urlParams.isEmpty { self.endpoint = endpointWitArgs } else { var urlc = URLComponents() urlc.queryItems = [URLQueryItem]() for (key, value) in urlParams { let queryItem = URLQueryItem(name: key, value: "\(value)") urlc.queryItems!.append(queryItem) } self.endpoint = "\(endpointWitArgs)?\(urlc.percentEncodedQuery ?? "")" } } } class MGRouterSearchAlbumsInput: MGRouterInput { init(urlParams: [String: Any]) { var params = urlParams params["method"] = Constants.methodSearchAlbum params["format"] = Constants.responseForamte params["api_key"] = Constants.APIKey super.init( endpoint: "", urlParams: params) } } class MGRouterGetAlbumInput: MGRouterInput { init(urlParams: [String: Any]) { var params = urlParams params["method"] = Constants.methodGetAlbum params["format"] = Constants.responseForamte params["api_key"] = Constants.APIKey super.init( endpoint: "", urlParams: params) } } <file_sep>// // MockConfiguration.swift // last_fm_searchUITests // // Created by <NAME> on 17/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation class MockConfiguration { enum ResponseType: String { case success case failure } static func setMockFile(for type: ResponseType, fileKey: String, forKey: String) { if let fileUrl = Bundle(for: MockConfiguration.self).url(forResource: "mock_file_path", withExtension: "plist") { do { let data = try Data(contentsOf: fileUrl) if var result = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: [String: Any]] { result[forKey]!["pick"] = type.rawValue + "_" + fileKey let plistData = try PropertyListSerialization.data(fromPropertyList: result, format: .xml, options: 0) try plistData.write(to: fileUrl) } } catch { print(error) } } } static func setMockFileForSuccess(fileKey: String, forKey: String) { setMockFile(for: .success, fileKey: fileKey, forKey: forKey) } static func setMockFileForFailure(fileKey: String, forKey: String) { setMockFile(for: .failure, fileKey: fileKey, forKey: forKey) } static func getFilePath(forKey: String) -> String { if let fileUrl = Bundle(for: MockConfiguration.self).url(forResource: "mock_file_path", withExtension: "plist") { do { let data = try Data(contentsOf: fileUrl) if let result = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: [String: Any]] { if let dicFile = result[forKey], let seletionName = dicFile["pick"] as? String { let comps = seletionName.components(separatedBy: "_") return (dicFile[comps[0]] as! [String: String])[comps[1]] as! String } } } catch { print(error) return "" } } return "" } } <file_sep>// // TrackTableViewCell.swift // last_fm_search // // Created by <NAME> on 23/06/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class TrackTableViewCell: UITableViewCell { var track: Track? @IBOutlet weak var lblTrackName: UILabel! @IBOutlet weak var lblArtistName: UILabel! @IBOutlet weak var lblDuration: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } /// load track data to cell /// - Parameter track: track object func loadData(track: Track) { self.track = track lblTrackName.text = track.name lblArtistName.text = track.artist.name lblDuration.text = track.formatedDuration } }
0dd943429df11e625a06ef62e9457f251b02f4a7
[ "Swift" ]
16
Swift
magirach/last_fm_search
079f337f3829cd19484b5f533103098ec2ed4e74
96dbe8c66f7ef729619ed74c35791d1c31fb8f6b
refs/heads/master
<repo_name>wuxinxi/GreenDaoDemo<file_sep>/app/src/main/java/com/wxx/greendao/utils/Test2.java package com.wxx.greendao.utils; /** * 作者:Tangren_ on 2017/3/27 0027. * 邮箱:<EMAIL> * TODO:用一句话概括 */ public class Test2 { } <file_sep>/app/src/main/java/com/wxx/greendao/MainActivity.java package com.wxx.greendao; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import com.wxx.greendao.bean.Info; import com.wxx.greendao.utils.DBManager; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity { @BindView(R.id.name) EditText name; @BindView(R.id.age) EditText age; @BindView(R.id.address) EditText address; @BindView(R.id.insert) Button insert; @BindView(R.id.delete) Button delete; @BindView(R.id.query) Button query; @BindView(R.id.query_name) Button queryName; private static final String TAG = "MainActivity"; @BindView(R.id.test) EditText test; @BindView(R.id.activity_main) LinearLayout activityMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @OnClick({R.id.insert, R.id.delete, R.id.query, R.id.query_name}) public void onClick(View view) { String n = name.getText().toString(); int a = Integer.valueOf(age.getText().toString()); String add = address.getText().toString(); String t = test.getText().toString(); switch (view.getId()) { case R.id.insert: Info info = new Info(null, n, a, add, t); DBManager.insert(info); break; case R.id.delete: // Info info2 = new Info(null, n, a, add,t); // DBManager.delet(info2); break; case R.id.query: List<Info> list = DBManager.query(); for (int i = 0; i < list.size(); i++) { Log.d(TAG, "--------------------------------------------------------"); Log.d(TAG, list.get(i).getAddRess()); Log.d(TAG, list.get(i).getName()); Log.d(TAG, "Age=" + list.get(i).getAge()); Log.d(TAG, "自增id=" + list.get(i).getId()); Log.d(TAG, "test=" + list.get(i).getTest()); Log.d(TAG, "--------------------------------------------------------"); } break; case R.id.query_name: List<Info> list2 = DBManager.query(n); for (int i = 0; i < list2.size(); i++) { Log.d(TAG, list2.get(i).getAddRess()); Log.d(TAG, list2.get(i).getName()); Log.d(TAG, "Age=" + list2.get(i).getAge()); Log.d(TAG, "自增id=" + list2.get(i).getId()); Log.d(TAG, "自增id=" + list2.get(i).getId()); Log.d(TAG, "自增id=" + list2.get(i).getId()); } break; } } } <file_sep>/app/src/main/java/com/wxx/greendao/utils/DBHelper.java package com.wxx.greendao.utils; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.github.yuweiguocn.library.greendao.MigrationHelper; import com.wxx.greendao.db.DaoMaster; import com.wxx.greendao.db.InfoDao; /** * 作者:Tangren_ on 2017/3/23 0023. * 邮箱:<EMAIL> * TODO: */ public class DBHelper extends DaoMaster.OpenHelper { public DBHelper(Context context, String name) { super(context, name); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { super.onUpgrade(db, oldVersion, newVersion); MigrationHelper.migrate(db, InfoDao.class); } } <file_sep>/app/src/main/java/com/wxx/greendao/utils/DBManager.java package com.wxx.greendao.utils; import com.wxx.greendao.MyApplication; import com.wxx.greendao.bean.Info; import com.wxx.greendao.db.InfoDao; import java.util.List; /** * 作者:Tangren_ on 2017/3/23 0023. * 邮箱:<EMAIL> * TODO:DBManger */ public class DBManager { //增 public static void insert(Info info) { MyApplication.getDaoInstance().getInfoDao().insert(info); } //根据id删除 public static void delete(long id) { MyApplication.getDaoInstance().getInfoDao().deleteByKey(id); } //删除 public static void delet(Info info) { MyApplication.getDaoInstance().getInfoDao().delete(info); } //更改 public static void update(Info info) { MyApplication.getDaoInstance().getInfoDao().update(info); } //查询所有 public static List<Info> query() { return MyApplication.getDaoInstance().getInfoDao().queryBuilder().list(); } //根据名字查询 public static List<Info> query(String name) { return MyApplication.getDaoInstance().getInfoDao().queryBuilder().where(InfoDao.Properties.Name.eq(name)).list(); } }
4f3812e3e219ef4ea2d39c37ff0f56e5a3c11a25
[ "Java" ]
4
Java
wuxinxi/GreenDaoDemo
1bd2dce689f9be8566c6e6edb6ddf8f89243a74b
d6ab59e1a9deb83f538e4b87adfaf47fdfa7492d
refs/heads/master
<repo_name>Jhht/readableapp<file_sep>/src/components/Post/Comments/comment.js import React, { Component } from 'react' import { connect } from 'react-redux' import { voteForComment, deleteComment} from '../../../actions/comment' import { Button } from 'react-bootstrap' import CreateComment from './CreateComment' class Comment extends Component { state = { edit : false } toggleEdit = () => { this.setState(prevState => ({edit: !prevState.edit})) } render(){ const { edit } = this.state const {comment , voteForComment, deleteComment} = this.props; if (edit) { return ( <CreateComment toggleEdit={ this.toggleEdit} commentId={comment.id} defaults={{id : comment.id, body: comment.body, author: comment.author}} /> ) } return ( <div key={comment.id}> <p>Author: {comment.author}</p> <p>Body: {comment.body}</p> <p>Votes: {comment.voteScore}</p> <Button onClick={() => this.toggleEdit()} > Edit </Button> <Button onClick={() => voteForComment(comment, 'upVote')} > + </Button> <Button onClick={() => voteForComment(comment, 'downVote')} > - </Button> <Button onClick={() => deleteComment(comment.id)} > Del </Button> </div>); } } const mapStateToProps = ({ post, comments}) => ({ post, comments}) export default connect(mapStateToProps, {voteForComment, deleteComment} )(Comment)<file_sep>/src/reducers/post.js import { GET_POST_BY_ID, } from '../actions/post' function post (state = {}, action){ switch(action.type){ case GET_POST_BY_ID: return{ ...action.post } default: return state } } export default post <file_sep>/src/actions/post.js import { fetchAllPosts , fetchPostsByCategory , createPostAPI , fetchPostById, editPostAPI, votePostAPI, deletePostAPI } from '../utils/api' export const GET_POSTS = 'GET_POSTS' export const GET_POSTS_BY_CAT = 'GET_POSTS_BY_CAT' export const GET_POST_BY_ID = 'GET_POST_BY_ID' export const CREATE_POST = 'CREATE_POST' export const EDIT_POST = 'EDIT_POST' export const VOTE_POST = 'VOTE_POST' export const POST_SORT_ORDER = 'POST_SORT_ORDER' export const DELETE_POST = 'DELETE_POST' export const getPosts = () => dispatch => ( fetchAllPosts() .then( posts => { dispatch({ type: GET_POSTS, posts }) }) ) export const getPostsByCategory = ( category ) => dispatch => ( fetchPostsByCategory( category ) .then( posts => { dispatch({ type: GET_POSTS_BY_CAT, posts }) }) ) export const getPostById= ( id ) => dispatch => ( fetchPostById( id ) .then( post => { dispatch({ type: GET_POST_BY_ID, post }) }) ) export const createPost = ( post ) => dispatch => ( createPostAPI( post ) .then( data => { dispatch({ type: CREATE_POST, data }) }) ) export const editPost = ( post ) => dispatch => ( editPostAPI( post ) .then( data => { dispatch({ type: EDIT_POST, data }) }) ) export const deletePost = ( id ) => dispatch => ( deletePostAPI( id ) .then( data => { dispatch({ type: DELETE_POST, data }) }) ) export const voteForPost = (post, vote) => dispatch => ( votePostAPI( post, vote ) .then( data => { dispatch({ type: VOTE_POST, data }) }) ) export function postSortOrder(sortType) { return { type: POST_SORT_ORDER, sortType } } <file_sep>/src/components/Post/Comments/CreateComment/index.js import React, {Component} from 'react'; import {connect } from 'react-redux'; import{createComment , editComment} from '../../../../actions/comment'; import {FormGroup, FormControl, ControlLabel, Button} from 'react-bootstrap'; class CreateComment extends Component { initialState = { id : '', author: '', body: '', }; // initialState, handlers constructor(props){ super(props) this.state = this.initialState; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleCancel = this.handleCancel.bind(this); const { defaults } = this.props; if(defaults){ var newState = {id : defaults.id, author: defaults.author, body: defaults.body}; this.state = (newState); } } // update state whenever input text is changed handleChange(event) { const {name, value} = event.target; this.setState({ [name]: value }); } // handle form submission handleSubmit(event) { event.preventDefault(); this.createComment(); } // handle cancellation handleCancel() { this.props.toggleEdit() } // create a new post createComment() { const {author, body, id} = this.state; const { post, toggleEdit } = this.props; if(toggleEdit){ const commentUpdate = {//testing id : id, author : author, body : body, timestamp : Date.now(), parentId : post.id, } this.props.editComment( commentUpdate ) toggleEdit(); }else{ const commentCreate = {//testing id : guid(), author : author, body : body, timestamp : Date.now(), parentId : post.id, } this.props.createComment( commentCreate ) } } render() { const {author, body} = this.state const {toggleEdit} = this.props; const button = toggleEdit ? ( <div> <Button bsStyle="primary" type="submit" >Save</Button> <Button bsStyle="primary" type="button" onClick={this.handleCancel}>Cancel</Button> </div> ) : ( <Button bsStyle="primary" type="submit" >Save</Button> ) return ( <form onSubmit={this.handleSubmit}> <h4> Create a new comment! </h4> <FormGroup controlId="postAuthor"> <ControlLabel>Author</ControlLabel> <FormControl type="text" name="author" placeholder="<NAME>" value={author} onChange={this.handleChange}/> </FormGroup> <FormGroup controlId="postBody"> <ControlLabel>Body</ControlLabel> <FormControl componentClass="textarea" name="body" placeholder="Body" value={body} onChange={this.handleChange}/> </FormGroup> {button} </form> ) } } export function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + s4() + s4() + s4(); } const mapStateToProps = ({post, comment}) => ({ post, comment}) export default connect(mapStateToProps, {createComment, editComment})(CreateComment)<file_sep>/src/components/ReadableIndex.js import React, {Component} from 'react' import Posts from './Posts' import Categories from './Categories' import {withRouter} from 'react-router-dom' class ReadableIndex extends Component { render(){ console.log('index ' + JSON.stringify(this.props)) return( <div> <h1> Readable Index </h1> <Categories /> <Posts category={this.props.match.params.category}/> </div> ) } } export default withRouter(ReadableIndex) <file_sep>/src/components/EditPost/index.js import React, {Component} from 'react'; import {connect} from 'react-redux'; import{editPost, getPostById} from '../../actions/post'; import {FormGroup, FormControl, ControlLabel, Button} from 'react-bootstrap'; import {withRouter} from 'react-router-dom' import {compose} from 'recompose' import {arrayFromObject} from '../../utils/helpers' import { Link } from 'react-router-dom' class EditPost extends Component { state = { id: '', title: '', body: '', category : '' }; constructor(props){ super(props) const postsArray = arrayFromObject(this.props.posts) let {post} = this.props let postFilteredArray; if(postsArray.length > 0){ postFilteredArray = postsArray.filter(post => this.props.match.params.postId === post.id ); post = postFilteredArray[0] } console.log('post vale ' + JSON.stringify(post)) var newState = {id: post.id, title: post.title, body: post.body, category : post.category}; this.state = (newState); this.handleSubmit = this.handleSubmit.bind(this); this.handleChange = this.handleChange.bind(this); this.handleCancel = this.handleCancel.bind(this); } // update state whenever input text is changed handleChange(event) { const {name, value} = event.target; this.setState({ [name]: value }); } handleSubmit(event){ this.editPost(); } // handle cancellation handleCancel() { // call onCancel function (if available) const {history} = this.props; history.push('/'); } editPost(){ const {history} = this.props; const postUpdate = {//testing id : this.state.id, title : this.state.title, body : this.state.body, category : this.state.category } this.props.editPost(postUpdate).then( history.push("/") ) } render() { const {category } = this.state const { categories } = this.props return ( <form onSubmit={this.handleSubmit}> <FormGroup controlId="postTitle"> <ControlLabel>Title: </ControlLabel> <FormControl type="text" name="title" placeholder="Title" value={this.state.title} onChange={this.handleChange}/> </FormGroup> <FormGroup> <ControlLabel>Category: </ControlLabel> <select name='category' value={category} placeholder='Category' onChange={this.handleChange} className='ui selection dropdown'> { categories.map( category => { return( <option key={category.path} value={category.name}>{category.name}</option> ) }) } </select> </FormGroup> <FormGroup controlId="postBody"> <ControlLabel>Text: </ControlLabel> <FormControl componentClass="textarea" name="body" placeholder="Body" value={this.state.body} onChange={this.handleChange}/> </FormGroup> <Button bsStyle="primary" type="submit" >Create Post</Button> <Button bsStyle="primary" type="button" onClick={this.handleCancel}>Cancel</Button> <Link to={'/'}>Back to all post </Link> </form> ) } } const mapStateToProps = ({categories, post, posts}) => ({ categories, post, posts}) const enhance = compose( connect(mapStateToProps, { editPost, getPostById }), withRouter ) export default enhance(EditPost)<file_sep>/src/utils/helpers.js /** * Create an object from given array */ export function objectFromArray(arr, key = 'id') { if (arr && arr.length) { return arr.reduce((v, i) => { v[i[key]] = i; return v; }, {}); } else { return {}; } } /** * Create an array from given object */ export function arrayFromObject(obj, key = 'id') { return Object.keys(obj).map(key => (obj[key])); } /** * Format date */ export function formatDate(timestamp) { const date = new Date( timestamp*1000); const hours = date.getHours(); const minutes = "0" + date.getMinutes(); const seconds = "0" + date.getSeconds(); return hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2); }<file_sep>/src/components/Error.js import React from 'react'; import { Link } from 'react-router-dom' const Error = ({name}) => ( <div><p>Error 404 :( </p> <Link to={`/`}> Back home</Link></div> ); export default Error;<file_sep>/src/actions/comment.js import { editCommentAPI, fetchPostComments, createCommentAPI, voteCommentAPI, deleteCommentAPI} from '../utils/api' export const GET_POST_COMMENTS = 'GET_POST_COMMENTS' export const CREATE_COMMENT = 'CREATE_COMMENT' export const EDIT_COMMENT = 'EDIT_COMMENT' export const DELETE_COMMENT = 'DELETE_COMMENT' export const VOTE_COMMENT = 'VOTE_COMMENT' export const getPostComments = (postId) => dispatch => ( fetchPostComments( postId) .then( data => { dispatch({ type: GET_POST_COMMENTS, data }) }) ) export const createComment = ( comment ) => dispatch => ( createCommentAPI( comment ) .then( data => { dispatch({ type: CREATE_COMMENT, data }) }) ) export const editComment = ( comment ) => dispatch => ( editCommentAPI( comment ) .then( data => { dispatch({ type: EDIT_COMMENT, data }) }) ) export const deleteComment = ( id ) => dispatch => ( deleteCommentAPI( id ) .then( data => { dispatch({ type: DELETE_COMMENT, data }) }) ) export const voteForComment = (comment, vote) => dispatch => ( voteCommentAPI( comment, vote ) .then( data => { dispatch({ type: VOTE_COMMENT, data }) }) ) <file_sep>/src/components/Post/Comments/index.js import React, { Component } from 'react' import { connect } from 'react-redux' import Comment from './comment' import CreateComment from './CreateComment' import { arrayFromObject} from '../../../utils/helpers.js' class Comments extends Component { render () { const {comments, post} = this.props const commentCount = comments.length const orderComments = arrayFromObject(comments) console.log(' -- render comments ' + JSON.stringify(comments)) return ( <div> <h3> Comments </h3> {commentCount === 0 && ( <div>No comments yet.</div> )} <ol> {orderComments.map((comment) => ( <li key={comment.id}> <Comment key={comment.id} comment={comment} /> </li> ))} < CreateComment post={post} history = {this.props.history}/> </ol> </div> ) } } const mapStateToProps = ({comments, post}) => ({comments, post}) export default connect(mapStateToProps)(Comments)<file_sep>/src/utils/api.js export function fetchCategories( ){ const url = 'http://localhost:3001'; let headers = { headers: { 'Authorization': 'whatever-you-want', 'Content-Type' : 'application/json' }} return fetch(`${url}/categories`, headers) .then((res) => res.json()) .then(data => data.categories) } export function fetchAllPosts( ){ const url = 'http://localhost:3001'; return fetch(`${url}/posts`, { headers: { 'Authorization': 'whatever-you-want', 'Content-Type' : 'application/json' }}) .then((res) => res.json() ) } export function fetchPostById( id ){ const url = 'http://localhost:3001'; return fetch(`${url}/posts/${id}`, { headers: { 'Authorization': 'whatever-you-want', 'Content-Type' : 'application/json' }}) .then((res) => res.json() ) } export function fetchPostsByCategory( category ) { const url = 'http://localhost:3001'; return fetch(`${url}/${category}/posts`, { headers: { 'Authorization': 'whatever-you-want', 'Content-Type' : 'application/json' }}) .then((res) => res.json() ) } export function createPostAPI( post ) { const urlA = 'http://localhost:3001/posts/'; var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'whatever-you-want'); var init = { method: 'POST', headers: headers }; if (post) { init.body = JSON.stringify(post) } return fetch(urlA, init).then((response) => response.json()) } export function editPostAPI( post ) { const urlA = 'http://localhost:3001/posts/' + post.id; var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'whatever-you-want'); var init = { method: 'PUT', headers: headers }; if (post) { init.body = JSON.stringify(post) } return fetch(urlA, init).then((response) => response.json()) } export function deletePostAPI( id ){ const urlA = 'http://localhost:3001/posts/' + id; var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'whatever-you-want'); var init = { method: 'DELETE', headers: headers }; return fetch(urlA, init).then((response) => response.json()) } export function votePostAPI( post, vote ) { const urlA = 'http://localhost:3001/posts/' + post.id; var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'whatever-you-want'); var init = { method: 'POST', headers: headers }; if (post) { init.body = JSON.stringify({option : vote}) } return fetch(urlA, init).then((response) => response.json()) } export function voteCommentAPI( comment, vote ) { const urlA = 'http://localhost:3001/comments/' + comment.id; var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'whatever-you-want'); var init = { method: 'POST', headers: headers }; if (comment) { init.body = JSON.stringify({option : vote}) } return fetch(urlA, init).then((response) => response.json()) } export function fetchPostComments( postId ){ const urlA = 'http://localhost:3001/posts/' + postId +'/comments'; var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'whatever-you-want'); var init = { method: 'GET', headers: headers }; return fetch(urlA, init).then((response) => response.json()) } export function createCommentAPI( comment ) { const urlA = 'http://localhost:3001/comments/'; var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'whatever-you-want'); var init = { method: 'POST', headers: headers }; if (comment) { init.body = JSON.stringify(comment) } return fetch(urlA, init).then((response) => response.json()) } export function editCommentAPI( comment ) { const urlA = 'http://localhost:3001/comments/'+ comment.id; var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'whatever-you-want'); var init = { method: 'PUT', headers: headers }; if(comment){ init.body = JSON.stringify(comment); } return fetch(urlA, init).then((response) => response.json()) } export function deleteCommentAPI( id, body, timestamp ) { const urlA = 'http://localhost:3001/comments/'+ id; var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'whatever-you-want'); var init = { method: 'DELETE', headers: headers }; return fetch(urlA, init).then((response) => response.json()) } <file_sep>/src/reducers/index.js import {combineReducers} from 'redux' import categories from './categories' import posts from './posts' import comments from './comments' import post from './post' import postOrder from './postOrder' export default combineReducers({categories, posts, comments, post, postOrder})
6727853163357d2fba69ea7487555a794ccfdd6e
[ "JavaScript" ]
12
JavaScript
Jhht/readableapp
14e1b7fe4cfc672e69ddfa0478498b9bbd1f3865
3a705c1846c0facadbc94e9f7af637ab2fb3a649
refs/heads/master
<repo_name>dynameek/better-together<file_sep>/README.md # better-together registration site <file_sep>/register_user.php <?php /* * * */ $first_name = htmlspecialchars($_POST['fname']); $last_name = htmlspecialchars($_POST['lname']); $level = htmlspecialchars($_POST['level']); $course = htmlspecialchars($_POST['course']); $phone_number = htmlspecialchars($_POST['phone']); # $file_name = "./students.txt"; /* * open file and write contents to it */ include_once('../credentials.php'); $db_handle = mysqli_connect($db_host, $db_user, $db_pass, $db_name); if(!$db_handle){ $returnValue = '{"isSucceed": false, "message": "Internal Error"}'; }else{ $sql = "INSERT INTO students VALUES('".md5($phone_number)."','".$first_name."', '".$last_name."', ".$level.", '".$course."',".$phone_number.")"; $query = mysqli_query($db_handle, $sql); if(!$query){ $returnValue = '{"isSucceed": false, "message": "User already exists"}'; }else{ $returnValue = '{"isSucceed": true, "message": "Registration Successful"}'; } } #close db mysqli_close($db_handle); echo $returnValue; ?><file_sep>/get_users.php <!DOCTYPE html> <head> <title>Students</title> <meta name="viewport" content="width=device-width,initial-scale=1.0"> </head> <body> <style> tr:first-child{ font-weight: bold; } tr:nth-child(2n){ background: #ADABAB; } </style> <!-- Code to get users --> <?php # include_once('../credentials.php'); # $db_handle = mysqli_connect($db_host, $db_user, $db_pass, $db_name); # if(!$db_handle){ $returnValue = false; }else{ $sql = "SELECT * FROM students"; $query = mysqli_query($db_handle, $sql); if(!$query){ $returnValue = false; }else{ $num_rows = mysqli_num_rows($query); echo "<table><tr><td>Student Name</td><td>Student level</td><td> Student Course</td><td>Student Phone number</td></tr>"; for($i = 0; $i < $num_rows; $i++){ $records[$i] = mysqli_fetch_assoc($query); echo "<tr>"; echo "<td>".$records[$i]['student_firstname']." ".$records[$i]['student_lastname']."</td><td> ".$records[$i]['student_level']." </td><td>".$records[$i]['student_course']."</td><td> ".$records[$i]['student_phone']."</td><br>"; echo "</tr>"; $returnValue = true; } echo "<table"; } } # mysqli_close($db_handle); ?> </body><file_sep>/bootcamp.js /* * */ var formHandler = { /* * Properties */ firstname: null, lastname: null, level: null, course: null, phoneNumber: null, registerUri: "./register_user.php", messageBoardId: "message_board", /* * METHODS */ checkText: function(value){ var valueLength = value.length; var pattern = /[^a-zA-Z]/; var returnValue; if((valueLength < 1)||(pattern.test(value))){ returnValue = false; }else{ returnValue = true; } return returnValue; }, checkNumber: function(value, len){ var valueLength = value.length; var pattern = /[^0-9 ]/; var returnValue; if((valueLength < len) || (pattern.test(value))){ returnValue = false; }else{ returnValue = true; } return returnValue; }, /*SETTERS*/ setFirstname: function(element){ var value = element.value; if(!this.checkText(value)){ //if value is not clean formHandler.firstname = false; element.style.borderColor = "#F99898"; }else{ formHandler.firstname = value; element.style.borderColor = "#8DEFBE"; } }, setLastname: function(element){ var value = element.value; if(!this.checkText(value)){ formHandler.lastname = false; element.style.borderColor = "#F99898"; }else{ formHandler.lastname = value; element.style.borderColor = "#8DEFBE"; } }, setLevel: function(element){ var value = element.value; if(!this.checkNumber(value, 1)){ formHandler.level = false; element.style.borderColor = "#F99898"; }else{ formHandler.level = value; element.style.borderColor = "#8DEFBE"; } }, setCourse: function(element){ var value = element.value; if(!this.checkText(value)){ formHandler.course = false; element.style.borderColor = "#F99898"; }else{ formHandler.course = value; element.style.borderColor = "#8DEFBE"; } }, setPhoneNumber: function(element){ var value = element.value; if(!this.checkNumber(value, 11)){ formHandler.phoneNumber = false; element.style.borderColor = "#F99898"; }else{ formHandler.phoneNumber = value; element.style.borderColor = "#8DEFBE"; } }, /**/ createAjaxObject: function(){ var Ajax; try{ Ajax = new XMLHttpRequest(); }catch(e){ try{ Ajax = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e0){ try{ Ajax = new ActiveXObject("Microsoft.XMLHTTP"); }catch(e1){ Ajax = false; } } } return Ajax; }, displayMessage: function(message, type){ var board = document.getElementById(formHandler.messageBoardId); board.innerHTML = message; switch(type){ case 1: // success board.style.backgroundColor = "#B7F7DD"; break; case 2: // process board.style.backgroundColor = "#59B2F2"; break; default: // error board.style.backgroundColor = "#F7B9B9"; } }, register: function(){ if(formHandler.firstname && formHandler.lastname && formHandler.level && formHandler.course && formHandler.phoneNumber){ /* if all data is clean * create an ajax object */ var AjaxObject = formHandler.createAjaxObject(); if(!AjaxObject){ // if Ajax object could not be created, return error formHandler.displayMessage("Internal Error", 0); }else{ /* if Ajax object was created successfully * configure it */ AjaxObject.open("post", formHandler.registerUri); AjaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); AjaxObject.send("fname="+formHandler.firstname+"&lname="+formHandler.lastname+"&level="+formHandler.level+"&course="+formHandler.course+"&phone="+formHandler.phoneNumber); AjaxObject.onerror = function(){ // If Ajax object encounters an error formHandler.displayMessage("Internal Error", 0); }; AjaxObject.onreadystatechange = function(){ if(AjaxObject.readyState == 4){ // on success, process returned result var response = JSON.parse(AjaxObject.responseText); if(response.isSucceed){ // if returned result us desired formHandler.displayMessage(response.message, 1); }else{ formHandler.displayMessage(response.message, 0); } }else{ formHandler.displayMessage("Registering user", 2); } }; } }else{ // if data is erroneous var message; if(!formHandler.firstname){ message = "Check firstname. No spaces allowed."; }else if(!formHandler.lastname){ message = "Check lastname. No spaces allowed."; }else if(!formHandler.level){ message = "Select level"; }else if(!formHandler.course){ message = "Select course"; }else{ message = "Phone number must be 11 digits long"; } formHandler.displayMessage(message,0); } } }; <file_sep>/create_db.php <?php /* * */ $db_name = "bootcamp"; $db_handle = mysqli_connect("onathan.5gbfree.com", "nate", "nathaneil.1995"); if(!$db_handle){ echo "Could not connect."; }else{ #create datbase $sql = "CREATE DATABASE IF NOT EXISTS ".$db_name; $query = mysqli_query($db_handle, $sql); if(!$query){ echo "Could not create database."; }else{ #select db mysqli_select_db($db_handle, $db_name); $sql = "CREATE TABLE IF NOT EXISTS students( student_id VARCHAR(50) NOT NULL UNIQUE, student_firstname VARCHAR(100) NOT NULL, student_lastname VARCHAR(100) NOT NULL, student_level TINYINT(3) NOT NULL, student_course VARCHAR(5) NOT NULL, student_phone BIGINT(12) NOT NULL UNIQUE, PRIMARY KEY(student_id) )"; $query = mysqli_query($db_handle, $sql); if(!$query){ echo "Could not create students table."; }else{ echo "Database created."; } } } mysqli_close($db_handle); ?>
1af26947d8a7ebb2d8d5e3101691d71ed39f597f
[ "Markdown", "JavaScript", "PHP" ]
5
Markdown
dynameek/better-together
8326db29198920da6514969d285a3335617f9850
73948961b3bb47c8f3b0afdfaaedc73fb5385307
refs/heads/master
<repo_name>yqlu/origamit-signin<file_sep>/origamit-signin.js Meetings = new Mongo.Collection('meetings'); Members = new Mongo.Collection('members'); if (Meteor.isClient) { // This code only runs on the client angular.module('signin',['angular-meteor', 'ui.bootstrap']); angular.module('signin') .controller('signinCtrl', ['$scope', '$meteor', function ($scope, $meteor) { // initialize meteor collections $scope.meetings = $meteor.collection(function() { return Meetings.find({}, { sort: { date: -1 } }); }); $scope.allMembers = $meteor.collection(function() { return Members.find({}); }); // calendar functions $scope.open = function($event) { $scope.popup.opened = true; $event.preventDefault(); $event.stopPropagation(); }; $scope.popup = { opened: false }; $scope.curDate = new Date(); $scope.dateError = ""; $scope.addDate = function(curDate) { // protest if meeting on this date already exists if ($scope.meetings.find(function(d) { return d.date.toDateString() === curDate.toDateString(); })) { $scope.dateError = "Error: meeting on this date already exists"; } else { // else create new meeting, reset curDate $scope.dateError = ""; $scope.meetings.push({date: curDate, members: []}); $scope.curDate = new Date(); } }; $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.export = function() { var data = [["date", "name", "affiliation", "email"]]; $scope.meetings.forEach(function(meeting) { var dateString = meeting.date.toLocaleDateString(); meeting.members.forEach(function(memid) { var mem = Members.findOne(memid); data.push([dateString, mem.name, mem.affiliation, mem.email]); }); }); var csvContent = "data:text/csv;charset=utf-8,"; data.forEach(function(infoArray, index){ var dataString = infoArray.join(","); csvContent += index < data.length ? dataString+ "\n" : dataString; }); var encodedUri = encodeURI(csvContent); var link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "attendance.csv"); document.body.appendChild(link); link.click(); document.body.removeChild(link); }; // navigation $scope.frontpage = true; $scope.curMeeting = {}; $scope.showThisMeeting = function(meeting) { $scope.curMeeting = meeting; $scope.frontpage = false; }; $scope.showFrontpage = function() { $scope.frontpage = true; $scope.curMeeting = {}; }; $scope.removeMeeting = function(meeting) { var r = confirm("Are you sure? This cannot be undone."); if (r) { $scope.meetings.remove(meeting); } }; $scope.curMember = {name: "", affiliation: "", email: ""}; $scope.displayMember = function(id) { var mem = Members.findOne(id); return mem.name + " (" + mem.affiliation + ")"; }; $scope.onMemberSelect = function($item, $model, $label, $event) { $scope.curMember = {name: $item.name, affiliation: $item.affiliation, email: $item.email}; }; $scope.memberError = ""; $scope.submitMember = function() { // validate inputs if ($scope.curMember.name.length === 0) { $scope.memberError = "Error: name cannot be blank."; } else if ($scope.curMember.affiliation.length === 0) { $scope.memberError = "Error: affiliation cannot be blank."; } else { $scope.memberError = ""; // insert or update record in database Meteor.call('upsertMember', $scope.curMember, function(err) { if (err) { console.error(err); } else { var newMember = Members.findOne({name: $scope.curMember.name}); if (newMember && newMember._id) { // find new memberId and push into current meeting's list of members // if not already inside if (!$scope.curMeeting.members.find(function(i) { return i === newMember._id; })) { $scope.curMeeting.members.splice(0,0,newMember._id); } $scope.$apply(); $scope.curMember = {name: "", affiliation: "", email: ""}; } else { console.error("Error: unable to insert member"); } } }); } }; $scope.removeMember = function(idx) { var removedMemberId = $scope.curMeeting.members[idx]; // remove from this meeting $scope.curMeeting.members.splice(idx, 1); // if member did not come for any other meetings // delete from allMembers list as well var meetingsWithMember = $scope.meetings.filter(function(meet) { return meet.members.find(function(mem) { return mem === removedMemberId; }); }); if (meetingsWithMember.length === 0) { var allMembersIdx = $scope.allMembers.findIndex(function(mem) { return mem._id === removedMemberId; }); $scope.allMembers.splice(allMembersIdx, 1); } }; }]); } if (Meteor.isServer) { var basicAuth = new HttpBasicAuth(function(user, pass) { return user === "origamit" && CryptoJS.SHA1(pass).toString() === "<PASSWORD>"; }); basicAuth.protect(); Meteor.startup(function () { // code to run on server at startup }); } Meteor.methods({ upsertMember: function(member) { var returnValue = Members.upsert({ name: member.name }, { $set: { affiliation: member.affiliation, email: member.email } }); } });
cf3a66419d3356ac427fccc97c674efc3d7b2c4f
[ "JavaScript" ]
1
JavaScript
yqlu/origamit-signin
84eeb68f5b7d0df7974c16073e747fe54c6c1082
aab6c4a2dfb095d7a63eaa167a288816843f0d4f
refs/heads/master
<file_sep>export { default as useFormEditDoc } from './useFormEditDoc'; export { default as useCreateChildPage } from './useCreateChildPage'; export { default as useCreateMainDoc } from './useCreateMainDoc'; export { default as useOnClickOutside } from './useOnClickOutside'; export { default as useNavigationForm } from './useNavigationForm'; export { default as useGlobalStyleForm } from './useGlobalStyleForm'; export { default as useCreateDocument } from './useCreateDocument'; <file_sep>--- title: Some Title2 description: This is a test doc tags: - dsr contentType: documentation date: 'Wed Sep 30 2020 10:09:35 GMT-0400 (Eastern Daylight Time)' slug: some-title2 parent: dsr --- # Heading Testing some document creation<file_sep>import Link from 'next/link'; import Error from 'next/error'; import { useRouter } from 'next/router'; import { InlineForm, InlineText } from 'react-tinacms-inline'; import matter from 'gray-matter'; import { useGithubMarkdownForm } from 'react-tinacms-github'; import { getGithubPreviewProps, parseMarkdown } from 'next-tinacms-github'; import { InlineWysiwyg } from 'react-tinacms-editor'; import { jsx, Button, Flex, NavLink, Box, Link as ThemeLink, Text } from 'theme-ui'; import { Icon } from '@makerdao/dai-ui-icons'; import MarkdownWrapper from '@components/markdown-wrapper'; import EditLink from '@components/EditLink'; import { usePlugin, useCMS } from 'tinacms'; import { createToc, getBlogPosts, getGuides } from '@utils'; import { ContentTypes } from '../../utils/constants'; import GuidesLayout from '@layouts/GuidesLayout'; const DocsPage = (props) => { const cms = useCMS(); const previewURL = props.previewURL || ''; const router = useRouter(); if (!props.file) { return <Error statusCode={404} />; } if (router.isFallback) { return <div>Loading...</div>; } const formOptions = { label: 'Edit doc page', fields: [ { name: 'frontmatter.title', label: 'Title', component: 'text', }, ], }; const [data, form] = useGithubMarkdownForm(props.file, formOptions); usePlugin(form); const moduleResources = props.resources ?.filter( (r) => r.data.frontmatter.parent === props.file.data.frontmatter.parent && r.data.frontmatter.contentType === ContentTypes.DOCUMENTATION ) .reduce((acc, val) => { acc.push({ title: val.data.frontmatter.title, slug: val.data.frontmatter.slug, root: val.data.frontmatter.root, }); return acc; }, []) .sort((a, b) => (a.root ? -1 : b.root ? 1 : 0)); return ( <GuidesLayout resources={moduleResources} slug={props.slug} toc={props.Alltocs} resourcePath={ContentTypes.DOCUMENTATION} > <InlineForm form={form}> <InlineWysiwyg name="markdownBody" sticky={'calc(var(--tina-toolbar-height) + var(--tina-padding-small))'} imageProps={{ directory: 'public/images/', parse: (filename) => '/images/' + filename, previewSrc(src) { return cms.api.github.getDownloadUrl('public/' + src); }, }} focusRing={{ offset: { x: 35, y: 0 }, borderRadius: 0 }} > <MarkdownWrapper source={data.markdownBody} /> </InlineWysiwyg> </InlineForm> <EditLink /> </GuidesLayout> ); }; /** * Fetch data with getStaticProps based on 'preview' mode */ export const getStaticProps = async function ({ preview, previewData, params }) { const { slug } = params; const fileRelativePath = `content/resources/documentation/${slug}.md`; let Alltocs = ''; const resources = await getGuides(preview, previewData, 'content/resources/documentation'); if (preview) { const previewProps = await getGithubPreviewProps({ ...previewData, fileRelativePath, parse: parseMarkdown, }); if (typeof window === 'undefined') { Alltocs = createToc(previewProps.props.file.data.markdownBody); } return { props: { resources, Alltocs, previewURL: `https://raw.githubusercontent.com/${previewData.working_repo_full_name}/${previewData.head_branch}`, ...previewProps.props, }, }; } const content = await import(`../../content/resources/documentation/${slug}.md`); const data = matter(content.default); if (typeof window === 'undefined') { Alltocs = createToc(data.content); } return { props: { slug, resources, Alltocs, sourceProvider: null, error: null, preview: false, // the markdown file file: { fileRelativePath, data: { frontmatter: data.data, markdownBody: data.content, }, }, }, }; }; export const getStaticPaths = async function () { const fg = require('fast-glob'); const contentDir = 'content/resources/documentation'; const files = await fg(`${contentDir}/*.md`); const paths = files .filter((file) => !file.endsWith('index.md')) .map((file) => { const path = file.substring(contentDir.length + 1, file.length - 3); return { params: { slug: path } }; }); return { fallback: true, paths, }; }; export default DocsPage; <file_sep>--- title: 'Maker Protocol 101' description: Getting Started with Maker Protocol tags: ['keepers', 'governance'] slug: maker-protocol-101 parent: 'governance' contentType: 'guides' --- # Maker Protocol 101 ## **For a fully comprehensive overview of the smart contracts within the Maker Protocol, please download the Maker Protocol 101 Slide Deck \(PDF\) below or visit the view-only link** [**here**](https://drive.google.com/file/d/1bEOlNk2xUXgwy0I_UlB_8tPPZ8mH1gy9/view?usp=sharing)**.** <file_sep>export { default as toMarkdownString } from './toMarkdownString'; export { default as flatDocs } from './flatDocs'; export { default as createToc } from './createToc.js'; export { default as theme } from './theme'; export { default as isActiveNav } from './isNavActive'; export { default as getRandID } from './getRandID'; export { default as getBlogPosts } from './getBlogPosts'; export { default as getGuides } from './getGuides'; <file_sep>import makerTheme from '@makerdao/dai-ui-theme-maker-neue'; import { icons as standardIcons } from '@makerdao/dai-ui-icons'; import { icons as brandIcons } from '@makerdao/dai-ui-icons-branding'; const icons = { ...standardIcons, ...brandIcons }; const theme = { ...makerTheme, icons, colors: { ...makerTheme.colors, background: '#212', surface: '#ffffff08', text: '#fffff0', onBackground: '#eaebf0', primary: '#F012BE', muted: '#ffffff08', onBackgroundAlt: '#e1dfec', onBackgroundMuted: '#ffffff99', onSurface: '#ABA8bc', }, fonts: { body: 'Inconsolata, sans-serif', heading: "'FT Base',-apple-system,system-ui,BlinkMacSystemFont,'SF Pro Text','Segoe UI',Roboto,Helvetica,Arial,sans-serif", monospace: 'monospace', }, text: { ...makerTheme.text, megaHeading: { variant: 'text.heading', fontSize: [9, 10], }, }, links: { ...makerTheme.links, nav: { ...makerTheme.links.nav, fontFamily: 'heading', }, sidebar: { variant: 'links.nav', fontSize: 1, }, }, styles: { ...makerTheme.styles, fakeLi: { listStyle: 'none', }, h1: { ...makerTheme.styles.h1, mt: 4, }, a: { color: 'primary', textDecoration: 'none', '&:hover': { color: 'primaryEmphasis', }, }, ul: { pl: 4, }, pre: { bg: 'background', }, code: { ...makerTheme.styles.code, p: 0, m: 0, }, // applies to single-backticks inlineCode: { fontFamily: 'monospace', fontSize: 3, bg: 'primaryMuted', color: 'primaryAlt', px: 1, }, }, }; export default theme; <file_sep>/** @jsx jsx */ import { jsx, Input, Box } from 'theme-ui'; const EmailSignup = ({ placeholder }) => { return ( <Box sx={{ width: '100%' }}> <Input placeholder={placeholder}></Input> </Box> ); }; export default EmailSignup; <file_sep>import { useCMS, usePlugins } from 'tinacms'; import { useRouter } from 'next/router'; import slugify from 'slugify'; import { FORM_ERROR } from 'final-form'; import { toMarkdownString, flatDocs, getRandID } from '@utils'; import { removeInvalidChars } from '../utils/removeInvalidChars'; const useCreateDocument = (resources, module) => { const router = useRouter(); const cms = useCMS(); usePlugins([ { __type: 'content-creator', name: 'Add a new resource', fields: [ { name: 'title', label: 'Title', component: 'text', required: true, validate(value, allValues, meta, field) { if (!value) { return 'A title is required'; } if (resources.some((post) => post.fileName === slugify(value, { lower: true }))) { return 'Sorry the document title must be unique'; } }, }, { name: 'description', label: 'Description', component: 'text', required: false, }, { name: 'tags', component: 'tags', label: 'Tags', required: true, description: 'Tags for this file', validate(value, allValues, meta, field) { if (!value) { return 'Tags are required'; } }, }, { component: 'select', name: 'contentType', label: 'Content Type', description: 'Select the content type for this resource.', options: ['documentation', 'guides'], required: true, validate(value, allValues, meta, field) { if (!value) { return 'Content type is required'; } }, }, ], onSubmit: async (frontMatter) => { const github = cms.api.github; const slug = removeInvalidChars(slugify(frontMatter.title, { lower: true })); const fileRelativePath = `content/resources/${frontMatter.contentType}/${slug}.md`; frontMatter.date = frontMatter.date || new Date().toString(); frontMatter.slug = slug; frontMatter.parent = module; return await github .commit( fileRelativePath, null, toMarkdownString({ fileRelativePath, rawFrontmatter: { ...frontMatter, }, }), `Created new document: ${frontMatter.title}` ) .then((response) => { // After creating the document with frontmatter, redirect to the new URL. // Since we're still in preview mode, the document is pulled from github and can now be edited. setTimeout(() => router.push(`/${frontMatter.contentType}/${slug}`), 1500); }) .catch((e) => { return { [FORM_ERROR]: e }; }); }, }, ]); }; export default useCreateDocument; <file_sep>/** @jsx jsx */ import { Fragment } from 'react'; import { jsx, Box, NavLink } from 'theme-ui'; import Link from 'next/link'; const ContentsMenuItem = ({ resourcePath, slug, title, anchor, root }) => { return ( <Box as="li" sx={{ variant: 'styles.fakeLi', }} > <Link href={`/${resourcePath}/[slug]`} as={`/${resourcePath}/${slug}#${anchor}`} passHref> <NavLink variant="sidebar" sx={{ textAlign: 'left', color: 'text', borderRadius: 'xs', pl: 0, fontWeight: () => root && 'heading', }} > {title} </NavLink> </Link> </Box> ); }; const FileContents = ({ resourcePath, slug, toc }) => { const h1s = toc.filter((x) => x.lvl === 1); return toc.map(({ content: title, slug: anchor, lvl }, i) => { const root = h1s.length === 1 ? lvl === 1 || lvl === 2 : lvl === 1; return ( <Fragment key={`${anchor}${i}`}> {root ? ( <ContentsMenuItem resourcePath={resourcePath} slug={slug} key={anchor} title={title} anchor={anchor} root /> ) : ( <ul sx={{ m: 0, p: 0, pl: 3, }} > <ContentsMenuItem resourcePath={resourcePath} slug={slug} key={anchor} title={title} anchor={anchor} /> </ul> )} </Fragment> ); }); }; const Infobar = ({ resourcePath, slug, toc }) => { return ( <Box sx={{ border: 'solid', borderColor: 'onBackgroundMuted', borderWidth: '0 0 0 1px', }} > <Box sx={{ alignItems: 'center', justifyContent: 'center', border: 'solid', borderColor: 'onBackgroundMuted', borderWidth: '0 0 1px 0', width: '100%', mt: 2, pb: 2, pl: 2, }} > <NavLink>Contents</NavLink> </Box> <Box sx={{ px: 3 }}> <FileContents resourcePath={resourcePath} slug={slug} toc={toc} /> </Box> </Box> ); }; export default Infobar; <file_sep>import { shape } from 'prop-types'; import CodeWrapper from '@components/CodeWrapper'; import Heading from './Heading'; // import { ReactMarkdowStyled } from "./styles" import ReactMarkdown from 'react-markdown'; const MarkdownWrapper = ({ source }) => ( <ReactMarkdown source={source} renderers={{ code: CodeWrapper, heading: Heading }} /> ); MarkdownWrapper.propTypes = { post: shape(), }; export default MarkdownWrapper; <file_sep>import { array, number } from 'prop-types'; const slugify = require('slugify'); // import styled from "styled-components" import { jsx, Link } from 'theme-ui'; const Headings = ({ children, level }) => { const Heading = `h${level}`; const value = children .map((child) => child.props.value || child.props.children[0].props.value) .join(''); const slug = slugify(value, { lower: true }); return ( <Heading id={slug}> {/* <Link href={`#${slug}`} aria-label={value} className="headingLink"> */} {children} {/* </Link> */} </Heading> ); }; Headings.propTypes = { children: array, level: number, }; export default Headings; // const HeadingLink = styled.a` // &.headingLink { // line-height: 36px; // color: #333333; // font-weight: 700; // margin: 0; // margin-bottom: 12px; // &:hover { // text-decoration: none; // } // } // ` <file_sep>/** @jsx jsx */ import { Container, jsx, NavLink, Flex, Box } from 'theme-ui'; import Link from 'next/link'; const Subheader = ({ links, query }) => { return ( <Box sx={{ border: 'light', borderColor: 'onBackgroundMuted', borderWidth: '1px 0 1px 0', }} > <Container sx={{ px: 0, mt: 2 }}> <Flex as="nav" sx={{ alignItems: 'center', justifyContent: 'space-between', pb: 2, }} > {links.map(({ name, url }) => ( <Link href={{ pathname: url, query }} passHref key={name}> <NavLink sx={{ '&:last-child': { pr: 0 }, }} > {name} </NavLink> </Link> ))} </Flex> </Container> </Box> ); }; export default Subheader; <file_sep>/** @jsx jsx */ import { Fragment } from 'react'; import { jsx, Flex, NavLink, Grid, Text } from 'theme-ui'; import { Icon } from '@makerdao/dai-ui-icons'; import Link from 'next/link'; const Sidebar = ({ resources, resourcePath, activeSlug }) => { return ( <Flex sx={{ p: 4, flexDirection: 'column' }}> <Grid gap={0} columns={'20px auto'}> <Text sx={{ pl: 2, gridColumnStart: 2 }}>Module</Text> {resources.map(({ title, slug }) => { const active = slug === activeSlug; return ( <Fragment key={slug}> <Icon name="arrow_right" sx={{ m: 'auto', visibility: active ? undefined : 'hidden' }} ></Icon> <Link href={`/${resourcePath}/[slug]`} as={`/${resourcePath}/${slug}`} passHref> <NavLink variant="sidebar">{title}</NavLink> </Link> </Fragment> ); })} </Grid> </Flex> ); }; export default Sidebar; <file_sep>--- description: A JavaScript library that makes it easy to build applications on top of MakerDAO's platform of smart contracts title: Savings Service tags: - daijs - dsr slug: savingsservice parent: daijs contentType: documentation --- # Dai Savings Rate Use the `'mcd:savings'` service to work with the Dai Savings Rate system. In the code, this is called [SavingsService](https://github.com/makerdao/dai.js/blob/dev/packages/dai-plugin-mcd/src/SavingsService.js). ```javascript const service = maker.service('mcd:savings'); ``` ## Instance methods All the methods below are asynchronous. `join`, `exit`, and `exitAll` use a [proxy contract](advanced-configuration/using-ds-proxy.md). ### join\(amount\) Deposit the specified amount of Dai into the Dai Savings Rate \(DSR\) contract. ```javascript await service.join(DAI(1000)); ``` ### exit\(amount\) Withdraw the specified amount of Dai from the DSR contract. ### exitAll\(\) Withdraw all Dai owned by the current account from the DSR contract. ### balance\(\) Return the amount of Dai in the DSR contract owned by the [current address](advanced-configuration/using-multiple-accounts.md). Strictly speaking, this method returns the amount of Dai owned by the proxy contract for the current address. to work with the methods above. ### balanceOf\(address\) Return the amount of Dai in the DSR contract owned by the specified address. ### getTotalDai\(\) Get the total amount of Dai in the DSR contract for all users. ### getYearlyRate\(\) Get the current annual savings rate. <file_sep>/** @jsx jsx */ import { jsx, Box, Grid, BaseStyles } from 'theme-ui'; import Sidebar from '@components/Sidebar'; import SingleLayout from '@layouts/SingleLayout'; import SubNav from '../components/SubNav'; import Infobar from '../components/Infobar'; import subNavLinks from '../data/resourcesSubNav.json'; import { useGithubToolbarPlugins } from 'react-tinacms-github'; const GuidesLayout = ({ resources, resourcePath, slug: activeSlug, toc, children }) => { useGithubToolbarPlugins(); const subnav = <SubNav links={subNavLinks} />; return ( <SingleLayout subnav={subnav}> <Grid columns={['auto', '300px auto 250px']} gap="0"> <Sidebar resources={resources} resourcePath={resourcePath} activeSlug={activeSlug} /> <Box sx={{ bg: 'surface', borderRadius: 0, py: 0, px: 4 }}> <BaseStyles>{children}</BaseStyles> </Box> <Infobar resourcePath={resourcePath} slug={activeSlug} toc={toc} /> </Grid> </SingleLayout> ); }; export default GuidesLayout; <file_sep>/** @jsx jsx */ import { jsx, Card, Heading, Text, Box, Flex, Grid, Container } from 'theme-ui'; import Link from 'next/link'; const GuideList = ({ guides, title, smallText, columns = [2, 3], path }) => { return ( <Container> <Flex sx={{ mb: 6 }}> <Box> <Flex sx={{ mb: 3 }}> <Heading>{title}</Heading> </Flex> <Grid columns={columns}> {guides.map( ({ data: { frontmatter: { title, description, slug }, }, }) => { return ( <Grid key={title} sx={{ mr: 3, }} > <Flex sx={{ flexDirection: 'column' }}> <Box sx={{ height: 6, border: 'light' }}></Box> {smallText && <Text variant="caps">{smallText}</Text>} </Flex> <Link key={title} href={`/${path}/${slug}/`}> <Flex sx={{ flexDirection: 'column' }}> <Heading as="a" sx={{ cursor: 'pointer' }}> {title} </Heading> <Text>{description}</Text> </Flex> </Link> </Grid> ); } )} </Grid> </Box> </Flex> </Container> ); }; export default GuideList; <file_sep>/** @jsx jsx */ import { useState, useEffect } from 'react'; import { Container, jsx, Card, Heading, Text, Grid, Flex, Image, Box } from 'theme-ui'; import { useGithubToolbarPlugins, useGithubJsonForm } from 'react-tinacms-github'; import { usePlugin } from 'tinacms'; import { getGithubPreviewProps, parseJson } from 'next-tinacms-github'; import { InlineForm, InlineText } from 'react-tinacms-inline'; import Link from 'next/link'; import useMaker from '../hooks/useMaker'; import SingleLayout from '@layouts/SingleLayout.js'; import { Icon } from '@makerdao/dai-ui-icons'; import ArticlesList from '@components/ArticlesList'; import GuideList from '../components/GuideList'; import EditLink from '../components/EditLink'; import CodeBox from '@components/CodeBox'; import { getGuides } from '@utils'; import useCreateDocument from '../hooks/useCreateDocument'; const codeSections = [ { title: 'Dai.js', des: 'the JS lib', language: 'javascript', link: '/documentation/savingsservice', code: ` async getTotalDai() { const totalPie = new BigNumber(await this._pot.Pie()); const chi = await this.chi(); return DAI( totalPie .times(chi) .div(WAD) .dp(18) ); } `, }, { title: 'Pot.sol', des: 'How join works in the contract', language: 'clike', link: '/documentation/pot-detailed-documentation', code: ` // --- Savings Dai Management --- function join(uint wad) external note { require(now == rho, "Pot/rho-not-updated"); pie[msg.sender] = add(pie[msg.sender], wad); Pie = add(Pie, wad); vat.move(msg.sender, address(this), mul(chi, wad)); } `, }, { title: 'pyMaker', language: 'python', link: '/', des: 'python pything ', code: 'snippet', }, ]; const DsrInfo = ({ rate, totalDai }) => { return ( <Grid columns={2}> <Card> <Flex sx={{ p: 3, flexDirection: 'column', alignItems: 'center' }}> <Heading sx={{ pb: 2 }}>{`${rate}%`}</Heading> <Heading>Dai Savings Rate</Heading> </Flex> </Card> <Card> <Flex sx={{ p: 3, flexDirection: 'column', alignItems: 'center' }}> <Heading sx={{ pb: 2 }}>{totalDai}</Heading> <Heading>Dai In DSR</Heading> </Flex> </Card> </Grid> ); }; const PageLead = ({ rate, totalDai }) => { return ( <Container> <Flex sx={{ flexDirection: 'column', alignItems: 'center' }}> <Heading sx={{ mt: 6 }} variant="largeHeading"> DSR </Heading> <Text sx={{ my: 4, mx: 7, px: 4 }}> The DSR is the Dai savings rate. It allows users to deposit dai and activate the Dai Savings Rate and earning savings on their dai. </Text> <DsrInfo rate={rate} totalDai={totalDai} /> </Flex> </Container> ); }; const Intro = () => { return ( <Container> <Grid columns={'1fr 2fr'} sx={{ mb: 4, p: 6 }}> <Heading variant="largeHeading">What is DSR?</Heading> <Grid> <Text className="subtext" variant="smallHeading"> <InlineText name="subtext" /> </Text> <Text sx={{ color: 'onBackgroundMuted' }}> Raising and lowering the DSR helps control the supply and demand of Dai, which in turn helps maintain the stability of the peg. </Text> </Grid> </Grid> </Container> ); }; const ListItem = ({ title, link, description }) => ( <Card px={4}> <Link href={link}> <Grid columns={'1fr auto'}> <Flex sx={{ flexDirection: 'column' }}> <Heading variant="microHeading">{title}</Heading> <Text variant="smallText">{description}</Text> </Flex> <Flex sx={{ alignItems: 'center', justifyContent: 'flex-end' }}> <Icon name="increase" /> </Flex> </Grid> </Link> </Card> ); const Ecosystem = () => { return ( <Container> <Flex sx={{ flexDirection: 'column', mb: 6, }} > <Flex sx={{ pb: 4, alignItems: 'center', }} > <Heading pr={3}>Ecosystem</Heading> </Flex> <Grid columns={2} sx={{ width: '100%' }}> {[ { title: 'Chai.money', description: 'Manage, optimise and deploy your assets to get the best returns across products', link: '/dsr', }, { title: 'test', description: 'Manage, optimise and deploy your assets to get the best returns across products', link: '/dsr', }, ].map(({ title, link, description }) => { return <ListItem key={title} title={title} description={description} link={link} />; })} </Grid> </Flex> </Container> ); }; const Dsr = ({ file, preview, documentation }) => { const { maker } = useMaker(); const [rate, setRate] = useState('0.00'); const [totalDai, setTotalDai] = useState('0.00'); useEffect(() => { if (!maker) return; const getDsr = async () => { const rate = await maker.service('mcd:savings').getYearlyRate(); setRate(rate.toFormat(2)); }; const getTotalDai = async () => { const total = await maker.service('mcd:savings').getTotalDai(); setTotalDai(total._amount.toFormat(2)); }; getDsr(); getTotalDai(); }, [maker]); const formOptions = { label: 'home page', fields: [ { name: 'subtext', component: 'text', }, ], }; const [data, form] = useGithubJsonForm(file, formOptions); usePlugin(form); useGithubToolbarPlugins(); // TODO pass resources in useCreateDocument([], 'dsr'); return ( <SingleLayout> <InlineForm form={form}> <PageLead rate={rate} totalDai={totalDai} /> <Intro /> <Grid sx={{ rowGap: 6, }} > <CodeBox cta="Dive in the code" sections={codeSections} /> <ArticlesList title="Resources" path="documentation" resources={documentation} /> <Ecosystem /> </Grid> </InlineForm> <Container> <EditLink enterText="Create a New Page" /> </Container> </SingleLayout> ); }; export const getStaticProps = async function ({ preview, previewData }) { //TODO fix path: const documentation = await getGuides(preview, previewData, 'content/resources'); const dsrDocs = documentation.filter( (g) => g.data.frontmatter.parent === 'dsr' || g.data.frontmatter.tags.includes('dsr') ); if (preview) { const file = ( await getGithubPreviewProps({ ...previewData, fileRelativePath: 'data/dsrPage.json', parse: parseJson, }) ).props; return { props: { ...file, documentation: dsrDocs, }, }; } return { props: { sourceProvider: null, error: null, preview: false, file: { fileRelativePath: 'data/dsrPage.json', data: (await import('../data/dsrPage.json')).default, }, documentation: dsrDocs, }, }; }; export default Dsr; <file_sep>export const ContentTypes = { DOCUMENTATION: 'documentation', GUIDE: 'guides', };
2d37841b1cf7d51c2add9482b792adb55499b55d
[ "Markdown", "JavaScript" ]
18
Markdown
b-pmcg/developer-portal
b3db046880a9e1bb55cd469c51d245af1163d3b6
9c8eb93bfcaf3878b80ef6d8b0db632b75cc09d0
refs/heads/master
<repo_name>tonyfraggins/tony.github.io<file_sep>/README.md # tony.github.io
cd500bfe8723b2772b639a96ff6ee3c385065385
[ "Markdown" ]
1
Markdown
tonyfraggins/tony.github.io
3d098eec5e550fd496e5bcff6688c622947e62f8
ddb8bd539773133e013cc2d5c4a1ff499ab3149c
refs/heads/master
<file_sep># Mr.CAD---Programming
20e27e9843c4b74ad17d3410f1d6e6ce7ca5cc28
[ "Markdown" ]
1
Markdown
Mr-CAD/Mr.CAD---Programming
af4f0bbcd26abe41c12116fd644f85308fe5b9eb
8a767b48c0318e2c4b597de91b844d28c3924d28
refs/heads/master
<repo_name>plaban1981/Matplotlib_and_Seaborn<file_sep>/README.md # Matplotlib_and_Seaborn Seaborn and matplotlib excercises
18d62ca5ccd81477f9f51def7f5c921059794a44
[ "Markdown" ]
1
Markdown
plaban1981/Matplotlib_and_Seaborn
029bdbc1b66071fe17570febfd533d1cfb6676ea
2955e98d8832cfb4c14325d4286cad266741878f
refs/heads/master
<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "IParameter.h" #define BB_OBJECT_COPY CKGUID(0x3f6b0ac7,0x47d20f78) #define BB_OBJECT_DELETE CKGUID(0x74120ded,0x76524673) enum BB_COPY_SETTINGS { bbS_Dynamic, bbS_Awak, bbs_Flags, bbs_NewBodyFlags, }; CKBEHAVIORFCT BBCopy; int BB_CopyNew(const CKBehaviorContext& context) { CKBehavior *beh = context.Behavior; CKContext *ctx = context.Context; BBCopy(context); // Copy Objects int count = beh->GetInputParameterCount(); // Dynamic ? BOOL dynamic = TRUE; beh->GetLocalParameterValue(0,&dynamic); int flags = 0; beh->GetLocalParameterValue(bbs_Flags,&flags); int newBodyFlags = 0; beh->GetLocalParameterValue(bbs_NewBodyFlags,&newBodyFlags); CKDependencies* dep = *(CKDependencies**)beh->GetInputParameterReadDataPtr(0); XArray<CK3dEntity*>SrcObjects; int i; for(i=1;i<count;++i) { // Input Reading CKObject* srcObject = beh->GetInputParameterObject(i); if (!srcObject) continue; // we do not want to to duplicate level if (CKIsChildClassOf(srcObject,CKCID_LEVEL)) continue; if (CKIsChildClassOf(srcObject,CKCID_3DENTITY)) { CK3dEntity *src=(CK3dEntity*)srcObject; CK3dEntity *dst=(CK3dEntity*)(beh->GetOutputParameterObject(i-1)); pObjectDescr oDescr; IParameter::Instance()->copyTo(oDescr,src,flags); //---------------------------------------------------------------- // // IC Data, we just save it out // if ( flags & PB_CF_COPY_IC ) { CKScene *scene = ctx()->GetCurrentScene(); if(scene && src->IsInScene(scene)) { CKStateChunk *chunk = scene->GetObjectInitialValue(src); if(chunk) { CKStateChunk *chunkClone=CreateCKStateChunk(CKCID_OBJECT); chunkClone->Clone(chunk); //---------------------------------------------------------------- // // copy and restore IC of parent object // if(chunkClone) { scene->SetObjectInitialValue(dst,chunkClone); } CKERROR error = 0; if ( flags & PB_CF_RESTORE_IC ) { error = CKReadObjectState(dst,chunkClone); } //---------------------------------------------------------------- // // copy and restore IC for children : // int a = ((*dep->At(CKCID_3DENTITY)) & CK_DEPENDENCIES_COPY_3DENTITY_CHILDREN); int a1 = (( flags & PB_CF_OVRRIDE_BODY_FLAGS ) && (newBodyFlags & BF_Hierarchy)); int a2 = ( oDescr.flags & BF_Hierarchy); if ( ((*dep->At(CKCID_3DENTITY)) & CK_DEPENDENCIES_COPY_3DENTITY_CHILDREN) && ( (( flags & PB_CF_OVRRIDE_BODY_FLAGS ) && (newBodyFlags & BF_Hierarchy)) || ( oDescr.flags & BF_Hierarchy) ) ) { CK3dEntity* subEntity = NULL; SrcObjects.Clear(); while (subEntity= dst->HierarchyParser(subEntity) ) { SrcObjects.PushBack(subEntity); } int dCount = dst->GetChildrenCount(); int dCount2 = SrcObjects.Size(); for(i = 0;i<SrcObjects.Size(); ++i) { subEntity = *SrcObjects.At(i); CK3dEntity *orginalObject = findSimilarInSourceObject(src,dst,subEntity); if (orginalObject) { CKStateChunk *chunkSub = scene->GetObjectInitialValue(orginalObject); if (chunkSub) { CKStateChunk *chunkCloneSub=CreateCKStateChunk(CKCID_OBJECT); chunkCloneSub->Clone(chunkSub); scene->SetObjectInitialValue(subEntity,chunkCloneSub); if ( flags & PB_CF_RESTORE_IC ) { CKReadObjectState(subEntity,chunkCloneSub); subEntity->SetParent(dst); } } } } } } } } pRigidBody *srcBody = GetPMan()->getBody((CK3dEntity*)src); NxShape *shape = NULL; if (srcBody) { shape = srcBody->getSubShape((CK3dEntity*)src); } //---------------------------------------------------------------- // // copy sub shape ? // if (shape && shape!=srcBody->getMainShape()) { pFactory::Instance()->cloneShape((CK3dEntity*)src,(CK3dEntity*)(beh->GetOutputParameterObject(i-1)),srcBody->GetVT3DObject(),flags,newBodyFlags); continue; } //---------------------------------------------------------------- // // copy body ? // if (srcBody) pFactory::Instance()->cloneRigidBody(src,dst,dep,flags,newBodyFlags); } } return CK_OK; } /************************************************************************/ /* */ /************************************************************************/ CKERROR PhysicManager::_HookGenericBBs() { CKBehaviorManager *bm = m_Context->GetBehaviorManager(); CKBehaviorPrototype *bproto = CKGetPrototypeFromGuid(BB_OBJECT_COPY); if(bproto) { bproto->DeclareSetting("Copy Flags",VTF_PHYSIC_ACTOR_COPY_FLAGS,""); bproto->DeclareSetting("New Body Flags",VTF_BODY_FLAGS,""); BBCopy = bproto->GetFunction(); bproto->SetFunction(BB_CopyNew); } return CK_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPJIsBrokenDecl(); CKERROR CreatePJIsBrokenProto(CKBehaviorPrototype **pproto); int PJIsBroken(const CKBehaviorContext& behcontext); CKERROR PJIsBrokenCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_BodyB, bbI_Type, }; //************************************ // Method: FillBehaviorPJIsBrokenDecl // FullName: FillBehaviorPJIsBrokenDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPJIsBrokenDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJIsBroken"); od->SetCategory("Physic/Joints"); od->SetDescription("Triggers when joint has been broken."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x17082b70,0x6eae5b38)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJIsBrokenProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJIsBrokenProto // FullName: CreatePJIsBrokenProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePJIsBrokenProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJIsBroken"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJIsBroken <br> PJIsBroken is categorized in \ref Joints <br> <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Activates output trigger when a joint has been broken. <br> <h3>Technical Information</h3> \image html PJIsBroken.png <SPAN CLASS="in">In: </SPAN> triggers the process. <BR> <BR> <SPAN CLASS="out">Exit On: </SPAN> is activated when the building block has been started. <BR> <SPAN CLASS="out">Exit Off: </SPAN> is activated when the process is completed. <BR> <SPAN CLASS="out">Broken: </SPAN> is activated when the joint has been broken. <BR> <BR> <SPAN CLASS="pin">Body B: </SPAN> The second body. Leave blank to create a joint constraint with the world. <BR> <SPAN CLASS="pin">Joint Type:</SPAN> The joint type. This helps the building block to identify a joint constraint. As usual there can be only one joint of the type x between two bodies. <BR> <BR> <SPAN CLASS="pout">Breaking Impulse:</SPAN> The impulse which broke the joint. This is clamped to the values of maxForce (or maxTorque, depending on what made the joint break) that was specified for the joint. <BR> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> */ proto->DeclareInput("On"); proto->DeclareInput("Off"); proto->DeclareOutput("Exit On"); proto->DeclareOutput("Exit Off"); proto->DeclareOutput("Broken"); proto->DeclareOutParameter("Break Impulse",CKPGUID_FLOAT); proto->SetBehaviorCallbackFct( PJIsBrokenCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Joint Type",VTE_JOINT_TYPE,"0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PJIsBroken); *pproto = proto; return CK_OK; } //************************************ // Method: PJIsBroken // FullName: PJIsBroken // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJIsBroken(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(1) ) { beh->ActivateInput(1,FALSE); return CK_OK; } if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); } ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bbI_BodyB); int jointType = GetInputParameterValue<int>(beh,bbI_Type); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,jointType)) { return CKBR_ACTIVATENEXTFRAME; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); int size = GetPMan()->getJointFeedbackList().Size(); if(bodyA || bodyB) { for (int i = 0 ; i < GetPMan()->getJointFeedbackList().Size(); i++ ) { pBrokenJointEntry *entry = *GetPMan()->getJointFeedbackList().At(i); if (entry) { if ( entry->jType ==jointType ) { CK3dEntity *bodyAEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(entry->mAEnt)); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(entry->mBEnt)); if ( bodyAEnt == target && bodyBEnt ==targetB) { beh->ActivateOutput(2); SetOutputParameterValue<float>(beh,0,entry->impulse); GetPMan()->getJointFeedbackList().EraseAt(i); return CKBR_ACTIVATENEXTFRAME; } if (bodyBEnt == targetB && bodyAEnt==target) { beh->ActivateOutput(2); SetOutputParameterValue<float>(beh,0,entry->impulse); GetPMan()->getJointFeedbackList().EraseAt(i); return CKBR_ACTIVATENEXTFRAME; } } } } } return CKBR_ACTIVATENEXTFRAME; } //************************************ // Method: PJIsBrokenCB // FullName: PJIsBrokenCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJIsBrokenCB(const CKBehaviorContext& behcontext) { return CKBR_OK; } <file_sep>#ifndef __VTCONNECTION_H_ #define __VTCONNECTION_H_ #include "xNetTypes.h" #include "tnl.h" #include "tnlGhostConnection.h" class xNetInterface; class xDistributedObject; class xDistributedClient; class vtConnection : public TNL::GhostConnection { typedef TNL::GhostConnection Parent; public: vtConnection(); TNL_DECLARE_RPC(c2sDOCreate, (TNL::Int<16>userSrcID,TNL::StringPtr objectName,TNL::StringPtr className,TNL::Int<16>classType)); TNL_DECLARE_RPC(c2sDODestroy, (TNL::Int<16>userSrcID,TNL::Int<16>serverID,TNL::StringPtr className,TNL::Int<16>classType)); TNL_DECLARE_RPC(c2sDORequestOwnerShip, (TNL::S32 userSrcID,TNL::Int<16>serverID)); TNL_DECLARE_RPC(s2cDOChangeOwnershipState, (TNL::Int<16>serverID,TNL::S32 newOwnerID,TNL::S32 state)); TNL_DECLARE_RPC(s2cSetUserDetails, (TNL::Int<16>userID)); TNL_DECLARE_RPC(c2sDeployDistributedClass,( TNL::StringPtr className, TNL::Int<16>entityType, TNL::Vector<TNL::StringPtr>propertyNames, TNL::Vector<TNL::Int<16> >propertyNativeTypes, TNL::Vector<TNL::Int<16> >propertyValueTypes, TNL::Vector<TNL::Int<16> >predictionTypes)); TNL_DECLARE_RPC(s2cDeployDistributedClass,( TNL::StringPtr className, TNL::Int<16>entityType, TNL::Vector<TNL::StringPtr>propertyNames, TNL::Vector<TNL::Int<16> >propertyNativeTypes, TNL::Vector<TNL::Int<16> >propertyValueTypes, TNL::Vector<TNL::Int<16> >predictionTypes)); void connect(TNL::NetInterface *theInterface, const TNL::Address &address, bool requestKeyExchange, bool requestCertificate); void onConnectTerminated(TNL::NetConnection::TerminationReason reason, const char *rejectionString); void onConnectionTerminated(TNL::NetConnection::TerminationReason reason, const char *string); void onConnectionEstablished(); bool isDataToTransmit(); int getUserID() const { return m_UserID; } void setUserID(int val) { m_UserID = val; } const char* GetUserName() const { return m_UserName.getString(); } void SetUserName(const char*val); void setClientName(const char *string) { mClientName = string; } int GetConnectionID() const { return m_ConnectionID; } void SetConnectionID(int val) { m_ConnectionID = val; } ////////////////////////////////////////////////////////////////////////// //overwrites : void writePacket(TNL::BitStream *bstream,TNL::NetConnection::PacketNotify *notify); void readPacket(TNL::BitStream *bstream); void packetReceived(TNL::GhostConnection::PacketNotify *notify); struct GamePacketNotify : public TNL::GhostConnection::GhostPacketNotify { TNL::U32 firstUnsentMoveIndex; TNL::U32 updateType; GamePacketNotify() { firstUnsentMoveIndex = 0;updateType=0; } }; PacketNotify *allocNotify() { return new GamePacketNotify; } TNL::U32 getControlCRC(); int m_UserID; xNString m_UserName; int m_ConnectionID; TNL::RefPtr<xNetInterface> m_NetInterface; TNL::Address localAddress; TNL::StringTableEntry mClientName; TNL_DECLARE_NETCONNECTION(vtConnection); TNL::SafePtr<xDistributedClient>scopeObject; enum { GHOST_UPDATE = 61, NO_UPDATE = 58, }; enum { MaxPendingMoves = 63, MaxMoveTimeCredit = 512, }; int mWriteTypeTracker; int mReadType; int getWriteTypeTracker() const { return mWriteTypeTracker; } void setWriteTypeTracker(int val) { mWriteTypeTracker = val; } TNL::Vector<xDistributedObject*>pendingObjects; void addUpdateObject(xDistributedObject*object); TNL::SafePtr<xDistributedObject> controlObject; TNL::U32 mLastClientControlCRC; bool mCompressPointsRelative; TNL::U32 firstMoveIndex; TNL::U32 highSendIndex[3]; TNL::U32 mMoveTimeCredit; /************************************************************************/ /* */ /************************************************************************/ TNL_DECLARE_RPC(c2sCreateSession_RPC,(TNL::StringPtr name,TNL::Int<16>type,TNL::Int<16>maxUsers,TNL::StringPtr password)); TNL_DECLARE_RPC(c2sDeleteSession_RPC,(TNL::Int<16>sessionID)); TNL_DECLARE_RPC(c2sJoinSession_RPC,(TNL::Int<16>userID,TNL::Int<16>sessionID,TNL::StringPtr password)); TNL_DECLARE_RPC(s2cUserJoinedSession_RPC,(TNL::Int<16>userID,TNL::Int<16>sessionID)); TNL_DECLARE_RPC(c2sLeaveSession_RPC,(TNL::Int<16>userID,TNL::Int<16>sessionID,TNL::Int<16>destroy)); TNL_DECLARE_RPC(s2cUserLeftSession_RPC,(TNL::Int<16>userID,TNL::Int<16>sessionID)); TNL_DECLARE_RPC(c2sLockSession_RPC,(TNL::Int<16>sessionID)); TNL_DECLARE_RPC(s2cAddServerLogEntry,(TNL::StringPtr entry)); virtual void disconnectFromServer(); ////////////////////////////////////////////////////////////////////////// int mSessionID; int getSessionID() const { return mSessionID; } void setSessionID(int val) { mSessionID = val; } }; #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "IParameter.h" XString PhysicManager::_getConfigPath() { XString result; CKPathManager *pm = (CKPathManager*)this->m_Context->GetPathManager(); //pm->OpenSubFile() XString configFile("DonglePaths.ini"); XString section("Paths"); char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,configFile); int errorLine; XString errorText; VxConfiguration config; VxConfigurationSection *tsection = NULL; VxConfigurationEntry *entry = NULL; if (!config.BuildFromFile(Ini, errorLine, errorText)) { MessageBox(NULL,"Cannot open DonglePath.Ini in Virtools directory",0,MB_OK|MB_ICONERROR); return XString("none"); } if ((tsection = config.GetSubSection((char*)section.Str(), FALSE)) != NULL) { ConstEntryIt it = tsection->BeginChildEntry(); VxConfigurationEntry *sEntry = NULL; char newPath[MAX_PATH]; while (sEntry=tsection->GetNextChildEntry(it)) { if (sEntry!=NULL) { const char * value = sEntry->GetValue(); XString path(value); FILE *file = fopen(path.CStr(),"r"); if (file) { fclose(file); return path; } } } MessageBox(NULL,"Couldnt find any valid license file in the DonglePaths.Ini",0,MB_OK|MB_ICONERROR); } return result; } void PhysicManager::bindVariables() { CKVariableManager* vm = m_Context->GetVariableManager(); if( !vm ) return; pSDKParameters& p = getSDKParameters(); vm->Bind( "Physic/Skin Width", &p.SkinWidth, 0.025f, VxVar::COMPOSITIONBOUND, "Default value for pShape::skinWidth."); vm->Bind( "Physic/Default Sleep Linear Velocity Squared", &p.DefaultSleepLinVelSquared, 0.15f*0.15f, VxVar::COMPOSITIONBOUND, "The default linear velocity, squared, below which objects start going to sleep. Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set."); vm->Bind( "Physic/Default Sleep Angular Velocity Squared", &p.DefaultSleepAngVel_squared, 0.14f * 0.14f, VxVar::COMPOSITIONBOUND, "The default angular velocity, squared, below which objects start going to sleep. Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set."); vm->Bind( "Physic/Bounce Threshold", &p.BounceThreshold , -2.0f , VxVar::COMPOSITIONBOUND, "A contact with a relative velocity below this will not bounce."); vm->Bind( "Physic/Dynamic Friction Scaling", &p.DynFrictScaling,1.0f , VxVar::COMPOSITIONBOUND, "This lets the user scale the magnitude of the dynamic friction applied to all objects. "); vm->Bind( "Physic/Static Friction Scaling", &p.StaFrictionScaling,1.0f,VxVar::COMPOSITIONBOUND, "This lets the user scale the magnitude of the static friction applied to all objects."); vm->Bind( "Physic/Maximum Angular Velocity", &p.MaxAngularVelocity , 7.0f, VxVar::COMPOSITIONBOUND, "See the comment for pRigidBody::setMaxAngularVelocity() for details."); vm->Bind( "Physic/Continuous Collision Detection", &p.ContinuousCD ,0.0f, VxVar::COMPOSITIONBOUND, "Enable/disable continuous collision detection (0.0f to disable)."); vm->Bind( "Physic/Adaptive Force", &p.AdaptiveForce ,1.0f , VxVar::COMPOSITIONBOUND, "Used to enable adaptive forces to accelerate convergence of the solver. "); vm->Bind( "Physic/Collision Veto Jointed", &p.CollVetoJointed , 1.0f , VxVar::COMPOSITIONBOUND, "Controls default filtering for jointed bodies. True means collision is disabled."); vm->Bind( "Physic/Trigger Trigger Callback", &p.TriggerTriggerCallback, 1.0f , VxVar::COMPOSITIONBOUND, "Controls whether two touching triggers generate a callback or not."); vm->Bind( "Physic/CCD Epsilon", &p.CCDEpsilon,0.01f, VxVar::COMPOSITIONBOUND, "Distance epsilon for the CCD algorithm."); vm->Bind( "Physic/Solver Convergence Threshold", &p.SolverConvergenceThreshold, 0.0f , VxVar::COMPOSITIONBOUND, "Used to accelerate solver."); vm->Bind( "Physic/BBox Noise Level", &p.BBoxNoiseLevel, 0.001f, VxVar::COMPOSITIONBOUND, "Used to accelerate HW Broad Phase. "); vm->Bind( "Physic/Implicit Sweep Cache Size", &p.ImplicitSweepCacheSize, 5.0f , VxVar::COMPOSITIONBOUND, "Used to set the sweep cache size. "); vm->Bind( "Physic/Default Sleep Energy", &p.DefaultSleepEnergy, 0.005f, VxVar::COMPOSITIONBOUND, "The default sleep energy threshold. Objects with an energy below this threshold are allowed to go to sleep. Note: Only used when the pSDKP_BF_ENERGY_SLEEP_TEST flag is set."); vm->Bind( "Physic/Constant Fluid Max Packets", &p.ConstantFluidMaxPackets, 925, VxVar::COMPOSITIONBOUND, " Constant for the maximum number of packets per fluid. Used to compute the fluid packet buffer size in NxFluidPacketData."); vm->Bind( "Physic/Constant Fluid Maximum Particles Per Step", &p.ConstantFluidMaxParticlesPerStep, 4096, VxVar::COMPOSITIONBOUND, "Constant for the maximum number of new fluid particles per frame."); vm->Bind( "Physic/Improved Spring Solver", &p.ImprovedSpringSolver,1.0f , VxVar::COMPOSITIONBOUND, "Enable/disable improved spring solver for joints and wheel shapes."); vm->Bind( "Physic/Disable Physics", &p.disablePhysics,false, VxVar::COMPOSITIONBOUND, "Enable/disable physic calculation"); ////////////////////////////////////////////////////////////////////////// pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); vm->Bind( "Physic Debugger/Host", &dbgSetup.mHost,XString("localhost"), VxVar::COMPOSITIONBOUND, "Specifies the host running a debugger"); vm->Bind( "Physic Debugger/Port", &dbgSetup.port,5425, VxVar::COMPOSITIONBOUND, "Specifies the port of the remote debugger"); vm->Bind( "Physic Debugger/Enabled", &dbgSetup.enabled,0, VxVar::COMPOSITIONBOUND, "Enables/Disables the remote debugger"); vm->Bind( "Physic Console Logger/Errors", &_LogErrors,0, VxVar::COMPOSITIONBOUND, "Log Errors"); vm->Bind( "Physic Console Logger/Infos", &_LogInfo,0, VxVar::COMPOSITIONBOUND, "Log Infos"); vm->Bind( "Physic Console Logger/Trace", &_LogTrace,0, VxVar::COMPOSITIONBOUND, "Log Trace"); vm->Bind( "Physic Console Logger/Warnings", &_LogWarnings,0, VxVar::COMPOSITIONBOUND, "Log Warnings"); vm->Bind( "Physic Console Logger/Console", &_LogWarnings,0, VxVar::COMPOSITIONBOUND, "Console"); } void PhysicManager::unBindVariables() { CKVariableManager* vm = m_Context->GetVariableManager(); if( !vm ) return; pSDKParameters& p = getSDKParameters(); vm->UnBind( "Physic Console Logger/Errors" ); vm->UnBind( "Physic Console Logger/Infos" ); vm->UnBind( "Physic Console Logger/Trace" ); vm->UnBind( "Physic Console Logger/Warnings" ); vm->UnBind( "Physic Console Logger/Console" ); vm->UnBind("Physic/Skin Width"); vm->UnBind("Physic/Default Sleep Linear Velocity Squared"); vm->UnBind( "Physic/Default Sleep Angular Velocity Squared "); vm->UnBind( "Physic/Bounce Threshold"); vm->UnBind( "Physic/Dynamic Friction Scaling"); vm->UnBind( "Physic/Static Friction Scaling"); vm->UnBind( "Physic/Maximum Angular Velocity"); vm->UnBind( "Physic/Continuous Collision Detection"); vm->UnBind( "Physic/Adaptive Force "); vm->UnBind( "Physic/Collision Veto Jointed "); vm->UnBind( "Physic/Trigger Trigger Callback"); vm->UnBind( "Physic/CCD Epsilon"); vm->UnBind( "Physic/Solver Convergence Threshold"); vm->UnBind( "Physic/BBox Noise Level"); vm->UnBind( "Physic/Implicit Sweep Cache Size"); vm->UnBind( "Physic/Default Sleep Energy"); vm->UnBind( "Physic/Constant Fluid Max Packets"); vm->UnBind( "Physic/Constant Fluid Maximum Particles Per Step"); vm->UnBind( "Physic/Improved Spring Solver" ); vm->UnBind( "Physic/Disable Physics"); vm->UnBind( "Physic Debugger/Host" ); vm->UnBind( "Physic Debugger/Port" ); vm->UnBind( "Physic Debugger/Enabled" ); } #define PMANAGER_CHUNKID 1005 #define PMANAGER_SAVE_VERSION 3 #define PMANAGER_FLAGS 0 #define PMANAGER_USER_ENUM_IDENTIFIER 11005 int PhysicManager::_migrateOldCustomStructures(CKScene *scnene) { bool bIsLoading = ctx()->IsInLoad(); //CKObject* o = ctx->GetObject(ol[CKCID_MESH]); int count = ctx()->GetObjectsCountByClassID(CKCID_3DOBJECT); if (!count) return 0; // CK_ID* ol = ctx->GetObjectsListByClassID(i); XString errMessage; int nbOfObjects = 0 ; CKAttributeManager* attman = m_Context->GetAttributeManager(); const XObjectPointerArray& Array = attman->GetAttributeListPtr(GetPAttribute()); nbOfObjects = Array.Size(); if (nbOfObjects==0) return 0; if (!scnene) return 0; int attOld = GetPAttribute(); int attNew = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); int nbRecovered=0; for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { int cCount = attman->GetAttributeListPtr(GetPAttribute()).Size(); if (!cCount) break; CK3dEntity*target = static_cast<CK3dEntity*>(*it); if (!target)//shit happens break; CKParameterOut * pOld =target->GetAttributeParameter(attOld); if (!pOld)//shit happens break; pObjectDescr * oDescr = pFactory::Instance()->createPObjectDescrFromParameter(pOld); if (!oDescr)//shit happens continue; //---------------------------------------------------------------- // // fix up : // //hierarchy bool hierarchy =false; if( (oDescr->flags & BF_Hierarchy) || oDescr->hirarchy ) hierarchy = true; if (hierarchy) oDescr->flags << BF_Hierarchy; oDescr->massOffsetLinear = oDescr->massOffset; oDescr->pivotOffsetLinear = oDescr->shapeOffset; //---------------------------------------------------------------- // // attach new attribute parameter // target->SetAttribute(attNew); CKParameterOut *newPar = target->GetAttributeParameter(attNew); if (newPar) { IParameter::Instance()->copyTo(newPar,oDescr); } //---------------------------------------------------------------- // // clean old attribute // target->RemoveAttribute(attOld); //---------------------------------------------------------------- // // set IC // //----- Restore the IC if(target->IsInScene(scnene)) { CKStateChunk *chunk = scnene->GetObjectInitialValue(target); if(chunk) { CKStateChunk *chunk = CKSaveObjectState(target); scnene->SetObjectInitialValue(target,chunk); } } it = Array.Begin(); SAFE_DELETE(oDescr); nbRecovered++; //---------------------------------------------------------------- // // cleanup // } if (attman->GetAttributeListPtr(GetPAttribute()).Size() >0) { _migrateOldCustomStructures(GetContext()->GetCurrentScene()); } /* errMessage.Format("nub of old objects recovered: %d",nbRecovered); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMessage.Str()); */ return nbOfObjects; } CKERROR PhysicManager::PostLoad() { CKScene *scene = GetContext()->GetCurrentScene(); _migrateOldCustomStructures(scene); //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Post Load"); return true; } void PhysicManager::setPSDKParameters(pSDKParameters&param) { if (!getPhysicsSDK()) return ; getPhysicsSDK()->setParameter((NxParameter)pSDKP_SkinWidth,param.SkinWidth); getPhysicsSDK()->setParameter((NxParameter)pSDKP_DefaultSleepLinVelSquared,param.DefaultSleepLinVelSquared); getPhysicsSDK()->setParameter((NxParameter)pSDKP_DefaultSleepAngVelSquared,param.DefaultSleepAngVel_squared); getPhysicsSDK()->setParameter((NxParameter)pSDKP_BounceThreshold,param.BounceThreshold); getPhysicsSDK()->setParameter((NxParameter)pSDKP_DynFrictScaling,param.DynFrictScaling); getPhysicsSDK()->setParameter((NxParameter)pSDKP_StaFrictionScaling,param.StaFrictionScaling); getPhysicsSDK()->setParameter((NxParameter)pSDKP_MaxAngularVelocity,param.MaxAngularVelocity); getPhysicsSDK()->setParameter((NxParameter)pSDKP_ContinuousCD,param.ContinuousCD); getPhysicsSDK()->setParameter((NxParameter)pSDKP_AdaptiveForce,param.AdaptiveForce); getPhysicsSDK()->setParameter((NxParameter)pSDKP_CollVetoJointed,param.CollVetoJointed); getPhysicsSDK()->setParameter((NxParameter)pSDKP_TriggerTriggerCallback,param.TriggerTriggerCallback); getPhysicsSDK()->setParameter((NxParameter)pSDKP_CCDEpsilon,param.CCDEpsilon); getPhysicsSDK()->setParameter((NxParameter)pSDKP_SolverConvergenceThreshold,param.SolverConvergenceThreshold); getPhysicsSDK()->setParameter((NxParameter)pSDKP_BBoxNoiseLevel,param.BBoxNoiseLevel); getPhysicsSDK()->setParameter((NxParameter)pSDKP_ImplicitSweepCacheSize,param.ImplicitSweepCacheSize); getPhysicsSDK()->setParameter((NxParameter)pSDKP_DefaultSleepEnergy,param.DefaultSleepEnergy); getPhysicsSDK()->setParameter((NxParameter)pSDKP_ConstantFluidMaxPackets,param.ConstantFluidMaxPackets); getPhysicsSDK()->setParameter((NxParameter)pSDKP_ConstantFluidMaxParticlesPerStep,param.ConstantFluidMaxParticlesPerStep); getPhysicsSDK()->setParameter((NxParameter)pSDKP_ImprovedSpringSolver,param.ImprovedSpringSolver); } CKStateChunk* PhysicManager::SaveData(CKFile* SavedFile) { if (!getNbObjects()) { return NULL; } CKStateChunk *chunk = CreateCKStateChunk(PMANAGER_CHUNKID, SavedFile); if (!chunk) return NULL; chunk->StartWrite(); chunk->WriteIdentifier(PMANAGER_CHUNKID); chunk->WriteInt(PMANAGER_SAVE_VERSION); chunk->WriteInt(PMANAGER_FLAGS); CKVariableManager* vm = m_Context->GetVariableManager(); if( !vm ) return NULL; pSDKParameters& p = getSDKParameters(); CKVariableManager::Variable *var = vm->GetVariable("Physic/Skin Width"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.SkinWidth); } var = vm->GetVariable("Physic/Default Sleep Linear Velocity Squared"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.DefaultSleepLinVelSquared); } var = vm->GetVariable("Physic/Default Sleep Angular Velocity Squared"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.DefaultSleepAngVel_squared); } var = vm->GetVariable("Physic/Bounce Threshold"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.BounceThreshold); } var = vm->GetVariable("Physic/Dynamic Friction Scaling"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.DynFrictScaling); } var = vm->GetVariable("Physic/Static Friction Scaling"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.StaFrictionScaling); } var = vm->GetVariable("Physic/Maximum Angular Velocity"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.MaxAngularVelocity); } var = vm->GetVariable("Physic/Continuous Collision Detection"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.ContinuousCD); } var = vm->GetVariable("Physic/Adaptive Force"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.AdaptiveForce); } var = vm->GetVariable("Physic/Collision Veto Jointed"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.CollVetoJointed); } var = vm->GetVariable("Physic/Trigger Trigger Callback"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.TriggerTriggerCallback); } var = vm->GetVariable("Physic/CCD Epsilon"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.CCDEpsilon); } var = vm->GetVariable("Physic/Solver Convergence Threshold"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.SolverConvergenceThreshold); } var = vm->GetVariable("Physic/BBox Noise Level"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.BBoxNoiseLevel); } var = vm->GetVariable("Physic/Implicit Sweep Cache Size"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.ImplicitSweepCacheSize); } var = vm->GetVariable("Physic/Default Sleep Energy"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.DefaultSleepEnergy); } var = vm->GetVariable("Physic/Constant Fluid Max Packets"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.ConstantFluidMaxPackets); } var = vm->GetVariable("Physic/Constant Fluid Maximum Particles Per Step"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.ConstantFluidMaxParticlesPerStep); } var = vm->GetVariable("Physic/Improved Spring Solver"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteFloat(p.ImprovedSpringSolver); } ////////////////////////////////////////////////////////////////////////// pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); var = vm->GetVariable("Physic Debugger/Host"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteString(dbgSetup.mHost.CStr()); } var = vm->GetVariable("Physic Debugger/Port"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteInt(dbgSetup.port); } var = vm->GetVariable("Physic Debugger/Enabled"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteInt(dbgSetup.enabled); } var = vm->GetVariable("Physic Console Logger/Errors"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteInt(_LogErrors); } var = vm->GetVariable("Physic Console Logger/Infos"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteInt(_LogInfo); } var = vm->GetVariable("Physic Console Logger/Trace"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteInt(_LogTrace); } var = vm->GetVariable("Physic Console Logger/Warnings"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteInt(_LogWarnings); } _saveUserEnumeration(chunk,SavedFile); var = vm->GetVariable("Physic Console Logger/Console"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteInt(_LogToConsole); } //**new var = vm->GetVariable("Physic/Disable Physics"); if (var) { chunk->WriteInt(var->IsCompositionDepending()); chunk->WriteInt(p.disablePhysics); } chunk->CloseChunk(); return chunk; } CKERROR PhysicManager::LoadData(CKStateChunk *chunk,CKFile* LoadedFile) { assert(LoadedFile != 0); if (!chunk) return CKERR_INVALIDPARAMETER; chunk->StartRead(); if (chunk->SeekIdentifier(PMANAGER_CHUNKID)) { // Check the version int version = chunk->ReadInt(); // Check the flags int flags = chunk->ReadInt(); CKVariableManager* vm = m_Context->GetVariableManager(); if( !vm ) return NULL; pSDKParameters& p = getSDKParameters(); ////////////////////////////////////////////////////////////////////////// int isInCMO = chunk->ReadInt(); float v = chunk->ReadFloat(); if (isInCMO) { p.SkinWidth = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.DefaultSleepLinVelSquared = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.DefaultSleepAngVel_squared = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.BounceThreshold = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.DynFrictScaling = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.StaFrictionScaling = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.MaxAngularVelocity = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.ContinuousCD = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.AdaptiveForce = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.CollVetoJointed = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.TriggerTriggerCallback = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.CCDEpsilon = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.SolverConvergenceThreshold = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.BBoxNoiseLevel = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.ImplicitSweepCacheSize = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.DefaultSleepEnergy = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.ConstantFluidMaxPackets = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.ConstantFluidMaxParticlesPerStep = v; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.ImprovedSpringSolver = v; } ////////////////////////////////////////////////////////////////////////// pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); isInCMO = chunk->ReadInt(); XString host = chunk->ReadString(); if (isInCMO) { dbgSetup.mHost = host; } isInCMO = chunk->ReadInt(); int port = chunk->ReadInt(); if (isInCMO) { dbgSetup.port= port; } isInCMO = chunk->ReadInt(); int enabled = chunk->ReadInt(); if (isInCMO) { dbgSetup.enabled= enabled; } ////////////////////////////////////////////////////////////////////////// isInCMO = chunk->ReadInt(); int val = chunk->ReadInt(); if (isInCMO==1 && val >=-1000 ) { _LogErrors=val; } if (isInCMO==0) { _LogErrors=1; } isInCMO = chunk->ReadInt(); val = chunk->ReadInt(); if (isInCMO==1 && val >=-1000 ) { _LogInfo=val; } isInCMO = chunk->ReadInt(); val = chunk->ReadInt(); if (isInCMO==1&& val >=-1000) { _LogTrace=val; } isInCMO = chunk->ReadInt(); val = chunk->ReadInt(); if (isInCMO==1&& val >=-1000 ) { _LogWarnings=val; } _loadUserEnumeration(chunk,LoadedFile); isInCMO = chunk->ReadInt(); val = chunk->ReadInt(); if (isInCMO==1&& val >=-1000 ) { _LogToConsole=val; } isInCMO = chunk->ReadInt(); v = chunk->ReadFloat(); if (isInCMO) { p.disablePhysics = v; } chunk->CloseChunk(); //disable physics } return CK_OK; } void PhysicManager::_saveUserEnumeration(CKStateChunk *chunk,CKFile* SavedFile) { ////////////////////////////////////////////////////////////////////////// //write a identifier, just to ensure due the load we are at right seek point ! chunk->WriteInt(PMANAGER_USER_ENUM_IDENTIFIER); /////////////////////////////////////////////////////////////////////////// //write out the the user enumeration for pWDominanceGroups XString enumDescription = getEnumDescription(m_Context->GetParameterManager(),VTE_PHYSIC_DOMINANCE_GROUP); XString enumDescriptionCollGroup = getEnumDescription(m_Context->GetParameterManager(),VTE_PHYSIC_BODY_COLL_GROUP); XString errString; errString.Format("Writing dominance enum :%s",enumDescription.Str()); //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.CStr()); chunk->WriteString(enumDescription.CStr()); chunk->WriteString(enumDescriptionCollGroup.CStr()); } void PhysicManager::_loadUserEnumeration(CKStateChunk *chunk,CKFile* LoadedFile) { int enumIdentfier = chunk->ReadInt(); if (enumIdentfier!=PMANAGER_USER_ENUM_IDENTIFIER) return; CKParameterManager *pm = m_Context->GetParameterManager(); ////////////////////////////////////////////////////////////////////////// //we read our dominance group enumeration back : XString dominanceGroupEnumerationString; int strEnumDescSizeDG = chunk->ReadString(dominanceGroupEnumerationString); XString collisionGroupEnumerationString; int strEnumDescSizeCG = chunk->ReadString(collisionGroupEnumerationString); XString errString; errString.Format("Loading dominance enum :%s",dominanceGroupEnumerationString.Str()); //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,dominanceGroupEnumerationString.CStr()); CKParameterType pType = pm->ParameterGuidToType(VTE_PHYSIC_DOMINANCE_GROUP); if (pType!=-1 && dominanceGroupEnumerationString.Length()) { pm->ChangeEnumDeclaration(VTE_PHYSIC_DOMINANCE_GROUP,dominanceGroupEnumerationString.Str()); } //---------------------------------------------------------------- // // collision group // pType = pm->ParameterGuidToType(VTE_PHYSIC_BODY_COLL_GROUP); if (pType!=-1 && collisionGroupEnumerationString.Length()) { XString enumDescriptionCollGroup = getEnumDescription(m_Context->GetParameterManager(),VTE_PHYSIC_BODY_COLL_GROUP); pm->ChangeEnumDeclaration(VTE_PHYSIC_BODY_COLL_GROUP,collisionGroupEnumerationString.Str()); //---------------------------------------------------------------- // // // CKEnumStruct *eStruct = pm->GetEnumDescByType(pType); if (eStruct) { int a = eStruct->GetNumEnums(); if (a) { XString enumString = eStruct->GetEnumDescription(0); if (!enumString.Length()) { pm->ChangeEnumDeclaration(VTE_PHYSIC_BODY_COLL_GROUP,enumDescriptionCollGroup.Str()); } } int ab = eStruct->GetNumEnums(); } } } CKERROR PhysicManager::PostSave() { return CK_OK; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" //#include "pVehicle.h" void PhysicManager::_RegisterVSLJoint() { STARTVSLBIND(m_Context) STOPVSLBIND } /* void __newvtWorldSettings(BYTE *iAdd) { new (iAdd) pWorldSettings(); } void __newvtSleepingSettings(BYTE *iAdd) { new (iAdd) pSleepingSettings(); } void __newvtJointSettings(BYTE *iAdd) { new (iAdd) pJointSettings(); } int TestWS(pWorldSettings pWS) { VxVector grav = pWS.Gravity(); return 2; } pFactory* GetPFactory(); pFactory* GetPFactory() { return pFactory::Instance(); } extern pRigidBody*getBody(CK3dEntity*ent); */<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorJSetD6Decl(); CKERROR CreateJSetD6Proto(CKBehaviorPrototype **pproto); int JSetD6(const CKBehaviorContext& behcontext); CKERROR JSetD6CB(const CKBehaviorContext& behcontext); enum bInputs { bbI_BodyA=0, bbI_BodyB, bbI_Anchor, bbI_AnchorRef, bbI_Axis, bbI_AxisRef, bbI_Coll, bbI_PMode, bbI_PDistance, bbI_PAngle }; //************************************ // Method: FillBehaviorJSetD6Decl // FullName: FillBehaviorJSetD6Decl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorJSetD6Decl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6"); od->SetCategory("Physic/D6"); od->SetDescription("Sets or modifies a D6 joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7456331,0xc6c58d6)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJSetD6Proto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreateJSetD6Proto // FullName: CreateJSetD6Proto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreateJSetD6Proto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PJD6 <br> PJD6 is categorized in \ref Joints <br> <br>See <A HREF="PJD6.cmo">PJD6.cmo</A>. <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Creates or modifies a D6 joint. <br> <br> DOFs removed: 0-6<br> DOFs remaining: 0-6<br> <br> <br> This joint type can be configured to model nearly any joint imaginable. Each degree of freedom - both linear and angular - can be selectively locked or freed, and separate limits can be applied to each. The 6 DOF joint provides motor drive on all axes independently, and also allows soft limits. The joint axis (localAxis[]) defines the joint's local x-axis. The joint normal (localNormal[]) defines the joint's local y-axis. The local z-axis is computed as a cross product of the first two. When constraining the angular motion of the joint, rotation around the x-axis is referred to as twist, rotation around the y-axis as swing1, and rotation around the z-axis as swing2. \image html 6dofaxis.png <h3>Technical Information</h3> \image html PJD6.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Body B: </SPAN>The second body. Leave blank to create a joint constraint with the world. <BR> <BR> <hr> <SPAN CLASS="pin">Anchor:</SPAN>A point in world space coordinates. See pJointD6::setGlobalAnchor(). <BR> <SPAN CLASS="pin">Anchor Reference: </SPAN>A helper entity to transform a local anchor into the world space. <BR> <hr> <SPAN CLASS="pin">Axis: </SPAN>An in world space. See pJointD6::setGlobalAxis(). <BR> <SPAN CLASS="pin">Axis Up Reference: </SPAN>A helper entity to transform a local axis into the world space. <BR> <BR> <hr> <SPAN CLASS="pin">Collision: </SPAN>Enable Collision. See pJointD6::enableCollision(). <BR> <hr> <SPAN CLASS="pin">Projection Mode: </SPAN>Joint projection mode. See pJointD6::setProjectionMode() and #ProjectionMode. <BR> <SPAN CLASS="pin">Projection Distance: </SPAN>If any joint projection is used, it is also necessary to set projectionDistance to a small value greater than zero. When the joint error is larger than projectionDistance the SDK will change it so that the joint error is equal to projectionDistance. Setting projectionDistance too small will introduce unwanted oscillations into the simulation.See pJointD6::setProjectionDistance(). <br> <SPAN CLASS="pin">Projection Angle: </SPAN>Angle must be greater than 0.02f .If its smaller then current algo gets too close to a singularity. See pJointD6::setProjectionAngle(). <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>VSL : Creation </h3><br> <SPAN CLASS="NiceCode"> \include D6Creation.vsl </SPAN> <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createD6Joint().<br> */ proto->SetBehaviorCallbackFct( JSetD6CB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Anchor",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY,"0.0f"); proto->DeclareInParameter("Axis",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Collision",CKPGUID_BOOL,"TRUE"); proto->DeclareInParameter("Projection Mode",VTE_JOINT_PROJECTION_MODE,"0"); proto->DeclareInParameter("Projection Distance",CKPGUID_FLOAT,"0"); proto->DeclareInParameter("Projection Angle",CKPGUID_FLOAT,"0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(JSetD6); *pproto = proto; return CK_OK; } //************************************ // Method: JSetD6 // FullName: JSetD6 // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int JSetD6(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); if(bodyA || bodyB) { pJointD6 *joint =static_cast<pJointD6*>(worldA->getJoint(target,targetB,JT_D6)); //anchor : VxVector anchor = GetInputParameterValue<VxVector>(beh,1); VxVector anchorOut = anchor; CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(2); if (anchorReference) { anchorReference->Transform(&anchorOut,&anchor); } //axis VxVector axis = GetInputParameterValue<VxVector>(beh,3); VxVector axisOut = axis; CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(4); if (axisReference) { VxVector dir,up,right; axisReference->GetOrientation(&dir,&up,&right); axisReference->TransformVector(&axisOut,&up); } int coll = GetInputParameterValue<int>(beh,bbI_Coll); ProjectionMode mode =GetInputParameterValue<ProjectionMode>(beh,bbI_PMode); float distance = GetInputParameterValue<float>(beh,bbI_PDistance); float angle= GetInputParameterValue<float>(beh,bbI_PAngle); if (!joint) { joint = static_cast<pJointD6*>(pFactory::Instance()->createD6Joint(target,targetB,anchorOut,axisOut,coll)); } ////////////////////////////////////////////////////////////////////////// //joints parameters : //set it up : if (joint) { joint->setGlobalAnchor(anchorOut); joint->setGlobalAxis(axisOut); joint->enableCollision(coll); if (mode != 0) { joint->setProjectionMode(mode); joint->setProjectionDistance(distance); joint->setProjectionAngle(angle); } } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: JSetD6CB // FullName: JSetD6CB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR JSetD6CB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD fmax; beh->GetLocalParameterValue(0,&fmax); if (fmax ) { beh->EnableInputParameter(6,fmax); beh->EnableInputParameter(7,fmax); }else { beh->EnableInputParameter(6,fmax); beh->EnableInputParameter(7,fmax); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (target && targetB) { // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) return CKBR_OK; // the physic object A and B : pRigidBody*bodyA= world->getBody(target); pRigidBody*bodyB= world->getBody(targetB); if(bodyA && bodyB) { // pJointHinge2 *joint = static_cast<pJointHinge2*>(bodyA->isConnected(targetB)); /* if (joint && joint->GetFeedBack()) { joint->SetFeedBack(NULL,0,0); }*/ } } } } break; } return CKBR_OK; } <file_sep>#ifndef __P_VEHICLE_MOTOR_H__ #define __P_VEHICLE_MOTOR_H__ #include "vtPhysXBase.h" #include "pVehicleTypes.h" #include "pDriveline.h" #include "pEngine.h" /** \addtogroup Vehicle @{ */ class MODULE_API pVehicleMotorDesc { public: pLinearInterpolation torqueCurve; float maxRpmToGearUp; float minRpmToGearDown; float maxRpm; float minRpm; void setToDefault(); pVehicleMotorDesc() { setToDefault(); } void setToCorvette(); bool isValid() const; }; class MODULE_API pVehicleMotor { public: pLinearInterpolation _torqueCurve; float _rpm; float getMaxTorquePos() const { return _maxTorquePos; } void setMaxTorquePos(float val) { _maxTorquePos = val; } float getMaxRpmToGearUp() const { return _maxRpmToGearUp; } void setMaxRpmToGearUp(float val) { _maxRpmToGearUp = val; } float getMinRpmToGearDown() const { return _minRpmToGearDown; } void setMinRpmToGearDown(float val) { _minRpmToGearDown = val; } float getMaxTorque() const { return _maxTorque; } void setMaxTorque(float val) { _maxTorque = val; } float _maxTorquePos; float _maxTorque; float _maxRpm; float _minRpm; float _minRpmToGearDown; float _maxRpmToGearUp; pVehicleMotor() : _rpm(0) { } void setMaxRpm(float val) { _maxRpm = val; } void setMinRpm(float val) { _minRpm = val; } void setRpm(float rpm) { _rpm = rpm; } float getRpm() const { return _rpm; } float getMinRpm() const { return _minRpm; } float getMaxRpm() const { return _maxRpm; } int changeGears(const pVehicleGears* gears, float threshold) const; float getTorque() const { return _torqueCurve.getValue(_rpm); } int loadNewTorqueCurve(pLinearInterpolation newTCurve); int reload(pVehicleMotorDesc* descr); }; /** @} */ #endif<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorDebugTextDecl(); CKERROR CreateDebugTextProto(CKBehaviorPrototype **pproto); int DebugText(const CKBehaviorContext& behcontext); CKERROR DebugTextCallBackObject(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorDebugTextDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DebugText"); od->SetDescription("Displays a text on console"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x37852d34,0x27a84a90)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00020000); od->SetCreationFunction(CreateDebugTextProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("TNL/Misc"); return od; } CKERROR CreateDebugTextProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("DebugText"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareOutput("Exit On"); proto->DeclareInParameter("Component", CKPGUID_INT); proto->DeclareInParameter("Level", CKPGUID_INT); proto->DeclareInParameter("Text", CKPGUID_STRING); proto->DeclareOutParameter("Text", CKPGUID_STRING); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(DebugText); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_VARIABLEPARAMETERINPUTS)); proto->SetBehaviorCallbackFct(DebugTextCallBackObject); *pproto = proto; return CK_OK; } int DebugText(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; int component=-1; beh->GetInputParameterValue(0,&component); int level=-1; beh->GetInputParameterValue(1,&level); CKParameterIn* pin; CKParameter* pout; XString buffer; // we construct the string int pinc = beh->GetInputParameterCount(); for(int i=2;i<pinc;i++) { pin = beh->GetInputParameter(i); pout = pin->GetRealSource(); if(pout) { int paramsize = pout->GetStringValue(NULL); if (paramsize) { XAP<char> paramstring(new char[paramsize]); pout->GetStringValue(paramstring,FALSE); buffer << (char*)paramstring; buffer << " "; } } } using namespace vtTools::BehaviorTools; SetOutputParameterValue<CKSTRING>(beh,0,buffer.Str()); xLogger::xLog(level,component,"Dbg %s",buffer.CStr()); beh->ActivateOutput(0); return 0; } CKERROR DebugTextCallBackObject(const CKBehaviorContext& behcontext) { return 0; } <file_sep>#include "stdafx2.h" #include "vtAgeiaInterfaceeditor.h" #include "vtAgeiaInterfaceMenu.h" //declaration of menu callback (for InitMenu function) void PluginMenuCallback(int commandID); //static main menu CMenu* s_MainMenu = NULL; #define PLUGINMENU_MAXENTRIES 20 //put there the max entries your menu may use //adds the menu to Virtools Dev main menu void InitMenu() { if (!s_Plugininterface) return; s_MainMenu = s_Plugininterface->AddPluginMenu(STR_MAINMENUNAME,PLUGINMENU_MAXENTRIES,NULL,(VoidFunc1Param)PluginMenuCallback); } //removes the menu from Virtools Dev main menu void RemoveMenu() { if (!s_Plugininterface || !s_MainMenu) return; s_Plugininterface->RemovePluginMenu(s_MainMenu); } //up to user. //(May be called on new composition notification for instance) //Note that first commandID can be 0 //but last command ID must be lesser thanPLUGINMENU_MAXENTRIES void UpdateMenu() { s_Plugininterface->ClearPluginMenu(s_MainMenu); //clear menu s_Plugininterface->AddPluginMenuItem(s_MainMenu,0,"item0"); //add simple item sample s_Plugininterface->AddPluginMenuItem(s_MainMenu,1,"item1"); //add simple item sample s_Plugininterface->AddPluginMenuItem(s_MainMenu,-1,NULL,TRUE); //add separator sample CMenu* sub0 = s_Plugininterface->AddPluginMenuItem(s_MainMenu,2,"SubMenu0",FALSE,TRUE); //sub menu sample CMenu* sub1 = s_Plugininterface->AddPluginMenuItem(s_MainMenu,3,"SubMenu1",FALSE,TRUE); //sub menu sample s_Plugininterface->AddPluginMenuItem(sub0,4,"item2"); //add simple item to sub menu sample s_Plugininterface->AddPluginMenuItem(sub0,5,"item3"); //add simple item to sub menu sample s_Plugininterface->AddPluginMenuItem(sub1,6,"item4"); //add simple item to sub menu sample s_Plugininterface->AddPluginMenuItem(sub1,7,"item5"); //add simple item to sub menu sample s_Plugininterface->UpdatePluginMenu(s_MainMenu); //update menu,always needed when you finished to update the menu //unless you want the menu not to have Virtools Dev main menu color scheme. } //fill with your command IDs and your actions void PluginMenuCallback(int commandID) { /*switch(commandID) { }*/ } <file_sep>// // Cameras.cpp : Defines the initialization routines for the DLL. // #include "CKAll.h" #ifdef CK_LIB #define RegisterBehaviorDeclarations Register_Cameras_BehaviorDeclarations #define InitInstance _Cameras_InitInstance #define ExitInstance _Cameras_ExitInstance #define CKGetPluginInfoCount CKGet_Cameras_PluginInfoCount #define CKGetPluginInfo CKGet_Cameras_PluginInfo #define g_PluginInfo g_Cameras_PluginInfo #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #endif CKERROR InitInstance(CKContext* context); CKERROR ExitInstance(CKContext* context); PLUGIN_EXPORT void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg); #define CAMERA_BEHAVIOR CKGUID(0x12d94eba,0x47057415) #define CKPGUID_PROJECTIONTYPE CKDEFINEGUID(0x1ee22148, 0x602c1ca1) CKPluginInfo g_PluginInfo; PLUGIN_EXPORT int CKGetPluginInfoCount() { return 1; } PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) { g_PluginInfo.m_Author = "Virtools"; g_PluginInfo.m_Description = "Camera building blocks"; g_PluginInfo.m_Extension = ""; g_PluginInfo.m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo.m_Version = 0x000001; g_PluginInfo.m_InitInstanceFct = InitInstance; g_PluginInfo.m_ExitInstanceFct = ExitInstance; g_PluginInfo.m_GUID = CAMERA_BEHAVIOR; g_PluginInfo.m_Summary = "Cameras"; return &g_PluginInfo; } /**********************************************************************************/ /**********************************************************************************/ CKERROR InitInstance(CKContext* context) { CKParameterManager* pm = context->GetParameterManager(); pm->RegisterNewEnum( CKPGUID_PROJECTIONTYPE,"Projection Mode","Perspective=1,Orthographic=2" ); // Mouse Camera Orbit #define CKPGUID_MOUSEBUTTON CKGUID(0x1ff24d5a,0x122f2c1f) pm->RegisterNewEnum(CKPGUID_MOUSEBUTTON,"Mouse Button","Left=0,Middle=2,Right=1" ); return CK_OK; } CKERROR ExitInstance(CKContext* context) { CKParameterManager* pm = context->GetParameterManager(); pm->UnRegisterParameterType(CKPGUID_PROJECTIONTYPE); pm->UnRegisterParameterType(CKPGUID_MOUSEBUTTON); return CK_OK; } void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) { // Cameras/Basic RegisterBehavior(reg, FillBehaviorDollyDecl); RegisterBehavior(reg, FillBehaviorSetOrthographicZoomDecl); RegisterBehavior(reg, FillBehaviorSetCameraTargetDecl); RegisterBehavior(reg, FillBehaviorSetClippingDecl); RegisterBehavior(reg, FillBehaviorSetFOVDecl); RegisterBehavior(reg, FillBehaviorSetProjectionDecl); RegisterBehavior(reg, FillBehaviorSetZoomDecl); // Cameras/FX RegisterBehavior(reg, FillBehaviorCameraColorFilterDecl); RegisterBehavior(reg, FillBehaviorVertigoDecl); // Cameras/Montage RegisterBehavior(reg, FillBehaviorGetCurrentCameraDecl); RegisterBehavior(reg, FillBehaviorSetAsActiveCameraDecl); // Cameras/Movement RegisterBehavior(reg, FillBehaviorOrbitDecl); RegisterBehavior(reg, FillBehaviorKeyboardCameraOrbitDecl); RegisterBehavior(reg, FillBehaviorMouseCameraOrbitDecl); RegisterBehavior(reg, FillBehaviorJoystickCameraOrbitDecl); RegisterBehavior(reg, FillBehaviorGenericCameraOrbitDecl); } <file_sep>#ifndef __PLOGGER_H__ #define __PLOGGER_H__ #include "pTypes.h" class pLogger { public: pLogger(); ~pLogger(); pErrorStream * getErrorStream() const { return mErrorStream; } void setErrorStream(pErrorStream * val) { mErrorStream = val; } protected: pErrorStream *mErrorStream; }; #endif<file_sep>#include <Python.h> #ifndef __VT_PYTHON_EXT_H_ #define __VT_PYTHON_EXT_H_ PyObject* log_CaptureStdout(PyObject* self, PyObject* pArgs); PyObject* log_CaptureStderr(PyObject* self, PyObject* pArgs); #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBSetTriggerMaskDecl(); CKERROR CreatePBSetTriggerMaskProto(CKBehaviorPrototype **pproto); int PBSetTriggerMask(const CKBehaviorContext& behcontext); CKERROR PBSetTriggerMaskCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_OnEnter, bbI_OnStay, bbI_OnLeave, }; //************************************ // Method: FillBehaviorPBSetTriggerMaskDecl // FullName: FillBehaviorPBSetTriggerMaskDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPBSetTriggerMaskDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PCSetTriggerMask"); od->SetCategory("Physic/Collision"); od->SetDescription("Modifies trigger mask"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x27ae51d4,0x45bf2c6c)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBSetTriggerMaskProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBSetTriggerMaskProto // FullName: CreatePBSetTriggerMaskProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBSetTriggerMaskProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCSetTriggerMask"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PCSetTriggerMask PCSetTriggerMask is categorized in \ref Collision <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies the trigger mask of a bodies or a sub shape of it.<br> See <A HREF="pBTriggerEvent.cmo">pBTriggerEvent.cmo</A> for example. <h3>Technical Information</h3> \image html PBSetTriggerMask.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The shape reference. Can be a sub shape or the initial mesh. <BR> <BR> <SPAN CLASS="pin">On Enter: </SPAN>Enables triggering if the body starts entering another shape. <BR> <SPAN CLASS="pin">On Stay: </SPAN>Enables triggering if the body stays in another shape. <BR> <SPAN CLASS="pin">On Leave: </SPAN>Enables triggering if the body leaves another shape. <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PCSetTriggerMask.cpp </SPAN> */ proto->SetBehaviorCallbackFct( PBSetTriggerMaskCB ); proto->DeclareInParameter("On Enter",CKPGUID_BOOL,"true"); proto->DeclareInParameter("On Stay",CKPGUID_BOOL,"true"); proto->DeclareInParameter("On Leave",CKPGUID_BOOL,"true"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBSetTriggerMask); *pproto = proto; return CK_OK; } //************************************ // Method: PBSetTriggerMask // FullName: PBSetTriggerMask // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBSetTriggerMask(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world = GetPMan()->getWorldByShapeReference(target); if (!world) { beh->ActivateOutput(0); return 0; } if (world) { NxShape *shape = world->getShapeByEntityID(target->GetID()); if (shape) { int onEnter = GetInputParameterValue<int>(beh,bbI_OnEnter); int onStay = GetInputParameterValue<int>(beh,bbI_OnStay); int onLeave = GetInputParameterValue<int>(beh,bbI_OnLeave); shape->setFlag(NX_TRIGGER_ON_ENTER,onEnter); shape->setFlag(NX_TRIGGER_ON_STAY,onStay); shape->setFlag(NX_TRIGGER_ON_LEAVE,onLeave); } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: PBSetTriggerMaskCB // FullName: PBSetTriggerMaskCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBSetTriggerMaskCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// struct clist2 { CK3dEntity *part; CK3dEntity *obstacle; CK3dEntity *sub_obstacle; VxVector pos; VxVector normal; float depth; clist2(CK3dEntity* p , CK3dEntity *o,CK3dEntity*so, VxVector po, VxVector n , float d ) : part(p) , obstacle(o), sub_obstacle(so), pos(po) , normal (n) , depth (d){} }; <file_sep>#include <StdAfx.h> #include <xAssertion.h> #include <xAssertCustomization.h> #include <xDebugTools.h> #include "vtPhysXBase.h" //#define WASSERT_VERIFY_PREFIX(Condition,bufferSize) xVerifyAndCorrect(Condition) static const xAssertInfo g_fiAssertInvalidInfo(AFS_ASSERT,NULL,NULL, 0 , NULL ,NULL,false); static xAssertInfo g_fiAssertLastInfo; void xCONVENTION_CALLBACK testAssertsAssertionFailure(E_ASSERTION_FAILURE_SEVERITY fsFailureSeverity, char *szAssertionExpression, char *szAssertionFileName, int uiAssertionSourceLine, char *assertionPostMessage, void* postAction, bool result ){ g_fiAssertLastInfo.failureSeverity= fsFailureSeverity; g_fiAssertLastInfo.assertionExpression = szAssertionExpression; g_fiAssertLastInfo.assertionFileName = szAssertionFileName; g_fiAssertLastInfo.assertionSourceLine = uiAssertionSourceLine; g_fiAssertLastInfo.assertionPostMessage = assertionPostMessage; g_fiAssertLastInfo.postAction = postAction; g_fiAssertLastInfo.result = result; } xAssertInfo* assertFailed() { /* if (g_fiAssertLastInfo.assertionExpression == NULL || g_fiAssertLastInfo.assertionFileName == NULL || strcmp(g_fiAssertLastInfo.assertionFileName, __FILE__) != 0 || g_fiAssertLastInfo.assertionSourceLine == 0 || !g_fiAssertLastInfo.result) {*/ if (!g_fiAssertLastInfo.result) { return NULL; } return &g_fiAssertLastInfo; } xAssertInfo *getLastAssertInfo(){ return &g_fiAssertLastInfo; } void xCONVENTION_CALLBACK tickAssertHandlerData() { bool bResult = false; xErrorHandlerFn fnAssertOldHandler = xAssertionEx::getErrorHandler(); xAssertionEx::updateErrorHandler(&updateAssertHandlerData); return; /* do { #if !defined(NDEBUG) // Only callback invocation is checked here. // Availability of functionality depending on preprocessor defines // is verified in OST_ASSERT subsystem. OU_ASSERT(false); // const unsigned int uiAssertToVerifyLines = 14; -- see further in code if (g_fiAssertLastInfo.m_fsFailureSeverity != AFS_ASSERT || g_fiAssertLastInfo.m_szAssertionExpression == NULL || g_fiAssertLastInfo.m_szAssertionFileName == NULL || strcmp(g_fiAssertLastInfo.m_szAssertionFileName, __FILE__) != 0 || g_fiAssertLastInfo.m_uiAssertionSourceLine == 0) { break; } CTestCustomizations_Asserts_FailureInfo fiAssertFailureInfoSave = g_fiAssertLastInfo; g_fiAssertLastInfo = g_fiAssertInvalidInfo; OU_VERIFY(false); const unsigned int uiAssertToVerifyLines = 14; if (g_fiAssertLastInfo.m_fsFailureSeverity != AFS_ASSERT || g_fiAssertLastInfo.m_szAssertionExpression == NULL || strcmp(g_fiAssertLastInfo.m_szAssertionExpression, fiAssertFailureInfoSave.m_szAssertionExpression) != 0 || g_fiAssertLastInfo.m_szAssertionFileName == NULL || strcmp(g_fiAssertLastInfo.m_szAssertionFileName, __FILE__) != 0 || g_fiAssertLastInfo.m_uiAssertionSourceLine != fiAssertFailureInfoSave.m_uiAssertionSourceLine + uiAssertToVerifyLines) { break; } g_fiAssertLastInfo = g_fiAssertInvalidInfo; #endif // #if !defined(NDEBUG) -- can't verify OU_CHECK() as it crashes the application on failure OU_CHECK(false); if (g_fiAssertLastInfo.m_fsFailureSeverity != AFS_CHECK || g_fiAssertLastInfo.m_szAssertionExpression == NULL || g_fiAssertLastInfo.m_szAssertionFileName == NULL || strcmp(g_fiAssertLastInfo.m_szAssertionFileName, __FILE__) != 0 || g_fiAssertLastInfo.m_uiAssertionSourceLine == 0) { break; } bResult = true; } while (false); CAssertionCheckCustomization::CustomizeAssertionChecks(fnAssertOldHandler); return bResult; */ } void xCONVENTION_CALLBACK rotateAssertInfo( E_ASSERTION_FAILURE_SEVERITY failureSeverity, char *assertionExpression, char *assertionFileName, int assertionSourceLine, char *assertionPostMessage, void* postAction, bool result) { g_fiAssertLastInfo.failureSeverity = failureSeverity; g_fiAssertLastInfo.assertionExpression = assertionExpression; g_fiAssertLastInfo.assertionFileName = assertionFileName; g_fiAssertLastInfo.assertionSourceLine = assertionSourceLine; g_fiAssertLastInfo.assertionPostMessage = assertionPostMessage; g_fiAssertLastInfo.postAction = postAction; xErrorHandlerFn fnAssertOldHandler = xAssertionEx::Instance()->getErrorHandler(); xAssertionEx::Instance()->updateErrorHandler(&updateAssertHandlerData); } void xCONVENTION_CALLBACK updateAssertHandlerData( E_ASSERTION_FAILURE_SEVERITY _failureSeverity, char *_assertionExpression, char *_assertionFileName, int _assertionSourceLine, char *_assertionPostMessage, void* _postAction, bool _result) { g_fiAssertLastInfo.failureSeverity = _failureSeverity; g_fiAssertLastInfo.assertionExpression = _assertionExpression; g_fiAssertLastInfo.assertionFileName = _assertionFileName; g_fiAssertLastInfo.assertionSourceLine = _assertionSourceLine; g_fiAssertLastInfo.assertionPostMessage = _assertionPostMessage; g_fiAssertLastInfo.postAction = _postAction; g_fiAssertLastInfo.result = _result; } xAssertInfo createAssertInfo( E_ASSERTION_FAILURE_SEVERITY failureSeverity, char *assertionExpression, char *assertionFileName, int assertionSourceLine, char *assertionPostMessage, void* postAction, bool result) { return xAssertInfo(failureSeverity,assertionExpression,assertionFileName,assertionSourceLine,assertionPostMessage,postAction,result); } bool customizeAsserts() { bool bResult = false; xErrorHandlerFn fnAssertOldHandler = xAssertionEx::getErrorHandler(); xAssertionEx::updateErrorHandler(&testAssertsAssertionFailure); return bResult; } bool TestCustomizations_Asserts() { bool bResult = false; xErrorHandlerFn fnAssertOldHandler = xAssertionEx::getErrorHandler(); xAssertionEx::updateErrorHandler(&testAssertsAssertionFailure); do { // Only callback invocation is checked here. // Availability of functionality depending on preprocessor defines // is verified in OST_ASSERT subsystem. float a = 10; //xAssert(1); // const unsigned int uiAssertToVerifyLines = 14; -- see further in code int test=0; bool resultAssert=false; xAssertW( a < 5,test=10,"reset value",D_SO_NAME,resultAssert); if (g_fiAssertLastInfo.failureSeverity != AFS_ASSERT || g_fiAssertLastInfo.assertionExpression == NULL || g_fiAssertLastInfo.assertionFileName == NULL || strcmp(g_fiAssertLastInfo.assertionFileName, __FILE__) != 0 || g_fiAssertLastInfo.assertionSourceLine == 0) { break; } xAssertInfo fiAssertFailureInfoSave = g_fiAssertLastInfo; xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,fiAssertFailureInfoSave.assertionExpression); g_fiAssertLastInfo = g_fiAssertInvalidInfo; } while (false); xAssertionEx::updateErrorHandler(fnAssertOldHandler); return false; } /* xAssertInfo *last = getLastAssertInfo(); if (last) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,last->assertionExpression); } */ /* xVerify(false); const unsigned int uiAssertToVerifyLines = 14; if (g_fiAssertLastInfo.failureSeverity != AFS_ASSERT || g_fiAssertLastInfo.assertionExpression == NULL || strcmp(g_fiAssertLastInfo.assertionExpression, fiAssertFailureInfoSave.assertionExpression) != 0 || g_fiAssertLastInfo.assertionFileName == NULL || strcmp(g_fiAssertLastInfo.assertionFileName, __FILE__) != 0 || g_fiAssertLastInfo.assertionSourceLine != fiAssertFailureInfoSave.assertionSourceLine + uiAssertToVerifyLines) { break; } */ //g_fiAssertLastInfo = g_fiAssertInvalidInfo; /*xAssertInfo *last = getLastAssertInfo(); if (last) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,last->assertionExpression); }*/ /* #endif //#if !defined(NDEBUG) // -- can't verify OU_CHECK() as it crashes the application on failure //xCheck(false); /* if (g_fiAssertLastInfo.failureSeverity != AFS_CHECK || g_fiAssertLastInfo.assertionExpression == NULL || g_fiAssertLastInfo.assertionFileName == NULL || strcmp(g_fiAssertLastInfo.assertionFileName, __FILE__) != 0 || g_fiAssertLastInfo.assertionSourceLine == 0) { break; }*/<file_sep>#ifndef __VTMODULE_ERROR_CODES_H__ #define __VTMODULE_ERROR_CODES_H__ /*! * \brief * Error codes to identifier common errors in the SDK with automatic * string conversion for building blocks */ typedef enum E_BB_ERRORS { E_PE_NONE, E_PE_INTERN, E_PE_PAR, E_PE_REF, E_PE_XML, E_PE_FILE, E_PE_NoBody, E_PE_NoVeh, E_PE_NoWheel, E_PE_NoJoint, E_PE_NoCloth, E_PE_NoSDK, }; #endif // __VTMODULEERRORCODES_H__<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "tinyxml.h" static const TiXmlElement *getFirstOdeElement(const TiXmlElement *root); static const TiXmlElement *getFirstOdeElement(const TiXmlElement *root) { // should have some recursive algo if (!strcmp(root->Value(), "vtPhysics")) { return root; } for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling()) { if (child->Type() == TiXmlNode::ELEMENT) { const TiXmlElement *res = getFirstOdeElement(child->ToElement ()); if (res) return res; } } return 0; } TiXmlDocument* PhysicManager::loadDefaults(XString filename) { // load and check file char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,filename.CStr()); XString name(Ini); name << '\0'; m_DefaultDocument = new TiXmlDocument(filename.Str()); m_DefaultDocument ->LoadFile(Ini); m_DefaultDocument ->Parse(Ini); if (m_DefaultDocument->Error()) { //xLogger::xLog("couldn't load default document"); delete m_DefaultDocument; m_DefaultDocument = NULL; return NULL; } // get the ogreode element. TiXmlNode* node = m_DefaultDocument->FirstChild( "vtPhysics" ); if (!node) { //Ogre::LogManager::getSingleton().logMessage(" cannot find ogreode root in XML file!"); return NULL; } return m_DefaultDocument; }<file_sep>#ifndef __MEMORY_FILE_MAPPING_TYPES_H__ #define __MEMORY_FILE_MAPPING_TYPES_H__ enum vtEventState { EEVT_STARTED, EEVT_FINISHED }; struct vtExternalEvent { unsigned long timeOfCreation; char command[MAX_PATH]; char commandArg[MAX_PATH]; vtEventState state; }; #endif<file_sep>/****************************************************************************** File : CustomPlayer.cpp Description: This file contains the CCustomPlayer class which is the "interface" with the Virtools SDK. All other files are Windows/MFC specific code. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ #include "CPStdAfx.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" CKMessageType GetMessageByString(const char *msg) { CKMessageManager *mm = GetPlayer().m_MessageManager; for (int i = 0 ; i < mm->GetMessageTypeCount() ; i++) { if (!strcmp(mm->GetMessageTypeName(i),msg) ) { return i; } } return -1; } //************************************ // Method: SendMessage // FullName: CCustomPlayer::SendMessage // Access: public // Returns: int // Qualifier: // Parameter: char *targetObject // Parameter: char *message // Parameter: int id0 // Parameter: int id1 // Parameter: int id2 // Parameter: int value //************************************ int CCustomPlayer::SendMessage(char *targetObject,char *message,int id0,int id1,int id2,int value) { CKContext *ctx = m_CKContext; CKLevel *level = ctx->GetCurrentLevel(); CKMessageManager *mm = GetPlayer().m_MessageManager; CKBeObject *obj = static_cast<CKBeObject*>(ctx->GetObjectByName(targetObject)); CKMessageType mType = GetMessageByString(message); if (level && mType) { if (mType) { CKMessage *msg = NULL; //no target object specified, we send a broadcast message : if (!obj) { msg = mm->SendMessageBroadcast(mType,CKCID_BEOBJECT,level); if(!msg) return -1; }//target object ok, we send a single message : else { msg = mm->SendMessageSingle(mType,obj,level); if(!msg) return -1; } ////////////////////////////////////////////////////////////////////////// // we attach our arguments as parameters : //id0 CKParameter *parameter0 = ctx->CreateCKParameterLocal("msg0",CKPGUID_INT,FALSE); parameter0->SetValue(&id0);msg->AddParameter(parameter0,true); //id1 CKParameter *parameter1 = ctx->CreateCKParameterLocal("msg1",CKPGUID_INT,FALSE); parameter1->SetValue(&id1); msg->AddParameter(parameter1,true); //id2 CKParameter *parameter2 = ctx->CreateCKParameterLocal("msg2",CKPGUID_INT,FALSE); parameter2->SetValue(&id2);msg->AddParameter(parameter2,true); //the value : CKParameter *valuex= ctx->CreateCKParameterLocal("msgValue",CKPGUID_INT,FALSE); valuex->SetValue(&value);msg->AddParameter(valuex,true); return 1; } } return -1; } //************************************ // Method: SendMessage // FullName: CCustomPlayer::SendMessage // Access: public // Returns: int // Qualifier: // Parameter: char *targetObject // Parameter: char *message // Parameter: int id0 // Parameter: int id1 // Parameter: int id2 // Parameter: int value //************************************ int CCustomPlayer::SendMessage(char *targetObject,char *message,int id0,int id1,int id2,float value) { CKContext *ctx = m_CKContext; CKLevel *level = ctx->GetCurrentLevel(); CKMessageManager *mm = GetPlayer().m_MessageManager; CKBeObject *obj = static_cast<CKBeObject*>(ctx->GetObjectByName(targetObject)); CKMessageType mType = GetMessageByString(message); if (level && mType) { if (mType) { CKMessage *msg = NULL; //no target object specified, we send a broadcast message : if (!obj) { msg = mm->SendMessageBroadcast(mType,CKCID_BEOBJECT,level); if(!msg) return -1; }//target object ok, we send a single message : else { msg = mm->SendMessageSingle(mType,obj,level); if(!msg) return -1; } ////////////////////////////////////////////////////////////////////////// // we attach our arguments as parameters : //id0 CKParameter *parameter0 = ctx->CreateCKParameterLocal("msg0",CKPGUID_INT,FALSE); parameter0->SetValue(&id0);msg->AddParameter(parameter0,true); //id1 CKParameter *parameter1 = ctx->CreateCKParameterLocal("msg1",CKPGUID_INT,FALSE); parameter1->SetValue(&id1); msg->AddParameter(parameter1,true); //id2 CKParameter *parameter2 = ctx->CreateCKParameterLocal("msg2",CKPGUID_INT,FALSE); parameter2->SetValue(&id2);msg->AddParameter(parameter2,true); //the value : CKParameter *valuex= ctx->CreateCKParameterLocal("msgValue",CKPGUID_FLOAT,FALSE); valuex->SetValue(&value);msg->AddParameter(valuex,true); return 1; } } return -1; } int CCustomPlayer::SendMessage(char *targetObject,char *message,int id0,int id1,int id2,char* value) { CKContext *ctx = m_CKContext; CKLevel *level = ctx->GetCurrentLevel(); CKMessageManager *mm = GetPlayer().m_MessageManager; CKBeObject *obj = static_cast<CKBeObject*>(ctx->GetObjectByName(targetObject)); CKMessageType mType = GetMessageByString(message); if (level && mType) { if (mType) { CKMessage *msg = NULL; //no target object specified, we send a broadcast message : if (!obj) { msg = mm->SendMessageBroadcast(mType,CKCID_BEOBJECT,level); if(!msg) return -1; }//target object ok, we send a single message : else { msg = mm->SendMessageSingle(mType,obj,level); if(!msg) return -1; } ////////////////////////////////////////////////////////////////////////// // we attach our arguments as parameters : //id0 CKParameter *parameter0 = ctx->CreateCKParameterLocal("msg0",CKPGUID_INT,FALSE); parameter0->SetValue(&id0);msg->AddParameter(parameter0,true); //id1 CKParameter *parameter1 = ctx->CreateCKParameterLocal("msg1",CKPGUID_INT,FALSE); parameter1->SetValue(&id1); msg->AddParameter(parameter1,true); //id2 CKParameter *parameter2 = ctx->CreateCKParameterLocal("msg2",CKPGUID_INT,FALSE); parameter2->SetValue(&id2);msg->AddParameter(parameter2,true); //the value : CKParameter *valuex= ctx->CreateCKParameterLocal("msgValue",CKPGUID_STRING,FALSE); valuex->SetStringValue(value);msg->AddParameter(valuex,true); return 1; } } return -1; } <file_sep>#include <base.h> #include <sstream> #include <iostream> std::ostream& base::_Debug = std::cerr; std::ostream& base::_Log = std::cout; std::ostream& base::_Console = std::cout; #ifdef DEBUG bool _outputExceptionOnConstruction = true; bool _abortOnAssertionFailure = false; #endif /* String base::intToString(Int i) { std::ostringstream oss; oss << i; return oss.str(); } Int base::stringToInt(const String& s) { std::istringstream iss(s); Int v; iss >> v; return v; } Real base::stringToReal(const String& s) { std::istringstream iss(s); Real v; iss >> v; return v; } String base::realToString(Real r) { std::ostringstream oss; oss << r; return oss.str(); } */ <file_sep>// racer/pacejka.h #ifndef __P_PACEJKA_H__ #define __P_PACEJKA_H__ #include "vtPhysXBase.h" #define RR_RAD_DEG_FACTOR 57.29578f // From radians to degrees" #define RR_RAD2DEG 57.29578f // A bit more descriptive #ifndef PI #define PI 3.14159265358979f #endif // Near-zero definitions #define RR_EPSILON_VELOCITY 0.001 // Wheel velocity class MODULE_API pPacejka // A Pacejka calculation engine // Uses SAE axis system for reference // (SAE X=Racer Z, SAE Y=Racer X, SAE Z=Racer -Y) { public: // Fx longitudinal force float a0,a1,a2,a3,a4,a5,a6,a7,a8, a9,a10,a111,a112,a12,a13; // Fy lateral force float b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10; // Mz aligning moment float c0,c1,c2,c3,c4,c5,c6, c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17; protected: // Input parameters float camber, // Angle of tire vs. surface (in degrees!) sideSlip, // Slip angle (in degrees!) slipPercentage, // Percentage slip ratio (in %) Fz; // Normal force (in kN!) // Output float Fx,Fy,Mz; // Longitudinal/lateral/aligning moment float longStiffness, // Longitudinal tire stiffness latStiffness; // Lateral or cornering stiffness VxVector maxForce; // Max. available tire force (friction ellipse) public: pPacejka(); ~pPacejka(); void setToDefault(); // Attribs void SetCamber(float _camber){ camber=_camber*RR_RAD2DEG; } void SetSlipAngle(float sa){ sideSlip=sa*RR_RAD2DEG; } void SetSlipRatio(float sr){ slipPercentage=sr*100.0f; } void SetNormalForce(float force){ Fz=force/1000.0f; } // Physics void Calculate(); protected: float CalcFx(); float CalcFy(); float CalcMz(); public: float GetFx(){ return Fx; } float GetFy(){ return Fy; } float GetMz(){ return Mz; } // Adjust (used in combined slip) void SetFx(float v){ Fx=v; } void SetFy(float v){ Fy=v; } void SetMz(float v){ Mz=v; } // Extras float GetMaxLongForce(){ return maxForce.x; } float GetMaxLatForce(){ return maxForce.y; } // Adjust (used for surface and quick-adjust modifications) void SetMaxLongForce(float v){ maxForce.x=v; } void SetMaxLatForce(float v){ maxForce.x=v; } float GetLongitudinalStiffness(){ return longStiffness; } float GetCorneringStiffness(){ return latStiffness; } }; #endif <file_sep>#ifndef __IDistributedClasses_h_ #define __IDistributedClasses_h_ #include "xNetTypes.h" class xNetInterface; class IDistributedClasses { public: IDistributedClasses(xNetInterface *netInterface); virtual ~IDistributedClasses(); xDistributedClassesArrayType* getDistrutedClassesPtr(); xDistributedClass *createClass(const char* name,int templatetype); xDistributedClass *get(const char* name); xDistributedClass *get(const char* name,int entityType); xDistributedClass *getByIndex(int index); int getNumClasses(); int destroyClass(xDistributedClass* _class); virtual void destroy(); xNetInterface*getNetInterface(); void setNetInterface(xNetInterface*netInterface); void deployClass(xDistributedClass*_class); private: //TNL::SafePtr<xNetInterface>m_NetInterface; xNetInterface *m_NetInterface; xDistributedClassesArrayType *m_DistrutedClasses; }; #endif <file_sep>#ifndef __xDistributedString_H #define __xDistributedString_H #include "xDistributedProperty.h" class xDistributedString : public xDistributedProperty { public: typedef xDistributedProperty Parent; xDistributedString ( xDistributedPropertyInfo *propInfo, xTimeType maxWriteInterval, xTimeType maxHistoryTime ) : xDistributedProperty(propInfo) { mLastTime = 0; mCurrentTime = 0; mLastDeltaTime = 0 ; mFlags = 0; mThresoldTicker = 0; mLastValue = xNString(""); mCurrentValue = xNString(""); } ~xDistributedString(){} xNString mLastValue; xNString mCurrentValue; bool updateValue(xNString value,xTimeType currentTime); void pack(xNStream *bstream); void unpack(xNStream *bstream,float sendersOneWayTime); void updateGhostValue(xNStream *stream); void updateFromServer(xNStream *stream); virtual uxString print(TNL::BitSet32 flags); }; #endif <file_sep>#ifndef NX_VEHICLE_DESC #define NX_VEHICLE_DESC #include "NxWheelDesc.h" #include "NxVehicleMotorDesc.h" #include "NxVehicleGearDesc.h" #include <NxArray.h> #include <NxShapeDesc.h> class NxVehicleDesc { public: NxArray<NxShapeDesc*> carShapes; NxArray<NxWheelDesc*> carWheels; NxArray<NxVehicleDesc*> children; NxVehicleMotorDesc* motorDesc; NxVehicleGearDesc* gearDesc; NxVec3 position; NxReal mass; NxReal motorForce; NxReal transmissionEfficiency; NxReal differentialRatio; NxVec3 steeringTurnPoint; NxVec3 steeringSteerPoint; NxReal steeringMaxAngle; NxVec3 centerOfMass; NxReal digitalSteeringDelta; NxReal maxVelocity; NxReal cameraDistance; //NxReal digitalSteeringDeltaVelocityModifier; void* userData; NX_INLINE NxVehicleDesc(); NX_INLINE void setToDefault(); NX_INLINE bool isValid() const; }; NX_INLINE NxVehicleDesc::NxVehicleDesc() //constructor sets to default { setToDefault(); } NX_INLINE void NxVehicleDesc::setToDefault() { userData = NULL; motorDesc = NULL; gearDesc = NULL; transmissionEfficiency = 1.0f; differentialRatio = 1.0f; maxVelocity = 80; cameraDistance = 15.f; children.clear(); carWheels.clear(); } NX_INLINE bool NxVehicleDesc::isValid() const { for (NxU32 i = 0; i < carWheels.size(); i++) { if (!carWheels[i]->isValid()) return false; } if (mass < 0) return false; return true; } #endif <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "ISession.h" #include "xDistributedSessionClass.h" #include "xDistributedSession.h" #include "xDistributedClient.h" #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorNSLeaveObjectDecl(); CKERROR CreateNSLeaveObjectProto(CKBehaviorPrototype **); int NSLeaveObject(const CKBehaviorContext& behcontext); CKERROR NSLeaveObjectCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 5 #define BEH_OUT_MIN_COUNT 2 #define BEH_OUT_MAX_COUNT 1 typedef enum BB_IT { BB_IT_IN }; typedef enum BB_INPAR { BB_IP_CONNECTION_ID, }; typedef enum BB_OT { BB_O_LEFT, BB_O_WAITING, BB_O_ERROR, }; typedef enum BB_OP { BB_OP_ERROR, }; /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ CKObjectDeclaration *FillBehaviorNSLeaveObjectDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NSLeave"); od->SetDescription("Leaves a session"); od->SetCategory("TNL/Sessions"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x9904be3,0x46526de2)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNSLeaveObjectProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ CKERROR CreateNSLeaveObjectProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NSLeave"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Left"); proto->DeclareOutput("Waiting For Answer"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareSetting("Wait For Answer", CKPGUID_BOOL, "0"); proto->DeclareSetting("Destroy Session", CKPGUID_BOOL, "TRUE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(NSLeaveObject); proto->SetBehaviorCallbackFct(NSLeaveObjectCB); *pproto = proto; return CK_OK; } typedef std::vector<xDistributedSession*>xSessions; /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int NSLeaveObject(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; bbNoError(E_NWE_OK); //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } if (!cin->getMyClient()) { bbError(E_NWE_INTERN); return 0; } ISession *sInterface = cin->getSessionInterface(); int connectionID = GetInputParameterValue<int>(beh,BB_IP_CONNECTION_ID); int deleteSession = 0; beh->GetLocalParameterValue(1,&deleteSession); int waiting= 0; beh->GetLocalParameterValue(0,&waiting); ////////////////////////////////////////////////////////////////////////// // // Check states : // xDistributedClient *myClient = cin->getMyClient(); if (!myClient) { bbError(E_NWE_INTERN); return 0; } ////////////////////////////////////////////////////////////////////////// if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); xDistributedSession *session = cin->getCurrentSession(); if (!session) { bbError(E_NWE_NO_SUCH_SESSION); return 0; } if (!myClient->getClientFlags().test(1 << E_CF_SESSION_JOINED)) { bbError(E_NWE_NO_SESSION); return 0; } sInterface->removeClient(myClient,session->getSessionID(),deleteSession); if (waiting) return CKBR_ACTIVATENEXTFRAME; else { if (cin->getCurrentSession()) { cin->setCurrentSession(NULL); } ////////////////////////////////////////////////////////////////////////// vtConnection *con = cin->getConnection(); if (con) { con->setSessionID(-1); } } return 0; } ////////////////////////////////////////////////////////////////////////// if (waiting && !myClient->getClientFlags().test(1 << E_CF_SESSION_JOINED)) { if (cin->getCurrentSession()) { cin->setCurrentSession(NULL); } ////////////////////////////////////////////////////////////////////////// vtConnection *con = cin->getConnection(); if (con) { con->setSessionID(-1); } return 0; } if (waiting) { beh->ActivateOutput(BB_O_WAITING); } return CKBR_ACTIVATENEXTFRAME; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ CKERROR NSLeaveObjectCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; } <file_sep>dofile("ModuleConfig.lua") dofile("ModuleHelper.lua") if _ACTION == "help" then premake.showhelp() return end solution "vtPlayer" configurations { "Debug", "Release" , "ReleaseDebug" } if _ACTION and _OPTIONS["Dev"] then setfields("location","./".._ACTION.._OPTIONS["Dev"]) end packageConfig_XSplash = { Name = "xSplash", Type = "SharedLib", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; "_AFXDLL" ; "WINVER=0x0500" }, Files = { D_XSPLASH.."src/**.cpp" ; D_XSPLASH.."include/**.h" }, Includes = { D_XSPLASH.."include" ; D_CORE_INCLUDES ; D_STD_INCLUDES }, StaticOptions = { "convert" }, Options = { "/W0" ; } } packageConfig_XUtils = { Name = "xUtils", Type = "SharedLib", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; "_AFXDLL" ; "WINVER=0x0500"}, Files = { D_XUTILS.."src/**.cpp" ; D_XUTILS.."include/**.h" }, Includes = { DDEPS.."psdk/include" ; D_STD_INCLUDES; D_XUTILS.."include/3D" ; D_CORE_INCLUDES ; D_DIRECTX9.."Include" }, Libs = { "Version" }, LibDirectories = { DDEPS.."psdk/lib" ; D_DIRECTX9.."lib" }, StaticOptions = { "convert" }, Options = { "/W0" ; } } packageConfig_vtWindowLib = { Name = "vtWindowLib", Type = "SharedLib", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "_AFXDLL" ; }, Files = { DROOT.."SDK/src/core/**.cpp" ; DROOT.."SDK/include/core/**.h" ; F_BASE_STD_INC ;F_VT_STD_INC; F_BASE_VT_SRC ;F_BASE_SRC;F_SHARED_SRC ; DROOT.."SDK/src/core/*.rc" }, Includes = { DDEPS.."psdk/include" ; D_STD_INCLUDES ; D_VT_BASE_INC; D_CORE_INCLUDES ; D_DIRECTX9.."Include" ;DROOT.."SDK/src/core" }, Libs = { "user32" ; "kernel32" ; "xSplash" ; "xUtils" ; "dxguid" ; "Version" ; }, LibDirectories = { DDEPS.."psdk/lib" ; D_DIRECTX9.."lib" ; DROOT.."SDK/lib" }, Options = { "/W0"}, StaticOptions = { "convert" }, StaticModules = { "vtWidgets" ; "vtToolkit" ; "vtPhysX" }, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower() } packageConfig_vtCSWindow = { Name = "vtCSWindow", Type = "SharedLib", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "_AFXDLL" }, Files = { DROOT.."SDK/src/CSharp/**.cxx" ; DROOT.."SDK/src/CSharp/*.i" ; F_BASE_VT_SRC }, Includes = { D_STD_INCLUDES ; D_VT_BASE_INC; D_CORE_INCLUDES ; D_DIRECTX9.."Include" ;DROOT.."SDK/src/core" }, Libs = { "user32" ; "kernel32" ; "xSplash" ; "xUtils" ; "dxguid" ; "Version" ; "vtWindowLib" }, LibDirectories = { D_DIRECTX9.."lib" ; DROOT.."SDK/Include/Core" ; DROOT.."SDK/lib" }, Options = { "/W0"}, StaticOptions = { "vtstatic" }, StaticModules = { "vtWidgets" ; "vtToolkit" ; "vtPhysX" }, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower() } packageConfig_vtPlayerApp = { Name = "vtPlayer", Type = "WindowedApp", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "_AFXDLL" ; }, Files = { DROOT.."SDK/src/core/**.cpp" ; DROOT.."SDK/include/core/**.h" ; F_BASE_STD_INC ;F_VT_STD_INC; F_BASE_VT_SRC ;F_BASE_SRC;F_SHARED_SRC ; DROOT.."SDK/src/core/*.rc" }, Includes = { D_STD_INCLUDES ; D_VT_BASE_INC; D_CORE_INCLUDES ; D_DIRECTX9.."Include" ;DROOT.."SDK/src/core" }, Libs = { "user32" ; "kernel32" ; "xSplash" ; "xUtils" ; "dxguid" ; "Version" }, LibDirectories = { D_DIRECTX9.."lib" ; DROOT.."SDK/Include/Core" ; DROOT.."SDK/lib" }, Options = { "/W0"}, StaticOptions = { "" }, StaticModules = { "vtWidgets" ; "vtToolkit" ; "vtPhysX" }, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower() } packageConfig_vtConsoleApp = { Name = "vtPlayerConsole", Type = "ConsoleApp", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "_AFXDLL" ; }, Files = { DROOT.."SDK/src/Console/**.cpp" ; DROOT.."SDK/include/core/**.h" ; F_BASE_STD_INC ;F_VT_STD_INC; F_BASE_VT_SRC ;F_BASE_SRC;F_SHARED_SRC ; DROOT.."SDK/src/core/*.rc"; DROOT.."SDK/src/core/*.rc" ; DROOT.."SDK/src/core/vtWindow.cpp" }, Includes = { D_STD_INCLUDES ; D_VT_BASE_INC; D_CORE_INCLUDES ; D_DIRECTX9.."Include" ;DROOT.."SDK/src/core" }, Libs = { "user32" ; "kernel32" ; "xSplash" ; "xUtils" ; "dxguid" ; "Version" ; "vtWindowLib" }, LibDirectories = { D_DIRECTX9.."lib" ; DROOT.."SDK/Include/Core" ; DROOT.."SDK/lib" }, Options = { "/W0"}, StaticOptions = { "vtstatic" }, StaticModules = { "vtWidgets" ; "vtToolkit" ; "vtPhysX" }, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower() } packageConfig_vtCSPlayerApp = { Name = "vtPlayerCS", Type = "WindowedApp", TargetSuffix = "", Language = "C#", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "_AFXDLL" }, Files = { DROOT.."SDK/Src/CSharp/*.cs" }, Includes = { }, Libs = { "vtCSWindow" ; "System" ; "System.Drawing" ; "System.Data" ; "System.Windows.Forms" ; "System.XML" }, LibDirectories = { }, Options = { "/W0"}, StaticOptions = { "" }, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower() } packageConfig_vtCSharpBuildingBlocks = { Name = "vtCSharpBuildingBlocks", Type = "SharedLib", TargetSuffix = "/BuildingBlocks", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "_AFXDLL" }, Files = { DROOT.."SDK/src/Behaviors/**.cpp" ; DROOT.."SDK/src/Behaviors/*.rc" ; DROOT.."SDK/src/Behaviors/*.def" ; F_BASE_STD_INC ;F_VT_STD_INC; F_BASE_VT_SRC ;F_BASE_SRC;F_SHARED_SRC }, Includes = { D_STD_INCLUDES ; D_CORE_INCLUDES ;}, Libs = { "user32" ; "kernel32" ; "Winmm" }, LibDirectories = { }, StaticOptions = { "convert" }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\BuildingBlocks" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\BuildingBlocks" } createStaticPackage(packageConfig_vtCSWindow) createStaticPackage(packageConfig_XSplash) createStaticPackage(packageConfig_XUtils) createStaticPackage(packageConfig_vtWindowLib) createStaticPackage(packageConfig_vtPlayerApp) createStaticPackage(packageConfig_vtCSPlayerApp) createStaticPackage(packageConfig_vtCSharpBuildingBlocks) createStaticPackage(packageConfig_vtConsoleApp) --createStaticPackage(packageConfig_vtAgeiaReader) --createStaticPackage(packageConfig_vtAgeiaInterface) --include "CppConsoleApp" function onclean() os.rmdir("vs**") end <file_sep>#include "CPStdAfx.h" //#include "CustomPlayer.h" #include "vtWindow.h" vtWindow *myWin=NULL; int _tmain(int argc, _TCHAR* argv[]) { myWin = new vtWindow(); if (myWin->Init()) { // CKInitCustomPlayer(false); CKStartUp(); // myWin->getPlayer()->m_hInstance myWin->DoFrame(); myWin->Destroy(); } } <file_sep>dofile("ModuleConfig.lua") dofile("ModuleHelper.lua") if _ACTION == "help" then premake.showhelp() return end solution "vtPhysX" configurations { "Debug", "Release" , "ReleaseDebug" ; "ReleaseRedist" ; "ReleaseDemo" } if _ACTION and _OPTIONS["Dev"] then setfields("location","./".._ACTION.._OPTIONS["Dev"]) end packageConfig_Stream = { Name = "NxuStream2", Type = "StaticLib", Defines = { DEF_STD_DIRECTIVES ; DEF_PHYSX_DIRECTIVES }, Files = { D_NXSTREAM.."*.cpp" ; D_NXSTREAM.."*.h" }, Includes = { D_PHYSX_INCLUDES }, Options = { "/W0"} } packageConfig_Common = { Name = "NxCommon", Type = "StaticLib", Defines = { DEF_STD_DIRECTIVES ; DEF_PHYSX_DIRECTIVES }, Files = { D_NXCOMMON.."*.cpp" ; D_NXCOMMON.."*.h" }, Includes = { D_PHYSX_INCLUDES }, Options = { "/W0"} } packageConfig_Character = { Name = "NxCharacter", Type = "StaticLib", Defines = { DEF_STD_DIRECTIVES ; DEF_PHYSX_DIRECTIVES ; "NX_USE_SDK_STATICLIBS" ; "NXCHARACTER_EXPORTS" }, Files = { D_NXCHARACTER.."**.cpp" ; D_NXCHARACTER.."**.h" }, Includes = { D_PHYSX_INCLUDES }, Options = { "/W0"} } packageConfig_TinyXML = { Name = "TinyXML", Type = "StaticLib", Defines = { DEF_STD_DIRECTIVES }, Files = { D_TINYXML.."*.cpp" ; D_TINYXML.."*.h" }, Includes = { D_PHYSX_INCLUDES }, Options = { "/W0"} } -- Static library of the built-in camera building blocks -- -- This package needs to be compiled for web player distributions. -- Call createSolutions40Web2005.bat for instance -- packageConfig_CameraRepack= { Name = "Camera", Type = "StaticLib", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" }, Files = { DDEPS.."camera/behaviors/**.cpp" }, Includes = { D_STD_INCLUDES ; }, Libs = { "ck2" ; "vxmath" }, LibDirectories = { }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower() } -- The core vtPhysX SDK, compiled as DLL with exports. This is the entire base library for -- -- - building blocks -- - interface plug-ins -- - custom parameter types -- - custom file readers -- -- packageConfig_vtAgeiaLib = { Name = "vtPhysXLib", Type = "SharedLib", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; DEF_PHYSX_DIRECTIVES ; "NX_USE_SDK_STATICLIBS" ; "NXCHARACTER_EXPORTS" ; "VIRTOOLS_USER_SDK" ; "MODULE_BASE_EXPORTS" ; }, Files = { DROOT.."SDK/src/core/**.cpp" ; DROOT.."SDK/include/core/**.h" ; F_BASE_STD_INC ;F_VT_STD_INC; F_BASE_VT_SRC ;F_BASE_SRC;F_SHARED_SRC }, Includes = { D_PHYSX_INCLUDES ; D_STD_INCLUDES ; D_VT_BASE_INC; D_CORE_INCLUDES ; DDEPS.."TinyXML" }, Libs = { "TinyXML" , "NxCharacter" , "NxCommon" , "NxuStream2"; "ck2" ; "vxmath" ; "user32" ; "kernel32" ; "PhysXLoader" ; "Winmm" }, LibDirectories = { D_PHYSX.."SDKs/lib/Win32" }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower() } -- The building blocks for vtPhysX, depending on packageConfig_vtAgeiaLib packageConfig_vtAgeiaBeh = { Name = "vtPhysX", Type = "SharedLib", TargetSuffix = "/BuildingBlocks", Defines = { DEF_STD_DIRECTIVES ; DEF_PHYSX_DIRECTIVES ; "NX_USE_SDK_STATICLIBS" ; "NXCHARACTER_EXPORTS" ; "VIRTOOLS_USER_SDK" ; "MODULE_BASE_EXPORTS" }, Files = { DROOT.."SDK/src/Behaviors/**.cpp" ; DROOT.."SDK/src/Behaviors/*.def" ; D_DOCS_PAGES.."*.page" ; F_SHARED_SRC ; DROOT.."build4/**.lua" ; F_EXTRA_BB_SRC ; F_BASE_SRC }, Includes = { D_PHYSX_INCLUDES ; D_STD_INCLUDES ; D_CORE_INCLUDES ; DDEPS.."TinyXML" ; DDEPS.."dx/Include" }, Libs = { "ck2" ; "vxmath" ; "user32" ; "kernel32" ; "vtPhysXLib" ;"Winmm" ; "dxerr"; "dinput8";"dxguid" }, LibDirectories = { D_PHYSX.."SDKs/lib/Win32" ; D_DX.."lib" }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\BuildingBlocks" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\BuildingBlocks" } -- The vtPhysX Reader plug-in supports NXU-Stream formats or collada, exporters for Maya and 3D-SMax -- are avaiable. Depends on packageConfig_vtAgeiaLib packageConfig_vtAgeiaReader = { Name = "vtPhysXReader", Type = "SharedLib", TargetSuffix = "/Plugins", Defines = { DEF_STD_DIRECTIVES ; DEF_PHYSX_DIRECTIVES ; "NX_USE_SDK_STATICLIBS" ; "NXCHARACTER_EXPORTS" ; "VIRTOOLS_USER_SDK" ; "MODULE_BASE_EXPORTS" }, Files = { D_READER_SRC.."*.cpp" ; D_READER_SRC.."*.def" ; }, Includes = { D_PHYSX_INCLUDES ; D_STD_INCLUDES ; D_CORE_INCLUDES ; DDEPS.."TinyXML" }, Libs = { "ck2" ; "vxmath" ; "user32" ; "kernel32" ; "vtPhysXLib" }, LibDirectories = { D_PHYSX.."SDKs/lib/Win32" }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\BuildingBlocks" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\Plugins" } -- An interface plug-in to create dialogs for physic related parameters. -- Depends on packageConfig_vtAgeiaLib packageConfig_vtAgeiaInterface = { Name = "vtPhysXInterface", Type = "SharedLib", TargetSuffix = "/InterfacePlugins", Defines = { DEF_STD_DIRECTIVES ; DEF_PHYSX_DIRECTIVES ; "NX_USE_SDK_STATICLIBS" ; "NXCHARACTER_EXPORTS" ; "VIRTOOLS_USER_SDK" ; "MODULE_BASE_EXPORTS" }, Files = { D_UI_SRC.."*.cpp" ; D_UI_SRC.."*.def" ; D_INCLUDE.."Interface/*.h" }, Includes = { D_PHYSX_INCLUDES ; D_STD_INCLUDES ; D_CORE_INCLUDES ; DDEPS.."TinyXML" ; D_INCLUDE.."Interface" }, Libs = { "ck2" ; "vxmath" ; "user32" ; "kernel32" ; "vtPhysXLib" ; "DllEditor" ; "InterfaceControls" ; "CKControls" ; "CK2Ui" }, LibDirectories = { D_PHYSX.."SDKs/lib/Win32" }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\InterfacePlugins" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\InterfacePlugins" } -- If the command line contains --ExtraDefines="WebPack" , we add "WebPack" to the -- pre-processor directives and also create a package to include the camera building blocks -- as defined in packageConfig_CameraRepack if _OPTIONS["ExtraDefines"] then if _OPTIONS["ExtraDefines"]=="WebPack" then createStaticPackage(packageConfig_CameraRepack) end end createStaticPackage(packageConfig_Common) createStaticPackage(packageConfig_Stream) createStaticPackage(packageConfig_Character) createStaticPackage(packageConfig_TinyXML) createStaticPackage(packageConfig_vtAgeiaLib) createStaticPackage(packageConfig_vtAgeiaBeh) --createStaticPackage(packageConfig_vtAgeiaReader) --createStaticPackage(packageConfig_vtAgeiaInterface) --include "CppConsoleApp" function onclean() os.rmdir("vs**") end <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Vertigo // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorVertigoDecl(); CKERROR CreateVertigoProto(CKBehaviorPrototype **pproto); int Vertigo(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorVertigoDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Vertigo"); od->SetDescription("Creates a 'Vertigo' effect on the Camera."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process<BR> <SPAN CLASS=in>Loop In: </SPAN>triggers the next step in the process loop.<BR> <BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <SPAN CLASS=out>Loop Out:</SPAN>is activated when the process needs to loop.<BR> <BR> <SPAN CLASS=pin>Focal Point: </SPAN>3D Entity that determines the constant focal plane for the camera during the effect.<BR> <SPAN CLASS=pin>Number of Frames: </SPAN>number of frames in which the effect will be performed.<BR> <SPAN CLASS=pin>Forward: </SPAN>'True' moves the camera forward, 'False' moves it backward.<BR> <SPAN CLASS=pin>Distortion Amount: </SPAN>amount of distorsion expressed in percentage.<BR> <SPAN CLASS=pin>Progression Curve: </SPAN>progression curve along the camera Z axis.<BR> <BR> This behavior creates a 'Vertigo' effect by moving the camera forward (or backward) along its Z axis while adjusting the field of view so that the objects in its focal plan remain the same size on the screen (while the others are deformed). Typically, this is used to produce dizziness or to increase tension before a scary event... */ /* warning: - As a old stuff, this building block is not time based at all. Therefore it is frame rate dependant.<BR> */ od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0xb00d010a, 0xc00d010a)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateVertigoProto); od->SetCompatibleClassId(CKCID_CAMERA); od->SetCategory("Cameras/FX"); return od; } CKERROR CreateVertigoProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Vertigo"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Loop In"); proto->DeclareOutput("Out"); proto->DeclareOutput("Loop Out"); proto->DeclareLocalParameter(NULL, CKPGUID_INT,0 );//"stepsRemaining" proto->DeclareLocalParameter(NULL, CKPGUID_FLOAT );//"projectionPlaneSize" proto->DeclareLocalParameter(NULL, CKPGUID_FLOAT );//"curveLastX" proto->DeclareLocalParameter(NULL, CKPGUID_FLOAT );//"curveDeltaX" proto->DeclareLocalParameter(NULL, CKPGUID_VECTOR );//"goingVector" proto->DeclareInParameter("Focal Point", CKPGUID_3DENTITY ); proto->DeclareInParameter("Number of Frames", CKPGUID_INT ,"100"); proto->DeclareInParameter("Forward", CKPGUID_BOOL ,"TRUE"); proto->DeclareInParameter("Distortion Amount", CKPGUID_PERCENTAGE ,"50"); proto->DeclareInParameter("Progression Curve", CKPGUID_2DCURVE ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(Vertigo); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int Vertigo(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; // we get the camera entity CKCamera *ent = (CKCamera *) beh->GetTarget(); if( !ent ) return CKBR_OWNERERROR; VxVector goingVector; // we get the steps remaining (local parameter) int stepsRemaining; beh->GetLocalParameterValue(0, &stepsRemaining); if(beh->IsInputActive(0)) { // first time in a loop vertigo is launched // we get the velocity (input parameter) int nb_frame = 100; beh->GetInputParameterValue(1, &nb_frame); // we calculate the steps remaining stepsRemaining = nb_frame; // we get the object position CK3dEntity *e = (CK3dEntity *)beh->GetInputParameterObject(0); if(!e) return CKBR_PARAMETERERROR; VxVector objectPosition; e->GetPosition(&objectPosition, ent); // we get the effect value float effectValue = 0.5f; beh->GetInputParameterValue(3, &effectValue); // we get the direction CKBOOL direction = TRUE; beh->GetInputParameterValue(2, &direction); // we calculate the goingVector if(direction) { // camera -> object goingVector.x = 0; goingVector.y = 0; goingVector.z = objectPosition.z; } else { // <- camera object goingVector.x = 0; goingVector.y = 0; goingVector.z = -objectPosition.z; effectValue = effectValue/(1.0f-effectValue); } float D=Magnitude(goingVector); goingVector *= effectValue; // we calculate the planeProjectionSize float fov=ent->GetFov(); float planeProjectionSize; planeProjectionSize=(float)(D*tan(fov/2.0f)); // we calculate the curveDeltaX float curveDeltaX; curveDeltaX = 1.0f/stepsRemaining; /////////////////////////////// // writing the local parameters // writing the stepsRemaining beh->SetLocalParameterValue(0, &stepsRemaining); // writing the planeProjectionSize beh->SetLocalParameterValue(1, &planeProjectionSize); // writing the curveLastX float clx=0.0; beh->SetLocalParameterValue(2, &clx); // writing the curveDeltaX beh->SetLocalParameterValue(3, &curveDeltaX); // writing the goingVector beh->SetLocalParameterValue(4, &goingVector); beh->ActivateInput(0, FALSE); beh->ActivateOutput(1); return CKBR_OK; } else { // we are in the loop beh->ActivateInput(1,FALSE); /////////////////////////////// // getting the input parameters // getting the 2d curve CK2dCurve *accelerationCurve = NULL; beh->GetInputParameterValue(4,&accelerationCurve); /////////////////////////////// // getting the local parameters // getting the planeProjectionSize float planeProjectionSize; beh->GetLocalParameterValue(1, &planeProjectionSize); // getting the curveLastX float curveLastX; beh->GetLocalParameterValue(2, &curveLastX); // getting the curveDeltaX float curveDeltaX; beh->GetLocalParameterValue(3, &curveDeltaX); // getting the goingVector VxVector goingVector; beh->GetLocalParameterValue(4, &goingVector); // calculating the deltaY of the curve float deltaY = accelerationCurve->GetY(curveLastX+curveDeltaX) - accelerationCurve->GetY(curveLastX); // translating the camera VxVector trans = goingVector * deltaY; ent->Translate(&trans, ent); // calculating the new D // we get the object position CK3dEntity *e = (CK3dEntity *) beh->GetInputParameterObject(0); VxVector objectPosition; e->GetPosition( &objectPosition, ent ); float D = (float) fabs( objectPosition.z ); // calculating the fov float fov = 2.0f * atanf( planeProjectionSize / D ); // changing the fov ent->SetFov(fov); /////////////////////////////// // writing the local parameters // writing the stepsRemaining stepsRemaining--; beh->SetLocalParameterValue(0, &stepsRemaining); // writing the curveLastX curveLastX += curveDeltaX; beh->SetLocalParameterValue(2, &curveLastX); if(stepsRemaining) { // vertigo not finished beh->ActivateOutput(1); return CKBR_OK; } else { // loop accomplished beh->ActivateOutput(0); return CKBR_OK; } } return CKBR_OK; } <file_sep>#include <StdAfx.h> #define STRICT #define DIRECTINPUT_VERSION 0x0800 #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #include <tchar.h> #include <windows.h> #include <commctrl.h> #include <basetsd.h> #include <commdlg.h> #include <dinput.h> #include "CKAll.h" static CKContext *ctx = NULL; //---------------------------------------------------------------- // // // #define HAS_CONFIG #ifdef HAS_CONFIG #include "gConfig.h" #endif // BB_TOOLS #ifdef BB_TOOLS #include <vtInterfaceEnumeration.h> #include "vtLogTools.h" #include "vtCBBErrorHelper.h" #include <virtools/vtBBHelper.h> #include <virtools/vtBBMacros.h> using namespace vtTools::BehaviorTools; #endif //----------------------------------------------------------------------------- // Defines, constants, and global variables //----------------------------------------------------------------------------- struct EFFECTS_NODE { LPDIRECTINPUTEFFECT pDIEffect; DWORD dwPlayRepeatCount; EFFECTS_NODE* pNext; }; LPDIRECTINPUT8 g_pDI = NULL; LPDIRECTINPUTDEVICE8 g_pFFDevice = NULL; EFFECTS_NODE g_EffectsList; static bool gInitiated = false; //----------------------------------------------------------------------------- // Function-prototypes //----------------------------------------------------------------------------- INT_PTR CALLBACK MainDialogProc( HWND, UINT, WPARAM, LPARAM ); BOOL CALLBACK EnumFFDevicesCallback2( LPCDIDEVICEINSTANCE pDDI, VOID* pvRef ); BOOL CALLBACK EnumAndCreateEffectsCallback2( LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ); HRESULT InitDirectInput2( HWND hDlg ); HRESULT FreeDirectInput2(); VOID EmptyEffectList2(); HRESULT OnReadFile2( HWND hDlg,const char*file); HRESULT OnPlayEffects2( HWND hDlg ); LPDIRECTINPUTEFFECT g_pEffect = NULL; BOOL g_bActive = TRUE; DWORD g_dwNumForceFeedbackAxis = 0; INT g_nXForce; INT g_nYForce; DWORD g_dwLastEffectSet; // Time of the previous force feedback effect set //----------------------------------------------------------------------------- // Name: EnumAxesCallback() // Desc: Callback function for enumerating the axes on a joystick and counting // each force feedback enabled axis //----------------------------------------------------------------------------- BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi, VOID* pContext ) { DWORD* pdwNumForceFeedbackAxis = ( DWORD* )pContext; if( ( pdidoi->dwFlags & DIDOI_FFACTUATOR ) != 0 ) ( *pdwNumForceFeedbackAxis )++; return DIENUM_CONTINUE; } HRESULT InitDirectInput2( HWND hDlg ) { HRESULT hr; DIPROPDWORD dipdw; // Setup the g_EffectsList circular linked list ZeroMemory( &g_EffectsList, sizeof( EFFECTS_NODE ) ); g_EffectsList.pNext = &g_EffectsList; // Create a DInput object if( FAILED( hr = DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&g_pDI, NULL ) ) ) { ctx->OutputToConsole("PlayFFE :: DirectInput8Create"); return hr; } // Get the first enumerated force feedback device if( FAILED( hr = g_pDI->EnumDevices( DI8DEVCLASS_GAMECTRL, EnumFFDevicesCallback2, 0, DIEDFL_ATTACHEDONLY | DIEDFL_FORCEFEEDBACK ) ) ) { ctx->OutputToConsole("PlayFFE :: EnumDevices failed"); return hr; } if( g_pFFDevice == NULL ) { ctx->OutputToConsole("PlayFFE :: No force feedback device found."); return -1; } // Set the data format if( FAILED( hr = g_pFFDevice->SetDataFormat( &c_dfDIJoystick ) ) ) return hr; // Set the coop level //hr = g_pFFDevice->SetCooperativeLevel( hDlg , DISCL_EXCLUSIVE | DISCL_FOREGROUND) ; hr = g_pFFDevice->SetCooperativeLevel( hDlg , DISCL_EXCLUSIVE | DISCL_BACKGROUND) ; //DISCL_NONEXCLUSIVE // Since we will be playing force feedback effects, we should disable the // auto-centering spring. dipdw.diph.dwSize = sizeof( DIPROPDWORD ); dipdw.diph.dwHeaderSize = sizeof( DIPROPHEADER ); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = FALSE; if( FAILED( hr = g_pFFDevice->SetProperty( DIPROP_AUTOCENTER, &dipdw.diph ) ) ) return hr; // Enumerate and count the axes of the joystick if( FAILED( hr = g_pFFDevice->EnumObjects( EnumAxesCallback, ( VOID* )&g_dwNumForceFeedbackAxis, DIDFT_AXIS ) ) ) return hr; // This simple sample only supports one or two axis joysticks if( g_dwNumForceFeedbackAxis > 2 ) g_dwNumForceFeedbackAxis = 2; // This application needs only one effect: Applying raw forces. DWORD rgdwAxes[2] = { DIJOFS_X, DIJOFS_Y }; LONG rglDirection[2] = { 0,0 }; DICONSTANTFORCE cf = { 0 }; cf.lMagnitude = 0; DIEFFECT eff; ZeroMemory( &eff, sizeof( eff ) ); eff.dwSize = sizeof( DIEFFECT ); eff.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; eff.dwDuration = INFINITE; eff.dwSamplePeriod = 0; eff.dwGain = DI_FFNOMINALMAX; eff.dwTriggerButton = DIEB_NOTRIGGER; eff.dwTriggerRepeatInterval = 0; eff.cAxes = g_dwNumForceFeedbackAxis; eff.rgdwAxes = rgdwAxes; eff.rglDirection = rglDirection; eff.lpEnvelope = 0; eff.cbTypeSpecificParams = sizeof( DICONSTANTFORCE ); eff.lpvTypeSpecificParams = &cf; eff.dwStartDelay = 0; // Create the prepared effect if( FAILED( hr = g_pFFDevice->CreateEffect( GUID_ConstantForce, &eff, &g_pEffect, NULL ) ) ) { return hr; } if( NULL == g_pEffect ) return E_FAIL; return S_OK; } //----------------------------------------------------------------------------- // Name: EnumFFDevicesCallback2() // Desc: Get the first enumerated force feedback device //----------------------------------------------------------------------------- BOOL CALLBACK EnumFFDevicesCallback2( LPCDIDEVICEINSTANCE pDDI, VOID* pvRef ) { if( FAILED( g_pDI->CreateDevice( pDDI->guidInstance, &g_pFFDevice, NULL ) ) ) return DIENUM_CONTINUE; // If failed, try again // Stop when a device was successfully found return DIENUM_STOP; } //----------------------------------------------------------------------------- // Name: FreeDirectInput2() // Desc: Initialize the DirectInput variables. //----------------------------------------------------------------------------- HRESULT FreeDirectInput2() { // Release any DirectInputEffect objects. if( g_pFFDevice ) { EmptyEffectList2(); g_pFFDevice->Unacquire(); SAFE_RELEASE( g_pFFDevice ); } // Release any DirectInput objects. SAFE_RELEASE( g_pDI ); return S_OK; } //----------------------------------------------------------------------------- // Name: EmptyEffectList2() // Desc: Goes through the circular linked list and releases the effects, // and deletes the nodes //----------------------------------------------------------------------------- VOID EmptyEffectList2() { EFFECTS_NODE* pEffectNode = g_EffectsList.pNext; EFFECTS_NODE* pEffectDelete; while ( pEffectNode != &g_EffectsList ) { pEffectDelete = pEffectNode; pEffectNode = pEffectNode->pNext; SAFE_RELEASE( pEffectDelete->pDIEffect ); SAFE_DELETE( pEffectDelete ); } g_EffectsList.pNext = &g_EffectsList; } //----------------------------------------------------------------------------- // Name: OnReadFile2() // Desc: Reads a file contain a collection of DirectInput force feedback // effects. It creates each of effect read in and stores it // in the linked list, g_EffectsList. //----------------------------------------------------------------------------- HRESULT OnReadFile2( HWND hDlg,const char*file) { HRESULT hr; EmptyEffectList2(); // Enumerate the effects in the file selected, and create them in the callback if( FAILED( hr = g_pFFDevice->EnumEffectsInFile( file,EnumAndCreateEffectsCallback2, NULL, DIFEF_MODIFYIFNEEDED ) ) ) return hr; // If list of effects is empty, then we haven't been able to create any effects if( g_EffectsList.pNext == &g_EffectsList ) { ctx->OutputToConsole("Unable to create any effects."); } else { // We have effects so enable the 'play effects' button } return S_OK; } BOOL CALLBACK EnumAndCreateEffectsCallback2(LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ) { HRESULT hr; LPDIRECTINPUTEFFECT pDIEffect = NULL; // Create the file effect if( FAILED( hr = g_pFFDevice->CreateEffect( pDIFileEffect->GuidEffect, pDIFileEffect->lpDiEffect, &pDIEffect, NULL ) ) ) { ctx->OutputToConsole("Could not create force feedback effect on this device"); return DIENUM_CONTINUE; } // Create a new effect node EFFECTS_NODE* pEffectNode = new EFFECTS_NODE; if( NULL == pEffectNode ) return DIENUM_STOP; // Fill the pEffectNode up ZeroMemory( pEffectNode, sizeof( EFFECTS_NODE ) ); pEffectNode->pDIEffect = pDIEffect; pEffectNode->dwPlayRepeatCount = 1; // Add pEffectNode to the circular linked list, g_EffectsList pEffectNode->pNext = g_EffectsList.pNext; g_EffectsList.pNext = pEffectNode; return DIENUM_CONTINUE; } HRESULT OnPlayEffects2( HWND hDlg ) { EFFECTS_NODE* pEffectNode = g_EffectsList.pNext; LPDIRECTINPUTEFFECT pDIEffect = NULL; HRESULT hr; // Stop all previous forces if( FAILED( hr = g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ) ) ) return hr; while ( pEffectNode != &g_EffectsList ) { // Play all of the effects enumerated in the file pDIEffect = pEffectNode->pDIEffect; if( NULL != pDIEffect ) { if( FAILED( hr = pDIEffect->Start( pEffectNode->dwPlayRepeatCount, 0 ) ) ) return hr; } pEffectNode = pEffectNode->pNext; } return S_OK; } CKObjectDeclaration *FillBehaviorJSetXYForceDecl(); CKERROR CreateJSetXYForceProto(CKBehaviorPrototype **); int JSetXYForce(const CKBehaviorContext& behcontext); CKERROR PlayFFECallBackObject(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorJSetXYForceDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("JSetXYForce"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x6890534f,0x31c12074)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJSetXYForceProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Controllers/Joystick"); return od; } enum bbIO_Inputs { BB_I_DO, BB_I_RELEASE, }; enum bbIO_Outputs { BB_O_DONE, BB_O_RELEASED, BB_O_ERROR, }; CKERROR CreateJSetXYForceProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("JSetXYForce"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); //proto->DeclareInput("stop"); proto->DeclareInput("release device"); proto->DeclareOutput("Done"); //proto->DeclareOutput("Stopped"); proto->DeclareOutput("Released"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Force Vector",CKPGUID_2DVECTOR); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( JSetXYForce ); proto->SetBehaviorCallbackFct(PlayFFECallBackObject); *pproto = proto; return CK_OK; } HRESULT SetDeviceForcesXY(float x,float y) { // Modifying an effect is basically the same as creating a new one, except // you need only specify the parameters you are modifying LONG rglDirection[2] = { 0, 0 }; DICONSTANTFORCE cf; if( g_dwNumForceFeedbackAxis == 1 ) { // If only one force feedback axis, then apply only one direction and // keep the direction at zero cf.lMagnitude = x; rglDirection[0] = 0; } else { // If two force feedback axis, then apply magnitude from both directions rglDirection[0] = x; rglDirection[1] = y; cf.lMagnitude = ( DWORD )sqrt( x * x + y * y ); } DIEFFECT eff; ZeroMemory( &eff, sizeof( eff ) ); eff.dwSize = sizeof( DIEFFECT ); eff.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; eff.cAxes = g_dwNumForceFeedbackAxis; eff.rglDirection = rglDirection; eff.lpEnvelope = 0; eff.cbTypeSpecificParams = sizeof( DICONSTANTFORCE ); eff.lpvTypeSpecificParams = &cf; eff.dwStartDelay = 0; // Now set the new parameters and start the effect immediately. HRESULT hr = S_OK; hr = g_pEffect->SetParameters( &eff, DIEP_DIRECTION |DIEP_TYPESPECIFICPARAMS |DIEP_START ); HRESULT a1 = DIERR_INVALIDPARAM; return hr; } int JSetXYForce(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx2 = behcontext.Context; if (!ctx) { ctx = ctx2; } HWND mWin = (HWND )ctx->GetMainWindow(); HRESULT hr = S_OK; //init and load effect if( beh->IsInputActive(BB_I_DO) ) { beh->ActivateInput(BB_I_DO,FALSE); if (!gInitiated) { if (!InitDirectInput2(mWin) == S_OK) { beh->ActivateOutput(BB_O_ERROR); return CKBR_OK; }else{ hr = g_pFFDevice->Acquire(); hr =g_pEffect->Start( 1, 0 ); // Start the effect // E_ACCESSDENIED gInitiated = true; } } Vx2DVector vectorForce; beh->GetInputParameterValue(0,&vectorForce); SetDeviceForcesXY(vectorForce.x,vectorForce.y); beh->ActivateOutput(BB_O_DONE); } //play if( beh->IsInputActive(BB_I_RELEASE)) { beh->ActivateInput(BB_I_RELEASE,FALSE); { beh->ActivateOutput(BB_I_RELEASE); FreeDirectInput2(); return CKBR_OK; } } /* //stop the effect if( beh->IsInputActive(2) ){ beh->ActivateInput(2,FALSE); //g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ); beh->ActivateOutput(2); return CKBR_OK; }*/ return CKBR_OK; } CKERROR PlayFFECallBackObject(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORDETACH: case CKM_BEHAVIORRESET: { gInitiated = false; if ( g_pFFDevice) g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ); FreeDirectInput2(); //Sleep(2000); } break; } return CKBR_OK; } <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "ISession.h" #include "IMessages.h" #include "xLogger.h" #include "vtLogTools.h" #include "xMessageTypes.h" CKObjectDeclaration *FillBehaviorDODistributedObjectCreatedDecl(); CKERROR CreateDODistributedObjectCreatedProto(CKBehaviorPrototype **); int DODistributedObjectCreated(const CKBehaviorContext& behcontext); CKERROR DODistributedObjectCreatedCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorDODistributedObjectCreatedDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DOCreated"); od->SetDescription("Creates an distributed object"); od->SetCategory("TNL/Distributed Objects"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x778b6a11,0x29892907)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDODistributedObjectCreatedProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } enum bbIn { bbI_ON, bbI_OFF, bbI_NEXT }; enum bbOut { BB_O_ON, BB_O_OFF, BB_O_OBJECT, BB_O_ERROR }; enum bbPO_TIME { BB_OP_TIME, BB_OP_NAME, BB_OP_OID, BB_OP_UID, BB_OP_ERROR }; CKERROR CreateDODistributedObjectCreatedProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("DOCreated"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareInput("Off"); proto->DeclareInput("Next"); proto->DeclareOutput("Exit On"); proto->DeclareOutput("Exit Off"); proto->DeclareOutput("Object"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Distributed Object Creation Time", CKPGUID_TIME, "0"); proto->DeclareOutParameter("Object Name", CKPGUID_STRING, "0"); proto->DeclareOutParameter("Distributed Object ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Owner ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareSetting("Class", CKPGUID_STRING, "My3DClass"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(DODistributedObjectCreated); proto->SetBehaviorCallbackFct(DODistributedObjectCreatedCB); *pproto = proto; return CK_OK; } int DODistributedObjectCreated(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; using namespace vtTools::BehaviorTools; ////////////////////////////////////////////////////////////////////////// //connection id : int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } //we come in by input off : if (beh->IsInputActive(bbI_OFF)) { beh->ActivateInput(bbI_OFF,FALSE); beh->ActivateOutput(BB_O_OFF); return 0; } //we come in by input off : if (beh->IsInputActive(bbI_ON)) { beh->ActivateInput(bbI_ON,FALSE); beh->ActivateOutput(BB_O_ON); // return 0; } IDistributedObjects *doInterface = cin->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = cin->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { xDistributedClass *_class = dobj->getDistributedClass(); if (_class) { XString name(dobj->GetName().getString()); if (_class->getEnitityType() == E_DC_BTYPE_3D_ENTITY ) { //we only output objects created by remote side : if (dobj->getUserID() != cin->getConnection()->getUserID() ) { DWORD iFlags = dobj->getInterfaceFlags(); if (!isFlagOn(dobj->getObjectStateFlags(),E_DOSF_SHOWN) ) { //output do's creation time enableFlag(dobj->getObjectStateFlags(),E_DOSF_SHOWN); SetOutputParameterValue<float>(beh,BB_OP_TIME,dobj->getCreationTime()/1000.0f); //output do's name SetOutputParameterValue<CKSTRING>(beh,BB_OP_NAME,const_cast<char*>(dobj->GetName().getString())); //output do's network id SetOutputParameterValue<int>(beh,BB_OP_OID,dobj->getServerID()); //output do's network id SetOutputParameterValue<int>(beh,BB_OP_UID,dobj->getUserID()); bbNoError(E_NWE_OK); beh->ActivateOutput(BB_O_OBJECT); dobj->setInterfaceFlags(E_DO_PROCESSED); xLogger::xLog(XL_START,ELOGTRACE,E_LI_3DOBJECT,"DObject created"); } } } } } begin++; } return CKBR_ACTIVATENEXTFRAME; } CKERROR DODistributedObjectCreatedCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#include "xDistributedRect.h" <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBAddShapeDecl(); CKERROR CreatePBAddShapeProto(CKBehaviorPrototype **pproto); int PBAddShape(const CKBehaviorContext& behcontext); CKERROR PBAddShapeCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPBAddShapeDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddShape"); od->SetCategory("Physic/Body"); od->SetDescription("Adds a sub shape given by a mesh or a reference object."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x55c61f90,0x2e512638)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBAddShapeProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBAddShapeProto // FullName: CreatePBAddShapeProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ enum bInputs { bbI_Mesh=0, bbI_PObject, bbI_Pos, bbI_Rot, bbI_Ref, bbI_Density, bbI_TotalMass, }; CKERROR CreatePBAddShapeProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddShape"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /* PBAddShape PBAddShape is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Adds a sub shape. See also pRigidBody::addSubShape() .<br> See <A HREF="PBAddShape.cmo">PBAddShape.cmo</A> for example. <h3>Technical Information</h3> \image html PBAddShape.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target:</SPAN>The 3D Entity associated to the rigid body.<BR> <SPAN CLASS="pin">Mesh:</SPAN>The mesh reference. If null then it’s using the current mesh of the reference 3D-entity object.<BR> <SPAN CLASS="pin">Physic Properties: </SPAN>The hull type, new density and/or total mass are used only. You can overwrite these values if the source mesh or the reference object has a physic attribute.<br> <SPAN CLASS="pin">Local Position:</SPAN> Local position in the bodies’ space. This parameter is used when mesh !=null AND reference 3D-entity = null <br> <SPAN CLASS="pin">Local Orientation: </SPAN>Local rotation in the bodies’ space. This parameter is used when : Mesh !=null AND reference 3D-entity = null <br> <SPAN CLASS="pin">Reference: </SPAN>If mesh != null and reference !=null ,then its adding the shape and using the reference only as transformation helper. If mesh = null and reference !=null, then its adding reference’s current mesh. In that, the function will try to get the hull type from objects attribute. If there is no attribute, then it’s using the building blocks physic properties parameter. <BR> <h3>Note</h3> <b>Physic Material Lookup: (it’s looking for the physic material attribute on the objects listed below)</b> - Materials lookup order for the case <b>reference is null </b>AND <b>mesh is not null</b> : - mesh - mesh’s material (index = 0) - Materials lookup order for the case <b>mesh is null</b> AND <b>reference is not null </b> : - reference object - reference’s current mesh’s material (index = 0 ) - Materials lookup order for the case <b>mesh is not null </b>AND <b>reference is not null</b>: - mesh - mesh’s material (index = 0) - reference’s current mesh’s material (index = 0 ) When it couldn’t find any material attribute until now, it’s using the target’s body material. This material is chosen or even created during the registration (\ref PBPhysicalize). Here the lookup order during the registration of an entity in the physic engine: - entity - entity current mesh - entity current mesh’s material ( index = 0 ) If no material specified, it fails back the the holding world’s material ( retrieved from PhysicDefaults.xml/Default ) <h3>Note</h3><br> <br> You can execute this function multiple times. Is utilizing #pRigidBody #pWorld #PhysicManager <br> */ proto->DeclareInParameter("Mesh",CKPGUID_MESH); proto->DeclareInParameter("Physic Properties",VTS_PHYSIC_PARAMETER); proto->DeclareInParameter("Local Position",CKPGUID_VECTOR); proto->DeclareInParameter("Local Rotation",CKPGUID_QUATERNION); proto->DeclareInParameter("Reference",CKPGUID_3DENTITY); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBAddShape); *pproto = proto; return CK_OK; } //************************************ // Method: PBAddShape // FullName: PBAddShape // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBAddShape(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) { beh->ActivateOutput(0); return 0; } pRigidBody*result = world->getBody(target); if(!result) { return 0; } CKMesh *mesh = (CKMesh*)GetInputParameterValue<CKObject*>(beh,bbI_Mesh); VxVector pos = GetInputParameterValue<VxVector>(beh,bbI_Pos); VxQuaternion rot = GetInputParameterValue<VxQuaternion>(beh,bbI_Rot); pObjectDescr *descr = pFactory::Instance()->createPObjectDescrFromParameter(beh->GetInputParameter(bbI_PObject)->GetRealSource()); CK3dEntity *ref = (CK3dEntity*)GetInputParameterValue<CKObject*>(beh,bbI_Ref); //float density = GetInputParameterValue<float>(beh,bbI_Density); //float totalMass = GetInputParameterValue<float>(beh,bbI_TotalMass); result->addSubShape(mesh,*descr,ref,pos,rot); beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PBAddShapeCB // FullName: PBAddShapeCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBAddShapeCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPManagerDecl(); CKERROR CreatePManagerProto(CKBehaviorPrototype **pproto); int PManager(const CKBehaviorContext& behcontext); CKERROR PManagerCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_ReloadXML, }; #define BB_SSTART 0 BBParameter pInMapM[] = { BB_SPIN(bbI_ReloadXML,CKPGUID_STRING,"XML File","None"), }; #define gPIMAP pInMapM //************************************ // Method: FillBehaviorPManagerDecl // FullName: FillBehaviorPManagerDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPManagerDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PManager"); od->SetCategory("Physic/Manager"); od->SetDescription("Calls various functions in the manager."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x57295d90,0x11da3970)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePManagerProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePManagerProto // FullName: CreatePManagerProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePManagerProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PManager"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( PManagerCB ); BB_EVALUATE_SETTINGS(gPIMAP) proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PManager); *pproto = proto; return CK_OK; } //************************************ // Method: PManager // FullName: PManager // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PManager(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); BB_DECLARE_PIMAP; /************************************************************************/ /* retrieve settings state */ /************************************************************************/ BBSParameter(bbI_ReloadXML); /************************************************************************/ /* retrieve values */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// // load some settings from XML if(sbbI_ReloadXML) { CKSTRING xmlFile = GetInputParameterValue<CKSTRING>(beh,BB_IP_INDEX(bbI_ReloadXML)); pFactory::Instance()->reloadConfig(xmlFile); } } beh->ActivateOutput(0); return 0; } //************************************ // Method: PManagerCB // FullName: PManagerCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PManagerCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; } <file_sep>#ifndef _PhysicManager_H #define _PhysicManager_H #include "vtPhysXBase.h" #include "CKPhysicsManager.h" #include "pManagerTypes.h" #include "pWorldTypes.h" class xTime; /** \brief PhysicManager is a Virtools manager and acts as singleton object. Its responsible for : - maintaining of multiple worlds and all other physic objects - providing quick access to physic objects beyond the world boundaries - holding default parameters */ class MODULE_API PhysicManager : public CKPhysicManager { public: int sceneWasChanged; void _removeObjectsFromOldScene(CKScene *lastScene); CKScene* _isSceneObject(CK3dEntity *object); void _registerNewScene(CKScene*newScene); JointFeedbackListType m_JointFeedbackList; JointFeedbackListType& getJointFeedbackList() { return m_JointFeedbackList; } void setJointFeedbackList(JointFeedbackListType val) { m_JointFeedbackList = val; } void _cleanOrphanedJoints(); int physicFlags; int getPhysicFlags() const { return physicFlags; } void setPhysicFlags(int val) { physicFlags = val; } pTriggerArray mTriggers; pTriggerArray& getTriggers() { return mTriggers; } void _cleanTriggers(); pBodyList bodyListRemove; int _checkRemovalList(); pBodyList &getRemovalList(){ return bodyListRemove;} pBodyList bodyListCheck; int _checkListCheck(); pBodyList &getCheckList(){ return bodyListCheck;} void copyToAttributes(pObjectDescr src,CK3dEntity *dst); xTime *time; bool disablePhysics; bool checkPhysics; bool m_IsSimulating; pBodyList resetList; pBodyList& _getResetList(){return resetList;} pRestoreMap *restoreMap; pRestoreMap* _getRestoreMap(); //################################################################ // // Friends // bool checkCallbackSignature(CKBehavior *beh,int type,XString& errMessage); //################################################################ // // Constructors,initialization,registration // XString m_LastLogEntry; XString GetLastLogEntry() const { return m_LastLogEntry; } void SetLastLogEntry(XString val) { m_LastLogEntry = val; } //---------------------------------------------------------------- // //! \brief Constructors // PhysicManager(CKContext* ctx); void _construct(xBitSet flags = 0 ); //---------------------------------------------------------------- // //! \brief Initialization // int initPhysicEngine(int flags = 0); int initManager(int flags=0); int performInitialization(); void _initResources(int flags); //################################################################ // // Registration of attributes, custom structures, custom // enumeration and related // void _registerWatchers(CKContext*context);//not used void _unregisterWatchers();// not used //---------------------------------------------------------------- // //! \brief Attaches functions per object type. Most // types are registered by attributes. // void _RegisterAttributeCallbacks(); //---------------------------------------------------------------- // //! \brief Registration of attribute types // void _RegisterAttributes(); //---------------------------------------------------------------- // //! \brief Attribute help functions // int getAttributeTypeByGuid(CKGUID guid); int GetPAttribute(){ return att_physic_object;} int GetSSAttribute(){ return att_sleep_settings;} //---------------------------------------------------------------- // //! \brief Help function, not been used yet. // Stub void registerCustomAttribute(XString attributeName,int attributeType); typedef int (*ObjectConstructorFunction)(PhysicManager*, CK3dEntity*,int); void registerObjectByAttributeFunction(CK3dEntity *ent,int attributeID,ObjectRegisterFunction cFunc); AttributeFunctionArrayType& getAttributeFunctions() { return mAttributeFunctions; } void setAttributeFunctions(AttributeFunctionArrayType val) { mAttributeFunctions = val; } ObjectRegisterFunction getAttributeFunction(CKGUID attributeParameterGuid); void populateAttributeFunctions(); void cleanAttributePostObjects(); AttributeFunctionArrayType mAttributeFunctions; PostRegistrationArrayType mPostCleanAttributeObjects; CustomParametersArrayType mCustomStructures; CustomParametersArrayType& _getCustomStructures() { return mCustomStructures; } void setCustomStructures(CustomParametersArrayType val) { mCustomStructures = val; } PostRegistrationArrayType& getAttributePostObjects() { return mPostCleanAttributeObjects; } void setAttributePostObjects(PostRegistrationArrayType val) { mPostCleanAttributeObjects = val; } ObjectRegistration* getRegistrationTable(); //---------------------------------------------------------------- // //! \brief Registers all custom parameter, enumeration. // void _RegisterParameters(); void _RegisterJointParameters(); void _RegisterBodyParameters(); void _RegisterBodyParameterFunctions(); void _RegisterVehicleParameters(); void _RegisterWorldParameters(); //---------------------------------------------------------------- // //! \brief Help functions to register customer enumerations which // are changed by xml files. OnCKReset for instance, the default // xml file will be re-parsed and the enumerations become update. // // void _RegisterDynamicParameters(); void _RegisterDynamicEnumeration(XString file,XString enumerationName,CKGUID enumerationGuid,PFEnumStringFunction enumFunc,BOOL hidden); //################################################################ // // Parameter operations // //---------------------------------------------------------------- // //! \brief Registers all parameter operations at once. // void _RegisterParameterOperations(); void _RegisterParameterOperationsBody(); void _RegisterParameterOperationsJoint(); void _RegisterParameterOperationsMisc(); void _RegisterParameterOperationsVehicle(); void _RegisterParameterOperationsCollision(); //################################################################ // // VSL Support // void _RegisterVSL(); void _RegisterVSLCommon(); void _RegisterVSLJoint(); void _RegisterVSLRigidBody(); void _RegisterVSLVehicle(); void _RegisterVSLCloth(); //---------------------------------------------------------------- // //! \brief The fluid SDK is not finished and is intended as // additional component. #ifdef HAS_FLUID void _RegisterFluid_VSL(); #endif //---------------------------------------------------------------- // //! \brief Hooking building blocks, adds settings to built-in building blocks. // CKERROR _Hook3DBBs(); CKERROR _HookGenericBBs(); CKERROR _UnHookGenericBBs(); CKERROR _UnHook3DBBs(); //---------------------------------------------------------------- // //! \brief Destruction // ~PhysicManager(); void _destruct(xBitSet flags = 0); void _UnRegister(xBitSet flags=0); void _UnRegisterAttributeCallbacks(xBitSet flags=0); void _UnRegisterParameters(xBitSet flags=0); void cleanAll(); void destroyWorlds(); //################################################################ // // Settings // //---------------------------------------------------------------- // //! \brief XML related help functions // void reloadXMLDefaultFile(const char*fName); //---------------------------------------------------------------- // //! \brief Flags to track the state of the manager. // xBitSet& _getManagerFlags() { return mManagerFlags; } void _setManagerFlags(xBitSet val) { mManagerFlags = val; } bool isValid(); //---------------------------------------------------------------- // //! \brief Common parameters for a world (NXScene) // pWorldSettings * getDefaultWorldSettings(){ return mDefaultWorldSettings; } void setDefaultWorldSettings(pWorldSettings * val) { mDefaultWorldSettings = val; } //---------------------------------------------------------------- // //! \brief Dongle related functions and members // XString _getConfigPath(); int DongleHasBasicVersion; int DongleHasAdvancedVersion; static void makeDongleTest(); //################################################################ // // Periodic functions, called by frame. // void checkWorldsByType(CKGUID attributeParameterType); //################################################################ // // Misc functions // //---------------------------------------------------------------- // //! \brief Logging // pLogger* getLogger(){ return mLogger; } void setLogger(pLogger* val) { mLogger = val; } void enableLogLevel(int type,int verbosity,int value); //################################################################ // // PhysX related helpers // NxPhysicsSDK* getPhysicsSDK(){ return mPhysicsSDK; } void setPhysicsSDK(NxPhysicsSDK* val) { mPhysicsSDK = val; } int getHWVersion(); int getNbPPUs(); int getInternalVersion(int& apiRev, int& descRev, int& branchId); //################################################################ // // Object helpers // int getNbObjects(int flags =0); //---------------------------------------------------------------- // //! \brief World related pWorldMap* getWorlds(){ return m_Worlds; } pWorld *getWorld(CK_ID _o); pWorld *getWorld(CK3dEntity *_o,CK3dEntity *body=NULL); pWorld *getWorld(int index =0); pVehicle* getVehicle(CK3dEntity*bodyReference); pWheel2* getWheel(CK3dEntity*wheelReference); pWorld *getWorldByBody(CK3dEntity*ent); pWorld *getWorldByShapeReference(CK3dEntity *shapeReference); int getNbWorlds(); void deleteWorld(CK_ID _o); void setWorlds(pWorldMap *val) { m_Worlds = val; } float timer; void advanceTime(float time); pWorld * getDefaultWorld() { return m_DefaultWorld; } void setDefaultWorld(pWorld * val) { m_DefaultWorld = val; } /************************************************************************************************/ /** @name Joints */ //@{ /** \brief Finds a joint object within all existing worlds, identified by two references and its type. \param[in] CK3dEntity * referenceA , r: the first object participating in the constraint. This argument must be non-zero.<br> - <b>Range:</b> [object range) <br> - <b>Default:</b> NULL <br> \param[in] CK3dEntity * referenceB , r: the second object participating in the constraint. This can be NULL because joint constraints can be created between a rigid body and the global world frame.<br> - <b>Range:</b> [object range) <br> - <b>Default:</b> NULL <br> \param[in] JType type, r: an additional hint to find the right joint object. Notice that one rigid body can have 1:n joints so it makes sense to pass the type to this function. By default its returning the first found joint on the given reference objects. <br> - <b>Range:</b> [joint type range) <br> - <b>Default:</b> #JT_Any <br> \return pJoint* @see deleteJoint() */ pJoint*getJoint(CK3dEntity*referenceA,CK3dEntity*referenceB=NULL,JType type=JT_Any); /** \if internal2 \brief Checks 3D entities for attached joint attributes. If so, its registering the new constraint. \return void \endif */ void _checkObjectsByAttribute(CKScene *newScene = NULL); int _checkResetList(); //@} void checkWorlds(); void checkClothes(); void checkBodies(); void _RegisterObjectsByAttribute(); void createWorlds(int flags); void destroy(); BOOL checkDemo(CK3dEntity*); pFactory * getCurrentFactory(){ return m_currentFactory; } void setCurrentFactory(pFactory * val) { m_currentFactory = val; } /************************************************************************/ /* xml document access */ /************************************************************************/ TiXmlDocument* loadDefaults(XString filename); TiXmlDocument* getDefaultConfig() const { return m_DefaultDocument; } void setDefaultConfig(TiXmlDocument* val) { m_DefaultDocument = val; } /************************************************************************/ /* RigidBody */ /************************************************************************/ pRigidBody *getBody(CK3dEntity*ent,bool lookInSubshapes=false); pRigidBody *getBody(CK3dEntity*ent,pWorld* world); pRigidBody *getBody(const char*name,int flags=0); NxShape *getSubShape(CK3dEntity*referenceObject); /** \brief Returns the givens entity's rigid body object to which the sub shape belongs to. \param[in] CK3dEntity * ent ,the entity r: This argument must be non-zero.<br> - <b>Range:</b> [object range) <br> - <b>Default:</b> NULL <br> \return pRigidBody* @see deleteJoint() */ pRigidBody* isSubShape(CK3dEntity*ent); NxCCDSkeleton *getCCDSkeleton(CKBeObject *shapeReference); void doInit(); /************************************************************************/ /* Clothes : */ /************************************************************************/ pCloth *getCloth(CK_ID entityID); /************************************************************************/ /* Fluids : */ /************************************************************************/ pFluid *getFluid(CK3dEntity *entityReference); pFluidEmitter *getFluidEmitter(CK3dEntity *entityReferene); /** \brief Function that lets you set global simulation parameters. Returns false if the value passed is out of range for usage specified by the enum. <b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected. See #pSDKParameter for a description of parameters support by hardware. \param[in] paramEnum Parameter to set. See #pSDKParameter \param[in] paramValue The value to set, see #pSDKParameter for allowable values. \return False if the parameter is out of range. \note All parameters are available in the variable manager too. @see pSDKParameter getParameter */ void setParameter(pSDKParameter parm,float value); /** \brief Function that lets you query global simulation parameters. See #pSDKParameter for a description of parameters support by hardware. \param[in] paramEnum The Parameter to retrieve. \return The value of the parameter. @see setParameter pSDKParameter */ float getParameter(pSDKParameter parm,float value); void bindVariables(); void unBindVariables(); void setPSDKParameters(pSDKParameters&param); //---------------------------------------------------------------- // // character controller // UserAllocator * getUserAllocator() const { return mUserAllocator; } void setUserAllocator(UserAllocator * val) { mUserAllocator = val; } NxControllerManager* getControllerManager() const { return mControllerManager; } void setControllerManager(NxControllerManager* val) { mControllerManager = val; } void _createControllerManager(); void _releaseControllerManager(); private : UserAllocator *mUserAllocator; NxControllerManager* mControllerManager; TiXmlDocument* m_DefaultDocument; pWorld *m_DefaultWorld; pFactory *m_currentFactory; pWorldMap* m_Worlds; NxPhysicsSDK* mPhysicsSDK; pLogger*mLogger; pWorldSettings *mDefaultWorldSettings; xBitSet mManagerFlags; NxRemoteDebugger* mRemoteDebugger; pSDKParameters m_SDKParameters; pRemoteDebuggerSettings mRemoteDebuggerSettings; pRemoteDebuggerSettings& getRemoteDebuggerSettings() { return mRemoteDebuggerSettings; } void setRemoteDebuggerSettings(pRemoteDebuggerSettings val) { mRemoteDebuggerSettings = val; } IParameter *mIParameter; public: int att_physic_object; int att_hull_type; int att_mass; int att_surface_props;int att_physic_limit; BOOL m_DelOnReset; int att_world_object;int att_sleep_settings;int att_damping;int att_collMask;int att_update_world_flags;int att_update_body_flags; int att_heightField;int att_JBall;int att_JFixed;int att_JHinge;int att_JHinge2;int att_JSlider;int att_JUniversal;int att_JMotor; int att_wheelDescr; int att_clothDescr; int att_trigger; int att_deformable; int att_capsule; float mLastStepTime; int _LogInfo; int _LogTrace; int _LogWarnings; int _LogErrors; int _LogToConsole; public : float getLastTimeStep(int flags); pSDKParameters& getSDKParameters() { return m_SDKParameters; } void setSDKParameters(pSDKParameters val) { m_SDKParameters = val; } NxRemoteDebugger* getRemoteDebugger(); void Update(); void update(float stepsize); static PhysicManager *GetInstance(); static CKContext *GetContext(); static PhysicManager * Cast(CKBaseManager* iM) { return GetInstance();} CKERROR OnCKInit(); CKERROR PostClearAll(); CKERROR PreSave(); CKERROR OnCKReset(); CKERROR OnCKEnd(); CKERROR PreProcess(); CKERROR SequenceToBeDeleted(CK_ID *objids,int count); CKERROR OnCKPlay(); CKERROR OnCKPause(); CKERROR PostProcess(); CKERROR SequenceAddedToScene(CKScene *scn,CK_ID *objids,int count); CKERROR SequenceRemovedFromScene(CKScene *scn,CK_ID *objids,int count); CKERROR PreLaunchScene(CKScene* OldScene,CKScene* NewScene); CKERROR PostLaunchScene(CKScene* OldScene,CKScene* NewScene); CKERROR SequenceDeleted(CK_ID *objids,int count); CKERROR PreClearAll(); CKERROR OnPostCopy(CKDependenciesContext& context); CKERROR PostLoad(); int _migrateOldCustomStructures(CKScene *scnene); //--- Called to save manager data. return NULL if nothing to save... virtual CKStateChunk* SaveData(CKFile* SavedFile); void _saveUserEnumeration(CKStateChunk *chunk,CKFile* SavedFile); virtual CKERROR LoadData(CKStateChunk *chunk,CKFile* LoadedFile); void _loadUserEnumeration(CKStateChunk *chunk,CKFile* LoadedFile); //--- Called at the end of a save operation. CKERROR PostSave(); float getLastDeltaTime(){return mLastStepTime;} virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_PreLaunchScene| CKMANAGER_FUNC_PostLaunchScene| CKMANAGER_FUNC_OnSequenceRemovedFromScene| CKMANAGER_FUNC_OnSequenceDeleted| CKMANAGER_FUNC_OnSequenceAddedToScene| CKMANAGER_FUNC_PreClearAll| CKMANAGER_FUNC_PostClearAll| CKMANAGER_FUNC_OnSequenceToBeDeleted| CKMANAGER_FUNC_OnCKPlay| CKMANAGER_FUNC_OnCKPause| CKMANAGER_FUNC_OnCKInit| CKMANAGER_FUNC_PreSave| CKMANAGER_FUNC_PostLoad| CKMANAGER_FUNC_OnPostCopy| CKMANAGER_FUNC_PostSave| CKMANAGER_FUNC_OnCKReset| CKMANAGER_FUNC_PostProcess| CKMANAGER_FUNC_PreProcess| CKMANAGER_FUNC_OnCKEnd; } int processOptions; virtual int& getProcessOptions() { return processOptions; } virtual void setProcessOptions(int val) { processOptions = val; } }; #define GetPMan() PhysicManager::GetInstance() #define ctx() PhysicManager::GetInstance()->GetContext() #define lastStepTimeSec GetPMan()->GetContext()->GetTimeManager()->GetLastDeltaTimeFree() * 0.001f #define lastStepTimeMS GetPMan()->GetContext()->GetTimeManager()->GetLastDeltaTimeFree() #endif <file_sep>--/************************************************************************/ --Build/Compiler Setup. --/************************************ --Internal Paths Substion : FROOT = "../../" DROOT = "../" DDEPS = DROOT.."Dependencies/" DDOCS = DROOT.."Docs" D_INCLUDE = DROOT.."SDK/Include/" D_LIBS = DROOT.."SDK/Lib/" D_SRC = DROOT.."SDK/Src/" D_BB = DROOT.."SDK/Behaviors/" D_DX = DDEPS.."dx/" D_BASE_INC = "../../usr/include/" D_VT_BASE_INC = D_BASE_INC.."virtools/" D_BASE_SRC = "../../usr/src/" D_BASE_VT_SRC = D_BASE_SRC.."virtools/" D_DOCS_PAGES = DROOT.."Doc/pages/" D_READER_SRC = D_SRC.."xmlstream/" D_UI_SRC = D_SRC.."Interface/" D_PHYSX = DDEPS.."NVIDIA.PhysX.SDK/" D_NXSTREAM = D_PHYSX.."Tools/NxuStream2/" D_NXCOMMON = D_PHYSX.."SDKs/Common/" D_NXCHARACTER = D_PHYSX.."SDKs/NxCharacter/" D_TINYXML = DDEPS.."TinyXML/" D_CORE_INCLUDES = { DROOT.."SDK/Include/Core/Common"; DROOT.."SDK/Include/Core/Manager"; DROOT.."SDK/Include/Core/pWorld"; DROOT.."SDK/Include/Core/pCloth"; DROOT.."SDK/Include/Core/pJoint"; DROOT.."SDK/Include/Core/pVehicle"; DROOT.."SDK/Include/Core/pRigidBody"; DROOT.."SDK/Include/Core/pFactory"; DROOT.."SDK/Include/Core/pFluid"; DROOT.."SDK/Include/Core/pSerializer"; DROOT.."SDK/Include/Core/pCharacter"; DROOT.."SDK/Include/Core"; DROOT.."SDK/Include/xmlstream"; } D_STD_INCLUDES = { "../Shared"; "../../usr/include"; "../../usr/include/virtools"; } D_PHYSX_INCLUDES = { D_PHYSX.."SDKs/Foundation/include"; D_PHYSX.."SDKs/Physics/include"; D_PHYSX.."SDKs/Physics/include/cloth"; D_PHYSX.."SDKs/Physics/include/fluids"; D_PHYSX.."SDKs/Physics/include/softbody"; D_PHYSX.."SDKs/NxVehicle"; D_PHYSX.."SDKs/Cooking/include"; D_PHYSX.."SDKs/PhysXLoader/include"; D_PHYSX.."SDKs/Common"; D_PHYSX.."SDKs/NxCharacter/include"; D_PHYSX.."Tools/NxuStream2"; } F_VT_STD_INC = { D_VT_BASE_INC.."**.h"; DROOT.."SDK/Include/xmlstream/XLoader.h"; } F_BASE_STD_INC = { D_BASE_INC.."BaseMacros.h"; D_BASE_INC.."DllTools.h"; D_BASE_INC.."xBitSet.h"; D_BASE_INC.."xLogger.h"; D_BASE_INC.."uxString.h"; D_BASE_INC.."pch.h"; } F_BASE_VT_SRC = { D_BASE_VT_SRC.."vtTools.cpp"; } F_BASE_SRC = { D_BASE_SRC.."xLogger.cpp"; D_BASE_SRC.."xAssertion.cpp"; D_BASE_SRC.."xAssertCustomization.cpp"; D_BASE_SRC.."ConStream.cpp"; } F_EXTRA_BB_SRC = { D_BASE_VT_SRC.."Behaviors/generic/GetSubBBId.cpp"; D_BASE_VT_SRC.."Behaviors/joystick/hasFFe.cpp"; D_BASE_VT_SRC.."Behaviors/joystick/JSetXYForce.cpp"; } F_SHARED_SRC = { "../Shared/*.cpp"; } DEF_STD_DIRECTIVES = { "WIN32";"_WINDOWS"; } DEF_PHYSX_DIRECTIVES = { "NOMINMAX";"_USRDLL"; } --/************************************ --~ Virtools SDK Paths. All files have to be inside the module path ! DEV35DIR=DDEPS.."vt/Dev35/" --DEV40DIR="x:/sdk/dev4/SDK/" DEV40DIR=DDEPS.."vt/Dev40/" DEV41DIR=DDEPS.."vt/Dev41/" DEV5DIR=DDEPS.."vt/Dev5/" --~ Virtools Real Paths. This paths will be used as deployment targets due the post build command DEV_40_BIN="x:\\sdk\\dev4" DEV_41_BIN="x:\\sdk\\dev41" DEV_35_BIN="x:\\sdk\\dev35" DEV_5_BIN="x:\\sdk\\dev5" OUTPUT_PATH_OFFSETT_TO_PROJECTFILES ="../../Bin" OUTPUT_PATH_OFFSETT_TO_PROJECTFILES_MINUS_ONE = "../Bin" OUTPUT_PATH_OFFSETT_TO_INTERNAL_LIBS="../SDK/Lib/" OUTPUT_PATH_OFFSETT_TO_TMP="../TEMP" --********************************* --"Control how the outputs will be named and odererd in a filesystem" PSTORE_PER_VS_VERSION = true PSTORE_PER_VT_VERSION = true PSTORE_PER_CONFIG= false PSTORE_NAME_VS_VERSION = false PSTORE_NAME_VT_VERSION = true PSTORE_NAME_CONFIG= false --/************************************ --Internal Path Cache : MERGED_DST_PATH = OUTOUT_PATH_OFFSETT_TO_PROJECTFILES --/************************************************************************/ --Feauteres : F_VC_DOC_PROJECT = "true" F_VC_PREMAKE_PROJECT = "true" --/************************************************************************/ --POST COMPILE ROUTINES : DEPLOY_TO_DEV = 1 DEPLOY_TO_ZIP = 0 --/************************************************************************/ <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "Stream.h" #include "cooking.h" #include "NXU_helper.h" // NxuStream helper functions. #include "NXU_PhysicsInstantiator.h" #include "IParameter.h" #include "xDebugTools.h" pRigidBody*pFactory::cloneRigidBody(CK3dEntity *src,CK3dEntity *dst,CKDependencies *deps,int copyFlags,int bodyFlags/* =0 */) { //src->Rest pRigidBody *result = GetPMan()->getBody(dst); pRigidBody *srcBody = GetPMan()->getBody(src); CK3dEntity *referenceObject = dst; XString errMsg; pObjectDescr oDescr; //---------------------------------------------------------------- // // sanity checks // #ifdef _DEBUG assert(src); assert(dst); #endif // _DEBUG if (!(copyFlags & PB_CF_PHYSICS)) { errMsg.Format("Nothing to copy, aborting"); xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,errMsg.Str()); return NULL; } //iAssertW(!result,"","Object :%s already physicalized"); //---------------------------------------------------------------- // // fill object description // if (!result && IParameter::Instance()->copyTo(oDescr,src,copyFlags)) { pWorld *world = GetPMan()->getWorld(oDescr.worlReference) ? GetPMan()->getWorld(oDescr.worlReference) : GetPMan()->getDefaultWorld(); if(world) { if ( (copyFlags && PB_CF_OVRRIDE_BODY_FLAGS) ) oDescr.flags = (BodyFlags)bodyFlags; //now create the final rigid body : result = pFactory::Instance()->createRigidBody(dst,oDescr); } } if (!result){ xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"cloning failed"); return NULL; } //---------------------------------------------------------------- // // clone joints // if ( (copyFlags & PB_CF_JOINTS) ) { pFactory::cloneJoints(src,dst,copyFlags); } //---------------------------------------------------------------- // // copy velocities // if ( (copyFlags & PB_CF_VELOCITIES) ) { NxActor *actorSrc = srcBody->getActor(); NxActor *actorDst = result->getActor(); actorDst->setLinearVelocity( actorSrc->getLinearVelocity() ); actorDst->setAngularVelocity( actorSrc->getAngularVelocity() ); } //---------------------------------------------------------------- // // copy forces // if ( (copyFlags & PB_CF_FORCE) ) { NxActor *actorSrc = srcBody->getActor(); NxActor *actorDst = result->getActor(); actorDst->setLinearMomentum( actorSrc->getLinearMomentum() ); actorDst->setAngularMomentum( actorSrc->getAngularMomentum() ); } //---------------------------------------------------------------- // // copy sub shapes if : // // "Copy Children In Dependencies" && // ( copyFlags::OverrideBodyFlags & hierarchy && newBodyFlags & hierarchy ) || // ( oldBodyFlags & hierarchy ) if ( ((*deps->At(CKCID_3DENTITY)) & CK_DEPENDENCIES_COPY_3DENTITY_CHILDREN) && ( (( copyFlags & PB_CF_OVRRIDE_BODY_FLAGS ) && (bodyFlags & BF_Hierarchy)) || ( oDescr.flags & BF_Hierarchy) ) ) { int dCount = dst->GetChildrenCount(); CK3dEntity* subEntity = NULL; while (subEntity= dst->HierarchyParser(subEntity) ) { if (subEntity==dst) continue; CK3dEntity *orginalObject = findSimilarInSourceObject(src,dst,subEntity); if (orginalObject) { iAssertW(cloneShape(orginalObject,subEntity,dst,copyFlags,bodyFlags),"","clone of sub shape failed"); } } } return NULL; } pRigidBody*pFactory::createRigidBody(CK3dEntity *referenceObject,pObjectDescr& oDescr) { CK3dEntity *worldReferenceObject = (CK3dEntity*)GetPMan()->GetContext()->GetObject(oDescr.worlReference); pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); if (!world) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"world object invalid, setting to default world"); world = GetPMan()->getDefaultWorld(); } pRigidBody*result = world->getBody(referenceObject); // create minimum object result = createBody(referenceObject,worldReferenceObject); if (!result) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed"); return NULL; } result->setWorld(world); result->setFlags(oDescr.flags); result->setHullType(oDescr.hullType); if (oDescr.density <= 0.001f) oDescr.density = 1.0f; if (oDescr.skinWidth <= 0.001f) oDescr.skinWidth = 0.025f; result->setDensity(oDescr.density); bool hierarchy = (oDescr.flags & BF_Hierarchy); bool isDeformable = oDescr.flags & BF_Deformable; bool trigger = oDescr.flags & BF_TriggerShape; //################################################################ // // Deformable ? // pCloth *cloth = NULL; pClothDesc cDescr; if (isDeformable) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"deformable feature disabled in this release"); return NULL; cDescr.setToDefault(); cDescr.worldReference = worldReferenceObject->GetID(); if ( result->getFlags() & BF_Gravity ) { cDescr.flags |= PCF_Gravity; } if ( result->getFlags() & BF_Collision ) { } if (!cloth) { cloth = pFactory::Instance()->createCloth(referenceObject,cDescr); if (!cloth) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : factory object failed !"); } } } float density = oDescr.density; VxVector box_s= BoxGetZero(referenceObject); VxMatrix v_matrix ; VxVector position,scale; VxQuaternion quat; v_matrix = referenceObject->GetWorldMatrix(); Vx3DDecomposeMatrix(v_matrix,quat,position,scale); NxVec3 pos = pMath::getFrom(position); NxQuat rot = pMath::getFrom(quat); //---------------------------------------------------------------- // // Fill NxActorDescr // NxActorDesc actorDesc;actorDesc.setToDefault(); NxBodyDesc bodyDesc;bodyDesc.setToDefault(); // // Fix parameters to default values actorDesc.density = oDescr.density; //skin width if (oDescr.skinWidth<=0.0001f) oDescr.skinWidth=0.025f; float radius = result->GetVT3DObject()->GetRadius(); //---------------------------------------------------------------- // // Create the physic mesh. Externalizing this procedure will corrupt the // actor description object. // switch(oDescr.hullType) { ////////////////////////////////////////////////////////////////////////// case HT_Box: { NxBoxShapeDesc shape; if (! (oDescr.flags & BF_Deformable) ) { shape.dimensions = pMath::getFrom(box_s)*0.5f; } shape.density = density; shape.skinWidth = oDescr.skinWidth; actorDesc.shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Sphere: { NxSphereShapeDesc shape; if (! (oDescr.flags & BF_Deformable) ) { shape.radius = radius; } shape.density = density; shape.skinWidth = oDescr.skinWidth; actorDesc.shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Mesh: { NxTriangleMeshDesc myMesh; myMesh.setToDefault(); pFactory::Instance()->createMesh(result->getWorld()->getScene(),result->GetVT3DObject()->GetCurrentMesh(),myMesh); NxTriangleMeshShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); return false; } MemoryWriteBuffer buf; status = CookTriangleMesh(myMesh, buf); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); return false; } shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); shape.density = density; shape.group = oDescr.collisionGroup; actorDesc.shapes.pushBack(&shape); shape.skinWidth = oDescr.skinWidth; CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_ConvexMesh: { if (result->GetVT3DObject()->GetCurrentMesh()) { if (result->GetVT3DObject()->GetCurrentMesh()->GetVertexCount()>=256 ) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshes allowed, by Ageia!"); return false; } }else { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); return false; } NxConvexMeshDesc myMesh; myMesh.setToDefault(); pFactory::Instance()->createConvexMesh(result->getWorld()->getScene(),result->GetVT3DObject()->GetCurrentMesh(),myMesh); NxConvexShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); return false; } MemoryWriteBuffer buf; status = CookConvexMesh(myMesh, buf); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); return false; } shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); shape.density = density; actorDesc.shapes.pushBack(&shape); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; int h = shape.isValid(); CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_ConvexCylinder: { NxConvexShapeDesc shape; pConvexCylinderSettings &cSettings = oDescr.convexCylinder; iAssertW( (oDescr.mask & OD_ConvexCylinder),pFactory::Instance()->findSettings(cSettings,result->GetVT3DObject()), "Hull type has been set to convex cylinder but there is no descriptions passed or activated in the pObjectDescr::mask.Trying object attributes...."); if (cSettings.radius.reference) cSettings.radius.evaluate(cSettings.radius.reference); if (cSettings.height.reference) cSettings.height.evaluate(cSettings.height.reference); iAssertW( cSettings.isValid() , cSettings.setToDefault(),""); cSettings.radius.value = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); cSettings.height.value = cSettings.height.value > 0.0f ? cSettings.height.value : (box_s.v[cSettings.height.referenceAxis] * 0.5f); bool resultAssert = true; iAssertWR( pFactory::Instance()->_createConvexCylinderMesh(&shape,cSettings,result->GetVT3DObject()),"",resultAssert); shape.density = density; shape.skinWidth = oDescr.skinWidth; actorDesc.shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Capsule: { NxCapsuleShapeDesc shape; pCapsuleSettingsEx &cSettings = oDescr.capsule; if (!( oDescr.mask & OD_Capsule) ) { // try over attribute : pFactory::Instance()->findSettings(cSettings,result->GetVT3DObject()); } bool resultAssert = true; if (cSettings.radius.reference) cSettings.radius.evaluate(cSettings.radius.reference); if (cSettings.height.reference) cSettings.height.evaluate(cSettings.height.reference); iAssertWR(cSettings.isValid(),cSettings.setToDefault(),resultAssert); shape.radius = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); shape.height = cSettings.height.value > 0.0f ? (cSettings.height.value-( 2*shape.radius)) : (box_s.v[cSettings.height.referenceAxis] - ( 2*shape.radius)) ; shape.density = density; shape.skinWidth = oDescr.skinWidth; actorDesc.shapes.pushBack(&shape); break; } case HT_Wheel: { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Wheel shape can be sub shape only!"); return false; } } if ( !isDeformable) { actorDesc.globalPose.t = pos; actorDesc.globalPose.M = rot; } //---------------------------------------------------------------- // // Create the final NxActor // if (oDescr.flags & BF_Moving) actorDesc.body = &bodyDesc; NxActor *actor = world->getScene()->createActor(actorDesc); if (!actor) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); delete result; return NULL; } //---------------------------------------------------------------- // // // result->setActor(actor); actor->setName(referenceObject->GetName()); result->SetVT3DObject(referenceObject); actor->userData= result; ////////////////////////////////////////////////////////////////////////// //Deformable : if (isDeformable && cloth) { pDeformableSettings dSettings; dSettings.ImpulsThresold = 50.0f; dSettings.PenetrationDepth= 0.1f ; dSettings.MaxDeform = 2.0f; CKParameterOut *poutDS = referenceObject->GetAttributeParameter(GetPMan()->att_deformable); if (poutDS) { pFactory::Instance()->copyTo(dSettings,poutDS); } cloth->attachToCore(referenceObject,dSettings.ImpulsThresold,dSettings.PenetrationDepth,dSettings.MaxDeform); result->setCloth(cloth); } ////////////////////////////////////////////////////////////////////////// // // Extra settings : // if (result->getFlags() & BF_Moving) { VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&oDescr.massOffsetLinear); actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); } if (result->getFlags() & BF_Kinematic) { result->setKinematic(true); } if (result->getFlags() & BF_Moving ) { result->enableGravity(result->getFlags() & BF_Gravity); } if (result->getFlags() & BF_Sleep ) { result->setSleeping(true); } if (oDescr.worlReference == 0) { if (GetPMan()->getDefaultWorld()) { oDescr.worlReference = GetPMan()->getDefaultWorld()->getReference()->GetID(); } } //---------------------------------------------------------------- // // store mesh meta info in the first main mesh // NxShape *shape = result->getShapeByIndex(); if (shape) { pSubMeshInfo *sInfo = new pSubMeshInfo(); sInfo->entID = referenceObject->GetID(); sInfo->refObject = (CKBeObject*)referenceObject; shape->userData = (void*)sInfo; result->setMainShape(shape); shape->setName(referenceObject->GetName()); } result->enableCollision( (result->getFlags() & BF_Collision), referenceObject ); //---------------------------------------------------------------- // // Adjust pivot // if ( (oDescr.mask & OD_Pivot) ) { iAssertW1( oDescr.pivot.isValid(),oDescr.pivot.setToDefault()); result->updatePivotSettings(oDescr.pivot,referenceObject); }else if(pFactory::Instance()->findSettings(oDescr.collision,referenceObject)) result->updatePivotSettings(oDescr.pivot,referenceObject); //---------------------------------------------------------------- // // Optimization // if ((oDescr.mask & OD_Optimization )) { iAssertW1( oDescr.optimization.isValid(),oDescr.optimization.setToDefault()); result->updateOptimizationSettings(oDescr.optimization); } else{ if(pFactory::Instance()->findSettings(oDescr.optimization,referenceObject)) { iAssertW1( oDescr.optimization.isValid(),oDescr.optimization.setToDefault()); result->updateOptimizationSettings(oDescr.optimization); } } //---------------------------------------------------------------- // // Collision // if ((oDescr.mask & OD_Collision)) result->updateCollisionSettings(oDescr.collision,referenceObject); else if(pFactory::Instance()->findSettings(oDescr.collision,referenceObject)) result->updateCollisionSettings(oDescr.collision,referenceObject); //---------------------------------------------------------------- // // Material // NxMaterialDesc *materialDescr = NULL; NxMaterial *material = NULL; pMaterial &bMaterial = oDescr.material; if (oDescr.mask & OD_Material) { result->updateMaterialSettings(bMaterial,referenceObject); }else { bool hasMaterial = pFactory::Instance()->findSettings(bMaterial,referenceObject); if (!hasMaterial) { if (world->getDefaultMaterial()) { int z = (int)world->getDefaultMaterial()->userData; shape->setMaterial(world->getDefaultMaterial()->getMaterialIndex()); } }else{ iAssertW( bMaterial.isValid(),bMaterial.setToDefault(), "Material settings were still invalid : "); NxMaterialDesc nxMatDescr; pFactory::Instance()->copyTo(nxMatDescr,bMaterial); NxMaterial *nxMaterial = world->getScene()->createMaterial(nxMatDescr); if (nxMaterial) { shape->setMaterial(nxMaterial->getMaterialIndex()); } } } xLogger::xLog(ELOGINFO,E_LI_MANAGER,"Rigid body creation successful : %s",referenceObject->GetName()); result->setInitialDescription(&oDescr); //---------------------------------------------------------------- // // Hierarchy mode fix : // if ( (oDescr.flags & BF_Hierarchy) ) oDescr.hirarchy = true; if ( oDescr.hirarchy ) oDescr.flags << BF_Hierarchy; if ( (!oDescr.hirarchy) || !(oDescr.flags & BF_Hierarchy) ) return result; //---------------------------------------------------------------- // // Parse hirarchy // CK3dEntity* subEntity = NULL; while (subEntity= referenceObject->HierarchyParser(subEntity) ) { pObjectDescr *subDescr = NULL; int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); if (subEntity->HasAttribute(attTypePBSetup)) { subDescr = new pObjectDescr(); CKParameterOut *par = subEntity->GetAttributeParameter(attTypePBSetup); IParameter::Instance()->copyTo(subDescr,par); subDescr->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; } if (!subDescr) continue; if (subDescr->flags & BF_SubShape) { ////////////////////////////////////////////////////////////////////////// // // Regular Mesh : // if (subDescr->hullType != HT_Cloth) { //result->addSubShape(NULL,*subDescr,subEntity); VxQuaternion refQuad;subEntity->GetQuaternion(&refQuad,referenceObject); VxVector relPos;subEntity->GetPosition(&relPos,referenceObject); shape = pFactory::Instance()->createShape(referenceObject,*subDescr,subEntity,subEntity->GetCurrentMesh(),relPos,refQuad); //NxShape *shape = result->getSubShape(subEntity); if (shape) { //---------------------------------------------------------------- // // check for collision setup // //try to get get from child attributes first /* if(pFactory::Instance()->findSettings(subDescr->collision,subEntity)) { result->updateCollisionSettings(subDescr->collision,subEntity); continue; } if ( (subDescr->mask & OD_Optimization) ) { //if (pFactory::Instance()->findSettings(subDescr->collision,subEntity)) result->updateCollisionSettings(subDescr->collision,subEntity); } else if ( (oDescr.mask & OD_Optimization) ) { result->updateCollisionSettings(oDescr.collision,subEntity); }else if(pFactory::Instance()->findSettings(subDescr->collision,subEntity)) { result->updateCollisionSettings(subDescr->collision,subEntity); } */ } } ////////////////////////////////////////////////////////////////////////// // // Cloth Mesh : // if (subDescr->hullType == HT_Cloth) { //pClothDesc *cloth = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); } } } //---------------------------------------------------------------- // // Adjust mass // //---------------------------------------------------------------- // // Collision // if ((oDescr.mask & OD_Mass)) result->updateMassSettings(oDescr.mass); else if(pFactory::Instance()->findSettings(oDescr.mass,referenceObject)) result->updateMassSettings(oDescr.mass); return result; nothing: return result; } pRigidBody*pFactory::createCapsule(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags) { pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); pRigidBody*result = world->getBody(referenceObject); if(result) { result->destroy(); delete result; result = NULL; } // we create our final body in the given world : result = createBody(referenceObject,worldReferenceObject); if (result) { result->setWorld(world); using namespace vtTools::AttributeTools; result->setFlags(descr->flags); result->setHullType(descr->hullType); result->setDataFlags(0x000); result->checkDataFlags(); if (result->getSkinWidth()==-1.0f) { result->setSkinWidth(0.01f); } VxMatrix v_matrix ; VxVector position,scale; VxQuaternion quat; v_matrix = referenceObject->GetWorldMatrix(); Vx3DDecomposeMatrix(v_matrix,quat,position,scale); VxVector box_s= BoxGetZero(referenceObject); NxVec3 pos = pMath::getFrom(position); NxQuat rot = pMath::getFrom(quat); float density = result->getDensity(); float radius = referenceObject->GetRadius(); if (referenceObject->GetRadius() < 0.001f ) { radius = 1.0f; } ////////////////////////////////////////////////////////////////////////// //create actors description NxActorDesc actorDesc;actorDesc.setToDefault(); NxBodyDesc bodyDesc;bodyDesc.setToDefault(); ////////////////////////////////////////////////////////////////////////// NxMaterialDesc *materialDescr = NULL; NxMaterial *material = NULL; if (isFlagOn(result->getDataFlags(),EDF_MATERIAL_PARAMETER)) { NxMaterialDesc entMatNull;entMatNull.setToDefault(); NxMaterialDesc *entMat = createMaterialFromEntity(referenceObject); material = world->getScene()->createMaterial(entMatNull); material->loadFromDesc(*entMat); result->setMaterial(material); }else{ if (world->getDefaultMaterial()) { result->setMaterial(world->getDefaultMaterial()); } } ////////////////////////////////////////////////////////////////////////// NxCapsuleShapeDesc capsuleShape; if ( creationFlags & E_OFC_DIMENSION ) { capsuleShape.height = box_s.y - ((box_s.x)); capsuleShape.radius = box_s.x*0.5f; } capsuleShape.density = descr->density; capsuleShape.materialIndex = result->getMaterial()->getMaterialIndex(); //shape.localPose.t = pMath::getFrom(shapeOffset); if (result->getSkinWidth()!=-1.0f) capsuleShape.skinWidth = result->getSkinWidth(); actorDesc.shapes.pushBack(&capsuleShape); ////////////////////////////////////////////////////////////////////////// //dynamic object ? if (result->getFlags() & BF_Moving){ actorDesc.body = &bodyDesc; } else actorDesc.body = NULL; ////////////////////////////////////////////////////////////////////////// //set transformations actorDesc.density = descr->density; if (creationFlags & E_OFC_POSITION) { actorDesc.globalPose.t = pos; } if (creationFlags & E_OFC_POSITION) { actorDesc.globalPose.M = rot; } ////////////////////////////////////////////////////////////////////////// //create the actor int v = actorDesc.isValid(); NxActor *actor = world->getScene()->createActor(actorDesc); if (!actor) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); delete result; return NULL; } ////////////////////////////////////////////////////////////////////////// //set additional settings : result->setActor(actor); actor->setName(referenceObject->GetName()); actor->userData= result; if (result->getFlags() & BF_Moving) { VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&result->getMassOffset()); actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); } if (result->getFlags() & BF_Kinematic) { actor->raiseBodyFlag(NX_BF_KINEMATIC); } result->enableCollision((result->getFlags() & BF_Collision)); if (result->getFlags() & BF_Moving) { if (!(result->getFlags() & BF_Gravity)) { actor->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); } } NxShape *shape = result->getShapeByIndex(); if (shape) { pSubMeshInfo *sInfo = new pSubMeshInfo(); sInfo->entID = referenceObject->GetID(); sInfo->refObject = (CKBeObject*)referenceObject; shape->userData = (void*)sInfo; result->setMainShape(shape); shape->setName(referenceObject->GetName()); } } return result; } pRigidBody*pFactory::createBox(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags) { pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); pRigidBody*result = world->getBody(referenceObject); if(result) { result->destroy(); delete result; result = NULL; } // we create our final body in the given world : result = createBody(referenceObject,worldReferenceObject); if (result) { result->setWorld(world); using namespace vtTools::AttributeTools; result->setFlags(descr->flags); result->setHullType(descr->hullType); result->setDataFlags(0x000); result->checkDataFlags(); if (result->getSkinWidth()==-1.0f) { result->setSkinWidth(0.01f); } VxMatrix v_matrix ; VxVector position,scale; VxQuaternion quat; v_matrix = referenceObject->GetWorldMatrix(); Vx3DDecomposeMatrix(v_matrix,quat,position,scale); VxVector box_s= BoxGetZero(referenceObject); NxVec3 pos = pMath::getFrom(position); NxQuat rot = pMath::getFrom(quat); float density = result->getDensity(); float radius = referenceObject->GetRadius(); if (referenceObject->GetRadius() < 0.001f ) { radius = 1.0f; } ////////////////////////////////////////////////////////////////////////// //create actors description NxActorDesc actorDesc;actorDesc.setToDefault(); NxBodyDesc bodyDesc;bodyDesc.setToDefault(); ////////////////////////////////////////////////////////////////////////// NxMaterialDesc *materialDescr = NULL; NxMaterial *material = NULL; if (isFlagOn(result->getDataFlags(),EDF_MATERIAL_PARAMETER)) { NxMaterialDesc entMatNull;entMatNull.setToDefault(); NxMaterialDesc *entMat = createMaterialFromEntity(referenceObject); material = world->getScene()->createMaterial(entMatNull); material->loadFromDesc(*entMat); result->setMaterial(material); }else{ if (world->getDefaultMaterial()) { result->setMaterial(world->getDefaultMaterial()); } } ////////////////////////////////////////////////////////////////////////// NxBoxShapeDesc boxShape; if (creationFlags & E_OFC_DIMENSION ) { boxShape.dimensions = pMath::getFrom(box_s)*0.5f; } boxShape.density = descr->density; boxShape.materialIndex = result->getMaterial()->getMaterialIndex(); if (result->getSkinWidth()!=-1.0f) boxShape.skinWidth = result->getSkinWidth(); actorDesc.shapes.pushBack(&boxShape); ////////////////////////////////////////////////////////////////////////// //dynamic object ? if (result->getFlags() & BF_Moving){ actorDesc.body = &bodyDesc; } else actorDesc.body = NULL; ////////////////////////////////////////////////////////////////////////// //set transformations actorDesc.density = descr->density; if (creationFlags & E_OFC_POSITION) { actorDesc.globalPose.t = pos; } if (creationFlags & E_OFC_POSITION) { actorDesc.globalPose.M = rot; } ////////////////////////////////////////////////////////////////////////// //create the actor int v = actorDesc.isValid(); NxActor *actor = world->getScene()->createActor(actorDesc); if (!actor) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); delete result; return NULL; } ////////////////////////////////////////////////////////////////////////// //set additional settings : result->setActor(actor); actor->setName(referenceObject->GetName()); actor->userData= result; if (result->getFlags() & BF_Moving) { VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&result->getMassOffset()); actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); } if (result->getFlags() & BF_Kinematic) { actor->raiseBodyFlag(NX_BF_KINEMATIC); } result->enableCollision((result->getFlags() & BF_Collision)); if (result->getFlags() & BF_Moving) { if (!(result->getFlags() & BF_Gravity)) { actor->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); } } NxShape *shape = result->getShapeByIndex(); if (shape) { pSubMeshInfo *sInfo = new pSubMeshInfo(); sInfo->entID = referenceObject->GetID(); sInfo->refObject = (CKBeObject*)referenceObject; shape->userData = (void*)sInfo; result->setMainShape(shape); shape->setName(referenceObject->GetName()); } } return result; } pRigidBody*pFactory::createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,NXU::NxActorDesc *desc,int flags) { #ifdef _DEBUG assert(referenceObject); assert(desc); #endif /************************************************************************/ /* */ /************************************************************************/ VxVector vpos; referenceObject->GetPosition(&vpos); VxQuaternion vquat; referenceObject->GetQuaternion(&vquat); NxQuat nrot = desc->globalPose.M; NxVec3 npos = desc->globalPose.t; NxMat33 rotX; rotX.rotX( PI / 2.0f ); NxMat33 rotZ; rotZ.rotZ( PI ); NxMat34 rotMat; rotMat.M.multiply( rotZ, rotX ); NxMat34 posMat( true ); /* posMat.t.set( -mTerrain->getPosition().x, mTerrain->getPosition().y, mTerrain->getPosition().z ); */ desc->globalPose.multiply( posMat, rotMat ); NxQuat nrot2 = desc->globalPose.M; NxVec3 npos2 = desc->globalPose.t; VxQuaternion nvm = getFromStream(nrot); VxVector nvpos = getFromStream(npos); for (NxU32 k=0; k<desc->mShapes.size(); k++) { NXU::NxShapeDesc *shape = desc->mShapes[k]; NxVec3 locPos = shape->localPose.t; NxQuat localQuad = shape->localPose.M; } int op = 2; return NULL; } pRigidBody*pFactory::createRigidBodyFull(CK3dEntity *referenceObject, CK3dEntity *worldReferenceObject) { //################################################################ // // Sanity checks // pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); pRigidBody*result = world->getBody(referenceObject); if(result) { result->destroy(); delete result; result = NULL; } //################################################################ // // Construct the result // result = createBody(referenceObject,worldReferenceObject); if (result) { result->setWorld(world); //---------------------------------------------------------------- // // Handle different attribute types (Object or pBSetup) // int attTypeOld = GetPMan()->GetPAttribute(); int attTypeNew = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); pObjectDescr *oDescr = NULL; //---------------------------------------------------------------- // // the old way : // if (referenceObject->HasAttribute(attTypeOld)) { result->retrieveSettingsFromAttribute(); oDescr = pFactory::Instance()->createPObjectDescrFromParameter(referenceObject->GetAttributeParameter(GetPMan()->GetPAttribute())); } bool hierarchy = result->getFlags() & BF_Hierarchy; bool isDeformable = result->getFlags() & BF_Deformable; bool trigger = (result->getFlags() & BF_TriggerShape); //---------------------------------------------------------------- // // the new way // if (referenceObject->HasAttribute(attTypeNew)) { oDescr = new pObjectDescr(); } result->checkDataFlags(); /* pObjectDescr *oDescr = if (!oDescr) return result; */ //################################################################ // // Older versions have the hierarchy mode settings not the body flags // We migrate it : // if (oDescr->hirarchy) { result->setFlags( (result->getFlags() | BF_Hierarchy )); } if (hierarchy) { oDescr->hirarchy = hierarchy; } //################################################################ // // Deformable ? // pCloth *cloth = NULL; pClothDesc cDescr; if (isDeformable) { cDescr.setToDefault(); cDescr.worldReference = worldReferenceObject->GetID(); if ( result->getFlags() & BF_Gravity ) { cDescr.flags |= PCF_Gravity; } if ( result->getFlags() & BF_Collision ) { } if (!cloth) { cloth = pFactory::Instance()->createCloth(referenceObject,cDescr); if (!cloth) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : factory object failed !"); } } } //################################################################ // // Some settings // if (result->getSkinWidth()==-1.0f) { result->setSkinWidth(0.01f); } float radius = referenceObject->GetRadius(); if (referenceObject->GetRadius() < 0.001f ) { radius = 1.0f; } float density = result->getDensity(); VxVector box_s= BoxGetZero(referenceObject); //################################################################ // // Calculate destination matrix // VxMatrix v_matrix ; VxVector position,scale; VxQuaternion quat; v_matrix = referenceObject->GetWorldMatrix(); Vx3DDecomposeMatrix(v_matrix,quat,position,scale); NxVec3 pos = pMath::getFrom(position); NxQuat rot = pMath::getFrom(quat); ////////////////////////////////////////////////////////////////////////// //create actors description NxActorDesc actorDesc;actorDesc.setToDefault(); NxBodyDesc bodyDesc;bodyDesc.setToDefault(); NxMaterialDesc *materialDescr = NULL; NxMaterial *material = NULL; switch(result->getHullType()) { ////////////////////////////////////////////////////////////////////////// case HT_Box: { NxBoxShapeDesc shape; if (! isDeformable ) { shape.dimensions = pMath::getFrom(box_s)*0.5f; } shape.density = density; //shape.localPose.t = pMath::getFrom(shapeOffset); if (result->getSkinWidth()!=-1.0f) shape.skinWidth = result->getSkinWidth(); actorDesc.shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Sphere: { NxSphereShapeDesc shape; if (! isDeformable ) { shape.radius = radius; } shape.density = density; //shape.localPose.t = pMath::getFrom(shapeOffset); if (result->getSkinWidth()!=-1.0f) shape.skinWidth = result->getSkinWidth(); actorDesc.shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Mesh: { if (! (result->getFlags() & BF_Deformable) ) { //xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Can not use a mesh as de"); //return NULL; } NxTriangleMeshDesc myMesh; myMesh.setToDefault(); createMesh(world->getScene(),referenceObject->GetCurrentMesh(),myMesh); NxTriangleMeshShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); return NULL; } MemoryWriteBuffer buf; status = CookTriangleMesh(myMesh, buf); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); return NULL; } shape.meshData = getManager()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); shape.density = density; // shape.materialIndex = result->getMaterial()->getMaterialIndex(); actorDesc.shapes.pushBack(&shape); //shape.localPose.t = pMath::getFrom(shapeOffset); if (result->getSkinWidth()!=-1.0f) shape.skinWidth = result->getSkinWidth(); CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_ConvexMesh: { if (referenceObject->GetCurrentMesh()) { if (referenceObject->GetCurrentMesh()->GetVertexCount()>=256 ) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshs allowed, by Ageia!"); goto nothing; } }else { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); goto nothing; } NxConvexMeshDesc myMesh; myMesh.setToDefault(); createConvexMesh(world->getScene(),referenceObject->GetCurrentMesh(),myMesh); NxConvexShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); goto nothing; } MemoryWriteBuffer buf; status = CookConvexMesh(myMesh, buf); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); goto nothing; } shape.meshData = getManager()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); shape.density = density; // shape.materialIndex = result->getMaterial()->getMaterialIndex(); actorDesc.shapes.pushBack(&shape); //shape.localPose.t = pMath::getFrom(shapeOffset); if (result->getSkinWidth()!=-1.0f) shape.skinWidth = result->getSkinWidth(); int h = shape.isValid(); CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_ConvexCylinder: { NxConvexShapeDesc shape; if (!_createConvexCylinder(&shape,referenceObject)) xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); shape.density = density; if (result->getSkinWidth()!=-1.0f) shape.skinWidth = result->getSkinWidth(); actorDesc.shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Capsule: { NxCapsuleShapeDesc shape; if ( !isDeformable ) { pCapsuleSettings cSettings; pFactory::Instance()->findSettings(cSettings,referenceObject); shape.radius = cSettings.radius > 0.0f ? cSettings.radius : box_s.v[cSettings.localRadiusAxis] * 0.5f; shape.height = cSettings.height > 0.0f ? cSettings.height : box_s.v[cSettings.localLengthAxis] - ( 2*shape.radius) ; } shape.density = density; // shape.materialIndex = result->getMaterial()->getMaterialIndex(); // shape.localPose.t = pMath::getFrom(shapeOffset); if (result->getSkinWidth()!=-1.0f) shape.skinWidth = result->getSkinWidth(); actorDesc.shapes.pushBack(&shape); break; } case HT_Wheel: { // xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); /* NxWheelShapeDesc shape; shape.radius = box_s.z*0.5f; shape.density = density; if (result->getSkinWidth()!=-1.0f) shape.skinWidth = result->getSkinWidth(); if (referenceObject && referenceObject->HasAttribute(GetPMan()->att_wheelDescr )) { CKParameter *par = referenceObject->GetAttributeParameter(GetPMan()->att_wheelDescr ); if (par) { pWheelDescr *wheelDescr = pFactory::Instance()->copyTo(par); if (wheelDescr) { float heightModifier = (wheelDescr->wheelSuspension + radius ) / wheelDescr->wheelSuspension; shape.suspension.damper = wheelDescr->springDamping * heightModifier; shape.suspension.targetValue = wheelDescr->springBias * heightModifier; shape.suspensionTravel = wheelDescr->wheelSuspension; shape.lateralTireForceFunction.stiffnessFactor *= wheelDescr->frictionToSide; shape.longitudalTireForceFunction.stiffnessFactor*=wheelDescr->frictionToFront; shape.inverseWheelMass = 0.1; int isValid = shape.isValid(); actorDesc.shapes.pushBack(&shape); } }else { XString name = result->GetVT3DObject()->GetName(); name << " needs to have an additional wheel attribute attached ! "; xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,name.CStr()); } } */ break; } } ////////////////////////////////////////////////////////////////////////// //dynamic object ? if (result->getFlags() & BF_Moving){ actorDesc.body = &bodyDesc; } else actorDesc.body = NULL; ////////////////////////////////////////////////////////////////////////// //set transformations actorDesc.density = result->getDensity(); if ( !isDeformable) { actorDesc.globalPose.t = pos; actorDesc.globalPose.M = rot; } ////////////////////////////////////////////////////////////////////////// //create the actor int v = actorDesc.isValid(); NxActor *actor = world->getScene()->createActor(actorDesc); if (!actor) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); delete result; return NULL; } ////////////////////////////////////////////////////////////////////////// //set additional settings : result->setActor(actor); actor->setName(referenceObject->GetName()); actor->userData= result; ////////////////////////////////////////////////////////////////////////// //Deformable : if (isDeformable && cloth) { pDeformableSettings dSettings; dSettings.ImpulsThresold = 50.0f; dSettings.PenetrationDepth= 0.1f ; dSettings.MaxDeform = 2.0f; CKParameterOut *poutDS = referenceObject->GetAttributeParameter(GetPMan()->att_deformable); if (poutDS) { pFactory::Instance()->copyTo(dSettings,poutDS); } cloth->attachToCore(referenceObject,dSettings.ImpulsThresold,dSettings.PenetrationDepth,dSettings.MaxDeform); result->setCloth(cloth); } ////////////////////////////////////////////////////////////////////////// // // Extra settings : // if (result->getFlags() & BF_Moving) { VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&result->getMassOffset()); actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); } if (result->getFlags() & BF_Kinematic) { result->setKinematic(true); } if (result->getFlags() & BF_Moving ) { result->enableGravity(result->getFlags() & BF_Gravity); } //---------------------------------------------------------------- // // Special Parameters // //- look for optimization attribute : result->checkForOptimization(); //---------------------------------------------------------------- // // store mesh meta info in the first main mesh // NxShape *shape = result->getShapeByIndex(); if (shape) { pSubMeshInfo *sInfo = new pSubMeshInfo(); sInfo->entID = referenceObject->GetID(); sInfo->refObject = (CKBeObject*)referenceObject; shape->userData = (void*)sInfo; result->setMainShape(shape); shape->setName(referenceObject->GetName()); pMaterial bMaterial; bool hasMaterial = pFactory::Instance()->findSettings(bMaterial,referenceObject); if (!hasMaterial) { if (world->getDefaultMaterial()) { int z = (int)world->getDefaultMaterial()->userData; shape->setMaterial(world->getDefaultMaterial()->getMaterialIndex()); //pFactory::Instance()->copyTo(bMaterial,world->getDefaultMaterial()); } }else{ NxMaterialDesc nxMatDescr; pFactory::Instance()->copyTo(nxMatDescr,bMaterial); NxMaterial *nxMaterial = world->getScene()->createMaterial(nxMatDescr); if (nxMaterial) { shape->setMaterial(nxMaterial->getMaterialIndex()); } } } result->enableCollision( (result->getFlags() & BF_Collision), referenceObject ); //- handle collisions setup if (oDescr->version == pObjectDescr::E_OD_VERSION::OD_DECR_V1) result->updateCollisionSettings(*oDescr,referenceObject); xLogger::xLog(ELOGINFO,E_LI_MANAGER,"Rigid body creation successful : %s",referenceObject->GetName()); //---------------------------------------------------------------- // // Parse hierarchy // if (!oDescr->hirarchy) return result; CK3dEntity* subEntity = NULL; while (subEntity= referenceObject->HierarchyParser(subEntity) ) { if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) { pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); if (subDescr->flags & BF_SubShape) { ////////////////////////////////////////////////////////////////////////// // // Regular Mesh : // if (subDescr->hullType != HT_Cloth) { result->addSubShape(NULL,*oDescr,subEntity); } ////////////////////////////////////////////////////////////////////////// // // Cloth Mesh : // if (subDescr->hullType == HT_Cloth) { //pClothDesc *cloth = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); } } } } if (oDescr->hirarchy) { if (oDescr->newDensity!=0.0f || oDescr->totalMass!=0.0f ) { result->updateMassFromShapes(oDescr->newDensity,oDescr->totalMass); } } return result; } nothing: return result; } pRigidBody*pFactory::createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject) { ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Pseudo code : // // 1. check the passed world, otherwise use+create the physic managers default world : // 1. ////////////////////////////////////////////////////////////////////////// if (!referenceObject) { return NULL; } pWorld *world=GetPMan()->getWorld(worldReferenceObject,referenceObject); if (world) { int p = 0; } if (!world) { return NULL; } pRigidBody *result = new pRigidBody(referenceObject,world); return result; } pRigidBody*pFactory::createBody(CK3dEntity *referenceObject,pObjectDescr description,CK3dEntity *worldReferenceObject/* =NULL */) { using namespace vtTools::BehaviorTools; using namespace vtTools; using namespace vtTools::AttributeTools; pRigidBody *result = NULL; if (!referenceObject) return result; pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); if (!world) { return result; } if (referenceObject->HasAttribute(GetPMan()->GetPAttribute())) { referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); } referenceObject->SetAttribute(GetPMan()->GetPAttribute()); int htype = description.hullType; int flags = description.flags; SetAttributeValue<xBool>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HIRARCHY,&description.hirarchy); SetAttributeValue<int>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HULLTYPE,&htype); SetAttributeValue<int>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_BODY_FLAGS,&flags); SetAttributeValue<float>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_DENSITY,&description.density); SetAttributeValue<float>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_NEW_DENSITY,&description.newDensity); SetAttributeValue<float>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_TOTAL_MASS,&description.totalMass); SetAttributeValue<VxVector>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_MASS_OFFSET,&description.massOffset); CK_ID wid = world->getReference()->GetID(); AttributeTools::SetAttributeValue<CK_ID>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_WORLD,&wid); result = pFactory::Instance()->createRigidBodyFull(referenceObject,world->getReference()); if (result) { result->translateLocalShapePosition(description.shapeOffset); result->setCMassOffsetLocalPosition(description.massOffset); } if ( ! (description.flags & BF_AddAttributes) ) { referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); } return result; } CK3dEntity *pFactory::getMostTopParent(CK3dEntity*ent) { if (!ent) { return NULL; } CK3dEntity *result = ent->GetParent(); if (result) { int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); //if ( (!result->HasAttribute(GetPMan()->GetPAttribute())) || !(result->HasAttribute(attTypePBSetup))) if ( (result->HasAttribute(GetPMan()->GetPAttribute())) || (result->HasAttribute(attTypePBSetup))) { return ent; } if (result->GetParent()) { return getMostTopParent(result); } else { return result; } }else { return ent; } } /* template<class T>class MODULE_API xImplementationObject2 { public: //xLinkedObjectStorage() : mInternalId(-1) , mClassId(-1) {}; typedef void* xImplementationObject2<T>::*StoragePtr; xImplementationObject2(){} xImplementationObject2(StoragePtr storage) { } void setStorage(StoragePtr* stPtr) { mStorage = stPtr; } T getImpl() { return mObject; } protected: private: T mObject; StoragePtr mStorage; }; class ATest : public xImplementationObject2<NxActor*> { public: ATest(); }; NxActor *actor = NULL; ATest::ATest() : xImplementationObject2<NxActor*>(actor->userData) { // setStorage(actor->userData); } */<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBGetVelocitiesAndForcesDecl(); CKERROR CreatePBGetVelocitiesAndForcesProto(CKBehaviorPrototype **pproto); int PBGetVelocitiesAndForces(const CKBehaviorContext& behcontext); CKERROR PBGetVelocitiesAndForcesCB(const CKBehaviorContext& behcontext); using namespace vtTools; using namespace BehaviorTools; enum bbI_Inputs { bbI_BodyReference, }; #define BB_SSTART 0 enum bInputs { bbO_Vel, bbO_AVel, bbO_Momentum, bbO_Torque, }; BBParameter pOutMapPBGetPar2[] = { BB_SPOUT(bbO_Vel,CKPGUID_VECTOR,"Linear Velocity",""), BB_SPOUT(bbO_AVel,CKPGUID_VECTOR,"Angular Velocity",""), BB_SPOUT(bbO_Torque,CKPGUID_VECTOR,"Linear Momentum",""), BB_SPOUT(bbO_Momentum,CKPGUID_VECTOR,"Angular Momentum",""), }; #define gOPMap pOutMapPBGetPar2 CKERROR PBGetVelocitiesAndForcesCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; int cb = behcontext.CallbackMessage; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_POMAP(gOPMap,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PMAP(gOPMap,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PMAP(gOPMap,BB_SSTART); break; } } return CKBR_OK; } CKObjectDeclaration *FillBehaviorPBGetVelocitiesAndForcesDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBGetParEx"); od->SetCategory("Physic/Body"); od->SetDescription("Retrieves forces and velocities"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x1076b62,0x1dea09ed)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBGetVelocitiesAndForcesProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBGetVelocitiesAndForcesProto // FullName: CreatePBGetVelocitiesAndForcesProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBGetVelocitiesAndForcesProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBGetParEx"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PBGetParEx PBGetParEx is categorized in \ref Vehicle <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Retrieves velocities and forces.<br> <h3>Technical Information</h3> \image html PBGetParEx.png <SPAN CLASS="in">In:</SPAN>triggers the process <BR> <SPAN CLASS="out">Out:</SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pout">Linear Velocity: </SPAN>The linear velocity.See pRigidBody::getLinearVelocity(). <BR> <SPAN CLASS="pout">Angular Velocity: </SPAN>The angular velocity.See pRigidBody::getAngularVelocity(). <BR> <SPAN CLASS="pout">Agular Momentum: </SPAN>The angular momentum.See pRigidBody::getAngularMomentum(). <BR> <SPAN CLASS="pout">Linear Momentum: </SPAN>The linear momentum.See pRigidBody::getLinearMomentum(). <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBGetEx.cpp </SPAN> */ proto->SetBehaviorCallbackFct( PBGetVelocitiesAndForcesCB ); BB_EVALUATE_SETTINGS(gOPMap); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBGetVelocitiesAndForces); *pproto = proto; return CK_OK; } //************************************ // Method: PBGetVelocitiesAndForces // FullName: PBGetVelocitiesAndForces // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBGetVelocitiesAndForces(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; body = GetPMan()->getBody(target); if (!body) bbErrorME("No Reference Object specified"); BB_DECLARE_PMAP; BBSParameter(bbO_Vel); BBSParameter(bbO_AVel); BBSParameter(bbO_Torque); BBSParameter(bbO_Momentum); BB_O_SET_VALUE_IF(VxVector,bbO_Vel,body->getLinearVelocity()); BB_O_SET_VALUE_IF(VxVector,bbO_AVel,body->getAngularVelocity()); BB_O_SET_VALUE_IF(VxVector,bbO_Momentum,body->getLinearMomentum()); BB_O_SET_VALUE_IF(VxVector,bbO_Vel,body->getLinearVelocity()); } beh->ActivateOutput(0); return 0; } //************************************ // Method: PBGetVelocitiesAndForcesCB // FullName: PBGetVelocitiesAndForcesCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ <file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #include "tnl.h" #include "tnlAsymmetricKey.h" #include "tnlNetConnection.h" #include "tnlNetInterface.h" #include "tnlBitStream.h" #include "tnlRandom.h" #include "tnlNetObject.h" #include "tnlClientPuzzle.h" #include "tnlCertificate.h" #include <mycrypt.h> namespace TNL { //----------------------------------------------------------------------------- // NetInterface initialization/destruction //----------------------------------------------------------------------------- NetInterface::NetInterface(const Address &bindAddress) : mSocket(bindAddress) { NetClassRep::initialize(); // initialize the net class reps, if they haven't been initialized already. mLastTimeoutCheckTime = 0; mAllowConnections = true; mRequiresKeyExchange = false; Random::read(mRandomHashData, sizeof(mRandomHashData)); mConnectionHashTable.setSize(129); for(S32 i = 0; i < mConnectionHashTable.size(); i++) mConnectionHashTable[i] = NULL; mSendPacketList = NULL; mCurrentTime = Platform::getRealMilliseconds(); } NetInterface::~NetInterface() { // gracefully close all the connections on this NetInterface: while(mConnectionList.size()) { NetConnection *c = mConnectionList[0]; disconnect(c, NetConnection::ReasonSelfDisconnect, "Shutdown"); } } Address NetInterface::getFirstBoundInterfaceAddress() { Address theAddress = mSocket.getBoundAddress(); if(theAddress.isEqualAddress(Address(IPProtocol, Address::Any, 0))) { Vector<Address> interfaceAddresses; Socket::getInterfaceAddresses(&interfaceAddresses); U16 savePort = theAddress.port; if(interfaceAddresses.size()) { theAddress = interfaceAddresses[0]; theAddress.port = savePort; } } return theAddress; } void NetInterface::setPrivateKey(AsymmetricKey *theKey) { mPrivateKey = theKey; } //----------------------------------------------------------------------------- // NetInterface packet sending functions //----------------------------------------------------------------------------- NetError NetInterface::sendto(const Address &address, BitStream *stream) { return mSocket.sendto(address, stream->getBuffer(), stream->getBytePosition()); } void NetInterface::sendtoDelayed(const Address &address, BitStream *stream, U32 millisecondDelay) { U32 dataSize = stream->getBytePosition(); // allocate the send packet, with the data size added on DelaySendPacket *thePacket = (DelaySendPacket *) malloc(sizeof(DelaySendPacket) + dataSize); thePacket->remoteAddress = address; thePacket->sendTime = getCurrentTime() + millisecondDelay; thePacket->packetSize = dataSize; memcpy(thePacket->packetData, stream->getBuffer(), dataSize); // insert it into the DelaySendPacket list, sorted by time DelaySendPacket **list; for(list = &mSendPacketList; *list && ((*list)->sendTime < thePacket->sendTime); list = &((*list)->nextPacket)) ; thePacket->nextPacket = *list; *list = thePacket; } //----------------------------------------------------------------------------- // NetInterface utility functions //----------------------------------------------------------------------------- U32 NetInterface::computeClientIdentityToken(const Address &address, const Nonce &theNonce) { hash_state hashState; U32 hash[8]; sha256_init(&hashState); sha256_process(&hashState, (const U8 *) &address, sizeof(Address)); sha256_process(&hashState, theNonce.data, Nonce::NonceSize); sha256_process(&hashState, mRandomHashData, sizeof(mRandomHashData)); sha256_done(&hashState, (U8 *) hash); return hash[0]; } //----------------------------------------------------------------------------- // NetInterface pending connection list management //----------------------------------------------------------------------------- void NetInterface::addPendingConnection(NetConnection *connection) { // make sure we're not already connected to the host at the // connection's Address findAndRemovePendingConnection(connection->getNetAddress()); NetConnection *temp = findConnection(connection->getNetAddress()); if(temp) disconnect(temp, NetConnection::ReasonSelfDisconnect, "Reconnecting"); // hang on to the connection and add it to the pending connection list connection->incRef(); mPendingConnections.push_back(connection); } void NetInterface::removePendingConnection(NetConnection *connection) { // search the pending connection list for the specified connection // and remove it. for(S32 i = 0; i < mPendingConnections.size(); i++) if(mPendingConnections[i] == connection) { connection->decRef(); mPendingConnections.erase(i); return; } } NetConnection *NetInterface::findPendingConnection(const Address &address) { // Loop through all the pending connections and compare the NetAddresses for(S32 i = 0; i < mPendingConnections.size(); i++) if(address == mPendingConnections[i]->getNetAddress()) return mPendingConnections[i]; return NULL; } void NetInterface::findAndRemovePendingConnection(const Address &address) { // Search through the list by Address and remove any connection // that matches. for(S32 i = 0; i < mPendingConnections.size(); i++) if(address == mPendingConnections[i]->getNetAddress()) { mPendingConnections[i]->decRef(); mPendingConnections.erase(i); return; } } //----------------------------------------------------------------------------- // NetInterface connection list management //----------------------------------------------------------------------------- NetConnection *NetInterface::findConnection(const Address &addr) { // The connection hash table is a single vector, with hash collisions // resolved to the next open space in the table. // Compute the hash index based on the network address U32 hashIndex = addr.hash() % mConnectionHashTable.size(); // Search through the table for an address that matches the source // address. If the connection pointer is NULL, we've found an // empty space and a connection with that address is not in the table while(mConnectionHashTable[hashIndex] != NULL) { if(addr == mConnectionHashTable[hashIndex]->getNetAddress()) return mConnectionHashTable[hashIndex]; hashIndex++; if(hashIndex >= (U32) mConnectionHashTable.size()) hashIndex = 0; } return NULL; } void NetInterface::removeConnection(NetConnection *conn) { for(S32 i = 0; i < mConnectionList.size(); i++) { if(mConnectionList[i] == conn) { mConnectionList.erase_fast(i); break; } } U32 index = conn->getNetAddress().hash() % mConnectionHashTable.size(); U32 startIndex = index; while(mConnectionHashTable[index] != conn) { index++; if(index >= (U32) mConnectionHashTable.size()) index = 0; TNLAssert(index != startIndex, "Attempting to remove a connection that is not in the table.") // not in the table if(index == startIndex) return; } mConnectionHashTable[index] = NULL; // rehash all subsequent entries until we find a NULL entry: for(;;) { index++; if(index >= (U32) mConnectionHashTable.size()) index = 0; if(!mConnectionHashTable[index]) break; NetConnection *rehashConn = mConnectionHashTable[index]; mConnectionHashTable[index] = NULL; U32 realIndex = rehashConn->getNetAddress().hash() % mConnectionHashTable.size(); while(mConnectionHashTable[realIndex] != NULL) { realIndex++; if(realIndex >= (U32) mConnectionHashTable.size()) realIndex = 0; } mConnectionHashTable[realIndex] = rehashConn; } conn->decRef(); } void NetInterface::addConnection(NetConnection *conn) { conn->incRef(); mConnectionList.push_back(conn); S32 numConnections = mConnectionList.size(); if(numConnections > mConnectionHashTable.size() / 2) { mConnectionHashTable.setSize(numConnections * 4 - 1); for(S32 i = 0; i < mConnectionHashTable.size(); i++) mConnectionHashTable[i] = NULL; for(S32 i = 0; i < numConnections; i++) { U32 index = mConnectionList[i]->getNetAddress().hash() % mConnectionHashTable.size(); while(mConnectionHashTable[index] != NULL) { index++; if(index >= (U32) mConnectionHashTable.size()) index = 0; } mConnectionHashTable[index] = mConnectionList[i]; } } else { U32 index = mConnectionList[numConnections - 1]->getNetAddress().hash() % mConnectionHashTable.size(); while(mConnectionHashTable[index] != NULL) { index++; if(index >= (U32) mConnectionHashTable.size()) index = 0; } mConnectionHashTable[index] = mConnectionList[numConnections - 1]; } } //----------------------------------------------------------------------------- // NetInterface timeout and packet send processing //----------------------------------------------------------------------------- void NetInterface::processConnections() { mCurrentTime = Platform::getRealMilliseconds(); mPuzzleManager.tick(mCurrentTime); // first see if there are any delayed packets that need to be sent... while(mSendPacketList && mSendPacketList->sendTime < getCurrentTime()) { DelaySendPacket *next = mSendPacketList->nextPacket; mSocket.sendto(mSendPacketList->remoteAddress, mSendPacketList->packetData, mSendPacketList->packetSize); free(mSendPacketList); mSendPacketList = next; } NetObject::collapseDirtyList(); // collapse all the mask bits... for(S32 i = 0; i < mConnectionList.size(); i++) mConnectionList[i]->checkPacketSend(false, getCurrentTime()); if(getCurrentTime() > mLastTimeoutCheckTime + TimeoutCheckInterval) { for(S32 i = 0; i < mPendingConnections.size();) { NetConnection *pending = mPendingConnections[i]; if(pending->getConnectionState() == NetConnection::AwaitingChallengeResponse && getCurrentTime() > pending->mConnectLastSendTime + ChallengeRetryTime) { if(pending->mConnectSendCount > ChallengeRetryCount) { pending->setConnectionState(NetConnection::ConnectTimedOut); pending->onConnectTerminated(NetConnection::ReasonTimedOut, "Timeout"); removePendingConnection(pending); continue; } else sendConnectChallengeRequest(pending); } else if(pending->getConnectionState() == NetConnection::AwaitingConnectResponse && getCurrentTime() > pending->mConnectLastSendTime + ConnectRetryTime) { if(pending->mConnectSendCount > ConnectRetryCount) { pending->setConnectionState(NetConnection::ConnectTimedOut); pending->onConnectTerminated(NetConnection::ReasonTimedOut, "Timeout"); removePendingConnection(pending); continue; } else { if(pending->getConnectionParameters().mIsArranged) sendArrangedConnectRequest(pending); else sendConnectRequest(pending); } } else if(pending->getConnectionState() == NetConnection::SendingPunchPackets && getCurrentTime() > pending->mConnectLastSendTime + PunchRetryTime) { if(pending->mConnectSendCount > PunchRetryCount) { pending->setConnectionState(NetConnection::ConnectTimedOut); pending->onConnectTerminated(NetConnection::ReasonTimedOut, "Timeout"); removePendingConnection(pending); continue; } else sendPunchPackets(pending); } else if(pending->getConnectionState() == NetConnection::ComputingPuzzleSolution && getCurrentTime() > pending->mConnectLastSendTime + PuzzleSolutionTimeout) { pending->setConnectionState(NetConnection::ConnectTimedOut); pending->onConnectTerminated(NetConnection::ReasonTimedOut, "Timeout"); removePendingConnection(pending); } i++; } mLastTimeoutCheckTime = getCurrentTime(); for(S32 i = 0; i < mConnectionList.size();) { if(mConnectionList[i]->checkTimeout(getCurrentTime())) { mConnectionList[i]->setConnectionState(NetConnection::TimedOut); mConnectionList[i]->onConnectionTerminated(NetConnection::ReasonTimedOut, "Timeout"); removeConnection(mConnectionList[i]); } else i++; } } // check if we're trying to solve any client connection puzzles for(S32 i = 0; i < mPendingConnections.size(); i++) { if(mPendingConnections[i]->getConnectionState() == NetConnection::ComputingPuzzleSolution) { continuePuzzleSolution(mPendingConnections[i]); break; } } } //----------------------------------------------------------------------------- // NetInterface incoming packet dispatch //----------------------------------------------------------------------------- void NetInterface::checkIncomingPackets() { PacketStream stream; NetError error; Address sourceAddress; mCurrentTime = Platform::getRealMilliseconds(); // read out all the available packets: while((error = stream.recvfrom(mSocket, &sourceAddress)) == NoError) processPacket(sourceAddress, &stream); } void NetInterface::processPacket(const Address &sourceAddress, BitStream *pStream) { // Determine what to do with this packet: if(pStream->getBuffer()[0] & 0x80) // it's a protocol packet... { // if the LSB of the first byte is set, it's a game data packet // so pass it to the appropriate connection. // lookup the connection in the addressTable // if this packet causes a disconnection, keep the conn around until this function exits RefPtr<NetConnection> conn = findConnection(sourceAddress); if(conn) conn->readRawPacket(pStream); } else { // Otherwise, it's either a game info packet or a // connection handshake packet. U8 packetType; pStream->read(&packetType); if(packetType >= FirstValidInfoPacketId) handleInfoPacket(sourceAddress, packetType, pStream); else { // check if there's a connection already: switch(packetType) { case ConnectChallengeRequest: handleConnectChallengeRequest(sourceAddress, pStream); break; case ConnectChallengeResponse: handleConnectChallengeResponse(sourceAddress, pStream); break; case ConnectRequest: handleConnectRequest(sourceAddress, pStream); break; case ConnectReject: handleConnectReject(sourceAddress, pStream); break; case ConnectAccept: handleConnectAccept(sourceAddress, pStream); break; case Disconnect: handleDisconnect(sourceAddress, pStream); break; case Punch: handlePunch(sourceAddress, pStream); break; case ArrangedConnectRequest: handleArrangedConnectRequest(sourceAddress, pStream); break; case BroadcastMessage: handleBroadcastMessage(sourceAddress,pStream); break; } } } } void NetInterface::handleBroadcastMessage(const Address &theAddress, BitStream *stream) { } void NetInterface::handleInfoPacket(const Address &address, U8 packetType, BitStream *stream) { } //----------------------------------------------------------------------------- // NetInterface connection handshake initiaton and processing //----------------------------------------------------------------------------- void NetInterface::startConnection(NetConnection *conn) { TNLAssert(conn->getConnectionState() == NetConnection::NotConnected, "Cannot start unless it is in the NotConnected state."); addPendingConnection(conn); conn->mConnectSendCount = 0; conn->setConnectionState(NetConnection::AwaitingChallengeResponse); sendConnectChallengeRequest(conn); } void NetInterface::sendConnectChallengeRequest(NetConnection *conn) { TNLLogMessageV(LogNetInterface, ("Sending Connect Challenge Request to %s", conn->getNetAddress().toString())); PacketStream out; out.write(U8(ConnectChallengeRequest)); ConnectionParameters &params = conn->getConnectionParameters(); params.mNonce.write(&out); out.writeFlag(params.mRequestKeyExchange); out.writeFlag(params.mRequestCertificate); conn->mConnectSendCount++; conn->mConnectLastSendTime = getCurrentTime(); out.sendto(mSocket, conn->getNetAddress()); } void NetInterface::handleConnectChallengeRequest(const Address &addr, BitStream *stream) { TNLLogMessageV(LogNetInterface, ("Received Connect Challenge Request from %s", addr.toString())); if(!mAllowConnections) return; Nonce clientNonce; clientNonce.read(stream); bool wantsKeyExchange = stream->readFlag(); bool wantsCertificate = stream->readFlag(); sendConnectChallengeResponse(addr, clientNonce, wantsKeyExchange, wantsCertificate); } void NetInterface::sendConnectChallengeResponse(const Address &addr, Nonce &clientNonce, bool wantsKeyExchange, bool wantsCertificate) { PacketStream out; out.write(U8(ConnectChallengeResponse)); clientNonce.write(&out); U32 identityToken = computeClientIdentityToken(addr, clientNonce); out.write(identityToken); // write out a client puzzle Nonce serverNonce = mPuzzleManager.getCurrentNonce(); U32 difficulty = mPuzzleManager.getCurrentDifficulty(); serverNonce.write(&out); out.write(difficulty); if(out.writeFlag(mRequiresKeyExchange || (wantsKeyExchange && !mPrivateKey.isNull()))) { if(out.writeFlag(wantsCertificate && !mCertificate.isNull())) out.write(mCertificate); else out.write(mPrivateKey->getPublicKey()); } TNLLogMessageV(LogNetInterface, ("Sending Challenge Response: %8x", identityToken)); out.sendto(mSocket, addr); } //----------------------------------------------------------------------------- void NetInterface::handleConnectChallengeResponse(const Address &address, BitStream *stream) { NetConnection *conn = findPendingConnection(address); if(!conn || conn->getConnectionState() != NetConnection::AwaitingChallengeResponse) return; Nonce theNonce; theNonce.read(stream); ConnectionParameters &theParams = conn->getConnectionParameters(); if(theNonce != theParams.mNonce) return; stream->read(&theParams.mClientIdentity); // see if the server wants us to solve a client puzzle theParams.mServerNonce.read(stream); stream->read(&theParams.mPuzzleDifficulty); if(theParams.mPuzzleDifficulty > ClientPuzzleManager::MaxPuzzleDifficulty) return; // see if the connection needs to be authenticated or uses key exchange if(stream->readFlag()) { if(stream->readFlag()) { theParams.mCertificate = new Certificate(stream); if(!theParams.mCertificate->isValid() || !conn->validateCertficate(theParams.mCertificate, true)) return; theParams.mPublicKey = theParams.mCertificate->getPublicKey(); } else { theParams.mPublicKey = new AsymmetricKey(stream); if(!theParams.mPublicKey->isValid() || !conn->validatePublicKey(theParams.mPublicKey, true)) return; } if(mPrivateKey.isNull() || mPrivateKey->getKeySize() != theParams.mPublicKey->getKeySize()) { // we don't have a private key, so generate one for this connection theParams.mPrivateKey = new AsymmetricKey(theParams.mPublicKey->getKeySize()); } else theParams.mPrivateKey = mPrivateKey; theParams.mSharedSecret = theParams.mPrivateKey->computeSharedSecretKey(theParams.mPublicKey); logprintf("shared secret (client) %s", theParams.mSharedSecret->encodeBase64()->getBuffer()); Random::read(theParams.mSymmetricKey, SymmetricCipher::KeySize); theParams.mUsingCrypto = true; } TNLLogMessageV(LogNetInterface, ("Received Challenge Response: %8x", theParams.mClientIdentity )); conn->setConnectionState(NetConnection::ComputingPuzzleSolution); conn->mConnectSendCount = 0; theParams.mPuzzleSolution = 0; conn->mConnectLastSendTime = getCurrentTime(); continuePuzzleSolution(conn); } void NetInterface::continuePuzzleSolution(NetConnection *conn) { ConnectionParameters &theParams = conn->getConnectionParameters(); bool solved = ClientPuzzleManager::solvePuzzle(&theParams.mPuzzleSolution, theParams.mNonce, theParams.mServerNonce, theParams.mPuzzleDifficulty, theParams.mClientIdentity); if(solved) { //logprintf("Client puzzle solved in %d ms.", Platform::getRealMilliseconds() - conn->mConnectLastSendTime); conn->setConnectionState(NetConnection::AwaitingConnectResponse); sendConnectRequest(conn); } } //----------------------------------------------------------------------------- // NetInterface connect request //----------------------------------------------------------------------------- void NetInterface::sendConnectRequest(NetConnection *conn) { TNLLogMessageV(LogNetInterface, ("Sending Connect Request")); PacketStream out; ConnectionParameters &theParams = conn->getConnectionParameters(); out.write(U8(ConnectRequest)); theParams.mNonce.write(&out); theParams.mServerNonce.write(&out); out.write(theParams.mClientIdentity); out.write(theParams.mPuzzleDifficulty); out.write(theParams.mPuzzleSolution); U32 encryptPos = 0; if(out.writeFlag(theParams.mUsingCrypto)) { out.write(theParams.mPrivateKey->getPublicKey()); encryptPos = out.getBytePosition(); out.setBytePosition(encryptPos); out.write(SymmetricCipher::KeySize, theParams.mSymmetricKey); } out.writeFlag(theParams.mDebugObjectSizes); out.write(conn->getInitialSendSequence()); out.writeString(conn->getClassName()); conn->writeConnectRequest(&out); if(encryptPos) { // if we're using crypto on this connection, // then write a hash of everything we wrote into the packet // key. Then we'll symmetrically encrypt the packet from // the end of the public key to the end of the signature. SymmetricCipher theCipher(theParams.mSharedSecret); out.hashAndEncrypt(NetConnection::MessageSignatureBytes, encryptPos, &theCipher); } conn->mConnectSendCount++; conn->mConnectLastSendTime = getCurrentTime(); out.sendto(mSocket, conn->getNetAddress()); } void NetInterface::handleConnectRequest(const Address &address, BitStream *stream) { if(!mAllowConnections) return; ConnectionParameters theParams; theParams.mNonce.read(stream); theParams.mServerNonce.read(stream); stream->read(&theParams.mClientIdentity); if(theParams.mClientIdentity != computeClientIdentityToken(address, theParams.mNonce)) return; stream->read(&theParams.mPuzzleDifficulty); stream->read(&theParams.mPuzzleSolution); // see if the connection is in the main connection table. // If the connection is in the connection table and it has // the same initiatorSequence, we'll just resend the connect // acceptance packet, assuming that the last time we sent it // it was dropped. NetConnection *connect = findConnection(address); if(connect) { ConnectionParameters &cp = connect->getConnectionParameters(); if(cp.mNonce == theParams.mNonce && cp.mServerNonce == theParams.mServerNonce) { sendConnectAccept(connect); return; } } // check the puzzle solution ClientPuzzleManager::ErrorCode result = mPuzzleManager.checkSolution( theParams.mPuzzleSolution, theParams.mNonce, theParams.mServerNonce, theParams.mPuzzleDifficulty, theParams.mClientIdentity); if(result != ClientPuzzleManager::Success) { sendConnectReject(&theParams, address, "Puzzle"); return; } if(stream->readFlag()) { if(mPrivateKey.isNull()) return; theParams.mUsingCrypto = true; theParams.mPublicKey = new AsymmetricKey(stream); theParams.mPrivateKey = mPrivateKey; U32 decryptPos = stream->getBytePosition(); stream->setBytePosition(decryptPos); theParams.mSharedSecret = theParams.mPrivateKey->computeSharedSecretKey(theParams.mPublicKey); logprintf("shared secret (server) %s", theParams.mSharedSecret->encodeBase64()->getBuffer()); SymmetricCipher theCipher(theParams.mSharedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher)) return; // now read the first part of the connection's symmetric key stream->read(SymmetricCipher::KeySize, theParams.mSymmetricKey); Random::read(theParams.mInitVector, SymmetricCipher::KeySize); } U32 connectSequence; theParams.mDebugObjectSizes = stream->readFlag(); stream->read(&connectSequence); TNLLogMessageV(LogNetInterface, ("Received Connect Request %8x", theParams.mClientIdentity)); if(connect) disconnect(connect, NetConnection::ReasonSelfDisconnect, "NewConnection"); char connectionClass[256]; stream->readString(connectionClass); NetConnection *conn = NetConnectionRep::create(connectionClass); if(!conn) return; RefPtr<NetConnection> theConnection = conn; conn->getConnectionParameters() = theParams; conn->setNetAddress(address); conn->setInitialRecvSequence(connectSequence); conn->setInterface(this); if(theParams.mUsingCrypto) conn->setSymmetricCipher(new SymmetricCipher(theParams.mSymmetricKey, theParams.mInitVector)); const char *errorString = NULL; if(!conn->readConnectRequest(stream, &errorString)) { sendConnectReject(&theParams, address, errorString); return; } addConnection(conn); conn->setConnectionState(NetConnection::Connected); conn->onConnectionEstablished(); sendConnectAccept(conn); } //----------------------------------------------------------------------------- // NetInterface connection acceptance and handling //----------------------------------------------------------------------------- void NetInterface::sendConnectAccept(NetConnection *conn) { TNLLogMessageV(LogNetInterface, ("Sending Connect Accept - connection established.")); PacketStream out; out.write(U8(ConnectAccept)); ConnectionParameters &theParams = conn->getConnectionParameters(); theParams.mNonce.write(&out); theParams.mServerNonce.write(&out); U32 encryptPos = out.getBytePosition(); out.setBytePosition(encryptPos); out.write(conn->getInitialSendSequence()); conn->writeConnectAccept(&out); if(theParams.mUsingCrypto) { out.write(SymmetricCipher::KeySize, theParams.mInitVector); SymmetricCipher theCipher(theParams.mSharedSecret); out.hashAndEncrypt(NetConnection::MessageSignatureBytes, encryptPos, &theCipher); } out.sendto(mSocket, conn->getNetAddress()); } void NetInterface::handleConnectAccept(const Address &address, BitStream *stream) { Nonce nonce, serverNonce; nonce.read(stream); serverNonce.read(stream); U32 decryptPos = stream->getBytePosition(); stream->setBytePosition(decryptPos); NetConnection *conn = findPendingConnection(address); if(!conn || conn->getConnectionState() != NetConnection::AwaitingConnectResponse) return; ConnectionParameters &theParams = conn->getConnectionParameters(); if(theParams.mNonce != nonce || theParams.mServerNonce != serverNonce) return; if(theParams.mUsingCrypto) { SymmetricCipher theCipher(theParams.mSharedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher)) return; } U32 recvSequence; stream->read(&recvSequence); conn->setInitialRecvSequence(recvSequence); const char *errorString = NULL; if(!conn->readConnectAccept(stream, &errorString)) { removePendingConnection(conn); return; } if(theParams.mUsingCrypto) { stream->read(SymmetricCipher::KeySize, theParams.mInitVector); conn->setSymmetricCipher(new SymmetricCipher(theParams.mSymmetricKey, theParams.mInitVector)); } addConnection(conn); // first, add it as a regular connection removePendingConnection(conn); // remove from the pending connection list conn->setConnectionState(NetConnection::Connected); conn->onConnectionEstablished(); // notify the connection that it has been established TNLLogMessageV(LogNetInterface, ("Received Connect Accept - connection established.")); } //----------------------------------------------------------------------------- // NetInterface connection rejection and handling //----------------------------------------------------------------------------- void NetInterface::sendConnectReject(ConnectionParameters *conn, const Address &theAddress, const char *reason) { if(!reason) return; // if the stream is NULL, we reject silently PacketStream out; out.write(U8(ConnectReject)); conn->mNonce.write(&out); conn->mServerNonce.write(&out); out.writeString(reason); out.sendto(mSocket, theAddress); } void NetInterface::handleConnectReject(const Address &address, BitStream *stream) { Nonce nonce; Nonce serverNonce; nonce.read(stream); serverNonce.read(stream); NetConnection *conn = findPendingConnection(address); if(!conn || (conn->getConnectionState() != NetConnection::AwaitingChallengeResponse && conn->getConnectionState() != NetConnection::AwaitingConnectResponse)) return; ConnectionParameters &p = conn->getConnectionParameters(); if(p.mNonce != nonce || p.mServerNonce != serverNonce) return; char reason[256]; stream->readString(reason); TNLLogMessageV(LogNetInterface, ("Received Connect Reject - reason %s", reason)); // if the reason is a bad puzzle solution, try once more with a // new nonce. if(!strcmp(reason, "Puzzle") && !p.mPuzzleRetried) { p.mPuzzleRetried = true; conn->setConnectionState(NetConnection::AwaitingChallengeResponse); conn->mConnectSendCount = 0; p.mNonce.getRandom(); sendConnectChallengeRequest(conn); return; } conn->setConnectionState(NetConnection::ConnectRejected); conn->onConnectTerminated(NetConnection::ReasonRemoteHostRejectedConnection, reason); removePendingConnection(conn); } //----------------------------------------------------------------------------- // NetInterface arranged connection process //----------------------------------------------------------------------------- void NetInterface::startArrangedConnection(NetConnection *conn) { conn->setConnectionState(NetConnection::SendingPunchPackets); addPendingConnection(conn); conn->mConnectSendCount = 0; conn->mConnectLastSendTime = getCurrentTime(); sendPunchPackets(conn); } void NetInterface::sendPunchPackets(NetConnection *conn) { ConnectionParameters &theParams = conn->getConnectionParameters(); PacketStream out; out.write(U8(Punch)); if(theParams.mIsInitiator) theParams.mNonce.write(&out); else theParams.mServerNonce.write(&out); U32 encryptPos = out.getBytePosition(); out.setBytePosition(encryptPos); if(theParams.mIsInitiator) theParams.mServerNonce.write(&out); else { theParams.mNonce.write(&out); if(out.writeFlag(mRequiresKeyExchange || (theParams.mRequestKeyExchange && !mPrivateKey.isNull()))) { if(out.writeFlag(theParams.mRequestCertificate && !mCertificate.isNull())) out.write(mCertificate); else out.write(mPrivateKey->getPublicKey()); } } SymmetricCipher theCipher(theParams.mArrangedSecret); out.hashAndEncrypt(NetConnection::MessageSignatureBytes, encryptPos, &theCipher); for(S32 i = 0; i < theParams.mPossibleAddresses.size(); i++) { out.sendto(mSocket, theParams.mPossibleAddresses[i]); TNLLogMessageV(LogNetInterface, ("Sending punch packet (%s, %s) to %s", ByteBuffer(theParams.mNonce.data, Nonce::NonceSize).encodeBase64()->getBuffer(), ByteBuffer(theParams.mServerNonce.data, Nonce::NonceSize).encodeBase64()->getBuffer(), theParams.mPossibleAddresses[i].toString())); } conn->mConnectSendCount++; conn->mConnectLastSendTime = getCurrentTime(); } void NetInterface::handlePunch(const Address &theAddress, BitStream *stream) { S32 i, j; NetConnection *conn; Nonce firstNonce; firstNonce.read(stream); ByteBuffer b(firstNonce.data, Nonce::NonceSize); TNLLogMessageV(LogNetInterface, ("Received punch packet from %s - %s", theAddress.toString(), b.encodeBase64()->getBuffer())); for(i = 0; i < mPendingConnections.size(); i++) { conn = mPendingConnections[i]; ConnectionParameters &theParams = conn->getConnectionParameters(); if(conn->getConnectionState() != NetConnection::SendingPunchPackets) continue; if((theParams.mIsInitiator && firstNonce != theParams.mServerNonce) || (!theParams.mIsInitiator && firstNonce != theParams.mNonce)) continue; // first see if the address is in the possible addresses list: for(j = 0; j < theParams.mPossibleAddresses.size(); j++) if(theAddress == theParams.mPossibleAddresses[j]) break; // if there was an exact match, just exit the loop, or // continue on to the next pending if this is not an initiator: if(j != theParams.mPossibleAddresses.size()) { if(theParams.mIsInitiator) break; else continue; } // if there was no exact match, we may have a funny NAT in the // middle. But since a packet got through from the remote host // we'll want to send a punch to the address it came from, as long // as only the port is not an exact match: for(j = 0; j < theParams.mPossibleAddresses.size(); j++) if(theAddress.isEqualAddress(theParams.mPossibleAddresses[j])) break; // if the address wasn't even partially in the list, just exit out if(j == theParams.mPossibleAddresses.size()) continue; // otherwise, as long as we don't have too many ping addresses, // add this one to the list: if(theParams.mPossibleAddresses.size() < 5) theParams.mPossibleAddresses.push_back(theAddress); // if this is the initiator of the arranged connection, then // process the punch packet from the remote host by issueing a // connection request. if(theParams.mIsInitiator) break; } if(i == mPendingConnections.size()) return; ConnectionParameters &theParams = conn->getConnectionParameters(); SymmetricCipher theCipher(theParams.mArrangedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, stream->getBytePosition(), &theCipher)) return; Nonce nextNonce; nextNonce.read(stream); if(nextNonce != theParams.mNonce) return; // see if the connection needs to be authenticated or uses key exchange if(stream->readFlag()) { if(stream->readFlag()) { theParams.mCertificate = new Certificate(stream); if(!theParams.mCertificate->isValid() || !conn->validateCertficate(theParams.mCertificate, true)) return; theParams.mPublicKey = theParams.mCertificate->getPublicKey(); } else { theParams.mPublicKey = new AsymmetricKey(stream); if(!theParams.mPublicKey->isValid() || !conn->validatePublicKey(theParams.mPublicKey, true)) return; } if(mPrivateKey.isNull() || mPrivateKey->getKeySize() != theParams.mPublicKey->getKeySize()) { // we don't have a private key, so generate one for this connection theParams.mPrivateKey = new AsymmetricKey(theParams.mPublicKey->getKeySize()); } else theParams.mPrivateKey = mPrivateKey; theParams.mSharedSecret = theParams.mPrivateKey->computeSharedSecretKey(theParams.mPublicKey); //logprintf("shared secret (client) %s", theParams.mSharedSecret->encodeBase64()->getBuffer()); Random::read(theParams.mSymmetricKey, SymmetricCipher::KeySize); theParams.mUsingCrypto = true; } conn->setNetAddress(theAddress); TNLLogMessageV(LogNetInterface, ("Punch from %s matched nonces - connecting...", theAddress.toString())); conn->setConnectionState(NetConnection::AwaitingConnectResponse); conn->mConnectSendCount = 0; conn->mConnectLastSendTime = getCurrentTime(); sendArrangedConnectRequest(conn); } void NetInterface::sendArrangedConnectRequest(NetConnection *conn) { TNLLogMessageV(LogNetInterface, ("Sending Arranged Connect Request")); PacketStream out; ConnectionParameters &theParams = conn->getConnectionParameters(); out.write(U8(ArrangedConnectRequest)); theParams.mNonce.write(&out); U32 encryptPos = out.getBytePosition(); U32 innerEncryptPos = 0; out.setBytePosition(encryptPos); theParams.mServerNonce.write(&out); if(out.writeFlag(theParams.mUsingCrypto)) { out.write(theParams.mPrivateKey->getPublicKey()); innerEncryptPos = out.getBytePosition(); out.setBytePosition(innerEncryptPos); out.write(SymmetricCipher::KeySize, theParams.mSymmetricKey); } out.writeFlag(theParams.mDebugObjectSizes); out.write(conn->getInitialSendSequence()); conn->writeConnectRequest(&out); if(innerEncryptPos) { SymmetricCipher theCipher(theParams.mSharedSecret); out.hashAndEncrypt(NetConnection::MessageSignatureBytes, innerEncryptPos, &theCipher); } SymmetricCipher theCipher(theParams.mArrangedSecret); out.hashAndEncrypt(NetConnection::MessageSignatureBytes, encryptPos, &theCipher); conn->mConnectSendCount++; conn->mConnectLastSendTime = getCurrentTime(); out.sendto(mSocket, conn->getNetAddress()); } void NetInterface::handleArrangedConnectRequest(const Address &theAddress, BitStream *stream) { S32 i, j; NetConnection *conn; Nonce nonce, serverNonce; nonce.read(stream); // see if the connection is in the main connection table. // If the connection is in the connection table and it has // the same initiatorSequence, we'll just resend the connect // acceptance packet, assuming that the last time we sent it // it was dropped. NetConnection *oldConnection = findConnection(theAddress); if(oldConnection) { ConnectionParameters &cp = oldConnection->getConnectionParameters(); if(cp.mNonce == nonce) { sendConnectAccept(oldConnection); return; } } for(i = 0; i < mPendingConnections.size(); i++) { conn = mPendingConnections[i]; ConnectionParameters &theParams = conn->getConnectionParameters(); if(conn->getConnectionState() != NetConnection::SendingPunchPackets || theParams.mIsInitiator) continue; if(nonce != theParams.mNonce) continue; for(j = 0; j < theParams.mPossibleAddresses.size(); j++) if(theAddress.isEqualAddress(theParams.mPossibleAddresses[j])) break; if(j != theParams.mPossibleAddresses.size()) break; } if(i == mPendingConnections.size()) return; ConnectionParameters &theParams = conn->getConnectionParameters(); SymmetricCipher theCipher(theParams.mArrangedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, stream->getBytePosition(), &theCipher)) return; stream->setBytePosition(stream->getBytePosition()); serverNonce.read(stream); if(serverNonce != theParams.mServerNonce) return; if(stream->readFlag()) { if(mPrivateKey.isNull()) return; theParams.mUsingCrypto = true; theParams.mPublicKey = new AsymmetricKey(stream); theParams.mPrivateKey = mPrivateKey; U32 decryptPos = stream->getBytePosition(); stream->setBytePosition(decryptPos); theParams.mSharedSecret = theParams.mPrivateKey->computeSharedSecretKey(theParams.mPublicKey); SymmetricCipher theCipher(theParams.mSharedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher)) return; // now read the first part of the connection's session (symmetric) key stream->read(SymmetricCipher::KeySize, theParams.mSymmetricKey); Random::read(theParams.mInitVector, SymmetricCipher::KeySize); } U32 connectSequence; theParams.mDebugObjectSizes = stream->readFlag(); stream->read(&connectSequence); TNLLogMessageV(LogNetInterface, ("Received Arranged Connect Request")); if(oldConnection) disconnect(oldConnection, NetConnection::ReasonSelfDisconnect, ""); conn->setNetAddress(theAddress); conn->setInitialRecvSequence(connectSequence); if(theParams.mUsingCrypto) conn->setSymmetricCipher(new SymmetricCipher(theParams.mSymmetricKey, theParams.mInitVector)); const char *errorString = NULL; if(!conn->readConnectRequest(stream, &errorString)) { sendConnectReject(&theParams, theAddress, errorString); removePendingConnection(conn); return; } addConnection(conn); removePendingConnection(conn); conn->setConnectionState(NetConnection::Connected); conn->onConnectionEstablished(); sendConnectAccept(conn); } //----------------------------------------------------------------------------- // NetInterface disconnection and handling //----------------------------------------------------------------------------- void NetInterface::disconnect(NetConnection *conn, NetConnection::TerminationReason reason, const char *reasonString) { if(conn->getConnectionState() == NetConnection::AwaitingChallengeResponse || conn->getConnectionState() == NetConnection::AwaitingConnectResponse) { conn->onConnectTerminated(reason, reasonString); removePendingConnection(conn); } else if(conn->getConnectionState() == NetConnection::Connected) { conn->setConnectionState(NetConnection::Disconnected); conn->onConnectionTerminated(reason, reasonString); if(conn->isNetworkConnection()) { // send a disconnect packet... PacketStream out; out.write(U8(Disconnect)); ConnectionParameters &theParams = conn->getConnectionParameters(); theParams.mNonce.write(&out); theParams.mServerNonce.write(&out); U32 encryptPos = out.getBytePosition(); out.setBytePosition(encryptPos); out.writeString(reasonString); if(theParams.mUsingCrypto) { SymmetricCipher theCipher(theParams.mSharedSecret); out.hashAndEncrypt(NetConnection::MessageSignatureBytes, encryptPos, &theCipher); } out.sendto(mSocket, conn->getNetAddress()); } removeConnection(conn); } } void NetInterface::handleDisconnect(const Address &address, BitStream *stream) { NetConnection *conn = findConnection(address); if(!conn) return; ConnectionParameters &theParams = conn->getConnectionParameters(); Nonce nonce, serverNonce; char reason[256]; nonce.read(stream); serverNonce.read(stream); if(nonce != theParams.mNonce || serverNonce != theParams.mServerNonce) return; U32 decryptPos = stream->getBytePosition(); stream->setBytePosition(decryptPos); if(theParams.mUsingCrypto) { SymmetricCipher theCipher(theParams.mSharedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher)) return; } stream->readString(reason); conn->setConnectionState(NetConnection::Disconnected); conn->onConnectionTerminated(NetConnection::ReasonRemoteDisconnectPacket, reason); removeConnection(conn); } void NetInterface::handleConnectionError(NetConnection *theConnection, const char *errorString) { disconnect(theConnection, NetConnection::ReasonError, errorString); } }; <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" NxCCDSkeleton *pFactory::createCCDSkeleton(CKBeObject *meshReference,int flags) { #ifdef _DEBUG assert(meshReference); #endif // _DEBUG NxCCDSkeleton *result = NULL; CKMesh *mesh = NULL; if (meshReference->GetClassID()==CKCID_MESH ) mesh = static_cast<CKMesh*>(meshReference); else if( meshReference->GetClassID() == CKCID_3DOBJECT && ((CK3dEntity*)meshReference)->GetCurrentMesh() ) mesh = ((CK3dEntity*)meshReference)->GetCurrentMesh(); if (!mesh) return NULL; int numVerts = mesh->GetVertexCount(); int numFaces = mesh->GetFaceCount(); NxReal *vertices = new float[3 * numVerts]; NxVec3 *verts = new NxVec3[numVerts]; for (int i = 0 ; i< numVerts ; i++ ) { VxVector v; mesh->GetVertexPosition(i,&v); vertices[i * 3] = v.x; vertices[i * 3 + 1] =v.y; vertices[i * 3 + 2] = v.z; } NxU32 *indices2 = new NxU32[numFaces*3]; for(int j = 0 ; j < numFaces ; j++) { int findicies[3]; mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); indices2[ j *3 ] = findicies[0]; indices2[ j *3 + 1 ] = findicies[1]; indices2[ j *3 + 2 ] = findicies[2]; } NxSimpleTriangleMesh descr; descr.numVertices = numVerts; descr.pointStrideBytes = sizeof(NxReal)*3; descr.points = vertices; descr.numTriangles = numFaces; descr.triangles = indices2; descr.triangleStrideBytes = sizeof(NxU32)*3; descr.flags = NX_MF_FLIPNORMALS; if (GetPMan()->getPhysicsSDK()) { result = GetPMan()->getPhysicsSDK()->createCCDSkeleton(descr); } delete [] vertices; delete [] verts; delete [] indices2; return result; } void pFactory::createConvexMesh(NxScene *scene,CKMesh *mesh,NxConvexMeshDesc&descr) { if (!scene || !mesh) { return; } int numVerts = mesh->GetVertexCount(); int numFaces = mesh->GetFaceCount(); NxReal *vertices = new float[3 * numVerts]; NxVec3 *verts = new NxVec3[numVerts]; for (int i = 0 ; i< numVerts ; i++ ) { VxVector v; mesh->GetVertexPosition(i,&v); vertices[i * 3] = v.x; vertices[i * 3 + 1] =v.y; vertices[i * 3 + 2] = v.z; } NxU32 *indices2 = new NxU32[numFaces*3]; for(int j = 0 ; j < numFaces ; j++) { int findicies[3]; mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); indices2[ j *3 ] = findicies[0]; indices2[ j *3 + 1 ] = findicies[1]; indices2[ j *3 + 2 ] = findicies[2]; } descr.numVertices = numVerts; descr.pointStrideBytes = sizeof(NxReal)*3; descr.points = vertices; descr.numTriangles = numFaces; descr.triangles = indices2; descr.triangleStrideBytes = sizeof(NxU32)*3; descr.flags = NX_CF_COMPUTE_CONVEX; /* delete [] vertices; delete [] verts; delete [] indices2;*/ } void pFactory::createMesh(NxScene *scene,CKMesh *mesh,NxTriangleMeshDesc&descr) { if (!scene || !mesh) { return; } int numVerts = mesh->GetVertexCount(); int numFaces = mesh->GetFaceCount(); NxReal *vertices = new float[3 * numVerts]; NxVec3 *verts = new NxVec3[numVerts]; for (int i = 0 ; i< numVerts ; i++ ) { VxVector v; mesh->GetVertexPosition(i,&v); vertices[i * 3] = v.x; vertices[i * 3 + 1] =v.y; vertices[i * 3 + 2] = v.z; } NxU32 *indices2 = new NxU32[numFaces*3]; for(int j = 0 ; j < numFaces ; j++) { int findicies[3]; mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); indices2[ j *3 ] = findicies[0]; indices2[ j *3 + 1 ] = findicies[1]; indices2[ j *3 + 2 ] = findicies[2]; } descr.numVertices = numVerts; descr.pointStrideBytes = sizeof(NxReal)*3; descr.points = vertices; descr.numTriangles = numFaces; descr.triangles = indices2; descr.triangleStrideBytes = sizeof(NxU32)*3; descr.flags = 0; /* delete [] vertices; delete [] verts; delete [] indices2; */ } <file_sep>#ifndef __P_BOX_CONTROLLER_H__ #define __P_BOX_CONTROLLER_H__ #include "pTypes.h" class BoxController; class pBoxController { public: pBoxController(const NxControllerDesc& desc, NxScene* scene); virtual ~pBoxController(); void move(const VxVector& disp, int activeGroups, float minDist, int& collisionFlags, float sharpness, const pGroupsMask* groupsMask); //bool setPosition(const VxVector& position) { return setPos(position); } pRigidBody* getBody() const; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // NxpBoxController const VxVector& getExtents() const; bool setExtents(const VxVector& extents); void setStepOffset(const float offset); VxVector getPosition()const; VxVector& getFilteredPosition(); bool getWorldBox(VxBbox& box) const; void setCollision(bool enabled); //virtual void setInteraction(NxCCTInteractionFlag flag) { Controller::setInteraction(flag); } //virtual NxCCTInteractionFlag getInteraction() const { return Controller::getInteraction(); } //vi//rtual void reportSceneChanged(); //virtual void* getUserData() const { return userData; } private: BoxController *mBoxController; }; #endif //AGCOPYRIGHTBEGIN /////////////////////////////////////////////////////////////////////////// // Copyright (c) 2005 AGEIA Technologies. // All rights reserved. www.ageia.com /////////////////////////////////////////////////////////////////////////// //AGCOPYRIGHTEND <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorLogEntryDecl(); CKERROR CreateLogEntryProto(CKBehaviorPrototype **); int LogEntry(const CKBehaviorContext& behcontext); CKERROR LogEntryCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 0 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorLogEntryDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("pLogEvent"); od->SetDescription("Displays Internal Log Entries"); od->SetCategory("Physics/Manager"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x512542dc,0x1b836fd9)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateLogEntryProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateLogEntryProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("pLogEvent"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Off"); proto->DeclareOutput("Message"); proto->DeclareOutput("Error"); proto->DeclareOutput("Warning"); proto->DeclareOutput("Info"); proto->DeclareOutput("Trace"); proto->DeclareOutput("Debug"); proto->DeclareOutParameter("Entry",CKPGUID_STRING); proto->DeclareOutParameter("Type",CKPGUID_INT); proto->DeclareOutParameter("Component",CKPGUID_STRING); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETERINPUTS )); proto->SetFunction(LogEntry); proto->SetBehaviorCallbackFct(LogEntryCB); *pproto = proto; return CK_OK; } int LogEntry(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); XString File((CKSTRING) beh->GetInputParameterReadDataPtr(0)); if (GetPMan()->GetLastLogEntry().Length()) { CKParameterOut *pout = beh->GetOutputParameter(0); pout->SetStringValue(GetPMan()->GetLastLogEntry().Str()); GetPMan()->SetLastLogEntry(""); vtTools::BehaviorTools::SetOutputParameterValue<int>(beh,1,xLogger::GetInstance()->lastTyp); int descriptionS = xLogger::GetInstance()->getItemDescriptions().size(); int compo = xLogger::GetInstance()->lastComponent; XString compoStr; /*if(compo<= xLogger::GetInstance()->getItemDescriptions().size() ) compoStr.Format("%s",xLogger::GetInstance()->getItemDescriptions().at(compo));*/ beh->ActivateOutput(0,TRUE); switch (xLogger::GetInstance()->lastTyp) { case ELOGERROR: beh->ActivateOutput(1,TRUE); case ELOGWARNING: beh->ActivateOutput(2,TRUE); case ELOGINFO: beh->ActivateOutput(3,TRUE); case ELOGTRACE: beh->ActivateOutput(4,TRUE); case ELOGDEBUG: beh->ActivateOutput(5,TRUE); default: beh->ActivateOutput(0,TRUE); } } // Steering if( beh->IsInputActive(1) ) { beh->ActivateOutput(0,FALSE); return 1; } return CKBR_ACTIVATENEXTFRAME; } CKERROR LogEntryCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { /* CKParameterIn* pin = beh->GetInputParameter(0); if (!pin) { CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : failed to retrieve first input parameter"; behcontext.Context->OutputToConsole(str.Str(),TRUE); return CKBR_PARAMETERERROR; } if (pin->GetGUID()!=CKPGUID_MESSAGE) { pin->SetGUID(CKPGUID_MESSAGE,FALSE); CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : first input parameter type must be \"Message\"!"; behcontext.Context->OutputToConsole(str.Str(),TRUE); } pin = beh->GetInputParameter(1); if (!pin) { CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : failed to retrieve second input parameter"; behcontext.Context->OutputToConsole(str.Str(),TRUE); return CKBR_PARAMETERERROR; } if (!behcontext.ParameterManager->IsDerivedFrom(pin->GetGUID(),CKPGUID_OBJECT)) { pin->SetGUID(CKPGUID_BEOBJECT,FALSE); CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : second input parameter type must derived from \"BeObject\"!"; behcontext.Context->OutputToConsole(str.Str(),TRUE); }*/ } return CKBR_OK; }<file_sep><Paths> RenderEngines = RenderEngines ManagerPath = Managers BehaviorPath = BuildingBlocks PluginPath = Plugins LoadFile1 = gallery_start_noText_012.cmo LoadFile = serverInit.cmo InstallDirectory = X:\sdk\dev4 </Paths> <VideoSettings> DisableSwitch = 0 WindowWidth = 400 WindowHeight = 300 FullscreenWidth = 1024 FullscreenHeight = 768 Bpp = 32 Driver = 1 FullScreen = 0 RefreshRate = 60 Mode = 0 AntiAlias = 0 HasResolutionMask = 1 XResolutions = 400,1024,800 YResolutions = 300,768,600 OpenGLVersions = 2.0 </VideoSettings> <ApplicationConfiguration> MouseDragsWindow = 1 OwnerDrawed = 0 Render = 1 AlwayOnTop = 0 ScreenSaverMode = 0 MouseMovesTerminatePlayer = 0 Resizeable = 1 CaptionBar = 1 ShowDialog = 0 ShowAboutTab = 0 ShowConfigTab = 1 MinDirectXVersion = 9 MinRAM = 256 SizeBox = 1 Title = Network Test UseSplash = 0 ShowLoadingProcess = 1 </ApplicationConfiguration> <Textures> entry0=Resource\3DChatResourceDB\Textures entry1=Resource\3DChatResourceDB\Textures\Dialogs </Textures><file_sep>#ifndef __VT_MODULE_ERROR_STRINGS_H__ #define __VT_MODULE_ERROR_STRINGS_H__ /*! * \brief * String to describe the error's source */ static char* sLogItems[]= { "AGEIA", "MANAGER", "VSL", }; /*! * \brief * String to describe generic return codes */ static char* sErrorStrings[]= { "OK", "Ageia error", "Invalid parameter", "Invalid operation", }; /*! * \brief * String to describe component specific return codes * */ static char* sBBErrorStrings[]= { "OK", "\t Intern :", "\t Parameter invalid :", "\t Reference object invalid:", "\t XML error:", "\t Invalid File:", "\t Reference object is not physicalized:", "\t Reference object doesn't contains a vehicle controller:", "\t Reference object is not a wheel:", "\t Reference object is not a joint:", "\t Reference object is not a cloth:", "\t Couldn't initialize PhysX :", }; #endif // __VTMODULEERRORSTRINGS_H__<file_sep>#ifndef __UX_STRING_H__ #define __UX_STRING_H__ #include <tchar.h> #include <wchar.h> #include <stdlib.h> #include <string> typedef char TAnsiChar; #ifdef _WIN32 typedef wchar_t TUnicodeChar; #else typedef unsigned short TUnicodeChar; #endif // // Define an alias for the native character data type // #ifdef _UNICODE typedef TUnicodeChar TChar; #else typedef TAnsiChar TChar; #endif // // This macro creates an ASCII string (actually a no-op) // #define __A(x) (x) // // This macro creates a Unicode string by adding the magic L before the string // #define __U(x) (L##x) // // Define an alias for building a string in the native format // #ifdef _UNICODE #define T __U #else #define T __A #endif //=============================================================================== // // uxString // class uxString { public: //======================================================= // // Construction and destruction // uxString() // Default constructor, just creates an empty string. { Text = NULL; Len = Size = 0; } uxString(const uxString& String) // Copy constructor, makes an instance an exact copy of { // another string. AssignFrom(String); } uxString(const TChar *String) // Constructor building a string from a regular C string { // of characters in native format. AssignFrom(String); } #ifdef _UNICODE uxString(const TAnsiChar *String) // Constructor building a Unicode string from a regular C { // string in ANSI format (used for doing conversions). if (String == NULL) // Early out if string is NULL { Text = NULL; Size = Len = 0; return; } Size = strlen(String) + 1; // Use ANSI strlen function Len = Size-1; Text = AllocStr(Size); for (int i=0 ; i<Len ; i++) // Convert ANSI->Unicode char-by-char Text[i] = (TUnicodeChar)String[i]; Text[Len] = __A('\0'); } #else uxString(const TUnicodeChar *String) // Constructor building an ANSI string from a regular C { // string in Unicode format (used for doing conversions). if (String == NULL) // Early out if string is NULL { Text = NULL; Size = Len = 0; return; } Size = wcslen(String) + 1; // Use Unicode wcslen function Len = Size-1; Text = AllocStr(Size); for (int i=0 ; i<Len ; i++) // Convert Unicode->ANSI char-by-char Text[i] = (TAnsiChar)String[i]; Text[Len] = __A('\0'); } #endif virtual ~uxString() // Destructor. The use of virtual is recommended in C++ { // for all destructors that can potentially be overloaded. if (Size && Text != NULL) // Free the memory used by the string FreeStr(Text); } //======================================================= // // Accessors // TChar *GetString() const // Returns a pointer to the actual string data. { return Text; } const int GetLength() const // Returns the length of the string currently { // held by an instance of the string class. return Len; } const bool IsNull() const // Returns true if a NULL string is held by an instance. { return (Text == NULL || !_tcslen(Text)); } const bool IsValidIndex(const int Index) const // Returns true if the character index { // specified is within the bounds of the string. return (Index >= 0 && Index < Len); } const TAnsiChar *CStr() const { return Text ? Text : NULL; } //======================================================= // // Regular transformation functions // int Compare(const uxString& String, bool IgnoreCase=false) const // Compares another string { // with this instance. Return if (IsNull() && !String.IsNull()) // values equals those of strcmp(), return 1; // ie -1, 0 or 1 (Less, Equal, Greater) else if (!IsNull() && String.IsNull()) // ... Trivial cases return -1; else if (IsNull() && String.IsNull()) return 0; if (IgnoreCase) return _tcsicmp(Text, String.Text); else return _tcscmp(Text, String.Text); } bool Find(uxString& Str, int& Pos, bool IgnoreCase=false) const // Finds a substring within this string. { // Returns true if found (position in Pos). if (IsNull() || Str.IsNull()) return false; // Define a function pointer that will be used to call the appropriate // compare function based on the value of IgnoreCase. int (* cmpfn)(const TCHAR*, const TCHAR*, size_t) = (IgnoreCase) ? _tcsnicmp : _tcsncmp; for (Pos=0 ; Pos<=(Len-Str.Len) ; Pos++) { if (cmpfn(&Text[Pos], Str.Text, Str.Len) == 0) return true; } return false; } void Delete(int Pos, int Count) // Deletes the specified number of characters, { // starting at the specified position. if (Pos > Len || Count==0) // Start is outside string or nothing to delete? return; if (Pos + Count > Len) // Clamp Count to string length Count = (Len - Pos); // Characters are deleted by moving up the data following the region to delete. for (int i=Pos ; i<Len-Count ; i++) Text[i] = Text[i+Count]; Len -= Count; Text[Len] = T('\0'); Optimize(); } void Insert(int Pos, TChar c) // Inserts a character at the given position in the string. { if (Pos<0 || Pos>Len) return; Grow(1); // Grow the string by one byte to be able to hold character // Move down rest of the string. // Copying overlapping memory blocks requires the use of memmove() instead of memcpy(). memmove((void *)&Text[Pos+1], (const void *)&Text[Pos], Len-Pos); Text[Pos] = c; Text[++Len] = T('\0'); } void Insert(int Pos, const uxString& String) // Inserts a complete string at the given { // location. if (Pos<0 || Pos>Len || String.IsNull()) return; TChar *New = AllocStr(String.Len + Len + 1); if (Pos > 0) // Set the string portion before the inserted string _tcsncpy(New, Text, Pos); _tcsncpy(&New[Pos], String.Text, String.Len); // Insert the string if (Len-Pos > 0) // Insert rest of orignal string _tcsncpy(&New[Pos+String.Len], &Text[Pos], Len-Pos); AssignFrom(New); // Copy new string back into stringobject } uxString GetSubString(int Start, int Count, uxString& Dest) // Crops out a substring. { if (!IsValidIndex(Start) || Count <= 0) // Valid operation? { Dest = T(""); return Dest; } TChar *Temp = AllocStr(Count + 1); _tcsncpy(Temp, &Text[Start], Count); Temp[Count] = T('\0'); Dest = Temp; FreeStr(Temp); return Dest; } //======================================================= // // Special transformation functions // void VarArg(TChar *Format, ...) // Allows you to fill a string object with data in the { // same way you use sprintf() /*TChar Buf[0x1000]; // Need lots of space va_list argptr; va_start(argptr, Format); #ifdef _UNICODE vswprintf(Buf, Format, argptr); #else vsprintf(Buf, Format, argptr); #endif va_end(argptr); Size = _tcslen(Buf) + 1; Len = _tcslen(Buf); FreeStr(Text); Text = AllocStr(Size); if (Len > 0) _tcscpy(Text, Buf); else Text[0] = T('\0');*/ } void EatLeadingWhitespace() // Convenient function that removes all whitespace { // (tabs and spaces) at the beginning of a string. if (IsNull()) return; int i=0; for (i=0 ; i<Len ; i++) { if (Text[i] != 0x20 && Text[i] != 0x09) break; } Delete(0, i); } void EatTrailingWhitespace() // Convenient function that removes all whitespace { // (tabs and spaces) from the end of a string. if (IsNull()) return; int i=0; for (i=Len-1 ; i>=0 ; i--) { if (Text[i] != 0x20 && Text[i] != 0x09) break; } Delete(i+1, Len-i-1); } //======================================================= // // Conversion functions // TAnsiChar *ToAnsi(TAnsiChar *Buffer, int BufferLen) const // Converts the string to an ANSI string. { int i, ConvertLen; if (BufferLen <= 0) { Buffer = NULL; return Buffer; } if (BufferLen >= Len) ConvertLen = Len; else ConvertLen = BufferLen-1; for (i=0 ; i<ConvertLen ; i++) { #ifdef _UNICODE if (Text[i] > 255) // If character is a non-ANSI Unicode character, fill with Buffer[i] = 0x20; // space instead. else #endif Buffer[i] = (TAnsiChar)Text[i]; } Buffer[i] = __A('\0'); return Buffer; } TUnicodeChar *ToUnicode(TUnicodeChar *Buffer, int BufferLen) const // Converts the string { // to a Unicode string. int i, ConvertLen; if (BufferLen <= 0) { Buffer = NULL; return Buffer; } if (BufferLen >= Len) ConvertLen = Len; else ConvertLen = BufferLen-1; for (i=0 ; i<ConvertLen ; i++) Buffer[i] = (TUnicodeChar)Text[i]; Buffer[i] = __U('\0'); return Buffer; } int ToInt() const // Converts the string to an integer. { if (IsNull()) return 0; #ifdef _UNICODE return _wtoi(Text); // Unicode version of atoi #else return atoi(Text); // ANSI version of atoi #endif } //======================================================= // // Assignment operators // void operator =(const uxString& String) // Sets this string to the contents of another string. { AssignFrom(String); } void operator =(const TChar *String) // Sets this string to the contents of a character array { // in native format. AssignFrom(String); } #ifdef _UNICODE void operator =(const TAnsiChar *String) // Sets this string to the contents of a character array { // in ANSI format (only included in Unicode builds) if (String == NULL) { Text = NULL; Size = Len = 0; return; } Size = strlen(String) + 1; // Use ANSI strlen function Len = Size-1; Text = AllocStr(Size); for (int i=0 ; i<Len ; i++) // Convert ANSI->Unicode char-by-char Text[i] = (TUnicodeChar)String[i]; Text[Len] = A('\0'); } #else void operator =(const TUnicodeChar *String) // Sets this string to the contents of a character array { // in Unicode format (only included in ANSI builds) if (String == NULL) { Text = NULL; Size = Len = 0; return; } Size = wcslen(String) + 1; // Use Unicode wcslen function Len = Size-1; Text = AllocStr(Size); for (int i=0 ; i<Len ; i++) // Convert Unicode->ANSI char-by-char Text[i] = (TAnsiChar)String[i]; Text[Len] = __A('\0'); } #endif //======================================================= // // Concatenation operators // inline friend uxString operator +(const uxString& Str1, const uxString& Str2); // Concatenates two strings (see text) void operator +=(const uxString& String) // Adds another string to the end of the { // current one. if (String.Len > 0) { Grow(String.Len); _tcsncpy(&Text[Len], String.Text, String.Len); Len += String.Len; } } //======================================================= // // Access operators // operator TChar *() const // Returns the address of the contained string. { return Text; } TChar& uxString::operator [](int Pos) // Returns a character reference at a { // specific location. if (Pos < 0) // If underrun, just return first character return Text[0]; else if (Pos >= Len) // If overrun, expand string in accordance { Grow(Pos+2); return Text[Pos]; } else // Otherwise, just return character return Text[Pos]; } //======================================================= // // Comparison operators (operates through Compare()). // Functions exist for comparing both string objects and character arrays. // bool operator < (const uxString& Str) const { return (bool)(Compare(Str) == -1); } bool operator > (const uxString& Str) const { return (bool)(Compare(Str) == 1); } bool operator <=(const uxString& Str) const { return (bool)(Compare(Str) != 1); } bool operator >=(const uxString& Str) const { return (bool)(Compare(Str) != -1); } bool operator ==(const uxString& Str) const { return (bool)(Compare(Str) == 0); } bool operator !=(const uxString& Str) const { return (bool)(Compare(Str) != 0); } bool operator < (const TChar *Chr) const { return (bool)(Compare(uxString(Chr)) == -1); } bool operator > (const TChar *Chr) const { return (bool)(Compare(uxString(Chr)) == 1); } bool operator <=(const TChar *Chr) const { return (bool)(Compare(uxString(Chr)) != 1); } bool operator >=(const TChar *Chr) const { return (bool)(Compare(uxString(Chr)) != -1); } bool operator ==(const TChar *Chr) const { return (bool)(Compare(uxString(Chr)) == 0); } bool operator !=(const TChar *Chr) const { return (bool)(Compare(uxString(Chr)) != 0); } //======================================================= // // Protected low-level functions // protected: void Optimize() // Discards any unused space allocated for the string { Size = Len + 1; TChar *Temp = AllocStr(Size); _tcscpy(Temp, Text); FreeStr(Text); Text = Temp; } void Grow(int Num) // Allocates some more memory so the string can hold an additional Num characters { Size += Num; TChar *Temp = AllocStr(Size); _tcscpy(Temp, Text); FreeStr(Text); Text = Temp; } void AssignFrom(uxString& Str) // Does the hard work for all non-converting assignments { Size = Str.Size; Len = Str.Len; if (Size && Len) // No point copying an empty string { Text = AllocStr(Size); _tcscpy(Text, Str.Text); } else { Text = NULL; } } void AssignFrom(const TChar *Str) // Does the hard work for all non-converting assignments { if (Str == NULL) // Early out if string is NULL { Text = NULL; Size = Len = 0; return; } Size = _tcslen(Str) + 1; Len = Size-1; Text = AllocStr(Size); _tcscpy(Text, Str); } static TChar *AllocStr(int Size) // Allocates a new character array. You can modify this { // function if you for instance use a custom memory manager. //return new TChar[Size]; return (TChar *)calloc(Size, sizeof(TChar)); } static void FreeStr(TChar *Ptr) // Ditto { if (Ptr == NULL) return; //delete [] Ptr; free(Ptr); } //======================================================= // // Protected data members // protected: TChar *Text; // The actual character array int Size; // Number of bytes allocated for string int Len; // Number of characters in string public: // Concatenation operator uxString& operator << (const TChar* rValue) { Insert(Len,rValue); return *this; } uxString& operator<<(const int iValue) { /*uxString buffer = uxString::AllocStr(15); #ifdef _UNICODE _itow(iValue,buffer.GetString(),10); #else _itot(iValue,buffer.GetString(),10); #endif */ char * szReal = new char[ 512 ]; sprintf( szReal, "%d",iValue); uxString buffer(szReal); delete [ ] szReal; int i = strlen(buffer.GetString()); int s=buffer.GetLength(); //buffer.EatTrailingWhitespace(); //buffer.Insert(buffer.Len+2,"\0"); Insert(Len,buffer); return *this; } }; //======================================================= // // Concatenation function (must be global for reasons stated in the text) // inline uxString operator +(const uxString& Str1, const uxString& Str2) { TChar *Temp = uxString::AllocStr(Str1.Size + Str2.Size); // Allocate memory for new string if (Str1.Len) // Copy first string into dest _tcscpy(Temp, Str1.Text); if (Str2.Len) // Copy second string into dest _tcscpy(&Temp[Str1.Len], Str2.Text); uxString Result = Temp; return Result; } #endif //__UX_STRING_H__<file_sep>#ifndef __P_LINEAR_INTERPOLATION_H__ #define __P_LINEAR_INTERPOLATION_H__ #include "NxMath.h" #include "NxSimpleTypes.h" #include <stdio.h> #include <map> class pLinearInterpolation { typedef std::map<float, float> MapType; typedef MapType::iterator MapIterator; typedef MapType::const_iterator ConstMapIterator; MapType _map; NxF32 _min, _max; public: pLinearInterpolation (): _min(0), _max(0), _map() { } void clear() { _map.clear(); } void insert(float index, float value) { if (_map.empty()) _min = _max = index; else { _min = NxMath::min(_min, index); _max = NxMath::max(_max, index); } _map[index] = value; } void print() const { ConstMapIterator it = _map.begin(); for (; it != _map.end(); ++it) { printf("%2.3f -> %2.3f\n", it->first, it->second); } } bool isValid(float number) const { return number>=_min && number<=_max; } float getValue(float number) const { ConstMapIterator lower = _map.begin(); if (number < _min) return lower->second; ConstMapIterator upper = _map.end(); upper--; if (number > _max) return upper->second; upper = _map.lower_bound(number); if (upper == lower) return (upper->second); lower = upper; lower--; //printf("- %2.3f %2.3f\n", lower->first, upper->first); float w1 = number - lower->first; float w2 = upper->first - number; return ((w2 * lower->second) + (w1 * upper->second)) / (w1 + w2); } NxF32 getValueAtIndex(NxI32 index) const { ConstMapIterator it = _map.begin(); for (int i = 0; i < index; i++) ++it; return it->second; } void operator=(const pLinearInterpolation& other) { _map.insert(other._map.begin(), other._map.end()); _max = other._max; _min = other._min; } int getSize() const { return _map.size(); } }; #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPJRevoluteDecl(); CKERROR CreatePJRevoluteProto(CKBehaviorPrototype **pproto); int PJRevolute(const CKBehaviorContext& behcontext); CKERROR PJRevoluteCB(const CKBehaviorContext& behcontext); enum bbInputs { bI_ObjectB, bI_Anchor, bI_AnchorRef, bI_Axis, bI_AxisRef, bbI_Collision, bbI_PMode, bbI_PDistance, bbI_PAngle, bbI_Spring, bbI_HighLimit, bbI_LowLimit, bbI_Motor }; //************************************ // Method: FillBehaviorPJRevoluteDecl // FullName: FillBehaviorPJRevoluteDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPJRevoluteDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJRevolute"); od->SetCategory("Physic/Joints"); od->SetDescription("Sets/modifies a revolute joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x77cb361c,0x670112a9)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJRevoluteProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJRevoluteProto // FullName: CreatePJRevoluteProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePJRevoluteProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJRevolute"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJRevolute <br> PJRevolute is categorized in \ref Joints <br> <br>See <A HREF="PJRevolute.cmo">PJRevolute.cmo</A>. <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Creates or modifies a revolute joint. <br> <br> DOFs removed: 5<br> DOFs remaining: 1<br> <br> \image html revoluteJoint.png A revolute joint removes all but a single rotational degree of freedom from two objects. The axis along which the two bodies may rotate is specified with a point and a direction vector. In theory, the point along the direction vector does not matter, but in practice, it should be near the area where the bodies are closest to improve simulation stability. An example for a revolute joint is a door hinge. Another example would be using a revolute joint to attach rotating fan blades to a ceiling. The revolute joint could be motorized, causing the fan to rotate. <h3>Technical Information</h3> \image html PJRevolute.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Body B: </SPAN>The second body. Leave blank to create a joint constraint with the world. <BR> <BR> <SPAN CLASS="pin">Anchor:</SPAN>A point in world space coordinates. See pJointRevolute::setGlobalAnchor(). <BR> <SPAN CLASS="pin">Anchor Reference: </SPAN>A helper entity to transform a local anchor into the world space. <BR> <SPAN CLASS="pin">Axis: </SPAN>An in world space. See pJointRevolute::setGlobalAxis(). <BR> <SPAN CLASS="pin">Axis Up Reference: </SPAN>A helper entity to transform a local axis into the world space. <BR> <BR> <hr> <SPAN CLASS="pin">Collision: </SPAN>Enable Collision. See pJointRevolute::enableCollision(). <BR> <hr> <SPAN CLASS="pin">Projection Mode: </SPAN>Joint projection mode. See pJointRevolute::setProjectionMode() and #ProjectionMode. <BR> <SPAN CLASS="pin">Projection Distance: </SPAN>If any joint projection is used, it is also necessary to set projectionDistance to a small value greater than zero. When the joint error is larger than projectionDistance the SDK will change it so that the joint error is equal to projectionDistance. Setting projectionDistance too small will introduce unwanted oscillations into the simulation.See pJointRevolute::setProjectionDistance(). <br> <SPAN CLASS="pin">Projection Angle: </SPAN>Angle must be greater than 0.02f .If its smaller then current algo gets too close to a singularity. See pJointRevolute::setProjectionAngle(). <BR> <hr> <SPAN CLASS="pin">Spring: </SPAN>Make it springy.See pJointRevolute::setSpring(). <BR> <hr> <SPAN CLASS="pin">High Limit: </SPAN>Higher rotation limit around the rotation axis. See pJointRevolute::setHighLimit(). <BR> <SPAN CLASS="pin">Low Limit: </SPAN>Lower rotation limit around rotation axis. See pJointRevolute::setLowLimit(). <BR> <hr> <SPAN CLASS="pin">Motor: </SPAN>Motor parameters. See pJointRevolute::setMotor(). <BR> <BR> <hr> <SPAN CLASS="setting">Spring: </SPAN>Enables parameter input for spring settings. <BR> <SPAN CLASS="setting">High Limit: </SPAN>Enables parameter inputs for angular limits. <BR> <SPAN CLASS="setting">Motor: </SPAN>Enables parameter input for motor settings. <BR> <h4>Revolute Joint Limits</h4> A revolute joint allows limits to be placed on how far it rotates around the joint axis. For example, a hinge on a door cannot rotate through 360 degrees; rather, it can rotate between 20 degrees and 180 degrees. The angle of rotation is measured using the joints normal (axis orthogonal to the joints axis). This is the angle reported by NxRevoluteJoint::getAngle(). The limits are specified as a high and low limit, which must satisfy the condition -Pi < low < high <Pi degrees. Below are valid revolute joint limits in which the joint is able to move between low and high: \image html revoluteJointLimits.png <br> Note : The white region represents the allowable rotation for the joint. <h4>Limitations of Revolute Joint Limits</h4> As shown below, it is not possible to specify certain limit configurations without rotating the joint axes, due to the restrictions on the values of low and high: \image html revoluteLimitLimitation.png To achieve this configuration, it is necessary to rotate the joint counter-clockwise so that low is below the 180 degree line. NOTE: If the angular region that is prohibited by the twist limit (as in the above figures) is very small, only a few degrees or so, then the joint may "push through" the limit and out on the other side if the relative angular velocity is large enough in relation to the time step. Care must be taken to make sure the limit is "thick" enough for the typical angular velocities it will be subjected to. <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>VSL : Creation </h3><br> <SPAN CLASS="NiceCode"> \include PJRevolute.vsl </SPAN> <br> <h3>VSL : Limit Modification </h3><br> <SPAN CLASS="NiceCode"> \include PJRevoluteSetLimits.vsl </SPAN> <br> <h3>VSL : Motor Modification </h3><br> <SPAN CLASS="NiceCode"> \include PJRevoluteSetMotor.vsl </SPAN> <br> <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createJointRevolute().<br> */ proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( PJRevoluteCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Anchor",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY,"0.0f"); proto->DeclareInParameter("Axis",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Collision",CKPGUID_BOOL); proto->DeclareInParameter("Projection Mode",VTE_JOINT_PROJECTION_MODE,"0"); proto->DeclareInParameter("Projection Distance",CKPGUID_FLOAT,"0"); proto->DeclareInParameter("Projection Angle",CKPGUID_FLOAT,"0.025"); proto->DeclareInParameter("Spring",VTS_JOINT_SPRING); proto->DeclareInParameter("High Limit",VTS_JLIMIT); proto->DeclareInParameter("Low Limit",VTS_JLIMIT); proto->DeclareInParameter("Motor",VTS_JOINT_MOTOR); proto->DeclareSetting("Spring",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Limit",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Motor",CKPGUID_BOOL,"FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PJRevolute); *pproto = proto; return CK_OK; } //************************************ // Method: PJRevolute // FullName: PJRevolute // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJRevolute(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Revolute)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA && ! worldB ) { return 0; } if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); //anchor : VxVector anchor = GetInputParameterValue<VxVector>(beh,bI_Anchor); VxVector anchorOut = anchor; CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); if (anchorReference) { anchorReference->Transform(&anchorOut,&anchor); } //swing axis VxVector Axis = GetInputParameterValue<VxVector>(beh,bI_Axis); VxVector axisOut = Axis; CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); if (axisReference) { VxVector dir,up,right; axisReference->GetOrientation(&dir,&up,&right); axisReference->TransformVector(&axisOut,&up); } ////////////////////////////////////////////////////////////////////////// //limit high : pJointLimit limitH; pJointLimit limitL; DWORD limit; beh->GetLocalParameterValue(1,&limit); if (limit) { CKParameterIn *par = beh->GetInputParameter(bbI_HighLimit); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { limitH = pFactory::Instance()->createLimitFromParameter(rPar); } } } if (limit) { CKParameterIn *par = beh->GetInputParameter(bbI_LowLimit); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { limitL = pFactory::Instance()->createLimitFromParameter(rPar); } } } ////////////////////////////////////////////////////////////////////////// DWORD spring; pSpring sSpring; beh->GetLocalParameterValue(0,&spring); if (spring) { CKParameterIn *par = beh->GetInputParameter(bbI_Spring); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { sSpring = pFactory::Instance()->createSpringFromParameter(rPar); } } } pMotor motor; DWORD hasMotor;beh->GetLocalParameterValue(2,&hasMotor); if (hasMotor) { CKParameterIn *par = beh->GetInputParameter(bbI_Motor); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { motor = pFactory::Instance()->createMotorFromParameter(rPar); } } } int col = GetInputParameterValue<int>(beh,bbI_Collision); ProjectionMode mode =GetInputParameterValue<ProjectionMode>(beh,bbI_PMode); float distance = GetInputParameterValue<float>(beh,bbI_PDistance); float angle= GetInputParameterValue<float>(beh,bbI_PAngle); ////////////////////////////////////////////////////////////////////////// // pJointRevolute *joint = static_cast<pJointRevolute*>(worldA->getJoint(target,targetB,JT_Revolute)); if(bodyA || bodyB) { ////////////////////////////////////////////////////////////////////////// //joint create ? if (!joint) { joint = static_cast<pJointRevolute*>(pFactory::Instance()->createRevoluteJoint(target,targetB,anchorOut,axisOut)); } ////////////////////////////////////////////////////////////////////////// Modification : if (joint) { joint->setGlobalAxis(axisOut); joint->setGlobalAnchor(anchorOut); if (mode!=0) { joint->setProjectionMode(mode); joint->setProjectionDistance(distance); joint->setProjectionAngle(angle); } ////////////////////////////////////////////////////////////////////////// if(limit) { joint->setHighLimit(limitH); joint->setLowLimit(limitL); } ////////////////////////////////////////////////////////////////////////// if (spring) { joint->setSpring(sSpring); } if (hasMotor) { joint->setMotor(motor); } joint->enableCollision(col); } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: PJRevoluteCB // FullName: PJRevoluteCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJRevoluteCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD twistLimit; beh->GetLocalParameterValue(1,&twistLimit); beh->EnableInputParameter(bbI_HighLimit,twistLimit); beh->EnableInputParameter(bbI_LowLimit,twistLimit); DWORD springSwing; beh->GetLocalParameterValue(0,&springSwing); beh->EnableInputParameter(bbI_Spring,springSwing); DWORD motor; beh->GetLocalParameterValue(2,&motor); beh->EnableInputParameter(bbI_Motor,motor); break; } } return CKBR_OK; }<file_sep>#include <StdAfx.h> //#include "stdafx.h" #include <pch.h> #include <io.h> #include <fcntl.h> #include "ConStream.h" using namespace std; // // The ConStream constructor initializes the object to point to the // NUL device. It does this by calling two consecutive constructors. // First, the member variable m_Nul is initialized with a FILE object // created by opening device "nul", the bit bucket. Second, the base // class constructor is called with a reference to m_Nul, which is // an ofstream object. This sets up ConStream so that it will direct // its output to the given file. // ConStream::ConStream() : m_Nul( m_fNul = fopen( "nul", "w" ) ), #ifdef _UNICODE basic_ostream<wchar_t>( &m_Nul ) #else basic_ostream<char>( &m_Nul ) #endif { lastLine = 0 ; fp; buf = new char[MAX_PATH]; m_FileBuf = 0; m_hConsole = INVALID_HANDLE_VALUE; } // // The ConStream destructor always has to close the m_fNul FILE object // which was created in the constructor. Even if the Open() method has // been called and the bit bucket isn't being used, the FILE object is // still using memory and a system file handle. // // If the ConStream object has been opened with a call to member function // Open(), we have to call the Win32 API function FreeConsole() to close // the console window. If the console window was open, we also call the // C fclose() function on the m_fConsole member. // ConStream::~ConStream() { delete m_FileBuf; if ( m_hConsole != INVALID_HANDLE_VALUE ) { FreeConsole(); fclose( fp ); } fclose( fp ); } // // Opening the stream means doing these things: // 1) Opening a Win32 console using the Win32 API // 2) Getting an O/S handle to the console // 3) Converting the O/S handle to a C stdio file handle // 4) Converting the C stdio file handler to a C FILE object // 5) Attaching the C FILE object to a C++ filebuf // 6) Attaching the filebuf object to this // 7) Disabling buffering so we see our output in real time. // void ConStream::Open() { // allocate a console for this app AllocConsole(); // set the screen buffer to be big enough to let us scroll text // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w+" ); *stdout = *fp; //setvbuf( stdout, buf, _IOFBF , MAX_PATH ); setvbuf( stdout, NULL, _IONBF , 0); // redirect unbuffered STDIN to the console lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "r+" ); *stdin = *fp; // setvbuf( stdin, buf, _IOFBF, MAX_PATH ); setvbuf( stdin, NULL, _IONBF , 0); // redirect unbuffered STDERR to the console lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w+" ); *stderr = *fp; //setvbuf( stderr, buf, _IOFBF, MAX_PATH ); setvbuf( stderr, NULL, _IONBF, 0); /*SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);*/ // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well ios::sync_with_stdio(); }; // // Closing the ConStream is considerably simpler. We just use the // init() call to attach this to the NUL file stream, then close // the console descriptors. // void ConStream::Close() { if ( fp != INVALID_HANDLE_VALUE ) { init( &m_Nul ); FreeConsole(); fclose( fp ); // fp = INVALID_HANDLE_VALUE; } }; <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtAttributeHelper.h" void PhysicManager::_checkObjectsByAttribute() { CKAttributeManager* attman = m_Context->GetAttributeManager(); int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;//(sizeof(*getRegistrationTable()) / sizeof((getRegistrationTable())[0])); for (int fIndex = 0 ; fIndex < sizeJFuncMap ; fIndex ++) { std::vector<int>attributeIdList; pFactory::Instance()->findAttributeIdentifiersByGuid(getRegistrationTable()[fIndex].guid,attributeIdList); int attCount = attributeIdList.size(); for (int i = 0 ; i < attCount ; i++ ) { int currentAttType = attributeIdList.at(i); const XObjectPointerArray& Array = attman->GetAttributeListPtr( attributeIdList.at(i) ); for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { CK3dEntity *target = static_cast<CK3dEntity*>(*it); if (target) { XString error; error.Format("Registering :%s with %s",target->GetName(),attman->GetAttributeNameByType(currentAttType)); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.CStr() ); (*getRegistrationTable()[fIndex].rFunc)(target,currentAttType,true,false); } } } } } void PhysicManager::_RegisterAttributeCallbacks() { if (!getAttributeFunctions().Size()) { return; } CKAttributeManager* attman = m_Context->GetAttributeManager(); AttributeFunctionArrayIteratorType it = getAttributeFunctions().Begin(); while(it != getAttributeFunctions().End()) { ObjectRegisterFunction myFn = (ObjectRegisterFunction)*it; if (myFn) { attman->SetAttributeCallbackFunction(it.GetKey(),PObjectAttributeCallbackFunc,myFn); } it++; } } void PhysicManager::cleanAttributePostObjects() { using namespace vtTools::ParameterTools; if (!getAttributePostObjects().Size()) return; CKAttributeManager* attman = m_Context->GetAttributeManager(); PostRegistrationArrayIteratorType it = getAttributePostObjects().Begin(); while(it != getAttributePostObjects().End()) { pAttributePostObject& post = *it; CK3dEntity *refObject = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(post.objectId)); if (refObject) { ObjectRegisterFunction regFn = (ObjectRegisterFunction)post.func; if (regFn) { (*regFn)(refObject,post.attributeID,true,false); } } it++; } int s = getAttributePostObjects().Size(); getAttributePostObjects().Clear(); } void PhysicManager::populateAttributeFunctions() { getAttributeFunctions().Clear(); int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;// (sizeof(*getRegistrationTable()) / sizeof(ObjectRegistration)); for (int fIndex = 0 ; fIndex < sizeJFuncMap ; fIndex ++) { #ifdef _DEBUG //XString _errorStr; //getRegistrationTable()[fIndex].rFunc. //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.Str()); #endif std::vector<int>attributeIdList; pFactory::Instance()->findAttributeIdentifiersByGuid(getRegistrationTable()[fIndex].guid,attributeIdList); int attCount = attributeIdList.size(); for (int i = 0 ; i < attCount ; i++ ) { int currentAttType = attributeIdList.at(i); getAttributeFunctions().Insert(currentAttType,getRegistrationTable()[fIndex].rFunc); } } } ObjectRegistration*PhysicManager::getRegistrationTable() { return attributeFunctionMap; } <file_sep>// racer/driveline.h #ifndef __P_DRIVELINE_H__ #define __P_DRIVELINE_H__ #include "vtPhysXBase.h" #include "XString.h" /* #ifdef RR_FIXED_TIMESTEP #define RR_TIMESTEP 0.01f #else #define RR_TIMESTEP 0.01f #endif */ #define D3_EPSILON (0.00001f) // Generic constants #ifndef PI #define PI 3.14159265358979 #endif // Clutch must be smoothed out a lot when applying starts #define DEFAULT_CLUTCH_LINEARITY 0.3f // Threshold at which force an unlock of engine and gearbox. // This can happen if the driver just throws in a gear, // without clutching (and if autoclutch is off). // We should penalize this with a gear scratch sound and // damage. #define DELTA_VEL_THRESHOLD 1.0f class pDriveLine; class MODULE_API pDriveLineComp // Driveline component base class { protected: // Administration XString name; // For easier debugging pDriveLineComp *parent, // Bi-directional tree *child[2]; pDriveLine *driveLine; // Part of which driveline private: // Static data float inertia; // Inertia of this component float ratio; // Gearing ratio (gearbox/differential) float invRatio; // 1/ratio (optimized multiplication) // Semi-static data (recalculated when gear is changed) float effectiveInertiaDownStream; // Inertia of component + children float cumulativeRatio; // Ratio at this point of the driveline // Dynamic data protected: float tReaction, // Reaction torque tBraking, // Braking torque (also a reaction torque) tEngine; // Torque from the engine side // State float rotV, // Rotational velocity rotA; // Rotational acceleration public: pDriveLineComp(); virtual ~pDriveLineComp(); // Attribs XString GetName(){ return name.CStr(); } void SetName(XString s){ name=s; } float GetInertia(){ return inertia; } void SetInertia(float i){ inertia=i; } float GetRatio(){ return ratio; } void SetRatio(float r); float GetInverseRatio(){ return invRatio; } float GetEffectiveInertia(){ return effectiveInertiaDownStream; } float GetCumulativeRatio(){ return cumulativeRatio; } pDriveLine *GetDriveLine(); void SetDriveLine(pDriveLine *dl){ driveLine=dl; } pDriveLineComp *GetParent(){ return parent; } pDriveLineComp *GetChild(int n); float GetReactionTorque(){ return tReaction; } float GetBrakingTorque(){ return tBraking; } float GetEngineTorque(){ return tEngine; } float GetRotationVel(){ return rotV; } void SetRotationVel(float v){ rotV=v; } float GetRotationAcc(){ return rotA; } void SetRotationAcc(float a){ rotA=a; } // Attaching to other components void AddChild(pDriveLineComp *comp); void SetParent(pDriveLineComp *comp); // Reset for new use virtual void Reset(); // Precalculation void CalcEffectiveInertia(); void CalcCumulativeRatio(); // Physics void CalcReactionForces(); void CalcEngineForces(); virtual void CalcForces(); virtual void CalcAccelerations(); virtual void Integrate(); // Debugging void DbgPrint(int depth,XString s); }; class MODULE_API pDriveLine // A complete driveline // Includes the clutch and the handbrakes { public: pDriveLineComp *root; // Root of driveline tree; the engine pDriveLineComp *gearbox; // The gearbox is always there pVehicle *car; // Static driveline data int diffs; // Number of differentials // Semi-static driveline data (changes when gear is changed) float preClutchInertia, // Total inertia before clutch (engine) postClutchInertia, // After clutch (gearbox, diffs) totalInertia; // Pre and post clutch inertia // Clutch float clutchApplication, // 0..1 (how much clutch is applied) clutchLinearity, // A linear clutch was too easy to stall clutchMaxTorque, // Clutch maximum generated torque (Nm) clutchCurrentTorque; // Clutch current torque (app*max) bool autoClutch; // Assist takes over clutch? // Handbrakes float handbrakeApplication; // 0..1 (control) // Dynamic bool prepostLocked; // Engine is locked to rest of drivetrain? float tClutch; // Directed clutch torque (+/-clutchCurT) public: pDriveLine(pVehicle *car); ~pDriveLine(); // Attribs void SetRoot(pDriveLineComp *comp); pDriveLineComp *GetRoot(){ return root; } pDriveLineComp *GetGearBox(){ return gearbox; } void SetGearBox(pDriveLineComp *c){ gearbox=c; } bool IsSingleDiff(){ return diffs==1; } int GetDifferentials(){ return diffs; } void SetDifferentials(int n){ diffs=n; } bool IsPrePostLocked(){ return prepostLocked; } void LockPrePost(){ prepostLocked=true; } void UnlockPrePost(){ prepostLocked=false; } float GetClutchTorque(){ return tClutch; } // Precalculation void CalcCumulativeRatios(); void CalcEffectiveInertiae(); void CalcPreClutchInertia(); void CalcPostClutchInertia(); // Clutch float GetClutchApplication(){ return clutchApplication; } float GetClutchMaxTorque(){ return clutchMaxTorque; } float GetClutchCurrentTorque(){ return clutchCurrentTorque; } void SetClutchApplication(float app); bool IsAutoClutchActive(){ return autoClutch; } void EnableAutoClutch(){ autoClutch=true; } void DisableAutoClutch(){ autoClutch=false; } // Handbrakes float GetHandBrakeApplication(){ return handbrakeApplication; } // Definition // Input void SetInput(int ctlClutch,int ctlHandbrake); // Physics void Reset(); void CalcForces(); void CalcAccelerations(); void Integrate(); // Debugging void DbgPrint(XString& s); }; #endif <file_sep>#include "StdAfx2.h" #include "PCommonDialog.h" #include "PBodySetup.h" #include "PBodyTabCtrl.h" #include "PBXMLSetup.h" #include "resource.h" #include "VITabCtrl.h" #include "resource.h" #include "VITabCtrl.h" #include "VIControl.h" #include "..\..\include\interface\pcommondialog.h" /************************************************************************/ /* Global vars */ /************************************************************************/ static CPSharedBase *gXML=NULL; static CPSharedBase *gCOMMON=NULL; static CPSharedBase *gCOLLISION=NULL; static CPSharedBase *gOPTIMIZATION=NULL; static CPSharedBase* gSharedBase=NULL; static CPSharedBase *gDialogs[DLGCOUNT] = { gXML, gCOMMON, }; CPBParentDialog::CPBParentDialog(CKParameter* Parameter,CWnd*parent,CK_CLASSID Cid) : CParameterDialog(Parameter,Cid) , CPSharedBase(Parameter,this,Cid) , m_TabControl(parent) { if (_cleanUpIfNew(Parameter)) { _emptyTabs(); } if (gSharedBase) gSharedBase=NULL; gSharedBase =this; setRootDialog(this); setRootParameter(Parameter); getInstance(); //loadTabPane(); } CPBParentDialog::CPBParentDialog(CKParameter* Parameter,CK_CLASSID Cid) : CParameterDialog(Parameter,Cid) , CPSharedBase(Parameter,this,Cid) , m_TabControl(NULL) { if (_cleanUpIfNew(Parameter)) { _emptyTabs(); } gSharedBase = this; setRootDialog(this); setRootParameter(Parameter); //loadTabPane(); } void CPBParentDialog::_destroy() { if (getTabs().GetTabCount()) { _emptyTabs(); } gSharedBase=NULL; } /* CPBParentDialog::CPBParentDialog(CWnd* pParent = NULL) : CParameterDialog(Parameter,Cid) , CPSharedBase(Parameter,this,Cid) { if (_cleanUpIfNew(Parameter)) { _emptyTabs(); } gSharedBase = this; setRootDialog(this); setRootParameter(Parameter); }*/ /************************************************************************/ /* */ /************************************************************************/ /************************************************************************/ /* */ /************************************************************************/ BOOL CPSharedBase::initChildWin(CDialog* pDlg, UINT dialogID,UINT dialogPlaceHolderID) { ASSERT( pDlg ); if (!pDlg) { return false; } // wind handle of the target bed : HWND dstWindow = NULL; CPBParentDialog* parent = (CPBParentDialog*)getInstance()->getRootDlg(); if (parent) { dstWindow = parent->getDlgWindowHandle(dialogPlaceHolderID); }else return false; CWnd *cDstWindow = CWnd::FromHandle(dstWindow); if (cDstWindow) { int p = getNbDialogs(); }else { return false; } //CWnd* pWnd = pDlg->GetDlgItem( dialogPlaceHolderID ); CRect rcValue; if (pDlg) { cDstWindow->GetWindowRect( &rcValue ); // Use picture box position. parent->ScreenToClient( &rcValue ); if (pDlg->Create( dialogID, cDstWindow )) { pDlg->SetWindowPos( cDstWindow, rcValue.left, rcValue.top,rcValue.Width(), rcValue.Height(), SWP_HIDEWINDOW); return true; } //pWnd->ShowWindow(SWP_SHOWWINDOW); } return false; } void CPSharedBase::_dtrBodyCommonDlg(){} CPSharedBase* CPSharedBase::getDialog(int identifier) { ASSERT( identifier >= 0 && identifier < DLGCOUNT ); if (gDialogs[identifier]) return gDialogs[identifier]; return NULL; } void CPSharedBase::setDialog(int identifier,CPSharedBase*src) { ASSERT( identifier >= 0 && identifier < DLGCOUNT ); //if (gDialogs[identifier] != src ) gDialogs[identifier] = src; } void CPSharedBase::destroyDialog(int identifier,CPSharedBase*src) { ASSERT( identifier >= 0 && identifier < DLGCOUNT ); if (src) { } src = gDialogs[identifier] = NULL; } CParameterDialog *CPSharedBase::getRootDlg() { return getInstance() ? getInstance()->dlgRoot : NULL; } CKParameter *CPSharedBase::getRootParameter() { return getInstance() ? getInstance()->parameter : NULL; } void CPSharedBase::setRootParameter(CKParameter * val) { if (getInstance()) getInstance()->parameter = val; } void CPSharedBase::setRootDialog(CParameterDialog * val) { if (getInstance()) getInstance()->dlgRoot = val; } ParDialogArrayType& CPSharedBase::getDialogs() { return getInstance() ? getInstance()->mDialogs : ParDialogArrayType() ; } CPSharedBase::~CPSharedBase() { _reset(); } void CPSharedBase::_destroy() { } void CPSharedBase::_reset() { parameter = NULL; dlgRoot = NULL; mDialogs.Clear(); mTab = NULL; } void CPSharedBase::_construct() { } CPSharedBase::CPSharedBase( CKParameter* Parameter, CParameterDialog *rootDialog, CK_CLASSID Cid) : dlgRoot(rootDialog) , parameter(Parameter) { mDialogs.Clear(); mTab = NULL; } CPSharedBase::CPSharedBase(CKParameter* Parameter,CK_CLASSID Cid) { dlgRoot=NULL; mDialogs.Clear(); mTab = NULL; } CPSharedBase*CPSharedBase::getInstance() { return gSharedBase; } CPSharedBase::CPSharedBase(CParameterDialog *consumer,CKParameter* parameter) { addDialog(consumer,parameter); } void CPSharedBase::addDialog(CParameterDialog *dlg,CKParameter*parameter) { /*if(getInstance() && (*getDialogs().FindPtr(parameter))) getDialogs().InsertUnique(parameter,dlg); */ } CPSharedBase** CPSharedBase::getStaticDialogs() { return gDialogs; } int CPSharedBase::getNbDialogs() { int result = 0; for ( int i = 0 ; i < DLGCOUNT ; i++ ) { if (getStaticDialogs()[i] != NULL ) { result++; } } return result; } /* LRESULT CPBParentDialog::OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam) { WORD keyState = 0; keyState |= (::GetKeyState(VK_CONTROL) < 0) ? MK_CONTROL : 0; keyState |= (::GetKeyState(VK_SHIFT) < 0) ? MK_SHIFT : 0; LRESULT lResult; HWND hwFocus = ::GetFocus(); const HWND hwDesktop = ::GetDesktopWindow(); if (hwFocus == NULL) lResult = SendMessage(WM_MOUSEWHEEL, (wParam << 16) | keyState, lParam); else { do { lResult = ::SendMessage(hwFocus, WM_MOUSEWHEEL,(wParam << 16) | keyState, lParam); hwFocus = ::GetParent(hwFocus); } while (lResult == 0 && hwFocus != NULL && hwFocus != hwDesktop); } return lResult; } */ /* void CPBParentDialog::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { //int cStates = GET_KEYSTATE_WPARAM(wParam); int wheelDirection = zDelta; if (wheelDirection>0) { if ( mTestViControl.GetActiveTabIndex() +1 < mTestViControl.GetTabCount() ) { mTestViControl.SetActiveTab(mTestViControl.GetActiveTabIndex() +1 ); }else{ mTestViControl.SetActiveTab( 0 ); } }else { if ( mTestViControl.GetActiveTabIndex() -1 >=0 ) { mTestViControl.SetActiveTab(mTestViControl.GetActiveTabIndex() - 1 ); }else{ mTestViControl.SetActiveTab(mTestViControl.GetTabCount()); } } } */ void CPBParentDialog::InitAllControls() { CRect rect; EnableWindow(true); PBodyTabContrl* viCtrl = getTabControl(); if (!viCtrl)return; GetClientRect(&rect); HRESULT res = ((VITabCtrl*)getTabControl())->Create("NoName",VITabCtrl::VITAB_UP|VITabCtrl::VITAB_DOWN,rect,((CWnd*)(getTabControl())),IDC_PBODY_TAB_PANE); getTabControl()->GetClientRect(&rect); getTabControl()->_construct(); getTabControl()->GetClientRect(&rect); /************************************************************************/ /* */ /************************************************************************/ // wind handle of the target bed : HWND dstWindow = NULL; CWnd *cDstWindow = NULL; CPBParentDialog* parent = (CPBParentDialog*)getInstance()->getRootDlg(); if (parent) { dstWindow = parent->getDlgWindowHandle(IDC_SPACER); if (dstWindow) { cDstWindow= CWnd::FromHandle(dstWindow); CRect rcValue; cDstWindow->GetWindowRect( &rcValue ); // Use picture box position. parent->ScreenToClient( &rcValue ); CWnd * target = parent->GetDlgItem(IDC_PBODY_TAB_PANE); if (target) { //target->SetWindowPos( cDstWindow, rcValue.left, rcValue.top,rcValue.Width(), rcValue.Height(), SWP_SHOWWINDOW); //pWnd->ShowWindow(SWP_SHOWWINDOW); } } } /************************************************************************/ /* */ /************************************************************************/ //CPBParentDialog* parent = (CPBParentDialog*)getInstance()->getRootDlg(); int err = getTabControl()->InsertTab(-1,"XML",parent,true); err = getTabControl()->InsertTab(-1,"XMLasas",parent,true ); VITabCtrl::VITab *bTab= new VITabCtrl::VITab(); bTab->m_Flags=VITabCtrl::VITAB_BORDER; bTab->m_Name = "XML"; bTab->m_Width = 30; bTab->m_Wnd = NULL; err = getTabControl()->GetTabCount(); err = getTabControl()->InsertTab(-1,bTab,true); // parent->ScreenToClient( &rect ); // getTabControl()->ScreenToClient(&rect); //*/ } int CPBParentDialog::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (__super::OnCreate(lpCreateStruct) == -1) return -1; return 1; } <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Keyboard Camera Orbit // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "GeneralCameraOrbit.h" CKObjectDeclaration *FillBehaviorKeyboardCameraOrbitDecl(); CKERROR CreateKeyboardCameraOrbitProto(CKBehaviorPrototype **pproto); int KeyboardCameraOrbit(const CKBehaviorContext& behcontext); void ProcessKeyboardInputs(VxVector* RotationAngles, CKBehavior* beh, CKInputManager *input, float delta, CKBOOL &Returns, CKBOOL &stopping); CKObjectDeclaration *FillBehaviorKeyboardCameraOrbitDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Keyboard Camera Orbit"); od->SetDescription("Makes a Camera orbit round a 3D Entity using keyboard with limited angles."); /* rem: <SPAN CLASS=in>On: </SPAN>Starts the behavior.<BR> <SPAN CLASS=in>Off: </SPAN>Stops the behavior.<BR> <SPAN CLASS=out>Exit On: </SPAN>is activated when the behavior has been started.<BR> <SPAN CLASS=out>Exit Off: </SPAN>is activated when the behavior has been stop. If in "return" mode, is activated only once the camera is back in place.<BR> <BR> <SPAN CLASS=pin>Target Position: </SPAN>Position we are turning around.<BR> <SPAN CLASS=pin>Target Referential: </SPAN>Referential where the position is defined.<BR> <SPAN CLASS=pin>Move Speed: </SPAN>Speed in angle per second used when the user moves the camera.<BR> <SPAN CLASS=pin>Return Speed: </SPAN>Speed in angle per second used when the camera returns.<BR> <SPAN CLASS=pin>Min Horizontal: </SPAN>Minimal angle allowed on the horizontal rotation. Must have a negative value.<BR> <SPAN CLASS=pin>Max Horizontal:</SPAN>Maximal angle allowed on the horizontal rotation. Must have a positive value.<BR> <SPAN CLASS=pin>Min Vertical: </SPAN>Minimal angle allowed on the vertical rotation. Must have a negative value.<BR> <SPAN CLASS=pin>Max Vertical: </SPAN>Maximal angle allowed on the vertical rotation. Must have a positive value.<BR> <SPAN CLASS=pin>Zoom Speed: </SPAN>Speed of the zoom in distance per second.<BR> <SPAN CLASS=pin>Zoom Min: </SPAN>Minimum zoom value allowed. Must have a negative value.<BR> <SPAN CLASS=pin>Zoom Max: </SPAN>Maximum zoom value allowed. Must have a positive value.<BR> <BR> The following keys are used by default to move the Camera around its target:<BR> <BR> <FONT COLOR=#FFFFFF>Page Up: </FONT>Zoom in.<BR> <FONT COLOR=#FFFFFF>Page Down: </FONT>Zoom out.<BR> <FONT COLOR=#FFFFFF>Up and Down Arrows: </FONT>Rotate vertically.<BR> <FONT COLOR=#FFFFFF>Left and Right Arrows: </FONT>Rotate horizontally.<BR> The arrow keys are the inverted T arrow keys and not the ones of the numeric keypad.<BR> <BR> <SPAN CLASS=setting>Returns: </SPAN>Does the camera systematically returns to its original position.<BR> <SPAN CLASS=setting>Key Rotate Left: </SPAN>Key used to rotate left.<BR> <SPAN CLASS=setting>Key Rotate Right: </SPAN>Key used to rotate right.<BR> <SPAN CLASS=setting>Key Rotate Up: </SPAN>Key used to rotate up.<BR> <SPAN CLASS=setting>Key Rotate Down: </SPAN>Key used to rotate down.<BR> <SPAN CLASS=setting>Key Zoom in: </SPAN>Key used to zoom in.<BR> <SPAN CLASS=setting>Key Zoom out: </SPAN>Key used to zoom in.<BR> <BR> */ od->SetCategory("Cameras/Movement"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7610f4d,0x69747b9d)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateKeyboardCameraOrbitProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(INPUT_MANAGER_GUID); return od; } ////////////////////////////////////////////////////////////////////////////// // // Prototype creation // ////////////////////////////////////////////////////////////////////////////// CKERROR CreateKeyboardCameraOrbitProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Keyboard Camera Orbit"); if(!proto) return CKERR_OUTOFMEMORY; // General Description CKERROR error = FillGeneralCameraOrbitProto(proto); if (error != CK_OK) return (error); // Additionnal Settings for the Keyboard proto->DeclareSetting("Key Rotate Left", CKPGUID_KEY,"Left Arrow"); proto->DeclareSetting("Key Rotate Right", CKPGUID_KEY,"Right Arrow"); proto->DeclareSetting("Key Rotate Up", CKPGUID_KEY,"Up Arrow"); proto->DeclareSetting("Key Rotate Down", CKPGUID_KEY,"Down Arrow"); proto->DeclareSetting("Key Zoom In", CKPGUID_KEY,"PREVIOUS"); proto->DeclareSetting("Key Zoom Out", CKPGUID_KEY,"NEXT"); // Set the execution functions proto->SetFunction(KeyboardCameraOrbit); proto->SetBehaviorCallbackFct(GeneralCameraOrbitCallback,CKCB_BEHAVIORSETTINGSEDITED|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORCREATE); // return OK *pproto = proto; return CK_OK; } ////////////////////////////////////////////////////////////////////////////// // // Main Function // ////////////////////////////////////////////////////////////////////////////// int KeyboardCameraOrbit(const CKBehaviorContext& behcontext) { return ( GeneralCameraOrbit(behcontext,ProcessKeyboardInputs) ); } ////////////////////////////////////////////////////////////////////////////// // // Function that process the inputs // ////////////////////////////////////////////////////////////////////////////// void ProcessKeyboardInputs(VxVector* RotationAngles, CKBehavior* beh, CKInputManager *input, float delta, CKBOOL &Returns, CKBOOL &stopping) { // Is the move limited ? CKBOOL Limited = TRUE; beh->GetLocalParameterValue(LOCAL_LIMITS,&Limited); // Gets the keys settings int key_left=0; beh->GetLocalParameterValue(LOCAL_KEY_LEFT,&key_left); if(!key_left) key_left=CKKEY_LEFT; int key_right=0; beh->GetLocalParameterValue(LOCAL_KEY_RIGHT,&key_right); if(!key_right) key_right=CKKEY_RIGHT; int key_up=0; beh->GetLocalParameterValue(LOCAL_KEY_UP,&key_up); if(!key_up) key_up=CKKEY_UP; int key_down=0; beh->GetLocalParameterValue(LOCAL_KEY_DOWN,&key_down); if(!key_down) key_down=CKKEY_DOWN; int key_Zin=0; beh->GetLocalParameterValue(LOCAL_KEY_ZIN,&key_Zin); if(!key_Zin) key_Zin=CKKEY_PRIOR; int key_Zout=0; beh->GetLocalParameterValue(LOCAL_KEY_ZOUT,&key_Zout); if(!key_Zout) key_Zout=CKKEY_NEXT; //////////////////// // Position Update //////////////////// // If the users is moving the camera if (((input->IsKeyDown(key_left)) || (input->IsKeyDown(key_right)) || (input->IsKeyDown(key_up)) || (input->IsKeyDown(key_down))) && !stopping) { float SpeedAngle = 0.87f; beh->GetInputParameterValue(IN_SPEED_MOVE,&SpeedAngle); SpeedAngle *= delta / 1000; if (Limited) { float MinH = -PI/2; beh->GetInputParameterValue(IN_MIN_H, &MinH); float MaxH = PI/2; beh->GetInputParameterValue(IN_MAX_H, &MaxH); float MinV = -PI/2; beh->GetInputParameterValue(IN_MIN_V, &MinV); float MaxV = PI/2; beh->GetInputParameterValue(IN_MAX_V, &MaxV); if( input->IsKeyDown(key_right) ) RotationAngles->x += XMin(SpeedAngle, MaxH - RotationAngles->x); if( input->IsKeyDown(key_left) ) RotationAngles->x -= XMin(SpeedAngle, RotationAngles->x - MinH); if( input->IsKeyDown(key_down) ) RotationAngles->y += XMin(SpeedAngle, MaxV - RotationAngles->y); if( input->IsKeyDown(key_up) ) RotationAngles->y -= XMin(SpeedAngle, RotationAngles->y - MinV); } else { if( input->IsKeyDown(key_right) ) RotationAngles->x += SpeedAngle; if( input->IsKeyDown(key_left) ) RotationAngles->x -= SpeedAngle; if( input->IsKeyDown(key_down) ) RotationAngles->y += SpeedAngle; if( input->IsKeyDown(key_up) ) RotationAngles->y -= SpeedAngle; } } else if ((Returns) && ((RotationAngles->x != 0) || (RotationAngles->y != 0))) { float ReturnSpeedAngle = 1.75f; beh->GetInputParameterValue(IN_SPEED_RETURN, &ReturnSpeedAngle); ReturnSpeedAngle *= delta / 1000; if( RotationAngles->x < 0 ) RotationAngles->x += XMin(ReturnSpeedAngle, -RotationAngles->x); if( RotationAngles->x > 0 ) RotationAngles->x -= XMin(ReturnSpeedAngle, RotationAngles->x); if( RotationAngles->y < 0 ) RotationAngles->y += XMin(ReturnSpeedAngle, -RotationAngles->y); if( RotationAngles->y > 0 ) RotationAngles->y -= XMin(ReturnSpeedAngle, RotationAngles->y); } //////////////// // Zoom Update //////////////// if ( (input->IsKeyDown(key_Zin)) || (input->IsKeyDown(key_Zout)) && !stopping ) { float ZoomSpeed = 40.0f; beh->GetInputParameterValue(IN_SPEED_ZOOM, &ZoomSpeed); ZoomSpeed *= delta / 1000; if (Limited) { float MinZoom = -40.0f; beh->GetInputParameterValue(IN_MIN_ZOOM, &MinZoom); float MaxZoom = 10.0f; beh->GetInputParameterValue(IN_MAX_ZOOM, &MaxZoom); if( input->IsKeyDown(key_Zin) ) RotationAngles->z -= XMin(ZoomSpeed, RotationAngles->z + MaxZoom ); if( input->IsKeyDown(key_Zout) ) RotationAngles->z += XMin(ZoomSpeed, - MinZoom - RotationAngles->z); } else { if( input->IsKeyDown(key_Zin) ) RotationAngles->z -= ZoomSpeed; if( input->IsKeyDown(key_Zout) ) RotationAngles->z += ZoomSpeed; } } } <file_sep>#ifndef _XDISTRIBUTED_3D_OBJECT_CLASS_H_ #define _XDISTRIBUTED_3D_OBJECT_CLASS_H_ #include "xDistributedBaseClass.h" class xDistributed3DObjectClass : public xDistributedClass { public : xDistributed3DObjectClass(); int getFirstUserField(); int getUserFieldBitValue(int walkIndex); int getInternalUserFieldIndex(int inputIndex); int getUserFieldCount(); void addProperty(const char*name,int type,int predictionType); void addProperty(int nativeType,int predictionType); protected : }; #endif <file_sep>/******************************************************************** created: 2009/02/16 created: 16:2:2009 11:07 filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\vtPhysXBase.h file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common file base: vtPhysXBase file ext: h author: <NAME> purpose: Minimal includes for the whole component. + Generic macros and constants, functions + Virtools specific forward decalarations + Generic base types such as std::vector + Component specific forward decalarations + Disabling Module specific Visual Studio compiler Warnings + Prerequisites + Virtools Base Types ( XString, CKGUID, HashTable ) + Constants warning: The order of the includes must stay ! remarks: - This module is using the concept of forward declaration - This header is the base for all other headers. - Do not introduce any platform specific dependencies( ie: windows.h ) *********************************************************************/ #ifndef __VT_PHYSX_BASE_H__ #define __VT_PHYSX_BASE_H__ //################################################################ // // Generic // //---------------------------------------------------------------- // // Include of base types, not involving external dependencies to std,etc.. // #include <xBaseTypes.h> //---------------------------------------------------------------- // // Class to encapsulate a set of flags in a word, using shift operators // #include <xBitSet.h> //---------------------------------------------------------------- // // Macros for generic DLL exports // #include <BaseMacros.h> //---------------------------------------------------------------- // // Include of Virtools related macros // #include <vtBaseMacros.h> //################################################################ // // Component specific constants,strings, error codes // //---------------------------------------------------------------- // // + API Prefix // + Error Codes // + Error Strings // #include "vtModuleConstants.h" //---------------------------------------------------------------- // // Virtools Guids of the plug-in ( manager + building block only !!! ) // // GUIDS for custom enumerations, structures are included by the managers // parameter_x.cpp explicitly ! // #include "vtModuleGuids.h" //---------------------------------------------------------------- // // Enumerations to identifier a custom structure's sub item // #include "vtParameterSubItemIdentifiers_All.h" //---------------------------------------------------------------- // // Enumerations used by the SDK and the Virtools Interface ( Schematics, VSL) // #include "vtInterfaceEnumeration.h" //################################################################ // // Compiler specific warnings // #include "vcWarnings.h" //################################################################ // // Prerequisites // #include "Prerequisites_All.h" #endif<file_sep><Profiling> ProfileEnabled = FALSE ProfilingBar = FALSE ProfilingHistogram = FALSE ProfilingHistogramRate = 2000.000000 </Profiling> <File Options> Textures,Sprites = Global Format Sounds = Includes Original Files Compression = Compressed Compression Level = 4 </File Options> <Globals> StartingFlags = NA </Globals> <BehaviorManager> MaxIteration = 90000 </BehaviorManager> <Sounds> Mixing Method = Software </Sounds> <Statistics> Particles Count = 0 </Statistics> <VSL> Stack Size = 1024 Data Size = 262144 Debug Check = FALSE Show Warnings = FALSE </VSL> <CK2_3D> ForceLinearFog = FALSE EnableScreenDump = FALSE EnableDebugMode = FALSE VertexCache = 16 ForceVBLRate = 0 BatchingMaxVertexCountToBeBatched = 32 BatchingDisable = FALSE EnableRefRasterizer = FALSE DebugModeLineCount = 10 SortTransparentObjects = TRUE TextureCacheManagement = TRUE ForceSoftware = FALSE DisableFilter = FALSE DisableDithering = FALSE DisableMipmap = FALSE DisableSpecular = FALSE DisablePerspectiveCorrection = FALSE UsePixelFog = TRUE DisableAnimationSorting = FALSE Antialias = 0 TextureVideoFormat = 32 bits ARGB 8888 SpriteVideoFormat = 32 bits ARGB 8888 BitmapSystemCaching = Procedural DisplayObjectInformation = NA DX5LightingModel = TRUE LinkLightMapTransparency = FALSE </CK2_3D> <Points Cloud> VerticesPerVB = 16384 DefaultPrecision = 0.000008 </Points Cloud> <file_sep> /* ----------------------------------- */ /* 16 bits declarations */ /* ----------------------------------- */ #ifndef _WIN32 # include <toolhelp.h> # define PostMessage(hWnd,wMsg,wParam,lParam) while (!PostMessage (hWnd,wMsg,wParam,lParam)) Yield (); # define GetCurrentThreadId GetCurrentTask # define Calloc(n,s) (void far *)GlobalAllocPtr(GMEM_SHARE | GMEM_ZEROINIT,n*s) # define Free(p) GlobalFreePtr (p) # define THREADID HTASK /* # define OF_WRITE WRITE # define OF_READ READ */ #endif /* ----------------------------------- */ /* 32 bits redeclarations */ /* ----------------------------------- */ #ifdef _WIN32 # define IsTask(x) ( GetThreadPriority(x)!= THREAD_PRIORITY_ERROR_RETURN \ || GetLastError() != ERROR_INVALID_HANDLE) # define _export # define unlink _unlink # define Calloc(n,s) calloc (n,s) # define Free(p) free (p) # define THREADID DWORD LPSTR GetTempDrive(int nDrive); #endif /* ----------------------------------- */ /* functions defined for compatibility */ /* ----------------------------------- */ HINSTANCE GetTaskInstance (HWND hParentWindow); <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #define PARAMETER_OP_TYPE_IS_CONNECTED CKGUID(0x2fe947dd,0x783224e9) #define PARAM_OP_TYPE_JGET_LIMIT1 CKGUID(0x3678447e,0x30362a74) #define PARAM_OP_TYPE_JGET_LIMIT2 CKGUID(0xc21ab2,0x465f7f69) #define PARAM_OP_TYPE_JGET_LIMIT3 CKGUID(0x3ed57b83,0x47ad145f) //pMotor : #define PARAM_OP_TYPE_JMOTOR_SET_TVEL CKGUID(0xa872a4,0x4e8921a4) #define PARAM_OP_TYPE_JMOTOR_SET_MAXF CKGUID(0x2026057d,0x372684a) #define PARAM_OP_TYPE_JMOTOR_SET_SPIN_FREE CKGUID(0x4aa2636b,0x734a6d4c) #define PARAM_OP_TYPE_JMOTOR_GET_TVEL CKGUID(0x6f91728a,0x29d13cda) #define PARAM_OP_TYPE_JMOTOR_GET_MAXF CKGUID(0x1e583ea9,0x4305055) #define PARAM_OP_TYPE_JMOTOR_GET_SPIN_FREE CKGUID(0x50f145b,0x45df2205) /************************************************************************/ /* joint structures : */ /************************************************************************/ void ParamOpJMotorSetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpJMotorSetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpJMotorSetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpJMotorGetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpJMotorGetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpJMotorGetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpJMotorSetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,0,value,false); } void ParamOpJMotorGetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),0,false); } } res->SetValue(&value); } void ParamOpJMotorSetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,1,value,false); } void ParamOpJMotorGetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),1,false); } } res->SetValue(&value); } void ParamOpJMotorSetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } int value = 0; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<int>(res,2,value,false); } void ParamOpJMotorGetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int value = 0; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),2,false); } } res->SetValue(&value); } /************************************************************************/ /* */ /************************************************************************/ #define PARAM_OP_TYPE_JLIMIT_SET_VALUE CKGUID(0x38a829f0,0x47851486) #define PARAM_OP_TYPE_JLIMIT_SET_RES CKGUID(0x3ce77eb1,0x2e921a87) #define PARAM_OP_TYPE_JLIMIT_SET_HARD CKGUID(0x111a4a9f,0x54094430) #define PARAM_OP_TYPE_JLIMIT_GET_VALUE CKGUID(0xc203321,0x4ca77bd) #define PARAM_OP_TYPE_JLIMIT_GET_RES CKGUID(0x19f812e7,0x5fb3cfc) #define PARAM_OP_TYPE_JLIMIT_GET_HARD CKGUID(0x6b1b44cd,0x5efc7f51) void ParamOpJLimitSetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,0,value,false); } void ParamOpJLimitGetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),0,false); } } res->SetValue(&value); } void ParamOpJLimitSetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,1,value,false); } void ParamOpJLimitGetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),1,false); } } res->SetValue(&value); } void ParamOpJLimitSetHard(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,2,value,false); } void ParamOpJLimitGetHard(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),2,false); } } res->SetValue(&value); } /************************************************************************/ /* spring : */ /************************************************************************/ #define PARAM_OP_TYPE_JSPRING_SET_SPRING CKGUID(0x2e0f1602,0x7f9d30fe) #define PARAM_OP_TYPE_JSPRING_SET_DAMPER CKGUID(0x7392369,0x168f33a1) #define PARAM_OP_TYPE_JSPRING_SET_VALUE CKGUID(0x70026320,0x35b41a38) #define PARAM_OP_TYPE_JSPRING_GET_SPRING CKGUID(0x3dde73ff,0x550c16ff) #define PARAM_OP_TYPE_JSPRING_GET_DAMPER CKGUID(0x1f793582,0x11f96df9) #define PARAM_OP_TYPE_JSPRING_GET_VALUE CKGUID(0x76226303,0x67ba262f) void ParamOpJSpringSetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,0,value,false); } void ParamOpJSpringGetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),0,false); } } res->SetValue(&value); } void ParamOpJSpringSetDamper(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,1,value,false); } void ParamOpJSpringGetDamper(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),1,false); } } res->SetValue(&value); } void ParamOpJSpringSetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,2,value,false); } void ParamOpJSpringGetVAlue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),2,false); } } res->SetValue(&value); } /************************************************************************/ /* spring : */ /************************************************************************/ #define PARAM_OP_TYPE_JSLIMIT_SET_DAMPING CKGUID(0x24e53be6,0x43bf6178) #define PARAM_OP_TYPE_JSLIMIT_SET_SPRING CKGUID(0x19ea18da,0x4a8f7902) #define PARAM_OP_TYPE_JSLIMIT_SET_VALUE CKGUID(0x7abb085e,0x464b16b4) #define PARAM_OP_TYPE_JSLIMIT_SET_RES CKGUID(0x8eb56f2,0x44a40a2) #define PARAM_OP_TYPE_JSLIMIT_GET_DAMPING CKGUID(0x74b33ddd,0x6faa11f1) #define PARAM_OP_TYPE_JSLIMIT_GET_SPRING CKGUID(0x4440614,0x134514de) #define PARAM_OP_TYPE_JSLIMIT_GET_VALUE CKGUID(0x455a525d,0x77e17e01) #define PARAM_OP_TYPE_JSLIMIT_GET_RES CKGUID(0x7d1554b4,0x32a72cd3) void ParamOpJSLimitSetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,0,value,false); } void ParamOpJSLimitGetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),0,false); } } res->SetValue(&value); } void ParamOpJSLimitSetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,1,value,false); } void ParamOpJSLimitGetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),1,false); } } res->SetValue(&value); } void ParamOpJSLimitSetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,2,value,false); } void ParamOpJSLimitGetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),2,false); } } res->SetValue(&value); } void ParamOpJSLimitSetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,3,value,false); } void ParamOpJSLimitGetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),3,false); } } res->SetValue(&value); } /************************************************************************/ /* spring : */ /************************************************************************/ #define PARAM_OP_TYPE_JDRIVE_SET_DAMPING CKGUID(0x2ef2554b,0x50681945) #define PARAM_OP_TYPE_JDRIVE_SET_SPRING CKGUID(0x657274d7,0x5c23079c) #define PARAM_OP_TYPE_JDRIVE_SET_FORCE CKGUID(0x54d75463,0x2e343c56) #define PARAM_OP_TYPE_JDRIVE_SET_TYPE CKGUID(0x37ff7a9d,0x1f1c3013) #define PARAM_OP_TYPE_JDRIVE_GET_DAMPING CKGUID(0x3d4b76b7,0xf059e8) #define PARAM_OP_TYPE_JDRIVE_GET_SPRING CKGUID(0x4abe6b69,0x56615834) #define PARAM_OP_TYPE_JDRIVE_GET_FORCE CKGUID(0x4ff912df,0x40d1429) #define PARAM_OP_TYPE_JDRIVE_GET_TYPE CKGUID(0x54a63237,0x1f8a3347) void ParamOpJDriveSetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,0,value,false); } void ParamOpJDriveGetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),0,false); } } res->SetValue(&value); } void ParamOpJDriveSetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,1,value,false); } void ParamOpJDriveGetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),1,false); } } res->SetValue(&value); } void ParamOpJDriveSetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } float value = 0.0f; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<float>(res,2,value,false); } void ParamOpJDriveGetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); float value = 0.0f; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),2,false); } } res->SetValue(&value); } void ParamOpJDriveSetType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (!GetPMan()->getCurrentFactory()) { return; } int value = 0; p2->GetValue(&value); res->CopyValue(p1->GetRealSource(),false); vtTools::ParameterTools::SetParameterStructureValue<int>(res,3,value,false); } void ParamOpJDriveGetType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int value = 0; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),3,false); } } res->SetValue(&value); } void ParamOpJIsConnected(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); CK_ID targetID2; p2->GetValue(&targetID2); CK3dEntity *ent2 = static_cast<CK3dEntity*>(context->GetObject(targetID2)); if (!pFactory::Instance()->jointCheckPreRequisites(ent,ent2,JT_Distance)) { int result = 0; res->SetValue(&result); return; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(ent); pWorld *worldB=GetPMan()->getWorldByBody(ent2); if (!worldA) { worldA = worldB; } if (!worldA) { int result = 0; res->SetValue(&result); return; } pJoint*joint = static_cast<pJoint*>(worldA->getJoint(ent,ent2,JT_Any)); int result = joint ? 1 : 0; res->SetValue(&result); return; } void PhysicManager::_RegisterParameterOperationsJoint() { CKParameterManager *pm = m_Context->GetParameterManager(); pm->RegisterOperationType(PARAMETER_OP_TYPE_IS_CONNECTED, "connected"); pm->RegisterOperationFunction(PARAMETER_OP_TYPE_IS_CONNECTED,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpJIsConnected); /************************************************************************/ /* Drive */ /************************************************************************/ pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_DAMPING, "jDsDamping"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_DAMPING,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,CKPGUID_FLOAT,ParamOpJDriveSetDamping); pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_DAMPING, "jDgDamping"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_DAMPING,CKPGUID_FLOAT,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetDamping); pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_SPRING, "jDsSpring"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_SPRING,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,CKPGUID_FLOAT,ParamOpJDriveSetSpring); pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_SPRING, "jDgSpring"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_SPRING,CKPGUID_FLOAT,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetSpring); pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_FORCE, "jDsForce"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_FORCE,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,CKPGUID_FLOAT,ParamOpJDriveSetForce); pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_FORCE, "jDgForce"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_FORCE,CKPGUID_FLOAT,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetForce); pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_TYPE, "jDsType"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_TYPE,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,VTE_PHYSIC_JDRIVE_TYPE,ParamOpJDriveSetType); pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_TYPE, "jDgType"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_TYPE,VTE_PHYSIC_JDRIVE_TYPE,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetType); /************************************************************************/ /* Soft Limit */ /************************************************************************/ pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_DAMPING, "jSLsDamping"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_DAMPING,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetDamping); pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_DAMPING, "jSLgDamping"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_DAMPING,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetDamping); pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_SPRING, "jSLsSpring"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_SPRING,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetSpring); pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_SPRING, "jSLgSpring"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_SPRING,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetSpring); pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_VALUE, "jSLsValue"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_VALUE,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetValue); pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_VALUE, "jSLgValue"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_VALUE,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetValue); pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_RES, "jSLsRes"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_RES,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetRes); pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_RES, "jSLgRes"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_RES,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetRes); /************************************************************************/ /* spring : */ /************************************************************************/ pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_SET_SPRING, "jSsSpring"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_SET_SPRING,VTS_JOINT_SPRING,VTS_JOINT_SPRING,CKPGUID_FLOAT,ParamOpJSpringSetSpring); pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_GET_SPRING, "jSgSpring"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_GET_SPRING,CKPGUID_FLOAT,VTS_JOINT_SPRING,CKPGUID_NONE,ParamOpJSpringGetSpring); pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_SET_DAMPER, "jSsDamper"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_SET_DAMPER,VTS_JOINT_SPRING,VTS_JOINT_SPRING,CKPGUID_FLOAT,ParamOpJSpringSetDamper); pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_GET_DAMPER, "jSgDamper"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_GET_DAMPER,CKPGUID_FLOAT,VTS_JOINT_SPRING,CKPGUID_NONE,ParamOpJSpringGetDamper); pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_SET_VALUE, "jSsValue"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_SET_VALUE,VTS_JOINT_SPRING,VTS_JOINT_SPRING,CKPGUID_FLOAT,ParamOpJSpringSetValue); pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_GET_VALUE, "jSgValue"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_GET_VALUE,CKPGUID_FLOAT,VTS_JOINT_SPRING,CKPGUID_NONE,ParamOpJSpringGetVAlue); /************************************************************************/ /* pJLimit Structure Access : */ /************************************************************************/ pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_SET_VALUE, "jLsValue"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_SET_VALUE,VTS_JLIMIT,VTS_JLIMIT,CKPGUID_FLOAT,ParamOpJLimitSetValue); pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_GET_VALUE, "jLgValue"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_GET_VALUE,CKPGUID_FLOAT,VTS_JLIMIT,CKPGUID_NONE,ParamOpJLimitGetValue); pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_SET_RES, "jLsRestitution"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_SET_RES,VTS_JLIMIT,VTS_JLIMIT,CKPGUID_FLOAT,ParamOpJLimitSetRes); pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_GET_RES, "jLgRestitution"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_GET_RES,CKPGUID_FLOAT,VTS_JLIMIT,CKPGUID_NONE,ParamOpJLimitGetRes); pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_SET_HARD, "jLsHardness"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_SET_HARD,VTS_JLIMIT,VTS_JLIMIT,CKPGUID_FLOAT,ParamOpJLimitSetHard); pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_GET_RES, "jLgHardness"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_GET_HARD,CKPGUID_FLOAT,VTS_JLIMIT,CKPGUID_NONE,ParamOpJLimitGetHard); /************************************************************************/ /* pMotor Structure Acess : */ /************************************************************************/ pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_SET_TVEL, "jMsVel"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_SET_TVEL,VTS_JOINT_MOTOR,VTS_JOINT_MOTOR,CKPGUID_FLOAT,ParamOpJMotorSetTVel); pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_GET_TVEL, "jMgVel"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_GET_TVEL,CKPGUID_FLOAT,VTS_JOINT_MOTOR,CKPGUID_NONE,ParamOpJMotorGetTVel); pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_SET_MAXF, "jMsFMax"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_SET_MAXF,VTS_JOINT_MOTOR,VTS_JOINT_MOTOR,CKPGUID_FLOAT,ParamOpJMotorSetFMAX); pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_GET_MAXF, "jMgFMax"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_GET_MAXF,CKPGUID_FLOAT,VTS_JOINT_MOTOR,CKPGUID_NONE,ParamOpJMotorGetFMAX); pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_SET_SPIN_FREE, "jMsSpinFree"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_SET_SPIN_FREE,VTS_JOINT_MOTOR,VTS_JOINT_MOTOR,CKPGUID_BOOL,ParamOpJMotorSetSpinFree); pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_GET_SPIN_FREE, "jMgSpingFree"); pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_GET_SPIN_FREE,CKPGUID_BOOL,VTS_JOINT_MOTOR,CKPGUID_NONE,ParamOpJMotorGetSpinFree); } <file_sep>//////////////////////////////////////////////////////////////////////////////// // // ARToolKitPlusDetect // ------------------- // // Description: // Buildingblock that detects pattern (single marker) in the given video // image. If you want to use more than one pattern, that it is wise to use // the ARToolKitPlusDetect-BB once and for each pattern the // ARTPlusPatternTransformation-BB instead of using the // ARTPlusDetectionAndTransformation-BB for each pattern. The cause is, that // the ARTPlusDetectionAndTransformation-BB will run a complete detection // on the video image eache time you call it. // // Input Parameter: // IN_VIDEO_TEXTURE : The image, in with ARToolKitPlus // perform the detection // IN_USE_BCH : Flag which indicates to use BCH-pattern // (look into ARToolKitPlus for description) // IN_THIN_BORDER : Flag which indicates to use pattern with // a thin boarder) // (look into ARToolKitPlus for description) // IN_AUTO_THRESHOLD : Flag which indicates to use the auto-threshold // function from the ARToolKitPlus // (look into ARToolKitPlus for description) // IN_THRESHOLD : The threshold value used, if IN_AUTO_THRESHOLD // is set to false // // Output Parameter: // OUT_ERROR_STRING : String which describe the error, if one occurs. If // there was no error the string will contain the word // "Success" (without the marks) // // Version 1.0 : First Release // // Known Bugs : None // // Copyright <NAME> <<EMAIL>>, University of Paderborn //////////////////////////////////////////////////////////////////////////////// // Input Parameter #define IN_VIDEO_TEXTURE 0 #define IN_USE_BCH 1 #define IN_THIN_BORDER 2 #define IN_AUTO_THRESHOLD 3 #define IN_THRESHOLD 4 // Output Parameter #define OUT_ERROR_STRING 0 // Output Signals #define OUTPUT_OK 0 #define OUTPUT_ERROR 1 #include "CKAll.h" #include <ARToolKitPlus/ar.h> #include <ARToolKitPlus/TrackerSingleMarker.h> CKObjectDeclaration *FillBehaviorARToolKitPlusDetectDecl(); CKERROR CreateARToolKitPlusDetectProto(CKBehaviorPrototype **); int ARToolKitPlusDetect(const CKBehaviorContext& BehContext); int ARToolKitPlusDetectCallBack(const CKBehaviorContext& BehContext); extern bool ARTPlusInitialized; ARToolKitPlus::ARMarkerInfo* markerInfo = NULL; int numMarkers = 0; extern ARToolKitPlus::TrackerSingleMarker *tracker; CKObjectDeclaration *FillBehaviorARToolKitPlusDetectDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Single Marker Detection"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetVersion(0x00010000); od->SetCreationFunction(CreateARToolKitPlusDetectProto); od->SetDescription("Single Marker Detection"); od->SetCategory("ARToolKitPlus"); od->SetGuid(CKGUID(0x1ff46552,0x6c31e58)); od->SetAuthorGuid(CKGUID(0x56495254,0x4f4f4c53)); od->SetAuthorName("<NAME>"); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateARToolKitPlusDetectProto(CKBehaviorPrototype** pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Single Marker Detection"); if (!proto) { return CKERR_OUTOFMEMORY; } //--- Inputs declaration proto->DeclareInput("In"); //--- Outputs declaration proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); //--- Input Parameters declaration proto->DeclareInParameter("VideoImage", CKPGUID_TEXTURE); proto->DeclareInParameter("Use BCH Pattern", CKPGUID_BOOL, "TRUE"); proto->DeclareInParameter("Use Thin Border", CKPGUID_BOOL, "TRUE"); proto->DeclareInParameter("Enable Auto Threshold", CKPGUID_BOOL, "FALSE"); proto->DeclareInParameter("Threshold", CKPGUID_INT, "150"); //--- Output Parameters declaration proto->DeclareOutParameter("Error", CKPGUID_STRING, "Success"); //---- Local Parameters Declaration //---- Settings Declaration proto->SetBehaviorCallbackFct(ARToolKitPlusDetectCallBack, CKCB_BEHAVIORATTACH|CKCB_BEHAVIORDETACH|CKCB_BEHAVIORDELETE|CKCB_BEHAVIOREDITED|CKCB_BEHAVIORSETTINGSEDITED|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORPRESAVE|CKCB_BEHAVIORPOSTSAVE|CKCB_BEHAVIORRESUME|CKCB_BEHAVIORPAUSE|CKCB_BEHAVIORRESET|CKCB_BEHAVIORRESET|CKCB_BEHAVIORDEACTIVATESCRIPT|CKCB_BEHAVIORACTIVATESCRIPT|CKCB_BEHAVIORREADSTATE, NULL); proto->SetFunction(ARToolKitPlusDetect); *pproto = proto; return CK_OK; } int ARToolKitPlusDetect(const CKBehaviorContext& BehContext) { CKBehavior* beh = BehContext.Behavior; beh->ActivateInput(0,FALSE); if(ARTPlusInitialized == true) { CKTexture* texture = NULL; CKBYTE *pixel = NULL; CKBOOL autoThreshold = FALSE; int threshold = 150; CKBOOL useBCH = TRUE; CKBOOL thinBorder = TRUE; // Texture (Wichtig, Object holen, nicht Value oder Ptr!!!) texture = CKTexture::Cast(beh->GetInputParameterObject(IN_VIDEO_TEXTURE)); if(texture == NULL) { beh->ActivateOutput(OUTPUT_ERROR); char string[] = "ERROR: No Texture Present"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKERR_NOTINITIALIZED; } pixel = texture->LockSurfacePtr(); if(pixel == NULL) { beh->ActivateOutput(OUTPUT_ERROR); char string[] = "ERROR: Can't lock texture surface"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKBR_BEHAVIORERROR; } // Auto Threshold holen beh->GetInputParameterValue(IN_AUTO_THRESHOLD, &autoThreshold); // set Auto Thresholding tracker->activateAutoThreshold(autoThreshold?true:false); // Threshold holen beh->GetInputParameterValue(IN_THRESHOLD, &threshold); // set a threshold. alternatively we could also activate automatic thresholding tracker->setThreshold(threshold); // Pattern Typ holen beh->GetInputParameterValue(IN_USE_BCH, &useBCH); // Thin Border holen beh->GetInputParameterValue(IN_THIN_BORDER, &thinBorder); if(useBCH) { // the marker in the BCH test image has a thin border... tracker->setBorderWidth(0.125f); } else { tracker->setBorderWidth(thinBorder ? 0.125f : 0.250f); } // switch to simple ID based markers // use the tool in tools/IdPatGen to generate markers tracker->setMarkerMode(useBCH ? ARToolKitPlus::MARKER_ID_BCH : ARToolKitPlus::MARKER_ID_SIMPLE); // here we go, just one call to find the camera pose numMarkers = 0; markerInfo = NULL; tracker->calc(pixel, -1, true, &markerInfo, &numMarkers); if(texture->Restore() != TRUE) { beh->ActivateOutput(OUTPUT_ERROR); char string[] = "ERROR: Can't restore texture surface"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKBR_BEHAVIORERROR; } } beh->ActivateOutput(OUTPUT_OK); char string[] = "Success"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKBR_OK; } int ARToolKitPlusDetectCallBack(const CKBehaviorContext& BehContext) { switch (BehContext.CallbackMessage) { case CKM_BEHAVIORATTACH: break; case CKM_BEHAVIORDETACH: break; case CKM_BEHAVIORDELETE: break; case CKM_BEHAVIOREDITED: break; case CKM_BEHAVIORSETTINGSEDITED: break; case CKM_BEHAVIORLOAD: break; case CKM_BEHAVIORPRESAVE: break; case CKM_BEHAVIORPOSTSAVE: break; case CKM_BEHAVIORRESUME: break; case CKM_BEHAVIORPAUSE: break; case CKM_BEHAVIORRESET: break; case CKM_BEHAVIORNEWSCENE: break; case CKM_BEHAVIORDEACTIVATESCRIPT: break; case CKM_BEHAVIORACTIVATESCRIPT: break; case CKM_BEHAVIORREADSTATE: break; } return CKBR_OK; } <file_sep>#pragma once #include "stdafx.h" class ExeInThread { public: static CKObjectDeclaration * FillBehaviour( void ); static int CallBack( const CKBehaviorContext& behaviorContext ); static int BehaviourFunction( const CKBehaviorContext& behaviorContext ); static CKERROR CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ); enum ThreadStatus { Idle = 0, Requested = 2, Active = 3}; friend unsigned int BlockingThreadFunction(void *arg); typedef struct ThreadInfo { CKBehavior* targetBeh; int targetInputToActivate; } AsyncThreadInfo; }; <file_sep>/*************************************************************************/ /* File : XLoader.h */ /* */ /* DirectX .X files loader */ /* */ /* Virtools SDK */ /* Copyright (c) Virtools 2000, All Rights Reserved. */ /*************************************************************************/ #ifndef _XLOADER_H #define _XLOADER_H //#include "Windows.h" #include "stdio.h" #include "DxFile.h" #include "rmxfguid.h" #include "rmxftmpl.h" #include "Ge2Virtools.h" #include "ptypes.h" XString GetFileObjectName(LPDIRECTXFILEOBJECT obj); #define SAFERELEASE(x) { if (x) x->Release(); x = NULL; } /************************************************** + Overload of a model reade + ***************************************************/ class CKXReader: public CKModelReader { public: void Release() {delete this; }; // Reader Info virtual CKPluginInfo* GetReaderInfo(); // No specific Options virtual int GetOptionsCount() { return 0; } virtual CKSTRING GetOptionDescription(int i) { return NULL; } // This reader can only load .X files virtual CK_DATAREADER_FLAGS GetFlags() {return (CK_DATAREADER_FLAGS)CK_DATAREADER_FILELOAD;} // Load Method virtual CKERROR Load(CKContext* context,CKSTRING FileName,CKObjectArray *liste,CKDWORD LoadFlags,CKCharacter *carac=NULL); BOOL LoadFromFileC(CKContext *ctx, XString filename, CKBOOL hidden, CKDWORD loadflags, CKObjectArray* targetArray, XString password); CKXReader() { m_Context = NULL; m_VirtoolsExport = NULL; m_Unnamed = 0; } ~CKXReader() { CleanUp(); } protected: void CleanUp() { delete m_VirtoolsExport; m_VirtoolsExport = NULL; } //-- High level //-- For unnamed objects return a generic string "Unnamed_XX" XString GetUnnamed() { XString Temp = "Unnamed_"; Temp << m_Unnamed++; return Temp; } public: CKContext* m_Context; CK_OBJECTCREATION_OPTIONS m_CreationOptions; CKCharacter* m_Character; DWORD m_LoadFlags; CK_CLASSID m_3dObjectsClass; XString m_FileName; Export2Virtools* m_VirtoolsExport; int m_Unnamed; float m_AnimationLength; }; #endif<file_sep> /******************************************************************** created: 2007/11/28 created: 28:11:2007 16:25 filename: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Dialogs\CustomPlayerConfigurationDialog.cpp file path: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Dialogs file base: CustomPlayerConfigurationDialog file ext: cpp author: mc007 purpose: *********************************************************************/ #include <CPStdAfx.h> #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "xSplash.h" #include "SplashScreenEx.h" //************************************ // Method: HideSplash // FullName: CCustomPlayer::HideSplash // Access: public // Returns: void // Qualifier: //************************************ void CCustomPlayer::HideSplash() { if (xSplash::GetSplash()) { xSplash::HideSplash(); } } //************************************ // Method: SetSplashText // FullName: CCustomPlayer::SetSplashText // Access: public // Returns: void // Qualifier: // Parameter: const char* text //************************************ void CCustomPlayer::SetSplashText(const char* text) { if (xSplash::GetSplash()) { xSplash::SetText(text); } } //************************************ // Method: ShowSplash // FullName: CCustomPlayer::ShowSplash // Access: public // Returns: void // Qualifier: //************************************ void CCustomPlayer::ShowSplash() { CWnd *main = CWnd::FromHandle(m_MainWindow); xSplash::CreateSplashEx(main,40,10); ////////////////////////////////////////////////////////////////////////// // we modify our splash : CSplashScreenEx *splash = xSplash::GetSplash(); /* // we set the loading perc to the right bottom corner : splash->SetTextFormat(DT_SINGLELINE | DT_RIGHT | DT_BOTTOM); //we set the splash file and the transparency key : splash->SetBitmap("splash.bmp",255,0,255); //font : splash->SetTextFont("MicrogrammaDBolExt",100,CSS_TEXT_NORMAL);*/ if (xSplash::GetSplash()) { xSplash::ShowSplash(); } }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" pJointRevolute::pJointRevolute(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Revolute) { } bool pJointRevolute::setHighLimit(pJointLimit limit) { NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast<NxRevoluteJoint*>(getJoint()); if (!joint)return false; joint->saveToDesc(descr); NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; if (!sLimit.isValid())return false; descr.limit.high= sLimit; if (sLimit.hardness!=0.0f || sLimit.restitution!=0.0f || sLimit.value !=0.0f ) { descr.flags |= NX_RJF_LIMIT_ENABLED; }else descr.flags &=~NX_RJF_LIMIT_ENABLED; int v = descr.isValid(); joint->loadFromDesc(descr); return true; } bool pJointRevolute::setLowLimit(pJointLimit limit) { NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast<NxRevoluteJoint*>(getJoint()); if (!joint)return false; joint->saveToDesc(descr); NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; if (!sLimit.isValid())return false; descr.limit.low= sLimit; if (sLimit.hardness!=0.0f || sLimit.restitution!=0.0f || sLimit.value !=0.0f ) { descr.flags |= NX_RJF_LIMIT_ENABLED; }else descr.flags &=~NX_RJF_LIMIT_ENABLED; bool ret = descr.isValid(); joint->loadFromDesc(descr); return ret; } pSpring pJointRevolute::getSpring() { NxRevoluteJointDesc descr; NxRevoluteJoint*joint = static_cast<NxRevoluteJoint*>(getJoint()); joint->saveToDesc(descr); return pSpring (descr.spring.damper,descr.spring.spring,descr.spring.targetValue); } bool pJointRevolute::setSpring(pSpring spring) { NxRevoluteJointDesc descr; NxRevoluteJoint*joint = static_cast<NxRevoluteJoint*>(getJoint()); joint->saveToDesc(descr); if (!joint)return false ; joint->saveToDesc(descr); NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; if (!sLimit.isValid())return false; descr.spring= sLimit; if (spring.damper!=0.0f || !spring.spring!=0.0f || !spring.targetValue !=0.0f ) { descr.flags |= NX_RJF_SPRING_ENABLED; }else descr.flags &=~NX_RJF_SPRING_ENABLED; joint->loadFromDesc(descr); return false; } pMotor pJointRevolute::getMotor() { NxRevoluteJointDesc descr; NxRevoluteJoint*joint = static_cast<NxRevoluteJoint*>(getJoint()); joint->saveToDesc(descr); NxMotorDesc mDescr = descr.motor; pMotor result; result.freeSpin = mDescr.freeSpin; result.targetVelocity= mDescr.velTarget; result.maximumForce = mDescr.maxForce; return result; } bool pJointRevolute::setMotor(pMotor motor) { NxRevoluteJointDesc descr; NxRevoluteJoint*joint = static_cast<NxRevoluteJoint*>(getJoint()); joint->saveToDesc(descr); NxMotorDesc mDescr = descr.motor; if (motor.maximumForce!=0.0f && motor.targetVelocity !=0.0f ) { mDescr.freeSpin = motor.freeSpin; mDescr.velTarget= motor.targetVelocity; mDescr.maxForce= motor.maximumForce; descr.flags |= NX_RJF_MOTOR_ENABLED; joint->setMotor(mDescr); descr.motor = mDescr; }else{ descr.flags &=~NX_RJF_MOTOR_ENABLED; } joint->loadFromDesc(descr); return descr.isValid(); } void pJointRevolute::enableCollision(bool collision) { NxRevoluteJointDesc descr; NxRevoluteJoint*joint = static_cast<NxRevoluteJoint*>(getJoint()); joint->saveToDesc(descr); if (collision) { descr.jointFlags |= NX_JF_COLLISION_ENABLED; }else descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; joint->loadFromDesc(descr); } void pJointRevolute::setGlobalAnchor(const VxVector& anchor) { NxRevoluteJointDesc descr; NxRevoluteJoint*joint = static_cast<NxRevoluteJoint*>(getJoint()); joint->saveToDesc(descr); //descr.setGlobalAnchor(pMath::getFrom(anchor)); //descr.localAnchor[0] = NxVec3(0,-40,0); // joint->loadFromDesc(descr); joint->setGlobalAnchor(pMath::getFrom(anchor)); } void pJointRevolute::setGlobalAxis(const VxVector& axis) { NxRevoluteJointDesc descr; NxRevoluteJoint*joint = static_cast<NxRevoluteJoint*>(getJoint()); //joint->saveToDesc(descr); //descr.setGlobalAxis(pMath::getFrom(axis)); //joint->loadFromDesc(descr); joint->setGlobalAxis(pMath::getFrom(axis)); } pJointLimit pJointRevolute::getHighLimit() { NxRevoluteJointDesc descr; NxRevoluteJoint*joint = static_cast<NxRevoluteJoint*>(getJoint()); joint->saveToDesc(descr); return pJointLimit (descr.limit.high.hardness,descr.limit.high.restitution,descr.limit.high.value); } pJointLimit pJointRevolute::getLowLimit() { NxRevoluteJointDesc descr; NxRevoluteJoint*joint = static_cast<NxRevoluteJoint*>(getJoint()); joint->saveToDesc(descr); return pJointLimit (descr.limit.low.hardness,descr.limit.low.restitution,descr.limit.low.value); } void pJointRevolute::setProjectionMode(ProjectionMode mode) { NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast<NxRevoluteJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.projectionMode = (NxJointProjectionMode)mode; joint->loadFromDesc(descr); } void pJointRevolute::setProjectionDistance(float distance) { NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast<NxRevoluteJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.projectionDistance= distance; joint->loadFromDesc(descr); } void pJointRevolute::setProjectionAngle(float angle) { NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast<NxRevoluteJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.projectionAngle= angle; int s = descr.isValid(); joint->loadFromDesc(descr); }<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBAddLocalForceAtLocalPosDecl(); CKERROR CreatePBAddLocalForceAtLocalPosProto(CKBehaviorPrototype **pproto); int PBAddLocalForceAtLocalPos(const CKBehaviorContext& behcontext); CKERROR PBAddLocalForceAtLocalPosCB(const CKBehaviorContext& behcontext); enum bbInputs { bbI_Force, bbI_Pos, bbI_Mode }; //************************************ // Method: FillBehaviorPBAddLocalForceAtLocalPosDecl // FullName: FillBehaviorPBAddLocalForceAtLocalPosDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPBAddLocalForceAtLocalPosDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddLocalForceAtLocalPos"); od->SetCategory("Physic/Body"); od->SetDescription("Applies a force (or impulse) defined in the bodies local coordinate frame, acting at a particular point in local coordinates, to the actor."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x27b72bda,0x4db179ce)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBAddLocalForceAtLocalPosProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBAddLocalForceAtLocalPosProto // FullName: CreatePBAddLocalForceAtLocalPosProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBAddLocalForceAtLocalPosProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddLocalForceAtLocalPos"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PBAddLocalForceAtLocalPos PBAddLocalForceAtLocalPos is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Applies a force (or impulse) defined in the actor local coordinate frame, acting at a particular point in local coordinates, to the actor.<br> <h3>Technical Information</h3> \image html PBAddLocalForceAtLocalPos.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pin">Local Force:</SPAN>Force/impulse to add, defined in the local frame. <BR> <SPAN CLASS="pin">Local Position:</SPAN>Position in the local frame to add the force at. <BR> <SPAN CLASS="pin">Force Mode: </SPAN>The way how the force is applied.See #ForceMode <BR> <BR> <h3>Warning</h3> The body must be dynamic. <h3>Note</h3><br> Note that if the force does not act along the center of mass of the actor, this will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addLocalForceAtLocalPos().<br> */ proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Local Force",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Local Position",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBAddLocalForceAtLocalPos); *pproto = proto; return CK_OK; } //************************************ // Method: PBAddLocalForceAtLocalPos // FullName: PBAddLocalForceAtLocalPos // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBAddLocalForceAtLocalPos(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) { beh->ActivateOutput(0); return 0; } //the vector : VxVector force = GetInputParameterValue<VxVector>(beh,bbI_Force); VxVector pos = GetInputParameterValue<VxVector>(beh,bbI_Pos); int fMode = GetInputParameterValue<int>(beh,bbI_Mode); // body exists already ? clean and delete it : pRigidBody*result = world->getBody(target); if(result) { result->addLocalForceAtLocalPos(force,pos,(ForceMode)fMode); } beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PBAddLocalForceAtLocalPosCB // FullName: PBAddLocalForceAtLocalPosCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBAddLocalForceAtLocalPosCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#ifndef __P_CALLBACK_OBJECT_H__ #define __P_CALLBACK_OBJECT_H__ #include <xBitSet.h> #include "vtInterfaceEnumeration.h" class pWheelContactModify; class pCollisionsEntry; class pTriggerEntry; class pContactModifyData; class pWheelContactModifyData; class MODULE_API pCallbackObject { public: pCallbackObject() { preScript = -1; postScript = -1; callMask = 0; overrideMask = -1; contactScript = -1; rayCastScript = -1; wheelContactScript = -1; triggerScript = -1; triggerEventMask = 0 ; collisionEventMask = 0 ; } int contactScript; int rayCastScript; int wheelContactScript; int triggerScript; int jointBreakScript; int collisionEventMask; int contactModificationScript; int& getCollisionEventMask() { return collisionEventMask; } void setCollisionEventMask(int val) { collisionEventMask = val; } int triggerEventMask; int& getTriggerEventMask() { return triggerEventMask; } void setTriggerEventMask(int val) { triggerEventMask = val; } // virtual void advanceTime(float lastDeltaMS); //---------------------------------------------------------------- // // generics // int overrideMask; int& getOverrideMask() { return overrideMask; } void setOverrideMask(int val) { overrideMask = val; } xBitSet callMask; xBitSet& getCallMask() { return callMask; } void setCallMask(int val) { callMask = val; } int preScript; int& getPreScript() { return preScript; } void setPreScript(int val) { preScript = val; } int postScript; int& getPostScript() { return postScript; } void setPostScript(int val) { postScript = val; } virtual void processPostScript(){}; virtual void processPreScript(){}; virtual int onPreProcess(){ return -1;}; virtual int onPostProcess(){return -1;}; //---------------------------------------------------------------- // // generic contact call // int getContactScript() const { return contactScript; } virtual void setContactScript(int behaviorID,int eventMask) { contactScript = behaviorID; collisionEventMask = eventMask; setFlag(getCallMask(),CB_OnContactNotify,behaviorID); } virtual int onContact(pCollisionsEntry *report){ return -1;}; //---------------------------------------------------------------- // // raycast, unused ! // int getRayCastScript() const { return rayCastScript; } virtual void setRayCastScript(int val) { rayCastScript = val; setFlag(getCallMask(),CB_OnRayCastHit,val); } virtual bool onRayCastHit(NxRaycastHit *report){ return false;}; //---------------------------------------------------------------- // // trigger // int getTriggerScript() const { return triggerScript; } virtual void setTriggerScript(int behaviorID,int eventMask,CK3dEntity *shapeReference = NULL) { triggerScript = behaviorID; triggerEventMask = eventMask; setFlag(getCallMask(),CB_OnTrigger,behaviorID); } virtual int onTrigger(pTriggerEntry *report){ return -1;}; //---------------------------------------------------------------- // // trigger // int getJointBreakScript() const { return jointBreakScript; } virtual void setJointBreakScript(int behaviorID,CK3dEntity *shapeReference = NULL) { jointBreakScript = behaviorID; setFlag(getCallMask(),CB_OnJointBreak,behaviorID); } virtual int onJointBreak(pBrokenJointEntry *entry){ return -1;}; //---------------------------------------------------------------- // // wheel related // int getWheelContactScript() const { return wheelContactScript; } virtual void setWheelContactScript(int val) { wheelContactScript = val; } virtual bool onWheelContact(CK3dEntity* wheelShapeReference, VxVector& contactPoint, VxVector& contactNormal, float& contactPosition, float& normalForce, CK3dEntity* otherShapeReference, int& otherShapeMaterialIndex){return true;} virtual bool onWheelContactModify(int& changeFlags,pWheelContactModifyData* contact){ return -1;} //---------------------------------------------------------------- // // contact modification // int getContactModificationScript() const { return contactModificationScript; } virtual void setContactModificationScript(int val) { contactModificationScript = val; setFlag(getCallMask(),CB_OnContactModify,val); } virtual bool onContactConstraint(int& changeFlags,CK3dEntity *sourceObject,CK3dEntity *otherObject,pContactModifyData *data){ changeFlags = CMM_None; return true; }; int processOptions; virtual int& getProcessOptions() { return processOptions; } virtual void setProcessOptions(int val) { processOptions = val; } protected: private: }; #endif<file_sep>#ifndef _XNET_TYPES_H_ #define _XNET_TYPES_H_ #include "vcWarnings.h" #ifndef _TNL_TYPES_H_ #include "tnlTypes.h" #endif #ifndef _XNET_ENUMERATIONS_H_ #include "xNetEnumerations.h" #endif #ifndef __UX_STRING_H__ #include <uxString.h> #endif using namespace TNL; #ifndef xTimeType typedef unsigned int xTimeType; #endif #ifndef StringPtr #include "tnlNetBase.h" #include "tnlString.h" #endif #ifndef xNStream #ifndef _TNL_BITSTREAM_H_ #include "tnlBitStream.h" #endif typedef TNL::BitStream xNStream; #endif __inline bool isFlagOn(TNL::BitSet32 value,int flag) { return value.test(1 << flag ); } __inline bool isFlagOff(TNL::BitSet32 value,int flag) { return value.test(1 << flag ) ? false : true; } __inline void enableFlag(TNL::BitSet32 &value,int flag) { value.set(1 << flag,true ); } __inline void disableFlag(TNL::BitSet32 &value,int flag) { value.set(1 << flag,false); } #ifndef xNString typedef TNL::StringPtr xNString; #endif #include <stdlib.h> #include <map> #include <vector> //#include <deque> class xDistributedClass; class xDistributed3DObjectClass; class xDistributedObject; class xDistributedProperty; class xDistributedPropertyInfo; class xDistributedSession; class xDistributedClient; class xNetMessage; class xNetworkMessage; class xMessageType; class xMessage; typedef std::vector<xDistributedProperty*>xDistributedPropertyArrayType; typedef std::vector<xDistributedProperty*>::iterator xDistributedPropertyArrayIterator; typedef std::vector<xDistributedPropertyInfo*>xDistributedPropertiesListType; typedef std::vector<xDistributedObject*>xDistributedObjectsArrayType; typedef std::vector<xDistributedObject*>::iterator xDistributedObjectsArrayIterator; typedef std::vector<xDistributedObject*>::iterator xDistObjectIt; typedef std::map<xNString,xDistributedClass*>xDistributedClassesArrayType; typedef std::map<xNString,xDistributedClass*>::iterator xDistributedClassesArrayIterator; typedef xDistributedClassesArrayIterator xDistClassIt; typedef std::vector<xNetworkMessage*>NetworkMessagesType; typedef std::vector<xNetworkMessage*>::iterator NetworkMessagesTypeIterator; typedef std::vector<xNetworkMessage*>xNetworkMessageArrayType; typedef std::vector<xNetworkMessage*>::iterator xNetworkMessageArrayTypeIterator; typedef std::vector<xDistributedSession*>xSessionArrayType; typedef std::vector<xDistributedClient*>xClientArrayType; typedef std::vector<xMessage*>xMessageArrayType; typedef std::vector<xMessage*>::iterator xMessageArrayIterator; typedef std::vector<xMessageType*>xMessageTypeArrayType; typedef std::vector<xMessageType*>::iterator xMessageTypeArrayIterator; class xNetworkMessage { public : typedef std::map<int,xNetMessage*> MessageParameterArrayType; typedef std::map<int,xNetMessage*>::iterator MessageParameterArrayTypeIterator; xNetworkMessage() { m_RecievedParameters = new MessageParameterArrayType(); } float lifeTime; bool complete; int targetUserID; int srcUserID; int numParameters; int messageID; virtual ~xNetworkMessage() { } xNString name; MessageParameterArrayType *m_RecievedParameters; }; struct xClientInfo { int userFlag; //USERNAME_FLAG userNameFlag; int userID; xNString userName; }; struct xDistDeleteInfo { int serverID; int entityID; int deleteState; }; #endif <file_sep>#ifndef __VT_C_BB_ERROR_HELPER_H__ #define __VT_C_BB_ERROR_HELPER_H__ #ifndef __X_LOGGER_H__ #include <xLogger.h> #endif #define CERROR_STRING(F) sBBErrorStrings[F] #define bbSErrorME(A) { xLogger::xLog(XL_START,ELOGERROR,E_BB,CERROR_STRING(A));\ XLOG_BB_INFO;\ beh->ActivateOutput(0);\ return CKBR_PARAMETERERROR ; } #define bbErrorME(A) { xLogger::xLog(XL_START,ELOGERROR,E_BB,A);\ XLOG_BB_INFO;\ beh->ActivateOutput(0);\ return CKBR_PARAMETERERROR ; } #define bbWarning(A){ xLogger::xLog(XL_START,ELOGWARNING,E_BB,A);\ XLOG_BB_INFO;\ } /*#define XL_BB_NAME beh->GetPrototype()->GetName() #define XL_BB_OWNER_SCRIPT beh->GetOwnerScript()->GetName() #define XL_BB_OWNER_OBJECT beh->GetOwner() ? beh->GetOwner()->GetName() : "none" #define XL_BB_SIGNATURE ("\n\tScript : %s\n\tBuildingBlock : %s \n\tObject :%s Error :") #define XLOG_FMT(msg,extro) msg##extro #define XLOG_MERGE(var, fmt) (#var##fmt ) #define XLOG_MERGE2(var,fmt) (var##fmt) #define XLOG_BB_INFO xLogger::xLogExtro(0,XL_BB_SIGNATURE,XL_BB_OWNER_SCRIPT,XL_BB_NAME,XL_BB_OWNER_OBJECT) #define VTERROR_STRING(F) sErrorStrings[F] #define bbError(F) XLOG_BB_INFO; \ Error(beh,F,BB_OP_ERROR,VTERROR_STRING(F),TRUE,BB_O_ERROR,TRUE) #define bbNoError(F) Error(beh,F,BB_OP_ERROR,VTERROR_STRING(F),FALSE,BB_O_ERROR,FALSE) */ #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" #include "pVehicleAll.h" void __newpVehicleDescr(BYTE *iAdd) { new (iAdd)pVehicleDesc(); } void __newpVehicleMotorDesc(BYTE *iAdd) { new (iAdd)pVehicleMotorDesc(); } void __newpVehicleGearDesc(BYTE *iAdd) { new(iAdd)pVehicleGearDesc(); } void PhysicManager::_RegisterVSLVehicle() { STARTVSLBIND(m_Context) //---------------------------------------------------------------- // // vehicle base types // DECLAREPOINTERTYPE(pVehicleMotorDesc) DECLAREMEMBER(pVehicleMotorDesc,float,maxRpmToGearUp) DECLAREMEMBER(pVehicleMotorDesc,float,minRpmToGearDown) DECLAREMEMBER(pVehicleMotorDesc,float,maxRpm) DECLAREMEMBER(pVehicleMotorDesc,float,minRpm) DECLAREMETHOD_0(pVehicleMotorDesc,void,setToCorvette) DECLAREPOINTERTYPE(pVehicleGearDesc) DECLAREMEMBER(pVehicleGearDesc,int,nbForwardGears) DECLAREMETHOD_0(pVehicleGearDesc,void,setToDefault) DECLAREMETHOD_0(pVehicleGearDesc,void,setToCorvette) DECLAREMETHOD_0(pVehicleGearDesc,bool,isValid) DECLAREOBJECTTYPE(pVehicleDesc) DECLARECTOR_0(__newpVehicleDescr) DECLAREMEMBER(pVehicleDesc,float,digitalSteeringDelta) DECLAREMEMBER(pVehicleDesc,VxVector,steeringSteerPoint) DECLAREMEMBER(pVehicleDesc,VxVector,steeringTurnPoint) DECLAREMEMBER(pVehicleDesc,float,steeringMaxAngle) DECLAREMEMBER(pVehicleDesc,float,transmissionEfficiency) DECLAREMEMBER(pVehicleDesc,float,differentialRatio) DECLAREMEMBER(pVehicleDesc,float,maxVelocity) DECLAREMEMBER(pVehicleDesc,float,motorForce) DECLAREMETHOD_0(pVehicleDesc,pVehicleGearDesc*,getGearDescription) DECLAREMETHOD_0(pVehicleDesc,pVehicleMotorDesc*,getMotorDescr) DECLAREMETHOD_0(pVehicleDesc,void,setToDefault) //---------------------------------------------------------------- // // vehicle specific // DECLAREMETHOD_1(pVehicle,void,setPreScript,int) DECLAREMETHOD_1(pVehicle,void,setPostScript,int) DECLAREMETHOD_1(pVehicle,void,setOverrideMask,int) DECLAREMETHOD_1(pVehicle,int,initEngine,int) DECLAREMETHOD_0(pVehicle,BOOL,isValidEngine) DECLAREMETHOD_0(pVehicle,pEngine*,getEngine) DECLAREMETHOD_0(pVehicle,pGearBox*,getGearBox) DECLAREMETHOD_0(pVehicle,int,getStateFlags) DECLAREMETHOD_1(pVehicle,void,setClutch,float) DECLAREMETHOD_0(pVehicle,float,getClutch) //---------------------------------------------------------------- // // egine // DECLAREMETHOD_1(pEngine,void,SetInertia,float) DECLAREMETHOD_1(pEngine,void,setIdleRPM,float) DECLAREMETHOD_1(pEngine,void,setStallRPM,float) DECLAREMETHOD_1(pEngine,void,setStartRPM,float) DECLAREMETHOD_1(pEngine,void,setTimeScale,float) DECLAREMETHOD_1(pEngine,void,setEndRotationalFactor,float) DECLAREMETHOD_1(pEngine,void,setForceFeedbackScale,float) DECLAREMETHOD_0(pEngine,float,getForceFeedbackScale) //---------------------------------------------------------------- // // engine // DECLAREMETHOD_0(pVehicle,pEngine*,getEngine) DECLAREMETHOD_0(pEngine,pLinearInterpolation,getTorqueCurve) DECLAREMETHOD_1(pEngine,void,setTorqueCurve,pLinearInterpolation) DECLAREMETHOD_0(pEngine,float,getRPM) DECLAREMETHOD_0(pEngine,float,getTorque) DECLAREMETHOD_0(pEngine,void,setToDefault) DECLAREMETHOD_1(pEngine,void,updateUserControl,int) DECLAREMETHOD_1(pEngine,void,setMaxTorque,float) DECLAREMETHOD_1(pEngine,void,setMaxRPM,float) DECLAREMETHOD_1(pEngine,void,setIdleRPM,float) DECLAREMETHOD_1(pEngine,void,setBrakingCoeff,float) DECLAREMETHOD_0(pEngine,float,getBrakingCoeff) DECLAREMETHOD_1(pEngine,void,setFriction,float) DECLAREMETHOD_0(pEngine,float,getFriction) DECLAREMETHOD_1(pEngine,void,SetInertia,float) DECLAREMETHOD_1(pEngine,void,setStartRPM,float) DECLAREMETHOD_0(pEngine,float,getStartRPM) DECLAREMETHOD_0(pEngine,int,GetGears) DECLAREMETHOD_0(pVehicle,void,PreCalcDriveLine) //DECLAREMETHOD_1(pEngine,float,GetGearRatio,int) //---------------------------------------------------------------- // // interpolation curve, used for for torque and gears // DECLAREMETHOD_0(pLinearInterpolation,int,getSize) DECLAREMETHOD_1(pLinearInterpolation,int,isValid,float) DECLAREMETHOD_1(pLinearInterpolation,float,getValue,float) DECLAREMETHOD_1(pLinearInterpolation,int,getValueAtIndex,int) DECLAREMETHOD_2(pLinearInterpolation,void,insert,float,float) //---------------------------------------------------------------- // // gearbox // DECLAREMETHOD_1(pGearBox,float,GetTorqueForWheel,pWheel2*) DECLAREMETHOD_0(pGearBox,pLinearInterpolation,getGearRatios) DECLAREMETHOD_1(pGearBox,void,setGearRatios,pLinearInterpolation) DECLAREMETHOD_0(pGearBox,pLinearInterpolation,getGearTensors) DECLAREMETHOD_1(pGearBox,void,setGearTensors,pLinearInterpolation) //---------------------------------------------------------------- // // wheel2 // DECLAREMETHOD_1(pWheel2,void,setPreScript,int) DECLAREMETHOD_1(pWheel2,void,setPostScript,int) DECLAREMETHOD_1(pWheel2,void,setOverrideMask,int) DECLAREMETHOD_0(pWheel2,float,getEndBrakingTorqueForWheel) DECLAREMETHOD_0(pWheel2,float,getEndTorqueForWheel) DECLAREMETHOD_0(pWheel2,float,getEndAccForWheel) DECLAREMETHOD_0(pWheel2,float,getWheelTorque) DECLAREMETHOD_0(pWheel2,float,getWheelBreakTorque) DECLAREMETHOD_0(pWheel2,float,getAxleSpeed) DECLAREMETHOD_0(pWheel2,VxVector,GetForceRoadTC) DECLAREMETHOD_0(pWheel2,VxVector,GetForceBodyCC) DECLAREMETHOD_0(pWheel2,VxVector,GetTorqueTC) DECLAREMETHOD_0(pWheel2,VxVector,GetTorqueFeedbackTC) DECLAREMETHOD_0(pWheel2,VxVector,GetTorqueBrakingTC) DECLAREMETHOD_0(pWheel2,VxVector,GetTorqueRollingTC) DECLAREMETHOD_0(pWheel2,float,GetSlipAngle) DECLAREMETHOD_0(pWheel2,float,GetSlipRatio) DECLAREMETHOD_0(pWheel2,float,GetHeading) DECLAREMETHOD_0(pWheel2,float,GetRotation) DECLAREMETHOD_0(pWheel2,float,GetRotationV) DECLAREMETHOD_0(pWheel2,float,GetAcceleration) DECLAREMETHOD_0(pWheel2,VxVector,GetVelocity) //DECLAREMETHOD_0(pWheel2,VxVector,GetAcceleration) DECLAREMETHOD_0(pWheel2,VxVector,GetSlipVectorCC) DECLAREMETHOD_0(pWheel2,VxVector,GetPosContactWC) DECLAREMETHOD_0(pWheel2,float,getEndBrakingTorqueForWheel) DECLAREMETHOD_0(pWheel2,float,getEndTorqueForWheel) DECLAREMETHOD_0(pWheel2,float,getEndAccForWheel) DECLAREMETHOD_0(pWheel2,float,getWheelTorque) DECLAREMETHOD_0(pWheel2,float,getWheelBreakTorque) DECLAREMETHOD_0(pWheel2,bool,isAxleSpeedFromVehicle) DECLAREMETHOD_0(pWheel2,bool,isTorqueFromVehicle) DECLAREMEMBER(pWheel2,float,radius) DECLAREMEMBER(pWheel2,VxVector,forceGravityCC) DECLAREMEMBER(pWheel2,VxVector,forceBrakingTC) DECLAREMEMBER(pWheel2,VxVector,torqueTC) DECLAREMEMBER(pWheel2,VxVector,forceRoadTC) DECLAREMEMBER(pWheel2,VxVector,rotation) DECLAREMEMBER(pWheel2,VxVector,rotationA) DECLAREMEMBER(pWheel2,VxVector,rotationV) DECLAREMEMBER(pWheel2,VxVector,velWheelTC) DECLAREMEMBER(pWheel2,VxVector,velWheelCC) DECLAREMETHOD_1(pWheel2,void,setMass,float) DECLAREMETHOD_1(pWheel2,void,setTireRate,float) DECLAREMETHOD_0(pWheel2,float,getCsSlipLen) DECLAREMETHOD_1(pWheel2,void,setRollingCoeff,float) DECLAREMETHOD_0(pWheel2,float,getSuspensionTravel) //---------------------------------------------------------------- // // pwheel contactdata // DECLAREMETHOD_0(pWheel2,pWheelContactData*,getContact) DECLAREMETHOD_1(pWheel2,bool,getContact,pWheelContactData&dst) DECLAREMEMBER(pWheel2,bool,hadContact) DECLAREMEMBER(pWheelContactData,VxVector,contactPoint) DECLAREMEMBER(pWheelContactData,VxVector,contactNormal) DECLAREMEMBER(pWheelContactData,VxVector,longitudalDirection) DECLAREMEMBER(pWheelContactData,VxVector,lateralDirection) DECLAREMEMBER(pWheelContactData,CK3dEntity*,contactEntity) DECLAREMEMBER(pWheelContactData,float,contactForce,) DECLAREMEMBER(pWheelContactData,float,longitudalSlip,) DECLAREMEMBER(pWheelContactData,float,lateralSlip) DECLAREMEMBER(pWheelContactData,float,longitudalImpulse) DECLAREMEMBER(pWheelContactData,float,lateralImpulse) DECLAREMEMBER(pWheelContactData,float,contactPosition) DECLAREMEMBER(pWheelContactData,int,otherShapeMaterialIndex) //---------------------------------------------------------------- // // // DECLAREMETHOD_0(pWheel2,pPacejka*,getPacejka) DECLAREMETHOD_1(pPacejka,void,SetFx,float) DECLAREMETHOD_1(pPacejka,void,SetFy,float) DECLAREMETHOD_1(pPacejka,void,SetMz,float) DECLAREMETHOD_1(pPacejka,void,SetCamber,float) DECLAREMETHOD_1(pPacejka,void,SetSlipAngle,float) DECLAREMETHOD_1(pPacejka,void,SetSlipRatio,float) DECLAREMETHOD_1(pPacejka,void,SetNormalForce,float) DECLAREMETHOD_0(pPacejka,void,setToDefault) DECLAREMETHOD_0(pPacejka,void,Calculate) DECLAREMETHOD_0(pPacejka,float,GetMaxLongForce) DECLAREMETHOD_0(pPacejka,float,GetMaxLatForce) DECLAREMETHOD_1(pPacejka,void,SetMaxLongForce,float) DECLAREMETHOD_1(pPacejka,void,SetMaxLatForce,float) DECLAREMETHOD_0(pPacejka,float,GetLongitudinalStiffness) DECLAREMETHOD_0(pPacejka,float,GetCorneringStiffness) DECLAREMETHOD_0(pPacejka,float,GetFx) DECLAREMETHOD_0(pPacejka,float,GetFy) DECLAREMETHOD_0(pPacejka,float,GetMz) DECLAREMETHOD_1(pRigidBody,pWheel2*,getWheel2,CK3dEntity*) DECLAREMETHOD_0(pVehicle,void,PreCalcDriveLine) //---------------------------------------------------------------- // // // /* DECLAREMETHOD_1(pVehicle,void,updateVehicle,float) DECLAREMETHOD_5(pVehicle,void,setControlState,float,bool,float,bool,bool) DECLAREMETHOD_1(pVehicle,pWheel*,getWheel,CK3dEntity*) DECLAREMETHOD_0(pVehicle,pVehicleMotor*,getMotor) DECLAREMETHOD_0(pVehicle,pVehicleGears*,getGears) DECLAREMETHOD_1(pVehicle,void,setPreProcessingScript,int) DECLAREMETHOD_1(pVehicle,void,setPostProcessingScript,int) DECLAREMETHOD_0(pVehicle,void,gearUp) DECLAREMETHOD_0(pVehicle,void,gearDown) DECLAREMETHOD_0(pVehicleGears,int,getGear) */ ////////////////////////////////////////////////////////////////////////// //motor : /*DECLAREMETHOD_0(pVehicleMotor,float,getRpm) DECLAREMETHOD_0(pVehicleMotor,float,getTorque) DECLAREMETHOD_0(pWheel,pWheel1*,castWheel1) DECLAREMETHOD_0(pWheel,pWheel2*,castWheel2) DECLAREMETHOD_0(pWheel,float,getWheelRollAngle) DECLAREMETHOD_0(pWheel2,float,getRpm) DECLAREMETHOD_0(pWheel2,float,getAxleSpeed) DECLAREMETHOD_0(pWheel2,float,getSuspensionTravel) DECLAREMETHOD_0(pWheel2,VxVector,getGroundContactPos) */ STOPVSLBIND }<file_sep>#ifndef __VTMODULES_GUIDS_H__ #define __VTMODULES_GUIDS_H__ #include "vtBaseMacros.h" //---------------------------------------------------------------- // //! \brief The guid of the modules manager. Used // // //! \brief Manager Guid, used in plug-in registration, building blocks and many core components // #define GUID_MODULE_MANAGER CKGUID(0x1c0f04e8,0x442e20e5) //---------------------------------------------------------------- // //! \brief :: The guid of the modules building blocks // If defined "WebPack", its using the guid of the built-in camera plug in. #ifdef WebPack #define GUID_MODULE_BUILDING_BLOCKS CKGUID(0x12d94eba,0x47057415) #else #define GUID_MODULE_BUILDING_BLOCKS CKGUID(0x36834d9e,0x63664944) #endif #endif<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" CKObjectDeclaration *FillBehaviorLogEntryDecl(); CKERROR CreateLogEntryProto(CKBehaviorPrototype **); int LogEntry(const CKBehaviorContext& behcontext); CKERROR LogEntryCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 0 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorLogEntryDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Log Event"); od->SetDescription("Displays Internal Log Entries"); od->SetCategory("TNL"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x512542dc,0x1b836fd9)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateLogEntryProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateLogEntryProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Log Event"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutParameter("Entry",CKPGUID_STRING); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETERINPUTS )); proto->SetFunction(LogEntry); proto->SetBehaviorCallbackFct(LogEntryCB); *pproto = proto; return CK_OK; } int LogEntry(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); XString File((CKSTRING) beh->GetInputParameterReadDataPtr(0)); if (GetNM()->GetLastLogEntry().Length()) { CKParameterOut *pout = beh->GetOutputParameter(0); pout->SetStringValue(GetNM()->GetLastLogEntry().Str()); GetNM()->SetLastLogEntry(""); beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } return CKBR_ACTIVATENEXTFRAME; } CKERROR LogEntryCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { /* CKParameterIn* pin = beh->GetInputParameter(0); if (!pin) { CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : failed to retrieve first input parameter"; behcontext.Context->OutputToConsole(str.Str(),TRUE); return CKBR_PARAMETERERROR; } if (pin->GetGUID()!=CKPGUID_MESSAGE) { pin->SetGUID(CKPGUID_MESSAGE,FALSE); CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : first input parameter type must be \"Message\"!"; behcontext.Context->OutputToConsole(str.Str(),TRUE); } pin = beh->GetInputParameter(1); if (!pin) { CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : failed to retrieve second input parameter"; behcontext.Context->OutputToConsole(str.Str(),TRUE); return CKBR_PARAMETERERROR; } if (!behcontext.ParameterManager->IsDerivedFrom(pin->GetGUID(),CKPGUID_OBJECT)) { pin->SetGUID(CKPGUID_BEOBJECT,FALSE); CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : second input parameter type must derived from \"BeObject\"!"; behcontext.Context->OutputToConsole(str.Str(),TRUE); }*/ } return CKBR_OK; }<file_sep>#include "Prereqs.h" #include <stdio.h> #include "tnl.h" #include "tnlNetBase.h" #include "xNetInterface.h" #include "xNetworkFactory.h" #include "tnlLog.h" using namespace TNL; static RefPtr<xNetInterface> myInterFace=NULL; static const char *localBroadcastAddress = "IP:broadcast:28999"; static const char *localHostAddress = "IP:127.0.0.1:28999"; class DedicatedServerLogConsumer : public TNL::LogConsumer { public: void logString(const char *string) { printf("%s\n", string); } } gDedicatedServerLogConsumer; int main(int argc, const char **argv) { TNLLogEnable(LogNetInterface, true); myInterFace = xNetworkFactory::CreateNetworkInterface(true,28999,localHostAddress); myInterFace->setAllowsConnections(true); myInterFace->setRequiresKeyExchange(false); //serverInterface->setPrivateKey(new AsymmetricKey(32)); //NetInterfaceTestConnection *clientConnection = new NetInterfaceTestConnection; //Address addr("IP:127.0.0.1:25001"); //clientConnection->connect(clientInterface, &addr, true, false); for(;;) { myInterFace->checkIncomingPackets(); myInterFace->processConnections(); //clientInterface->checkIncomingPackets(); //clientInterface->processConnections(); } }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> #include "pWorldCallbacks.h" #include "pCallbackSignature.h" #include "virtools/vtTools.h" #include "pVehicleAll.h" using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; using namespace vtTools::BehaviorTools; bool pWheel2::isTorqueFromVehicle() { return getWheelFlag(WF_Accelerated) && getVehicle() && getVehicle()->isValidEngine() && getDifferential() ; } bool pWheel2::isAxleSpeedFromVehicle() { return ( getWheelFlag(WF_Accelerated) ) && ( getWheelShape()->getWheelFlags() & WSF_AxleSpeedOverride ) && getVehicle() && getVehicle()->isValidEngine() && getDifferential() ; } void pWheel2::applyTorqueToPhysics() { if (getDifferential()) { pDifferential *diff = getDifferential(); float finalTorqueOut = diff->GetTorqueOut(differentialSide); mWheelShape->setMotorTorque(finalTorqueOut); // Add torque to body because of the accelerating drivetrain // This gives a bit of the GPL effect where your car rolls when // you throttle with the clutch disengaged. float tr=getVehicle()->getEngine()->GetTorqueReaction(); if(tr>0) { // VxVector torque(0,0,diff->GetAccIn()*diff->inertiaIn*tr); // getBody()->addTorque(torque); } /* if( (wheel->getWheelShape()->getWheelFlags() & WSF_AxleSpeedOverride ) ) { float v = wheel->rotationV.x; v = v * getEngine()->getEndRotationalFactor() * getEngine()->getTimeScale(); } */ } } void pWheel2::_createInternalContactModifyCallback() { if (mWheelShape) { if (!wheelContactModifyCallback) { wheelContactModifyCallback = new pWheelContactModify(); wheelContactModifyCallback->setWheel(this); mWheelShape->setUserWheelContactModify((NxUserWheelContactModify*)wheelContactModifyCallback); } //---------------------------------------------------------------- //track information about callback if (getBody()) getBody()->getCallMask().set(CB_OnWheelContactModify,true); } } bool pWheelContactModify::onWheelContact(NxWheelShape* wheelShape, NxVec3& contactPoint, NxVec3& contactNormal, NxReal& contactPosition, NxReal& normalForce, NxShape* otherShape, NxMaterialIndex& otherShapeMaterialIndex, NxU32 otherShapeFeatureIndex) { pWheel2 *wheel = static_cast<pWheel2*>(getWheel()); if (!getWheel()) return true; int contactModifyFlags = 0 ; bool createContact=true; //---------------------------------------------------------------- // // store compact : // if (wheel->getBody()->getCallMask().test(CB_OnWheelContactModify)) { pWheelContactModifyData &contactData = lastData; contactData.object = getEntityFromShape(wheelShape); contactData.contactNormal = getFrom(contactNormal); contactData.contactPoint = getFrom(contactPoint); contactData.contactPosition = contactPosition; contactData.normalForce = normalForce; contactData.otherMaterialIndex = otherShapeMaterialIndex; createContact = wheel->onWheelContactModify(contactModifyFlags,&contactData); if (!createContact) return false; if (contactModifyFlags==0) return true; //---------------------------------------------------------------- // // copy result back to sdk // contactNormal = getFrom(contactData.contactNormal); contactPoint = getFrom(contactData.contactPoint); contactPosition = contactData.contactPosition; normalForce = contactData.normalForce; } //xWarning("whatever"); return true; } bool pWheel2::onWheelContactModify(int& changeFlags,pWheelContactModifyData* contact) { bool result = true; //---------------------------------------------------------------- // // sanity checks // if (!contact) return true; //---------------------------------------------------------------- // // keep some informationens for our self // if( getProcessOptions() & pVPO_Wheel_UsePHYSX_Load && getProcessOptions() & pVPO_Wheel_UsePHYSX_CONTACT_DATA && getVehicle() ) { load = contact->contactNormal.y; if (load > 1500) load = 1500; if (load <= 0) load = 1000; } CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getWheelContactScript()); if (beh && CKGetObject(ctx(),getEntID())) { SetInputParameterValue<CK_ID>(beh,bbIWC_SrcObject,getEntID()); SetInputParameterValue<VxVector>(beh,bbIWC_Point,contact->contactPoint); SetInputParameterValue<VxVector>(beh,bbIWC_Normal,contact->contactNormal); SetInputParameterValue<float>(beh,bbIWC_Position,contact->contactPosition); SetInputParameterValue<float>(beh,bbIWC_NormalForce,contact->normalForce); SetInputParameterValue<int>(beh,bbIWC_OtherMaterialIndex,contact->otherMaterialIndex); //---------------------------------------------------------------- // // execute: // beh->Execute(lastStepTimeSec); //---------------------------------------------------------------- // // refuse contact // result = GetOutputParameterValue<int>(beh,bbOWC_CreateContact); if (!result) return false; //---------------------------------------------------------------- // // nothing changed, return true // changeFlags = GetOutputParameterValue<int>(beh,bbOWC_ModificationFlags); if (changeFlags == 0 ) { return true; } //---------------------------------------------------------------- // // pickup data, according to change flags // if (changeFlags & CWCM_ContactPoint ) contact->contactPoint = GetOutputParameterValue<VxVector>(beh,bbOWC_Point); if (changeFlags & CWCM_ContactNormal) contact->contactNormal= GetOutputParameterValue<VxVector>(beh,bbOWC_Normal); if (changeFlags & CWCM_ContactPosition ) contact->contactPosition= GetOutputParameterValue<float>(beh,bbOWC_Position); if (changeFlags & CWCM_NormalForce ) contact->normalForce = GetOutputParameterValue<float>(beh,bbOWC_NormalForce); } return true; } bool pWheel2::onWheelContact(CK3dEntity* wheelShapeReference, VxVector& contactPoint, VxVector& contactNormal, float& contactPosition, float& normalForce, CK3dEntity* otherShapeReference, int& otherShapeMaterialIndex) { //NxUserAllocator return true; } void pWheel2::setWheelContactScript(int val) { CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(val); if (!beh) return; XString errMessage; if (!GetPMan()->checkCallbackSignature(beh,CB_OnWheelContactModify,errMessage)) { xError(errMessage.Str()); return; } pCallbackObject::setWheelContactScript(val); wheelContactModifyCallback = new pWheelContactModify(); wheelContactModifyCallback->setWheel(this); getWheelShape()->setUserWheelContactModify((NxUserWheelContactModify*)wheelContactModifyCallback); //---------------------------------------------------------------- //track information about callback getBody()->getCallMask().set(CB_OnWheelContactModify,true); } void pWheel2::processPreScript() { } void pWheel2::processPostScript() { } int pWheel2::onPostProcess() { return 1; } int pWheel2::onPreProcess() { return 1; } void pWheel2::_tick(float dt) { float dt2 = dt; NxWheelShape *wShape = getWheelShape(); if (!wShape) return; NxVec3 _localVelocity; bool _breaking=false; NxWheelContactData wcd; NxShape* contactShape = wShape->getContact(wcd); if (contactShape) { NxVec3 relativeVelocity; if ( !contactShape->getActor().isDynamic()) { relativeVelocity = getActor()->getLinearVelocity(); } else { relativeVelocity = getActor()->getLinearVelocity() - contactShape->getActor().getLinearVelocity(); } NxQuat rotation = getActor()->getGlobalOrientationQuat(); _localVelocity = relativeVelocity; rotation.inverseRotate(_localVelocity); _breaking = false; //NxMath::abs(_localVelocity.z) < ( 0.1 ); // wShape->setAxleSpeed() } float rollAngle = getWheelRollAngle(); rollAngle+=wShape->getAxleSpeed() * (dt); //rollAngle+=wShape->getAxleSpeed() * (1.0f/60.0f /*dt* 0.01f*/); while (rollAngle > NxTwoPi) //normally just 1x rollAngle-= NxTwoPi; while (rollAngle< -NxTwoPi) //normally just 1x rollAngle+= NxTwoPi; setWheelRollAngle(rollAngle); NxMat34& wheelPose = wShape->getGlobalPose(); NxReal stravel = wShape->getSuspensionTravel(); NxReal radius = wShape->getRadius(); //have ground contact? if( contactShape && wcd.contactPosition <= (stravel + radius) ) { wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); } else { wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); } float rAngle = getWheelRollAngle(); float steer = wShape->getSteerAngle(); NxVec3 p0; NxVec3 dir; /* getWorldSegmentFast(seg); seg.computeDirection(dir); dir.normalize(); */ NxReal r = wShape->getRadius(); NxReal st = wShape->getSuspensionTravel(); NxReal steerAngle = wShape->getSteerAngle(); p0 = wheelPose.t; //cast from shape origin wheelPose.M.getColumn(1, dir); dir = -dir; //cast along -Y. NxReal castLength = r + st; //cast ray this long NxMat33 rot, axisRot, rollRot; rot.rotY( wShape->getSteerAngle() ); axisRot.rotY(0); rollRot.rotX(rAngle); wheelPose.M = rot * wheelPose.M * axisRot * rollRot; setWheelPose(wheelPose); } <file_sep>/*--------------------------------------------------------------------- NVMH5 -|---------------------- Path: Sdk\Demos\Direct3D9\src\GetGPUAndSystemInfo\ File: GetGPUAndSystemInfo.cpp Copyright NVIDIA Corporation 2003 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND NVIDIA AND AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Comments: See GetGPUAndSystemInfo.h for additional comments. -------------------------------------------------------------------------------|--------------------*/ #include <windows.h> #include <d3dx9.h> #include "GetGPUAndSystemInfo.h" #include "shared\NV_Common.h" #include "shared\NV_Error.h" /*------------------------------------------------------------------ Retrieve various data through the IDxDiagContainer interface. The DXDiagNVUtil class provides a few convenient wrapper functions, and direct querries using the IDxDiagContainer COM object names are also supported. For a list of all the container and property COM object names, call ListAllDXDiagPropertyNames(..) ------------------------------------------------------------------*/ HRESULT GetGPUAndSystemInfo::GetData() { HRESULT hr = S_OK; //---------------------------------------------------------------------------- hr = m_DXDiagNVUtil.InitIDxDiagContainer(); MSG_AND_RET_VAL_IF( FAILED(hr), "Couldn't initialize DXDiagNVUtil!\n", hr ); wstring wstr; // Get the computer's machine name: m_DXDiagNVUtil.GetProperty( L"DxDiag_SystemInfo", L"szMachineNameEnglish", &wstr ); m_strMachineName = m_DXDiagNVUtil.WStringToString( &wstr ); FMsg("\n\n"); FMsg("------------------------------------------------------------------------\n"); FMsgW(L"machine name: %s\n", wstr.c_str() ); // Get info about physcial memory: m_DXDiagNVUtil.GetPhysicalMemoryInMB( & m_fSystemPhysicalMemoryMB ); FMsg("physical memory: %g MB\n", m_fSystemPhysicalMemoryMB ); // Get info about logical disks IDxDiagContainer * pContainer, *pChild; DWORD dwNumDisks; hr = m_DXDiagNVUtil.GetChildContainer( L"DxDiag_LogicalDisks", & pContainer ); if( SUCCEEDED(hr)) { pContainer->GetNumberOfChildContainers( & dwNumDisks ); wstring drive, space; FMsgW(L"logical disks: %d\n", dwNumDisks ); for( DWORD n=0; n < dwNumDisks; n++ ) { hr = m_DXDiagNVUtil.GetChildByIndex( pContainer, n, &pChild ); if( SUCCEEDED(hr) ) { m_DXDiagNVUtil.GetProperty( pChild, L"szDriveLetter", &drive ); m_DXDiagNVUtil.GetProperty( pChild, L"szFreeSpace", &space ); FMsgW(L" %s Free space = %s\n", drive.c_str(), space.c_str() ); SAFE_RELEASE( pChild ); } } SAFE_RELEASE( pContainer ); } FMsg("------------------------------------------------------------------------\n"); m_DXDiagNVUtil.GetDirectXVersion( &m_dwDXVersionMajor, &m_dwDXVersionMinor, &m_cDXVersionLetter ); FMsg("DirectX Version: %d.%d%c\n", m_dwDXVersionMajor, m_dwDXVersionMinor, m_cDXVersionLetter ); hr = m_DXDiagNVUtil.GetNumDisplayDevices( & m_dwNumDisplayDevices ); MSG_AND_RET_VAL_IF( FAILED(hr), "Couldn't GetNumDisplayDevices()\n", hr ); FMsg("Num Display Devices: %d\n", m_dwNumDisplayDevices ); string str; // for( DWORD dev=0; dev < m_dwNumDisplayDevices; dev ++ ) if( m_dwNumDisplayDevices > 0 ) { DWORD dev = 0; // get info from display devices m_DXDiagNVUtil.GetDisplayDeviceDescription( dev, & m_wstrDeviceDesc ); m_DXDiagNVUtil.GetDisplayDeviceNVDriverVersion( dev, & m_fDriverVersion ); m_DXDiagNVUtil.GetDisplayDeviceMemoryInMB( dev, & m_nDeviceMemoryMB ); // report the info via OutputDebugString FMsgW(L"Device %d Description: %s\n", dev, m_wstrDeviceDesc.c_str() ); FMsg( "Device %d Driver version: %g\n", dev, m_fDriverVersion ); FMsg( "Device %d Physical mem: %d MB\n", dev, m_nDeviceMemoryMB ); // Get info about AGP memory: wstring wstrAGPEnabled, wstrAGPExists, wstrAGPStatus; hr = m_DXDiagNVUtil.GetDisplayDeviceAGPMemoryStatus( dev, &wstrAGPEnabled, &wstrAGPExists, &wstrAGPStatus ); if( SUCCEEDED(hr)) { // create a string from the AGP status strings m_strAGPStatus = ""; str = m_DXDiagNVUtil.WStringToString( &wstrAGPEnabled ); m_strAGPStatus += "AGP Enabled = "; m_strAGPStatus += str; m_strAGPStatus += ", "; str = m_DXDiagNVUtil.WStringToString( &wstrAGPExists ); m_strAGPStatus += "AGP Exists = "; m_strAGPStatus += str; m_strAGPStatus += ", "; str = m_DXDiagNVUtil.WStringToString( &wstrAGPStatus ); m_strAGPStatus += "AGP Status = "; m_strAGPStatus += str; } FMsg("%s\n", m_strAGPStatus.c_str() ); wstring wstrNotes, wstrTestD3D9; m_DXDiagNVUtil.GetProperty( L"DxDiag_DisplayDevices", L"0", L"szTestResultD3D9English", &wstrTestD3D9 ); m_DXDiagNVUtil.GetProperty( L"DxDiag_DisplayDevices", L"0", L"szNotesEnglish", &wstrNotes ); str = m_DXDiagNVUtil.WStringToString( &wstrTestD3D9 ); FMsg("Device 0 szTestResultD3D9English = \"%s\"\n", str.c_str() ); str = m_DXDiagNVUtil.WStringToString( &wstrNotes ); FMsg("Device 0 szNotesEnglish = \"%s\"\n", str.c_str() ); } m_DXDiagNVUtil.GetDebugLevels( & m_wstrDxDebugLevels ); FMsg("DirectX Debug Levels:\n"); FMsgW(L"%s\n", m_wstrDxDebugLevels.c_str() ); // ListAllDXDiagPropertyNames() is slow // It prints out all nodes, child nodes, properties and their values // m_DXDiagNVUtil.ListAllDXDiagPropertyNames(); // Use a call like that below to print out a specific node and it's children. // For example, to list all the display device property names. /* m_DXDiagNVUtil.GetChildContainer( L"DxDiag_DisplayDevices", &pContainer ); m_DXDiagNVUtil.ListAllDXDiagPropertyNames( pContainer, L"DxDiag_DisplayDevices" ); SAFE_RELEASE( pContainer ); // */ m_DXDiagNVUtil.FreeIDxDiagContainer(); return( hr ); } HRESULT GetGPUAndSystemInfo::IsFPBlendingSupported( IDirect3D9 * pD3D9, FloatingPointBlendModes * pOutResult ) { FMsg("There is a bug with this code in that is does not report that blending works for ordinary backbuffer formats\n"); assert( false ); HRESULT hr = S_OK; FAIL_IF_NULL( pD3D9 ); FAIL_IF_NULL( pOutResult ); bool * pResult; hr = pD3D9->CheckDeviceFormat( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_A8R8G8B8, D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_SURFACE, D3DFMT_R16F ); pResult = &pOutResult->m_bR16f; if( hr == D3D_OK ) *pResult = true; else if( hr == D3DERR_NOTAVAILABLE ) *pResult = false; else FMsg("Unknown return result for D3DFMT_R16F : %u\n", hr ); hr = pD3D9->CheckDeviceFormat( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_A8R8G8B8, D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_SURFACE, D3DFMT_A16B16G16R16F ); pResult = &pOutResult->m_bA16B16G16R16f; if( hr == D3D_OK ) *pResult = true; else if( hr == D3DERR_NOTAVAILABLE ) *pResult = false; else FMsg("Unknown return result for D3DFMT_A16B16G16R16F : %u\n", hr ); hr = pD3D9->CheckDeviceFormat( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_A8R8G8B8, // D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, 0 | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, // per the DX90SDK docs D3DRTYPE_SURFACE, D3DFMT_A8R8G8B8 ); pResult = &pOutResult->m_bA8R8G8B8; if( hr == D3D_OK ) *pResult = true; else if( hr == D3DERR_NOTAVAILABLE ) *pResult = false; else FMsg("Unknown return result for D3DFMT_A8R8G8B8 : %u\n", hr ); if( pOutResult->m_bA16B16G16R16f == true ) FMsg("D3DFMT_A16B16G16R16F POSTPIXELSHADER_BLENDING is supported\n"); else FMsg("D3DFMT_A16B16G16R16F POSTPIXELSHADER_BLENDING is not supported\n"); if( pOutResult->m_bR16f == true ) FMsg("D3DFMT_R16F POSTPIXELSHADER_BLENDING is supported\n"); else FMsg("D3DFMT_R16F POSTPIXELSHADER_BLENDING is not supported\n"); if( pOutResult->m_bA8R8G8B8 == true ) FMsg("D3DFMT_A8R8G8B8 POSTPIXELSHADER_BLENDING is supported\n"); else FMsg("D3DFMT_A8R8G8B8 POSTPIXELSHADER_BLENDING is not supported\n"); /* Use IDirect3D9::CheckDeviceFormat, with usage (D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADERBLENDING). HRESULT CheckDeviceFormat( UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, DWORD Usage, D3DRESOURCETYPE RType, D3DFORMAT CheckFormat ); D3DFMT_R16F 111 16-bit float format using 16 bits for the red channel. D3DFMT_G16R16F 112 32-bit float format using 16 bits for the red channel and 16 bits for the green channel. D3DFMT_A16B16G16R16F D3DFMT_R32F 114 32-bit float format using 32 bits for the red channel. D3DFMT_G32R32F 115 64-bit float format using 32 bits for the red channel and 32 bits for the green channel. D3DFMT_A32B32G32R32F D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING D3DUSAGE_QUERY_FILTER (more than just point sampling) Query the resource to verify support for post pixel shader blending support. If IDirect3D9::CheckDeviceFormat fails with D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, post pixel blending operations are not supported. These include alpha test, pixel fog, render-target blending, color write enable, and dithering. MSFT examples from SDK if( pCaps->PixelShaderVersion < D3DPS_VERSION(1,1) ) { if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, adapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_A8R8G8B8 ) ) ) { return E_FAIL; } } // Need to support post-pixel processing (for alpha blending) if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, adapterFormat, D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_SURFACE, backBufferFormat ) ) ) { return E_FAIL; } HRESULT CMyD3DApplication::ConfirmDevice( D3DCAPS9* pCaps, DWORD dwBehavior, D3DFORMAT adapterFormat, D3DFORMAT backBufferFormat ) { // Need to support post-pixel processing (for alpha blending) if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, adapterFormat, D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_SURFACE, backBufferFormat ) ) ) { return E_FAIL; } */ return( hr ); } <file_sep>#ifndef __P_WORLD_H__ #define __P_WORLD_H__ #include "pTypes.h" /** \brief Class to maintain physical objects. */ class MODULE_API pWorld { public: pWorld(); bool m_bCompletedLastFrame; // in class definition float m_fTimeSinceLastCallToSimulate; // in class def pWorld(CK3dEntity* _o); virtual ~pWorld(); void _construct(); int hadBrokenJoint(); void cleanBrokenJoints(); CK3dEntity* getReference() const { return m_vtReference; } void setReference(CK3dEntity* val) { m_vtReference = val; } pWorldSettings * getWorldSettings() const { return m_worldSettings; } void setWorldSettings(pWorldSettings * val) { m_worldSettings = val; } pSleepingSettings * getSleepingSettings() const { return m_SleepingSettings; } void setSleepingSettings(pSleepingSettings * val) { m_SleepingSettings = val; } NxScene* getScene() const { return mScene; } void setScene(NxScene* val) { mScene = val; } NxMaterial* getDefaultMaterial() const { return mDefaultMaterial; } void setDefaultMaterial(NxMaterial* val) { mDefaultMaterial = val; } int UpdateProperties(DWORD mode,DWORD flags); int& getDataFlags() { return m_DataFlags; } void setDataFlags(int val) { m_DataFlags = val; } void destroy(); pRigidBody *getBody(CK3dEntity*ent); pRigidBody *getBodyFromSubEntity(CK3dEntity *sub); //pJoint*getJoint(CK3dEntity*,CK3dEntity*); pJoint*getJoint(CK3dEntity*_a,CK3dEntity*_b,JType type); void deleteJoint(pJoint*joint); void _checkForDominanceConstraints(); NxCompartment * compartment; NxCompartment * getCompartment() const { return compartment; } void setCompartment(NxCompartment * val) { compartment = val; } /** @name Collision Filtering */ //@{ /** \brief Setups filtering operations. See comments for ::pGroupsMask <b>Sleeping:</b> Does <b>NOT</b> wake the actors up automatically. \param[in] op0 Filter op 0. \param[in] op1 Filter op 1. \param[in] op2 Filter op 2. @see setFilterBool() setFilterConstant0() setFilterConstant1() */ void setFilterOps(pFilterOp op0,pFilterOp op1, pFilterOp op2); /** \brief Setups filtering's boolean value. See comments for ::pGroupsMask <b>Sleeping:</b> Does <b>NOT</b> wake the actors up automatically. \param[in] flag Boolean value for filter. @see setFilterOps() setFilterConstant0() setFilterConstant1() */ void setFilterBool(bool flag); /** \brief Setups filtering's K0 value. See comments for ::pGroupsMask <b>Sleeping:</b> Does <b>NOT</b> wake the actors up automatically. \param[in] mask The new group mask. See #pGroupsMask. @see setFilterOps() setFilterBool() setFilterConstant1() */ void setFilterConstant0(const pGroupsMask& mask); /** \brief Setups filtering's K1 value. See comments for ::pGroupsMask <b>Sleeping:</b> Does <b>NOT</b> wake the actors up automatically. \param[in] mask The new group mask. See #pGroupsMask. @see setFilterOps() setFilterBool() setFilterConstant0() */ void setFilterConstant1(const pGroupsMask& mask); /** \brief Retrieves filtering operation. See comments for ::pGroupsMask \param[out] op0 First filter operator. \param[out] op1 Second filter operator. \param[out] op2 Third filter operator. See the user guide page "Contact Filtering" for more details. \return the filter operation requested @see setFilterOps() setFilterBool() setFilterConstant0() setFilterConstant1() */ void getFilterOps(pFilterOp& op0, pFilterOp& op1, pFilterOp& op2)const; /** \brief Retrieves filtering's boolean value. See comments for ::pGroupsMask \return flag Boolean value for filter. @see setFilterBool() setFilterConstant0() setFilterConstant1() */ bool getFilterBool() const; /** \brief Gets filtering constant K0. See comments for ::pGroupsMask \return the filtering constant, as a mask. See #pGroupsMask. @see setFilterOps() setFilterBool() setFilterConstant0() setFilterConstant1() getFilterConstant1() */ pGroupsMask getFilterConstant0() const; /** \brief Gets filtering constant K1. See comments for ::NxGroupsMask \return the filtering constant, as a mask. See #pGroupsMask. @see setFilterOps() setFilterBool() setFilterConstant0() setFilterConstant1() getFilterConstant0() */ pGroupsMask getFilterConstant1() const; //@} /** @name Raycasting */ //@{ /** \brief Returns true if any axis aligned bounding box enclosing a shape of type shapeType is intersected by the ray. \note Make certain that the direction vector of NxRay is normalized. \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is taken. For example the result of setting the global pose is not immediately visible. \param[in] worldRay The ray to cast in the global frame. <b>Range:</b> See #NxRay \param[in] shapesType Choose if to raycast against static, dynamic or both types of shape. See #pShapesType. \param[in] groups Mask used to filter shape objects. See #pRigidBody::setGroup \param[in] maxDist Max distance to check along the ray for intersecting bounds. <b>Range:</b> (0,inf) \param[in] groupsMask Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask \return true if any axis aligned bounding box enclosing a shape of type shapeType is intersected by the ray @see pShapesType VxRay pRigidBody.setGroup() raycastAnyShape() */ bool raycastAnyBounds (const VxRay& worldRay, pShapesType shapesType, pGroupsMask *groupsMask=NULL,int groups=0xffffffff, float maxDist=pFLOAT_MAX); /** \brief Returns true if any shape of type ShapeType is intersected by the ray. \note Make certain that the direction vector of NxRay is normalized. \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is taken. For example the result of setting the global pose is not immediately visible. \param[in] worldRay The ray to cast in the global frame. <b>Range:</b> See #VxRay \param[in] shapesType Choose if to raycast against static, dynamic or both types of shape. See #pShapesType. \param[in] groups Mask used to filter shape objects. See #pRigidBody::setGroup \param[in] maxDist Max distance to check along the ray for intersecting objects. <b>Range:</b> (0,inf) \param[in] groupsMask Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask \param[in] cache Possible cache for persistent raycasts, filled out by the SDK. \return Returns true if any shape of type ShapeType is intersected by the ray. @see pShapesType VxRay pRigidBody.setGroup() raycastAnyBounds() */ bool raycastAnyShape (const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,CKDataArray* cache, int groups=0xffffffff, float maxDist=pFLOAT_MAX); /** \brief Calls the report's hitCallback() method for all the shapes of type ShapeType intersected by the ray. hintFlags is a combination of ::NxRaycastBit flags. Returns the number of shapes hit. The point of impact is provided as a parameter to hitCallback(). \note Make certain that the direction vector of NxRay is normalized. \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is taken. For example the result of setting the global pose is not immediatly visible. <h3>Example</h3> \include NxUserRaycastReport_Usage.cpp \param[in] worldRay The ray to cast in the global frame. <b>Range:</b> See #NxRay \param[in] report User callback, to be called when an intersection is encountered. \param[in] shapesType Choose if to raycast against static, dynamic or both types of shape. See #NxShapesType. \param[in] groups Mask used to filter shape objects. See #NxShape::setGroup \param[in] maxDist Max distance to check along the ray for intersecting objects. <b>Range:</b> (0,inf) \param[in] hintFlags Allows the user to specify which field of #NxRaycastHit they are interested in. See #NxRaycastBit \param[in] groupsMask Alternative mask used to filter shapes. See #NxShape::setGroupsMask \return the number of shapes hit <b>Platform:</b> \li PC SW: Yes \li PPU : Yes \li PS3 : Yes \li XB360: Yes @see raycastAnyShape() raycastAllBounds() NxRay NxUserRaycastReport NxShapesType NxShape.setGroup() NxRaycastHit */ int raycastAllShapes (const VxRay& worldRay, pShapesType shapesType, int groups=0xffffffff, float maxDist=pFLOAT_MAX, pRaycastBit hintFlags=(pRaycastBit)0xffffffff, const pGroupsMask* groupsMask=NULL); //@} /** @name Overlap Testing */ //@{ /** \brief Returns the set of shapes overlapped by the world-space sphere. You can test against static and/or dynamic objects by adjusting 'shapeType'. Shapes are written to the static array 'shapes', which should be big enough to hold 'nbShapes'. The function returns the total number of collided shapes. \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is taken. For example the result of setting the global pose is not immediatly visible. \param[in] worldSphere Sphere description in world space. <b>Range:</b> See #VxSphere \param[in] shapeType Choose if to intersect with static, dynamic or both types of shape. See #pShapesType. \param[out] shapes Buffer to store intersecting shapes. \param[in] activeGroups Mask used to filter shape objects. See #pRigidBody::setGroup \param[in] groupsMask Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask \param[in] accurateCollision True to test the sphere against the actual shapes, false to test against the AABBs only. \return the total number of collided shapes. @see pShapesType overlapAABBShapes */ int overlapSphereShapes (const VxSphere& worldSphere,CK3dEntity*shapeReference,pShapesType shapeType,CKGroup *shapes,int activeGroups=0xffffffff, const pGroupsMask* groupsMask=NULL, bool accurateCollision=false); /** \brief Returns the set of shapes overlapped by the world-space AABB. You can test against static and/or dynamic objects by adjusting 'shapeType'. Shapes are written to the static array 'shapes', which should be big enough to hold 'nbShapes'. The function returns the total number of collided shapes. \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is taken. For example the result of setting the global pose is not immediatly visible. \param[in] worldBounds Axis Aligned Bounding Box in world space. <b>Range:</b> \param[in] shapeType Choose if to intersect with static, dynamic or both types of shape. See pShapesType. \param[out] shapes Buffer to store intersecting shapes. \param[in] activeGroups Mask used to filter shape objects. See #pRigidBody::setGroup \param[in] groupsMask Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask \param[in] accurateCollision True to test the AABB against the actual shapes, false to test against the AABBs only. \return the total number of collided shapes. @see pxShapesType overlapAABBShapes */ int overlapAABBShapes (const VxBbox& worldBounds, CK3dEntity*shapeReference, pShapesType shapeType,CKGroup *shapes,int activeGroups=0xffffffff, const pGroupsMask* groupsMask=NULL, bool accurateCollision=false); /** \brief Returns the set of shapes overlapped by the world-space OBB. You can test against static and/or dynamic objects by adjusting 'shapeType'. The function returns the total number of collided shapes. \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is taken. For example the result of setting the global pose is not immediatly visible. \param[in] worldBox Oriented Bounding Box in world space. <b>Range:</b> See #NxBox \param[in] shapeType Choose if to intersect with static, dynamic or both types of shape. See #NxShapesType. \param[out] shapes Buffer to store intersecting shapes. Should be at least sizeof(NxShape *) * nbShapes. \param[in] activeGroups Mask used to filter shape objects. See #NxShape::setGroup \param[in] groupsMask Alternative mask used to filter shapes. See #NxShape::setGroupsMask \param[in] accurateCollision True to test the OBB against the actual shapes, false to test against the AABBs only. \return the total number of collided shapes. @see pShapesType overlapOBBShapes */ int overlapOBBShapes (const VxBbox& worldBox,CK3dEntity*shapeReference, pShapesType shapeType,CKGroup *shapes, int activeGroups=0xffffffff, const pGroupsMask* groupsMask=NULL, bool accurateCollision=false); /** \brief Returns the set of shapes overlapped by the world-space capsule. You can test against static and/or dynamic objects by adjusting 'shapeType'. Shapes are written to the static array 'shapes', which should be big enough to hold 'nbShapes'. An alternative is to use the ::NxUserEntityReport callback mechanism. The function returns the total number of collided shapes. \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is taken. For example the result of setting the global pose is not immediatly visible. \param[in] worldCapsule capsule in world space. <b>Range:</b> See #NxCapsule \param[in] shapeType Choose if to intersect with static, dynamic or both types of shape. See #NxShapesType. \param[out] shapes Buffer to store intersecting shapes. Should be at least sizeof(NxShape *) * nbShapes. \param[in] activeGroups Mask used to filter shape objects. See #NxShape::setGroup \param[in] groupsMask Alternative mask used to filter shapes. See #NxShape::setGroupsMask \param[in] accurateCollision True to test the capsule against the actual shapes, false to test against the AABBs only. \return the total number of collided shapes. <b>Platform:</b> \li PC SW: Yes \li PPU : Yes \li PS3 : Yes \li XB360: Yes @see pShapesType overlapCapsuleShapes */ //virtual NxU32 overlapCapsuleShapes (const NxCapsule& worldCapsule, NxShapesType shapeType, NxU32 nbShapes, NxShape** shapes, NxUserEntityReport<NxShape*>* callback, NxU32 activeGroups=0xffffffff, const NxGroupsMask* groupsMask=NULL, bool accurateCollision=false) = 0; //@} void step(float stepsize); bool isValid(); JointFeedbackListType m_JointFeedbackList; JointFeedbackListType& getJointFeedbackList() { return m_JointFeedbackList; } void setJointFeedbackList(JointFeedbackListType val) { m_JointFeedbackList = val; } void inspectJoints(); void deleteBody(pRigidBody*body); int getNbBodies(); int getNbJoints(); void checkList(); /************************************************************************/ /* */ /************************************************************************/ void cSetGroupCollisionFlag(int g1 , int g2,int enabled); void cIgnorePair(CK3dEntity* _a,CK3dEntity *_b,int ignore); void initUserReports(); pContactReport *contactReport; pContactReport*getContactReportPtr(){ return contactReport;} pContactModify *contactModify; pContactModify*getContactModifyPtr(){ return contactModify;} pTriggerReport *triggerReport; pTriggerReport *getTriggerReportPtr(){ return triggerReport;} pRayCastReport *raycastReport; pRayCastReport * getRaycastReport(){ return raycastReport; } void setRaycastReport(pRayCastReport * val) { raycastReport = val; } UserAllocator* mAllocator; UserAllocator* setAllocator() const { return mAllocator; } void setAllocator(UserAllocator* val) { mAllocator= val; } int getNbOfVehicles(); int getNbOfWhees(); public : CK3dEntity* m_vtReference; pSleepingSettings *m_SleepingSettings; pWorldSettings *m_worldSettings; NxScene* mScene; NxMaterial* mDefaultMaterial; NxControllerManager *mCManager; void updateVehicles(float dt); void updateVehicle(pVehicle *vehicle,float dt); pVehicle *getVehicle(CK3dEntity* body); void deleteVehicle(CK3dEntity*body,int flags = 0); bool isVehicle(NxActor* actor); pWheel1 *getWheel1(CK3dEntity *reference); pWheel2 *getWheel2(CK3dEntity *reference); /************************************************************************/ /* */ /************************************************************************/ void updateClothes(); void updateFluids(); pCloth *getCloth(CK3dEntity*reference); pCloth *getCloth(CK_ID id); void destroyCloth(CK_ID id); pFluid *getFluid(CK_ID id); pFluid *getFluid(CK3dEntity* entity); NxShape *getShapeByEntityID(CK_ID id); NxShape *getShapeByMeshID(CK_ID id); NxControllerManager * getCManager() const { return mCManager; } void setCManager(NxControllerManager * val) { mCManager = val; } void advanceTime(float lastDeltaMS); int onPreProcess(); int onPostProcess(); int callMask; int& getCallMask() { return callMask; } void setCallMask(int val) { callMask = val; } int overrideMask; int& getOverrideMask() { return overrideMask; } void setOverrideMask(int val) { overrideMask = val; } //---------------------------------------------------------------- // // material // bool getMaterialByIndex(int index,pMaterial&dst); bool updateMaterialByIndex(int index,pMaterial src); //---common settings void setGravity(VxVector gravity); VxVector getGravity(); int m_DataFlags; }; /** @} */ #endif // !defined(EA_0976AF4F_8E4B_4e7b_B4CD_B7588D3D4FF8__INCLUDED_) <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "ISession.h" #include "xDistributedSessionClass.h" #include "xDistributedSession.h" CKObjectDeclaration *FillBehaviorNSGetListObjectDecl(); CKERROR CreateNSGetListObjectProto(CKBehaviorPrototype **); int NSGetListObject(const CKBehaviorContext& behcontext); CKERROR NSGetListObjectCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 5 #define BEH_OUT_MIN_COUNT 10 #define BEH_OUT_MAX_COUNT 1 typedef enum BB_IT { BB_IT_IN, BB_IT_NEXT }; typedef enum BB_INPAR { BB_IP_CONNECTION_ID, BB_IP_SESSION_TYPE, BB_IP_LIST_FULL, BB_IP_LIST_PRIVATE, BB_IP_LIST_LOCKED, }; typedef enum BB_OT { BB_O_OUT, BB_O_WAITING, BB_O_ERROR, BB_O_SESSION }; typedef enum BB_OP { BB_OP_SESSIONS, BB_OP_SESSION_ID, BB_OP_SESSION_NAME, BB_OP_SESSION_MASTER, BB_OP_SESSION_USERS, BB_OP_SESSION_MAX_PLAYERS, BB_OP_SESSION_FULL, BB_OP_SESSION_PRIVATE, BB_OP_SESSION_LOCKED, BB_OP_ERROR }; #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorNSGetListObjectDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NSGetList"); od->SetDescription("Iterates through all server sessions"); od->SetCategory("TNL/Sessions"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x16760924,0x29200470)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNSGetListObjectProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateNSGetListObjectProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NSGetList"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Next"); proto->DeclareOutput("Out"); proto->DeclareOutput("Waiting For Answer"); proto->DeclareOutput("Error"); proto->DeclareOutput("Session"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Session Type", CKPGUID_INT, "-1"); proto->DeclareInParameter("List Full Sessions", CKPGUID_BOOL, "TRUE"); proto->DeclareInParameter("List Private Sessions", CKPGUID_BOOL, "TRUE"); proto->DeclareInParameter("List Locked Sessions", CKPGUID_BOOL, "TRUE"); proto->DeclareOutParameter("Sessions", CKPGUID_INT, "-1"); proto->DeclareOutParameter("Session ID", CKPGUID_INT, "-1"); proto->DeclareOutParameter("Session Name", CKPGUID_STRING, ""); proto->DeclareOutParameter("Session Master", CKPGUID_STRING, ""); proto->DeclareOutParameter("Users", CKPGUID_INT, "-1"); proto->DeclareOutParameter("Max Players", CKPGUID_INT, "-1"); proto->DeclareOutParameter("Full", CKPGUID_BOOL, "FALSE"); proto->DeclareOutParameter("Private", CKPGUID_BOOL, "FALSE"); proto->DeclareOutParameter("Locked", CKPGUID_BOOL, "FALSE"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareLocalParameter("current result", CKPGUID_POINTER, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS)); proto->SetFunction(NSGetListObject); proto->SetBehaviorCallbackFct(NSGetListObjectCB); *pproto = proto; return CK_OK; } typedef std::vector<xDistributedSession*>xSessions; #include "vtLogTools.h" int NSGetListObject(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; ////////////////////////////////////////////////////////////////////////// //connection id + session name : using namespace vtTools::BehaviorTools; int connectionID = GetInputParameterValue<int>(beh,0); ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } /************************************************************************/ /* */ /************************************************************************/ if (beh->IsInputActive(0)) { bbNoError(E_NWE_OK); beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //we reset our session counter int sessionIndex=-1; beh->SetOutputParameterValue(BB_OP_SESSIONS,&sessionIndex); xSessions *sResults = NULL; beh->GetLocalParameterValue(0,&sResults); if (!sResults) { sResults = new xSessions(); }else sResults->clear(); beh->SetLocalParameterValue(0,&sResults); int sessionType = GetInputParameterValue<int>(beh,BB_IP_SESSION_TYPE); int listFull = GetInputParameterValue<int>(beh,BB_IP_LIST_FULL); int listPrivate = GetInputParameterValue<int>(beh,BB_IP_LIST_PRIVATE); int listLocked = GetInputParameterValue<int>(beh,BB_IP_LIST_LOCKED); ////////////////////////////////////////////////////////////////////////// //we iterate though all session objects and add it in a filtered temporary array : ISession *sInterface = cin->getSessionInterface(); IDistributedObjects *doInterface = cin->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = cin->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { xDistributedClass *_class = dobj->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_SESSION ) { xDistributedSession *session = static_cast<xDistributedSession*>(dobj); if (session && session->getSessionFlags().test(1<< E_SF_COMPLETE ) ) { if ( session->isPrivate() && !listPrivate) { begin++; continue; } if ( session->isLocked() && !listLocked) { begin++; continue; } if ( session->isFull() && !listFull) { begin++; continue; } sResults->push_back(session); } } } } begin++; } if (sResults->size()) { beh->ActivateInput(1); }else { beh->ActivateOutput(BB_O_OUT); return 0; } } /************************************************************************/ /* */ /************************************************************************/ if (beh->IsInputActive(1)) { beh->ActivateInput(1,FALSE); int currentIndex=0; CKParameterOut *pout = beh->GetOutputParameter(BB_OP_SESSIONS); pout->GetValue(&currentIndex); currentIndex++; xSessions *sResults = NULL; beh->GetLocalParameterValue(0,&sResults); if (!sResults) { beh->ActivateOutput(BB_O_OUT); return 0; } if (currentIndex>=sResults->size()) { sResults->clear(); beh->ActivateOutput(BB_O_OUT); return 0; } xDistributedSession * session = sResults->at(currentIndex); if (session!=NULL) { int sIndex = currentIndex+1; beh->SetOutputParameterValue(BB_OP_SESSIONS,&sIndex); /************************************************************************/ /* output bas data : */ /************************************************************************/ int sessionID = session->getSessionID();beh->SetOutputParameterValue(BB_OP_SESSION_ID,&sessionID); CKSTRING sesssionName = const_cast<char*>(session->GetName().getString()); CKParameterOut *poutName = beh->GetOutputParameter(BB_OP_SESSION_NAME); poutName->SetStringValue(sesssionName); int maxPlayers = session->getMaxUsers(); beh->SetOutputParameterValue(BB_OP_SESSION_MAX_PLAYERS,&maxPlayers); int isFull = session->isFull(); beh->SetOutputParameterValue(BB_OP_SESSION_FULL,&isFull); int isPrivate = session->isPrivate(); beh->SetOutputParameterValue(BB_OP_SESSION_PRIVATE,&isPrivate); int isLocked = session->isLocked(); beh->SetOutputParameterValue(BB_OP_SESSION_LOCKED,&isLocked); int numUsers = session->getNumUsers(); beh->SetOutputParameterValue(BB_OP_SESSION_USERS,&numUsers); beh->SetOutputParameterValue(BB_OP_SESSIONS,&currentIndex); beh->ActivateOutput(BB_O_SESSION); /************************************************************************/ /*output additional properties */ /************************************************************************/ if ( beh->GetOutputParameterCount() > BEH_OUT_MIN_COUNT ) { xDistributedSessionClass *_class = (xDistributedSessionClass*)session->getDistributedClass(); CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); for (int i = BEH_OUT_MIN_COUNT ; i < beh->GetOutputParameterCount() ; i++ ) { CKParameterOut *ciIn = beh->GetOutputParameter(i); CKParameterType pType = ciIn->GetType(); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); xDistributedPropertyArrayType &props = *session->getDistributedPorperties(); int propID = _class->getInternalUserFieldIndex(i - BEH_OUT_MIN_COUNT); int startIndex = _class->getFirstUserField(); int pSize = props.size(); if (propID==-1 || propID > props.size() ) { beh->ActivateOutput(BB_O_ERROR); return 0; } xDistributedProperty *prop = props[propID]; if (prop) { //we set the update flag in the prop by hand : xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); if (propInfo) { if (xDistTools::ValueTypeToSuperType(propInfo->mValueType) ==sType ) { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); switch(propInfo->mValueType) { case E_DC_PTYPE_3DVECTOR: { xDistributedPoint3F * dpoint3F = (xDistributedPoint3F*)prop; if (dpoint3F) { VxVector vvalue = xMath::getFrom(dpoint3F->mLastServerValue); beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_FLOAT: { xDistributedPoint1F * dpoint3F = (xDistributedPoint1F*)prop; if (dpoint3F) { float vvalue = dpoint3F->mLastServerValue; beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_2DVECTOR: { xDistributedPoint2F * dpoint3F = (xDistributedPoint2F*)prop; if (dpoint3F) { Vx2DVector vvalue = xMath::getFrom(dpoint3F->mLastServerValue); beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_QUATERNION: { xDistributedQuatF * dpoint3F = (xDistributedQuatF*)prop; if (dpoint3F) { VxQuaternion vvalue = xMath::getFrom(dpoint3F->mLastServerValue); beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_STRING: { xDistributedString * propValue = (xDistributedString*)prop; if (propValue) { TNL::StringPtr ovalue = propValue->mCurrentValue; CKParameterOut *pout = beh->GetOutputParameter(i); XString errorMesg(ovalue.getString()); pout->SetStringValue(errorMesg.Str()); } break; } case E_DC_PTYPE_INT: { xDistributedInteger * dpoint3F = (xDistributedInteger*)prop; if (dpoint3F) { int ovalue = dpoint3F->mLastServerValue; beh->SetOutputParameterValue(i,&ovalue); } break; } case E_DC_PTYPE_UNKNOWN: { bbError(E_NWE_INVALID_PARAMETER); break; } } } } } } } } } return 0; } CKERROR NSGetListObjectCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; } <file_sep>//////////////////////////////////////////////////////////////////////////////// // // ARToolKitPlusLogger // -------------------------------------- // // Description: // Little helper class which encapsulate the error logging // (look into ARToolKitPlus for description) // // Version 1.0 : First Release // // Known Bugs : Not really integrated into Virtools, just a dummy call // // Copyright <NAME> <<EMAIL>>, University of Paderborn //////////////////////////////////////////////////////////////////////////////// #ifndef ARToolKitPlusLogger_H #define ARToolKitPlusLogger_H "$Id:$" #include <ARToolKitPlus/TrackerSingleMarkerImpl.h> class ARToolKitLogger : public ARToolKitPlus::Logger { void artLog(const char* nStr) { printf(nStr); } }; #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> void pRigidBody::updateMaterialSettings(pMaterial& material,CK3dEntity*shapeReference/* =NULL */) { if (shapeReference==NULL) assert (getMainShape()); NxShape *shape = getSubShape(shapeReference); if (shape) { pMaterial &bMaterial = material; if (bMaterial.xmlLinkID !=0) { int bIndex = bMaterial.xmlLinkID; XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,bMaterial.xmlLinkID); bool err = pFactory::Instance()->loadFrom(bMaterial,nodeName.Str(), pFactory::Instance()->getDefaultDocument() ); } iAssertW( bMaterial.isValid(),pFactory::Instance()->findSettings(bMaterial,shapeReference), "Material settings invalid, try to find material attributes"); iAssertW( bMaterial.isValid(),bMaterial.setToDefault(), "Material settings were still invalid : "); NxMaterialDesc nxMatDescr; pFactory::Instance()->copyTo(nxMatDescr,bMaterial); NxMaterial *nxMaterial = getWorld()->getScene()->createMaterial(nxMatDescr); if (nxMaterial) { shape->setMaterial(nxMaterial->getMaterialIndex()); } } } void pRigidBody::updatePivotSettings(pPivotSettings pivot,CK3dEntity*shapeReference/* =NULL */) { if (shapeReference==NULL) assert (getMainShape()); NxShape *shape = getSubShape(shapeReference); if (shape) { // Referential CK3dEntity* pivotRef = (CK3dEntity*)GetPMan()->GetContext()->GetObject(pivot.pivotReference); VxVector pivotLocalOut = pivot.localPosition; //---------------------------------------------------------------- // // position // if (pivotRef) { pivotRef->Transform(&pivotLocalOut,&pivotLocalOut); shape->setGlobalPosition(getFrom(pivotLocalOut)); }else { shape->setLocalPosition(getFrom(pivotLocalOut)); } //---------------------------------------------------------------- // // rotational offset : todo // VxMatrix mat; Vx3DMatrixFromEulerAngles(mat,pivot.localOrientation.x,pivot.localOrientation.y,pivot.localOrientation.z); VxQuaternion outQuat; outQuat.FromMatrix(mat); VxQuaternion referenceQuat=outQuat; if (pivotRef) { pivotRef->GetQuaternion(&referenceQuat,NULL); shape->setLocalOrientation(getFrom(referenceQuat)); }else{ shape->setLocalOrientation(getFrom(outQuat)); } } } void pRigidBody::saveToAttributes(pObjectDescr* oDescr) { if (!oDescr) return; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; int attTypeActor = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); int attTypeMaterial = GetPMan()->getAttributeTypeByGuid(VTS_MATERIAL); int attTypeOptimization = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); int attTypeCCD = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CCD_SETTINGS); //---------------------------------------------------------------- // // disable attribute callback // CKAttributeManager *aMan = GetPMan()->GetContext()->GetAttributeManager(); if (aMan) { //aMan->SetAttributeCallbackFunction(attTypeActor) } CK3dEntity *referenceObject = GetVT3DObject(); ////////////////////////////////////////////////////////////////////////// // we remove the old physic attribute : if (referenceObject->HasAttribute(attTypeActor)) { referenceObject->RemoveAttribute(attTypeActor); } referenceObject->SetAttribute(attTypeActor); CKParameterOut* actorAttribute = referenceObject->GetAttributeParameter(attTypeActor); //---------------------------------------------------------------- // // Common Settings // CKParameterOut *parBCommon = GetParameterFromStruct(actorAttribute,PS_COMMON_SETTINGS); if (parBCommon) { SetParameterStructureValue<int>(parBCommon,PS_BC_HULL_TYPE,oDescr->hullType); SetParameterStructureValue<int>(parBCommon,PS_BC_FLAGS,oDescr->flags); SetParameterStructureValue<float>(parBCommon,PS_BC_DENSITY,oDescr->density); SetParameterStructureValue<CK_ID>(parBCommon,PS_BC_WORLD,oDescr->worlReference); } //---------------------------------------------------------------- // // Collision Setting // CKParameterOut *parBCollision = GetParameterFromStruct(actorAttribute,PS_COLLISION_SETTINGS); CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); if (parBCollision) { SetParameterStructureValue<int>(parBCollision,PS_BC_GROUP,oDescr->collisionGroup); SetParameterStructureValue<float>(parBCollision,PS_BC_SKINWITDH,oDescr->skinWidth); if (parGroupsMask) { SetParameterStructureValue<int>(parGroupsMask,0,oDescr->groupsMask.bits0); SetParameterStructureValue<int>(parGroupsMask,1,oDescr->groupsMask.bits1); SetParameterStructureValue<int>(parGroupsMask,2,oDescr->groupsMask.bits2); SetParameterStructureValue<int>(parGroupsMask,3,oDescr->groupsMask.bits3); } } //---------------------------------------------------------------- // // Optimization // if (oDescr->mask & OD_Optimization) { if (referenceObject->HasAttribute(attTypeOptimization)) { referenceObject->RemoveAttribute(attTypeOptimization); } referenceObject->SetAttribute(attTypeOptimization); CKParameterOut *parBOptimization = referenceObject->GetAttributeParameter(attTypeOptimization); if (parBOptimization) { SetParameterStructureValue<int>(parBOptimization,PS_BO_LOCKS,oDescr->optimization.transformationFlags); SetParameterStructureValue<int>(parBOptimization,PS_BO_SOLVER_ITERATIONS,oDescr->optimization.solverIterations); SetParameterStructureValue<int>(parBOptimization,PS_BO_DOMINANCE_GROUP,oDescr->optimization.dominanceGroup); SetParameterStructureValue<int>(parBOptimization,PS_BO_COMPARTMENT_ID,oDescr->optimization.compartmentGroup); } //---------------------------------------------------------------- // // sleeping // CKParameterOut *parBSleeping = GetParameterFromStruct(parBOptimization,PS_BO_SLEEPING); if (parBSleeping) { SetParameterStructureValue<float>(parBSleeping,PS_BS_ANGULAR_SLEEP,oDescr->optimization.angSleepVelocity); SetParameterStructureValue<float>(parBSleeping,PS_BS_LINEAR_SLEEP,oDescr->optimization.linSleepVelocity); SetParameterStructureValue<float>(parBSleeping,PS_BS_THRESHOLD,oDescr->optimization.sleepEnergyThreshold); } //---------------------------------------------------------------- // // damping // CKParameterOut *parBDamping = GetParameterFromStruct(parBOptimization,PS_BO_DAMPING); if (parBDamping) { SetParameterStructureValue<float>(parBDamping,PS_BD_ANGULAR,oDescr->optimization.angDamping); SetParameterStructureValue<float>(parBDamping,PS_BD_LINEAR,oDescr->optimization.linDamping); } } //---------------------------------------------------------------- // // CCD // if (oDescr->mask & OD_CCD ) { if (referenceObject->HasAttribute(attTypeCCD)) { referenceObject->RemoveAttribute(attTypeCCD); } referenceObject->SetAttribute(attTypeCCD); CKParameterOut *parBCCD = referenceObject->GetAttributeParameter(attTypeCCD); if (parBCCD) { SetParameterStructureValue<float>(parBCCD,PS_B_CCD_MOTION_THRESHOLD,oDescr->ccd.motionThresold); SetParameterStructureValue<int>(parBCCD,PS_B_CCD_FLAGS,oDescr->ccd.flags); SetParameterStructureValue<float>(parBCCD,PS_B_CCD_SCALE,oDescr->ccd.scale); SetParameterStructureValue<CK_ID>(parBCCD,PS_B_CCD_MESH_REFERENCE,oDescr->ccd.meshReference); } } //---------------------------------------------------------------- // // Material // if (oDescr->mask & OD_Material ) { if (referenceObject->HasAttribute(attTypeMaterial)) { referenceObject->RemoveAttribute(attTypeMaterial); } referenceObject->SetAttribute(attTypeMaterial); CKParameterOut *parBMaterial = referenceObject->GetAttributeParameter(attTypeMaterial); if (parBMaterial) { pFactory::Instance()->copyTo(parBMaterial,oDescr->material); } } } void pRigidBody::updateOptimizationSettings(pOptimization optimization) { lockTransformation(optimization.transformationFlags); setSolverIterationCount(optimization.solverIterations); getActor()->setDominanceGroup(optimization.dominanceGroup); setAngularDamping(optimization.angDamping); setLinearDamping(optimization.linDamping); setSleepAngularVelocity(optimization.angSleepVelocity); setSleepLinearVelocity(optimization.linSleepVelocity); setSleepEnergyThreshold(optimization.sleepEnergyThreshold); } void pRigidBody::setSleepAngularVelocity(float threshold) { getActor()->setSleepAngularVelocity(threshold); } void pRigidBody::setSleepLinearVelocity(float threshold) { getActor()->setSleepLinearVelocity(threshold); } void pRigidBody::setSleepEnergyThreshold(float threshold) { getActor()->setSleepEnergyThreshold(threshold); } void pRigidBody::setDominanceGroup(int dominanceGroup) { getActor()->setDominanceGroup(dominanceGroup); } void pRigidBody::setSolverIterationCount(int count) { if (getActor()) { if (count > 0) { getActor()->setSolverIterationCount(count); } } } void pRigidBody::checkForOptimization() { int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); CK3dEntity *ent = (CK3dEntity*)ctx()->GetObject(mEntID); if ( !ent ) return; if (!ent->HasAttribute(att)) return; CKParameterOut *optPar = ent->GetAttributeParameter(att); if(!optPar) return; using namespace vtTools::ParameterTools; using namespace vtTools::AttributeTools; ////////////////////////////////////////////////////////////////////////// // // Lock transformation degrees : // int transformationlockFlags = GetValueFromAttribute<int>(ent,att,PS_BO_LOCKS); lockTransformation(transformationlockFlags); ////////////////////////////////////////////////////////////////////////// // // Damping // CKParameterOut * dampPar= GetParameterFromStruct(optPar,PS_BO_DAMPING); float linDamp = GetValueFromParameterStruct<float>(dampPar,PS_BD_LINEAR); float angDamp = GetValueFromParameterStruct<float>(dampPar,PS_BD_ANGULAR); if ( linDamp !=0.0f) setLinearDamping(linDamp); if ( angDamp!=0.0f) setAngularDamping(angDamp); /////////////////////////////////////////////////////////////////////////// // // Sleeping Settings // CKParameterOut * sleepPar= GetParameterFromStruct(optPar,PS_BO_SLEEPING); float linSleep = GetValueFromParameterStruct<float>(dampPar,PS_BS_LINEAR_SLEEP); ////////////////////////////////////////////////////////////////////////// // // Solver Iterations // //CKParameterOut * sleepPar= GetParameterFromStruct(optPar,); int solverIterations = GetValueFromParameterStruct<float>(optPar,PS_BO_SOLVER_ITERATIONS); if (solverIterations !=0) { setSolverIterationCount(solverIterations); } ////////////////////////////////////////////////////////////////////////// // // Dominance // int dGroup = GetValueFromParameterStruct<int>(optPar,PS_BO_DOMINANCE_GROUP); if (dGroup!=0) { getActor()->setDominanceGroup(dGroup); } } void pRigidBody::checkDataFlags() { using namespace vtTools::AttributeTools; int att = GetPMan()->GetPAttribute(); int att_damping = GetPMan()->att_damping; int att_ss = GetPMan()->att_sleep_settings; int att_surface =GetPMan()->att_surface_props; int att_deformable =GetPMan()->att_deformable; xBitSet& dFlags = getDataFlags(); CK3dEntity *ent = GetVT3DObject(); if (!ent) { return; } if (ent->HasAttribute(att_surface)) enableFlag(dFlags,EDF_MATERIAL_PARAMETER); else disableFlag(dFlags,EDF_MATERIAL_PARAMETER); if (ent->HasAttribute(att_damping)) enableFlag(dFlags,EDF_DAMPING_PARAMETER); else disableFlag(dFlags,EDF_DAMPING_PARAMETER); if (ent->HasAttribute(att_ss)) enableFlag(dFlags,EDF_SLEEPING_PARAMETER); else disableFlag(dFlags,EDF_SLEEPING_PARAMETER); if (ent->HasAttribute(att_deformable)) enableFlag(dFlags,EDF_DEFORMABLE_PARAMETER); else disableFlag(dFlags,EDF_DEFORMABLE_PARAMETER); if (ent->HasAttribute( GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION) )) enableFlag(dFlags,EDF_OPTIMIZATION_PARAMETER); else disableFlag(dFlags,EDF_OPTIMIZATION_PARAMETER); } void pRigidBody::destroy() { if(!getActor()) return; NxU32 nbShapes = getActor()->getNbShapes(); /* CKSTRING name = GetVT3DObject()->GetName(); while(nbShapes ) { NxShape *s = ((NxShape **)getActor()->getShapes())[0]; pSubMeshInfo *sinfo = static_cast<pSubMeshInfo*>(s->userData); ////////////////////////////////////////////////////////////////////////// // Wheel attached ! if (sinfo && s->isWheel() && sinfo->wheel ) { pWheel2 *wheel = (pWheel2*)sinfo->wheel; delete wheel; wheel = NULL; sinfo->wheel =NULL; } if (sinfo) { delete sinfo; sinfo = NULL; } s->userData = NULL; if (getActor()->isDynamic() || ( !getActor()->isDynamic() && nbShapes >1 ) ) { getActor()->releaseShape(*s); s=NULL; destroy(); }break; } */ /************************************************************************/ /* */ /************************************************************************/ pVehicle *v = getVehicle(); if ( v ) { getVehicle()->getWheels().clear(); getVehicle()->setActor(NULL); getVehicle()->setBody(NULL); delete v; setVehicle(NULL); } pCloth *cloth = getCloth(); if (cloth) { cloth->releaseReceiveBuffers(); getActor()->getScene().releaseCloth(*cloth->getCloth()); } getActor()->getScene().releaseActor(*getActor()); setActor(NULL); } int pRigidBody::getTransformationsLockFlags() { int result = 0 ; if (getActor()->readBodyFlag(NX_BF_FROZEN_POS_X))result|=NX_BF_FROZEN_POS_X; if (getActor()->readBodyFlag(NX_BF_FROZEN_POS_Y))result|=NX_BF_FROZEN_POS_Y; if (getActor()->readBodyFlag(NX_BF_FROZEN_POS_Z))result|=NX_BF_FROZEN_POS_Z; if (getActor()->readBodyFlag(NX_BF_FROZEN_ROT_X))result|=NX_BF_FROZEN_ROT_X; if (getActor()->readBodyFlag(NX_BF_FROZEN_ROT_Y))result|=NX_BF_FROZEN_ROT_Y; if (getActor()->readBodyFlag(NX_BF_FROZEN_ROT_Z))result|=NX_BF_FROZEN_ROT_Z; return result; } void pRigidBody::lockTransformation(int flags) { if (getActor() && getActor()->isDynamic()) { if (flags & NX_BF_FROZEN_POS_X) getActor()->raiseBodyFlag(NX_BF_FROZEN_POS_X); else getActor()->clearBodyFlag(NX_BF_FROZEN_POS_X); if (flags & NX_BF_FROZEN_POS_Y) getActor()->raiseBodyFlag(NX_BF_FROZEN_POS_Y); else getActor()->clearBodyFlag(NX_BF_FROZEN_POS_Y); if (flags & NX_BF_FROZEN_POS_Z) getActor()->raiseBodyFlag(NX_BF_FROZEN_POS_Z); else getActor()->clearBodyFlag(NX_BF_FROZEN_POS_Z); if (flags & NX_BF_FROZEN_ROT_X) getActor()->raiseBodyFlag(NX_BF_FROZEN_ROT_X); else getActor()->clearBodyFlag(NX_BF_FROZEN_ROT_X); if (flags & NX_BF_FROZEN_ROT_Y) getActor()->raiseBodyFlag(NX_BF_FROZEN_ROT_Y); else getActor()->clearBodyFlag(NX_BF_FROZEN_ROT_Y); if (flags & NX_BF_FROZEN_ROT_Z) getActor()->raiseBodyFlag(NX_BF_FROZEN_ROT_Z); else getActor()->clearBodyFlag(NX_BF_FROZEN_ROT_Z); } } bool pRigidBody::isSleeping()const { if (getActor()) { return getActor()->isSleeping(); } return true; } void pRigidBody::setSleeping(bool sleeping) { if (getActor()) { if (sleeping) { getActor()->putToSleep(); }else{ getActor()->wakeUp(); } } } void pRigidBody::enableGravity(bool enable) { if (getActor()) { if (!enable) { getActor()->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); }else{ getActor()->clearBodyFlag(NX_BF_DISABLE_GRAVITY); } } } bool pRigidBody::isAffectedByGravity()const { if (getActor()) { return !getActor()->readBodyFlag(NX_BF_DISABLE_GRAVITY); } return false; } void pRigidBody::setKinematic(bool enabled) { if (getActor()) { if (enabled) getActor()->raiseBodyFlag(NX_BF_KINEMATIC); else getActor()->clearBodyFlag(NX_BF_KINEMATIC); } } bool pRigidBody::isKinematic()const { if (getActor()) { return getActor()->readBodyFlag(NX_BF_KINEMATIC); } return false; } bool pRigidBody::isValid()const { return GetPMan()->GetContext()->GetObject(getEntID()) ? true : false && getActor() ? true : false; } int pRigidBody::getHullType(){ return m_HullType;} void pRigidBody::setHullType(int _type){ m_HullType= _type;} void pRigidBody::recalculateFlags(int _flags) { if (!isValid()) { return; } int current = m_sFlags; if (getActor()->isDynamic() && !getActor()->readBodyFlag(NX_BF_DISABLE_GRAVITY)) { current |=BF_Gravity; } if (!getActor()->readActorFlag(NX_AF_DISABLE_COLLISION)) { current |=BF_Collision; } if (getActor()->isSleeping()) { current |=BF_Sleep; } if (getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) { current |=BF_CollisionNotify; } if (isKinematic()) { current |=BF_Kinematic; } m_sFlags = current; } void pRigidBody::updateFlags( int _flags,CK3dEntity*shapeReference/*=NULL*/ ) { if (!isValid())return; setKinematic(_flags & BF_Kinematic); enableCollision(_flags & BF_Collision,shapeReference); enableCollisionsNotify(_flags & BF_CollisionNotify); enableGravity(_flags & BF_Gravity); setSleeping(_flags & BF_Sleep); enableTriggerShape(_flags & BF_TriggerShape,shapeReference); m_sFlags |=_flags; } int pRigidBody::getFlags(){ return m_sFlags;; } void pRigidBody::setFlags(int _flags){ m_sFlags = _flags;} void pRigidBody::retrieveSettingsFromAttribute() { assert(getWorld()); assert(getWorld()->getScene()); assert(getWorld()->getReference()); assert(GetVT3DObject()); using namespace vtTools::AttributeTools; setDataFlags(0x000); int att = GetPMan()->GetPAttribute(); //---------------------------------------------------------------- // // Old version // CK_ID id = getWorld()->getReference()->GetID(); SetAttributeValue<CK_ID>(GetVT3DObject(),att,E_PPS_WORLD,&id); setHullType(GetValueFromAttribute<int>(GetVT3DObject(),att,E_PPS_HULLTYPE)); //Sets some flags like movable , etc... setFlags(GetValueFromAttribute<int>(GetVT3DObject(),att,E_PPS_BODY_FLAGS)); setDensity(GetValueFromAttribute<float>(GetVT3DObject(),att, E_PPS_DENSITY)); setMassOffset(GetValueFromAttribute<VxVector>(GetVT3DObject(),att, E_PPS_MASS_OFFSET)); setPivotOffset(GetValueFromAttribute<VxVector>(GetVT3DObject(),att, E_PPS_SHAPE_OFFSET)); setSkinWidth(GetValueFromAttribute<float>(GetVT3DObject(),att, E_PPS_SKIN_WIDTH)); } int pRigidBody::isBodyFlagOn(int flags) { if (getActor() && getActor()->isDynamic()) { return getActor()->readBodyFlag((NxBodyFlag)flags); } return -1; } void pRigidBody::wakeUp(float wakeCounterValue/* =NX_SLEEP_INTERVAL */) { getActor()->wakeUp(wakeCounterValue); } <file_sep>copy X:\ProjectRoot\svn\local\vtPhysX\Doc\examples\*.cmo X:\ProjectRoot\svn\local\vtPhysX\Doc\doxyOutput\html /y copy .\doxyOutput\vtPhysX.CHM x:\ProjectRoot\vdev\Documentation\ copy .\doxyOutput\vtPhysX.chi x:\ProjectRoot\vdev\Documentation\ doxygen DoxyfileGraphs.dox cd doxyOutput vtPhysX.chm REM copy X:\ProjectRoot\vdev\Documentation\vtAgeia.CHM X:\ProjectRoot\vtmod_vtAgeia\Doc /y REM copy X:\ProjectRoot\vdev\Documentation\vtAgeia.CHM X:\ProjectRoot\vtmodsvn\Plugins\vtAgeia\Documentation /y <file_sep>/* ***************************************************************** * Copyright © ITI Scotland 2006 *---------------------------------------------------------------- * Module : $File: //depot/ITITM005/Code/GBLCommon/Managers/Include/GBLTools.h $ * * Programmer : $Author: sylvain.le.breton $ * Date : $DateTime: 2006/06/12 18:38:19 $ * *---------------------------------------------------------------- * * Module Summary : Generic Tools for GBL. * Parts : + structures + typedefs + Enums + tools for CKParameter + tools for CKBehavior *---------------------------------------------------------------- * $Revision: #7 $ * $Change: 23589 $ ***************************************************************** */ #ifndef __VT_TOOLS_H #define __VT_TOOLS_H #include "CKAll.h" namespace vtTools { /*************************************************************************/ /* common enumerations */ /* */ namespace Enums { /* Represents a virtools super type. See GetVirtoolsSuperType. */ enum SuperType { vtSTRING = 1, vtFLOAT = 2, vtINTEGER = 3, vtVECTOR = 4, vtVECTOR2D = 5, vtCOLOUR = 6, vtMATRIX = 7, vtQUATERNION = 8, vtRECTANGLE = 9, vtBOX = 10, vtBOOL = 11, vtENUMERATION = 12, vtFLAGS = 13, vtFile = 14, vtOBJECT = 16, vtUNKNOWN = 17 }; /* Author: gunther.baumgart Represents the c++ equivalent for TGBLWidgetType pm->RegisterNewEnum(EVTWIDGETTYPE,"EVTWidgetType", "StaticText=1, TextEdit=2, CheckButton=4, PushButton=8, ListBox=16, ComboBox=32, FileSelector=64, ColorSelector=128" ); */ enum EVTWidgetType { EVT_WIDGET_STATIC_TEXT = 1, EVT_WIDGET_EDIT_TEXT =2, EVT_WIDGET_CHECK_BUTTON =3, EVT_WIDGET_LIST_BOX =5, EVT_WIDGET_COMBO_BOX =6, EVT_WIDGET_FILE_SELECTION =7, EVT_WIDGET_COLOR_SELECTION =8 }; /* */ }/* end namespace typedefs */ /*************************************************************************/ /* common Structs */ /* */ namespace Structs { ////////////////////////////////////////////////////////////////////////// /* ParameterInfo is used to describe a virtools parameter type. Example : Matrix = horizontalItems = 4, verticalItems = 4 memberType =vtFLOAT, superType= vtMATRIX */ struct ParameterInfo { int horizontalItems; int verticalItems; Enums::SuperType superType; Enums::SuperType memberType; }; ////////////////////////////////////////////////////////////////////////// /* SGBL_WidgetInfo describes an parameter for using GBLWidgets GBL-Widgets. */ struct WidgetInfo { struct WidgetInfoItem { Enums::SuperType baseType; Enums::EVTWidgetType widgetType; //with which widget XString value; XString label; }; XArray<WidgetInfoItem*>items; Structs::ParameterInfo parameterInfo; }; }/* end namespace Structs */ /************************************************************************/ /* parameter tools */ /* */ namespace ParameterTools { /* ******************************************************************* * Function: IsNumeric() * * Description : Check each character of the string If a character at a certain position is not a digit, then the string is not a valid natural number * Parameters : char*Str,r : the string to test * Returns : int * ******************************************************************* */ int IsNumeric(const char* Str,Enums::SuperType superType); /* ******************************************************************* * Function: GetParameterMemberInfo() * * Description : GetParameterMemberInfo returns the type super type of the used structure members. Example : vtVECTOR returns vtFLOAT * Parameters : CKContext* context, r : the virtools context. CKParameterType parameterType, r : the type to test. * Returns : CO_EVT_VirtoolsSuperType * ******************************************************************* */ Enums::SuperType GetParameterMemberInfo(CKContext* context,CKParameterType parameterType); /* ******************************************************************* * Function: GetParameterInfo() * * Description : GetParameterInfo returns an info about a virtools type. Example : Vector4D returns : result.horizontalItems = 4 ; result.verticalItems = 1 ; result.memberType = vtFLOAT result.superType = vtQUATERNION; * Parameters : CKContext* context, r : the virtools context. CKParameterType parameterType, r : the type to test. * Returns : ParameterInfo * ******************************************************************* */ Structs::ParameterInfo GetParameterInfo(CKContext* context,CKParameterType parameterType); /* ******************************************************************* * Function: CreateWidgetInfo() * * Description : CreateWidgetInfo returns an handy info about an parameter type and a given string value of this parameter. * Parameters : CKContext* context, r : the virtools context. CKParameterType parameterType, r : the type to test. XString stringValue,r : the string value of the given type. * Returns : WidgetInfo ******************************************************************* */ Structs::WidgetInfo* CreateWidgetInfo(CKContext* context,CKParameterType parameterType,XString stringValue); /* ******************************************************************* * Function: GetWidgetType() * * Description : GetWidgetType returns the type of the GBLWidget which should used for a specific virtools super type. Example : vtBOOL = CheckBox vtENUMERATION = ComboBox * * Parameters : CO_EVT_VirtoolsSuperType superType, r : the given virtools super type * Returns : EWidgetType * ******************************************************************* */ Enums::EVTWidgetType GetWidgetType(Enums::SuperType superType); /* ******************************************************************* * Function: TypeCheckedParameterCopy() * * Description : Copies the source parameter to a destination parameter. On a type mismatch * it tries to copy as string. This also works for nested virtools structures. See CO_EVT_VirtoolsSuperType for supported types. * * Parameters : CKParameter*dest,rw : the destination parameter CKParameter*src,r : the source parameter * Returns : bool = true if succesful. * todo:: return copied diff * ******************************************************************* */ int TypeCheckedParameterCopy( CKParameter*dest, CKParameter*src); /* ******************************************************************* * Function: GetParameterAsString() * * Description : Returns the string value a CKParameter. * * Parameters : CKParameter*src ,r the given parameter * Returns : CKSTRING * ******************************************************************* */ CKSTRING GetParameterAsString( CKParameter*src); /* ******************************************************************* * Function: CompareStringRep() * * Description : This function compares the string representation of the two CKParameters. * * Parameters : CKParameter* valueA,r : the first parameter CKParameter* valueB,r : the second parameter * Returns : int (like strcmp) * ******************************************************************* */ int CompareStringRep(CKParameter*valueA, CKParameter*valueB); /* ******************************************************************* * Function:GetVirtoolsSuperType() * * Description : GetVirtoolsSuperType returns the base type of a virtools parameter. This is very useful to determine whether a parameter can be used for network or a database. * * Parameters : CKContext *ctx, r : the virtools context CKGUID guid, r : the guid of the parameter * * Returns : CO_EVT_VirtoolsSuperType, * ******************************************************************* */ Enums::SuperType GetVirtoolsSuperType(CKContext *ctx,const CKGUID guid); /* ******************************************************************* * Function: TypeIsSerializable() * Description : Returns true if the given type can be stored as string. + It also checks custom virtools structures recursive. + it checks only * * Parameters : CKContext *ctx, r : the virtools context CKParameterType type, r : the type * Returns : bool * ******************************************************************* */ bool TypeIsSerializable(CKContext *ctx,CKParameterType type); /* ******************************************************************* * Function: IsValidStruct() * * Description : Like TypeIsSerializable, even checks a custom virtools structure, recursive. * * Parameters : CKContext *ctx,r : the virtools context CKGUID type,r : the type to check * Returns : bool * ******************************************************************* */ bool IsValidStruct(CKContext *ctx,CKGUID type); /* ******************************************************************* * Function:SetParameterStructureValue() * * Description : Sets a specific value in a custom structure. * * Parameters : CKParameter *par, r : the virtools virtools parameter const unsigned short StructurIndex, r : the index within the custom structure T value, r : the value. bool update,r : If this function is part of a virtools parameter operation, this should set to false, otherwise it is an infinity loop. * Returns : is a void * ******************************************************************* */ template<class T>void SetParameterStructureValue( CKParameter *par, const unsigned short StructurIndex, T value, bool update = TRUE ) { assert(par && StructurIndex>=0 ); CK_ID* paramids = (CK_ID*)par->GetReadDataPtr(update); CKParameterOut *pout = static_cast<CKParameterOut*>(par->GetCKContext()->GetObject(paramids[StructurIndex])); pout->SetValue(&value); } /* ******************************************************************* * Function:SetParameterStructureValue() * * Description : This is a template function specialization for CKSTRING. * Sets a specific value in a custom structure. * * Parameters : CKParameter *par, r : the virtools virtools parameter const unsigned short StructurIndex, r : the index within the custom structure T value, r : the value. bool update,r : If this function is part of a virtools parameter operation, this should set to false, otherwise it is an infinity loop. * Returns : is a void * ******************************************************************* */ template<>__inline void SetParameterStructureValue<CKSTRING> ( CKParameter *par, const unsigned short StructurIndex, CKSTRING value, bool update ) { assert(par && StructurIndex>=0 ); static_cast<CKParameterOut*>(par->GetCKContext()->GetObject( static_cast<CK_ID*>(par->GetReadDataPtr(update))[StructurIndex]))->SetStringValue(value); } /* ******************************************************************* * Function:GetValueFromParameterStruct() * * Description : returns a object from a custom structure. * * Parameters : CKParameter *par, r : the virtools virtools parameter const unsigned short StructurIndex, r : the index within the custom structures bool update,r : If this function is part of a virtools parameter operation, this should set to false, otherwise it is an infinity loop. * Returns : T. * ******************************************************************* */ template<class T>__inline T GetValueFromParameterStruct( CKParameter *par, const unsigned short StructurIndex, bool update) { T value; assert(par && value); CK_ID* paramids = static_cast<CK_ID*>(par->GetReadDataPtr(update)); CKParameterOut* pout = static_cast<CKParameterOut*>(par->GetCKContext()->GetObject(paramids[StructurIndex])); pout->GetValue(&value); return value; } /* ******************************************************************* * Function:GetValueFromParameterStruct() * * Description : This is a template function specialization for CKSTRING * Gets a specific value from custom structure. * * Parameters : CKParameter *par, r : the virtools virtools parameter const unsigned short StructurIndex, r : the index within the custom structures bool update,r : If this function is part of a virtools parameter operation, this should set to false, otherwise it is an infinity loop. * Returns : CKSTRING. * ******************************************************************* */ template<>__inline CKSTRING GetValueFromParameterStruct<CKSTRING>( CKParameter *par, const unsigned short StructurIndex, bool update) { assert( par && StructurIndex >=0 ); CK_ID* paramids = static_cast<CK_ID*>(par->GetReadDataPtr(update)); CKParameterOut* pout = static_cast<CKParameterOut*>(par->GetCKContext()->GetObject(paramids[StructurIndex])); CKSTRING stringValue = static_cast<CKSTRING>(pout->GetReadDataPtr(update)); return stringValue; } } /*end namespace virtools parameter tools */ /************************************************************************/ /* building block tools */ /* */ namespace BehaviorTools { /* ******************************************************************* * Function:GetInputParameterValue() * * Description : Returns an input parameter value. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : T * ******************************************************************* */ template<class T>__inline T GetInputParameterValue( CKBehavior *beh, const int pos) { assert(beh); T value ; beh->GetInputParameterValue(pos,&value); return value; } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : This is a template function specialization for CKSTRING. Returns an input parameter value. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKSTRING * ******************************************************************* */ template<>__inline CKSTRING GetInputParameterValue<CKSTRING>( CKBehavior *beh, const int pos) { assert(beh); return static_cast<CKSTRING>(beh->GetInputParameterReadDataPtr(pos)); } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<>__inline CKObject* GetInputParameterValue<CKObject*>( CKBehavior *beh, const int pos) { assert(beh); return beh->GetInputParameterObject(pos); } //todo : parametric log / debug forwarding!!! - > g.baumgart ! }/* end namespace behavior tools*/ /**************************************************************************/ /* attribute tools */ /* */ /* */ namespace AttributeTools { /* ****************************************************************** * Function:GetObjectFromAttribute() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<class T>__inline T* GetObjectFromAttribute(CKContext *ctx,CKObject *_e,const int attributeID,const int StructurIndex) { T *value; CKParameterOut* pout = _e->GetAttributeParameter(attributeID); CK_ID* paramids = (CK_ID*)pout->GetReadDataPtr(); pout = (CKParameterOut*)ctx->GetObject(paramids[StructurIndex]); value = (T*)ctx->GetObject(*(CK_ID*)pout->GetReadDataPtr()); return value ? value : NULL; } /* ****************************************************************** * Function:GetObjectFromAttribute() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<class T>__inline void SetAttributeValue(CKObject *_e,const int attributeID,const int StructurIndex,T* value) { CKParameterOut* pout = _e->GetAttributeParameter(attributeID); if(pout) { CK_ID* paramids = (CK_ID*)pout->GetReadDataPtr(); pout = (CKParameterOut*)_e->GetCKContext()->GetObject(paramids[StructurIndex]); if (pout) { pout->SetValue(&value); } } } /* ****************************************************************** * Function:GetObjectFromAttribute() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<class T>__inline T GetValueFromAttribute(CKBeObject *_e,int attributeID,int StructurIndex) { T value; CKParameterOut* pout = _e->GetAttributeParameter(attributeID); if (pout) { CK_ID* paramids = static_cast<CK_ID*>(pout->GetReadDataPtr()); pout = static_cast<CKParameterOut*>(_e->GetCKContext()->GetObject(paramids[StructurIndex])); if (pout) { pout->GetValue(&value); } } return value; } /* ****************************************************************** * Function:GetObjectFromAttribute() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<class T>__inline T GetValueFromAttribute(CKBeObject *_e,int attributeID) { T value; CKParameterOut* pout = _e->GetAttributeParameter(attributeID); if (pout) { pout->GetValue(&value); } return value; } }/* end namespace attribute tools*/ } #endif <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" CKObjectDeclaration *FillBehaviorDOControlDecl(); CKERROR CreateDOControlProto(CKBehaviorPrototype **); int DOControl(const CKBehaviorContext& behcontext); CKERROR DOControlCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorDOControlDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DOControl"); od->SetDescription("Creates an distributed object"); od->SetCategory("TNL/Distributed Objects"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x59f62787,0x78a73262)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDOControlProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateDOControlProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("DOControl"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Exit In"); proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Object", CKPGUID_BEOBJECT, "test"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareSetting("Timeout", CKPGUID_TIME, "0"); proto->DeclareLocalParameter("elapsed time", CKPGUID_FLOAT, "0.0f"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(DOControl); proto->SetBehaviorCallbackFct(DOControlCB); *pproto = proto; return CK_OK; } int DOControl(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; ////////////////////////////////////////////////////////////////////////// //connection id : int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *obj= (CK3dEntity*)beh->GetInputParameterObject(1); if (!obj) { beh->ActivateOutput(2); return 0; } ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { CKParameterOut *pout = beh->GetOutputParameter(0); XString errorMesg("distributed object creation failed,no network connection !"); pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(2); return 0; } IDistributedObjects*doInterface = cin->getDistObjectInterface(); xDistributedObject *dobj = doInterface->getByEntityID(obj->GetID()); if (!dobj) { CKParameterOut *pout = beh->GetOutputParameter(0); XString errorMesg("There is no such an object"); pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(2); return 0; } ////////////////////////////////////////////////////////////////////////// //we come in by input 0 : if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); //reset elapsed time : float elapsedTime = 0.0f; beh->SetLocalParameterValue(1,&elapsedTime); if (!dobj->isOwner() /*&& !dobj->getOwnershipState().test(E_DO_OS_REQUEST) */) { dobj->getOwnershipState().set( 1<< E_DO_OS_REQUEST,true ); if (cin->isValid()) { cin->getConnection()->c2sDORequestOwnerShip(cin->getConnection()->getUserID(),dobj->getServerID()); } beh->ActivateOutput(0); } return CKBR_ACTIVATENEXTFRAME; } ////////////////////////////////////////////////////////////////////////// //we come in by loop : if ( dobj->getOwnershipState().test(E_DO_OS_REQUEST) ) { //we requested a dist object already, check the its timeout : float elapsedTime = 0.0f; beh->GetLocalParameterValue(1,&elapsedTime); //pickup creations timeout settings : float timeOut=0.0f; beh->GetLocalParameterValue(0,&timeOut); ////////////////////////////////////////////////////////////////////////// //timeout reached : reset everything back if (elapsedTime > timeOut) { //reset output server id : int ids = -1; beh->SetOutputParameterValue(0,&ids); //output an error string : CKParameterOut *pout = beh->GetOutputParameter(1); XString errorMesg("Ownership request failed,timeout"); pout->SetStringValue(errorMesg.Str()); //finish, activate error output trigger: beh->ActivateOutput(2); return 0; } float dt = ctx->GetTimeManager()->GetLastDeltaTime(); elapsedTime+=dt; beh->SetLocalParameterValue(1,&elapsedTime); ////////////////////////////////////////////////////////////////////////// //we are within the timeout range, check we have a successfully created object by the server : //we are owner now ? if ( dobj->getOwnershipState().test(1<<E_DO_OS_REQUEST) && dobj->getOwnershipState().test(1<<E_DO_OS_OWNERCHANGED) && dobj->isOwner() ) { //xLogger::xLog(ELOGINFO,XL_START,"Got ownership"); //clear the change bit : //dobj->getOwnershipState().set( 1<<E_DO_OS_OWNERCHANGED ,false ); //clear in-request bit : dobj->getOwnershipState().set( 1<< E_DO_OS_REQUEST,false); beh->ActivateOutput(1); return 0; } } return CKBR_ACTIVATENEXTFRAME; } CKERROR DOControlCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>// -------------------------------------------------------------------------- // www.UnitedBusinessTechnologies.com // Copyright (c) 1998 - 2002 All Rights Reserved. // // Source in this file is released to the public under the following license: // -------------------------------------------------------------------------- // This toolkit may be used free of charge for any purpose including corporate // and academic use. For profit, and Non-Profit uses are permitted. // // This source code and any work derived from this source code must retain // this copyright at the top of each source file. // // UBT welcomes any suggestions, improvements or new platform ports. // email to: <EMAIL> // -------------------------------------------------------------------------- #include "pch.h" #include "GStringList.h" #include "GString.h" #include <stdio.h> #include <string.h> // for: strlen(), strstr() #include "GProfile.h" const char *GStringList::PeekLast() { m_strSerializeDest = ""; GString *pG = (GString *)GList::Last(); if (pG) m_strSerializeDest = (const char *)*pG; return m_strSerializeDest; } const char *GStringList::PeekFirst() { m_strSerializeDest = ""; GString *pG = (GString *)GList::First(); if (pG) m_strSerializeDest = (const char *)*pG; return m_strSerializeDest; } const char *GStringList::RemoveFirst() { m_strSerializeDest = ""; GString *pG = (GString *)GList::First(); if (pG) { GList::RemoveFirst(); m_strSerializeDest = (const char *)*pG; delete pG; } return m_strSerializeDest; } const char *GStringList::RemoveLast() { m_strSerializeDest = ""; GString *pG = (GString *)GList::RemoveLast(); if (pG) { m_strSerializeDest = (const char *)*pG; delete pG; } return m_strSerializeDest; } GString *GStringList::AddFirst(const char *szString) { GString *pstrString = new GString(szString); GList::AddHead(pstrString); return pstrString; } GString *GStringList::AddLast(const char *szString) { GString *pstrString = new GString(szString); GList::AddLast(pstrString); return pstrString; } GStringList::GStringList(const GStringList &src) { GStringIterator it(&src); while (it()) AddLast(it++); } GStringList::GStringList() { } void GStringList::operator+=(const GStringList &src) { GStringIterator it(&src); while (it()) AddLast(it++); } void GStringList::operator+=(const char *szSrc) { AddLast(szSrc); } void GStringList::RemoveAll() { int n = Size(); for(int i=0; i<n;i++) delete (GString *)RemoveLast(); } GStringList::~GStringList() { while (FirstNode) { if (CurrentNode == FirstNode) CurrentNode = FirstNode->NextNode; if (LastNode == FirstNode) LastNode = 0; Node *Save = FirstNode->NextNode; delete (GString *)FirstNode->Data; delete FirstNode; FirstNode = Save; iSize--; } } void GStringIterator::reset() { pDataNode = (GStringList::Node *)((GStringList *)pTList)->FirstNode; } GStringIterator::GStringIterator(const GStringList *pList) { pTList = (GStringList *)pList; pDataNode = (GStringList::Node *)((GStringList *)pList)->FirstNode; } const char *GStringIterator::operator ++ (int) { GString *pRet = (GString *)pDataNode->Data; pCurrentNode = pDataNode; pDataNode = pDataNode->NextNode; return pRet->StrVal(); } int GStringIterator::operator () (void) const { return pDataNode != 0; } const char *GStringList::Serialize(const char *pzDelimiter) { m_strSerializeDest = ""; GStringIterator it(this); int nCount = 0; while (it()) { if (nCount) m_strSerializeDest += pzDelimiter; nCount++; m_strSerializeDest += it++; } return m_strSerializeDest; } GStringList::GStringList(const char *pzDelimiter, const char *pzSource) { DeSerialize(pzDelimiter, pzSource); } void GStringList::DeSerialize(const char *pzDelimiter, const char *pzSource) { if (!pzDelimiter || !pzSource || !pzDelimiter[0] || !pzSource[0]) return; int nSourceLen = strlen(pzSource); int nDelimiterLen = strlen(pzDelimiter); if (!nSourceLen) return; char *beg = (char *)pzSource; char *del = strstr(beg,pzDelimiter); while(1) { if ( !del ) { // there is only one entry in the list AddLast(beg); break; } // temporarily null on the delimiter char chOld = *del; *del = 0; // add this (now null terminated) entry AddLast(beg); // advance to the next string beg = del + nDelimiterLen; // unnull the previous *del = chOld; // advance to the next delimiter, break if none del = strstr(beg,pzDelimiter); if ( !del ) { AddLast(beg); break; } } } <file_sep>#include "StdAfx2.h" #include "PCommonDialog.h" #include "PBodySetup.h" #include "..\..\include\interface\pbodysetup.h" #define LAYOUT_STYLE (WS_CHILD|WS_VISIBLE) #define LAYOUT_ShaderREE 130 int CPBodyCfg::OnSelect(int before/* =-1 */) { return -1; } CParameterDialog* CPBodyCfg::refresh(CKParameter*src) { return this; } void CPBodyCfg::fillFlags() { BF_Move.SetCheck(true); } void CPBodyCfg::fillHullType() { HType.AddString("Sphere"); HType.AddString("Box"); HType.AddString("Capsule"); HType.AddString("Plane"); HType.AddString("Convex Mesh"); HType.AddString("Height Field"); HType.AddString("Wheel"); HType.AddString("Cloth"); HType.SetCurSel(0); } void CPBodyCfg::initSplitter() { //[...] //optional pre initialization steps //int opt = mTestViControl.Create(WS_CHILD|WS_VISIBLE,r,pWnd,IDC_TRACKTEST); /*if (opt) {*/ // mTestViControl.SetColors(CZC_176,CZC_BLACK,CZC_176,CZC_WHITE,CZC_128,CZC_200); /* mTestViControl.SetFont(GetVIFont(VIFONT_NORMAL),FALSE); mTestViControl.SetItemHeight(18);*/ //mTestViControl.SetWindowText("Shader Tree"); // mTestViControl.SetStyle(NTVS_DRAWHSEPARATOR); // mTestViControl.SetPreAllocSize(2); // Create columns // mTestViControl.SetColumnCount(1); //mTestViControl.SetColumn(0, "Shader", 0, 10); //HTREEITEM newItem = mTestViControl.InsertItem("asddad", 0,0, mTestViControl.GetFirstVisibleItem() ); // newItem->Flags = NTVI_EDITABLE; // newItem->Data = NULL; /*HNTVITEM newItem; newItem = mTestViControl.InsertItem("asddad", (HNTVITEM)NULL, TRUE); newItem->Flags = NTVI_EDITABLE; newItem->Data = NULL;*/ //} } void CPBodyCfg::Init(CParameterDialog *parent) { mParent = parent; } CPBodyCfg::~CPBodyCfg() { _destroy(); } void CPBodyCfg::_destroy() { //::CPSharedBase::_destroy(); } //CPSharedBase(this,Parameter) CPBodyCfg::CPBodyCfg(CKParameter* Parameter,CK_CLASSID Cid) :CParameterDialog(Parameter,Cid) { setEditedParameter(Parameter); //int snow = getNbDialogs(); } LRESULT CPBodyCfg::OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam) { WORD keyState = 0; keyState |= (::GetKeyState(VK_CONTROL) < 0) ? MK_CONTROL : 0; keyState |= (::GetKeyState(VK_SHIFT) < 0) ? MK_SHIFT : 0; LRESULT lResult; HWND hwFocus = ::GetFocus(); const HWND hwDesktop = ::GetDesktopWindow(); if (hwFocus == NULL) lResult = SendMessage(WM_MOUSEWHEEL, (wParam << 16) | keyState, lParam); else { do { lResult = ::SendMessage(hwFocus, WM_MOUSEWHEEL,(wParam << 16) | keyState, lParam); hwFocus = ::GetParent(hwFocus); } while (lResult == 0 && hwFocus != NULL && hwFocus != hwDesktop); } return lResult; } LRESULT CPBodyCfg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { /* case WM_MOUSEWHEEL: { int cStates = GET_KEYSTATE_WPARAM(wParam); int wheelDirection = GET_WHEEL_DELTA_WPARAM(wParam); if (wheelDirection>0) { if ( mTestViControl.GetActiveTabIndex() +1 < mTestViControl.GetTabCount() ) { mTestViControl.SetActiveTab(mTestViControl.GetActiveTabIndex() +1 ); }else{ mTestViControl.SetActiveTab( 0 ); } }else { if ( mTestViControl.GetActiveTabIndex() -1 >=0 ) { mTestViControl.SetActiveTab(mTestViControl.GetActiveTabIndex() - 1 ); }else{ mTestViControl.SetActiveTab(mTestViControl.GetTabCount()); } } break; return NULL; } */ case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: { int indexTabUnderMouse = 0; indexTabUnderMouse = mTestViControl.GetTabUnderMouse(); if (indexTabUnderMouse >=0 ) { mTestViControl.SetActiveTab(indexTabUnderMouse); } //HTREEITEM newItem = mTestViControl.InsertItem("asddad2323",mTestViControl.GetFirstVisibleItem(), mTestViControl.GetFirstVisibleItem() ); /*HTREEITEM newItem; newItem = mTestViControl.InsertItem("asddad", (HTREEITEM)NULL, NULL); */ /* HNTVITEM newItem; newItem = mTestViControl.InsertItem("asddad", (HNTVITEM)NULL, TRUE); newItem->Flags = NTVI_EDITABLE; newItem->Data = NULL; */ /* mTestViControl.UpdateWindow(); mTestViControl.ShowWindow(1); */ /* mTestViControl.AddItem("asdasd",NULL); int a = mTestViControl.GetSubItemCount(0);*/ /* RECT r; GetClientRect(&r); CDC* pDC=CDC::FromHandle((HDC)wParam); pDC->FillSolidRect(&r,RGB(100,200,200));*/ break; } case WM_ERASEBKGND: { /*RECT r; GetClientRect(&r); CDC* pDC=CDC::FromHandle((HDC)wParam); pDC->FillSolidRect(&r,RGB(200,200,200)); return 1;*/ }break; case CKWM_OK: { //CEdit *valueText = (CEdit*)GetDlgItem(IDC_EDIT); /*CString l_strValue; valueText->GetWindowText(l_strValue); double d; if (sscanf(l_strValue,"%Lf",&d)) { parameter->SetValue(&d); }*/ } break; case CKWM_INIT: { RECT r; GetClientRect(&r); /* CDC* pDC=CDC::FromHandle((HDC)wParam);*/ //initSplitter(); fillHullType(); char temp[64]; double d; } break; } return CDialog::WindowProc(message, wParam, lParam); } void CPBodyCfg::DoDataExchange(CDataExchange* pDX) { //CDialog::DoDataExchange(pDX); CParameterDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPBodyCfg) DDX_Control(pDX, IDC_HULLTYPE, HType); DDX_Control(pDX, IDC_LBL_HTYPE, LBL_HType); DDX_Control(pDX, IDC_BFLAGS_MOVING,BF_Move); DDX_Control(pDX, IDC_BFLAGS_GRAV,BF_Grav); DDX_Control(pDX, IDC_BFLAGS_COLL,BF_Collision); DDX_Control(pDX, IDC_BFLAGS_COLL_NOTIFY,BF_CollisionNotify); DDX_Control(pDX, IDC_BFLAGS_KINEMATIC,BF_Kinematic); DDX_Control(pDX, IDC_BFLAGS_TRIGGER,BF_TriggerShape); DDX_Control(pDX, IDC_BFLAGS_SLEEP,BF_Sleep); DDX_Control(pDX, IDC_BFLAGS_SSHAPE,BF_SubShape); DDX_Control(pDX, IDC_BFLAGS_HIERARCHY,BF_Hierarchy); DDX_Control(pDX, IDC_BFLAGS_DEFORMABLE,BF_Deformable); DDX_Control(pDX, IDC_FLAGS_BG,BF_BG_Rect); DDX_Control(pDX, IDC_LBL_FLAGS,LBL_Flags); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPBodyCfg, CParameterDialog) ON_WM_MOUSEMOVE() ON_STN_CLICKED(IDC_LBL_FLAGS, OnStnClickedLblFlags) ON_STN_CLICKED(IDC_DYNA_FLAGS_RECT, OnStnClickedDynaFlagsRect) END_MESSAGE_MAP() void CPBodyCfg::OnStnClickedLblFlags() { // TODO: Add your control notification handler code here } void CPBodyCfg::OnStnClickedDynaFlagsRect() { // TODO: Add your control notification handler code here } <file_sep>#include <StdAfx.h> #include "pCommon.h" #include "IParameter.h" CKObjectDeclaration *FillBehaviorPBAddShapeExDecl(); CKERROR CreatePBAddShapeExProto(CKBehaviorPrototype **pproto); int PBAddShapeEx(const CKBehaviorContext& behcontext); CKERROR PBAddShapeExCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_BodyRef, bbI_HullType, bbI_Flags, bbI_Pivot, bbI_Mass, bbI_Collision, bbI_CCD, bbI_Material, bbI_Capsule, bbI_CCylinder, bbI_Wheel, }; #define BB_SSTART 3 #define gPIMAP pInMap2322 BBParameter pInMap2322[] = { BB_PIN(bbI_BodyRef,CKPGUID_3DENTITY,"Body Reference",""), BB_PIN(bbI_HullType,VTE_COLLIDER_TYPE,"Hull Type","Sphere"), BB_PIN(bbI_Flags,VTF_BODY_FLAGS,"Flags","Collision,Sub Shape"), BB_SPIN(bbI_Pivot,VTS_PHYSIC_PIVOT_OFFSET,"Pivot",""), BB_SPIN(bbI_Mass,VTS_PHYSIC_MASS_SETUP,"Mass",""), BB_SPIN(bbI_Collision,VTS_PHYSIC_COLLISIONS_SETTINGS,"Collision","All,0,0.025f"), BB_SPIN(bbI_CCD,VTS_PHYSIC_CCD_SETTINGS,"CCD",""), BB_SPIN(bbI_Material,VTS_MATERIAL,"Material",""), BB_SPIN(bbI_Capsule,VTS_CAPSULE_SETTINGS_EX,"Capsule Settings",""), BB_SPIN(bbI_CCylinder,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,"Convex Cylinder Settings",""), BB_SPIN(bbI_Wheel,VTS_PHYSIC_WHEEL_DESCR,"Wheel Settings",""), }; CKObjectDeclaration *FillBehaviorPBAddShapeExDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddShapeEx"); od->SetCategory("Physic/Body"); od->SetDescription("Adds an entity to the physic engine."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0xd8e2970,0x1efe7f65)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBAddShapeExProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBAddShapeExProto // FullName: CreatePBAddShapeExProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBAddShapeExProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddShapeEx"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PBAddShapeEx PBAddShapeEx is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Adds a sub shape to a registered rigid body.<br> See <A HREF="PBPhysicalizeEx.cmo">PBPhysicalizeExSamples.cmo</A> for example. <h3>Technical Information</h3> \image html PBAddShapeEx.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed <BR> <BR> <SPAN CLASS="pin">Target:</SPAN>The 3D Entity associated to the rigid body <BR> <SPAN CLASS="pin">Flags: </SPAN>Flags to determine common properties for the desired body.It is possible to alter certain flags after creation. See #BodyFlags for more information <br> - <b>Range:</b> [BodyFlags] - <b>Default:</b>Moving,Collision,World Gravity<br> - Ways to alter flags : - Using \ref PBSetPar - Using VSL : #pRigidBody::updateFlags() <SPAN CLASS="pin">Hull Type: </SPAN>The desired shape type. The intial shape can NOT be changed after creation. See #HullType for more information <br> - <b>Range:</b> [HullType]<br> - <b>Default:</b>Sphere<br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createRigidBody().<br> <h3>Optional Parameters</h3> All more specific parameters such as material or pivot offset must be enabled by the building block settings<br> <SPAN CLASS="pin">Pivot: </SPAN>Specifies the rigid bodies local shape offset (#pPivotSettings) <br><br> \image html pBPivotParameter.jpg - <b>Offset Linear:</b> \copydoc pPivotSettings::localPosition - <b>Offset Angular:</b> \copydoc pPivotSettings::localOrientation - <b>Offset Reference:</b> \copydoc pPivotSettings::pivotReference <h4>Notes</h4><br> - Alter or set the shape offset : - Using the built-in building blocks with "Physics" settings enabled : - "Set Position" - "Translate" - "Set Orientation" - #pRigidBody::setPosition() or #pRigidBody::setRotation() - Attach attribute "Physics\pBPivotSettings" to : - 3D-Entity - its mesh - or to the meshes material<br> <hr> <SPAN CLASS="pin">Mass: </SPAN>Overrides mass setup (#pMassSettings) <br><br> \image html pBMassParameter.jpg - <b>New Density:</b> \copydoc pMassSettings::newDensity - <b>Total Mass:</b> \copydoc pMassSettings::totalDensity - <b>Offset Linear:</b> \copydoc pMassSettings::localPosition - <b>Offset Angular:</b> \copydoc pMassSettings::localOrientation - <b>Offset Reference:</b> \copydoc pMassSettings::massReference <h4>Notes</h4><br> - Alter or set mass settings : - Attach attribute "Physics\pBOptimization" to the : - 3D-Entity - its mesh - or to the meshes material<br> - #pRigidBody::updateMassFromShapes() <hr> <SPAN CLASS="pin">Collision: </SPAN>Overrides collsion settings (#pCollisionSettings) <br><br> \image html pBCollisionParameter.jpg - <b>Collision Group: </b> \copydoc pCollisionSettings::collisionGroup - <b>Group Mask:</b> \copydoc pCollisionSettings::groupsMask - <b>Skin Width:</b>\copydoc pCollisionSettings::skinWidth <h4>Notes</h4><br> - Alter or set collisions settings : - \ref PBSetPar. Collisions group can be set per sub shape. - pRigidBody::setCollisionsGroup() - pRigidBody::setGroupsMask() - Attach attribute "Physics\pBCollisionSettings" to : - 3D-Entity - its mesh - or to the meshes material <br> - Please create custom groups in the Virtools "Flags and Enum manager" : "pBCollisionsGroup". This enumeration is stored in the cmo <br> <hr> <SPAN CLASS="pin">CCD: </SPAN>Specifies a CCD mesh. This parameter is NOT being used in this release.<br><br> \image html pBCCSettingsParameter.jpg <hr> <SPAN CLASS="pin">Material: </SPAN>Specifies a physic material(#pMaterial)<br><br> \image html pBMaterial.jpg - <b>XML Link :</b> \copydoc pMaterial::xmlLinkID - <b>Dynamic Friction :</b> \copydoc pMaterial::dynamicFriction - <b>Static Friction: </b> \copydoc pMaterial::staticFriction - <b>Restitution: </b> \copydoc pMaterial::restitution - <b>Dynamic Friction V: </b> \copydoc pMaterial::dynamicFrictionV - <b>Static Friction V : </b> \copydoc pMaterial::staticFrictionV - <b>Direction Of Anisotropy: </b> \copydoc pMaterial::dirOfAnisotropy - <b>Friction Combine Mode: </b> \copydoc pMaterial::frictionCombineMode - <b>Restitution Combine Mode: </b> \copydoc pMaterial::restitutionCombineMode - <b>Flags: </b> \copydoc pMaterial::flags <h4>Notes</h4><br> - Alter or set a physic material is also possible by : - \ref PBSetMaterial - #pRigidBody::updateMaterialSettings() - Attach attribute "Physics\pBMaterial" to : - 3D-Entity - its mesh - or to the meshes material - Using VSL : <SPAN CLASS="NiceCode"> \include pBMaterialSetup.vsl </SPAN> - The enumeration "XML Link" is being populated by the file "PhysicDefaults.xml" and gets updated on every reset. - If using settings from XML, the parameter gets updated too<br> <hr> <SPAN CLASS="pin">Capsule Settings: </SPAN>Overrides capsule default dimensions(#pCapsuleSettingsEx)<br><br> \image html pBCapsuleSettings.jpg - <b>Radius :</b> \copydoc pCapsuleSettingsEx::radius - <b>Height :</b> \copydoc pCapsuleSettingsEx::height <h4>Notes</h4><br> - Setting a rigid bodies capsule dimension is also possible by : - Attach the attribute "Physics\pCapsule" to : - 3D-Entity - its mesh - or to the meshes material - VSL : <SPAN CLASS="NiceCode"> \include pBCapsuleEx.vsl </SPAN> <hr> <SPAN CLASS="pin">Convex Cylinder Settings: </SPAN>Overrides default convex cylinder settings(#pConvexCylinderSettings)<br><br> \image html pBConvexCylinder.jpg - <b>Approximation :</b> \copydoc pConvexCylinderSettings::approximation - <b>Radius :</b> \copydoc pConvexCylinderSettings::radius - <b>Height :</b> \copydoc pConvexCylinderSettings::height - <b>Forward Axis :</b> \copydoc pConvexCylinderSettings::forwardAxis - <b>Forward Axis Reference:</b> \copydoc pConvexCylinderSettings::forwardAxisRef - <b>Down Axis :</b> \copydoc pConvexCylinderSettings::downAxis - <b>Down Axis Reference:</b> \copydoc pConvexCylinderSettings::downAxisRef - <b>Right :</b> \copydoc pConvexCylinderSettings::rightAxis - <b>Right Axis Reference:</b> \copydoc pConvexCylinderSettings::rightAxisRef - <b>Build Lower Half Only :</b> \copydoc pConvexCylinderSettings::buildLowerHalfOnly - <b>Convex Flags :</b> \copydoc pConvexCylinderSettings::convexFlags <h4>Notes</h4><br> - Set a rigid bodies convex cylinder parameters by : - Attach the attribute "Physics\pConvexCylinder" to : - 3D-Entity - its mesh - or to the meshes material - VSL : <SPAN CLASS="NiceCode"> \include pBConvexCylinder.vsl </SPAN> <hr> <SPAN CLASS="pin">Wheel: </SPAN>Overrides wheel settings(#pWheelDescr)<br><br> \image html pBWheelSettings.jpg - @todo Documentation ! */ BB_EVALUATE_PINS(gPIMAP) BB_EVALUATE_SETTINGS(gPIMAP) proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct( PBAddShapeExCB ); proto->SetFunction(PBAddShapeEx); *pproto = proto; return CK_OK; } //************************************ // Method: PBAddShapeEx // FullName: PBAddShapeEx // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBAddShapeEx(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // objects // CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); //the world reference, optional used CK3dEntity*worldRef = NULL; //the world object, only used when reference has been specified pWorld *world = NULL; //final object description pObjectDescr oDesc; pRigidBody *body = NULL; NxShape *shape = NULL; XString errMesg; //---------------------------------------------------------------- // // sanity checks // CK3dEntity *bodyReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_BodyRef); if( !bodyReference) bbErrorME("No body reference specified"); body = GetPMan()->getBody(bodyReference); if( !body){ errMesg.Format("Object %s is not physicalized",bodyReference->GetName()); bbErrorME(errMesg.Str()); } if( !target->GetCurrentMesh() ){ errMesg.Format("Object %s has no mesh",target->GetName()); bbErrorME(errMesg.Str()); } shape= GetPMan()->getSubShape(target); if (shape && !body->isSubShape(bodyReference) ) { errMesg.Format("Object %s is not a sub shape of %s",target,bodyReference->GetName()); bbErrorME(errMesg.Str()); } //get the parameter array BB_DECLARE_PIMAP; //---------------------------------------------------------------- // // general settings // oDesc.hullType = (HullType)GetInputParameterValue<int>(beh,bbI_HullType); oDesc.flags = (BodyFlags)GetInputParameterValue<int>(beh,bbI_Flags); oDesc.version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; VxQuaternion refQuad;target->GetQuaternion(&refQuad,body->GetVT3DObject()); VxVector relPos;target->GetPosition(&relPos,body->GetVT3DObject()); // optional // Pivot // BBSParameterM(bbI_Pivot,BB_SSTART); if (sbbI_Pivot) { CKParameter*pivotParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Pivot))->GetRealSource(); if (pivotParameter) { IParameter::Instance()->copyTo(oDesc.pivot,pivotParameter); oDesc.mask |= OD_Pivot; } } //---------------------------------------------------------------- // optional // mass // BBSParameterM(bbI_Mass,BB_SSTART); if (sbbI_Mass) { CKParameter*massParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Mass))->GetRealSource(); if (massParameter) { IParameter::Instance()->copyTo(oDesc.mass,massParameter); oDesc.mask |= OD_Mass; } } //---------------------------------------------------------------- // optional // collision // BBSParameterM(bbI_Collision , BB_SSTART); if (sbbI_Collision) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Collision))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc.collision,par); oDesc.mask |= OD_Collision; } } //---------------------------------------------------------------- // optional // collision : CCD // BBSParameterM(bbI_CCD, BB_SSTART); if (sbbI_CCD) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCD))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc.ccd,par); oDesc.mask |= OD_CCD; } } //---------------------------------------------------------------- // optional // Material // BBSParameterM(bbI_Material, BB_SSTART); if (sbbI_Material) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); if (par) { pFactory::Instance()->copyTo(oDesc.material,par); oDesc.mask |= OD_Material; } } //---------------------------------------------------------------- // optional // capsule // BBSParameterM(bbI_Capsule, BB_SSTART); if (sbbI_Capsule) { if (oDesc.hullType == HT_Capsule) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Capsule))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc.capsule,par); oDesc.mask |= OD_Capsule; } }else{ errMesg.Format("You attached a capsule parameter but the hull type is not capsule"); bbWarning(errMesg.Str()); } } //---------------------------------------------------------------- // optional // convex cylinder // BBSParameterM(bbI_CCylinder, BB_SSTART); if (sbbI_CCylinder) { if (oDesc.hullType == HT_ConvexCylinder) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCylinder))->GetRealSource(); if (par) { pFactory::Instance()->copyTo(oDesc.convexCylinder,par,true); oDesc.mask |= OD_ConvexCylinder; } }else{ errMesg.Format("You attached a convex cylinder parameter but the hull type is not a convex cylinder"); bbWarning(errMesg.Str()); } } //---------------------------------------------------------------- // optional // convex cylinder // BBSParameterM(bbI_Wheel, BB_SSTART); if (sbbI_Wheel) { if (oDesc.hullType == HT_Wheel) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Wheel))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc.wheel,(CKParameterOut*)par); oDesc.mask |= OD_Wheel; } }else{ errMesg.Format("You attached a wheel parameter but the hull type is not a wheel"); bbWarning(errMesg.Str()); } } //---------------------------------------------------------------- // // create sub shape : // shape = pFactory::Instance()->createShape(bodyReference,oDesc,target,target->GetCurrentMesh(),relPos,refQuad); //---------------------------------------------------------------- // // update input parameters // if (sbbI_Material) { CKParameterOut *par = (CKParameterOut*)beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); if (par) { pFactory::Instance()->copyTo(par,oDesc.material); } } //---------------------------------------------------------------- // // error out // errorFound: { beh->ActivateOutput(0); return CKBR_GENERICERROR; } //---------------------------------------------------------------- // // All ok // allOk: { beh->ActivateOutput(0); return CKBR_OK; } return 0; } //************************************ // Method: PBAddShapeExCB // FullName: PBAddShapeExCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBAddShapeExCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; } <file_sep>#include "xDistributed3DObjectClass.h" #include "xDistributedPropertyInfo.h" #include "xDistTools.h" /*xDistributed3DObjectClass::~xDistributed3DObjectClass() { }*/ xDistributed3DObjectClass::xDistributed3DObjectClass() : xDistributedClass() { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributed3DObjectClass::getFirstUserField(){ return 8; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributed3DObjectClass::getUserFieldBitValue(int walkIndex) { int userTypeCounter = 0; xDistributedPropertiesListType &props = *getDistributedProperties(); for (unsigned int i = 0 ; i < props.size() ; i ++ ) { xDistributedPropertyInfo *dInfo = props[i]; if (dInfo->mNativeType==E_DC_3D_NP_USER) { if (i ==walkIndex) { break; } userTypeCounter++; } } int result = getFirstUserField(); result +=userTypeCounter; return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributed3DObjectClass::getInternalUserFieldIndex(int inputIndex) { int userTypeCounter = 0; xDistributedPropertiesListType &props = *getDistributedProperties(); for (unsigned int i = 0 ; i < props.size() ; i ++ ) { xDistributedPropertyInfo *dInfo = props[i]; if (dInfo->mNativeType==E_DC_3D_NP_USER) { if (userTypeCounter == inputIndex) { return i; } userTypeCounter++; } } return -1; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributed3DObjectClass::getUserFieldCount() { int userTypeCounter = 0; xDistributedPropertiesListType &props = *getDistributedProperties(); for (unsigned int i = 0 ; i < props.size() ; i ++ ) { if (props[i]->mNativeType==E_DC_3D_NP_USER) userTypeCounter++; } return userTypeCounter; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObjectClass::addProperty(int nativeType,int predictionType) { xDistributedPropertyInfo *result = exists(nativeType); if (!result) { TNL::StringPtr name = xDistTools::NativeTypeToString(nativeType); int valueType = xDistTools::NativeTypeToValueType(nativeType); result = new xDistributedPropertyInfo( name ,valueType , nativeType ,predictionType ); getDistributedProperties()->push_back( result ); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObjectClass::addProperty(const char*name,int type,int predictionType) { xDistributedPropertyInfo *result = exists(name); if (!result) { result = new xDistributedPropertyInfo( name ,type,E_DC_3D_NP_USER ,predictionType ); getDistributedProperties()->push_back( result ); } } <file_sep>#include "CKAll.h" CKObjectDeclaration *FillBehaviorSaveObjectsDecl(); CKERROR CreateSaveObjectsProto(CKBehaviorPrototype **pproto); int SaveObjects(const CKBehaviorContext& behcontext); CKERROR ZipCallBack(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSaveObjectsDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("Save Objects"); od->SetDescription(""); od->SetCategory("Narratives/Files"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x6f12495d,0x1aff17f4)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSaveObjectsProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateSaveObjectsProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Save Objects"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Save"); proto->DeclareOutput("Saved"); proto->DeclareInParameter("Filename", CKPGUID_STRING); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_VARIABLEPARAMETERINPUTS)); proto->SetFunction(SaveObjects); *pproto = proto; return CK_OK; } int SaveObjects(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; XString filename((CKSTRING) beh->GetInputParameterReadDataPtr(0)); CKBeObject *beo; CKObjectArray* oa = CreateCKObjectArray(); for (int i = 1 ;i<beh->GetInputParameterCount();i++) { beo = (CKBeObject *)beh->GetInputParameterObject(i); oa->InsertAt(beo->GetID()); } ctx->Save(filename.Str(),oa,0xFFFFFFFF,NULL); beh->ActivateOutput(0); return CKBR_OK; return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPCGroupTriggerEventDecl(); CKERROR CreatePCGroupTriggerEventProto(CKBehaviorPrototype **pproto); int PCGroupTriggerEvent(const CKBehaviorContext& behcontext); CKERROR PCGroupTriggerEventCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPCGroupTriggerEventDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PCGroupTriggerEvent"); od->SetCategory("Physic/Collision"); od->SetDescription("Triggers output if elements of a group stays within, enters or leaves a body ."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0xd8c142a,0x4ce04f7b)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePCGroupTriggerEventProto); od->SetCompatibleClassId(CKCID_GROUP); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePCGroupTriggerEventProto // FullName: CreatePCGroupTriggerEventProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePCGroupTriggerEventProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCGroupTriggerEvent"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PCGroupTriggerEvent PCGroupTriggerEvent is categorized in \ref Collision <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Triggers outputs if the body enters,stays or leaves another body .<br> See <A HREF="pBTriggerEvent.cmo">pBTriggerEvent.cmo</A> for example. <h3>Technical Information</h3> \image html PCGroupTriggerEvent.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">No Event: </SPAN>Nothing touched. <BR> <SPAN CLASS="out">Entering: </SPAN>Body entered. <BR> <SPAN CLASS="out">Leaving: </SPAN>Body leaved. <BR> <SPAN CLASS="out">Stay: </SPAN>Inside body . <BR> <SPAN CLASS="pin">Target Group: </SPAN>The group which the bb outputs triggers for. <BR> <SPAN CLASS="pout">Touched Object: </SPAN>The touched body. <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3><br> <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForce().<br> */ //proto->DeclareInParameter("Extra Filter",VTF_TRIGGER,"0"); //proto->DeclareInParameter("Remove Event",CKPGUID_BOOL,"0"); proto->DeclareInput("In"); proto->DeclareInput("Next"); proto->DeclareOutput("No Event"); proto->DeclareOutput("Entering"); proto->DeclareOutput("Stay"); proto->DeclareOutput("Leaving"); proto->DeclareOutput("Has More"); proto->DeclareOutParameter("Trigger Object",CKPGUID_3DENTITY,0); proto->DeclareOutParameter("Touched Object",CKPGUID_3DENTITY,0); proto->DeclareOutParameter("Trigger Event",VTF_TRIGGER,0); proto->DeclareLocalParameter("currentIndex", CKPGUID_INT); //proto->DeclareSetting("Trigger on Enter",CKPGUID_BOOL,"FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PCGroupTriggerEvent); *pproto = proto; return CK_OK; } enum bOutputs { bbO_None, bbO_Enter, bbO_Stay, bbO_Leave, bbO_HasMore, }; enum bInputs { bbI_Init, bbI_Next, }; bool isInGroup(CKGroup *src, CK3dEntity* testObject) { if (src && testObject) { for (int i = 0 ; i < src->GetObjectCount() ; i++ ) { CK3dEntity *ent = (CK3dEntity*)src->GetObject(i); if(ent) { if (ent==testObject) { return true; } } } } return false; } int getEventCount() { int result= 0; int nbEntries = GetPMan()->getTriggers().Size() ; for (int i = 0 ; i < GetPMan()->getTriggers().Size(); i++ ) { pTriggerEntry &entry = *GetPMan()->getTriggers().At(i); if(!entry.triggered) result++; } return result; } //************************************ // Method: PCGroupTriggerEvent // FullName: PCGroupTriggerEvent // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PCGroupTriggerEvent(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; ////////////////////////////////////////////////////////////////////////// //the object : CKGroup *target = (CKGroup *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; //int extraFilter = GetInputParameterValue<int>(beh,0); //int remove = GetInputParameterValue<int>(beh,1); int nbOfEvents = getEventCount(); if (!nbOfEvents) { beh->ActivateOutput(bbO_None); return 0; } /************************************************************************/ /* handle init */ /************************************************************************/ if( beh->IsInputActive(bbI_Init) ) { beh->ActivateInput(bbI_Init,FALSE); int index = 0;beh->SetLocalParameterValue(0,&index); //we have some, forward to in 1:next if (nbOfEvents) { beh->ActivateInput(bbI_Next,TRUE); beh->ActivateOutput(bbO_HasMore); } } /************************************************************************/ /* handle trigger 'next' */ /************************************************************************/ if( beh->IsInputActive(bbI_Next) ) { beh->ActivateInput(bbI_Next,FALSE); int index = 0;beh->GetLocalParameterValue(0,&index); for (int i = index ; i < GetPMan()->getTriggers().Size(); i++ ) { pTriggerEntry &entry = *GetPMan()->getTriggers().At(i); if (!entry.triggered) { if (isInGroup(target,entry.triggerShapeEnt)) { beh->SetOutputParameterObject(0,entry.triggerShapeEnt); beh->SetOutputParameterObject(1,entry.otherObject); SetOutputParameterValue<int>(beh,2,entry.triggerEvent); entry.triggered = true; //trigger out if(entry.triggerEvent == NX_TRIGGER_ON_ENTER) { beh->ActivateOutput(bbO_Enter); } if(entry.triggerEvent == NX_TRIGGER_ON_STAY) { beh->ActivateOutput(bbO_Stay); } if(entry.triggerEvent == NX_TRIGGER_ON_LEAVE) { beh->ActivateOutput(bbO_Leave); } //store index beh->SetLocalParameterValue(1,&index); int nbOfLeftEvents = getEventCount(); if (nbOfLeftEvents) { beh->ActivateOutput(bbO_HasMore); return 0; }else { beh->ActivateOutput(bbO_None); return 0; } } } } } /************************************************************************/ /* */ /************************************************************************/ return 0; } //************************************ // Method: PCGroupTriggerEventCB // FullName: PCGroupTriggerEventCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PCGroupTriggerEventCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Dolly Camera // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorDollyDecl(); CKERROR CreateDollyProto(CKBehaviorPrototype **pproto); int Dolly(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorDollyDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Dolly"); od->SetDescription("Keeps the projection plane at the same position while translating the camera on its Z local axis."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Translation Value: </SPAN>translation value on the Camera Z local axis.<BR> <SPAN CLASS=pin>Hierarchy: </SPAN>if TRUE, then this building block will also apply to the 3D Entity's children.<BR> <BR> Keeps the projection plane at the same position while translating the camera on its Z local axis.<BR> */ od->SetCategory("Cameras/Basic"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0xb98b83bb, 0x87787878)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDollyProto); od->SetCompatibleClassId(CKCID_TARGETCAMERA); return od; } CKERROR CreateDollyProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Dolly"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Translation Value", CKPGUID_FLOAT, "1.0"); proto->DeclareInParameter("Hierarchy", CKPGUID_BOOL, "TRUE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(Dolly); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int Dolly(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKTargetCamera *tcam = (CKTargetCamera *) beh->GetTarget(); if( !tcam ) return CKBR_OWNERERROR; // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); // Get Translation value float value=1.0f; beh->GetInputParameterValue(0,&value); // Hierarchy CKBOOL k=TRUE; beh->GetInputParameterValue(1,&k); k=!k; tcam->Translate(0.0f, 0.0f, value, tcam, k); return CKBR_OK; } <file_sep> rmdir .\CMakeFiles /s /q del .\*.vcproj /q /f del *.sln /q /f del CMakeCache.txt /q /f del cmake_install.cmake /q /f del VTPaths.lua cmake -Wno-dev -p CMakeLists.txt copy VTPaths.lua .\..\ rmdir .\CMakeFiles /s /q del .\*.vcproj /q /f del *.sln /q /f del CMakeCache.txt /q /f del cmake_install.cmake /q /f <file_sep>#include <StdAfx.h> #include "ToolManager.h" #include "vtCModuleDefines.h" #include "vtBaseMacros.h" ToolManager *manager = NULL; ////////////////////////////////////////////////////////////////////////// ToolManager::ToolManager(CKContext* ctx) : vtBaseManager(ctx,VTM_TOOL_MANAGER_GUID,"ToolManager") { m_Context->RegisterNewManager(this); manager = this; } ////////////////////////////////////////////////////////////////////////// CKERROR ToolManager::OnCKPause() { return CK_OK; } CKERROR ToolManager::OnCKPlay() { return CK_OK; } CKERROR ToolManager::PostClearAll() { return CK_OK; } CKERROR ToolManager::OnCKInit() { return CK_OK; } CKERROR ToolManager::PreSave() { return CK_OK; } CKContext* ToolManager::GetContext() { return GetInstance()->m_Context; } ToolManager* ToolManager::GetInstance() { if (manager) { return manager; } return NULL; } ToolManager::~ToolManager(){} CKERROR ToolManager::SequenceDeleted(CK_ID *objids,int count) { return CK_OK; } CKERROR ToolManager::SequenceAddedToScene(CKScene *scn,CK_ID *objids,int count) { return CK_OK; } CKERROR ToolManager::SequenceToBeDeleted(CK_ID *objids,int count) { return CK_OK; } CKERROR ToolManager::SequenceRemovedFromScene(CKScene *scn,CK_ID *objids,int count) { return CK_OK; } CKERROR ToolManager::OnCKReset() { return CK_OK; } CKERROR ToolManager::OnCKEnd() { return 0; } CKStateChunk* ToolManager::SaveData(CKFile* SavedFile) { return CK_OK; } CKERROR ToolManager::PostProcess() { return CK_OK; } CKERROR ToolManager::PreProcess() { return CK_OK; } CKERROR ToolManager::LoadData(CKStateChunk *chunk,CKFile* LoadedFile) { return CK_OK; } CKERROR ToolManager::PostSave() { return CK_OK; } <file_sep>/****************************************************************************** File : CustomPlayer.cpp Description: This file contains the CCustomPlayer class which is the "interface" with the Virtools SDK. All other files are Windows/MFC specific code. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ #include "CPStdAfx.h" #include "CustomPlayer.h" #include "CustomPlayerApp.h" #include "CustomPlayerDefines.h" #if defined(CUSTOM_PLAYER_STATIC) // include file used for the static configuration #include "CustomPlayerStaticLibs.h" #include "CustomPlayerRegisterDlls.h" #endif extern CCustomPlayerApp theApp; CCustomPlayer* thePlayer=0; int& CCustomPlayer::RasterizerFamily() { return m_RasterizerFamily; } int& CCustomPlayer::RasterizerFlags() { return m_RasterizerFlags; } int& CCustomPlayer::WindowedWidth() { return m_WindowedWidth; } int& CCustomPlayer::WindowedHeight() { return m_WindowedHeight; } int& CCustomPlayer::MininumWindowedWidth() { return m_MinWindowedWidth; } int& CCustomPlayer::MininumWindowedHeight() { return m_MinWindowedHeight; } int& CCustomPlayer::FullscreenWidth() { return m_FullscreenWidth; } int& CCustomPlayer::FullscreenHeight() { return m_FullscreenHeight; } int CCustomPlayer::Driver() { return m_Driver; } int& CCustomPlayer::FullscreenBpp() { return m_FullscreenBpp; } CKRenderContext* CCustomPlayer::GetRenderContext() { return m_RenderContext; } extern CKERROR LoadCallBack(CKUICallbackStruct& loaddata,void*); //************************************ // Method: GetEnginePointers // FullName: CCustomPlayer::GetEnginePointers // Access: public // Returns: vtPlayer::Structs::xSEnginePointers* // Qualifier: //************************************ vtPlayer::Structs::xSEnginePointers* CCustomPlayer::GetEnginePointers() { return &m_EnginePointers; } //************************************ // Method: GetEngineWindowInfo // FullName: CCustomPlayer::GetEngineWindowInfo // Access: public // Returns: vtPlayer::Structs::xSEngineWindowInfo* // Qualifier: //************************************ vtPlayer::Structs::xSEngineWindowInfo* CCustomPlayer::GetEngineWindowInfo() { return m_EngineWindowInfo; } //////////////////////////////////////////////////////////////////////////////// // // CCustomPlayer: PUBLIC STATIC METHODS // //////////////////////////////////////////////////////////////////////////////// CCustomPlayer& CCustomPlayer::Instance() { if (thePlayer==0) { thePlayer = new CCustomPlayer(); } return *thePlayer; } //////////////////////////////////////////////////////////////////////////////// // // CCustomPlayer: PUBLIC METHODS // //////////////////////////////////////////////////////////////////////////////// CCustomPlayer::~CCustomPlayer() { // here we stop/release/clear the Virtools Engine try { if (!m_CKContext) { return; } // clear the CK context m_CKContext->Reset(); m_CKContext->ClearAll(); // destroy the render engine if (m_RenderManager && m_RenderContext) { m_RenderManager->DestroyRenderContext(m_RenderContext); } m_RenderContext = NULL; // close the ck context CKCloseContext(m_CKContext); m_CKContext = NULL; // shutdown all CKShutdown(); m_CKContext = NULL; if (m_AWStyle) { delete m_AWStyle; m_AWStyle =NULL; } } catch(...) { } } CCustomPlayer::CCustomPlayer() : m_State(eInitial), m_MainWindow(0),m_RenderWindow(0), m_CKContext(0),m_RenderContext(0), m_MessageManager(0),m_RenderManager(0),m_TimeManager(0), m_AttributeManager(0),m_InputManager(0), m_Level(0),m_QuitAttType(-1),m_SwitchResolutionAttType(-1),m_SwitchMouseClippingAttType(-1), m_WindowedResolutionAttType(-1),m_FullscreenResolutionAttType(-1),m_FullscreenBppAttType(-1), m_MsgClick(0),m_MsgDoubleClick(0), m_RasterizerFamily(CKRST_DIRECTX),m_RasterizerFlags(CKRST_SPECIFICCAPS_HARDWARE|CKRST_SPECIFICCAPS_DX9), m_WindowedWidth(640),m_WindowedHeight(480), m_MinWindowedWidth(400),m_MinWindowedHeight(300), m_FullscreenWidth(640),m_FullscreenHeight(480),m_FullscreenBpp(32), m_Driver(-1),m_FullscreenEnabled(FALSE), m_EatDisplayChange(FALSE),m_MouseClipped(FALSE),m_LastError(0), m_PlayerClass(MAINWINDOW_CLASSNAME),m_RenderClass(RENDERWINDOW_CLASSNAME) { m_EngineWindowInfo = new xSEngineWindowInfo(); m_EPaths = new xSEnginePaths(); // m_AWStyle = NULL; m_AWStyle = new xSApplicationWindowStyle(); m_AppMode = normal; m_hThread = NULL; } BOOL CCustomPlayer::_CheckDriver(VxDriverDesc* iDesc, int iFlags) { // check the rasterizer family if (iFlags & eFamily) { if (iDesc->Caps2D.Family!=m_RasterizerFamily) { return FALSE; } } // test directx version if ( (iDesc->Caps2D.Family==CKRST_DIRECTX) && (iFlags & eDirectXVersion) ) { if ((iDesc->Caps3D.CKRasterizerSpecificCaps&0x00000f00UL)!=(m_RasterizerFlags&0x00000f00UL)) { return FALSE; } } // test hardware/software if (iFlags & eSoftware) { if (((int)iDesc->Caps3D.CKRasterizerSpecificCaps&CKRST_SPECIFICCAPS_SOFTWARE)!=(m_RasterizerFlags&CKRST_SPECIFICCAPS_SOFTWARE)) { return FALSE; } } return TRUE; } void CCustomPlayer::_MissingGuids(CKFile* iFile, const char* iResolvedFile) { // here we manage the error CKERR_PLUGINSMISSING when loading a composition failed // create missing guids log filename char fp[_MAX_PATH]; { GetTempPath(_MAX_PATH,fp); char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; _splitpath(fp,drive,dir,fname,ext); _makepath(fp,drive,dir,MISSINGUIDS_LOG,NULL); } // retrieve the list of missing plugins/guids XClassArray<CKFilePluginDependencies> *p = iFile->GetMissingPlugins(); CKFilePluginDependencies*it = p->Begin(); FILE *logf = NULL; char str[64]; for(CKFilePluginDependencies* it=p->Begin();it!=p->End();it++) { int count = (*it).m_Guids.Size(); for(int i=0;i<count;i++) { if (!((*it).ValidGuids[i])) { if(!logf) { logf = fopen(fp,"wt"); if (!logf) { return; } if (iResolvedFile) { fprintf(logf,"File Name : %s\nMissing GUIDS:\n",iResolvedFile); } } sprintf(str,"%x,%x\n",(*it).m_Guids[i].d1,(*it).m_Guids[i].d2); fprintf(logf,"%s",str); } } } fclose(logf); } <file_sep>doxygen doxyConfigInternal.dox X:\ProjectRoot\vdev\Documentation\vtAgeia.CHM copy X:\ProjectRoot\vdev\Documentation\vtAgeia.CHM X:\ProjectRoot\vtmod_vtAgeia\Doc /y copy X:\ProjectRoot\vdev\Documentation\vtAgeia.CHM X:\ProjectRoot\vtmodsvn\Plugins\vtAgeia\Documentation /y exit <file_sep>/******************************************************************** created: 2006/22/06 created: 22:06:2006 12:26 filename: x:\junctions\ProjectRoot\current\vt_plugins\vt_toolkit\Behaviors\Generic\BGInstancer.h file path: x:\junctions\ProjectRoot\current\vt_plugins\vt_toolkit\Behaviors\Generic file base: BGInstancer file ext: h author: mc007 purpose: instancing of b-graphs per file *********************************************************************/ #define BGWRAPPER_GUID CKGUID(0x35fb3204,0x6b59721c) // Parameters for BGWrapper enum EBGWRAPPERPARAM { // local EBGWRAPPERPARAM_PARAMETER_SCRIPT = 0, EBGWRAPPERPARAM_PARAMETER_NAME = 1, EBGWRAPPERPARAM_LOCAL_PARAMETER_COUNT, }; class BGWrapper { public: static CKObjectDeclaration* FillBehaviour( void ); static CKERROR CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ); static int BehaviourFunction( const CKBehaviorContext& behaviorContext ); private: static CKERROR BGWrapperCB(const CKBehaviorContext& behContext); static BOOL HasIO(CKBehavior* pBeh); static BOOL DeleteIO(CKBehavior* pBeh); static BOOL CreateIO(CKBehavior* pBeh, CKBehavior* pScript); static BOOL CheckIO(CKBehavior* pBeh, CKBehavior* pScript); static CKBehavior* BGLoader(CKSTRING fileName,const CKBehaviorContext& behContext); static void ActivateNextFrameSubBB(CKBehavior* scriptObject,BOOL &bActivateNextFrame); static void DesactivateSubBB(CKBehavior* scriptObject); static void OwnerSubBB(CKBehavior* scriptObject,CKBeObject*owner); static void SetNewBG(CKBehavior *behaviour,CKBehavior *newBehavior); static void DestroyCurrentBG(CKLevel* level,CKBehavior *behaviour,CKBehavior *scriptObject); }; <file_sep>/* * Tcp4u v 3.31 Last Revision 27/02/1998 3.30 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: build.h * Purpose: Common header file. Group all includes needed * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #if defined (UNIX) # define API4U #elif defined (_WINDOWS) # ifdef _WIN32 # define API4U PASCAL # else # define API4U _export PASCAL FAR # endif #endif /* --------------------------------------------------- */ /* The exported include files should compile properly */ /* --------------------------------------------------- */ #include "tcp4u.h" #include "udp4u.h" #include "http4u.h" #include "smtp4u.h" /* --------------------------------------------------- */ /* The rest of them will have more troubles.......... */ /* --------------------------------------------------- */ #define HPUX_SOURCE #include <memory.h> #include <assert.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #ifdef _WINDOWS # include <windows.h> # include <windowsx.h> # include <winsock.h> #endif #ifdef UNIX # include <stdio.h> # include <unistd.h> # include <errno.h> # include <sys/types.h> # include <sys/ioctl.h> # include <sys/socket.h> # include <netinet/in.h> # include <netdb.h> #ifndef HPUX # include <arpa/inet.h> #endif # include <fcntl.h> # include <time.h> /* systemes un peu speciaux --------------------------------------- */ #ifdef AIX # include <sys/select.h> #endif #if defined (SOLARIS) || defined (SunOS) # include <sys/sockio.h> #endif # include <sys/time.h> /* ---------------------------------------------------------------- */ /* Et si ca ne marche toujours pas, on essaie les definitions :---- */ #ifndef INADDR_NONE # define INADDR_NONE -1 #endif #ifndef FIONREAD # define FIONREAD _IOR('f', 127, int) /* get number of bytes to read */ #endif #ifndef SIOCATMARK # define SIOCATMARK _IOR('s', 7, int) /* at oob mark? */ #endif /* ---------------------------------------------------------------- */ #endif /* UNIX */ #include "port.h" /* fonctions de portage */ #include "skt4u.h" /* define internes */ #include "dimens.h" /* size of communly used data */ #ifndef SizeOfTab # define SizeOfTab(x) (sizeof x / sizeof (*x)) #endif #ifndef min # define min(a,b) ( (a)<(b) ? (a) : (b) ) #endif <file_sep>#ifndef __X_BIT_SET_H__ #define __X_BIT_SET_H__ #ifndef u32 typedef unsigned int u32; #endif class xBitSet { private: u32 mBits; public: /// Default constructor initializes this bit set to all zeros. xBitSet() { mBits = 0; } /// Copy constructor. xBitSet(const xBitSet& in_rCopy) { mBits = in_rCopy.mBits; } /// Construct from an input u32. xBitSet(const u32 in_mask) { mBits = in_mask; } /// @name Accessors /// @{ /// Returns the u32 representation of the bit set. operator u32() const { return mBits; } /// Returns the u32 representation of the bit set. u32 getMask() const { return mBits; } /// @} /// @name Mutators /// /// Most of these methods take a word (ie, a BitSet32) of bits /// to operate with. /// @{ /// Sets all the bits in the bit set to 1 void set() { mBits = 0xFFFFFFFFUL; } /// Sets all the bits in the bit set that are set in m. void set(const u32 m) { mBits |= m; } /// For each bit set in s, sets or clears that bit in this, depending on whether b is true or false. void set(xBitSet s, bool b) { mBits = (mBits&~(s.mBits))|(b?s.mBits:0); } /// Clears all the bits in the bit set to 0. void clear() { mBits = 0; } /// Clears all the bits in the bit set that are set in m. void clear(const u32 m) { mBits &= ~m; } /// Flips all the bits in the bit set that are set in m. void toggle(const u32 m) { mBits ^= m; } /// Test if the passed bits are set. bool test(const u32 m) const { return (mBits & m) != 0; } /// Test if the passed bits and only the passed bits are set. bool testStrict(const u32 m) const { return (mBits & m) == m; } xBitSet& operator =(const u32 m) { mBits = m; return *this; } xBitSet& operator|=(const u32 m) { mBits |= m; return *this; } xBitSet& operator&=(const u32 m) { mBits &= m; return *this; } xBitSet& operator^=(const u32 m) { mBits ^= m; return *this; } xBitSet operator|(const u32 m) const { return xBitSet(mBits | m); } xBitSet operator&(const u32 m) const { return xBitSet(mBits & m); } xBitSet operator^(const u32 m) const { return xBitSet(mBits ^ m); } /// @} }; #ifndef xBit #define xBit(f) (1 << f) #endif __inline bool isFlagOn(xBitSet value,int flag) { return value.test(1 << flag ); } __inline bool isFlagOff(xBitSet value,int flag) { return value.test(1 << flag ) ? false : true; } __inline void setFlag(xBitSet& value,int flag,bool condition) { value.set(flag,condition); } __inline void enableFlag(xBitSet& value,int flag) { value.set(1 << flag,true ); } __inline void disableFlag(xBitSet& value,int flag) { value.set(1 << flag,false); } #endif<file_sep>//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by vtAgeiaInterface.rc // #define IDD_MYTABEXAMPLE_DIALOG 102 #define IDR_MAINFRAME 128 #define IDD_TAB_ONE 129 #define IDD_TAB_TWO 130 #define IDD_TAB_THREE 131 #define IDC_PBODY_TAB_PANE 145 #define IDC_TREE1 147 #define IDC_MAIN_VIEW_XML 998 #define IDC_PB_XML_TABS 9995 #define IDD_PB_XML_PARENT 9999 #define IDC_BFLAGS_MOVING 10001 #define IDC_LBL_FLAGS 10002 #define IDC_BFLAGS_DEFORMABLE 10003 #define IDC_BFLAGS_GRAV 10004 #define IDC_BFLAGS_KINEMATIC 10005 #define IDC_LBL_DYNAFLAGS 10006 #define IDC_BFLAGS_COLL_NOTIFY 10007 #define IDD_BODYSHORTPANE 10007 #define IDC_BFLAGS_TRIGGER 10008 #define IDC_BFLAGS_SSHAPE 10009 #define IDC_BFLAGS_HIERARCHY 10010 #define IDD_EDITOR 10011 #define IDC_LBL_LFLAGS 10011 #define IDC_FLAGS_BG 10012 #define IDI_EDITORICON 10013 #define IDC_TLFLAGS_POS 10013 #define IDC_TLFLAGS_ROT 10014 #define IDC_HULLTYPE 10015 #define IDC_HULLTYPE2 10016 #define IDC_TLFLAGS_POS_X 10016 #define IDC_TLFLAGS_POS_Y 10017 #define IDC_TLFLAGS_POS_Z 10018 #define IDC_TLFLAGS_ROT_Y 10019 #define IDC_TLFLAGS_ROT_Z 10020 #define IDC_BFLAGS_SLEEP 10021 #define IDD_PBCOMMON 10022 #define IDC_TLFLAGS_ROT_Y2 10022 #define IDC_TLFLAGS_ROT_X 10022 #define IDD_TOOLBAR 10023 #define IDC_XML_MAIN_VIEW 10027 #define IDC_EDIT1 10028 #define IDC_DYNA_FLAGS_RECT 10029 #define IDC_SPACER 10031 #define IDC_BFLAGS_COLL 10306 #define IDC_LBL_HTYPE 10890 #define IDC_LBL_HTYPE2 10891 #define IDD_PB_PARENT_DIALOG 30000 #define IDC_PB_MAINTAB 30001 #define IDD_PB_MAINTAB_DST 30002 #define IDC_MAIN_VIEW 30004 #define IDD_PB_COLLISION_PARENT 30008 #define IDC_XEXTERN_LINK 30022 #define IDC_XEXTERN_LINK_LBL 30030 #define IDC_XINTERN_LINK2 30031 #define IDC_XINTERN_LINK_LBL2 30032 #define IDD_PBODY_TAB_PANE 30033 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 10008 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 10030 #define _APS_NEXT_SYMED_VALUE 10000 #endif #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pWorldCallbacks.h" void pContactReport::onContactNotify(NxContactPair& pair, NxU32 events) { pRigidBody *bodyA = NULL; pRigidBody *bodyB = NULL; if (pair.actors[0]) { bodyA = static_cast<pRigidBody*>(pair.actors[0]->userData); } if (pair.actors[1]) { bodyB = static_cast<pRigidBody*>(pair.actors[1]->userData); } if (bodyA) { if (bodyA->hasWheels()) { bodyA->handleContactPair(&pair,0); return ; } if (bodyA->getVehicle()) { pVehicle* v = bodyA->getVehicle(); v->handleContactPair(&pair, 0); return ; } } if ( bodyB ) { if (bodyB->hasWheels()) { bodyB->handleContactPair(&pair,1); return ; } if (bodyB->getVehicle()) { pVehicle* v = bodyB->getVehicle(); v->handleContactPair(&pair, 1); return ; } } // Iterate through contact points NxContactStreamIterator i(pair.stream); //user can call getNumPairs() here while(i.goNextPair()) { //user can also call getShape() and getNumPatches() here while(i.goNextPatch()) { //user can also call getPatchNormal() and getNumPoints() here const NxVec3& contactNormal = i.getPatchNormal(); while(i.goNextPoint()) { //user can also call getPoint() and getSeparation() here const NxVec3& contactPoint = i.getPoint(); pCollisionsEntry entry; entry.point = pMath::getFrom(contactPoint); NxU32 faceIndex = i.getFeatureIndex0(); if(faceIndex==0xffffffff) faceIndex = i.getFeatureIndex1(); if(faceIndex!=0xffffffff) { entry.faceIndex = faceIndex; } entry.actors[0] = pair.actors[0]; entry.actors[1] = pair.actors[1]; entry.faceIndex = faceIndex; entry.sumNormalForce = pMath::getFrom(pair.sumNormalForce); entry.sumFrictionForce = pMath::getFrom(pair.sumFrictionForce); entry.faceNormal = pMath::getFrom(contactNormal); pRigidBody *bodyA = NULL; pRigidBody *bodyB = NULL; if (pair.actors[0]) { bodyA = static_cast<pRigidBody*>(pair.actors[0]->userData); } if (pair.actors[1]) { bodyB = static_cast<pRigidBody*>(pair.actors[1]->userData); } if (bodyA && bodyA->getActor() && (bodyA->getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) ) { entry.bodyA = bodyA; entry.bodyB = bodyB; bodyA->getCollisions().Clear(); bodyA->getCollisions().PushBack(entry); } if (bodyB && bodyB->getActor() && (bodyB->getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) ) { entry.bodyA = bodyA; entry.bodyB = bodyB; bodyB->getCollisions().Clear(); bodyB->getCollisions().PushBack(entry); } // result->getActor()->setContactReportFlags(NX_NOTIFY_ON_TOUCH); /* { entry.bodyA = body; body->getCollisions().Clear(); body->getCollisions().PushBack(entry); } if (pair.actors[1]) { pRigidBody *body = static_cast<pRigidBody*>(pair.actors[1]->userData); if (body) { entry.bodyB = body; body->getCollisions().Clear(); body->getCollisions().PushBack(entry); } }*/ /*getWorld()->getCollisions().PushBack(entry);*/ } } } } int pWorld::overlapOBBShapes(const VxBbox& worldBounds, CK3dEntity*shapeReference, pShapesType shapeType,CKGroup *shapes,int activeGroups/* =0xffffffff */, const pGroupsMask* groupsMask/* =NULL */, bool accurateCollision/* =false */) { int result=0; NxBox box; if (shapeReference) { NxShape *shape = getShapeByEntityID(shapeReference->GetID()); if (shape) { //shape->checkOverlapAABB() NxBoxShape*boxShape = static_cast<NxBoxShape*>(shape->isBox()); if (boxShape) { boxShape->getWorldOBB(box); } } }else{ box.center = getFrom(worldBounds.GetCenter()); box.extents = getFrom(worldBounds.GetSize()); } int total = 0; if (shapeType & ST_Dynamic ) { total+=getScene()->getNbDynamicShapes(); } if (shapeType & ST_Static) { total+=getScene()->getNbStaticShapes(); } NxShape** _shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); for (NxU32 i = 0; i < total; i++) _shapes[i] = NULL; NxGroupsMask mask; if (groupsMask) { mask.bits0 = groupsMask->bits0; mask.bits1 = groupsMask->bits1; mask.bits2 = groupsMask->bits2; mask.bits3 = groupsMask->bits3; }else{ mask.bits0 = 0; mask.bits1 = 0; mask.bits2 = 0; mask.bits3 = 0; } result = getScene()->overlapOBBShapes(box,(NxShapesType)shapeType,total,_shapes,NULL,activeGroups,&mask,accurateCollision); if (_shapes && shapes ) { for (int i = 0 ; i < result ; i++) { NxShape *s = _shapes[i]; if (s) { const char* name =s->getName(); pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(s->userData); if (sInfo->entID) { CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); if (obj) { shapes->AddObject((CKBeObject*)obj); } } } } } int op=2; return result; } int pWorld::overlapSphereShapes(const VxSphere& worldSphere,CK3dEntity*shapeReference,pShapesType shapeType,CKGroup*shapes,int activeGroups/* =0xffffffff */, const pGroupsMask* groupsMask/* =NULL */, bool accurateCollision/* =false */) { int result=0; NxSphere sphere; if (shapeReference) { NxShape *shape = getShapeByEntityID(shapeReference->GetID()); if (shape) { //shape->checkOverlapAABB() NxSphereShape *sphereShape = static_cast<NxSphereShape*>(shape->isSphere()); if (sphereShape) { sphere.radius = sphereShape->getRadius() + worldSphere.Radius(); //ori : VxVector ori = worldSphere.Center(); VxVector oriOut = ori; if (shapeReference) { shapeReference->Transform(&oriOut,&ori); } sphere.center = getFrom(oriOut); } } }else{ sphere.center = getFrom(worldSphere.Center()); sphere.radius = worldSphere.Radius(); } int total = 0; if (shapeType & ST_Dynamic ) { total+=getScene()->getNbDynamicShapes(); } if (shapeType & ST_Static) { total+=getScene()->getNbStaticShapes(); } NxShape** _shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); for (NxU32 i = 0; i < total; i++) _shapes[i] = NULL; NxGroupsMask mask; if (groupsMask) { mask.bits0 = groupsMask->bits0; mask.bits1 = groupsMask->bits1; mask.bits2 = groupsMask->bits2; mask.bits3 = groupsMask->bits3; }else{ mask.bits0 = 0; mask.bits1 = 0; mask.bits2 = 0; mask.bits3 = 0; } result = getScene()->overlapSphereShapes(sphere,(NxShapesType)shapeType,total,_shapes,NULL,activeGroups,&mask,accurateCollision); if (_shapes && shapes ) { for (int i = 0 ; i < result ; i++) { NxShape *s = _shapes[i]; if (s) { const char* name =s->getName(); pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(s->userData); if (sInfo->entID) { CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); if (obj) { shapes->AddObject((CKBeObject*)obj); } } } } } int op=2; return result; } int pWorld::raycastAllShapes(const VxRay& worldRay, pShapesType shapesType, int groups, float maxDist, pRaycastBit hintFlags, const pGroupsMask* groupsMask) { int result = 0; NxRay rayx; rayx.dir = getFrom(worldRay.m_Direction); rayx.orig = getFrom(worldRay.m_Origin); pRayCastReport &report = *getRaycastReport(); NxGroupsMask *mask = NULL; if (groupsMask) { mask = new NxGroupsMask(); mask->bits0 = groupsMask->bits0; mask->bits1 = groupsMask->bits1; mask->bits2 = groupsMask->bits2; mask->bits3 = groupsMask->bits3; } result = getScene()->raycastAllShapes(rayx,report,(NxShapesType)shapesType,groups,maxDist,hintFlags,mask); return result; } bool pWorld::raycastAnyBounds(const VxRay& worldRay, pShapesType shapesType, pGroupsMask *groupsMask/* =NULL */,int groups/* =0xffffffff */, float maxDist/* =NX_MAX_F32 */) { if (!getScene()) { return false; } NxRay _worldRay; _worldRay.dir = getFrom(worldRay.m_Direction); _worldRay.orig = getFrom(worldRay.m_Origin); NxShapesType _shapesType = (NxShapesType)shapesType; NxReal _maxDist=maxDist; NxGroupsMask *mask = NULL; if (groupsMask) { mask = new NxGroupsMask(); mask->bits0 = groupsMask->bits0; mask->bits1 = groupsMask->bits1; mask->bits2 = groupsMask->bits2; mask->bits3 = groupsMask->bits3; } bool result = getScene()->raycastAnyBounds(_worldRay,_shapesType,groups,_maxDist,mask); return result; } void pWorld::cIgnorePair(CK3dEntity *_a, CK3dEntity *_b, int ignore) { pRigidBody *a = GetPMan()->getBody(_a); pRigidBody *b = GetPMan()->getBody(_b); if (a&&b && a->getActor() && b->getActor() ) { if (getScene()) { getScene()->setActorPairFlags(*a->getActor(),*b->getActor(),ignore ? NX_IGNORE_PAIR : NX_NOTIFY_ALL ); } } } void pWorld::cSetGroupCollisionFlag(int g1 , int g2,int enabled) { if (getScene()) { if (g1 >=0 && g1 <= 31 && g2 >=0 && g2 <= 31) { if (enabled==0 || enabled ==1) { getScene()->setGroupCollisionFlag(g1,g2,enabled); } } } } void pTriggerReport::onTrigger(NxShape& triggerShape, NxShape& otherShape, NxTriggerFlag status) { NxActor *triggerActor = &triggerShape.getActor(); NxActor *otherActor = &otherShape.getActor(); pRigidBody *triggerBody = NULL; pRigidBody *otherBody = NULL; if (triggerActor) { triggerBody = static_cast<pRigidBody*>(triggerActor->userData); triggerBody->getTriggers().Clear(); } if (otherActor) { otherBody = static_cast<pRigidBody*>(otherActor->userData); otherBody->getTriggers().Clear(); } pTriggerEntry entry; entry.shapeA = &triggerShape; entry.shapeB = &otherShape; entry.triggerEvent = status; if (triggerBody) { triggerBody->getTriggers().PushBack(entry); } /*if(status & NX_TRIGGER_ON_ENTER) { } if(status & NX_TRIGGER_ON_LEAVE) { } if(status & NX_TRIGGER_ON_STAY) { // A body entered the trigger area for the first time }*/ } void pWorld::initUserReports() { contactReport = new pContactReport(); contactReport->setWorld(this); triggerReport = new pTriggerReport(); triggerReport->setWorld(this); raycastReport = new pRayCastReport(); raycastReport->setWorld(this); //getScene()->raycastAllShapes() } bool pRayCastReport::onHit(const NxRaycastHit& hit) { CKBehavior *beh =(CKBehavior*)GetPMan()->m_Context->GetObject(mCurrentBehavior); if ( beh ) { pRayCastHits *carray = NULL; beh->GetLocalParameterValue(0,&carray); if (carray) { //carray->clear(); }else { carray = new pRayCastHits(); } //carray->push_back(const_cast<NxRaycastHit&>(&hit)); NxRaycastHit *_hit = new NxRaycastHit(); _hit->distance = hit.distance; _hit->faceID = hit.faceID; _hit->flags = hit.flags; _hit->internalFaceID = hit.internalFaceID; _hit->materialIndex = hit.materialIndex; _hit->shape = hit.shape; _hit->u = hit.u; _hit->v = hit.v; _hit->worldImpact = hit.worldImpact; _hit->worldNormal = hit.worldNormal; const char *name = hit.shape->getName(); carray->push_back(_hit); beh->SetLocalParameterValue(0,&carray); } return true; } void pWorld::setFilterOps(pFilterOp op0,pFilterOp op1, pFilterOp op2) { getScene()->setFilterOps((NxFilterOp)op0,(NxFilterOp)op1,(NxFilterOp)op2); } void pWorld::setFilterBool(bool flag) { getScene()->setFilterBool(flag); } void pWorld::setFilterConstant0(const pGroupsMask& mask) { NxGroupsMask _mask; _mask.bits0=mask.bits0; _mask.bits1=mask.bits1; _mask.bits2=mask.bits2; _mask.bits3=mask.bits3; getScene()->setFilterConstant0(_mask); } void pWorld::setFilterConstant1(const pGroupsMask& mask) { NxGroupsMask _mask; _mask.bits0=mask.bits0; _mask.bits1=mask.bits1; _mask.bits2=mask.bits2; _mask.bits3=mask.bits3; getScene()->setFilterConstant1(_mask); } bool pWorld::getFilterBool()const { return getScene()->getFilterBool(); } pGroupsMask pWorld::getFilterConstant0()const { NxGroupsMask mask = getScene()->getFilterConstant0(); pGroupsMask _mask; _mask.bits0=mask.bits0; _mask.bits1=mask.bits1; _mask.bits2=mask.bits2; _mask.bits3=mask.bits3; return _mask; } pGroupsMask pWorld::getFilterConstant1()const { NxGroupsMask mask = getScene()->getFilterConstant1(); pGroupsMask _mask; _mask.bits0=mask.bits0; _mask.bits1=mask.bits1; _mask.bits2=mask.bits2; _mask.bits3=mask.bits3; return _mask; } /* int pWorld::CIsInCollision(CK3dEntity*_a,CK3dEntity*_b) { pWorld *world=GetPMan()->getWorldByBody(_a); pWorld *world2=GetPMan()->getWorldByBody(_b); if (!world || !world2 || world!=world2 ) return false; pRigidBody*bodyA= world->getBody(_a); pRigidBody*bodyB= world->getBody(_b); dSurfaceParameters *surface = NULL; bool worldHasSurface = ( world->GetDataFlags() & WDF_HAS_SURFACE_PARAMETER ) ; bool useSurface = false; if (worldHasSurface) { surface = &GetDefaultSurface(); useSurface = true; } if ( bodyA->GetDataFlags() & BDF_HAS_SURFACE_PARAMETER ) { surface = &bodyA->GetDefaultSurface(); useSurface = true; } if ( bodyB->GetDataFlags() & BDF_HAS_SURFACE_PARAMETER ) { surface = &bodyB->GetDefaultSurface(); useSurface = true; } pRigidBody *surfaceMaterialBody=NULL; if (bodyA->GetDataFlags() & BDF_HAS_MATERIAL_SURFACE_PARAMETER) { surfaceMaterialBody = bodyA; useSurface = true; } if (bodyB->GetDataFlags() & BDF_HAS_MATERIAL_SURFACE_PARAMETER) { surfaceMaterialBody = bodyB; useSurface = true; } if (bodyA && bodyB && bodyA !=bodyB) { dGeomID gid1 = bodyA->GetOdeGeom(); dGeomID gid2 = bodyB->GetOdeGeom(); if (gid1 && gid2 && gid1!=gid2) { dContact *contact = new dContact[1]; int nbContacts = dCollide (gid1,gid2,1,&contact[0].geom,sizeof(dContactGeom)); if (nbContacts) { for (int i=0; i < nbContacts; i++) { if (surfaceMaterialBody) { CK3dEntity *colliderB = NULL; if (surfaceMaterialBody->GetVT3DObject() == _a ) { colliderB = _b; }else colliderB = _a; if (surfaceMaterialBody->GetVT3DObject() == colliderB ) { int op = 3; } VxVector cPos(contact[i].geom.pos[0],contact[i].geom.pos[1],contact[i].geom.pos[2] ); int faceIndex = vtAgeia::math::GetNearestFace(surfaceMaterialBody->GetVT3DObject(),cPos); CKMesh * mesh = surfaceMaterialBody->GetVT3DObject()->GetCurrentMesh(); if (mesh) { VxVector pos1,pos2; surfaceMaterialBody->GetVT3DObject()->GetBaryCenter(&pos2); surfaceMaterialBody->GetVT3DObject()->Transform(&pos2,&pos2); VxIntersectionDesc desc; surfaceMaterialBody->GetVT3DObject()->RayIntersection(&cPos,&pos2,&desc,NULL); CKMaterial *material = mesh->GetFaceMaterial(desc.FaceIndex); if (material) { PhysicMaterialList& mList = surfaceMaterialBody->GetPhysicMaterials(); int mSize = mList.Size(); PhysicMaterialList::Iterator it = mList.Find(material->GetID() ); if( it != mList.End() ) { dSurfaceParameters *sPar = *it; if (sPar) { surface = sPar; } } } } } } } } } return 0; } void collisionCallback(void *data,dGeomID o1,dGeomID o2) { pWorld *world = static_cast<pWorld*>(data); if(!world) return; if( !o1 || !o2) return; if (!o1->body && !o2->body) return; if( o1 == o2 ) return; if (dGeomIsSpace(o1) || dGeomIsSpace(o2)) { // colliding a space with something dSpaceCollide2(o1,o2,data,&collisionCallback); // Note we do not want to test intersections within a space, // only between spaces. return; } dBodyID b1,b2; b1 = dGeomgetBody(o1); b2 = dGeomgetBody(o2); CK_ID e1 = (CK_ID)(dGeomGetData(o1)); CK_ID e2 = (CK_ID)(dGeomGetData(o2)); CK3dEntity *_e1 = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(e1)); CK3dEntity* _e2 = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(e2)); // exit without doing anything if the two bodies are connected by a joint if (b1 && b2 && dAreConnected (b1,b2)) return; pRigidBody *solid1 = world->getBody(_e1); pRigidBody *solid2 = world->getBody(_e2); if (!solid1 || !solid2) { return; } float friction=solid1->GetFriction(); float restitution = solid1->GetRestitution(); //for friction, take minimum friction=(friction < solid2->GetFriction() ? friction :solid2->GetFriction()); //restitution:take minimum restitution = restitution < solid2->GetRestitution() ? restitution : solid2->GetRestitution(); dSurfaceParameters *surface = NULL; bool worldHasSurface = ( world->GetDataFlags() & WDF_HAS_SURFACE_PARAMETER ) ; bool useSurface = false; if (worldHasSurface) { surface = &world->GetDefaultSurface(); useSurface = true; } if ( solid1->GetDataFlags() & BDF_HAS_SURFACE_PARAMETER ) { surface = &solid1->GetDefaultSurface(); useSurface = true; } if ( solid2->GetDataFlags() & BDF_HAS_SURFACE_PARAMETER ) { surface = &solid2->GetDefaultSurface(); useSurface = true; } pRigidBody *surfaceMaterialBody=NULL; if (solid1->GetDataFlags() & BDF_HAS_MATERIAL_SURFACE_PARAMETER) { surfaceMaterialBody = solid1; useSurface = true; } if (solid2->GetDataFlags() & BDF_HAS_MATERIAL_SURFACE_PARAMETER) { surfaceMaterialBody = solid2; useSurface = true; } dContact contact[10]; if (int numc = dCollide (o1, o2, 10,&contact[0].geom, sizeof(dContact))) { for (int i=0; i < numc; i++) { if (contact[i].geom.depth > 0.0f && contact[i].geom.depth <= 0.0001f) { contact[i].geom.depth = 0.001f; } if (contact[i].geom.depth == 0.0f) { continue; } if (surfaceMaterialBody) { CK3dEntity *colliderB = NULL; if (surfaceMaterialBody->GetVT3DObject() == _e1 ) { colliderB = _e2; }else colliderB = _e1; VxVector cPos(contact[i].geom.pos[0],contact[i].geom.pos[1],contact[i].geom.pos[2] ); //int faceIndex = vtODE::math::GetNearestFace(surfaceMaterialBody->GetVT3DObject(),cPos); VxVector pos1,pos2; surfaceMaterialBody->GetVT3DObject()->GetBaryCenter(&pos2); surfaceMaterialBody->GetVT3DObject()->Transform(&pos2,&pos2); VxIntersectionDesc desc; surfaceMaterialBody->GetVT3DObject()->RayIntersection(&cPos,&pos2,&desc,NULL); int faceIndex = desc.FaceIndex; CKMesh * mesh = surfaceMaterialBody->GetVT3DObject()->GetCurrentMesh(); if (mesh) { CKMaterial *material = mesh->GetFaceMaterial(faceIndex); if (material) { PhysicMaterialList& mList = surfaceMaterialBody->GetPhysicMaterials(); int mSize = mList.Size(); PhysicMaterialList::Iterator it = mList.Find(material->GetID() ); if( it != mList.End() ) { dSurfaceParameters *sPar = *it; if (sPar) { surface = sPar; } } } } } if ( useSurface) { contact[i].surface.mode = surface->mode; contact[i].surface.mu = surface->mu; contact[i].surface.mu2 = friction; contact[i].surface.slip1 = surface->slip1; contact[i].surface.slip2 = surface->slip2; contact[i].surface.motion1 = surface->motion1; contact[i].surface.motion2 = surface->motion2; contact[i].surface.motionN = surface->motionN; contact[i].surface.soft_erp = surface->soft_erp; contact[i].surface.soft_cfm = surface->soft_cfm; contact[i].surface.bounce = restitution;//0.5; contact[i].surface.bounce_vel = surface->bounce_vel; }else { //contact[i].surface.mode = dContactSlip1 | dContactSlip2 |dContactBounce|dContactSoftERP | dContactSoftCFM | dContactApprox1; //contact[i].surface.mode = dContactSoftERP | dContactApprox1| dContactApprox0 | dContactSoftCFM|dContactBounce ; //contact[i].surface.mode = dContactSlip1 | dContactSlip2 | dContactSoftERP | dContactApprox1 |dContactBounce; contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactSlip1 | dContactSlip2; //contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactBounce| dContactApprox0| dContactSlip1 | dContactSlip2; //contact[i].surface.mode = dContactSlip1 | dContactSlip2 | dContactSoftERP | dContactApprox1 ; contact[i].surface.mu = dInfinity; contact[i].surface.mu2 = friction; contact[i].surface.slip1 = 0.000001; contact[i].surface.slip2 = 0.000001; contact[i].surface.soft_erp = 0.4; contact[i].surface.soft_cfm = 0.000000005; contact[i].surface.bounce = restitution;//0.5; contact[i].surface.bounce_vel = 0.0000001f; } dJointID c = dJointCreateContact (world->World(),world->ContactGroup(),contact+i); dJointAttach (c,dGeomgetBody(o1),dGeomgetBody(o2)); } } } ////////////////////////////////////////////////////////////////////////// bool pWorld::collide() { SpaceID()->collide(this,&collisionCallback); return true; } ////////////////////////////////////////////////////////////////////////// vt3DObjectType pWorld::CIsInCollision(vt3DObjectType a, CKGroup *group,VxVector& pos, VxVector& normal,float &length) { pRigidBody *bodyA = getBody(a); dGeomID gid1 = NULL; if (bodyA) { gid1 = bodyA->GetOdeGeom(); } if (!a || !group || !bodyA || !gid1) { return NULL; } for (int i = 0 ; i < group->GetObjectCount() ; i ++) { pRigidBody*bodyB= getBody((CK3dEntity*)group->GetObject(i)); if (bodyB) { if (bodyB==bodyA) { continue; } if (bodyB) { dGeomID gid2 = bodyB->GetOdeGeom(); if (gid1==gid2) { continue; } if (gid2) { dContact *contact = new dContact[1]; int nbContacts = dCollide (gid1,gid2,1,&contact[0].geom,sizeof(dContactGeom)); if (nbContacts) { for (int i = 0 ; i < nbContacts ; i++ ) { pos.x = contact[0].geom.pos[0]; pos.y = contact[0].geom.pos[1]; pos.z = contact[0].geom.pos[2]; normal.x =contact[0].geom.normal[0]; normal.y =contact[0].geom.normal[1]; normal.z = contact[0].geom.normal[2]; return bodyB->GetVT3DObject(); } } } } } } return NULL; } ////////////////////////////////////////////////////////////////////////// vt3DObjectType pWorld::CRayCollision(VxVector point,CK3dEntity*pointRef,VxVector dir,CK3dEntity*dirRef,float depth,bool skipPosRef,VxVector& pos, VxVector& normal) { ////////////////////////////////////////////////////////////////////////// //origin of the ray : VxVector origin = point; VxVector originOut = origin; if (pointRef) { pointRef->Transform(&originOut,&origin); } ////////////////////////////////////////////////////////////////////////// //direction of the ray : VxVector dirIn = dir; VxVector dirOut = dirIn; if (dirRef) { VxVector dirl,up,right; dirRef->GetOrientation(&dirl,&up,&right); dirRef->TransformVector(&dirOut,&dirIn); } //dirOut*=dirIn; ////////////////////////////////////////////////////////////////////////// pRigidBody *bodyA = NULL; dGeomID gid1 = NULL; //if position reference is given : if (pointRef) { bodyA = getBody(pointRef); if (bodyA) { gid1 = bodyA->GetOdeGeom(); } } ////////////////////////////////////////////////////////////////////////// //our ray : dGeomID raygeom = dCreateRay(SpaceID(),depth); if (raygeom) { dGeomRaySet(raygeom,originOut.x,originOut.y,originOut.z,dirOut.x,dirOut.y,dirOut.z); } if (!raygeom) { return NULL; } ////////////////////////////////////////////////////////////////////////// //we check through the world : dxBody *bb; for (bb=World()->firstbody; bb; bb=(dxBody*)bb->next) { pRigidBody *bodyB = static_cast<pRigidBody*>(dBodyGetData(bb)); if (bodyB) { dGeomID gid2 = bodyB->GetOdeGeom(); CK3dEntity *ent2 = bodyB->GetVT3DObject(); if (gid2) { dContact *contact = new dContact[1]; int nbContacts = dCollide (raygeom,gid2,1,&contact[0].geom,sizeof(dContactGeom)); if (nbContacts) { if (gid1 && gid2 == gid1 && skipPosRef ) { continue; } pos.x = contact[0].geom.pos[0]; pos.y = contact[0].geom.pos[1]; pos.z = contact[0].geom.pos[2]; normal.x =contact[0].geom.normal[0]; normal.y =contact[0].geom.normal[1]; normal.z = contact[0].geom.normal[2]; return bodyB->GetVT3DObject(); } } } } return NULL; } ////////////////////////////////////////////////////////////////////////// vt3DObjectType pWorld::CIsInCollision(vt3DObjectType a, VxVector& pos, VxVector& normal,float &length) { pWorld *world=GetPMan()->getWorldByBody(a); if (world) { pRigidBody*bodyA= world->getBody(a); if (bodyA) { dGeomID gid1 = bodyA->GetOdeGeom(); if (gid1) { dxBody *bb; for (bb=world->World()->firstbody; bb; bb=(dxBody*)bb->next) { pRigidBody *bodyB = static_cast<pRigidBody*>(dBodyGetData(bb)); if (bodyB==bodyA) { continue; } if (bodyB) { dGeomID gid2 = bodyB->GetOdeGeom(); if (gid1==gid2) { continue; } if (gid2) { dContact *contact = new dContact[1]; int nbContacts = dCollide (gid1,gid2,1,&contact[0].geom,sizeof(dContactGeom)); if (nbContacts) { pos.x = contact[0].geom.pos[0]; pos.y = contact[0].geom.pos[1]; pos.z = contact[0].geom.pos[2]; normal.x =contact[0].geom.normal[0]; normal.y =contact[0].geom.normal[1]; normal.z = contact[0].geom.normal[2]; length = contact[0].geom.depth; return bodyB->GetVT3DObject(); } } } } } } } return NULL; } ////////////////////////////////////////////////////////////////////////// bool pWorld::CIsInCollision(vt3DObjectType a, vt3DObjectType b,VxVector& pos, VxVector& normal,float &length) { bool result = false; pWorld *world=GetPMan()->getWorldByBody(a); pWorld *world2=GetPMan()->getWorldByBody(b); if (!world || !world2 || world!=world2 ) return false; pRigidBody*bodyA= world->getBody(a); pRigidBody*bodyB= world->getBody(b); if (bodyA && bodyB && bodyA !=bodyB) { dGeomID gid1 = bodyA->GetOdeGeom(); dGeomID gid2 = bodyB->GetOdeGeom(); if (gid1 && gid2 && gid1!=gid2) { dContact *contact = new dContact[1]; int nbContacts = dCollide (gid1,gid2,1,&contact[0].geom,sizeof(dContactGeom)); if (nbContacts) { pos.x = contact[0].geom.pos[0]; pos.y = contact[0].geom.pos[1]; pos.z = contact[0].geom.pos[2]; normal.x =contact[0].geom.normal[0]; normal.y =contact[0].geom.normal[1]; normal.z = contact[0].geom.normal[2]; length = contact[0].geom.depth; return true; } } } return result; } */<file_sep>#ifndef __PREREQUISITES_PHYS_X_H__ #define __PREREQUISITES_PHYS_X_H__ class NxCompartment; class NxActor; class NxActorDesc; class NxScene; class NxSceneDescr; class NxUserNotify; class NxFluidUserNotify; class NxCloth; class NxClothDesc; class NxClothUserNotify; class NxClothMeshDesc; class NxSoftBodyUserNotify; class NxUserContactModify; class NxUserTriggerReport; class NxUserContactReport; class NxUserActorPairFiltering; class NxBounds3; class NxUserScheduler; class NxSceneDesc; class NxBodyDesc; class NxShapeDesc; class NxMaterial; class NxMaterialDesc; class NxUserDebugRenderer; class NxTriangleMesh; class NxTriangleMeshDesc; class NxConvexMesh; class NxConvexMeshDesc; class NxUserOutputStream; class NxUserAllocator; class NxJoint; class NxD6Joint; class NxStream; class NxFoundationSDK; class NxCCDSkeleton; //this class doesn't actually exist. class NxSimpleTriangleMesh; class NxHeightField; class NxHeightFieldDesc; class NxPhysicsSDKDesc; class NxPhysicsSDK; class NxMeshData; class NxClothMesh; class NxControllerManager; class NxBoxController; class NxBoxControllerDesc; class NxCapsuleController; class NxCapsuleControllerDesc; class UserAllocator; class NxRemoteDebugger; class NxShape; class NxContactPair; class NxConvexShapeDesc; class NxWheelShape; class NxConvexShape; class NxCapsuleShape; class NxRaycastHit; class NxWheelContactData; #if NX_USE_CLOTH_API class NxClothMesh; #endif #if NX_USE_SOFTBODY_API class NxSoftBodyMesh; #endif //---------------------------------------------------------------- // //! \brief NxU Stream // namespace NXU { class NxActorDesc; class NxuPhysicsCollection; } #endif<file_sep>dofile("ModuleConfig.lua") dofile("ModuleHelper.lua") if _ACTION == "clean" then os.rmdir("./vs*") os.rmdir("../Temp") return end if _ACTION == "help" then premake.showhelp() return end solution "vtTools" configurations { "Debug", "Release" , "ReleaseDebug" } if _ACTION and _OPTIONS["Dev"] then setfields("location","./".._ACTION.._OPTIONS["Dev"]) end packageConfig_Behaviours = { Name = "vtToolkit", Type = "SharedLib", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "_AFXDLL" }, TargetSuffix = "/BuildingBlocks", Files = { D_INCLUDE_ROOT.."*.h" ; D_INCLUDE_ROOT.."Core/**.h" ; D_CORE_SRC.."**.c*"; D_BB_SRC.."**.c*" ; D_BB_SRC.."*.def" }, Includes = { D_STD_INCLUDES ; D_CORE_INCLUDE_DIRS ; D_DIRECTX9.."Include" }, Libs = { "user32" ; "kernel32" ; "dxerr"; "dinput8" ; "dxguid" }, LibDirectories = { D_DIRECTX9.."lib" }, StaticOptions = { "convert" }, Options = { "/W0 /wd4430"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\BuildingBlocks" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\BuildingBlocks" } packageConfig_RemoteConsole = { Name = "vtRemoteConsole", Type = "ConsoleApp", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" }, TargetSuffix = "", Files = { D_INCLUDE_ROOT.."*.h" ; D_INCLUDE_ROOT.."Core/**.h" ; DROOT.."Test/RemoteConsole/*.**"}, Includes = { D_STD_INCLUDES ; D_CORE_INCLUDE_DIRS ; }, Libs = { "ck2" ; "vxmath" ; "user32" ; "kernel32" ; }, LibDirectories = { }, Options = { "/W1"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\BuildingBlocks" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\BuildingBlocks" } createStaticPackage(packageConfig_Behaviours) --createStaticPackage(packageConfig_RemoteConsole) function onclean() print("cleaning") os.rmdir("vs*") end <file_sep>#ifndef _XDISTRIBUTED_3F_H_ #define _XDISTRIBUTED_3F_H_ #include "xDistributedProperty.h" #include "xPoint.h" class xDistributedPoint3F : public xDistributedProperty { public: // typedef xDistributedPropertyBase<Point3F>DataBase; typedef xDistributedProperty Parent; xDistributedPoint3F ( xDistributedPropertyInfo *propInfo, xTimeType maxWriteInterval, xTimeType maxHistoryTime ) : xDistributedProperty(propInfo) { mLastValue = Point3F(0,0,0); mCurrentValue= Point3F(0,0,0); mDifference = Point3F(0,0,0); mLastTime = 0; mCurrentTime = 0; mLastDeltaTime = 0 ; mFlags = 0; mThresoldTicker = 0; } virtual ~xDistributedPoint3F(){} Point3F mLastValue; Point3F mCurrentValue; Point3F mDifference; Point3F mLastServerValue; Point3F mLastServerDifference; bool updateValue(Point3F value,xTimeType currentTime); Point3F getDiff(Point3F value); void pack(xNStream *bstream); void unpack(xNStream *bstream,float sendersOneWayTime); void updateGhostValue(xNStream *stream); void updateFromServer(xNStream *stream); virtual uxString print(TNL::BitSet32 flags); }; #endif <file_sep>#ifndef __PWORLDTYPES_H__ #define __PWORLDTYPES_H__ //################################################################ // // Help structures and types // //---------------------------------------------------------------- // //! \brief Meta info to track a broken joint from a NX-SDK callback to the next frame. // struct pBrokenJointEntry { pJoint*joint; float impulse; CK_ID mAEnt; CK_ID mBEnt; bool isTriggered; int jType; pBrokenJointEntry() { impulse = 0 ; mAEnt = NULL; mBEnt = NULL; jType -1; isTriggered = false; } }; typedef XArray<pBrokenJointEntry*>JointFeedbackListType; /** \addtogroup World @{ */ //---------------------------------------------------------------- // //! \brief Dominance setup for the scene // struct pDominanceSetupItem { struct pDominanceConstraint { float dominanceA; float dominanceB; pDominanceConstraint() : dominanceA(1.0f), dominanceB(0.0f) { } }; pDominanceConstraint constraint; int dominanceGroup0; int dominanceGroup1; pDominanceSetupItem() : dominanceGroup0(0), dominanceGroup1(0) { } }; /** @} */ //################################################################ // // User callbacks // #endif <file_sep>#include "CKAll.h" #include "../MidiManager.h" CKObjectDeclaration *FillBehaviorGetMidiINDevicesDecl(); CKERROR CreateGetMidiINDevicesProto(CKBehaviorPrototype **pproto); int GetMidiINDevices(const CKBehaviorContext& behcontext); /************************************************************************/ /* */ /************************************************************************/ CKObjectDeclaration *FillBehaviorGetMidiINDevicesDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("Get MidiIN Devices"); od->SetDescription("Returns all Midi IN Devices"); od->SetCategory("Controllers/Midi"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5f521403,0x3bef5561)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGetMidiINDevicesProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateGetMidiINDevicesProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Get MidiIN Devices"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Get Next"); proto->DeclareInput("Get Prev"); proto->DeclareOutput("Finish"); proto->DeclareOutput("LoopOut"); proto->DeclareOutParameter("Name",CKPGUID_STRING); proto->DeclareOutParameter("Index",CKPGUID_INT); proto->DeclareOutParameter("Count",CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(GetMidiINDevices); *pproto = proto; return CK_OK; } int indexD = 0; int countD = 0; int GetMidiINDevices(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; CKPluginManager* ThePluginManager=CKGetPluginManager(); CKRenderManager *rm = (CKRenderManager *)ctx->GetRenderManager(); ////////////////////////////////////////////////////////////////////////// if( beh->IsInputActive(0) ){ MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); countD=midiInGetNumDevs(); if( !countD){ mm->m_Context->OutputToConsole("No Midi IN Devices !"); return CK_OK; } beh->ActivateInput(0, FALSE); indexD = 0; beh->ActivateInput(1, TRUE); } ////////////////////////////////////////////////////////////////////////// if( beh->IsInputActive(1) ){ beh->ActivateInput(1, FALSE); if (indexD > (countD-1)){ indexD = 0; beh->ActivateOutput(0,TRUE); return CKBR_OK; } beh->SetOutputParameterValue(1,&indexD); MIDIINCAPS tmp; midiInGetDevCaps(indexD, &tmp,sizeof(tmp) ); indexD++; CKParameterOut *pout2 = beh->GetOutputParameter(0); pout2->SetStringValue( tmp.szPname ); beh->ActivateOutput(1); } return CKBR_OK; } <file_sep>class NxActor; class NxScene; #include <string> #include <NxVec3.h> NxActor* CookASE(const std::string& filename, NxScene* scene, NxVec3 offset = NxVec3(0,0,0), NxVec3 scale = NxVec3(1,1,1)); <file_sep>#ifndef __IMessages_h #define __IMessages_h #include "xNetTypes.h" class Point3F; class Point4F; class xNetInterface; class xNetworkMessage; class IMessages { public: IMessages(xNetInterface *ninterface); xMessageArrayType *getMessages(); xNetInterface * getNetInterface() const { return mNetInterface; } void setNetInterface(xNetInterface * val) { mNetInterface = val; } void addMessage(xMessage*msg); xMessage*getNextOutMessage(); xMessage*getNextInMessage(); xMessage*getNextInMessage(xNString mName); void removeMessage(xMessage*msg); void deleteMessage(xMessage*msg); void deleteAllOldMessages(); int getNumMessagesOfType(int type); int getNumOutMessages(); xMessage*readFromStream(TNL::BitStream *bstream,TNL::BitSet32 flags); void writeToStream(xMessage *msg,TNL::BitStream *bstream,TNL::BitSet32 flags); void advanceTime(float deltaTime); float getMessageTimeout() const { return mMessageTimeout; } void setMessageTimeout(float val) { mMessageTimeout = val; } void checkMessages(); xMessageType *getMessageType(xMessage*message); xMessageType *createMessageType(xMessage*message); void registerMessageType(xNString name,int type,int numParameters); float getThresoldTicker() const { return mThresoldTicker; } void setThresoldTicker(float val) { mThresoldTicker = val; } float getMinSendTime() const { return mMinSendTime; } void setMinSendTime(float val) { mMinSendTime = val; } protected: private: xNetInterface *mNetInterface; float mMessageTimeout; float mThresoldTicker; float mMinSendTime; }; #endif <file_sep>#include "StdAfx.h" #include "vt_python_ext.h" #include "initman.h" extern vt_python_man* pym; ////////////////////////////////////////////////////////////////////////// PyObject* log_CaptureStdout(PyObject* self, PyObject* pArgs) { char* LogStr = NULL; if (!PyArg_ParseTuple(pArgs, "s", &LogStr)) return NULL; if (pym) { pym->m_stdOut << LogStr; } Py_INCREF(Py_None); return Py_None; } ////////////////////////////////////////////////////////////////////////// PyObject* log_CaptureStderr(PyObject* self, PyObject* pArgs) { char* LogStr = NULL; if (!PyArg_ParseTuple(pArgs, "s", &LogStr)) return NULL; if (pym) { pym->m_stdOut << LogStr; } Py_INCREF(Py_None); return Py_None; } ////////////////////////////////////////////////////////////////////////// <file_sep>#include "PCommonDialog.h" #include "resource.h" #include "VITabCtrl.h" #include "VIControl.h" #define LAYOUT_STYLE (WS_CHILD|WS_VISIBLE) #define LAYOUT_ShaderREE 130 RECT _GetNullRect() { return RECT(); } LRESULT CPBCommonDialog::OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam) { LRESULT lResult; return lResult; } void CPBCommonDialog::fillFlags() { BF_Move.SetCheck(true); } void CPBCommonDialog::fillHullType() { HType.AddString("Sphere"); HType.AddString("Box"); HType.AddString("Capsule"); HType.AddString("Plane"); HType.AddString("Convex Mesh"); HType.AddString("Height Field"); HType.AddString("Wheel"); HType.AddString("Cloth"); HType.SetCurSel(0); } namespace vtAgeia { } CKBOOL CPBCommonDialog::On_Init() { fillHullType(); return true; } LRESULT CPBCommonDialog::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_MOUSEWHEEL: { break; } case WM_ERASEBKGND: { /*RECT r; GetClientRect(&r); CDC* pDC=CDC::FromHandle((HDC)wParam); pDC->FillSolidRect(&r,RGB(100,8,100)); */ }break; case CKWM_OK: { } break; case CKWM_INIT: { fillHullType(); } break; } return CDialog::WindowProc(message, wParam, lParam); } void CPBCommonDialog::DoDataExchange(CDataExchange* pDX) { //CDialog::DoDataExchange(pDX); CParameterDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPBCommonDialog) //DDX_Control(pDX, IDC_DYNA_FLAGS_RECT,mDynaFlagsRect); DDX_Control(pDX, IDC_HULLTYPE, HType); DDX_Control(pDX, IDC_LBL_HTYPE, LBL_HType); DDX_Control(pDX, IDC_BFLAGS_MOVING,BF_Move); DDX_Control(pDX, IDC_BFLAGS_GRAV,BF_Grav); DDX_Control(pDX, IDC_BFLAGS_HIERARCHY,BF_Hierarchy); DDX_Control(pDX, IDC_BFLAGS_COLL,BF_Collision); DDX_Control(pDX, IDC_BFLAGS_COLL_NOTIFY,BF_CollisionNotify); DDX_Control(pDX, IDC_BFLAGS_KINEMATIC,BF_Kinematic); DDX_Control(pDX, IDC_BFLAGS_TRIGGER,BF_TriggerShape); DDX_Control(pDX, IDC_BFLAGS_SLEEP,BF_Sleep); DDX_Control(pDX, IDC_BFLAGS_SSHAPE,BF_SubShape); DDX_Control(pDX, IDC_BFLAGS_DEFORMABLE,BF_Deformable); DDX_Control(pDX, IDC_LBL_LFLAGS,LBL_Flags); DDX_Control(pDX, IDC_LBL_FLAGS,LBL_Flags); DDX_Control(pDX, IDC_LBL_DYNAFLAGS,LBL_DFlags); DDX_Control(pDX, IDC_TLFLAGS_POS,TF_POS); DDX_Control(pDX, IDC_TLFLAGS_ROT,TF_ROT); DDX_Control(pDX, IDC_TLFLAGS_POS_X,TF_PX); DDX_Control(pDX, IDC_TLFLAGS_POS_Y,TF_PY); DDX_Control(pDX, IDC_TLFLAGS_POS_Z,TF_PZ); DDX_Control(pDX, IDC_TLFLAGS_ROT_X,TF_RX); DDX_Control(pDX, IDC_TLFLAGS_ROT_Y,TF_RY); DDX_Control(pDX, IDC_TLFLAGS_ROT_Z,TF_RZ); //}}AFX_DATA_MAP } // DoubleParamDialog dialog BEGIN_MESSAGE_MAP(CPBCommonDialog, CParameterDialog) ON_STN_CLICKED(IDC_DYNA_FLAGS_RECT, OnStnClickedDynaFlagsRect) END_MESSAGE_MAP() #include "xEnumerations.h" #include "..\..\include\interface\pcommondialog.h" /*IMPLEMENT_DYNAMIC(CPBCommonDialog, CDialog) CPBCommonDialog::CPBCommonDialog(CKParameter *param, CWnd* pParent) : CDialog(CPBCommonDialog::IDD, pParent) { parameter = param; }*/ BOOL CPBCommonDialog::OnInitDialog() { CParameterDialog::OnInitDialog(); m_tt = new CToolTipCtrl(); m_tt->Create(this); // Add tool tips to the controls, either by hard coded string // or using the string table resource m_tt->AddTool( &BF_Move, _T("This is a tool tip!")); /*m_tt->AddTool( &mDynaFlagsRect, _T("This is a tool tip!")); //m_ToolTip.AddTool( &m_myEdit, IDS_MY_EDIT); m_tt->Activate(TRUE); */ // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } BOOL CPBCommonDialog::PreTranslateMessage(MSG* pMsg) { if(pMsg->message >= WM_MOUSEFIRST && pMsg->message <= WM_MOUSELAST) m_tt->RelayEvent(pMsg); // TODO: Add your specialized code here and/or call the base class return CParameterDialog::PreTranslateMessage(pMsg); } void CPBCommonDialog::OnStnClickedDynaFlagsRect() { m_tt->Activate(TRUE); LPRECT rect; m_tt->GetWindowRect(rect); m_tt->GetWindowRect(rect); } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPJPulleyDecl(); CKERROR CreatePJPulleyProto(CKBehaviorPrototype **pproto); int PJPulley(const CKBehaviorContext& behcontext); CKERROR PJPulleyCB(const CKBehaviorContext& behcontext); enum bbInputs { bI_ObjectB, bI_Anchor0, bI_Anchor1, bI_Pulley0, bI_Pulley0Ref, bI_Pulley1, bI_Pulley1Ref, bI_Stifness, bI_Distance, bI_Ratio, bI_Rigid, bi_Collision, bI_Motor, }; //************************************ // Method: FillBehaviorPJPulleyDecl // FullName: FillBehaviorPJPulleyDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPJPulleyDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJPulley"); od->SetCategory("Physic/Joints"); od->SetDescription("Sets a pulley joint between two bodies."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x43d5361f,0x683f2741)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJPulleyProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJPulleyProto // FullName: CreatePJPulleyProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePJPulleyProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJPulley"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJPulley <br> PJPulley is categorized in \ref Joints <br> <br>See <A HREF="pJPulley.cmo">pJPulley.cmo</A>. <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Creates or modifies a pulley (rope) joint. <br> \image html pulleyJoint.png The pulley joint simulates a rope that can be thrown across a pair of pulleys. In this way, it is similar to the distance joint (the length of the rope is the distance) but the rope doesn't connect the two bodies along the shortest path, rather it leads from the connection point on one actor to the pulley point (fixed in world space), then to the second pulley point, and finally to the other actor. The pulley joint can also be used to simulate a rope around a single point by making the pulley points coincide. Note that a setup where either object attachment point coincides with its corresponding pulley suspension point in world space is invalid. In this case, the simulation would be unable to determine the appropriate direction in which to pull the object and a random direction would result. The simulation will be unstable. Note that it is also invalid to allow the simulation to end up in such a state. <h3>Technical Information</h3> \image html PJPulley.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Body B: </SPAN>The second body. Leave blank to create a joint constraint with the world. <BR> <BR> <SPAN CLASS="pin">Local Anchor A:</SPAN>Sets the attachment point of joint in bodie[0]'s space.See pJointPulley::setLocalAnchorA(). <BR> <SPAN CLASS="pin">Local Anchor B:</SPAN>Sets the attachment point of joint in bodie[1]'s space.See pJointPulley::setLocalAnchorB(). <BR> <SPAN CLASS="pin">Pulley A: </SPAN>Sets the suspension point of joint in world space. See pJointPulley::setPulleyA(). <BR> <SPAN CLASS="pin">Pulley A Reference: </SPAN>Sets the suspension point of joint in local space by using an reference entity. The above vector gets transformed. <BR> <SPAN CLASS="pin">Pulley B: </SPAN>Sets the suspension point of joint in world space.See pJointPulley::setPulleyA(). <BR> <SPAN CLASS="pin">Pulley B Reference: </SPAN>Sets the suspension point of joint in local space by using an reference entity. The above vector gets transformed. <BR> <SPAN CLASS="pin">Stiffness: </SPAN>Sets how stiff the constraint is, between 0 and 1 (stiffest). See pJointPulley::setStiffness(). <BR> <SPAN CLASS="pin">Distance: </SPAN> Sets the rest length of the rope connecting the two objects.See pJointPulley::setDistance(). <BR> \Note The distance is computed as ||(pulley0 - anchor0)|| + ||(pulley1 - anchor1)|| * ratio. <SPAN CLASS="pin">Ratio: </SPAN>.Sets transmission ratio. See pJointPulley::setRatio(). <BR> <SPAN CLASS="pin">Is Rigid: </SPAN>.Set true if the joint also has to maintain a minimum distance, not just a maximum. See pJointPulley::setRigid(). <BR> <SPAN CLASS="pin">Collision: </SPAN>Enables Collision. See pJointPulley::enableCollision(). <BR> <SPAN CLASS="pin">Motor: </SPAN>Motor parameters. See pJointPulley::setMotor(). <BR> <BR> <hr> <BR> <h3>Warning</h3> At least one body must be dynamic. <br> <h3>VSL : Creation </h3><br> <SPAN CLASS="NiceCode"> \include pJPulley.vsl </SPAN> <br> <h3>VSL : Motor Modification </h3><br> <SPAN CLASS="NiceCode"> \include PJRevoluteSetMotor.vsl </SPAN> <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createJointPulley(). #pJointPulley<br> */ proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( PJPulleyCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Local Anchor A",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Local Anchor B",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Pulley A",CKPGUID_VECTOR); proto->DeclareInParameter("Pulley A Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Pulley B",CKPGUID_VECTOR); proto->DeclareInParameter("Pulley B Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Stiffness",CKPGUID_FLOAT); proto->DeclareInParameter("Distance",CKPGUID_FLOAT); proto->DeclareInParameter("Ratio",CKPGUID_FLOAT); proto->DeclareInParameter("Is Rigid",CKPGUID_BOOL); proto->DeclareInParameter("Collision",CKPGUID_BOOL); proto->DeclareInParameter("Motor",VTS_JOINT_MOTOR); proto->DeclareSetting("Motor",CKPGUID_BOOL,"FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PJPulley); *pproto = proto; return CK_OK; } //************************************ // Method: PJPulley // FullName: PJPulley // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJPulley(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Pulley)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA && !worldB) bbErrorME("Couldnt find any world object"); // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); if (!bodyA && !bodyB) bbErrorME("Couldnt find any physic object"); if(bodyA && bodyB) { VxVector anchor0 = GetInputParameterValue<VxVector>(beh,bI_Anchor0); VxVector anchor1 = GetInputParameterValue<VxVector>(beh,bI_Anchor1); VxVector pulley0 = GetInputParameterValue<VxVector>(beh,bI_Pulley0); CK3dEntity*pulley0Ref= (CK3dEntity *) beh->GetInputParameterObject(bI_Pulley0Ref); VxVector pulley1 = GetInputParameterValue<VxVector>(beh,bI_Pulley1); CK3dEntity*pulley1Ref= (CK3dEntity *) beh->GetInputParameterObject(bI_Pulley1Ref); int coll = GetInputParameterValue<int>(beh,bi_Collision); VxVector pulley0Out = pulley0; if (pulley0Ref) pulley0Ref->Transform(&pulley0Out,&pulley0); VxVector pulley1Out = pulley1; if (pulley1Ref) pulley1Ref->Transform(&pulley1Out,&pulley1); float ratio = GetInputParameterValue<float>(beh,bI_Ratio); float stiff = GetInputParameterValue<float>(beh,bI_Stifness); float distance = GetInputParameterValue<float>(beh,bI_Distance); int rigid = GetInputParameterValue<float>(beh,bI_Rigid); pMotor motor; DWORD hasMotor;beh->GetLocalParameterValue(0,&hasMotor); if (hasMotor) { CKParameterIn *par = beh->GetInputParameter(bI_Motor); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { motor = pFactory::Instance()->createMotorFromParameter(rPar); } } } ////////////////////////////////////////////////////////////////////////// // pJointPulley*joint = static_cast<pJointPulley*>(worldA->getJoint(target,targetB,JT_Pulley)); if (!joint) { joint = static_cast<pJointPulley*>(pFactory::Instance()->createPulleyJoint(target,targetB,pulley0Out,pulley1Out,anchor0,anchor1)); if (!joint) { bbErrorMesg("Couldn't create Pulley joint!"); } } ////////////////////////////////////////////////////////////////////////// //joint exists : update : if (joint) { joint->setStiffness(stiff); joint->setRatio(ratio); joint->setRigid(rigid); joint->setDistance(distance); joint->setPulleyA(pulley0Out); joint->setPulleyB(pulley1Out); joint->setLocalAnchorA(anchor0); joint->setLocalAnchorB(anchor1); joint->enableCollision(coll); if (hasMotor) { joint->setMotor(motor); } } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: PJPulleyCB // FullName: PJPulleyCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJPulleyCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD hasMotor; beh->GetLocalParameterValue(0,&hasMotor); beh->EnableInputParameter(bI_Motor,hasMotor); break; } } return CKBR_OK; }<file_sep>// vDevTestUnit.cpp : Defines the entry point for the DLL application. // //#include "stdafx.h" // #include "CKAll.h" #include "Dll_Tools.h" #include <windows.h> #include "VSLManagerSDK.h" #include <typeinfo> #include <tchar.h> #include <shellapi.h> #define DECLAREFUN_6d(ret,func,callconv,dllName,arg1,arg2,arg3,arg4,arg5,arg6){\ DllFunc< ret (*)(arg1,arg2,arg3,arg4,arg5,arg6) > Dllf(dllName,func);\ VSLM->RegisterFunction(func, Dllf ,callconv,6,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6);\ } #define DECLAREFUN_C_6d(ret,func,dllName,arg1,arg2,arg3,arg4,arg5,arg6) DECLAREFUN_6d(ret,func,VCALLTYPE_CDECL,dllName,arg1,arg2,arg3,arg4,arg5,arg6) /* #define DECLAREFUN_0(ret,func,callconv) {\ typedef ret (*fptr)(); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,0,#ret);\ } #define DECLAREFUN_C_0(ret,func) DECLAREFUN_0(ret,func,VCALLTYPE_CDECL) #define DECLAREFUN_S_0(ret,func) DECLAREFUN_0(ret,func,VCALLTYPE_STDCALL) */ bool is=false; template<class T>class Real{ }; template<class T>class tSocket{ public : tSocket(const char*in){ resultT = new Real<void*>(); } T resultT; operator T(){ return resultT; } }; #define DECLAREFUNS_0(ret,func,callconv,dllName) {\ typedef ret (*fptr)(); \ DllFunc<fptr>Dllf(_T(dllName),func);\ fptr rawPtr = (fptr)Dllf; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ is=VSLM->RegisterFunction(func,ptr,callconv,0,#ret);\ } #define DECLAREFUNSS_0(ret,func,dllName) DECLAREFUNS_0(ret,func,VCALLTYPE_CDECL,dllName) CKERROR InitInstanc1e(CKContext* context) { using namespace VSL; VSLManager *VSLM = (VSLManager *)context->GetManagerByGuid(VSLMANAGER_GUID); DECLAREFUNSS_0(void,"testS","base.dll") typedef HINSTANCE(WINAPI *_ShellExec_proto)(HWND,const char *,const char*,const char*,const char *,int); DllFunc<_ShellExec_proto>_ShellExec(_T("shell32.dll"),"ShellExecuteA"); HINSTANCE a = (*_ShellExec)(NULL,"open","www.gmx.net",NULL,NULL, SW_MAXIMIZE); //MessageBox(NULL,"","",0); //typedef void (*ptrF)(); //tSocket<void*>("void"); //DllFunc<ptrF>asd( _T("Base.dll"),"testS"); //VSLM->RegisterFunction( "testS", asd ,VCALLTYPE_CDECL,0,"void"); //(*asd)(); //if (is) //MessageBox(NULL,"succed","",0); //(*_ShellExec)(NULL,"open","www.gmx.net",NULL,NULL, SW_MAXIMIZE); //-) simple and handy, or not ? //DECLAREFUN_C_6d(void,"ShellExecuteA","shell32.dll",int,const char*,const char*,const char*,const char*,int) //base::win32::shell::testS(); //VSLM->RegisterSpace(); //DECLAREFUN_C_0d(void,_ShellExec,"base.dll") // typedef void(*_ShellExec_proto)(); //DllFunc<void(*)()>xas(("Base.dll"),"testS"); return CK_OK; } <file_sep>//////////////////////////////////////////////////////////////////////////////// // // ARTPlusDetectionAndTransformation // --------------------------------- // // Description: // Buildingblock that detects a pattern (single marker) and transforms // the related Object. If the pattern is not detected, the Object will // be hidden. // // Input Parameter: // IN_OBJECT : The related virtools object // IN_VIDEO_TEXTURE : The image, in with ARToolKitPlus // perform the detection // IN_PATTERN_NUMBER : The pattern number, which will // be detected by the BB // IN_PATTERN_WIDTH : The width of the real pattern in mm // IN_USE_BCH : Flag which indicates to use BCH-pattern // (look into ARToolKitPlus for description) // IN_THIN_BORDER : Flag which indicates to use pattern with // a thin boarder) // (look into ARToolKitPlus for description) // IN_AUTO_THRESHOLD : Flag which indicates to use the auto-threshold // function from the ARToolKitPlus // (look into ARToolKitPlus for description) // IN_THRESHOLD : The threshold value used, if IN_AUTO_THRESHOLD // is set to false // // Output Parameter: // OUT_POSITION : Position vector of the detected pattern // OUT_QUATERNION : Rotation, given in quaternions, of the detected // pattern // OUT_MARKERID : The ID of the Pattern, which has been detected. // Should be the same number as IN_PATTERN_NUMBER // OUT_DETECTED : Flag which indicates that the pattern has been // detected in the image or not // OUT_TRANSFORM_MATRIX : The complete transformation matrix. // // // Version 1.0 : First Release // // Known Bugs : None // // Copyright <NAME> <<EMAIL>>, University of Paderborn //////////////////////////////////////////////////////////////////////////////// #include "CKAll.h" #include <ARToolKitPlus/TrackerSingleMarker.h> extern bool ARTPlusInitialized; extern ARToolKitPlus::TrackerSingleMarker *tracker; #define IN_OBJECT 0 #define IN_VIDEO_TEXTURE 1 #define IN_PATTERN_NUMBER 2 #define IN_PATTERN_WIDTH 3 #define IN_USE_BCH 4 #define IN_THIN_BORDER 5 #define IN_AUTO_THRESHOLD 6 #define IN_THRESHOLD 7 #define OUT_POSITION 0 #define OUT_QUATERNION 1 #define OUT_MARKERID 2 #define OUT_DETECTED 3 #define OUT_TRANSFORM_MATRIX 4 CKObjectDeclaration *FillBehaviorARTPlusDetectionAndTransformationDecl(); CKERROR CreateARTPlusDetectionAndTransformationProto(CKBehaviorPrototype **); int ARTPlusDetectionAndTransformation(const CKBehaviorContext& BehContext); CKERROR ARTPlusDetectionAndTransformationCB(const CKBehaviorContext& BehContext); CKObjectDeclaration *FillBehaviorARTPlusDetectionAndTransformationDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Single Marker Detection and Transformation"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetVersion(0x00010000); od->SetCreationFunction(CreateARTPlusDetectionAndTransformationProto); od->SetDescription("Detects Single Marker and Calculates Transformation for given Videoframe"); od->SetCategory("ARToolKitPlus"); od->SetGuid(CKGUID(0x2f9e2472,0x639e208c)); od->SetAuthorGuid(CKGUID(0x653d3e01,0x631c3314)); od->SetAuthorName("<NAME>"); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateARTPlusDetectionAndTransformationProto(CKBehaviorPrototype** pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Single Marker Detection and Transformation"); if(!proto) return CKERR_OUTOFMEMORY; //--- Inputs declaration proto->DeclareInput("In"); //--- Outputs declaration proto->DeclareOutput("Out"); //----- Input Parameters Declaration proto->DeclareInParameter("Object", CKPGUID_3DENTITY); proto->DeclareInParameter("Video Texture",CKPGUID_TEXTURE); proto->DeclareInParameter("Pattern Number",CKPGUID_INT, "0"); proto->DeclareInParameter("Pattern Width (cm)", CKPGUID_FLOAT, "8.0"); proto->DeclareInParameter("Use BCH Pattern", CKPGUID_BOOL, "TRUE"); proto->DeclareInParameter("Use Thin Border", CKPGUID_BOOL, "TRUE"); proto->DeclareInParameter("Enable Auto Threshold", CKPGUID_BOOL, "FALSE"); proto->DeclareInParameter("Threshold", CKPGUID_INT, "150"); //--- Output Parameters Declaration proto->DeclareOutParameter("Position",CKPGUID_VECTOR); proto->DeclareOutParameter("Quaternion",CKPGUID_QUATERNION); proto->DeclareOutParameter("Marker ID",CKPGUID_INT, "-1"); proto->DeclareOutParameter("Detected",CKPGUID_BOOL, FALSE); proto->DeclareOutParameter("Transformation Matrix",CKPGUID_MATRIX); //---- Local Parameters Declaration //---- Settings Declaration proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorCallbackFct(ARTPlusDetectionAndTransformationCB,CKCB_BEHAVIORBASE|CKCB_BEHAVIOREDITIONS|CKCB_BEHAVIORPAUSE|CKCB_BEHAVIORREADSTATE|CKCB_BEHAVIORRESET|CKCB_BEHAVIORACTIVATESCRIPT|CKCB_BEHAVIORDEACTIVATESCRIPT|CKCB_BEHAVIORRESUME|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORNEWSCENE,NULL); proto->SetFunction(ARTPlusDetectionAndTransformation); *pproto = proto; return CK_OK; } int ARTPlusDetectionAndTransformation(const CKBehaviorContext& BehContext) { CKBehavior* beh = BehContext.Behavior; CKTexture* texture = NULL; CKBYTE *pixel = NULL; CKBOOL detected = FALSE; int patternID = -1; int markerId = -1; float* buffer = NULL; float patternWidth = 8.0f; CKBOOL useBCH = TRUE; CKBOOL thinBorder = TRUE; CKBOOL autoThreshold = FALSE; int threshold = 150; CK3dEntity* Object = NULL; VxQuaternion quat = VxQuaternion(); VxVector pos = VxVector(); VxVector scale = VxVector(); float gl_para[4][4] = { {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f} }; float gl_tmp[4][4] = { {0.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 0.0f} }; float koordSys[4][4] = { {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f} }; float koordSys2[4][4] = { {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, -1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f} }; beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); if(ARTPlusInitialized == true) { // PatterID beh->GetInputParameterValue(IN_PATTERN_NUMBER, &patternID); // Get object Object = CK3dEntity::Cast(beh->GetInputParameterObject(IN_OBJECT)); if(Object==NULL) return CKBR_BEHAVIORERROR; // Get texture texture = CKTexture::Cast(beh->GetInputParameterObject(IN_VIDEO_TEXTURE)); if(texture == NULL) return CKBR_BEHAVIORERROR; // Get pattern width beh->GetInputParameterValue(IN_PATTERN_WIDTH, &patternWidth); // define size of the marker tracker->setPatternWidth(patternWidth); // Get the type of pattern beh->GetInputParameterValue(IN_USE_BCH, &useBCH); // Get value for thin border beh->GetInputParameterValue(IN_THIN_BORDER, &thinBorder); if(useBCH) { // the marker in the BCH test image has a thin border... tracker->setBorderWidth(0.125f); } else { tracker->setBorderWidth(thinBorder ? 0.125f : 0.250f); } // switch to simple ID based markers // use the tool in tools/IdPatGen to generate markers tracker->setMarkerMode(useBCH ? ARToolKitPlus::MARKER_ID_BCH : ARToolKitPlus::MARKER_ID_SIMPLE); // Get auto threshold beh->GetInputParameterValue(IN_AUTO_THRESHOLD, &autoThreshold); // Set auto thresholding in ARToolKitPlus tracker->activateAutoThreshold(autoThreshold?true:false); pixel = texture->LockSurfacePtr(); if(pixel == NULL) return CKBR_BEHAVIORERROR; // here we go, just one call to find the camera pose markerId = tracker->calc(pixel, patternID); //markerId = tracker->calc(pixel); //float conf = (float)tracker->getConfidence(); if(texture->Restore() != TRUE) return CKBR_BEHAVIORERROR; if(markerId==patternID) { // use the result of calc() to setup the OpenGL transformation buffer = (float *)tracker->getModelViewMatrix(); detected = TRUE; for( int j = 0; j < 4; j++ ) { for( int i = 0; i < 4; i++ ) { gl_para[j][i] = buffer[j*4+i]; } } for( int j = 0; j < 4; j++ ) { for( int i = 0; i < 4; i++ ) { gl_tmp[j][i] = 0.0; for(int k=0 ; k<4 ; k++) { gl_tmp[j][i] += koordSys[j][k]*gl_para[k][i]; } } } for( int j = 0; j < 4; j++ ) { for( int i = 0; i < 4; i++ ) { gl_para[j][i] = 0.0; for(int k=0 ; k<4 ; k++) { gl_para[j][i] += gl_tmp[j][k]*koordSys2[k][i]; } } } } // Set boolean beh->SetOutputParameterValue(OUT_DETECTED, &detected, 0); // Set marker id beh->SetOutputParameterValue(OUT_MARKERID, &markerId, 0); VxMatrix mat = VxMatrix(gl_para); Vx3DDecomposeMatrix(mat, quat, pos, scale); // Set position beh->SetOutputParameterValue(OUT_POSITION, &pos, 0); // Set quaternion beh->SetOutputParameterValue(OUT_QUATERNION, &quat, 0); // Set matrix beh->SetOutputParameterValue(OUT_TRANSFORM_MATRIX, &mat, 0); //Set visibility if the Object if(detected==TRUE) { // transform object if marker is detected Object->SetPosition(&pos, NULL, FALSE); Object->SetQuaternion(&quat, NULL, FALSE, FALSE); Object->Show(CKSHOW); } else { Object->Show(CKHIERARCHICALHIDE); } } return CKBR_OK; } CKERROR ARTPlusDetectionAndTransformationCB(const CKBehaviorContext& BehContext) { switch (BehContext.CallbackMessage) { case CKM_BEHAVIORATTACH: break; case CKM_BEHAVIORDELETE: break; case CKM_BEHAVIORDETACH: break; case CKM_BEHAVIORRESUME: break; case CKM_BEHAVIORPAUSE: break; case CKM_BEHAVIORRESET: break; case CKM_BEHAVIORSETTINGSEDITED: break; case CKM_BEHAVIOREDITED: break; case CKM_BEHAVIORLOAD: break; case CKM_BEHAVIORACTIVATESCRIPT: break; case CKM_BEHAVIORDEACTIVATESCRIPT: break; case CKM_BEHAVIORNEWSCENE: break; case CKM_BEHAVIORREADSTATE: break; default: return CKBR_OK; } return CKBR_OK; } <file_sep>import string import vt currentIndex = 0; def loop(): global currentIndex print (currentIndex) maxcount = vt.GetInVal(bid,3) startindex = vt.GetInVal(bid,4) step = vt.GetInVal(bid,5) currentIndex +=step vt.SetOutVal(bid,0,currentIndex) count = (currentIndex-startindex)/step if count >= maxcount: currentIndex = 0 vt.ActivateOut(bid,0,1) else: vt.ActivateOut(bid,2,1) print(count) def counter(): if vt.IsInputActive(bid,0) : global currentIndex currentIndex = 0 loop() if vt.IsInputActive(bid,1) : loop() <file_sep>#include "virtools/vtcxglobal.h" #include "windows.h" #include "vt_python_funcs.h" #include <iostream> #include "pyembed.h" #include "initman.h" #include "vtTools.h" #include "vt_python_ext.h" extern vt_python_man* pym; //************************************ // Method: syspath_append // FullName: syspath_append // Access: public // Returns: void // Qualifier: // Parameter: char *dirname //************************************ int syspath_append( char *dirname ) { PyObject *mod_sys, *dict, *path, *dir; PyErr_Clear( ); dir = Py_BuildValue( "s", dirname ); mod_sys = PyImport_ImportModule( "sys" ); /* new ref */ dict = PyModule_GetDict( mod_sys ); /* borrowed ref */ path = PyDict_GetItemString( dict, "path" ); /* borrowed ref */ if( !PyList_Check( path ) ) return 0; PyList_Append( path, dir ); if( PyErr_Occurred( ) ) Py_FatalError( "could not build sys.path" ); Py_DECREF( mod_sys ); return 1; } //************************************ // Method: vt_ActivateOut // FullName: vt_ActivateOut // Access: public static // Returns: PyObject * // Qualifier: // Parameter: PyObject * self // Parameter: PyObject * args //************************************ static PyObject *vt_ActivateOut( PyObject * self, PyObject * args ) { int size = PyTuple_Size(args); int bid, index, value; PyArg_ParseTuple(args, "iii", &bid, &index, &value); CK_ID cid = bid; CKBehavior *beh = static_cast<CKBehavior*>(pym->m_Context->GetObject(cid)); if (size!=3) { pym->m_Context->OutputToConsoleEx("PyError:%s : This function only accepts 3 arguments : \n\t bid,index,value ",beh->GetName()); Py_RETURN_NONE; } if(beh && index < beh->GetOutputCount()) { beh->ActivateOutput(index,value); } Py_RETURN_NONE; } //************************************ // Method: vt_SetOutVal // FullName: vt_SetOutVal // Access: public static // Returns: PyObject * // Qualifier: // Parameter: PyObject * self // Parameter: PyObject * args //************************************ static PyObject *vt_SetOutVal( PyObject * self, PyObject * args ) { int size = PyTuple_Size(args); PyObject *val; int bid, index; PyArg_ParseTuple(args, "iiO", &bid, &index,&val); CK_ID cid = bid; CKBehavior *beh = static_cast<CKBehavior*>(pym->m_Context->GetObject(cid)); if (size!=3) { pym->m_Context->OutputToConsole("PyError : This function only accepts 3 arguments : \n\t bid,index,value "); Py_RETURN_NONE; } using namespace vtTools; if (beh && val && index < beh->GetOutputParameterCount() ) { if (PyInt_Check(val)) { long ret = PyInt_AsLong(val); int retx = static_cast<int>(ret); beh->SetOutputParameterValue(index,&retx); Py_RETURN_NONE; } if (PyFloat_Check(val)) { double ret = PyFloat_AsDouble(val); float retx = static_cast<float>(ret); beh->SetOutputParameterValue(index,&retx); Py_RETURN_NONE; } if (PyString_Check(val)) { std::string ret; CKParameterOut * pout = beh->GetOutputParameter(index); XString retx(ret.c_str()); pout->SetStringValue(retx.Str()); Py_RETURN_NONE; } if (PyTuple_Check(val)) { std::string outList = to_string(val); CKParameterOut * pout = beh->GetOutputParameter(index); XString retx(outList.c_str()); pout->SetStringValue(retx.Str()); Py_RETURN_NONE; } } Py_RETURN_NONE; } //************************************ // Method: vt_GetInVal // FullName: vt_GetInVal // Access: public static // Returns: PyObject * // Qualifier: // Parameter: PyObject * self // Parameter: PyObject * args //************************************ static PyObject *vt_GetInVal( PyObject * self, PyObject * args ) { int size = PyTuple_Size(args); int bid, index; PyArg_ParseTuple(args, "ii", &bid, &index); CK_ID cid = bid; CKBehavior *beh = static_cast<CKBehavior*>(pym->m_Context->GetObject(cid)); if (size!=2) { pym->m_Context->OutputToConsole("PyError : This function needs 2 arguments : \n\t bid,index"); Py_RETURN_NONE; } using namespace vtTools; using namespace vtTools::Enums; CKParameterManager *pam = static_cast<CKParameterManager *>(pym->m_Context->GetParameterManager()); if (index < beh->GetInputParameterCount() ) { CKParameterIn *ciIn = beh->GetInputParameter(index); CKParameterType pType = ciIn->GetType(); vtTools::Enums::SuperType sType = ParameterTools::GetVirtoolsSuperType(pym->m_Context,pam->ParameterTypeToGuid(pType)); PyObject *val; switch (sType) { case vtSTRING: { val = PyString_FromString( vtTools::BehaviorTools::GetInputParameterValue<CKSTRING>(beh,index )); break; } case vtFLOAT: { val = PyFloat_FromDouble(static_cast<float>(vtTools::BehaviorTools::GetInputParameterValue<float>(beh,index ))); break; } case vtINTEGER: { val = PyInt_FromLong( static_cast<long>(vtTools::BehaviorTools::GetInputParameterValue<int>(beh,index ))); break; } default : XString err("wrong input parameter type: "); err << ciIn->GetName() << "Only Types derivated from Interger,Float or String are acceptable"; pym->m_Context->OutputToConsole(err.Str(),FALSE ); Py_RETURN_NONE; } if (!val) { Py_DECREF(val); } return val; } Py_RETURN_NONE; } PyObject *vt_IsInputActive( PyObject * self, PyObject * args ) { PyObject *arg; int size = PyTuple_Size(args); int bid, index, value; PyArg_ParseTuple(args, "ii", &bid, &index); CK_ID cid = bid; if (size!=2) { pym->m_Context->OutputToConsole("PyError : This function only accepts 2 arguments : \n\t bid,index "); Py_RETURN_NONE; } CKBehavior *beh = static_cast<CKBehavior*>(pym->m_Context->GetObject(cid)); if(beh && index < beh->GetInputCount()) { return Py_BuildValue( "i", beh->IsInputActive(index) ? 1:0 ); } Py_RETURN_NONE; } static struct PyMethodDef vt_methods[] = { {"ActivateOut", vt_ActivateOut, METH_VARARGS, NULL}, {"SetOutVal", vt_SetOutVal, METH_VARARGS, NULL}, {"GetInVal", vt_GetInVal, METH_VARARGS, NULL}, {"IsInputActive", vt_IsInputActive, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; void VTPy_Init(void); static struct _inittab VTy_Inittab_Modules[] = { {"vt", VTPy_Init}, {NULL, NULL} }; void VTPy_Init(void) { PyObject *module; PyObject *dict, *smode, *SpaceHandlers, *UnpackModes; module = Py_InitModule3("vt", vt_methods,"The main vt module"); } int vt_python_man::InitPythonModules() { return vpInitModules(); } int vpInitModules() { return PyImport_ExtendInittab(VTy_Inittab_Modules); } //************************************ // Method: PythonLoad // FullName: PythonLoad // Access: public // Returns: void // Qualifier: //************************************ bool PythonLoad() { bool result = false; if (!pym->pLoaded) { int argc = 1; char *cmd =GetCommandLineA(); char *c1[1]; c1[0]=new char[256]; strcpy(c1[0],cmd); result = !pym->InitPythonModules(); pym->py = new Python(argc,c1); pym->pLoaded = true; PySetupStdRedirect(); } return result; } static PyMethodDef logMethods[] = { { "CaptureStdout", log_CaptureStdout, METH_VARARGS, "Logs stdout" }, { "CaptureStderr", log_CaptureStderr, METH_VARARGS, "Logs stderr" }, { NULL, NULL, 0, NULL } }; void PySetupStdRedirect() { Py_InitModule("log", logMethods); PyRun_SimpleString("import log\n" "import sys\n" "class StdoutCatcher:\n" "\tdef write(self, str):\n" "\t\tlog.CaptureStdout(str)\n" "class StderrCatcher:\n" "\tdef write(self, str):\n" "\t\tlog.CaptureStderr(str)\n" "sys.stdout = StdoutCatcher()\n" "sys.stderr = StderrCatcher()\n" ); } //************************************ // Method: vpCInit // FullName: vpCInit // Access: public // Returns: void // Qualifier: //************************************ int vpCInit() { Py_Initialize(); return true; } //************************************ // Method: vpCPyRun_SimpleString // FullName: vpCPyRun_SimpleString // Access: public // Returns: void // Qualifier: // Parameter: const char*cmd //************************************ void vpCPyRun_SimpleString(const char*cmd) { PyRun_SimpleString(cmd); } //************************************ // Method: vpCPy_Finalize // FullName: vpCPy_Finalize // Access: public // Returns: void // Qualifier: //************************************ void DestroyPython() { if (pym->pLoaded) { if (pym->py) { } } if ( pym->py && pym->py->GetModule()) { Py_XDECREF(pym->py->module); pym->py->module = NULL; } pym->pLoaded = false; Py_Finalize(); } <file_sep>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* */ /* D L L F T P */ /* */ /* W I N D O W S */ /* */ /* P o u r A r t h i c */ /* */ /* V e r s i o n 3 . 0 */ /* */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* ---------------------- */ /* Transferts de Fichiers */ /* ---------------------- */ #define FTP4W_INCLUDES_AND_GENERAL + #include <windows.h> #include <windowsx.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <tcp4w.h> /* external header file */ #include "port32.h" /* 16/32 bits */ #include "ftp4w.h" /* external header file */ #include "ftp4w_in.h" /* internal header file */ #include "rfc959.h" /* only for error codes */ extern LPProcData pFirstProcData; /* ----------------------------------------------------------- */ /* FtpCloseFileTransfer: Ferme les ressources Winsockets */ /* ouvertes pour un transfert de fichier */ /* le fichier est également fermé */ /* Si bFlush est a TRUE, la socket de */ /* données est vidée. */ /* ----------------------------------------------------------- */ int FtpCloseFileTransfer (LPProcData pProcData, BOOL bFlush) { int Rc; _lclose (pProcData->File.hf); /* close file */ pProcData->File.hf = HFILE_ERROR; /* close listen socket */ /* flush received buffer */ if (bFlush) { do Rc = TcpRecv ( pProcData->ftp.data_socket, pProcData->File.szBuf, sizeof pProcData->File.szBuf, min (5, pProcData->ftp.nTimeOut), HFILE_ERROR ); while (Rc > 0); } /* bFlush */ /* close opened sockets */ return TcpClose(&pProcData->ftp.data_socket)==0 ? FTPERR_OK : FTPERR_CANTCLOSE; } /* FtpCloseFileTransfer */ /* ------------------------------------------------------------ */ /* Utilitaire GetFTPListenSocket */ /* ouvre une socket en réception */ /* based on WINTEL (ftp.c) and BSD (ftp.c) */ /* Retourne un numéro de socket */ /* Si erreur de la pile TCP : INVALID_SOCKET */ /* Si erreur de communication: INVALID_ANSWER */ /* ------------------------------------------------------------ */ SOCKET GetFTPListenSocket(LPFtpData pFtpData) { SOCKET listen_skt; int iLength, Rc; LPSTR a, p; char szTmp2 [sizeof "PORT 255,255,255,255,255,255"]; unsigned short NonPrivPort; /* a non priviliged port chosen by system */ struct sockaddr_in saTmpAddr; NonPrivPort = 0; Rc = TcpGetListenSocket (& listen_skt, NULL, & NonPrivPort, 1); if (Rc != TCP4U_SUCCESS) return INVALID_SOCKET; p = (LPSTR) & NonPrivPort; /* inform remote end about our port that we created. */ iLength = sizeof (saTmpAddr); getsockname(pFtpData->ctrl_socket, (LPSOCKADDR) &saTmpAddr, &iLength); a = (LPSTR) & saTmpAddr.sin_addr; #define UC(b) (((int)b)&0xff) wsprintf (szTmp2, "PORT %d,%d,%d,%d,%d,%d", UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), UC(p[1]), UC(p[0]) ); /* on envoie la requete et on attend la réponse */ if ( TnSend (pFtpData->ctrl_socket, szTmp2, FALSE, pFtpData->hLogFile) !=TN_SUCCESS || IntFtpGetAnswerCode (pFtpData) != 200 ) { closesocket (listen_skt); return (SOCKET) INVALID_ANSWER; } return listen_skt; } /* GetFTPListenSocket */ /* ------------------------------------------------------------ */ /* Utilitaire GetFTPConnectSocket */ /* Prépare une socket pour le connect */ /* Retourne un numéro de socket */ /* Si erreur de la pile TCP : INVALID_SOCKET */ /* Si erreur de communication: INVALID_ANSWER */ /* Si erreur dans passive mode:INVALID_MODE */ /* ------------------------------------------------------------ */ SOCKET GetFTPConnectSocket(LPFtpData pFtpData) { int nCount; int Rc; SOCKET connect_skt; LPSTR a, p1, p2; /* a comme adress IP, p comme port */ unsigned short nPort; if ( TnSend (pFtpData->ctrl_socket, "PASV", FALSE, pFtpData->hLogFile) !=TN_SUCCESS) return (SOCKET) INVALID_ANSWER; Rc = IntFtpGetAnswerCode (pFtpData); if (Rc != 227 ) /* 227 seul retour acceptable */ { switch (Rc) { case 500 : case 502 : return (SOCKET) INVALID_MODE; default : return (SOCKET) INVALID_ANSWER; } } /* Retour command PASV incorrect */ /* Réponse du type : 227 Entering Passive Mode (0,0,0,0,12,56) */ a = strchr (& pFtpData->szInBuf [4], '('); if (a==NULL) return (SOCKET) INVALID_ANSWER; /* transforme les 3 premiers ',' en '.' */ for ( p1=strchr(++a,','), nCount=0; p1!=NULL && nCount<3; nCount++) { *p1++='.'; p1 = strchr(p1, ','); } if (p1==NULL) return (SOCKET) INVALID_ANSWER; /* mauvaise chaine */ *p1++=0; /* fin de chaine et p pointe sur la chaine Port*/ if ( (p2=strchr(p1, ','))==NULL ) return (SOCKET) INVALID_ANSWER; *p2++=0; nPort = atoi (p1) * 256 + atoi(p2); Rc = TcpConnect (& connect_skt, a, NULL, & nPort); return Rc==TCP4U_SUCCESS ? connect_skt : INVALID_SOCKET; } /* GetFTPConnectSocket */ /* ------------------------------------------------------------ */ /* Tools Fonction ToolsSetDataConnection () */ /* etablit une connexion sur le port 20 */ /* A l'aide de GetFTPlistenScket */ /* Modifie les éléments suivants : */ /* - pProcData->File.hf */ /* - pProcData->ftp.saAcceptAddr */ /* - pProcData->ftp.cType */ /* - pProcData->ftp.data_socket */ /* ------------------------------------------------------------ */ int ToolsSetDataConnection (LPProcData pProcData, LPCSTR szLocalFile, int nMode, char cBinAscMode, long lByteCount, LPSTR szCmdString) { SOCKET tmp_socket; /* socket d'aide à la création de la connexion data */ HFILE hFile = HFILE_ERROR; int Rc, wErrMsg; /* ferme le fichier de la précédent connexion si besoin */ if (pProcData->File.hf!=HFILE_ERROR) _lclose (pProcData->File.hf); pProcData->File.hf = HFILE_ERROR; pProcData->File.bAborted = FALSE; /* changement de type (ASCII / binaire) */ if (cBinAscMode==TYPE_I || cBinAscMode==TYPE_A || cBinAscMode==TYPE_L8) { Rc=FtpSetType (cBinAscMode); if (Rc!=FTPERR_OK) return Rc; } /* Ouverture du fichier local */ if (szLocalFile!=NULL) { switch (nMode) { case FTPMODE_WRITE : hFile = _lcreat (szLocalFile, 0); break; case FTPMODE_APPEND : hFile = _lopen (szLocalFile, OF_WRITE); if (hFile==HFILE_ERROR) hFile = _lcreat (szLocalFile, 0); else _llseek (hFile, 0, SEEK_END); break; case FTPMODE_READ : hFile = _lopen (szLocalFile, OF_READ); break; default : hFile = HFILE_ERROR; break; } if (hFile == HFILE_ERROR) return FTPERR_CANTOPENLOCALFILE; } /* szLocalFile non Nul */ /* demande de la socket de connexion : distinction mode passif/mode classique */ if (pProcData->ftp.bPassif) tmp_socket = GetFTPConnectSocket (& pProcData->ftp); else tmp_socket = GetFTPListenSocket (& pProcData->ftp); /* discussion sur les cas d'erreur */ switch (tmp_socket) { case INVALID_SOCKET : /* error in socket calls */ _lclose (hFile); return pProcData->ftp.bPassif ? FTPERR_CANTCREATESOCKET : FTPERR_DATACONNECTION ; case INVALID_MODE : /* Server does not support passive mode */ _lclose (hFile); return FTPERR_PASVCMDNOTIMPL ; case INVALID_ANSWER : /* error in answer */ _lclose (hFile); return FTPERR_UNEXPECTEDANSWER; } /* tmp_socket en erreur */ if (lByteCount>0) { Rc = FtpRestart (lByteCount); if (Rc != FTPERR_RESTARTOK) { _lclose (hFile); return Rc; } } /* Commande Restart */ /* envoi de la requete Get/Put/Dir */ Rc = TnSend ( pProcData->ftp.ctrl_socket, szCmdString, FALSE, pProcData->ftp.hLogFile ); if (Rc!=TN_SUCCESS) { _lclose (hFile); TcpClose (& tmp_socket); return FTPERR_SENDREFUSED; } Rc = IntFtpGetAnswerCode ( & pProcData->ftp ); if (Rc!=150 && Rc!=125) /* 150 et 125 seules réponses autorisées */ { switch (Rc) { case -1 : wErrMsg = FTPERR_NOREPLY; break; case 550 : wErrMsg = FTPERR_NOREMOTEFILE; break; case 553 : wErrMsg = FTPERR_TRANSFERREFUSED; break; default : wErrMsg = FTPERR_UNEXPECTEDANSWER;break; } _lclose (hFile); if (pProcData->ftp.bPassif) WSACancelBlockingCall (); TcpClose (& tmp_socket); return wErrMsg; } /* discussion des cas d'erreur */ /* mode classique, il reste à attendre la connexion */ if (! pProcData->ftp.bPassif) { Rc = TcpAccept (& pProcData->ftp.data_socket, tmp_socket, pProcData->ftp.nTimeOut); /* fermeture de la socket d'attente de connexion */ TcpClose (& tmp_socket); if (Rc != TCP4U_SUCCESS) { _lclose (hFile); /* fermeture fichier */ return HAS_ABORTED() ? FTPERR_CANCELBYUSER : FTPERR_DATACONNECTION; } } /* mode classique */ else pProcData->ftp.data_socket = tmp_socket; pProcData->File.hf = hFile; return FTPERR_OK; } /* ToolsSetDataConnection */ /* ------------------------------------------------------------ */ /* Tools Fonction AbortAction () */ /* Traitement Asynchrone de l'abort ou de */ /* certains accidents comme plus d'espace */ /* disque */ /* ------------------------------------------------------------ */ int AbortAction (LPProcData pProcData, BOOL bFlush, BOOL bMsg, UINT nDbg) { int Rc; /* =====> Premier cas : FtpRelease a été appelé -> */ #ifdef TRACE_ABORT char szTmp[50]; wsprintf (szTmp, "Abort n° %d -> %d/%d", nDbg, pProcData->File.bAborted, IsBadWritePtr(pProcData, sizeof *pProcData) ); MessageBox (pProcData->hParentWnd, szTmp, "DLL", MB_OK); #endif if (pProcData->ftp.bVerbose) Ftp4w_Trace (NULL, "entering AbortAction, Debug pos %d", nDbg); if (IsBadWritePtr (pProcData, sizeof *pProcData)) return 0; /* reset flag */ pProcData->File.bAborted = FALSE; /* =====> Soit un réél Abort, warning to server */ do { /* emission prioritaire de Abort */ Rc = TnSend ( pProcData->ftp.ctrl_socket, "ABOR", TRUE, pProcData->ftp.hLogFile ); Rc = IntFtpGetAnswerCode ( & pProcData->ftp ); } while (Rc==500); Rc = IntFtpGetAnswerCode ( & pProcData->ftp ); /* close sockets and files */ FtpCloseFileTransfer (pProcData, bFlush); /* send Message if AsynchronousMode */ if (bMsg && pProcData->File.bAsyncMode) PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, TRUE, (LPARAM) FTPERR_CANCELBYUSER); TcpFlush (pProcData->ftp.ctrl_socket); return Rc; } /* AbortAction */ /* ******************************************************************* */ /* */ /* Partie VI : Utilisation de la fenêtre FTP */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------- */ /* CALBACK */ /* The Data transfer are not logged */ /* ------------------------------------------------------------- */ LRESULT _export PASCAL FAR DLLWndProc (HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { LPProcData pProcData; int Rc, iRetCode=0; int nRead=0, nWritten=0; LPSTR p; pProcData = FtpDataPtr (); if (pProcData==NULL) return (LRESULT) DefWindowProc (hWnd,Msg,wParam,lParam); /* ------- */ /* ABORT ? */ /* ------- */ if ( HAS_ABORTED() && (Msg==WMFTP_RECV || Msg==WMFTP_SEND ||Msg==WMFTP_DIR) ) { AbortAction (pProcData, Msg!=WMFTP_SEND, TRUE, 1); return 0l; } /* Abort */ switch (Msg) { /* Essentiel pour windows 3.1 */ case WM_TIMER : KillTimer (hWnd, wParam); PostMessage (hWnd, wParam, 0, 0l); break; /* ---------------- */ /* Suite du fichier */ /* ---------------- */ case WMFTP_SEND : nRead = _lread (pProcData->File.hf, pProcData->File.szBuf, sizeof pProcData->File.szBuf ); /* lecture OK */ if (nRead > 0) { pProcData->File.lPos += (LONG) nRead; Rc = TcpSend (pProcData->ftp.data_socket, pProcData->File.szBuf, nRead, 0, HFILE_ERROR); if (Rc == TCP4U_SUCCESS) /* envoi OK */ { /* on envoie un message à la fenêtre FTP */ if ( ++pProcData->File.nCount % FTP_RATE(pProcData) != 0 || ! SetTimer (pProcData->hFtpWnd, WMFTP_SEND, pProcData->File.nDelay, NULL) ) PostMessage (pProcData->hFtpWnd, WMFTP_SEND, 0, (LPARAM) pProcData); /* on envoie un message à l'utilisateur */ if (pProcData->File.bNotify) PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, FALSE, pProcData->File.lPos ); } /* TcpSend OK */ /* Fin du fichier */ else /* problem */ { /* Abort can happen during send */ if HAS_ABORTED() AbortAction (pProcData, FALSE, TRUE, 2); else { FtpCloseFileTransfer (pProcData, FALSE); PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, TRUE, (LPARAM) FTPERR_SENDREFUSED); break; } } } /* lecture du fichier possible */ else /* fin de fichier */ { FtpCloseFileTransfer (pProcData, FALSE); Rc = IntFtpGetAnswerCode ( & pProcData->ftp ); switch (Rc) { case 250 : case 226 : iRetCode = FTPERR_OK ; break; case 452 : case 552 : iRetCode = FTPERR_CANTWRITE ; break; default : iRetCode = FTPERR_UNEXPECTEDANSWER; break; } PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, TRUE, (LPARAM) iRetCode); } break; case WMFTP_RECV : nRead = TcpRecv (pProcData->ftp.data_socket, pProcData->File.szBuf, sizeof pProcData->File.szBuf, pProcData->ftp.nTimeOut, HFILE_ERROR); /* Abort during receive */ if HAS_ABORTED() { AbortAction (pProcData, TRUE, TRUE, 3); break; } /* Abort */ /* ---------------- */ /* Suite du fichier */ /* ---------------- */ if ( nRead > 0 && (nWritten = _lwrite (pProcData->File.hf, pProcData->File.szBuf, nRead) ) == nRead ) { pProcData->File.lPos += (LONG) nWritten; if ( ++pProcData->File.nCount % FTP_RATE(pProcData) != 0 || ! SetTimer (pProcData->hFtpWnd, WMFTP_RECV, pProcData->File.nDelay, NULL) ) PostMessage (pProcData->hFtpWnd, WMFTP_RECV, 0, (LPARAM) pProcData); /* on envoie un message à l'utilisateur */ if (pProcData->File.bNotify) PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, FALSE, pProcData->File.lPos ); } /* TcpRecv and write OK */ else /* fin de données */ { if (nRead>0 && nWritten!=nRead) /* erreur d'ecriture */ { AbortAction (pProcData, TRUE, FALSE, 4); iRetCode=FTPERR_CANTWRITE; } else { FtpCloseFileTransfer (pProcData, FALSE); Rc = IntFtpGetAnswerCode ( & pProcData->ftp ); if (nRead == 0) /* fin de transfert */ switch (Rc) { case 226 : case 250 : iRetCode = FTPERR_OK ; break; default : iRetCode = FTPERR_UNEXPECTEDANSWER; } else iRetCode = FTPERR_DATACONNECTION; } PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, TRUE, (LPARAM) iRetCode); } /* end of data transfer or error */ break; /* Dir : Mode trame (sinon receive classique) */ case WMFTP_DIR : nRead = TnReadLine (pProcData->ftp.data_socket, pProcData->File.szBuf, sizeof pProcData->File.szBuf, pProcData->ftp.nTimeOut, HFILE_ERROR ); if HAS_ABORTED() { AbortAction (pProcData, TRUE, TRUE, 5); break; } /* Abort */ /* --------------------------------- */ /* Suite de la lecture du répertoire */ /* --------------------------------- */ p = strchr (pProcData->File.szBuf, '\r'); if (p!=NULL) *p = 0; if (nRead > 0) { /* on envoie un message à l'utilisateur */ PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, FALSE, (LPARAM) pProcData->File.szBuf); if ( ++pProcData->File.nCount % FTP_DIRRATE(pProcData) != 0 || ! SetTimer (pProcData->hFtpWnd, WMFTP_DIR, pProcData->File.nDelay, NULL) ) PostMessage (pProcData->hFtpWnd, WMFTP_DIR, 0, (LPARAM) pProcData); } /* Receive OK */ else /* fin de données */ { FtpCloseFileTransfer (pProcData, FALSE); if (nRead == 0) /* fin de transfert */ { Rc = IntFtpGetAnswerCode ( & pProcData->ftp ); switch (Rc) { case 226 : case 250 : iRetCode = FTPERR_OK ; break; default : iRetCode = FTPERR_UNEXPECTEDANSWER; } } else iRetCode = FTPERR_DATACONNECTION; PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, TRUE, (LPARAM) iRetCode); } break; } /* switch Msg */ return (LRESULT) DefWindowProc (hWnd, Msg, wParam, lParam); } /* DLLWndProc */ /* ******************************************************************* */ /* */ /* Partie VII : Transfert de fichier synchrone */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------ */ /* FtpSyncSend */ /* ------------------------------------------------------------ */ int FtpSyncSend (LPProcData pProcData) { int nRead, Rc; struct timeval TO; for ( ; ; ) { if HAS_ABORTED() { AbortAction (pProcData, FALSE, TRUE, 6); return FTPERR_CANCELBYUSER; } nRead = _lread (pProcData->File.hf, pProcData->File.szBuf, sizeof pProcData->File.szBuf); if (nRead > 0) { pProcData->File.lPos += nRead; Rc = TcpSend (pProcData->ftp.data_socket, pProcData->File.szBuf, nRead, 0, HFILE_ERROR); if (Rc == TCP4U_SUCCESS) { if (pProcData->File.bNotify) PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, FALSE, pProcData->File.lPos ); if (++pProcData->File.nCount % FTP_RATE(pProcData) == 0) { TO.tv_sec = pProcData->File.nDelay / 1000; TO.tv_usec = (long) (pProcData->File.nDelay % 1000) * 1000l; Rc = select (0, NULL, NULL, NULL, & TO); if (Rc==-1 && HAS_ABORTED()) { AbortAction (pProcData, FALSE, TRUE, 7); return FTPERR_CANCELBYUSER; } } /* pause */ } /* nWritten <> nRead */ else { FtpCloseFileTransfer (pProcData, FALSE); return FTPERR_SENDREFUSED; } /* probleme reseau */ } /* nRead > 0 */ else /* fin de données */ { FtpCloseFileTransfer (pProcData, FALSE); return FtpAutomate (_S_ENDFILETRANSFER, NULL); } /* can not read file */ } /* do forever */ } /* FtpSyncSend */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpSyncRecv */ /* ------------------------------------------------------------ */ int FtpSyncRecv (LPProcData pProcData) { int nRead=0, nWritten, iRetCode, Rc; struct timeval TO; for ( ; ; ) { if ( ! HAS_ABORTED() ) nRead = TcpRecv (pProcData->ftp.data_socket, pProcData->File.szBuf, sizeof pProcData->File.szBuf, pProcData->ftp.nTimeOut, HFILE_ERROR); /* repeter le test car bAborted peut etre positionne entre temps */ if HAS_ABORTED() { AbortAction (pProcData, TRUE, TRUE, 8); return FTPERR_CANCELBYUSER; } if (nRead > 0) { nWritten = _lwrite (pProcData->File.hf, pProcData->File.szBuf, nRead); if (nWritten!=nRead) { /* envoi d'un ABORT au distant */ AbortAction (pProcData, TRUE, FALSE, 9); /* receive data */ return FTPERR_CANTWRITE; } /* lecture TCP Non OK */ pProcData->File.lPos += (unsigned) nWritten; if (pProcData->File.bNotify) PostMessage (pProcData->Msg.hParentWnd, pProcData->Msg.nCompletedMessage, FALSE, pProcData->File.lPos ); if (++pProcData->File.nCount % FTP_RATE(pProcData) == 0) { TO.tv_sec = pProcData->File.nDelay / 1000; TO.tv_usec = (long) (pProcData->File.nDelay % 1000) * 1000l; Rc = select (0, NULL, NULL, NULL, & TO); } /* pause to be done */ } /* nRead > 0 */ else /* fin de données */ { if (nRead == TCP4U_SOCKETCLOSED) /* fin de transfert normal */ { FtpCloseFileTransfer (pProcData, FALSE); iRetCode = FtpAutomate (_S_ENDFILETRANSFER, NULL); } else /* erreur dans la connexion */ { AbortAction (pProcData, TRUE, FALSE, 10); iRetCode = FTPERR_DATACONNECTION; } return iRetCode; } /* nRead <=0 */ } /* do forever */ } /* FtpSyncRecv */ /* ******************************************************************* */ /* */ /* Partie VIII : Fonctions FTP exportées */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpAbort */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpAbort (void) { LPProcData pProcData; pProcData = FtpDataPtr (); if (pProcData == NULL) return FALSE; if (pProcData->ftp.data_socket != INVALID_SOCKET) { WSACancelBlockingCall (); pProcData->File.bAborted = TRUE; } else if (pProcData->ftp.ctrl_socket!=INVALID_SOCKET) WSACancelBlockingCall (); return TRUE; } /* ------------------------------------------------------------ */ /* Fonction DLL FtpGetFileSize */ /* ------------------------------------------------------------ */ DWORD _export PASCAL FAR FtpGetFileSize (void) { LPProcData pProcData; LPSTR lp; long lFileSize=0; pProcData = FtpDataPtr (); if (pProcData == NULL) return 0; /* code de retour serveur : 150, 125 -> opening data connection */ if ( _fmemcmp (pProcData->ftp.szInBuf, "150", 3)!=0 && _fmemcmp (pProcData->ftp.szInBuf, "125", 3)!=0) return 0; AnsiLower (pProcData->ftp.szInBuf) ; lp=_fstrstr (pProcData->ftp.szInBuf, " bytes"); if (lp==NULL) return 0; while (isdigit (*--lp)); for (lp++ ; isdigit (*lp) ; lp++ ) { lFileSize *= 10; lFileSize += (*lp-'0'); } return lFileSize; } /* FtpGetFileSize */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpOpenDataConnection */ /* Open the data connection on port 20 */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpOpenDataConnection (LPCSTR szRemote, int nAction, char cType) { char szTmp [FTP_REPSTRLENGTH]; LPProcData pProcData; pProcData = FtpDataPtr (); wsprintf (szTmp, "%s %s", nAction==FTP4W_STORE_ON_SERVER ? (LPSTR) "STOR" : nAction==FTP4W_APPEND_ON_SERVER ? (LPSTR) "APPE" : (LPSTR) "RETR", szRemote); return ToolsSetDataConnection (pProcData, NULL, FTPMODE_NOTHING, cType, 0, szTmp); } /* FtpOpenDataConnection */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpRecvThroughDataConnection */ /* recv on port port 20 */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpRecvThroughDataConnection (LPSTR szBuf, unsigned int far *lpBufSize) { int Rc= FTPERR_CANCELBYUSER; LPProcData pProcData; pProcData = FtpDataPtr (); if ( ! HAS_ABORTED() ) Rc = TcpRecv (pProcData->ftp.data_socket, szBuf, *lpBufSize, pProcData->ftp.nTimeOut, HFILE_ERROR); /* repeter le test car bAborted peut etre positionne entre temps */ if HAS_ABORTED() { AbortAction (pProcData, TRUE, TRUE, 20); return FTPERR_CANCELBYUSER; } if (Rc>=TCP4U_SUCCESS) { *lpBufSize = Rc; return FTPERR_OK; } if (Rc==TCP4U_SOCKETCLOSED) return FTPERR_ENDOFDATA ; else return FTPERR_DATACONNECTION; } /* FtpRecvTroughDataConnection */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpSendThroughDataConnection */ /* send on port port 20 */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpSendThroughDataConnection (LPCSTR szBuf, unsigned int uBufSize) { int Rc; LPProcData pProcData; pProcData = FtpDataPtr (); Rc=TcpSend (pProcData->ftp.data_socket, szBuf, uBufSize, FALSE,HFILE_ERROR); if (Rc>=TCP4U_SUCCESS) return FTPERR_OK; else return FTPERR_DATACONNECTION; } /* FtpSendTroughDataConnection */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpCloseDataConnection */ /* Closes the data connection on port 20 */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpCloseDataConnection (void) { LPProcData pProcData; int Rc; pProcData = FtpDataPtr (); Rc = TcpClose(&pProcData->ftp.data_socket)==TCP4U_SUCCESS ? FTPERR_OK : FTPERR_CANTCLOSE; if (Rc==FTPERR_OK) { Rc = IntFtpGetAnswerCode ( & pProcData->ftp ); switch (Rc) { case 250 : case 226 : return FTPERR_OK ; case 452 : case 552 : return FTPERR_CANTWRITE ; default : return FTPERR_UNEXPECTEDANSWER; } } /* transfert OK */ return FTPERR_CANTCLOSE; } /* FtpCloseDataConnection */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpRecvFile */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpRecvFile (LPCSTR szRemote, LPCSTR szLocal, char cType, BOOL bNotify, HWND hParentWnd, UINT wMsg) { LPProcData pProcData; int Rc; char szTmp [FTP_REPSTRLENGTH]; pProcData = FtpDataPtr (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; if (pProcData->ftp.ctrl_socket==INVALID_SOCKET) return FTPERR_NOTCONNECTED; pProcData->Msg.nCompletedMessage = wMsg; pProcData->Msg.hParentWnd = hParentWnd; wsprintf (szTmp, "RETR %s", szRemote); Rc = ToolsSetDataConnection (pProcData, szLocal, FTPMODE_WRITE, cType, 0, /* Skip restart command */ szTmp); if (Rc!=FTPERR_OK) RETURN(pProcData,Rc); pProcData->File.bNotify = bNotify; pProcData->File.lPos = 0; pProcData->File.lTotal = FtpGetFileSize (); if (pProcData->File.bAsyncMode) { PostMessage (pProcData->hFtpWnd, WMFTP_RECV, 0,(LPARAM)pProcData); return FTPERR_OK; } else return FtpSyncRecv (pProcData); } /* FtpRecvFile */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpSendFile */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpSendFile (LPCSTR szLocal, LPCSTR szRemote, char cType, BOOL bNotify, HWND hParentWnd, UINT wMsg) { LPProcData pProcData; int Rc; char szTmp [FTP_REPSTRLENGTH]; pProcData = FtpDataPtr (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; if (pProcData->ftp.ctrl_socket==INVALID_SOCKET) return FTPERR_NOTCONNECTED; pProcData->Msg.nCompletedMessage = wMsg; pProcData->Msg.hParentWnd = hParentWnd; wsprintf ( szTmp, "STOR %s", szRemote); Rc = ToolsSetDataConnection (pProcData, szLocal, FTPMODE_READ, cType, 0, /* Skip restart command */ szTmp); if (Rc!=FTPERR_OK) RETURN(pProcData, Rc); pProcData->File.bNotify = bNotify; pProcData->File.lPos = 0; pProcData->File.lTotal = _llseek (pProcData->File.hf, 0, SEEK_END); _llseek (pProcData->File.hf, 0, SEEK_SET); if (pProcData->File.bAsyncMode) { PostMessage (pProcData->hFtpWnd, WMFTP_SEND, 0,(LPARAM)pProcData); return FTPERR_OK; } else return FtpSyncSend (pProcData); } /* FtpSendFile */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpAppendToLocalFile */ /* The same function than FtpRecvFile */ /* Only a parameter has been changed : */ /* ToolsSetDataConnection is called with */ /* FTPMODE_APPEND instead of FTPMODE_READ */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpAppendToLocalFile (LPCSTR szRemote, LPCSTR szLocal, char cType, BOOL bNotify, HWND hParentWnd, UINT wMsg) { LPProcData pProcData; int Rc; char szTmp [FTP_REPSTRLENGTH]; pProcData = FtpDataPtr (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; if (pProcData->ftp.ctrl_socket==INVALID_SOCKET) return FTPERR_NOTCONNECTED; pProcData->Msg.nCompletedMessage = wMsg; pProcData->Msg.hParentWnd = hParentWnd; wsprintf (szTmp, "RETR %s", szRemote); Rc = ToolsSetDataConnection (pProcData, szLocal, FTPMODE_APPEND, cType, 0, /* Skip restart command */ szTmp); if (Rc!=FTPERR_OK) RETURN(pProcData,Rc); pProcData->File.bNotify = bNotify; pProcData->File.lPos = 0; pProcData->File.lTotal = FtpGetFileSize (); if (pProcData->File.bAsyncMode) { PostMessage (pProcData->hFtpWnd, WMFTP_RECV, 0,(LPARAM)pProcData); return FTPERR_OK; } else return FtpSyncRecv (pProcData); } /* FtpAppendToLocalFile */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpAppendToRemoteFile */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpAppendToRemoteFile (LPCSTR szLocal, LPCSTR szRemote, char cType, BOOL bNotify, HWND hParentWnd, UINT wMsg) { LPProcData pProcData; int Rc; char szTmp [FTP_REPSTRLENGTH]; pProcData = FtpDataPtr (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; if (pProcData->ftp.ctrl_socket==INVALID_SOCKET) return FTPERR_NOTCONNECTED; pProcData->Msg.nCompletedMessage = wMsg; pProcData->Msg.hParentWnd = hParentWnd; wsprintf ( szTmp, "APPE %s", szRemote); Rc = ToolsSetDataConnection (pProcData, szLocal, FTPMODE_READ, cType, 0, /* Skip restart command */ szTmp); if (Rc!=FTPERR_OK) RETURN(pProcData, Rc); pProcData->File.bNotify = bNotify; pProcData->File.lPos = 0; pProcData->File.lTotal = _llseek (pProcData->File.hf, 0, SEEK_END); _llseek (pProcData->File.hf, 0, SEEK_SET); if (pProcData->File.bAsyncMode) { PostMessage (pProcData->hFtpWnd, WMFTP_SEND, 0,(LPARAM)pProcData); return FTPERR_OK; } else return FtpSyncSend (pProcData); } /* FtpAppendToRemoteFile */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpRestartRecvFile */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpRestartRecvFile (LPCSTR szRemote, HFILE hLocal, char cType, BOOL bNotify, long lByteCount, HWND hParentWnd, UINT wMsg) { LPProcData pProcData; int Rc; char szTmp [FTP_REPSTRLENGTH]; pProcData = FtpDataPtr (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; if (pProcData->ftp.ctrl_socket==INVALID_SOCKET) return FTPERR_NOTCONNECTED; pProcData->Msg.nCompletedMessage = wMsg; pProcData->Msg.hParentWnd = hParentWnd; wsprintf (szTmp, "RETR %s", szRemote); Rc = ToolsSetDataConnection (pProcData, NULL, /* no file to be opened */ FTPMODE_WRITE, /* unused */ cType, lByteCount, /* Restart command */ szTmp); if (Rc!=FTPERR_OK) RETURN(pProcData,Rc); pProcData->File.hf = hLocal; pProcData->File.bNotify = bNotify; pProcData->File.lPos = 0; pProcData->File.lTotal = FtpGetFileSize () - lByteCount; if (pProcData->File.bAsyncMode) { PostMessage (pProcData->hFtpWnd, WMFTP_RECV, 0,(LPARAM)pProcData); return FTPERR_OK; } else return FtpSyncRecv (pProcData); } /* FtpRestartRecvFile */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpRestartSendFile */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpRestartSendFile (HFILE hLocal, LPCSTR szRemote, char cType, BOOL bNotify, long lByteCount, HWND hParentWnd, UINT wMsg) { LPProcData pProcData; int Rc; char szTmp [FTP_REPSTRLENGTH]; long lFilePos; pProcData = FtpDataPtr (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; if (pProcData->ftp.ctrl_socket==INVALID_SOCKET) return FTPERR_NOTCONNECTED; pProcData->Msg.nCompletedMessage = wMsg; pProcData->Msg.hParentWnd = hParentWnd; wsprintf ( szTmp, "STOR %s", szRemote); Rc = ToolsSetDataConnection (pProcData, NULL, /* no file to be opened */ FTPMODE_READ, /* unused */ cType, lByteCount, /* Restart command */ szTmp); if (Rc!=FTPERR_OK) RETURN(pProcData, Rc); pProcData->File.hf = hLocal; pProcData->File.bNotify = bNotify; /* le nombre d'octets transférés doit partir de 0. En revanche, le nombre */ /* d'octets à transférer doit tenir compte de l'avancement dans le fichier */ lFilePos = _llseek (pProcData->File.hf, 0, SEEK_CUR); pProcData->File.lTotal =_llseek (pProcData->File.hf, 0, SEEK_END) - lFilePos; _llseek (pProcData->File.hf, lFilePos, SEEK_SET); pProcData->File.lPos = 0; if (pProcData->File.bAsyncMode) { PostMessage (pProcData->hFtpWnd, WMFTP_SEND, 0,(LPARAM)pProcData); return FTPERR_OK; } else return FtpSyncSend (pProcData); } /* FtpRestartSendFile */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpDir */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpDir (LPCSTR szDef, LPCSTR szLocalFile, BOOL bLongDir, HWND hParentWnd, UINT wMsg) { LPProcData pProcData; int Rc; char szTmp [FTP_REPSTRLENGTH]; pProcData = FtpDataPtr (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; if (pProcData->ftp.ctrl_socket==INVALID_SOCKET) return FTPERR_NOTCONNECTED; pProcData->File.bNotify = FALSE; pProcData->Msg.nCompletedMessage = wMsg; pProcData->Msg.hParentWnd = hParentWnd; /* synchronous mode -> data must be sent into a file */ if (! pProcData->File.bAsyncMode && szLocalFile==NULL) return FTPERR_INVALIDPARAMETER; if (szDef!=NULL && szDef[0]!=0) wsprintf ( szTmp, "%s %s", (LPSTR) (bLongDir ? "LIST" : "NLST"), szDef); else lstrcpy (szTmp, bLongDir ? "LIST" : "NLST"); Rc = ToolsSetDataConnection (pProcData, szLocalFile, FTPMODE_WRITE, TYPE_A, 0, szTmp); if (Rc!=FTPERR_OK) RETURN (pProcData, Rc); /* On complete la structure */ pProcData->File.lPos = 0; pProcData->File.lTotal = 0; if (pProcData->File.bAsyncMode) { PostMessage (pProcData->hFtpWnd, szLocalFile==NULL ? WMFTP_DIR : WMFTP_RECV, 0, (LPARAM) pProcData); return FTPERR_OK; } else return FtpSyncRecv (pProcData); } /* FtpDir */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* FtpMGet */ /* Receptionne tous les fichiers du repertoire courant */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int _export PASCAL FAR FtpMGet (LPCSTR szFilter, char cType, BOOL bNotify, BOOL (CALLBACK *f) (LPCSTR szRemFile, LPCSTR szLocalFile, int Rc) ) { char szDir [FTP_REPSTRLENGTH]; char szDirTo [FTP_REPSTRLENGTH]; int Ark; int Rc; char szTempDirFile [144]; /* nom du fichier temporaire */ HFILE hTmpFile; /* handler fichier temporaire */ LPProcData pProcData; LPSTR p; if (FtpIsAsynchronousMode ()) return FTPERR_ASYNCMODE; pProcData = FtpDataPtr (); if (pProcData == NULL) return FTPERR_NOACTIVESESSION; /* on conserve l'ancien mode */ GetTempFileName (GetTempDrive(0), "4w", 0, szTempDirFile); /* NLST sur le filtre propose */ Rc = FtpDir (szFilter, szTempDirFile, FALSE, 0, 0); if (Rc != FTPERR_OK) { unlink (szTempDirFile); return FTPERR_CANTOPENLOCALFILE; } /* error in Dir command */ /* dir command is OK: list of files to be received is in szTmpFile */ hTmpFile = _lopen (szTempDirFile, OF_READ); if (hTmpFile==HFILE_ERROR) { unlink (szTempDirFile); return FTPERR_CANTOPENLOCALFILE; } /* can not open temporary file (?) */ do { memset (szDir, 0, sizeof szDir); Ark = _lread (hTmpFile, szDir, sizeof szDir - 1); if (Ark<=0) break; p = strchr (szDir, '\n'); if (p == NULL) break; *p=0; /* fin de chaine */ if (*(p-1)=='\r') *(p-1)=0; /* precaution */ /* revenir sur le debut de la ligne suivante */ _llseek (hTmpFile, 1 + (int) (p - szDir) - Ark, 1); lstrcpy (szDirTo, szDir); Rc = FTPERR_OK; if (f == NULL || (*f) (szDir, szDirTo, FTPERR_ENDOFDATA)) Rc = FtpRecvFile (szDir, szDirTo, cType, bNotify, 0, 0); } /* reste des donnees a lire */ while ( (Rc==FTPERR_OK && f == NULL) || (*f) (szDir, szDirTo, Rc) ); _lclose (hTmpFile); unlink (szTempDirFile); return Rc; } /* FtpMGFet */ <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPVWSetDecl(); CKERROR CreatePVWSetProto(CKBehaviorPrototype **pproto); int PVWSet(const CKBehaviorContext& behcontext); CKERROR PVWSetCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_XML, bbI_AxleSpeed, bbI_Steer, bbI_MotorTorque, bbI_BrakeTorque, bbI_SuspensionSpring, bbI_SuspensionTravel, bbI_Radius, bbI_WFlags, bbI_WSFlags, bbI_LatFunc, bbI_LongFunc, }; #define BB_SSTART 0 BBParameter pInMap2[] = { BB_SPIN(bbI_XML,VTE_XML_VEHICLE_SETTINGS,"XML Link","None"), BB_SPIN(bbI_AxleSpeed,CKPGUID_FLOAT,"Axle Speed","2000.0"), BB_SPIN(bbI_Steer,CKPGUID_ANGLE,"Steer Angle","1.0"), BB_SPIN(bbI_MotorTorque,CKPGUID_FLOAT,"Motor Torque","0.0"), BB_SPIN(bbI_BrakeTorque,CKPGUID_FLOAT,"Break Torque","0.0"), BB_SPIN(bbI_SuspensionSpring,VTS_JOINT_SPRING,"Suspension Spring",""), BB_SPIN(bbI_SuspensionTravel,CKPGUID_FLOAT,"Suspension Travel","0.0"), BB_SPIN(bbI_Radius,CKPGUID_FLOAT,"Radius","1.0"), BB_SPIN(bbI_WFlags,VTS_PHYSIC_WHEEL_FLAGS,"Wheel Flags",""), BB_SPIN(bbI_WSFlags,VTF_VWSHAPE_FLAGS,"Wheel ShapeFlags",""), BB_SPIN(bbI_LatFunc,VTF_VWTIRE_SETTINGS,"Latitude Force Settings",""), BB_SPIN(bbI_LongFunc,VTF_VWTIRE_SETTINGS,"Longitudinal Force Settings","0.0"), }; #define gPIMAP pInMap2 //************************************ // Method: FillBehaviorPVWSetDecl // FullName: FillBehaviorPVWSetDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPVWSetDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVWSet"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Sets physical quantities."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7805147,0x322e17e7)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVWSetProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePVWSetProto // FullName: CreatePVWSetProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePVWSetProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVWSet"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PVWSet PVWSet is categorized in \ref Vehicle <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies various physical parameters.<br> <h3>Technical Information</h3> \image html PVWSet.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBSetEx.cpp </SPAN> */ proto->SetBehaviorCallbackFct( PVWSetCB ); BB_EVALUATE_SETTINGS(pInMap2); //---------------------------------------------------------------- // // We just want create the building block pictures // #ifdef _DOC_ONLY_ BB_EVALUATE_INPUTS(pInMap2); #endif // _DOC_ONLY_ proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PVWSet); *pproto = proto; return CK_OK; } //************************************ // Method: PVWSet // FullName: PVWSet // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PVWSet(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; body = GetPMan()->getBody(target); if (!body) bbErrorME("No Reference Object specified"); pWheel *wheel = body->getWheel(target); if (!wheel)bbErrorME("pWheel object doesnt exist!"); pWheel2 *wheel2 = wheel->castWheel2(); if (!wheel2)bbErrorME("Couldnt cast a pWheel2 object"); BB_DECLARE_PIMAP; /************************************************************************/ /* engel kuehne un partner */ /************************************************************************/ /************************************************************************/ /* retrieve settings state */ /************************************************************************/ BBSParameter(bbI_XML); BBSParameter(bbI_AxleSpeed); BBSParameter(bbI_Steer); BBSParameter(bbI_MotorTorque); BBSParameter(bbI_BrakeTorque); BBSParameter(bbI_SuspensionSpring); BBSParameter(bbI_SuspensionTravel); BBSParameter(bbI_Radius); BBSParameter(bbI_WFlags); BBSParameter(bbI_WSFlags); BBSParameter(bbI_LatFunc); BBSParameter(bbI_LongFunc); /************************************************************************/ /* retrieve values */ /************************************************************************/ int xmlValue = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_XML)); float axleVel = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_AxleSpeed)); float steer = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_Steer)); float mTorque = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_MotorTorque)); float bTorque = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_BrakeTorque)); float suspensionTravel = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_SuspensionTravel)); int wFlags = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_WFlags)); int wSFlags = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_WSFlags)); pSpring sSpring; if (sbbI_SuspensionSpring) { CKParameterIn *par = beh->GetInputParameter(bbI_SuspensionSpring); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { sSpring = pFactory::Instance()->createSpringFromParameter(rPar); NxSpringDesc xsp; xsp.damper = sSpring.damper; xsp.spring = sSpring.spring; xsp.targetValue = sSpring.targetValue; if (xsp.isValid()) { wheel2->setSuspensionSpring(sSpring); }else bbErrorME("Invalid Spring Setings!"); } } } /************************************************************************/ /* Update Object ! */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// // load some settings from XML if(sbbI_XML) { } if (sbbI_Steer)wheel2->setAngle(steer); if (sbbI_AxleSpeed)wheel2->setAxleSpeed(axleVel); if (sbbI_MotorTorque)wheel2->setMotorTorque(mTorque); if (sbbI_BrakeTorque)wheel2->setBreakTorque(bTorque); if (sbbI_SuspensionSpring)wheel2->setSuspensionSpring(sSpring); if (sbbI_SuspensionTravel)wheel2->setSuspensionTravel(suspensionTravel); if (sbbI_WFlags) { ////////////////////////////////////////////////////////////////////////// // // wheel2->setFlags(wFlags); } if (sbbI_WSFlags) { wheel2->getWheelShape()->setWheelFlags(wSFlags); } if (sbbI_LatFunc) { CKParameterIn *par = beh->GetInputParameter(BB_IP_INDEX(bbI_LatFunc)); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { pTireFunction func = pFactory::Instance()->createTireFuncFromParameter(rPar); if (func.isValid()) { NxTireFunctionDesc xFn; xFn.asymptoteSlip = func.asymptoteSlip; xFn.asymptoteValue = func.asymptoteValue; xFn.extremumSlip= func.extremumSlip; xFn.extremumValue= func.extremumValue; xFn.stiffnessFactor= func.stiffnessFactor; wheel2->getWheelShape()->setLongitudalTireForceFunction(xFn); }else bbErrorME("Invalid Tire Function Settings!"); } } } if (sbbI_LongFunc) { CKParameterIn *par = beh->GetInputParameter(BB_IP_INDEX(bbI_LongFunc)); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { pTireFunction func = pFactory::Instance()->createTireFuncFromParameter(rPar); if (func.isValid()) { NxTireFunctionDesc xFn; xFn.asymptoteSlip = func.asymptoteSlip; xFn.asymptoteValue = func.asymptoteValue; xFn.extremumSlip= func.extremumSlip; xFn.extremumValue= func.extremumValue; xFn.stiffnessFactor= func.stiffnessFactor; wheel2->getWheelShape()->setLongitudalTireForceFunction(xFn); }else bbErrorME("Invalid Tire Function Settings!"); } } } } beh->ActivateOutput(0); return 0; } //************************************ // Method: PVWSetCB // FullName: PVWSetCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PVWSetCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; } <file_sep>/******************************************************************** created: 2007/10/29 created: 29:10:2007 15:19 filename: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src\xSystem3D.cpp file path: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src file base: xSystem3D file ext: cpp author: mc007 purpose: *********************************************************************/ /*#ifndef USEDIRECTX9 #define USEDIRECTX9 #endif*/ #include "pch.h" #include "xSystem3D.h" #include "d3d9.h" #include "CKAll.h" #include "3d/DXDiagNVUtil.h" #include "../Manager/InitMan.h" extern InitMan *_im2; ////////////////////////////////////////////////////////////////////// // // DirectX-Helpers // // namespace xSystem3DHelper { /************************************************************************/ /* */ /************************************************************************/ void xSSaveAllDxPropsToFile(char*file) { DXDiagNVUtil nvutil; nvutil.InitIDxDiagContainer(); FILE *fp = fopen("x:\\dx.out","a"); //nvutil.ListAllDXDiagPropertyNames(); nvutil.ListAllDXDiagPropertyNamesToTxtFile(fp,true,NULL,NULL); } //int xSGetAvailableTextureMem(); int xSGetAvailableTextureMem(CKContext *ctx) { ////////////////////////////////////////////////////////////////////////// if (GetIManager() && GetIManager()->m_Context) { CKContext * ctx1 = GetIManager()->m_Context; CKRenderManager* rm = ctx1->GetRenderManager(); CKRenderContext* rc = rm->GetRenderContext(0); VxDirectXData* dx = rc->GetDirectXInfo(); int z_ = 0; IDirect3DDevice9 *d_ptr = ((IDirect3DDevice9*)dx->D3DDevice); if(dx) { return d_ptr->GetAvailableTextureMem(); } } ////////////////////////////////////////////////////////////////////////// return -1; } /************************************************************************/ /* */ /************************************************************************/ float xSGetPhysicalMemoryInMB() { DXDiagNVUtil nvutil; nvutil.InitIDxDiagContainer(); float ret = -1; nvutil.GetPhysicalMemoryInMB(&ret); nvutil.FreeIDxDiagContainer(); return ret; } ///////////////////////////////////////////////////////////////////////// int xSGetPhysicalGPUMemoryInMB(int device) { DXDiagNVUtil nvutil; nvutil.InitIDxDiagContainer(); int ret = -1; nvutil.GetDisplayDeviceMemoryInMB(device, &ret); nvutil.FreeIDxDiagContainer(); return ret; } }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" using namespace vtTools::AttributeTools; void pWorld::_construct() { //mAllocator = new UserAllocator; //mCManager = NxCreateControllerManager(mAllocator); } void pWorld::destroyCloth(CK_ID id) { pCloth*cloth = getCloth(id); if (cloth) { delete cloth; } } pCloth *pWorld::getCloth(CK_ID id) { int nbClothes = getScene()->getNbCloths(); NxCloth** clothes = getScene()->getCloths(); while(nbClothes--) { NxCloth* cloth = *clothes++; if(cloth->userData != NULL) { pCloth *vCloth = static_cast<pCloth*>(cloth->userData); if (vCloth) { if (id == vCloth->getEntityID() ) { return vCloth; } } } } return NULL; } pCloth *pWorld::getCloth(CK3dEntity*reference) { if (!reference) { return NULL; } int nbClothes = getScene()->getNbCloths(); NxCloth** clothes = getScene()->getCloths(); while(nbClothes--) { NxCloth* cloth = *clothes++; if(cloth->userData != NULL) { pCloth *vCloth = static_cast<pCloth*>(cloth->userData); if (vCloth) { if (reference->GetID() == vCloth->getEntityID() ) { return vCloth; } } } } return NULL; } void pWorld::updateClothes() { int nbClothes = getScene()->getNbCloths(); NxCloth** clothes = getScene()->getCloths(); while(nbClothes--) { NxCloth* cloth = *clothes++; if(cloth->userData != NULL) { pCloth *vCloth = static_cast<pCloth*>(cloth->userData); if (vCloth) { vCloth->updateVirtoolsMesh(); } } } } int pWorld::getNbBodies() { int result = 0; if (!getScene()) { return result; } result+= getScene()->getNbActors(); return result; } int pWorld::getNbJoints() { int result = 0; if (!getScene()) { return result; } result+= getScene()->getNbJoints(); return result; } NxShape *pWorld::getShapeByEntityID(CK_ID id) { if (!getScene() ) { return NULL; } CK3dEntity *entA = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(id)); if (!entA) { return NULL; } int nbActors = getScene()->getNbActors(); if (!nbActors) { return NULL; } NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body =static_cast<pRigidBody*>(actor->userData); if (body) { NxU32 nbShapes = body->getActor()->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)body->getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *info = static_cast<pSubMeshInfo*>(s->userData); if (info) { CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(info->entID)); if (ent == entA ) { return s; } } } } } } } } return NULL; } pRigidBody* pWorld::getBodyFromSubEntity(CK3dEntity *sub) { if (!getScene() ) { return NULL; } int nbActors = getScene()->getNbActors(); if (!nbActors) { return NULL; } NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body =static_cast<pRigidBody*>(actor->userData); if (body) { NxU32 nbShapes = body->getActor()->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)body->getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *info = static_cast<pSubMeshInfo*>(s->userData); if (info) { CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(info->entID)); if (ent) { if (sub == ent) { return body; } } } } } } } } } return NULL; } void pWorld::checkList() { if (!getScene() ) { return; } int nbActors = getScene()->getNbActors(); if (!nbActors) { return; } NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body = (pRigidBody*)actor->userData; if (body) { CK3dEntity * ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(body->getEntID())); if (!ent) { deleteBody(body); } } } } int nbClothes = getScene()->getNbCloths(); NxCloth** clothes = getScene()->getCloths(); while(nbClothes--) { NxCloth* cloth = *clothes++; if(cloth->userData != NULL) { pCloth *vCloth = static_cast<pCloth*>(cloth->userData); if (vCloth) { CK3dEntity * ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(vCloth->getEntityID())); if (!ent) { destroyCloth(vCloth->getEntityID()); } } } } } void pWorld::deleteBody(pRigidBody*body) { if (body) { body->destroy(); if (body->getWorld() && body->getWorld()->getScene() ) { for (int i = 0 ; i < body->getWorld()->getJointFeedbackList().Size(); i++ ) { pBrokenJointEntry *entry = *body->getWorld()->getJointFeedbackList().At(i); if (entry && entry->joint) { /*if (entry->joint->GetVTEntA() == body->GetVT3DObject() || entry->joint->GetVTEntB() == body->GetVT3DObject() ) { i = 0; }*/ } } } delete body; body =NULL; } checkList(); } void pWorld::deleteJoint(pJoint*joint) { if (!joint) { return; } pWorld *world = joint->getWorld(); if (world && world->getScene() ) { for (int i = 0 ; i < world->getJointFeedbackList().Size(); i++ ) { pBrokenJointEntry *entry = *world->getJointFeedbackList().At(i); if (entry && entry->joint == joint) { world->getJointFeedbackList().EraseAt(i); break; } } joint->getJoint()->userData = NULL; world->getScene()->releaseJoint(*joint->getJoint()); delete joint; } } pJoint* pWorld::getJoint(CK3dEntity *_a, CK3dEntity *_b, JType type) { if (!getScene()) { return NULL; } pRigidBody *a = GetPMan()->getBody(_a); pRigidBody *b = GetPMan()->getBody(_b); //bodies have already a joint together ? if ( !a && !b) { return NULL; } if ( a == b) { return NULL; } if (a && !a->isValid() ) { return NULL; } if (a && !GetPMan()->getWorldByBody(_a)) { return NULL; } if (b && !GetPMan()->getWorldByBody(_b) ) { return NULL; } if (b && !b->isValid()) { return NULL; } if ( a && b ) { pWorld*worldA = GetPMan()->getWorldByBody(_a); pWorld*worldB = GetPMan()->getWorldByBody(_b); if (!worldA || !worldB || (worldA!=worldB) || !worldA->isValid() || !worldB->isValid() ) { return NULL; } } NxU32 jointCount = getScene()->getNbJoints(); if (jointCount) { NxArray< NxJoint * > joints; getScene()->resetJointIterator(); for (NxU32 i = 0; i < jointCount; ++i) { NxJoint *j = getScene()->getNextJoint(); if (type == JT_Any) { pJoint *mJoint = static_cast<pJoint*>( j->userData ); if ( mJoint ) { if (mJoint->GetVTEntA() == _a && mJoint->GetVTEntB() == _b ) { return mJoint; } CK3dEntity *inA = _b; CK3dEntity *inB = _a; if (mJoint->GetVTEntA() == inA && mJoint->GetVTEntB() == inB ) { return mJoint; } } } if ( j->getType() == type) { pJoint *mJoint = static_cast<pJoint*>( j->userData ); if ( mJoint ) { if (mJoint->GetVTEntA() == _a && mJoint->GetVTEntB() == _b ) { return mJoint; } CK3dEntity *inA = _b; CK3dEntity *inB = _a; if (mJoint->GetVTEntA() == inA && mJoint->GetVTEntB() == inB ) { return mJoint; } } } } } return NULL; } bool pWorld::isValid() { return getScene() ? true : false; } void pWorld::step(float stepsize) { if (getScene()) { NxU32 nbTransforms = 0; NxActiveTransform *activeTransforms = getScene()->getActiveTransforms(nbTransforms); //getScene()->fetchResults(NX_ALL_FINISHED,true); //stepsize *=0.001f; updateVehicles(stepsize); updateClothes(); #ifdef HAS_FLUIDS updateFluids(); #endif getScene()->simulate(stepsize); if(nbTransforms && activeTransforms) { for(NxU32 i = 0; i < nbTransforms; ++i) { // the user data of the actor holds the game object pointer NxActor *actor = activeTransforms[i].actor; if (actor) { pRigidBody *body = (pRigidBody*)actor->userData; // update the game object's transform to match the NxActor if(body) { //gameObject->setTransform(activeTransforms[i].actor2World); NxMat34 transformation = activeTransforms[i].actor2World; VxQuaternion rot = pMath::getFrom(transformation.M); VxVector pos = pMath::getFrom(transformation.t); VxVector pos2 = pMath::getFrom(transformation.t); CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(body->getEntID())); NxShape *mainShape=body->getMainShape(); if (mainShape) { VxVector diff = getFrom(mainShape->getLocalPosition()); if (XAbs(diff.SquareMagnitude()) > 0.01f) { //pos+=diff; } } if (ent) { ent->SetPosition(&pos); ent->SetQuaternion(&rot); body->updateSubShapes(); }else{ xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Invalid Body due simulation."); } } } } } NxU32 error; getScene()->flushStream(); getScene()->fetchResults(NX_RIGID_BODY_FINISHED,true,&error); int err = error; } } pRigidBody*pWorld::getBody(CK3dEntity*ent) { pRigidBody *result = NULL; if (!ent || !getScene() ) { return NULL; } int nbActors = getScene()->getNbActors(); NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body = (pRigidBody*)actor->userData; if (body && body->getEntID() == ent->GetID() ) { return body; } if (body && body->isSubShape(ent) ) { return body; } } } return NULL; } pWorld::pWorld(CK3dEntity* _o) { m_SleepingSettings = NULL; m_worldSettings =NULL; m_vtReference = _o; mScene = NULL; contactReport = NULL; triggerReport = NULL; } pWorld::~pWorld() { //m_worldSettings = NULL; //m_SleepingSettings =NULL; mScene = NULL; //m_vtReference =NULL; } void pWorld::destroy() { if (getScene()) { int nbActors = getScene()->getNbActors(); if (!nbActors)return; NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body = (pRigidBody*)actor->userData; if (body) { body->destroy(); if (body->GetVT3DObject()) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Body destroyed :"); } delete body; body =NULL; } } } } if (GetPMan()->getPhysicsSDK()) { GetPMan()->getPhysicsSDK()->releaseScene(*mScene); mScene = NULL; } if (m_SleepingSettings) { delete m_SleepingSettings; m_SleepingSettings = NULL; } if (m_worldSettings) { delete m_worldSettings; m_worldSettings = NULL; } } int pWorld::UpdateProperties(DWORD mode,DWORD flags) { return 0; }<file_sep>// racer/time.h #ifndef __X_TIME_H__ #define __X_TIME_H__ #include <qTimer.h> #include <BaseMacros.h> class MODULE_API xTime // A notion of simulation time { protected: float span; // Time of integration (in seconds) int spanMS; // Time of integration in milliseconds QTimer *tmr; // Actual real timer int curRealTime; // Last recorded REAL time in msecs int curSimTime; // Time calculated in the sim int lastSimTime; // Last point of simulation public: xTime(); ~xTime(); // Attribs int GetRealTime(){ return curRealTime; } int GetSimTime(){ return curSimTime; } int GetLastSimTime(){ return lastSimTime; } int GetSpanMS(){ return spanMS; } inline float GetSpan(){ return span; } void AddSimTime(int msecs); void SetLastSimTime(){ lastSimTime=curSimTime; } void SetSpan(int ms); // Methods void Start(); void Stop(); void Reset(); void Update(); }; #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" //#include "tinyxml.h" #include <PhysicManager.h> static pFactory* pFact = NULL; void pFactory::findAttributeIdentifiersByGuid(CKGUID guid,std::vector<int>&targetList) { CKContext *ctx = GetPMan()->GetContext(); CKAttributeManager *attMan = ctx->GetAttributeManager(); CKParameterManager *parMan = ctx->GetParameterManager(); int cCount = attMan->GetAttributeCount(); for(int i = 0 ; i < cCount ; i++) { CKSTRING name = attMan->GetAttributeNameByType(i); if ( parMan->ParameterTypeToGuid(attMan->GetAttributeParameterType(i)) == guid ) { targetList.push_back(i); } } } //************************************ // Method: Instance // FullName: vtODE::pFactory::Instance // Access: public // Returns: pFactory* // Qualifier: //************************************ pFactory* pFactory::Instance() { if (!pFact) { pFact = new pFactory(GetPMan(),GetPMan()->getDefaultConfig()); } return pFact; } //************************************ // Method: ~pFactory // FullName: vtODE::pFactory::~pFactory // Access: public // Returns: // Qualifier: //************************************ pFactory::~pFactory() { //Clean(); delete pFact; pFact = NULL; } pFactory::pFactory() { } //************************************ // Method: pFactory // FullName: vtODE::pFactory::pFactory // Access: public // Returns: // Qualifier: : m_PManager(prm1), m_DefaultDocument(prm2) // Parameter: PhysicManager* prm1 // Parameter: TiXmlDocument*prm2 //************************************ pFactory::pFactory(PhysicManager* prm1,TiXmlDocument*prm2) : mManager(prm1), m_DefaultDocument(prm2) { pFact = this; mPhysicSDK = NULL; } //************************************ // Method: ResolveFileName // FullName: vtODE::pFactory::ResolveFileName // Access: public // Returns: XString // Qualifier: // Parameter: const char *input //************************************ XString pFactory::ResolveFileName(const char *input) { CKPathManager *pm = GetPMan()->m_Context->GetPathManager(); FILE *file = fopen(input,"r"); XString result; if (file) { char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,input); fclose(file); return XString(Ini); } if (!file) { CKSTRING lastCmo = GetPMan()->m_Context->GetLastCmoLoaded(); CKPathSplitter splitter(const_cast<char*>(lastCmo)); CKPathSplitter splitter2(const_cast<char*>(input)); CKPathMaker maker(splitter.GetDrive(),splitter.GetDir(),const_cast<char*>(input),""); char* NewFilename = maker.GetFileName(); file = fopen(NewFilename,"r"); if (!file) { char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,input); file = fopen(Ini,"r"); if(file) { fclose(file); return XString(Ini); } if(pm) { XString fname(const_cast<char*>(input)); CKERROR error = GetPMan()->m_Context->GetPathManager()->ResolveFileName( fname , DATA_PATH_IDX); if (error ==CK_OK) { file = fopen(fname.CStr(),"r"); if (file) { fclose(file); result = fname; } } } } } return result; } //************************************ // Method: CreateFrame // FullName: vtODE::pFactory::CreateFrame // Access: public // Returns: CK3dEntity* // Qualifier: // Parameter: XString name //************************************ CK3dEntity* pFactory::createFrame(const char* name) { if (!strlen(name)) { return NULL; } int count = ctx()->GetObjectsCountByClassID(CKCID_3DENTITY); CK_ID* ol = ctx()->GetObjectsListByClassID(CKCID_3DENTITY); for(int j=0;j<count;j++ ) { CKBeObject* o = static_cast<CKBeObject*>(ctx()->GetObject(ol[j])); if (!strcmp(o->GetName(),name ) ) { return static_cast<CK3dEntity*>(o); } } CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_NONAMECHECK; //if (dynamic) creaoptions = CK_OBJECTCREATION_DYNAMIC; // The Creation CKObject* object = ctx()->CreateObject(CKCID_3DENTITY,const_cast<char*>(name),creaoptions); CK3dEntity* ent=(CK3dEntity*)object; ent->SetFlags(ent->GetFlags()|CK_3DENTITY_FRAME); // we add it to the level CKLevel *level = ctx()->GetCurrentLevel(); if (level) { level->AddObject(object); } return ent; } //************************************ // Method: _str2Vec // FullName: vtODE::pFactory::_str2Vec // Access: public // Returns: VxVector // Qualifier: // Parameter: XString _in //************************************ VxVector pFactory::_str2Vec(XString _in) { short nb = 0 ; VxVector out; XStringTokenizer tokizer(_in.CStr(), ","); const char*tok = NULL; while ((tok=tokizer.NextToken(tok)) && nb < 3) { XString tokx(tok); out.v[nb] = tokx.ToFloat(); nb++; } return out; } int pFactory::_str2MaterialFlag(XString _in) { short nb = 0 ; int result = 0; XStringTokenizer tokizer(_in.CStr(), "|"); const char*tok = NULL; while ((tok=tokizer.NextToken(tok)) && nb < 3) { XString tokx(tok); if ( _stricmp(tokx.CStr(),"Anisotropic") == 0 ) { result |= MF_Anisotropic; } if ( _stricmp(tokx.CStr(),"DisableFriction") == 0 ) { result |= MF_DisableFriction; } if ( _stricmp(tokx.CStr(),"DisableStrongFriction") == 0 ) { result |= MF_DisableStrongFriction; } nb++; } return result; } int pFactory::_getEnumIndex(XString enumerationFull,XString enumValue) { int result = 0; XStringTokenizer tokizer(enumerationFull.CStr(), ","); const char*tok = NULL; while ((tok=tokizer.NextToken(tok))) { XString tokx(tok); if ( !strcmp(tokx.CStr(),enumValue.CStr()) ) { return result; } // out.v[nb] = tokx.ToFloat(); result++; } return 0; }<file_sep>// PBDodyTab.cpp : implementation file // #include "stdafx.h" #include "PBDodyTab.h" // PBDodyTab IMPLEMENT_DYNAMIC(PBDodyTab, CTabCtrl) PBDodyTab::PBDodyTab() { EnableAutomation(); } PBDodyTab::~PBDodyTab() { } void PBDodyTab::OnFinalRelease() { // When the last reference for an automation object is released // OnFinalRelease is called. The base class will automatically // deletes the object. Add additional cleanup required for your // object before calling the base class. CTabCtrl::OnFinalRelease(); } BEGIN_MESSAGE_MAP(PBDodyTab, CTabCtrl) END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(PBDodyTab, CTabCtrl) END_DISPATCH_MAP() // Note: we add support for IID_IPBDodyTab to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .IDL file. // {35C830F1-59A2-40B2-971F-2BEEC5930188} static const IID IID_IPBDodyTab = { 0x35C830F1, 0x59A2, 0x40B2, { 0x97, 0x1F, 0x2B, 0xEE, 0xC5, 0x93, 0x1, 0x88 } }; BEGIN_INTERFACE_MAP(PBDodyTab, CTabCtrl) INTERFACE_PART(PBDodyTab, IID_IPBDodyTab, Dispatch) END_INTERFACE_MAP() // PBDodyTab message handlers <file_sep>#ifndef __xDistributedClient_h #define __xDistributedClient_h #include "xDistributedObject.h" class xDistributedClient : public xDistributedObject { typedef xDistributedObject Parent; public: xDistributedClient(); virtual ~xDistributedClient(); enum MaskBits { InitialMask = (1 << 0), ///< This mask bit is never set explicitly, so it can be used for initialization data. NameMask = (1 << 1), ///< This mask bit is set when the position information changes on the server. MessageMask = (1 << 2), ///< This mask bit is set when the position information changes on the server. }; void onGhostRemove(); bool onGhostAdd(TNL::GhostConnection *theConnection); void onGhostAvailable(TNL::GhostConnection *theConnection); TNL::U32 packUpdate(TNL::GhostConnection *connection, TNL::U32 updateMask, TNL::BitStream *stream); void unpackUpdate(TNL::GhostConnection *connection, TNL::BitStream *stream); void performScopeQuery(TNL::GhostConnection *connection); TNL::StringPtr getLocalAddress() const { return m_localAddress; } void setLocalAddress(TNL::StringPtr val) { m_localAddress = val; } virtual void destroy(); void writeControlState(TNL::BitStream *stream); void readControlState(TNL::BitStream * bstream); void pack(TNL::BitStream *bstream); void unpack(TNL::BitStream *bstream,float sendersOneWayTime); int mUserFlags; int getUserFlags() const { return mUserFlags; } void setUserFlags(int val) { mUserFlags = val; } TNL::StringPtr mUserName; TNL::StringPtr getUserName() const { return mUserName; } void setUserName(TNL::StringPtr val) { mUserName = val; } TNL_DECLARE_RPC(rpcSetName, (TNL::StringPtr name)); TNL::BitSet32 mClientFlags; TNL::BitSet32& getClientFlags() { return mClientFlags; } void setClientFlags(TNL::BitSet32 val) { mClientFlags = val; } void setCurrentOutMessage(xMessage* msg); xMessage*getCurrentMessage(){ return mCurrentMessage ; } xMessage *mCurrentMessage; void calculateUpdateBits(); uxString print(TNL::BitSet32 flags); protected: int m_UserID; TNL::StringPtr m_localAddress; public: TNL_DECLARE_CLASS(xDistributedClient); }; #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #define PARAMETER_OP_TYPE_WHEEL_GETCONTACT CKGUID(0x74654a40,0x74ba3b5b) #define PARAMETER_OP_TYPE_WDATA_GET_COLLIDER CKGUID(0x4dae6732,0x37740a24) #define PARAMETER_OP_TYPE_WDATA_GET_MATERIAL CKGUID(0xa45301e,0x73e41d8f) #define PARAMETER_OP_TYPE_WDATA_GET_CPOINT CKGUID(0x2f731ff8,0xa792311) void ParamOpWheelContactGetCollider(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (p1) { if (p1->GetRealSource()) { CK_ID value = vtTools::ParameterTools::GetValueFromParameterStruct<CK_ID>(p1->GetRealSource(),E_WCD_CONTACT_ENTITY,false); res->SetValue(&value); } } } void ParamOpWheelContactGetMaterial(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); if (p1) { if (p1->GetRealSource()) { CKParameterOut *materialParameter = vtTools::ParameterTools::GetParameterFromStruct(p1->GetRealSource(),E_WCD_OTHER_MATERIAL_INDEX,false); if (materialParameter) { res->CopyValue(materialParameter); } } } } void ParamOpWheelGetContact(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); pRigidBody *body = NULL; //user comes usually with entity which is associated with the wheel and not with the body reference : body = GetPMan()->getBody(pFactory::Instance()->getMostTopParent(ent)); if (!body) return; pWheel2 *wheel =(pWheel2*)body->getWheel(ent); if (!wheel)return; pWheelContactData cData = *wheel->getContact(); //copy result in the parameter operations result parameter : pFactory::Instance()->copyTo(res,cData); } void PhysicManager::_RegisterParameterOperationsVehicle() { CKParameterManager *pm = m_Context->GetParameterManager(); pm->RegisterOperationType(PARAMETER_OP_TYPE_WHEEL_GETCONTACT, "pwGContact"); pm->RegisterOperationFunction(PARAMETER_OP_TYPE_WHEEL_GETCONTACT,VTS_WHEEL_CONTACT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpWheelGetContact); ////////////////////////////////////////////////////////////////////////// // member retrieve of the type pWheelContactData : //other entity : pm->RegisterOperationType(PARAMETER_OP_TYPE_WDATA_GET_COLLIDER, "wcdGEntity"); pm->RegisterOperationFunction(PARAMETER_OP_TYPE_WDATA_GET_COLLIDER,CKPGUID_3DENTITY,VTS_WHEEL_CONTACT,CKPGUID_NONE,ParamOpWheelContactGetCollider); //material pm->RegisterOperationType(PARAMETER_OP_TYPE_WDATA_GET_MATERIAL, "wcdGMaterial"); pm->RegisterOperationFunction(PARAMETER_OP_TYPE_WDATA_GET_MATERIAL,VTS_MATERIAL,VTS_WHEEL_CONTACT,CKPGUID_NONE,ParamOpWheelContactGetMaterial); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" int pVehicleMotor::loadNewTorqueCurve(pLinearInterpolation newTCurve) { _torqueCurve.clear(); _torqueCurve = newTCurve; NxReal maxTorque = 0; NxI32 maxTorquePos = -1; for (NxU32 i = 0; i < _torqueCurve.getSize(); i++) { NxReal v = _torqueCurve.getValueAtIndex(i); if (v > maxTorque) { maxTorque = v; maxTorquePos = i; } } _maxTorque = maxTorque; _maxTorquePos = (float)maxTorquePos; return 1; } void pVehicleMotorDesc::setToDefault() { torqueCurve.clear(); minRpmToGearDown = 1000.0f; maxRpmToGearUp = 4000.f; maxRpm = 5000.f; minRpm = 1000.f; setToCorvette(); } void pVehicleMotorDesc::setToCorvette() { // Default should be values for a corvette! // These are corresponding numbers for rotations and torque (in rpm and Nm) /* torqueCurve.insert(1000.f, 193.f); torqueCurve.insert(2000.f, 234.f); torqueCurve.insert(4000.f, 275.f); torqueCurve.insert(5000.f, 275.f); torqueCurve.insert(6000.f, 166.f);*/ torqueCurve.insert(1000, 400); torqueCurve.insert(3000, 500); torqueCurve.insert(5000, 300); minRpmToGearDown = 1500.f; maxRpmToGearUp = 4000.f; minRpm = 1000.f; maxRpm = 5000.f; } bool pVehicleMotorDesc::isValid() const { if (torqueCurve.getSize() == 0) { fprintf(stderr, "pVehicleMotorDesc::isValid(): Empty TorqueCurve\n"); return false; } if (maxRpmToGearUp < minRpmToGearDown) { fprintf(stderr, "pVehicleMotorDesc::isValid(): maxRpmToGearUp (%2.3f) is smaller than minRpmToGearDown (%2.3f)\n", maxRpmToGearUp, minRpmToGearDown); return false; } return true; } int pVehicleMotor::changeGears(const pVehicleGears* gears, float threshold) const { NxI32 gear = gears->getGear(); if (_rpm > _maxRpmToGearUp && gear < gears->getMaxGear()) return 1; else if (_rpm < _minRpmToGearDown && gear > 1) return -1; /* NxReal normalTorque = _torqueCurve.getValue(_rpm); NxReal lowerGearRatio = gears->getRatio(gear-1); NxReal normalGearRatio = gears->getCurrentRatio(); NxReal upperGearRatio = gears->getRatio(gear+1); NxReal lowerGearRpm = _rpm / normalGearRatio * lowerGearRatio; NxReal upperGearRpm = _rpm / normalGearRatio * upperGearRatio; NxReal lowerTorque = _torqueCurve.getValue(lowerGearRpm); NxReal upperTorque = _torqueCurve.getValue(upperGearRpm); NxReal lowerWheelTorque = lowerTorque * lowerGearRatio; NxReal normalWheelTorque = normalTorque * normalGearRatio; NxReal upperWheelTorque = upperTorque * upperGearRatio; //printf("%2.3f %2.3f %2.3f\n", lowerWheelTorque, normalWheelTorque, upperWheelTorque); */ return 0; } <file_sep>/******************************************************************** created: 2006/11/17 created: 17:11:2006 7:11 filename: f:\ProjectRoot\current\vt_plugins\vt_PyCaller\behaviors\CallPython.cpp file path: f:\ProjectRoot\current\vt_plugins\vt_PyCaller\behaviors file base: CallPython file ext: cpp author: mc007 purpose: *********************************************************************/ #include "vt_python_funcs.h" //#include "vt_python_funcs.h" #include <iostream> #include "pyembed.h" #include "InitMan.h" using std::cout; #include <sstream> #include "vtTools.h" using namespace vtTools; CKObjectDeclaration *FillBehaviorCallPythonFuncDecl(); CKERROR CreateCallPythonProto(CKBehaviorPrototype **); int CallPythonFunc(const CKBehaviorContext& behcontext); CKERROR CallPythonFuncCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 3 #define BEH_OUT_MIN_COUNT 0 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorCallPythonFuncDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("CallPythonFunc"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x75251b1b,0x382129b8)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateCallPythonProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Python"); return od; } CKERROR CreateCallPythonProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("CallPythonFunc"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); proto->DeclareInParameter("File",CKPGUID_STRING); proto->DeclareInParameter("Func",CKPGUID_STRING); proto->DeclareInParameter("Reload",CKPGUID_BOOL); //proto->DeclareOutParameter("return",CKPGUID_STRING); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS|CKBEHAVIOR_VARIABLEPARAMETERINPUTS|CKBEHAVIOR_INTERNALLYCREATEDOUTPUTPARAMS|CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS|CKBEHAVIOR_VARIABLEOUTPUTS|CKBEHAVIOR_VARIABLEINPUTS)); //proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS|CKBEHAVIOR_VARIABLEPARAMETERINPUTS)); proto->SetFunction( CallPythonFunc ); proto->SetBehaviorCallbackFct(CallPythonFuncCB); *pproto = proto; return CK_OK; } int CallPythonFunc(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; //beh->ActivateInput(0,FALSE); XString File((CKSTRING) beh->GetInputParameterReadDataPtr(0)); XString Func((CKSTRING) beh->GetInputParameterReadDataPtr(1)); int reload=false; //= BehaviorTools::GetInputParameterValue<bool>(beh,2); beh->GetInputParameterValue(2,&reload); vt_python_man *pm = (vt_python_man*)ctx->GetManagerByGuid(INIT_MAN_GUID); CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); ////////////////////////////////////////////////////////////////////////// //python env test : if (!pm->pLoaded) { pm->m_Context->OutputToConsoleEx("You must load Python before !"); beh->ActivateOutput(1,false); return CKBR_BEHAVIORERROR; } ////////////////////////////////////////////////////////////////////////// //creating args : Arg_mmap argsout; using namespace vtTools::Enums; for (int i = BEH_IN_INDEX_MIN_COUNT ; i < beh->GetInputParameterCount() ; i++ ) { CKParameterIn *ciIn = beh->GetInputParameter(i); CKParameterType pType = ciIn->GetType(); SuperType sType = ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); const char *pname = pam->ParameterTypeToName(pType); switch (sType) { case vtSTRING: { argsout.insert(argsout.end(),std::make_pair(ParameterTools::GetParameterAsString(ciIn->GetRealSource()),Py_string)); break; } case vtFLOAT: { argsout.insert(argsout.end(),std::make_pair(ParameterTools::GetParameterAsString(ciIn->GetRealSource()),Py_real)); break; } case vtINTEGER: { argsout.insert(argsout.end(),std::make_pair(ParameterTools::GetParameterAsString(ciIn->GetRealSource()),Py_long)); break; } default : XString err("wrong input parameter type: "); err << ciIn->GetName() << "Only Types derivated from Interger,Float or String are acceptable"; ctx->OutputToConsole(err.Str(),FALSE ); return CKBR_BEHAVIORERROR; } } ////////////////////////////////////////////////////////////////////////// if( beh->IsInputActive(0) ) { try // always check for Python_exceptions { Python *py = pm->py; if (Func.Length()==0) { py->run_file(File.CStr()); beh->ActivateOutput(0,TRUE); return CKBR_OK; } PyObject *module = pm->InsertPModule(beh->GetID(),File,reload); PyObject* val = PyInt_FromLong(beh->GetID()); //pm->CurrentId(beh->GetID()); PyObject_SetAttrString( module , "bid", val); int bOutCount = beh->GetOutputParameterCount(); if (bOutCount) { CKParameterOut *ciIn = beh->GetOutputParameter(0); CKParameterType pType = ciIn->GetType(); SuperType sType = ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); const char *pname = pam->ParameterTypeToName(pType); switch (sType) { case vtSTRING: { std::string ret; pm->CallPyModule(beh->GetID(),Func,argsout,ret); CKParameterOut * pout = beh->GetOutputParameter(0); XString retx(ret.c_str()); pout->SetStringValue(retx.Str()); break; } case vtFLOAT: { double ret=0.0f; pm->CallPyModule(beh->GetID(),Func,argsout,ret); float retx = (float)ret; beh->SetOutputParameterValue(0,&retx); break; } case vtINTEGER: { long ret=0; pm->CallPyModule(beh->GetID(),Func,argsout,ret); int retx = (int)ret; beh->SetOutputParameterValue(0,&retx); break; } default : XString err("wrong output parameter type: "); err << ciIn->GetName() << "Only Types derivated from Interger,Float or String are acceptable"; ctx->OutputToConsole(err.Str(),FALSE ); return CKBR_BEHAVIORERROR; } } else { pm->py->call(Func.Str(),argsout); } beh->ActivateOutput(0,TRUE); } catch (Python_exception ex) { pm->m_Context->OutputToConsoleEx("PyErr : \t %s",(CKSTRING)ex.what()); std::cout << ex.what() << "pyexeption in beh : " << beh->GetName(); PyErr_Clear(); beh->ActivateOutput(1,TRUE); } beh->ActivateInput(0,false); } return CKBR_OK; } ////////////////////////////////////////////////////////////////////////// CKERROR CallPythonFuncCB(const CKBehaviorContext& behcontext) { /************************************************************************/ /* collecting data : */ /* */ CKBehavior *beh = behcontext.Behavior; CKContext* ctx = beh->GetCKContext(); CKParameterManager *pm = static_cast<CKParameterManager*>(ctx->GetParameterManager()); /************************************************************************/ /* process virtools callbacks : */ /* */ switch(behcontext.CallbackMessage) { case CKM_BEHAVIOREDITED: case CKM_BEHAVIORSETTINGSEDITED: { assert(beh && ctx); int p_count = beh->GetOutputParameterCount(); /*while( (BEH_OUT_MIN_COUNT ) < p_count ) { CKDestroyObject( beh->RemoveOutputParameter( --p_count) ); }*/ XString name("PyFunc: "); name << ((CKSTRING) beh->GetInputParameterReadDataPtr(1)); if ( strlen(((CKSTRING) beh->GetInputParameterReadDataPtr(1))) ==0) { XString name("PyFile: "); name << ((CKSTRING) beh->GetInputParameterReadDataPtr(0)); beh->SetName(name.Str()); break; } beh->SetName(name.Str()); break; } case CKM_BEHAVIORLOAD : { XString name("PyFunc: "); name << ((CKSTRING) beh->GetInputParameterReadDataPtr(1)); beh->SetName(name.Str()); if ( strlen(((CKSTRING) beh->GetInputParameterReadDataPtr(1))) ==0) { XString name("PyFile: "); name << ((CKSTRING) beh->GetInputParameterReadDataPtr(0)); beh->SetName(name.Str()); break; } } case CKM_BEHAVIORATTACH: { /*CKObject *bobj = (CKObject *)beh; CK_ID idb = bobj->GetID(); ctx->OutputToConsoleEx("beh id1 : %d",idb);*/ break; } } return CKBR_OK; }<file_sep>#ifndef __VEHICLE_AND_WHEEL_STRUCTS_H__ #define __VEHICLE_AND_WHEEL_STRUCTS_H__ /* typedef enum PS_WHEELSHAPE { E_WD_XML, E_WD_SUSPENSION, E_WD_SPRING_RES, E_WD_DAMP, E_WD_SPRING_BIAS, E_WD_MAX_BFORCE, E_WD_FSIDE, E_WD_FFRONT, E_WD_APPROX, E_WD_FLAGS, E_WD_SFLAGS, E_WD_LAT_FUNC, E_WD_LONG_FUNC, }; */ #endif<file_sep>#ifndef ACTORPICKING_H #define ACTORPICKING_H #include "Actors.h" #include "Joints.h" #ifdef USE_NX_DOUBLE_BUFFERED #include "NxdActor.h" #endif void LetGoActor(); bool PickActor(int x, int y); void MoveActor(int x, int y); void ViewProject(NxVec3 &v, int &xi, int &yi, float &depth); void ViewUnProject(int xi, int yi, float depth, NxVec3 &v); #endif //ACTORPICKING_H <file_sep>#ifndef __P_WHEEL_H__ #define __P_WHEEL_H__ #include "vtPhysXBase.h" #include "pDriveline.h" #include "pReferencedObject.h" #include "pCallbackObject.h" #include "pPacejka.h" class pDifferential; class pWheelContactModifyData; //#include "pWheelTypes.h" /** \addtogroup Vehicle @{ */ /** \brief Base class to handle a vehicle wheel. */ class MODULE_API pWheel : public pDriveLineComp { public: virtual ~pWheel() {} pWheel(pRigidBody *body,pWheelDescr *descr); pRigidBody * getBody() const { return mBody; } void setBody(pRigidBody * val) { mBody= val; } virtual void tick(bool handbrake, float motorTorque, float brakeTorque, NxReal dt) = 0; virtual NxActor * getTouchedActor() const; virtual VxVector getWheelPos() const = 0; virtual void setAngle(NxReal angle) = 0; virtual float getRpm() const = 0; virtual VxVector getGroundContactPos() const = 0; virtual float getRadius() const = 0; virtual bool hasGroundContact() const { return getTouchedActor() != NULL; } bool getWheelFlag(WheelFlags flag) const { return (mWheelFlags & flag) != 0; } NxActor *getActor() const { return mActor; } void setActor(NxActor* val) { mActor = val; } pRigidBody *mBody; NxActor *mActor; int mWheelFlags; int& getWheelFlags(){ return mWheelFlags; } float _wheelRollAngle; float& getWheelRollAngle() { return _wheelRollAngle; } void setWheelRollAngle(float val) { _wheelRollAngle = val; } pWheel1 *castWheel1(); pWheel2 *castWheel2(); virtual void _updateVirtoolsEntity(bool position,bool rotation)=0; virtual void _updateAgeiaShape(bool position,bool rotation)=0; int mEntID; int getEntID() const { return mEntID; } void setEntID(int val) { mEntID = val; } void setFlags(int flags); virtual void _tick(float dt){}; virtual int _constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); virtual pWheelContactData* getContact()=0; NxMat34 mWheelPose; virtual NxMat34& getWheelPose(){ return mWheelPose; } void setWheelPose(NxMat34 val) { mWheelPose = val; } }; class MODULE_API pWheel1 : public pWheel { public: pWheel1(pRigidBody *body,pWheelDescr *descr); pWheel1(); virtual void tick(bool handbrake, float motorTorque, float brakeTorque, float dt); virtual NxActor * getTouchedActor(); virtual VxVector getWheelPos() const; virtual void setAngle(float angle); virtual float getRpm() const; virtual VxVector getGroundContactPos() const { return getWheelPos(); } virtual float getRadius() const { return _radius; } ContactInfo *contactInfo; void _updateVirtoolsEntity(bool position,bool rotation); void _updateAgeiaShape(bool position,bool rotation); NxConvexShape* getWheelConvex() const { return wheelConvex; } void setWheelConvex(NxConvexShape* val) { wheelConvex = val; } NxCapsuleShape* getWheelCapsule() const { return wheelCapsule; } void setWheelCapsule(NxCapsuleShape* val) { wheelCapsule = val; } int _constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); void getSteeringDirection(NxVec3& dir); void updateContactPosition(); void updateAngularVelocity(float lastTimeStepSize, bool handbrake); void setWheelOrientation(const NxMat33& m); virtual void _tick(float dt); NxCapsuleShape* wheelCapsule; NxConvexShape* wheelConvex; NxMaterial* material; float _frictionToSide; float _frictionToFront; float _turnAngle; float _turnVelocity; float _radius; float _perimeter; float _angle; float _wheelWidth; float _maxSuspension; //NxReal _rpm; VxVector _maxPosition; pWheelContactData *getContact(); }; class MODULE_API pWheel2 : public pWheel , public xEngineObjectAssociation<CK3dEntity*>, public pCallbackObject { public: pWheel2(); pWheel2(pRigidBody *body,pWheelDescr *descr,CK3dEntity *wheelShapeReference); //---------------------------------------------------------------- // // vehicle // //---------------------------------------------------------------- // // new vehicle code : differential // pDifferential *differential; int differentialSide; // Which output from the diff void setDifferential(pDifferential *diff,int side); pDifferential *getDifferential(){ return differential; } int getDifferentialSide(){ return differentialSide; } pPacejka pacejka; pPacejka *getPacejka() { return &pacejka; } void setPacejka(pPacejka val) { pacejka = val; } // Translation VxVector position; // Position in CC wrt the body (!) VxVector velocity; // Velocity in wheel coords acceleration; VxVector acceleration; // For the suspension VxVector GetVelocity(){ return velocity; } VxVector GetAcceleration(){ return acceleration; } VxVector GetSlipVectorCC(){ return slipVectorCC; } VxVector GetPosContactWC(){ return posContactWC; } // Rotation VxVector rotation; // Current rotation VxVector rotationV; VxVector rotationA; // Rotation speed and acceleration // Braking float maxBrakingTorque; // Max. force when braking 100% float brakingFactor; // For example .58 for fronts, .42 back float lock; // Max angle of heading (radians) int stateFlags; float lowSpeedFactor; // How slow it is spinning float slipAngle; // Vel. vs. wheel dir in radians float slipRatio; // Ratio of wheel speed vs. velocity // Pre-calculated float distCGM; // Distance to center of geometry float angleCGM; // Angle (around car Y) of wheel float distCM; // Distance to center of mass float GetSlipAngle(){ return slipAngle; } float GetSlipRatio(){ return slipRatio; } float GetHeading(){ return rotation.y; } float GetRotation(){ return rotation.x; } float GetRotationV(){ return rotationV.x; } float GetLock(){ return lock; } // End forces VxVector forceVerticalCC; // Result of suspension+gravity float differentialSlipRatio; // SR calculated by differential eq. float tanSlipAngle; // From this, 'slipAngle' is derived float relaxationLengthLat; // 'b' in SAE 950311 float lastU; // To detect switching of long. speed float signU; // Sign of longitudinal speed float relaxationLengthLong; // 'B' in SAE 950311 float dampingFactorLong; // Damping at low speed float dampingFactorLat; // Damping laterally // Combined slip float csSlipLen; // Combined slip vector length float load; // Load on the wheel (N) float mass; // Mass of wheel+tyre float radius, width; float rollingCoeff; // Rolling resistance coefficient float toe; // Pre-rotating the wheel float ackermanFactor; // Scaling the steering angle float optimalSR,optimalSA; // Optimal slip ratio/angle (in rad) float tanOptimalSA; // Spring values float tireRate; // Spring vertical rate of tire // SAE 950311 float dampingCoefficientLat, // Amount of damping at low speed dampingCoefficientLong; float dampingSpeed; // Speed at which to start damping float getTireRate() const { return tireRate; } void setTireRate(float val) { tireRate = val; } void preCalculate(); void preAnimate(); void postAnimate(); void calcForces(); void calcVerticalForces(); void calcLongForces(); void calcLatForces(); void calcBreakForces(); void Integrate(); void postStep(); void cleanup(); // Physics void CalcSlipRatio(VxVector *velWheelCC); void CalcSlipAngle(); void CalcSlipVelocity(); void CalcLoad(); void CalcPacejka(); void CalcDamping(); void CalcWheelPosWC(); void CalcWheelAngAcc(); void CalcBodyForce(); void CalcAccelerations(); void updateSteeringPose(float rollangle,float steerAngle,float dt); void updatePosition(); void setSteering(float angle); float pWheel2::getSteerAngle(); void calculatePose(float dt); // Other state vars //rfloat load; // Load on the wheel (N) float radiusLoaded; // Rl = radius of loaded wheel to gnd float aligningTorque; // Mz in the SAE system //---------------------------------------------------------------- // // // VxVector torqueTC; // 3-dimensions of torque VxVector torqueBrakingTC; // Total braking torque (incl. rr) VxVector torqueRollingTC; // Rolling resistance VxVector torqueFeedbackTC; // Feedback (road reaction) VxVector forceRoadTC; // Because of slip ratio/angle VxVector forceDampingTC; // Damping if low-speed (SAE950311) VxVector forceBrakingTC; // Brakes VxVector forceBodyCC; // Force on body (for acc.) VxVector forceGravityCC; // Gravity that pulls wheel down float velMagnitude; // Length of slip velocity vector (obs) VxVector velWheelCC, // Real velocity of wheel velWheelTC; // Velocity in tire coords // End forces VxVector posContactWC; // Position of contact patch in WC VxVector slipVectorCC, // Diff of tire vs wheel velocity slipVectorTC; // In tire coords float slipVectorLength; // Magnitude of slipVector?C pLinearInterpolation crvSlipTraction; // Traction curve for slip ratio pLinearInterpolation crvSlipBraking; // Braking curve pLinearInterpolation crvLatForce; // Slip angle -> normalized lat. force pLinearInterpolation crvSlip2FC; // Effect of slip vel on frict. circle // Status VxVector slipVector; // Diff. of theorial v vs ACTUAL v float frictionCoeff; // Current friction coefficient float skidFactor; // How much skidding? 0..1 float slip2FCVelFactor; // Scaling of 'crvSlip2FC' X axis // Forces VxVector GetForceRoadTC(){ return forceRoadTC; } VxVector GetForceBodyCC(){ return forceBodyCC; } VxVector GetTorqueTC(){ return torqueTC; } // Feedback torque is the road reaction torque VxVector GetTorqueFeedbackTC(){ return torqueFeedbackTC; } VxVector GetTorqueBrakingTC(){ return torqueBrakingTC; } VxVector GetTorqueRollingTC(){ return torqueRollingTC; } float getCsSlipLen() const { return csSlipLen; } void setCsSlipLen(float val) { csSlipLen = val; } VxVector getVelWheelCC() const { return velWheelCC; } void setVelWheelCC(VxVector val) { velWheelCC = val; } VxVector getVelWheelTC() const { return velWheelTC; } void setVelWheelTC(VxVector val) { velWheelTC = val; } float getRollingCoeff() { return rollingCoeff; } void setRollingCoeff(float val) { rollingCoeff = val; } float getMass(); void setMass(float val) { mass = val; } bool hadContact; //NxWheelContactData *lastContactData; pWheelContactData *lastContactData;// = *wheel2->getContact(); virtual void tick(bool handbrake, float motorTorque, float brakeTorque, float dt); virtual NxActor * getTouchedActor() const; virtual VxVector getWheelPos() const; virtual void setAngle(float angle); virtual float getRpm() const; VxVector getGroundContactPos() const; bool hasGroundContact() const ; float getRadius()const; NxWheelShape * getWheelShape() const { return mWheelShape; } void setWheelShape(NxWheelShape * val) { mWheelShape = val; } void setAxleSpeed(float speed); void setMotorTorque(float torque); void setBreakTorque(float torque); float getSuspensionTravel() const; float getAxleSpeed()const; void _updateVirtoolsEntity(bool position,bool rotation); void _updateAgeiaShape(bool position,bool rotation); bool setSuspensionSpring(const pSpring& spring); pSpring getSuspensionSpring(); void setSuspensionTravel(float travel); int _constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation){ return 1;} pWheelContactData *getContact(); bool getContact(pWheelContactData&dst); virtual void _tick(float dt); pVehicle * getVehicle() const { return mVehicle; } void setVehicle(pVehicle * val) { mVehicle = val; } //---------------------------------------------------------------- // // manager calls // int onPreProcess(); int onPostProcess(); void processPostScript(); void processPreScript(); virtual bool onWheelContact(CK3dEntity* wheelShapeReference, VxVector& contactPoint, VxVector& contactNormal, float& contactPosition, float& normalForce, CK3dEntity* otherShapeReference, int& otherShapeMaterialIndex); virtual void setWheelContactScript(int val); virtual bool onWheelContactModify(int& changeFlags,pWheelContactModifyData *contact); pWheelContactModify *wheelContactModifyCallback; void _createInternalContactModifyCallback(); //---------------------------------------------------------------- // // physics // float getEndBrakingTorqueForWheel(); float getEndTorqueForWheel(); float getEndAccForWheel(); float getWheelTorque(); float getWheelBreakTorque(); bool isAxleSpeedFromVehicle(); bool isTorqueFromVehicle(); void applyTorqueToPhysics(); void applyAxleSpeedToPhysics(); CK3dEntity * getEntity() const { return entity; } void setEntity(CK3dEntity * val) { entity = val; } private: NxWheelShape * mWheelShape; pVehicle *mVehicle; CK3dEntity *entity; }; /** @} */ #endif<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <virtools/vt_tools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "vtNetConfig.h" #ifdef CK_LIB #define RegisterBehaviorDeclarations Register_TOOLS_BehaviorDeclarations #define InitInstance _TOOLS_InitInstance #define ExitInstance _TOOLS_ExitInstance #define CKGetPluginInfoCount CKGet_TOOLS_PluginInfoCount #define CKGetPluginInfo CKGet_TOOLS_PluginInfo #define g_PluginInfo g_TOOLS_PluginInfo #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #endif CKPluginInfo g_PluginInfo; PLUGIN_EXPORT int CKGetPluginInfoCount(){return 2;} CKERROR InitInstanc1e(CKContext* context); vtNetworkManager *nm = NULL; CKERROR InitInstance(CKContext* context) { CKParameterManager* pm = context->GetParameterManager(); vtNetworkManager* initman =new vtNetworkManager(context); nm = initman; initman->RegisterVSL(); initman->RegisterParameters(); return CK_OK; } CKERROR ExitInstance(CKContext* context) { vtNetworkManager* initman =(vtNetworkManager*)context->GetManagerByGuid(NET_MAN_GUID); delete initman; return CK_OK; } #define INIT_BEH_GUID CKGUID(0x8ac02ae,0x224341f4) PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) { switch (Index) { case 0: g_PluginInfo.m_Author = "<NAME>"; g_PluginInfo.m_Description = "Network Building Blocks"; g_PluginInfo.m_Extension = ""; g_PluginInfo.m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo.m_Version = 0x000001; g_PluginInfo.m_InitInstanceFct = NULL; g_PluginInfo.m_ExitInstanceFct = NULL; g_PluginInfo.m_GUID = INIT_BEH_GUID; g_PluginInfo.m_Summary = "Network Building Blocks"; break; case 1: g_PluginInfo.m_Author = "<NAME>"; g_PluginInfo.m_Description = "Network Manager"; g_PluginInfo.m_Extension = ""; g_PluginInfo.m_Type = CKPLUGIN_MANAGER_DLL; g_PluginInfo.m_Version = 0x000001; g_PluginInfo.m_InitInstanceFct = InitInstance; g_PluginInfo.m_ExitInstanceFct = ExitInstance; g_PluginInfo.m_GUID = NET_MAN_GUID; g_PluginInfo.m_Summary = "Network Manager"; break; } return &g_PluginInfo; } #undef HAS_DISTOBJECTS PLUGIN_EXPORT void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg); void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) { RegisterBehavior(reg,FillBehaviorConnectToServerDecl); RegisterBehavior(reg,FillBehaviorLogEntryDecl); RegisterBehavior(reg,FillBehaviorGetIncomingUserDecl); RegisterBehavior(reg,FillBehaviorGetOutgoingUserUserDecl); RegisterBehavior(reg,FillBehaviorSetUserNameDecl); RegisterBehavior(reg,FillBehaviorUserNameModifiedDecl); RegisterBehavior(reg,FillBehaviorNDisconnectDecl); RegisterBehavior(reg,FillBehaviorDOCreateDistributedObjectDecl); RegisterBehavior(reg,FillBehaviorDODistributedObjectCreatedDecl); RegisterBehavior(reg,FillBehaviorDOUserValueModifiedDecl); RegisterBehavior(reg,FillBehaviorDOBindDecl); RegisterBehavior(reg,FillBehaviorDODestroyDecl); RegisterBehavior(reg,FillBehaviorDODestroyedDecl); RegisterBehavior(reg,FillBehaviorDOSetUserValueDecl); RegisterBehavior(reg,FillBehaviorDOControlDecl); RegisterBehavior(reg,FillBehaviorDOOwnerChangedDecl); RegisterBehavior(reg,FillBehaviorDOGetCurrentOwnerDecl); RegisterBehavior(reg,FillBehaviorDOReleaseDecl); ////////////////////////////////////////////////////////////////////////// RegisterBehavior(reg,FillBehaviorNSCreateObjectDecl); RegisterBehavior(reg,FillBehaviorNSGetListObjectDecl); RegisterBehavior(reg,FillBehaviorNSJoinObjectDecl); RegisterBehavior(reg,FillBehaviorNSLeaveObjectDecl); RegisterBehavior(reg,FillBehaviorNSLockObjectDecl); RegisterBehavior(reg,FillBehaviorNSUnlockObjectDecl); RegisterBehavior(reg,FillBehaviorNSRemoveUserDecl); RegisterBehavior(reg,FillBehaviorNMSendDecl); RegisterBehavior(reg,FillBehaviorNMWaiterDecl); RegisterBehavior(reg,FillBehaviorNCheckForLanServerDecl); RegisterBehavior(reg,FillBehaviorDebugTextDecl); RegisterBehavior(reg,FillBehaviorNServerStartDecl); RegisterBehavior(reg,FillBehaviorNServerStopDecl); RegisterBehavior(reg,FillBehaviorNServerIsRunningDecl); RegisterBehavior(reg,FillBehaviorNGetInterfacesDecl); RegisterBehavior(reg,FillBehaviorNSetParametersDecl); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pConfig.h" #ifdef DONGLE_VERSION #include "matrix32.h" #endif long DataIn[256]; /* Buffer to read the Dongle data */ long DataOut[256]; /* Buffer for data to be stored */ long DataBlock[2]; /* Data buffer for Encrypt/Decrypt */ short RetCode; /* Return value */ long API_Version; /* Version number of the Matrix-API */ long DNG_Version; /* Dongle version number */ short DNG_LPTADR; /* Adress of LPT port */ short DNG_Count; /* Number of Dongles connected */ short DNG_Mem; /* Memory size of Dongle */ short DNG_MaxVar; /* Maximum number of data fields */ short AppSlot; /* Application-Slot for Network access */ short i; int netMode = 0; short DNG_Port = 1; long UserCode = 4002529; int DONGLE_BASIC_VERSION_KEY_1 = 28071977; int DONGLE_BASIC_VERSION_KEY_2 = 77917082; int DONGLE_BASIC_VERSION_KEY_1_ENC = 364898188; int DONGLE_BASIC_VERSION_KEY_2_ENC = 930141357; int DONGLE_ADVANCED_VERSION_KEY1 = 56143954; int DONGLE_ADVANCED_VERSION_KEY2 = 45934165; extern PhysicManager*manager; #ifdef DONGLE_VERSION #pragma comment(lib,"matrix32.lib") void PhysicManager::_initResources(int flags){ // Init Matrix-API RetCode = Init_MatrixAPI(); if(RetCode < 0) { printf("Init_MatrixAPI failed %d \n", RetCode); exit; } API_Version = GetVersionAPI(); if(API_Version == 0) { printf("Cannot read API-Version! \n"); Release_MatrixAPI(); return; } // Search for number of Dongles at DNG_Port DNG_Port = Dongle_Find(); DNG_Count = Dongle_Count(DNG_Port); long test = 0 ; if(DNG_Count > 0) { //manager->m_Context->OutputToConsoleEx("Matrix-Modules at Port %d: %d \n", DNG_Port, DNG_Count); } else { XString donglePath = _getConfigPath(); //manager->m_Context->OutputToConsoleEx("Cannot find Matrix-Modules at Port %d ! \n", DNG_Port); //return; //goto NETWORK_CHECK; int ret = SetConfig_MatrixNet(1,donglePath.Str()); int DNG_NR = 1; AppSlot = 1; ret = LogIn_MatrixNet(UserCode, AppSlot, DNG_NR); if (ret<=0) { MessageBox(NULL,"Couldn't find Dongle!",0,MB_OK|MB_ICONERROR); this->DongleHasBasicVersion=0; this->DongleHasAdvancedVersion=0; //Release_MatrixAPI(); return; } netMode = 1; DNG_Port = Dongle_Find(); DNG_Count = Dongle_Count(DNG_Port); if(DNG_Count == 0) { manager->m_Context->OutputToConsoleEx("Couldn't find Dongle"); } } DNG_Mem = Dongle_MemSize(DNG_Count, DNG_Port); if(DNG_Mem > 0) { //manager->m_Context->OutputToConsoleEx("MemSize of Matrix-Module %d at Port %d: %d Bytes \n", DNG_Count, DNG_Port, DNG_Mem); } else { //manager->m_Context->OutputToConsoleEx("Cannot read MemSize! \n"); Release_MatrixAPI(); return; } RetCode = Dongle_ReadData(UserCode, DataIn,6, DNG_Count, DNG_Port); if(RetCode < 0) { m_Context->OutputToConsoleEx("Data Read-Error! \n"); Release_MatrixAPI(); return; } DataBlock[0] = 28071977; /* Clear Data */ DataBlock[1] = 77917082; /* Clear Data */ long DataBlockKeyBasic[2]; DataBlockKeyBasic[0] = DataIn[2]; DataBlockKeyBasic[1] = DataIn[3]; long DataBlockKeyAdvanced[2]; DataBlockKeyAdvanced[0] = DataIn[4]; DataBlockKeyAdvanced[1] = DataIn[5]; RetCode = Dongle_DecryptData(UserCode, DataBlockKeyBasic, DNG_Count, DNG_Port); RetCode = Dongle_DecryptData(UserCode, DataBlockKeyAdvanced, DNG_Count, DNG_Port); if (netMode) { if (DataBlockKeyBasic[0]==DONGLE_BASIC_VERSION_KEY_1_ENC && DataBlockKeyBasic[1]==DONGLE_BASIC_VERSION_KEY_2_ENC ) { DongleHasBasicVersion= 1; } }else { if (DataBlockKeyBasic[0]==DONGLE_BASIC_VERSION_KEY_1 && DataBlockKeyBasic[1]==DONGLE_BASIC_VERSION_KEY_2 ) { DongleHasBasicVersion= 1; } if (DataBlockKeyAdvanced[0]==DONGLE_ADVANCED_VERSION_KEY1 && DataBlockKeyAdvanced[1]==DONGLE_ADVANCED_VERSION_KEY2) { DongleHasAdvancedVersion=1; } } Release_MatrixAPI(); } #endif /* #ifdef REDIST #endif */ /* #ifdef DEMO_ONLY void FindResourceX() { } #endif */ /* #if defined (DONGLE_VERSION) void PhysicManager::makeDongleTest() { //FindResourceX(); } */ /* void MODULE_API FindResourceX() { RetCode = Init_MatrixAPI(); if(RetCode < 0) { printf("Init_MatrixAPI failed %d \n", RetCode); exit; } API_Version = GetVersionAPI(); if(API_Version == 0) { printf("Cannot read API-Version! \n"); Release_MatrixAPI(); return; } else { // printf("Version of Matrix-API: %d.%d \n", HIWORD(API_Version), LOWORD(API_Version)); // manager->m_Context->OutputToConsoleEx("Version of Matrix-API: %d.%d \n", HIWORD(API_Version), LOWORD(API_Version)); } int port = Dongle_Find(); DNG_Count = Dongle_Count(port); DNG_Port = port; if(DNG_Count > 0) { //manager->m_Context->OutputToConsoleEx("Matrix-Modules at Port %d: %d \n", DNG_Port, DNG_Count); } else { //goto NETWORK //manager->m_Context->OutputToConsoleEx("Cannot find Matrix-Modules at Port %d ! \n", DNG_Port); Release_MatrixAPI(); return; } DNG_Mem = Dongle_MemSize(DNG_Count, DNG_Port); if(DNG_Mem > 0) { //manager->m_Context->OutputToConsoleEx("MemSize of Matrix-Module %d at Port %d: %d Bytes \n", DNG_Count, DNG_Port, DNG_Mem); } else { //manager->m_Context->OutputToConsoleEx("Cannot read MemSize! \n"); Release_MatrixAPI(); return; } RetCode = Dongle_ReadData(UserCode, DataIn,6, DNG_Count, DNG_Port); if(RetCode < 0) { manager->m_Context->OutputToConsoleEx("Data Read-Error! \n"); Release_MatrixAPI(); return; } DataBlock[0] = 28071977; DataBlock[1] = 77917082; long DataBlockKeyBasic[2]; DataBlockKeyBasic[0] = DataIn[2]; DataBlockKeyBasic[1] = DataIn[3]; long DataBlockKeyAdvanced[2]; DataBlockKeyAdvanced[0] = DataIn[4]; DataBlockKeyAdvanced[1] = DataIn[5]; RetCode = Dongle_DecryptData(UserCode, DataBlockKeyBasic, DNG_Count, DNG_Port); RetCode = Dongle_DecryptData(UserCode, DataBlockKeyAdvanced, DNG_Count, DNG_Port); //manager->m_Context->OutputToConsoleEx("Decrypted Data: %lu %lu \n", DataBlockKeyBasic[0], DataBlockKeyBasic[1]); //manager->m_Context->OutputToConsoleEx("Decrypted Data: %lu %lu \n", DataBlockKeyAdvanced[0], DataBlockKeyAdvanced[1]); if (DataBlockKeyBasic[0]==DONGLE_BASIC_VERSION_KEY_1 && DataBlockKeyBasic[1]==DONGLE_BASIC_VERSION_KEY_2 ) { // DongleHasBasicVersion= 1; } if (DataBlockKeyAdvanced[0]==DONGLE_ADVANCED_VERSION_KEY1 && DataBlockKeyAdvanced[1]==DONGLE_ADVANCED_VERSION_KEY2) { // DongleHasAdvancedVersion= 1; } //manager->m_Context->OutputToConsoleEx("Clear Data: %lu %lu \n", DataBlock[0], DataBlock[1]); //manager->m_Context->OutputToConsoleEx("Encrypted Data: %lu %lu \n", DataBlock[0], DataBlock[1]); Release_MatrixAPI(); } #endif */<file_sep>#ifndef __PRIGIDBODYTYPES_H__ #define __PRIGIDBODYTYPES_H__ #include "vtPhysXBase.h" #include "pVTireFunction.h" //#include "pWheelTypes.h" /** \addtogroup RigidBody @{ */ struct pRigidBodyRestoreInfo { bool hierarchy; bool removeJoints; pRigidBodyRestoreInfo() : hierarchy(false) , removeJoints(false){} }; /** \brief Class describing a rigid bodies mass offset. */ class MODULE_API pMassSettings { public: /** \brief Density scale factor of the shapes belonging to the body - <b>Range:</b> [0,inf) - <b>Default:</b> [0) **/ float newDensity; /** \brief Total mass of the actor(or zero). - <b>Range:</b> [0,inf) - <b>Default:</b> 0.0f **/ float totalMass; /** \brief Local position offset - <b>Range:</b> [vector) - <b>Default:</b> (0,0,0) **/ VxVector localPosition; /** \brief Local orientation offset - <b>Range:</b> [0,inf) - <b>Default:</b> (0,0,0) **/ VxVector localOrientation; /** \brief Reference object to determine the mass local position. The members "Linear" and "Angular" are being used to transform the final matrix. - <b>Range:</b> [object) - <b>Default:</b> 0 **/ CK_ID massReference; pMassSettings() { newDensity = totalMass = 0.0f; massReference = 0 ; } }; /** \brief Class to describe a pivot offset */ class MODULE_API pPivotSettings { public: bool isValid(); bool setToDefault(); bool evaluate(CKBeObject*referenceObject); /** \brief Local position offset. The local position of can be changed by #pRigidBody::setPosition - <b>Range:</b> [vector) - <b>Default:</b> (0,0,0) **/ VxVector localPosition; /** \brief Local orientation offset. The local orientation of can be changed by #pRigidBody::setRotation - <b>Range:</b> [0,inf) - <b>Default:</b> (0,0,0) **/ VxVector localOrientation; /** \brief Reference object to determine the shape local matrix. The members "Linear" and "Angular" are being used to transform the final matrix. - <b>Range:</b> [object) - <b>Default:</b> 0 **/ CK_ID pivotReference; pPivotSettings() { pivotReference=0; } }; //---------------------------------------------------------------- // //! \brief Help info to specify a length by an entity reference // class MODULE_API pAxisReferencedLength { public: bool isValid(); bool setToDefault(); bool evaluate(CKBeObject *referenceObject); float value; CKBeObject *reference; int referenceAxis; pAxisReferencedLength() : value(0.0f) , reference(NULL) , referenceAxis(0) { } }; //---------------------------------------------------------------- // //! \brief Additional information for deformable objects // struct MODULE_API pDeformableSettings { public : bool isValid(); bool setToDefault(); bool evaluate(CKBeObject*referenceObject); float ImpulsThresold; float PenetrationDepth; float MaxDeform; pDeformableSettings() { ImpulsThresold = 50.0f; PenetrationDepth = 0.1f ; MaxDeform= 0.1f; } }; //---------------------------------------------------------------- // //! \brief Additional settings to override a default capsule // struct pCapsuleSettings { public : int localLengthAxis; int localRadiusAxis; float height; float radius; pCapsuleSettings() { localRadiusAxis=0; localLengthAxis=0; height = 0.0f; radius = 0.0f; } }; //---------------------------------------------------------------- // //! \brief Additional settings to override a default capsule // struct MODULE_API pCapsuleSettingsEx { public : bool isValid(); bool setToDefault(); bool evaluate(CKBeObject*referenceObject); /** \brief Radius specified by value or an objects local box size and an axis **/ pAxisReferencedLength radius; /** \brief Height specified by value or an objects local box size and an axis **/ pAxisReferencedLength height; pCapsuleSettingsEx() { } }; //---------------------------------------------------------------- // //! \brief Optional override to describe a convex cylinder. // class MODULE_API pConvexCylinderSettings { public: bool isValid(); bool setToDefault(); bool evaluate(CKBeObject*referenceObject); /** \brief Radius specified by value or an objects local box size and an axis **/ pAxisReferencedLength radius; /** \brief Height specified by value or an objects local box size and an axis **/ pAxisReferencedLength height; /** \brief Amount of cap segments **/ int approximation; /** \brief Rotation part 1. If a forward axis reference has been specified, the vector gets transformed **/ VxVector forwardAxis; /** \brief Reference to specify the "Dir" axis **/ CK_ID forwardAxisRef; /** \brief Rotation part 2. If a down axis reference has been specified, the vector gets transformed **/ VxVector downAxis; /** \brief Reference to specify the "Up" axis **/ CK_ID downAxisRef; /** \brief Rotation part 3. If a right axis reference has been specified, the vector gets transformed **/ VxVector rightAxis; /** \brief Reference to specify the "Right" axis **/ CK_ID rightAxisRef; /** \brief Create only a half cylinder */ bool buildLowerHalfOnly; /** \brief Flags which describe the format and behavior of a convex mesh. See #pConvexFlags */ pConvexFlags convexFlags; pConvexCylinderSettings() : approximation(0), forwardAxisRef(0), rightAxisRef(0), downAxisRef(0), buildLowerHalfOnly(false) { setToDefault(); convexFlags=((pConvexFlags)(CF_ComputeConvex)); } }; class MODULE_API pWheelDescr { public : //################################################################ // // Wheel Capsule Specific // int wheelApproximation; pAxisReferencedLength radius; float width; //################################################################ // // Wheel Common Attributes // float wheelSuspension; float springRestitution; float springDamping; float springBias; float maxBrakeForce; float frictionToSide; float frictionToFront; WheelFlags wheelFlags; //################################################################ // // Wheel Shape Specific // WheelShapeFlags wheelShapeFlags; float inverseWheelMass; pConvexCylinderSettings convexCylinder; pConvexCylinderSettings getConvexCylinderSettings() { return convexCylinder; } void setConvexCylinderSettings(pConvexCylinderSettings val) { convexCylinder = val; } pTireFunction latFunc;int latFuncXML_Id; pTireFunction longFunc;int longFuncXML_Id; pWheelDescr(){ setToDefault(); } ~pWheelDescr(){} void* userData; void setToDefault(); bool isValid() const; }; //---------------------------------------------------------------- // //! \brief Container to store joints // typedef XArray<pJoint*>JointListType; class pClothDescr { }; /** ! \brief Describes a rigid body. This is used by #pFactory::createBody() and #pRigidBody::addSubShape() only. */ class MODULE_API pObjectDescr { public : int mask; typedef enum E_OD_VERSION { OD_DECR_V0, OD_DECR_V1, }; CK_ID worlReference; int version; /** \brief The shape type of the body. Default = HT_Sphere. */ HullType hullType; /** \brief The shape type of the body. Default = 1.0f. */ float density; /** \brief Translates the mass center after the body is created in local space. */ VxVector massOffset; /** \brief Translates the pivot after the body is created in local space. */ VxVector shapeOffset; /** \brief Translates the pivot after the body is created in local space. */ VxVector pivotOffsetLinear; /** \brief Translates the pivot after the body is created in local space. */ CK_ID pivotOffsetReference; /** \brief Translates the pivot after the body is created in local space. */ VxVector pivotOffsetAngular; /** \brief Describes several properties. See #BodyFlags. Default = 0. */ BodyFlags flags; /** \brief Will parse the entities hierarchy for additional sub shapes. Child objects needs to have the physic object attribute attached. Default = false. */ bool hirarchy; /** \brief If there are sub shape attached, #pRigidBodie::addSubShape will call #pRigidBody::updateMassFromShapes(). Default = 0.0f. */ float newDensity; /** \brief If there are sub shape attached, #pRigidBodie::addSubShape will call #pRigidBody::updateMassFromShapes(). Default = 0.0f. */ float totalMass; int subEntID; int transformationFlags; int internalXmlID; int externalXmlID; int xmlImportFlags; VxVector pivotAngularOffset; /************************************************************************************************/ /** @name Collision */ //@{ /** \brief Sets 128-bit mask used for collision filtering. See comments for ::pGroupsMask */ pGroupsMask groupsMask; /** \brief Adds an additional offset for collision response. */ float skinWidth; /** \brief The collision group the body belongs to. Default = 0. */ int collisionGroup; //@} /************************************************************************************************/ /** @name CCD Settings */ //@{ float ccdMotionThresold; int ccdFlags; CK_ID ccdMeshReference; float ccdScale; //@} /************************************************************************************************/ /** @name Damping */ //@{ /** \brief the linear damping. */ float linearDamping; /** \brief the angular damping. */ float angularDamping; //@} /************************************************************************************************/ /** @name Sleeping Settings */ //@{ float linearSleepVelocity; float angularSleepVelocity; float sleepingEnergyThresold; //@} /************************************************************************************************/ /** @name Optimization */ //@{ int solverIterations; int dominanceGroups; int compartmentID; //@} /************************************************************************************************/ /** @name Mass */ //@{ VxVector massOffsetLinear; VxVector massOffsetAngular; CK_ID massOffsetReference; //@} pOptimization optimization; pOptimization& getOptimization() { return optimization; } void setOptimization(pOptimization val) { optimization = val; } pMaterial material; pMaterial& getMaterial() { return material; } void setMaterial(pMaterial val) { material = val; } pCCDSettings ccd; pCCDSettings& getCCD() { return ccd; } void setCCD(pCCDSettings val) { ccd = val; } pCapsuleSettingsEx capsule; pCapsuleSettingsEx& getCapsule() { return capsule; } void setCapsule(pCapsuleSettingsEx val) { capsule = val; } pConvexCylinderSettings convexCylinder; pConvexCylinderSettings& getConvexCylinder() { return convexCylinder; } void setConvexCylinder(pConvexCylinderSettings val) { convexCylinder = val; } pMassSettings mass; pMassSettings& getMass() { return mass; } void setMass(pMassSettings val) { mass = val; } pPivotSettings pivot; pPivotSettings& getPivot() { return pivot; } void setPivot(pPivotSettings val) { pivot = val; } pCollisionSettings collision; pCollisionSettings& getCollision() { return collision; } void setCollision(pCollisionSettings val) { collision = val; } pWheelDescr wheel; pWheelDescr& getWheel() { return wheel; } void setWheel(pWheelDescr val) { wheel = val; } pObjectDescr() { setToDefault(); } bool isValid(); bool setToDefault(); }; //---------------------------------------------------------------- // //! \brief Meta data to track the relation between a NxShape and an CK3dEntity. //! Also used to track a wheel object in the NxShapes user data. // struct pSubMeshInfo { pObjectDescr initDescription; NxCCDSkeleton *ccdSkeleton; int meshID; CKBeObject *mesh; int entID; CKBeObject *refObject; CK_ID ccdReference; pWheel *wheel; pSubMeshInfo() { wheel = NULL; meshID = -1; entID = -1 ; mesh = NULL; refObject = NULL; ccdSkeleton = NULL; ccdReference = 0; } }; /** @} */ #endif // __PRIGIDBODYTYPES_H__<file_sep>/******************************************************************** created: 2009/02/17 created: 17:2:2009 10:21 filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\vtPhysXAll.h file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core file base: vtPhysXAll file ext: h author: <NAME> purpose: Common header for all definitions. Includes ALL ! *********************************************************************/ #ifndef __VTPHYSXALL_H__ #define __VTPHYSXALL_H__ #include "pTypes.h" //################################################################ // // Help types // //---------------------------------------------------------------- // //! \brief Include of necessary meta and extra structures. // #include "pTypes.h" #include "pWorldTypes.h" #include "pManagerTypes.h" #include "pJointTypes.h" #include "pRigidBodyTypes.h" #include "pVehicleTypes.h" #include "pWheelTypes.h" #include "pVehicleMotor.h" #include "pVehicleGears.h" #include "pClothTypes.h" //---------------------------------------------------------------- // //! \brief Logger // #include <xLogger.h> //################################################################ // // Implementation Objects // #include "PhysicManager.h" #include "pRigidBody.h" #include "pFactory.h" #include "pWorld.h" #include "pJoint.h" #include "pSerializer.h" #include "pWheel.h" #include "pCloth.h" //---------------------------------------------------------------- // //! \brief Vehicle Based Types // #include "pVehicle.h" //################################################################ // // Implementation Helper // #include "pMisc.h" //################################################################ // // Parameter Guids // #include "vtParameterGuids.h" //################################################################ // // NVDIA PhysX Objects // #include "NxPhysics.h" #include "NxUserOutputStream.h" #include "NxSceneDesc.h" #include "NxClothDesc.h" #include "NxFluidDesc.h" #include "NxFluidEmitterDesc.h" #include "NxConvexShapeDesc.h" #include "NxScene.h" #ifdef VTPX_HAS_CHARACTER_CONTROLLER #include "NxControllerManager.h" #include "NxCharacter.h" #include "NxBoxController.h" #include "NxCapsuleController.h" #include "pBoxController.h" #endif //################################################################ // // Generic Virtools Helpers // #include <virtools/vtTools.h> //################################################################ // // Math conversions // #include "pMathTools.h" using namespace pMath; #endif // __VTPHYSXALL_H__<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPClothAddDirectedForceAtPosDecl(); CKERROR CreatePClothAddDirectedForceAtPosProto(CKBehaviorPrototype **pproto); int PClothAddDirectedForceAtPos(const CKBehaviorContext& behcontext); CKERROR PClothAddDirectedForceAtPosCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_Pos, bbI_Force, bbI_Radius, bbI_ForceMode, }; //************************************ // Method: FillBehaviorPClothAddDirectedForceAtPosDecl // FullName: FillBehaviorPClothAddDirectedForceAtPosDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPClothAddDirectedForceAtPosDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAddDirectedForceAtPos"); od->SetCategory("Physic/Cloth"); od->SetDescription("Applies a directed force (or impulse) at a particular position. All vertices within radius will be affected with a quadratic drop-off. "); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x439b04ff,0x252950fc)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePClothAddDirectedForceAtPosProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePClothAddDirectedForceAtPosProto // FullName: CreatePClothAddDirectedForceAtPosProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePClothAddDirectedForceAtPosProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAddDirectedForceAtPos"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PClothAddDirectedForceAtPos PClothAddDirectedForceAtPos is categorized in \ref Clothes <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Applies a directed force (or impulse) at a particular position. All vertices within radius will be affected with a quadratic drop-off. <br> Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. @see pCloth::addDirectedForceAtPos() <h3>Technical Information</h3> \image html PClothAddDirectedForceAtPos.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>Target cloth reference. <BR> <SPAN CLASS="pin">Position: </SPAN>Position to apply force at. <BR> <SPAN CLASS="pin">Force: </SPAN>Force to apply. <BR> <SPAN CLASS="pin">Magnitude: </SPAN>Magnitude of the force/impulse to apply. <BR> <SPAN CLASS="pin">Radius: </SPAN>The sphere radius in which particles will be affected. <BR> <SPAN CLASS="pin">Force Mode: </SPAN>The mode to use when applying the force/impulse. (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange). <BR> */ proto->SetBehaviorCallbackFct( PClothAddDirectedForceAtPosCB ); proto->DeclareInParameter("Position",CKPGUID_VECTOR); proto->DeclareInParameter("Magnitude",CKPGUID_FLOAT); proto->DeclareInParameter("Radius",CKPGUID_FLOAT); proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PClothAddDirectedForceAtPos); *pproto = proto; return CK_OK; } //************************************ // Method: PClothAddDirectedForceAtPos // FullName: PClothAddDirectedForceAtPos // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PClothAddDirectedForceAtPos(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// pCloth *cloth = GetPMan()->getCloth(target->GetID()); if (!cloth) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } VxVector position= GetInputParameterValue<VxVector>(beh,bbI_Pos); VxVector force = GetInputParameterValue<VxVector>(beh,bbI_Force); float radius= GetInputParameterValue<float>(beh,bbI_Radius); int forceMode = GetInputParameterValue<int>(beh,bbI_ForceMode); cloth->addDirectedForceAtPos(position,force,radius,(ForceMode)forceMode); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PClothAddDirectedForceAtPosCB // FullName: PClothAddDirectedForceAtPosCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PClothAddDirectedForceAtPosCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; }<file_sep> PhysicManager pm = GetPhysicManager(); pRigidBody b = pm.getBody(body); if(b) { int collGroupMainShape = b.getCollisionsGroup(); bool isKinematic = b.isKinematic(); bool isGravityOn = b.isAffectedByGravity(); bool is collisionOn = b.isCollisionEnabled(); } <file_sep>#ifndef __PCROSS_TYPES_H__ #define __PCROSS_TYPES_H__ #include "pTypes.h" //#include "NxWheelDesc.h" #include "VxMath.h" #include "XString.h" #include "CK3DEntity.h" #include "pVTireFunction.h" #endif<file_sep>#include "pch.h" #include "CKAll.h" #include "FTP4W.H" CKObjectDeclaration *FillBehaviorFTPLoginDecl(); CKERROR CreateFTPLoginProto(CKBehaviorPrototype **pproto); int FTPLogin(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorFTPLoginDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("FTP Login"); od->SetDescription(""); od->SetCategory("Narratives/Files"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x3d100c46,0x206c6bc2)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateFTPLoginProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateFTPLoginProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("FTP Login"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Login"); proto->DeclareInput("Logout"); proto->DeclareOutput("Login Exit"); proto->DeclareOutput("Logout Exit"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Host", CKPGUID_STRING,"127.0.0.1"); proto->DeclareInParameter("User", CKPGUID_STRING,"ich"); proto->DeclareInParameter("Password", CKPGUID_STRING,"ich"); proto->DeclareInParameter("Port", CKPGUID_INT,"21"); proto->DeclareOutParameter("Error Code 0=ok", CKPGUID_INT,"0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(FTPLogin); *pproto = proto; return CK_OK; } #define LOG_FILE "c:\\ftp4w.log" int FTPLogin(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; if( beh->IsInputActive(0)){ beh->ActivateInput(0,FALSE); HWND win = (HWND)ctx->GetMainWindow(); FtpInit(win); //HFILE hLogFile = _lcreat (LOG_FILE, 0); //FtpLogTo (hLogFile); FtpSetDefaultTimeOut (30); FtpSetPassiveMode(TRUE); FtpSetAsynchronousMode(); int Port; beh->GetInputParameterValue(3,&Port); XString Host((CKSTRING) beh->GetInputParameterReadDataPtr(0)); XString User((CKSTRING) beh->GetInputParameterReadDataPtr(1)); XString Pw((CKSTRING) beh->GetInputParameterReadDataPtr(2)); int Login = FtpLogin(Host.Str(),User.Str(),Pw.Str(),win,0); beh->SetOutputParameterValue(0,&Login); if (Login == 0)beh->ActivateOutput(0); else{ beh->ActivateOutput(2); return CKBR_OK; } return CKBR_ACTIVATENEXTFRAME; } if( beh->IsInputActive(1)){ beh->ActivateInput(1,FALSE); FtpCloseConnection(); FtpRelease (); beh->ActivateOutput(1); return CKBR_OK; } return CKBR_ACTIVATENEXTFRAME; } <file_sep>#ifndef __PJOINT_H_ #define __PJOINT_H_ #include "vtPhysXBase.h" /** \addtogroup Joints @{ */ /** \brief Abstract base class for the different types of joints. All joints are used to connect two dynamic bodies, or an body and the environment. A NULL body represents the environment. Whenever the below comments mention two bodies, one of them may always be the environment (NULL). */ class MODULE_API pJoint { public: pJoint(){} pJoint(CK3dEntity* _e); pJoint(pRigidBody* _a,pRigidBody* _b,int _type); NxJoint *getJoint() { return mJoint;} void setJoint(NxJoint*j) { mJoint = j ;} ////////////////////////////////////////////////////////////////////////// protected : pRigidBody* m_SolidA; pRigidBody* m_SolidB; CK3dEntity* m_vtObjectA; CK3dEntity* m_vtObjectB; int m_type; pWorld *m_pWorld; NxJoint *mJoint; ////////////////////////////////////////////////////////////////////////// public : /** \brief Retrieve the type of this joint. \return The type of joint. \see NxJointType */ JType getType() const { return (JType)m_type; } CK3dEntity* GetVTEntA(){ return m_vtObjectA;} CK3dEntity* GetVTEntB(){ return m_vtObjectB;} pRigidBody *GetSolidA(); pRigidBody *GetSolidB(); CK_ID mAID; CK_ID mBID; pWorld * getWorld() const { return m_pWorld; } void setWorld(pWorld * val) { m_pWorld = val; } /** \brief Sets the maximum force magnitude that the joint is able to withstand without breaking. There are two values, one for linear forces, and one for angular forces. Both values are used directly as a value for the maximum impulse tolerated by the joint constraints. Both force values are MaxFloat by default. This setting makes the joint unbreakable. The values should always be nonnegative. The distinction between maxForce and maxTorque is dependent on how the joint is implemented internally, which may not be obvious. For example what appears to be an angular degree of freedom may be constrained indirectly by a linear constraint. So in most practical applications the user should set both maxTorque and maxForce to low values. <b>Sleeping:</b> This call wakes the body(s) if they are sleeping. \param[in] maxForce Maximum force the joint can withstand without breaking. <b>Range:</b> (0,inf] \param[in] maxTorque Maximum torque the joint can withstand without breaking. <b>Range:</b> (0,inf] */ void setBreakForces(float maxForce,float maxTorque); /** \brief Retrieves the max forces of a breakable joint. See #setBreakable(). \param[out] maxForce Retrieves the maximum force the joint can withstand without breaking. \param[out] maxTorque Retrieves the maximum torque the joint can withstand without breaking. */ void getBreakForces(float& maxForce,float& maxTorque); /** \brief Adds a limit plane. Both of the parameters are given in global coordinates. see setLimitPoint() for the meaning of limit planes. The plane is affixed to the body that does not have the limit point. The normal of the plane points toward the positive side of the plane, and thus toward the limit point. If the normal points away from the limit point at the time of this call, the method returns false and the limit plane is ignored. \note This function always returns true and adds the limit plane unlike earlier versions. This behavior was changed to allow the joint to be serialized easily. <b>Sleeping:</b> This call wakes the body(s) if they are sleeping. \param[in] normal Normal for the limit plane in global coordinates. <b>Range:</b> direction vector \param[in] pointInPlane Point in the limit plane in global coordinates. <b>Range:</b> position vector \param[in] restitution Restitution of the limit plane. <b>Range:</b> [0.0, 1.0] <b>Default:</b> 0.0 \return Always true. \see setLimitPoint() purgeLimitPlanes() getNextLimitPlane() */ int addLimitPlane(const VxVector normal, VxVector pointInPlane, float restitution=0.0f); /** \brief deletes all limit planes added to the joint. Invalidates limit plane iterator. <b>Sleeping:</b> Does <b>NOT</b> wake the associated body up automatically. \see addLimitPlane() getNextLimitPlane() */ void purgeLimitPlanes(); /** \brief Restarts the limit plane iteration. Call before starting to iterate. This method may be used together with the below two methods to enumerate the limit planes. This iterator becomes invalid when planes are added or removed, or the plane iterator mechanism is invoked on another joint. \see hasMoreLimitPlanes() getNextLimitPlane() */ void resetLimitPlaneIterator(); /** \brief Returns true until the iterator reaches the end of the set of limit planes. Adding or removing elements does not reset the iterator. \return True if the iterator has not reached the end of the sequence of limit planes. \see resetLimitPlaneIterator() getNextLimitPlane() */ int hasMoreLimitPlanes (); /** \brief Returns the next element pointed to by the limit plane iterator, and increments the iterator. Places the global frame plane equation (consisting of normal and d, the 4th element) coefficients in the argument references. The plane equation is of the form: dot(n,p) + d == 0 (n = normal, p = a point on the plane) \param[out] planeNormal Used to store the plane normal. \param[out] planeD Used to store the plane 'D'. \param[out] restitution Optional, used to store restitution of the limit plane. \return Returns true if the limit plane is satisfied. \see resetLimitPlaneIterator() hasMoreLimitPlanes() */ int getNextLimitPlane (VxVector &planeNormal, float &planeD,float *restitution=NULL); /** \brief Sets the limit point. The point is specified in the global coordinate frame. All types of joints may be limited with the same system: You may elect a point attached to one of the two bodies to act as the limit point. You may also specify several planes attached to the other body. The points and planes move together with the body they are attached to. The simulation then makes certain that the pair of bodies only move relative to each other so that the limit point stays on the positive side of all limit planes. the default limit point is (0,0,0) in the local frame of actor2. Calling this deletes all existing limit planes. <b>Sleeping:</b> This call wakes the body(s) if they are sleeping. \param[in] point The limit reference point defined in the global frame. <b>Range:</b> position vector \param[in] pointIsOnActor2 if true the point is attached to the second body. Otherwise it is attached to the first. \sa getLimitPoint() addLimitPlane() */ void setLimitPoint(VxVector point,bool pointIsOnActor2=true); /** \brief Retrieves the global space limit point. Returns true if the point is fixed on actor2. \param[out] worldLimitPoint Used to store the global frame limit point. \return True if the point is fixed to body 2 otherwise the point is fixed to body 1. \see setLimitPoint() addLimitPlane() */ bool getLimitPoint(VxVector & worldLimitPoint); bool IsValid(); CKContext *context; pJointD6 *castD6Joint(); pJointFixed*castFixed(); pJointDistance*castDistanceJoint(); pJointBall *castBall(); pJointPulley *castPulley(); pJointRevolute *castRevolute(); pJointPrismatic *castPrismatic(); pJointCylindrical *castCylindrical(); pJointPointInPlane *castPointInPlane(); pJointPointOnLine *castPointOnLine(); void setLocalAnchor0(VxVector anchor0); void setLocalAnchor1(VxVector anchor1); VxVector getGlobalAxis(); void setGlobalAxis(VxVector axis); VxVector getGlobalAnchor(); void setGlobalAnchor(VxVector anchor); int getNbLimitPlanes(); virtual void enableCollision(int collision){} virtual ~pJoint(){} }; /** \brief A prismatic joint permits relative translational movement between two bodies along an axis, but no relative rotational movement. \image html prismJoint.png <h3>Creation</h3> \include NxPrismaticJoint_Create.cpp \sa pFactory::createPrismaticJoint() */ class MODULE_API pJointPrismatic : public pJoint { public: pJointPrismatic(pRigidBody* _a,pRigidBody* _b); void setGlobalAxis(VxVector axis); void setGlobalAnchor(VxVector anchor); void enableCollision(int collision); }; /** \brief Cylindrical Joints permit relative translational movement between two bodies along an axis, and also relative rotation along the axis. \image html cylinderJoint.png \sa pFactory::createCylindricalJoint() */ class MODULE_API pJointCylindrical: public pJoint { public: pJointCylindrical(pRigidBody* _a,pRigidBody* _b); void setGlobalAxis(VxVector axis); void setGlobalAnchor(VxVector anchor); void enableCollision(int collision); }; /** \brief A point in plane joint constrains a point on one actor to only move inside a plane attached to another actor. The point attached to the plane is defined by the anchor point. The joint's axis specifies the plane normal. DOFs removed: 1 <br> DOFs remaining: 5<br> \image html pointInPlaneJoint.png \sa pFactory::createPointInPlaneJoint() */ class MODULE_API pJointPointInPlane: public pJoint { public: pJointPointInPlane(pRigidBody* _a,pRigidBody* _b); /** \brief Sets the global axis. \param[in] axis The new axis. */ void setGlobalAxis(VxVector axis); /** \brief Sets the global anchor. \param[in] anchor The new anchor. */ void setGlobalAnchor(VxVector anchor); /** \brief Enables collision between both bodies. \param[in] collision Collision is enabled. */ void enableCollision(int collision); }; /** \brief A point on line joint constrains a point on one actor to only move along a line attached to another actor. The point attached to the line is the anchor point for the joint. The line through this point is specified by its direction (axis) vector. DOFs removed: 2 <br> DOFs remaining: 4<br> \image html pointOnLineJoint.png \sa pFactory::createPointInPlaneJoint() */ class MODULE_API pJointPointOnLine: public pJoint { public: pJointPointOnLine(pRigidBody* _a,pRigidBody* _b); /** \brief Sets the global axis. \param[in] axis The new axis. */ void setGlobalAxis(VxVector axis); /** \brief Sets the global anchor. \param[in] anchor The new anchor. */ void setGlobalAnchor(VxVector anchor); /** \brief Enables collision between both bodies. \param[in] collision Collision is enabled. */ void enableCollision(int collision); }; /** \brief A joint which behaves in a similar way to a hinge or axle. \image html revoluteJoint.png A hinge joint removes all but a single rotational degree of freedom from two objects. The axis along which the two bodies may rotate is specified with a point and a direction vector. An example for a revolute joint is a door hinge. Another example would be using a revolute joint to attach rotating fan blades to a ceiling. The revolute joint could be motorized, causing the fan to rotate. <h4>Revolute Joint Limits</h4> A revolute joint allows limits to be placed on how far it rotates around the joint axis. For example, a hinge on a door cannot rotate through 360 degrees; rather, it can rotate between 20 degrees and 180 degrees. The angle of rotation is measured using the joints normal (axis orthogonal to the joints axis). This is the angle reported by NxRevoluteJoint::getAngle(). The limits are specified as a high and low limit, which must satisfy the condition -Pi < low < high <Pi degrees. Below are valid revolute joint limits in which the joint is able to move between low and high: \image html revoluteJointLimits.png <br> Note : The white region represents the allowable rotation for the joint. <h4>Limitations of Revolute Joint Limits</h4> As shown below, it is not possible to specify certain limit configurations without rotating the joint axes, due to the restrictions on the values of low and high: \image html revoluteLimitLimitation.png To achieve this configuration, it is necessary to rotate the joint counter-clockwise so that low is below the 180 degree line. NOTE: If the angular region that is prohibited by the twist limit (as in the above figures) is very small, only a few degrees or so, then the joint may "push through" the limit and out on the other side if the relative angular velocity is large enough in relation to the time step. Care must be taken to make sure the limit is "thick" enough for the typical angular velocities it will be subjected to. \sa pFactory::createRevoluteJoint() */ class MODULE_API pJointRevolute : public pJoint { public: pJointRevolute(pRigidBody* _a,pRigidBody* _b); /** \brief Sets the global axis. \param[in] axis The new axis. */ void setGlobalAxis(const VxVector& axis); /** \brief Sets the global anchor. \param[in] anchor The new anchor. */ void setGlobalAnchor(const VxVector& anchor); /** \brief Retrieves the optional spring. \return The spring. \sa setSpring() */ pSpring getSpring(); /** \brief Sets an optional spring. \param[in] spring The spring. \return TRUE if spring was valid. \sa getSpring() */ bool setSpring(pSpring spring); /** \brief Retrieves an optional high limit for angular motion of the joint. \sa setHighLimit() */ pJointLimit getHighLimit(); /** \brief Sets an optional high limit for angular motion of the joint. \param[in] limit The new high limit. \return True if the limit was valid. \sa getLowLimit() */ bool setHighLimit(pJointLimit limit); /** \brief Retrieves an optional low limit for angular motion of the joint. \sa setLowLimit() */ pJointLimit getLowLimit(); /** \brief Sets an optional high limit for angular motion of the joint. \param[in] limit The new low limit. \return True if the limit was valid. \sa setLowLimit() */ bool setLowLimit(pJointLimit limit); /** \brief Sets a motor. \param[in] motor The new motor settings. \return True if the motor was valid. \sa getMotor() */ bool setMotor(pMotor motor); /** \brief Retrieves a motor. \return The motor settings \sa setMotor() */ pMotor getMotor(); /** \brief Enables collision between both bodies. \param[in] collision Collision is enabled. */ void enableCollision(bool collision); void setProjectionMode(ProjectionMode mode); void setProjectionDistance(float distance); void setProjectionAngle(float angle); protected: private: }; /*! * \brief A pulley joint simulates a rope between two objects passing over 2 pulleys. * * \image html pulleyJoint.png * * The pulley joint simulates a rope that can be thrown across a pair of pulleys. In this way, it is similar to the distance joint (the length of the rope is the distance) but the rope doesn't connect the two bodies along the shortest path, rather it leads from the connection point on one actor to the pulley point (fixed in world space), then to the second pulley point, and finally to the other actor. The pulley joint can also be used to simulate a rope around a single point by making the pulley points coincide. <b>Note</b> that a setup where either object attachment point coincides with its corresponding pulley suspension point in world space is invalid. In this case, the simulation would be unable to determine the appropriate direction in which to pull the object and a random direction would result. The simulation will be unstable. Note that it is also invalid to allow the simulation to end up in such a state. */ class MODULE_API pJointPulley : public pJoint { public: pJointPulley(pRigidBody* _a,pRigidBody* _b); /** \brief Sets the attachment point of joint in bodie[0]'s space. \param[in] VxVector anchor \return void @see pJointPulley::setLocalAnchorB */ void setLocalAnchorA(VxVector anchor); /** \brief Sets the attachment point of joint in bodie[1]'s space. \param[in] VxVector anchor \return void @see pJointPulley::setLocalAnchorB */ void setLocalAnchorB(VxVector anchor); /** \brief Returns the attachment point of joint in bodie[0]'s space. \return VxVector @see pJointPulley::setLocalAnchorB */ VxVector getLocalAnchorA(); /** \brief Returns the attachment point of joint in bodie[0]'s space. \param[in] VxVector anchor \return VxVector @see pJointPulley::setLocalAnchorA */ VxVector getLocalAnchorB(); /** \brief Sets the suspension point of joint in world space. \param[in] VxVector pulley \return void @see pJointPulley::setPulleyB */ void setPulleyA(VxVector pulley); /** \brief Sets the suspension point of joint in world space. \param[in] VxVector pulley \return void @see pJointPulley::setPulleyA */ void setPulleyB(VxVector pulley); /** \brief Returns the suspension point of joint in world space. \return VxVector @see pJointPulley::getPulleyB */ VxVector getPulleyA(); /** \brief Returns the suspension point of joint in world space. \return VxVector @see pJointPulley::getPulleyA */ VxVector getPulleyB(); /** \brief Sets how stiff the constraint is, between 0 and 1 (stiffest). \param[in] float stiffness - <b>Range:</b> [0,1.0f) <br> - <b>Default:</b> 1.0f \return void @see getStiffness() */ void setStiffness(float stiffness); /** \brief Returns how stiff the constraint is, between 0 and 1 (stiffest). \return float @see setStiffness() */ float getStiffness(); /** \brief Sets transmission ratio. \param[in] float ratio - <b>Range:</b> [0,1.0f) <br> - <b>Default:</b> 1.0f \return void @see ::getRatio() */ void setRatio(float ratio); /** \brief Gets transmission ratio. \return float @see setRatio */ float getRatio(); /** \brief Set true if the joint also has to maintain a minimum distance, not just a maximum. \param[in] bool rigid - <b>Range:</b> [true,false) <br> - <b>Default:</b>false \return void @see ::isRigid() */ void setRigid(bool rigid); /** \brief Returns true if the joint also has to maintain a minimum distance, not just a maximum. \return bool @see */ bool isRigid(); /** \brief Sets the rest length of the rope connecting the two objects. The distance is computed as ||(pulley0 - anchor0)|| + ||(pulley1 - anchor1)|| * ratio. \param[in] float distance - <b>Range:</b> [0,inf) <br> - <b>Default:</b> 0.0f \return void @see getDistance() */ void setDistance(float distance); /** \brief Returns the rest length of the rope connecting the two objects. \return float @see setDistance() */ float getDistance(); /** \brief Sets motor parameters for the joint. \param[in] pMotor motor - <b>Range:</b> [#pMotor) <br> - <b>Default:</b> no motor \return void @see getMotor() */ void setMotor(pMotor motor); /** \brief Returns motor parameter for the joint. \return pMotor @see setMotor() */ pMotor getMotor(); /** \brief For convenience only. For the case the pulley hooks are moving, the SDK corrects the these points according to reference entities. \return void @see */ void setFollowPulleyReferences(bool follow); /** \brief Sets the first pulley. \return void @see setPulleyBReference() */ void setPulleyAReference(CK3dEntity*ent); /** \brief Sets the second pulley. \return void @see setPulleyAReference() */ void setPulleyBReference(CK3dEntity*ent); /** \brief Returns the first pulley reference. \return void @see setPulley1Ref() */ CK3dEntity *getPulleyAReference(); /** \brief Sets the second pulley reference \return void @see setPulley1Ref() */ CK3dEntity *getPulleyBReference(); /** \brief Enables collision between both bodies. \return void @see setPulley1Ref() */ void enableCollision(bool collision); private : CK_ID m_Pulley0Reference0; CK_ID m_Pulley0Reference1; bool mFollowPulleyReferences; public : }; /** \brief A D6 joint is a general constraint between two actors. It allows the user to individually define the linear and rotational degrees of freedom. It also allows the user to configure the joint with limits and driven degrees of freedom as they wish. */ class MODULE_API pJointD6 : public pJoint { public: pJointD6(pRigidBody* _a,pRigidBody* _b); /** \brief Sets the motion mode for the twist axis. \param[in] mode The new mode. \sa getTwistMotionMode() */ void setTwistMotionMode(D6MotionMode mode); D6MotionMode getTwist(); /** \brief Sets the motion mode for the swing1 axis. \param[in] mode The new mode. \sa getSwing1MotionMode() */ void setSwing1MotionMode(D6MotionMode mode); D6MotionMode getSwing1(); /** \brief Sets the motion mode for the swing2 axis. \param[in] mode The new mode. \sa getSwing2MotionMode() */ void setSwing2MotionMode(D6MotionMode mode); D6MotionMode getSwing2(); /** \brief Sets the motion mode for the linear x axis. \param[in] mode The new mode \sa getXMotionMode() */ void setXMotionMode(D6MotionMode mode); D6MotionMode getXMotion(); /** \brief Sets the motion mode for the linear y axis. \param[in] mode The new mode \sa getZMotionMode() */ void setYMotionMode(D6MotionMode mode); D6MotionMode getYMotion(); /** \brief Sets the motion mode for the linear z axis. \param[in] mode The new mode \sa getZMotionMode() */ void setZMotionMode(D6MotionMode mode); D6MotionMode getZMotion(); int setLinearLimit(pJD6SoftLimit limit); pJD6SoftLimit getLinearLimit(); int setSwing1Limit(pJD6SoftLimit limit); pJD6SoftLimit getSwing1Limit( ); int setSwing2Limit(pJD6SoftLimit limit); pJD6SoftLimit getSwing2Limit(); int setTwistLowLimit(pJD6SoftLimit value); pJD6SoftLimit getTwistLowLimit(); int setTwistHighLimit(pJD6SoftLimit value); pJD6SoftLimit getTwistHighLimit(); pJD6Drive getXDrive(); int setXDrive(pJD6Drive drive); pJD6Drive getYDrive(); int setYDrive(pJD6Drive drive); pJD6Drive getZDrive(); int setZDrive(pJD6Drive drive); pJD6Drive getSwingDrive(); int setSwingDrive(pJD6Drive drive); pJD6Drive getTwistDrive();int setTwistDrive(pJD6Drive drive); pJD6Drive getSlerpDrive();int setSlerpDrive(pJD6Drive drive); /**\brief If the type of xDrive (yDrive,zDrive) is #D6DT_Position, drivePosition defines the goal position. <b>Range:</b> position vector<br> <b>Default:</b> Zero */ void setDrivePosition(VxVector pos); /**\brief If the type of swingDrive or twistDrive is #D6DT_Position, driveOrientation defines the goal orientation. <b>Range:</b> position vector<br> <b>Default:</b> Zero */ void setDriveRotation(VxQuaternion rot); /**\brief If the type of xDrive (yDrive,zDrive) is D6DT_Velocity, driveLinearVelocity defines the goal linear velocity. <b>Range:</b> unit quaternion<br> <b>Default:</b> Identity Quaternion */ void setDriveLinearVelocity(VxVector linVel); /**\brief If the type of swingDrive or twistDrive is D6DT_Velocity, driveAngularVelocity defines the goal angular velocity. - driveAngularVelocity.x - goal angular velocity about the twist axis - driveAngularVelocity.y - goal angular velocity about the swing1 axis - driveAngularVelocity.z - goal angular velocity about the swing2 axis <b>Range:</b> angular velocity vector<br> <b>Default:</b> Zero */ void setDriveAngularVelocity(VxVector angVel); /** \brief Enables collision between the two bodies. \param[in] Collide or not. */ void enableCollision(bool value); /** \brief Sets the global anchor. \param[in] anchor The new anchor. */ void setGlobalAnchor(VxVector anchor); /** \brief Sets the global axis. \param[in] axis The new axis. */ void setGlobalAxis(VxVector axis); void setRatio(float ratio); void setProjectionMode(ProjectionMode mode); void setProjectionDistance(float distance); void setProjectionAngle(float angle); protected: private: }; /** \brief A distance joint maintains a certain distance between two points on two bodies. \image html distanceJoint.png \sa pFactory::createDistanceJoint() */ class MODULE_API pJointDistance : public pJoint { public: pJointDistance(pRigidBody* _a,pRigidBody* _b); /** \brief Sets the minimum rest length of the rope or rod between the two anchor points. \param[in] distance The new rest length. The value must be non-zero! \sa getMinDistance() */ void setMinDistance(float distance); /** \brief Sets the maximum rest length of the rope or rod between the two anchor points. \param[in] distance The new rest length.The value must be non-zero! \sa getMaxDistance() */ void setMaxDistance(float distance); /** \brief Sets the attachment point of the joint in bodies[0] space. \param[in] anchor The new anchor. \sa getLocalAnchor0() */ void setLocalAnchor0(VxVector anchor); /** \brief Sets the attachment point of the joint in bodies[1] space. \param[in] anchor The new anchor. \sa getLocalAnchor1() */ void setLocalAnchor1(VxVector anchor); /** \brief Retrieves the attachment point of the joint in bodies[1] space. \return anchor The local anchor 0 . \sa setLocalAnchor0() */ VxVector getLocalAnchor0(); /** \brief Retrieves the attachment point of the joint in bodies[1] space. \return The local anchor 1. \sa setLocalAnchor1() */ VxVector getLocalAnchor1(); /** \brief Retrieves the minimum rest length of the rope or rod between the two anchor points. \return The minimum distance amongst both bodies. \sa setMinDist() */ float getMinDistance(); /** \brief Retrieves the maximum rest length of the rope or rod between the two anchor points. \return The maximum distance amongst both bodies. \sa setMaxDist() */ float getMaxDistance(); /** \brief Retrieves the spring which keeps both bodies springy. \return The spring. \sa setSpring() */ pSpring getSpring(); /** \brief Makes the joint springy. \param[in] spring The new rest length. The spring.targetValue field is not used. \sa getSpring() */ bool setSpring(pSpring spring); /** \brief Enables collision between the two bodies. \param[in] Collide or not. */ void enableCollision(int collision); protected: private: }; class MODULE_API pJointFixed : public pJoint { public: pJointFixed(pRigidBody* _a,pRigidBody* _b); protected: private: }; /** \brief A sphere joint constrains two points on two bodies to coincide. This point, specified in world space (this guarantees that the points coincide to start with) is the only parameter that has to be specified. \image html sphericalJoint.png */ class MODULE_API pJointBall : public pJoint { public: pJointBall(pRigidBody* _a,pRigidBody* _b); pJointBall(pRigidBody* _a,pRigidBody* _b,VxVector anchor); /** \brief Retrieves the global space anchor. \return The joints anchor. \sa getAnchor() */ VxVector getAnchor(); /** \brief Sets the global space anchor. \param[in] worldLimitPoint Used to store the global frame limit point. \sa getAnchor() */ void setAnchor(const VxVector& anchor); /** \brief Sets the limit axis defined in the joint space of body a. \param[in] swingLimitAxis The new limit axis. \sa getAnchor() */ void setSwingLimitAxis(const VxVector& swingLimitAxis); /** \brief Sets the swing limit of the twist axis. \param[in] limit The new swing limit axis. \return True if the limit was valid. \sa getSwingLimit() */ bool setSwingLimit(pJointLimit limit); /** \brief Sets the high rotation limit around the twist axis. \param[in] limit The new twist high limit. \return True if the limit was valid. \sa getTwistLowLimit() */ bool setTwistHighLimit(pJointLimit limit); /** \brief Sets the high rotation limit around the twist axis. \param[in] limit The new twist low limit. \return True if the limit was valid. \sa getTwistLowLimit() */ bool setTwistLowLimit(pJointLimit limit); /** \brief Sets a spring that works against swinging. \param[in] spring The new spring. \return True if the spring was valid. \sa getSwingSpring() */ bool setSwingSpring(pSpring spring); /** \brief Sets a spring that works against twisting. \param[in] spring The new spring. \return True if the spring was valid. \sa getTwistSpring() */ bool setTwistSpring(pSpring spring); /** \brief Sets a spring that lets the joint get pulled apart. \param[in] spring The new spring. \return True if the spring was valid. \sa getJointSpring() */ bool setJointSpring(pSpring spring); pJointLimit getSwingLimit(); pJointLimit getTwistHighLimit(); pJointLimit getTwistLowLimit(); pSpring getSwingSpring(); pSpring getTwistSpring(); pSpring getJointSpring(); void enableFlag(int flag,bool enable); /** \brief Enables collision between the two bodies. \param[in] collision Collide or not. */ void enableCollision(bool collision); void setProjectionMode(ProjectionMode mode); void setProjectionDistance(float distance); void setProjectionAngle(float angle); protected: private: }; /** @} */ #endif<file_sep>/******************************************************************** created: 2009/02/14 created: 14:2:2009 15:50 filename: SDK\Include\Core\vtParameterGuids.h file path: SDK\Include\Core file base: vtParameterGuids file ext: h author: <NAME> purpose: Unique identifiers for the entire component *********************************************************************/ #ifndef __VT_PARAMETER_GUIDS_H__ #define __VT_PARAMETER_GUIDS_H__ //################################################################ // // Common Parameter, used by joints, bodies, -or world objects // #define VTS_AXIS_REFERENCED_LENGTH CKGUID(0x19d6054d,0x4c2a2c99) #define VTE_PHYSIC_DOMINANCE_GROUP CKGUID(0x2ae53cee,0x57ca74d0) #define VTS_SLEEPING_SETTINGS CKGUID(0x28d13431,0x24186938) #define VTF_TRIGGER CKGUID(0xe9c412e,0x68025071) #define VTE_FILTER_OPS CKGUID(0x58340fe5,0x67892b1f) #define VTE_FILTER_MASK CKGUID(0x30ff289e,0x7e57707c) #define VTS_FILTER_GROUPS CKGUID(0x14443c3a,0x7c886162) #define VTF_SHAPES_TYPE CKGUID(0x2ff80c77,0x7ab71a8) #define VTF_RAY_HINTS CKGUID(0x7f5552d,0x70632e9a) #define VTS_RAYCAST CKGUID(0x3842035f,0x1bc81c7f) #define VTF_COLLISIONS_EVENT_MASK CKGUID(0x1beb409d,0x5028494f) #define VTF_WHEEL_CONTACT_MODIFY_FLAGS CKGUID(0x40495482,0x4ab3283e) //################################################################ // // Shape overrides // #define VTS_CAPSULE_SETTINGS CKGUID(0x9a441c3,0x1e1d25ce) #define VTS_CAPSULE_SETTINGS_EX CKGUID(0x16f102dc,0x7cb97e54) // Wheel type using a convex cylinder, a capsule and a joint spring #define VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR CKGUID(0x65e30713,0x55ca1048) //################################################################ // // World Related // #define VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS CKGUID(0x636c3e44,0x658213ea) #define VTS_PHYSIC_DOMINANCE_ITEM CKGUID(0x7bee51cc,0xb676809) #define VTS_PHYSIC_DOMINANCE_CONSTRAINT CKGUID(0x6f44420b,0x14b7435d) #define VTS_WORLD_SETTINGS CKGUID(0x5a0b56eb,0x50fc04d2) #define VTS_PHYSIC_WORLD_PARAMETER CKGUID(0x27f223a1,0x365777f0) //################################################################ // // Rigid Body Related // #define VTS_PHYSIC_PARAMETER CKGUID(0x90e519f,0x7ec5345d) #define VTS_PHYSIC_ACTOR CKGUID(0x381d7e69,0x456458fb) #define VTF_PHYSIC_SUBSHAPE_INHERITANCE_FLAGS CKGUID(0x55c60b24,0x4ddc754e) #define VTS_PHYSIC_TRANSFORMATIONS_LIMIT_PARAMETER CKGUID(0x413f3fb4,0x4f545c24) #define VTF_PHYSIC_BODY_COMMON_SETTINGS CKGUID(0x44bc4e8d,0x16cb3288) #define VTE_BODY_FORCE_MODE CKGUID(0x28c8214c,0x1ab04db8) #define VTF_PHYSIC_BODY_UPDATE_FLAGS CKGUID(0x7f824fb3,0x5496b62) #define VTF_PHYSIC_WORLD_UPDATE_FLAGS CKGUID(0x7f824fb3,0x5496b62) #define VTF_BODY_FLAGS CKGUID(0x2c173381,0x10f66ab3) #define VTF_BODY_TRANS_FLAGS CKGUID(0x41242761,0x72e70c27) #define VTE_COLLIDER_TYPE CKGUID(0x1c415d41,0x5c534d7a) #define VTF_CONVEX_FLAGS CKGUID(0x2d9d5c3e,0x468c0266) #define VTF_CONTACT_MODIFY_FLAGS CKGUID(0x7d5c0e7c,0x144d2596) //---------------------------------------------------------------- // // XML Setup // #define VTS_PHYSIC_ACTOR_XML_SETTINGS_INTERN CKGUID(0x35977af4,0x5b430c0c) #define VTS_PHYSIC_ACTOR_XML_SETTINGS_EXTERN CKGUID(0x57aa4cab,0x7e173b06) #define VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS CKGUID(0x2a2c3ee5,0x33cc3c2f) #define VTS_PHYSIC_ACTOR_XML_SETUP CKGUID(0x5e916f6,0x6e7a44ed) #define VTF_PHYSIC_ACTOR_COPY_FLAGS CKGUID(0x7013615f,0x9aa642e) //---------------------------------------------------------------- // // Geometry // #define VTS_PHYSIC_PIVOT_OFFSET CKGUID(0x19e432af,0x571f5bf7) //---------------------------------------------------------------- // // Collision // #define VTF_PHYSIC_COLLISION_MASK CKGUID(0x7bf86391,0x1ac73b1) #define VTS_PHYSIC_CCD_SETTINGS CKGUID(0x37537e0c,0x55b668d6) #define VTF_PHYSIC_CCD_FLAGS CKGUID(0x25ee18c2,0x3419342d) #define VTS_PHYSIC_COLLISIONS_SETTINGS CKGUID(0x8027e35,0x7c940e70) #define VTE_PHYSIC_BODY_COLL_GROUP CKGUID(0xc1e1e0a,0x36fd0de4) #define VTS_PHYSIC_COLLISIONS_SETUP CKGUID(0x64043794,0x4d9f454b) //---------------------------------------------------------------- // // Mass Configuration // #define VTS_PHYSIC_MASS_SETUP CKGUID(0x36855c80,0x81a0a4e) #define VTE_PHYSIC_MASS_TYPE CKGUID(0x71921e8a,0x8e22f63) //---------------------------------------------------------------- // // Optimization // #define VTS_PHYSIC_SLEEP_SETTINGS CKGUID(0x41450454,0x3b4a65c2) #define VTS_PHYSIC_DAMPING_PARAMETER CKGUID(0x17ad0411,0x3ccd0dd7) #define VTS_PHYSIC_ACTOR_OPTIMIZATION CKGUID(0x2fca03db,0x25644fd4) //---------------------------------------------------------------- // // Material // #define VTS_MATERIAL CKGUID(0x4785249d,0x57af4457) #define VTF_MATERIAL_FLAGS CKGUID(0x14ce161f,0x27cc5b83) #define VTE_MATERIAL_COMBINE_MODE CKGUID(0x6dbf7c19,0x3dfb0e12) #define VTE_XML_MATERIAL_TYPE CKGUID(0x57430496,0x29193343) //################################################################ // // Joints : // //---------------------------------------------------------------- // // Common shared types // #define VTE_JOINT_TYPE CKGUID(0x5d9c0413,0xcb96c02) #define VTS_PHYSIC_JAMOTOR_AXIS_TYPE CKGUID(0x21352808,0x1e932c41) #define VTE_JOINT_MOTION_MODE CKGUID(0x6ec04e81,0xfd537e) #define VTS_JOINT_DRIVE CKGUID(0x563c20ca,0x581e0e4b) #define VTS_JOINT_SPRING CKGUID(0x495d0920,0x189674ba) #define VTS_JLIMIT CKGUID(0x8d61654,0x1fd01503) #define VTS_JOINT_SLIMIT CKGUID(0xd997313,0x28523dc0) #define VTS_JOINT_MOTOR CKGUID(0x50ab7cc2,0x37ce0071) #define VTS_JOINT_D6 CKGUID(0x215a2fa1,0x7cc02701) #define VTF_JOINT_D6_AXIS_MASK CKGUID(0x461c1af3,0x4b194a84) #define VTS_JOINT_D6_AXIS_ITEM CKGUID(0x37d01b38,0x10a03ef) #define VTE_JOINT_MOTION_MODE_AXIS CKGUID(0x5adb450c,0x5798057d) #define VTE_JOINT_LIMIT_AXIS CKGUID(0x16d654a4,0x276a048f) #define VTE_JOINT_DRIVE_AXIS CKGUID(0x1c73456a,0x7d846d2a) #define VTE_JOINT_PROJECTION_MODE CKGUID(0x2cce3d0b,0x60603c02) #define VTE_JOINT_TYPE CKGUID(0x16f21041,0x7a6479f3) //---------------------------------------------------------------- // // Complete Joint Setups // #define VTS_JOINT_FIXED CKGUID(0x3a5163bf,0x3c315528) #define VTS_JOINT_DISTANCE CKGUID(0x1edf6510,0xdea68b2) #define VTS_JOINT_BALL CKGUID(0x20271cdc,0x645c4212) #define VTS_JOINT_REVOLUTE CKGUID(0x7d45030c,0x4f6216ef) #define VTS_JOINT_PRISMATIC CKGUID(0x37fd735c,0x6b83447d) #define VTS_JOINT_CYLINDRICAL CKGUID(0x45e07719,0xba2297) #define VTS_JOINT_POINT_IN_PLANE CKGUID(0xed23f6,0x2ba449a3) #define VTS_JOINT_POINT_ON_LINE CKGUID(0x4429006a,0x34345b66) #define VTS_JOINT_D6 CKGUID(0x52467f8a,0x3adc012b) #define VTS_JOINT_D6_DRIVES CKGUID(0x46067fc4,0x56cf693e) #define VTS_JOINT_BREAKABLE CKGUID(0xe3d7a63,0x2cc61e4a) #define VTS_JOINT_D6 CKGUID(0x11bd2119,0x3843102b) #define VTS_PHYSIC_JBALL_PARAMETER CKGUID(0x2c47770d,0x1b7173ad) #define VTS_PHYSIC_JFIXED_PARAMETER CKGUID(0x780650ae,0x7e6406c5) #define VTS_PHYSIC_JHINGE_PARAMETER CKGUID(0x5a805563,0x292021ce) #define VTS_PHYSIC_JHINGE2_PARAMETER CKGUID(0x281717e5,0x353b61f2) #define VTS_PHYSIC_JUNIVERSAL_PARAMETER CKGUID(0x7a283845,0x53144e6a) #define VTS_PHYSIC_JSLIDER_PARAMETER CKGUID(0x67837673,0x20c04330) #define VTS_PHYSIC_JMOTOR_PARAMETER CKGUID(0x677e7eba,0x6505310c) #define VTS_PHYSIC_JLIMIT_PARAMETER CKGUID(0x17e57c53,0x43585c91) #define VTE_PHYSIC_JDRIVE_TYPE CKGUID(0x75a51b10,0xe00025c) //---------------------------------------------------------------- // // Joint Misc Structures // #define VTS_PHYSIC_JLIMIT_PLANE CKGUID(0x5abe5f0b,0x7ca6657e) //################################################################ // // Wheel Parameters // #define VTF_VSTATE_FLAGS CKGUID(0x49ce782d,0x7566828) #define VTF_VFLAGS CKGUID(0x5cf964cf,0xd382f37) #define VTF_VWSHAPE_FLAGS CKGUID(0x7da158eb,0x16e921a1) #define VTF_VWTIRE_SETTINGS CKGUID(0x2690c24,0xde55e2b) #define VTE_BRAKE_XML_LINK CKGUID(0x77806807,0x4eac2b27) #define VTE_BRAKE_LEVEL CKGUID(0x161f2b7d,0x2f657a2a) #define VTF_BRAKE_FLAGS CKGUID(0x46535a8f,0x11815172) #define VTS_BRAKE_TABLE CKGUID(0x59052709,0xa555846) #define VTF_WHEEL_CONEX_SHAPE CKGUID(0x3f913a00,0x372f4a50) #define VTS_WHEEL_CONTACT CKGUID(0x33f24aa8,0x34a57460) #define VTS_PHYSIC_WHEEL_DESCR CKGUID(0x5dcd09ae,0x73f72b97) #define VTS_PHYSIC_WHEEL_FLAGS CKGUID(0x72b70c7d,0x3b60239d) //################################################################ // // Vehicle // #define VTS_PHYSIC_VEHICLE_DESCR CKGUID(0x54562468,0xd1a6de6) #define VTS_PHYSIC_VEHICLE_MOTOR_DESCR CKGUID(0x19317402,0x2f4b65a1) #define VTS_PHYSIC_GEAR_DESCR CKGUID(0x308e5c88,0x433871f9) #define VTE_XML_VEHICLE_SETTINGS CKGUID(0x67ca76e9,0x452f7ceb) #define VTE_XML_VMOTOR_SETTINGS CKGUID(0x6af977a6,0x11084c45) #define VTF_VEHICLE_ENGINE_FLAGS CKGUID(0x23823b40,0x694f152c) #define VTE_XML_VGEAR_SETTINGS CKGUID(0x9bc7981,0x4a6f7245) #define VTE_XML_WHEEL_SETTINGS CKGUID(0x1ed80439,0x1f9825c4) #define VTE_XML_TIRE_SETTINGS CKGUID(0x4cb47505,0x7b022333) #define VTS_VMOTOR_ENTRY CKGUID(0x12dd3a77,0x5db358f8) #define VTS_VMOTOR_TVALUES CKGUID(0x34af3aa2,0x23aa6422) #define VTS_VGEAR_GRAPH_SETTINGS CKGUID(0x25016106,0x3a0024a0) #define VTS_VGEARBOX_FLAGS CKGUID(0x47d632a5,0x50057698) #define VTS_VGEAR_RATIO_ENTRY CKGUID(0x36b93b1c,0x79f804c2) #define VTS_VGEAR_RATIOS CKGUID(0x5a0230db,0x441f5c18) #define VTS_VGEAR_CURVE CKGUID(0x6352317b,0x41fe3769) #define VTS_VGEAR_SETTINGS CKGUID(0x7dde30fb,0x701915ea) #define VTE_VEHICLE_XML_LINK CKGUID(0x4c43611,0x736078b9) #define VTF_VEHICLE_PROCESS_OPTIONS CKGUID(0x24fa465f,0x1c2f5b88) //################################################################ // // Cloth // #define VTE_CLOTH_FLAGS CKGUID(0x2c7d5bb6,0x6a9d7c41) #define VTS_CLOTH_DESCR CKGUID(0x722a5c01,0x5c8d413d) #define VTS_CLOTH_METAL_DESCR CKGUID(0x1ecb0821,0x709e7bdf) #define VTE_CLOTH_ATTACH_FLAGS CKGUID(0x428b755b,0x36d60122) //################################################################ // // UNknow : // #define VTS_PHYSIC_HEIGHTFIELD_PARAMETERS CKGUID(0x37430de4,0x54d06445) #endif<file_sep>/******************************************************************** created: 2006/05/07 created: 05:07:2006 8:14 filename: x:\junctions\ProjectRoot\current\vt_plugins\vt_toolkit\Behaviors\Generic\BGInstancer.cpp file path: x:\junctions\ProjectRoot\current\vt_plugins\vt_toolkit\Behaviors\Generic file base: BGInstancer file ext: cpp author: mc007 purpose: *********************************************************************/ #include <virtools/vtcxglobal.h> //for pch only,can be removed! #include "BGInstancer.h" /* ******************************************************************* * Function: CKObjectDeclaration *FillBehaviour( void ) * * Description : As its name infers, this function describes each Building Block * on a functional level : what it can be applied to, its GUID, its * creation function, etc.. * * * Parameters : * None * * Returns : CKObjectDeclaration *, containing: * - The type of object declaration ( Must Be CKDLL_BEHAVIORPROTOTYPE ) * - The function that will create the CKBehaviorPrototype for this behavior. * - A short description of what the behavior is supposed to do. * - The category in which this behavior will appear in the Virtools interface. * - A unique CKGUID * - Author and Version info * - The class identifier of objects to which the behavior can be applied to. * ******************************************************************* */ CKObjectDeclaration * BGWrapper::FillBehaviour( void ) { CKObjectDeclaration *objectDeclaration = CreateCKObjectDeclaration( "BgInstancer" ); objectDeclaration->SetType( CKDLL_BEHAVIORPROTOTYPE ); objectDeclaration->SetCreationFunction( BGWrapper::CreatePrototype ); objectDeclaration->SetDescription( "Encapsulates the functionality provided by a Behaviour Graph and allows reuse while minimising maintenance overhead." ); objectDeclaration->SetCategory( "Narratives/Script Management" ); objectDeclaration->SetGuid( BGWRAPPER_GUID ); objectDeclaration->SetVersion( 0x00000001 ); objectDeclaration->SetAuthorGuid( VTCX_AUTHOR_GUID ); objectDeclaration->SetAuthorName( VTCX_AUTHOR ); objectDeclaration->SetCompatibleClassId( CKCID_BEOBJECT ); return objectDeclaration; } /* ******************************************************************* * Function: CKERROR CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ) * * Description : The prototype creation function will be called the first time * a behavior must be created to create the CKBehaviorPrototype * that contains the description of the behavior. * * Parameters : * behaviorPrototypePtr Pointer to a CKBehaviorPrototype object that * describes the behavior's internal structure * and relationships with other objects. * * Returns : CKERROR * ******************************************************************* */ CKERROR BGWrapper::CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ) { #if RUNTIME // Not editable from Virtools Dev CKBehaviorPrototype *behaviorPrototype = CreateCKBehaviorPrototypeRunTime( "BGWrapper" ); #elif GAMEDEVELOPER // Edition depend on the BB. CKBehaviorPrototype *behaviorPrototype = CreateCKBehaviorPrototype( "BGWrapper" ); #else // Editable from Virtools Dev CKBehaviorPrototype *behaviorPrototype = CreateCKBehaviorPrototype( "BGWrapper" ); #endif if ( !behaviorPrototype ) return CKERR_OUTOFMEMORY; //---- Local Parameters Declaration behaviorPrototype->DeclareLocalParameter("BG Script", CKPGUID_BEHAVIOR ); //---- Settings Declaration behaviorPrototype->DeclareSetting("BG filename", CKPGUID_STRING ,"path undefined.(BGWrapper Settings)"); behaviorPrototype->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); behaviorPrototype->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDINPUTS | CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS | CKBEHAVIOR_INTERNALLYCREATEDOUTPUTS | CKBEHAVIOR_INTERNALLYCREATEDOUTPUTPARAMS)); behaviorPrototype->SetBehaviorCallbackFct(BGWrapperCB, CKCB_BEHAVIORLOAD | CKCB_BEHAVIORRESET | CKCB_BEHAVIORSETTINGSEDITED | CKCB_BEHAVIORDETACH | CKCB_BEHAVIORDEACTIVATESCRIPT , NULL); behaviorPrototype->SetFunction( BGWrapper::BehaviourFunction ); *behaviorPrototypePtr = behaviorPrototype; return CK_OK; } /* ******************************************************************* * Function: int BehaviourFunction( const CKBehaviorContext& behaviorContext ) * * Description : The execution function is the function that will be called * during the process loop of the behavior engine, if the behavior * is defined as using an execution function. This function is not * called if the behavior is defined as a graph. This function is the * heart of the behavior: it should compute the essence of the behavior, * in an incremental way. The minimum amount of computing should be * done at each call, to leave time for the other behaviors to run. * The function receives the delay in milliseconds that has elapsed * since the last behavioral process, and should rely on this value to * manage the amount of effect it has on its computation, if the effect * of this computation relies on time. * * Parameters : * behaviourContext Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : int, If it is done, it should return CKBR_OK. If it returns * CKBR_ACTIVATENEXTFRAME, the behavior will again be called * during the next process loop. * ******************************************************************* */ int BGWrapper::BehaviourFunction( const CKBehaviorContext& behContext ) { CKBehavior *behaviour = behContext.Behavior; CKContext *context = behContext.Context; int iPin, nbPin; CKBehavior* script = (CKBehavior*)behaviour->GetLocalParameterObject(EBGWRAPPERPARAM_PARAMETER_SCRIPT); if (script == NULL) return CKBR_GENERICERROR; // Activate the right inputs nbPin = behaviour->GetInputCount(); for (iPin = 0; iPin < nbPin; iPin++) { if (behaviour->IsInputActive(iPin)) { script->ActivateInput(iPin, TRUE); behaviour->ActivateInput(iPin, FALSE); } } // Deactivate all the outputs nbPin = script->GetOutputCount(); for (iPin = 0; iPin < nbPin; iPin++) { behaviour->ActivateOutput(iPin, FALSE); } // Parameter In: Set Source int nbPinBB = behaviour->GetInputParameterCount(); int nbPinBG = script->GetInputParameterCount(); if (nbPinBB != nbPinBG) return CKBR_GENERICERROR; for (iPin = 0; iPin < nbPinBB; iPin++) { CKParameterIn *pBin = behaviour->GetInputParameter(iPin); CKParameter* pSource = pBin->GetDirectSource(); CKParameterIn *pSin = script->GetInputParameter(iPin); pSin->SetDirectSource(pSource); } // Execute the contained script CKERROR result = script->Execute(behContext.DeltaTime); // The script loop on itself too much times if (result == CKBR_INFINITELOOP) { context->OutputToConsoleExBeep("Execute Script : Script %s Executed too much times",script->GetName()); script->Activate(FALSE,FALSE); return CKBR_OK; } // Activate the right outputs nbPin = script->GetOutputCount(); for (iPin = 0; iPin < nbPin; iPin++) { if (script->IsOutputActive(iPin)) { behaviour->ActivateOutput(iPin); script->ActivateOutput(iPin, FALSE); } } // Update Parameters Out nbPin = behaviour->GetOutputParameterCount(); for (iPin = 0; iPin < nbPin; iPin++) { CKParameterOut *pBout = behaviour->GetOutputParameter(iPin); CKParameterOut *pSout = script->GetOutputParameter(iPin); pBout->CopyValue(pSout, TRUE); } // Test if there are any active sub-behaviors, restart the next frame if any BOOL bActivateNextFrame = FALSE; ActivateNextFrameSubBB(script,bActivateNextFrame); if (bActivateNextFrame) return CKBR_ACTIVATENEXTFRAME; // return the execute value return result; } /* ******************************************************************* * Function: CKERROR BGWrapperCB(const CKBehaviorContext& behContext) * * Description : The Behavior Callback function is called by Virtools * when various events happen in the life of a BuildingBlock. * * Parameters : * behaviourContext Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : CKERROR * ******************************************************************* */ CKERROR BGWrapper::BGWrapperCB(const CKBehaviorContext& behContext) { CKERROR result = CKBR_GENERICERROR; // Initialize common pointers. CKBehavior *behaviour = behContext.Behavior; CKContext *context = behContext.Context; CKLevel *level = behContext.CurrentLevel; CKBeObject *owner = behContext.Behavior->GetOwner(); char*name = behaviour->GetName(); if ( behaviour == NULL || context == NULL || level == NULL /*|| owner == NULL*/ ) return CKBR_OK; //Get The BG Script Object if exists CKBehavior* newBG = NULL; CKBehavior* curBG = (CKBehavior*)behaviour->GetLocalParameterObject(EBGWRAPPERPARAM_PARAMETER_SCRIPT); // Get the BG nms file path. GetStringValue doesn't work with setting... char fileName[_MAX_PATH+1]; memset(fileName,0,_MAX_PATH+1); CKParameter* scriptPath = behaviour->GetLocalParameter(EBGWRAPPERPARAM_PARAMETER_NAME); if ( scriptPath == NULL ) return CKBR_OK; int lenPath = scriptPath->GetDataSize(); if ( lenPath >= _MAX_PATH ) return CKBR_OK; void*ptrPath = scriptPath->GetReadDataPtr(TRUE); if ( ptrPath == NULL ) return CKBR_OK; memcpy(fileName,ptrPath,lenPath); CKDWORD message = behContext.CallbackMessage; switch (message) { case CKM_BEHAVIORLOAD : // when the behavior is loaded case CKM_BEHAVIORRESET: // when the behavior is reseted case CKM_BEHAVIORSETTINGSEDITED : // when the settings are edited { if ( curBG != NULL ) { DestroyCurrentBG(level,behaviour,curBG); curBG = NULL; } newBG = BGLoader( fileName, behContext ); if ( newBG == NULL ) return CKBR_OK; if ( message == CKM_BEHAVIORLOAD || message == CKM_BEHAVIORRESET ) { //context->OutputToConsoleExBeep("%s : LOADED %s",behaviour->GetName(), fileName); if ( CheckIO(behaviour, newBG) == TRUE ) result = CKBR_OK; else context->OutputToConsoleExBeep("%s : Too many inputs/outputs changes in %s\r\nPlease reconstruct the wrapper.",behaviour->GetName(), fileName); } else if ( message == CKM_BEHAVIORSETTINGSEDITED ) { if ( CheckIO(behaviour, newBG) == TRUE ) { result = CKBR_OK; } else if (DeleteIO(behaviour) == TRUE) { if ( CreateIO(behaviour, newBG ) == TRUE ) result = CKBR_OK; else context->OutputToConsoleExBeep("%s : Cannot Create Inputs/Outputs %s",behaviour->GetName(), fileName); } else context->OutputToConsoleExBeep("%s : Cannot Delete Inputs/Outputs %s",behaviour->GetName(), fileName); } if ( result == CKBR_OK && newBG != NULL ) SetNewBG(behaviour,newBG); } break; case CKM_BEHAVIORDEACTIVATESCRIPT: { if ( curBG != NULL ) DesactivateSubBB(curBG); result = CKBR_OK; } break; case CKM_BEHAVIORDETACH : // when the behavior is deleted { if (curBG != NULL) { DestroyCurrentBG(level,behaviour,curBG); curBG = NULL; } result = CKBR_OK; } break; default: { result = CKBR_OK; } break; } if (result != CKBR_OK) context->OutputToConsoleExBeep("%s : Problem while manipulating",behaviour->GetName()); return result; } /* ******************************************************************* * Function: CKBehavior* BGLoader(CKSTRING fileName,const CKBehaviorContext& behContext) * * Description : Load a virtools script.and add it to the current level. * * Parameters : * fileName string containing the script filename to be loaded. * behaviourContext Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : CKBehavior* the loaded behaviour, NULL if failed. * ******************************************************************* */ CKBehavior* BGWrapper::BGLoader(CKSTRING fileName,const CKBehaviorContext& behContext) { CKERROR result = CKBR_GENERICERROR; // Initialize common pointers. CKBehavior *behaviour = behContext.Behavior; CKContext *context = behContext.Context; CKLevel *level = behContext.CurrentLevel; CKBeObject *owner = behContext.Behavior->GetOwner(); if ( behaviour == NULL || context == NULL || level == NULL ) return NULL; char fileToLoad[_MAX_PATH],nakedFileName[_MAX_PATH]; char drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; _splitpath(fileName, drive, dir, fname, ext); if ( ext[0] == 0 ) strcpy(ext,".nms"); strcpy(fileToLoad,drive); strcat(fileToLoad,dir); strcat(fileToLoad,fname); strcat(fileToLoad,ext); if ( strcmp(_strlwr(ext),".nms") != 0 ) { context->OutputToConsoleExBeep("BGWrapper : Can only load .nms files %s",fileToLoad); return NULL; } CKObjectArray* array = CreateCKObjectArray(); context->SetAutomaticLoadMode(CKLOAD_OK, CKLOAD_OK, CKLOAD_USECURRENT, CKLOAD_USECURRENT); // Virtools Load the BGs nms file.first try the absolute path, then the lastCmoloaded path, and then the PathManager manager data paths if (context->Load(fileToLoad, array, (CK_LOAD_FLAGS)(CK_LOAD_AUTOMATICMODE | CK_LOAD_AS_DYNAMIC_OBJECT )) != CK_OK) { strcpy(nakedFileName,fname); strcat(nakedFileName,ext); CKSTRING lastCmo = context->GetLastCmoLoaded(); char driveCmo[_MAX_DRIVE], dirCmo[_MAX_DIR], fnameCmo[_MAX_FNAME], extCmo[_MAX_EXT]; _splitpath(lastCmo, driveCmo, dirCmo, fnameCmo, extCmo); strcpy(fileToLoad,driveCmo);strcat(fileToLoad,dirCmo);strcat(fileToLoad,nakedFileName); if (context->Load(fileToLoad, array, (CK_LOAD_FLAGS)(CK_LOAD_AUTOMATICMODE | CK_LOAD_AS_DYNAMIC_OBJECT )) != CK_OK) { // failed then try to go thru the data path. CKPathManager* pathmanager = behContext.Context->GetPathManager(); if (!pathmanager) { context->OutputToConsoleExBeep("BGWrapper : Cannot find the Path Manager"); return NULL; } XString resolved(nakedFileName); array->Clear(); pathmanager->ResolveFileName(resolved,DATA_PATH_IDX,-1); if (context->Load(resolved.Str(), array, (CK_LOAD_FLAGS)(CK_LOAD_AUTOMATICMODE | CK_LOAD_AS_DYNAMIC_OBJECT )) != CK_OK) { context->OutputToConsoleExBeep("BGWrapper : Cannot Load %s", nakedFileName); return NULL; } } } // Check if only one Object is loaded (we should have only one BG here) if ( array->GetCount() != 1 ) { context->OutputToConsoleExBeep("BGWrapper : To many objects inside the nms %s.It should contain one BG only.",fileToLoad); level->BeginRemoveSequence(TRUE); for (array->Reset(); !array->EndOfList(); array->Next()) { CKObject* curObject = array->GetData(context); level->RemoveObject(curObject); CKDestroyObject(curObject); } level->BeginRemoveSequence(FALSE); DeleteCKObjectArray(array); return NULL; } array->Reset(); CKObject* curObject = array->GetData(context); if ( curObject == NULL ) { context->OutputToConsoleExBeep("BGWrapper : Object NULL in loaded array."); return NULL; } // Make it not to be saved even if it is loaded as dynamic... (not needed ?) curObject->ModifyObjectFlags( CK_OBJECT_NOTTOBESAVED,0 ); // Check if the object we've loaded is derivated from the BEHAVIOR if ( !CKIsChildClassOf(curObject, CKCID_BEHAVIOR) ) { context->OutputToConsoleExBeep("BGWrapper : no behavior in the nms : %s",fileToLoad); level->BeginRemoveSequence(TRUE); level->RemoveObject(curObject); level->BeginRemoveSequence(FALSE); CKDestroyObject(curObject); DeleteCKObjectArray(array); return NULL; } CKBehavior*pBG = (CKBehavior*)curObject; // Check if the behavior we've loaded is a BG and not a BB. if ( pBG->IsUsingFunction() ) { context->OutputToConsoleExBeep("BGWrapper : BGWrapper accepts only a BG not a BB : %s",fileToLoad); level->BeginRemoveSequence(TRUE); level->RemoveObject(curObject); level->BeginRemoveSequence(FALSE); CKDestroyObject(curObject); DeleteCKObjectArray(array); return NULL; } // Check if the BG can be applied to the <BGWrapper BB>'s BeObject owner. char*nameee = pBG->GetName(); CK_CLASSID cid = pBG->GetCompatibleClassID(); if (owner!=NULL) if ( !CKIsChildClassOf(owner, pBG->GetCompatibleClassID()) ) { context->OutputToConsoleExBeep("BGWrapper : Incompatible Class, cannot add BG to script %s",fileToLoad); level->BeginRemoveSequence(TRUE); level->RemoveObject(curObject); level->BeginRemoveSequence(FALSE); CKDestroyObject(curObject); DeleteCKObjectArray(array); return NULL; } // Add the BG to the <BGWrapper BB>'s level. level->BeginAddSequence(TRUE); level->AddObject(curObject); level->BeginAddSequence(FALSE); DeleteCKObjectArray(array); if (owner!=NULL) OwnerSubBB(pBG,owner); return pBG; } /* ******************************************************************* * Function: BOOL CheckIO(CKBehavior* behaviour, CKBehavior* script) * * Description : Check if all the Inputs,Outputs, pIns and pOuts of both behavior are matching * * Parameters : * behaviour Behavior 1, usually the BG wrapper BB. * script Behavior 2, usually the wrapped BG. * * Returns : BOOL * ******************************************************************* */ BOOL BGWrapper::CheckIO(CKBehavior* behaviour, CKBehavior* script) { int iParam; int nbPin0, nbPin1; int flag = 0; // Input nbPin0 = behaviour->GetInputCount(); nbPin1 = script->GetInputCount(); if (nbPin0 != nbPin1) return FALSE; // Ouput nbPin0 = behaviour->GetOutputCount(); nbPin1 = script->GetOutputCount(); if (nbPin0 != nbPin1) return FALSE; // Parameter In nbPin0 = behaviour->GetInputParameterCount(); nbPin1 = script->GetInputParameterCount(); if (nbPin0 != nbPin1) return FALSE; for (iParam = 0; iParam < nbPin0; iParam++) { CKParameterIn* pSin = script->GetInputParameter(iParam); CKParameterIn* pBin = behaviour->GetInputParameter(iParam); if (pSin == NULL || pBin == NULL) return FALSE; if (pSin->GetType() != pBin->GetType()) return FALSE; } // Parameter Out nbPin0 = behaviour->GetOutputParameterCount(); nbPin1 = script->GetOutputParameterCount(); if (nbPin0 != nbPin1) return FALSE; for (iParam = 0; iParam < nbPin0; iParam++) { CKParameterOut* pSout = script->GetOutputParameter(iParam); CKParameterOut* pBout = behaviour->GetOutputParameter(iParam); if (pSout == NULL || pBout == NULL) return FALSE; if (pSout->GetType() != pBout->GetType()) return FALSE; } return TRUE; } /* ******************************************************************* * Function: BOOL :CreateIO(CKBehavior* behaviour, CKBehavior* script) * * Description : Check if all the Inputs,Outputs, pIns and pOuts of both behavior are matching * * Parameters : * behaviour Behavior 1, usually the BG wrapper BB. * script Behavior 2, usually the wrapped BG. * * Returns : BOOL * ******************************************************************* */ BOOL BGWrapper::CreateIO(CKBehavior* behaviour, CKBehavior* script) { int iIO; int nbPin; // Input nbPin = script->GetInputCount(); for (iIO = 0; iIO < nbPin; iIO++) { CKBehaviorIO* pPin = script->GetInput(iIO); if (pPin == NULL) return FALSE; if (behaviour->AddInput(pPin->GetName()) != iIO) return FALSE; } // Output nbPin = script->GetOutputCount(); for (iIO = 0; iIO < nbPin; iIO++) { CKBehaviorIO* pPin = script->GetOutput(iIO); if (pPin == NULL) return FALSE; if (behaviour->AddOutput(pPin->GetName()) != iIO) return FALSE; } // Parameter In nbPin = script->GetInputParameterCount(); for (iIO = 0; iIO < nbPin; iIO++) { CKParameterIn* pPin = script->GetInputParameter(iIO); if (pPin == NULL) return FALSE; CKParameterIn* pPin2; if ((pPin2 = behaviour->CreateInputParameter(pPin->GetName(), (CKParameterType)pPin->GetType())) == NULL) return FALSE; } // Parameter Out nbPin = script->GetOutputParameterCount(); for (iIO = 0; iIO < nbPin; iIO++) { CKParameterOut* pPin = script->GetOutputParameter(iIO); if (pPin == NULL) return FALSE; if (behaviour->CreateOutputParameter(pPin->GetName(), (CKParameterType)pPin->GetType()) == NULL) return FALSE; } return TRUE; } /* ******************************************************************* * Function: BOOL DeleteIO(CKBehavior* behaviour) * * Description : Delete all kind of inputs/outputs on the given behavior * * Parameters : * behaviour The behavior to be naked on. * * Returns : BOOL * ******************************************************************* */ BOOL BGWrapper::DeleteIO(CKBehavior* behaviour) { int iIO; int nbPin0; // Input nbPin0 = behaviour->GetInputCount(); for (iIO = nbPin0-1; iIO >= 0; iIO--) { if (behaviour->DeleteInput(iIO) != CK_OK) return FALSE; } // Ouput nbPin0 = behaviour->GetOutputCount(); for (iIO = nbPin0-1; iIO >= 0; iIO--) { if (behaviour->DeleteOutput(iIO) != CK_OK) return FALSE; } // Parameter In nbPin0 = behaviour->GetInputParameterCount(); for (iIO = nbPin0-1; iIO >= 0; iIO--) { CKParameterIn* pParam; if ((pParam = behaviour->RemoveInputParameter(iIO)) == NULL) return FALSE; CKDestroyObject(pParam); } // Parameter Out nbPin0 = behaviour->GetOutputParameterCount(); for (iIO = nbPin0-1; iIO >= 0; iIO--) { CKParameterOut* pParam; if ((pParam = behaviour->RemoveOutputParameter(iIO)) == NULL) return FALSE; CKDestroyObject(pParam); } return TRUE; } /* ******************************************************************* * Function: BOOL HasIO(CKBehavior* behaviour) * * Description : return TRUE if the behavior has almost one IN/OU/PIN/POUT * * Parameters : * behaviour The behavior to be checked. * * Returns : BOOL * ******************************************************************* */ BOOL BGWrapper::HasIO(CKBehavior* behaviour) { // Input if (behaviour->GetInputCount()) return TRUE; // Ouput if (behaviour->GetOutputCount()) return TRUE; // Parameter In if (behaviour->GetInputParameterCount()) return TRUE; // Parameter Out if (behaviour->GetOutputParameterCount()) return TRUE; return FALSE; } /* ******************************************************************* * Function: void ActivateNextFrameSubBB(CKBehavior* scriptObject,BOOL &bActivateNextFrame) * * Description : set the bActivateNextFrame to TRUE if one sub behavior is still active. * * Parameters : * scriptObject The behavior to be checked. * * Returns : void * ******************************************************************* */ void BGWrapper::ActivateNextFrameSubBB(CKBehavior* scriptObject,BOOL &bActivateNextFrame) { if ( scriptObject == NULL ) return; if ( scriptObject->IsActive() ) { bActivateNextFrame = TRUE; return; } for ( int i = 0; i < scriptObject->GetSubBehaviorCount(); i++) { CKBehavior*scriptSub = scriptObject->GetSubBehavior(i); ActivateNextFrameSubBB(scriptSub,bActivateNextFrame); } } /* ******************************************************************* * Function: void DesactivateSubBB(CKBehavior* scriptObject) * * Description : Desactivate all sub-Behavior * * Parameters : * scriptObject The behavior to be totally desactivated. * * Returns : void * ******************************************************************* */ void BGWrapper::DesactivateSubBB(CKBehavior* scriptObject) { if ( scriptObject == NULL ) return; scriptObject->Activate(FALSE,TRUE); for ( int i = 0; i < scriptObject->GetSubBehaviorCount(); i++) { CKBehavior*scriptSub = scriptObject->GetSubBehavior(i); DesactivateSubBB(scriptSub); } } /* ******************************************************************* * Function: void OwnerSubBB(CKBehavior* scriptObject,CKBeObject*owner) * * Description : Set Owner ptr to all sub-Behavior. * * Parameters : * scriptObject behavior to be parsed. * owner owner to be assigned. * * Returns : void * ******************************************************************* */ void BGWrapper::OwnerSubBB(CKBehavior* scriptObject,CKBeObject*owner) { if ( scriptObject == NULL ) return; scriptObject->SetSubBehaviorOwner(owner); scriptObject->SetOwner(owner); for ( int i = 0; i < scriptObject->GetSubBehaviorCount(); i++) { CKBehavior*scriptSub = scriptObject->GetSubBehavior(i); OwnerSubBB(scriptSub,owner); } } /* ******************************************************************* * Function: void SetNewBG(CKBehavior *behaviour,CKBehavior *newBehavior) * * Description : Set new BB name and store the BG locally. * * Parameters : * behaviour BG wrapper BB * newBehavior BG assigned to the wrapper * * Returns : void * ******************************************************************* */ void BGWrapper::SetNewBG(CKBehavior *behaviour,CKBehavior *newBehavior) { if ( behaviour == NULL || newBehavior == NULL ) return; CKSTRING nameBG = newBehavior->GetName(); size_t len = strlen(nameBG); char*buf = (char*)malloc(len+128); if ( buf != NULL ) { sprintf(buf, "BI(%s)", newBehavior->GetName()); behaviour->SetName(buf); free(buf); } else behaviour->SetName("BI(###ERROR###)"); behaviour->SetLocalParameterObject(EBGWRAPPERPARAM_PARAMETER_SCRIPT,newBehavior); } /* ******************************************************************* * Function: void DestroyCurrentBG(CKLevel* level,CKBehavior *behaviour,CKBehavior *scriptObject) * * Description : Destroy the currently wrapped BG * * Parameters : * level level from witch the BG will be removed * behaviour BG wrapper BB. * scriptObject BG assigned to the wrapper. * * Returns : void * ******************************************************************* */ void BGWrapper::DestroyCurrentBG(CKLevel* level,CKBehavior *behaviour,CKBehavior *scriptObject) { if ( level == NULL || behaviour == NULL || scriptObject == NULL ) return; behaviour->SetName("BI(###Failed###)"); level->BeginRemoveSequence(TRUE); level->RemoveObject(scriptObject); level->BeginRemoveSequence(FALSE); CKDestroyObject(scriptObject); behaviour->SetLocalParameterObject(EBGWRAPPERPARAM_PARAMETER_SCRIPT,NULL); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" //#include "pVehicle.h" #include "Bind.h" PhysicManager *ourMan = NULL; typedef ForceMode PForceMode; typedef D6MotionMode PJMotion; typedef D6DriveType PDriveType; // a {d1=35549095 d2=1877427728 d=0x0012fc9c } CKGUID #define BEH_GUID_VSL CKGUID(35549095,1877427728) CKGUID getGuidByID(int op) { CKBeObject *obj = (CKBeObject*)GetPMan()->GetContext()->GetObject(op); CKGUID a; if (obj) { CKBehavior *beh = (CKBehavior*)(obj); if (beh) { a = beh->GetPrototypeGuid(); } } return CKGUID(); } int doVSLScript(int vslBehID) { //---------------------------------------------------------------- // // our script, simple addition of two inputs // XString vslScript; vslScript << "void main(){ c = a + b; }" ; int result = 0; CKBehaviorIO *scriptIn; //sprintf(tmpName,"%s-beh",NameChar); /* CKBehavior *MyScript = (CKBehavior *) ctx()->CreateObject(CKCID_BEHAVIOR,"MyScript"); MyScript->SetType(CKBEHAVIORTYPE_SCRIPT); scriptIn=MyScript->CreateInput("Start"); MyScript->UseGraph(); MyScript->SetCompatibleClassID(CKCID_BEOBJECT); */ //---------------------------------------------------------------- // // create script // //CK_OBJECTCREATION_OPTIONS crOptions = CK_OBJECTCREATION_DYNAMIC; //CKBehavior *script = (CKBehavior *)ctx()->CreateObject(CKCID_BEHAVIOR,NULL,CK_OBJECTCREATION_DYNAMIC); CKBehavior *script = (CKBehavior *)ctx()->GetObject(vslBehID); //CKERROR error = script->InitFromGuid(BEH_GUID_VSL); // create ins/outs // script->CreateInputParameter("a",CKPGUID_INT); script->CreateInputParameter("b",CKPGUID_INT); script->CreateOutputParameter("c",CKPGUID_INT); script->SetName("Created_Rotate"); //script->SetAsTargetable(); //script->UseTarget(); //error= MyScript->AddSubBehavior(script); //ctx()->GetCurrentLevel()->AddObject(MyScript); //---------------------------------------------------------------- // // activate RunVSL Settings "Run-Time Script Change" // bool dynaFlag=true; //script->SetLocalParameterValue(0,&dynaFlag); //script->SetLocalParameterValue(1,&dynaFlag); int count = script->GetInputParameterCount(); int lcount = script->GetLocalParameterCount(); //---------------------------------------------------------------- // // Pass the script content // vtTools::BehaviorTools::SetInputParameterValue<CKSTRING>(script,0,vslScript.Str()); //---------------------------------------------------------------- // // Pass arguments // vtTools::BehaviorTools::SetInputParameterValue<int>(script,1,10); vtTools::BehaviorTools::SetInputParameterValue<int>(script,2,11); //---------------------------------------------------------------- // // execute // script->Execute(0.5f); result = vtTools::BehaviorTools::GetOutputParameterValue<int>(script,0); /* CKFile* file = ctx()->CreateCKFile(); file->StartSave("c:\\1.nms"); file->SaveObject((CKObject *) MyScript); file->EndSave(); ctx()->DeleteCKFile(file); */ return result; } pRigidBody *getBody(CK3dEntity*ent){ pRigidBody *body = GetPMan()->getBody(ent); if (body) { return body; }else{ return NULL; } } void __newpSpring(BYTE *iAdd) { new (iAdd) pSpring(); } void __newpSoftLimit(BYTE *iAdd) { new (iAdd) pJD6SoftLimit(); } void __newpDrive(BYTE *iAdd) { new (iAdd) pJD6Drive(); } void __newpJointLimit(BYTE *iAdd) { new (iAdd) pJointLimit(); } void __newpMotor(BYTE *iAdd) { new (iAdd) pMotor(); } pSerializer *GetSerializer() { return pSerializer::Instance(); } void __newpClothDescr(BYTE *iAdd) { new(iAdd)pClothDesc(); } #define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) void PhysicManager::_RegisterVSL() { ourMan = GetPMan(); _RegisterVSLCommon(); _RegisterVSLVehicle(); STARTVSLBIND(m_Context) DECLAREFUN_C_1(CKGUID,getGuidByID,int) DECLAREFUN_C_1(int,doVSLScript,int) ////////////////////////////////////////////////////////////////////////// // // Bindings for pVehicle related classes : // // DECLAREENUM("pClothAttachmentFlag") DECLAREENUMVALUE("pClothAttachmentFlag", "PCAF_ClothAttachmentTwoway" ,1 ) DECLAREENUMVALUE("pClothAttachmentFlag", "PCAF_ClothAttachmentTearable" ,2 ) DECLAREENUM("pClothFlag") DECLAREENUMVALUE("pClothFlag", "PCF_Pressure" ,1 ) DECLAREENUMVALUE("pClothFlag", "PCF_Static",2) DECLAREENUMVALUE("pClothFlag", "PCF_DisableCollision",4) DECLAREENUMVALUE("pClothFlag", "PCF_SelfCollision",8) DECLAREENUMVALUE("pClothFlag", "PCF_Gravity",32) DECLAREENUMVALUE("pClothFlag", "PCF_Bending",64) DECLAREENUMVALUE("pClothFlag", "PCF_BendingOrtho",128) DECLAREENUMVALUE("pClothFlag", "PCF_Damping",256) DECLAREENUMVALUE("pClothFlag", "PCF_CollisionTwoway",512) DECLAREENUMVALUE("pClothFlag", "PCF_TriangleCollision",2048) DECLAREENUMVALUE("pClothFlag", "PCF_Tearable",4096) DECLAREENUMVALUE("pClothFlag", "PCF_Hardware",8192) DECLAREENUMVALUE("pClothFlag", "PCF_ComDamping",16384) DECLAREENUMVALUE("pClothFlag", "PCF_ValidBounds",32768) DECLAREENUMVALUE("pClothFlag", "PCF_FluidCollision",65536) DECLAREENUMVALUE("pClothFlag", "PCF_DisableDynamicCCD",131072) DECLAREENUMVALUE("pClothFlag", "PCF_AddHere",262144) DECLAREENUMVALUE("pClothFlag", "PCF_AttachToParentMainShape",524288) DECLAREENUMVALUE("pClothFlag", "PCF_AttachToCollidingShapes",1048576) DECLAREENUMVALUE("pClothFlag", "PCF_AttachToCore",2097152) DECLAREENUMVALUE("pClothFlag", "PCF_AttachAttributes",4194304) DECLAREOBJECTTYPE(pClothDesc) DECLAREMEMBER(pClothDesc,float,thickness) DECLAREMEMBER(pClothDesc,float,density) DECLAREMEMBER(pClothDesc,float,bendingStiffness) DECLAREMEMBER(pClothDesc,float,stretchingStiffness) DECLAREMEMBER(pClothDesc,float,dampingCoefficient) DECLAREMEMBER(pClothDesc,float,friction) DECLAREMEMBER(pClothDesc,float,pressure) DECLAREMEMBER(pClothDesc,float,tearFactor) DECLAREMEMBER(pClothDesc,float,collisionResponseCoefficient) DECLAREMEMBER(pClothDesc,float,attachmentResponseCoefficient) DECLAREMEMBER(pClothDesc,float,attachmentTearFactor) DECLAREMEMBER(pClothDesc,float,toFluidResponseCoefficient) DECLAREMEMBER(pClothDesc,float,fromFluidResponseCoefficient) DECLAREMEMBER(pClothDesc,float,minAdhereVelocity) DECLAREMEMBER(pClothDesc,int,solverIterations) DECLAREMEMBER(pClothDesc,VxVector,externalAcceleration) DECLAREMEMBER(pClothDesc,VxVector,windAcceleration) DECLAREMEMBER(pClothDesc,float,wakeUpCounter) DECLAREMEMBER(pClothDesc,float,sleepLinearVelocity) DECLAREMEMBER(pClothDesc,int,collisionGroup) DECLAREMEMBER(pClothDesc,VxBbox,validBounds) DECLAREMEMBER(pClothDesc,float,relativeGridSpacing) DECLAREMEMBER(pClothDesc,pClothFlag,flags) DECLAREMEMBER(pClothDesc,pClothAttachmentFlag,attachmentFlags) DECLAREMEMBER(pClothDesc,VxColor,tearVertexColor) DECLAREMEMBER(pClothDesc,CK_ID,worldReference) DECLAREMETHOD_0(pClothDesc,void,setToDefault) DECLARECTOR_0(__newpClothDescr) ////////////////////////////////////////////////////////////////////////// // // Vehicle : // DECLAREMETHOD_1(PhysicManager,pVehicle*,getVehicle,CK3dEntity*) DECLAREMETHOD_1(PhysicManager,pWheel2*,getWheel,CK3dEntity*) ////////////////////////////////////////////////////////////////////////// // // Bindings for pVehicle related classes : // // ////////////////////////////////////////////////////////////////////////// // // Bindings for pVehicle related classes : // // DECLAREOBJECTTYPE(pJointLimit) DECLARECTOR_0(__newpJointLimit) DECLAREMEMBER(pJointLimit,float,hardness) DECLAREMEMBER(pJointLimit,float,restitution) DECLAREMEMBER(pJointLimit,float,value) DECLAREOBJECTTYPE(pJD6Drive) DECLARECTOR_0(__newpDrive) DECLAREMEMBER(pJD6Drive,float,damping) DECLAREMEMBER(pJD6Drive,float,spring) DECLAREMEMBER(pJD6Drive,float,forceLimit) DECLAREMEMBER(pJD6Drive,int,driveType) DECLAREOBJECTTYPE(pJD6SoftLimit) DECLARECTOR_0(__newpSoftLimit) DECLAREMEMBER(pJD6SoftLimit,float,damping) DECLAREMEMBER(pJD6SoftLimit,float,spring) DECLAREMEMBER(pJD6SoftLimit,float,value) DECLAREMEMBER(pJD6SoftLimit,float,restitution) DECLAREOBJECTTYPE(pSpring) DECLARECTOR_0(__newpSpring) //DECLARECTOR_3(__newpSpringSettings3,float,float,float) DECLAREMEMBER(pSpring,float,damper) DECLAREMEMBER(pSpring,float,spring) DECLAREMEMBER(pSpring,float,targetValue) DECLAREOBJECTTYPE(pMotor) DECLARECTOR_0(__newpMotor) DECLAREMEMBER(pMotor,float,maximumForce) DECLAREMEMBER(pMotor,float,targetVelocity) DECLAREMEMBER(pMotor,float,freeSpin) ////////////////////////////////////////////////////////////////////////// // // Serializer : // DECLAREPOINTERTYPE(pSerializer) DECLAREFUN_C_0(pSerializer*, GetSerializer) DECLAREMETHOD_2(pSerializer,void,overrideBody,pRigidBody*,int) DECLAREMETHOD_2(pSerializer,int,loadCollection,const char*,int) DECLAREMETHOD_1(pSerializer,int,saveCollection,const char*) DECLAREMETHOD_2(pSerializer,void,parseFile,const char*,int) ////////////////////////////////////////////////////////////////////////// // // Factory // ////////////////////////////////////////////////////////////////////////// // // ENUMERATION // DECLAREENUM("D6DriveType") DECLAREENUMVALUE("D6DriveType", "D6DT_Position" ,1 ) DECLAREENUMVALUE("D6DriveType", "D6DT_Velocity" ,2 ) DECLAREENUM("PForceMode") DECLAREENUMVALUE("PForceMode", "PFM_Force" , 0) DECLAREENUMVALUE("PForceMode", "PFM_Impulse" , 1) DECLAREENUMVALUE("PForceMode", "PFM_VelocityChange" , 2) DECLAREENUMVALUE("PForceMode", "PFM_SmoothImpulse" , 3) DECLAREENUMVALUE("PForceMode", "PFM_SmoothVelocityChange" , 4) DECLAREENUMVALUE("PForceMode", "PFM_Acceleration" , 5) DECLAREENUM("D6MotionMode") DECLAREENUMVALUE("D6MotionMode", "D6MM_Locked" , 0) DECLAREENUMVALUE("D6MotionMode", "D6MM_Limited" , 1) DECLAREENUMVALUE("D6MotionMode", "D6MM_Free" , 2) DECLAREENUM("JType") DECLAREENUMVALUE("JType", "JT_Any" , -1) DECLAREENUMVALUE("JType", "JT_Prismatic" , 0) DECLAREENUMVALUE("JType", "JT_Revolute" , 1) DECLAREENUMVALUE("JType", "JT_Cylindrical" , 2) DECLAREENUMVALUE("JType", "JT_Spherical" , 3) DECLAREENUMVALUE("JType", "JT_PointOnLine" , 4) DECLAREENUMVALUE("JType", "JT_PointInPlane" , 5) DECLAREENUMVALUE("JType", "JT_Distance" , 6) DECLAREENUMVALUE("JType", "JT_Pulley" , 7) DECLAREENUMVALUE("JType", "JT_Fixed" ,8 ) DECLAREENUMVALUE("JType", "JT_D6" ,9 ) ////////////////////////////////////////////////////////////////////////// // // Bindings for pVehicle related classes : // // DECLAREMETHOD_2(pFactory,pVehicle*,createVehicle,CK3dEntity*,pVehicleDesc) //DECLAREMETHOD_0(pVehicle,float,getWheelRollAngle) //DECLAREMETHOD_0(pVehicle,float,getRpm) ////////////////////////////////////////////////////////////////////////// // // JOINT CREATION // DECLAREMETHOD_11_WITH_DEF_VALS(pFactory,pJointDistance*,createDistanceJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,VxVector(),VxVector,VxVector(),float,0.0f,float,0.0f,pSpring,pSpring(),BOOL,"TRUE",float,"0.0",float,"0.0",const char *,"pJDistance") DECLAREMETHOD_5(pFactory,pJointD6*,createD6Joint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,bool) DECLAREMETHOD_5_WITH_DEF_VALS(pFactory,pJointFixed*,createFixedJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,float,"0.0",float,"0,0",const char*,"PJFixed") DECLAREMETHOD_3_WITH_DEF_VALS(pFactory,pRigidBody*,createBody,CK3dEntity*,NODEFAULT,pObjectDescr,NODEFAULT,CK3dEntity*,NULL) DECLAREMETHOD_2(pFactory,pRigidBody*,createRigidBody,CK3dEntity*,pObjectDescr&) DECLAREMETHOD_2(pFactory,bool,loadMaterial,pMaterial&,const char*) DECLAREMETHOD_2(pFactory,pMaterial,loadMaterial,const char*,int&) DECLAREMETHOD_2(pFactory,bool,loadFrom,pWheelDescr&,const char*) DECLAREMETHOD_5(pFactory,pWheel*,createWheel,CK3dEntity *,CK3dEntity*,pWheelDescr,pConvexCylinderSettings,VxVector) DECLAREMETHOD_9_WITH_DEF_VALS(pFactory,pJointPulley*,createPulleyJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,BOOL,"TRUE",float,"0.0",float,"0.0") DECLAREMETHOD_9_WITH_DEF_VALS(pFactory,pJointBall*,createBallJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,VxVector,"0,0,1",bool,"TRUE",float,"0.0",float,"0.0",const char*,"pJBall") DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointRevolute*,createRevoluteJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,"TRUE",float,"0.0",float,"0.0",const char*,"pJRevolute") DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointPrismatic*,createPrismaticJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,TRUE,float,"0.0",float,"0.0",const char*,"pJPrismatic") DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointCylindrical*,createCylindricalJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,TRUE,float,"0.0",float,"0.0",,const char*,"pJCylindrical") DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointPointInPlane*,createPointInPlaneJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,TRUE,float,"0.0",float,"0.0",const char*,"pJPointInPlane") DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointPointOnLine*,createPointOnLineJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,TRUE,float,"0.0",float,"0.0",const char*,"pJPointOnLine") DECLAREMETHOD_2(pFactory,pCloth*,createCloth,CK3dEntity*,pClothDesc) ////////////////////////////////////////////////////////////////////////// // // Cloth // DECLAREMETHOD_4(pCloth,void,attachToCore,CK3dEntity*,float,float,float) DECLAREMETHOD_2(pCloth,void,attachToShape,CK3dEntity*,pClothAttachmentFlag) ////////////////////////////////////////////////////////////////////////// // // MANAGER // DECLAREMETHOD_0(PhysicManager,pWorld*,getDefaultWorld) DECLAREMETHOD_2_WITH_DEF_VALS(PhysicManager,pRigidBody*,getBody,CK3dEntity*,NODEFAULT,bool,FALSE) DECLAREMETHOD_1(PhysicManager,pWorld*,getWorldByBody,CK3dEntity*) DECLAREMETHOD_1(PhysicManager,pWorld*,getWorld,CK_ID) DECLAREMETHOD_1(PhysicManager,int,getAttributeTypeByGuid,CKGUID) DECLAREMETHOD_2(PhysicManager,void,copyToAttributes,pObjectDescr,CK3dEntity*) DECLAREMETHOD_1(CK3dEntity,CKBOOL,HasAttribute,int) DECLAREMETHOD_3_WITH_DEF_VALS(PhysicManager,pJoint*,getJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NULL,JType,JT_Any) // DECLAREMETHOD_0(PhysicManager,void,makeDongleTest) ////////////////////////////////////////////////////////////////////////// // // World // DECLAREMETHOD_1(pWorld,pRigidBody*,getBody,CK3dEntity*) DECLAREMETHOD_1(pWorld,pVehicle*,getVehicle,CK3dEntity*) DECLAREMETHOD_3(pWorld,pJoint*,getJoint,CK3dEntity*,CK3dEntity*,JType) DECLAREMETHOD_3(pWorld,void,setFilterOps,pFilterOp,pFilterOp,pFilterOp) DECLAREMETHOD_1(pWorld,void,setFilterBool,bool) DECLAREMETHOD_1(pWorld,void,setFilterConstant0,const pGroupsMask&) DECLAREMETHOD_1(pWorld,void,setFilterConstant1,const pGroupsMask&) DECLAREMETHOD_1(pWorld,void,setGravity,VxVector) DECLAREMETHOD_0(pWorld,VxVector,getGravity) // DECLAREMETHOD_5_WITH_DEF_VALS(pWorld,bool,raycastAnyBounds,const VxRay&,NODEFAULT,pShapesType,NODEFAULT,pGroupsMask,NODEFAULT,int,0xffffffff,float,NX_MAX_F32) DECLAREMETHOD_8(pWorld,bool,overlapSphereShapes,CK3dEntity*,const VxSphere&,CK3dEntity*,pShapesType,CKGroup*,int,const pGroupsMask*,BOOL) //(const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,unsigned int groups=0xffffffff, float maxDist=NX_MAX_F32); DECLAREMETHOD_1(pJoint,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJoint,void,setGlobalAnchor,VxVector) DECLAREMETHOD_0(pJoint,VxVector,getGlobalAxis) DECLAREMETHOD_0(pJoint,VxVector,getGlobalAnchor) ////////////////////////////////////////////////////////////////////////// // // JOINT :: Revolute // DECLAREMETHOD_0(pJoint,pJointRevolute*,castRevolute) DECLAREMETHOD_1(pJointRevolute,void,setGlobalAnchor,const VxVector&) DECLAREMETHOD_1(pJointRevolute,void,setGlobalAxis,const VxVector&) DECLAREMETHOD_1(pJointRevolute,void,setSpring,pSpring) DECLAREMETHOD_1(pJointRevolute,void,setHighLimit,pJointLimit) DECLAREMETHOD_1(pJointRevolute,void,setLowLimit,pJointLimit) DECLAREMETHOD_1(pJointRevolute,void,setMotor,pMotor) DECLAREMETHOD_0(pJointRevolute,pSpring,getSpring) DECLAREMETHOD_0(pJointRevolute,pJointLimit,getLowLimit) DECLAREMETHOD_0(pJointRevolute,pJointLimit,getHighLimit) DECLAREMETHOD_0(pJointRevolute,pMotor,getMotor) DECLAREMETHOD_1(pJointRevolute,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT :: Ball // DECLAREMETHOD_0(pJoint,pJointBall*,castBall) DECLAREMETHOD_1(pJointBall,void,setAnchor,VxVector) DECLAREMETHOD_1(pJointBall,void,setSwingLimitAxis,VxVector) DECLAREMETHOD_1(pJointBall,bool,setSwingLimit,pJointLimit) DECLAREMETHOD_1(pJointBall,bool,setTwistHighLimit,pJointLimit) DECLAREMETHOD_1(pJointBall,bool,setTwistLowLimit,pJointLimit) DECLAREMETHOD_0(pJointBall,pJointLimit,getSwingLimit) DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistHighLimit) DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistLowLimit) DECLAREMETHOD_1(pJointBall,bool,setSwingSpring,pSpring) DECLAREMETHOD_1(pJointBall,bool,setTwistSpring,pSpring) DECLAREMETHOD_1(pJointBall,void,setJointSpring,pSpring) DECLAREMETHOD_0(pJointBall,pSpring,getSwingSpring) DECLAREMETHOD_0(pJointBall,pSpring,getTwistSpring) DECLAREMETHOD_0(pJointBall,pSpring,getJointSpring) DECLAREMETHOD_1(pJointBall,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT Prismatic // // DECLAREMETHOD_0(pJoint,pJointPrismatic*,castPrismatic) DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointPrismatic,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT Cylindrical // // DECLAREMETHOD_0(pJoint,pJointCylindrical*,castCylindrical) DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointCylindrical,void,enableCollision,int) ////////////////////////////////////////////////////////////////////////// // // JOINT Point In Plane // // DECLAREMETHOD_0(pJoint,pJointPointInPlane*,castPointInPlane) DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointPointInPlane,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT Point In Plane // // DECLAREMETHOD_0(pJoint,pJointPointOnLine*,castPointOnLine) DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointPointOnLine,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT BASE // // DECLAREMETHOD_1(pJoint,void,setLocalAnchor0,VxVector) DECLAREMETHOD_2(pJoint,void,setBreakForces,float,float) DECLAREMETHOD_2(pJoint,void,getBreakForces,float&,float&) DECLAREMETHOD_3(pJoint,int,addLimitPlane,VxVector,VxVector,float) DECLAREMETHOD_2_WITH_DEF_VALS(pJoint,void,setLimitPoint,VxVector,NODEFAULT,bool,true) DECLAREMETHOD_0(pJoint,void,purgeLimitPlanes) DECLAREMETHOD_0(pJoint,void,resetLimitPlaneIterator) DECLAREMETHOD_0(pJoint,int,hasMoreLimitPlanes) DECLAREMETHOD_3(pJoint,int,getNextLimitPlane,VxVector&,float&,float&) DECLAREMETHOD_0(pJoint,int,getType) ////////////////////////////////////////////////////////////////////////// // // JOINT :: DISTANCE // DECLAREMETHOD_0(pJoint,pJointDistance*,castDistanceJoint) DECLAREMETHOD_1(pJointDistance,void,setMinDistance,float) DECLAREMETHOD_1(pJointDistance,void,setMaxDistance,float) DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor0,VxVector) DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor1,VxVector) DECLAREMETHOD_1(pJointDistance,void,setSpring,pSpring) DECLAREMETHOD_0(pJointDistance,float,getMinDistance) DECLAREMETHOD_0(pJointDistance,float,getMaxDistance) DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor0) DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor1) DECLAREMETHOD_0(pJointDistance,pSpring,getSpring) DECLAREMETHOD_1(pJointDistance,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT PULLEY // DECLAREMETHOD_0(pJoint,pJointPulley*,castPulley) DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorA,VxVector) DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorB,VxVector) DECLAREMETHOD_1(pJointPulley,void,setPulleyA,VxVector) DECLAREMETHOD_1(pJointPulley,void,setPulleyB,VxVector) DECLAREMETHOD_1(pJointPulley,void,setStiffness,float) DECLAREMETHOD_1(pJointPulley,void,setRatio,float) DECLAREMETHOD_1(pJointPulley,void,setRigid,int) DECLAREMETHOD_1(pJointPulley,void,setDistance,float) DECLAREMETHOD_1(pJointPulley,void,setMotor,pMotor) DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorA) DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorB) DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyA) DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyB) DECLAREMETHOD_0(pJointPulley,float,getStiffness) DECLAREMETHOD_0(pJointPulley,float,getRatio) DECLAREMETHOD_0(pJointPulley,float,getDistance) DECLAREMETHOD_1(pJointPulley,void,enableCollision,bool) DECLAREMETHOD_0(pJointPulley,pMotor,getMotor) ////////////////////////////////////////////////////////////////////////// // // JOINT D6 // DECLAREMETHOD_0(pJoint,pJointD6*,castD6Joint) DECLAREMETHOD_1(pJointD6,void,setTwistMotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setSwing1MotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setSwing2MotionMode,D6MotionMode) DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) DECLAREMETHOD_1(pJointD6,void,setXMotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setYMotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setZMotionMode,D6MotionMode) DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) ////////////////////////////////////////////////////////////////////////// //softwLimits DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getLinearLimit) DECLAREMETHOD_1(pJointD6,int,setLinearLimit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing1Limit) DECLAREMETHOD_1(pJointD6,int,setSwing1Limit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing2Limit) DECLAREMETHOD_1(pJointD6,int,setSwing2Limit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistHighLimit) DECLAREMETHOD_1(pJointD6,int,setTwistHighLimit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistLowLimit) DECLAREMETHOD_1(pJointD6,int,setTwistLowLimit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6Drive,getXDrive) DECLAREMETHOD_1(pJointD6,int,setXDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getYDrive) DECLAREMETHOD_1(pJointD6,int,setYDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getZDrive) DECLAREMETHOD_1(pJointD6,int,setZDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getSwingDrive) DECLAREMETHOD_1(pJointD6,int,setSwingDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getTwistDrive) DECLAREMETHOD_1(pJointD6,int,setTwistDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getSlerpDrive) DECLAREMETHOD_1(pJointD6,int,setSlerpDrive,pJD6Drive) DECLAREMETHOD_1(pJointD6,void,setDrivePosition,VxVector) DECLAREMETHOD_1(pJointD6,void,setDriveRotation,VxQuaternion) DECLAREMETHOD_1(pJointD6,void,setDriveLinearVelocity,VxVector) DECLAREMETHOD_1(pJointD6,void,setDriveAngularVelocity,VxVector) DECLAREMETHOD_1(pJointD6,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // Rigid Body Exports // // /************************************************************************/ /* Forces */ /************************************************************************/ DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addForce,const VxVector&,NODEFAULT, PForceMode, 0,bool,true) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addTorque,const VxVector&,NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalForce,const VxVector&,NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalTorque,const VxVector&,NODEFAULT, PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtPos, const VxVector&,NODEFAULT,const VxVector&,NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtLocalPos,const VxVector,NODEFAULT, const VxVector&, NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtPos, const VxVector&, NODEFAULT,const VxVector&,NODEFAULT, PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtLocalPos, const VxVector&, NODEFAULT,const VxVector&, NODEFAULT,PForceMode,0,bool,true) /************************************************************************/ /* Momentum */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setAngularMomentum,const VxVector&) DECLAREMETHOD_1(pRigidBody,void,setLinearMomentum,const VxVector&) DECLAREMETHOD_0(pRigidBody,VxVector,getAngularMomentum) DECLAREMETHOD_0(pRigidBody,VxVector,getLinearMomentum) /************************************************************************/ /* collision + callbacks */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setContactReportThreshold,float) DECLAREMETHOD_0(pRigidBody,float,setContactReportThreshold) DECLAREMETHOD_1(pRigidBody,void,setContactReportFlags,pContactPairFlags) DECLAREMETHOD_0(pRigidBody,int,getContactReportFlags) DECLAREMETHOD_2(pRigidBody,void,setContactScript,int,int) DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setTriggerScript,int,NODEFAULT,int,NODEFAULT,CK3dEntity*,NULL) DECLAREMETHOD_1(pRigidBody,void,setContactModificationScript,int) DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setSkinWidth,const float,NODEFAULT,CK3dEntity*,NULL) /************************************************************************/ /* Pose : */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setPosition,const VxVector&) DECLAREMETHOD_1(pRigidBody,void,setRotation,const VxQuaternion&) DECLAREMETHOD_1(pRigidBody,void,translateLocalShapePosition,VxVector) /************************************************************************/ /* Velocity : */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setLinearVelocity,const VxVector&) DECLAREMETHOD_1(pRigidBody,void,setAngularVelocity,const VxVector&) DECLAREMETHOD_0(pRigidBody,float,getMaxAngularSpeed) DECLAREMETHOD_0(pRigidBody,VxVector,getLinearVelocity) DECLAREMETHOD_0(pRigidBody,VxVector,getAngularVelocity) /************************************************************************/ /* Mass */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setCMassOffsetGlobalPosition,VxVector) DECLAREMETHOD_1(pRigidBody,void,setCMassGlobalPosition,VxVector) DECLAREMETHOD_0(pRigidBody,VxVector,getCMassLocalPosition) DECLAREMETHOD_0(pRigidBody,VxVector,getCMassGlobalPosition) //DECLAREMETHOD_1(pRigidBody,void,setMass,float) DECLAREMETHOD_0(pRigidBody,float,getMass) DECLAREMETHOD_1(pRigidBody,void,setMassSpaceInertiaTensor,VxVector) DECLAREMETHOD_0(pRigidBody,VxVector,getMassSpaceInertiaTensor) DECLAREMETHOD_1(pRigidBody,void,setCMassOffsetLocalPosition,VxVector) DECLAREMETHOD_1(pRigidBody,void,setMassOffset,VxVector) DECLAREMETHOD_1(pRigidBody,void,setMaxAngularSpeed,float) /************************************************************************/ /* Hull */ /************************************************************************/ DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) DECLAREMETHOD_0(pRigidBody,pWorld*,getWorld) DECLAREMETHOD_1(pRigidBody,pJoint*,isConnected,CK3dEntity*) DECLAREMETHOD_2(pRigidBody,pJoint*,isConnected,CK3dEntity*,int) //DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) //DECLAREMETHOD_1_WITH_DEF_VALS(pRigidBody,float,getMass,CK3dEntity*,NULL) DECLAREMETHOD_0(pRigidBody,int,getHullType) DECLAREMETHOD_2(pRigidBody,void,setGroupsMask,CK3dEntity*,const pGroupsMask&) DECLAREMETHOD_0(pRigidBody,int,getFlags) DECLAREMETHOD_1(pRigidBody,VxVector,getPointVelocity,const VxVector&) DECLAREMETHOD_1(pRigidBody,VxVector,getLocalPointVelocity,const VxVector&) DECLAREMETHOD_0(pRigidBody,bool,isCollisionEnabled) DECLAREMETHOD_1(pRigidBody,void,setKinematic,int) DECLAREMETHOD_0(pRigidBody,int,isKinematic) DECLAREMETHOD_1(pRigidBody,void,enableGravity,int) DECLAREMETHOD_0(pRigidBody,bool,isAffectedByGravity) DECLAREMETHOD_1(pRigidBody,void,setSleeping,int) DECLAREMETHOD_0(pRigidBody,int,isSleeping) DECLAREMETHOD_1(pRigidBody,void,setLinearDamping,float) DECLAREMETHOD_1(pRigidBody,void,setAngularDamping,float) DECLAREMETHOD_1(pRigidBody,void,lockTransformation,BodyLockFlags) DECLAREMETHOD_1(pRigidBody,int,isBodyFlagOn,int) DECLAREMETHOD_1_WITH_DEF_VALS(pRigidBody,void,wakeUp,float,NX_SLEEP_INTERVAL) DECLAREMETHOD_1(pRigidBody,void,setSleepEnergyThreshold,float) DECLAREMETHOD_1(pRigidBody,void,setSolverIterationCount,int) DECLAREMETHOD_5_WITH_DEF_VALS(pRigidBody,bool,onSubShapeTransformation,bool,TRUE,bool,TRUE,bool,TRUE,CK3dEntity*,NULL,bool,true) DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setCollisionsGroup,int,NODEFAULT,CK3dEntity*,) DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,enableCollision,bool,NODEFAULT,CK3dEntity*,NULL) DECLAREMETHOD_0(pRigidBody,bool,hasWheels); DECLAREMETHOD_0(pRigidBody,int,getNbWheels); DECLAREMETHOD_0(pRigidBody,int,getNbSubShapes); DECLAREMETHOD_0(pRigidBody,int,getNbSubBodies); DECLAREMETHOD_0(pRigidBody,int,getCollisionsGroup) DECLAREMETHOD_2(pRigidBody,int,updateMassFromShapes,float,float) DECLAREMETHOD_5_WITH_DEF_VALS(pRigidBody,int,addSubShape,CKMesh*,NULL,pObjectDescr,NODEFAULT,CK3dEntity*,NULL,VxVector,VxVector(),VxQuaternion,VxQuaternion()) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,int,removeSubShape,CKMesh*,NODEFAULT,float,0.0,float,0.0) /************************************************************************/ /* Joint */ /************************************************************************/ DECLAREMETHOD_0(pRigidBody,int,getNbJoints); //DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,pJoint*,getJointAtIndex,int,NODEFAULT,int&,NODEFAULT,CK3dEntity**,NULL) DECLAREMETHOD_1(pRigidBody,pJoint*,getJointAtIndex,int) DECLAREMETHOD_2(pRigidBody,pJoint*,getJoint,CK3dEntity*,JType) DECLAREMETHOD_1(pRigidBody,void,deleteJoint,pJoint*) DECLAREMETHOD_2(pRigidBody,void,deleteJoint,CK3dEntity*,JType) STOPVSLBIND } <file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #include "tnlLog.h" #include "tnlDataChunker.h" #include <stdarg.h> namespace TNL { LogConsumer *LogConsumer::mLinkedList = NULL; LogConsumer::LogConsumer() { mNextConsumer = mLinkedList; if(mNextConsumer) mNextConsumer->mPrevConsumer = this; mPrevConsumer = NULL; mLinkedList = this; } LogConsumer::~LogConsumer() { if(mNextConsumer) mNextConsumer->mPrevConsumer = mPrevConsumer; if(mPrevConsumer) mPrevConsumer->mNextConsumer = mNextConsumer; else mLinkedList = mNextConsumer; } LogType *LogType::linkedList = NULL; LogType *LogType::current = NULL; #ifdef TNL_ENABLE_LOGGING LogType *LogType::find(const char *name) { static ClassChunker<LogType> logTypeChunker(4096); for(LogType *walk = linkedList; walk; walk = walk->next) if(!strcmp(walk->typeName, name)) return walk; LogType *ret = logTypeChunker.alloc(); ret->next = linkedList; linkedList = ret; ret->isEnabled = false; ret->typeName = name; return ret; } #endif void LogConsumer::logString(const char *string) { // by default the LogConsumer will output to the platform debug // string printer, but only if we're in debug mode #ifdef TNL_DEBUG Platform::outputDebugString(string); Platform::outputDebugString("\n"); #endif //printf(string); } void logprintf(const char *format, ...) { char buffer[4096]; U32 bufferStart = 0; if(LogType::current) { strcpy(buffer, LogType::current->typeName); bufferStart = strlen(buffer); buffer[bufferStart] = ':'; buffer[bufferStart+1] = ' '; bufferStart += 2; } va_list s; va_start( s, format ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, format, s); for(LogConsumer *walk = LogConsumer::getLinkedList(); walk; walk = walk->getNext()) walk->logString(buffer); va_end(s); Platform::outputDebugString(buffer); Platform::outputDebugString("\n"); } }; <file_sep>============================================ Readme for Virtools 4.1 January 2007 (C) Virtools SA, 2007. All rights reserved ============================================ This file contains last-minute information for Virtools. For information on how to use Virtools and how to get further information, refer to the Online Reference (documentation.chm) and the printed User Guide. -------- CONTENTS -------- 1. System Requirements 1.1 Hardware 1.2 Software 2. Registration and Support 2.1 Registration 2.2 Support 3. Installing Additional Components 4. Addons Folder 5. Logos 6. Last Minute Addenda ---------------------- 1. SYSTEM REQUIREMENTS ---------------------- To use Virtools, please ensure you respect the minimum requirements: 1.1 Hardware ------------ - Pentium III or equivalent - 1 GB of RAM - DVD ROM drive - Monitor capable of displaying 1024 by 768 in 16 bit color (65536 color/Hi-color) - Pointing device (mouse, trackball, etc.) - Direct3D or OpenGL compatible 3D graphic accelerator card with 128 MB of RAM - DirectSound compatible sound card (not a requirement but recommended) You should ensure you have the latest official drivers for your graphics card. 1.2 Software ------------ - Microsoft Windows (2000, XP or Vista) - Microsoft DirectX 9.0C (August 2007) for DirectX compatible 3D graphic accelerator cards - For OpenGL, an OpenGL 2.0 compatible graphics card and driver - Microsoft Internet Explorer 6.0 (for the Online Reference) --------------------------- 2. REGISTRATION AND SUPPORT --------------------------- You will need your Virtools serial number to activate your Virtools Software (with a FlexLM License), as well as to register for technical support at the virtools website: www.virtools.com. 2.1 License Registration under FlexLM ------------------------------------- You will need obtain a FlexLM license to be able to use your Virtools Software. Procedures and options are explained here: http://www.virtools.com/downloads/Doc/ 2.2 Support ----------- To qualify for support, you must first register online via the Virtools Website. To do this: - from the Start menu, choose Program Files > Virtools > Virtools 4.1 > then "Virtools Support Center". To obtain technical support, make sure you have a valid maintenance contract and use the link described above to go to the tech support page where you can send your question. ----------------------------------- 3. INSTALLING ADDITIONAL COMPONENTS ----------------------------------- By default, all components are selected when you first launch the Virtools installation program. However, the full install takes up a fair amount of space (c. 1 GB), and may include components that you do not at the moment need, such as export plugins and sample files, so you may have decided to install only some components. To add or re-install any components, simply insert the Virtools DVD, select "Virtools" in the installation program once more, and only select the components you want to install. ---------------- 4. ADDONS FOLDER ---------------- In addition to the Virtools installation folder on the Virtools Installation DVD-ROM, you will find a folder 'Addons', containing several applications helpful or necessary for Virtools. Of note are: - Microsoft DirectX 9.0c August 2007 (recommended for DirectX compatible graphics card) - Adobe Acrobat Reader 6.0.1 - Virtools Thumbnail Viewer (already installed by default) --------------- 5. LOGOS --------------- The various Virtools logos that you may need for contractual or licensing reasons are available at: http://www.virtools.com/partners/partner_zone_library.asp --------------- 6. Last Minute Addenda --------------- - IMPORTANT: If you are using the FlexLM Server to manage your Virtools Licenses, please reinstall the new FlexLM Server available on the DVD or at http://www.virtools.com/downloads/Doc/.<file_sep>//#include "StdAfx2.h" /* #include <Windows.h> #include "PCommonDialog.h" #include "PBodySetup.h" #include "PBXMLSetup.h" */ /* void CPBParentDialog::OnTabChange(int last,int current) { //mTestViControl.SetActiveTab(current); return; CPSharedBase* lastDlg = (CPSharedBase*)getDialog(last); if (lastDlg) { switch(last) { case BTAB_XML: { CPBXMLSetup*xmlDlg=(CPBXMLSetup*)CPSharedBase::getInstance()->getDialog(BTAB_XML); if (xmlDlg) { //xmlDlg->ShowWindow(SW_HIDE); //xmlDlg->UpdateWindow(); } }break; case BTAB_COMMON: { CPBodyCfg*cfg=(CPBodyCfg*)CPSharedBase::getInstance()->getDialog(BTAB_COMMON); if (cfg) { //cfg->ShowWindow(SW_HIDE); //cfg->UpdateWindow(); } }break; } } CPSharedBase* selectedDlg = (CPSharedBase*)getDialog(current); if (selectedDlg) { switch(current) { case BTAB_XML: { CPBXMLSetup*xmlDlg=(CPBXMLSetup*)CPSharedBase::getInstance()->getDialog(BTAB_XML); if (xmlDlg) { //xmlDlg->ShowWindow(SW_SHOW); //xmlDlg->UpdateWindow(); //xmlDlg->OnSelect(last); } }break; case BTAB_COMMON: { CPBodyCfg*cfg=(CPBodyCfg*)CPSharedBase::getInstance()->getDialog(BTAB_COMMON); if (cfg) { // cfg->ShowWindow(SW_NORMAL); //cfg->UpdateWindow(); cfg->OnSelect(last); } }break; } } } */<file_sep> -no need for any virtools dlls here -includes the physic pack, toolkit , interface widgets please have directx and physx - system software installed. if you run these exe files, please take care your are not using the standard plugin paths from the player.ini vtPlayerConsole.bat starts the player but just without rendering <file_sep>#include "xDistributedSession.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributedSessionClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xDistributedClient.h" int sessionIDCounter = 20; #include "xLogger.h" uxString xDistributedSession::print(TNL::BitSet32 flags) { return Parent::print(flags); } TNL_IMPLEMENT_NETOBJECT(xDistributedSession); xDistributedSession::xDistributedSession() { mSessionFlags = 0; mSessionID =sessionIDCounter; sessionIDCounter ++; mClientTable = new xClientArrayType(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedSession::~xDistributedSession() { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::pack(TNL::BitStream *bstream) { //writes update bits : ! Parent::pack(bstream); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); if (propInfo) { if (prop->getFlags() & E_DP_NEEDS_SEND) { prop->pack(bstream); //xLogger::xLog(ELOGINFO,XL_START,"sending session parameter to server : %s",prop->getPropertyInfo()->mName.getString()); } } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::unpack( TNL::BitStream *bstream,float sendersOneWayTime ) { Parent::unpack(bstream,sendersOneWayTime); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (propInfo) { if (getUpdateBits().testStrict(1<<blockIndex)) { prop->unpack(bstream,sendersOneWayTime); //xLogger::xLog(ELOGINFO,XL_START,"\t unpacking session prop on server :%s",propInfo->mName.getString()); setMaskBits(1<<blockIndex); } } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL::U32 xDistributedSession::packUpdate(TNL::GhostConnection *connection, TNL::U32 updateMask, TNL::BitStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); if (netInterface) { //the first time ? : we write out all necessary attributes for the client : if(stream->writeFlag(updateMask & InitialMask)) { if(stream->writeFlag(true)) { //write out name : stream->writeString(GetName().getString(),strlen(GetName().getString())); //retrieve its class : xDistributedClass *distClass = getDistributedClass(); if (distClass) { //write out the class name : stream->writeString(distClass->getClassName().getString(),strlen(distClass->getClassName().getString())); //write out the class base type : stream->writeInt(distClass->getEnitityType(),32); //write out users id : vtConnection *con = (vtConnection*)connection; int uid = getUserID(); stream->writeInt(getUserID(),32); //write out server side id : int serverID = connection->getGhostIndex(this); stream->writeInt(connection->getGhostIndex(this),32); setServerID(connection->getGhostIndex(this)); float time = getCreationTime(); //write out creation time stream->write(getCreationTime()); // xLogger::xLog(ELOGINFO,XL_START,"server:init pack update of %s: %f , %d , ",GetName().getString(),time,uid); stream->writeInt(getSessionID(),32); stream->writeInt(getMaxUsers(),32); stream->writeString(getPassword().getString(),strlen(getPassword().getString())); //netInterface->deploySessionClasses(connection); } setNetInterface(netInterface); } } /************************************************************************/ /* */ /************************************************************************/ stream->writeSignedInt(getUpdateBits().getMask(),32); //xLogger::xLog(ELOGINFO,XL_START,"server is updating ghosts %d", getUpdateBits().getMask() ); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (propInfo) { if (getUpdateBits().testStrict(1<<blockIndex)) { prop->updateGhostValue(stream); //xLogger::xLog(ELOGINFO,XL_START,"server is updating ghosts %d",blockIndex); } } } //getUpdateBits().clear(); } return 0; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::unpackUpdate(TNL::GhostConnection *connection, TNL::BitStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); if (netInterface) { ////////////////////////////////////////////////////////////////////////// //initial update ? if(stream->readFlag()) { if(stream->readFlag()) { char oName[256];stream->readString(oName); // retrieve objects name : char cName[256];stream->readString(cName); // retrieve objects dist class name : int type = stream->readInt(32); //read the dist class base type : int userID = stream->readInt(32); int serverID2 = stream->readInt(32); float creationTime = 0.0f; stream->read(&creationTime); int sessionID = stream->readInt(32); int MaxUsers = stream->readInt(32); char pass[256];stream->readString(pass); ////////////////////////////////////////////////////////////////////////// //now we store all in the dist object : //find and store the dist class : xDistributedClassesArrayType *_classes = netInterface->getDistributedClassInterface()->getDistrutedClassesPtr(); xDistributedClass *classTemplate = netInterface->getDistributedClassInterface()->get(cName,type); if (!classTemplate) { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Warning initial unpack of session %s failed : no related class found : %s",oName,cName); //xLogger::xLog(ELOGINFO,XL_START,"Warning Initial Unpack Update, no related class found : %s",cName); //xLogger::xLog(ELOGERROR,XL_SESSION,"Warning Initial Unpack Update, no related class found : %s",cName); classTemplate = netInterface->getDistributedClassInterface()->createClass(cName,type); } setDistributedClass(classTemplate); SetName(oName); setServerID(connection->getGhostIndex(this)); setObjectFlags(E_DO_CREATION_CREATED); setUserID(userID); setNetInterface(netInterface); setCreationTime(creationTime); setSessionID(sessionID); getOwnershipState().set( 1<<E_DO_OS_OWNER, getUserID() == ((vtConnection*)connection)->getUserID() ); setInterfaceFlags(E_DO_CREATED); getSessionFlags().set( 1 << E_SF_INCOMPLETE ); xLogger::xLog(ELOGTRACE,E_LI_SESSION,"Retrieved initial state of session %s",oName); initProperties(); setMaxUsers(MaxUsers); setPassword(xNString(pass)); vtConnection *con = (vtConnection*)connection; setOwnerConnection(con); } } int updateBits = stream->readSignedInt(32); TNL::BitSet32 updateBitsMask(updateBits); setGhostUpdateBits(updateBits); xDistributedPropertyArrayType &props = *getDistributedPorperties(); int propCounter = 0; for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (updateBitsMask.testStrict(1<<blockIndex)) { prop->updateFromServer(stream); xLogger::xLog(ELOGTRACE,E_LI_SESSION,"Client : retrieving session property : %s |pred :%d",prop->getPropertyInfo()->mName.getString(),prop->getPropertyInfo()->mPredictionType); //xLogger::xLog(ELOGINFO,XL_START,"client : retrieving session property : %s",prop->getPropertyInfo()->mName.getString()); getSessionFlags().set( 1 << E_SF_COMPLETE ); propCounter++; } } if (propCounter == props.size()) { getSessionFlags().set( 1 << E_SF_COMPLETE ); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::initProperties() { ////////////////////////////////////////////////////////////////////////// //we iterate through the dist classes properties and create a real //data holding dist prop in the object ! xLogger::xLog(ELOGTRACE,E_LI_SESSION,"Initiate properties of session : %s",this->GetName().getString()); if (getDistributedClass()) { xDistributedClass *_class = getDistributedClass(); xDistributedPropertiesListType &props = *_class->getDistributedProperties(); int userTypeCounter = 0; for (unsigned int i = 0 ; i < props.size() ; i ++ ) { xDistributedProperty *prop = NULL; xDistributedPropertyInfo *dInfo = props[i]; xLogger::xLog(ELOGTRACE,E_LI_SESSION,"\t attaching prop : %s | native type : %d | valueType : %d | prediction type : %d ",dInfo->mName.getString(),dInfo->mNativeType,dInfo->mValueType,dInfo->mPredictionType); //xLogger::xLogExtro(0,"\t attaching prop : %s | native type : %d | valueType : %d | prediction type : %d ",dInfo->mName.getString(),dInfo->mNativeType,dInfo->mValueType,dInfo->mPredictionType); switch(dInfo->mValueType) { case E_DC_PTYPE_3DVECTOR : { prop = new xDistributedPoint3F(dInfo,30,3000); getDistributedPorperties()->push_back(prop); break; } case E_DC_PTYPE_FLOAT: { prop = new xDistributedPoint1F(dInfo,30,3000); getDistributedPorperties()->push_back(prop); break; } case E_DC_PTYPE_2DVECTOR: { prop = new xDistributedPoint2F(dInfo,30,3000); getDistributedPorperties()->push_back(prop); break; } case E_DC_PTYPE_QUATERNION: { prop = new xDistributedQuatF(dInfo,30,3000); getDistributedPorperties()->push_back(prop); break; } case E_DC_PTYPE_STRING: { prop = new xDistributedString(dInfo,30,3000); getDistributedPorperties()->push_back(prop); break; } case E_DC_PTYPE_INT: { prop = new xDistributedInteger(dInfo,30,3000); getDistributedPorperties()->push_back(prop); break; } } if (dInfo->mNativeType == E_DC_S_NP_USER ) { int blockID = _class->getFirstUserField() + userTypeCounter; userTypeCounter++; prop->setBlockIndex(blockID); }else { prop->setBlockIndex(dInfo->mNativeType); } } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::prepare() { Parent::prepare(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::onGhostRemove() { xNetInterface *netInterface = getNetInterface(); if (getNetInterface()) { if(!getNetInterface()->IsServer()) { xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject *distObject = *begin; if (distObject) { xDistributedClass *_class = distObject->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT ) { xDistributedClient *distClient = static_cast<xDistributedClient*>(distObject); if (distClient && distClient->getSessionID() == getSessionID() ) { distClient->setSessionID(-1); disableFlag(distClient->getClientFlags(),E_CF_SESSION_JOINED); enableFlag(distClient->getClientFlags(),E_CF_DELETING); enableFlag(distClient->getClientFlags(),E_CF_SESSION_DESTROYED); } } } } begin++; } } if(getNetInterface()->IsServer()) { xLogger::xLog(XL_START,ELOGINFO,E_LI_SESSION,"Server : Session is going to be deleted : %s",this->GetName().getString()); } getNetInterface()->getDistObjectInterface()->removeObject(this); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedSession::onGhostAdd(TNL::GhostConnection *theConnection) { return Parent::onGhostAdd(theConnection); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::onGhostAvailable(TNL::GhostConnection *theConnection) { Parent::onGhostAvailable(theConnection); int conID = ((vtConnection*)theConnection)->getUserID(); //xLogger::xLog(ELOGINFO,XL_START, "session ghost available %d",conID); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (propInfo) { if (getUpdateBits().set(1<<blockIndex),true) { } setMaskBits(1<<blockIndex); } } xNetInterface *netInterface = (xNetInterface*) theConnection->getInterface(); if (netInterface->IsServer()) { setServerID(theConnection->getGhostIndex((TNL::NetObject*)this)); //xLogger::xLog(XL_START,ELOGINFO,E_LI_SESSION, "ServerID %d | Name : %s",getServerID(),GetName().getString()); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::performScopeQuery(TNL::GhostConnection *connection) { xNetInterface *netInterface = getNetInterface(); if (!netInterface) { return; } xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); if (!distObjects) { return; } xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin != end) { xDistributedObject*dobject = *begin; if (dobject) { connection->objectInScope((TNL::NetObject*) dobject ); } begin++; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedProperty*xDistributedSession::getProperty(int nativeType) { //return Parent::getProperty(nativeType); xDistributedProperty* result = NULL; if (getDistributedClass()) { xDistributedClass *_class = getDistributedClass(); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; if (prop->getPropertyInfo()->mNativeType == nativeType) { return prop; } } } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedProperty*xDistributedSession::getUserProperty(const char*name) { //return Parent::getUserProperty(name); xDistributedProperty* result = NULL; if (getDistributedClass()) { xDistributedClass *_class = getDistributedClass(); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; if (!strcmp(prop->getPropertyInfo()->mName.getString(),name)) { return prop; } } } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedSession::isClientJoined(int userID) { bool result = false; for (int i = 0 ; i < getClientTable().size() ; i ++) { xDistributedClient *client = getClientTable().at(i); if (client->getUserID() == userID) return true; } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::addUser(xDistributedClient *client) { if (client) { if (!isClientJoined(client->getUserID())) { getClientTable().push_back(client); xDistributedInteger *numUser= (xDistributedInteger *)getProperty(E_DC_S_NP_NUM_USERS); numUser->updateValue(getClientTable().size(),0); setNumUsers(getClientTable().size()); int blockIndex = numUser->getBlockIndex(); getUpdateBits().set(1<<blockIndex,true); setMaskBits(1<<blockIndex); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::removeUser(xDistributedClient *client) { xNetInterface *nInterface = getNetInterface(); if (!nInterface) { return; } xDistributedClient *myClient = nInterface->getMyClient(); if (client && myClient && client->getUserID() == myClient->getUserID()) { myClient->setSessionID(-1); } if (client) { if (isClientJoined(client->getUserID())) { ////////////////////////////////////////////////////////////////////////// if (client->getUserID() == getUserID()) { xLogger::xLog(XL_START,ELOGINFO,E_LI_SESSION,"Session master %d left session %d",client->getUserID(),getSessionID()); if (nInterface) { ////////////////////////////////////////////////////////////////////////// //we tag all existing users as new : IDistributedObjects *doInterface = nInterface->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = nInterface->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject *distObject = *begin; if (distObject) { xDistributedClass *_class = distObject->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT ) { xDistributedClient *distClient = static_cast<xDistributedClient*>(distObject); if (distClient && isClientJoined(distClient->getUserID())) { if (isFlagOn(distClient->getClientFlags(),E_CF_SESSION_JOINED)) { //distClient->setSessionID(-1); disableFlag(distClient->getClientFlags(),E_CF_SESSION_JOINED); enableFlag(distClient->getClientFlags(),E_CF_DELETING); enableFlag(distClient->getClientFlags(),E_CF_SESSION_DESTROYED); xLogger::xLogExtro(0,"\tRemoving user %d from session",distClient->getUserID(),getSessionID()); } } } } } begin++; } getClientTable().clear(); goto ENDUPDATE; return; } } } if (client->getUserID() != getUserID()) { enableFlag(client->getClientFlags(),E_CF_REMOVED); client->setSessionID(-1); } ////////////////////////////////////////////////////////////////////////// for(int i = 0 ; i < getClientTable().size() ; i++) { std::vector<xDistributedClient*>::iterator begin = getClientTable().begin(); std::vector<xDistributedClient*>::iterator end = getClientTable().end(); while (begin !=end) { xDistributedClient *current = *begin; if (current && current->getUserID() == client->getUserID() ) { getClientTable().erase(begin); } begin++; } } goto ENDUPDATE; ENDUPDATE : xDistributedInteger *numUser= (xDistributedInteger *)getProperty(E_DC_S_NP_NUM_USERS); numUser->updateValue(getClientTable().size(),0); setNumUsers(getClientTable().size()); int blockIndex = numUser->getBlockIndex(); getUpdateBits().set(1<<blockIndex,true); setMaskBits(1<<blockIndex); }else xLogger::xLog(XL_START,ELOGERROR,E_LI_SESSION,"couldn't find client object"); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xNString xDistributedSession::getPassword() { if (getProperty(E_DC_S_NP_PASSWORD)) { xDistributedString* passwordP= (xDistributedString*)getProperty(E_DC_S_NP_PASSWORD); if (passwordP) { return passwordP->mCurrentValue; } } return xNString(""); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSession::setPassword(xNString val) { if (getProperty(E_DC_S_NP_PASSWORD)) { xDistributedString* passwordP= static_cast<xDistributedString*>(getProperty(E_DC_S_NP_PASSWORD)); if (passwordP!=NULL) { passwordP->mCurrentValue = val; } } } void xDistributedSession::setNumUsers(int val) { if (getProperty(E_DC_S_NP_NUM_USERS)) { xDistributedInteger* value = (xDistributedInteger*)getProperty(E_DC_S_NP_NUM_USERS); if (value) { value->mLastServerValue = val; value->mCurrentValue = val; } } } void xDistributedSession::setMaxUsers(int val) { if (getProperty(E_DC_S_NP_MAX_USERS)) { xDistributedInteger* maxUsers = (xDistributedInteger*)getProperty(E_DC_S_NP_MAX_USERS); if (maxUsers) { maxUsers->mLastServerValue = val; maxUsers->mCurrentValue = val; } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedSession::isPrivate() { if (getProperty(E_DC_S_NP_PASSWORD)) { return true; } return false; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedSession::isLocked() { int locked = -1; if (getProperty(E_DC_S_NP_LOCKED)) { xDistributedInteger* isLocked = (xDistributedInteger*)getProperty(E_DC_S_NP_LOCKED); if (isLocked) { locked = isLocked->mLastServerValue; return locked; } } return locked; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributedSession::getNumUsers() { int numUsers = -1; if (getProperty(E_DC_S_NP_LOCKED)) { xDistributedInteger* num = (xDistributedInteger*)getProperty(E_DC_S_NP_NUM_USERS); if (num) { numUsers = num->mLastServerValue; //TNL::logprintf("numPS:%d | numPC:%d",num->mLastServerValue,num->mCurrentTime); return numUsers; } } return numUsers; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedSession::isFull() { return getNumUsers() >= getMaxUsers(); int maxplayers = -1; if (getProperty(E_DC_S_NP_MAX_USERS)) { xDistributedInteger* maxPlayersP = (xDistributedInteger*)getProperty(E_DC_S_NP_MAX_USERS); if (maxPlayersP) { maxplayers = maxPlayersP->mLastServerValue; return getNumUsers() < getMaxUsers(); } } return true; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributedSession::getMaxUsers() { int maxplayers = -1; if (getProperty(E_DC_S_NP_MAX_USERS)) { xDistributedInteger* maxPlayersP = (xDistributedInteger*)getProperty(E_DC_S_NP_MAX_USERS); if (maxPlayersP) { maxplayers = maxPlayersP->mCurrentValue; // TNL::logprintf("maxPS:%d | maxPC:%d",maxPlayersP->mLastServerValue,maxPlayersP->mCurrentTime); return maxplayers; } } return true; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" void PhysicManager::_RegisterParameterOperationsMisc() { CKParameterManager *pm = m_Context->GetParameterManager(); //pm->RegisterOperationType(PARAM_OP_TYPE_BGET_MATERIAL, "bMat"); //pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_MATERIAL,VTS_MATERIAL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBGetMaterial); }<file_sep>/******************************************************************** created: 2009/06/01 created: 1:6:2009 14:12 filename: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick\hasFFe.cpp file path: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick file base: hasFFe file ext: cpp author: <NAME> purpose: *********************************************************************/ #define STRICT #define DIRECTINPUT_VERSION 0x0800 #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } //#include <tchar.h> #include <windows.h> #include <commctrl.h> #include <basetsd.h> #include <commdlg.h> #include "dinput.h" #include "CKAll.h" //---------------------------------------------------------------- // // globals // LPDIRECTINPUT8 g_pDI2 = NULL; LPDIRECTINPUTDEVICE8 g_pFFDevice2 = NULL; #define HAS_CONFIG #ifdef HAS_CONFIG #include "gConfig.h" #endif // BB_TOOLS #ifdef BB_TOOLS #include <vtInterfaceEnumeration.h> #include "vtLogTools.h" #include "vtCBBErrorHelper.h" #include <virtools/vtBBHelper.h> #include <virtools/vtBBMacros.h> using namespace vtTools::BehaviorTools; #endif CKObjectDeclaration *FillBehaviorHasFFEffectsDecl(); CKERROR CreateHasFFEffectsProto(CKBehaviorPrototype **); int HasFFEffects(const CKBehaviorContext& behcontext); CKERROR PlayFFECallBackObject2(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorHasFFEffectsDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("JHasForceFeedback"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x12641a78,0x7ca70c45)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateHasFFEffectsProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Controllers/Joystick"); return od; } CKERROR CreateHasFFEffectsProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("JHasForceFeedback"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("yes"); proto->DeclareOutput("no"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( HasFFEffects ); *pproto = proto; return CK_OK; } BOOL CALLBACK EnumFFDevicesCallback0( LPCDIDEVICEINSTANCE pDDI, VOID* pvRef ) { if( FAILED( g_pDI2->CreateDevice( pDDI->guidInstance, &g_pFFDevice2, NULL ) ) ) return DIENUM_CONTINUE; // If failed, try again return DIENUM_STOP; } HRESULT FreeDirectInput0() { // Release any DirectInputEffect objects. if( g_pFFDevice2 ) { g_pFFDevice2->Unacquire(); SAFE_RELEASE( g_pFFDevice2 ); } // Release any DirectInput objects. SAFE_RELEASE( g_pDI2 ); return S_OK; } int HasFFEffects(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; HWND mWin = (HWND )ctx->GetMainWindow(); DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&g_pDI2, NULL ) ; // Get the first enumerated force feedback device g_pDI2->EnumDevices( 0, EnumFFDevicesCallback0, 0, DIEDFL_ATTACHEDONLY | DIEDFL_FORCEFEEDBACK ); if( g_pFFDevice2 == NULL ) beh->ActivateOutput(1); else beh->ActivateOutput(0); FreeDirectInput0(); return CKBR_OK; } <file_sep>/* * Tcp4u v 3.31 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: skt4u.h * Purpose: Internal header file. Lowest layer of the library * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #ifndef _SKT4U_LOADDED #define _SKT4U_LOADDED /* ****************************************************************** */ /* */ /* Etage 0 : Gestion des donnees internes */ /* */ /* ****************************************************************** */ #define STATE_LISTEN 12 #define STATE_CLIENT 13 #define STATE_SERVER 14 struct S_HistoSocket { SOCKET skt; int nState; long nRcv; long nSnd; HTASK hTask; } ; /* struct S_HistoSocket */ #define TCP4U_SUCCESS 1 /* >=1 function OK */ #define TCP4U_ERROR -1 /* error */ #define TCP4U_TIMEOUT -2 /* timeout has occured */ #define TCP4U_BUFFERFREED -3 /* the buffer has been freed */ #define TCP4U_HOSTUNKNOWN -4 /* connect to unknown host */ #define TCP4U_NOMORESOCKET -5 /* all socket has been used */ #define TCP4U_NOMORERESOURCE -5 /* or no more free resource */ #define TCP4U_CONNECTFAILED -6 /* connect function has failed*/ #define TCP4U_UNMATCHEDLENGTH -7 /* TcpPPRecv : Error in length*/ #define TCP4U_BINDERROR -8 /* bind failed (Task already started?) */ #define TCP4U_OVERFLOW -9 /* Overflow during TcpPPRecv */ #define TCP4U_EMPTYBUFFER -10 /* TcpPPRecv receives 0 byte */ #define TCP4U_CANCELLED -11 /* Call cancelled by signal */ #define TCP4U_INSMEMORY -12 /* Not enough memory */ #define TCP4U_SOCKETCLOSED 0 /* Host has closed connection */ /* ----------- Functions ---------- */ void Skt4uRcd (SOCKET sNewSkt, int nState); /* new socket created */ void Skt4uUnRcd (SOCKET sNewSkt); /* socket destroyed */ int Skt4uCleanup (void); /* clean internal tables */ int Skt4uInit (void); /* inits internal tables */ struct S_HistoSocket *Skt4uGetStats (SOCKET s); /* Get Histo data */ #endif /* _SKT4U_LOADDED */ <file_sep>//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by DistributedNetworkClassDialog.rc // #define IDC_SPLIT_MAIN 2012 #define IDD_EDITOR 10009 #define IDC_LIST1 10003 #define IDD_TOOLBAR 10001 #define IDI_EDITORICON 10002 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 10008 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 10007 #define _APS_NEXT_SYMED_VALUE 10006 #endif #endif <file_sep>#pragma once #include "PhysicManager.h" // vtAgeiaInterfaceEditorDlg.h : header file // //editor dialog creation function, to be called by Virtools Dev DllEditorDlg* fCreateEditorDlg(HWND parent); ///////////////////////////////////////////////////////////////////////////// // EditorDlg dialog class vtAgeiaInterfaceEditorDlg : public DllEditorDlg { public: //called on creation of the dialog by Virtools Dev interface //the PluginInterface will be avalaible only when the OnInterfaceInit() has been called virtual void OnInterfaceInit(); //called on destruction of the dialog by Virtools Dev interface virtual void OnInterfaceEnd(); //callback for receiving notification virtual HRESULT ReceiveNotification(UINT MsgID,DWORD Param1=0,DWORD Param2=0,CKScene* Context=NULL); int OnGlobalKeyboardShortcut(int commandID); int OnLocalKeyboardShortcut(int commandID); virtual void OnCustomMenu(CMenu* menu,int startingCommandID,int endingCommandID); //fill custom menu, use commandID= baseID+startingCommandID virtual void OnCustomMenu(int commandID); //callback when custom menu used, commandID==baseID (without the startingCommandID) //Create a CTooltipCtrl for tooltip management void CreateTooltip(); CKContext *mContext; PhysicManager *pMan; PhysicManager *getPMan(){return pMan;} CKContext *getContext(){return mContext;} void init(CKContext *ctx,PhysicManager *pm); void objectPosChanged(CK_ID objID); void objectSelChanged(DWORD par1,DWORD par2); virtual BOOL LoadData(CKInterfaceObjectManager* iom); virtual BOOL SaveData(CKInterfaceObjectManager* iom); protected: //tooltip CToolTipCtrl m_wndToolTip; // Construction public: vtAgeiaInterfaceEditorDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(vtAgeiaInterfaceEditorDlg) enum { IDD = IDD_EDITOR }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(vtAgeiaInterfaceEditorDlg) public: virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(vtAgeiaInterfaceEditorDlg) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. <file_sep>#ifndef __PCLOTHTYPES_H__ #define __PCLOTHTYPES_H__ #include "pClothFlags.h" /** \addtogroup Cloth @{ */ /** \brief Descriptor class for pCloth. */ class MODULE_API pClothDesc { public: /** \brief Thickness of the cloth. The thickness is usually a fraction of the overall extent of the cloth and should not be set to a value greater than that. A good value is the maximal distance between two adjacent cloth particles in their rest pose. Visual artifacts or collision problems may appear if the thickness is too small. <b>Default:</b> 0.01 <br> <b>Range:</b> [0,inf) @see pCloth.setThickness() */ float thickness; /** \brief Density of the cloth (mass per area). <b>Default:</b> 1.0 <br> <b>Range:</b> (0,inf) */ float density; /** \brief Bending stiffness of the cloth in the range 0 to 1. Only has an effect if the flag PCF_Bending is set. <b>Default:</b> 1.0 <br> <b>Range:</b> [0,1] @see PCF_Bending pCloth.setBendingStiffness() */ float bendingStiffness; /** \brief Stretching stiffness of the cloth in the range 0 to 1. Note: stretching stiffness must be larger than 0. <b>Default:</b> 1.0 <br> <b>Range:</b> (0,1] @see pCloth.setStretchingStiffness() */ float stretchingStiffness; /** \brief Spring damping of the cloth in the range 0 to 1. Only has an effect if the flag PCF_Damping is set. <b>Default:</b> 0.5 <br> <b>Range:</b> [0,1] @see PCF_Damping pCloth.setDampingCoefficient() */ float dampingCoefficient; /** \brief Friction coefficient in the range 0 to 1. Defines the damping of the velocities of cloth particles that are in contact. <b>Default:</b> 0.5 <br> <b>Range:</b> [0,1] @see pCloth.setFriction() */ float friction; /** \brief If the flag PCF_Pressure is set, this variable defines the volume of air inside the mesh as volume = pressure * restVolume. For pressure < 1 the mesh contracts w.r.t. the rest shape For pressure > 1 the mesh expands w.r.t. the rest shape <b>Default:</b> 1.0 <br> <b>Range:</b> [0,inf) @see PCF_pressure pCloth.setPressure() */ float pressure; /** \brief If the flag PCF_Tearable is set, this variable defines the elongation factor that causes the cloth to tear. Must be larger than 1. Make sure meshData.maxVertices and the corresponding buffers in meshData are substantially larger (e.g. 2x) than the number of original vertices since tearing will generate new vertices. When the buffer cannot hold the new vertices anymore, tearing stops. <b>Default:</b> 1.5 <br> <b>Range:</b> (1,inf) @see pCloth.setTearFactor() */ float tearFactor; /** \brief Defines a factor for the impulse transfer from cloth to colliding rigid bodies. Only has an effect if PCF_CollisionTwoWay is set. <b>Default:</b> 0.2 <br> <b>Range:</b> [0,inf) @see PCF_CollisionTwoWay pCloth.setCollisionResponseCoefficient() */ float collisionResponseCoefficient; /** \brief Defines a factor for the impulse transfer from cloth to attached rigid bodies. Only has an effect if the mode of the attachment is set to nx_cloth_attachment_twoway. <b>Default:</b> 0.2 <br> <b>Range:</b> [0,1] @see pCloth.attachToShape pCloth.attachToCollidingShapes pCloth.attachVertexToShape pCloth.setAttachmentResponseCoefficient() */ float attachmentResponseCoefficient; /** \brief If the flag nx_cloth_attachment_tearable is set in the attachment method of pCloth, this variable defines the elongation factor that causes the attachment to tear. Must be larger than 1. <b>Default:</b> 1.5 <br> <b>Range:</b> (1,inf) @see pCloth.setAttachmentTearFactor() pCloth.attachToShape pCloth.attachToCollidingShapes pCloth.attachVertexToShape */ float attachmentTearFactor; /** \brief Defines a factor for the impulse transfer from this cloth to colliding fluids. Only has an effect if the PCF_FluidCollision flag is set. <b>Default:</b> 1.0 <br> <b>Range:</b> [0,inf) Note: Large values can cause instabilities @see pClothDesc.flags pClothDesc.fromFluidResponseCoefficient */ float toFluidResponseCoefficient; /** \brief Defines a factor for the impulse transfer from colliding fluids to this cloth. Only has an effect if the PCF_FluidCollision flag is set. <b>Default:</b> 1.0 <br> <b>Range:</b> [0,inf) Note: Large values can cause instabilities @see pClothDesc.flags pClothDesc.ToFluidResponseCoefficient */ float fromFluidResponseCoefficient; /** \brief If the PCF_Adhere flag is set the cloth moves partially in the frame of the attached actor. This feature is useful when the cloth is attached to a fast moving character. In that case the cloth adheres to the shape it is attached to while only velocities below the parameter minAdhereVelocity are used for secondary effects. <b>Default:</b> 1.0 <b>Range:</b> [0,inf) @see PCF_ADHERE */ float minAdhereVelocity; /** \brief Number of solver iterations. Note: Small numbers make the simulation faster while the cloth gets less stiff. <b>Default:</b> 5 <b>Range:</b> [1,inf) @see pCloth.setSolverIterations() */ unsigned int solverIterations; /** \brief External acceleration which affects all non attached particles of the cloth. <b>Default:</b> (0,0,0) @see pCloth.setExternalAcceleration() */ VxVector externalAcceleration; /** \brief Acceleration which acts normal to the cloth surface at each vertex. <b>Default:</b> (0,0,0) @see pCloth.setWindAcceleration() */ VxVector windAcceleration; /** \brief The cloth wake up counter. <b>Range:</b> [0,inf)<br> <b>Default:</b> 20.0f*0.02f @see pCloth.wakeUp() pCloth.putToSleep() */ float wakeUpCounter; /** \brief Maximum linear velocity at which cloth can go to sleep. If negative, the global default will be used. <b>Range:</b> [0,inf)<br> <b>Default:</b> -1.0 @see pCloth.setSleepLinearVelocity() pCloth.getSleepLinearVelocity() */ float sleepLinearVelocity; /** \brief Sets which collision group this cloth is part of. <b>Range:</b> [0, 31] <b>Default:</b> 0 pCloth.setCollisionGroup() */ xU16 collisionGroup; /** \brief Sets the 128-bit mask used for collision filtering. <b>Default:</b> 0 @see NxGroupsMask pCloth.setGroupsMask() pCloth.getGroupsMask() */ pGroupsMask groupsMask; /** \brief Force Field Material Index, index != 0 has to be created. <b>Default:</b> 0 */ xU16 forceFieldMaterial; /** \brief If the flag PCF_ValidBounds is set, this variable defines the volume outside of which cloth particle are automatically removed from the simulation. @see PCF_ValidBounds pCloth.setValidBounds() */ VxBbox validBounds; /** \brief This parameter defines the size of grid cells for collision detection. The cloth is represented by a set of world aligned cubical cells in broad phase. The size of these cells is determined by multiplying the length of the diagonal of the AABB of the initial cloth size with this constant. <b>Range:</b> [0.01,inf)<br> <b>Default:</b> 0.25 */ float relativeGridSpacing; /** \brief Flag bits. <b>Default:</b> PCF_GRAVITY @see NxClothFlag pCloth.setFlags() */ unsigned int flags; /** \brief Possible debug name. The string is not copied by the SDK, only the pointer is stored. <b>Default:</b> NULL @see pCloth.setName() pCloth.getName() */ const char* name; /** \brief Vertex color to identify vertieces as tearable. <b>Default:</b> 255,255,254 */ VxColor tearVertexColor; /** \brief Reference object to identify the world. <b>Default:</b> pDefaultWorld */ CK_ID worldReference; /** \brief Attachment flags. <b>Default:</b> PCAF_ClothAttachmentTwoway @see #pClothAttachmentFlag */ pClothAttachmentFlag attachmentFlags; /** \brief Constructor sets to default. */ pClothDesc(); /** \brief (Re)sets the structure to the default. */ void setToDefault(); /** \brief Returns true if the current settings are valid */ bool isValid() const; }; /** @} */ #endif // __PCLOTHTYPES_H__<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" CKObjectDeclaration *FillBehaviorDOUserValueModifiedDecl(); CKERROR CreateDOUserValueModifiedProto(CKBehaviorPrototype **); int DOUserValueModified(const CKBehaviorContext& behcontext); CKERROR DOUserValueModifiedCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorDOUserValueModifiedDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DOUserValueModified"); od->SetDescription("Gets a user value on a distributed object"); od->SetCategory("TNL/Distributed Objects"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x349c10e0,0x7982264c)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDOUserValueModifiedProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateDOUserValueModifiedProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("DOUserValueModified"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Off"); proto->DeclareInput("Next Value"); proto->DeclareOutput("Exit In"); proto->DeclareOutput("Exit Off"); proto->DeclareOutput("New Value"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Object", CKPGUID_BEOBJECT, "test"); proto->DeclareOutParameter("Time", CKPGUID_TIME, "0"); proto->DeclareOutParameter("Value", CKPGUID_STRING, "No Error"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareSetting("Class", CKPGUID_STRING, "My3DClass"); proto->DeclareSetting("Parameter Name", CKPGUID_STRING, "test"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(DOUserValueModified); proto->SetBehaviorCallbackFct(DOUserValueModifiedCB); *pproto = proto; return CK_OK; } int DOUserValueModified(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; ////////////////////////////////////////////////////////////////////////// //connection id : int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); if (beh->IsInputActive(1)) { beh->ActivateInput(1,FALSE); beh->ActivateOutput(1); return 0; } ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *obj= (CK3dEntity*)beh->GetInputParameterObject(1); if (!obj) { beh->ActivateOutput(3); return CKBR_ACTIVATENEXTFRAME; } ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { CKParameterOut *pout = beh->GetOutputParameter(2); XString errorMesg("distributed object creation failed,no network connection !"); pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(3); return CKBR_ACTIVATENEXTFRAME; } //use objects name, if not specified : CKSTRING name= obj->GetName(); IDistributedObjects*doInterface = cin->getDistObjectInterface(); IDistributedClasses*cInterface = cin->getDistributedClassInterface(); XString className((CKSTRING) beh->GetLocalParameterReadDataPtr(0)); XString parameterName((CKSTRING) beh->GetLocalParameterReadDataPtr(1)); xDistributedClass *_class = cInterface->get(className.CStr()); ////////////////////////////////////////////////////////////////////////// //dist class ok ? if (_class==NULL) { beh->ActivateOutput(3); ctx->OutputToConsoleEx("Distributed Class doesn't exists : %s",className.CStr()); return CKBR_ACTIVATENEXTFRAME; } const char * cNAme = _class->getClassName().getString(); int classType = _class->getEnitityType(); int bcount = beh->GetInputParameterCount(); ////////////////////////////////////////////////////////////////////////// //we come in by input 0 : xDistributedObject *dobjDummy = NULL; xDistributedObject *dobj = doInterface->getByEntityID(obj->GetID()); if (!dobj) { beh->ActivateOutput(3); return CKBR_ACTIVATENEXTFRAME; } if (dobj) { xDistributedProperty * prop = dobj->getUserProperty(parameterName.CStr()); if (prop) { if ( dobj->getGhostUpdateBits().testStrict(1 << prop->getBlockIndex())) { CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); CKParameterOut *ciIn = beh->GetOutputParameter(1); CKParameterType pType = ciIn->GetType(); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); int userType = xDistTools::ValueTypeToSuperType(prop->getPropertyInfo()->mValueType); if ( userType ==sType ) { beh->ActivateOutput(2); dobj->getGhostUpdateBits().set(1 << prop->getBlockIndex(),false); switch(xDistTools::ValueTypeToSuperType(prop->getPropertyInfo()->mValueType)) { case vtFLOAT: { xDistributedPoint1F *propValue = static_cast<xDistributedPoint1F*>(prop); if (propValue) { float ovalue = propValue->mLastServerValue; beh->SetOutputParameterValue(1,&ovalue); break; } } case vtVECTOR2D: { xDistributedPoint2F *propValue = static_cast<xDistributedPoint2F*>(prop); if (propValue) { Point2F ovalue = propValue->mLastServerValue; Vx2DVector ovaluex(ovalue.x,ovalue.y); beh->SetOutputParameterValue(1,&ovaluex); break; } } case vtVECTOR: { xDistributedPoint3F *propValue = static_cast<xDistributedPoint3F*>(prop); if (propValue) { Point3F ovalue = propValue->mLastServerValue; VxVector ovaluex(ovalue.x,ovalue.y,ovalue.z); beh->SetOutputParameterValue(1,&ovaluex); break; } } case vtQUATERNION: { xDistributedQuatF*propValue = static_cast<xDistributedQuatF*>(prop); if (propValue) { QuatF ovalue = propValue->mLastServerValue; VxQuaternion ovaluex(ovalue.x,ovalue.y,ovalue.z,ovalue.w); beh->SetOutputParameterValue(1,&ovaluex); break; } } case vtSTRING: { xDistributedString*propValue = static_cast<xDistributedString*>(prop); if (propValue) { TNL::StringPtr ovalue = propValue->mCurrentValue; CKParameterOut *pout = beh->GetOutputParameter(1); XString errorMesg(ovalue.getString()); pout->SetStringValue(errorMesg.Str()); break; } } case vtINTEGER: { xDistributedInteger*propValue = static_cast<xDistributedInteger*>(prop); if (propValue) { int ovalue = propValue->mLastServerValue; beh->SetOutputParameterValue(1,&ovalue); break; } } } } } } } return CKBR_ACTIVATENEXTFRAME; if (beh->IsInputActive(0)) { beh->ActivateOutput(0); } /* ////////////////////////////////////////////////////////////////////////// //we come in by input 0 : if (beh->IsInputActive(0)) { beh->ActivateOutput(0); for (int i = BEH_IN_INDEX_MIN_COUNT ; i < beh->GetInputParameterCount() ; i++ ) { beh->ActivateInput(0,FALSE); xDistributedObject *dobj = doInterface->get(name); if (!dobj) { beh->ActivateOutput(0); return 0; } CKParameterIn *ciIn = beh->GetInputParameter(i); CKParameterType pType = ciIn->GetType(); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); xDistributedPropertyArrayType &props = *dobj->getDistributedPorperties(); int propID = _class->getInternalUserFieldIndex(i - BEH_IN_INDEX_MIN_COUNT); if (propID==-1 || propID > props.size() ) { beh->ActivateOutput(1); return 0; } xDistributedProperty *prop = props[propID]; if (prop) { xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); if (propInfo) { if (xDistTools::ValueTypeToSuperType(propInfo->mValueType) ==sType ) { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); switch(propInfo->mValueType) { case E_DC_PTYPE_3DVECTOR: { xDistributedPoint3F * dpoint3F = (xDistributedPoint3F*)prop; if (dpoint3F) { VxVector vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(xMath::getFrom(vvalue),currentTime); } break; } case E_DC_PTYPE_FLOAT: { xDistributedPoint1F * dpoint3F = (xDistributedPoint1F*)prop; if (dpoint3F) { float vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(vvalue,currentTime); } break; } } } } } } beh->ActivateOutput(0); } */ ////////////////////////////////////////////////////////////////////////// //we come in by loop : return 0; } CKERROR DOUserValueModifiedCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>/******************************************************************** created: 2007/12/12 created: 12:12:2007 11:54 filename: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude\vtCXPrecomp.h file path: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude file base: vtCXPrecomp file ext: h author: mc007 purpose: *********************************************************************/ #ifndef __VTX_PRECOMP_H #define __VTX_PRECOMP_H #include "VxMath.h" #include "CKAll.h" #undef min #undef max #endif <file_sep>#ifndef __vtNetAll_h_ #define __vtNetAll_h_ #include "xNetworkTypes.h" //#include "vtNetEnums.h" #include "xNetObject.h" //#include "vtNetworkManager.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "xDistributedObject.h" #include "xDistributedClient.h" #include "xDistributed3DObject.h" #include "IDistributedObjectsInterface.h" #include "IDistributedClasses.h" #include "IMessages.h" #include "xPredictionSetting.h" //#include <xMathTools.h> #endif <file_sep>#include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xDistributedClient.h" #include "xLogger.h" TNL_IMPLEMENT_NETOBJECT(xDistributed3DObject); uxString xDistributed3DObject::print(TNL::BitSet32 flags) { return Parent::print(flags); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::pack(TNL::BitStream *bstream) { //writes update bits : ! Parent::pack(bstream); int updateBites = getUpdateBits().getMask(); int packCounter = 0 ; xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); if (propInfo) { int blockIndex = prop->getBlockIndex(); int blockIndexF = BIT(blockIndex); int blockIndexF2 = 1 << blockIndex; if (prop->getFlags() & E_DP_NEEDS_SEND) { prop->pack(bstream); packCounter++; //xLogger::xLog(ELOGINFO,XL_START,"packing byflag"); } if (getUpdateBits().test( 1 << (prop->getBlockIndex()))) { } } } //xLogger::xLog(ELOGINFO,XL_START,"packing %d props with mask ",packCounter,getUpdateBits().getMask() ); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::unpack( TNL::BitStream *bstream,float sendersOneWayTime ) { Parent::unpack(bstream,sendersOneWayTime); int updateBites = getUpdateBits().getMask(); int unpackCounter = 0 ; xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (propInfo) { if (getUpdateBits().testStrict(1<<blockIndex)) { prop->unpack(bstream,sendersOneWayTime); unpackCounter++; //xLogger::xLog(ELOGINFO,XL_START,"\t unpacking prop:%s",propInfo->mName.getString()); setMaskBits(1<<blockIndex); } } } //xLogger::xLog(ELOGINFO,XL_START,"\t unpacking %d props with mask %d",unpackCounter,getUpdateBits().getMask() ); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL::U32 xDistributed3DObject::packUpdate(TNL::GhostConnection *connection, TNL::U32 updateMask, TNL::BitStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); if (netInterface) { //the first time ? : we write out all necessary attributes for the client : if(stream->writeFlag(updateMask & InitialMask)) { if(stream->writeFlag(true)) { //write out name : stream->writeString(GetName().getString(),strlen(GetName().getString())); //retrieve its class : xDistributedClass *distClass = getDistributedClass(); if (distClass) { //write out the class name : stream->writeString(distClass->getClassName().getString(),strlen(distClass->getClassName().getString())); //write out the class base type : stream->writeInt(distClass->getEnitityType(),32); //write out users id : vtConnection *con = (vtConnection*)connection; int uid = getUserID(); stream->writeInt(getUserID(),32); //write out server side id : int serverID = connection->getGhostIndex(this); stream->writeInt(connection->getGhostIndex(this),32); setServerID(connection->getGhostIndex(this)); float time = getCreationTime(); //write out creation time stream->write(getCreationTime()); //xLogger::xLog(ELOGINFO,XL_START,"server:init pack update : %f , %d , ",time,uid); xLogger::xLog(XL_START,ELOGTRACE,E_LI_3DOBJECT,"initial pack!"); } setNetInterface(netInterface); } } /************************************************************************/ /* */ /************************************************************************/ stream->writeSignedInt(getUpdateBits().getMask(),32); int unpackCounter = 0 ; xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (propInfo) { if (getUpdateBits().testStrict(1<<blockIndex)) { prop->updateGhostValue(stream); //xLogger::xLog(ELOGINFO,XL_START,"server is updating ghosts %d",blockIndex); } } } } return 0; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::unpackUpdate(TNL::GhostConnection *connection, TNL::BitStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); if (netInterface) { ////////////////////////////////////////////////////////////////////////// //initial update ? if(stream->readFlag()) { if(stream->readFlag()) { char oName[256];stream->readString(oName); // retrieve objects name : char cName[256];stream->readString(cName); // retrieve objects dist class name : int type = stream->readInt(32); //read the dist class base type : int userID = stream->readInt(32); int serverID2 = stream->readInt(32); float creationTime = 0.0f; stream->read(&creationTime); ////////////////////////////////////////////////////////////////////////// //now we store all in the dist object : //find and store the dist class : xDistributedClassesArrayType *_classes = netInterface->getDistributedClassInterface()->getDistrutedClassesPtr(); xDistributedClass *classTemplate = netInterface->getDistributedClassInterface()->get(cName); if (!classTemplate) { classTemplate = netInterface->getDistributedClassInterface()->createClass(cName,type); xLogger::xLog(XL_START,ELOGERROR,E_LI_3DOBJECT,"No class found %s",oName); } setDistributedClass(classTemplate); SetName(oName); setServerID(connection->getGhostIndex(this)); setObjectFlags(E_DO_CREATION_CREATED); setUserID(userID); getOwnershipState().set( 1<<E_DO_OS_OWNER, getUserID() == ((vtConnection*)connection)->getUserID() ); setNetInterface(netInterface); setCreationTime(creationTime); setInterfaceFlags(E_DO_CREATED); initProperties(); setSessionID((netInterface->getMyClient()->getSessionID())); enableFlag(getObjectStateFlags(),E_DOSF_UNPACKED); xLogger::xLog(XL_START,ELOGTRACE,E_LI_3DOBJECT,"Retrieved initial state %s | sessionID:%d",oName,netInterface->getMyClient()->getSessionID()); } } int updateBits = stream->readSignedInt(32); TNL::BitSet32 updateBitsMask(updateBits); setGhostUpdateBits(updateBits); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (updateBitsMask.testStrict(1<<blockIndex)) { prop->updateFromServer(stream); } } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::destroy() { Parent::destroy(); m_DistributedClass=NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributed3DObject::xDistributed3DObject() : xDistributedObject() { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributed3DObject::~xDistributed3DObject() { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::performScopeQuery(TNL::GhostConnection *connection) { xNetInterface *netInterface = getNetInterface(); if (!netInterface) { return; } xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); if (!distObjects) { return; } xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin != end) { xDistributedObject*dobject = *begin; if (dobject) { //if (getSessionID() == dobject->getSessionID()) { connection->objectInScope((TNL::NetObject*) dobject ); } } begin++; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::doInitUpdate() { xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (propInfo) { prop->setFlags(E_DP_NEEDS_SEND ); } } setUpdateState(E_DO_US_PENDING); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::updateAll() { xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (propInfo) { setMaskBits(1<<blockIndex); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::onGhostAvailable(TNL::GhostConnection *theConnection) { xNetInterface *netInterface = (xNetInterface*) theConnection->getInterface(); vtConnection *con = (vtConnection*)theConnection; xDistributedClient *client = (xDistributedClient*)netInterface->getDistObjectInterface()->getByUserID(con->getUserID(),E_DC_BTYPE_CLIENT); if (netInterface) { if (netInterface->IsServer()) { IDistributedObjects *distInterface = netInterface->getDistObjectInterface(); if (distInterface) { setServerID(theConnection->getGhostIndex(this)); setSessionID(client->getSessionID()); //doInitUpdate(); } } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributed3DObject::onGhostAdd(TNL::GhostConnection *theConnection) { xNetInterface *netInterface = (xNetInterface*) theConnection->getInterface(); if (netInterface) { if (!netInterface->IsServer()) { xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); distObjects->push_back(this); setNetInterface(netInterface); } } return true; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::initProperties() { ////////////////////////////////////////////////////////////////////////// //we iterate through the dist classes properties and create a real //data holding dist prop in the object ! //xLogger::xLog(ELOGINFO,XL_START,"init props of dist object : %s",this->GetName().getString()); if (getDistributedClass()) { xDistributedClass *_class = getDistributedClass(); xDistributedPropertiesListType &props = *_class->getDistributedProperties(); int userTypeCounter = 0; for (unsigned int i = 0 ; i < props.size() ; i ++ ) { xDistributedProperty *prop = NULL; xDistributedPropertyInfo *dInfo = props[i]; xLogger::xLog(XL_START,ELOGTRACE,E_LI_3DOBJECT,"\t attaching prop : %s | native type : %d",dInfo->mName.getString(),dInfo->mNativeType); switch(dInfo->mValueType) { case E_DC_PTYPE_3DVECTOR : { prop = new xDistributedPoint3F(dInfo,30,3000); getDistributedPorperties()->push_back(prop); //xLogger::xLog(ELOGINFO,XL_START,"\t attaching prop : %s | native type : %d",dInfo->mName.getString(),dInfo->mNativeType); } break; case E_DC_PTYPE_FLOAT: { prop = new xDistributedPoint1F(dInfo,30,3000); getDistributedPorperties()->push_back(prop); //xLogger::xLog(ELOGINFO,XL_START,"\t attaching prop : %s | native type : %d",dInfo->mName.getString(),dInfo->mNativeType); break; } case E_DC_PTYPE_2DVECTOR: { prop = new xDistributedPoint2F(dInfo,30,3000); getDistributedPorperties()->push_back(prop); //xLogger::xLog(ELOGINFO,XL_START,"\t attaching prop : %s | native type : %d",dInfo->mName.getString(),dInfo->mNativeType); break; } case E_DC_PTYPE_QUATERNION: { prop = new xDistributedQuatF(dInfo,30,3000); getDistributedPorperties()->push_back(prop); //xLogger::xLog(ELOGINFO,XL_START,"\t attaching prop : %s | native type : %d",dInfo->mName.getString(),dInfo->mNativeType); break; } case E_DC_PTYPE_STRING: { prop = new xDistributedString(dInfo,30,3000); getDistributedPorperties()->push_back(prop); //xLogger::xLog(ELOGINFO,XL_START,"\t attaching prop : %s | native type : %d",dInfo->mName.getString(),dInfo->mNativeType); break; } case E_DC_PTYPE_INT: { prop = new xDistributedInteger(dInfo,30,3000); getDistributedPorperties()->push_back(prop); //xLogger::xLog(ELOGINFO,XL_START,"\t attaching prop : %s | native type : %d",dInfo->mName.getString(),dInfo->mNativeType); break; } } if (dInfo->mNativeType == E_DC_3D_NP_USER ) { int blockID = _class->getFirstUserField() + userTypeCounter; userTypeCounter++; prop->setBlockIndex(blockID); }else { prop->setBlockIndex(dInfo->mNativeType); } } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedProperty* xDistributed3DObject::getProperty(int nativeType) { //return Parent::getProperty(nativeType); xDistributedProperty* result = NULL; if (getDistributedClass()) { xDistributedClass *_class = getDistributedClass(); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; if (prop->getPropertyInfo()->mNativeType == nativeType) { return prop; } } } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedProperty* xDistributed3DObject::getUserProperty(const char*name) { //return Parent::getUserProperty(name); xDistributedProperty* result = NULL; if (getDistributedClass()) { xDistributedClass *_class = getDistributedClass(); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; if (!strcmp(prop->getPropertyInfo()->mName.getString(),name)) { return prop; } } } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::update(float time) { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributed3DObject::prepare() { Parent::prepare(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_NETOBJECT_RPC(xDistributed3DObject,c2sGetOwnerShip, (TNL::U32 userSrcID),(userSrcID), TNL::NetClassGroupGameMask, TNL::RPCGuaranteedOrdered,TNL::RPCToGhostParent, 0) { //setMaskBits(PositionMask); } void xDistributed3DObject::onGhostRemove() { if (getNetInterface()) { if(!getNetInterface()->IsServer()) { getNetInterface()->addDeleteObject(this); } xLogger::xLog(XL_START,ELOGTRACE,E_LI_3DOBJECT,"removing..."); getNetInterface()->getDistObjectInterface()->removeObject(this); } } <file_sep>#include "pch.h" #include "GProfile.h" #include "GException.h" #include "DirectoryListing.h" #include <string.h> //for: memcpy() #ifndef _WIN32 #include <errno.h> #endif #ifdef _WIN32 #include <Windows.h> #endif static GProfile *g_AlternateProfile = 0; GProfile *SetProfile(GProfile *pApplicationProfile) { GProfile *pReturn = g_AlternateProfile; g_AlternateProfile = pApplicationProfile; return pReturn; } GProfile &GetProfile() { static GProfile *s_pDefaultProfile = 0; if (g_AlternateProfile) return *g_AlternateProfile; if (!s_pDefaultProfile) s_pDefaultProfile = new GProfile ("txml.txt","XML_CONFIG_FILE"); return *s_pDefaultProfile; } GProfile::GProfile(const char *pzFileName, const char *pzEnvOverride ) : m_bCached(0) { m_strEnvOverride = pzEnvOverride; m_strBaseFileName = pzFileName; // no path GString strConfigFileDefault; #ifdef _WIN32 // like "txml.txt" strConfigFileDefault.Format("c:\\%s",pzFileName); #else strConfigFileDefault.Format("/%s",pzFileName); #endif // env var like "XML_CONFIG_FILE" if (getenv(pzEnvOverride)) // Use the system environment setting m_strFile = getenv(pzEnvOverride); else // Use the default m_strFile = strConfigFileDefault; } // // load the profile configuration file yourself, // and create this object "with no disk config file" GProfile::GProfile(const char *szBuffer, long dwSize) { ProfileParse(szBuffer, dwSize); } // create a profile from the supplied file name GProfile::GProfile(const char *pzFilePathAndName ) : m_bCached(0) { m_strEnvOverride = "NONE"; m_strBaseFileName = CDirectoryListing::LastLeaf(pzFilePathAndName); //"txml.txt"; if (pzFilePathAndName && pzFilePathAndName[0]) // use the supplied pzFilePathAndName m_strFile = pzFilePathAndName; } GProfile::~GProfile() { Destroy(); } void GProfile::Destroy() { GListIterator itSections(&m_lstSections); while (itSections()) { Section *pSection = (Section *)itSections++; GListIterator itNVP(&pSection->m_lstNVP); while (itNVP()) { NameValuePair *pNVP = (NameValuePair *)itNVP++; delete pNVP; } delete pSection; } m_lstSections.RemoveAll(); } #ifdef _WIN32 void GProfile::ThrowLastError(const char *pzFile) { LPVOID lpMsgBuf; DWORD dwExp = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwExp, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); GString strTemp = (char *)lpMsgBuf; strTemp.TrimRightWS(); GString strFile; strFile.Format("%s - %s", (const char *)strTemp,pzFile); GenericException exp(dwExp,(const char *)strFile); LocalFree( lpMsgBuf ); throw exp; } #endif void GProfile::GetLine(GString &strLine, const char *szBuffer, int *nIdx, int dwSize) { strLine.Empty(); while (*nIdx < dwSize) { if (szBuffer[*nIdx] == '\n') break; strLine += szBuffer[*nIdx]; (*nIdx)++; } (*nIdx)++; } void GProfile::ProfileParse(const char *szBuffer, long dwSize) { Section *pSection = 0; // parse the file int nIdx = 0; while (nIdx < dwSize) { GString strLine; GetLine(strLine, szBuffer, &nIdx, dwSize); strLine.TrimRightWS(); strLine.TrimLeftWS(); if ((strLine.IsEmpty()) || (strLine[0] == ';')) continue; strLine.Replace("\\n", '\n'); if (strLine[0] == '[') { int nIdx = strLine.Find(']'); if (nIdx == -1) nIdx = strLine.Length(); // new section pSection = new Section; pSection->m_strName = strLine.Mid(1, nIdx - 1); pSection->m_strName.TrimLeftWS(); pSection->m_strName.TrimRightWS(); m_lstSections.AddLast(pSection); } else if (pSection) { int nIdx = strLine.Find('='); if (nIdx == -1) continue; NameValuePair *pNVP = new NameValuePair; pSection->m_lstNVP.AddLast(pNVP); pNVP->m_strName = strLine.Left(nIdx); pNVP->m_strName.TrimLeftWS(); pNVP->m_strName.TrimRightWS(); pNVP->m_strValue = strLine.Mid(nIdx + 1); pNVP->m_strValue.TrimLeftWS(); pNVP->m_strValue.TrimRightWS(); } } m_bCached = true; } void GProfile::Load() { if (m_bCached) return; // destroy the cached objects Destroy(); char *szBuffer = 0; long dwSize = 0; #ifdef _WIN32 // open the file HANDLE hFile = CreateFile((const char *)m_strFile, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); dwSize = GetFileSize(hFile, NULL); szBuffer = new char[dwSize + 1]; // read the file long dwRead; if (!ReadFile(hFile, szBuffer, dwSize, (DWORD *)&dwRead, 0)) { delete [] szBuffer; CloseHandle(hFile); } // close the file CloseHandle(hFile); #else // open the file GString strTemp; int nResult = strTemp.FromFile((const char *)m_strFile, 0); szBuffer = new char[strTemp.Length() + 1]; memcpy(szBuffer,(const char *)strTemp, strTemp.Length()); dwSize = strTemp.Length(); #endif // terminate the buffer //szBuffer[dwSize] = 0; ProfileParse(szBuffer, dwSize); delete [] szBuffer; } GProfile::Section *GProfile::FindSection(const char *szSection) { Load(); Section *pRet = 0; GListIterator itSections(&m_lstSections); while ( itSections() && (!pRet)) { Section *pSection = (Section *)itSections++; if (pSection->m_strName.CompareNoCase(szSection) == 0) pRet = pSection; } return pRet; } GProfile::NameValuePair *GProfile::FindKey(const char *szKey, GProfile::Section *pSection) { NameValuePair *pRet = 0; if (pSection) { GListIterator itNVP(&pSection->m_lstNVP); while ((itNVP()) && (!pRet)) { NameValuePair *pNVP = (NameValuePair *)itNVP++; if (pNVP->m_strName.CompareNoCase(szKey) == 0) pRet = pNVP; } } return pRet; } // function retrieves the names of all sections void GProfile::GetSectionNames(GStringList *lpList) { Load(); if (lpList) { GListIterator itSections(&m_lstSections); while (itSections()) { Section *pSection = (Section *)itSections++; lpList->AddLast(pSection->m_strName); } } } const GList *GProfile::GetSection(const char *szSectionName) { Section *pSection = FindSection(szSectionName); if (pSection) return &pSection->m_lstNVP; return 0; } // written by sean, not sure what this is about... static bool IsTrue(char chValue) { bool bRet; if (chValue > '1') bRet = ((chValue & 0x10) != 0); else bRet = ((chValue & 0x01) != 0); return bRet; } // function retrieves a boolean from the specified section short GProfile::GetBool(const char *szSectionName, const char *szKey, short bThrowNotFound /* = true */) { Section *pSection = FindSection(szSectionName); if (pSection) { NameValuePair *pNVP = FindKey(szKey, pSection); if (pNVP) { char chTest = '0'; if (!pNVP->m_strValue.IsEmpty()) chTest = pNVP->m_strValue[0]; return IsTrue(chTest); } else if (bThrowNotFound) { // throw key not found } } else if (bThrowNotFound) { } return 0; } // function retrieves a boolean from the specified section short GProfile::GetBoolean(const char *szSectionName, const char *szKey, short bThrowNotFound /* = true */) { Section *pSection = FindSection(szSectionName); if (pSection) { NameValuePair *pNVP = FindKey(szKey, pSection); if (pNVP) { if (pNVP->m_strValue.CompareNoCase("true") == 0 || pNVP->m_strValue.CompareNoCase("on") == 0 || pNVP->m_strValue.CompareNoCase("yes") == 0 || pNVP->m_strValue.CompareNoCase("1") == 0) { return 1; } else { return 0; } } else if (bThrowNotFound) { } } else if (bThrowNotFound) { // throw key not found } return 0; } // function retrieves a long from the specified section long GProfile::GetLong(const char *szSectionName, const char *szKey, short bThrowNotFound /* = true */) { Section *pSection = FindSection(szSectionName); if (pSection) { NameValuePair *pNVP = FindKey(szKey, pSection); if (pNVP) { if (!pNVP->m_strValue.IsEmpty()) return atol((const char *)pNVP->m_strValue); } else if (bThrowNotFound) { // throw key not found } } else if (bThrowNotFound) { // throw key not found } return 0; } const char *GProfile::GetPath(const char *szSectionName, const char *szKey, short bThrowNotFound) { Section *pSection = FindSection(szSectionName); if (pSection) { NameValuePair *pNVP = FindKey(szKey, pSection); if (pNVP) { if ( !( pNVP->m_strValue.Right(1) == "/" || pNVP->m_strValue.Right(1) == "\\") ) { #ifdef _WIN32 pNVP->m_strValue += "\\"; #else pNVP->m_strValue += "/"; #endif } return pNVP->m_strValue; } else if (bThrowNotFound) { // throw key not found } } else if (bThrowNotFound) { // throw key not found } return 0; } // function retrieves a string from the specified section const char *GProfile::GetString(const char *szSectionName, const char *szKey, short bThrowNotFound /* = true */) { Section *pSection = FindSection(szSectionName); if (pSection) { NameValuePair *pNVP = FindKey(szKey, pSection); if (pNVP) { return (const char *)pNVP->m_strValue; } else if (bThrowNotFound) { // throw key not found } } else if (bThrowNotFound) { // throw key not found } return 0; } void GProfile::SetString(const char *szSectionName, const char *szKey, const char *szValue) { m_bCached = true; Section *pSection = FindSection(szSectionName); if (!pSection) { pSection = new Section; pSection->m_strName = szSectionName; pSection->m_strName.TrimLeftWS(); pSection->m_strName.TrimRightWS(); m_lstSections.AddLast(pSection); } if (pSection) { NameValuePair *pNVP = FindKey(szKey, pSection); if (!pNVP) { pNVP = new NameValuePair; pSection->m_lstNVP.AddLast(pNVP); pNVP->m_strName = szKey; pNVP->m_strName.TrimLeftWS(); pNVP->m_strName.TrimRightWS(); } if (pNVP) { pNVP->m_strValue = szValue; pNVP->m_strValue.TrimLeftWS(); pNVP->m_strValue.TrimRightWS(); } } } <file_sep>#include "pGearbox.h" #include "vtPhysXAll.h" #include <xDebugTools.h> #define DEF_SIZE .25 #define DEF_MAXRPM 5000 #define DEF_MAXPOWER 100 #define DEF_FRICTION 0 #define DEF_MAXTORQUE 340 // ~ F1 Jos Verstappen #define DEF_TORQUE 100 // In case no curve is present // If USE_HARD_REVLIMIT is used, any rpm above the max. RPM // returns a 0 engine torque. Although this works, it gives quite // hard rev limits (esp. when in 1st gear). Better is to supply // a curve which moves down to 0 torque when rpm gets above maxRPM, // so a more natural (smooth) balance is obtained (and turn // this define off) //#define USE_HARD_REVLIMIT void pGearBox::SetGear(int gear) { /*#ifdef LTRACE qdbg("pGearBox:SetGear(%d)\n",gear); #endif */ //QASSERT_V(gear>=0&&gear<gears); curGear=gear; // Calculate resulting ratio SetRatio(gearRatio[curGear]); SetInertia(gearInertia[curGear]); // Recalculate driveline inertias and ratios //car->PreCalcDriveLine(); } void pGearBox::CalcForces() { /*#ifdef LTRACE //qdbg("pGearBox::CalcForces()\n"); #endif */ } /************ * Integrate * ************/ void pGearBox::Integrate() // Based on current input values, adjust the engine { int t; bool ac=true;// RMGR->IsEnabled(RManager::ASSIST_AUTOCLUTCH); pDriveLineComp::Integrate(); // The shifting process if(autoShiftStart) { //t=RMGR->time->GetSimTime()-autoShiftStart; t=car->_lastDT; if(ac)car->GetDriveLine()->EnableAutoClutch(); // We are in a shifting operation if(curGear!=futureGear) { // We are in the pre-shift phase if(t>=timeToDeclutch) { //qdbg("Shift: declutch ready, change gear\n"); // Declutch is ready, change gear SetGear(futureGear); // Trigger gear shift sample //car->GetRAPGear()->GetSample()->Play(); if(ac) car->GetDriveLine()->SetClutchApplication(1.0f); } else { // Change clutch if(ac) car->GetDriveLine()->SetClutchApplication((t*1000/timeToDeclutch)/1000.0f); } } else { // We are in the post-shift phase if(t>=timeToClutch+timeToDeclutch) { //qdbg("Shift: clutch ready, end shift\n"); // Clutch is ready, end shifting process #ifdef OBS_MANUAL_CLUTCH clutch=1.0f; #endif // Conclude the shifting process autoShiftStart=0; if(ac) { car->GetDriveLine()->SetClutchApplication(0.0f); car->GetDriveLine()->DisableAutoClutch(); } } else { // Change clutch if(ac)car->GetDriveLine()->SetClutchApplication( ((t-timeToClutch)*1000/timeToDeclutch)/1000.0f); } } } } void pGearBox::OnGfxFrame() { /* //qdbg("pGearBox:OnGfxFrame()\n"); if(autoShiftStart==0) { // No shift in progress; check shift commands from the controllers if(RMGR->controls->control[RControls::T_SHIFTUP]->value) { //qdbg("Shift Up!\n"); if(curGear<gears) { autoShiftStart=RMGR->time->GetSimTime(); switch(curGear) { case 0: futureGear=2; break; // From neutral to 1st case 1: futureGear=0; break; // From reverse to neutral default: futureGear=curGear+1; break; } } } else if(RMGR->controls->control[RControls::T_SHIFTDOWN]->value) { autoShiftStart=RMGR->time->GetSimTime(); if(curGear!=1) // Not in reverse? { switch(curGear) { case 0: futureGear=1; break; // From neutral to reverse case 2: futureGear=0; break; // From 1st to neutral default: futureGear=curGear-1; break; } } qdbg("Switch back to futureGear=%d\n",futureGear); } } */ } /* bool pGearBox::LoadState(QFile *f) { RDriveLineComp::LoadState(f); f->Read(&curGear,sizeof(curGear)); f->Read(&autoShiftStart,sizeof(autoShiftStart)); f->Read(&futureGear,sizeof(futureGear)); return TRUE; } bool pGearBox::SaveState(QFile *f) { RDriveLineComp::SaveState(f); f->Write(&curGear,sizeof(curGear)); f->Write(&autoShiftStart,sizeof(autoShiftStart)); f->Write(&futureGear,sizeof(futureGear)); return TRUE; } */ /* bool pGearBox::Load(QInfo *info,cstring path) // 'path' may be 0, in which case the default "engine" is used { char buf[128]; int i; if(!path)path="engine"; // Shifting (still in the 'engine' section for historical reasons) sprintf(buf,"%s.shifting.automatic",path); if(info->GetInt(buf)) flags|=AUTOMATIC; //qdbg("Autoshift: flags=%d, buf='%s'\n",flags,buf); sprintf(buf,"%s.shifting.shift_up_rpm",path); shiftUpRPM=info->GetFloat(buf,3500); sprintf(buf,"%s.shifting.shift_down_rpm",path); shiftDownRPM=info->GetFloat(buf,2000); sprintf(buf,"%s.shifting.time_to_declutch",path); timeToDeclutch=info->GetInt(buf,500); sprintf(buf,"%s.shifting.time_to_clutch",path); timeToClutch=info->GetInt(buf,500); //qdbg("declutch=%d, clutch=%d (buf=%s)\n",timeToDeclutch,timeToClutch,buf); // Gearbox path="gearbox"; // ! sprintf(buf,"%s.gears",path); gears=info->GetInt(buf,4); if(gears>=MAX_GEAR-1) { qwarn("Too many gears defined (%d, max=%d)",gears,MAX_GEAR-1); gears=MAX_GEAR-1; } for(i=0;i<gears;i++) { sprintf(buf,"%s.gear%d.ratio",path,i); gearRatio[i+1]=info->GetFloat(buf,1.0); sprintf(buf,"%s.gear%d.inertia",path,i); gearInertia[i+1]=info->GetFloat(buf); } return TRUE; } */ #ifdef OBS float pGearBox::GetInertiaAtDifferential() // Returns effective inertia as seen at the input of the differential. // This may be used as the input for the differential. // Notice the gearing from differential to engine. { float totalInertia; float ratio,ratioSquared; // From differential towards engine // First, the driveshaft ratio=endRatio; ratioSquared=ratio*ratio; totalInertia=inertiaDriveShaft*ratioSquared; // Gearing and engine // Both engine and the faster rotating part of the gearbox are at // the engine side of the clutch. Therefore, both interia's from those // 2 objects must be scaled to get the effective inertia. // Note this scaling factor is squared, for reasons // I explain on the Racer website. ratio=gearRatio[curGear]*endRatio; ratioSquared=ratio*ratio; totalInertia+=clutch*(gearInertia[curGear]+inertiaEngine)*ratioSquared; return totalInertia; } float pGearBox::GetInertiaForWheel(RWheel *w) // Return effective inertia as seen in the perspective of wheel 'w' // Takes into account any clutch effects { float totalInertia; float inertiaBehindClutch; float NtfSquared,NfSquared; //float rotationA; RWheel *wheel; int i; // Calculate total ratio multiplier; note the multipliers are squared, // and not just a multiplier for the inertia. See Gillespie's book, // 'Fundamentals of Vehicle Dynamics', page 33. NtfSquared=gearRatio[curGear]*endRatio; NtfSquared*=NtfSquared; // Calculate total inertia that is BEHIND the clutch NfSquared=endRatio*endRatio; inertiaBehindClutch=gearInertia[curGear]*NtfSquared+ inertiaDriveShaft*NfSquared; // Add inertia of attached and powered wheels // This is a constant, so it should be cached actually (except // when a wheel breaks off) /* for(i=0;i<car->GetWheels();i++) { wheel=car->GetWheel(i); if(wheel->IsPowered()&&wheel->IsAttached()) inertiaBehindClutch+=wheel->GetRotationalInertia()->x; } */ // Add the engine's inertia based on how far the clutch is engaged /* totalInertia=inertiaBehindClutch+clutch*inertiaEngine*NtfSquared; */ return totalInertia; } // Return effective torque for wheel 'w' // Takes into account any clutch effects float pGearBox::GetTorqueForWheel(pWheel *w) { //qdbg("clutch=%f, T=%f, ratio=%f\n",clutch,torque,gearRatio[curGear]*endRatio); //return clutch*torque*gearRatio[curGear]*endRatio; } #endif void pGearBox::setToDefault() { gears = 7; gearRatio[0]=-2.59f; gearInertia[0]=0.1f; gearRatio[1]=2.94f; gearInertia[1]=0.06f; gearRatio[2]=2.056f; gearInertia[2]=0.05f; gearRatio[3]=1.520f; gearInertia[3]=0.04f; gearRatio[4]=1.179f; gearInertia[4]=0.03f; gearRatio[5]=1.030f; gearInertia[5]=0.02f; gearRatio[6]=0.914f; gearInertia[6]=0.01f; autoShiftStart = 1; timeToClutch=25.0f; timeToDeclutch=352.0f; shiftDownRPM= 3000.0f; shiftUpRPM=7000.0f; } pGearBox::pGearBox(pVehicle *_car) : pDriveLineComp() { //SetName("gearbox"); car=_car; Reset(); } pGearBox::~pGearBox() { } void pGearBox::Reset() // Reset all variables { int i; flags=0; timeToDeclutch=timeToClutch=0; autoShiftStart=1; futureGear=0; for(i=0;i<MAX_GEAR;i++) { gearRatio[i]=1; gearInertia[i]=0; } curGear=0; // Neutral gears=4; } XString pGearBox::GetGearName(int gear) // Returns a name for a gear // Convenience function. { switch(gear) { case 0: return "N"; case 1: return "R"; case 2: return "1st"; case 3: return "2nd"; case 4: return "3rd"; case 5: return "4th"; case 6: return "5th"; case 7: return "6th"; case 8: return "7th"; case 9: return "8th"; default: return "G??"; } } void pGearBox::Paint() { } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" using namespace xUtils; using namespace vtAgeia; #include "vtAttributeHelper.h" // [3/31/2009 master] Temp ! #include "IParameter.h" //################################################################ // // Declaration of rigid body related attribute callback function // int registerRigidBody(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { using namespace vtTools::ParameterTools; int error = 0 ; //---------------------------------------------------------------- // // Sanity checks : // assert(target); CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); CKParameterOut *bodyParameter = target->GetAttributeParameter(attributeType); assert(bodyParameter); CKStructHelper sHelper(bodyParameter); if (sHelper.GetMemberCount() ==0 ) { //happens when dev is being opened and loads a cmo with physic objects. return -1; } if (set) { pRigidBody* body = GetPMan()->getBody(target); if (body) { return true; } //---------------------------------------------------------------- // // attribute has been added at run-time, post pone the registration to the next frame. // if ( isPostJob && GetPMan()->GetContext()->IsPlaying() ) { pAttributePostObject postAttObject(target->GetID(),registerRigidBody,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); return true; } if(!GetPMan()->GetContext()->IsPlaying()) return true; pObjectDescr *objDecr = new pObjectDescr(); IParameter::Instance()->copyTo(objDecr,bodyParameter); //---------------------------------------------------------------- // // Pivot override ? // int attPivot = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); if (target->HasAttribute(attPivot)){ IParameter::Instance()->copyTo(objDecr->pivot,target->GetAttributeParameter(attPivot)); objDecr->mask << OD_Pivot; } //---------------------------------------------------------------- // // Pivot override ? // int attMass = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); if (target->HasAttribute(attMass)){ IParameter::Instance()->copyTo(objDecr->mass,target->GetAttributeParameter(attMass)); objDecr->mask << OD_Mass; } //---------------------------------------------------------------- // // register the body // if(!body && !(objDecr->flags & BF_SubShape) ) { body = pFactory::Instance()->createRigidBody(target,*objDecr); if (body) { body->setInitialDescription(objDecr); } } //SAFE_DELETE(objDecr); } //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"register object"); error++; return error; } /* //################################################################ // // Not being used // int registerRigidBody(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { if (!GetPMan()->GetContext()->IsPlaying() && set) { using namespace vtTools::ParameterTools; CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); XString errString; errString.Format("attr added"); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.Str()); XString value = getDefaultValue(distanceParameter); } return 0; } */ <file_sep>#include "ckall.h" CKERROR CreateMeshAddProto(CKBehaviorPrototype **pproto); int MeshAdd(const CKBehaviorContext& context); extern void CleanUp(CKBehavior *beh); extern void Load(CKBehavior *beh,CKScene *scn); CKObjectDeclaration *FillMeshAddDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Mesh Addition"); od->SetDescription("Duplicates objects"); od->SetCategory("Mesh Modifications/Multi Mesh"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0xc73102f,0x4f8c574b)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateMeshAddProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateMeshAddProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Mesh Addition"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Original", CKPGUID_3DENTITY); proto->DeclareInParameter("Additional", CKPGUID_3DENTITY); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(MeshAdd); *pproto = proto; return CK_OK; } int MeshAdd(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; CK3dEntity *oe = (CK3dEntity *)beh->GetInputParameterObject(0); CKMesh *om=oe->GetCurrentMesh(); CK3dEntity *ae = (CK3dEntity *)beh->GetInputParameterObject(1); CKMesh *am=ae->GetCurrentMesh(); VxVector oePos; oe->GetPosition(&oePos,NULL); int oVCount = om->GetVertexCount(); int aVCount = am->GetVertexCount(); int oFCount = om->GetFaceCount(); int aFCount = am->GetFaceCount(); om->SetVertexCount(oVCount+aVCount); om->SetFaceCount(oFCount+aFCount); VxVector oVPos,oVNormals; float u,v; VxVector aePos,Delta; ae->GetPosition(&aePos,NULL); Delta = aePos-oePos; for (int j = 0; j< aVCount; j++){ am->GetVertexPosition(j,&oVPos); oVPos += Delta; om->SetVertexPosition(j+oVCount,&oVPos); am->GetVertexNormal(j,&oVNormals); om->SetVertexNormal(j+oVCount,&oVNormals); am->GetVertexTextureCoordinates(j,&u,&v,-1); om->SetVertexTextureCoordinates(j+oVCount,u,v,-1); } for ( int l=0;l< aFCount;l++){ int a,b,c; VxVector FN; am->GetFaceVertexIndex(l,a,b,c); om->SetFaceVertexIndex(l+oFCount,a+oVCount,b+oVCount,c+oVCount); CKMaterial *OMAT = am->GetFaceMaterial(l); om->SetFaceMaterial(l+oFCount,OMAT); } om->BuildFaceNormals(); beh->ActivateOutput(0); return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pVehicleAll.h" #include "pWorldSettings.h" #include <stdlib.h> #include <exception> using namespace vtTools::AttributeTools; int pWorld::hadBrokenJoint() { int nbActors = getScene()->getNbActors(); NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor && actor->userData != NULL) { pRigidBody* body = (pRigidBody*)actor->userData; if (body && body->hasBrokenJoint) { return 1; } } } return 0; } void pWorld::cleanBrokenJoints() { int nbActors = getScene()->getNbActors(); NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor && actor->userData != NULL) { pRigidBody* body = (pRigidBody*)actor->userData; if (body ) { body->hasBrokenJoint = false; } } } } void pWorld::step(float stepsize) { if (getScene()) { CKVariableManager* vm = GetPMan()->GetContext()->GetVariableManager(); if( !vm ) return; int disable = 0 ; vm->GetValue("Physic/Disable Physics",&disable); if (disable) { return; } //int hasBroken = hadBrokenJoint(); NxU32 nbTransforms = 0; NxActiveTransform *activeTransforms = getScene()->getActiveTransforms(nbTransforms); updateVehicles(stepsize); updateClothes(); #ifdef HAS_FLUIDS updateFluids(); #endif vtAgeia::pWorldSettings *wSettings = GetPMan()->getDefaultWorldSettings(); if (wSettings->isFixedTime()) getScene()->setTiming(wSettings->getFixedTimeStep() * 10.0f, wSettings->getNumIterations() , NX_TIMESTEP_FIXED); /*else getScene()->setTiming( (stepsize * 100 ) / wSettings->getNumIterations() , wSettings->getNumIterations() , NX_TIMESTEP_VARIABLE); */ /* NxU32 nbIter = 0 ; int op =2; NxTimeStepMethod mode = NX_TIMESTEP_FIXED;*/ /*float stepSz;getScene()->getTiming(stepSz,nbIter,op);*/ int nbDeleted = GetPMan()->_checkRemovalList(); if (nbDeleted) { //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"objects to delete"); //return; } int nbReset = GetPMan()->_getRestoreMap()->Size(); if(nbReset) { GetPMan()->_checkResetList(); //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"objects to reset"); GetPMan()->_getResetList().Clear(); return; } int nbCheck = GetPMan()->getCheckList().Size(); if(nbCheck) { //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"objects to check"); GetPMan()->_checkObjectsByAttribute(GetPMan()->GetContext()->GetCurrentLevel()->GetCurrentScene()); GetPMan()->_checkListCheck(); if(nbCheck) { if(nbCheck && GetPMan()->sceneWasChanged ) { //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"objects to check & and scene change, aborting"); } //GetPMan()->checkWorlds();drdrdr //return; } } if(!getScene()->checkResults(NX_RIGID_BODY_FINISHED,false)) { getScene()->simulate(stepsize * GetPMan()->GetContext()->GetTimeManager()->GetTimeScaleFactor() ); } if(getScene()->checkResults(NX_RIGID_BODY_FINISHED,false) /*&& hasBroken==0*/) { //if(nbDeleted) return; int nbNewPostObjects = GetPMan()->getAttributePostObjects().Size(); /* if(m_bCompletedLastFrame) { //getScene()->simulate(stepsize * GetPMan()->GetContext()->GetTimeManager()->GetTimeScaleFactor() ); getScene()->simulate( m_fTimeSinceLastCallToSimulate ); m_bCompletedLastFrame = false; m_fTimeSinceLastCallToSimulate = 0.0; } m_fTimeSinceLastCallToSimulate +=(stepsize * GetPMan()->GetContext()->GetTimeManager()->GetTimeScaleFactor()); if(getScene()->checkResults(NX_ALL_FINISHED,false)) {*/ m_bCompletedLastFrame = true; if(nbTransforms && activeTransforms && !nbDeleted && !nbReset && !nbCheck && !nbNewPostObjects /*&& hasBroken== 0*/) { for(NxU32 i = 0; i < nbTransforms; ++i) { // the user data of the actor holds the game object pointer NxActor *actor = activeTransforms[i].actor; //XString name = actor->getName(); if (actor !=NULL) { pRigidBody *body = static_cast<pRigidBody*>(actor->userData); // update the game object's transform to match the NxActor if(body !=NULL) { assert(body && body->getEntID()); NxMat34 transformation = activeTransforms[i].actor2World; VxQuaternion rot = pMath::getFrom(transformation.M); VxVector pos = pMath::getFrom(transformation.t); VxVector pos2 = pMath::getFrom(transformation.t); CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(body->getEntID())); if (ent !=NULL && ent->GetClassID() != CKCID_3DOBJECT) { continue; } //assert(ent && ent->GetID()); /* XString errMessage= "update body"; errMessage+=ent->GetName(); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMessage.Str()); */ //NxShape *mainShape=body->getMainShape(); if (ent !=NULL) { int hier = (body->getFlags() & BF_Hierarchy ); ent->SetPosition(&pos,NULL); ent->SetQuaternion(&rot,NULL); body->updateSubShapes(); body->onMove(true,true,pos,rot); if (body->hasWheels()) { body->wakeUp(); } }else{ //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Invalid entity due simulation."); } }else { //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Invalid Body due simulation."); } } } } NxU32 error=0; getScene()->flushStream(); getScene()->fetchResults(NX_ALL_FINISHED,true,&error); if(error !=0) { XString err="error fetching results : "; err << error; xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,err.Str()); } }else { //cleanBrokenJoints(); //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"world has broken joints !"); return; } } ////////////////////////////////////////////////////////////////////////// // // // update Virtools from hardware objects int nbActors = getScene()->getNbActors(); NxActor** actors = getScene()->getActors(); if(getCompartment()) { while(nbActors--) { NxActor* actor = *actors++; if(actor && actor->userData != NULL) { pRigidBody* body = (pRigidBody*)actor->userData; if (body && body->getActor()->getCompartment()) { NxMat34 transformation = actor->getGlobalPose(); VxQuaternion rot = pMath::getFrom(transformation.M); VxVector pos = pMath::getFrom(transformation.t); VxVector pos2 = pMath::getFrom(transformation.t); CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(body->getEntID())); //NxShape *mainShape=body->getMainShape(); if (ent) { //int hier = (body->getFlags() & BF_Hierarchy ); ent->SetPosition(&pos,NULL); ent->SetQuaternion(&rot,NULL); body->updateSubShapes(); body->onMove(true,true,pos,rot); if (body->hasWheels()) { // body->wakeUp(); } }else{ //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Invalid Body due simulation."); } } } } } /* if(getScene()->checkResults(NX_RIGID_BODY_FINISHED)) { NxU32 error; getScene()->flushStream(); getScene()->fetchResults(NX_RIGID_BODY_FINISHED,true,&error); } */ /* int err = error; NxReal maxTimestep; NxTimeStepMethod method; NxU32 maxIter; NxU32 numSubSteps; //getScene()->getTiming(maxTimestep, maxIter, method, &numSubSteps); int op2 = 3; op2++; */ } int pWorld::onPreProcess() { int nbActors = getScene()->getNbActors(); if (!nbActors) { return 0; } NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; pRigidBody *body = static_cast<pRigidBody*>(actor->userData); if (body) { pVehicle *v = body->getVehicle(); if (!v && body->hasWheels()) { int nbShapes = actor->getNbShapes(); NxShape ** slist = (NxShape **)actor->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *sinfo = static_cast<pSubMeshInfo*>(s->userData); if (sinfo && sinfo->wheel !=NULL) { pWheel *wheel = sinfo->wheel; pWheel2* wheel2 = dynamic_cast<pWheel2*>(wheel); if ( wheel2 && (wheel2->getCallMask().test(CB_OnPreProcess)) ) { wheel2->onPreProcess(); } } } } } //if (v && (v->getCallMask().test(CB_OnPreProcess))) // v->onPreProcess(); } } return 1; } int pWorld::onPostProcess() { int nbActors = getScene()->getNbActors(); if (!nbActors) { return 0; } NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; pRigidBody *body = static_cast<pRigidBody*>(actor->userData); if (body) { pVehicle *v = body->getVehicle(); if (!v && body->hasWheels()) { int nbShapes = actor->getNbShapes(); NxShape ** slist = (NxShape **)actor->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *sinfo = static_cast<pSubMeshInfo*>(s->userData); if (sinfo && sinfo->wheel !=NULL) { pWheel *wheel = sinfo->wheel; pWheel2* wheel2 = dynamic_cast<pWheel2*>(wheel); if ( wheel2 && (wheel2->getCallMask().test(CB_OnPostProcess))) { wheel2->onPostProcess(); } } } } } //if (v && (v->getCallMask().test(CB_OnPostProcess))) //v->onPostProcess(); } } return 1; } <file_sep>#ifndef __P_SERIALIZER_H__ #define __P_SERIALIZER_H__ #include "vtPhysXBase.h" /** \addtogroup Serialization @{ */ /** \brief Class to import and export NxStream files. Those files can be created by 3D related content editors such as Maya and 3D-SMax. Also, you can dump the entire Virtools scene and load it in the supplied PhysX Viewer. */ class MODULE_API pSerializer { public: pSerializer(); ~pSerializer(); static pSerializer*Instance(); NXU::NxuPhysicsCollection *getCollection(const char *pFilename,int type); bool overrideBody(pRigidBody *body,int flags); int loadCollection(const char*fileName,int flags); int saveCollection(const char*filename); void parseFile(const char*filename,int flags); protected: NXU::NxuPhysicsCollection *mCollection; private: }; /** @} */ #endif<file_sep>#include "CKAll.h" CKObjectDeclaration *FillBehaviorDirToArrayDecl(); CKERROR CreateDirToArrayProto(CKBehaviorPrototype **pproto); int DirToArray(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorDirToArrayDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("Dir to Array"); od->SetDescription(""); od->SetCategory("Narratives/Files"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x4be0703f,0x208b5a7f)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDirToArrayProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateDirToArrayProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Dir to Array"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Fill"); proto->DeclareInput("Loop In"); proto->DeclareOutput("Reseted"); proto->DeclareOutput("Loop Out"); proto->DeclareInParameter("Directory", CKPGUID_STRING,"0"); proto->DeclareInParameter("Mask", CKPGUID_STRING,"0"); proto->DeclareInParameter("Recursive", CKPGUID_BOOL,"0"); proto->DeclareOutParameter("entry", CKPGUID_STRING); proto->DeclareOutParameter("counter", CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(DirToArray); *pproto = proto; return CK_OK; } #include <vector> std::vector<XString>flist; int counter = 0 ; int DirToArray(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; XString filename((CKSTRING) beh->GetInputParameterReadDataPtr(0)); XString Mask((CKSTRING) beh->GetInputParameterReadDataPtr(1)); int rec; beh->GetInputParameterValue(2,&rec); if( beh->IsInputActive(0) ){ beh->ActivateInput(0,FALSE); flist.erase(flist.begin(),flist.end()); CKDirectoryParser MyParser(filename.Str(),Mask.Str(),rec); char* str = NULL; while(str = MyParser.GetNextFile()) flist.push_back(XString(str)); counter = 0; beh->ActivateInput(1,TRUE); } if( beh->IsInputActive(1) ){ beh->ActivateInput(1,FALSE); if ( counter < flist.size() ){ XString entry = flist.at(counter); CKParameterOut * pout = beh->GetOutputParameter(0); pout->SetStringValue(entry.Str() ); counter++; beh->SetOutputParameterValue(1,&counter); beh->ActivateOutput(1); }else{ beh->SetOutputParameterValue(1,&counter); counter = 0 ; beh->ActivateOutput(0); } } return 0; } <file_sep> #include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPVControl2Decl(); CKERROR CreatePVControl2Proto(CKBehaviorPrototype **pproto); int PVControl2(const CKBehaviorContext& behcontext); CKERROR PVControl2CB(const CKBehaviorContext& behcontext); using namespace vtTools::BehaviorTools; enum bInTrigger { TI_DO, }; enum bOutputs { O_Gear, O_MPH, O_GearRatio, O_MotorRPM, /*O_RPM, O_RPM_WHEELS, O_RATIO,*/ }; enum bTInputs { IT_On, IT_Off, IT_Forward, IT_Backwards, IT_Left, IT_Right, IT_HandBrake, IT_GUP, IT_GDOWN }; enum bTOutputs { OT_On, OT_Off, OT_GearUp, OT_GearDown, }; enum bSettings { bs_Manual, }; #define BB_SSTART 0 //************************************ // Method: FillBehaviorPVControl2Decl // FullName: FillBehaviorPVControl2Decl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPVControl2Decl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVCarControl"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Physics Car"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x26371b1c,0x4e3924)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVControl2Proto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePVControl2Proto // FullName: CreatePVControl2Proto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePVControl2Proto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVCarControl"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareInput("Off"); proto->DeclareInput("Forward"); proto->DeclareInput("Backward"); proto->DeclareInput("Turn Left"); proto->DeclareInput("Turn Right"); proto->DeclareInput("Handbrake"); proto->DeclareOutput("Exit On"); proto->DeclareOutput("Exit Off"); proto->DeclareOutput("GearUp"); proto->DeclareOutput("GearDown"); proto->DeclareOutParameter("Current Gear",CKPGUID_INT,"-1"); proto->DeclareOutParameter("MPH",CKPGUID_FLOAT,"-1"); proto->DeclareOutParameter("Gear Ratio",CKPGUID_FLOAT,"-1"); proto->DeclareOutParameter("Motor RPM",CKPGUID_FLOAT,"-1"); proto->DeclareSetting("Automatic",CKPGUID_BOOL,"TRUE"); proto->DeclareSetting("Semi Analog",CKPGUID_BOOL,"TRUE"); /* PVControl2 PVControl2 is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies various physical parameters.<br> <h3>Technical Information</h3> \image html PVControl2.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pin">Collisions Group: </SPAN>Which collision group this body is part of.See pRigidBody::setCollisionsGroup(). <BR> <SPAN CLASS="pin">Kinematic Object: </SPAN>The kinematic state. See pRigidBody::setKinematic(). <BR> <SPAN CLASS="pin">Gravity: </SPAN>The gravity state.See pRigidBody::enableGravity(). <BR> <SPAN CLASS="pin">Collision: </SPAN>Determines whether the body reacts to collisions.See pRigidBody::enableCollision(). <BR> <SPAN CLASS="pin">Mass Offset: </SPAN>The new mass center in the bodies local space. <BR> <SPAN CLASS="pin">Pivot Offset: </SPAN>The initial shape position in the bodies local space. <BR> <SPAN CLASS="pin">Notify Collision: </SPAN>Enables collision notification.This is necessary to use collisions related building blocks. <BR> <SPAN CLASS="pin">Transformation Locks: </SPAN>Specifies in which dimension a a transformation lock should occour. <BR> <SPAN CLASS="pin">Linear Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Angular Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Filter Groups: </SPAN>Sets the filter mask of the initial or sub shape. <BR> <SPAN CLASS="setting">Collisions Group: </SPAN>Enables input for collisions group. <BR> <SPAN CLASS="setting">Kinematic Object: </SPAN>Enables input for kinematic object. <BR> <SPAN CLASS="setting">Gravity: </SPAN>Enables input for gravity. <BR> <SPAN CLASS="setting">Collision: </SPAN>Enables input for collision. <BR> <SPAN CLASS="setting">Mas Offset: </SPAN>Enables input for mass offset. <BR> <SPAN CLASS="setting">Pivot Offset: </SPAN>Enables input for pivot offset. <BR> <SPAN CLASS="setting">Notify Collision: </SPAN>Enables input for collision. <BR> <SPAN CLASS="setting">Linear Damping: </SPAN>Enables input for linear damping. <BR> <SPAN CLASS="setting">Angular Damping: </SPAN>Enables input for angular damping. <BR> <SPAN CLASS="setting">Filter Groups: </SPAN>Enables input for filter groups. <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> */ proto->SetBehaviorCallbackFct( PVControl2CB ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PVControl2); *pproto = proto; return CK_OK; } //************************************ // Method: PVControl2 // FullName: PVControl2 // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ #define BBSParameter(A) DWORD s##A;\ beh->GetLocalParameterValue(A,&s##A) int PVControl2(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbSErrorME(E_PE_REF); pRigidBody *body = NULL; body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); pVehicle *v = body->getVehicle(); if (!v) { bbSErrorME(E_PE_NoVeh); } if( beh->IsInputActive(IT_On) ) { beh->ActivateInput(IT_On,FALSE); beh->ActivateOutput(OT_On); } if( beh->IsInputActive(IT_Off) ) { beh->ActivateInput(IT_Off,FALSE); beh->ActivateOutput(OT_Off); return 0; } ////////////////////////////////////////////////////////////////////////// // // // Acceleration // float acceleration = 0.0f; float steering = 0.0; int gearUP= 0; int gearDown= 0; int handbrake = 0; /* v->setControlState(E_VCS_ACCELERATION,acceleration); v->setControlState(E_VCS_HANDBRAKE,handbrake); v->setControlState(E_VCS_STEERING,steering); v->setControlMode(E_VCS_ACCELERATION,E_VCSM_DIGITAL); v->setControlMode(E_VCS_STEERING,E_VCSM_DIGITAL); */ ////////////////////////////////////////////////////////////////////////// // // Acceleration + Handbrake // if( beh->IsInputActive(IT_Forward) ) { beh->ActivateInput(IT_Forward,FALSE); acceleration = 1.0f; v->setControlState(E_VCS_ACCELERATION,acceleration); } if( beh->IsInputActive(IT_Backwards) ) { beh->ActivateInput(IT_Backwards,FALSE); acceleration = -1.0f; v->setControlState(E_VCS_ACCELERATION,acceleration); } if( beh->IsInputActive(IT_HandBrake) ) { beh->ActivateInput(IT_HandBrake,FALSE); handbrake = 1; v->setControlState(E_VCS_HANDBRAKE,handbrake); } ////////////////////////////////////////////////////////////////////////// // // Steering if( beh->IsInputActive(IT_Left) ) { beh->ActivateInput(IT_Left,FALSE); steering = 1.0f; v->setControlState(E_VCS_STEERING,steering); } if( beh->IsInputActive(IT_Right) ) { beh->ActivateInput(IT_Right,FALSE); steering = -1.0f; v->setControlState(E_VCS_STEERING,steering); } //if(acceleration !=0.0f || steering !=0.0f || handbrake) //v->control(steering,false,acceleration,false,handbrake); int semiAnalog = 0; beh->GetLocalParameterValue(1,&semiAnalog); ////////////////////////////////////////////////////////////////////////// // // Gears // int automatic=0; beh->GetLocalParameterValue(bs_Manual,&automatic); v->setAutomaticMode(automatic); int lastGear=0; beh->GetOutputParameterValue(O_Gear,&lastGear); int currentGear = 0; if (v->getGears()) { currentGear = v->getGears()->getGear(); } if (!automatic) { if( beh->IsInputActive(IT_GUP) ) { beh->ActivateInput(IT_GUP,FALSE); gearUP =1; } if( beh->IsInputActive(IT_GDOWN) ) { beh->ActivateInput(IT_GDOWN,FALSE); gearDown=1; } } if ( gearUP && !gearDown) { v->setControlState(E_VCS_GUP,1); v->setControlState(E_VCS_GDOWN,0); }else{ v->setControlState(E_VCS_GUP,0); } if ( !gearUP && gearDown) { v->setControlState(E_VCS_GUP,0); v->setControlState(E_VCS_GDOWN,1); } if ( !gearUP) { v->setControlState(E_VCS_GUP,0); } if ( !gearDown) { v->setControlState(E_VCS_GDOWN,0); } /* if (!automatic) { if( beh->IsInputActive(IT_GUP) ) { beh->ActivateInput(IT_GUP,FALSE); gearUP =1; } if( beh->IsInputActive(IT_GDOWN) ) { beh->ActivateInput(IT_GDOWN,FALSE); gearDown=1; } if (gearUP && !gearDown) { v->gearUp(); } if (!gearUP && gearDown) { v->gearDown(); } }else { if (v->getGears()) { if (currentGear!=lastGear) { if (currentGear > lastGear) { beh->ActivateOutput(OT_GearUp); }else beh->ActivateOutput(OT_GearDown); } } } */ /////////////////////////////////////////////////////////////////////////// // // Vehicle Data : // float mph = v->getMPH(); beh->SetOutputParameterValue(O_MPH,&mph); float gRatio = v->_getGearRatio(); beh->SetOutputParameterValue(O_GearRatio,&gRatio); beh->SetOutputParameterValue(O_Gear,&currentGear); if (v->getMotor()) { float rpm = v->getMotor()->getRpm(); beh->SetOutputParameterValue(O_MotorRPM,&rpm); } return CKBR_ACTIVATENEXTFRAME; } CKERROR PVControl2CB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORLOAD: { break; } case CKM_BEHAVIORDETACH: { break; } case CKM_BEHAVIORATTACH: { break; } case CKM_BEHAVIORSETTINGSEDITED: { int automatic=0; beh->GetLocalParameterValue(bs_Manual,&automatic); int nbI = beh->GetInputCount(); if (automatic) { if (nbI > IT_GUP ) { beh->DeleteInput( IT_GUP); beh->DeleteInput( IT_GUP); } } if (!automatic) { if (nbI < IT_GDOWN ) { beh->AddInput("Gear Up"); beh->AddInput("Gear Down"); } } break; } } return CKBR_OK; } <file_sep>FIND_PATH(VTDEV41DIR NAMES dev.exe devr.exe PATHS [HKEY_LOCAL_MACHINE\\SOFTWARE\\Virtools\\Dev\\4.1;InstallPath] ) MARK_AS_ADVANCED(CMAKE_MAKE_PROGRAM) SET(VTDEV41 1) <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" pWheelContactData* pWheel1::getContact(){ return new pWheelContactData(); } float pWheel1::getRpm()const{ return NxMath::abs(_turnVelocity * 60.f);} NxActor *pWheel1::getTouchedActor(){ return contactInfo->otherActor; } void pWheel1::_tick(float dt) { if(!hasGroundContact()) updateContactPosition(); //################################################################ // // Calculate the wheel rotation around the roll axis // updateAngularVelocity(dt*0.001f, false); float motorTorque=0.0; if(getWheelFlag(WF_Accelerated)) { /*if (handBrake && getWheelFlag(NX_WF_AFFECTED_BY_HANDBRAKE)) { // Handbrake, blocking! }*/ if (hasGroundContact()) { // Touching, force applies NxVec3 steeringDirection; getSteeringDirection(steeringDirection); steeringDirection.normalize(); NxReal localTorque = motorTorque; NxReal wheelForce = localTorque / _radius; steeringDirection *= wheelForce; wheelCapsule->getActor().addForceAtPos(steeringDirection, contactInfo->contactPosition); if(contactInfo->otherActor->isDynamic()) contactInfo->otherActor->addForceAtPos(-steeringDirection, contactInfo->contactPosition); } } NxMat34& wheelPose = getWheelCapsule()->getGlobalPose(); NxMat33 rot, axisRot, rollRot; rot.rotY( _angle ); axisRot.rotY(0); rollRot.rotX(_turnAngle); wheelPose.M = rot * wheelPose.M * axisRot * rollRot; float a = _angle; float b = getWheelRollAngle(); setWheelPose(wheelPose); //setWheelOrientation(wheelPose.M); contactInfo->reset(); } void pWheel1::_updateVirtoolsEntity(bool position,bool rotation) { CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(getEntID())); if (ent && position) { /* NxWheelShape *wShape = getWheelShape(); NxMat34 pose = wShape->getGlobalPose(); NxWheelContactData wcd; NxShape* contactShape = wShape->getContact(wcd); NxVec3 suspensionOffsetDirection; pose.M.getColumn(1, suspensionOffsetDirection); suspensionOffsetDirection =-suspensionOffsetDirection; if (contactShape && wcd.contactForce > -1000) { NxVec3 toContact = wcd.contactPoint - pose.t; double alongLength = suspensionOffsetDirection.dot(toContact); NxVec3 across = toContact - alongLength * suspensionOffsetDirection; double r = wShape->getRadius(); double pullBack = sqrt(r*r - across.dot(across)); pose.t += (alongLength - pullBack) * suspensionOffsetDirection; } else { pose.t += wShape->getSuspensionTravel() * suspensionOffsetDirection; } VxVector oPos = getFrom(pose.t); ent->SetPosition(&oPos); if (hasGroundContact()) { }else { // VxVector gPos = getWheelPos(); // ent->SetPosition(&gPos,getBody()->GetVT3DObject()); } */ } if (ent && rotation) { //float rollAngle = getWheelRollAngle(); //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); VxQuaternion rot = pMath::getFrom( getWheelPose().M ); ent->SetQuaternion(&rot,NULL); } } void pWheel1::updateContactPosition() { contactInfo->contactPositionLocal = getFrom(_maxPosition) - NxVec3(0, _maxSuspension+_radius, 0); } void pWheel1::setAngle(float angle) { _angle = angle; NxReal Cos, Sin; NxMath::sinCos(_angle, Sin, Cos); NxMat33 wheelOrientation = wheelCapsule->getLocalOrientation(); wheelOrientation.setColumn(0, NxVec3( Cos, 0, Sin )); wheelOrientation.setColumn(2, NxVec3( Sin, 0,-Cos )); setWheelOrientation(wheelOrientation); } void pWheel1::updateAngularVelocity(float lastTimeStepSize, bool handbrake) { if((mWheelFlags & WF_AffectedByHandbrake) && handbrake) { _turnVelocity = 0; } else if (contactInfo->isTouching()) { NxReal wheelPerimeter = NxTwoPi * _radius; NxReal newTurnVelocity = contactInfo->relativeVelocity / wheelPerimeter; _turnVelocity = newTurnVelocity; _turnAngle += _turnVelocity * lastTimeStepSize * NxTwoPi; } else { _turnVelocity *= 0.99f; _turnAngle += _turnVelocity; } while(_turnAngle >= NxTwoPi) _turnAngle -= NxTwoPi; while (_turnAngle < 0) _turnAngle += NxTwoPi; setWheelRollAngle(_turnAngle); } void pWheel1::getSteeringDirection(NxVec3& dir) { if(mWheelFlags & (WF_SteerableInput | WF_SteerableAuto)) { wheelCapsule->getGlobalOrientation().getColumn(0, dir); } else { wheelCapsule->getActor().getGlobalOrientation().getColumn(0, dir); } } void pWheel1::tick(bool handbrake, float motorTorque, float brakeTorque, float dt) { if(getWheelFlag(WF_Accelerated)) { if (handbrake && getWheelFlag(WF_AffectedByHandbrake)) { // Handbrake, blocking! } else if (hasGroundContact()) { // Touching, force applies NxVec3 steeringDirection; getSteeringDirection(steeringDirection); steeringDirection.normalize(); NxReal localTorque = motorTorque; NxReal wheelForce = localTorque / _radius; steeringDirection *= wheelForce; wheelCapsule->getActor().addForceAtPos(steeringDirection, contactInfo->contactPosition); if(contactInfo->otherActor->isDynamic()) contactInfo->otherActor->addForceAtPos(-steeringDirection, contactInfo->contactPosition); } } NxReal OneMinusBreakPedal = 1-brakeTorque; /* if(handBrake && getWheelFlag(WF_AffectedByHandbrake)) { material->setDynamicFrictionV(1); material->setStaticFrictionV(4); material->setDynamicFriction(0.4f); material->setStaticFriction(1.0f); } else { NxReal newv = OneMinusBreakPedal * _frictionToFront + brakeTorque; NxReal newv4= OneMinusBreakPedal * _frictionToFront + brakeTorque*4; material->setDynamicFrictionV(newv); material->setDynamicFriction(_frictionToSide); material->setStaticFrictionV(newv*4); material->setStaticFriction(2); }*/ if(!hasGroundContact()) updateContactPosition(); updateAngularVelocity(dt, handbrake); contactInfo->reset(); } VxVector pWheel1::getWheelPos()const{ return getFrom(wheelCapsule->getLocalPosition()); } void pWheel1::setWheelOrientation(const NxMat33& m) { wheelCapsule->setLocalOrientation(m); if (wheelConvex != NULL) wheelConvex->setLocalOrientation(m); } void pWheel1::_updateAgeiaShape(bool position,bool rotation) { } int pWheel1::_constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) { return 1; } pWheel1::pWheel1(pRigidBody *body, pWheelDescr *descr) : pWheel(body,descr) { wheelCapsule = NULL; wheelConvex = NULL; contactInfo = new ContactInfo(); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "Stream.h" #include "cooking.h" #include "IParameter.h" bool pFactory::_createConvexCylinder(NxConvexShapeDesc* shape, CK3dEntity*dstBodyReference, pObjectDescr *oDescr) { #ifdef _DEBUG assert(dstBodyReference); // <- should never happen ! #endif // _DEBUG bool result = false; pConvexCylinderSettings cSettingsZero; pConvexCylinderSettings &cSettings = cSettingsZero; if (oDescr ) { if( (oDescr->mask & OD_ConvexCylinder) ) cSettings = oDescr->convexCylinder; }else { findSettings(cSettings,dstBodyReference); } cSettings.radius.value *=0.5f; cSettings.height.value *=0.5f; NxArray<NxVec3> points; NxVec3 center(0,0,0); NxVec3 frontAxis = getFrom(cSettings.forwardAxis); // = wheelDesc->downAxis.cross(wheelDesc->wheelAxis); NxVec3 downAxis = getFrom(cSettings.downAxis);//downAxis *=-1.0; // = wheelDesc->downAxis; NxVec3 wheelAxis = getFrom(cSettings.rightAxis); // = wheelDesc->wheelAxis; //frontAxis.normalize(); frontAxis *= cSettings.radius.value; //downAxis.normalize(); downAxis *= cSettings.radius.value; //wheelAxis.normalize(); wheelAxis *= cSettings.height.value; NxReal step; if(cSettings.buildLowerHalfOnly) { if((cSettings.approximation& 0x1) == 0) cSettings.approximation++; step = (NxReal)(NxTwoPi) / (NxReal)(cSettings.approximation*2); } else { step = (NxReal)(NxTwoPi) / (NxReal)(cSettings.approximation); } for(NxU32 i = 0; i < cSettings.approximation; i++) { NxReal iReal; if(cSettings.buildLowerHalfOnly) { iReal = (i > (cSettings.approximation >> 1))?(NxReal)(i+cSettings.approximation):(NxReal)i; } else { iReal = (NxReal)i; } NxReal Sin, Cos; NxMath::sinCos(step * iReal, Sin, Cos); NxVec3 insPoint = (downAxis * -Cos) + (frontAxis * Sin); points.pushBack(insPoint + wheelAxis); points.pushBack(insPoint - wheelAxis); } NxConvexMeshDesc convexDesc; convexDesc.numVertices = points.size(); convexDesc.pointStrideBytes = sizeof(NxVec3); convexDesc.points = &points[0].x; int cf = CF_ComputeConvex; cf |= cSettings.convexFlags; convexDesc.flags |= cf; // Cooking from memory bool status = InitCooking(); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't initiate cooking lib!"); return NULL; } MemoryWriteBuffer buf; int s = convexDesc.isValid(); if(CookConvexMesh(convexDesc, buf)) { //NxConvexShapeDesc convexShapeDesc; shape->meshData = getPhysicSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); shape->localPose.t = center; shape->localPose.M.setColumn(0, NxVec3( 1, 0, 0)); shape->localPose.M.setColumn(1, NxVec3( 0,-1, 0)); shape->localPose.M.setColumn(2, NxVec3( 0, 0, -1)); if(shape->meshData != NULL) { result = true; // NxU32 shapeNumber = actor->getNbShapes(); // result = actor->createShape(convexShapeDesc)->isConvexMesh(); // if (!result) { // xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); // } //wheel->wheelConvex->userData = wheel; } } CloseCooking(); return result; } void pRigidBody::updateCollisionSettings(pCollisionSettings collision,CK3dEntity*shapeReference/* =NULL */) { if (shapeReference==NULL) assert (getMainShape()); NxShape *shape = getSubShape(shapeReference); if (shape) { //---------------------------------------------------------------- // // Update groups mask // NxGroupsMask mask1; mask1.bits0 = collision.groupsMask.bits0; mask1.bits1 = collision.groupsMask.bits1; mask1.bits2 = collision.groupsMask.bits2; mask1.bits3 = collision.groupsMask.bits3; shape->setGroupsMask(mask1); //---------------------------------------------------------------- // // Collisions group // shape->setGroup(collision.collisionGroup); //---------------------------------------------------------------- // // Skin Width // shape->setSkinWidth(collision.skinWidth); } } void pRigidBody::updateCollisionSettings(const pObjectDescr oDescr,CK3dEntity*shapeReference/* =NULL */) { int v = oDescr.version; assert(oDescr.version == pObjectDescr::E_OD_VERSION::OD_DECR_V1); if (shapeReference==NULL) assert (getMainShape()); NxShape *shape = getSubShape(shapeReference); if (shape) { //---------------------------------------------------------------- // // Update groups mask // NxGroupsMask mask1; mask1.bits0 = oDescr.groupsMask.bits0; mask1.bits1 = oDescr.groupsMask.bits1; mask1.bits2 = oDescr.groupsMask.bits2; mask1.bits3 = oDescr.groupsMask.bits3; shape->setGroupsMask(mask1); //---------------------------------------------------------------- // // Collisions group // shape->setGroup(oDescr.collisionGroup); //---------------------------------------------------------------- // // Skin Width // shape->setSkinWidth(oDescr.skinWidth); //---------------------------------------------------------------- // // CCD Setup : // if (oDescr.ccdMeshReference) { NxCCDSkeleton *skeleton = NULL; if (oDescr.ccdFlags && CCD_Shared && GetPMan()->GetContext()->GetObject(oDescr.ccdMeshReference) ) skeleton = GetPMan()->getCCDSkeleton(((CKBeObject*)(GetPMan()->GetContext()->GetObject(oDescr.ccdMeshReference)))); if (skeleton == NULL ) skeleton = pFactory::Instance()->createCCDSkeleton(shapeReference,oDescr.ccdFlags); XString errorString; if (!skeleton){ errorString.Format("Creation of CCD skeleton for %s failed!",GetVT3DObject()->GetName()); xLogger::xLog(ELOGERROR,E_LI_MANAGER,errorString.Str()); return; } shape->setCCDSkeleton(skeleton); //---------------------------------------------------------------- // // update sub mesh info : // pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(shape->userData); if (sInfo){ sInfo->ccdReference = oDescr.ccdMeshReference; sInfo->ccdSkeleton = skeleton; } //---------------------------------------------------------------- // // update actors ccd motion threshold // if(getActor()) getActor()->setCCDMotionThreshold(oDescr.ccdMotionThresold); //NX_SF_DYNAMIC_DYNAMIC_CCD //---------------------------------------------------------------- // // Check we have CCD enabled at all, if not then produce warning // NxPhysicsSDK *sdk = GetPMan()->getPhysicsSDK(); if (sdk) { float ccdParameter = sdk->getParameter(NX_CONTINUOUS_CD); if (ccdParameter < 0.5f) { errorString.Format("CCD Skeleton for %s created successfully but CCD is not enabled.\n Please goto Variable Manager and set ´Continues Collision Detection´ to 1.0f",GetVT3DObject()); xLogger::xLog(ELOGWARNING,E_LI_MANAGER,errorString.Str()); } } } } } int pRigidBody::handleContactPair(NxContactPair* pair,int shapeIndex) { handleContactPairWheel(pair,shapeIndex); return 0; } int pRigidBody::handleContactPairWheel(NxContactPair* pair,int shapeIndex) { if (!hasWheels()) return 0; NxContactStreamIterator i(pair->stream); while(i.goNextPair()) { NxShape * s = i.getShape(shapeIndex); while(i.goNextPatch()) { const NxVec3& contactNormal = i.getPatchNormal(); while(i.goNextPoint()) { const NxVec3& contactPoint = i.getPoint(); //assuming front wheel drive we need to apply a force at the wheels. if (s->is(NX_SHAPE_CAPSULE) && s->userData != NULL) { //assuming only the wheels of the car are capsules, otherwise we need more checks. //this branch can't be pulled out of loops because we have to do a full iteration through the stream NxQuat local2global = s->getActor().getGlobalOrientationQuat(); pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(s->userData); if (!sInfo)return 0; pWheel1* wheel = dynamic_cast<pWheel1*>(sInfo->wheel); if (!wheel)return 0; /* if (!wheel->getWheelFlag(WF_UseWheelShape)) { wheel->contactInfo->otherActor = pair->actors[1-shapeIndex]; wheel->contactInfo->contactPosition = contactPoint; wheel->contactInfo->contactPositionLocal = contactPoint; wheel->contactInfo->contactPositionLocal -= wheel->getActor()->getGlobalPosition(); local2global.inverseRotate(wheel->contactInfo->contactPositionLocal); wheel->contactInfo->contactNormal = contactNormal; if (wheel->contactInfo->otherActor->isDynamic()) { NxVec3 globalV = s->getActor().getLocalPointVelocity( getFrom(wheel->getWheelPos()) ); globalV -= wheel->contactInfo->otherActor->getLinearVelocity(); local2global.inverseRotate(globalV); wheel->contactInfo->relativeVelocity = globalV.x; //printf("%2.3f (%2.3f %2.3f %2.3f)\n", wheel->contactInfo.relativeVelocity, // globalV.x, globalV.y, globalV.z); } else { NxVec3 vel = s->getActor().getLocalPointVelocity( getFrom(wheel->getWheelPos())); local2global.inverseRotate(vel); wheel->contactInfo->relativeVelocity = vel.x; wheel->contactInfo->relativeVelocitySide = vel.z; } //NX_ASSERT(wheel->hasGroundContact()); //printf(" Wheel %x is touching\n", wheel); } */ } } } } //printf("----\n"); return 0; }<file_sep>dofile("ModuleConfig.lua") dofile("ModuleHelper.lua") if _ACTION == "help" then premake.showhelp() return end solution "vtPython" configurations { "Debug", "Release" , "ReleaseDebug" ; "ReleaseRedist" } if _ACTION and _OPTIONS["Dev"] then setfields("location","./".._ACTION.._OPTIONS["Dev"]) end -- The building blocks for vtPythonCaller packageConfig_vtPythonCaller = { Name = "vtPythonCaller", Type = "SharedLib", TargetSuffix = "/BuildingBlocks", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "MODULE_BASE_EXPORTS" }, Files = { DROOT.."SDK/src/Behaviors/**.cpp" ; DROOT.."SDK/src/core/*.cpp" ; DROOT.."SDK/src/Behaviors/*.def" ; F_SHARED_SRC ; DROOT.."build4/**.lua" ; F_BASE_VT_SRC ; F_VT_STD_INC }, Includes = { D_STD_INCLUDES ; D_CORE_INCLUDES ; D_PY.."include" }, Libs = { "ck2" ; "vxmath" ; "user32" ; "kernel32" ;}, LibDirectories = { D_PY.."lib" }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\BuildingBlocks" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\BuildingBlocks" } -- If the command line contains --ExtraDefines="WebPack" , we add "WebPack" to the -- pre-processor directives and also create a package to include the camera building blocks -- as defined in packageConfig_CameraRepack if _OPTIONS["ExtraDefines"] then if _OPTIONS["ExtraDefines"]=="WebPack" then createStaticPackage(packageConfig_CameraRepack) end end createStaticPackage(packageConfig_vtPythonCaller) function onclean() os.rmdir("vs**") end <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorNDisconnectDecl(); CKERROR CreateNDisconnectProto(CKBehaviorPrototype **); int NDisconnect(const CKBehaviorContext& behcontext); CKERROR NDisconnectCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorNDisconnectDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NDisconnect"); od->SetDescription("Disconnects from the server"); od->SetCategory("TNL/Server"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x76531dd9,0x4a317862)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNDisconnectProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } typedef enum BB_OT { BB_O_OUT, BB_O_ERROR }; typedef enum BB_OP { BB_OP_ERROR }; CKERROR CreateNDisconnectProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NDisconnect"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareOutput("Exit On"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(NDisconnect); *pproto = proto; return CK_OK; } int NDisconnect(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterOut *pout = beh->GetOutputParameter(0); XString errorMesg("No network connection !"); ////////////////////////////////////////////////////////////////////////// //connection id : int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { errorMesg = "No network connection !"; pout->SetStringValue(errorMesg.Str()); // Error(beh,"No connection at the moment",BB_OP_ERROR,TRUE,BB_O_ERROR); //xLogger::xLog(ELOGERROR,"No Connection available. See Script :%s --> Building Block : %s",beh->GetOwnerScript()->GetName(),"NSCreate" ); xLogger::xLog(ELOGERROR,E_LI_CONNECTION,"No connection at the moment"); XLOG_BB_INFO; beh->ActivateOutput(0); return 0; } if (!cin->IsServer()) { cin->disconnect(connectionID); } return 0; }<file_sep>#if !defined(EA_C2D3E6DE_B1A5_4f07_B3FA_73F108249451__INCLUDED_) #define EA_C2D3E6DE_B1A5_4f07_B3FA_73F108249451__INCLUDED_ #include "vtPhysXBase.h" #include "pReferencedObject.h" #include "pCallbackObject.h" /** \addtogroup RigidBody @{ */ struct pContactModifyData { float minImpulse; //!< Minimum impulse value that the solver can apply. Normally this should be 0, negative amount gives sticky contacts. float maxImpulse; //!< Maximum impulse value that the solver can apply. Normally this is FLT_MAX. If you set this to 0 (and the min impulse value is 0) then you will void contact effects of the constraint. VxVector error; //!< Error vector. This is the current error that the solver should try to relax. VxVector target; //!< Target velocity. This is the relative target velocity of the two bodies. /** \brief Constraint attachment point for shape 0. If the shape belongs to a dynamic actor, then localpos0 is relative to the body frame of the actor. Alternatively it is relative to the world frame for a static actor. */ VxVector localpos0; /** \brief Constraint attachment point for shape 1. If the shape belongs to a dynamic actor, then localpos1 is relative to the body frame of the actor. Alternatively it is relative to the world frame for a static actor. */ VxVector localpos1; /** \brief Constraint orientation quaternion for shape 0 relative to shape 0s body frame for dynamic actors and relative to the world frame for static actors. The constraint axis (normal) is along the x-axis of the quaternion. The Y axis is the primary friction axis and the Z axis the secondary friction axis. */ VxQuaternion localorientation0; /** \brief Constraint orientation quaternion for shape 1 relative to shape 1s body frame for dynamic actors and relative to the world frame for static actors. The constraint axis (normal) is along the x-axis of the quaternion. The Y axis is the primary friction axis and the Z axis the secondary friction axis. */ VxQuaternion localorientation1; /** \brief Static friction parameter 0. \note 0 does not have anything to do with shape 0/1, but is related to anisotropic friction, 0 is the primary friction axis. */ float staticFriction0; /** \brief Static friction parameter 1. \note 1 does not have anything to do with shape 0/1, but is related to anisotropic friction, 0 is the primary friction axis. */ float staticFriction1; /** \brief Dynamic friction parameter 0. \note 0 does not have anything to do with shape 0/1, but is related to anisotropic friction, 0 is the primary friction axis. */ float dynamicFriction0; /** \brief Dynamic friction parameter 1. \note 1 does not have anything to do with shape 0/1, but is related to anisotropic friction, 0 is the primary friction axis. */ float dynamicFriction1; float restitution; //!< Restitution value. }; struct pCollisionsEntry { VxVector sumNormalForce; VxVector sumFrictionForce; VxVector faceNormal; VxVector point; xU32 faceIndex; float pointNormalForce; /*float patchNormalForce;*/ NxActor *actors[2]; pRigidBody *bodyA; pRigidBody *bodyB; int eventType; float distance; CK_ID shapeEntityA; CK_ID shapeEntityB; pCollisionsEntry(){ bodyB = bodyA = NULL; actors[0]=NULL; actors[1]=NULL; eventType; distance = pointNormalForce = 0.0f; shapeEntityA = shapeEntityB = 0 ; } }; typedef XArray<pCollisionsEntry>CollisionsArray; /** \brief pRigidBody is the main simulation object in the physics SDK. The body is owned by and contained in a pWorld. <h3>Creation</h3> Instances of this class are created by calling #pFbodyy::createBody() and deleted with #NxScene::deleteBody(). See #pObjectDescr for a more detailed description of the parameters which can be set when creating a body. //class MODULE_API pRigidBody : public xEngineObjectAssociation<CK3dEntity*> class MODULE_API pRigidBody : public pStoredObjectAssociation<CK3dEntity*,NxActor*> */ class MODULE_API pRigidBody : public xEngineObjectAssociation<CK3dEntity*>, public pCallbackObject { public: pRigidBody(CK3dEntity* _e); pRigidBody(CK3dEntity* _e,pWorld *world); virtual ~pRigidBody(){} void test(); pObjectDescr *mInitialDescription; pObjectDescr * getInitialDescription() const { return mInitialDescription; } void setInitialDescription(pObjectDescr * val) { mInitialDescription = val; } void onICRestore(CK3dEntity* parent,pRigidBodyRestoreInfo *restoreInfo); bool hasBrokenJoint; int onJointBreak(pBrokenJointEntry *entry); /************************************************************************************************/ /** @name Callback handler */ //@{ bool onSubShapeTransformation(bool fromPhysicToVirtools=true,bool position=true,bool rotation=true,CK3dEntity*parent=NULL,bool children=true); bool onMove(bool position,bool rotation,VxVector pos,VxQuaternion quad); void processScriptCallbacks(); //---------------------------------------------------------------- // // collision notification // void onContactNotify(pCollisionsEntry *collisionData); void setContactScript(int behaviorID,int eventMask); /** \brief Sets the force threshold for contact reports. See #getContactReportThreshold(). The actor must be dynamic. \param[in] threshold Force threshold for contact reports. - <b>Range:</b> (0,inf) @see getContactReportThreshold getContactReportFlags pContactPairFlag */ void setContactReportThreshold(float threshold); /** \brief Retrieves the force threshold for contact reports. The contact report threshold is a force threshold. If the force between two actors exceeds this threshold for either of the two actors, a contact report will be generated according to the union of both body' contact report threshold flags. See #getContactReportFlags(). The body must be dynamic. The threshold used for a collision between a dynamic actor and the static environment is the threshold of the dynamic actor, and all contacts with static actors are summed to find the total normal force. \return Force threshold for contact reports. @see setContactReportThreshold getContactReportFlags pContactPairFlag */ float getContactReportThreshold(); void setContactReportFlags(pContactPairFlags flags); int getContactReportFlags(); ////////////////////////////////////////////////////////////////////////// // // joint break events // void setJointBreakScript(int behaviorID,CK3dEntity *shapeReference = NULL); //---------------------------------------------------------------- // // trigger notification // void setTriggerScript(int behaviorID,int eventMask,CK3dEntity *shapeReference = NULL); int onTrigger(pTriggerEntry *report); //---------------------------------------------------------------- // // contact modification // void setContactModificationScript(int behaviorID); bool onContactConstraint(int& changeFlags,CK3dEntity *sourceObject,CK3dEntity *otherObject,pContactModifyData *data); //---------------------------------------------------------------- // // raycast hit // virtual void setRayCastScript(int val); virtual bool onRayCastHit(NxRaycastHit *report); //@} /************************************************************************************************/ /** @name Collision */ //@{ void setTriggerFlags(pTriggerFlags flags,CKBeObject *shapeReference=NULL); pTriggerFlags getTriggerFlags(CKBeObject *shapeReference=NULL); int handleContactPair(NxContactPair* pair,int shapeIndex); int handleContactPairWheel(NxContactPair* pair,int shapeIndex); /** \brief Sets 128-bit mask used for collision filtering. See comments for ::pGroupsMask <b>Sleeping:</b> Does <b>NOT</b> wake the associated body up automatically. \param[in] shape Reference The sub shape reference object. Leave blank to set the bodies initial shapes groups mask. \param[in] mask The group mask to set for the shape. @see getGroupsMask() */ void setGroupsMask(CK3dEntity *shapeReference,const pGroupsMask& mask); pGroupsMask getGroupsMask(CK3dEntity *shapeReference); //@} /************************************************************************************************/ /** @name Velocity */ //@{ /** \brief Retrieves the angular velocity of a rigid body. \return Vector @see setAngularVelocity() getLinearVelocity() \warning The body must be dynamic. */ VxVector getAngularVelocity()const; /** \brief Retrieves the linear velocity of a rigid body. \return Vector \sa setLinearVelocity() getAngularVelocity() \warning The body must be dynamic. */ VxVector getLinearVelocity()const; /** \brief Retrieves the maximum angular velocity permitted for this body. \return float \sa setMaxAngularVelocity \warning The body must be dynamic. */ float getMaxAngularSpeed()const; /** \brief Lets you set the maximum angular velocity permitted for this body. Because for various internal computations, very quickly rotating bodies introduce error into the simulation, which leads to undesired results. With PhysicManager::setParameter(EX_MAX_ANGULAR_VELOCITY) you can set the default maximum velocity for bodies created after the call. Bodies' high angular velocities are clamped to this value. However, because some bodies, such as car wheels, should be able to rotate quickly, you can override the default setting on a per-body basis with the below call. Note that objects such as wheels which are approximated with spherical or other smooth collision primitives can be simulated with stability at a much higher angular velocity than, say, a box that has corners. Note: The angular velocity is clamped to the set value <i>before</i> the solver, which means that the limit may still be momentarily exceeded. \param[in] val Max allowable angular velocity for body. <b>Range:</b> (0,inf) \sa getMaxAngularVelocity() \warning The body must be dynamic. */ void setMaxAngularSpeed(float val); /** \brief Computes the velocity of a point given in body local coordinates as if it were attached to the body and moving with it. \param[in] point Point we wish to determine the velocity of, defined in the body local frame. <b>Range:</b> position vector \return The velocity, in the global frame, of the point. \sa getLocalPointVelocity() \warning The body must be dynamic. */ VxVector getPointVelocity(const VxVector& point)const; /** \brief Computes the velocity of a point given in body local coordinates as if it were attached to the body and moving with it. \param[in] point Point we wish to determine the velocity of, defined in the body local frame. <b>Range:</b> position vector \return The velocity, in the global frame, of the point. \sa getPointVelocity() \warning The body must be dynamic. */ VxVector getLocalPointVelocity(const VxVector& point)const; /** \brief Sets the angular velocity of the body. \note Note that if you continuously set the angular velocity of an body yourself, forces such as friction will not be able to rotate the body, because forces directly influence only the velocity/momentum. \param[in] angVel New angular velocity of body. <b>Range:</b> angular velocity vector \sa getAngularVelocity() setLinearVelocity() \warning The body must be dynamic.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping. */ void setAngularVelocity(const VxVector& angVel); /** \brief Sets the linear velocity of the body. \note Note that if you continuously set the velocity of an body yourself, forces such as gravity or friction will not be able to manifest themselves, because forces directly influence only the velocity/momentum of an body. \param[in] linVel New linear velocity of body. <b>Range:</b> velocity vector \sa getLinearVelocity() setAngularVelocity() \warning The body must be dynamic.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping. */ void setLinearVelocity(const VxVector& linVel); //@} /************************************************************************************************/ /** @name Mass Manipulation */ //@{ /** \brief The setCMassOffsetLocal*() methods set the pose of the center of mass relative to the actor. See ::setCMassOffsetLocalPose() for more information. \note Setting an unrealistic center of mass which is a long way from the body can make it difficult for the SDK to solve constraints. Perhaps leading to instability and jittering bodies. The actor must be dynamic. <b>Sleeping:</b> This call wakes the actor if it is sleeping. \param[in] vec Mass frame offset relative to the actor frame. <b>Range:</b> position vector @see setCMassOffsetLocalPose() setCMassOffsetLocalOrientation() setCMassOffsetGlobalPose() */ //void setCMassOffsetLocalPosition(VxVector vec); /** \brief The setCMassOffsetGlobal*() methods set the pose of the center of mass relative to world space. See ::setCMassOffsetGlobalPose() for more information. \note Setting an unrealistic center of mass which is a long way from the body can make it difficult for the SDK to solve constraints. Perhaps leading to instability and jittering bodies. The rigid body must be dynamic. <b>Sleeping:</b> This call wakes the rigid body if it is sleeping. \param[in] vec Mass frame offset relative to the global frame. <b>Range:</b> position vector @see setCMassOffsetGlobalPose() setCMassOffsetGlobalOrientation() */ void setCMassOffsetGlobalPosition(VxVector vec); /** \brief The setCMassGlobal*() methods move the rigid body by setting the pose of the center of mass. See ::setCMassGlobalPose() for more information. The rigid body must be dynamic. <b>Sleeping:</b> This call wakes the rigid body if it is sleeping. \param[in] vec rigid bodys new position, from the transformation of the mass frame to the global frame. <b>Range:</b> position vector @see setCMassGlobalPose() setCMassGlobalOrientation() getCMassLocalPose() */ void setCMassGlobalPosition(VxVector vec); /** \brief The getCMassLocal*() methods retrieve the center of mass pose relative to the rigid body. The rigid body must be dynamic. \return The center of mass position relative to the rigid body. @see getCMassLocalPose() getCMassLocalOrientation() getCMassGlobalPose() */ VxVector getCMassLocalPosition(); /** \brief The getCMassGlobal*() methods retrieve the center of mass pose in world space. The rigid body must be dynamic. \return The position of the center of mass relative to the global frame. @see getCMassGlobalPose() getCMassGlobalOrientation() getCMassLocalPose() */ VxVector getCMassGlobalPosition(); /** \brief Sets the inertia tensor, using a parameter specified in mass space coordinates. Note that such matrices are diagonal -- the passed vector is the diagonal. If you have a non diagonal world/rigid body space inertia tensor(3x3 matrix). Then you need to diagonalize it and set an appropriate mass space transform. See #setCMassOffsetLocalPose(). The rigid body must be dynamic. <b>Sleeping:</b> Does <b>NOT</b> wake the rigid body up automatically. \param[in] m New mass space inertia tensor for the rigid body. <b>Range:</b> inertia vector @see NxBodyDesc.massSpaceInertia getMassSpaceInertia() setMass() setCMassOffsetLocalPose() */ void setMassSpaceInertiaTensor(VxVector m); /** \brief Retrieves the diagonal inertia tensor of the rigid body relative to the mass coordinate frame. This method retrieves a mass frame inertia vector. If you want a global frame inertia tensor(3x3 matrix), then see #getGlobalInertiaTensor(). The rigid body must be dynamic. \return The mass space inertia tensor of this rigid body. @see NxBodyDesc.massSpaceInertia setMassSpaceInertiaTensor() setMass() CMassOffsetLocalPose() */ VxVector getMassSpaceInertiaTensor(); /** \brief Retrieves the mass of the body. Zero represents no damping. The damping coefficient must be nonnegative. \param[in] angDamp Angular damping coefficient. <b>Range:</b> [0,inf) \sa setMass() \warning Static bodies will always return 0. */ float getMass(); /** \brief Sets the mass of a dynamic body. The mass must be positive and the body must be dynamic. setMass() does not update the inertial properties of the body, to change the inertia tensor use setMassSpaceInertiaTensor() or updateMassFromShapes(). <b>Sleeping:</b> Does <b>NOT</b> wake the body up automatically. \param[in] mass New mass value for the body. <b>Range:</b> (0,inf) \sa setMass() \warning The mass must be positive and the body must be dynamic. */ void setMass(float mass,CKBeObject *shapeReference=NULL); /** \brief The setCMassOffsetLocal*() methods set the pose of the center of mass relative to the body. Methods that automatically compute the center of mass such as updateMassFromShapes() as well as computing the mass and inertia using the bodies shapes, will set this pose automatically. \note Setting an unrealistic center of mass which is a long way from the body can make it difficult for the SDK to solve constraints. Perhaps leading to instability and jittering bodies. <b>Sleeping:</b> This call wakes the body if it is sleeping. \param[in] vec Mass frame offset relative to the body frame. <b>Range:</b> position vector \warning The body must be dynamic. */ void setCMassOffsetLocalPosition(VxVector offset); /** \brief Recomputes a dynamic body's mass properties from its shapes Given a constant density or total mass, the bodies mass properties can be recomputed using the shapes attached to the body. If the body has no shapes, then only the totalMass parameter can be used. If all shapes in the body are trigger shapes (non-physical), the call will fail. The mass of each shape is either the shape's local density (as specified in the #NxShapeDesc; default 1.0) multiplied by the shape's volume or a directly specified shape mass. The inertia tensor, mass frame and center of mass will always be recomputed. If there are no shapes in the body, the mass will be totalMass, and the mass frame will be set to the center of the body. If you supply a non-zero total mass, the body's mass and inertia will first be computed as above and then scaled to fit this total mass. If you supply a non-zero density, the body's mass and inertia will first be computed as above and then scaled by this fbody. Either totalMass or density must be non-zero. \param[in] density Density scale fbody of the shapes belonging to the body. <b>Range:</b> [0,inf) \param[in] totalMass Total mass of the body(or zero). <b>Range:</b> [0,inf) \sa setMass() \warning The body must be dynamic.<br> <b>Sleeping:</b> Does <b>NOT</b> wake the body up automatically. */ int updateMassFromShapes( float density, float totalMass ); //@} /************************************************************************************************/ /** @name Forces */ //@{ /** \brief Applies a force (or impulse) defined in the global coordinate frame to the body. Methods that automatically compute the center of mass such as updateMassFromShapes() as well as computing the mass and inertia using the bodies shapes, will set this pose automatically. \param[in] force Force/Impulse to apply defined in the global frame. <b>Range:</b> force vector \param[in] mode The mode to use when applying the force/impulse(see #ForceMode).Default = #FM_Force. \param[in] wakeUp Specify if the call should wake up the body.Default = true. \sa addForceAtPos() addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() \warning The body must be dynamic.<br> <b>This will not induce a torque</b>.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping and the wakeup parameter is true (default). */ void addForce(const VxVector& force,ForceMode mode=FM_Force,bool wakeUp=true); /** \brief Applies a force (or impulse) defined in the global coordinate frame, acting at a particular point in global coordinates, to the body. Note that if the force does not act along the center of mass of the body, this will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. \param[in] force Force/impulse to add, defined in the global frame. <b>Range:</b> force vector \param[in] point Position in the global frame to add the force at. <b>Range:</b> position vector \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) \param[in] wakeUp Specify if the call should wake up the body. \sa ForceMode \sa addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() addLocalForce() \warning The body must be dynamic.<br> <b>This will not induce a torque</b>.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping and the wakeup parameter is true (default). */ void addForceAtPos(const VxVector& force,const VxVector& point,ForceMode mode=FM_Force,bool wakeUp=true); /** \brief Applies a force (or impulse) defined in the global coordinate frame, acting at a particular point in local coordinates, to the body. \note Note that if the force does not act along the center of mass of the body, this will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. ::ForceMode determines if the force is to be conventional or impulsive. \param[in] force Force/impulse to add, defined in the global frame. <b>Range:</b> force vector \param[in] point Position in the local frame to add the force at. <b>Range:</b> position vector \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) \param[in] wakeUp Specify if the call should wake up the body. \sa ForceMode \sa addForceAtPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() addLocalForce() \warning The body must be dynamic.<br> <b>This will not induce a torque</b>.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping and the wakeup parameter is true (default). */ void addForceAtLocalPos(const VxVector& force,const VxVector& point,ForceMode mode=FM_Force,bool wakeUp=true); /** \brief Applies a force (or impulse) defined in the body local coordinate frame to the body. ::ForceMode determines if the force is to be conventional or impulsive. \param[in] force Force/Impulse to apply defined in the local frame. <b>Range:</b> force vector \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) \param[in] wakeUp Specify if the call should wake up the body. \sa ForceMode \sa addForceAtPos() addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() \warning The body must be dynamic.<br> <b>This will not induce a torque</b>.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping and the wakeup parameter is true (default). */ void addLocalForce(const VxVector& force,ForceMode mode=FM_Force,bool wakeUp=true); /** \brief Applies a force (or impulse) defined in the body local coordinate frame, acting at a particular point in global coordinates, to the body. \note Note that if the force does not act along the center of mass of the body, this will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. ::ForceMode determines if the force is to be conventional or impulsive. \param[in] force Force/impulse to add, defined in the local frame. <b>Range:</b> force vector \param[in] point Position in the global frame to add the force at. <b>Range:</b> position vector \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) \param[in] wakeUp Specify if the call should wake up the body. \sa ForceMode \sa addForceAtPos() addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() \warning The body must be dynamic.<br> <b>This will not induce a torque</b>.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping and the wakeup parameter is true (default). */ void addLocalForceAtPos(const VxVector& force,const VxVector& point,ForceMode mode=FM_Force,bool wakeUp=true); /** \brief Applies a force (or impulse) defined in the body local coordinate frame, acting at a particular point in local coordinates, to the body. \note Note that if the force does not act along the center of mass of the body, this will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. ::ForceMode determines if the force is to be conventional or impulsive. \param[in] force Force/impulse to add, defined in the local frame. <b>Range:</b> force vector \param[in] point Position in the local frame to add the force at. <b>Range:</b> position vector \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) \param[in] wakeUp Specify if the call should wake up the body. \sa ForceMode \sa addForceAtPos() addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() \warning The body must be dynamic.<br> <b>This will not induce a torque</b>.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping and the wakeup parameter is true (default). */ void addLocalForceAtLocalPos(const VxVector& force,const VxVector& point,ForceMode mode=FM_Force,bool wakeUp=true); /** \brief Applies an impulsive torque defined in the global coordinate frame to the body. ::ForceMode determines if the force is to be conventional or impulsive. \param[in] torque Torque to apply defined in the global frame. \param[in] mode The mode to use when applying the force/impulse(see #ForceMode). \param[in] wakeUp Specify if the call should wake up the body. \sa addLocalTorque() addForce() \warning The body must be dynamic.<br> <b>This will not induce a torque</b>.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping and the wakeup parameter is true (default). */ void addTorque(const VxVector& torque,ForceMode mode=FM_Force,bool wakeUp=true); /** \brief Applies an impulsive torque defined in the body local coordinate frame to the body. ::ForceMode determines if the force is to be conventional or impulsive. \param[in] torque Torque to apply defined in the local frame. \param[in] mode The mode to use when applying the force/impulse(see #ForceMode). \param[in] wakeUp Specify if the call should wake up the body. \sa addLocalTorque() addForce() \warning The body must be dynamic.<br> <b>This will not induce a torque</b>.<br> <b>Sleeping:</b> This call wakes the body if it is sleeping and the wakeup parameter is true (default). */ void addLocalTorque(const VxVector& torque,ForceMode mode=FM_Force,bool wakeUp=true); //@} /************************************************************************************************/ /** @name Momentum */ //@{ /** \brief Sets the angular momentum of the body. \note Note that if you continuously set the linear momentum of an body yourself, forces such as gravity or friction will not be able to manifest themselves, because forces directly influence only the velocity/momentum of a body. \param[in] angMoment New angular momentum. <b>Range:</b> angular momentum vector \sa getAngularMomentum() \warning The body must be dynamic.<br> */ void setAngularMomentum(const VxVector& angMoment); /** \brief Sets the linear momentum of the body. \note Note that if you continuously set the linear momentum of an body yourself, forces such as gravity or friction will not be able to manifest themselves, because forces directly influence only the velocity/momentum of a body. \param[in] linMoment New linear momentum. <b>Range:</b> momentum vector \sa getLinearMomentum() \warning The body must be dynamic.<br> */ void setLinearMomentum(const VxVector& linMoment); /** \brief Retrieves the angular momentum of an body. The angular momentum is equal to the angular velocity times the global space inertia tensor. \return The angular momentum for the body. \sa setLinearMomentum() getAngularMomentum() \warning The body must be dynamic.<br> */ VxVector getAngularMomentum()const; /** \brief Retrieves the linear momentum of an body. The momentum is equal to the velocity times the mass. \return The linear momentum for the body. \sa setLinearMomentum() getAngularMomentum() \warning The body must be dynamic.<br> */ VxVector getLinearMomentum()const; //@} /************************************************************************************************/ /** @name Pose */ //@{ /** \brief Sets a dynamic body's position in the world. \param[in] pos New position for the bodies frame relative to the global frame. <b>Range:</b> position vector \param[in] subShapeReference Reference object specifing a subshape for the case the body is a compound object. Must be a mesh or an 3D-entity. Default = Null \sa getPosition() */ void setPosition(const VxVector& pos,CK3dEntity *subShapeReference=NULL); /** \brief Sets a dynamic body's orientation in the world. \param[in] rot New orientation for the bodies frame. \param[in] subShapeReference Reference object specifying a sub shape for the case the body is a compound object. Must be a mesh or an 3D-entity. Default = Null \sa getLinearMomentum() setAngularMomentum() */ void setRotation(const VxQuaternion& rot,CK3dEntity *subShapeReference=NULL); //@} /************************************************************************************************/ /** @name Collision */ //@{ /** \brief Enables/disable collision detection. I.e. the body will not collide with other objects. Please note that you might need to wake the body up if it is sleeping, this depends on the result you wish to get when using this flag. (If a body is asleep it will not start to fall through objects unless you activate it). \param[in] enable. Flag to determining collisions response for the body. to collision detect with each other. \param[in] subShapeReference Reference object specifing a subshape for the case the body is a compound object. Must be a mesh or an 3D-entity. Default = Null \Note : Also excludes the body from overlap tests! \sa isCollisionEnabled() <b>Sleeping:</b> Does <b>NOT</b> wake the associated body up automatically. */ void enableCollision(bool enable,CK3dEntity* subShapeReference=NULL); bool isCollisionEnabled(CK3dEntity* subShapeReference=NULL) ; void enableCollisionsNotify(bool enable); bool isCollisionsNotifyEnabled(); void enableContactModification(bool enable); void enableCollisionForceCalculation(bool enable,CK3dEntity* subShapeReference=NULL); void enableTriggerShape(bool enable,CK3dEntity* subShapeReference=NULL); bool isTriggerShape(CK3dEntity* subShapeReference=NULL); /** \brief Sets the collisions group the body belongs too. \param[in] index The new group index. Default group is 0. Maximum possible group is 31.Collision groups are sets of shapes which may or may not be set to collision detect with each other. \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \note If you pass a sub shape reference then its only setting the group on the sub shape and not for all sub shapes. \sa getCollisionsGroup() \warning The body must be dynamic.<br> <b>Sleeping:</b> Does <b>NOT</b> wake the associated body up automatically. */ void setCollisionsGroup(int index,CK3dEntity* subShapeReference=NULL); /** \brief Retrieves the collisions group which this body or a sub shape of it is part of. \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \return The collision group this body or sub shape belongs to. \sa setCollisionsGroup() \warning The body must be dynamic.<br> */ int getCollisionsGroup(CK3dEntity* subShapeReference=NULL); //@} /************************************************************************************************/ /** @name Shape */ //@{ /** \brief Updates the box dimension of the initial shape or a sub shape. \param[in] dimension New dimension. <b>Range:</b> dimension vector \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \sa getBoxDimensions() \warning The call doesnt updates the bodies mass.Use updateMassFromShapes()<br> */ void setBoxDimensions(const VxVector&dimension,CKBeObject* subShapeReference=NULL); /** \brief Retrieves the box dimension of the initial shape or sub shape. \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \sa setBoxDimensions() */ VxVector getBoxDimensions(CKBeObject* subShapeReference=NULL); /** \brief Updates the radius of the initial shape or a sub shape. \param[in] radius New radius. \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \sa getSphereRadius() \warning The call doest updates the bodies mass.Use updateMassFromShapes()<br> */ void setSphereRadius(float radius,CKBeObject* subShapeReference=NULL); /** \brief Retrieves the radius of the initial shape or sub shape. \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \sa setSphereRadius() . */ float getSphereRadius(CKBeObject* subShapeReference=NULL); /** \brief Updates the capsule parameter of the initial shape or a sub shape. \param[in] radius New radius. \param[in] length New length. \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \sa getCapsuleDimensions() \warning The call doesnt updates the bodies mass.Use updateMassFromShapes()<br> */ void setCapsuleDimensions(float radius,float length,CKBeObject* subShapeReference=NULL); /** \brief Retrieves the capsule parameters of the initial shape or sub shape. \param[out] radius The radius of the capsule. \param[out] length The length of the capsule. \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \sa setCapsuleDimensions() . */ void getCapsuleDimensions(float& radius,float& length,CKBeObject* subShapeReference=NULL); /** \brief Retrieves the hull type of the initial shape or sub shape. \return The hull type. \param[in] subShapeReference Sub shape reference. Default = Null. */ HullType getShapeType(CKBeObject* subShapeReference=NULL); /** \brief Retrieves the skin width of the initial shape or a sub shape. \return The skin with. \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \sa setSkinWidth() */ float getSkinWidth(CKBeObject* subShapeReference=NULL); /** \brief Updates the skin width of the initial shape or a sub shape. \param[in] skinWidth The new skin width. <b>Range:</b> (0,inf) \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. \sa setSkinWidth() \warning <b>Sleeping:</b> Does <b>NOT</b> wake the associated body up automatically. */ void setSkinWidth(const float skinWidth,CKBeObject* subShapeReference=NULL); //@} /************************************************************************************************/ /** @name Optimization */ //@{ /** \brief The solver iteration count determines how accurately joints and contacts are resolved. <br> If you are having trouble with jointed bodies oscillating and behaving erratically, then setting a higher solver iteration count may improve their stability. \param[in] count Number of iterations the solver should perform for this body. <br> - <b>Range:</b> [1,255] */ void setSolverIterationCount(int count); /** \brief Assigns dynamic bodies a dominance group identifier.<br> The dominance group is a 5 bit group identifier (legal range from 0 to 31). The #pWorld::setDominanceGroupPair() lets you set certain behaviors for pairs of dominance groups. By default every body is created in group 0. Static bodies must stay in group 0; thus you can only call this on dynamic bodys. <b>Sleeping:</b> Changing the dominance group does <b>NOT</b> wake the body up automatically. @see getDominanceGroup() NxScene::setDominanceGroupPair() */ void setDominanceGroup(int dominanceGroup); /** \brief Retrieves the value set with setDominanceGroup().<br> \return The dominance group of this body. @see setDominanceGroup() pWorld::setDominanceGroupPair() */ int getDominanceGroup() const; /** \brief Returns the linear velocity below which an body may go to sleep.<br> Bodies whose linear velocity is above this threshold will not be put to sleep. The body must be dynamic. @see isSleeping \return The threshold linear velocity for sleeping. @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepLinearVelocity() setSleepEnergyThreshold() getSleepEnergyThreshold() */ float getSleepLinearVelocity() const ; /** \brief Sets the linear velocity below which an body may go to sleep.<br> Bodies whose linear velocity is above this threshold will not be put to sleep. If the threshold value is negative, the velocity threshold is set using the NxPhysicsSDK's NX_DEFAULT_SLEEP_LIN_VEL_SQUARED parameter. Setting the sleep angular/linear velocity only makes sense when the NX_BF_ENERGY_SLEEP_TEST is not set. In version 2.5 and later a new method is used by default which uses the kinetic energy of the body to control sleeping. The body must be dynamic. \param[in] threshold Linear velocity below which an body may sleep. <b>Range:</b> (0,inf] @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepEnergyThreshold() getSleepEnergyThreshold() */ void setSleepLinearVelocity(float threshold); /** \brief Returns the angular velocity below which an body may go to sleep.<br> Bodies whose angular velocity is above this threshold will not be put to sleep. The body must be dynamic. \return The threshold angular velocity for sleeping. @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepAngularVelocity() setSleepEnergyThreshold() getSleepEnergyThreshold() */ float getSleepAngularVelocity() const; /** \brief Sets the angular velocity below which an body may go to sleep.<br> Bodies whose angular velocity is above this threshold will not be put to sleep. If the threshold value is negative, the velocity threshold is set using the NxPhysicsSDK's NX_DEFAULT_SLEEP_LIN_VEL_SQUARED parameter. Setting the sleep angular/linear velocity only makes sense when the NX_BF_ENERGY_SLEEP_TEST is not set. In version 2.5 and later a new method is used by default which uses the kinetic energy of the body to control sleeping. The body must be dynamic. \param[in] threshold Angular velocity below which an body may go to sleep. - <b>Range:</b> (0,inf] @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepLinearVelocity() setSleepEnergyThreshold() getSleepEnergyThreshold() */ void setSleepAngularVelocity(float threshold); /** \brief Sets the energy threshold below which an body may go to sleep.<br> Bodies whose kinematic energy is above this threshold will not be put to sleep. If the threshold value is negative, the velocity threshold is set using the NxPhysicsSDK's NX_DEFAULT_SLEEP_ENERGY parameter. Setting the sleep energy threshold only makes sense when the NX_BF_ENERGY_SLEEP_TEST is set. There are also other types of sleeping that uses the linear and angular velocities directly instead of the energy. The body must be dynamic. \param[in] threshold Energy below which an actor may go to sleep. <br> - <b>Range:</b> (0,inf] @see isGroupSleeping() isSleeping() getSleepEnergyThreshold() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepLinearVelocity() setSleepAngularVelocity() */ void setSleepEnergyThreshold(float threshold); /** \brief Returns the energy below which an body may go to sleep.<br> Bodies whose energy is above this threshold will not be put to sleep. The body must be dynamic. \return The energy threshold for sleeping. @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepAngularVelocity() */ float getSleepEnergyThreshold() const; /** \brief Retrieves the linear damping coefficient.<br> \return The linear damping coefficient associated with this body. \sa getAngularDamping() \warning The body must be dynamic. */ float getLinearDamping()const; /** \brief Retrieves the angular damping coefficient.<br> \return The angular damping coefficient associated with this body. \sa setAngularDamping() \warning The body must be dynamic. */ float getAngularDamping()const; /** \brief Sets the linear damping coefficient.<br> Zero represents no damping. The damping coefficient must be nonnegative. \param[in] linDamp Linear damping coefficient. <b>Range:</b> [0,inf) \sa getLinearDamping() \warning The body must be dynamic. */ void setLinearDamping(float linDamp); /** \brief Sets the angular damping coefficient.<br> Zero represents no damping. The damping coefficient must be nonnegative. \param[in] angDamp Angular damping coefficient. <b>Range:</b> [0,inf) \sa getLinearDamping() \warning The body must be dynamic. */ void setAngularDamping(float angDamp); //@} /************************************************************************************************/ /** @name Conditions */ //@{ /** \brief Sets the body to kinematic. \param[in] enabled Enable kinematic mode. <b>Range:</b> (0,inf) \sa isKinematic() */ void setKinematic(bool enabled); /** \brief Retrieves the bodies kinematic state. \return the kinematic state. */ bool isKinematic()const; /** \brief Checks whether the body is affected by the worlds gravity. \return Is affected by gravity. \sa enableGravity() */ bool isAffectedByGravity()const; /** \brief Enables gravity on the body. \param[in] enable The gravity state. \sa isAffectedByGravity() */ void enableGravity(bool enable); //@} /************************************************************************************************/ /** @name Sleeping */ //@{ /** \brief Checks whether the body is in a sleeping state. \return True if sleeping. \sa setSleeping() */ bool isSleeping()const; /** \brief Forces the body to sleep. The body will stay asleep until the next call to simulate, and will not wake up until then even when otherwise it would (for example a force is applied to it). It can however wake up during the next simulate call. \param[in] sleeping The sleeping state. \sa setSleeping() \warning The body must be dynamic.<br> */ void setSleeping(bool sleeping); /** \brief Wakes up the body if it is sleeping. The wakeCounterValue determines how long until the body is put to sleep, a value of zero means that the body is sleeping. wakeUp(0) is equivalent to NxActor::putToSleep(). \param[in] wakeCounterValue New sleep counter value. Default = (20.0f*0.02f) . <b>Range:</b> [0,inf] \sa setSleeping() isSleeping() \warning The body must be dynamic.<br> */ void wakeUp(float wakeCounterValue=pSLEEP_INTERVAL); //@} /************************************************************************************************/ /** @name Sub shapes */ //@{ /* * \brief Adds an additional shape to the body. * * * * \return int * \param CKMesh * mesh * \param pObjectDescr objectDescr * \param CK3dEntity * srcRefEntity * \param VxVector localPosition * \param VxQuaternion localRotation * \note * \sa * \warning */ int addSubShape(CKMesh *mesh,pObjectDescr& objectDescr,CK3dEntity*srcRefEntity=NULL,VxVector localPosition=VxVector(),VxQuaternion localRotation=VxQuaternion()); int addCollider(pObjectDescr objectDescr,CK3dEntity*srcRefEntity); int removeSubShape(CKBeObject *reference,float newensity=0.0f,float totalMass=0.0f); NxShape *_getSubShape(CK_ID meshID); NxShape *_getSubShapeByEntityID(CK_ID id); bool isSubShape(CKBeObject *object); int updateSubShapes(bool fromPhysicToVirtools= true,bool position=true,bool rotation=true,CK3dEntity *childObject=NULL); int updateSubShape(bool fromPhysicToVirtools=true,bool position=true,bool rotation=true,CK3dEntity *childObject=NULL,bool hierarchy=true); NxShape * getMainShape() const { return mMainShape; } void setMainShape(NxShape * val) { mMainShape = val; } NxShape *getShapeByIndex(int index=0); NxShape* getSubShape(CK3dEntity*shapeReference=NULL); //@} int _initMainShape(const pObjectDescr oDescr,NxActorDesc&bodyDesc); int _initMainShape(const pObjectDescr oDescr,NxActorDesc* bodyDesc); bool isWheel(CKBeObject *object); bool isVehicle(CKBeObject *object); bool isCharacter(CKBeObject *object); int getNbJoints(); pJoint* getJointAtIndex(int index); pJoint* getJoint(CK3dEntity*_b,JType type); void deleteJoint(pJoint*joint); void deleteJoint(CK3dEntity*_b,JType type); /************************************************************************************************/ /** @name Serialization */ //@{ void readFrom(NXU::NxActorDesc *desc,int flags); void writeTo(const char *filename,int flags); //@} int getFlags(); void recalculateFlags(int _flags); void updateFlags(int _flags,CK3dEntity*shapeReference=NULL); void setFlags(int _flags); int getHullType(); void setHullType(int _type); ////////////////////////////////////////////////////////////////////////// //geometry related : bool isValid()const; ////////////////////////////////////////////////////////////////////////// //maintainence : CK3dEntity* GetVT3DObject(); void SetVT3DObject(CK3dEntity* _obj); CK_ID getEntID() const { return mEntID; } void setEntID(CK_ID val) { mEntID = val; } void destroy(); ////////////////////////////////////////////////////////////////////////// //optimization settings : pSleepingSettings* getSleepingSettings() { return m_SleepingSettings; } void setSleepingSettings(pSleepingSettings* val) { m_SleepingSettings = val; } void Init(); void retrieveSettingsFromAttribute(); void UpdateGeometry(int flags=0); ////////////////////////////////////////////////////////////////////////// //pivot manipulation,no affects to mass ! void setLocalShapePosition(VxVector relative,CK3dEntity*shapeReference=NULL); //void SetPivotOrientation(VxQuaternion relative); pWorld * getWorld() const { return m_pWorld; } void setWorld(pWorld * val) { m_pWorld = val; } void clean(int flags=0); ////////////////////////////////////////////////////////////////////////// //joint related pJoint* isConnected(CK3dEntity*); pJoint* isConnected(CK3dEntity*,int type); int JGetNumJoints(); JointListType& GetJoints(){ return m_Joints; } ////////////////////////////////////////////////////////////////////////// //composite geometries VxVector getMassOffset() const { return massOffset; } void setMassOffset(VxVector val) { massOffset = val; } void setPivotOffset(VxVector val) { pivotOffset = val; } VxVector getPivotOffset(CK3dEntity*shapeReference); void translateLocalShapePosition(VxVector vec); float getDensity() const { return mDensity; } void setDensity(float val) { mDensity = val; } ////////////////////////////////////////////////////////////////////////// //prototype : xBitSet& getDataFlags() { return mDataFlags; } void setDataFlags(xBitSet val) { mDataFlags = val; } void checkDataFlags(); void checkForOptimization(); void updateOptimizationSettings(pOptimization optimization); void checkForCCDSettings(CK3dEntity *shapeReference=NULL); void updateCCDSettings(pCCDSettings ccd,CK3dEntity*shapeReference=NULL); void updateCollisionSettings(const pObjectDescr oDescr,CK3dEntity*shapeReference=NULL); void updateCollisionSettings(pCollisionSettings collision,CK3dEntity*shapeReference=NULL); void updatePivotSettings(pPivotSettings pivot,CK3dEntity*shapeReference=NULL); void updateMaterialSettings(pMaterial& material,CK3dEntity*shapeReference=NULL); void updateMassSettings(pMassSettings massSettings); void saveToAttributes(pObjectDescr* oDescr); ////////////////////////////////////////////////////////////////////////// //Surface : void InitSurfaceMaterials(); ////////////////////////////////////////////////////////////////////////// /************************************************************************/ /* Material */ /********************************* ***************************************/ pMaterial& getShapeMaterial(CK3dEntity *shapeReference=NULL); void setShapeMaterial(pMaterial&material,CK3dEntity*shapeReference=NULL); void setShapeMaterialFrom(CKBeObject*src,CK3dEntity*shapeReference=NULL); NxMaterial* getMaterial() const { return mMaterial; } void setMaterial(NxMaterial* val) { mMaterial = val; } NxActor* getActor() const { return mActor; } void setActor(NxActor* val) { mActor = val; } /************************************************************************/ /* */ /************************************************************************/ pCloth *mCloth; pCloth * getCloth() const { return mCloth; } void setCloth(pCloth * val) { mCloth = val; } bool isDeformable(); ////////////////////////////////////////////////////////////////////////// void lockTransformation(int flags); int getTransformationsLockFlags(); int isBodyFlagOn(int flags); /************************************************************************/ /* Sub shapes : */ /************************************************************************/ CollisionsArray mCollisions; CollisionsArray&getCollisions(){return mCollisions;} pTriggerArray mTriggers; pTriggerArray& getTriggers() { return mTriggers; } xBitSet mCollisionFlags; xBitSet&getCollisionFlags(); pVehicle * getVehicle() const { return mVehicle; } void setVehicle(pVehicle * val) { mVehicle = val; } pWheel* getWheel(CK3dEntity* subShapeReference); pWheel2* getWheel2(CK3dEntity* subShapeReference); int getTriggerState() const { return mTriggerState; } void setTriggerState(int val) { mTriggerState = val; } int getNbWheels(); void updateWheels(float step); void _transformWheels(); bool hasWheels(); int getNbSubShapes(); int getNbSubBodies(); protected : DWORD m_DataFlags;//deprecated ! xBitSet mDataFlags; CK_ID mEntID; CKContext* context; int m_sFlags; int m_HullType; float m_friction; float m_restitution; float mDensity; VxVector massOffset; VxVector pivotOffset; CK3dEntity* mVTObject; pWorld * m_pWorld; pSleepingSettings* m_SleepingSettings; JointListType m_Joints; NxActor* mActor; NxMaterial*mMaterial; float mSkinWidth; NxShape *mMainShape; pVehicle *mVehicle; int mTriggerState; public: void _checkForNewSubShapes(); void _checkForRemovedSubShapes(); }; /** @} */ #endif // !defined(EA_C2D3E6DE_B1A5_4f07_B3FA_73F108249451__INCLUDED_) <file_sep>#ifndef __vtNetStructs_h #define __vtNetStructs_h #include "xNetTypes.h" #endif <file_sep>#include <StdAfx.h> #include "pCommon.h" #include "pWorldCallbacks.h" CKObjectDeclaration *FillBehaviorPWRayCastAnyBoundsDecl(); CKERROR CreatePWRayCastAnyBoundsProto(CKBehaviorPrototype **pproto); int PWRayCastAnyBounds(const CKBehaviorContext& behcontext); CKERROR PWRayCastAnyBoundsCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPWRayCastAnyBoundsDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PWRayCastAnyBounds"); od->SetCategory("Physic/Collision"); od->SetDescription("Performs a ray cast test"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x6e155f2f,0x6d634931)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePWRayCastAnyBoundsProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePWRayCastAnyBoundsProto // FullName: CreatePWRayCastAnyBoundsProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ enum bInput { bbI_RayOri, bbI_RayOriRef, bbI_RayDir, bbI_RayDirRef, bbI_Length, bbI_ShapesType, bbI_Groups, bbI_Mask, }; enum bbS { bbS_Groups=0, bbS_Mask=1 }; enum bbOT { bbOT_Yes, bbOT_No, }; CKERROR CreatePWRayCastAnyBoundsProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWRayCastAnyBounds"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PWRayCastAnyBounds PWRayCastAnyBounds is categorized in \ref Collision <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Performs a ray cast test.<br> See <A HREF="PWRayCasts.cmo">PWRayCasts.cmo</A> for example. <h3>Technical Information</h3> \image html PWRayCastAnyBounds.png <SPAN CLASS="in">In: </SPAN>Triggers the process. <BR> <SPAN CLASS="out">Yes: </SPAN>Hit occured. <BR> <SPAN CLASS="out">No: </SPAN>No hits. <BR> <SPAN CLASS="pin">Target: </SPAN>World Reference. pDefaultWorld! <BR> <SPAN CLASS="pin">Ray Origin: </SPAN>Start of the ray. <BR> <SPAN CLASS="pin">Ray Origin Reference: </SPAN>Reference object to determine the start of the ray. Ray Origin becomes transformed if an object is given. <BR> <SPAN CLASS="pin">Ray Direction: </SPAN>Direction of the ray. <BR> <SPAN CLASS="pin">Ray Direction Reference: </SPAN>Reference object to determine the direction of the ray. Ray Direction becomes transformed if an object is given. Up axis will be used then. <BR> <SPAN CLASS="Length">Length: </SPAN>Lenght of the ray. <BR> <SPAN CLASS="pin">Shapes Types: </SPAN>Adds static and/or dynamic shapes to the test. <BR> <SPAN CLASS="pin">Groups: </SPAN>Includes specific groups to the test. <BR> <SPAN CLASS="pin">Groups Mask: </SPAN>Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask <BR> <h3>Note</h3> This is as parameter opertion avaiable. See \ref CollisionsOps ! <br> <br> Is utilizing #pWorld::raycastAnyBounds().<br> */ proto->DeclareInput("In"); proto->DeclareOutput("Yes"); proto->DeclareOutput("No"); proto->DeclareInParameter("Ray Origin",CKPGUID_VECTOR); proto->DeclareInParameter("Ray Origin Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Ray Direction",CKPGUID_VECTOR); proto->DeclareInParameter("Ray Direction Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Length",CKPGUID_FLOAT); proto->DeclareInParameter("Shapes Type",VTF_SHAPES_TYPE); proto->DeclareInParameter("Groups",CKPGUID_INT); proto->DeclareInParameter("Filter Mask",VTS_FILTER_GROUPS); proto->DeclareSetting("Groups",CKPGUID_BOOL,"false"); proto->DeclareSetting("Groups Mask",CKPGUID_BOOL,"false"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct( PWRayCastAnyBoundsCB ); proto->SetFunction(PWRayCastAnyBounds); *pproto = proto; return CK_OK; } enum bOutputs { bbO_None, bbO_Enter, bbO_Stay, bbO_Leave, }; //************************************ // Method: PWRayCastAnyBounds // FullName: PWRayCastAnyBounds // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PWRayCastAnyBounds(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorld(target->GetID()); if (!world) { beh->ActivateOutput(bbOT_No); return 0; } NxScene *scene = world->getScene(); if (!scene) { beh->ActivateOutput(bbOT_No); return 0; } if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// CK3dEntity *rayOriRef= (CK3dEntity *) beh->GetInputParameterObject(bbI_RayOriRef); CK3dEntity *rayDirRef= (CK3dEntity *) beh->GetInputParameterObject(bbI_RayDirRef); //ori : VxVector ori = GetInputParameterValue<VxVector>(beh,bbI_RayOri); VxVector oriOut = ori; if (rayOriRef) { rayOriRef->Transform(&oriOut,&ori); } //dir : VxVector dir = GetInputParameterValue<VxVector>(beh,bbI_RayDir); VxVector dirOut = dir; if (rayDirRef) { VxVector dir,up,right; rayDirRef->GetOrientation(&dir,&up,&right); rayDirRef->TransformVector(&dirOut,&up); } float lenght = GetInputParameterValue<float>(beh,bbI_Length); int types = GetInputParameterValue<int>(beh,bbI_ShapesType); VxRay ray; ray.m_Direction = dirOut; ray.m_Origin = oriOut; pRayCastReport &report = *world->getRaycastReport(); report.setCurrentBehavior(beh->GetID()); int groupsEnabled; DWORD groups = 0xffffffff; beh->GetLocalParameterValue(bbS_Groups,&groupsEnabled); if (groupsEnabled) { groups = GetInputParameterValue<int>(beh,bbI_Groups); } pGroupsMask *gmask = NULL; DWORD mask; beh->GetLocalParameterValue(bbS_Mask,&mask); if (mask) { CKParameter *maskP = beh->GetInputParameter(bbI_Mask)->GetRealSource(); gmask->bits0 = GetValueFromParameterStruct<int>(maskP,0); gmask->bits1 = GetValueFromParameterStruct<int>(maskP,1); gmask->bits2 = GetValueFromParameterStruct<int>(maskP,2); gmask->bits3 = GetValueFromParameterStruct<int>(maskP,3); } int nbShapes = world->raycastAnyBounds(ray,(pShapesType)types,gmask,groups,lenght); if (nbShapes) { beh->ActivateOutput(bbOT_Yes); }else{ beh->ActivateOutput(bbOT_No); } } return 0; } //************************************ // Method: PWRayCastAnyBoundsCB // FullName: PWRayCastAnyBoundsCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PWRayCastAnyBoundsCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD groups; beh->GetLocalParameterValue(bbS_Groups,&groups); beh->EnableInputParameter(bbI_Groups,groups); DWORD mask; beh->GetLocalParameterValue(bbS_Mask,&mask); beh->EnableInputParameter(bbI_Mask,mask); } break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" void pWorld::updateVehicle(pVehicle *vehicle, float dt) { if (vehicle) { vehicle->updateVehicle(dt); } } void pWorld::updateVehicles(float dt) { int nbActors = getScene()->getNbActors(); if (!nbActors) { return; } NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; pRigidBody *body = static_cast<pRigidBody*>(actor->userData); if (body) { if (!isVehicle(actor) && body->hasWheels()) { body->updateWheels(dt); } } if (body && isVehicle(actor)) { updateVehicle(body->getVehicle(),dt); } } } bool pWorld::isVehicle(NxActor* actor) { pRigidBody *body = static_cast<pRigidBody*>(actor->userData); if (body) { return body->getVehicle() ? true : false; } return false; } pVehicle*pWorld::getVehicle(CK3dEntity* body) { pRigidBody *rbody = getBody(body); if (body && rbody->getVehicle() ) { return rbody->getVehicle(); } return NULL; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" pJointCylindrical::pJointCylindrical(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Cylindrical) { } void pJointCylindrical::setGlobalAnchor(VxVector anchor) { NxCylindricalJointDesc descr; NxCylindricalJoint*joint = static_cast<NxCylindricalJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.setGlobalAnchor(getFrom(anchor)); joint->loadFromDesc(descr); } void pJointCylindrical::setGlobalAxis(VxVector axis) { NxCylindricalJointDesc descr; NxCylindricalJoint*joint = static_cast<NxCylindricalJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.setGlobalAxis(getFrom(axis)); joint->loadFromDesc(descr); } void pJointCylindrical::enableCollision(int collision) { NxCylindricalJointDesc descr; NxCylindricalJoint*joint = static_cast<NxCylindricalJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (collision) { descr.jointFlags |= NX_JF_COLLISION_ENABLED; }else descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; joint->loadFromDesc(descr); }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "NXU_helper.h" // NxuStream helper functions. #include "NXU_PhysicsInstantiator.h" #include "Stream.h" #include "cooking.h" #include "IParameter.h" void pRigidBody::updateMassSettings(pMassSettings massSettings) { // Referential CK3dEntity* massRef = (CK3dEntity*)GetPMan()->GetContext()->GetObject(massSettings.massReference); VxVector massLocalOut = massSettings.localPosition; //---------------------------------------------------------------- // // position // if (XAbs(massSettings.localPosition.SquareMagnitude()) >0.0f ) { if (massRef) { VxVector tOut = massLocalOut; massRef->Transform(&massLocalOut,&massLocalOut); massRef->TransformVector(&tOut,&tOut,GetVT3DObject()); getActor()->setCMassOffsetLocalPosition(getFrom(tOut)); }else { getActor()->setCMassOffsetLocalPosition(getFrom(massLocalOut)); } } //---------------------------------------------------------------- // // rotational offset : todo // VxMatrix mat; Vx3DMatrixFromEulerAngles(mat,massSettings.localOrientation.x,massSettings.localOrientation.y,massSettings.localOrientation.z); VxQuaternion outQuat; outQuat.FromMatrix(mat); VxQuaternion referenceQuat=outQuat; if (XAbs(massSettings.localOrientation.SquareMagnitude()) >0.0f ) { if (massRef) { massRef->GetQuaternion(&referenceQuat,NULL); getActor()->setCMassOffsetGlobalOrientation(getFrom(referenceQuat)); }else{ getActor()->setCMassOffsetGlobalOrientation(getFrom(outQuat)); } } //---------------------------------------------------------------- // // recompute mass // float newDensity=massSettings.newDensity; float totalMass =massSettings.totalMass; int bMassResult = 0 ; if (newDensity!=0.0f || totalMass!=0.0f ) { bMassResult = getActor()->updateMassFromShapes(newDensity,totalMass); } int op = bMassResult; } int pRigidBody::_initMainShape(const pObjectDescr oDescr,NxActorDesc *actorDesc) { //---------------------------------------------------------------- // // Sanity Checks // #ifdef _DEBUG assert(GetVT3DObject()); // has to been set before #endif // _DEBUG //---------------------------------------------------------------- // // Collect some data // VxVector box_s= BoxGetZero(GetVT3DObject()); float density = oDescr.density; float radius = GetVT3DObject()->GetRadius(); switch(oDescr.hullType) { ////////////////////////////////////////////////////////////////////////// case HT_Box: { NxBoxShapeDesc shape; if (! (oDescr.flags & BF_Deformable) ) { shape.dimensions = pMath::getFrom(box_s)*0.5f; } shape.density = density; //shape.localPose.t = pMath::getFrom(shapeOffset); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; actorDesc->shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Sphere: { NxSphereShapeDesc shape; if (! (oDescr.flags & BF_Deformable) ) { shape.radius = radius; } shape.density = density; //shape.localPose.t = pMath::getFrom(shapeOffset); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; actorDesc->shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Mesh: { if (! (oDescr.flags & BF_Deformable) ) { //xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Can not use a mesh as de"); //return NULL; } NxTriangleMeshDesc myMesh; myMesh.setToDefault(); pFactory::Instance()->createMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); NxTriangleMeshShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); return false; } MemoryWriteBuffer buf; status = CookTriangleMesh(myMesh, buf); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); return false; } shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); shape.density = density; shape.group = oDescr.collisionGroup; actorDesc->shapes.pushBack(&shape); //shape.localPose.t = pMath::getFrom(shapeOffset); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_ConvexMesh: { if (GetVT3DObject()->GetCurrentMesh()) { if (GetVT3DObject()->GetCurrentMesh()->GetVertexCount()>=256 ) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshs allowed, by Ageia!"); return false; } }else { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); return false; } NxConvexMeshDesc myMesh; myMesh.setToDefault(); pFactory::Instance()->createConvexMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); NxConvexShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); return false; } MemoryWriteBuffer buf; status = CookConvexMesh(myMesh, buf); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); return false; } shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); shape.density = density; actorDesc->shapes.pushBack(&shape); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_ConvexCylinder: { NxConvexShapeDesc shape; if (!pFactory::Instance()->_createConvexCylinder(&shape,GetVT3DObject())){ xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); return false; } shape.density = density; if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; actorDesc->shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Capsule: { NxCapsuleShapeDesc shape; if (! (oDescr.flags & BF_Deformable) ) { pCapsuleSettings cSettings; pFactory::Instance()->findSettings(cSettings,GetVT3DObject()); shape.radius = cSettings.radius > 0.0f ? cSettings.radius : box_s.v[cSettings.localRadiusAxis] * 0.5f; shape.height = cSettings.height > 0.0f ? cSettings.height : box_s.v[cSettings.localLengthAxis] - ( 2*shape.radius) ; } shape.density = density; // shape.materialIndex = result->getMaterial()->getMaterialIndex(); // shape.localPose.t = pMath::getFrom(shapeOffset); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; actorDesc->shapes.pushBack(&shape); break; } case HT_Wheel: { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Wheel shape can be sub shape only!"); return false; } } return true; } /*int pRigidBody::_initMainShape(const pObjectDescr oDescr,NxActorDesc&actorDesc) { //---------------------------------------------------------------- // // Sanity Checks // #ifdef _DEBUG assert(GetVT3DObject()); // has to been set before #endif // _DEBUG //---------------------------------------------------------------- // // Collect some data // VxVector box_s= BoxGetZero(GetVT3DObject()); float density = oDescr.density; float radius = GetVT3DObject()->GetRadius(); switch(oDescr.hullType) { ////////////////////////////////////////////////////////////////////////// case HT_Box: { NxBoxShapeDesc shape; if (! (oDescr.flags & BF_Deformable) ) { shape.dimensions = pMath::getFrom(box_s)*0.5f; } shape.density = density; //shape.localPose.t = pMath::getFrom(shapeOffset); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; actorDesc.shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Sphere: { NxSphereShapeDesc shape; if (! (oDescr.flags & BF_Deformable) ) { shape.radius = radius; } shape.density = density; //shape.localPose.t = pMath::getFrom(shapeOffset); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; int oG = oDescr.collisionGroup; shape.group = oDescr.collisionGroup; int k = shape.isValid(); actorDesc.shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Mesh: { if (! (oDescr.flags & BF_Deformable) ) { //xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Can not use a mesh as de"); //return NULL; } NxTriangleMeshDesc myMesh; myMesh.setToDefault(); pFactory::Instance()->createMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); NxTriangleMeshShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); return false; } MemoryWriteBuffer buf; status = CookTriangleMesh(myMesh, buf); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); return false; } shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); shape.density = density; shape.group = oDescr.collisionGroup; actorDesc.shapes.pushBack(&shape); //shape.localPose.t = pMath::getFrom(shapeOffset); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_ConvexMesh: { if (GetVT3DObject()->GetCurrentMesh()) { if (GetVT3DObject()->GetCurrentMesh()->GetVertexCount()>=256 ) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshs allowed, by Ageia!"); return false; } }else { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); return false; } NxConvexMeshDesc myMesh; myMesh.setToDefault(); pFactory::Instance()->createConvexMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); NxConvexShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); return false; } MemoryWriteBuffer buf; status = CookConvexMesh(myMesh, buf); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); return false; } shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); shape.density = density; // shape.materialIndex = result->getMaterial()->getMaterialIndex(); actorDesc.shapes.pushBack(&shape); //shape.localPose.t = pMath::getFrom(shapeOffset); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; int h = shape.isValid(); CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_ConvexCylinder: { NxConvexShapeDesc shape; if (!pFactory::Instance()->_createConvexCylinder(&shape,GetVT3DObject())){ xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); return false; } shape.density = density; if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; actorDesc.shapes.pushBack(&shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Capsule: { NxCapsuleShapeDesc shape; if (! (oDescr.flags & BF_Deformable) ) { pCapsuleSettings cSettings; pFactory::Instance()->findSettings(cSettings,GetVT3DObject()); shape.radius = cSettings.radius > 0.0f ? cSettings.radius : box_s.v[cSettings.localRadiusAxis] * 0.5f; shape.height = cSettings.height > 0.0f ? cSettings.height : box_s.v[cSettings.localLengthAxis] - ( 2*shape.radius) ; } shape.density = density; // shape.materialIndex = result->getMaterial()->getMaterialIndex(); // shape.localPose.t = pMath::getFrom(shapeOffset); if (oDescr.skinWidth!=-1.0f) shape.skinWidth = oDescr.skinWidth; actorDesc.shapes.pushBack(&shape); break; } case HT_Wheel: { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Wheel shape can be sub shape only!"); return false; } } return true; } */ int pRigidBody::getNbJoints() { pWorld *wA =getWorld(); int result = 0 ; if (!wA) { return result; } NxU32 jointCount = wA->getScene()->getNbJoints(); if (jointCount) { NxArray< NxJoint * > joints; wA->getScene()->resetJointIterator(); for (NxU32 i = 0; i < jointCount; ++i) { NxJoint *j = wA->getScene()->getNextJoint(); pJoint *mJoint = static_cast<pJoint*>( j->userData ); if ( mJoint ) { if (mJoint->GetVTEntA() == GetVT3DObject() || mJoint->GetVTEntB() == GetVT3DObject() ) { result++; } } } } return result; } void pRigidBody::test() { pRigidBody *body = this; CK3dEntity* test = (CK3dEntity*)body; } void pRigidBody::readFrom(NXU::NxActorDesc *desc,int flags) { if ( desc->mHasBody ) // only for dynamic actors { for (NxU32 k=0; k<desc->mShapes.size(); k++) { NXU::NxShapeDesc *shape = desc->mShapes[k]; NxVec3 locPos = shape->localPose.t; NxQuat localQuad = shape->localPose.M; } } } float pRigidBody::getMass(CK3dEntity *shapeReference/* =NULL */) { float result = 0 ; if (getActor()) { result = getActor()->getMass(); } return result; } VxVector pRigidBody::getLocalPointVelocity( const VxVector& point ) const { if(isValid()) return pMath::getFrom(getActor()->getLocalPointVelocity(getFrom(point))); return VxVector(); } VxVector pRigidBody::getPointVelocity( const VxVector& point ) const { if(isValid()) return pMath::getFrom(getActor()->getPointVelocity(getFrom(point))); return VxVector(); } pJoint* pRigidBody::isConnected(CK3dEntity*ent) { pJoint *result = NULL; pWorld *wA =getWorld(); pWorld *wB =NULL; pRigidBody *b = NULL; if (!wA) { return NULL; } if (ent) { b = GetPMan()->getBody(ent); } if (b) { wB = b->getWorld(); } NxU32 jointCount = wA->getScene()->getNbJoints(); if (jointCount) { NxArray< NxJoint * > joints; wA->getScene()->resetJointIterator(); for (NxU32 i = 0; i < jointCount; ++i) { NxJoint *j = wA->getScene()->getNextJoint(); pJoint *mJoint = static_cast<pJoint*>( j->userData ); if ( mJoint ) { if (mJoint->GetVTEntA() == GetVT3DObject() && mJoint->GetVTEntB() == ent ) { return mJoint; } if (mJoint->GetVTEntB() == GetVT3DObject() && mJoint->GetVTEntA() == ent ) { return mJoint; } } } } return NULL; } int pRigidBody::JGetNumJoints() { int result = 0 ; /* OdeBodyType bid = GetOdeBody(); if (bid) { dxJoint *j = NULL; for (j=World()->World()->firstjoint; j; j=(dxJoint*)j->next) { pJoint *pJ = static_cast<pJoint*>(dJointGetData(j)); if (pJ) { if (pJ->GetOdeBodyA() == bid || pJ->GetOdeBodyA() == bid ) { result ++; } } } } */ return 0; } void pRigidBody::setLocalShapePosition(VxVector relative,CK3dEntity*shapeReference/* =NULL */) { if(!getActor()) return; NxShape *subShape = getSubShape(shapeReference); if (subShape ) { subShape->setLocalPosition(getFrom(relative)); } /*NxU32 nbShapes = getActor()->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { s->setLocalPosition(pMath::getFrom(relative)); int op=2; return; //getActor()->updateMassFromShapes() } //addShapeMesh(c,s); } }*/ } pRigidBody::pRigidBody(CK3dEntity* _e,pWorld *world) : xEngineObjectAssociation<CK3dEntity*>(_e,_e->GetID()) , mVTObject(_e) , m_pWorld(world) { using namespace vtTools::AttributeTools; mActor = NULL; context = NULL; if (_e) { mEntID = _e->GetID(); mVTObject = _e; } mMaterial = NULL; mDataFlags = 0; mMainShape = NULL; mMaterial = NULL; mVehicle = NULL; mMainShape = NULL; mActor =NULL; mCloth = NULL; //mClothRecieveBuffer=NULL; } pRigidBody::pRigidBody(CK3dEntity* _e) { SetVT3DObject(_e); if (_e){ mEntID = _e->GetID(); mVTObject = _e; } mMaterial = NULL; mDataFlags = 0; mVehicle = NULL; mMainShape = NULL; mActor =NULL; mVTObject = NULL; m_pWorld = NULL; mCloth = NULL; mInitialDescription = NULL; } void pRigidBody::addLocalForceAtLocalPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) { if(isValid()) getActor()->addLocalForceAtLocalPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode,wakeUp); } void pRigidBody::addLocalForceAtPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) { if(isValid()) getActor()->addLocalForceAtPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode,wakeUp); } void pRigidBody::addForceAtLocalPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) { if(isValid()) getActor()->addForceAtLocalPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode,wakeUp); } void pRigidBody::addForceAtPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) { if(isValid()) getActor()->addForceAtPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode); } void pRigidBody::addTorque(const VxVector& torque,ForceMode mode,bool wakeUp) { if(isValid()) getActor()->addTorque(pMath::getFrom(torque),(NxForceMode)mode,wakeUp); } void pRigidBody::addLocalTorque(const VxVector& torque,ForceMode mode,bool wakeUp) { if(isValid()) getActor()->addLocalTorque(pMath::getFrom(torque),(NxForceMode)mode); } void pRigidBody::addLocalForce(const VxVector& force,ForceMode mode,bool wakeUp) { if(isValid()) getActor()->addLocalForce(pMath::getFrom(force),(NxForceMode)mode,wakeUp); } void pRigidBody::addForce( const VxVector& force,ForceMode mode/*=E_FM_FORCE*/,bool wakeUp/*=true*/ ) { if(isValid()) getActor()->addForce(pMath::getFrom(force),(NxForceMode)mode,wakeUp); } void pRigidBody::setLinearMomentum( const VxVector& linMoment ) { if(isValid()) getActor()->setLinearMomentum(pMath::getFrom(linMoment)); } void pRigidBody::setAngularMomentum( const VxVector& angMoment ) { if(isValid()) getActor()->setAngularMomentum(pMath::getFrom(angMoment)); } VxVector pRigidBody::getAngularMomentum() const { if(isValid()) return pMath::getFrom(getActor()->getAngularMomentum()); return VxVector(); } float pRigidBody::getAngularDamping() const { if(isValid()) return getActor()->getAngularDamping(); return 0.0f; } float pRigidBody::getLinearDamping() const { if(isValid()) return getActor()->getLinearDamping(); return 0.0f; } VxVector pRigidBody::getLinearMomentum()const{ if(isValid()) return pMath::getFrom(getActor()->getLinearMomentum()); return VxVector(); } void pRigidBody::setPosition(const VxVector& pos,CK3dEntity *subShapeReference) { if(isValid()){ NxShape *subShape = getSubShape(subShapeReference); if (subShape == getMainShape() ) { if (!isKinematic()) { getActor()->setGlobalPosition(pMath::getFrom(pos)); }else{ getActor()->moveGlobalPosition(pMath::getFrom(pos)); } }else{ if (subShape) { subShape->setGlobalPosition(getFrom(pos)); } } } } void pRigidBody::setRotation(const VxQuaternion& rot,CK3dEntity *subShapeReference) { if(isValid()) { NxShape *subShape = getSubShape(subShapeReference); if (subShape == getMainShape() ) { getActor()->setGlobalOrientation(pMath::getFrom(rot)); }else { if (subShape) { subShape->setGlobalOrientation(getFrom(rot)); } } } } float pRigidBody::getMaxAngularSpeed() const { if(isValid())return getActor()->getMaxAngularVelocity(); return 0.0f; } void pRigidBody::setMaxAngularSpeed(float val) { if(isValid())getActor()->setMaxAngularVelocity(val); } VxVector pRigidBody::getLinearVelocity() const{ return pMath::getFrom(getActor()->getLinearVelocity());} VxVector pRigidBody::getAngularVelocity() const{ return pMath::getFrom(getActor()->getAngularVelocity());} void pRigidBody::setLinearVelocity( const VxVector& linVel ) { if(isValid()) getActor()->setLinearVelocity(pMath::getFrom(linVel)); } void pRigidBody::setAngularVelocity( const VxVector& angVel ) { if(isValid()) getActor()->setAngularVelocity(pMath::getFrom(angVel)); } void pRigidBody::setAngularDamping(float scale) { if (getActor() && getActor()->isDynamic()) { getActor()->setAngularDamping(scale); } } void pRigidBody::setLinearDamping(float scale) { if (getActor() && getActor()->isDynamic()) { getActor()->setLinearDamping(scale); } } void pRigidBody::setCMassOffsetLocalPosition(VxVector offset) { if (getActor()) { getActor()->setCMassOffsetLocalPosition( getFrom(offset) ); } } void pRigidBody::translateLocalShapePosition(VxVector vec) { if (getActor()) { if (getMainShape()) { NxVec3 currentPos = getMainShape()->getLocalPosition(); getMainShape()->setLocalPosition( currentPos + getFrom(vec)); } } } pJoint* pRigidBody::isConnected(CK3dEntity*ent,int type) { /* pJoint *result = NULL; if ( GetVT3DObject()!=ent) { pRigidBody *b = GetPMan()->getBody(ent); OdeBodyType abid = GetOdeBody(); OdeBodyType bbid = NULL; if (b) { bbid = b->GetOdeBody(); } dxJoint *j = NULL; for (j=World()->World()->firstjoint; j; j=(dxJoint*)j->next) { pJoint *pJ = static_cast<pJoint*>(dJointGetData(j)); if (pJ) { if (!bbid) { if (dJointGetType(j) ==dJointTypeFixed ) { if (pJ->GetOdeBodyA()==abid) { return pJ; } } } if ( pJ->GetOdeBodyA()==abid && dJointGetType(j) == type) { if (pJ->GetOdeBodyB()==bbid ) { return pJ; } } if ( pJ->GetOdeBodyA()==bbid && dJointGetType(j) == type) { if (pJ->GetOdeBodyB()==abid ) { return pJ; } } } } } return result; */ return NULL; } void pRigidBody::SetVT3DObject(CK3dEntity* _obj) { mEntID = _obj->GetID(); mVTObject=_obj;} CK3dEntity*pRigidBody::GetVT3DObject() { return mVTObject; }<file_sep>#include <StdAfx.h> #include "pCommon.h" #include "pVehicleAll.h" CKObjectDeclaration *FillBehaviorPVSetExDecl(); CKERROR CreatePVSetExProto(CKBehaviorPrototype **pproto); int PVSetEx(const CKBehaviorContext& behcontext); CKERROR PVSetExCB(const CKBehaviorContext& behcontext); using namespace vtTools::BehaviorTools; enum bInputs { I_XML, I_Flags, I_PFlags, I_SteerMax, }; #define BB_SSTART 0 BBParameter pInMapx[] = { BB_SPIN(I_XML,VTE_XML_VEHICLE_SETTINGS,"Vehicle Settings","None"), BB_SPIN(I_Flags,VTF_VFLAGS,"Vehicle Flags",""), BB_SPIN(I_PFlags,VTF_VEHICLE_PROCESS_OPTIONS,"Vehicle Process Flags",""), BB_SPIN(I_SteerMax,CKPGUID_ANGLE,"Maximum Steer","15"), }; #define gVSMap pInMapx //#define BB_LOAD_PIMAP(SOURCE_MAP,SETTING_START_INDEX) BBHelper::loadPIMap(beh,pIMap,SOURCE_MAP,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX) CKERROR PVSetExCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gVSMap,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gVSMap,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gVSMap,BB_SSTART); break; } } return CKBR_OK; } CKObjectDeclaration *FillBehaviorPVSetExDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVSetEx"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Modifies vehicle parameter."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5b527a19,0x1e1600a9)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVSetExProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } CKERROR CreatePVSetExProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVSetEx"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( PVSetExCB ); BB_EVALUATE_SETTINGS(gVSMap); //---------------------------------------------------------------- // // We just want create the building block pictures // #ifdef _DOC_ONLY_ BB_EVALUATE_INPUTS(pInMap); #endif // _DOC_ONLY_ proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PVSetEx); *pproto = proto; return CK_OK; } int PVSetEx(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbSErrorME(E_PE_REF); pRigidBody *body = NULL; BB_DECLARE_PIMAP; body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); float steerMax = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_SteerMax)); int flags = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_Flags)); int pflags = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_PFlags)); BBSParameter(I_XML); BBSParameter(I_Flags); BBSParameter(I_PFlags); BBSParameter(I_SteerMax); pVehicle *v = body->getVehicle(); if (!v) { pVehicleDesc vdesc; vdesc.setToDefault(); if (sI_SteerMax) { vdesc.steeringMaxAngle = steerMax * RR_RAD_DEG_FACTOR ; } if (sI_PFlags) { vdesc.processFlags = pflags; } v = pFactory::Instance()->createVehicle(target,vdesc); } if (!v) bbErrorME("Couldn't create vehicle"); if (sI_SteerMax) v->getSteer()->setLock(steerMax * RR_RAD_DEG_FACTOR); if (sI_PFlags)v->setProcessOptions(pflags); /* if (sI_Mass) v->setMass(mass); if (sI_Flags) v->flags = flags; if (sI_MotorForce) v->setMotorForce(mForce); if (sI_DiffRatio)v->setDifferentialRatio(dRatio); if (sI_SteerMax)v->setMaxSteering(steerMax) ; if (sI_DSDelta)v->setDigitalSteeringDelta(dsDelta); if (sI_MaxVelocity)v->setMaxVelocity(maxVel); if (sI_CMass)v->setCenterOfMass(cMass); if (sI_TEff)v->setTransmissionEfficiency(tEff); if(sI_SteeringSteerPoint)v->setSteeringSteerPoint(steeringSteerPoint); if(sI_SteerTurnPoint)v->setSteeringTurnPoint(steeringTurnPoint ); */ } beh->ActivateOutput(0); return 0; } //************************************ // Method: PVSetExCB // FullName: PVSetExCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ /* dx -0.99999821 float angle -0.21089047 float zPos 0.99999857 float dz 4.6712832 float xPos -0.99999821 float atan3 -0.21089047 float dx 1.0000019 float angle 0.21089132 float zPos 1.0000004 float dz 4.6712813 float xPos 1.0000019 float atan3 0.21089132 float */ /* // int indexA = BBHelper::getIndex(beh,pMap,bbI_AxleSpeed); // int indexB = BBHelper::getIndex(beh,pMap,bbI_Steer); /* EnablePInputBySettings(beh,bbI_AxleSpeed); EnablePInputBySettings(beh,bbI_Steer); EnablePInputBySettings(beh,bbI_MotorTorque); EnablePInputBySettings(beh,bbI_BrakeTorque); EnablePInputBySettings(beh,bbI_SuspensionSpring); EnablePInputBySettings(beh,bbI_SuspensionTravel); EnablePInputBySettings(beh,bbI_Radius); */ /* case CKM_BEHAVIORDETACH: { /* BB_DECLARE_PIMAP; while ( pIMap->getArray().size() ) { BBParameter *p=pIMap->getArray().at(0); pIMap->getArray().erase(pIMap->getArray().begin()); delete p; p = NULL; } break; */ // BB_DECLARE_PIMAP; // BBHelper::destroyPIMap(beh,pIMap,BB_PMAP_SIZE); <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" pJointPointOnLine::pJointPointOnLine(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_PointOnLine) { } void pJointPointOnLine::setGlobalAnchor(VxVector anchor) { NxPointOnLineJointDesc descr; NxPointOnLineJoint*joint = static_cast<NxPointOnLineJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.setGlobalAnchor(getFrom(anchor)); joint->loadFromDesc(descr); } void pJointPointOnLine::setGlobalAxis(VxVector axis) { NxPointOnLineJointDesc descr; NxPointOnLineJoint*joint = static_cast<NxPointOnLineJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.setGlobalAxis(getFrom(axis)); joint->loadFromDesc(descr); } void pJointPointOnLine::enableCollision(int collision) { NxPointOnLineJointDesc descr; NxPointOnLineJoint*joint = static_cast<NxPointOnLineJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (collision) { descr.jointFlags |= NX_JF_COLLISION_ENABLED; }else descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; joint->loadFromDesc(descr); }<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorCollisionsCheckADecl(); CKERROR CreateCollisionsCheckAProto(CKBehaviorPrototype **pproto); int CollisionsCheckA(const CKBehaviorContext& behcontext); CKERROR CollisionsCheckACB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorCollisionsCheckADecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("PCHasContact"); od->SetDescription("Checks for a collision on a given body"); od->SetCategory("Physic/Collision"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5189255c,0x18134074)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateCollisionsCheckAProto); //od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } CKERROR CreateCollisionsCheckAProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCHasContact"); if(!proto) return CKERR_OUTOFMEMORY; proto->SetBehaviorCallbackFct( CollisionsCheckACB ); proto->DeclareInput("Check"); proto->DeclareOutput("Collision"); proto->DeclareOutput("No Collision"); proto->DeclareOutParameter("Collider", CKPGUID_3DENTITY); proto->DeclareOutParameter("Position", CKPGUID_VECTOR); proto->DeclareOutParameter("Normal", CKPGUID_VECTOR); proto->DeclareOutParameter("Face Index", CKPGUID_INT); proto->DeclareOutParameter("Normal Force", CKPGUID_VECTOR); proto->DeclareOutParameter("Friction Force", CKPGUID_VECTOR); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(CollisionsCheckA); *pproto = proto; return CK_OK; } int CollisionsCheckA(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0, FALSE); ////////////////////////////////////////////////////////////////////////// //we haven't't seen yet, create a local array : //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_PARAMETERERROR; pRigidBody *body = GetPMan()->getBody(target); if (body) { VxVector pos; VxVector normal; float depth; int size = body->getCollisions().Size(); CK3dEntity *colliderEntity = NULL; if (!size) { beh->ActivateOutput(1); beh->SetOutputParameterObject(0,NULL); return 0; } if (size) { for (int i = 0; i < body->getCollisions().Size() ; i ++) { pCollisionsEntry *entry = body->getCollisions().At(i); if (entry) { CK3dEntity *shapeA = (CK3dEntity*)GetPMan()->GetContext()->GetObject(entry->shapeEntityA); CK3dEntity *shapeB = (CK3dEntity*)GetPMan()->GetContext()->GetObject(entry->shapeEntityB); pRigidBody *collider = NULL; body->getCollisions().RemoveAt(i); if( target == body->GetVT3DObject()) { if (entry->bodyA && entry->bodyA == body) { collider = entry->bodyB; colliderEntity = shapeB; } if (entry->bodyB && entry->bodyB == body) { collider = entry->bodyA; colliderEntity = shapeA; } }else // its a sub shape collision { if (shapeA && shapeA == target ) { colliderEntity = shapeB; } if (shapeB && shapeB == target) { colliderEntity = shapeA; } } if (colliderEntity) { beh->SetOutputParameterObject(0,colliderEntity); beh->ActivateOutput(0); SetOutputParameterValue<VxVector>(beh,1,entry->point); SetOutputParameterValue<VxVector>(beh,2,entry->faceNormal); SetOutputParameterValue<int>(beh,3,entry->faceIndex); SetOutputParameterValue<VxVector>(beh,4,entry->sumNormalForce); SetOutputParameterValue<VxVector>(beh,5,entry->sumFrictionForce); body->getCollisions().Clear(); return 0; } } } } /* int size = world->getCollisions().Size(); for (int i = 0; i < world->getCollisions().Size() ; i ++) { pCollisionsEntry *entry = world->getCollisions().At(i); if (entry) { printf("asdasd"); int o = 2; o++; } } */ //CK3dEntity *collider = world->CIsInCollision(target,pos,normal,depth); /* if (collider) { beh->SetOutputParameterObject(0,collider); beh->SetOutputParameterValue(1,&pos); beh->SetOutputParameterValue(2,&normal); beh->SetOutputParameterValue(3,&depth); beh->ActivateOutput(0); return 0; }else { beh->ActivateOutput(1); }*/ } } beh->ActivateOutput(1); return 0; } CKERROR CollisionsCheckACB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#ifndef __XMATH_ALL_H__ #define __XMATH_ALL_H__ #include "Prereqs.h" #include "xTNLInternAll.h" //#include "xMathTools.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #endif<file_sep>#include "IDistributedObjectsInterface.h" #include "IDistributedClasses.h" #include "xDistributedBaseClass.h" #include "xDistributedObject.h" #include "xNetInterface.h" #include "vtConnection.h" #include <assert.h> #include "xLogger.h" /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedObject* IDistributedObjects::getByUserID(int userID,int classType) { xDistributedObjectsArrayType *distObjects = getNetInterface()->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj && dobj->getUserID() == userID && dobj->getDistributedClass() && dobj->getDistributedClass()->getEnitityType() == classType ) { return dobj; } begin++; } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IDistributedObjects::cCreateDistObject(int objectID,int ownerID,const char* objectName,const char*className) { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IDistributedObjects::create(const char* objectName,const char*className) { ////////////////////////////////////////////////////////////////////////// //sanity checks : if (!strlen(objectName) || !strlen(className) ) return; if (!getNetInterface()) return; if (getNetInterface()->IsServer()) return; if (!getNetInterface()->getConnection())return; if (!getNetInterface()->getDistributedClassInterface())return; IDistributedClasses *cInterface = getNetInterface()->getDistributedClassInterface(); xDistributedClass *_class = cInterface->get(className); if (!_class)return; ////////////////////////////////////////////////////////////////////////// //check we have it already : if (get(objectName))return; ////////////////////////////////////////////////////////////////////////// //call via connection rpc a dist object creation : int userID = getNetInterface()->getConnection()->getUserID(); getNetInterface()->getConnection()->c2sDOCreate(userID,objectName,className,_class->getEnitityType()); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IDistributedObjects::Destroy() { if (!getNetInterface()) { return; } if (!getNetInterface()->getDistributedObjects())return; xDistributedObjectsArrayType *distObjects = getNetInterface()->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); /* while (begin!=end) { int size = distObjects->Size(); xDistributedObject* dobj = *begin; if (dobj) { dobj->Destroy(); distObjects->Remove(dobj); delete dobj; dobj = NULL; begin = distObjects->begin(); //continue; } begin++; } */ distObjects->clear(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedObject* IDistributedObjects::get(const char*name) { #ifdef _DEBUG assert(strlen(name)); #endif if (!strlen(name))return NULL; xDistributedObjectsArrayType *distObjects = getNetInterface()->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { if(!strcmp(const_cast<char*>(dobj->GetName().getString()),name)) { return dobj; } } begin++; } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedObject* IDistributedObjects::get(const char*name,int classType) { #ifdef _DEBUG assert(strlen(name)); #endif if (!strlen(name))return NULL; xDistributedObjectsArrayType *distObjects = getNetInterface()->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { xDistributedClass *_class = dobj->getDistributedClass(); if (!_class) { xLogger::xLog(ELOGERROR,E_LI_DISTRIBUTED_BASE_OBJECT,"Found distributed object without class template: %s",name); return NULL; } int classType = _class->getEnitityType(); if(!strcmp(const_cast<char*>(dobj->GetName().getString()),name) && classType == classType ) { return dobj; } } begin++; } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedObject* IDistributedObjects::get(int serverID) { #ifdef _DEBUG assert( getNetInterface() ); #endif if (!serverID)return NULL; xDistributedObjectsArrayType *distObjects = getNetInterface()->getDistributedObjects(); int server = getNetInterface()->m_IsServer; xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { int serverID2 = dobj->getServerID(); if(dobj->getServerID() == serverID) { return dobj; } } begin++; } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedObject* IDistributedObjects::getByEntityID(int entityID) { #ifdef _DEBUG assert( getNetInterface() ); #endif if (!entityID)return NULL; xDistributedObjectsArrayType *distObjects = getNetInterface()->getDistributedObjects(); int server = getNetInterface()->m_IsServer; xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { if(dobj->getEntityID() == entityID) { return dobj; } } begin++; } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedObject * IDistributedObjects::create(int objID,const char *templateClassName,const char* objectName/*=""*/ ) { if (!objID)return NULL; if (!getNetInterface())return NULL; ////////////////////////////////////////////////////////////////////////// //the dist class : xDistributedClassesArrayType *_classes = getNetInterface()->getDistributedClassInterface()->getDistrutedClassesPtr(); //look it exist : xDistClassIt it = _classes->find(templateClassName); xDistributedClass *classTemplate = it->second; xDistributedObject*distObject = get(objID); ///////////////////////////////////////////////////////////////////////// //the network update : xNetInterface *cin = getNetInterface(); if (!cin) { //xLogger::xLog(ELOGERROR,XL_SESSION," return NULL; } vtConnection *con = cin->getConnection(); //if (!con)return NULL; ////////////////////////////////////////////////////////////////////////// //the dist object : xDistributedObjectsArrayType *distObjects = cin->getDistributedObjects(); if (!distObjects)return NULL; if ( !distObject /*&& classTemplate->GetEnitityType() == E_DC_BTYPE_3D_ENTITY */) { distObject = new xDistributedObject(); //distObject->SetDistributedClass(classTemplate); distObject->setObjectFlags(E_DO_CREATION_INCOMPLETE); distObject->setEntityID(objID); distObject->setServerID(-1); distObject->setCreationTime((float)TNL::Platform::getRealMilliseconds()); distObject->SetName(objectName); distObjects->push_back(distObject); xLogger::xLog(ELOGINFO,XL_START,"dist object created : %s",objectName); return distObject; } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ IDistributedObjects::IDistributedObjects() { m_NetworkInterface = NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ IDistributedObjects::IDistributedObjects(xNetInterface *netInterface) : m_NetworkInterface(netInterface) { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ IDistributedObjects::~IDistributedObjects() { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IDistributedObjects::Clean() { /*if(GetNetworkInterface()) GetNetworkInterface()->GetDistributedObjects()->Clear();*/ } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IDistributedObjects::deleteObject(int serverID) { TNL::logprintf("___delete object : %d",serverID); xDistributedObject *distObject = get(serverID); if (distObject) { removeObject(distObject); xDistributedClass *_class = distObject->getDistributedClass(); if (_class) { xLogger::xLog(XL_START,ELOGINFO,E_LI_DISTRIBUTED_BASE_OBJECT,"Distributed object deleted,server id : %d class : %s",serverID,_class->getClassName().getString()); if (_class->getEnitityType() == E_DC_BTYPE_SESSION ) { getNetInterface()->getDistributedClassInterface()->destroyClass(_class); } delete distObject; }else xLogger::xLog(XL_START,ELOGERROR,E_LI_DISTRIBUTED_BASE_OBJECT,"Object %d has no class!",serverID); }else{ xLogger::xLog(XL_START,ELOGERROR,E_LI_DISTRIBUTED_BASE_OBJECT,"Couldn't find distributed object with server id : %d",serverID); } } void IDistributedObjects::deleteObject(xDistributedObject*object) { //TNL::logprintf("___delete object : %d",serverID); if (!object) { xLogger::xLog(XL_START,ELOGERROR,E_LI_DISTRIBUTED_BASE_OBJECT,"invalid object"); return; } if (object) { removeObject(object); xDistributedClass *_class = object->getDistributedClass(); if (_class) { xLogger::xLog(XL_START,ELOGINFO,E_LI_DISTRIBUTED_BASE_OBJECT,"deleted %s | class : %s",object->GetName().getString(),_class->getClassName().getString()); if (_class->getEnitityType() == E_DC_BTYPE_SESSION ) { getNetInterface()->getDistributedClassInterface()->destroyClass(_class); } delete object; }else xLogger::xLog(XL_START,ELOGERROR,E_LI_DISTRIBUTED_BASE_OBJECT,"Object %d has no class!"); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IDistributedObjects::removeObject(xDistributedObject* object) { if (!object)return; if (!getNetInterface()) { return; } if (!getNetInterface()->getDistributedObjects())return; xDistributedObjectsArrayType *distObjects = getNetInterface()->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj && dobj==object) { xLogger::xLog(ELOGINFO,E_LI_DISTRIBUTED_BASE_OBJECT,"Removed : server id : %d | class : %s ",object->getServerID(),object->getDistributedClass() ? object->getDistributedClass()->getClassName().getString() : "NOCLASS"); getNetInterface()->getDistributedObjects()->erase(begin); xDistributedClass *_class = object->getDistributedClass(); if (_class && _class->getEnitityType() == E_DC_BTYPE_SESSION) { getNetInterface()->getDistributedClassInterface()->destroyClass(_class); }else xLogger::xLog(XL_START,ELOGERROR,E_LI_DISTRIBUTED_BASE_OBJECT,"Object %d : %s has no class!",object->getServerID(),object->GetName().getString()); return; } begin++; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IDistributedObjects::removeAll(xDistributedObjectsArrayType *distObjects) { if (!distObjects)return; xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { //distObjects->erase(begin); delete dobj; } //begin = distObjects->begin(); begin++; } distObjects->clear(); } <file_sep>#ifndef __P_FLUIDS_FLUID_EMITTER_H__ #define __P_FLUIDS_FLUID_EMITTER_H__ /** \addtogroup fluids @{ */ #include "Nxp.h" #include "NxPhysicsSDK.h" #include "pFluidEmitterDesc.h" class pFluid; class pFluidEmitterDesc; class NxShape; /** \brief The fluid emitter class. It represents an emitter (fluid source) which is associated with one fluid. The emitter is an alternative to adding particles to the fluid via the pFluid::addParticles() method. Emission always takes place in a plane given by the orientation and position of the emitter. The shape of the area of emission is either a rectangle or an ellipse. The direction of emission is usually perpendicular to the emission plane. However, this can be randomly modulated using the setRandomAngle() method. An emitter can have two types of operation: <ol> <li> <i>Constant pressure.</i> In this case the state of the surrounding fluid is taken into account. The emitter tries to match the rest spacing of the particles. Nice rays of water can be generated this way. <li> <i>Constant flow rate.</i> In this case the emitter keeps emitting the same number of particles each frame. The rate can be adjusted dynamically. </ol> The emitter's pose can be animated directly or attached to a shape which belongs to a dynamic actor. This shape is called the frame shape. When attaching an emitter to a shape, one has the option of enabling impulse transfer from the emitter to the body of the shape. The impulse generated is dependent on the rate, density, and velocity of the emitted particles. */ class MODULE_API pFluidEmitter { public: pFluidEmitter(); ~pFluidEmitter() {} /** \brief Sets the position of the emitter in world space. \param[in] vec New position in world space. */ void setGlobalPosition(const VxVector& vec); /** \brief Sets the orientation of the emitter in world space. \param[in] rot New orientation in world space. */ void setGlobalOrientation(const VxQuaternion& rot); /** \brief Returns the position of the emitter in world space. \return The world space position. */ VxVector getGlobalPosition()const; /** \brief Returns the orientation of the emitter in world space. \return The world space orientation. */ VxQuaternion getGlobalOrientation()const; /** \brief Sets the position of the emitter relative to the frameShape. The pose is relative to the shape frame. If the frameShape is NULL, world space is used. \param[in] vec The new local position of the emitter. @see pFluidEmitterDesc.relPose */ void setLocalPosition(const VxVector& vec) ; /** \brief Sets the orientation of the emitter relative to the frameShape. The pose is relative to the shape frame. If the frameShape is NULL, world space is used. \param[in] mat The new local orientation of the emitter. @see pFluidEmitterDesc.relPose */ void setLocalOrientation(const VxQuaternion& mat); /** \brief Returns the position of the emitter relative to the frameShape. The pose is relative to the shape frame. If the frameShape is NULL, world space is used. \return The local position of the emitter. @see pFluidEmitterDesc.relPose */ VxVector getLocalPosition()const; /** \brief Returns the orientation of the emitter relative to the frameShape. The pose is relative to the shape frame. If the frameShape is NULL, world space is used. \return The local orientation of the emitter. @see pFluidEmitterDesc.relPose */ VxQuaternion getLocalOrientation()const; /** \brief Sets the frame shape. Can be set to NULL. \param[in] shape The frame shape. @see pFluidEmitterDesc.frameShape */ void setFrameShape(CK3dEntity* shape); /** \brief Returns the frame shape. May be NULL. \return The frame shape. @see pFluidEmitterDesc.frameShape */ CK3dEntity * getFrameShape() const; /** \brief Returns the radius of the emitter along the x axis. \return Radius of emitter along the X axis. @see pFluidEmitterDesc.dimensionX */ float getDimensionX() const; /** \brief Returns the radius of the emitter along the y axis. \return Radius of emitter along the Y axis. @see pFluidEmitterDesc.dimensionY */ float getDimensionY()const; /** \brief Sets the maximal random displacement in every dimension. \param[in] disp The maximal random displacement of particles. @see pFluidEmitterDesc.randomPos */ void setRandomPos(VxVector disp); /** \brief Returns the maximal random displacement in every dimension. \return The maximal random displacement of particles. @see pFluidEmitterDesc.randomPos */ VxVector getRandomPos()const; /** \brief Sets the maximal random angle offset (in radians). <b>Unit:</b> Radians \param[in] angle Maximum random angle for emitted particles. @see pFluidEmitterDesc.randomAngle */ void setRandomAngle(float angle); /** \brief Returns the maximal random angle offset (in radians). <b>Unit:</b> Radians \return Maximum random angle for emitted particles. @see pFluidEmitterDesc.randomAngle */ float getRandomAngle(); /** \brief Sets the velocity magnitude of the emitted particles. \param[in] vel New velocity magnitude of emitted particles. @see pFluidEmitterDesc.fluidVelocityMagnitude */ void setFluidVelocityMagnitude(float vel) ; /** \brief Returns the velocity magnitude of the emitted particles. \return Velocity magnitude of emitted particles. @see pFluidEmitterDesc.fluidVelocityMagnitude */ float getFluidVelocityMagnitude() const; /** \brief Sets the emission rate (particles/second). Only used if the pEmitterType is PFET_ConstantFlowRate. \param[in] rate New emission rate. @see pFluidEmitterDesc.rate */ void setRate(float rate); /** \brief Returns the emission rate. \return Emission rate. @see pFluidEmitterDesc.rate */ float getRate() const; /** \brief Sets the particle lifetime. \param[in] life Lifetime of emitted particles. @see pFluidEmitterDesc.particleLifetime */ void setParticleLifetime(float life) ; /** \brief Returns the particle lifetime. \return Lifetime of emitted particles. @see pFluidEmitterDesc.particleLifetime */ float getParticleLifetime() const; /** \brief Sets the repulsion coefficient. \param[in] coefficient The repulsion coefficient in the range from 0 to inf. @see pFluidEmitterDesc.repulsionCoefficient getRepulsionCoefficient() */ void setRepulsionCoefficient(float coefficient); /** \brief Retrieves the repulsion coefficient. \return The repulsion coefficient. @see pFluidEmitterDesc.repulsionCoefficient setRepulsionCoefficient() */ float getRepulsionCoefficient() const; /** \brief Resets the particle reservoir. \param[in] new maxParticles value. @see pFluidEmitterDesc.maxParticles */ void resetEmission(int maxParticles); /** \brief Returns the maximal particle number to be emitted. \return max particles. @see pFluidEmitterDesc.maxParticles */ int getMaxParticles() const; /** \brief Returns the number of particles that have been emitted already. \return number of particles already emitted. */ int getNbParticlesEmitted() const; /** \brief Sets the emitter flags. \param[in] flag Member of #pFluidEmitterFlag. \param[in] val New flag value. @see pFluidEmitterFlag */ void setFlag(pFluidEmitterFlag flag, bool val); /** \brief Returns the emitter flags. \param[in] flag Member of #pFluidEmitterFlag. \return The current flag value. @see pFluidEmitterFlag */ bool getFlag(pFluidEmitterFlag flag) const; /** \brief Get the emitter shape. \param[in] shape Member of #pEmitterShape. \return True if it is of type shape. @see pFluidEmitterDesc.shape */ bool getShape(pEmitterShape shape) const; /** \brief Get the emitter type. \param[in] type Member of #pEmitterType \return True if it is of type type. @see pEmitterType */ bool getType(pEmitterType type) const; NxFluidEmitter* getEmitter() const { return mEmitter; } void setEmitter(NxFluidEmitter* val) { mEmitter = val; } /** \brief Returns the owner fluid. \return The fluid this emitter is associated with. */ pFluid * getFluid() const { return mFluid; } void setFluid(pFluid * val) { mFluid = val; } CK_ID getEntityReference() const { return mEntityReference; } void setEntityReference(CK_ID val) { mEntityReference = val; } pFluidRenderSettings * getRenderSettings() const { return mRenderSettings; } void setRenderSettings(pFluidRenderSettings * val) { mRenderSettings = val; } private : NxFluidEmitter* mEmitter; pFluid *mFluid; CK_ID mEntityReference; pFluidRenderSettings *mRenderSettings; }; /** @} */ #endif <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SendMidiSignal // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "../MidiManager.h" CKERROR CreateSendMidiSignalProto(CKBehaviorPrototype **); int SendMidiSignal(const CKBehaviorContext& behcontext); CKERROR SendMidiSignalCallBack(const CKBehaviorContext& behcontext); // CallBack Functioon /*******************************************************/ /* PROTO DECALRATION */ /*******************************************************/ CKObjectDeclaration *FillBehaviorSendMidiSignalDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Send Midi Data"); od->SetDescription("Sends a Midi signal."); od->SetCategory("Controllers/Midi"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x19c33646,0x22be5e86)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00020000); od->SetCreationFunction(CreateSendMidiSignalProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } /*******************************************************/ /* PROTO CREATION */ /*******************************************************/ CKERROR CreateSendMidiSignalProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Send Midi Data"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareOutput("Activated"); proto->DeclareOutput("Error"); proto->DeclareInParameter("cmd", CKPGUID_INT, "144"); proto->DeclareInParameter("var0", CKPGUID_INT, "10"); proto->DeclareInParameter("var1", CKPGUID_INT, "0"); proto->DeclareOutParameter("return code", CKPGUID_INT, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SendMidiSignal); *pproto = proto; return CK_OK; } /*******************************************************/ /* MAIN FUNCTION */ /*******************************************************/ int SendMidiSignal(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); int return_code; union { unsigned long word; unsigned char data[4]; } message; beh->GetInputParameterValue(0, &message.data[0]); beh->GetInputParameterValue(1, &message.data[1]); beh->GetInputParameterValue(2, &message.data[2] ); message.data[3] = 0; // unused return_code = midiOutShortMsg(mm->midiDeviceOutHandle, message.word); if (return_code != MMSYSERR_NOERROR) { mm->m_Context->OutputToConsole("error sending midi-cmd"); beh->SetOutputParameterValue(0,&return_code); beh->ActivateInput(0, FALSE); return CK_OK; }else beh->ActivateInput(1, FALSE); return CK_OK; } <file_sep>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* */ /* Fichier de portage Applis 16 bits --> Applis 32 bits */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* Version 1.0 ------------------------------------------------------- */ /* 25.11.95 Creation du source pour portage 32 bits */ #include <windows.h> #include <windowsx.h> #include "port32.h" /* --------------------------------- */ /* 32 bits code */ /* --------------------------------- */ #ifdef _WIN32 HINSTANCE GetTaskInstance (HWND hParentWnd) { return (HINSTANCE) GetWindowLong (hParentWnd,GWL_HINSTANCE); } /* GetTaskInstance */ LPSTR GetTempDrive(int nDrive) { static char szTempPath[144]; GetTempPath (sizeof szTempPath, szTempPath); return (LPSTR) szTempPath; } #endif /* --------------------------------- */ /* 16 bits code */ /* --------------------------------- */ #ifndef _WIN32 HINSTANCE GetTaskInstance (HWND hParentWnd) { TASKENTRY TaskEntry; if (hParentWnd==NULL) { TaskEntry.dwSize = sizeof TaskEntry; TaskFindHandle ( & TaskEntry, GetCurrentTask() ); return TaskEntry.hInst; } else return (HINSTANCE) GetWindowWord (hParentWnd,GWW_HINSTANCE); } /* GetTaskInstance */ #endif /* 16 bits code */ <file_sep>#ifndef __vtDistributedObjectsInterface_h_ #define __vtDistributedObjectsInterface_h_ #include "xNetTypes.h" class xDistributedObject; class xNetInterface; class IDistributedObjects { public: IDistributedObjects(); IDistributedObjects(xNetInterface *netInterface); ~IDistributedObjects(); xDistributedObject *create(int objID,const char *templateClassName,const char* objectName=""); xDistributedObject *getByUserID(int userID,int classType); xDistributedObject *get(int serverID); xDistributedObject *getByEntityID(int entityID); xDistributedObject *get(const char*name); xDistributedObject *get(const char*name,int classType); xNetInterface * getNetInterface(){return m_NetworkInterface;} void setNetInterface(xNetInterface * val){ m_NetworkInterface = val; } void create(const char* objectName,const char*className); void cCreateDistObject(int objectID,int ownerID,const char* objectName,const char*className); void removeObject(xDistributedObject* object); void deleteObject(int serverID); void deleteObject(xDistributedObject*object); void Clean(); virtual void Destroy(); virtual void removeAll(xDistributedObjectsArrayType *distObjects); uxString print(TNL::BitSet32 flags); protected: // TNL::SafePtr <xNetInterface> m_NetworkInterface; xNetInterface *m_NetworkInterface; private: }; #endif <file_sep>// OggReaderDll.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" #define READER_COUNT 1 CKPluginInfo g_piInfo[READER_COUNT]; #define READER_VERSION 0x00000001 #define OGGREADER_GUID CKGUID(0x28391930,0x225f26df) CKPluginInfo* OGGReader::GetReaderInfo() { return &g_piInfo[0]; } #ifdef CK_LIB CKDataReader *CKGet_OggReader_Reader(int pos) #else CKDataReader* CKGetReader(int pos) #endif { return new OGGReader; } #ifdef CK_LIB CKPluginInfo* CKGet_OggReader_PluginInfo(int index) #else CKPluginInfo* CKGetPluginInfo(int index) #endif { g_piInfo[0].m_GUID = OGGREADER_GUID; g_piInfo[0].m_Version = READER_VERSION; g_piInfo[0].m_Description = "Ogg Sound Files"; g_piInfo[0].m_Summary = "Ogg reader"; g_piInfo[0].m_Extension = "ogg"; g_piInfo[0].m_Author = "Flashbang Studios, LLC"; //g_piInfo[0].m_InitInstanceFct = InitInstance; g_piInfo[0].m_Type = CKPLUGIN_SOUND_READER; // Plugin Type return &g_piInfo[0]; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPJPointPlaneDecl(); CKERROR CreatePJPointPlaneProto(CKBehaviorPrototype **pproto); int PJPointPlane(const CKBehaviorContext& behcontext); CKERROR PJPointPlaneCB(const CKBehaviorContext& behcontext); enum bbInputs { bI_ObjectB, bI_Anchor, bI_AnchorRef, bI_Axis, bI_AxisRef, bI_Coll }; //************************************ // Method: FillBehaviorPJPointPlaneDecl // FullName: FillBehaviorPJPointPlaneDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPJPointPlaneDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJPointInPlane"); od->SetCategory("Physic/Joints"); od->SetDescription("Sets/modifies a point in plane joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x6b7f6a11,0x4cb565b8)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJPointPlaneProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJPointPlaneProto // FullName: CreatePJPointPlaneProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePJPointPlaneProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJPointInPlane"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJPointInPlane <br> PJPointPlane is categorized in \ref Joints <br> <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Creates or modifies a cylindrical joint between a two bodies or the world. <br> <br>See <A HREF="PJPointInPlane.cmo">PJPointInPlane.cmo</A>. \image html pointInPlaneJoint.png <h3>Technical Information</h3> \image html PJPointPlane.png A point in plane joint constrains a point on one actor to only move inside a plane attached to another actor. The point attached to the plane is defined by the anchor point. The joint's axis specifies the plane normal. An example for a point in plane joint is a magnet on a refrigerator. DOFs removed: 1 DOFs remaining: 5 <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Body B: </SPAN>The second body. Leave blank to create a joint constraint with the world. <BR> <SPAN CLASS="pin">Anchor:</SPAN>A point in world space coordinates. See pJointPointInPlane::setGlobalAnchor(). <BR> <SPAN CLASS="pin">Anchor Reference: </SPAN>A helper entity to transform a local anchor into the world space. <BR> <SPAN CLASS="pin">Axis: </SPAN>An in world space. See pJointPointInPlane::setGlobalAxis(). <BR> <SPAN CLASS="pin">Axis Up Reference: </SPAN>A helper entity to transform a local axis into the world space. <BR> <SPAN CLASS="pin">Collision: </SPAN>Enables Collision. See pJointPointInPlane::enableCollision(). <BR> <h3>VSL : Creation </h3><br> <SPAN CLASS="NiceCode"> \include PJPointInPlane.vsl </SPAN> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createPointInPlaneJoint().<br> */ proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( PJPointPlaneCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Anchor",CKPGUID_VECTOR); proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Axis",CKPGUID_VECTOR); proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Collision",CKPGUID_BOOL); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PJPointPlane); *pproto = proto; return CK_OK; } //************************************ // Method: PJPointPlane // FullName: PJPointPlane // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJPointPlane(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_PointInPlane)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA && ! worldB ) bbErrorME("Couldnt find any world object"); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); //anchor : VxVector anchor = GetInputParameterValue<VxVector>(beh,bI_Anchor); VxVector anchorOut = anchor; CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); if (anchorReference) { anchorReference->Transform(&anchorOut,&anchor); } //swing axis VxVector Axis = GetInputParameterValue<VxVector>(beh,bI_Axis); VxVector axisOut = Axis; CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); if (axisReference) { VxVector dir,up,right; axisReference->GetOrientation(&dir,&up,&right); axisReference->TransformVector(&axisOut,&up); } ////////////////////////////////////////////////////////////////////////// int col = GetInputParameterValue<int>(beh,bI_Coll); ////////////////////////////////////////////////////////////////////////// // pJointPointInPlane *joint = static_cast<pJointPointInPlane*>(GetPMan()->getJoint(target,targetB,JT_PointInPlane)); if(bodyA || bodyB) { ////////////////////////////////////////////////////////////////////////// //joint create ? if (!joint) { joint = static_cast<pJointPointInPlane*>(pFactory::Instance()->createPointInPlaneJoint(target,targetB,anchorOut,axisOut)); } ////////////////////////////////////////////////////////////////////////// Modification : if (joint) { joint->setGlobalAxis(axisOut); joint->setGlobalAnchor(anchorOut); joint->enableCollision(col); } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: PJPointPlaneCB // FullName: PJPointPlaneCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJPointPlaneCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { break; } } return CKBR_OK; }<file_sep>#ifndef __VTODE_ENUMS_H_ #define __VTODE_ENUMS_H_ #endif<file_sep>#ifndef SOFT_MESH_OBJ_H #define SOFT_MESH_OBJ_H namespace SOFTBODY { class SoftMeshInterface; bool loadSoftMeshObj(const char *oname,const char *tname,SoftMeshInterface *smi); }; // END OF SOFTBODY NAMESPACE #endif <file_sep>rmdir .\Release /s /q mkdir Release xcopy ..\Release\Author .\Release /s /e REM #rar a -ep1 -r -s -x@RarExclusionList.txt vtPhysXDemo.zip ..\Release\Author\ winrar a -ep1 -r -s -x@RarExclusionList.txt -n@RarInclusionList.txt vtPhysXDemo.zip Release REM rar a -r -s -x@RarExclusionList.txt -agYYYYMMDD-HHMM GBLSourceSnapshot.rar ..\\.. <file_sep> /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* */ /* D L L F T P */ /* */ /* W I N D O W S */ /* */ /* P o u r A r t h i c */ /* */ /* V e r s i o n 3 . 0 */ /* */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* -------------------------- */ /* internal header file */ /* -------------------------- */ #ifdef PAS_TCP4W # define FTP_DEFCTRLPORT (htons (21)) /* port FTP commande */ #else # define FTP_DEFCTRLPORT 21 /* port FTP commande */ #endif #define FTP_DEFTIMEOUT 30 /* timeout en secondes */ #define FTP_TMPSTRLENGTH 50 /* taille d'une chaine temporaire */ #define FTP_REPSTRLENGTH 256 /* taille d'une chaine repertoire */ /* messages internes */ #define WMFTP_RELEASE (WM_USER+92) /* msg interne demande FtpRelease */ #define WMFTP_RECV (WM_USER+95) /* msg interne de réception fichier */ #define WMFTP_DIR (WM_USER+96) /* msg interne de réception dir */ #define WMFTP_SEND (WM_USER+98) /* msg interne d'envoi de fichier */ /* Modes d'ouverture de fichier */ #define FTPMODE_WRITE 32 #define FTPMODE_READ 216 #define FTPMODE_APPEND 467 #define FTPMODE_NOTHING 0 /* pause dans l'envoi/réception */ #define FTP_DEFASYNCALONE 10 #define FTP_DEFASYNCMULTI 3 #define FTP_DEFDELAY 100 /* millisecondes */ #define FTP_DIRRATE(pX) (pX->Next==NULL && pX->Prev==NULL ? 10 : 4) #define FTP_RATE(pX) (pX->Next==NULL && pX->Prev==NULL ? \ pX->File.nAsyncAlone : pX->File.nAsyncMulti) /* return codes for GetFtpConnectSocket/GetFtpListeSocket */ #define INVALID_MODE ((SOCKET) -2) #define INVALID_ANSWER ((SOCKET) -3) /* Arret pendant un transfert */ #define HAS_ABORTED() ( IsBadWritePtr (pProcData,sizeof *pProcData) \ || pProcData->File.bAborted) /* Fin de fonction asynchrone/synchrone */ #define RETURN(pD,x) \ { if( (! IsBadWritePtr(pD,sizeof *pD)) && pD->File.bAsyncMode ) \ { PostMessage(pD->Msg.hParentWnd,pD->Msg.nCompletedMessage,TRUE,x); \ return FTPERR_OK; } \ else { return x; } } /* ------------------------------------------------- */ /* structures imbriquees */ /* ------------------------------------------------- */ struct S_FtpData { SOCKET ctrl_socket; /* control stream init INVALID_SOCKET */ SOCKET data_socket; /* data stream init INVALID_SOCKET */ char cType; /* type (ASCII/binary) init TYPE_A */ BOOL bVerbose; /* verbose mode init FALSE */ BOOL bPassif; /* VRAI -> mode passif */ unsigned short nPort; /* connexion Port init FTP_DEFPORT */ unsigned nTimeOut; /* TimeOut in seconds init FTP_DEFTIMEOUT */ HFILE hLogFile; /* Log file */ char szInBuf [2048]; /* incoming Buffer */ struct sockaddr_in saSockAddr; /* not used anymore */ struct sockaddr_in saAcceptAddr; /* not used anymore */ }; /* struct S_FtpData */ struct S_FileTrf { HFILE hf; /* handle of the file which is being transfered */ unsigned nCount; /* number of writes/reads made on a file */ unsigned nAsyncAlone;/* pause each N frame in Async mode (Def 40) */ unsigned nAsyncMulti;/* Idem but more than one FTP sssion (Def 10) */ unsigned nDelay; /* time of the pause in milliseconds */ BOOL bAborted; /* data transfer has been canceled */ char szBuf[FTP_DATABUFFER]; /* Data buffer */ BOOL bNotify; /* application receives a msg each data packet */ BOOL bAsyncMode; /* synchronous or asynchronous Mode */ LONG lPos; /* Bytes transfered */ LONG lTotal; /* bytes to be transfered */ }; /* struct S_FileTrf */ struct S_Msg { HWND hParentWnd; /* window which the msg is to be passed */ UINT nCompletedMessage; /* msg to be sent at end of the function */ }; /* struct S_Msg */ struct S_Verbose { HWND hVerboseWnd; /* window which the message is to be passed */ UINT nVerboseMsg; /* msg to be sent each time a line is received */ }; /* ------------------------------------------------- */ /* global structure */ /* ------------------------------------------------- */ struct S_ProcData { /* task data */ THREADID (CALLBACK * fIdentifyThread)(void); /* function d'identification thread */ THREADID nThreadIdent; /* Identifiant du Thread */ /*HTASK hTask; * Task Id */ HWND hFtpWnd; /* Handle of the internal window */ HWND hParentWnd; /* handle given to the FtpInit function */ HINSTANCE hInstance; /* Task Instance */ BOOL bRelease; /* FtpRelease has been called */ /* Mesasge information */ struct S_Msg Msg; struct S_Verbose VMsg; /* File information */ struct S_FileTrf File; /* Ftp information */ struct S_FtpData ftp; /* Linked list */ struct S_ProcData far *Next; struct S_ProcData far *Prev; }; /* struct S_ProcData */ typedef struct S_ProcData far * LPProcData; typedef struct S_FtpData far * LPFtpData; /* ------------------------------------------------- */ /* donnees automate */ /* ------------------------------------------------- */ #define _S_END -2 enum FtpCmds { _S_CONNECT = 0, _S_USER, _S_PASS, _S_ACCOUNT, _S_QUIT, _S_HELP, _S_HELPCMD, _S_DELE, _S_CWD, _S_CDUP, _S_MKD, _S_RMD, _S_PWD, _S_TYPE, _S_RNFR, _S_RNTO, _S_SYST, _S_NOOP, _S_REST, _S_ENDFILETRANSFER }; /* ------------------------------------------------- */ /* primitives internes */ /* ------------------------------------------------- */ LPProcData _export PASCAL FAR FtpDataPtr(void); int Protection (void); int PASCAL FAR IntFtpGetAnswerCode (LPFtpData pFtpData); int PASCAL FAR IntTnSend (SOCKET s, LPSTR szString, BOOL bHighPriority, HFILE hf); /* etage III : fonctions FTP */ int FtpCloseFileTransfer (LPProcData pProcData, BOOL bFlush); /* utilitaires */ LPProcData ToolsLocateProcData (void); SOCKET GetFTPListenSocket(LPFtpData pFtpData); int AbortAction (LPProcData pProcData, BOOL bFlush, BOOL bMsg, UINT nDbg); /* Synchrones */ int FtpSyncSend (LPProcData pProcData); int FtpSyncRecv (LPProcData pProcData); /* Asynchrone */ LRESULT _export PASCAL FAR DLLWndProc (HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); void _cdecl Ftp4w_Trace (const char *szFile, const char *fmt, ...); <file_sep>/* * u2d v 1.10 Last Revision 02/03/1998 1.10 * *=========================================================================== * * Project: u2d, Unix To Dos converter * File: u2d.c * Purpose: u2d source code. * Compilation vith microsoft C compiler: * cl -O1 u2d.c setargv.obj * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <stdio.h> int Convert (char *szFile) { #define XX_RETURN(s,x) \ { printf ("%s\n", s) ; if (pFIn!=NULL) fclose(pFIn) ; \ if (pFOut!=NULL) fclose(pFOut); \ if (TmpFile!=NULL) remove(TmpFile); \ return x; } char *TmpFile=NULL; int c; FILE *pFIn=NULL, *pFOut=NULL; printf ("%s", szFile); fflush (stdout); TmpFile = tmpnam(NULL); if (TmpFile==NULL) XX_RETURN ("\tCan not create temporary file", -1); pFOut = fopen (TmpFile, "w"); if (pFOut==NULL) XX_RETURN ("\tCan not create temporary file", -2); pFIn = fopen (szFile, "r"); if (pFIn==NULL) XX_RETURN ("\tCan not open input file", -3); while ( (c=fgetc (pFIn)) != EOF) { if (fputc (c, pFOut)==EOF) XX_RETURN ("\tCan not write into output file", -4); } if (!feof (pFIn)) XX_RETURN ("\tCan not read from input file", -5); fclose (pFIn); fclose (pFOut); if (remove (szFile)) XX_RETURN ("\tCan not rename output file", -6); if (rename (TmpFile, szFile)==-1) { printf ("\tinput file %s removed, temp file %s can not be removed\n", szFile, TmpFile); return -8; } printf ("\n"); return 0; } /* Convert */ int main (int argc, char *argv[]) { if (argc<2) { printf ("Usage: u2d file [file [...]]\n" "Translate a unix text file. Existing file is overwritten\n"); } else {int Ark; for (Ark=1 ; Ark<argc ; Ark++) Convert (argv[Ark]); } return 0; } /* main */ <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtAttributeHelper.h" pJoint*PhysicManager::getJoint(CK3dEntity*referenceA,CK3dEntity*referenceB/* =NULL */,JType type/* =JT_Any */) { pJoint *result = NULL; pRigidBody *a = GetPMan()->getBody(referenceA); pRigidBody *b = GetPMan()->getBody(referenceB); pWorld *wA = a ? a->getWorld() : NULL; pWorld *wB = b ? b->getWorld() : NULL; pWorld *worldFinal = NULL; bool oneBodyJoint = false;// body with world frame ? CK3dEntity* oneBodyJointReference =NULL; //---------------------------------------------------------------- // // Sanity Checks // XString errorString; // Reference A physicalized at all ? if ( !referenceA && !referenceB ) { errorString.Format("No reference specified"); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); return result; } // Reference A IS NOT Reference B ? if ( (referenceA!=NULL && referenceB!=NULL) && (a==b) ) { errorString.Format("Reference A (%s) is the same as Reference B (%s)",referenceA->GetName()); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); return result; } // Reference A physicalized at all ? if (referenceA && !a){ errorString.Format("Reference A (%s) valid but not physicalized",referenceA->GetName()); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); return result; } // Reference B physicalized at all ? if (referenceB && !b){ errorString.Format("Reference B (%s) valid but not physicalized",referenceB->GetName()); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); return result; } // world of object a valid ? if (a && !wA){ errorString.Format("Reference A (%s) is physicalized but has no valid world object",referenceA->GetName()); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); return result; } // world of object b valid ? if (b && !wB){ errorString.Format("Reference B (%s) is physicalized but has no valid world object",referenceB->GetName()); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); return result; } // rigid bodies are in the same world if ( (wA!=NULL && wB!=NULL) && (wA!=wB) ) { errorString.Format("Reference A (%s) and B(%s) is physicalized but are not in the same world",referenceA->GetName(),referenceB->GetName()); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); return result; } //---------------------------------------------------------------- // // Preparing lookup // if ( wA ) worldFinal = wA; if ( wB ) worldFinal = wB; // constraint is attached to world frame ? if ( (a && !b) || (b && !a) ) oneBodyJoint = true; // world frame constraint, track the reference if (oneBodyJoint) { if ( a ) oneBodyJointReference = referenceA; if ( b ) oneBodyJointReference = referenceB; } //---------------------------------------------------------------- // // Parse the scene joints // NxU32 jointCount = worldFinal->getScene()->getNbJoints(); if (jointCount) { NxArray< NxJoint * > joints; worldFinal->getScene()->resetJointIterator(); for (NxU32 i = 0; i < jointCount; ++i) { NxJoint *j = worldFinal->getScene()->getNextJoint(); pJoint *_cJoint = static_cast<pJoint*>( j->userData ); if (!_cJoint) continue; //---------------------------------------------------------------- // // Special case : has a joint at all, only for world frame constraints // if (type == JT_Any) { if ( oneBodyJoint && _cJoint->GetVTEntA() == oneBodyJointReference || _cJoint->GetVTEntB() == oneBodyJointReference ) return _cJoint; } //---------------------------------------------------------------- // // Specific joint type // if ( j->getType() == type) { //---------------------------------------------------------------- // // world constraint joint // if (oneBodyJoint && _cJoint->GetVTEntA() == oneBodyJointReference || _cJoint->GetVTEntB() == oneBodyJointReference ) return _cJoint; //---------------------------------------------------------------- // // Two references given // if ( _cJoint->GetVTEntA() == referenceA && _cJoint->GetVTEntB() == referenceB ) return _cJoint; if ( _cJoint->GetVTEntA() == referenceB && _cJoint->GetVTEntB() == referenceA ) return _cJoint; } } } return NULL; }<file_sep>#include "CKAll.h" #ifdef WebPack #define CAMERA_BEHAVIOR CKGUID(0x12d94eba,0x47057415) #define CKPGUID_PROJECTIONTYPE CKDEFINEGUID(0x1ee22148, 0x602c1ca1) #define CKPGUID_MOUSEBUTTON CKGUID(0x1ff24d5a,0x122f2c1f) CKERROR InitInstanceCamera(CKContext* context) { CKParameterManager* pm = context->GetParameterManager(); pm->RegisterNewEnum( CKPGUID_PROJECTIONTYPE,"Projection Mode","Perspective=1,Orthographic=2" ); // Mouse Camera Orbit pm->RegisterNewEnum(CKPGUID_MOUSEBUTTON,"Mouse Button","Left=0,Middle=2,Right=1" ); return CK_OK; } CKERROR ExitInstanceCamera(CKContext* context) { CKParameterManager* pm = context->GetParameterManager(); pm->UnRegisterParameterType(CKPGUID_PROJECTIONTYPE); pm->UnRegisterParameterType(CKPGUID_MOUSEBUTTON); return CK_OK; } int RegisterCameraBeh(XObjectDeclarationArray *reg) { // Cameras/Basic RegisterBehavior(reg, FillBehaviorDollyDecl); RegisterBehavior(reg, FillBehaviorSetOrthographicZoomDecl); RegisterBehavior(reg, FillBehaviorSetCameraTargetDecl); RegisterBehavior(reg, FillBehaviorSetClippingDecl); RegisterBehavior(reg, FillBehaviorSetFOVDecl); RegisterBehavior(reg, FillBehaviorSetProjectionDecl); RegisterBehavior(reg, FillBehaviorSetZoomDecl); // Cameras/FX RegisterBehavior(reg, FillBehaviorCameraColorFilterDecl); RegisterBehavior(reg, FillBehaviorVertigoDecl); // Cameras/Montage RegisterBehavior(reg, FillBehaviorGetCurrentCameraDecl); RegisterBehavior(reg, FillBehaviorSetAsActiveCameraDecl); // Cameras/Movement RegisterBehavior(reg, FillBehaviorOrbitDecl); RegisterBehavior(reg, FillBehaviorKeyboardCameraOrbitDecl); RegisterBehavior(reg, FillBehaviorMouseCameraOrbitDecl); RegisterBehavior(reg, FillBehaviorJoystickCameraOrbitDecl); RegisterBehavior(reg, FillBehaviorGenericCameraOrbitDecl); return 0; } #endif<file_sep>/* -*- c -*- */ /* ------------------------------------------------------------------------- * swig.i * * Interface file for the SWIG core. * * Author(s) : <NAME> (<EMAIL>) * <NAME> (<EMAIL>) * * Copyright (C) 1999-2000. The University of Chicago * See the file LICENSE for information on usage and redistribution. * * $Header: /cvsroot/swig/SWIG/Source/Swig/swig.i,v 1.11 2002/11/30 22:10:17 beazley Exp $ * ------------------------------------------------------------------------- */ /* todo: implement callable stuff -- ternaryfunc? */ /* todo: new DOH type to wrap Python objects. geesh. */ /* todo: Delattr -> return errors */ %module swig %{ #include "doh.h" %} %typemap(python,in) FILE * { $target = PyFile_AsFile($source); } %typemap(python,out) FILE * { $target = PyFile_FromFile($source, "unknown", "?", fclose); } %{ /* ------------------------------------------------------------------------- * An extension type for DOH objects -- we could use shadow classes, * but this will be lots faster, and provide a slightly cleaner interface. * ------------------------------------------------------------------------- */ typedef struct PyDOH { PyObject_HEAD DOH *doh; } PyDOH; staticforward PyTypeObject PyDOHSequenceType, PyDOHMappingType; /* --------------------------------------------------------------------- */ /* meta-functions */ /* Given a DOH object, return an equivalent PyObject. Note that when the PyObject is destroyed, the DOH's reference count will decrease; thus this is refcount-safe on both the DOH and Python sides. */ static PyObject * Swig_PyDOH_new(DOH *in) { PyDOH *self; if (!in) { Incref(Py_None); return Py_None; } if (DohIsMapping(in)) self = PyObject_NEW(PyDOH, &PyDOHMappingType); else self = PyObject_NEW(PyDOH, &PyDOHSequenceType); if (!self) return (PyObject *)self; self->doh = in; Incref(in); /* increase the DOH refcount */ return (PyObject *)self; } static void Swig_PyDOH_delete(PyDOH *self) { Delete(self->doh); /* decrease the DOH refcount */ PyMem_DEL(self); } static int Swig_PyDOH_check(void *self) { return ((PyObject *)self)->ob_type == &PyDOHMappingType || ((PyObject *)self)->ob_type == &PyDOHSequenceType; } /* Given a PyObject, return an equivalent DOH object */ static PyDOH *Swig_PyDOH_as_DOH(PyObject *source) { DOH *target; if (Swig_PyDOH_check(source)) target = ((PyDOH *)source)->doh; else if (PyString_Check(source)) target = (DOH *)PyString_AsString(source); else if (PySequence_Check(source)) printf("Sequence -> NULL\n"), target = NULL; else if (PyMapping_Check(source)) printf("Mapping -> NULL\n"), target = NULL; else if (PyNumber_Check(source)) target = (DOH *)source; else if (PyFile_Check(source)) target = (DOH *)PyFile_AsFile(source); else printf("?? -> NULL\n"), target = NULL; return target; } /* --------------------------------------------------------------------- */ /* sequence methods */ static int Swig_PyDOH_length(PyDOH *self) { return Len(self->doh); /* also a mapping method */ } static PyObject *Swig_PyDOH_item(PyDOH *self, int index) { DOH *r = Getitem(self->doh, index); if (r) return Swig_PyDOH_new(r); /* return an exception */ PyErr_SetObject(PyExc_KeyError, PyInt_FromLong(index)); return NULL; } static int Swig_PyDOH_ass_item(PyDOH *self, int index, PyObject *v) { int result; if (v) result = Setitem(self->doh, index, Swig_PyDOH_as_DOH(v)); else /* NULL v => delete item */ result = Delitem(self->doh, index); /* post an exception if necessary */ if (result == -1) PyErr_SetObject(PyExc_KeyError, PyInt_FromLong(index)); return result; } static PySequenceMethods Swig_PyDOH_as_sequence = { (inquiry)Swig_PyDOH_length, (binaryfunc)NULL, /* sq_concat */ (intargfunc)NULL, /* sq_repeat */ (intargfunc)Swig_PyDOH_item, (intintargfunc)NULL, /* sq_slice */ (intobjargproc)Swig_PyDOH_ass_item, (intintobjargproc)NULL /* sq_ass_slice */ }; /* --------------------------------------------------------------------- */ /* Mapping methods */ static PyObject *Swig_PyDOH_subscript(PyDOH *self, PyObject *k) { DOH *r = Getattr(self->doh, Swig_PyDOH_as_DOH(k)); if (r) return Swig_PyDOH_new(r); PyErr_SetObject(PyExc_KeyError, k); return NULL; } static int Swig_PyDOH_ass_subscript(PyDOH *self, PyObject *k, PyObject *v) { int result = 0; if (v) result = Setattr(self->doh, Swig_PyDOH_as_DOH(k), Swig_PyDOH_as_DOH(v)); else Delattr(self->doh, Swig_PyDOH_as_DOH(k)); if (result == -1) PyErr_SetObject(PyExc_KeyError, k); return result; } static PyMappingMethods Swig_PyDOH_as_mapping = { (inquiry)Swig_PyDOH_length, (binaryfunc)Swig_PyDOH_subscript, (objobjargproc)Swig_PyDOH_ass_subscript }; /* --------------------------------------------------------------------- */ /* named methods */ static PyObject *Swig_PyDOH_Copy(PyDOH *self, PyObject *args) { DOH * _result; if(!PyArg_ParseTuple(args,":Copy")) return NULL; _result = (DOH *)DohCopy(self->doh); return Swig_PyDOH_new(_result); } static PyObject *Swig_PyDOH_Clear(PyDOH *self, PyObject *args) { if(!PyArg_ParseTuple(args,":Clear")) return NULL; DohClear(self->doh); Py_INCREF(Py_None); return Py_None; } static PyObject *Swig_PyDOH_SetScope(PyDOH *self, PyObject *args) { int _arg1; if(!PyArg_ParseTuple(args,"i:SetScope",&_arg1)) return NULL; DohSetScope(self->doh,_arg1); Py_INCREF(Py_None); return Py_None; } static PyObject *Swig_PyDOH_Dump(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; DOH * _arg1; PyObject * _obj1 = 0; if(!PyArg_ParseTuple(args,"O:Dump",&_obj1)) return NULL; _arg1 = Swig_PyDOH_as_DOH(_obj1); _result = (int )DohDump(self->doh,_arg1); return PyInt_FromLong(_result); } static PyObject *Swig_PyDOH_Firstkey(PyDOH *self, PyObject *args) { PyObject * _resultobj; DOH * _result; if(!PyArg_ParseTuple(args,":Firstkey")) return NULL; _result = (DOH *)DohFirstkey(self->doh); _resultobj = Swig_PyDOH_new(_result); return _resultobj; } static PyObject *Swig_PyDOH_Nextkey(PyDOH *self, PyObject *args) { PyObject * _resultobj; DOH * _result; if(!PyArg_ParseTuple(args,":Nextkey")) return NULL; _result = (DOH *)DohNextkey(self->doh); _resultobj = Swig_PyDOH_new(_result); return _resultobj; } static PyObject *Swig_PyDOH_GetInt(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; DOH * _arg1; PyObject * _obj1 = 0; if(!PyArg_ParseTuple(args,"O:GetInt",&_obj1)) return NULL; _arg1 = Swig_PyDOH_as_DOH(_obj1); _result = (int )DohGetInt(self->doh,_arg1); _resultobj = Py_BuildValue("i",_result); return _resultobj; } static PyObject *Swig_PyDOH_GetDouble(PyDOH *self, PyObject *args) { PyObject * _resultobj; double _result; DOH * _arg1; PyObject * _obj1 = 0; if(!PyArg_ParseTuple(args,"O:GetDouble",&_obj1)) return NULL; _arg1 = Swig_PyDOH_as_DOH(_obj1); _result = (double )DohGetDouble(self->doh,_arg1); _resultobj = Py_BuildValue("d",_result); return _resultobj; } static PyObject *Swig_PyDOH_GetChar(PyDOH *self, PyObject *args) { PyObject * _resultobj; char * _result; DOH * _arg1; PyObject * _obj1 = 0; if(!PyArg_ParseTuple(args,"O:GetChar",&_obj1)) return NULL; _arg1 = Swig_PyDOH_as_DOH(_obj1); _result = (char *)DohGetChar(self->doh,_arg1); _resultobj = Py_BuildValue("s", _result); return _resultobj; } static PyObject *Swig_PyDOH_SetInt(PyDOH *self, PyObject *args) { PyObject * _resultobj; DOH * _arg1; int _arg2; PyObject * _obj1 = 0; if(!PyArg_ParseTuple(args,"Oi:SetInt",&_obj1,&_arg2)) return NULL; _arg1 = Swig_PyDOH_as_DOH(_obj1); DohSetInt(self->doh,_arg1,_arg2); Py_INCREF(Py_None); _resultobj = Py_None; return _resultobj; } static PyObject *Swig_PyDOH_SetDouble(PyDOH *self, PyObject *args) { PyObject * _resultobj; DOH * _arg1; double _arg2; PyObject * _obj1 = 0; if(!PyArg_ParseTuple(args,"Od:SetDouble",&_obj1,&_arg2)) return NULL; _arg1 = Swig_PyDOH_as_DOH(_obj1); DohSetDouble(self->doh,_arg1,_arg2); Py_INCREF(Py_None); _resultobj = Py_None; return _resultobj; } static PyObject *Swig_PyDOH_Insertitem(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; int _arg1; DOH * _arg2; PyObject * _obj2 = 0; if(!PyArg_ParseTuple(args,"iO:Insertitem",&_arg1,&_obj2)) return NULL; _arg2 = Swig_PyDOH_as_DOH(_obj2); _result = (int )DohInsertitem(self->doh,_arg1,_arg2); _resultobj = Py_BuildValue("i",_result); return _resultobj; } static PyObject *Swig_PyDOH_Firstitem(PyDOH *self, PyObject *args) { PyObject * _resultobj; DOH * _result; if(!PyArg_ParseTuple(args,":Firstitem")) return NULL; _result = (DOH *)DohFirstitem(self->doh); _resultobj = Swig_PyDOH_new(_result); return _resultobj; } static PyObject *Swig_PyDOH_Nextitem(PyDOH *self, PyObject *args) { PyObject * _resultobj; DOH * _result; if(!PyArg_ParseTuple(args,":Nextitem")) return NULL; _result = (DOH *)DohNextitem(self->doh); _resultobj = Swig_PyDOH_new(_result); return _resultobj; } static PyObject *Swig_PyDOH_Write(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; int _arg2; char * _arg1 = 0; if(!PyArg_ParseTuple(args,"si:Write",&_arg1,&_arg2)) return NULL; _result = (int )DohWrite(self->doh,_arg1,_arg2); _resultobj = Py_BuildValue("i",_result); return _resultobj; } static PyObject *Swig_PyDOH_Read(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; int _arg2; char *buffer; if(!PyArg_ParseTuple(args,"i:Read",&_arg2)) return NULL; buffer = DohMalloc(_arg2); if (!buffer) { PyErr_SetString(PyExc_MemoryError, "Not enough memory for Read buffer"); return NULL; } _result = (int )DohRead(self->doh,buffer,_arg2); _resultobj = Py_BuildValue("(is)",_result, buffer); DohFree(buffer); return _resultobj; } static PyObject *Swig_PyDOH_Seek(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; long _arg1; int _arg2; if(!PyArg_ParseTuple(args,"li:Seek",&_arg1,&_arg2)) return NULL; _result = (int )DohSeek(self->doh,_arg1,_arg2); _resultobj = Py_BuildValue("i",_result); return _resultobj; } static PyObject *Swig_PyDOH_Tell(PyDOH *self, PyObject *args) { PyObject * _resultobj; long _result; if(!PyArg_ParseTuple(args,":Tell")) return NULL; _result = (long )DohTell(self->doh); _resultobj = Py_BuildValue("l",_result); return _resultobj; } static PyObject *Swig_PyDOH_Getc(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; if(!PyArg_ParseTuple(args,":Getc")) return NULL; _result = (int )DohGetc(self->doh); if (_result > 0) { char c[2] = { (char)_result, 0 }; _resultobj = PyString_FromString(c); } else { Py_INCREF(Py_None); _resultobj = Py_None; } return _resultobj; } static PyObject *Swig_PyDOH_Putc(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; int _arg0; if(!PyArg_ParseTuple(args,"i:Putc",&_arg0)) return NULL; _result = (int )DohPutc(_arg0, self->doh); _resultobj = Py_BuildValue("i",_result); return _resultobj; } static PyObject *Swig_PyDOH_Ungetc(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; int _arg0; if(!PyArg_ParseTuple(args,"iO:Ungetc",&_arg0)) return NULL; _result = (int )DohUngetc(_arg0,self->doh); _resultobj = Py_BuildValue("i",_result); return _resultobj; } static PyObject *Swig_PyDOH_Getline(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _result; if(!PyArg_ParseTuple(args,":Getline")) return NULL; _result = (int )DohGetline(self->doh); _resultobj = Py_BuildValue("i",_result); return _resultobj; } static PyObject *Swig_PyDOH_Setline(PyDOH *self, PyObject *args) { PyObject * _resultobj; int _arg1; if(!PyArg_ParseTuple(args,"i:Setline",&_arg1)) return NULL; DohSetline(self->doh,_arg1); Py_INCREF(Py_None); _resultobj = Py_None; return _resultobj; } static PyObject *Swig_PyDOH_Getfile(PyDOH *self, PyObject *args) { PyObject * _resultobj; DOH * _result; if(!PyArg_ParseTuple(args,":Getfile")) return NULL; _result = (DOH *)DohGetfile(self->doh); _resultobj = Swig_PyDOH_new(_result); return _resultobj; } static PyObject *Swig_PyDOH_Setfile(PyDOH *self, PyObject *args) { PyObject * _resultobj; DOH * _arg1; PyObject * _obj1 = 0; if(!PyArg_ParseTuple(args,"O:Setfile",&_obj1)) return NULL; _arg1 = Swig_PyDOH_as_DOH(_obj1); DohSetfile(self->doh,_arg1); Py_INCREF(Py_None); _resultobj = Py_None; return _resultobj; } static struct PyMethodDef Swig_PyDOH_methods[] = { {"copy", (PyCFunction)Swig_PyDOH_Copy, METH_VARARGS}, {"clear", (PyCFunction)Swig_PyDOH_Clear, METH_VARARGS}, {"setscope", (PyCFunction)Swig_PyDOH_SetScope, METH_VARARGS}, {"dump", (PyCFunction)Swig_PyDOH_Dump, METH_VARARGS}, {"firstkey", (PyCFunction)Swig_PyDOH_Firstkey, METH_VARARGS}, {"nextkey", (PyCFunction)Swig_PyDOH_Nextkey, METH_VARARGS}, {"getint", (PyCFunction)Swig_PyDOH_GetInt, METH_VARARGS}, {"getdouble", (PyCFunction)Swig_PyDOH_GetDouble, METH_VARARGS}, {"getchar", (PyCFunction)Swig_PyDOH_GetChar, METH_VARARGS}, {"setint", (PyCFunction)Swig_PyDOH_SetInt, METH_VARARGS}, {"setdouble", (PyCFunction)Swig_PyDOH_SetDouble, METH_VARARGS}, {"insertitem", (PyCFunction)Swig_PyDOH_Insertitem, METH_VARARGS}, {"insert", (PyCFunction)Swig_PyDOH_Insertitem, METH_VARARGS}, {"firstitem", (PyCFunction)Swig_PyDOH_Firstitem, METH_VARARGS}, {"nextitem", (PyCFunction)Swig_PyDOH_Nextitem, METH_VARARGS}, {"write", (PyCFunction)Swig_PyDOH_Write, METH_VARARGS}, {"read", (PyCFunction)Swig_PyDOH_Read, METH_VARARGS}, {"seek", (PyCFunction)Swig_PyDOH_Seek, METH_VARARGS}, {"tell", (PyCFunction)Swig_PyDOH_Tell, METH_VARARGS}, {"getc", (PyCFunction)Swig_PyDOH_Getc, METH_VARARGS}, {"putc", (PyCFunction)Swig_PyDOH_Putc, METH_VARARGS}, {"ungetc", (PyCFunction)Swig_PyDOH_Ungetc, METH_VARARGS}, {"getline", (PyCFunction)Swig_PyDOH_Getline, METH_VARARGS}, {"setline", (PyCFunction)Swig_PyDOH_Setline, METH_VARARGS}, {"getfile", (PyCFunction)Swig_PyDOH_Getfile, METH_VARARGS}, {"setfile", (PyCFunction)Swig_PyDOH_Setfile, METH_VARARGS}, {NULL, NULL} }; /* --------------------------------------------------------------------- */ /* general methods */ static PyObject *Swig_PyDOH_getattr(PyDOH *self, char *name) { return Py_FindMethod(Swig_PyDOH_methods, (PyObject *)self, name); } static int Swig_PyDOH_setattr(PyDOH *self, char *name, PyObject *v) { return Setattr(self->doh, name, Swig_PyDOH_as_DOH(v)); } static int Swig_PyDOH_cmp(PyDOH *self, PyObject *other) { return Cmp(self->doh, Swig_PyDOH_as_DOH(other)); } static PyObject *Swig_PyDOH_repr(PyDOH *self) { char *str = Char(self->doh); char buffer[1024] = ""; str = Char(self->doh); if (!str) { /* give up! */ sprintf(buffer, "<DOH *0x%08x>", self->doh); str = buffer; } return PyString_FromString(str); } static long Swig_PyDOH_hash(PyDOH *self) { return (long)Hashval(self->doh); } static char PyDOH_docstring[] = "Interface to DOH objects from Python. DOH objects behave largely\n\ like Python objects, although some functionality may be different."; /* Type objects (one for mappings, one for everything else) */ static PyTypeObject PyDOHSequenceType = { PyObject_HEAD_INIT(&PyType_Type) 0, "DOH", sizeof(PyDOH), 0, (destructor)Swig_PyDOH_delete, (printfunc)0, (getattrfunc)Swig_PyDOH_getattr, (setattrfunc)Swig_PyDOH_setattr, (cmpfunc)Swig_PyDOH_cmp, (reprfunc)Swig_PyDOH_repr, 0, /* tp_as_number */ &Swig_PyDOH_as_sequence, 0, /* tp_as_mapping */ (hashfunc)Swig_PyDOH_hash, (ternaryfunc)0, /* tp_call */ (reprfunc)0, /* tp_str */ (getattrofunc)0, (setattrofunc)0, 0, /* tp_as_buffer */ 0, /* tp_xxx4 */ PyDOH_docstring }; static PyTypeObject PyDOHMappingType = { PyObject_HEAD_INIT(&PyType_Type) 0, "DOH_hash", sizeof(PyDOH), 0, (destructor)Swig_PyDOH_delete, (printfunc)0, (getattrfunc)Swig_PyDOH_getattr, (setattrfunc)Swig_PyDOH_setattr, (cmpfunc)Swig_PyDOH_cmp, (reprfunc)Swig_PyDOH_repr, 0, /* tp_as_number */ 0, /* tp_as_sequence */ &Swig_PyDOH_as_mapping, (hashfunc)Swig_PyDOH_hash, (ternaryfunc)0, /* tp_call */ (reprfunc)0, /* tp_str */ (getattrofunc)0, (setattrofunc)0, 0, /* tp_as_buffer */ 0, /* tp_xxx4 */ PyDOH_docstring }; %} %typemap(python,in) DOH * { $target = Swig_PyDOH_as_DOH($source); } %typemap(python,out) DOH * { $target = Swig_PyDOH_new($source); } %typemap(python,in) char * { if (Swig_PyDOH_check($source)) $target = Char(((PyDOH *)$source)->doh); else $target = PyString_AsString($source); } %title "SWIG", after %section "DOH Objects", before %subsection "Constants" /* The beginning of a sequence */ #define DOH_BEGIN -1 /* The end of a sequence */ #define DOH_END -2 /* The current point in a sequence */ #define DOH_CUR -3 /* Synonymous with DOH_CUR */ #define DOH_CURRENT -3 /* Replace any matches of the given text */ #define DOH_REPLACE_ANY 0x00 /* Replace, but not inside of quotes */ #define DOH_REPLACE_NOQUOTE 0x01 /* Replace only full identifiers */ #define DOH_REPLACE_ID 0x02 /* Replace only the first match */ #define DOH_REPLACE_FIRST 0x04 %subsection "SuperStrings" /* SuperString constructor */ extern DOH *NewSuperString(char *string, DOH *filename, int firstline); /* Is this a SuperString? */ extern int SuperString_check(DOH *); %subsection "Strings" /* String constructor */ extern DOH *NewString(const DOH *c); /* Is this a string? */ extern int String_check(const DOH *); %subsection "Files" /* File constructor */ extern DOH *NewFile(DOH *file, char *mode); /* File constructor from Python file */ extern DOH *NewFileFromFile(FILE *file); /* File constructor from a file descriptor */ extern DOH *NewFileFromFd(int fd); /* Copy from file to file */ %name(CopyTo) extern int DohCopyto(DOH *input, DOH *output); %subsection "Lists" /* List constructor */ extern DOH *NewList(); /* Is this a list? */ extern int List_check(const DOH *); /* Sort a list */ extern void List_sort(DOH *); %subsection "Hash tables" /* Hash table constructor */ extern DOH *NewHash(); /* Is this a hash table? */ extern int Hash_check(const DOH *); /* Get a List of the keys in a hash table */ extern DOH *Hash_keys(DOH *); %section "Files" extern void Swig_add_directory(DOH *dirname); extern DOH *Swig_last_file(); extern DOH *Swig_search_path(); extern FILE *Swig_open(DOH *name); extern DOH *Swig_read_file(FILE *file); extern DOH *Swig_include(DOH *name); #define SWIG_FILE_DELIMETER "/" %section "Command Line Parsing" extern void Swig_init_args(int argc, char **argv); extern void Swig_mark_arg(int n); extern void Swig_check_options(); extern void Swig_arg_error(); %section "Miscelaneous", after extern int DohNewScope(); /* create a new scope */ extern void DohDelScope(int); /* Delete a scope */ extern void DohIntern(DOH *); /* Intern an object */ extern void DohDebug(int d); /* set debugging level */ %section "Scanner Interface" /* typedef struct SwigScanner SwigScanner; */ /* extern SwigScanner *NewSwigScanner(); */ /* extern void DelSwigScanner(SwigScanner *); */ /* extern void SwigScanner_clear(SwigScanner *); */ /* extern void SwigScanner_push(SwigScanner *, DOH *); */ /* extern void SwigScanner_pushtoken(SwigScanner *, int); */ /* extern int SwigScanner_token(SwigScanner *); */ /* extern DOH *SwigScanner_text(SwigScanner *); */ /* extern void SwigScanner_skip_line(SwigScanner *); */ /* extern int SwigScanner_skip_balanced(SwigScanner *, int startchar, int endchar); */ /* extern void SwigScanner_set_location(SwigScanner *, DOH *file, int line); */ /* extern DOH *SwigScanner_get_file(SwigScanner *); */ /* extern int SwigScanner_get_line(SwigScanner *); */ /* extern void SwigScanner_idstart(SwigScanner *, char *idchar); */ /* #define SWIG_MAXTOKENS 512 */ /* #define SWIG_TOKEN_LPAREN 1 */ /* #define SWIG_TOKEN_RPAREN 2 */ /* #define SWIG_TOKEN_SEMI 3 */ /* #define SWIG_TOKEN_COMMA 4 */ /* #define SWIG_TOKEN_STAR 5 */ /* #define SWIG_TOKEN_LBRACE 6 */ /* #define SWIG_TOKEN_RBRACE 7 */ /* #define SWIG_TOKEN_EQUAL 8 */ /* #define SWIG_TOKEN_EQUALTO 9 */ /* #define SWIG_TOKEN_NOTEQUAL 10 */ /* #define SWIG_TOKEN_PLUS 11 */ /* #define SWIG_TOKEN_MINUS 12 */ /* #define SWIG_TOKEN_AND 13 */ /* #define SWIG_TOKEN_LAND 14 */ /* #define SWIG_TOKEN_OR 15 */ /* #define SWIG_TOKEN_LOR 16 */ /* #define SWIG_TOKEN_XOR 17 */ /* #define SWIG_TOKEN_LESSTHAN 18 */ /* #define SWIG_TOKEN_GREATERTHAN 19 */ /* #define SWIG_TOKEN_LTEQUAL 20 */ /* #define SWIG_TOKEN_GTEQUAL 21 */ /* #define SWIG_TOKEN_NOT 22 */ /* #define SWIG_TOKEN_LNOT 23 */ /* #define SWIG_TOKEN_LBRACKET 24 */ /* #define SWIG_TOKEN_RBRACKET 25 */ /* #define SWIG_TOKEN_SLASH 26 */ /* #define SWIG_TOKEN_BACKSLASH 27 */ /* #define SWIG_TOKEN_ENDLINE 28 */ /* #define SWIG_TOKEN_STRING 29 */ /* #define SWIG_TOKEN_POUND 30 */ /* #define SWIG_TOKEN_PERCENT 31 */ /* #define SWIG_TOKEN_COLON 32 */ /* #define SWIG_TOKEN_DCOLON 33 */ /* #define SWIG_TOKEN_LSHIFT 34 */ /* #define SWIG_TOKEN_RSHIFT 35 */ /* #define SWIG_TOKEN_ID 36 */ /* #define SWIG_TOKEN_FLOAT 37 */ /* #define SWIG_TOKEN_DOUBLE 38 */ /* #define SWIG_TOKEN_INT 39 */ /* #define SWIG_TOKEN_UINT 40 */ /* #define SWIG_TOKEN_LONG 41 */ /* #define SWIG_TOKEN_ULONG 42 */ /* #define SWIG_TOKEN_CHAR 43 */ /* #define SWIG_TOKEN_PERIOD 44 */ /* #define SWIG_TOKEN_AT 45 */ /* #define SWIG_TOKEN_DOLLAR 46 */ /* #define SWIG_TOKEN_CODEBLOCK 47 */ /* #define SWIG_TOKEN_ILLEGAL 98 */ /* #define SWIG_TOKEN_LAST 99 */ %section "SWIG types" /* #define SWIG_TYPE_BYTE 1 */ /* #define SWIG_TYPE_UBYTE 2 */ /* #define SWIG_TYPE_SHORT 3 */ /* #define SWIG_TYPE_USHORT 4 */ /* #define SWIG_TYPE_INT 5 */ /* #define SWIG_TYPE_UINT 6 */ /* #define SWIG_TYPE_LONG 7 */ /* #define SWIG_TYPE_ULONG 8 */ /* #define SWIG_TYPE_LONGLONG 9 */ /* #define SWIG_TYPE_ULONGLONG 10 */ /* #define SWIG_TYPE_FLOAT 11 */ /* #define SWIG_TYPE_DOUBLE 12 */ /* #define SWIG_TYPE_QUAD 13 */ /* #define SWIG_TYPE_CHAR 14 */ /* #define SWIG_TYPE_WCHAR 15 */ /* #define SWIG_TYPE_VOID 16 */ /* #define SWIG_TYPE_ENUM 17 */ /* #define SWIG_TYPE_VARARGS 18 */ /* #define SWIG_TYPE_TYPEDEF 19 */ /* #define SWIG_TYPE_POINTER 50 */ /* #define SWIG_TYPE_REFERENCE 51 */ /* #define SWIG_TYPE_FUNCTION 52 */ /* #define SWIG_TYPE_ARRAY 53 */ /* #define SWIG_TYPE_RECORD 54 */ /* #define SWIG_TYPE_NAME 55 */ /* DOH *NewSwigType(int tc, DOH *value); */ <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorAddForceAtPosDecl(); CKERROR CreateAddForceAtPosProto(CKBehaviorPrototype **pproto); int AddForceAtPos(const CKBehaviorContext& behcontext); CKERROR AddForceAtPosCB(const CKBehaviorContext& behcontext); //************************************ // Method: FillBehaviorAddForceAtPosDecl // FullName: FillBehaviorAddForceAtPosDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorAddForceAtPosDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddForceAtPos"); od->SetCategory("Physic/Body"); od->SetDescription("Applies a force (or impulse) defined in the global coordinate frame, acting at a particular point in global coordinates, to the body."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5f182eea,0x747f062d)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateAddForceAtPosProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreateAddForceAtPosProto // FullName: CreateAddForceAtPosProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreateAddForceAtPosProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddForceAtPos"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PBAddForceAtPos PBAddForceAtPos is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Applies a force (or impulse) defined in the global coordinate frame, acting at a particular point in global coordinates, to the actor. <br> <h3>Technical Information</h3> \image html PBAddForceAtPos.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pin">Global Force:</SPAN>Force/impulse to add, defined in the global frame. <BR> <SPAN CLASS="pin">Point:</SPAN>Position in the global/local frame to add the force at. <BR> <SPAN CLASS="pin">Point Reference:</SPAN>Reference object to transform a local point into world coords. <BR> <SPAN CLASS="pin">Force Mode: </SPAN>The way how the force is applied.See #ForceMode <BR> <BR> <h3>Warning</h3> The body must be dynamic. <h3>Note</h3><br> Note that if the force does not act along the center of mass of the actor, this will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForceAtPos().<br> */ proto->DeclareInput("In0"); proto->DeclareOutput("Out0"); proto->DeclareInParameter("Global Force",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Point",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Point Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); //proto->SetBehaviorCallbackFct( AddForceAtPosCB ); proto->SetFunction(AddForceAtPos); *pproto = proto; return CK_OK; } //************************************ // Method: AddForceAtPos // FullName: AddForceAtPos // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int AddForceAtPos(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; //the vector : VxVector vec = GetInputParameterValue<VxVector>(beh,0); VxVector vec0 = GetInputParameterValue<VxVector>(beh,1); VxVector outPos = vec0; //the reference object : CK3dEntity *referenceObject = (CK3dEntity *) beh->GetInputParameterObject(2); if (referenceObject) { referenceObject->Transform(&outPos,&vec0); } int fMode = GetInputParameterValue<int>(beh,3); ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) { beh->ActivateOutput(0); return 0; } // body exists already ? clean and delete it : pRigidBody*result = world->getBody(target); if(result) { result->addForceAtPos(vec,outPos,(ForceMode)fMode); } beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } return 0; } //************************************ // Method: AddForceAtPosCB // FullName: AddForceAtPosCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR AddForceAtPosCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #define BB_SET_POSITION_GUID CKGUID(0xe456e78a, 0x456789aa) #define BB_SET_ORIENTATION_GUID CKGUID(0x625874aa, 0xaa694132) #define BB_ROTATE_GUID CKGUID(0xffffffee, 0xeeffffff) #define BB_TRANSLATE_GUID CKGUID(0x000d000d, 0x000d000d) #define BB_SET_EORIENTATION_GUID CKGUID(0xc4966d8,0x6c0c6d14) CKBEHAVIORFCT BBSetEOri; int BB_SetEOrientationNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBSetEOri(context); int pUpdate=0; behaviour->GetLocalParameterValue(1,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setRotation(quat); VxVector vectorN(0,0,0); int pResetF=0; behaviour->GetLocalParameterValue(2,&pResetF); int pResetT=0; behaviour->GetLocalParameterValue(3,&pResetT); int pResetLV=0; behaviour->GetLocalParameterValue(4,&pResetLV); int pResetAV=0; behaviour->GetLocalParameterValue(5,&pResetAV); if (pResetF) { solid->setLinearMomentum(vectorN); } if (pResetT) { solid->setAngularMomentum(vectorN); } if (pResetLV) { solid->setLinearVelocity(vectorN); } if (pResetAV) { solid->setAngularVelocity(vectorN); } }else { pWorld *world = GetPMan()->getWorldByBody(ent); if (world) { solid = world->getBodyFromSubEntity(ent); if (solid) { solid->updateSubShapes(false,false,true); } } } } return CK_OK; } /************************************************************************/ /* Set Position : */ /************************************************************************/ CKBEHAVIORFCT BBSetPos; int BB_SetPosNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBSetPos(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pWorld *world = GetPMan()->getWorldByBody(ent); if (!world) { return 0; } pRigidBody *solid = world->getBody(ent); if (solid) { VxVector vector(0,0,0); //behaviour->GetInputParameterValue(0,&vector); ent->GetPosition(&vector); solid->setPosition(vector,ent); VxVector vectorN(0,0,0); int pResetF=0; behaviour->GetLocalParameterValue(1,&pResetF); int pResetT=0; behaviour->GetLocalParameterValue(2,&pResetT); int pResetLV=0; behaviour->GetLocalParameterValue(3,&pResetLV); int pResetAV=0; behaviour->GetLocalParameterValue(4,&pResetAV); if (pResetF) { solid->setLinearMomentum(vectorN); } if (pResetT) { solid->setAngularMomentum(vectorN); } if (pResetLV) { solid->setLinearVelocity(vectorN); } if (pResetAV) { solid->setAngularVelocity(vectorN); } }else { pWorld *world = GetPMan()->getWorldByBody(ent); if (world) { solid = world->getBodyFromSubEntity(ent); if (solid) { solid->updateSubShapes(false,true,false); } } } } return CK_OK; } /************************************************************************/ /* Set Orientation : */ /************************************************************************/ CKBEHAVIORFCT BBSetOri; int BB_SetOrientationNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBSetOri(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setRotation(quat); VxVector vectorN(0,0,0); int pResetF=0; behaviour->GetLocalParameterValue(1,&pResetF); int pResetT=0; behaviour->GetLocalParameterValue(2,&pResetT); int pResetLV=0; behaviour->GetLocalParameterValue(3,&pResetLV); int pResetAV=0; behaviour->GetLocalParameterValue(4,&pResetAV); if (pResetF) { solid->setLinearMomentum(vectorN); } if (pResetT) { solid->setAngularMomentum(vectorN); } if (pResetLV) { solid->setLinearVelocity(vectorN); } if (pResetAV) { solid->setAngularVelocity(vectorN); } }else { pWorld *world = GetPMan()->getWorldByBody(ent); if (world) { solid = world->getBodyFromSubEntity(ent); if (solid) { solid->updateSubShapes(false,false,true); } } } } return CK_OK; } /************************************************************************/ /* */ /************************************************************************/ CKBEHAVIORFCT BBRotate; int BB_RotateNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBRotate(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setRotation(quat); VxVector vectorN(0,0,0); int pResetF=0; behaviour->GetLocalParameterValue(1,&pResetF); int pResetT=0; behaviour->GetLocalParameterValue(2,&pResetT); int pResetLV=0; behaviour->GetLocalParameterValue(3,&pResetLV); int pResetAV=0; behaviour->GetLocalParameterValue(4,&pResetAV); if (pResetF) { solid->setLinearMomentum(vectorN); } if (pResetT) { solid->setAngularMomentum(vectorN); } if (pResetLV) { solid->setLinearVelocity(vectorN); } if (pResetAV) { solid->setAngularVelocity(vectorN); } }else { pWorld *world = GetPMan()->getWorldByBody(ent); if (world) { solid = world->getBodyFromSubEntity(ent); if (solid) { solid->updateSubShapes(false,false,true); } } } } return CK_OK; } /************************************************************************/ /* */ /************************************************************************/ CKBEHAVIORFCT BBTranslate; int BB_TranslateNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBTranslate(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setPosition(pos,ent); VxVector vectorN(0,0,0); int pResetF=0; behaviour->GetLocalParameterValue(1,&pResetF); int pResetT=0; behaviour->GetLocalParameterValue(2,&pResetT); int pResetLV=0; behaviour->GetLocalParameterValue(3,&pResetLV); int pResetAV=0; behaviour->GetLocalParameterValue(4,&pResetAV); if (pResetF) { solid->setLinearMomentum(vectorN); } if (pResetT) { solid->setAngularMomentum(vectorN); } if (pResetLV) { solid->setLinearVelocity(vectorN); } if (pResetAV) { solid->setAngularVelocity(vectorN); } }else { pWorld *world = GetPMan()->getWorldByBody(ent); if (world) { solid = world->getBodyFromSubEntity(ent); if (solid) { solid->updateSubShapes(false,true,false); } } } } return CK_OK; } /************************************************************************/ /* */ /************************************************************************/ CKERROR PhysicManager::_Hook3DBBs() { CKBehaviorManager *bm = m_Context->GetBehaviorManager(); CKBehaviorPrototype *bproto = CKGetPrototypeFromGuid(BB_SET_EORIENTATION_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBSetEOri = bproto->GetFunction(); bproto->SetFunction(BB_SetEOrientationNew); } bproto = CKGetPrototypeFromGuid(BB_SET_POSITION_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBSetPos = bproto->GetFunction(); bproto->SetFunction(BB_SetPosNew); } bproto = CKGetPrototypeFromGuid(BB_SET_ORIENTATION_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBSetOri = bproto->GetFunction(); bproto->SetFunction(BB_SetOrientationNew); } bproto = CKGetPrototypeFromGuid(BB_ROTATE_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBRotate = bproto->GetFunction(); bproto->SetFunction(BB_RotateNew); } bproto = CKGetPrototypeFromGuid(BB_TRANSLATE_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBTranslate = bproto->GetFunction(); bproto->SetFunction(BB_TranslateNew); } return CK_OK; } <file_sep> /******************************************************************** created: 2007/11/28 created: 28:11:2007 16:25 filename: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Dialogs\CustomPlayerConfigurationDialog.cpp file path: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Dialogs file base: CustomPlayerConfigurationDialog file ext: cpp author: mc007 purpose: *********************************************************************/ #include <CPStdAfx.h> #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "xUtils.h" int CCustomPlayer::DoSystemCheck(XString&errorText) { /************************************************************************/ /* System Check : */ /************************************************************************/ int foundError = 0; ////////////////////////////////////////////////////////////////////////// // Check DirectX Version : bool DirectXVer_OK = true; if (CPR_CHECK_DIRECTX) { DWORD dxVerMinor=0; char *strVersion = NULL; xUtils::system::GetDirectVersion(strVersion,dxVerMinor); XString dxVer(strVersion); XString dxVer3 = dxVer.Crop(0,3); int dxVerWeNeedMin = GetPAppStyle()->g_MinimumDirectXVersion; int dxVerInt = dxVer3.ToInt(); if(dxVerInt < dxVerWeNeedMin ) { errorText << "\n\n" << "Wrong DirectX Version Detected !"; errorText << "\n\n" << "This application needs at least version : " << GetPAppStyle()->g_MinimumDirectXVersion; errorText << "\n\n" << "You have version : " << strVersion; errorText << "\n\n" << "You can download it from here :" << CPR_MINIMUM_DIRECTX_VERSION_FAIL_URL ; errorText << "\n"; foundError =1; DirectXVer_OK =false; } } ////////////////////////////////////////////////////////////////////////// // Check System Ram if (CPR_CHECK_RAM && DirectXVer_OK ) { int ram = xUtils::system::GetPhysicalMemoryInMB(); if( ram < GetPAppStyle()->g_MiniumumRAM) { errorText << "\n This application needs at least : " << GetPAppStyle()->g_MiniumumRAM << " of System Memory."; errorText << "\n\n\t You have only : " << ram ; foundError = 1; } } ////////////////////////////////////////////////////////////////////////// // Add the last line : support eMail if(foundError) { errorText << "\n\n You can contact us via EMail : mailto:"<<CP_SUPPORT_EMAIL ; } m_LastErrorText = errorText ; return foundError; } <file_sep>#if !defined(CUSTOMPLAYERAPP_H) #define CUSTOMPLAYERAPP_H #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "CustomPlayerStructs.h" #include "BaseMacros.h" /************************************************************************* Summary: This class defines the Windows application object. Description: This class provides member functions for initializing the application and for running the application. See also: CCustomPlayerApp::InitInstance, CCustomPlayerApp::Run, CCustomPlayer. *************************************************************************/ class CCustomPlayerApp : public CWinApp { public: /************************************************************************* Summary: Initialize class members. *************************************************************************/ CCustomPlayerApp(); /************************************************************************* Summary: Release window handles. *************************************************************************/ ~CCustomPlayerApp(); // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCustomPlayerApp) public: virtual BOOL InitInstance(); virtual int ExitInstance(); virtual int Run(); //}}AFX_VIRTUAL public: //{{AFX_MSG(CCustomPlayerApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() protected: HWND m_MainWindow; // the main window (visible in windowed mode). HWND m_RenderWindow; // the render window (used for windowed and fullscreen mode). //HWND m_Splash; // the window used to display the splash screen. XString m_PlayerClass; // the name of the windows class used for the main window. XString m_RenderClass; // the name of the windows class used for the render window. XString m_PlayerTitle; // the string display in the title bar of the main window. int m_Config; // the configuration of the player (see EConfigPlayer). HACCEL m_hAccelTable; //////////////////////////////////////// // initialization function ATOM _RegisterClass(); int _CreateWindows(); void _DisplaySplashWindow(); void _PublishingRights(); //////////////////////////////////////// // configurations management BOOL _ReadConfig(XString& oFilename, const char*& oBufferFile,XDWORD& oSize); BOOL _ReadInternalConfig(const char*& oBufferFile, XDWORD& oSize); BOOL _ReadCommandLine(const char* iArguments, XString& oFilename); BOOL _LoadInternal(XString& oFilename); ////////////////////////////////////////////////////////////////////////// public: /************************************************************************/ /* */ /************************************************************************/ // USHORT PSaveEngineWindowProperties(const char *configFile,const vtPlayer::Structs::xSEngineWindowInfo& input); // [11/28/2007 mc007]- Dialog functions to modify the render settings of the application //void DoConfig(); //INT_PTR CALLBACK ConfigureDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ); ////////////////////////////////////////////////////////////////////////// // // this is just for handy writing : static CCustomPlayerApp* GetInstance(); ////////////////////////////////////////////////////////////////////////// // _NextBlank, _SkipBlank and _ComputeParamValue are tools used // while parsing the command line. const char* _NextBlank(const char* iStr); const char* _SkipBlank(const char* iPtr); BOOL _ComputeParamValue(const char* iPtr, XString& oValue); //////////////////////////////////////// // windocprocs // main windowproc static LRESULT CALLBACK _MainWindowWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); // splash screen windowproc static LRESULT CALLBACK _LoadingDlgWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); void StartMove(LPARAM lParam); void DoMMove(LPARAM lParam, WPARAM wParam); int nMMoveX, nMMoveY; //initial mouse position from window origin. }; //////////////////////////////////////// // inlines // _NextBlank, _SkipBlank and _ComputeParamValue are tools used // while parsing the command line. inline const char* CCustomPlayerApp::_NextBlank(const char* iStr) { const char* ptr = iStr; while(*ptr!='\0' && *ptr!=' ' && *ptr!='\t') { ptr++; } return ptr; } inline const char* CCustomPlayerApp::_SkipBlank(const char* iPtr) { while(*iPtr!='\0' && (*iPtr==' ' || *iPtr=='\t')) { iPtr++; } return iPtr; } inline BOOL CCustomPlayerApp::_ComputeParamValue(const char* iPtr, XString& oValue) { const char* tmp = 0; if (*iPtr=='"') { tmp = strchr(iPtr+1,'"'); if (tmp==0) { return FALSE; } ++iPtr; } else { tmp = _NextBlank(iPtr); } oValue.Create(iPtr,tmp-iPtr); return TRUE; } ////////////////////////////////////////////////////////////////////////// #define GetApp() CCustomPlayerApp::GetInstance() #endif // CUSTOMPLAYERAPP_H <file_sep>#ifndef _XDISTRIBUTED_SESSION_CLASS_H_ #define _XDISTRIBUTED_SESSION_CLASS_H_ #include "xDistributedBaseClass.h" class xDistributedSessionClass : public xDistributedClass { public : xDistributedSessionClass(); int getFirstUserField(); int getUserFieldBitValue(int walkIndex); int getInternalUserFieldIndex(int inputIndex); int getUserFieldCount(); void addProperty(const char*name,int type,int predictionType); void addProperty(int nativeType,int predictionType); xNString NativeTypeToString(int nativeType); int NativeTypeToValueType(int nativeType); protected : }; #endif <file_sep>#ifndef __VT_C_BB_ERROR_HELPER_H__ #define __VT_C_BB_ERROR_HELPER_H__ #ifndef __X_LOGGER_H__ #include <xLogger.h> #endif #ifndef __P_CONSTANTS_H__ #include "pConstants.h" #endif #define CERROR_STRING(F) sBBErrorStrings[F] #define bbSErrorME(A) { xLogger::xLog(XL_START,ELOGERROR,E_BB,CERROR_STRING(A));\ XLOG_BB_INFO;\ beh->ActivateOutput(0);\ return CKBR_PARAMETERERROR ; } #define bbErrorME(A) { xLogger::xLog(XL_START,ELOGERROR,E_BB,A);\ XLOG_BB_INFO;\ beh->ActivateOutput(0);\ return CKBR_PARAMETERERROR ; } #endif<file_sep>/******************************************************************** created: 2009/06/01 created: 1:6:2009 14:15 filename: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick\JSetXYForce.cpp file path: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick file base: JSetXYForce file ext: cpp author: <NAME> purpose: *********************************************************************/ #include <dinput.h> #include "CKAll.h" #include "dInputShared.h" static CKContext *ctx = NULL; static bool gInitiated = false; extern LPDIRECTINPUTEFFECT g_pEffect; extern LPDIRECTINPUTDEVICE8 g_pFFDevice; #define HAS_CONFIG #ifdef HAS_CONFIG #include "gConfig.h" #endif // BB_TOOLS #ifdef BB_TOOLS #include <vtInterfaceEnumeration.h> #include "vtLogTools.h" #include "vtCBBErrorHelper.h" #include <virtools/vtBBHelper.h> #include <virtools/vtBBMacros.h> using namespace vtTools::BehaviorTools; #endif CKObjectDeclaration *FillBehaviorJSetXYForceDecl(); CKERROR CreateJSetXYForceProto(CKBehaviorPrototype **); int JSetXYForce(const CKBehaviorContext& behcontext); CKERROR PlayFFECallBackObject(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorJSetXYForceDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("JSetXYForce"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x6890534f,0x31c12074)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJSetXYForceProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Controllers/Joystick"); return od; } enum bbIO_Inputs { BB_I_DO, BB_I_RELEASE, }; enum bbIO_Outputs { BB_O_DONE, BB_O_RELEASED, BB_O_ERROR, }; CKERROR CreateJSetXYForceProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("JSetXYForce"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("release device"); proto->DeclareOutput("Done"); proto->DeclareOutput("Released"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Force Vector",CKPGUID_2DVECTOR); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( JSetXYForce ); proto->SetBehaviorCallbackFct(PlayFFECallBackObject); *pproto = proto; return CK_OK; } int JSetXYForce(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx2 = behcontext.Context; if (!ctx) { ctx = ctx2; } HWND mWin = (HWND )ctx->GetMainWindow(); HRESULT hr = S_OK; //init and load effect if( beh->IsInputActive(BB_I_DO) ) { beh->ActivateInput(BB_I_DO,FALSE); if (!gInitiated) { if (!InitDirectInput2(mWin) == S_OK) { beh->ActivateOutput(BB_O_ERROR); return CKBR_OK; }else{ hr = g_pFFDevice->Acquire(); hr =g_pEffect->Start( 1, 0 ); // Start the effect gInitiated = true; } } Vx2DVector vectorForce; beh->GetInputParameterValue(0,&vectorForce); SetDeviceForcesXY(vectorForce.x,vectorForce.y); beh->ActivateOutput(BB_O_DONE); } //play if( beh->IsInputActive(BB_I_RELEASE)) { beh->ActivateInput(BB_I_RELEASE,FALSE); { beh->ActivateOutput(BB_I_RELEASE); FreeDirectInput2(); return CKBR_OK; } } /* //stop the effect if( beh->IsInputActive(2) ){ beh->ActivateInput(2,FALSE); //g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ); beh->ActivateOutput(2); return CKBR_OK; }*/ return CKBR_OK; } CKERROR PlayFFECallBackObject(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORDETACH: case CKM_BEHAVIORRESET: { gInitiated = false; if ( g_pFFDevice) g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ); FreeDirectInput2(); } break; } return CKBR_OK; } <file_sep>#include "xDistributedString.h" uxString xDistributedString::print(TNL::BitSet32 flags) { return uxString(); } void xDistributedString::updateFromServer(xNStream *stream) { mLastValue = mCurrentValue; char value[256];stream->readString(value); mCurrentValue = value; setValueState(E_DV_UPDATED); } void xDistributedString::updateGhostValue(xNStream *stream) { stream->writeString(mCurrentValue.getString(),strlen(mCurrentValue.getString())); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedString::unpack(xNStream *bstream,float sendersOneWayTime) { mLastValue = mCurrentValue; char value[256];bstream->readString(value); mCurrentValue = value; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedString::pack(xNStream *bstream) { bstream->writeString(mCurrentValue.getString(),strlen(mCurrentValue.getString())); int flags = getFlags(); flags &= (~E_DP_NEEDS_SEND); setFlags(flags); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedString::updateValue(TNL::StringPtr value,xTimeType currentTime) { mLastTime = mCurrentTime; mCurrentTime = currentTime; mLastDeltaTime = mCurrentTime - mLastTime; mLastValue=TNL::StringPtr(mCurrentValue.getString()); mCurrentValue = value; mThresoldTicker +=mLastDeltaTime; int flags = getFlags(); flags =E_DP_OK; bool result = false; if ( strcmp(mCurrentValue,mLastValue) ) { if (mThresoldTicker2 > 50 ) { flags =E_DP_NEEDS_SEND; result = true ; } } if (mThresoldTicker2 > 50 ) { mThresoldTicker2 = 0 ; mThresoldTicker = 0; } setFlags(flags); return result; }<file_sep>#ifndef __XDIST_TOOLS_H_ #define __XDIST_TOOLS_H_ #include "xNetTypes.h" namespace xDistTools { TNL::StringPtr NativeTypeToString(int nativeType); int NativeTypeToValueType(int nativeType); int ValueTypeToSuperType(int valueType); int SuperTypeToValueType(int superType); xNString ValueTypeToString(int valueType); }; #endif <file_sep> #include "CKAll.h" CKObjectDeclaration *FillBehaviorGetAdaptersDecl(); CKERROR CreateGetAdaptersProto(CKBehaviorPrototype **pproto); int GetAdapters(const CKBehaviorContext& behcontext); /************************************************************************/ /* */ /************************************************************************/ CKObjectDeclaration *FillBehaviorGetAdaptersDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("Get Adapters"); od->SetDescription("Add Objects"); od->SetCategory("Narratives/System"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x2ab2796a,0x24c15af7)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("mw"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGetAdaptersProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateGetAdaptersProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Get Adapters"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Get Next"); proto->DeclareInput("Get Prev"); proto->DeclareOutput("Finish"); proto->DeclareOutput("LoopOut"); proto->DeclareOutParameter("Name",CKPGUID_STRING); proto->DeclareOutParameter("Index",CKPGUID_INT); proto->DeclareOutParameter("Count",CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(GetAdapters); *pproto = proto; return CK_OK; } int indexD = 0; int countD = 0; int GetAdapters(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; CKPluginManager* ThePluginManager=CKGetPluginManager(); CKRenderManager *rm = (CKRenderManager *)ctx->GetRenderManager(); if( beh->IsInputActive(0) ){ beh->ActivateInput(0, FALSE); countD=rm->GetRenderDriverCount(); indexD = 0; beh->ActivateInput(1, TRUE); } if( beh->IsInputActive(1) ){ beh->ActivateInput(1, FALSE); if (indexD > (countD-1)){ indexD = 0; beh->ActivateOutput(0,TRUE); return CKBR_OK; } beh->SetOutputParameterValue(1,&indexD); VxDriverDesc *desc=rm->GetRenderDriverDescription(indexD); indexD++; CKParameterOut *pout2 = beh->GetOutputParameter(0); pout2->SetStringValue(desc->DriverName.Str() ); beh->ActivateOutput(1); } return CKBR_OK; } <file_sep>/******************************************************************** created: 2009/02/16 created: 16:2:2009 7:23 filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\vtParameterAll.h file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common file base: vtParameterAll file ext: h author: <NAME> purpose: *********************************************************************/ #ifndef __VT_PARAMETER_STRUCTS_H__ #define __VT_PARAMETER_STRUCTS_H__ //################################################################ // // Parameter Structures have been divided by type. // #include "vtParameterSubItemIdentifiers_Body.h" #include "vtParameterSubItemIdentifiers_Joints.h" #include "vtParameterSubItemIdentifiers_VehicleAndWheelStructs.h" #include "vtParameterSubItemIdentifiers_World.h" #endif<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Joysitck Camera Orbit // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "GeneralCameraOrbit.h" CKObjectDeclaration *FillBehaviorJoystickCameraOrbitDecl(); CKERROR CreateJoystickCameraOrbitProto(CKBehaviorPrototype **pproto); int JoystickCameraOrbit(const CKBehaviorContext& behcontext); void ProcessJoystickInputs(VxVector* RotationAngles, CKBehavior* beh, CKInputManager *input, float delta, CKBOOL &Returns, CKBOOL &stopping); CKObjectDeclaration *FillBehaviorJoystickCameraOrbitDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Joystick Camera Orbit"); od->SetDescription("Makes a Camera orbit round a 3D Entity using Joystick."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=in>Stop: </SPAN>stops the process.<BR> <SPAN CLASS=out>Ended: </SPAN>is activated when the process has been stopped and the camera has recovered its original position in case "returns" setting is true.<BR> <BR> <SPAN CLASS=pin>Target Position: </SPAN>Position we are turning around.<BR> <SPAN CLASS=pin>Target Referential: </SPAN>Referential where the position is defined.<BR> <SPAN CLASS=pin>Move Speed: </SPAN>Speed in angle per second used when the user moves the camera.<BR> <SPAN CLASS=pin>Return Speed: </SPAN>Speed in angle per second used when the camera returns.<BR> <SPAN CLASS=pin>Min Horizontal: </SPAN>Minimal angle allowed on the horizontal rotation. Must have a negative value.<BR> <SPAN CLASS=pin>Max Horizontal:</SPAN>Maximal angle allowed on the horizontal rotation. Must have a positive value.<BR> <SPAN CLASS=pin>Min Vertical: </SPAN>Minimal angle allowed on the vertical rotation. Must have a negative value.<BR> <SPAN CLASS=pin>Max Vertical: </SPAN>Maximal angle allowed on the vertical rotation. Must have a positive value.<BR> <SPAN CLASS=pin>Zoom Speed: </SPAN>Speed of the zoom in distance per second.<BR> <SPAN CLASS=pin>Zoom Min: </SPAN>Minimum zoom value allowed. Must have a negative value.<BR> <SPAN CLASS=pin>Zoom Max: </SPAN>Maximum zoom value allowed. Must have a positive value.<BR> <BR> The following keys are used by default to move the Camera around its target:<BR> <BR> <FONT COLOR=#FFFFFF>Page Up: </FONT>Zoom in.<BR> <FONT COLOR=#FFFFFF>Page Down: </FONT>Zoom out.<BR> <FONT COLOR=#FFFFFF>Up and Down Arrows: </FONT>Rotate vertically.<BR> <FONT COLOR=#FFFFFF>Left and Right Arrows: </FONT>Rotate horizontally.<BR> The arrow keys are the inverted T arrow keys and not the ones of the numeric keypad.<BR> <BR> <SPAN CLASS=setting>Returns: </SPAN>Does the camera systematically returns to its original position.<BR> <SPAN CLASS=setting>Key Rotate Left: </SPAN>Key used to rotate left.<BR> <SPAN CLASS=setting>Key Rotate Right: </SPAN>Key used to rotate right.<BR> <SPAN CLASS=setting>Key Rotate Up: </SPAN>Key used to rotate up.<BR> <SPAN CLASS=setting>Key Rotate Down: </SPAN>Key used to rotate down.<BR> <SPAN CLASS=setting>Key Zoom in: </SPAN>Key used to zoom in.<BR> <SPAN CLASS=setting>Key Zoom out: </SPAN>Key used to zoom in.<BR> <BR> */ od->SetCategory("Cameras/Movement"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x400f0e6f,0x72822162)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJoystickCameraOrbitProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(INPUT_MANAGER_GUID); return od; } ////////////////////////////////////////////////////////////////////////////// // // Prototype creation // ////////////////////////////////////////////////////////////////////////////// CKERROR CreateJoystickCameraOrbitProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Joystick Camera Orbit"); if(!proto) return CKERR_OUTOFMEMORY; // General Description CKERROR error = FillGeneralCameraOrbitProto(proto); if (error != CK_OK) return (error); // Setting to choose the mouse button proto->DeclareSetting("Joystick Number", CKPGUID_INT,"0"); proto->DeclareSetting("Zoom In Button", CKPGUID_INT,"1"); proto->DeclareSetting("Zoom Out Button", CKPGUID_INT,"2"); proto->DeclareSetting("Inverse Up / Down", CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Threshold", CKPGUID_FLOAT,"0.1"); // Set the execution functions proto->SetFunction(JoystickCameraOrbit); proto->SetBehaviorCallbackFct(GeneralCameraOrbitCallback,CKCB_BEHAVIORSETTINGSEDITED|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORCREATE); // return OK *pproto = proto; return CK_OK; } ////////////////////////////////////////////////////////////////////////////// // // Main Function // ////////////////////////////////////////////////////////////////////////////// int JoystickCameraOrbit(const CKBehaviorContext& behcontext) { return ( GeneralCameraOrbit(behcontext,ProcessJoystickInputs) ); } ////////////////////////////////////////////////////////////////////////////// // // Function that process the inputs // ////////////////////////////////////////////////////////////////////////////// void ProcessJoystickInputs(VxVector* RotationAngles, CKBehavior* beh, CKInputManager *input, float delta, CKBOOL &Returns, CKBOOL &stopping) { // Is the move limited ? CKBOOL Limited = TRUE; beh->GetLocalParameterValue(LOCAL_LIMITS,&Limited); // Gets the Joystick informations int JoystickNumber = 0; VxVector JoystickPosition(0,0,0); beh->GetLocalParameterValue(LOCAL_JOY_NB,&JoystickNumber); input->GetJoystickPosition(JoystickNumber,&JoystickPosition); // Is the move vertically inverted ? CKBOOL inverse = FALSE; float InverseFactor = 1.0f; beh->GetLocalParameterValue(LOCAL_JOY_INVERSE,&inverse); if (inverse) InverseFactor = -1.0f; // Gets the joystick threshold float epsilon = 0.1f; beh->GetLocalParameterValue(LOCAL_JOY_THRESHOLD,&epsilon); //////////////////// // Position Update //////////////////// // If the users is moving the camera if ( ((fabs(JoystickPosition.x) > epsilon) || (fabs(JoystickPosition.y) > epsilon)) && !stopping) { float SpeedAngle = 0.87f; beh->GetInputParameterValue(IN_SPEED_MOVE,&SpeedAngle); SpeedAngle *= delta / 1000; if (Limited) { float MinH = -PI/2; beh->GetInputParameterValue(IN_MIN_H, &MinH); float MaxH = PI/2; beh->GetInputParameterValue(IN_MAX_H, &MaxH); float MinV = -PI/2; beh->GetInputParameterValue(IN_MIN_V, &MinV); float MaxV = PI/2; beh->GetInputParameterValue(IN_MAX_V, &MaxV); RotationAngles->x += JoystickPosition.x * SpeedAngle; RotationAngles->x = XMin(RotationAngles->x, MaxH); RotationAngles->x = XMax(RotationAngles->x, MinH); RotationAngles->y += InverseFactor * JoystickPosition.y * SpeedAngle; RotationAngles->y = XMin(RotationAngles->y, MaxV); RotationAngles->y = XMax(RotationAngles->y, MinV); } else { RotationAngles->x += JoystickPosition.x * SpeedAngle; RotationAngles->y += InverseFactor * JoystickPosition.y * SpeedAngle; } } else if (Returns && ((RotationAngles->x != 0) || (RotationAngles->y != 0))) { float ReturnSpeedAngle = 1.75f; beh->GetInputParameterValue(IN_SPEED_RETURN, &ReturnSpeedAngle); ReturnSpeedAngle *= delta / 1000; if( RotationAngles->x < 0 ) RotationAngles->x += XMin(ReturnSpeedAngle, -RotationAngles->x); if( RotationAngles->x > 0 ) RotationAngles->x -= XMin(ReturnSpeedAngle, RotationAngles->x); if( RotationAngles->y < 0 ) RotationAngles->y += XMin(ReturnSpeedAngle, -RotationAngles->y); if( RotationAngles->y > 0 ) RotationAngles->y -= XMin(ReturnSpeedAngle, RotationAngles->y); } //////////////// // Zoom Update //////////////// int ZinButton; beh->GetLocalParameterValue(LOCAL_JOY_ZIN,&ZinButton); int ZoutButton; beh->GetLocalParameterValue(LOCAL_JOY_ZOUT,&ZoutButton); if ((input->IsJoystickButtonDown(JoystickNumber, ZinButton)) || (input->IsJoystickButtonDown(JoystickNumber, ZoutButton)) && !stopping) { float ZoomSpeed = 40.0f; beh->GetInputParameterValue(IN_SPEED_ZOOM,&ZoomSpeed); ZoomSpeed *= delta / 1000; if (Limited) { float MinZoom = -40.0f; beh->GetInputParameterValue(IN_MIN_ZOOM, &MinZoom); float MaxZoom = 10.0f; beh->GetInputParameterValue(IN_MAX_ZOOM, &MaxZoom); if(input->IsJoystickButtonDown(JoystickNumber, ZinButton)) RotationAngles->z -= XMin(ZoomSpeed, RotationAngles->z + MaxZoom); if(input->IsJoystickButtonDown(JoystickNumber, ZoutButton)) RotationAngles->z += XMin(ZoomSpeed, - MinZoom - RotationAngles->z); } else { if( input->IsJoystickButtonDown(JoystickNumber, ZinButton) ) RotationAngles->z -= ZoomSpeed; if( input->IsJoystickButtonDown(JoystickNumber, ZoutButton) ) RotationAngles->z += ZoomSpeed; } } } <file_sep>FIND_PATH(WEBPLAYERDIR NAMES WebPlayerConfig.exe PATHS [HKEY_LOCAL_MACHINE\\SOFTWARE\\Virtools\\WebPlayer;InstallPath] "C://ProgramFiles/3D Life Player" ) MARK_AS_ADVANCED(CMAKE_MAKE_PROGRAM) SET(WEBPLAYER 1) <file_sep>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* */ /* D L L F T P */ /* */ /* W I N D O W S */ /* */ /* P o u r A r t h i c */ /* */ /* V e r s i o n 3 . 0 */ /* */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define FTP4W_INCLUDES_AND_GENERAL + #include <windows.h> #include <windowsx.h> #include <string.h> #include <tcp4w.h> /* external header file */ #include "port32.h" /* 16/32 bits */ #include "ftp4w.h" /* external header file */ #include "ftp4w_in.h" /* internal header file */ #include "rfc959.h" /* only for error codes */ /* -------------------------------------- */ /* Acces a TnSend depuis Ftp4w */ /* -------------------------------------- */ int _export PASCAL FAR IntTnSend (SOCKET s, LPSTR szString, BOOL bHighPriority, HFILE hf) { int Rc; LPProcData p = FtpDataPtr(); Rc = TnSend (s, szString, bHighPriority, hf); if (p != NULL && p->ftp.bVerbose) { OutputDebugString (szString); OutputDebugString ("\r\n"); } return Rc; } /* ******************************************************************* */ /* */ /* Partie III : Etage Telnet avec utilisation de la structure FtpData */ /* Traitement du mode Verbose */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------ */ /* FtpGetAnswerCode : Attend une réponse du serveur et rend le */ /* code numérique (les 3 premiers octets) */ /* renvoyé par le serveur. */ /* - Le mode verbose consiste à envoyer */ /* l'adresse du buffer à l'utilisateur */ /* - Retourne un nombre entre 100 et 999 si la */ /* fonction s'est bien passée, sinon un code */ /* d'erreur TN_ERROR, TN_TIMEOUT... */ /* ------------------------------------------------------------ */ int _export PASCAL FAR IntFtpGetAnswerCode (LPFtpData pFtpData) { int Rc; memset (pFtpData->szInBuf, 0, sizeof pFtpData->szInBuf); Rc = TnGetAnswerCode (pFtpData->ctrl_socket, pFtpData->szInBuf, sizeof pFtpData->szInBuf, pFtpData->nTimeOut, pFtpData->hLogFile); if (Rc>0 && pFtpData->bVerbose) { LPProcData p = FtpDataPtr(); if (p != NULL) SendMessage (p->VMsg.hVerboseWnd, p->VMsg.nVerboseMsg, TRUE, (LPARAM) pFtpData->szInBuf); OutputDebugString (pFtpData->szInBuf); OutputDebugString ("\r\n"); } return Rc; } /* IntFtpGetAnswerCode */ <file_sep>/******************************************************************** created: 2007/12/12 created: 12:12:2007 11:55 filename: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude\BaseMacros.hpp file path: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude file base: BaseMacros file ext: hpp author: mc007 purpose: *********************************************************************/ #ifndef __BASEMACROS_H #define __BASEMACROS_H ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Platform Headers // ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Platform specific header switchs : // /*#ifdef _WIN32 #include "vtCXPlatform32.h" #endif */ ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Build switchs : // ////////////////////////////////////////////////////////////////////////// // DebugBuild is used to hide private building blocks, types, attributes,... #ifdef NDEBUG static const bool DebugBuild = true; #else static const bool DebugBuild = false; #endif ////////////////////////////////////////////////////////////////////////// // dll directives : #ifdef _WIN32 #define API_EXPORT __declspec(dllexport) #else // Unix needs no export, but for name mangling, keep the function name // clean. If you omit the 'extern "C"', the .so names will be compiler dependent. #define API_EXPORT extern "C" #endif #ifndef API_INLINE #define API_INLINE __inline #endif #ifndef API_sCALL #define API_sCALL __stdcall #endif #ifndef API_cDECL #define API_cDECL __cdecl #endif #define DLLEXPORT __declspec( dllexport ) #define DLLIMPORT __declspec( dllimport ) #if defined(MODULE_STATIC) # define MODULE_IMPORT_API # define MODULE_EXPORT_API #else # define MODULE_IMPORT_API DLLIMPORT # define MODULE_EXPORT_API DLLEXPORT #endif // MODULE_BASE_API #if defined( MODULE_BASE_EXPORTS ) # define MODULE_API MODULE_EXPORT_API #else # define MODULE_API MODULE_IMPORT_API #endif ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // API Specific Constants : // #define API_PREFIX "mw" #define API_ENTRY(F) API_PREFIX##F #define API_CUSTOM_BB_CATEGORY(F) API_PREFIX##F // #define MY_BB_CAT API_CUSTOM_BB_CATEGORY(/MySubCategory) leads to : "mw/MySubCategory" #ifndef AUTHOR #define AUTHOR "<NAME>" #endif #ifndef AUTHOR_GUID #define AUTHOR_GUID CKGUID(0x79ba75dd,0x41d77c63) #endif ////////////////////////////////////////////////////////////////////////// // // Error Identifiers : // ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // File System Specific : // #if defined (_LINUX) #define FS_PATH_SEPERATOR '/' #define FS_PATH_DRIVE_SEPARATOR ':' #define FS_EOL "\n" //(0x0D) #endif #ifdef _WIN32 #define FS_PATH_SEPERATOR '\\' #define FS_PATH_DRIVE_SEPARATOR #define FS_EOL "\r\n" //(0x0A 0x0D) #endif #if defined (macintosh) #define FS_PATH_SEPERATOR '/' #define FS_PATH_DRIVE_SEPARATOR #define FS_EOL "\r" //(0x0A) #endif #define FS_PATH_EXT_SEPARATOR '.' ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // // #endif<file_sep>/***************************************************************************** * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR * A PARTICULAR PURPOSE. * * Copyright (C) 1993 - 1996 Microsoft Corporation. All Rights Reserved. * ****************************************************************************** * * Seq.H * * Public include file for sequencer interface. * *****************************************************************************/ #ifndef MidiSound_h #define MidiSound_h #include "smf.h" #define VERSION_MINOR 0x00 #define VERSION_MAJOR 0x04 #define SEQ_VERSION ((DWORD)(WORD)((BYTE)VERSION_MINOR | (((WORD)(BYTE)VERSION_MAJOR) << 8))) #define SEQ_F_EOF 0x00000001L #define SEQ_F_COLONIZED 0x00000002L #define SEQ_F_WAITING 0x00000004L #define SEQ_S_NOFILE 0 #define SEQ_S_OPENED 1 #define SEQ_S_PREROLLING 2 #define SEQ_S_PREROLLED 3 #define SEQ_S_PLAYING 4 #define SEQ_S_PAUSED 5 #define SEQ_S_STOPPING 6 #define SEQ_S_RESET 7 #define MMSG_DONE (WM_USER+20) #define MMRESULT unsigned int typedef struct tag_preroll { TICKS tkBase; TICKS tkEnd; } PREROLL, *LPPREROLL; typedef struct tag_seq * PSEQ; typedef struct tag_seq { public: DWORD cBuffer; /* Number of streaming buffers to alloc */ DWORD cbBuffer; /* Size of each streaming buffer */ LPSTR pstrFile; /* Pointer to filename to open */ UINT uDeviceID; /* Requested MIDI device ID for MMSYSTEM */ UINT uMCIDeviceID; /* Our MCI device ID given to us */ UINT uMCITimeFormat; /* Current time format */ UINT uMCITimeDiv; /* MCI_SEQ_DIV_xxx for current file */ HWND hWnd; /* Where to post MMSG_DONE when done playing */ UINT uState; /* Sequencer state (SEQ_S_xxx) */ TICKS tkLength; /* Length of longest track */ DWORD cTrk; /* Number of tracks */ MMRESULT mmrcLastErr; /* Error return from last sequencer operation */ PSEQ pNext; /* Link to next PSEQ */ HSMF hSmf; /* Handle to open file */ HMIDIOUT hmidi; /* Handle to open MIDI device */ DWORD dwTimeDivision; /* File time division */ LPBYTE lpbAlloc; /* Streaming buffers -- initial allocation */ LPMIDIHDR lpmhFree; /* Streaming buffers -- free list */ LPMIDIHDR lpmhPreroll; /* Streaming buffers -- preroll buffer */ DWORD cbPreroll; /* Streaming buffers -- size of lpmhPreroll */ UINT uBuffersInMMSYSTEM; /* Streaming buffers -- in use */ TICKS tkBase; /* Where playback started from in stream */ TICKS tkEnd; /* Where playback should end */ DWORD fdwSeq; /* Various sequencer flags */ } SEQ, *PSEQ; class MidiSound { private: PSEQ pSeq; private: MMRESULT AllocBuffers(); VOID FreeBuffers(); public: MidiSound(void *hwnd); ~MidiSound(); // Fichier midi associe MMRESULT SetSoundFileName(const char * fname); const char* GetSoundFileName(); BOOL IsPlaying(); BOOL IsPaused(); MMRESULT OpenFile(); MMRESULT CloseFile( ); MMRESULT Preroll(); MMRESULT Start(); MMRESULT Pause(); MMRESULT Restart(); MMRESULT Stop(); MMRESULT Time(PTICKS pTicks); TICKS MillisecsToTicks(DWORD msOffset); DWORD TicksToMillisecs(TICKS tkOffset); }; #endif <file_sep>// DistributedNetworkClassDialogEditor.h : main header file for the EDITOR DLL // #pragma once #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols class DistributedNetworkClassDialogEditorDlg; class DistributedNetworkClassDialogToolbarDlg; extern DistributedNetworkClassDialogEditorDlg* g_Editor; extern DistributedNetworkClassDialogToolbarDlg* g_Toolbar; //plugin interface for communication with Virtools Dev extern PluginInterface* s_Plugininterface; ///////////////////////////////////////////////////////////////////////////// // CEditorApp // See Editor.cpp for the implementation of this class // class DistributedNetworkClassDialogEditorApp : public CWinApp { protected: void InitImageList(); void DeleteImageList(); CImageList m_ImageList; public: DistributedNetworkClassDialogEditorApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(DistributedNetworkClassDialogCEditorApp) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL //{{AFX_MSG(DistributedNetworkClassDialogCEditorApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. <file_sep> #ifndef __QLIB_TIMER_H #define __QLIB_TIMER_H #include <BaseMacros.h> #include <time.h> #ifdef linux #include <sys/time.h> #endif // Vertical trace resolution? //#define USE_VTRACE #if defined(__sgi) // UST nanosecond resolution? #define USE_UST #endif #if defined(linux) // time() usage? Bad resolution and misplaced offsets within the second #define USE_GETTIMEOFDAY #endif #if defined(WIN32) #define USE_OS_TICK // Use milliseconds NT timer #endif #ifndef ulong typedef unsigned long ulong; #endif class MODULE_API QTimer { private: #ifdef USE_TIME time_t base_secs; int ticks; // Seconds (not very high frequency!) #endif #ifdef USE_GETTIMEOFDAY int ticks; struct timeval tv; // Should do microsecs int base_usecs; // Base time in usecs struct timeval tvBase; // Base time #endif #ifdef USE_OS_TICK int ticks; int baseTicks; #endif #if defined(__sgi) ulong base_secs,base_micros; // Intuition (Amiga) style #ifdef USE_UST uint64 ticks; // UST ticks go FAST! uint64 baseUST; // UST timing #endif #ifdef USE_VTRACE int baseVCount; // Vertical retraces base int ticks; // Current #ticks recorded #endif #endif bool isRunning; // Recording time? //QClassType ID() const { return QOBJ_TIMER; } protected: void ResetBase(); // Base GLX vtrace counter void UpdateTicks(); public: QTimer(); ~QTimer(); bool IsRunning(){ return isRunning; } void Reset(); void Start(); void Stop(); // Get time void GetTime(ulong *secs,ulong *micros); ulong GetSeconds(); int GetMilliSeconds(); int GetMicroSeconds(); #ifdef WIN32 int GetTicks(); #else // SGI #ifdef USE_UST uint64 GetTicks(); #else int GetTicks(); #endif #endif // Adjust time void AdjustMilliSeconds(int delta); // Higher level void WaitForTime(int secs,int msecs=0); }; #endif <file_sep>#ifndef __P_COMMON_H__ #define __P_COMMON_H__ #include "vtPhysXBase.h" #include "vtPhysXAll.h" #include "vtLogTools.h" #include "vtCBBErrorHelper.h" #include <virtools/vtBBHelper.h> #include <virtools/vtBBMacros.h> #define HAS_CONFIG #ifdef HAS_CONFIG #include "gConfig.h" #endif using namespace vtTools::BehaviorTools; #endif<file_sep>#ifndef _XDISTRIBUTED_POINT4F_H_ #define _XDISTRIBUTED_POINT4F_H_ #include "xDistributedProperty.h" #include "xQuat.h" class xDistributedQuatF : public xDistributedProperty { public: typedef xDistributedProperty Parent; xDistributedQuatF ( xDistributedPropertyInfo *propInfo, xTimeType maxWriteInterval, xTimeType maxHistoryTime ) : xDistributedProperty(propInfo) { mLastValue = QuatF(0.0f,0.0f,0.0f,0.0f); mCurrentValue= QuatF(0.0f,0.0f,0.0f,0.0f); mDifference = QuatF(0.0f,0.0f,0.0f,0.0f); mLastTime = 0; mCurrentTime = 0; mLastDeltaTime = 0 ; mFlags = 0; mThresoldTicker = 0; } ~xDistributedQuatF(){} QuatF mLastValue; QuatF mCurrentValue; QuatF mDifference; QuatF mLastServerValue; QuatF mLastServerDifference; bool updateValue(QuatF value,xTimeType currentTime); QuatF getDiff(QuatF value); void pack(xNStream *bstream); void unpack(xNStream *bstream,float sendersOneWayTime); void updateGhostValue(xNStream *stream); void updateFromServer(xNStream *stream); virtual uxString print(TNL::BitSet32 flags); }; #endif <file_sep>#include <StdAfx.h> #include "NxShape.h" #include "Nxp.h" #include "pMisc.h" #include "PhysicManager.h" #include "vtPhysXAll.h" namespace vtAgeia { CK3dEntity *getEntityFromShape(NxShape* shape) { if ( !shape) return NULL; pSubMeshInfo *sInfo = (pSubMeshInfo*)shape->userData; if (sInfo) { CK3dEntity *ent = (CK3dEntity*)CKGetObject(ctx(),sInfo->entID); return ent; } return NULL; } bool isChildOf(CK3dEntity*parent,CK3dEntity*test) { CK3dEntity* subEntity = NULL; while (subEntity= parent->HierarchyParser(subEntity) ) { if (subEntity == test) { return true; } } return false; } CK3dEntity* findSimilarInSourceObject(CK3dEntity *parentOriginal,CK3dEntity* partentCopied,CK3dEntity *copiedObject,CK3dEntity*prev) { if (!parentOriginal || !copiedObject ) return NULL; if (parentOriginal->GetChildrenCount() < 1) return NULL; if ( prev && prev!=copiedObject && isChildOf(parentOriginal,prev) && !isChildOf(partentCopied,prev) ) return prev; CK3dEntity *orginalObject= (CK3dEntity*)ctx()->GetObjectByNameAndClass(copiedObject->GetName(),CKCID_3DOBJECT,prev); if (orginalObject) { //---------------------------------------------------------------- // // tests // if ( orginalObject==copiedObject ) findSimilarInSourceObject(parentOriginal,partentCopied,copiedObject,orginalObject); if ( !isChildOf(parentOriginal,orginalObject)) findSimilarInSourceObject(parentOriginal,partentCopied,copiedObject,orginalObject); if( isChildOf(partentCopied,orginalObject) ) findSimilarInSourceObject(parentOriginal,partentCopied,copiedObject,orginalObject); return orginalObject; } return NULL; } bool calculateOffsets(CK3dEntity*source,CK3dEntity*target,VxQuaternion &quat,VxVector& pos) { if (!source && !target) return false; CK3dEntity* child = NULL; bool isChild = false; while (child = source->HierarchyParser(child) ) { if (child == target ) { isChild = true; } } VxQuaternion refQuad2; target->GetQuaternion(&refQuad2,source); VxVector relPos; target->GetPosition(&relPos,source); pos = relPos; quat = refQuad2; return true; } int getNbOfPhysicObjects(CK3dEntity *parentObject,int flags/* =0 */) { #ifdef _DEBUG assert(parentObject); #endif // _DEBUG int result = 0; //---------------------------------------------------------------- // // parse hierarchy // CK3dEntity* subEntity = NULL; while (subEntity= parentObject->HierarchyParser(subEntity) ) { pRigidBody *body = GetPMan()->getBody(subEntity); if (body) result++; } return result; } int getHullTypeFromShape(NxShape *shape) { int result = - 1; if (!shape) { return result; } int nxType = shape->getType(); switch (nxType) { case NX_SHAPE_PLANE: return HT_Plane; case NX_SHAPE_BOX: return HT_Box; case NX_SHAPE_SPHERE: return HT_Sphere; case NX_SHAPE_CONVEX: return HT_ConvexMesh; case NX_SHAPE_CAPSULE: return HT_Capsule; case NX_SHAPE_MESH: return HT_Mesh; } return -1; } int getEnumIndex(CKParameterManager* pm,CKGUID parGuide,XString enumValue) { int pType = pm->ParameterGuidToType(parGuide); CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); if ( enumStruct ) { for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) { if( !strcmp(enumStruct->GetEnumDescription(i),enumValue.Str()) ) return i; } } return 0; } XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide) { XString result; int pType = pm->ParameterGuidToType(parGuide); CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); if ( enumStruct ) { for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) { result << enumStruct->GetEnumDescription(i); result << "="; result << enumStruct->GetEnumValue(i); if (i < enumStruct->GetNumEnums() -1 ) { result << ","; } } } return result; } XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide,int parameterSubIndex) { XString result="None"; int pType = pm->ParameterGuidToType(parGuide); CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); if ( enumStruct ) { for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) { if(i == parameterSubIndex) { result = enumStruct->GetEnumDescription(i); } } } return result; } //************************************ // Method: BoxGetZero // FullName: vtAgeia::BoxGetZero // Access: public // Returns: VxVector // Qualifier: // Parameter: vt3DObject ent //************************************ VxVector BoxGetZero(CK3dEntity* ent) { VxVector box_s= VxVector(1,1,1); if (ent) { VxMatrix mat = ent->GetWorldMatrix(); VxVector g; //Vx3DMatrixToEulerAngles(mat,&g.x,&g.y,&g.z); //SetEulerDirection(ent,VxVector(0,0,0)); CKMesh *mesh = ent->GetCurrentMesh(); if (mesh!=NULL) { box_s = mesh->GetLocalBox().GetSize(); } //SetEulerDirection(ent,g); } return box_s; } //************************************ // Method: SetEulerDirection // FullName: vtAgeia::SetEulerDirection // Access: public // Returns: void // Qualifier: // Parameter: CK3dEntity* ent // Parameter: VxVector direction //************************************ void SetEulerDirection(CK3dEntity* ent,VxVector direction) { VxVector dir,up,right; VxMatrix mat; Vx3DMatrixFromEulerAngles(mat,direction.x,direction.y,direction.z); dir=(VxVector)mat[2]; up=(VxVector)mat[1]; right=(VxVector)mat[0]; ent->SetOrientation(&dir,&up,&right,NULL,FALSE); } } <file_sep> /* ***************************************************************** * Copyright © ITI Scotland 2006 *---------------------------------------------------------------- * Module : $File: //depot/ITITM005/Code/GBLCommon/include/GBLPlatformWIN32.h $ * * Programmer : $Author: gunther.baumgart $ * Date : $DateTime: 2006/05/17 15:37:18 $ * *---------------------------------------------------------------- * * Module Summary : Platform specific Types and Functions. * *---------------------------------------------------------------- * $Revision: #5 $ * $Change: 21762 $ ***************************************************************** */ #include <WTypes.h> ////////////////////////////////////////////////////////////////////////// //Macros : /* From winnt.h : */ #ifndef MAKEWORD #define MAKEWORD(a, b) ((WORD)(((BYTE)((DWORD_PTR)(a) & 0xff)) | ((WORD)((BYTE)((DWORD_PTR)(b) & 0xff))) << 8)) #endif #ifndef LOWORD #define LOWORD(l) ((WORD)((DWORD_PTR)(l) & 0xffff)) #endif #ifndef HIWORD #define HIWORD(l) ((WORD)((DWORD_PTR)(l) >> 16)) #endif ////////////////////////////////////////////////////////////////////////// <file_sep>// DataRelay.cpp : Defines the initialization routines for the plugin DLL. // #include "CKAll.h" #include "DataManager.h" #include "bginstancer.h" #include "gblasyncblock.h" #ifdef CK_LIB #define RegisterBehaviorDeclarations Register_TOOLS_BehaviorDeclarations #define InitInstance _TOOLS_InitInstance #define ExitInstance _TOOLS_ExitInstance #define CKGetPluginInfoCount CKGet_TOOLS_PluginInfoCount #define CKGetPluginInfo CKGet_TOOLS_PluginInfo #define g_PluginInfo g_TOOLS_PluginInfo #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #endif CKERROR InitInstance(CKContext* context); CKERROR ExitInstance(CKContext* context); #define PLUGIN_COUNT 2 CKPluginInfo g_PluginInfo[PLUGIN_COUNT]; PLUGIN_EXPORT int CKGetPluginInfoCount(){return 2;} PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) { int Plugin = 0; g_PluginInfo[Plugin].m_Author = "Virtools"; g_PluginInfo[Plugin].m_Description = "Generic tools"; g_PluginInfo[Plugin].m_Extension = ""; g_PluginInfo[Plugin].m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo[Plugin].m_Version = 0x00010000; g_PluginInfo[Plugin].m_InitInstanceFct = NULL; g_PluginInfo[Plugin].m_GUID = CKGUID(0xbd1e1d69, 0x0ee9fdca); g_PluginInfo[Plugin].m_Summary = "Collection of generic tools"; Plugin++; g_PluginInfo[Plugin].m_Author = "Virtools"; g_PluginInfo[Plugin].m_Description = "Tools manager"; g_PluginInfo[Plugin].m_Extension = ""; g_PluginInfo[Plugin].m_Type = CKPLUGIN_MANAGER_DLL; g_PluginInfo[Plugin].m_Version = 0x00010000; g_PluginInfo[Plugin].m_InitInstanceFct = InitInstance; g_PluginInfo[Plugin].m_ExitInstanceFct = ExitInstance; g_PluginInfo[Plugin].m_GUID = DataManagerGUID; g_PluginInfo[Plugin].m_Summary = "Tool manager"; return &g_PluginInfo[Index]; } // If no manager is used in the plugin // these functions are optional and can be exported. // Virtools will call 'InitInstance' when loading the behavior library // and 'ExitInstance' when unloading it. // It is a good place to perform Attributes Types declaration, // registering new enums or new parameter types. CKERROR InitInstance(CKContext* context) { new DataManager(context); return CK_OK; } CKERROR ExitInstance(CKContext* context) { // This function will only be called if the dll is unloaded explicitely // by a user in Virtools Dev interface // Otherwise the manager destructor will be called by Virtools runtime directly delete context->GetManagerByGuid(DataManagerGUID); return CK_OK; } void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) { ::CKStoreDeclaration(reg, BGWrapper::FillBehaviour()); ::CKStoreDeclaration(reg, ExeInThread::FillBehaviour()); RegisterBehavior(reg,FillBehaviorGetAdaptersDecl); RegisterBehavior(reg,FillBehaviorGetAdaptersModieDecl); RegisterBehavior(reg,FillBehaviorGoFullScreenDecl); RegisterBehavior(reg, FillBehaviorHasFFEffectsDecl); RegisterBehavior(reg, FillBehaviorJSetXYForceDecl); RegisterBehavior(reg,FillBehaviorGetCurrentPathDecl); RegisterBehavior(reg,FillBehaviorDirToArrayDecl); } <file_sep>/******************************************************************** created: 2008/04/10 created: 10:4:2008 12:49 filename: x:\junctions\ProjectRoot\current\vt_plugins\vt_tnl\Manager\xDistributedBaseClass.h file path: x:\junctions\ProjectRoot\current\vt_plugins\vt_tnl\Manager file base: xDistributedBaseClass file ext: h author: mc007 purpose: *********************************************************************/ #ifndef _XDISTRIBUTED_BASE_CLASS_H_ #define _XDISTRIBUTED_BASE_CLASS_H_ #include "xNetTypes.h" //typedef XHashTable<xDistributedPropertyInfo*,XString,XHashFunXStringI>xDistributedPropertyInfoArrayType; //typedef XHashTable<xDistributedPropertyInfo*,XString,XHashFunXStringI>::Iterator xDistributedPropertyInfoArrayIterator; class xDistributed3DObjectClass; /* #ifdef GetClassNameA #undef GetClassNameA #endif */ class xDistributedClass { public: xDistributedClass(); virtual ~xDistributedClass(); int getEnitityType() { return m_EnitityType; } void setEnitityType(int val) { m_EnitityType = val; } xNString getClassName(); void setClassName(xNString name); xDistributedPropertiesListType* getDistributedProperties() { return m_DistributedProperties; } int getNativeFlags() { return m_NativeFlags; } void setNativeFlags( int val ){ m_NativeFlags = val; } virtual void addProperty(const char*name,int type,int predictionType){} virtual void addProperty(int nativeType,int predictionType){} xDistributed3DObjectClass *cast(xDistributedClass *_in); virtual int getFirstUserField(){ return 0; } virtual int getUserFieldBitValue(int walkIndex){ return 0; } virtual int getInternalUserFieldIndex(int inputIndex){ return 0;} virtual int getUserFieldCount(){return 0;} virtual xNString NativeTypeToString(int nativeType){ return xNString("");} virtual int NativeTypeToValueType(int nativeType){ return -1;} public : xDistributedPropertyInfo *exists(const char*name); virtual xDistributedPropertyInfo *exists(int nativeType); protected: int m_NativeFlags; int m_EnitityType; xNString m_ClassName; int m_NativeProperties; xDistributedPropertiesListType *m_DistributedProperties; private: }; #endif <file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #include "tnl.h" #include "tnlClientPuzzle.h" #include "tnlRandom.h" #include <mycrypt.h> namespace TNL { void ClientPuzzleManager::NonceTable::reset() { mChunker.freeBlocks(); mHashTableSize = Random::readI(MinHashTableSize, MaxHashTableSize) * 2 + 1; mHashTable = (Entry **) mChunker.alloc(sizeof(Entry *) * mHashTableSize); for(U32 i = 0; i < mHashTableSize; i++) mHashTable[i] = NULL; } bool ClientPuzzleManager::NonceTable::checkAdd(Nonce &theNonce) { U32 nonce1 = readU32FromBuffer(theNonce.data); U32 nonce2 = readU32FromBuffer(theNonce.data + 4); U64 fullNonce = (U64(nonce1) << 32) | nonce2; U32 hashIndex = U32(fullNonce % mHashTableSize); for(Entry *walk = mHashTable[hashIndex]; walk; walk = walk->mHashNext) if(walk->mNonce == theNonce) return false; Entry *newEntry = (Entry *) mChunker.alloc(sizeof(Entry)); newEntry->mNonce = theNonce; newEntry->mHashNext = mHashTable[hashIndex]; mHashTable[hashIndex] = newEntry; return true; } ClientPuzzleManager::ClientPuzzleManager() { mCurrentDifficulty = InitialPuzzleDifficulty; mLastUpdateTime = 0; mLastTickTime = 0; Random::read(mCurrentNonce.data, Nonce::NonceSize); Random::read(mLastNonce.data, Nonce::NonceSize); mCurrentNonceTable = new NonceTable; mLastNonceTable = new NonceTable; } ClientPuzzleManager::~ClientPuzzleManager() { delete mCurrentNonceTable; delete mLastNonceTable; } void ClientPuzzleManager::tick(U32 currentTime) { if(!mLastTickTime) mLastTickTime = currentTime; // use delta of last tick time and current time to manage puzzle // difficulty. // not yet implemented. // see if it's time to refresh the current puzzle: U32 timeDelta = currentTime - mLastUpdateTime; if(timeDelta > PuzzleRefreshTime) { mLastUpdateTime = currentTime; mLastNonce = mCurrentNonce; NonceTable *tempTable = mLastNonceTable; mLastNonceTable = mCurrentNonceTable; mCurrentNonceTable = tempTable; mLastNonce = mCurrentNonce; mCurrentNonceTable->reset(); Random::read(mCurrentNonce.data, Nonce::NonceSize); } } bool ClientPuzzleManager::checkOneSolution(U32 solution, Nonce &clientNonce, Nonce &serverNonce, U32 puzzleDifficulty, U32 clientIdentity) { U8 buffer[8]; writeU32ToBuffer(solution, buffer); writeU32ToBuffer(clientIdentity, buffer + 4); hash_state hashState; U8 hash[32]; sha256_init(&hashState); sha256_process(&hashState, buffer, sizeof(buffer)); sha256_process(&hashState, clientNonce.data, Nonce::NonceSize); sha256_process(&hashState, serverNonce.data, Nonce::NonceSize); sha256_done(&hashState, hash); U32 index = 0; while(puzzleDifficulty > 8) { if(hash[index]) return false; index++; puzzleDifficulty -= 8; } U8 mask = 0xFF << (8 - puzzleDifficulty); return (mask & hash[index]) == 0; } ClientPuzzleManager::ErrorCode ClientPuzzleManager::checkSolution(U32 solution, Nonce &clientNonce, Nonce &serverNonce, U32 puzzleDifficulty, U32 clientIdentity) { return Success; if(puzzleDifficulty != mCurrentDifficulty) return InvalidPuzzleDifficulty; NonceTable *theTable = NULL; if(serverNonce == mCurrentNonce) theTable = mCurrentNonceTable; else if(serverNonce == mLastNonce) theTable = mLastNonceTable; if(!theTable) return InvalidServerNonce; if(!checkOneSolution(solution, clientNonce, serverNonce, puzzleDifficulty, clientIdentity)) return InvalidSolution; if(!theTable->checkAdd(clientNonce)) return InvalidClientNonce; return Success; } bool ClientPuzzleManager::solvePuzzle(U32 *solution, Nonce &clientNonce, Nonce &serverNonce, U32 puzzleDifficulty, U32 clientIdentity) { U32 startTime = Platform::getRealMilliseconds(); U32 startValue = *solution; // Until we're done... for(;;) { U32 nextValue = startValue + SolutionFragmentIterations; for(;startValue < nextValue; startValue++) { if(checkOneSolution(startValue, clientNonce, serverNonce, puzzleDifficulty, clientIdentity)) { *solution = startValue; return true; } } // Then we check to see if we're out of time... if(Platform::getRealMilliseconds() - startTime > MaxSolutionComputeFragment) { *solution = startValue; return false; } } } }; <file_sep>#include <StdAfx.h> #include "pCommon.h" #include "IParameter.h" #include "pVehicleAll.h" #include <xDebugTools.h> CKObjectDeclaration *FillBehaviorPVSetGearsDecl(); CKERROR CreatePVSetGearsProto(CKBehaviorPrototype **pproto); int PVSetGears(const CKBehaviorContext& behcontext); CKERROR PVSetGearsCB(const CKBehaviorContext& behcontext); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; enum bInputs { I_XML, I_nbFGears, I_Flags, I_Ratios, I_ShiftUpRPM, I_ShiftDownRPM, I_Clutch, I_ClutchRelease, }; #define BB_SSTART 4 BBParameter pInMap6[] = { BB_PIN(I_XML,VTE_XML_VGEAR_SETTINGS,"XML Link","None"), BB_PIN(I_nbFGears,CKPGUID_INT,"Number of Forward Gears","None"), BB_PIN(I_Flags,VTS_VGEARBOX_FLAGS,"Flags","None"), BB_PIN(I_Ratios,VTS_VGEAR_RATIOS,"Forward Ratios/Inertias","None"), BB_SPIN(I_ShiftUpRPM,CKPGUID_FLOAT,"Shift Up RPM",""), BB_SPIN(I_ShiftDownRPM,CKPGUID_FLOAT,"Shift Down RPM",""), BB_SPIN(I_Clutch,CKPGUID_TIME,"Clutch Time",""), BB_SPIN(I_ClutchRelease,CKPGUID_TIME,"Clutch Release Time",""), /*BB_SPIN(I_RatioC,VTS_VGEAR_SETTINGS,"Gear Graphic Setup","None"),*/ }; #define gPIMAP pInMap6 CKERROR PVSetGearsCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKContext *ctx = beh->GetCKContext(); BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDELETE: case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; } //************************************ // Method: FillBehaviorPVSetGearsDecl // FullName: FillBehaviorPVSetGearsDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration*FillBehaviorPVSetGearsDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVGears"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Attachs and/or modifies a gearbox of a vehicle controller"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5d701f33,0x17d519eb)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVSetGearsProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePVSetGearsProto // FullName: CreatePVSetGearsProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePVSetGearsProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVGears"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); //proto->DeclareOutParameter("Result Ratio Curve",CKPGUID_2DCURVE,"FALSE"); // proto->DeclareOutParameter("Result Torque Curve",CKPGUID_2DCURVE,"FALSE"); // /* PVSetGears PVSetGears is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies various physical parameters.<br> <h3>Technical Information</h3> \image html PVSetGears.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pin">Collisions Group: </SPAN>Which collision group this body is part of.See pRigidBody::setCollisionsGroup(). <BR> <SPAN CLASS="pin">Kinematic Object: </SPAN>The kinematic state. See pRigidBody::setKinematic(). <BR> <SPAN CLASS="pin">Gravity: </SPAN>The gravity state.See pRigidBody::enableGravity(). <BR> <SPAN CLASS="pin">Collision: </SPAN>Determines whether the body reacts to collisions.See pRigidBody::enableCollision(). <BR> <SPAN CLASS="pin">Mass Offset: </SPAN>The new mass center in the bodies local space. <BR> <SPAN CLASS="pin">Pivot Offset: </SPAN>The initial shape position in the bodies local space. <BR> <SPAN CLASS="pin">Notify Collision: </SPAN>Enables collision notification.This is necessary to use collisions related building blocks. <BR> <SPAN CLASS="pin">Transformation Locks: </SPAN>Specifies in which dimension a a transformation lock should occour. <BR> <SPAN CLASS="pin">Linear Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Angular Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Filter Groups: </SPAN>Sets the filter mask of the initial or sub shape. <BR> <SPAN CLASS="setting">Collisions Group: </SPAN>Enables input for collisions group. <BR> <SPAN CLASS="setting">Kinematic Object: </SPAN>Enables input for kinematic object. <BR> <SPAN CLASS="setting">Gravity: </SPAN>Enables input for gravity. <BR> <SPAN CLASS="setting">Collision: </SPAN>Enables input for collision. <BR> <SPAN CLASS="setting">Mas Offset: </SPAN>Enables input for mass offset. <BR> <SPAN CLASS="setting">Pivot Offset: </SPAN>Enables input for pivot offset. <BR> <SPAN CLASS="setting">Notify Collision: </SPAN>Enables input for collision. <BR> <SPAN CLASS="setting">Linear Damping: </SPAN>Enables input for linear damping. <BR> <SPAN CLASS="setting">Angular Damping: </SPAN>Enables input for angular damping. <BR> <SPAN CLASS="setting">Filter Groups: </SPAN>Enables input for filter groups. <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBSetEx.cpp </SPAN> */ //proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); /*proto->DeclareSetting("Kinematic",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Gravity",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Collision",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Mass Offset",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Pivot Offset",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Notify Collision",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Transformation Locks",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Linear Damping",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Angular Damping",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Filter Groups",CKPGUID_BOOL,"FALSE"); */ proto->SetBehaviorCallbackFct( PVSetGearsCB ); BB_EVALUATE_PINS(gPIMAP) BB_EVALUATE_SETTINGS(gPIMAP); //proto->DeclareSetting("Output Ratio Curve",CKPGUID_BOOL,"TRUE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PVSetGears); *pproto = proto; return CK_OK; } //************************************ // Method: PVSetGears // FullName: PVSetGears // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int getNewRatioTable( CKBehavior*beh,float dst[],CK2dCurve *resultCurve,int size = 6) { int result = 0 ; BB_DECLARE_PIMAP;//retrieves the parameter input configuration array ////////////////////////////////////////////////////////////////////////// // // We store safely some temporary data to determine the given // user values are valid and can be send to the motor // CKParameterIn *inP = beh->GetInputParameter(BB_IP_INDEX(I_Ratios)); CKParameter *pout= inP->GetDirectSource(); if (pout) { int gear = 0; float ratio = 0.0f; for (int i = 0 ; i < 6 ; i++) { CK_ID* paramids = static_cast<CK_ID*>(pout->GetReadDataPtr()); CKParameter * sub = static_cast<CKParameterOut*>(GetPMan()->m_Context->GetObject(paramids[i])); if (sub) { gear = GetValueFromParameterStruct<int>(sub,0,false); ratio = GetValueFromParameterStruct<float>(sub,1,false); if ( ratio !=0.0 ) { dst[i] = ratio; result++; //dst.insert(gear,ratio); if (resultCurve ) { float dx = 1/ (size) ; float dy = ratio / 10; resultCurve->AddControlPoint(Vx2DVector(dx,dy) ); beh->SetOutputParameterValue(0,&resultCurve); } } } } } return result; } int PVSetGears(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbSErrorME(E_PE_REF); pRigidBody *body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); pVehicle *v = body->getVehicle(); if (!v) bbSErrorME(E_PE_NoVeh); if (!v->isValidEngine()) bbErrorME("Vehicle is not complete"); pGearBox *gBox = v->getGearBox(); if (!gBox) bbErrorME("No valid gearbox"); CK2dCurve* pOCurve = NULL; //optional CK2dCurve* pICurve = NULL; //optional BB_DECLARE_PIMAP;//retrieves the parameter input configuration array BBSParameterM(I_XML,BB_SSTART);//our bb settings concated as s##I_XML BBSParameterM(I_nbFGears,BB_SSTART); BBSParameterM(I_Flags,BB_SSTART); BBSParameterM(I_Ratios,BB_SSTART); BBSParameterM(I_ShiftUpRPM,BB_SSTART); BBSParameterM(I_ShiftDownRPM,BB_SSTART); BBSParameterM(I_Clutch,BB_SSTART); BBSParameterM(I_ClutchRelease,BB_SSTART); int xmlLink = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_XML)); int nbGears = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_nbFGears)); int flags = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_Flags)); //---------------------------------------------------------------- // // setup ratios / inertias // CKParameterIn *inP = beh->GetInputParameter(BB_IP_INDEX(I_Ratios)); CKParameter *pout= inP->GetDirectSource(); if (pout) { IParameter::Instance()->copyTo(gBox,pout); v->getDriveLine()->CalcPreClutchInertia(); v->getDriveLine()->CalcCumulativeRatios(); v->getDriveLine()->CalcEffectiveInertiae(); v->getDriveLine()->CalcPostClutchInertia(); } //---------------------------------------------------------------- // // Setup nb of gears // iAssertW1(X_IS_BETWEEN(nbGears,3,10),nbGears=3); gBox->setGears(nbGears); //---------------------------------------------------------------- // // RPMs // if (sI_ShiftUpRPM) gBox->setShiftUpRPM(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_ShiftUpRPM))); if (sI_ShiftDownRPM) gBox->setShiftDownRPM(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_ShiftDownRPM))); if (sI_Clutch) gBox->setTimeToClutch(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_Clutch))); if (sI_ClutchRelease) gBox->setTimeToDeclutch(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_ClutchRelease))); //float bRatio = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_BRatio));//silent update ////////////////////////////////////////////////////////////////////////// //a optinal curve to display ratio between horse power and rpm /*DWORD outputCurve; beh->GetLocalParameterValue(BB_PMAP_SIZE(gPIMAP),&outputCurve);//special settings ! if (outputCurve) beh->GetOutputParameterValue(0,&pOCurve); */ /*if (!gears && !sI_Ratios ) { sI_Ratios = true; }*/ ////////////////////////////////////////////////////////////////////////// // // Checking we have to replace of the entire motor object ! // if (sI_Ratios) { ////////////////////////////////////////////////////////////////////////// // pLinearInterpolation nTable; /*nbGears = gDesc->nbForwardGears; int ratioSize = getNewRatioTable(beh,gDesc->forwardGearRatios,NULL,nbGears); */ /* if (ratioSize ) { ////////////////////////////////////////////////////////////////////////// if (pOCurve) { while (pOCurve->GetControlPointCount()) { pOCurve->DeleteControlPoint(pOCurve->GetControlPoint(0)); pOCurve->Update(); } } // gDesc->backwardGearRatio = sI_BRatio ? bRatio : gears ? gears->_minRpm: mDesc->minRpm; //getNewRatioTable(beh,gDesc->forwardGearRatios,pOCurve,ratioSize); //if (!gDesc->isValid()) bbErrorME("gear description was invalid, aborting update "); //gDesc->nbForwardGears =ratioSize; //v->setGears(pFactory::Instance()->createVehicleGears(*gDesc)); pVehicleGears *loaded = v->getGears(); if (!loaded) bbErrorME("creating of new gears failed unexpected"); } */ } ////////////////////////////////////////////////////////////////////////// // // Flexibility : // /* if (sI_nbFGears && gears )gears->_nbForwardGears = nbGears; if (sI_BRatio && gears )gears->_backwardGearRatio; if (outputCurve && pOCurve ) { int s = pOCurve->GetControlPointCount(); for (int i = 0 ; i < pOCurve->GetControlPointCount() ; i++) { CK2dCurvePoint* point = pOCurve->GetControlPoint(i); point->SetLinear(true); } pOCurve->Update(); beh->SetOutputParameterValue(0,&pOCurve); } delete gDesc; gDesc; */ } beh->ActivateOutput(0); return 0; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtAttributeHelper.h" #include "pCommon.h" #include "IParameter.h" #include "vtBBHelper.h" #include "xDebugTools.h" #include "pCallbackSignature.h" int PhysicManager::_checkListCheck() { int result = 0 ; while(bodyListCheck.Size()) { result ++; bodyListCheck.PopBack(); } return result; } int PhysicManager::_checkRemovalList() { int result = 0 ; if (bodyListRemove.Size() < 1) return 0; pWorldMapIt wit = getWorlds()->Begin(); bool wasDeleting = false; while(wit != getWorlds()->End()) { pWorld *w = *wit; int cCount = bodyListRemove.Size(); //for (CK3dEntity** it = bodyListRemove.Begin(); it != bodyListRemove.End(); ++it) //int i = 0 ; i < bodyListRemove.Size() ; i ++ ) while(bodyListRemove.Size()) { CK_ID id = *bodyListRemove.At(0); CK3dEntity * ent = (CK3dEntity*)GetPMan()->GetContext()->GetObject(id); if(ent) { pRigidBody* body = GetPMan()->getBody(ent); if (body) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"deleting body "); body->destroy(); SAFE_DELETE(body) cCount = bodyListRemove.Size(); result ++; } } bodyListRemove.PopFront(); } wit++; } //bodyListRemove.Clear(); //_cleanOrphanedJoints(); if(wasDeleting) { } //getScene()->checkResults(NX_ALL_FINISHED,true) /* pWorldMapIt it = getWorlds()->Begin(); while(it != getWorlds()->End()) { pWorld *w = *it; w->getScene()->fetchResults(NX_ALL_FINISHED,false); it++; } */ return result; } XString printSignature(BBParameter pAarray[],int size) { CKParameterManager *pm = GetPMan()->GetContext()->GetParameterManager(); XString signature; for(int i = 0 ; i < size ; i ++ ) { BBParameter *par = &pAarray[i]; signature << "\t\t Parameter :" << par->name << ": must be type of " << pm->ParameterGuidToName(par->guid) << " \n "; } return signature; } bool isCompatible(CKParameterManager *pm,CKGUID a,CKGUID b) { if (a == b) { return true; } //---------------------------------------------------------------- // // special case custom flags or enumeration, integer is possible // if ( ( pm->GetEnumDescByType(pm->ParameterGuidToType(a)) || pm->GetFlagsDescByType(pm->ParameterGuidToType(a)) ) && pm->IsDerivedFrom(b,CKPGUID_INT) ) { return true; } return false; } int checkInputSignature(CKBehavior *beh,BBParameter *pAarray,int size) { int result = true; int parameterCount = beh->GetInputParameterCount(); if ( parameterCount < size) { result = 0; } CKParameterManager *pm = GetPMan()->GetContext()->GetParameterManager(); for (int i = 0 ; i < size ; i ++) { CKParameterIn *inPar = beh->GetInputParameter(i); BBParameter *par = &pAarray[i]; if (!isCompatible(pm,par->guid,inPar->GetGUID())) { result = 0; } } return result; } int checkOutputSignature(CKBehavior *beh,BBParameter *pAarray,int size) { int result = 1; int parameterCount = beh->GetOutputParameterCount(); if ( parameterCount < size) { result= 0; } CKParameterManager *pm = GetPMan()->GetContext()->GetParameterManager(); for (int i = 0 ; i < size ; i ++) { CKParameterOut *inPar = beh->GetOutputParameter(i); BBParameter *par = &pAarray[i]; if (!isCompatible(pm,par->guid,inPar->GetGUID())) { result= 0; } } return result; } bool PhysicManager::checkCallbackSignature(CKBehavior *beh,int type,XString& errMessage) { if (!beh) { return false; } CKParameterManager *pm = GetPMan()->GetContext()->GetParameterManager(); int parameterCount = beh->GetInputParameterCount(); switch(type) { //---------------------------------------------------------------- // // Collisions notify // case CB_OnContactNotify: { errMessage.Format("\n\t Input parameters for collisions notify must have this signature : \n"); if ( parameterCount < BB_PMAP_SIZE(pInMapContactCallback)) { errMessage << printSignature(pInMapContactCallback,BB_PMAP_SIZE(pInMapContactCallback) ); return false; } for (int i = 0 ; i < BB_PMAP_SIZE(pInMapContactCallback) ; i ++) { CKParameterIn *inPar = beh->GetInputParameter(i); BBParameter *par = &pInMapContactCallback[i]; if (!isCompatible(pm,par->guid,inPar->GetGUID())) { errMessage << printSignature(pInMapContactCallback,BB_PMAP_SIZE(pInMapContactCallback) ); return false; } } return true; } //---------------------------------------------------------------- // // wheel contact modify // case CB_OnWheelContactModify: { //---------------------------------------------------------------- // // check input parameters // bool result = true; errMessage.Format("\n\t Input parameters for wheel contact modification must have this signature : \n"); int ok = checkInputSignature(beh,pInMapWheelContactModifyCallback,BB_PMAP_SIZE(pInMapWheelContactModifyCallback)); if ( !ok ) { errMessage << printSignature(pInMapWheelContactModifyCallback,BB_PMAP_SIZE(pInMapWheelContactModifyCallback) ); result =false; } //---------------------------------------------------------------- // // check output parameters // errMessage.Format("\n\t Input parameters for wheel contact modification must have this signature : \n"); ok = checkOutputSignature(beh,pOutMapWheelContactModifyCallback,BB_PMAP_SIZE(pOutMapWheelContactModifyCallback)); if (!ok) { errMessage << printSignature(pOutMapWheelContactModifyCallback,BB_PMAP_SIZE(pOutMapWheelContactModifyCallback) ); result = false; } return result; } //---------------------------------------------------------------- // // Collisions notify // case CB_OnRayCastHit: { //---------------------------------------------------------------- // // check input parameters // errMessage.Format("\n\t Input parameters for raycast hit report must have this signature : \n"); int ok = checkInputSignature(beh,pInMapRaycastHitCallback,BB_PMAP_SIZE(pInMapRaycastHitCallback)); if ( !ok ) { errMessage << printSignature(pInMapRaycastHitCallback,BB_PMAP_SIZE(pInMapRaycastHitCallback)); return false; } return true; } //---------------------------------------------------------------- // // Collisions notify // case CB_OnContactModify: { //---------------------------------------------------------------- // // check input parameters // bool result = true; errMessage.Format("\n\t Input parameters for contact modification must have this signature : \n"); int ok = checkInputSignature(beh,pInMapContactModifyCallback,BB_PMAP_SIZE(pInMapContactModifyCallback)); if ( !ok ) { errMessage << printSignature(pInMapContactModifyCallback,BB_PMAP_SIZE(pInMapContactModifyCallback) ); result =false; } //---------------------------------------------------------------- // // check output parameters // errMessage.Format("\n\t Output parameters for contact modification must have this signature : \n"); ok = checkOutputSignature(beh,pOutMapContactModifyCallback,BB_PMAP_SIZE(pOutMapContactModifyCallback)); if (!ok) { errMessage << printSignature(pOutMapContactModifyCallback,BB_PMAP_SIZE(pOutMapContactModifyCallback) ); result = false; } return result; } //---------------------------------------------------------------- // // trigger // //---------------------------------------------------------------- // // Collisions notify // case CB_OnTrigger: { errMessage.Format("\n\t Input parameters for trigger notify must have this signature : \n"); if ( parameterCount < BB_PMAP_SIZE(pInMapTriggerCallback)) { errMessage << printSignature(pInMapTriggerCallback,BB_PMAP_SIZE(pInMapTriggerCallback) ); return false; } for (int i = 0 ; i < BB_PMAP_SIZE(pInMapTriggerCallback) ; i ++) { CKParameterIn *inPar = beh->GetInputParameter(i); BBParameter *par = &pInMapTriggerCallback[i]; if (!isCompatible(pm,par->guid,inPar->GetGUID())) { errMessage << printSignature(pInMapTriggerCallback,BB_PMAP_SIZE(pInMapTriggerCallback) ); return false; } } return true; } //---------------------------------------------------------------- // // Joint Break Script // case CB_OnJointBreak: { errMessage.Format("\n\t Input parameters for joint breaks must have this signature : \n"); if ( parameterCount < BB_PMAP_SIZE(pInMapJointBreakCallback)) { errMessage << printSignature(pInMapJointBreakCallback,BB_PMAP_SIZE(pInMapJointBreakCallback) ); return false; } for (int i = 0 ; i < BB_PMAP_SIZE(pInMapJointBreakCallback) ; i ++) { CKParameterIn *inPar = beh->GetInputParameter(i); BBParameter *par = &pInMapJointBreakCallback[i]; if (!isCompatible(pm,par->guid,inPar->GetGUID())) { errMessage << printSignature(pInMapJointBreakCallback,BB_PMAP_SIZE(pInMapJointBreakCallback) ); return false; } } return true; } } return false; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" //#include "pVehicle.h" PhysicManager *ourMan = NULL; CKGUID GetPhysicManagerGUID() { return GUID_MODULE_MANAGER;} typedef ForceMode PForceMode; typedef D6MotionMode PJMotion; typedef D6DriveType PDriveType; typedef int BodyLockFlags; ////////////////////////////////////////////////////////////////////////// #define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) void PhysicManager::_RegisterVSLRigidBody() { STARTVSLBIND(m_Context) STOPVSLBIND } PhysicManager*GetPhysicManager() { return GetPMan(); } /* void __newvtWorldSettings(BYTE *iAdd) { new (iAdd) pWorldSettings(); } void __newvtSleepingSettings(BYTE *iAdd) { new (iAdd) pSleepingSettings(); } void __newvtJointSettings(BYTE *iAdd) { new (iAdd) pJointSettings(); } int TestWS(pWorldSettings pWS) { VxVector grav = pWS.Gravity(); return 2; } pFactory* GetPFactory(); pFactory* GetPFactory() { return pFactory::Instance(); } extern pRigidBody*getBody(CK3dEntity*ent); */<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "tinyxml.h" pVehicle *pFactory::createVehicle(CK3dEntity *body,pVehicleDesc descr) { pVehicle *result =NULL; if (!body) { return result; } pRigidBody *rBody = GetPMan()->getBody(body); if (!rBody) { return result; } if (rBody->getVehicle()) { return rBody->getVehicle(); } descr.body = rBody; result = new pVehicle(descr,body); result->_vehicleMotor = NULL; result->_vehicleGears = NULL; result->setProcessOptions(descr.processFlags); result->setActor(rBody->getActor()); rBody->setVehicle(result); result->setMaxSteering(descr.steeringMaxAngle); result->initWheels(0); result->initEngine(0); //result->control(0, true, 0, true, false); //result->control(0, true, 0, true, false); return result; } pVehicleGears* pFactory::createVehicleGears(pVehicleGearDesc descr) { if (!descr.isValid()) return NULL; pVehicleGears *gears = new pVehicleGears(); NxI32 nbForwardGears = gears->_nbForwardGears = descr.nbForwardGears; memcpy(gears->_forwardGearRatios, descr.forwardGearRatios, sizeof(NxF32) * nbForwardGears); memcpy(gears->_forwardGears, descr.forwardGears, sizeof(pLinearInterpolation) * nbForwardGears); gears->_curGear = 1; //gears->_backwardGear = gearDesc.backwardGear; gears->_backwardGearRatio = descr.backwardGearRatio; return gears; } pVehicleMotor* pFactory::createVehicleMotor(pVehicleMotorDesc descr) { if (!descr.isValid()) return NULL; pVehicleMotor* motor = new pVehicleMotor(); motor->_torqueCurve = descr.torqueCurve; NxReal maxTorque = 0; NxI32 maxTorquePos = -1; for (NxU32 i = 0; i < motor->_torqueCurve.getSize(); i++) { NxReal v = motor->_torqueCurve.getValueAtIndex(i); if (v > maxTorque) { maxTorque = v; maxTorquePos = i; } } motor->_maxTorque = maxTorque; motor->_maxTorquePos = (float)maxTorquePos; motor->_maxRpmToGearUp = descr.maxRpmToGearUp; motor->_minRpmToGearDown = descr.minRpmToGearDown; motor->_maxRpm = descr.maxRpm; motor->_minRpm = descr.minRpm; motor->_rpm = 0.0f; return motor; } XString pFactory::_getVehicleWheelAsEnumeration(const TiXmlDocument * doc) { if (!doc) { return XString(""); } XString result("None=0"); int counter = 1; /************************************************************************/ /* */ /************************************************************************/ if ( doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "wheel" ) ) { const TiXmlElement *sube = (const TiXmlElement*)child; const char* vSName = NULL; vSName = sube->Attribute("name"); if (vSName && strlen(vSName)) { if (result.Length()) { result << ","; } result << vSName; result << "=" << counter; counter ++; } } } } } return result; } XString pFactory::_getVehicleSettingsAsEnumeration(const TiXmlDocument * doc) { if (!doc) { return XString(""); } XString result("None=0"); int counter = 1; /************************************************************************/ /* */ /************************************************************************/ if ( doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "vehicle" ) ) { const TiXmlElement *sube = (const TiXmlElement*)child; const char* vSName = NULL; vSName = sube->Attribute("name"); if (vSName && strlen(vSName)) { if (result.Length()) { result << ","; } result << vSName; result << "=" << counter; counter ++; } } } } } return result; } <file_sep>#include <StdAfx.h> #include "ToolManager.h" void ToolManager::RegisterVSL() { } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #ifdef HAS_FLUIDS pFluidEmitterDesc::pFluidEmitterDesc() { setToDefault(); } pFluidEmitterDesc::~pFluidEmitterDesc() { } void pFluidEmitterDesc::setToDefault() { frameShape = NULL; type = (pEmitterType)(NX_FE_CONSTANT_PRESSURE); maxParticles = 0; shape = (pEmitterShape)(NX_FE_RECTANGULAR); dimensionX = 0.25f; dimensionY = 0.25f; randomAngle = 0.0f; randomPos = VxVector(0,0,0); fluidVelocityMagnitude = 1.0f; rate = 100.0f; particleLifetime = 0.0f; repulsionCoefficient = 1.0f; flags = (pFluidEmitterFlag)(NX_FEF_ENABLED|NX_FEF_VISUALIZATION|NX_FEF_ADD_BODY_VELOCITY); } bool pFluidEmitterDesc::isValid() const { if (dimensionX < 0.0f) return false; if (dimensionY < 0.0f) return false; if (randomPos.x < 0.0f) return false; if (randomPos.y < 0.0f) return false; if (randomPos.z < 0.0f) return false; if (randomAngle < 0.0f) return false; if (!(((shape & NX_FE_ELLIPSE) > 0) ^ ((shape & NX_FE_RECTANGULAR) > 0))) return false; if (!(((type & NX_FE_CONSTANT_FLOW_RATE) > 0) ^ ((type & NX_FE_CONSTANT_PRESSURE) > 0))) return false; if (rate < 0.0f) return false; if (fluidVelocityMagnitude < 0.0f) return false; if (particleLifetime < 0.0f) return false; if (repulsionCoefficient < 0.0f) return false; return true; } #endif<file_sep>#define STRICT #define DIRECTINPUT_VERSION 0x0800 #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #include <tchar.h> #include <windows.h> #include <commctrl.h> #include <basetsd.h> #include <commdlg.h> #include <dinput.h> #include "CKAll.h" static CKContext *ctx = NULL; //---------------------------------------------------------------- // // // #define HAS_CONFIG #ifdef HAS_CONFIG #include "gConfig.h" #endif // BB_TOOLS #ifdef BB_TOOLS #include <vtInterfaceEnumeration.h> #include "vtLogTools.h" #include "vtCBBErrorHelper.h" #include <virtools/vtBBHelper.h> #include <virtools/vtBBMacros.h> using namespace vtTools::BehaviorTools; #endif //----------------------------------------------------------------------------- // Defines, constants, and global variables //----------------------------------------------------------------------------- struct EFFECTS_NODE { LPDIRECTINPUTEFFECT pDIEffect; DWORD dwPlayRepeatCount; EFFECTS_NODE* pNext; }; LPDIRECTINPUT8 g_pDI = NULL; LPDIRECTINPUTDEVICE8 g_pFFDevice = NULL; EFFECTS_NODE g_EffectsList; //----------------------------------------------------------------------------- // Function-prototypes //----------------------------------------------------------------------------- INT_PTR CALLBACK MainDialogProc( HWND, UINT, WPARAM, LPARAM ); BOOL CALLBACK EnumFFDevicesCallback( LPCDIDEVICEINSTANCE pDDI, VOID* pvRef ); BOOL CALLBACK EnumAndCreateEffectsCallback( LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ); HRESULT InitDirectInput( HWND hDlg ); HRESULT FreeDirectInput2(); VOID EmptyEffectList(); HRESULT OnReadFile( HWND hDlg,const char*file); HRESULT OnPlayEffects2( HWND hDlg ); HRESULT InitDirectInput( HWND hDlg ) { HRESULT hr; // Setup the g_EffectsList circular linked list ZeroMemory( &g_EffectsList, sizeof( EFFECTS_NODE ) ); g_EffectsList.pNext = &g_EffectsList; // Create a DInput object if( FAILED( hr = DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&g_pDI, NULL ) ) ) { ctx->OutputToConsole("PlayFFE :: DirectInput8Create"); return hr; } // Get the first enumerated force feedback device if( FAILED( hr = g_pDI->EnumDevices( 0, EnumFFDevicesCallback, 0, DIEDFL_ATTACHEDONLY | DIEDFL_FORCEFEEDBACK ) ) ) { ctx->OutputToConsole("PlayFFE :: EnumDevices failed"); return hr; } if( g_pFFDevice == NULL ) { ctx->OutputToConsole("PlayFFE :: No force feedback device found."); return -1; } // Set the data format if( FAILED( hr = g_pFFDevice->SetDataFormat( &c_dfDIJoystick ) ) ) return hr; // Set the coop level hr = g_pFFDevice->SetCooperativeLevel( hDlg , DISCL_EXCLUSIVE | DISCL_FOREGROUND) ; // Disable auto-centering spring DIPROPDWORD dipdw; dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = FALSE; if( FAILED( hr = g_pFFDevice->SetProperty( DIPROP_AUTOCENTER, &dipdw.diph ) ) ) return hr; // Acquire the device if( FAILED( hr = g_pFFDevice->Acquire() ) ) return hr; int op = 2; return S_OK; } //----------------------------------------------------------------------------- // Name: EnumFFDevicesCallback() // Desc: Get the first enumerated force feedback device //----------------------------------------------------------------------------- BOOL CALLBACK EnumFFDevicesCallback( LPCDIDEVICEINSTANCE pDDI, VOID* pvRef ) { if( FAILED( g_pDI->CreateDevice( pDDI->guidInstance, &g_pFFDevice, NULL ) ) ) return DIENUM_CONTINUE; // If failed, try again // Stop when a device was successfully found return DIENUM_STOP; } //----------------------------------------------------------------------------- // Name: FreeDirectInput2() // Desc: Initialize the DirectInput variables. //----------------------------------------------------------------------------- HRESULT FreeDirectInput2() { // Release any DirectInputEffect objects. if( g_pFFDevice ) { EmptyEffectList(); g_pFFDevice->Unacquire(); SAFE_RELEASE( g_pFFDevice ); } // Release any DirectInput objects. SAFE_RELEASE( g_pDI ); return S_OK; } //----------------------------------------------------------------------------- // Name: EmptyEffectList() // Desc: Goes through the circular linked list and releases the effects, // and deletes the nodes //----------------------------------------------------------------------------- VOID EmptyEffectList() { EFFECTS_NODE* pEffectNode = g_EffectsList.pNext; EFFECTS_NODE* pEffectDelete; while ( pEffectNode != &g_EffectsList ) { pEffectDelete = pEffectNode; pEffectNode = pEffectNode->pNext; SAFE_RELEASE( pEffectDelete->pDIEffect ); SAFE_DELETE( pEffectDelete ); } g_EffectsList.pNext = &g_EffectsList; } //----------------------------------------------------------------------------- // Name: OnReadFile() // Desc: Reads a file contain a collection of DirectInput force feedback // effects. It creates each of effect read in and stores it // in the linked list, g_EffectsList. //----------------------------------------------------------------------------- HRESULT OnReadFile( HWND hDlg,const char*file) { HRESULT hr; EmptyEffectList(); // Enumerate the effects in the file selected, and create them in the callback if( FAILED( hr = g_pFFDevice->EnumEffectsInFile( file,EnumAndCreateEffectsCallback, NULL, DIFEF_MODIFYIFNEEDED ) ) ) return hr; // If list of effects is empty, then we haven't been able to create any effects if( g_EffectsList.pNext == &g_EffectsList ) { ctx->OutputToConsole("Unable to create any effects."); } else { // We have effects so enable the 'play effects' button } return S_OK; } //----------------------------------------------------------------------------- // Name: EnumAndCreateEffectsCallback() // Desc: Create the effects as they are enumerated and add them to the // linked list, g_EffectsList //----------------------------------------------------------------------------- BOOL CALLBACK EnumAndCreateEffectsCallback(LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ) { HRESULT hr; LPDIRECTINPUTEFFECT pDIEffect = NULL; // Create the file effect if( FAILED( hr = g_pFFDevice->CreateEffect( pDIFileEffect->GuidEffect, pDIFileEffect->lpDiEffect, &pDIEffect, NULL ) ) ) { ctx->OutputToConsole("Could not create force feedback effect on this device"); return DIENUM_CONTINUE; } // Create a new effect node EFFECTS_NODE* pEffectNode = new EFFECTS_NODE; if( NULL == pEffectNode ) return DIENUM_STOP; // Fill the pEffectNode up ZeroMemory( pEffectNode, sizeof( EFFECTS_NODE ) ); pEffectNode->pDIEffect = pDIEffect; pEffectNode->dwPlayRepeatCount = 1; // Add pEffectNode to the circular linked list, g_EffectsList pEffectNode->pNext = g_EffectsList.pNext; g_EffectsList.pNext = pEffectNode; return DIENUM_CONTINUE; } //----------------------------------------------------------------------------- // Name: OnPlayEffects2() // Desc: Plays all of the effects enumerated in the file //----------------------------------------------------------------------------- HRESULT OnPlayEffects2( HWND hDlg ) { EFFECTS_NODE* pEffectNode = g_EffectsList.pNext; LPDIRECTINPUTEFFECT pDIEffect = NULL; HRESULT hr; // Stop all previous forces if( FAILED( hr = g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ) ) ) return hr; while ( pEffectNode != &g_EffectsList ) { // Play all of the effects enumerated in the file pDIEffect = pEffectNode->pDIEffect; if( NULL != pDIEffect ) { if( FAILED( hr = pDIEffect->Start( pEffectNode->dwPlayRepeatCount, 0 ) ) ) return hr; } pEffectNode = pEffectNode->pNext; } return S_OK; } CKObjectDeclaration *FillBehaviorPlayFFEffectDecl(); CKERROR CreatePlayFFEffectProto(CKBehaviorPrototype **); int PlayFFEffect(const CKBehaviorContext& behcontext); CKERROR PlayFFECallBackObject(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPlayFFEffectDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PlayFFEffect"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x54397475,0x4ca43e26)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePlayFFEffectProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Controllers/Joystick"); return od; } CKERROR CreatePlayFFEffectProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("PlayFFEffect"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Init"); proto->DeclareInput("play"); proto->DeclareInput("stop"); proto->DeclareInput("release device"); proto->DeclareOutput("initiated"); proto->DeclareOutput("play exit"); proto->DeclareOutput("stopped"); proto->DeclareOutput("released"); proto->DeclareOutput("error"); proto->DeclareInParameter("effect file",CKPGUID_STRING); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( PlayFFEffect ); proto->SetBehaviorCallbackFct(PlayFFECallBackObject); *pproto = proto; return CK_OK; } int PlayFFEffect(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx2 = behcontext.Context; ctx = ctx2; HWND mWin = (HWND )ctx->GetMainWindow(); //init and load effect if( beh->IsInputActive(0) ){ beh->ActivateInput(0,FALSE); HRESULT result = InitDirectInput(mWin); HRESULT sa = S_OK; if (InitDirectInput(mWin) == S_OK) { XString filename((CKSTRING) beh->GetInputParameterReadDataPtr(0)); OnReadFile(mWin,filename.Str()); beh->ActivateOutput(0); return CKBR_OK; }else{ beh->ActivateOutput(4); return CKBR_OK; } } //play if( beh->IsInputActive(1) ){ beh->ActivateInput(1,FALSE); if (OnPlayEffects2(NULL) != S_OK ){ beh->ActivateOutput(4); return CKBR_OK; } beh->ActivateOutput(1); return CKBR_OK; } //stop the effect if( beh->IsInputActive(2) ){ beh->ActivateInput(2,FALSE); // Stop all previous forces g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ); beh->ActivateOutput(2); return CKBR_OK; } // [11/7/2004] //save device release if( beh->IsInputActive(3) ){ beh->ActivateInput(3,FALSE); if ( g_pFFDevice) g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ); FreeDirectInput2(); beh->ActivateOutput(3); return CKBR_OK; } return CKBR_OK; } CKERROR PlayFFECallBackObject(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORDETACH: case CKM_BEHAVIORRESET: { if ( g_pFFDevice) g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ); FreeDirectInput2(); //Sleep(2000); } break; } return CKBR_OK; } <file_sep>#include "StdAfx.h" #include <PythonModule.h> #include "InitMan.h" extern vt_python_man *pym; int pModId = 0; PythonModule* PythonModule::GetPythonModule(int id) { VSLPModulesIt it = pym->GetVSLPModules().find(id); if(it != pym->GetVSLPModules().end() ) { return it->second; }else { return NULL; } return NULL; } ////////////////////////////////////////////////////////////////////////// PythonModule::PythonModule(const char*file,const char*func,int bid) : m_File(file) , m_Func(func) , m_BehaviourID(bid) { } ////////////////////////////////////////////////////////////////////////// PythonModule* PythonModule::CreatePythonModule(const char*file,const char*func,int bid) { PythonModule *pmod = new PythonModule(file,func,bid); int targetID = -1; ////////////////////////////////////////////////////////////////////////// //its used in schematic ? CKBehavior *script = static_cast<CKBehavior*>(pym->m_Context->GetObject(bid)); if (script) { targetID = bid; //PyObject* val = PyInt_FromLong(bid); //PyObject_SetAttrString( module , "bid", val); }else { } pym->InsertPVSLModule(pmod); return pmod; } <file_sep>#ifndef __VT_BB_HELPER_H__ #define __VT_BB_HELPER_H__ #include <xLogger.h> namespace vtTools { namespace BehaviorTools { struct BBParameter { int ID; CKGUID guid; XString name; XString defaultValue; int condition; int settingsID; int inputIndex; CKObject *par; bool fixed; BBParameter() { condition = -1; ID = 0; guid = CKGUID(0,0); name = ""; defaultValue = ""; settingsID = -1; par = NULL; inputIndex= -1; fixed = false; } BBParameter(int _ID,CKGUID _guid,XString _name,XString _defaultValue) : ID(_ID), guid(_guid) , name(_name) , defaultValue(_defaultValue) { condition = -1; settingsID = 0; par = NULL; inputIndex= -1; fixed = false; } BBParameter(int _ID,bool _fixed,CKGUID _guid,XString _name,XString _defaultValue,int _condition) : ID(_ID), guid(_guid) , name(_name) , defaultValue(_defaultValue) { condition = _condition; settingsID = 0; par = NULL; inputIndex= -1; fixed = _fixed; } BBParameter(int _ID,CKGUID _guid,XString _name,XString _defaultValue,int _condition) : ID(_ID), guid(_guid) , name(_name) , defaultValue(_defaultValue), condition(_condition) { settingsID = 0; par = NULL; inputIndex= -1; fixed = false; } }; class BBParArray { public : BBParArray() : isDuplicat(false) , isLoaded(false) , states(0){} std::vector<BBParameter*>pars; std::vector<BBParameter*>&getArray() { return pars; } bool isDuplicat; bool isLoaded; int states; int bbId; enum { BBArrayIsLoaded=1, BBArrayIsInitiated=2 }; }; class BBPOHelper { public : static int getIndex(CKBehavior *beh,BBParameter *par) { if (!par)return -1; if (par && !par->par )return -1; for (int i = 0 ; i< beh->GetOutputParameterCount() ; i++) { if (par->par == beh->GetOutputParameter(i)) return i; } return -1; } static void remapIndex(CKBehavior *beh,BBParArray *pAarray,int size ) { for (int i = 0 ; i < size ; i ++) { BBParameter *p=pAarray->getArray().at(i); p->inputIndex = p->par !=NULL ? getIndex(beh,p) : -1; } } static int getIndex(CKBehavior *beh,BBParArray *pAarray,int indicator ) { #ifdef _DEBUG assert(beh); assert(pAarray); #endif return pAarray->getArray().at(indicator)->inputIndex; } static int getIndexInv(CKBehavior *beh,BBParameter pInMap[],int indicator ) { #ifdef _DEBUG assert(beh); #endif for ( int i = 0 ; i < beh->GetOutputParameterCount() ; i++ ) { if (!strcmp(beh->GetOutputParameter(i)->GetName(),pInMap[indicator].name.Str() )) { return i; } } return -1; } static void loadPOMap(CKBehavior *beh,BBParArray *dst,BBParameter pInMap[],int size,int start) { for (int i = 0 ; i < size ; i ++) { BBParameter *p=new BBParameter(pInMap[i].ID,pInMap[i].guid,pInMap[i].name,pInMap[i].defaultValue,pInMap[i].condition); dst->getArray().push_back(p); CKParameterLocal *lp = beh->GetLocalParameter(start + i ); int v=0 ; lp->GetValue(&p->condition); if (p->condition) { int index = getIndexInv(beh,pInMap,i); p->par = ((CKObject*)beh->GetOutputParameter(index)); p->condition = 1; p->inputIndex = index; }else { p->par = NULL; p->condition=-1; p->inputIndex = -1; } } dst->isLoaded=true; } static void printPOMap(CKBehavior *beh,BBParArray *dst,BBParameter pInMap[],int size,int start) { XString header; if (dst->isLoaded) { header << "IsLoaded:" << "TRUE"; } header << "|Size:" << dst->getArray().size(); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,header.Str()); for (int i = 0 ; i < size ; i ++) { BBParameter *par = dst->getArray().at( i ); XString o; o << par->name << " : iIndex" << par->inputIndex << " | cond:" << par->condition; if (par->par !=NULL) { o << "| Par=1"; } xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,o.Str()); } } static void initPMap(CKBehavior *beh,BBParArray *dst,BBParameter pInMap[],int size,int start) { if (dst==NULL) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"No Array supplied"); } if (dst->isLoaded) { return; } for (int i = 0 ; i < size ; i ++) { BBParameter *p=new BBParameter(pInMap[i].ID,pInMap[i].guid,pInMap[i].name,pInMap[i].defaultValue,pInMap[i].condition); dst->getArray().push_back(p); if (pInMap[i].condition ==1 ) { CKParameterLocal *lp = beh->GetLocalParameter(start + i ); lp->SetValue(&pInMap[i].condition); p->par = (CKObject*)beh->CreateOutputParameter(pInMap[i].name.Str(),pInMap[i].guid); int index = getIndex(beh,p); } } BBPOHelper::remapIndex(beh,dst,size); } static void remapArray(CKBehavior *beh,BBParArray *pArray,int size,int settingStartIndex) { for (int sI = settingStartIndex; sI < size + settingStartIndex; sI ++ ) { CKParameterLocal *lp = beh->GetLocalParameter(sI ); int val = 0; lp->GetValue(&val); BBParameter *par = pArray->getArray().at( sI - settingStartIndex); ////////////////////////////////////////////////////////////////////////// // Settings ON : if (val) { if ( par->par == NULL ) { par->condition = 1; par->par = (CKObject*)beh->CreateOutputParameter(par->name.Str(),par->guid); } } ////////////////////////////////////////////////////////////////////////// // Settings ON : if (!val) { if ( par->par ) { CKDestroyObject(par->par); par->par = NULL; par->condition = -1; } } } remapIndex(beh,pArray,size); } static void destroyPMap(CKBehavior *beh,BBParArray *pArray) { BBParArray *pMap = static_cast<BBParArray *>(beh->GetAppData()); if (pMap) { while ( pMap->getArray().size() ) { BBParameter *p=pMap->getArray().at(0); pMap->getArray().erase(pMap->getArray().begin()); if (p) { p->par = NULL; delete p; p = NULL; } } beh->SetAppData(NULL); pMap->getArray().clear(); delete pMap; pMap = NULL; } } }; class BBHelper { public : /************************************************************************/ /* */ /************************************************************************/ static int getIndex(CKBehavior *beh,BBParameter *par) { if (!par)return -1; if (par && !par->par )return -1; for (int i = 0 ; i< beh->GetInputParameterCount() ; i++) { if (par->par == beh->GetInputParameter(i)) return i; } return -1; } /************************************************************************/ /* */ /************************************************************************/ static void remapIndex(CKBehavior *beh,BBParArray *pAarray,int size ) { for (int i = 0 ; i < size ; i ++) { BBParameter *p=pAarray->getArray().at(i); p->inputIndex = p->par !=NULL ? getIndex(beh,p) : -1; } } /************************************************************************/ /* */ /************************************************************************/ static int getIndex(CKBehavior *beh,BBParArray *pAarray,int indicator ) { #ifdef _DEBUG assert(beh); assert(pAarray); #endif return pAarray->getArray().at(indicator)->inputIndex; } /************************************************************************/ /* */ /************************************************************************/ static int getIndexInv(CKBehavior *beh,BBParameter pInMap[],int indicator ) { #ifdef _DEBUG assert(beh); #endif for ( int i = 0 ; i < beh->GetInputParameterCount() ; i++ ) { if (!strcmp(beh->GetInputParameter(i)->GetName(),pInMap[indicator].name.Str() )) { return i; } } return -1; } static void loadPIMap(CKBehavior *beh,BBParArray *dst,BBParameter pInMap[],int size,int start) { for (int i = 0 ; i < size ; i ++) { BBParameter *p=new BBParameter(pInMap[i].ID,pInMap[i].fixed,pInMap[i].guid,pInMap[i].name,pInMap[i].defaultValue,pInMap[i].condition); dst->getArray().push_back(p); if (!p->fixed) { int d = i - start ; CKParameterLocal *lp = beh->GetLocalParameter( i - start); lp->GetValue(&p->condition); } if (p->condition) { int index = getIndexInv(beh,pInMap,i); p->par = ((CKObject*)beh->GetInputParameter(index)); p->condition = 1; p->inputIndex = index; }else { p->par = NULL; p->condition=-1; p->inputIndex = -1; } } dst->isLoaded = true; } /************************************************************************/ /* */ /************************************************************************/ static void initPIMap(CKBehavior *beh,BBParArray *dst,BBParameter pInMap[],int size,int start) { if (dst->isLoaded) { return; } for (int i = 0 ; i < size ; i ++) { BBParameter *p=new BBParameter(pInMap[i].ID,pInMap[i].guid,pInMap[i].name,pInMap[i].defaultValue,pInMap[i].condition); dst->getArray().push_back(p); if (pInMap[i].condition ==1 ) { CKParameterLocal *lp = beh->GetLocalParameter(start + i ); lp->SetValue(&pInMap[i].condition); p->par = (CKObject*)beh->CreateInputParameter(pInMap[i].name.Str(),pInMap[i].guid); int index = getIndex(beh,p); } } BBHelper::remapIndex(beh,dst,size); } static void remapArray(CKBehavior *beh,BBParArray *pArray,int size,int settingStartIndex) { for (int sI = 0; sI < size ; sI ++ ) { BBParameter *par = pArray->getArray().at(sI); if (par->fixed) continue; CKParameterLocal *lp = beh->GetLocalParameter(sI - settingStartIndex ); int val = 0; lp->GetValue(&val); ////////////////////////////////////////////////////////////////////////// // Settings ON : if (val) { if ( par->par == NULL ) { par->condition = 1; par->par = (CKObject*)beh->CreateInputParameter(par->name.Str(),par->guid); } } ////////////////////////////////////////////////////////////////////////// // Settings ON : if (!val) { if ( par->par ) { CKDestroyObject(par->par); par->par = NULL; par->condition = -1; } } } remapIndex(beh,pArray,size); } /************************************************************************/ /* */ /************************************************************************/ static void destroyPIMap(CKBehavior *beh,BBParArray *pArray) { BBParArray *pIMap = static_cast<BBParArray *>(beh->GetAppData()); if (pIMap) { while ( pIMap->getArray().size() ) { BBParameter *p=pIMap->getArray().at(0); pIMap->getArray().erase(pIMap->getArray().begin()); if (p) { p->par = NULL; delete p; p = NULL; } } beh->SetAppData(NULL); pIMap->getArray().clear(); delete pIMap; pIMap = NULL; } } }; } } #endif<file_sep>dofile("ModuleConfig.lua") dofile("ModuleHelper.lua") if _ACTION == "help" then premake.showhelp() return end solution "vtArToolkit" configurations { "Debug", "Release" , "ReleaseDebug" ; "ReleaseRedist" ; "ReleaseDemo" } if _ACTION and _OPTIONS["Dev"] then setfields("location","./".._ACTION.._OPTIONS["Dev"]) end packageConfig_ARToolkit = { Name = "ArtToolkitLib", Type = "StaticLib", Defines = { DEF_STD_DIRECTIVES ; D_AT_DEFINES }, Files = { D_AT_SRC ; D_AT.."include/**.h"}, Includes = { D_AT_INCLUDES }, Options = { "/W0"} } -- Static library of the built-in camera building blocks -- -- This package needs to be compiled for web player distributions. -- Call createSolutions40Web2005.bat for instance -- packageConfig_CameraRepack= { Name = "Camera", Type = "StaticLib", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" }, Files = { DDEPS.."camera/behaviors/**.cpp" }, Includes = { D_STD_INCLUDES ; }, Libs = { "ck2" ; "vxmath" }, LibDirectories = { }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower() } -- The core vtPhysX SDK, compiled as DLL with exports. This is the entire base library for -- -- - building blocks -- - interface plug-ins -- - custom parameter types -- - custom file readers -- -- -- The building blocks for vtPhysX, depending on packageConfig_vtAgeiaLib packageConfig_vtArToolkitBeh = { Name = "ARToolkitBehaviors", Type = "SharedLib", TargetSuffix = "/BuildingBlocks", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "MODULE_BASE_EXPORTS" }, Files = { D_CORE_SRC ; DROOT.."SDK/src/Behaviors/**.cpp" ; DROOT.."SDK/src/Behaviors/*.def" ; F_SHARED_SRC ; DROOT.."build4/**.lua" ; F_EXTRA_BB_SRC ; F_BASE_SRC }, Includes = { D_STD_INCLUDES ; D_CORE_INCLUDES ; D_AT_INCLUDES }, Libs = { "ck2" ; "vxmath" ; "user32" ; "kernel32" ; "ArtToolkitLib" }, LibDirectories = { }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\BuildingBlocks" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\BuildingBlocks" } -- If the command line contains --ExtraDefines="WebPack" , we add "WebPack" to the -- pre-processor directives and also create a package to include the camera building blocks -- as defined in packageConfig_CameraRepack if _OPTIONS["ExtraDefines"] then if _OPTIONS["ExtraDefines"]=="WebPack" then createStaticPackage(packageConfig_CameraRepack) end end createStaticPackage(packageConfig_ARToolkit) createStaticPackage(packageConfig_vtArToolkitBeh) --include "CppConsoleApp" function onclean() os.rmdir("vs**") end <file_sep>--/************************************************************************/ --Build/Compiler Setup. --/************************************ --Internal Paths Substitution : DROOT = "../" DDEPS = DROOT.."Dependencies/" DDOCS = DROOT.."Docs" D_INCLUDE_ROOT = DROOT.."SDK/Include/" D_LIBS = DROOT.."SDK/Lib/" D_CORE_SRC = DROOT.."SDK/Src/Core/" D_BB_SRC = DROOT.."SDK/Src/Behaviors/" D_DIRECTX9 = DDEPS.."dx/" D_CORE_INCLUDE_DIRS = { D_INCLUDE_ROOT.."Core/Manager"; D_INCLUDE_ROOT.."Core"; D_INCLUDE_ROOT.."Core/Common"; } D_STD_INCLUDES = { "../Shared"; "../../usr/include"; } DEF_STD_DIRECTIVES = { "WIN32";"_WINDOWS" } --/************************************ --Your Paths settings : DEV35DIR=DDEPS.."vt/Dev35/" DEV40DIR=DDEPS.."vt/Dev40/" DEV41DIR=DDEPS.."vt/Dev41/" OUTPUT_PATH_OFFSETT_TO_PROJECTFILES ="../../Bin" OUTPUT_PATH_OFFSETT_TO_PROJECTFILES_MINUS_ONE = "../Bin" OUTPUT_PATH_OFFSETT_TO_INTERNAL_LIBS="../SDK/Lib/" OUTPUT_PATH_OFFSETT_TO_TMP="../TEMP" <file_sep>#include <CPStdAfx.h> #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "resourceplayer.h" #include "CustomPlayerDialogAboutPage.h" #include "CustomPlayerDialog.h" #include "commonhelpers.h" #include "CustomPlayerDefines.h" #include "mdexceptions.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutPage dialog namespace { enum { RE_CONTROL = 4711 // Id of the RichEdit Control }; // Retrieve the GPL text from our resources CString GetTextResource(UINT id) { CString s; HGLOBAL hresource = NULL; try { HRSRC hrsrc= FindResource(NULL, MAKEINTRESOURCE(id), _T("TEXT")); if (hrsrc == NULL) MdThrowLastWinerror(); DWORD dwSize= SizeofResource(AfxGetInstanceHandle(), hrsrc); if (dwSize == 0) MdThrowLastWinerror(); hresource= LoadResource(NULL, hrsrc); const BYTE *pData= (const BYTE *)LockResource(hresource); CComBSTR bstr(dwSize, (LPCSTR)pData); s= bstr; } catch (CException *pe) { pe->ReportError(); pe->Delete(); } if (hresource != NULL) FreeResource(hresource); return s; } } CustomPlayerDialogAboutPage::CustomPlayerDialogAboutPage() : CPropertyPage(CustomPlayerDialogAboutPage::IDD) { //{{AFX_DATA_INIT(CAboutPage) //}}AFX_DATA_INIT } void CustomPlayerDialogAboutPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutPage) //}}AFX_DATA_MAP DDX_Control(pDX, IDC_ERROR_RICHT_TEXT, m_ErrorRichText); } BEGIN_MESSAGE_MAP(CustomPlayerDialogAboutPage, CPropertyPage) //{{AFX_MSG_MAP(CAboutPage) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP ON_EN_SETFOCUS(IDC_ERROR_RICHT_TEXT, OnEnSetfocusErrorRichtText) ON_NOTIFY(EN_LINK, IDC_ERROR_RICHT_TEXT, OnEnLinkErrorRichtText) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CAboutPage message handlers void CustomPlayerDialogAboutPage::OnEnSetfocusErrorRichtText() { if (m_ErrorRichText) { CRect rc; m_ErrorRichText.GetWindowRect(rc); ScreenToClient(rc); DWORD newStyle= ES_CENTER; DWORD style= m_ErrorRichText.GetStyle(); style&= ~ES_CENTER; style|= newStyle; style|= WS_VSCROLL; DWORD exstyle= m_ErrorRichText.GetExStyle(); m_ErrorRichText.SetAutoURLDetect(); m_ErrorRichText.SetEventMask(ENM_LINK); m_ErrorRichText.SetFont(GetFont()); CString text; CFile aboutFile; CFileException ex; char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,"playerinfo.dat"); if(aboutFile.Open(Ini,CFile::modeNoTruncate|CFile::modeReadWrite|CFile::shareExclusive,&ex)) { char pbuf[16000]; DWORD length = aboutFile.Read(pbuf,16000); XString b(pbuf); XString bufferOut = b.Create(b.Str(),length); text.SetString(bufferOut.Str()); aboutFile.Close(); }else { text = GetTextResource(IDR_ABOUT); } m_ErrorRichText.SetWindowText(text); m_ErrorRichText.UpdateData(); m_ErrorRichText.UpdateWindow(); m_ErrorRichText.HideCaret(); } } void CustomPlayerDialogAboutPage::OnEnLinkErrorRichtText(NMHDR *pNMHDR, LRESULT *pResult) { ENLINK *el= reinterpret_cast<ENLINK *>(pNMHDR); *pResult = 0; if (el->msg == WM_LBUTTONDOWN) { CString link; m_ErrorRichText.GetTextRange(el->chrg.cpMin, el->chrg.cpMax, link); ShellExecute(*this, NULL, link, NULL, _T(""), SW_SHOWNORMAL); } } <file_sep>#ifndef _DistTypesAll_h #define _DistTypesAll_h #include "xDistributedPoint3F.h" #include "xDistributedPoint1F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint4F.h" #include "xDistributedInteger.h" #include "xDistributedString.h" #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "IParameter.h" bool pFactory::findSettings(pPivotSettings& dst,CKBeObject*src) { if (!src)return false; int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_PIVOT_OFFSET); if (par) return IParameter::Instance()->copyTo(dst,(CKParameter*)par); return false; } CKParameterOut* pFactory::findSettings(pWheelDescr& dst,CKBeObject*src) { if (!src)return false; int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_WHEEL_DESCR); CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_WHEEL_DESCR); if (!par) { att = GetPMan()->GetContext()->GetAttributeManager()->GetAttributeTypeByName("Wheel"); par = src->GetAttributeParameter(att); } bool copied = IParameter::Instance()->copyTo(dst,(CKParameter*)par); return par; } bool pFactory::findSettings(pCollisionSettings& dst,CKBeObject*src) { if (!src)return false; int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_COLLISIONS_SETTINGS); CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_COLLISIONS_SETTINGS); if (par) return IParameter::Instance()->copyTo(dst,(CKParameter*)par); return false; } bool pFactory::findSettings(pOptimization& dst,CKBeObject*src) { if (!src)return false; int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_ACTOR_OPTIMIZATION); if (par) return IParameter::Instance()->copyTo(dst,(CKParameter*)par); return false; } bool pFactory::findSettings(pMassSettings& dst,CKBeObject*src) { if (!src)return false; int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_MASS_SETUP); if (par) return IParameter::Instance()->copyTo(dst,(CKParameter*)par); return false; } int pFactory::copyTo(CKParameter *src,pDominanceSetupItem&dst) { int result = 0 ; #ifdef _DEBUG assert(src); #endif // _DEBUG using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; CKParameter *contraintParameter = GetParameterFromStruct(src,PS_WD_CONSTRAINT); dst.constraint.dominanceA = GetValueFromParameterStruct<float>(contraintParameter,PS_WDC_A); dst.constraint.dominanceB = GetValueFromParameterStruct<float>(contraintParameter,PS_WDC_B); dst.dominanceGroup0 = GetValueFromParameterStruct<int>(src,PS_WD_GROUP_A); dst.dominanceGroup1 = GetValueFromParameterStruct<int>(src,PS_WD_GROUP_B); return 0; } bool pFactory::copyTo(pConvexCylinderSettings&dst,CKParameter*src,bool evaluate/* =true */) { bool result = false; #ifdef _DEBUG assert(src); #endif // _DEBUG using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; //int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); //CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_MASS_SETUP); /* if (par) return IParameter::Instance()->copyTo(dst,(CKParameter*)src); */ copyTo(dst.radius, GetParameterFromStruct(src,PS_CC_RADIUS_REFERENCED_VALUE),true); copyTo(dst.height, GetParameterFromStruct(src,PS_CC_HEIGHT_REFERENCED_VALUE),true); dst.approximation = GetValueFromParameterStruct<int>(src,PS_CC_APPROXIMATION); //################################################################ // // Calculate Forward Axis, optionally referenced by an entity // dst.forwardAxis = GetValueFromParameterStruct<VxVector>(src,PS_CC_FORWARD_AXIS); dst.forwardAxisRef = GetValueFromParameterStruct<CK_ID>(src,PS_CC_FORWARD_AXIS_REF); CK3dEntity *f = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.forwardAxisRef); if (f) { VxVector dir,up,right; f->GetOrientation(&dir,&up,&right); f->TransformVector(&dst.forwardAxis,&dir); dst.forwardAxis.Normalize(); } //################################################################ // // Calculate Down Axis, optionally referenced by an entity // dst.downAxis = GetValueFromParameterStruct<VxVector>(src,PS_CC_DOWN_AXIS); dst.downAxisRef = GetValueFromParameterStruct<CK_ID>(src,PS_CC_DOWN_AXIS_REF); CK3dEntity *d = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.downAxisRef); if (d) { VxVector dir,up,right; d->GetOrientation(&dir,&up,&right); d->TransformVector(&dst.downAxis,&up); dst.downAxis.Normalize(); } //################################################################ // // Calculate Right Axis, optionally referenced by an entity // dst.rightAxis = GetValueFromParameterStruct<VxVector>(src,PS_CC_RIGHT_AXIS); dst.rightAxisRef = GetValueFromParameterStruct<CK_ID>(src,PS_CC_RIGHT_AXIS_REF); CK3dEntity *r = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.rightAxisRef); if (r) { VxVector dir,up,right; r->GetOrientation(&dir,&up,&right); r->TransformVector(&dst.rightAxis,&right); dst.rightAxis.Normalize(); } dst.buildLowerHalfOnly = GetValueFromParameterStruct<int>(src,PS_CC_BUILD_LOWER_HALF_ONLY); dst.convexFlags = (pConvexFlags)GetValueFromParameterStruct<int>(src,PS_CC_EXTRA_SHAPE_FLAGS); return true; } bool pFactory::findSettings(pConvexCylinderSettings&dst,CKBeObject *src) { bool result = false; #ifdef _DEBUG assert(src); #endif // _DEBUG using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; int attType = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR); CKParameterOut *pout = src->GetAttributeParameter(attType); if (!pout) { CKMesh *currentMesh = ((CK3dEntity*)src)->GetCurrentMesh(); if (currentMesh) { pout = currentMesh->GetAttributeParameter(attType); if (!pout) { dst.forwardAxis.Set(1.0f,0.0f,0.0f); dst.downAxis.Set(0.0f,-1.0f,0.0f); dst.rightAxis.Set(0.0f,0.0f,-1.0f); dst.buildLowerHalfOnly = false; dst.approximation = 10; VxVector size(0.0f); if (src->GetClassID() == CKCID_3DOBJECT ) { CK3dEntity *ent3D = (CK3dEntity*)src; if (ent3D) { size = ent3D->GetBoundingBox(true).GetSize(); } }else if(src->GetClassID() == CKCID_MESH) { CKMesh *mesh = (CKMesh*)src; if (mesh) { size = mesh->GetLocalBox().GetSize(); } } dst.radius.value = size.x * 0.5f; dst.height.value = size.y; return false; } } } return copyTo(dst,pout); } bool pFactory::findSettings(pCapsuleSettings&dst,CKBeObject *src) { bool result = false; if (!src) { return result; } using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; CKParameterOut *pout = src->GetAttributeParameter(GetPMan()->att_capsule); if (!pout) { CKMesh *currentMesh = ((CK3dEntity*)src)->GetCurrentMesh(); if (currentMesh) { pout = currentMesh->GetAttributeParameter(GetPMan()->att_capsule); if (!pout) { dst.localLengthAxis = CKAXIS_Y; dst.localRadiusAxis = CKAXIS_X; dst.height = -1.0f; dst.radius = -1.0f; return false; } } } return copyTo(dst,pout); } bool pFactory::findSettings(pCapsuleSettingsEx&dst,CKBeObject *src) { using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; if (!src)return false; int att = GetPMan()->getAttributeTypeByGuid(VTS_CAPSULE_SETTINGS_EX); CKParameterOut *par = findSettingsParameter(src,VTS_CAPSULE_SETTINGS_EX); if (par) return IParameter::Instance()->copyTo(dst,(CKParameter*)par); //dst.height.referenceAxis = CKAXIS_Y; //dst.radius.referenceAxis = CKAXIS_X; return false; } void pFactory::copyTo(pAxisReferencedLength&dst,CKParameter*src,bool evaluate) { #ifdef _DEBUG assert(src); #endif using namespace vtTools::ParameterTools; //################################################################ // // Retrieve the value : // dst.value = GetValueFromParameterStruct<float>(src,PS_ARL_VALUE); dst.referenceAxis = GetValueFromParameterStruct<int>(src,PS_ARL_REF_OBJECT_AXIS); //################################################################ // // Calculate the value basing on the given objects local box and an axis. // CK_ID idRef= GetValueFromParameterStruct<CK_ID>(src,PS_ARL_REF_OBJECT); CKBeObject *object = (CKBeObject*)GetPMan()->GetContext()->GetObject(idRef); if (!object) return; dst.reference = object; if (!evaluate)return; VxVector size(0.0f); if (object->GetClassID() == CKCID_3DOBJECT ) { CK3dEntity *ent3D = (CK3dEntity*)object; if (ent3D) { size = ent3D->GetBoundingBox(true).GetSize(); } }else if(object->GetClassID() == CKCID_MESH) { CKMesh *mesh = (CKMesh*)object; if (mesh) { size = mesh->GetLocalBox().GetSize(); } } dst.value = size[dst.referenceAxis]; } pWorldSettings*pFactory::getWorldSettings(CK3dEntity*ent) { /* ////////////////////////////////////////////////////////////////////////// //sanity checks : if (!ent ) { return NULL; } if (!ent->HasAttribute(GetPMan()->att_world_object )) { return NULL; } ////////////////////////////////////////////////////////////////////////// pWorldSettings *result = new pWorldSettings(); using namespace vtTools::AttributeTools; result->m_Gravity= GetValueFromAttribute<VxVector>(ent,GetPMan()->att_world_object,0); result->m_CFM= GetValueFromAttribute<float>(ent,GetPMan()->att_world_object,1); result->m_ERP= GetValueFromAttribute<float>(ent,GetPMan()->att_world_object,2); result->m_MaximumContactCorrectVelocity = GetValueFromAttribute<int>(ent,GetPMan()->att_world_object,3); result->m_ContactSurfaceLayer = GetValueFromAttribute<int>(ent,GetPMan()->att_world_object,4); return result; */ return NULL; } pObjectDescr* pFactory::createPObjectDescrFromParameter(CKParameter *par) { if (!par) return NULL; //################################################################ // // ATTENTION : // pObjectDescr *descr = new pObjectDescr(); using namespace vtTools::ParameterTools; int hType,flags,hierarchy,collGroup; VxVector mOffset,sOffset; float density,skinWidth,newDensity,totalMass; collGroup = GetValueFromParameterStruct<int>(par,E_PPS_COLL_GROUP,false); hierarchy = GetValueFromParameterStruct<int>(par,E_PPS_HIRARCHY,false); hType = GetValueFromParameterStruct<int>(par,E_PPS_HULLTYPE,false); flags = GetValueFromParameterStruct<int>(par,E_PPS_BODY_FLAGS,false); density = GetValueFromParameterStruct<float>(par,E_PPS_DENSITY,false); newDensity = GetValueFromParameterStruct<float>(par,E_PPS_NEW_DENSITY,false); totalMass = GetValueFromParameterStruct<float>(par,E_PPS_TOTAL_MASS,false); skinWidth = GetValueFromParameterStruct<float>(par,E_PPS_SKIN_WIDTH,false); mOffset = GetValueFromParameterStruct<VxVector>(par,E_PPS_MASS_OFFSET,false); sOffset = GetValueFromParameterStruct<VxVector>(par,E_PPS_MASS_OFFSET,false); descr->density = density; descr->skinWidth = skinWidth; descr->massOffset = mOffset; descr->shapeOffset = sOffset; descr->hullType = (HullType)hType; descr->flags = (BodyFlags)flags; descr->hirarchy = hierarchy; descr->newDensity = newDensity; descr->totalMass = totalMass; return descr; return NULL; } pSleepingSettings*pFactory::getSleepingSettings(CK3dEntity*ent) { /* ////////////////////////////////////////////////////////////////////////// //sanity checks : if (!ent ) { return NULL; } if (!ent->HasAttribute(GetPMan()->att_sleep_settings )) { return NULL; } ////////////////////////////////////////////////////////////////////////// pSleepingSettings *result = new pSleepingSettings(); using namespace vtTools::AttributeTools; result->m_SleepSteps= GetValueFromAttribute<int>(ent,GetPMan()->att_sleep_settings,0); result->m_AngularThresold= GetValueFromAttribute<float>(ent,GetPMan()->att_sleep_settings,1); result->m_LinearThresold = GetValueFromAttribute<float>(ent,GetPMan()->att_sleep_settings,2); result->m_AutoSleepFlag = GetValueFromAttribute<int>(ent,GetPMan()->att_sleep_settings,3); return result; */ return NULL; } bool pFactory::copyTo(pCapsuleSettings&dst,CKParameter*src) { if (!src) return false; using namespace vtTools::ParameterTools; dst.localLengthAxis = GetValueFromParameterStruct<int>(src,E_CS_LENGTH_AXIS); dst.localRadiusAxis = GetValueFromParameterStruct<int>(src,E_CS_RADIUS_AXIS); dst.radius = GetValueFromParameterStruct<float>(src,E_CS_RADIUS); dst.height = GetValueFromParameterStruct<float>(src,E_CS_LENGTH); return true; } int pFactory::copyTo(CKParameterOut*dst,pGroupsMask src) { if (!dst) return 0; using namespace vtTools::ParameterTools; using namespace vtTools::ParameterTools; int result = 0; SetParameterStructureValue<int>(dst,0,src.bits0,false); SetParameterStructureValue<int>(dst,1,src.bits1,false); SetParameterStructureValue<int>(dst,2,src.bits2,false); SetParameterStructureValue<int>(dst,3,src.bits3,false); return true; } int pFactory::copyTo(pGroupsMask &dst,CKParameter*src) { if (!src) return 0; using namespace vtTools::ParameterTools; using namespace vtTools::ParameterTools; dst.bits0 = GetValueFromParameterStruct<int>(src,0); dst.bits1 = GetValueFromParameterStruct<int>(src,1); dst.bits2 = GetValueFromParameterStruct<int>(src,2); dst.bits3 = GetValueFromParameterStruct<int>(src,3); return 1; } CKParameterOut *pFactory::findSettingsParameter(CKBeObject *src,CKGUID guid) { if (!src)return NULL; int att = GetPMan()->getAttributeTypeByGuid(guid); CKParameterOut *par = src->GetAttributeParameter(att); if (par){ return par; } //---------------------------------------------------------------- // // Try sub objects // CK3dEntity *ent3D = static_cast<CK3dEntity*>(src); if (ent3D) { CKMesh *mesh = ent3D->GetCurrentMesh(); if (mesh) { par = mesh->GetAttributeParameter(att); if (!par) { for (int i = 0 ; i < mesh->GetMaterialCount() ; i++) { CKMaterial *entMaterial = mesh->GetMaterial(i); par = entMaterial->GetAttributeParameter(att); if (par) { break; } } } } } return par; }<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // AddNodalLink // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "StdAfx.h" #include "virtools/vtcxglobal.h" #include "windows.h" #include "Python.h" #include "vt_python_funcs.h" #include "pyembed.h" #include "InitMan.h" CKObjectDeclaration *FillBehaviorLoadPythonDecl(); CKERROR CreateLoadPythonProto(CKBehaviorPrototype **); int LoadPython(const CKBehaviorContext& behcontext); CKERROR LoadPythonCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorLoadPythonDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("LoadPython"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x422f5f39,0x71d0452b)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateLoadPythonProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Python"); return od; } CKERROR CreateLoadPythonProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("LoadPython"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); proto->DeclareInParameter("append libpath",CKPGUID_STRING); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( LoadPython ); *pproto = proto; return CK_OK; } int LoadPython(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; beh->ActivateInput(0,FALSE); XString path((CKSTRING) beh->GetInputParameterReadDataPtr(0)); vt_python_man *pm = (vt_python_man*)ctx->GetManagerByGuid(INIT_MAN_GUID); if (PythonLoad()) { syspath_append(path.Str()); beh->ActivateOutput(0); }else { beh->ActivateOutput(1); } return CKBR_OK; } <file_sep>#ifndef _XNETBASE_H_ #define _XNETBASE_H_ #ifndef _XNET_ENUMERATIONS_H_ #include "xNetEnumerations.h" #endif #ifndef _XNET_TYPES_H_ #include "xNetTypes.h" #endif #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPVGetDecl(); CKERROR CreatePVGetProto(CKBehaviorPrototype **pproto); int PVGet(const CKBehaviorContext& behcontext); CKERROR PVGetCB(const CKBehaviorContext& behcontext); using namespace vtTools; using namespace BehaviorTools; enum bbI_Inputs { bbI_BodyReference, }; #define BB_SSTART 0 enum bbOutputs { O_StateFlags, O_Acceleration, O_Steering, O_MTorque, O_MPH, O_RPM, O_MRPM, O_WRPM, O_Gear, }; BBParameter pOutMapv[] = { BB_SPOUT(O_StateFlags,VTF_VSTATE_FLAGS,"State Flags","0.0"), BB_SPOUT(O_Acceleration,CKPGUID_FLOAT,"Acceleration","0.0"), BB_SPOUT(O_Steering,CKPGUID_ANGLE,"Steering","0.0"), BB_SPOUT(O_MTorque,CKPGUID_FLOAT,"Motor Torque","0.0"), BB_SPOUT(O_MPH,CKPGUID_FLOAT,"MPH","0.0"), BB_SPOUT(O_RPM,CKPGUID_FLOAT,"RPM","0.0"), BB_SPOUT(O_MRPM,CKPGUID_FLOAT,"M - RPM","0.0"), BB_SPOUT(O_WRPM,CKPGUID_FLOAT,"Wheel RPM","0.0"), BB_SPOUT(O_Gear,CKPGUID_INT,"Gear","0.0"), }; #define gOPMap pOutMapv CKERROR PVGetCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; int cb = behcontext.CallbackMessage; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_POMAP(gOPMap,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PMAP(gOPMap,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PMAP(gOPMap,BB_SSTART); break; } } return CKBR_OK; } CKObjectDeclaration *FillBehaviorPVGetDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVGet"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Retrieves vehicle related parameters."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x70b293c,0x1ef4fa7)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVGetProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePVGetProto // FullName: CreatePVGetProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePVGetProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVGet"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( PVGetCB ); BB_EVALUATE_SETTINGS(gOPMap); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PVGet); *pproto = proto; return CK_OK; } //************************************ // Method: PVGet // FullName: PVGet // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PVGet(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); pVehicle *v = body->getVehicle(); if (!v) { bbSErrorME(E_PE_NoVeh); } BB_DECLARE_PMAP; /************************************************************************/ /* retrieve settings state */ /***** *******************************************************************/ BBSParameter(O_StateFlags); BBSParameter(O_Acceleration); BBSParameter(O_Steering); BBSParameter(O_MTorque); BBSParameter(O_MPH); BBSParameter(O_RPM); BBSParameter(O_MRPM); BBSParameter(O_WRPM); BBSParameter(O_Gear); /************************************************************************/ /* */ /************************************************************************/ BB_O_SET_VALUE_IF(int,O_StateFlags,v->getStateFlags()); BB_O_SET_VALUE_IF(float,O_Acceleration,v->_cAcceleration); BB_O_SET_VALUE_IF(float,O_Steering,v->_cSteering); BB_O_SET_VALUE_IF(float,O_MPH,v->getMPH()); float wRPM = v->_computeRpmFromWheels(); BB_O_SET_VALUE_IF(float,O_WRPM,wRPM); //---------------------------------------------------------------- // // output new engine values // if (v->isValidEngine()) { BB_O_SET_VALUE_IF(float,O_MTorque,v->getEngine()->GetEngineTorque()); BB_O_SET_VALUE_IF(float,O_RPM,v->getRPM()); BB_O_SET_VALUE_IF(int,O_Gear,v->getGear()); } /* if (v->getMotor()) { BB_O_SET_VALUE_IF(float,O_MTorque,v->getMotor()->getTorque()); float mRPM = v->_computeMotorRpm(wRPM); BB_O_SET_VALUE_IF(float,O_MRPM,mRPM); BB_O_SET_VALUE_IF(float,O_RPM,v->getMotor()->getRpm()); } if (v->getGears()) { BB_O_SET_VALUE_IF(int,O_Gear,v->getGears()->getGear()); } */ } beh->ActivateOutput(0); return 0; } //************************************ // Method: PVGetCB // FullName: PVGetCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ <file_sep>dofile("ModuleConfig.lua") dofile("ModuleHelper.lua") if _ACTION == "clean" then os.rmdir("./vs*") os.rmdir("../Temp") return end if _ACTION == "help" then premake.showhelp() return end solution "vtTools" configurations { "Debug", "Release" , "ReleaseDebug" } if _ACTION and _OPTIONS["Dev"] then setfields("location","./".._ACTION.._OPTIONS["Dev"]) end packageConfig_TCP4 = { Name = "Tcp4u", Type = "StaticLib", Defines = { DEF_STD_DIRECTIVES }, Files = { DDEPS.."tcp4u/include/*.h" ; DDEPS.."tcp4u/src/*.c*" }, Includes = { DDEPS.."tcp4u/include" }, Options = { "/W0"} } packageConfig_FTP4W32 = { Name = "FTP4W32", Type = "StaticLib", Defines = { DEF_STD_DIRECTIVES }, Files = { DDEPS.."ftpw32/*.h" ; DDEPS.."ftpw32/*.c*" }, Includes = { DDEPS.."tcp4u/include"; DDEPS.."ftpw32" }, Options = { "/W0"} } D_NetIncDirs = { DDEPS.."ftpw32" ; DDEPS.."tcp4u/include" } packageConfig_Behaviours = { Name = "vtToolkit", Type = "SharedLib", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "MODULE_BASE_EXPORTS" ; "USEDIRECTX9" }, TargetSuffix = "/BuildingBlocks", Files = { D_INCLUDE_ROOT.."*.h" ; D_INCLUDE_ROOT.."Core/**.h" ; D_CORE_SRC.."**.c*"; D_BB_SRC.."**.c*" ; D_BB_SRC.."*.def" }, Includes = { D_STD_INCLUDES ; D_CORE_INCLUDE_DIRS ; D_NetIncDirs ; DDEPS.."dx/Include" }, Libs = { "ck2" ; "vxmath" ; "user32" ; "kernel32" ; "FTP4W32" ; "Tcp4u" ; "Ws2_32" ; "dxerr"; "dinput8";"dxguid" ; "Version" }, LibDirectories = { D_DX.."lib" }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\BuildingBlocks" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\BuildingBlocks" } createStaticPackage(packageConfig_TCP4) createStaticPackage(packageConfig_FTP4W32) createStaticPackage(packageConfig_Behaviours) function onclean() print("cleaning") os.rmdir("vs*") end <file_sep>/******************************************************************** created: 2009/02/17 created: 17:2:2009 8:26 filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\include\core\Common\pTypes.h file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\include\core\Common file base: pTypes file ext: h author: <NAME> purpose: Type definitions, Function pointers *********************************************************************/ #ifndef __P_TYPES_H__ #define __P_TYPES_H__ #include "vtPhysXBase.h" #include "CKAll.h" //################################################################ // // Common used types for rigid bodies and joints // /** \brief Describes a joint spring. The spring is implicitly integrated, so even high spring and damper coefficients should be robust. pSpring is registered as custom structure #pJSpring and can be accessed or modified through parameter operations.<br> */ class pSpring { public: /** Damper coefficient */ float damper; /** Spring coefficient */ float spring; /** Target value (angle/position) of spring where the spring force is zero. */ float targetValue; pSpring() { damper = 0.0f; spring = 0.0f; targetValue = 0.0f; } pSpring(float _damper,float _spring,float _targetValue) { damper = _damper; spring = _spring; targetValue = _targetValue; } }; /** \addtogroup Collision @{ */ /** \brief 128-bit mask used for collision filtering. The collision filtering equation for 2 shapes S0 and S1 is: <pre> (G0 op0 K0) op2 (G1 op1 K1) == b </pre> with <ul> <li> G0 = pGroupsMask for shape S0. See ::setGroupsMask </li> <li> G1 = pGroupsMask for shape S1. See ::setGroupsMask </li> <li> K0 = filtering constant 0. See ::setFilterConstant0 </li> <li> K1 = filtering constant 1. See ::setFilterConstant1 </li> <li> b = filtering boolean. See ::setFilterBool </li> <li> op0, op1, op2 = filtering operations. See ::setFilterOps </li> </ul> If the filtering equation is true, collision detection is enabled. @see pWorld::setFilterOps() */ class pGroupsMask { public: API_INLINE pGroupsMask() {} API_INLINE ~pGroupsMask() {} int bits0, bits1, bits2, bits3; }; class pRay { public: VxVector orig; VxVector dir; }; class pRaycastHit { public: float distance; CK3dEntity *shape; VxVector worldImpact; VxVector worldNormal; int faceID; int internalFaceID; float u; float v; int materialIndex; int flags; pRaycastHit() { distance = 0.0; shape = NULL; u = 0.0f; v= 0.0f; faceID = 0 ; materialIndex = 0 ; flags = 0; } }; /** \brief Class for describing rigid bodies ccd settings. */ class pCCDSettings { public : bool isValid(); bool setToDefault(); bool evaluate(CKBeObject*referenceObject); float motionThresold; int flags; CK_ID meshReference; float scale; pCCDSettings() { motionThresold = 0.0; flags = 0 ; meshReference =0; scale = 1.0f; } }; /** \brief Class for describing rigid bodies or its sub shapes collisions settings. \sa #pRigidBody::updateCollisionSettings() */ class pCollisionSettings { public: bool isValid(); bool setToDefault(); /** \brief collisions group the shape belongs to - <b>Range:</b> [0,32] - <b>Default:</b> 0 */ int collisionGroup; /** \brief 128-bit mask used for collision filtering - <b>Range:</b> [0,4x4 bits] - <b>Default:</b> all off */ pGroupsMask groupsMask; /** \brief Additional collisions offset - <b>Range:</b> [0,1.0f] - <b>Default:</b>0.25f - Can NOT altered after creation */ float skinWidth; pCollisionSettings() { collisionGroup = 0; skinWidth = 0.025f; } }; //@} typedef std::vector<NxRaycastHit*>pRayCastHits; /** \brief Class for describing rigid bodies optimization. */ class MODULE_API pOptimization { public : bool isValid(); bool setToDefault(); /** \brief Flags to lock a rigid body in certain degree of freedom. See also #pRigidBody::lockTransformation */ BodyLockFlags transformationFlags; /** \brief Sets the linear damping coefficient. Zero represents no damping. The damping coefficient must be nonnegative. See pRigidBody::setLinearDamping */ float linDamping; /** \brief Sets the angular damping coefficient.Zero represents no damping. The damping coefficient must be nonnegative.See pRigidBody::setAngularDamping */ float angDamping; /** \copydoc pRigidBody::setSolverIterationCount */ int solverIterations; /** \copydoc pRigidBody::setDominanceGroup */ int dominanceGroup; /** \brief Not Implemented */ int compartmentGroup; /** \copydoc pRigidBody::setSleepEnergyThreshold */ float sleepEnergyThreshold; /** \copydoc pRigidBody::setSleepLinearVelocity */ float linSleepVelocity; /** \copydoc pRigidBody::setSleepAngularVelocity */ float angSleepVelocity; pOptimization() { transformationFlags = (BodyLockFlags)0; linDamping = angDamping = 0.0f; solverIterations = 24 ; dominanceGroup=0; compartmentGroup=0; sleepEnergyThreshold =0.0f; linSleepVelocity = angSleepVelocity = 0.0; } }; /** \brief Class for describing a shape's surface properties. */ class MODULE_API pMaterial { public : bool isValid(); /** \brief Flags, a combination of the bits defined by the enum ::pMaterialFlag <br> - <b>Default:</b> 0 @see MaterialFlags */ int flags; /** \brief Coefficient of dynamic friction. If set to greater than staticFriction, <br> the effective value of staticFriction will be increased to match. if flags & MF_Anisotropic is set, then this value is used for the primary direction of anisotropy (U axis)<br> - <b>Range:</b> [0,+inf) - <b>Default:</b> [0) */ float dynamicFriction; /** \brief Coefficient of static friction. If flags & MF_Anisotropic is set,<br> then this value is used for the primary direction of anisotropy (U axis) */ float staticFriction; /** \brief Coefficient of restitution. Makes the object bounce as little as possible, higher values up to 1.0 result in more bounce. Note that values close to or above 1 may cause stability problems and/or increasing energy. - <b>Range:</b> [0,1) - <b>Default:</b> [0) */ float restitution; /** \brief Anisotropic dynamic friction coefficient for along the secondary (V) axis of anisotropy. This is only used if flags & MF_Anisotropic is set. - <b>Range:</b> [0,inf) - <b>Default:</b> [0) */ float dynamicFrictionV; /** \brief Anisotropic static friction coefficient for along the secondary (V) axis of anisotropy. This is only used if flags & MF_Anisotropic is set. - <b>Range:</b> [0,inf) - <b>Default:</b> [0) */ float staticFrictionV; /** \brief Friction combine mode. See the enum CombineMode . - <b>Range:</b> [CombineMode) - <b>Default:</b> [CM_Average) */ CombineMode frictionCombineMode; /** \brief Restitution combine mode. See the enum CombineMode . - <b>Range:</b> [CombineMode) - <b>Default:</b> [CM_Average) */ CombineMode restitutionCombineMode; /** \brief shape space direction (unit vector) of anisotropy. This is only used if flags & MF_Anisotropic is set. - <b>Range:</b> [vector) - <b>Default:</b> [1.0f,0.0f,0.0f) */ VxVector dirOfAnisotropy; /** \brief unique name of the material */ const char* name; /** \brief Enumeration to identify a material setup from PhysicDefaults.xml. Is being populated automatically on reset. - <b>Range:</b> [0,Number of material setups in xml file) - <b>Default:</b> [NONE) */ int xmlLinkID; int getNxMaterialID() const { return mNxMaterialID; } void setNxMaterialID(int val) { mNxMaterialID = val; } pMaterial() { setToDefault(); } __inline void setToDefault() { dynamicFriction = 0.0f; staticFriction = 0.0f; restitution = 0.0f; dynamicFrictionV= 0.0f; staticFrictionV = 0.0f; dirOfAnisotropy = VxVector(1,0,0); flags = 0; frictionCombineMode = CM_Average; restitutionCombineMode = CM_Average; xmlLinkID =0; name = ""; } private : int mNxMaterialID; }; #endif<file_sep> #include "CKAll.h" #include "N3dGraph.h" char* Network3dName = "Nodal Path"; N3DGraph::N3DGraph(CKContext *context):m_Size(0),m_AllocatedSize(10) { m_States = new N3DState[m_AllocatedSize]; m_Display = NULL; m_EdgeNumber = 0; m_Context=context; } N3DGraph::~N3DGraph() { for(int i=0;i<m_Size;i++) { N3DEdge* edge = m_States[i].m_Edges; N3DEdge* temp; while(edge) { temp = edge; edge = edge->m_Next; delete temp; } } delete [] m_States; m_States = NULL; } void N3DGraph::TestAndReallocate(int n) { if(m_Size+n > m_AllocatedSize) { m_AllocatedSize *= 2; N3DState* old = m_States; m_States = new N3DState[m_AllocatedSize]; memcpy(m_States,old,m_Size*sizeof(N3DState)); delete [] old; } } int N3DGraph::GetStatesNumber() const { return m_Size; } int N3DGraph::GetEdgesNumber() const { return m_EdgeNumber; } N3DState* N3DGraph::InsertState(CK3dEntity* e) { if(!StateSeek(CKOBJID(e))) { TestAndReallocate(); m_States[m_Size].m_Edges = NULL; m_States[m_Size].m_Data = CKOBJID(e); m_Size++; return m_States+(m_Size-1); } return NULL; } void N3DGraph::SetDifficult(CK3dEntity *ent,float diff){ int sp = SeekPosition(CKOBJID(ent)); if(sp<0) return; N3DState* state = GetState(sp); if(state) { // first we (de)activate all the leaving edges N3DEdge* edge; edge = state->m_Edges; while(edge) { edge->m_Difficulty = diff ; edge = edge->m_Next; } } } N3DEdge* N3DGraph::InsertEdge(CK3dEntity* s,CK3dEntity* e,float d) { if(s == e) return NULL; int spos = SeekPosition(CKOBJID(s)); if(spos == -1) { // the first state isn't yet in graph InsertState(s); spos = m_Size-1; } // we check if the destination state is in the graph int epos = SeekPosition(CKOBJID(e)); if(epos == -1) { InsertState(e); epos = m_Size-1; } N3DEdge* edge = m_States[spos].m_Edges; if(edge) { while(edge->m_Next) { // if successor is already there, we didn't do anything if(edge->m_Successor == epos) return NULL; edge=edge->m_Next; } if(edge->m_Successor == epos) return NULL; edge->m_Next = CreateEdge(epos,d,GetDistance(GetState(spos),GetState(epos))); return edge->m_Next; } else { m_States[spos].m_Edges = CreateEdge(epos,d,GetDistance(GetState(spos),GetState(epos))); return m_States[spos].m_Edges; } } void N3DGraph::ActivateEdge(CK3dEntity* s,CK3dEntity* e,BOOL a,BOOL dyn) { N3DEdge* edge = EdgeSeek(CKOBJID(s),CKOBJID(e)); if(edge) { if(dyn) { if(a) edge->m_Active |= STATEDYNAMICACTIVITY; else edge->m_Active &= ~STATEDYNAMICACTIVITY; } else { if(a) { edge->m_Active |= STATEBASICACTIVITY; edge->m_Active |= STATEDYNAMICACTIVITY; } else { edge->m_Active &= ~STATEBASICACTIVITY; edge->m_Active &= ~STATEDYNAMICACTIVITY; } } } } void N3DGraph::ActivateState(CK3dEntity* s,BOOL a) { int sp = SeekPosition(CKOBJID(s)); if(sp<0) return; N3DState* state = GetState(sp); if(state) { // first we (de)activate all the leaving edges N3DEdge* edge; edge = state->m_Edges; while(edge) { if(a) edge->m_Active |= STATEDYNAMICACTIVITY; else edge->m_Active &= ~STATEDYNAMICACTIVITY; edge = edge->m_Next; } // next we iterate all the edges to (de)activate the entering ones for(int i=0;i<m_Size;i++) { // we have done it already... if(i == sp) continue; edge=m_States[i].m_Edges; while(edge) { if(edge->m_Successor == sp) { if(a) edge->m_Active |= STATEDYNAMICACTIVITY; else edge->m_Active &= ~STATEDYNAMICACTIVITY; } edge = edge->m_Next; } } } } BOOL N3DGraph::SetOccupier(CK3dEntity* s,CK3dEntity* o) { N3DState* state = StateSeek(CKOBJID(s)); if(state) { CK_ID id = CKOBJID(o); if(id) { // we are trying to set an occupier if(state->m_Occupier && state->m_Occupier!=id ) // there is already an occupier : we can't set it return FALSE; state->m_Occupier = id; } else { // we are trying to remove an occupation state->m_Occupier = 0; } return TRUE; } return FALSE; } CK3dEntity* N3DGraph::GetOccupier(CK3dEntity* s) { N3DState* state = StateSeek(CKOBJID(s)); if(state) { return (CK3dEntity*)m_Context->GetObject(state->m_Occupier); } return NULL; } BOOL N3DGraph::IsEdgeActive(CK3dEntity* s,CK3dEntity* e) { N3DEdge* edge = EdgeSeek(CKOBJID(s),CKOBJID(e)); if(edge) { return (edge->m_Active&STATEDYNAMICACTIVITY); } else return false; } void N3DGraph::ResetActivity() { N3DEdge* edge; for(int i=0;i<m_Size;i++) { // we delete the occupation m_States[i].m_Occupier = 0; // we reset links activity edge=m_States[i].m_Edges; while(edge) { if(edge->m_Active&STATEBASICACTIVITY) edge->m_Active |= STATEDYNAMICACTIVITY; else edge->m_Active &= ~STATEDYNAMICACTIVITY; edge = edge->m_Next; } } } void N3DGraph::DeleteState(CK_ID e) { int ni = SeekPosition(e); if(ni<0) return; // we now destroy all the edges leaving the destroyed node N3DEdge* edge; N3DEdge* backedge; edge = m_States[ni].m_Edges; while(edge) { backedge = edge; edge = edge->m_Next; delete backedge; m_EdgeNumber--; } memmove(m_States+ni,m_States+ni+1,sizeof(N3DState)*(m_Size-ni-1)); int* trans = new int[m_Size]; int i; for (i=0;i<m_Size;i++) { if(i<ni) trans[i]=i; else if(i==ni) trans[i]=-1; else trans[i]=i-1; } m_Size--; // now we iterate all the edges to decal the indices for(i=0;i<m_Size;i++) { edge=m_States[i].m_Edges; backedge = NULL; while(edge) { edge->m_Successor = trans[edge->m_Successor]; if(edge->m_Successor == -1) { if(backedge) { N3DEdge* temp = backedge->m_Next; backedge->m_Next = edge->m_Next; edge=edge->m_Next; delete temp; m_EdgeNumber--; } else { N3DEdge* temp = edge; m_States[i].m_Edges = edge->m_Next; edge = edge->m_Next; delete temp; m_EdgeNumber--; } } else { backedge = edge; edge=edge->m_Next; } } } delete [] trans; } void N3DGraph::DeleteEdge(CK3dEntity* s,CK3dEntity* e) { int si = SeekPosition(CKOBJID(s)); int ei = SeekPosition(CKOBJID(e)); N3DEdge* edge; N3DEdge* backedge; edge=m_States[si].m_Edges; backedge = NULL; while(edge) { if(edge->m_Successor == ei) { if(backedge) { N3DEdge* temp = backedge->m_Next; backedge->m_Next = edge->m_Next; edge=edge->m_Next; delete temp; m_EdgeNumber--; } else { N3DEdge* temp = edge; m_States[si].m_Edges = edge->m_Next; edge = edge->m_Next; delete temp; m_EdgeNumber--; } } else { backedge = edge; edge=edge->m_Next; } } } N3DEdge* N3DGraph::EdgeSeek(CK_ID s,CK_ID e) { int si = SeekPosition(s); int ei = SeekPosition(e); if(si < 0 || ei < 0) return NULL; N3DEdge* edge; edge=m_States[si].m_Edges; while(edge) { if(edge->m_Successor == ei) { return edge; } else { edge=edge->m_Next; } } return NULL; } N3DState* N3DGraph::StateSeek(CK_ID s) { for(int i=0;i<m_Size;i++) { if(m_States[i].m_Data == s) return m_States+i; } return NULL; } N3DEdge* N3DGraph::CreateEdge(int e,float d,float dist) { N3DEdge* edge = new N3DEdge; m_EdgeNumber++; edge->m_Active = STATEBASICACTIVITY|STATEDYNAMICACTIVITY; edge->m_Next = NULL; edge->m_Successor = e; edge->m_Difficulty = d; return edge; } N3DEdge* N3DGraph::GetSuccessorsList(int i) { return m_States[i].m_Edges; } int N3DGraph::SeekPosition(CK_ID e) const { for(int i=0;i<m_Size;i++) { if(m_States[i].m_Data == e) return i; } return -1; } N3DState* N3DGraph::GetState(int i) { return m_States+i; } typedef XList<N3DState*> nodelist; typedef XListIt<N3DState*> nodelistit; CK3dEntity* N3DGraph::FindPath(CK3dEntity* start,CK3dEntity* goal,CKGroup* path,BOOL basic,BOOL occupation) { DWORD activity; if(basic) activity = STATEBASICACTIVITY; else activity = STATEDYNAMICACTIVITY; nodelist open; VxVector a,b,c; N3DState* startnode = StateSeek(CKOBJID(start)); if(!startnode) return NULL; N3DState* goalnode = StateSeek(CKOBJID(goal)); if(!goalnode) return NULL; startnode->m_AStar.g = 0; startnode->m_AStar.h = GetDistance(startnode,goalnode); startnode->m_AStar.f = startnode->m_AStar.g + startnode->m_AStar.h; startnode->m_AStar.parent = NULL; PushOnOpen(open,startnode); while (open.Size()) { nodelistit first = open.Begin(); N3DState* n = *first; open.Remove(first); n->m_Flag &= ~LISTOPEN; if(n == goalnode) { CK3dEntity* nodetogo = NULL; if(path) { // we construct an entire path // parcourir n en remontant les parent et ajouter les m_Data au path while(n->m_AStar.parent && (n!=n->m_AStar.parent)) { path->AddObjectFront((CKBeObject*)m_Context->GetObject(n->m_Data)); n = n->m_AStar.parent; } nodetogo = (CK3dEntity*)path->GetObject(0); path->AddObjectFront((CKBeObject*)m_Context->GetObject(n->m_Data)); } else { // parcourir n en remontant les parent et ajouter les m_Data au path CK_ID idtogo=0; while(n->m_AStar.parent && (n!=n->m_AStar.parent)) { idtogo = n->m_Data; n = n->m_AStar.parent; } nodetogo = (CK3dEntity*)m_Context->GetObject(idtogo); } // now we must clear the flags for(int i=0;i<m_Size;i++) { m_States[i].m_Flag = 0; } // and then delete the list // maybe todo : clear // in any case, we return the first node to go return nodetogo; } N3DEdge* edge = n->m_Edges; N3DState* n_; float newg; while(edge) { if(edge->m_Active&activity) { n_ = m_States+edge->m_Successor; if(!occupation || !n_->m_Occupier) { // newg = n->m_AStar.g + GetDistance(n,n_); newg = n->m_AStar.g + edge->m_Difficulty*edge->m_Distance; if(n_->m_Flag) { if(n_->m_AStar.g <= newg) { edge = edge->m_Next; continue; } } n_->m_AStar.parent = n; n_->m_AStar.g = newg; n_->m_AStar.h = GetDistance(n_,goalnode); n_->m_AStar.f = n_->m_AStar.g + n_->m_AStar.h; // remove n' if present in closed n_->m_Flag &= ~LISTCLOSE; // add n_ in open if it is not yet in it if(!(n_->m_Flag&LISTOPEN)) { PushOnOpen(open,n_); } } } // get the next successor edge = edge->m_Next; } // closed->InsertRear(n); n->m_Flag |= LISTCLOSE; } // now we must clear the flags for(int i=0;i<m_Size;i++) { m_States[i].m_Flag = 0; } // we then delete the array return NULL; } void N3DGraph::PushOnOpen(nodelist& open,N3DState* n) { n->m_Flag |= LISTOPEN; nodelistit first = open.Begin(); nodelistit last = open.End(); while(first != last) { if(n->m_AStar.f < (*first)->m_AStar.f) { open.Insert(first,n); return; } first++; } open.Insert(first,n); } float N3DGraph::GetDistance(N3DState* n1,N3DState* n2) { return Magnitude(n1->m_Position-n2->m_Position); } CK3dEntity* N3DGraph::GetSafeEntity(N3DState* s) { CK3dEntity *ent = (CK3dEntity*)m_Context->GetObject(s->m_Data); if(!ent) { DeleteState(s->m_Data); } return ent; } void N3DGraph::CreateFromChunk(CKStateChunk* chunk) { chunk->StartRead(); if(!chunk->SeekIdentifier(N3DGRAPHSTART_IDENTIFIER)) return; int version = chunk->ReadInt(); if((version != N3DGRAPH_VERSION1)&&(version != N3DGRAPH_VERSION2)) return; m_Size = chunk->ReadInt(); delete[] m_States; if(m_Size) { m_States = new N3DState[m_Size]; m_AllocatedSize = m_Size; } else { // size = 0 m_States = new N3DState[1]; m_AllocatedSize = 1; } for(int i=0;i<m_Size;i++) { // state data m_States[i].m_Data = chunk->ReadObjectID(); if(version == N3DGRAPH_VERSION2) { m_States[i].m_Occupier = chunk->ReadObjectID(); } else m_States[i].m_Occupier = 0; // edges number int size = chunk->ReadInt(); N3DEdge* edge; N3DEdge* oldedge = NULL; N3DEdge* firstedge = NULL; for(int j=0;j<size;j++) { edge = CreateEdge(0,0,0.0f); if(!oldedge) { firstedge = edge; oldedge = edge; } else { oldedge->m_Next = edge; oldedge = edge; } edge->m_Active = chunk->ReadInt(); edge->m_Difficulty= chunk->ReadFloat(); edge->m_Successor = chunk->ReadInt(); } m_States[i].m_Edges = firstedge; } // We clean everything Clean(); // we calculate the distance UpdateDistance(); } void N3DGraph::Clean() { // we check if the nodes have themselves as successors = not permitted int i; for(i=0;i<m_Size;i++) { N3DEdge* edge = m_States[i].m_Edges; N3DEdge* backedge = NULL; while(edge) { if(edge->m_Successor == i) { // Self edge : achtung if(backedge) { N3DEdge* temp = backedge->m_Next; backedge->m_Next = edge->m_Next; edge=edge->m_Next; delete temp; m_EdgeNumber--; } else { N3DEdge* temp = edge; m_States[i].m_Edges = edge->m_Next; edge = edge->m_Next; delete temp; m_EdgeNumber--; } } else { backedge = edge; edge=edge->m_Next; } } } } void N3DGraph::SaveToChunk(CKStateChunk* chunk) { Clean(); chunk->StartWrite(); // start identifier chunk->WriteIdentifier(N3DGRAPHSTART_IDENTIFIER); // version chunk->WriteInt(N3DGRAPH_VERSION2); // size chunk->WriteInt(m_Size); // state size int i; for(i=0;i<m_Size;i++) { chunk->WriteObject(m_Context->GetObject(m_States[i].m_Data)); chunk->WriteObject(m_Context->GetObject(m_States[i].m_Occupier)); int count=0; N3DEdge* edge = m_States[i].m_Edges; while(edge) { edge=edge->m_Next; count++; } chunk->WriteInt(count); edge = m_States[i].m_Edges; while(edge) { chunk->WriteInt(edge->m_Active); chunk->WriteFloat(edge->m_Difficulty); chunk->WriteInt(edge->m_Successor); edge = edge->m_Next; } } // end identifier chunk->CloseChunk(); } void N3DGraph::UpdateDistance() { int i; for(i=0;i<m_Size;i++) { VxVector a; CK3dEntity* ent; ent = GetSafeEntity(m_States+i); if(ent) ent->GetPosition(&a); m_States[i].m_Position = a; } for(i=0;i<m_Size;i++) { N3DEdge* edge = m_States[i].m_Edges; while(edge) { edge->m_Distance = GetDistance(GetState(i),GetState(edge->m_Successor)); edge=edge->m_Next; } } } void GraphRender(CKRenderContext* rc, void *arg) { CKContext* m_Context=rc->GetCKContext(); VxDrawPrimitiveData* data = rc->GetDrawPrimitiveStructure(CKRST_DP_TR_CL_VC,3); CKWORD* indices = rc->GetDrawPrimitiveIndices(3); VxVector4* positions = (VxVector4*)data->Positions.Ptr; DWORD* colors = (DWORD*)data->Colors.Ptr; VxVector pos; VxVector nodepos,nodepos2; VxVector4 hompos; indices[0] = 0; indices[1] = 1; indices[2] = 2; VxVector v0(0,3,0); VxVector v1(3,-3,0); VxVector v2(-3,-3,0); int width = rc->GetWidth(); int height= rc->GetHeight(); colors[0] = RGBAFTOCOLOR(1.0f,1.0f,1.0f,1.0f); VxRect ScreenSize; rc->GetViewRect(ScreenSize); float WidthOn2=ScreenSize.GetWidth()*0.5f; float HeightOn2=ScreenSize.GetHeight()*0.5f; float DevX=ScreenSize.left+WidthOn2; float DevY=ScreenSize.top+HeightOn2; v0.x *=0.5f / WidthOn2; v1.x *=0.5f / WidthOn2; v2.x *=0.5f / WidthOn2; v0.y *=0.5f / HeightOn2; v1.y *=0.5f / HeightOn2; v2.y *=0.5f / HeightOn2; VxMatrix View = rc->GetViewTransformationMatrix(); VxMatrix Projection = rc->GetProjectionTransformationMatrix(); // A custom projection matrix to render homogenous coordinates rc->SetWorldTransformationMatrix(VxMatrix::Identity()); rc->SetViewTransformationMatrix(VxMatrix::Identity()); N3DGraph* graph = (N3DGraph*)arg; if(!graph) return; N3DDisplayStructure* display = graph->GetDisplay(); XVoidArray* extents = graph->GetExtentsList(); if(extents) { for (void** ptr=extents->Begin();ptr!=extents->End();++ptr) delete (N3DExtent*)*ptr; extents->Clear(); } N3DEdge* edge; N3DEdge* edgeend; N3DState* start; N3DState* end; CK3dEntity* startent; CK3dEntity* endent; int i; rc->SetTexture(NULL); rc->SetState(VXRENDERSTATE_ALPHATESTENABLE,FALSE); rc->SetState(VXRENDERSTATE_ZENABLE,TRUE); rc->SetState(VXRENDERSTATE_CULLMODE,VXCULL_NONE); rc->SetState(VXRENDERSTATE_ZWRITEENABLE,FALSE); rc->SetState(VXRENDERSTATE_ALPHABLENDENABLE,TRUE); rc->SetState(VXRENDERSTATE_SRCBLEND,VXBLEND_SRCALPHA); rc->SetState(VXRENDERSTATE_DESTBLEND,VXBLEND_INVSRCALPHA); for(i=0;i<graph->GetStatesNumber();i++) { start = graph->GetState(i); edge = start->m_Edges; startent = graph->GetSafeEntity(start); if(!startent) { continue; } startent->GetPosition(&pos); // Transform Pos to Node_Pos & Hom_pos (ClipFlags is 0 if the vertex is inside the view frustrum) Vx3DMultiplyMatrixVector(&nodepos,View,&pos); Vx3DMultiplyMatrixVector4(&hompos,Projection,&nodepos); BOOL Clipped = FALSE; if ((hompos.x<-hompos.w) || (hompos.x>hompos.w) || (hompos.y<-hompos.w) || (hompos.y>hompos.w) || (hompos.z<0) || (hompos.z>hompos.w)) { Clipped = TRUE; } // First we draw the node data->VertexCount=3; if( !Clipped) { // is the node in viewport // we can then add it to the Node Extents list if(extents) { N3DExtent* ext = new N3DExtent; VxVector4 screenpos = hompos; screenpos.w = 1.0f/screenpos.w; screenpos.x = (screenpos.x*screenpos.w*WidthOn2)+DevX; screenpos.y = -(screenpos.y*screenpos.w*HeightOn2)+DevY; ext->m_Node = start->m_Data; ext->m_Rect.left = (long)screenpos.x - 6; ext->m_Rect.right= (long)screenpos.x + 6; ext->m_Rect.top = (long)screenpos.y - 6; ext->m_Rect.bottom = (long)screenpos.y + 6; extents->PushBack((void *)ext); } if(display && ((start->m_Data == display->m_Node)||(start->m_Data == display->m_EndNode))) { // this node is the selected one or the ending one positions[0] = nodepos + 2 * v0 * nodepos.z; positions[1] = nodepos + 2 * v1 * nodepos.z; positions[2] = nodepos + 2 * v2 * nodepos.z; colors[0] = colors[1] = colors[2] = RGBAFTOCOLOR(1.0f ,0,1.0f,0.6f); } else { positions[0] = nodepos + v0 * nodepos.z; positions[1] = nodepos + v1 * nodepos.z; positions[2] = nodepos + v2 * nodepos.z; if(start->m_Occupier) { colors[0] = colors[1] = colors[2] = RGBAFTOCOLOR(1.0f,0.0f,0.0f,0.6f); } else { colors[0] = colors[1] = colors[2] = RGBAFTOCOLOR(0.3f,0.3f,1.0f,0.6f); } } // we actually draw it rc->DrawPrimitive(VX_TRIANGLELIST,indices,3,data); } // Next we draw the edges data->VertexCount=2; while(edge) { BOOL MustDraw = TRUE; end = graph->GetState(edge->m_Successor); edgeend = end->m_Edges; if(edge->m_Active&STATEDYNAMICACTIVITY) { colors[0]=RGBAFTOCOLOR(0,1.0f,0,0.6f); } else { colors[0]=RGBAFTOCOLOR(1.0f,0,0,0.6f); } colors[1]=RGBAFTOCOLOR(0,0,1.0f,0.6f); while(edgeend) { if(edgeend->m_Successor == i) { if(i > edge->m_Successor) MustDraw = FALSE; else { if(edge->m_Active&STATEDYNAMICACTIVITY) { colors[0]=RGBAFTOCOLOR(0,1.0f,0.0f,0.6f); } else { colors[0]=RGBAFTOCOLOR(1.0f,0,0,0.6f); } if(edgeend->m_Active&STATEDYNAMICACTIVITY) { colors[1]=RGBAFTOCOLOR(0,1.0f,0,0.6f); } else { colors[1]=RGBAFTOCOLOR(1.0f,0,0,0.6f); } } break; } edgeend = edgeend->m_Next; } if(MustDraw) { endent = graph->GetSafeEntity(end); if(!endent) return; endent->GetPosition(&pos); Vx3DMultiplyMatrixVector(&nodepos2,View,&pos); positions[0] = nodepos; positions[1] = nodepos2; rc->DrawPrimitive(VX_LINELIST,indices,2,data); } edge = edge->m_Next; } } // We now draw the path selected data->VertexCount=3; CKGroup* group = graph->GetPath(); if(group) { int count = group->GetObjectCount(); for(i=1;i<count;i++) { // we draw the line from the past one to the current one startent = (CK3dEntity*)group->GetObject(i-1); endent = (CK3dEntity*)group->GetObject(i); startent->GetPosition(&pos); Vx3DMultiplyMatrixVector(&nodepos,View,&pos); endent->GetPosition(&pos); Vx3DMultiplyMatrixVector(&nodepos2,View,&pos); positions[2] = nodepos2; VxVector d = Normalize(nodepos2 - nodepos); d.x *= nodepos.z * 0.5f / WidthOn2; d.y *= nodepos.z * 0.5f / HeightOn2; VxVector n(-d.y*3.0f ,d.x*3.0f,0); positions[0] = nodepos + n; positions[1] = nodepos - n; colors[0] = colors[1] = colors[2] = RGBAFTOCOLOR(1.0f,0.0f,1.0f,0.6f); // we actually draw it rc->DrawPrimitive(VX_TRIANGLELIST,indices,3,data); } } rc->SetViewTransformationMatrix(View); } <file_sep> #include "CKAll.h" #include "vtNetworkManager.h" #include "xNetTypes.h" #include "tnl.h" #include "tnlPlatform.h" #include "xNetInterface.h" #include "tnlGhostConnection.h" #include "vtConnection.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "IDistributedObjectsInterface.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xPredictionSetting.h" #include "vtGuids.h" #include "xNetConstants.h" #include "vtTools.h" void ParamOpBGetErrorString(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetErrorString(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int error; p1->GetValue(&error); if (error < 15) { res->SetStringValue(sErrorStrings[error]); } } void vtNetworkManager::RegisterParameters() { CKParameterManager *pm = m_Context->GetParameterManager(); CKAttributeManager* attman = m_Context->GetAttributeManager(); pm->RegisterNewEnum(VTE_NETWORK_ERROR,"Network Error","Ok=0,\ Intern=1,\ No connection=2,\ Not joined to a session=3,\ Session needs password=4,\ Session is locked=5,\ Session already exists=6,\ Session is full=7,\ You must be session master=8,\ Invalid parameter=9,\ There is not such user=10,\ Distributed class already exists=11,\ Couldn't connect to any server=12,\ You already joined to a session=13,\ No such session=14"); pm->RegisterOperationType(PARAM_OP_TYPE_GET_ERROR_TEXT, "GetString"); pm->RegisterOperationFunction(PARAM_OP_TYPE_GET_ERROR_TEXT,CKPGUID_STRING,VTE_NETWORK_ERROR,CKPGUID_NONE,ParamOpBGetErrorString); } <file_sep>#ifndef CKPhysicManager_H #define CKPhysicManager_H "$Id:$" #include "vtPhysXBase.h" #include "CKBaseManager.h" class MODULE_API CKPhysicManager :public CKBaseManager { public: #ifdef DOCJETDUMMY // Docjet secret macro #else virtual CKERROR OnCKInit()=0; virtual CKERROR PostClearAll()=0; virtual CKERROR PreSave()=0; virtual CKERROR OnCKReset()=0; virtual CKERROR PreProcess()=0; virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_PostClearAll| CKMANAGER_FUNC_OnCKInit| CKMANAGER_FUNC_PreSave| CKMANAGER_FUNC_PostLoad| CKMANAGER_FUNC_OnCKReset| CKMANAGER_FUNC_PreProcess; } virtual void _RegisterParameters()=0; virtual void _RegisterVSL()=0; CKPhysicManager(CKContext *Context,CKGUID guid,char* name); virtual ~CKPhysicManager() {} #endif // Docjet secret macro }; // CK2 VERSION ... #endif <file_sep>#include "StdAfx.h" #include "virtools/vtcxglobal.h" #include "vt_python_funcs.h" #include <iostream> #include "pyembed.h" #include "InitMan.h" using std::cout; #include <sstream> #include "vtTools.h" using namespace vtTools; CKObjectDeclaration *FillBehaviorCallPythonFuncDecl2(); CKERROR CreateCallPythonProto2(CKBehaviorPrototype **); int CallPythonFunc2(const CKBehaviorContext& behcontext); CKERROR CallPythonFuncCB2(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 3 #define BEH_OUT_MIN_COUNT 0 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorCallPythonFuncDecl2() { CKObjectDeclaration *od = CreateCKObjectDeclaration("CallPythonFuncEx"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x67251d33,0x402868fb)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateCallPythonProto2); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Python"); return od; } CKERROR CreateCallPythonProto2(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("CallPythonFuncEx"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); proto->DeclareInParameter("File",CKPGUID_STRING); proto->DeclareInParameter("Func",CKPGUID_STRING); proto->DeclareInParameter("Reload",CKPGUID_BOOL); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS|CKBEHAVIOR_VARIABLEPARAMETERINPUTS|CKBEHAVIOR_INTERNALLYCREATEDOUTPUTPARAMS|CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS|CKBEHAVIOR_VARIABLEOUTPUTS|CKBEHAVIOR_VARIABLEINPUTS)); proto->SetFunction( CallPythonFunc2 ); proto->SetBehaviorCallbackFct(CallPythonFuncCB2); *pproto = proto; return CK_OK; } int CallPythonFunc2(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; XString File((CKSTRING) beh->GetInputParameterReadDataPtr(0)); XString Func((CKSTRING) beh->GetInputParameterReadDataPtr(1)); int reload=false; //= BehaviorTools::GetInputParameterValue<bool>(beh,2); beh->GetInputParameterValue(2,&reload); vt_python_man *pm = (vt_python_man*)ctx->GetManagerByGuid(INIT_MAN_GUID); CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); Python *py = pm->py; if (!pm->pLoaded) { pm->m_Context->OutputToConsoleEx("You must load Python before !"); beh->ActivateOutput(1,false); return CKBR_BEHAVIORERROR; } ////////////////////////////////////////////////////////////////////////// if( beh->IsInputActive(0) ) { try { PyObject *module = pm->InsertPModule(beh->GetID(),File,reload); PyObject* val = PyInt_FromLong(beh->GetID()); PyObject_SetAttrString( module , "bid", val); pm->CallPyModule(beh->GetID(),Func); } catch (Python_exception ex) { pm->m_Context->OutputToConsoleEx("PyErr : \t %s",(CKSTRING)ex.what()); std::cout << ex.what() << "pyexeption in beh : " << beh->GetName(); PyErr_Clear(); beh->ActivateOutput(1,false); } beh->ActivateInput(0,false); } ////////////////////////////////////////////////////////////////////////// else { for (int i = 1 ; i < beh->GetOutputCount() ; i++ ) { try { PyObject *module = pm->GetPModule(beh->GetID()); if(module) pm->CallPyModule(beh->GetID(),Func); } catch (Python_exception ex) { pm->m_Context->OutputToConsoleEx("PyErr : \t %s",(CKSTRING)ex.what()); std::cout << ex.what() << "pyexeption in beh : " << beh->GetName(); beh->ActivateOutput(1,TRUE); return CKBR_BEHAVIORERROR; } beh->ActivateInput(i,false); } } return CKBR_OK; } ////////////////////////////////////////////////////////////////////////// CKERROR CallPythonFuncCB2(const CKBehaviorContext& behcontext) { /************************************************************************/ /* collecting data : */ /* */ CKBehavior *beh = behcontext.Behavior; CKContext* ctx = beh->GetCKContext(); CKParameterManager *pm = static_cast<CKParameterManager*>(ctx->GetParameterManager()); /************************************************************************/ /* process virtools callbacks : */ /* */ switch(behcontext.CallbackMessage) { case CKM_BEHAVIOREDITED: case CKM_BEHAVIORSETTINGSEDITED: { assert(beh && ctx); int p_count = beh->GetOutputParameterCount(); /*while( (BEH_OUT_MIN_COUNT ) < p_count ) { CKDestroyObject( beh->RemoveOutputParameter( --p_count) ); }*/ XString name("PyFuncX: "); name << ((CKSTRING) beh->GetInputParameterReadDataPtr(1)); if ( strlen(((CKSTRING) beh->GetInputParameterReadDataPtr(1))) ==0) { XString name("PyFileX: "); name << ((CKSTRING) beh->GetInputParameterReadDataPtr(0)); beh->SetName(name.Str()); break; } beh->SetName(name.Str()); break; } case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD : { XString name("PyFuncX: "); name << ((CKSTRING) beh->GetInputParameterReadDataPtr(1)); beh->SetName(name.Str()); if ( strlen(((CKSTRING) beh->GetInputParameterReadDataPtr(1))) ==0) { XString name("PyFileX: "); name << ((CKSTRING) beh->GetInputParameterReadDataPtr(0)); beh->SetName(name.Str()); break; } } } return CKBR_OK; }<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPJCreateDistanceJointDecl(); CKERROR CreatePJCreateDistanceJointProto(CKBehaviorPrototype **pproto); int PJCreateDistanceJoint(const CKBehaviorContext& behcontext); CKERROR PJCreateDistanceJointCB(const CKBehaviorContext& behcontext); enum bbInputs { bI_ObjectB, bI_Anchor0, bI_Anchor1, bI_Collision, bbI_Min, bbI_Max, bbI_Spring, }; //************************************ // Method: FillBehaviorPJCreateDistanceJointDecl // FullName: FillBehaviorPJCreateDistanceJointDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPJCreateDistanceJointDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJDistance"); od->SetCategory("Physic/Joints"); od->SetDescription("Sets a distance joint between two bodies."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x52ff6b14,0x474e4938)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJCreateDistanceJointProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJCreateDistanceJointProto // FullName: CreatePJCreateDistanceJointProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePJCreateDistanceJointProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJDistance"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJDistance <br> PJDistance is categorized in \ref Joints <br> <br>See <A HREF="PJDistance.cmo">PJDistance.cmo</A>. <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Creates or modifies a distance joint. <br> <br> DOFs removed: 1<br> DOFs remaining: 5<br> <br> \image html distanceJoint.png The distance joint tries to maintain a certain minimum and/or maximum distance between two points attached to a pair of actors. It can be set to springy in order to behave like a rubber band. An example for a distance joint is a pendulum swinging on a string, or in the case of a springy distance joint, a rubber band between two objects. <h3>Technical Information</h3> \image html PJDistance.png <SPAN CLASS="in">In :</SPAN>triggers the process <BR> <SPAN CLASS="out">Out :</SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Body B :</SPAN>The second body. Leave blank to create a joint constraint with the world. <BR> <BR> <SPAN CLASS="pin">Local Anchor 0 :</SPAN>A point in bodies a local space. See pJointDistance::setLocalAnchor0(). <BR> <BR> <SPAN CLASS="pin">Local Anchor 1 :</SPAN>A point in bodies a local space. See pJointDistance::setLocalAnchor1(). <BR> <BR> <SPAN CLASS="pin">Collision :</SPAN>Enable Collision. See pJointDistance::enableCollision(). <BR> <BR> <SPAN CLASS="pin">Minimum Distance :</SPAN>The minimum rest length of the rope or rod between the two anchor points.The value must be non-zero! See pJointDistance::setMinDistance(). <BR> <BR> <SPAN CLASS="pin">Maximum Distance :</SPAN>The maximum rest length of the rope or rod between the two anchor points. The value must be non-zero! See pJointDistance::setMaxDistance(). <BR> <BR> <SPAN CLASS="pin">Joint Spring: </SPAN>The spring to make it springy. The spring.targetValue field is not used. See pJointDistance::setSpring(). <BR> <BR> <SPAN CLASS="setting">Minimum Distance : </SPAN>Enables parameter input for minimum distance. <BR> <SPAN CLASS="setting">Maximum Distance : </SPAN>Enables parameter input for maximum distance. <BR> <SPAN CLASS="setting">Spring : </SPAN>Enables parameter input for the spring. <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>VSL : Creation </h3><br> <SPAN CLASS="NiceCode"> \include PJDistance.vsl </SPAN> <br> <h3>VSL : Modifiy </h3><br> <SPAN CLASS="NiceCode"> \include PJDistanceModify.vsl </SPAN> <br> <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createDistanceJoint().<br> */ proto->DeclareInput("In0"); proto->DeclareOutput("Out0"); proto->SetBehaviorCallbackFct( PJCreateDistanceJointCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Local Anchor 0",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Local Anchor 1",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Collision",CKPGUID_BOOL,"TRUE"); proto->DeclareInParameter("Minimum Distance",CKPGUID_FLOAT,"0.0f"); proto->DeclareInParameter("Maximum Distance",CKPGUID_FLOAT,"0.0f"); proto->DeclareInParameter("Joint Spring",VTS_JOINT_SPRING,"2.1,3.0,4.0"); proto->DeclareSetting("Minimum Distance",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Maximum Distance",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Spring",CKPGUID_BOOL,"TRUE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PJCreateDistanceJoint); *pproto = proto; return CK_OK; } //************************************ // Method: PJCreateDistanceJoint // FullName: PJCreateDistanceJoint // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJCreateDistanceJoint(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Distance)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); if(bodyA && bodyB) { //anchor : VxVector anchor0 = GetInputParameterValue<VxVector>(beh,bI_Anchor0); VxVector anchor1 = GetInputParameterValue<VxVector>(beh,bI_Anchor1); int coll = GetInputParameterValue<int>(beh,bI_Collision); float min= 0.0f; float max = 0.0f; DWORD minDistance; beh->GetLocalParameterValue(0,&minDistance); if (minDistance) { min = GetInputParameterValue<float>(beh,bbI_Min); } DWORD maxDistance; beh->GetLocalParameterValue(1,&maxDistance); if (maxDistance) { max = GetInputParameterValue<float>(beh,bbI_Max); } pSpring spring; DWORD hasspring; beh->GetLocalParameterValue(2,&hasspring); if (hasspring) { CKParameterIn *par = beh->GetInputParameter(bbI_Spring); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { spring = pFactory::Instance()->createSpringFromParameter(rPar); } } }else { spring.spring = 0.0f; spring.damper = 0.0f; spring.targetValue= 0.0f; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// pJointDistance *joint = static_cast<pJointDistance*>(worldA->getJoint(target,targetB,JT_Distance)); if (!joint) { joint = static_cast<pJointDistance*>(pFactory::Instance()->createDistanceJoint(target,targetB,anchor0,anchor1,min,max,spring)); } if (joint) { joint->setMinDistance(min); joint->setMaxDistance(max); joint->setLocalAnchor0(anchor0); joint->setLocalAnchor1(anchor1); joint->setSpring(spring); joint->enableCollision(coll); } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: PJCreateDistanceJointCB // FullName: PJCreateDistanceJointCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJCreateDistanceJointCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD minDistance; beh->GetLocalParameterValue(0,&minDistance); beh->EnableInputParameter(bbI_Min,minDistance); DWORD maxDistance; beh->GetLocalParameterValue(1,&maxDistance); beh->EnableInputParameter(bbI_Max,maxDistance); DWORD spring; beh->GetLocalParameterValue(2,&spring); beh->EnableInputParameter(bbI_Spring,spring); break; } } return CKBR_OK; } <file_sep>#include "InitMan.h" #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #include <iostream> #include <iomanip> #include <windows.h> #include <tchar.h> #include <process.h> #include "AutoLock.h" using namespace AutoLock; vtExternalEvent *Msg; HANDLE hmem = NULL; int post = 0; extern InitMan *_im; #pragma comment (lib,"ATLSD.LIB") HANDLE m_hLogItemSendEvent = ::CreateEvent(NULL,TRUE,FALSE,"LogItemSendEventName"); HANDLE m_hShutdownEvent = ::CreateEvent(NULL,FALSE,FALSE,"SendRcvShutdownEvent"); HANDLE m_hLogItemReceivedEvent = ::CreateEvent(NULL,FALSE,FALSE,"LogItemReceivedEventName"); HANDLE aHandles[] = { m_hShutdownEvent , m_hLogItemSendEvent }; BOOL vt_UnloadPlugin(CKGUID input); BOOL vt_ReloadPlugin(CKGUID input); BOOL recieved = false; BOOL changed = true; void InitMan::InitMessages(int flags,XString name) { m_Context->ActivateManager((CKBaseManager*) this,true); if( NULL != ( m_hMMFile = CreateFileMapping( INVALID_HANDLE_VALUE, NULL,PAGE_READWRITE,0, sizeof( vtExternalEvent ),"sharedMemFile" ) ))//_T("LogSndRcvMMF") ))) { if( NULL != (m_pData = (vtExternalEvent*)::MapViewOfFile(m_hMMFile, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, sizeof( vtExternalEvent* )) ) ) { // return S_OK; } } //return HRESULT_FROM_WIN32( ::GetLastError( ) ); } CKERROR InitMan::PostProcess() { if (!changed){ SetEvent( m_hShutdownEvent ); } return CK_OK; } void InitMan::PerformMessages() { // m_Context->OutputToConsole("performe"); HRESULT hr = S_OK; USES_CONVERSION; switch( ::WaitForMultipleObjects(sizeof(aHandles) /sizeof(HANDLE),&(aHandles[0]),FALSE,1)) { case WAIT_OBJECT_0: { SetEvent( m_hShutdownEvent ); break; } case WAIT_OBJECT_0 + 1: { try { CLockableMutex m_mtxMMFile("sharedMem"); CAutoLockT< CLockableMutex > lock(&m_mtxMMFile, 5000 ); vtExternalEvent *pLI = reinterpret_cast<vtExternalEvent*>(m_pData); if (pLI) { m_Context->OutputToConsole("vtPluginProxy : msg recieved",FALSE); XString command(pLI->command); m_Context->OutputToConsoleEx(command.Str()); XString commandArg(pLI->commandArg); if (!command.Compare("unload")) { /*vtGUID inputGuid; inputGuid.FromString(commandArg); m_Context->OutputToConsole("vtPluginProxy : Unload Plugin",FALSE); vt_UnloadPlugin(inputGuid.GetVirtoolsGUID());*/ } if (!command.Compare("reload")) { /*vtGUID inputGuid; inputGuid.FromString( commandArg ); m_Context->OutputToConsole("vtPluginProxy : Reload Plugin",FALSE); vt_ReloadPlugin(inputGuid.GetVirtoolsGUID());*/ } changed = true; SetEvent( m_hLogItemReceivedEvent ); ::ResetEvent(m_hShutdownEvent); } return ; } catch( CAutoLockTimeoutExc ) { hr = HRESULT_FROM_WIN32( WAIT_TIMEOUT ); } catch( CAutoLockWaitExc& e ) { hr = HRESULT_FROM_WIN32( e.GetLastError() ); } break; } default: int op=0; // ATLASSERT(0); } } <file_sep>/******************************************************************** created: 2009/01/05 created: 5:1:2009 18:18 filename: x:\ProjectRoot\svn\local\vtTools\SDK\Include\Core\vtCModuleDefines.h file path: x:\ProjectRoot\svn\local\vtTools\SDK\Include\Core file base: vtCModuleDefines file ext: h author: purpose: *********************************************************************/ #ifndef __VTCMODULES_DEFINES_H_ #define __VTCMODULES_DEFINES_H_ #include <vtCXGlobal.h> #define VTCMODULE_NAME VTCX_API_PREFIX("TOOLS") #define VTCMODULE_ATTRIBUTE_CATAEGORY VTCMODULE_NAME #define VTM_TOOL_MANAGER_GUID CKGUID(0x7a9a6475,0x6fb90c74) #define VTBB_PLG_GUID CKGUID(0x3262afb,0x230b4434) #endif <file_sep>#include "StdAfx.h" #include "vtPhysXAll.h" #include "IParameter.h" #include "vtStructHelper.h" static IParameter* gIPar = NULL; #include "pMisc.h" #include "pVehicleAll.h" using namespace vtTools::ParameterTools; int IParameter::copyTo(pLinearInterpolation& dst,CKParameter*src) { if (!src) return false; int gear = 0; float ratio = 0.0f; CKStructHelper sHelper(src); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; for (int i = 0 ; i < sHelper.GetMemberCount() ; i++) { CK_ID* paramids = static_cast<CK_ID*>(src->GetReadDataPtr()); CKParameter * sub = static_cast<CKParameterOut*>(GetPMan()->m_Context->GetObject(paramids[i])); if (sub) { dst.insert(GetValueFromParameterStruct<float>(sub,0,false), GetValueFromParameterStruct<float>(sub,1,false) ); } } return true; } int IParameter::copyTo(pGearBox *dst,CKParameter*src) { if (!src || !dst) return false; int gear = 0; float ratio = 0.0f; for (int i = 0 ; i < 7 ; i++) { CK_ID* paramids = static_cast<CK_ID*>(src->GetReadDataPtr()); CKParameter * sub = static_cast<CKParameterOut*>(GetPMan()->m_Context->GetObject(paramids[i])); if (sub) { dst->gearRatio[i] = GetValueFromParameterStruct<float>(sub,0,false); dst->gearInertia[i] = GetValueFromParameterStruct<float>(sub,1,false); dst->getGearRatios().insert((float)i,dst->gearRatio[i]); dst->getGearTensors().insert((float)i,dst->gearInertia[i]); } } return true; } int IParameter::copyTo(pVehicleBrakeTable& dst,CKParameter*src) { int result = 0; for (int i = 0 ; i < BREAK_TABLE_ENTRIES ; i ++) dst.brakeEntries[i] = GetValueFromParameterStruct<float>(src,i); return true; } int IParameter::copyTo(CKParameter*dst,pWheelDescr src) { if (!dst)return false; using namespace vtTools::ParameterTools; int result = 0; SetParameterStructureValue<float>(dst,E_WD_SPRING_BIAS,src.springBias,false); SetParameterStructureValue<float>(dst,E_WD_SPRING_RES,src.springRestitution,false); SetParameterStructureValue<float>(dst,E_WD_DAMP,src.springDamping,false); SetParameterStructureValue<float>(dst,E_WD_MAX_BFORCE,src.maxBrakeForce,false); SetParameterStructureValue<float>(dst,E_WD_FFRONT,src.frictionToFront,false); SetParameterStructureValue<float>(dst,E_WD_FSIDE,src.frictionToSide,false); SetParameterStructureValue<int>(dst,E_WD_FLAGS,src.wheelFlags,false); SetParameterStructureValue<float>(dst,E_WD_INVERSE_WHEEL_MASS,src.inverseWheelMass,false); SetParameterStructureValue<int>(dst,E_WD_SFLAGS,src.wheelShapeFlags,false); SetParameterStructureValue<float>(dst,E_WD_SUSPENSION,src.wheelSuspension,false); } int IParameter::copyTo(pWheelDescr& dst,CKParameter*src) { int result = 1; if (!src) { return NULL; } using namespace vtTools::ParameterTools; dst.wheelSuspension = GetValueFromParameterStruct<float>(src,E_WD_SUSPENSION); dst.springRestitution= GetValueFromParameterStruct<float>(src,E_WD_SPRING_RES); dst.springBias = GetValueFromParameterStruct<float>(src,E_WD_SPRING_BIAS); dst.springDamping= GetValueFromParameterStruct<float>(src,E_WD_DAMP); dst.maxBrakeForce= GetValueFromParameterStruct<float>(src,E_WD_MAX_BFORCE); dst.frictionToSide= GetValueFromParameterStruct<float>(src,E_WD_FSIDE); dst.frictionToFront= GetValueFromParameterStruct<float>(src,E_WD_FFRONT); CKParameterOut *pOld = GetParameterFromStruct(src,E_WD_INVERSE_WHEEL_MASS); if (pOld) { if (pOld->GetGUID() == CKPGUID_FLOAT) { dst.inverseWheelMass= GetValueFromParameterStruct<float>(src,E_WD_INVERSE_WHEEL_MASS); } if (pOld->GetGUID() == CKPGUID_INT) { dst.wheelApproximation= GetValueFromParameterStruct<int>(src,E_WD_INVERSE_WHEEL_MASS); } } dst.wheelFlags= (WheelFlags)GetValueFromParameterStruct<int>(src,E_WD_FLAGS); dst.wheelShapeFlags=(WheelShapeFlags) GetValueFromParameterStruct<int>(src,E_WD_SFLAGS); CKParameterOut *parLatFunc = GetParameterFromStruct(src,E_WD_LAT_FUNC); CKParameterOut *parLongFunc = GetParameterFromStruct(src,E_WD_LONG_FUNC); /************************************************************************/ /* XML Setup ? */ /************************************************************************/ int xmlLinkId= GetValueFromParameterStruct<int>(src,E_WD_XML); bool wIsXML=false; bool latIsXML= false; bool longIsXML=false; XString nodeName; if ( xmlLinkId !=0 ) { nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_WHEEL_SETTINGS,xmlLinkId); pFactory::Instance()->loadWheelDescrFromXML(dst,nodeName.CStr(),pFactory::Instance()->getDefaultDocument()); wIsXML =true; if (!dst.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Wheel Description was invalid"); } if (dst.latFunc.xmlLink!=0) { latIsXML=true; } if (dst.longFunc.xmlLink!=0) { longIsXML=true; } } if (!latIsXML) { dst.latFunc = pFactory::Instance()->createTireFuncFromParameter(parLatFunc); } if (!longIsXML) { dst.longFunc= pFactory::Instance()->createTireFuncFromParameter(parLongFunc); } if (wIsXML) { IParameter::Instance()->copyTo((CKParameterOut*)src,dst); } if (longIsXML) { pFactory::Instance()->copyTo(GetParameterFromStruct(src,E_WD_LONG_FUNC),dst.longFunc); } if (latIsXML) { pFactory::Instance()->copyTo(GetParameterFromStruct(src,E_WD_LAT_FUNC),dst.latFunc); } return result; } int IParameter::copyTo(pConvexCylinderSettings& dst,CKParameter*src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(src); #endif using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; copyTo(dst.radius, GetParameterFromStruct(src,PS_CC_RADIUS_REFERENCED_VALUE),true); copyTo(dst.height, GetParameterFromStruct(src,PS_CC_HEIGHT_REFERENCED_VALUE),true); dst.approximation = GetValueFromParameterStruct<int>(src,PS_CC_APPROXIMATION); dst.buildLowerHalfOnly = GetValueFromParameterStruct<int>(src,PS_CC_BUILD_LOWER_HALF_ONLY); dst.convexFlags = (pConvexFlags)GetValueFromParameterStruct<int>(src,PS_CC_EXTRA_SHAPE_FLAGS); //---------------------------------------------------------------- // // Calculate Forward Axis, optionally referenced by an entity // dst.forwardAxis = GetValueFromParameterStruct<VxVector>(src,PS_CC_FORWARD_AXIS); dst.forwardAxisRef = GetValueFromParameterStruct<CK_ID>(src,PS_CC_FORWARD_AXIS_REF); CK3dEntity *f = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.forwardAxisRef); if (f) { VxVector dir,up,right; f->GetOrientation(&dir,&up,&right); f->TransformVector(&dst.forwardAxis,&dir); dst.forwardAxis.Normalize(); } //---------------------------------------------------------------- // // Calculate Down Axis, optionally referenced by an entity // dst.downAxis = GetValueFromParameterStruct<VxVector>(src,PS_CC_DOWN_AXIS); dst.downAxisRef = GetValueFromParameterStruct<CK_ID>(src,PS_CC_DOWN_AXIS_REF); CK3dEntity *d = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.downAxisRef); if (d) { VxVector dir,up,right; d->GetOrientation(&dir,&up,&right); d->TransformVector(&dst.downAxis,&up); dst.downAxis.Normalize(); } //---------------------------------------------------------------- // // Calculate Right Axis, optionally referenced by an entity // dst.rightAxis = GetValueFromParameterStruct<VxVector>(src,PS_CC_RIGHT_AXIS); dst.rightAxisRef = GetValueFromParameterStruct<CK_ID>(src,PS_CC_RIGHT_AXIS_REF); CK3dEntity *r = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.rightAxisRef); if (r) { VxVector dir,up,right; r->GetOrientation(&dir,&up,&right); r->TransformVector(&dst.rightAxis,&right); dst.rightAxis.Normalize(); } return 1; } int IParameter::copyTo(CKParameter*dst,pConvexCylinderSettings& src) { copyTo(src.radius, GetParameterFromStruct(dst,PS_CC_RADIUS_REFERENCED_VALUE),true); copyTo(src.height, GetParameterFromStruct(dst,PS_CC_HEIGHT_REFERENCED_VALUE),true); SetParameterStructureValue<int>(dst,PS_CC_APPROXIMATION,src.approximation,false); SetParameterStructureValue<int>(dst,PS_CC_BUILD_LOWER_HALF_ONLY,src.buildLowerHalfOnly,false); SetParameterStructureValue<int>(dst,PS_CC_EXTRA_SHAPE_FLAGS,src.convexFlags,false); SetParameterStructureValue<VxVector>(dst,PS_CC_FORWARD_AXIS,src.forwardAxis,false); SetParameterStructureValue<VxVector>(dst,PS_CC_DOWN_AXIS,src.downAxis,false); SetParameterStructureValue<VxVector>(dst,PS_CC_RIGHT_AXIS,src.rightAxis,false); CK3dEntity *f = (CK3dEntity*)GetPMan()->m_Context->GetObject(src.forwardAxisRef); if (f) SetParameterStructureValue<CK_ID>(dst,PS_CC_FORWARD_AXIS_REF,f->GetID(),false); CK3dEntity *d = (CK3dEntity*)GetPMan()->m_Context->GetObject(src.downAxisRef); if (d) SetParameterStructureValue<CK_ID>(dst,PS_CC_DOWN_AXIS_REF,d->GetID(),false); CK3dEntity *r = (CK3dEntity*)GetPMan()->m_Context->GetObject(src.rightAxisRef); if (r) SetParameterStructureValue<CK_ID>(dst,PS_CC_RIGHT_AXIS_REF,r->GetID(),false); return 1; } int IParameter::copyTo(pMassSettings& dst,CKParameter*src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(src); #endif using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; dst.newDensity= GetValueFromParameterStruct<float>(src,PS_BM_DENSITY,false); dst.totalMass= GetValueFromParameterStruct<float>(src,PS_BM_TOTAL_MASS,false); dst.localPosition = GetValueFromParameterStruct<VxVector>(src,PS_BM_PIVOT_POS,false); dst.localOrientation = GetValueFromParameterStruct<VxVector>(src,PS_BM_PIVOT_ROTATION,false); dst.massReference= GetValueFromParameterStruct<CK_ID>(src,PS_BM_PIVOT_REFERENCE,false); return 1; } int IParameter::copyTo(CKParameter*dst,pMassSettings src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(dst); #endif using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; SetParameterStructureValue<float>(dst,PS_BM_DENSITY,src.newDensity,false); SetParameterStructureValue<float>(dst,PS_BM_TOTAL_MASS,src.totalMass,false); SetParameterStructureValue<VxVector>(dst,PS_BM_PIVOT_POS,src.localPosition,false); SetParameterStructureValue<VxVector>(dst,PS_BM_PIVOT_ROTATION,src.localOrientation,false); SetParameterStructureValue<CK_ID>(dst,PS_BM_PIVOT_REFERENCE,src.massReference,false); return 1; } int IParameter::copyTo(CKParameter*dst,pPivotSettings src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(dst); #endif using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; SetParameterStructureValue<VxVector>(dst,PS_BP_LINEAR,src.localPosition,false); SetParameterStructureValue<VxVector>(dst,PS_BP_ANGULAR,src.localOrientation,false); SetParameterStructureValue<CK_ID>(dst,PS_BP_REFERENCE,src.pivotReference,false); /* dst.localPosition = GetValueFromParameterStruct<VxVector>(src,PS_BP_LINEAR,false); dst.localOrientation = GetValueFromParameterStruct<VxVector>(src,PS_BP_ANGULAR,false); dst.pivotReference = GetValueFromParameterStruct<CK_ID>(src,PS_BP_REFERENCE,false); */ return 1; } int IParameter::copyTo(pPivotSettings& dst,CKParameter*src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(src); #endif using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; dst.localPosition = GetValueFromParameterStruct<VxVector>(src,PS_BP_LINEAR,false); dst.localOrientation = GetValueFromParameterStruct<VxVector>(src,PS_BP_ANGULAR,false); dst.pivotReference = GetValueFromParameterStruct<CK_ID>(src,PS_BP_REFERENCE,false); return 1; } int IParameter::copyTo(pObjectDescr&dst,CK3dEntity*src,int copyFlags) { pRigidBody *srcBody = GetPMan()->getBody(src); NxActor *actor = NULL; pObjectDescr*initDescr = NULL; NxShape *mainShape= NULL; //---------------------------------------------------------------- // // sanity checks // if (!src || !srcBody || !srcBody->getMainShape()) return 0; initDescr = srcBody->getInitialDescription(); actor = srcBody->getActor(); mainShape = srcBody->getMainShape(); if (!initDescr || !actor ) return 0; //---------------------------------------------------------------- // // general settings // dst.hullType = (HullType)vtAgeia::getHullTypeFromShape(srcBody->getMainShape()); srcBody->recalculateFlags(0); dst.flags = (BodyFlags)srcBody->getFlags(); dst.worlReference = srcBody->getWorld()->getReference()->GetID(); dst.density = initDescr->density; dst.mask = initDescr->mask; //---------------------------------------------------------------- // // specific override : optimization // if ( (copyFlags & PB_CF_OPTIMIZATION) ) { //---------------------------------------------------------------- // // damping + sleeping // dst.optimization.angDamping = actor->getAngularDamping(); dst.optimization.linDamping = actor->getLinearDamping(); dst.optimization.linSleepVelocity = actor->getSleepLinearVelocity(); dst.optimization.angSleepVelocity = actor->getSleepAngularVelocity(); dst.optimization.sleepEnergyThreshold = actor->getSleepEnergyThreshold(); //---------------------------------------------------------------- // // transformation flags // dst.optimization.transformationFlags = (BodyLockFlags)srcBody->getTransformationsLockFlags(); dst.optimization.solverIterations = actor->getSolverIterationCount(); dst.optimization.dominanceGroup = actor->getDominanceGroup(); dst.optimization.compartmentGroup = initDescr->optimization.compartmentGroup; } //---------------------------------------------------------------- // // specific override : collision // //if ( (dst.mask & OD_Optimization ) ) if ( (copyFlags & PB_CF_COLLISION ) ) { dst.collisionGroup = mainShape->getGroup(); NxGroupsMask nxMask = mainShape->getGroupsMask(); dst.groupsMask.bits0 = nxMask.bits0; dst.groupsMask.bits1 = nxMask.bits1; dst.groupsMask.bits2 = nxMask.bits2; dst.groupsMask.bits3 = nxMask.bits3; dst.skinWidth = mainShape->getSkinWidth(); } //---------------------------------------------------------------- // // specific override : ccd // //if ( (dst.mask & OD_CCD) ) if ( (copyFlags & OD_CCD ) && (dst.mask & OD_CCD) ) { dst.ccd.flags = initDescr->ccd.flags; dst.ccd.meshReference = initDescr->ccd.meshReference; dst.ccd.motionThresold = initDescr->ccd.motionThresold; dst.ccd.scale = initDescr->ccd.scale; } //---------------------------------------------------------------- // // specific override : capsule // if ( (copyFlags && OD_Capsule) && (dst.mask & OD_Capsule) ) dst.capsule = initDescr->capsule; //---------------------------------------------------------------- // // specific override : convex cylinder // if ( (copyFlags && OD_ConvexCylinder) && (dst.mask & OD_ConvexCylinder) ) dst.convexCylinder = initDescr->convexCylinder; //---------------------------------------------------------------- // // specific override : material // if ( (copyFlags && OD_Material) && (dst.mask & OD_Material) ) dst.material = initDescr->material; //---------------------------------------------------------------- // // specific override : pivot // if ( (copyFlags && OD_Pivot) ) { //dst.pivotOffsetAngular = getFrom(mainShape->getLocalOrientation() ); dst.pivotOffsetLinear = getFrom( mainShape->getLocalPosition() ); //dst.pivotOffsetReference= initDescr->pivotOffsetReference; } if ( (copyFlags && PB_CF_MASS_SETTINGS) ) { //dst.pivotOffsetAngular = getFrom(mainShape->getLocalOrientation() ); dst.massOffsetLinear = getFrom(actor->getCMassLocalPosition()); //dst.pivotOffsetReference= initDescr->pivotOffsetReference; } //---------------------------------------------------------------- // // correct data mask : // DWORD mask = (DWORD)(dst.mask); mask &=~((OD_Pivot)); if ( !(copyFlags & PB_CF_PIVOT_SETTINGS) ) mask &=~((OD_Pivot)); if ( !(copyFlags & PB_CF_MASS_SETTINGS) ) mask &=~(OD_Mass); if ( !(copyFlags & PB_CF_OPTIMIZATION) ) mask &=~(OD_Optimization); if ( !(copyFlags & PB_CF_COLLISION) ) mask &=~(OD_Collision); if ( !(copyFlags & PB_CF_CCD) ) mask &=~(OD_CCD); if ( !(copyFlags & PB_CF_CAPSULE) ) mask &=~(OD_Capsule); if ( !(copyFlags & PB_CF_CONVEX_CYLINDER) ) mask&=~(OD_ConvexCylinder); if ( !(copyFlags & PB_CF_MATERIAL) ) mask &=~(OD_Material); return 1; } int IParameter::copyTo(pAxisReferencedLength&dst,CKParameter*src,bool evaluate) { #ifdef _DEBUG assert(src); #endif using namespace vtTools::ParameterTools; //################################################################ // // Retrieve the value : // dst.value = GetValueFromParameterStruct<float>(src,PS_ARL_VALUE); dst.referenceAxis = GetValueFromParameterStruct<int>(src,PS_ARL_REF_OBJECT_AXIS); //################################################################ // // Calculate the value basing on the given objects local box and an axis. // CK_ID idRef= GetValueFromParameterStruct<CK_ID>(src,PS_ARL_REF_OBJECT); CKBeObject *object = (CKBeObject*)GetPMan()->GetContext()->GetObject(idRef); if (!object) return -1; dst.reference = object; if (!evaluate)return -1; VxVector size(0.0f); if (object->GetClassID() == CKCID_3DOBJECT ) { CK3dEntity *ent3D = (CK3dEntity*)object; if (ent3D) { size = ent3D->GetBoundingBox(true).GetSize(); } }else if(object->GetClassID() == CKCID_MESH) { CKMesh *mesh = (CKMesh*)object; if (mesh) { size = mesh->GetLocalBox().GetSize(); } } dst.value = size[dst.referenceAxis]; return 1; } int IParameter::copyTo(CKParameter *dst, pAxisReferencedLength &src, bool evaluate) { SetParameterStructureValue<float>(dst,PS_ARL_VALUE,src.value,false); SetParameterStructureValue<int>(dst,PS_ARL_REF_OBJECT_AXIS,src.referenceAxis,false); if (src.reference) { SetParameterStructureValue<CK_ID>(dst,PS_ARL_REF_OBJECT,src.reference->GetID(),false); } return 1; } int IParameter::copyTo(pCapsuleSettingsEx& dst,CKParameter*src) { //SetParameterStructureValue<float>(dst,PS_BM_DENSITY,src.newDensity,false); //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(src); #endif using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; pFactory::Instance()->copyTo(dst.radius, GetParameterFromStruct(src,PS_BCAPSULE_RADIUS_REFERENCED_VALUE),false); pFactory::Instance()->copyTo(dst.height, GetParameterFromStruct(src,PS_PCAPSULE_HEIGHT_REFERENCED_VALUE),false); return 1; } int IParameter::copyTo(CKParameter*dst,pCapsuleSettingsEx src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(dst); #endif using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; copyTo(GetParameterFromStruct(dst,PS_BCAPSULE_RADIUS_REFERENCED_VALUE),src.radius,false); copyTo(GetParameterFromStruct(dst,PS_PCAPSULE_HEIGHT_REFERENCED_VALUE),src.height,false); return 1; } int IParameter::copyTo(pCCDSettings& dst,CKParameter*src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(src); #endif using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; //---------------------------------------------------------------- // // general // dst.flags = GetValueFromParameterStruct<int>(src,PS_B_CCD_FLAGS,false); dst.motionThresold = GetValueFromParameterStruct<float>(src,PS_B_CCD_MOTION_THRESHOLD,false); dst.scale= GetValueFromParameterStruct<float>(src,PS_B_CCD_SCALE,false); dst.meshReference= GetValueFromParameterStruct<CK_ID>(src,PS_B_CCD_MESH_REFERENCE,false); return 1; } int IParameter::copyTo(pOptimization& dst,CKParameter*src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(src); #endif using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; //---------------------------------------------------------------- // // Retrieve all sub parameters : // CKParameterOut *parSleeping = GetParameterFromStruct(src,PS_BO_SLEEPING); CKParameterOut *parDamping = GetParameterFromStruct(src,PS_BO_DAMPING); //---------------------------------------------------------------- // // general // dst.transformationFlags = (BodyLockFlags) GetValueFromParameterStruct<int>(src,PS_BO_LOCKS,false); dst.solverIterations = GetValueFromParameterStruct<int>(src,PS_BO_SOLVER_ITERATIONS,false); dst.compartmentGroup = GetValueFromParameterStruct<int>(src,PS_BO_COMPARTMENT_ID,false); dst.dominanceGroup = GetValueFromParameterStruct<int>(src,PS_BO_DOMINANCE_GROUP,false); //---------------------------------------------------------------- // // Sleeping // dst.angSleepVelocity = GetValueFromParameterStruct<float>(parSleeping,PS_BS_ANGULAR_SLEEP,false); dst.linSleepVelocity = GetValueFromParameterStruct<float>(parSleeping,PS_BS_LINEAR_SLEEP,false); dst.sleepEnergyThreshold = GetValueFromParameterStruct<float>(parSleeping,PS_BS_THRESHOLD,false); //---------------------------------------------------------------- // // Damping // dst.angDamping = GetValueFromParameterStruct<float>(parDamping,PS_BD_ANGULAR,false); dst.linDamping= GetValueFromParameterStruct<float>(parDamping,PS_BD_LINEAR,false); return 1; } int IParameter::copyTo(CKParameter*dst,pObjectDescr*src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(dst); assert(src); #endif using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; //---------------------------------------------------------------- // // Retrieve all sub parameters : // CKParameterOut *parBCommon = GetParameterFromStruct(dst,PS_COMMON_SETTINGS); CKParameterOut *parBCollision = GetParameterFromStruct(dst,PS_COLLISION_SETTINGS); //CKParameterOut *parBCCD = GetParameterFromStruct(parBCollision,PS_BC_CCD_SETUP); CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); #ifdef _DEBUG assert(parBCommon); //assert(parBPivot); //assert(parBCCD); assert(parBCollision); #endif ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // transfer // //---------------------------------------------------------------- // // common // SetParameterStructureValue<int>(parBCommon,PS_BC_HULL_TYPE,src->hullType); SetParameterStructureValue<float>(parBCommon,PS_BC_DENSITY,src->density); SetParameterStructureValue<int>(parBCommon,PS_BC_FLAGS,src->flags); SetParameterStructureValue<CK_ID>(parBCommon,PS_BC_WORLD,src->worlReference); //---------------------------------------------------------------- // // XML // //---------------------------------------------------------------- // // Collision // SetParameterStructureValue<int>(parBCollision,PS_BC_GROUP,src->collisionGroup); SetParameterStructureValue<float>(parBCollision,PS_BC_SKINWITDH,src->skinWidth); SetParameterStructureValue<int>(parGroupsMask,0,src->groupsMask.bits0); SetParameterStructureValue<int>(parGroupsMask,1,src->groupsMask.bits1); SetParameterStructureValue<int>(parGroupsMask,2,src->groupsMask.bits2); SetParameterStructureValue<int>(parGroupsMask,3,src->groupsMask.bits3); //---------------------------------------------------------------- // // CCD // /* SetParameterStructureValue<float>(parBCCD,PS_B_CCD_MOTION_THRESHOLD,src->ccdMotionThresold); SetParameterStructureValue<int>(parBCCD,PS_B_CCD_FLAGS,src->ccdFlags); SetParameterStructureValue<int>(parBCCD,PS_B_CCD_MESH_REFERENCE,src->ccdMeshReference); SetParameterStructureValue<float>(parBCCD,PS_B_CCD_SCALE,src->ccdScale); */ return 1; } int IParameter::copyTo(pCollisionSettings &dst,CKParameter*src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(src); #endif using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; CKParameterOut *parGroupsMask = GetParameterFromStruct(src,PS_BC_GROUPSMASK); // Sanity checks #ifdef _DEBUG assert(parGroupsMask); #endif //---------------------------------------------------------------- // // Collision Setup // dst.collisionGroup = GetValueFromParameterStruct<int>(src,PS_BC_GROUP,false); // dst.groupsMask.bits0 = GetValueFromParameterStruct<int>(parGroupsMask,0); dst.groupsMask.bits1 = GetValueFromParameterStruct<int>(parGroupsMask,1); dst.groupsMask.bits2 = GetValueFromParameterStruct<int>(parGroupsMask,2); dst.groupsMask.bits3 = GetValueFromParameterStruct<int>(parGroupsMask,3); dst.skinWidth = GetValueFromParameterStruct<float>(src,PS_BC_SKINWITDH,false); return 1; } int IParameter::copyTo(pObjectDescr*dst,CKParameter*src) { //---------------------------------------------------------------- // // Sanity checks // #ifdef _DEBUG assert(dst); assert(src); #endif //---------------------------------------------------------------- // // Possible this function is invoked due the loading of a cmo file whilst core is not started yet : // CKStructHelper sHelper(src); if(sHelper.GetMemberCount() == 0) return 0; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; //---------------------------------------------------------------- // // Retrieve all sub parameters : // CKParameterOut *parBCommon = GetParameterFromStruct(src,PS_COMMON_SETTINGS); //CKParameterOut *parBPivot = GetParameterFromStruct(src,PS_PIVOT); //CKParameterOut *parBMass = GetParameterFromStruct(src,PS_MASS); CKParameterOut *parBCollision = GetParameterFromStruct(src,PS_COLLISION_SETTINGS); //CKParameterOut *parBCCD = GetParameterFromStruct(parBCollision,PS_BC_CCD_SETUP); CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); #ifdef _DEBUG assert(parBCommon); //assert(parBPivot); //assert(parBMass); assert(parBCollision); #endif //---------------------------------------------------------------- // // Common settings as hull type, body flags, ... // dst->hullType =(HullType)GetValueFromParameterStruct<int>(parBCommon,PS_BC_HULL_TYPE,false); dst->flags = (BodyFlags)GetValueFromParameterStruct<int>(parBCommon,PS_BC_FLAGS,false); /*dst->transformationFlags = GetValueFromParameterStruct<int>(parBCommon,PS_BC_TFLAGS,false);*/ dst->worlReference = GetValueFromParameterStruct<CK_ID>(parBCommon,PS_BC_WORLD,false); dst->density = GetValueFromParameterStruct<float>(parBCommon,PS_BC_DENSITY,false); //---------------------------------------------------------------- // // Pivot Offset // /* dst->pivotOffsetLinear = GetValueFromParameterStruct<VxVector>(parBPivot,PS_BP_LINEAR,false); dst->pivotOffsetAngular = GetValueFromParameterStruct<VxVector>(parBPivot,PS_BP_ANGULAR,false); //---------------------------------------------------------------- // // Mass Offset // dst->density = GetValueFromParameterStruct<float>(parBMass,PS_BM_DENSITY,false); dst->totalMass = GetValueFromParameterStruct<float>(parBMass,PS_BM_TOTAL_MASS,false); dst->massOffsetLinear = GetValueFromParameterStruct<VxVector>(parBMass,PS_BM_PIVOT_POS,false); */ //dst->massOffsetAngular = GetValueFromParameterStruct<VxVector>(parBMass,PS_BM_PIVOT_ROTATION,false); //---------------------------------------------------------------- // // Collision Setup // dst->collisionGroup = GetValueFromParameterStruct<int>(parBCollision,PS_BC_GROUP,false); // dst->groupsMask.bits0 = GetValueFromParameterStruct<int>(parGroupsMask,0); dst->groupsMask.bits1 = GetValueFromParameterStruct<int>(parGroupsMask,1); dst->groupsMask.bits2 = GetValueFromParameterStruct<int>(parGroupsMask,2); dst->groupsMask.bits3 = GetValueFromParameterStruct<int>(parGroupsMask,3); dst->skinWidth = GetValueFromParameterStruct<float>(parBCollision,PS_BC_SKINWITDH,false); dst->collision.groupsMask.bits0 = GetValueFromParameterStruct<int>(parGroupsMask,0); dst->collision.groupsMask.bits1 = GetValueFromParameterStruct<int>(parGroupsMask,1); dst->collision.groupsMask.bits2 = GetValueFromParameterStruct<int>(parGroupsMask,2); dst->collision.groupsMask.bits3 = GetValueFromParameterStruct<int>(parGroupsMask,3); dst->collision.skinWidth = GetValueFromParameterStruct<float>(parBCollision,PS_BC_SKINWITDH,false); dst->collision.collisionGroup = GetValueFromParameterStruct<int>(parBCollision,PS_BC_GROUP,false); //---------------------------------------------------------------- // // CCD Settings // /*dst->ccdFlags = GetValueFromParameterStruct<int>(parBCCD,PS_B_CCD_FLAGS,false); dst->ccdMotionThresold= GetValueFromParameterStruct<float>(parBCCD,PS_B_CCD_MOTION_THRESHOLD,false); dst->ccdScale = GetValueFromParameterStruct<float>(parBCCD,PS_B_CCD_SCALE,false); dst->ccdMeshReference = GetValueFromParameterStruct<CK_ID>(parBCCD,PS_B_CCD_MESH_REFERENCE,false); */ dst->mask << OD_Collision; //---------------------------------------------------------------- // // Misc // dst->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; return 1; } IParameter* IParameter::Instance() { if (!gIPar) { gIPar = new IParameter(GetPMan()); } return gIPar; } IParameter::IParameter(PhysicManager*_pManager) : mManager(_pManager) { gIPar = this; }<file_sep>#include "xNetEnumerations.h" #include "xDistTools.h" namespace xDistTools { xNString ValueTypeToString(int valueType) { switch(valueType) { case E_DC_PTYPE_3DVECTOR: return xNString("3D Vector"); case E_DC_PTYPE_2DVECTOR: return xNString("2D Vector"); case E_DC_PTYPE_INT: return xNString("Integer"); case E_DC_PTYPE_FLOAT: return xNString("Float"); case E_DC_PTYPE_STRING: return xNString("String"); } return xNString("Unknown"); } int SuperTypeToValueType(int superType) { switch(superType) { case vtVECTOR2D: return E_DC_PTYPE_2DVECTOR; case vtVECTOR: return E_DC_PTYPE_3DVECTOR; case vtINTEGER: return E_DC_PTYPE_INT; case vtQUATERNION: return E_DC_PTYPE_QUATERNION; case vtSTRING: return E_DC_PTYPE_STRING; case vtBOOL: return E_DC_PTYPE_INT; case vtFLOAT: return E_DC_PTYPE_FLOAT; default : return E_DC_PTYPE_UNKNOWN; } return E_DC_PTYPE_UNKNOWN; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int ValueTypeToSuperType(int valueType) { switch(valueType) { case E_DC_PTYPE_3DVECTOR: return vtVECTOR; case E_DC_PTYPE_2DVECTOR: return vtVECTOR2D; case E_DC_PTYPE_QUATERNION: return vtQUATERNION; case E_DC_PTYPE_INT: return vtINTEGER; case E_DC_PTYPE_FLOAT: return vtFLOAT; case E_DC_PTYPE_STRING: return vtSTRING; } return vtUNKNOWN; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int NativeTypeToValueType(int nativeType) { int result = 0; switch(nativeType) { case E_DC_3D_NP_LOCAL_POSITION: case E_DC_3D_NP_LOCAL_SCALE: case E_DC_3D_NP_WORLD_POSITION: case E_DC_3D_NP_WORLD_SCALE: return E_DC_PTYPE_3DVECTOR; case E_DC_3D_NP_WORLD_ROTATION: case E_DC_3D_NP_LOCAL_ROTATION: return E_DC_PTYPE_QUATERNION; case E_DC_3D_NP_VISIBILITY: return E_DC_PTYPE_BOOL; break; } return E_DC_PTYPE_UNKNOWN; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL::StringPtr NativeTypeToString(int nativeType) { switch(nativeType) { case E_DC_3D_NP_LOCAL_POSITION: return TNL::StringPtr("Local Position"); break; case E_DC_3D_NP_LOCAL_ROTATION: return TNL::StringPtr("Local Rotation"); break; case E_DC_3D_NP_LOCAL_SCALE: return TNL::StringPtr("Local Scale"); case E_DC_3D_NP_WORLD_POSITION: return TNL::StringPtr("World Position"); break; case E_DC_3D_NP_WORLD_ROTATION: return TNL::StringPtr("World Rotation"); break; case E_DC_3D_NP_WORLD_SCALE: return TNL::StringPtr("World Scale"); break; case E_DC_3D_NP_VISIBILITY: return TNL::StringPtr("Visibility"); break; default: return TNL::StringPtr("Unknown"); break; } return TNL::StringPtr("null"); } } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBPhysicalizeDecl(); CKERROR CreatePBPhysicalizeProto(CKBehaviorPrototype **pproto); int PBPhysicalize(const CKBehaviorContext& behcontext); CKERROR PBPhysicalizeCB(const CKBehaviorContext& behcontext); enum bInputs { /* bbI_TargetObject=0,*/ bbI_Flags=0, bbI_HullType, bbI_Density, bbI_SkinWidth, bbI_MassShift, bbI_ShapeShift, bbI_TargetWorld, bbI_Hierachy, bbI_NewDensity, bbI_TotalMass, bbI_Material }; enum bSettings { bbS_USE_DEFAULT_WORLD, //bbS_USE_WORLD_SLEEP_SETTINGS, //bbS_USE_WORLD_DAMPING_SETTINGS, bbS_USE_WORLD_MATERIAL, bbS_ADD_ATTRIBUTES }; //************************************ // Method: FillBehaviorPBPhysicalizeDecl // FullName: FillBehaviorPBPhysicalizeDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPBPhysicalizeDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBPhysicalize"); od->SetCategory("Physic/Body"); od->SetDescription("Adds an entity to the physic engine."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x186f7d29,0xe8901dc)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBPhysicalizeProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBPhysicalizeProto // FullName: CreatePBPhysicalizeProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBPhysicalizeProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBPhysicalize"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /* \page TestBlock PBPhysicalize PBPhysicalize is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Applies an impulsive torque defined in the actor local coordinate frame to the actor.<br> See <A HREF="pBPhysicalize.cmo">pBPhysicalize.cmo</A> for example. <h3>Technical Information</h3> \image html PBPhysicalize.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <SPAN CLASS="pin">Flags: </SPAN>Flags to determine common properties for the desired body. See #BodyFlags. <BR> <SPAN CLASS="pin">Hulltype: </SPAN>The desired shape type. See #HullType. <br> <SPAN CLASS="framedOrange">You can add or remove sub shapes on the fly by pRigidBody::addSubShape() or #PBAddShape.<br> The intial shape can NOT changed after the bodies registration.</SPAN> <BR> <SPAN CLASS="pin">Density: </SPAN>Density of the initial shape. This will be only used if <br> "Hierarchy" =false and <br> "New Density" !=0.0f or "Total Mass" != 0.0f. #pRigidBody::updateMassFromShapes() can update the mass dynamically. <br> <br> <SPAN CLASS="pin">Skin Width: </SPAN>Specifies by how much shapes can interpenetrate. See #pRigidBody::setSkinWidth(). <br> <br> <SPAN CLASS="pin">Mass Offset: </SPAN>Moves the mass center in the local bodies space. <br> <br> <SPAN CLASS="pin">Pivot Offset: </SPAN>Position of the initial shape in the bodies space. <br> <br> <SPAN CLASS="pin">Target World: </SPAN>Multiple worlds are provided. If not specified, it belongs to an automatically created default world(pDefaultWorld).This parameter must be enabled through the settings of this building block. <br> <br> <SPAN CLASS="pin">Hierarchy: </SPAN>If enabled, this function will parse the entities hierarchy and attaches children as additional collisions shapes. Those children must have the physic attribute attached whereby the sub shape flag must be enabled(#BodyFlags). Sub shapes can be attached by #addSubShape() or #PBAddShape afterwards. <br> <br> <SPAN CLASS="pin">New Density: </SPAN>Density scale factor of the shapes belonging to the body.If you supply a non-zero total mass, the bodies mass and inertia will first be computed as above and then scaled to fit this total mass. See #pRigidBody::updateMassFromShapes(). <br> <br> <SPAN CLASS="pin">Total Mass: </SPAN>Total mass if it has sub shapes.If you supply a non-zero density, the bodies mass and inertia will first be computed as above and then scaled by this factor.See #pRigidBody::updateMassFromShapes(). <br> <br> <SPAN CLASS="pin">Material: </SPAN>The material of this body. This parameter must be enabled through the settings of this building block.By default it is using the worlds material. The material of a body can be specified explicity by attaching a physic material attribute on the entity or its mesh or the meshs material. This is the lookup order : <br> - building block input parameter <br> - entity mesh <br> - entities mesh material <br> <br> <br> <SPAN CLASS="setting">Use Default World: </SPAN>Enables input for the world reference. <BR> <SPAN CLASS="setting">Use Worlds Material: </SPAN>Enables input for a physic material. <BR> <SPAN CLASS="setting">Add Attributes: </SPAN>Attaches the physic attribute to the entity. <BR> <BR> <h3>Warning</h3> <h3>Note</h3><br> <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createBody().<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBPhysicalize.cpp </SPAN> */ proto->DeclareInParameter("Flags",VTF_BODY_FLAGS,"Moving Object,Updates in Virtools,Auto Disable,World Gravity,Enabled,Collision"); proto->DeclareInParameter("Hull type",VTE_COLLIDER_TYPE,"Sphere"); proto->DeclareInParameter("Density",CKPGUID_FLOAT,"1.0f"); proto->DeclareInParameter("Skin Width",CKPGUID_FLOAT,"-1.0f"); proto->DeclareInParameter("Mass Offset",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Pivot Offset",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Target World Reference",CKPGUID_3DENTITY,"pDefaultWorld"); proto->DeclareInParameter("Hierarchy",CKPGUID_BOOL,"FALSE"); proto->DeclareInParameter("New Density",CKPGUID_FLOAT,"0.0f"); proto->DeclareInParameter("Total Mass",CKPGUID_FLOAT,"0.0f"); proto->DeclareInParameter("Material",VTS_MATERIAL); proto->DeclareSetting("Use Default World",CKPGUID_BOOL,"TRUE"); proto->DeclareSetting("Use Worlds Material",CKPGUID_BOOL,"TRUE"); proto->DeclareSetting("Add Attributes",CKPGUID_BOOL,"TRUE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct( PBPhysicalizeCB ); proto->SetFunction(PBPhysicalize); *pproto = proto; return CK_OK; } //************************************ // Method: PBPhysicalize // FullName: PBPhysicalize // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBPhysicalize(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; using namespace vtTools; using namespace vtTools::AttributeTools; ////////////////////////////////////////////////////////////////////////// //basic parameters CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); ////////////////////////////////////////////////////////////////////////// //settings int useDWorld; beh->GetLocalParameterValue(bbS_USE_DEFAULT_WORLD,&useDWorld); // int useWorldSS; beh->GetLocalParameterValue(bbS_USE_WORLD_SLEEP_SETTINGS,&useWorldSS); // int useWorldDS; beh->GetLocalParameterValue(bbS_USE_WORLD_DAMPING_SETTINGS,&useWorldDS); int useWorldM; beh->GetLocalParameterValue(bbS_USE_WORLD_MATERIAL,&useWorldM); int addAttributes; beh->GetLocalParameterValue(bbS_ADD_ATTRIBUTES,&addAttributes); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *referenceObject = (CK3dEntity *) beh->GetTarget(); if( !referenceObject ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// //the world : CK3dEntity*worldRef = NULL; if (!useDWorld) { worldRef = (CK3dEntity *) beh->GetInputParameterObject(bbI_TargetWorld); } // the world : pWorld *world=GetPMan()->getWorld(worldRef,referenceObject); if (!world) { beh->ActivateOutput(0); return 0; } pRigidBody*result = world->getBody(referenceObject); if (result) { beh->ActivateOutput(0); return 0; } ////////////////////////////////////////////////////////////////////////// //pick up some parameters : int flags = GetInputParameterValue<int>(beh,bbI_Flags); int hType = GetInputParameterValue<int>(beh,bbI_HullType); float density = GetInputParameterValue<float>(beh,bbI_Density); float skinWidth = GetInputParameterValue<float>(beh,bbI_SkinWidth); int hierarchy = GetInputParameterValue<int>(beh,bbI_Hierachy); float newDensity = GetInputParameterValue<float>(beh,bbI_NewDensity); float totalMass = GetInputParameterValue<float>(beh,bbI_TotalMass); VxVector massOffset = GetInputParameterValue<VxVector>(beh,bbI_MassShift); VxVector shapeOffset = GetInputParameterValue<VxVector>(beh,bbI_ShapeShift); ////////////////////////////////////////////////////////////////////////// // we remove the old physic attribute : if (referenceObject->HasAttribute(GetPMan()->GetPAttribute())) { referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); } referenceObject->SetAttribute(GetPMan()->GetPAttribute()); SetAttributeValue<int>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HIRARCHY,&hierarchy); SetAttributeValue<int>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HULLTYPE,&hType); SetAttributeValue<int>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_BODY_FLAGS,&flags); SetAttributeValue<float>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_DENSITY,&density); SetAttributeValue<float>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_NEW_DENSITY,&newDensity); SetAttributeValue<float>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_TOTAL_MASS,&totalMass); SetAttributeValue<VxVector>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_MASS_OFFSET,&massOffset); //SetAttributeValue<VxVector>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_MASS_OFFSET,&massOffset); CK_ID wID = world->getReference()->GetID(); AttributeTools::SetAttributeValue<CK_ID>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_WORLD,&wID); ////////////////////////////////////////////////////////////////////////// //Material : if (!useWorldM) { if (referenceObject->HasAttribute(GetPMan()->att_surface_props)) { referenceObject->RemoveAttribute(GetPMan()->att_surface_props); } referenceObject->SetAttribute(GetPMan()->att_surface_props); CKParameterIn *pMatIn = beh->GetInputParameter(bbI_Material); CKParameter *pMat = pMatIn->GetRealSource(); CKParameterOut* pout = referenceObject->GetAttributeParameter(GetPMan()->att_surface_props); int error = pout->CopyValue(pMat); pout->Update(); } pRigidBody *body = pFactory::Instance()->createRigidBodyFull(referenceObject,worldRef); if (body) { body->translateLocalShapePosition(shapeOffset); } //GetPMan()->checkWorlds(); if (!addAttributes) { referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); referenceObject->RemoveAttribute(GetPMan()->att_surface_props); } beh->ActivateOutput(0); return 0; } //************************************ // Method: PBPhysicalizeCB // FullName: PBPhysicalizeCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBPhysicalizeCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD useDWorld; beh->GetLocalParameterValue(bbS_USE_DEFAULT_WORLD,&useDWorld); beh->EnableInputParameter(bbI_TargetWorld,!useDWorld); /* DWORD useDWorldSS; beh->GetLocalParameterValue(bbS_USE_WORLD_SLEEP_SETTINGS,&useDWorldSS); beh->EnableInputParameter(bbI_SleepSettings,!useDWorldSS); DWORD useDWorldDS; beh->GetLocalParameterValue(bbS_USE_WORLD_DAMPING_SETTINGS,&useDWorldDS); beh->EnableInputParameter(bbI_DampingSettings,!useDWorldDS); */ DWORD useDWorldM; beh->GetLocalParameterValue(bbS_USE_WORLD_MATERIAL,&useDWorldM); beh->EnableInputParameter(bbI_Material,!useDWorldM); } break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtAttributeHelper.h" #include "pCommon.h" #include "IParameter.h" #include "vtBBHelper.h" #include "xDebugTools.h" void PhysicManager::_cleanOrphanedJoints() { pWorldMapIt it = getWorlds()->Begin(); while(it != getWorlds()->End()) { pWorld *w = *it; NxU32 jointCount = w->getScene()->getNbJoints(); if (jointCount) { NxArray< NxJoint * >joints; w->getScene()->resetJointIterator(); for (NxU32 i = 0; i < jointCount; ++i) { NxJoint *j = w->getScene()->getNextJoint(); NxActor *a= NULL; NxActor *b= NULL; if (a == NULL && b==NULL) { w->getScene()->releaseJoint(*j); pJoint *mJoint = static_cast<pJoint*>( j->userData ); /*if(mJoint) mJoint->setJoint(NULL); SAFE_DELETE(mJoint); */ } } } it++; } } void PhysicManager::_removeObjectsFromOldScene(CKScene *lastScene) { if (!lastScene) return; CKSceneObjectIterator objIt = lastScene->GetObjectIterator(); CKObject *tpObj; while(!objIt.End()) { CK3dEntity *tpObj = (CK3dEntity *)GetContext()->GetObject(objIt.GetObjectID()); if (tpObj) { pRigidBody *body = getBody(tpObj); if (body) { body->getWorld()->deleteBody(body); } } objIt++; } } void PhysicManager::copyToAttributes( pObjectDescr src,CK3dEntity *dst ) { if (!dst) return; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; int attTypeActor = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); int attTypeMaterial = GetPMan()->getAttributeTypeByGuid(VTS_MATERIAL); int attTypeOptimization = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); int attTypeCCD = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CCD_SETTINGS); int attTypePivot = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); int attTypeMass = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); int attTypeCapsule= GetPMan()->getAttributeTypeByGuid(VTS_CAPSULE_SETTINGS_EX); int attTypeCCyl= GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR); //---------------------------------------------------------------- // // disable attribute callback // CKAttributeManager *aMan = GetPMan()->GetContext()->GetAttributeManager(); if (aMan) { //aMan->SetAttributeCallbackFunction(attTypeActor) } CK3dEntity *referenceObject = dst; ////////////////////////////////////////////////////////////////////////// // we remove the old physic attribute : if (referenceObject->HasAttribute(attTypeActor)) { referenceObject->RemoveAttribute(attTypeActor); } referenceObject->SetAttribute(attTypeActor); CKParameterOut* actorAttribute = referenceObject->GetAttributeParameter(attTypeActor); //---------------------------------------------------------------- // // Common Settings // CKParameterOut *parBCommon = GetParameterFromStruct(actorAttribute,PS_COMMON_SETTINGS); if (parBCommon) { SetParameterStructureValue<int>(parBCommon,PS_BC_HULL_TYPE,src.hullType); SetParameterStructureValue<int>(parBCommon,PS_BC_FLAGS,src.flags); SetParameterStructureValue<float>(parBCommon,PS_BC_DENSITY,src.density); SetParameterStructureValue<CK_ID>(parBCommon,PS_BC_WORLD,src.worlReference); } //---------------------------------------------------------------- // // Collision Setting // CKParameterOut *parBCollision = GetParameterFromStruct(actorAttribute,PS_COLLISION_SETTINGS); CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); if (parBCollision) { SetParameterStructureValue<int>(parBCollision,PS_BC_GROUP,src.collisionGroup); SetParameterStructureValue<float>(parBCollision,PS_BC_SKINWITDH,src.skinWidth); if (parGroupsMask) { SetParameterStructureValue<int>(parGroupsMask,0,src.groupsMask.bits0); SetParameterStructureValue<int>(parGroupsMask,1,src.groupsMask.bits1); SetParameterStructureValue<int>(parGroupsMask,2,src.groupsMask.bits2); SetParameterStructureValue<int>(parGroupsMask,3,src.groupsMask.bits3); } } //---------------------------------------------------------------- // // Optimization // if (src.mask & OD_Optimization) { if (referenceObject->HasAttribute(attTypeOptimization)) { referenceObject->RemoveAttribute(attTypeOptimization); } referenceObject->SetAttribute(attTypeOptimization); CKParameterOut *parBOptimization = referenceObject->GetAttributeParameter(attTypeOptimization); if (parBOptimization) { SetParameterStructureValue<int>(parBOptimization,PS_BO_LOCKS,src.optimization.transformationFlags); SetParameterStructureValue<int>(parBOptimization,PS_BO_SOLVER_ITERATIONS,src.optimization.solverIterations); SetParameterStructureValue<int>(parBOptimization,PS_BO_DOMINANCE_GROUP,src.optimization.dominanceGroup); SetParameterStructureValue<int>(parBOptimization,PS_BO_COMPARTMENT_ID,src.optimization.compartmentGroup); } //---------------------------------------------------------------- // // sleeping // CKParameterOut *parBSleeping = GetParameterFromStruct(parBOptimization,PS_BO_SLEEPING); if (parBSleeping) { SetParameterStructureValue<float>(parBSleeping,PS_BS_ANGULAR_SLEEP,src.optimization.angSleepVelocity); SetParameterStructureValue<float>(parBSleeping,PS_BS_LINEAR_SLEEP,src.optimization.linSleepVelocity); SetParameterStructureValue<float>(parBSleeping,PS_BS_THRESHOLD,src.optimization.sleepEnergyThreshold); } //---------------------------------------------------------------- // // damping // CKParameterOut *parBDamping = GetParameterFromStruct(parBOptimization,PS_BO_DAMPING); if (parBDamping) { SetParameterStructureValue<float>(parBDamping,PS_BD_ANGULAR,src.optimization.angDamping); SetParameterStructureValue<float>(parBDamping,PS_BD_LINEAR,src.optimization.linDamping); } } //---------------------------------------------------------------- // // CCD // if (src.mask & OD_CCD ) { if (referenceObject->HasAttribute(attTypeCCD)) { referenceObject->RemoveAttribute(attTypeCCD); } referenceObject->SetAttribute(attTypeCCD); CKParameterOut *parBCCD = referenceObject->GetAttributeParameter(attTypeCCD); if (parBCCD) { SetParameterStructureValue<float>(parBCCD,PS_B_CCD_MOTION_THRESHOLD,src.ccd.motionThresold); SetParameterStructureValue<int>(parBCCD,PS_B_CCD_FLAGS,src.ccd.flags); SetParameterStructureValue<float>(parBCCD,PS_B_CCD_SCALE,src.ccd.scale); SetParameterStructureValue<CK_ID>(parBCCD,PS_B_CCD_MESH_REFERENCE,src.ccd.meshReference); } } //---------------------------------------------------------------- // // Material // if (src.mask & OD_Material ) { if (referenceObject->HasAttribute(attTypeMaterial)) { referenceObject->RemoveAttribute(attTypeMaterial); } referenceObject->SetAttribute(attTypeMaterial); CKParameterOut *parBMaterial = referenceObject->GetAttributeParameter(attTypeMaterial); if (parBMaterial) { pFactory::Instance()->copyTo(parBMaterial,src.material); } } //---------------------------------------------------------------- // // Pivot // if (src.mask & OD_Pivot ) { if (referenceObject->HasAttribute(attTypePivot)) { referenceObject->RemoveAttribute(attTypePivot); } referenceObject->SetAttribute(attTypePivot); CKParameterOut *parBPivot = referenceObject->GetAttributeParameter(attTypePivot); if (parBPivot) { IParameter::Instance()->copyTo(parBPivot,src.pivot); } } //---------------------------------------------------------------- // // Mass // if (src.mask & OD_Mass ) { if (referenceObject->HasAttribute(attTypeMass)) { referenceObject->RemoveAttribute(attTypeMass); } referenceObject->SetAttribute(attTypeMass); CKParameterOut *parBMass = referenceObject->GetAttributeParameter(attTypeMass); if (parBMass) { IParameter::Instance()->copyTo(parBMass,src.mass); } } //---------------------------------------------------------------- // // Capsule // if (src.mask & OD_Capsule) { if (referenceObject->HasAttribute(attTypeCapsule)) { referenceObject->RemoveAttribute(attTypeCapsule); } referenceObject->SetAttribute(attTypeCapsule); CKParameterOut *parBCapsule = referenceObject->GetAttributeParameter(attTypeCapsule); if (parBCapsule) { IParameter::Instance()->copyTo(parBCapsule,src.capsule); } } //---------------------------------------------------------------- // // convex Cylinder // if (src.mask & OD_ConvexCylinder) { if (referenceObject->HasAttribute(attTypeCCyl)) { referenceObject->RemoveAttribute(attTypeCCyl); } referenceObject->SetAttribute(attTypeCCyl); CKParameterOut *parBCCyl= referenceObject->GetAttributeParameter(attTypeCCyl); if (parBCCyl) { IParameter::Instance()->copyTo(parBCCyl,src.convexCylinder); } } } pVehicle*PhysicManager::getVehicle(CK3dEntity*bodyReference) { pRigidBody *body=getBody(bodyReference); if (bodyReference && body ) { return body->getVehicle(); } return NULL; } pWheel2*PhysicManager::getWheel(CK3dEntity*wheelReference) { pRigidBody *body=getBody(wheelReference); if (wheelReference && body ) { return static_cast<pWheel2*>(body->getWheel(wheelReference)); } return NULL; } NxShape *PhysicManager::getSubShape(CK3dEntity*referenceObject) { if (!referenceObject) return NULL; pRigidBody *body = getBody(referenceObject); if (!body) return NULL; return body->getSubShape(referenceObject); } NxCCDSkeleton* PhysicManager::getCCDSkeleton(CKBeObject *shapeReference) { pWorldMapIt it = getWorlds()->Begin(); int s = getWorlds()->Size(); while(it != getWorlds()->End()) { pWorld *w = *it; NxActor** actors = w->getScene()->getActors(); int nbActors = w->getScene()->getNbActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { NxU32 nbShapes = actor->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)actor->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(s->userData); if (sInfo) { } } } } } } return NULL; } void PhysicManager::createWorlds(int flags) { #ifdef _DEBUG //assert(m_DefaultSleepingSettings()); // assert(getWorlds()); #endif CKAttributeManager* attman = m_Context->GetAttributeManager(); const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_world_object); for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { CK3dEntity*target = static_cast<CK3dEntity*>(*it); pWorld *world = getWorld(target->GetID()); const char*name = target->GetName(); if (world == getDefaultWorld() ) { continue; } ////////////////////////////////////////////////////////////////////////// //world not registered : if (!world) { //at first we check for an attached sleeping settings attribute, when not, we use this->DefaultDefaultSleepingSettings // pSleepingSettings *sleepSettings = target->HasAttribute(att_sleep_settings) ? // pFactory::Instance()->GetSleepingSettingsFromEntity(target) : &this->DefaultSleepingSettings(); //we also retrieve objects world settings //pWorldSettings * worldSettings = pFactory::Instance()->GetWorldSettingsFromEntity(target); //now we can create the final world,the function initiates the world and also it inserts the world //in our m_pWorlds array ! //world = pFactory::Instance()->createWorld(target,worldSettings,sleepSettings); } } }; int PhysicManager::getNbWorlds(){ return getWorlds()->Size();} void PhysicManager::checkClothes() { if (!getNbObjects()) return; if (!isValid()) performInitialization(); if (!isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't make manager valid"); return; } ////////////////////////////////////////////////////////////////////////// // we iterate through all entities tagged with the physic attribute CKAttributeManager* attman = m_Context->GetAttributeManager(); const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_clothDescr); for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { CK3dEntity *target = static_cast<CK3dEntity*>(*it); if (target) { const char *bName = target->GetName(); // is the body registered in any world ? CK_ID wID = vtTools::AttributeTools::GetValueFromAttribute<CK_ID>(target,att_clothDescr,E_CS_WORLD_REFERENCE); CK3dEntity *worldReference = (CK3dEntity*)m_Context->GetObject(wID); pWorld *world = getWorld(wID); if (!worldReference) { continue; } if (getBody(target)) { continue; } if (world->getShapeByEntityID(target->GetID())) { continue; } if (world && worldReference) { pCloth *cloth = world->getCloth(target); if (!cloth) { pClothDesc *descr = pFactory::Instance()->createClothDescrFromParameter(target->GetAttributeParameter(att_clothDescr)); cloth = pFactory::Instance()->createCloth(target,*descr); if(cloth) { ////////////////////////////////////////////////////////////////////////// if (descr->flags & PCF_AttachToParentMainShape ) { if (target->GetParent()) { CK3dEntity *bodyReference = pFactory::Instance()->getMostTopParent(target); if (bodyReference) { pRigidBody *body = GetPMan()->getBody(bodyReference); if (body) { cloth->attachToShape((CKBeObject*)bodyReference,descr->attachmentFlags); } } } } ////////////////////////////////////////////////////////////////////////// if (descr->flags & PCF_AttachToCollidingShapes) { cloth->attachToCollidingShapes(descr->attachmentFlags); } } } } } } } bool isSceneObject(CK3dEntity *object) { CKLevel *level = GetPMan()->GetContext()->GetCurrentLevel(); if(level) { for(int i = 0 ; i < level->GetSceneCount() ; i++ ) { CKScene *scene = level->GetScene(i); if(scene && scene->IsObjectHere(object)) return true; } } return false; } void PhysicManager::checkWorlds() { CKScene *currentScene = NULL; CKLevel *level = GetContext()->GetCurrentLevel(); if(level) { currentScene = level->GetCurrentScene(); } if (!getNbObjects()) return; if (!isValid()) performInitialization(); if (!isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't make manager valid"); return; } ////////////////////////////////////////////////////////////////////////// // we iterate through all entities tagged with the physic attribute CKAttributeManager* attman = m_Context->GetAttributeManager(); const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_physic_object); for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { CK3dEntity *target = static_cast<CK3dEntity*>(*it); if (target && !isSceneObject(target)) { const char *bName = target->GetName(); // is the body registered in any world ? pRigidBody* body = getBody(target); if(!body) { //we retrieve the bodies target world : CK_ID wID = vtTools::AttributeTools::GetValueFromAttribute<CK_ID>(target,GetPAttribute(),E_PPS_WORLD); int flags = vtTools::AttributeTools::GetValueFromAttribute<CK_ID>(target,GetPAttribute(),E_PPS_BODY_FLAGS); if (flags & BF_SubShape) { continue; } pWorld *world = getWorld(wID) ? getWorld(wID) : getDefaultWorld(); if(world) { //now create the final rigid body : body = pFactory::Instance()->createRigidBodyFull(target,world->getReference()); GetPMan()->getCheckList().PushBack(target->GetID()); } } } } checkClothes(); _checkObjectsByAttribute(currentScene); ////////////////////////////////////////////////////////////////////////// pWorldMapIt itx = getWorlds()->Begin(); while(itx != getWorlds()->End()) { pWorld *w = *itx; if (w) { w->checkList(); } itx++; } } pWorld *PhysicManager::getWorld(CK3dEntity *_o, CK3dEntity *body) { pWorld *result=NULL; ////////////////////////////////////////////////////////////////////////// // // Priorities : // 1. the given world by _o // 2. DefaultWorld // 3. body physic attribute // 4. created default world // ////////////////////////////////////////////////////////////////////////// // we try to get it over _o : if (_o) { result = getWorld(_o->GetID()); if (result && getWorld(_o->GetID())->getReference() ) { _o = result->getReference(); return result; } } ////////////////////////////////////////////////////////////////////////// //still nothing, we try to get the default world : result = getDefaultWorld(); if (result && getDefaultWorld()->getReference() ) { CK_ID id = getDefaultWorld()->getReference()->GetID(); _o = result->getReference(); return result; } ////////////////////////////////////////////////////////////////////////// //we try to get it over the bodies attribute : if (body) { if (body->HasAttribute(GetPAttribute())) { CK_ID id = vtTools::AttributeTools::GetValueFromAttribute<CK_ID>(body,GetPMan()->GetPAttribute(),E_PPS_WORLD); _o = static_cast<CK3dEntity*>(ctx()->GetObject(id)); if (_o) { result = getWorld(_o->GetID()); if (result && getWorld(_o->GetID())->getReference()) { _o = result->getReference(); return result; } _o = NULL; } } } ////////////////////////////////////////////////////////////////////////// //still nothing if (!getDefaultWorld()) { return NULL; //result = pFactory::Instance()->createDefaultWorld("pDefaultWorld"); /* if (result) { _o = getDefaultWorld()->getReference(); }else{ GetPMan()->performInitialization(); result = GetPMan()->getDefaultWorld(); _o = result->getReference(); } */ } return result; } void PhysicManager::destroyWorlds() { pWorldMapIt it = getWorlds()->Begin(); int s = getWorlds()->Size(); while(it != getWorlds()->End()) { pWorld *w = *it; if (w) { w->destroy(); if (w->getReference()) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"World destroyed :%s",w->getReference()->GetName()); } getWorlds()->Remove(w->getReference()); delete w; w = NULL; if (getWorlds()->Size()) { destroyWorlds(); } } } getWorlds()->Clear(); } pWorld*PhysicManager::getWorld(CK_ID _o) { pWorld *result = NULL; CK3dEntity *obj = static_cast<CK3dEntity*>(GetContext()->GetObject(_o)); if (obj) { if (getWorlds()->FindPtr(obj)) { return *getWorlds()->FindPtr(obj); } } return 0; } void PhysicManager::deleteWorld(CK_ID _o) { CK3dEntity *obj = static_cast<CK3dEntity*>(GetContext()->GetObject(_o)); if (obj) { pWorld *w = getWorld(_o); if (w) { w->destroy(); getWorlds()->Remove(obj); delete w; } } } pWorld*PhysicManager::getWorldByShapeReference(CK3dEntity *shapeReference) { if (!shapeReference) { return NULL; } for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) { pWorld *w = *it; if(w) { pRigidBody *body = w->getBody(pFactory::Instance()->getMostTopParent(shapeReference)); if (body) { if (body->isSubShape((CKBeObject*)shapeReference)) { return w; } } } } return 0; } pWorld*PhysicManager::getWorldByBody(CK3dEntity*ent) { if (!ent) { return NULL; } for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) { pWorld *w = *it; if(w) { //pRigidBody *body = w->getBody(pFactory::Instance()->getMostTopParent(ent)); pRigidBody *body = w->getBody(ent); if (body) { return w; } } } return 0; } pCloth *PhysicManager::getCloth(CK_ID entityID) { CK3dEntity *entity = (CK3dEntity*)m_Context->GetObject(entityID); if (!entityID) { return NULL; } for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) { pWorld *w = *it; if(w) { pCloth *cloth = w->getCloth(entity); if (cloth) { return cloth; } } } return NULL; } int PhysicManager::getNbObjects(int flags /* =0 */) { CKAttributeManager* attman = ctx()->GetAttributeManager(); int testAtt = -1; if (flags == 0) testAtt = GetPMan()->GetPAttribute(); int newPhysicObjectAttributeType = getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); // [3/31/2009 master] const XObjectPointerArray& Array = attman->GetAttributeListPtr(testAtt); int startSize = 0; startSize +=Array.Size(); startSize+=attman->GetAttributeListPtr(newPhysicObjectAttributeType).Size(); /* pWorldMapIt it = getWorlds()->Begin(); while(it != getWorlds()->End()) { pWorld *w = *it; if (w) { w->checkList(); } it++; } */ return startSize; }<file_sep>Virtools RSC File 1.0 <file_sep>#include "xMessage.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" xMessage::~xMessage() { xDistributedPropertyArrayIterator begin = getParameters().begin(); xDistributedPropertyArrayIterator end = getParameters().end(); while (begin!=end) { xDistributedProperty *prop = *begin; if (prop) { xDistributedPropertyInfo *info = prop->m_PropertyInfo; if (info) { delete info; prop->m_PropertyInfo=NULL; } getParameters().erase(begin); delete prop; begin = getParameters().begin(); int size = getParameters().size(); if (size) continue; else break; } begin++; } }<file_sep>#include <CPStdAfx.h> #include "vtWindow.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "Manager.h" /************************************************************************/ /* tools */ /************************************************************************/ void vtWindow::ParseCommandLine(const char*cmdLine) { char Dummy[512]=""; char Dummy2[512]=""; char Dummy3[512]=""; char FileName[512]=""; char Options[8][128]={"","","","","","","",""}; char Engine[128]="CK2_3D"; // Default render engine XString lpCmdLine(cmdLine); lpCmdLine.ToLower(); sscanf(lpCmdLine.Str(),"""%s"" -%s -%s -%s -%s -%s -%s -%s -%s",Dummy,Options[0],Options[1],Options[2],Options[3],Options[4],Options[5],Options[6],Options[7]); for (int i=0;i<7;i++) { switch (Options[i][0]) { case 'd': sscanf(Options[i],"d=%d",&m_Player->GetPAppStyle()->g_Render); break; /* case 'w': sscanf(Options[i],"w=%d",&m_ep.g_Width); break; case 'h': sscanf(Options[i],"h=%d",&m_ep.g_Height); break; case 'b': sscanf(Options[i],"bpp=%d",&m_ep.g_Bpp); break; case 'f' : sscanf(Options[i],"f=%d",&m_ep.g_GoFullScreen); break; */ } } } /************************************************************************/ /* player control */ /************************************************************************/ void vtWindow::Terminate(int flags) { m_Player->Pause(); m_Player->Terminate(flags); if (m_Player) { //PostQuitMessage(0); delete m_Player; m_Player =0; } } void vtWindow::Pause() { if (m_Player->m_CKContext) { m_Player->Pause(); } } void vtWindow::Play() { if (m_Player->m_CKContext) { m_Player->Play(); } } void vtWindow::LoadCompostion(char *file) { Pause(); if(m_Player->_Load((const char*)file)!=CK_OK) { // else we load it from a file (iData contains the filename) MessageBox(NULL,"Unable to load composition from file.","Initialisation Error",MB_OK|MB_ICONERROR); } if (!m_Player->_FinishLoad()) { MessageBox(NULL,"Unable to start composition from file.","Initialisation Error",MB_OK|MB_ICONERROR); } } int vtWindow::WndProc(long *hWnd, int uMsg, long * wParam, long* lParam ) { if (m_Player && m_Player->m_CKContext->IsPlaying() ) { m_Player->_MainWindowWndProcStub((HWND)hWnd,(UINT)uMsg,(WPARAM)wParam,(LPARAM)lParam); } return NULL; } /************************************************************************/ /*vt to cshap messaging : */ /************************************************************************/ void vtWindow::DeleteMessage(int messageID) { int result = -1; if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { cman->DeleteMessage(messageID); } } } ////////////////////////////////////////////////////////////////////////// void vtWindow::CleanMessages() { if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { cman->CleanMessages(); cman->SetHasMessages(false); } } } ////////////////////////////////////////////////////////////////////////// char*vtWindow::GetMessageValueStr(int messageID,int parameterSubID) { char* result = NULL; if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { result = cman->GetMessageValueStr(messageID,parameterSubID); } } return result; } ////////////////////////////////////////////////////////////////////////// float vtWindow::GetMessageValueFloat(int messageID,int parameterSubID) { float result = -1.0f; if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { result = cman->GetMessageValueFloat(messageID,parameterSubID); } } return result; } ////////////////////////////////////////////////////////////////////////// int vtWindow::GetMessageValueInt(int messageID,int parameterSubID) { int result = -1; if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { result = cman->GetMessageValueInt(messageID,parameterSubID); } } return result; } ////////////////////////////////////////////////////////////////////////// char* vtWindow::GetMessageName(int messageID) { XString result; if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { return cman->GetMessageName(messageID); } } return result.Str(); } ////////////////////////////////////////////////////////////////////////// int vtWindow::HasMessages() { int result = -1; //MessageBox(NULL,"","",1); if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { result = cman->HasMessages(); } } return result; } int vtWindow::GetMessageParameterType(int messageID, int parameterSubID) { int result = -1; if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { result = cman->GetMessageParameterType(messageID,parameterSubID); } } return result; } ////////////////////////////////////////////////////////////////////////// int vtWindow::GetNumParameters(int messageID) { int result = -1; if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { result = cman->GetNumParameters(messageID); } } return result; } ////////////////////////////////////////////////////////////////////////// int vtWindow::GetNumMessages() { int result = -1; if (m_Player->m_CKContext) { CSManager* cman =(CSManager*)m_Player->m_CKContext->GetManagerByGuid(INIT_MAN_GUID); if (cman) { result = cman->GetNumMessages(); } } return result; } ////////////////////////////////////////////////////////////////////////// /************************************************************************/ /* window specific functions */ /************************************************************************/ int vtWindow::UpdateRenderSize(int w,int h) { Pause(); //m_Player->Stop(); if (m_Player->m_RenderContext) { Sleep(300); ::SetWindowPos(m_Player->m_MainWindow,NULL,0,0,w,h,SWP_NOMOVE); ::SetWindowPos(m_Player->m_RenderWindow,NULL,0,0,w,h,SWP_NOMOVE); m_Player->m_WindowedWidth = w; m_Player->m_WindowedHeight = h; Sleep(150); m_Player->m_RenderContext->Resize(0,0,w,h); } Sleep(50); Play(); return 1; } ////////////////////////////////////////////////////////////////////////// int vtWindow::GetWidth(){ return m_Player->m_WindowedWidth;} ////////////////////////////////////////////////////////////////////////// int vtWindow::GetHeight(){ return m_Player->m_WindowedHeight;} ////////////////////////////////////////////////////////////////////////// int vtWindow::Show(int ShowFlags) { ShowWindow(m_Player->m_RenderWindow,1); return 1;} /************************************************************************/ /* sending msg to vt */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// int vtWindow::SendMessage(char *targetObject,char *message,int id0,int id1,int id2,char* value) { if (m_Player) { return m_Player->SendMessage(targetObject,message,id0,id1,id2,value); } return 0; } ////////////////////////////////////////////////////////////////////////// int vtWindow::SendMessage(char *targetObject,char *message,int id0,int id1,int id2,float value) { //MessageBox(NULL,"","",1); if (m_Player) { return m_Player->SendMessage(targetObject,message,id0,id1,id2,value); } return 0; } ////////////////////////////////////////////////////////////////////////// int vtWindow::SendMessage(char *targetObject,char *message,int id0,int id1,int id2,int value) { if (m_Player) { return m_Player->SendMessage(targetObject,message,id0,id1,id2,value); } return 0; } int vtWindow::CreateAsChild(long * parent) { HWND win = (HWND)(parent); int ptr = (int)parent; /*XString buffer; buffer.Format("id:%d",ptr); MessageBox(NULL,buffer.Str(),"",1);*/ m_Player = &CCustomPlayer::Instance(); HINSTANCE hinst = (HINSTANCE)GetModuleHandle("vtWindow.dll"); m_Player->m_hInstance = hinst; m_Player->m_hWndParent = win; m_Player->_RegisterClass(); m_Player->PLoadEngineWindowProperties(CUSTOM_PLAYER_CONFIG_FILE); m_Player->PLoadEnginePathProfile(CUSTOM_PLAYER_CONFIG_FILE); m_Player->PLoadAppStyleProfile(CUSTOM_PLAYER_CONFIG_FILE); m_Player->m_AppMode = preview; //we only create windows when we want to render something ! if (GetPlayer().GetPAppStyle()->IsRenderering()) { if(!GetPlayer()._CreateWindows()) { MessageBox(NULL,FAILED_TO_CREATE_WINDOWS,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } } const char* fileBuffer = 0; XDWORD fileSize = 0; XString filename(GetPlayer().GetEPathProfile()->CompositionFile); // initialize the player if(!m_Player->InitPlayer(m_Player->m_MainWindow,m_Player->m_RenderWindow,m_Player->m_Config,filename.Length()==0?fileBuffer:filename.CStr(),filename.Length()==0?fileSize:0)) { return FALSE; } m_Player->m_Config = 0 ; if (GetPlayer().GetPAppStyle()->IsRenderering()) { if (m_Player->m_Config&eAutoFullscreen) { // we are a auto fullscreen mode // so we hide the main window ShowWindow(m_Player->m_MainWindow,SW_SHOW); UpdateWindow(m_Player->m_MainWindow); // we show the render window ShowWindow(m_Player->m_RenderWindow,1); UpdateWindow(m_Player->m_RenderWindow); // and set the focus to it SetFocus(m_Player->m_RenderWindow); } else { // we are in windowed mode // so we show the main window /*ShowWindow(m_Player->m_MainWindow,1); UpdateWindow(m_Player->m_MainWindow); // the render window too ShowWindow(m_Player->m_RenderWindow,1); UpdateWindow(m_Player->m_RenderWindow); // and set the focus to it SetFocus(m_Player->m_RenderWindow);*/ } } // we reset the player to start it m_Player->Reset(); m_Player->RedirectLog(); return true; } void vtWindow::Destroy() { if (m_Player) { PostQuitMessage(0); delete m_Player; m_Player =0; } } int vtWindow::Run() { if (m_Player->m_hThread) { m_Player->Stop(); } if (m_Player) { return m_Player->RunInThread(); } return 1; } int vtWindow::DoFrame() { if (m_Player) { return m_Player->DoFrame(); } return 1; } int vtWindow::Tick() { return m_Player->Tick(); } ////////////////////////////////////////////////////////////////////////// vtWindow::vtWindow() { m_Player = NULL; } ////////////////////////////////////////////////////////////////////////// int vtWindow::Init() { m_Player = &CCustomPlayer::Instance(); HINSTANCE hinst = (HINSTANCE)GetModuleHandle("vtWindow.dll"); m_Player->m_hInstance = hinst; ////////////////////////////////////////////////////////////////////////// m_Player->_RegisterClass(); int LastError = GetLastError(); m_Player->PLoadEngineWindowProperties(CUSTOM_PLAYER_CONFIG_FILE); m_Player->PLoadEnginePathProfile(CUSTOM_PLAYER_CONFIG_FILE); m_Player->PLoadAppStyleProfile(CUSTOM_PLAYER_CONFIG_FILE); m_Player->m_AppMode = m_Player->PGetApplicationMode(GetCommandLine()); // sets player.m_AppMode = full; ParseCommandLine(GetCommandLine()); //we only create windows when we want to render something ! if (GetPlayer().GetPAppStyle()->IsRenderering()) { if(!GetPlayer()._CreateWindows()) { MessageBox(NULL,FAILED_TO_CREATE_WINDOWS,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } } const char* fileBuffer = 0; XDWORD fileSize = 0; XString filename(GetPlayer().GetEPathProfile()->CompositionFile); // initialize the player if(!m_Player->InitPlayer(m_Player->m_MainWindow,m_Player->m_RenderWindow,m_Player->m_Config,filename.Length()==0?fileBuffer:filename.CStr(),filename.Length()==0?fileSize:0)) { return FALSE; } m_Player->m_Config = 0 ; if (GetPlayer().GetPAppStyle()->IsRenderering()) { if (m_Player->m_Config&eAutoFullscreen) { // we are a auto fullscreen mode // so we hide the main window ShowWindow(m_Player->m_MainWindow,SW_SHOW); UpdateWindow(m_Player->m_MainWindow); // we show the render window ShowWindow(m_Player->m_RenderWindow,1); UpdateWindow(m_Player->m_RenderWindow); // and set the focus to it SetFocus(m_Player->m_RenderWindow); } else { // we are in windowed mode // so we show the main window ShowWindow(m_Player->m_MainWindow,1); UpdateWindow(m_Player->m_MainWindow); // the render window too ShowWindow(m_Player->m_RenderWindow,1); UpdateWindow(m_Player->m_RenderWindow); // and set the focus to it SetFocus(m_Player->m_RenderWindow); } } // we reset the player to start it m_Player->Reset(); m_Player->RedirectLog(); return 1; }<file_sep>/* * Tcp4u v 3.31 Last Revision 27/02/1998 3.30 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: smtp4u.c * Purpose: manage SMTP protocol * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ static char szWhat[]="@(#)X-Mailer: Smtp4u by Ph. Jounin version 3.30"; #include "build.h" #define SMTP4U_STDHEADER &szWhat[4] /* ------------------------------------ */ /* DATA */ /* ------------------------------------ */ struct S_SmtpProto { char *szCmd; struct S_TnProto tAnswer[16]; }; /* this enum should be in the same order */ /* than the SmtpProto array */ enum { _SMTP4U_CONNECT=0, _SMTP4U_HELO, _SMTP4U_MAILFROM, _SMTP4U_MAILFROMSIZE, _SMTP4U_RCPTTO, _SMTP4U_DATA, _SMTP4U_ENDOFDATA, _SMTP4U_VERIFY, _SMTP4U_QUIT, _SMTP4U_REST, }; /* The last NULL string is handled by the TnProtoExchange Callback */ struct S_SmtpProto SmtpProto[] = { { NULL, /* CONNECTION */ { { "220", SMTP4U_SUCCESS, }, { "421", SMTP4U_SERVICECLOSED, }, { NULL, 0 } } }, { "HELO %s", { { "250", SMTP4U_SUCCESS, }, { "421", SMTP4U_SERVERCANTEXECUTE, }, { "500", SMTP4U_SYNTAXERROR, }, { "501", SMTP4U_SYNTAXERROR, }, { "504", SMTP4U_NOTIMPLEMENTED, }, { "550", SMTP4U_SERVERCANTEXECUTE, }, { NULL, 0 } } }, { "MAIL From:<%s>", { { "250", SMTP4U_SUCCESS, }, { "421", SMTP4U_SERVERCANTEXECUTE, }, { "451", SMTP4U_SERVERCANTEXECUTE, }, { "452", SMTP4U_STORAGEEXCEDED, }, { "500", SMTP4U_SERVERCANTEXECUTE, }, { "501", SMTP4U_SERVERCANTEXECUTE, }, { "504", SMTP4U_NOTIMPLEMENTED, }, { "552", SMTP4U_STORAGEEXCEDED, }, { NULL, 0 } } }, { "MAIL From:<%s> SIZE=%ld", { { "250", SMTP4U_SUCCESS, }, { "421", SMTP4U_SERVERCANTEXECUTE, }, { "451", SMTP4U_SERVERCANTEXECUTE, }, { "452", SMTP4U_STORAGEEXCEDED, }, { "500", SMTP4U_SERVERCANTEXECUTE, }, { "501", SMTP4U_SERVERCANTEXECUTE, }, { "504", SMTP4U_NOTIMPLEMENTED, }, { "552", SMTP4U_STORAGEEXCEDED, }, { NULL, 0 } } }, { "RCPT To: ", { { "250", SMTP4U_SUCCESS, }, { "251", SMTP4U_SUCCESS, }, /* forwarded */ { "421", SMTP4U_SERVERCANTEXECUTE, }, { "451", SMTP4U_SERVERCANTEXECUTE, }, { "452", SMTP4U_STORAGEEXCEDED, }, { "500", SMTP4U_SERVERCANTEXECUTE, }, { "501", SMTP4U_SERVERCANTEXECUTE, }, { "504", SMTP4U_NOTIMPLEMENTED, }, { "551", SMTP4U_UNKNOWNUSER, }, { "552", SMTP4U_STORAGEEXCEDED, }, { "553", SMTP4U_SERVERCANTEXECUTE, }, { NULL, 0 } } }, { "DATA", { { "354", SMTP4U_SUCCESS, }, { "421", SMTP4U_SERVERCANTEXECUTE, }, { "451", SMTP4U_SERVERCANTEXECUTE, }, { "452", SMTP4U_STORAGEEXCEDED, }, { "504", SMTP4U_NOTIMPLEMENTED, }, /* ??? */ { "554", SMTP4U_SERVERCANTEXECUTE, }, { NULL, 0 } } }, { "\r\n.", /* END DATA */ { { "250", SMTP4U_SUCCESS, }, { "451", SMTP4U_SERVERCANTEXECUTE, }, { "452", SMTP4U_STORAGEEXCEDED, }, { "552", SMTP4U_STORAGEEXCEDED, }, { "554", SMTP4U_SERVERCANTEXECUTE, }, { NULL, 0 } } }, { "VRFY %s", { { "250", SMTP4U_SUCCESS, }, { "251", SMTP4U_FORWARDED }, { "421", SMTP4U_SERVERCANTEXECUTE, }, { "500", SMTP4U_SERVERCANTEXECUTE, }, { "501", SMTP4U_SERVERCANTEXECUTE, }, { "504", SMTP4U_NOTIMPLEMENTED, }, { "550", SMTP4U_UNKNOWNUSER, }, { "551", SMTP4U_UNKNOWNUSER, }, { "553", SMTP4U_SERVERCANTEXECUTE, }, { NULL, 0 } } }, { "QUIT", { { "221", SMTP4U_SUCCESS, }, { "250", SMTP4U_SUCCESS, }, { "500", SMTP4U_SERVERCANTEXECUTE, }, { NULL, 0 } } }, { "REST", { { "250", SMTP4U_SUCCESS, }, { "500", SMTP4U_SERVERCANTEXECUTE, }, { "501", SMTP4U_SERVERCANTEXECUTE, }, { "503", SMTP4U_SERVERCANTEXECUTE, }, { "504", SMTP4U_SERVERCANTEXECUTE, }, { NULL, 0 } } }, }; /* SMTP protocol */ /* -------------------------------------------------------------- */ /* Send one RCPT command by user */ /* returns : SMTP4U_SUCCESS */ /* SMTP4U_DATAERROR */ /* SMTP4U_TIMEOUT */ /* SMTP4U_UNKNOWNUSER */ /* SMTP4U_SERVERCANTEXECUTE */ /* SMTP4U_NOTIMPLEMENTED */ /* SMTP4U_UNEXCEPTEDANSWER */ /* -------------------------------------------------------------- */ int API4U SmtpSendRcpt (SOCKET CSock, LPCSTR szTo, LPSTR szBuffer, UINT uBufSize) { LPCSTR pTo = szTo; LPSTR qCmd = NULL; int Rc = SMTP4U_SUCCESS; int Ark; Tcp4uLog (LOG4U_PROC, "SmtpSendRcpt"); while (*pTo!=0 && Rc==SMTP4U_SUCCESS) { /* constructs the beginning of the command */ Strcpy (szBuffer, SmtpProto[_SMTP4U_RCPTTO].szCmd); qCmd = szBuffer + Strlen (SmtpProto[_SMTP4U_RCPTTO].szCmd); /* get the first recipient from the pTo line */ for (Ark=0 ; pTo[Ark]!=0 && pTo[Ark]!=SMTP4U_SEPARATOR ; Ark++) qCmd[Ark] = pTo[Ark]; qCmd[Ark]=0; /* skip spaces and affect pTo the next recipient */ while (pTo[Ark]==SMTP4U_SEPARATOR || pTo[Ark]==' ' || pTo[Ark]=='\t') Ark++; pTo += Ark; /* send the RCPT string */ Rc = TnProtoExchange (CSock, /* used socket */ szBuffer, szBuffer, uBufSize, TnReadMultiLine, /* recv function */ SmtpProto[_SMTP4U_RCPTTO].tAnswer, SizeOfTab(SmtpProto[_SMTP4U_RCPTTO].tAnswer), TRUE, /* sensitive compare */ SMTP4U_DEFTIMEOUT, HFILE_ERROR); } /* until either error or no more recipient */ Tcp4uLog (LOG4U_EXIT, "SmtpSendRcpt"); return Rc<TN_SUCCESS ? SMTP4U_DATAERROR : Rc ; } /* SmtpSendRcpt */ int API4U SmtpSendMessage (LPCSTR szFrom, LPCSTR szTo, LPCSTR szMessage, LPCSTR szHost, LPCSTR szLocalDomain) { int Rc; SOCKET CSock=INVALID_SOCKET; unsigned short usPort = SMTP4U_DEFPORT; char szBuf[2048]; /* overflow is not handled */ #define XX_RETURN(x) { \ TcpClose (& CSock); \ Tcp4uLog (LOG4U_HIPROC, "exit SmtpSendMessage"); \ return (x); } Tcp4uLog (LOG4U_HIPROC, "SmtpSendMessage"); /* Ok search for SMTP server */ Rc = TcpConnect(& CSock, szHost, "smtp", & usPort); if (Rc!=TCP4U_SUCCESS) XX_RETURN (SMTP4U_CANTCONNECT); /* waits for incoming frame */ Rc = TnProtoExchange (CSock, /* used socket */ NULL, /* no frame to be sent */ szBuf, sizeof szBuf, TnReadMultiLine, /* recv function */ SmtpProto[_SMTP4U_CONNECT].tAnswer, SizeOfTab(SmtpProto[_SMTP4U_CONNECT].tAnswer), TRUE, /* sensitive compare */ SMTP4U_DEFTIMEOUT, HFILE_ERROR); if (Rc != SMTP4U_SUCCESS) XX_RETURN (Rc<TN_SUCCESS ? SMTP4U_DATAERROR : Rc); /* sends the hello command */ Sprintf (szBuf, SmtpProto[_SMTP4U_HELO].szCmd, szLocalDomain==NULL ? "" : szLocalDomain); Rc = TnProtoExchange (CSock, /* used socket */ szBuf, /* no frame to be sent */ szBuf, sizeof szBuf, TnReadMultiLine, /* recv function */ SmtpProto[_SMTP4U_HELO].tAnswer, SizeOfTab(SmtpProto[_SMTP4U_HELO].tAnswer), TRUE, /* sensitive compare */ SMTP4U_DEFTIMEOUT, HFILE_ERROR); if (Rc != SMTP4U_SUCCESS) XX_RETURN (Rc<TN_SUCCESS ? SMTP4U_DATAERROR : Rc); /* sends the Mail From */ Sprintf (szBuf, SmtpProto[_SMTP4U_MAILFROM].szCmd, szFrom); Rc = TnProtoExchange (CSock, /* used socket */ szBuf, /* no frame to be sent */ szBuf, sizeof szBuf, TnReadMultiLine, /* recv function */ SmtpProto[_SMTP4U_MAILFROM].tAnswer, SizeOfTab(SmtpProto[_SMTP4U_MAILFROM].tAnswer), TRUE, /* sensitive compare */ SMTP4U_DEFTIMEOUT, HFILE_ERROR); if (Rc != SMTP4U_SUCCESS) XX_RETURN (Rc<TN_SUCCESS ? SMTP4U_DATAERROR : Rc); /* Rcpt command is handled by the SmtpSendRcpt function*/ Rc = SmtpSendRcpt (CSock, szTo, szBuf, sizeof szBuf); if (Rc!=SMTP4U_SUCCESS) XX_RETURN (Rc); /* sends the Data command */ Rc = TnProtoExchange (CSock, /* used socket */ SmtpProto[_SMTP4U_DATA].szCmd, szBuf, sizeof szBuf, TnReadMultiLine, /* recv function */ SmtpProto[_SMTP4U_DATA].tAnswer, SizeOfTab(SmtpProto[_SMTP4U_DATA].tAnswer), TRUE, /* sensitive compare */ SMTP4U_DEFTIMEOUT, HFILE_ERROR); if (Rc != SMTP4U_SUCCESS) XX_RETURN (Rc<TN_SUCCESS ? SMTP4U_DATAERROR : Rc); /* Sends the data using TnSendMultiLine */ TnSendMultiLine (CSock, SMTP4U_STDHEADER, TRUE, HFILE_ERROR); Rc = TnSendMultiLine (CSock, szMessage, TRUE, HFILE_ERROR); if (Rc<TN_SUCCESS) XX_RETURN (SMTP4U_DATAERROR); /* sends the End of Data command */ Rc = TnProtoExchange (CSock, /* used socket */ SmtpProto[_SMTP4U_ENDOFDATA].szCmd, szBuf, sizeof szBuf, TnReadMultiLine, /* recv function */ SmtpProto[_SMTP4U_ENDOFDATA].tAnswer, SizeOfTab(SmtpProto[_SMTP4U_ENDOFDATA].tAnswer), TRUE, /* sensitive compare */ SMTP4U_DEFTIMEOUT, HFILE_ERROR); if (Rc != SMTP4U_SUCCESS) XX_RETURN (Rc<TN_SUCCESS ? SMTP4U_DATAERROR : Rc); /* and Quit properly */ Rc = TnProtoExchange (CSock, /* used socket */ SmtpProto[_SMTP4U_QUIT].szCmd, szBuf, sizeof szBuf, TnReadMultiLine, /* recv function */ SmtpProto[_SMTP4U_QUIT].tAnswer, SizeOfTab(SmtpProto[_SMTP4U_QUIT].tAnswer), TRUE, /* sensitive compare */ SMTP4U_DEFTIMEOUT, HFILE_ERROR); XX_RETURN (Rc<TN_SUCCESS ? SMTP4U_DATAERROR : Rc); #undef XX_RETURN } /* SmtpSendMessage */ <file_sep>/******************************************************************** created: 2007/11/23 created: 23:11:2007 12:21 filename: e:\ProjectRoot\current\vt_plugins\vtOpenDynamics\Manager\vtOdeTypes.h file path: e:\ProjectRoot\current\vt_plugins\vtOpenDynamics\Manager file base: vtOdeTypes file ext: h author: mc007 purpose: *********************************************************************/ #ifndef __VTODE_TYPES_H_ #define __VTODE_TYPES_H_ #include "pSleepingSettings.h" #include "pWorldSettings.h" typedef CK3dEntity* vt3DObjectType; typedef VxVector xVector3; struct vtHeightFieldData { /* int wS,dS,warp; float w,d,thickness,scale; int ID,tID; float rF,gF,bF,aF; float maxH; CK_ID maxHReference; dHeightfieldDataID heightFieldData; vtHeightFieldData(float _w,float _d,float _thickness,float _scale,int _wS,int _dS,int _warp,int _ID,int _texID,float _rF,float _gF,float _bF,float _aF) : w(_w) , d(_d) , thickness(_thickness) , scale(_scale ) ,warp(_warp) , ID(_ID) , wS(_wS) , dS(_dS) ,tID(_texID) , rF(_rF) , gF(_gF) ,bF(_bF) , aF(_aF) { heightFieldData = NULL; } float lastH; Vx2DVector lastHCoord; int lastColor; */ }; struct vtWorldInfo { /* VxVector Gravity; float CFM; float ERP; float StepResFactor; int MaxIterations; int AutoEnableDepth; float MaximumContactCorrectVelocity; float ContactSurfaceLayer; float rF,gF,bF,aF; vtWorldInfo() { Gravity.x = 0.0f; Gravity.y = -10.0f; Gravity.z = 0.0f; CFM = 0.00000001f; ERP = 0.9f; AutoEnableDepth = 1; MaxIterations = 100; StepResFactor = 0.0085f; } vtWorldInfo(VxVector _g,float _CFM,float _ERP,int _Auto,int _Max,float _StepResFactor,float _rF,float _gF,float _bF,float _aF) : Gravity(_g) , CFM(_CFM) , ERP(_ERP) , AutoEnableDepth(_Auto) , MaxIterations(_Max) , StepResFactor(_StepResFactor) , rF(_rF) , gF(_gF),bF(_bF ),aF(_aF) { } */ }; ////////////////////////////////////////////////////////////////////////// struct vtIntersectionInfo { /* vt3DObjectType m_ObjectPart; vt3DObjectType m_TouchedObstacle; vt3DObjectType m_TouchedSubObstacle; xVector3 m_position; xVector3 m_Normal; float m_Depth; int m_num; */ }; #endif<file_sep> // -------------------------------------------------------------------------- // www.UnitedBusinessTechnologies.com // Copyright (c) 1998 - 2002 All Rights Reserved. // // Source in this file is released to the public under the following license: // -------------------------------------------------------------------------- // This toolkit may be used free of charge for any purpose including corporate // and academic use. For profit, and Non-Profit uses are permitted. // // This source code and any work derived from this source code must retain // this copyright at the top of each source file. // // UBT welcomes any suggestions, improvements or new platform ports. // email to: <EMAIL> // -------------------------------------------------------------------------- #include "pch.h" #include "GException.h" #include "GString.h" #include "GProfile.h" #include <stdarg.h> //for: va_start(), va_end #include <string.h> //for: strlen(), memcpy() static char *g_pzStaticErrMap = 0; void SetErrorDescriptions(const char *pzErrData) { if (g_pzStaticErrMap) delete g_pzStaticErrMap; g_pzStaticErrMap = new char[strlen(pzErrData)+1]; memcpy(g_pzStaticErrMap,pzErrData,strlen(pzErrData)+1); } GProfile &GetErrorProfile() { static GString strErrorFile; GString *pstrErrorFileContents = 0; if (strErrorFile.IsEmpty()) { if (g_pzStaticErrMap) { strErrorFile = "Static Load"; pstrErrorFileContents = new GString(g_pzStaticErrMap,strlen(g_pzStaticErrMap)); } else { const char *pzErrFile = GetProfile().GetString("System", "Errors", 0); if (pzErrFile && pzErrFile[0]) { pstrErrorFileContents = new GString(); if (!pstrErrorFileContents->FromFile(pzErrFile,0)) { pzErrFile = 0; } strErrorFile = pzErrFile; } // if the error file could not be found, default to a minimal error file if (!pzErrFile) { (*pstrErrorFileContents) = "[Exception]\nSubSystem=0\n[Profile]\nSubSystem=1\n0=[%s.%s]Error Description File Not loaded.\n1=[%s]Error Description File Not loaded.\n"; strErrorFile = "Static"; } } } static GProfile ErrorProfile(pstrErrorFileContents->StrVal(), pstrErrorFileContents->Length()); return ErrorProfile; } #if defined _DEBUGX && _WIN32 #include <eh.h> #include <string> #include <vector> #pragma comment( lib, "imagehlp" ) /////////////////////////////////////////////////////////////////////////// /////////////////////// Win32 stack tracing /////////////////////////////// #define gle (GetLastError()) #define lenof(a) (sizeof(a) / sizeof((a)[0])) #define MAXNAMELEN 1024 // max name length for found symbols #define IMGSYMLEN ( sizeof IMAGEHLP_SYMBOL ) #define TTBUFLEN 65536 // for a temp buffer void _stack_se_translator(unsigned int e, _EXCEPTION_POINTERS* p) { HANDLE hThread; DuplicateHandle( GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hThread, 0, false, DUPLICATE_SAME_ACCESS ); GenericCallStack stk(hThread, *(p->ContextRecord)); CloseHandle( hThread ); throw stk; } GenericCallStack::GenericCallStack(const GenericCallStack &src) { _stk = src._stk; } struct ModuleEntry { std::string imageName; std::string moduleName; DWORD baseAddress; DWORD size; }; typedef std::vector< ModuleEntry > ModuleList; typedef ModuleList::iterator ModuleListIter; // miscellaneous toolhelp32 declarations; we cannot #include the header // because not all systems may have it #define MAX_MODULE_NAME32 255 #define TH32CS_SNAPMODULE 0x00000008 #pragma pack( push, 8 ) typedef struct tagMODULEENTRY32 { DWORD dwSize; DWORD th32ModuleID; // This module DWORD th32ProcessID; // owning process DWORD GlblcntUsage; // Global usage count on the module DWORD ProccntUsage; // Module usage count in th32ProcessID's context BYTE * modBaseAddr; // Base address of module in th32ProcessID's context DWORD modBaseSize; // Size in bytes of module starting at modBaseAddr HMODULE hModule; // The hModule of this module in th32ProcessID's context char szModule[MAX_MODULE_NAME32 + 1]; char szExePath[MAX_PATH]; } MODULEENTRY32; typedef MODULEENTRY32 * PMODULEENTRY32; typedef MODULEENTRY32 * LPMODULEENTRY32; #pragma pack( pop ) bool fillModuleListTH32( ModuleList& modules, DWORD pid ) { // CreateToolhelp32Snapshot() typedef HANDLE (__stdcall *tCT32S)( DWORD dwFlags, DWORD th32ProcessID ); // Module32First() typedef BOOL (__stdcall *tM32F)( HANDLE hSnapshot, LPMODULEENTRY32 lpme ); // Module32Next() typedef BOOL (__stdcall *tM32N)( HANDLE hSnapshot, LPMODULEENTRY32 lpme ); // I think the DLL is called tlhelp32.dll on Win9X, so we try both const char *dllname[] = { "kernel32.dll", "tlhelp32.dll" }; HINSTANCE hToolhelp; tCT32S pCT32S; tM32F pM32F; tM32N pM32N; HANDLE hSnap; MODULEENTRY32 me = { sizeof me }; bool keepGoing; ModuleEntry e; int i; for ( i = 0; i < lenof( dllname ); ++ i ) { hToolhelp = LoadLibrary( dllname[i] ); if ( hToolhelp == 0 ) continue; pCT32S = (tCT32S) GetProcAddress( hToolhelp, "CreateToolhelp32Snapshot" ); pM32F = (tM32F) GetProcAddress( hToolhelp, "Module32First" ); pM32N = (tM32N) GetProcAddress( hToolhelp, "Module32Next" ); if ( pCT32S != 0 && pM32F != 0 && pM32N != 0 ) break; // found the functions! FreeLibrary( hToolhelp ); hToolhelp = 0; } if ( hToolhelp == 0 ) // nothing found? return false; hSnap = pCT32S( TH32CS_SNAPMODULE, pid ); if ( hSnap == (HANDLE) -1 ) return false; keepGoing = !!pM32F( hSnap, &me ); while ( keepGoing ) { // here, we have a filled-in MODULEENTRY32 e.imageName = me.szExePath; e.moduleName = me.szModule; e.baseAddress = (DWORD) me.modBaseAddr; e.size = me.modBaseSize; modules.push_back( e ); keepGoing = !!pM32N( hSnap, &me ); } CloseHandle( hSnap ); FreeLibrary( hToolhelp ); return modules.size() != 0; } // miscellaneous psapi declarations; we cannot #include the header // because not all systems may have it typedef struct _MODULEINFO { LPVOID lpBaseOfDll; DWORD SizeOfImage; LPVOID EntryPoint; } MODULEINFO, *LPMODULEINFO; bool fillModuleListPSAPI( ModuleList& modules, DWORD pid, HANDLE hProcess ) { // EnumProcessModules() typedef BOOL (__stdcall *tEPM)( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded ); // GetModuleFileNameEx() typedef DWORD (__stdcall *tGMFNE)( HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize ); // GetModuleBaseName() -- redundant, as GMFNE() has the same prototype, but who cares? typedef DWORD (__stdcall *tGMBN)( HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize ); // GetModuleInformation() typedef BOOL (__stdcall *tGMI)( HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize ); HINSTANCE hPsapi; tEPM pEPM; tGMFNE pGMFNE; tGMBN pGMBN; tGMI pGMI; int i; ModuleEntry e; DWORD cbNeeded; MODULEINFO mi; HMODULE *hMods = 0; char *tt = 0; hPsapi = LoadLibrary( "psapi.dll" ); if ( hPsapi == 0 ) return false; modules.clear(); pEPM = (tEPM) GetProcAddress( hPsapi, "EnumProcessModules" ); pGMFNE = (tGMFNE) GetProcAddress( hPsapi, "GetModuleFileNameExA" ); pGMBN = (tGMFNE) GetProcAddress( hPsapi, "GetModuleBaseNameA" ); pGMI = (tGMI) GetProcAddress( hPsapi, "GetModuleInformation" ); if ( pEPM == 0 || pGMFNE == 0 || pGMBN == 0 || pGMI == 0 ) { // yuck. Some API is missing. FreeLibrary( hPsapi ); return false; } hMods = new HMODULE[TTBUFLEN / sizeof HMODULE]; tt = new char[TTBUFLEN]; // not that this is a sample. Which means I can get away with // not checking for errors, but you cannot. :) if ( ! pEPM( hProcess, hMods, TTBUFLEN, &cbNeeded ) ) { goto cleanup; } if ( cbNeeded > TTBUFLEN ) { goto cleanup; } for ( i = 0; i < cbNeeded / sizeof hMods[0]; ++ i ) { // for each module, get: // base address, size pGMI( hProcess, hMods[i], &mi, sizeof mi ); e.baseAddress = (DWORD) mi.lpBaseOfDll; e.size = mi.SizeOfImage; // image file name tt[0] = '\0'; pGMFNE( hProcess, hMods[i], tt, TTBUFLEN ); e.imageName = tt; // module name tt[0] = '\0'; pGMBN( hProcess, hMods[i], tt, TTBUFLEN ); e.moduleName = tt; modules.push_back( e ); } cleanup: if ( hPsapi ) FreeLibrary( hPsapi ); delete [] tt; delete [] hMods; return modules.size() != 0; } bool fillModuleList( ModuleList& modules, DWORD pid, HANDLE hProcess ) { // try toolhelp32 first if ( fillModuleListTH32( modules, pid ) ) return true; // nope? try psapi, then return fillModuleListPSAPI( modules, pid, hProcess ); } void enumAndLoadModuleSymbols( HANDLE hProcess, DWORD pid ) { ModuleList modules; ModuleListIter it; char *img, *mod; // fill in module list fillModuleList( modules, pid, hProcess ); for ( it = modules.begin(); it != modules.end(); ++ it ) { // unfortunately, SymLoadModule() wants writeable strings img = new char[(*it).imageName.size() + 1]; strcpy( img, (*it).imageName.c_str() ); mod = new char[(*it).moduleName.size() + 1]; strcpy( mod, (*it).moduleName.c_str() ); SymLoadModule( hProcess, 0, img, mod, (*it).baseAddress, (*it).size ); delete [] img; delete [] mod; } } GenericCallStack::GenericCallStack(HANDLE hThread, CONTEXT& c) { DWORD imageType = IMAGE_FILE_MACHINE_I386; HANDLE hProcess = GetCurrentProcess(); int frameNum; // counts walked frames DWORD offsetFromSymbol; // tells us how far from the symbol we were DWORD symOptions; // symbol handler settings IMAGEHLP_SYMBOL *pSym = (IMAGEHLP_SYMBOL *) malloc( IMGSYMLEN + MAXNAMELEN ); char undFullName[MAXNAMELEN]; // undecorated name with all shenanigans IMAGEHLP_MODULE Module; IMAGEHLP_LINE Line; std::string symSearchPath; char *tt = 0, *p; STACKFRAME s; // in/out stackframe memset( &s, '\0', sizeof s ); tt = new char[TTBUFLEN]; // build symbol search path from: symSearchPath = ""; // current directory if ( GetCurrentDirectory( TTBUFLEN, tt ) ) symSearchPath += tt + std::string( ";" ); // dir with executable if ( GetModuleFileName( 0, tt, TTBUFLEN ) ) { for ( p = tt + strlen( tt ) - 1; p >= tt; -- p ) { // locate the rightmost path separator if ( *p == '\\' || *p == '/' || *p == ':' ) break; } // if we found one, p is pointing at it; if not, tt only contains // an exe name (no path), and p points before its first byte if ( p != tt ) // path sep found? { if ( *p == ':' ) // we leave colons in place ++ p; *p = '\0'; // eliminate the exe name and last path sep symSearchPath += tt + std::string( ";" ); } } // environment variable _NT_SYMBOL_PATH if ( GetEnvironmentVariable( "_NT_SYMBOL_PATH", tt, TTBUFLEN ) ) symSearchPath += tt + std::string( ";" ); // environment variable _NT_ALTERNATE_SYMBOL_PATH if ( GetEnvironmentVariable( "_NT_ALTERNATE_SYMBOL_PATH", tt, TTBUFLEN ) ) symSearchPath += tt + std::string( ";" ); // environment variable SYSTEMROOT if ( GetEnvironmentVariable( "SYSTEMROOT", tt, TTBUFLEN ) ) symSearchPath += tt + std::string( ";" ); if ( symSearchPath.size() > 0 ) // if we added anything, we have a trailing semicolon symSearchPath = symSearchPath.substr( 0, symSearchPath.size() - 1 ); // why oh why does SymInitialize() want a writeable string? strncpy( tt, symSearchPath.c_str(), TTBUFLEN ); tt[TTBUFLEN - 1] = '\0'; // if strncpy() overruns, it doesn't add the null terminator // init symbol handler stuff (SymInitialize()) if ( ! SymInitialize( hProcess, tt, false ) ) { goto tagCleanUp; } symOptions = SymGetOptions(); symOptions |= SYMOPT_LOAD_LINES; symOptions &= ~SYMOPT_UNDNAME; SymSetOptions( symOptions ); // SymSetOptions() enumAndLoadModuleSymbols( hProcess, GetCurrentProcessId() ); // init STACKFRAME for first call // Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway, // and good riddance. s.AddrPC.Offset = c.Eip; s.AddrPC.Mode = AddrModeFlat; s.AddrFrame.Offset = c.Ebp; s.AddrFrame.Mode = AddrModeFlat; memset( pSym, '\0', IMGSYMLEN + MAXNAMELEN ); pSym->SizeOfStruct = IMGSYMLEN; pSym->MaxNameLength = MAXNAMELEN; memset( &Line, '\0', sizeof Line ); Line.SizeOfStruct = sizeof Line; memset( &Module, '\0', sizeof Module ); Module.SizeOfStruct = sizeof Module; offsetFromSymbol = 0; for ( frameNum = 0; ;) { // get next stack frame (StackWalk(), SymFunctionTableAccess(), SymGetModuleBase()) // if this returns ERROR_INVALID_ADDRESS (487) or ERROR_NOACCESS (998), you can // assume that either you are done, or that the stack is so hosed that the next // deeper frame could not be found. if ( ! StackWalk( imageType, hProcess, hThread, &s, &c, NULL, SymFunctionTableAccess, SymGetModuleBase, NULL ) ) break; if ( s.AddrPC.Offset != 0 ) { // we seem to have a valid PC // show procedure info (SymGetSymFromAddr()) if ( ! SymGetSymFromAddr( hProcess, s.AddrPC.Offset, &offsetFromSymbol, pSym ) ) { break; } else { // UnDecorateSymbolName() UnDecorateSymbolName( pSym->Name, undFullName, MAXNAMELEN, UNDNAME_COMPLETE ); if (!frameNum && strstr(undFullName, "Exception")) continue; _stk += undFullName; } } // we seem to have a valid PC // no return address means no deeper stackframe if ( s.AddrReturn.Offset == 0 ) { // avoid misunderstandings in the printf() following the loop SetLastError( 0 ); break; } ++frameNum; } // de-init symbol handler etc. (SymCleanup()) SymCleanup( hProcess ); free( pSym ); tagCleanUp:; delete [] tt; } GenericCallStack::~GenericCallStack() { } const GStringList *GenericCallStack::GetStack() { return &_stk; } const char *GenericCallStack::GetStackAsString() { _strStk.Empty(); GStringIterator it(&_stk); while (it()) { if (!_strStk.IsEmpty()) _strStk += "\n"; _strStk += it++; } return (const char *)_strStk; } #endif GenericException::GenericException(int nError, int nSubSystem, const char *pzText, GStringList *pStack) { _error = nError; _subSystem = nSubSystem; _cause = 0; this->Format("%s",pzText); if (pStack) { GStringIterator it(pStack); while (it()) _stk.AddLast(it++); } } void GenericException::AddErrorDetail(int nError, const char *pzErrorText) { GString strTemp; strTemp.Format("[Error %ld] %s\n",nError,pzErrorText); _ErrorDetail.AddLast(strTemp); } void GenericException::AddErrorDetail(const char* szSystem, int error, ...) { int nSubSystem = 0; int nError = error; try { GProfile &ErrorProfile = GetErrorProfile(); nSubSystem = atoi(ErrorProfile.GetString(szSystem, "SubSystem")); GString strKey; strKey.Format("%ld", error); strKey = ErrorProfile.GetString(szSystem, (const char *)strKey); GString strTemp; va_list argList; va_start(argList, error); strTemp.FormatV((const char *)strKey, argList); va_end(argList); GString strAddedToUserStack; strAddedToUserStack.Format("[Error %ld:%ld] %s\n", nSubSystem, nError, (const char *)strTemp); _ErrorDetail.AddLast(strAddedToUserStack); } catch (GenericException &e) { _subSystem = e._subSystem; _error = e._error; Format("%s", (const char *)e); return; } } GenericException::GenericException(const char* szSystem, int error, ...) { _subSystem = 0; _error = error; try { GProfile &ErrorProfile = GetErrorProfile(); _subSystem = atoi(ErrorProfile.GetString(szSystem, "SubSystem")); GString strKey; strKey.Format("%ld", error); strKey = ErrorProfile.GetString(szSystem, (const char *)strKey); va_list argList; va_start(argList, error); FormatV((const char *)strKey, argList); va_end(argList); } catch (GenericException &e) { _subSystem = e._subSystem; _error = e._error; Format("%s", (const char *)e); return; } } GenericException::GenericException(const GenericException &cpy) { _subSystem = cpy._subSystem; _error = cpy._error; _ErrorDetail = cpy._ErrorDetail; Format("%s", (const char *)cpy); } GenericException::GenericException(int error, const char *str) { _subSystem = 0; _error = error; Format("%s", str); } GenericException::GenericException() { _subSystem = 0; } GenericException::~GenericException() { } const char *GenericException::GetDescription() { // Get the user stack into strUserStack GString strUserStack; GStringIterator it(&_ErrorDetail); while (it()) { strUserStack += it++; if (it()) strUserStack += "\n"; } _ret.Format("[Error %ld:%ld] %s\n%s", _subSystem, _error, (const char *)*this, (const char *)strUserStack); return (const char *)_ret; } const char *GenericException::ToXML(const char *pzExceptionParent/* = "TransactResultSet"*/) { _ret.Empty(); // Get the user stack into strUserStack GString strUserStack; GStringIterator it(&_ErrorDetail); while (it()) { strUserStack += "\t\t<UserStack>"; strUserStack.AppendEscapeXMLReserved(it++); strUserStack += "</UserStack>"; if (it()) strUserStack += "\n"; } GString strDescription = (const char *)*this; strDescription.EscapeXMLReserved(); _ret.Format("<%s>\n\t<Exception>\n\t\t<Description>%s</Description>\n\t\t" "<ErrorNumber>%ld</ErrorNumber>\n\t\t<SubSystem>%d</SubSystem>\n%s\t</Exception></%s>", pzExceptionParent, (const char *)strDescription, _error, _subSystem, (const char *)strUserStack, pzExceptionParent); return (const char *)_ret; } long GenericException::GetCause() { _cause = _subSystem; _cause <<= 4; _cause |= _error; return _cause; } const GStringList *GenericException::GetStack() { return &_stk; } const char *GenericException::GetStackAsString() { _ret.Empty(); if (_stk.isEmpty()) { _ret = "Call stack unavailable."; } else { GStringIterator it(&_stk); while (it()) { if (!_ret.IsEmpty()) _ret += "\n"; _ret += it++; } } return (const char *)_ret; } <file_sep>#ifndef __IPARAMETER_H__ #define __IPARAMETER_H__ #include "vtPhysXBase.h" /*! \if internal2 \brief Interface for parameters, implemented as singleton. Helps to convert from PhysX to Virtools and vice versa. \Note This class has been introduced to collect parameter exchange related functionality. In the initial implementation of this SDK, pFactory was responsible to perform these tasks. \Warning We are migrating all parameter related functions from pFactory to here. \endif */ class MODULE_API IParameter { public: /*! * \brief Default Constructor. Not been used. This is a singleton class and needs to be instanced only the PhysicManager */ IParameter(); IParameter(PhysicManager*_pManager); /************************************************************************************************/ /** @name RigidBody */ //@{ /** \brief Conversion for the custom structure #pBSetup. \param[in] pObjectDescr * dst, w: target object \param[in] CKParameter * src, r : source parameter. \return int @see */ int copyTo(pObjectDescr*dst,CKParameter*src); /** \brief Conversion for the custom structure #pBSetup. \param[in] CKParameter * src, r : source parameter. \param[in] pObjectDescr * dst, w: target object \return int @see */ int copyTo(CKParameter*dst,pObjectDescr*src); /** \brief Conversion for the custom structure #pBPivotSettings. \param[in] CKParameter * dst, w : target parameter. \param[in] pObjectDescr * src, w: src object \return int @see */ int copyTo(pOptimization& dst,CKParameter*src); int copyTo(CKParameter*dst,pOptimization src); int copyTo(pCCDSettings& dst,CKParameter*src); int copyTo(CKParameter*dst,pCCDSettings src); int copyTo(pAxisReferencedLength&dst,CKParameter*src,bool evaluate=true); int copyTo(CKParameter*dst,pAxisReferencedLength&src,bool evaluate=true); int copyTo(pCapsuleSettingsEx& dst,CKParameter*src); int copyTo(CKParameter*dst,pCapsuleSettingsEx src); int copyTo(pConvexCylinderSettings& dst,CKParameter*src); int copyTo(CKParameter*dst,pConvexCylinderSettings& src); int copyTo(pObjectDescr&dst,CK3dEntity*src,int copyFlags); int copyTo(pObjectDescr&dst,const pObjectDescr&src); int copyTo(pMassSettings& dst,CKParameter*src); int copyTo(CKParameter*dst,pMassSettings src); int copyTo(pPivotSettings& dst,CKParameter*src); int copyTo(CKParameter*dst,pPivotSettings src); int copyTo(pCollisionSettings& dst,CKParameter*src); int copyTo(CKParameter*dst,pCollisionSettings src); int copyTo(pWheelDescr& dst,CKParameter*src); int copyTo(CKParameter*dst,pWheelDescr src); int copyTo(pVehicleBrakeTable& dst,CKParameter*src); int copyTo(pLinearInterpolation&dst,CKParameter*src); int copyTo(pGearBox *dst,CKParameter*src); int copyTo(CKParameter*dst,pGearBox *src); int copyTo(pLinearInterpolation&dst,CKParameter*src,int size,float maxValue,float minValue); //@} static IParameter* Instance(); private: PhysicManager* mManager; }; #define GetIPar() IParameter::Instance() #endif // __IPARAMETER_H__<file_sep>#include "ZipDll.h" #include "UnzipDll.h" #include "CKAll.h" //#include "..\Manager\ZipManager.h" #define ZERROR_NONE 0 #define ZERROR_DLL_NOT_FOUND 1 #define ZERROR_DLL_FOUNCTION_NOT_FOUND 2 #define ZERROR_NOT_INITIALIZED 3 class CInfoZip { public: CInfoZip(); virtual ~CInfoZip(); BOOL ExtractFiles(const char* pszArchive, const char* pszTargetFolder); void SetDefaultValues(CUnzipParams *pParams); void ReleaseParams(CUnzipParams *pParams); BOOL Execute(CUnzipParams *pParams); BOOL FinalizeUnzip(); BOOL FinalizeZip(char *tempfile); BOOL InitializeUnzip(); BOOL InitializeZip(char *tempfile); BOOL GetInitializedUnzip(); BOOL GetInitializedZip(); void ReleaseParams(CZipParams *pParams); BOOL AddFiles(const char *pszArchive, char **paFiles, int iFileCount); BOOL Execute(CZipParams *pParams); void SetDefaultValues(CZipParams *pZipParms); BOOL GetInitialized(); UINT GetLastError(); int GetZipDllVersion(); int GetUnzipDllVersion(); CZipDllExec m_ZipDllExec; void SetLastError(UINT uiError); UINT m_uiLastError; HINSTANCE m_ZipDllHandle; HINSTANCE m_UnzipDllHandle; CUnzipDllExec m_UnzipDllExec; CGetZipDllVersion m_GetZipDllVersion; private: }; BOOL __stdcall DefaultZipCallback(CZipCallbackData *pData); <file_sep>using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace runme { /// <summary> /// Summary description for vtPanel. /// </summary> public class vtPanel : System.Windows.Forms.Panel { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public vtWindow vtWin = null; public WindowsApplication.Form1 parent; public void Init(WindowsApplication.Form1 _parent, vtWindow vtw) { parent = _parent; vtWin = vtw; //this.OnSizeChanged() } protected override void OnSizeChanged(EventArgs e) { System.Drawing.Size panelSize = this.Size; base.OnSizeChanged(e); } public vtPanel() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion //protected override void OnPaintBackground(PaintEventArgs pevent) { /*protected override void OnPaintBackground(PaintEventArgs pevent) { if(vtWin.HasMessages()==1) { String console = parent.richTextBox1.Text; for (int nbMsg = 0 ; nbMsg < vtWin.GetNumMessages() ; nbMsg ++) { console +="\n message recieved : " + nbMsg + " name : " + vtWin.GetMessageName(nbMsg); for (int nbPar = 0 ; nbPar < vtWin.GetNumParameters(nbMsg) ; nbPar ++ ) { int parType = vtWin.GetMessageParameterType(nbMsg,nbPar); switch (parType) { //string : case 1: { String value = vtWin.GetMessageValueStr(nbMsg,nbPar); console +="\n\t parameter attached : " + nbPar + " : type : " + vtWin.GetMessageParameterType(nbMsg,nbPar) + " value : " + value; break; } //float : case 2: { float value = vtWin.GetMessageValueFloat(nbMsg,nbPar); console +="\n\t parameter attached : " + nbPar + " : type : " + vtWin.GetMessageParameterType(nbMsg,nbPar) + " value : " + value; break; } //integer : case 3: { int value = vtWin.GetMessageValueInt(nbMsg,nbPar); console +="\n\t parameter attached : " + nbPar + " : type : " + vtWin.GetMessageParameterType(nbMsg,nbPar) + " value : " + value; break; } default: break; } } } //vtWin.DeleteMessage(0); vtWin.CleanMessages(); parent.richTextBox1.Text = console; } // Calling the base class OnPaint base.OnPaint(pevent); }*/ } } <file_sep>/* * FileAndDirUtil.h * * Author: <NAME> * * Content: Tools for directory structure handling and file processing. * */ #ifndef _FileAndDirUtil_H_ #define _FileAndDirUtil_H_ #ifdef WIN32 #include <stdio.h> #include <assert.h> #include <windows.h> bool isFile(const char* filename); bool isDir(const char* dirpath); bool getDir(char* path, bool cutLastSlash); HANDLE fileSearchGetNext(HANDLE searchHandle, const char* path, char* file_name); #endif // WIN32 #endif // _FileAndDirUtil_H_ <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SetMidiOutPort // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "../MidiManager.h" CKERROR CreateSetMidiOutPortProto(CKBehaviorPrototype **); int SetMidiOutPort(const CKBehaviorContext& behcontext); /*******************************************************/ /* PROTO DECALRATION */ /*******************************************************/ CKObjectDeclaration *FillBehaviorSetMidiOutPortDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Set Midi Output Port"); od->SetDescription("Sets the Midi Out Port (usally 0)."); od->SetType( CKDLL_BEHAVIORPROTOTYPE ); od->SetGuid(CKGUID(0x149d28c7,0x29947940)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetMidiOutPortProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Controllers/Midi"); return od; } /*******************************************************/ /* PROTO CREATION */ /*******************************************************/ CKERROR CreateSetMidiOutPortProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set Midi Out Port"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Midi Output Port", CKPGUID_INT, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetMidiOutPort); *pproto = proto; return CK_OK; } /*******************************************************/ /* MAIN FUNCTION */ /*******************************************************/ int SetMidiOutPort(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); //see @MidiManager::PostProcess(); beh->GetInputParameterValue(0, &mm->DesiredmidiOutDevice); return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPClothDecl(); CKERROR CreatePClothProto(CKBehaviorPrototype **pproto); int PCloth(const CKBehaviorContext& behcontext); CKERROR PClothCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_AttachmentFlags=E_CS_FLAGS+2, bbI_TargetWorld = E_CS_FLAGS+3, }; enum bSettings { bbS_USE_DEFAULT_WORLD, bbS_ADD_ATTRIBUTES }; //************************************ // Method: FillBehaviorPClothDecl // FullName: FillBehaviorPClothDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPClothDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PCloth"); od->SetCategory("Physic/Cloth"); od->SetDescription("Creates or modifies a cloth."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7901564e,0x7fdb5d76)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePClothProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePClothProto // FullName: CreatePClothProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePClothProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCloth"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PCloth PCloth is categorized in \ref Clothes <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Creates or modifies a cloth.<br> <h3>Technical Information</h3> \image html PCloth.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>Target reference. The entity can not be a rigid body or a shub shape! <BR> <BR> <SPAN CLASS="pin">Thickness: </SPAN>Thickness of the cloth. The thickness is usually a fraction of the overall extent of the cloth and should not be set to a value greater than that. A good value is the maximal distance between two adjacent cloth particles in their rest pose. Visual artifacts or collision problems may appear if the thickness is too small. <b>Default:</b> 0.01 <br> <b>Range:</b> [0,inf) @see pCloth.setThickness() <BR> <SPAN CLASS="pin">Density : </SPAN> Density of the cloth (mass per area). <b>Default:</b> 1.0 <br> <b>Range:</b> (0,inf) <BR> <BR> <SPAN CLASS="pin">Bending Stiffness: </SPAN> Bending stiffness of the cloth in the range 0 to 1. Only has an effect if the flag PCF_Bending is set. <b>Default:</b> 1.0 <br> <b>Range:</b> [0,1] @see PCF_Bending pCloth.setBendingStiffness() <BR> <SPAN CLASS="pin">Stretching Stiffness: </SPAN>Stretching stiffness of the cloth in the range 0 to 1. \note: stretching stiffness must be larger than 0. <b>Default:</b> 1.0 <br> <b>Range:</b> (0,1] @see pCloth.setStretchingStiffness() <BR> <BR> <BR> <SPAN CLASS="pin">Damping: </SPAN>Spring damping of the cloth in the range 0 to 1. Only has an effect if the flag PCF_Damping is set. <b>Default:</b> 0.5 <br> <b>Range:</b> [0,1] @see PCF_Damping pCloth.setDampingCoefficient() <BR> <BR> <BR> <SPAN CLASS="pin">Friction</SPAN>Friction coefficient in the range 0 to 1. Defines the damping of the velocities of cloth particles that are in contact. <b>Default:</b> 0.5 <br> <b>Range:</b> [0,1] @see pCloth.setFriction() <BR> <BR> <BR> <SPAN CLASS="pin">Pressure :</SPAN> If the flag PCF_Pressure is set, this variable defines the volume of air inside the mesh as volume = pressure * restVolume. For pressure < 1 the mesh contracts w.r.t. the rest shape For pressure > 1 the mesh expands w.r.t. the rest shape <b>Default:</b> 1.0 <br> <b>Range:</b> [0,inf) @see PCF_pressure pCloth.setPressure() <BR> <BR> <BR> <BR> <BR> <SPAN CLASS="pin">Tear Factor: </SPAN> If the flag PCF_Tearable is set, this variable defines the elongation factor that causes the cloth to tear. Must be larger than 1. Make sure meshData.maxVertices and the corresponding buffers in meshData are substantially larger (e.g. 2x) than the number of original vertices since tearing will generate new vertices. When the buffer cannot hold the new vertices anymore, tearing stops. <b>Default:</b> 1.5 <br> <b>Range:</b> (1,inf) @see pCloth.setTearFactor() <BR> <BR> <BR> <SPAN CLASS="pin">Collision Response Coefficient: </SPAN> Defines a factor for the impulse transfer from cloth to colliding rigid bodies. Only has an effect if PCF_CollisionTwoWay is set. <b>Default:</b> 0.2 <br> <b>Range:</b> [0,inf) @see PCF_CollisionTwoWay pCloth.setCollisionResponseCoefficient() <BR> <BR> <BR> <SPAN CLASS="pin"></SPAN> <BR> <BR> <BR> <SPAN CLASS="pin">Attachment Response Coefficient: </SPAN>Defines a factor for the impulse transfer from cloth to attached rigid bodies. Only has an effect if the mode of the attachment is set to nx_cloth_attachment_twoway. <b>Default:</b> 0.2 <br> <b>Range:</b> [0,1] @see pCloth.attachToShape pCloth.attachToCollidingShapes pCloth.attachVertexToShape pCloth.setAttachmentResponseCoefficient() <BR> <BR> <BR> <SPAN CLASS="pin">Attachment Tear Factor: </SPAN> If the flag PCF_Tearable is set in the attachment method of pCloth, this variable defines the elongation factor that causes the attachment to tear. Must be larger than 1. <b>Default:</b> 1.5 <br> <b>Range:</b> (1,inf) @see pCloth.setAttachmentTearFactor() pCloth.attachToShape pCloth.attachToCollidingShapes pCloth.attachVertexToShape <BR> <BR> <BR> <SPAN CLASS="pin">To Fluid Response Coefficient: </SPAN> Defines a factor for the impulse transfer from this cloth to colliding fluids. Only has an effect if the PCF_FluidCollision flag is set. <b>Default:</b> 1.0 <br> <b>Range:</b> [0,inf) Note: Large values can cause instabilities @see pClothDesc.flags pClothDesc.fromFluidResponseCoefficient <BR> <BR> <BR> <SPAN CLASS="pin">From Fluid Response Coefficient: </SPAN> Defines a factor for the impulse transfer from colliding fluids to this cloth. Only has an effect if the PCF_FluidCollision flag is set. <b>Default:</b> 1.0 <br> <b>Range:</b> [0,inf) Note: Large values can cause instabilities @see pClothDesc.flags pClothDesc.ToFluidResponseCoefficient <BR> <BR> <BR> <SPAN CLASS="pin">Min Adhere Velocity: </SPAN> If the PCF_Adhere flag is set the cloth moves partially in the frame of the attached actor. This feature is useful when the cloth is attached to a fast moving character. In that case the cloth adheres to the shape it is attached to while only velocities below the parameter minAdhereVelocity are used for secondary effects. <b>Default:</b> 1.0 <b>Range:</b> [0,inf) @see PCF_AdHere <BR> <BR> <BR> <SPAN CLASS="pin">Solver Iterations: </SPAN> Number of solver iterations. Note: Small numbers make the simulation faster while the cloth gets less stiff. <b>Default:</b> 5 <b>Range:</b> [1,inf) @see pCloth.setSolverIterations() <BR> <BR> <BR> <SPAN CLASS="pin">External acceleration : </SPAN> External acceleration which affects all non attached particles of the cloth. <b>Default:</b> (0,0,0) @see pCloth.setExternalAcceleration() <BR> <BR> <BR> <SPAN CLASS="pin">Wind Acceleration: </SPAN> Acceleration which acts normal to the cloth surface at each vertex. <b>Default:</b> (0,0,0) @see pCloth.setWindAcceleration() <BR> <BR> <BR> <SPAN CLASS="pin">Wake Up Counter: </SPAN> The cloth wake up counter. <b>Range:</b> [0,inf)<br> <b>Default:</b> 20.0f*0.02f @see pCloth.wakeUp() pCloth.putToSleep() <BR> <BR> <BR> <SPAN CLASS="pin">Sleep Linear Velocity:</SPAN> Maximum linear velocity at which cloth can go to sleep. If negative, the global default will be used. <b>Range:</b> [0,inf)<br> <b>Default:</b> -1.0 @see pCloth.setSleepLinearVelocity() pCloth.getSleepLinearVelocity() <BR> <BR> <BR> <SPAN CLASS="pin">Collision Group: </SPAN> Sets which collision group this cloth is part of. <b>Range:</b> [0, 31] <b>Default:</b> 0 pCloth.setCollisionGroup() <BR> <BR> <BR> <SPAN CLASS="pin">Valid Bounds: </SPAN> If the flag PCF_ValidBounds is set, this variable defines the volume outside of which cloth particle are automatically removed from the simulation. @see PCF_ValidBounds pCloth.setValidBounds() <BR> <BR> <BR> <SPAN CLASS="pin">Relative Grid Spacing: </SPAN> This parameter defines the size of grid cells for collision detection. The cloth is represented by a set of world aligned cubical cells in broad phase. The size of these cells is determined by multiplying the length of the diagonal of the AABB of the initial cloth size with this constant. <b>Range:</b> [0.01,inf)<br> <b>Default:</b> 0.25 <BR> <BR> <BR> <SPAN CLASS="pin">Flags: </SPAN> Cloth flags. <b>Default:</b> Gravity @see pClothFlag <BR> <BR> <BR> <SPAN CLASS="pin">Attachment Flags: </SPAN> Attachment flags. <b>Default:</b> PCAF_ClothAttachmentTwoway @see pClothAttachmentFlag <BR> <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager #pCloth <br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PClothCreate.vsl </SPAN> */ proto->SetBehaviorCallbackFct( PClothCB ); proto->DeclareInParameter("Thickness",CKPGUID_FLOAT,"0.01f"); proto->DeclareInParameter("Density",CKPGUID_FLOAT,"1.0f"); proto->DeclareInParameter("Bending Stiffness",CKPGUID_FLOAT,"1.0f"); proto->DeclareInParameter("Stretching Stiffness",CKPGUID_FLOAT,"1.0f"); proto->DeclareInParameter("Damping Coefficient",CKPGUID_FLOAT,"0.50f"); proto->DeclareInParameter("Friction",CKPGUID_FLOAT,"0.5f"); proto->DeclareInParameter("Pressure",CKPGUID_FLOAT,"1.0f"); proto->DeclareInParameter("Tear Factor",CKPGUID_FLOAT,"1.5f"); proto->DeclareInParameter("Collision Response Coefficient",CKPGUID_FLOAT,"0.2f"); proto->DeclareInParameter("Attachment Response Coefficient",CKPGUID_FLOAT,"0.2f"); proto->DeclareInParameter("AttachmentTearFactor",CKPGUID_FLOAT,"1.5f"); proto->DeclareInParameter("ToFluidResponseCoefficient",CKPGUID_FLOAT,"1.0f"); proto->DeclareInParameter("FromFluidResponseCoefficient",CKPGUID_FLOAT,"1.0f"); proto->DeclareInParameter("MinAdhereVelocity",CKPGUID_FLOAT,"1.0f"); proto->DeclareInParameter("SolverIterations",CKPGUID_INT,"5"); proto->DeclareInParameter("ExternalAcceleration",CKPGUID_VECTOR); proto->DeclareInParameter("WindAcceleration",CKPGUID_VECTOR); proto->DeclareInParameter("WakeUpCounter",CKPGUID_FLOAT,"0.4f"); proto->DeclareInParameter("SleepLinearVelocity",CKPGUID_FLOAT,"-1.0f"); proto->DeclareInParameter("CollisionGroup",CKPGUID_INT); proto->DeclareInParameter("ValidBounds",CKPGUID_BOX); proto->DeclareInParameter("RelativeGridSpacing",CKPGUID_FLOAT,"0.25f"); proto->DeclareInParameter("Flags",VTE_CLOTH_FLAGS,"Gravity"); proto->DeclareInParameter("Tear Vertex Color",CKPGUID_COLOR,"1.0f"); proto->DeclareInParameter("Target World Reference",CKPGUID_3DENTITY,"pDefaultWorld"); proto->DeclareInParameter("Attachment Flags",VTE_CLOTH_ATTACH_FLAGS); proto->DeclareInParameter("Core Body Reference",CKPGUID_3DENTITY,""); proto->DeclareInParameter("Metal Impulse Threshold",CKPGUID_FLOAT,"50"); proto->DeclareInParameter("Metal Penetration Depth",CKPGUID_FLOAT,"0.5"); proto->DeclareInParameter("Metal Max Deformation Distance",CKPGUID_FLOAT,"0.5"); //proto->DeclareSetting("Use Default World",CKPGUID_BOOL,"TRUE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PCloth); *pproto = proto; return CK_OK; } //************************************ // Method: PCloth // FullName: PCloth // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PCloth(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; #ifdef DONLGE if(!PhysicManager::DongleHasAdvancedVersion) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : no license !"); beh->ActivateOutput(0); return 0; } #endif if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// CK3dEntity*worldRef = (CK3dEntity *) beh->GetInputParameterObject(E_CS_WORLD_REFERENCE); if (!worldRef) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : invalid world reference !"); beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } CK3dEntity*metalCoreRef = (CK3dEntity *) beh->GetInputParameterObject(E_CS_ATTACHMENT_FLAGS +1); if (!metalCoreRef) { //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : invalid world reference !"); //beh->ActivateOutput(0); //return CKBR_PARAMETERERROR; } pWorld *world = GetPMan()->getWorld(worldRef->GetID()); if (!world) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : couldn't find world !"); beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pRigidBody*body = world->getBody(target); if(body) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Cannot create cloth : target can not be a rigid body !"); beh->ActivateOutput(0); return CKBR_OWNERERROR; } NxShape *shape = world->getShapeByEntityID(target->GetID()); if(shape) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Cannot create cloth : target can not be a shape !"); beh->ActivateOutput(0); return CKBR_OWNERERROR; } pClothDesc *descr = new pClothDesc(); using namespace vtTools::ParameterTools; using namespace vtTools::BehaviorTools; descr->thickness = GetInputParameterValue<float>(beh,E_CS_THICKNESS); descr->density = GetInputParameterValue<float>(beh,E_CS_DENSITY); descr->bendingStiffness = GetInputParameterValue<float>(beh,E_CS_BENDING_STIFFNESS); descr->stretchingStiffness = GetInputParameterValue<float>(beh,E_CS_STRETCHING_STIFFNESS); descr->dampingCoefficient = GetInputParameterValue<float>(beh,E_CS_DAMPING_COEFFICIENT); descr->friction = GetInputParameterValue<float>(beh,E_CS_FRICTION); descr->pressure = GetInputParameterValue<float>(beh,E_CS_PRESSURE); descr->tearFactor = GetInputParameterValue<float>(beh,E_CS_TEAR_FACTOR); descr->collisionResponseCoefficient = GetInputParameterValue<float>(beh,E_CS_COLLISIONRESPONSE_COEFFICIENT); descr->attachmentResponseCoefficient = GetInputParameterValue<float>(beh,E_CS_ATTACHMENTRESPONSE_COEFFICIENT); descr->attachmentTearFactor = GetInputParameterValue<float>(beh,E_CS_ATTACHMENT_TEAR_FACTOR); descr->toFluidResponseCoefficient = GetInputParameterValue<float>(beh,E_CS_TO_FLUID_RESPONSE_COEFFICIENT); descr->fromFluidResponseCoefficient = GetInputParameterValue<float>(beh,E_CS_FROM_FLUIDRESPONSE_COEFFICIENT); descr->minAdhereVelocity = GetInputParameterValue<float>(beh,E_CS_MIN_ADHERE_VELOCITY); descr->solverIterations = GetInputParameterValue<unsigned int>(beh,E_CS_SOLVER_ITERATIONS); descr->externalAcceleration = GetInputParameterValue<VxVector>(beh,E_CS_EXTERN_ALACCELERATION); descr->windAcceleration = GetInputParameterValue<VxVector>(beh,E_CS_WIND_ACCELERATION); descr->wakeUpCounter = GetInputParameterValue<float>(beh,E_CS_WAKE_UP_COUNTER); descr->sleepLinearVelocity = GetInputParameterValue<float>(beh,E_CS_SLEEP_LINEAR_VELOCITY); descr->collisionGroup = GetInputParameterValue<int>(beh,E_CS_COLLISIONG_ROUP); descr->validBounds = GetInputParameterValue<VxBbox>(beh,E_CS_VALID_BOUNDS); descr->relativeGridSpacing = GetInputParameterValue<float>(beh,E_CS_RELATIVE_GRID_SPACING); descr->flags = GetInputParameterValue<int>(beh,E_CS_FLAGS); descr->tearVertexColor = GetInputParameterValue<VxColor>(beh,E_CS_TEAR_VERTEX_COLOR); descr->attachmentFlags = (pClothAttachmentFlag)GetInputParameterValue<int>(beh,E_CS_ATTACHMENT_FLAGS); float metalImpulsThresold = GetInputParameterValue<float>(beh,E_CS_ATTACHMENT_FLAGS + 2); float metalPenetrationDepth = GetInputParameterValue<float>(beh,E_CS_ATTACHMENT_FLAGS + 3); float metalMaxDeform= GetInputParameterValue<float>(beh,E_CS_ATTACHMENT_FLAGS + 4); descr->worldReference = worldRef->GetID(); //descr->setToDefault(); // descr->flags = descr->flags | PCF_Bending; pCloth *cloth = world->getCloth(target); if (!cloth) { cloth = pFactory::Instance()->createCloth(target,*descr); if (!cloth) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : factory object failed !"); } } // descr->flags = descr->flags | PCF_AttachToCore; if (cloth) { cloth->setThickness(descr->thickness); cloth->setBendingStiffness(descr->bendingStiffness); cloth->setStretchingStiffness(descr->stretchingStiffness); cloth->setDampingCoefficient(descr->dampingCoefficient); cloth->setFriction(descr->friction); cloth->setPressure(descr->pressure); cloth->setTearFactor(descr->tearFactor); cloth->setCollisionResponseCoefficient(descr->collisionResponseCoefficient); cloth->setAttachmentResponseCoefficient(descr->attachmentResponseCoefficient); cloth->setAttachmentTearFactor(descr->attachmentTearFactor); cloth->setToFluidResponseCoefficient(descr->toFluidResponseCoefficient); cloth->setFromFluidResponseCoefficient(descr->fromFluidResponseCoefficient); cloth->setMinAdhereVelocity(descr->minAdhereVelocity); cloth->setSolverIterations(descr->solverIterations); cloth->setExternalAcceleration(descr->externalAcceleration); cloth->setWindAcceleration(descr->windAcceleration); cloth->setSleepLinearVelocity(descr->sleepLinearVelocity); cloth->setGroup(descr->collisionGroup); cloth->setValidBounds(descr->validBounds); cloth->setFlags(descr->flags); } int flags = GetInputParameterValue<int>(beh,bbI_AttachmentFlags); if (descr->flags & PCF_AttachToParentMainShape ) { if (target->GetParent()) { CK3dEntity *bodyReference = pf->getMostTopParent(target); if (bodyReference) { pRigidBody *body = GetPMan()->getBody(bodyReference); if (body) { cloth->attachToShape((CKBeObject*)bodyReference,flags); } } } } if (descr->flags & PCF_AttachToCollidingShapes) { cloth->attachToCollidingShapes(flags); } if (descr->flags & PCF_AttachToCore) { if (metalCoreRef) { pRigidBody*metalBody = world->getBody(metalCoreRef); if (!metalBody) { pObjectDescr objDesc; objDesc.flags =(BodyFlags)(BF_Collision|BF_Gravity|BF_Moving); objDesc.hullType = HT_Capsule; objDesc.density = 0.1f; metalBody = pFactory::Instance()->createCapsule(metalCoreRef,worldRef,&objDesc,0); if (metalBody) { cloth->attachToCore(metalCoreRef,metalImpulsThresold,metalPenetrationDepth,metalMaxDeform); } } } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: PClothCB // FullName: PClothCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PClothCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { /* DWORD useDWorld; beh->GetLocalParameterValue(bbS_USE_DEFAULT_WORLD,&useDWorld); beh->EnableInputParameter(bbI_TargetWorld,!useDWorld); */ /*DWORD ADamp; beh->GetLocalParameterValue(bbI_ADamp,&ADamp); beh->EnableInputParameter(bbI_ADamp,ADamp);*/ } break; } return CKBR_OK; }<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPClothDestroyDecl(); CKERROR CreatePClothDestroyProto(CKBehaviorPrototype **pproto); int PClothDestroy(const CKBehaviorContext& behcontext); CKERROR PClothDestroyCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_ShapeReference, }; //************************************ // Method: FillBehaviorPClothDestroyDecl // FullName: FillBehaviorPClothDestroyDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPClothDestroyDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothDestroy"); od->SetCategory("Physic/Cloth"); od->SetDescription("Destroys a physical cloth."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x8d604ec,0x2e926408)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePClothDestroyProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePClothDestroyProto // FullName: CreatePClothDestroyProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePClothDestroyProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothDestroy"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PClothDestroy PClothDestroy is categorized in \ref Clothes <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Destroys a physical cloth.<br> @see pWorld::destroyCloth() <h3>Technical Information</h3> \image html PClothDestroy.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>Target cloth reference. <BR> <BR> */ proto->SetBehaviorCallbackFct( PClothDestroyCB ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PClothDestroy); *pproto = proto; return CK_OK; } //************************************ // Method: PClothDestroy // FullName: PClothDestroy // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PClothDestroy(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// pCloth *cloth = GetPMan()->getCloth(target->GetID()); if (!cloth) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pWorld *world = cloth->getWorld(); world->destroyCloth(target->GetID()); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PClothDestroyCB // FullName: PClothDestroyCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PClothDestroyCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> NxActor*pWheel::getTouchedActor()const{ return NULL;} void pWheelDescr::setToDefault() { userData = NULL; wheelFlags =(WheelFlags)0; //radius.setToDefault(); springBias = 0; springRestitution = 1.f; springDamping = 0.f; wheelSuspension = 1.f; maxBrakeForce = 0.0f; frictionToSide = 1.0f; frictionToFront = 1.0f; latFuncXML_Id=0; longFuncXML_Id=0; inverseWheelMass = 0.1f; wheelShapeFlags =(WheelShapeFlags)0; latFunc.setToDefault(); longFunc.setToDefault(); } bool pWheelDescr::isValid() const { /*if(!NxMath::isFinite(radius)) return false; if(radius<=0.0f) return false;*/ bool result = true; int a=X_NEGATE(NxMath::isFinite(wheelSuspension)); //iAssertWR(X_NEGATE(NxMath::isFinite(wheelSuspension)),"",result ); iAssertWR(inverseWheelMass > 0.0f,"",result ); iAssertWR(X_NEGATE(inverseWheelMass<0.0f),"",result ); //iAssertWR(X_NEGATE(brakeTorque<0.0f),"",result ); //iAssertWR(X_NEGATE(NxMath::isFinite(steerAngle)),"",result ); //iAssertWR(X_NEGATE(brakeTorque<0.0f),"",result ); iAssertWR(longFunc.isValid(),"",result ); iAssertWR(latFunc.isValid(),"",result ); /* if (!suspension.isValid()) return false; if (!longitudalTireForceFunction.isValid()) return false; if (!lateralTireForceFunction.isValid()) return false; */ //if (NxMath::abs(1-wheelAxis.magnitudeSquared()) > 0.001f) // return false; if (wheelApproximation > 0 && wheelApproximation < 4) { return false; } if ((wheelFlags & WF_SteerableAuto) && (wheelFlags & WF_SteerableInput)) { return false; } return result; } int pWheel::_constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) { return 1; } void pWheel::setFlags(int flags) { mWheelFlags = flags; } pWheel::pWheel(pRigidBody *body,pWheelDescr *descr) { mBody = body; mWheelFlags = descr->wheelFlags; _wheelRollAngle = 0.0f; mActor= body->getActor(); } pWheel1*pWheel::castWheel1() { return dynamic_cast<pWheel1*>(this); } pWheel2*pWheel::castWheel2() { return dynamic_cast<pWheel2*>(this); } <file_sep>#ifndef __XMATH_TOOLS_H__ #define __XMATH_TOOLS_H__ #include "Prereqs.h" #include "xTNLInternAll.h" #include "xPoint.h" #include "xQuat.h" namespace xMath { __inline void convert(Point3F &target,VxVector source) { target.x = source.x; target.y = source.y; target.z = source.z; } __inline Point3F getFrom(VxVector source) { return Point3F(source.x,source.y,source.z); } __inline VxVector getFrom(Point3F source){return VxVector(source.x,source.y,source.z);} ////////////////////////////////////////////////////////////////////////// __inline void convert(Point2F &target,Vx2DVector source) { target.x = source.x; target.y = source.y; } __inline Point2F getFrom(Vx2DVector source) { return Point2F(source.x,source.y); } __inline Vx2DVector getFrom(Point2F source){return Vx2DVector(source.x,source.y);} ////////////////////////////////////////////////////////////////////////// __inline QuatF getFrom(VxQuaternion source) { return QuatF(source.x,source.y,source.z,source.w); } __inline VxQuaternion getFrom(QuatF source){return VxQuaternion(source.x,source.y,source.z,source.w);} __inline void convert(QuatF &target,VxQuaternion source) { target.x = source.x; target.y = source.y; target.z = source.z; target.w = source.w; } } #endif <file_sep>#ifndef __bCCOError_H #define __bCCOError_H #include <CKAll.h> /** * Within the Virtools C/C++ SDK, this element a learning application error. */ class bCCOError { public: /** * Within the Virtools C/C++ SDK, this enumeration represents the type of the * error which will be used to determine how the handling operation reacts to the * error. */ enum bECOErrorType { /** * Within the Virtools C/C++ SDK, this enumeration denotes a fatal GBL platform * error. The GBL platform will take appropriate steps to shutdown the learning * application in such circumstances. */ bERROR_FATAL = 2, /** * Within the Virtools C/C++ SDK, this enumeration denotes a local GBL platform * error. The GBL platform will not take additional steps to handle such an error, * instead, it is the responsibility of the operation receiving such an error to * take appropriate actions. */ bERROR_LOCAL = 1, /** * Within the Virtools C/C++ SDK, this enumeration denotes a successful status, * generally used by operations as a successful return value. */ bERROR_OK = 0 }; /** * The destructor of the class. **/ bCCOError() {;} /** * This is the copy constructor for the GBL error class, ensuring that * a deep copy of the information is performed, including the internal * error description. **/ bCCOError(bCCOError&error) { errorType = error.GetType(); errorDescription = error.GetDescription(); errorCode = error.GetCode(); } inline bCCOError& operator=( const bCCOError &rhs ) { errorType = rhs.GetType(); errorDescription = rhs.GetDescription(); errorCode = rhs.GetCode(); return *this; } inline bCCOError& operator=( const bECOErrorType &type ) { errorType = type; return *this; } inline bCCOError& operator=( const int &code ) { errorCode = code; return *this; } inline bCCOError& operator=( const XString &desc ) { errorDescription = desc; return *this; } /** * A constructor for the class, which only requires the type to be specified. **/ bCCOError(bCCOError::bECOErrorType type) : errorType(type) {;} /** * A standard constructor for the class, which will accept values being supplied * for all values contained within the error. NOTE: This operation also specifies * default initial values for any of the parameters that are not provided. **/ bCCOError(bCCOError::bECOErrorType type , XString description, int code) : errorType(type) , errorDescription(description), errorCode(code) {;} /** * The destructor of the class. **/ ~bCCOError() {;} /** * Implicit conversion to string. **/ inline operator const char *( ) const { return errorDescription.CStr(); } inline const char * GetDescription()const { return errorDescription.CStr(); } /** * Implicit conversion to int. It will return the error code. **/ inline operator int()const{ return errorCode; } inline int GetCode()const { return errorCode; } /** * Implicit conversion to bECOErrorType. It will return the error type. **/ inline operator bECOErrorType()const { return errorType; } inline bECOErrorType GetType()const { return errorType; } /** * An accessor operation to set the value of the description for the GBL error. **/ inline SetDescription(XString desc) { errorDescription = desc; } /** * An accessor operation to set the value of the code for the GBL error. **/ inline SetCode(int code) { errorCode = code; } /** * An accessor operation to set the value of the type for the GBL error. **/ inline SetType(bECOErrorType type) { errorType = type; } private: /** * This element represents the unique code associated with the GBL platform error. */ int errorCode; /** * This element represents the human readable description associated with error, * that is suitable for being displayed in a dialog or log file. */ XString errorDescription; /** * This element is represents the severity associated with the GBL platform error. */ bCCOError::bECOErrorType errorType; }; #endif<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // MidiPlayer // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKALL.h" #include "CKMidiSound.h" CKERROR CreateMidiPlayerBehaviorProto(CKBehaviorPrototype **pproto); int MidiPlayer(const CKBehaviorContext& behcontext); CKERROR MidiPlayerCB(const CKBehaviorContext& behcontext); /*******************************************************/ /* PROTO DECALRATION */ /*******************************************************/ CKObjectDeclaration *FillBehaviorMidiPlayerDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Midi Player"); od->SetDescription("Plays/Stops a MIDI sound."); /* rem: <SPAN CLASS=in>Play: </SPAN>Starts playback.<BR> <SPAN CLASS=in>Stop: </SPAN>Stops playback.<BR> <BR> <SPAN CLASS=out>Out Play: </SPAN>is activated when the Play input is triggered.<BR> <SPAN CLASS=out>Out Stop: </SPAN>is activated when the Stop input is triggered.<BR> <BR> */ od->SetCategory("Sounds/Midi"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x843cb43a, 0xa12dac48)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateMidiPlayerBehaviorProto); od->SetCompatibleClassId(CKCID_MIDISOUND); return od; } /*******************************************************/ /* PROTO CREATION */ /*******************************************************/ CKERROR CreateMidiPlayerBehaviorProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Midi Player"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Play"); proto->DeclareInput("Stop"); proto->DeclareInput("Pause/Resume"); proto->DeclareOutput("Out Play"); proto->DeclareOutput("Out Stop"); proto->DeclareOutput("Out Pause/Resume"); proto->SetBehaviorFlags(CKBEHAVIOR_NONE); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(MidiPlayer); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct(MidiPlayerCB); *pproto = proto; return CK_OK; } /*******************************************************/ /* MAIN FUNCTION */ /*******************************************************/ int MidiPlayer(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; //____________________________/ PLAY if( beh->IsInputActive(0) ){ CKMidiSound *midi=NULL; // back-compatibility midi = (CKMidiSound *)( beh->GetInputParameter(0) ? beh->GetInputParameterObject(0):beh->GetTarget() ); if(midi){ midi->Play(); beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } } //____________________________/ STOP if( beh->IsInputActive(1) ){ CKMidiSound *midi=NULL; // back-compatibility midi = (CKMidiSound *)( beh->GetInputParameter(0) ? beh->GetInputParameterObject(0):beh->GetTarget() ); if(midi){ midi->Stop(); beh->ActivateInput(1,FALSE); beh->ActivateOutput(1); } } //____________________________/ PAUSE if( beh->IsInputActive(2) ){ CKMidiSound *midi=NULL; // back-compatibility midi = (CKMidiSound *)( beh->GetInputParameter(0) ? beh->GetInputParameterObject(0):beh->GetTarget() ); if(midi){ midi->Pause( midi->IsPlaying() ); beh->ActivateInput(2,FALSE); beh->ActivateOutput(2); } } return CKBR_OK; } /*******************************************************/ /* CALLBACK */ /*******************************************************/ CKERROR MidiPlayerCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKMidiSound *midi=NULL; // back-compatibility midi = (CKMidiSound *)( beh->GetInputParameter(0) ? beh->GetInputParameterObject(0):beh->GetTarget() ); if( !midi ) return CKBR_OK; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORDETACH: case CKM_BEHAVIORRESET: { midi->Stop(); } break; case CKM_BEHAVIORPAUSE: { midi->Pause(); } break; case CKM_BEHAVIORRESUME: { if( midi->IsPaused() ){ midi->Pause(FALSE); } } break; } return CKBR_OK; } <file_sep>/******************************************************************** created: 2008/01/14 created: 14:1:2008 12:06 filename: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer\AboutPage.h file path: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer file base: AboutPage file ext: h author: mc007 purpose: Show an about text via a rich text control given from the projects resource file about.txt ! *********************************************************************/ #pragma once #include "resourceplayer.h" #include "afxwin.h" #include "afxcmn.h" class CustomPlayerDialogAboutPage : public CPropertyPage { // Construction public: CustomPlayerDialogAboutPage(); // Dialog Data //{{AFX_DATA(CAboutPage) enum { IDD = IDD_ABOUTP }; //}}AFX_DATA // Overrides // ClassWizard generate virtual function overrides //{{AFX_VIRTUAL(CAboutPage) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CAboutPage) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() public: CRichEditCtrl m_ErrorRichText; afx_msg void OnEnSetfocusErrorRichtText(); CString errorText; afx_msg void OnEnLinkErrorRichtText(NMHDR *pNMHDR, LRESULT *pResult); }; <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> #include "pCallbackObject.h" #include "pCallbackSignature.h" #include <xBitSet.h> #include "virtools/vtTools.h" #include "vtInterfaceEnumeration.h" #include "vtAttributeHelper.h" static float incrTimer = 0.0f; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; using namespace vtTools::BehaviorTools; int getJointType(int attributeIndex) { switch(attributeIndex) { case 1: return JT_Distance; case 2: return JT_Fixed; case 3: return JT_Spherical; case 4: return JT_Prismatic; case 5: return JT_PointInPlane; case 6: return JT_PointOnLine; case 7: return JT_Cylindrical; case 8: return JT_Revolute; case 9: return JT_D6; default: return -1; } return -1; } void pRigidBody::onICRestore(CK3dEntity* parent,pRigidBodyRestoreInfo *restoreInfo) { if (!parent) return; CKScene *level_scene = GetPMan()->GetContext()->GetCurrentLevel()->GetLevelScene(); if(level_scene) { if(level_scene) { CKStateChunk *chunk = level_scene->GetObjectInitialValue(parent); if (chunk) { CKReadObjectState(parent,chunk); } } } VxVector pos(0,0,0); VxVector scale; VxQuaternion quat; Vx3DDecomposeMatrix(parent->GetWorldMatrix(),quat,pos,scale); VxVector vectorN(0,0,0); setLinearMomentum(vectorN); setAngularMomentum(vectorN); setLinearVelocity(vectorN); setAngularVelocity(vectorN); parent->GetPosition(&pos); setPosition(pos); setRotation(quat); if (level_scene && restoreInfo->hierarchy) { CK3dEntity* subEntity = NULL; XArray<NxShape*>SrcObjects; while (subEntity= parent->HierarchyParser(subEntity) ) { CKStateChunk *chunk = level_scene->GetObjectInitialValue(subEntity); if (chunk) { CKReadObjectState(subEntity,chunk); } } } onSubShapeTransformation(false,true,true,parent,restoreInfo->hierarchy); bool hadJoints = false; if (restoreInfo->removeJoints) { CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;//(sizeof(*getRegistrationTable()) / sizeof((getRegistrationTable())[0])); for (int fIndex = 1 ; fIndex < sizeJFuncMap ; fIndex ++) { std::vector<int>attributeIdList; pFactory::Instance()->findAttributeIdentifiersByGuid(GetPMan()->getRegistrationTable()[fIndex].guid,attributeIdList); int attCount = attributeIdList.size(); for (int i = 0 ; i < attCount ; i++ ) { int currentAttType = attributeIdList.at(i); const XObjectPointerArray& Array = attman->GetAttributeListPtr( attributeIdList.at(i) ); for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { CK3dEntity *target = static_cast<CK3dEntity*>(*it); if (target == parent && fIndex != -1 ) { using namespace vtTools::ParameterTools; CKParameterOut *attributeParameter = target->GetAttributeParameter(currentAttType); if (attributeParameter) { CKStructHelper sHelper(target->GetAttributeParameter(currentAttType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. continue; // get body b : CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(attributeParameter,0); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); pJoint *joint = getJoint(bodyBEnt,(JType)getJointType(fIndex)); if (joint) { XString error; XString bodyBName; if (joint->GetVTEntB()) { bodyBName.Format(" %s ",joint->GetVTEntB()->GetName()); } error.Format("Deleting joint by attribute from : %s with attribute %s connected to :%s",target->GetName(),attman->GetAttributeNameByType(currentAttType),bodyBName.Str()); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.CStr() ); deleteJoint(bodyBEnt, (JType)getJointType(fIndex)); hadJoints = true; int b = getNbJoints(); b++; } } /* XString error; error.Format("Deleting joint by attribute from : %s with %s",target->GetName(),attman->GetAttributeNameByType(currentAttType)); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.CStr() );*/ } } } } } if(hadJoints) GetPMan()->getCheckList().PushBack(getEntID()); //GetPMan()->checkPhysics = true; ////////////////////////////////////////////////////////////////////////// // check for constraint attributes //GetPMan()->_checkObjectsByAttribute(); } bool pRigidBody::onMove(bool position/* =true */,bool rotation/* =true */,VxVector pos,VxQuaternion quad) { /************************************************************************/ /* + determine whether the specified "children" object have sub shapes ! - recursive call of updateSubShape + exit if any object has been updated */ /************************************************************************/ //pSubMeshInfo *info = static_cast<pSubMeshInfo*>(subShape->userData); CK3dEntity* subEntity = NULL; XArray<NxShape*>SrcObjects; //SrcObjects.PushBack( subShape ); CK_ID id = getEntID(); CK3dEntity * thisEnt = (CK3dEntity*)GetPMan()->GetContext()->GetObject(id); if(thisEnt) return false; while (subEntity= thisEnt->HierarchyParser(subEntity)) { CKSTRING name =subEntity->GetName(); /* NxShape *childShape = getSubShape(subEntity); if (childShape) {s pSubMeshInfo *childInfo = static_cast<pSubMeshInfo*>(childShape->userData); if (childInfo) { CK3dEntity *child = (CK3dEntity*)ctx()->GetObject(childInfo->entID); if ( child && isSubShape(child) && childInfo->initDescription.flags & BF_SubShape ) { //SrcObjects.PushBack(child);// } } } */ // body ? pRigidBody *body = GetPMan()->getBody(subEntity); if (body && body!=this ) { body->updateSubShapes(); } } /* for(int i = 0;i<SrcObjects.Size(); ++i) { //subEntity = *SrcObjects.At(i); NxShape *s= (static_cast<NxShape*>(*SrcObjects.At(i))); if (s) { pSubMeshInfo *childInfo = static_cast<pSubMeshInfo*>(s->userData); CK3dEntity *ent = (CK3dEntity*)ctx()->GetObject(childInfo->entID); if (!ent) continue; if (position) { VxVector relPos; ent->GetPosition(&relPos,GetVT3DObject()); s->setLocalPosition(getFrom(relPos)); //onSubShapeTransformation(fromPhysicToVirtools,position,false,childObject); } if (rotation) { /* VxQuaternion refQuad2; ent->GetQuaternion(&refQuad2,GetVT3DObject()); s->setLocalOrientation(getFrom(refQuad2)); //onSubShapeTransformation(fromPhysicToVirtools,false,rotation,childObject); } } } */ return true; } bool pRigidBody::onSubShapeTransformation(bool fromPhysicToVirtools/* =true */,bool position/* =true */,bool rotation/* =true */,CK3dEntity*parent,bool children/* =true */) { /************************************************************************/ /* + determine whether the specified "children" object have sub shapes ! - recursive call of updateSubShape + exit if any object has been updated */ /************************************************************************/ if ( !parent ) return false; NxShape *subShape = getSubShape(parent); if (!subShape) return false; int count = parent->GetChildrenCount(); if (subShape == getMainShape()) return false; pSubMeshInfo *info = static_cast<pSubMeshInfo*>(subShape->userData); CK3dEntity* subEntity = NULL; XArray<NxShape*>SrcObjects; SrcObjects.PushBack( subShape ); while (subEntity= parent->HierarchyParser(subEntity) ) { CKSTRING name =subEntity->GetName(); NxShape *childShape = getSubShape(subEntity); if (childShape) { pSubMeshInfo *childInfo = static_cast<pSubMeshInfo*>(childShape->userData); if (childInfo) { CK3dEntity *child = (CK3dEntity*)ctx()->GetObject(childInfo->entID); if ( child && isSubShape(child) && childInfo->initDescription.flags & BF_SubShape ) { SrcObjects.PushBack( childShape ); } } } } for(int i = 0;i<SrcObjects.Size(); ++i) { NxShape *s= (static_cast<NxShape*>(*SrcObjects.At(i))); if (s) { pSubMeshInfo *childInfo = static_cast<pSubMeshInfo*>(s->userData); CK3dEntity *ent = (CK3dEntity*)ctx()->GetObject(childInfo->entID); if (!ent) continue; if (position) { VxVector relPos; ent->GetPosition(&relPos,GetVT3DObject()); s->setLocalPosition(getFrom(relPos)); //onSubShapeTransformation(fromPhysicToVirtools,position,false,childObject); } if (rotation) { VxQuaternion refQuad2; ent->GetQuaternion(&refQuad2,GetVT3DObject()); s->setLocalOrientation(getFrom(refQuad2)); //onSubShapeTransformation(fromPhysicToVirtools,false,rotation,childObject); } } } return true; } bool pRigidBody::onRayCastHit(NxRaycastHit *report) { return true; } void pRigidBody::setRayCastScript(int val) { CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(val); if (!beh) return; XString errMessage; if (!GetPMan()->checkCallbackSignature(beh,CB_OnRayCastHit,errMessage)) { xError(errMessage.Str()); return; } pCallbackObject::setRayCastScript(val); } bool pRigidBody::onContactConstraint(int& changeFlags,CK3dEntity *sourceObject,CK3dEntity *otherObject,pContactModifyData *data) { bool result = true; //---------------------------------------------------------------- // // sanity checks // if (sourceObject != GetVT3DObject()) return true; CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getContactModificationScript()); if (!beh) return true; if (!data) return true; //---------------------------------------------------------------- // // store data in behaviors inputs // if (sourceObject) SetInputParameterValue<CK_ID>(beh,bbICM_SrcObject,sourceObject->GetID()); if (otherObject) SetInputParameterValue<CK_ID>(beh,bbICM_OtherObject,otherObject->GetID()); SetInputParameterValue<float>(beh,bbICM_MinImpulse,data->minImpulse); SetInputParameterValue<float>(beh,bbICM_MaxImpulse,data->maxImpulse); SetInputParameterValue<VxVector>(beh,bbICM_Error,data->error); SetInputParameterValue<VxVector>(beh,bbICM_Target,data->target); SetInputParameterValue<VxVector>(beh,bbICM_LP0,data->localpos0); SetInputParameterValue<VxVector>(beh,bbICM_LP1,data->localpos1); SetInputParameterValue<VxQuaternion>(beh,bbICM_LO0,data->localorientation0); SetInputParameterValue<VxQuaternion>(beh,bbICM_LO1,data->localorientation1); SetInputParameterValue<float>(beh,bbICM_SF0,data->staticFriction0); SetInputParameterValue<float>(beh,bbICM_SF1,data->staticFriction1); SetInputParameterValue<float>(beh,bbICM_DF0,data->dynamicFriction0); SetInputParameterValue<float>(beh,bbICM_DF1,data->dynamicFriction1); SetInputParameterValue<float>(beh,bbICM_Restitution,data->restitution); //---------------------------------------------------------------- // // execute: // beh->Execute(lastStepTimeMS); //---------------------------------------------------------------- // // refuse contact // result = GetOutputParameterValue<int>(beh,bbOCM_CreateContact); if (!result) return false; //---------------------------------------------------------------- // // nothing changed, return true // changeFlags = GetOutputParameterValue<int>(beh,bbOCM_ModifyFlags); if (changeFlags == CMM_None ) { return true; } //---------------------------------------------------------------- // // pickup data, according to change flags // if (changeFlags & CMM_MinImpulse ) data->minImpulse = GetOutputParameterValue<float>(beh,bbOCM_MinImpulse); if (changeFlags & CMM_MaxImpulse) data->maxImpulse = GetOutputParameterValue<float>(beh,bbOCM_MaxImpulse); if (changeFlags & CMM_Error ) data->error = GetOutputParameterValue<VxVector>(beh,bbOCM_Error); if (changeFlags & CMM_Target ) data->target = GetOutputParameterValue<VxVector>(beh,bbOCM_Target); if (changeFlags & CMM_StaticFriction0) data->staticFriction0 = GetOutputParameterValue<float>(beh,bbOCM_SF0); if (changeFlags & CMM_StaticFriction1) data->staticFriction1 = GetOutputParameterValue<float>(beh,bbOCM_SF1); if (changeFlags & CMM_DynamicFriction0) data->dynamicFriction0 = GetOutputParameterValue<float>(beh,bbOCM_DF0); if (changeFlags & CMM_DynamicFriction1) data->dynamicFriction1 = GetOutputParameterValue<float>(beh,bbOCM_DF1); if (changeFlags & CMM_LocalPosition0) data->localpos0 = GetOutputParameterValue<VxVector>(beh,bbOCM_LP0); if (changeFlags & CMM_LocalPosition1) data->localpos1 = GetOutputParameterValue<VxVector>(beh,bbOCM_LP1); if (changeFlags & CMM_LocalOrientation0) data->localorientation0 = GetOutputParameterValue<VxQuaternion>(beh,bbOCM_LO0); if (changeFlags & CMM_LocalOrientation1) data->localorientation1 = GetOutputParameterValue<VxQuaternion>(beh,bbOCM_LO1); if (changeFlags & CMM_Restitution) data->restitution = GetOutputParameterValue<float>(beh,bbOCM_Restitution); return true; } void pRigidBody::setContactModificationScript(int behaviorID) { CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(behaviorID); if (!beh) return; XString errMessage; if (!GetPMan()->checkCallbackSignature(beh,CB_OnContactModify,errMessage)) { xError(errMessage.Str()); return; } pCallbackObject::setContactModificationScript(behaviorID); enableContactModification(true); } void pRigidBody::setJointBreakScript(int behaviorID,CK3dEntity *shapeReference) { CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(behaviorID); if (!beh) return; XString errMessage; if (!GetPMan()->checkCallbackSignature(beh,CB_OnJointBreak,errMessage)) { xError(errMessage.Str()); return; } pCallbackObject::setJointBreakScript(behaviorID); } void pRigidBody::setTriggerScript(int behaviorID,int eventMask,CK3dEntity *shapeReference) { /*if (descr.flags & BF_TriggerShape ) { result->setFlag(NX_TRIGGER_ENABLE,TRUE); } */ CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(behaviorID); if (!beh) return; XString errMessage; if (!GetPMan()->checkCallbackSignature(beh,CB_OnTrigger,errMessage)) { xError(errMessage.Str()); return; } NxShape * shape = getSubShape(shapeReference); //---------------------------------------------------------------- // // check mask // pTriggerFlags tFlags = (pTriggerFlags)eventMask; if ( (eventMask & TF_OnEnter) || (eventMask & TF_OnStay) || (eventMask & TF_OnLeave) ) { shape->setFlag(NX_TRIGGER_ON_ENTER,eventMask & TF_OnEnter); shape->setFlag(NX_TRIGGER_ON_STAY,eventMask & TF_OnStay); shape->setFlag(NX_TRIGGER_ON_LEAVE,eventMask & TF_OnLeave); pCallbackObject::setTriggerScript(behaviorID,eventMask); }else { shape->setFlag(NX_TRIGGER_ENABLE,false); pCallbackObject::setTriggerScript(-1,0); } } int pRigidBody::onTrigger(pTriggerEntry *report) { CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getTriggerScript()); if (!beh) return -1; if (!report) return -1; if (getTriggerEventMask() & report->triggerEvent ) { if (report->triggerBody) SetInputParameterValue<CK_ID>(beh,bbIT_SrcObject,report->triggerBody->GetID()); if (report->otherObject) SetInputParameterValue<CK_ID>(beh,bbIT_OtherObject,report->otherObject->GetID()); SetInputParameterValue<int>(beh,bbIT_EventType,report->triggerEvent); report->triggered = true; beh->ActivateInput(0,TRUE); beh->Execute(lastStepTimeMS); return 1; } return -1; } void pRigidBody::setContactScript(int behaviorID,int eventMask) { CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(behaviorID); if (!beh) return; XString errMessage; if (!GetPMan()->checkCallbackSignature(beh,CB_OnContactNotify,errMessage)) { xError(errMessage.Str()); return; } pCallbackObject::setContactScript(behaviorID,eventMask); if (getActor()) getActor()->setContactReportFlags(eventMask); } void pRigidBody::onContactNotify(pCollisionsEntry *collisionData) { CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getContactScript()); if (!beh) return; if (!collisionData) return; if (getCollisionEventMask() & collisionData->eventType ) { if (collisionData->bodyA != this ) XSwap(collisionData->bodyA,collisionData->bodyB); SetInputParameterValue<CK_ID>(beh,bbI_SrcObject,collisionData->bodyA->GetVT3DObject()->GetID()); SetInputParameterValue<int>(beh,bbI_EventType,collisionData->eventType); SetInputParameterValue<VxVector>(beh,bbI_NormalForce,collisionData->sumNormalForce); SetInputParameterValue<VxVector>(beh,bbI_FForce,collisionData->sumFrictionForce); SetInputParameterValue<VxVector>(beh,bbI_Point,collisionData->point); SetInputParameterValue<float>(beh,bbI_PointNormalForce,collisionData->pointNormalForce); SetInputParameterValue<VxVector>(beh,bbI_FaceNormal,collisionData->faceNormal); SetInputParameterValue<int>(beh,bbI_FaceIndex,collisionData->faceIndex); SetInputParameterValue<float>(beh,bbI_Distance,collisionData->distance); if (collisionData->bodyB && collisionData->bodyB->GetVT3DObject() ) { SetInputParameterValue<CK_ID>(beh,bbI_OtherObject,collisionData->bodyB->GetVT3DObject()->GetID()); } beh->Execute(lastStepTimeMS); } } int pRigidBody::onJointBreak(pBrokenJointEntry *entry) { CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getJointBreakScript()); if (!beh) return -1; if (!entry) return -1; CK3dEntity *bodyAEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(entry->mAEnt)); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(entry->mBEnt)); if (bodyAEnt) { SetInputParameterValue<CK_ID>(beh,bbJB_SrcObject,entry->mAEnt); }else SetInputParameterValue<CK_ID>(beh,bbJB_SrcObject,0); if(bodyBEnt) SetInputParameterValue<CK_ID>(beh,bbJB_OtherObject,entry->mBEnt); else SetInputParameterValue<CK_ID>(beh,bbJB_OtherObject,0); SetInputParameterValue<float>(beh,bbJB_Force,entry->impulse); float elapsedTime = GetPMan()->GetContext()->GetTimeManager()->GetLastDeltaTimeFree(); beh->Execute(elapsedTime); /* XString log = "joint break at : " ; log+= elapsedTime; if (bodyAEnt) { log+=bodyAEnt->GetName(); } if (bodyBEnt) { log= log + " : with : " + bodyBEnt->GetName(); } xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,log.Str()); */ //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"joint break"); GetPMan()->getJointFeedbackList().RemoveAt( GetPMan()->getJointFeedbackList().GetPosition(entry) ); return 1; } float pRigidBody::getContactReportThreshold() { if (getActor()) { return getActor()->getContactReportThreshold(); } return -1.0f; } void pRigidBody::setContactReportThreshold(float threshold) { if (getActor()) { getActor()->setContactReportThreshold(threshold); } } void pRigidBody::setContactReportFlags(pContactPairFlags flags) { if (getActor()) { getActor()->setContactReportFlags((NxU32)flags); } } int pRigidBody::getContactReportFlags() { if (getActor()) { return getActor()->getContactReportFlags(); } return -1; } void pRigidBody::processScriptCallbacks() { //---------------------------------------------------------------- // // Collision Callbacks // /*if ( !(getCallMask() & CB_OnContactNotify) ) return; */ }<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorRegisterAttributeTypeDecl(); CKERROR CreateRegisterAttributeTypeProto(CKBehaviorPrototype **pproto); int RegisterAttributeType(const CKBehaviorContext& behcontext); CKERROR RegisterAttributeTypeCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_Name, bbI_Category, bbI_DefValue, bbI_PType, bbI_Class, bbI_User, bbI_Save, }; //************************************ // Method: FillBehaviorRegisterAttributeTypeDecl // FullName: FillBehaviorRegisterAttributeTypeDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorRegisterAttributeTypeDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("RegisterAttribute"); od->SetCategory("Physic/Manager"); od->SetDescription("Registers a new attribute type."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x63e567c4,0x65583276)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateRegisterAttributeTypeProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreateRegisterAttributeTypeProto // FullName: CreateRegisterAttributeTypeProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreateRegisterAttributeTypeProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("RegisterAttribute"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Name",CKPGUID_STRING); proto->DeclareInParameter("Category",CKPGUID_STRING); proto->DeclareInParameter("Default Value",CKPGUID_STRING); proto->DeclareInParameter("Parameter Type",CKPGUID_PARAMETERTYPE); proto->DeclareInParameter("Compatible Class",CKPGUID_CLASSID); proto->DeclareInParameter("User",CKPGUID_BOOL,"TRUE"); proto->DeclareInParameter("Save",CKPGUID_BOOL,"TRUE"); proto->SetBehaviorCallbackFct( RegisterAttributeTypeCB ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(RegisterAttributeType); *pproto = proto; return CK_OK; } //************************************ // Method: RegisterAttributeType // FullName: RegisterAttributeType // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int RegisterAttributeType(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); CKAttributeManager* attman = ctx->GetAttributeManager(); CKParameterManager *pMan = ctx->GetParameterManager(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CKSTRING name = GetInputParameterValue<CKSTRING>(beh,bbI_Name); CKSTRING category = GetInputParameterValue<CKSTRING>(beh,bbI_Category); CKSTRING defValue = GetInputParameterValue<CKSTRING>(beh,bbI_DefValue); int pType = GetInputParameterValue<int>(beh,bbI_PType); CK_CLASSID classId = GetInputParameterValue<CK_CLASSID>(beh,bbI_Class); int attFlags = 0 ; int user = GetInputParameterValue<int>(beh,bbI_User); int save = GetInputParameterValue<int>(beh,bbI_Save); if(user) attFlags|=CK_ATTRIBUT_USER; if(save) attFlags|=CK_ATTRIBUT_TOSAVE; attFlags|=CK_ATTRIBUT_CAN_DELETE; CKAttributeType aIType = attman->GetAttributeTypeByName(name); if (aIType!=-1) { beh->ActivateOutput(1); } int att = attman->RegisterNewAttributeType(name,pMan->ParameterTypeToGuid(pType),classId,(CK_ATTRIBUT_FLAGS)attFlags); if (strlen(category)) { attman->AddCategory(category); attman->SetAttributeCategory(att,category); } if (strlen(defValue)) { attman->SetAttributeDefaultValue(att,defValue); } } pm->populateAttributeFunctions(); pm->_RegisterAttributeCallbacks(); beh->ActivateOutput(0); return 0; } //************************************ // Method: RegisterAttributeTypeCB // FullName: RegisterAttributeTypeCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR RegisterAttributeTypeCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; /* switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } */ return CKBR_OK; } <file_sep>vtPlayerConsole.exe -d=1 -mode=server <file_sep>#ifndef __X_DEBUG_TOOLS_H__ #define __X_DEBUG_TOOLS_H__ #include "xPlatform.h" #include "xAssertion.h" #include "xLogger.h" // #include <string> #include <fstream> #define X_IS_BETWEEN(VALUE,MIN,MAX) (VALUE < MAX && VALUE > MIN) #define X_NEGATE(A) !(A) #define _FLT_ASSIGMENT(A,B) ((A=B)==0) //---------------------------------------------------------------- // // base types // #define D_MSG_BUFFER_MAX 4096 #ifdef _DEBUG #define D_FILE_INFO 1 #define D_FILE_LINE_INFO 0 #else #define D_FILE_INFO 1 #define D_FILE_LINE_INFO 0 #endif //---------------------------------------------------------------- // // constants // //---------------------------------------------------------------- // hide filed details #if D_FILE_INFO==1 #if !defined(__FILE__) extern const char *const __FILE__; #endif #else #undef __FILE__ #define __FILE__ "" #endif #if D_FILE_LINE_INFO==1 #if !defined(__LINE__) extern const unsigned int __LINE__; #endif #else #undef __LINE__ #define __LINE__ 0 #endif //---------------------------------------------------------------- // // surround objects : // #if defined(referenceObject) #define DC_OBJECT referenceObject #else #define DC_OBJECT NULL #endif //---------------------------------------------------------------- // // Constants // #define ASSERT_STRING "Assertion" #define FATAL_STRING "Assertion" #define D_SO_NAME_EX(SourceObjectName) SourceObjectName ? SourceObjectName->GetName() : "none" #ifdef referenceObject #define D_SO_NAME referenceObject ? referenceObject->GetName() : "none" #else #define D_SO_NAME "???" #endif //---------------------------------------------------------------- // // code fragments // #define D_DO_POST(PostAction) PostAction; #define D_ASSERT_P_END(PostAction) xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,buffer);\ D_DO_POST(PostAction); #define xSTR_MERGE(A,B) A##B //---------------------------------------------------------------- // // Assertions code fragments // #define WCASSERT_PREFIX(Assertion,bufferSize) if(!(Assertion)){char buffer[bufferSize]; #define xASSERT_FORMAT_STRING(Assertion) "%s :\n\t Assertion \"" #Assertion "\" failed \n\t : %s : " //#define xASSERT_FORMAT_OPERATION(Assertion,postMsg,PostAction) _snprintf(buffer,D_MSG_BUFFER_MAX,xASSERT_FORMAT_STRING_PA(Assertion,PostAction),D_SO_NAME,xSTR_MERGE(postMsg,PostAction)); #define xASSERT_FORMAT_OPERATION_EX(Assertion,SourceObjectName,PostMessage,PostAction) _snprintf(buffer,D_MSG_BUFFER_MAX,xASSERT_FORMAT_STRING(Assertion),SourceObjectName, \ xSTR_MERGE(PostMessage,xSTR_MERGE(" , excecuting : ",#PostAction))); //---------------------------------------------------------------- // // constants // #if D_FILE_INFO==1 #define xASSERT_FORMAT_STRING(A) "%s :\n\t Assertion2 \"" #A "\" failed in \n\t : (%s:%d) :\n\t %s " // \"" #B "\" " #define xASSERT_FORMAT_OPERATION_EX(Assertion,SourceObjectName,PostMessage,PostAction) _snprintf(buffer,D_MSG_BUFFER_MAX,xASSERT_FORMAT_STRING(Assertion),SourceObjectName,__FILE__,__LINE__, \ xSTR_MERGE(PostMessage,xSTR_MERGE(" , excecuting : ",#PostAction))); #endif #define WIDEN2(x) L ## x #define WIDEN(x) WIDEN2(x) #define __WFILE__ WIDEN(__FILE__) #define AMACRO( object_name, var_name ) reinterpret_cast<int>((&(((object_name*)0)->var_name))) #define xAssertWPO(Assertion) xVerify(Assertion) #define REFRESH_ASSERT_HANDLER(Type,Assertion,PostMessage,PostAction,Result) updateAssertHandlerData(Type,#Assertion,__FILE__,__LINE__,PostMessage,((void*)(PostAction)),Result); //---------------------------------------------------------------- // // macros to make an assert, error warning message, and providing a field to correct data // // prepare meta data : #define CREATE_ASSERT_INFO_EX(Assertion,Type,FormatString,SourceObjectName,PostMessage,PostAction) WCASSERT_PREFIX(Assertion,D_MSG_BUFFER_MAX) \ xASSERT_FORMAT_OPERATION_EX(Assertion,SourceObjectName,PostMessage,PostAction); #define xwASSERTEx(Assertion,SourceObjectName,PostMessage,PostAction,Result) CREATE_ASSERT_INFO_EX(Assertion,AFS_ASSERT,xASSERT_FORMAT_STRING(Assertion),SourceObjectName,PostMessage,PostAction,Result); //REFRESH_ASSERT_HANDLER(AFS_ASSERT,Assertion,buffer,PostAction,Result); #define __xwASSERT(Assertion,SourceObjectName,PostMessage,PostAction,Result) xwASSERTEx(Assertion,SourceObjectName,PostMessage,PostAction,Result) #define xAssertW(Assertion,PostAction,PostMessage,SourceObjectName,Result) \ __xwASSERT(Assertion,SourceObjectName,PostMessage,PostAction,Result) \ _xAssertHandler(Assertion); \ D_ASSERT_P_END(PostAction) \ Result = false; \ } /* #define xAssertW(Assertion,PostAction,PostMessage,SourceObjectName,Result) \ __xwASSERT(Assertion,SourceObjectName,PostMessage,PostAction,Result) \ xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"start assert");\ (false || (Assertion) || (xAssertionEx::getErrorHandler() && (xAssertionEx::getErrorHandler()\ ( AFS_ASSERT, #Assertion, __FILE__, __LINE__,"asdasd",NULL,TRUE), true)));\ xAssertInfo *info = assertFailed();\ if(info ){\ xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"assert failed");\ D_ASSERT_P_END(PostAction) \ Result = false; } \ }*/ /* _xAssertHandler(Assertion); \ xAssertInfo *info = assertFailed();\ if(info ){\ xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"assert failed");\ D_ASSERT_P_END(PostAction) \ Result = false; } \ } */ #define iAssertW(Assertion,PostAction,PostMessage)\ { bool returnValue = false;\ xAssertW(Assertion,PostAction,PostMessage,D_SO_NAME,returnValue)\ } #define iAssertWR(Assertion,PostAction,Result){\ xAssertW(Assertion,PostAction,"",D_SO_NAME,Result)\ } #define iAssertW1(Assertion,PostAction)\ { bool returnValue = false;\ iAssertW(Assertion,PostAction,"")\ } #define iAssertAndAbortMesg(Assertion,Msg)\ { bool returnValue = false;\ iAssertW(Assertion,NULL,Msg);\ if(!returnValue)return;\ } #define iAssertAndAbort1(Assertion,POSTACTION)\ { bool returnValue = false;\ iAssertW(Assertion,POSTACTION,"");\ if(!returnValue)return;\ } #define xError(Message) xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,Message); #define xWarning(Message) xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,Message); #define xTrace(Message) xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,Message); #define xInfo(Message) xLogger::xLog(XL_START,ELOGINFO,E_LI_MANAGER,Message); void _inline qdbg(const char *fmt,...) { char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, fmt ); _vsnprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, fmt, s); va_end(s); xLogger::xLog(XL_START,ELOGINFO,E_LI_MANAGER,buffer); } #define xTrace1(Message,Object) { char buffer[D_MSG_BUFFER_MAX];\ _snprintf(buffer,Message,Object ? Object->GetName() : "");\ xTrace(buffer)\ } //#define iAssertWR(Assertion,PostAction,Result) xVerify(Assertion) //#define iAssertW1(Assertion,PostAction) xVerify(Assertion) //(xAssertionEx::getErrorHandler() && (xAssertionEx::getErrorHandler()( AFS_ASSERT, #Assertion, __FILE__, __LINE__,"","",FALSE), true))) //xVerify(Assertion); //xVerify(Assertion) //xASSERT_FORMAT_OPERATION(Condition,postMsg) \ //D_ASSERT_P_END(postStep) } //#define D_VERIFY_O(Condition,obj,postMsg) WASSERT_VERIFY_PREFIX(Condition,D_MSG_BUFFER_MAX) //#define D_VERIFY_CORRECT_MOP(Condition) WASSERT_VERIFY_AND_CORRECT_PREFIX(Condition) //xASSERT_FORMAT_OPERATION(Condition,postMsg); //,postMsg,postStep,Result //if(!(Condition)){char buffer[bufferSize]; //char buffer[bufferSize]; //#define WASSERT_CHECK_PREFIX(Condition,bufferSize) xCheck(Condition); //char buffer[bufferSize]; //---------------------------------------------------------------- // // !assert(a) ? : print warning, do post step // // #define xWASSERT_O_P(Condition,obj,postMsg,postStep) WCASSERT_PREFIX(Condition,D_MSG_BUFFER_MAX)\ xASSERT_FORMAT_OPERATION(Condition,postMsg) \ D_ASSERT_P_END(postStep) } //---------------------------------------------------------------- // // !assert(condition)? print warning and leave // #define D_WASSERTION_O(Condition,obj,postMsg) WASSERT_CHECK_PREFIX(Condition,D_MSG_BUFFER_MAX) \ xASSERT_FORMAT_OPERATION(Condition,postMsg); #define D_CHECK_O(Condition,obj,postMsg) WASSERT_CHECK_PREFIX(Condition,D_MSG_BUFFER_MAX) //xASSERT_FORMAT_OPERATION(Condition,postMsg); /*D_ASSERT_P_END(postStep) }*/ //---------------------------------------------------------------- // // !assert(condition)? print warning and leave // /* #define eAssertCheckMO(cond,obj,postMsg) WASSERT_CHECK_PREFIX(cond,D_MSG_BUFFER_MAX)\ xASSERT_FORMAT_OPERATION(cond,postMsg) \ D_ASSERT_P_END(postStep) } */ #endif //D_FILE_INFO //#endif//file <file_sep>#ifndef __VSL_GLOBAL_FUNCTIONS_H__ #define __VSL_GLOBAL_FUNCTIONS_H__ #include "vtPhysXBase.h" /************************************************************************************************/ /** @name Joints */ //@{ /** \brief Quick access for #PhysicManager::getJoint \return pJoint* @see */ pJoint*getJoint(CK3dEntity *referenceA,CK3dEntity *referenceB=NULL,JType type= JT_Any); //@} #endif<file_sep>/******************************************************************** created: 2009/02/17 created: 17:2:2009 8:23 filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\xBaseTypes.h file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common file base: xBaseTypes file ext: h author: <NAME> purpose: Type definitions, Arrays, ... *********************************************************************/ #ifndef __X_BASE_TYPES_H__ #define __X_BASE_TYPES_H__ //################################################################ // // Float, Integers, Boolean // #ifndef u32 typedef unsigned int u32; #endif namespace xBase { typedef float xReal32; typedef int xS32; typedef unsigned int xU32; typedef bool xBool; typedef unsigned short xU16; } using xBase::xS32; using xBase::xU32; using xBase::xReal32; using xBase::xBool; using xBase::xU16; //################################################################ // // Containers // #include<stdlib.h> #include <map> #include <vector> #endif // __XBASETYPES_H__<file_sep>project( NxuStreamLib ) add_subdirectory (./) include_directories( ../../include/Physics ../../include/ageia ../../src/NXStream ) add_definitions( -DMODULE_BASE_EXPORTS -DNOMINMAX -DVIRTOOLS_MODULE -DVIRTOOLS_USER_SDK -DWIN32 -D_CRT_SECURE_NO_DEPRECATE -D_DEBUG -D_USRDLL ) add_library( NxuStreamLib STATIC ${SOURCES} ) <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPMaterialIteratorDecl(); CKERROR CreatePMaterialIteratorProto(CKBehaviorPrototype **pproto); int PMaterialIterator(const CKBehaviorContext& behcontext); CKERROR PMaterialIteratorCB(const CKBehaviorContext& behcontext); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; enum bInputs { I_XML, I_DFRICTION, I_SFRICTION, I_RES, I_DFRICTIONV, I_SFRICTIONV, I_ANIS, I_FCMODE, I_RCMODE, I_FLAGS, }; enum bOutputs { O_INDEX, O_XML, O_NAME, O_DFRICTION, O_SFRICTION, O_RES, O_DFRICTIONV, O_SFRICTIONV, O_ANIS, O_FCMODE, O_RCMODE, O_FLAGS, O_MATERIAL, }; CKERROR PMaterialIteratorCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKContext *ctx = beh->GetCKContext(); switch(behcontext.CallbackMessage) { case CKM_BEHAVIORLOAD: case CKM_BEHAVIORATTACH: { break; } case CKM_BEHAVIORSETTINGSEDITED: { } } return CKBR_OK; } //************************************ // Method: FillBehaviorPMaterialIteratorDecl // FullName: FillBehaviorPMaterialIteratorDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration*FillBehaviorPMaterialIteratorDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PMaterialIterator"); od->SetCategory("Physic/Body"); od->SetDescription("Attaches and/or modifies the physic material of a rigid body or its sub shape"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x121d1c0f,0x65a62e73)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePMaterialIteratorProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePMaterialIteratorProto // FullName: CreatePMaterialIteratorProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePMaterialIteratorProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PMaterialIterator"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Next"); proto->DeclareOutput("Finish"); proto->DeclareOutput("Loop"); proto->DeclareLocalParameter("current result", CKPGUID_POINTER, "0"); proto->DeclareOutParameter("Index",CKPGUID_INT); proto->DeclareOutParameter("XML Link",VTE_XML_MATERIAL_TYPE); proto->DeclareOutParameter("Name",CKPGUID_STRING); proto->DeclareOutParameter("Dynamic Friction",CKPGUID_FLOAT); proto->DeclareOutParameter("Static Friction",CKPGUID_FLOAT); proto->DeclareOutParameter("Restitution",CKPGUID_FLOAT); proto->DeclareOutParameter("Dynamic Friction V",CKPGUID_FLOAT); proto->DeclareOutParameter("Static Friction V",CKPGUID_FLOAT); proto->DeclareOutParameter("Direction of Anisotropy ",CKPGUID_VECTOR); proto->DeclareOutParameter("Friction Combine Mode",VTE_MATERIAL_COMBINE_MODE); proto->DeclareOutParameter("Restitution Combine Mode",VTE_MATERIAL_COMBINE_MODE); proto->DeclareOutParameter("Flags",VTF_MATERIAL_FLAGS); proto->DeclareOutParameter("Result",VTS_MATERIAL); proto->SetBehaviorCallbackFct( PMaterialIteratorCB ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PMaterialIterator); *pproto = proto; return CK_OK; } //************************************ // Method: PMaterialIterator // FullName: PMaterialIterator // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ typedef std::vector<NxMaterial*>LMaterials; int PMaterialIterator(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //we reset our session counter int sessionIndex=-1; beh->SetOutputParameterValue(0,&sessionIndex); LMaterials*sResults = NULL; beh->GetLocalParameterValue(0,&sResults); if (!sResults) { sResults = new LMaterials(); }else sResults->clear(); NxScene * scene = GetPMan()->getDefaultWorld()->getScene(); for(int i = 0 ; i < GetPMan()->getDefaultWorld()->getScene()->getNbMaterials() ; i ++) { NxMaterial *currentMaterial = scene->getMaterialFromIndex(i); sResults->push_back(currentMaterial); } beh->SetLocalParameterValue(0,&sResults); if (sResults->size()) { beh->ActivateInput(1); }else { beh->ActivateOutput(0); return 0; } } if( beh->IsInputActive(1) ) { beh->ActivateInput(1,FALSE); int currentIndex=0; CKParameterOut *pout = beh->GetOutputParameter(0); pout->GetValue(&currentIndex); currentIndex++; LMaterials *sResults = NULL; beh->GetLocalParameterValue(0,&sResults); if (!sResults) { beh->ActivateOutput(0); return 0; } if (currentIndex>=sResults->size()) { sResults->clear(); beh->ActivateOutput(0); return 0; } NxMaterial * material = sResults->at(currentIndex); if (material!=NULL) { int sIndex = currentIndex+1; beh->SetOutputParameterValue(0,&sIndex); //SetOutputParameterValue<int>(beh,O_XML,material->xmlLinkID); SetOutputParameterValue<float>(beh,O_DFRICTION,material->getDynamicFriction()); SetOutputParameterValue<float>(beh,O_SFRICTION,material->getStaticFriction()); SetOutputParameterValue<float>(beh,O_RES,material->getRestitution()); SetOutputParameterValue<float>(beh,O_DFRICTIONV,material->getDynamicFrictionV()); SetOutputParameterValue<float>(beh,O_SFRICTIONV,material->getStaticFrictionV()); SetOutputParameterValue<VxVector>(beh,O_ANIS,getFrom(material->getDirOfAnisotropy())); SetOutputParameterValue<int>(beh,O_FCMODE,material->getFrictionCombineMode()); SetOutputParameterValue<int>(beh,O_RCMODE,material->getFrictionCombineMode()); SetOutputParameterValue<int>(beh,O_FLAGS,material->getFlags()); } if(material->userData ) { pMaterial *bMaterial = static_cast<pMaterial*>(material->userData); if (bMaterial && bMaterial->xmlLinkID ) { int xid = bMaterial->xmlLinkID; XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,xid); CKParameterOut *nameStr = beh->GetOutputParameter(O_NAME); nameStr->SetStringValue(nodeName.Str()); } } //pFactory::Instance()->copyTo(beh->GetOutputParameter(O_MATERIAL),material); beh->ActivateOutput(0); } return 0; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtStructHelper.h" #define PHYSIC_JOINT_CAT "Physic Constraints" using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; StructurMember myStructJBall[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Limit Swing Axis","0,0,0"), STRUCT_ATTRIBUTE(VTE_JOINT_PROJECTION_MODE,"Projection Mode","None"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Projection Distance","0.0"), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision","TRUE"), STRUCT_ATTRIBUTE(VTS_JLIMIT,"Swing Limit","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(VTS_JLIMIT,"Twist High Limit ","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(VTS_JLIMIT,"Twist Low Limit ","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Swing Spring","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Twist Spring","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Joint Spring","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), }; StructurMember myStructJDistance[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Local 0 Anchor","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Local 0 Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Local 1 Anchor","0,0,0.0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Local 1 Reference","pDefaultWorld"), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision","TRUE"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Minimum Distance","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Distance","0.0"), STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Spring","0.0f,0.0f,0.0f"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), }; StructurMember myStructJFixed[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), }; StructurMember JPrismaticMemberTable[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), }; StructurMember JCylindricalMemberTable[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), }; StructurMember JPointInPlaneMemberTable[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), }; StructurMember JPointOnLineMemberTable[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), }; StructurMember JRevoluteMemberTable[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision","TRUE"), STRUCT_ATTRIBUTE(VTE_JOINT_PROJECTION_MODE,"Projection Mode","None"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Projection Distance","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Projection Angle","0.3"), STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Spring","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(VTS_JLIMIT,"Limit High","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(VTS_JLIMIT,"Limit Low","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(VTS_JOINT_MOTOR,"Motor","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), }; StructurMember JLimitPlaneMemberTable[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(VTE_JOINT_TYPE,"Target Joint Type","JT_Any"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Restitution","0.0f"), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Point is on Body","False"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Limit Point",""), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Limit Point Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Normal",""), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Normal Up Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Point in Plane",""), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Point in Plane Reference",""), }; StructurMember JD6Members[] = { STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), STRUCT_ATTRIBUTE(VTF_JOINT_D6_AXIS_MASK,"Axis Mask",""), STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"X",""), STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Y",""), STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Z",""), STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Swing 1",""), STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Swing 2",""), STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Twist Low",""), STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Twist High",""), }; StructurMember JD6AxisItem[] = { STRUCT_ATTRIBUTE(VTE_JOINT_MOTION_MODE_AXIS,"Axis","X"), STRUCT_ATTRIBUTE(VTS_JOINT_SLIMIT,"Limit",""), }; #define gSMapJDistance myStructJDistance #define gSMapJFixed myStructJFixed #define gSMapJBall myStructJBall #define gSMapJPrismatic JPrismaticMemberTable #define gSMapJRevolute JRevoluteMemberTable #define gSMapJCylindrical JCylindricalMemberTable #define gSMapJPointInPlane JPointInPlaneMemberTable #define gSMapJPointOnLine JPointOnLineMemberTable #define gSMapJLimitPlane JLimitPlaneMemberTable extern void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); void PhysicManager::_RegisterJointParameters() { CKParameterManager *pm = m_Context->GetParameterManager(); CKAttributeManager* attman = m_Context->GetAttributeManager(); //---------------------------------------------------------------- // // D6 Help Structures // pm->RegisterNewEnum(VTE_JOINT_MOTION_MODE,"pJMotionMode","Locked=0,Limited=1,Free=2"); pm->RegisterNewStructure(VTS_JOINT_SLIMIT,"pJD6SLimit","Damping,Spring,Value,Restitution",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_ANGLE,CKPGUID_FLOAT); //---------------------------------------------------------------- // // Types for D6 - Joint - Attribute only : // //SetWindowLong(m_hWnd,GWL_USERDATA,(LONG)this_mod); // set our user data to a "this" pointer /* pm->RegisterNewEnum(VTF_JOINT_D6_AXIS_MASK,"pD6AxisMask","X=1,Y=2,Z=4,Swing1=8,Swing2=16,Twist Low=32,Twist High=64"); REGISTER_CUSTOM_STRUCT("pJD6AxisItem",PS_D6_AXIS_ITEM,VTS_JOINT_D6_AXIS_ITEM,JD6AxisItem,TRUE); REGISTER_CUSTOM_STRUCT("pJD6",PS_D6,VTS_JOINT_D6,JD6Members,TRUE); REGISTER_STRUCT_AS_ATTRIBUTE("pJD6",PS_D6,PHYSIC_JOINT_CAT,VTS_JOINT_D6,CKCID_BEOBJECT,JD6Members,true,attRef); */ int attRef=0; pm->RegisterNewEnum(VTE_JOINT_TYPE,"pJointType","None=-1,Prismatic=0,Revolute=1,Cylindrical=2,Spherical=3,Point On Line=4,Point In Plane=5,Distance=6,Pulley=7,Fixed=8,D6=9"); pm->RegisterNewEnum(VTE_PHYSIC_JDRIVE_TYPE,"pJD6DriveType","Disabled=0,Position=1,Velocity=2"); pm->RegisterNewStructure(VTS_JOINT_DRIVE,"pJD6Drive","Damping,Spring,Force Limit,Drive Type",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,VTE_PHYSIC_JDRIVE_TYPE); pm->RegisterNewStructure(VTS_JOINT_SPRING,"pJSpring","Damper,Spring,Target Value",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT); pm->RegisterNewStructure(VTS_JLIMIT,"pJLimit","Value,Restitution,Hardness",CKPGUID_ANGLE,CKPGUID_FLOAT,CKPGUID_FLOAT); pm->RegisterNewEnum(VTE_JOINT_MOTION_MODE_AXIS,"pJD6Axis","Twist=0,Swing1=1,Swing2=2,X=3,Y=4,Z=5"); pm->RegisterNewEnum(VTE_JOINT_DRIVE_AXIS,"pJD6DriveAxis","Twist=0,Swing=1,Slerp=2,X=3,Y=4,Z=5"); pm->RegisterNewEnum(VTE_JOINT_LIMIT_AXIS,"pJD6LimitAxis","Linear=0,Swing1=1,Swing2,Twist High,Twist Low"); pm->RegisterNewEnum(VTE_JOINT_PROJECTION_MODE,"pJProjectionMode","None=0,Point MinDist=1,Linear MindDist"); pm->RegisterNewStructure(VTS_JOINT_MOTOR,"pJMotor","Target Velocity,Maximum Force,Free Spin",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_BOOL); REGISTER_CUSTOM_STRUCT("pJDistance",PS_JDISTANCE_MEMBERS,VTS_JOINT_DISTANCE,gSMapJDistance,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pJDistance",PS_JDISTANCE_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_DISTANCE,CKCID_3DOBJECT,gSMapJDistance,true,attRef); REGISTER_CUSTOM_STRUCT("pJFixed",PS_JFIXED_MEMBERS,VTS_JOINT_FIXED,gSMapJFixed,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pJFixed",PS_JFIXED_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_FIXED,CKCID_3DOBJECT,gSMapJFixed,true,attRef); REGISTER_CUSTOM_STRUCT("pJBall",PS_JBALL_MEMBERS,VTS_JOINT_BALL,gSMapJBall,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pJBall",PS_JBALL_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_BALL,CKCID_3DOBJECT,gSMapJBall,true,attRef); REGISTER_CUSTOM_STRUCT("pJPrismatic",PS_JPRISMATIC_MEMBERS,VTS_JOINT_PRISMATIC ,gSMapJPrismatic,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pJPrismatic",PS_JPRISMATIC_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_PRISMATIC ,CKCID_BEOBJECT,gSMapJPrismatic,true,attRef); REGISTER_CUSTOM_STRUCT("pJCylindrical",PS_JCYLINDRICAL_MEMBERS,VTS_JOINT_CYLINDRICAL,gSMapJCylindrical,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pJCylindrical",PS_JCYLINDRICAL_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_CYLINDRICAL,CKCID_BEOBJECT,gSMapJCylindrical,true,attRef); REGISTER_CUSTOM_STRUCT("pJRevolute",PS_JREVOLUTE,VTS_JOINT_REVOLUTE,gSMapJRevolute,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pJRevolute",PS_JREVOLUTE,PHYSIC_JOINT_CAT,VTS_JOINT_REVOLUTE ,CKCID_BEOBJECT,gSMapJRevolute,true,attRef); REGISTER_CUSTOM_STRUCT("pJPointInPlane",PS_JPOINT_IN_PLANE_MEMBERS,VTS_JOINT_POINT_IN_PLANE,gSMapJPointInPlane,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pJPointInPlane",PS_JPOINT_IN_PLANE_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_POINT_IN_PLANE,CKCID_BEOBJECT,gSMapJPointInPlane,true,attRef); REGISTER_CUSTOM_STRUCT("pJPointOnLine",PS_JPOINT_ON_LINE_MEMBERS,VTS_JOINT_POINT_ON_LINE,gSMapJPointOnLine,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pJPointOnLine",PS_JPOINT_ON_LINE_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_POINT_ON_LINE,CKCID_BEOBJECT,gSMapJPointOnLine,true,attRef); REGISTER_CUSTOM_STRUCT("pJLimitPlane",PS_JLIMIT_PLANE_MEMBERS,VTS_PHYSIC_JLIMIT_PLANE,gSMapJLimitPlane,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pJLimitPlane",PS_JLIMIT_PLANE_MEMBERS,PHYSIC_JOINT_CAT,VTS_PHYSIC_JLIMIT_PLANE,CKCID_BEOBJECT,gSMapJLimitPlane,true,attRef); populateAttributeFunctions(); _RegisterAttributeCallbacks(); } <file_sep> /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* */ /* D L L */ /* */ /* W I N D O W S */ /* */ /* P o u r A r t h i c */ /* */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* Cette partie décrit les codes de retour du serveur vers le client Ils sont disponibles dans le RFC numéro 959 FILE TRANSFER PROTOCOL En voici un extrait */ /* RFC 959 October 1985 File Transfer Protocol 4.2.2 Numeric Order List of Reply Codes 110 Restart marker reply. In this case, the text is exact and not left to the particular implementation; it must read: MARK yyyy = mmmm Where yyyy is User-process data stream marker, and mmmm server's equivalent marker (note the spaces between markers and "="). 120 Service ready in nnn minutes. 125 Data connection already open; transfer starting. 150 File status okay; about to open data connection. 200 Command okay. 202 Command not implemented, superfluous at this site. 211 System status, or system help reply. 212 Directory status. 213 File status. 214 Help message. On how to use the server or the meaning of a particular non-standard command. This reply is useful only to the human user. 215 NAME system type. Where NAME is an official system name from the list in the Assigned Numbers document. 220 Service ready for new user. 221 Service closing control connection. Logged out if appropriate. 225 Data connection open; no transfer in progress. 226 Closing data connection. Requested file action successful (for example, file transfer or file abort). 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). 230 User logged in, proceed. 250 Requested file action okay, completed. 257 "PATHNAME" created. 331 User name okay, need password. 332 Need account for login. 350 Requested file action pending further information. 421 Servlosing control connection. This may be a reply to any command if the service knows it must shut down. 425 Can't open data connection. 426 Connection closed; transfer aborted. 450 Requested file action not taken. File unavailable (e.g., file busy). 451 Requested action aborted: local error in processing. 452 Requested action not taken. Insufficient storage space in system. 500 Syntax error, command unrecognized. This may include errors such as command line too long. 501 Syntax error in parameters or arguments. 502 Command not implemented. 503 Bad sequence of commands. 504 Command not implemented for that parameter. 530 Not logged in. 532 Need account for storing files. 550 Requested action not taken. File unavailable (e.g., file not found, no access). 551 Requested action aborted: page type unknown. 552 Requested file action aborted. Exceeded storage allocation (for current directory or dataset). 553 Requested action not taken. File name not allowed. */ #define RFC_CMDOK 200 #define RFC_DATACONNECTIONCLOSED 226 #define RFC_USERLOGGEDIN 230 #define RFC_FILEACTIONOK 250 #define RFC_BADPARAMETERS 501 #define RFC_NOTIMPLEMENTED 502 #define RFC_NOTCONNECTED 530 #define RFC_FILEUNAVAILABLE 550 #define RFC_FILEACTIONABORTED 552 #define RFC_BADFILENAME 553<file_sep>#if !defined(CUSTOMPLAYERSTATICDLLS_H) #define CUSTOMPLAYERSTATICDLLS_H #if defined(CUSTOM_PLAYER_STATIC) #ifdef WIN32 #define CDECL_CALL __cdecl #else #define CDECL_CALL #endif //----- Registration functions inline void CustomPlayerRegisterRenderEngine(CKPluginManager& iPluginManager); inline void CustomPlayerRegisterReaders(CKPluginManager& iPluginManager); inline void CustomPlayerRegisterManagers(CKPluginManager& iPluginManager); inline void CustomPlayerRegisterBehaviors(CKPluginManager& iPluginManager); //----- Behaviors inline void Register3DTransfoBehaviors(CKPluginManager& iPluginManager); inline void RegisterBBAddonsBehaviors(CKPluginManager& iPluginManager); inline void RegisterBBAddons2Behaviors(CKPluginManager& iPluginManager); inline void RegisterCamerasBehaviors(CKPluginManager& iPluginManager); inline void RegisterCharactersBehaviors(CKPluginManager& iPluginManager); inline void RegisterCollisionsBehaviors(CKPluginManager& iPluginManager); inline void RegisterControllersBehaviors(CKPluginManager& iPluginManager); inline void RegisterGridsBehaviors(CKPluginManager& iPluginManager); inline void RegisterInterfaceBehaviors(CKPluginManager& iPluginManager); inline void RegisterLightsBehaviors(CKPluginManager& iPluginManager); inline void RegisterLogicsBehaviors(CKPluginManager& iPluginManager); inline void RegisterMaterialsBehaviors(CKPluginManager& iPluginManager); inline void RegisterMeshesBehaviors(CKPluginManager& iPluginManager); inline void RegisterMidiBehaviors(CKPluginManager& iPluginManager); inline void RegisterNarrativesBehaviors(CKPluginManager& iPluginManager); inline void RegisterParticleSystemsBehaviors(CKPluginManager& iPluginManager); inline void RegisterShaderBehaviors(CKPluginManager& iPluginManager); inline void RegisterSoundsBehaviors(CKPluginManager& iPluginManager); inline void RegisterVSLBehaviors(CKPluginManager& iPluginManager); inline void RegisterVideoBehaviors(CKPluginManager& iPluginManager); inline void RegisterVisualsBehaviors(CKPluginManager& iPluginManager); inline void RegisterWorldEnvBehaviors(CKPluginManager& iPluginManager); // network inline void RegisterNetworkBehaviors(CKPluginManager& iPluginManager); inline void RegisterNetworkServerBehaviors(CKPluginManager& iPluginManager); inline void RegisterMultiPlayerBehaviors(CKPluginManager& iPluginManager); inline void RegisterDownloadBehaviors(CKPluginManager& iPluginManager); inline void RegisterDatabaseBehaviors(CKPluginManager& iPluginManager); inline void RegisterCryptoBehaviors(CKPluginManager& iPluginManager); // physics inline void RegisterPhysicsBehaviors(CKPluginManager& iPluginManager); //----- Managers inline void RegisterParamOpManager(CKPluginManager& iPluginManager); inline void RegisterInputManager(CKPluginManager& iPluginManager); inline void RegisterSoundManager(CKPluginManager& iPluginManager); inline void RegisterCKFEMgrManager(CKPluginManager& iPluginManager); inline void RegisterVideoManager(CKPluginManager& iPluginManager); inline void RegisterDX8VideoManager(CKPluginManager& iPluginManager); inline void RegisterDX9VideoManager(CKPluginManager& iPluginManager); //----- Readers inline void RegisterVirtoolsReader(CKPluginManager& iPluginManager); inline void RegisterImageReader(CKPluginManager& iPluginManager); inline void RegisterAVIReader(CKPluginManager& iPluginManager); inline void RegisterPNGReader(CKPluginManager& iPluginManager); inline void RegisterJPGReader(CKPluginManager& iPluginManager); inline void RegisterWAVReader(CKPluginManager& iPluginManager); inline void RegisterTIFFReader(CKPluginManager& iPluginManager); //----------------------------------------------------------- // When behaviors and plugins are compiled in a static library : // List of declaration functions for every possible plugins... struct CKRasterizerInfo; struct CKPluginInfo; class CKDataReader; /******************************************* + There is only one function a rasterizer Dll is supposed to export :"CKRasterizerGetInfo", it will be used by the render engine to retrieve information about the plugin : - Description ******************************************/ typedef void (*CKRST_GETINFO)(CKRasterizerInfo*); /***************************************************/ /**** RENDER ENGINE ********************************/ CKPluginInfo* CDECL_CALL CK2_3DGetPluginInfo(int Index); /***************************************************/ /***** RASTERIZERS *********************************/ void CDECL_CALL CKDX7RasterizerGetInfo(CKRasterizerInfo* Info); void CDECL_CALL CKDX8RasterizerGetInfo(CKRasterizerInfo* Info); void CDECL_CALL CKDX9RasterizerGetInfo(CKRasterizerInfo* Info); void CDECL_CALL CKGL15RasterizerGetInfo(CKRasterizerInfo* Info); /***************************************************/ /**** READERS **************************************/ //---- Virtools Reader (4) CKPluginInfo* CDECL_CALL CKGetVirtoolsPluginInfo(int index); CKDataReader* CDECL_CALL CKGetVirtoolsReader(int index); //---- Image Reader (3) CKPluginInfo* CDECL_CALL CKGet_ImageReader_PluginInfo(int index); CKDataReader* CDECL_CALL CKGet_ImageReader_Reader(int pos); //---- Avi Reader (1) CKPluginInfo* CDECL_CALL CKGet_AviReader_PluginInfo(int index); CKDataReader* CDECL_CALL CKGet_AviReader_Reader(int pos); //---- PNG Reader (1) CKPluginInfo* CDECL_CALL CKGet_PngReader_PluginInfo(int index); CKDataReader* CDECL_CALL CKGet_PngReader_Reader(int pos); //---- JPG Reader (1) CKPluginInfo* CDECL_CALL CKGet_JpgReader_PluginInfo(int index); CKDataReader* CDECL_CALL CKGet_JpgReader_Reader(int pos); //---- Wav Reader (3) CKPluginInfo* CDECL_CALL CKGet_WavReader_PluginInfo(int index); CKDataReader* CDECL_CALL CKGet_WavReader_Reader(int pos); //---- Tif Reader (1) CKPluginInfo* CDECL_CALL CKGet_TifReader_PluginInfo(int index); CKDataReader* CDECL_CALL CKGet_TifReader_Reader(int pos); /***************************************************/ /**** EXTENSIONS ***********************************/ CKPluginInfo* CDECL_CALL CKGet_ParamOp_PluginInfo(int Index); /***************************************************/ /**** MANAGERS ***********************************/ CKPluginInfo* CDECL_CALL CKGet_InputManager_PluginInfo(int Index); CKPluginInfo* CDECL_CALL CKGet_SoundManager_PluginInfo(int Index); CKPluginInfo* CDECL_CALL CKGet_VideoManager_PluginInfo(int Index); CKPluginInfo* CDECL_CALL CKGet_CKFEMgr_PluginInfo(int Index); CKPluginInfo* CDECL_CALL CKGet_Dx8VideoManager_PluginInfo(int Index); CKPluginInfo* CDECL_CALL CKGet_Dx9VideoManager_PluginInfo(int Index); void CDECL_CALL Register_Dx8VideoManager_BehaviorDeclarations(XObjectDeclarationArray *reg); void CDECL_CALL Register_Dx9VideoManager_BehaviorDeclarations(XObjectDeclarationArray *reg); /***************************************************/ /**** BEHAVIORS ***********************************/ //--- 3D Transfo (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_3DTransfo_PluginInfo(int index); void CDECL_CALL Register_3DTransfo_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ BuildingBlock Addons (1 : Beh) CKPluginInfo* CDECL_CALL CKGet_BBAddons_PluginInfo(int Index); void CDECL_CALL Register_BBAddons_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ BuildingBlock Addons 2 (1 : Beh) CKPluginInfo* CDECL_CALL CKGet_BBAddons2_PluginInfo(int Index); void CDECL_CALL Register_BBAddons2_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ Cameras (1 : Beh) CKPluginInfo* CDECL_CALL CKGet_Cameras_PluginInfo(int Index); void CDECL_CALL Register_Cameras_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ Controllers (1 : Beh) CKPluginInfo* CDECL_CALL CKGet_Controllers_PluginInfo(int Index); void CDECL_CALL Register_Controllers_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ Characters (1 : Beh) CKPluginInfo* CDECL_CALL CKGet_Characters_PluginInfo(int Index); void CDECL_CALL Register_Characters_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ Collisions (1: Coll Manager, 2 : Floor Manager , 3 : Beh) CKPluginInfo* CDECL_CALL CKGet_Collisions_PluginInfo(int Index); void CDECL_CALL Register_Collisions_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Grids (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_Grids_PluginInfo(int index); void CDECL_CALL Register_Grids_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Interface (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_Interface_PluginInfo(int index); void CDECL_CALL Register_Interface_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ Lights (1 : Beh) CKPluginInfo* CDECL_CALL CKGet_Lights_PluginInfo(int Index); void CDECL_CALL Register_Lights_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ Logics (1 : Beh) CKPluginInfo* CDECL_CALL CKGet_Logics_PluginInfo(int Index); void CDECL_CALL Register_Logics_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ Materials (1 : Beh) CKPluginInfo* CDECL_CALL CKGet_Materials_PluginInfo(int Index); void CDECL_CALL Register_Materials_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Meshes (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_MeshModifiers_PluginInfo(int Index); void CDECL_CALL Register_MeshModifiers_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Midi (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_MidiBehaviors_PluginInfo(int Index); void CDECL_CALL Register_MidiBehaviors_BehaviorDeclarations(XObjectDeclarationArray *reg); //------ Narratives (1 : Beh) CKPluginInfo* CDECL_CALL CKGet_Narratives_PluginInfo(int Index); void CDECL_CALL Register_Narratives_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Particles (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_Particles_PluginInfo(int Index); void CDECL_CALL Register_Particles_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Physics (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_Physics_PluginInfo(int Index); void CDECL_CALL Register_Physics_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Sounds (1: Beh) CKPluginInfo* CDECL_CALL CKGet_Sounds_PluginInfo(int Index); void CDECL_CALL Register_Sounds_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Visuals (1: Beh) CKPluginInfo* CDECL_CALL CKGet_Visuals_PluginInfo(int Index); void CDECL_CALL Register_Visuals_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- World Env (1: Beh) CKPluginInfo* CDECL_CALL CKGet_WorldEnvironment_PluginInfo(int Index); void CDECL_CALL Register_WorldEnvironment_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- VSManager (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_VSManager_PluginInfo(int Index); void CDECL_CALL Register_VSManager_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- VSServerManager (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_VSServerManager_PluginInfo(int Index); void CDECL_CALL Register_VSServerManager_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- MultiPlayer (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_MP_PluginInfo(int Index); void CDECL_CALL Register_MP_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- DownloadMedia (1: Beh) CKPluginInfo* CDECL_CALL CKGet_DLM_PluginInfo(int Index); void CDECL_CALL Register_DLM_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Database (1: Beh) CKPluginInfo* CDECL_CALL CKGet_DBC_PluginInfo(int Index); void CDECL_CALL Register_DBC_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- VSLManager (1: Beh, 2 : Manager) CKPluginInfo* CDECL_CALL CKGet_VSLManager_PluginInfo(int Index); void CDECL_CALL Register_VSLManager_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- ShaderManager ( 1 : Manager, 2 : Beh) CKPluginInfo* CDECL_CALL CKGet_Shaders_PluginInfo(int Index); void CDECL_CALL Register_Shaders_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- CryptedLoader (1: Beh) CKPluginInfo* CDECL_CALL CKGet_CryptedLoader_PluginInfo(int Index); void CDECL_CALL Register_CryptedLoader_BehaviorDeclarations(XObjectDeclarationArray *reg); //--- Video (1: Beh) CKPluginInfo* CDECL_CALL CKGet_Video_PluginInfo(int Index); void CDECL_CALL Register_Video_BehaviorDeclarations(XObjectDeclarationArray *reg); //--------------------- Implementation -------------------------------------// //--------------------- of -------------------------------------// //--------------------- registration functions -----------------------------// /**************************************************************************** BEHAVIORS *******************************************************************************/ inline void Register3DTransfoBehaviors(CKPluginManager& iPluginManager) { //--- 3D Tranfo iPluginManager.RegisterPluginInfo(0,CKGet_3DTransfo_PluginInfo(0),Register_3DTransfo_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_3DTransfo_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("3DTransfo",2); } inline void RegisterBBAddonsBehaviors(CKPluginManager& iPluginManager) { //--- BuildingBlock Addons (1 : Beh) iPluginManager.RegisterPluginInfo(0,CKGet_BBAddons_PluginInfo(0),Register_BBAddons_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("BBAddons",1); } inline void RegisterBBAddons2Behaviors(CKPluginManager& iPluginManager) { //--- BuildingBlock Addons 2 (1 : Beh) iPluginManager.RegisterPluginInfo(0,CKGet_BBAddons2_PluginInfo(0),Register_BBAddons2_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("BBAddons2",1); } inline void RegisterCamerasBehaviors(CKPluginManager& iPluginManager) { //-- Cameras iPluginManager.RegisterPluginInfo(0,CKGet_Cameras_PluginInfo(0),Register_Cameras_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Cameras",1); } inline void RegisterControllersBehaviors(CKPluginManager& iPluginManager) { //-- Controllers iPluginManager.RegisterPluginInfo(0,CKGet_Controllers_PluginInfo(0),Register_Controllers_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Controllers",1); } inline void RegisterCharactersBehaviors(CKPluginManager& iPluginManager) { //-- Characters iPluginManager.RegisterPluginInfo(0,CKGet_Characters_PluginInfo(0),Register_Characters_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Character",1); } inline void RegisterCollisionsBehaviors(CKPluginManager& iPluginManager) { //-- Collisions iPluginManager.RegisterPluginInfo(0,CKGet_Collisions_PluginInfo(0),NULL,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_Collisions_PluginInfo(1),NULL,NULL); iPluginManager.RegisterPluginInfo(2,CKGet_Collisions_PluginInfo(2),Register_Collisions_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Collision",3); } inline void RegisterGridsBehaviors(CKPluginManager& iPluginManager) { //--- Grids iPluginManager.RegisterPluginInfo(0,CKGet_Grids_PluginInfo(0),Register_Grids_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_Grids_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("Grids",2); } inline void RegisterInterfaceBehaviors(CKPluginManager& iPluginManager) { //--- Interface iPluginManager.RegisterPluginInfo(0,CKGet_Interface_PluginInfo(0),Register_Interface_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_Interface_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("Interface",2); } inline void RegisterLightsBehaviors(CKPluginManager& iPluginManager) { //-- Lights iPluginManager.RegisterPluginInfo(0,CKGet_Lights_PluginInfo(0),Register_Lights_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Lights",1); } inline void RegisterLogicsBehaviors(CKPluginManager& iPluginManager) { //-- Logics iPluginManager.RegisterPluginInfo(0,CKGet_Logics_PluginInfo(0),Register_Logics_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Logics",1); } inline void RegisterMaterialsBehaviors(CKPluginManager& iPluginManager) { //-- Materials iPluginManager.RegisterPluginInfo(0,CKGet_Materials_PluginInfo(0),Register_Materials_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Materials",1); } inline void RegisterMeshesBehaviors(CKPluginManager& iPluginManager) { //--- Meshes iPluginManager.RegisterPluginInfo(0,CKGet_MeshModifiers_PluginInfo(0),Register_MeshModifiers_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_MeshModifiers_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("Meshes",2); } inline void RegisterMidiBehaviors(CKPluginManager& iPluginManager) { //--- Midi iPluginManager.RegisterPluginInfo(0,CKGet_MidiBehaviors_PluginInfo(0),Register_MidiBehaviors_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_MidiBehaviors_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("Midi",2); } inline void RegisterNarrativesBehaviors(CKPluginManager& iPluginManager) { //-- Narratives iPluginManager.RegisterPluginInfo(0,CKGet_Narratives_PluginInfo(0),Register_Narratives_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Narratives",1); } inline void RegisterParticleSystemsBehaviors(CKPluginManager& iPluginManager) { //-- Particle systems iPluginManager.RegisterPluginInfo(0,CKGet_Particles_PluginInfo(0),Register_Particles_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_Particles_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("ParticleSystems",2); } inline void RegisterPhysicsBehaviors(CKPluginManager& iPluginManager) { //-- Physics iPluginManager.RegisterPluginInfo(0,CKGet_Physics_PluginInfo(0),Register_Physics_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_Physics_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("Physics",2); } inline void RegisterSoundsBehaviors(CKPluginManager& iPluginManager) { //-- Sounds iPluginManager.RegisterPluginInfo(0,CKGet_Sounds_PluginInfo(0),Register_Sounds_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Sounds",1); } inline void RegisterShaderBehaviors(CKPluginManager& iPluginManager) { //-- Shader Behaviors iPluginManager.RegisterPluginInfo(0,CKGet_Shaders_PluginInfo(0),NULL,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_Shaders_PluginInfo(1),Register_Shaders_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Shaders",2); } inline void RegisterVideoBehaviors(CKPluginManager& iPluginManager) { //-- Visuals iPluginManager.RegisterPluginInfo(0,CKGet_Video_PluginInfo(0),Register_Video_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Video",1); } inline void RegisterVisualsBehaviors(CKPluginManager& iPluginManager) { //-- Visuals iPluginManager.RegisterPluginInfo(0,CKGet_Visuals_PluginInfo(0),Register_Visuals_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Visuals",1); } inline void RegisterWorldEnvBehaviors(CKPluginManager& iPluginManager) { //-- World Env iPluginManager.RegisterPluginInfo(0,CKGet_WorldEnvironment_PluginInfo(0),Register_WorldEnvironment_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("WorldEnv",1); } inline void RegisterNetworkBehaviors(CKPluginManager& iPluginManager) { //-- Network Manager iPluginManager.RegisterPluginInfo(0,CKGet_VSManager_PluginInfo(0),Register_VSManager_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_VSManager_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("Network",2); } inline void RegisterNetworkServerBehaviors(CKPluginManager& iPluginManager) { //-- Network Server Manager iPluginManager.RegisterPluginInfo(0,CKGet_VSServerManager_PluginInfo(0),Register_VSServerManager_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_VSServerManager_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("NetworkServer",2); } inline void RegisterMultiPlayerBehaviors(CKPluginManager& iPluginManager) { //-- MultiPlayer iPluginManager.RegisterPluginInfo(0,CKGet_MP_PluginInfo(0),Register_MP_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_MP_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("MultiPlayer",2); } inline void RegisterDownloadBehaviors(CKPluginManager& iPluginManager) { //-- DownloadMedia iPluginManager.RegisterPluginInfo(0,CKGet_DLM_PluginInfo(0),Register_DLM_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("DownloadMedia",1); } inline void RegisterDatabaseBehaviors(CKPluginManager& iPluginManager) { //-- Database iPluginManager.RegisterPluginInfo(0,CKGet_DBC_PluginInfo(0),Register_DBC_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("Database",1); } inline void RegisterVSLBehaviors(CKPluginManager& iPluginManager) { //-- VSL iPluginManager.RegisterPluginInfo(0,CKGet_VSLManager_PluginInfo(0),Register_VSLManager_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_VSLManager_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("VSL",2); } inline void RegisterCryptoBehaviors(CKPluginManager& iPluginManager) { //-- CryptedLoader iPluginManager.RegisterPluginInfo(0,CKGet_CryptedLoader_PluginInfo(0),Register_CryptedLoader_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("CryptedLoader",1); } /**************************************************************************** MANAGERS *******************************************************************************/ inline void RegisterParamOpManager(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_ParamOp_PluginInfo(0),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("CKParamOp",1); } inline void RegisterCKFEMgrManager(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_CKFEMgr_PluginInfo(0),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("CKFEMgr",1); } inline void RegisterInputManager(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_InputManager_PluginInfo(0),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("InputManager",1); } inline void RegisterSoundManager(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_SoundManager_PluginInfo(0),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("SoundManager",1); } inline void RegisterVideoManager(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_VideoManager_PluginInfo(0),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("VideoManager",1); } inline void RegisterDX8VideoManager(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_Dx8VideoManager_PluginInfo(0),NULL,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_Dx8VideoManager_PluginInfo(1),Register_Dx8VideoManager_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("DX8VideoManager",2); } inline void RegisterDX9VideoManager(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_Dx9VideoManager_PluginInfo(0),NULL,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_Dx9VideoManager_PluginInfo(1),Register_Dx9VideoManager_BehaviorDeclarations,NULL); iPluginManager.RegisterNewStaticLibAsDll("DX9VideoManager",2); } /**************************************************************************** READERS *******************************************************************************/ inline void RegisterVirtoolsReader(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGetVirtoolsPluginInfo(0),NULL,CKGetVirtoolsReader); iPluginManager.RegisterPluginInfo(1,CKGetVirtoolsPluginInfo(1),NULL,CKGetVirtoolsReader); iPluginManager.RegisterPluginInfo(2,CKGetVirtoolsPluginInfo(2),NULL,CKGetVirtoolsReader); iPluginManager.RegisterPluginInfo(3,CKGetVirtoolsPluginInfo(3),NULL,CKGetVirtoolsReader); iPluginManager.RegisterNewStaticLibAsDll("Virtools Reader",4); } inline void RegisterImageReader(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_ImageReader_PluginInfo(0),NULL,CKGet_ImageReader_Reader); iPluginManager.RegisterPluginInfo(1,CKGet_ImageReader_PluginInfo(1),NULL,CKGet_ImageReader_Reader); iPluginManager.RegisterPluginInfo(2,CKGet_ImageReader_PluginInfo(2),NULL,CKGet_ImageReader_Reader); iPluginManager.RegisterNewStaticLibAsDll("Image Reader",3); } inline void RegisterAVIReader(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_AviReader_PluginInfo(0),NULL,CKGet_AviReader_Reader); iPluginManager.RegisterNewStaticLibAsDll("AVI Reader",1); } inline void RegisterPNGReader(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_PngReader_PluginInfo(0),NULL,CKGet_PngReader_Reader); iPluginManager.RegisterNewStaticLibAsDll("PNG Reader",1); } inline void RegisterJPGReader(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_JpgReader_PluginInfo(0),NULL,CKGet_JpgReader_Reader); iPluginManager.RegisterNewStaticLibAsDll("JPG Reader",1); } inline void RegisterWAVReader(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_WavReader_PluginInfo(0),NULL,CKGet_WavReader_Reader); iPluginManager.RegisterPluginInfo(1,CKGet_WavReader_PluginInfo(1),NULL,CKGet_WavReader_Reader); iPluginManager.RegisterPluginInfo(2,CKGet_WavReader_PluginInfo(2),NULL,CKGet_WavReader_Reader); iPluginManager.RegisterNewStaticLibAsDll("Wav Reader",3); } inline void RegisterTIFFReader(CKPluginManager& iPluginManager) { iPluginManager.RegisterPluginInfo(0,CKGet_TifReader_PluginInfo(0),NULL,CKGet_TifReader_Reader); iPluginManager.RegisterNewStaticLibAsDll("Tiff Reader",1); } inline void CustomPlayerRegisterRenderEngine(CKPluginManager& iPluginManager) { #if defined(USE_DX8) iPluginManager.AddRenderEngineRasterizer(CKDX8RasterizerGetInfo); #else iPluginManager.AddRenderEngineRasterizer(CKDX9RasterizerGetInfo); #endif iPluginManager.AddRenderEngineRasterizer(CKGL15RasterizerGetInfo); iPluginManager.RegisterPluginInfo(0,CK2_3DGetPluginInfo(0),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("ck2_3d",1); } inline void CustomPlayerRegisterReaders(CKPluginManager& iPluginManager) { RegisterVirtoolsReader(iPluginManager); RegisterImageReader(iPluginManager); RegisterAVIReader(iPluginManager); RegisterPNGReader(iPluginManager); RegisterJPGReader(iPluginManager); RegisterWAVReader(iPluginManager); #if !defined(_DEBUG) RegisterTIFFReader(iPluginManager); #endif } inline void CustomPlayerRegisterManagers(CKPluginManager& iPluginManager) { RegisterParamOpManager(iPluginManager); RegisterInputManager(iPluginManager); RegisterSoundManager(iPluginManager); RegisterCKFEMgrManager(iPluginManager); //RegisterVideoManager(iPluginManager); #if defined(USE_DX8) RegisterDX8VideoManager(iPluginManager); #else //RegisterDX9VideoManager(iPluginManager); #endif } inline void CustomPlayerRegisterBehaviors(CKPluginManager& iPluginManager) { Register3DTransfoBehaviors(iPluginManager); RegisterBBAddonsBehaviors(iPluginManager); RegisterBBAddons2Behaviors(iPluginManager); RegisterCamerasBehaviors(iPluginManager); RegisterCharactersBehaviors(iPluginManager); RegisterCollisionsBehaviors(iPluginManager); RegisterControllersBehaviors(iPluginManager); RegisterGridsBehaviors(iPluginManager); RegisterInterfaceBehaviors(iPluginManager); RegisterLightsBehaviors(iPluginManager); RegisterLogicsBehaviors(iPluginManager); RegisterMaterialsBehaviors(iPluginManager); RegisterMeshesBehaviors(iPluginManager); RegisterMidiBehaviors(iPluginManager); RegisterNarrativesBehaviors(iPluginManager); RegisterParticleSystemsBehaviors(iPluginManager); //RegisterShaderBehaviors(iPluginManager); RegisterSoundsBehaviors(iPluginManager); RegisterVSLBehaviors(iPluginManager); //RegisterVideoBehaviors(iPluginManager); RegisterVisualsBehaviors(iPluginManager); RegisterWorldEnvBehaviors(iPluginManager); RegisterPhysicsBehaviors(iPluginManager); /* RegisterCryptoBehaviors(iPluginManager); RegisterNetworkBehaviors(iPluginManager); RegisterNetworkServerBehaviors(iPluginManager); RegisterMultiPlayerBehaviors(iPluginManager); RegisterDownloadBehaviors(iPluginManager); RegisterDatabaseBehaviors(iPluginManager); */ } #endif // CUSTOM_PLAYER_STATIC #endif // CUSTOMPLAYERSTATICDLLS_H<file_sep>#include "StdAfx.h" #include <qTimer.h> #include <time.h> #include <Windows.h> #ifdef linux #include <sys/time.h> #endif // Screen Hertz; for Quizes, PAL should do the trick #define TRACES_PER_SECOND 50 QTimer::QTimer() { Reset(); } QTimer::~QTimer() { } void QTimer::ResetBase() // Reset 0-base for time counting { #ifdef USE_VTRACE baseVCount=app->GetVTraceCount(); #endif #ifdef USE_UST dmGetUST(&baseUST); #endif #ifdef USE_TIME time(&base_secs); #endif #ifdef USE_GETTIMEOFDAY struct timezone tz; gettimeofday(&tvBase,&tz); // Calculate time in usecs base_usecs=tvBase.tv_sec*1000000+tvBase.tv_usec; #endif #ifdef USE_OS_TICK //baseTicks=(int)GetTickCount(); baseTicks=(int)timeGetTime(); #endif } /********************** * STOPWATCH EMULATION * **********************/ void QTimer::UpdateTicks() // Updates 'ticks' to the last available time instant (NOW) { if(!isRunning) { return; } #ifdef USE_VTRACE int vc; vc=app->GetVTraceCount(); ticks+=vc-baseVCount; baseVCount=vc; #endif #ifdef USE_UST uint64 vc; dmGetUST(&vc); ticks+=vc-baseUST; baseUST=vc; #endif #ifdef USE_OS_TICK // Looks a lot like UST int t; //t=(int)GetTickCount(); t=(int)timeGetTime(); ticks+=t-baseTicks; baseTicks=t; #endif #ifdef USE_GETTIMEOFDAY int t; struct timezone tz; gettimeofday(&tv,&tz); t=tv.tv_sec*1000000+tv.tv_usec; ticks+=t-base_usecs; base_usecs=t; #endif } void QTimer::Reset() { /** Starts timer at current time **/ ResetBase(); ticks=0; isRunning=FALSE; } void QTimer::Start() // Turn timer on { if(isRunning)return; ResetBase(); isRunning=TRUE; } void QTimer::Stop() // Stop time recording { if(!isRunning)return; UpdateTicks(); isRunning=FALSE; } /**************** * RETRIEVE TIME * ****************/ void QTimer::GetTime(ulong *secs,ulong *micros) /** Get passed time since last reset **/ { } ulong QTimer::GetSeconds() /** Get passed seconds since last Start() **/ { #ifdef USE_VTRACE long s; int vc; //vc=app->GetVTraceCount(); //return (ulong)((vc-baseVCount)/TRACES_PER_SECOND); UpdateTicks(); return ticks/TRACES_PER_SECOND; #endif #ifdef USE_UST UpdateTicks(); return ticks/1000000000; // 10^9 = nanoseconds #endif #ifdef USE_TIME time_t t; time(&t); return (ulong)(t-base_secs); #endif #ifdef USE_OS_TICK UpdateTicks(); return ticks/1000; #endif #ifdef USE_GETTIMEOFDAY UpdateTicks(); return ticks/1000000; #endif } #ifdef USE_UST uint64 QTimer::GetTicks() #else int QTimer::GetTicks() #endif // Get #ticks, 1 tick is 1 vertical blank interval, or nanosecond, or WHATEVER! // Don't use this function in application code; too many variant { UpdateTicks(); return ticks; //int vc; //vc=app->GetVTraceCount(); //return (int)(vc-baseVCount); } int QTimer::GetMilliSeconds() { #ifdef USE_UST //uint64 div; //div=1000000; UpdateTicks(); //qdbg("ticks=%lld\n",ticks); return (int)(ticks/1000000); #endif #ifdef USE_TIME UpdateTicks(); return (int)(ticks*1000); #endif #ifdef USE_OS_TICK UpdateTicks(); return (int)ticks; #endif #ifdef USE_GETTIMEOFDAY UpdateTicks(); return ticks/1000; #endif } int QTimer::GetMicroSeconds() // Returns time in microseconds { #ifdef USE_UST UpdateTicks(); return (int)(ticks/1000); #endif #ifdef USE_TIME UpdateTicks(); return (int)(ticks*1000000); #endif #ifdef USE_OS_TICK // Not really microseconds! UpdateTicks(); return (int)ticks; #endif #ifdef USE_GETTIMEOFDAY UpdateTicks(); return ticks; #endif } void QTimer::WaitForTime(int secs,int msecs) // Reasonably multitasking-friendly wait for the timer to pass the given // time and return. // On O2's and most low level SGI's, the accurary is ~10ms (scheduler slice) // Starts the timer if it is not running (instead of just returning) // On Win32, we might just use Sleep() { int n; secs=secs*1000+msecs; // Make sure timer is running if(!IsRunning())Start(); while(1) { n=GetMilliSeconds(); if(n>=secs)break; Sleep(10); } } /***************** * TIME ADJUSTING * *****************/ void QTimer::AdjustMilliSeconds(int delta) // Adjust time in milliseconds // 'delta' may be negative or positive. Note that this may underflow the // timer, meaning it will be negative. { #ifdef USE_UST uint64 delta64; delta64=(uint64)delta; // Get time in nanoseconds delta64*=1000000; ticks+=delta64; #endif #ifdef USE_OS_TICK // Adjust msecs ticks+=delta; #endif #ifdef USE_GETTIMEOFDAY ticks+=delta*1000; #endif } /** TEST **/ //#define NOTDEF_TEST #ifdef NOTDEF_TEST #include <stdio.h> void main(void) { QTimer *qt; ulong s,m; QAppSetup(); qt=new QTimer(); while(!RMB()) { qt->GetTime(&s,&m); printf("S=%d, M=%4d\n",s,m); } //delete qt; QAppQuit(); } #endif <file_sep>#ifndef __PWHEELTYPES_H__ #define __PWHEELTYPES_H__ #include "NxVec3.h" #include "NxMat34.h" #include "NxUserContactReport.h" //#include "pRigidBodyTypes.h" //#include "pVTireFunction.h" /** \addtogroup Vehicle @{ */ class pWheelContactModifyData { public : CK3dEntity *object; VxVector contactPoint; VxVector contactNormal; float contactPosition; float normalForce; int otherMaterialIndex; pWheelContactModify() { object = NULL; contactPosition = 0.0f; normalForce = 0.0f; otherMaterialIndex = 0; } }; struct ContactInfo { ContactInfo() { reset(); } void reset() { otherActor = NULL; relativeVelocity = 0; } bool isTouching() const { return otherActor != NULL; } NxActor* otherActor; NxVec3 contactPosition; NxVec3 contactPositionLocal; NxVec3 contactNormal; NxReal relativeVelocity; NxReal relativeVelocitySide; }; /** \brief Contact information used by pWheel @see pWheel pWheel.getContact() */ class pWheelContactData { public: /** \brief The point of contact between the wheel shape and the ground. */ VxVector contactPoint; /** \brief The normal at the point of contact. */ VxVector contactNormal; /** \brief The direction the wheel is pointing in. */ VxVector longitudalDirection; /** \brief The sideways direction for the wheel(at right angles to the longitudinal direction). */ VxVector lateralDirection; /** \brief The magnitude of the force being applied for the contact. */ float contactForce; /** \brief What these exactly are depend on NX_WF_INPUT_LAT_SLIPVELOCITY and NX_WF_INPUT_LNG_SLIPVELOCITY flags for the wheel. */ float longitudalSlip, lateralSlip; /** \brief the clipped impulses applied at the wheel. */ float longitudalImpulse, lateralImpulse; /** \brief The material index of the shape in contact with the wheel. @see pMaterial */ int otherShapeMaterialIndex; /** \brief The distance on the spring travel distance where the wheel would end up if it was resting on the contact point. */ float contactPosition; /** \brief The distance on the spring travel distance where the wheel would end up if it was resting on the contact point. */ CK3dEntity* contactEntity; /** \brief The material of the colliding shape */ pMaterial otherMaterial; }; /** \brief An interface class that the user can implement in order to modify the contact point on which the WheelShape base its simulation constraints. <b>Threading:</b> It is <b>necessary</b> to make this class thread safe as it will be called in the context of the simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded parts of the physics engine. You enable the use of this callback by specifying a callback function in NxWheelShapeDesc.wheelContactModify or by setting a callback function through NxWheelShape.setUserWheelContactModify(). Please note: + There will only be callbacks if the WheelShape finds a contact point. Increasing the suspensionTravel value gives a longer raycast and increases the chance of finding a contact point (but also gives a potentially slower simulation). @see NxWheelShapeDesc.wheelContactModify NxWheelShape.setUserWheelContactModify() NxWheelShape.getUserWheelContactModify() */ class MODULE_API pWheelContactModify : NxUserWheelContactModify { public: pWheelContactModify() : wheel(NULL) , lastContactModifyData() { } /** \brief This callback is called once for each wheel and sub step before the wheel constraints are setup and fed to the SDK. The values passed in the parameters can be adjusted to affect the vehicle simulation. The most interesting values are contactPosition, contactPoint, and contactNormal. The contactPosition value specifies how far on the travel distance the contactPoint was found. If you want to simulate a bumpy road, then this is the main parameter to change. It is also good to adjust the contactPoint variable, so that the wheel forces are applied in the correct position. \param wheelShape The WheelShape that is being processed. \param contactPoint The contact point (in world coordinates) that is being used for the wheel. \param contactNormal The normal of the geometry at the contact point. \param contactPosition The distance on the spring travel distance where the wheel would end up if it was resting on the contact point. \param normalForce The normal force on the wheel from the last simulation step. \param otherShape The shape with which the wheel is in contact. \param otherShapeMaterialIndex The material on the other shape in the position where the wheel is in contact. Currently has no effect on the simulation. \param otherShapeFeatureIndex The feature on the other shape in the position where the wheel is in contact. \return Return true to keep the contact (with the possibly edited values) or false to drop the contact. */ virtual bool onWheelContact(NxWheelShape* wheelShape, NxVec3& contactPoint, NxVec3& contactNormal, NxReal& contactPosition, NxReal& normalForce, NxShape* otherShape, NxMaterialIndex& otherShapeMaterialIndex, NxU32 otherShapeFeatureIndex); pWheelContactModifyData* lastContactModifyData; pWheelContactModifyData* getLastContactModifyData() const { return lastContactModifyData; } void setLastContactModifyData(pWheelContactModifyData* val) { lastContactModifyData = val; } pWheel2* getWheel() const { return wheel; } void setWheel(pWheel2* val) { wheel = val; } pWheelContactModifyData& getLastData(){ return lastData; } void setLastData(pWheelContactModifyData val) { lastData = val; } private: pWheel2* wheel; pWheelContactModifyData lastData; }; /** @} */ #endif // __PWHEELTYPES_H__<file_sep>#ifndef __P_V_TIRE_FUNCTION_H__ #define __P_V_TIRE_FUNCTION_H__ #include "vtPhysXBase.h" /** \addtogroup Vehicle @{ */ /** \brief cubic hermit spline coefficients describing the longitudinal tire force curve. Force ^ extrema | _*_ | ~ \ asymptote | / \~__*______________ | / |/ ---------------------------> Slip */ class MODULE_API pTireFunction { public: virtual ~pTireFunction(){}; /** \brief extremal point of curve. Both values must be positive. <b>Range:</b> (0,inf)<br> <b>Default:</b> 1.0 */ float extremumSlip; /** \brief extremal point of curve. Both values must be positive. <b>Range:</b> (0,inf)<br> <b>Default:</b> 0.02 */ float extremumValue; /** \brief point on curve at which for all x > minumumX, function equals minimumY. Both values must be positive. <b>Range:</b> (0,inf)<br> <b>Default:</b> 2.0 */ float asymptoteSlip; /** \brief point on curve at which for all x > minumumX, function equals minimumY. Both values must be positive. <b>Range:</b> (0,inf)<br> <b>Default:</b> 0.01 */ float asymptoteValue; /** \brief Scaling factor for tire force. This is an additional overall positive scaling that gets applied to the tire forces before passing them to the solver. Higher values make for better grip. If you raise the *Values above, you may need to lower this. A setting of zero will disable all friction in this direction. <b>Range:</b> (0,inf)<br> <b>Default:</b> 1000000.0 (quite stiff by default) */ float stiffnessFactor; /** \brief Scaling factor for tire force. This is an additional overall positive scaling that gets applied to the tire forces before passing them to the solver. Higher values make for better grip. If you raise the *Values above, you may need to lower this. A setting of zero will disable all friction in this direction. <b>Range:</b> (0,inf)<br> <b>Default:</b> 1000000.0 (quite stiff by default) */ // float stiffnessFactor; /** constructor sets to default. */ pTireFunction(); /** (re)sets the structure to the default. */ virtual void setToDefault(); /** returns true if the current settings are valid */ virtual bool isValid() const; /** evaluates the Force(Slip) function */ float hermiteEval(float t) const; int xmlLink; }; /** @} */ #endif<file_sep>#include "xDistributedInteger.h" #include "xPredictionSetting.h" #include "xMathFnc2.h" uxString xDistributedInteger::print(TNL::BitSet32 flags) { return uxString(); } void xDistributedInteger::updateFromServer(TNL::BitStream *stream) { mLastServerValue = stream->readSignedInt(32); setValueState(E_DV_UPDATED); } void xDistributedInteger::updateGhostValue(TNL::BitStream *stream) { stream->writeSignedInt(mCurrentValue,32); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedInteger::unpack(TNL::BitStream *bstream,float sendersOneWayTime) { mLastValue = mCurrentValue; int value = bstream->readSignedInt(32); mCurrentValue = value; mDifference= mCurrentValue - mLastValue; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedInteger::pack(TNL::BitStream *bstream) { bstream->writeSignedInt(mCurrentValue,32); int flags = getFlags(); flags &= (~E_DP_NEEDS_SEND); setFlags(flags); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedInteger::updateValue(TNL::S32 value,xTimeType currentTime) { mLastTime = mCurrentTime; mCurrentTime = currentTime; mLastDeltaTime = mCurrentTime - mLastTime; mLastValue = mCurrentValue; mCurrentValue = value; mDifference = mCurrentValue - mLastValue; mThresoldTicker +=mLastDeltaTime; float lengthDiff = fabsf((float)mDifference +0.5f); int flags = getFlags(); flags =E_DP_OK; bool result = false; if ( lengthDiff > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime() ) { flags =E_DP_NEEDS_SEND; result = true ; } } float serverDiff = (float)(mCurrentValue-mLastServerValue); if ( fabsf( serverDiff + .5f) > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > (getPredictionSettings()->getMinSendTime() * 0.2f) ) { flags =E_DP_NEEDS_SEND; result = true ; } } if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime() ) { mThresoldTicker2 = 0 ; mThresoldTicker = 0; } setFlags(flags); return result; }<file_sep>#ifndef __P_REFERENCED_OBJECT_H__ #define __P_REFERENCED_OBJECT_H__ template<class EngineObject,class ImplementationObject>class MODULE_API pStoredObjectAssociation { public: //xEngineObjectAssociation() : mInternalId(-1) , mClassId(-1) {}; //xEngineObjectAssociation(EngineObject _Object,ImplementationObject _ImplObject,int _EngineObjectId) : mEngineObject(_Object) , mImplementationObject(_ImplObject) , mInternalId(_EngineObjectId) { } //xEngineObjectAssociation< (EngineObject _Object,ImplementationObject _ImplObject,int _EngineObjectId){} int getInternalId() const { return mInternalId; } void setInternalId(int val) { mInternalId = val; } int getClassId() const { return mClassId; } void setClassId(int val) { mClassId = val; } bool existsInCore(); virtual void onCreate(){}; virtual void onCopy(int oldId){}; virtual void onRemove(){}; virtual void onDelete(){}; virtual void onCheck(){}; //operator T(){ return mObject; } protected: private: int mClassId; int mInternalId; EngineObject mEngineObject; ImplementationObject mImplementationObject; }; template<class T>class MODULE_API xImplementationObject { public: //xLinkedObjectStorage() : mInternalId(-1) , mClassId(-1) {}; typedef void* xImplementationObject<T>::*StoragePtr; xImplementationObject(){} xImplementationObject(StoragePtr storage) { } T getImpl() { return mObject; } protected: private: T mObject; StoragePtr mStorage; }; template<class T>class MODULE_API xEngineObjectAssociation { public: xEngineObjectAssociation() : mInternalId(-1) , mClassId(-1) {}; xEngineObjectAssociation(T _Object,int _InternalId) : mObject(_Object) , mInternalId(_InternalId) { } int getInternalId() const { return mInternalId; } void setInternalId(int val) { mInternalId = val; } int getClassId() const { return mClassId; } void setClassId(int val) { mClassId = val; } bool existsInCore(); virtual void onCreate(){}; virtual void onCopy(int oldId){}; virtual void onRemove(){}; virtual void onDelete(){}; virtual void onCheck(){}; //operator T(){ return mObject; } protected: private: int mClassId; int mInternalId; T mObject; }; #endif<file_sep>#if !defined(CUSTOMPLAYERSTATICLIBS_H) #define CUSTOMPLAYERSTATICLIBS_H #if defined(CUSTOM_PLAYER_STATIC) #pragma warning( disable : 4099) #if defined(_DEBUG) #pragma comment(lib,"strmbase") #else #pragma comment(lib,"strmbase") #endif // virtools base libraries #pragma comment(lib,"CKZlibStatic") #pragma comment(lib,"VxMathStatic") #pragma comment(lib,"CK2Static") #pragma comment(lib,"AssemblerStatic") #pragma comment(lib,"VSLStatic") #pragma comment(lib,"VSLManagerStatic") #pragma comment(lib,"CKFEMgrStatic") #pragma comment(lib,"CKRasterizerLibStatic") #pragma comment(lib,"CK2_3DStatic") // opengl rasterizers // If you need CGFX uncomment //#pragma comment(lib,"cg") //#pragma comment(lib,"cgGL") #pragma comment(lib,"opengl32") #pragma comment(lib,"CKGLRasterizerStatic") // DirectX rasterizers #pragma comment(lib,"dxguid") #if defined(USE_DX8) #pragma comment(lib,"d3dx8") #pragma comment(lib,"d3d8") #pragma comment(lib,"CKDX8RasterizerStatic") #else #pragma comment(lib,"dxerr9") #pragma comment(lib,"d3dx9") #pragma comment(lib,"d3d9") #pragma comment(lib,"CKDX9RasterizerStatic") #endif // virtools plugins #pragma comment(lib,"VirtoolsLoaderStatic") #pragma comment(lib,"ImageReaderStatic") #pragma comment(lib,"TiffReaderStatic") #pragma comment(lib,"Vfw32") #pragma comment(lib,"Winmm") #pragma comment(lib,"Msacm32") #pragma comment(lib,"AviReaderStatic") #pragma comment(lib,"WavReaderStatic") #pragma comment(lib,"JpgLoaderStatic") #pragma comment(lib,"PngLoaderStatic") #pragma comment(lib,"AscLoaderStatic") #if defined(USE_DX8) #pragma comment(lib,"Dx8VideoManagerStatic") #else //#pragma comment(lib,"Dx9VideoManagerStatic") #endif #pragma comment(lib,"3dsLoaderStatic") #if defined(USE_DX8) #pragma comment(lib,"DDSReaderStatic") #else #pragma comment(lib,"DDSReaderStatic9") #endif #pragma comment(lib,"TiffReaderStatic") #pragma comment(lib,"XLoaderStatic") // thir party libraries used for plugins #if defined(_DEBUG) #pragma comment(lib,"JpegLibD") #pragma comment(lib,"pnglibd") #else #pragma comment(lib,"jpeglib") #pragma comment(lib,"pnglib") #pragma comment(lib,"LibTiff") #endif // virtools managers #pragma comment(lib,"dsound") #pragma comment(lib,"DX7SoundManagerStatic") #pragma comment(lib,"dinput8") #pragma comment(lib,"DX5InputManagerStatic") #pragma comment(lib,"ParameterOperationsStatic") //#pragma comment(lib,"VideoManagerStatic") // virtools behaviors #pragma comment(lib,"3DTransfoStatic") #pragma comment(lib,"BuildingBlocksAddons1Static") #pragma comment(lib,"BuildingBlocksAddons2Static") #pragma comment(lib,"CamerasStatic") #pragma comment(lib,"CharactersStatic") #pragma comment(lib,"CollisionsStatic") #pragma comment(lib,"ControllersStatic") #pragma comment(lib,"GridsStatic") #pragma comment(lib,"InterfaceStatic") #pragma comment(lib,"LightsStatic") #pragma comment(lib,"LogicsStatic") #pragma comment(lib,"MaterialsStatic") #pragma comment(lib,"MeshModifiersStatic") #pragma comment(lib,"MidiManagerStatic") #pragma comment(lib,"NarrativesStatic") #pragma comment(lib,"ParticleSystemsStatic") #pragma comment(lib,"SoundsStatic") //#pragma comment(lib,"VideoStatic") #pragma comment(lib,"VisualsStatic") #pragma comment(lib,"WorldEnvironmentsStatic") // If you need CGFX uncomment this line and comment the next one //#pragma comment(lib,"ShaderStatic") /*#pragma comment(lib,"ShaderStaticHLSL")*/ #ifdef vtToolkit #pragma comment(lib,"vtToolkit") #endif // vtTools #ifdef vtWidgets #pragma comment(lib,"vtWidgets") #endif #ifdef vtPhysX #pragma comment(lib,"vtPhysXLib") #endif // physics libraries #pragma comment(lib,"PhysicsStatic") // virtools network /*#pragma comment(lib,"VCryptStatic") #pragma comment(lib,"CryptedLoaderStatic") #pragma comment(lib,"nk2static") #pragma comment(lib,"vsutilsstatic") #pragma comment(lib,"vsmanager2static") #pragma comment(lib,"VSServer2static") // NOTE: this lib is in the Additional Dependencies of the linker (for linking problems) #pragma comment(lib,"MultiUserClientStatic") #pragma comment(lib,"MultiUserServerStatic")// NOTE: this lib is in the Additional Dependencies of the linker (for linking problems) #pragma comment(lib,"DatabaseClientModule2Static") #pragma comment(lib,"DownloadMediaClient2Static") */ #endif // CUSTOM_PLAYER_STATIC #endif // CUSTOMPLAYERSTATICLIBS_H <file_sep>/* * Tcp4u v 3.31 Creation 27/02/1998 Last Revision 27/02/1998 3.30 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: smtp4u.h * Purpose: main functions for smtp protocol management * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * Permission is hereby granted to copy, distribute or otherwise * use any part of this package as long as you do not try to make * money from it or pretend that you wrote it. This copyright * notice must be maintained in any copy made. * * Use of this software constitutes acceptance for use in an AS IS * condition. There are NO warranties with regard to this software. * In no event shall the author be liable for any damages whatsoever * arising out of or in connection with the use or performance of this * software. Any use of this software is at the user's own risk. * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * <NAME> (<EMAIL>) */ #ifndef SMTP4UX_API #ifdef __cplusplus extern "C" { /* Assume C declarations for C++ */ #endif /* __cplusplus */ #define SMTP4U_DEFPORT 25 #define SMTP4U_DEFTIMEOUT 60 /* seconds */ #define SMTP4U_SEPARATOR ';' /* semi colon character */ /************************** * definition error code **************************/ enum SMTP4_RETURN_CODE { SMTP4U_UNEXPECTEDANSWER = -3100, /* answer was not expected */ SMTP4U_SERVICECLOSED, /* service unavailable */ SMTP4U_NOTIMPLEMENTED, /* host recognize but can't exec cmd*/ SMTP4U_MIMENOTSUPPORTED, /* server doesn't support MIME ext. */ SMTP4U_SERVERCANTEXECUTE, /* refused by server */ SMTP4U_CANTCONNECT, /* can not connect to the server */ SMTP4U_DATAERROR, /* Error during communication */ SMTP4U_SYNTAXERROR, /* Bad parameters */ SMTP4U_STORAGEEXCEDED, /* server limits exceeded */ SMTP4U_UNKNOWNUSER, /* unknown destinee */ SMTP4U_SUCCESS = 1, /* Success !! */ SMTP4U_FORWARDED /* address OK,unknwon on this server*/ }; int API4U SmtpSendMessage (LPCSTR szFrom, LPCSTR szTo, LPCSTR szMessage, LPCSTR szHost, LPCSTR szMyDomain); #ifdef __cplusplus } /* End of extern "C" */ #endif /* ifdef __cplusplus */ #define SMTP4UX_API loaded #endif /* ifndef SMTP4UX_API */ <file_sep>#include "CKAll.h" CKObjectDeclaration *FillBehaviorGetCurrentPathDecl(); CKERROR CreateGetCurrentPathProto(CKBehaviorPrototype **pproto); int GetCurrentPath(const CKBehaviorContext& behcontext); /************************************************************************/ /* */ /************************************************************************/ CKObjectDeclaration *FillBehaviorGetCurrentPathDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("Get Current Path"); od->SetDescription("Add Objects"); od->SetCategory("Narratives/Objects"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x41676403,0x5d3d10c4)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGetCurrentPathProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateGetCurrentPathProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Get Current Path"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Create Zip File"); proto->DeclareOutput("Zip File created"); proto->DeclareOutParameter("Path",CKPGUID_STRING); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(GetCurrentPath); *pproto = proto; return CK_OK; } int GetCurrentPath(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; XString Current; VxGetCurrentDirectory(Current.Str()); CKParameterOut *pout = beh->GetOutputParameter(0); pout->SetStringValue(Current.Str()); beh->ActivateOutput(0); return CKBR_OK; } <file_sep>/******************************************************************** created: 2007/12/12 created: 12:12:2007 11:55 filename: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude\vtcxglobal.h file path: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude file base: vtcxglobal file ext: h author: mc007 purpose: *********************************************************************/ #ifndef __VTCXGLOBAL_H_ #define __VTCXGLOBAL_H_ ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Platform Headers // #include <vtCXPrecomp.h> ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Platform specific header switchs : // #ifdef _WIN32 #include <vtCXPlatform32.h> #endif ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Build switchs : // ////////////////////////////////////////////////////////////////////////// // GBLDebugBuild is used to hide GBL - private building blocks, types, attributes,... #ifdef NDEBUG static const bool vtCXDebugBuild = true; #else static const bool vtCXDebugBuild = false; #endif ////////////////////////////////////////////////////////////////////////// // dll directives : #ifndef VTCX_API_EXPORT #define VTCX_API_EXPORT __declspec(dllexport) #endif #ifndef VTCX_API_INLINE #define VTCX_API_INLINE __inline #endif #ifndef VTCX_API_sCALL #define VTCX_API_sCALL __stdcall #endif #ifndef VTCX_API_cDECL #define VTCX_API_cDECL __cdecl #endif ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // API Specific Constants : // #define VTCX_API_PREFIX "vtCX" #define VTCX_API_ENTRY(F) VTCX_API_PREFIX##F #define VTCX_API_CUSTOM_BB_CATEGORY(F) VTCX_API_PREFIX##F // #define MY_BB_CAT VTCX_API_CUSTOM_BB_CATEGORY(/Configurable Information) leads to : "GBL/Configurable Information" #ifndef VTCX_AUTHOR #define VTCX_AUTHOR "<NAME>" #endif #ifndef VTCX_AUTHOR_GUID #define VTCX_AUTHOR_GUID CKGUID(0x79ba75dd,0x41d77c63) #endif ////////////////////////////////////////////////////////////////////////// // // Error Identifiers : // //Error code to identify the GBL-COMMON Component : #define VTCX_ERROR_ID_VTCX_COMMON 10 ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // File System Specific : // #if defined (_LINUX) #define VTCX_FS_PATH_SEPERATOR '/' #define VTCX_FS_PATH_DRIVE_SEPARATOR ':' #define VTCX_FS_EOL "\n" //(0x0D) #endif #ifdef _WIN32 #define VTCX_FS_PATH_SEPERATOR '\\' #define VTCX_FS_PATH_DRIVE_SEPARATOR #define VTCX_FS_EOL "\r\n" //(0x0A 0x0D) #endif #if defined (macintosh) #define VTCX_FS_PATH_SEPERATOR '/' #define VTCX_FS_PATH_DRIVE_SEPARATOR #define VTCX_FS_EOL "\r" //(0x0A) #endif #define VTCX_FS_PATH_EXT_SEPARATOR '.' ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // #endif<file_sep>/////////////////////////////////////////////////////////// // xLogger.cpp // Implementation of the Class xLogger // Created on: 10-Feb-2007 12:40:39 /////////////////////////////////////////////////////////// //#include <virtools/vtCXGlobal.h> //#include <pch.h> #include <Windows.h> #include <stdio.h> #include <stdarg.h> #include "xLogger.h" #include "uxString.h" #include "xBitSet.h" #include <tnl.h> #include "tnlLog.h" using xUtils::xLogger; using xUtils::xLoggerFlags; //using xUtils::xLogConsumer; using namespace xUtils; /* using namespace TNL; using namespace TNL::Platform; */ xLogConsumer *xLogConsumer::mLinkedList = NULL; void xLogConsumer::logString(const char *string) { // by default the LogConsumer will output to the platform debug // string printer, but only if we're in debug mode //#ifdef TNL_DEBUG TNL::Platform::outputDebugString(string); TNL::Platform::outputDebugString("\n"); //printf(string); /* OutputDebugString(string); OutputDebugString("\n"); */ } xLogConsumer::xLogConsumer() { mNextConsumer = mLinkedList; if(mNextConsumer) mNextConsumer->mPrevConsumer = this; mPrevConsumer = NULL; mLinkedList = this; } xLogConsumer::~xLogConsumer() { if(mNextConsumer) mNextConsumer->mPrevConsumer = mPrevConsumer; if(mPrevConsumer) mPrevConsumer->mNextConsumer = mNextConsumer; else mLinkedList = mNextConsumer; } static xLogger *xlog=NULL; const char*formatLine(const char *msg,...); void printMessage(const char*buffer); #include <cstdio> #define ANSI /* Comment out for UNIX version */ #ifdef ANSI /* ANSI compatible version */ #include <stdarg.h> int average( int first, ... ); #else /* UNIX compatible version */ #include <varargs.h> int average( va_list ); #endif #ifdef VIRTOOLS_USER_SDK #include "CKAll.h" #endif void xLogger::finalPrint(const char*string) { #ifdef VIRTOOLS_USER_SDK if (getVirtoolsContext()) { getVirtoolsContext()->OutputToConsole(const_cast<char*>(string),FALSE); } #endif if (strlen(string)) { printf(string); TNL::Platform::outputDebugString(string); } for(xLogConsumer *walk = xLogConsumer::getLinkedList(); walk; walk = walk->getNext()) walk->logString(string); } void xLogger::enableLoggingLevel(int item,int level,int enable) { std::map<int,xBitSet>::iterator it = getLogItems().find(item); if ( it !=getLogItems().end() ) { xBitSet& flags = it->second; if (level !=8) { flags.set( 1 << level,enable); }else flags.set(); } } //************************************ // Method: getLogLevel // FullName: xLogger::getLogLevel // Access: public // Returns: xBitSet // Qualifier: // Parameter: int item //************************************ xBitSet xLogger::getLogLevel(int item) { std::map<int,xBitSet>::iterator it = getLogItems().find(item); if ( it !=getLogItems().end() ) { return it->second; } xBitSet result; result.set(); return result; } //************************************ // Method: addLogItem // FullName: xLogger::addLogItem // Access: public // Returns: void // Qualifier: // Parameter: int item //************************************ void xLogger::addLogItem(int item) { xBitSet flags; flags.set(1 << ELOGWARNING,true); flags.set(1 << ELOGERROR,true); flags.set(1 << ELOGINFO,true); getLogItems().insert(std::make_pair(item,flags)); } //************************************ // Method: setLoggingLevel // FullName: xLogger::setLoggingLevel // Access: public // Returns: void // Qualifier: // Parameter: int item // Parameter: xBitSet flags //************************************ void xLogger::setLoggingLevel(int item,xBitSet flags) { std::map<int,xBitSet>::iterator it = getLogItems().find(item); if ( it !=getLogItems().end() ) { xBitSet& lflags = it->second; lflags = flags; } } //************************************ // Method: dVsprintf // FullName: dVsprintf // Access: public // Returns: signed int // Qualifier: // Parameter: char *buffer // Parameter: unsigned int bufferSize // Parameter: const char *format // Parameter: void *arglist //************************************ signed int dVsprintf(char *buffer, unsigned int bufferSize, const char *format, void *arglist) { #ifdef TNL_COMPILER_VISUALC signed int len = _vsnprintf(buffer, bufferSize, format, (va_list) arglist); #else signed int len = vsnprintf(buffer, bufferSize, format, (char *) arglist); #endif return len; } //************************************ // Method: xLog // FullName: xLogger::xLog // Access: public // Returns: void // Qualifier: // Parameter: char *cppText // Parameter: int type // Parameter: int component // Parameter: const char *header // Parameter: ... //************************************ void xLogger::xLog(char *cppText,int type,int component,const char *header, ...) { if (!xLogger::GetInstance()->getLogLevel(component).test(1<< type) ) { return; } char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, header ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, header, s); va_end(s); char headerout[2048]; if (strlen(cppText)) { sprintf(headerout,"%s :\t->%s",cppText,header); xLog(type,component,headerout,buffer); }else { xLog(type,component,header,buffer); } } //************************************ // Method: xLog // FullName: xLogger::xLog // Access: public // Returns: void // Qualifier: // Parameter: xBitSet styleFlags // Parameter: int type // Parameter: int component // Parameter: const char *header // Parameter: ... //************************************ void xLogger::xLog(xBitSet styleFlags,int type,int component,const char *header, ...) { /* if (!xLogger::GetInstance()->getLogLevel(component).test(1<< type) ) { return; } char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, header ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, header, s); va_end(s); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); char headerBuffer[4096]; char verbosityStr[512]; char componentString[256]; sprintf(componentString,"%s",sLogItems[component]); uxString leadIn(""); if (type > 4) { type =4; } if (type < 0) { type =0; } if ( styleFlags.test(E_PSF_PRINT_LOG_TYPE) ) { leadIn << "\n<-----------------> " << sLogTypes[type] << " : "; } if ( styleFlags.test(E_PSF_PRINT_COMPONENT) ) { leadIn << "|---" << componentString << "--|"; } leadIn << "\n"; switch(type) { case ELOGINFO: SetConsoleTextAttribute(hConsole, 10); break; case ELOGTRACE: SetConsoleTextAttribute(hConsole, 11); break; case ELOGERROR: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY | FOREGROUND_RED); break; case ELOGWARNING: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY | FOREGROUND_RED |FOREGROUND_GREEN); break; } if ( styleFlags.test(E_PSF_PRINT_LOG_TYPE) || styleFlags.test(E_PSF_PRINT_COMPONENT) ) TNL::logprintf(leadIn.CStr()); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY | FOREGROUND_RED |FOREGROUND_GREEN | FOREGROUND_BLUE); char buffer2[4096]; sprintf(buffer2," : %s ",buffer); TNL::logprintf(buffer2); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); */ return; } //************************************ // Method: xLog // FullName: xLogger::xLog // Access: public // Returns: void // Qualifier: // Parameter: int type // Parameter: int component // Parameter: const char *header // Parameter: ... //************************************ void xLogger::xLog(int type,int component,const char *header, ...) { if (!xLogger::GetInstance()->getLogLevel(component).test(1<< type) ) { return; } char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, header ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, header, s); va_end(s); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); char headerBuffer[4096]; char verbosityStr[512]; char componentString[256]; int descriptionS = xLogger::GetInstance()->getItemDescriptions().size(); const char* cString = GetInstance()->getItemDescriptions().at(component); if(component <= xLogger::GetInstance()->getItemDescriptions().size() ) sprintf(componentString,"%s",GetInstance()->getItemDescriptions().at(component)); else sprintf(componentString,"UNKNOWN COMPONENT"); switch(type) { case ELOGINFO: { sprintf(verbosityStr,"\n<-----------------> INFO : |---%s---|\n",componentString); SetConsoleTextAttribute(hConsole, 10); } break; case ELOGTRACE: { sprintf(verbosityStr,"\n<-----------------> TRACE : |---%s---|\n",componentString); SetConsoleTextAttribute(hConsole, 11); } break; case ELOGERROR: { sprintf(verbosityStr,"\n<-----------------> ERROR : |---%s---|\n",componentString); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED); } break; case ELOGWARNING: { sprintf(verbosityStr,"\n<-----------------> WARNING : |---%s---|\n",componentString); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); } break; } sprintf(headerBuffer,"%s",verbosityStr); GetInstance()->finalPrint(headerBuffer); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); char buffer2[4096]; sprintf(buffer2," : %s\n",buffer); GetInstance()->finalPrint(buffer2); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); return; } //************************************ // Method: xLogExtro // FullName: xLogger::xLogExtro // Access: public // Returns: void // Qualifier: // Parameter: int style // Parameter: const char *header // Parameter: ... //************************************ void xLogger::xLogExtro(int style,const char *header, ...) { char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, header ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, header, s); // TNL::Platform::outputDebugString(buffer); // TNL::Platform::outputDebugString("\n"); va_end(s); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); char headerBuffer[4096]; sprintf(headerBuffer,"%s\n",header); GetInstance()->finalPrint(buffer); //printf(headerBuffer); /* SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); */ // printf("\n%s",buffer); //TNL::logprintf(headerBuffer); // TNL::logprintf(buffer); /* SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);*/ return; } void xLogger::xLog(int verbosity,const char *header,const char*msg,...) { char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, msg ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, msg, s); va_end(s); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); char headerBuffer[4096]; char verbosityStr[512]; switch(verbosity) { case ELOGINFO: { sprintf(verbosityStr,"--------------------------------------INFO \n-\n"); SetConsoleTextAttribute(hConsole, 10); } break; case ELOGERROR: { sprintf(verbosityStr,"ooo--------------------------------ERROR \n-\n"); /*SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);*/ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED); } break; } //sprintf(headerBuffer,"%s %s\n\t%s\n----",verbosityStr,header,buffer); sprintf(headerBuffer,"%s %s-\n--",verbosityStr,header); printf(headerBuffer); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); printf("--->%s\n",buffer); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); //TNL::logprintf(headerBuffer); return; va_list va; va_start (va,msg); char bufferN[1024] = { 0 } ; vsprintf(bufferN,msg,va ); va_end (va); printMessage(bufferN); } //************************************ // Method: getLogFlags // FullName: xLogger::getLogFlags // Access: public // Returns: xBitSet& // Qualifier: //************************************ xBitSet& xLogger::getLogFlags() { return GetInstance()->mLogFlags ; } //************************************ // Method: getVerbosityFlags // FullName: xLogger::getVerbosityFlags // Access: public // Returns: xBitSet& // Qualifier: //************************************ xBitSet& xLogger::getVerbosityFlags() { return GetInstance()->m_VerbosityFlags; } //************************************ // Method: isLogging // FullName: xLogger::isLogging // Access: public // Returns: bool // Qualifier: // Parameter: int logItem //************************************ bool xLogger::isLogging(int logItem) { return GetInstance()->getVerbosityFlags().test(1<<logItem); } //************************************ // Method: enableLogItem // FullName: xLogger::enableLogItem // Access: public // Returns: void // Qualifier: // Parameter: int logItem // Parameter: bool enbabled //************************************ void xLogger::enableLogItem(int logItem,bool enbabled) { return GetInstance()->getVerbosityFlags().set(1<< logItem,enbabled); } /* void xLogger::xLog(DWORD verbosity,const char*msg,...) { char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, msg ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, msg, s); va_end(s); //printf(buffer); TNL::logprintf(buffer); return; va_list va; va_start (va,msg); char bufferN[1024] = { 0 } ; vsprintf(bufferN,msg,va ); va_end (va); printMessage(bufferN); } */ void xLogger::Init() { } xLogger::xLogger() { xlog = this; m_LogOutChannels = ELOGGER_NONE; #ifdef VIRTOOLS_USER_SDK mContext = NULL; #endif } //************************************ // Method: GetInstance // FullName: xLogger::GetInstance // Access: public // Returns: xLogger* // Qualifier: //************************************ xLogger*xLogger::GetInstance() { if (xlog ==NULL) { xlog = new xLogger(); } return xlog; } void printMessage(const char*buffer) { using namespace xUtils; /*if ( (xlog->m_LogOutChannels & ELOGGER_CONSOLE) && console ) { //Consoleln(buffer); fflush (stderr); fflush (stdout); strcpy(xlog->m_ConsStream->buf,buffer); } if ( (xlog->m_LogOutChannels & ELOGGER_CEGUI) && ceGUI && xGuiSystem::GetInstance()->m_RenderingGUI ) { getApp->SetDebugPanelText(0,buffer); }*/ } xLogger::~xLogger() { } <file_sep>/* * Tcp4u v 3.31 Last Revision 06/06/1997 3.20 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: skt4u.c * Purpose: Stats on socket usage * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" /* ****************************************************************** */ /* Etage 0 : */ /* Gestion des donnees internes */ /* */ /* ****************************************************************** */ static BOOL bInitDone=FALSE; /* Init has been done */ /* ------------------------------------------------------------------ */ /* Historiques des ouvertures / fermetures */ /* ------------------------------------------------------------------ */ static struct S_HistoSocket HistoSocket[512]; #define FindFirstFreeIdx() FindSocketIdx (INVALID_SOCKET) #define INVALID_INDEX -1 #ifndef INVALID_SOCKET # define INVALID_SOCKET (SOCKET) (-1) #endif /* INVALID_SOCKET */ /* ------------------------------------------------------------------ */ /* recherche d'un index dans le tableau */ /* ------------------------------------------------------------------ */ static int FindSocketIdx (SOCKET s) { int Ark; for (Ark=0 ; Ark<SizeOfTab(HistoSocket) && s!=HistoSocket[Ark].skt ; Ark++); return Ark<SizeOfTab(HistoSocket) ? Ark : INVALID_INDEX; } /* FindSocketIdx */ /* ------------------------------------------------------------------ */ /* Enregistrement d'une socket dans l'historique */ /* ------------------------------------------------------------------ */ void Skt4uRcd (SOCKET sNewSkt, int nState) { int Ark; if ( (Ark=FindFirstFreeIdx()) != INVALID_INDEX) { HistoSocket[Ark].skt = sNewSkt; HistoSocket[Ark].nState = nState; HistoSocket[Ark].nRcv = HistoSocket[Ark].nSnd = 0; HistoSocket[Ark].hTask = GetCurrentTask (); } } /* RcdSocket */ /* ------------------------------------------------------------------ */ /* Elimination d'une socket dans l'historique */ /* ------------------------------------------------------------------ */ void Skt4uUnRcd (SOCKET sClosedSkt) { int Ark; if ( (Ark=FindSocketIdx(sClosedSkt)) != INVALID_INDEX) { HistoSocket[Ark].skt = INVALID_SOCKET; } }/* UnRcdSocket */ /* ********************************************************************** */ /* Etage I : */ /* Initialisations */ /* ********************************************************************** */ /* ----------------------------------------------------- */ /* Initialisation */ /* Pour Windows, on verifie que les sockets attribuees */ /* correspondent a des taches actives. */ /* ----------------------------------------------------- */ int Skt4uInit (void) { int Ark; if (! bInitDone) /* Aucune socket ouverte */ { for (Ark=0 ; Ark<SizeOfTab(HistoSocket) ; Ark++) HistoSocket[Ark].skt = INVALID_SOCKET; bInitDone=TRUE; } #ifdef WINDOWS /* liberation des sockets appartenant a des taches mortes */ else { for (Ark=0 ; Ark<SizeOfTab(HistoSocket) ; Ark++) if ( HistoSocket[Ark].skt!=INVALID_SOCKET && !IsTask(HistoSocket[Ark].hTask) ) TcpClose (& HistoSocket[Ark].skt); } /* InitDone */ #endif return TCP4U_SUCCESS; } /* Skt4wInit */ /* ------------------------------------------------------------------ */ /* Destructeurs */ /* ------------------------------------------------------------------ */ int Skt4uCleanup (void) { int Ark; if (bInitDone) { /* blocking call ? */ if (WSAIsBlocking()) { WSACancelBlockingCall (); return TCP4U_ERROR; } else { /* TcpClose (&s) force s a -1 -> pas besoin de UnrcdSkt */ for (Ark=0 ; Ark<SizeOfTab(HistoSocket) ; Ark++) if ( HistoSocket[Ark].hTask == GetCurrentTask () && HistoSocket[Ark].skt != INVALID_SOCKET ) TcpClose (& HistoSocket[Ark].skt); WSACleanup (); } /* requete non bloquante */ } /* bInitDone */ return TCP4U_SUCCESS; } /* Skt4wCleanup */ /* *************************************************************** */ /* Etage II : */ /* Statistiques */ /* *************************************************************** */ /* ------------------------------------------------------------------ */ /* Add the number of received bytes */ /* ------------------------------------------------------------------ */ void Skt4uAddRcvSocket (SOCKET sSkt, int nRcv) { int Ark; if ( (Ark=FindSocketIdx(sSkt)) != INVALID_INDEX) HistoSocket[Ark].nRcv += nRcv; } /* SktAddRcvSocket */ /* ------------------------------------------------------------------ */ /* Add the number of sent bytes */ /* ------------------------------------------------------------------ */ void Skt4uAddSndSocket (SOCKET sSkt, int nSnd) { int Ark; if ( (Ark=FindSocketIdx(sSkt)) != INVALID_INDEX) HistoSocket[Ark].nSnd += nSnd; } /* SktAddSndSocket */ /* ------------------------------------------------------------------ */ /* Returns a pointer on the struct for socket sSkt */ /* ------------------------------------------------------------------ */ struct S_HistoSocket *Skt4uGetStats (SOCKET sSkt) { int Ark; if ( (Ark=FindSocketIdx(sSkt)) != INVALID_INDEX) { return & HistoSocket[Ark]; } return NULL; } /* S_HistoSocket */ <file_sep>#ifndef __X_MESSAGE_H_ #define __X_MESSAGE_H_ #include "xNetTypes.h" class xMessage { public : xMessage() { messageID = -1; messageType = -1; mFlags = 0 ; lifeTime = 0.0f; mSendCount =0; srcUser = -1; dstUser = -1; mNumUsers = 0; } float getLifeTime() const { return lifeTime; } void setLifeTime(float val) { lifeTime = val; } bool IsComplete() const { return complete; } void SetComplete(bool val) { complete = val; } int getDstUser() const { return dstUser; } void setDstUser(int val) { dstUser = val; } int getSrcUser() const { return srcUser; } void setSrcUser(int val) { srcUser = val; } int getClientSideSrcUser() const { return clientSideSrcUser; } void setClientSideSrcUser(int val) { clientSideSrcUser = val; } int getNumParameters() { return mParameters.size(); } int getMessageID() const { return messageID; } void setMessageID(int val) { messageID = val; } int getMessageType() const { return messageType; } void setMessageType(int val) { messageType = val; } xNString getName() const { return name; } void setName(xNString val) { name = val; } TNL::BitSet32& getFlags() { return mFlags; } void setFlags(TNL::BitSet32 val) { mFlags = val; } int getSendCount() { return mSendCount; } void setSendCount(int val) { mSendCount = val; } ~xMessage(); xDistributedPropertyArrayType mParameters; xDistributedPropertyArrayType& getParameters() { return mParameters; } xDistributedClient * getClientSource() { return mClientSource; } void setClientSource(xDistributedClient * val) { mClientSource = val; } bool getIgnoreSessionMaster() const { return ignoreSessionMaster; } void setIgnoreSessionMaster(bool val) { ignoreSessionMaster = val; } int& getNumUsers() { return mNumUsers; } void setNumUsers(int val) { mNumUsers = val; } protected : float lifeTime; bool complete; int dstUser; int srcUser; int clientSideSrcUser; int messageID; int messageType; xNString name; TNL::BitSet32 mFlags; int mSendCount; int mNumUsers; bool ignoreSessionMaster; xDistributedClient *mClientSource; }; #endif<file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #include "tnlTypes.h" #include "tnl.h" #include "tnlJournal.h" #include <string.h> #if defined (TNL_OS_XBOX) #include <xtl.h> #elif defined (TNL_OS_WIN32) #include <windows.h> #include <malloc.h> #else #include <unistd.h> #include <signal.h> #include <sys/time.h> #endif #include <stdlib.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include "tnlRandom.h" #include "tnlLog.h" namespace TNL { #if defined (TNL_OS_XBOX) void Platform::outputDebugString(const char *string) { OutputDebugString(string); } void Platform::debugBreak() { DebugBreak(); } void Platform::forceQuit() { logprintf("-Force Quit-"); // Reboot! LD_LAUNCH_DASHBOARD LaunchData = { XLD_LAUNCH_DASHBOARD_MAIN_MENU }; XLaunchNewImage( NULL, (LAUNCH_DATA*)&LaunchData ); } U32 Platform::getRealMilliseconds() { U32 tickCount; TNL_JOURNAL_READ_BLOCK ( getRealMilliseconds, TNL_JOURNAL_READ( (&tickCount) ); return tickCount; ) tickCount = GetTickCount(); TNL_JOURNAL_WRITE_BLOCK ( getRealMilliseconds, TNL_JOURNAL_WRITE( (tickCount) ); ) return tickCount; } //-------------------------------------- void Platform::AlertOK(const char *windowTitle, const char *message) { // ShowCursor(true); // MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OK); TNLLogMessageV(LogPlatform, ("AlertOK: %s - %s", message, windowTitle)); return; } //-------------------------------------- bool Platform::AlertOKCancel(const char *windowTitle, const char *message) { // ShowCursor(true); // return MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OKCANCEL) == IDOK; TNLLogMessageV(LogPlatform, ("AlertOKCancel: %s - %s", message, windowTitle)); return false; } //-------------------------------------- bool Platform::AlertRetry(const char *windowTitle, const char *message) { // ShowCursor(true); // return (MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_RETRYCANCEL) == IDRETRY); TNLLogMessageV(LogPlatform, ("AlertRetry: %s - %s", message, windowTitle)); return false; } class WinTimer { private: F64 mPeriod; bool mUsingPerfCounter; public: WinTimer() { S64 frequency; mUsingPerfCounter = QueryPerformanceFrequency((LARGE_INTEGER *) &frequency); mPeriod = 1000.0f / F64(frequency); } S64 getCurrentTime() { if(mUsingPerfCounter) { S64 value; QueryPerformanceCounter( (LARGE_INTEGER *) &value); return value; } else { return GetTickCount(); } } F64 convertToMS(S64 delta) { if(mUsingPerfCounter) return mPeriod * F64(delta); else return F64(delta); } }; static WinTimer gTimer; S64 Platform::getHighPrecisionTimerValue() { return gTimer.getCurrentTime(); } F64 Platform::getHighPrecisionMilliseconds(S64 timerDelta) { return gTimer.convertToMS(timerDelta); } void Platform::sleep(U32 msCount) { // no need to sleep on the xbox... } #elif defined (TNL_OS_WIN32) bool Platform::checkHeap() { #ifdef TNL_COMPILER_VISUALC return _heapchk() == _HEAPOK; #else return true; #endif } void Platform::outputDebugString(const char *string) { OutputDebugString(string); } void Platform::debugBreak() { DebugBreak(); } void Platform::forceQuit() { ExitProcess(1); } U32 Platform::getRealMilliseconds() { U32 tickCount; TNL_JOURNAL_READ_BLOCK ( getRealMilliseconds, TNL_JOURNAL_READ( (&tickCount) ); return tickCount; ) tickCount = GetTickCount(); TNL_JOURNAL_WRITE_BLOCK ( getRealMilliseconds, TNL_JOURNAL_WRITE( (tickCount) ); ) return tickCount; } class WinTimer { private: F64 mPeriod; bool mUsingPerfCounter; public: WinTimer() { S64 frequency; mUsingPerfCounter = QueryPerformanceFrequency((LARGE_INTEGER *) &frequency); mPeriod = 1000.0f / F64(frequency); } S64 getCurrentTime() { if(mUsingPerfCounter) { S64 value; QueryPerformanceCounter( (LARGE_INTEGER *) &value); return value; } else { return GetTickCount(); } } F64 convertToMS(S64 delta) { if(mUsingPerfCounter) return mPeriod * F64(delta); else return F64(delta); } }; static WinTimer gTimer; S64 Platform::getHighPrecisionTimerValue() { S64 currentTime; TNL_JOURNAL_READ_BLOCK ( getHighPrecisionTimerValue, TNL_JOURNAL_READ( (&currentTime) ); return currentTime; ) currentTime = gTimer.getCurrentTime(); TNL_JOURNAL_WRITE_BLOCK ( getHighPrecisionTimerValue, TNL_JOURNAL_WRITE( (currentTime) ); ) return currentTime; } F64 Platform::getHighPrecisionMilliseconds(S64 timerDelta) { F64 timerValue; TNL_JOURNAL_READ_BLOCK ( getHighPrecisionMilliseconds, TNL_JOURNAL_READ( (&timerValue) ); return timerValue; ) timerValue = gTimer.convertToMS(timerDelta); TNL_JOURNAL_WRITE_BLOCK ( getHighPrecisionMilliseconds, TNL_JOURNAL_WRITE( (timerValue) ); ) return timerValue; } void Platform::sleep(U32 msCount) { Sleep(msCount); } //-------------------------------------- void Platform::AlertOK(const char *windowTitle, const char *message) { ShowCursor(true); MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OK); } //-------------------------------------- bool Platform::AlertOKCancel(const char *windowTitle, const char *message) { ShowCursor(true); return MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OKCANCEL) == IDOK; } //-------------------------------------- bool Platform::AlertRetry(const char *windowTitle, const char *message) { ShowCursor(true); return (MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_RETRYCANCEL) == IDRETRY); } #else // osx and linux void Platform::debugBreak() { kill(getpid(), SIGTRAP); } void Platform::outputDebugString(const char *string) { //printf("%s", string); } void Platform::forceQuit() { debugBreak(); exit(1); } U32 x86UNIXGetTickCount(); //-------------------------------------- U32 Platform::getRealMilliseconds() { return x86UNIXGetTickCount(); } static bool sg_initialized = false; static U32 sg_secsOffset = 0; U32 x86UNIXGetTickCount() { // TODO: What happens when crossing a day boundary? // timeval t; if (sg_initialized == false) { sg_initialized = true; ::gettimeofday(&t, NULL); sg_secsOffset = t.tv_sec; } ::gettimeofday(&t, NULL); U32 secs = t.tv_sec - sg_secsOffset; U32 uSecs = t.tv_usec; // Make granularity 1 ms return (secs * 1000) + (uSecs / 1000); } class UnixTimer { public: UnixTimer() { } S64 getCurrentTime() { return x86UNIXGetTickCount(); } F64 convertToMS(S64 delta) { return F64(delta); } }; static UnixTimer gTimer; S64 Platform::getHighPrecisionTimerValue() { return gTimer.getCurrentTime(); } F64 Platform::getHighPrecisionMilliseconds(S64 timerDelta) { return gTimer.convertToMS(timerDelta); } void Platform::sleep(U32 msCount) { usleep(msCount * 1000); } //-------------------------------------- void Platform::AlertOK(const char *windowTitle, const char *message) { // ShowCursor(true); // MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OK); TNLLogMessageV(LogPlatform, ("AlertOK: %s - %s", message, windowTitle)); return; } //-------------------------------------- bool Platform::AlertOKCancel(const char *windowTitle, const char *message) { // ShowCursor(true); // return MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_OKCANCEL) == IDOK; TNLLogMessageV(LogPlatform, ("AlertOKCancel: %s - %s", message, windowTitle)); return false; } //-------------------------------------- bool Platform::AlertRetry(const char *windowTitle, const char *message) { // ShowCursor(true); // return (MessageBox(NULL, message, windowTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TASKMODAL | MB_RETRYCANCEL) == IDRETRY); TNLLogMessageV(LogPlatform, ("AlertRetry: %s - %s", message, windowTitle)); return false; } #endif /* char *strdup(const char *src) { char *buffer = (char *) malloc(strlen(src) + 1); strcpy(buffer, src); return buffer; }*/ bool atob(const char *str) { return !stricmp(str, "true") || atof(str); } S32 dSprintf(char *buffer, U32 bufferSize, const char *format, ...) { va_list args; va_start(args, format); #ifdef TNL_COMPILER_VISUALC S32 len = _vsnprintf(buffer, bufferSize, format, args); #else S32 len = vsnprintf(buffer, bufferSize, format, args); #endif return (len); } S32 dVsprintf(char *buffer, U32 bufferSize, const char *format, void *arglist) { #ifdef TNL_COMPILER_VISUALC S32 len = _vsnprintf(buffer, bufferSize, format, (va_list) arglist); #else S32 len = vsnprintf(buffer, bufferSize, format, (char *) arglist); #endif return len; } }; #if defined (__GNUC__) int stricmp(const char *str1, const char *str2) { while(toupper(*str1) == toupper(*str2) && *str1) { str1++; str2++; } return (toupper(*str1) > toupper(*str2)) ? 1 : ((toupper(*str1) < toupper(*str2)) ? -1 : 0); } int strnicmp(const char *str1, const char *str2, unsigned int len) { for(unsigned int i = 0; i < len; i++) { if(toupper(str1[i]) == toupper(str2[i])) continue; return (toupper(str1[i]) > toupper(str2[i])) ? 1 : ((toupper(str1[i]) < toupper(str2[i])) ? -1 : 0); } return 0; } #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" using namespace vtAgeia; pJointD6::pJointD6(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_D6) { } void pJointD6::setDriveAngularVelocity(VxVector angVel) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return; joint->saveToDesc(descr); //joint->setDriveAngularVelocity(pMath::getFrom(angVel)); descr.driveAngularVelocity = (pMath::getFrom(angVel)); joint->loadFromDesc(descr); } ////////////////////////////////////////////////////////////////////////// void pJointD6::setDriveLinearVelocity(VxVector linVel) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); //joint->setDriveLinearVelocity(pMath::getFrom(linVel)); descr.driveLinearVelocity = (pMath::getFrom(linVel)); joint->loadFromDesc(descr); } ////////////////////////////////////////////////////////////////////////// void pJointD6::setDriveRotation(VxQuaternion rot) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); joint->setDriveOrientation(pMath::getFrom(rot)); joint->loadFromDesc(descr); } ////////////////////////////////////////////////////////////////////////// void pJointD6::setDrivePosition(VxVector pos) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); joint->setDrivePosition(pMath::getFrom(pos)); descr.drivePosition = (pMath::getFrom(pos)); joint->loadFromDesc(descr); } ////////////////////////////////////////////////////////////////////////// pJD6Drive pJointD6::getSlerpDrive() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6Drive result(descr.slerpDrive.damping,descr.slerpDrive.spring,descr.slerpDrive.forceLimit,descr.slerpDrive.driveType.bitField); return result; } int pJointD6::setSlerpDrive(pJD6Drive drive) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.slerpDrive = sdrive; descr.flags |=NX_D6JOINT_SLERP_DRIVE; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6Drive pJointD6::getTwistDrive() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6Drive result(descr.twistDrive.damping,descr.twistDrive.spring,descr.twistDrive.forceLimit,descr.twistDrive.driveType); return result; } int pJointD6::setTwistDrive(pJD6Drive drive) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.twistDrive = sdrive; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6Drive pJointD6::getSwingDrive() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6Drive result(descr.swingDrive.damping,descr.swingDrive.spring,descr.swingDrive.forceLimit,descr.swingDrive.driveType); return result; } int pJointD6::setSwingDrive(pJD6Drive drive) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.swingDrive = sdrive; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6Drive pJointD6::getZDrive() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6Drive result(descr.zDrive.damping,descr.zDrive.spring,descr.zDrive.forceLimit,descr.zDrive.driveType); return result; } int pJointD6::setZDrive(pJD6Drive drive) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.zDrive = sdrive; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6Drive pJointD6::getYDrive() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6Drive result(descr.yDrive.damping,descr.yDrive.spring,descr.yDrive.forceLimit,descr.yDrive.driveType); return result; } int pJointD6::setYDrive(pJD6Drive drive) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.yDrive = sdrive; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6Drive pJointD6::getXDrive() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6Drive result(descr.xDrive.damping,descr.xDrive.spring,descr.xDrive.forceLimit,descr.xDrive.driveType); return result; } int pJointD6::setXDrive(pJD6Drive drive) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.xDrive = sdrive; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6SoftLimit pJointD6::getTwistLowLimit() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6SoftLimit result(descr.twistLimit.low.damping,descr.twistLimit.low.spring,descr.twistLimit.low.value,descr.twistLimit.low.restitution); return result; } int pJointD6::setTwistLowLimit(pJD6SoftLimit limit) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; if (!sLimit.isValid())return -1; descr.twistLimit.low= sLimit; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6SoftLimit pJointD6::getTwistHighLimit() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6SoftLimit result(descr.twistLimit.high.damping,descr.twistLimit.high.spring,descr.twistLimit.high.value,descr.twistLimit.high.restitution); return result; } int pJointD6::setTwistHighLimit(pJD6SoftLimit limit) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; if (!sLimit.isValid())return -1; descr.twistLimit.high= sLimit; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6SoftLimit pJointD6::getSwing2Limit() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6SoftLimit result(descr.swing2Limit.damping,descr.swing2Limit.spring,descr.swing2Limit.value,descr.swing2Limit.restitution); return result; } int pJointD6::setSwing2Limit(pJD6SoftLimit limit) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; if (!sLimit.isValid())return -1; descr.swing2Limit= sLimit; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6SoftLimit pJointD6::getSwing1Limit() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6SoftLimit result(descr.swing1Limit.damping,descr.swing1Limit.spring,descr.swing1Limit.value,descr.swing1Limit.restitution); return result; } int pJointD6::setSwing1Limit(pJD6SoftLimit limit) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; if (!sLimit.isValid())return -1; descr.swing1Limit= sLimit; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// pJD6SoftLimit pJointD6::getLinearLimit() { NxD6JointDesc descr;NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());joint->saveToDesc(descr); pJD6SoftLimit result(descr.linearLimit.damping,descr.linearLimit.spring,descr.linearLimit.value,descr.linearLimit.restitution); return result; } int pJointD6::setLinearLimit(pJD6SoftLimit limit) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; if (!sLimit.isValid())return -1; descr.linearLimit = sLimit; joint->loadFromDesc(descr); return 1; } ////////////////////////////////////////////////////////////////////////// void pJointD6::setTwistMotionMode(D6MotionMode mode) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());if (!joint)return;joint->saveToDesc(descr); descr.twistMotion = (NxD6JointMotion)mode; joint->loadFromDesc(descr); } void pJointD6::setSwing1MotionMode(D6MotionMode mode) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());if (!joint)return;joint->saveToDesc(descr); descr.swing1Motion = (NxD6JointMotion)mode; joint->loadFromDesc(descr); } void pJointD6::setSwing2MotionMode(D6MotionMode mode) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());if (!joint)return;joint->saveToDesc(descr); descr.swing2Motion = (NxD6JointMotion)mode; joint->loadFromDesc(descr); } void pJointD6::setXMotionMode(D6MotionMode mode) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());if (!joint)return;joint->saveToDesc(descr); descr.xMotion = (NxD6JointMotion)mode; joint->loadFromDesc(descr); } void pJointD6::setYMotionMode(D6MotionMode mode) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());if (!joint)return;joint->saveToDesc(descr); descr.yMotion = (NxD6JointMotion)mode; joint->loadFromDesc(descr); } void pJointD6::setZMotionMode(D6MotionMode mode) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint());if (!joint)return;joint->saveToDesc(descr); descr.zMotion = (NxD6JointMotion)mode; joint->loadFromDesc(descr); } D6MotionMode pJointD6::getTwist() { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return D6MM_Locked; joint->saveToDesc(descr); return (D6MotionMode)descr.twistMotion; } D6MotionMode pJointD6::getSwing1() { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return D6MM_Locked; joint->saveToDesc(descr); return (D6MotionMode)descr.swing1Motion; } D6MotionMode pJointD6::getSwing2() { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return D6MM_Locked; joint->saveToDesc(descr); return (D6MotionMode)descr.swing2Motion; } D6MotionMode pJointD6::getXMotion() { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return D6MM_Locked; joint->saveToDesc(descr); return (D6MotionMode)descr.xMotion; } D6MotionMode pJointD6::getYMotion() { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return D6MM_Locked; joint->saveToDesc(descr); return (D6MotionMode)descr.yMotion; } D6MotionMode pJointD6::getZMotion() { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return D6MM_Locked; joint->saveToDesc(descr); return (D6MotionMode)descr.zMotion; } void pJointD6::setGlobalAnchor(VxVector anchor) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); joint->setGlobalAnchor(pMath::getFrom(anchor)); } void pJointD6::setGlobalAxis(VxVector axis) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); joint->setGlobalAxis(pMath::getFrom(axis)); //joint->setGlobalA(pMath::getFrom(anchor)); } void pJointD6::setRatio(float ratio) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (ratio!=0.0f) { descr.jointFlags|=NX_D6JOINT_GEAR_ENABLED; descr.gearRatio = ratio; }else { descr.jointFlags&=~NX_D6JOINT_GEAR_ENABLED; } joint->loadFromDesc(descr); } void pJointD6::enableCollision( bool value ) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (value) { descr.jointFlags|=NX_JF_COLLISION_ENABLED; }else { descr.jointFlags&=~NX_JF_COLLISION_ENABLED; } joint->loadFromDesc(descr); } void pJointD6::setProjectionMode(ProjectionMode mode) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.projectionMode = (NxJointProjectionMode)mode; joint->loadFromDesc(descr); } void pJointD6::setProjectionDistance(float distance) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.projectionDistance= distance; joint->loadFromDesc(descr); } void pJointD6::setProjectionAngle(float angle) { NxD6JointDesc descr; NxD6Joint *joint = static_cast<NxD6Joint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.projectionAngle= angle; joint->loadFromDesc(descr); }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> #include "pDifferential.h" #include "pVehicleAll.h" //+ velWheelCC {x=66.735077 y=0.097698294 z=-215.35669 ...} VxVector //+ velWheelTC {x=66.735077 y=0.097698294 z=-215.35669 ...} VxVector enum StateFlags { ON_SURFACE=1, // Wheel is touching surface? ATTACHED=2, // Attached to suspension? LOW_SPEED=4 // Wheel is turning slow }; #define FRICTION_COEFF 100.0f #define MASS 12 #define TIRE_RATE 50000.0f #define WHEEL_PENETRATION_DEPTH -0.0258f #define WHEEL_SUSPENSION_FORCE VxVector(0,-1025.0f,0) #define RR_EPSILON_VELOCITY 0.001 // Wheel velocity #define OPT_SLIPVECTOR_USES_TANSA // Use full 3D patch for surface detection? #define USE_3D_PATCH #define ENV_INI "env.ini" // For method #3, slipVector (Gregor Veble), use tan(SA) or SA? #define OPT_SLIPVECTOR_USES_TANSA // Skid methods //#define SKID_METHOD_SEPARATE_LON_LAT //#define SKID_METHOD_SLIP_RA_VECTOR #define SKID_METHOD_Z_GREGOR // Point at which skidmarks appear #define SKIDMARK_SLIPRATIO 0.2 // Apply damping to slipRatio/slipAngle differential eq's at low speed? //#define DO_DAMPING_LAT //#define DO_DAMPING_LONG // Apply low-speed enhancements? (obsolete since 18-5-01) #define DO_LOW_SPEED // Distance (in m) to start with wheel ray-track intersection; this is // the height at which the ray is started to avoid getting a ray // that starts BENEATH the track surface and therefore not hitting it. #define DIST_INTERSECT 1.0 // Define the next symbol to check for wheel velocity reversal (vertically), // and if so, the wheel is stopped momentarily. Is used to rule out // incredibly high damper forces from pushing the wheel to full up or down. // Should perhaps not be needed anymore combined with the implicit integrator. // Note that this acts at the outermost positions of the wheel. //#define DAMP_VERTICAL_VELOCITY_REVERSAL // Damp the wheel when crossing the equilibrium position? // As the wheel passes its center position, the spring force reverses. To // avoid adding energy into the system, when passing this position, damping // is used to avoid overaccelerating the tire to the other side. // Note that this acts when the wheel is near its center (rest) position, // contrast this with DAMP_VERTICAL_VELOCITY_REVERSAL. #define DAMP_VERTICAL_EQUILIBRIUM_REVERSAL // Use implicit integration? This should be more stable with // high damper rates. #define INTEGRATE_IMPLICIT_VERTICAL // Gregor Veble combined slip algorithm? (instead of Pacejka) //#define DO_GREGOR #ifdef DO_GREGOR #undef DO_DAMPING_LAT #undef DO_DAMPING_LONG #endif // Delayed slip angle? //#define USE_SAE950311_LAT // If not using SAE950311, damp SA at low speed? (to avoid jittering) #define USE_SA_DAMPING_AT_LOW_SPEED // Wheel locking results in force going the direction of -slipVector? #define USE_WHEEL_LOCK_ADJUST #define USE_NXWHEEL_CONTACT_DATA #define USE_NXWHEEL_NORMALFORCE_LOAD static int getFrictionMethod(){ return FC_SLIPVECTOR; } void pWheel2::CalcPacejka() { float normalForce; if (hadContact) { normalForce=forceRoadTC.y; }else{ normalForce = 0.0f; } /* if (hadContact) { normalForce=500.0f; }else{ normalForce = 0.0f; } */ pacejka.SetCamber(0); bool FC_SLIPVECTOR =true; // Note our positive slipAngle is the reverse of SAE's definition if(FC_SLIPVECTOR) { // <NAME>'s and also <NAME>'s idea of mixing Pacejka // Note that Gregor's Veble 'z' is 'csSlipLen' here. // The load isn't touched pacejka.SetNormalForce(normalForce); // Lateral //qdbg(" csSlipLen=%f, oSA=%f,oSR=%f\n",csSlipLen,optimalSA,optimalSR); if(csSlipLen<D3_EPSILON) { //qdbg(" csSlipLen near 0; load %f\n",normalForce); pacejka.SetSlipAngle(0); pacejka.SetSlipRatio(0); // Calculate separate Flat/Flong (Fy/Fx) pacejka.Calculate(); } else { if(slipAngle<0) pacejka.SetSlipAngle(csSlipLen*optimalSA); else pacejka.SetSlipAngle(-csSlipLen*optimalSA); // Longitudinal if(slipRatio<0) pacejka.SetSlipRatio(-csSlipLen*optimalSR); else pacejka.SetSlipRatio(csSlipLen*optimalSR); // Calculate separate Flat/Flong (Fy/Fx) pacejka.Calculate(); // Combine #ifdef OPT_SLIPVECTOR_USES_TANSA pacejka.SetFy( (fabs(tanSlipAngle)/(tanOptimalSA*csSlipLen))* pacejka.GetFy()); pacejka.SetMz( (fabs(tanSlipAngle)/(tanOptimalSA*csSlipLen))* pacejka.GetMz()); #else // Use normal slip angle pacejka.SetFy( (fabs(slipAngle)/(optimalSA*csSlipLen))*pacejka.GetFy()); pacejka.SetMz( (fabs(slipAngle)/(optimalSA*csSlipLen))*pacejka.GetMz()); #endif pacejka.SetFx( (fabs(slipRatio)/(optimalSR*csSlipLen))*pacejka.GetFx()); } } else { // Calculate Fx and Fy really separate, and possible combine later pacejka.SetSlipAngle(-slipAngle); pacejka.SetSlipRatio(slipRatio); pacejka.SetNormalForce(normalForce); // Calculate separate Flat/Flong (Fy/Fx), and maximum force // Combined Pacejka (slipratio & slipangle) will be done later pacejka.Calculate(); } //---------------------------------------------------------------- // // // // Adjust forces according to the surface // May also add here some Pacejka scaling to get quick grip changes /* RSurfaceType *st=surfaceInfo.surfaceType; if(st) { if(st->frictionFactor!=1.0f) { float frictionFactor = 0.1f; pacejka.SetFx(pacejka.GetFx()*frictionFactor); pacejka.SetFy(pacejka.GetFy()*frictionFactor); // Do the same to the aligning moment, although not scientifically // based (does aligning torque scale linearly with surface friction?) pacejka.SetMz(pacejka.GetMz()*frictionFactor); pacejka.SetMaxLongForce(pacejka.GetMaxLongForce()*frictionFactor); pacejka.SetMaxLatForce(pacejka.GetMaxLatForce()*frictionFactor); } */ //forceRoadTC.z=pacejka.GetFx(); //---------------------------------------------------------------- // // old // /* float factor = getVehicle()->getEngine()->getForceFeedbackScale(); float longitudalImpulse = xCheckFloat(lastContactData->longitudalImpulse); if (lastContactData) { forceRoadTC.z= longitudalImpulse * factor; }*/ // Put some results in appropriate variables #ifdef LTRACE qdbg(" pacejka.Fx=%f\n",pacejka.GetFx()); #endif float fx = pacejka.GetFx();; forceRoadTC.z=pacejka.GetFx(); } void ConvertTireToCarOrientation(pWheel2 * wheel , VxVector *from,VxVector *to) // Convert vector 'from' from tire coordinates // to car coordinates (into 'to') // Assumes: from!=to { if (!wheel) return; float angle,sinAngle,cosAngle; // Note that the tire is constrained in 5 dimensions, so only // 1 rotation needs to be done // Heading angle=wheel->GetHeading(); sinAngle=sin(angle); cosAngle=cos(angle); // Rotate around Y axis to get heading of car right to->x=from->z*sinAngle+from->x*cosAngle; to->y=from->y; to->z=from->z*cosAngle-from->x*sinAngle; } void ConvertCarToTireOrientation (pWheel2*wheel, VxVector *from,VxVector*to) // Convert vector 'from' from car coordinates // to tire coordinates (into 'to') // Assumes: from!=to { if (!wheel) return; float angle,sinAngle,cosAngle; // Heading angle=-wheel->GetHeading(); if(fabs(angle)<D3_EPSILON) { *to=*from; return; } sinAngle=sin(angle); cosAngle=cos(angle); // Rotate around Y axis to get heading of car right to->x=from->z*sinAngle+from->x*cosAngle; to->y=from->y; to->z=from->z*cosAngle-from->x*sinAngle; //to->DbgPrint("C2T to"); } void pWheel2::calcVerticalForces() { VxVector downGravity; //float mass = getVehicle()->getBody()->getMass(); NxVec3 grav; getVehicle()->getBody()->getActor()->getScene().getGravity(grav); downGravity.y = -mass * -grav.y ; if (getEntity()) { getEntity()->TransformVector(&forceGravityCC,&downGravity); } forceVerticalCC=forceGravityCC+forceRoadTC+WHEEL_SUSPENSION_FORCE; float inverseWheelMass = mWheelShape->getInverseWheelMass(); } void pWheel2::calcLongForces() { if (lastContactData) { // // LONGITUDINAL FORCES // // Differential will do resulting long. torques for the engine // Calculate longitudinal road reaction force using Pacejka's magic formula float pf; // Pacejka float factor = getVehicle()->getEngine()->getForceFeedbackScale(); float longitudalImpulse = xCheckFloat(lastContactData->longitudalImpulse); //qdbg("Pacejka Fx=%f, signU=%f\n",pf,signU); forceRoadTC.z= factor * longitudalImpulse * signU ; } } void pWheel2::calcBreakForces() { } void pWheel2::preAnimate() { //---------------------------------------------------------------- // // store last contact // hadContact = getContact(*lastContactData); //---------------------------------------------------------------- // // reset // forceRoadTC.Set(0,0,0); torqueTC.Set(0,0,0); torqueFeedbackTC.Set(0,0,0); dampingFactorLong=dampingFactorLat=0; forceVerticalCC.Set(0,0,0); forceDampingTC.Set(0,0,0); torqueTC.Set(0,0,0); torqueFeedbackTC.Set(0,0,0); velWheelTC.Set(0,0,0); velWheelCC.Set(0,0,0); //signU = ( getVehicle()->_currentStatus & VS_IsRollingForward ) ? 1.0f : - 1.0f; CalcLoad(); CalcSlipAngle(); CalcSlipRatio(&velWheelTC); float tanOptimalSA=tan(0.18296f); float optimalSR=0.0965f; bool make =true; if(getFrictionMethod() == FC_SLIPVECTOR) { // Calculate SA/SR vector length (>1 = wanting more than tire supports) float lat,lon; if (getVehicle()->getProcessOptions() & pVPO_SV_Tansa ) lat=tanSlipAngle/tanOptimalSA; else lat=slipAngle/optimalSA; lon=slipRatio/optimalSR; csSlipLen=sqrtf(lat*lat+lon*lon); //qdbg(" latNrm=%f, lonNrm=%f, csSlipLen=%f\n",lat,lon,csSlipLen); } CalcSlipVelocity(); // Low speed detection if (getVehicle()->getProcessOptions() & pVPO_CheckLowSpeed) { float lowSpeed = 0.03f; if(rotationV.x>-lowSpeed&&rotationV.x<lowSpeed) { stateFlags|=LOW_SPEED; // Calculate factor from 0..1. 0 means real low, 1 is on the edge // of becoming high-enough speed. lowSpeedFactor=rotationV.x/lowSpeed; // Don't zero out all if(lowSpeedFactor<0.01f) lowSpeedFactor=0.01f; } else { stateFlags&=~LOW_SPEED; } } CalcPacejka(); CalcDamping(); //CalcSlipAngle(); //CalcSlipRatio(&velWheelTC); } void pWheel2::CalcSlipVelocity() { slipVectorTC.x=0; slipVectorTC.y=0; slipVectorTC.z=rotationV.x*radius; ConvertTireToCarOrientation(this,&slipVectorTC,&slipVectorCC); /* VxVector a0(1,2,3); VxVector a1(3,4,5); ConvertCarToTireOrientation(this,&a0,&a1);*/ //a1 = {x=1.0522050 y=2.0000000 z=2.9820907 ...} slipVectorCC-=velWheelCC; // Calculate length of slip slipVectorLength=slipVectorCC.Magnitude(); // Calculate resulting friction coefficient // This will be used to determine the tire's maximum force float coeff = slipVectorLength/slip2FCVelFactor; bool make = true; /*if(make) frictionCoeff=crvSlip2FC->GetValue(coeff); else*/ this->frictionCoeff=1.0f; } void pWheel2::CalcLoad() { if (hadContact) { //forceRoadTC.y=-50*0.057598811f;// float; lastContactData->contactForce; if ( (getVehicle()->getProcessOptions() & pVPO_Wheel_UsePHYSX_Load) && (getVehicle()->getProcessOptions() & pVPO_Wheel_UsePHYSX_CONTACT_DATA) ) { forceRoadTC.y = load; } else{ forceRoadTC.y=-tireRate * WHEEL_PENETRATION_DEPTH;// float; lastContactData->contactForce; } stateFlags|=ON_SURFACE; }else { stateFlags&=~ON_SURFACE; forceRoadTC.y = 0.0f; } //load=forceRoadTC.y; radiusLoaded=getWheelShape()->getRadius(); } void pWheel2::calcForces() { if (hadContact) { float len; float pf=0.0f; float radiusLoaded = getRadius(); //---------------------------------------------------------------- // // vertical forces // NxVec3 grav;getBody()->getActor()->getScene().getGravity(grav); VxVector forceGravityWC; forceGravityWC.y = getMass() * grav.y; if (getEntity()) getEntity()->TransformVector(&forceGravityCC,&forceGravityWC); VxVector suspension; suspension.y = -load; forceVerticalCC=forceGravityCC+forceRoadTC+suspension; //---------------------------------------------------------------- // // long forces // // // LONGITUDINAL FORCES // // Differential will do resulting long. torques for the engine // Calculate longitudinal road reaction force using Pacejka's magic formula // Pacejka //float factor = getVehicle()->getEngine()->getForceFeedbackScale(); //float longitudalImpulse = xCheckFloat(lastContactData->longitudalImpulse); //qdbg("Pacejka Fx=%f, signU=%f\n",pf,signU); //forceRoadTC.z= factor * longitudalImpulse * signU ; //---------------------------------------------------------------- // // // #ifdef DO_GREGOR pf=Fx; #else // Pacejka pf=pacejka.GetFx()*this->frictionCoeff; #endif //qdbg("Pacejka Fx=%f, signU=%f\n",pf,signU); forceRoadTC.z=signU*pf; if ( getVehicle()->getProcessOptions() & pVPO_Lat_Damping ) { // Add damping force because of slipRatio vibrations // at low speed (SAE950311) forceRoadTC.z+=forceDampingTC.z; //qdbg("FroadTC.z=%f, Fdamp=%f\n",forceRoadTC.z,forceDampingTC.z); } //---------------------------------------------------------------- // // Calculate braking forces & torques (brakes & rolling resistance) // float curBrakingTorque; // Calculate braking torque more directly float bTorqueV = getVehicle()->calculateBraking( getVehicle()->_lastDT ); curBrakingTorque= bTorqueV * maxBrakingTorque/1000.0f; curBrakingTorque*=brakingFactor; // Apply braking torque in the reverse direction of the wheel's rotation if(rotationV.x>0) { torqueBrakingTC.x=curBrakingTorque; } else { torqueBrakingTC.x=-curBrakingTorque; } forceBrakingTC.z=torqueBrakingTC.x/radiusLoaded; // Calculate feedback torque (goes back to differential) // This doesn't include braking and rolling resistance, which are // potential braking forces (which may not be fully used if the // wheel is not rotating), but only the forces which are always // there, like road reaction. torqueFeedbackTC.x=-forceRoadTC.z*radiusLoaded; //---------------------------------------------------------------- // // // // Calculate rolling resistance (from <NAME>, Fr=u*Fv // where Fv is the normal force, and 'u' the rolling coefficient) // Rolling coefficient may need to go up with speed though //forceRoadTC.y = pf; if(rotationV.x>0) torqueRollingTC.x=-rollingCoeff*forceRoadTC.y*radiusLoaded; else torqueRollingTC.x=rollingCoeff*forceRoadTC.y*radiusLoaded; // Calculate total braking torque (this is POTENTIAL, not always acted upon!) torqueBrakingTC.x=-forceBrakingTC.z*radiusLoaded; torqueBrakingTC.x+=torqueRollingTC.x; // // lateral forces : // /*float lateralForce = xCheckFloat(lastContactData->lateralImpulse); factor = getVehicle()->getEngine()->getForceFeedbackScale(); forceRoadTC.x= signU*lateralForce * factor ; */ #ifdef DO_GREGOR pf=Fy; #else pf=pacejka.GetFy()*frictionCoeff; #endif //pf=forceRoadTC.x; #ifdef OBS qdbg("Pacejka Fy(lat)=%f, SR=%f, SA=%f, load=%f\n",pf,slipRatio,slipAngle,load); #endif forceRoadTC.x=pf; if(getProcessOptions() & pVPO_Forces_No_Lateral) { // Cancel lateral forces pacejka.SetFy(0); forceRoadTC.x=0; } if (getProcessOptions() & pVPO_Lat_Damping ) { // Add damping force because of slipAngle vibrations // at low speed (SAE950311) // Note the mix of 2 coordinate systems here forceRoadTC.x+=forceDampingTC.x; //qdbg("Damping fRoad.x=%f, Fdamp=%f\n",forceRoadTC.x,forceDampingTC.x); } // WHEEL LOCKING if(getVehicle()->getProcessOptions() & pVPO_Wheel_LockAdjust ) goto skip_wla; if(slipRatio<0) { VxVector forceLockedCC,forceLockedTC; float slideFactor,oneMinusSlideFactor,lenSlip,lenNormal,y; // As the wheel is braked, more and more sliding kicks in. // At the moment of 100% slide, the braking force points // in the reverse direction of the slip velocity. Inbetween // SR=0 and SR=-1 (and beyond), there is more and more sliding, // so the force begins to point more and more like the slip vel. // Calculate sliding factor (0..1) if(slipRatio<-1.0f) slideFactor=1.0f; else slideFactor=-slipRatio; //slideFactor*=.75f; oneMinusSlideFactor=1.0f-slideFactor; // Calculate 100% wheel lock direction forceLockedCC.x=slipVectorCC.x; forceLockedCC.y=0; forceLockedCC.z=slipVectorCC.z; // Make it match forceRoadTC's coordinate system ConvertCarToTireOrientation(this,&forceLockedCC,&forceLockedTC); // Calc magnitude of normal and locked forces lenSlip=forceLockedTC.Magnitude(); y=forceRoadTC.y; forceRoadTC.y=0; lenNormal=forceRoadTC.Magnitude(); forceRoadTC.y=y; if(lenSlip<D3_EPSILON) { // No force forceLockedTC.Set(0,0,0); } else { // Equalize force magnitude forceLockedTC *=(lenNormal/lenSlip); } // Interpolate between both extreme forces forceRoadTC.x=oneMinusSlideFactor*forceRoadTC.x+slideFactor*forceLockedTC.x; forceRoadTC.z=oneMinusSlideFactor*forceRoadTC.z+slideFactor*forceLockedTC.z; } skip_wla: // ALIGNING TORQUE aligningTorque=pacejka.GetMz(); // Damp aligning torque at low speed to avoid jittering of wheel // Friction will take care of forces in that case len=velWheelCC.SquareMagnitude(); if(len<1.0) { // Damp aligningTorque*=len; } //---------------------------------------------------------------- // // aligning torque // // ALIGNING TORQUE aligningTorque=pacejka.GetMz(); // Damp aligning torque at low speed to avoid jittering of wheel // Friction will take care of forces in that case len=velWheelCC.SquareMagnitude(); if(len<1.0) { // Damp aligningTorque*=len; } if((stateFlags&LOW_SPEED)) { //qdbg("LS: factor=%f\n",lowSpeedFactor); // Long. force is often too high at low speed forceRoadTC.z*=lowSpeedFactor; } } } void pWheel2::Integrate() { VxVector translation; float oldVX; float mTorque = getVehicle()->getGearBox()->GetTorqueForWheel(this); // // ROTATIONAL acceleration // oldVX=rotationV.x; //---------------------------------------------------------------- // // // // // ROTATIONAL acceleration // //#define OBS #ifdef OBS // Check for locked wheel braking //float netForce= getVehicle()->getEngine()->forEngin .z+forceRoadTC.z; //qdbg("Fe=%f, Fr=%f, Fb=%f\n",forceEngineTC.z,forceRoadTC.z,forceBrakingTC.z); if(rotationV.x>-RR_EPSILON_VELOCITY&&rotationV.x<RR_EPSILON_VELOCITY) { if((netForce<0&&forceBrakingTC.z>-netForce)|| (netForce>0&&forceBrakingTC.z<-netForce)) //if(forceBrakingTC.z<-netForce||forceBrakingTC.z>netForce) { //qdbg("RWh:Int; braking force keeps wheel still\n"); rotationV.x=0; goto skip_rot; } } #endif float timeStep= lastStepTimeSec; float a = rotationA.x*timeStep ; rotationV.x+=rotationA.x*timeStep; //skip_rot: // Check for wheel velocity reversal; in this case, damp the // velocity to a minimum to get rid of jittering wheels at low // speed and/or high braking. if(differential) { if(oldVX>0&&rotationV.x<0) { // Lock the side //qdbg("RWh%d; vel reversal, lock\n",wheelIndex); differential->Lock(differentialSide); rotationV.x=0; differentialSlipRatio=0; } else if(oldVX<0&&rotationV.x>0) { //qdbg("RWh%d; vel reversal, lock\n",wheelIndex); // Lock the side differential->Lock(differentialSide); rotationV.x=0; differentialSlipRatio=0; } } else { // No differential, use controlled jittering if(oldVX>=0&&rotationV.x<0) { // Just lift the rotation over the 0 barrier; this will induce // jittering near 0, but it's so small that it's unnoticeable. // If we keep it at 0, you get larger jitters either way (+/-) // until the wheel rotates again and starts the reversal again. rotationV.x=-0.0001; } else if(oldVX<=0&&rotationV.x>0) { rotationV.x=0.0001; } } //qdbg(" rotV after velocity reversal=%f\n",rotationV.x); // Wheel rotation (spinning) // float rotVx =rotation.x; rotation.x+=rotationV.x*timeStep; //rotation.x+=(rotationV.x+0.5f*rotationA.x*timeStep)*timeStep; //rotation.x+=rotationV.x*timeStep; // Keep rotation in limits while(rotation.x>=2*PI) rotation.x-=2*PI; while(rotation.x<0) rotation.x+=2*PI; // Friction reversal measures if( (oldVX<0&&rotationV.x>0) || (oldVX>0&&rotationV.x<0) ) { rotationV.x=0; //qdbg("RWh:Int; friction reversal halt; %f -> %f\n",oldVX,rotationV.x); } } void pWheel2::CalcWheelAngAcc() { if(differential) { // Use differential to determine acceleration if(differential->IsLocked(differentialSide)) { // Wheel is held still by braking torques rotationA.x=0; } else { // Wheel is allowed to roll rotationA.x=differential->GetAccOut(differentialSide); } //qdbg("diff=%p, diffSide=%d\n",differential,differentialSide); } else { // Uses torque directly (no engine/differential forces) rotationA.x=(torqueFeedbackTC.x+torqueBrakingTC.x)/GetInertia(); } } void pWheel2::CalcAccelerations() { rotationA.Set(0,0,0); CalcWheelAngAcc(); //CalcBodyForce(); // Vertical forces; suspension, gravity, ground, tire rate //acceleration=forceVerticalCC/GetMass(); acceleration.x=acceleration.z=0.0f; acceleration.y=forceVerticalCC.y/mass; #ifdef OBS qdbg("RWh:AF; forceVerticalCC.y=%f, mass=%f\n",forceVerticalCC.y,MASS); #endif } void pWheel2::CalcSlipRatio(VxVector *velWheelCC) { //rfloat vGround,vFreeRolling; float lastTime =lastStepTimeSec; /* lastTime*=0.1f; */ //velWheelTC->DbgPrint("velWheelTC in CalcSR"); if(!hadContact) { //qdbg("CalcSR; not on surface\n"); // Not touching the surface, no slip ratio slipRatio=0; // Tire vibrations stop differentialSlipRatio=0; return; } // SAE950311 algorithm float u,delta,B; u=velWheelTC.z; B=relaxationLengthLong; // Switch to normal slip ratio calculations when there is // speed (in the case when the velocities catch up on the timestep) // Notice this test can be optimized, because the timestep and B // are constants, so a 'turningPointU' can be defined. //qdbg("Threshold: %f\n",u*RR_TIMESTEP/B); float t0 = u*lastTime; bool tc = B>0.5 ? true : false; if(u*lastTime/B>0.5) { //---------------------------------------------------------------- // // changed : // //float wheelSlipRatio slipRatio=rotationV.x*radiusLoaded/u-1; //slipRatio = lastContactData->longitudalSlip; return; // Use straightforward slip ratio slipRatio=rotationV.x*radiusLoaded/u-1; //qdbg("'u' big enough; straight SR %f\n",slipRatio); return; } if((lastU<0&&u>=0)||(lastU>=0&&u<0)) { // 'u' changed sign, reverse slip //qdbg("'u' changed sign from %f to %f; SR=-SR\n",u,lastU); //differentialSlipRatio=-differentialSlipRatio; // Damp while reversing slip; we're close to a standstill. float dampSRreversal = 0.2f; differentialSlipRatio=-dampSRreversal*differentialSlipRatio; } lastU=u; // Detect sign of 'u' (real velocity of wheel) if(u<0)signU=-1.0f; else signU=1.0f; // Eq. 26 //delta=(fabs(u)-rotationV.x*radius*signU)/B-(fabs(u)/B)*differentialSlipRatio; if(u<0) { // Eq. 25 delta=(-u+rotationV.x*radius)/B+(u/B)*differentialSlipRatio; } else { // Eq. 20 delta=(u-rotationV.x*radius)/B-(u/B)*differentialSlipRatio; } // Integrate differentialSlipRatio+=delta*lastTime; if(differentialSlipRatio>10)differentialSlipRatio=10; else if(differentialSlipRatio<-10)differentialSlipRatio=-10; // Set slip ratio for the rest of the sim. Note that // we use a different slip ratio definition from that of SAE950311 //qdbg(" old SR=%f => new SR=%f\n",slipRatio,-differentialSlipRatio); slipRatio=-differentialSlipRatio; } void pWheel2::updatePosition() { NxMat34 &wheelPose = getWheelPose(); NxWheelContactData wcd; NxShape* contactShape = mWheelShape->getContact(wcd); NxReal stravel = mWheelShape->getSuspensionTravel(); NxReal radius = mWheelShape->getRadius(); //have ground contact? if( contactShape && wcd.contactPosition <= (stravel + radius) ) { wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); } else { wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); } } void pWheel2::updateSteeringPose(float rollangle,float steerAngle,float dt) { float rollAngle = getWheelRollAngle(); rollAngle+=getWheelShape()->getAxleSpeed() * (dt * 0.01f); while (rollAngle > NxTwoPi) //normally just 1x rollAngle-= NxTwoPi; while (rollAngle< -NxTwoPi) //normally just 1x rollAngle+= NxTwoPi; setWheelRollAngle(rollAngle); NxMat34& wheelPose = mWheelShape->getGlobalPose(); NxReal stravel = mWheelShape->getSuspensionTravel(); NxReal radius = mWheelShape->getRadius(); float rAngle = getWheelRollAngle(); float steer = mWheelShape->getSteerAngle(); NxVec3 dir; NxReal r = mWheelShape->getRadius(); NxReal st = mWheelShape->getSuspensionTravel(); wheelPose.M.getColumn(1, dir); dir = -dir; //cast along -Y. NxReal castLength = r + st; //cast ray this long NxMat33 rot, axisRot, rollRot; rot.rotY( mWheelShape->getSteerAngle() ); axisRot.rotY(0); rollRot.rotX(rAngle); wheelPose.M = rot * wheelPose.M * axisRot * rollRot; setWheelPose(wheelPose); } void pWheel2::CalcSlipAngle() // Based on the wheel world velocity and heading, calculate // the angle from the wheel heading to the wheel's actual velocity // Contrary to SAE, our Y-axis points up, and slipAngle>0 means // in our case that the you're in a right turn (basically) // 31-03-01: SAE950311 implementation (using relaxation lengths // and a differential equation for the slip angle) for low-speed etc. { VxVector velWheelWC; if(!hadContact) { //qdbg("CalcSA; not on surface\n"); // Not touching the surface, no need to do slip angle slipAngle=0; // Tire springs back to 0 instantly (should be slowly actually) tanSlipAngle=0; velWheelTC.Set(0,0,0); velWheelCC.Set(0,0,0); return; } int options = getProcessOptions(); if (options & pVPO_Wheel_UsePHYSX_CONTACT_DATA ) { /* VxVector dir,up,right; getEntity()->GetOrientation(&dir,&up,&right); */ VxVector point= lastContactData->contactPoint; if( lastContactData->contactPosition <= ( getWheelShape()->getSuspensionTravel() + radius) ) point.y+=getRadius(); else point.y = getWheelPose().t.y - getSuspensionTravel(); //getEntity()->TransformVector(&point,&point); /* getBody()->GetVT3DObject()->InverseTransformVector(&point,&point); /* getEntity()->InverseTransformVector(&contactLocal,&point); VxVector contactLocal2; getEntity()->InverseTransform(&contactLocal,&point); */ getBody()->GetVT3DObject()->InverseTransform(&point,&point); velWheelCC = getBody()->getLocalPointVelocity(point); //getEntity()->TransformVector(&velWheelCC,&velWheelCC); ConvertCarToTireOrientation(this,&velWheelCC,&velWheelTC); } if ( options & pVPO_SA_Delay ) { // Derive change in tan(slipAngle) using SAE950311 // u=longitudinal velocity, v=lateral velocity float u,b,v,delta; u=velWheelTC.z; v=velWheelTC.x; b=relaxationLengthLat; if ( options & pVPO_SA_DownSettle) { // Make sure SA settles down at low speeds float min=5.0f; if(u<min&&u>=0.0f)u=min; else if(u>-min&&u<=0)u=-min; } // Calculate change in tan(SA) delta=(v/b)-(fabs(u)/b)*tanSlipAngle; if( getWheelFlag(WF_Accelerated) && getVehicle() ) { //qdbg("CSA; u=%f, v=%f, delta=%f, tanSA=%f, SA=%f\n",u,v,delta,tanSlipAngle,slipAngle); // qdbg("delta=%f, tanSA=%f, SA=%f\n",delta,tanSlipAngle,atan(tanSlipAngle)); // Integrate tanSlipAngle+=delta*lastStepTimeMS; // Derive new slip angle from state variable 'tanSlipAngle' slipAngle=atanf(tanSlipAngle); } }else { // Calculate wheel velocity because of rotation around yaw (Y) axis /*velWheelCC.x+=car->GetBody()->GetRotVel()->y*cos(-angleCGM)*distCGM; velWheelCC.z+=car->GetBody()->GetRotVel()->y*sin(-angleCGM)*distCGM; ConvertCarToTireOrientation(&velWheelCC,&velWheelTC); */ /* // Get velocity of contact patch wrt the track (=world) DVector3 cpPos,*p; p=susp->GetPosition(); // Taking the tire movement from really the contact patch location // seems to overrate the lateral movement the tire goes through. // This is due because the body rolls, but normally the suspension // won't roll the tire in exactly the same way, but instead, // the tire rotates with respect to the body, so the lateral // movements are actually quite small. // To simulate this, I approximate the movement with respect // to the suspension attachment point, which moves far less // laterally. This became apparent when dealing with much stiffer // tire and suspension spring rates, which made the car wobbly. // Taking a less laterally sensitive position solved this. cpPos.x=p->x; //cpPos.y=p->y+susp->GetLength()+radius; cpPos.y=p->y; cpPos.z=p->z; // Kingpin effects are ignored car->GetBody()->CalcBodyVelForBodyPos(&cpPos,&velWheelCC); car->ConvertCarToWorldOrientation(&velWheelCC,&velWheelWC); ConvertCarToTireOrientation(&velWheelCC,&velWheelTC); */ //qdbg("velWheelTC.z=%f, rotZ=%f\n",velWheelTC.z,rotationV.x*radius); // Non-SAE950311 method (no lag in slip angle buildup) // Calculate slip angle as the angle between the wheel velocity vector // and the wheel direction vector if(velWheelCC.x>-RR_EPSILON_VELOCITY&&velWheelCC.x<RR_EPSILON_VELOCITY && velWheelCC.z>-RR_EPSILON_VELOCITY&&velWheelCC.z<RR_EPSILON_VELOCITY) { //Very low speed; no slip angle //slipAngle=-GetHeading(); slipAngle=0; //qdbg(" RWh;CSA; LS => slipAngle=0\n"); } else { // Enough velocity, calculate real angle float h = GetHeading(); float realSteer = mWheelShape->getSteerAngle(); slipAngle=atan2(velWheelCC.x,velWheelCC.z)-GetHeading(); if (getProcessOptions() & pVPO_SA_Damping ) { // Damp down at low velocity if(fabs(velWheelCC.x)<0.3f&&fabs(velWheelCC.z)<0.3f) { float max=fabs(velWheelCC.x); if(fabs(velWheelCC.z)<max) max=fabs(velWheelCC.z); //qdbg("damp SA %f factor %f => %f\n",slipAngle*RR_RAD2DEG,max,slipAngle*max); slipAngle*=max*0.5f; } } // Keep slipAngle between -180..180 degrees if(slipAngle<-PI) slipAngle+=2*PI; else if(slipAngle>PI) slipAngle-=2*PI; } if ( options & pVPO_SV_Tansa) { bool make = true ; if(make) { // We need tan(SA) when combining Pacejka Fx/Fy later tanSlipAngle=tan(slipAngle); //qdbg("FCSV: tanSA=%f\n",tanSlipAngle); } } } }<file_sep>#include "VxDefines.h" #include "CKAll.h" #undef min #undef max <file_sep>// =============================================================================== // NVIDIA PHYSX SDK TRAINING PROGRAMS // LESSON 404: TANK // // Written by <NAME>, 5-1-06 // =============================================================================== #ifndef LESSON407_H #define LESSON407_H #include "CommonCode2.h" void PrintControls(); void NewLight(); void SetMotorOnTread(int i, const NxMotorDesc& mDesc); void ProcessMotorKeys(); void InitMotors(); int main(int argc, char** argv); #endif // LESSON407_H <file_sep>/* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * typemap.c * * A somewhat generalized implementation of SWIG1.1 typemaps. * ----------------------------------------------------------------------------- */ char cvsroot_typemap_c[] = "$Id: typemap.c 9889 2007-08-10 02:55:27Z wuzzeb $"; #include "swig.h" #include "cparse.h" #include <ctype.h> #if 0 #define SWIG_DEBUG #endif static void replace_embedded_typemap(String *s); /* ----------------------------------------------------------------------------- * Typemaps are stored in a collection of nested hash tables. Something like * this: * * [ type ] * +-------- [ name ] * +-------- [ name ] * * Each hash table [ type ] or [ name ] then contains references to the * different typemap methods. These are referenced by names such as * "tmap:in", "tmap:out", "tmap:argout", and so forth. * * The object corresponding to a specific method has the following * attributes: * * "type" - Typemap type * "pname" - Parameter name * "code" - Typemap code * "typemap" - Descriptive text describing the actual map * "locals" - Local variables (if any) * * ----------------------------------------------------------------------------- */ #define MAX_SCOPE 32 static Hash *typemaps[MAX_SCOPE]; static int tm_scope = 0; static Hash *get_typemap(int tm_scope, SwigType *type) { Hash *tm = 0; SwigType *dtype = 0; if (SwigType_istemplate(type)) { String *ty = Swig_symbol_template_deftype(type, 0); dtype = Swig_symbol_type_qualify(ty, 0); /* Printf(stderr,"gettm %s %s\n", type, dtype); */ type = dtype; Delete(ty); } tm = Getattr(typemaps[tm_scope], type); if (dtype) { if (!tm) { String *t_name = SwigType_templateprefix(type); if (!Equal(t_name, type)) { tm = Getattr(typemaps[tm_scope], t_name); } Delete(t_name); } Delete(dtype); } return tm; } static void set_typemap(int tm_scope, SwigType *type, Hash *tm) { SwigType *dtype = 0; if (SwigType_istemplate(type)) { String *ty = Swig_symbol_template_deftype(type, 0); dtype = Swig_symbol_type_qualify(ty, 0); /* Printf(stderr,"settm %s %s\n", type, dtype); */ type = dtype; Delete(ty); } else { dtype = Copy(type); type = dtype; } Setattr(typemaps[tm_scope], type, tm); Delete(dtype); } /* ----------------------------------------------------------------------------- * Swig_typemap_init() * * Initialize the typemap system * ----------------------------------------------------------------------------- */ void Swig_typemap_init() { int i; for (i = 0; i < MAX_SCOPE; i++) { typemaps[i] = 0; } typemaps[0] = NewHash(); tm_scope = 0; } static String *tmop_name(const String_or_char *op) { static Hash *names = 0; String *s; /* Due to "interesting" object-identity semantics of DOH, we have to make sure that we only intern strings without object identity into the hash table. (Swig_typemap_attach_kwargs calls tmop_name several times with the "same" String *op (i.e., same object identity) but differing string values.) Most other callers work around this by using char* rather than String *. -- mkoeppe, Jun 17, 2003 */ const char *op_without_object_identity = Char(op); if (!names) names = NewHash(); s = Getattr(names, op_without_object_identity); if (s) return s; s = NewStringf("tmap:%s", op); Setattr(names, op_without_object_identity, s); Delete(s); return s; } /* ----------------------------------------------------------------------------- * Swig_typemap_new_scope() * * Create a new typemap scope * ----------------------------------------------------------------------------- */ void Swig_typemap_new_scope() { tm_scope++; typemaps[tm_scope] = NewHash(); } /* ----------------------------------------------------------------------------- * Swig_typemap_pop_scope() * * Pop the last typemap scope off * ----------------------------------------------------------------------------- */ Hash *Swig_typemap_pop_scope() { if (tm_scope > 0) { return typemaps[tm_scope--]; } return 0; } /* ----------------------------------------------------------------------------- * Swig_typemap_register() * * Add a new multi-valued typemap * ----------------------------------------------------------------------------- */ void Swig_typemap_register(const String_or_char *op, ParmList *parms, String_or_char *code, ParmList *locals, ParmList *kwargs) { Hash *tm; Hash *tm1; Hash *tm2; Parm *np; String *tmop; SwigType *type; String *pname; if (!parms) return; tmop = tmop_name(op); /* Register the first type in the parameter list */ type = Getattr(parms, "type"); pname = Getattr(parms, "name"); /* See if this type has been seen before */ tm = get_typemap(tm_scope, type); if (!tm) { tm = NewHash(); set_typemap(tm_scope, type, tm); Delete(tm); } if (pname) { /* See if parameter has been seen before */ tm1 = Getattr(tm, pname); if (!tm1) { tm1 = NewHash(); Setattr(tm, pname, tm1); Delete(tm1); } tm = tm1; } /* Now see if this typemap op has been seen before */ tm2 = Getattr(tm, tmop); if (!tm2) { tm2 = NewHash(); Setattr(tm, tmop, tm2); Delete(tm2); } /* For a multi-valued typemap, the typemap code and information is really only stored in the last argument. However, to make this work, we perform a really neat trick using the typemap operator name. For example, consider this typemap %typemap(in) (int foo, int *bar, char *blah[]) { ... } To store it, we look at typemaps for the following: operator type-name ---------------------------------------------- "in" int foo "in-int+foo:" int *bar "in-int+foo:-p.int+bar: char *blah[] Notice how the operator expands to encode information about previous arguments. */ np = nextSibling(parms); if (np) { /* Make an entirely new operator key */ String *newop = NewStringf("%s-%s+%s:", op, type, pname); /* Now reregister on the remaining arguments */ Swig_typemap_register(newop, np, code, locals, kwargs); /* Setattr(tm2,newop,newop); */ Delete(newop); } else { String *str = SwigType_str(type, pname); String *typemap = NewStringf("typemap(%s) %s", op, str); ParmList *clocals = CopyParmList(locals); ParmList *ckwargs = CopyParmList(kwargs); Setattr(tm2, "code", code); Setattr(tm2, "type", type); Setattr(tm2, "typemap", typemap); if (pname) { Setattr(tm2, "pname", pname); } Setattr(tm2, "locals", clocals); Setattr(tm2, "kwargs", ckwargs); Delete(clocals); Delete(ckwargs); Delete(str); Delete(typemap); } } /* ----------------------------------------------------------------------------- * Swig_typemap_get() * * Retrieve typemap information from current scope. * ----------------------------------------------------------------------------- */ static Hash *Swig_typemap_get(SwigType *type, String_or_char *name, int scope) { Hash *tm, *tm1; /* See if this type has been seen before */ if ((scope < 0) || (scope > tm_scope)) return 0; tm = get_typemap(scope, type); if (!tm) { return 0; } if ((name) && Len(name)) { tm1 = Getattr(tm, name); return tm1; } return tm; } /* ----------------------------------------------------------------------------- * Swig_typemap_copy() * * Copy a typemap * ----------------------------------------------------------------------------- */ int Swig_typemap_copy(const String_or_char *op, ParmList *srcparms, ParmList *parms) { Hash *tm = 0; String *tmop; Parm *p; String *pname; SwigType *ptype; int ts = tm_scope; String *tmops, *newop; if (ParmList_len(parms) != ParmList_len(srcparms)) return -1; tmop = tmop_name(op); while (ts >= 0) { p = srcparms; tmops = NewString(tmop); while (p) { ptype = Getattr(p, "type"); pname = Getattr(p, "name"); /* Lookup the type */ tm = Swig_typemap_get(ptype, pname, ts); if (!tm) break; tm = Getattr(tm, tmops); if (!tm) break; /* Got a match. Look for next typemap */ newop = NewStringf("%s-%s+%s:", tmops, ptype, pname); Delete(tmops); tmops = newop; p = nextSibling(p); } Delete(tmops); if (!p && tm) { /* Got some kind of match */ Swig_typemap_register(op, parms, Getattr(tm, "code"), Getattr(tm, "locals"), Getattr(tm, "kwargs")); return 0; } ts--; } /* Not found */ return -1; } /* ----------------------------------------------------------------------------- * Swig_typemap_clear() * * Delete a multi-valued typemap * ----------------------------------------------------------------------------- */ void Swig_typemap_clear(const String_or_char *op, ParmList *parms) { SwigType *type; String *name; Parm *p; String *newop; Hash *tm = 0; /* This might not work */ newop = NewString(op); p = parms; while (p) { type = Getattr(p, "type"); name = Getattr(p, "name"); tm = Swig_typemap_get(type, name, tm_scope); if (!tm) return; p = nextSibling(p); if (p) Printf(newop, "-%s+%s:", type, name); } if (tm) { tm = Getattr(tm, tmop_name(newop)); if (tm) { Delattr(tm, "code"); Delattr(tm, "locals"); Delattr(tm, "kwargs"); } } Delete(newop); } /* ----------------------------------------------------------------------------- * Swig_typemap_apply() * * Multi-argument %apply directive. This is pretty horrible so I sure hope * it works. * ----------------------------------------------------------------------------- */ static int count_args(String *s) { /* Count up number of arguments */ int na = 0; char *c = Char(s); while (*c) { if (*c == '+') na++; c++; } return na; } int Swig_typemap_apply(ParmList *src, ParmList *dest) { String *ssig, *dsig; Parm *p, *np, *lastp, *dp, *lastdp = 0; int narg = 0; int ts = tm_scope; SwigType *type = 0, *name; Hash *tm, *sm; int match = 0; /* Printf(stdout,"apply : %s --> %s\n", ParmList_str(src), ParmList_str(dest)); */ /* Create type signature of source */ ssig = NewStringEmpty(); dsig = NewStringEmpty(); p = src; dp = dest; lastp = 0; while (p) { lastp = p; lastdp = dp; np = nextSibling(p); if (np) { Printf(ssig, "-%s+%s:", Getattr(p, "type"), Getattr(p, "name")); Printf(dsig, "-%s+%s:", Getattr(dp, "type"), Getattr(dp, "name")); narg++; } p = np; dp = nextSibling(dp); } /* make sure a typemap node exists for the last destination node */ type = Getattr(lastdp, "type"); tm = get_typemap(tm_scope, type); if (!tm) { tm = NewHash(); set_typemap(tm_scope, type, tm); Delete(tm); } name = Getattr(lastdp, "name"); if (name) { Hash *tm1 = Getattr(tm, name); if (!tm1) { tm1 = NewHash(); Setattr(tm, NewString(name), tm1); Delete(tm1); } tm = tm1; } /* This is a little nasty. We need to go searching for all possible typemaps in the source and apply them to the target */ type = Getattr(lastp, "type"); name = Getattr(lastp, "name"); while (ts >= 0) { /* See if there is a matching typemap in this scope */ sm = Swig_typemap_get(type, name, ts); /* if there is not matching, look for a typemap in the original typedef, if any, like in: typedef unsigned long size_t; ... %apply(size_t) {my_size}; ==> %apply(unsigned long) {my_size}; */ if (!sm) { SwigType *ntype = SwigType_typedef_resolve(type); if (ntype && (Cmp(ntype, type) != 0)) { sm = Swig_typemap_get(ntype, name, ts); } Delete(ntype); } if (sm) { /* Got a typemap. Need to only merge attributes for methods that match our signature */ Iterator ki; match = 1; for (ki = First(sm); ki.key; ki = Next(ki)) { /* Check for a signature match with the source signature */ if ((count_args(ki.key) == narg) && (Strstr(ki.key, ssig))) { String *oldm; /* A typemap we have to copy */ String *nkey = Copy(ki.key); Replace(nkey, ssig, dsig, DOH_REPLACE_ANY); /* Make sure the typemap doesn't already exist in the target map */ oldm = Getattr(tm, nkey); if (!oldm || (!Getattr(tm, "code"))) { String *code; ParmList *locals; ParmList *kwargs; Hash *sm1 = ki.item; code = Getattr(sm1, "code"); locals = Getattr(sm1, "locals"); kwargs = Getattr(sm1, "kwargs"); if (code) { Replace(nkey, dsig, "", DOH_REPLACE_ANY); Replace(nkey, "tmap:", "", DOH_REPLACE_ANY); Swig_typemap_register(nkey, dest, code, locals, kwargs); } } Delete(nkey); } } } ts--; } Delete(ssig); Delete(dsig); return match; } /* ----------------------------------------------------------------------------- * Swig_typemap_clear_apply() * * %clear directive. Clears all typemaps for a type (in the current scope only). * ----------------------------------------------------------------------------- */ /* Multi-argument %clear directive */ void Swig_typemap_clear_apply(Parm *parms) { String *tsig; Parm *p, *np, *lastp; int narg = 0; Hash *tm; String *name; /* Create a type signature of the parameters */ tsig = NewStringEmpty(); p = parms; lastp = 0; while (p) { lastp = p; np = nextSibling(p); if (np) { Printf(tsig, "-%s+%s:", Getattr(p, "type"), Getattr(p, "name")); narg++; } p = np; } tm = get_typemap(tm_scope, Getattr(lastp, "type")); if (!tm) { Delete(tsig); return; } name = Getattr(lastp, "name"); if (name) { tm = Getattr(tm, name); } if (tm) { /* Clear typemaps that match our signature */ Iterator ki, ki2; char *ctsig = Char(tsig); for (ki = First(tm); ki.key; ki = Next(ki)) { char *ckey = Char(ki.key); if (strncmp(ckey, "tmap:", 5) == 0) { int na = count_args(ki.key); if ((na == narg) && strstr(ckey, ctsig)) { Hash *h = ki.item; for (ki2 = First(h); ki2.key; ki2 = Next(ki2)) { Delattr(h, ki2.key); } } } } } Delete(tsig); } /* Internal function to strip array dimensions. */ static SwigType *strip_arrays(SwigType *type) { SwigType *t; int ndim; int i; t = Copy(type); ndim = SwigType_array_ndim(t); for (i = 0; i < ndim; i++) { SwigType_array_setdim(t, i, "ANY"); } return t; } /* ----------------------------------------------------------------------------- * Swig_typemap_search() * * Search for a typemap match. Tries to find the most specific typemap * that includes a 'code' attribute. * ----------------------------------------------------------------------------- */ Hash *Swig_typemap_search(const String_or_char *op, SwigType *type, const String_or_char *name, SwigType **matchtype) { Hash *result = 0, *tm, *tm1, *tma; Hash *backup = 0; SwigType *noarrays = 0; SwigType *primitive = 0; SwigType *ctype = 0; int ts; int isarray; const String *cname = 0; SwigType *unstripped = 0; String *tmop = tmop_name(op); if ((name) && Len(name)) cname = name; ts = tm_scope; while (ts >= 0) { ctype = type; while (ctype) { /* Try to get an exact type-match */ tm = get_typemap(ts, ctype); if (tm && cname) { tm1 = Getattr(tm, cname); if (tm1) { result = Getattr(tm1, tmop); /* See if there is a type-name match */ if (result && Getattr(result, "code")) goto ret_result; if (result) backup = result; } } if (tm) { result = Getattr(tm, tmop); /* See if there is simply a type match */ if (result && Getattr(result, "code")) goto ret_result; if (result) backup = result; } isarray = SwigType_isarray(ctype); if (isarray) { /* If working with arrays, strip away all of the dimensions and replace with "ANY". See if that generates a match */ if (!noarrays) { noarrays = strip_arrays(ctype); } tma = get_typemap(ts, noarrays); if (tma && cname) { tm1 = Getattr(tma, cname); if (tm1) { result = Getattr(tm1, tmop); /* type-name match */ if (result && Getattr(result, "code")) goto ret_result; if (result) backup = result; } } if (tma) { result = Getattr(tma, tmop); /* type match */ if (result && Getattr(result, "code")) goto ret_result; if (result) backup = result; } Delete(noarrays); noarrays = 0; } /* No match so far. If the type is unstripped, we'll strip its qualifiers and check. Otherwise, we'll try to resolve a typedef */ if (!unstripped) { unstripped = ctype; ctype = SwigType_strip_qualifiers(ctype); if (!Equal(ctype, unstripped)) continue; /* Types are different */ Delete(ctype); ctype = unstripped; unstripped = 0; } { String *octype; if (unstripped) { Delete(ctype); ctype = unstripped; unstripped = 0; } octype = ctype; ctype = SwigType_typedef_resolve(ctype); if (octype != type) Delete(octype); } } /* Hmmm. Well, no match seems to be found at all. See if there is some kind of default mapping */ primitive = SwigType_default(type); while (primitive) { tm = get_typemap(ts, primitive); if (tm && cname) { tm1 = Getattr(tm, cname); if (tm1) { result = Getattr(tm1, tmop); /* See if there is a type-name match */ if (result) goto ret_result; } } if (tm) { /* See if there is simply a type match */ result = Getattr(tm, tmop); if (result) goto ret_result; } { SwigType *nprim = SwigType_default(primitive); Delete(primitive); primitive = nprim; } } if (ctype != type) { Delete(ctype); ctype = 0; } ts--; /* Hmmm. Nothing found in this scope. Guess we'll go try another scope */ } result = backup; ret_result: if (noarrays) Delete(noarrays); if (primitive) Delete(primitive); if ((unstripped) && (unstripped != type)) Delete(unstripped); if (matchtype) { *matchtype = Copy(ctype); } if (type != ctype) Delete(ctype); return result; } /* ----------------------------------------------------------------------------- * Swig_typemap_search_multi() * * Search for a multi-valued typemap. * ----------------------------------------------------------------------------- */ Hash *Swig_typemap_search_multi(const String_or_char *op, ParmList *parms, int *nmatch) { SwigType *type; SwigType *mtype = 0; String *name; String *newop; Hash *tm, *tm1; if (!parms) { *nmatch = 0; return 0; } type = Getattr(parms, "type"); name = Getattr(parms, "name"); /* Try to find a match on the first type */ tm = Swig_typemap_search(op, type, name, &mtype); if (tm) { if (mtype && SwigType_isarray(mtype)) { Setattr(parms, "tmap:match", mtype); } Delete(mtype); newop = NewStringf("%s-%s+%s:", op, type, name); tm1 = Swig_typemap_search_multi(newop, nextSibling(parms), nmatch); if (tm1) tm = tm1; if (Getattr(tm, "code")) { *(nmatch) = *nmatch + 1; } else { tm = 0; } Delete(newop); } return tm; } /* ----------------------------------------------------------------------------- * typemap_replace_vars() * * Replaces typemap variables on a string. index is the $n variable. * type and pname are the type and parameter name. * ----------------------------------------------------------------------------- */ static void replace_local_types(ParmList *p, const String *name, const String *rep) { SwigType *t; while (p) { t = Getattr(p, "type"); Replace(t, name, rep, DOH_REPLACE_ANY); p = nextSibling(p); } } static int check_locals(ParmList *p, const char *s) { while (p) { char *c = GetChar(p, "type"); if (strstr(c, s)) return 1; p = nextSibling(p); } return 0; } static void typemap_replace_vars(String *s, ParmList *locals, SwigType *type, SwigType *rtype, String *pname, String *lname, int index) { char var[512]; char *varname; SwigType *ftype; Replaceall(s, "$typemap", "$TYPEMAP"); ftype = SwigType_typedef_resolve_all(type); if (!pname) pname = lname; { Parm *p; int rep = 0; p = locals; while (p) { if (Strchr(Getattr(p, "type"), '$')) rep = 1; p = nextSibling(p); } if (!rep) locals = 0; } sprintf(var, "$%d_", index); varname = &var[strlen(var)]; /* If the original datatype was an array. We're going to go through and substitute its array dimensions */ if (SwigType_isarray(type) || SwigType_isarray(ftype)) { String *size; int ndim; int i; if (SwigType_array_ndim(type) != SwigType_array_ndim(ftype)) type = ftype; ndim = SwigType_array_ndim(type); size = NewStringEmpty(); for (i = 0; i < ndim; i++) { String *dim = SwigType_array_getdim(type, i); if (index == 1) { char t[32]; sprintf(t, "$dim%d", i); Replace(s, t, dim, DOH_REPLACE_ANY); replace_local_types(locals, t, dim); } sprintf(varname, "dim%d", i); Replace(s, var, dim, DOH_REPLACE_ANY); replace_local_types(locals, var, dim); if (Len(size)) Putc('*', size); Append(size, dim); Delete(dim); } sprintf(varname, "size"); Replace(s, var, size, DOH_REPLACE_ANY); replace_local_types(locals, var, size); Delete(size); } /* Parameter name substitution */ if (index == 1) { Replace(s, "$parmname", pname, DOH_REPLACE_ANY); } strcpy(varname, "name"); Replace(s, var, pname, DOH_REPLACE_ANY); /* Type-related stuff */ { SwigType *star_type, *amp_type, *base_type, *lex_type; SwigType *ltype, *star_ltype, *amp_ltype; String *mangle, *star_mangle, *amp_mangle, *base_mangle, *base_name; String *descriptor, *star_descriptor, *amp_descriptor; String *ts; char *sc; sc = Char(s); if (strstr(sc, "type") || check_locals(locals, "type")) { /* Given type : $type */ ts = SwigType_str(type, 0); if (index == 1) { Replace(s, "$type", ts, DOH_REPLACE_ANY); replace_local_types(locals, "$type", type); } strcpy(varname, "type"); Replace(s, var, ts, DOH_REPLACE_ANY); replace_local_types(locals, var, type); Delete(ts); sc = Char(s); } if (strstr(sc, "ltype") || check_locals(locals, "ltype")) { /* Local type: $ltype */ ltype = SwigType_ltype(type); ts = SwigType_str(ltype, 0); if (index == 1) { Replace(s, "$ltype", ts, DOH_REPLACE_ANY); replace_local_types(locals, "$ltype", ltype); } strcpy(varname, "ltype"); Replace(s, var, ts, DOH_REPLACE_ANY); replace_local_types(locals, var, ltype); Delete(ts); Delete(ltype); sc = Char(s); } if (strstr(sc, "mangle") || strstr(sc, "descriptor")) { /* Mangled type */ mangle = SwigType_manglestr(type); if (index == 1) Replace(s, "$mangle", mangle, DOH_REPLACE_ANY); strcpy(varname, "mangle"); Replace(s, var, mangle, DOH_REPLACE_ANY); descriptor = NewStringf("SWIGTYPE%s", mangle); if (index == 1) if (Replace(s, "$descriptor", descriptor, DOH_REPLACE_ANY)) SwigType_remember(type); strcpy(varname, "descriptor"); if (Replace(s, var, descriptor, DOH_REPLACE_ANY)) SwigType_remember(type); Delete(descriptor); Delete(mangle); } /* One pointer level removed */ /* This creates variables of the form $*n_type $*n_ltype */ if (SwigType_ispointer(ftype) || (SwigType_isarray(ftype)) || (SwigType_isreference(ftype))) { if (!(SwigType_isarray(type) || SwigType_ispointer(type) || SwigType_isreference(type))) { star_type = Copy(ftype); } else { star_type = Copy(type); } if (!SwigType_isreference(star_type)) { if (SwigType_isarray(star_type)) { SwigType_del_element(star_type); } else { SwigType_del_pointer(star_type); } ts = SwigType_str(star_type, 0); if (index == 1) { Replace(s, "$*type", ts, DOH_REPLACE_ANY); replace_local_types(locals, "$*type", star_type); } sprintf(varname, "$*%d_type", index); Replace(s, varname, ts, DOH_REPLACE_ANY); replace_local_types(locals, varname, star_type); Delete(ts); } else { SwigType_del_element(star_type); } star_ltype = SwigType_ltype(star_type); ts = SwigType_str(star_ltype, 0); if (index == 1) { Replace(s, "$*ltype", ts, DOH_REPLACE_ANY); replace_local_types(locals, "$*ltype", star_ltype); } sprintf(varname, "$*%d_ltype", index); Replace(s, varname, ts, DOH_REPLACE_ANY); replace_local_types(locals, varname, star_ltype); Delete(ts); Delete(star_ltype); star_mangle = SwigType_manglestr(star_type); if (index == 1) Replace(s, "$*mangle", star_mangle, DOH_REPLACE_ANY); sprintf(varname, "$*%d_mangle", index); Replace(s, varname, star_mangle, DOH_REPLACE_ANY); star_descriptor = NewStringf("SWIGTYPE%s", star_mangle); if (index == 1) if (Replace(s, "$*descriptor", star_descriptor, DOH_REPLACE_ANY)) SwigType_remember(star_type); sprintf(varname, "$*%d_descriptor", index); if (Replace(s, varname, star_descriptor, DOH_REPLACE_ANY)) SwigType_remember(star_type); Delete(star_descriptor); Delete(star_mangle); Delete(star_type); } else { /* TODO: Signal error if one of the $* substitutions is requested */ } /* One pointer level added */ amp_type = Copy(type); SwigType_add_pointer(amp_type); ts = SwigType_str(amp_type, 0); if (index == 1) { Replace(s, "$&type", ts, DOH_REPLACE_ANY); replace_local_types(locals, "$&type", amp_type); } sprintf(varname, "$&%d_type", index); Replace(s, varname, ts, DOH_REPLACE_ANY); replace_local_types(locals, varname, amp_type); Delete(ts); amp_ltype = SwigType_ltype(type); SwigType_add_pointer(amp_ltype); ts = SwigType_str(amp_ltype, 0); if (index == 1) { Replace(s, "$&ltype", ts, DOH_REPLACE_ANY); replace_local_types(locals, "$&ltype", amp_ltype); } sprintf(varname, "$&%d_ltype", index); Replace(s, varname, ts, DOH_REPLACE_ANY); replace_local_types(locals, varname, amp_ltype); Delete(ts); Delete(amp_ltype); amp_mangle = SwigType_manglestr(amp_type); if (index == 1) Replace(s, "$&mangle", amp_mangle, DOH_REPLACE_ANY); sprintf(varname, "$&%d_mangle", index); Replace(s, varname, amp_mangle, DOH_REPLACE_ANY); amp_descriptor = NewStringf("SWIGTYPE%s", amp_mangle); if (index == 1) if (Replace(s, "$&descriptor", amp_descriptor, DOH_REPLACE_ANY)) SwigType_remember(amp_type); sprintf(varname, "$&%d_descriptor", index); if (Replace(s, varname, amp_descriptor, DOH_REPLACE_ANY)) SwigType_remember(amp_type); Delete(amp_descriptor); Delete(amp_mangle); Delete(amp_type); /* Base type */ if (SwigType_isarray(type)) { SwigType *bt = Copy(type); Delete(SwigType_pop_arrays(bt)); base_type = SwigType_str(bt, 0); Delete(bt); } else { base_type = SwigType_base(type); } base_name = SwigType_namestr(base_type); if (index == 1) { Replace(s, "$basetype", base_name, DOH_REPLACE_ANY); replace_local_types(locals, "$basetype", base_name); } strcpy(varname, "basetype"); Replace(s, var, base_type, DOH_REPLACE_ANY); replace_local_types(locals, var, base_name); base_mangle = SwigType_manglestr(base_type); if (index == 1) Replace(s, "$basemangle", base_mangle, DOH_REPLACE_ANY); strcpy(varname, "basemangle"); Replace(s, var, base_mangle, DOH_REPLACE_ANY); Delete(base_mangle); Delete(base_type); Delete(base_name); lex_type = SwigType_base(rtype); if (index == 1) Replace(s, "$lextype", lex_type, DOH_REPLACE_ANY); strcpy(varname, "lextype"); Replace(s, var, lex_type, DOH_REPLACE_ANY); Delete(lex_type); } /* Replace any $n. with (&n)-> */ { char temp[64]; sprintf(var, "$%d.", index); sprintf(temp, "(&$%d)->", index); Replace(s, var, temp, DOH_REPLACE_ANY); } /* Replace the bare $n variable */ sprintf(var, "$%d", index); Replace(s, var, lname, DOH_REPLACE_ANY); Delete(ftype); } /* ------------------------------------------------------------------------ * static typemap_locals() * * Takes a string, a parameter list and a wrapper function argument and * creates the local variables. * ------------------------------------------------------------------------ */ static void typemap_locals(DOHString * s, ParmList *l, Wrapper *f, int argnum) { Parm *p; char *new_name; p = l; while (p) { SwigType *pt = Getattr(p, "type"); SwigType *at = SwigType_alttype(pt, 1); String *pn = Getattr(p, "name"); String *value = Getattr(p, "value"); if (at) pt = at; if (pn) { if (Len(pn) > 0) { String *str; int isglobal = 0; str = NewStringEmpty(); if (strncmp(Char(pn), "_global_", 8) == 0) { isglobal = 1; } /* If the user gave us $type as the name of the local variable, we'll use the passed datatype instead */ if ((argnum >= 0) && (!isglobal)) { Printf(str, "%s%d", pn, argnum); } else { Append(str, pn); } if (isglobal && Wrapper_check_local(f, str)) { p = nextSibling(p); Delete(str); if (at) Delete(at); continue; } if (value) { String *pstr = SwigType_str(pt, str); new_name = Wrapper_new_localv(f, str, pstr, "=", value, NIL); Delete(pstr); } else { String *pstr = SwigType_str(pt, str); new_name = Wrapper_new_localv(f, str, pstr, NIL); Delete(pstr); } if (!isglobal) { /* Substitute */ Replace(s, pn, new_name, DOH_REPLACE_ID | DOH_REPLACE_NOQUOTE); } Delete(str); } } p = nextSibling(p); if (at) Delete(at); } } /* ----------------------------------------------------------------------------- * Swig_typemap_lookup() * * Perform a typemap lookup (ala SWIG1.1) * ----------------------------------------------------------------------------- */ String *Swig_typemap_lookup(const String_or_char *op, SwigType *type, String_or_char *pname, String_or_char *lname, String_or_char *source, String_or_char *target, Wrapper *f) { Hash *tm; String *s = 0; SwigType *mtype = 0; ParmList *locals; tm = Swig_typemap_search(op, type, pname, &mtype); if (!tm) return 0; s = Getattr(tm, "code"); if (!s) { if (mtype) Delete(mtype); return 0; } /* Blocked */ if (Cmp(s, "pass") == 0) { Delete(mtype); return 0; } s = Copy(s); /* Make a local copy of the typemap code */ locals = Getattr(tm, "locals"); if (locals) locals = CopyParmList(locals); /* This is wrong. It replaces locals in place. Need to fix this */ if (mtype && SwigType_isarray(mtype)) { typemap_replace_vars(s, locals, mtype, type, pname, lname, 1); } else { typemap_replace_vars(s, locals, type, type, pname, lname, 1); } if (locals && f) { typemap_locals(s, locals, f, -1); } replace_embedded_typemap(s); /* Now perform character replacements */ Replace(s, "$source", source, DOH_REPLACE_ANY); Replace(s, "$target", target, DOH_REPLACE_ANY); /* { String *tmname = Getattr(tm,"typemap"); if (tmname) Replace(s,"$typemap",tmname, DOH_REPLACE_ANY); } */ Replace(s, "$parmname", pname, DOH_REPLACE_ANY); /* Replace(s,"$name",pname,DOH_REPLACE_ANY); */ Delete(locals); Delete(mtype); return s; } /* ----------------------------------------------------------------------------- * Swig_typemap_lookup_new() * * Attach one or more typemaps to a node * op - typemap name, eg "out", "newfree" * node - the node to attach the typemaps to * lname - * f - * ----------------------------------------------------------------------------- */ String *Swig_typemap_lookup_new(const String_or_char *op, Node *node, const String_or_char *lname, Wrapper *f) { SwigType *type; SwigType *mtype = 0; String *pname; Hash *tm = 0; String *s = 0; String *sdef = 0; ParmList *locals; ParmList *kw; char temp[256]; String *symname; String *cname = 0; String *clname = 0; char *cop = Char(op); /* special case, we need to check for 'ref' call and set the default code 'sdef' */ if (node && Cmp(op, "newfree") == 0) { sdef = Swig_ref_call(node, lname); } type = Getattr(node, "type"); if (!type) return sdef; pname = Getattr(node, "name"); #if 1 if (pname && node && checkAttribute(node, "kind", "function")) { /* For functions, look qualified names first, such as struct Foo { int *foo(int bar) -> Foo::foo }; */ Symtab *st = Getattr(node, "sym:symtab"); String *qsn = st ? Swig_symbol_string_qualify(pname, st) : 0; if (qsn) { if (Len(qsn) && !Equal(qsn, pname)) { tm = Swig_typemap_search(op, type, qsn, &mtype); if (tm && (!Getattr(tm, "pname") || strstr(Char(Getattr(tm, "type")), "SWIGTYPE"))) { tm = 0; } } Delete(qsn); } } if (!tm) #endif tm = Swig_typemap_search(op, type, pname, &mtype); if (!tm) return sdef; s = Getattr(tm, "code"); if (!s) return sdef; /* Empty typemap. No match */ if (Cmp(s, "pass") == 0) return sdef; s = Copy(s); /* Make a local copy of the typemap code */ locals = Getattr(tm, "locals"); if (locals) locals = CopyParmList(locals); if (pname) { if (SwigType_istemplate(pname)) { cname = SwigType_namestr(pname); pname = cname; } } if (SwigType_istemplate((char *) lname)) { clname = SwigType_namestr((char *) lname); lname = clname; } if (mtype && SwigType_isarray(mtype)) { typemap_replace_vars(s, locals, mtype, type, pname, (char *) lname, 1); } else { typemap_replace_vars(s, locals, type, type, pname, (char *) lname, 1); } if (locals && f) { typemap_locals(s, locals, f, -1); } replace_embedded_typemap(s); /* { String *tmname = Getattr(tm,"typemap"); if (tmname) Replace(s,"$typemap",tmname, DOH_REPLACE_ANY); } */ Replace(s, "$name", pname, DOH_REPLACE_ANY); symname = Getattr(node, "sym:name"); if (symname) { Replace(s, "$symname", symname, DOH_REPLACE_ANY); } Setattr(node, tmop_name(op), s); if (locals) { sprintf(temp, "%s:locals", cop); Setattr(node, tmop_name(temp), locals); Delete(locals); } if (Checkattr(tm, "type", "SWIGTYPE")) { sprintf(temp, "%s:SWIGTYPE", cop); Setattr(node, tmop_name(temp), "1"); } /* Attach kwargs */ kw = Getattr(tm, "kwargs"); while (kw) { String *value = Copy(Getattr(kw, "value")); String *type = Getattr(kw, "type"); char *ckwname = Char(Getattr(kw, "name")); if (type) { String *mangle = Swig_string_mangle(type); Append(value, mangle); Delete(mangle); } sprintf(temp, "%s:%s", cop, ckwname); Setattr(node, tmop_name(temp), value); Delete(value); kw = nextSibling(kw); } /* Look for warnings */ { String *w; sprintf(temp, "%s:warning", cop); w = Getattr(node, tmop_name(temp)); if (w) { Swig_warning(0, Getfile(node), Getline(node), "%s\n", w); } } /* Look for code fragments */ { String *f; sprintf(temp, "%s:fragment", cop); f = Getattr(node, tmop_name(temp)); if (f) { String *fname = Copy(f); Setfile(fname, Getfile(node)); Setline(fname, Getline(node)); Swig_fragment_emit(fname); Delete(fname); } } if (cname) Delete(cname); if (clname) Delete(clname); if (mtype) Delete(mtype); if (sdef) { /* put 'ref' and 'newfree' codes together */ String *p = NewStringf("%s\n%s", sdef, s); Delete(s); Delete(sdef); s = p; } return s; } /* ----------------------------------------------------------------------------- * Swig_typemap_attach_kwargs() * * If this hash (tm) contains a linked list of parameters under its "kwargs" * attribute, add keys for each of those named keyword arguments to this * parameter for later use. * For example, attach the typemap attributes to p: * %typemap(in, foo="xyz") ... * A new attribute called "tmap:in:foo" with value "xyz" is attached to p. * ----------------------------------------------------------------------------- */ void Swig_typemap_attach_kwargs(Hash *tm, const String_or_char *op, Parm *p) { String *temp = NewStringEmpty(); Parm *kw = Getattr(tm, "kwargs"); while (kw) { String *value = Copy(Getattr(kw, "value")); String *type = Getattr(kw, "type"); if (type) { Hash *v = NewHash(); Setattr(v, "type", type); Setattr(v, "value", value); Delete(value); value = v; } Clear(temp); Printf(temp, "%s:%s", op, Getattr(kw, "name")); Setattr(p, tmop_name(temp), value); Delete(value); kw = nextSibling(kw); } Clear(temp); Printf(temp, "%s:match_type", op); Setattr(p, tmop_name(temp), Getattr(tm, "type")); Delete(temp); } /* ----------------------------------------------------------------------------- * Swig_typemap_warn() * * If any warning message is attached to this parameter's "tmap:op:warning" * attribute, print that warning message. * ----------------------------------------------------------------------------- */ static void Swig_typemap_warn(const String_or_char *op, Parm *p) { String *temp = NewStringf("%s:warning", op); String *w = Getattr(p, tmop_name(temp)); Delete(temp); if (w) { Swig_warning(0, Getfile(p), Getline(p), "%s\n", w); } } static void Swig_typemap_emit_code_fragments(const String_or_char *op, Parm *p) { String *temp = NewStringf("%s:fragment", op); String *f = Getattr(p, tmop_name(temp)); if (f) { String *fname = Copy(f); Setfile(fname, Getfile(p)); Setline(fname, Getline(p)); Swig_fragment_emit(fname); Delete(fname); } Delete(temp); } /* ----------------------------------------------------------------------------- * Swig_typemap_attach_parms() * * Given a parameter list, this function attaches all of the typemaps for a * given typemap type * ----------------------------------------------------------------------------- */ String *Swig_typemap_get_option(Hash *tm, String *name) { Parm *kw = Getattr(tm, "kwargs"); while (kw) { String *kname = Getattr(kw, "name"); if (Equal(kname, name)) { return Getattr(kw, "value"); } kw = nextSibling(kw); } return 0; } void Swig_typemap_attach_parms(const String_or_char *op, ParmList *parms, Wrapper *f) { Parm *p, *firstp; Hash *tm; int nmatch = 0; int i; String *s; ParmList *locals; int argnum = 0; char temp[256]; char *cop = Char(op); String *kwmatch = 0; p = parms; #ifdef SWIG_DEBUG Printf(stdout, "Swig_typemap_attach_parms: %s\n", op); #endif while (p) { argnum++; nmatch = 0; #ifdef SWIG_DEBUG Printf(stdout, "parms: %s %s %s\n", op, Getattr(p, "name"), Getattr(p, "type")); #endif tm = Swig_typemap_search_multi(op, p, &nmatch); #ifdef SWIG_DEBUG if (tm) Printf(stdout, "found: %s\n", tm); #endif if (!tm) { p = nextSibling(p); continue; } /* Check if the typemap requires to match the type of another typemap, for example: %typemap(in) SWIGTYPE * (int var) {...} %typemap(freearg,match="in") SWIGTYPE * {if (var$argnum) ...} here, the freearg typemap requires the "in" typemap to match, or the 'var$argnum' variable will not exist. */ kwmatch = Swig_typemap_get_option(tm, "match"); if (kwmatch) { String *tmname = NewStringf("tmap:%s", kwmatch); String *tmin = Getattr(p, tmname); Delete(tmname); #ifdef SWIG_DEBUG if (tm) Printf(stdout, "matching: %s\n", kwmatch); #endif if (tmin) { String *tmninp = NewStringf("tmap:%s:numinputs", kwmatch); String *ninp = Getattr(p, tmninp); Delete(tmninp); if (ninp && Equal(ninp, "0")) { p = nextSibling(p); continue; } else { SwigType *typetm = Getattr(tm, "type"); String *temp = NewStringf("tmap:%s:match_type", kwmatch); SwigType *typein = Getattr(p, temp); Delete(temp); if (!Equal(typein, typetm)) { p = nextSibling(p); continue; } else { int nnmatch; Hash *tmapin = Swig_typemap_search_multi(kwmatch, p, &nnmatch); String *tmname = Getattr(tm, "pname"); String *tnname = Getattr(tmapin, "pname"); if (!(tmname && tnname && Equal(tmname, tnname)) && !(!tmname && !tnname)) { p = nextSibling(p); continue; } } } } else { p = nextSibling(p); continue; } } s = Getattr(tm, "code"); if (!s) { p = nextSibling(p); continue; } #ifdef SWIG_DEBUG if (s) Printf(stdout, "code: %s\n", s); #endif /* Empty typemap. No match */ if (Cmp(s, "pass") == 0) { p = nextSibling(p); continue; } s = Copy(s); locals = Getattr(tm, "locals"); if (locals) locals = CopyParmList(locals); firstp = p; #ifdef SWIG_DEBUG Printf(stdout, "nmatch: %d\n", nmatch); #endif for (i = 0; i < nmatch; i++) { SwigType *type; String *pname; String *lname; SwigType *mtype; type = Getattr(p, "type"); pname = Getattr(p, "name"); lname = Getattr(p, "lname"); mtype = Getattr(p, "tmap:match"); if (mtype) { typemap_replace_vars(s, locals, mtype, type, pname, lname, i + 1); Delattr(p, "tmap:match"); } else { typemap_replace_vars(s, locals, type, type, pname, lname, i + 1); } if (Checkattr(tm, "type", "SWIGTYPE")) { sprintf(temp, "%s:SWIGTYPE", cop); Setattr(p, tmop_name(temp), "1"); } p = nextSibling(p); } if (locals && f) { typemap_locals(s, locals, f, argnum); } replace_embedded_typemap(s); /* Replace the argument number */ sprintf(temp, "%d", argnum); Replace(s, "$argnum", temp, DOH_REPLACE_ANY); /* Attach attributes to object */ #ifdef SWIG_DEBUG Printf(stdout, "attach: %s %s %s\n", Getattr(firstp, "name"), tmop_name(op), s); #endif Setattr(firstp, tmop_name(op), s); /* Code object */ if (locals) { sprintf(temp, "%s:locals", cop); Setattr(firstp, tmop_name(temp), locals); Delete(locals); } /* Attach a link to the next parameter. Needed for multimaps */ sprintf(temp, "%s:next", cop); Setattr(firstp, tmop_name(temp), p); /* Attach kwargs */ Swig_typemap_attach_kwargs(tm, op, firstp); /* Print warnings, if any */ Swig_typemap_warn(op, firstp); /* Look for code fragments */ Swig_typemap_emit_code_fragments(op, firstp); /* increase argnum to consider numinputs */ argnum += nmatch - 1; Delete(s); #ifdef SWIG_DEBUG Printf(stdout, "res: %s %s %s\n", Getattr(firstp, "name"), tmop_name(op), Getattr(firstp, tmop_name(op))); #endif } #ifdef SWIG_DEBUG Printf(stdout, "Swig_typemap_attach_parms: end\n"); #endif } /* ----------------------------------------------------------------------------- * split_embedded() * * This function replaces the special variable $typemap(....) with typemap * code. The general form of $typemap is as follows: * * $TYPEMAP(method, $var1=value, $var2=value, $var3=value,...) * * For example: * * $TYPEMAP(in, $1=int x, $input=y, ...) * * Note: this was added as an experiment and could be removed * ----------------------------------------------------------------------------- */ /* Splits the arguments of an embedded typemap */ static List *split_embedded(String *s) { List *args = 0; char *c, *start; int level = 0; int leading = 1; args = NewList(); c = strchr(Char(s), '('); c++; start = c; while (*c) { if (*c == '\"') { c++; while (*c) { if (*c == '\\') { c++; } else { if (*c == '\"') break; } c++; } } if ((level == 0) && ((*c == ',') || (*c == ')'))) { String *tmp = NewStringWithSize(start, c - start); Append(args, tmp); Delete(tmp); start = c + 1; leading = 1; if (*c == ')') break; c++; continue; } if (*c == '(') level++; if (*c == ')') level--; if (isspace((int) *c) && leading) start++; if (!isspace((int) *c)) leading = 0; c++; } return args; } static void split_var(String *s, String **name, String **value) { char *eq; char *c; eq = strchr(Char(s), '='); if (!eq) { *name = 0; *value = 0; return; } c = Char(s); *name = NewStringWithSize(c, eq - c); /* Look for $n variables */ if (isdigit((int) *(c))) { /* Parse the value as a type */ String *v; Parm *p; v = NewString(eq + 1); p = Swig_cparse_parm(v); Delete(v); *value = p; } else { *value = NewString(eq + 1); } } static void replace_embedded_typemap(String *s) { char *start = 0; while ((start = strstr(Char(s), "$TYPEMAP("))) { /* Gather the argument */ char *end = 0, *c; int level = 0; String *tmp; c = start; while (*c) { if (*c == '(') level++; if (*c == ')') { level--; if (level == 0) { end = c + 1; break; } } c++; } if (end) { tmp = NewStringWithSize(start, (end - start)); } else { tmp = 0; } /* Got a substitution. Split it apart into pieces */ if (tmp) { List *l; Hash *vars; String *method; int i, ilen; l = split_embedded(tmp); vars = NewHash(); ilen = Len(l); for (i = 1; i < ilen; i++) { String *n, *v; split_var(Getitem(l, i), &n, &v); if (n && v) { Insert(n, 0, "$"); Setattr(vars, n, v); } Delete(n); Delete(v); } method = Getitem(l, 0); /* Generate the parameter list for matching typemaps */ { Parm *p = 0; Parm *first = 0; char temp[32]; int n = 1; while (1) { Hash *v; sprintf(temp, "$%d", n); v = Getattr(vars, temp); if (v) { if (p) { set_nextSibling(p, v); set_previousSibling(v, p); } p = v; Setattr(p, "lname", Getattr(p, "name")); if (Getattr(p, "value")) { Setattr(p, "name", Getattr(p, "value")); } if (!first) first = p; DohIncref(p); Delattr(vars, temp); } else { break; } n++; } /* Perform a typemap search */ if (first) { #ifdef SWIG_DEBUG Printf(stdout, "Swig_typemap_attach_parms: embedded\n"); #endif Swig_typemap_attach_parms(method, first, 0); { String *tm; int match = 0; char attr[64]; sprintf(attr, "tmap:%s", Char(method)); /* Look for the typemap code */ tm = Getattr(first, attr); if (tm) { sprintf(attr, "tmap:%s:next", Char(method)); if (!Getattr(first, attr)) { /* Should be no more matches. Hack??? */ /* Replace all of the remaining variables */ Iterator ki; for (ki = First(vars); ki.key; ki = Next(ki)) { Replace(tm, ki.key, ki.item, DOH_REPLACE_ANY); } /* Do the replacement */ Replace(s, tmp, tm, DOH_REPLACE_ANY); Delete(tm); match = 1; } } if (!match) { Swig_error(Getfile(s), Getline(s), "No typemap found for %s\n", tmp); } } } } Replace(s, tmp, "<embedded typemap>", DOH_REPLACE_ANY); Delete(vars); Delete(tmp); Delete(l); } } } /* ----------------------------------------------------------------------------- * Swig_typemap_debug() * ----------------------------------------------------------------------------- */ void Swig_typemap_debug() { int ts; Printf(stdout, "---[ typemaps ]--------------------------------------------------------------\n"); ts = tm_scope; while (ts >= 0) { Printf(stdout, "::: scope %d\n\n", ts); Printf(stdout, "%s\n", typemaps[ts]); ts--; } Printf(stdout, "-----------------------------------------------------------------------------\n"); } <file_sep>/******************************************************************** created: 2007/12/12 created: 12:12:2007 11:55 filename: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude\CustomPlayerStructs.h file path: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude file base: CustomPlayerStructs file ext: h author: mc007 purpose: *********************************************************************/ #ifndef __CUSTOM_PLAYER_STRUCTS_H_ #define __CUSTOM_PLAYER_STRUCTS_H_ namespace vtPlayer { namespace Structs { ////////////////////////////////////////////////////////////////////////// //managers,... : struct xSEnginePointers { CKContext* TheCKContext; CKTimeManager* TheTimeManager; CKMessageManager* TheMessageManager; CKRenderManager* TheRenderManager; CKRenderContext* TheRenderContext; CKPluginManager* ThePluginManager; xSEnginePointers() : TheCKContext(0),TheTimeManager(0),TheMessageManager(0), TheRenderManager(0),TheRenderContext(0),ThePluginManager(0) { } }; ////////////////////////////////////////////////////////////////////////// //player modies : enum xEApplicationMode { config, // Config dialog box preview, // Mini preview window in Display Properties dialog normal, // Full-on screensaver mode passwordchange, java, decompress, static_res, popup }; ////////////////////////////////////////////////////////////////////////// //Paths : class xSEnginePaths { public: XString RenderPath; XString ManagerPath; XString BehaviorPath; XString PluginPath; XString CompositionFile; XString DecompressFile; XString ConfigFile; XString ApplicationProfileFile; XString InstallDirectory; virtual ~xSEnginePaths(){} }; ////////////////////////////////////////////////////////////////////////// //Engine Parameters: struct xSEngineWindowInfo{ int g_FullScreenDriver; int g_Mode; BOOL g_DisableSwitch; BOOL g_NoContextMenu; BOOL g_GoFullScreen; int g_RefreshRate; int g_WidthW; int g_HeightW; int g_Width; int g_Height; int g_Bpp; int g_Driver; int FSSA; BOOL g_HasResMask; typedef XArray<int> xSResMaskArray; xSResMaskArray g_ResMaskArrayX; xSResMaskArray g_ResMaskArrayY; typedef XArray<XString> xSAllowedOpenGLVersions; xSAllowedOpenGLVersions g_OpenGLMask; xSEngineWindowInfo() : g_FullScreenDriver(0), g_Mode(0), g_DisableSwitch(false), g_NoContextMenu(false), g_GoFullScreen(false), g_RefreshRate(g_Width), g_Width(1024), g_Height(768), g_Bpp(32), g_Driver(0), FSSA(0){} }; ////////////////////////////////////////////////////////////////////////// //Application Style class xSApplicationWindowStyle { public: int g_MouseDrag; int g_OwnerDrawed; int g_Render; int IsRenderering() const { return g_Render; } int g_Sound; int g_CaptionBar; int g_IsResizeable; int g_SizeBox; int g_AOT; XString g_AppTitle; XString AppTitle() const { return g_AppTitle; } int g_SSMode; int g_MMT; BOOL g_UseSplash; BOOL g_ShowLoadingProcess; BOOL g_AllowEscExit; int g_ShowDialog; int g_ShowAboutTab; int g_ShowConfigTab; int g_MinimumDirectXVersion; int g_MiniumumRAM; BOOL ShowLoadingProcess() const { return g_ShowLoadingProcess; } BOOL UseSplash() const { return g_UseSplash; } xSApplicationWindowStyle() : g_Render(0), g_CaptionBar(0), g_IsResizeable(0), g_SizeBox(0), g_AOT(0), g_SSMode(0), g_MMT(0), g_ShowDialog(0), g_ShowAboutTab(0), g_ShowConfigTab(0), g_MinimumDirectXVersion(9), g_MiniumumRAM(256), g_UseSplash(false), g_AllowEscExit(false) { } virtual ~xSApplicationWindowStyle() { } }; } //end of namespace structs } //end of namespace structs using namespace vtPlayer::Structs; #endif<file_sep>/* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * utils.cxx * * Various utility functions. * ----------------------------------------------------------------------------- */ char cvsroot_utils_cxx[] = "$Id: utils.cxx 10003 2007-10-17 21:42:11Z wsfulton $"; #include <swigmod.h> int is_public(Node *n) { String *access = Getattr(n, "access"); return !access || !Cmp(access, "public"); } int is_private(Node *n) { String *access = Getattr(n, "access"); return access && !Cmp(access, "private"); } int is_protected(Node *n) { String *access = Getattr(n, "access"); return access && !Cmp(access, "protected"); } int is_member_director(Node *parentnode, Node *member) { int director_mode = Swig_director_mode(); if (parentnode && checkAttribute(member, "storage", "virtual")) { int parent_nodirector = GetFlag(parentnode, "feature:nodirector"); if (parent_nodirector) return 0; int parent_director = director_mode && GetFlag(parentnode, "feature:director"); int cdecl_director = parent_director || GetFlag(member, "feature:director"); int cdecl_nodirector = GetFlag(member, "feature:nodirector"); return cdecl_director && !cdecl_nodirector && !GetFlag(member, "feature:extend"); } else { return 0; } } int is_member_director(Node *member) { return is_member_director(Getattr(member, "parentNode"), member); } /* Clean overloaded list. Removes templates, ignored, and errors */ void clean_overloaded(Node *n) { Node *nn = Getattr(n, "sym:overloaded"); Node *first = 0; int cnt = 0; while (nn) { String *ntype = nodeType(nn); if ((GetFlag(nn, "feature:ignore")) || (Getattr(nn, "error")) || (Strcmp(ntype, "template") == 0) || ((Strcmp(ntype, "cdecl") == 0) && is_protected(nn) && !is_member_director(nn)) || ((Strcmp(ntype, "using") == 0) && !firstChild(nn))) { /* Remove from overloaded list */ Node *ps = Getattr(nn, "sym:previousSibling"); Node *ns = Getattr(nn, "sym:nextSibling"); if (ps) { Setattr(ps, "sym:nextSibling", ns); } if (ns) { Setattr(ns, "sym:previousSibling", ps); } Delattr(nn, "sym:previousSibling"); Delattr(nn, "sym:nextSibling"); Delattr(nn, "sym:overloaded"); nn = ns; continue; } else if ((Strcmp(ntype, "using") == 0)) { /* A possibly dangerous parse tree hack. We're going to cut the parse tree node out and stick in the resolved using declarations */ Node *ps = Getattr(nn, "sym:previousSibling"); Node *ns = Getattr(nn, "sym:nextSibling"); Node *un = firstChild(nn); Node *pn = un; if (!first) { first = un; } while (pn) { Node *ppn = Getattr(pn, "sym:nextSibling"); Setattr(pn, "sym:overloaded", first); Setattr(pn, "sym:overname", NewStringf("%s_%d", Getattr(nn, "sym:overname"), cnt++)); if (ppn) pn = ppn; else break; } if (ps) { Setattr(ps, "sym:nextSibling", un); Setattr(un, "sym:previousSibling", ps); } if (ns) { Setattr(ns, "sym:previousSibling", pn); Setattr(pn, "sym:nextSibling", ns); } if (!first) { first = un; Setattr(nn, "sym:overloaded", first); } } else { if (!first) first = nn; Setattr(nn, "sym:overloaded", first); } nn = Getattr(nn, "sym:nextSibling"); } if (!first || (first && !Getattr(first, "sym:nextSibling"))) { Delattr(n, "sym:overloaded"); } } <file_sep>#include "xDistributedObject.h" #include "xDistributed3DObject.h" #include "xDistributedBaseClass.h" #include "xNetInterface.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "IDistributedClasses.h" #include <xLogger.h> #include <uxString.h> uxString xDistributedObject::print(TNL::BitSet32 flags) { using namespace std; uxString result(" "); char buffer[4096]; ////////////////////////////////////////////////////////////////////////// //name ? if (isFlagOn(flags,E_OPF_NAME)) { result << " Name:" << GetName().getString(); } //ghostID if (isFlagOn(flags,E_OPF_GHOST_ID)) { result << " GhostID:"; int gID = getOwnerConnection() ? getOwnerConnection()->getGhostIndex((TNL::NetObject*)this) :-1 ; result <<gID ; } //userID? if (isFlagOn(flags,E_OPF_USER_ID)) { result << " UserID:" << getUserID(); } //userID? if (isFlagOn(flags,E_OPF_CLASS)) { result << " Class : " << uxString(getDistributedClass() ? getDistributedClass()->getClassName().getString() : "NOCLASS"); int EType = getDistributedClass() ? getDistributedClass()->getEnitityType() : -1; result << " : EType:" << EType; } //SessionID? if (isFlagOn(flags,E_OPF_SESSION_ID)) { result << " SessionID:" << getSessionID(); } return result; //TNL::logprintf(result.CStr()); // xLogger::xLogExtro(0,"UserName : %s \n\tSessionID:%d \n\tIsJoined:%d \n\tGhostIndex:%d",sobj->getUserName().getString(),sobj->getSessionID(),isFlagOn(sobj->getClientFlags(),E_CF_SESSION_JOINED) ? 1 : 0,gIndex ); } TNL::U32 xDistributedObject::packUpdate(TNL::GhostConnection *connection, TNL::U32 updateMask, TNL::BitStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); //write out name : const char* name = GetName().getString(); stream->writeString(name,strlen(name)); //write class : xDistributedClass *distClass = getDistributedClass(); if (distClass) { //write out the class name : stream->writeString(distClass->getClassName().getString()); //write out the class base type : stream->writeInt(distClass->getEnitityType(),32); }else xLogger::xLog(XL_START,ELOGWARNING,E_LI_DISTRIBUTED_BASE_OBJECT,"initial pack : no class found"); //write user id stream->writeInt(getUserID(),32); //write session id stream->writeInt(getSessionID(),32); setNetInterface(netInterface); xLogger::xLog(XL_START,ELOGTRACE,E_LI_DISTRIBUTED_BASE_OBJECT,"initial pack"); return 0; } void xDistributedObject::unpackUpdate(TNL::GhostConnection *connection, TNL::BitStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); vtConnection *vconnection = (vtConnection*)connection; char oName[256];stream->readString(oName); // retrieve objects name : char cName[256];stream->readString(cName); // retrieve objects dist class name : int type = stream->readInt(32); setUserID(stream->readInt(32)); setSessionID(stream->readInt(32)); SetName(oName); //find and store the dist class : xDistributedClassesArrayType *_classes = netInterface->getDistributedClassInterface()->getDistrutedClassesPtr(); xDistributedClass *classTemplate = netInterface->getDistributedClassInterface()->get(cName); if (!classTemplate) { classTemplate = netInterface->getDistributedClassInterface()->createClass(cName,type); }else xLogger::xLog(XL_START,ELOGWARNING,E_LI_DISTRIBUTED_BASE_OBJECT,"initial unpack : no class found"); setDistributedClass(classTemplate); xLogger::xLog(XL_START,ELOGTRACE,E_LI_DISTRIBUTED_BASE_OBJECT,"initial unpack"); setNetInterface(netInterface); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedProperty* xDistributedObject::getProperty(int nativeType) { xDistributedProperty* result = NULL; if (getDistributedClass()) { xDistributedClass *_class = getDistributedClass(); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; if (prop->getPropertyInfo()->mNativeType == nativeType) { return prop; } } } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedProperty* xDistributedObject::getUserProperty(const char*name) { xDistributedProperty* result = NULL; if (getDistributedClass()) { xDistributedClass *_class = getDistributedClass(); xDistributedPropertyArrayType &props = *getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; if (!strcmp(prop->getPropertyInfo()->mName.getString(),name)) { return prop; } } } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedObject::onGhostAvailable(TNL::GhostConnection *theConnection) { xNetInterface *netInterface = (xNetInterface*) theConnection->getInterface(); if (netInterface) { if (netInterface->IsServer()) { IDistributedObjects *distInterface = netInterface->getDistObjectInterface(); if (distInterface) { setServerID(theConnection->getGhostIndex(this)); } } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedObject::onGhostAdd(TNL::GhostConnection *theConnection) { xNetInterface *netInterface = (xNetInterface*) theConnection->getInterface(); if (netInterface) { if (!netInterface->IsServer()) { xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); distObjects->push_back(this); setNetInterface(netInterface); } } return true; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedObject::writeControlState(xNStream *stream) { } void xDistributedObject::changeOwnership(int newUserID,int state) { setUserID(newUserID); if (newUserID == getUserID()) { setOwnershipState(E_DO_OS_OWNER); } if (newUserID !=getUserID()) { setOwnershipState(E_DO_OS_OTHER); } } void xDistributedObject::getOwnership() { getOwnershipState().set( 1<< E_DO_OS_REQUEST,true ); /* xNetInterface *nInterface = getNetInterface(); if (nInterface) { if (nInterface->isValid()) { nInterface->getConnection()->c2sDORequestOwnerShip() } }*/ /* if ( && getOwnershipState() !=E_DO_OS_REQUEST) { setOwnershipState(E_DO_OS_REQUEST); } */ } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedObject::pack(xNStream *bstream) { bstream->writeSignedInt(this->getUpdateBits().getMask(),32); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedObject::unpack( xNStream *bstream,float sendersOneWayTime ) { int uFlags = bstream->readSignedInt(32); setUpdateBits(uFlags); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedObject::prepare() { //TNL::PacketStream stream; /*pack(&stream); stream.setBytePosition(0); unpack(&stream);*/ } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedObject::initProperties() { ////////////////////////////////////////////////////////////////////////// //we iterate through the dist classes properties if (getDistributedClass()) { xDistributedClass *_class = getDistributedClass(); xDistributedPropertiesListType *props = _class->getDistributedProperties(); if (props) { } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributed3DObject* xDistributedObject::cast(xDistributedObject* _in){ return static_cast<xDistributed3DObject*>(_in); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedObject::destroy() { xNetInterface *netInterface = getNetInterface(); if (netInterface) { xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { if (*begin==this) { distObjects->erase(begin); } begin++; } } Parent::Destroy(); m_DistributedClass=NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedObject::xDistributedObject() : xNetObject() { m_DistributedClass=NULL; m_EntityID = 0; m_InterfaceFlags =0; m_ObjectFlags = 0; m_UpdateFlags = 0; m_UpdateState = 0; m_GhostDebugID = 0; m_GhostUpdateBits = 0; m_DistrtibutedPorperties = new xDistributedPropertyArrayType(); m_OwnershipState.clear(); mSessionID = -1; mObjectStateFlags =0; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedObject::~xDistributedObject() { Parent::Destroy(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ /* void xDistributedObject::performScopeQuery(TNL::GhostConnection *connection) { xNetInterface *netInterface = GetNetInterface(); if (!netInterface) { return; } vtDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); if (!distObjects) { return; } vtDistObjectIt begin = distObjects->begin(); vtDistObjectIt end = distObjects->end(); while (begin != end) { xDistributedObject*dobject = *begin; if (dobject) { connection->objectInScope((TNL::NetObject*) dobject ); } begin++; } }*/ /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ /* void xDistributedObject::onGhostAvailable(TNL::GhostConnection *theConnection) { xNetInterface *netInterface = (xNetInterface*) theConnection->getInterface(); if (netInterface) { if (netInterface->IsServer()) { IDistributedObjects *distInterface = netInterface->getDistObjectInterface(); if (distInterface) { //cast a dist object : // xDistributedObject *distObject = static_cast<xDistributedObject *>(this); // const char *className =distObject->GetDistributedClass()->ClassName().CStr(); //distInterface->cCreateDistObject(distObject->GetServerID(),this->GetUserID(),this->GetName().getString(),className); logprintf("OnGhostAdd"); } } } }*/ /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ /* bool xDistributedObject::onGhostAdd(TNL::GhostConnection *theConnection) { xNetInterface *netInterface = (xNetInterface*) theConnection->getInterface(); if (netInterface) { if (!netInterface->IsServer()) { vtDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); distObjects->PushBack(this); SetNetInterface(netInterface); logprintf("OnGhostAdd"); } } return TRUE; } */ /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ /* TNL::U32 xDistributedObject::packUpdate(TNL::GhostConnection *connection, TNL::U32 updateMask, xNStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); if (netInterface) { //server side only : if (netInterface->IsServer()) { //the first time ? : we write out all necessary attributes for the client : if(stream->writeFlag(updateMask & InitialMask)) { //write out name : const char* name = this->GetName().getString(); stream->writeString(name,strlen(name)); //retrieve its class : xDistributedClass *distClass = GetDistributedClass(); if (distClass) { //write out the class name : stream->writeString(distClass->ClassName().CStr()); //write out the class base type : stream->writeSignedInt(distClass->GetEnitityType(),16); vtConnection *con = (vtConnection*)connection; stream->writeSignedInt(con->GetUserID(),16); }else { //write out the class name : stream->writeString("NOCLASS"); //write out the class base type : stream->writeSignedInt(100,16); vtConnection *con = (vtConnection*)connection; stream->writeSignedInt(con->GetUserID(),16); } logprintf("server:init pack update"); SetNetInterface(netInterface); } } } return 0; } */ /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ /* void xDistributedObject::unpackUpdate(TNL::GhostConnection *connection, xNStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); if (netInterface) { //client side only : if (!netInterface->IsServer()) { ////////////////////////////////////////////////////////////////////////// //initial update ? if(stream->readFlag()) { char oName[256];stream->readString(oName); // retrieve objects name : char cName[256];stream->readString(cName); // retrieve objects dist class name : int type = stream->readInt(16); //read the dist class base type : ////////////////////////////////////////////////////////////////////////// //now we store all in the dist object : SetName(oName); //find and store the dist class : XDistributedClassesArrayType *_classes = netInterface->getDistributedClassInterface()->getDistrutedClassesPtr(); xDistributedClass *classTemplate = NULL; xDistClassIt it = _classes->Find(cName); if (it != _classes->End()) { classTemplate = *it; //store the class : //distObject->SetDistributedClass(classTemplate); } //store server id : int serverID = connection->getGhostIndex((NetObject*)this); SetServerID(serverID); SetObjectFlags(E_DO_CREATION_CREATED); this->SetNetInterface(netInterface); vtConnection *con = (vtConnection*)connection; int userID = stream->readInt(16); SetUserID(userID); logprintf("DO initial update received by server : %s | class : %s",oName,cName ); //store it in our array : //vtDistributedObjectsArrayType *distObjects = netInterface->GetDistributedObjects(); //distObjects->PushBack(distObject); } } } } */ <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorJD6SetDriveDecl(); CKERROR CreateJD6SetDriveProto(CKBehaviorPrototype **pproto); int JD6SetDrive(const CKBehaviorContext& behcontext); CKERROR JD6SetDriveCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_BodyA=0, bbI_BodyB, bbI_Anchor, bbI_AnchorRef, bbI_Axis, bbI_AxisRef }; //************************************ // Method: FillBehaviorJD6SetDriveDecl // FullName: FillBehaviorJD6SetDriveDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorJD6SetDriveDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6SetDrive"); od->SetCategory("Physic/D6"); od->SetDescription("Modifies the D6 drive."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x2db16c45,0x695938e4)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJD6SetDriveProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreateJD6SetDriveProto // FullName: CreateJD6SetDriveProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreateJD6SetDriveProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6SetDrive"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PJD6SetDrive <br> PJD6SetDrive is categorized in \ref D6BB <br> <br>See <A HREF="PJD6.cmo">PJD6.cmo</A>. <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies a linear or an angular drive. <br> <br> <h3>Technical Information</h3> \image html PJD6SetDrive.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Body B: </SPAN>The second body to identfy the joint. <BR> <BR> <SPAN CLASS="pin">Target Drive: </SPAN>The target drive. See #D6DriveAxis. <BR> <SPAN CLASS="pin">Drive: </SPAN> Holds drive settings. See #pJD6Drive. <BR> See \ref D6AngularDrivesGuide "Angular Drives"<br> See \ref D6LinearDrivesGuide "Linear Drives"<br> */ proto->SetBehaviorCallbackFct( JD6SetDriveCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Target Drive",VTE_JOINT_DRIVE_AXIS,0); proto->DeclareInParameter("Drive",VTS_JOINT_DRIVE); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(JD6SetDrive); *pproto = proto; return CK_OK; } //************************************ // Method: JD6SetDrive // FullName: JD6SetDrive // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int JD6SetDrive(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); if(bodyA || bodyB) { pJointD6 *joint =static_cast<pJointD6*>(worldA->getJoint(target,targetB,JT_D6)); D6DriveAxis targetDrive = GetInputParameterValue<D6DriveAxis>(beh,1); pJD6Drive drive; CKParameter* pout = beh->GetInputParameter(2)->GetRealSource(); CK_ID* ids = (CK_ID*)pout->GetReadDataPtr(); float damping,spring,forceLimit; int driveMode; pout = (CKParameterOut*)ctx->GetObject(ids[0]); pout->GetValue(&damping); pout = (CKParameterOut*)ctx->GetObject(ids[1]); pout->GetValue(&spring); pout = (CKParameterOut*)ctx->GetObject(ids[2]); pout->GetValue(&forceLimit); pout = (CKParameterOut*)ctx->GetObject(ids[3]); pout->GetValue(&driveMode); drive.damping = damping; drive.spring = spring; drive.driveType = driveMode; drive.forceLimit = forceLimit; if (joint) { switch(targetDrive) { case D6DA_Twist: joint->setTwistDrive(drive); break; case D6DA_Swing: joint->setSwingDrive(drive); break; case D6DA_Slerp: joint->setSlerpDrive(drive); break; case D6DA_X: joint->setXDrive(drive); break; case D6DA_Y: joint->setYDrive(drive); break; case D6DA_Z: joint->setZDrive(drive); break; } } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: JD6SetDriveCB // FullName: JD6SetDriveCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR JD6SetDriveCB(const CKBehaviorContext& behcontext) { return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pVehicleMotor.h" #include "pVehicleGears.h" #include "pSteer.h" #include "pGearbox.h" #include <xDebugTools.h> #include "NxArray.h" #include "pVehicleAll.h" #include "virtools/vtTools.h" using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; using namespace vtTools::BehaviorTools; void pVehicle::step(float dt) { if (isValidEngine()) { //---------------------------------------------------------------- // // update user controls // steer->SetInput(_cSteering);doSteering(); engine->updateUserControl(_cAcceleration); if ( (_currentStatus & VS_IsAcceleratedForward ) || (_currentStatus & VS_IsAcceleratedBackward) ) { driveLine->SetInput(1000.0f,_cHandbrake); } if (!(_currentStatus & VS_IsAccelerated) ) { driveLine->SetInput(0.0f,_cHandbrake); } //---------------------------------------------------------------- // // // preAnimate(); engine->CalcForces(); for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel2 *cW = (pWheel2*)_wheels[i]; if (cW->isAxleSpeedFromVehicle() || cW->isTorqueFromVehicle() ) cW->calcForces(); } driveLine->CalcForces(); ////////////////////////////////////////////////////////////////////////// // Now that engine and wheel forces are unknown, check the diffs for(int i=0;i<differentials;i++) differential[i]->CalcForces(); ////////////////////////////////////////////////////////////////////////// driveLine->CalcAccelerations(); for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel2 *cW = (pWheel2*)_wheels[i]; if (cW->isAxleSpeedFromVehicle() || cW->isTorqueFromVehicle() ) cW->CalcAccelerations(); } ////////////////////////////////////////////////////////////////////////// #ifdef OBS_RPM_IS_NEW // Engine RPM is related to the rotation of the powered wheels, // since they are physically connected, somewhat // Take the minimal rotation float minV=99999.0f,maxV=0; for(int i=0;i<_wheels.size();i++) { pWheel2 *cW = (pWheel2*)_wheels[i]; if (cW && (cW->getWheelFlag(WF_Accelerated) && ( cW->getWheelShape()->getWheelFlags() & WSF_AxleSpeedOverride)) ) { if(cW->GetRotationV()>maxV) maxV=cW->GetRotationV(); #ifdef OBS_HMM if(cW[i]->GetRotationV()<minV) minV=cW->GetRotationV(); #endif } } /*engine-> engine->ApplyWheelRotation(maxV);*/ #endif ////////////////////////////////////////////////////////////////////////// steer->Integrate(); for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel2 *cW = (pWheel2*)_wheels[i]; if (cW->isAxleSpeedFromVehicle() || cW->isTorqueFromVehicle() ) cW->Integrate(); } driveLine->Integrate(); for(int i=0;i<differentials;i++) { getDifferential(i)->Integrate(); } gearbox->processFutureGear(); } } void pVehicle::processPreScript() { } void pVehicle::processPostScript() { CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(postScript); if (beh) { SetInputParameterValue<int>(beh,0,5); beh->Execute(_lastDT); GetOutputParameterValue<int>(beh,0); } } int pVehicle::onPostProcess() { /* if (getBody()->isSleeping()) getBody()->wakeUp(); */ _lastDT = lastStepTimeMS; _currentStatus = _calculateCurrentStatus(); VehicleStatus status = (VehicleStatus)_currentStatus; float bTorque = calculateBraking(_lastDT); if (_cSteering != 0 || _cAcceleration != 0 || _cHandbrake) getActor()->wakeUp(0.05); if (isValidEngine()) //new vehicle code step(_lastDT); else //old _performSteering(_lastDT ); if ( !(flags & VF_UseAdvance )) { _performAcceleration(_lastDT); postStep(); }else { for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel2* wheel = (pWheel2*)_wheels[i]; if( wheel->isTorqueFromVehicle()) wheel->applyTorqueToPhysics(); if( wheel->isAxleSpeedFromVehicle() ) { /* float v = wheel->rotationV.x; v = v * getEngine()->getEndRotationalFactor() * getEngine()->getTimeScale(); */ //wheel->getWheelShape()->setAxleSpeed(v); /* pDifferential *diff = getDifferential(0); float tOutOne = diff->GetTorqueOut(wheel[0]->differentialSide); float tOutSeconf = diff->GetTorqueOut(wheel[1]->differentialSide); */ } } } for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel2* wheel = (pWheel2*)_wheels[i]; wheel->updateSteeringPose( wheel->getWheelRollAngle(),wheel->getWheelShape()->getSteerAngle(),_lastDT); wheel->updatePosition(); } setVSFlags(_currentStatus); processPostScript(); updateControl(0,false,0,false,false); return 1; } int pVehicle::onPreProcess() { _lastDT = lastStepTimeMS; return 1; } void pVehicle::updateVehicle( float lastTimeStepSize ) { return; _lastDT = lastTimeStepSize; _currentStatus = _calculateCurrentStatus(); VehicleStatus status = (VehicleStatus)_currentStatus; if (_cSteering != 0 || _cAcceleration != 0 || _cHandbrake) getActor()->wakeUp(0.05); float bTorque = calculateBraking(lastTimeStepSize); _performSteering(lastTimeStepSize); if (engine && gearbox && driveLine ) { step(lastTimeStepSize); } if ( !(flags & VF_UseAdvance )) { _performAcceleration(lastTimeStepSize); postStep(); }else { for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel2* wheel = (pWheel2*)_wheels[i]; /* if( (wheel->getWheelFlag(WF_Accelerated)) && (wheel->getWheelShape()->getWheelFlags() & WSF_AxleSpeedOverride )) { float v = wheel->rotationV.x *= 1.0f; wheel->getWheelShape()->setAxleSpeed( v ); } */ } } for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel2* wheel = (pWheel2*)_wheels[i]; wheel->updateSteeringPose( wheel->getWheelRollAngle(),wheel->getWheelShape()->getSteerAngle(),lastTimeStepSize); wheel->updatePosition(); } if (getMotor()) { _currentStatus |= E_VSF_HAS_MOTOR; } if (getGears()) { _currentStatus |= E_VSF_HAS_GEARS; } setVSFlags(_currentStatus); return; //---------------------------------------------------------------- // // old code // //control(_cSteering,_cAnalogSteering,_cAcceleration,_cAnalogAcceleration,_cHandbrake); //printf("updating %x\n", this); NxReal distanceSteeringAxisCarTurnAxis = _steeringSteerPoint.x - _steeringTurnPoint.x; NX_ASSERT(_steeringSteerPoint.z == _steeringTurnPoint.z); NxReal distance2 = 0; if (NxMath::abs(_steeringWheelState) > 0.01f) distance2 = distanceSteeringAxisCarTurnAxis / NxMath::tan(_steeringWheelState * _steeringMaxAngleRad); NxU32 nbTouching = 0; NxU32 nbNotTouching = 0; NxU32 nbHandBrake = 0; int wSize = _wheels.size(); for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel* wheel = _wheels[i]; if(wheel->getWheelFlag(WF_SteerableInput)) { if(distance2 != 0) { NxReal xPos = wheel->getWheelPos().x; NxReal xPos2 = _steeringSteerPoint.x- wheel->getWheelPos().x; NxReal zPos = wheel->getWheelPos().z; NxReal dz = -zPos + distance2; NxReal dx = xPos - _steeringTurnPoint.x; float atan3 = NxMath::atan(dx/dz); float angle =(NxMath::atan(dx/dz)); if (dx < 0.0f) { angle*=-1.0f; } wheel->setAngle(angle); //errMessage.Format("w%d dz:%f dx:%f dx2%f distance:%f atan3:%f",i,dz,dx,xPos2,distance2,atan3); //xInfo(errMessage.Str()); } else { wheel->setAngle(0.0f); } //printf("%2.3f\n", wheel->getAngle()); } else if(wheel->getWheelFlag(WF_SteerableAuto)) { NxVec3 localVelocity = getActor()->getLocalPointVelocity(getFrom(wheel->getWheelPos())); NxQuat local2Global = getActor()->getGlobalOrientationQuat(); local2Global.inverseRotate(localVelocity); // printf("%2.3f %2.3f %2.3f\n", wheel->getWheelPos().x,wheel->getWheelPos().y,wheel->getWheelPos().z); localVelocity.y = 0; if(localVelocity.magnitudeSquared() < 0.1f) { wheel->setAngle(0.0f); } else { localVelocity.normalize(); // printf("localVelocity: %2.3f %2.3f\n", localVelocity.x, localVelocity.z); if(localVelocity.x < 0) localVelocity = -localVelocity; NxReal angle = NxMath::clamp((NxReal)atan(localVelocity.z / localVelocity.x), 0.3f, -0.3f); wheel->setAngle(angle); } } // now the acceleration part if(!wheel->getWheelFlag(WF_Accelerated)) continue; if(_handBrake && wheel->getWheelFlag(WF_AffectedByHandbrake)) { nbHandBrake++; } else { if (!wheel->hasGroundContact()) { nbNotTouching++; } else { nbTouching++; } } } NxReal motorTorque = 0.0; float _acc = NxMath::abs(_accelerationPedal); XString errMessage; if(nbTouching && NxMath::abs(_accelerationPedal) > 0.1f ) { NxReal axisTorque = _computeAxisTorque(); NxReal wheelTorque = axisTorque / (NxReal)(_wheels.size() - nbHandBrake); NxReal wheelTorqueNotTouching = nbNotTouching>0?wheelTorque*(NxMath::pow(0.5f, (NxReal)nbNotTouching)):0; NxReal wheelTorqueTouching = wheelTorque - wheelTorqueNotTouching; motorTorque = wheelTorqueTouching / (NxReal)nbTouching; } else { _updateRpms(); } } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #define BB_SET_POSITION_GUID CKGUID(0xe456e78a, 0x456789aa) #define BB_SET_ORIENTATION_GUID CKGUID(0x625874aa, 0xaa694132) #define BB_ROTATE_GUID CKGUID(0xffffffee, 0xeeffffff) #define BB_TRANSLATE_GUID CKGUID(0x000d000d, 0x000d000d) #define BB_SET_EORIENTATION_GUID CKGUID(0xc4966d8,0x6c0c6d14) #define BB_PLAY_GLOBAL_ANIMATION CKGUID(0x1c9236e1,0x42f40996) #define BB_SET_LOCAL_MATRIX CKGUID(0x21f5f30d, 0x08d5a1db) #define BB_SET_WORLD_MATRIX CKGUID(0xaa4aa6f0, 0xddefdef4) #define BB_RESTORE_IC CKGUID(0x766e4e44,0x4fac6d52) #define BB_LAUNCH_SCENE CKGUID(0x188d6d43,0x169613dd) CKBEHAVIORFCT BBSetEOri; CKBEHAVIORFCT BBSetPos; CKBEHAVIORFCT BBSetOri; CKBEHAVIORFCT BBRotate; CKBEHAVIORFCT BBTranslate; CKBEHAVIORFCT BBPlayGlobalAnimation; CKBEHAVIORFCT BBSetLocalMatrix; CKBEHAVIORFCT BBSetWorldMatrix; CKBEHAVIORFCT BBRestoreIC; CKBEHAVIORFCT BBLaunchScene; #define BRESET VxVector vectorN(0,0,0);\ int pResetF=0;behaviour->GetLocalParameterValue(1,&pResetF);\ int pResetT=0;behaviour->GetLocalParameterValue(2,&pResetT);\ int pResetLV=0;behaviour->GetLocalParameterValue(3,&pResetLV);\ int pResetAV=0;behaviour->GetLocalParameterValue(4,&pResetAV);\ if (pResetF) solid->setLinearMomentum(vectorN);\ if (pResetT)solid->setAngularMomentum(vectorN);\ if (pResetLV)solid->setLinearVelocity(vectorN);\ if (pResetAV)solid->setAngularVelocity(vectorN);\ int BB_SetEOrientationNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBSetEOri(context); int pUpdate=0; behaviour->GetLocalParameterValue(1,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { BRESET; VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); int hierarchy = vtTools::BehaviorTools::GetInputParameterValue<int>(behaviour,1); if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) { solid->onSubShapeTransformation(false,true,true,ent,hierarchy); }else{ VxVector vector(0,0,0); ent->GetPosition(&vector); solid->setPosition(vector,ent); VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setRotation(quat); } //solid->updateSubShapes(false,false,true,ent); } } return CK_OK; } int BB_SetPosNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBSetPos(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pWorld *world = GetPMan()->getWorldByBody(ent); if (!world) { return 0; } pRigidBody *solid = world->getBody(ent); if (solid) { BRESET; VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); int hierarchy = vtTools::BehaviorTools::GetInputParameterValue<int>(behaviour,1); if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) { solid->onSubShapeTransformation(false,true,false,ent,hierarchy); }else{ VxVector vector(0,0,0); ent->GetPosition(&vector); solid->setPosition(vector,ent); } } } return CK_OK; } int BB_SetOrientationNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBSetOri(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { BRESET int hierarchy = vtTools::BehaviorTools::GetInputParameterValue<int>(behaviour,2); if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) { solid->onSubShapeTransformation(false,true,true,ent,hierarchy); }else{ VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setRotation(quat); } //solid->updateSubShapes(false,true,true,ent); } } return CK_OK; } int BB_RotateNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBRotate(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent,true); if (solid) { BRESET; int hierarchy = vtTools::BehaviorTools::GetInputParameterValue<int>(behaviour,3); if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) { solid->onSubShapeTransformation(false,true,true,ent,hierarchy); }else{ VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setRotation(quat); } } } return CK_OK; } int BB_TranslateNew(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBTranslate(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { BRESET; VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); int hierarchy = vtTools::BehaviorTools::GetInputParameterValue<int>(behaviour,1); if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) { solid->onSubShapeTransformation(false,true,true,ent,hierarchy); }else{ solid->setPosition(pos,ent); } } } return CK_OK; } int BBPlayGlobalAnimation_New(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; int returnValue= BBPlayGlobalAnimation(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { BRESET if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) { solid->onSubShapeTransformation(false,true,true,ent,true); }else{ VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setPosition(pos,ent); } }/* else { pWorld *world = GetPMan()->getWorldByBody(ent); if (world) { solid = world->getBodyFromSubEntity(ent); if (solid) { solid->updateSubShapes(false,true,true); } } }*/ } return returnValue; } int BBSetLocalMatrix_New(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBSetLocalMatrix(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { BRESET; int hierarchy = vtTools::BehaviorTools::GetInputParameterValue<int>(behaviour,1); if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) { solid->onSubShapeTransformation(false,true,true,ent,hierarchy); }else{ VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setPosition(pos,ent); } } } return CK_OK; } int BBSetWorldMatrix_New(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBSetWorldMatrix(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); if (pUpdate) { CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { //solid->getActor()-> BRESET int hierarchy = vtTools::BehaviorTools::GetInputParameterValue<int>(behaviour,1); if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) { solid->onSubShapeTransformation(false,true,true,ent,hierarchy); }else{ VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setPosition(pos,ent); } } } return CK_OK; } int BBRestoreIC_New(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; BBRestoreIC(context); int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); int hierarchy=0;behaviour->GetLocalParameterValue(5,&hierarchy); int restoreJoints=0;behaviour->GetLocalParameterValue(6,&restoreJoints); bool done= false; if (pUpdate) { if( !ent ) return CKBR_OWNERERROR; pRigidBody *solid = GetPMan()->getBody(ent); if (solid) { BRESET if (ent && ent->GetClassID() != CKCID_3DOBJECT) { return CK_OK; } /* if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) { solid->onSubShapeTransformation(false,true,true,ent,(solid->getFlags() & BF_Hierarchy )); }else{ VxVector pos,scale; VxQuaternion quat; Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); solid->setPosition(pos,ent); } */ pRigidBodyRestoreInfo *rInfo = new pRigidBodyRestoreInfo(); rInfo->hierarchy = hierarchy; rInfo->removeJoints= restoreJoints; GetPMan()->_getRestoreMap()->Insert(ent->GetID(),rInfo); done = true; } } if (hierarchy && !done) { CKScene *scene = GetPMan()->GetContext()->GetCurrentLevel()->GetLevelScene(); if(scene) { CK3dEntity* subEntity = NULL; XArray<NxShape*>SrcObjects; while (subEntity= ent->HierarchyParser(subEntity) ) { CKStateChunk *chunk = scene->GetObjectInitialValue(subEntity); if (chunk) { CKReadObjectState(subEntity,chunk); } } } } return CK_OK; } int BBLaunchScene_New(const CKBehaviorContext& context) { CKBehavior *behaviour = context.Behavior; CKContext *ctx = context.Context; CKScene *currentScene= GetPMan()->GetContext()->GetCurrentLevel()->GetCurrentScene(); CKScene *nextScene = NULL; BBLaunchScene(context); /* int pUpdate=0; behaviour->GetLocalParameterValue(0,&pUpdate); nextScene = (CKScene*)behaviour->GetInputParameterObject(0); if (pUpdate) { if(GetPMan()->GetContext()->IsPlaying()) { GetPMan()->_removeObjectsFromOldScene(currentScene); GetPMan()->_checkObjectsByAttribute(nextScene); } } */ return CK_OK; } CKERROR PhysicManager::_Hook3DBBs() { CKBehaviorManager *bm = m_Context->GetBehaviorManager(); CKBehaviorPrototype *bproto = CKGetPrototypeFromGuid(BB_SET_EORIENTATION_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBSetEOri = bproto->GetFunction(); bproto->SetFunction(BB_SetEOrientationNew); } bproto = CKGetPrototypeFromGuid(BB_SET_POSITION_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBSetPos = bproto->GetFunction(); bproto->SetFunction(BB_SetPosNew); } bproto = CKGetPrototypeFromGuid(BB_SET_ORIENTATION_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBSetOri = bproto->GetFunction(); bproto->SetFunction(BB_SetOrientationNew); } bproto = CKGetPrototypeFromGuid(BB_ROTATE_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBRotate = bproto->GetFunction(); bproto->SetFunction(BB_RotateNew); } bproto = CKGetPrototypeFromGuid(BB_TRANSLATE_GUID); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBTranslate = bproto->GetFunction(); bproto->SetFunction(BB_TranslateNew); } bproto = CKGetPrototypeFromGuid(BB_PLAY_GLOBAL_ANIMATION); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBPlayGlobalAnimation = bproto->GetFunction(); bproto->SetFunction(BBPlayGlobalAnimation_New); } bproto = CKGetPrototypeFromGuid(BB_SET_LOCAL_MATRIX); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBSetLocalMatrix = bproto->GetFunction(); bproto->SetFunction(BBSetLocalMatrix_New); } bproto = CKGetPrototypeFromGuid(BB_SET_WORLD_MATRIX); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); BBSetWorldMatrix = bproto->GetFunction(); bproto->SetFunction(BBSetWorldMatrix_New); } bproto = CKGetPrototypeFromGuid(BB_RESTORE_IC); if(bproto) { bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Hierarchy",CKPGUID_BOOL,"true"); bproto->DeclareSetting("Restore Joints from Attribute",CKPGUID_BOOL,"true"); BBRestoreIC = bproto->GetFunction(); bproto->SetFunction(BBRestoreIC_New); } bproto = CKGetPrototypeFromGuid(BB_LAUNCH_SCENE); if(bproto) { //bproto->DeclareSetting("Destroy Old Physics",CKPGUID_BOOL,"true"); BBLaunchScene = bproto->GetFunction(); bproto->SetFunction(BBLaunchScene_New); } return CK_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" #include "pVehicleAll.h" PhysicManager*GetPhysicManager(); pRigidBody *getBody(CK3dEntity*ent); CKGUID GetPhysicManagerGUID() { return GUID_MODULE_MANAGER;} typedef ForceMode PForceMode; typedef D6MotionMode PJMotion; typedef D6DriveType PDriveType; pFactory* getPFactory() { return pFactory::Instance(); } void __newpObjectDescr(BYTE *iAdd) { new (iAdd) pObjectDescr(); } void __newpRaycastHit(BYTE *iAdd) { new(iAdd)pRaycastHit(); } void __newpGroupsMask(BYTE *iAdd) { new(iAdd)pGroupsMask(); } void __newpOptimization(BYTE *iAdd) { new(iAdd)pOptimization(); } void __newpMassSettings(BYTE *iAdd) { new(iAdd)pMassSettings(); } void __newpCCD(BYTE *iAdd) { new(iAdd)pCCDSettings(); } void __newpCollisionSettings(BYTE *iAdd) { new(iAdd)pCollisionSettings(); } void __newpPivotSettings(BYTE *iAdd) { new(iAdd)pPivotSettings(); } void __newpMaterial(BYTE *iAdd) { new(iAdd)pMaterial(); } void __newpAxisReferenceLength(BYTE *iAdd) { new(iAdd)pAxisReferencedLength(); } void __newpCapsuleSettingsEx(BYTE *iAdd) { new(iAdd)pCapsuleSettingsEx(); } void __newpConvexCylinder(BYTE *iAdd) { new(iAdd)pConvexCylinderSettings(); } void __newpWheelDescr(BYTE *iAdd) { new (iAdd)pWheelDescr(); } void __newpTireFunction(BYTE *iAdd) { new (iAdd)pTireFunction(); } void __newpInterpolation(BYTE *iAdd) { new (iAdd)pLinearInterpolation(); } CKGUID getRigidBodyParameterType() { return VTS_PHYSIC_ACTOR; } ////////////////////////////////////////////////////////////////////////// #define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) void logWarning(const char*errMessage) { if (!errMessage || !strlen(errMessage)) return; xLogger::xLog(XL_START,ELOGWARNING,E_VSL,errMessage); } void PhysicManager::_RegisterVSLCommon() { STARTVSLBIND(m_Context) //---------------------------------------------------------------- // // manager related // { DECLAREENUM("pSDKParameter") DECLAREENUMVALUE("pSDKParameter", "pSDKP_SkinWidth" ,1 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_DefaultSleepLinVelSquared" ,2 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_DefaultSleepAngVelSquared" ,3 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_BounceThreshold" ,4 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_DynFrictScaling" , 5) DECLAREENUMVALUE("pSDKParameter", "pSDKP_StaFrictionScaling" ,6 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_MaxAngularVelocity" ,7 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_ContinuousCD" ,8 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_AdaptiveForce" ,68 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_CollVetoJointed" ,69 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_TriggerTriggerCallback" ,70 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_SelectHW_Algo" ,71 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_CCDEpsilon" ,73 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_SolverConvergenceThreshold" ,74 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_BBoxNoiseLevel" ,75 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_ImplicitSweepCacheSize" , 76) DECLAREENUMVALUE("pSDKParameter", "pSDKP_DefaultSleepEnergy" ,77 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_ConstantFluidMaxPackets" ,78 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_ConstantFluidMaxParticlesPerStep" ,79 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_AsynchronousMeshCreation" ,96 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_ForceFieldCustomKernelEpsilon" ,97 ) DECLAREENUMVALUE("pSDKParameter", "pSDKP_ImprovedSpringSolver" ,98 ) } REGISTERCONST("FLT_MAX",BIND_FLOAT,FLT_MAX) REGISTERCONST("PTYPE_RIGID_BODY",BIND_FLOAT,FLT_MAX) //---------------------------------------------------------------- // // common types // DECLAREPOINTERTYPE(pFactory) DECLAREFUN_C_0(pFactory,getPFactory) DECLAREFUN_C_0(CKGUID, GetPhysicManagerGUID) DECLAREOBJECTTYPE(PhysicManager) DECLARESTATIC_1(PhysicManager,PhysicManager*,Cast,CKBaseManager* iM) DECLAREFUN_C_0(PhysicManager*, GetPhysicManager) DECLAREPOINTERTYPE(pRigidBody) DECLAREPOINTERTYPE(pPacejka) DECLAREPOINTERTYPEALIAS(pRigidBody,"pBody") DECLAREFUN_C_0(CKGUID,getRigidBodyParameterType) DECLAREFUN_C_1(void,logWarning,const char*) DECLAREPOINTERTYPE(pWorld) DECLAREPOINTERTYPE(pCloth) DECLAREPOINTERTYPE(pVehicle) DECLAREPOINTERTYPE(pWheel) DECLAREPOINTERTYPE(pVehicle) DECLAREPOINTERTYPE(pVehicleMotor) DECLAREPOINTERTYPE(pVehicleGears) DECLAREPOINTERTYPE(pWheel1) DECLAREPOINTERTYPE(pWheel2) //---------------------------------------------------------------- // // new vehicle pack // DECLAREPOINTERTYPE(pEngine) DECLAREPOINTERTYPE(pGearBox) DECLAREPOINTERTYPE(pWheelContactData) DECLAREPOINTERTYPE(pLinearInterpolation) //DECLARECTOR_0(__newpInterpolation) DECLAREINHERITANCESIMPLE("pWheel","pWheel1") DECLAREINHERITANCESIMPLE("pWheel","pWheel2") ////////////////////////////////////////////////////////////////////////// // // Joints : // DECLAREPOINTERTYPE(pJoint) DECLAREPOINTERTYPE(pJointFixed) DECLAREPOINTERTYPE(pJointDistance) DECLAREPOINTERTYPE(pJointD6) DECLAREPOINTERTYPE(pJointPulley) DECLAREPOINTERTYPE(pJointBall) DECLAREPOINTERTYPE(pJointRevolute) DECLAREPOINTERTYPE(pJointPrismatic) DECLAREPOINTERTYPE(pJointCylindrical) DECLAREPOINTERTYPE(pJointPointInPlane) DECLAREPOINTERTYPE(pJointPointOnLine) DECLAREINHERITANCESIMPLE("pJoint","pJointDistance") DECLAREINHERITANCESIMPLE("pJoint","pJointD6") DECLAREINHERITANCESIMPLE("pJoint","pJointFixed") DECLAREINHERITANCESIMPLE("pJoint","pJointPulley") DECLAREINHERITANCESIMPLE("pJoint","pJointBall") DECLAREINHERITANCESIMPLE("pJoint","pJointRevolute") DECLAREINHERITANCESIMPLE("pJoint","pJointPrismatic") DECLAREINHERITANCESIMPLE("pJoint","pJointCylindrical") DECLAREINHERITANCESIMPLE("pJoint","pJointPointOnLine") DECLAREINHERITANCESIMPLE("pJoint","pJointPointInPlane") //---------------------------------------------------------------- // // help structures collision // DECLAREOBJECTTYPE(pGroupsMask) DECLARECTOR_0(__newpGroupsMask) DECLAREMEMBER(pGroupsMask,int,bits0) DECLAREMEMBER(pGroupsMask,int,bits1) DECLAREMEMBER(pGroupsMask,int,bits2) DECLAREMEMBER(pGroupsMask,int,bits3) DECLAREOBJECTTYPE(pCollisionSettings) DECLARECTOR_0(__newpCollisionSettings) DECLAREMEMBER(pCollisionSettings,int,collisionGroup) DECLAREMEMBER(pCollisionSettings,pGroupsMask,groupsMask) DECLAREMEMBER(pCollisionSettings,float,skinWidth) DECLAREOBJECTTYPE(pRaycastHit) DECLARECTOR_0(__newpRaycastHit) DECLAREMEMBER(pRaycastHit,float,distance) DECLAREMEMBER(pRaycastHit,CK3dEntity*,shape) DECLAREMEMBER(pRaycastHit,VxVector,worldImpact) DECLAREMEMBER(pRaycastHit,VxVector,worldNormal) DECLAREMEMBER(pRaycastHit,int,faceID) DECLAREMEMBER(pRaycastHit,int,internalFaceID) DECLAREMEMBER(pRaycastHit,float,u) DECLAREMEMBER(pRaycastHit,float,v) DECLAREMEMBER(pRaycastHit,int,materialIndex) DECLAREMEMBER(pRaycastHit,int,flags) DECLAREENUM("pFilterOp") DECLAREENUMVALUE("pFilterOp", "FO_And" , 0) DECLAREENUMVALUE("pFilterOp", "FO_Or" , 1) DECLAREENUMVALUE("pFilterOp", "FO_Xor" ,2) DECLAREENUMVALUE("pFilterOp", "FO_Nand",3 ) DECLAREENUMVALUE("pFilterOp", "FO_Nor" , 4) DECLAREENUMVALUE("pFilterOp", "FO_NXor" ,5 ) DECLAREENUM("pShapesType") DECLAREENUMVALUE("pShapesType", "ST_Static" , 1) DECLAREENUMVALUE("pShapesType", "ST_Dynamic" , 2) DECLAREENUMVALUE("pShapesType", "ST_All" , 3) DECLAREENUM("pTriggerFlags") DECLAREENUMVALUE("pTriggerFlags", "TF_Disable" , 8) DECLAREENUMVALUE("pTriggerFlags", "TF_OnEnter" , 1) DECLAREENUMVALUE("pTriggerFlags", "TF_OnLeave" , 2) DECLAREENUMVALUE("pTriggerFlags", "TF_OnStay" , 4) DECLAREENUM("pContactModifyMask") DECLAREENUMVALUE("pContactModifyMask", "CMM_None" , 0) DECLAREENUMVALUE("pContactModifyMask", "CMM_MinImpulse" , 1) DECLAREENUMVALUE("pContactModifyMask", "CMM_MaxImpulse" , 2) DECLAREENUMVALUE("pContactModifyMask", "CMM_Error" , 4) DECLAREENUMVALUE("pContactModifyMask", "CMM_Target" , 8) DECLAREENUMVALUE("pContactModifyMask", "CMM_LocalPosition0" , 16) DECLAREENUMVALUE("pContactModifyMask", "CMM_LocalPosition1" , 32) DECLAREENUMVALUE("pContactModifyMask", "CMM_LocalOrientation0" , 64) DECLAREENUMVALUE("pContactModifyMask", "CMM_LocalOrientation1" , 128) DECLAREENUMVALUE("pContactModifyMask", "CMM_StaticFriction0" , 256) DECLAREENUMVALUE("pContactModifyMask", "CMM_StaticFriction1" , 512) DECLAREENUMVALUE("pContactModifyMask", "CMM_DynamicFriction0" , 1024) DECLAREENUMVALUE("pContactModifyMask", "CMM_DynamicFriction1" , 2048) DECLAREENUMVALUE("pContactModifyMask", "CMM_Restitution" , 8196) DECLAREENUMVALUE("pContactModifyMask", "CMM_Force32" ,2147483648 ) DECLAREENUM("pCollisionEventMask") DECLAREENUMVALUE("pCollisionEventMask", "CPF_IgnorePair" , 1) DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnStartTouch" , 2) DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnEndTouch" , 4) DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnTouch" , 8) DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnImpact" , 16) DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnRoll" , 32) DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnSlide" , 64) DECLAREENUMVALUE("pCollisionEventMask", "CPF_Forces" , 128) DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnStartTouchForceThreshold" , 256) DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnEndTouchForceThreshold" , 512) DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnTouchForceThreshold" , 1024) DECLAREENUMVALUE("pCollisionEventMask", "CPF_ContactModification" , 65536) //---------------------------------------------------------------- // // help structures Rigid body // DECLAREENUM("BodyFlags") DECLAREENUMVALUE("BodyFlags", "BF_Moving" , 1) DECLAREENUMVALUE("BodyFlags", "BF_Gravity" , 2) DECLAREENUMVALUE("BodyFlags", "BF_Collision" , 4) DECLAREENUMVALUE("BodyFlags", "BF_Kinematic" , 8) DECLAREENUMVALUE("BodyFlags", "BF_SubShape" , 16) DECLAREENUMVALUE("BodyFlags", "BF_Hierarchy" , 32) DECLAREENUMVALUE("BodyFlags", "BF_Attributes" , 64) DECLAREENUMVALUE("BodyFlags", "BF_TriggerShape" , 128) DECLAREENUMVALUE("BodyFlags", "BF_Sleep" , 4096) DECLAREENUMVALUE("BodyFlags", "BF_CollisionNotify" , 512) DECLAREENUMVALUE("BodyFlags", "BF_CollisionsForce" , 1024) DECLAREENUMVALUE("BodyFlags", "BF_ContactModify" , 2048) DECLAREENUM("BodyLockFlags") DECLAREENUMVALUE("BodyLockFlags", "BF_LPX" , 2) DECLAREENUMVALUE("BodyLockFlags", "BF_LPY" , 4) DECLAREENUMVALUE("BodyLockFlags", "BF_LPZ" , 8) DECLAREENUMVALUE("BodyLockFlags", "BF_LRX" , 16) DECLAREENUMVALUE("BodyLockFlags", "BF_LRY" , 32) DECLAREENUMVALUE("BodyLockFlags", "BF_LRZ" , 64) DECLAREENUM("HullType") DECLAREENUMVALUE("HullType", "HT_Sphere" , 0) DECLAREENUMVALUE("HullType", "HT_Box" , 1) DECLAREENUMVALUE("HullType", "HT_Capsule" , 2) DECLAREENUMVALUE("HullType", "HT_Plane" , 3) DECLAREENUMVALUE("HullType", "HT_Mesh" , 4) DECLAREENUMVALUE("HullType", "HT_ConvexMesh" , 5) DECLAREENUMVALUE("HullType", "HT_HeightField" , 6) DECLAREENUMVALUE("HullType", "HT_Wheel" , 7) DECLAREENUMVALUE("HullType", "HT_ConvexCylinder" , 9) DECLAREENUM("CombineMode") DECLAREENUMVALUE("CombineMode", "CM_Average" , 0) DECLAREENUMVALUE("CombineMode", "CM_Min" , 1) DECLAREENUMVALUE("CombineMode", "CM_Multiply" , 2) DECLAREENUMVALUE("CombineMode", "CM_Max" , 3) DECLAREENUM("pObjectDescrMask") DECLAREENUMVALUE("pObjectDescrMask", "OD_XML" , 1) DECLAREENUMVALUE("pObjectDescrMask", "OD_Pivot" , 2) DECLAREENUMVALUE("pObjectDescrMask", "OD_Mass" , 4) DECLAREENUMVALUE("pObjectDescrMask", "OD_Collision" , 8) DECLAREENUMVALUE("pObjectDescrMask", "OD_CCD" , 16) DECLAREENUMVALUE("pObjectDescrMask", "OD_Material" , 32) DECLAREENUMVALUE("pObjectDescrMask", "OD_Optimization" , 64) DECLAREENUMVALUE("pObjectDescrMask", "OD_Capsule" , 128) DECLAREENUMVALUE("pObjectDescrMask", "OD_ConvexCylinder" , 256) DECLAREENUMVALUE("pObjectDescrMask", "OD_Wheel" , 512) DECLAREENUM("DIRECTION") DECLAREENUMVALUE("DIRECTION", "DIR_X" , 0) DECLAREENUMVALUE("DIRECTION", "DIR_Y" , 1) DECLAREENUMVALUE("DIRECTION", "DIR_Z" , 2) //---------------------------------------------------------------- // // Wheel related types // DECLAREOBJECTTYPE(pTireFunction) DECLARECTOR_0(__newpTireFunction) DECLAREMEMBER(pTireFunction,float,extremumSlip) DECLAREMEMBER(pTireFunction,float,extremumValue) DECLAREMEMBER(pTireFunction,float,asymptoteSlip) DECLAREMEMBER(pTireFunction,float,stiffnessFactor) DECLAREMEMBER(pTireFunction,int,xmlLink) DECLAREMETHOD_0(pTireFunction,void,setToDefault) DECLAREENUM("WheelFlags") DECLAREENUMVALUE("WheelFlags", "WF_SteerableInput" , 1) DECLAREENUMVALUE("WheelFlags", "WF_SteerableAuto" , 2) DECLAREENUMVALUE("WheelFlags", "WF_AffectedByHandbrake" , 4) DECLAREENUMVALUE("WheelFlags", "WF_Accelerated" , 8) DECLAREENUMVALUE("WheelFlags", "WF_BuildLowerHalf" , 256) DECLAREENUMVALUE("WheelFlags", "WF_UseWheelShape" , 512) DECLAREENUMVALUE("WheelFlags", "WF_VehicleControlled" , 1024) DECLAREENUM("WheelShapeFlags") DECLAREENUMVALUE("WheelShapeFlags", "WSF_WheelAxisContactNormal" , 1) DECLAREENUMVALUE("WheelShapeFlags", "WSF_InputLatSlipVelocity" , 1) DECLAREENUMVALUE("WheelShapeFlags", "WSF_InputLongSlipVelocity" , 2) DECLAREENUMVALUE("WheelShapeFlags", "WSF_UnscaledSpringBehavior" , 4) DECLAREENUMVALUE("WheelShapeFlags", "WSF_EmulateLegacyWheel" , 8) DECLAREENUMVALUE("WheelShapeFlags", "WSF_ClampedFriction" , 16) DECLAREENUM("pConvexFlags") DECLAREENUMVALUE("pConvexFlags", "CF_FlipNormals" , CF_FlipNormals) DECLAREENUMVALUE("pConvexFlags", "CF_16BitIndices" , CF_16BitIndices) DECLAREENUMVALUE("pConvexFlags", "CF_ComputeConvex" , CF_ComputeConvex) DECLAREENUMVALUE("pConvexFlags", "CF_InflateConvex" , CF_InflateConvex) DECLAREENUMVALUE("pConvexFlags", "CF_UncompressedNormals" , CF_UncompressedNormals) DECLAREOBJECTTYPE(pAxisReferencedLength) DECLARECTOR_0(__newpAxisReferenceLength) DECLAREMEMBER(pAxisReferencedLength,float,value) DECLAREMEMBER(pAxisReferencedLength,CKBeObject*,reference) DECLAREMEMBER(pAxisReferencedLength,int,referenceAxis) DECLAREMETHOD_0(pAxisReferencedLength,bool,isValid) DECLAREMETHOD_0(pAxisReferencedLength,void,setToDefault) DECLAREOBJECTTYPE(pWheelDescr) DECLARECTOR_0(__newpWheelDescr) DECLAREMEMBER(pWheelDescr,float,springRestitution) DECLAREMEMBER(pWheelDescr,pAxisReferencedLength,radius) DECLAREMEMBER(pWheelDescr,float,wheelSuspension) DECLAREMEMBER(pWheelDescr,float,springDamping) DECLAREMEMBER(pWheelDescr,float,springDamping) DECLAREMEMBER(pWheelDescr,float,maxBrakeForce) DECLAREMEMBER(pWheelDescr,float,frictionToFront) DECLAREMEMBER(pWheelDescr,float,frictionToSide) DECLAREMEMBER(pWheelDescr,float,inverseWheelMass) DECLAREMEMBER(pWheelDescr,WheelFlags,wheelFlags) DECLAREMEMBER(pWheelDescr,WheelShapeFlags,wheelShapeFlags) DECLAREMEMBER(pWheelDescr,pTireFunction,latFunc) DECLAREMEMBER(pWheelDescr,pTireFunction,longFunc) DECLAREMETHOD_0(pWheelDescr,void,setToDefault) DECLAREMETHOD_0(pWheelDescr,bool,isValid) DECLAREOBJECTTYPE(pConvexCylinderSettings) DECLARECTOR_0(__newpCollisionSettings) DECLAREMEMBER(pConvexCylinderSettings,pAxisReferencedLength,radius) DECLAREMEMBER(pConvexCylinderSettings,pAxisReferencedLength,height) DECLAREMEMBER(pConvexCylinderSettings,int,approximation) DECLAREMEMBER(pConvexCylinderSettings,VxVector,forwardAxis) DECLAREMEMBER(pConvexCylinderSettings,CK3dEntity*,forwardAxisRef) DECLAREMEMBER(pConvexCylinderSettings,VxVector,downAxis) DECLAREMEMBER(pConvexCylinderSettings,CK3dEntity*,downAxisRef) DECLAREMEMBER(pConvexCylinderSettings,VxVector,rightAxis) DECLAREMEMBER(pConvexCylinderSettings,CK3dEntity*,rightAxisRef) DECLAREMEMBER(pConvexCylinderSettings,bool,buildLowerHalfOnly) DECLAREMEMBER(pConvexCylinderSettings,pConvexFlags,convexFlags) DECLAREMETHOD_0(pConvexCylinderSettings,bool,isValid) DECLAREMETHOD_0(pConvexCylinderSettings,void,setToDefault) DECLAREOBJECTTYPE(pCapsuleSettingsEx) DECLARECTOR_0(__newpCapsuleSettingsEx) DECLAREMEMBER(pCapsuleSettingsEx,pAxisReferencedLength,radius) DECLAREMEMBER(pCapsuleSettingsEx,pAxisReferencedLength,height) DECLAREOBJECTTYPE(pMaterial) DECLARECTOR_0(__newpMaterial) DECLAREMEMBER(pMaterial,int,flags) DECLAREMEMBER(pMaterial,float,dynamicFriction) DECLAREMEMBER(pMaterial,float,staticFriction) DECLAREMEMBER(pMaterial,float,restitution) DECLAREMEMBER(pMaterial,float,dynamicFrictionV) DECLAREMEMBER(pMaterial,float,staticFrictionV) DECLAREMEMBER(pMaterial,CombineMode,frictionCombineMode) DECLAREMEMBER(pMaterial,CombineMode,restitutionCombineMode) DECLAREMEMBER(pMaterial,VxVector,dirOfAnisotropy) DECLAREMEMBER(pMaterial,int,xmlLinkID) DECLAREOBJECTTYPE(pOptimization) DECLARECTOR_0(__newpOptimization) DECLAREMEMBER(pOptimization,BodyLockFlags,transformationFlags) DECLAREMEMBER(pOptimization,float,linDamping) DECLAREMEMBER(pOptimization,float,angDamping) DECLAREMEMBER(pOptimization,float,linSleepVelocity) DECLAREMEMBER(pOptimization,float,angSleepVelocity) DECLAREMEMBER(pOptimization,float,sleepEnergyThreshold) DECLAREMEMBER(pOptimization,int,dominanceGroup) DECLAREMEMBER(pOptimization,int,solverIterations) DECLAREMEMBER(pOptimization,int,compartmentGroup) DECLAREOBJECTTYPE(pMassSettings) DECLARECTOR_0(__newpMassSettings) DECLAREMEMBER(pMassSettings,float,newDensity) DECLAREMEMBER(pMassSettings,float,totalMass) DECLAREMEMBER(pMassSettings,VxVector,localPosition) DECLAREMEMBER(pMassSettings,VxVector,localOrientation) DECLAREMEMBER(pMassSettings,CK_ID,massReference) DECLAREOBJECTTYPE(pPivotSettings) DECLARECTOR_0(__newpPivotSettings) DECLAREMEMBER(pPivotSettings,VxVector,localPosition) DECLAREMEMBER(pPivotSettings,VxVector,localOrientation) DECLAREMEMBER(pPivotSettings,CK_ID,pivotReference) DECLAREOBJECTTYPE(pCCDSettings) DECLARECTOR_0(__newpCCD) DECLAREMEMBER(pCCDSettings,float,motionThresold) DECLAREMEMBER(pCCDSettings,int,flags) DECLAREMEMBER(pCCDSettings,CK_ID,meshReference) DECLAREMEMBER(pCCDSettings,float,scale) DECLAREOBJECTTYPE(pObjectDescr) DECLARECTOR_0(__newpObjectDescr) DECLAREMEMBER(pObjectDescr,HullType,hullType) DECLAREMEMBER(pObjectDescr,float,density) DECLAREMEMBER(pObjectDescr,BodyFlags,flags) DECLAREMEMBER(pObjectDescr,VxVector,massOffset) DECLAREMEMBER(pObjectDescr,VxVector,shapeOffset) DECLAREMEMBER(pObjectDescr,float,skinWidth) DECLAREMEMBER(pObjectDescr,float,newDensity) DECLAREMEMBER(pObjectDescr,float,totalMass) DECLAREMEMBER(pObjectDescr,int,collisionGroup) DECLAREMEMBER(pObjectDescr,int,hirarchy) DECLAREMEMBER(pObjectDescr,int,mask) DECLAREMEMBER(pObjectDescr,pCollisionSettings,collision) DECLAREMETHOD_0(pObjectDescr,pCollisionSettings&,getCollision) DECLAREMETHOD_1(pObjectDescr,void,setCollision,pCollisionSettings) DECLAREMEMBER(pObjectDescr,pMaterial,material) DECLAREMETHOD_0(pObjectDescr,pMaterial&,getMaterial) DECLAREMETHOD_1(pObjectDescr,void,setMaterial,pMaterial) DECLAREMEMBER(pObjectDescr,pMassSettings,mass) DECLAREMETHOD_0(pObjectDescr,pMassSettings&,getMass) DECLAREMETHOD_1(pObjectDescr,void,setMass,pMassSettings) DECLAREMEMBER(pObjectDescr,pCCDSettings,ccd) DECLAREMETHOD_0(pObjectDescr,pCCDSettings&,getCollision) DECLAREMETHOD_1(pObjectDescr,void,setCollision,pCCDSettings) DECLAREMEMBER(pObjectDescr,pOptimization,optimization) DECLAREMETHOD_0(pObjectDescr,pOptimization&,getOptimization) DECLAREMETHOD_1(pObjectDescr,void,setOptimization,pOptimization) DECLAREMEMBER(pObjectDescr,pPivotSettings,pivot) DECLAREMETHOD_0(pObjectDescr,pPivotSettings&,getPivot) DECLAREMETHOD_1(pObjectDescr,void,setPivot,pPivotSettings) DECLAREMEMBER(pObjectDescr,pCapsuleSettingsEx,capsule) DECLAREMETHOD_0(pObjectDescr,pCapsuleSettingsEx&,getCapsule) DECLAREMETHOD_1(pObjectDescr,void,setCapsule,pCapsuleSettingsEx) DECLAREMEMBER(pObjectDescr,pConvexCylinderSettings,convexCylinder) DECLAREMETHOD_0(pObjectDescr,pConvexCylinderSettings&,getConvexCylinder) DECLAREMETHOD_1(pObjectDescr,void,setConvexCylinder,pConvexCylinderSettings) DECLAREMETHOD_1(CK3dEntity,CKParameterOut*,GetAttributeParameter,int) //#define REGISTERVSLGUID(iGUID, iClassName) VSLM->RegisterGUID(iGUID, iClassName); STOPVSLBIND } PhysicManager*GetPhysicManager() { return GetPMan(); } <file_sep>/****************************************************************************** Copyright (C) 1999, 2000 NVIDIA Corporation This file is provided without support, instruction, or implied warranty of any kind. NVIDIA makes no guarantee of its fitness for a particular purpose and is not liable under any circumstances for any damages or loss whatsoever arising from the use or inability to use this file or items derived from it. Comments: ******************************************************************************/ #ifndef __NVFILE_H #define __NVFILE_H //#include "NVDX8Macros.h" #include "nvmesh.h" #include "nvframe.h" #include <D3DX9.h> #include <TCHAR.H> typedef std::basic_string<TCHAR> tstring; class NVFile : public NVFrame { HRESULT LoadMesh( IDirect3DDevice9* pDevice, LPD3DXFILEDATA pFileData, NVFrame* pParentFrame ); HRESULT LoadFrame( IDirect3DDevice9* pDevice, LPD3DXFILEDATA pFileData, NVFrame* pParentFrame ); public: void GetBoundingInfo(NVBounds* pBounds); HRESULT Create( IDirect3DDevice9* pDevice, const tstring& strFilename ); HRESULT Render( IDirect3DDevice9* pDevice ); NVFile() : NVFrame( _T("NVFile_Root") ) {} tstring m_strFilePath; }; #endif <file_sep>#include "CKAll.h" #define SNDINTERNAL /***************************************************************************** * * pSeq CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR * A PARTICULAR PURPOSE. * * Copyright (C) 1993 - 1996 Microsoft Corporation. All Rights Reserved. * ****************************************************************************** * *MidiSound::uence.C * *MidiSound::uencer engine for MIDI player app * *****************************************************************************/ #include <windows.h> #include <windowsx.h> #include <mmsystem.h> #include <limits.h> #include "MidiSound.h" static void FAR PASCAL seqMIDICallback(HMIDISTRM hms, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2); static MMRESULT XlatSMFErr(SMFRESULT smfrc); extern CRITICAL_SECTION gMidiCS; // Fichier de son associe MMRESULT MidiSound::SetSoundFileName(const char * name) { if (name==NULL) { return MCIERR_INVALID_FILE; } pSeq->pstrFile=CKStrdup((char *)name); return OpenFile(); } const char* MidiSound::GetSoundFileName() { return pSeq->pstrFile; } BOOL MidiSound::IsPlaying() { return (pSeq->uState==SEQ_S_PLAYING); } BOOL MidiSound::IsPaused() { return (pSeq->uState==SEQ_S_PAUSED); } /*************************************************************************** * *MidiSound::AllocBuffers * * Allocate buffers for pSeq instance. * * pSeq - TheMidiSound::uencer instance to allocate buffers for. * * Returns * MMSYSERR_NOERROR If the operation was successful. * * MCIERR_OUT_OF_MEMORY If there is insufficient memory for * the requested number and size of buffers. * *MidiSound::AllocBuffers allocates playback buffers based on the * cbBuffer and cBuffer fields of pSeq. cbBuffer specifies the * number of bytes in each buffer, and cBuffer specifies the * number of buffers to allocate. * *MidiSound::AllocBuffers must be called before any otherMidiSound::uencer call * on a newly alloctedMidiSound::UENCE structure. It must be paired with * a call toMidiSound::FreeBuffers, which should be the last call made * before theMidiSound::UENCE structure is discarded. * ***************************************************************************/ MMRESULT MidiSound::AllocBuffers() { DWORD dwEachBufferSize; DWORD dwAlloc; UINT i; LPBYTE lpbWork; //assert(pSeq != NULL); pSeq->uState =SEQ_S_NOFILE; pSeq->lpmhFree = NULL; pSeq->lpbAlloc = NULL; pSeq->hSmf = (HSMF)NULL; /* First make sure we can allocate the buffers they asked for */ dwEachBufferSize = sizeof(MIDIHDR) + (DWORD)(pSeq->cbBuffer); dwAlloc = dwEachBufferSize * (DWORD)(pSeq->cBuffer); pSeq->lpbAlloc = (unsigned char*) GlobalAllocPtr(GMEM_MOVEABLE|GMEM_SHARE, dwAlloc); if (NULL == pSeq->lpbAlloc) return MCIERR_OUT_OF_MEMORY; /* Initialize all MIDIHDR's and throw them into a free list */ pSeq->lpmhFree = NULL; lpbWork = pSeq->lpbAlloc; for (i=0; i < pSeq->cBuffer; i++) { ((LPMIDIHDR)lpbWork)->lpNext = pSeq->lpmhFree; ((LPMIDIHDR)lpbWork)->lpData = (char*)lpbWork + sizeof(MIDIHDR); ((LPMIDIHDR)lpbWork)->dwBufferLength = pSeq->cbBuffer; ((LPMIDIHDR)lpbWork)->dwBytesRecorded = 0; ((LPMIDIHDR)lpbWork)->dwUser = (DWORD)(UINT)pSeq; ((LPMIDIHDR)lpbWork)->dwFlags = 0; pSeq->lpmhFree = (LPMIDIHDR)lpbWork; lpbWork += dwEachBufferSize; } return MMSYSERR_NOERROR; } /*************************************************************************** * *MidiSound::FreeBuffers * * Free buffers for pSeq instance. * * pSeq - TheMidiSound::uencer instance to free buffers for. * *MidiSound::FreeBuffers frees all allocated memory belonging to the * givenMidiSound::uencer instance pSeq. It must be the last call * performed on the instance before it is destroyed. * ****************************************************************************/ VOID MidiSound::FreeBuffers() { LPMIDIHDR lpmh; //assert(pSeq != NULL); if (NULL != pSeq->lpbAlloc) { lpmh = (LPMIDIHDR)pSeq->lpbAlloc; //assert(!(lpmh->dwFlags & MHDR_PREPARED)); GlobalFreePtr(pSeq->lpbAlloc); } } /*************************************************************************** * *MidiSound::OpenFile * * Associates a MIDI file with the givenMidiSound::uencer instance. * * pSeq - TheMidiSound::uencer instance. * * Returns * MMSYSERR_NOERROR If the operation is successful. * * MCIERR_UNSUPPORTED_FUNCTION If there is already a file open * on pSeq instance. * * MCIERR_OUT_OF_MEMORY If there was insufficient memory to * allocate internal buffers on the file. * * MCIERR_INVALID_FILE If initial attempts to parse the file * failed (such as the file is not a MIDI or RMI file). * *MidiSound::OpenFile may only be called if there is no currently open file * on the instance. It must be paired with a call toMidiSound::CloseFile * when operations on pSeq file are complete. * * The pstrFile field of pSeq contains the name of the file * to open. pSeq name will be passed directly to mmioOpen; it may * contain a specifcation for a custom MMIO file handler. The task * context used for all I/O will be the task which callsMidiSound::OpenFile. * ***************************************************************************/ MMRESULT MidiSound::OpenFile() { MMRESULT rc = MMSYSERR_NOERROR; SMFOPENFILESTRUCT sofs; SMFFILEINFO sfi; SMFRESULT smfrc; DWORD cbBuffer; //assert(pSeq != NULL); if (pSeq->uState !=SEQ_S_NOFILE) { return MCIERR_UNSUPPORTED_FUNCTION; } //assert(pSeq->pstrFile != NULL); sofs.pstrName = pSeq->pstrFile; smfrc = smfOpenFile(&sofs); if (SMF_SUCCESS != smfrc) { rc = XlatSMFErr(smfrc); goto Seq_Open_File_Cleanup; } pSeq->hSmf = sofs.hSmf; smfGetFileInfo(pSeq->hSmf, &sfi); pSeq->dwTimeDivision = sfi.dwTimeDivision; pSeq->tkLength = sfi.tkLength; pSeq->cTrk = sfi.dwTracks; /* Track buffers must be big enough to hold the state data returned ** by smfSeek() */ cbBuffer = __min(pSeq->cbBuffer, smfGetStateMaxSize()); Seq_Open_File_Cleanup: if (MMSYSERR_NOERROR != rc) CloseFile(); else pSeq->uState =SEQ_S_OPENED; return rc; } /*************************************************************************** * *MidiSound::CloseFile * * Deassociates a MIDI file with the givenMidiSound::uencer instance. * * pSeq - TheMidiSound::uencer instance. * * Returns * MMSYSERR_NOERROR If the operation is successful. * * MCIERR_UNSUPPORTED_FUNCTION If theMidiSound::uencer instance is not * stopped. * * A call toMidiSound::CloseFile must be paired with a prior call to *MidiSound::OpenFile. All buffers associated with the file will be * freed and the file will be closed. TheMidiSound::uencer must be * stopped before pSeq call will be accepted. * ***************************************************************************/ MMRESULT MidiSound::CloseFile() { LPMIDIHDR lpmh; //assert(pSeq != NULL); if (SEQ_S_OPENED != pSeq->uState) return MCIERR_UNSUPPORTED_FUNCTION; if ((HSMF)NULL != pSeq->hSmf) { smfCloseFile(pSeq->hSmf); pSeq->hSmf = (HSMF)NULL; } /* If we were prerolled, need to clean up -- have an open MIDI handle ** and buffers in the ready queue */ //EnterCriticalSection(&gMidiCS); for (lpmh = pSeq->lpmhFree; lpmh; lpmh = lpmh->lpNext) midiOutUnprepareHeader(pSeq->hmidi, lpmh, sizeof(*lpmh)); if (pSeq->lpmhPreroll) { midiOutUnprepareHeader(pSeq->hmidi, pSeq->lpmhPreroll, sizeof(*pSeq->lpmhPreroll)); (void) GlobalFreePtr(pSeq->lpmhPreroll); } if (pSeq->hmidi != NULL) { // cast by aymeric //EnterCriticalSection(&gMidiCS); midiStreamClose((HMIDISTRM)pSeq->hmidi); pSeq->hmidi = NULL; //LeaveCriticalSection(&gMidiCS); } pSeq->uState =SEQ_S_NOFILE; //LeaveCriticalSection(&gMidiCS); return MMSYSERR_NOERROR; } /*************************************************************************** * *MidiSound::Preroll * * Prepares the file for playback at the given position. * * pSeq - TheMidiSound::uencer instance. * * lpPreroll - Specifies the starting and ending tick * positions to play between. * * Returns * MMSYSERR_NOERROR If the operation is successful. * * MCIERR_UNSUPPORTED_FUNCTION If theMidiSound::uencer instance is not * opened or prerolled. * * Open the device so we can initialize channels. * * Loop through the tracks. For each track, seek to the given position and * send the init data SMF gives us to the handle. * * Wait for all init buffers to finish. * * Unprepare the buffers (they're only ever sent here; theMidiSound::uencer * engine merges them into a single stream during normal playback) and * refill them with the first chunk of data from the track. * * ****************************************************************************/ MMRESULT MidiSound::Preroll() { pSeq->tkBase=0; pSeq->tkEnd=pSeq->tkLength; struct tag_preroll prerroll={0,pSeq->tkLength}; LPPREROLL lpPreroll=&prerroll; SMFRESULT smfrc; MMRESULT mmrc = MMSYSERR_NOERROR; MIDIPROPTIMEDIV mptd; LPMIDIHDR lpmh = NULL; LPMIDIHDR lpmhPreroll = NULL; DWORD cbPrerollBuffer; UINT uDeviceID=MIDI_MAPPER ; //assert(pSeq != NULL); pSeq->mmrcLastErr = MMSYSERR_NOERROR; if (pSeq->uState !=SEQ_S_OPENED && pSeq->uState !=SEQ_S_PREROLLED) return MCIERR_UNSUPPORTED_FUNCTION; pSeq->tkBase = lpPreroll->tkBase; pSeq->tkEnd = lpPreroll->tkEnd; if (pSeq->hmidi) { // Recollect buffers from MMSYSTEM back into free queue // //EnterCriticalSection(&gMidiCS); pSeq->uState =SEQ_S_RESET; midiOutReset(pSeq->hmidi); //LeaveCriticalSection(&gMidiCS); while (pSeq->uBuffersInMMSYSTEM) Sleep(0); } pSeq->uBuffersInMMSYSTEM = 0; pSeq->uState =SEQ_S_PREROLLING; // // We've successfully opened the file and all of the tracks; now // open the MIDI device and set the time division. // // NOTE:MidiSound::Preroll is equivalent to seek; device might already be open // if (NULL == pSeq->hmidi) { uDeviceID = pSeq->uDeviceID; uDeviceID = MIDI_MAPPER; // cast by aymeric if ((mmrc = midiStreamOpen((LPHMIDISTRM)&pSeq->hmidi, &uDeviceID, 1, (DWORD)seqMIDICallback, 0, CALLBACK_FUNCTION)) != MMSYSERR_NOERROR) { pSeq->hmidi = NULL; goto Preroll_Cleanup; } mptd.cbStruct = sizeof(mptd); mptd.dwTimeDiv = pSeq->dwTimeDivision; // cast by aymeric if ((mmrc = midiStreamProperty( (HMIDISTRM)pSeq->hmidi, (LPBYTE)&mptd, MIDIPROP_SET|MIDIPROP_TIMEDIV)) != MMSYSERR_NOERROR) { //DPF(1, "midiStreamProperty() -> %04X", (WORD)mmrc); //EnterCriticalSection(&gMidiCS); midiStreamClose((HMIDISTRM)pSeq->hmidi); pSeq->hmidi = NULL; mmrc = MCIERR_DEVICE_NOT_READY; //LeaveCriticalSection(&gMidiCS); goto Preroll_Cleanup; } } mmrc = MMSYSERR_NOERROR; // // Allocate a preroll buffer. Then if we don't have enough room for // all the preroll info, we make the buffer larger. // if (!pSeq->lpmhPreroll) { cbPrerollBuffer = 4096; lpmhPreroll = (LPMIDIHDR)GlobalAllocPtr(GMEM_MOVEABLE|GMEM_SHARE, cbPrerollBuffer); } else { cbPrerollBuffer = pSeq->cbPreroll; lpmhPreroll = pSeq->lpmhPreroll; } lpmhPreroll->lpNext = pSeq->lpmhFree; lpmhPreroll->lpData = (char*)lpmhPreroll + sizeof(MIDIHDR); lpmhPreroll->dwBufferLength = cbPrerollBuffer - sizeof(MIDIHDR); lpmhPreroll->dwBytesRecorded = 0; lpmhPreroll->dwUser = (DWORD)(UINT)pSeq; lpmhPreroll->dwFlags = 0; do { smfrc = smfSeek(pSeq->hSmf, pSeq->tkBase, lpmhPreroll); if( SMF_SUCCESS != smfrc ) { if( ( SMF_NO_MEMORY != smfrc ) || ( cbPrerollBuffer >= 32768L ) ) { //DPF(1, "smfSeek() returned %lu", (DWORD)smfrc); GlobalFreePtr(lpmhPreroll); pSeq->lpmhPreroll = NULL; mmrc = XlatSMFErr(smfrc); goto Preroll_Cleanup; } else // Try to grow buffer. { cbPrerollBuffer *= 2; lpmh = (LPMIDIHDR)GlobalReAllocPtr( lpmhPreroll, cbPrerollBuffer, 0 ); if( NULL == lpmh ) { //DPF(2,"seqPreroll - realloc failed, aborting preroll."); mmrc = MCIERR_OUT_OF_MEMORY; goto Preroll_Cleanup; } lpmhPreroll = lpmh; lpmhPreroll->lpData = (char*)lpmhPreroll + sizeof(MIDIHDR); lpmhPreroll->dwBufferLength = cbPrerollBuffer - sizeof(MIDIHDR); pSeq->lpmhPreroll = lpmhPreroll; pSeq->cbPreroll = cbPrerollBuffer; } } } while( SMF_SUCCESS != smfrc ); if (!pSeq->lpmhPreroll) { //to keep access to buffer and free memory before closing pSeq->lpmhPreroll = lpmhPreroll; pSeq->cbPreroll = cbPrerollBuffer; } if (MMSYSERR_NOERROR != (mmrc = midiOutPrepareHeader(pSeq->hmidi, lpmhPreroll, sizeof(MIDIHDR)))) { //DPF(1, "midiOutPrepare(preroll) -> %lu!", (DWORD)mmrc); mmrc = MCIERR_DEVICE_NOT_READY; goto Preroll_Cleanup; } ++pSeq->uBuffersInMMSYSTEM; if (MMSYSERR_NOERROR != (mmrc = midiStreamOut((HMIDISTRM)pSeq->hmidi, lpmhPreroll, sizeof(MIDIHDR)))) { //DPF(1, "midiStreamOut(preroll) -> %lu!", (DWORD)mmrc); mmrc = MCIERR_DEVICE_NOT_READY; --pSeq->uBuffersInMMSYSTEM; goto Preroll_Cleanup; } //DPF(3,"seqPreroll: midiStreamOut(0x%x,0x%lx,%u) returned %u.",pSeq->hmidi,lpmhPreroll,sizeof(MIDIHDR),mmrc); pSeq->fdwSeq &= ~SEQ_F_EOF; while (pSeq->lpmhFree) { lpmh = pSeq->lpmhFree; pSeq->lpmhFree = lpmh->lpNext; smfrc = smfReadEvents(pSeq->hSmf, lpmh, pSeq->tkEnd); if (SMF_SUCCESS != smfrc && SMF_END_OF_FILE != smfrc) { //DPF(1, "SFP: smfReadEvents() -> %u", (UINT)smfrc); mmrc = XlatSMFErr(smfrc); goto Preroll_Cleanup; } if (MMSYSERR_NOERROR != (mmrc = midiOutPrepareHeader(pSeq->hmidi, lpmh, sizeof(*lpmh)))) { //DPF(1, "SFP: midiOutPrepareHeader failed"); goto Preroll_Cleanup; } if (MMSYSERR_NOERROR != (mmrc = midiStreamOut((HMIDISTRM)pSeq->hmidi, lpmh, sizeof(*lpmh)))) { //DPF(1, "SFP: midiStreamOut failed"); goto Preroll_Cleanup; } ++pSeq->uBuffersInMMSYSTEM; if (SMF_END_OF_FILE == smfrc) { pSeq->fdwSeq |=SEQ_F_EOF; break; } } Preroll_Cleanup: if (MMSYSERR_NOERROR != mmrc) { pSeq->uState =SEQ_S_OPENED; pSeq->fdwSeq &= ~SEQ_F_WAITING; } else { pSeq->uState =SEQ_S_PREROLLED; } return mmrc; } /*************************************************************************** * *MidiSound::Start * * Starts playback at the current position. * * pSeq - TheMidiSound::uencer instance. * * Returns * MMSYSERR_NOERROR If the operation is successful. * * MCIERR_UNSUPPORTED_FUNCTION If theMidiSound::uencer instance is not * stopped. * * MCIERR_DEVICE_NOT_READY If the underlying MIDI device could * not be opened or fails any call. * * TheMidiSound::uencer must be prerolled beforeMidiSound::Start may be called. * * Just feed everything in the ready queue to the device. * ***************************************************************************/ MMRESULT MidiSound::Start() { if (NULL == pSeq) { return MCIERR_UNSUPPORTED_FUNCTION; } if (SEQ_S_PREROLLED != pSeq->uState) { Preroll(); } if (SEQ_S_PREROLLED != pSeq->uState) { //DPF(1, "seqStart(): State is wrong! [%u]", pSeq->uState); return MCIERR_UNSUPPORTED_FUNCTION; } pSeq->uState =SEQ_S_PLAYING; return midiStreamRestart((HMIDISTRM)pSeq->hmidi); } /*************************************************************************** * *MidiSound::Pause * * Pauses playback of the instance. * * pSeq - TheMidiSound::uencer instance. * * Returns * MMSYSERR_NOERROR If the operation is successful. * * MCIERR_UNSUPPORTED_FUNCTION If theMidiSound::uencer instance is not * playing. * * TheMidiSound::uencer must be playing beforeMidiSound::Pause may be called. * Pausing theMidiSound::uencer will cause all currently on notes to be turned * off. pSeq may cause playback to be slightly inaccurate on restart * due to missing notes. * ***************************************************************************/ MMRESULT MidiSound::Pause() { //assert(NULL != pSeq); if (SEQ_S_PLAYING != pSeq->uState) return MCIERR_UNSUPPORTED_FUNCTION; pSeq->uState =SEQ_S_PAUSED; OutputDebugString("MidiSound::Pause\n"); //EnterCriticalSection(&gMidiCS); midiStreamPause((HMIDISTRM)pSeq->hmidi); //LeaveCriticalSection(&gMidiCS); return MMSYSERR_NOERROR; } /*************************************************************************** * *MidiSound::Restart * * Restarts playback of an instance after a pause. * * pSeq - TheMidiSound::uencer instance. * * Returns * MMSYSERR_NOERROR If the operation is successful. * * MCIERR_UNSUPPORTED_FUNCTION If theMidiSound::uencer instance is not * paused. * * TheMidiSound::uencer must be paused beforeMidiSound::Restart may be called. * ***************************************************************************/ MMRESULT MidiSound::Restart() { //assert(NULL != pSeq); switch(pSeq->uState){ case SEQ_S_PAUSED: pSeq->uState =SEQ_S_PLAYING; midiStreamRestart((HMIDISTRM)pSeq->hmidi); break; case SEQ_S_OPENED: Start(); break; } return MMSYSERR_NOERROR; } /*************************************************************************** * *MidiSound::Stop * * Totally stops playback of an instance. * * pSeq - TheMidiSound::uencer instance. * * Returns * MMSYSERR_NOERROR If the operation is successful. * * MCIERR_UNSUPPORTED_FUNCTION If theMidiSound::uencer instance is not * paused or playing. * * TheMidiSound::uencer must be paused or playing beforeMidiSound::Stop may be called. * ***************************************************************************/ MMRESULT MidiSound::Stop() { //assert(NULL != pSeq); /* Automatic success if we're already stopped */ if (SEQ_S_PLAYING != pSeq->uState && SEQ_S_PAUSED != pSeq->uState) { pSeq->fdwSeq &= ~SEQ_F_WAITING; return MMSYSERR_NOERROR; } pSeq->uState =SEQ_S_STOPPING; pSeq->fdwSeq |=SEQ_F_WAITING; //EnterCriticalSection(&gMidiCS); OutputDebugString("MidiSound::Stop\n"); if(pSeq->hmidi){ #if 1 //--- modification by Francisco pSeq->mmrcLastErr = midiStreamClose((HMIDISTRM)pSeq->hmidi); pSeq->uState = SEQ_S_OPENED; pSeq->hmidi = 0; pSeq->fdwSeq &= ~SEQ_F_WAITING; return MMSYSERR_NOERROR; #else //--- if (MMSYSERR_NOERROR != (pSeq->mmrcLastErr = midiStreamStop((HMIDISTRM)pSeq->hmidi))) { pSeq->fdwSeq &= ~SEQ_F_WAITING; //LeaveCriticalSection(&gMidiCS); return MCIERR_DEVICE_NOT_READY; } while (pSeq->uBuffersInMMSYSTEM) Sleep(0); if(pSeq->hmidi) midiStreamClose((HMIDISTRM)pSeq->hmidi); #endif } //LeaveCriticalSection(&gMidiCS); return MMSYSERR_NOERROR; } /*************************************************************************** * *MidiSound::Time * * Determine the current position in playback of an instance. * * pSeq - TheMidiSound::uencer instance. * * pTicks - A pointer to a DWORD where the current position * in ticks will be returned. * * Returns * MMSYSERR_NOERROR If the operation is successful. * * MCIERR_DEVICE_NOT_READY If the underlying device fails to report * the position. * * MCIERR_UNSUPPORTED_FUNCTION If theMidiSound::uencer instance is not * paused or playing. * * TheMidiSound::uencer must be paused, playing or prerolled beforeMidiSound::Time * may be called. * ***************************************************************************/ MMRESULT MidiSound::Time(PTICKS pTicks) { MMRESULT mmr; MMTIME mmt; //assert(pSeq != NULL); if (SEQ_S_PLAYING != pSeq->uState && SEQ_S_PAUSED != pSeq->uState && SEQ_S_PREROLLING != pSeq->uState && SEQ_S_PREROLLED != pSeq->uState && SEQ_S_OPENED != pSeq->uState) { //DPF(1, "seqTime(): State wrong! [is %u]", pSeq->uState); return MCIERR_UNSUPPORTED_FUNCTION; } *pTicks = 0; if (SEQ_S_OPENED != pSeq->uState) { *pTicks = pSeq->tkBase; if (SEQ_S_PREROLLED != pSeq->uState) { mmt.wType = TIME_TICKS; mmr = midiStreamPosition((HMIDISTRM)pSeq->hmidi, &mmt, sizeof(mmt)); if (MMSYSERR_NOERROR != mmr) { //DPF(1, "midiStreamPosition() returned %lu", (DWORD)mmr); return MCIERR_DEVICE_NOT_READY; } *pTicks += mmt.u.ticks; } } return MMSYSERR_NOERROR; } /*************************************************************************** * *MidiSound::MillisecsToTicks * * Given a millisecond offset in the output stream, returns the associated * tick position. * * pSeq - TheMidiSound::uencer instance. * * msOffset - The millisecond offset into the stream. * * Returns the number of ticks into the stream. * ***************************************************************************/ TICKS MidiSound::MillisecsToTicks(DWORD msOffset) { return smfMillisecsToTicks(pSeq->hSmf, msOffset); } /*************************************************************************** * *MidiSound::TicksToMillisecs * * Given a tick offset in the output stream, returns the associated * millisecond position. * * pSeq - TheMidiSound::uencer instance. * * tkOffset - The tick offset into the stream. * * Returns the number of milliseconds into the stream. * ***************************************************************************/ DWORD MidiSound::TicksToMillisecs(TICKS tkOffset) { return smfTicksToMillisecs(pSeq->hSmf, tkOffset); } /*************************************************************************** * *MidiSound::MIDICallback * * Called by the system when a buffer is done * * dw1 - The buffer that has completed playback. * ***************************************************************************/ static void FAR PASCAL seqMIDICallback(HMIDISTRM hms, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) { LPMIDIHDR lpmh = (LPMIDIHDR)dw1; PSEQ pSeq; MMRESULT mmrc; SMFRESULT smfrc; if (uMsg != MOM_DONE) return; //assert(NULL != lpmh); pSeq = (PSEQ)(lpmh->dwUser); //assert(pSeq != NULL); --pSeq->uBuffersInMMSYSTEM; if (SEQ_S_RESET == pSeq->uState) { // We're recollecting buffers from MMSYSTEM // if (lpmh != pSeq->lpmhPreroll) { lpmh->lpNext = pSeq->lpmhFree; pSeq->lpmhFree = lpmh; } return; } if ((SEQ_S_STOPPING == pSeq->uState) || (pSeq->fdwSeq &SEQ_F_EOF)) { /* ** Reached EOF, just put the buffer back on the free ** list */ if (lpmh != pSeq->lpmhPreroll) { lpmh->lpNext = pSeq->lpmhFree; pSeq->lpmhFree = lpmh; } if (MMSYSERR_NOERROR != (mmrc = midiOutUnprepareHeader(pSeq->hmidi, lpmh, sizeof(*lpmh)))) { //DPF(1, "midiOutUnprepareHeader failed inMidiSound::BufferDone! (%lu)", (DWORD)mmrc); } if (0 == pSeq->uBuffersInMMSYSTEM) { //DPF(1, "seqBufferDone: normalMidiSound::uencer shutdown."); /* Totally done! Free device and notify. */ //EnterCriticalSection(&gMidiCS); OutputDebugString("midiStreamClose\n"); /* if(pSeq->hmidi) midiStreamClose((HMIDISTRM)pSeq->hmidi); */ pSeq->hmidi = NULL; pSeq->uState =SEQ_S_OPENED; pSeq->mmrcLastErr = MMSYSERR_NOERROR; pSeq->fdwSeq &= ~SEQ_F_WAITING; //LeaveCriticalSection(&gMidiCS); // lParam indicates whether or not to preroll again. Don't if we were explicitly // stopped. // PostMessage(pSeq->hWnd, MMSG_DONE, (WPARAM)pSeq, (LPARAM)(SEQ_S_STOPPING != pSeq->uState)); } } else { /* ** Not EOF yet; attempt to fill another buffer */ smfrc = smfReadEvents(pSeq->hSmf, lpmh, pSeq->tkEnd); switch(smfrc) { case SMF_SUCCESS: break; case SMF_END_OF_FILE: pSeq->fdwSeq |=SEQ_F_EOF; smfrc = SMF_SUCCESS; break; default: //DPF(1, "smfReadEvents returned %lu in callback!", (DWORD)smfrc); pSeq->uState =SEQ_S_STOPPING; break; } if (SMF_SUCCESS == smfrc) { ++pSeq->uBuffersInMMSYSTEM; mmrc = midiStreamOut((HMIDISTRM)pSeq->hmidi, lpmh, sizeof(*lpmh)); if (MMSYSERR_NOERROR != mmrc) { //DPF(1, "seqBufferDone(): midiStreamOut() returned %lu!", (DWORD)mmrc); --pSeq->uBuffersInMMSYSTEM; pSeq->uState =SEQ_S_STOPPING; } } } } /*************************************************************************** * * XlatSMFErr * * Translates an error from the SMF layer into an appropriate MCI error. * * smfrc - The return code from any SMF function. * * Returns * A parallel error from the MCI error codes. * ***************************************************************************/ static MMRESULT XlatSMFErr(SMFRESULT smfrc) { switch(smfrc) { case SMF_SUCCESS: return MMSYSERR_NOERROR; case SMF_NO_MEMORY: return MCIERR_OUT_OF_MEMORY; case SMF_INVALID_FILE: case SMF_OPEN_FAILED: case SMF_INVALID_TRACK: return MCIERR_INVALID_FILE; default: return MCIERR_UNSUPPORTED_FUNCTION; } } MidiSound::MidiSound(void *hwnd) { if ((pSeq = (PSEQ)LocalAlloc(LPTR, sizeof(SEQ))) == NULL) return; pSeq->cBuffer = 4; pSeq->cbBuffer = 1024; pSeq->pstrFile = NULL; if (AllocBuffers() != MMSYSERR_NOERROR) return; pSeq->hWnd = (HWND)hwnd; } MidiSound::~MidiSound() { Stop(); if (pSeq->pstrFile) free(pSeq->pstrFile); pSeq->pstrFile=NULL; FreeBuffers(); LocalFree(pSeq); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #define PARAMETER_OP_TYPE_STRING_TO_ATT CKGUID(0x3678447e,0x30362a74) #define PARAM_OP_TYPE_CIS_INI_COLLISION CKGUID(0x4ec2349b,0x5edf7dd8) #define PARAM_OP_TYPE_CHAS_CONTACT CKGUID(0x3ed57b83,0x47ad145f) #define PARAM_OP_TYPE_CRAY_COLLISION CKGUID(0x53425880,0x1b540c2b) #define PARAM_OP_TYPE_CGROUP_COLLISION CKGUID(0x7b762a1a,0x702e471c) #define PARAM_OP_RC_ANY_BOUNDS CKGUID(0x31e415e2,0x61e42210) #define PARAM_OP_RC_ANY_SHAPE CKGUID(0x62943427,0x31877a8f) void ParamOpRayCastAnyShape(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { using namespace vtTools::ParameterTools; using namespace vtTools::BehaviorTools; CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID = vtTools::ParameterTools::GetValueFromParameterStruct<CK_ID>(p1->GetRealSource(),E_RC_WORLD,false); CK_ID oriRef = vtTools::ParameterTools::GetValueFromParameterStruct<CK_ID>(p1->GetRealSource(),E_RC_ORI_REF,false); CK_ID dirRef = vtTools::ParameterTools::GetValueFromParameterStruct<CK_ID>(p1->GetRealSource(),E_RC_DIR_REF,false); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorld(targetID); if (!world) { int result = false; res->SetValue(&result); return; } CK3dEntity *rayOriRef= (CK3dEntity *)GetPMan()->m_Context->GetObject(oriRef); CK3dEntity *rayDirRef= (CK3dEntity *) GetPMan()->m_Context->GetObject(dirRef); VxVector ori = vtTools::ParameterTools::GetValueFromParameterStruct<VxVector>(p1->GetRealSource(),E_RC_ORI,false); VxVector dir = vtTools::ParameterTools::GetValueFromParameterStruct<VxVector>(p1->GetRealSource(),E_RC_DIR,false); VxVector oriOut = ori; if (rayOriRef) { rayOriRef->Transform(&oriOut,&ori); } //dir : VxVector dirOut = dir; if (rayDirRef) { VxVector dir,up,right; rayDirRef->GetOrientation(&dir,&up,&right); rayDirRef->TransformVector(&dirOut,&up); } int groups = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),E_RC_GROUPS,false); float length = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),E_RC_LENGTH,false); int types = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),E_RC_SHAPES_TYPES,false); CK_ID* paramids = static_cast<CK_ID*>(p1->GetReadDataPtr()); CKParameterOut* maskP = static_cast<CKParameterOut*>(p1->GetCKContext()->GetObject(paramids[E_RC_GROUPS_MASK])); NxGroupsMask mask; mask.bits0 = GetValueFromParameterStruct<int>(maskP,0); mask.bits1 = GetValueFromParameterStruct<int>(maskP,1); mask.bits2 = GetValueFromParameterStruct<int>(maskP,2); mask.bits3 = GetValueFromParameterStruct<int>(maskP,3); NxRay ray; ray.orig = getFrom(oriOut); ray.dir = getFrom(dirOut); //NxShape **shapes = new NxShape*[2]; NxU32 total = world->getScene()->getTotalNbShapes();//world->getScene()->getNbDynamicShapes() + world->getScene()->getNbStaticShapes(); //NxShape** shapes = NULL ;//(NxShape**)NxAlloca(nbShapes*sizeof(NxShape*)); NxShape** shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); for (NxU32 i = 0; i < total; i++) shapes[i] = NULL; //NxShape **shapes = NULL; int result = world->getScene()->raycastAnyShape(ray,(NxShapesType)types,groups,length,&mask,shapes); NxShape *s = shapes[0]; if (s) { pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(s->userData); if (sInfo->entID) { CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); if (obj) { CK_ID id = obj->GetID(); res->SetValue(&id); //beh->SetOutputParameterObject(bbO_Shape,obj); } } } //res->SetValue(&result); return; } } void ParamOpRayCastAnyBounds(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { using namespace vtTools::ParameterTools; using namespace vtTools::BehaviorTools; CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID = vtTools::ParameterTools::GetValueFromParameterStruct<CK_ID>(p1->GetRealSource(),E_RC_WORLD,false); CK_ID oriRef = vtTools::ParameterTools::GetValueFromParameterStruct<CK_ID>(p1->GetRealSource(),E_RC_ORI_REF,false); CK_ID dirRef = vtTools::ParameterTools::GetValueFromParameterStruct<CK_ID>(p1->GetRealSource(),E_RC_DIR_REF,false); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorld(targetID); if (!world) { int result = false; res->SetValue(&result); return; } CK3dEntity *rayOriRef= (CK3dEntity *)GetPMan()->m_Context->GetObject(oriRef); CK3dEntity *rayDirRef= (CK3dEntity *) GetPMan()->m_Context->GetObject(dirRef); VxVector ori = vtTools::ParameterTools::GetValueFromParameterStruct<VxVector>(p1->GetRealSource(),E_RC_ORI,false); VxVector dir = vtTools::ParameterTools::GetValueFromParameterStruct<VxVector>(p1->GetRealSource(),E_RC_DIR,false); VxVector oriOut = ori; if (rayOriRef) { rayOriRef->Transform(&oriOut,&ori); } //dir : VxVector dirOut = dir; if (rayDirRef) { VxVector dir,up,right; rayDirRef->GetOrientation(&dir,&up,&right); rayDirRef->TransformVector(&dirOut,&up); } int groups = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),E_RC_GROUPS,false); float length = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),E_RC_LENGTH,false); int types = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),E_RC_SHAPES_TYPES,false); CK_ID* paramids = static_cast<CK_ID*>(p1->GetReadDataPtr()); CKParameterOut* maskP = static_cast<CKParameterOut*>(p1->GetCKContext()->GetObject(paramids[E_RC_GROUPS_MASK])); NxGroupsMask mask; mask.bits0 = GetValueFromParameterStruct<int>(maskP,0); mask.bits1 = GetValueFromParameterStruct<int>(maskP,1); mask.bits2 = GetValueFromParameterStruct<int>(maskP,2); mask.bits3 = GetValueFromParameterStruct<int>(maskP,3); NxRay ray; ray.orig = getFrom(oriOut); ray.dir = getFrom(dirOut); int result = world->getScene()->raycastAnyBounds(ray,(NxShapesType)types,groups,length,&mask); res->SetValue(&result); return; } } #define PARAM_OP_TYPE_MGET_SFRICTION CKGUID(0x58566e7b,0x494f208a) #define PARAM_OP_TYPE_MGET_SFRICTIONV CKGUID(0x7af723af,0x7e222884) #define PARAM_OP_TYPE_MGET_SDFRICTION CKGUID(0x10733925,0x77c37dba) #define PARAM_OP_TYPE_MGET_SDFRICTIONV CKGUID(0x29131ba,0x3b2a6f07) #define PARAM_OP_TYPE_MGET_ANIS CKGUID(0x255256df,0x61fe2f77) #define PARAM_OP_TYPE_MGET_FMODE CKGUID(0x321f0335,0x589576df) #define PARAM_OP_TYPE_MGET_RMODE CKGUID(0x1cb07645,0x79ff1329) #define PARAM_OP_TYPE_MGET_XML_TYPE CKGUID(0x6fea2100,0x6667545b) #define PARAM_OP_TYPE_MGET_RES CKGUID(0x41702512,0x78c48ca) #define PARAM_OP_TYPE_MSET_SFRICTION CKGUID(0x2f2e1071,0x2d4623ec) #define PARAM_OP_TYPE_MSET_SFRICTIONV CKGUID(0x31940b2a,0x67f43440) #define PARAM_OP_TYPE_MSET_SDFRICTION CKGUID(0x205b0164,0x39d626d0) #define PARAM_OP_TYPE_MSET_SDFRICTIONV CKGUID(0x11f36b7a,0x7877377b) #define PARAM_OP_TYPE_MSET_ANIS CKGUID(0x36565c47,0x46002830) #define PARAM_OP_TYPE_MSET_FMODE CKGUID(0x4ddb7828,0x4d111b71) #define PARAM_OP_TYPE_MSET_RMODE CKGUID(0x5d2315b7,0x2cb834f3) void ParamOpMGetF(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int index = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),0,false); float value = 0; if (index !=0 && GetPMan()->getCurrentFactory()) { if (GetPMan()->getDefaultConfig()) { XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); if (mDesrc) { value = mDesrc->staticFriction; res->SetValue(&value); delete mDesrc; mDesrc = NULL; return; } } } if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),2,false); } } res->SetValue(&value); } void ParamOpMGetDF(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int index = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),0,false); float value = 0; if (index !=0 && GetPMan()->getCurrentFactory()) { if (GetPMan()->getDefaultConfig()) { XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); if (mDesrc) { value = mDesrc->dynamicFriction; res->SetValue(&value); delete mDesrc; mDesrc = NULL; return; } } } if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),1,false); } } res->SetValue(&value); } void ParamOpMGetR(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int index = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),0,false); float value = 0; if (index !=0 && GetPMan()->getCurrentFactory()) { if (GetPMan()->getDefaultConfig()) { XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); if (mDesrc) { value = mDesrc->restitution; res->SetValue(&value); delete mDesrc; mDesrc = NULL; return; } } } if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),3,false); } } res->SetValue(&value); } void ParamOpMGetDFV(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int index = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),0,false); float value = 0; if (index !=0 && GetPMan()->getCurrentFactory()) { if (GetPMan()->getDefaultConfig()) { XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); if (mDesrc) { value = mDesrc->dynamicFrictionV; res->SetValue(&value); delete mDesrc; mDesrc = NULL; return; } } } if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),4,false); } } res->SetValue(&value); } void ParamOpMGetFV(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int index = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),0,false); float value = 0; if (index !=0 && GetPMan()->getCurrentFactory()) { if (GetPMan()->getDefaultConfig()) { XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); if (mDesrc) { value = mDesrc->staticFrictionV; res->SetValue(&value); delete mDesrc; mDesrc = NULL; return; } } } if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<float>(p1->GetRealSource(),5,false); } } res->SetValue(&value); } void ParamOpMGetA(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int index = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),0,false); VxVector value(0.0f); if (index !=0 && GetPMan()->getCurrentFactory()) { if (GetPMan()->getDefaultConfig()) { XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); if (mDesrc) { value = getFrom(mDesrc->dirOfAnisotropy); res->SetValue(&value); delete mDesrc; mDesrc = NULL; return; } } } if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<VxVector>(p1->GetRealSource(),6,false); } } res->SetValue(&value); } void ParamOpMGetFMode(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int index = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),0,false); int value = 0; if (index !=0 && GetPMan()->getCurrentFactory()) { if (GetPMan()->getDefaultConfig()) { XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); if (mDesrc) { value = mDesrc->frictionCombineMode; res->SetValue(&value); delete mDesrc; mDesrc = NULL; return; } } } if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),7,false); } } res->SetValue(&value); } ////////////////////////////////////////////////////////////////////////// void ParamOpMGetRMode(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int index = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),0,false); int value = 0; if (index !=0 && GetPMan()->getCurrentFactory()) { if (GetPMan()->getDefaultConfig()) { XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); if (mDesrc) { value = mDesrc->restitutionCombineMode; res->SetValue(&value); delete mDesrc; mDesrc = NULL; return; } } } if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),8,false); } } res->SetValue(&value); } void ParamOpMGetXMat(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); int value = 0; if (p1) { if (p1->GetRealSource()) { value = vtTools::ParameterTools::GetValueFromParameterStruct<int>(p1->GetRealSource(),0,false); } } res->SetValue(&value); } #define PARAM_OP_TYPE_BGET_RESTITUTION CKGUID(0x58566e7b,0x494f208a) void ParamOpStringToAdd(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CKAttributeManager *am = (CKAttributeManager*)context->GetAttributeManager(); //CKSTRING test = CKParameter *p = p1->GetRealSource(); if (!p) { return; } CKSTRING test = vtTools::ParameterTools::GetParameterAsString(p); if (!strlen(test))return; XString aName; XString aCat; XString aType; XStringTokenizer tokizer(test, "|"); const char*tok = NULL; int nb = 0; while ((tok=tokizer.NextToken(tok)) && nb < 3) { XString tokx(tok); switch (nb) { case 0: aName = tokx.Str(); break; case 1: aCat= tokx.Str(); break; case 2: aType = tokx.Str(); break; } nb++; } CKAttributeType aIType = am->GetAttributeTypeByName(aName.Str()); if (aIType!=-1) { res->SetValue(&aIType); return; } CKGUID pType = pm->ParameterNameToGuid(aType.Str()); CKParameterType pt = pm->ParameterGuidToType(pType); if (pt==-1) { pType = CKPGUID_NONE; } aIType = am->RegisterNewAttributeType(aName.Str(),pType,CKCID_OBJECT); if (aCat.Length()) { am->AddCategory(aCat.Str()); am->SetAttributeCategory(aIType,aCat.Str()); } res->SetValue(&aIType); } void PhysicManager::_RegisterParameterOperations() { CKParameterManager *pm = m_Context->GetParameterManager(); _RegisterParameterOperationsBody(); _RegisterParameterOperationsJoint(); _RegisterParameterOperationsVehicle(); pm->RegisterOperationType(PARAMETER_OP_TYPE_STRING_TO_ATT, "convert"); pm->RegisterOperationFunction(PARAMETER_OP_TYPE_STRING_TO_ATT,CKPGUID_ATTRIBUTE,CKPGUID_STRING,CKPGUID_NONE,ParamOpStringToAdd); pm->RegisterOperationType(PARAM_OP_TYPE_MGET_RMODE, "pMgRMode"); pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_RMODE,VTE_MATERIAL_COMBINE_MODE,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetRMode); pm->RegisterOperationType(PARAM_OP_TYPE_MGET_FMODE, "pMgFMode"); pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_FMODE,VTE_MATERIAL_COMBINE_MODE,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetFMode); pm->RegisterOperationType(PARAM_OP_TYPE_MGET_RES, "pMgRestitution"); pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_RES,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetR); pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SFRICTION, "pMgSFriction"); pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SFRICTION,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetF); pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SFRICTIONV, "pMgSVFriction"); pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SFRICTIONV,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetFV); pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SDFRICTION, "pMgDFriction"); pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SDFRICTION,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetDF); pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SDFRICTIONV, "pMgDVFriction"); pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SDFRICTIONV,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetDFV); pm->RegisterOperationType(PARAM_OP_TYPE_MGET_ANIS, "pMgAnis"); pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_ANIS,CKPGUID_VECTOR,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetA); pm->RegisterOperationType(PARAM_OP_TYPE_MGET_XML_TYPE, "pMgType"); pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_XML_TYPE,VTE_XML_MATERIAL_TYPE,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetXMat); /************************************************************************/ /* */ /************************************************************************/ /* pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FRICTION, "GetFriction"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FRICTION,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetFriction); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_LDAMP, "GetLinDamping"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_LDAMP,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetLDamp); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_LDAMPT, "GetLinDampingT"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_LDAMPT,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetLDampT); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_ADAMP, "GetAngDamping"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_ADAMP,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetADamp); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_ADAMPT, "GetAngDampingT"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_ADAMPT,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetADampT); pm->RegisterOperationType(PARAM_OP_TYPE_CIS_INI_COLLISION, "IsInCollision"); pm->RegisterOperationFunction(PARAM_OP_TYPE_CIS_INI_COLLISION,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpCIsInCollision); pm->RegisterOperationType(PARAM_OP_TYPE_CHAS_CONTACT, "HasContact"); pm->RegisterOperationFunction(PARAM_OP_TYPE_CHAS_CONTACT,CKPGUID_3DENTITY,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpCHasContact); pm->RegisterOperationType(PARAM_OP_TYPE_CRAY_COLLISION, "RayCollision"); pm->RegisterOperationFunction(PARAM_OP_TYPE_CRAY_COLLISION,CKPGUID_3DENTITY,CKPGUID_3DENTITY,CKPGUID_VECTOR4,ParamOpCRayCollision); pm->RegisterOperationType(PARAM_OP_TYPE_CGROUP_COLLISION, "IsCollision"); pm->RegisterOperationFunction(PARAM_OP_TYPE_CGROUP_COLLISION,CKPGUID_3DENTITY,CKPGUID_3DENTITY,CKPGUID_GROUP,ParamOpCIsInCollisionWithGroup); */ pm->RegisterOperationType(PARAM_OP_RC_ANY_BOUNDS, "raycastAnyBounds"); pm->RegisterOperationFunction(PARAM_OP_RC_ANY_BOUNDS,CKPGUID_BOOL,VTS_RAYCAST,CKPGUID_NONE,ParamOpRayCastAnyBounds); pm->RegisterOperationType(PARAM_OP_RC_ANY_SHAPE, "raycastAnyShape"); pm->RegisterOperationFunction(PARAM_OP_RC_ANY_SHAPE,CKPGUID_3DENTITY,VTS_RAYCAST,CKPGUID_NONE,ParamOpRayCastAnyShape); } /* void ParamOpBGetLVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetAVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetTorque(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetFriction(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBisFixed(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetHType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetLDamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetLDampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetADamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpBGetADampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpCIsInCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpCHasContact(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpCRayCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); void ParamOpCIsInCollisionWithGroup(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); */ /* void ParamOpCIsInCollisionWithGroup(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { ////////////////////////////////////////////////////////////////////////// //retrieve the position ori : CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); ////////////////////////////////////////////////////////////////////////// //retrieve the group CK_ID targetIDG; p2->GetValue(&targetIDG); CKGroup *group = static_cast<CKGroup*>(context->GetObject(targetIDG)); ////////////////////////////////////////////////////////////////////////// //our result object : CK3dEntity* result = NULL; CK_ID id = 0; ////////////////////////////////////////////////////////////////////////// //check our input object : if (!ent) { res->SetValue(&id); return; } if (ent ) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { VxVector pos,normal; float depth; result = world->CIsInCollision(ent,group,pos,normal,depth); if (result) { id = result->GetID(); } } } res->SetValue(&id); } ////////////////////////////////////////////////////////////////////////// void ParamOpCRayCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { ////////////////////////////////////////////////////////////////////////// //retrieve the position ori : CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); ////////////////////////////////////////////////////////////////////////// //our result object : CK3dEntity* result = NULL; CK_ID id = 0; ////////////////////////////////////////////////////////////////////////// //check our input object : if (!ent) { res->SetValue(&id); return; } ////////////////////////////////////////////////////////////////////////// //we retrieve ori of the ray by a box : VxVector4 inVec(0,0,0,0); p2->GetValue(&inVec); VxVector oriOut(0,0,0); ////////////////////////////////////////////////////////////////////////// //direction of the ray : VxVector dirIn (inVec.x,inVec.y,inVec.z); pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { VxVector pos,normal; float depth; result = world->CRayCollision(oriOut,ent,dirIn,ent,inVec.w,true,pos,normal); if (result) { id = result->GetID(); } } res->SetValue(&id); } ////////////////////////////////////////////////////////////////////////// void ParamOpCHasContact(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); CK3dEntity* result = NULL; CK_ID id = 0; if (ent ) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { VxVector pos,normal; float depth; result = world->CIsInCollision(ent,pos,normal,depth); if (result) { id = result->GetID(); } } } res->SetValue(&id); } ////////////////////////////////////////////////////////////////////////// void ParamOpCIsInCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); CK_ID targetID2; p2->GetValue(&targetID2); CK3dEntity *ent2 = static_cast<CK3dEntity*>(context->GetObject(targetID2)); int result = 0; if (ent && ent2) { pWorld *world=GetPMan()->getWorldByBody(ent); pWorld *world2=GetPMan()->getWorldByBody(ent2); if (world && world2 && world == world2) { VxVector pos,normal; float depth; result = world->CIsInCollision(ent,ent2,pos,normal,depth); } } res->SetValue(&result); } ////////////////////////////////////////////////////////////////////////// void ParamOpBGetFriction(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { float vec = target->GetFriction(); res->SetValue(&vec); } } } } ////////////////////////////////////////////////////////////////////////// void ParamOpBGetLDamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { float vec = target->GetLinearDamping(); res->SetValue(&vec); } } } } ////////////////////////////////////////////////////////////////////////// void ParamOpBGetLDampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { float vec = target->GetLinearDampingThreshold(); res->SetValue(&vec); } } } } ////////////////////////////////////////////////////////////////////////// void ParamOpBGetADamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { float vec = target->GetLinearDamping(); res->SetValue(&vec); } } } } ////////////////////////////////////////////////////////////////////////// void ParamOpBGetADampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { float vec = target->GetLinearDampingThreshold(); res->SetValue(&vec); } } } } */ //////////////////////////////////////////////////////////////////////////<file_sep>DEV35DIR="X:/sdk/dev35" DEV40DIR="X:/sdk/dev4" DEV41DIR="X:/sdk/dev41R" <file_sep>/******************************************************************** created: 2009/01/05 created: 5:1:2009 18:18 filename: x:\ProjectRoot\svn\local\vtTools\SDK\Include\Core\vtCModuleDefines.h file path: x:\ProjectRoot\svn\local\vtTools\SDK\Include\Core file base: vtCModuleDefines file ext: h author: purpose: *********************************************************************/ #ifndef __VTMODULES_DEFINES_H_ #define __VTMODULES_DEFINES_H_ #include <virtools/vtCXGlobal.h> #define VTCMODULE_NAME VTCX_API_PREFIX("TOOLS") #define VTCMODULE_ATTRIBUTE_CATAEGORY VTCMODULE_NAME #define VTM_TOOL_MANAGER_GUID CKGUID(0x7a9a6475,0x6fb90c74) #define VTBB_PLG_GUID CKGUID(0x3262afb,0x230b4434) #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" #ifdef HAS_FLUID void __newpFluidDescr(BYTE *iAdd) { new(iAdd)pFluidDesc(); } void __newpFluidEmitterDesc(BYTE *iAdd) { new(iAdd)pFluidEmitterDesc(); } void PhysicManager::_RegisterFluid_VSL() { STARTVSLBIND(m_Context) /************************************************************************/ /* pFluidFlags */ /************************************************************************/ DECLAREENUM("pFluidFlag") DECLAREENUMVALUE("pFluidFlag", "PFF_DisableGravity" , 2) DECLAREENUMVALUE("pFluidFlag", "PFF_CollisionTwoway" , 4) DECLAREENUMVALUE("pFluidFlag", "PFF_Enabled" , 8) DECLAREENUMVALUE("pFluidFlag", "PFF_Hardware" , 16) DECLAREENUMVALUE("pFluidFlag", "PFF_PriorityMode" , 32) DECLAREENUMVALUE("pFluidFlag", "PFF_ProjectToPlane" , 64) DECLAREENUM("pFluidSimulationMethod") DECLAREENUMVALUE("pFluidSimulationMethod", "PFS_SPH" , 1) DECLAREENUMVALUE("pFluidSimulationMethod", "PFS_NoParticleInteraction" , 2) DECLAREENUMVALUE("pFluidSimulationMethod", "PFS_MixedMode" , 4) DECLAREENUM("pFluidCollisionMethod") DECLAREENUMVALUE("pFluidCollisionMethod", "PFCM_Static" , 1) DECLAREENUMVALUE("pFluidCollisionMethod", "PFCM_Dynamic" , 2) DECLAREOBJECTTYPE(pFluidDesc) DECLARECTOR_0(__newpFluidDescr) DECLAREMEMBER(pFluidDesc,int,maxParticles) DECLAREMEMBER(pFluidDesc,float,attractionForDynamicShapes) DECLAREMEMBER(pFluidDesc,float,attractionForStaticShapes) DECLAREMEMBER(pFluidDesc,float,collisionDistanceMultiplier) DECLAREMEMBER(pFluidDesc,int,collisionGroup) DECLAREMEMBER(pFluidDesc,pFluidCollisionMethod,collisionMethod) DECLAREMEMBER(pFluidDesc,float,collisionResponseCoefficient) DECLAREMEMBER(pFluidDesc,float,damping) DECLAREMEMBER(pFluidDesc,float,dynamicFrictionForDynamicShapes) DECLAREMEMBER(pFluidDesc,float,dynamicFrictionForStaticShapes) DECLAREMEMBER(pFluidDesc,VxVector,externalAcceleration) DECLAREMEMBER(pFluidDesc,float,fadeInTime) DECLAREMEMBER(pFluidDesc,float,kernelRadiusMultiplier) DECLAREMEMBER(pFluidDesc,float,packetSizeMultiplier) DECLAREMEMBER(pFluidDesc,int,maxParticles) DECLAREMEMBER(pFluidDesc,float,motionLimitMultiplier) DECLAREMEMBER(pFluidDesc,int,numReserveParticles) DECLAREMEMBER(pFluidDesc,int,packetSizeMultiplier) DECLAREMEMBER(pFluidDesc,float,restitutionForDynamicShapes) DECLAREMEMBER(pFluidDesc,float,restitutionForStaticShapes) DECLAREMEMBER(pFluidDesc,float,restParticlesPerMeter) DECLAREMEMBER(pFluidDesc,float,restDensity) DECLAREMEMBER(pFluidDesc,pFluidSimulationMethod,simulationMethod) DECLAREMEMBER(pFluidDesc,float,staticFrictionForDynamicShapes) DECLAREMEMBER(pFluidDesc,float,staticFrictionForStaticShapes) DECLAREMEMBER(pFluidDesc,float,stiffness) DECLAREMEMBER(pFluidDesc,float,surfaceTension) DECLAREMEMBER(pFluidDesc,float,viscosity) DECLAREMEMBER(pFluidDesc,pFluidFlag,flags) DECLAREMEMBER(pFluidDesc,CK_ID,worldReference) DECLAREMETHOD_0(pFluidDesc,void,setToDefault) DECLAREMETHOD_0(pFluidDesc,bool,isValid) /************************************************************************/ /* emitter */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // emitter flags : // DECLAREENUM("pFluidEmitterFlag") DECLAREENUMVALUE("pFluidEmitterFlag", "PFEF_ForceOnBody" , 4) DECLAREENUMVALUE("pFluidEmitterFlag", "PFEF_AddBodyVelocity" , 8) DECLAREENUMVALUE("pFluidEmitterFlag", "PFEF_Enabled" , 16) DECLAREENUM("pEmitterShape") DECLAREENUMVALUE("pEmitterShape", "PFES_Rectangular" , 1) DECLAREENUMVALUE("pEmitterShape", "PFES_Ellipse" , 2) DECLAREENUM("pEmitterType") DECLAREENUMVALUE("pEmitterType", "PFET_ConstantPressure" , 1) DECLAREENUMVALUE("pEmitterType", "PFET_ConstantFlowRate" , 2) ////////////////////////////////////////////////////////////////////////// // // emitter descr : // DECLAREOBJECTTYPE(pFluidEmitterDesc) DECLARECTOR_0(__newpFluidEmitterDesc) DECLAREMEMBER(pFluidEmitterDesc,CK3dEntity*,frameShape) DECLAREMEMBER(pFluidEmitterDesc,pEmitterType,type) DECLAREMEMBER(pFluidEmitterDesc,int,maxParticles) DECLAREMEMBER(pFluidEmitterDesc,pEmitterShape,shape) DECLAREMEMBER(pFluidEmitterDesc,float,dimensionX) DECLAREMEMBER(pFluidEmitterDesc,float,dimensionY) DECLAREMEMBER(pFluidEmitterDesc,VxVector,randomPos) DECLAREMEMBER(pFluidEmitterDesc,float,randomAngle) DECLAREMEMBER(pFluidEmitterDesc,float,fluidVelocityMagnitude) DECLAREMEMBER(pFluidEmitterDesc,float,rate) DECLAREMEMBER(pFluidEmitterDesc,float,randomAngle) DECLAREMEMBER(pFluidEmitterDesc,float,particleLifetime) DECLAREMEMBER(pFluidEmitterDesc,float,repulsionCoefficient) DECLAREMEMBER(pFluidEmitterDesc,pFluidEmitterFlag,flags) DECLAREMETHOD_0(pFluidEmitterDesc,void,setToDefault) DECLAREMETHOD_0(pFluidEmitterDesc,bool,isValid) DECLAREMEMBER(pFluidEmitterDesc,CK_ID,entityReference) DECLAREPOINTERTYPE(pFluidEmitter) /************************************************************************/ /* fluid */ /************************************************************************/ DECLAREPOINTERTYPE(pFluid) DECLAREMETHOD_0(pFluid,CK3dEntity*,getParticleObject) DECLAREMETHOD_2(pFactory,pFluid*,createFluid,CK3dEntity*,pFluidDesc) DECLAREMETHOD_1(pFluid,pFluidEmitter*,createEmitter,const pFluidEmitterDesc&) STOPVSLBIND } #endif // HAS_FLUID<file_sep>#include "crypting.h" #include <Windows.h> #include <StdIO.h> #include <Math.h> int EncryptPassword(char* pcPassword) { int aiKey[50] = {0x02, 0x03, 0x05, 0x07, 0x11, 0x13, 0x17, 0x19, 0x23, 0x29, 0xA2, 0xB3, 0xC5, 0xD7, 0xE1, 0xF3, 0xA7, 0xB9, 0xC3, 0xD9, 0x93, 0xA4, 0xB6, 0xC8, 0xD2, 0xE4, 0x98, 0xA8, 0xB4, 0xC8, 0x46, 0x58, 0x63, 0x67, 0x74, 0x78, 0x57, 0x57, 0x68, 0x67, 0xA9, 0xBC, 0xC9, 0xDF, 0xF6, 0x0C, 0xBF, 0xCF, 0xFC, 0xFF}; char acPassword[256]; char acTemp[3]; if(pcPassword == NULL) return TRUE; ZeroMemory(acPassword, 256 * sizeof(char)); srand(strlen(pcPassword) * 17); for(int a = 0; a < (int)(strlen(pcPassword)); a++) { srand(rand() + strlen(pcPassword) * a); srand((rand() % (aiKey[a % 50])) + (rand() % (aiKey[(a * 23) % 50]))); srand((rand() % (aiKey[(a + 2305) % 50])) + (rand() % (aiKey[(17 + a * 133) % 50])) * 177); acPassword[a] = pcPassword[a] + (rand() % 256); srand(((BYTE)(acPassword[a]) + 1) * (a + 23) + (rand() % 1381)); //ok, thatīs crazy enough } ZeroMemory(pcPassword, strlen(pcPassword) * sizeof(char)); for(int a = 0; a < (int)(strlen(acPassword)); a++) { sprintf(acTemp, "%02x", (byte)(acPassword[a])); strcat(pcPassword, acTemp); } return FALSE; } <file_sep>// mdexceptions.h // // WinDirStat - Directory Statistics // Copyright (C) 2003-2004 <NAME> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // This general purpose header is derived from a file // created by www.daccord.net und published // here under GPL with friendly permission of D'accord. // Md is just a prefix. #ifndef MDEXCEPTIONS_H_INCLUDED #define MDEXCEPTIONS_H_INCLUDED #ifndef _INC_STDARG #include <stdarg.h> #endif #pragma warning(disable: 4290) // C++ Exception Specification ignored class CMdStringException: public CException { public: CMdStringException(LPCTSTR pszText) : m_sText(pszText) // pszText may be a MAKEINTRESOURCE {} virtual BOOL GetErrorMessage(LPTSTR lpszError, UINT nMaxError, PUINT pnHelpContext = NULL) { if (pnHelpContext != NULL) *pnHelpContext= 0; if (nMaxError != 0 && lpszError != NULL) lstrcpyn(lpszError, m_sText, nMaxError); return true; } protected: CString m_sText; }; inline CString MdGetExceptionMessage(CException *pe) { CString s; BOOL b= pe->GetErrorMessage(s.GetBuffer(1024), 1024); s.ReleaseBuffer(); if (!b) s= _T("(no error message available)"); return s; } inline CString MdGetWinerrorText(HRESULT hr) { CString sRet; LPVOID lpMsgBuf; DWORD dw= FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); if (dw == NULL) { CString s(MAKEINTRESOURCE(AFX_IDP_NO_ERROR_AVAILABLE)); sRet.Format(_T("%s (0x%08lx)"), s, hr); } else { sRet= (LPCTSTR)lpMsgBuf; LocalFree(lpMsgBuf); } return sRet; } inline void MdThrowStringException(UINT resId) throw (CMdStringException *) { throw new CMdStringException(MAKEINTRESOURCE(resId)); } inline void MdThrowStringException(LPCTSTR pszText) throw (CMdStringException *) { throw new CMdStringException(pszText); } inline void __MdFormatStringExceptionV(CString& rsText, LPCTSTR pszFormat, va_list vlist) { CString sFormat(pszFormat); // may be a MAKEINTRESOURCE rsText.FormatMessageV(sFormat, &vlist); } inline void AFX_CDECL MdThrowStringExceptionF(LPCTSTR pszFormat, ...) { CString sText; va_list vlist; va_start(vlist, pszFormat); __MdFormatStringExceptionV(sText, pszFormat, vlist); va_end(vlist); MdThrowStringException(sText); } inline void MdThrowStringExceptionV(LPCTSTR pszFormat, va_list vlist) { CString sText; __MdFormatStringExceptionV(sText, pszFormat, vlist); MdThrowStringException(sText); } inline void AFX_CDECL MdThrowStringExceptionF(UINT nResIdFormat, ...) { CString sText; va_list vlist; va_start(vlist, nResIdFormat); __MdFormatStringExceptionV(sText, MAKEINTRESOURCE(nResIdFormat), vlist); va_end(vlist); MdThrowStringException(sText); } inline void MdThrowStringExceptionF(UINT nResIdFormat, va_list vlist) { CString sText; __MdFormatStringExceptionV(sText, MAKEINTRESOURCE(nResIdFormat), vlist); MdThrowStringException(sText); } inline void MdThrowWinerror(DWORD dw, LPCTSTR pszPrefix =NULL) throw (CMdStringException *) { CString sMsg= pszPrefix; sMsg+= _T(": ") + MdGetWinerrorText(dw); MdThrowStringException(sMsg); } inline void MdThrowHresult(HRESULT hr, LPCTSTR pszPrefix =NULL) throw (CMdStringException *) { CString sMsg= pszPrefix; sMsg+= _T(": ") + MdGetWinerrorText(hr); MdThrowStringException(sMsg); } inline void MdThrowLastWinerror(LPCTSTR pszPrefix =NULL) throw (CMdStringException *) { MdThrowWinerror(GetLastError(), pszPrefix); } inline void MdThrowFailed(HRESULT hr, LPCTSTR pszPrefix =NULL) throw (CMdStringException *) { if (FAILED(hr)) MdThrowHresult(hr, pszPrefix); } #endif <file_sep>import vt import sys import socket ### Common #### MSGLEN = 10 def vt_client(): client = server_connect('localhost', 9090) vt.ActivateOut(bid,0,1) if vt.IsInputActive(bid,0): my_message = vt.GetInVal(bid,3) vt.SetOutVal(bid,0,my_message) if message_send(client, my_message): vt.ActivateOut(bid,2,1) msg = message_get(client) if(msg): vt.ActivateOut(bid,3,1) vt.SetOutVal(bid,1,len(msg)) vt.SetOutVal(bid,2, msg) def server_connect(host, port): #create an INET, STREAMing socket client = socket.socket( socket.AF_INET, socket.SOCK_STREAM) #now connect to the web server on port 80 # - the normal http port client.connect((host, port)) return client def message_get(sock): msg = '' chunk = '' while len(msg) < MSGLEN: chunk = sock.recv(MSGLEN-len(msg)) if chunk == '': vt.ActivateOut(bid,1,1) vt.SetOutVal(bid,3, "socket connection broken") msg = msg + chunk return msg return 0 def message_send(sock, message): msgfmt = "%-" + "%ds" % (MSGLEN) msg = msgfmt % (message) totalsent = 0 while totalsent < MSGLEN: sent = sock.send(msg[totalsent:]) if sent == 0: vt.ActivateOut(bid,1,1) vt.SetOutVal(bid,3, "socket connection broken") totalsent = totalsent + sent return 1 <file_sep>dofile("ModuleConfig.lua") dofile("ModuleHelper.lua") if _ACTION == "help" then premake.showhelp() return end solution "vtPhysX" configurations { "Debug", "Release" , "ReleaseDebug" ; "ReleaseRedist" ; "ReleaseDemo" } if _ACTION and _OPTIONS["Dev"] then setfields("location","./".._ACTION.._OPTIONS["Dev"]) end packageConfig_libtomcrypt = { Name = "libtomcrypt", Type = "StaticLib", Defines = { DEF_STD_DIRECTIVES }, Files = { DDEPS.."libtomcrypt/*.c" ; DDEPS.."libtomcrypt/*.h"}, Includes = { DDEPS.."libtomcrypt" }, ExludeFiles = { DDEPS.."libtomcrypt/aes_tab.c" ; DDEPS.."libtomcrypt/sha384.c" ; DDEPS.."libtomcrypt/sha224.c" ; DDEPS.."libtomcrypt/rsa_sys.c" ; DDEPS.."libtomcrypt/ecc_sys.c" ; DDEPS.."libtomcrypt/dh_sys.c" ; }, Options = { "/W0"} } packageConfig_libTNL = { Name = "libTNL", Type = "StaticLib", Defines = { DEF_STD_DIRECTIVES; "TNL_ENABLE_LOGGING" ; "TNL_DEBUG" }, Files = { DDEPS.."tnl/*.cpp" ; DDEPS.."tnl/*.h"}, Includes = { DDEPS.."libtomcrypt" ; }, Libs = { }, Options = { "/W0"} } -- The building blocks for vtPhysX, depending on packageConfig_vtAgeiaLib packageConfig_vtTNL = { Name = "vtTNL", Type = "SharedLib", TargetSuffix = "/BuildingBlocks", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "MODULE_BASE_EXPORTS" ; "TNL_ENABLE_LOGGING" ; "TNL_DEBUG" }, Files = { DROOT.."SDK/src/Behaviors/**.cpp" ; DROOT.."SDK/src/Behaviors/*.def" ; D_DOCS_PAGES.."*.page" ; F_SHARED_SRC ; DROOT.."build4/**.lua" ; F_BASE_SRC ; D_CORE_SRC ; F_BASE_VT_SRC ; F_BASE_STD_INC}, Includes = { D_STD_INCLUDES ; D_CORE_INCLUDES }, Libs = { "ck2" ; "vxmath" ; "user32" ; "kernel32" ; "libTNL" ; "Ws2_32" ; "libtomcrypt" }, LibDirectories = { }, Options = { "/W0"}, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\\BuildingBlocks" .."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower().."\\BuildingBlocks" } packageConfig_xConsoleServer = { Name = "xConsoleServer", Type = "ConsoleApp", TargetSuffix = "", Defines = { DEF_STD_DIRECTIVES ; "VIRTOOLS_USER_SDK" ; "MODULE_BASE_EXPORTS"; "TNL_ENABLE_LOGGING" ; "TNL_DEBUG" }, Files = { DROOT.."SDK/src/ConsoleServer/*.cpp"; F_SHARED_SRC ; F_BASE_SRC ; D_CORE_SRC ; F_BASE_VT_SRC ; F_BASE_STD_INC }, Includes = { D_STD_INCLUDES ; D_CORE_INCLUDES }, Libs = { "ck2" ; "vxmath" ; "user32" ; "kernel32" ; "libTNL" ; "Ws2_32" ; "libtomcrypt" }, LibDirectories = { }, Options = { "/W0"}, ExludeFiles = { DROOT.."SDK/src/core/vtNetworkManager*.cpp" }, PostCommand = "copy $(TargetDir)$(TargetFileName) "..getVTDirectory():lower().."\n".."copy $(TargetDir)$(InputName).pdb "..getVTDirectory():lower() } -- If the command line contains --ExtraDefines="WebPack" , we add "WebPack" to the -- pre-processor directives and also create a package to include the camera building blocks -- as defined in packageConfig_CameraRepack if _OPTIONS["ExtraDefines"] then if _OPTIONS["ExtraDefines"]=="WebPack" then createStaticPackage(packageConfig_CameraRepack) end end createStaticPackage(packageConfig_vtTNL) createStaticPackage(packageConfig_libtomcrypt) createStaticPackage(packageConfig_libTNL) createStaticPackage(packageConfig_xConsoleServer) --include "CppConsoleApp" function onclean() os.rmdir("vs**") end <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include <vtTools.h> #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorGetIncomingUserDecl(); CKERROR CreateGetIncomingUserProto(CKBehaviorPrototype **); int GetIncomingUser(const CKBehaviorContext& behcontext); CKERROR GetIncomingUserCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorGetIncomingUserDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NIncomingUser"); od->SetDescription("User enters a session"); od->SetCategory("TNL/User Management"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7a770be7,0x77130778)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGetIncomingUserProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } typedef enum BB_IT { BB_IT_IN, BB_IT_OFF, BB_IT_NEXT, }; typedef enum BB_INPAR { BB_IP_CONNECTION_ID, }; typedef enum BB_OT { BB_O_OUT, BB_O_INCOMING, BB_O_ERROR, }; typedef enum BB_OP { BB_OP_USER_ID, BB_OP_USER_NAME, BB_OP_ERROR }; CKERROR CreateGetIncomingUserProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NIncomingUser"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Stop"); proto->DeclareInput("Next"); proto->DeclareOutput("Out"); proto->DeclareOutput("Incoming"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("User ID", CKPGUID_INT, "-1"); proto->DeclareOutParameter("User Name", CKPGUID_STRING, "-1"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "-1"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(GetIncomingUser); proto->SetBehaviorCallbackFct(GetIncomingUserCB); *pproto = proto; return CK_OK; } int GetIncomingUser(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); int connectionID=-1; beh->GetInputParameterValue(0,&connectionID); XString userName((CKSTRING) beh->GetInputParameterReadDataPtr(1)); /************************************************************************/ /* */ /************************************************************************/ beh->ActivateInput(0,FALSE); bbNoError(E_NWE_OK); xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } if (!cin->getMyClient()) { bbError(E_NWE_INTERN); return 0; } xDistributedClient *myClient = cin->getMyClient(); if (!myClient) { bbError(E_NWE_INTERN); return 0; } /* xDistributedSession *session = cin->getCurrentSession(); if (!session) { bbError(E_NWE_NO_SUCH_SESSION); return 0; } if (!myClient->getClientFlags().test(1 << E_CF_SESSION_JOINED)) { bbError(E_NWE_NO_SESSION); return 0; } */ IDistributedObjects *doInterface = cin->getDistObjectInterface(); vtConnection *con = cin->getConnection(); xDistributedObjectsArrayType *distObjects = cin->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { xDistributedClass *_class = dobj->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT) { xDistributedClient *client = static_cast<xDistributedClient*>(dobj); if (client) { xDistributedClient *myClient = cin->getMyClient(); xDistributedSession *session = cin->getCurrentSession(); if ( isFlagOn(client->getClientFlags(),E_CF_ADDING) && client->getUserID() != con->getUserID() ) { disableFlag(client->getClientFlags(),E_CF_ADDING); enableFlag(client->getClientFlags(), E_CF_ADDED); if (isFlagOn(myClient->getClientFlags(),E_CF_SESSION_JOINED)) { SetOutputParameterValue<int>(beh,BB_OP_USER_ID,client->getUserID()); SetOutputParameterValue<const char*>(beh,BB_OP_USER_NAME,client->getUserName().getString()); //xLogger::xLog(ELOGINFO,E_LI_CLIENT,"Incoming user %d",client->getUserID()); //XLOG_BB_INFO; beh->ActivateOutput(1); return CKBR_ACTIVATENEXTFRAME; } } } } } } begin++; } /************************************************************************/ /* */ /************************************************************************/ if (beh->IsInputActive(1)) { beh->ActivateInput(1,FALSE); beh->ActivateOutput(0); return CKBR_OK; } return CKBR_ACTIVATENEXTFRAME; } CKERROR GetIncomingUserCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>/****************************************************************************** File : CustomPlayer.cpp Description: This file contains the CCustomPlayer class which is the "interface" with the Virtools SDK. All other files are Windows/MFC specific code. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ #include "CPStdAfx.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "resourceplayer.h" #if defined(CUSTOM_PLAYER_STATIC) // include file used for the static configuration #include "CustomPlayerStaticLibs.h" #include "CustomPlayerRegisterDlls.h" #endif #include "vtTools.h" extern CCustomPlayer* thePlayer; int CCustomPlayer::_CreateWindows() { RECT mainRect; int k = WindowedWidth(); int k1 = WindowedHeight(); // compute the main window rectangle, so the window is centered mainRect.left = (GetSystemMetrics(SM_CXSCREEN)-WindowedWidth())/2; mainRect.right = WindowedWidth()+mainRect.left; mainRect.top = (GetSystemMetrics(SM_CYSCREEN)-WindowedHeight())/2; mainRect.bottom = WindowedHeight()+mainRect.top; BOOL ret = AdjustWindowRect(&mainRect,WS_OVERLAPPEDWINDOW & ~(WS_SYSMENU|WS_SIZEBOX|WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_SIZEBOX),FALSE); DWORD dwStyle; // create the main window switch(PGetApplicationMode()) { case normal: { m_MainWindow = CreateWindow(m_PlayerClass.CStr(),GetPAppStyle()->g_AppTitle.Str(),WS_OVERLAPPEDWINDOW & ~(WS_SIZEBOX|WS_MAXIMIZEBOX), mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top, NULL,NULL,m_hInstance,NULL); break; } case preview: { RECT rc; GetClientRect( m_hWndParent, &rc ); dwStyle = WS_VISIBLE | WS_CHILD; AdjustWindowRect( &rc, dwStyle, FALSE ); m_MainWindow = m_hWndParent; m_WindowedWidth = rc.right - rc.left ; m_WindowedHeight = rc.bottom - rc.top; m_RenderWindow = CreateWindowEx(WS_EX_TOPMOST,m_RenderClass.CStr(),"",(WS_CHILD|WS_VISIBLE)&~WS_CAPTION,rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,m_MainWindow,NULL,m_hInstance,this); } break; case popup: { dwStyle = (WS_OVERLAPPEDWINDOW); //m_MainWindow = CreateWindowEx( dwStyle , m_PlayerClass.CStr(), GetPAppStyle()->g_AppTitle.Str(), WS_POPUP, mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top , m_MainWindow, NULL,m_hInstance, NULL ); m_MainWindow = CreateWindow(m_PlayerClass.CStr(),"asd",WS_POPUP,mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top,NULL,NULL,m_hInstance,NULL); break; } default: m_MainWindow = CreateWindow(m_PlayerClass.CStr(),GetPAppStyle()->g_AppTitle.Str(),WS_OVERLAPPEDWINDOW & ~(WS_SIZEBOX|WS_MAXIMIZEBOX), mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top, NULL,NULL,m_hInstance,NULL); break; } // m_MainWindow = CreateWindow(m_PlayerClass.CStr(),"asd",WS_OVERLAPPEDWINDOW & ~(WS_SIZEBOX|WS_MAXIMIZEBOX), // mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top, // NULL,NULL,m_hInstance,NULL); int errorL = GetLastError(); if(!m_MainWindow) { return FALSE; } if(PGetApplicationMode() != preview) { // create the render window if (( GetEWindowInfo()->g_GoFullScreen )) { m_RenderWindow = CreateWindowEx(WS_EX_TOPMOST,m_RenderClass.CStr(),"",(WS_CHILD|WS_OVERLAPPED|WS_VISIBLE)&~WS_CAPTION, 0,0,FullscreenWidth(),FullscreenHeight(),m_MainWindow,NULL,m_hInstance,0); } else { m_RenderWindow = CreateWindowEx(WS_EX_TOPMOST,m_RenderClass.CStr(),"",(WS_CHILD|WS_OVERLAPPED|WS_VISIBLE)&~WS_CAPTION, 0,0,WindowedWidth(),WindowedHeight(),m_MainWindow,NULL,m_hInstance,0); } } if(!m_RenderWindow) { return FALSE; } return TRUE; } ATOM CCustomPlayer::_RegisterClass() { // register window classes WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; wcex.lpfnWndProc = (WNDPROC)_MainWindowWndProcStub; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = m_hInstance; //wcex.hIconSm = (HICON) LoadImage(m_hInstance,TEXT("AppIcon"),IMAGE_ICON,16, 16,LR_LOADFROMFILE); HICON icon = NULL; icon = (HICON) LoadImage(NULL,TEXT("app.ico"),IMAGE_ICON,16, 16,LR_LOADFROMFILE); if (icon) { wcex.hIcon = icon; }else{ wcex.hIcon = LoadIcon( m_hInstance, MAKEINTRESOURCE(IDI_VIRTOOLS) ); } wcex.hCursor = NULL; wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.lpszClassName = m_PlayerClass.CStr(); wcex.hIconSm = icon; WNDCLASS MyRenderClass; ZeroMemory(&MyRenderClass,sizeof(MyRenderClass)); MyRenderClass.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; MyRenderClass.lpfnWndProc = (WNDPROC)_MainWindowWndProcStub; MyRenderClass.hInstance = m_hInstance; MyRenderClass.lpszClassName = m_RenderClass.CStr(); ::RegisterClass(&MyRenderClass); int le = GetLastError(); int result = ::RegisterClassEx(&wcex); le = GetLastError(); int h = 2 ; return result; } void CCustomPlayer::_SetResolutions() { // retrieve the windowed attribute CKParameterOut* pout = m_Level->GetAttributeParameter(m_WindowedResolutionAttType); if (pout) { Vx2DVector res(m_WindowedWidth,m_WindowedHeight); // set it pout->SetValue(&res); } // retrieve the fullscreen attribute pout = m_Level->GetAttributeParameter(m_FullscreenResolutionAttType); if (pout) { Vx2DVector res(m_FullscreenWidth,m_FullscreenHeight); // set it pout->SetValue(&res); } // retrieve the fullscreen bpp attribute pout = m_Level->GetAttributeParameter(m_FullscreenBppAttType); if (pout) { // set it pout->SetValue(&m_FullscreenBpp); } } BOOL CCustomPlayer::ChangeResolution() { if (!m_RenderContext) return FALSE; if (m_RenderContext->IsFullScreen()) { // we are in fullscreen mode if (_GetFullScreenResolution()) { // the resolution has changed // pause the player m_CKContext->Pause(); // and stop fullscreen m_RenderContext->StopFullScreen(); // return to fullscreen with the new resolution m_RenderContext->GoFullScreen(m_FullscreenWidth,m_FullscreenHeight,m_FullscreenBpp,m_Driver); VxDriverDesc* Check_API_Desc = m_RenderManager->GetRenderDriverDescription(m_Driver); //we have to resize the mainwin to allow correct picking (only in DX) if (Check_API_Desc->Caps2D.Family==CKRST_DIRECTX && m_RenderContext->IsFullScreen()) { //store current size GetWindowRect(m_MainWindow,&m_MainWindowRect); //Resize the window ::SetWindowPos(m_MainWindow,HWND_TOPMOST,0,0,m_FullscreenWidth,m_FullscreenHeight,NULL); //Prevent the window from beeing resized LONG st = GetWindowLong(m_MainWindow,GWL_STYLE); st&=~WS_THICKFRAME; st&=~WS_SIZEBOX; SetWindowLong(m_MainWindow,GWL_STYLE,st); } // everything is ok to restart the player m_CKContext->Play(); } } else { // we are in windowed mode if (_GetWindowedResolution()) { // the resolution has changed //allow the window to be resized LONG st = GetWindowLong(m_MainWindow,GWL_STYLE); st|=WS_THICKFRAME; st&=~WS_SIZEBOX; SetWindowLong(m_MainWindow,GWL_STYLE,st); //reposition the window m_MainWindowRect.left = (GetSystemMetrics(SM_CXSCREEN)-m_WindowedWidth)/2; m_MainWindowRect.right = m_WindowedWidth+m_MainWindowRect.left; m_MainWindowRect.top = (GetSystemMetrics(SM_CYSCREEN)-m_WindowedHeight)/2; m_MainWindowRect.bottom = m_WindowedHeight+m_MainWindowRect.top; BOOL ret = AdjustWindowRect(&m_MainWindowRect,WS_OVERLAPPEDWINDOW & ~(WS_SYSMENU|WS_SIZEBOX|WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_SIZEBOX),FALSE); ::SetWindowPos(m_MainWindow,0,m_MainWindowRect.left,m_MainWindowRect.top,m_MainWindowRect.right - m_MainWindowRect.left,m_MainWindowRect.bottom - m_MainWindowRect.top,NULL); // and set the position of the render window in the main window ::SetWindowPos(m_RenderWindow,NULL,0,0,m_WindowedWidth,m_WindowedHeight,SWP_NOMOVE|SWP_NOZORDER); m_RenderContext->Resize(0,0,m_WindowedWidth,m_WindowedHeight); } } return TRUE; } BOOL CCustomPlayer::ClipMouse(BOOL iEnable) { // manage the mouse clipping if (!GetPlayer().GetPAppStyle()->IsRenderering()) return false; if(iEnable==FALSE) { // disable the clipping return ClipCursor(NULL); } if (!m_RenderContext) { return FALSE; } // retrieve the render window rectangle VxRect r; m_RenderContext->GetWindowRect(r,TRUE); RECT rect; rect.top = (LONG)r.top; rect.left = (LONG)r.left; rect.bottom = (LONG)r.bottom; rect.right = (LONG)r.right; // to clip the mouse in it. return ClipCursor(&rect); } BOOL CCustomPlayer::SwitchFullscreen(BOOL value) { if (!m_RenderContext || !m_FullscreenEnabled) { return FALSE; } // mark eat display change to true // so we cannot switch the display during this function. m_EatDisplayChange = TRUE; if ( !value && m_RenderContext->IsFullScreen() ) { // siwtch to windowed mode // retrieve the windowed resolution from the attributes _GetWindowedResolution(); // we pause the player m_CKContext->Pause(); // stop the fullscreen m_RenderContext->StopFullScreen(); //restore the main window size (only in DirectX rasterizer->m_MainWindowRect.bottom not modified) if (m_MainWindowRect.bottom!=0 && !m_RenderContext->IsFullScreen()) { //allow the window to be resized LONG st = GetWindowLong(m_MainWindow,GWL_STYLE); st|=WS_THICKFRAME; st&=~WS_SIZEBOX; SetWindowLong(m_MainWindow,GWL_STYLE,st); } //reposition the window m_MainWindowRect.left = (GetSystemMetrics(SM_CXSCREEN)-m_WindowedWidth)/2; m_MainWindowRect.right = m_WindowedWidth+m_MainWindowRect.left; m_MainWindowRect.top = (GetSystemMetrics(SM_CYSCREEN)-m_WindowedHeight)/2; m_MainWindowRect.bottom = m_WindowedHeight+m_MainWindowRect.top; BOOL ret = AdjustWindowRect(&m_MainWindowRect,WS_OVERLAPPEDWINDOW & ~(WS_SYSMENU|WS_SIZEBOX|WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_SIZEBOX),FALSE); ::SetWindowPos(m_MainWindow,HWND_NOTOPMOST,m_MainWindowRect.left,m_MainWindowRect.top,m_MainWindowRect.right - m_MainWindowRect.left,m_MainWindowRect.bottom - m_MainWindowRect.top,NULL); // now we can show the main widnwos ShowWindow(m_MainWindow,SW_SHOW); SetFocus(m_MainWindow); // and set the position of the render window in the main window ::SetWindowPos(m_RenderWindow,NULL,0,0,m_WindowedWidth,m_WindowedHeight,SWP_NOMOVE|SWP_NOZORDER); m_RenderContext->Resize(0,0,m_WindowedWidth,m_WindowedHeight); // and give the focus to the render window SetFocus(m_RenderWindow); // everything is ok to restart the player m_CKContext->Play(); } else if(value && !m_RenderContext->IsFullScreen()) { // switch to fullscreen mode // retrieve the fullscreen resolution from the attributes _GetFullScreenResolution(); // we pause the player m_CKContext->Pause(); // and go fullscreen m_RenderContext->GoFullScreen(m_FullscreenWidth,m_FullscreenHeight,m_FullscreenBpp,m_Driver); // everything is ok to restart the player m_CKContext->Play(); VxDriverDesc* Check_API_Desc = m_RenderManager->GetRenderDriverDescription(m_Driver); //we have to resize the mainwin to allow correct picking (only in DX) if (Check_API_Desc->Caps2D.Family==CKRST_DIRECTX && m_RenderContext->IsFullScreen()) { //store current size GetWindowRect(m_MainWindow,&m_MainWindowRect); //Resize the window ::SetWindowPos(m_MainWindow,HWND_TOPMOST,0,0,m_FullscreenWidth,m_FullscreenHeight,NULL); //Prevent the window from beeing resized LONG st = GetWindowLong(m_MainWindow,GWL_STYLE); st&=~WS_THICKFRAME; st&=~WS_SIZEBOX; SetWindowLong(m_MainWindow,GWL_STYLE,st); } } // mark eat display change to false // as we have finished m_EatDisplayChange = FALSE; ClipMouse(m_MouseClipped); return TRUE; } BOOL CCustomPlayer::SwitchFullscreen() { if (!m_RenderContext || !m_FullscreenEnabled) { return FALSE; } // mark eat display change to true // so we cannot switch the display during this function. m_EatDisplayChange = TRUE; if (m_RenderContext->IsFullScreen()) { // siwtch to windowed mode // retrieve the windowed resolution from the attributes _GetWindowedResolution(); // we pause the player m_CKContext->Pause(); // stop the fullscreen m_RenderContext->StopFullScreen(); //restore the main window size (only in DirectX rasterizer->m_MainWindowRect.bottom not modified) if (m_MainWindowRect.bottom!=0 && !m_RenderContext->IsFullScreen()) { //allow the window to be resized LONG st = GetWindowLong(m_MainWindow,GWL_STYLE); st|=WS_THICKFRAME; st&=~WS_SIZEBOX; SetWindowLong(m_MainWindow,GWL_STYLE,st); } //reposition the window m_MainWindowRect.left = (GetSystemMetrics(SM_CXSCREEN)-m_WindowedWidth)/2; m_MainWindowRect.right = m_WindowedWidth+m_MainWindowRect.left; m_MainWindowRect.top = (GetSystemMetrics(SM_CYSCREEN)-m_WindowedHeight)/2; m_MainWindowRect.bottom = m_WindowedHeight+m_MainWindowRect.top; BOOL ret = AdjustWindowRect(&m_MainWindowRect,WS_OVERLAPPEDWINDOW & ~(WS_SYSMENU|WS_SIZEBOX|WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_SIZEBOX),FALSE); ::SetWindowPos(m_MainWindow,HWND_NOTOPMOST,m_MainWindowRect.left,m_MainWindowRect.top,m_MainWindowRect.right - m_MainWindowRect.left,m_MainWindowRect.bottom - m_MainWindowRect.top,NULL); // now we can show the main widnwos ShowWindow(m_MainWindow,SW_SHOW); SetFocus(m_MainWindow); // and set the position of the render window in the main window ::SetWindowPos(m_RenderWindow,NULL,0,0,m_WindowedWidth,m_WindowedHeight,SWP_NOMOVE|SWP_NOZORDER); // and give the focus to the render window SetFocus(m_RenderWindow); // everything is ok to restart the player m_CKContext->Play(); } else { // switch to fullscreen mode // retrieve the fullscreen resolution from the attributes _GetFullScreenResolution(); // we pause the player m_CKContext->Pause(); // and go fullscreen m_RenderContext->GoFullScreen(m_FullscreenWidth,m_FullscreenHeight,m_FullscreenBpp,m_Driver); // everything is ok to restart the player m_CKContext->Play(); VxDriverDesc* Check_API_Desc = m_RenderManager->GetRenderDriverDescription(m_Driver); //we have to resize the mainwin to allow correct picking (only in DX) if (Check_API_Desc->Caps2D.Family==CKRST_DIRECTX && m_RenderContext->IsFullScreen()) { //store current size GetWindowRect(m_MainWindow,&m_MainWindowRect); //Resize the window ::SetWindowPos(m_MainWindow,HWND_TOPMOST,0,0,m_FullscreenWidth,m_FullscreenHeight,NULL); //Prevent the window from beeing resized LONG st = GetWindowLong(m_MainWindow,GWL_STYLE); st&=~WS_THICKFRAME; st&=~WS_SIZEBOX; SetWindowLong(m_MainWindow,GWL_STYLE,st); } } // mark eat display change to false // as we have finished m_EatDisplayChange = FALSE; ClipMouse(m_MouseClipped); return TRUE; } BOOL CCustomPlayer::_CheckFullscreenDisplayMode(BOOL iDoBest) { VxDriverDesc* desc = m_RenderManager->GetRenderDriverDescription(m_Driver); // try to find the correct fullscreen display mode VxDisplayMode* displayMode = NULL; for (displayMode=desc->DisplayModes.Begin();displayMode!=desc->DisplayModes.End();displayMode++) { if (displayMode->Width==m_FullscreenWidth && displayMode->Height==m_FullscreenHeight && displayMode->Bpp==m_FullscreenBpp) { m_FullscreenEnabled = TRUE; return TRUE; } } if (!iDoBest) { return FALSE; } // we did not find a display mode // try 640x480x32 m_FullscreenWidth = 640; m_FullscreenHeight = 480; m_FullscreenBpp = 32; for (displayMode=desc->DisplayModes.Begin();displayMode!=desc->DisplayModes.End();displayMode++) { if (displayMode->Width==m_FullscreenWidth && displayMode->Height==m_FullscreenHeight && displayMode->Bpp==m_FullscreenBpp) { m_FullscreenEnabled = TRUE; return TRUE; } } // we did not find a display mode // try 640x480x16 m_FullscreenBpp = 16; for (displayMode=desc->DisplayModes.Begin();displayMode!=desc->DisplayModes.End();displayMode++) { if (displayMode->Width==m_FullscreenWidth && displayMode->Height==m_FullscreenHeight && displayMode->Bpp==m_FullscreenBpp) { m_FullscreenEnabled = TRUE; return TRUE; } } m_FullscreenEnabled = FALSE; return FALSE; } BOOL CCustomPlayer::_GetFullScreenResolution() { // retrieve the fullscreen resolution from attribute // retrieve the attribute (resolution width and height) CKParameterOut* paramRes = m_Level->GetAttributeParameter(m_FullscreenResolutionAttType); if (!paramRes) { return FALSE; } // save old values int oldWidth = m_FullscreenWidth; int oldHeight = m_FullscreenHeight; int oldBpp = m_FullscreenBpp; // retrieve the attribute (bpp) CKParameterOut* paramBpp = m_Level->GetAttributeParameter(m_FullscreenBppAttType); if (paramBpp) { paramBpp->GetValue(&m_FullscreenBpp); } Vx2DVector res(m_FullscreenWidth,m_FullscreenHeight); paramRes->GetValue(&res); m_FullscreenWidth = (int)res.x; m_FullscreenHeight = (int)res.y; // check the resolution is compatible with the fullscreen mode if (!_CheckFullscreenDisplayMode(FALSE)) { // else ... m_FullscreenWidth = oldWidth; m_FullscreenHeight = oldHeight; m_FullscreenBpp = oldBpp; // ... reset attributes with old values _SetResolutions(); } // returns TRUE if at least one value has changed return (m_FullscreenWidth!=oldWidth || m_FullscreenHeight!=oldHeight || m_FullscreenBpp!=oldBpp); } BOOL CCustomPlayer::_GetWindowedResolution() { // retrieve the windowed resolution from attribute // retrieve the attribute (resolution width and height) CKParameterOut* pout = m_Level->GetAttributeParameter(m_WindowedResolutionAttType); if (!pout) { return FALSE; } // save old values int oldWidth = m_WindowedWidth; int oldHeight = m_WindowedHeight; Vx2DVector res(m_WindowedWidth,m_WindowedHeight); pout->GetValue(&res); m_WindowedWidth = (int)res.x; m_WindowedHeight = (int)res.y; // returns TRUE if at least one value has changed return (m_WindowedWidth!=oldWidth || m_WindowedHeight!=oldHeight); } LRESULT CCustomPlayer::OnSysKeyDownMainWindow(int iConfig, int iKey) { // Manage system key (ALT + KEY) // system keys can be disable using eDisableKeys switch(iKey) { case VK_RETURN: if (!(iConfig&eDisableKeys)) { // ALT + ENTER -> SwitchFullscreen SwitchFullscreen( !m_RenderContext->IsFullScreen() ); } break; case VK_F4: if (!(iConfig&eDisableKeys)) { // ALT + F4 -> Quit the application PostQuitMessage(0); return 1; } break; } return 0; } void CCustomPlayer::OnActivateApp(BOOL iActivate) { // if // - the application is being activated (iActivate == TRUE) // - the render context is in fullscreen // - and the player is not already switching fullscreen (m_EatDisplayChange == FALSE) if (iActivate==FALSE && m_RenderContext && m_RenderContext->IsFullScreen() && !m_EatDisplayChange) { // we switch fullscreen because the application is deactivated //SwitchFullscreen(); } } void CCustomPlayer::OnFocusChange(BOOL iFocus) { // here we manage the focus change if (!m_CKContext) { return; } /////////////////////// // First, check minimize/restore /////////////////////// if ( (m_State==ePlaying) && IsIconic(m_MainWindow) ) { // we must pause process // the application is minimized m_State = eMinimized; // so we pause the player m_CKContext->Pause(); return; } if ( (m_State==eMinimized) && !IsIconic(m_MainWindow) ) { // we must restart process // the application is no longer minimized m_State = ePlaying; // so we restart the player m_CKContext->Play(); return; } /////////////////////// // then check focus lost behavior /////////////////////// CKDWORD pauseMode = m_CKContext->GetFocusLostBehavior(); if(m_State==ePlaying || m_State==eFocusLost) { switch (pauseMode) { // if the composition is configured to pause // the input manager when the focus is lost // note: for a stand alone player // CK_FOCUSLOST_PAUSEINPUT_MAIN and CK_FOCUSLOST_PAUSEINPUT_PLAYER // is the same thing. there is a difference only for the webplayer case CK_FOCUSLOST_PAUSEINPUT_MAIN: case CK_FOCUSLOST_PAUSEINPUT_PLAYER: // we pause/unpause it depending on the focus m_InputManager->Pause(!iFocus); break; // if the composition is configured to pause // the player (pause all) when the focus is lost case CK_FOCUSLOST_PAUSEALL: if (!iFocus) { // focus lost m_State = eFocusLost; // pause the player m_CKContext->Pause(); } else { // else m_State = ePlaying; // play m_CKContext->Play(); } break; } } } void CCustomPlayer::OnMouseClick(int iMessage) { // here we manage the mouse click if (!m_RenderContext) { return; } // retrieve the cursor position POINT pt; GetCursorPos(&pt); ScreenToClient(m_RenderWindow,&pt); // convert the windows message to the virtools message int msg = (iMessage==WM_LBUTTONDOWN)?m_MsgClick:m_MsgDoubleClick; // retrieve information about object "under" the mouse VxIntersectionDesc desc; CKObject* obj = m_RenderContext->Pick(pt.x,pt.y,&desc); if(obj && CKIsChildClassOf(obj,CKCID_BEOBJECT)) { // send a message to the beobject m_MessageManager->SendMessageSingle(msg,(CKBeObject*)obj); } if (desc.Sprite) { // send a message to the sprite m_MessageManager->SendMessageSingle(msg,(CKBeObject *)desc.Sprite); } } void CCustomPlayer::OnPaint() { if (!m_RenderContext || m_RenderContext->IsFullScreen()) { return; } // in windowed mode call render when WM_PAINT m_RenderContext->Render(); } <file_sep>/******************************************************************** created: 2008/01/14 created: 14:1:2008 12:02 filename: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer\stylepge.h file path: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer file base: stylepge file ext: h author: mc007 purpose: Displays and stores settings in/from the player.ini *********************************************************************/ #pragma once #include "resourceplayer.h" #include "afxwin.h" class CustomPlayerDialogGraphicPage : public CPropertyPage { // Construction public: CustomPlayerDialogGraphicPage(); // Dialog Data //{{AFX_DATA(CStylePage) enum { IDD = IDD_STYLE }; int m_nShapeStyle; int m_FSSA; //}}AFX_DATA // Overrides // ClassWizard generate virtual function overrides //{{AFX_VIRTUAL(CStylePage) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: virtual void OnOK(); // Generated message map functions //{{AFX_MSG(CStylePage) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() public: CComboBox m_windowMode; CListBox m_Driver; CComboBox m_FModes; CComboBox m_Bpps; CComboBox m_RRates; BOOL m_FullScreen; afx_msg void OnLbnSelchangeDriverList(); CButton m_FullScreenBtn; CComboBox m_CB_FSSA; afx_msg void OnCbnSelchangeCombo1(); afx_msg void OnCbnSelchangeCbFmode(); afx_msg void OnCbnSelchangeCbBpps(); afx_msg void OnCbnSelchangeCbRrates(); afx_msg void OnBnClickedCheckbFullscreen(); afx_msg void OnCbnSelchangeCbFssa(); }; <file_sep>#ifndef NX_PHYSICS_NXTARGETS #define NX_PHYSICS_NXTARGETS #include "NxSwTarget.h" #if NX_ENABLE_HW_PARSER #include "NxHwTarget.h" #endif #endif //AGCOPYRIGHTBEGIN /////////////////////////////////////////////////////////////////////////// // Copyright (c) 2007 AGEIA Technologies. // All rights reserved. www.ageia.com /////////////////////////////////////////////////////////////////////////// //AGCOPYRIGHTEND <file_sep>/****************************************************************************** Copyright (C) 1999, 2000 NVIDIA Corporation This file is provided without support, instruction, or implied warranty of any kind. NVIDIA makes no guarantee of its fitness for a particular purpose and is not liable under any circumstances for any damages or loss whatsoever arising from the use or inability to use this file or items derived from it. Comments: ******************************************************************************/ #include <windows.h> #include <dxfile.h> #include "rmxfguid.h" #include "rmxftmpl.h" #include "shared/nvfile.h" using namespace std; #ifndef SAFE_RELEASE #define SAFE_RELEASE(x) { if (x) { x->Release(); x = NULL; } } #endif HRESULT NVFile::LoadFrame( IDirect3DDevice9* pDevice, LPD3DXFILEDATA pFileData, NVFrame* pParentFrame ) { LPD3DXFILEDATA pChildData = NULL; GUID guid; DWORD cbSize; NVFrame* pCurrentFrame; HRESULT hr; // Get the type of the object if( FAILED( hr = pFileData->GetType( &guid ) ) ) return hr; if( guid == TID_D3DRMMesh ) { hr = LoadMesh( pDevice, pFileData, pParentFrame ); if( FAILED(hr) ) return hr; } if( guid == TID_D3DRMFrameTransformMatrix ) { D3DXMATRIX* pmatMatrix; hr = pFileData->Lock(&cbSize, (LPCVOID*)&pmatMatrix ); if( FAILED(hr) ) return hr; // Update the parent's matrix with the new one pParentFrame->SetMatrix( pmatMatrix ); } if( guid == TID_D3DRMFrame ) { // Get the frame name TCHAR strAnsiName[512] = _T(""); SIZE_T dwNameLength = 512; SIZE_T cChildren; #ifdef UNICODE CHAR tmp[512]; if( FAILED( hr = pFileData->GetName( tmp, &dwNameLength ) ) ) return hr; MultiByteToWideChar(CP_ACP,0,tmp,512,strAnsiName,512); #else if( FAILED( hr = pFileData->GetName( strAnsiName, &dwNameLength ) ) ) return hr; #endif // Create the frame pCurrentFrame = new NVFrame( strAnsiName ); if( pCurrentFrame == NULL ) return E_OUTOFMEMORY; pCurrentFrame->m_pNext = pParentFrame->m_pChild; pParentFrame->m_pChild = pCurrentFrame; // Enumerate child objects pFileData->GetChildren(&cChildren); for (UINT iChild = 0; iChild < cChildren; iChild++) { // Query the child for its FileData hr = pFileData->GetChild(iChild, &pChildData ); if( SUCCEEDED(hr) ) { hr = LoadFrame( pDevice, pChildData, pCurrentFrame ); SAFE_RELEASE( pChildData ); } if( FAILED(hr) ) return hr; } } return S_OK; } HRESULT NVFile::LoadMesh( IDirect3DDevice9* pDevice, LPD3DXFILEDATA pFileData, NVFrame* pParentFrame ) { // Currently only allowing one mesh per frame if( pParentFrame->m_pMesh ) return E_FAIL; // Get the mesh name TCHAR strAnsiName[512] = {0}; SIZE_T dwNameLength = 512; HRESULT hr; #ifdef UNICODE CHAR tmp[512]; if( FAILED( hr = pFileData->GetName( tmp, &dwNameLength ) ) ) return hr; MultiByteToWideChar(CP_ACP,0,tmp,512,strAnsiName,512); #else if( FAILED( hr = pFileData->GetName( strAnsiName, &dwNameLength ) ) ) return hr; #endif // Create the mesh pParentFrame->m_pMesh = new NVMesh( strAnsiName ); if( pParentFrame->m_pMesh == NULL ) return E_OUTOFMEMORY; pParentFrame->m_pMesh->Create( pDevice, pFileData ); return S_OK; } HRESULT NVFile::Create( IDirect3DDevice9* pDevice, const tstring& strPathname ) { LPD3DXFILE pDXFile = NULL; LPD3DXFILEENUMOBJECT pEnumObj = NULL; LPD3DXFILEDATA pFileData = NULL; HRESULT hr; SIZE_T cChildren; tstring::size_type Pos = strPathname.find_last_of(_T("\\"), strPathname.size()); if (Pos != strPathname.npos) { // Make sure we are on the right path for loading resources associated with this file m_strFilePath = strPathname.substr(0, Pos); SetCurrentDirectory(m_strFilePath.c_str()); } // Create a x file object if( FAILED( hr = D3DXFileCreate( &pDXFile ) ) ) return E_FAIL; // Register templates for d3drm and patch extensions. if( FAILED( hr = pDXFile->RegisterTemplates( (VOID*)D3DRM_XTEMPLATES, D3DRM_XTEMPLATE_BYTES ) ) ) { SAFE_RELEASE( pDXFile ); return E_FAIL; } #ifdef UNICODE int len = WideCharToMultiByte(CP_ACP,0,strPathname.c_str(),-1,NULL,NULL,NULL,NULL); char *tmp = new char[len]; WideCharToMultiByte(CP_ACP,0,strPathname.c_str(),-1,tmp,len,NULL,NULL); hr = pDXFile->CreateEnumObject( (VOID*)tmp, D3DXF_FILELOAD_FROMFILE, &pEnumObj ); #else // Create enum object hr = pDXFile->CreateEnumObject( (VOID*)strPathname.c_str(), D3DXF_FILELOAD_FROMFILE, &pEnumObj ); #endif if (FAILED(hr)) { SAFE_RELEASE( pDXFile ); return hr; } // Enumerate top level objects (which are always frames) pEnumObj->GetChildren(&cChildren); for (UINT iChild = 0; iChild < cChildren; iChild++) { hr = pEnumObj->GetChild(iChild, &pFileData); if (FAILED(hr)) return hr; hr = LoadFrame( pDevice, pFileData, this ); SAFE_RELEASE( pFileData ); if( FAILED(hr) ) { SAFE_RELEASE( pEnumObj ); SAFE_RELEASE( pDXFile ); return E_FAIL; } } SAFE_RELEASE( pFileData ); SAFE_RELEASE( pEnumObj ); SAFE_RELEASE( pDXFile ); return S_OK; } HRESULT NVFile::Render( IDirect3DDevice9* pDevice ) { // Setup the world transformation D3DXMATRIX matSavedWorld, matWorld; pDevice->GetTransform(D3DTS_WORLD, &matSavedWorld); D3DXMatrixMultiply( &matWorld, &matSavedWorld, &m_mat ); pDevice->SetTransform(D3DTS_WORLD, &matWorld ); // Render opaque subsets in the meshes if( m_pChild ) m_pChild->Render( pDevice, TRUE, FALSE ); // Enable alpha blending pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); pDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); pDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); // Render alpha subsets in the meshes if( m_pChild ) m_pChild->Render( pDevice, FALSE, TRUE ); // Restore state pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); pDevice->SetTransform(D3DTS_WORLD, &matSavedWorld ); return S_OK; } bool CalcFileObjectSizeCB( NVFrame* pFrame, D3DXMATRIX* pMat, VOID* pfSize ) { NVBounds* pBounds = (NVBounds*)pfSize; NVMesh* pMesh = pFrame->m_pMesh; DWORD dwStride = 0; if (!pMesh) { return true; } // Get the bounds for the mesh and transform them by the local // world transform. NVBounds MeshBounds = *pMesh->GetBounds(); MeshBounds.Transform(pMat); if (pBounds->m_vecMaxExtents.x < MeshBounds.m_vecMaxExtents.x) pBounds->m_vecMaxExtents.x = MeshBounds.m_vecMaxExtents.x; if (pBounds->m_vecMaxExtents.y < MeshBounds.m_vecMaxExtents.y) pBounds->m_vecMaxExtents.y = MeshBounds.m_vecMaxExtents.y; if (pBounds->m_vecMaxExtents.z < MeshBounds.m_vecMaxExtents.z) pBounds->m_vecMaxExtents.z = MeshBounds.m_vecMaxExtents.z; if (pBounds->m_vecMinExtents.x > MeshBounds.m_vecMinExtents.x) pBounds->m_vecMinExtents.x = MeshBounds.m_vecMinExtents.x; if (pBounds->m_vecMinExtents.y > MeshBounds.m_vecMinExtents.y) pBounds->m_vecMinExtents.y = MeshBounds.m_vecMinExtents.y; if (pBounds->m_vecMinExtents.z > MeshBounds.m_vecMinExtents.z) pBounds->m_vecMinExtents.z = MeshBounds.m_vecMinExtents.z; if (pBounds->m_fRadius < MeshBounds.m_fRadius) pBounds->m_fRadius = MeshBounds.m_fRadius; return true; } //----------------------------------------------------------------------------- // Name: GetBoundingInfo() // Desc: //----------------------------------------------------------------------------- void NVFile::GetBoundingInfo(NVBounds* pBounds) { pBounds->m_vecCenter = D3DXVECTOR3(0.0f, 0.0f, 0.0f); pBounds->m_fRadius = 0.0f; pBounds->m_vecMinExtents = D3DXVECTOR3(FLT_MAX, FLT_MAX, FLT_MAX); pBounds->m_vecMaxExtents = D3DXVECTOR3(-FLT_MAX, -FLT_MAX, -FLT_MAX); D3DXMATRIX Matrix; D3DXMatrixIdentity(&Matrix); WalkFrames(CalcFileObjectSizeCB, &Matrix, (VOID*)pBounds); pBounds->m_vecCenter = (pBounds->m_vecMaxExtents + pBounds->m_vecMinExtents) / 2.0f; } <file_sep>#include "stdafx2.h" #include "resource.h" #include "PBodyTabCtrl.h" #include "PBodyQuickPage.h" /*#include "TabOne.h" #include "TabTwo.h" #include "TabThree.h" */ #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // PBodyTabContrl IMPLEMENT_DYNCREATE(PBodyTabContrl,VITabCtrl) PBodyTabContrl::PBodyTabContrl(CWnd*win) { //PBodyTabContrl m_tabPages[0]=new PBodyQuickPage(); if (m_tabPages[0]) { m_nNumberOfPages=1; } /*m_tabPages[1]=new CTabTwo; m_tabPages[2]=new CTabThree; */ m_nNumberOfPages=1; } PBodyTabContrl::PBodyTabContrl() : VITabCtrl() { //PBodyTabContrl m_tabPages[0]=new PBodyQuickPage(); if (m_tabPages[0]) { m_nNumberOfPages=1; } /*m_tabPages[1]=new CTabTwo; m_tabPages[2]=new CTabThree; */ m_nNumberOfPages=1; } PBodyTabContrl::~PBodyTabContrl() { for(int nCount=0; nCount < m_nNumberOfPages; nCount++){ delete m_tabPages[nCount]; } } void PBodyTabContrl::_construct() { VITabCtrl::EnableWindow(true); VITabCtrl::EnableAutomation(); VITabCtrl::ShowWindow(SW_SHOW); AFX_MANAGE_STATE(AfxGetStaticModuleState()); m_tabCurrent=0; //m_tabPages[0]->Create(IDD_PBCOMMON, this); //m_tabPages[1]->Create(IDD_PBCOMMON, this); //m_tabPages[0]->ShowWindow(SW_SHOW); //m_tabPages[1]->ShowWindow(SW_SHOW); //m_tabPages[1]->ShowWindow(SW_SHOW); //m_tabPages[2]->ShowWindow(SW_HIDE); m_nNumberOfPages = 1; SetRectangle(); } void PBodyTabContrl::Init() { //VITabCtrl::UpdateWindow(); } void PBodyTabContrl::SetRectangle() { CRect tabRect, itemRect; int nX, nY, nXc, nYc; GetClientRect(&tabRect); CRect r; ((CTabCtrl *)(this))->GetItemRect(0, &itemRect); //TabCtrl_GetItemRect(0, &itemRect); //GetItemRect nX=itemRect.left; nY=itemRect.bottom+1; nXc=tabRect.right-itemRect.left-1; nYc=tabRect.bottom-nY-1; /* m_tabPages[0]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_SHOWWINDOW); for(int nCount=1; nCount < m_nNumberOfPages; nCount++){ m_tabPages[nCount]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_HIDEWINDOW); }*/ } BEGIN_MESSAGE_MAP(PBodyTabContrl, VITabCtrl) //{{AFX_MSG_MAP(PBodyTabContrl) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // PBodyTabContrl message handlers /* void PBodyTabContrl::OnLButtonDown(UINT nFlags, CPoint point) { CTabCtrl &tabContr = ((CTabCtrl*)(this)); tabContr::OnLButtonDown(nFlags, point); if(m_tabCurrent != (CTabCtrl*)GetCurFocus()){ m_tabPages[m_tabCurrent]->ShowWindow(SW_HIDE); m_tabCurrent=GetCurFocus(); m_tabPages[m_tabCurrent]->ShowWindow(SW_SHOW); m_tabPages[m_tabCurrent]->SetFocus(); } } */<file_sep>int EncryptPassword(char* pcPassword); <file_sep> #include "xNetInterface.h" #include "vtConnection.h" #include <tnlAsymmetricKey.h> //#include "windows.h" TNL::RefPtr<xNetInterface>m_NetInterfaceServer = NULL; TNL::RefPtr<xNetInterface>GetServerInterface(){ return m_NetInterfaceServer;} const char *localBroadcastAddress = "IP:broadcast:28999"; const char *localHostAddress = "IP:127.0.0.1:28999"; const char *localServerAddress ="IP:Any:28999"; #include "xLogger.h" #include "IMessages.h" class DedicatedServerLogConsumer : public TNL::LogConsumer { public: void logString(const char *string) { //ctx()->OutputToConsoleEx("%s\n",string); printf("%s\n\n", string); } } gDedicatedServerLogConsumer; using namespace TNL; float mLastTime=0.0; #include <stdio.h> #include <conio.h> #include <ctype.h> #include <process.h> #include <tchar.h> #include "xNetConstants.h" HANDLE m_hPromptThread; bool m_bQuitThread = false; UINT WINAPI PromptThread( LPVOID pParam ); //----------------------------------------------------------------------------- // Name: ParseInput // Desc: Handle user input //----------------------------------------------------------------------------- void ParseInput( TCHAR* buffer ) { TCHAR* token = _tcstok( buffer, TEXT(" \t") ); if( token == NULL ) return; _tcsupr( token ); if( !_tcscmp( token, TEXT("LOGLEVEL") ) || !_tcscmp( token, TEXT("SETLOG") )) { token = _tcstok( NULL, TEXT(" \t") ); int component = 0; int level = 0; int value = 0; if( token ) { component = _ttol( token ); } token = _tcstok( NULL, TEXT(" \t") ); if( token ) { level = _ttol( token ); } token = _tcstok( NULL, TEXT(" \t") ); if( token ) { value = _ttol( token ); } token = NULL; if (GetServerInterface()) { GetServerInterface()->enableLogLevel(component,level,value); } return; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// if( !_tcscmp( token, TEXT("STATS") ) || !_tcscmp( token, TEXT("PRINT") ) ) { token = _tcstok( NULL, TEXT(" \t") ); int component = 0; if( token ) { component = _ttol( token ); if (GetServerInterface()) { GetServerInterface()->printObjects(component,component); } }else { if (GetServerInterface()) { GetServerInterface()->printObjects(0,0); } } return; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// if( !_tcscmp( token, TEXT("SETMSGMINTIME") ) || !_tcscmp( token, TEXT("MMTIME") ) ) { token = _tcstok( NULL, TEXT(" \t") ); float component = 0; if( token ) { component = (float)_ttol( token ); if (GetServerInterface()) { GetServerInterface()->getMessagesInterface()->setThresoldTicker(component); } } return; } if( !_tcscmp( token, TEXT("SETMSGTIMEOUT") ) || !_tcscmp( token, TEXT("MTOUT") ) ) { token = _tcstok( NULL, TEXT(" \t") ); float component = 0; if( token ) { component = (float)_ttol( token ); if (GetServerInterface()) { GetServerInterface()->getMessagesInterface()->setMessageTimeout(component); } } return; } if( !_tcscmp( token, TEXT("HELP") ) || !_tcscmp( token, TEXT("?") ) ) { xLogger::xLog(ELOGINFO,E_LI_CPP,"Print component index for command setLog"); for (int i = 0 ; i < 16 ; i++ ) { xLogger::xLogExtro(0,"Index : %d : \t %s",i,sLogItems[i]); } xLogger::xLog(ELOGINFO,E_LI_CPP,"Print verbosity levels"); xLogger::xLogExtro(0,"0 : DEBUG"); xLogger::xLogExtro(0,"1 : TRACE"); xLogger::xLogExtro(0,"2 : ERROR"); xLogger::xLogExtro(0,"3 : WARNING"); xLogger::xLogExtro(0,"4 : INFO"); xLogger::xLogExtro(0,"\t write 'setLog 1 2 1' to enable all session related errors" ); xLogger::xLogExtro(0,"\t write 'setLog 1 2 0' to disable all session related errors \n" ); xLogger::xLog(ELOGINFO,E_LI_CPP,"commands :"); xLogger::xLogExtro(0,"\t print [Index]:0-4 : prints object informations\n" ); xLogger::xLogExtro(0,"\t setMsgMinTime [value]:5-x ms : sets minimum time between message sending\n" ); xLogger::xLogExtro(0,"\t setMsgTimeout [value]:5-x ms : sets message lifetime,\n" ); return; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// if( !_tcscmp( token, TEXT("STOP") ) || !_tcscmp( token, TEXT("QUIT") ) || !_tcscmp( token, TEXT("EXIT") ) ) { m_bQuitThread = TRUE; } } void DoPrompt( TCHAR* strPromptString, TCHAR* strBuffer ) { //m_pMazeApp->ConsolePrintf( LINE_PROMPT, strPromptString ); DWORD dwRead; BOOL bSuccess; bSuccess = ReadConsole( GetStdHandle(STD_INPUT_HANDLE), strBuffer, 128, &dwRead, NULL ); if( !bSuccess || dwRead < 2 ) { _tcscpy( strBuffer, TEXT("") ); return; } strBuffer[dwRead-2]=0; //m_pMazeApp->ConsolePrintf( LINE_INPUT, strBuffer ); } UINT WINAPI StaticPromptThread( LPVOID pParam ) { return PromptThread( pParam ); } //----------------------------------------------------------------------------- // Name: PromptThread // Desc: Thread body for infite command prompts //----------------------------------------------------------------------------- UINT WINAPI PromptThread( LPVOID pParam ) { // Loop around getting and dealing with keyboard input TCHAR buffer[512]; while( !m_bQuitThread ) { DoPrompt( TEXT("Command> "), buffer ); ParseInput( buffer ); }; //_tprintf( TEXT("Stopping...") ); return 0; } int main(int argc, const char **argv) { xLogger::GetInstance()->addLogItem(E_LI_SESSION); //xLogger::GetInstance()->enableLoggingLevel(E_LI_SESSION,ELOGINFO,1); xLogger::GetInstance()->addLogItem(E_LI_CLIENT); xLogger::GetInstance()->addLogItem(E_LI_3DOBJECT); xLogger::GetInstance()->addLogItem(E_LI_2DOBJECT); xLogger::GetInstance()->addLogItem(E_LI_DISTRIBUTED_BASE_OBJECT); xLogger::GetInstance()->addLogItem(E_LI_DISTRIBUTED_CLASS_DESCRIPTORS); xLogger::GetInstance()->addLogItem(E_LI_MESSAGES); xLogger::GetInstance()->addLogItem(E_LI_ARRAY_MESSAGES); xLogger::GetInstance()->addLogItem(E_LI_CONNECTION); xLogger::GetInstance()->addLogItem(E_LI_NET_INTERFACE); xLogger::GetInstance()->addLogItem(E_LI_GHOSTING); xLogger::GetInstance()->addLogItem(E_LI_STATISTICS); xLogger::GetInstance()->addLogItem(E_LI_BUILDINGBLOCKS); xLogger::GetInstance()->addLogItem(E_LI_VSL); xLogger::GetInstance()->addLogItem(E_LI_CPP); xLogger::GetInstance()->enableLoggingLevel(E_LI_CPP,ELOGINFO,1); xLogger::GetInstance()->addLogItem(E_LI_ASSERTS); xLogger::GetInstance()->addLogItem(E_LI_PREDICTION); xLogger::GetInstance()->addLogItem(E_LI_SERVER_MESSAGES); xLogger::GetInstance()->addItemDescription("Session"); xLogger::GetInstance()->addItemDescription("Client"); xLogger::GetInstance()->addItemDescription("3dObject"); xLogger::GetInstance()->addItemDescription("2dObject"); xLogger::GetInstance()->addItemDescription("DistBase Object"); xLogger::GetInstance()->addItemDescription("DistClassDescr"); xLogger::GetInstance()->addItemDescription("Messages"); xLogger::GetInstance()->addItemDescription("ArrayMessages"); xLogger::GetInstance()->addItemDescription("Connection"); xLogger::GetInstance()->addItemDescription("NetInterface"); xLogger::GetInstance()->addItemDescription("Ghosting"); xLogger::GetInstance()->addItemDescription("Stats"); xLogger::GetInstance()->addItemDescription("BB"); xLogger::GetInstance()->addItemDescription("VSL"); xLogger::GetInstance()->addItemDescription("CPP"); xLogger::GetInstance()->addItemDescription("Asserts"); xLogger::GetInstance()->addItemDescription("Prediction"); xLogger::GetInstance()->addItemDescription("ServerMsg"); TNLLogEnable(LogNetInterface,true); ////////////////////////////////////////////////////////////////////////// //create a server : TNL::Address *add = new TNL::Address("IP:Any:28999"); TNL::Address *addBC=new TNL::Address("IP:broadcast:28999"); m_NetInterfaceServer = new xNetInterface(true,*add,*addBC); TNL::AsymmetricKey *theKey = new TNL::AsymmetricKey(32); m_NetInterfaceServer->setPrivateKey(theKey); m_NetInterfaceServer->setRequiresKeyExchange(false); if (m_NetInterfaceServer) { m_NetInterfaceServer->setAllowsConnections(true); } //Sleep(2000); if (GetServerInterface() && GetServerInterface()->getSocket().isValid() ) { //logprintf("\t Server Created"); xLogger::xLog(ELOGINFO,E_LI_CPP,"Server created"); xLogger::xLog(ELOGINFO,E_LI_CPP,"enter '?' for available commands !" ); }else{ xLogger::xLog(ELOGERROR,E_LI_CPP,"Couldn't create socket"); } UINT dwPromptThreadID; m_hPromptThread = (HANDLE)_beginthreadex( NULL, 0, StaticPromptThread, NULL, 0, &dwPromptThreadID ); for (;;) { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); float timeDelta = (currentTime - mLastTime); mLastTime = (float)currentTime; GetServerInterface()->getMessagesInterface()->advanceTime(timeDelta); GetServerInterface()->tick(); GetServerInterface()->getMessagesInterface()->checkMessages(); GetServerInterface()->getMessagesInterface()->deleteAllOldMessages(); if (m_bQuitThread) { GetServerInterface()->destroy(); break; } /*char message[400]; gets(message); if (!strcmp(message,"exit")) { break; } while (kbhit()){ getch(); }*/ TNL::Platform::sleep(1); } return 0; } <file_sep>/******************************************************************** created: 2009/04/14 created: 14:4:2009 11:29 filename: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Src\Core\DataManagerRemote.cpp file path: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Src\Core file base: DataManagerRemote file ext: cpp author: <NAME> purpose: handles remote messages *********************************************************************/ #include "StdAfx.h" #include "DataManager.h" #ifdef G_EXTERNAL_ACCESS #include "MemoryFileMappingTypes.h" #include <process.h> #include "AutoLock.h" #include "vtGUID.h" using namespace AutoLock; vtExternalEvent *Msg; HANDLE hmem = NULL; int post = 0; HANDLE m_hLogItemSendEvent = ::CreateEvent(NULL,TRUE,FALSE,"LogItemSendEventName"); HANDLE m_hShutdownEvent = ::CreateEvent(NULL,FALSE,FALSE,"SendRcvShutdownEvent"); HANDLE m_hLogItemReceivedEvent = ::CreateEvent(NULL,FALSE,FALSE,"LogItemReceivedEventName"); HANDLE aHandles[] = { m_hShutdownEvent , m_hLogItemSendEvent }; BOOL recieved = false; BOOL changed = true; int DataManager::_SharedMemoryTickPost(int flagsOfWhatever) { if (!changed){ SetEvent( m_hShutdownEvent ); } return CK_OK; return 0; } int DataManager::_SharedMemoryTick(int flagsOfWhatever) { HRESULT hr = S_OK; //USES_CONVERSION; switch( ::WaitForMultipleObjects(sizeof(aHandles) /sizeof(HANDLE),&(aHandles[0]),FALSE,1)) { case WAIT_OBJECT_0: { SetEvent( m_hShutdownEvent ); break; } case WAIT_OBJECT_0 + 1: { try { CLockableMutex m_mtxMMFile("sharedMem"); CAutoLockT< CLockableMutex > lock(&m_mtxMMFile, 5000 ); vtExternalEvent *pLI = reinterpret_cast<vtExternalEvent*>(m_pData); //XString command(pLI->command); //XString commandArg(pLI->commandArg); XString msgStr; msgStr.Format("Remote Message:%s",pLI->command); m_Context->OutputToConsole(msgStr.Str(),FALSE); changed = true; SetEvent( m_hLogItemReceivedEvent ); ::ResetEvent(m_hShutdownEvent); return CK_OK; } catch( CAutoLockTimeoutExc ) { hr = HRESULT_FROM_WIN32( WAIT_TIMEOUT ); } catch( CAutoLockWaitExc& e ) { hr = HRESULT_FROM_WIN32( e.GetLastError() ); } break; } // default: // ATLASSERT(0); } return CK_OK; } int DataManager::_initSharedMemory(int flagsOfWhatever) { if( NULL != ( m_hMMFile = CreateFileMapping( INVALID_HANDLE_VALUE, NULL,PAGE_READWRITE,0, sizeof( vtExternalEvent ),"sharedMemFile" ) ))//_T("LogSndRcvMMF") ))) { if( NULL != (m_pData = (vtExternalEvent*)::MapViewOfFile(m_hMMFile, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, sizeof( vtExternalEvent* )) ) ) { return S_OK; } } return HRESULT_FROM_WIN32( ::GetLastError( ) ); } #endif <file_sep>/******************************************************************** created: 2007/11/28 created: 28:11:2007 16:25 filename: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Dialogs\CustomPlayerConfigurationDialog.cpp file path: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Dialogs file base: CustomPlayerConfigurationDialog file ext: cpp author: mc007 purpose: *********************************************************************/ #include <CPStdAfx.h> #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "resource.h" ////////////////////////////////////////////////////////////////////////// // // // // ////////////////////////////////////////////////////////////////////////// extern CCustomPlayerApp theApp; extern CCustomPlayer* thePlayer; INT_PTR CALLBACK ConfigureDialogProcHelper( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { return GetApp()->ConfigureDialogProc( hwndDlg, uMsg, wParam, lParam ); } ////////////////////////////////////////////////////////////////////////// // void CCustomPlayerApp::DoConfig() { DialogBox( m_hInstance, MAKEINTRESOURCE(IDD_DIALOG1), m_MainWindow , (DLGPROC)ConfigureDialogProcHelper ); } ////////////////////////////////////////////////////////////////////////// // struct _dinfo { int _w,_h,_bpp,_hz; _dinfo():_w(0), _h(0),_bpp(0),_hz(0){} _dinfo(int w,int h,int bpp,int hz) : _w(w), _h(h),_bpp(bpp),_hz(hz){} }; #include <stdlib.h> #include <vector> std::vector<_dinfo>_modes; _dinfo _current; _dinfo *_currentW=NULL; int _currentDriver=-1; int _currentWMode=-1; int currentRes=-1; int currentBpp=-1; int currentRRate = -1; int currentFSSA = -1; void _UpdateLists(HWND hwndDlg,int DriverId) { vtPlayer::Structs::xSEnginePointers* ep = GetPlayer().GetEnginePointers(); vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); int count = GetPlayer().GetEnginePointers()->TheRenderManager->GetRenderDriverCount(); int i,index; char ChaineW[256]; bool driverfound = false; SendDlgItemMessage(hwndDlg,IDC_LISTMODE,LB_RESETCONTENT,0,0); SendDlgItemMessage(hwndDlg,IDC_LISTDRIVER,LB_RESETCONTENT,0,0); SendDlgItemMessage(hwndDlg,IDCB_BPP,CB_RESETCONTENT,0,0); SendDlgItemMessage(hwndDlg,IDCB_RRATE,CB_RESETCONTENT,0,0); SendDlgItemMessage(hwndDlg,IDCB_RRATE,CB_RESETCONTENT,0,0); SendDlgItemMessage(hwndDlg,IDC_WINSIZE,CB_RESETCONTENT,0,0); ////////////////////////////////////////////////////////////////////////// //we fill the driver list : for (i=0;i<count;i++) { VxDriverDesc *desc=ep->TheRenderManager->GetRenderDriverDescription(i); index=SendDlgItemMessage(hwndDlg,IDC_LISTDRIVER,LB_ADDSTRING,0,(LPARAM)desc->DriverName.CStr()); SendDlgItemMessage(hwndDlg,IDC_LISTDRIVER,LB_SETITEMDATA,index,i); ////////////////////////////////////////////////////////////////////////// //we set the driver in the listbox to driver we found in the player.ini if (i==DriverId) { SendDlgItemMessage(hwndDlg,IDC_LISTDRIVER,LB_SETCURSEL,index,0); driverfound = true; } } //FullScreen : SendDlgItemMessage(hwndDlg,IDC_CHB_FULLSCREEN,BM_SETCHECK,ewinfo->g_GoFullScreen,0); VxDriverDesc *MainDesc=ep->TheRenderManager->GetRenderDriverDescription(ewinfo->g_FullScreenDriver); XArray<int> bpps;//temporary storage to avoid doubles in the list XArray<int> rrates;//temporary storage to avoid doubles in the list XArray<int>modes;//temporary storage to avoid doubles in the list ////////////////////////////////////////////////////////////////////////// //we only display window resolutions according to the current display settings: HDC hdc; PAINTSTRUCT ps ; hdc = BeginPaint (hwndDlg, &ps) ; int currentDesktopBpp = GetDeviceCaps (hdc, BITSPIXEL) ; int currentDesktopRRate = GetDeviceCaps (hdc, VREFRESH) ; EndPaint(hwndDlg,&ps); ////////////////////////////////////////////////////////////////////////// //we fill the bpp and the refresh rate combo boxes : for (i=0;i<MainDesc->DisplayModes.Size();i++) { XArray<int>::Iterator it = bpps.Find(MainDesc->DisplayModes[i].Bpp); if( it == bpps.End() ) { bpps.PushBack(MainDesc->DisplayModes[i].Bpp); sprintf(ChaineW,"%d",MainDesc->DisplayModes[i].Bpp); index = SendDlgItemMessage(hwndDlg,IDCB_BPP,CB_ADDSTRING,0,(LPARAM)ChaineW); SendDlgItemMessage(hwndDlg,IDCB_BPP,CB_SETITEMDATA,index,i); if (ewinfo->g_Bpp== MainDesc->DisplayModes[i].Bpp) { SendDlgItemMessage(hwndDlg,IDCB_BPP,CB_SETCURSEL,index,0); } } it = rrates.Find(MainDesc->DisplayModes[i].RefreshRate); if( it == rrates.End() ) { rrates.PushBack(MainDesc->DisplayModes[i].RefreshRate); sprintf(ChaineW,"%d",MainDesc->DisplayModes[i].RefreshRate); index = SendDlgItemMessage(hwndDlg,IDCB_RRATE,CB_ADDSTRING,0,(LPARAM)ChaineW); SendDlgItemMessage(hwndDlg,IDCB_RRATE,CB_SETITEMDATA,index,i); if (ewinfo->g_RefreshRate == MainDesc->DisplayModes[i].RefreshRate) { SendDlgItemMessage(hwndDlg,IDCB_RRATE,CB_SETCURSEL,index,0); } } ////////////////////////////////////////////////////////////////////////// XString mode;mode<<MainDesc->DisplayModes[i].Width<<MainDesc->DisplayModes[i].Height; it = modes.Find(mode.ToInt()); if( it == modes.End() ) { modes.PushBack(mode.ToInt()); sprintf(ChaineW,"%d x %d",MainDesc->DisplayModes[i].Width,MainDesc->DisplayModes[i].Height); index=SendDlgItemMessage(hwndDlg,IDC_LISTMODE,LB_ADDSTRING,0,(LPARAM)ChaineW); SendDlgItemMessage(hwndDlg,IDC_LISTMODE,LB_SETITEMDATA,index,i); if (ewinfo->g_Height == MainDesc->DisplayModes[i].Height && ewinfo->g_Width == MainDesc->DisplayModes[i].Width ) { SendDlgItemMessage(hwndDlg,IDC_LISTMODE,LB_SETCURSEL,index,0); SendDlgItemMessage(hwndDlg,IDC_LISTMODE,LB_SETTOPINDEX,index,0); } int iRRate = MainDesc->DisplayModes[i].RefreshRate; int iBpp = MainDesc->DisplayModes[i].Bpp; int h= iRRate; if (MainDesc->DisplayModes[i].Bpp == currentDesktopBpp && MainDesc->DisplayModes[i].RefreshRate == currentDesktopRRate ) { index=SendDlgItemMessage(hwndDlg,IDC_WINSIZE,CB_ADDSTRING,0,(LPARAM)ChaineW); SendDlgItemMessage(hwndDlg,IDC_WINSIZE,CB_SETITEMDATA,index,i); if (ewinfo->g_HeightW == MainDesc->DisplayModes[i].Height && ewinfo->g_WidthW == MainDesc->DisplayModes[i].Width ) { SendDlgItemMessage(hwndDlg,IDC_WINSIZE,CB_SETCURSEL,index,0); SendDlgItemMessage(hwndDlg,IDC_WINSIZE,CB_SETTOPINDEX,index,0); } } } } } INT_PTR CALLBACK CCustomPlayerApp::ConfigureDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { WORD wNotifyCode = HIWORD(wParam); int wID = LOWORD(wParam); vtPlayer::Structs::xSEnginePointers* ep = GetPlayer().GetEnginePointers(); vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); switch (uMsg) { case WM_INITDIALOG: { //bpp,rrate,res,resW,driver: _UpdateLists(hwndDlg,ewinfo->g_FullScreenDriver); //FSSA : switch(ewinfo->FSSA) { case 0: SendDlgItemMessage(hwndDlg,IDC_FSSA_0,BM_SETCHECK,1,0); break; case 1: SendDlgItemMessage(hwndDlg,IDC_FSSA_1,BM_SETCHECK,1,0); break; case 2: SendDlgItemMessage(hwndDlg,IDC_FSSA_2,BM_SETCHECK,1,0); break; default: SendDlgItemMessage(hwndDlg,IDC_FSSA_0,BM_SETCHECK,1,0); break; } } return FALSE; case WM_COMMAND: int prevWidth=0,prevHeight=0,prevBpp=0; if (wNotifyCode==LBN_SELCHANGE) { if (wID==IDC_LISTDRIVER) { int index=SendDlgItemMessage(hwndDlg,IDC_LISTDRIVER,LB_GETCURSEL,0,0); _UpdateLists(hwndDlg,index); return FALSE; } if (wID==IDC_LISTMODE) { currentRes = SendDlgItemMessage(hwndDlg,IDC_LISTMODE,LB_GETCURSEL,0,0); //VxDriverDesc *MainDesc=ep->TheRenderManager->GetRenderDriverDescription(ewinfo->g_FullScreenDriver); return FALSE; } } if(wNotifyCode==BN_CLICKED) { if (wID==IDC_FSSA_0) { currentFSSA = 0; return FALSE; } if (wID==IDC_FSSA_1) { currentFSSA = 1; return FALSE; } if (wID==IDC_FSSA_2) { currentFSSA = 2; return FALSE; } } if (wNotifyCode==CBN_SELCHANGE ) { if (wID==IDC_WINSIZE) { _currentWMode =SendDlgItemMessage(hwndDlg,IDC_WINSIZE,CB_GETCURSEL,0,0); return FALSE; } if (wID==IDCB_BPP) { currentBpp =SendDlgItemMessage(hwndDlg,IDCB_BPP,CB_GETCURSEL,0,0); return FALSE; } if (wID==IDCB_RRATE) { currentRRate =SendDlgItemMessage(hwndDlg,IDCB_RRATE,CB_GETCURSEL,0,0); return FALSE; } } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// if (LOWORD(wParam) == IDC_CANCEL2){ EndDialog(hwndDlg, LOWORD(wParam)); SendNotifyMessageW(m_MainWindow,WM_CLOSE,0,0); return TRUE; } if (LOWORD(wParam) == IDOK) { //fssa : if(currentFSSA>=0) ewinfo->FSSA = currentFSSA; //fullscreen : ewinfo->g_GoFullScreen = IsDlgButtonChecked(hwndDlg, IDC_CHB_FULLSCREEN ) == BST_CHECKED; //bpp if(currentBpp>=0){ TCHAR szText[_MAX_PATH + 1]; SendDlgItemMessage(hwndDlg,IDCB_BPP, CB_GETLBTEXT, (WPARAM)currentBpp, (LPARAM)szText); XString o(szText); ewinfo->g_Bpp = o.ToInt(); } //refresh rate if (currentRRate>=0) { TCHAR szText[_MAX_PATH + 1]; SendDlgItemMessage(hwndDlg,IDCB_RRATE, CB_GETLBTEXT, (WPARAM)currentRRate, (LPARAM)szText); XString o(szText); ewinfo->g_RefreshRate = o.ToInt(); } //full screen settings if (currentRes>=0) { int index=SendDlgItemMessage(hwndDlg,IDC_LISTMODE,LB_GETCURSEL,0,0); TCHAR szText[MAX_PATH]; SendDlgItemMessage(hwndDlg,IDC_LISTMODE, LB_GETTEXT, index, ((LPARAM)szText)); XStringTokenizer tokizer(szText, " x "); const char*tok = NULL; tok = tokizer.NextToken(tok); XString width(tok); tok = tokizer.NextToken(tok); XString height(tok); ewinfo->g_Width = width.ToInt(); ewinfo->g_Height = height.ToInt(); } if (_currentWMode>=0) { TCHAR szText[_MAX_PATH + 1]; SendDlgItemMessage(hwndDlg,IDC_WINSIZE, CB_GETLBTEXT, (WPARAM)_currentWMode, (LPARAM)szText); MessageBox(NULL,szText,"",1); XStringTokenizer tokizer(szText, "x"); const char*tok = NULL; tok = tokizer.NextToken(tok); XString width(tok); tok = tokizer.NextToken(tok); XString height(tok); ewinfo->g_WidthW = width.ToInt(); ewinfo->g_HeightW = height.ToInt(); } EndDialog(hwndDlg, LOWORD(wParam)); PSaveEngineWindowProperties(CUSTOM_PLAYER_CONFIG_FILE,*GetPlayer().GetEngineWindowInfo()); SendNotifyMessageW(m_MainWindow,WM_CLOSE,0,0); return TRUE; } } return FALSE; } <file_sep>#ifndef _XNET_CONSTANTS_H_ #define _XNET_CONSTANTS_H_ //#include "xNetTypes.h" static float DO_TIME_THRESHOLD = 150.0f; static char* sLogItems[]= { "CLIENT", "SESSION", "3DOBJECT", "2DOBJECT", "Distributed Base Object", "Distributed Classes", "MESSAGES", "ARRAY_MESSAGES", "CONNECTION", "NET_INTERFACE", "GHOSTING", "STATISTICS", "BUILDINGBLOCKS", "VSL", "CPP", "ASSERTS", "PREDICTION", "SERVER_MESSAGES" }; static char* sErrorStrings[]= { "OK", "\t Intern :", "\t No connection :", "\t Not joined to a session:", "\t Session needs right password:", "\t Session is locked:", "\t Session already exists:", "\t Session is full:", "\t You must be session master:", "\t Invalid parameter :", "\t There is not such user :", "\t Distributed class already exists :", "\t Couldn't connect to any server :", "\t You already joined to a session :", "\t No such session :" }; #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" static pFactory* pFact = NULL; int pFactory::cloneLimitPlanes(pJoint *src,pJoint *dst,CK3dEntity *srcReference,CK3dEntity *dstReference) { //---------------------------------------------------------------- // // sanity checks // #ifdef _DEBUG assert(src); assert(dst); assert(dstReference); assert(srcReference); #endif // _DEBUG NxJoint *j = src->getJoint(); if (!j) return 0; int numLimitPlanes = src->getNbLimitPlanes(); if (!numLimitPlanes) return -1; NxVec3 *planeNormal = new NxVec3[numLimitPlanes]; NxReal *planeD = new NxReal[numLimitPlanes]; NxReal *restitution = new NxReal[numLimitPlanes]; NxVec3 planeLimitPt; bool onActor2 = j->getLimitPoint( planeLimitPt ); NxVec3 *worldLimitPt = new NxVec3[numLimitPlanes]; //---------------------------------------------------------------- // // copy to buffer // j->resetLimitPlaneIterator(); for(int iter=0 ; iter < numLimitPlanes ; iter++ ) { j->getNextLimitPlane( planeNormal[iter], planeD[iter], &restitution[iter] ); } //---------------------------------------------------------------- // // create limitPoints // dst->setLimitPoint(getFrom(planeLimitPt),onActor2); for(int iter=0 ; iter < numLimitPlanes ; iter++ ) { if ( ( fabs(planeNormal[iter].z) > fabs(planeNormal[iter].x) ) && ( fabs(planeNormal[iter].z) > fabs(planeNormal[iter].y) ) ) { worldLimitPt[iter].x = planeLimitPt.x; worldLimitPt[iter].y = planeLimitPt.y; worldLimitPt[iter].z = -planeD[iter] / planeNormal[iter].z; } // k, that didn't work - try x,z = 0 else if ( ( fabs(planeNormal[iter].y) > fabs(planeNormal[iter].x) ) && ( fabs(planeNormal[iter].y) > fabs(planeNormal[iter].z) ) ) { worldLimitPt[iter].x = planeLimitPt.x; worldLimitPt[iter].z = planeLimitPt.z; worldLimitPt[iter].y = -planeD[iter] / planeNormal[iter].y; } else { worldLimitPt[iter].y = planeLimitPt.y; worldLimitPt[iter].z = planeLimitPt.z; worldLimitPt[iter].x = -planeD[iter] / planeNormal[iter].x; } dst->addLimitPlane(getFrom(planeNormal[iter]),getFrom(worldLimitPt[iter]),restitution[iter]); } delete []worldLimitPt; delete []planeNormal; delete []restitution; delete []planeD; worldLimitPt = NULL; planeD = NULL; restitution = NULL; planeD = NULL; return numLimitPlanes; } pJoint *pFactory::cloneJoint(pJoint *src,CK3dEntity *srcReference,CK3dEntity *dstReference,int copyFlags) { //---------------------------------------------------------------- // // sanity checks // #ifdef _DEBUG assert(src); assert(dstReference); #endif // _DEBUG //---------------------------------------------------------------- // // Prepare pointers // NxActor *actorA = NULL; pRigidBody *actorABody = GetPMan()->getBody(dstReference); if (actorABody){ actorA = actorABody->getActor(); } else{ xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"You need at least one rigid body"); return NULL; } //actorB can be NULL and can not be the same as actorA : NxActor *actorB = NULL; pRigidBody *actorBBody = NULL; CK3dEntity *referenceB = NULL; //---------------------------------------------------------------- // // determine the first, this will be the clone ! // if ( src->GetVTEntA() && src->GetVTEntA() !=srcReference ) { actorBBody = GetPMan()->getBody(src->GetVTEntA()); if (actorBBody) { actorB = actorBBody->getActor(); referenceB = actorBBody->GetVT3DObject(); } } //---------------------------------------------------------------- // // determine the second // if ( src->GetVTEntB() && src->GetVTEntB() !=srcReference ) { actorBBody = GetPMan()->getBody(src->GetVTEntB()); if (actorBBody) { actorB = actorBBody->getActor(); referenceB = actorBBody->GetVT3DObject(); } } if ( (copyFlags & PB_CF_SWAP_JOINTS_REFERENCES) ) { XSwap(actorA,actorB); XSwap(actorABody,actorBBody); } CK3dEntity *testA = actorABody->GetVT3DObject(); CK3dEntity *testB = NULL; if (actorBBody) testB = actorBBody->GetVT3DObject(); switch (src->getType()) { //---------------------------------------------------------------- // // Distance Joint : // case JT_Distance : { NxDistanceJoint *nxSrc = src->getJoint()->isDistanceJoint(); if (nxSrc) { NxDistanceJointDesc descrNew; nxSrc->saveToDesc(descrNew); descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; NxDistanceJoint *nxJoint = (NxDistanceJoint*)actorA->getScene().createJoint(descrNew); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointDistance *joint = new pJointDistance(actorABody,actorBBody); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(actorABody->getWorld()); return joint; } break; } //---------------------------------------------------------------- // // Fixed Joint : // case JT_Fixed : { NxFixedJoint *nxSrc = src->getJoint()->isFixedJoint(); if (nxSrc) { NxFixedJointDesc descrNew; nxSrc->saveToDesc(descrNew); descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; NxFixedJoint *nxJoint = (NxFixedJoint*)actorA->getScene().createJoint(descrNew); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointFixed *joint = new pJointFixed(actorABody,actorBBody); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(actorABody->getWorld()); return joint; } break; } //---------------------------------------------------------------- // // Ball Joint : // case JT_Spherical: { NxSphericalJoint *nxSrc = src->getJoint()->isSphericalJoint(); if (nxSrc) { NxSphericalJointDesc descrNew; nxSrc->saveToDesc(descrNew); descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; NxSphericalJoint *nxJoint = (NxSphericalJoint*)actorA->getScene().createJoint(descrNew); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointBall *joint = new pJointBall(actorABody,actorBBody); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(actorABody->getWorld()); return joint; } break; } //---------------------------------------------------------------- // // Revolute Joint : // case JT_Revolute: { NxRevoluteJoint *nxSrc = src->getJoint()->isRevoluteJoint(); if (nxSrc) { NxRevoluteJointDesc descrNew; nxSrc->saveToDesc(descrNew); descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; NxRevoluteJoint *nxJoint = (NxRevoluteJoint*)actorA->getScene().createJoint(descrNew); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointRevolute *joint = new pJointRevolute(actorABody,actorBBody); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(actorABody->getWorld()); return joint; } break; } //---------------------------------------------------------------- // // Cylindrical Joint : // case JT_Cylindrical: { NxCylindricalJoint *nxSrc = src->getJoint()->isCylindricalJoint(); if (nxSrc) { NxCylindricalJointDesc descrNew; nxSrc->saveToDesc(descrNew); descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; NxCylindricalJoint *nxJoint = (NxCylindricalJoint*)actorA->getScene().createJoint(descrNew); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointCylindrical*joint = new pJointCylindrical(actorABody,actorBBody); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(actorABody->getWorld()); return joint; } break; } //---------------------------------------------------------------- // // Prismatic Joint : // case JT_Prismatic: { NxPrismaticJoint *nxSrc = src->getJoint()->isPrismaticJoint(); if (nxSrc) { NxPrismaticJointDesc descrNew; nxSrc->saveToDesc(descrNew); descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; NxPrismaticJoint *nxJoint = (NxPrismaticJoint*)actorA->getScene().createJoint(descrNew); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointPrismatic*joint = new pJointPrismatic(actorABody,actorBBody); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(actorABody->getWorld()); return joint; } break; } //---------------------------------------------------------------- // // PointInPlane Joint : // case JT_PointInPlane: { NxPointInPlaneJoint*nxSrc = src->getJoint()->isPointInPlaneJoint(); if (nxSrc) { NxPointInPlaneJointDesc descrNew; nxSrc->saveToDesc(descrNew); descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; NxPointInPlaneJoint *nxJoint = (NxPointInPlaneJoint*)actorA->getScene().createJoint(descrNew); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointPointInPlane*joint = new pJointPointInPlane(actorABody,actorBBody); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(actorABody->getWorld()); return joint; } break; } //---------------------------------------------------------------- // // PointOnLine Joint : // case JT_PointOnLine: { NxPointOnLineJoint*nxSrc = src->getJoint()->isPointOnLineJoint(); if (nxSrc) { NxPointOnLineJointDesc descrNew; nxSrc->saveToDesc(descrNew); descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; NxPointOnLineJoint *nxJoint = (NxPointOnLineJoint*)actorA->getScene().createJoint(descrNew); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointPointOnLine*joint = new pJointPointOnLine(actorABody,actorBBody); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(actorABody->getWorld()); return joint; } break; } } return NULL; } void pFactory::cloneJoints(CK3dEntity *src,CK3dEntity *dst,int copyFlags) { //---------------------------------------------------------------- // // sanity checks // #ifdef _DEBUG assert(src); assert(dst); #endif // _DEBUG pRigidBody *srcBody = GetPMan()->getBody(src); pRigidBody *dstBody = GetPMan()->getBody(dst); XString errMsg; if ( !srcBody || !dstBody ) { errMsg.Format("You need two rigid objects to clone joints from a rigid body"); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMsg.Str()); return; } pWorld* srcBodyWorld = srcBody->getWorld(); pWorld* dstBodyWorld = dstBody->getWorld(); if( !srcBodyWorld || !dstBodyWorld ) { errMsg.Format("You need two valid world objects to clone joints from a rigid body"); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMsg.Str()); return; } if( srcBodyWorld!=dstBodyWorld ) { errMsg.Format("Worlds objects must be same"); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMsg.Str()); return; } //---------------------------------------------------------------- // // copy process // pWorld *testWorld = dstBodyWorld; NxU32 jointCount = testWorld->getScene()->getNbJoints(); if (jointCount) { NxArray< NxJoint * > joints; testWorld->getScene()->resetJointIterator(); NxJoint *last = NULL; pJoint *lastJ = NULL; for (NxU32 i = 0; i < jointCount; ++i) { NxJoint *j = testWorld->getScene()->getNextJoint(); pJoint *mJoint = static_cast<pJoint*>( j->userData ); if ( mJoint ) { if (mJoint==lastJ)// avoid double clone { continue; } if (mJoint->GetVTEntA() == srcBody->GetVT3DObject() || mJoint->GetVTEntB() == srcBody->GetVT3DObject() ) { pJoint *clone = pFactory::cloneJoint(mJoint,src,dst,copyFlags); if (clone ) { if ((copyFlags & PB_CF_LIMIT_PLANES)) { int limitPlanes = pFactory::cloneLimitPlanes(mJoint,clone,src,dst); } } } } lastJ = mJoint; } } } pJointPointOnLine*pFactory::createPointOnLineJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) { if (jointCheckPreRequisites(a,b,JT_PointOnLine) == -1 ) { return NULL; } pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); pWorld*world = GetPMan()->getWorldByBody(a); if (!world) { world = GetPMan()->getWorldByBody(b); } NxActor *a0 = NULL; if (ba) { a0 = ba->getActor(); } NxActor *a1 = NULL; if (bb) { a1 = bb->getActor(); } NxPointOnLineJointDesc desc; desc.actor[0] = a0; desc.actor[1] = a1; desc.setGlobalAxis(getFrom(axis)); desc.setGlobalAnchor(getFrom(anchor)); if (!desc.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); return NULL; } NxPointOnLineJoint* nxJoint = (NxPointOnLineJoint*)world->getScene()->createJoint(desc); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointPointOnLine*joint = new pJointPointOnLine(ba,bb); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(world); return joint; } pJointPointInPlane*pFactory::createPointInPlaneJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) { if (jointCheckPreRequisites(a,b,JT_PointInPlane) == -1 ) { return NULL; } pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); pWorld*world = GetPMan()->getWorldByBody(a); if (!world) { world = GetPMan()->getWorldByBody(b); } NxActor *a0 = NULL; if (ba) { a0 = ba->getActor(); } NxActor *a1 = NULL; if (bb) { a1 = bb->getActor(); } NxPointInPlaneJointDesc desc; desc.actor[0] = a0; desc.actor[1] = a1; desc.setGlobalAxis(getFrom(axis)); desc.setGlobalAnchor(getFrom(anchor)); if (!desc.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); return NULL; } NxPointInPlaneJoint* nxJoint = (NxPointInPlaneJoint*)world->getScene()->createJoint(desc); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointPointInPlane*joint = new pJointPointInPlane(ba,bb); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(world); return joint; } pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) { if (jointCheckPreRequisites(a,b,JT_Cylindrical) == -1 ) { return NULL; } pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); pWorld*world = GetPMan()->getWorldByBody(a); if (!world) { world = GetPMan()->getWorldByBody(b); } NxActor *a0 = NULL; if (ba) { a0 = ba->getActor(); } NxActor *a1 = NULL; if (bb) { a1 = bb->getActor(); } NxCylindricalJointDesc desc; desc.actor[0] = a0; desc.actor[1] = a1; desc.setGlobalAxis(getFrom(axis)); desc.setGlobalAnchor(getFrom(anchor)); if (!desc.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); return NULL; } NxCylindricalJoint* nxJoint = (NxCylindricalJoint*)world->getScene()->createJoint(desc); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointCylindrical*joint = new pJointCylindrical(ba,bb); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(world); return joint; } pJointPrismatic *pFactory::createPrismaticJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) { if (jointCheckPreRequisites(a,b,JT_Prismatic) == -1 ) { return NULL; } pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); pWorld*world = GetPMan()->getWorldByBody(a); if (!world) { world = GetPMan()->getWorldByBody(b); } NxActor *a0 = NULL; if (ba) { a0 = ba->getActor(); } NxActor *a1 = NULL; if (bb) { a1 = bb->getActor(); } NxPrismaticJointDesc desc; desc.actor[0] = a0; desc.actor[1] = a1; desc.setGlobalAxis(getFrom(axis)); desc.setGlobalAnchor(getFrom(anchor)); if (!desc.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); return NULL; } NxPrismaticJoint* nxJoint = (NxPrismaticJoint*)world->getScene()->createJoint(desc); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointPrismatic*joint = new pJointPrismatic(ba,bb); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(world); return joint; } pJointRevolute*pFactory::createRevoluteJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) { if (jointCheckPreRequisites(a,b,JT_Revolute) == -1 ) { return NULL; } pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); if (!ba && !bb) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"No body specified"); return NULL; } pWorld*world = GetPMan()->getWorldByBody(a); if (!world && bb) { world = bb->getWorld(); } NxRevoluteJointDesc descr; /*descr.projectionDistance = (NxReal)0.05; descr.projectionAngle= (NxReal)0.05; descr.projectionMode = NX_JPM_POINT_MINDIST;*/ if (ba) { descr.actor[0]=ba->getActor(); } if (bb) { descr.actor[1]=bb->getActor(); } NxRevoluteJoint *nxJoint=(NxRevoluteJoint*)world->getScene()->createJoint(descr); if (!descr.isValid()) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Revolute joint invalid!"); return NULL; } nxJoint->setGlobalAnchor(getFrom(anchor)); nxJoint->setGlobalAxis(getFrom(axis)); //////////////////////////////////////////////////////////////////////////, // vt object : pJointRevolute*joint = new pJointRevolute(ba,bb); nxJoint->userData = joint; joint->setWorld(world); joint->setJoint(nxJoint); return joint; } pJointPulley* pFactory::createPulleyJoint( CK3dEntity*a,CK3dEntity*b,VxVector pulley0,VxVector pulley1, VxVector anchor0, VxVector anchor1 ) { if (jointCheckPreRequisites(a,b,JT_Pulley) == -1 ) { return NULL; } VxVector globalAxis(0,1,0); float distance = 10.0f; float ratio = 1.0f; float stiffness = 1.0f; int flags = 0 ; pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); if (!ba && !bb) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"You need two bodies for a pulley joint!"); return NULL; } pWorld*world = GetPMan()->getWorldByBody(a); ////////////////////////////////////////////////////////////////////////// // nx object : NxPulleyJointDesc descr; descr.setToDefault(); descr.actor[0]=ba->getActor(); descr.actor[1]=bb->getActor(); descr.localAnchor[0] = pMath::getFrom(anchor0); descr.localAnchor[1] = pMath::getFrom(anchor1); descr.setGlobalAxis(pMath::getFrom(globalAxis)); descr.pulley[0] = pMath::getFrom(pulley0); // suspension points of two bodies in world space. descr.pulley[1] = pMath::getFrom(pulley1); // suspension points of two bodies in world space. descr.distance = distance; // the rest length of the rope connecting the two objects. The distance is computed as ||(pulley0 - anchor0)|| + ||(pulley1 - anchor1)|| * ratio. descr.stiffness = stiffness; // how stiff the constraint is, between 0 and 1 (stiffest) descr.ratio = ratio; // transmission ratio descr.flags = flags; // This is a combination of the bits defined by ::NxPulleyJointFlag. if (!descr.isValid()) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Pully joint invalid!"); return NULL; } NxPulleyJoint *nxJoint = (NxPulleyJoint*)world->getScene()->createJoint(descr); if (!nxJoint) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointPulley*joint = new pJointPulley(ba,bb); nxJoint->userData = joint; joint->setWorld(world); joint->setJoint(nxJoint); return joint; //descr.motor = gMotorDesc; // pulleyDesc.projectionMode = NX_JPM_NONE; // pulleyDesc.projectionMode = NX_JPM_POINT_MINDIST; // pulleyDesc.jointFlags |= NX_JF_COLLISION_ENABLED; return NULL; } pJointFixed*pFactory::createFixedJoint(CK3dEntity *a, CK3dEntity *b) { if (jointCheckPreRequisites(a,b,JT_Fixed) == -1 ) { return NULL; } pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); pWorld*world = GetPMan()->getWorldByBody(a); if (!world) { world = GetPMan()->getWorldByBody(b); } NxActor *a0 = NULL; if (ba) { a0 = ba->getActor(); } NxActor *a1 = NULL; if (bb) { a1 = bb->getActor(); } NxFixedJointDesc descr; descr.actor[0] = a0; descr.actor[1] = a1; if (!descr.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); return NULL; } NxJoint *nxJoint = (NxDistanceJoint*)world->getScene()->createJoint(descr); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointFixed*joint = new pJointFixed(ba,bb); nxJoint->userData = joint; joint->setWorld(world); joint->setJoint(nxJoint); return joint; } pJointD6*pFactory::createD6Joint(CK3dEntity *a, CK3dEntity *b, VxVector globalAnchor,VxVector globalAxis,int collision) { if (jointCheckPreRequisites(a,b,JT_D6) == -1 ) { return NULL; } pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); pWorld*world = GetPMan()->getWorldByBody(a); if (!world) { world = GetPMan()->getWorldByBody(b); } NxActor *a0 = NULL; if (ba) { a0 = ba->getActor(); } NxActor *a1 = NULL; if (bb) { a1 = bb->getActor(); } NxD6JointDesc d6Desc; d6Desc.actor[0] = a0; d6Desc.actor[1] = a1; d6Desc.setGlobalAnchor(pMath::getFrom(globalAnchor)); d6Desc.setGlobalAxis(pMath::getFrom(globalAxis)); if (collision) { //d6Desc.flags d6Desc.jointFlags|=NX_JF_COLLISION_ENABLED; } if (!d6Desc.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); return NULL; } NxJoint *nxJoint = (NxDistanceJoint*)world->getScene()->createJoint(d6Desc); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointD6 *joint = new pJointD6(ba,bb); nxJoint->userData = joint; joint->setWorld(world); joint->setJoint(nxJoint); return joint; } pJointBall *pFactory::createBallJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector swingAxis) { pJointBall *result; if (jointCheckPreRequisites(a,b,JT_Spherical) == -1 ) { return NULL; } pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); pWorld*world = GetPMan()->getWorldByBody(a); if (!world) { world = GetPMan()->getWorldByBody(b); } NxActor *a0 = NULL; if (ba) { a0 = ba->getActor(); } NxActor *a1 = NULL; if (bb) { a1 = bb->getActor(); } NxSphericalJointDesc desc; desc.actor[0] = a0; desc.actor[1] = a1; desc.swingAxis = pMath::getFrom(swingAxis); /*desc.projectionDistance = (NxReal)0.15; desc.projectionMode = NX_JPM_POINT_MINDIST;*/ if (!desc.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); return NULL; } NxSphericalJoint* nxJoint = (NxSphericalJoint*)world->getScene()->createJoint(desc); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointBall*joint = new pJointBall(ba,bb); nxJoint->userData = joint; joint->setJoint(nxJoint); nxJoint->setGlobalAnchor(pMath::getFrom(anchor)); joint->setWorld(world); return joint; } int pFactory::jointCheckPreRequisites(CK3dEntity*_a,CK3dEntity*_b,int type) { pRigidBody *a = GetPMan()->getBody(_a); pRigidBody *b = GetPMan()->getBody(_b); //bodies have already a joint together ? if ( !a && !b) { return -1; } if (a && !a->isValid() ) { return -1; } if (a && !GetPMan()->getWorldByBody(_a)) { return -1; } if (b && !GetPMan()->getWorldByBody(_b)) { return -1; } if (b && !b->isValid()) { return -1; } if ( a && b ) { pWorld*worldA = GetPMan()->getWorldByBody(_a); pWorld*worldB = GetPMan()->getWorldByBody(_b); if (!worldA || !worldB || (worldA!=worldB) || !worldA->isValid() ) { return -1; } } return 1; } pJointDistance*pFactory::createDistanceJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor0,VxVector anchor1,float minDistance,float maxDistance,pSpring sSettings) { if (jointCheckPreRequisites(a,b,JT_Distance) == -1 ) { return NULL; } pRigidBody *ba = GetPMan()->getBody(a); pRigidBody *bb = GetPMan()->getBody(b); pWorld*world = GetPMan()->getWorldByBody(a); ////////////////////////////////////////////////////////////////////////// // nx object : NxDistanceJointDesc descr; descr.actor[0]=ba->getActor(); descr.actor[1]= b ? bb->getActor() : NULL ; descr.localAnchor[0] = pMath::getFrom(anchor0); descr.localAnchor[1] = pMath::getFrom(anchor1); descr.minDistance = minDistance; descr.maxDistance = maxDistance; if (minDistance!=0.0f) descr.flags|=NX_DJF_MIN_DISTANCE_ENABLED; if (maxDistance!=0.0f) descr.flags|=NX_DJF_MAX_DISTANCE_ENABLED; if(sSettings.damper!=0.0f || sSettings.damper!=0.0f ) { descr.flags|=NX_DJF_SPRING_ENABLED; NxSpringDesc sDescr; sDescr.damper = sSettings.damper; sDescr.spring = sSettings.spring; sDescr.targetValue = sSettings.targetValue; descr.spring = sDescr; } NxDistanceJoint *nxJoint = (NxDistanceJoint*)world->getScene()->createJoint(descr); if (!nxJoint) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); int v = descr.isValid(); return NULL; } //////////////////////////////////////////////////////////////////////////, // vt object : pJointDistance *joint = new pJointDistance(ba,bb); nxJoint->userData = joint; joint->setJoint(nxJoint); joint->setWorld(world); return joint; } pJoint*pFactory::createJoint(CK3dEntity*_a,CK3dEntity*_b,int type) { return NULL ; } pJointSettings*pFactory::CreateJointSettings(const XString nodeName/* = */,const TiXmlDocument * doc /* = NULL */) { /* pJointSettings *result = new pJointSettings(); if (nodeName.Length() && doc) { const TiXmlElement *root = GetFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "JointSettings" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),nodeName.CStr() ) ) { float vF=0.0f; int res; ////////////////////////////////////////////////////////////////////////// res = element->QueryFloatAttribute("LowStop",&vF); if (res == TIXML_SUCCESS) { result->LowStop(vF); } ////////////////////////////////////////////////////////////////////////// res = element->QueryFloatAttribute("HiStop",&vF); if (res == TIXML_SUCCESS) { result->HighStop(vF); } ////////////////////////////////////////////////////////////////////////// res = element->QueryFloatAttribute("LowStop2",&vF); if (res == TIXML_SUCCESS) { result->LowStop2(vF); } ////////////////////////////////////////////////////////////////////////// res = element->QueryFloatAttribute("HiStop2",&vF); if (res == TIXML_SUCCESS) { result->HighStop2(vF); } return result; } } } } } } */ return NULL; } pJointSettings*pFactory::CreateJointSettings(const char* nodeName,const char *filename) { /* XString fname(filename); XString nName(nodeName); if ( nName.Length() && fname.Length() ) { TiXmlDocument * document = getDocument(fname); if (document) { pJointSettings *result = CreateJointSettings(nodeName,document); if ( result) { delete document; return result; } } } */ return NULL; } pJointLimit pFactory::createLimitFromParameter(CKParameter *par) { pJointLimit result; CKContext *ctx = GetPMan()->GetContext(); if (par) { CKParameter* pout = NULL; CK_ID* ids = (CK_ID*)par->GetReadDataPtr(); float value,restitution,hardness; pout = (CKParameterOut*)ctx->GetObject(ids[0]); pout->GetValue(&value); pout = (CKParameterOut*)ctx->GetObject(ids[1]); pout->GetValue(&restitution); pout = (CKParameterOut*)ctx->GetObject(ids[2]); pout->GetValue(&hardness); result.value = value; result.restitution = restitution; result.hardness =hardness; return result; } return result; } pSpring pFactory::createSpringFromParameter(CKParameter *par) { pSpring result; CKContext *ctx = GetPMan()->GetContext(); if (par) { CKParameter* pout = NULL; CK_ID* ids = (CK_ID*)par->GetReadDataPtr(); float damping,spring,targetValue; pout = (CKParameterOut*)ctx->GetObject(ids[0]); pout->GetValue(&damping); pout = (CKParameterOut*)ctx->GetObject(ids[1]); pout->GetValue(&spring); pout = (CKParameterOut*)ctx->GetObject(ids[2]); pout->GetValue(&targetValue); result.spring = spring; result.damper = damping; result.targetValue = targetValue; return result; } return result; } pMotor pFactory::createMotorFromParameter(CKParameter *par) { pMotor result; CKContext *ctx = GetPMan()->GetContext(); if (par) { CKParameter* pout = NULL; CK_ID* ids = (CK_ID*)par->GetReadDataPtr(); float targetVel,maxF; int freeSpin; pout = (CKParameterOut*)ctx->GetObject(ids[0]); pout->GetValue(&targetVel); pout = (CKParameterOut*)ctx->GetObject(ids[1]); pout->GetValue(&maxF); pout = (CKParameterOut*)ctx->GetObject(ids[2]); pout->GetValue(&freeSpin); result.targetVelocity = targetVel; result.maximumForce = maxF; result.freeSpin = freeSpin; return result; } return result; } pJoint*pFactory::GetJoint(CK3dEntity*_a,CK3dEntity*_b) { /* if (!_a ||!_b) { return 0; } pRigidBody *ba = getBody(_a); pRigidBody *bb = getBody(_b); if ( !ba || !bb || ba == bb ) return NULL; //we check whether both associated bodies are in the same world : if ( ba->World() != bb->World() ) { return 0; } OdeBodyType oba = ba->GetOdeBody(); OdeBodyType obb = bb->GetOdeBody(); if ( !oba || !obb ) return NULL; for (int i = 0 ; i < dBodyGetNumJoints(oba) ; i++) { dJointID jID = dBodyGetJoint(oba,i); pJoint *joint = static_cast<pJoint*>(dJointGetData(jID)); if (joint && joint->GetOdeBodyB() == obb) { return joint; } } for (int i = 0 ; i < dBodyGetNumJoints(obb) ; i++) { dJointID jID = dBodyGetJoint(obb,i); pJoint *joint = static_cast<pJoint*>(dJointGetData(jID)); if (joint && joint->GetOdeBodyB() == oba) { return joint; } } */ return NULL; } <file_sep>// -------------------------------------------------------------------------- // www.UnitedBusinessTechnologies.com // Copyright (c) 1998 - 2002 All Rights Reserved. // // Source in this file is released to the public under the following license: // -------------------------------------------------------------------------- // This toolkit may be used free of charge for any purpose including corporate // and academic use. For profit, and Non-Profit uses are permitted. // // This source code and any work derived from this source code must retain // this copyright at the top of each source file. // // UBT welcomes any suggestions, improvements or new platform ports. // email to: <EMAIL> // -------------------------------------------------------------------------- #include "pch.h" #include "DirectoryListing.h" #include "GString.h" #include "GException.h" //#include <string.h> // #include <windows.h> // #include "Winbase.h" #include <sys/stat.h> #include <io.h> #include <direct.h> // for: mkdir const char *CDirectoryListing::LastLeaf(const char *pzFullPath, char chSlash/*= 0*/) { static GString strReturnValue; strReturnValue = ""; if (pzFullPath && pzFullPath[0]) { strReturnValue = pzFullPath; int nLen = strlen(pzFullPath); if (chSlash) { if (pzFullPath[nLen - 1] == chSlash) nLen--; } else if ( pzFullPath[nLen - 1] == '\\' || pzFullPath[nLen - 1] == '/') { nLen--; // if the input value is "/etc/bin/" start searching behind the last '/' // so that the return leaf value is "bin" } for(int i = nLen-1; i > -1; i-- ) { if (chSlash) { if (pzFullPath[i] == chSlash) { strReturnValue = &pzFullPath[i+1]; break; } } else if (pzFullPath[i] == '\\' || pzFullPath[i] == '/') { strReturnValue = &pzFullPath[i+1]; break; } } } return strReturnValue; } void CDirectoryListing::CreatePath(const char *pzPathOnlyOrPathAndFileName, int bPathHasFileName) { // cast off the const, we'll modify then restore the string char *pzFileAndPath = (char *)pzPathOnlyOrPathAndFileName; if (!pzFileAndPath) { return; } int nLen = strlen(pzFileAndPath); for(int i=0;i<nLen+1;i++) { if (pzFileAndPath[i] == '\\' || pzFileAndPath[i] == '/' || pzFileAndPath[i] == 0) { if ( bPathHasFileName && pzFileAndPath[i] == 0) { // if the path includes a filename, we're done. break; } char ch = pzFileAndPath[i]; pzFileAndPath[i] = 0; int nAttempts = 0; RETRY_MKDIR: nAttempts++; int nRslt = mkdir(pzFileAndPath); if (nRslt != 0 && nAttempts < 5 && errno == 2) { goto RETRY_MKDIR; } pzFileAndPath[i] = ch; } } } // returns 1 if the argument is a directory, 0 if it's a file or a bad path. int CDirectoryListing::IsDirectory(const char *szDirPath) { struct stat sstruct; int result = stat(szDirPath, &sstruct); if (result == 0) { if ( (sstruct.st_mode & _S_IFDIR) ) { return 1; } } return 0; } void CDirectoryListing::RecurseFolder(const char *pzDir, GStringList *strDirs, GStringList *strFiles) { char chSlash = '\\'; static GString strDot("[dir] ."); static GString strDotDot("[dir] .."); try { // Sample listing 2 files + 1 directory = "file1.txt*[dir] Temp*file2.txt" GString strResults; CDirectoryListing dir(pzDir, 2); // directories only GStringIterator it(&dir); while (it()) { // pzResult will look something like "[dir] SubDir" const char *pzResult = it++; if (strDot.Compare(pzResult) != 0 && strDotDot.Compare(pzResult) != 0) { // pzDir may be "/myPath" to begin with GString strFullPath(pzDir); if ( strFullPath.GetAt(strFullPath.GetLength() - 1) != '\\' && strFullPath.GetAt(strFullPath.GetLength() - 1) != '/') { // pzDir will now end with a slash if it did not already. // like "/myPath/" or "c:\myPath\" strFullPath += chSlash; } // add the file name to the complete path we're building strFullPath += &pzResult[6]; // skip the "[dir] ", add a string like "SubDir" if(strDirs) { strDirs->AddLast(strFullPath); } // now add the final slash for a string like this "/myPath/SubDir/" strFullPath += chSlash; // go down into that directory now. RecurseFolder(strFullPath, strDirs, strFiles); } } if(strFiles) { CDirectoryListing files(pzDir, 1); // files only GStringIterator it2(&files); while (it2()) { // pzDir may be "/myPath" to begin with GString strFullPath(pzDir); if ( strFullPath.GetAt(strFullPath.GetLength() - 1) != '\\' && strFullPath.GetAt(strFullPath.GetLength() - 1) != '/') { // strFullPath will now end with a slash like "/myPath/" strFullPath += chSlash; } const char *pzFile = it2++; strFullPath += pzFile; strFiles->AddLast((const char *)strFullPath); } } } catch( GenericException & ) { // ignore the directory we can't access // rErr.GetDescription(); } } void CDirectoryListing::Init(const char *szDirPath, int nMode) { static GString dotdot(".."); static GString dot("."); bool bIncludeSubDirs = (nMode == 2 || nMode == 3) ? 1 : 0; bool bIncludeFiles = (nMode == 1 || nMode == 3) ? 1 : 0; GString strPathWithTrailingSlash(szDirPath); GString strPathWithNoTrailingSlash(szDirPath); // if szDirPath ends with a slash if ( strPathWithNoTrailingSlash.Right(1) == "/" || strPathWithNoTrailingSlash.Right(1) == "\\" ) { // if the path is "/" leave it alone if (strPathWithNoTrailingSlash.Length() > 1) strPathWithNoTrailingSlash = strPathWithNoTrailingSlash.Left(strPathWithNoTrailingSlash.Length() - 1); } else { strPathWithTrailingSlash += "\\"; } if( _access( (const char *)strPathWithNoTrailingSlash, 0 ) ) { throw GenericException("GDirectoryListing",0,(const char *)strPathWithNoTrailingSlash, errno); } // FindFirstFile & FindNextFile HANDLE hFindFile; WIN32_FIND_DATA find; BOOL fRet = TRUE; GString strSearch( strPathWithTrailingSlash ); strSearch += "*.*"; hFindFile = FindFirstFile((const char *)strSearch, &find); while (hFindFile != (HANDLE)-1 && fRet == TRUE) { GString strTemp( strPathWithTrailingSlash ); strTemp += find.cFileName; struct stat sstruct; int result = stat(strTemp, &sstruct); if (result == 0) { if ( !(sstruct.st_mode & _S_IFDIR) ) { // Add the file if (bIncludeFiles) { AddLast((const char *)find.cFileName); } } else if (bIncludeSubDirs) { GString strFileName( LastLeaf( (char *)(const char *)strTemp,'\\') ); if ( ( dotdot.Compare(strFileName) != 0 ) && ( dot.Compare(strFileName) != 0 )) { GString strFormattedDir; strFormattedDir.Format("[dir] %s", LastLeaf( (char *)(const char *)strFileName,'\\') ); AddLast((const char *)strFormattedDir); } } } fRet = FindNextFile(hFindFile, &find); } FindClose(hFindFile); } CDirectoryListing::CDirectoryListing(const char *szPath) { Init(szPath, 1); } // nMode = 1 files, 2 dirs, 3 both CDirectoryListing::CDirectoryListing(const char *szPath, int nMode) { Init(szPath, nMode); } CDirectoryListing::~CDirectoryListing() { } <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" CKObjectDeclaration *FillBehaviorDOOwnerChangedDecl(); CKERROR CreateDOOwnerChangedProto(CKBehaviorPrototype **); int DOOwnerChanged(const CKBehaviorContext& behcontext); CKERROR DOOwnerChangedCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorDOOwnerChangedDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DOOwnerChanged"); od->SetDescription("Returns the current owner of a distributed object"); od->SetCategory("TNL/Distributed Objects"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x34f668cc,0x43c51c58)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDOOwnerChangedProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateDOOwnerChangedProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("DOOwnerChanged"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareInput("Off"); proto->DeclareOutput("Exit On"); proto->DeclareOutput("Exit Off"); proto->DeclareOutput("New Owner"); proto->DeclareOutput("Object Released"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Object", CKPGUID_BEOBJECT, "test"); proto->DeclareOutParameter("Owner ID", CKPGUID_ID, "-1"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(DOOwnerChanged); proto->SetBehaviorCallbackFct(DOOwnerChangedCB); *pproto = proto; return CK_OK; } int DOOwnerChanged(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; ////////////////////////////////////////////////////////////////////////// //connection id : int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); ////////////////////////////////////////////////////////////////////////// //we come in by input 0 : if (beh->IsInputActive(0)) { beh->ActivateOutput(0); beh->ActivateInput(0,FALSE); } if (beh->IsInputActive(1)) { beh->ActivateOutput(1); beh->ActivateInput(1,FALSE); return 0; } ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *obj= (CK3dEntity*)beh->GetInputParameterObject(1); if (!obj) { beh->ActivateOutput(4); return CKBR_ACTIVATENEXTFRAME; } ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { CKParameterOut *pout = beh->GetOutputParameter(1); XString errorMesg("distributed object creation failed,no network connection !"); pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(4); return CKBR_ACTIVATENEXTFRAME; } IDistributedObjects*doInterface = cin->getDistObjectInterface(); ////////////////////////////////////////////////////////////////////////// //we come in by input 0 : xDistributedObject *dobj = doInterface->getByEntityID(obj->GetID()); if (!dobj) { CKParameterOut *pout = beh->GetOutputParameter(1); XString errorMesg("There is no such an object"); pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(4); }else { if (dobj->getOwnershipState().test(1 << E_DO_OS_RELEASED) && dobj->getOwnershipState().test( 1 << E_DO_OS_OWNERCHANGED) ) { beh->ActivateOutput(3); } if (dobj->getOwnershipState().testStrict(1 << E_DO_OS_OWNERCHANGED)) { dobj->getOwnershipState().set( 1<<E_DO_OS_OWNERCHANGED ,false ); int newCLientID = dobj->getUserID(); beh->SetOutputParameterValue(0,&newCLientID); beh->ActivateOutput(2); } } return CKBR_ACTIVATENEXTFRAME; } CKERROR DOOwnerChangedCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#include "CKAll.h" CKObjectDeclaration *FillBehaviorExecBBDecl(); CKERROR CreateExecBBProto(CKBehaviorPrototype **pproto); int ExecBB(const CKBehaviorContext& behcontext); CKERROR ZipCallBack(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorExecBBDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("ExecBB"); od->SetDescription(""); od->SetCategory("Narratives/Files"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x6b62506d,0x3dd1067)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateExecBBProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateExecBBProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("ExecBB"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Execute"); proto->DeclareOutput("Ok"); proto->DeclareOutput("Failed"); proto->DeclareInParameter("Filename", CKPGUID_STRING); proto->DeclareInParameter("Directory", CKPGUID_STRING); proto->DeclareOutParameter("last error", CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_VARIABLEPARAMETERINPUTS)); proto->SetFunction(ExecBB); *pproto = proto; return CK_OK; } #include <windows.h> BOOL RunAndForgetProcess(char *pCmdLine, char *pRunningDir, int *nRetValue) { int nError; STARTUPINFO stInfo; PROCESS_INFORMATION prInfo; BOOL bResult; ZeroMemory( &stInfo, sizeof(stInfo) ); stInfo.cb = sizeof(stInfo); stInfo.dwFlags=STARTF_USESHOWWINDOW; stInfo.wShowWindow=SW_SHOW; bResult = CreateProcess(NULL, (LPSTR)pCmdLine, NULL, NULL, TRUE, CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP // DETACHED_PROCESS | NORMAL_PRIORITY_CLASS , NULL, (LPSTR)pRunningDir , &stInfo, &prInfo); *nRetValue = nError = GetLastError(); // Don't write these two lines if you need CloseHandle(prInfo.hThread); // to use these handles CloseHandle(prInfo.hProcess); if (!bResult) return FALSE; return TRUE; } int ExecBB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; char* filename = ((CKSTRING) beh->GetInputParameterReadDataPtr(0)); char* dirname = ((CKSTRING) beh->GetInputParameterReadDataPtr(1)) ; if (!strlen(dirname)) dirname = NULL;//argh....... ? int ret = 0; bool res = RunAndForgetProcess(filename,dirname,&ret); beh->SetOutputParameterValue(0,&ret); if (res) beh->ActivateOutput(0); else beh->ActivateOutput(1); return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" #include "IParameter.h" #include "pCallbackSignature.h" #include "vtBBHelper.h" #include "xDebugTools.h" #include "pCallbackSignature.h" CKObjectDeclaration *FillBehaviorPBSetCallbackDecl(); CKERROR CreatePBSetCallbackProto(CKBehaviorPrototype **pproto); int PBSetCallback(const CKBehaviorContext& behcontext); CKERROR PBSetCallbackCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_FetchSignature, bbI_ContactTypeMask, bbI_TriggerTypeMask, bbI_Threshold, bbI_Reserved, bbI_Reserved2, bbI_Contact, bbI_ContactModification, bbI_Trigger, bbI_WheelContact, bbI_RayCastHit, bbI_PreProcess, bbI_PostProcess, bbI_Copy, bbI_Delete // bbI_JointBreak, }; void creatInputParameters(BBParameter pArray[],int size,CKBehavior *beh) { //---------------------------------------------------------------- // // remove all // while(beh->GetInputParameterCount()) { CKParameterIn* pi = beh->RemoveInputParameter(0); CKDestroyObject(pi); } for(int i = 0 ; i < size ; i ++ ) { BBParameter *par = &pArray[i]; beh->CreateInputParameter( par->name.Str(), par->guid); } } void creatOutputParameters(BBParameter pArray[],int size,CKBehavior *beh) { //---------------------------------------------------------------- // // remove all // while(beh->GetOutputParameterCount()) { CKParameterOut* pi = beh->RemoveOutputParameter(0); CKDestroyObject(pi); } for(int i = 0 ; i < size ; i ++ ) { BBParameter *par = &pArray[i]; beh->CreateOutputParameter( par->name.Str(), par->guid); } } #define BB_SSTART 6 BBParameter pInMap221[] = { BB_PIN(bbI_FetchSignature,CKPGUID_BOOL,"Create Parameters Only",""), BB_PIN(bbI_ContactTypeMask,VTF_COLLISIONS_EVENT_MASK,"Contact Event Mask",""), BB_PIN(bbI_TriggerTypeMask,VTF_TRIGGER,"Trigger Event Mask",""), BB_PIN(bbI_Threshold,CKPGUID_FLOAT,"Contact Threshold",""), BB_PIN(bbI_Reserved,CKPGUID_FLOAT,"Stub",""), BB_PIN(bbI_Reserved2,CKPGUID_FLOAT,"Stub",""), BB_SPIN(bbI_Contact,CKPGUID_BEHAVIOR,"Contact Notification",""), BB_SPIN(bbI_ContactModification,CKPGUID_BEHAVIOR,"Contact Modification",""), BB_SPIN(bbI_Trigger,CKPGUID_BEHAVIOR,"Trigger Event",""), BB_SPIN(bbI_WheelContact,CKPGUID_BEHAVIOR,"Wheel Contact Modify",""), BB_SPIN(bbI_RayCastHit,CKPGUID_BEHAVIOR,"Raycast Hit",""), BB_SPIN(bbI_PreProcess,CKPGUID_BEHAVIOR,"Pre Process",""), BB_SPIN(bbI_PostProcess,CKPGUID_BEHAVIOR,"Post Process",""), BB_SPIN(bbI_Copy,CKPGUID_BEHAVIOR,"Copy",""), BB_SPIN(bbI_Delete,CKPGUID_BEHAVIOR,"Delete","") //BB_SPIN(bbI_JointBreak,CKPGUID_BEHAVIOR,"Joint Break",""), }; #define gPIMAP pInMap221 CKObjectDeclaration *FillBehaviorPBSetCallbackDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetCallback"); od->SetCategory("Physic/Body"); od->SetDescription("Sets a callback script for the manager post process."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x1db50304,0x371a786b)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBSetCallbackProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } CKERROR CreatePBSetCallbackProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetCallback"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PBSetCallback PBSetCallback is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies various physical parameters.<br> <h3>Technical Information</h3> \image html PBSetCallback.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body or its sub shape. <BR> <SPAN CLASS="NiceCode"> \include PBSetEx.cpp </SPAN> */ proto->SetBehaviorCallbackFct( PBSetCallbackCB ); BB_EVALUATE_PINS(gPIMAP) BB_EVALUATE_SETTINGS(pInMap221) proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBSetCallback); *pproto = proto; return CK_OK; } //************************************ // Method: PBSetCallback // FullName: PBSetCallback // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBSetCallback(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; BB_DECLARE_PIMAP; int fetchSignature = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_FetchSignature)); if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target && !fetchSignature ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world && !fetchSignature) bbErrorME("No valid world object found"); body = GetPMan()->getBody(target); if (!body && !fetchSignature) bbErrorME("Object not physicalized"); int contactMask = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_ContactTypeMask)); int triggerMask = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_TriggerTypeMask)); BBSParameterM(bbI_Contact,BB_SSTART); BBSParameterM(bbI_Trigger,BB_SSTART); BBSParameterM(bbI_ContactModification,BB_SSTART); BBSParameterM(bbI_RayCastHit,BB_SSTART); BBSParameterM(bbI_Copy,BB_SSTART); BBSParameterM(bbI_Delete,BB_SSTART); BBSParameterM(bbI_WheelContact,BB_SSTART); BBSParameterM(bbI_PreProcess,BB_SSTART); BBSParameterM(bbI_PostProcess,BB_SSTART); //BBSParameterM(bbI_JointBreak,BB_SSTART); //---------------------------------------------------------------- // // update contact threshold // float threshold = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_Threshold)); if (body && !fetchSignature && sbbI_Contact && (body->getFlags() & BF_Moving )) body->setContactReportThreshold(threshold); if (sbbI_Delete || sbbI_Copy || sbbI_PostProcess || sbbI_PostProcess || sbbI_RayCastHit) { bbErrorME("Not Implemented yet"); } XString errMessg; //---------------------------------------------------------------- // // collision notify // if (sbbI_Contact) { CK_ID contactScript = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_Contact)); CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(contactScript); if (!cScript) { errMessg.Format("Callback for contact notification enabled but input script invalid"); bbWarning(errMessg.Str()); }else { if (fetchSignature){ creatInputParameters(pInMapContactCallback,BB_PMAP_SIZE(pInMapContactCallback),cScript); } else body->setContactScript(contactScript,contactMask); } } //---------------------------------------------------------------- // // wheel contact modify // if (sbbI_WheelContact) { CK_ID wheelContactModifyScript = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_WheelContact)); CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(wheelContactModifyScript); if (!cScript) { errMessg.Format("Callback for wheel contact modification enabled but input script invalid"); bbWarning(errMessg.Str()); }else { if (fetchSignature){ creatInputParameters(pInMapWheelContactModifyCallback,BB_PMAP_SIZE(pInMapWheelContactModifyCallback),cScript); creatOutputParameters(pOutMapWheelContactModifyCallback,BB_PMAP_SIZE(pOutMapWheelContactModifyCallback),cScript); } else{ pWheel2 *w = body->getWheel2(target); w->setWheelContactScript(wheelContactModifyScript); } } } //---------------------------------------------------------------- // // collision notify // if (sbbI_Trigger) { CK_ID triggerScript = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_Trigger)); CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(triggerScript); if (!cScript) { errMessg.Format("Callback for trigger notification enabled but input script invalid"); bbWarning(errMessg.Str()); }else { if (fetchSignature){ creatInputParameters(pInMapTriggerCallback,BB_PMAP_SIZE(pInMapTriggerCallback),cScript); } else body->setTriggerScript(triggerScript,triggerMask,target); } } //---------------------------------------------------------------- // // collision notify // if (sbbI_ContactModification) { CK_ID contactModifyScript = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_ContactModification)); CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(contactModifyScript); if (!cScript) { errMessg.Format("Callback for contact modification enabled but input script invalid"); bbWarning(errMessg.Str()); }else { if (fetchSignature) { creatInputParameters(pInMapContactModifyCallback,BB_PMAP_SIZE(pInMapContactModifyCallback),cScript); creatOutputParameters(pOutMapContactModifyCallback,BB_PMAP_SIZE(pOutMapContactModifyCallback),cScript); } else body->setContactModificationScript(contactModifyScript); } } //---------------------------------------------------------------- // // raycast // if (sbbI_RayCastHit) { bbErrorME("Not Implemented yet"); CK_ID raycastScript = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_RayCastHit)); CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(raycastScript); if (!cScript) { errMessg.Format("Callback for raycast hit reports enabled but input script invalid"); bbWarning(errMessg.Str()); }else { if (fetchSignature) { creatInputParameters(pInMapRaycastHitCallback,BB_PMAP_SIZE(pInMapRaycastHitCallback),cScript); } else body->setRayCastScript(raycastScript); } } //---------------------------------------------------------------- // // raycast // /*if (sbbI_JointBreak) { CK_ID jointBreakScript = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_JointBreak)); CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(jointBreakScript); if (!cScript) { errMessg.Format("Callback for joint breaks enabled but input script invalid"); bbWarning(errMessg.Str()); }else { if (fetchSignature) { creatInputParameters(pInMapJointBreakCallback,BB_PMAP_SIZE(pInMapJointBreakCallback),cScript); } else body->setJointBreakScript(jointBreakScript); } } */ } beh->ActivateOutput(0); return 0; } //************************************ // Method: PBSetCallbackCB // FullName: PBSetCallbackCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBSetCallbackCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" void __newpVehicleDescr(BYTE *iAdd) { new (iAdd)pVehicleDesc(); } void __newpVehicleMotorDesc(BYTE *iAdd) { new (iAdd)pVehicleMotorDesc(); } void __newpVehicleGearDesc(BYTE *iAdd) { new(iAdd)pVehicleGearDesc(); } void PhysicManager::_RegisterVSLVehicle() { STARTVSLBIND(m_Context) //---------------------------------------------------------------- // // vehicle base types // DECLAREPOINTERTYPE(pVehicleMotorDesc) DECLAREMEMBER(pVehicleMotorDesc,float,maxRpmToGearUp) DECLAREMEMBER(pVehicleMotorDesc,float,minRpmToGearDown) DECLAREMEMBER(pVehicleMotorDesc,float,maxRpm) DECLAREMEMBER(pVehicleMotorDesc,float,minRpm) DECLAREMETHOD_0(pVehicleMotorDesc,void,setToCorvette) DECLAREPOINTERTYPE(pVehicleGearDesc) DECLAREMEMBER(pVehicleGearDesc,int,nbForwardGears) DECLAREMETHOD_0(pVehicleGearDesc,void,setToDefault) DECLAREMETHOD_0(pVehicleGearDesc,void,setToCorvette) DECLAREMETHOD_0(pVehicleGearDesc,bool,isValid) DECLAREOBJECTTYPE(pVehicleDesc) DECLARECTOR_0(__newpVehicleDescr) DECLAREMEMBER(pVehicleDesc,float,digitalSteeringDelta) DECLAREMEMBER(pVehicleDesc,VxVector,steeringSteerPoint) DECLAREMEMBER(pVehicleDesc,VxVector,steeringTurnPoint) DECLAREMEMBER(pVehicleDesc,float,steeringMaxAngle) DECLAREMEMBER(pVehicleDesc,float,transmissionEfficiency) DECLAREMEMBER(pVehicleDesc,float,differentialRatio) DECLAREMEMBER(pVehicleDesc,float,maxVelocity) DECLAREMEMBER(pVehicleDesc,float,motorForce) DECLAREMETHOD_0(pVehicleDesc,pVehicleGearDesc*,getGearDescription) DECLAREMETHOD_0(pVehicleDesc,pVehicleMotorDesc*,getMotorDescr) DECLAREMETHOD_0(pVehicleDesc,void,setToDefault) STOPVSLBIND }<file_sep>#ifndef _XDISTRIBUTED_SESSION_H_ #define _XDISTRIBUTED_SESSION_H_ #include "xNetTypes.h" #include "xDistributedObject.h" class xDistributedClient; class xDistributedSession : public xDistributedObject { typedef xDistributedObject Parent; public : xDistributedSession(); ~xDistributedSession(); enum MaskBits { InitialMask = BIT(0), ///< This mask bit is never set explicitly, so it can be used for initialization data. PositionMask = BIT(1), ///< This mask bit is set when the position information changes on the server. }; int getSessionType() const { return mSessionType; } void setSessionType(int val) { mSessionType = val; } bool isLocked(); xNString getPassword(); void setPassword(xNString val); int getMaxUsers(); void setMaxUsers(int val); int getSessionID() const { return mSessionID; } void setSessionID(int val) { mSessionID = val; } bool isPrivate(); int getNumUsers(); void setNumUsers(int val); bool isFull(); TNL::BitSet32& getSessionFlags() { return mSessionFlags; } void setSessionFlags(TNL::BitSet32 val) { mSessionFlags = val; } xClientArrayType *mClientTable; xClientArrayType&getClientTable() { return *mClientTable; } bool isClientJoined(int userID); void addUser(xDistributedClient *client); void removeUser(xDistributedClient *client); void onGhostRemove(); bool onGhostAdd(TNL::GhostConnection *theConnection); void onGhostAvailable(TNL::GhostConnection *theConnection); TNL::U32 packUpdate(TNL::GhostConnection *connection, TNL::U32 updateMask, TNL::BitStream *stream); void unpackUpdate(TNL::GhostConnection *connection, TNL::BitStream *stream); void performScopeQuery(TNL::GhostConnection *connection); void pack(TNL::BitStream *bstream); void unpack(TNL::BitStream *bstream,float sendersOneWayTime); void prepare(); void initProperties(); xDistributedProperty *getProperty(int nativeType); xDistributedProperty *getUserProperty(const char*name); int mSessionType; int mMaxUsers; xNString mPassword; xNString mSessionMaster; bool mPrivate; bool mLocked; int mSessionID; int mUsers; TNL::BitSet32 mSessionFlags; uxString print(TNL::BitSet32 flags); public: TNL_DECLARE_CLASS(xDistributedSession); }; #endif<file_sep>/* * Tcp4u v 3.31 Created may 93 - Last Revision 20/10/1997 3.20 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: tcp4u.c * Purpose: main functions for tcp management * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" #define TCP4U_SENDTIMEOUT 3600l /* one hour */ /* ******************************************************************* */ /* */ /* Partie I : constructeurs /Destructeurs */ /* */ /* */ /* Tcp4uInit, Tcp4uCleanup */ /* */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------------ */ /* Initialisation */ /* ------------------------------------------------------------------ */ int API4U Tcp4uInit (void) { int Rc=0; Tcp4uLog (LOG4U_PROC, "Tcp4uInit"); Skt4uInit (); # ifdef _WINDOWS { /* enregistrement aupres de Winsock.Dll */ WSADATA WSAData; Tcp4uLog (LOG4U_CALL, "WSAStartup, Winsock 1.1 required"); Rc = WSAStartup (MAKEWORD (1,1), & WSAData); } # endif Tcp4uLog (LOG4U_EXIT, "Tcp4uInit"); return Rc==0 ? TCP4U_SUCCESS : TCP4U_ERROR; } /* Tcp4uInit */ /* ------------------------------------------------------------------ */ /* Destructeurs */ /* ------------------------------------------------------------------ */ int API4U Tcp4uCleanup (void) { int Rc; Tcp4uLog (LOG4U_PROC, "Tcp4uCleanup"); Rc = Skt4uCleanup (); Tcp4uLog (LOG4U_EXIT, "Tcp4uCleanup"); return Rc; } /* Tcp4wCleanup */ /* ------------------------------------------------------------------ */ /* WINDOWS : Fin de vie de la DLL */ /* ------------------------------------------------------------------ */ #ifdef TCP4W_DLL int API4U WEP (int nExitType) { Tcp4uLog (LOG4U_PROC, "WEP"); Skt4uCleanup (); nExitType=0; /* suppress warning */ Tcp4uLog (LOG4U_EXIT, "WEP"); return 1; /* definition Windows */ } /* WEP */ #endif /* ------------------------------------------------------------------ */ /* Aliases : Tcp4uxInit/Tcp4uxCleanup ; Tcp4wInit/Tcp4wCleanup */ /* ------------------------------------------------------------------ */ #ifdef _WINDOWS int API4U Tcp4wInit (void) { return Tcp4uInit (); } int API4U Tcp4wCleanup (void) { return Tcp4uCleanup (); } #endif #ifdef UNIX int API4U Tcp4uxInit (void) { return Tcp4uInit (); } int API4U Tcp4uxCleanup (void) { return Tcp4uCleanup (); } #endif /* ******************************************************************* */ /* */ /* Partie I : Fonctions de bas niveau TCP */ /* */ /* */ /* TcpAbort */ /* TcpAccept */ /* TcpConnect */ /* TcpClose */ /* TcpFlush */ /* TcpGetListenSocket */ /* TcpRecv */ /* TcpSend */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------ */ /* TcpAbort: Stoppe un appel bloquant */ /* Retourne TCP4U_SUCCESS */ /* ------------------------------------------------------------ */ int API4U TcpAbort (void) { Tcp4uLog (LOG4U_PROC, "TcpAbort"); if (WSAIsBlocking ()) { Tcp4uLog (LOG4U_CALL, "WSACancelBlockingCall"); WSACancelBlockingCall (); } else Tcp4uLog (LOG4U_ERROR, "TcpAbort: No calling process to cancel"); Tcp4uLog (LOG4U_EXIT, "TcpAbort"); return TCP4U_SUCCESS; } /* TcpAbort */ /* ------------------------------------------------------------ */ /* TcpAccept : itablissement d'une connexion TCP avec Timeout */ /* Retourne TCP4U_ERROR, TCP4U_TIMEOUT, TCP4U_SUCCESS */ /* ou TCP4U_BUFFERFREED si pConnectSock n'existe plus */ /* En cas de succes la variable pConnectSock est */ /* renseignee. */ /* ------------------------------------------------------------ */ int API4U TcpAccept (SOCKET far *pCSock, SOCKET ListenSock, UINT nTO) { struct timeval TO; /* Time Out structure */ fd_set ReadMask; /* select mask */ SOCKET ConSock; struct sockaddr_in saSockAddr; /* specifications pour le Accept */ struct linger sling = { TRUE, 5 }; /* 5-seconds timeout */ int nAddrLen = sizeof saSockAddr; int Rc; Tcp4uLog (LOG4U_PROC, "TcpAccept. Listen socket %d, Timeout %d", ListenSock, nTO); /* prepare select */ FD_ZERO (& ReadMask); /* mise a zero du masque */ FD_SET (ListenSock, & ReadMask); /* Attente d'evenement en lecture */ TO.tv_sec = (long) nTO; /* secondes */ TO.tv_usec = 0; /* microsecondes */ /* s+1 normally unused but better for a lot of bugged TCP Stacks */ Tcp4uLog (LOG4U_CALL, "select on socket %d", ListenSock); Rc = select (1+ListenSock, & ReadMask, NULL, NULL, nTO==0 ? NULL : & TO); if (Rc<0) { Tcp4uLog (LOG4U_ERROR, "select on socket %d", ListenSock); return IsCancelled() ? TCP4U_CANCELLED : TCP4U_ERROR; /* erreur reseau */ } if (Rc==0) { Tcp4uLog (LOG4U_ERROR, "select on socket %d: Timeout", ListenSock); return TCP4U_TIMEOUT; } Tcp4uLog (LOG4U_CALL, "accept on listen socket %d", ListenSock); ConSock = accept (ListenSock, (struct sockaddr far *) &saSockAddr, &nAddrLen); if (ConSock==INVALID_SOCKET) { Tcp4uLog (LOG4U_ERROR, "accept on socket %d", ListenSock); return IsCancelled() ? TCP4U_CANCELLED : TCP4U_ERROR; } Skt4uRcd (ConSock, STATE_SERVER); Tcp4uLog (LOG4U_CALL, "setsockopt SOL_LINGER on socket %d", ConSock); setsockopt (ConSock, SOL_SOCKET, SO_LINGER,(LPSTR) &sling, sizeof sling); /* validite des pointeurs */ if (IsBadWritePtr (pCSock, sizeof *pCSock)) { TcpClose (& ConSock); Tcp4uLog (LOG4U_ERROR, "TcpAccept. invalid pointer"); return TCP4U_BUFFERFREED; } else { *pCSock = ConSock; Tcp4uLog (LOG4U_EXIT, "TcpAccept"); return TCP4U_SUCCESS; } } /* TcpAccept */ /* ------------------------------------------------------------ */ /* TcpClose - Fermeture d'une socket */ /* La socket pointie par pS est fermie, *pS est */ /* mise ` INVALID_SOCKET. */ /* - Retourne 1 en cas de succhs, -1 sinon (en giniral */ /* du ` l'erreur WSAEINTR) */ /* constantes (TCP4U_SUCCESS et TCP4U_ERROR) */ /* ------------------------------------------------------------ */ int API4U TcpClose (SOCKET far *pS) { SOCKET s; struct timeval TO; /* Time Out structure */ struct S_HistoSocket *pStat; /* stats about socket */ Tcp4uLog (LOG4U_PROC, "TcpClose socket %d", *pS); if (*pS==(unsigned) INVALID_SOCKET) return TCP4U_SUCCESS; /* bien passe */ s = *pS; pStat = Skt4uGetStats (s); if (pStat!=NULL && pStat->nState==STATE_LISTEN) { /* Ici une petite tempo pour les winsockets qui n'apprecient */ /* pas la succession trop rapide Accept/Close */ TO.tv_sec = 0; TO.tv_usec = 100000l; /* microsecondes */ select (s+1, NULL, NULL, NULL, & TO); } /* pause */ /* Si on effectue un shutdown (s, 2), certaines winsocket */ /* n'envoie plus la trame de longueur 0 caracteristique */ /* de la fin de connexion. */ /* On le remplace donc par le TcpFlush */ if (pStat!=NULL && pStat->nState!=STATE_LISTEN) TcpFlush (s); Tcp4uLog (LOG4U_CALL, "closesocket socket %d", s); if (CloseSocket (s)==0) { Skt4uUnRcd (s); if (!IsBadWritePtr(pS, sizeof *pS)) *pS =(unsigned) INVALID_SOCKET; else Tcp4uLog (LOG4U_ERROR, "TcpClose: Invalid pointer"); Tcp4uLog (LOG4U_EXIT, "TcpClose"); return TCP4U_SUCCESS; } Tcp4uLog (LOG4U_ERROR, "closesocket socket %d", s); return TCP4U_ERROR; } /* TcpClose */ /* --------------------------------------------------------------------- */ /* TcpConnect : Tentative d'etablissemnt d'une connexion TCP */ /* Retourne TCP4U_ERROR, TCP4U_SUCCESS, TCP4U_HOSTUNKNONW */ /* --------------------------------------------------------------------- */ int API4U TcpConnect (SOCKET far *pS, LPCSTR szHost, LPCSTR szService, unsigned short far *lpPort) { int Rc; struct sockaddr_in saSockAddr; struct servent far * lpServEnt; SOCKET connect_skt; unsigned short Zero = 0; Tcp4uLog (LOG4U_PROC, "TcpConnect. Host %s, service %s, port %u", szHost, szService==NULL ? "none" : szService, lpPort==NULL ? -1 : *lpPort); *pS = INVALID_SOCKET; /* par defaut erreur */ if (lpPort==NULL) lpPort = & Zero; /* evite de tester sans arret */ /* --- 1er champ de saSockAddr : Port */ if (szService==NULL) lpServEnt = NULL ; else { Tcp4uLog (LOG4U_DBCALL, "getservbyname %s/tcp", szService); lpServEnt = getservbyname (szService, "tcp") ; } saSockAddr.sin_port = lpServEnt!=NULL ? lpServEnt->s_port : htons(*lpPort); if (saSockAddr.sin_port == 0) return TCP4U_BADPORT; /* erreur dans port */ /* --- 2eme champ de saSockAddr : Addresse serveur */ saSockAddr.sin_addr = Tcp4uGetIPAddr (szHost); if (saSockAddr.sin_addr.s_addr==INADDR_NONE) return TCP4U_HOSTUNKNOWN; /* --- Dernier champ : liaison connectie */ saSockAddr.sin_family = AF_INET; /* on utilise le mode connecte TCP */ /* --- creation de la socket */ Tcp4uLog (LOG4U_CALL, "socket PF_INET, SOCK_STREAM"); if ( (connect_skt = socket (PF_INET, SOCK_STREAM, 0))==SOCKET_ERROR) { Tcp4uLog (LOG4U_ERROR, "socket"); return TCP4U_NOMORESOCKET; } /* --- connect retourne INVALID_SOCKET ou numero valide */ Tcp4uLog (LOG4U_CALL, "connect on host %s", inet_ntoa (saSockAddr.sin_addr)); Rc = connect (connect_skt,(struct sockaddr far *) & saSockAddr, sizeof saSockAddr); /* --- enregistrement dans notre table */ if (Rc==SOCKET_ERROR) { Tcp4uLog (LOG4U_ERROR, "connect"); CloseSocket (connect_skt); /* release buffer */ } else Skt4uRcd (connect_skt, STATE_CLIENT); *lpPort = htons (saSockAddr.sin_port); if (IsBadWritePtr (pS, sizeof *pS)) { Tcp4uLog (LOG4U_ERROR, "TcpConnect: invalid pointer"); return TCP4U_BUFFERFREED; } else *pS = Rc==SOCKET_ERROR ? INVALID_SOCKET : connect_skt; Tcp4uLog (LOG4U_EXIT, "TcpConnect"); return Rc==SOCKET_ERROR ? TCP4U_CONNECTFAILED : TCP4U_SUCCESS; } /* TcpConnect */ /* ------------------------------------------------------------ */ /* TcpFlush: Vide le buffer relatif a une socket */ /* Retourne TCP4U_ERROR, TCP4U_SUCCESS, TCP4U_CLOSEDSOCKET */ /* ------------------------------------------------------------ */ int API4U TcpFlush (SOCKET s) { int nBR=-1; char szBuf[64]; Tcp4uLog (LOG4U_PROC, "TcpFlush on socket %d", s); if (s==INVALID_SOCKET) return TCP4U_ERROR; while ( TcpIsDataAvail (s) && (nBR=recv (s,szBuf,sizeof szBuf,0)) > 0 ) Tcp4uDump (szBuf, nBR, "Flushed"); while ( TcpIsOOBDataAvail (s) &&(nBR=recv (s,szBuf,sizeof szBuf,MSG_OOB))>0 ) Tcp4uDump (szBuf, nBR, "Flushed"); Tcp4uLog (LOG4U_EXIT, "TcpFlush"); if (nBR<0) return IsCancelled() ? TCP4U_CANCELLED : TCP4U_ERROR; if (nBR==0) return TCP4U_SOCKETCLOSED; return TCP4U_SUCCESS; } /* TcpFlush */ /* ------------------------------------------------------------ */ /* TcpGetListenSocket */ /* Retourne TCP4U_ERROR, TCP4U_SUCCESS */ /* ------------------------------------------------------------ */ int API4U TcpGetListenSocket (SOCKET far *pS, LPCSTR szService, unsigned short far *lpPort, int nPendingConnection) { struct sockaddr_in saSockAddr; /* specifications pour le Accept */ int nAddrLen; SOCKET ListenSock; int One=1; int Rc; unsigned short Zero = 0; struct servent far * lpServEnt; Tcp4uLog (LOG4U_PROC, "TcpGetListenSocket on service %s, port %u", szService==NULL ? "none" : szService, lpPort==NULL ? 0 : *lpPort); *pS = INVALID_SOCKET; if (lpPort==NULL) lpPort = & Zero; /* --- 1er champ de saSockAddr : Port */ if (szService==NULL) lpServEnt = NULL ; else { Tcp4uLog (LOG4U_DBCALL, "getservbyname %s/tcp", szService); lpServEnt = getservbyname (szService, "tcp") ; } saSockAddr.sin_port = (lpServEnt!=NULL) ? lpServEnt->s_port : htons(*lpPort); #ifdef CONTROL_EN_TROP if (saSockAddr.sin_port==0) return TCP4U_BADPORT; /* erreur attribution Port */ #endif /* create socket */ Tcp4uLog (LOG4U_CALL, "socket AF_INET, SOCK_STREAM"); ListenSock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ListenSock==INVALID_SOCKET) { Tcp4uLog (LOG4U_ERROR, "socket"); return TCP4U_NOMORESOCKET; } saSockAddr.sin_family = AF_INET; saSockAddr.sin_addr.s_addr=INADDR_ANY; /* set options ReuseAddress and Linger */ Tcp4uLog (LOG4U_CALL, "setsockopt SO_REUSEADDR on sock %d", ListenSock); setsockopt (ListenSock, SOL_SOCKET, SO_REUSEADDR, (char far *)&One, sizeof One); Tcp4uLog (LOG4U_CALL, "setsockopt SO_LINGER on sock %d", ListenSock); setsockopt (ListenSock, SOL_SOCKET, SO_LINGER,(char far *)&One, sizeof One); /* Bind name to socket */ Tcp4uLog (LOG4U_CALL, "bind socket %d to %s", ListenSock, inet_ntoa (saSockAddr.sin_addr)); Rc = bind (ListenSock,(struct sockaddr far *) & saSockAddr, sizeof(struct sockaddr)); if (Rc != SOCKET_ERROR) { Tcp4uLog (LOG4U_CALL, "listen on socket %d. %d pendind connections", ListenSock, nPendingConnection); Rc = listen (ListenSock, nPendingConnection); } if (Rc==SOCKET_ERROR) { Tcp4uLog (LOG4U_ERROR, "bind or listen on socket %d", WSAGetLastError (), ListenSock); CloseSocket (ListenSock); return TCP4U_BINDERROR; } /* Get port id with getsockname */ nAddrLen = sizeof saSockAddr; memset (& saSockAddr, 0, sizeof(struct sockaddr) ); Tcp4uLog (LOG4U_DBCALL, "getsockname on socket %d", ListenSock); getsockname (ListenSock, (struct sockaddr far *) &saSockAddr, &nAddrLen); *lpPort = htons (saSockAddr.sin_port); Skt4uRcd (ListenSock, STATE_LISTEN); if (IsBadWritePtr (pS, sizeof *pS)) { Tcp4uLog (LOG4U_ERROR, "TcpGetListenSocket: invalid pointer"); return TCP4U_BUFFERFREED; } else *pS = ListenSock; Tcp4uLog (LOG4U_EXIT, "TcpGetListenSocket"); return TCP4U_SUCCESS; } /* TcpGetListenSock */ /* ------------------------------------------------------------ */ /* TcpRecv - Lecture d'une trame avec Timeout */ /* TcpRecv recoit uBufSize octets de donnies */ /* la fonction s'arrjte avant si la socket est fermie */ /* ou si une timeout arrive. */ /* - Retourne le nombre d'octets lus, */ /* TCP4U_SOCKETCLOSED si la socket a iti fermie */ /* TCP4U_ERROR sur une erreur de lecture */ /* TCP4U_TIMEOUT sur un TO */ /* TCP4U_BUFFERFREED si libiration des buffers */ /* - Remarque : Pour iviter que le buffer appelant soit */ /* libere de manihre asynchrone, la fonction utilise */ /* ses propres buffers. */ /* - Ajout des modes TCP4U_WAITFOREVER et TCP4U_WAIT */ /* ------------------------------------------------------------ */ /* forme avec log */ int API4U TcpRecv (SOCKET s, LPSTR szBuf, unsigned uBufSize, unsigned uTimeOut, HFILE hLogFile) { int Rc; Tcp4uLog (LOG4U_PROC, "TcpRecv on socket %d. Timeout %d, bufsize %d", s, uTimeOut, uBufSize); Rc = InternalTcpRecv (s, szBuf, uBufSize, uTimeOut, hLogFile); if (Rc>=TCP4U_SUCCESS) Tcp4uDump (szBuf, Rc, DUMP4U_RCVD); Tcp4uLog (LOG4U_EXIT, "TcpRecv"); return Rc; } /* TcpRecv */ /* forme sans log */ int InternalTcpRecv (SOCKET s, LPSTR szBuf, unsigned uBufSize, unsigned uTimeOut, HFILE hLogFile) { char cBuf; LPSTR p = NULL; int Rc, nUpRc; /* Return Code of select and recv */ struct timeval TO; /* Time Out structure */ struct timeval *pTO; /* Time Out structure */ fd_set ReadMask; /* select mask */ if (s==INVALID_SOCKET) return TCP4U_ERROR; FD_ZERO (& ReadMask); /* mise a zero du masque */ FD_SET (s, & ReadMask); /* Attente d'evenement en lecture */ /* detail des modes */ switch (uTimeOut) { case TCP4U_WAITFOREVER : pTO = NULL; break; case TCP4U_DONTWAIT : TO.tv_sec = TO.tv_usec=0 ; pTO = & TO; break; /* Otherwise uTimeout is really the Timeout */ default : TO.tv_sec = (long) uTimeOut; TO.tv_usec=0; pTO = & TO; break; } /* s+1 normally unused but better for a lot of bugged TCP Stacks */ Tcp4uLog (LOG4U_CALL, "select on socket %d", s); Rc = select (s+1, & ReadMask, NULL, NULL, pTO); if (Rc<0) { Tcp4uLog (LOG4U_ERROR, "select on socket %d", s); return IsCancelled() ? TCP4U_CANCELLED : TCP4U_ERROR; } if (Rc==0) { Tcp4uLog (LOG4U_ERROR, "select on socket %d: Timeout", s); return TCP4U_TIMEOUT; /* timeout en reception */ } if (szBuf==NULL || uBufSize==0) { Tcp4uLog (LOG4U_EXIT, "TcpRecv"); return TCP4U_SUCCESS; } if (uBufSize==1) /* cas frequent : lecture caractere par caractere */ p = & cBuf; else { p = Calloc (uBufSize, 1); if (p==NULL) return TCP4U_INSMEMORY; } Tcp4uLog (LOG4U_CALL, "recv socket %d, buffer %d bytes", s, uBufSize); Rc = recv (s, p, uBufSize, 0); /* chgt 11/01/95 */ switch (Rc) { case SOCKET_ERROR : Tcp4uLog (LOG4U_ERROR, "recv socket %d", s); nUpRc = IsCancelled() ? TCP4U_CANCELLED : TCP4U_ERROR ; break; case 0 : Tcp4uLog (LOG4U_ERROR,"socket %d: Host has closed connection", s); nUpRc = TCP4U_SOCKETCLOSED ; break; default : if (hLogFile!=HFILE_ERROR) Write (hLogFile, p, Rc); if (IsBadWritePtr (szBuf, 1)) nUpRc = TCP4U_BUFFERFREED; else memcpy (szBuf, p, nUpRc=Rc); break; } /* translation des codes d'erreurs */ if (p!=NULL && uBufSize!=1) Free (p); return nUpRc; } /* TcpRecv */ /* ------------------------------------------------------------ */ /* TcpSend : Envoi de uBufSize octets vers le distant */ /* Retourne TCP4U_ERROR ou TCP4U_SUCCESS */ /* ------------------------------------------------------------ */ /* forme avec log */ int API4U TcpSend (SOCKET s, LPCSTR szBuf, unsigned uBufSize, BOOL bHighPriority, HFILE hLogFile) { int Rc; Tcp4uLog (LOG4U_PROC,"TcpSend on socket %d. %d bytes to be sent",s,uBufSize); Rc = InternalTcpSend (s, szBuf, uBufSize, bHighPriority, hLogFile); if (Rc==TCP4U_SUCCESS) Tcp4uDump (szBuf, uBufSize, DUMP4U_SENT); Tcp4uLog (LOG4U_EXIT, "TcpSend"); return Rc; } /* TcpSend */ /* forme sans log */ int InternalTcpSend (SOCKET s, LPCSTR szBuf, unsigned uBufSize, BOOL bHighPriority, HFILE hLogFile) { int Rc; unsigned Total; LPSTR p; if (s==INVALID_SOCKET) return TCP4U_ERROR; p = Calloc (uBufSize, 1); if (p==NULL) return TCP4U_INSMEMORY; memcpy (p, szBuf, uBufSize); if (hLogFile!=HFILE_ERROR) Write (hLogFile, p, uBufSize); for ( Total = 0, Rc = 1 ; Total < uBufSize && Rc > 0 ; Total += Rc) { Tcp4uLog (LOG4U_CALL, "send on socket %d. %d bytes to be sent", s, uBufSize-Total); Rc = send (s, & p[Total], uBufSize-Total, bHighPriority ? MSG_OOB : 0); if (Rc<=0) Tcp4uLog (LOG4U_ERROR, "send on socket %d.", s); } Free(p); return Total>=uBufSize ? TCP4U_SUCCESS : IsCancelled() ? TCP4U_CANCELLED : TCP4U_ERROR; } /* TcpSend */ /* ******************************************************************* */ /* */ /* Partie I (suite) : Fonctions d'information */ /* */ /* TcpGetLocalID */ /* TcpGetRemoteID */ /* TcpIsDataAvail */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------ */ /* TcpGetLocalID: Retourne nom et adresse IP de la station */ /* Retourne TCP4U_SUCCESS, TCP4U_ERROR */ /* ------------------------------------------------------------ */ int API4U TcpGetLocalID (LPSTR szStrName, int uNameSize, DWORD far *lpAddress) { char szName[128]; struct hostent far *lpHostEnt; int Rc; Tcp4uLog (LOG4U_PROC, "TcpGetLocalID"); if (lpAddress!=NULL) memset (lpAddress, 0, sizeof (DWORD)); /* on envisage 2 methodes pour obtenir le nom du PC */ /* d'abord un appel a gethostname */ Tcp4uLog (LOG4U_DBCALL, "gethostname"); if (gethostname (szName, sizeof szName)==SOCKET_ERROR) return TCP4U_ERROR; if (lpAddress != NULL) { Tcp4uLog (LOG4U_DBCALL, "gethostbyname on host %s", szName); lpHostEnt = gethostbyname (szName); if (lpHostEnt==NULL) return TCP4U_ERROR; memcpy (lpAddress, lpHostEnt->h_addr_list[0], lpHostEnt->h_length); } if (szStrName!=NULL) { Strcpyn (szStrName, szName, uNameSize); Rc = Strlen(szName)>Strlen(szStrName) ? TCP4U_OVERFLOW : TCP4U_SUCCESS; } else Rc = TCP4U_SUCCESS; Tcp4uLog (LOG4U_EXIT, "TcpGetLocalID"); return TCP4U_SUCCESS; } /* TcpGetLocalID */ /* ------------------------------------------------------------ */ /* TcpGetRemoteID: Retourne nom et adresse IP du distant */ /* Retourne TCP4U_SUCCESS, TCP4U_ERROR */ /* ------------------------------------------------------------ */ int API4U TcpGetRemoteID (SOCKET s, LPSTR szStrName, int uNameSize, DWORD far *lpAddress) { struct sockaddr_in SockAddr; int SockAddrLen=sizeof SockAddr; struct hostent far *lpHostEnt; Tcp4uLog (LOG4U_PROC, "TcpGetRemoteID on socket %d", s); /* determiner l'adress IP de la station distante */ Tcp4uLog (LOG4U_DBCALL, "getpeername on socket %d", s); if (getpeername (s, (struct sockaddr far *) & SockAddr, & SockAddrLen)==SOCKET_ERROR) { Tcp4uLog (LOG4U_ERROR, "getpeername on socket %d", s); return TCP4U_ERROR; } if (lpAddress!=NULL) memcpy (lpAddress, & SockAddr.sin_addr.s_addr, sizeof SockAddr.sin_addr.s_addr); if (szStrName!=NULL && uNameSize > 0) { /* determiner par gethostbyaddr le nom de la station */ szStrName[0]=0; /* si erreur */ Tcp4uLog (LOG4U_DBCALL, "gethostbyaddr on host %s", inet_ntoa (SockAddr.sin_addr)); lpHostEnt = gethostbyaddr ((LPSTR) & SockAddr.sin_addr.s_addr, 4, PF_INET); if (lpHostEnt!=NULL) Strcpyn (szStrName, lpHostEnt->h_name, uNameSize); else Tcp4uLog (LOG4U_ERROR, "gethostbyaddr"); } Tcp4uLog (LOG4U_EXIT, "TcpGetRemoteID"); return TCP4U_SUCCESS; } /* TcpGetRemoteID */ /* ------------------------------------------------------------- */ /* TcpIsDataAvail: Retourne VRAI si des donnees sont disponibles */ /* ------------------------------------------------------------- */ BOOL API4U TcpIsDataAvail (SOCKET s) { unsigned long ulData; int Rc; Tcp4uLog (LOG4U_PROC, "TcpIsDataAvail on socket %d", s); Tcp4uLog (LOG4U_CALL, "Ioctl FIONREAD on socket %d", s); Rc = IoctlSocket (s, FIONREAD, & ulData); Tcp4uLog (LOG4U_EXIT, "TcpIsDataAvail"); return Rc==0 && ulData>0; } /* TcpIsDataAvail */ /* ------------------------------------------------------------- */ /* TcpIsOOBDataAvail: Retourne VRAI si des donnees Out Of Band */ /* sont disponibles */ /* ------------------------------------------------------------- */ BOOL API4U TcpIsOOBDataAvail (SOCKET s) { unsigned long ulData; int Rc; Tcp4uLog (LOG4U_PROC, "TcpIsOOBDataAvail on socket %d", s); Rc = IoctlSocket (s, SIOCATMARK, & ulData); Tcp4uLog (LOG4U_EXIT, "TcpIsOOBDataAvail"); return Rc==0 && ! ulData; } /* TcpIsOOBDataAvail */ /* ******************************************************************* */ /* */ /* Partie II : Gestion d'un mini- protocole */ /* */ /* */ /* TcpPPSend - TcpPPRecv */ /* */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------ */ /* TcpPPRecv - Lecture d'une trame avec Timeout */ /* TcpPPRecv recoit uBufSize octets de donnies */ /* la fonction s'arrjte avant si la socket est fermie */ /* ou si un timeout arrive. */ /* - Retourne le nombre d'octets lus, */ /* TCP4U_SOCKETCLOSED si la socket a iti fermie */ /* TCP4U_ERROR sur une erreur de lecture */ /* TCP4U_TIMEOUT sur un TO */ /* TCP4U_BUFFERFREED si libiration des buffers */ /* - Remarque : Pour iviter que le buffer appelant soit */ /* libiri de manihre asynchrone, la fonction utilise */ /* ses propres buffers. */ /* ------------------------------------------------------------ */ int API4U TcpPPRecv (SOCKET s, LPSTR szBuf, unsigned uBufSize, unsigned uTimeOut, BOOL bExact, HFILE hLogFile) { LPSTR p, q; int Rc, nUpRc; /* Return Code of select and recv */ unsigned short nToBeReceived, nReceived; Tcp4uLog (LOG4U_PROC, "TcpPPRecv on socket %d. Timeout %d, buffer %d bytes", s, uTimeOut, uBufSize); if (s==INVALID_SOCKET) return TCP4U_ERROR; Rc = TcpRecv (s, (LPSTR) & nToBeReceived, 2, uTimeOut, hLogFile); if (Rc<TCP4U_SUCCESS) return Rc; /* remise dans l'ordre PC */ nToBeReceived = ntohs (nToBeReceived); /* Si longueur connue a l'avance, sinon ne pas depasser le buffer donne */ if (bExact && nToBeReceived!=uBufSize) return TCP4U_UNMATCHEDLENGTH; if (uBufSize < nToBeReceived) return TCP4U_OVERFLOW; if (nToBeReceived==0) return TCP4U_EMPTYBUFFER; /* On elimine une des causes de crash: on lit dans un buffer qui n'existe plus */ q = p = Calloc (nToBeReceived, 1); if (p==NULL) return TCP4U_INSMEMORY; nReceived = 0; nUpRc=0; do /* On boucle tant qu'on a pas eu les nToBeReceived octets */ { nUpRc = TcpRecv (s, q, nToBeReceived - nReceived, uTimeOut/4 + 1, hLogFile); nReceived += (short) nUpRc; q += nUpRc; } while (nUpRc>0 && nReceived<nToBeReceived); /* Analyse du code de retour */ if (nUpRc >= TCP4U_SUCCESS) { if (IsBadWritePtr (szBuf, nToBeReceived)) nUpRc = TCP4U_BUFFERFREED; else memcpy (szBuf, p, nUpRc=nToBeReceived); } Free (p); Tcp4uLog (LOG4U_EXIT, "TcpPPRecv"); return nUpRc; } /* TcpPPRecv */ /* -------------------------------------------------------------- */ /* TcpPPSend : Envoi de uBufSize octets vers le distant */ /* Retourne TCP4U_ERROR ou TCP4U_SUCCESS */ /* -------------------------------------------------------------- */ int API4U TcpPPSend (SOCKET s, LPCSTR szBuf, unsigned uBufSize, HFILE hLogFile) { int Rc; unsigned short Total; Tcp4uLog (LOG4U_PROC, "TcpPPSend on socket %d. %d bytes to send", s, uBufSize); if (s==INVALID_SOCKET) return TCP4U_ERROR; /* Envoi de la longueur de la trame sur 2 octets */ Total = htons ((unsigned short) uBufSize); Rc = TcpSend (s, (void far *) & Total, 2, FALSE, hLogFile); /* cas d'une sequence vide -> envoi de 0 OK: retour OK */ if (Rc>=TCP4U_SUCCESS && uBufSize>0) /* maintenant on envoie la sequence (qui n'est pas vide) */ Rc = TcpSend (s, szBuf, uBufSize, FALSE, hLogFile); Tcp4uLog (LOG4U_EXIT, "TcpPPSend"); return Rc; } /* TcpPPSend */ /* ******************************************************************* */ /* */ /* Partie III : Lecture Jusqu'a ... */ /* */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------ */ /* TcpRecvUntilStr */ /* Recois des donnees jusqu'a */ /* - Une erreur */ /* - Une Fermeture de socket */ /* - un timeout */ /* - la reception de la chaine szStop */ /* - le remplissage du buffer */ /* Le Retour soit un code d'erreur, soit TCP4U_SUCCESS */ /* Si c'est TCP4U_OVERFLOW, uBufSize octes ont iti lus, mais */ /* la chaine szStop n'a pas iti trouvie */ /* Si c'est TCP4U_SOCKETCLOSED, le distant a ferme la connexion */ /* La chaine szStop n'est pas ajoutie au buffer */ /* lpBufSize contient le nombre d'octets lus */ /* NOTE: Cette fonction est incompatible avec La pile de Novell */ /* LAN Workplace */ /* ------------------------------------------------------------ */ /* redeclaration de tolower: MSCV2 semble avoir des problemes avec */ static char ToLower (char c) { return (c>='A' && c<='Z') ? c + ('a' -'A') : c; } /* ToLower */ /* compare les chaines s1 et s2 sur nLength caracteres */ /* retourne TRUE si les deux chaines sont identiques */ static BOOL uMemcmp (LPSTR s1, LPSTR s2, int nLength, BOOL bCaseSensitive) { int Evan; if (bCaseSensitive) return memcmp (s1, s2, nLength)==0; else { for (Evan=0 ; Evan<nLength && ToLower(s1[Evan])==ToLower(s2[Evan]) ; Evan++); return Evan==nLength; } } /* uMemcmp */ /* Sous procedure : Recherche de la sous chaine s2 dans s1 */ /* Renvoie l'index de s1 auquel on peut trouver s2 */ /* ou -1 si s2 n'est pas incluse dans s1, dans */ /* ce cas, *nProx est le nombre d'octets de */ /* s2 contenu ` la fin de s1 */ static int FindPos (LPSTR s1, int ns1, LPSTR s2, int ns2, int *npProx, BOOL bCaseSensitive) { int Ark; BOOL bNotFound; if (*npProx!=0) /* on compare aussi si l'inclusion ne continue pas */ { if (ns1<ns2-*npProx && uMemcmp (s1, & s2[*npProx], ns1, bCaseSensitive)) { *npProx+=ns1 ; return -1; } if (ns1>=ns2-*npProx && uMemcmp (s1, & s2[*npProx], ns2-*npProx, bCaseSensitive)) { return 0; } } /* traitement des antecedents */ for ( Ark=0, bNotFound=TRUE; Ark<=ns1-ns2 && (bNotFound= ! uMemcmp (& s1[Ark], s2, ns2, bCaseSensitive)) ; Ark++) ; /* recherche de s2 */ if (bNotFound) { for ( *npProx = min (ns1, ns2-1) ; *npProx>0 && !uMemcmp (& s1[ns1-*npProx], s2, *npProx, bCaseSensitive); (*npProx)-- ); } return bNotFound ? -1 : Ark; /* si bNotFounf, *npProx est positionne */ } /* FindPos */ int API4U TcpRecvUntilStr (SOCKET s, LPSTR szBuf,unsigned far *lpBufSize, LPSTR szStop, unsigned uStopSize, BOOL bCaseSensitive, unsigned uTimeOut, HFILE hLogFile) { int Rc; Tcp4uLog ( LOG4U_PROC, "TcpRecvUntilStr on socket %d. Timeout %d, buffer %d bytes", s, uTimeOut, *lpBufSize); Rc = InternalTcpRecvUntilStr (s, szBuf, lpBufSize, szStop, uStopSize, bCaseSensitive, uTimeOut, hLogFile); if (Rc==TCP4U_SUCCESS) Tcp4uDump (szBuf, *lpBufSize, DUMP4U_RCVD); if (Rc==TCP4U_OVERFLOW) Tcp4uDump (szBuf, *lpBufSize, "Overflow"); Tcp4uLog (LOG4U_EXIT, "TcpRecvUntilStr"); return Rc; } /* TcpRecvUntilStr */ int InternalTcpRecvUntilStr (SOCKET s, LPSTR szBuf,unsigned far *lpBufSize, LPSTR szStop, unsigned uStopSize, BOOL bCaseSensitive, unsigned uTimeOut, HFILE hLogFile) { unsigned uNbRecus; static int nProxy; /* Proxy sert si clef partagee sur 2 trames */ LPSTR pTest = NULL; int Rc; int Idx; #define XX_RETURN(x,s) \ { if (pTest!=NULL) Free(pTest); \ *lpBufSize=uNbRecus; \ Tcp4uLog (LOG4U_ERROR, IsCancelled() ? "call cancelled" : s); \ return IsCancelled() ? TCP4U_CANCELLED : x; } if (s==INVALID_SOCKET || *lpBufSize==0) return TCP4U_ERROR; /* On prend un buffer qui permet de lire la trame, */ /* la chaine de stop et qui soit toujours 0-terminee */ /* Le recv suivant est sur de ne pas bloquer, vu que */ /* le PEEK a rendu OK */ pTest = Calloc (*lpBufSize+uStopSize+1, 1); if (pTest==NULL) return TCP4U_INSMEMORY; uNbRecus = 0; do { Rc = InternalTcpRecv (s, NULL, 0, uTimeOut, HFILE_ERROR); /* ereur select */ if (Rc != TCP4U_SUCCESS) XX_RETURN (Rc, "Timeout"); /* Lecture en MSG_PEEK */ Tcp4uLog (LOG4U_CALL, "recv on socket %d. MSG_PEEK, buffer %d bytes", s, *lpBufSize + uStopSize - uNbRecus); Rc = recv (s, & pTest[uNbRecus], *lpBufSize+uStopSize-uNbRecus, MSG_PEEK); if (Rc<=0) XX_RETURN (Rc, "TcpRecvUntilStr"); /* --- Maintenant on distingue 2 cas: */ /* Cas 1 : la clef est dans le buffer, */ Idx = FindPos (& pTest[uNbRecus], Rc, szStop, uStopSize, & nProxy, bCaseSensitive); if (Idx!=-1) /* la clef est disponible -> pas de probleme */ { if ( IsBadWritePtr (& szBuf[uNbRecus], Idx) ) XX_RETURN (TCP4U_BUFFERFREED, "TcpRecvUntilStr: invalid pointer") else { if (Idx!=0) { InternalTcpRecv (s, & szBuf[uNbRecus], Idx, 0, hLogFile); uNbRecus += Idx; } else uNbRecus -= nProxy; *lpBufSize = uNbRecus; InternalTcpRecv (s, pTest, uStopSize - (Idx==0 ? nProxy:0), 0, hLogFile); nProxy = 0; /* pour la prochaine recherche */ Free (pTest); return TCP4U_SUCCESS; } } /* chaine trouvee */ else /* Cas 2 : la clef n'est pas dans le buffer */ {int nToBeReceived = min (Rc, (signed) (*lpBufSize-uNbRecus)); if (IsBadWritePtr (& szBuf[uNbRecus], nToBeReceived) ) { Free (pTest); Tcp4uLog (LOG4U_ERROR, "TcpRecvUntilStr: invalid pointer"); return TCP4U_BUFFERFREED; } else { InternalTcpRecv (s, & szBuf[uNbRecus], nToBeReceived , 0, hLogFile); uNbRecus += nToBeReceived; } } /* chaine pas trouvee */ } while (uNbRecus<*lpBufSize); Free (pTest); *lpBufSize = uNbRecus; #undef XX_RETURN return TCP4U_OVERFLOW; } /* InternalTcpRecvUntilStr */ <file_sep>#include "StdAfx.h" #include "InitMan.h" #include "Dll_Tools.h" #include "vt_python_funcs.h" static vt_python_man *_im; #include "PythonModule.h" #ifdef RegisterClassA #undef RegisterClassA #endif #include "VSLManagerSDK.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// vt_python_man::vt_python_man(CKContext* context):CKBaseManager(context,INIT_MAN_GUID,"vt_python_man")//Name as used in profiler { m_Context->RegisterNewManager(this); _im = this; } void vt_python_man::RegisterVSL(){ STARTVSLBIND(m_Context) DECLAREPOINTERTYPE(PythonModule) DECLARESTATIC_3(PythonModule,PythonModule*,CreatePythonModule,const char*,const char*,int) DECLAREFUN_C_0(void,vpCInit) DECLAREFUN_C_1(void,vpCPyRun_SimpleString,const char*) //DECLAREFUN_S_3(const char*,vpSimpleTest,const char*,const char*,const char*) DECLAREFUN_C_0(void,DestroyPython) DECLAREFUN_C_0(void,PythonLoad) /************************************************************************/ /* Variable|Parameter Stuff */ /************************************************************************/ //DECLAREFUN_C_3(BOOL,VT_SetVariableValue,const char*, int,bool ) //DECLAREFUN_C_1(BOOL,ImportVars,const char*) /*DECLAREFUN_C_4(BOOL, WriteIniValue, const char* ,const char*,const char*,const char*) DECLAREFUN_C_1(BOOL, CreatePath,const char*) DECLAREFUN_C_0(void, testAll) DECLAREFUN_C_2(BOOL, ShowNodalDebug,CKGroup*,BOOL)*/ STOPVSLBIND }<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SetInMidiPort // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "../MidiManager.h" CKERROR CreateSetInMidiPortProto(CKBehaviorPrototype **); int SetInMidiPort(const CKBehaviorContext& behcontext); CKERROR SetInMidiPortCallBack(const CKBehaviorContext& behcontext); // CallBack Functioon /*******************************************************/ /* PROTO DECALRATION */ /*******************************************************/ CKObjectDeclaration *FillBehaviorSetInMidiPortDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Set Midi Input Port"); od->SetDescription("Sets the Midi Input Port (usally 0)."); od->SetType( CKDLL_BEHAVIORPROTOTYPE ); od->SetGuid(CKGUID(0x42d96c11,0x64242546)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetInMidiPortProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Controllers/Midi"); return od; } /*******************************************************/ /* PROTO CREATION */ /*******************************************************/ CKERROR CreateSetInMidiPortProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set Midi Input Port"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Midi Input Port", CKPGUID_INT, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetInMidiPort); proto->SetBehaviorCallbackFct( SetInMidiPortCallBack ); *pproto = proto; return CK_OK; } /*******************************************************/ /* MAIN FUNCTION */ /*******************************************************/ int SetInMidiPort(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); mm->DesiredmidiDevice = 0; beh->GetInputParameterValue(0, &mm->DesiredmidiDevice); return CKBR_OK; } /*******************************************************/ /* CALLBACK */ /*******************************************************/ CKERROR SetInMidiPortCallBack(const CKBehaviorContext& behcontext){ CKBehavior *beh = behcontext.Behavior; MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); switch( behcontext.CallbackMessage ){ case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: { mm->AddMidiBBref(); } break; case CKM_BEHAVIORDETACH: { mm->RemoveMidiBBref(); } break; } return CKBR_OK; } <file_sep>/****************************************************************************** File : CustomPlayerDefines.h Description: This file contains some defines/enums/types used by the project. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ #if !defined(CUSTOMPLAYERDEFINES_H) #define CUSTOMPLAYERDEFINES_H /************************************************************************/ /* Error Codes : */ /************************************************************************/ #define INIT_ERROR "Initialisation Error" #define CANNOT_READ_CONFIG "Cannot read configuration/command line.\nPlayer will quit!" #define FAILED_TO_CREATE_WINDOWS "Unable to create windows.\nPlayer will quit!" #define UNABLE_TO_INIT_PLUGINS "Unable to initialize plugins.\nPlayer will quit!" #define UNABLE_TO_LOAD_RENDERENGINE "Unable to load a RenderEngine.\nPlayer will quit!" #define UNABLE_TO_INIT_CK "Unable to initialize CK Engine.\nPlayer will quit!" #define UNABLE_TO_INIT_MANAGERS "Unable to initialize Managers.\nPlayer will quit!" #define UNABLE_TO_INIT_DRIVER "Unable to initialize display driver.\nPlayer will quit!" #define UNABLE_TO_CREATE_RENDERCONTEXT "Cannot initialize RenderContext.\nPlayer will quit!" #define CANNOT_FIND_LEVEL "Cannot find Level.\nPlayer will quit!" #define MAINWINDOW_TITLE "Virtools Custom Player" #define MAINWINDOW_CLASSNAME "CustomPlayer" #define RENDERWINDOW_CLASSNAME "CustomPlayerRender" #define MISSINGUIDS_LOG "CustomPlayerMissingGuids.log" // [11/28/2007 mc007] ////////////////////////////////////////////////////////////////////////// // // PROFILE LOAD ERRORS // #define CPE_OK 0 #define CPE_PROFILE_STARTING_ERROR 0 #define CPE_PROFILE_ERROR_FILE_ERROR (CPE_PROFILE_STARTING_ERROR + 10) #define CPE_PROFILE_ERROR_FILE_INCORRECT (CPE_PROFILE_ERROR_FILE_ERROR + 1) #define CPE_PROFILE_ERROR_FILE_INCORRECT_DESC "Couldnt Load File" #define CPE_PROFILE_ERROR_ENTRY_INCORRECT (CPE_PROFILE_ERROR_FILE_ERROR + 2) #define CPE_PROFILE_ERROR_ENTRY_INCORRECT_DESC "Couldnt find entry" #define CPE_PROFILE_ERROR_PROFILEID_INCORRECT_PARAM (CPE_PROFILE_ERROR_FILE_ERROR + 2) #define CPE_PROFILE_ERROR_PROFILEID_INCORRECT_PARAM_DESC "Missing or incorrect parameter provided" #define CUSTOM_PLAYER_CONFIG_FILE "player.ini" // [12/15/2007 mc007] ////////////////////////////////////////////////////////////////////////// // // Application Requirements : #define CPR_CHECK_DIRECTX 1 // this leads to a directx check, is using xUtils.dll #define CPR_MINIMUM_DIRECTX_VERSION 9 // this is our minimum version #define CPR_MINIMUM_DIRECTX_VERSION_FAIL_URL "http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=2da43d38-db71-4c1b-bc6a-9b6652cd92a3" #define CPR_OFFER_INTERNAL_DIRECTX_INSTALLER 0 // not implemented #define CPR_CHECK_RAM 1 //performes a memory check, is using xUtils.dll and it needs a directx !!! #define CPR_MINIMUM_RAM 256 //our minimum pRam #define CPR_MINIMUM_RAM_FAIL_ABORT 0 // this leads to a application exit ! #define CP_SUPPORT_EMAIL "<EMAIL>" // // [12/16/2007 mc007] ////////////////////////////////////////////////////////////////////////// // // Application Features : #define CPF_SPLASH_FILE "splash.bmp" //not used ! #define CPF_SPLASH_TEXT_TYPE "MicrogrammaDBolExt" #define CPF_SPLASH_TEXT_FORMAT (DT_SINGLELINE | DT_RIGHT | DT_BOTTOM) // [12/17/2007 mc007] #define CPA_SHOW_ABOUT_TAB 1 //adds an about tab, is using about.txt from \project source folder \res #define CPA_SHOW_LICENSE_TAB 0 //adds an about tab, is using license.txt from \project source folder \res #define CPA_SHOW_ERROR_TAB 1 #define CPA_ABORT_ON_ERROR 1 // aborts when the requirements are failing ////////////////////////////////////////////////////////////////////////// #define PUBLISHING_RIGHT_TITLE "AtlantisVR.com" #define PUBLISHING_RIGHT_TEXT \ "Click Okay for hooray\n" \ "code prior to compilation).\n\n" \ "This dialog box serves to remind you that publishing rights, a.k.a. runtime\n" \ "fees, are due when building any custom executable (like the player you just\n" \ "compiled). Contact <EMAIL> for more information.\n" enum EConfigPlayer { eAutoFullscreen = 1, // -auto_fullscreen (or -f) on command line eDisableKeys = 2 // -disable_keys (or -d) on command line }; #endif // CUSTOMPLAYERDEFINES_H<file_sep>#ifndef __P_ERRROR_STREAM_H__ #define __P_ERRROR_STREAM_H__ #include "pTypes.h" #include "NxUserOutputStream.h" namespace vtAgeia { class pErrorStream : public NxUserOutputStream { public: pErrorStream(){} void reportError(NxErrorCode e, const char* message, const char* file, int line); NxAssertResponse reportAssertViolation(const char* message, const char* file, int line); void print(const char* message); }; } #endif<file_sep>#include "BaseMacros.hpp" #include "pch.h" #include "CKAll.h" #ifdef __cplusplus extern "C" { #endif API_EXPORT int API_cDECL InitPyVTModule(CKContext** _ctx); #ifdef __cplusplus } #endif ////////////////////////////////////////////////////////////////////////// #include <iostream> using namespace std; #include <boost/python.hpp> namespace python = boost::python; class Player { public: Player() {} Player( std::string name ) : m_name(name) {} Player( std::string name, int score ) : m_name(name), m_score(score) {} void setName( std::string name ) { m_name = name; } std::string getName() { return m_name; } void setScore( int score ) { m_score = score; } int getScore() { return m_score; } private: std::string m_name; int m_score; }; BOOST_PYTHON_MODULE( PyVT ) { python::class_<Player>("Player") .def( python::init<std::string>() ) // Overloaded constructor version #1 .def( python::init<std::string, int>() ) // Overloaded constructor version #2 .def( "setName", &Player::setName ) .def( "getName", &Player::getName ) .def( "setScore", &Player::setScore ) .def( "getScore", &Player::getScore ) ; } BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { //DisableThreadLibraryCalls(NULL); //MessageBox(NULL,"","attach",0); // int y = 0; } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #include "pch.h" #include "CKAll.h" CKContext *mctx=NULL; int InitPyVTModule(CKContext ** _ctx) { //MessageBox(NULL,"","asd",0); DebugBreak(); if( PyImport_AppendInittab( "PyVT", initPyVT ) == -1 ) throw runtime_error( "Failed to add \"testDerived\" to the " "interpreter's built-in modules" ); if(*_ctx) { mctx = *_ctx; mctx->OutputToConsole("ASDASD"); printf(("asdasdasd")); return 1; } return 0; } <file_sep>/******************************************************************** created: 2007/11/28 created: 28:11:2007 16:25 filename: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Dialogs\CustomPlayerConfigurationDialog.cpp file path: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Dialogs file base: CustomPlayerConfigurationDialog file ext: cpp author: mc007 purpose: *********************************************************************/ #include <CPStdAfx.h> #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" ////////////////////////////////////////////////////////////////////////// // // // // ////////////////////////////////////////////////////////////////////////// extern CCustomPlayer* thePlayer; vtPlayer::Structs::xEApplicationMode CCustomPlayer::PGetApplicationMode(const char* pstrCommandLine) { using namespace vtPlayer::Structs; // Skip the first part of the command line, which is the full path // to the exe. If it contains spaces, it will be contained in quotes. if (*pstrCommandLine == TEXT('\"')) { pstrCommandLine++; while (*pstrCommandLine != TEXT('\0') && *pstrCommandLine != TEXT('\"')) pstrCommandLine++; if( *pstrCommandLine == TEXT('\"') ) pstrCommandLine++; } else { while (*pstrCommandLine != TEXT('\0') && *pstrCommandLine != TEXT(' ')) pstrCommandLine++; if( *pstrCommandLine == TEXT(' ') ) pstrCommandLine++; } // Skip along to the first option delimiter "/" or "-" while ( *pstrCommandLine != TEXT('\0') && *pstrCommandLine != TEXT('/') && *pstrCommandLine != TEXT('-') ) pstrCommandLine++; // If there wasn't one, then must be config mode if ( *pstrCommandLine == TEXT('\0') ) return normal; // Otherwise see what the option was switch ( *(++pstrCommandLine) ) { case 'p': case 'P': pstrCommandLine++; while ( *pstrCommandLine && !isdigit(*pstrCommandLine) ) pstrCommandLine++; if ( isdigit(*pstrCommandLine) ) { #ifdef _WIN64 CHAR strCommandLine[2048]; DXUtil_ConvertGenericStringToAnsiCb(strCommandLine, pstrCommandLine, sizeof(strCommandLine)); m_hWndParent = (HWND)(_atoi64(strCommandLine)); #else m_hWndParent = (HWND)LongToHandle(_ttol(pstrCommandLine)); #endif } return preview; // call config dialog : case 'C': case 'c': return config; case 'D': case 'd': return popup; break; default: // All other options => run the screensaver (typically this is "/s") return normal; } return normal; } <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "ISession.h" #include "IMessages.h" #include "xLogger.h" #include "vtLogTools.h" #include "xMessageTypes.h" CKObjectDeclaration *FillBehaviorNSetParametersDecl(); CKERROR CreateNSetParametersProto(CKBehaviorPrototype **); int NSetParameters(const CKBehaviorContext& behcontext); CKERROR NSetParametersCB(const CKBehaviorContext& behcontext); typedef enum BB_IT { BB_IT_IN, }; typedef enum BB_INPAR { BB_IP_MIN_MANAGER, BB_IP_MIN_MESSAGE_TICK, BB_IP_MESSAGE_TIMEOUT, BB_IP_CONNECTION_TIMEOUT, BB_IP_PACKET_LOSS, BB_IP_LATENCY, BB_IP_MIN_SEND_PERIOD, BB_IP_MIN_RECV_PERIOD, BB_IP_MAX_SEND_BANDWITH, BB_IP_MAX_RECV_BANDWITH }; typedef enum BB_OT { BB_O_ERROR, }; typedef enum BB_OP { BB_OP_ERROR, }; CKObjectDeclaration *FillBehaviorNSetParametersDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NSetParameters"); od->SetDescription("Sends a Message to a Network."); od->SetCategory("TNL/Misc"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7dc37c6f,0x524f7732)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNSetParametersProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateNSetParametersProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NSetParameters"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Min Tick Time Manager", CKPGUID_FLOAT, "50"); proto->DeclareInParameter("Min Tick Time Message Send", CKPGUID_FLOAT, "50"); proto->DeclareInParameter("Message Timeout", CKPGUID_FLOAT, "300"); proto->DeclareInParameter("Connection Timeout", CKPGUID_FLOAT, "3000"); proto->DeclareInParameter("Packet Loss", CKPGUID_FLOAT, "0.1"); proto->DeclareInParameter("Latency",CKPGUID_INT, "100"); proto->DeclareInParameter("MinPacketSendPeriod",CKPGUID_INT,"50"); proto->DeclareInParameter("MinPacketRecvPeriod",CKPGUID_INT,"50"); proto->DeclareInParameter("MaxSendBandwidth",CKPGUID_INT,"2000"); proto->DeclareInParameter("MaxRecvBandwidth",CKPGUID_INT,"2000"); proto->DeclareSetting("Only Client", CKPGUID_BOOL, "FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(NSetParameters); proto->SetBehaviorCallbackFct(NSetParametersCB); *pproto = proto; return CK_OK; } int NSetParameters(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); using namespace vtTools::BehaviorTools; bbNoError(E_NWE_OK); beh->ActivateInput(0,FALSE); float minManagerTick = GetInputParameterValue<float>(beh,BB_IP_MIN_MANAGER); float messageTick = GetInputParameterValue<float>(beh,BB_IP_MIN_MESSAGE_TICK); float messageTimeout = GetInputParameterValue<float>(beh,BB_IP_MESSAGE_TIMEOUT); float connectionTimeout = GetInputParameterValue<float>(beh,BB_IP_CONNECTION_TIMEOUT); float packetLoss = GetInputParameterValue<float>(beh,BB_IP_PACKET_LOSS); int latency = GetInputParameterValue<int>(beh,BB_IP_LATENCY); int MinPacketSendPeriod = GetInputParameterValue<int>(beh,BB_IP_MIN_SEND_PERIOD); int MinPacketRecvPeriod = GetInputParameterValue<int>(beh,BB_IP_MIN_RECV_PERIOD); int MaxSendBandwidth = GetInputParameterValue<int>(beh,BB_IP_MAX_SEND_BANDWITH); int MaxRecvBandwidth = GetInputParameterValue<int>(beh,BB_IP_MAX_RECV_BANDWITH); int clientOnly = false; beh->GetLocalParameterValue(0,&clientOnly); //void NetConnection:: //setFixedRateParameters(U32 minPacketSendPeriod, U32 minPacketRecvPeriod, U32 maxSendBandwidth, U32 maxRecvBandwidth) //setFixedRateParameters(50, 50, 2000, 2000); if (minManagerTick < 50) { minManagerTick = 50.0f; } if (messageTick < 50) { messageTick = 50.0f; } if (messageTimeout< 150) { messageTimeout = 150.0f; } if (connectionTimeout < 200.0f) { connectionTimeout = 200.0f; } if (latency < 0) { latency = 0; } if (packetLoss < 0.0f) { packetLoss = 0.0f; } if (packetLoss > 1.0f) { packetLoss= 1.0f; } GetNM()->setMinTickTime(minManagerTick); xNetInterface *cin = GetNM()->GetClientNetInterface(); if (cin) { if (cin->isValid()) { vtConnection *con = cin->getConnection(); if (con) { con->setSimulatedNetParams(packetLoss,latency); con->setPingTimeouts(connectionTimeout,3); cin->setFixedRateParameters(MinPacketSendPeriod,MinPacketRecvPeriod,MaxSendBandwidth,MaxRecvBandwidth,false); } } cin->getMessagesInterface()->setMessageTimeout(messageTimeout); cin->getMessagesInterface()->setMinSendTime(messageTick); } if (!clientOnly) { cin = GetNM()->GetServerNetInterface(); if (cin) { cin->getMessagesInterface()->setMessageTimeout(messageTimeout); cin->getMessagesInterface()->setMinSendTime(messageTick); cin->setFixedRateParameters(MinPacketSendPeriod,MinPacketRecvPeriod,MaxSendBandwidth,MaxRecvBandwidth,true); } } beh->ActivateOutput(0); return CKBR_OK; } CKERROR NSetParametersCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#ifndef __vtNetEnumerations_h #define __vtNetEnumerations_h #define xBIT(x) (1 << (x)) ///< Returns value with bit x set (2^x) typedef enum E_DV_STATE { E_DV_OK, E_DV_UPDATED }; enum SuperType { vtSTRING = 1, vtFLOAT = 2, vtINTEGER = 3, vtVECTOR = 4, vtVECTOR2D = 5, vtCOLOUR = 6, vtMATRIX = 7, vtQUATERNION = 8, vtRECTANGLE = 9, vtBOX = 10, vtBOOL = 11, vtENUMERATION = 12, vtFLAGS = 13, vtFile = 14, vtOBJECT = 16, vtUNKNOWN = 17 }; typedef enum E_DO_FLAGS { E_DO_OK=0x0000, E_DO_NEEDS_SEND=0x0001, }; typedef enum E_DP_FLAGS { E_DP_OK=0x0000, E_DP_NEEDS_SEND=0x0001, }; typedef enum E_DO_UPDATE_FLAGS { E_DO_NONE=0x0000, E_DO_POSITION=0x0001, E_DO_ROTATION=0x0002, }; typedef enum E_DO_INTERFACE_FLAGS { E_DO_CREATED=0x0001, E_DO_PROCESSED=0x0002, E_DO_BINDED=0x0004 }; typedef enum E_XNETWORK_INTERFACE_STATUS { E_NI_CREATED, E_NI_CONNECTING, E_NI_CONNECTED, E_NI_ERROR }; enum E_DO_DELETE_STATE { E_DO_DS_DELETED, E_DO_DS_DELETE_NOTIFIED, }; enum USER_FLAG { USER_NEW, USER_OK, USER_DELETED, USERNAME_CHANGED, USERNAME_OK }; /*enum USERNAME_FLAG { USERNAME_CHANGED, USERNAME_OK };*/ typedef enum E_DO_OWNERSHIP_STATUS { E_DO_OS_OWNER, E_DO_OS_REQUEST, E_DO_OS_OTHER, E_DO_OS_BIND, E_DO_OS_RELEASED }; typedef enum E_DO_OWNERSHIP_REQUEST { E_DO_OSR_PROGRESS, E_DO_OSR_FAILED, E_DO_OSR_ACCEPTED }; typedef enum E_DO_CREATION_FLAGS { E_DO_CREATION_NONE, E_DO_CREATION_INCOMPLETE, E_DO_PENDING_ID_REQUESTED, E_DO_CREATION_CREATED, E_DO_CREATION_COMPLETE, E_DO_CREATION_TIMEOUT, E_DO_CREATION_ERROR }; typedef enum E_PREDICTION_TYPE { E_PTYPE_PREDICTED, E_PTYPE_RELIABLE, E_PTYPE_NON_RELIABLE }; typedef enum E_DC_BASE_TYPE { E_DC_BTYPE_3D_ENTITY, E_DC_BTYPE_2D_ENTITY, E_DC_BTYPE_CLIENT, E_DC_BTYPE_SESSION }; typedef enum E_DC_PROPERTY_TYPE { E_DC_PTYPE_3DVECTOR, E_DC_PTYPE_QUATERNION, E_DC_PTYPE_2DVECTOR, E_DC_PTYPE_FLOAT, E_DC_PTYPE_INT, E_DC_PTYPE_BOOL, E_DC_PTYPE_STRING, E_DC_PTYPE_UNKNOWN, }; /* typedef enum E_DCI_3D_NATIVE_PROPERTIES { E_DCI_3D_NP_LOCAL_POSITION, E_DCI_3D_NP_LOCAL_ROTATION, E_DCI_3D_NP_LOCAL_SCALE, E_DCI_3D_NP_WORLD_POSITION, E_DCI_3D_NP_WORLD_ROTATION, E_DCI_3D_NP_WORLD_SCALE, E_DCI_3D_NP_VISIBILITY, E_DCI_3D_NP_UNKNOWN };*/ typedef enum E_DCF_3D_NATIVE_PROPERTIES { E_DCF_3D_NP_LOCAL_POSITION=0x0001, E_DCF_3D_NP_LOCAL_ROTATION=0x0002, E_DCF_3D_NP_LOCAL_SCALE=0x0004, E_DCF_3D_NP_WORLD_POSITION=0x0008, E_DCF_3D_NP_WORLD_ROTATION=0x0010, E_DCF_3D_NP_WORLD_SCALE=0x0020, E_DCF_3D_NP_VISIBILITY=0x0040, E_DCF_3D_NP_USER_0=0x0080, E_DCF_3D_NP_USER_1=0x0100, E_DCF_3D_NP_USER_2=0x0200, E_DCF_3D_NP_USER_3=0x0400, E_DCF_3D_NP_USER_4=0x0800, }; typedef enum E_DC_3D_NATIVE_PROPERTIES { E_DC_3D_NP_LOCAL_POSITION=1, E_DC_3D_NP_LOCAL_ROTATION=2, E_DC_3D_NP_LOCAL_SCALE=3, E_DC_3D_NP_WORLD_POSITION=4, E_DC_3D_NP_WORLD_ROTATION=5, E_DC_3D_NP_WORLD_SCALE=6, E_DC_3D_NP_VISIBILITY=7, E_DC_3D_NP_USER=8 }; /*typedef enum E_DC_3D_NATIVE_PROPERTIES { E_DC_3D_NP_LOCAL_POSITION=1, E_DC_3D_NP_LOCAL_ROTATION=2, E_DC_3D_NP_LOCAL_SCALE=4, E_DC_3D_NP_WORLD_POSITION=8, E_DC_3D_NP_WORLD_ROTATION=16, E_DC_3D_NP_WORLD_SCALE=32, E_DC_3D_NP_VISIBILITY=64, E_DC_3D_NP_USER=128 };*/ typedef enum E_DO_UPDATE_STATE { E_DO_US_OK, E_DO_US_PENDING, E_DO_US_SEND, }; typedef enum E_C_PACKET { E_C_CLIENT_NONE=0x000, E_C_CLIENT_OBJECT_UPDATE=0x0001 }; #endif <file_sep>#include "precomp.h" #include "vtPrecomp.h" #include "vtNetAll.h" #include "xNetInterface.h" #include "tnlRandom.h" #include "tnlSymmetricCipher.h" #include "tnlAsymmetricKey.h" #include <pch.h> #include <vtNetAll.h> static const char *localBroadcastAddress = "IP:broadcast:28999"; static const char *localHostAddress = "IP:127.0.0.1:28999"; TNL::SafePtr<xNetInterface>m_NetInterfaceServer = NULL; TNL::SafePtr<xNetInterface>m_NetInterfaceClient = NULL; xNetInterface* GetNetInterfaceServer() { return m_NetInterfaceServer ; } void SetNetInterfaceClient(xNetInterface *cInterface) { if (m_NetInterfaceClient!=NULL) { m_NetInterfaceClient->destroy(); delete m_NetInterfaceClient; m_NetInterfaceClient = NULL; } m_NetInterfaceClient = cInterface; } void SetNetInterfaceServer(xNetInterface *cInterface) { if (m_NetInterfaceServer!=NULL) { m_NetInterfaceServer->destroy(); delete m_NetInterfaceServer; m_NetInterfaceServer = NULL; } m_NetInterfaceServer = cInterface; } xNetInterface *GetNetInterfaceClient(){ return m_NetInterfaceClient;} /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int vtNetworkManager::Init() { return 0; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int vtNetworkManager::ConnectToServer(bool deleteExisting,const char *address) { int result = 0 ; if(GetNetInterfaceClient()) { TNL::Address addr = TNL::Address(address); GetNetInterfaceClient()->setConnection(new vtConnection()); GetNetInterfaceClient()->getConnection()->connect(m_NetInterfaceClient,addr,true,false); } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int vtNetworkManager::CreateClient(bool deleteExisting,int port,const char *address) { if (m_NetInterfaceClient && !deleteExisting ) { return 0; } if (deleteExisting) { delete m_NetInterfaceClient; } m_NetInterfaceClient = new xNetInterface(false,TNL::Address(TNL::IPProtocol, TNL::Address::Any, 0),TNL::Address(localBroadcastAddress)); TNL::AsymmetricKey *theKey = new TNL::AsymmetricKey(32); m_NetInterfaceClient->setPrivateKey(theKey); m_NetInterfaceClient->setRequiresKeyExchange(true); m_NetInterfaceClient->initBaseClasses(0); if (m_NetInterfaceClient) { m_NetInterfaceClient->getDistObjectInterface()->setNetInterface(m_NetInterfaceClient); return 1; }else return 0; return 0; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int vtNetworkManager::CreateServer(bool deleteExisting,int port,const char *address) { /*if (m_NetInterfaceServer && !deleteExisting ) { return 0; }*/ if (deleteExisting && m_NetInterfaceServer) { SetServerNetInterface(NULL); } TNL::Address add(address); m_NetInterfaceServer = new xNetInterface(true,add,TNL::Address(localBroadcastAddress)); if (m_NetInterfaceServer) { TNL::Socket *socket = &m_NetInterfaceServer->getSocket(); if (socket) { if (!socket->isValid()) { SetServerNetInterface(NULL); return E_NWE_INVALID_PARAMETER; } } } TNL::AsymmetricKey *theKey = new TNL::AsymmetricKey(32); m_NetInterfaceServer->setPrivateKey(theKey); m_NetInterfaceServer->setRequiresKeyExchange(false); m_NetInterfaceServer->initBaseClasses(0); if (m_NetInterfaceServer) { GetNetInterfaceServer()->setAllowsConnections(true); } return E_NWE_OK; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int vtNetworkManager::CreateLocalConnection() { int result = 0 ; if (localConnection) { delete localConnection; } if (GetNetInterfaceServer()) CreateClient(true,0,localHostAddress); if (GetNetInterfaceClient() && GetNetInterfaceServer()) { GetNetInterfaceClient()->setConnection(new vtConnection()); result = GetNetInterfaceClient()->getConnection()->connectLocal(m_NetInterfaceClient,m_NetInterfaceServer); } return result; } <file_sep>/***************************************************************************** * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR * A PARTICULAR PURPOSE. * * Copyright (C) 1993 - 1996 Microsoft Corporation. All Rights Reserved. * ****************************************************************************** * * SMF.H * * Public include file for Standard MIDI File access routines. * *****************************************************************************/ #ifndef _SMF_ #define _SMF_ //#include "global.h" typedef DWORD SMFRESULT; typedef DWORD TICKS; typedef TICKS *PTICKS; typedef BYTE *HPBYTE; #define MAX_TICKS ((TICKS)0xFFFFFFFFL) #define SMF_SUCCESS (0L) #define SMF_INVALID_FILE (1L) #define SMF_NO_MEMORY (2L) #define SMF_OPEN_FAILED (3L) #define SMF_INVALID_TRACK (4L) #define SMF_META_PENDING (5L) #define SMF_ALREADY_OPEN (6L) #define SMF_END_OF_TRACK (7L) #define SMF_NO_META (8L) #define SMF_INVALID_PARM (9L) #define SMF_INVALID_BUFFER (10L) #define SMF_END_OF_FILE (11L) #define SMF_REACHED_TKMAX (12L) DECLARE_HANDLE(HSMF); typedef struct tag_smfopenstruct { LPSTR pstrName; DWORD dwTimeDivision; HSMF hSmf; } SMFOPENFILESTRUCT, *PSMFOPENFILESTRUCT; extern SMFRESULT smfOpenFile( PSMFOPENFILESTRUCT psofs); extern SMFRESULT smfCloseFile( HSMF hsmf); typedef struct tag_smffileinfo { DWORD dwTracks; DWORD dwFormat; DWORD dwTimeDivision; TICKS tkLength; } SMFFILEINFO, *PSMFFILEINFO; extern SMFRESULT smfGetFileInfo( HSMF hsmf, PSMFFILEINFO psfi); extern DWORD smfTicksToMillisecs( HSMF hsmf, TICKS tkOffset); extern DWORD smfMillisecsToTicks( HSMF hsmf, DWORD msOffset); extern SMFRESULT smfReadEvents( HSMF hsmf, LPMIDIHDR lpmh, TICKS tkMax); extern SMFRESULT smfSeek( HSMF hsmf, TICKS tkPosition, LPMIDIHDR lpmh); extern DWORD smfGetStateMaxSize( void); /* Buffer described by LPMIDIHDR is in polymsg format, except that it ** can contain meta-events (which will be ignored during playback by ** the current system). This means we can use the pack functions, etc. */ #define PMSG_META ((BYTE)0xC0) #endif <file_sep>#ifndef _XNET_ENUMERATIONS_H_ #define _XNET_ENUMERATIONS_H_ #define xBIT(x) (1 << (x)) ///< Returns value with bit x set (2^x) typedef enum E_MESSAGE_FLAGS { E_MF_NEW, E_MF_SENDING, E_MF_SENT, E_MF_TIMEOUT, E_MF_FINISH, E_MF_OUTGOING, E_MF_INCOMING, E_MF_SEND_TO_ALL, E_MF_DELETED, }; typedef enum E_MESSAGE_WRITE_FLAGS { E_MWF_UPDATE_SERVER, E_MWF_SEND_SRC_USER_ID, E_MWF_SEND_TARGET_USER_ID, E_MWF_UPDATE_GHOST, E_MWF_SERVER_UPDATE, }; typedef enum E_MESSAGE_READ_FLAGS { E_MRF_UPDATE_BY_GHOST, E_MRF_READ_SRC_USER_ID, E_MRF_READ_TARGET_USER_ID, E_MRF_UPDATE_GHOST, E_MRF_SERVER_UPDATE, }; typedef enum E_OBJECT_TYPE { E_OT_DIST_OBJECT, E_OT_DIST_PROPERTY, E_OT_CLASS, E_OT_MESSAGE, }; typedef enum E_LOG_ITEMS { E_LI_CLIENT, E_LI_SESSION, E_LI_3DOBJECT, E_LI_2DOBJECT, E_LI_DISTRIBUTED_BASE_OBJECT, E_LI_DISTRIBUTED_CLASS_DESCRIPTORS, E_LI_MESSAGES, E_LI_ARRAY_MESSAGES, E_LI_CONNECTION, E_LI_NET_INTERFACE, E_LI_GHOSTING, E_LI_STATISTICS, E_LI_BUILDINGBLOCKS, E_LI_VSL, E_LI_CPP, E_LI_ASSERTS, E_LI_PREDICTION, E_LI_SERVER_MESSAGES }; typedef enum E_LOG_FLAGS { E_LF_CPP_FUNCS, E_LF_CPP_FUNC_SIGNATURE, E_LF_BB_NAME, E_LF_BB_OWNER, E_LF_TIMESTAMPS, }; typedef enum E_DV_STATE { E_DV_OK, E_DV_UPDATED }; enum SuperType { vtSTRING = 1, vtFLOAT = 2, vtINTEGER = 3, vtVECTOR = 4, vtVECTOR2D = 5, vtCOLOUR = 6, vtMATRIX = 7, vtQUATERNION = 8, vtRECTANGLE = 9, vtBOX = 10, vtBOOL = 11, vtENUMERATION = 12, vtFLAGS = 13, vtFile = 14, vtOBJECT = 16, vtUNKNOWN = 17 }; typedef enum E_DO_FLAGS { E_DO_OK=0x0000, E_DO_NEEDS_SEND=0x0001, }; typedef enum E_DP_FLAGS { E_DP_OK=0x0000, E_DP_NEEDS_SEND=0x0001, }; typedef enum E_DO_UPDATE_FLAGS { E_DO_NONE=0x0000, E_DO_POSITION=0x0001, E_DO_ROTATION=0x0002, }; typedef enum E_DO_INTERFACE_FLAGS { E_DO_CREATED=0x0001, E_DO_PROCESSED=0x0002, E_DO_BINDED=0x0004 }; typedef enum E_XNETWORK_INTERFACE_STATUS { E_NI_CREATED, E_NI_CONNECTING, E_NI_CONNECTED, E_NI_DESTROYED_BY_SERVER, E_NI_ERROR }; enum E_DO_DELETE_STATE { E_DO_DS_DELETED, E_DO_DS_DELETE_NOTIFIED, }; enum USER_FLAG { USER_NEW, USER_OK, USER_DELETED, USERNAME_CHANGED, USERNAME_OK }; typedef enum E_DO_OWNERSHIP_STATUS { E_DO_OS_OWNER, E_DO_OS_OWNERCHANGED, E_DO_OS_REQUEST, E_DO_OS_OTHER, E_DO_OS_NONE, E_DO_OS_BIND, E_DO_OS_RELEASED }; typedef enum E_DO_OWNERSHIP_REQUEST { E_DO_OSR_PROGRESS, E_DO_OSR_FAILED, E_DO_OSR_ACCEPTED }; typedef enum E_DO_STATE_FLAGS { E_DOSF_UNPACKED, E_DOSF_SHOWN, E_DOSF_SESSION_LEFT, E_DOSF_DELETED, E_DOSF_INITIAL_STATE_SEND }; typedef enum E_DO_CREATION_FLAGS { E_DO_CREATION_NONE, E_DO_CREATION_INCOMPLETE, E_DO_PENDING_ID_REQUESTED, E_DO_CREATION_CREATED, E_DO_CREATION_COMPLETE, E_DO_CREATION_TIMEOUT, E_DO_CREATION_ERROR }; typedef enum E_PREDICTION_TYPE { E_PTYPE_PREDICTED, E_PTYPE_RELIABLE, E_PTYPE_NON_RELIABLE }; typedef enum E_DC_BASE_TYPE { E_DC_BTYPE_3D_ENTITY, E_DC_BTYPE_2D_ENTITY, E_DC_BTYPE_CLIENT, E_DC_BTYPE_SESSION }; typedef enum E_DC_PROPERTY_TYPE { E_DC_PTYPE_3DVECTOR, E_DC_PTYPE_QUATERNION, E_DC_PTYPE_2DVECTOR, E_DC_PTYPE_FLOAT, E_DC_PTYPE_INT, E_DC_PTYPE_BOOL, E_DC_PTYPE_STRING, E_DC_PTYPE_UNKNOWN, }; typedef enum E_DCF_3D_NATIVE_PROPERTIES { E_DCF_3D_NP_LOCAL_POSITION=0x0001, E_DCF_3D_NP_LOCAL_ROTATION=0x0002, E_DCF_3D_NP_LOCAL_SCALE=0x0004, E_DCF_3D_NP_WORLD_POSITION=0x0008, E_DCF_3D_NP_WORLD_ROTATION=0x0010, E_DCF_3D_NP_WORLD_SCALE=0x0020, E_DCF_3D_NP_VISIBILITY=0x0040, E_DCF_3D_NP_USER_0=0x0080, E_DCF_3D_NP_USER_1=0x0100, E_DCF_3D_NP_USER_2=0x0200, E_DCF_3D_NP_USER_3=0x0400, E_DCF_3D_NP_USER_4=0x0800, }; typedef enum E_DC_3D_NATIVE_PROPERTIES { E_DC_3D_NP_LOCAL_POSITION=1, E_DC_3D_NP_LOCAL_ROTATION=2, E_DC_3D_NP_LOCAL_SCALE=3, E_DC_3D_NP_WORLD_POSITION=4, E_DC_3D_NP_WORLD_ROTATION=5, E_DC_3D_NP_WORLD_SCALE=6, E_DC_3D_NP_VISIBILITY=7, E_DC_3D_NP_USER=8 }; typedef enum E_DC_SESSION_NATIVE_PROPERTIES { E_DC_S_NP_MAX_USERS=1, E_DC_S_NP_PASSWORD=2, E_DC_S_NP_TYPE=3, E_DC_S_NP_LOCKED=4, E_DC_S_NP_NUM_USERS=5, E_DC_S_NP_USER=6, }; typedef enum E_DO_UPDATE_STATE { E_DO_US_OK, E_DO_US_PENDING, E_DO_US_SEND, }; typedef enum E_C_PACKET { E_C_CLIENT_NONE=0x000, E_C_CLIENT_OBJECT_UPDATE=0x0001 }; typedef enum E_CLIENT_FLAGS { E_CF_CONNECTED, E_CF_CONNECTION_LOST, E_CF_SESSION_JOINED, E_CF_SESSION_DESTROYED, E_CF_REMOVED, E_CF_ADDING, E_CF_ADDED, E_CF_DELETING, E_CF_DELETED, E_CF_NM_FREE, E_CF_NM_SENDING, E_CF_NM_SENT, }; typedef enum E_SESSION_FLAGS { E_SF_INCOMPLETE, E_SF_PARAMETER_ATTACHED, E_SF_POPULATE_PARAMETERS, E_SF_COMPLETE, E_SF_LOCKED }; typedef enum E_NETWORK_ERROR { E_NWE_OK, E_NWE_INTERN, E_NWE_NO_CONNECTION, E_NWE_NO_SESSION, E_NWE_SESSION_WRONG_PASSWORD, E_NWE_SESSION_LOCKED, E_NWE_SESSION_EXISTS, E_NWE_SESSION_FULL, E_NWE_NOT_SESSION_MASTER, E_NWE_INVALID_PARAMETER, E_NWE_NO_SUCH_USER, E_NWE_DIST_CLASS_EXISTS, E_NWE_NO_SERVER, E_NWE_SESSION_ALREADY_JOINED, E_NWE_NO_SUCH_SESSION }; typedef enum E_OBJECT_PRINT_FLAGS { E_OPF_NAME, E_OPF_GHOST_ID, E_OPF_USER_ID, E_OPF_SESSION_ID, E_OPF_CLASS, E_OPF_NUM_PROPS, E_OPF_PROPS, E_OPF_NATIVE_PROPERTIES, E_OPF_USER_PROPERTIES, E_OPF_SESSION_LOCKED, E_OPF_SESSION_USERS, E_OPF_SESSION_NAME, E_OPF_SESSION_PRIVATE, E_OPF_SESSION_MAXUSERS, E_OPF_SESSION_MASTER, E_OPF_CLIENT_USERNAME, E_OPF_CLIENT_LOCAL_ADDRESS, E_OPF_CLIENT_LOCAL_GHOST_IDS, E_OPF_CLIENT_CONNECTION_SETUP, }; typedef enum E_PROPERTY_PRINT_FLAGS { E_PPF_NAME, E_PPF_VALUE_TYPE, E_PPF_NATIVE_TYPE, E_PPF_PREDICTION_TYPE, E_PPF_SERVER_VALUE, E_PPF_LAST_VALUE, E_PPF_CURRENT_VALUE, E_PPF_DIFFERENCE, E_PPF_MIN_TIME, E_PPF_MIN_THRESHOLD }; #endif <file_sep>#ifndef __DLL_TOOLS_H__ #define __DLL_TOOLS_H__ #include <wtypes.h> */ namespace DllTools { /*************************************************************************/ /* class : DllFunc */ /* this is a small helper to bind an exported dll-func to a prototyyp example, you want to replace a load/save function for custom parameter at run-time: typedef void (*_CGBLCISAVELOADFUNC_proto)(CKParameter *,CKStateChunk **,CKBOOL); DllFunc<_CGBLCISAVELOADFUNC_proto>CGBLCISAVELOADFUNC_proto(_T("proto.dll"),"CGBLCISAVELOADFUNC"); CGBLCISAVELOADFUNC_proto.Load(); // binds the func to the functor CGBLCISAVELOADFUNC_proto.Release(); // unbind, but keeps infos about dll-name/func. (*CGBLCISAVELOADFUNC_proto)(par,chunk,true); for executing . You can use this for dynamic dll to vsl mapping ! : see last comment. */ template<class T> class DllFunc { public: DllFunc( const char* _dllName, const char* _fnName ,const bool logging = TRUE ) : dllName(_dllName) , fn(0) , fnName(_fnName) { if (logging && !dllHandle) { printf("couldn't found DLL\n"); return; } } operator T() { printf("executing func : %s ",fnName); return fn; } void Release() { FreeLibrary(dllHandle); fn = 0; } void Load() { FreeLibrary(dllHandle); printf("loading lib : %s for function",dllName,fnName); dllHandle = ( LoadLibrary (dllName) ); fn = ( T )GetProcAddress(dllHandle, fnName); if (!fn) { printf("couldn't attach fnc \n"); } } public: T fn; HMODULE dllHandle; const char* dllName; const char* fnName; }; }/*end namespace */ #endif<file_sep>/******************************************************************** created: 2008/01/14 created: 14:1:2008 12:14 filename: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer\CustomPlayerDialogErrorPage.cpp file path: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer file base: CustomPlayerDialogErrorPage file ext: cpp author: mc007 purpose: Displays an Error Tab, the text is set by CustomPlayerDialog.InitDialog ! *********************************************************************/ // CErrorPage dialog #pragma once #include "resourceplayer.h" #include "afxwin.h" #include "afxcmn.h" class CustomPlayerDialogErrorPage : public CPropertyPage { // Construction public: CustomPlayerDialogErrorPage(); // Dialog Data //{{AFX_DATA(CErrorPage) enum { IDD = IDD_ERROR }; //}}AFX_DATA // Overrides // ClassWizard generate virtual function overrides //{{AFX_VIRTUAL(CErrorPage) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CErrorPage) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() public: CRichEditCtrl m_ErrorRichText; afx_msg void OnEnSetfocusErrorRichtText(); CString errorText; afx_msg void OnEnLinkErrorRichtText(NMHDR *pNMHDR, LRESULT *pResult); }; <file_sep>#ifndef InitMAN_H #define InitMAN_H #include "CKBaseManager.h" #include <stdlib.h> #include <map> #define S_PARAMETER_GUID CKGUID(0x7a7104e2,0x72c56435) #define SFLOAT_PARAMETER_GUID CKGUID(0x6a5b2ec3,0x63f84a40) #define SCOLOR_PARAMETER_GUID CKGUID(0x47cc15d2,0xf366299) #define SINT_PARAMETER_GUID CKGUID(0x31d3196f,0x787306e1) #define CKPGUID_LOOPMODE CKDEFINEGUID(0x63942d15,0x5ac51a7) typedef enum QAD_OBJECT_TYPE { CHARACTER = 1, PUSHBOX = 2, BALL = 3, STONE = 4, COIN = 5, FUEL = 6, ROCKET = 7, MOVINGBOARD = 8, SPRINGPAIR =9, } QAD_OBJECT_TYPE; ////////////////////////////////////////////////////////////////////////// #define VLEFT VxVector(-1.0f,0.0f,0.0f) #define VRIGHT VxVector(1.0f,0.0f,0.0f) #define VUP VxVector(1.0f,1.0f,0.0f) #define VDOWN VxVector(0.0f,-1.0f,0.0f) #define VZERO VxVector(0.0f,0.0f,0.0f) #define PHYSIC_OBJECT_2D_PARAMETER CKDEFINEGUID(0x57ba4ee6,0x4d8740a9) #define PHYSIC_OBJECT_SIMULATION_FILTER CKDEFINEGUID(0x248f1f51,0x72070f85) #define PHYSIC_OBJECT_2D_WORLDSPRING_PARAMETER CKDEFINEGUID(0x1b8e268b,0x11041fa0) ////////////////////////////////////////////////////////////////////////// #include "typedefs.h" #include "ZipDll.h" #include "UnzipDll.h" #include "ZCallBck.h" BOOL __stdcall DefaultZipCallback(CZipCallbackData *pData);//thanks #include "sharedStructs.h" #define INIT_MAN_GUID CKGUID(0x35824c8a,0x4e320ac4) class InitMan : public CKBaseManager { public: //Ctor InitMan(CKContext* ctx); //Dtor ~InitMan(); static InitMan* GetInstance(); ////////////////////////////////////////////////////////////////////////// //virtual file mapping , used for command pipe: HANDLE m_hMMFile; vtExternalEvent *m_pData; typedef XHashTable<vtExternalEvent*,unsigned long>vtExternalEventQueueType; vtExternalEventQueueType incomingEvents; void PerformMessages(); void InitMessages(int flags,XString name); // Initialization virtual CKERROR OnCKInit(); virtual CKERROR OnCKEnd(); virtual CKERROR OnCKReset(); CKERROR PreProcess(); CKERROR PostProcess(); virtual CKERROR PostClearAll(); virtual CKERROR OnCKPlay(); CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_OnCKInit| CKMANAGER_FUNC_OnCKEnd| CKMANAGER_FUNC_OnCKReset| CKMANAGER_FUNC_PreProcess| CKMANAGER_FUNC_PostProcess| CKMANAGER_FUNC_PostClearAll| CKMANAGER_FUNC_OnCKPlay; } /************************************************************************/ /* Parameter Functions */ /************************************************************************/ int move_object_att; int moving_board_att; int rocket_att; int keyboard_config_att; int att_character_keyboard_config; int att_character_anim_messages; int att_character_anims; int att_character_ckof; int att_character_object_set; int att_spring_pair; VxVector Position(CK3dEntity *ent); int att_rigid_body_2D; int att_rigid_body_2D_worldspring; int att_need_update; int att_do_physics; int att_sim_filter; void RegisterVSL(); void RegisterRacknetVSL(); void RegisterCEGUI_VSL(CKContext *ctx); void RegisterParameters(); void RegisterParameters2(); //void RegisterHUD(); /************************************************************************/ /* zip lib */ /************************************************************************/ ZipJobList zili; bool AddFileEntry(XString ArchiveName,XString FileEntry); BOOL LoadZipDll();//from the projects resource BOOL UnLoadZipDll(); void SetDefaultZipValues(CZipParams *pParams); int GetZipDllVersion(); /************************************************************************/ /* decompressing funcs */ /************************************************************************/ BOOL LoadUnzipDll(); BOOL UnLoadUnZipDll(); void SetDefaultUnZipValues(CUnzipParams * pParams); int GetUnzipDllVersion(); UINT m_uiLastError;//unused /************************************************************************/ /* compress */ /************************************************************************/ HINSTANCE m_ZipDllHandle; char ZipDllTempFile[MAX_PATH]; CZipDllExec m_ZipDllExec; CGetZipDllVersion m_GetZipDllVersion; /************************************************************************/ /* decompress */ /************************************************************************/ HINSTANCE m_UnzipDllHandle; char UnZipDllTempFile[MAX_PATH]; CGetUnzipDllVersion m_GetUnzipDllVersion; CUnzipDllExec m_UnzipDllExec; private: }; #define GetIManager() InitMan::GetInstance() #endif <file_sep>#include "StdAfx.h" #include "InitMan.h" #include "vt_python_funcs.h" #include <iostream> using std::cout; #include <sstream> #include "pyembed.h" //#include "VSLManagerSDK.h" /*#include <iostream> #include "pyembed.h" */ //************************************ // Method: ClearModules // FullName: vt_python_man::ClearModules // Access: public // Returns: void // Qualifier: //************************************ void vt_python_man::ClearModules() { PModulesIt begin = GetPModules().begin(); PModulesIt end = GetPModules().end(); while(begin!=end) { if (begin->second) { Py_XDECREF(begin->second); begin->second = NULL; } begin++; } GetPModules().clear(); } void vt_python_man::CallPyModule(CK_ID id,XString func,const Arg_mmap& args,long& ret) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr(),args,ret); } } } void vt_python_man::CallPyModule(CK_ID id,XString func,const Arg_mmap& args,double& ret) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr(),args,ret); } } } void vt_python_man::CallPyModule(CK_ID id,XString func,const Arg_mmap& args,std::string& ret) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr(),args,ret); } } } void vt_python_man::CallPyModule(CK_ID id,Arg_mmap *args,XString func) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr()); } } } void vt_python_man::CallPyModule(CK_ID id,XString func) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr()); } } } //************************************ // Method: RemovePModule // FullName: vt_python_man::RemovePModule // Access: public // Returns: void // Qualifier: // Parameter: CK_ID id //************************************ void vt_python_man::RemovePModule(CK_ID id) { CKObject* obj = m_Context->GetObject(id); if(obj) { PModulesIt it = GetPModules().find(id); if(it != GetPModules().end() ) { if (it->second) { Py_DECREF(it->second); it->second = NULL; GetPModules().erase(it); } } } } //************************************ // Method: GetPModule // FullName: vt_python_man::GetPModule // Access: public // Returns: PyObject* // Qualifier: // Parameter: CK_ID id //************************************ PyObject* vt_python_man::GetPModule(CK_ID id) { CKObject* obj = m_Context->GetObject(id); if(obj) { PModulesIt it = GetPModules().find(id); if(it != GetPModules().end() ) { return it->second; }else { return NULL; } } } //************************************ // Method: InsertPModule // FullName: vt_python_man::InsertPModule // Access: public // Returns: void // Qualifier: // Parameter: CK_ID id // Parameter: XString name // Parameter: bool reload //************************************ PyObject* vt_python_man::InsertPModule(CK_ID id,XString name,bool reload) { CKObject* obj = m_Context->GetObject(id); if(obj) { if (GetPModule(id)) { RemovePModule(id); } //bit = BArray.insert(BArray.end(),std::make_pair(target,bodyI)); PModulesIt it = GetPModules().find(id); if(it == GetPModules().end() ) { try { PyObject* namep = PyString_FromString( name.CStr() ); PyObject* module = PyImport_Import(namep); if (reload) PyImport_ReloadModule(module); Py_DECREF(namep); GetPModules().insert( GetPModules().end(),std::make_pair(id,module ) ); if (!module) { std::ostringstream oss; m_Context->OutputToConsoleEx("PyErr : \t Failed to load module" ); return NULL; } return module; } catch (Python_exception ex) { m_Context->OutputToConsoleEx("PyErr : \t %s",(CKSTRING)ex.what()); std::cout << ex.what() << "pyexeption in beh : "; PyErr_Clear(); //beh->ActivateOutput(1,TRUE); } /*if (!module) { std::ostringstream oss; oss << "Failed to load module <" << name.CStr() << ">"; throw Python_exception(oss.str()); return NULL; }*/ //GetPModules().insert( GetPModules().end(),std::make_pair(id,module ) ); //return module; } } return NULL; } void vt_python_man::InsertPVSLModule(PythonModule *pMod) { if (pMod) { } } <file_sep>#ifndef __G_CONFIG_H__ #define __G_CONFIG_H__ #ifdef _DEBUG static bool GC_SHOWPARAMETER = true; #else static BOOL GC_SHOWPARAMETER = false; #endif //#define BBC_JOYSTICK #define BBC_TOOLS #define BB_TOOLS #define HAS_CONFIG #define BBC_VEHICLES #define BBC_CLOTHES #define BBC_JOINTS #define CORE_CLOTH #define CORE_PARTICLE #endif<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" CKObjectDeclaration *FillBehaviorDODestroyedDecl(); CKERROR CreateDODestroyedProto(CKBehaviorPrototype **); int DODestroyed(const CKBehaviorContext& behcontext); CKERROR DODestroyedCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorDODestroyedDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DODestroyed"); od->SetDescription("Notifies about a deleted Object"); od->SetCategory("TNL/Distributed Objects"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x440a6b7a,0x2efb0cee)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDODestroyedProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateDODestroyedProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("DODestroyed"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Stop"); proto->DeclareInput("Next"); proto->DeclareOutput("Exit On"); proto->DeclareOutput("Exit Off"); proto->DeclareOutput("Object"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Object", CKPGUID_BEOBJECT, "-1"); proto->DeclareOutParameter("Object ID", CKPGUID_INT, "-1"); proto->DeclareOutParameter("Error", CKPGUID_INT, "-1"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(DODestroyed); proto->SetBehaviorCallbackFct(DODestroyedCB); *pproto = proto; return CK_OK; } int DODestroyed(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); int connectionID=-1; beh->GetInputParameterValue(0,&connectionID); /************************************************************************/ /* */ /************************************************************************/ if (beh->IsInputActive(1)) { beh->ActivateInput(1,FALSE); beh->ActivateOutput(1); return 0; } xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin || !cin->isValid() ) { return CKBR_ACTIVATENEXTFRAME; } TNL::Vector<xDistDeleteInfo*>&clientTable = cin->getDistDeleteTable(); for (int i = 0 ; i < clientTable.size() ; i++ ) { xDistDeleteInfo*cInfo = clientTable[i]; if (cInfo->deleteState == E_DO_DS_DELETED ) { int sID = cInfo->serverID; beh->SetOutputParameterValue(1,&sID); CKBeObject * obj = (CKBeObject*)ctx->GetObject(cInfo->entityID); if (obj) { beh->SetOutputParameterObject(0,obj); } beh->ActivateOutput(2); clientTable.erase(i); return CKBR_ACTIVATENEXTFRAME; } } /************************************************************************/ /* */ /************************************************************************/ return CKBR_ACTIVATENEXTFRAME; } CKERROR DODestroyedCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#ifndef __PREREQUISITES_MODULE_H__ #define __PREREQUISITES_MODULE_H__ class PhysicManager; //################################################################ // // Physic Types // class pContactReport; class pTriggerReport; class pRayCastReport; class pContactModify; class pRigidBody; class pObjectDescr; class pJointSettings; class pJoint; class pJointBall; class pJointFixed; class pJointPulley; class pJointPointOnLine; class pJointPointInPlane; class pJointRevolute; class pJointDistance; class pJointD6; class pJointPrismatic; class pJointCylindrical; class pClothDesc; class pCloth; class pFluid; class pFluidDesc; class pFluidEmitterDesc; class pFluidEmitter; class pFluidRenderSettings; class pWheelContactData; class pSerializer; class pWorld; class pFactory; class pSoftBody; class pWheelDescr; class pWheel; class pWheel1; class pWheel2; class pVecicleDescr; class pVehicle; class pVehicleMotor; class pVehicleGears; class pVehicleMotorDesc; class pVehicleGearDesc; class pBoxController; class pObjectDescr; class IParameter; struct pRigidBodyRestoreInfo; namespace vtAgeia { class pWorldSettings; class pSleepingSettings; class pShape; class pErrorStream; class pCollisionsListener; } class pLogger; class ContactInfo; namespace vtTools { namespace ParameterTools { class CustomStructure; } } using namespace vtAgeia; #endif <file_sep>/* * Tcp4u v 3.31 Last Revision 27/06/1997 3.10 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: http4u.c * Purpose: manage http 1.0 protocol * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> and <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ static char szWhat[]="@(#)http4u by <NAME> and <NAME> version 3.11"; #include "build.h" /****************************** * Http4u internal structures ******************************/ /* status-line for http 1.0 answers */ struct S_HttpStatus { int nVersion; /* version should be 1 */ int nMinor; /* revision (0 or 1) */ int code; /* status-code (ex: 200 ) */ char reason[64]; /* reason (ex: "OK") */ }; /******************************* * A few globals variables *******************************/ static unsigned int s_uHttp4uTimeout = DFLT_TIMEOUT; static unsigned int s_uHttp4uBufferSize = DFLT_BUFFERSIZE; static DO_NOT_LOG = HFILE_ERROR; /*===================================================================== * PRIVATE FUNCTION SOURCES *===================================================================*/ /*###################################################################### *## *## NAME: HttpProcessAnswer *## *## PURPOSE: get HTTP version + HTTP return code + data string *## fully reeentrant *## *####################################################################*/ static int HttpProcessAnswer (LPCSTR szAns, int far *pnVer, int far *pnMinor, int far *pnAnswer, LPSTR szData, int nDataSize) { LPCSTR p; Tcp4uLog (LOG4U_INTERN, "HttpProcessAnswer"); if (memcmp (szAns, "HTTP/", sizeof ("HTTP/") - 1)!=0) { Tcp4uLog (LOG4U_ERROR, "HttpProcessAnswer: bad protocol returned (%s)", szAns); return HTTP4U_PROTOCOL_ERROR; } /* 27/06/97: ignore version numbers (RFC2145) */ *pnAnswer=1; *pnMinor=0; /* search for a space character, then skip it */ p = szAns + sizeof "HTTP/"; while (*p!=0 && !isspace(*p)) p++; while (*p!=0 && isspace(*p)) p++; if (*p==0) { Tcp4uLog (LOG4U_ERROR, "HttpProcessAnswer: bad protocol returned (%s)", szAns); return HTTP4U_PROTOCOL_ERROR; } *pnAnswer = Tcp4uAtoi (p); /* continue only if szData is to be filled */ if (szData!=NULL && nDataSize>0) { /* search for a non-digit then skips spaces */ while (*p!=0 && isdigit(*p)) p++; while (*p!=0 && isspace(*p)) p++; Strcpyn (szData, p, nDataSize); } return HTTP4U_SUCCESS; } /* HttpProcessAnswer */ /*###################################################################### *## *## NAME: HttpSendAdditionnalHeader *## *## PURPOSE: Send a http 1.0 general-header *## *####################################################################*/ static int HttpSendAdditionnalHeader(SOCKET CSock) { int Ark; int Rc; static LPCSTR szAdditionnalStrings[] = { "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*", "User-Agent: Http4u by <NAME> and <NAME>", "", }; Tcp4uLog (LOG4U_INTERN, "HttpSendAdditionnalHeader"); /* sending request, if successful send Request Header */ for (Rc=TCP4U_SUCCESS,Ark=0 ; Rc==TCP4U_SUCCESS && Ark<SizeOfTab(szAdditionnalStrings); Ark++) Rc = TnSend (CSock, szAdditionnalStrings[Ark], FALSE, DO_NOT_LOG); return Rc==TCP4U_SUCCESS ? HTTP4U_SUCCESS : HTTP4U_TCP_FAILED; } /* END HttpSendAdditionnalHeader */ /*###################################################################### *## *## NAME: HttpSendRequest10 *## *## PURPOSE: Send an http 1.0 method request-line *## Note: szReq can be "HEAD ", "POST ", "GET ", .. *## *####################################################################*/ static int HttpSendRequest10(SOCKET CSock, /* socket decriptor */ LPCSTR szReq, /* request to be sent */ LPCSTR szURL /* URL or URI */) { LPSTR sRequest = NULL; int Rc; Tcp4uLog (LOG4U_INTERN, "HttpSendRequest10"); /* allocate buffer wide eough to contain all data */ sRequest = Calloc (sizeof(" HTTP/1.0 ") + Strlen (szURL) + Strlen(szReq), sizeof(char)); if (sRequest == NULL) return HTTP4U_INSMEMORY; /* compose request with reentrant functions */ Strcpy(sRequest, szReq); Strcat(sRequest, szURL); Strcat(sRequest, " HTTP/1.0"); /* send the request then forget it */ Rc = TnSend (CSock, sRequest, FALSE, DO_NOT_LOG); Free (sRequest); if (Rc!=TCP4U_SUCCESS) return HTTP4U_TCP_FAILED ; /* Send general-header */ return HttpSendAdditionnalHeader(CSock); } /* END HttpSendRequestHEAD10 */ /*###################################################################### *## *## NAME: HttpRecvRespStatus *## *## PURPOSE: Get the status-line of the http answer *## The data are copied into saRespStatus and szAnswer *## *####################################################################*/ static int HttpRecvRespStatus(SOCKET CSock, struct S_HttpStatus far *saRespStatus, LPSTR szAnswer, int nAnswerSize) { #define RECV_BUF_SIZE 1024 LPSTR sBufStatus; int nBufStatusLen = RECV_BUF_SIZE ; int Rc; Tcp4uLog (LOG4U_INTERN, "HttpRecvRespStatus"); if (szAnswer !=NULL && nAnswerSize > 0) szAnswer[0]=0; /* If ye can keep user's buffer */ if (szAnswer!=NULL && nAnswerSize >= RECV_BUF_SIZE) { sBufStatus = szAnswer; nBufStatusLen = nAnswerSize; } else { sBufStatus = Calloc (RECV_BUF_SIZE, sizeof (char)); if (sBufStatus == NULL) return HTTP4U_INSMEMORY; } /* receive data */ Rc = TnReadLine (CSock,sBufStatus,nBufStatusLen,s_uHttp4uTimeout, DO_NOT_LOG); switch(Rc) { case TCP4U_SUCCESS: break; case TCP4U_OVERFLOW: return HTTP4U_OVERFLOW; case TCP4U_TIMEOUT: return HTTP4U_TIMEOUT; case TCP4U_CANCELLED: return HTTP4U_CANCELLED; case TCP4U_ERROR: return HTTP4U_TCP_FAILED; case TCP4U_SOCKETCLOSED: return HTTP4U_PROTOCOL_ERROR; default: return HTTP4U_TCP_FAILED; } /* control format */ Rc = HttpProcessAnswer ( sBufStatus, & saRespStatus->nVersion, & saRespStatus->nMinor, & saRespStatus->code, saRespStatus->reason, sizeof saRespStatus->reason); /* Copy data, free buffer */ if (sBufStatus != szAnswer) { if (szAnswer != NULL) Strcpyn (szAnswer, sBufStatus, nAnswerSize); Free (sBufStatus); } return Rc; #undef RECV_BUF_SIZE } /* END HttpRecvRespStatus */ /*###################################################################### *## *## NAME: HttpRecvHeaders10 *## *## PURPOSE: Return the headers section of the http respons *## sBufHeaders Can not be NULL, but sBufHeadersLen can !! *## *####################################################################*/ static int HttpRecvHeaders10 (SOCKET CSock, LPSTR sBufHeaders, int nBufHeadersLen) { int Rc; int nRcvd, nLineLength; LPSTR p; #define EMPTY(s) ((s)[0]=='\r' || (s)[0]=='\n') Tcp4uLog (LOG4U_INTERN, "Http4RecvHeaders10"); if (sBufHeaders==NULL) return HTTP4U_BAD_PARAM; memset(sBufHeaders, 0, nBufHeadersLen); /* Keep space for last ending line and nul character */ nBufHeadersLen -= sizeof SYSTEM_EOL; /* receive data from distant http server. Must use loop on TcpRecvUntilStr */ /* since some unix servers send \n\n instead of regular \n\r\n.... */ nRcvd = 0 ; do { p = & sBufHeaders[nRcvd]; Rc = InternalTnReadLine (CSock, p, nBufHeadersLen-nRcvd, s_uHttp4uTimeout, DO_NOT_LOG); Strcat (p, SYSTEM_EOL); nLineLength = Strlen (p); /* 0 on error */ nRcvd += nLineLength; } /* loop until error or empty line */ while (Rc==TCP4U_SUCCESS && !EMPTY(p) && nRcvd < nBufHeadersLen); /* translate return code */ switch(Rc) { /* remember to put the last \n into destination string */ case TCP4U_SUCCESS: Tcp4uDump (sBufHeaders, nRcvd, DUMP4U_RCVD); return nRcvd >= nBufHeadersLen ? HTTP4U_OVERFLOW : HTTP4U_SUCCESS; case TCP4U_OVERFLOW: return HTTP4U_OVERFLOW; case TCP4U_TIMEOUT: return HTTP4U_TIMEOUT; case TCP4U_CANCELLED: return HTTP4U_CANCELLED; case TCP4U_ERROR: return HTTP4U_TCP_FAILED; case TCP4U_INSMEMORY: return HTTP4U_INSMEMORY; case TCP4U_SOCKETCLOSED: return HTTP4U_PROTOCOL_ERROR; default: return HTTP4U_TCP_FAILED; } /* END switch(Rc) */ #undef EMPTY } /* END HttpRecvHeaders10 */ /*===================================================================== * PUBLIC FUNCTION SOURCES *===================================================================*/ /*###################################################################### *## *## NAME: HttpGetHeaders10 *## *## PURPOSE: Return the header section of the http request *## *####################################################################*/ int HttpGetHeaders10( LPCSTR szURL, /* URL target */ LPSTR szResponse, /* user's buffer for HTTP response */ int nResponseSize, /* */ LPSTR szData, /* user's buffer for HTTP headers */ int nDataSize /* */) { int Rc; SOCKET CSock = INVALID_SOCKET; char szService[SERVICE_LENGTH]; char szHost[HOST_LENGTH]; char szFichier[FILE_LENGTH]; unsigned short usPort; struct S_HttpStatus saRespStatus; Tcp4uLog (LOG4U_INTERN, "HttpGetHeaders10"); /* control the URL's validity and receive the URL distinct components */ if (!HttpIsValidURL(szURL, &usPort, szService, sizeof szService , szHost, sizeof szHost , szFichier, sizeof szFichier )) return HTTP4U_BAD_URL; /* connect to the http server */ Rc = TcpConnect(&CSock, szHost, szService, &usPort); switch (Rc) { case TCP4U_SUCCESS : break; /* continue */ case TCP4U_HOSTUNKNOWN : return HTTP4U_HOST_UNKNOWN; default : return HTTP4U_TCP_CONNECT; } /* Send request-line method "HEAD" then receive the status-line answer */ /* then receive headers */ (Rc = HttpSendRequest10 (CSock,"HEAD ", szURL)) == HTTP4U_SUCCESS && (Rc = HttpRecvRespStatus (CSock, & saRespStatus, szResponse, nResponseSize)) == HTTP4U_SUCCESS && (Rc = HttpRecvHeaders10 (CSock, szData, nDataSize)) == HTTP4U_SUCCESS ; TcpClose (&CSock); return Rc; } /* END HttpGetHeaders10 */ /*###################################################################### *## *## NAME: Http4uSetTimeout *## *## PURPOSE: Sets user preference of the timeout value *## *####################################################################*/ void API4U Http4uSetTimeout( unsigned int uTimeout /* timeout value in sec */) { Tcp4uLog (LOG4U_HIPROC, "Http4uSetTimeout"); s_uHttp4uTimeout = uTimeout; } /* END Http4uSetTimeout */ /*###################################################################### *## *## NAME: Http4uSetBufferSize *## *## PURPOSE: Sets user preference of the buffer size *## *####################################################################*/ void API4U Http4uSetBufferSize( unsigned int uBufferSize /* buffer size in bytes */) { Tcp4uLog (LOG4U_HIPROC, "Http4uSetbufferSize"); s_uHttp4uBufferSize = uBufferSize; } /* END Http4uSetBufferSize */ /*###################################################################### *## *## NAME: HttpGetFileEx *## *## PURPOSE: Return headers and body of a http request *## *####################################################################*/ int API4U HttpGetFileEx( LPCSTR szURL, LPCSTR szProxyURL, LPCSTR szLocalFile, LPCSTR szHeaderFile, HTTP4U_CALLBACK CbkTransmit, long lUserValue, LPSTR szResponse, int nResponseSize, LPSTR szHeaders, int nHeadersSize ) { SOCKET CSock = INVALID_SOCKET; int Rc; int hHeaderFile = HFILE_ERROR; char szService[SERVICE_LENGTH]; char szHost[HOST_LENGTH]; char szFichier[FILE_LENGTH]; LPSTR szData = NULL; LPSTR p; LPCSTR szRequest; long RealBodySize = -1; struct S_HttpStatus saRespStatus; unsigned short usPort = 0; Tcp4uLog (LOG4U_HIPROC, "HttpGetFileEx"); #define XX_RETURN(a) {if (szData!=NULL) Free(szData);\ if (hHeaderFile!=HFILE_ERROR){\ Close(hHeaderFile);\ Unlink(szHeaderFile);\ }\ if (CSock != INVALID_SOCKET) TcpClose(&CSock);\ Tcp4uLog (LOG4U_HIEXIT, "HttpGetFileEx with return code %d", a); \ return a;\ } #ifdef UNIX /* use "hidden" env variable in order to send logs to stdout */ if (getenv ("http4u_log")!=NULL) DO_NOT_LOG = fileno(stdout); #endif /* control URL's validity and receive URL's components. If a proxy */ /* is used, send the connection components into usPort, szService */ /* and szHost. */ if ( ! HttpIsValidURL( szURL, & usPort, szService, sizeof szService , szHost, sizeof szHost , szFichier, sizeof szFichier ) || ( szProxyURL!=NULL && ! HttpIsValidURL (szProxyURL, & usPort, szService, sizeof szService, szHost, sizeof szHost, NULL, 0)) ) { XX_RETURN (HTTP4U_BAD_URL); } /* allocate buffer */ if ( (szData = Calloc(1,s_uHttp4uBufferSize)) == NULL) { XX_RETURN (HTTP4U_INSMEMORY); } /* connect to http server, or proxy server : we don't care now */ Rc = TcpConnect(& CSock, szHost, usPort==0 ? szService : NULL, & usPort); switch (Rc) { case TCP4U_SUCCESS : break; /* continue */ case TCP4U_HOSTUNKNOWN : XX_RETURN (HTTP4U_HOST_UNKNOWN); default : XX_RETURN (HTTP4U_TCP_CONNECT); } /* send a request-line method "GET", receive reply, receive data */ szRequest= szProxyURL==NULL? szFichier : szURL; /* if no proxy, simple ! */ if ( (Rc=HttpSendRequest10 (CSock, "GET ", szRequest)) != HTTP4U_SUCCESS || (Rc=HttpRecvRespStatus (CSock, & saRespStatus, szResponse,nResponseSize)) != HTTP4U_SUCCESS ) { XX_RETURN (Rc); } /* an answer has been received, let us have a look on it */ switch(saRespStatus.code) { case 200: break; /* reason-phrase OK */ case 204: XX_RETURN (HTTP4U_NO_CONTENT); case 300: case 301: XX_RETURN (HTTP4U_MOVED); case 400: XX_RETURN (HTTP4U_BAD_REQUEST); case 401: case 403: XX_RETURN (HTTP4U_FORBIDDEN); case 404: XX_RETURN (HTTP4U_NOT_FOUND); default: XX_RETURN (HTTP4U_PROTOCOL_ERROR); } /* read headers */ Rc = HttpRecvHeaders10(CSock, szData, s_uHttp4uBufferSize); /* copy headers into user buffer even if return incorrect */ if (szHeaders != NULL) Strcpyn (szHeaders, szData, min(s_uHttp4uBufferSize, (unsigned) nHeadersSize)); if (Rc!=HTTP4U_SUCCESS) XX_RETURN (Rc); /* write headers into the user local file */ if (szHeaderFile != NULL ) { if ((hHeaderFile = Open(szHeaderFile, WRITE_CR)) == HFILE_ERROR) { XX_RETURN (HTTP4U_FILE_ERROR); } /* write */ if (Write(hHeaderFile, szData, Strlen(szData)) == HFILE_ERROR) { XX_RETURN(HTTP4U_FILE_ERROR); } Close(hHeaderFile); hHeaderFile = HFILE_ERROR; } /* szHeaderFile not NULL */ /* if we do not need something else, just close the connection */ /* not really nice, but HTTP servers are used to deal with it */ if (szLocalFile==NULL && CbkTransmit==NULL) { XX_RETURN (HTTP4U_SUCCESS); } /* search real length of the body */ RealBodySize = -1; /* can not compute it */ szData[s_uHttp4uBufferSize-1] = '\0'; p = Tcp4uStrIStr (szData, "content-length:"); if (p!=NULL) { p += sizeof("Content-Length:"); while (isspace(*p)) p++; /* skip space character */ RealBodySize = Tcp4uAtol (p); } /* read Body of the respons */ Rc=TcpRecvUntilClosedEx (& CSock, szLocalFile, (FARPROC) CbkTransmit, s_uHttp4uTimeout, s_uHttp4uBufferSize, lUserValue, RealBodySize); switch (Rc) { case TCP4U_SUCCESS: Rc = HTTP4U_SUCCESS; break; case TCP4U_TIMEOUT: Rc = HTTP4U_TIMEOUT; break; case TCP4U_FILE_ERROR : Rc = HTTP4U_FILE_ERROR; break; case TCP4U_INSMEMORY : Rc = HTTP4U_INSMEMORY; break; case TCP4U_CANCELLED : Rc = HTTP4U_CANCELLED; break; default: Rc = HTTP4U_TCP_FAILED; break; } XX_RETURN (Rc); #undef XX_RETURN } /* HttpGetFileEx */ /*###################################################################### *## *## NAME: HttpGetFile *## *## PURPOSE: Return body associate with the URL's parameter *## *####################################################################*/ int API4U HttpGetFile( LPCSTR szURL, LPCSTR szProxyURL, LPCSTR szLocalFile ) { int Rc; Tcp4uLog (LOG4U_HIPROC, "HttpGetFile"); /* Appel sans callback */ Rc = HttpGetFileEx(szURL, /* the URL to be retrieved */ szProxyURL, /* The proxy to be used or NULL */ szLocalFile, /* the file to be written */ NULL, /* No header file */ NULL, 0, /* No callback */ NULL, 0, /* No memory allocated for response */ NULL, 0 /* No memory allocated for header */ ); Tcp4uLog (LOG4U_HIEXIT, "HttpGetFile"); return Rc; } /* END HttpGetFile */ <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> #include "pVehicleAll.h" #define RR_RAD_DEG_FACTOR 57.29578f // From radians to degrees" float pWheel2::getSteerAngle() { return mWheelShape->getSteerAngle(); } void pWheel2::setSteering(float angle) { if(angle>lock)angle=lock; else if(angle<-lock)angle=-lock; rotation.y=angle+toe; // Apply Ackerman effect if((ackermanFactor<0&&angle<0)||(ackermanFactor>0&&angle>0)) rotation.y*=fabs(ackermanFactor); float a = rotation.y; float steerangle= rotation.y * lastStepTimeSec; while (steerangle > NxTwoPi) //normally just 1x steerangle-= NxTwoPi; while (steerangle< -NxTwoPi) //normally just 1x steerangle+= NxTwoPi; getWheelShape()->setSteerAngle(steerangle); } bool pWheel2::getContact(pWheelContactData&dst) { NxWheelContactData wcd; NxShape* contactShape = mWheelShape->getContact(wcd); dst.contactEntity = NULL; if (contactShape) { dst.contactForce = wcd.contactForce; dst.contactNormal = getFrom(wcd.contactNormal); dst.contactPoint= getFrom(wcd.contactPoint); dst.contactPosition= wcd.contactPosition; dst.lateralDirection= getFrom(wcd.lateralDirection); dst.lateralImpulse= wcd.lateralImpulse; dst.lateralSlip = wcd.lateralSlip; dst.longitudalDirection = getFrom(wcd.longitudalDirection); dst.longitudalImpulse = wcd.longitudalImpulse; dst.longitudalSlip= wcd.longitudalSlip; pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(contactShape->userData); if (sInfo->entID) { CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); if (obj) { dst.contactEntity = (CK3dEntity*)obj; }else { dst.contactEntity = NULL; } } dst.otherShapeMaterialIndex = contactShape->getMaterial(); NxMaterial* otherMaterial = contactShape->getActor().getScene().getMaterialFromIndex(contactShape->getMaterial()); if (otherMaterial) { pFactory::Instance()->copyTo(dst.otherMaterial,otherMaterial); } return true; } return false; } pWheelContactData* pWheel2::getContact() { NxWheelShape *wShape = getWheelShape(); if (!wShape) { return new pWheelContactData(); } NxWheelContactData wcd; NxShape* contactShape = wShape->getContact(wcd); pWheelContactData result; result.contactEntity = NULL; if (contactShape) { result.contactForce = wcd.contactForce; result.contactNormal = getFrom(wcd.contactNormal); result.contactPoint= getFrom(wcd.contactPoint); result.contactPosition= wcd.contactPosition; result.lateralDirection= getFrom(wcd.lateralDirection); result.lateralImpulse= wcd.lateralImpulse; result.lateralSlip = wcd.lateralSlip; result.longitudalDirection = getFrom(wcd.longitudalDirection); result.longitudalImpulse = wcd.longitudalImpulse; result.longitudalSlip= wcd.longitudalSlip; pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(contactShape->userData); if (sInfo->entID) { CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); if (obj) { result.contactEntity = (CK3dEntity*)obj; }else { result.contactEntity = NULL; } } result.otherShapeMaterialIndex = contactShape->getMaterial(); NxMaterial* otherMaterial = contactShape->getActor().getScene().getMaterialFromIndex(contactShape->getMaterial()); if (otherMaterial) { pFactory::Instance()->copyTo(result.otherMaterial,otherMaterial); } } return &result; } void pWheel2::_updateVirtoolsEntity(bool position,bool rotation) { CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(getEntID())); if (ent && position) { NxWheelShape *wShape = getWheelShape(); NxMat34 pose = wShape->getGlobalPose(); NxWheelContactData wcd; NxShape* contactShape = wShape->getContact(wcd); NxVec3 suspensionOffsetDirection; pose.M.getColumn(1, suspensionOffsetDirection); suspensionOffsetDirection =-suspensionOffsetDirection; if (contactShape && wcd.contactForce > -1000) { NxVec3 toContact = wcd.contactPoint - pose.t; double alongLength = suspensionOffsetDirection.dot(toContact); NxVec3 across = toContact - alongLength * suspensionOffsetDirection; double r = wShape->getRadius(); double pullBack = sqrt(r*r - across.dot(across)); pose.t += (alongLength - pullBack) * suspensionOffsetDirection; } else { pose.t += wShape->getSuspensionTravel() * suspensionOffsetDirection; } VxVector oPos = getFrom(pose.t); ent->SetPosition(&oPos); if (hasGroundContact()) { NxWheelShape *wShape = getWheelShape(); NxMat34& wheelPose = wShape->getGlobalPose(); /* NxWheelContactData wcd; NxShape* cShape = wShape->getContact(wcd); NxReal stravel = wShape->getSuspensionTravel(); NxReal radius = wShape->getRadius(); VxVector gPos = getFrom(getWheelPose().t); /* if( cShape && wcd.contactPosition <= (stravel + radius) ) { }*/ ////////////////////////////////////////////////////////////////////////// /*VxVector gPos = getFrom(getWheelPose().t); //gPos*=-1.0f; gPos -=getWheelPos(); V 3. xVector gPos2 = getFrom(getWheelShape()->getLocalPose().t); ent->SetPosition(&gPos2,getBody()->GetVT3DObject()); */ }else { // VxVector gPos = getWheelPos(); // ent->SetPosition(&gPos,getBody()->GetVT3DObject()); } } if (ent && rotation) { //float rollAngle = getWheelRollAngle(); //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); VxQuaternion rot = pMath::getFrom( getWheelPose().M ); ent->SetQuaternion(&rot,NULL); } NxWheelShape *wShape = getWheelShape(); //NxWheelShape *wShape = getWheelShape(); /* float rollAngle = getWheelRollAngle(); //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); rollAngle+=wShape->getAxleSpeed() * ((1/60) * 0.01f); */ /* while (rollAngle > NxTwoPi) //normally just 1x rollAngle-= NxTwoPi; while (rollAngle< -NxTwoPi) //normally just 1x rollAngle+= NxTwoPi; setWheelRollAngle(rollAngle); NxMat34& wheelPose = wShape->getGlobalPose(); NxWheelContactData wcd; NxShape* cShape = wShape->getContact(wcd); NxReal stravel = wShape->getSuspensionTravel(); NxReal radius = wShape->getRadius(); //have ground contact? if( cShape && wcd.contactPosition <= (stravel + radius) ) { wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); } else { wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); } float rAngle = rollAngle; float steer = wShape->getSteerAngle(); NxMat33 rot, axisRot, rollRot; rot.rotY( wShape->getSteerAngle() ); axisRot.rotY(0); rollRot.rotX(rollAngle); wheelPose.M = rot * wheelPose.M * axisRot * rollRot; setWheelPose(wheelPose); */ } void pWheel2::_updateAgeiaShape(bool position,bool rotation) { } float pWheel2::getRadius()const { return mWheelShape->getRadius(); } float pWheel2::getRpm() const { float a = NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; if (getVehicle()) { float b = NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * getVehicle()->_lastDT; return b; } return NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; } VxVector pWheel2::getWheelPos() const { return getFrom(mWheelShape->getLocalPosition()); } void pWheel2::setAngle(float angle) { mWheelShape->setSteerAngle(-angle); } NxActor*pWheel2::getTouchedActor()const { NxWheelContactData wcd; NxShape * s = mWheelShape->getContact(wcd); if (s) { if (&s->getActor()) { return &s->getActor(); }else { return NULL; } }else { return NULL; } return NULL; //return s ? &s->getActor() : NULL; } float pWheel2::getAxleSpeed()const { if (mWheelShape) { return mWheelShape->getAxleSpeed(); } return -1.f; } bool pWheel2::hasGroundContact() const { return getTouchedActor() != NULL; } void pWheel2::tick(bool handBrake, float motorTorque, float brakeTorque, float dt) { if(handBrake && getWheelFlag(WF_AffectedByHandbrake)) brakeTorque = 1000.0f; if(getWheelFlag(WF_Accelerated)) mWheelShape->setMotorTorque(motorTorque); mWheelShape->setBrakeTorque(brakeTorque); /* NxWheelShape *wShape = getWheelShape(); float rollAngle = getWheelRollAngle(); rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); while (rollAngle > NxTwoPi) //normally just 1x rollAngle-= NxTwoPi; while (rollAngle< -NxTwoPi) //normally just 1x rollAngle+= NxTwoPi; setWheelRollAngle(rollAngle); NxMat34& wheelPose = wShape->getGlobalPose(); NxWheelContactData wcd; NxShape* cShape = wShape->getContact(wcd); NxReal stravel = wShape->getSuspensionTravel(); NxReal radius = wShape->getRadius(); //have ground contact? if( cShape && wcd.contactPosition <= (stravel + radius) ) { wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); } else { wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); } float rAngle = rollAngle; float steer = wShape->getSteerAngle(); NxMat33 rot, axisRot, rollRot; rot.rotY( wShape->getSteerAngle() ); axisRot.rotY(0); rollRot.rotX(rollAngle); wheelPose.M = rot * wheelPose.M * axisRot * rollRot; setWheelPose(wheelPose); */ } VxVector pWheel2::getGroundContactPos()const { VxVector pos = getWheelPos()+VxVector(0, -mWheelShape->getRadius(), 0); if (pos.Magnitude()) { int op2 = 0 ; op2++; } return pos; } float pWheel2::getSuspensionTravel()const { if (mWheelShape) { return mWheelShape->getSuspensionTravel(); } return 0.0f; } bool pWheel2::setSuspensionSpring(const pSpring& spring) { NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; if (!sLimit.isValid())return false; NxWheelShape *wShape = getWheelShape(); if (!wShape) { return false; } wShape->setSuspension(sLimit); return true; } void pWheel2::setAxleSpeed(float speed) { getWheelShape()->setAxleSpeed(speed); } void pWheel2::setMotorTorque(float torque) { getWheelShape()->setMotorTorque(torque); } void pWheel2::setBreakTorque(float torque) { getWheelShape()->setBrakeTorque(torque); } void pWheel2::setSuspensionTravel(float travel) { getWheelShape()->setSuspensionTravel(travel); } pWheel2::pWheel2(pRigidBody *body,pWheelDescr *descr,CK3dEntity *wheelShapeReference): pWheel(body,descr) ,xEngineObjectAssociation<CK3dEntity*>(wheelShapeReference,wheelShapeReference->GetID()) { this->setBody(body); this->setEntity(wheelShapeReference); brakingFactor = 0.05f; frictionCoeff = 1.0f; rollingCoeff = 1.0f; mWheelShape = NULL; mWheelFlags = descr->wheelFlags; _wheelRollAngle = 0.0f; mVehicle = NULL; lastContactData = new pWheelContactData(); differentialSide=0; differential = NULL; hadContact = false; slip2FCVelFactor = 1.0f; tanSlipAngle=0; slipAngle=0; slipRatio=0; lastU=0; signU=1; // u>=0 differentialSlipRatio=0; maxBrakingTorque = 400.0; lock = 80.0f; ackermanFactor=1.1f; tireRate = 180000; mass = 10.0f; radius = descr->radius.value; radiusLoaded = descr->radius.value; SetInertia(5.3f); relaxationLengthLat=0.91f; relaxationLengthLong=0.091f; dampingSpeed = 0.15f; dampingCoefficientLong = 1.5f; dampingFactorLat=0.75; dampingFactorLong=1.5f; dampingCoefficientLat = 1.066f; toe =-(1.0f/RR_RAD_DEG_FACTOR); rotation.Set(0,0,0); rotation.y = toe; //---------------------------------------------------------------- // // pacejka // pacejka.setToDefault(); //Statistical data (SR, SA in radians) optimalSR=0.09655f; optimalSA=0.18296f; stateFlags = 0; lowSpeedFactor = 0.0f; slipAngle = 0.0f; slipRatio = 0.0f; overrideMask = 0; callMask.set(CB_OnPostProcess,1); callMask.set(CB_OnPreProcess,1); preScript = postScript = 0; entity = NULL; wheelContactModifyCallback =NULL; differential = NULL; differentialSide =-1; } void pWheel2::setDifferential(pDifferential *diff,int side) { differential=diff; differentialSide=side; } float pWheel2::getEndBrakingTorqueForWheel() { if(differential) { return differential->GetBreakTorqueOut(differentialSide); } return 0.0f; } float pWheel2::getEndTorqueForWheel() { if(differential) { //*2*PI/60.0f return differential->GetTorqueOut(differentialSide); } return 0.0f; } float pWheel2::getEndAccForWheel() { if(differential) { return differential->GetAccOut(differentialSide); } return 0.0f; } float pWheel2::getWheelBreakTorque() { if(mWheelShape) { return mWheelShape->getBrakeTorque(); } return 0.0f; } float pWheel2::getWheelTorque() { if(mWheelShape) { return mWheelShape->getMotorTorque(); } return 0.0f; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> void pWheel2::_tick(float dt) { NxWheelShape *wShape = getWheelShape(); if (!wShape) return; NxVec3 _localVelocity; bool _breaking=false; ////////////////////////////////////////////////////////////////////////// // // // NxWheelContactData wcd; NxShape* contactShape = wShape->getContact(wcd); if (contactShape) { NxVec3 relativeVelocity; if ( !contactShape->getActor().isDynamic()) { relativeVelocity = getActor()->getLinearVelocity(); } else { relativeVelocity = getActor()->getLinearVelocity() - contactShape->getActor().getLinearVelocity(); } NxQuat rotation = getActor()->getGlobalOrientationQuat(); _localVelocity = relativeVelocity; rotation.inverseRotate(_localVelocity); _breaking = false; //NxMath::abs(_localVelocity.z) < ( 0.1 ); // wShape->setAxleSpeed() } float rollAngle = getWheelRollAngle(); rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); //rollAngle+=wShape->getAxleSpeed() * (1.0f/60.0f /*dt* 0.01f*/); while (rollAngle > NxTwoPi) //normally just 1x rollAngle-= NxTwoPi; while (rollAngle< -NxTwoPi) //normally just 1x rollAngle+= NxTwoPi; setWheelRollAngle(rollAngle); NxMat34& wheelPose = wShape->getGlobalPose(); NxReal stravel = wShape->getSuspensionTravel(); NxReal radius = wShape->getRadius(); //have ground contact? if( contactShape && wcd.contactPosition <= (stravel + radius) ) { wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); } else { wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); } float rAngle = getWheelRollAngle(); float steer = wShape->getSteerAngle(); NxVec3 p0; NxVec3 dir; /* getWorldSegmentFast(seg); seg.computeDirection(dir); dir.normalize(); */ NxReal r = wShape->getRadius(); NxReal st = wShape->getSuspensionTravel(); NxReal steerAngle = wShape->getSteerAngle(); p0 = wheelPose.t; //cast from shape origin wheelPose.M.getColumn(1, dir); dir = -dir; //cast along -Y. NxReal castLength = r + st; //cast ray this long NxMat33 rot, axisRot, rollRot; rot.rotY( wShape->getSteerAngle() ); axisRot.rotY(0); rollRot.rotX(rAngle); wheelPose.M = rot * wheelPose.M * axisRot * rollRot; setWheelPose(wheelPose); } pWheelContactData* pWheel2::getContact() { NxWheelShape *wShape = getWheelShape(); if (!wShape) { return new pWheelContactData(); } NxWheelContactData wcd; NxShape* contactShape = wShape->getContact(wcd); pWheelContactData result; result.contactEntity = NULL; if (contactShape) { result.contactForce = wcd.contactForce; result.contactNormal = getFrom(wcd.contactNormal); result.contactPoint= getFrom(wcd.contactPoint); result.contactPosition= wcd.contactPosition; result.lateralDirection= getFrom(wcd.lateralDirection); result.lateralImpulse= wcd.lateralImpulse; result.lateralSlip = wcd.lateralSlip; result.longitudalDirection = getFrom(wcd.longitudalDirection); result.longitudalImpulse = wcd.longitudalImpulse; result.longitudalSlip= wcd.longitudalSlip; pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(contactShape->userData); if (sInfo->entID) { CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); if (obj) { result.contactEntity = (CK3dEntity*)obj; }else { result.contactEntity = NULL; } } result.otherShapeMaterialIndex = contactShape->getMaterial(); NxMaterial* otherMaterial = contactShape->getActor().getScene().getMaterialFromIndex(contactShape->getMaterial()); if (otherMaterial) { pFactory::Instance()->copyTo(result.otherMaterial,otherMaterial); } } return &result; } void pWheel2::_updateVirtoolsEntity(bool position,bool rotation) { CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(getEntID())); if (ent && position) { NxWheelShape *wShape = getWheelShape(); NxMat34 pose = wShape->getGlobalPose(); NxWheelContactData wcd; NxShape* contactShape = wShape->getContact(wcd); NxVec3 suspensionOffsetDirection; pose.M.getColumn(1, suspensionOffsetDirection); suspensionOffsetDirection =-suspensionOffsetDirection; if (contactShape && wcd.contactForce > -1000) { NxVec3 toContact = wcd.contactPoint - pose.t; double alongLength = suspensionOffsetDirection.dot(toContact); NxVec3 across = toContact - alongLength * suspensionOffsetDirection; double r = wShape->getRadius(); double pullBack = sqrt(r*r - across.dot(across)); pose.t += (alongLength - pullBack) * suspensionOffsetDirection; } else { pose.t += wShape->getSuspensionTravel() * suspensionOffsetDirection; } VxVector oPos = getFrom(pose.t); ent->SetPosition(&oPos); if (hasGroundContact()) { NxWheelShape *wShape = getWheelShape(); NxMat34& wheelPose = wShape->getGlobalPose(); /* NxWheelContactData wcd; NxShape* cShape = wShape->getContact(wcd); NxReal stravel = wShape->getSuspensionTravel(); NxReal radius = wShape->getRadius(); VxVector gPos = getFrom(getWheelPose().t); /* if( cShape && wcd.contactPosition <= (stravel + radius) ) { }*/ ////////////////////////////////////////////////////////////////////////// /*VxVector gPos = getFrom(getWheelPose().t); //gPos*=-1.0f; gPos -=getWheelPos(); V 3. xVector gPos2 = getFrom(getWheelShape()->getLocalPose().t); ent->SetPosition(&gPos2,getBody()->GetVT3DObject()); */ }else { // VxVector gPos = getWheelPos(); // ent->SetPosition(&gPos,getBody()->GetVT3DObject()); } } if (ent && rotation) { //float rollAngle = getWheelRollAngle(); //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); VxQuaternion rot = pMath::getFrom( getWheelPose().M ); ent->SetQuaternion(&rot,NULL); } /* NxWheelShape *wShape = getWheelShape(); while (rollAngle > NxTwoPi) //normally just 1x rollAngle-= NxTwoPi; while (rollAngle< -NxTwoPi) //normally just 1x rollAngle+= NxTwoPi; setWheelRollAngle(rollAngle); NxMat34& wheelPose = wShape->getGlobalPose(); NxWheelContactData wcd; NxShape* cShape = wShape->getContact(wcd); NxReal stravel = wShape->getSuspensionTravel(); NxReal radius = wShape->getRadius(); //have ground contact? if( cShape && wcd.contactPosition <= (stravel + radius) ) { wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); } else { wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); } float rAngle = rollAngle; float steer = wShape->getSteerAngle(); NxMat33 rot, axisRot, rollRot; rot.rotY( wShape->getSteerAngle() ); axisRot.rotY(0); rollRot.rotX(rollAngle); wheelPose.M = rot * wheelPose.M * axisRot * rollRot; setWheelPose(wheelPose); */ } void pWheel2::_updateAgeiaShape(bool position,bool rotation) { } float pWheel2::getRadius()const { return mWheelShape->getRadius(); } float pWheel2::getRpm() const { float a = NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; if (getVehicle()) { float b = NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * getVehicle()->_lastDT; return b; } return NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; } VxVector pWheel2::getWheelPos() const { return getFrom(mWheelShape->getLocalPosition()); } void pWheel2::setAngle(float angle) { mWheelShape->setSteerAngle(-angle); } NxActor*pWheel2::getTouchedActor()const { NxWheelContactData wcd; NxShape * s = mWheelShape->getContact(wcd); if (s) { if (&s->getActor()) { return &s->getActor(); }else { return NULL; } }else { return NULL; } return NULL; //return s ? &s->getActor() : NULL; } float pWheel2::getAxleSpeed()const { if (mWheelShape) { return mWheelShape->getAxleSpeed(); } return -1.f; } bool pWheel2::hasGroundContact() const { return getTouchedActor() != NULL; } void pWheel2::tick(bool handBrake, float motorTorque, float brakeTorque, float dt) { if(handBrake && getWheelFlag(WF_AffectedByHandbrake)) brakeTorque = 1000.0f; if(getWheelFlag(WF_Accelerated)) mWheelShape->setMotorTorque(motorTorque); mWheelShape->setBrakeTorque(brakeTorque); NxWheelShape *wShape = getWheelShape(); float rollAngle = getWheelRollAngle(); rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); while (rollAngle > NxTwoPi) //normally just 1x rollAngle-= NxTwoPi; while (rollAngle< -NxTwoPi) //normally just 1x rollAngle+= NxTwoPi; setWheelRollAngle(rollAngle); NxMat34& wheelPose = wShape->getGlobalPose(); NxWheelContactData wcd; NxShape* cShape = wShape->getContact(wcd); NxReal stravel = wShape->getSuspensionTravel(); NxReal radius = wShape->getRadius(); //have ground contact? if( cShape && wcd.contactPosition <= (stravel + radius) ) { wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); } else { wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); } float rAngle = rollAngle; float steer = wShape->getSteerAngle(); NxMat33 rot, axisRot, rollRot; rot.rotY( wShape->getSteerAngle() ); axisRot.rotY(0); rollRot.rotX(rollAngle); wheelPose.M = rot * wheelPose.M * axisRot * rollRot; setWheelPose(wheelPose); } VxVector pWheel2::getGroundContactPos()const { VxVector pos = getWheelPos()+VxVector(0, -mWheelShape->getRadius(), 0); if (pos.Magnitude()) { int op2 = 0 ; op2++; } return pos; } float pWheel2::getSuspensionTravel()const { if (mWheelShape) { return mWheelShape->getSuspensionTravel(); } return 0.0f; } bool pWheel2::setSuspensionSpring(const pSpring& spring) { NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; if (!sLimit.isValid())return false; NxWheelShape *wShape = getWheelShape(); if (!wShape) { return false; } wShape->setSuspension(sLimit); return true; } void pWheel2::setAxleSpeed(float speed) { getWheelShape()->setAxleSpeed(speed); } void pWheel2::setMotorTorque(float torque) { getWheelShape()->setMotorTorque(torque); } void pWheel2::setBreakTorque(float torque) { getWheelShape()->setBrakeTorque(torque); } void pWheel2::setSuspensionTravel(float travel) { getWheelShape()->setSuspensionTravel(travel); } pWheel2::pWheel2(pRigidBody *body, pWheelDescr *descr) : pWheel(body,descr) { this->setBody(body); mWheelShape = NULL; mWheelFlags = descr->wheelFlags; _wheelRollAngle = 0.0f; mVehicle = NULL; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" pJointPrismatic::pJointPrismatic(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Prismatic) { } void pJointPrismatic::setGlobalAnchor(VxVector anchor) { NxPrismaticJointDesc descr; NxPrismaticJoint*joint = static_cast<NxPrismaticJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.setGlobalAnchor(getFrom(anchor)); joint->loadFromDesc(descr); } void pJointPrismatic::setGlobalAxis(VxVector axis) { NxPrismaticJointDesc descr; NxPrismaticJoint*joint = static_cast<NxPrismaticJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.setGlobalAxis(getFrom(axis)); joint->loadFromDesc(descr); } void pJointPrismatic::enableCollision(int collision) { NxPrismaticJointDesc descr; NxPrismaticJoint*joint = static_cast<NxPrismaticJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (collision) { descr.jointFlags |= NX_JF_COLLISION_ENABLED; }else descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; joint->loadFromDesc(descr); }<file_sep>#include "IDistributedClasses.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "xDistributedSessionClass.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xLogger.h" /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IDistributedClasses::deployClass(xDistributedClass*_class) { if (!_class)return; xNetInterface *nInterface = getNetInterface(); if (!nInterface)return; if (nInterface->IsServer())return; ////////////////////////////////////////////////////////////////////////// //pickup some data : TNL::StringPtr className(_class->getClassName().getString()); TNL::Int<16>entityType = _class->getEnitityType(); TNL::Vector<TNL::StringPtr>propertyNames; TNL::Vector<TNL::Int<16> >nativeTypes; TNL::Vector<TNL::Int<16> >valueTypes; TNL::Vector<TNL::Int<16> >predictionTypes; xDistributedPropertiesListType &props = *_class->getDistributedProperties(); for (unsigned int i = 0 ; i < props.size() ; i ++ ) { xDistributedPropertyInfo *dInfo = props[i]; propertyNames.push_back( TNL::StringPtr(dInfo->mName) ); nativeTypes.push_back(dInfo->mNativeType); valueTypes.push_back(dInfo->mValueType); predictionTypes.push_back(dInfo->mPredictionType); } ////////////////////////////////////////////////////////////////////////// //we call this on the server : if (nInterface->getConnection()) { nInterface->getConnection()->c2sDeployDistributedClass(className,entityType,propertyNames,nativeTypes,valueTypes,predictionTypes); } } /* ******************************************************************* * Function: IDistributedClasses::IDistributedClasses * * Description: * Distributed class interface destructor. * Parameters: * Returns: * ******************************************************************* */ IDistributedClasses::~IDistributedClasses() { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ IDistributedClasses::IDistributedClasses(xNetInterface *netInterface) : m_NetInterface(netInterface) , m_DistrutedClasses(new xDistributedClassesArrayType() ) { //m_DistrutedClasses = new XDistributedClassesArrayType(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedClassesArrayType* IDistributedClasses::getDistrutedClassesPtr() { return m_DistrutedClasses; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedClass*IDistributedClasses::createClass(const char* name,int templatetype) { if (!strlen(name)) return NULL; xDistributedClassesArrayType *_classes = getDistrutedClassesPtr(); xDistributedClass *result = get(name); if (result ==NULL ) { switch(templatetype) { case E_DC_BTYPE_3D_ENTITY: { result = new xDistributed3DObjectClass(); } break; case E_DC_BTYPE_CLIENT: { result = new xDistributedClass(); } break; case E_DC_BTYPE_SESSION: { result = new xDistributedSessionClass(); } break; default: { result = new xDistributedClass(); } break; } result->setClassName(name); result->setEnitityType(templatetype); _classes->insert(std::make_pair(name,result)); //xLogger::xLog(ELOGINFO,E_LI_DISTRIBUTED_CLASS_DESCRIPTORS,"Distributed class created : %s : type : %d",name,templatetype); //xLogger::xLog(XL_START,ELOGINFO,E_LI_DISTRIBUTED_CLASS_DESCRIPTORS,"Distributed class created : %s : type : %d",name,templatetype); return result; }else { return result; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedClass* IDistributedClasses::getByIndex(int index) { /*if (index > 0 && index < getDistrutedClassesPtr()->size() ) { return *getDistrutedClassesPtr()->GetByIndex(index); }*/ return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int IDistributedClasses::destroyClass(xDistributedClass *_class) { if (_class ==NULL ) { xLogger::xLog(XL_START,ELOGERROR,E_LI_DISTRIBUTED_CLASS_DESCRIPTORS,"invalid object"); return -1; } xDistributedClassesArrayType *_classes = getDistrutedClassesPtr(); xDistClassIt begin = _classes->begin(); xDistClassIt end = _classes->end(); while (begin!=end) { xDistributedClass *_tclass = begin->second; if (_tclass == _class) { xNString cName = _class->getClassName().getString(); _classes->erase(begin); delete _tclass; //xLogger::xLog(XL_START,ELOGINFO,E_LI_DISTRIBUTED_CLASS_DESCRIPTORS,"%s removed and destroyed! Classes left :%d ",cName.getString(),_classes->size()); return 1; } begin++; } //xLogger::xLog(XL_START,ELOGERROR,E_LI_DISTRIBUTED_CLASS_DESCRIPTORS,"couldn't find object"); return 0; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int IDistributedClasses::getNumClasses(){ return getDistrutedClassesPtr()->size();} /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedClass*IDistributedClasses::get(const char* name) { xDistributedClassesArrayType *_classes = getDistrutedClassesPtr(); xDistClassIt begin = _classes->begin(); xDistClassIt end = _classes->end(); while (begin!=end) { xDistributedClass *_class = begin->second; if (_class) { if (!strcmp(_class->getClassName().getString(),name) ) { return _class; } } begin++; } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedClass*IDistributedClasses::get(const char* name,int entityType) { xDistributedClassesArrayType *_classes = getDistrutedClassesPtr(); xDistClassIt begin = _classes->begin(); xDistClassIt end = _classes->end(); while (begin!=end) { xDistributedClass *_class = begin->second; if (_class) { if (!strcmp(_class->getClassName().getString(),name) && _class->getEnitityType() == entityType) { return _class; } } begin++; } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IDistributedClasses::destroy() { xDistributedClassesArrayType *_classes = getDistrutedClassesPtr(); xDistClassIt begin = _classes->begin(); xDistClassIt end = _classes->end(); _classes->clear(); return; while (begin!=end) { xDistributedClass *_class = begin->second; if (_class) { delete _class; _class = NULL; begin = _classes->begin(); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xNetInterface* IDistributedClasses::getNetInterface(){ return m_NetInterface; } <file_sep>#include "xDistributedSessionClass.h" #include "xDistributedPropertyInfo.h" #include "xDistTools.h" xDistributedSessionClass::xDistributedSessionClass() : xDistributedClass() { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributedSessionClass::getFirstUserField(){ return 6; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributedSessionClass::getUserFieldBitValue(int walkIndex) { int userTypeCounter = 0; xDistributedPropertiesListType &props = *getDistributedProperties(); for (unsigned int i = 0 ; i < props.size() ; i ++ ) { xDistributedPropertyInfo *dInfo = props[i]; if (dInfo->mNativeType==E_DC_S_NP_USER ) { if (i ==walkIndex) { break; } userTypeCounter++; } } int result = getFirstUserField(); result +=userTypeCounter; return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributedSessionClass::getInternalUserFieldIndex(int inputIndex) { int userTypeCounter = 0; xDistributedPropertiesListType &props = *getDistributedProperties(); for (unsigned int i = 0 ; i < props.size() ; i ++ ) { xDistributedPropertyInfo *dInfo = props[i]; if (dInfo->mNativeType==E_DC_S_NP_USER) { if (userTypeCounter == inputIndex) { return i; } userTypeCounter++; } } return -1; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributedSessionClass::getUserFieldCount() { int userTypeCounter = 0; xDistributedPropertiesListType &props = *getDistributedProperties(); for (unsigned int i = 0 ; i < props.size() ; i ++ ) { if (props[i]->mNativeType==E_DC_S_NP_USER) userTypeCounter++; } return userTypeCounter; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSessionClass::addProperty(int nativeType,int predictionType) { xDistributedPropertyInfo *result = exists(nativeType); if (!result) { TNL::StringPtr name = NativeTypeToString(nativeType); int valueType = NativeTypeToValueType(nativeType); result = new xDistributedPropertyInfo( name ,valueType , nativeType ,predictionType ); getDistributedProperties()->push_back( result ); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedSessionClass::addProperty(const char*name,int type,int predictionType) { xDistributedPropertyInfo *result = exists(name); if (!result) { result = new xDistributedPropertyInfo( name ,type,E_DC_S_NP_USER ,predictionType ); getDistributedProperties()->push_back( result ); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xNString xDistributedSessionClass::NativeTypeToString(int nativeType) { switch(nativeType) { case E_DC_S_NP_MAX_USERS: return TNL::StringPtr("Max Users"); break; case E_DC_S_NP_PASSWORD: return TNL::StringPtr("Password"); break; case E_DC_S_NP_LOCKED: return TNL::StringPtr("Is Locked"); case E_DC_S_NP_NUM_USERS: return TNL::StringPtr("Num Users"); case E_DC_S_NP_TYPE: return TNL::StringPtr("Session Type"); default: return TNL::StringPtr("Unknown"); break; } return TNL::StringPtr("null"); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xDistributedSessionClass::NativeTypeToValueType(int nativeType) { int result = 0; switch(nativeType) { case E_DC_S_NP_TYPE: case E_DC_S_NP_LOCKED: case E_DC_S_NP_NUM_USERS: case E_DC_S_NP_MAX_USERS: return E_DC_PTYPE_INT; case E_DC_S_NP_PASSWORD: return E_DC_PTYPE_STRING; } return E_DC_PTYPE_UNKNOWN; }<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Bend // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorBendDecl(); CKERROR CreateBendProto(CKBehaviorPrototype **); int Bend(const CKBehaviorContext& behcontext); //CKERROR MeshModificationsCallBack(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorBendDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Bend2"); od->SetDescription("Bends a mesh uniformly along an axis with an angle and a direction of bending."); /* rem: <SPAN CLASS=in>In : </SPAN>triggers the process.<BR> <SPAN CLASS=out>Exit : </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Angle : </SPAN>angle to bend from the vertical plane.<BR> <SPAN CLASS=pin>Direction : </SPAN>direction of the bend relative to the horizontal plane.<BR> <SPAN CLASS=pin>Axis : </SPAN>vector that specifies the axis that the object will bend along.<BR> <SPAN CLASS=pin>Reset Mesh: </SPAN>if TRUE, the mesh is resetted to its initial conditions at activation.<BR> <BR> The model need to be somewhat facetted for a good result.<BR> */ od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7c9a7008,0x6b0f1d1f)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00020000); od->SetCreationFunction(CreateBendProto); od->SetCompatibleClassId(CKCID_3DOBJECT); od->SetCategory("Mesh Modifications/Deformation"); return od; } CKERROR CreateBendProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("Bend"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Exit"); proto->DeclareInParameter("Angle", CKPGUID_ANGLE, "0:90" ); proto->DeclareInParameter("Direction", CKPGUID_FLOAT ,"0.0"); // To change by Radio buttons proto->DeclareInParameter("Axis", CKPGUID_VECTOR, "0,0,1" ); proto->DeclareInParameter("Reset Mesh", CKPGUID_BOOL, "TRUE" ); proto->DeclareInParameter("Normal Recalculation", CKPGUID_BOOL, "TRUE" ); proto->DeclareLocalParameter(NULL, CKPGUID_VOIDBUF ); // Data proto->DeclareLocalParameter(NULL, CKPGUID_BOX ); // Initial Box proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(Bend); // proto->SetBehaviorCallbackFct(MeshModificationsCallBack); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int Bend(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; // we get the entity CK3dEntity *ent = (CK3dEntity *) beh->GetTarget(); // we get the angle float angle; beh->GetInputParameterValue(0,&angle); angle *= 0.5f; // we get the direction float direction; beh->GetInputParameterValue(1,&direction); // we get the axis VxVector axis; beh->GetInputParameterValue(2,&axis); int naxis=0; while (axis[naxis]==0.0f) naxis++; // we get the mesh CKMesh *mesh = ent->GetCurrentMesh(); CKDWORD vStride=0; BYTE* varray = (BYTE*)mesh->GetModifierVertices(&vStride); int pointsNumber = mesh->GetModifierVertexCount(); /* CKBOOL resetmesh = TRUE; beh->GetInputParameterValue(3,&resetmesh); if (resetmesh) { // The Mesh must be resetted if(beh->GetVersion() < 0x00020000) { // Old Version with vertices stuffed inside // we get the saved position VxVector* savePos = (VxVector*)beh->GetLocalParameterWriteDataPtr(0); BYTE* temparray = varray; for(int i=0;i<pointsNumber;i++,temparray+=vStride) { *(VxVector*)temparray = savePos[i]; } } else { // new version : based on ICs CKScene *scn = behcontext.CurrentScene; CKStateChunk *chunk = scn->GetObjectInitialValue(mesh); if(chunk) mesh->LoadVertices(chunk); varray = (BYTE*)mesh->GetModifierVertices(&vStride); pointsNumber = mesh->GetModifierVertexCount(); const VxBbox& bbox = mesh->GetLocalBox(); beh->SetLocalParameterValue(1,&bbox); } } VxBbox bbox; beh->GetLocalParameterValue(1,&bbox); VxMatrix mat; switch (naxis) { case 0: { VxVector vz(0.0f,1.0f,0.0f); Vx3DMatrixFromRotation(mat,vz,-HALFPI); } break; //x case 1: { VxVector vx(0.0f,0.0f,1.0f); Vx3DMatrixFromRotation(mat,vx,-HALFPI); } break; //y case 2: { mat = VxMatrix::Identity(); } break; //z } // attention inversion y / z if (direction) { VxMatrix rot; VxVector vz(0.0f,0.0f,1.0f); Vx3DMatrixFromRotation(rot,vz,direction); Vx3DMultiplyMatrix(mat,rot,mat); } float r,len; switch (naxis) { case 0: len = bbox.Max.x - bbox.Min.x; break; case 1: len = bbox.Max.y - bbox.Min.y; break; case 2: len = bbox.Max.z - bbox.Min.z; break; } // Skip the singularity if (fabs(angle) <0.0001) { beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); return CKBR_OK; } else { r = len/angle; } VxMatrix invmat; Vx3DInverseMatrix(invmat,mat); // we move all the points float x,y,c,s,yr; VxVector v,n; float invr = 1.0f/r; CKBOOL normalc = TRUE; beh->GetInputParameterValue(4,&normalc); CKDWORD nStride=0; BYTE* narray = (BYTE*)mesh->GetNormalsPtr(&nStride); if (CKIsChildClassOf(mesh,CKCID_PATCHMESH) || !normalc) narray = NULL; for(int i=0;i<pointsNumber;i++,varray+=vStride) { Vx3DMultiplyMatrixVector(&v,mat,(VxVector*)varray); x = v.x; y = v.y; yr = y*invr; c = XCos(PI-yr); s = XSin(PI-yr); v.x = r*c + r - x*c; v.y = r*s - x*s; Vx3DMultiplyMatrixVector((VxVector *)varray,invmat,&v); // normal calculation if (narray) { Vx3DRotateVector(&n,mat,(VxVector*)narray); n.x += x; n.y += y; x = n.x; y = n.y; yr = y*invr; c = XCos(PI-yr); s = XSin(PI-yr); n.x = r*c + r - x*c; n.y = r*s - x*s; n.x -= v.x; n.y -= v.y; Vx3DRotateVector((VxVector *)narray,invmat,&n); narray += nStride; } } // we only rebuild the faces normals mesh->ModifierVertexMove(FALSE,TRUE); beh->ActivateInput(0,FALSE); beh->ActivateOutput(0,TRUE); */ return CKBR_OK; }<file_sep> #include "CPStdAfx.h" #include <stdio.h> #include "profile/GProfile.h" //used from LoadProfile /************************************************************************/ /* Enigne Parameter Initiating */ /************************************************************************/ engine_profile vtBaseWindow::LoadProfile(const char* _iniFile){ engine_profile res; char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,_iniFile); GProfile PProfile(Ini); PProfile.Load(); ////////////////////////////////////////////////////////////////////////// //Path stuff : GProfile::Section *pSection = (GProfile::Section*)PProfile.FindSection("PATHS"); strcpy(res.RenderPath,PProfile.FindKey("RenderPath",pSection)->m_strValue); strcpy(res.ManagerPath,PProfile.FindKey("ManagerPath",pSection)->m_strValue); strcpy(res.BehaviorPath,PProfile.FindKey("BehaviorPath",pSection)->m_strValue); strcpy(res.PluginPath,PProfile.FindKey("PluginPath",pSection)->m_strValue); strcpy(res.LoadFile,PProfile.FindKey("LoadFile",pSection)->m_strValue); ////////////////////////////////////////////////////////////////////////// //Engine Stuff pSection = (GProfile::Section*)PProfile.FindSection("Engine"); res.g_DisableSwitch = PProfile.GetInt(pSection->m_strName,"DisableSwitch",false); res.g_Width = PProfile.GetInt(pSection->m_strName,"Width",false); res.g_Height= PProfile.GetInt(pSection->m_strName,"Height",false); res.g_Bpp = PProfile.GetInt(pSection->m_strName,"Bpp",false); res.g_FullScreenDriver = PProfile.GetInt(pSection->m_strName,"Driver",false); res.g_GoFullScreen = PProfile.GetInt(pSection->m_strName,"FullScreen",false); res.g_RefreshRate = PProfile.GetInt(pSection->m_strName,"RefreshRate",false); res.g_Mode = PProfile.GetInt(pSection->m_strName,"Mode",false); PProfile.Destroy(); return res; }<file_sep>#pragma once //by default these functions are called in vtAgeiaInterfacecallback.cpp //if you do not use callback (do not have vtAgeiaInterfacecallback.cpp), you should call these functions manually //to add a menu in Virtools Dev main menu. void InitMenu(); //to remove the menu from Virtools Dev main menu void RemoveMenu(); //to fill menu with your own commands void UpdateMenu(); #define STR_MAINMENUNAME "vtAgeiaInterface Menu" <file_sep>#ifndef __VTCXPRECOMP_H #define __VTCXPRECOMP_H #include "VxMath.h" #include "CKAll.h" #undef min #undef max #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "NXU_helper.h" // NxuStream helper functions. #include "NXU_PhysicsInstantiator.h" #include "UserAllocator.h" #include "ErrorStream.h" #include "Utilities.h" static ErrorStream gErrorStream; static pSerializer *gSerializer = NULL; void pSerializer::parseFile(const char*filename,int flags) { if(!GetPMan()->getPhysicsSDK()) return; if (!loadCollection(filename,1)) { return ; } NXU::instantiateCollection(mCollection, *GetPMan()->getPhysicsSDK(), 0, 0, 0); NXU::NxuPhysicsInstantiator Instantiator(mCollection); Instantiator.instantiate(*GetPMan()->getPhysicsSDK()); int sCount = mCollection->mScenes.size(); for (NxU32 i=0; i<mCollection->mScenes.size(); i++) { NXU::NxSceneDesc *sd = mCollection->mScenes[i]; for (NxU32 j=0; j<sd->mActors.size(); j++) { NXU::NxActorDesc *ad = sd->mActors[j]; const char*name = ad->name; XString nameStr(name); CK3dEntity *ent = (CK3dEntity*)ctx()->GetObjectByNameAndClass(nameStr.Str(),CKCID_3DOBJECT); if (ent) { pRigidBody *body = GetPMan()->getBody(nameStr.CStr()); if (body) body->readFrom(ad,0); else body = pFactory::Instance()->createBody(ent,NULL,ad,1); } if ( ad->mHasBody ) // only for dynamic actors { for (NxU32 k=0; k<ad->mShapes.size(); k++) { NXU::NxShapeDesc *shape = ad->mShapes[k]; NxVec3 locPos = shape->localPose.t; NxQuat localQuad = shape->localPose.M; } } } } } class MyUserNotify: public NXU_userNotify, public NXU_errorReport { public: virtual void NXU_errorMessage(bool isError, const char *str) { if (isError) { printf("NxuStream ERROR: %s\r\n", str); } else { printf("NxuStream WARNING: %s\r\n", str); } } virtual void NXU_notifyScene(NxU32 sno, NxScene *scene, const char *userProperties) { }; }; MyUserNotify gUserNotify; bool pSerializer::overrideBody(pRigidBody *body,int flags) { if (!mCollection) { return false; } NXU::instantiateCollection(mCollection, *GetPMan()->getPhysicsSDK(), 0, 0, 0); NXU::NxuPhysicsInstantiator Instantiator(mCollection); Instantiator.instantiate(*GetPMan()->getPhysicsSDK()); int sCount = mCollection->mScenes.size(); for (NxU32 i=0; i<mCollection->mScenes.size(); i++) { NXU::NxSceneDesc *sd = mCollection->mScenes[i]; for (NxU32 j=0; j<sd->mActors.size(); j++) { NXU::NxActorDesc *ad = sd->mActors[j]; const char*name = ad->name; XString nameStr(name); if ( ad->mHasBody ) // only for dynamic actors { for (NxU32 k=0; k<ad->mShapes.size(); k++) { NXU::NxShapeDesc *shape = ad->mShapes[k]; NxVec3 locPos = shape->localPose.t; NxQuat localQuad = shape->localPose.M; } } } } return true; } int pSerializer::loadCollection(const char*fileName,int flags) { if (mCollection) { releaseCollection(mCollection); mCollection = NULL; } mCollection = getCollection(fileName,flags); if (mCollection) { return 1; }else { return 0; } } pSerializer::pSerializer() { gSerializer = this; mCollection = NULL; } //************************************ // Method: Instance // FullName: vtAgeia::pSerializer::Instance // Access: public static // Returns: pSerializer* // Qualifier: //************************************ pSerializer*pSerializer::Instance() { if (!gSerializer) { gSerializer = new pSerializer(); } return gSerializer; } NXU::NxuPhysicsCollection* pSerializer::getCollection(const char *pFilename,int type) { NXU::NxuPhysicsCollection* c = NULL; c = NXU::loadCollection(pFilename,(NXU::NXU_FileType)type); if (!c) { return NULL; } return c; } int pSerializer::saveCollection(const char*filename) { char SaveFilename[512]; //GetTempFilePath(SaveFilename); strcat(SaveFilename, filename); NXU::setUseClothActiveState(false); NXU::setUseSoftBodyActiveState(false); NXU::setErrorReport(&gUserNotify); NXU::setEndianMode(isProcessorBigEndian()); NXU::NxuPhysicsCollection *c = NXU::extractCollectionScene(GetPMan()->getDefaultWorld()->getScene()); if (c) { char scratch[512]; XString fName(filename); //fName << "\0"; sprintf(scratch, "%s.xml", SaveFilename); printf("Saving NxuStream XML file to '%s'\r\n", scratch); NXU::saveCollection(c, fName.CStr(), NXU::FT_BINARY, false, false); NXU::releaseCollection(c); } releaseCollection(c); return 0; } <file_sep>#include <StdAfx.h> #include "CKAll.h" CKObjectDeclaration *FillBehaviorGetNextBBIdDecl(); CKERROR CreateGetNextBBIdProto(CKBehaviorPrototype **); int GetNextBBId(const CKBehaviorContext& behcontext); CKERROR GetNextBBIdCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorGetNextBBIdDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("GetNextBBId"); od->SetDescription("Returns behavior id of first found and connected building block or behavior graph"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x572066cc,0x58402b59)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGetNextBBIdProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Narratives"); return od; } CKERROR CreateGetNextBBIdProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("GetNextBBId"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutParameter("ID",CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( GetNextBBId ); *pproto = proto; return CK_OK; } int GetNextBBId(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; beh->ActivateInput(0,FALSE); int count = beh->GetParent()->GetSubBehaviorLinkCount(); int result = -1; for (int i=0; i<count; i++) { CKBehaviorLink *link = beh->GetParent()->GetSubBehaviorLink(i); if (link->GetInBehaviorIO() == beh->GetOutput(0)) { result = link->GetOutBehaviorIO()->GetOwner()->GetID(); beh->SetOutputParameterValue(0,&result); break; } } CKBehavior *script = static_cast<CKBehavior*>(ctx->GetObject(result)); if (script) { int bc = script->GetOutputCount(); int bc2 = script->GetInputCount(); } beh->ActivateOutput(0); beh->SetOutputParameterValue(0,&result); return CKBR_OK; } <file_sep>REM createSolutions402003.bat REM createSolutions412005.bat REM createSolutions52005.bat rmdir ..\TEMP /s /q rmdir ..\BIN /s /q premake4 --ExternalVTDirectory=./VTPaths.lua --DeployDirect=TRUE --Dev=Dev40 --file="./premake4.lua" vs2003 premake4 --ExternalVTDirectory=./VTPaths.lua --DeployDirect=TRUE --Dev=Dev41 --file="./premake4.lua" vs2005 premake4 --ExternalVTDirectory=./VTPaths.lua --DeployDirect=TRUE --Dev=Dev5 --file="./premake4.lua" vs2005 start _build4Msvc7.bat start _build41Msvc8.bat start _build5Msvc8.bat ReleaseDemoPost.bat REM ----------------------------------------------------- REM -- REM -- Copy to release REM -- REM -- <file_sep>// DistributedNetworkClassDialogEditorDlg.cpp : implementation file // #include "stdafx.h" #include "DistributedNetworkClassDialogEditor.h" #include "DistributedNetworkClassDialogEditorDlg.h" #include ".\distributednetworkclassdialogeditordlg.h" #ifdef _MFCDEBUGNEW #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif DllEditorDlg* fCreateEditorDlg(HWND parent) { HRESULT r = CreateDllDialog(parent,IDD_EDITOR,&g_Editor); return (DllEditorDlg*)g_Editor; } ///////////////////////////////////////////////////////////////////////////// // DistributedNetworkClassDialogEditorDlg dialog DistributedNetworkClassDialogEditorDlg::DistributedNetworkClassDialogEditorDlg(CWnd* pParent /*=NULL*/) : DllEditorDlg(DistributedNetworkClassDialogEditorDlg::IDD, pParent),m_SplitMain(3,1) { //{{AFX_DATA_INIT(DistributedNetworkClassDialogEditorDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void DistributedNetworkClassDialogEditorDlg::DoDataExchange(CDataExchange* pDX) { DllEditorDlg::DoDataExchange(pDX); //{{AFX_DATA_MAP(DistributedNetworkClassDialogEditorDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(DistributedNetworkClassDialogEditorDlg, DllEditorDlg) //{{AFX_MSG_MAP(DistributedNetworkClassDialogEditorDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // DistributedNetworkClassDialogEditorDlg message handlers LRESULT DistributedNetworkClassDialogEditorDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { // TODO: Add your specialized code here and/or call the base class return DllEditorDlg::WindowProc(message, wParam, lParam); } BOOL DistributedNetworkClassDialogEditorDlg::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class return DllEditorDlg::PreTranslateMessage(pMsg); } BOOL DistributedNetworkClassDialogEditorDlg::OnInitDialog() { DllEditorDlg::OnInitDialog(); // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } //this is the almost equivalent of OnInitDialog you should use if you want to //use the PluginInterface with GetInterface or if you want to be sure the toolbar is present void DistributedNetworkClassDialogEditorDlg::OnInterfaceInit() { //sample code : here we ask to listen to the _CKFILELOADED notification //which is send when a file is loaded from Virtools Dev's user interface ObserveNotification(CUIK_NOTIFICATION_CKFILELOADED); _SetupSplitters(); } BOOL DistributedNetworkClassDialogEditorDlg::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) { MSGFILTER* filter = (MSGFILTER*)lParam; return DllEditorDlg::OnNotify(wParam, lParam, pResult); } //----------------------------------------------------------------------------- void DistributedNetworkClassDialogEditorDlg::OnSize(UINT nType, int cx, int cy) { if (m_SplitMain.m_hWnd) { RECT rect; GetClientRect(&rect); m_SplitMain.MoveWindow(&rect); //m_SplitEditorTitle.SetHorizontalSplitbarPosition(0, LAYOUT_EDITORTITLE-5); } DllEditorDlg::OnSize(nType, cx, cy); } void DistributedNetworkClassDialogEditorDlg::_SetupSplitters() { RECT rect; GetClientRect(&rect); int width = 1140; int height = 381; // int : column count // int : row count // int : width of window RECT at saving time // int : height of window RECT at saving time // array of int (column count-1) : SplitBars X positions (in pixel or percentage if percent==TRUE) // array of int (row count-1) : SplitBars Y positions (in pixel or percentage if percent==TRUE) int SplitMainState[] = { 3, 1, width, height, 0, 0}; _SplitterLoadState(m_SplitMain, SplitMainState, sizeof(SplitMainState) / sizeof(int)); m_SplitMain.Create(-1, rect, this, IDC_SPLIT_MAIN); } void DistributedNetworkClassDialogEditorDlg::_SplitterLoadState(VISplitterWnd &splitter, int statebuf[], int num) const { XArray<int> state; for (int i = 0; i < num; ++i) state.PushBack(statebuf[i]); splitter.LoadState(state); } //called on WM_DESTROY void DistributedNetworkClassDialogEditorDlg::OnInterfaceEnd() { } HRESULT DistributedNetworkClassDialogEditorDlg::ReceiveNotification(UINT MsgID,DWORD Param1,DWORD Param2,CKScene* Context) { switch(MsgID) { //sample code : case CUIK_NOTIFICATION_CKFILELOADED: { }break; } return 0; }<file_sep>#ifndef __VT_AGEIA_H__ #define __VT_AGEIA_H__ #include "pFactory.h" #include "pWorldSettings.h" #include "pSleepingSettings.h" #include "pWorld.h" #include "pRigidBody.h" #include "pJoint.h" #endif<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // OrthographicZoom // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorSetOrthographicZoomDecl(); CKERROR CreateSetOrthographicZoomProto(CKBehaviorPrototype **pproto); int SetOrthographicZoom(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSetOrthographicZoomDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Orthographic Zoom"); od->SetDescription("Emulates a zoom when the viewing mode is orthographic."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Zoom: </SPAN>zoom value. The higher the value, the greater the zooming in. Typical values are between 0 and 3.<BR> <BR> See Also: 'Set Projection'.<BR> */ od->SetCategory("Cameras/Basic"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x0a125555, 0x0eee5488)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00020000); od->SetCreationFunction(CreateSetOrthographicZoomProto); od->SetCompatibleClassId(CKCID_CAMERA); return od; } CKERROR CreateSetOrthographicZoomProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Orthographic Zoom"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Zoom", CKPGUID_FLOAT, "1"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetOrthographicZoom); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int SetOrthographicZoom(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); CKCamera *cam = (CKCamera *) beh->GetTarget(); if( !cam ) return CKBR_OWNERERROR; // Get Zoom float zoom=1.0f; beh->GetInputParameterValue(0, &zoom); if( beh->GetVersion()<0x00020000 ) zoom *= 0.01f; cam->SetOrthographicZoom( zoom ); return CKBR_OK; } <file_sep>/******************************************************************** created: 2009/06/01 created: 1:6:2009 14:19 filename: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick\dInputShared.h file path: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick file base: dInputShared file ext: h author: <NAME> purpose: shared functions for joystick *********************************************************************/ #ifndef __DINPUT_SHARED_H__ #define __DINPUT_SHARED_H__ #define STRICT #define DIRECTINPUT_VERSION 0x0800 #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #include <dinput.h> //----------------------------------------------------------------------------- // Function-prototypes //----------------------------------------------------------------------------- INT_PTR CALLBACK MainDialogProc( HWND, UINT, WPARAM, LPARAM ); BOOL CALLBACK EnumFFDevicesCallback2( LPCDIDEVICEINSTANCE pDDI, VOID* pvRef ); BOOL CALLBACK EnumAndCreateEffectsCallback2( LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ); HRESULT InitDirectInput2( HWND hDlg ); HRESULT FreeDirectInput2(); VOID EmptyEffectList2(); HRESULT OnReadFile2( HWND hDlg,const char*file); HRESULT OnPlayEffects2( HWND hDlg ); HRESULT SetDeviceForcesXY(float x,float y); #endif<file_sep>/* * Tcp4u v 3.31 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: dimens.h * Purpose: Internal header file * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ void Tcp4uLog (unsigned uLevel, LPCSTR szText, ...); /* internal dimensions */ #define HOST_LENGTH 256 #define SERVICE_LENGTH 64 #define FILE_LENGTH 512 /* les symboles des sump */ #define DUMP4U_SENT ">" #define DUMP4U_RCVD "<" /* internal functions */ /* these interface are subject to change */ int Tcp4uAtoi (LPCSTR p); long Tcp4uAtol (LPCSTR p); int Tcp4uStrncasecmp (LPCSTR s1, LPCSTR s2, size_t n); LPSTR Tcp4uStrIStr (LPCSTR s1, LPCSTR s2); struct in_addr Tcp4uGetIPAddr (LPCSTR szHost); /* Tcp4u.c internal cals */ int InternalTcpSend (SOCKET s, LPCSTR szBuf, unsigned uBufSize, BOOL bHighPriority, HFILE hLogFile); int InternalTcpRecv (SOCKET s, LPSTR szBuf, unsigned uBufSize, unsigned uTimeOut, HFILE hLogFile); int InternalTcpRecvUntilStr (SOCKET s, LPSTR szBuf,unsigned far *lpBufSize, LPSTR szStop, unsigned uStopSize, BOOL bCaseSensitive, unsigned uTimeOut, HFILE hLogFile); /* tn4u.c internal cals */ int InternalTnReadLine (SOCKET s,LPSTR szBuf,UINT uBufSize,UINT uTimeOut, HFILE hf); /* Udp4u.c internal cals */ int InternalUdpRecv (LPUDPSOCK pUdp, LPSTR sData, int nDataSize, unsigned uTimeOut, HFILE hLogFile); int InternalUdpSend (LPUDPSOCK Udp,LPCSTR sData, int nDataSize, BOOL bHighPriority, HFILE hLogFile); <file_sep>////////////////////////////////////////////////////////////////////////////////////////////////////////// // NeoSetMousePos ////////////////////////////////////////////////////////////////////////////////////////////////////////// //#include <winuser.h> #include "CKAll.h" #include "windows.h" CKObjectDeclaration *FillBehaviorNeoSetMousePosDecl(); CKERROR CreateNeoSetMousePosProto(CKBehaviorPrototype **); int NeoSetMousePos(const CKBehaviorContext& BehContext); int NeoSetMousePosCallBack(const CKBehaviorContext& BehContext); CKObjectDeclaration *FillBehaviorNeoSetMousePosDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Set Mouse Pos"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetVersion(0x0000001); od->SetCreationFunction(CreateNeoSetMousePosProto); od->SetDescription("Set Mouse Position"); od->SetCategory("Controllers/Mouse"); od->SetGuid(CKGUID(0xa72d87d4, 0x882b89a6)); od->SetAuthorGuid(CKGUID(0x56495254,0x4f4f4c53)); od->SetAuthorName("Neo"); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateNeoSetMousePosProto(CKBehaviorPrototype** pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set Mouse Pos"); if (!proto) { return CKERR_OUTOFMEMORY; } //--- Inputs declaration proto->DeclareInput("Set"); //--- Outputs declaration proto->DeclareOutput("Done"); //--- Input Parameters declaration proto->DeclareInParameter("X", CKPGUID_INT,"100"); proto->DeclareInParameter("Y", CKPGUID_INT,"100"); proto->DeclareInParameter("Keep Active", CKPGUID_BOOL, "TRUE"); // proto->DeclareSetting("Keep Active",CKPGUID_BOOL,"TRUE"); // proto->DeclareLocalParameter("KeepActive", CKPGUID_BOOL); //---- Local Parameters Declaration //---- Settings Declaration proto->SetBehaviorCallbackFct(NeoSetMousePosCallBack, NULL); proto->SetFunction(NeoSetMousePos); *pproto = proto; return CK_OK; } int NeoSetMousePos(const CKBehaviorContext& BehContext) { CKBehavior* beh = BehContext.Behavior; int x, y; beh->GetInputParameterValue(0,&x); beh->GetInputParameterValue(1,&y); SetCursorPos(x,y); beh->ActivateOutput(0); CKBOOL keepActive; beh->GetInputParameterValue(2,&keepActive); if(keepActive)return CKBR_ACTIVATENEXTFRAME; return CKBR_OK; } int NeoSetMousePosCallBack(const CKBehaviorContext& BehContext) { return CKBR_OK; } <file_sep>/*--------------------------------------------------------------------- NVMH5 -|---------------------- Path: Sdk\Demos\Direct3D9\src\GetGPUAndSystemInfo\ File: GetGPUAndSystemInfo.h Copyright NVIDIA Corporation 2003 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND NVIDIA AND AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Comments: A simple class to demonstrate the use of DXDiagNVUtil which is a convenient wrapper for the IDxDiagContainer interface from Microsoft. GetGPUAndSystemInfo gets only a small fraction of the information that IDxDiagContainer makes available. Since this class is simple to create and destroy, there is no specific handling for when the D3D device is lost. Simply Free() and re Initialize() the class if that should happen. -------------------------------------------------------------------------------|--------------------*/ #ifndef H_GETGPUANDSYSTEMINFO_GJ_H #define H_GETGPUANDSYSTEMINFO_GJ_H #include "3D\DXDiagNVUtil.h" #include <string> // for wstring struct IDirect3D9; struct FloatingPointBlendModes { bool m_bR16f; bool m_bR32f; bool m_bG16R16f; bool m_bG32R32f; bool m_bA16B16G16R16f; bool m_bA32B32G32R32f; bool m_bA8R8G8B8; // not an fp mode, but there for good measure }; class GetGPUAndSystemInfo { public: // DXDiagNVUtil is a utility class for creating and querring the IDxDiagContainer interface DXDiagNVUtil m_DXDiagNVUtil; // Data fields that will be filled in by the GetData() function DWORD m_dwNumDisplayDevices; float m_fDriverVersion; wstring m_wstrDeviceDesc; int m_nDeviceMemoryMB; float m_fSystemPhysicalMemoryMB; string m_strAGPStatus; string m_strMachineName; DWORD m_dwDXVersionMajor; DWORD m_dwDXVersionMinor; char m_cDXVersionLetter; wstring m_wstrDxDebugLevels; FloatingPointBlendModes m_FPBlendModes; // ---- Main interface functions -------- HRESULT GetData(); HRESULT IsFPBlendingSupported( IDirect3D9 * pD3D9, FloatingPointBlendModes * pOutResult ); // -------------------------------------- protected: void SetAllNull() { }; public: GetGPUAndSystemInfo() { SetAllNull(); }; ~GetGPUAndSystemInfo() { SetAllNull(); } }; #endif <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPClothFreeVertexDecl(); CKERROR CreatePClothFreeVertexProto(CKBehaviorPrototype **pproto); int PClothFreeVertex(const CKBehaviorContext& behcontext); CKERROR PClothFreeVertexCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_VertexIndex, }; //************************************ // Method: FillBehaviorPClothFreeVertexDecl // FullName: FillBehaviorPClothFreeVertexDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPClothFreeVertexDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothFreeVertex"); od->SetCategory("Physic/Cloth"); od->SetDescription("Frees a previously attached cloth point."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x718e795d,0x5006d9d)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePClothFreeVertexProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePClothFreeVertexProto // FullName: CreatePClothFreeVertexProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePClothFreeVertexProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothFreeVertex"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PClothFreeVertex PClothFreeVertex is categorized in \ref Clothes <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Frees a previously attached cloth point.<br> @see pCloth::freeVertex() <h3>Technical Information</h3> \image html PClothFreeVertex.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>Target cloth reference. <BR> <BR> <BR> <BR> <SPAN CLASS="pin">Vertex Index: </SPAN>Index of the vertex to free. <BR> <BR> */ proto->SetBehaviorCallbackFct( PClothFreeVertexCB ); proto->DeclareInParameter("Vertex Index",CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PClothFreeVertex); *pproto = proto; return CK_OK; } //************************************ // Method: PClothFreeVertex // FullName: PClothFreeVertex // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PClothFreeVertex(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// pWorld *world = GetPMan()->getDefaultWorld(); if (!world) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pCloth *cloth = world->getCloth(target); if (!cloth) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } int vertexIndex = GetInputParameterValue<int>(beh,bbI_VertexIndex); cloth->freeVertex(vertexIndex); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PClothFreeVertexCB // FullName: PClothFreeVertexCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PClothFreeVertexCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; }<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "ISession.h" #include "xDistributedSessionClass.h" #include "xDistributedSession.h" #include "xDistributedClient.h" #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorNSJoinObjectDecl(); CKERROR CreateNSJoinObjectProto(CKBehaviorPrototype **); int NSJoinObject(const CKBehaviorContext& behcontext); CKERROR NSJoinObjectCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 5 #define BEH_OUT_MIN_COUNT 2 #define BEH_OUT_MAX_COUNT 1 typedef enum BB_IT { BB_IT_IN }; typedef enum BB_INPAR { BB_IP_CONNECTION_ID, BB_IP_SESSION_ID, BB_IP_SESSION_PASSWORD }; typedef enum BB_OT { BB_O_JOINED, BB_O_WAITING, BB_O_ERROR }; typedef enum BB_OP { BB_OP_MASTER_ID, BB_OP_ERROR }; CKObjectDeclaration *FillBehaviorNSJoinObjectDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NSJoin"); od->SetDescription("Joins to a session"); od->SetCategory("TNL/Sessions"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5a42f45,0x49eb1634)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNSJoinObjectProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateNSJoinObjectProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NSJoin"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Joined"); proto->DeclareOutput("Waiting For Answer"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Session ID", CKPGUID_INT, "-1"); proto->DeclareInParameter("Password", CKPGUID_STRING, "none"); proto->DeclareOutParameter("Master ID", CKPGUID_INT, "-1"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareLocalParameter("state", CKPGUID_INT, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS)); proto->SetFunction(NSJoinObject); proto->SetBehaviorCallbackFct(NSJoinObjectCB); *pproto = proto; return CK_OK; } typedef std::vector<xDistributedSession*>xSessions; /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int NSJoinObject(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; bbNoError(E_NWE_OK); //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } ISession *sInterface = cin->getSessionInterface(); int connectionID = GetInputParameterValue<int>(beh,BB_IP_CONNECTION_ID); int sessionID = GetInputParameterValue<int>(beh,BB_IP_SESSION_ID); XString password ((CKSTRING) beh->GetInputParameterReadDataPtr(BB_IP_SESSION_PASSWORD)); xDistributedSession *session = sInterface->get(sessionID); if (!session) { bbError(E_NWE_NO_SUCH_SESSION); return 0; } xDistributedClient *myClient = cin->getMyClient(); if (!myClient) { bbError(E_NWE_INTERN); return 0; } if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); if (session && session->isFull()) { bbError(E_NWE_SESSION_FULL); return 0; } if (session && session->isLocked()) { bbError(E_NWE_SESSION_LOCKED); return 0; } if (session && session->isPrivate() && strcmp(password.CStr(),session->getPassword() ) ) { bbError(E_NWE_SESSION_WRONG_PASSWORD); return 0; } if (isFlagOn(myClient->getClientFlags(),E_CF_SESSION_JOINED )) { bbError(E_NWE_SESSION_ALREADY_JOINED); return 0; } sInterface->joinClient(cin->getMyClient(),sessionID,xNString(password.Str())); } if (!myClient->getClientFlags().test(1 << E_CF_SESSION_JOINED )) { bbNoError(E_NWE_OK); beh->ActivateOutput(BB_O_WAITING); } if (session && myClient->getClientFlags().test(1 << E_CF_SESSION_JOINED) ) { beh->ActivateOutput(BB_O_JOINED); ////////////////////////////////////////////////////////////////////////// //we tag all existing users as new : xDistributedClient *myClient = cin->getMyClient(); IDistributedObjects *doInterface = cin->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = cin->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject *distObject = *begin; if (distObject) { xDistributedClass *_class = distObject->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT ) { xDistributedClient *distClient = static_cast<xDistributedClient*>(distObject); if (distClient && distClient->getSessionID() == sessionID) { if (isFlagOn(distClient->getClientFlags(),E_CF_SESSION_JOINED)) enableFlag(distClient->getClientFlags(),E_CF_ADDING); } } } } begin++; } //we output all attached parameters: int sessionMasterID = session->getUserID(); beh->SetOutputParameterValue(BB_OP_MASTER_ID,&sessionMasterID); if ( beh->GetOutputParameterCount() > BEH_OUT_MIN_COUNT ) { xDistributedSessionClass *_class = (xDistributedSessionClass*)session->getDistributedClass(); CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); for (int i = BEH_OUT_MIN_COUNT ; i < beh->GetOutputParameterCount() ; i++ ) { CKParameterOut *ciIn = beh->GetOutputParameter(i); CKParameterType pType = ciIn->GetType(); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); xDistributedPropertyArrayType &props = *session->getDistributedPorperties(); int propID = _class->getInternalUserFieldIndex(i - BEH_OUT_MIN_COUNT); int startIndex = _class->getFirstUserField(); int pSize = props.size(); if (propID==-1 || propID > props.size() ) { beh->ActivateOutput(BB_O_ERROR); return 0; } xDistributedProperty *prop = props[propID]; if (prop) { //we set the update flag in the prop by hand : xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); if (propInfo) { if (xDistTools::ValueTypeToSuperType(propInfo->mValueType) ==sType ) { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); switch(propInfo->mValueType) { case E_DC_PTYPE_3DVECTOR: { xDistributedPoint3F * dpoint3F = (xDistributedPoint3F*)prop; if (dpoint3F) { VxVector vvalue = xMath::getFrom(dpoint3F->mLastServerValue); beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_FLOAT: { xDistributedPoint1F * dpoint3F = (xDistributedPoint1F*)prop; if (dpoint3F) { float vvalue = dpoint3F->mLastServerValue; beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_2DVECTOR: { xDistributedPoint2F * dpoint3F = (xDistributedPoint2F*)prop; if (dpoint3F) { Vx2DVector vvalue = xMath::getFrom(dpoint3F->mLastServerValue); beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_QUATERNION: { xDistributedQuatF * dpoint3F = (xDistributedQuatF*)prop; if (dpoint3F) { VxQuaternion vvalue = xMath::getFrom(dpoint3F->mLastServerValue); beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_STRING: { xDistributedString * propValue = (xDistributedString*)prop; if (propValue) { TNL::StringPtr ovalue = propValue->mCurrentValue; CKParameterOut *pout = beh->GetOutputParameter(i); XString errorMesg(ovalue.getString()); pout->SetStringValue(errorMesg.Str()); } break; } case E_DC_PTYPE_INT: { xDistributedInteger * dpoint3F = (xDistributedInteger*)prop; if (dpoint3F) { int ovalue = dpoint3F->mLastServerValue; beh->SetOutputParameterValue(i,&ovalue); } break; } case E_DC_PTYPE_UNKNOWN: { bbError(E_NWE_INVALID_PARAMETER); break; } } } } } } } beh->ActivateOutput(BB_O_JOINED); return 0; } return CKBR_ACTIVATENEXTFRAME; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ CKERROR NSJoinObjectCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPCTriggerEventDecl(); CKERROR CreatePCTriggerEventProto(CKBehaviorPrototype **pproto); int PCTriggerEvent(const CKBehaviorContext& behcontext); CKERROR PCTriggerEventCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPCTriggerEventDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PCTriggerEvent"); od->SetCategory("Physic/Collision"); od->SetDescription("Triggers output if body stays,enter or leaves a body ."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7e866b0f,0x5935367c)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePCTriggerEventProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePCTriggerEventProto // FullName: CreatePCTriggerEventProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePCTriggerEventProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCTriggerEvent"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PCTriggerEvent PCTriggerEvent is categorized in \ref Collision <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Triggers outputs if the body enters,stays or leaves another body .<br> See <A HREF="pBTriggerEvent.cmo">pBTriggerEvent.cmo</A> for example. <h3>Technical Information</h3> \image html PCTriggerEvent.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">No Event: </SPAN>Nothing touched. <BR> <SPAN CLASS="out">Entering: </SPAN>Body entered. <BR> <SPAN CLASS="out">Leaving: </SPAN>Body leaved. <BR> <SPAN CLASS="out">Stay: </SPAN>Inside body . <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <SPAN CLASS="pout">Touched Object: </SPAN>The touched body. <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3><br> <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForce().<br> */ proto->DeclareInput("In"); proto->DeclareInput("Next"); proto->DeclareOutput("No Event"); proto->DeclareOutput("Entering"); proto->DeclareOutput("Stay"); proto->DeclareOutput("Leaving"); proto->DeclareOutParameter("Touched Object",CKPGUID_3DENTITY,0); //proto->DeclareSetting("Trigger on Enter",CKPGUID_BOOL,"FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PCTriggerEvent); *pproto = proto; return CK_OK; } enum bOutputs { bbO_None, bbO_Enter, bbO_Stay, bbO_Leave, }; //************************************ // Method: PCTriggerEvent // FullName: PCTriggerEvent // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PCTriggerEvent(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); using namespace vtTools::BehaviorTools; ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; //world->getScene()->setFilterOps() // body exists already ? clean and delete it : pRigidBody*result = GetPMan()->getBody(target); if (!result) { beh->ActivateOutput(bbO_None); return 0; } if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); if (GetPMan()->getTriggers().Size()==0) { beh->ActivateOutput(bbO_None); return 0; } if (GetPMan()->getTriggers().Size()) { int nbEntries = GetPMan()->getTriggers().Size() ; for (int i = 0 ; i < GetPMan()->getTriggers().Size(); i++ ) { pTriggerEntry &entry = *GetPMan()->getTriggers().At(i); if (!entry.triggered) { if(entry.triggerEvent == NX_TRIGGER_ON_ENTER) { beh->ActivateOutput(bbO_Enter); } if(entry.triggerEvent == NX_TRIGGER_ON_STAY) { beh->ActivateOutput(bbO_Stay); } if(entry.triggerEvent == NX_TRIGGER_ON_LEAVE) { beh->ActivateOutput(bbO_Leave); } nbEntries--; entry.triggered = true; NxActor *triggerActor = &entry.shapeA->getActor(); NxActor *otherActor = &entry.shapeB->getActor(); pRigidBody *triggerBody = NULL; pRigidBody *otherBody = NULL; if (triggerActor) { triggerBody = static_cast<pRigidBody*>(triggerActor->userData); } if (otherActor) { otherBody = static_cast<pRigidBody*>(otherActor->userData); } if (triggerBody && result == triggerBody) { CK_ID id = otherBody->getEntID(); CKObject *entOut= (CK3dEntity*)ctx->GetObject(id); beh->SetOutputParameterObject(0,entOut); } if (otherBody && result == otherBody ) { CK_ID id = triggerBody->getEntID(); CKObject *entOut= (CK3dEntity*)ctx->GetObject(id); beh->SetOutputParameterObject(0,entOut); } } } }else{ beh->SetOutputParameterObject(0,NULL); } } return 0; } //************************************ // Method: PCTriggerEventCB // FullName: PCTriggerEventCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PCTriggerEventCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>/*************************************************************************/ /* File : MidiManager.h /* /* Author : /* Last Modification : /* /*************************************************************************/ #include "CKBaseManager.h" #include "XList.h" #ifdef _XBOX #include "Xtl.h" #else #include "windows.h" #endif //_________________Struct midiMessage struct midiMessage { unsigned char channel; unsigned char command; unsigned char note; unsigned char attack; UINT time; }; typedef XList<midiMessage> midiMessageList; class MidiManager :public CKMidiManager{ //////////////////////////////////////////////////////// // Public Part //// //////////////////////////////////////////////////////// public : // Midi Sound Playing Functions virtual void* Create(void* hwnd) ; virtual void Release(void* source) ; virtual CKERROR SetSoundFileName(void* source,CKSTRING filename) ; virtual CKSTRING GetSoundFileName(void* source) ; virtual CKERROR Play(void* source) ; virtual CKERROR Restart(void* source) ; virtual CKERROR Stop(void* source) ; virtual CKERROR Pause(void* source,CKBOOL pause=TRUE) ; virtual CKBOOL IsPlaying(void* source) ; virtual CKBOOL IsPaused(void* source) ; virtual CKERROR OpenFile(void* source) ; virtual CKERROR CloseFile(void* source) ; virtual CKERROR Preroll(void* source) ; virtual CKERROR Time(void* source,CKDWORD* pTicks) ; virtual CKDWORD MillisecsToTicks(void* source,CKDWORD msOffset) ; virtual CKDWORD TicksToMillisecs(void* source,CKDWORD tkOffset) ; // Initialization virtual CKERROR OnCKInit(); virtual CKERROR OnCKEnd(); virtual CKERROR OnCKReset(); virtual CKERROR PreProcess(); virtual CKERROR PostProcess(); virtual CKERROR PostClearAll(); virtual CKERROR OnCKPlay(); virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_OnCKInit| CKMANAGER_FUNC_OnCKEnd| CKMANAGER_FUNC_OnCKReset| CKMANAGER_FUNC_PreProcess| CKMANAGER_FUNC_PostProcess| CKMANAGER_FUNC_PostClearAll| CKMANAGER_FUNC_OnCKPlay; } //{secret} MidiManager(CKContext *ctx); //{secret} ~MidiManager(); //----- Midi Methodes void ActivateNote( int note, int channel, CKBOOL state=TRUE); CKBOOL IsNoteActive( int note, int channel ); CKERROR OpenMidiIn(int); //Try to open the midi device passed as paramter CKERROR CloseMidiIn(); CKERROR OpenMidiOut(int); //Try to open the midi device passed as paramter CKERROR CloseMidiOut(); inline void AddMidiBBref(){ ++midiDeviceBBrefcount; } inline void RemoveMidiBBref(){ --midiDeviceBBrefcount; } public: HMIDIIN midiDeviceHandle; // Device Handle HMIDIOUT midiDeviceOutHandle; int midiCurrentDevice; // current used Device ID int midiCurrentOutDevice; // current used Device ID int DesiredmidiDevice; //midi device to which the user would like to change during runtime int DesiredmidiOutDevice; //midi device to which the user would like to change during runtime CKBOOL midiDeviceIsOpen; // tells whether the current Device is open or not CKBOOL midiOutDeviceIsOpen; // tells whether the current Device is open or not int midiDeviceBBrefcount; midiMessageList listFromCallBack; midiMessageList listForBehaviors; #define MIDI_MAXNOTES 256 unsigned char noteState[MIDI_MAXNOTES]; // nb of channels * nb of note = 16 * 128 = 2048 bits = 256 bytes }; <file_sep>#ifndef _XNET_MATH_H_ #define _XNET_MATH_H_ #ifndef _XNET_TYPES_H_ #include "xNetTypes.h" #endif #ifndef _XPOINT_H_ #include "xPoint.h" #endif #ifndef _MQUAT_H_ #include "xQuat.h" #endif #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #ifdef HAS_FLUIDS #include "pFluidEmitterDesc.h" #include "pFluidEmitter.h" pFluidEmitter::pFluidEmitter() { mFluid = NULL; mEmitter = NULL; mEntityReference = 0; mRenderSettings = NULL; } #endif // HAS_FLUIDS<file_sep>/******************************************************************** created: 2007/12/12 created: 12:12:2007 11:54 filename: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude\vtCXPlatform32.h file path: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\inlcude file base: vtCXPlatform32 file ext: h author: mc007 purpose: *********************************************************************/ #include <WTypes.h> ////////////////////////////////////////////////////////////////////////// //Macros : /* From winnt.h : */ #ifndef MAKEWORD #define MAKEWORD(a, b) ((WORD)(((BYTE)((DWORD_PTR)(a) & 0xff)) | ((WORD)((BYTE)((DWORD_PTR)(b) & 0xff))) << 8)) #endif #ifndef LOWORD #define LOWORD(l) ((WORD)((DWORD_PTR)(l) & 0xffff)) #endif #ifndef HIWORD #define HIWORD(l) ((WORD)((DWORD_PTR)(l) >> 16)) #endif ////////////////////////////////////////////////////////////////////////// <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPClothAttachVertexToShapeDecl(); CKERROR CreatePClothAttachVertexToShapeProto(CKBehaviorPrototype **pproto); int PClothAttachVertexToShape(const CKBehaviorContext& behcontext); CKERROR PClothAttachVertexToShapeCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_ShapeReference, bbI_AttachmentFlags, bbI_VertexIndex, bbI_LocalPosition }; enum bSettings { bbS_USE_DEFAULT_WORLD, bbS_ADD_ATTRIBUTES }; //************************************ // Method: FillBehaviorPClothAttachVertexToShapeDecl // FullName: FillBehaviorPClothAttachVertexToShapeDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPClothAttachVertexToShapeDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAttachVertexToShape"); od->SetCategory("Physic/Cloth"); od->SetDescription("Attaches a cloth vertex to another shape."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x27970ee2,0x1247425d)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePClothAttachVertexToShapeProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePClothAttachVertexToShapeProto // FullName: CreatePClothAttachVertexToShapeProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePClothAttachVertexToShapeProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAttachVertexToShape"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PClothAttachVertexToShape PClothAttachVertexToShape is categorized in \ref Clothes <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Attaches a cloth vertex to a shape .<br> @see pCloth::attachVertexToShape() <h3>Technical Information</h3> \image html PClothAttachVertexToShape.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>Target cloth reference. <BR> <BR> <SPAN CLASS="pin">Shape Reference: </SPAN>Shape to which the cloth should be attached to. @see pCloth::attachToShape() <BR> <BR> <SPAN CLASS="pin">Attachment Flags: </SPAN>One or two way interaction, tearable or non-tearable <b>Default:</b> PCAF_ClothAttachmentTwoway @see pClothAttachmentFlag <BR> <BR> <BR> <BR> <SPAN CLASS="pin">Vertex Index: </SPAN>Index of the vertex to attach. <BR> <BR> <SPAN CLASS="pin">Local Position: </SPAN>The position relative to the pose of the shape. <BR> <BR> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include pCloth.cpp </SPAN> */ proto->SetBehaviorCallbackFct( PClothAttachVertexToShapeCB ); proto->DeclareInParameter("Shape Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Attachment Flags",VTE_CLOTH_ATTACH_FLAGS); proto->DeclareInParameter("Vertex Index",CKPGUID_INT); proto->DeclareInParameter("Local Position",CKPGUID_VECTOR); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PClothAttachVertexToShape); *pproto = proto; return CK_OK; } //************************************ // Method: PClothAttachVertexToShape // FullName: PClothAttachVertexToShape // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PClothAttachVertexToShape(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// CK3dEntity*shapeReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_ShapeReference); if (!shapeReference) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pWorld *world = GetPMan()->getDefaultWorld(); if (!world) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pCloth *cloth = world->getCloth(target); if (!cloth) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } int flags = GetInputParameterValue<int>(beh,bbI_AttachmentFlags); int vertexIndex = GetInputParameterValue<int>(beh,bbI_VertexIndex); VxVector localPosition = GetInputParameterValue<VxVector>(beh,bbI_LocalPosition); NxShape *shape = world->getShapeByEntityID(shapeReference->GetID()); if(shape) { cloth->attachVertexToShape(vertexIndex,(CKBeObject*)shapeReference,localPosition,flags); } beh->ActivateOutput(0); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PClothAttachVertexToShapeCB // FullName: PClothAttachVertexToShapeCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PClothAttachVertexToShapeCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#include <WTypes.h> ////////////////////////////////////////////////////////////////////////// //Macros : /* From winnt.h : */ #ifndef MAKEWORD #define MAKEWORD(a, b) ((WORD)(((BYTE)((DWORD_PTR)(a) & 0xff)) | ((WORD)((BYTE)((DWORD_PTR)(b) & 0xff))) << 8)) #endif #ifndef LOWORD #define LOWORD(l) ((WORD)((DWORD_PTR)(l) & 0xffff)) #endif #ifndef HIWORD #define HIWORD(l) ((WORD)((DWORD_PTR)(l) >> 16)) #endif ////////////////////////////////////////////////////////////////////////// <file_sep>#include "xDistributedClient.h" #include "xDistributedBaseClass.h" #include "xNetInterface.h" #include "vtConnection.h" #include "IDistributedClasses.h" #include "IDistributedObjectsInterface.h" #include "ISession.h" #include "xDistributedSessionClass.h" #include "xDistributedSession.h" #include "xDistributedClient.h" #include "xLogger.h" #include "IMessages.h" #include "xMessageTypes.h" #include "vtLogTools.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" TNL_IMPLEMENT_NETOBJECT(xDistributedClient); using namespace TNL; int messageIDCounter2 = 0; int messageINCounter = 0; uxString xDistributedClient::print(TNL::BitSet32 flags) { return Parent::print(flags); } void xDistributedClient::setCurrentOutMessage(xMessage* msg) { //xMessage *currentMsg = getCurrentMessage(); /*if (currentMsg && isFlagOn(currentMsg->getFlags(),E_MF_SENT)) { getNetInterface()->getMessagesInterface()->deleteMessage(currentMsg); }*/ if (msg) { enableFlag(getClientFlags(),E_CF_NM_SENDING); }else { mCurrentMessage = NULL; } mCurrentMessage = msg; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::pack(TNL::BitStream *bstream) { //Parent::pack(bstream); xMessage *currentMsg = getCurrentMessage(); IMessages *mInterface = getNetInterface()->getMessagesInterface(); if (currentMsg) { TNL::BitSet32 writeFlags=0; enableFlag(writeFlags,E_MWF_UPDATE_SERVER); disableFlag(writeFlags,E_MWF_SEND_SRC_USER_ID); if (!isFlagOn(currentMsg->getFlags(),E_MF_SEND_TO_ALL)) { enableFlag(writeFlags,E_MWF_SEND_TARGET_USER_ID); } mInterface->writeToStream(currentMsg,bstream,writeFlags); enableFlag(currentMsg->getFlags(),E_MF_SENT); enableFlag(currentMsg->getFlags(),E_MF_DELETED); setCurrentOutMessage(NULL); disableFlag(getClientFlags(),E_CF_NM_SENDING); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::unpack( TNL::BitStream *bstream,float sendersOneWayTime ) { IMessages *mInterface = getNetInterface()->getMessagesInterface(); TNL::BitSet32 readFlags=0; enableFlag(readFlags,E_MRF_UPDATE_BY_GHOST); disableFlag(readFlags,E_MRF_READ_SRC_USER_ID); enableFlag(readFlags,E_MRF_READ_TARGET_USER_ID); xMessage *msg = mInterface->readFromStream(bstream,readFlags); if (msg) { xDistributedClient *client = static_cast<xDistributedClient*>(getOwnerConnection()->resolveGhostParent(getLastUpdater())); if (client) { msg->setSrcUser(client->getUserID()); msg->setClientSource(client); enableFlag(msg->getFlags(),E_MF_NEW); enableFlag(msg->getFlags(),E_MF_OUTGOING); mInterface->getMessages()->push_back(msg); xDistributedSession *session = NULL; session = getNetInterface()->getSessionInterface()->get(msg->getClientSource()->getSessionID()); if (!session) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MESSAGES,"no session object"); } ////////////////////////////////////////////////////////////////////////// int numUsers = session->getNumUsers() -1; if (isFlagOn(msg->getFlags(),E_MF_SEND_TO_ALL)) { if (msg->getIgnoreSessionMaster() && client->getUserID() !=session->getUserID() ) { numUsers--; } /* if (client->getUserID()) { } */ }else { // xDistributedClient *dstclient = (xDistributedClient*)client->getOwnerConnection()->resolveGhostParent(msg->getDstUser()); xDistributedClient *dstclient = static_cast<xDistributedClient*>(getNetInterface()->getDistObjectInterface()->getByUserID(msg->getDstUser(),E_DC_BTYPE_CLIENT)); //TNL::logprintf("server msg received from user : %d| to %d ",client->getUserID(),msg->getClientSource()->getOwnerConnection()->getGhostIndex(dstclient),msg->getDstUser()); numUsers = 1; } msg->setNumUsers(numUsers); //TNL::logprintf("server msg received from user : %d,num users : %d | dst :%d",client->getUserID(),numUsers,msg->getDstUser()); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL::U32 xDistributedClient::packUpdate(TNL::GhostConnection *connection, TNL::U32 updateMask, TNL::BitStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); IMessages *mInterface = netInterface->getMessagesInterface(); ISession *sInterface = netInterface->getSessionInterface(); if (netInterface) { //server side only : if (netInterface->IsServer()) { //the first time ? : we write out all necessary attributes for the client : if(stream->writeFlag(updateMask & InitialMask)) { if(stream->writeFlag(true)) { Parent::packUpdate(connection,updateMask,stream); //write out users local address string : stream->writeString(getLocalAddress().getString()); stream->writeString(getUserName().getString()); } } ////////////////////////////////////////////////////////////////////////// if(stream->writeFlag(updateMask & NameMask)) { stream->writeString(getUserName().getString()); } ////////////////////////////////////////////////////////////////////////// xMessage*msg = getCurrentMessage(); xDistributedSession *session = NULL; session = msg ? getNetInterface()->getSessionInterface()->get(msg->getClientSource()->getSessionID()) : NULL; if (msg && !session) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MESSAGES,"no session object"); stream->writeFlag(false); enableFlag(msg->getFlags(),E_MF_SENT); enableFlag(msg->getFlags(),E_MF_DELETED); setCurrentOutMessage(NULL); return 0; } if (msg) { vtConnection *con = (vtConnection*)connection; //int ghostIndexFrom = con->getGhostIndex( msg->getClientSource() ); int ignore = msg->getIgnoreSessionMaster(); if (msg->getClientSource()->getOwnerConnection() == connection) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MESSAGES,"going to msg source :%d !",getUserID()); stream->writeFlag(false); return 0; } if (ignore && session && con->getUserID() == session->getUserID()) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MESSAGES,"going to session master :%d !",getUserID()); stream->writeFlag(false); return 0; } if (!isFlagOn(msg->getFlags(),E_MF_SEND_TO_ALL)) { IDistributedObjects *doInterface = netInterface->getDistObjectInterface(); xDistributedClient *dstClient = static_cast<xDistributedClient*>(doInterface->getByUserID(msg->getDstUser(),E_DC_BTYPE_CLIENT)); if (con->getUserID() != msg->getDstUser() ) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MESSAGES,"wrong destination :%d !",con->getUserID()); stream->writeFlag(false); return 0; } } stream->writeFlag(true); TNL::BitSet32 writeFlags=0; enableFlag(writeFlags,E_MWF_UPDATE_GHOST); disableFlag(writeFlags,E_MWF_SEND_TARGET_USER_ID); enableFlag(writeFlags,E_MWF_SEND_SRC_USER_ID); mInterface->writeToStream(msg,stream,writeFlags); //TNL::logprintf("msg stats : sendCount %d , numUsers %d",msg->getSendCount() , msg->getNumUsers() ); if (msg->getSendCount() == msg->getNumUsers() ) { enableFlag(msg->getFlags(),E_MF_SENT); enableFlag(msg->getFlags(),E_MF_DELETED); setCurrentOutMessage(NULL); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MESSAGES,"message complete"); } }else{ stream->writeFlag(false); } } } return 0; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::unpackUpdate(TNL::GhostConnection *connection, TNL::BitStream *stream) { xNetInterface *netInterface = (xNetInterface*) connection->getInterface(); vtConnection *vconnection = (vtConnection*)connection; if (netInterface) { //client side only : if (!netInterface->IsServer()) { ////////////////////////////////////////////////////////////////////////// //initial update ? if(stream->readFlag()) { if(stream->readFlag()) { Parent::unpackUpdate(connection,stream); char localAddress[256];stream->readString(localAddress); // retrieve the local address char userName[256];stream->readString(userName); // retrieve the user name setServerID(connection->getGhostIndex((NetObject*)this)); setObjectFlags(E_DO_CREATION_CREATED); setLocalAddress(localAddress); vtConnection *con = (vtConnection*)connection; setOwnerConnection(con); if (con->getUserID() == getUserID()) enableFlag(getClientFlags(),E_CF_ADDED); else enableFlag(getClientFlags(),E_CF_ADDING); setUserName(userName); } } ////////////////////////////////////////////////////////////////////////// if(stream->readFlag()) { char oName[256];stream->readString(oName); // retrieve objects name : setUserName(oName); setUserFlags(USERNAME_CHANGED); xLogger::xLog(XL_START,ELOGTRACE,E_LI_CLIENT,"name changed"); } ////////////////////////////////////////////////////////////////////////// bool msgRecieved = stream->readFlag(); if (msgRecieved) { IMessages *mInterface = getNetInterface()->getMessagesInterface(); TNL::BitSet32 readFlags=0; enableFlag(readFlags,E_MRF_SERVER_UPDATE); disableFlag(readFlags,E_MRF_READ_TARGET_USER_ID); enableFlag(readFlags,E_MRF_READ_SRC_USER_ID); xMessage *msg = mInterface->readFromStream(stream,readFlags); if (msg) { enableFlag(msg->getFlags(),E_MF_INCOMING); enableFlag(msg->getFlags(),E_MF_NEW); enableFlag(msg->getFlags(),E_MF_FINISH); msg->setMessageID(messageINCounter); messageINCounter++; mInterface->getMessages()->push_back(msg); //xDistributedObject *dobj = static_cast<xDistributedObject*>(getNetInterface()->getConnection()->(msg->getSrcUser())); //TNL::logprintf("msg by %d",dobj->getUserID()); } } } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::calculateUpdateBits() { IMessages *mInterface = getNetInterface()->getMessagesInterface(); xMessage *msg = getCurrentMessage(); getUpdateBits().clear(); if (msg && isFlagOn(msg->getFlags(),E_MF_NEW) && !isFlagOn(msg->getFlags(),E_MF_DELETED) ) { getUpdateBits().set(BIT(1),true); //&& (msg->getLifeTime() < mInterface->getMessageTimeout()) /*int index = 1 ; for (int i =0 ; msg->getParameters().size() ; i++) { xDistributedProperty *prop = msg->getParameters().at(i); getUpdateBits().set(BIT(index),prop->getFlags() & E_DP_NEEDS_SEND ); }*/ xDistributedPropertyArrayIterator begin = msg->getParameters().begin(); xDistributedPropertyArrayIterator end = msg->getParameters().end(); int index = 2 ; while (begin!=end) { xDistributedProperty *prop = *begin; if (prop==NULL) { int op2 = 2; } getUpdateBits().set(BIT(index),prop->getFlags() & E_DP_NEEDS_SEND ); index++; begin++; } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_NETOBJECT_RPC(xDistributedClient,rpcSetName, (TNL::StringPtr name),(name), TNL::NetClassGroupGameMask, TNL::RPCGuaranteedOrdered,TNL::RPCToGhostParent, 0) { setUserName(name); setMaskBits(NameMask); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::onGhostRemove() { xNetInterface *netInterface = getNetInterface(); if (!netInterface) { return; } // if (netInterface->IsServer()) // { xLogger::xLog(XL_START,ELOGINFO,E_LI_CLIENT,"Remove clients ghost %d",getUserID()); // } netInterface->removeClient(getUserID()); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::writeControlState(TNL::BitStream *stream) { stream->writeFlag(true); stream->writeRangedU32(10, 0, 63); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::readControlState(TNL::BitStream * bstream) { bstream->readFlag(); U32 count = bstream->readRangedU32(0, 63); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::destroy() { Parent::destroy(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedClient::xDistributedClient() : xDistributedObject() { m_DistributedClass=NULL; m_EntityID = 0; mClientFlags=0; mCurrentMessage = NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedClient::~xDistributedClient() { destroy(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::performScopeQuery(TNL::GhostConnection *connection) { xNetInterface *netInterface = getNetInterface(); if (!netInterface) { return; } xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); if (!distObjects) { return; } xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin != end) { xDistributedObject*dobject = *begin; if (dobject) { vtConnection *con =(vtConnection*)connection; int conUID = ((vtConnection*)connection)->getUserID(); int conUIDT = dobject->getUserID(); int thisID = getSessionID(); int targetID = dobject->getSessionID(); if (dobject->getDistributedClass()->getEnitityType() == E_DC_BTYPE_3D_ENTITY ) { if (getSessionID() == dobject->getSessionID()) { connection->objectInScope((TNL::NetObject*) dobject ); } } if (dobject->getDistributedClass()->getEnitityType() == E_DC_BTYPE_SESSION ) { connection->objectInScope((TNL::NetObject*) dobject ); } if (conUID == conUIDT) { int op = 0; connection->objectInScope((TNL::NetObject*) dobject ); begin++; continue; } if (getSessionID() >1 && dobject->getSessionID() >1 && (getSessionID() == dobject->getSessionID())) { connection->objectInScope((TNL::NetObject*) dobject ); }else { //connection->objectInScope((TNL::NetObject*) dobject ); int op2 = 2; op2++; } } begin++; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedClient::onGhostAvailable(TNL::GhostConnection *theConnection) { xNetInterface *netInterface = (xNetInterface*) theConnection->getInterface(); if (netInterface) { if (netInterface->IsServer()) { if (getServerID()==-1) { setServerID(theConnection->getGhostIndex(this)); xLogger::xLog(XL_START,ELOGTRACE,E_LI_CLIENT,"Server id %d",getServerID()); } } } if (netInterface->IsServer()) { //setServerID(theConnection->getGhostIndex((TNL::NetObject*)this)); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedClient::onGhostAdd(TNL::GhostConnection *theConnection) { xNetInterface *netInterface = (xNetInterface*) theConnection->getInterface(); vtConnection *con = (vtConnection*)theConnection; if (netInterface) { if (!netInterface->IsServer()) { xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); enableFlag(getClientFlags(),E_CF_ADDING); distObjects->push_back(this); setNetInterface(netInterface); if ( con->getUserID() == getUserID() ) { netInterface->setMyClient(this); } int sessionID = getSessionID(); ISession *sInterface = netInterface->getSessionInterface(); xDistributedSession *session = sInterface->get(sessionID); if (session) { session->addUser(this); enableFlag(getClientFlags(),E_CF_SESSION_JOINED); } }else{ setServerID(theConnection->getGhostIndex(this)); TNL::logprintf("on add ServerID %d | Name : %s",getServerID(),GetName().getString()); } } return true; } <file_sep>// vtAgeiaInterfaceEditor.h : main header file for the EDITOR DLL // #pragma once #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols class vtAgeiaInterfaceEditorDlg; class vtAgeiaInterfaceToolbarDlg; extern vtAgeiaInterfaceEditorDlg* g_Editor; extern vtAgeiaInterfaceToolbarDlg* g_Toolbar; //plugin interface for communication with Virtools Dev extern PluginInterface* s_Plugininterface; ///////////////////////////////////////////////////////////////////////////// // CEditorApp // See Editor.cpp for the implementation of this class // #include "PhysicManager.h" class vtAgeiaInterfaceEditorApp : public CWinApp { protected: void InitImageList(); void DeleteImageList(); CImageList m_ImageList; public: vtAgeiaInterfaceEditorApp(); CKContext *mContext; PhysicManager *pMan; PhysicManager *getPMan(){return pMan;} CKContext *getContext(){return mContext;} // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(vtAgeiaInterfaceCEditorApp) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL //{{AFX_MSG(vtAgeiaInterfaceCEditorApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorJD6SetSoftLimitDecl(); CKERROR CreateJD6SetSoftLimitProto(CKBehaviorPrototype **pproto); int JD6SetSoftLimit(const CKBehaviorContext& behcontext); CKERROR JD6SetSoftLimitCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_BodyA=0, bbI_BodyB, bbI_Anchor, bbI_AnchorRef, bbI_Axis, bbI_AxisRef }; //************************************ // Method: FillBehaviorJD6SetSoftLimitDecl // FullName: FillBehaviorJD6SetSoftLimitDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorJD6SetSoftLimitDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6SetSoftLimit"); od->SetCategory("Physic/D6"); od->SetDescription("Sets the soft limits in a D6 joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x536d5df9,0x4e5b275c)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJD6SetSoftLimitProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreateJD6SetSoftLimitProto // FullName: CreateJD6SetSoftLimitProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreateJD6SetSoftLimitProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6SetSoftLimit"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PJD6SetSoftLimit <br> PJD6SetSoftLimit is categorized in \ref D6 <br> <br>See <A HREF="PJD6.cmo">PJD6.cmo</A>. <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies D6 joint limits. <br> <br> <h3>Technical Information</h3> \image html PJD6SetSoftLimit.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Body B: </SPAN>The second body to identfy the joint. <BR> <BR> <SPAN CLASS="pin">Limit Axis: </SPAN>The target limit axis. See #D6LimitAxis. <BR> <SPAN CLASS="pin">Soft Limit: </SPAN>The new limit. See #pJD6SoftLimit. <BR> <BR> <hr> See \ref D6AngularLimitGuide "Angular Limits"<br> See \ref D6LinearLimitGuide "Linear Limits"<br> */ proto->SetBehaviorCallbackFct( JD6SetSoftLimitCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Limit Axis",VTE_JOINT_LIMIT_AXIS,0); proto->DeclareInParameter("Soft Limit",VTS_JOINT_SLIMIT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(JD6SetSoftLimit); *pproto = proto; return CK_OK; } //************************************ // Method: JD6SetSoftLimit // FullName: JD6SetSoftLimit // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int JD6SetSoftLimit(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); if(bodyA || bodyB) { pJointD6 *joint =static_cast<pJointD6*>(worldA->getJoint(target,targetB,JT_D6)); D6LimitAxis limitAxis = GetInputParameterValue<D6LimitAxis>(beh,1); pJD6SoftLimit softLimit; CKParameter* pout = beh->GetInputParameter(2)->GetRealSource(); CK_ID* ids = (CK_ID*)pout->GetReadDataPtr(); float damping,spring,value,restitution; pout = (CKParameterOut*)ctx->GetObject(ids[0]); pout->GetValue(&damping); pout = (CKParameterOut*)ctx->GetObject(ids[1]); pout->GetValue(&spring); pout = (CKParameterOut*)ctx->GetObject(ids[2]); pout->GetValue(&value); pout = (CKParameterOut*)ctx->GetObject(ids[3]); pout->GetValue(&restitution); softLimit.damping = damping; softLimit.spring = spring; softLimit.value = value; softLimit.restitution = restitution; if (joint) { switch(limitAxis) { case D6LA_Linear: joint->setLinearLimit(softLimit); break; case D6LA_Swing1: joint->setSwing1Limit(softLimit); break; case D6LA_Swing2: joint->setSwing2Limit(softLimit); break; case D6LA_TwistHigh: joint->setTwistHighLimit(softLimit); break; case D6LA_TwistLow: joint->setTwistLowLimit(softLimit); break; } } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: JD6SetSoftLimitCB // FullName: JD6SetSoftLimitCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR JD6SetSoftLimitCB(const CKBehaviorContext& behcontext) { return CKBR_OK; } <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SetAsActiveCamera // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorSetAsActiveCameraDecl(); CKERROR CreateSetAsActiveCameraProto(CKBehaviorPrototype **pproto); int SetAsActiveCamera(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSetAsActiveCameraDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Set As Active Camera"); od->SetDescription("Tells the camera to be the active one."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> This building block enables you to switch dynamically between cameras.<BR> See Also: 'Get Current Camera'.<BR> */ od->SetCategory("Cameras/Montage"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x368f0ab1,0x2d8957e4)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetAsActiveCameraProto); od->SetCompatibleClassId(CKCID_CAMERA); return od; } CKERROR CreateSetAsActiveCameraProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set As Active Camera"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetAsActiveCamera); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int SetAsActiveCamera(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKCamera *cam = (CKCamera *) beh->GetTarget(); if( !cam ) return CKBR_OWNERERROR; // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); if(behcontext.CurrentRenderContext) behcontext.CurrentRenderContext->AttachViewpointToCamera( cam ); return CKBR_OK; } <file_sep>/* * Tcp4u v 3.31 Last Revision 27/02/1998 3.30 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: tn_proto.c * Purpose: telnet based-protocol transactions * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" /* ------------------------------------------------------------------------- */ /* This function does the dirty job of any protocol a la telnet */ /* it sends an order accepting variable length parameter, then waits for the */ /* response. The response is compared with an array if strings passed by the */ /* calling function. The result is the matching integer if any or */ /* TN_UNEXPECTED */ /* ------------------------------------------------------------------------- */ int API4U TnProtoExchange (SOCKET s, LPCSTR szCommande, LPSTR szResponse, UINT uBufSize, TNPROTOEXCHG_CBK TnProtoRecv, struct S_TnProto far *tTranslation, int nTabSize, BOOL bCaseCmp, UINT uTimeout, HFILE hLogFile) { int Rc; int Ark; int (far * fCompare) (LPCSTR, LPCSTR, size_t); #define XX_RETURN(x) { \ Tcp4uLog (LOG4U_EXIT, "TnReadAnswerCode: return code %d", x); \ return (x); } Tcp4uLog (LOG4U_PROC, "TnProtoExchange"); if (szCommande != NULL) { Rc = TnSend (s, szCommande, FALSE, hLogFile); if (Rc != TN_SUCCESS) XX_RETURN (Rc); } /* waits for answer. NOte the final test */ Rc = TnProtoRecv (s, szResponse, uBufSize, uTimeout, hLogFile); if (Rc<TN_SUCCESS) XX_RETURN (Rc); /* choose the function for string compare */ fCompare = bCaseCmp ? strncmp : Tcp4uStrncasecmp; /* translate the code */ for ( Ark=0 ; Ark<nTabSize && tTranslation[Ark].szString!=NULL; Ark++) { if (fCompare (szResponse, tTranslation[Ark].szString, Strlen (tTranslation[Ark].szString)) == 0) XX_RETURN (tTranslation[Ark].iCode); } XX_RETURN (TN_UNEXPECTED); } /* TnProtoExchange */ <file_sep>#include "StdAfx.h" #include "pGearbox.h" #include "vtPhysXAll.h" #include "pVehicleAll.h" #include <xDebugTools.h> #define DEF_SIZE .25 #define DEF_MAXRPM 5000 #define DEF_MAXPOWER 100 #define DEF_FRICTION 0 #define DEF_MAXTORQUE 340 // ~ F1 Jos Verstappen #define DEF_TORQUE 100 // In case no curve is present #define USE_HARD_REVLIMIT float pGearBox::GetInertiaForWheel(pWheel2 *w) // Return effective inertia as seen in the perspective of wheel 'w' // Takes into account any clutch effects { float totalInertia; float inertiaBehindClutch; float NtfSquared,NfSquared; //rfloat rotationA; pWheel *wheel; int i; // Calculate total ratio multiplier; note the multipliers are squared, // and not just a multiplier for the inertia. See Gillespie's book, // 'Fundamentals of Vehicle Dynamics', page 33. NtfSquared=gearRatio[curGear]*endRatio; NtfSquared*=NtfSquared; /* // Calculate total inertia that is BEHIND the clutch NfSquared=endRatio*endRatio; inertiaBehindClutch=gearInertia[curGear]*NtfSquared+inertiaDriveShaft*NfSquared; /* // Add inertia of attached and powered wheels // This is a constant, so it should be cached actually (except // when a wheel breaks off) for(i=0;i<car->GetWheels();i++) { wheel=car->GetWheel(i); if(wheel->IsPowered()&&wheel->IsAttached()) inertiaBehindClutch+=wheel->GetRotationalInertia()->x; } // Add the engine's inertia based on how far the clutch is engaged totalInertia=inertiaBehindClutch+clutch*inertiaEngine*NtfSquared;*/ return totalInertia; } float pGearBox::GetTorqueForWheel(pWheel2 *w) // Return effective torque for wheel 'w' // Takes into account any clutch effects { float clutch =car->getDriveLine()->GetClutchApplication(); float torque = car->getDifferential(0)->GetTorqueOut(w->differentialSide); endRatio = car->getEngine()->GetCumulativeRatio(); //car->getDriveLine()-> //qdbg("clutch=%f, T=%f, ratio=%f\n",clutch,torque,gearRatio[curGear]*endRatio); return clutch*torque*gearRatio[curGear]*endRatio; } void pGearBox::SetGear(int gear) { curGear=gear; float cRatio = gearRatio[curGear]; float cInertia = gearInertia[curGear]; SetRatio(gearRatio[curGear]); SetInertia(gearInertia[curGear]); car->PreCalcDriveLine(); } void pGearBox::CalcForces() { } void pGearBox::Integrate() // Based on current input values, adjust the engine { int t; bool ac=true;// RMGR->IsEnabled(RManager::ASSIST_AUTOCLUTCH); pDriveLineComp::Integrate(); // The shifting process if(autoShiftStart) { t=GetPMan()->GetContext()->GetTimeManager()->GetAbsoluteTime()-autoShiftStart; if(ac){ car->getDriveLine()->EnableAutoClutch(); } // We are in a shifting operation if(curGear!=futureGear) { // We are in the pre-shift phase if(t>=timeToDeclutch) { // Declutch is ready, change gear SetGear(futureGear); // Trigger gear shift sample if(ac && (car->_currentStatus & VS_IsAccelerated) ) car->getDriveLine()->SetClutchApplication(1.0f); } else { // Change clutch if(ac && (car->_currentStatus & VS_IsAccelerated) ) car->getDriveLine()->SetClutchApplication((t*1000/timeToDeclutch)/1000.0f); } } else { // We are in the post-shift phase if(t>=timeToClutch+timeToDeclutch) { // Clutch is ready, end shifting process // Conclude the shifting process autoShiftStart=0; if(ac) { car->getDriveLine()->SetClutchApplication(0.0f); car->getDriveLine()->DisableAutoClutch(); } } else { // Change clutch if(ac && (car->_currentStatus & VS_IsAccelerated)) car->getDriveLine()->SetClutchApplication(((t-timeToClutch)*1000/timeToDeclutch)/1000.0f); } } } } void pGearBox::processFutureGear() { //qdbg("pGearBox:OnGfxFrame()\n"); if(autoShiftStart==0) { // No shift in progress; check shift commands from the controllers if(car->_cShiftStateUp) { //qdbg("Shift Up!\n"); if(curGear<gears) { autoShiftStart=GetPMan()->GetContext()->GetTimeManager()->GetAbsoluteTime(); switch(curGear) { case 0: futureGear=2; break; // From neutral to 1st case 1: futureGear=0; break; // From reverse to neutral default: futureGear=curGear+1; break; } } }else if(car->_cShiftStateDown) { autoShiftStart=GetPMan()->GetContext()->GetTimeManager()->GetAbsoluteTime(); if(curGear!=1) // Not in reverse? { switch(curGear) { case 0: futureGear=1; break; // From neutral to reverse case 2: futureGear=0; break; // From 1st to neutral default: futureGear=curGear-1; break; } } //qdbg("Switch back to futureGear=%d\n",futureGear); } } } void pGearBox::setToDefault() { gears = 6; gearRatio[0]=1.0f; gearInertia[0]=0.0f; gearRatio[1]=-3.59f; gearInertia[1]=0.9f; gearRatio[2]=3.61f; gearInertia[2]=0.13f; gearRatio[3]=4.36f; gearInertia[3]=0.4f; gearRatio[4]=1.69f; gearInertia[4]=0.07f; gearRatio[5]=1.29f; gearInertia[5]=0.05f; gearRatio[6]=1.03f; gearInertia[6]=0.04f; gearRatios.insert(0,-3.61f); gearTensors.insert(0,0.13f); gearRatios.insert(1,3.61f); gearTensors.insert(1,0.13f); gearRatios.insert(2,2.36f); gearTensors.insert(2,0.09f); gearRatios.insert(3,1.69f); gearTensors.insert(3,0.07f); gearRatios.insert(4,1.29f); gearTensors.insert(4,0.05f); gearRatios.insert(5,1.03f); gearTensors.insert(5,0.04f); autoShiftStart = 0; timeToClutch=300; timeToDeclutch=300.0f; shiftDownRPM= 1110.0f; shiftUpRPM=5500.0f; futureGear = 0; } pGearBox::pGearBox(pVehicle *_car) : pDriveLineComp() { SetName("gearbox"); car=_car; Reset(); } pGearBox::~pGearBox() { } void pGearBox::Reset() // Reset all variables { int i; flags=0; timeToDeclutch=timeToClutch=0; autoShiftStart=0; futureGear=0; for(i=0;i<MAX_GEAR;i++) { gearRatio[i]=1; gearInertia[i]=0; } curGear=0; // Neutral gears=4; } XString pGearBox::GetGearName(int gear) // Returns a name for a gear // Convenience function. { switch(gear) { case 0: return "N"; case 1: return "R"; case 2: return "1st"; case 3: return "2nd"; case 4: return "3rd"; case 5: return "4th"; case 6: return "5th"; case 7: return "6th"; case 8: return "7th"; case 9: return "8th"; default: return "G??"; } } void pGearBox::Paint() { } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "tinyxml.h" #include <xDebugTools.h> NxMaterialDesc* pFactory::createMaterialFromEntity(CKBeObject*object) { ////////////////////////////////////////////////////////////////////////// //sanity checks : if (!object ) { return NULL; } if (!object->HasAttribute(GetPMan()->att_surface_props)) { return NULL; } ////////////////////////////////////////////////////////////////////////// CKParameterManager *pm = object->GetCKContext()->GetParameterManager(); int parameterType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); NxMaterialDesc *result = new NxMaterialDesc(); using namespace vtTools::AttributeTools; XString nodeName; int enumID = GetValueFromAttribute<int>(object,GetPMan()->att_surface_props,0); if (enumID==0) { goto takeFromAttribute; } CKEnumStruct *enumStruct = pm->GetEnumDescByType(parameterType); if ( enumStruct ) { for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) { if(i == enumID) { nodeName = enumStruct->GetEnumDescription(i); if (nodeName.Length()) { result = createMaterialFromXML(nodeName.CStr(),getDefaultDocument()); if (result) { return result; } } } } } takeFromAttribute : { float dynamicFriction = GetValueFromAttribute<float>(object,GetPMan()->att_surface_props,1); if (dynamicFriction >=0.0f) { result->dynamicFriction =dynamicFriction; } float statFriction = GetValueFromAttribute<float>(object,GetPMan()->att_surface_props,2); if (statFriction>=0.0f) { result->staticFriction=statFriction; } float rest = GetValueFromAttribute<float>(object,GetPMan()->att_surface_props,3); if (rest>=0.0f) { result->restitution=rest; } float dynamicFrictionV = GetValueFromAttribute<float>(object,GetPMan()->att_surface_props,4); if (dynamicFrictionV >=0.0f) { result->dynamicFrictionV =dynamicFrictionV; } float staticFrictionV = GetValueFromAttribute<float>(object,GetPMan()->att_surface_props,5); if (staticFrictionV>=0.0f) { result->staticFriction=staticFrictionV; } VxVector anis = GetValueFromAttribute<VxVector>(object,GetPMan()->att_surface_props,6); if (anis.Magnitude()>=0.01f) { result->dirOfAnisotropy=pMath::getFrom(anis); } int fMode = GetValueFromAttribute<int>(object,GetPMan()->att_surface_props,7); if (fMode !=-1) { result->frictionCombineMode=(NxCombineMode)fMode; } int rMode = GetValueFromAttribute<int>(object,GetPMan()->att_surface_props,8); if (rMode !=-1) { result->restitutionCombineMode=(NxCombineMode)rMode; } return result; } return result; } bool pFactory::copyTo(pMaterial&dst,NxMaterial*src) { if (!src) { return false; } dst.xmlLinkID = (int)src->userData; dst.dirOfAnisotropy = getFrom(src->getDirOfAnisotropy()); dst.dynamicFriction = src->getDynamicFriction(); dst.dynamicFrictionV = src->getDynamicFrictionV(); dst.staticFriction = src->getStaticFriction(); dst.staticFrictionV = src->getStaticFrictionV(); dst.frictionCombineMode = (CombineMode)src->getFrictionCombineMode(); dst.restitutionCombineMode = (CombineMode)src->getRestitutionCombineMode(); dst.restitution = src->getRestitution(); dst.flags = src->getFlags(); dst.setNxMaterialID(src->getMaterialIndex()); return false; } bool pFactory::copyTo(NxMaterialDesc &dst, const pMaterial &src) { dst.dirOfAnisotropy = getFrom(src.dirOfAnisotropy); dst.dynamicFriction = src.dynamicFriction; dst.dynamicFrictionV = src.dynamicFrictionV; dst.staticFriction = src.staticFriction; dst.staticFrictionV = src.staticFrictionV; dst.frictionCombineMode = (NxCombineMode)src.frictionCombineMode; dst.restitutionCombineMode = (NxCombineMode)src.restitutionCombineMode; dst.restitution = src.restitution; dst.flags = src.flags; return true; } bool pFactory::copyTo(pMaterial& dst,CKParameter*src) { if (!src)return false; using namespace vtTools::ParameterTools; dst.xmlLinkID = GetValueFromParameterStruct<int>(src,E_MS_XML_TYPE); dst.dirOfAnisotropy = GetValueFromParameterStruct<VxVector>(src,E_MS_ANIS); dst.dynamicFriction = GetValueFromParameterStruct<float>(src,E_MS_DFRICTION); dst.dynamicFrictionV = GetValueFromParameterStruct<float>(src,E_MS_DFRICTIONV); dst.staticFriction = GetValueFromParameterStruct<float>(src,E_MS_SFRICTION); dst.staticFrictionV = GetValueFromParameterStruct<float>(src,E_MS_SFRICTIONV); dst.restitution= GetValueFromParameterStruct<float>(src,E_MS_RESTITUTION); dst.restitutionCombineMode= (CombineMode)GetValueFromParameterStruct<int>(src,E_MS_RCMODE); dst.frictionCombineMode= (CombineMode)GetValueFromParameterStruct<int>(src,E_MS_FCMODE); dst.flags= GetValueFromParameterStruct<int>(src,E_MS_FLAGS); return true; } bool pFactory::findSettings(pMaterial& dst,CKBeObject*src) { if (!src)return false; CKParameterOut *parMaterial = src->GetAttributeParameter(GetPMan()->att_surface_props); if (parMaterial){ pFactory::Instance()->copyTo(dst,(CKParameter*)parMaterial); goto EVALUATE; } CK3dEntity *ent3D = static_cast<CK3dEntity*>(src); if (ent3D) { CKMesh *mesh = ent3D->GetCurrentMesh(); if (mesh) { parMaterial = mesh->GetAttributeParameter(GetPMan()->att_surface_props); if (!parMaterial) { for (int i = 0 ; i < mesh->GetMaterialCount() ; i++) { CKMaterial *entMaterial = mesh->GetMaterial(i); parMaterial = entMaterial->GetAttributeParameter(GetPMan()->att_surface_props); if (parMaterial) { break; } } } } } if (!parMaterial) return false; ////////////////////////////////////////////////////////////////////////// //copy parameter content to c++ pFactory::Instance()->copyTo(dst,(CKParameter*)parMaterial); /////////////////////////////////////////////////////////////////////////// // // Evaluate from XML // EVALUATE: if ( dst.xmlLinkID !=0 ) { XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,dst.xmlLinkID); bool err = loadFrom(dst,nodeName.Str(),getDefaultDocument()); if (err) { copyTo(parMaterial,dst); return true; } } return false; } bool pFactory::copyTo(CKParameterOut*dst,const pMaterial&src) { if (!dst)return false; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// //@todo : find the xml name ! SetParameterStructureValue<int>(dst,E_MS_XML_TYPE,src.xmlLinkID,false); SetParameterStructureValue<float>(dst,E_MS_DFRICTION,src.dynamicFriction,false); SetParameterStructureValue<float>(dst,E_MS_DFRICTIONV,src.dynamicFrictionV,false); SetParameterStructureValue<float>(dst,E_MS_SFRICTION,src.staticFriction,false); SetParameterStructureValue<float>(dst,E_MS_SFRICTIONV,src.staticFrictionV,false); SetParameterStructureValue<int>(dst,E_MS_FCMODE,src.frictionCombineMode,false); SetParameterStructureValue<int>(dst,E_MS_RCMODE,src.restitutionCombineMode,false); SetParameterStructureValue<float>(dst,E_MS_RESTITUTION,src.restitution,false); SetParameterStructureValue<int>(dst,E_MS_XML_TYPE,src.xmlLinkID,false); SetParameterStructureValue<int>(dst,E_MS_FLAGS,src.flags,false); SetParameterStructureValue<VxVector>(dst,E_MS_ANIS,src.dirOfAnisotropy,false); } pMaterial pFactory::loadMaterial(const char* nodeName,int& error) { pMaterial result; if(loadFrom(result,nodeName,getDefaultDocument())) { error = 0; }else error =1; return result; } bool pFactory::loadMaterial(pMaterial&dst,const char* nodeName/* = */) { return loadFrom(dst,nodeName,getDefaultDocument()); } bool pFactory::loadFrom(pMaterial &dst,const char *nodeName,const TiXmlDocument *doc) { /************************************************************************/ /* try to load settings from xml : */ /************************************************************************/ if ( strlen(nodeName) && doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "material" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),nodeName ) ) { for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) { if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) { const TiXmlElement *sube = (const TiXmlElement*)node; double v; ////////////////////////////////////////////////////////////////////////// int res = sube->QueryDoubleAttribute("DynamicFriction",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.dynamicFriction = (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("StaticFriction",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ dst.staticFriction= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("Restitution",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ dst.restitution= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ dst.dynamicFrictionV= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("StaticFrictionV",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ dst.staticFrictionV= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// const char* dirOfAnisotropy = NULL; dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); if (dirOfAnisotropy && strlen(dirOfAnisotropy)) { VxVector vec = _str2Vec(dirOfAnisotropy); dst.dirOfAnisotropy = vec; continue; } const char* flags = NULL; flags = sube->Attribute("Flags"); if (flags && strlen(flags)) { dst.flags = _str2MaterialFlag(flags); continue; } ////////////////////////////////////////////////////////////////////////// const char* FrictionCombineMode = NULL; FrictionCombineMode = sube->Attribute("FrictionCombineMode"); if (FrictionCombineMode && strlen(FrictionCombineMode)) { int fMode = _str2CombineMode(FrictionCombineMode); dst.frictionCombineMode = (CombineMode)fMode; continue; } ////////////////////////////////////////////////////////////////////////// const char* RestitutionCombineMode = NULL; RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); if (RestitutionCombineMode && strlen(RestitutionCombineMode)) { int fMode = _str2CombineMode(RestitutionCombineMode); dst.restitutionCombineMode= (CombineMode)fMode; continue; } } } return true; } } } } } } return false; } NxMaterialDesc*pFactory::createMaterialFromXML(const char* nodeName/* = */,const TiXmlDocument * doc /* = NULL */) { NxMaterialDesc *result = new NxMaterialDesc(); result->setToDefault(); if (doc ==NULL) return result; if (!getFirstDocElement(doc->RootElement())) return result; /************************************************************************/ /* try to load settings from xml : */ /************************************************************************/ if ( strlen(nodeName) && doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "material" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),nodeName ) ) { for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) { if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) { const TiXmlElement *sube = (const TiXmlElement*)node; double v; ////////////////////////////////////////////////////////////////////////// int res = sube->QueryDoubleAttribute("DynamicFriction",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { result->dynamicFriction = (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("StaticFriction",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ result->staticFriction= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("Restitution",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ result->restitution= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ result->dynamicFrictionV= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("StaticFrictionV",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ result->staticFrictionV= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// const char* dirOfAnisotropy = NULL; dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); if (dirOfAnisotropy && strlen(dirOfAnisotropy)) { VxVector vec = _str2Vec(dirOfAnisotropy); if (vec.Magnitude() >0.1f) { result->flags = NX_MF_ANISOTROPIC; result->dirOfAnisotropy = pMath::getFrom(vec); continue; }else { result->dirOfAnisotropy = pMath::getFrom(VxVector(0,0,0)); } //result->setGravity(vec); } ////////////////////////////////////////////////////////////////////////// const char* FrictionCombineMode = NULL; FrictionCombineMode = sube->Attribute("FrictionCombineMode"); if (FrictionCombineMode && strlen(FrictionCombineMode)) { int fMode = _str2CombineMode(FrictionCombineMode); result->frictionCombineMode = (NxCombineMode)fMode; continue; } ////////////////////////////////////////////////////////////////////////// const char* RestitutionCombineMode = NULL; RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); if (RestitutionCombineMode && strlen(RestitutionCombineMode)) { int fMode = _str2CombineMode(RestitutionCombineMode); result->restitutionCombineMode= (NxCombineMode)fMode; continue; } } } return result; } } } } } } return result; }<file_sep>import sys import socket def main(): server = server_create('localhost', 9090) while 1: #accept connections from outside (client, address) = server.accept() msg = message_get(client) if (msg): print "recieved(%s)" % (msg) message_send(client, sys.argv[1]) print "sent(%s)" % (sys.argv[1]) else: break def server_create(host, port): #create an INET, STREAMing socket server = socket.socket( socket.AF_INET, socket.SOCK_STREAM) #bind the socket to a public host, # and a well-known port server.bind((host, port)) #become a server socket server.listen(5) return server ### Common #### MSGLEN = 1024 def message_get(sock): msg = '' while len(msg) < MSGLEN: chunk = sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg return 0 def message_send(sock, message): msgfmt = "%-" + "%ds" % (MSGLEN) msg = msgfmt % (message) totalsent = 0 while totalsent < MSGLEN: sent = sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent return 1 main()<file_sep>#include <StdAfx.h> #include "pCrossTypes.h" #include <StdAfx.h> #include "vtPhysXAll.h" #include "vtStructHelper.h" #include "vtAttributeHelper.h" using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; /************************************************************************/ /* Dominance Setup */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // Dominance help member : // StructurMember dominanceConstraint[] = { STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Dominance 0","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Dominance 1","1.0"), }; ////////////////////////////////////////////////////////////////////////// // // Dominance help member : // StructurMember dominanceItem[] = { STRUCT_ATTRIBUTE(VTE_PHYSIC_DOMINANCE_GROUP,"Dominance Group A","1"), STRUCT_ATTRIBUTE(VTE_PHYSIC_DOMINANCE_GROUP,"Dominance Group B","2"), STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_CONSTRAINT,"Dominance Constraint","1.0,0.0"), }; StructurMember dominanceSetup[] = { STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 1","0"), STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 2","0"), STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 3","0"), STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 4","0"), STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 5","0"), }; //STRUCT_ATTRIBUTE(CKPGUID_2DCURVE,"Settings 5","0"), void PhysicManager::_RegisterWorldParameters() { CKParameterManager *pm = m_Context->GetParameterManager(); CKAttributeManager* attman = m_Context->GetAttributeManager(); CKParameterTypeDesc* param_type = NULL; /************************************************************************/ /* Dominance Structs */ /************************************************************************/ REGISTER_CUSTOM_STRUCT("pWDominanceConstraint",PS_W_DOMINANCE_CONSTRAINT,VTS_PHYSIC_DOMINANCE_CONSTRAINT,dominanceConstraint,true); // Dominance group as user friendly enumeration pm->RegisterNewEnum(VTE_PHYSIC_DOMINANCE_GROUP,"pDominanceGroup","None=0,First=1,Second=2"); param_type=pm->GetParameterTypeDescription(VTE_PHYSIC_DOMINANCE_GROUP); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; //if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; REGISTER_CUSTOM_STRUCT("pDominanceItem",PS_W_DOIMINANCE,VTS_PHYSIC_DOMINANCE_ITEM,dominanceItem,true); REGISTER_CUSTOM_STRUCT("pDominanceSetup",PS_W_DOIMINANCE_SETUP,VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS,dominanceSetup,true); REGISTER_STRUCT_AS_ATTRIBUTE("Dominance Group Setup",PS_W_DOIMINANCE_SETUP,PHYSIC_BODY_CAT,VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS,CKCID_3DENTITY,dominanceSetup,true); /************************************************************************/ /* world */ /************************************************************************/ /*pm->RegisterNewEnum(VTE_PHYSIC_BODY_COLL_GROUP,"pBCollisionsGroup","All=0,MyObstacles=1,MyWheels=2"); param_type=pm->GetParameterTypeDescription(VTE_PHYSIC_BODY_COLL_GROUP); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; */ pm->RegisterNewStructure(VTS_PHYSIC_WORLD_PARAMETER, "pWorldSettings", "Gravity,SkinWith", CKPGUID_VECTOR, CKPGUID_FLOAT ); att_world_object = attman->RegisterNewAttributeType("World",VTS_PHYSIC_WORLD_PARAMETER,CKCID_BEOBJECT); attman->SetAttributeCategory(att_world_object,"Physic"); } <file_sep>swig.exe -c++ -csharp csWindow.i <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPJAddLimitPlaneDecl(); CKERROR CreatePJAddLimitPlaneProto(CKBehaviorPrototype **pproto); int PJAddLimitPlane(const CKBehaviorContext& behcontext); CKERROR PJAddLimitPlaneCB(const CKBehaviorContext& behcontext); enum bbInputs { bI_ObjectB, bI_Type, bI_Res, bI_LPoint, bI_LPointRef, bI_IsOnBodyB, bI_Anchor, bI_AnchorRef, bI_Axis, bI_AxisRef, bI_Coll }; //************************************ // Method: FillBehaviorPJAddLimitPlaneDecl // FullName: FillBehaviorPJAddLimitPlaneDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPJAddLimitPlaneDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJAddLimitPlane"); od->SetCategory("Physic/Joints"); od->SetDescription("Adds a limit plane to a joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x150a1e5a,0xebc0c00)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJAddLimitPlaneProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJAddLimitPlaneProto // FullName: CreatePJAddLimitPlaneProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePJAddLimitPlaneProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJAddLimitPlane"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJAddLimitPlane <br> PJAddLimitPlane is categorized in \ref Joints <br> <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Adds a limit plane. <br> <br>See <A HREF="PJPointInPlane.cmo">PJPointInPlane.cmo</A>. <h3>Technical Information</h3> \image html PJAddLimitPlane.png This building blocks invokes #pJoint::setLimitPoint() and afterwards #pJoint::addLimitPlane() internally. <SPAN CLASS="in">In: </SPAN>triggers the process. <BR> <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <SPAN CLASS="pin">Body B: </SPAN>The second body. Leave blank to create a joint constraint with the world. <BR> <SPAN CLASS="pin">Joint Type:</SPAN> The joint type. This helps the building block to identify a joint constraint. As usual there can be only one joint of the type x between two bodies.<BR> <SPAN CLASS="pin">Restitution:</SPAN> Restitution of the limit plane. </br> - <b>Range:</b> [0,1.0f) - <b>Default:</b> 0.0 <SPAN CLASS="pin">Limit Point:</SPAN>The point specified in global coordinate frame.</br> - <b>Range:</b> [Position Vector) <SPAN CLASS="pin">Limit Point Reference:</SPAN>Reference to transform limit point (local) into world space.</br> <SPAN CLASS="pin">Point is Body B:</SPAN>Set to true if the point is attached to the second actor.Otherwise it is attached to the first.</br> <SPAN CLASS="pin">Point in Plane:</SPAN>Point in the limit plane in global coordinates.</br> - <b>Range:</b> [Position Vector) <SPAN CLASS="pin">Point in Plane Reference:</SPAN>Reference to transform plane "Point in Plane"(local then) into global coordinates.</br> <SPAN CLASS="pin">Normal:</SPAN>Normal for the limit plane in global coordinates.</br> - <b>Range:</b> [Position Vector) <SPAN CLASS="pin">Normal Reference:</SPAN>Reference to transform plane "Normal"(local up then) into global coordinates.</br> <h3>VSL : Creation </h3><br> <SPAN CLASS="NiceCode"> \include pJAddLimitPlane.vsl </SPAN> Is utilizing #pRigidBody #pWorld #PhysicManager #joint::setLimitPoint() #joint::addLimitPlane() */ proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( PJAddLimitPlaneCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Type",VTE_JOINT_TYPE,""); proto->DeclareInParameter("Restitution",CKPGUID_FLOAT,"0.0f"); proto->DeclareInParameter("Limit Point",CKPGUID_VECTOR); proto->DeclareInParameter("Limit Point Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Point Is On Body B",CKPGUID_BOOL,"TRUE"); proto->DeclareInParameter("Point In Plane",CKPGUID_VECTOR); proto->DeclareInParameter("Point In Plane Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Normal",CKPGUID_VECTOR); proto->DeclareInParameter("Normal Reference",CKPGUID_3DENTITY); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PJAddLimitPlane); *pproto = proto; return CK_OK; } //************************************ // Method: PJAddLimitPlane // FullName: PJAddLimitPlane // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJAddLimitPlane(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Revolute)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA && ! worldB ) { return 0; } if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); //anchor : VxVector anchor0 = GetInputParameterValue<VxVector>(beh,bI_LPoint); VxVector anchorOut0 = anchor0; CK3dEntity*anchorReference0 = (CK3dEntity *) beh->GetInputParameterObject(bI_LPointRef); if (anchorReference0) { anchorReference0->Transform(&anchorOut0,&anchor0); } //anchor : VxVector anchor = GetInputParameterValue<VxVector>(beh,bI_Anchor); VxVector anchorOut = anchor; CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); if (anchorReference) { anchorReference->Transform(&anchorOut,&anchor); } //swing axis VxVector Axis = GetInputParameterValue<VxVector>(beh,bI_Axis); VxVector axisOut = Axis; CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); if (axisReference) { VxVector dir,up,right; axisReference->GetOrientation(&dir,&up,&right); axisReference->TransformVector(&axisOut,&up); } ////////////////////////////////////////////////////////////////////////// int type = GetInputParameterValue<int>(beh,bI_Type); int isOnBodyB = GetInputParameterValue<int>(beh,bI_IsOnBodyB); float res = GetInputParameterValue<float>(beh,bI_Res); pJoint*joint = (worldA->getJoint(target,targetB,(JType)type)); if(bodyA || bodyB) { if (joint) { if (XAbs(anchorOut0.SquareMagnitude()) >=0.01f) joint->setLimitPoint(anchorOut0,isOnBodyB); VxVector b = anchorOut; joint->addLimitPlane(axisOut,anchorOut,res); } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: PJAddLimitPlaneCB // FullName: PJAddLimitPlaneCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJAddLimitPlaneCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { /* DWORD twistLimit; beh->GetLocalParameterValue(1,&twistLimit); beh->EnableInputParameter(bbI_HighLimit,twistLimit); beh->EnableInputParameter(bbI_LowLimit,twistLimit); DWORD springSwing; beh->GetLocalParameterValue(0,&springSwing); beh->EnableInputParameter(bbI_Spring,springSwing); DWORD motor; beh->GetLocalParameterValue(2,&motor); beh->EnableInputParameter(bbI_Motor,motor); */ break; } } return CKBR_OK; } <file_sep>/******************************************************************** created: 2007/12/15 created: 15:12:2007 22:33 filename: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\plugins\xUtils\src\xUtils.cpp file path: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\plugins\xUtils\src file base: xUtils file ext: cpp author: <NAME> purpose: *********************************************************************/ #include <pch.h> /// DWORD, #include <tchar.h> #include "xUtils.h" #include "d3d9.h" #include "3d/DXDiagNVUtil.h" //************************************ // Method: GetPhysicalMemoryInMB // FullName: xUtils::system::GetPhysicalMemoryInMB // Access: public // Returns: int // Qualifier: //************************************ int xUtils::system::GetPhysicalMemoryInMB() { DXDiagNVUtil nvutil; nvutil.InitIDxDiagContainer(); float ret = -1; nvutil.GetPhysicalMemoryInMB(&ret); nvutil.FreeIDxDiagContainer(); return static_cast<int>(ret); } //is defined in GetDXVer.cpp : extern HRESULT GetDXVersion( DWORD* pdwDirectXVersion, TCHAR* strDirectXVersion, int cchDirectXVersion ); //************************************ // Method: GetDirectVersion // FullName: xUtils::GetDirectVersion // Access: private static // Returns: void // Qualifier: // Parameter: char*&version // Parameter: int& minor // Description : //************************************ HRESULT xUtils::system::GetDirectVersion(char*&version,DWORD& minor) { HRESULT hr; TCHAR strResult[128]; DWORD dwDirectXVersion = 0; TCHAR strDirectXVersion[10]; hr = GetDXVersion( &minor,strResult, 10 ); version = new char[strlen(strResult)]; strcpy(version,strResult); return hr; //strcpy(version,strDirectXVersion); } int GetPhysicalMemoryInMB() { DXDiagNVUtil nvutil; nvutil.InitIDxDiagContainer(); float ret = -1; nvutil.GetPhysicalMemoryInMB(&ret); nvutil.FreeIDxDiagContainer(); return ret; } <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // AddNodalLink // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "StdAfx.h" #include "virtools/vtcxglobal.h" #include "windows.h" #include "Python.h" #include "vt_python_funcs.h" #include "pyembed.h" #include "InitMan.h" CKObjectDeclaration *FillBehaviorGetNextBBIdDecl(); CKERROR CreateGetNextBBIdProto(CKBehaviorPrototype **); int GetNextBBId(const CKBehaviorContext& behcontext); CKERROR GetNextBBIdCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorGetNextBBIdDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("GetNextBBId"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x572066cc,0x58402b59)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGetNextBBIdProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Python"); return od; } CKERROR CreateGetNextBBIdProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("GetNextBBId"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); //proto->DeclareOutput("Error"); proto->DeclareOutParameter("ck_id",CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( GetNextBBId ); *pproto = proto; return CK_OK; } int GetNextBBId(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; beh->ActivateInput(0,FALSE); int count = beh->GetParent()->GetSubBehaviorLinkCount(); int result = -1; for (int i=0; i<count; i++) { CKBehaviorLink *link = beh->GetParent()->GetSubBehaviorLink(i); if (link->GetInBehaviorIO() == beh->GetOutput(0)) { result = link->GetOutBehaviorIO()->GetOwner()->GetID(); beh->SetOutputParameterValue(0,&result); //threadInfo->targetBeh = link->GetOutBehaviorIO()->GetOwner(); /*int targetInputs = threadInfo->targetBeh->GetInputCount(); if (targetInputs == 1) { //threadInfo->targetInputToActivate = 0; } else { for (int j=0; j<targetInputs; j++) { if (link->GetOutBehaviorIO() == threadInfo->targetBeh->GetInput(j)) { //threadInfo->targetInputToActivate = j; break; } } }*/ break; } } CKBehavior *script = static_cast<CKBehavior*>(ctx->GetObject(result)); if (script) { int bc = script->GetOutputCount(); int bc2 = script->GetInputCount(); } beh->ActivateOutput(0); beh->SetOutputParameterValue(0,&result); return CKBR_OK; } <file_sep>/******************************************************************** created: 2009/02/16 created: 16:2:2009 9:07 filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\ModulePrerequisites.h file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common file base: ModulePrerequisites file ext: h author: <NAME> purpose: Include of all prerequisites *********************************************************************/ #ifndef __PREREQUISITES_ALL_H__ #define __PREREQUISITES_ALL_H__ //################################################################ // // Common forward declarations : // //################################################################ // // Virtools related forward declarations : // #include "Prerequisites_Virtools.h" //################################################################ // // 3th party forward declarations : // // + TinyXML // + NXUStream // #include "Prerequisites_3thParty.h" //################################################################ // // Main library forward declarations : // #include "Prerequisites_PhysX.h" //################################################################ // // Forward declarations for this module itself : // #include "Prerequisites_Module.h" #include "Timing.h" #endif <file_sep>#ifndef __P_GEARBOX_H__ #define __P_GEARBOX_H__ #include "vtPhysXBase.h" #include "XString.h" #include "pDriveline.h" #include "pLinearInterpolation.h" class MODULE_API pGearBox : public pDriveLineComp { public: enum Max { MAX_GEAR=10 // #gears possible }; enum Flags { AUTOMATIC=1 // Auto shifting }; //---------------------------------------------------------------- // // public access // pLinearInterpolation gearRatios; pLinearInterpolation gearTensors; pLinearInterpolation& getGearTensors() { return gearTensors; } void setGearTensors(pLinearInterpolation val) { gearTensors = val; } pLinearInterpolation& getGearRatios(){ return gearRatios; } void setGearRatios(pLinearInterpolation val) { gearRatios = val; } void setToDefault(); int getGears() const { return gears; } void setGears(int val) { gears = val; } float getShiftUpRPM() const { return shiftUpRPM; } void setShiftUpRPM(float val) { shiftUpRPM = val; } float getShiftDownRPM() const { return shiftDownRPM; } void setShiftDownRPM(float val) { shiftDownRPM = val; } int& getFlags(){return flags;}; void setFlags(int val); int getTimeToDeclutch() const { return timeToDeclutch; } void setTimeToDeclutch(int val) { timeToDeclutch = val; } int getTimeToClutch() const { return timeToClutch; } void setTimeToClutch(int val) { timeToClutch = val; } public: // Semi-fixed properties pVehicle *car; // The car to which we belong // Physical attributes int flags; float gearRatio[MAX_GEAR]; int gears; float gearInertia[MAX_GEAR]; // Rotational inertia per gear // Shifting (static) int timeToDeclutch; // Auto-shifting time int timeToClutch; float shiftUpRPM; // Automatic transmissions float shiftDownRPM; // State (dynamic output) int curGear; // Selected gear int autoShiftStart; // Time of auto shift initiation int futureGear; // Gear to shift to public: pGearBox(pVehicle *car); ~pGearBox(); void Reset(); // Reset all vars // Definition /* bool Load(QInfo *info,cstring path=0); bool LoadState(QFile *f); bool SaveState(QFile *f); */ float endRatio; // Final drive ratio // Attribs #ifdef OBS // Engine torque generation float GetMinTorque(float rpm); float GetMaxTorque(float rpm); float GetTorqueAtDifferential(); #endif //float GetEngineInertia(){ return inertiaEngine; } float GetGearInertia(){ return gearInertia[curGear]; } float GetInertiaAtDifferential(); float GetInertiaForWheel(pWheel2 *w); float GetTorqueForWheel(pWheel2 *w); int GetGears(){ return gears; } int GetGear(){ return curGear; } float GetGearRatio(int n); //float GetEndRatio(); void SetGear(int n); XString GetGearName(int gear); bool IsNeutral(){ if(curGear==0)return true; return false; } void processFutureGear(); // Input void SetInput(int ctlThrottle,int ctlClutch); // Graphics void Paint(); // Physics void CalcForces(); void Integrate(); void OnGfxFrame(); }; #endif <file_sep>#ifndef __VT_BASE_MACROS_H__ #define __VT_BASE_MACROS_H__ #include "vtModuleConstants.h" //################################################################ // // Universal macros // #define VTCX_API_ENTRY(F) VTCX_API_PREFIX##F #define VTCX_API_CUSTOM_BB_CATEGORY(F) VTCX_API_PREFIX##F #ifndef XINLINE #define XINLINE inline #endif #endif<file_sep>// racer/engine.h // 30-12-01: Gearbox split from engine into class RGearBox #ifndef __P_ENGINE_H__ #define __P_ENGINE_H__ #include "vtPhysXBase.h" #include "pDriveline.h" #include "pVehicleTypes.h" class RWheel; class MODULE_API pEngine : public pDriveLineComp { public: enum Flags { STALLED=1, // Engine is turned off HAS_STARTER=2, // Start engine present? START_STALLED=4, // When reset, don't autostart engine? AUTOCLUTCH_ACTIVE=8 // Assist on? }; enum Max { MAX_GEAR=10 // #gears possible }; //---------------------------------------------------------------- // // public interface // public: pVehicle *ownerVehicle; // The car to which we belong // Static data float size; VxVector position; float mass; int flags; int& getFlags() { return flags; } void setFlags(int val); // To calculate engine braking float idleThrottle, // Always open by this much 0..1 throttleRange; // Effective throttle range float maxTorque; // Factor for normalize torque curve float maxRPM; // Hard maximum float getMaxTorque() const { return maxTorque; } void setMaxTorque(float val) { maxTorque = val; } float getMaxRPM() const { return maxRPM; } void setMaxRPM(float val) { maxRPM = val; } float getClutch() const { return clutch; } void setClutch(float val) { clutch = val; } int getFrictionMethod() { return FC_GENTA ;} float clutch; // Clutch 0..1 (1=fully locked) //int autoShiftStart; // Time of auto shift initiation //int futureGear; // Gear to shift to //float rotationV; // Engine rotation speed float torqueWheels, // Torque available for the wheels torqueEngine; //---------------------------------------------------------------- // // customizable attributes // float starterTorque; // Torque generated by starter float idleRPM; // RPM when no throttle/friction float forceFeedbackScale; public : float getForceFeedbackScale() const { return forceFeedbackScale; } void setForceFeedbackScale(float val) { forceFeedbackScale = val; } float getStarterTorque() const { return starterTorque; } void setStarterTorque(float val); float getIdleRPM() const { return idleRPM; } void setIdleRPM(float val); float getStallRPM() const { return stallRPM; } void setStallRPM(float val) { stallRPM = val; } float getBrakingCoeff() const { return brakingCoeff; } void setBrakingCoeff(float val); float getFriction() const { return friction; } void setFriction(float val); float getStartRPM() const { return startRPM; } void setStartRPM(float val); float getAutoClutchRPM() const { return autoClutchRPM; } void setAutoClutchRPM(float val) { autoClutchRPM = val; } float stallRPM; // At which point does the engine stall float startRPM; // At which point does it turn on again? float autoClutchRPM; // When to start applying the clutch float friction; // Friction coeff of motor itself float brakingCoeff; //---------------------------------------------------------------- // // unknown // float torqueReaction; // Amount (0..1) at which engine // Dynamic data (some (tEngine) is stored in RDriveLineComp) // torque reaches the body // Physical attributes // Inertia float inertiaEngine, // Engine internal rotation inertiaDriveShaft; // Differential // Gearbox float gearRatio[MAX_GEAR]; int gears; float endRatio; // Final drive ratio float gearInertia[MAX_GEAR]; // Rotational inertia per gear // Shifting int timeToDeclutch, // Auto-shifting time timeToClutch; float shiftUpRPM, // Automatic transmissions shiftDownRPM; // State (dynamic output) int curGear; // Selected gear float force; // Force put out float torque; // Torque sent to drivetrain // Input float throttle; float brakes; pLinearInterpolation torqueCurve; public: pEngine(pVehicle *car); ~pEngine(); void setToDefault(); pLinearInterpolation* getTorqueCurve(){ return &torqueCurve; } void setTorqueCurve(pLinearInterpolation val); pVehicle * getVehicle(){ return ownerVehicle; } void getVehicle(pVehicle * val) { ownerVehicle = val; } float getRPM(){ return (GetRotationVel()/(2*PI))*60.0f; } void setRPM(float rpm); float getTorque(){ return GetEngineTorque(); } // Definition void clean(); // clean all vars void initData(); // Initialize usage of engine void preStep(); // Precalculate some variables // Attribs float GetMass(){ return mass; } bool IsStalled(){ if(flags&STALLED)return TRUE; return FALSE; } void EnableStall(){ flags|=STALLED; } void DisableStall(){ flags&=~STALLED; } bool HasStarter(){ if(flags&HAS_STARTER)return TRUE; return FALSE; } /* bool IsAutoClutchActive() { if(flags&AUTOCLUTCH_ACTIVE)return TRUE; return FALSE; } float GetAutoClutch(){ return autoClutch; } */ // Engine torque generation float GetMinTorque(float rpm); float GetMaxTorque(float rpm); float GetTorqueAtDifferential(); float GetEngineInertia(){ return inertiaEngine; } float GetGearInertia(){ return gearInertia[curGear]; } float GetInertiaAtDifferential(); float GetInertiaForWheel(pWheel2 *w); float GetTorqueForWheel(pWheel2 *w); // Gearbox int GetGears(){ return gears; } int GetGear(){ return curGear; } float GetGearRatio(int n); float GetEndRatio(); void SetGear(int n); // Input void updateUserControl(int ctlThrottle); // Physics void CalcForces(); void CalcAccelerations(); void Integrate(); float GetForce(){ return force; } float GetTorqueReaction(){ return torqueReaction; } float getEndBrakingTorqueForWheel(CK3dEntity *wheelReference); float getEndTorqueForWheel(CK3dEntity *wheelReference); float getEndAccForWheel(CK3dEntity *wheelReference); float rotationalEndFactor; float timeScale; float getTimeScale() const { return timeScale; } void setTimeScale(float val) { timeScale = val; } float getEndRotationalFactor() { return rotationalEndFactor; } void setEndRotationalFactor(float val) { rotationalEndFactor = val; } //float GetRollingFrictionCoeff(){ return rollingFrictionCoeff; } }; #endif <file_sep>#include "Manager.h" #ifdef CK_LIB #define RegisterBehaviorDeclarations Register_CSHARP_BehaviorDeclarations #define InitInstance _CSHARP_InitInstance #define ExitInstance _CSHARP_ExitInstance #define CKGetPluginInfoCount CKGet_CSHARP_PluginInfoCount #define CKGetPluginInfo CKGet_CSHARP_PluginInfo #define g_PluginInfo g_CSHARP_PluginInfo #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #endif PLUGIN_EXPORT void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg); #define ADDONS2_BEHAVIOR CKGUID(0x119d47be,0x74c0241b) CKPluginInfo g_PluginInfo; PLUGIN_EXPORT int CKGetPluginInfoCount() { return 2; } CKERROR InitInstance(CKContext* context) { CSManager* csman =new CSManager(context); return CK_OK; } CKERROR ExitInstance(CKContext* context) { CSManager* cman =(CSManager*)context->GetManagerByGuid(INIT_MAN_GUID); delete cman; return CK_OK; } PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) { switch (Index) { case 0: g_PluginInfo.m_Author = "<NAME>"; g_PluginInfo.m_Description = "tool building blocks"; g_PluginInfo.m_Extension = ""; g_PluginInfo.m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo.m_Version = 0x000001; g_PluginInfo.m_InitInstanceFct = NULL; g_PluginInfo.m_ExitInstanceFct = NULL; g_PluginInfo.m_GUID = ADDONS2_BEHAVIOR; g_PluginInfo.m_Summary = "CSharp BB"; break; case 1: g_PluginInfo.m_Author = "<NAME>"; g_PluginInfo.m_Description = "tool Manager "; g_PluginInfo.m_Extension = ""; g_PluginInfo.m_Type = CKPLUGIN_MANAGER_DLL; g_PluginInfo.m_Version = 0x000001; g_PluginInfo.m_InitInstanceFct = InitInstance; g_PluginInfo.m_ExitInstanceFct = ExitInstance; g_PluginInfo.m_GUID = INIT_MAN_GUID; g_PluginInfo.m_Summary = "CSharpManager"; break; } return &g_PluginInfo; } /**********************************************************************************/ /**********************************************************************************/ void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) { RegisterBehavior(reg, FillBehaviorSendCSMessageDecl); /* // Get Nearest Vertex RegisterBehavior(reg, FillBehaviorGetNearestVertexDecl); // Scene Antialias RegisterBehavior(reg, FillBehaviorSceneAntialiasDecl); // Merge Mesh RegisterBehavior(reg, FillBehaviorMergeMeshDecl); // Get Host Platform RegisterBehavior(reg, FillBehaviorGetHostPlatformDecl); //Open File RegisterBehavior(reg, FillBehaviorOpenFileDecl);*/ } <file_sep> FAQ : Where to set fade in/out time, splash bitmap, bitmap trancparency, text position for loading text, or the font type ? -> go in the project xSplash -> xSplash.cpp -> function CreateSplashEx(...) : #define CSS_FADEIN 0x0001 #define CSS_FADEOUT 0x0002 #define CSS_FADE CSS_FADEIN | CSS_FADEOUT #define CSS_SHADOW 0x0004 #define CSS_CENTERSCREEN 0x0008 #define CSS_CENTERAPP 0x0010 #define CSS_HIDEONCLICK 0x0020 #define CSS_TEXT_NORMAL 0x0000 #define CSS_TEXT_BOLD 0x0001 #define CSS_TEXT_ITALIC 0x0002 #define CSS_TEXT_UNDERLINE 0x0004 Where to change the "Load ...90%" Text ? ->CustomPlayer.cpp -> LoadCallback() (last function) if (loaddata.NbObjetsLoaded % 10 == 0) : means, update text each 10th object ! Where to change the about tab text ? - goto \res\about.txt ! you can use mailto:<EMAIL> or www.playgen.com for links. Where to change global settings ? in CustomPlayerDefines.h ! : #define CPR_CHECK_DIRECTX 1 // this leads to a directx check, is using xUtils.dll #define CPR_MINIMUM_DIRECTX_VERSION 8 // this is our minimum version, always write at least 3 letters like 10.0 #define CPR_MINIMUM_DIRECTX_VERSION_FAIL_URL "www.microsoft.com" #define CPR_OFFER_INTERNAL_DIRECTX_INSTALLER 0 // not implemented #define CPR_CHECK_RAM 1 //performes a memory check, is using xUtils.dll and it needs a directx !!! #define CPR_MINIMUM_RAM 256 //our minimum pRam #define CPR_MINIMUM_RAM_FAIL_ABORT 0 // this leads to a application exit ! #define CP_SUPPORT_EMAIL "<EMAIL>" // // [12/16/2007 mc007] ////////////////////////////////////////////////////////////////////////// // // Application Features : #define CPF_HAS_SPLASH 1 // displays a splash, is using xsplash.dll ! it also adds a loading callback #define CPF_SPLASH_FILE "splash.bmp" //not used ! #define CPF_SPLASH_TEXT_TYPE "MicrogrammaDBolExt" #define CPF_SPLASH_TEXT_FORMAT (DT_SINGLELINE | DT_RIGHT | DT_BOTTOM) // [12/17/2007 mc007] #define CPA_SHOW_ABOUT_TAB 1 //adds an about tab, is using about.txt from \project source folder \res #define CPA_SHOW_LICENSE_TAB 0 //adds an about tab, is using license.txt from \project source folder \res #define CPA_SHOW_ERROR_TAB 1 #define CPA_ABORT_ON_ERROR 1 // aborts when the requirements are failing <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pVehicleMotor.h" #include "pVehicleGears.h" #include <xDebugTools.h> #include "NxArray.h" int pVehicle::_calculateCurrentStatus() { int result = 0; //---------------------------------------------------------------- // // is moving ? // { _computeLocalVelocity(); if ( NxMath::abs(_localVelocity.z) > 0.1f) result |=VS_IsMoving; } NxVec3 _loc = _localVelocity; //---------------------------------------------------------------- // // is accelerated ? // if ( _cAcceleration > 0.1f ) result |=VS_IsAcceleratedForward; if ( _cAcceleration < 0.0f ) result |=VS_IsAcceleratedBackward; if ( (result & VS_IsAcceleratedForward) || (result & VS_IsAcceleratedBackward) ) result |=VS_IsAccelerated; //---------------------------------------------------------------- // // is Braking ? // if ( (result & VS_IsMoving ) ) { if ( _localVelocity.z > 0.0f && ( result & VS_IsAcceleratedBackward ) ) { result |=VS_IsBraking; } if ( _localVelocity.z < 0.0f && (result & VS_IsAcceleratedForward ) ) { result |=VS_IsBraking; } } //---------------------------------------------------------------- // // is steering // if( XAbs(_cSteering) > 0.01f ) result|=VS_IsSteering; //---------------------------------------------------------------- // // is falling + handbrake // _nbNotTouching =0; _nbTouching =0; _nbHandbrakeOn =0; int nbWheels = _wheels.size(); for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel* wheel = _wheels[i]; if (!wheel->hasGroundContact()) { _nbNotTouching++; } else { _nbTouching++; } if(_cHandbrake && wheel->getWheelFlag(WF_AffectedByHandbrake)) { _nbHandbrakeOn++; } } if (_nbNotTouching == _wheels.size()) result |= VS_IsFalling; if (_cHandbrake && _nbHandbrakeOn ) { result|=VS_Handbrake; } /* if ( !(result & VS_IsBraking) ) { mBreakLastFrame = false; mTimeBreaking = 0.0f; } */ _accelerationPedal = _cAcceleration; return result; } void pVehicle::updateControl(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) { setControlState(E_VCS_ACCELERATION,acceleration); setControlState(E_VCS_HANDBRAKE,handBrake); setControlState(E_VCS_STEERING,steering); setControlMode(E_VCS_ACCELERATION,analogAcceleration ? E_VCSM_ANALOG : E_VCSM_DIGITAL); setControlMode(E_VCS_STEERING, analogSteering ? E_VCSM_ANALOG : E_VCSM_DIGITAL); } void pVehicle::control(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) { if (steering != 0 || acceleration != 0 || handBrake) getActor()->wakeUp(0.05); return; _controlSteering(steering, analogSteering); _computeLocalVelocity(); NxVec3 locVel = _localVelocity; float lcx = locVel.x; float lcz = locVel.z; float test = _localVelocity.z * acceleration < ( NxMath::sign(-acceleration) ); float test2 = _localVelocity.z * acceleration < ( -0.1f ); float test3 = XAbs(_localVelocity.z) * acceleration < ( -0.1f ); if (!_braking || _releaseBraking) { //_braking = _localVelocity.x * acceleration < (-0.1f /** NxMath::sign(-acceleration) */); _braking = _localVelocity.z * acceleration < ( -0.1 /*NxMath::sign(acceleration) */ ); //_braking = _localVelocity.z * acceleration < ( NxMath::sign(acceleration)); _releaseBraking = false; } if(_handBrake != handBrake) { _handBrake = handBrake; _brakePedalChanged; } //printf("Braking: %s, Handbrake: %s\n", _braking?"true":"false", handBrake?"true":"false"); _controlAcceleration(acceleration, analogAcceleration); } void pVehicle::updateVehicle( float lastTimeStepSize ) { _lastDT = lastTimeStepSize; _currentStatus = _calculateCurrentStatus(); VehicleStatus status = (VehicleStatus)_currentStatus; if (_cSteering != 0 || _cAcceleration != 0 || _cHandbrake) getActor()->wakeUp(0.05); _performAcceleration(lastTimeStepSize); _performSteering(lastTimeStepSize); if (getMotor()) { _currentStatus |= E_VSF_HAS_MOTOR; } if (getGears()) { _currentStatus |= E_VSF_HAS_GEARS; } setVSFlags(_currentStatus); if (engine && gearbox && driveLine ) { doEngine(0,lastTimeStepSize); } return; //---------------------------------------------------------------- // // old code // //control(_cSteering,_cAnalogSteering,_cAcceleration,_cAnalogAcceleration,_cHandbrake); //printf("updating %x\n", this); NxReal distanceSteeringAxisCarTurnAxis = _steeringSteerPoint.x - _steeringTurnPoint.x; NX_ASSERT(_steeringSteerPoint.z == _steeringTurnPoint.z); NxReal distance2 = 0; if (NxMath::abs(_steeringWheelState) > 0.01f) distance2 = distanceSteeringAxisCarTurnAxis / NxMath::tan(_steeringWheelState * _steeringMaxAngleRad); NxU32 nbTouching = 0; NxU32 nbNotTouching = 0; NxU32 nbHandBrake = 0; int wSize = _wheels.size(); for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel* wheel = _wheels[i]; if(wheel->getWheelFlag(WF_SteerableInput)) { if(distance2 != 0) { NxReal xPos = wheel->getWheelPos().x; NxReal xPos2 = _steeringSteerPoint.x- wheel->getWheelPos().x; NxReal zPos = wheel->getWheelPos().z; NxReal dz = -zPos + distance2; NxReal dx = xPos - _steeringTurnPoint.x; float atan3 = NxMath::atan(dx/dz); float angle =(NxMath::atan(dx/dz)); if (dx < 0.0f) { angle*=-1.0f; } wheel->setAngle(angle); //errMessage.Format("w%d dz:%f dx:%f dx2%f distance:%f atan3:%f",i,dz,dx,xPos2,distance2,atan3); //xInfo(errMessage.Str()); } else { wheel->setAngle(0.0f); } //printf("%2.3f\n", wheel->getAngle()); } else if(wheel->getWheelFlag(WF_SteerableAuto)) { NxVec3 localVelocity = getActor()->getLocalPointVelocity(getFrom(wheel->getWheelPos())); NxQuat local2Global = getActor()->getGlobalOrientationQuat(); local2Global.inverseRotate(localVelocity); // printf("%2.3f %2.3f %2.3f\n", wheel->getWheelPos().x,wheel->getWheelPos().y,wheel->getWheelPos().z); localVelocity.y = 0; if(localVelocity.magnitudeSquared() < 0.1f) { wheel->setAngle(0.0f); } else { localVelocity.normalize(); // printf("localVelocity: %2.3f %2.3f\n", localVelocity.x, localVelocity.z); if(localVelocity.x < 0) localVelocity = -localVelocity; NxReal angle = NxMath::clamp((NxReal)atan(localVelocity.z / localVelocity.x), 0.3f, -0.3f); wheel->setAngle(angle); } } // now the acceleration part if(!wheel->getWheelFlag(WF_Accelerated)) continue; if(_handBrake && wheel->getWheelFlag(WF_AffectedByHandbrake)) { nbHandBrake++; } else { if (!wheel->hasGroundContact()) { nbNotTouching++; } else { nbTouching++; } } } NxReal motorTorque = 0.0; float _acc = NxMath::abs(_accelerationPedal); XString errMessage; if(nbTouching && NxMath::abs(_accelerationPedal) > 0.1f ) { NxReal axisTorque = _computeAxisTorque(); NxReal wheelTorque = axisTorque / (NxReal)(_wheels.size() - nbHandBrake); NxReal wheelTorqueNotTouching = nbNotTouching>0?wheelTorque*(NxMath::pow(0.5f, (NxReal)nbNotTouching)):0; NxReal wheelTorqueTouching = wheelTorque - wheelTorqueNotTouching; motorTorque = wheelTorqueTouching / (NxReal)nbTouching; } else { _updateRpms(); } for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel* wheel = _wheels[i]; wheel->tick(_handBrake, motorTorque, _brakePedal, lastTimeStepSize); //wheel->tick(_handBrake, motorTorque, _brakePedal, 1/60); } } pWheel*pVehicle::getWheel(CK3dEntity *wheelReference) { if (!wheelReference) { return NULL; } for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel* wheel = _wheels[i]; if (wheel->getEntID() == wheelReference->GetID()) { return wheel; } } return NULL; } void pVehicle::handleContactPair(NxContactPair* pair, int carIndex) { NxContactStreamIterator i(pair->stream); while(i.goNextPair()) { NxShape * s = i.getShape(carIndex); while(i.goNextPatch()) { const NxVec3& contactNormal = i.getPatchNormal(); while(i.goNextPoint()) { //user can also call getPoint() and getSeparation() here const NxVec3& contactPoint = i.getPoint(); //add forces: //assuming front wheel drive we need to apply a force at the wheels. if (s->is(NX_SHAPE_CAPSULE) && s->userData != NULL) { //assuming only the wheels of the car are capsules, otherwise we need more checks. //this branch can't be pulled out of loops because we have to do a full iteration through the stream NxQuat local2global = s->getActor().getGlobalOrientationQuat(); /* NxWheel* w = (NxWheel*)s->userData; if (!w->getWheelFlag(E_WF_USE_WHEELSHAPE)) { NxWheel1 * wheel = static_cast<NxWheel1*>(w); wheel->contactInfo.otherActor = pair.actors[1-carIndex]; wheel->contactInfo.contactPosition = contactPoint; wheel->contactInfo.contactPositionLocal = contactPoint; wheel->contactInfo.contactPositionLocal -= _bodyActor->getGlobalPosition(); local2global.inverseRotate(wheel->contactInfo.contactPositionLocal); wheel->contactInfo.contactNormal = contactNormal; if (wheel->contactInfo.otherActor->isDynamic()) { NxVec3 globalV = s->getActor().getLocalPointVelocity(wheel->getWheelPos()); globalV -= wheel->contactInfo.otherActor->getLinearVelocity(); local2global.inverseRotate(globalV); wheel->contactInfo.relativeVelocity = globalV.x; //printf("%2.3f (%2.3f %2.3f %2.3f)\n", wheel->contactInfo.relativeVelocity, // globalV.x, globalV.y, globalV.z); } else { NxVec3 vel = s->getActor().getLocalPointVelocity(wheel->getWheelPos()); local2global.inverseRotate(vel); wheel->contactInfo.relativeVelocity = vel.x; wheel->contactInfo.relativeVelocitySide = vel.z; } NX_ASSERT(wheel->hasGroundContact()); //printf(" Wheel %x is touching\n", wheel); } */ } } } } //printf("----\n"); } float pVehicle::_computeAxisTorqueV2() { if(_vehicleMotor != NULL) { NxReal rpm = _computeRpmFromWheels(); NxReal motorRpm = _computeMotorRpm(rpm); _vehicleMotor->setRpm(motorRpm); float acc = _accelerationPedal; NxReal torque = _accelerationPedal * _vehicleMotor->getTorque(); NxReal v = getActor()->getLinearVelocity().magnitude(); /* printf("v: %2.3f m/s (%2.3f km/h)\n", v, v*3.6f); printf("rpm %2.3f, motorrpm %2.3f, torque %2.3f, realtorque %2.3f\n", rpm, motorRpm, torque, torque*_getGearRatio()*_differentialRatio*_transmissionEfficiency); */ return torque * _getGearRatio() * _differentialRatio * _transmissionEfficiency; } else { _computeRpmFromWheels(); return _cAcceleration * _motorForce; } } float pVehicle::_computeRpmFromWheels() { NxReal wheelRpms = 0; NxI32 nbWheels = 0; int nbAcc=0; int nbNotAcc=0; int s = _wheels.size(); for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel* wheel = _wheels[i]; if (wheel->getWheelFlag(WF_Accelerated)) { nbWheels++; wheelRpms += wheel->getRpm(); } } return wheelRpms / (NxReal)nbWheels; } float pVehicle::_getGearRatio() { if(_vehicleGears == NULL) { return 1; } else { return _vehicleGears->getCurrentRatio(); } } void pVehicle::gearUp() { if (_vehicleGears) { printf("Changing gear from %d to", _vehicleGears->getGear()); _vehicleGears->gearUp(); printf(" %d\n", _vehicleGears->getGear()); } else { printf("gearUp not supported if no gears available\n"); } } void pVehicle::gearDown() { if(_vehicleGears) { printf("Changing gear from %d to", _vehicleGears->getGear()); _vehicleGears->gearDown(); printf(" %d\n", _vehicleGears->getGear()); } else { printf("gearDown not supported if no gears available\n"); } } void pVehicle::setAutomaticMode(bool autoMode) { mAutomaticMode=autoMode; } float pVehicle::_computeMotorRpm(float rpm) { NxReal temp = _getGearRatio() * _differentialRatio; NxReal motorRpm = rpm * temp; NxI32 change = -1; if(_vehicleMotor) { NxI32 change; if(_vehicleGears && (change = _vehicleMotor->changeGears(_vehicleGears, 0.2f))) { change = _vehicleMotor->changeGears(_vehicleGears, 0.2f); if(change == 1 && mAutomaticMode ) { gearUp(); } else { NX_ASSERT(change == -1); gearDown(); } } temp = _getGearRatio() * _differentialRatio; motorRpm = NxMath::max(rpm * temp, _vehicleMotor->getMinRpm()); } return motorRpm; } void pVehicle::_updateRpms() { NxReal rpm = _computeRpmFromWheels(); if(_vehicleMotor != NULL) { NxReal motorRpm = _computeMotorRpm(rpm); _vehicleMotor->setRpm(motorRpm); } } NxActor* pVehicle::getActor(){ return mActor; } float pVehicle::getDriveVelocity() { return NxMath::abs(_localVelocity.x); } const pWheel*pVehicle::getWheel(int i) { NX_ASSERT(i < _wheels.size()); return _wheels[i]; } void pVehicle::_computeLocalVelocity() { _computeMostTouchedActor(); NxVec3 relativeVelocity; if (_mostTouchedActor == NULL || !_mostTouchedActor->isDynamic()) { relativeVelocity = getActor()->getLinearVelocity(); } else { relativeVelocity = getActor()->getLinearVelocity() - _mostTouchedActor->getLinearVelocity(); } NxQuat rotation = getActor()->getGlobalOrientationQuat(); NxQuat global2Local; _localVelocity = relativeVelocity; rotation.inverseRotate(_localVelocity); char master[512]; //sprintf(master,"Velocity: %2.3f %2.3f %2.3f\n", _localVelocity.x, _localVelocity.y, _localVelocity.z); //OutputDebugString(master); } void pVehicle::_controlSteering(float steering, bool analogSteering) { if(analogSteering) { _steeringWheelState = steering; } else if (NxMath::abs(steering) > 0.0001f) { _steeringWheelState += NxMath::sign(steering) * getDigitalSteeringDelta(); } else if (NxMath::abs(_steeringWheelState) > 0.0001f) { _steeringWheelState -= NxMath::sign(_steeringWheelState) * getDigitalSteeringDelta(); } _steeringWheelState = NxMath::clamp(_steeringWheelState, 1.f, -1.f); } void pVehicle::_computeMostTouchedActor() { std::map<NxActor*, NxU32> actors; typedef std::map<NxActor*, NxU32> Map; for(NxU32 i = 0; i < _wheels.size(); i++) { NxActor* curActor = _wheels[i]->getTouchedActor(); Map::iterator it = actors.find(curActor); if (it == actors.end()) { actors[curActor] = 1; } else { it->second++; } } NxU32 count = 0; _mostTouchedActor = NULL; for(Map::iterator it = actors.begin(); it != actors.end(); ++it) { if(it->second > count) { count = it->second; _mostTouchedActor = it->first; } } } int pVehicle::initWheels(int flags) { getWheels().clear(); int nbShapes = getActor()->getNbShapes(); NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *sinfo = static_cast<pSubMeshInfo*>(s->userData); if (sinfo && sinfo->wheel !=NULL) { pWheel *wheel = sinfo->wheel; pWheel2* wheel2 = (pWheel2*)wheel; NxWheelShape *wShape = wheel2->getWheelShape(); if (!wShape) continue; if (wheel2->getWheelFlag(WF_VehicleControlled) ) { getWheels().push_back(wheel); wheel2->setVehicle(this); } } } } return getWheels().size(); /* int result = 0 ; if (!getBody() || !getBody()->isValid() ) { return result; } getWheels().clear(); CK3dEntity* subEntity = NULL; while (subEntity= getBody()->GetVT3DObject()->HierarchyParser(subEntity) ) { if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) { pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); if (subDescr->flags & BF_SubShape) { if (subDescr->hullType == HT_Wheel) { if (subEntity->HasAttribute(GetPMan()->att_wheelDescr )) { CKParameter *par = subEntity->GetAttributeParameter(GetPMan()->att_wheelDescr ); if (par) { pWheelDescr *wDescr = pFactory::Instance()->createWheelDescrFromParameter(par); if (wDescr) { pWheel *wheel = pFactory::Instance()->createWheel(getBody(),*wDescr); if (wheel) { NxWheelShape *wShape = static_cast<NxWheelShape*>(getBody()->_getSubShapeByEntityID(subEntity->GetID())); if(wDescr->wheelFlags & E_WF_USE_WHEELSHAPE) { pWheel2 *wheel2 = static_cast<pWheel2*>(wheel); if (wheel2) { if(wShape) wheel2->setWheelShape(wShape); } } wheel->setEntID(subEntity->GetID()); getWheels().push_back(wheel); // subEntity->SetParent(NULL); } } } } } } } } return getWheels().size(); */ } void pVehicle::findDifferentialWheels(int& wheel1Index,int& wheel2Index) { pWheel *wheel1 = NULL; pWheel* wheel2 = NULL; wheel1 = wheel2 = 0; for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel *cW = _wheels[i]; if (cW->getWheelFlag(WF_AffectedByDifferential)) { if (!wheel1){ wheel1 = cW; wheel1Index=i; } else{ wheel2 = cW;wheel2Index=i; } } } if (!wheel1) { xWarning("couldn't find first differential wheel"); wheel1Index = -1; } if (!wheel2) { xWarning("couldn't find second differential wheel"); wheel2Index = -1; } } pVehicle::pVehicle() { } void pVehicle::setControlState(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) { _cAcceleration = acceleration; _cSteering = steering; _cAnalogAcceleration = analogAcceleration; _cAnalogSteering = analogSteering; _cHandbrake = handBrake; } pVehicle::pVehicle(pVehicleDesc descr) { _digitalSteeringDelta = descr.digitalSteeringDelta; _steeringSteerPoint = descr.steeringSteerPoint; _steeringTurnPoint = descr.steeringTurnPoint; _steeringMaxAngleRad = NxMath::degToRad(descr.steeringMaxAngle); _transmissionEfficiency = descr.transmissionEfficiency; _differentialRatio = descr.differentialRatio; _maxVelocity = descr.maxVelocity; _motorForce = descr.motorForce; _cSteering = 0.0f; _cAcceleration = 0.0f; _cAnalogAcceleration = false; _cAnalogSteering = false; _cHandbrake = false; mAutomaticMode = true; setBody(descr.body); _vehicleMotor = NULL; _vehicleGears = NULL; //---------------------------------------------------------------- // // Break settings // mBreakLastFrame = false; mTimeBreaking = 0.0f; mBrakeMediumThresold = 1.5f; mBrakeHighThresold = 3.0f; mBreakPressures[BL_Small] = 0.1f; mBreakPressures[BL_Medium] = 0.3f; mBreakPressures[BL_High] = 1.0f; useBreakTable = false; mSmallBrakeTable.brakeEntries[0] = 10.0f; mSmallBrakeTable.brakeEntries[1] = 20.0f; mSmallBrakeTable.brakeEntries[2] = 30.0f; mSmallBrakeTable.brakeEntries[3] = 40.0f; mSmallBrakeTable.brakeEntries[4] = 50.0f; mSmallBrakeTable.brakeEntries[5] = 100.0f; mSmallBrakeTable.brakeEntries[6] = 200.0f; mSmallBrakeTable.brakeEntries[7] = 400.0f; mSmallBrakeTable.brakeEntries[8] = 1000.0f; mSmallBrakeTable.brakeEntries[9] = 1000.0f; mMediumBrakeTable.brakeEntries[0] = 400.0f; mMediumBrakeTable.brakeEntries[1] = 450.0f; mMediumBrakeTable.brakeEntries[2] = 550.0f; mMediumBrakeTable.brakeEntries[3] = 650.0f; mMediumBrakeTable.brakeEntries[4] = 725.0f; mMediumBrakeTable.brakeEntries[5] = 900.0f; mMediumBrakeTable.brakeEntries[6] = 1050.0f; mMediumBrakeTable.brakeEntries[7] = 1000.0f; mMediumBrakeTable.brakeEntries[8] = 1000.0f; mHighBrakeTable.brakeEntries[0] = 700.0f; mHighBrakeTable.brakeEntries[1] = 775.0f; mHighBrakeTable.brakeEntries[2] = 950.0f; mHighBrakeTable.brakeEntries[3] = 1100.0f; mHighBrakeTable.brakeEntries[4] = 1200.0f; mHighBrakeTable.brakeEntries[5] = 1250.0f; mHighBrakeTable.brakeEntries[6] = 1500.0f; mHighBrakeTable.brakeEntries[7] = 2000.0f; mHighBrakeTable.brakeEntries[8] = 1000.0f; mHighBrakeTable.brakeEntries[9] = 1000.0f; breakConditionLevels[BC_NoUserInput]=BL_Small; breakConditionLevels[BC_DirectionChange]=BL_High; breakConditionLevels[BC_Handbrake]=BL_Medium; breakConditionLevels[BC_UserBreak]=BL_Medium; } pVehicleDesc::pVehicleDesc() //constructor sets to default { setToDefault(); } void pVehicleDesc::setToDefault() { userData = NULL; transmissionEfficiency = 1.0f; differentialRatio = 1.0f; maxVelocity = 80; motorForce = 100.0f; body = NULL; gearDescription = NULL;//new pVehicleGearDesc(); motorDescr = NULL;//new pVehicleMotorDesc(); steeringMaxAngle = 30; steeringSteerPoint = VxVector(0,0,0); steeringTurnPoint = VxVector(0,0,0); digitalSteeringDelta = 0.04f; } bool pVehicleDesc::isValid() const { /*for (NxU32 i = 0; i < carWheels.size(); i++) { if (!carWheels[i]->isValid()) return false; } */ if (mass < 0) return false; return true; } void pVehicle::setControlState(int parameter,float value) { switch (parameter) { case E_VCS_GUP: _cShiftStateUp = (int)value; break; case E_VCS_GDOWN: _cShiftStateDown = (int)value; break; case E_VCS_ACCELERATION: _cAcceleration = value; break; case E_VCS_STEERING: _cSteering = value; break; case E_VCS_HANDBRAKE: _cHandbrake= (int)value; break; } } void pVehicle::setControlMode(int parameter,int mode) { switch (parameter) { case E_VCS_ACCELERATION: _cAnalogAcceleration = (mode == E_VCSM_ANALOG) ? true : false; break; case E_VCS_STEERING: _cAnalogSteering = (mode == E_VCSM_ANALOG) ? true : false; break; } } float pVehicle::_computeAxisTorque() { if(_vehicleMotor != NULL) { NxReal rpm = _computeRpmFromWheels(); NxReal motorRpm = _computeMotorRpm(rpm); _vehicleMotor->setRpm(motorRpm); NxReal torque = _accelerationPedal * _vehicleMotor->getTorque(); NxReal v = getActor()->getLinearVelocity().magnitude(); //printf("v: %2.3f m/s (%2.3f km/h)\n", v, v*3.6f); //printf("rpm %2.3f, motorrpm %2.3f, torque %2.3f, realtorque %2.3f\n", // rpm, motorRpm, torque, torque*_getGearRatio()*_differentialRatio*_transmissionEfficiency); return torque * _getGearRatio() * _differentialRatio * _transmissionEfficiency; } else { _computeRpmFromWheels(); return _accelerationPedal * _motorForce; } } void pVehicle::getControlState(int parameter,float &value,int &mode) { switch (parameter) { case E_VCS_ACCELERATION: value = _cAcceleration; mode = _cAnalogAcceleration; break; case E_VCS_STEERING: value = _cSteering; mode = _cAnalogSteering; break; case E_VCS_HANDBRAKE: value = ((float)_cHandbrake); mode = _cHandbrake; break; } }<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBSetDecl(); CKERROR CreateBodySetProto(CKBehaviorPrototype **pproto); int BodySet(const CKBehaviorContext& behcontext); CKERROR BodySetCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_Vel=0, bbI_AVel, bbI_Torque, bbI_Force, bbI_Pos, bbI_Rot }; enum bSettings { bbS_Vel=0, bbS_AVel, bbS_Torque, bbS_Force, bbS_Pos, bbS_Rot }; //************************************ // Method: FillBehaviorPBSetDecl // FullName: FillBehaviorPBSetDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPBSetDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSet"); od->SetCategory("Physic/Body"); od->SetDescription("Sets physical quantities."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x6915390d,0x1d775a96)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateBodySetProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } CKERROR CreateBodySetProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSet-Obsolete"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( BodySetCB ); /* PBSet PBSet is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies various physical parameters.<br> <h3>Technical Information</h3> \image html PBSet.png <SPAN CLASS="in">In:</SPAN>triggers the process <BR> <SPAN CLASS="out">Out:</SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pin">Linear Velocity: </SPAN>The linear velocity.See pRigidBody::setLinearVelocity(). <BR> <SPAN CLASS="pin">Angular Velocity: </SPAN>The angular velocity.See pRigidBody::setAngularVelocity(). <BR> <SPAN CLASS="pin">Agular Momentum: </SPAN>The angular momentum.See pRigidBody::getAngularMomentum(). <BR> <SPAN CLASS="pin">Linear Momentum: </SPAN>The linear momentum.See pRigidBody::getLinearMomentum(). <BR> <SPAN CLASS="pin">Position: </SPAN>The position.See pRigidBody::setPosition(). <BR> <BR> <SPAN CLASS="setting">Linear Velocity: </SPAN>Enables output for linear velocity. <BR> <SPAN CLASS="setting">Angular Velocity: </SPAN>Enables output for angular velocity. <BR> <SPAN CLASS="setting">Agular Momentum: </SPAN>Enables output for angular momentum. <BR> <SPAN CLASS="setting">Linear Momentum: </SPAN>Enables output for linear momentum. <BR> <SPAN CLASS="setting">Position: </SPAN>Enables output for position. <BR> <SPAN CLASS="setting">Orientation: </SPAN>Enables output for orientation. <BR> <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager . <br> <br> <SPAN CLASS="framedWhite"> The known building block <A HREF="Documentation.chm::/behaviors/3D%20Transformations/Set%20Position.html">"Set Position"</A> has new settings avaiable. Enable there "Update Physics" in order to transfer the new position on the body automatically! </SPAN> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBSet.cpp </SPAN> */ proto->DeclareInParameter("Linear Velocity",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Angular Velocity",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Angular Momentum",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Linear Momentum",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Position",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); proto->DeclareInParameter("Orientation",CKPGUID_QUATERNION); proto->DeclareSetting("Velocity",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Angular Velocity",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Torque",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Force",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Position",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Rotation",CKPGUID_BOOL,"FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(BodySet); *pproto = proto; return CK_OK; } int BodySet(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) { beh->ActivateOutput(0); return 0; } // body exists already ? clean and delete it : pRigidBody*result = world->getBody(target); if(result) { ////////////////////////////////////////////////////////////////////////// //velocity : DWORD vel=0; beh->GetLocalParameterValue(bbS_Vel,&vel); if (vel) { VxVector vec = GetInputParameterValue<VxVector>(beh,bbI_Vel); result->setLinearVelocity(vec); } ////////////////////////////////////////////////////////////////////////// //angular velocity DWORD avel=0; beh->GetLocalParameterValue(bbS_AVel,&avel); if (avel) { VxVector vec = GetInputParameterValue<VxVector>(beh,bbI_AVel); result->setAngularVelocity(vec); } ////////////////////////////////////////////////////////////////////////// //torque DWORD torque=0; beh->GetLocalParameterValue(bbS_Torque,&avel); if (torque) { VxVector vec = GetInputParameterValue<VxVector>(beh,bbI_Torque); result->setAngularMomentum(vec); } ////////////////////////////////////////////////////////////////////////// //force DWORD force=0; beh->GetLocalParameterValue(bbS_Force,&force); if (force) { VxVector vec = GetInputParameterValue<VxVector>(beh,bbI_Force); result->setLinearMomentum(vec); } ////////////////////////////////////////////////////////////////////////// //force DWORD pos=0; beh->GetLocalParameterValue(bbS_Pos,&pos); if (pos) { VxVector vec = GetInputParameterValue<VxVector>(beh,bbI_Pos); result->setPosition(vec); } ////////////////////////////////////////////////////////////////////////// DWORD rot=0; beh->GetLocalParameterValue(bbS_Rot,&rot); if (rot) { VxQuaternion vec = GetInputParameterValue<VxQuaternion>(beh,bbI_Rot); result->setRotation(vec); } } beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } return 0; } //************************************ // Method: BodySetCB // FullName: BodySetCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR BodySetCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD vel; beh->GetLocalParameterValue(bbS_Vel,&vel); beh->EnableInputParameter(bbI_Vel,vel); DWORD avel; beh->GetLocalParameterValue(bbS_AVel,&avel); beh->EnableInputParameter(bbI_AVel,avel); DWORD torque; beh->GetLocalParameterValue(bbS_Torque,&torque); beh->EnableInputParameter(bbI_Torque,torque); DWORD force; beh->GetLocalParameterValue(bbS_Force,&force); beh->EnableInputParameter(bbI_Force,force); DWORD pos; beh->GetLocalParameterValue(bbS_Pos,&pos); beh->EnableInputParameter(bbI_Pos,pos); DWORD rot; beh->GetLocalParameterValue(bbS_Rot,&rot); beh->EnableInputParameter(bbI_Rot,rot); } break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtStructHelper.h" #include "vtAttributeHelper.h" #include "gConfig.h" #define PHYSIC_JOINT_CAT "Physic Constraints" using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; StructurMember bodyDamping[] = { STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Linear Damping","0.1"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Angular Damping","0.1"), }; StructurMember bodySleeping[] = { STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Linear Sleep Velocity","0.1"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Angular Sleep Velocity","0.1"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Sleep Energy Threshold","0.1"), }; StructurMember bodyXMLSetup[] = { STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_SETTINGS_INTERN,"Internal","None"), STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_SETTINGS_EXTERN,"External","None"), STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS,"Import Flags","Stub"), }; StructurMember bodyCCDSettings[] = { STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Motion Threshold","None"), STRUCT_ATTRIBUTE(VTF_PHYSIC_CCD_FLAGS,"Flags","Stub"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Mesh Scale","1.0f"), STRUCT_ATTRIBUTE(CKPGUID_BEOBJECT,"Shape Reference","None"), }; StructurMember bodyCollisionsSettings[] = { STRUCT_ATTRIBUTE(VTE_PHYSIC_BODY_COLL_GROUP,"Collisions Group","All"), STRUCT_ATTRIBUTE(VTS_FILTER_GROUPS,"Group Mask","None"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Skin Width","-1.0"), //STRUCT_ATTRIBUTE(VTS_PHYSIC_CCD_SETTINGS,"CCD Settings","None"), }; StructurMember bodyCollisionsSetup[] = { STRUCT_ATTRIBUTE(VTS_PHYSIC_COLLISIONS_SETTINGS,"Collisions Settings","None"), //STRUCT_ATTRIBUTE(VTS_PHYSIC_CCD_SETTINGS,"CCD Settings","0"), }; StructurMember bodyOptimistationSettings[] = { STRUCT_ATTRIBUTE(VTF_BODY_TRANS_FLAGS,"Transformation Locks","None"), STRUCT_ATTRIBUTE(VTS_PHYSIC_DAMPING_PARAMETER,"Damping Settings","None"), STRUCT_ATTRIBUTE(VTS_PHYSIC_SLEEP_SETTINGS,"Sleeping Settings","None"), STRUCT_ATTRIBUTE(CKPGUID_INT,"Solver Iterations",""), STRUCT_ATTRIBUTE(VTE_PHYSIC_DOMINANCE_GROUP,"Dominance Group",""), STRUCT_ATTRIBUTE(CKPGUID_INT,"Compartment Id",""), }; StructurMember bodyCommonSettings[] = { STRUCT_ATTRIBUTE(VTE_COLLIDER_TYPE,"Hull Type","1"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Density","1"), STRUCT_ATTRIBUTE(VTF_BODY_FLAGS,"Flags","Moving Object,World Gravity,Enabled,Collision"), /* STRUCT_ATTRIBUTE(VTF_BODY_TRANS_FLAGS,"Transformation Locks",""),*/ STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"World","pWorldDefault"), }; StructurMember bodyGeomtryOverride[] = { STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Offset Linear","0.0"), STRUCT_ATTRIBUTE(CKPGUID_EULERANGLES,"Offset Angular","0.0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Offset Reference",""), }; StructurMember bodyMassSetup[] = { STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"New Density","0.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Total Mass","0.0"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Offset Linear","0.0"), STRUCT_ATTRIBUTE(CKPGUID_EULERANGLES,"Offset Angular","0.0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Mass Offset Reference","0.0"), }; StructurMember bodySetup[] = { STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_SETUP,"XML Links","0"), STRUCT_ATTRIBUTE(VTF_PHYSIC_BODY_COMMON_SETTINGS,"Common Settings","0"), /*STRUCT_ATTRIBUTE(VTS_PHYSIC_PIVOT_OFFSET,"Pivot","0"), STRUCT_ATTRIBUTE(VTS_PHYSIC_MASS_SETUP,"Mass Setup","0"),*/ STRUCT_ATTRIBUTE(VTS_PHYSIC_COLLISIONS_SETTINGS,"Collisions Setup","0"), /*STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_OPTIMIZATION,"Optimization","0"),*/ }; StructurMember axisReferencedLength[] = { STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Value","0"), STRUCT_ATTRIBUTE(CKPGUID_BEOBJECT,"Reference Object","0"), STRUCT_ATTRIBUTE(CKPGUID_AXIS,"Local Axis","0"), }; StructurMember customCapsule[] = { STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Radius",""), STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Width","0"), }; StructurMember customConvexCylinder[] = { STRUCT_ATTRIBUTE(CKPGUID_INT,"Approximation","10"), STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Radius",""), STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Width","0"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Forward Axis","0.0,0.0,-1.0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Forward Axis Reference","0"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Down Axis","0.0,-1.0,0.0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Down Axis Reference","0"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Right Axis","1.0,0.0,0.0"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Right Axis Reference","0"), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Build Lower Half Only","0"), STRUCT_ATTRIBUTE(VTF_CONVEX_FLAGS,"Convex Flags","0"), }; //#define gSMapJDistance myStructJDistance extern void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); typedef CKERROR (*bodyParameterDefaultFunction)(CKParameter*); bodyParameterDefaultFunction bodyCreateFuncOld = NULL; /* #define REGISTER_CUSTOM_STRUCT(NAME,ENUM_TYPE,GUID,MEMBER_ARRAY,HIDDEN) DECLARE_STRUCT(ENUM_TYPE,NAME,GUID,MEMBER_ARRAY,STRUCT_SIZE(MEMBER_ARRAY)); \ XArray<CKGUID> ListGuid##ENUM_TYPE = STRUCT_MEMBER_GUIDS(ENUM_TYPE);\ pm->RegisterNewStructure(GUID,NAME,STRUCT_MEMBER_NAMES(ENUM_TYPE).Str(),ListGuid##ENUM_TYPE);\ CKParameterTypeDesc* param_type##ENUM_TYPE=pm->GetParameterTypeDescription(GUID);\ if (param_type##ENUM_TYPE && HIDDEN) param_type##ENUM_TYPE->dwFlags|=CKPARAMETERTYPE_HIDDEN;\ _getCustomStructures().Insert(GUID,(CustomStructure*)&MEMBER_ARRAY) */ void bodyDefaultFunctionMerged(CKParameter*in) { CKStructHelper sHelper(in); //if ( ==0 ) //happens when dev is being opened and loads a cmo with physic objects. XString msg; msg.Format("parameter members : %d",sHelper.GetMemberCount()); if(bodyCreateFuncOld!=0 ) { bodyCreateFuncOld(in); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,msg.Str()); } return; // CKParameter //CKAttributeManager::SetAttributeDefaultValue() } void PhysicManager::_RegisterBodyParameterFunctions() { return; CKContext* ctx = GetContext(); CKParameterManager *pm = ctx->GetParameterManager(); CKParameterTypeDesc *param_desc = pm->GetParameterTypeDescription(VTF_PHYSIC_BODY_COMMON_SETTINGS); if( !param_desc ) return; if (param_desc->CreateDefaultFunction!=0) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"has function"); bodyCreateFuncOld = param_desc->CreateDefaultFunction; param_desc->CreateDefaultFunction = (CK_PARAMETERCREATEDEFAULTFUNCTION)bodyDefaultFunctionMerged; } //param_desc->UICreatorFunction = CKActorUIFunc; //param_desc->UICreatorFunction = CKDoubleUIFunc; } void PhysicManager::_RegisterBodyParameters() { CKParameterManager *pm = m_Context->GetParameterManager(); CKAttributeManager* attman = m_Context->GetAttributeManager(); int attRef=0; //################################################################ // // Geometry Related // // Object and Axis Related Length : REGISTER_CUSTOM_STRUCT("pAxisReferencedLength",PS_AXIS_REFERENCED_LENGTH,VTS_AXIS_REFERENCED_LENGTH,axisReferencedLength,false); REGISTER_CUSTOM_STRUCT("pCustomConvexCylinder",PS_CUSTOM_CONVEX_CYLINDER_DESCR,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,customConvexCylinder,false); REGISTER_STRUCT_AS_ATTRIBUTE("pCustomConvexCylinder",PS_CUSTOM_CONVEX_CYLINDER_DESCR,PHYSIC_BODY_CAT,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,CKCID_3DOBJECT,customConvexCylinder,true); REGISTER_CUSTOM_STRUCT("pCapsule",PS_CAPSULE,VTS_CAPSULE_SETTINGS_EX,customCapsule,false); REGISTER_STRUCT_AS_ATTRIBUTE("pCapsule",PS_CAPSULE,PHYSIC_BODY_CAT,VTS_CAPSULE_SETTINGS_EX,CKCID_3DOBJECT,customCapsule,true); ////////////////////////////////////////////////////////////////////////// // // Collision Common Structs : // pm->RegisterNewFlags(VTF_COLLISIONS_EVENT_MASK,"pCollisionEventMask","Ignore=1,Start Touch=2,End Touch=4,Touch=8,Impact=16,Roll=32,Slide=64,Forces=128,Start Touch Force Threshold=256,End Touch Force Threshold=512,Touch Force Threshold=1024,Contact Modification=65536"); pm->RegisterNewFlags(VTF_WHEEL_CONTACT_MODIFY_FLAGS,"pWheelContactModifyFlags","Point=1,Normal=2,Position=4,Force=8,Material=16"); pm->RegisterNewFlags(VTF_CONTACT_MODIFY_FLAGS,"pContactModifyFlags","None=0,Min Impulse=1,Max Impulse=2,Error=4,Target=8,Local Position0=16,Local Position1=32,Local Orientation0=64,Local Orientation1=128,Static Friction0=256,Static Friction1=512,Dynamic Friction0=1024,Dynamic Friction1=2048,Restitution=4096,Force32=2147483648"); pm->RegisterNewFlags(VTF_CONVEX_FLAGS,"pConvexFlags","Flip Normals=1,16 Bit Indices=2,Compute Convex=4,Inflate Convex=8,Uncompressed Normals=64"); pm->RegisterNewFlags(VTF_TRIGGER,"pTriggerFlags","Disable=8,OnEnter=1,OnLeave=2,OnStay=4"); pm->RegisterNewEnum(VTE_FILTER_OPS,"pFilterOp","And=0,Or=1,Xor=2,Nand=3,Nor=4,NXor=5"); pm->RegisterNewFlags(VTE_FILTER_MASK,"pFilterMask","0,1,2,3"); pm->RegisterNewStructure(VTS_FILTER_GROUPS,"pFilterGroups","bits0,bits1,bits2,bits3",VTE_FILTER_MASK,VTE_FILTER_MASK,VTE_FILTER_MASK,VTE_FILTER_MASK); pm->RegisterNewFlags(VTF_SHAPES_TYPE,"pShapesTypes","Static=1,Dynamic=2"); ////////////////////////////////////////////////////////////////////////// // // Body Sub Structs : // pm->RegisterNewFlags(VTF_BODY_FLAGS,"pBFlags","Moving Object=1,World Gravity=2,Collision=4,Kinematic Object=8,Sub Shape=16,Hierarchy=32,Add Attributes=64,Trigger Shape=128,Deformable=256,Collision Notify=512,Collisions Force=1024,Contact Modify=2048,Sleep=4096"); pm->RegisterNewFlags(VTF_BODY_TRANS_FLAGS,"pBTFlags","FrozenPositionX=2,FrozenPositionY=4,FrozenPositionZ=8,FrozenRotationX=16,FrozenRotationY=32,FrozenRotationZ=64"); pm->RegisterNewEnum(VTE_COLLIDER_TYPE,"pBHullType","Sphere=0,Box=1,Capsule=2,Plane=3,Mesh=4,Convex Mesh=5,Height Field=6,Wheel=7,Cloth=8,Convex Cylinder"); pm->RegisterNewStructure(VTS_PHYSIC_PARAMETER,"pObject", "Geometry,Physic Flags,Density,Skin Width,Mass Offset,Pivot Offset,Hierarchy,World,New Density,Total Mass,Collision Group",VTE_COLLIDER_TYPE,VTF_BODY_FLAGS,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_INT); int currentAttributeType = -1; att_physic_object= attman->RegisterNewAttributeType("Object",VTS_PHYSIC_PARAMETER,CKCID_3DOBJECT); attman->SetAttributeDefaultValue(att_physic_object,"1;Moving Object,World Gravity,Enabled,Collision;1;-1;0,0,0;0,0,0;FALSE,pDefaultWorld"); attman->SetAttributeCategory(att_physic_object,"Physic"); pm->RegisterNewEnum(VTE_BODY_FORCE_MODE,"pBForceMode","Force=0,Impulse=1,Velocity Change=2,Smooth Impulse=3,Smooth Velocity Change=4,Acceleration=5"); attman->SetAttributeCategory(att_physic_limit,"Physic"); ////////////////////////////////////////////////////////////////////////// // // Capsule : // pm->RegisterNewStructure(VTS_CAPSULE_SETTINGS,"Capsule", "Local Length Axis,Local Radius Axis,Length,Radius",CKPGUID_AXIS,CKPGUID_AXIS,CKPGUID_FLOAT,CKPGUID_FLOAT); CKParameterTypeDesc* param_type=pm->GetParameterTypeDescription(VTS_CAPSULE_SETTINGS); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; /* att_capsule = attman->RegisterNewAttributeType("Capsule",VTS_CAPSULE_SETTINGS,CKCID_BEOBJECT); attman->SetAttributeDefaultValue(att_capsule,"1;0;-1.0;-1.0f"); attman->SetAttributeCategory(att_capsule,"Physic"); */ //---------------------------------------------------------------- // // copy flags // pm->RegisterNewFlags(VTF_PHYSIC_ACTOR_COPY_FLAGS,"pBCopyFlags","Physics=1,Shared=2,Pivot=4,Mass=8,Collision=16,CCD=32,Material=64,Optimization=128,Capsule=256,Convex Cylinder=512,Force=1024,Velocities=2048,Joints=4096,Limit Planes=8192,Swap Joint References=16384,Override Body Flags=32768,Copy IC=65536,Restore IC=131072"); /* param_type=pm->GetParameterTypeDescription(VTF_PHYSIC_ACTOR_COPY_FLAGS); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; */ ////////////////////////////////////////////////////////////////////////// // // Body Collision Setup // ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // CCD Settings : // // Custom Enumeration to setup ccd flags pm->RegisterNewFlags(VTF_PHYSIC_CCD_FLAGS,"pBCCDFlags","None=1,Shared=2,DynamicDynamic=4"); REGISTER_CUSTOM_STRUCT("pBCCDSettings",PS_B_CCD,VTS_PHYSIC_CCD_SETTINGS,bodyCCDSettings,GC_SHOWPARAMETER); REGISTER_STRUCT_AS_ATTRIBUTE("pBCCDSettings",PS_B_CCD,PHYSIC_BODY_CAT,VTS_PHYSIC_CCD_SETTINGS,CKCID_3DOBJECT,bodyCCDSettings,true,attRef); //////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Collisions Settings // pm->RegisterNewEnum(VTE_PHYSIC_BODY_COLL_GROUP,"pBCollisionsGroup","All=0,MyObstacles=1,MyWheels=2"); param_type=pm->GetParameterTypeDescription(VTE_PHYSIC_BODY_COLL_GROUP); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; REGISTER_CUSTOM_STRUCT("pBCollisionSettings",PS_B_COLLISON,VTS_PHYSIC_COLLISIONS_SETTINGS,bodyCollisionsSettings,GC_SHOWPARAMETER); REGISTER_STRUCT_AS_ATTRIBUTE("pBCollisionSettings",PS_B_COLLISON,PHYSIC_BODY_CAT,VTS_PHYSIC_COLLISIONS_SETTINGS,CKCID_3DOBJECT,bodyCollisionsSettings,true,attRef); /* Merged */ REGISTER_CUSTOM_STRUCT("pBCSetup",PS_B_COLLISION_SETUP,VTS_PHYSIC_COLLISIONS_SETUP,bodyCollisionsSetup,GC_SHOWPARAMETER ); ////////////////////////////////////////////////////////////////////////// // // XML Setup pm->RegisterNewFlags(VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS,"pBXMLFlags","None=0,Stub=1"); param_type=pm->GetParameterTypeDescription(VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; REGISTER_CUSTOM_STRUCT("pBXMLSetup",PS_BODY_XML_SETUP,VTS_PHYSIC_ACTOR_XML_SETUP,bodyXMLSetup,false); ////////////////////////////////////////////////////////////////////////// // // Common REGISTER_CUSTOM_STRUCT("pBCommon",PS_BODY_COMMON,VTF_PHYSIC_BODY_COMMON_SETTINGS,bodyCommonSettings,false); ////////////////////////////////////////////////////////////////////////// // // Sleep REGISTER_CUSTOM_STRUCT("pBSleepSettings",PS_B_SLEEPING,VTS_PHYSIC_SLEEP_SETTINGS,bodySleeping,GC_SHOWPARAMETER); ////////////////////////////////////////////////////////////////////////// // // Damping REGISTER_CUSTOM_STRUCT("pBDamping",PS_B_DAMPING,VTS_PHYSIC_DAMPING_PARAMETER,bodyDamping,GC_SHOWPARAMETER); ////////////////////////////////////////////////////////////////////////// // // Optimization REGISTER_CUSTOM_STRUCT("pBOptimisation",PS_B_OPTIMISATION,VTS_PHYSIC_ACTOR_OPTIMIZATION,bodyOptimistationSettings,GC_SHOWPARAMETER); REGISTER_STRUCT_AS_ATTRIBUTE("pBOptimisation",PS_B_OPTIMISATION,PHYSIC_BODY_CAT,VTS_PHYSIC_ACTOR_OPTIMIZATION,CKCID_3DOBJECT,bodyOptimistationSettings,true,attRef); ////////////////////////////////////////////////////////////////////////// // // Geometry REGISTER_CUSTOM_STRUCT("pBPivotSettings",PS_B_PIVOT,VTS_PHYSIC_PIVOT_OFFSET,bodyGeomtryOverride,GC_SHOWPARAMETER); REGISTER_STRUCT_AS_ATTRIBUTE("pBPivotSettings",PS_B_PIVOT,PHYSIC_BODY_CAT,VTS_PHYSIC_PIVOT_OFFSET,CKCID_3DOBJECT,bodyGeomtryOverride,true,attRef); ////////////////////////////////////////////////////////////////////////// // // Mass Override REGISTER_CUSTOM_STRUCT("pBMassSettings",PS_B_MASS,VTS_PHYSIC_MASS_SETUP,bodyMassSetup,false); param_type=pm->GetParameterTypeDescription(VTS_PHYSIC_MASS_SETUP); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; REGISTER_STRUCT_AS_ATTRIBUTE("pBMassSettings",PS_B_MASS,PHYSIC_BODY_CAT,VTS_PHYSIC_MASS_SETUP,CKCID_3DOBJECT,bodyMassSetup,true,attRef); ////////////////////////////////////////////////////////////////////////// // // this is the new replacement for the "Object" attribute. // REGISTER_CUSTOM_STRUCT("pBSetup",PS_BODY_SETUP,VTS_PHYSIC_ACTOR,bodySetup,FALSE); REGISTER_STRUCT_AS_ATTRIBUTE("pBSetup",PS_BODY_SETUP,PHYSIC_BODY_CAT,VTS_PHYSIC_ACTOR,CKCID_3DOBJECT,bodySetup,attRef); } <file_sep>/* * Tcp4u v 3.31 Last Revision 09/03/1997 3.31-00 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: udp4u.c * Purpose: main functions for udp protocol management * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" static char szWhat[] ="@(#)Udp4u by Ph. Jounin version 3.31"; /* ------------------------------------------------------------------------- */ /* Fonction de traduction Service -> port */ /* ------------------------------------------------------------------------- */ unsigned short API4U Udp4uServiceToPort (LPCSTR szService) { unsigned short uPort = 0; struct servent far * lpServEnt; if (szService!=NULL) { Tcp4uLog (LOG4U_CALL, "getservbyname service %s", szService); lpServEnt = getservbyname (szService, "udp") ; if (lpServEnt==NULL) Tcp4uLog (LOG4U_ERROR, "getservbyname service %s", szService); else uPort = ntohs (lpServEnt->s_port); } return uPort; } /* Udp4uServiceToPort */ /* ------------------------------------------------------------------------- */ /* initialisation UDP */ /* ------------------------------------------------------------------------- */ int API4U UdpInit (LPUDPSOCK far *pUdp, LPCSTR szHost, unsigned short uRemotePort, unsigned short uLocalPort) { int Rc; SOCKET UdpSock = INVALID_SOCKET; struct sockaddr_in saSendAddr; /* structure identifiant le destinataire */ struct sockaddr_in saBindAddr; /* structure limitant les clients */ Tcp4uLog (LOG4U_PROC, "UdpInit, host %s", szHost); memset (& saBindAddr, 0, sizeof saBindAddr); memset (& saSendAddr, 0, sizeof saSendAddr); /* --- 1. calcul de saSendAddr : RemoteService et szHost */ saSendAddr.sin_family = AF_INET; saSendAddr.sin_port = htons (uRemotePort) ; if (szHost!=NULL) { saSendAddr.sin_addr = Tcp4uGetIPAddr (szHost); if (saSendAddr.sin_addr.s_addr==INADDR_NONE) { Tcp4uLog (LOG4U_ERROR, "UdpInit: host Unknown"); return TCP4U_HOSTUNKNOWN; } } /* szHost is specified */ /* --- autres champs de saBindAddr */ saBindAddr.sin_port = htons (uLocalPort); saBindAddr.sin_family = AF_INET; saBindAddr.sin_addr.s_addr = INADDR_ANY; /* --- Allocation de la socket */ Tcp4uLog (LOG4U_CALL, "socket PF_INET SOCK_DGRAM"); UdpSock = socket (PF_INET, SOCK_DGRAM, 0); if (UdpSock<0) { Tcp4uLog (LOG4U_ERROR, "socket PF_INET SOCK_DGRAM"); return TCP4U_NOMORESOCKET; } /* --- do a bind, thus all packets to be received will come on given port */ Tcp4uLog (LOG4U_CALL, "bind to %s", inet_ntoa (saBindAddr.sin_addr)); Rc = bind (UdpSock, (struct sockaddr far *) & saBindAddr, sizeof(struct sockaddr)); if (Rc<0) { Tcp4uLog (LOG4U_ERROR, "bind to %s", inet_ntoa (saBindAddr.sin_addr)); CloseSocket (UdpSock); return TCP4U_BINDERROR; } /* --- Allocation de la structure */ *pUdp = Calloc (sizeof (UDPSOCK), 1); if (*pUdp==NULL) { CloseSocket (UdpSock); return TCP4U_INSMEMORY; } (*pUdp)->UdpSock = UdpSock; (*pUdp)->saSendAddr = saSendAddr; (*pUdp)->bSemiConnected = FALSE; /* can receive data from any host */ Tcp4uLog (LOG4U_EXIT, "UdpInit"); return TCP4U_SUCCESS; } /* UdpInit */ /* ------------------------------------------------------------------------ */ /* UdpBind: Restrict socket to listen only from previous client */ /* ------------------------------------------------------------------------ */ int API4U UdpBind (LPUDPSOCK pUdp, BOOL bFilter, int nMode) { Tcp4uLog (LOG4U_PROC, "UdpBind Mode %s", nMode==UDP4U_CLIENT ? "client" : "server"); if (bFilter) { switch (nMode) { /* le client ne peut recevoir que de la machine serveur */ /* le serveur que depuis la machine d'ou il a deja recu des infos */ /* en mode serveur, l'adresse de destination devient l'adresse */ /* du dernier host. */ case UDP4U_CLIENT : pUdp->saFilter = pUdp->saSendAddr.sin_addr ; break; case UDP4U_SERVER : pUdp->saFilter = pUdp->saRecvAddr.sin_addr; pUdp->saSendAddr = pUdp->saRecvAddr; break; default : return TCP4U_ERROR; } /* selon mode */ } /* si filtre positionne */ /* filtre ou pas filtre */ pUdp->bSemiConnected = bFilter; Tcp4uLog (LOG4U_EXIT, "UdpBind"); return TCP4U_SUCCESS; } /* UdpBind */ /* ------------------------------------------------------------------------- */ /* destructeur : UdpCleanup */ /* ------------------------------------------------------------------------- */ int API4U UdpCleanup (LPUDPSOCK Udp) { int Rc; Tcp4uLog (LOG4U_PROC, "UdpCleanup sock %d", Udp->UdpSock); Tcp4uLog (LOG4U_CALL, "closesocket sock %d", Udp->UdpSock); Rc = CloseSocket (Udp->UdpSock); if (Rc!=0) { Tcp4uLog (LOG4U_ERROR, "closesocket sock %d", Udp->UdpSock); return TCP4U_ERROR; } Free (Udp); Tcp4uLog (LOG4U_EXIT, "UdpCleanup"); return TCP4U_SUCCESS; } /* UdpCleanup */ /* ------------------------------------------------------------------------- */ /* Envoi d'une trame UDP */ /* ------------------------------------------------------------------------- */ int API4U UdpSend (LPUDPSOCK Udp, LPCSTR sData, int nDataSize, BOOL bHighPriority, HFILE hLogFile) { int Rc; Tcp4uLog (LOG4U_PROC, "UdpSend sock %d, %d bytes to be sent ", Udp->UdpSock, nDataSize); Rc = InternalUdpSend (Udp, sData, nDataSize, bHighPriority, hLogFile); if (Rc==TCP4U_SUCCESS) Tcp4uDump (sData, nDataSize, DUMP4U_SENT); Tcp4uLog (LOG4U_EXIT, "UdpSend"); return Rc; } /* UdpSend */ int InternalUdpSend (LPUDPSOCK Udp,LPCSTR sData, int nDataSize, BOOL bHighPriority, HFILE hLogFile) { int Rc; Tcp4uLog (LOG4U_CALL, "sendto host %s sock %d, %d bytes to be sent ", inet_ntoa (Udp->saSendAddr.sin_addr), Udp->UdpSock, nDataSize); Rc = sendto ( Udp->UdpSock, sData, nDataSize, bHighPriority ? MSG_OOB : 0, (struct sockaddr far *) &Udp->saSendAddr, sizeof Udp->saSendAddr); /* --- Analyser la valeur retounee */ if (Rc<0) { Tcp4uLog (LOG4U_ERROR, "sendto host %s", inet_ntoa (Udp->saSendAddr.sin_addr) ); return TCP4U_ERROR; } if (hLogFile!=HFILE_ERROR) Write (hLogFile, sData, Rc); return Rc==nDataSize ? TCP4U_SUCCESS : TCP4U_OVERFLOW; } /* InternalUdpSend */ /* ------------------------------------------------------------------------- */ /* La fonction reciproque : UdpRecv */ /* ------------------------------------------------------------------------- */ int API4U UdpRecv (LPUDPSOCK pUdp, LPSTR sData, int nDataSize, unsigned uTimeOut, HFILE hLogFile) { int Rc; Tcp4uLog (LOG4U_PROC, "UdpRecv sock %d, buffer %d bytes", pUdp->UdpSock, nDataSize); Rc = InternalUdpRecv (pUdp, sData, nDataSize, uTimeOut, hLogFile); if (Rc>=TCP4U_SUCCESS) Tcp4uDump (sData, Rc, DUMP4U_RCVD); Tcp4uLog (LOG4U_EXIT, "UdpRecv %d bytes received", Rc); return Rc; } /* UdpRecv */ int InternalUdpRecv (LPUDPSOCK pUdp, LPSTR sData, int nDataSize, unsigned uTimeOut, HFILE hLogFile) { int Rc; struct timeval TO; fd_set ReadMask; /* select mask */ int Len = sizeof (struct sockaddr_in); if (pUdp->UdpSock==INVALID_SOCKET) return TCP4U_ERROR; /* bug 1 : Timeout kept in Loop, should be decremented */ /* (can be done by the select function) */ /* bug 2 : some frames are read even if they do not concern this process */ TO.tv_sec = (long) uTimeOut; /* secondes */ TO.tv_usec = 0; /* microsecondes */ do { FD_ZERO (& ReadMask); /* mise a zero du masque */ FD_SET (pUdp->UdpSock, & ReadMask); /* Attente d'evenement en lecture */ /* s+1 normally unused but better for a lot of bugged TCP Stacks */ Tcp4uLog (LOG4U_CALL, "select Timeout %d", uTimeOut); Rc = select ( pUdp->UdpSock+1, & ReadMask, NULL, NULL, uTimeOut==0? NULL: &TO); if (Rc<0) { Tcp4uLog (LOG4U_ERROR, "select"); return IsCancelled() ? TCP4U_CANCELLED : TCP4U_ERROR; } if (Rc==0) { Tcp4uLog (LOG4U_ERROR, "select: Timeout"); return TCP4U_TIMEOUT; /* timeout en reception */ } Tcp4uLog (LOG4U_CALL, "recvfrom host %s", inet_ntoa (pUdp->saRecvAddr.sin_addr)); Rc = recvfrom (pUdp->UdpSock, sData, nDataSize, 0, (struct sockaddr far *) & pUdp->saRecvAddr, & Len); if (Rc<0) { Tcp4uLog (LOG4U_ERROR, "recvfrom"); return TCP4U_ERROR; } } while ( pUdp->bSemiConnected && memcmp (& pUdp->saRecvAddr.sin_addr, & pUdp->saFilter, sizeof pUdp->saFilter) != 0); if (hLogFile!=HFILE_ERROR) Write (hLogFile, sData, Rc); return Rc; } /* InternalUdpRecv */ <file_sep>// OGGReader.cpp: implementation of the OGGReader class. // ////////////////////////////////////////////////////////////////////////////////////////// #include "StdAfx.h" //#include "URLMon.h" #include <vorbis/codec.h> #include <vorbis/vorbisfile.h> /* debug context CKContext *g_pContext; CKERROR InitInstance(CKContext* context) { g_pContext = context; return CK_OK; } */ ////////////////////////////////////////////////////////////////////////////////////////// // Construction OGGReader::OGGReader() { // Init data members m_FormatInfo.cbSize = 0; m_FormatInfo.nAvgBytesPerSec = 0; m_FormatInfo.nBlockAlign = 0; m_FormatInfo.nChannels = 0; m_FormatInfo.nSamplesPerSec = 0; m_FormatInfo.wBitsPerSample = 0; m_FormatInfo.wFormatTag = 0; m_EOF = 0; m_CurrentSection = -1; m_pBuffer = new BYTE[BUFFERSIZE]; m_BufferDataRead = 0; m_FileOpen = false; } ////////////////////////////////////////////////////////////////////////////////////////// // Destruction OGGReader::~OGGReader() { // Close Ogg file if(m_FileOpen) ov_clear(&m_VorbisFile); delete [] m_pBuffer; } //CKERROR OGGReader::ReadMemory(void* memory, int size) //{ // return CKSOUND_READER_GENERICERR; //} ////////////////////////////////////////////////////////////////////////////////////////// // Opens a file bool isExist(const char* filepath) { FILE* f = 0; if (filepath && (f=fopen(filepath,"r")) != 0) fclose(f); return f != 0; } CKERROR OGGReader::OpenFile(char *file) { CKERROR fRtn = CK_OK; // assume success int ovResult; if (!file || strlen(file) == 0) goto OPEN_ERROR; if(isExist(file) == FALSE) goto OPEN_ERROR; // Make a C-style file stream out of the cached path FILE *pOggFile; if (!(pOggFile = fopen(file, "rb"))) goto OPEN_ERROR; // Open the vorbis file ovResult = ov_open(pOggFile, &m_VorbisFile, NULL, 0); if(ovResult < 0) goto OPEN_ERROR; m_FileOpen = true; vorbis_info *pVorbisInfo; if(!(pVorbisInfo = ov_info(&m_VorbisFile, -1))) { // g_pContext->OutputToConsole("Ogg Error", false); goto OPEN_ERROR; } m_FormatInfo.wFormatTag = 1; m_FormatInfo.nChannels = pVorbisInfo->channels; m_FormatInfo.nSamplesPerSec = pVorbisInfo->rate; m_FormatInfo.wBitsPerSample = BITSPERSAMPLE; m_FormatInfo.nBlockAlign = (pVorbisInfo->channels * m_FormatInfo.wBitsPerSample) / 8; // m_FormatInfo.nAvgBytesPerSec = ov_bitrate(m_VorbisFile, -1) / 8; m_FormatInfo.nAvgBytesPerSec = m_FormatInfo.nBlockAlign * m_FormatInfo.nSamplesPerSec; m_FormatInfo.cbSize = 0; /* sprintf(str, "Channels: %i", m_FormatInfo.nChannels); g_pContext->OutputToConsole(str, false); sprintf(str, "SamplesPerSec: %i", m_FormatInfo.nSamplesPerSec); g_pContext->OutputToConsole(str, false); sprintf(str, "BlockAlign: %i", m_FormatInfo.nBlockAlign); g_pContext->OutputToConsole(str, false); sprintf(str, "AvgBytesPerSec: %i", m_FormatInfo.nAvgBytesPerSec); g_pContext->OutputToConsole(str, false); */ //return CK_OK; return fRtn; OPEN_ERROR: // Handle all errors here fRtn = CKSOUND_READER_GENERICERR; // Close Ogg file //ov_clear(&m_VorbisFile); return CKSOUND_READER_GENERICERR; } ////////////////////////////////////////////////////////////////////////////////////////// // Decodes 'n' stuff // Decodes next chunk of data, use get data buffer to get decoded data CKERROR OGGReader::Decode() { m_BufferDataRead = 0; int startSection = m_CurrentSection; long result = ov_read(&m_VorbisFile, (char *)m_pBuffer, BUFFERSIZE, 0, 2, 1, &m_CurrentSection); // char str[256]; // sprintf(str, "ov_read result: %i", result); // g_pContext->OutputToConsole(str, true); // End Of File if (result == 0) { m_EOF = true; //g_pContext->OutputToConsole("E-O-F", true); return CKSOUND_READER_EOF; } // Error in the bitstram else if (result < 0) { //g_pContext->OutputToConsole("Error in the bitstram in Decode", false); return CKSOUND_READER_GENERICERR; } // Successfully read some stuff m_BufferDataRead = result; if (m_CurrentSection != startSection) { vorbis_info *pVorbisInfo; m_FormatInfo.wFormatTag = 1; m_FormatInfo.nChannels = pVorbisInfo->channels; m_FormatInfo.nSamplesPerSec = pVorbisInfo->rate; m_FormatInfo.wBitsPerSample = BITSPERSAMPLE; m_FormatInfo.nBlockAlign = (pVorbisInfo->channels * m_FormatInfo.wBitsPerSample) / 8; // m_FormatInfo.nAvgBytesPerSec = ov_bitrate(m_VorbisFile, -1) / 8; m_FormatInfo.nAvgBytesPerSec = m_FormatInfo.nBlockAlign * m_FormatInfo.nSamplesPerSec; m_FormatInfo.cbSize = 0; } return CK_OK; } ////////////////////////////////////////////////////////////////////////////////////////// // Gets the last decoded buffer CKERROR OGGReader::GetDataBuffer(BYTE **buf, int *size) { *buf = m_pBuffer; *size = m_BufferDataRead; return CK_OK; } ////////////////////////////////////////////////////////////////////////////////////////// // Gets the ogg format of decoded datas CKERROR OGGReader::GetWaveFormat(CKWaveFormat *wfe) { memcpy(wfe, &m_FormatInfo, sizeof(CKWaveFormat)); return CK_OK; } ////////////////////////////////////////////////////////////////////////////////////////// // Gets whole decoded data size int OGGReader::GetDataSize() { return (int)(ov_pcm_total(&m_VorbisFile, -1) * m_FormatInfo.nBlockAlign); // * m_FormatInfo.nSamplesPerSec * m_FormatInfo.nBlockAlign); } ////////////////////////////////////////////////////////////////////////////////////////// // Gets the play time length int OGGReader::GetDuration() { return (int)(ov_time_total(&m_VorbisFile, -1) * 1000); } ////////////////////////////////////////////////////////////////////////////////////////// // Seek some shit CKERROR OGGReader::Seek(int pos) { if(ov_seekable(&m_VorbisFile)) { ov_time_seek(&m_VorbisFile, pos); } else { //g_pContext->OutputToConsole("Tried to seek a non-seekable file!", false); return CKSOUND_READER_GENERICERR; } return CK_OK; } ////////////////////////////////////////////////////////////////////////////////////////// // Play CKERROR OGGReader::Play() { return CK_OK; } ////////////////////////////////////////////////////////////////////////////////////////// // Stop CKERROR OGGReader::Stop() { return CK_OK; } ////////////////////////////////////////////////////////////////////////////////////////// // Release void OGGReader::Release() { delete this; } <file_sep>#include "InitMan.h" #include "CKAll.h" #include "VSLManagerSDK.h" #ifdef RACKNET #include <network/rNetServer.h> #include "network/racknet/NetworkStructures.h" #include "network/racknet/PacketEnumerations.h" #include "network/laser_point.h" #include "network/rNetStructs.h" #pragma comment (lib,"RakNet.lib") extern InitMan *_im; static rNetServer *server = NULL; unsigned char GetPacketIdentifier(Packet *p); laser_pointers *lPointers; lpoint pointers[5]; boolean recieved =false; int packetDelay; int prevPacketCount; int pCount =0; int GetPacketDT(); ////////////////////////////////////////////////////////////////////////// BOOL rNetServerCreate(const char*server_name,int server_port); BOOL rNetServerStart(){ return server->start(); } void rNetServerDestroy(){ if(server->realInterface){ server->destroy(); } } int rNetServerGetClientCount(){ return server->GetClientCount(); } int rNetServerGetBytesReceivedPerSecond(){ return server->realInterface->GetBytesReceivedPerSecond(); return -1; } int GetPacketOutputBufferSize(){ return server->realInterface->GetPacketOutputBufferSize(); } int rGetPacketsPerSecond(){ int just = server->realInterface->GetReceivedPacketCount(); int res = just - prevPacketCount; prevPacketCount = just; return res; } int rGetPaketCount(){ return server->realInterface->GetReceivedPacketCount(); } ////////////////////////////////////////////////////////////////////////// lpoint GetCoord(int index){ if(recieved){ return pointers[index]; } return lpoint(-1,-1,-1); } VxRect rNetRecieve(){ Packet* p = server->realInterface->Receive(); if (p!=0){ recieved =true; lPointers = ((laser_pointers*)p->data); /* for (int i = 0 ; i < 10 ; i++){ pointers[i].x = lPointers->LArray[i].x; pointers[i].y = lPointers->LArray[i].y; } //Vx2DVector coord = GetLPCoord(0); char buffer[400]; lpoint coord = GetCoord(0); sprintf(buffer,"x : %d, y: %d",coord.x,coord.y); _im->m_Context->OutputToConsole(buffer,false); */ VxRect m (lPointers->LArray[0].x,lPointers->LArray[0].y,lPointers->LArray[0].x,lPointers->LArray[0].x); // server->realInterface->DeallocatePacket(p); // server->realInterface->DesynchronizeAllMemory(); pCount =1; return m; } pCount = -1; recieved = false; return VxRect(-1,-1,-1,-1); } /************************************************************************/ /* */ /************************************************************************/ Vx2DVector GetLPCoord(int index){ if (recieved) return Vx2DVector((const float)pointers[index].x,(const float)pointers[index].y); return Vx2DVector(-1,-1); } laser_pointers& GetLaserPointerArray(){ /* Packet* p = server->realInterface->Receive(); if (p!=0){ recieved =true; laser_pointers *tmpArray = ((laser_pointers*)p->data); for (int i = 0 ; i < 99 ; i++){ pointers[i].x = tmpArray->LArray[i].x; pointers[i].y = tmpArray->LArray[i].y; } char buffer[400]; SYSTEMTIME time; GetSystemTime(&time); packetDelay = time.wMilliseconds - tmpArray->sStamp.miliseconds; WORD sDT = time.wSecond - tmpArray->sStamp.seconds; //sprintf(buffer,"dtSec : %d, dtMSec: %d", sDT, msDT ); sprintf(buffer,"x : %f, y: %f", pointers[0].x ,pointers[0].y); _im->m_Context->OutputToConsole(buffer,false); server->realInterface->DeallocatePacket(p); server->realInterface->DesynchronizeAllMemory(); return laser_pointers(); } recieved = false ; */ return laser_pointers(); } void laser_pointers::GetCoord(Vx2DVector& target,int index){ if (lPointers){ target.x = (float)pointers[index].x; target.y = (float)pointers[index].y; } } void InitMan::RegisterRacknetVSL(){ STARTVSLBIND(m_Context) /************************************************************************/ /* Variable|Parameter Stuff */ /************************************************************************/ DECLAREFUN_C_2(BOOL,rNetServerCreate,const char*, int ) DECLAREFUN_C_0(BOOL,rNetServerStart) DECLAREFUN_C_0(void,rNetServerDestroy) DECLAREFUN_C_0(int,rGetPaketCount) DECLAREFUN_C_0(int,GetPacketDT) DECLAREFUN_C_0(int,rGetPacketsPerSecond) DECLAREFUN_C_0(int,rNetServerGetClientCount) DECLAREFUN_C_0(int,rNetServerGetBytesReceivedPerSecond) DECLAREFUN_C_0(VxRect,rNetRecieve) DECLAREFUN_C_0(int,GetPacketOutputBufferSize) DECLAREOBJECTTYPE(lpoint) DECLAREMEMBER(lpoint,int,x) DECLAREMEMBER(lpoint,int,y) DECLAREFUN_C_1(lpoint,GetCoord,int) DECLAREPOINTERTYPE(laser_pointers) DECLAREMETHODC_1(laser_pointers,lpoint,GetPointByIndex,int) DECLAREFUN_C_0(laser_pointers&,GetLaserPointerArray) DECLAREMETHODC_2(laser_pointers,void,GetCoord,Vx2DVector&,int) DECLAREFUN_C_1(Vx2DVector,GetLPCoord,int) STOPVSLBIND } CKERROR InitMan::PostProcess(){ /* if (server->realInterface && server->isStarted){ Packet* p = server->realInterface->Receive(); if (p!=0){ lPointers = ((laser_pointers*)p->data); m_Context->OutputToConsole("processing incoming packets",false); /* char buffer[400]; SYSTEMTIME time; GetSystemTime(&time); packetDelay = time.wMilliseconds - lPointers->sStamp.miliseconds; WORD sDT = time.wSecond - lPointers->sStamp.seconds; */ /* for (int i = 0 ; i < 4 ; i++) { //pointers[i].x = lPointers->LArray[i].x; //pointers[i].y = lPointers->LArray[i].y; }*/ /* char buffer[400]; lpoint coord = GetCoord(0); sprintf(buffer,"x : %d, y: %d",coord.x,coord.y); m_Context->OutputToConsole(buffer,false); */ //server->realInterface->DeallocatePacket(p); //server->realInterface->DesynchronizeAllMemory(); //} return CK_OK; //} } /************************************************************************/ /* */ /************************************************************************/ unsigned char GetPacketIdentifier(Packet *p) { if (p==0) return 255; if ((unsigned char)p->data[0] == ID_TIMESTAMP) { assert(p->length > sizeof(unsigned char) + sizeof(unsigned long)); return (unsigned char) p->data[sizeof(unsigned char) + sizeof(unsigned long)]; } else return (unsigned char) p->data[0]; } ////////////////////////////////////////////////////////////////////////// BOOL rNetServerCreate(const char*server_name,int server_port){ server = new rNetServer(server_name,server_port); lPointers = new laser_pointers(); return true; } ////////////////////////////////////////////////////////////////////////// int GetPacketDT(){ return packetDelay; } #endif <file_sep>// OGGReader.h: interface for the OGGReader class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_OGGReader_H__1ACADF42_5A21_11D3_BA37_00105A669BB5__INCLUDED_) #define AFX_OGGReader_H__1ACADF42_5A21_11D3_BA37_00105A669BB5__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <vorbis/codec.h> #include <vorbis/vorbisfile.h> // buffer and size #define BUFFERSIZE 16384 #define BITSPERSAMPLE 16 //CKERROR InitInstance(CKContext *context); class OGGReader : public CKSoundReader { public: OGGReader(); virtual ~OGGReader(); virtual void Release(); virtual CKPluginInfo * GetReaderInfo(); // Get Options Count virtual int GetOptionsCount() { return 0; } // Get Options Description virtual CKSTRING GetOptionDescription(int i) {return NULL; } // Get Flags virtual CK_DATAREADER_FLAGS GetFlags() { return (CK_DATAREADER_FLAGS) (CK_DATAREADER_FILELOAD | CK_DATAREADER_MEMORYLOAD); } public: // Opens a file virtual CKERROR OpenFile(char *file); //virtual CKERROR ReadMemory(void* memory, int size); // Decodes next chunk of data, use get data buffer to get decoded data virtual CKERROR Decode(); // Gets the last decoded buffer virtual CKERROR GetDataBuffer(BYTE **buf, int *size); // Gets the wave format of decoded datas virtual CKERROR GetWaveFormat(CKWaveFormat *wfe); // Gets whole decoded data size virtual int GetDataSize(); // Gets the play time length virtual int GetDuration(); // Seek virtual CKERROR Seek(int pos); // Play; virtual CKERROR Play(); // Stop virtual CKERROR Stop(); virtual CKERROR Pause(){return CK_OK;} virtual CKERROR Resume(){return CK_OK;} protected: /* int DataRead(int count, char* buf); int DataRead(long pos, int count, char* buf); int DataSeek(long pos); */ OggVorbis_File m_VorbisFile; CKWaveFormat m_FormatInfo; bool m_EOF; bool m_FileOpen; int m_CurrentSection; /* UINT m_nBlockAlign; // ogg data block alignment spec UINT m_nAvgDataRate; // average ogg data rate UINT m_nBytesPlayed; // offset into data chunk BOOL m_IsPcm; unsigned long m_OutDataSize; // size of in data chunk unsigned long m_InDataSize; // size of out data chunk unsigned long m_InDataCursor; */ // PCM Data BYTE *m_pBuffer; // Data Buffer; int m_BufferDataRead; }; #endif // !defined(AFX_OGGReader_H__1ACADF42_5A21_11D3_BA37_00105A669BB5__INCLUDED_) <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBGetParameterDecl(); CKERROR CreatePBGetParameterProto(CKBehaviorPrototype **pproto); int PBGetParameter(const CKBehaviorContext& behcontext); CKERROR PBGetParameterCB(const CKBehaviorContext& behcontext); using namespace vtTools; using namespace BehaviorTools; enum bbI_Inputs { bbI_BodyReference, }; #define BB_SSTART 0 enum bInputs { bbO_CollisionGroup, bbO_GroupsMask, bbO_Flags, bbO_TFlags, bbO_LinDamp, bbO_AngDamp, bbO_MassOffset, bbO_ShapeOffset, }; BBParameter pOutMap12[] = { BB_SPOUT(bbO_CollisionGroup,CKPGUID_INT,"Collision Group","0.0"), BB_SPOUT(bbO_GroupsMask,VTS_FILTER_GROUPS,"Groups Mask",""), BB_SPOUT(bbO_Flags,VTF_BODY_FLAGS,"Body Flags",""), BB_SPOUT(bbO_TFlags,VTF_BODY_TRANS_FLAGS,"Transformation Lock Flags",""), BB_SPOUT(bbO_LinDamp,CKPGUID_FLOAT,"Linear Damping","0.0"), BB_SPOUT(bbO_AngDamp,CKPGUID_FLOAT,"Angular Damping","0.0"), BB_SPOUT(bbO_MassOffset,CKPGUID_VECTOR,"Mass Offset","0.0"), BB_SPOUT(bbO_ShapeOffset,CKPGUID_VECTOR,"Pivot Offset","0.0"), }; #define gOPMap pOutMap12 CKERROR PBGetParameterCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; int cb = behcontext.CallbackMessage; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_POMAP(gOPMap,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PMAP(gOPMap,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PMAP(gOPMap,BB_SSTART); break; } } return CKBR_OK; } CKObjectDeclaration *FillBehaviorPBGetParameterDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBGetPar"); od->SetCategory("Physic/Body"); od->SetDescription("Retrieves rigid bodies parameters"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x59a670a,0x59a557ec)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBGetParameterProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBGetParameterProto // FullName: CreatePBGetParameterProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBGetParameterProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBGetPar"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /* PBGetPar PBGetPar is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Retrieves various physical informations.<br> <h3>Technical Information</h3> \image html PBGetPar.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pout">Collisions Group: </SPAN>Which collision group this body or the sub shape is part of.See pRigidBody::getCollisionsGroup(). <BR> <SPAN CLASS="pout">Groupsmask: </SPAN>Sets 128-bit mask used for collision filtering. It can be sub shape specific.See comments for ::pGroupsMask and pRigidBody::setGroupsMask() <BR> <SPAN CLASS="pout">Flags: </SPAN>The current flags. See pRigidBody::getFlags() <br> <SPAN CLASS="pout">Transformation Locks: </SPAN>Current transformations locks. <BR> <SPAN CLASS="pout">Linear Damping: </SPAN>The linear damping scale. <BR> <SPAN CLASS="pout">Angular Damping: </SPAN>The linear damping scale. <BR> <SPAN CLASS="pout">Mass Offset: </SPAN>The mass center in the bodies local space. <BR> <SPAN CLASS="pout">Pivot Offset: </SPAN>The shapes position in the bodies local space. See pRigidBody::getLocalShapePosition(). <BR> <h3>Warning</h3> */ proto->SetBehaviorCallbackFct( PBGetParameterCB ); BB_EVALUATE_SETTINGS(gOPMap); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBGetParameter); *pproto = proto; return CK_OK; } //************************************ // Method: PBGetParameter // FullName: PBGetParameter // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBGetParameter(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; body = GetPMan()->getBody(target); if (!body) bbErrorME("No Reference Object specified"); BB_DECLARE_PMAP; BBSParameter(bbO_CollisionGroup); BBSParameter(bbO_GroupsMask); BBSParameter(bbO_Flags); BBSParameter(bbO_TFlags); BBSParameter(bbO_LinDamp); BBSParameter(bbO_AngDamp); BBSParameter(bbO_MassOffset); BBSParameter(bbO_ShapeOffset); body->recalculateFlags(0); BB_O_SET_VALUE_IF(int,bbO_CollisionGroup,body->getCollisionsGroup(target)); BB_O_SET_VALUE_IF(int,bbO_Flags,body->getFlags()); BB_O_SET_VALUE_IF(int,bbO_TFlags,body->getTransformationsLockFlags()); BB_O_SET_VALUE_IF(float,bbO_LinDamp,body->getLinearDamping()); BB_O_SET_VALUE_IF(float,bbO_AngDamp,body->getAngularDamping()); BB_O_SET_VALUE_IF(VxVector,bbO_MassOffset,body->getMassOffset()); BB_O_SET_VALUE_IF(VxVector,bbO_ShapeOffset,body->getPivotOffset(target)); if (sbbO_GroupsMask) { pGroupsMask gMask = body->getGroupsMask(target); CKParameterOut *poutMask = beh->GetOutputParameter(BB_OP_INDEX(bbO_GroupsMask)); if (poutMask) { pFactory::Instance()->copyTo(poutMask,gMask); } } } beh->ActivateOutput(0); return 0; } //************************************ // Method: PBGetParameterCB // FullName: PBGetParameterCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ <file_sep>#ifndef __xDistributedProperty_h #define __xDistributedProperty_h #include "xNetTypes.h" namespace TNL { class BitStream; } class xPredictionSetting; class xDistributedPropertyInfo; class xDistributedProperty { public: xDistributedProperty(xDistributedPropertyInfo *propInfo); virtual ~xDistributedProperty(){} xDistributedPropertyInfo *m_PropertyInfo; xDistributedPropertyInfo * getPropertyInfo() { return m_PropertyInfo; } void setPropertyInfo(xDistributedPropertyInfo * val) { m_PropertyInfo = val; } xTimeType mLastTime; xTimeType getLastTime() const { return mLastTime; } void setLastTime(xTimeType val) { mLastTime = val; } xTimeType mThresoldTicker; xTimeType getThresoldTicker() const { return mThresoldTicker; } void setThresoldTicker(xTimeType val) { mThresoldTicker = val; } xTimeType mCurrentTime; xTimeType mLastDeltaTime; xTimeType getCurrentTime() const { return mCurrentTime; } void setCurrentTime(xTimeType val) { mCurrentTime = val; } int mFlags; TNL::U32 mGhostId; TNL::U32 getGhostId() const { return mGhostId; } void setGhostId(TNL::U32 val) { mGhostId = val; } int getFlags() const { return mFlags; } void setFlags(int val) { mFlags = val; } virtual void pack(TNL::BitStream *bstream); virtual void unpack(TNL::BitStream *bstream,float sendersOneWayTime); virtual int getBlockIndex(){return m_BlockIndex;} virtual void setBlockIndex(int index){m_BlockIndex = index;} int m_BlockIndex; float mLastTime2; float mLastDeltaTime2; float mThresoldTicker2; void advanceTime(xTimeType time1,float lastDeltaTime2 ); xPredictionSetting *m_PredictionSettings; xPredictionSetting *getPredictionSettings() const { return m_PredictionSettings; } void setPredictionSettings(xPredictionSetting * val) { m_PredictionSettings = val; } virtual void updateGhostValue(TNL::BitStream *stream){} virtual void updateFromServer(TNL::BitStream *stream){} float m_ownersOneWayTime; float getOwnersOneWayTime() const { return m_ownersOneWayTime; } void setOwnersOneWayTime(float val) { m_ownersOneWayTime = val; } int mValueState; int getValueState() const { return mValueState; } void setValueState(int val) { mValueState = val; } virtual uxString print(TNL::BitSet32 flags); }; #endif <file_sep>#ifndef __P_VEHICLE_GEARS_H__ #define __P_VEHICLE_GEARS_H__ #include "pVehicleTypes.h" #include "NxArray.h" #define NX_VEHICLE_MAX_NB_GEARS 32 /** \addtogroup Vehicle @{ */ class MODULE_API pVehicleGearDesc { public: pVehicleGearDesc() { setToDefault(); } void setToDefault(); void setToCorvette(); bool isValid() const; int getMaxNumOfGears() const { return NX_VEHICLE_MAX_NB_GEARS; } //NxArray<pLinearInterpolation> forwardGears; //NxArray<float> forwardGearRatios; int nbForwardGears; pLinearInterpolation forwardGears[NX_VEHICLE_MAX_NB_GEARS]; float forwardGearRatios[NX_VEHICLE_MAX_NB_GEARS]; //NxLinearInterpolationValues backwardGear; float backwardGearRatio; }; /** \brief A abstract base class for a vehicle gear box. */ class MODULE_API pVehicleGears { public: //NxArray<NxLinearInterpolationValues> _forwardGears; //NxArray<float> _forwardGearRatios; int _nbForwardGears; pLinearInterpolation _forwardGears[NX_VEHICLE_MAX_NB_GEARS]; float _forwardGearRatios[NX_VEHICLE_MAX_NB_GEARS]; //NxLinearInterpolationValues _backwardGear; float _backwardGearRatio; int _curGear; public: pVehicleGears(): _curGear(1) { } //static NxVehicleGears* createVehicleGears(const NxVehicleGearDesc& gearDesc); float getCurrentRatio() const; float getRatio(int gear) const; int getGear() const { return _curGear; } int getMaxGear() const { return _nbForwardGears; } void gearUp() { _curGear = NxMath::min(_curGear+1, (int)_nbForwardGears); } void gearDown() { _curGear = NxMath::max(_curGear-1, -1); } }; /** @} */ #endif<file_sep>/****************************************************************************** File : CustomPlayer.cpp Description: This file contains the CCustomPlayer class which is the "interface" with the Virtools SDK. All other files are Windows/MFC specific code. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ #include "CPStdAfx.h" #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #if defined(CUSTOM_PLAYER_STATIC) // include file used for the static configuration #include "CustomPlayerStaticLibs.h" #include "CustomPlayerRegisterDlls.h" #endif extern CCustomPlayerApp theApp; extern CCustomPlayer* thePlayer; BOOL CCustomPlayer::_FinishLoad() { // retrieve the level m_Level = m_CKContext->GetCurrentLevel(); if (!m_Level) { MessageBox(NULL,CANNOT_FIND_LEVEL,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } if(m_RenderContext) { // Add the render context to the level m_Level->AddRenderContext(m_RenderContext,TRUE); // Take the first camera we found and attach the viewpoint to it. // (in case it is not set by the composition later) const XObjectPointerArray cams = m_CKContext->GetObjectListByType(CKCID_CAMERA,TRUE); if(cams.Size()) { m_RenderContext->AttachViewpointToCamera((CKCamera*)cams[0]); } // Hide curves ? int curveCount = m_CKContext->GetObjectsCountByClassID(CKCID_CURVE); CK_ID* curve_ids = m_CKContext->GetObjectsListByClassID(CKCID_CURVE); for (int i=0;i<curveCount;++i) { CKMesh* mesh = ((CKCurve*)m_CKContext->GetObject(curve_ids[i]))->GetCurrentMesh(); if(mesh) mesh->Show(CKHIDE); } // retrieve custom player attributes // from an exemple about using this attributes see sample.cmo which is delivered with this player sample // simply set the "Quit" attribute to quit the application m_QuitAttType = m_AttributeManager->GetAttributeTypeByName("Quit"); // simply set the "Switch Fullscreen" attribute to make the player switch between fullscreen and windowed mode m_SwitchFullscreenAttType = m_AttributeManager->GetAttributeTypeByName("Switch Fullscreen"); // simply set the "Switch Resolution" attribute to make the player change its resolution according // to the "Windowed Resolution" or "Fullscreen Resolution" (depending on the current mode) m_SwitchResolutionAttType = m_AttributeManager->GetAttributeTypeByName("Switch Resolution"); // simply set the "Switch Mouse Clipping" attribute to make the player clip/unclip the mouse to the render window m_SwitchMouseClippingAttType = m_AttributeManager->GetAttributeTypeByName("Switch Mouse Clipping"); // the windowed resolution m_WindowedResolutionAttType = m_AttributeManager->GetAttributeTypeByName("Windowed Resolution"); // the fullscreen resolution m_FullscreenResolutionAttType = m_AttributeManager->GetAttributeTypeByName("Fullscreen Resolution"); // the fullscreen bpp m_FullscreenBppAttType = m_AttributeManager->GetAttributeTypeByName("Fullscreen Bpp"); // remove attributes (quit,switch fullscreen and switch resolution) if present if (m_Level->HasAttribute(m_QuitAttType)) { m_Level->RemoveAttribute(m_QuitAttType); } if (m_Level->HasAttribute(m_SwitchFullscreenAttType)) { m_Level->RemoveAttribute(m_SwitchFullscreenAttType); } if (m_Level->HasAttribute(m_SwitchResolutionAttType)) { m_Level->RemoveAttribute(m_SwitchResolutionAttType); } if (m_Level->HasAttribute(m_SwitchMouseClippingAttType)) { m_Level->RemoveAttribute(m_SwitchMouseClippingAttType); } // set the attributes so it match the current player configuration _SetResolutions(); // set a fake last cmo loaded // we build a filename using the exe full filename // remplacing exe by vmo. { char path[MAX_PATH]; if (::GetModuleFileName(0,path,MAX_PATH)) { char drive[MAX_PATH]; char dir[MAX_PATH]; char filename[MAX_PATH]; char ext[MAX_PATH]; _splitpath(path,drive,dir,filename,ext); _makepath(path,drive,dir,filename,"vmo"); m_CKContext->SetLastCmoLoaded(path); } } } // we launch the default scene m_Level->LaunchScene(NULL); // ReRegister OnClick Message in case it changed m_MsgClick = m_MessageManager->AddMessageType("OnClick"); m_MsgDoubleClick = m_MessageManager->AddMessageType("OnDblClick"); // render the first frame if (m_RenderContext) m_RenderContext->Render(); return TRUE; } CKERROR CCustomPlayer::_Load(const char* str) { // the composition from a file // validate the filename if(!str || !(*str) || strlen(str)<=0) { return FALSE; } // here we decompose the loading from a file to manage the missing guids case // create a ckfile CKFile *f = m_CKContext->CreateCKFile(); XString resolvedfile = str; // resolve the filename using the pathmanager { CKPathManager *pm = m_CKContext->GetPathManager(); if(pm) { pm->ResolveFileName(resolvedfile,0); } } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // dbo - modification - displaying a bitmap during the load process // init - BEGIN ////////////////////////////////////////////////////////////////////////// CKSprite* loadingScreen = NULL; ////////////////////////////////////////////////////////////////////////// // dbo mod - init - END ////////////////////////////////////////////////////////////////////////// // open the file DWORD res = CKERR_INVALIDFILE; res = f->OpenFile(resolvedfile.Str(),(CK_LOAD_FLAGS) (CK_LOAD_DEFAULT | CK_LOAD_CHECKDEPENDENCIES)); if (res!=CK_OK) { // something failed if (res==CKERR_PLUGINSMISSING) { // log the missing guids _MissingGuids(f,resolvedfile.CStr()); } //m_CKContext->DeleteCKFile(f); //return res; } CKPathSplitter ps(resolvedfile.Str()); CKPathMaker mp(ps.GetDrive(),ps.GetDir(),NULL,NULL); if(strcmp(mp.GetFileName(),CKGetStartPath())){ CKPathManager *pm = m_CKContext->GetPathManager(); XString XStr = XString(mp.GetFileName()); pm->AddPath(BITMAP_PATH_IDX,XStr); XStr = XString(mp.GetFileName()); pm->AddPath(DATA_PATH_IDX,XStr); XStr = XString(mp.GetFileName()); pm->AddPath(SOUND_PATH_IDX,XStr); } CKObjectArray *array = CreateCKObjectArray(); res = f->LoadFileData(array); ////////////////////////////////////////////////////////////////////////// // loading is done either as failed, or ok. Let's deleted the loading sprite ////////////////////////////////////////////////////////////////////////// /*if (loadingScreen) { m_CKContext->DestroyObject(loadingScreen->GetID()); m_Level->RemoveRenderContext(m_RenderContext); m_CKContext->DestroyObject(m_Level->GetID()); // in case we changed it, it might have side effects, so we restore to black m_RenderContext->GetBackgroundMaterial()->SetDiffuse(VxColor(0,0,0).GetRGB()); }*/ ////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////// if(res != CK_OK) { m_CKContext->DeleteCKFile(f); DeleteCKObjectArray(array); return res; } m_CKContext->DeleteCKFile(f); DeleteCKObjectArray(array); return CK_OK; } CKERROR CCustomPlayer::_Load(const void* iMemoryBuffer,int iBufferSize) { CKFile *f = m_CKContext->CreateCKFile(); DWORD res = CKERR_INVALIDFILE; res = f->OpenMemory((void*)iMemoryBuffer,iBufferSize,(CK_LOAD_FLAGS) (CK_LOAD_DEFAULT | CK_LOAD_CHECKDEPENDENCIES)); if (res!=CK_OK) { if (res==CKERR_PLUGINSMISSING) { _MissingGuids(f,0); } //m_CKContext->DeleteCKFile(f); //return res; } CKObjectArray *array = CreateCKObjectArray(); res = f->LoadFileData(array); if(res != CK_OK) { m_CKContext->DeleteCKFile(f); return res; } m_CKContext->DeleteCKFile(f); DeleteCKObjectArray(array); return CK_OK; } <file_sep>#ifndef __PYTHON_MODULE_H_ #define __PYTHON_MODULE_H_ #endif #include "pyembed.h" class PythonModule { public: PythonModule(const char*file,const char*func,int bid); int m_BehaviourID; int GetBehaviourID() const { return m_BehaviourID; } void SetBehaviourID(int val) { m_BehaviourID = val; } PyObject *m_PObject; static PythonModule* CreatePythonModule(const char*file,const char*func,int bid=0); static PythonModule* GetPythonModule(int id); private: const char* m_File; const char* m_Func; };<file_sep>#ifndef __XNETINTERFACE_H_ #define __XNETINTERFACE_H_ #include "xNetTypes.h" #include "tnl.h" #include "tnlNetInterface.h" #include "vtConnection.h" class IMessages; class IDistributedObjects; class IDistributedClasses; struct xClientInfo; struct xDistDeleteInfo; class xDistributedObject; class xDistributedClient; class xDistributedSession; class ISession; class xNetInterface : public TNL::NetInterface { typedef TNL::NetInterface Parent; public: ISession* getSessionInterface() const { return mISession; } void setSessionInterface(ISession* val) { mISession = val; } xSessionArrayType& getSessions() { return *mSessions; } ////////////////////////////////////////////////////////////////////////// xNetworkMessageArrayType *m_NetworkMessages; xNetworkMessageArrayType& getNetworkMessages() { return *m_NetworkMessages; } IMessages * getMessagesInterface() { return m_IMessages; } void setMessagesInterface(IMessages * val) { m_IMessages = val; } /************************************************************************/ /* */ /************************************************************************/ xMessageArrayType* mMessages; xMessageArrayType* getMessages() { return mMessages; } ////////////////////////////////////////////////////////////////////////// //user : TNL::Vector<xClientInfo*>m_ClientInfoTable; TNL::Vector<xClientInfo*>&getClientInfoTable() { return m_ClientInfoTable; } TNL::Vector<xDistDeleteInfo*>m_DistDeleteTable; TNL::Vector<xDistDeleteInfo*>&getDistDeleteTable() { return m_DistDeleteTable; } void addDeleteObject(xDistributedObject* object); ////////////////////////////////////////////////////////////////////////// // Distributed Classes Interface IDistributedClasses *getDistributedClassInterface(); void setDistributedClassInterface(IDistributedClasses *distClassInterface); ////////////////////////////////////////////////////////////////////////// //Distributed Objects xDistributedObjectsArrayType * getDistributedObjects() { return m_DistributedObjects; } void setDistributedObjects(xDistributedObjectsArrayType * val) { m_DistributedObjects = val; } IDistributedObjects * getDistObjectInterface() { return m_DistObjectInterface; } void setDistObjectInterface(IDistributedObjects * val) { m_DistObjectInterface = val; } typedef TNL::NetInterface Parent; /// Constants used in this NetInterface enum Constants { PingDelayTime = 2000, ///< Milliseconds to wait between sending GamePingRequest packets. GamePingRequest = FirstValidInfoPacketId, ///< Byte value of the first byte of a GamePingRequest packet. GamePingResponse, ///< Byte value of the first byte of a GamePingResponse packet. ScanPingRequest, ScanPingResponse }; bool pingingServers; ///< True if this is a client that is pinging for active servers. TNL::U32 lastPingTime; ///< The last platform time that a GamePingRequest was sent from this network interface. bool m_IsServer; ///< True if this network interface is a server, false if it is a client. bool IsServer() const { return m_IsServer; } void IsServer(bool val) { m_IsServer = val; } TNL::SafePtr<vtConnection>connectionToServer; ///< A safe pointer to the current connection to the server, if this is a client. vtConnection* getConnection() const { return connectionToServer; } void setConnection(vtConnection* val); TNL::Address pingAddress; ///< Network address to ping in searching for a server. This can be a specific host address or it can be a LAN broadcast address. xNetInterface(); /// Constructor for this network interface, called from the constructor for TestGame. /// The constructor initializes and binds the network interface, as well as sets /// parameters for the associated game and whether or not it is a server. xNetInterface(bool server, const TNL::Address &bindAddress, const TNL::Address &pingAddr); /// handleInfoPacket overrides the method in the NetInterface class to handle processing /// of the GamePingRequest and GamePingResponse packet types. void handleInfoPacket(const TNL::Address &address, TNL::U8 packetType, TNL::BitStream *stream); /// sendPing sends a GamePingRequest packet to pingAddress of this TestNetInterface. void sendPing(); /// Tick checks to see if it is an appropriate time to send a ping packet, in addition /// to checking for incoming packets and processing connections. void tick(); void *m_UserData; void * GetUserData() const { return m_UserData; } void SetUserData(void * val) { m_UserData = val; } void processPacket(const TNL::Address &sourceAddress, TNL::BitStream *pStream); float elapsedConnectionTime; float getElapsedConnectionTime() const { return elapsedConnectionTime; } void setElapsedConnectionTime(float val) { elapsedConnectionTime = val; } float connectionTimeOut; float getConnectionTimeOut() const { return connectionTimeOut; } void setConnectionTimeOut(float val) { connectionTimeOut = val; } bool connectionInProgress; bool isConnectionInProgress() const { return connectionInProgress; } void setConnectionInProgress(bool val) { connectionInProgress = val; } void sendPing(TNL::Address addr,int type=GamePingRequest); bool isValid(); bool m_isConnected; bool isConnected() const { return m_isConnected; } void setConnected(bool val) { m_isConnected = val; } void destroy(); void createScopeObject(); /************************************************************************/ /* user table */ /************************************************************************/ /************************************************************************/ /* clean funcs : */ /************************************************************************/ int mConnectionIDCounter; int getConnectionIDCounter() const { return mConnectionIDCounter; } void setConnectionIDCounter(int val) { mConnectionIDCounter = val; } int m_DOCounter; int getDOCounter() const { return m_DOCounter; } void setDOCounter(int val) { m_DOCounter = val; } TNL::U32& getObjectUpdateCounter() { return m_ObjectUpdateCounter; } void setObjectUpdateCounter(TNL::U32 val) { m_ObjectUpdateCounter = val; } TNL::U32 m_ObjectUpdateCounter; /************************************************************************/ /* */ /************************************************************************/ void updateDistributedObjects(int flags,float deltaTime); float mLastTime; float mDeltaTime; float mLastSendTime; float getLastOneWayTime() { return mLastSendTime; } float mLastRoundTripTime; float getLastRoundTripTime() { return mLastRoundTripTime; } int mLastTime2; float mLastDeltaTime2; float getLastDeltaTime2() const { return mLastDeltaTime2; } void setLastDeltaTime2(float val) { mLastDeltaTime2 = val; } void advanceTime(xTimeType timeNow,float deltaTime); float GetConnectionTime(){ return mLastSendTime ;} void writeDistributedProperties(TNL::BitStream *bstream); void calculateUpdateCounter(); float mCurrentThresholdTicker; float& getCurrentThresholdTicker(){ return mCurrentThresholdTicker; } void setCurrentThresholdTicker(float val) { mCurrentThresholdTicker = val; } /************************************************************************/ /* */ /************************************************************************/ void removeClient(int clientID); virtual void checkConnections(); int getNumConnections(); int getNumSessions(); void checkOwners(); void disconnect(int connectionID); int getNumDistributedObjects(int templateType); bool mCheckObjects; bool getCheckObjects() const { return mCheckObjects; } void setCheckObjects(bool val) { mCheckObjects = val; } void checkObjects(); void initBaseClasses(int flags); void deploySessionClasses(TNL::GhostConnection *connection); xDistributedSession * getCurrentSession() { return mCurrentSession; } void setCurrentSession(xDistributedSession * val) { mCurrentSession = val; } int getMyUserID() const { return mMyUserID; } void setMyUserID(int val) { mMyUserID = val; } xDistributedClient * getMyClient() { return mMyClient; } void setMyClient(xDistributedClient * val) { mMyClient = val; } void checkSessions(); void printObjects(int type, int flags); std::vector<xNString>& getLocalLanServers() { return mLocalLanServers; } void setLocalLanServers(std::vector<xNString> val) { mLocalLanServers = val; } void enableLogLevel(int type,int verbosity,int value); TNL::BitSet32& getInterfaceFlags() { return mInterfaceFlags; } void setInterfaceFlags(TNL::BitSet32 val) { mInterfaceFlags = val; } void setFixedRateParameters(TNL::U32 minPacketSendPeriod, TNL::U32 minPacketRecvPeriod, TNL::U32 maxSendBandwidth, TNL::U32 maxRecvBandwidth,bool global=false); protected: private: ////////////////////////////////////////////////////////////////////////// // [5/5/2008 mc007] : final IDistributedClasses *m_DistributedClassInterface; IDistributedObjects *m_DistObjectInterface; xDistributedObjectsArrayType *m_DistributedObjects; IMessages *m_IMessages; ISession*mISession; xSessionArrayType* mSessions; xDistributedSession *mCurrentSession; int mMyUserID; xDistributedClient *mMyClient; std::vector<xNString>mLocalLanServers; TNL::BitSet32 mInterfaceFlags; }; #endif <file_sep>#ifndef DataManager_H #define DataManager_H "$Id:$" #include "CKBaseManager.h" // define whether we use the manager to relay data or the global variable #define USE_MANAGER // [4/13/2009 macro willson] new headers for external access added #include "gConfig.h" //---------------------------------------------------------------- // // External access // #ifdef G_EXTERNAL_ACCESS #include <WTypes.h> //! @todo : HANDLE type #include "MemoryFileMappingTypes.h" //! todo : use forwards #endif // G_EXTERNAL_ACCESS //---------------------------------------------------------------- // // unique object identifiers // #define DataManagerGUID CKGUID(0x5164ef93, 0x384edab9) class DataManager : public CKBaseManager { //############################################################## // Public Part //############################################################## public : DataManager(CKContext* Context); ~DataManager(); VxVector _vPos; #ifdef G_EXTERNAL_ACCESS // [4/13/2009 macro willson] //---------------------------------------------------------------- // // External access : data members // HANDLE m_hMMFile; vtExternalEvent *m_pData; //---------------------------------------------------------------- // // External access : functions // /*! \brief initiates shared memory helper objects. Must be called due CKInit */ int _initSharedMemory(int); /* \brief handles messages. Must be called in a PreProcess. */ int _SharedMemoryTick(int); /* \brief Might be silly. Just to clean up. Must be called in PostProcess. */ int _SharedMemoryTickPost(int); //---------------------------------------------------------------- #endif // [4/13/2009 macro willson] : enabled for external access /*! \brief Called at the end of each process loop. */ virtual CKERROR PostProcess(); //--- Called at the beginning of each process loop. virtual CKERROR PreProcess(); // -- Called once at CKPlay. Needed to initiate shared memory CKERROR OnCKInit(); //- set function mask for pre and post process callbacks virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_OnCKInit|CKMANAGER_FUNC_PostProcess|CKMANAGER_FUNC_PreProcess; } // [4/14/2009 macro willson] : end external access ---------------------------------------------------------------- //-------------------------------------------------------------- // Unused methods //-------------------------------------------------------------- /* //--- Called after the composition has been restarted. virtual CKERROR OnCKPostReset(); //--- Called before the composition is reset. virtual CKERROR OnCKReset(); //--- Called when the process loop is started. virtual CKERROR OnCKPlay(); //--- Called when the process loop is paused. virtual CKERROR OnCKPause(); //--- Called before a scene becomes active. virtual CKERROR PreLaunchScene(CKScene* OldScene, CKScene* NewScene); //--- Called after a scene became active. virtual CKERROR PostLaunchScene(CKScene* OldScene, CKScene* NewScene); //--- Called at the beginning of a copy. virtual CKERROR OnPreCopy(CKDependenciesContext& context); //--- Called at the end of a copy. virtual CKERROR OnPostCopy(CKDependenciesContext& context); //--- Called when objects are added to a scene. virtual CKERROR SequenceAddedToScene(CKScene* scn, CK_ID* objids, int count); //--- Called when objects are removed from a scene. virtual CKERROR SequenceRemovedFromScene(CKScene* scn, CK_ID* objids, int count); //--- Called just before objects are deleted. virtual CKERROR SequenceToBeDeleted(CK_ID* objids, int count); //--- Called after objects have been deleted. virtual CKERROR SequenceDeleted(CK_ID* objids, int count); //--- Called before the rendering of the 3D objects. virtual CKERROR OnPreRender(CKRenderContext* dev); //--- Called after the rendering of the 3D objects. virtual CKERROR OnPostRender(CKRenderContext* dev); //--- Called after the rendering of 2D entities. virtual CKERROR OnPostSpriteRender(CKRenderContext* dev); //--- Called before the backbuffer is presented. virtual CKERROR OnPreBackToFront(CKRenderContext* dev); //--- Called after the backbuffer is presented. virtual CKERROR OnPostBackToFront(CKRenderContext* dev); //--- Called before switching to/from fullscreen. virtual CKERROR OnPreFullScreen(BOOL Going2Fullscreen, CKRenderContext* dev); //--- Called after switching to/from fullscreen. virtual CKERROR OnPostFullScreen(BOOL Going2Fullscreen, CKRenderContext* dev); //--- Called at the end of the creation of a CKContext. //--- Called at deletion of a CKContext. virtual CKERROR OnCKEnd(); //--- Called at the beginning of a load operation. virtual CKERROR PreLoad(); //--- Called to load manager data. virtual CKERROR LoadData(CKStateChunk* chunk, CKFile* LoadedFile) { return CK_OK; } //--- Called at the end of a load operation. virtual CKERROR PostLoad(); //--- Called at the beginning of a save operation. virtual CKERROR PreSave(); //--- Called to save manager data. return NULL if nothing to save. virtual CKStateChunk* SaveData(CKFile* SavedFile) { return NULL; } //--- Called at the end of a save operation. virtual CKERROR PostSave(); //--- Called at the beginning of a CKContext::ClearAll operation. virtual CKERROR PreClearAll(); //--- Called at the end of a CKContext::ClearAll operation. virtual CKERROR PostClearAll(); */ //############################################################## // Protected Part //############################################################## protected : }; #endif <file_sep>#ifndef __xDOStructs_h #define __xDOStructs_h #include "xNetTypes.h" #include "xPoint.h" struct x3DPositionState { Point3F state; F32 stateDeltaTime; Point3F stateVelocity; x3DPositionState() { state = Point3F(0,0,0); stateDeltaTime = 0.0f; stateVelocity = Point3F(0,0,0); } }; struct x3DObjectData { x3DPositionState *prevState; x3DPositionState *currentState; ////////////////////////////////////////////////////////////////////////// //Position Point3F lastPostion; Point3F currentPosition; ////////////////////////////////////////////////////////////////////////// float dT; float currentTime; float lastTime; int warpCount; int UpdateFlags; ////////////////////////////////////////////////////////////////////////// x3DObjectData() : currentPosition(Point3F(0,0,0)) { currentTime = 0.0f; lastTime = 0.0f; dT = 0.0f; prevState = new x3DPositionState(); currentState = new x3DPositionState(); UpdateFlags = 0 ; warpCount = 0; } }; #endif <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPWSetCollisionGroupFlagDecl(); CKERROR CreatePWSetCollisionGroupFlagProto(CKBehaviorPrototype **pproto); int PWSetCollisionGroupFlag(const CKBehaviorContext& behcontext); CKERROR PWSetCollisionGroupFlagCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPWSetCollisionGroupFlagDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PWSetCollisionGroupFlag"); od->SetCategory("Physic/Collision"); od->SetDescription("Enables collision between two collisions groups."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x44961cc7,0x2d104ced)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePWSetCollisionGroupFlagProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePWSetCollisionGroupFlagProto // FullName: CreatePWSetCollisionGroupFlagProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePWSetCollisionGroupFlagProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWSetCollisionGroupFlag"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( PWSetCollisionGroupFlagCB ); proto->DeclareInParameter("Collisions Group A",CKPGUID_INT,"0"); proto->DeclareInParameter("Collisions Group A",CKPGUID_INT,"0"); proto->DeclareInParameter("Enabled",CKPGUID_BOOL,"0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PWSetCollisionGroupFlag); *pproto = proto; return CK_OK; } //************************************ // Method: PWSetCollisionGroupFlag // FullName: PWSetCollisionGroupFlag // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PWSetCollisionGroupFlag(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorld(target); int collGA = GetInputParameterValue<int>(beh,0); int collGB = GetInputParameterValue<int>(beh,1); int value = GetInputParameterValue<int>(beh,2); if(world) world->cSetGroupCollisionFlag(collGA,collGB,value); beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PWSetCollisionGroupFlagCB // FullName: PWSetCollisionGroupFlagCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PWSetCollisionGroupFlagCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SetZoom Camera // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorSetZoomDecl(); CKERROR CreateSetZoomProto(CKBehaviorPrototype **pproto); int SetZoom(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSetZoomDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Set Zoom"); od->SetDescription("Sets the Zoom (or Lens) of a perspective camera (millimeter)."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Focal Length: </SPAN>lens size expressed in millimeters. <BR> See Also: 'Set FOV'.<BR> */ od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x40540a0d, 0x000aaaaa)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetZoomProto); od->SetCompatibleClassId(CKCID_CAMERA); od->SetCategory("Cameras/Basic"); return od; } CKERROR CreateSetZoomProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set Zoom"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Focal Length (mm)", CKPGUID_FLOAT, "50"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetZoom); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int SetZoom(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKCamera *cam = (CKCamera *) beh->GetTarget(); if( !cam ) return CKBR_OWNERERROR; float zoom = 50; // Zoom in mm beh->GetInputParameterValue(0, &zoom); float fov = 2.0f * atanf(18.0f / zoom); cam->SetFov( fov ); beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pVehicleMotor.h" #include "pVehicleGears.h" #include "pSteer.h" #include <xDebugTools.h> #include "NxArray.h" float pVehicle::getBrakeAmountFromTable(pVehicleBreakLevel brakeLevel) { int value = abs((int(getMPH()) / 10)); if(value > BREAK_TABLE_ENTRIES - 1) value = BREAK_TABLE_ENTRIES - 1; if(value < 0 || value == BREAK_TABLE_ENTRIES) { return 1.0f; } switch(brakeLevel) { case BL_Small: return mSmallBrakeTable.brakeEntries[brakeLevel]; case BL_Medium: return mMediumBrakeTable.brakeEntries[brakeLevel]; case BL_High: return mHighBrakeTable.brakeEntries[brakeLevel]; } return 1.0f; } pVehicleBreakCase pVehicle::calculateBreakCase(int currentAccelerationStatus) { //---------------------------------------------------------------- // // is rolling or no user input ? // if( !(currentAccelerationStatus & VS_Handbrake ) && (currentAccelerationStatus & VS_IsMoving ) && !(currentAccelerationStatus & VS_IsAccelerated) ) return BC_NoUserInput; //---------------------------------------------------------------- // // direction change ? // if( !(currentAccelerationStatus & VS_Handbrake ) && (currentAccelerationStatus & VS_IsBraking ) && (currentAccelerationStatus & VS_IsMoving ) && (currentAccelerationStatus & VS_IsAccelerated) ) return BC_DirectionChange; //---------------------------------------------------------------- // // handbrake // if( (currentAccelerationStatus & VS_Handbrake ) ) return BC_Handbrake; return BC_NoUserInput; } void pVehicle::doSteering() { for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel2* wheel = (pWheel2*)_wheels[i]; if(wheel->getWheelFlag(WF_SteerableInput)) { int i; // Send steering angle through to steering wheels float factor=steer->GetLock()/wheel->GetLock()*2.0f; float angle = steer->GetAngle(); float rAngle = wheel->getWheelShape()->getSteerAngle(); wheel->setSteering(steer->GetAngle()/factor); } } } int pVehicle::_performSteering(float dt) { _controlSteering(_cSteering, _cAnalogSteering); NxReal distanceSteeringAxisCarTurnAxis = _steeringSteerPoint.x - _steeringTurnPoint.x; //NX_ASSERT(_steeringSteerPoint.z == _steeringTurnPoint.z); NxReal distance2 = 0; if (NxMath::abs(_steeringWheelState) > 0.01f) distance2 = distanceSteeringAxisCarTurnAxis / NxMath::tan(_steeringWheelState * getMaxSteering()); float tanS = NxMath::tan(_steeringWheelState * getMaxSteering()); for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel* wheel = _wheels[i]; if(wheel->getWheelFlag(WF_SteerableInput)) { if(distance2 != 0) { //NxReal xPos = wheel->getWheelPos().x; NxReal xPos = ((pWheel2*)wheel)->getWheelShape()->getLocalPosition().x; //NxReal xPos2 = _steeringSteerPoint.x- wheel->getWheelPos().x; //NxReal xPos2 = _steeringSteerPoint.x- ((pWheel2*)wheel)->getWheelShape()->getLocalPosition().z; NxReal zPos = ((pWheel2*)wheel)->getWheelShape()->getLocalPosition().z; //NxReal zPos = wheel->getWheelPos().z; NxReal dz = -zPos + distance2; NxReal dx = xPos - _steeringTurnPoint.x; float angle =(NxMath::atan(dx/dz)); if (dx < 0.0f) { angle*=-1.0f; } wheel->setAngle(angle); } else { wheel->setAngle(0.0f); } } else if(wheel->getWheelFlag(WF_SteerableAuto)) { NxVec3 localVelocity = getActor()->getLocalPointVelocity(getFrom(wheel->getWheelPos())); NxQuat local2Global = getActor()->getGlobalOrientationQuat(); local2Global.inverseRotate(localVelocity); // printf("%2.3f %2.3f %2.3f\n", wheel->getWheelPos().x,wheel->getWheelPos().y,wheel->getWheelPos().z); localVelocity.y = 0; if(localVelocity.magnitudeSquared() < 0.1f) { wheel->setAngle(0.0f); } else { localVelocity.normalize(); // printf("localVelocity: %2.3f %2.3f\n", localVelocity.x, localVelocity.z); if(localVelocity.x < 0) localVelocity = -localVelocity; NxReal angle = NxMath::clamp((NxReal)atan(localVelocity.z / localVelocity.x), 0.3f, -0.3f); wheel->setAngle(angle); } } } return 0; } float pVehicle::calculateBraking(float dt) { float breakTorque = 0.0f; pVehicleBreakCase currentBreakCase = calculateBreakCase(_currentStatus); /* int currentBreakLevel = getBreaklevelForCase(currentBreakCase); */ bool calculateBreaking = false; XString errMessage; if( ((_currentStatus & VS_IsBraking ) && (_currentStatus & VS_IsMoving)) ) calculateBreaking = true; if ( (_currentStatus & VS_IsMoving ) && (getBreakFlags() & VBF_Autobreak) && (currentBreakCase == BC_NoUserInput)&& (_currentStatus & VS_IsMoving ) && !(_currentStatus & VS_IsAccelerated ) ) { calculateBreaking = true; /* errMessage.Format("autobreak");*/ //xInfo(errMessage.Str()); } if (_currentStatus & VS_Handbrake) { /*errMessage.Format("handbrake"); xInfo(errMessage.Str());*/ goto performAcceleration; } //---------------------------------------------------------------- // // calculate break torque // if ( calculateBreaking ) { //---------------------------------------------------------------- // // increase break time counter // if(mBreakLastFrame) mTimeBreaking+=dt; //---------------------------------------------------------------- // // determine break amount by table // if ( (getBreakFlags() & VBF_UseTable) ) { if(mTimeBreaking < mBrakeMediumThresold) { breakTorque = getBrakeAmountFromTable(BL_Small); errMessage.Format("breaking at small : bt : %f at %f",breakTorque,mTimeBreaking); //xInfo(errMessage.Str()); }else if(mTimeBreaking >= mBrakeMediumThresold && mTimeBreaking < mBrakeHighThresold ) { breakTorque = getBrakeAmountFromTable(BL_Medium); errMessage.Format("breaking at medium : bt : %f at %f",breakTorque,mTimeBreaking); //xInfo(errMessage.Str()); }else { breakTorque = getBrakeAmountFromTable(BL_High); errMessage.Format("breaking at high : bt : %f at %f",breakTorque,mTimeBreaking); //xInfo(errMessage.Str()); } }else { //---------------------------------------------------------------- // // use break pressures // float mCurrentBrakeTorque = getBrakeTorque()*0.01f; float AmountToBrakeFinal = 0.0f; if(mTimeBreaking < mBrakeMediumThresold) { breakTorque = mCurrentBrakeTorque * mBreakPressures[BL_Small]; errMessage.Format("breaking at small : bt : %f at %f",breakTorque,mTimeBreaking); //xInfo(errMessage.Str()); } else if(mTimeBreaking >= mBrakeMediumThresold && mTimeBreaking < mBrakeHighThresold ) { breakTorque = mCurrentBrakeTorque * mBreakPressures[BL_Medium]; errMessage.Format("breaking at medium : bt : %f at %f",breakTorque,mTimeBreaking); //xInfo(errMessage.Str()); } else { breakTorque = mCurrentBrakeTorque * mBreakPressures[BL_High]; errMessage.Format("breaking at high : bt : %f at %f",breakTorque,mTimeBreaking); //xInfo(errMessage.Str()); } if (breakTorque > 1000.f) { breakTorque= 1000.0f; } } }else { mBreakLastFrame = false; mTimeBreaking = 0.0f; } performAcceleration: if (breakTorque > 0.0f) { mBreakLastFrame = true; } return breakTorque; } int pVehicle::_performAcceleration(float dt) { motorTorque = 0.0f; if ( _nbTouching && _currentStatus & VS_IsAccelerated ) { NxReal axisTorque = _computeAxisTorqueV2(); NxReal wheelTorque = axisTorque / (NxReal)(_wheels.size() - _nbHandbrakeOn ); NxReal wheelTorqueNotTouching = _nbNotTouching > 0 ? wheelTorque * ( NxMath::pow(0.5f, (NxReal) _nbNotTouching )):0; NxReal wheelTorqueTouching = wheelTorque - wheelTorqueNotTouching; motorTorque = wheelTorqueTouching / (NxReal)_nbTouching; }else { _updateRpms(); } return 1; } void pVehicle::postStep() { for(NxU32 i = 0; i < _wheels.size(); i++) { //---------------------------------------------------------------- // // determine break torque : // // is moving in the opposite direction than its accelerated pWheel* wheel = _wheels[i]; wheel->tick( ( _currentStatus & VS_Handbrake) , motorTorque, breakTorque , _lastDT ); } } void pVehicle::setBreakPressure(int breakLevel,float pressure) { mBreakPressures[breakLevel]=pressure; } void pVehicle::setBreakCaseLevel(pVehicleBreakCase breakCase,pVehicleBreakLevel level) { breakConditionLevels[breakCase]=level; } // ( X * 10 * 60) / (5280* 12) * 100 = X * 0.9469696 //return (-((10 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed() * 60) / (5280 * 12)) * 100); //return -0.9469696 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed(); float pVehicle::getBrakeTorque() { int nbAWheels =0; float radius = 0.0; float axleSpeed = 0.0; for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel* wheel = _wheels[i]; if(wheel->getWheelFlag(WF_Accelerated)) { nbAWheels++; if (wheel->getRadius() > radius) radius = wheel->getRadius(); pWheel2* w2 = (pWheel2*)wheel; if (w2->getWheelShape()->getAxleSpeed() > axleSpeed) { axleSpeed = w2->getWheelShape()->getAxleSpeed(); } } } if(fabs(axleSpeed) != 0) { return ((5252 * getMotorForce()) / (fabs(axleSpeed) * 10)); } return 0.0f; } float pVehicle::getMPH(int type) { int nbAWheels =0; float radius = 0.0; float axleSpeed = 0.0; for(NxU32 i = 0; i < _wheels.size(); i++) { pWheel* wheel = _wheels[i]; if(wheel->getWheelFlag(WF_Accelerated)) { nbAWheels++; if (wheel->getRadius() > radius) radius = wheel->getRadius(); pWheel2* w2 = (pWheel2*)wheel; if (w2->getWheelShape()->getAxleSpeed() > axleSpeed) { axleSpeed = w2->getWheelShape()->getAxleSpeed(); } } } // ( X * 10 * 60) / (5280* 12) * 100 = X * 0.9469696 //return (-((10 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed() * 60) / (5280 * 12)) * 100); return 0.9469696 * radius * NxPi * axleSpeed; } void pVehicle::_controlAcceleration(float acceleration, bool analogAcceleration) { if(NxMath::abs(acceleration) < 0.001f) { _releaseBraking = true; //xInfo("set release breaking = true"); } if(!_braking) { _accelerationPedal = NxMath::clamp(acceleration, 1.f, -1.f); _brakePedalChanged = _brakePedal == 0; _brakePedal = 0; //xInfo("breaking = false : clamp accPedal 1|-1"); } else { //xInfo("breaking = true : accPeal = 0"); _accelerationPedal = 0; NxReal newv = NxMath::clamp(NxMath::abs(acceleration), 1.f, 0.f); _brakePedalChanged = _brakePedal == newv; _brakePedal = newv; } char master[512]; sprintf(master,"Acceleration: %2.3f, Braking %2.3f\n", _accelerationPedal, _brakePedal); xInfo(master); //OutputDebugString(master); } <file_sep>// vtAgeiaInterfaceToolbarDlg.cpp : implementation file // #include "stdafx2.h" #include "vtAgeiaInterfaceEditor.h" #include "vtAgeiaInterfaceToolbarDlg.h" #ifdef _MFCDEBUGNEW #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif DllToolbarDlg* fCreateToolbarDlg(HWND parent) { HRESULT r = CreateDllDialog(parent,IDD_TOOLBAR,&g_Toolbar); return (DllToolbarDlg*)g_Toolbar; } ///////////////////////////////////////////////////////////////////////////// // vtAgeiaInterfaceToolbarDlg dialog vtAgeiaInterfaceToolbarDlg::vtAgeiaInterfaceToolbarDlg(CWnd* pParent /*=NULL*/) : DllToolbarDlg(vtAgeiaInterfaceToolbarDlg::IDD, pParent) { //{{AFX_DATA_INIT(vtAgeiaInterfaceToolbarDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void vtAgeiaInterfaceToolbarDlg::DoDataExchange(CDataExchange* pDX) { DllToolbarDlg::DoDataExchange(pDX); //{{AFX_DATA_MAP(vtAgeiaInterfaceToolbarDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(vtAgeiaInterfaceToolbarDlg, DllToolbarDlg) //{{AFX_MSG_MAP(vtAgeiaInterfaceToolbarDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // vtAgeiaInterfaceToolbarDlg message handlers BOOL vtAgeiaInterfaceToolbarDlg::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class if ( pMsg->message >= WM_MOUSEFIRST && pMsg->message <= WM_MOUSELAST) { MSG msg; ::CopyMemory(&msg, pMsg, sizeof(MSG)); m_wndToolTip.RelayEvent(pMsg); } return DllToolbarDlg::PreTranslateMessage(pMsg); } BOOL vtAgeiaInterfaceToolbarDlg::OnInitDialog() { DllToolbarDlg::OnInitDialog(); // TODO: Add extra initialization here // EnableToolTips(TRUE); // CreateTooltip(); ActivateClosebutton(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } //this is the almost equivalent of OnInitDialog you should use if you want to //use the PluginInterface with GetInterface or if you want to be sure the editor is present void vtAgeiaInterfaceToolbarDlg::OnInterfaceInit() { } //called on WM_DESTROY void vtAgeiaInterfaceToolbarDlg::OnInterfaceEnd() { } HRESULT vtAgeiaInterfaceToolbarDlg::ReceiveNotification(UINT MsgID,DWORD Param1,DWORD Param2,CKScene* Context) { return 0; } void vtAgeiaInterfaceToolbarDlg::CreateTooltip() { //m_wndToolTip.Create(this); // m_wndToolTip.Activate(TRUE); //delay after which the tooltip apppear, value of 1 is immediate, 0 is default (that is 500 for windows) //m_wndToolTip.SetDelayTime(500); //change tooltip back color //m_wndToolTip.SetTipBkColor(CZC_176); //change tooltip text color //m_wndToolTip.SetTipTextColor(CZC_BLACK); //for each control you want to add a tooltip on, add the following line //m_wndToolTip.AddTool(CWnd* target,const char* tooltip_string); //delay after which the tooltip will auto close itself /* m_wndToolTip.SetDelayTime(TTDT_AUTOPOP,5000); m_wndToolTip.SetWindowPos(&(CWnd::wndTopMost),0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); //if you want multiline tooltip, you must add the following line (note that this represent the max tooltip width in pixel) m_wndToolTip.SendMessage(TTM_SETMAXTIPWIDTH, 0, 500); */ } <file_sep>#include "PCommonDialog.h" #include "PBodySetup.h" #include "PBXMLSetup.h" #include "resource.h" #include "VITabCtrl.h" #include "VIControl.h" #define LAYOUT_STYLE (WS_CHILD|WS_VISIBLE) #define LAYOUT_ShaderREE 130 /* MultiParamEditDlg* CPBXMLSetup::refresh(CKParameter*src) { return this; } */ void CPBXMLSetup::Init(CParameterDialog *parent){} CPBXMLSetup::~CPBXMLSetup(){ _destroy();} void CPBXMLSetup::_destroy(){ ::CPSharedBase::_destroy();} /* CPBXMLSetup::CPBXMLSetup( CKParameter* Parameter, CK_CLASSID Cid) : CParameterDialog(Parameter,Cid) , CPSharedBase(this,Parameter) { setEditedParameter(Parameter); } */ LRESULT CPBXMLSetup::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: { break; } case WM_ERASEBKGND: { /*RECT r; GetClientRect(&r); CDC* pDC=CDC::FromHandle((HDC)wParam); pDC->FillSolidRect(&r,RGB(200,200,200)); return 1;*/ }break; case CKWM_OK: { //CEdit *valueText = (CEdit*)GetDlgItem(IDC_EDIT); /*CString l_strValue; valueText->GetWindowText(l_strValue); double d; if (sscanf(l_strValue,"%Lf",&d)) { parameter->SetValue(&d); }*/ } break; case CKWM_INIT: { RECT r; GetClientRect(&r); /* CDC* pDC=CDC::FromHandle((HDC)wParam);*/ //initSplitter(); char temp[64]; double d; } break; } return CDialog::WindowProc(message, wParam, lParam); } void CPBXMLSetup::DoDataExchange(CDataExchange* pDX) { //CDialog::DoDataExchange(pDX); CParameterDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPBXMLSetup) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPBXMLSetup, CParameterDialog) END_MESSAGE_MAP() <file_sep>#ifndef __VT_TOOLS_H__ #define __VT_TOOLS_H__ #include "CKAll.h" #ifndef _INC_STDLIB #include <stdlib.h> #endif #ifndef _VECTOR_ #include <vector> #endif //#ifndef __VT_BB_MACROS_H__ // #include <virtools/vtBBMacros.h> //#endif //#ifndef __VT_BB_HELPER_H__ //#include <virtools/vtBBHelper.h> //#endif namespace vtTools { /*************************************************************************/ /* common enumerations */ /* */ namespace Enums { /* Represents a virtools super type. See GetVirtoolsSuperType. */ enum SuperType { vtSTRING = 1, vtFLOAT = 2, vtINTEGER = 3, vtVECTOR = 4, vtVECTOR2D = 5, vtCOLOUR = 6, vtMATRIX = 7, vtQUATERNION = 8, vtRECTANGLE = 9, vtBOX = 10, vtBOOL = 11, vtENUMERATION = 12, vtFLAGS = 13, vtFile = 14, vtOBJECT = 16, vtUNKNOWN = 17 }; /* Author: gunther.baumgart Represents the c++ equivalent for TGBLWidgetType pm->RegisterNewEnum(EVTWIDGETTYPE,"EVTWidgetType", "StaticText=1, TextEdit=2, CheckButton=4, PushButton=8, ListBox=16, ComboBox=32, FileSelector=64, ColorSelector=128" ); */ enum EVTWidgetType { EVT_WIDGET_STATIC_TEXT = 1, EVT_WIDGET_EDIT_TEXT =2, EVT_WIDGET_CHECK_BUTTON =3, EVT_WIDGET_LIST_BOX =5, EVT_WIDGET_COMBO_BOX =6, EVT_WIDGET_FILE_SELECTION =7, EVT_WIDGET_COLOR_SELECTION =8 }; /* */ }/* end namespace typedefs */ /*************************************************************************/ /* common Structs */ /* */ namespace Structs { ////////////////////////////////////////////////////////////////////////// /* ParameterInfo is used to describe a virtools parameter type. Example : Matrix = horizontalItems = 4, verticalItems = 4 memberType =vtFLOAT, superType= vtMATRIX */ struct ParameterInfo { int horizontalItems; int verticalItems; Enums::SuperType superType; Enums::SuperType memberType; }; ////////////////////////////////////////////////////////////////////////// /* SGBL_WidgetInfo describes an parameter for using GBLWidgets GBL-Widgets. */ struct WidgetInfo { struct WidgetInfoItem { Enums::SuperType baseType; Enums::EVTWidgetType widgetType; //with which widget XString value; XString label; }; XArray<WidgetInfoItem*>items; Structs::ParameterInfo parameterInfo; }; }/* end namespace Structs */ /************************************************************************/ /* parameter tools */ /* */ namespace ParameterTools { /* ******************************************************************* * Function: IsNumeric() * * Description : Check each character of the string If a character at a certain position is not a digit, then the string is not a valid natural number * Parameters : char*Str,r : the string to test * Returns : int * ******************************************************************* */ int IsNumeric(const char* Str,Enums::SuperType superType); /* ******************************************************************* * Function: GetParameterMemberInfo() * * Description : GetParameterMemberInfo returns the type super type of the used structure members. Example : vtVECTOR returns vtFLOAT * Parameters : CKContext* context, r : the virtools context. CKParameterType parameterType, r : the type to test. * Returns : CO_EVT_VirtoolsSuperType * ******************************************************************* */ Enums::SuperType GetParameterMemberInfo(CKContext* context,CKParameterType parameterType); /* ******************************************************************* * Function: GetParameterInfo() * * Description : GetParameterInfo returns an info about a virtools type. Example : Vector4D returns : result.horizontalItems = 4 ; result.verticalItems = 1 ; result.memberType = vtFLOAT result.superType = vtQUATERNION; * Parameters : CKContext* context, r : the virtools context. CKParameterType parameterType, r : the type to test. * Returns : ParameterInfo * ******************************************************************* */ Structs::ParameterInfo GetParameterInfo(CKContext* context,CKParameterType parameterType); /* ******************************************************************* * Function: CreateWidgetInfo() * * Description : CreateWidgetInfo returns an handy info about an parameter type and a given string value of this parameter. * Parameters : CKContext* context, r : the virtools context. CKParameterType parameterType, r : the type to test. XString stringValue,r : the string value of the given type. * Returns : WidgetInfo ******************************************************************* */ Structs::WidgetInfo* CreateWidgetInfo(CKContext* context,CKParameterType parameterType,XString stringValue); /* ******************************************************************* * Function: GetWidgetType() * * Description : GetWidgetType returns the type of the GBLWidget which should used for a specific virtools super type. Example : vtBOOL = CheckBox vtENUMERATION = ComboBox * * Parameters : CO_EVT_VirtoolsSuperType superType, r : the given virtools super type * Returns : EWidgetType * ******************************************************************* */ Enums::EVTWidgetType GetWidgetType(Enums::SuperType superType); /* ******************************************************************* * Function: TypeCheckedParameterCopy() * * Description : Copies the source parameter to a destination parameter. On a type mismatch * it tries to copy as string. This also works for nested virtools structures. See CO_EVT_VirtoolsSuperType for supported types. * * Parameters : CKParameter*dest,rw : the destination parameter CKParameter*src,r : the source parameter * Returns : bool = true if succesful. * todo:: return copied diff * ******************************************************************* */ int TypeCheckedParameterCopy( CKParameter*dest, CKParameter*src); /* ******************************************************************* * Function: GetParameterAsString() * * Description : Returns the string value a CKParameter. * * Parameters : CKParameter*src ,r the given parameter * Returns : CKSTRING * ******************************************************************* */ CKSTRING GetParameterAsString( CKParameter*src); /* ******************************************************************* * Function: CompareStringRep() * * Description : This function compares the string representation of the two CKParameters. * * Parameters : CKParameter* valueA,r : the first parameter CKParameter* valueB,r : the second parameter * Returns : int (like strcmp) * ******************************************************************* */ int CompareStringRep(CKParameter*valueA, CKParameter*valueB); /* ******************************************************************* * Function:GetVirtoolsSuperType() * * Description : GetVirtoolsSuperType returns the base type of a virtools parameter. This is very useful to determine whether a parameter can be used for network or a database. * * Parameters : CKContext *ctx, r : the virtools context CKGUID guid, r : the guid of the parameter * * Returns : CO_EVT_VirtoolsSuperType, * ******************************************************************* */ Enums::SuperType GetVirtoolsSuperType(CKContext *ctx,const CKGUID guid); /* ******************************************************************* * Function: TypeIsSerializable() * Description : Returns true if the given type can be stored as string. + It also checks custom virtools structures recursive. + it checks only * * Parameters : CKContext *ctx, r : the virtools context CKParameterType type, r : the type * Returns : bool * ******************************************************************* */ bool TypeIsSerializable(CKContext *ctx,CKParameterType type); /* ******************************************************************* * Function: IsValidStruct() * * Description : Like TypeIsSerializable, even checks a custom virtools structure, recursive. * * Parameters : CKContext *ctx,r : the virtools context CKGUID type,r : the type to check * Returns : bool * ******************************************************************* */ bool IsValidStruct(CKContext *ctx,CKGUID type); /* ******************************************************************* * Function:SetParameterStructureValue() * * Description : Sets a specific value in a custom structure. * * Parameters : CKParameter *par, r : the virtools virtools parameter const unsigned short StructurIndex, r : the index within the custom structure T value, r : the value. bool update,r : If this function is part of a virtools parameter operation, this should set to false, otherwise it is an infinity loop. * Returns : is a void * ******************************************************************* */ template<class T>void SetParameterStructureValue( CKParameter *par, const unsigned short StructurIndex, T value, bool update = TRUE ) { assert(par && StructurIndex>=0 ); CK_ID* paramids = (CK_ID*)par->GetReadDataPtr(update); CKParameterOut *pout = static_cast<CKParameterOut*>(par->GetCKContext()->GetObject(paramids[StructurIndex])); pout->SetValue(&value); } /* ******************************************************************* * Function:SetParameterStructureValue() * * Description : This is a template function specialization for CKSTRING. * Sets a specific value in a custom structure. * * Parameters : CKParameter *par, r : the virtools virtools parameter const unsigned short StructurIndex, r : the index within the custom structure T value, r : the value. bool update,r : If this function is part of a virtools parameter operation, this should set to false, otherwise it is an infinity loop. * Returns : is a void * ******************************************************************* */ template<>__inline void SetParameterStructureValue<CKSTRING> ( CKParameter *par, const unsigned short StructurIndex, CKSTRING value, bool update ) { assert(par && StructurIndex>=0 ); static_cast<CKParameterOut*>(par->GetCKContext()->GetObject( static_cast<CK_ID*>(par->GetReadDataPtr(update))[StructurIndex]))->SetStringValue(value); } /* ******************************************************************* * Function:GetValueFromParameterStruct() * * Description : returns a object from a custom structure. * * Parameters : CKParameter *par, r : the virtools virtools parameter const unsigned short StructurIndex, r : the index within the custom structures bool update,r : If this function is part of a virtools parameter operation, this should set to false, otherwise it is an infinity loop. * Returns : T. * ******************************************************************* */ template<class T>__inline T GetValueFromParameterStruct( CKParameter *par, const unsigned short StructurIndex, bool update=false) { T value; assert(par); CK_ID* paramids = static_cast<CK_ID*>(par->GetReadDataPtr(update)); CKParameterOut* pout = static_cast<CKParameterOut*>(par->GetCKContext()->GetObject(paramids[StructurIndex])); pout->GetValue(&value); return value; } /* ******************************************************************* * Function:GetValueFromParameterStruct() * * Description : This is a template function specialization for CKSTRING * Gets a specific value from custom structure. * * Parameters : CKParameter *par, r : the virtools virtools parameter const unsigned short StructurIndex, r : the index within the custom structures bool update,r : If this function is part of a virtools parameter operation, this should set to false, otherwise it is an infinity loop. * Returns : CKSTRING. * ******************************************************************* */ template<>__inline CKSTRING GetValueFromParameterStruct<CKSTRING>( CKParameter *par, const unsigned short StructurIndex, bool update) { assert( par && StructurIndex >=0 ); CK_ID* paramids = static_cast<CK_ID*>(par->GetReadDataPtr(update)); CKParameterOut* pout = static_cast<CKParameterOut*>(par->GetCKContext()->GetObject(paramids[StructurIndex])); CKSTRING stringValue = static_cast<CKSTRING>(pout->GetReadDataPtr(update)); return stringValue; } __inline CKParameterOut* GetParameterFromStruct(CKParameter *par,const int index,bool update=false) { CK_ID* paramids = static_cast<CK_ID*>(par->GetReadDataPtr(update)); if (paramids) { return static_cast<CKParameterOut*>(par->GetCKContext()->GetObject(paramids[index])); } return NULL; } } /*end namespace virtools parameter tools */ /************************************************************************/ /* building block tools */ /* */ namespace BehaviorTools { __inline void Error(CKBehavior *beh,CKSTRING errorString,int errorOutputIndex,bool trigger=false,int outTrigger=0,bool outputOnConsole = false) { if(!beh) return; if(!strlen(errorString)) return; CKParameterOut *pout = beh->GetOutputParameter(errorOutputIndex); pout->SetStringValue(errorString); if (trigger) { beh->ActivateOutput(outTrigger); } CKContext* ctx = beh->GetCKContext(); if(outputOnConsole && ctx) ctx->OutputToConsole(errorString,FALSE); } __inline void Error(CKBehavior *beh,int error,int errorOutputIndex,CKSTRING errorString,bool trigger=false,int outTrigger=0,bool outputOnConsole = false) { if(!beh) return; beh->SetOutputParameterValue(errorOutputIndex,&error); if (trigger) { beh->ActivateOutput(outTrigger); } if(!strlen(errorString)) return; CKContext* ctx = beh->GetCKContext(); if(outputOnConsole && ctx) ctx->OutputToConsole(errorString,FALSE); } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : Returns an input parameter value. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : T * ******************************************************************* */ template<class T>__inline void SetOutputParameterValue( CKBehavior *beh, const int pos, T value) { #ifdef _DEBUG assert(beh); #endif T val = value; beh->SetOutputParameterValue(pos,&val); } template<class T>__inline void SetInputParameterValue( CKBehavior *beh, const int pos, T value) { T val = value; CKParameterOut *inPar = (CKParameterOut*)(beh->GetInputParameter(pos)->GetRealSource()); if (inPar) { inPar->SetValue(&val); } } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : Returns an input parameter value. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : T * ******************************************************************* * */ template<>__inline void SetInputParameterValue<CKSTRING>( CKBehavior *beh, const int pos, CKSTRING val) { CKParameterIn*inPar = beh->GetInputParameter(pos); if (inPar && val && strlen(val) ) { CKParameter*par = inPar->GetRealSource(); if (par) par->SetStringValue(val); } } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : Returns an input parameter value. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : T * ******************************************************************* */ template<>__inline void SetOutputParameterValue<CKSTRING>( CKBehavior *beh, const int pos, CKSTRING val) { #ifdef _DEBUG assert(beh); #endif // _DEBUG if(strlen(val)) { CKParameterOut *pout = beh->GetOutputParameter(pos); if (pout) { pout->SetStringValue(val); } } } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : Returns an input parameter value. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : T * ******************************************************************* */ template<>__inline void SetOutputParameterValue<const char*>( CKBehavior *beh, const int pos, const char *val) { #ifdef _DEBUG assert(beh); #endif // _DEBUG if(strlen(val)) { CKParameterOut *pout = beh->GetOutputParameter(pos); if (pout) { pout->SetStringValue(const_cast<char*>(val)); } } } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : Returns an input parameter value. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : T * ******************************************************************* */ template<class T>__inline T GetInputParameterValue( CKBehavior *beh, const int pos) { assert(beh); T value ; beh->GetInputParameterValue(pos,&value); return value; } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : Returns an input parameter value. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : T * ******************************************************************* */ template<class T>__inline T GetOutputParameterValue( CKBehavior *beh, const int pos) { assert(beh); T value ; beh->GetOutputParameterValue(pos,&value); return value; } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : This is a template function specialization for CKSTRING. Returns an input parameter value. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKSTRING * ******************************************************************* */ template<>__inline CKSTRING GetInputParameterValue<CKSTRING>( CKBehavior *beh, const int pos) { assert(beh); return static_cast<CKSTRING>(beh->GetInputParameterReadDataPtr(pos)); } /* ******************************************************************* * Function:GetInputParameterValue() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<>__inline CKObject* GetInputParameterValue<CKObject*>( CKBehavior *beh, const int pos) { assert(beh); return beh->GetInputParameterObject(pos); } void __inline EnablePOutputBySettings(CKBehavior *beh,int index) { int cond; beh->GetLocalParameterValue(index,&cond); beh->EnableOutputParameter(index,cond); } void __inline EnablePInputBySettings(CKBehavior *beh,int index) { int cond; beh->GetLocalParameterValue(index,&cond); beh->EnableInputParameter(index,cond); } //void SetOutputParameterValueBySettings template<class T>__inline T SetOutputParameterBySettings( CKBehavior *beh, const int pos, T value) { int cond; beh->GetLocalParameterValue(pos,&cond); if (cond) { SetOutputParameterValue<T>(beh,pos,value); } } //todo : parametric log / debug forwarding!!! - > g.baumgart ! }/* end namespace behavior tools*/ /**************************************************************************/ /* attribute tools */ /* */ /* */ namespace AttributeTools { /* ****************************************************************** * Function:GetObjectFromAttribute() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<class T>__inline T* GetObjectFromAttribute(CKContext *ctx,CKObject *_e,const int attributeID,const int StructurIndex) { T *value; CKParameterOut* pout = _e->GetAttributeParameter(attributeID); CK_ID* paramids = (CK_ID*)pout->GetReadDataPtr(); pout = (CKParameterOut*)ctx->GetObject(paramids[StructurIndex]); value = (T*)ctx->GetObject(*(CK_ID*)pout->GetReadDataPtr()); return value ? value : NULL; } /* ****************************************************************** * Function:GetObjectFromAttribute() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<class T>__inline void SetAttributeValue(CKBeObject *_e,const int attributeID,const int StructurIndex,T* value) { CKParameterOut* pout = _e->GetAttributeParameter(attributeID); if(pout) { CK_ID* paramids = (CK_ID*)pout->GetReadDataPtr(); pout = (CKParameterOut*)_e->GetCKContext()->GetObject(paramids[StructurIndex]); if (pout) { pout->SetValue(value); } } } /* ****************************************************************** * Function:GetObjectFromAttribute() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<class T>__inline T GetValueFromAttribute(CKBeObject *_e,int attributeID,int StructurIndex) { T value; CKParameterOut* pout = _e->GetAttributeParameter(attributeID); if (pout) { CK_ID* paramids = static_cast<CK_ID*>(pout->GetReadDataPtr()); pout = static_cast<CKParameterOut*>(_e->GetCKContext()->GetObject(paramids[StructurIndex])); if (pout) { pout->GetValue(&value); } } return value; } /* ****************************************************************** * Function:GetObjectFromAttribute() * * Description : This is a template function specialization for CKBeObject*. Returns a input parameter value from a building block. * * Parameters : CKBehavior *beh, r : the behavior context const unsigned short pos, r : the parameter input index * Returns : CKBeObject. * ******************************************************************* */ template<class T>__inline T GetValueFromAttribute(CKBeObject *_e,int attributeID) { T value; CKParameterOut* pout = _e->GetAttributeParameter(attributeID); if (pout) { pout->GetValue(&value); } return value; } }/* end namespace attribute tools*/ } #endif <file_sep>#include <virtools/vtcxglobal.h> #include ".\GBLAsyncBlock.h" /* ******************************************************************* * Function: CKObjectDeclaration *FillBehaviour( void ) * * Description : As its name infers, this function describes each Building Block * on a functional level : what it can be applied to, its GUID, its * creation function, etc.. * * * Paramters : * None * * Returns : CKObjectDeclaration *, containing: * - The type of object declaration ( Must Be CKDLL_BEHAVIORPROTOTYPE ) * - The function that will create the CKBehaviorPrototype for this behavior. * - A short description of what the behavior is supposed to do. * - The category in which this behavior will appear in the Virtools interface. * - A unique CKGUID * - Author and Version info * - The class identifier of objects to which the behavior can be applied to. * ******************************************************************* */ CKObjectDeclaration * ExeInThread::FillBehaviour( void ) { CKObjectDeclaration *objectDeclaration = CreateCKObjectDeclaration( "ExecuteBBInThread" ); objectDeclaration->SetType( CKDLL_BEHAVIORPROTOTYPE ); objectDeclaration->SetCreationFunction( ExeInThread::CreatePrototype ); objectDeclaration->SetDescription( "Executes a BB in a Thread" ); objectDeclaration->SetCategory( "Narratives/Script Management" ); objectDeclaration->SetGuid( CKGUID( 0x72387e71,0x89d786d) ); objectDeclaration->SetVersion( 0x00000001 ); objectDeclaration->SetAuthorGuid( VTCX_AUTHOR_GUID ); objectDeclaration->SetAuthorName( VTCX_AUTHOR ); objectDeclaration->SetCompatibleClassId( CKCID_BEOBJECT ); return objectDeclaration; } /* ******************************************************************* * Function: CKERROR CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ) * * Description : The prototype creation function will be called the first time * a behavior must be created to create the CKBehaviorPrototype * that contains the description of the behavior. * * Paramters : * behaviorPrototypePtr w Pointer to a CKBehaviorPrototype object that * describes the behavior's internal structure * and relationships with other objects. * * Returns : CKERROR * ******************************************************************* */ CKERROR ExeInThread::CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ) { CKBehaviorPrototype *behaviorPrototype = CreateCKBehaviorPrototype( "ExecuteBBInThread" ); if ( !behaviorPrototype ) { return CKERR_OUTOFMEMORY; } //--- Inputs declaration behaviorPrototype->DeclareInput( "In" ); //--- Outputs declaration behaviorPrototype->DeclareOutput( "Out" ); //---- Local Parameters Declaration behaviorPrototype->DeclareLocalParameter("thethread", CKPGUID_POINTER, "0"); behaviorPrototype->DeclareLocalParameter("thestatus", CKPGUID_INT, "0"); //---- Settings Declaration behaviorPrototype->SetBehaviorCallbackFct( ExeInThread::CallBack, CKCB_BEHAVIORATTACH|CKCB_BEHAVIORDETACH|CKCB_BEHAVIORDELETE|CKCB_BEHAVIOREDITED|CKCB_BEHAVIORSETTINGSEDITED|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORPRESAVE|CKCB_BEHAVIORPOSTSAVE|CKCB_BEHAVIORRESUME|CKCB_BEHAVIORPAUSE|CKCB_BEHAVIORRESET|CKCB_BEHAVIORRESET|CKCB_BEHAVIORDEACTIVATESCRIPT|CKCB_BEHAVIORACTIVATESCRIPT|CKCB_BEHAVIORREADSTATE, NULL ); behaviorPrototype->SetFunction( ExeInThread::BehaviourFunction ); *behaviorPrototypePtr = behaviorPrototype; return CK_OK; } /* ******************************************************************* * Function: int BehaviourFunction( const CKBehaviorContext& behaviorContext ) * * Description : The execution function is the function that will be called * during the process loop of the behavior engine, if the behavior * is defined as using an execution function. This function is not * called if the behavior is defined as a graph. This function is the * heart of the behavior: it should compute the essence of the behavior, * in an incremental way. The minimum amount of computing should be * done at each call, to leave time for the other behaviors to run. * The function receives the delay in milliseconds that has elapsed * since the last behavioral process, and should rely on this value to * manage the amount of effect it has on its computation, if the effect * of this computation relies on time. * * Paramters : * behaviourContext r Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : int, If it is done, it should return CKBR_OK. If it returns * CKBR_ACTIVATENEXTFRAME, the behavior will again be called * during the next process loop. * ******************************************************************* */ int ExeInThread::BehaviourFunction( const CKBehaviorContext& behaviorContext ) { CKBehavior* beh = behaviorContext.Behavior; CKContext* ctx = beh->GetCKContext(); if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); VxThread *VXT; int status = 0; beh->GetLocalParameterValue(1,&status); if (status == ThreadStatus::Requested) { return CKBR_ACTIVATENEXTFRAME; } if (status == ThreadStatus::Active) { status = ThreadStatus::Requested; beh->SetLocalParameterValue(1,&status); return CKBR_ACTIVATENEXTFRAME; } VXT = new VxThread(); VXT->SetName("Thread"); VXT->SetPriority(VXTP_NORMAL); AsyncThreadInfo * threadInfo; threadInfo = new AsyncThreadInfo; threadInfo->targetBeh = NULL; int count = beh->GetParent()->GetSubBehaviorLinkCount(); for (int i=0; i<count; i++) { CKBehaviorLink *link = beh->GetParent()->GetSubBehaviorLink(i); if (link->GetInBehaviorIO() == beh->GetOutput(0)) { threadInfo->targetBeh = link->GetOutBehaviorIO()->GetOwner(); int targetInputs = threadInfo->targetBeh->GetInputCount(); if (targetInputs == 1) { threadInfo->targetInputToActivate = 0; } else { for (int j=0; j<targetInputs; j++) { if (link->GetOutBehaviorIO() == threadInfo->targetBeh->GetInput(j)) { threadInfo->targetInputToActivate = j; break; } } } break; } } if (threadInfo->targetBeh == NULL) { delete threadInfo; return CKBR_BEHAVIORERROR; } VXT->CreateThread(BlockingThreadFunction,threadInfo); beh->SetLocalParameterValue(0,&VXT,sizeof(VxThread *)); status = ThreadStatus::Active; beh->SetLocalParameterValue(1,&status); return CKBR_ACTIVATENEXTFRAME; } else { VxThread *VXT; beh->GetLocalParameterValue(0,&VXT); unsigned int status = -1; VXT->GetExitCode(status); if (status == VXT_OK) { VXT->Close(); delete VXT; VXT=NULL; beh->SetLocalParameterValue(0,&VXT); int status; beh->GetLocalParameterValue(1,&status); if (status == ThreadStatus::Requested) { beh->ActivateInput(0); status = ThreadStatus::Idle; beh->SetLocalParameterValue(1,&status); return CKBR_ACTIVATENEXTFRAME; } status = ThreadStatus::Idle; beh->SetLocalParameterValue(1,&status); return CKBR_OK; } } return CKBR_ACTIVATENEXTFRAME; } /* ******************************************************************* * Function: int Callback( const CKBehaviorContext& behaviorContext ) * * Description : The Behavior Callback function is called by Virtools when various events happen * in the life of a BuildingBlock. Exactly which events trigger a call to the * Behavior Callback function is defined in the Behavior Prototype, along with the * declaration of the function pointer * * Parameters : * behaviourContext r Behavior context reference, which gives * access to frequently used global objects * ( context, level, manager, etc... ) * * Returns : int, The return value of the callback function should be one of the CK_BEHAVIOR_RETURN values. * ******************************************************************* */ int ExeInThread::CallBack( const CKBehaviorContext& behaviorContext ) { switch ( behaviorContext.CallbackMessage ) { case CKM_BEHAVIORATTACH: break; case CKM_BEHAVIORDETACH: break; case CKM_BEHAVIORDELETE: break; case CKM_BEHAVIOREDITED: break; case CKM_BEHAVIORSETTINGSEDITED: break; case CKM_BEHAVIORLOAD: break; case CKM_BEHAVIORPRESAVE: break; case CKM_BEHAVIORPOSTSAVE: break; case CKM_BEHAVIORRESUME: { int status = ThreadStatus::Idle; behaviorContext.Behavior->SetLocalParameterValue(1,&status); } break; case CKM_BEHAVIORPAUSE: break; case CKM_BEHAVIORRESET: break; case CKM_BEHAVIORNEWSCENE: break; case CKM_BEHAVIORDEACTIVATESCRIPT: break; case CKM_BEHAVIORACTIVATESCRIPT: break; case CKM_BEHAVIORREADSTATE: break; } return CKBR_OK; } unsigned int BlockingThreadFunction(void *arg) { ExeInThread::AsyncThreadInfo* threadInfo = (ExeInThread::AsyncThreadInfo*)arg; threadInfo->targetBeh->ActivateInput(threadInfo->targetInputToActivate); int res; do { res = threadInfo->targetBeh->Execute(0); } while (res == CKBR_ACTIVATENEXTFRAME); delete threadInfo; return VXT_OK; } <file_sep>#include "CKAll.h" CKObjectDeclaration *FillBehaviorSetMousPosDecl(); CKERROR CreateSetMousPosProto(CKBehaviorPrototype **pproto); int SetMousPos(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSetMousPosDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("SetMousePos"); od->SetCategory("Narratives/Mouse"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7938083c,0x32f03a3d)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetMousPosProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateSetMousPosProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("SetMousePos"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Create Zip File"); proto->DeclareOutput("Zip File created"); proto->DeclareInParameter("IsServer",CKPGUID_FLOAT); proto->DeclareInParameter("IsServer",CKPGUID_FLOAT); proto->DeclareOutParameter("UP",CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetMousPos); *pproto = proto; return CK_OK; } #include <Windows.h> int SetMousPos(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; if( beh->IsInputActive(0) ){ beh->ActivateInput(0,FALSE); DWORD data = 0; DWORD flags = MOUSEEVENTF_ABSOLUTE; // - Has the pointer moved since the last event? flags |= MOUSEEVENTF_MOVE; mouse_event(flags, 100,100, data, 0); beh->ActivateOutput(0); } return 0; } <file_sep>#include "precomp.h" #include "vtPrecomp.h" #include "vtNetAll.h" #include "xNetInterface.h" #include "tnlRandom.h" #include "tnlSymmetricCipher.h" #include "tnlAsymmetricKey.h" #include "xNetworkTypes.h" extern xNetInterface* GetNetInterfaceServer(); extern xNetInterface *GetNetInterfaceClient(); extern void SetNetInterfaceClient(xNetInterface *cInterface); extern void SetNetInterfaceServer(xNetInterface *cInterface); void vtNetworkManager::SetClientNetInterface(xNetInterface *cinterface) { SetNetInterfaceClient(cinterface);} void vtNetworkManager::SetServerNetInterface(xNetInterface *cinterface){ SetNetInterfaceServer(cinterface); } xNetInterface* vtNetworkManager::GetServerNetInterface() { return GetNetInterfaceServer(); } xNetInterface*vtNetworkManager::GetClientNetInterface(){ return GetNetInterfaceClient(); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// void vtNetworkManager::DeleteServer(int flags) { } <file_sep>#ifndef _BASE_ #define _BASE_ #include <iostream> #include <string> #include <list> #include <stdexcept> #include <algorithm> #include <typeinfo> #include <functional> extern "C" { #include <string.h> #include <math.h> #include <stdio.h> #include <stdlib.h> //#include <GL/gl.h> } // instantiate unit tests #ifdef DEBUG #define INSTANTIATE_TEST_SUITES2 extern bool _abortOnAssertionFailure; #endif namespace base { typedef unsigned char Byte; typedef int SInt; typedef unsigned int Int; typedef long unsigned int LInt; typedef std::string String; typedef double Real; // Real & GLreal must be the same built-in type /// throw a std::runtime_error(errorstring). If DEBUG, output an assertion failure message /// to the Log and abort() if abortOnAssertionFailure mode set void assertionFailure(const String& errorstring); template<typename A> inline void tassert(A assertion, const String& errorstring) { if (!assertion) assertionFailure(errorstring); } template<typename T> void clearMemory(T* start, Int length) { memset(start, 0, size_t(length*sizeof(T))); } template<typename T> void copyMemory(const T* src, T* dest, Int length) { memcpy(dest, src, length*sizeof(T)); } // convenience: subscripting & indexing for list ( O(n) ) template<typename T> const T& elementAt(const std::list<T>& l, typename std::list<T>::size_type i) { typename std::list<T>::const_iterator it = l.begin(); while ((it != l.end()) && (i > 0)) { ++it; --i; } if (it == l.end()) throw std::out_of_range("elementAt - specified index not present"); return *it; } template<typename T> T& elementAt(std::list<T>& l, typename std::list<T>::size_type i) { typename std::list<T>::iterator it = l.begin(); while ((it != l.end()) && (i > 0)) { ++it; --i; } if (it == l.end()) throw std::out_of_range("elementAt - specified index not present"); return *it; } class DeleteObject { public: template<typename T> void operator()(const T* ptr) const { delete ptr; } }; template<typename C> void delete_all(C& c) { for_all(c, DeleteObject()); } template<typename InputIterator, typename OutputIterator, typename Predicate> OutputIterator copy_if(InputIterator begin, InputIterator end, OutputIterator destBegin, Predicate p) { while(begin!=end) { if (p(*begin)) *destBegin++=*begin; ++begin; } return destBegin; } String intToString(Int i); String realToString(Real r); Int stringToInt(const String& s); Real stringToReal(const String& s); template<typename T> String toString(const T& t) { std::ostringstream oss; oss << t; return oss.str(); } template<typename T> T fromString(const String& s) { std::istringstream iss(s); T t; iss >> t; return t; } class Cloneable; template<typename C> C& clone(const C& c) { return dynamic_cast<C&>( static_cast<const Cloneable&>(c).clone()); } #ifndef VIRTOOLS extern std::ostream& _Debug; extern std::ostream& _Log; extern std::ostream& _Console; #else extern std::ostream& _Debug; extern std::ostream& _Log; extern std::ostream& _Console; #endif /// convert typeid().name() string into demangled form (e.g. "base::Object") String demangleTypeidName(const String& typeidName); /// convert type_info into qualified class name (calls demangleTypeidName() ) String className(const std::type_info& ti); extern int _currentDebugVerbosity; // make narrow casting explicit for readability template < typename Sub, typename Super> //inline Sub* narrow_cast(Select< SUPERSUBCLASS_STRICT(Super,Sub),Super*,NullType>::Result p) { return static_cast<Sub*>(p); } inline Sub* narrow_cast(Super* p) { return static_cast<Sub*>(p); } template < typename Sub, typename Super> //inline Sub& narrow_cast(Select< SUPERSUBCLASS_STRICT(Super,Sub),Super&,NullType>::Result p) { return static_cast<Sub&>(p); } inline Sub& narrow_cast(Super& p) { return static_cast<Sub&>(p); } } // base // global names using std::for_each; using std::mem_fun; using base::narrow_cast; // Use Log() funcions to output to the log file. This will remain in // release code. Use Debug() if you want output that will dissapear // in release code. Use Console() to write on the graphical console // (e.g. for user status messages etc.) // NB: see debugtools header for Debug() usage. //#include <bDebugtools.h> #ifdef __mips #define __func__ String("unknown") #endif #ifdef __GNUC_ #define _LOG_CALLER_NAME __PRETTY_FUNCTION__ << " -- " #else #define _LOG_CALLER_NAME base::className(typeid(*this)) << "::" << __FUNCTION__ << " -- " #endif #define Log(o) { base::_Log << _LOG_CALLER_NAME << o; } #define Logln(o) { base::_Log << _LOG_CALLER_NAME << o << "\n"; } #define Logc(o) { base::_Log << o; } #define Logcln(o) { base::_Log << o << "\n"; } #define Logf(o) { base::_Log << __func__ << " -- " << o; } #define Logfln(o) { base::_Log << __func__ << " -- " << o << "\n"; } #define Logfc(o) Logc(o) #define Logfcln(o) Logcln(o) #define Console(o) { base::_Console << o; } #define Consoleln(o) { base::_Console << o << std::endl; } // Often, when an Assert() fails, it is not clear where the exception // was raised from the message alone. Enabling this flag will cause // the program to abort() from inside Assert() so that a debugger // stack trace can show the point of failure. #ifdef DEBUG extern bool _abortOnAssertionFailure; #define abortOnAssertionFailureEnabled(e) _abortOnAssertionFailure=(e) #else #define abortOnAssertionFailureEnabled(e) #endif // During development it is not unusual for exceptions to be thrown in unexpected places. For example, // from a function declared with throw(). It also happens when an exception tries to propagate // through C code in the call stack. For example, this is common if the main loop of the app // is being executed from a C library callback (e.g. from GLUT). // This typically results in a call to abort() before the exception is caught. The only way to trace where // the exception was thrown in that case is via the debugger. To make life a little easier, in DEBUG mode // the Exception() macro is defined to print the exception text upon construction - so it can be seen even if // the exception is not caught. However, this can be annoying in circumstances when exceptions are // expected (for example, in test cases that test for correct exception throwing). Consequently, it may // be disabled. #ifdef DEBUG extern bool _outputExceptionOnConstruction; #define exceptionOutputEnabled(e) _outputExceptionOnConstruction=(e) #else #define exceptionOutputEnabled(e) #endif #ifdef __GNUC__ #ifdef DEBUG #define Exception(o) (( (_outputExceptionOnConstruction?(printf("constructing exception: %s\n", \ (String(__PRETTY_FUNCTION__)+" (line "+base::intToString(__LINE__)+") - "+String(o)).c_str())):(0)) ), \ String(String("exception thrown: ")+__PRETTY_FUNCTION__+":\n - "+String(o))) #else // ndef DEBUG #define Exception(o) String(String("exception thrown: ")+__PRETTY_FUNCTION__+" - "+String(o)) #endif // DEBUG #define Exceptionf(o) String(String("exception thrown: ")+__PRETTY_FUNCTION__+":\n - "+String(o)) #define Assertion(o) String(String("assertion failed: ")+__PRETTY_FUNCTION__+" (line "+base::intToString(__LINE__)+") - "+String(o)) #define Assertionf(o) String(String("assertion failed: ")+__PRETTY_FUNCTION__+" (line "+base::intToString(__LINE__)+") - "+String(o)) #else // ndef __GNUC__ #ifdef DEBUG #define Exception(o) (( (_outputExceptionOnConstruction?(printf("constructing exception: %s\n", \ (String(base::className(typeid(*this)))+"::"+String(__func__)+" - "+String(o)).c_str())):(0) )), \ String(String("exception thrown: ")+String(base::className(typeid(*this)))+"::"+String(__func__)+":\n - "+String(o))) #else #define Exception(o) String(String("exception thrown: ")+String(base::className(typeid(*this)))+"::"+String(__func__)+":\n - "+String(o)) #endif #define Exceptionf(o) String(String("exception thrown: ")+String(__func__)+":\n - "+String(o)) #define Assertion(o) String(String("assertion failed: ")+String(base::className(typeid(*this)))+"::"+String(__func__)+" - "+String(o)) #define Assertionf(o) String(String("assertion failed: ")+String(__func__)+" - "+String(o)) #endif // __GNUC__ #ifdef DEBUG #define Assert(a) { if (!(a)) base::assertionFailure(Assertion(#a)); } #define Assertf(a) { if (!(a)) base::assertionFailure(Assertionf(#a)); } #define Assertm(a,s) { if (!(a)) base::assertionFailure(Assertion(s)); } #define Assertmf(a,s) { if (!(a)) base::assertionFailure(Assertionf(s)); } #else // ndef DEBUG #define Assert(a) #define Assertf(a) #define Assertm(a,s) #define Assertmf(a,s) #endif // DEBUG #define Assertifm(f,a,s) Assertm(!f || a,s) #define Assertifmf(f,a,s) Assertmf(!f || a,s) #define instanceof(var,type) (dynamic_cast<type*>(&var) != 0) #endif <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Noise // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorNoiseDecl(); CKERROR CreateNoiseProto(CKBehaviorPrototype **); int Noise(const CKBehaviorContext& behcontext); //CKERROR MeshModificationsCallBack(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorNoiseDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Noise2"); od->SetDescription("Displaces the vertices of the mesh with a random vector."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Seed: </SPAN>generates a random starting point from the number you set.<BR> <SPAN CLASS=pin>Scale: </SPAN>size of noise effect (not strength).<BR> <SPAN CLASS=pin>Axis: </SPAN>strength of the noise effect along each of three axes.<BR> <SPAN CLASS=pin>Reset Mesh: </SPAN>if TRUE, the mesh is reseted to its initial conditions at activation.<BR> */ od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x6d300730,0x26c83f42)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00020000); od->SetCreationFunction(CreateNoiseProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Mesh Modifications/Deformation"); return od; } CKERROR CreateNoiseProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("Noise2"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Seed", CKPGUID_FLOAT,"0.1" ); proto->DeclareInParameter("Scale", CKPGUID_FLOAT ,"50.0"); // To change by Radio buttons proto->DeclareInParameter("Axis", CKPGUID_VECTOR, "0.1,0,0" ); proto->DeclareInParameter("Reset Mesh", CKPGUID_BOOL, "TRUE" ); proto->DeclareInParameter("target", CKPGUID_3DENTITY); proto->DeclareLocalParameter("data", CKPGUID_VOIDBUF ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(Noise); //proto->SetBehaviorCallbackFct(MeshModificationsCallBack); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } #define B 0x100 #define BM 0xff #define N 0x1000 #define NP 12 /* 2^N */ #define NM 0xfff static int p[B + B + 2]; static float g3[B + B + 2][3]; static float g2[B + B + 2][2]; static float g1[B + B + 2]; static int start = 1; static void init(void); #define s_curve(t) ( t * t * (3.0f - 2.0f * t) ) #define lerp(t, a, b) ( a + t * (b - a) ) #define setup(i,b0,b1,r0,r1)\ t = vec[i] + N;\ b0 = ((int)t) & BM;\ b1 = (b0+1) & BM;\ r0 = t - (int)t;\ r1 = r0 - 1.0f; float noise3(const VxVector &vect) { const float *vec = vect.v; int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v; register int i, j; if (start) { start = 0; init(); } setup(0, bx0,bx1, rx0,rx1); setup(1, by0,by1, ry0,ry1); setup(2, bz0,bz1, rz0,rz1); i = p[ bx0 ]; j = p[ bx1 ]; b00 = p[ i + by0 ]; b10 = p[ j + by0 ]; b01 = p[ i + by1 ]; b11 = p[ j + by1 ]; t = s_curve(rx0); sy = s_curve(ry0); sz = s_curve(rz0); #define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] ) q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0); q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0); a = lerp(t, u, v); q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0); q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0); b = lerp(t, u, v); c = lerp(sy, a, b); q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1); q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1); a = lerp(t, u, v); q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1); q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1); b = lerp(t, u, v); d = lerp(sy, a, b); return lerp(sz, c, d); } static void normalize2(float v[2]) { float s; s = 1.0f / sqrtf(v[0] * v[0] + v[1] * v[1]); v[0] = v[0] * s; v[1] = v[1] * s; } static void normalize3(float v[3]) { float s; s = 1.0f / sqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); v[0] = v[0] * s; v[1] = v[1] * s; v[2] = v[2] * s; } static void init(void) { int i, j, k; for (i = 0 ; i < B ; i++) { p[i] = i; g1[i] = (float)((rand() % (B + B)) - B) / B; for (j = 0 ; j < 2 ; j++) g2[i][j] = (float)((rand() % (B + B)) - B) / B; normalize2(g2[i]); for (j = 0 ; j < 3 ; j++) g3[i][j] = (float)((rand() % (B + B)) - B) / B; normalize3(g3[i]); } while (--i) { k = p[i]; p[i] = p[j = rand() % B]; p[j] = k; } for (i = 0 ; i < B + 2 ; i++) { p[B + i] = p[i]; g1[B + i] = g1[i]; for (j = 0 ; j < 2 ; j++) g2[B + i][j] = g2[i][j]; for (j = 0 ; j < 3 ; j++) g3[B + i][j] = g3[i][j]; } } int Noise(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; // we get the 3d entity CK3dEntity *ent = (CK3dEntity *) beh->GetInputParameterObject(4); if(!ent) return 0; // we get the seed value float seed=0.1f; CKParameterIn *pin = beh->GetInputParameter(0); if( pin->GetGUID() == CKPGUID_INT ){ // back compatibility int seed_int = 0; pin->GetValue( &seed_int ); seed = (float)seed_int; } else { beh->GetInputParameterValue(0,&seed); } seed *= 0.01f; // we get the scale value float scale; beh->GetInputParameterValue(1,&scale); // we get the amount value VxVector axis; beh->GetInputParameterValue(2,&axis); // we get the mesh CKMesh *mesh = ent->GetCurrentMesh(); CKDWORD vStride=0; BYTE* varray = (BYTE*)mesh->GetModifierVertices(&vStride); int pointsNumber = mesh->GetModifierVertexCount(); CKBOOL resetmesh = TRUE; beh->GetInputParameterValue(3,&resetmesh); if (resetmesh) { // The Mesh must be reseted if(beh->GetVersion() < 0x00020000) { // Old Version with vertices stuffed inside // we get the saved position VxVector* savePos = (VxVector*)beh->GetLocalParameterWriteDataPtr(0); BYTE* temparray = varray; for(int i=0;i<pointsNumber;i++,temparray+=vStride) { *(VxVector*)temparray = savePos[i]; } } else { // new version : based on ICs CKScene *scn = behcontext.CurrentScene; CKStateChunk *chunk = scn->GetObjectInitialValue(mesh); if(chunk) mesh->LoadVertices(chunk); varray = (BYTE*)mesh->GetModifierVertices(&vStride); pointsNumber = mesh->GetModifierVertexCount(); } } // we move all the points VxVector v,sp,d(0,0,0); VxVector offset(0.5f,0.5f,0.5f); VxVector noise_vect(0,0,seed); for(int i=0;i<pointsNumber;i++,varray+=vStride) { v = *(VxVector*)varray; sp = v * scale + offset; noise_vect.x = sp.y; noise_vect.y = sp.z; d.x = noise3(noise_vect); noise_vect.x = sp.x; d.y = noise3(noise_vect); noise_vect.y = sp.y; d.z = noise3(noise_vect); *(VxVector*)varray = (v+(d*axis)); } mesh->ModifierVertexMove(TRUE,TRUE); beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); return CKBR_OK; } <file_sep>#ifndef InitMAN_H #define InitMAN_H #include "CKBaseManager.h" #define INIT_MAN_GUID CKGUID(0x6add640f,0x1acc1484) class Python; class PythonModule; #include <stdlib.h> #include <map> #include "pyembed.h" typedef std::map<CK_ID,PyObject*>PModules; typedef std::map<CK_ID,PyObject*>::iterator PModulesIt; typedef std::map<CK_ID,PythonModule*>VSLPModules; typedef std::map<CK_ID,PythonModule*>::iterator VSLPModulesIt; class vt_python_man : public CKBaseManager { public: //Ctor vt_python_man(CKContext* ctx); //Dtor ~vt_python_man(); Python *py; static vt_python_man*GetPyMan(); PModules m_pModules; CK_ID m_CurrentId; CK_ID CurrentId() const { return m_CurrentId; } void CurrentId(CK_ID val) { m_CurrentId = val; } PModules& GetPModules(){return m_pModules;} PyObject *InsertPModule(CK_ID id,XString name,bool reload); void RemovePModule(CK_ID id); PyObject *GetPModule(CK_ID id); void CallPyModule(CK_ID id,XString func); void CallPyModule(CK_ID id,Arg_mmap *args,XString func); void CallPyModule(CK_ID id,XString func,const Arg_mmap& args,std::string& ret); void CallPyModule(CK_ID id,XString func,const Arg_mmap& args,double& ret); void CallPyModule(CK_ID id,XString func,const Arg_mmap& args,long& ret); void ClearModules(); VSLPModules m_PVSLModules; VSLPModules& GetVSLPModules(){ return m_PVSLModules;} PythonModule *CreatePythonModule(char*file,char*func,CK_ID bid); PythonModule *DestroyPythonModule(CK_ID bid); PythonModule *GetPythonModule(CK_ID bid); void ClearPythonModules(); void InsertPVSLModule(PythonModule *pMod); XString m_stdOut; XString m_stdErr; int InitPythonModules(); // Initialization virtual CKERROR OnCKInit(); virtual CKERROR OnCKEnd(); virtual CKERROR OnCKReset(); virtual CKERROR PreProcess(); virtual CKERROR PostProcess(); virtual CKERROR PostClearAll(); virtual CKERROR OnCKPlay(); virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_OnCKInit| CKMANAGER_FUNC_PostProcess| CKMANAGER_FUNC_OnCKEnd| CKMANAGER_FUNC_OnCKReset| CKMANAGER_FUNC_PreProcess| CKMANAGER_FUNC_PostClearAll| CKMANAGER_FUNC_OnCKPlay; } /************************************************************************/ /* Parameter Functions */ /************************************************************************/ void RegisterVSL(); bool pLoaded; }; #endif <file_sep>#include "xDistributedProperty.h" #include "xPredictionSetting.h" uxString xDistributedProperty::print(TNL::BitSet32 flags) { return uxString(); } xDistributedProperty::xDistributedProperty(xDistributedPropertyInfo *propInfo) : m_PropertyInfo( propInfo) { m_BlockIndex = 0; mLastTime = 0; mThresoldTicker =0; mCurrentTime =0; mLastDeltaTime =0; mThresoldTicker2 =0.0f; mLastTime2 = 0.0f; mLastDeltaTime2 =0.0; m_PredictionSettings = new xPredictionSetting(); m_PredictionSettings->setMinDifference(1.0f); m_PredictionSettings->setMinSendTime(50.0f); m_PredictionSettings->setPredictionFactor( 10.0f); } void xDistributedProperty::advanceTime(xTimeType time1,float lastDeltaTime2 ) { mLastTime2 = mLastTime2 + lastDeltaTime2; mLastDeltaTime2 = lastDeltaTime2; mThresoldTicker2 = mThresoldTicker2 + lastDeltaTime2; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedProperty::unpack( xNStream *bstream,float sendersOneWayTime ) { } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedProperty::pack(xNStream *bstream) { } <file_sep>DEV35DIR="x:/sdk/dev35" DEV40DIR="x:/sdk/dev4" DEV41DIR="x:/sdk/dev41R" DEV5DIR="x:/sdk/dev5GA" WEBPLAYERDIR="c:/Programme/Virtools/3D Life Player" <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorDOCreateDistributedObjectDecl(); CKERROR CreateDOCreateDistributedObjectProto(CKBehaviorPrototype **); int DOCreateDistributedObject(const CKBehaviorContext& behcontext); CKERROR DOCreateDistributedObjectCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 typedef enum BB_INPAR { BB_IP_CONNECTION_ID, BB_IP_OBJECT, BB_IP_OBJECT_NAME, }; typedef enum BB_OT { BB_O_EXIT, BB_O_CREATED, BB_O_ERROR }; typedef enum BB_OP { BB_OP_OBJECT_ID, BB_OP_ERROR }; CKObjectDeclaration *FillBehaviorDOCreateDistributedObjectDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DOCreate"); od->SetDescription("Creates an distributed object"); od->SetCategory("TNL/Distributed Objects"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x4b134dfa,0xaca30cb)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDOCreateDistributedObjectProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateDOCreateDistributedObjectProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("DOCreate"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Exit In"); proto->DeclareOutput("Created"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Object", CKPGUID_BEOBJECT, "test"); proto->DeclareInParameter("Object Name", CKPGUID_STRING, "test"); proto->DeclareOutParameter("Distributed Object ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareSetting("Class", CKPGUID_STRING, "My3DClass"); proto->DeclareSetting("Timeout", CKPGUID_TIME, "0"); proto->DeclareLocalParameter("elapsed time", CKPGUID_FLOAT, "0.0f"); proto->DeclareLocalParameter("Creation Status", CKPGUID_INT, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(DOCreateDistributedObject); proto->SetBehaviorCallbackFct(DOCreateDistributedObjectCB); *pproto = proto; return CK_OK; } int DOCreateDistributedObject(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; using namespace vtTools::BehaviorTools; ////////////////////////////////////////////////////////////////////////// //connection id : int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *obj= (CK3dEntity*)beh->GetInputParameterObject(1); if (!obj) { bbError(E_NWE_INVALID_PARAMETER); return 0; } ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } //use objects name, if not specified : CKSTRING name=vtTools::BehaviorTools::GetInputParameterValue<CKSTRING>(beh,2); if (!strlen(name)) { name = obj->GetName(); } IDistributedObjects*doInterface = cin->getDistObjectInterface(); IDistributedClasses*cInterface = cin->getDistributedClassInterface(); XString className((CKSTRING) beh->GetLocalParameterReadDataPtr(0)); xDistributedClass *classTemplate = cInterface->get(className.CStr()); ////////////////////////////////////////////////////////////////////////// //dist class ok ? if (!classTemplate) { bbError(E_NWE_INTERN); return 0; } int classType = classTemplate->getEnitityType(); ////////////////////////////////////////////////////////////////////////// //we come in by input 0 : if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); //reset elapsed time : float elapsedTime = 0.0f; beh->SetLocalParameterValue(2,&elapsedTime); //reset status to incomplete int creationStatus = E_DO_CREATION_INCOMPLETE; beh->SetLocalParameterValue(3,&creationStatus); xDistributedObject *dobj = doInterface->get(name); if (!dobj) { doInterface->create(name,className.CStr()); beh->ActivateOutput(0); } } ////////////////////////////////////////////////////////////////////////// //we come in by loop : //pickup the creations state : int creationState=0; beh->GetLocalParameterValue(3,&creationState); if (creationState == E_DO_CREATION_INCOMPLETE ) { //we requested a dist object already, check the its timeout : float elapsedTime = 0.0f; beh->GetLocalParameterValue(2,&elapsedTime); //pickup creations timeout settings : float timeOut=0.0f; beh->GetLocalParameterValue(1,&timeOut); ////////////////////////////////////////////////////////////////////////// //timeout reached : reset everything back if (elapsedTime > timeOut) { //reset output server id : int ids = -1; beh->SetOutputParameterValue(0,&ids); //output an error string : CKParameterOut *pout = beh->GetOutputParameter(1); XString errorMesg("distributed object creation failed, timeout reached"); pout->SetStringValue(errorMesg.Str()); //store state : int state = E_DO_CREATION_NONE; beh->SetLocalParameterValue(3,&state); //finish, activate error output trigger: beh->ActivateOutput(2); return 0; } else // increase and store elapsed time : { float dt = ctx->GetTimeManager()->GetLastDeltaTime(); elapsedTime+=dt; beh->SetLocalParameterValue(2,&elapsedTime); } ////////////////////////////////////////////////////////////////////////// //we are within the timeout range, check we have a successfully created object by the server : xDistributedObject *dobj = doInterface->get(name); if (dobj && isFlagOn(dobj->getObjectStateFlags(),E_DOSF_UNPACKED) && !isFlagOn(dobj->getObjectStateFlags(),E_DOSF_SHOWN)) { enableFlag(dobj->getObjectStateFlags(),E_DOSF_SHOWN); xLogger::xLog(XL_START,ELOGTRACE,E_LI_3DOBJECT,"distributed object creation finish"); if (obj) { dobj->setEntityID(obj->GetID()); xDistributed3DObject *dobj3D = static_cast<xDistributed3DObject*>(dobj); if (dobj3D) { } } //store state : int state = E_DO_CREATION_NONE; beh->SetLocalParameterValue(3,&state); //store elapsed time : elapsedTime = 0.0f; beh->SetLocalParameterValue(2,&elapsedTime); //output server id : int index = dobj->getServerID(); beh->SetOutputParameterValue(0,&index); CKParameterOut *pout = beh->GetOutputParameter(1); XString errorMesg("No Error"); pout->SetStringValue(errorMesg.Str()); //return : beh->ActivateOutput(1); return 0; } } return CKBR_ACTIVATENEXTFRAME; } CKERROR DOCreateDistributedObjectCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>SET devdir=X:\sdk\msvc\Common7\IDE\ SET devexe=X:\sdk\msvc\Common7\IDE\devenv.com SET solution=X:\ProjectRoot\svn\pearls-media\private\virtools\vtPhysX\build4\vs2003Dev40\vtPhysX.sln REM cd %devdir% %devexe% %solution% /out x:\logDev42003.txt /Build "ReleaseDemo" <file_sep>#pragma once ///////////////////////////////////////////////////////////// // Externs binding must use these macro // This macro is duplicated in VSL projet, // because we don't want to provide VSL src in the SDK #define NODEFAULT nodefault #define STARTVSLBIND(context) using namespace VSL; \ VSLManager *VSLM = (VSLManager *)context->GetManagerByGuid(VSLMANAGER_GUID); \ if (VSLM) { VSLM->RegisterSpace(); #define STOPVSLBIND } #define REGISTERVSLGUID(iGUID, iClassName) VSLM->RegisterGUID(iGUID, iClassName); ///////////////////////////////////////////////////////////// // Type Declaration // TODO : 3 param = alias type::RawName() // Special class option for CKObjects #ifndef VCLASSOPTION_USERDATA #define VCLASSOPTION_USERDATA(x) ((x << 24) & 0xFF000000) #endif #define VCLASSOPTION_CKOBJECT VCLASSOPTION_USERDATA(1) #define VCLASSOPTION_PINBYPOINTER VCLASSOPTION_USERDATA(2) #define DECLARETYPE(type) VSLM->RegisterClass(#type, sizeof(type)); #define DECLARETYPEALIAS(type,alias) VSLM->RegisterClass(#type, sizeof(type), alias); #define DECLARETYPEWITHREF(type,ref) VSLM->RegisterClass(#type, ref); #define DECLARETYPEALIASWITHREF(type,ref,alias) VSLM->RegisterClass(#type, ref, alias); #if defined(_DEBUG) && !defined(VIRTOOLS_USER_SDK) #define DECLAREDOCSDKLINK(type,link) VSLM->RegisterClassDocSDKLink(#type, link); #else #define DECLAREDOCSDKLINK(type,link) #endif #define DECLAREPOINTERTYPE(type) VSLM->RegisterClass(#type, sizeof(type), NULL, VCLASSOPTION_POINTERCOPY); #define DECLAREPOINTERTYPEALIAS(type,alias) VSLM->RegisterClass(#type, sizeof(type), alias, VCLASSOPTION_POINTERCOPY); #define DECLARECKOBJECTTYPEALIAS(type,alias) VSLM->RegisterClass(#type, sizeof(type), alias, VCLASSOPTION_POINTERCOPY|VCLASSOPTION_CKOBJECT); #define DECLAREOBJECTTYPE(type) VSLM->RegisterClass(#type, sizeof(type), NULL, VCLASSOPTION_MEMCOPY); #define DECLAREOBJECTTYPEALIAS(type,alias) VSLM->RegisterClass(#type, sizeof(type), alias, VCLASSOPTION_MEMCOPY); #define DECLAREOBJECTTYPEALIAS_PINBYPOINTER(type,alias) VSLM->RegisterClass(#type, sizeof(type), alias, VCLASSOPTION_MEMCOPY|VCLASSOPTION_PINBYPOINTER); #define DECLAREINHERITANCESIMPLE(a,b) VSLM->RegisterHeritage(a,b,0); #define DECLAREINHERITANCEDOUBLE(a,b,c) VSLM->RegisterHeritage(a,b,c,0); #define REGISTERCONST(name,type,data) VSLM->RegisterConstant(name,type,data); /////////////////////////////////////////////////////////////////// // Enum #define DECLAREENUM(enumName) VSLM->RegisterEnum(enumName); #define DECLAREENUMVALUE(enumName,valueName,value) VSLM->RegisterEnumMember(enumName,valueName,value); /////////////////////////////////////////////////////////////////// // Enum enum BindedConstType { BIND_BOOL, BIND_CHAR, BIND_INT, BIND_FLOAT }; #define DECLARECONST(constName,constType,value) VSLM->RegisterConstant(constName,constType,value); /////////////////////////////////////////////////////////////////// // Member Declaration #if defined(macintosh) || defined(PSX2) || defined(PSP) || (_XBOX_VER>=200) #define DECLAREMEMBER(classe,mtype,member) { \ classe* instance = NULL; \ int offset = (int) &(instance->member); \ XASSERT((offset + sizeof(mtype)) <= sizeof(classe)); \ VSLM->RegisterMember(#classe,#member,#mtype, offset);\ } #else #define DECLAREMEMBER(classe,mtype,member) { \ typedef mtype (classe::*mptr); \ mptr var = (mptr)(&classe::member); \ void* ptr = (void*)*(DWORD*)&var; \ VSLM->RegisterMember(#classe,#member,#mtype,(int)ptr);\ } #endif ///////////////////////////////////////////////////////////// // function Declaration #define DECLAREFUN_0(ret,func,callconv) {\ typedef ret (*fptr)(); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,0,#ret);\ } #define DECLAREFUN_C_0(ret,func) DECLAREFUN_0(ret,func,VCALLTYPE_CDECL) #define DECLAREFUN_S_0(ret,func) DECLAREFUN_0(ret,func,VCALLTYPE_STDCALL) #define DECLAREFUN_1(ret,func,arg1,callconv) {\ typedef ret (*fptr)(arg1); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,1,#ret,#arg1);\ } #define DECLAREFUN_1_WITH_DEF_VALS(ret,func,arg1,defVal1,callconv) {\ typedef ret (*fptr)(arg1); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,1,#ret,#arg1" = "#defVal1);\ } #define DECLAREFUN_C_1(ret,func,arg1) DECLAREFUN_1(ret,func,arg1,VCALLTYPE_CDECL) #define DECLAREFUN_S_1(ret,func,arg1) DECLAREFUN_1(ret,func,arg1,VCALLTYPE_STDCALL) #define DECLAREFUN_C_1_WITH_DEF_VALS(ret,func,arg1,defVal1) DECLAREFUN_1_WITH_DEF_VALS(ret,func,arg1,defVal1,VCALLTYPE_CDECL) #define DECLAREFUN_S_1_WITH_DEF_VALS(ret,func,arg1,defVal1) DECLAREFUN_1_WITH_DEF_VALS(ret,func,arg1,defVal1,VCALLTYPE_STDCALL) #define DECLAREFUN_2(ret,func,arg1,arg2,callconv) { \ typedef ret (*fptr)(arg1,arg2); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,2,#ret,#arg1,#arg2); \ } #define DECLAREFUN_2_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,callconv) { \ typedef ret (*fptr)(arg1,arg2); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,2,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2); \ } #define DECLAREFUN_C_2(ret,func,arg1,arg2) DECLAREFUN_2(ret,func,arg1,arg2,VCALLTYPE_CDECL) #define DECLAREFUN_S_2(ret,func,arg1,arg2) DECLAREFUN_2(ret,func,arg1,arg2,VCALLTYPE_STDCALL) #define DECLAREFUN_C_2_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2) DECLAREFUN_2_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,VCALLTYPE_CDECL) #define DECLAREFUN_S_2_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2) DECLAREFUN_2_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,VCALLTYPE_STDCALL) #define DECLAREFUN_3(ret,func,arg1,arg2,arg3,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,3,#ret,#arg1,#arg2,#arg3);\ } #define DECLAREFUN_3_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,3,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3);\ } #define DECLAREFUN_C_3(ret,func,arg1,arg2,arg3) DECLAREFUN_3(ret,func,arg1,arg2,arg3,VCALLTYPE_CDECL) #define DECLAREFUN_S_3(ret,func,arg1,arg2,arg3) DECLAREFUN_3(ret,func,arg1,arg2,arg3,VCALLTYPE_STDCALL) #define DECLAREFUN_C_3_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3) DECLAREFUN_3_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,VCALLTYPE_CDECL) #define DECLAREFUN_S_3_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3) DECLAREFUN_3_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,VCALLTYPE_STDCALL) #define DECLAREFUN_4(ret,func,arg1,arg2,arg3,arg4,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3,arg4); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,4,#ret,#arg1,#arg2,#arg3,#arg4);\ } #define DECLAREFUN_4_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3,arg4); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,4,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4);\ } #define DECLAREFUN_C_4(ret,func,arg1,arg2,arg3,arg4) DECLAREFUN_4(ret,func,arg1,arg2,arg3,arg4,VCALLTYPE_CDECL) #define DECLAREFUN_S_4(ret,func,arg1,arg2,arg3,arg4) DECLAREFUN_4(ret,func,arg1,arg2,arg3,arg4,VCALLTYPE_STDCALL) #define DECLAREFUN_C_4_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4) DECLAREFUN_4_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,VCALLTYPE_CDECL) #define DECLAREFUN_S_4_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4) DECLAREFUN_4_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,VCALLTYPE_STDCALL) #define DECLAREFUN_5(ret,func,arg1,arg2,arg3,arg4,arg5,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,5,#ret,#arg1,#arg2,#arg3,#arg4,#arg5);\ } #define DECLAREFUN_5_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,5,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5);\ } #define DECLAREFUN_C_5(ret,func,arg1,arg2,arg3,arg4,arg5) DECLAREFUN_5(ret,func,arg1,arg2,arg3,arg4,arg5,VCALLTYPE_CDECL) #define DECLAREFUN_S_5(ret,func,arg1,arg2,arg3,arg4,arg5) DECLAREFUN_5(ret,func,arg1,arg2,arg3,arg4,arg5,VCALLTYPE_STDCALL) #define DECLAREFUN_C_5_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5) DECLAREFUN_5_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,VCALLTYPE_CDECL) #define DECLAREFUN_S_5_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5) DECLAREFUN_5_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,VCALLTYPE_STDCALL) #define DECLAREFUN_6(ret,func,arg1,arg2,arg3,arg4,arg5,arg6,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,6,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6);\ } #define DECLAREFUN_6_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,6,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6);\ } #define DECLAREFUN_C_6(ret,func,arg1,arg2,arg3,arg4,arg5,arg6) DECLAREFUN_6(ret,func,arg1,arg2,arg3,arg4,arg5,arg6,VCALLTYPE_CDECL) #define DECLAREFUN_S_6(ret,func,arg1,arg2,arg3,arg4,arg5,arg6) DECLAREFUN_6(ret,func,arg1,arg2,arg3,arg4,arg5,arg6,VCALLTYPE_STDCALL) #define DECLAREFUN_C_6_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6) DECLAREFUN_6_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,VCALLTYPE_CDECL) #define DECLAREFUN_S_6_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6) DECLAREFUN_6_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,VCALLTYPE_STDCALL) /////////////////////////////////////////////////////////////////// // Function Declaration with a different name #define DECLAREFUNALIAS_0(name,ret,func,callconv) {\ typedef ret (*fptr)(); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(name,ptr,callconv,0,#ret); \ } #define DECLAREFUNALIAS_C_0(name,ret,func) DECLAREFUNALIAS_0(name,ret,func,(VSL::VCallType)(VCALLTYPE_CDECL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_S_0(name,ret,func) DECLAREFUNALIAS_0(name,ret,func,(VSL::VCallType)(VCALLTYPE_STDCALL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_1(name,ret,func,arg1,callconv) {\ typedef ret (*fptr)(arg1); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(name,ptr,callconv,1,#ret,#arg1);\ } #define DECLAREFUNALIAS_C_1(name,ret,func,arg1) DECLAREFUNALIAS_1(name,ret,func,arg1,(VSL::VCallType)(VCALLTYPE_CDECL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_S_1(name,ret,func,arg1) DECLAREFUNALIAS_1(name,ret,func,arg1,(VSL::VCallType)(VCALLTYPE_STDCALL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_2(name,ret,func,arg1,arg2,callconv) {\ typedef ret (*fptr)(arg1,arg2); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(name,ptr,callconv,2,#ret,#arg1,#arg2);\ } #define DECLAREFUNALIAS_C_2(name,ret,func,arg1,arg2) DECLAREFUNALIAS_2(name,ret,func,arg1,arg2,(VSL::VCallType)(VCALLTYPE_CDECL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_S_2(name,ret,func,arg1,arg2) DECLAREFUNALIAS_2(name,ret,func,arg1,arg2,(VSL::VCallType)(VCALLTYPE_STDCALL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_3(name,ret,func,arg1,arg2,arg3,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(name,ptr,callconv,3,#ret,#arg1,#arg2,#arg3);\ } #define DECLAREFUNALIAS_C_3(name,ret,func,arg1,arg2,arg3) DECLAREFUNALIAS_3(name,ret,func,arg1,arg2,arg3,(VSL::VCallType)(VCALLTYPE_CDECL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_S_3(name,ret,func,arg1,arg2,arg3) DECLAREFUNALIAS_3(name,ret,func,arg1,arg2,arg3,(VSL::VCallType)(VCALLTYPE_STDCALL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_4(name,ret,func,arg1,arg2,arg3,arg4,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3,arg4); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(name,ptr,callconv,4,#ret,#arg1,#arg2,#arg3,#arg4);\ } #define DECLAREFUNALIAS_C_4(name,ret,func,arg1,arg2,arg3,arg4) DECLAREFUNALIAS_4(name,ret,func,arg1,arg2,arg3,arg4,(VSL::VCallType)(VCALLTYPE_CDECL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_S_4(name,ret,func,arg1,arg2,arg3,arg4) DECLAREFUNALIAS_4(name,ret,func,arg1,arg2,arg3,arg4,(VSL::VCallType)(VCALLTYPE_STDCALL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_5(name,ret,func,arg1,arg2,arg3,arg4,arg5,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(name,(fptr)ptr,callconv,4,#ret,#arg1,#arg2,#arg3,#arg4,arg5);\ } #define DECLAREFUNALIAS_C_5(name,ret,func,arg1,arg2,arg3,arg4,arg5) DECLAREFUNALIAS_5(name,ret,func,arg1,arg2,arg3,arg4,arg5,(VSL::VCallType)(VCALLTYPE_CDECL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_S_5(name,ret,func,arg1,arg2,arg3,arg4,arg5) DECLAREFUNALIAS_5(name,ret,func,arg1,arg2,arg3,arg4,arg5,(VSL::VCallType)(VCALLTYPE_STDCALL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_6(name,ret,func,arg1,arg2,arg3,arg4,arg5,arg6,callconv) {\ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(name,ptr,callconv,4,#ret,#arg1,#arg2,#arg3,#arg4,arg5,arg6);\ } #define DECLAREFUNALIAS_C_6(name,ret,func,arg1,arg2,arg3,arg4,arg5,arg6) DECLAREFUNALIAS_6(name,ret,func,arg1,arg2,arg3,arg4,arg5,arg6,(VSL::VCallType)(VCALLTYPE_CDECL|VCALLTYPE_ALIAS)) #define DECLAREFUNALIAS_S_6(name,ret,func,arg1,arg2,arg3,arg4,arg5,arg6) DECLAREFUNALIAS_6(name,ret,func,arg1,arg2,arg3,arg4,arg5,arg6,(VSL::VCallType)(VCALLTYPE_STDCALL|VCALLTYPE_ALIAS)) /////////////////////////////////////////////////////////////////// // constructor Declaration #define DECLARENEW_0(ret,func,callconv) {\ typedef ret (*fptr)(BYTE*); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,0,#ret);\ } #define DECLARECTOR_0(func) DECLARENEW_0(void,func,VCALLTYPE_CDECL) #define DECLARENEW_1(ret,func,arg1,callconv) {\ typedef ret (*fptr)(BYTE*,arg1); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,1,#ret,#arg1);\ } #define DECLARECTOR_1(func,arg1) DECLARENEW_1(void,func,arg1,VCALLTYPE_CDECL) #define DECLARENEW_2(ret,func,arg1,arg2,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,2,#ret,#arg1,#arg2);\ } #define DECLARECTOR_2(func,arg1,arg2) DECLARENEW_2(void,func,arg1,arg2,VCALLTYPE_CDECL) #define DECLARENEW_3(ret,func,arg1,arg2,arg3,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,3,#ret,#arg1,#arg2,#arg3);\ } #define DECLARECTOR_3(func,arg1,arg2,arg3) DECLARENEW_3(void,func,arg1,arg2,arg3,VCALLTYPE_CDECL) #define DECLARENEW_4(ret,func,arg1,arg2,arg3,arg4,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,4,#ret,#arg1,#arg2,#arg3,#arg4);\ } #define DECLARECTOR_4(func,arg1,arg2,arg3,arg4) DECLARENEW_4(void,func,arg1,arg2,arg3,arg4,VCALLTYPE_CDECL) #define DECLARENEW_5(ret,func,arg1,arg2,arg3,arg4,arg5,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4,arg5); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,4,#ret,#arg1,#arg2,#arg3,#arg4,arg5);\ } #define DECLARECTOR_5(func,arg1,arg2,arg3,arg4,arg5) DECLARENEW_5(void,func,arg1,arg2,arg3,arg4,arg5,VCALLTYPE_CDECL) #define DECLARENEW_6(ret,func,arg1,arg2,arg3,arg4,arg5,arg6,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4,arg5,arg6); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,4,#ret,#arg1,#arg2,#arg3,#arg4,arg5,arg6);\ } #define DECLARECTOR_6(func,arg1,arg2,arg3,arg4,arg5,arg6) DECLARENEW_6(void,func,arg1,arg2,arg3,arg4,arg5,arg6,VCALLTYPE_CDECL) #define DECLARENEW_7(ret,func,arg1,arg2,arg3,arg4,arg5,arg6,arg7,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4,arg5,arg6,arg7); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,4,#ret,#arg1,#arg2,#arg3,#arg4,arg5,arg6,arg7);\ } #define DECLARECTOR_7(func,arg1,arg2,arg3,arg4,arg5,arg6,arg7) DECLARENEW_7(void,func,arg1,arg2,arg3,arg4,arg5,arg6,arg7,VCALLTYPE_CDECL) #define DECLARENEW_8(ret,func,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,8,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6,#arg7,#arg8);\ } #define DECLARECTOR_8(func,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) DECLARENEW_8(void,func,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,VCALLTYPE_CDECL) // With Def Values #define DECLARENEW_1_WITH_DEF_VALS(ret,func,arg1,defVal1,callconv) {\ typedef ret (*fptr)(BYTE*,arg1); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,1,#ret,#arg1" = "#defVal1);\ } #define DECLARECTOR_1_WITH_DEF_VALS(func,arg1) DECLARENEW_1_WITH_DEF_VALS(void,func,arg1,defVal1,VCALLTYPE_CDECL) #define DECLARENEW_2_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,2,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2);\ } #define DECLARECTOR_2_WITH_DEF_VALS(func,arg1,defVal1,arg2,defVal2) DECLARENEW_2_WITH_DEF_VALS(void,func,arg1,defVal1,arg2,defVal2,VCALLTYPE_CDECL) #define DECLARENEW_3_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,3,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3);\ } #define DECLARECTOR_3_WITH_DEF_VALS(func,arg1,defVal1,arg2,defVal2,arg3,defVal3) DECLARENEW_3_WITH_DEF_VALS(void,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,VCALLTYPE_CDECL) #define DECLARENEW_4_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,4,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4);\ } #define DECLARECTOR_4_WITH_DEF_VALS(func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4) DECLARENEW_4_WITH_DEF_VALS(void,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,VCALLTYPE_CDECL) #define DECLARENEW_5_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4,arg5); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,5,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5);\ } #define DECLARECTOR_5_WITH_DEF_VALS(func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5) DECLARENEW_5_WITH_DEF_VALS(void,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,VCALLTYPE_CDECL) #define DECLARENEW_6_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4,arg5,arg6); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,6,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6);\ } #define DECLARECTOR_6_WITH_DEF_VALS(func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6) DECLARENEW_6_WITH_DEF_VALS(void,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,VCALLTYPE_CDECL) #define DECLARENEW_7_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4,arg5,arg6,arg7); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,7,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7);\ } #define DECLARECTOR_7_WITH_DEF_VALS(func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7) DECLARENEW_7_WITH_DEF_VALS(void,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,VCALLTYPE_CDECL) #define DECLARENEW_8_WITH_DEF_VALS(ret,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,arg8,defVal8,callconv) {\ typedef ret (*fptr)(BYTE*,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,callconv,8,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7,#arg8" = "#defVal8);\ } #define DECLARECTOR_8_WITH_DEF_VALS(func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,arg8,defVal8) DECLARENEW_8_WITH_DEF_VALS(void,func,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,arg8,defVal8,VCALLTYPE_CDECL) /////////////////////////////////////////////////////////////////// // destructor Declaration #ifdef __GNUC__ #define DECLAREDESTRUCTORFUNCTION(classe) void __dest##classe(classe *obj){obj->~classe();} #define DECLAREDESTRUCTORFUNCTIONALIAS(classe, alias) void __dest##alias(classe *obj){obj->~classe();} #else #define DECLAREDESTRUCTORFUNCTION(classe) void __dest##classe(classe *obj){obj->~##classe();} #define DECLAREDESTRUCTORFUNCTIONALIAS(classe, alias) void __dest##alias(classe *obj){obj->~##classe();} #endif #define DECLAREDESTRUCTOR(func) {\ typedef void (*fptr)(BYTE*); \ fptr rawPtr = (fptr) func; \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &rawPtr); \ VSLM->RegisterFunction(#func,ptr,VCALLTYPE_CDECL,0,"void");\ } /////////////////////////////////////////////////////////////////// // class method Declaration #define FPTR(a) (fptr) a #define DECLAREMETHOD_0(classe,ret,method) { \ typedef ret (classe::*fptr)(); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,0,#ret);\ } #define DECLAREMETHODC_0(classe,ret,method) { \ typedef ret (classe::*fptr)() const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,0,#ret);\ } #define DECLAREMETHOD_1(classe,ret,method,arg1) { \ typedef ret (classe::*fptr)(arg1); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,1,#ret,#arg1);\ } #define DECLAREMETHOD_1_WITH_DEF_VALS(classe,ret,method,arg1,defVal1) { \ typedef ret (classe::*fptr)(arg1); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,1,#ret,#arg1" = "#defVal1);\ } #define DECLAREMETHODC_1(classe,ret,method,arg1) { \ typedef ret (classe::*fptr)(arg1) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,1,#ret,#arg1);\ } #define DECLAREMETHODC_1_WITH_DEF_VALS(classe,ret,method,arg1,defVal1) { \ typedef ret (classe::*fptr)(arg1) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,1,#ret,#arg1" = "#defVal1);\ } #define DECLAREMETHOD_2(classe,ret,method,arg1,arg2) { \ typedef ret (classe::*fptr)(arg1,arg2); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,2,#ret,#arg1,#arg2);\ } #define DECLAREMETHOD_2_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2) { \ typedef ret (classe::*fptr)(arg1,arg2); \ fptr var = FPTR(fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,2,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2);\ } #define DECLAREMETHODC_2(classe,ret,method,arg1,arg2) { \ typedef ret (classe::*fptr)(arg1,arg2) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,2,#ret,#arg1,#arg2);\ } #define DECLAREMETHODC_2_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2) { \ typedef ret (classe::*fptr)(arg1,arg2) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,2,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2);\ } #define DECLAREMETHOD_3(classe,ret,method,arg1,arg2,arg3) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,3,#ret,#arg1,#arg2,#arg3);\ } #define DECLAREMETHOD_3_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,3,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3);\ } #define DECLAREMETHODC_3(classe,ret,method,arg1,arg2,arg3) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,3,#ret,#arg1,#arg2,#arg3);\ } #define DECLAREMETHODC_3_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,3,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3);\ } #define DECLAREMETHOD_4(classe,ret,method,arg1,arg2,arg3,arg4) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,4,#ret,#arg1,#arg2,#arg3,#arg4);\ } #define DECLAREMETHODC_4(classe,ret,method,arg1,arg2,arg3,arg4) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,4,#ret,#arg1,#arg2,#arg3,#arg4);\ } #define DECLAREMETHOD_4_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,4,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4);\ } #define DECLAREMETHODC_4_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,4,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4);\ } #define DECLAREMETHOD_5(classe,ret,method,arg1,arg2,arg3,arg4,arg5) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,5,#ret,#arg1,#arg2,#arg3,#arg4,#arg5);\ } #define DECLAREMETHODC_5(classe,ret,method,arg1,arg2,arg3,arg4,arg5) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,5,#ret,#arg1,#arg2,#arg3,#arg4,#arg5);\ } #define DECLAREMETHOD_5_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,5,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5);\ } #define DECLAREMETHODC_5_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,5,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5);\ } #define DECLAREMETHOD_6(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,6,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6);\ } #define DECLAREMETHODC_6(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,6,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6);\ } #define DECLAREMETHOD_6_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,6,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6);\ } #define DECLAREMETHODC_6_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,6,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6);\ } #define DECLAREMETHOD_7(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6,arg7) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,7,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6,#arg7);\ } #define DECLAREMETHODC_7(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6,arg7) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,7,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6,#arg7);\ } #define DECLAREMETHOD_7_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,7,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7);\ } #define DECLAREMETHODC_7_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,7,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7);\ } #define DECLAREMETHOD_8(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,8,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6,#arg7,#arg8);\ } #define DECLAREMETHODC_8(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,8,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6,#arg7,#arg8);\ } #define DECLAREMETHOD_8_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,arg8,defVal8) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,8,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7,#arg8" = "#defVal8);\ } #define DECLAREMETHODC_8_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,arg8,defVal8) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) const; \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,TRUE,ptr,VCALLTYPE_STDCALL,8,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7,#arg8" = "#defVal8);\ } #define DECLAREMETHOD_9_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,arg8,defVal8,arg9,defVal9) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,9,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7,#arg8" = "#defVal8,#arg9" = "#defVal9);\ } #define DECLAREMETHOD_10_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,arg8,defVal8,arg9,defVal9,arg10,defVal10) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,10,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7,#arg8" = "#defVal8,#arg9" = "#defVal9,#arg10" = "#defVal10);\ } #define DECLAREMETHOD_11_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,arg8,defVal8,arg9,defVal9,arg10,defVal10,arg11,defVal11) { \ typedef ret (classe::*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11); \ fptr var = FPTR(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,FALSE,FALSE,ptr,VCALLTYPE_STDCALL,11,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7,#arg8" = "#defVal8,#arg9" = "#defVal9,#arg10" = "#defVal10,#arg11" = "#defVal11);\ } /////////////////////////////////////////////////////////////////// // class operator Declaration inline const char* extractOperator(const char* opname) { const char* s = opname+8; while (*s == ' ') ++s; return s; } #define DECLAREOP_0(classe,ret,op) { \ typedef ret (classe::*fptr)(); \ fptr var = (fptr)(&classe::op); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,extractOperator(#op),FALSE,FALSE,ptr,VCALLTYPE_STDCALL,0,#ret);\ } #define DECLAREOP_1(classe,ret,op,arg1) { \ typedef ret (classe::*fptr)(arg1); \ fptr var = (fptr)(&classe::op); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,extractOperator(#op),FALSE,FALSE,ptr,VCALLTYPE_STDCALL,1,#ret,#arg1);\ } #define DECLAREOP_2(classe,ret,op,arg1,arg2) { \ typedef ret (classe::*fptr)(arg1,arg2); \ fptr var = (fptr)(&classe::op); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,extractOperator(#op),FALSE,FALSE,ptr,VCALLTYPE_STDCALL,2,#ret,#arg1,#arg2);\ } // constant versions #define DECLAREOPC_0(classe,ret,op) { \ typedef ret (classe::*fptr)() const; \ fptr var = (fptr)(&classe::op); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,extractOperator(#op),FALSE,TRUE,ptr,VCALLTYPE_STDCALL,0,#ret);\ } #define DECLAREOPC_1(classe,ret,op,arg1) { \ typedef ret (classe::*fptr)(arg1) const; \ fptr var = (fptr)(&classe::op); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,extractOperator(#op),FALSE,TRUE,ptr,VCALLTYPE_STDCALL,1,#ret,#arg1);\ } #define DECLAREOPC_2(classe,ret,op,arg1,arg2) { \ typedef ret (classe::*fptr)(arg1,arg2) const; \ fptr var = (fptr)(&classe::op); \ TPtrToRoutine ptr; \ ptr.CreateMethodPtr((void**) &var); \ VSLM->RegisterMethod(#classe,extractOperator(#op),FALSE,TRUE,ptr,VCALLTYPE_STDCALL,2,#ret,#arg1,#arg2);\ } /////////////////////////////////////////////////////////////////// // friend method Declaration #define DECLAREFRIEND_0(ret,method) { \ typedef ret (*fptr)(); \ fptr var = (fptr)(&method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterFunction(#method,ptr,VCALLTYPE_CDECL,0,#ret);\ } #define DECLAREFRIEND_1(ret,method,arg1) { \ typedef ret (*fptr)(arg1); \ fptr var = (fptr)(&method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterFunction(#method,ptr,VCALLTYPE_CDECL,1,#ret,#arg1);\ } #define DECLAREFRIEND_2(ret,method,arg1,arg2) { \ typedef ret (*fptr)(arg1,arg2); \ fptr var = (fptr)(&method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterFunction(#method,ptr,VCALLTYPE_CDECL,2,#ret,#arg1,#arg2);\ } #define DECLAREFRIEND_3(ret,method,arg1,arg2,arg3) { \ typedef ret (*fptr)(arg1,arg2,arg3); \ fptr var = (fptr)(&method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterFunction(#method,ptr,VCALLTYPE_CDECL,3,#ret,#arg1,#arg2,#arg3);\ } #define DECLAREFRIEND_4(ret,method,arg1,arg2,arg3,arg4) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4); \ fptr var = (fptr)(&method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterFunction(#method,ptr,VCALLTYPE_CDECL,4,#ret,#arg1,#arg2,#arg3,#arg4);\ } /////////////////////////////////////////////////////////////////// // friend operator #define DECLAREFRIENDOP_0(ret,op) { \ typedef ret (*fptr)(); \ fptr var = (fptr)(&op); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterFunction(extractOperator(#op),ptr,VCALLTYPE_CDECL,0,#ret);\ } #define DECLAREFRIENDOP_1(ret,op,arg1) { \ typedef ret (*fptr)(arg1); \ fptr var = (fptr)(&op); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterFunction(extractOperator(#op),ptr,VCALLTYPE_CDECL,1,#ret,#arg1);\ } #define DECLAREFRIENDOP_2(ret,op,arg1,arg2) { \ typedef ret (*fptr)(arg1,arg2); \ fptr var = (fptr)(&op); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterFunction(extractOperator(#op),ptr,VCALLTYPE_CDECL,2,#ret,#arg1,#arg2);\ } /////////////////////////////////////////////////////////////////// // static method Declaration #define DECLARESTATIC_0(classe,ret,method) { \ typedef ret (*fptr)(); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,0,#ret);\ } #define DECLARESTATIC_1(classe,ret,method,arg1) { \ typedef ret (*fptr)(arg1); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,1,#ret,#arg1);\ } #define DECLARESTATIC_2(classe,ret,method,arg1,arg2) { \ typedef ret (*fptr)(arg1,arg2); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,2,#ret,#arg1,#arg2);\ } #define DECLARESTATIC_3(classe,ret,method,arg1,arg2,arg3) { \ typedef ret (*fptr)(arg1,arg2,arg3); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,3,#ret,#arg1,#arg2,#arg3);\ } #define DECLARESTATIC_4(classe,ret,method,arg1,arg2,arg3,arg4) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,4,#ret,#arg1,#arg2,#arg3,#arg4);\ } #define DECLARESTATIC_5(classe,ret,method,arg1,arg2,arg3,arg4,arg5) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,5,#ret,#arg1,#arg2,#arg3,#arg4,#arg5);\ } #define DECLARESTATIC_6(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,6,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6);\ } #define DECLARESTATIC_7(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6,arg7) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,7,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6,#arg7);\ } #define DECLARESTATIC_8(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,8,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6,#arg7,#arg8);\ } #define DECLARESTATIC_9(classe,ret,method,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8, arg9) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,9,#ret,#arg1,#arg2,#arg3,#arg4,#arg5,#arg6,#arg7,#arg8,#arg9);\ } // With Default Values #define DECLARESTATIC_1_WITH_DEF_VALS(classe,ret,method,arg1,defVal1) { \ typedef ret (*fptr)(arg1); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,1,#ret,#arg1#defVal1);\ } #define DECLARESTATIC_2_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2) { \ typedef ret (*fptr)(arg1,arg2); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,2,#ret,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2);\ } #define DECLARESTATIC_3_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3) { \ typedef ret (*fptr)(arg1,arg2,arg3); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,3,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3);\ } #define DECLARESTATIC_4_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,4,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4);\ } #define DECLARESTATIC_5_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,5,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5);\ } #define DECLARESTATIC_6_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,6,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6);\ } #define DECLARESTATIC_7_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,7,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7);\ } #define DECLARESTATIC_8_WITH_DEF_VALS(classe,ret,method,arg1,defVal1,arg2,defVal2,arg3,defVal3,arg4,defVal4,arg5,defVal5,arg6,defVal6,arg7,defVal7,arg8,defVal8) { \ typedef ret (*fptr)(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); \ fptr var = (fptr)(&classe::method); \ TPtrToRoutine ptr; \ ptr.CreateFunctionPtr((void**) &var); \ VSLM->RegisterMethod(#classe,#method,TRUE,FALSE,ptr,VCALLTYPE_CDECL,8,#ret,#arg1" = "#defVal1,#arg2" = "#defVal2,#arg3" = "#defVal3,#arg4" = "#defVal4,#arg5" = "#defVal5,#arg6" = "#defVal6,#arg7" = "#defVal7,#arg8" = "#defVal8);\ } /////////////////////////////////////////////////////////////////// // Enum for array of GUID used by binded function GetGUID enum PGUID { PGUID_NONE = 0, PGUID_VOIDBUF, PGUID_FLOAT, PGUID_ANGLE, PGUID_PERCENTAGE, PGUID_INT, PGUID_KEY, PGUID_BOOL, PGUID_STRING, PGUID_RECT, PGUID_VECTOR, PGUID_2DVECTOR, PGUID_QUATERNION, PGUID_EULERANGLES, PGUID_MATRIX, PGUID_COLOR, PGUID_BOX, PGUID_OBJECTARRAY, PGUID_OBJECT, PGUID_BEOBJECT, PGUID_MESH, PGUID_MATERIAL, PGUID_TEXTURE, PGUID_SPRITE, PGUID_3DENTITY, PGUID_CURVEPOINT, PGUID_LIGHT, PGUID_TARGETLIGHT, PGUID_ID, PGUID_CAMERA, PGUID_TARGETCAMERA, PGUID_SPRITE3D, PGUID_OBJECT3D, PGUID_BODYPART, PGUID_CHARACTER, PGUID_CURVE, PGUID_2DCURVE, PGUID_LEVEL, PGUID_PLACE, PGUID_GROUP, PGUID_2DENTITY, PGUID_RENDEROBJECT, PGUID_SPRITETEXT, PGUID_SOUND, PGUID_WAVESOUND, PGUID_MIDISOUND, PGUID_OBJECTANIMATION, PGUID_ANIMATION, PGUID_KINEMATICCHAIN, PGUID_SCENE, PGUID_BEHAVIOR, PGUID_MESSAGE, PGUID_SYNCHRO, PGUID_CRITICALSECTION, PGUID_STATE, PGUID_ATTRIBUTE, PGUID_CLASSID, PGUID_DIRECTION, PGUID_BLENDMODE, PGUID_FILTERMODE, PGUID_BLENDFACTOR, PGUID_FILLMODE, PGUID_LITMODE, PGUID_SHADEMODE, PGUID_GLOBALEXMODE, PGUID_ZFUNC, PGUID_ADDRESSMODE, PGUID_WRAPMODE, PGUID_3DSPRITEMODE, PGUID_FOGMODE, PGUID_LIGHTTYPE, PGUID_SPRITEALIGN, PGUID_SCRIPT, PGUID_LAYERTYPE, PGUID_STATECHUNK, PGUID_DATAARRAY, PGUID_COMPOPERATOR, PGUID_BINARYOPERATOR, PGUID_SETOPERATOR, PGUID_SPRITETEXTALIGNMENT, PGUID_OBSTACLEPRECISION, PGUID_OBSTACLEPRECISIONBEH, PGUID_OBSTACLE, PGUID_PATCHMESH, PGUID_POINTER, PGUID_ENUMS, PGUID_STRUCTS, PGUID_FLAGS, PGUID_FILTER, PGUID_TIME, PGUID_OLDTIME, PGUID_COPYDEPENDENCIES, PGUID_DELETEDEPENDENCIES, PGUID_SAVEDEPENDENCIES, PGUID_REPLACEDEPENDENCIES, PGUID_SCENEACTIVITYFLAGS, PGUID_SCENEOBJECT, PGUID_SCENERESETFLAGS, PGUID_ARRAYTYPE, PGUID_RENDEROPTIONS, PGUID_PARAMETERTYPE, PGUID_MATERIALEFFECT, PGUID_TEXGENEFFECT, PGUID_TEXGENREFEFFECT, PGUID_COMBINE2TEX, PGUID_COMBINE3TEX, PGUID_BUMPMAPPARAM, PGUID_TEXCOMBINE, PGUID_PIXELFORMAT, PGUID_AXIS, PGUID_SUPPORT, PGUID_BITMAP_SYSTEMCACHING, PGUID_OLDMESSAGE, PGUID_OLDATTRIBUTE, PGUID_3DPOINTCLOUD, PGUID_VIDEO, PGUID_RTVIEW, PGUID_LASTGUID // must stay in last position }; <file_sep> /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* */ /* D L L F T P */ /* */ /* W I N D O W S */ /* */ /* P o u r A r t h i c */ /* */ /* V e r s i o n 3 . 0 1 */ /* */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* Version 1.2 ------------------------------------------------------------- */ /* 23.02.95 : Correction d'un mauvais code de retour */ /* 27.02.95 : Ajout du code de retour 250 pour les transferts de */ /* fichiers (retour de MVS) */ /* 02.03.95 : Ajout de la fonction Ftp4wVer */ /* 07.03.95 : FtpRelease : Destruction de la fenêtre avant */ /* l'appel à UnregisterClass */ /* Version 2.0 ------------------------------------------------------------- */ /* 10.03.95 : Réorganisation du code */ /* 14.03.95 : Ajout de FtpPWD, FtpMKD, FtpRMD, FtpCDUP */ /* Rajout des lignes */ /* case 502,504: return FTPERR_CMDNOTIMPLEMENTED */ /* Ajout de FtpDelete */ /* 15.03.95 : Ajout du mode Passif */ /* Reste peut-être une petite erreur : si le fichier */ /* n'existe pas, la socket n'est pas forcément fermée */ /* 16.03.95 : Suppression des warnings de compilation */ /* 27.03.95 : Ajout de la commande FtpSyst */ /* 27.03.95 : Ajout de la commande FtpRenameFile */ /* 29.03.95 : Modification du fonctionnement de FtpSyst */ /* 29.03.95 : Ajout de la fonction FtpAppendToRemoteFile */ /* 29.03.95 : Correction d'un bug dans la fonction Ftp4wVer */ /* 31.03.95 : WSACleanUp est appele apres les close dans WEP */ /* Version 2.1 ------------------------------------------------------------- */ /* 3.04.95 : Utilisation de la bibliotheque Tcp4w/Tn4w */ /* 4.04.95 : Fonctionnement en Automate */ /* Version 2.2 ------------------------------------------------------------- */ /* 7.04.95 : Ajout de FtpAppendToLocalFile */ /* Ajout des constantes FTPMODE_APPEND, FTPMODE_READ */ /* 12.04.95 : Elimination du delai sur reception synchrone */ /* 21.04.95 Integration des primitives Telnet */ /* 28.04.95 Modification des parametres Slices */ /* 6.06.95 Modification pour le support de LAN WorkPlace */ /* 12.06.95 Compilation pour Version 2.2j (CICA) */ /* 17.07.95 Correction du bug SetDefaultPort Version 2.2k */ /* 08.08.95 Bug: Changement de la macro RETURN */ /* Version 2.3 ------------------------------------------------------------- */ /* 29.08.95 Suppression du WEP */ /* 29.08.95 Ajout de la fonction FtpSendAccount */ /* 12.10.95 changement de fonctionnement du TcpClose */ /* Ajout d'un type par defaut dans Recv/Send */ /* 3.11.95 FtpOpenConnection retourne FTERR_CANCELBYUSER, si */ /* il est interrompu par un FtpAbort */ /* Version 2.4 ------------------------------------------------------------- */ /* 16.11.95 Implementation des commandes FtpRestartSend/Recv */ /* Ajout du parametre lByte ds ToolsSetDataConnection */ /* Implementation de la commande FtpRestart */ /* Extension de l'utilisation de Tcp4w */ /* 21.11.95 Correction dans le Calcul de la jauge (%) pour */ /* FtpRestartSendFile */ /* 25.11.95 Portage 32 bits: Ajout des fichiers Port32.h et */ /* Port32.c */ /* Version 2.5 ------------------------------------------------------------- */ /* 8.02.96 Ajout des commandes FtpOpenDataConnection, */ /* FtpCloseDataConnection, FtpSendThroughDataConn... */ /* 20.02.96 AJout de FtpFirewallLogin */ /* 14.03.96 Ajout de FtpErrorString, FtpMGet (module WFTP4W_E) */ /* 1.04.96 Ajout de FtpBufferPtr */ /* 10.04.96 Utilisation de Tcp4u Version 2.0 */ /* Version 2.6 ------------------------------------------------------------- */ /* 22.05.96 Passage en environnement Gulliver */ /* 11.06.96 Externalisation de IntFtpGetAnswerCode */ /* et création de IntTnSend (pour Firewall code) */ /* 12.06.96 Elimination du htons devant FtpSetDefaultPort */ /* Version 2.7 ------------------------------------------------------------- */ /* 05.08.96 Premier essai de MultiThread avec FtpMtInit */ /* Correction d'une mauvaise detection de timeout */ /* 27.11.96 Ajout du code retour 257 sur RMD (WAR FTP server) */ /* 06.12.96 Détails codes retour sur Get(Connect/Listen)Socket */ /* Version 3.0 ------------------------------------------------------------- */ /* 31.01.97 Nouvelle annee, nouvelle version */ /* Fin du suppotr de la DLL 16 bits -> V2.7 */ /* Division du code en petits modules */ /* 06.12.97 Ajout du code 230 Acct Unisys */ /* 08.12.97 Utilisation du Debug de Tcp4u */ #define FTP4W_INCLUDES_AND_GENERAL + #include <windows.h> #include <windowsx.h> #include <time.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <winsock.h> #include <tcp4w.h> /* external header file */ #include "port32.h" /* 16/32 bits */ #include "ftp4w.h" /* external header file */ #include "ftp4w_in.h" /* internal header file */ #include "rfc959.h" /* only for error codes */ #define FTP4W_CLASS_NAME "Ftp4wClassName" /* ------------------------------------------------------------------------- */ /* Variables */ /* ------------------------------------------------------------------------- */ /* Pointeur sur l'index de la première connexion */ LPProcData pFirstProcData=NULL; int Protection (void); /* ******************************************************************* */ /* */ /* Partie IV : Allocations/libérations des ressources */ /* */ /* ******************************************************************* */ /* --------------------------------------------------------------*/ /* Fonction DLL FtpInit */ /* Création d'une structure de travail */ /* ouverture d'une fenêtre interne */ /* Initialisation de la structure */ /* ------------------------------------------------------------- */ int _export PASCAL FAR FtpInit (HWND hParentWnd) { LPProcData pProcData, pLast; HWND hFtpWnd; int Rc; if (ToolsLocateProcData () != NULL) return FTPERR_SESSIONUSED; Rc=Tcp4uInit (); if (Rc!=TCP4U_SUCCESS) return FTPERR_WINSOCKNOTUSABLE; if (pFirstProcData==NULL || IsBadWritePtr(pFirstProcData, sizeof *pFirstProcData)) { pProcData = pFirstProcData = Calloc (1, sizeof *pProcData); if (pProcData==NULL) return FTPERR_INSMEMORY; pProcData->Next = pProcData->Prev = NULL; } else { for ( pLast=pFirstProcData ; pLast->Next!=NULL ; pLast= pLast->Next ); pLast->Next = pProcData = Calloc (1, sizeof *pProcData); if (pProcData==NULL) return FTPERR_INSMEMORY; pProcData->Prev = pLast; pProcData->Next = NULL; } /* Get task information */ pProcData->hInstance = GetTaskInstance (hParentWnd); /* port32.c */ /* fIdentifyThread callback sur l'appelant, nThread sa valeur */ pProcData->fIdentifyThread = GetCurrentThreadId; pProcData->nThreadIdent = GetCurrentThreadId(); /* est-ce que la fenetre interne a deja ete creee */ if (pProcData==pFirstProcData) {WNDCLASS wndClass; /* lstrcpy (szFTPDLL_CLASSNAME, FTP4W_CLASS_NAME); */ /* EnregistreClasse : Enregistre la classe de notre fenêtre */ memset (& wndClass, 0, sizeof wndClass); wndClass.lpszClassName = FTP4W_CLASS_NAME; wndClass.hInstance = pProcData->hInstance; wndClass.lpfnWndProc = (WNDPROC) DLLWndProc; Rc = RegisterClass (&wndClass); if (! Rc) { FtpRelease(); return FTPERR_CANTCREATEWINDOW; } } #ifdef UNE_FENETRE if (pProcData==pFirstProcData) { #endif /* création de la fenêtre */ hFtpWnd=CreateWindow (FTP4W_CLASS_NAME,/* window class name */ "", 0, /* window title, style */ 0, 0, 0, 0, /* x, y, cx, xy */ hParentWnd, /* a parent for this window */ NULL, /* use the class menu */ pProcData->hInstance, /* who created this wndw */ NULL ); /* no parms to pass on */ if (hFtpWnd==NULL) { FtpRelease (); return FTPERR_CANTCREATEWINDOW; } pProcData->hFtpWnd = hFtpWnd; #ifdef UNE_FENETRE } /* pas d'instance deja cree -> creation de la fenetre interne */ /* si la fenetre interne existe, on la reutilise simplement */ else pProcData->hFtpWnd = pFirstProcData->hFtpWnd; #endif /* On remplit les infos relatives à la tâche */ pProcData->hParentWnd = hParentWnd; /* renseignements FTP : Pas de session existante */ pProcData->ftp.ctrl_socket = INVALID_SOCKET; pProcData->ftp.data_socket = INVALID_SOCKET; /* juste pour noyer l'appel */ pProcData->ftp.bVerbose = Protection (); /* Protection rend FALSE */ pProcData->ftp.nTimeOut = FTP_DEFTIMEOUT; pProcData->ftp.hLogFile = HFILE_ERROR; pProcData->ftp.bPassif = FALSE; pProcData->ftp.nPort = FTP_DEFCTRLPORT; /* renseignement fichier */ pProcData->File.bAborted = FALSE; pProcData->File.bNotify = FALSE; pProcData->File.bAsyncMode = TRUE; pProcData->File.hf = HFILE_ERROR; pProcData->File.nAsyncAlone= FTP_DEFASYNCALONE; pProcData->File.nAsyncMulti= FTP_DEFASYNCMULTI; pProcData->File.nDelay = FTP_DEFDELAY; return FTPERR_OK; }; /* FtpInit */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* tentative de Multithread */ /* L'utilisateur donne un callback retournant un DWORD (typiquement */ /* GetCurrentThreadId() appele a chaque appel Ftp4w32 */ /* Cet appel n'est pas fait dans la DLL car l'id retourne par Windows*/ /* serait identique d'uin thread a l'autre (pas de difference a */ /* l'interieur d'une DLL */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* Note warning "voulu" en compil 16 bits -> THREADID -> HANDLE */ /* et déclaration en DWORD dans le .H */ int _export PASCAL FAR FtpMtInit ( HWND hParentWnd, THREADID (CALLBACK *f)(void) ) { LPProcData pProcData; /* Init comme d'habitude */ int Rc=FtpInit (hParentWnd); if (Rc==FTPERR_OK) { /* et ecrasement des identifiants de thread */ pProcData = ToolsLocateProcData (); pProcData->fIdentifyThread = f; pProcData->nThreadIdent = (*f) (); } return Rc; } /* FtpMtInit */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpRelease */ /* Libère les ressources Windows (fenêtre et */ /* structure) prises par FtpInit */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpRelease (void) { LPProcData pProcData; pProcData = ToolsLocateProcData (); if (pProcData == NULL) return FTPERR_NOACTIVESESSION; if (Tcp4uCleanup ()!=TCP4U_SUCCESS) return FTPERR_STILLCONNECTED; /* si une seule appli est enregistre detruire la fenetre */ #ifdef UNE_FENETRE if (pProcData==pFirstProcData && pProcData->Next==NULL) { DestroyWindow (pProcData->hFtpWnd); /* Avant le UnregisterClass */ UnregisterClass (FTP4W_CLASS_NAME, pProcData->hInstance); } #else DestroyWindow (pProcData->hFtpWnd); /* Avant le UnregisterClass */ if (pProcData==pFirstProcData && pProcData->Next==NULL) UnregisterClass (FTP4W_CLASS_NAME, pProcData->hInstance); #endif if (pProcData->Next != NULL) pProcData->Next->Prev = pProcData->Prev; if (pProcData->Prev != NULL) pProcData->Prev->Next = pProcData->Next; else pFirstProcData = pProcData->Next; Free (pProcData); return FTPERR_OK; } /* FtpRelease */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpLocalClose */ /* Ferme les ressources Winsockets */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpLocalClose (void) { LPProcData pProcData; pProcData = ToolsLocateProcData (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; FtpCloseFileTransfer (pProcData, FALSE); TcpClose (& pProcData->ftp.ctrl_socket); return pProcData->ftp.ctrl_socket==INVALID_SOCKET && pProcData->ftp.data_socket==INVALID_SOCKET ? FTPERR_OK : FTPERR_CANTCLOSE; } /* FtpLocalClose */ /* ----------------------------------------------------------- */ /* Procédure de fin de vie de la DLL */ /* Libération des ressources Windows en cours */ /* On essaie aussi de libérer les sockets utilisées */ /* La procédure doit rendre 1 pour que le module soit */ /* libéré */ /* ----------------------------------------------------------- */ int _export CALLBACK WEP (int nType) { nType=1; /* suppress warning */ return 1; } /* WEP */ /* --------------------------------------------------------------*/ /* Fonction DLL FtpNOOP */ /* Vide le buffer de control */ /* ------------------------------------------------------------- */ int _export PASCAL FAR FtpFlush (void) { LPProcData pProcData; pProcData = ToolsLocateProcData (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; TcpFlush (pProcData->ftp.ctrl_socket); return FTPERR_OK; } /* FtpFlush () */ <file_sep>/******************************************************************** created: 2008/05/29 created: 29:5:2008 13:06 filename: x:\junctions\ProjectRoot\current\vt_plugins\svnLocal\vtTnlMaster\Manager\xNetObject.h file path: x:\junctions\ProjectRoot\current\vt_plugins\svnLocal\vtTnlMaster\Manager file base: xNetObject file ext: h author: mc007 purpose: *********************************************************************/ #ifndef _XNETOBJECT_H_ #define _XNETOBJECT_H_ #include "tnl.h" #include "tnlNetObject.h" #include "xNetTypes.h" class xNetInterface; class vtConnection; class xNetObject : public TNL::NetObject { public: xNetObject(); xNetObject(xNString name); virtual ~xNetObject(); typedef NetObject Parent; protected: xNString m_Name; xNetInterface *m_NetInterface; int m_UserID; vtConnection *mOwnerConnection; public : xNString GetName() { return m_Name; } void SetName(xNString val) { m_Name = val; } xNetInterface * getNetInterface() { return m_NetInterface; } void setNetInterface(xNetInterface * val) { m_NetInterface = val; } int getUserID() const { return m_UserID; } void setUserID(int val) { m_UserID = val; } virtual void Destroy(); vtConnection * getOwnerConnection() const { return mOwnerConnection; } void setOwnerConnection(vtConnection * val) { mOwnerConnection = val; } }; #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pConfig.h" int demoTimerExpired=0; void PhysicManager::advanceTime(float time) { timer +=time; float timeNow = timer; mLastStepTime = time; } void PhysicManager::update(float stepsize) { advanceTime(stepsize); #ifdef SESSION_LIMIT #ifndef REDIST if (timer >(SESSION_MAX)) { if (demoTimerExpired==0) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Demo expires after 15 mins"); demoTimerExpired = 1; } return ; } #endif #endif #ifdef REDIST if (m_Context->IsInInterfaceMode()) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"This is a redist Dll"); return; } #pragma message("-------------------------------PManager ::Update REDIST" ) #endif #if PROFILER //CKTimeProfiler(const char* iTitle, CKContext* iContext, int iStartingCount = 4): //CKTimeProfiler MyProfiler("PhysX Step",GetContext(),8); #endif pWorldMapIt it = getWorlds()->Begin(); while(it != getWorlds()->End()) { pWorld *w = *it; w->step(stepsize); it++; } //float pTime = MyProfiler //float a = pTime; } CKERROR PhysicManager::PostProcess() { pWorldMapIt it = getWorlds()->Begin(); while(it != getWorlds()->End()) { pWorld *w = *it; //w->getCollisions().Clear(); it++; } cleanAttributePostObjects(); return CK_OK; } CKERROR PhysicManager::PreProcess() { float timeCtx = GetContext()->GetTimeManager()->GetLastDeltaTimeFree(); update(timeCtx); return CK_OK; } <file_sep>#pragma once #include "StdAfx2.h" #include "VIControls.h" #include "ParameterDialog.h" #include "CKShader.h" #include "ParameterDialog.h" //#include "CUIKNotificationReceiver.h" //--- Include "GenericObjectParameterDialog.h" from CK2UI define IDDs to mak it compile #define IDD_GENOBJECTDIALOG 2011 #define IDD_BASEPARAMDIALOG 2000 #include "Parameters\GenericObjectParameterDialog.h" #include "resource.h" //--- Some constants #define MFC_NAME_OF_DIALOG "#32770" #define CHECK_MATERIAL_TIMER 57 class CPBCommonDialog : public CParameterDialog { public: bool InitChildWin( CDialog* pDlg, UINT iWinID,int otherID ); LRESULT OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam); //virtual BOOL Create(UINT nIDTemplate, CWnd* pParentWnd /* = NULL */); VIComboBox HType; VIStaticText LBL_HType; VIStaticText LBL_Flags; VIStaticText LBL_DFlags; VICheckButton BF_Move; VICheckButton BF_Grav; VICheckButton BF_Collision; VICheckButton BF_CollisionNotify; VICheckButton BF_Kinematic; VICheckButton BF_TriggerShape; VICheckButton BF_SubShape; VICheckButton BF_Sleep; VICheckButton BF_Hierarchy; VICheckButton BF_Deformable; VIStaticRectangle BF_BG_Rect; VIStaticRectangle BF_FLEX_Rect; CButton FlexButton; CStatic mPlaceHolder; VIStaticRectangle mDynaFlagsRect; VICheckButton TF_POS; VICheckButton TF_ROT; VICheckButton TF_PX; VICheckButton TF_RX; VICheckButton TF_PY; VICheckButton TF_RY; VICheckButton TF_PZ; VICheckButton TF_RZ; CToolTipCtrl *m_tt; int m_paramType; CPBCommonDialog(CKParameter* Parameter,CK_CLASSID Cid=CKCID_OBJECT) : CParameterDialog(Parameter,Cid) { setEditedParameter(Parameter); m_tt =NULL; } virtual ~CPBCommonDialog() { } CKParameter *m_EditedParameter; CKParameter * getEditedParameter() const { return m_EditedParameter; } void setEditedParameter(CKParameter * val) { m_EditedParameter = val; } virtual CKBOOL On_Init(); // associated resource id : enum { IDD = IDD_PBCOMMON }; // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CPBCommonDialog) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL void fillHullType(); void fillFlags(); void fillTransformationFlags(); public: virtual BOOL On_UpdateFromParameter(CKParameter* p){ // if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); // if(!p) return FALSE; return TRUE; } virtual BOOL On_UpdateToParameter(CKParameter* p){ /* if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); if(!p) return FALSE; CString cstr; /* */ return TRUE; } virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); public: CKParameter *parameter; VIEdit editValue; VIStaticText textValue; DECLARE_MESSAGE_MAP() virtual BOOL OnInitDialog(); virtual BOOL PreTranslateMessage(MSG* pMsg); afx_msg void OnStnClickedDynaFlagsRect(); };<file_sep>#pragma once #include "StdAfx2.h" #include "VIControls.h" #include "ParameterDialog.h" #include "CKShader.h" #include "ParameterDialog.h" #include "MultiParamEditDlg.h" //#include "CUIKNotificationReceiver.h" //--- Include "GenericObjectParameterDialog.h" from CK2UI define IDDs to mak it compile #define IDD_GENOBJECTDIALOG 2011 #define IDD_BASEPARAMDIALOG 2000 #include "Parameters\GenericObjectParameterDialog.h" #include "resource.h" #include "PCommonDialog.h" //--- Some constants #define MFC_NAME_OF_DIALOG "#32770" #define CHECK_MATERIAL_TIMER 57 class CPBXMLSetup : public MultiParamEditDlg , public CPSharedBase { public: // virtual void PreSubclassWindow(); int m_paramType; CPBXMLSetup(CKContext* context,CWnd* parent = NULL); CPBXMLSetup(CKParameter* Parameter,CK_CLASSID Cid=CKCID_OBJECT); virtual ~CPBXMLSetup(); void _destroy(); //virtual BOOL Create(UINT nIDTemplate, CWnd* pParentWnd); virtual void Init(CParameterDialog *parent); CParameterDialog* refresh(CKParameter*src); /************************************************************************/ /* Overrides */ /************************************************************************/ void OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); LRESULT OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam); /************************************************************************/ /* Accessors */ /************************************************************************/ CKParameter * getEditedParameter() const { return mParameter; } void setEditedParameter(CKParameter * val) { mParameter= val; } /************************************************************************/ /* Virtools mParameter transfer callbacks : */ /************************************************************************/ virtual BOOL On_UpdateFromParameter(CKParameter* p){ // if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); // if(!p) return FALSE; return TRUE; } virtual BOOL On_UpdateToParameter(CKParameter* p) { /* if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); if(!p) return FALSE; CString cstr;*/ return TRUE; } // associated resource id : enum { IDD = IDD_PBCOMMON_DEFORMABLE }; /************************************************************************/ /* MFC */ /************************************************************************/ //{{AFX_VIRTUAL(CPBXMLSetup) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL //{{AFX_MSG(CPBXMLSetup) //ON_REGISTERED_MESSAGE(_afxMsgMouseWheel, OnRegisteredMouseWheel); //afx_msg void OnMouseMove(UINT nFlags, CPoint point); //afx_msg void OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); //}}AFX_MSG public: /************************************************************************/ /* Low Level passes */ /************************************************************************/ LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); /************************************************************************/ /* Members */ /************************************************************************/ public: CKParameter *mParameter; VIEdit editValue; VIStaticText textValue; VIComboBox type; DECLARE_MESSAGE_MAP() }; <file_sep>#ifndef __PSHAPE_H_ #define __PSHAPE_H_ #include "vtOdeEnums.h" #include "vtOdeTypes.h" #include "pPrereqs.h" namespace vtAgeia { class pShape { public : pShape() { } virtual ~pShape(){} dGeomID m_OdeGeomID; dGeomID OdeGeomID() const { return m_OdeGeomID; } void OdeGeomID(dGeomID val) { m_OdeGeomID = val; } void SetOffsetPosition (VxVector position); void setOffsetQuaternion(VxQuaternion quad); void setOffsetWorldPosition(VxVector position); void setOffsetWorldQuaternion(VxQuaternion orientation) ; }; } #endif<file_sep>#ifndef __VT_PYTHON_FUNCS_H_ #define __VT_PYTHON_FUNCS_H_ //class PythonModule; int vpInitModules(); int vpCInit(); void vpCPyRun_SimpleString(const char*); void DestroyPython(); const char* vpSimpleTest(const char*,const char*,const char*); bool PythonLoad(); void PySetupStdRedirect(void); int syspath_append( char *dirname ); //PythonModule* CreatePythonModule(const char*file,const char*func,int bid); #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pVTireFunction.h" pTireFunction::pTireFunction() { setToDefault(); } void pTireFunction::setToDefault() { extremumSlip = 1.0f; extremumValue = 0.02f; asymptoteSlip = 2.0f; asymptoteValue = 0.01f; stiffnessFactor = 1000000.0f; //quite stiff by default. xmlLink =0; } bool pTireFunction::isValid() const { if(!(0.0f < extremumSlip)) return false; if(!(extremumSlip < asymptoteSlip)) return false; if(!(0.0f < extremumValue)) return false; if(!(0.0f < asymptoteValue)) return false; if(!(0.0f <= stiffnessFactor)) return false; return true; } float pTireFunction::hermiteEval(float t) const { // This fix for TTP 3429 & 3675 is from Sega. // Assume blending functions (look these up in a graph): // H0(t) = 2ttt - 3tt + 1 // H1(t) = -2ttt + 3tt // H2(t) = ttt - 2tt + t // H3(t) = ttt - tt float v = NxMath::abs(t); float s = (t>=0) ? 1.0f : -1.0f; float F; if(v<extremumSlip) { // For t in the interval 0 < t < extremumSlip // We normalize t: // a = t/extremumSlip; // and use H1 + H2 to compute F: // F = extremumValue * ( H1(a) + H2(a) ) float a = v/extremumSlip; float a2 = a*a; float a3 = a*a2; F = extremumValue * (-a3 + a2 + a); } else { if(v<asymptoteSlip) { // For the interval extremumSlip <= t < asymtoteSlip // We normalize and remap t: // a = (t-extremumSlip)/(asymptoteSlip - extremumSlip) // and use H0 to compute F: // F = extremumValue + (extremumValue - asymtoteValue) * H0(a) // note that the above differs from the actual expression but this is how it looks with H0 factorized. float a = (v-extremumSlip)/(asymptoteSlip - extremumSlip); float a2 = a*a; float a3 = a*a2; float diff = asymptoteValue - extremumValue; F = -2.0f*diff*a3 + 3.0f*diff*a2 + extremumValue; } else { F = asymptoteValue; } } return s*F; } <file_sep>REM lua5.1.exe -e "io.stdout:setvbuf 'no'" --Dev=Dev35 --file="./premake4.lua" -A vs2003 premake4 --ExternalVTDirectory=./VTPaths.lua --DeployDirect=TRUE --Dev=Dev40 --file="./premake4.lua" vs2003 REM premake4 --ExternalVTDirectory=./VTPaths.lua --DeployDirect=TRUE --Dev=Dev40 --file="./premake4.lua" vs2005 REM lua5.1.exe -e "io.stdout:setvbuf 'no'" --Dev=Dev40 --file="./premake4.lua" -A vs2008 REM lua5.1.exe -e "io.stdout:setvbuf 'no'" --Dev=Dev41 --file="./premake4.lua" -A vs2005 <file_sep>REM Please install CMAKE BEFORE !!!!! cd Scripts findDevDirs.bat <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "CK3dPointCloud.h" #ifdef HAS_FLUIDS int RenderParticles_P(CKRenderContext *dev,CKRenderObject *obj,void *arg); void pFactory::copyToEmitterDesc(NxFluidEmitterDesc&dst,pFluidEmitterDesc src) { dst.dimensionX = src.dimensionX; dst.dimensionY = src.dimensionY; dst.flags = (NxFluidEmitterFlag)src.flags; dst.fluidVelocityMagnitude = src.fluidVelocityMagnitude; dst.maxParticles = src.maxParticles; dst.particleLifetime = src.particleLifetime; dst.randomAngle = src.randomAngle; dst.randomPos = getFrom( src.randomPos); dst.rate = src.rate; dst.type = (NxEmitterType)src.type; dst.repulsionCoefficient = src.repulsionCoefficient; if (src.frameShape) { pWorld *w = GetPMan()->getWorldByShapeReference(src.frameShape); if (w) { NxShape *shape = w->getShapeByEntityID(src.frameShape->GetID()); if (shape) { dst.frameShape = shape; }else { dst.frameShape = NULL; } } } } void pFactory::initParticles(pFluidDesc &desc,NxParticleData&dst,CK3dEntity*srcReference,CK3dEntity*dstEntity) { CKMesh *mesh = dstEntity->GetCurrentMesh(); if (!mesh) return; ////////////////////////////////////////////////////////////////////////// mesh->SetVertexCount(desc.maxParticles); CKDWORD stride; void* ptr = mesh->GetPositionsPtr(&stride); XPtrStrided<VxVector> vpos(ptr,stride); VxVector pos(0,0,0); for (int i = 0 ; i < mesh->GetVertexCount();i++ ) { pos.x +=(float)(i*0.0001f); mesh->SetVertexPosition(i,&pos); } ////////////////////////////////////////////////////////////////////////// mesh->VertexMove(); char* bufferPos = reinterpret_cast<char*>(dst.bufferPos); char* bufferVel = reinterpret_cast<char*>(dst.bufferVel); char* bufferLife = reinterpret_cast<char*>(dst.bufferLife); // if(bufferPos == NULL && bufferVel == NULL && bufferLife == NULL) // return; /* NxVec3 aabbDim; aabb.getExtents(aabbDim); aabbDim *= 2.0f; */ (*dst.numParticlesPtr) = 0; for (int j = 0 ; j < desc.maxParticles ; j ++ ) { VxVector mPos; mesh->GetVertexPosition(j,&mPos); srcReference->Transform(&mPos,&mPos); NxVec3 p(mPos.x,mPos.y,mPos.z); NxVec3& position = *reinterpret_cast<NxVec3*>(bufferPos); position = p; int stride = dst.bufferPosByteStride; bufferPos += dst.bufferPosByteStride; NxVec3& velocity = *reinterpret_cast<NxVec3*>(bufferVel); NxVec3 vel; velocity = vel; bufferVel += dst.bufferVelByteStride; if (bufferLife) { NxReal& life = *reinterpret_cast<NxReal*>(bufferLife); life = 0.0f; bufferLife += dst.bufferLifeByteStride; } (*dst.numParticlesPtr)++; } } pFluid* pFactory::createFluid(CK3dEntity *srcReference ,pFluidDesc desc) { //Create a set of initial particles pParticle* initParticle = new pParticle[desc.maxParticles]; unsigned initParticlesNum = 0; //Setup structure to pass initial particles. NxParticleData initParticleData; initParticleData.numParticlesPtr = &initParticlesNum; initParticleData.bufferPos = &initParticle[0].position.x; initParticleData.bufferPosByteStride = sizeof(pParticle); initParticleData.bufferVel = &initParticle[0].velocity.x; initParticleData.bufferVelByteStride = sizeof(pParticle); CK3dEntity *particleEntity = createFluidEntity(); CKMesh *mesh = particleEntity->GetCurrentMesh(); mesh->SetVertexCount(desc.maxParticles); VxVector pos; srcReference->GetPosition(&pos); particleEntity->SetPosition(&pos); CK3dPointCloud *cloud = createPointCloud(desc); if (cloud) { cloud->SetReferentialPosition(pos); } //initParticles(desc,initParticleData,srcReference,particleEntity); //Setup fluid descriptor NxFluidDesc fluidDesc; fluidDesc.setToDefault(); copyToFluidDescr(fluidDesc,desc); /*fluidDesc.maxParticles = desc.maxParticles; fluidDesc.kernelRadiusMultiplier = 2.0f; fluidDesc.restParticlesPerMeter = 10.0f; fluidDesc.motionLimitMultiplier = 3.0f; fluidDesc.packetSizeMultiplier = 8; fluidDesc.collisionDistanceMultiplier = 0.1; fluidDesc.stiffness = 50.0f; fluidDesc.viscosity = 40.0f; fluidDesc.restDensity = 1000.0f; fluidDesc.damping = 0.0f; fluidDesc.restitutionForStaticShapes = 0.2f; fluidDesc.dynamicFrictionForStaticShapes= 0.05f; fluidDesc.simulationMethod = NX_F_SPH;*/ fluidDesc.flags &= ~NX_FF_HARDWARE; //Add initial particles to fluid creation. fluidDesc.initialParticleData = initParticleData; //Create user fluid. //- create NxFluid in NxScene //- setup the buffers to read from data from the SDK //- set NxFluid::userData field to MyFluid instance bool trackUserData = false; bool provideCollisionNormals = false; pFluid* fluid = new pFluid(fluidDesc, trackUserData, provideCollisionNormals, getFrom(NxVec3(0.4f,0.5f,0.9f)), 0.03f); if (fluidDesc.flags & NX_FF_HARDWARE) { int op = 2; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// CK3dEntity*worldReference = (CK3dEntity*)GetPMan()->m_Context->GetObject(desc.worldReference); if (!worldReference) { if (GetPMan()->getDefaultWorld()) { worldReference = GetPMan()->getDefaultWorld()->getReference(); }else return NULL; } pWorld*world = GetPMan()->getWorld(worldReference->GetID()); if (!world) { return NULL; } int s = fluidDesc.isValid(); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// NxFluid* xfluid = world->getScene()->createFluid(fluidDesc); if (xfluid) { xfluid->userData = fluid; fluid->setFluid( xfluid ); fluid->setEntityID( particleEntity->GetID() ); particleEntity->SetRenderCallBack(RenderParticles_P,fluid); return fluid; } return NULL; } void pFactory::copyToFluidDescr(NxFluidDesc &dst , pFluidDesc src ) { dst.attractionForDynamicShapes = src.attractionForDynamicShapes; dst.attractionForStaticShapes = src.attractionForStaticShapes; dst.collisionDistanceMultiplier = src.collisionDistanceMultiplier; dst.collisionGroup = src.collisionGroup; dst.collisionMethod = src.collisionMethod; dst.collisionResponseCoefficient =src.collisionResponseCoefficient; dst.damping = src.damping; dst.dynamicFrictionForDynamicShapes = src.dynamicFrictionForDynamicShapes; dst.dynamicFrictionForStaticShapes = src.dynamicFrictionForStaticShapes; dst.externalAcceleration = getFrom(src.externalAcceleration); dst.fadeInTime = src.fadeInTime; dst.kernelRadiusMultiplier = src.kernelRadiusMultiplier; dst.packetSizeMultiplier = src.packetSizeMultiplier; dst.maxParticles = src.maxParticles; dst.motionLimitMultiplier = src.motionLimitMultiplier; dst.numReserveParticles = src.numReserveParticles; dst.packetSizeMultiplier = src.packetSizeMultiplier; dst.restitutionForDynamicShapes = src.restitutionForDynamicShapes; dst.restitutionForStaticShapes =src.restitutionForStaticShapes; dst.restParticlesPerMeter = src.restParticlesPerMeter; dst.restDensity = src.restDensity; dst.simulationMethod = src.simulationMethod; dst.staticFrictionForDynamicShapes = src.staticFrictionForDynamicShapes; dst.staticFrictionForStaticShapes = src.staticFrictionForStaticShapes; dst.stiffness = src.stiffness; dst.surfaceTension =src.surfaceTension; dst.viscosity =src.viscosity; dst.flags = src.flags; } CK3dEntity*pFactory::createFluidEntity() { CK3dEntity *result = NULL; CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; XString name; name << "_Decal"; CK3dEntity* decal = (CK3dEntity*)ctx()->CreateObject(CKCID_3DOBJECT,name.Str(),creaoptions); name << "Mesh"; CKMesh* decalmesh = (CKMesh*)ctx()->CreateObject(CKCID_MESH,name.Str(),creaoptions); if (!decalmesh) return NULL; // Add to the level CKLevel* level = ctx()->GetCurrentLevel(); CKScene* scene = ctx()->GetCurrentScene(); level->AddObject(decal); level->AddObject(decalmesh); // And to the current scene if any if (scene != level->GetLevelScene()) { scene->AddObject(decal); scene->AddObject(decalmesh); } // 3DEntity decal->SetWorldMatrix(VxMatrix::Identity()); decal->SetCurrentMesh(decalmesh); return decal; } CK3dPointCloud*pFactory::createPointCloud(const pFluidDesc&descr) { CK3dPointCloud*result = NULL; CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; XString name; name << "_FluidCloud"; result = (CK3dPointCloud*)ctx()->CreateObject(CKCID_3DPOINTCLOUD,name.Str(),creaoptions); // Add to the level CKLevel* level = ctx()->GetCurrentLevel(); CKScene* scene = ctx()->GetCurrentScene(); level->AddObject((CKObject*)result); // And to the current scene if any if (scene != level->GetLevelScene()) { scene->AddObject((CKSceneObject*)result); } // 3DEntity result->SetWorldMatrix(VxMatrix::Identity()); //decal->SetCurrentMesh(decalmesh); return result; } #endif // HAS_FLUIDS<file_sep> #include "CKAll.h" #include "vtNetworkManager.h" #include "xNetTypes.h" #include "tnl.h" #include "tnlPlatform.h" #include "xNetInterface.h" #include "tnlGhostConnection.h" #include "vtConnection.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "IDistributedObjectsInterface.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xPredictionSetting.h" CKGUID GetNetManagerGUID() { return NET_MAN_GUID;} extern xNetInterface* GetNetInterfaceServer(); extern xNetInterface *GetNetInterfaceClient(); xNetInterface* GetNetInterface() { if (GetNetInterfaceClient()) { return GetNetInterfaceClient(); } if (GetNetInterfaceServer()) { return GetNetInterfaceServer(); } return NULL; } #include "xLogger.h" #include "VSLManagerSDK.h" //#define VIRTOOLS_DEV35 void xSConsoleMessage(const char *msg) { //TNL::logprintf(msg); xLogger::xLog(ELOGWARNING,E_LI_VSL,"vsl message : %s",msg); } void xSConsoleError(const char *msg) { //TNL::logprintf(msg); xLogger::xLog(ELOGERROR,E_LI_VSL,"vsl message : %s",msg); } const char* xSGetCommandLine() { return GetCommandLine(); } void vtNetworkManager::RegisterVSL() { //TNLLogEnable(LogGhostConnection, true); //TNLLogEnable(LogNetInterface,true); //TNLLogEnable(LogConnectionProtocol,true); //TNLLogEnable(LogNetConnection,true); STARTVSLBIND(m_Context) DECLAREFUN_C_0(CKGUID, GetNetManagerGUID) DECLAREFUN_C_1(void,xSConsoleMessage,const char*) DECLAREFUN_C_1(void,xSConsoleError,const char*) DECLAREFUN_C_0(const char*,xSGetCommandLine) /************************************************************************/ /* Dist Object enumerations */ /************************************************************************/ DECLAREENUM("E_DC_BASE_TYPE") DECLAREENUMVALUE("E_DC_BASE_TYPE","E_DC_BTYPE_3D_ENTITY",0) DECLAREENUMVALUE("E_DC_BASE_TYPE","E_DC_BTYPE_2D_ENTITY",1) DECLAREENUMVALUE("E_DC_BASE_TYPE","E_DC_BTYPE_CLIENT",2) DECLAREENUMVALUE("E_DC_BASE_TYPE","E_DC_BTYPE_SESSION",3) DECLAREENUM("E_OBJECT_TYPE") DECLAREENUMVALUE("E_OBJECT_TYPE","E_OT_DIST_OBJECT",0) DECLAREENUMVALUE("E_OBJECT_TYPE","E_OT_DIST_PROPERTY",1) DECLAREENUMVALUE("E_OBJECT_TYPE","E_OT_CLASS",2) DECLAREENUM("E_DC_PROPERTY_TYPE") DECLAREENUMVALUE("E_DC_PROPERTY_TYPE","E_DC_PTYPE_3DVECTOR",0) DECLAREENUMVALUE("E_DC_PROPERTY_TYPE","E_DC_PTYPE_QUATERNION",1) DECLAREENUMVALUE("E_DC_PROPERTY_TYPE","E_DC_PTYPE_2DVECTOR",2) DECLAREENUMVALUE("E_DC_PROPERTY_TYPE","E_DC_PTYPE_FLOAT",3) DECLAREENUMVALUE("E_DC_PROPERTY_TYPE","E_DC_PTYPE_INT",4) DECLAREENUMVALUE("E_DC_PROPERTY_TYPE","E_DC_PTYPE_BOOL",5) DECLAREENUMVALUE("E_DC_PROPERTY_TYPE","E_DC_PTYPE_STRING",6) DECLAREENUM("E_DC_3D_NATIVE_PROPERTIES") DECLAREENUMVALUE("E_DC_3D_NATIVE_PROPERTIES","E_DC_3D_NP_LOCAL_POSITION",1) DECLAREENUMVALUE("E_DC_3D_NATIVE_PROPERTIES","E_DC_3D_NP_LOCAL_ROTATION",2) DECLAREENUMVALUE("E_DC_3D_NATIVE_PROPERTIES","E_DC_3D_NP_LOCAL_SCALE",3) DECLAREENUMVALUE("E_DC_3D_NATIVE_PROPERTIES","E_DC_3D_NP_WORLD_POSITION",4) DECLAREENUMVALUE("E_DC_3D_NATIVE_PROPERTIES","E_DC_3D_NP_WORLD_ROTATION",5) DECLAREENUMVALUE("E_DC_3D_NATIVE_PROPERTIES","E_DC_3D_NP_WORLD_SCALE",6) DECLAREENUMVALUE("E_DC_3D_NATIVE_PROPERTIES","E_DC_3D_NP_VISIBILITY",7) DECLAREENUMVALUE("E_DC_3D_NATIVE_PROPERTIES","E_DC_3D_NP_USER_0",8) DECLAREENUM("E_PREDICTION_TYPE") DECLAREENUMVALUE("E_PREDICTION_TYPE","E_PTYPE_PREDICTED",0) DECLAREENUMVALUE("E_PREDICTION_TYPE","E_PTYPE_RELIABLE",1) DECLAREENUMVALUE("E_PREDICTION_TYPE","E_PTYPE_NON_RELIABLE",2) DECLAREPOINTERTYPE(xDistributedClass) DECLAREPOINTERTYPE(xDistributed3DObjectClass) DECLAREPOINTERTYPE(IDistributedClasses) DECLAREPOINTERTYPE(IDistributedObjects) DECLAREPOINTERTYPE(xDistributedObject) DECLAREPOINTERTYPE(xDistributed3DObject) DECLAREPOINTERTYPE(xDistributedPropertyInfo) DECLAREPOINTERTYPE(xDistributedProperty) DECLAREPOINTERTYPE(xPredictionSetting) DECLAREPOINTERTYPE(vtConnection) DECLAREPOINTERTYPE(xNetInterface) /************************************************************************/ /* Distributed Network Classes : */ /************************************************************************/ DECLAREMETHOD_2(IDistributedClasses,xDistributedClass*,createClass,const char*,int) DECLAREMETHOD_1(IDistributedClasses,xDistributedClass*,get,const char*) DECLAREMETHOD_1(IDistributedClasses,xDistributedClass*,getByIndex,int) DECLAREMETHOD_1(IDistributedClasses,xDistributedClass*,getByIndex,int) DECLAREMETHOD_0(IDistributedClasses,int,getNumClasses) #ifndef VIRTOOLS_DEV35 DECLAREMETHOD_1(IDistributedClasses,int,destroyClass,xDistributedClass*) DECLAREMETHOD_1(IDistributedClasses,void,deployClass,xDistributedClass*) DECLAREMETHOD_1(xDistributedClass,xDistributedClass*,cast,xDistributed3DObjectClass*) DECLAREMETHOD_1(xDistributedClass,xDistributed3DObjectClass*,cast,int) #endif ////////////////////////////////////////////////////////////////////////// // // // // ////////////////////////////////////////////////////////////////////////// DECLAREMETHOD_2(xDistributedClass,void,addProperty,int,int) DECLAREMETHOD_3(xDistributedClass,void,addProperty,const char*,int,int) DECLAREOBJECTTYPE(vtNetworkManager) /************************************************************************/ /* Network Manager : */ /************************************************************************/ DECLARESTATIC_1(vtNetworkManager,vtNetworkManager*,Cast,CKBaseManager* iM) DECLAREMETHOD_3(vtNetworkManager,int,CreateClient,bool,int,const char*) DECLAREMETHOD_3(vtNetworkManager,int,CreateServer,bool,int,const char*) DECLAREMETHOD_2(vtNetworkManager,int,ConnectToServer,bool,const char*) DECLAREMETHOD_0(vtNetworkManager,int,CreateLocalConnection) #ifndef VIRTOOLS_DEV35 DECLAREMETHOD_1(vtNetworkManager,int,DeleteServer,int) DECLAREMETHOD_0(vtNetworkManager,float,getMinTickTime) DECLAREMETHOD_1(vtNetworkManager,void,setMinTickTime,float) #endif DECLAREMETHOD_0(vtNetworkManager,xNetInterface*,GetServerNetInterface) DECLAREMETHOD_0(vtNetworkManager,xNetInterface*,GetClientNetInterface) /************************************************************************/ /* net interface methods : */ /************************************************************************/ DECLAREFUN_C_0(xNetInterface*, GetNetInterface) DECLAREMETHOD_0(xNetInterface,IDistributedObjects*,getDistObjectInterface) DECLAREMETHOD_0(xNetInterface,void,createScopeObject) DECLAREMETHOD_0(xNetInterface,IDistributedClasses*,getDistributedClassInterface) DECLAREMETHOD_1(xNetInterface,int,getNumDistributedObjects,int) DECLAREMETHOD_2(xNetInterface,void,printObjects,int,int) DECLAREMETHOD_3(xNetInterface,void,enableLogLevel,int,int,int) DECLAREMETHOD_0(xNetInterface,float,getLastOneWayTime) DECLAREMETHOD_0(xNetInterface,float,getLastRoundTripTime) /************************************************************************/ /*IDistObjects : */ /************************************************************************/ DECLAREMETHOD_2(IDistributedObjects,void,create,const char*,const char*) DECLAREMETHOD_3(IDistributedObjects,xDistributedObject*,create,int,const char*,const char*) DECLAREMETHOD_1(IDistributedObjects,xDistributedObject*,get,int) /************************************************************************/ /* xDistributed Objects : */ /************************************************************************/ DECLAREMETHOD_1(xDistributedObject,xDistributed3DObject*,cast,xDistributedObject*) DECLAREMETHOD_0(xDistributed3DObject,void,updateAll) DECLAREMETHOD_0(xDistributed3DObject,void,doInitUpdate) #ifndef VIRTOOLS_DEV35 DECLAREMETHOD_0(xDistributedObject,void,getGhostDebugID) DECLAREMETHOD_1(xDistributedObject,void,setGhostDebugID,int) DECLAREMETHOD_1(xDistributedObject,void,setSessionID,int) DECLAREMETHOD_0(xDistributedObject,int,getSessionID) DECLAREMETHOD_1(xDistributedObject,xDistributedProperty*,getProperty,int) DECLAREMETHOD_1(xDistributedObject,xDistributedProperty*,getUserProperty,const char*) DECLAREMETHOD_0(xDistributedProperty,xPredictionSetting*,getPredictionSettings) DECLAREMETHOD_1(xDistributedObject,xDistributedProperty*,getProperty,int) DECLAREMETHOD_1(xPredictionSetting,void,setMinSendTime,float) DECLAREMETHOD_0(xPredictionSetting,float,getMinSendTime) DECLAREMETHOD_1(xPredictionSetting,void,setMinDifference,float) DECLAREMETHOD_0(xPredictionSetting,float,getMinDifference) DECLAREMETHOD_1(xPredictionSetting,void,setPredictionFactor,float) DECLAREMETHOD_0(xPredictionSetting,float,getPredictionFactor) #endif STOPVSLBIND }<file_sep>#pragma once void PluginCallback(PluginInfo::CALLBACK_REASON reason,PluginInterface* plugininterface); <file_sep>#include "xDistributedPoint4F.h" #include "xMathStream.h" #include "xPredictionSetting.h" #include "xDistributedPropertyInfo.h" uxString xDistributedQuatF::print(TNL::BitSet32 flags) { return uxString(); } void xDistributedQuatF::updateFromServer(xNStream *stream) { xMath::stream::mathRead(*stream,&mLastServerValue); if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { xMath::stream::mathRead(*stream,&mLastServerDifference); } setValueState(E_DV_UPDATED); } void xDistributedQuatF::updateGhostValue(xNStream *stream) { xMath::stream::mathWrite(*stream,mCurrentValue); if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) xMath::stream::mathWrite(*stream,mDifference); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedQuatF::unpack(xNStream *bstream,float sendersOneWayTime) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { sendersOneWayTime *= 0.001f; QuatF p; xMath::stream::mathRead(*bstream,&p); QuatF v; xMath::stream::mathRead(*bstream,&v); mLastValue = mCurrentValue; mCurrentValue = p; mDifference= v; QuatF predictedPos;// = p + v * sendersOneWayTime; setOwnersOneWayTime(sendersOneWayTime); } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { QuatF p; xMath::stream::mathRead(*bstream,&p); mLastValue = p; mCurrentValue = p; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedQuatF::pack(xNStream *bstream) { xMath::stream::mathWrite(*bstream,mCurrentValue); if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) xMath::stream::mathWrite(*bstream,mDifference); int flags = getFlags(); flags &= (~E_DP_NEEDS_SEND); setFlags(flags); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedQuatF::updateValue(QuatF value,xTimeType currentTime) { bool result = false; mLastTime = mCurrentTime; mCurrentTime = currentTime; mLastDeltaTime = mCurrentTime - mLastTime; mLastValue = mCurrentValue; mCurrentValue = value; mDifference = mCurrentValue - mLastValue; mThresoldTicker +=mLastDeltaTime; float lengthDiff = fabsf(mCurrentValue.angleBetween(mLastValue)); float timeDiffMs = ((float)mThresoldTicker) / 1000.f; int flags = getFlags(); flags =E_DP_OK; if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { if (lengthDiff > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime()) { flags =E_DP_NEEDS_SEND; result = true ; } } QuatF serverDiff = mCurrentValue-mLastServerValue ; float serverDiff2 = fabsf(mCurrentValue.angleBetween(mLastServerValue)); if ( serverDiff2 > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > (getPredictionSettings()->getMinSendTime() * 0.2f) ) { flags =E_DP_NEEDS_SEND; result = true ; } } if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime()) { mThresoldTicker2 = 0 ; mThresoldTicker = 0; } } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { flags =E_DP_NEEDS_SEND; result = true ; mLastValue = value; mCurrentValue = value; } setFlags(flags); return result; }<file_sep>premake4 --ExternalVTDirectory=./VTPaths.lua --Dev=Dev41 --file="./premake4.lua" vs2005 <file_sep>#include "CKAll.h" #include "Manager/InitMan.h" #ifdef CK_LIB #define RegisterBehaviorDeclarations Register_TOOLS_BehaviorDeclarations #define InitInstance _TOOLS_InitInstance #define ExitInstance _TOOLS_ExitInstance #define CKGetPluginInfoCount CKGet_TOOLS_PluginInfoCount #define CKGetPluginInfo CKGet_TOOLS_PluginInfo #define g_PluginInfo g_TOOLS_PluginInfo #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #endif CKPluginInfo g_PluginInfo; PLUGIN_EXPORT int CKGetPluginInfoCount(){return 2;} #ifdef Dev25 #include "vslmanagersdk.h" #endif #ifdef Dev3 #include "VSLManager.h" #endif CKERROR InitInstance(CKContext* context) { CKParameterManager* pm = context->GetParameterManager(); InitMan* initman =new InitMan(context); initman->RegisterVSL(); return CK_OK; } CKERROR ExitInstance(CKContext* context) { InitMan* initman =(InitMan*)context->GetManagerByGuid(INIT_MAN_GUID); delete initman; return CK_OK; } #define INIT_BEH_GUID CKGUID(0x64cb5f9a,0x1aac3b37) PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) { switch (Index) { case 0: g_PluginInfo.m_Author = "mw"; g_PluginInfo.m_Description = "tool building blocks"; g_PluginInfo.m_Extension = ""; g_PluginInfo.m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo.m_Version = 0x000001; g_PluginInfo.m_InitInstanceFct = NULL; g_PluginInfo.m_ExitInstanceFct = NULL; g_PluginInfo.m_GUID = INIT_BEH_GUID; g_PluginInfo.m_Summary = "tool BB's"; break; case 1: g_PluginInfo.m_Author = "mw"; g_PluginInfo.m_Description = "tool Manager "; g_PluginInfo.m_Extension = ""; g_PluginInfo.m_Type = CKPLUGIN_MANAGER_DLL; g_PluginInfo.m_Version = 0x000001; g_PluginInfo.m_InitInstanceFct = InitInstance; g_PluginInfo.m_ExitInstanceFct = ExitInstance; g_PluginInfo.m_GUID = INIT_MAN_GUID; g_PluginInfo.m_Summary = "tool Manager"; break; } return &g_PluginInfo; } PLUGIN_EXPORT void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg); void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) { RegisterBehavior(reg,FillBehaviorAddNodalLinkDecl); RegisterBehavior(reg,FillBehaviorDirToArrayDecl); RegisterBehavior(reg,FillBehaviorSetNodalDifficultDecl); RegisterBehavior(reg,FillBehaviorCopyFileBBDecl); RegisterBehavior(reg,FillBehaviorExecBBDecl); // [11/6/2004] // FTP /* RegisterBehavior(reg,FillBehaviorFTPLoginDecl); RegisterBehavior(reg,FillBehaviorGetFileDecl); RegisterBehavior(reg,FillBehaviorSendFileDecl);* // [11/6/2004] //Zip RegisterBehavior(reg,FillBehaviorLoadUnZipLibraryDecl); RegisterBehavior(reg,FillBehaviorLoadZipLibraryDecl); RegisterBehavior(reg,FillBehaviorUnzipFilesDecl); RegisterBehavior(reg,FillBehaviorZipFilesDecl); **/ RegisterBehavior(reg,FillBehaviorSaveObjectsDecl); RegisterBehavior(reg,FillBehaviorTextureSinusDecl); RegisterBehavior(reg,FillBehaviorNoiseDecl); RegisterBehavior(reg, FillBehaviorHasFFEffectsDecl); RegisterBehavior(reg, FillBehaviorJSetXYForceDecl); RegisterBehavior(reg,FillBehaviorGetCurrentPathDecl); RegisterBehavior(reg,FillBehaviorResolveFileNameDecl); RegisterBehavior(reg,FillBehaviorMimicDecl); /* RegisterBehavior(reg,*/ // RegisterBehavior(reg,FillBehaviorCharacterControllerDecl); } <file_sep>FIND_PATH(VTDEV35DIR NAMES dev.exe devr.exe PATHS [HKEY_LOCAL_MACHINE\\SOFTWARE\\Virtools\\Dev\\3.5;InstallPath] "X:/sdk/dev322/" ) MARK_AS_ADVANCED(CMAKE_MAKE_PROGRAM) SET(VTDEV35 1) <file_sep>#include "pTypes.h" /** \addtogroup Cloth @{ */ //! Collection of flags describing the behavior of a cloth object. enum pClothFlag { /** \brief Enable/disable pressure simulation. Note: Pressure simulation only produces meaningful results for closed meshes. */ PCF_Pressure = (1<<0), /** \brief Makes the cloth static. */ PCF_Static = (1<<1), /** \brief PCF_Static = (1<<1),/*!<Makes the cloth static. */ /** \brief Disable collision handling with the rigid body scene. @see pClothDesc.collisionResponseCoefficient */ PCF_DisableCollision = (1<<2), /** \brief Enable/disable self-collision handling within a single piece of cloth. @see PCF_triangle_collision */ PCF_SelfCollision = (1<<3), /** \brief Enable/disable gravity. If off, the cloth is not subject to the gravitational force of the rigid body scene. */ PCF_Gravity = (1<<5), /** \brief Enable/disable bending resistance. Select the bending resistance through pClothDesc.bendingStiffness. Two bending modes can be selected via the PCF_BendingOrtho flag. @see pClothDesc.bendingStiffness PCF_BendingOrtho */ PCF_Bending = (1<<6), /** \brief Enable/disable orthogonal bending resistance. This flag has an effect only if PCF_Bending is set. If PCF_BendingOrtho is not set, bending is modeled via an additional distance constraint. This mode is fast but not independent of stretching resistance. If PCF_BendingOrtho is set, bending is modeled via an angular spring between adjacent triangles. This mode is slower but independent of stretching resistance. @see pClothDesc.bendingStiffness PCF_Bending */ PCF_BendingOrtho = (1<<7), /** \brief Enable/disable damping of internal velocities. Use pClothDesc.dampingCoefficient to control damping. @see pClothDesc.dampingCoefficient */ PCF_Damping = (1<<8), /** \brief Enable/disable two way collision of cloth with the rigid body scene. In either case, cloth is influenced by colliding rigid bodies. If PCF_CollisionTwoway is not set, rigid bodies are not influenced by colliding pieces of cloth. Use pClothDesc.collisionResponseCoefficient to control the strength of the feedback force on rigid bodies. When using two way interaction care should be taken when setting the density of the attached objects. For example if an object with a very low or high density is attached to a cloth then the simulation may behave poorly. This is because impulses are only transfered between the cloth and rigid body solver outside the solvers. Two way interaction works best when NX_SF_SEQUENTIAL_PRIMARY is set in the primary scene. If not set, collision and attachment artifacts may happen. @see pClothDesc.collisionResponseCoefficient */ PCF_CollisionTwoway = (1<<9), /** Not supported in current release. \brief Enable/disable collision detection of cloth triangles against the scene. If PCF_TriangleCollision is not set, only collisions of cloth particles are detected. If PCF_TriangleCollision is set, collisions of cloth triangles are detected as well. */ PCF_TriangleCollision = (1<<11), /** \brief Defines whether the cloth is tearable. Note: Make sure meshData.maxVertices and the corresponding buffers in meshData are substantially larger (e.g. 2x) then the number of original vertices since tearing will generate new vertices. When the buffer cannot hold the new vertices anymore, tearing stops. Note: For tearing, make sure you cook the mesh with the flag NX_CLOTH_MESH_TEARABLE set in the NxClothMeshDesc.flags. @see pClothDesc.tearFactor */ PCF_Tearable = (1<<12), /** \brief Defines whether this cloth is simulated on the PPU. To simulate a piece of cloth on the PPU set this flag and create the cloth in a regular software scene. Note: only use this flag during creation, do not change it using NxCloth.setFlags(). */ PCF_Hardware = (1<<13), /** \brief Enable/disable center of mass damping of internal velocities. This flag only has an effect if the flag PCF_Damping is set. If set, the global rigid body modes (translation and rotation) are extracted from damping. This way, the cloth can freely move and rotate even under high damping. Use pClothDesc.dampingCoefficient to control damping. @see pClothDesc.dampingCoefficient */ PCF_ComDamping = (1<<14), /** \brief If the flag PCF_ValidBounds is set, cloth particles outside the volume defined by pClothDesc.validBounds are automatically removed from the simulation. @see pClothDesc.validBounds */ PCF_ValidBounds = (1<<15), /** \brief Enable/disable collision handling between this cloth and fluids. Note: With the current implementation, do not switch on fluid collision for many cloths. Create scenes with a few large pieces because the memory usage increases linearly with the number of cloths. The performance of the collision detection is dependent on both, the thickness and the particle radius of the fluid so tuning these parameters might improve the performance significantly. Note: The current implementation does not obey the pWorld::setGroupCollisionFlag settings. If PCF_FluidCollision is set, collisions will take place even if collisions between the groups that the corresponding cloth and fluid belong to are disabled. @see pClothDesc.toFluidResponseCoefficient pClothDesc.fromFluidResponseCoefficient */ PCF_FluidCollision = (1<<16), /** \brief Disable continuous collision detection with dynamic actors. Dynamic actors are handled as static ones. */ PCF_DisableDynamicCCD = (1<<17), /** \brief Moves cloth partially in the frame of the attached actor. This feature is useful when the cloth is attached to a fast moving character. In that case the cloth adheres to the shape it is attached to while only velocities below the parameter minAdhereVelocity are used for secondary effects. @see pClothDesc.minAdhereVelocity */ PCF_AddHere = (1<<18), /** \brief Invokes #attachToShape() automatically during the clothes creation procedure. This is only to be used when the entity has a physic attribute attached whereas it has to have the BF_SubShape flags enabled and the entity must be in the hierarchy of the rigid body. */ PCF_AttachToParentMainShape = (1<<19), /** \brief Invokes #attachToCollidingShapes() automatically during the clothes creation procedure. */ PCF_AttachToCollidingShapes = (1<<20), /** \brief Invokes #attachToCore() automatically during the clothes creation procedure. */ PCF_AttachToCore = (1<<21), /** \brief Attaches a cloth attribute after the clothes creation. */ PCF_AttachAttributes = (1<<22), }; /** \brief Cloth attachment flags. @see pCloth.attachToShape() pCloth.attachToCollidingShapes() pCloth.attachVertexToShape() */ enum pClothAttachmentFlag { /** \brief The default is only object->cloth interaction (one way). With this flag set, cloth->object interaction is turned on as well. */ PCAF_ClothAttachmentTwoway = (1<<0), /** \brief When this flag is set, the attachment is tearable. \note If the cloth is attached to a dynamic shape using two way interaction half way torn attachments can generate unexpected impluses on the shape. To prevent this, only attach one row of cloth vertices to the shape. @see pClothDesc.attachmentTearFactor */ PCAF_ClothAttachmentTearable = (1<<1), }; /** @} */<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> class PhysicVariableWatcher : public CKVariableManager::Watcher { public: PhysicVariableWatcher(CKContext* context, XString variableName, XString currentValue); virtual void PostWrite(const char* iName); private: PhysicVariableWatcher(); CKContext* context; CKBOOL manualSetInProgress; XString variableName; XString currentValue; }; PhysicVariableWatcher::PhysicVariableWatcher(CKContext* context, XString variableName, XString currentValue) { this->context = context; this->manualSetInProgress = FALSE; this->variableName = variableName; this->currentValue = currentValue; } static PhysicVariableWatcher *watcherConsole=NULL; void PhysicVariableWatcher::PostWrite(const char* iName) { XString newValue; XString msg; // Check if we are currently manually setting the value if (this->manualSetInProgress) return; if( !context || !context->GetVariableManager()) return; if(!GetPMan()) return; // Get new value int a=0; context->GetVariableManager()->GetValue(iName, &GetPMan()->_LogToConsole); xLogger::GetInstance()->enableConsoleOutput(GetPMan()->_LogToConsole); return ; // Validate value if (0 == newValue.Length()) { // This is valid, it means disable the GBL platform } else { int LogConsole = newValue.ToInt(); if ( LogConsole ==1 ) { // Restore back to previous value // this->manualSetInProgress = TRUE; // context->GetVariableManager()->SetValue(this->variableName.CStr(), this->currentValue.CStr()); // this->manualSetInProgress = FALSE; } else { // Remember current value //this->currentValue = newValue; // Write back in preferred format //newValue.Format("(0x%08x,0x%08x)", laid.guid.d1, laid.guid.d2); //this->manualSetInProgress = TRUE; //context->GetVariableManager()->SetValue(this->variableName.CStr(), newValue.CStr()); //this->manualSetInProgress = FALSE; } } } void PhysicManager::_registerWatchers(CKContext*context) { const char* nameConsoleLogger = "Physic Console Logger/Console"; watcherConsole = new PhysicVariableWatcher(context, nameConsoleLogger, "0"); context->GetVariableManager()->RegisterWatcher(nameConsoleLogger, watcherConsole); }<file_sep>#ifndef __xDistributedPropertyInfo_h #define __xDistributedPropertyInfo_h #include "xNetTypes.h" class xDistributedPropertyInfo { public: xDistributedPropertyInfo() : mName(NULL) , mValueType(-1) , mNativeType(-1) , mPredictionType(-1) { } xDistributedPropertyInfo( xNString name , int valueType,int nativeType, int predictionType ) : mName(name) , mValueType(valueType) , mNativeType(nativeType) , mPredictionType(predictionType) { } virtual ~xDistributedPropertyInfo(){} xNString mName; int mValueType; int mNativeType; int mPredictionType; }; #endif <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorSetUserNameDecl(); CKERROR CreateSetUserNameProto(CKBehaviorPrototype **); int SetUserName(const CKBehaviorContext& behcontext); CKERROR SetUserNameCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorSetUserNameDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NSetUserName"); od->SetDescription("Sets your user name"); od->SetCategory("TNL/User Management"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x68be0952,0xb376cd4)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetUserNameProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } typedef enum BB_IT { BB_IT_IN, }; typedef enum BB_INPAR { BB_IP_CONNECTION_ID, }; typedef enum BB_OT { BB_O_OUT, BB_O_ERROR, }; typedef enum BB_OP { BB_OP_ERROR }; CKERROR CreateSetUserNameProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NSetUserName"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("User Name ", CKPGUID_STRING, "MyNetName"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(SetUserName); proto->SetBehaviorCallbackFct(SetUserNameCB); *pproto = proto; return CK_OK; } int SetUserName(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); beh->ActivateInput(0,FALSE); int connectionID=-1; beh->GetInputParameterValue(0,&connectionID); XString userName((CKSTRING) beh->GetInputParameterReadDataPtr(1)); /************************************************************************/ /* */ /************************************************************************/ using namespace vtTools::BehaviorTools; bbNoError(E_NWE_OK); xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } if (!cin->getMyClient()) { bbError(E_NWE_INTERN); return 0; } xDistributedClient *myClient = cin->getMyClient(); if (!myClient) { bbError(E_NWE_INTERN); return 0; } IDistributedObjects *doInterface = cin->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = cin->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { xDistributedClass *_class = dobj->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT) { xDistributedClient *client = static_cast<xDistributedClient*>(dobj); if (client) { if (client->getUserID() == cin->getConnection()->getUserID() ) { client->rpcSetName(userName.CStr()); break; } } } } } begin++; } beh->ActivateOutput(0); return CKBR_OK; } CKERROR SetUserNameCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep> PhysicManager pm = GetPhysicManager(); pRigidBody b = pm.getBody(body); if(b) { b.setPosition(myPosition); b.setRotation(myQuat); b.setLinearMomentum(theNewForce); b.setAngularMomentum(theNewTorque); b.setLinearVelocity(theNewVelocity); b.setAngularVelocity(theNewVelocity); } <file_sep><Paths> RenderEngines = RenderEngines ManagerPath = Managers BehaviorPath = BuildingBlocks PluginPath = Plugins LoadFile = pBPhysicalizeExSamples.cmo LoadFile1 = GFXMenu.cmo InstallDirectory = X:\sdk\dev4 </Paths> <VideoSettings> DisableSwitch = 0 WindowWidth = 800 WindowHeight = 600 FullscreenWidth = 1024 FullscreenHeight = 768 Bpp = 32 Driver = 0 FullScreen = 0 RefreshRate = 60 Mode = 0 AntiAlias = 0 HasResolutionMask = 0 XResolutions = 400,1024,800 YResolutions = 300,768,600 OpenGLVersions = 2.0 </VideoSettings> <ApplicationConfiguration> MouseDragsWindow = 1 OwnerDrawed = 0 Render = 1 AlwayOnTop = 0 ScreenSaverMode = 0 MouseMovesTerminatePlayer = 0 Resizeable = 1 CaptionBar = 1 ShowDialog = 1 ShowAboutTab = 0 ShowConfigTab = 1 MinDirectXVersion = 9 MinRAM = 256 SizeBox = 1 Title = vtPhysX - Unit - Test UseSplash = 0 ShowLoadingProcess = 0 </ApplicationConfiguration> <Textures> entry0 = Resource\3DChatResourceDB\Textures entry1 = Resource\3DChatResourceDB\Textures\Dialogs </Textures> <file_sep>#include <StdAfx.h> #include <stdio.h> #include <cstdio> #include <stdarg.h> #include "xLogger.h" #include "uxString.h" #include "xBitSet.h" #include <Base.h> #ifdef VIRTOOLS_USER_SDK #include "CKAll.h" #endif #include <ConStream.h> using xUtils::xLogger; using xUtils::xLoggerFlags; using namespace xUtils; ConStream *consoleStream = NULL; // consoleStream = new ConStream(); void xLogger::enableConsoleOutput(bool enable) { if (enable) { if (!consoleStream) { m_LogOutChannels |= ELOGGER_CONSOLE; consoleStream = new ConStream(); consoleStream->Open(); }else{ consoleStream->Open(); } } if (!enable && consoleStream) { consoleStream->Close(); } } xLogConsumer *xLogConsumer::mLinkedList = NULL; void xLogConsumer::logString(const char *string) { OutputDebugString(string); OutputDebugString("\n"); } xLogConsumer::xLogConsumer() { mNextConsumer = mLinkedList; if(mNextConsumer) mNextConsumer->mPrevConsumer = this; mPrevConsumer = NULL; mLinkedList = this; } xLogConsumer::~xLogConsumer() { if(mNextConsumer) mNextConsumer->mPrevConsumer = mPrevConsumer; if(mPrevConsumer) mPrevConsumer->mNextConsumer = mNextConsumer; else mLinkedList = mNextConsumer; } static xLogger *xlog=NULL; const char*formatLine(const char *msg,...); void printMessage(const char*buffer); #define ANSI /* Comment out for UNIX version */ #ifdef ANSI /* ANSI compatible version */ #include <stdarg.h> int average( int first, ... ); #else /* UNIX compatible version */ #include <varargs.h> int average( va_list ); #endif void xLogger::finalPrint(const char*string) { #ifdef VIRTOOLS_USER_SDK if (getVirtoolsContext()) { getVirtoolsContext()->OutputToConsole(const_cast<char*>(string),FALSE); } #endif if (strlen(string)) { printf(string); OutputDebugString(string); } for(xLogConsumer *walk = xLogConsumer::getLinkedList(); walk; walk = walk->getNext()) walk->logString(string); } void xLogger::enableLoggingLevel(int item,int level,int enable) { std::map<int,xBitSet>::iterator it = getLogItems().find(item); if ( it !=getLogItems().end() ) { xBitSet& flags = it->second; if (level !=8) { flags.set( 1 << level,enable); }else flags.set(); } } xBitSet xLogger::getLogLevel(int item) { std::map<int,xBitSet>::iterator it = getLogItems().find(item); if ( it !=getLogItems().end() ) { return it->second; } xBitSet result; result.set(); return result; } void xLogger::addLogItem(int item) { xBitSet flags; flags.set(1 << ELOGWARNING,true); flags.set(1 << ELOGERROR,true); flags.set(1 << ELOGINFO,true); getLogItems().insert(std::make_pair(item,flags)); } void xLogger::setLoggingLevel(int item,xBitSet flags) { std::map<int,xBitSet>::iterator it = getLogItems().find(item); if ( it !=getLogItems().end() ) { xBitSet& lflags = it->second; lflags = flags; } } signed int dVsprintf(char *buffer, unsigned int bufferSize, const char *format, void *arglist) { #ifdef TNL_COMPILER_VISUALC signed int len = _vsnprintf(buffer, bufferSize, format, (va_list) arglist); #else signed int len = vsnprintf(buffer, bufferSize, format, (char *) arglist); #endif return len; } void xLogger::xLog(char *cppText,int type,int component,const char *header, ...) { GetInstance()->lastTyp = type; GetInstance()->lastComponent = component; if (!xLogger::GetInstance()->getLogLevel(component).test(1<< type) ) { return; } char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, header ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, header, s); va_end(s); char headerout[4096]; if (strlen(cppText)) { sprintf(headerout,"%s::%s\n",cppText,header); xLog(type,component,headerout,buffer); }else { xLog(type,component,header,buffer); } } void xLogger::xLog(xBitSet styleFlags,int type,int component,const char *header, ...) { /* if (!xLogger::GetInstance()->getLogLevel(component).test(1<< type) ) { return; } char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, header ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, header, s); va_end(s); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); char headerBuffer[4096]; char verbosityStr[512]; char componentString[256]; sprintf(componentString,"%s",sLogItems[component]); uxString leadIn(""); if (type > 4) { type =4; } if (type < 0) { type =0; } if ( styleFlags.test(E_PSF_PRINT_LOG_TYPE) ) { leadIn << "\n<-----------------> " << sLogTypes[type] << " : "; } if ( styleFlags.test(E_PSF_PRINT_COMPONENT) ) { leadIn << "|---" << componentString << "--|"; } leadIn << "\n"; switch(type) { case ELOGINFO: SetConsoleTextAttribute(hConsole, 10); break; case ELOGTRACE: SetConsoleTextAttribute(hConsole, 11); break; case ELOGERROR: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY | FOREGROUND_RED); break; case ELOGWARNING: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY | FOREGROUND_RED |FOREGROUND_GREEN); break; } if ( styleFlags.test(E_PSF_PRINT_LOG_TYPE) || styleFlags.test(E_PSF_PRINT_COMPONENT) ) TNL::logprintf(leadIn.CStr()); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY | FOREGROUND_RED |FOREGROUND_GREEN | FOREGROUND_BLUE); char buffer2[4096]; sprintf(buffer2," : %s ",buffer); TNL::logprintf(buffer2); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); */ return; } void xLogger::xLog(int type,int component,const char *header, ...) { GetInstance()->lastTyp = type; GetInstance()->lastComponent = component; if (!xLogger::GetInstance()->getLogLevel(component).test(1<< type) ) { return; } char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, header ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, header, s); va_end(s); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); char headerBuffer[4096]; char verbosityStr[512]; char componentString[256]; int descriptionS = xLogger::GetInstance()->getItemDescriptions().size(); const char* cString = GetInstance()->getItemDescriptions().at(component); if(component <= xLogger::GetInstance()->getItemDescriptions().size() ) sprintf(componentString,"%s",GetInstance()->getItemDescriptions().at(component)); else sprintf(componentString,"UNKNOWN COMPONENT"); switch(type) { case ELOGINFO: { sprintf(verbosityStr,"-> INFO : %s ",componentString); SetConsoleTextAttribute(hConsole, 10); } break; case ELOGTRACE: { sprintf(verbosityStr,"->TRACE: %s",componentString); SetConsoleTextAttribute(hConsole, 11); } break; case ELOGERROR: { sprintf(verbosityStr,"->ERROR:%s",componentString); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED); } break; case ELOGWARNING: { sprintf(verbosityStr,"->WARNING : %s",componentString); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); } break; } sprintf(headerBuffer,"%s",verbosityStr); //GetInstance()->finalPrint(headerBuffer); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); char buffer2[4096]; sprintf(buffer2,":%s :%s",headerBuffer,buffer); GetInstance()->finalPrint(buffer2); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); return; } void xLogger::xLogExtro(int style,const char *header, ...) { char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, header ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, header, s); va_end(s); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); char headerBuffer[4096]; sprintf(headerBuffer,"%s\n",header); GetInstance()->finalPrint(buffer); return; } void xLogger::xLog(int verbosity,const char *header,const char*msg,...) { char buffer[4096]; unsigned int bufferStart = 0; va_list s; va_start( s, msg ); dVsprintf(buffer + bufferStart, sizeof(buffer) - bufferStart, msg, s); va_end(s); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); char headerBuffer[4096]; char verbosityStr[512]; switch(verbosity) { case ELOGINFO: { sprintf(verbosityStr,"--------------------------------------INFO \n-\n"); SetConsoleTextAttribute(hConsole, 10); } break; case ELOGERROR: { sprintf(verbosityStr,"ooo--------------------------------ERROR \n-\n"); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED); } break; } sprintf(headerBuffer,"%s %s-\n--",verbosityStr,header); printf(headerBuffer); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); printf("--->%s\n ",buffer); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); return; va_list va; va_start (va,msg); char bufferN[1024] = { 0 } ; vsprintf(bufferN,msg,va ); va_end (va); printMessage(bufferN); } xBitSet& xLogger::getLogFlags() { return GetInstance()->mLogFlags ; } xBitSet& xLogger::getVerbosityFlags() { return GetInstance()->m_VerbosityFlags; } bool xLogger::isLogging(int logItem) { return GetInstance()->getVerbosityFlags().test(1<<logItem); } void xLogger::enableLogItem(int logItem,bool enbabled) { return GetInstance()->getVerbosityFlags().set(1<< logItem,enbabled); } void xLogger::Init() { #ifdef CONSOLE_OUTPUT //consoleStream->Open(); #endif } xLogger::xLogger() { xlog = this; m_LogOutChannels = ELOGGER_NONE; lastTyp = 0; lastComponent = 0; #ifdef CONSOLE_OUTPUT //m_LogOutChannels |= ELOGGER_CONSOLE; //consoleStream = new ConStream(); #endif #ifdef VIRTOOLS_USER_SDK mContext = NULL; #endif } xLogger*xLogger::GetInstance() { if (xlog ==NULL) { xlog = new xLogger(); } return xlog; } void printMessage(const char*buffer) { using namespace xUtils; #ifdef CONSOLE_OUTPUT if ( consoleStream ) { Consoleln(buffer); fflush (stderr); fflush (stdout); strcpy(consoleStream->buf,buffer); } #endif } xLogger::~xLogger() { } <file_sep>/* * Tcp4u v 3.31 Last Revision 27/06/1997 3.10 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: tcp4u_ex.c * Purpose: Add-on to Tcp4u library * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" #ifndef trace #define trace 1 #endif /*###################################################################### *## *## NAME: TCPRecvUntilClosedEx *## *## PURPOSE: Receive Tcp data until socket connection closed by server *## *####################################################################*/ int API4U TcpRecvUntilClosedEx (SOCKET far *pCSock, /* socket comm.*/ LPCSTR szLocalFile, /* local file transfer */ TRANSFER_CBK CbkTransmit, /* callback transfer */ unsigned uTimeout, /* timeout */ unsigned int uBufSize, /* buffer transfer size */ long lUserValue, /* user value */ long lTotalBytes) /* */ { int Rc; long lBytesTransferred = 0; HFILE hFile = HFILE_ERROR; LPSTR sBufRead = NULL; #define XX_RETURN(a) {\ if (hFile != HFILE_ERROR) Close(hFile);\ if (sBufRead != NULL) Free(sBufRead);\ Tcp4uLog (LOG4U_EXIT, "TcpRecvUntilClosedEx, return code %d", a); \ return a;\ } Tcp4uLog (LOG4U_PROC, "TcpRecvUntilClosedEx"); /* open user local file */ if (szLocalFile!=NULL && (hFile=Open(szLocalFile, WRITE_CR)) == HFILE_ERROR) { /* open failed */ XX_RETURN (TCP4U_FILE_ERROR); } /* allocate buffer */ if ( (sBufRead = Calloc(uBufSize<128 ? 128 : uBufSize,1)) == NULL) { XX_RETURN(TCP4U_INSMEMORY); } /* first call to user callback */ if (CbkTransmit != NULL && (*CbkTransmit)(lBytesTransferred, lTotalBytes, lUserValue, sBufRead, 0) == FALSE) { /* user stop order */ XX_RETURN (TCP4U_CANCELLED); } /* read data from http server */ do { /* read one data frame */ Rc=TcpRecv(*pCSock, sBufRead, /* adress */ uBufSize, uTimeout, HFILE_ERROR); if (Rc >= TCP4U_SUCCESS) { /* write to the user local file --> Warning signed/unsigned mismatch */ if (hFile != HFILE_ERROR && Write(hFile, sBufRead, Rc) != Rc) { XX_RETURN(TCP4U_FILE_ERROR); } lBytesTransferred += (long) Rc; /* appel du callback */ if (CbkTransmit != NULL && (*CbkTransmit)(lBytesTransferred, lTotalBytes, lUserValue, sBufRead, Rc) == FALSE) { XX_RETURN (TCP4U_CANCELLED); } } } while (Rc >= TCP4U_SUCCESS); /* END do while */ /* close all files and free allocated buffers */ XX_RETURN(Rc == TCP4U_SOCKETCLOSED ? TCP4U_SUCCESS : Rc); #undef XX_RETURN } /* END TcpRecvUntilClosedEx */ <file_sep>#ifndef __vtModuleConstants_h__ #define __vtModuleConstants_h__ //---------------------------------------------------------------- // // Include of system headers // #include <float.h> // float max //################################################################ // // Component specific names, prefixes,etc.... // //---------------------------------------------------------------- // //! \brief Global API prefix // #define VTCX_API_PREFIX "vt" //---------------------------------------------------------------- // //! \brief Module name, merged with module suffix "vt" with see #VTCX_API_PREFIX // #define VTCMODULE_NAME VTCX_API_PREFIX("Physic") //---------------------------------------------------------------- // //! \brief Modules attribute category prefix , using module name above // #define VTCMODULE_ATTRIBUTE_CATAEGORY VTCMODULE_NAME //---------------------------------------------------------------- // //! \brief Error enumerations // #include "vtModuleErrorCodes.h" //---------------------------------------------------------------- // //! \brief Error strings // #include "vtModuleErrorStrings.h" //---------------------------------------------------------------- // //! \brief Guids of the plug-in it self // #include "vtModuleGuids.h" //---------------------------------------------------------------- // //! \brief Math oriented values // #define pSLEEP_INTERVAL (20.0f*0.02f) #define pFLOAT_MAX FLT_MAX //---------------------------------------------------------------- // //! \brief Constants for building blocks // #ifndef VTCX_AUTHOR #define VTCX_AUTHOR "<NAME>" #endif #ifndef VTCX_AUTHOR_GUID #define VTCX_AUTHOR_GUID CKGUID(0x79ba75dd,0x41d77c63) #endif #endif // vtModuleConstants_h__<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "tinyxml.h" int pFactory::loadFrom(pTireFunction& dst,const char* nodeName,const TiXmlDocument * doc ) { int result = 0 ; if (!strlen(nodeName)) { return -1; } if (!doc) { return -1; } const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "tireFunction" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),nodeName ) ) { for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) { if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) { const TiXmlElement *sube = (const TiXmlElement*)node; double v; ////////////////////////////////////////////////////////////////////////// int res = sube->QueryDoubleAttribute("ExtremumSlip",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.extremumSlip = static_cast<float>(v); } } res = sube->QueryDoubleAttribute("ExtremumValue",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.extremumValue = static_cast<float>(v); } } res = sube->QueryDoubleAttribute("AsymptoteSlip",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.asymptoteSlip = static_cast<float>(v); } } res = sube->QueryDoubleAttribute("AsymptoteValue",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.asymptoteValue = static_cast<float>(v); } } res = sube->QueryDoubleAttribute("StiffnessFactor",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.stiffnessFactor = static_cast<float>(v); } } } } } } } } } return result; } int pFactory::loadWheelDescrFromXML(pWheelDescr& dst,const char* nodeName,const TiXmlDocument * doc ) { int result = 0 ; if (!strlen(nodeName)) { return -1; } if (!doc) { return -1; } const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "wheel" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),nodeName ) ) { for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) { if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) { const TiXmlElement *sube = (const TiXmlElement*)node; double v; ////////////////////////////////////////////////////////////////////////// int res = sube->QueryDoubleAttribute("Suspension",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.wheelSuspension = static_cast<float>(v); } } res = sube->QueryDoubleAttribute("Restitution",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.springRestitution = static_cast<float>(v); } } res = sube->QueryDoubleAttribute("Damping",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.springDamping = static_cast<float>(v); } } res = sube->QueryDoubleAttribute("Bias",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.springBias= static_cast<float>(v); } } res = sube->QueryDoubleAttribute("MaxBreakForce",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.maxBrakeForce = static_cast<float>(v); continue; } } res = sube->QueryDoubleAttribute("FrictionToSide",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.frictionToSide = static_cast<float>(v); continue; } } res = sube->QueryDoubleAttribute("FrictionToFront",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.frictionToFront = static_cast<float>(v); continue; } } res = sube->QueryDoubleAttribute("InverseWheelMass",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.inverseWheelMass = static_cast<float>(v); continue; } } const char* flags = NULL; flags = sube->Attribute("Flags"); if (flags && strlen(flags)) { dst.wheelFlags = (WheelFlags)_str2WheelFlag(flags); } const char* latFunc = NULL; latFunc = sube->Attribute("LateralFunction"); if (latFunc && strlen(latFunc)) { int index = getEnumIndex(getManager()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,latFunc); if (index!=0) { loadFrom(dst.latFunc,latFunc,doc); dst.latFunc.xmlLink = index; if (!dst.latFunc.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Lateral Tire Function from XML was incorrect, setting to default"); dst.latFunc.setToDefault(); } } } const char* longFunc = NULL; longFunc = sube->Attribute("LongitudeFunction"); if (longFunc && strlen(longFunc)) { int index = getEnumIndex(getManager()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,longFunc); if (index!=0) { loadFrom(dst.longFunc,longFunc,doc); dst.longFunc.xmlLink = index; if (!dst.longFunc.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Longitude Tire Function from XML was incorrect, setting to default"); dst.longFunc.setToDefault(); } } } } } } } } } } return result; } int pFactory::loadVehicleDescrFromXML(pVehicleDesc& dst,const char* nodeName,const TiXmlDocument * doc ) { int result = 0 ; if (!strlen(nodeName)) { return -1; } if (!doc) { return -1; } const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "vehicle" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),nodeName ) ) { for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) { if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) { const TiXmlElement *sube = (const TiXmlElement*)node; double v; ////////////////////////////////////////////////////////////////////////// int res = sube->QueryDoubleAttribute("Mass",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.mass = static_cast<float>(v); continue; } } ////////////////////////////////////////////////////////////////////////// /* int res = sube->QueryDoubleAttribute("Mass",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { dst.mass = static_cast<float>(v); continue; } } */ } } } } } } } return result; } int pFactory::_str2WheelFlag(XString _in) { short nb = 0 ; int result = 0; XStringTokenizer tokizer(_in.CStr(), "|"); const char*tok = NULL; while ((tok=tokizer.NextToken(tok)) && nb < 3) { XString tokx(tok); if ( _stricmp(tokx.CStr(),"Steerable") == 0 ) { result |= WF_SteerableInput; } if ( _stricmp(tokx.CStr(),"VehicleControlled") == 0 ) { result |= WF_VehicleControlled; } if ( _stricmp(tokx.CStr(),"SteerableAuto") == 0 ) { result |= WF_SteerableAuto; } if ( _stricmp(tokx.CStr(),"Handbrake") == 0 ) { result |= WF_AffectedByHandbrake; } if ( _stricmp(tokx.CStr(),"Accelerated") == 0 ) { result |= WF_Accelerated; } /*if ( _stricmp(tokx.CStr(),"Wheelshape") == 0 ) { result |= WF_UseWheelShape; }*/ nb++; } return result; } /* int pVehicle::loadFromXML(const char* nodeName,const TiXmlDocument * doc ) { NxMaterialDesc *result = new NxMaterialDesc(); result->setToDefault(); int res = 0; if (!strlen(nodeName)) { return -1; } if (!doc) { return -1; } if ( strlen(nodeName) && doc) { const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "vehicle" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),nodeName ) ) { for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) { if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) { const TiXmlElement *sube = (const TiXmlElement*)node; double v; ////////////////////////////////////////////////////////////////////////// int res = sube->QueryDoubleAttribute("Mass",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f) { //setMass() = continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("StaticFriction",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ result->staticFriction= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("Restitution",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ result->restitution= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ result->dynamicFrictionV= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// res = sube->QueryDoubleAttribute("StaticFrictionV",&v); if (res == TIXML_SUCCESS) { if(v >=0.0f){ result->staticFrictionV= (float)v; continue; } } ////////////////////////////////////////////////////////////////////////// const char* dirOfAnisotropy = NULL; dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); if (dirOfAnisotropy && strlen(dirOfAnisotropy)) { VxVector vec = pFactory::Instance()->_str2Vec(dirOfAnisotropy); if (vec.Magnitude() >0.1f) { result->flags = NX_MF_ANISOTROPIC; result->dirOfAnisotropy = pMath::getFrom(vec); continue; }else { result->dirOfAnisotropy = pMath::getFrom(VxVector(0,0,0)); } //result->setGravity(vec); } ////////////////////////////////////////////////////////////////////////// const char* FrictionCombineMode = NULL; FrictionCombineMode = sube->Attribute("FrictionCombineMode"); if (FrictionCombineMode && strlen(FrictionCombineMode)) { // int fMode = _str2CombineMode(FrictionCombineMode); // result->frictionCombineMode = (NxCombineMode)fMode; continue; } ////////////////////////////////////////////////////////////////////////// const char* RestitutionCombineMode = NULL; RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); if (RestitutionCombineMode && strlen(RestitutionCombineMode)) { // int fMode = _str2CombineMode(RestitutionCombineMode); // result->restitutionCombineMode= (NxCombineMode)fMode; continue; } } } // return result; } } } } } } return 0; } */ <file_sep>/// //////////////////////////////////////////////////////// // xLogger.h // Implementation of the Class xLogger // Created on: 10-Feb-2007 12:40:39 /////////////////////////////////////////////////////////// #if !defined __X_LOGGER_H__ #define __X_LOGGER_H__ #include <pch.h> //#include <LogTools.h> #include <xBitSet.h> //#include <base.h> #include <TypeInfo.h> #include <BaseMacros.h> #include <stdlib.h> #include <map> #include <vector> #ifndef DEBUG_CALLER #define DEBUG_CALLER #endif #ifndef TNL_COMPILER_VISUALC #define TNL_COMPILER_VISUALC #endif #ifndef DEBUG_CALLERS_FUNC #define DEBUG_CALLERS_FUNC #endif #ifndef this #define XL_PREFIX __FUNCTION__ #else #define XL_PREFIX typeid(this).name() #endif #ifndef this #define XL_OBJECT_PREFIX(T) "FN:"##T #else #define XL_OBJECT_PREFIX(T) "Call in Class:"##T #endif #define XL_START XL_OBJECT_PREFIX(XL_PREFIX) #define XLOG_PREFIX0 #ifdef VIRTOOLS_USER_SDK class CKContext; #endif namespace xUtils { typedef enum xLoggerFlags { ELOGGER_NONE=0, ELOGGER_CONSOLE=2, ELOGGER_MCORE=4, ELOGGER_CEGUI=8, ELOGGER_OUT_OBJECTS=16 }xLoggerFlags; enum ELOGTYPE { ELOGDEBUG, ELOGTRACE, ELOGERROR, ELOGWARNING, ELOGINFO, ELOGALL, }; typedef enum E_PRINT_STYLE_FLAGS { E_PSF_PRINT_LOG_TYPE=1, E_PSF_PRINT_COMPONENT, E_PSF_PRINT_NEWLINE, E_PSF_PRINT_TAB, }; static char* sLogTypes[]= { "DEBUG", "TRACE", "ERROR", "WARNING", "INFO", }; /// xLogConsumer is the base class for the message logging system in TNL. /// /// TNL by default doesn't log messages anywhere, but users of the library /// can instantiate subclasses that override the logString method. /// Any instantiated subclass of xLogConsumer will receive all general /// logprintf's, as well as any log messages that are enabled via /// the TNLLogEnable macro. class xLogConsumer { xLogConsumer *mNextConsumer; ///< Next xLogConsumer in the global linked list of log consumers. xLogConsumer *mPrevConsumer; ///< Previous xLogConsumer in the global linked list of log consumers. static xLogConsumer *mLinkedList; ///< Head of the global linked list of log consumers. public: /// Constructor adds this xLogConsumer to the global linked list. xLogConsumer(); /// Destructor removes this xLogConsumer from the global linked list, and updates the log flags. virtual ~xLogConsumer(); /// Returns the head of the linked list of all log consumers. static xLogConsumer *getLinkedList() { return mLinkedList; } /// Returns the next xLogConsumer in the linked list. xLogConsumer *getNext() { return mNextConsumer; } /// Writes a string to this instance of xLogConsumer. /// /// By default the string is sent to the Platform::outputDebugString function. Subclasses /// might log to a file, a remote service, or even a message box. virtual void logString(const char *string); }; class MODULE_API xLogger { public: xLogger(); virtual ~xLogger(); void Init(); static xBitSet& getVerbosityFlags(); void setVerbosityFlags(xBitSet val) { m_VerbosityFlags = val; } static xBitSet& getLogFlags(); void setLogFlags(xBitSet val) { mLogFlags = val; } static bool isLogging(int logItem); static void enableLogItem(int logItem,bool enbabled=true); static void xLog(int verbosity,const char *header,const char*msg,...); static void xLog(int type,int component,const char *header, ...); static void xLog(xBitSet styleFlags,int type,int component,const char *header, ...); static void xLog(char *cppText,int type,int component,const char *header, ...); static void xLogExtro(int style,const char *header, ...); static xLogger*GetInstance(); void DoProcessing(float eTime/* =0::0f */); typedef std::map<int,xBitSet>xLogItems; typedef std::vector<const char*>itemDescriptionArray; itemDescriptionArray mItemsDescriptions; itemDescriptionArray& getItemDescriptions(){return xLogger::GetInstance()->mItemsDescriptions;} inline void addItemDescription(const char*descr){ mItemsDescriptions.push_back(descr); } const char*getItemDescription(); xLogItems mLogItems; xUtils::xLogger::xLogItems& getLogItems() { return mLogItems; } void setLogItems(xUtils::xLogger::xLogItems val) { mLogItems = val; } void addLogItem(int item); void setLoggingLevel(int item,xBitSet flags); xBitSet getLogLevel(int item); void enableLoggingLevel(int item,int level,int enable); void finalPrint(const char*string); #ifdef VIRTOOLS_USER_SDK CKContext * getVirtoolsContext() const { return mContext; } void setVirtoolsContext(CKContext * val) { mContext = val; } #endif void enableConsoleOutput(bool enable); protected : #ifdef VIRTOOLS_USER_SDK CKContext *mContext; #endif xBitSet mLogFlags; xBitSet m_VerbosityFlags; int m_Verbosity; int m_LogOutChannels; public : int lastTyp; int lastComponent; }; } using namespace xUtils; #endif // !defined(EA_3DFA15A6_382B_4624_9E00_4531365CB9AF__INCLUDED_) <file_sep>/******************************************************************** created: 2004/11/06 created: 6:11:2004 16:53 filename: D:\projects new\vt tools\Manager\typedefs.h file path: D:\projects new\vt tools\Manager file base: typedefs file ext: h author: purpose: gBaumgart *********************************************************************/ #ifndef TYPEDEFS_H #define TYPEDEFS_H #include "CKAll.h" #include <STDLIB.H> #include <LIST> #include <MAP> /* The following template "Hashfunc" only meets the requests of std::map. the reason for it is the standard compare.(result : int, but bool is used) from XString.h: int operator == (const XBaseString& iStr) const { return !Compare(iStr); } if i donŽt use this help class iŽll get the following warning: " D:\SDK\VC98\INCLUDE\functional(86) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning) D:\SDK\VC98\INCLUDE\functional(86) : while compiling class-template member function 'bool __thiscall std::less<class XString>::operator ()(const class XString &,const class XString &) const' " by call ZipJobList zili.find(XXX) or use simply : struct XStringCMP{ bool operator() (const XString& p, const XString& q) const { return strcmp(p.CStr(),q.CStr())<0; } }; */ template <class T> struct HashFunc{ bool operator ()(const T& x,const T& y)const; }; //the XString special: template <> struct HashFunc<XString>{ bool operator ()(const XString& In1,const XString& In2)const{ return strcmp(In1.CStr(),In2.CStr())<0; /* or : size_t out = 0; const char* key = In1.CStr(); while (*key) out = (out <<1)^*key++;//an integer rep of a c-string */ } }; /* ZipJobList +Keystring | Filelist +...... */ typedef std::list<XString>XFileList; typedef std::list<XString>::iterator XFileListIterator; typedef std::map<XString,XFileList*,HashFunc<XString> >ZipJobList; typedef std::map<XString,XFileList*,HashFunc<XString> >::iterator ZiJoIt; /************************************************************************/ /* none zip stuff */ /************************************************************************/ /************************************************************************/ /* a workin array container */ /************************************************************************/ /* template<class T, int amount> class fake_container{ public: //standard stuff: typedef T value_type; typedef T* iterator; typedef const T*const_iterator; typedef T& reference; typedef const T& const_reference; typedef const T* const_iterator; T v[amount]; operator T*() {return v;} //ops: iterator& operator++(){return v+1;} iterator& operator--(){return v-1;} //.......................................................... //nice: reference operator[] (ptrdiff_t i) { return v[i] ; } const_reference operator[] (ptrdiff_t i) const { return v[i] ; } iterator begin() {return v;} const_iterator begin() const {return v;} iterator end() {return v+amount;} const_iterator end() const {return v + amount;} size_t size () const { return amount;} protected: }; */ /************************************************************************/ /* tests */ /************************************************************************/ //this should become pointer array, but very strange /* template<class T> class Vector{ T*v; int sz; public: Vector(); // explicit Vector(int); // Vector(); // operator T*() {return v;} //T& elem(int i){return v[i];} //T& operator[](int i); }; */ //thats becomes a vector - void - pointer - special template /* template<> class Vector<void*>{ void **p; void *&operator[](int i); }; */ /************************************************************************/ /* the void* specialist: */ /************************************************************************/ /* template<class T> class Vector<T*> : private Vector<void*>{ public: typedef Vector<void*> Base; Vector() : Base(){} puplicit Vector()(int i) : Base(i){} T*elem(int i){ return static_cast<T*&>(Base::elem(i));} T*& operator[](int i){return static_cast<T*&>(Base::operator [](i));} }; */ /* template<class T> class Vector{ T*v; int sz; public: Vector(); explicit Vector(int); operator T*() {return v;} T& elem(int i){return v[i];} T& operator[](int i); }; */ #endif <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SwitchOnMidi // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "../MidiManager.h" CKERROR CreateSwitchOnMidiProto(CKBehaviorPrototype **); int SwitchOnMidi(const CKBehaviorContext& behcontext); CKERROR SwitchOnMidiCallBack(const CKBehaviorContext& behcontext); // CallBack Functioon /*******************************************************/ /* PROTO DECALRATION */ /*******************************************************/ CKObjectDeclaration *FillBehaviorSwitchOnMidiDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Switch On Midi"); od->SetDescription("Activates the appropriate output when receiving a Midi event."); od->SetType( CKDLL_BEHAVIORPROTOTYPE ); od->SetGuid(CKGUID(0x624b1bec,0x509400a8)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSwitchOnMidiProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Controllers/Midi"); return od; } /*******************************************************/ /* PROTO CREATION */ /*******************************************************/ CKERROR CreateSwitchOnMidiProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Switch On Midi"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareInput("Off"); proto->DeclareOutput("Out 1"); proto->DeclareInParameter("Channel", CKPGUID_INT, "0"); proto->DeclareInParameter("Note 1", CKPGUID_INT, "0"); proto->DeclareOutParameter("Nop", CKPGUID_NONE); proto->DeclareOutParameter("Attack 1", CKPGUID_INT, "0"); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEOUTPUTS| CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS| CKBEHAVIOR_INTERNALLYCREATEDOUTPUTPARAMS)); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SwitchOnMidi); proto->SetBehaviorCallbackFct( SwitchOnMidiCallBack ); *pproto = proto; return CK_OK; } /*******************************************************/ /* MAIN FUNCTION */ /*******************************************************/ int SwitchOnMidi(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; if( beh->IsInputActive(1) ){ // OFF beh->ActivateInput(1, FALSE); return CKBR_OK; } if( beh->IsInputActive(0) ){ // ON beh->ActivateInput(0, FALSE); } int channel=0; // Channel beh->GetInputParameterValue(0, &channel); MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); int note, attack, count = beh->GetInputParameterCount(); for( int a=1 ; a<count ; a++ ){ beh->GetInputParameterValue(a, &note); if( mm->IsNoteActive(note, channel) ){ beh->ActivateOutput(a-1); } //--- Attack part XListIt<midiMessage> it; for( it = mm->listForBehaviors.Begin() ; it!=mm->listForBehaviors.End() ; it++ ){ if( (*it).channel==channel ){ if( (*it).command==9 || (*it).command==8 ){ // start a note if( note == (*it).note ){ attack = (*it).attack; beh->SetOutputParameterValue(a, &attack); } } } } //--- } return CKBR_ACTIVATENEXTFRAME; } /*******************************************************/ /* CALLBACK */ /*******************************************************/ CKERROR SwitchOnMidiCallBack(const CKBehaviorContext& behcontext){ CKBehavior *beh = behcontext.Behavior; MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); switch( behcontext.CallbackMessage ){ case CKM_BEHAVIOREDITED: { int c_out = beh->GetOutputCount(); int c_pin = beh->GetInputParameterCount()-1; char str[16]; while( c_pin < c_out ){ // we must add Input Params / Ouput Params sprintf( str, "Note %d", c_pin+1); beh->CreateInputParameter(str, CKPGUID_INT); sprintf( str, "Attack %d", c_pin+1); beh->CreateOutputParameter(str, CKPGUID_INT); ++c_pin; } while( c_pin > c_out ){ // we must remove Input Params / Ouput Params CKDestroyObject(beh->RemoveInputParameter(c_pin)); CKDestroyObject(beh->RemoveOutputParameter(c_pin)); --c_pin; } CKBehaviorIO *out; while( c_out ){ --c_out; out = beh->GetOutput(c_out); sprintf( str, "Out %d", c_out+1); out->SetName(str); } } break; case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: { mm->AddMidiBBref(); } break; case CKM_BEHAVIORDETACH: { mm->RemoveMidiBBref(); } break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" #include "IParameter.h" CKObjectDeclaration *FillBehaviorPBPhysicalizeExDecl(); CKERROR CreatePBPhysicalizeExProto(CKBehaviorPrototype **pproto); int PBPhysicalizeEx(const CKBehaviorContext& behcontext); CKERROR PBPhysicalizeExCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_HullType, bbI_Flags, bbI_Density, bbI_XML,// from here optional parameters bbI_World, bbI_Pivot, bbI_Mass, bbI_Collision, bbI_CCD, bbI_Material, bbI_Optimization, bbI_Capsule, bbI_CCylinder, }; #define BB_SSTART 3 #define gPIMAP pInMap232 BBParameter pInMap232[] = { BB_PIN(bbI_HullType,VTE_COLLIDER_TYPE,"Hull Type","Sphere"), BB_PIN(bbI_Flags,VTF_BODY_FLAGS,"Flags","Moving Object,World Gravity,Collision"), BB_PIN(bbI_Density,CKPGUID_FLOAT,"Density","1.0"), BB_SPIN(bbI_XML,VTS_PHYSIC_ACTOR_XML_SETUP,"XML Setup",""),// from here optional parameters BB_SPIN(bbI_World,CKPGUID_3DENTITY,"World Reference","pDefaultWorld"), BB_SPIN(bbI_Pivot,VTS_PHYSIC_PIVOT_OFFSET,"Pivot",""), BB_SPIN(bbI_Mass,VTS_PHYSIC_MASS_SETUP,"Mass",""), BB_SPIN(bbI_Collision,VTS_PHYSIC_COLLISIONS_SETTINGS,"Collision","All,0,0.025f"), BB_SPIN(bbI_CCD,VTS_PHYSIC_CCD_SETTINGS,"CCD",""), BB_SPIN(bbI_Material,VTS_MATERIAL,"Material",""), BB_SPIN(bbI_Optimization,VTS_PHYSIC_ACTOR_OPTIMIZATION,"Optimization",""), BB_SPIN(bbI_Capsule,VTS_CAPSULE_SETTINGS_EX,"Capsule Settings",""), BB_SPIN(bbI_CCylinder,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,"Convex Cylinder Settings",""), }; CKObjectDeclaration *FillBehaviorPBPhysicalizeExDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBPhysicalizeEx"); od->SetCategory("Physic/Body"); od->SetDescription("Adds an entity to the physic engine."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x16b33c81,0x8a96d3e)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBPhysicalizeExProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBPhysicalizeExProto // FullName: CreatePBPhysicalizeExProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBPhysicalizeExProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBPhysicalizeEx"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PBPhysicalizeEx PBPhysicalizeEx is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Registers an object in the physic engine.<br> See <A HREF="PBPhysicalizeExSamples.cmo">PBPhysicalizeEx.cmo</A> for example. <h3>Technical Information</h3> \image html PBPhysicalizeEx.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed <BR> <BR> <SPAN CLASS="pin">Target:</SPAN>The 3D Entity associated to the rigid body <BR> <SPAN CLASS="pin">Flags: </SPAN>Flags to determine common properties for the desired body.It is possible to alter certain flags after creation. See #BodyFlags for more information <br> - <b>Range:</b> [BodyFlags] - <b>Default:</b>Moving,Collision,World Gravity<br> - Ways to alter flags : - Using \ref PBSetPar - Using VSL : #pRigidBody::updateFlags() <SPAN CLASS="pin">Hull Type: </SPAN>The desired shape type. The intial shape can NOT be changed after creation. See #HullType for more information <br> - <b>Range:</b> [HullType]<br> - <b>Default:</b>Sphere<br> <SPAN CLASS="pin">Density: </SPAN>Density of the initial shape <br> - <b>Range:</b> [0,inf]<br> - <b>Default:</b>1.0f<br> - Ways to change the mass : - Enable "Mass" in building block settings and set "New Density" or "Total Mass" non-zero. - Using VSL #pRigidBody::updateMassFromShapes() <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createRigidBody().<br> <h3>Optional Parameters</h3> All more specific parameters such as material or pivot offset must be enabled by the building block settings<br> PBPhysicalizeEx all settings enabled : <br> \image html PBPhysicalizeExCollapsed.jpg <SPAN CLASS="pin">XML Setup: </SPAN>This parameter is not being used in this release<br> <hr> <SPAN CLASS="pin">World Reference: </SPAN>World associated with this rigid body. Leave blank to use default world (3D - Frame "pDefaultWorld" with world attribute) <br> - <b>Range:</b> [object range]<br> - <b>Default:</b>NULL<br> <hr> <SPAN CLASS="pin">Pivot: </SPAN>Specifies the rigid bodies local shape offset (#pPivotSettings) <br><br> \image html pBPivotParameter.jpg - <b>Offset Linear:</b> \copydoc pPivotSettings::localPosition - <b>Offset Angular:</b> \copydoc pPivotSettings::localOrientation - <b>Offset Reference:</b> \copydoc pPivotSettings::pivotReference <h4>Notes</h4><br> - Alter or set the shape offset : - Using the built-in building blocks with "Physics" settings enabled : - "Set Position" - "Translate" - "Set Orientation" - #pRigidBody::setPosition() or #pRigidBody::setRotation() - Attach attribute "Physics\pBPivotSettings" to : - 3D-Entity - its mesh - or to the meshes material<br> <hr> <SPAN CLASS="pin">Mass: </SPAN>Overrides mass setup (#pMassSettings) <br><br> \image html pBMassParameter.jpg - <b>New Density:</b> \copydoc pMassSettings::newDensity - <b>Total Mass:</b> \copydoc pMassSettings::totalDensity - <b>Offset Linear:</b> \copydoc pMassSettings::localPosition - <b>Offset Angular:</b> \copydoc pMassSettings::localOrientation - <b>Offset Reference:</b> \copydoc pMassSettings::massReference <h4>Notes</h4><br> - Alter or set mass settings : - Attach attribute "Physics\pBOptimization" to the : - 3D-Entity - its mesh - or to the meshes material<br> - #pRigidBody::updateMassFromShapes() <hr> <SPAN CLASS="pin">Collision: </SPAN>Overrides collsion settings (#pCollisionSettings) <br><br> \image html pBCollisionParameter.jpg - <b>Collision Group: </b> \copydoc pCollisionSettings::collisionGroup - <b>Group Mask:</b> \copydoc pCollisionSettings::groupsMask - <b>Skin Width:</b>\copydoc pCollisionSettings::skinWidth <h4>Notes</h4><br> - Alter or set collisions settings : - \ref PBSetPar. Collisions group can be set per sub shape. - pRigidBody::setCollisionsGroup() - pRigidBody::setGroupsMask() - Attach attribute "Physics\pBCollisionSettings" to : - 3D-Entity - its mesh - or to the meshes material <br> - Please create custom groups in the Virtools "Flags and Enum manager" : "pBCollisionsGroup". This enumeration is stored in the cmo <br> <hr> <SPAN CLASS="pin">CCD: </SPAN>Specifies a CCD mesh. This parameter is NOT being used in this release.<br><br> \image html pBCCSettingsParameter.jpg <hr> <SPAN CLASS="pin">Material: </SPAN>Specifies a physic material(#pMaterial)<br><br> \image html pBMaterial.jpg - <b>XML Link :</b> \copydoc pMaterial::xmlLinkID - <b>Dynamic Friction :</b> \copydoc pMaterial::dynamicFriction - <b>Static Friction: </b> \copydoc pMaterial::staticFriction - <b>Restitution: </b> \copydoc pMaterial::restitution - <b>Dynamic Friction V: </b> \copydoc pMaterial::dynamicFrictionV - <b>Static Friction V : </b> \copydoc pMaterial::staticFrictionV - <b>Direction Of Anisotropy: </b> \copydoc pMaterial::dirOfAnisotropy - <b>Friction Combine Mode: </b> \copydoc pMaterial::frictionCombineMode - <b>Restitution Combine Mode: </b> \copydoc pMaterial::restitutionCombineMode - <b>Flags: </b> \copydoc pMaterial::flags <h4>Notes</h4><br> - Alter or set a physic material is also possible by : - \ref PBSetMaterial - #pRigidBody::updateMaterialSettings() - Attach attribute "Physics\pBMaterial" to : - 3D-Entity - its mesh - or to the meshes material - Using VSL : <SPAN CLASS="NiceCode"> \include pBMaterialSetup.vsl </SPAN> - The enumeration "XML Link" is being populated by the file "PhysicDefaults.xml" and gets updated on every reset. - If using settings from XML, the parameter gets updated too<br> <hr> <SPAN CLASS="pin">Optimization: </SPAN>Specifies various optimizations(#pOptimization)<br><br> \image html pBOptimization.jpg - <b>Transformation Locks :</b> Flags to lock a rigid body in certain degree of freedom. See also #pRigidBody::lockTransformation - <b>Damping:</b> - <b>Linear Damping :</b> \copydoc pRigidBody::setLinearDamping - <b>Angular Damping :</b> \copydoc pRigidBody::setAngularDamping - <b>Sleeping:</b> - <b>Linear Sleep Velocity :</b> \copybrief pRigidBody::setSleepLinearVelocity - <b>Angular Sleep Velocity :</b> \copydoc pRigidBody::setSleepAngularVelocity - <b>Sleep Energy Threshold :</b> \copydoc pRigidBody::setSleepEnergyThreshold - <b>Solver Iteration :</b> \copydoc pRigidBody::setSolverIterationCount - <b>Dominance Group :</b> \copydoc pRigidBody::setDominanceGroup - <b>Compartment Id :</b> Not Implemented <h4>Notes</h4><br> - Alter or set a rigid bodies optimization is also possible by : - \ref PBSetPar - #pRigidBody::updateOptimizationSettings() - Attach the attribute "Physics\pBOptimization" to : - 3D-Entity - its mesh - or to the meshes material<br> - Using VSL before creation : \include pBOptimizationCreation.vsl - Using VSL after creation : <SPAN CLASS="NiceCode"> \include pBOptimizationAfterCreation.vsl </SPAN> <hr> <SPAN CLASS="pin">Capsule Settings: </SPAN>Overrides capsule default dimensions(#pCapsuleSettingsEx)<br><br> \image html pBCapsuleSettings.jpg - <b>Radius :</b> \copydoc pCapsuleSettingsEx::radius - <b>Height :</b> \copydoc pCapsuleSettingsEx::height <h4>Notes</h4><br> - Setting a rigid bodies capsule dimension is also possible by : - Attach the attribute "Physics\pCapsule" to : - 3D-Entity - its mesh - or to the meshes material - VSL : <SPAN CLASS="NiceCode"> \include pBCapsuleEx.vsl </SPAN> <hr> <SPAN CLASS="pin">Convex Cylinder Settings: </SPAN>Overrides default convex cylinder settings(#pConvexCylinderSettings)<br><br> \image html pBConvexCylinder.jpg - <b>Approximation :</b> \copydoc pConvexCylinderSettings::approximation - <b>Radius :</b> \copydoc pConvexCylinderSettings::radius - <b>Height :</b> \copydoc pConvexCylinderSettings::height - <b>Forward Axis :</b> \copydoc pConvexCylinderSettings::forwardAxis - <b>Forward Axis Reference:</b> \copydoc pConvexCylinderSettings::forwardAxisRef - <b>Down Axis :</b> \copydoc pConvexCylinderSettings::downAxis - <b>Down Axis Reference:</b> \copydoc pConvexCylinderSettings::downAxisRef - <b>Right :</b> \copydoc pConvexCylinderSettings::rightAxis - <b>Right Axis Reference:</b> \copydoc pConvexCylinderSettings::rightAxisRef - <b>Build Lower Half Only :</b> \copydoc pConvexCylinderSettings::buildLowerHalfOnly - <b>Convex Flags :</b> \copydoc pConvexCylinderSettings::convexFlags <h4>Notes</h4><br> - Set a rigid bodies convex cylinder parameters by : - Attach the attribute "Physics\pConvexCylinder" to : - 3D-Entity - its mesh - or to the meshes material - VSL : <SPAN CLASS="NiceCode"> \include pBConvexCylinder.vsl </SPAN> <hr> */ BB_EVALUATE_PINS(gPIMAP) BB_EVALUATE_SETTINGS(gPIMAP) proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct( PBPhysicalizeExCB ); proto->SetFunction(PBPhysicalizeEx); *pproto = proto; return CK_OK; } //************************************ // Method: PBPhysicalizeEx // FullName: PBPhysicalizeEx // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBPhysicalizeEx(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // objects // CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); //the world reference, optional used CK3dEntity*worldRef = NULL; //the world object, only used when reference has been specified pWorld *world = NULL; //final object description pObjectDescr *oDesc = new pObjectDescr(); pRigidBody *body = NULL; XString errMesg; //---------------------------------------------------------------- // // sanity checks // // rigid body GetPMan()->getBody(target); if( body){ errMesg.Format("Object %s already registered.",target->GetName()); bbErrorME(errMesg.Str()); } //---------------------------------------------------------------- // // // if (!GetPMan()->isValid()) GetPMan()->performInitialization(); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Collecting data. Stores all settings in a pObjectDescr. // //get the parameter array BB_DECLARE_PIMAP; //---------------------------------------------------------------- // // generic settings // oDesc->hullType = (HullType)GetInputParameterValue<int>(beh,bbI_HullType); oDesc->flags = (BodyFlags)GetInputParameterValue<int>(beh,bbI_Flags); oDesc->density = GetInputParameterValue<float>(beh,bbI_Density); //---------------------------------------------------------------- // optional // world // BBSParameterM(bbI_World,BB_SSTART); if (sbbI_World) { worldRef = (CK3dEntity *) beh->GetInputParameterObject(BB_IP_INDEX(bbI_World)); if (worldRef) { world = GetPMan()->getWorld(worldRef,target); if (!world) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"World reference has been specified but no valid world object found. Switching to default world"); goto errorFound; } } } //---------------------------------------------------------------- // optional // Pivot // BBSParameterM(bbI_Pivot,BB_SSTART); if (sbbI_Pivot) { CKParameter*pivotParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Pivot))->GetRealSource(); if (pivotParameter) { IParameter::Instance()->copyTo(oDesc->pivot,pivotParameter); oDesc->mask |= OD_Pivot; } } //---------------------------------------------------------------- // optional // mass // BBSParameterM(bbI_Mass,BB_SSTART); if (sbbI_Mass) { CKParameter*massParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Mass))->GetRealSource(); if (massParameter) { IParameter::Instance()->copyTo(oDesc->mass,massParameter); oDesc->mask |= OD_Mass; } } //---------------------------------------------------------------- // optional // collision // BBSParameterM(bbI_Collision , BB_SSTART); if (sbbI_Collision) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Collision))->GetRealSource(); if (par) { oDesc->collisionGroup = GetValueFromParameterStruct<int>(par,PS_BC_GROUP,false); CKParameterOut* maskPar = GetParameterFromStruct(par,PS_BC_GROUPSMASK); if (maskPar) { oDesc->groupsMask.bits0 = GetValueFromParameterStruct<int>(maskPar,0); oDesc->groupsMask.bits1 = GetValueFromParameterStruct<int>(maskPar,1); oDesc->groupsMask.bits2 = GetValueFromParameterStruct<int>(maskPar,2); oDesc->groupsMask.bits3 = GetValueFromParameterStruct<int>(maskPar,3); } oDesc->skinWidth = GetValueFromParameterStruct<float>(par,PS_BC_SKINWITDH,false); IParameter::Instance()->copyTo(oDesc->collision,par); oDesc->mask |= OD_Collision; } } //---------------------------------------------------------------- // optional // collision : CCD // BBSParameterM(bbI_CCD, BB_SSTART); if (sbbI_CCD) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCD))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc->ccd,par); oDesc->mask |= OD_CCD; } } //---------------------------------------------------------------- // optional // optimization // BBSParameterM(bbI_Optimization, BB_SSTART); if (sbbI_Optimization) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Optimization))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc->optimization,par); oDesc->mask |= OD_Optimization; } } //---------------------------------------------------------------- // optional // Material // BBSParameterM(bbI_Material, BB_SSTART); if (sbbI_Material) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); if (par) { pFactory::Instance()->copyTo(oDesc->material,par); oDesc->mask |= OD_Material; } } //---------------------------------------------------------------- // optional // capsule // BBSParameterM(bbI_Capsule, BB_SSTART); if (sbbI_Capsule) { if (oDesc->hullType == HT_Capsule) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Capsule))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc->capsule,par); oDesc->mask |= OD_Capsule; } }else{ errMesg.Format("You attached a capsule parameter but the hull type is not capsule"); bbWarning(errMesg.Str()); } } //---------------------------------------------------------------- // optional // convex cylinder // BBSParameterM(bbI_CCylinder, BB_SSTART); if (sbbI_CCylinder) { if (oDesc->hullType == HT_ConvexCylinder) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCylinder))->GetRealSource(); if (par) { pFactory::Instance()->copyTo(oDesc->convexCylinder,par,true); oDesc->mask |= OD_ConvexCylinder; } }else{ errMesg.Format("You attached a convex cylinder parameter but the hull type is not a convex cylinder"); bbWarning(errMesg.Str()); } } oDesc->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // body creation // if (!body) { if(! (oDesc->flags & BF_SubShape) ) { body = pFactory::Instance()->createRigidBody(target,*oDesc); } } if (!body) { SAFE_DELETE(oDesc); bbErrorME("No Reference Object specified"); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // attribute creation, attach settings // if (oDesc->flags & BF_AddAttributes ) { //body->saveToAttributes(oDesc); GetPMan()->copyToAttributes(*oDesc,target); } //---------------------------------------------------------------- // // update input parameters // if (sbbI_Material) { CKParameterOut *par = (CKParameterOut*)beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); if (par) { pFactory::Instance()->copyTo(par,oDesc->material); } } //---------------------------------------------------------------- // // cleanup // //SAFE_DELETE(oDesc); //---------------------------------------------------------------- // // error out // errorFound: { beh->ActivateOutput(0); return CKBR_GENERICERROR; } //---------------------------------------------------------------- // // All ok // allOk: { beh->ActivateOutput(0); return CKBR_OK; } return 0; } //************************************ // Method: PBPhysicalizeExCB // FullName: PBPhysicalizeExCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBPhysicalizeExCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; } <file_sep>#include "ResourceTools.h" HINSTANCE GetModulefromResource(HMODULE hModule,int name,char *tempfile){ BYTE *data; HANDLE hfile; DWORD len,c; char temppath[MAX_PATH]; HRSRC hres; if (hres=FindResource((HMODULE)hModule,MAKEINTRESOURCE(name),RT_RCDATA)){ len=SizeofResource(hModule,hres); hres=(HRSRC)LoadResource(hModule,hres); data=(BYTE*)LockResource((HRSRC)hres); } GetTempPath(MAX_PATH,temppath); GetTempFileName(temppath,"tostrong",0,tempfile); hfile=CreateFile(tempfile,GENERIC_WRITE|FILE_SHARE_DELETE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); WriteFile(hfile,data,len,&c,NULL); CloseHandle(hfile); delete data; return LoadLibrary(tempfile); } HMODULE GetParentModule(CK_PLUGIN_TYPE type,CKGUID guid){ CKPluginManager* ThePluginManager=CKGetPluginManager(); for (int i=0;i<ThePluginManager->GetPluginDllCount();i++){ CKPluginEntry* desc=ThePluginManager->GetPluginInfo(type,i); CKPluginDll* dll =ThePluginManager->GetPluginDllInfo(desc->m_PluginDllIndex); if (desc->m_PluginInfo.m_GUID == guid)return ((HMODULE)dll->m_DllInstance); } return NULL; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pWorldCallbacks.h" bool pContactModify::onContactConstraint(NxU32& changeFlags, const NxShape* shape0, const NxShape* shape1, const NxU32 featureIndex0, const NxU32 featureIndex1, NxContactCallbackData& data) { bool result = true; NxActor *actor0 = &shape0->getActor(); NxActor *actor1 = &shape1->getActor(); pRigidBody *body0 = NULL; pRigidBody *body1 = NULL; if (actor0) { body0 = static_cast<pRigidBody*>(actor0->userData); } if (actor1) { body1 = static_cast<pRigidBody*>(actor1->userData); } pContactModifyData cData; cData.dynamicFriction0 = data.dynamicFriction0; cData.dynamicFriction1 = data.dynamicFriction1; cData.staticFriction0 = data.staticFriction0; cData.staticFriction1 = data.staticFriction1; cData.localorientation0 = getFrom(data.localorientation0); cData.localorientation1 = getFrom(data.localorientation1); cData.localpos0 = getFrom(data.localpos0); cData.localpos1 = getFrom(data.localpos1); cData.restitution = data.restitution; cData.minImpulse = data.minImpulse; cData.maxImpulse = data.maxImpulse; cData.target = getFrom(data.target); cData.error = getFrom(data.error); //---------------------------------------------------------------- // // execute callback scripts // if (body0 ) { if (body0->getFlags() & BF_ContactModify ) { result = body0->onContactConstraint((int&)changeFlags,body0->GetVT3DObject(),body1->GetVT3DObject(),&cData); if (!result) return false; if (changeFlags == CMM_None ) { return true; } } } if (body1) { if (body1->getFlags() & BF_ContactModify) { result = body1->onContactConstraint((int&)changeFlags,body1->GetVT3DObject(),body0->GetVT3DObject(),&cData); if (!result) return false; if (changeFlags == CMM_None ) { return true; } } } //---------------------------------------------------------------- // // copy result back to sdk // if (changeFlags!=CMM_None) { data.dynamicFriction0 = cData.dynamicFriction0; data.dynamicFriction1 = cData.dynamicFriction1; data.staticFriction0 = cData.staticFriction0; data.staticFriction1 = cData.staticFriction1; data.localorientation0 = getFrom(cData.localorientation0); data.localorientation1 = getFrom(cData.localorientation1); data.localpos0 = getFrom(cData.localpos0); data.localpos1 = getFrom(cData.localpos1); data.restitution = cData.restitution; data.minImpulse = cData.minImpulse; data.maxImpulse = cData.maxImpulse; data.target = getFrom(cData.target); data.error = getFrom(cData.error); } return true; } void pContactReport::onContactNotify(NxContactPair& pair, NxU32 events) { pRigidBody *bodyA = NULL; pRigidBody *bodyB = NULL; if (pair.actors[0]) { bodyA = static_cast<pRigidBody*>(pair.actors[0]->userData); } if (pair.actors[1]) { bodyB = static_cast<pRigidBody*>(pair.actors[1]->userData); } if (bodyA) { /* if (bodyA->hasWheels()) { bodyA->handleContactPair(&pair,0); return ; } */ /* if (bodyA->getVehicle()) { pVehicle* v = bodyA->getVehicle(); v->handleContactPair(&pair, 0); return ; } */ } if ( bodyB ) { /* if (bodyB->hasWheels()) { bodyB->handleContactPair(&pair,1); return ; } if (bodyB->getVehicle()) { pVehicle* v = bodyB->getVehicle(); v->handleContactPair(&pair, 1); return ; } */ } // Iterate through contact points NxContactStreamIterator i(pair.stream); //user can call getNumPairs() here while(i.goNextPair()) { //user can also call getShape() and getNumPatches() here while(i.goNextPatch()) { //user can also call getPatchNormal() and getNumPoints() here const NxVec3& contactNormal = i.getPatchNormal(); while(i.goNextPoint()) { //user can also call getPoint() and getSeparation() here const NxVec3& contactPoint = i.getPoint(); pCollisionsEntry entry; entry.point = pMath::getFrom(contactPoint); NxU32 faceIndex = i.getFeatureIndex0(); if(faceIndex==0xffffffff)faceIndex = i.getFeatureIndex1(); if(faceIndex!=0xffffffff)entry.faceIndex = faceIndex; entry.actors[0] = pair.actors[0]; entry.actors[1] = pair.actors[1]; entry.faceIndex = faceIndex; entry.sumNormalForce = pMath::getFrom(pair.sumNormalForce); entry.sumFrictionForce = pMath::getFrom(pair.sumFrictionForce); entry.faceNormal = pMath::getFrom(contactNormal); entry.eventType = events; entry.pointNormalForce=i.getPointNormalForce(); entry.distance = i.getSeparation(); //////////////////////////////////////////////////////////////////////////// //store shapes NxShape *shapeA = i.getShape(0); if (shapeA) { pSubMeshInfo *shapeInfo= static_cast<pSubMeshInfo*>(shapeA->userData); if (shapeInfo) { entry.shapeEntityA = shapeInfo->entID; } } shapeA = i.getShape(1); if (shapeA) { pSubMeshInfo *shapeInfo= static_cast<pSubMeshInfo*>(shapeA->userData); if (shapeInfo) { entry.shapeEntityB = shapeInfo->entID; } } pRigidBody *bodyA = NULL; pRigidBody *bodyB = NULL; if (pair.actors[0]) { bodyA = static_cast<pRigidBody*>(pair.actors[0]->userData); } if (pair.actors[1]) { bodyB = static_cast<pRigidBody*>(pair.actors[1]->userData); } if (bodyA && bodyA->getActor() /*&& (bodyA->getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) */) { entry.bodyA = bodyA; entry.bodyB = bodyB; bodyA->getCollisions().Clear(); bodyA->getCollisions().PushBack(entry); bodyA->onContactNotify(&entry); } if (bodyB && bodyB->getActor()/* && (bodyB->getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) */) { entry.bodyA = bodyA; entry.bodyB = bodyB; bodyB->getCollisions().Clear(); bodyB->getCollisions().PushBack(entry); bodyB->onContactNotify(&entry); } // result->getActor()->setContactReportFlags(NX_NOTIFY_ON_TOUCH); /* { entry.bodyA = body; body->getCollisions().Clear(); body->getCollisions().PushBack(entry); } if (pair.actors[1]) { pRigidBody *body = static_cast<pRigidBody*>(pair.actors[1]->userData); if (body) { entry.bodyB = body; body->getCollisions().Clear(); body->getCollisions().PushBack(entry); } }*/ /*getWorld()->getCollisions().PushBack(entry);*/ } } } } int pWorld::overlapOBBShapes(const VxBbox& worldBounds, CK3dEntity*shapeReference, pShapesType shapeType,CKGroup *shapes,int activeGroups/* =0xffffffff */, const pGroupsMask* groupsMask/* =NULL */, bool accurateCollision/* =false */) { int result=0; NxBox box; if (shapeReference) { NxShape *shape = getShapeByEntityID(shapeReference->GetID()); if (shape) { //shape->checkOverlapAABB() NxBoxShape*boxShape = static_cast<NxBoxShape*>(shape->isBox()); if (boxShape) { boxShape->getWorldOBB(box); } } }else{ box.center = getFrom(worldBounds.GetCenter()); box.extents = getFrom(worldBounds.GetSize()); } int total = 0; if (shapeType & ST_Dynamic ) { total+=getScene()->getNbDynamicShapes(); } if (shapeType & ST_Static) { total+=getScene()->getNbStaticShapes(); } NxShape** _shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); for (NxU32 i = 0; i < total; i++) _shapes[i] = NULL; NxGroupsMask mask; if (groupsMask) { mask.bits0 = groupsMask->bits0; mask.bits1 = groupsMask->bits1; mask.bits2 = groupsMask->bits2; mask.bits3 = groupsMask->bits3; }else{ mask.bits0 = 0; mask.bits1 = 0; mask.bits2 = 0; mask.bits3 = 0; } result = getScene()->overlapOBBShapes(box,(NxShapesType)shapeType,total,_shapes,NULL,activeGroups,&mask,accurateCollision); if (_shapes && shapes ) { for (int i = 0 ; i < result ; i++) { NxShape *s = _shapes[i]; if (s) { const char* name =s->getName(); pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(s->userData); if (sInfo->entID) { CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); if (obj) { shapes->AddObject((CKBeObject*)obj); } } } } } int op=2; return result; } int pWorld::overlapSphereShapes(const VxSphere& worldSphere,CK3dEntity*shapeReference,pShapesType shapeType,CKGroup*shapes,int activeGroups/* =0xffffffff */, const pGroupsMask* groupsMask/* =NULL */, bool accurateCollision/* =false */) { int result=0; NxSphere sphere; if (shapeReference) { NxShape *shape = getShapeByEntityID(shapeReference->GetID()); if (shape) { //shape->checkOverlapAABB() NxSphereShape *sphereShape = static_cast<NxSphereShape*>(shape->isSphere()); if (sphereShape) { sphere.radius = sphereShape->getRadius() + worldSphere.Radius(); //ori : VxVector ori = worldSphere.Center(); VxVector oriOut = ori; if (shapeReference) { shapeReference->Transform(&oriOut,&ori); } sphere.center = getFrom(oriOut); } } }else{ sphere.center = getFrom(worldSphere.Center()); sphere.radius = worldSphere.Radius(); } int total = 0; if (shapeType & ST_Dynamic ) { total+=getScene()->getNbDynamicShapes(); } if (shapeType & ST_Static) { total+=getScene()->getNbStaticShapes(); } NxShape** _shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); for (NxU32 i = 0; i < total; i++) _shapes[i] = NULL; NxGroupsMask mask; if (groupsMask) { mask.bits0 = groupsMask->bits0; mask.bits1 = groupsMask->bits1; mask.bits2 = groupsMask->bits2; mask.bits3 = groupsMask->bits3; }else{ mask.bits0 = 0; mask.bits1 = 0; mask.bits2 = 0; mask.bits3 = 0; } result = getScene()->overlapSphereShapes(sphere,(NxShapesType)shapeType,total,_shapes,NULL,activeGroups,&mask,accurateCollision); if (_shapes && shapes ) { for (int i = 0 ; i < result ; i++) { NxShape *s = _shapes[i]; if (s) { const char* name =s->getName(); pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(s->userData); if (sInfo->entID) { CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); if (obj) { shapes->AddObject((CKBeObject*)obj); } } } } } int op=2; return result; } int pWorld::raycastAllShapes(const VxRay& worldRay, pShapesType shapesType, int groups, float maxDist, pRaycastBit hintFlags, const pGroupsMask* groupsMask) { int result = 0; NxRay rayx; rayx.dir = getFrom(worldRay.m_Direction); rayx.orig = getFrom(worldRay.m_Origin); pRayCastReport &report = *getRaycastReport(); NxGroupsMask *mask = NULL; if (groupsMask) { mask = new NxGroupsMask(); mask->bits0 = groupsMask->bits0; mask->bits1 = groupsMask->bits1; mask->bits2 = groupsMask->bits2; mask->bits3 = groupsMask->bits3; } result = getScene()->raycastAllShapes(rayx,report,(NxShapesType)shapesType,groups,maxDist,hintFlags,mask); return result; } bool pWorld::raycastAnyBounds(const VxRay& worldRay, pShapesType shapesType, pGroupsMask *groupsMask/* =NULL */,int groups/* =0xffffffff */, float maxDist/* =NX_MAX_F32 */) { if (!getScene()) { return false; } NxRay _worldRay; _worldRay.dir = getFrom(worldRay.m_Direction); _worldRay.orig = getFrom(worldRay.m_Origin); NxShapesType _shapesType = (NxShapesType)shapesType; NxReal _maxDist=maxDist; NxGroupsMask *mask = NULL; if (groupsMask) { mask = new NxGroupsMask(); mask->bits0 = groupsMask->bits0; mask->bits1 = groupsMask->bits1; mask->bits2 = groupsMask->bits2; mask->bits3 = groupsMask->bits3; } bool result = getScene()->raycastAnyBounds(_worldRay,_shapesType,groups,_maxDist,mask); return result; } void pWorld::cIgnorePair(CK3dEntity *_a, CK3dEntity *_b, int ignore) { pRigidBody *a = GetPMan()->getBody(_a); pRigidBody *b = GetPMan()->getBody(_b); if (a&&b && a->getActor() && b->getActor() ) { if (getScene()) { getScene()->setActorPairFlags(*a->getActor(),*b->getActor(),ignore ? NX_IGNORE_PAIR : NX_NOTIFY_ALL ); } } } void pWorld::cSetGroupCollisionFlag(int g1 , int g2,int enabled) { if (getScene()) { if (g1 >=0 && g1 <= 31 && g2 >=0 && g2 <= 31) { if (enabled==0 || enabled ==1) { getScene()->setGroupCollisionFlag(g1,g2,enabled); } } } } void pTriggerReport::onTrigger(NxShape& triggerShape, NxShape& otherShape, NxTriggerFlag status) { NxActor *triggerActor = &triggerShape.getActor(); NxActor *otherActor = &otherShape.getActor(); pRigidBody *triggerBody = NULL; pRigidBody *otherBody = NULL; if (triggerActor) { triggerBody = static_cast<pRigidBody*>(triggerActor->userData); //triggerBody->getTriggers().Clear(); } if (otherActor) { otherBody = static_cast<pRigidBody*>(otherActor->userData); //otherBody->getTriggers().Clear(); } pTriggerEntry entry; entry.shapeA = &triggerShape; entry.shapeB = &otherShape; entry.triggerEvent = status; entry.triggerBodyB = triggerBody; entry.otherBodyB = otherBody; entry.triggerBody = triggerBody->GetVT3DObject(); pSubMeshInfo *sInfo = (pSubMeshInfo*)otherShape.userData; if (sInfo) { entry.otherObject = (CK3dEntity*)GetPMan()->GetContext()->GetObject(sInfo->entID); } pSubMeshInfo *sInfoOri = (pSubMeshInfo*)triggerShape.userData; if (sInfo) { entry.triggerShapeEnt = (CK3dEntity*)GetPMan()->GetContext()->GetObject(sInfoOri->entID); } if (triggerBody) { //triggerBody->getTriggers().PushBack(entry); triggerBody->onTrigger(&entry); GetPMan()->getTriggers().PushBack(entry); } } void pWorld::initUserReports() { contactReport = new pContactReport(); contactReport->setWorld(this); triggerReport = new pTriggerReport(); triggerReport->setWorld(this); raycastReport = new pRayCastReport(); raycastReport->setWorld(this); contactModify = new pContactModify(); contactModify->setWorld(this); //getScene()->raycastAllShapes() } bool pRayCastReport::onHit(const NxRaycastHit& hit) { CKBehavior *beh =(CKBehavior*)GetPMan()->m_Context->GetObject(mCurrentBehavior); if ( beh ) { pRayCastHits *carray = NULL; beh->GetLocalParameterValue(0,&carray); if (carray) { //carray->clear(); }else { carray = new pRayCastHits(); } //carray->push_back(const_cast<NxRaycastHit&>(&hit)); NxRaycastHit *_hit = new NxRaycastHit(); _hit->distance = hit.distance; _hit->faceID = hit.faceID; _hit->flags = hit.flags; _hit->internalFaceID = hit.internalFaceID; _hit->materialIndex = hit.materialIndex; _hit->shape = hit.shape; _hit->u = hit.u; _hit->v = hit.v; _hit->worldImpact = hit.worldImpact; _hit->worldNormal = hit.worldNormal; const char *name = hit.shape->getName(); carray->push_back(_hit); beh->SetLocalParameterValue(0,&carray); } return true; } void pWorld::setFilterOps(pFilterOp op0,pFilterOp op1, pFilterOp op2) { getScene()->setFilterOps((NxFilterOp)op0,(NxFilterOp)op1,(NxFilterOp)op2); } void pWorld::setFilterBool(bool flag){ getScene()->setFilterBool(flag);} void pWorld::setFilterConstant0(const pGroupsMask& mask) { NxGroupsMask _mask; _mask.bits0=mask.bits0; _mask.bits1=mask.bits1; _mask.bits2=mask.bits2; _mask.bits3=mask.bits3; getScene()->setFilterConstant0(_mask); } void pWorld::setFilterConstant1(const pGroupsMask& mask) { NxGroupsMask _mask; _mask.bits0=mask.bits0; _mask.bits1=mask.bits1; _mask.bits2=mask.bits2; _mask.bits3=mask.bits3; getScene()->setFilterConstant1(_mask); } bool pWorld::getFilterBool()const{ return getScene()->getFilterBool();} pGroupsMask pWorld::getFilterConstant0()const { NxGroupsMask mask = getScene()->getFilterConstant0(); pGroupsMask _mask; _mask.bits0=mask.bits0; _mask.bits1=mask.bits1; _mask.bits2=mask.bits2; _mask.bits3=mask.bits3; return _mask; } pGroupsMask pWorld::getFilterConstant1()const { NxGroupsMask mask = getScene()->getFilterConstant1(); pGroupsMask _mask; _mask.bits0=mask.bits0; _mask.bits1=mask.bits1; _mask.bits2=mask.bits2; _mask.bits3=mask.bits3; return _mask; } <file_sep>// -------------------------------------------------------------------------- // www.UnitedBusinessTechnologies.com // Copyright (c) 1998 - 2002 All Rights Reserved. // // Source in this file is released to the public under the following license: // -------------------------------------------------------------------------- // This toolkit may be used free of charge for any purpose including corporate // and academic use. For profit, and Non-Profit uses are permitted. // // This source code and any work derived from this source code must retain // this copyright at the top of each source file. // // UBT welcomes any suggestions, improvements or new platform ports. // email to: <EMAIL> // -------------------------------------------------------------------------- #include "pch.h" #include "GString.h" #include "GException.h" #include <string.h> // for: memcpy(), strlen(), strcmp(), memmove(), strchr(), // strstr(), strncmp() #include <ctype.h> // for: isdigit() #include <stdlib.h> // for: atof(), atoi(), atol(), abs(), and strtol() #include <stdio.h> // for: sprintf(), vsprintf(), FILE, fopen(), fwrite(), // fclose(), fseek(), fread() #include <stdarg.h> // for: va_start(), va_end */ // Global default format specifiers that affect all GStrings GString GString::g_FloatFmt("%.6g"); GString GString::g_DoubleFmt("%.6g"); GString GString::g_LongDoubleFmt("%.6Lg"); #ifndef _WIN32 #ifndef __int64 #define __int64 long long #endif #endif static void x64toa ( unsigned __int64 val, char *buf, unsigned radix, int is_neg ) { char *p; /* pointer to traverse string */ char *firstdig; /* pointer to first digit */ char temp; /* temp char */ unsigned digval; /* value of digit */ p = buf; if ( is_neg ) { *p++ = '-'; /* negative, so output '-' and negate */ val = (unsigned __int64)(-(__int64)val); } firstdig = p; /* save pointer to first digit */ do { digval = (unsigned) (val % radix); val /= radix; /* get next digit */ /* convert to ascii and store */ if (digval > 9) *p++ = (char) (digval - 10 + 'a'); /* a letter */ else *p++ = (char) (digval + '0'); /* a digit */ } while (val > 0); /* We now have the digit of the number in the buffer, but in reverse order. Thus we reverse them now. */ *p-- = '\0'; /* terminate string; p points to last digit */ do { temp = *p; *p = *firstdig; *firstdig = temp; /* swap *p and *firstdig */ --p; ++firstdig; /* advance to next two digits */ } while (firstdig < p); /* repeat until halfway */ } // long long to ascii char * lltoa ( __int64 val,char *buf,int radix) { x64toa((unsigned __int64)val, buf, radix, (radix == 10 && val < 0)); return buf; } #define CommonConstruct(nInitialSize) \ _str = 0; \ _len = 0; \ _strIsOnHeap = 0; \ _max = nInitialSize; \ if (nInitialSize == 256) \ _str = _initialbuf; \ else \ { \ _initialbuf[0] = 0; \ _str = new char[nInitialSize]; \ _strIsOnHeap = 1; \ } \ if (!_str) \ throw GenericException("String", 0); \ _str[_len] = 0; void GString::AppendEscapeXMLReserved(const char *Src, int nLen/* = -1*/) { const unsigned char *src = (const unsigned char *)Src; while (*src && (nLen != 0)) { if (nLen != -1) // -1 means to append until a null in src nLen--; switch (*src) { case '<' : case '>' : case '&' : case '"' : case '\'' : this->write("&#",2); (*this) += (unsigned int)(unsigned char)*src; (*this) += ';'; break; default : // IE can't deal with special chars(йвезкли....) so escape them too if ((*src > 127) || (*src < 32)) { this->write("&#",2); (*this) += (unsigned int)(unsigned char)*src; (*this) += ';'; break; } else // most cases, append normal char to this GString { // inline operator += code if (_len >= _max) resize(); _str[_len] = *src; _len++; if (_len >= _max) resize(); _str[_len] = 0; } break; } src++; } } void GString::AppendXMLTabs( int nTabs ) { static const char* TABS = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; const int MAX_TABS = 80; if (_len) #ifdef _WIN32 (*this) << "\r\n"; #else (*this) << "\n"; #endif write( TABS, (nTabs > MAX_TABS) ? MAX_TABS : nTabs ); } void GString::EscapeXMLReserved() { GString str_xml( Length() + 1024 ); const unsigned char *src = (const unsigned char *)(const char *)(*this); while (*src) { switch (*src) { case '<' : case '>' : case '&' : case '"' : case '\'' : str_xml << "&#" << (unsigned int)*src << ';'; break; default : if ((*src > 127) || (*src < 32)) { str_xml << "&#" << (unsigned int)((unsigned char)*src) << ';'; } else { str_xml << *src; } break; } src++; } (*this) = str_xml; } void GString::resize() { // double the size of the buffer _max <<= 1; char *nstr = new char[_max]; // not enough memory for resize if (!nstr) throw GenericException("String", 0); nstr[0] = 0; if (_str) { memcpy(nstr, _str, _len); if (_strIsOnHeap) delete [] _str; } _str = nstr; _strIsOnHeap = 1; _initialbuf[0] = 0; } // constructs an empty string GString::GString(long nInitialSize) { CommonConstruct(nInitialSize); } // constructs a copy of the source string GString::GString(const GString &src ) { long l = (src._len > 256) ? src._len + 256 : 256; CommonConstruct( l ); _len = ___min(_max, src._len); memcpy(_str, src._str, _len); _str[_len] = 0; } GString::GString(const GString &src, int nCnt) { long l = (src._len > 256) ? src._len + 256 : 256; CommonConstruct(l); _len = ___min(_max, ___min(src._len, nCnt)); memcpy(_str, src._str, _len); _str[_len] = 0; } // constructs a copy of the character string GString::GString(const char *src) { long srcLen = (src) ? strlen(src) : 256; long nInitialSize = (srcLen > 256) ? srcLen + 256 : 256; CommonConstruct(nInitialSize); while (src && *src) { _str[_len] = *src; _len++; src++; if (_len >= _max) resize(); } if (_len >= _max) resize(); _str[_len] = 0; } GString::GString(const char *src, int nCnt) { long nInitialSize = (nCnt > 256) ? nCnt + 256 : 256; CommonConstruct(nInitialSize); _len = 0; if (src) { int i; _len = ___min(_max - 1, nCnt); for (i = 0; i < _len && src[i]; i++) _str[i] = src[i]; _len = i; } _str[_len] = 0; } // constructs a string with ch repeated nCnt times GString::GString(char ch, short nCnt) { long nInitialSize = (nCnt > 256) ? nCnt + 256 : 256; CommonConstruct(nInitialSize); _len = ___min(_max - 1, nCnt); int i; for (i = 0; i < _len; i++) _str[i] = ch; _len = i; _str[_len] = 0; } GString::~GString() { if (_strIsOnHeap) delete [] _str; } /* .h declaration: GString & operator=(const strstreambuf &); GString & GString::operator=(const strstreambuf &buf) { _max = ((strstreambuf &)buf).seekoff(0, ios::cur, ios::in | ios::out) + 1; char *nstr = new char[_max]; // not enough memory for resize if (!nstr) throw GenericException("String", 0); nstr[0] = 0; if (_str) { if (_strIsOnHeap) delete [] _str; } _str = nstr; _strIsOnHeap = 1; _initialbuf[0] = 0; _len = _max - 1; strncpy(_str, ((strstreambuf &)buf).str(), _len); _str[_len] = 0; ((strstreambuf &)buf).freeze(0); return *this; }*/ GString & GString::operator=(char _p) { if (!_max) { _max = 2; resize(); } _len = 0; _str[_len] = _p; _len++; _str[_len] = 0; return *this; } GString & GString::operator=(__int64 _p) { char szBuffer[256]; // sprintf(szBuffer, "%I64d", _p); lltoa ( _p,szBuffer,10); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(const char * _p) { _len = 0; while (_p && *_p) { if (_len >= _max) resize(); _str[_len] = *_p; _p++; _len++; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(const signed char * _p) { *this = (const char *)_p; return *this; } GString & GString::operator=(unsigned char _p) { *this = (char)_p; return *this; } GString & GString::operator=(signed char _p) { *this = (char)_p; return *this; } GString & GString::operator=(short _p) { char szBuffer[25]; sprintf(szBuffer, "%hi", _p); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(unsigned short _p) { char szBuffer[25]; sprintf(szBuffer, "%hu", _p); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(int _p) { char szBuffer[25]; sprintf(szBuffer, "%li", _p); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(unsigned int _p) { char szBuffer[25]; sprintf(szBuffer, "%lu", _p); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(long _p) { char szBuffer[25]; sprintf(szBuffer, "%li", _p); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(unsigned long _p) { char szBuffer[25]; sprintf(szBuffer, "%lu", _p); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(float _p) { char szBuffer[50]; sprintf(szBuffer, g_FloatFmt._str, _p); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(double _p) { char szBuffer[50]; sprintf(szBuffer, "%.6g", _p); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(long double _p) { char szBuffer[50]; sprintf(szBuffer, "%.6Lg", _p); int nLen = strlen(szBuffer); for (_len = 0; _len < nLen; _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator=(const GString & _p) { for (_len = 0; _len < _p._len; _len++) { if (_len >= _max) resize(); _str[_len] = _p._str[_len]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(__int64 _p) { char szBuffer[25]; // sprintf(szBuffer, "%I64d", _p); lltoa ( _p,szBuffer,10); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(const signed char * _p) { while (_p && *_p) { if (_len >= _max) resize(); _str[_len] = *_p; _p++; _len++; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(const char * _p) { while (_p && *_p) { if (_len >= _max) resize(); _str[_len] = *_p; _p++; _len++; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } void GString::write(const char *p,int nSize) { while (_len + nSize + 1 >= _max) resize(); memcpy(&_str[_len],p,nSize); _len += nSize; _str[_len] = 0; } GString & GString::operator+=(char _p) { if (_p) { if (_len >= _max) resize(); _str[_len] = _p; _len++; if (_len >= _max) resize(); _str[_len] = 0; } return *this; } GString & GString::operator+=(unsigned char _p) { if (_p) { if (_len >= _max) resize(); _str[_len] = _p; _len++; if (_len >= _max) resize(); _str[_len] = 0; } return *this; } GString & GString::operator+=(signed char _p) { if (_p) { if (_len >= _max) resize(); _str[_len] = _p; _len++; if (_len >= _max) resize(); _str[_len] = 0; } return *this; } GString & GString::operator+=(short _p) { char szBuffer[25]; sprintf(szBuffer, "%hi", _p); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(unsigned short _p) { char szBuffer[25]; sprintf(szBuffer, "%hu", _p); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(int _p) { char szBuffer[25]; sprintf(szBuffer, "%li", _p); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(unsigned int _p) { char szBuffer[25]; sprintf(szBuffer, "%lu", _p); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(long _p) { char szBuffer[25]; sprintf(szBuffer, "%ld", _p); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(unsigned long _p) { char szBuffer[25]; sprintf(szBuffer, "%lu", _p); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(float _p) { char szBuffer[50]; sprintf(szBuffer, g_FloatFmt._str, _p); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(double _p) { char szBuffer[50]; sprintf(szBuffer, "%.6g", _p); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(long double _p) { char szBuffer[50]; sprintf(szBuffer, "%.6Lg", _p); int nLen = strlen(szBuffer); for (int i = 0; i < nLen; i++, _len++) { if (_len >= _max) resize(); _str[_len] = szBuffer[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator+=(const GString & _p) { while (_len + _p._len + 1 >= _max) resize(); memcpy(&_str[_len],_p._str,_p._len); _len += _p._len; _str[_len] = 0; return *this; /* for (int i = 0; i < _p._len; i++, _len++) { if (_len >= _max) resize(); _str[_len] = _p._str[i]; } if (_len >= _max) resize(); _str[_len] = 0; return *this; */ } GString & GString::operator<<(__int64 _p) { return *this += _p; } GString & GString::operator<<(const char * _p) { while (_p && *_p) { if (_len >= _max) resize(); _str[_len] = *_p; _p++; _len++; } if (_len >= _max) resize(); _str[_len] = 0; return *this; } GString & GString::operator<<(const signed char * _p) { return *this += _p; } GString & GString::operator<<(char _p) { if (_p) { if (_len >= _max) resize(); _str[_len] = _p; _len++; if (_len >= _max) resize(); _str[_len] = 0; } return *this; } GString & GString::operator<<(unsigned char _p) { return *this += _p; } GString & GString::operator<<(signed char _p) { return *this += _p; } GString & GString::operator<<(short _p) { return *this += _p; } GString & GString::operator<<(unsigned short _p) { return *this += _p; } GString & GString::operator<<(int _p) { return *this += _p; } GString & GString::operator<<(unsigned int _p) { return *this += _p; } GString & GString::operator<<(long _p) { return *this += _p; } GString & GString::operator<<(unsigned long _p) { return *this += _p; } GString & GString::operator<<(float _p) { return *this += _p; } GString & GString::operator<<(double _p) { return *this += _p; } GString & GString::operator<<(long double _p) { return *this += _p; } GString & GString::operator<<(const GString & _p) { // return *this += _p; while (_len + _p._len + 1 >= _max) resize(); memcpy(&_str[_len],_p._str,_p._len); _len += _p._len; _str[_len] = 0; return *this; } GString operator+(GString &_p1, GString &_p2) { GString strRet(_p1._len + _p2._len + 1); int i; for (i = 0; i < _p1._len; strRet._len++, i++) strRet._str[strRet._len] = _p1._str[i]; for (i = 0; i < _p2._len; strRet._len++, i++) strRet._str[strRet._len] = _p2._str[i]; strRet._str[strRet._len] = 0; return strRet; } GString operator+(GString &_p1, const char *_p2) { GString strRet; for (int i = 0; i < _p1._len; strRet._len++, i++) { if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = _p1._str[i]; } while (_p2 && *_p2) { if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = *_p2; _p2++; strRet._len++; } if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = 0; return strRet; } GString operator+(const char *_p1, GString &_p2) { GString strRet; while (_p1 && *_p1) { if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = *_p1; _p1++; strRet._len++; } for (int i = 0; i < _p2._len; strRet._len++, i++) { if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = _p2._str[i]; } if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = 0; return strRet; } GString operator+(GString &_p1, const signed char *_p2) { GString strRet; for (int i = 0; i < _p1._len; strRet._len++, i++) { if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = _p1._str[i]; } while (_p2 && *_p2) { if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = *_p2; _p2++; strRet._len++; } if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = 0; return strRet; } GString operator+(const signed char *_p1, GString &_p2) { GString strRet; while (_p1 && *_p1) { if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = *_p1; _p1++; strRet._len++; } for (int i = 0; i < _p2._len; strRet._len++, i++) { if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = _p2._str[i]; } if (strRet._len >= strRet._max) strRet.resize(); strRet._str[strRet._len] = 0; return strRet; } GString operator+(GString &_p1, char _p2) { GString strRet(_p1._len + 2); for (int i = 0; i < _p1._len; strRet._len++, i++) strRet._str[strRet._len] = _p1._str[i]; strRet._str[strRet._len] = _p2; strRet._len++; strRet._str[strRet._len] = 0; return strRet; } GString operator+(char _p1, GString &_p2) { GString strRet(_p2._len + 2); strRet._str[strRet._len] = _p1; strRet._len++; for (int i = 0; i < _p2._len; strRet._len++, i++) strRet._str[strRet._len] = _p2._str[i]; strRet._str[strRet._len] = 0; return strRet; } GString operator+(GString &_p1, unsigned char _p2) { GString strRet(_p1._len + 2); for (int i = 0; i < _p1._len; strRet._len++, i++) strRet._str[strRet._len] = _p1._str[i]; strRet._str[strRet._len] = _p2; strRet._len++; strRet._str[strRet._len] = 0; return strRet; } GString operator+(unsigned char _p1, GString &_p2) { GString strRet(_p2._len + 2); strRet._str[strRet._len] = _p1; strRet._len++; for (int i = 0; i < _p2._len; strRet._len++, i++) strRet._str[strRet._len] = _p2._str[i]; strRet._str[strRet._len] = 0; return strRet; } GString operator+(GString &_p1, signed char _p2) { GString strRet(_p1._len + 2); for (int i = 0; i < _p1._len; strRet._len++, i++) strRet._str[strRet._len] = _p1._str[i]; strRet._str[strRet._len] = _p2; strRet._len++; strRet._str[strRet._len] = 0; return strRet; } GString operator+(signed char _p1, GString &_p2) { GString strRet(_p2._len + 2); strRet._str[strRet._len] = _p1; strRet._len++; for (int i = 0; i < _p2._len; strRet._len++, i++) strRet._str[strRet._len] = _p2._str[i]; strRet._str[strRet._len] = 0; return strRet; } //ostream& operator<<(ostream &os, GString &s) //{ // os << s._str; // return os; //} int GString::operator > (const GString &s) const { return strcmp(_str, s._str) > 0; } int GString::operator >= (const GString &s) const { return strcmp(_str, s._str) >= 0; } int GString::operator == (const GString &s) const { return strcmp(_str, s._str) == 0; } int GString::operator < (const GString &s) const { return strcmp(_str, s._str) < 0; } int GString::operator <= (const GString &s) const { return strcmp(_str, s._str) <= 0; } int GString::operator != (const GString &s) const { return strcmp(_str, s._str) != 0; } int GString::operator > (const char *s) const { return strcmp(_str, s) > 0; } int GString::operator >= (const char *s) const { return strcmp(_str, s) >= 0; } int GString::operator == (const char *s) const { return strcmp(_str, s) == 0; } int GString::operator < (const char *s) const { return strcmp(_str, s) < 0; } int GString::operator <= (const char *s) const { return strcmp(_str, s) <= 0; } int GString::operator != (const char *s) const { return strcmp(_str, s) != 0; } int GString::Compare(const char *s) const { return strcmp(_str, s); } int GString::Compare(GString &s) const { return strcmp(_str, s._str); } int GString::CompareNoCase(const char *s) const { int i = 0; // start at the beginning // loop through the two strings comparing case insensitively while ((toupper(_str[i]) == toupper(s[i])) && // the two strings are equal (_str[i] != '\0')) // the first hasn't ended i++; // the difference between the characters that ended it is // indicative of the direction of the comparison. if this // is negative, the first was before the second. if it is // positive, the first was after the second. if it is zero, // the two are equal (and the != '\0' condition stopped the // loop such that the two were of equal length). return (short)toupper(_str[i]) - (short)toupper(s[i]); } int GString::CompareNoCase(const GString &s) const { int i = 0; // start at the beginning // loop through the two strings comparing case insensitively while ((toupper(_str[i]) == toupper(s._str[i])) && // the two strings are equal (_str[i] != '\0')) // the first hasn't ended i++; // the difference between the characters that ended it is // indicative of the direction of the comparison. if this // is negative, the first was before the second. if it is // positive, the first was after the second. if it is zero, // the two are equal (and the != '\0' condition stopped the // loop such that the two were of equal length). return (short)toupper(_str[i]) - (short)toupper(s._str[i]); } char& GString::operator[](int nIdx) { // check for subscript out of range if (nIdx > _len) throw GenericException("String", 1); return _str[nIdx]; } char GString::GetAt(int nIdx) const { // check for subscript out of range if (nIdx > _len) throw GenericException("String", 1); return _str[nIdx]; } void GString::SetAt(int nIdx, char ch) { // check for subscript out of range if (nIdx >= _len) throw GenericException("String", 1); _str[nIdx] = ch; } void GString::PadLeft(int nCnt, char ch /* = ' ' */) { if (nCnt > _len) Prepend(nCnt - _len, ch); } void GString::Prepend(int nCnt, char ch /* = ' ' */) { while (nCnt + _len + 1 >= _max) resize(); memmove(&_str[nCnt], _str, _len); _len += nCnt; for (int i = 0; i < nCnt; i++) _str[i] = ch; _str[_len] = 0; } void GString::TrimLeft(char ch /* = ' ' */, short nCnt /* = -1 */) { int i = 0; while ((i < _len) && (_str[i] == ch) && (nCnt != 0)) { i++; nCnt--; } if (i != 0) { _len -= i; memmove(_str, &_str[i], _len + 1); } } #define isWS(ch) ( ch == 0x20 || ch == 0x09 || ch == 0x0D || ch == 0x0A) void GString::TrimLeftWS() { int i = 0; while ((i < _len) && (isWS(_str[i]))) i++; if (i != 0) { _len -= i; memmove(_str, &_str[i], _len + 1); } } void GString::PadRight(int nCnt, char ch /* = ' ' */) { if (nCnt > _len) Append(nCnt - _len, ch); } void GString::Append(int nCnt, char ch /* = ' ' */) { for (int i = 0; i < nCnt; i++, _len++) { if (_len >= _max) resize(); _str[_len] = ch; } if (_len >= _max) resize(); _str[_len] = 0; } void GString::TrimRightBytes(short nCnt) { if (_len >= nCnt) _len -= nCnt; _str[_len] = 0; } void GString::TrimRight(char ch /* = ' ' */, short nCnt /* = -1 */) { while ((_len) && (_str[_len - 1] == ch) && (nCnt != 0)) { _len--; nCnt--; } _str[_len] = 0; } GString GString::Left (int nCnt) const { if (nCnt > _len) nCnt = _len; return GString(_str, nCnt); } GString GString::Mid (int nFirst) const { if (nFirst > _len) nFirst = _len; return GString(&_str[nFirst]); } GString GString::Mid (int nFirst, int nCnt) const { if (nFirst > _len) nFirst = _len; return GString(&_str[nFirst], nCnt); } GString GString::Right(int nCnt) const { if (nCnt > _len) nCnt = _len + 1; int nFirst = _len - nCnt; return GString(&_str[nFirst]); } void GString::TrimRightWS() { while ((_len) && (isWS(_str[_len - 1]))) _len--; _str[_len] = 0; } void GString::MakeUpper() { for (int i = 0; i < _len; i++) _str[i] = toupper(_str[i]); } void GString::MakeLower() { for (int i = 0; i < _len; i++) _str[i] = tolower(_str[i]); } void GString::MakeReverse() { for (int a = 0, b = _len - 1; a < b; a++, b--) { char c = _str[b]; _str[b] = _str[a]; _str[a] = c; } } char * stristr(const char * str1, const char * str2) { char *cp = (char *) str1; char *s1, *s2; if ( !*str2 ) return((char *)str1); while (*cp) { s1 = cp; s2 = (char *) str2; while ( *s1 && *s2 && !(tolower(*s1)-tolower(*s2)) ) s1++, s2++; if (!*s2) return(cp); cp++; } return 0; } int GString::FindSubStringCaseInsensitive( const char * lpszSub, int nStart/* = 0*/ ) const { char *p = stristr(&_str[nStart], lpszSub); if (p) return p - _str; return -1; } int GString::Find( char ch ) const { return Find(ch, 0); } int GString::Find( const char * lpszSub ) const { return Find(lpszSub, 0); } int GString::Find( char ch, int nStart ) const { if (nStart >= _len) return -1; // find first single character const char *lpsz = strchr(_str + nStart, (int)ch); // return -1 if not found and index otherwise return (lpsz == NULL) ? -1 : (int)(lpsz - _str); } int GString::Find( const char * lpszSub, int nStart ) const { if (nStart > _len) return -1; // find first matching substring const char *lpsz = strstr(_str + nStart, lpszSub); // return -1 for not found, distance from beginning otherwise return (lpsz == NULL) ? -1 : (int)(lpsz - _str); } void GString::Insert( int nIndex, char ch ) { // subscript out of range if (nIndex > _len) throw GenericException("String", 1); if (_len + 2 >= _max) resize(); _len++; memmove(&_str[nIndex + 1], &_str[nIndex], _len - nIndex); _str[nIndex] = ch; _str[_len] = 0; } void GString::Insert( int nIndex, const char * pstr ) { if (!pstr) return; // subscript out of range if (nIndex > _len) throw GenericException("String", 1); int nCnt = strlen(pstr); while (_len + nCnt + 1 >= _max) resize(); _len += nCnt; memmove(&_str[nIndex + nCnt], &_str[nIndex], _len - nIndex); while (*pstr) { _str[nIndex] = *pstr; pstr++; nIndex++; } _str[_len] = 0; } void GString::MergeMask(const char *szSrc, const char *szMask) { Empty(); if ((szSrc != 0) && (*szSrc != 0)) { while ((*szSrc != 0) || (*szMask != 0)) { switch (*szMask) { // copy a single character from the case '_' : if (*szSrc) { *this += *szSrc; szSrc++; } szMask++; break; // copy the remaining characters from szSrc case '*' : *this += szSrc; while (*szSrc) szSrc++; szMask++; break; // all other characters are mask chars // with the exception of '\' which is // used to escape '_', '*' and '\' default : if (*szMask != 0) { if (*szMask == '\\') // skip the escape character szMask++; if (*szMask != 0) { *this += *szMask; szMask++; } } break; } // throw away the remaining characters in the source string if (*szMask == 0) break; } } } bool IsNaN(const char *szN, char decimal_separator, char grouping_separator, char minus_sign) { bool bRet = false; bool bDot = false; bool bNeg = false; int i = 0; while ((*szN) && (!bRet)) { bRet = !(((*szN >= '0') && (*szN <= '9')) || *szN == grouping_separator || *szN == decimal_separator || *szN == minus_sign); if (*szN == decimal_separator) { if (bDot) bRet = true; // NaN bDot = true; } if (*szN == minus_sign) { if (((i) && szN[1]) || bNeg) bRet = true; // NaN bNeg = true; } szN++; i++; } return bRet; } short CountOf(const char *szN, char zero_digit) { int nRet = 0; while (*szN) { if (*szN == zero_digit) nRet++; szN++; } return nRet; } long round(const char *value) { long dres = (long)atof(value); double drem = atof(value); drem -= dres; short nAdd = 1; if (drem < 0) drem *= -1, nAdd *= -1; if (drem >= .5) dres += nAdd; return dres; } void GString::FormatNumber(const char *szFormat, char decimal_separator, char grouping_separator, char minus_sign, const char *NaN, char zero_digit, char digit, char pattern_separator, char percent, char permille) { if (szFormat && *szFormat) { // make sure that the string is a number {0..9, '.', '-'} // if the string contains a character not in the number // subset then set the value of the string to NaN. const char *szValue = _str; if (IsNaN(szValue, '.', ',', '-')) *this = NaN; else { // it's a number, get the whole part and the fraction part int nIdx = Find('.'); GString strWhole; strWhole = (nIdx == -1) ? _str : (const char *)Left(nIdx); GString strFraction('0', (short)1); nIdx = Find('.') + 1; if (nIdx > 0) strFraction = Mid(nIdx); bool bIsNeg = (Find(minus_sign) != -1); long nWhole = abs(atol((const char *)strWhole)); long nFract = abs(atol((const char *)strFraction)); // check for % and ? if (percent == szFormat[0]) { double d = atof(_str); d *= 100; GString strTemp; strTemp.Format("%f", d); nIdx = strTemp.Find('.'); strFraction = (nIdx == -1) ? strTemp._str : (const char *)strTemp.Left(nIdx); nWhole = atol((const char *)strFraction); nFract = 0; } if (permille == szFormat[0]) { double d = atof(_str); d *= 1000; GString strTemp; strTemp.Format("%f", d); nIdx = strTemp.Find('.'); strFraction = (nIdx == -1) ? strTemp._str : (const char *)strTemp.Left(nIdx); nWhole = atol((const char *)strFraction); nFract = 0; } // if the number is negative, get the negative pattern out of the format. // if a negative pattern doesn't exist, the minus_sign will be prepended // to the positive pattern. GString strFormat(szFormat); nIdx = strFormat.Find(pattern_separator); if (bIsNeg) { if (nIdx != -1) strFormat = strFormat.Mid(nIdx + 1); else strFormat.Format("%c%s", minus_sign, (const char *)strFormat); } else { if (nIdx != -1) strFormat = strFormat.Left(nIdx); } GString strFormatWhole(strFormat); GString strFormatDecimal('#', (short)1); // determine the number of digits per group int nGroup = 0; nIdx = strFormat.Find(','); if (nIdx != -1) { nIdx++; int nNext = strFormat.Find(',', nIdx); if (nNext == -1) nNext = strFormat.Find('.', nIdx); if (nNext == -1) nNext = strFormat.Length(); nGroup = (nNext - nIdx); } // determine the number of decimals to display int nDecimals = 0; nIdx = strFormat.Find('.'); if ((nIdx != -1) && (percent != szFormat[0]) && (permille != szFormat[0])) { if (nGroup) strFormatWhole = strFormat.Mid(nIdx - nGroup, nGroup); else strFormatWhole = strFormat.Left(nIdx); nIdx++; strFormatDecimal = strFormat.Mid(nIdx); nDecimals = (strFormat.Length() - nIdx); } // Format the whole part of the number int nCount = CountOf((const char *)strFormatWhole, zero_digit); strWhole.Format("%0ld", nWhole); if (strWhole.Length() < nCount) { GString temp(zero_digit, (short)(nCount - (short)strWhole.Length())); strWhole.Format("%s%s", (const char *)temp, (const char *)strWhole); } Empty(); // add all prefix characters nIdx = 0; const char *szP = (const char *)strFormat; while (*szP) { if (*szP == digit || *szP == zero_digit || *szP == decimal_separator || *szP == grouping_separator || *szP == percent || *szP == permille) break; szP++; nIdx++; } strFormat = strFormat.Left(nIdx); strFormat.MakeReverse(); int i, j; for (i = 0, j = strWhole.Length() - 1; j >= 0; j--, i++) { if ((nGroup) && (i == nGroup)) { *this += grouping_separator; i = 0; } *this += strWhole[j]; } *this += strFormat; MakeReverse(); if (nDecimals) { *this += decimal_separator; strFraction.Format("%ld", nFract); const char *szF1 = (const char *)strFormatDecimal; const char *szF2 = (const char *)strFraction; i = 0; while (*szF1) { if (*szF2) *this += *szF2; else if (*szF1 == zero_digit) *this += zero_digit; else if (*szF1 != digit) // add all sufix characters *this += *szF1; if (*szF2) szF2++; if (*szF1) szF1++; } } if (percent == szFormat[0]) *this += percent; if (permille == szFormat[0]) *this += permille; } } } #define FORCE_ANSI 0x10000 #define FORCE_UNICODE 0x20000 #define FORCE_INT64 0x40000 void GString::FormatV(const char *lpszFormat, va_list argList) { va_list argListSave = argList; // make a guess at the maximum length of the resulting string int nMaxLen = 0; for (const char *lpsz = lpszFormat; *lpsz != '\0'; lpsz++) { // handle '%' character, but watch out for '%%' if (*lpsz != '%' || *(lpsz = lpsz + 1) == '%') { nMaxLen += strlen(lpsz); continue; } int nItemLen = 0; // handle '%' character with format int nWidth = 0; for (; *lpsz != '\0'; lpsz++) { // check for valid flags if (*lpsz == '#') nMaxLen += 2; // for '0x' else if (*lpsz == '*') nWidth = va_arg(argList, int); else if (*lpsz == '-' || *lpsz == '+' || *lpsz == '0' || *lpsz == ' ') ; else // hit non-flag character break; } // get width and skip it if (nWidth == 0) { // width indicated by nWidth = atoi(lpsz); for (; *lpsz != '\0' && isdigit(*lpsz); lpsz++) ; } (nWidth >= 0); int nPrecision = 0; if (*lpsz == '.') { // skip past '.' separator (width.precision) lpsz++; // get precision and skip it if (*lpsz == '*') { nPrecision = va_arg(argList, int); lpsz++; } else { nPrecision = atoi(lpsz); for (; *lpsz != '\0' && isdigit(*lpsz); lpsz++) ; } (nPrecision >= 0); } // should be on type modifier or specifier int nModifier = 0; if (strncmp(lpsz, "I64", 3) == 0) { lpsz += 3; nModifier = FORCE_INT64; } else { switch (*lpsz) { // modifiers that affect size case 'h': nModifier = FORCE_ANSI; lpsz++; break; case 'l': nModifier = FORCE_UNICODE; lpsz++; break; // modifiers that do not affect size case 'F': case 'N': case 'L': lpsz++; break; } } // now should be on specifier switch (*lpsz | nModifier) { // single characters case 'c': case 'C': nItemLen = 2; #ifdef WIN32 va_arg(argList, char); #else // gcc says: "`char' is promoted to `int' when passed through ... // so we pass 'int' not 'char' to va_arg" va_arg(argList, int); #endif break; // strings case 's': { const char *pstrNextArg = va_arg(argList, const char *); if (pstrNextArg == NULL) nItemLen = 6; // "(null)" else { nItemLen = strlen(pstrNextArg); nItemLen = ___max(1, nItemLen); } } break; case 's'|FORCE_ANSI: case 'S'|FORCE_ANSI: { const char * pstrNextArg = va_arg(argList, const char *); if (pstrNextArg == NULL) nItemLen = 6; // "(null)" else { nItemLen = strlen(pstrNextArg); nItemLen = ___max(1, nItemLen); } } break; } // adjust nItemLen for strings if (nItemLen != 0) { if (nPrecision != 0) nItemLen = ___min(nItemLen, nPrecision); nItemLen = ___max(nItemLen, nWidth); } else { switch (*lpsz) { // integers case 'd': case 'i': case 'u': case 'x': case 'X': case 'o': if (nModifier & FORCE_INT64) va_arg(argList, __int64); else va_arg(argList, int); nItemLen = 32; nItemLen = ___max(nItemLen, nWidth+nPrecision); break; case 'e': case 'g': case 'G': va_arg(argList, double); nItemLen = 128; nItemLen = ___max(nItemLen, nWidth+nPrecision); break; case 'f': { double f; // 312 == strlen("-1+(309 zeroes).") // 309 zeroes == max precision of a double // 6 == adjustment in case precision is not specified, // which means that the precision defaults to 6 char *pszTemp = new char[___max(nWidth, 312+nPrecision+6)]; f = va_arg(argList, double); sprintf( pszTemp, "%*.*f", nWidth, nPrecision+6, f ); nItemLen = strlen(pszTemp); delete [] pszTemp; } break; case 'p': va_arg(argList, void*); nItemLen = 32; nItemLen = ___max(nItemLen, nWidth+nPrecision); break; // no output case 'n': va_arg(argList, int*); break; } } // adjust nMaxLen for output nItemLen nMaxLen += nItemLen; } if (nMaxLen + 1 > _max) { if (_strIsOnHeap) delete _str; _max = nMaxLen + 1; _str = new char[_max]; _strIsOnHeap = 1; _initialbuf[0] = 0; } _len = vsprintf(_str, lpszFormat, argListSave); va_end(argListSave); if (_len < 0) { _len = 0; _str[_len] = 0; } } // Load an error from the active ErrorProfile() owned by GException.cpp void GString::LoadResource(const char* szSystem, int error, ...) { int nerror = error; GProfile &ErrorProfile = GetErrorProfile(); int nsubSystem = atoi(ErrorProfile.GetString(szSystem, "SubSystem")); GString strKey; strKey.Format("%ld", error); strKey = ErrorProfile.GetString(szSystem, (const char *)strKey); va_list argList; va_start(argList, error); FormatV((const char *)strKey, argList); va_end(argList); } void GString::Format(const char *lpszFormat, ...) { va_list argList; va_start(argList, lpszFormat); FormatV(lpszFormat, argList); va_end(argList); } int GString::ToFileAppend(const char* pzFileName, bool bThrowOnFail /*= 1*/) { FILE *fp = fopen(pzFileName,"a"); if (fp) { fwrite(_str,1,_len,fp); fclose(fp); } else { // the file could not be opened for writing if (bThrowOnFail) throw GenericException("String", 3, pzFileName); // fail return 0; } // success return 1; } int GString::ToFile(const char* pzFileName, bool bThrowOnFail/* = 1*/) { FILE *fp = fopen(pzFileName,"wb"); if (fp) { fwrite(_str,1,_len,fp); fclose(fp); } else { // the file could not be opened for writing if (bThrowOnFail) throw GenericException("String", 3, pzFileName); // fail return 0; } // success return 1; } int GString::FromFile(const char* pzFileName, bool bThrowOnFail/* = 1*/) { FILE *fp = fopen(pzFileName,"rb"); if (fp) { // get the size of the file fseek(fp,0,SEEK_END); long lBytes = ftell(fp); fseek(fp,0,SEEK_SET); if (_strIsOnHeap) delete [] _str; // pre-alloc the GString _str = new char[lBytes + 1]; _strIsOnHeap = 1; _initialbuf[0] = 0; int n = fread(_str,sizeof(char),lBytes,fp); _len = lBytes; _str[_len] = 0; fclose(fp); } else { // the file could not be opened. if (bThrowOnFail) throw GenericException("String", 2, pzFileName); // fail return 0; } // success return 1; } /* int GString::GStringFromFile(GString &strDest, const char* pzFileName, int nMode) { fstream fs(pzFileName, nMode); if (fs.good()) { fs.seekg( 0, ios::end ); long lFileBytes = fs.tellg(); fs.seekg( 0, ios::beg ); if (strDest._strIsOnHeap) delete [] strDest._str; strDest._str = new char[lFileBytes + 1]; strDest._strIsOnHeap = 1; strDest._initialbuf[0] = 0; fs.read(strDest._str, lFileBytes); strDest._len = lFileBytes; strDest._str[strDest._len] = 0; } else { return 0; // Failed to open input file } return 1; // success } int GString::GStringFromFile(ostream &strDest, const char* pzFileName, int nMode) { fstream fs(pzFileName, nMode); if (fs.good()) { fs.seekg( 0, ios::end ); long lFileBytes = fs.tellg(); fs.seekg( 0, ios::beg ); char *buf = new char[lFileBytes]; fs.read(buf,lFileBytes); if (strDest.tellp()) strDest.seekp(strDest.tellp() - 1); strDest.write(buf,lFileBytes); delete buf; strDest << ends; } else { return 0; // Failed to open input file } return 1; // success } */ void GString::ReplaceCaseInsensitive( const char * szWhat, const char *szRep, int nStart/* = 0*/ ) { if ((!szWhat) || (!szRep)) return; int nPos = FindSubStringCaseInsensitive(szWhat, nStart); int nLen = strlen(szRep); while (nPos != -1) { Remove(nPos, strlen(szWhat)); if (nLen) Insert(nPos, szRep); nPos += nLen; nPos = FindSubStringCaseInsensitive(szWhat, nPos); } } void GString::Replace( const char * szWhat, const char *szRep ) { if ((!szWhat) || (!szRep)) return; int nPos = Find(szWhat); int nLen = strlen(szRep); while (nPos != -1) { Remove(nPos, strlen(szWhat)); if (nLen) Insert(nPos, szRep); nPos += nLen; nPos = Find(szWhat, nPos); } } void GString::Replace( char chWhat, char chRep ) { char szWhat[2]; szWhat[0] = chWhat; szWhat[1] = 0; char szRep[2]; szRep[0] = chRep; szRep[1] = 0; Replace( (const char *)szWhat, (const char *)szRep ); } void GString::Replace( const char * szWhat, char chRep ) { char szRep[2]; szRep[0] = chRep; szRep[1] = 0; Replace( (const char *)szWhat, (const char *)szRep ); } void GString::Replace( char chWhat, const char *szRep ) { char szWhat[2]; szWhat[0] = chWhat; szWhat[1] = 0; Replace( (const char *)szWhat, (const char *)szRep ); } void GString::Remove( int nStart, int nLen ) { // subscript out of range if (nStart + nLen > _len) throw GenericException("String", 1); memmove(&_str[nStart], &_str[nStart + nLen], _len - (nStart + nLen)); _len -= nLen; _str[_len] = 0; } void GString::StripQuotes() { if ((_len >= 2) && (_str[0] == _str[_len - 1])) { if ((_str[0] == '\'') || (_str[0] == '"')) { memmove(&_str[0], &_str[1], _len - 2); _len -= 2; _str[_len] = 0; } } } void GString::NormalizeSpace() { int nBegWS = -1; int nEndWS = -1; for (int i = 0; i < _len; i++) { if (isWS(_str[i])) { nEndWS = i; if (nBegWS == -1) nBegWS = i; } else if ((nBegWS != -1) && (nEndWS != -1)) { nEndWS++; Remove(nBegWS, nEndWS - nBegWS); Insert(nBegWS, ' '); i = nBegWS; nBegWS = -1; nEndWS = -1; } else { nBegWS = -1; nEndWS = -1; } } if ((nBegWS != -1) && (nEndWS != -1)) { nEndWS++; Remove(nBegWS, nEndWS - nBegWS); Insert(nBegWS, ' '); } TrimLeftWS(); TrimRightWS(); } void GString::Translate(const char *szConvert, const char *szTo) { if ((szConvert) && (szTo)) { int nTranslate = ___min(strlen(szConvert), strlen(szTo)); for (int i = 0; i < _len; i++) { for (int j = 0; j < nTranslate; j++) { if (_str[i] == szConvert[j]) _str[i] = szTo[j]; } } } } // replace each char in pzReplaceChars with %nn where // nn is a two byte hex value of the byte that was replaced. // example: GString s("ABC"); // s.EscapeWithHex("XYZB"); // s == "A%42C" // 42 is hex for 66 that is the ASCII of a B // // example: GString s("A\nC"); // s.EscapeWithHex("\r\n\t"); // s == "A%0AC" // const char *GString::EscapeWithHex(const char *pzEscapeChars) { GString strDestrination; GString strEscapeChars(pzEscapeChars); char *pSrc = (char *)(const char *)(*this); int nSourceBytes = strlen(pSrc); for(int i=0;i < nSourceBytes; i++) { // escape special chars if ( strEscapeChars.Find(pSrc[i]) > -1 ) { char buf[20]; sprintf(buf,"%%%02X",pSrc[i]); strDestrination += buf; } else { strDestrination += pSrc[i]; } } *this = strDestrination; return *this; } // reverse of GString::EscapeWithHex() void GString::UnEscapeHexed() { const char *pSource = *this; char *pDest = new char [strlen(pSource) + 1]; char *pszQuery = (char *)pSource; char *t = pDest; while (*pszQuery) { switch (*pszQuery) { case '%' : { pszQuery++; char chTemp = pszQuery[2]; pszQuery[2] = 0; char *pStart = pszQuery; char *pEnd; *t = (char)strtol(pStart, &pEnd, 16); pszQuery[2] = chTemp; pszQuery = pEnd; t++; continue; } break; default : *t = *pszQuery; break; } pszQuery++; t++; } *t = 0; *this = pDest; delete pDest; } <file_sep>/////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // // Functions for the Camera Orbits behaviors // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #include "CKAll.h" #include "GeneralCameraOrbit.h" ////////////////////////////////////////////////////////////////////////////// // // General Creation Function // // Note : Creates the common inputs, outputs, settings and local parameters. // And sets the common flags. // ////////////////////////////////////////////////////////////////////////////// CKERROR FillGeneralCameraOrbitProto(CKBehaviorPrototype *proto) { proto->DeclareInput("On"); proto->DeclareInput("Off"); proto->DeclareOutput("Exit On"); proto->DeclareOutput("Exit Off"); // Default Inputs proto->DeclareInParameter("Target Position", CKPGUID_VECTOR); proto->DeclareInParameter("Target Referential", CKPGUID_3DENTITY); proto->DeclareInParameter("Move Speed", CKPGUID_ANGLE, "0:100"); proto->DeclareInParameter("Return Speed", CKPGUID_ANGLE, "0:200"); proto->DeclareInParameter("Min Horizontal", CKPGUID_ANGLE, "0:-180"); proto->DeclareInParameter("Max Horizontal", CKPGUID_ANGLE, "0:180"); proto->DeclareInParameter("Min Vertical", CKPGUID_ANGLE, "0:-180"); proto->DeclareInParameter("Max Vertical", CKPGUID_ANGLE, "0:180"); proto->DeclareInParameter("Zoom Speed", CKPGUID_FLOAT, "40"); proto->DeclareInParameter("Zoom Min", CKPGUID_FLOAT, "-40"); proto->DeclareInParameter("Zoom Max", CKPGUID_FLOAT, "10"); proto->DeclareLocalParameter("Initial Angles & Radius",CKPGUID_VECTOR); proto->DeclareLocalParameter("Rotation Angles & Radius",CKPGUID_VECTOR); proto->DeclareLocalParameter("Stopping",CKPGUID_BOOL,"TRUE"); proto->DeclareSetting("Limits", CKPGUID_BOOL,"TRUE"); proto->DeclareSetting("Returns", CKPGUID_BOOL,"TRUE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); return CK_OK; } ////////////////////////////////////////////////////////////////////////////// // // Main General Function // // Note : We use the polar angle of the camera in the target referential to // turn around it. Therefore, if the target moves, the camera moves with it // to stay around it. // Takes a specific input processing function. // ////////////////////////////////////////////////////////////////////////////// int GeneralCameraOrbit(const CKBehaviorContext& behcontext,INPUTPROCESSFUNCTION InputFunction) { // Get the behavior CKBehavior* beh = behcontext.Behavior; float delta = behcontext.DeltaTime; // Current state of the behavior CKBOOL stopping; // Indicates the behavior we are stopping if returns, stop otherwise CKBOOL Returns = TRUE; beh->GetLocalParameterValue(LOCAL_RETURN,&Returns); // Stop Entrance, we stop if (beh->IsInputActive(1)) { // Set IO State beh->ActivateInput(1,FALSE); // A protection in case we stop the behavior before having started it VxVector InitialAngles; beh->GetLocalParameterValue(LOCAL_INIT,&InitialAngles); // Get current position VxVector RotationAngles; beh->GetLocalParameterValue(LOCAL_ROT,&RotationAngles); // Stopping Now stopping = TRUE; beh->SetLocalParameterValue(LOCAL_STOPPING,&stopping); if ( !Returns || ((RotationAngles.x == 0) && (RotationAngles.y == 0)) ) { beh->ActivateOutput(1,TRUE); return CKBR_OK; } } // Gets the current camera CKCamera *Camera = (CKCamera *) beh->GetTarget(); if( !Camera ) return CKBR_OWNERERROR; // Gets the target informations VxVector TargetPosition; beh->GetInputParameterValue(IN_TARGET_POS,&TargetPosition); CK3dEntity* TargetRef = (CK3dEntity*)beh->GetInputParameterObject(IN_TARGET_REF); ////////////////////////////////////////////// // Gets the input parameters of the behavior ////////////////////////////////////////////// VxVector InitialAngles(0,0,0), RotationAngles(0,0,0); // First entrance, sets the initial values here only if (beh->IsInputActive(0)) { // Sets IO State beh->ActivateInput(0,FALSE); beh->ActivateOutput(0,TRUE); // Not Stopping stopping = FALSE; beh->SetLocalParameterValue(LOCAL_STOPPING,&stopping); // Compute the Initial Angles, the radius VxVector InitialPosition; Camera->GetPosition(&InitialPosition, TargetRef); InitialPosition -= TargetPosition; InitialAngles.z = Magnitude(InitialPosition); if ( InitialAngles.z == 0.0f ) { InitialAngles.x = 0.0f; InitialAngles.y = 0.0f; } else { // Vertical Polar Angle float d; InitialPosition.Normalize(); d = DotProduct(InitialPosition,VxVector::axisY()); // bound the value of d to avoid errors due to precision. if (d < -1) d = -1; else if (d > 1) d = 1; InitialAngles.y = acosf(d); // Horizontal Polar Angle InitialPosition.y = 0; if ( (InitialPosition.x == 0.0f) && (InitialPosition.y == 0.0f) && (InitialPosition.z == 0.0f) ) InitialAngles.x = PI/2; else { InitialPosition.Normalize(); d = DotProduct(InitialPosition,VxVector::axisX()); // bound the value of d to avoid eroors due to precision. if (d < -1) d = -1; else if (d > 1) d = 1; InitialAngles.x = acosf(d); d = DotProduct(InitialPosition,VxVector::axisZ()); if (d < 0) InitialAngles.x *= -1; } // In case the camera has the head down, we need to inverse the commands when we go // Up otherwise, the user will have the feeling to turn on the wrong direction. VxVector CamUp; Camera->GetOrientation(NULL,&CamUp,NULL,NULL); if ( CamUp.y < 0 ) { InitialAngles.x += PI; InitialAngles.y *= -1; InitialAngles.x = (float)fmod(InitialAngles.x,2*PI); } } // Reset stopping stopping = FALSE; // Sets the values in memory beh->SetLocalParameterValue(LOCAL_INIT,&InitialAngles); beh->SetLocalParameterValue(LOCAL_ROT,&RotationAngles); beh->SetLocalParameterValue(LOCAL_STOPPING,&stopping); // Only initialization on "On" entrance return CKBR_ACTIVATENEXTFRAME; } // Auto-activation of the behavior beh->GetLocalParameterValue(LOCAL_INIT,&InitialAngles); beh->GetLocalParameterValue(LOCAL_ROT,&RotationAngles); beh->GetLocalParameterValue(LOCAL_STOPPING,&stopping); // Get the input manager CKInputManager *input = (CKInputManager*)behcontext.Context->GetManagerByGuid(INPUT_MANAGER_GUID); // Call the input processing function InputFunction (&RotationAngles,beh,input,delta,Returns,stopping); // Do nothing when initial angle were not initialized. // Simply stop the BB. No output activated. if ( (InitialAngles.x == INF) || (RotationAngles.x == INF) ) return CKBR_OK; // When we are exactly on the top or the bottom of the target, +/-90°, // The LookAt BB won't rotate the camera when we turn right or left as // it already looks at the target. Therefore, when we are at +/-90°, we // add or remove a little something. if ( (RotationAngles.y==PI/2) || (RotationAngles.y == -PI/2) ) { // Get Min, Max // If equals, nothing to change, it is the given value. float MinH = -PI/2; float MaxH = PI/2; beh->GetInputParameterValue(IN_MIN_H, &MinH); beh->GetInputParameterValue(IN_MAX_H, &MaxH); if ( MaxH - MinH > 2 * STEP ) { float sign = (RotationAngles.y > 0) ? 1.0f : -1.0f; if ( MaxH >= sign * PI/2 + STEP ) RotationAngles.y += STEP; else RotationAngles.y -= STEP; } } // We memorize the new state with modulos RotationAngles.x = (float)fmod(RotationAngles.x,2*PI); RotationAngles.y = (float)fmod(RotationAngles.y,2*PI); beh->SetLocalParameterValue(LOCAL_ROT,&RotationAngles); // Computes the coordinates of the camera in the target referential thanks to the // current polar angles and radius informations. And moves the camera VxVector Position; Position = InitialAngles + RotationAngles; Position = Position.z * (cosf(Position.x) * sinf(Position.y) * VxVector::axisX() + sinf(Position.x) * sinf(Position.y) * VxVector::axisZ() + cosf(Position.y) * VxVector::axisY()); Position += TargetPosition; Camera->SetPosition(&Position, TargetRef, FALSE); // Does the camera has a Target ? CK3dEntity *CameraTarget; CKBOOL CameraHasTarget = CKIsChildClassOf(Camera,CKCID_TARGETCAMERA) && (CameraTarget=((CKTargetCamera*)Camera)->GetTarget()); // Orients the Camera. The LookAt implies that when the camera reach // the 90°, it may be flipped and suddently have the head up and down. // Therefore we use the target for target cameras as we have to use the // target. But for free cameras, we do our own look at using our rotation // angle to avoid this problem. if (CameraHasTarget) CameraTarget->SetPosition(&TargetPosition, TargetRef, TRUE); else { // New direction VxVector Dir; Dir = TargetPosition - Position; // Temp Right Value VxMatrix mat; VxVector R(0,0,-1); // Up for (0,0) angle Vx3DMatrixFromRotationAndOrigin(mat,VxVector::axisY(),VxVector(0,0,0),InitialAngles.x + RotationAngles.x); R.Rotate(mat); // Get Up VxVector Up; Up = CrossProduct(R,Dir); Camera->SetOrientation(&Dir,&Up,NULL,TargetRef); //Camera->LookAt(&TargetPosition,TargetRef); } // Stop is finished, reset values. if ( stopping && ((RotationAngles.x == 0) && (RotationAngles.y == 0)) ) { beh->ActivateOutput(1,TRUE); return CKBR_OK; } else // Come back next frame return CKBR_ACTIVATENEXTFRAME; } ////////////////////////////////////////////////////////////////////////////// // // Callback Function // ////////////////////////////////////////////////////////////////////////////// CKERROR GeneralCameraOrbitCallback(const CKBehaviorContext& context) { CKBehavior* beh = context.Behavior; switch(context.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { VxVector InitialAngles(INF,INF,INF); beh->SetLocalParameterValue(LOCAL_INIT,&InitialAngles); VxVector RotationAngles(0,0,0); beh->SetLocalParameterValue(LOCAL_ROT,&RotationAngles); } break; case CKM_BEHAVIORSETTINGSEDITED: { // Update the needed input for "returns" CKBOOL Returns = TRUE; beh->GetLocalParameterValue(LOCAL_RETURN,&Returns); beh->EnableInputParameter(IN_SPEED_RETURN, Returns); // Updates the needed inputs for limiting the move CKBOOL Limited = TRUE; beh->GetLocalParameterValue(LOCAL_LIMITS,&Limited); beh->EnableInputParameter(IN_MIN_H,Limited); beh->EnableInputParameter(IN_MAX_H,Limited); beh->EnableInputParameter(IN_MIN_V,Limited); beh->EnableInputParameter(IN_MAX_V,Limited); beh->EnableInputParameter(IN_MIN_ZOOM,Limited); beh->EnableInputParameter(IN_MAX_ZOOM,Limited); } break; default: break; } return CKBR_OK; } <file_sep>/******************************************************************** created: 2007/12/15 created: 15:12:2007 22:28 filename: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\plugins\xUtils\include\xUtils.h file path: x:\junctions\ProjectRoot\current\vt_player\exKamPlayer\plugins\xUtils\include file base: xUtils file ext: h author: mc007 purpose: *********************************************************************/ #ifndef __X_UTILS_H_ #define __X_UTILS_H_ #include <BaseMacros.h> namespace xUtils { namespace system { MODULE_API HRESULT GetDirectVersion(char*&version,DWORD& minor); MODULE_API int GetPhysicalMemoryInMB(); } } #endif <file_sep>#include <StdAfx.h> #include "vtPhysXBase.h" #include "xAssertion.h" #include "xAssertCustomization.h" //---------------------------------------------------------------- // // global data // CAssertionFailedProcedure xAssertionEx::g_fnAssertFailureHandler = NULL; xErrorHandlerFn xAssertionEx::g_fnAssertHandler = NULL; xAssertionEx* gAssertionEx = NULL; //---------------------------------------------------------------- // // // xAssertionEx*xAssertionEx::Instance() { if (!gAssertionEx) gAssertionEx = &xAssertionEx(); return gAssertionEx; } xAssertionEx::xAssertionEx() { gAssertionEx = this; } /* xErrorHandlerFn xAssertionEx::getErrorHandler() { return g_fnAssertHandler; } void xAssertionEx::setErrorHandler(xErrorHandlerFn fnFailureProcedure) { g_fnAssertHandler = fnFailureProcedure; } */ //---------------------------------------------------------------- // // // void assert_notify_failure(const char* str) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,str); //std::cerr << str << " failed" << std::endl; } <file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #ifndef _TNL_BITSTREAM_H_ #define _TNL_BITSTREAM_H_ #ifndef _TNL_BYTEBUFFER_H_ #include "tnlByteBuffer.h" #endif #ifndef _TNL_CONNECTIONSTRINGTABLE_H_ #include "tnlConnectionStringTable.h" #endif namespace TNL { class SymmetricCipher; /// Point3F is used by BitStream for transmitting 3D points and vectors. /// /// Users of the TNL should provide conversion operators to and from /// this TNL-native type. struct Point3f { F32 x; ///< the X coordinate F32 y; ///< the Y coordinate F32 z; ///< the Z coordinate }; /// Helper macro used in BitStream declaration. /// /// @note DeclareTemplatizedReadWrite macro declares a read and write function /// for the specified type. This is a macro because MSVC6 has seriously /// broken template functionality. Thanks MS! #define DeclareTemplatizedReadWrite(T) \ inline bool write(T value) { T temp = convertHostToLEndian(value); return write(sizeof(T), &temp); } \ inline bool read(T *value) { T temp; bool success = read(sizeof(T), &temp); *value = convertLEndianToHost(temp); return success;} /// BitStream provides a bit-level stream interface to a data buffer. class BitStream : public ByteBuffer { protected: enum { ResizePad = 1500, }; U32 bitNum; ///< The current bit position for reading/writing in the bit stream. bool error; ///< Flag set if a user operation attempts to read or write past the max read/write sizes. bool mCompressRelative; ///< Flag set if the bit stream should compress points relative to a compression point. Point3f mCompressPoint; ///< Reference point for relative point compression. U32 maxReadBitNum; ///< Last valid read bit position. U32 maxWriteBitNum; ///< Last valid write bit position. ConnectionStringTable *mStringTable; ///< String table used to compress StringTableEntries over the network. /// String buffer holds the last string written into the stream for substring compression. char mStringBuffer[256]; bool resizeBits(U32 numBitsNeeded); public: /// @name Constructors /// /// Note that the BitStream essentially wraps an existing buffer, so to use a bitstream you must /// have an existing buffer for it to work with! /// /// @{ /// Default to maximum write size being the size of the buffer. BitStream(U8 *bufPtr, U32 bufSize) : ByteBuffer(bufPtr, bufSize) { setMaxSizes(bufSize, bufSize); reset(); } /// Optionally, specify a maximum write size. BitStream(U8 *bufPtr, U32 bufSize, U32 maxWriteSize) : ByteBuffer(bufPtr, bufSize) { setMaxSizes(bufSize, maxWriteSize); reset(); } /// Creates a resizable BitStream BitStream() : ByteBuffer() { setMaxSizes( getBufferSize(), getBufferSize() ); reset(); } /// @} /// Sets the maximum read and write sizes for the BitStream. void setMaxSizes(U32 maxReadSize, U32 maxWriteSize = 0); /// Sets the maximum read and write bit sizes for the BitStream. void setMaxBitSizes(U32 maxReadBitSize, U32 maxWriteBitSize = 0); /// resets the read/write position to 0 and clears any error state. void reset(); /// clears the string compression buffer. void clearStringBuffer() { mStringBuffer[0] = 0; } /// sets the ConnectionStringTable for compressing string table entries across the network void setStringTable(ConnectionStringTable *table) { mStringTable = table; } /// clears the error state from an attempted read or write overrun void clearError() { error = false; } /// Returns a pointer to the next byte in the BitStream from the current bit position U8* getBytePtr(); /// Returns the current position in the stream rounded up to the next byte. U32 getBytePosition() const; /// Returns the current bit position in the stream U32 getBitPosition() const; /// Sets the position in the stream to the first bit of byte newPosition. void setBytePosition(const U32 newPosition); /// Sets the position in the stream to newBitPosition. void setBitPosition(const U32 newBitPosition); /// Advances the position in the stream by numBits. void advanceBitPosition(const S32 numBits); /// Returns the maximum readable bit position U32 getMaxReadBitPosition() const { return maxReadBitNum; } /// Returns the number of bits that can be written into the BitStream without resizing U32 getBitSpaceAvailable() const { return maxWriteBitNum - bitNum; } /// Pads the bits up to the next byte boundary with 0's. void zeroToByteBoundary(); /// Writes an unsigned integer value between 0 and 2^(bitCount - 1) into the stream. void writeInt(U32 value, U8 bitCount); /// Reads an unsigned integer value between 0 and 2^(bitCount - 1) from the stream. U32 readInt(U8 bitCount); /// Writes an unsigned integer value between 0 and 2^(bitCount -1) into the stream at the specified position, without changing the current write position. void writeIntAt(U32 value, U8 bitCount, U32 bitPosition); /// Writes a signed integer value between -2^(bitCount-1) and 2^(bitCount-1) - 1. void writeSignedInt(S32 value, U8 bitCount); /// Reads a signed integer value between -2^(bitCount-1) and 2^(bitCount-1) - 1. S32 readSignedInt(U8 bitCount); /// Writes an unsigned integer value in the range rangeStart to rangeEnd inclusive. void writeRangedU32(U32 value, U32 rangeStart, U32 rangeEnd); /// Reads an unsigned integer value in the range rangeStart to rangeEnd inclusive. U32 readRangedU32(U32 rangeStart, U32 rangeEnd); /// Writes an enumeration value in the range of 0 ... enumRange - 1. void writeEnum(U32 enumValue, U32 enumRange); /// Reads an enumeration value in the range 0 ... enumRange - 1. U32 readEnum(U32 enumRange); /// Writes a float from 0 to 1 inclusive, using bitCount bits of precision. void writeFloat(F32 f, U8 bitCount); /// Reads a float from 0 to 1 inclusive, using bitCount bits of precision. F32 readFloat(U8 bitCount); /// Writes a signed float from -1 to 1 inclusive, using bitCount bits of precision. void writeSignedFloat(F32 f, U8 bitCount); /// Reads a signed float from -1 to 1 inclusive, using bitCount bits of precision. F32 readSignedFloat(U8 bitCount); /// Writes an object's class ID, given its class type and class group. void writeClassId(U32 classId, U32 classType, U32 classGroup); /// Reads a class ID for an object, given a class type and class group. Returns -1 if the class type is out of range U32 readClassId(U32 classType, U32 classGroup); /// Writes a normalized vector into the stream, using bitCount bits for the precision of angles phi and theta. void writeNormalVector(const Point3f &vec, U8 bitCount); /// Reads a normalized vector from the stream, using bitCount bits for the precision of angles phi and theta. void readNormalVector(Point3f *vec, U8 bitCount); /// Uses the same method as in writeNormalVector to reduce the precision of a normal vector /// to determine what will be read from the stream. static Point3f dumbDownNormal(const Point3f& vec, U8 bitCount); /// Writes a normalized vector by writing a z value and theta angle. void writeNormalVector(const Point3f& vec, U8 angleBitCount, U8 zBitCount); /// Reads a normalized vector by reading a z value and theta angle. void readNormalVector(Point3f *vec, U8 angleBitCount, U8 zBitCount); /// Sets a reference point for subsequent compressed point writing. void setPointCompression(const Point3f &p); /// Disables compression of point. void clearPointCompression(); /// Writes a point into the stream, to a precision denoted by scale. void writePointCompressed(const Point3f &p, F32 scale); /// Reads a compressed point from the stream, to a precision denoted by scale. void readPointCompressed(Point3f *p, F32 scale); /// Writes bitCount bits into the stream from bitPtr. bool writeBits(U32 bitCount, const void *bitPtr); /// Reads bitCount bits from the stream into bitPtr. bool readBits(U32 bitCount, void *bitPtr); /// Writes a ByteBuffer into the stream. The ByteBuffer can be no larger than 1024 bytes in size. bool write(const ByteBuffer *theBuffer); /// Reads a ByteBuffer in from the stream. bool read(ByteBuffer *theBuffer); /// Writes a single boolean flag (bit) into the stream, and returns the boolean that was written. /// /// This is set up so you can do... /// /// @code /// if(stream->writeFlag(foo == bar)) /// { /// ... write other stuff ... /// } /// @endcode bool writeFlag(bool val); /// Reads a single bit from the stream. /// /// This is set up so you can do... /// /// @code /// if(stream->readFlag()) /// { /// ... read other stuff ... /// } /// @endcode bool readFlag(); bool write(bool value) { writeFlag(value); return !error; } bool read(bool *value) { *value = readFlag(); return !error; } /// Writes a huffman compressed string into the stream. void writeString(const char *stringBuf, U8 maxLen=255); /// Reads a huffman compressed string from the stream. void readString(char stringBuf[256]); /// Writes a string table entry into the stream void writeStringTableEntry(const StringTableEntry &ste); /// Reads a string table entry from the stream void readStringTableEntry(StringTableEntry *ste); /// Writes byte data into the stream. bool write(const U32 in_numBytes, const void* in_pBuffer); /// Reads byte data from the stream. bool read(const U32 in_numBytes, void* out_pBuffer); /// @name Various types that the BitStream can read and write... /// @{ /// DeclareTemplatizedReadWrite(U8); DeclareTemplatizedReadWrite(S8); DeclareTemplatizedReadWrite(U16); DeclareTemplatizedReadWrite(S16); DeclareTemplatizedReadWrite(U32); DeclareTemplatizedReadWrite(S32); DeclareTemplatizedReadWrite(S64); DeclareTemplatizedReadWrite(U64); DeclareTemplatizedReadWrite(F32); DeclareTemplatizedReadWrite(F64); /// @} /// Sets the bit at position bitCount to the value of set bool setBit(U32 bitCount, bool set); /// Tests the value of the bit at position bitCount. bool testBit(U32 bitCount); /// Returns whether the BitStream writing has exceeded the write target size. bool isFull() { return bitNum > (getBufferSize() << 3); } /// Returns whether the stream has generated an error condition due to reading or writing past the end of the buffer. bool isValid() { return !error; } /// Hashes the BitStream, writing the hash digest into the end of the buffer, and then encrypts with the given cipher void hashAndEncrypt(U32 hashDigestSize, U32 encryptStartOffset, SymmetricCipher *theCipher); /// Decrypts the BitStream, then checks the hash digest at the end of the buffer to validate the contents bool decryptAndCheckHash(U32 hashDigestSize, U32 decryptStartOffset, SymmetricCipher *theCipher); }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ inline U32 BitStream::getBytePosition() const { return (bitNum + 7) >> 3; } inline U32 BitStream::getBitPosition() const { return bitNum; } inline void BitStream::setBytePosition(const U32 newPosition) { bitNum = newPosition << 3; } inline void BitStream::setBitPosition(const U32 newBitPosition) { bitNum = newBitPosition; } inline void BitStream::advanceBitPosition(const S32 numBits) { setBitPosition(getBitPosition() + numBits); } inline void BitStream::zeroToByteBoundary() { if(bitNum & 0x7) writeInt(0, 8 - (bitNum & 0x7)); } inline bool BitStream::write(const U32 in_numBytes, const void* in_pBuffer) { return writeBits(in_numBytes << 3, in_pBuffer); } inline bool BitStream::read(const U32 in_numBytes, void* out_pBuffer) { return readBits(in_numBytes << 3, out_pBuffer); } inline bool BitStream::readFlag() { if(bitNum > maxReadBitNum) { error = true; TNLAssert(false, "Out of range read"); return false; } S32 mask = 1 << (bitNum & 0x7); bool ret = (*(getBuffer() + (bitNum >> 3)) & mask) != 0; bitNum++; return ret; } inline void BitStream::writeIntAt(U32 value, U8 bitCount, U32 bitPosition) { U32 curPos = getBitPosition(); setBitPosition(bitPosition); writeInt(value, bitCount); setBitPosition(curPos); } inline void BitStream::writeRangedU32(U32 value, U32 rangeStart, U32 rangeEnd) { TNLAssert(value >= rangeStart && value <= rangeEnd, "Out of bounds value!"); TNLAssert(rangeEnd >= rangeStart, "error, end of range less than start"); U32 rangeSize = rangeEnd - rangeStart + 1; U32 rangeBits = getNextBinLog2(rangeSize); writeInt(S32(value - rangeStart), S32(rangeBits)); } inline U32 BitStream::readRangedU32(U32 rangeStart, U32 rangeEnd) { TNLAssert(rangeEnd >= rangeStart, "error, end of range less than start"); U32 rangeSize = rangeEnd - rangeStart + 1; U32 rangeBits = getNextBinLog2(rangeSize); U32 val = U32(readInt(S32(rangeBits))); return val + rangeStart; } inline void BitStream::writeEnum(U32 enumValue, U32 enumRange) { writeInt(enumValue, getNextBinLog2(enumRange)); } inline U32 BitStream::readEnum(U32 enumRange) { return U32(readInt(getNextBinLog2(enumRange))); } /// PacketStream provides a network interface to the BitStream for easy construction of data packets. class PacketStream : public BitStream { typedef BitStream Parent; U8 buffer[MaxPacketDataSize]; ///< internal buffer for packet data, sized to the maximum UDP packet size. public: /// Constructor assigns the internal buffer to the BitStream. PacketStream(U32 targetPacketSize = MaxPacketDataSize) : BitStream(buffer, targetPacketSize, MaxPacketDataSize) {} /// Sends this packet to the specified address through the specified socket. NetError sendto(Socket &outgoingSocket, const Address &theAddress); /// Reads a packet into the stream from the specified socket. NetError recvfrom(Socket &incomingSocket, Address *recvAddress); }; }; #endif //_TNL_BITSTREAM_H_ <file_sep>#ifndef __P_CLOTH_H__ #define __P_CLOTH_H__ #include "vtPhysXBase.h" /** \addtogroup Cloth @{ */ /** brief2 Class for clothes. */ class MODULE_API pCloth { public: /************************************************************************/ /* */ /************************************************************************/ void releaseReceiveBuffers(); void allocateClothReceiveBuffers(int numVertices, int numTriangles); CK_ID getEntityID() const { return mEntityID; } void setEntityID(CK_ID val) { mEntityID = val; } NxCloth * getCloth() const { return mCloth; } void setCloth(NxCloth * val) { mCloth = val; } pCloth(); virtual ~pCloth(); NxMeshData * getReceiveBuffers() const { return mReceiveBuffers; } void setReceiveBuffers(NxMeshData * val) { mReceiveBuffers = val; } bool cookMesh(NxClothMeshDesc* desc); void releaseMeshDescBuffers(const NxClothMeshDesc* desc); bool generateMeshDesc(pClothDesc cDesc,NxClothMeshDesc *desc, CKMesh*mesh); pWorld * getWorld() const { return mWorld; } void setWorld(pWorld * val) { mWorld = val; } NxClothMesh * getClothMesh() const { return mClothMesh; } void setClothMesh(NxClothMesh * val) { mClothMesh = val; } void updateVirtoolsMesh(); /************************************************************************/ /* */ /************************************************************************/ /** \brief Sets the cloth bending stiffness in the range from 0 to 1. \param[in] stiffness The stiffness of this cloth. @see pClothDesc.bendingStiffness getBendingStiffness() */ void setBendingStiffness(float stiffness); /** \brief Retrieves the cloth bending stiffness. \return Bending stiffness of cloth. @see pClothDesc.bendingStiffness setBendingStiffness() */ float getBendingStiffness() const; /** \brief Sets the cloth stretching stiffness in the range from 0 to 1. Note: The stretching stiffness must be larger than 0. \param[in] stiffness Stiffness of cloth. @see pClothDesc.stretchingStiffness getStretchingStiffness() */ void setStretchingStiffness(float stiffness); /** \brief Retrieves the cloth stretching stiffness. \return stretching stiffness of cloth. @see pClothDesc.stretchingStiffness setStretchingStiffness() */ float getStretchingStiffness() const; /** \brief Sets the damping coefficient in the range from 0 to 1. \param[in] dampingCoefficient damping coefficient of cloth. @see pClothDesc.dampingCoefficient getDampingCoefficient() */ void setDampingCoefficient(float dampingCoefficient); /** \brief Retrieves the damping coefficient. \return damping coefficient of cloth. @see pClothDesc.dampingCoefficient setDampingCoefficient() */ float getDampingCoefficient() const; /** \brief Sets the cloth friction coefficient in the range from 0 to 1. \param[in] friction The friction of the cloth. @see pClothDesc.friction getFriction() */ void setFriction(float friction); /** \brief Retrieves the cloth friction coefficient. \return Friction coefficient of cloth. @see pClothDesc.friction setFriction() */ float getFriction() const; /** \brief Sets the cloth pressure coefficient (must be non negative). \param[in] pressure The pressure applied to the cloth. @see pClothDesc.pressure getPressure() */ void setPressure(float pressure); /** \brief Retrieves the cloth pressure coefficient. \return Pressure of cloth. @see pClothDesc.pressure setPressure() */ float getPressure() const; /** \brief Sets the cloth tear factor (must be larger than one). \param[in] factor The tear factor for the cloth @see pClothDesc.tearFactor getTearFactor() */ void setTearFactor(float factor); /** \brief Retrieves the cloth tear factor. \return tear factor of cloth. @see pClothDesc.tearFactor setTearFactor() */ float getTearFactor() const; /** \brief Sets the cloth attachment tear factor (must be larger than one). \param[in] factor The attachment tear factor for the cloth @see pClothDesc.attachmentTearFactor getAttachmentTearFactor() */ void setAttachmentTearFactor(float factor); /** \brief Retrieves the attachment cloth tear factor. \return tear attachment factor of cloth. @see pClothDesc.attachmentTearFactor setAttachmentTearFactor() */ float getAttachmentTearFactor() const; /** \brief Sets the cloth thickness (must be positive). \param[in] thickness The thickness of the cloth. @see pClothDesc.thickness getThickness() */ void setThickness(float thickness); /** \brief Gets the cloth thickness. \return thickness of cloth. @see pClothDesc.thickness setThickness() */ float getThickness() const; /** \brief Gets the cloth density. \return density of cloth. @see pClothDesc.density */ float getDensity() const; /** \brief Gets the relative grid spacing for the broad phase. The cloth is represented by a set of world aligned cubical cells in broad phase. The size of these cells is determined by multiplying the length of the diagonal of the AABB of the initial cloth size with this constant. \return relative grid spacing. @see pClothDesc.relativeGridSpacing */ float getRelativeGridSpacing() const; /** \brief Retrieves the cloth solver iterations. \return solver iterations of cloth. @see pClothDesc.solverIterations setSolverIterations() */ int getSolverIterations() const; /** \brief Sets the cloth solver iterations. \param[in] iterations The new solver iteration count for the cloth. @see pClothDesc.solverIterations getSolverIterations() */ void setSolverIterations(int iterations); /** \brief Returns a world space AABB enclosing all cloth points. \param[out] bounds Retrieves the world space bounds. @see NxBounds3 */ void getWorldBounds(VxBbox & bounds) const; /** \brief Attaches the cloth to a shape. All cloth points currently inside the shape are attached. \note This method only works with primitive and convex shapes. Since the inside of a general triangle mesh is not clearly defined. \param[in] shape Shape to which the cloth should be attached to. \param[in] attachmentFlags One or two way interaction, tearable or non-tearable @see NxClothAttachmentFlag freeVertex() attachToCollidingShapes() */ void attachToShape(CKBeObject *shape, int attachmentFlags); /** \brief Attaches the cloth to all shapes, currently colliding. \note This method only works with primitive and convex shapes. Since the inside of a general triangle mesh is not clearly defined. \param[in] attachmentFlags One or two way interaction, tearable or non-tearable @see NxClothAttachmentFlag pClothDesc.attachmentTearFactor pClothDesc.attachmentResponseCoefficient freeVertex() */ void attachToCollidingShapes(int attachmentFlags); /** \brief Detaches the cloth from a shape it has been attached to before. If the cloth has not been attached to the shape before, the call has no effect. \param[in] shape Shape from which the cloth should be detached. @see NxClothAttachmentFlag pClothDesc.attachmentTearFactor pClothDesc.attachmentResponseCoefficient freeVertex() attachToShape() */ void detachFromShape(CKBeObject *shape); /** \brief Attaches a cloth vertex to a local position within a shape. \param[in] vertexId Index of the vertex to attach. \param[in] shape Shape to attach the vertex to. \param[in] localPos The position relative to the pose of the shape. \param[in] attachmentFlags One or two way interaction, tearable or non-tearable <b>Platform:</b> \li PC SW: Yes \li PPU : Yes \li PS3 : Yes \li XB360: Yes @see NxShape freeVertex() NxClothAttachmentFlag attachToShape() */ void attachVertexToShape(int vertexId, CKBeObject *shape, const VxVector &localPos, int attachmentFlags); /** \brief Attaches a cloth vertex to a position in world space. \param[in] vertexId Index of the vertex to attach. \param[in] pos The position in world space. @see pClothAttachmentFlag pClothDesc.attachmentTearFactor pClothDesc.attachmentResponseCoefficient freeVertex() attachToShape() */ void attachVertexToGlobalPosition(const int vertexId, const VxVector &pos); /** \brief Frees a previously attached cloth point. \param[in] vertexId Index of the vertex to free. @see attachVertexToGlobalPosition() attachVertexToShape() detachFromShape() */ void freeVertex(const int vertexId); /** \brief Changes the weight of a vertex in the cloth solver for a period of time. If this method is called for some vertex, the cloth solver will, during a time period of length expirationTime, assign a different weight to the vertex while internal cloth constraints (i.e. bending & stretching) are being resolved. With a high dominanceWeight, the modified vertex will force neighboring vertices to strongly accommodate their positions while its own is kept fairly constant. The reverse holds for smaller dominanceWeights. Using a dominanceWeight of +infinity has a similar effect as temporarily attaching the vertex to a global position. However, unlike using attachments, the velocity of the vertex is kept intact when using this method. \note The current implementation will not support the full range of dominanceWeights. All dominanceWeights > 0.0 are treated equally as being +infinity. \note An expiration time of 0.0 is legal and will result in dominance being applied throughout one substep before being discarded immediately. \note Having a large number of vertices dominant at once may result in a performance penalty. \param[in] vertexId Index of the vertex. \param[in] expirationTime Time period where dominance will be active for this vertex. \param[in] dominanceWeight Dominance weight for this vertex. @see attachVertexToGlobalPosition() */ void dominateVertex(int vertexId, float expirationTime, float dominanceWeight); /** \brief Return the attachment status of the given vertex. \param[in] vertexId Index of the vertex. @see getVertexAttachmentShape() getVertexAttachmentPosition() */ xU16 getVertexAttachmentStatus(int vertexId) const; /** \brief Returns the pointer to an attached shape pointer of the given vertex. If the vertex is not attached or attached to a global position, NULL is returned. \param[in] vertexId Index of the vertex. @see getVertexAttachmentStatus() getVertexAttachmentPosition() */ NxShape* getVertexAttachmentShape(int vertexId) const; /** \brief Returns the attachment position of the given vertex. If the vertex is attached to shape, the position local to the shape's pose is returned. If the vertex is not attached, the return value is undefined. \param[in] vertexId Index of the vertex. @see getVertexAttachmentStatus() getVertexAttachmentShape() */ VxVector getVertexAttachmentPosition(int vertexId) const; /** \brief Attaches the cloth to an actor. \note Call this function only once right after the cloth is created. Turning cloth into metal and vice versa during the simulation is not recommended. \note This feature is well suited for volumetric objects like barrels. It cannot handle two dimensional flat pieces well. After this call, the cloth is infinitely stiff between collisions and simply moves with the actor. At impacts with an impact impulse greater than impulseThreshold, the cloth is plastically deformed. Thus, a cloth with a core behaves like a piece of metal. The core actor's geometry is adjusted automatically. Its size also depends on the cloth thickness. Thus, it is recommended to choose small values for the thickness. At impacts, colliding objects are moved closer to the cloth by the value provided in penetrationDepth which causes a more dramatic collision result. The core actor must have at least one shape, and currently supported shapes are spheres, capsules, boxes and compounds of spheres. It is recommended to specify the density rather than the mass of the core body. This way the mass and inertia tensor are updated when the core deforms. The maximal deviation of cloth particles from their initial positions (modulo the global rigid body transforms translation and rotation) can be specified via the parameter maxDeformationDistance. Setting this parameter to zero means that the deformation is not limited. \param actor The core actor to attach the cloth to. \param impulseThreshold Threshold for when deformation is allowed. \param penetrationDepth Amount by which colliding objects are brought closer to the cloth. \param maxDeformationDistance Maximum deviation of cloth particles from initial position. */ void attachToCore(CK3dEntity *body, float impulseThreshold, float penetrationDepth, float maxDeformationDistance); /** \brief Tears the cloth at a given vertex. First the vertex is duplicated. The triangles on one side of the split plane keep the original vertex. For all triangles on the opposite side the original vertex is replaced by the new one. The split plane is defined by the world location of the vertex and the normal provided by the user. Note: TearVertex performs a user defined vertex split in contrast to an automatic split that is performed when the flag NX_CLF_TEARABLE is set. Therefore, tearVertex works even if NX_CLF_TEARABLE is not set in pClothDesc.flags. Note: For tearVertex to work, the clothMesh has to be cooked with the flag NX_CLOTH_MESH_TEARABLE set in NxClothMeshDesc.flags. \param[in] vertexId Index of the vertex to tear. \param[in] normal The normal of the split plane. \return true if the split had an effect (i.e. there were triangles on both sides of the split plane) @see NxClothFlag, NxClothMeshFlags, pClothDesc.flags NxSimpleTriangleMesh.flags <b>Platform:</b> \li PC SW: Yes \li PPU : Yes \li PS3 : Yes \li XB360: Yes */ bool tearVertex(const int vertexId, const VxVector &normal); /** \brief Executes a raycast against the cloth. \param[in] worldRay The ray in world space. \param[out] hit The hit position. \param[out] vertexId Index to the nearest vertex hit by the raycast. \return true if the ray hits the cloth. */ //BOOL raycast(const NxRay& worldRay, VxVector &hit, int &vertexId); /** \brief Sets which collision group this cloth is part of. \param[in] collisionGroup The collision group for this cloth. @see NxCollisionGroup */ void setGroup(int collisionGroup); /** \brief Retrieves the value set with #setGroup(). \return The collision group this cloth belongs to. @see NxCollisionGroup */ int getGroup() const; /** \brief Sets 128-bit mask used for collision filtering. \param[in] groupsMask The group mask to set for the cloth. @see getGroupsMask() NxGroupsMask */ void setGroupsMask(const pGroupsMask& groupsMask); /** \brief Sets 128-bit mask used for collision filtering. \return The group mask for the cloth. @see setGroupsMask() NxGroupsMask */ const pGroupsMask getGroupsMask() const; /** \brief Sets the valid bounds of the cloth in world space. If the flag NX_CLF_VALIDBOUNDS is set, these bounds defines the volume outside of which cloth particle are automatically removed from the simulation. \param[in] validBounds The valid bounds. @see pClothDesc.validBounds getValidBounds() NxBounds3 */ void setValidBounds(const VxBbox& validBounds); /** \brief Returns the valid bounds of the cloth in world space. \param[out] validBounds The valid bounds. @see pClothDesc.validBounds setValidBounds() NxBounds3 */ void getValidBounds(NxBounds3& validBounds) const; /** \brief Sets the position of a particular vertex of the cloth. \param[in] position New position of the vertex. \param[in] vertexId Index of the vertex. @see getPosition() setPositions() getPositions() setVelocity() getVelocity() getNumberOfParticles() */ void setPosition(const VxVector& position, int vertexId); /** \brief Sets the positions of the cloth. The user must supply a buffer containing all positions (i.e same number of elements as number of particles). \param[in] buffer The user supplied buffer containing all positions for the cloth. \param[in] byteStride The stride in bytes between the position vectors in the buffer. Default is size of VxVector. @see getPositions() setVelocities() getVelocities() getNumberOfParticles() */ void setPositions(void* buffer, int byteStride = sizeof(VxVector)); /** \brief Gets the position of a particular vertex of the cloth. \param[in] vertexId Index of the vertex. @see setPosition() setPositions() getPositions() setVelocity() getVelocity() getNumberOfParticles() */ VxVector getPosition(int vertexId) const; /** \brief Gets the positions of the cloth. The user must supply a buffer large enough to hold all positions (i.e same number of elements as number of particles). \param[in] buffer The user supplied buffer to hold all positions of the cloth. \param[in] byteStride The stride in bytes between the position vectors in the buffer. Default is size of VxVector. @see setPositions() setVelocities() getVelocities() getNumberOfParticles() */ void getPositions(void* buffer, int byteStride = sizeof(VxVector)); /** \brief Sets the velocity of a particular vertex of the cloth. \param[in] position New velocity of the vertex. \param[in] vertexId Index of the vertex. @see setPosition() getPosition() getVelocity() setVelocities() getVelocities() getNumberOfParticles() */ void setVelocity(const VxVector& velocity, int vertexId); /** \brief Sets the velocities of the cloth. The user must supply a buffer containing all velocities (i.e same number of elements as number of particles). \param[in] buffer The user supplied buffer containing all velocities for the cloth. \param[in] byteStride The stride in bytes between the velocity vectors in the buffer. Default is size of VxVector. @see getVelocities() setPositions() getPositions() getNumberOfParticles() */ void setVelocities(void* buffer, int byteStride = sizeof(VxVector)); /** \brief Gets the velocity of a particular vertex of the cloth. \param[in] vertexId Index of the vertex. @see setPosition() getPosition() setVelocity() setVelocities() getVelocities() getNumberOfParticles() */ VxVector getVelocity(int vertexId) const; /** \brief Sets the collision response coefficient. \param[in] coefficient The collision response coefficient (0 or greater). @see pClothDesc.collisionResponseCoefficient getCollisionResponseCoefficient() */ void setCollisionResponseCoefficient(float coefficient); /** \brief Retrieves the collision response coefficient. \return The collision response coefficient. @see pClothDesc.collisionResponseCoefficient setCollisionResponseCoefficient() */ float getCollisionResponseCoefficient() const; /** \brief Sets the attachment response coefficient \param[in] coefficient The attachment response coefficient in the range from 0 to 1. @see pClothDesc.attachmentResponseCoefficient getAttachmentResponseCoefficient() */ void setAttachmentResponseCoefficient(float coefficient); /** \brief Retrieves the attachment response coefficient \return The attachment response coefficient. @see pClothDesc.attachmentResponseCoefficient setAttachmentResponseCoefficient() */ float getAttachmentResponseCoefficient() const; /** \brief Sets the response coefficient for collisions from fluids to this cloth \param[in] coefficient The response coefficient @see pClothDesc.fromFluidResponseCoefficient getFromFluidResponseCoefficient() */ void setFromFluidResponseCoefficient(float coefficient); /** \brief Retrieves response coefficient for collisions from fluids to this cloth \return The response coefficient. @see pClothDesc.fromFluidResponseCoefficient setFromFluidResponseCoefficient() */ float getFromFluidResponseCoefficient() const; /** \brief Sets the response coefficient for collisions from this cloth to fluids \param[in] coefficient The response coefficient @see pClothDesc.toFluidResponseCoefficient getToFluidResponseCoefficient() */ void setToFluidResponseCoefficient(float coefficient); /** \brief Retrieves response coefficient for collisions from this cloth to fluids \return The response coefficient. @see pClothDesc.toFluidResponseCoefficient setToFluidResponseCoefficient() */ float getToFluidResponseCoefficient() const; /** \brief Sets an external acceleration which affects all non attached particles of the cloth \param[in] acceleration The acceleration vector (unit length / s^2) @see pClothDesc.externalAcceleration getExternalAcceleration() */ void setExternalAcceleration(VxVector acceleration); /** \brief Retrieves the external acceleration which affects all non attached particles of the cloth \return The acceleration vector (unit length / s^2) @see pClothDesc.externalAcceleration setExternalAcceleration() */ VxVector getExternalAcceleration() const; /** \brief If the NX_CLF_ADHERE flag is set the cloth moves partially in the frame of the attached actor. This feature is useful when the cloth is attached to a fast moving character. In that case the cloth adheres to the shape it is attached to while only velocities below the parameter minAdhereVelocity are used for secondary effects. \param[in] velocity The minimal velocity for cloth to adhere (unit length / s) @see pClothDesc.minAdhereVelocity getMinAdhereVelocity() */ void setMinAdhereVelocity(float velocity); /** \brief If the NX_CLF_ADHERE flag is set the cloth moves partially in the frame of the attached actor. This feature is useful when the cloth is attached to a fast moving character. In that case the cloth adheres to the shape it is attached to while only velocities below the parameter minAdhereVelocity are used for secondary effects. \return Returns the minimal velocity for cloth to adhere (unit length / s) @see pClothDesc.minAdhereVelocity setMinAdhereVelocity() */ float getMinAdhereVelocity() const; /** \brief Sets an acceleration acting normal to the cloth surface at each vertex. \param[in] acceleration The acceleration vector (unit length / s^2) @see pClothDesc.windAcceleration getWindAcceleration() */ void setWindAcceleration(VxVector acceleration); /** \brief Retrieves the acceleration acting normal to the cloth surface at each vertex. \return The acceleration vector (unit length / s^2) @see pClothDesc.windAcceleration setWindAcceleration() */ VxVector getWindAcceleration() const; /** \brief Returns true if this cloth is sleeping. When a cloth does not move for a period of time, it is no longer simulated in order to save time. This state is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object, or one of its properties is changed by the user, the entire sleep mechanism should be transparent to the user. If a cloth is asleep after the call to NxScene::fetchResults() returns, it is guaranteed that the position of the cloth vertices was not changed. You can use this information to avoid updating dependent objects. \return True if the cloth is sleeping. @see isSleeping() getSleepLinearVelocity() wakeUp() putToSleep() */ bool isSleeping() const; /** \brief Returns the linear velocity below which a cloth may go to sleep. A cloth whose linear velocity is above this threshold will not be put to sleep. @see isSleeping \return The threshold linear velocity for sleeping. @see isSleeping() getSleepLinearVelocity() wakeUp() putToSleep() setSleepLinearVelocity() */ float getSleepLinearVelocity() const; /** \brief Sets the linear velocity below which a cloth may go to sleep. A cloth whose linear velocity is above this threshold will not be put to sleep. If the threshold value is negative, the velocity threshold is set using the NxPhysicsSDK's NX_DEFAULT_SLEEP_LIN_VEL_SQUARED parameter. \param[in] threshold Linear velocity below which a cloth may sleep. <b>Range:</b> (0,inf] @see isSleeping() getSleepLinearVelocity() wakeUp() putToSleep() */ void setSleepLinearVelocity(float threshold); /** \brief Wakes up the cloth if it is sleeping. The wakeCounterValue determines how long until the cloth is put to sleep, a value of zero means that the cloth is sleeping. wakeUp(0) is equivalent to NxCloth::putToSleep(). \param[in] wakeCounterValue New sleep counter value. <b>Range:</b> [0,inf] @see isSleeping() getSleepLinearVelocity() putToSleep() */ void wakeUp(float wakeCounterValue = pSLEEP_INTERVAL); /** \brief Forces the cloth to sleep. The cloth will fall asleep. @see isSleeping() getSleepLinearVelocity() wakeUp() */ void putToSleep(); /** \brief Sets the flags, a combination of the bits defined by the enum ::NxClothFlag. \param[in] flags #NxClothFlag combination. @see pClothDesc.flags NxClothFlag getFlags() */ void setFlags(int flags); /** \brief Retrieves the flags. \return The cloth flags. @see pClothDesc.flags NxClothFlag setFlags() */ int getFlags() const; /** \brief Sets a name string for the object that can be retrieved with getName(). This is for debugging and is not used by the SDK. The string is not copied by the SDK, only the pointer is stored. \param[in] name String to set the objects name to. @see getName() */ void setName(const char* name); /** \brief Applies a force (or impulse) defined in the global coordinate frame, to a particular vertex of the cloth. Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. ::NxForceMode determines if the force is to be conventional or impulsive. \param[in] force Force/impulse to add, defined in the global frame. <b>Range:</b> force vector \param[in] vertexId Number of the vertex to add the force at. <b>Range:</b> position vector \param[in] mode The mode to use when applying the force/impulse (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange) @see ForceMode */ void addForceAtVertex(const VxVector& force, int vertexId, ForceMode mode = FM_Force); /** \brief Applies a radial force (or impulse) at a particular position. All vertices within radius will be affected with a quadratic drop-off. Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. ::NxForceMode determines if the force is to be conventional or impulsive. \param[in] position Position to apply force at. \param[in] magnitude Magnitude of the force/impulse to apply. \param[in] radius The sphere radius in which particles will be affected. <b>Range:</b> position vector \param[in] mode The mode to use when applying the force/impulse (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange). @see ForceMode */ void addForceAtPos(const VxVector& position, float magnitude, float radius, ForceMode mode = FM_Force); /** \brief Applies a directed force (or impulse) at a particular position. All vertices within radius will be affected with a quadratic drop-off. Because forces are reset at the end of every timestep, you can maintain a total external force on an object by calling this once every frame. ::NxForceMode determines if the force is to be conventional or impulsive. \param[in] position Position to apply force at. \param[in] force Force to apply. \param[in] radius The sphere radius in which particles will be affected. <b>Range:</b> position vector \param[in] mode The mode to use when applying the force/impulse (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange). @see ForceMode */ void addDirectedForceAtPos(const VxVector& position, const VxVector& force, float radius, ForceMode mode = FM_Force); /** \brief Finds triangles touching the input bounds. \warning This method returns a pointer to an internal structure using the indices member. Hence the user should use or copy the indices before calling any other API function. \param[in] bounds Bounds to test against in world space. <b>Range:</b> See #NxBounds3 \param[out] nb Retrieves the number of triangle indices touching the AABB. \param[out] indices Returns an array of touching triangle indices. The triangle indices correspond to the triangles referenced to by pClothDesc.meshdata (#NxMeshData). Triangle i has the vertices 3i, 3i+1 and 3i+2 in the array NxMeshData.indicesBegin. \return True if there is an overlap. @see NxBounds3 pClothDesc NxMeshData */ bool overlapAABBTriangles(const NxBounds3& bounds, int& nb, const int*& indices) const; protected: private: NxMeshData *mReceiveBuffers; CK_ID mEntityID; NxCloth *mCloth; NxClothMesh *mClothMesh; pWorld *mWorld; }; /** @} */ #endif<file_sep>/******************************************************************** created: 2003/12/01 filename: H:\XLANG PROJECTS\BASE\INCLUDES\Dll_Tools.h file path: H:\XLANG PROJECTS\BASE\INCLUDES file base: Dll_Tools file ext: h author: <NAME> purpose: rum DLL´eln *********************************************************************/ #ifndef __Dll_Tools_h_ #define __Dll_Tools_h_ "$Id:$" #include <stdlib.h> #include <string> #include <windows.h> ////////////////////////////////////////////////////////////////////////// //ie: // the fnc prototyp : typedef HINSTANCE(WINAPI *_ShellExec_proto)(HWND,const char *,const char*,const char*,const char *,int); // the fill : DLL::DllFunc<_ShellExec_proto>_ShellExec(_T("shell32.dll"),"ShellExecute"); template<class T> class DllFunc { public: DllFunc(const char* dllName, const char* fnName ,const bool logging = TRUE ) : dllHandle( LoadLibrary (dllName) ) , fn(0) { if (!dllHandle && logging) { //loggin @: return; } fn = ( T )GetProcAddress(dllHandle, fnName); if (!fn) { char modName[_MAX_PATH],logmsg [400],_path[_MAX_PATH]; GetModuleFileName( GetModuleHandle(NULL) ,modName,_MAX_PATH ); // loggin @: sprintf ( logmsg , "%s %s %s" , modName , "couldn´t get function with prototyp : ", typeid(fn).name() ) ; sprintf( _path , "%s%s", modName ,".log" ) ; //loggin : return; } } operator T(){ return fn; } public: T fn; HMODULE dllHandle; void *ret; }; #endif //__win32Tools_h_ /* DLL::DynamicFn<_ShellExec_proto>_ShellExec(_T("shell32.dll"),"ShellExecuteA"); // DLL::DynamicFn<ptrM>_ShellExec(_T("shell32.dll"),"ShellExecuteA"); return (*_ShellExec)(NULL,"open","www.gmx.net",NULL,NULL, SW_MAXIMIZE);*/ /* /******************************************************************** created: 2003/12/01 filename: H:\XLANG PROJECTS\BASE\INCLUDES\Dll_Tools.h file path: H:\XLANG PROJECTS\BASE\INCLUDES file base: Dll_Tools file ext: h author: <NAME> purpose: rum DLL´eln *********************************************************************/ #ifndef __Dll_Tools_h_ #define __Dll_Tools_h_ "$Id:$" #include <stdlib.h> #include <string> #include <windows.h> ////////////////////////////////////////////////////////////////////////// //ie: // the fnc prototyp : typedef HINSTANCE(WINAPI *_ShellExec_proto)(HWND,const char *,const char*,const char*,const char *,int); // the fill : DLL::DllFunc<_ShellExec_proto>_ShellExec(_T("shell32.dll"),"ShellExecute"); template<class T> class DllFunc { public: DllFunc(const char* dllName, const char* fnName ,const bool logging = TRUE ) : dllHandle( LoadLibrary (dllName) ) , fn(0) { if (!dllHandle && logging) { char modName[_MAX_PATH],logmsg [400],_path[_MAX_PATH]; GetModuleFileName( GetModuleHandle(NULL) ,modName,_MAX_PATH ); sprintf ( logmsg , "%s %s %s" , modName , "couldn´t find ", dllName ) ; sprintf( _path , "%s%s", modName ,".log" ) ; return; } fn = ( T )GetProcAddress(dllHandle, fnName); if (!fn) { char modName[_MAX_PATH],logmsg [400],_path[_MAX_PATH]; GetModuleFileName( GetModuleHandle(NULL) ,modName,_MAX_PATH ); // loggin sprintf ( logmsg , "%s %s %s" , modName , "couldn´t get function with prototyp : ", typeid(fn).name() ) ; sprintf( _path , "%s%s", modName ,".log" ) ; return; } } operator T(){ return fn; } public: T fn; HMODULE dllHandle; void *ret; }; #endif //__win32Tools_h_ <file_sep>#include "pch.h" #include "CKAll.h" #include "FTP4W.H" CKObjectDeclaration *FillBehaviorSendFileDecl(); CKERROR CreateSendFileProto(CKBehaviorPrototype **pproto); int SendFile(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSendFileDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("Send File"); od->SetDescription(""); od->SetCategory("Narratives/Files"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x637664ae,0x57df7e83)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSendFileProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateSendFileProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Send File"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Start Upload"); proto->DeclareOutput("Upload Started"); proto->DeclareOutput("Finish"); proto->DeclareInParameter("LocalFile", CKPGUID_STRING); proto->DeclareInParameter("RemoteFile", CKPGUID_STRING); proto->DeclareOutParameter("Legth", CKPGUID_INT); proto->DeclareOutParameter("Current Download in Bytes", CKPGUID_INT); proto->DeclareOutParameter("Current Download in %", CKPGUID_PERCENTAGE); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SendFile); *pproto = proto; return CK_OK; } int SendFile(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; int Length=0; // Start by In0 if( beh->IsInputActive(0)){ beh->ActivateInput(0,FALSE); XString LocalFile((CKSTRING) beh->GetInputParameterReadDataPtr(0)); XString RemoteFile((CKSTRING) beh->GetInputParameterReadDataPtr(1)); char *Type = "Type_B"; int Send = FtpSendFile(LocalFile.Str(),RemoteFile.Str(),*Type, FALSE,NULL,NULL); Length = FtpBytesToBeTransferred(); beh->SetOutputParameterValue(0,&Length); beh->ActivateOutput(0); return CKBR_ACTIVATENEXTFRAME; } beh->GetOutputParameterValue(0,&Length); int down=FtpBytesTransferred(); beh->SetOutputParameterValue(1,&down); float progress=(float)(down*100.0f/Length); // percentage of file downloaded progress /=100.0f; beh->SetOutputParameterValue(2,&progress); if ( down == Length){ beh->ActivateOutput(1); return CKBR_OK; } return CKBR_ACTIVATENEXTFRAME; } <file_sep>#include "vtConnection.h" #include "xNetInterface.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "IDistributedObjectsInterface.h" #include "IDistributedClasses.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IMessages.h" #include "xLogger.h" <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "IParameter.h" #include <xDebugTools.h> int pRigidBody::addCollider(pObjectDescr objectDescr,CK3dEntity*srcRefEntity) { int result = 0 ; using namespace vtTools::AttributeTools; CK3dEntity* child = NULL; CKMesh *srcMesh = NULL; if (!srcRefEntity ||!srcRefEntity->GetCurrentMesh()) return 0; bool isChild = vtAgeia::isChildOf(GetVT3DObject(), srcRefEntity); objectDescr.subEntID = srcRefEntity->GetID(); //---------------------------------------------------------------- // // essential values // VxVector box_s = BoxGetZero(srcRefEntity); float radius = 1.0f; radius = srcRefEntity->GetCurrentMesh()->GetRadius(); VxQuaternion refQuad; srcRefEntity->GetQuaternion(&refQuad,GetVT3DObject()); VxVector relPos; srcRefEntity->GetPosition(&relPos,GetVT3DObject()); NxQuat rot = pMath::getFrom(refQuad); srcMesh = srcRefEntity->GetCurrentMesh(); pWheel *wheel =NULL; NxShape *shape = NULL; if (objectDescr.hullType != HT_Wheel) { shape = pFactory::Instance()->createShape(GetVT3DObject(),objectDescr,srcRefEntity,srcMesh,relPos,refQuad); } else { iAssertW( objectDescr.wheel.isValid(),objectDescr.wheel.setToDefault()); iAssertW( objectDescr.wheel.radius.isValid(),objectDescr.wheel.radius.evaluate(srcRefEntity)); shape = pFactory::Instance()->createWheelShape2(GetVT3DObject(),srcRefEntity, objectDescr.wheel ); } if (!shape) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create sub shape!"); return 0; } pSubMeshInfo *sInfo = new pSubMeshInfo(); sInfo->meshID = srcMesh->GetID(); sInfo->mesh =(CKBeObject*)srcMesh; sInfo->entID = srcRefEntity->GetID(); sInfo->refObject = (CKBeObject*)srcRefEntity; sInfo->wheel = NULL; shape->setName(srcRefEntity->GetName()); shape->userData = (void*)sInfo; sInfo->initDescription = objectDescr; getActor()->wakeUp(); if ( (!objectDescr.flags &BF_Hierarchy) ) { return result; } /* //################################################################ // // If more entities in hierarchy, invoke this function recursively // CK3dEntity* subEntity = NULL; while (subEntity= srcRefEntity->HierarchyParser(subEntity) ) { pObjectDescr *subDescr = NULL; //-try old version : if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) { subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); } //-try new version int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); if (subEntity->HasAttribute(attTypePBSetup)) { subDescr = new pObjectDescr(); CKParameterOut *par = subEntity->GetAttributeParameter(attTypePBSetup); IParameter::Instance()->copyTo(subDescr,par); subDescr->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; } if (!subDescr) continue; if (subDescr->flags & BF_SubShape) { ////////////////////////////////////////////////////////////////////////// if (subDescr->hullType != HT_Cloth) { addSubShape(NULL,*subDescr,subEntity); } if (subDescr->hullType == HT_Cloth) { } } } */ return 1; } int pRigidBody::addSubShape( CKMesh *mesh,pObjectDescr& objectDescr,CK3dEntity*srcRefEntity,VxVector localPosition,VxQuaternion localRotation) { int result = 0 ; int att = GetPMan()->GetPAttribute(); int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); bool isNewType = ( objectDescr.version == pObjectDescr::E_OD_VERSION::OD_DECR_V1) ? true : false ; using namespace vtTools::AttributeTools; CK3dEntity* child = NULL; bool isChild = false; while (child = GetVT3DObject()->HierarchyParser(child) ) { if (child == srcRefEntity ) { isChild = true; } } /************************************************************************/ /* parameters for final composition : */ /************************************************************************/ CKMesh *srcMesh = NULL; float density = 0.0f; VxVector mOffset; VxVector sOffset; float skinWidth; int hType = 0; if (!mesh && !srcRefEntity ) { return result; } if (!mesh && srcRefEntity && !srcRefEntity->GetCurrentMesh() ) { return result; } CKBeObject *attObject = NULL; if (mesh && (mesh->HasAttribute(att) || isNewType) ) { attObject = (CKBeObject*)mesh; } if (srcRefEntity && (srcRefEntity->HasAttribute(att) || isNewType ) ) { attObject = (CKBeObject*)srcRefEntity; } //################################################################ // // Fill sub shapes object description. // if (attObject && !isNewType ) //we have attribute values: { objectDescr.density = GetValueFromAttribute<float>(attObject ,att, E_PPS_DENSITY); objectDescr.massOffset= GetValueFromAttribute<VxVector>(attObject ,att, E_PPS_MASS_OFFSET); objectDescr.shapeOffset = GetValueFromAttribute<VxVector>(attObject ,att, E_PPS_SHAPE_OFFSET); objectDescr.skinWidth = GetValueFromAttribute<float>(attObject,att, E_PPS_SKIN_WIDTH); objectDescr.hullType = GetValueFromAttribute<HullType>(attObject,att,E_PPS_HULLTYPE); objectDescr.hirarchy = GetValueFromAttribute<int>(attObject,att,E_PPS_HIRARCHY); objectDescr.collisionGroup = GetValueFromAttribute<int>(attObject,att,E_PPS_COLL_GROUP); objectDescr.newDensity = GetValueFromAttribute<int>(attObject,att,E_PPS_NEW_DENSITY); objectDescr.totalMass = GetValueFromAttribute<int>(attObject,att,E_PPS_TOTAL_MASS); } if (srcRefEntity) { objectDescr.subEntID = srcRefEntity->GetID(); } //################################################################ // // Transformation values // VxVector box_s; if (!mesh && srcRefEntity) { box_s = BoxGetZero(srcRefEntity); } if (!srcRefEntity && mesh) { box_s = mesh->GetLocalBox().GetSize(); } if (srcRefEntity && mesh ) { box_s = mesh->GetLocalBox().GetSize(); } //################################################################ // // Determine radius // float radius = 1.0f; if ( mesh && !srcRefEntity ) { radius = mesh->GetRadius(); } if (!mesh && srcRefEntity && srcRefEntity->GetCurrentMesh() ) { radius = srcRefEntity->GetCurrentMesh()->GetRadius(); } if (mesh && srcRefEntity) { radius = mesh->GetRadius(); } //################################################################ // // Calculate destination matrix // VxMatrix v_matrix ; VxVector pos,scale; VxQuaternion quat; if (srcRefEntity) { if (isChild) { v_matrix = srcRefEntity->GetLocalMatrix(); }else { v_matrix = srcRefEntity->GetWorldMatrix(); } } Vx3DDecomposeMatrix(v_matrix,quat,pos,scale); if (mesh && !srcRefEntity) { pos = localPosition; quat = localRotation; } if (mesh && srcRefEntity ) { VxQuaternion refQuad2; srcRefEntity->GetQuaternion(&refQuad2,GetVT3DObject()); VxVector relPos; srcRefEntity->GetPosition(&relPos,GetVT3DObject()); if (!isChild) { pos = relPos; quat = refQuad2; } } if (!mesh && srcRefEntity ) { VxVector relPos; srcRefEntity->GetPosition(&relPos,GetVT3DObject()); VxQuaternion refQuad2; srcRefEntity->GetQuaternion(&refQuad2,GetVT3DObject()); pos = relPos; quat = refQuad2; } NxQuat rot = pMath::getFrom(quat); //################################################################ // // Determine the mesh // if (mesh && srcRefEntity==NULL ) { srcMesh = mesh; } if (!mesh && srcRefEntity && srcRefEntity->GetCurrentMesh() ) { srcMesh = srcRefEntity->GetCurrentMesh(); } if (mesh && srcRefEntity && srcRefEntity->GetCurrentMesh()) { srcMesh = mesh; } CK_ID srcID = 0 ; if (srcMesh) { srcID = srcMesh->GetID(); } //################################################################ // // Create the final sub shape // pSubMeshInfo *sInfo = new pSubMeshInfo(); bool isWheel1 = false; pWheel *wheel =NULL; NxShape *shape = NULL; if (objectDescr.hullType != HT_Wheel) { shape = pFactory::Instance()->createShape(GetVT3DObject(),objectDescr,srcRefEntity,srcMesh,pos,quat); }else { wheel = pFactory::Instance()->createWheelSubShape(this,srcRefEntity,srcMesh,&objectDescr,pos,quat,shape); if (wheel) { sInfo->wheel = wheel; pWheel1* w1 = dynamic_cast<pWheel1*>(wheel); if (w1){ isWheel1 = true; shape = (NxShape*)w1->getWheelConvex(); } pWheel2* w2 = dynamic_cast<pWheel2*>(wheel); if (w2) { shape =(NxShape*)w2->getWheelShape(); } }else { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Creating wheel sub shape failed"); return NULL; } } if (!shape) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create sub shape!"); } if (shape) { //################################################################ // // Setup the material // int materialIndex = 0; pMaterial bMaterial; bool hasMaterial = pFactory::Instance()->findSettings(bMaterial,srcRefEntity); if (!hasMaterial) { hasMaterial = pFactory::Instance()->findSettings(bMaterial,mesh); } if (hasMaterial) { NxMaterialDesc nxMatDescr; pFactory::Instance()->copyTo(nxMatDescr,bMaterial); NxMaterial *nxMaterial = getWorld()->getScene()->createMaterial(nxMatDescr); if (nxMaterial) { materialIndex = nxMaterial->getMaterialIndex(); nxMaterial->userData = (void*)&bMaterial; } }else { materialIndex = getWorld()->getDefaultMaterial()->getMaterialIndex(); } shape->setMaterial(materialIndex); //################################################################ // // Store meta info in shape user data. // shape->setGroup(objectDescr.collisionGroup); if (srcMesh) { sInfo->meshID = srcMesh->GetID(); sInfo->mesh =(CKBeObject*)srcMesh; shape->setName(srcMesh->GetName()); } if(srcRefEntity) { sInfo->entID = srcRefEntity->GetID(); sInfo->refObject = (CKBeObject*)srcRefEntity; shape->setName(srcRefEntity->GetName()); } shape->userData = (void*)sInfo; } //################################################################ // // Wheel Type one has an additional capsule swept shape // We store the shape meta data there as well if ( isWheel1 && wheel && dynamic_cast<pWheel1*>(wheel) && (pWheel1*)(dynamic_cast<pWheel1*>(wheel))->getWheelCapsule() ) { ((pWheel1*)(dynamic_cast<pWheel1*>(wheel)))->getWheelCapsule()->userData = sInfo; } //################################################################ // // Modify mass // if (objectDescr.mass.newDensity!=0.0f || objectDescr.mass.totalMass!=0.0f ) { getActor()->updateMassFromShapes(objectDescr.mass.newDensity,objectDescr.mass.totalMass); } //################################################################ // // Post routine // getActor()->wakeUp(); if(mesh) return result; if (!objectDescr.hirarchy) { return result; } if (!srcRefEntity) { return result; } //################################################################ // // If more entities in hierarchy, invoke this function recursively // CK3dEntity* subEntity = NULL; while (subEntity= srcRefEntity->HierarchyParser(subEntity) ) { pObjectDescr *subDescr = NULL; //-try old version : if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) { subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); } //-try new version int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); if (subEntity->HasAttribute(attTypePBSetup)) { subDescr = new pObjectDescr(); CKParameterOut *par = subEntity->GetAttributeParameter(attTypePBSetup); IParameter::Instance()->copyTo(subDescr,par); subDescr->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; } if (!subDescr) continue; if (subDescr->flags & BF_SubShape) { ////////////////////////////////////////////////////////////////////////// if (subDescr->hullType != HT_Cloth) { addSubShape(NULL,*subDescr,subEntity); } if (subDescr->hullType == HT_Cloth) { } } } return result; } void pRigidBody::setBoxDimensions( const VxVector&dimension,CKBeObject* subShapeReference/*=NULL*/ ) { if (!isValid() || !getMainShape() ) { return; } /// shape is specified -> modify bodies first shape : if (subShapeReference == NULL) { NxBoxShape *box = static_cast<NxBoxShape*>(getMainShape()->isBox()); if (!box) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); return; } box->setDimensions(getFrom(dimension)); } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try an mesh : s = _getSubShape(subShapeReference->GetID()); } NxBoxShape *box = static_cast<NxBoxShape*>(s->isBox()); if (!box) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); return; } box->setDimensions(getFrom(dimension)); } } VxVector pRigidBody::getBoxDimensions(CKBeObject* subShapeReference) { VxVector result(-1.f,-1.f,-1.f); if (!isValid() || !getMainShape() ) { return result; } /// shape is specified -> modify bodies first shape : if (subShapeReference == NULL) { NxBoxShape *box = static_cast<NxBoxShape*>(getMainShape()->isBox()); if (!box) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); return result; } return getFrom(box->getDimensions()); } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try an mesh : s = _getSubShape(subShapeReference->GetID()); } NxBoxShape *box = static_cast<NxBoxShape*>(s->isBox()); if (!box) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); return result; } getFrom(box->getDimensions()); } return result; } void pRigidBody::setSphereRadius(float radius,CKBeObject* subShapeReference/* =NULL */) { if (!isValid() || !getMainShape() ) { return; } /// shape is specified -> modify bodies first shape : if (subShapeReference == NULL) { NxSphereShape *sphere = static_cast<NxSphereShape*>(getMainShape()->isSphere()); if (!sphere) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); return; } sphere->setRadius(radius); } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try an mesh : s = _getSubShape(subShapeReference->GetID()); } NxSphereShape*sphere = static_cast<NxSphereShape*>(s->isSphere()); if (!sphere) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); return; } sphere->setRadius(radius); } } float pRigidBody::getSphereRadius(CKBeObject* subShapeReference/* =NULL */) { if (!isValid() || !getMainShape() ) { return -1.0f; } /// shape is specified -> modify bodies first shape : if (subShapeReference == NULL) { NxSphereShape *sphere = static_cast<NxSphereShape*>(getMainShape()->isSphere()); if (!sphere) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); return -1.0f; } return sphere->getRadius(); } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try an mesh : s = _getSubShape(subShapeReference->GetID()); } NxSphereShape*sphere = static_cast<NxSphereShape*>(s->isSphere()); if (!sphere) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); return -1.0f; } return sphere->getRadius(); } return -1.0f; } void pRigidBody::setCapsuleDimensions(float radius,float length,CKBeObject* subShapeReference) { if (!isValid() || !getMainShape() ) { return; } /// shape is specified -> modify bodies first shape : if (subShapeReference == NULL) { NxCapsuleShape *capsule = static_cast<NxCapsuleShape*>(getMainShape()->isCapsule()); if (!capsule) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); return; } capsule->setHeight(length); capsule->setRadius(radius); } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try an mesh : s = _getSubShape(subShapeReference->GetID()); } NxCapsuleShape*capsule = static_cast<NxCapsuleShape*>(s->isCapsule()); if (!capsule) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); return; } capsule->setHeight(length); capsule->setRadius(radius); } } void pRigidBody::getCapsuleDimensions(float& radius,float& length,CKBeObject* subShapeReference) { if (!isValid() || !getMainShape() ) { return; } /// shape is specified -> modify bodies first shape : if (subShapeReference == NULL) { NxCapsuleShape *capsule = static_cast<NxCapsuleShape*>(getMainShape()->isCapsule()); if (!capsule) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); radius = -1.0f; length = -1.0f; return; } radius = capsule->getRadius(); length = capsule->getHeight(); } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try a mesh : s = _getSubShape(subShapeReference->GetID()); } NxCapsuleShape*capsule = static_cast<NxCapsuleShape*>(s->isCapsule()); if (!capsule) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); radius = -1.0f; length = -1.0f; return; } radius = capsule->getRadius(); length = capsule->getHeight(); } } HullType pRigidBody::getShapeType(CKBeObject* subShapeReference) { if (!isValid() || !getMainShape() ) { return HT_Unknown; } /// shape is specified -> modify bodies first shape : if (subShapeReference == NULL) { return (HullType)vtAgeia::getHullTypeFromShape(getMainShape()); } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try a mesh : s = _getSubShape(subShapeReference->GetID()); } if (!s) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"couldn't find sub shape!"); return HT_Unknown; } return (HullType)vtAgeia::getHullTypeFromShape(s); } return HT_Unknown; } float pRigidBody::getSkinWidth(CKBeObject* subShapeReference) { if (!isValid() || !getMainShape() ) { return -1.0f; } /// shape is specified -> modify bodies first shape : if (subShapeReference == NULL && !getMainShape() ) { return mSkinWidth; } if(subShapeReference == NULL && getMainShape() ) { return getMainShape()->getSkinWidth(); } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try a mesh : s = _getSubShape(subShapeReference->GetID()); } if (!s) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"couldn't find sub shape!"); return -1.0f; } return s->getSkinWidth(); } return -1.0f; } void pRigidBody::setSkinWidth(const float skinWidth,CKBeObject* subShapeReference) { if (!isValid() || !getMainShape() ) { mSkinWidth = mSkinWidth; return; } /// shape is specified -> modify bodies first shape : if (subShapeReference == NULL && !getMainShape() ) { mSkinWidth = skinWidth; } if(subShapeReference == NULL && getMainShape() ) { getMainShape()->setSkinWidth(skinWidth); } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try a mesh : s = _getSubShape(subShapeReference->GetID()); } if (!s) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"couldn't find sub shape!"); return; } s->setSkinWidth(skinWidth); } } int pRigidBody::removeSubShape( CKBeObject *reference,float newensity/*=0.0f*/,float totalMass/*=0.0f*/ ) { int result = -1; if (!reference || !getActor()) { return result; } NxShape *subShape = NULL; bool found = false; while(subShape = _getSubShape(reference->GetID())) { getActor()->releaseShape(*subShape); found =true; } ////////////////////////////////////////////////////////////////////////// if (!found) { while(subShape = _getSubShape(reference->GetID())) { getActor()->releaseShape(*subShape); found =true; } } if (found && newensity !=0.0f || totalMass!=0.0f ) { getActor()->updateMassFromShapes(newensity,totalMass); } getActor()->wakeUp(); return 1; } NxShape * pRigidBody::_getSubShapeByEntityID( CK_ID id ) { if (!getActor()) { return NULL; } int nbShapes = getActor()->getNbShapes(); NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *sinfo = static_cast<pSubMeshInfo*>(s->userData); if (sinfo && sinfo->entID == id) { return s; } } } return NULL; } bool pRigidBody::isSubShape(CKBeObject *object) { bool result = false; if (!object) { return result; } if ( _getSubShape(object->GetID()) || _getSubShapeByEntityID(object->GetID() )) { return true ; } return result; } NxShape *pRigidBody::_getSubShape(CK_ID meshID) { if (!getActor()) { return NULL; } int nbShapes = getActor()->getNbShapes(); NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *sinfo = static_cast<pSubMeshInfo*>(s->userData); if (sinfo && sinfo->meshID == meshID) { return s; } } } return NULL; } int pRigidBody::updateMassFromShapes( float density, float totalMass ) { if (getActor()) { return getActor()->updateMassFromShapes(density,totalMass); } return -1; } NxShape *pRigidBody::getShapeByIndex(int index/* =0 */) { NxU32 nbShapes = getActor()->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s && j == index) { return s; } } } return NULL; } bool pRigidBody::isCollisionEnabled( CK3dEntity* subShapeReference/*=NULL*/ ) { NxShape *subShape = getSubShape(subShapeReference); if (subShape ) { if (subShape ==getMainShape()) { if (getActor()) { return !getActor()->readActorFlag(NX_AF_DISABLE_COLLISION); } }else{ return !subShape->getFlag(NX_SF_DISABLE_COLLISION); } } return false; } void pRigidBody::enableCollision( bool enable,CK3dEntity* subShapeReference/*=NULL*/ ) { NxShape *subShape = getSubShape(subShapeReference); if (!subShape) { subShape==getMainShape(); } if (subShape ) { if (subShape ==getMainShape()) { if (!enable) { getActor()->raiseActorFlag(NX_AF_DISABLE_COLLISION); }else { getActor()->clearActorFlag(NX_AF_DISABLE_COLLISION); } }else{ subShape->setFlag(NX_SF_DISABLE_RESPONSE, !enable ); } } } void pRigidBody::enableTriggerShape( bool enable,CK3dEntity* subShapeReference/*=NULL*/ ) { NxShape *subShape = getSubShape(subShapeReference); if (subShape) { subShape->setFlag(NX_TRIGGER_ENABLE,enable); } } bool pRigidBody::isTriggerShape( CK3dEntity* subShapeReference/*=NULL*/ ) { NxShape *subShape = getSubShape(subShapeReference); if (subShape) { return subShape->getFlag(NX_TRIGGER_ENABLE); } return false; } bool pRigidBody::isCollisionsNotifyEnabled() { return ( getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ); } void pRigidBody::enableCollisionsNotify( bool enable ) { if (enable) { getActor()->setContactReportFlags(NX_NOTIFY_ON_TOUCH); }else getActor()->setContactReportFlags(NX_IGNORE_PAIR); } void pRigidBody::enableContactModification(bool enable) { int& flags = m_sFlags; if (getActor()) { if (enable){ getActor()->raiseActorFlag(NX_AF_CONTACT_MODIFICATION); flags|=BF_ContactModify; } else{ getActor()->clearActorFlag(NX_AF_CONTACT_MODIFICATION); flags&=~(BF_ContactModify); } } } void pRigidBody::enableCollisionForceCalculation(bool enable,CK3dEntity* subShapeReference/* =NULL */) { NxShape *subShape = getSubShape(subShapeReference); if (subShape) { int o = subShape->getFlag(NX_SF_POINT_CONTACT_FORCE); subShape->setFlag(NX_SF_POINT_CONTACT_FORCE,enable); int o2 = subShape->getFlag(NX_SF_POINT_CONTACT_FORCE); int o3 = subShape->getFlag(NX_SF_POINT_CONTACT_FORCE); } } VxVector pRigidBody::getPivotOffset(CK3dEntity*shapeReference) { NxShape *subshape = getSubShape(shapeReference); if (subshape) return getFrom(subshape->getLocalPosition()); return VxVector(); } NxShape*pRigidBody::getSubShape(CK3dEntity*shapeReference/* =NULL */) { if (shapeReference) { NxShape *inputShape = _getSubShapeByEntityID(shapeReference->GetID()); if (getMainShape() ==inputShape) { return getMainShape(); }else{ return inputShape; } } return getMainShape(); } void pRigidBody::setShapeMaterial(pMaterial&material,CK3dEntity*shapeReference/* =NULL */) { NxShape *dstShape = NULL; if (shapeReference) { dstShape = _getSubShapeByEntityID(shapeReference->GetID()); }else{ dstShape = getMainShape(); } #ifdef _DEBUG assert(dstShape); #endif int materialIndex = dstShape->getMaterial(); NxMaterial *currentMaterial = getActor()->getScene().getMaterialFromIndex(materialIndex); if (!material.isValid()) return; NxMaterialDesc nxMatDescr; ////////////////////////////////////////////////////////////////////////// // // We dont alter the default material ! We create a new one !! // int defaultID = getWorld()->getDefaultMaterial()->getMaterialIndex(); if ( !currentMaterial || materialIndex ==0 || materialIndex == getWorld()->getDefaultMaterial()->getMaterialIndex() ) { pFactory::Instance()->copyTo(nxMatDescr,material); NxMaterial *newMaterial = getActor()->getScene().createMaterial(nxMatDescr); if (newMaterial){ dstShape->setMaterial(newMaterial->getMaterialIndex()); newMaterial->userData = (void*)&material; } } else { pFactory::Instance()->copyTo(nxMatDescr,material); currentMaterial->loadFromDesc(nxMatDescr); //currentMaterial->userData = (void*)&material; } } pMaterial&pRigidBody::getShapeMaterial(CK3dEntity *shapeReference/* =NULL */) { pMaterial result; if (shapeReference && !isSubShape(shapeReference)) { return result; } NxShape *srcShape = NULL; CK3dEntity *ent = GetVT3DObject(); if (shapeReference) { srcShape = getSubShape(shapeReference); }else{ srcShape = getMainShape(); } #ifdef _DEBUG assert(srcShape); #endif int index = srcShape->getMaterial(); NxMaterial *mat = getActor()->getScene().getMaterialFromIndex(srcShape->getMaterial()); pFactory::Instance()->copyTo(result,getActor()->getScene().getMaterialFromIndex(srcShape->getMaterial())); return result; } void pRigidBody::_checkForRemovedSubShapes() { } void pRigidBody::_checkForNewSubShapes() { pObjectDescr *oDescr = pFactory::Instance()->createPObjectDescrFromParameter(GetVT3DObject()->GetAttributeParameter(GetPMan()->GetPAttribute())); if (!oDescr) { return; } if (! ( getFlags() & BF_Hierarchy ) ) { return ; } CK3dEntity* subEntity = NULL; while (subEntity= GetVT3DObject()->HierarchyParser(subEntity) ) { if ( !_getSubShapeByEntityID(subEntity->GetID()) ) { CKSTRING name = subEntity->GetName(); int s = isSubShape(subEntity); if ( subEntity->HasAttribute(GetPMan()->GetPAttribute() ) ) { pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); if (subDescr->flags & BF_SubShape) { if (subDescr->hullType != HT_Cloth) { addSubShape(NULL,*oDescr,subEntity); } if (subDescr->hullType == HT_Cloth) { //pClothDesc *cloth = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); } } } } } if (( getFlags() & BF_Hierarchy )) { if (oDescr->newDensity!=0.0f || oDescr->totalMass!=0.0f ) { updateMassFromShapes(oDescr->newDensity,oDescr->totalMass); } } } int pRigidBody::updateSubShape(bool fromPhysicToVirtools/* =true */,bool position/* =true */,bool rotation/* =true */,CK3dEntity *childObject/* =NULL */,bool hierarchy/* =true */) { if(!getActor()) return -1; NxU32 nbShapes = getActor()->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *info = static_cast<pSubMeshInfo*>(s->userData); if (info) { CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(info->entID)); if (ent) { if (s == getMainShape()) continue; if (fromPhysicToVirtools) { //pVehicle *v =getVehicle(); pWheel* wheel = (pWheel*)getWheel(ent); if (wheel) { wheel->_updateVirtoolsEntity(position,rotation); }else { if (position) { VxVector gPos = getFrom(s->getLocalPose().t); ent->SetPosition(&gPos,GetVT3DObject()); } if (rotation) { VxQuaternion rot = pMath::getFrom( s->getLocalPose().M ); if(s->isWheel()) { }else { ent->SetQuaternion(&rot,GetVT3DObject()); } } } }else//Virtools to Ageia ! { if (position) { VxVector relPos; ent->GetPosition(&relPos,GetVT3DObject()); s->setLocalPosition(getFrom(relPos)); } if (rotation) { VxQuaternion refQuad2; ent->GetQuaternion(&refQuad2,GetVT3DObject()); s->setLocalOrientation(getFrom(refQuad2)); } } } } } } } return 0; } int pRigidBody::updateSubShapes(bool fromPhysicToVirtools/* = true */,bool position/* =true */,bool rotation/* =true */,CK3dEntity *childObject) { if(!getActor()) return -1; NxU32 nbShapes = getActor()->getNbShapes(); if ( nbShapes ) { bool hierarchy = (getFlags() & BF_Hierarchy ) ? true : false; NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *info = static_cast<pSubMeshInfo*>(s->userData); if (info) { CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(info->entID)); if (ent) { if (fromPhysicToVirtools) { //pVehicle *v =getVehicle(); pWheel* wheel = (pWheel*)getWheel(ent); if (wheel) { wheel->_updateVirtoolsEntity(position,rotation); }else { if (position) { if ( s != getMainShape()){ VxVector gPos = getFrom(s->getLocalPose().t); ent->SetPosition(&gPos,GetVT3DObject()); }else { { VxVector gPos = getFrom(s->getGlobalPose().t); ent->SetPosition(&gPos,NULL,!hierarchy); /*pivot correction*/ VxVector diff = getFrom(s->getLocalPosition()); if (XAbs(diff.SquareMagnitude()) > 0.01f) { diff *=-1.0f; ent->SetPosition(&diff,ent,!hierarchy); } } } } if (rotation) { if ( s != getMainShape()){ VxQuaternion rot = pMath::getFrom( s->getLocalPose().M ); ent->SetQuaternion(&rot,GetVT3DObject()); }else{ VxQuaternion rot = pMath::getFrom( s->getGlobalPose().M ); ent->SetQuaternion(&rot,NULL,!hierarchy); } } } }else//Virtools to Ageia ! { if (position) { VxVector relPos; ent->GetPosition(&relPos,GetVT3DObject()); s->setLocalPosition(getFrom(relPos)); //onKinematicMove(fromPhysicToVirtools,position,false,childObject); } if (rotation) { VxQuaternion refQuad2; ent->GetQuaternion(&refQuad2,GetVT3DObject()); s->setLocalOrientation(getFrom(refQuad2)); } } } } } } } return 0; } int pRigidBody::getCollisionsGroup( CK3dEntity* subShapeReference/*=NULL*/ ) { NxShape *subShape = getSubShape(subShapeReference); if (subShape) { return subShape->getGroup(); } return -1; } void pRigidBody::setCollisionsGroup( int index,CK3dEntity* subShapeReference/*=NULL*/ ) { if(!getActor()) return; if (subShapeReference == NULL) { if(index>=0 && index <=32) getActor()->setGroup(index); NxU32 nbShapes = getActor()->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { if(index>=0 && index <=32) s->setGroup(index); } } } } // shape reference is specified - > modify sub shape : if (subShapeReference !=NULL && isSubShape(subShapeReference) ) { // try an entity : NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); if (!s) { //try an mesh : s = _getSubShape(subShapeReference->GetID()); } if (!s) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"there is no such sub shape!"); return; } s->setGroup(index); } } void pRigidBody::setGroupsMask(CK3dEntity *shapeReference,const pGroupsMask& mask) { NxShape *mainshape = getMainShape(); NxShape *dstShape = getMainShape(); if (shapeReference) { NxShape *inputShape = _getSubShapeByEntityID(shapeReference->GetID()); if (mainshape==inputShape) { dstShape = mainshape; }else{ dstShape = inputShape; } } NxGroupsMask mask1; mask1.bits0 = mask.bits0; mask1.bits1 = mask.bits1; mask1.bits2 = mask.bits2; mask1.bits3 = mask.bits3; if (dstShape) { dstShape->setGroupsMask(mask1); } } pGroupsMask pRigidBody::getGroupsMask(CK3dEntity *shapeReference) { NxShape *mainshape = getMainShape(); NxShape *dstShape = getMainShape(); if (shapeReference) { NxShape *inputShape = _getSubShapeByEntityID(shapeReference->GetID()); if (mainshape==inputShape) { dstShape = mainshape; }else{ dstShape = inputShape; } } if (dstShape) { NxGroupsMask gMask = dstShape->getGroupsMask(); pGroupsMask vtGMask; vtGMask.bits0 = gMask.bits0; vtGMask.bits1 = gMask.bits1; vtGMask.bits2 = gMask.bits2; vtGMask.bits3 = gMask.bits3; return vtGMask; } return pGroupsMask(); } /* if (srcRefEntity && srcRefEntity->HasAttribute(GetPMan()->att_wheelDescr )) { CKParameterOut *par = srcRefEntity->GetAttributeParameter(GetPMan()->att_wheelDescr ); if (par) { pWheelDescr *wDescr = new pWheelDescr(); int err = pFactory::Instance()->copyTo(wDescr,par); if (wDescr && !wDescr->isValid() ) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Wheel Description was invalid"); delete wDescr; } if (wDescr) { pWheel *wheel = pFactory::Instance()->createWheel(this,*wDescr); shape = pFactory::Instance()->createWheelShape(getActor(),&objectDescr,wDescr,srcRefEntity,srcMesh,pos,quat); if (shape) { if(wDescr->wheelFlags & E_WF_USE_WHEELSHAPE) { pWheel2 * wheel2 = (pWheel2*)wheel; wheel2->setWheelShape((NxWheelShape*)shape); }else{ } if (wheel->getWheelFlag(E_WF_VEHICLE_CONTROLLED) && mVehicle) mVehicle->getWheels().push_back(wheel); wheel->mWheelFlags = wDescr->wheelFlags; sInfo->wheel = wheel; wheel->setEntID(srcRefEntity->GetID()); } } } } */<file_sep>// DistributedNetworkClassDialogToolbarDlg.cpp : implementation file // #include "stdafx.h" #include "DistributedNetworkClassDialogEditor.h" #include "DistributedNetworkClassDialogToolbarDlg.h" #ifdef _MFCDEBUGNEW #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif DllToolbarDlg* fCreateToolbarDlg(HWND parent) { HRESULT r = CreateDllDialog(parent,IDD_TOOLBAR,&g_Toolbar); return (DllToolbarDlg*)g_Toolbar; } ///////////////////////////////////////////////////////////////////////////// // DistributedNetworkClassDialogToolbarDlg dialog DistributedNetworkClassDialogToolbarDlg::DistributedNetworkClassDialogToolbarDlg(CWnd* pParent /*=NULL*/) : DllToolbarDlg(DistributedNetworkClassDialogToolbarDlg::IDD, pParent) { //{{AFX_DATA_INIT(DistributedNetworkClassDialogToolbarDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void DistributedNetworkClassDialogToolbarDlg::DoDataExchange(CDataExchange* pDX) { DllToolbarDlg::DoDataExchange(pDX); //{{AFX_DATA_MAP(DistributedNetworkClassDialogToolbarDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(DistributedNetworkClassDialogToolbarDlg, DllToolbarDlg) //{{AFX_MSG_MAP(DistributedNetworkClassDialogToolbarDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // DistributedNetworkClassDialogToolbarDlg message handlers BOOL DistributedNetworkClassDialogToolbarDlg::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class return DllToolbarDlg::PreTranslateMessage(pMsg); } BOOL DistributedNetworkClassDialogToolbarDlg::OnInitDialog() { DllToolbarDlg::OnInitDialog(); // TODO: Add extra initialization here ActivateClosebutton(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } //this is the almost equivalent of OnInitDialog you should use if you want to //use the PluginInterface with GetInterface or if you want to be sure the editor is present void DistributedNetworkClassDialogToolbarDlg::OnInterfaceInit() { } //called on WM_DESTROY void DistributedNetworkClassDialogToolbarDlg::OnInterfaceEnd() { } HRESULT DistributedNetworkClassDialogToolbarDlg::ReceiveNotification(UINT MsgID,DWORD Param1,DWORD Param2,CKScene* Context) { return 0; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "IParameter.h" #include <xDebugTools.h> bool pPivotSettings::isValid() { return true; } bool pObjectDescr::setToDefault() { hullType =HT_Sphere; density = 1.0f; massOffset = VxVector(); shapeOffset = VxVector(); flags = (BodyFlags)0; skinWidth =0.0f; newDensity = 0.0f; totalMass = 0.0f; collisionGroup = 0; hirarchy = 0; subEntID = -1; transformationFlags = 0; worlReference = 0; internalXmlID = externalXmlID = xmlImportFlags = 0; massOffsetReference = 0; pivotOffsetReference = 0; ccdMotionThresold = 0.0; ccdFlags = 0 ; ccdMeshReference =NULL; ccdScale = 1.0f; linearDamping = angularDamping = 0.0f; linearSleepVelocity = angularSleepVelocity = sleepingEnergyThresold = 0.0f; solverIterations = dominanceGroups = compartmentID = 0; version = OD_DECR_V0; mask = (pObjectDescrMask)0; groupsMask.bits0=0; groupsMask.bits1=0; groupsMask.bits2=0; groupsMask.bits3=0; wheel.setToDefault(); optimization.setToDefault(); material.setToDefault(); collision.setToDefault(); pivot.setToDefault(); //mass.setToDefault(); ccd.setToDefault(); return true; } bool pCollisionSettings::setToDefault() { collisionGroup = 0; collisionGroup = 0; skinWidth = 0.025f; return true; } bool pPivotSettings::setToDefault() { pivotReference = 0; return true; } bool pCCDSettings::setToDefault() { motionThresold = 0.0; flags = 0 ; meshReference =0; scale = 1.0f; return true; } bool pOptimization::setToDefault() { transformationFlags = (BodyLockFlags)0; linDamping = angDamping = 0.0f; solverIterations = 24 ; dominanceGroup=0; compartmentGroup=0; sleepEnergyThreshold =0.0f; linSleepVelocity = angSleepVelocity = 0.0; return true; } bool pOptimization::isValid() { bool result = true; iAssertWR( X_IS_BETWEEN(solverIterations,1,255) ,solverIterations=24,result ); iAssertWR( !(linDamping < 0) ,"",result ); iAssertWR( !(angDamping< 0) ,"",result ); iAssertWR( !(transformationFlags < 0) ,transformationFlags=((BodyLockFlags)0),result ); iAssertWR( !(linSleepVelocity < 0) ,"",result ); iAssertWR( !(angSleepVelocity < 0) ,"",result ); return true; } bool pMaterial::isValid() { bool result = true; iAssertWR( !(dynamicFriction < 0.0f) ,"",result ); iAssertWR( !(staticFriction < 0.0f) ,"",result ); iAssertWR( !(restitution < 0.0f || restitution > 1.0f) ,"",result ); if (flags & 1) { float sMagnitude = dirOfAnisotropy.SquareMagnitude(); iAssertWR( sMagnitude > 0.98f || sMagnitude < 1.03f ,"",result ); iAssertWR( !(dynamicFrictionV < 0.0f) ,"",result ); iAssertWR( !(staticFrictionV < 0.0f) ,"",result ); } iAssertWR( frictionCombineMode <= 4 ,"",result ); iAssertWR( restitutionCombineMode <= 4 ,"",result ); return result; } bool pConvexCylinderSettings::setToDefault() { radius.setToDefault(); height.setToDefault(); approximation = 4; downAxis.Set(0,-1,0); rightAxis.Set(1,0,0); forwardAxis.Set(0,0,1); convexFlags = CF_ComputeConvex; return true; } bool pConvexCylinderSettings::isValid() { bool result=true; iAssertWR(radius.isValid(),"",result); iAssertWR(height.isValid(),"",result); iAssertWR(approximation >= 4 && approximation > 0,"",result); iAssertWR( XAbs(forwardAxis.SquareMagnitude()) > 0.1f || forwardAxisRef,"",result); iAssertWR( XAbs(downAxis.SquareMagnitude()) > 0.1f || downAxisRef,"",result); iAssertWR( XAbs(rightAxis.SquareMagnitude()) > 0.1f || rightAxisRef,"",result); return result; } bool pAxisReferencedLength::isValid() { return ( referenceAxis<3 && referenceAxis >=0) && (value > 0.0f || reference ) ; } bool pAxisReferencedLength::evaluate(CKBeObject *referenceObject) { if (!reference && referenceObject) { this->reference = referenceObject; } if (reference) { VxVector size; if (reference->GetClassID() == CKCID_3DOBJECT ) { CK3dEntity *ent = (CK3dEntity*)reference; if (ent && ent->GetCurrentMesh() ) size = ent->GetCurrentMesh()->GetLocalBox().GetSize(); } else if(reference->GetClassID() == CKCID_MESH) { CKMesh *mesh = (CKMesh*)reference; if (mesh) { size = mesh->GetLocalBox().GetSize(); } } value = size[referenceAxis]; return XAbs(size.SquareMagnitude()) >0.0f; } return false; } bool pAxisReferencedLength::setToDefault() { value=0.0f; referenceAxis = 0; reference = NULL; return true; } bool pCapsuleSettingsEx::setToDefault() { radius.setToDefault(); height.setToDefault(); return true; } bool pCapsuleSettingsEx::isValid() { return radius.isValid() && height.isValid(); } <file_sep>#include "pDifferential.h" void pDifferential::setToDefault() { type = 1; SetRatio(2.53f); SetInertia(0.15f); lockingCoeff = 275.0f; } pDifferential::pDifferential(pVehicle *_car) : pDriveLineComp() { SetName("differential"); car=_car; type=FREE; lockingCoeff=0; powerAngle=coastAngle=0; clutches=0; clutchFactor=0; flags=0; Reset(); setToDefault(); } pDifferential::~pDifferential() { } void pDifferential::Reset() { torqueIn=0; torqueOut[0]=torqueOut[1]=0; torqueBrakingOut[0]=torqueBrakingOut[1]=0; inertiaIn=0; inertiaOut[0]=inertiaOut[1]=0; accIn=0; accOut[0]=accOut[1]=0; torqueLock=0; rotVdriveShaft=0; velASymmetric=0; locked=0; engine=0; wheel[0]=wheel[1]=0; pDriveLineComp::Reset(); } /******** * Input * ********/ void pDifferential::Lock(int wheel) // Lock a side (0 or 1) // The wheel calls this function as soon as it sees rotational // velocity reversal (the wheel from moving forward suddenly starts // moving backward due to (mostly) braking or rolling resistance) // In CalcForces(), the side can be unlocked again if the reaction // torques exceed the (potential) braking torque. { locked|=(1<<wheel); } /******************* * Calculate forces * *******************/ void pDifferential::CalcForces() // Calculates accelerations of the 3 sides of the differential // based on incoming torques and inertia's. // Also unlocks sides (only the wheels can be locked for now) // if the torques (engine for example) exceeds the braking torque // (if that side was locked, see Lock()) { // <NAME>'s naming convention float j1,j2,j3, // Inertia of output1/output2/input jw, // Total inertia of wheels jt, // Total inertia of all attached components jd; // Difference of wheel inertia's float m0, // Locking torque m1, // Output1 torque m2, // Output2 torque m3; // Input torque (from the engine probably) float mt, // Total net torque md; // Asymmetric torque (?) float det; // Check that everything is ok if(!engine)return; if(wheel[0]==0||wheel[1]==0)return; // Note that no ratios are used here; the input and outputs // are geared 1:1:1. This makes the formulas easier. To add // a differential ratio, the other functions for the input torques // take care of this. #ifdef LTRACE qdbg("RDiff:CalcForces()\n"); #endif // Retrieve current effective inertia // The base is the driveshaft; the accelerations and torques are // related to its position in the drivetrain. #ifdef ND_DRIVELINE inertiaIn=engine->GetInertiaAtDifferential(); inertiaOut[0]=wheel[0]->GetRotationalInertia()->x; inertiaOut[1]=wheel[1]->GetRotationalInertia()->x; #else inertiaIn=1; inertiaOut[0]=1; inertiaOut[1]=1; #endif // Retrieve torques at all ends // Notice that inside the diff, there can be a ratio. If this is 2 for // example, the driveshaft will rotate twice as fast as the wheel axles. #ifdef ND_DRIVELINE torqueIn=engine->GetTorqueAtDifferential(); #else torqueIn=1; #endif /* torqueOut[0]=wheel[0]->GetTorqueFeedbackTC()->x; torqueOut[1]=wheel[1]->GetTorqueFeedbackTC()->x; */ // Retrieve potential braking torque; if bigger than the reaction // torque, the output will become unlocked. If not, the output is // locked. // Note that the braking torque already points in the opposite // direction of the output (mostly a wheel) rotation. This is contrary // to Gregor Veble's approach, which only calculates the direction // in the formulae below. /* torqueBrakingOut[0]=wheel[0]->GetTorqueBrakingTC()->x; torqueBrakingOut[1]=wheel[1]->GetTorqueBrakingTC()->x; */ #ifdef LTRACE qdbg(" torqueIn=%f, torqueOut0=%f, 1=%f\n",torqueIn,torqueOut[0],torqueOut[1]); #endif // Proceed to Gregor's naming convention and algorithm // Determine locking switch(type) { case FREE: // No locking; both wheels run free m0=0; break; case VISCOUS: // velASymmetric=wheel[1]->GetRotationV()-wheel[0]->GetRotationV(); m0=-lockingCoeff*velASymmetric; #ifdef LTRACE qdbg(" velASymm=%f, lockCoeff=%f => m0=%f\n",velASymmetric,lockingCoeff,m0); #endif break; case SALISBURY: // Salisbury diff locks based on the ratio of reaction torques on // the tires. // Calculate torque bias ratio if(fabs(torqueOut[1])>D3_EPSILON) torqueBiasRatio=torqueOut[0]/torqueOut[1]; else if(fabs(torqueOut[0])>D3_EPSILON) torqueBiasRatio=torqueOut[1]/torqueOut[0]; else torqueBiasRatio=1; // Both wheels doing pretty much nothing // Get a number which always has a ratio>1 if(torqueBiasRatio<1.0)torqueBiasRatioAbs=1.0f/torqueBiasRatio; else torqueBiasRatioAbs=torqueBiasRatio; // Is the ratio exceeded? //xxxx continue here if(torqueIn>0) { // Power if(torqueBiasRatioAbs>maxBiasRatioPower); } m0=0; break; default: m0=0; break; } m3=torqueIn; // Entails engine braking already #ifdef LTRACE qdbg(" torqueIn=%f, locked=%d\n",m3,locked); #endif j1=inertiaOut[0]; j2=inertiaOut[1]; j3=inertiaIn; jw=j1+j2; jt=jw+j3; jd=j1-j2; // Inertia difference (of outputs) // Calculate determinant of 2x2 matrix det=4.0f*j1*j2+j3*jw; m3=torqueIn; switch(locked) { case 0: // No outputs locked m1=torqueOut[0]+torqueBrakingOut[0]; m2=torqueOut[1]+torqueBrakingOut[1]; //qdbg(" m1=%f, m2=%f\n",m1,m2); break; case 1: // Output 0 is locked, output 1 is unlocked m2=torqueOut[1]+torqueBrakingOut[1]; m1=(m2*j3-2.0f*m3*j2-m0*(2.0f*j2+j3))/(4.0f*j2+j3); if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) locked=0; break; case 2: // Output 1 is locked, output 0 is unlocked m1=torqueOut[0]+torqueBrakingOut[0]; m2=(m1*j3-2.0f*m3*j1+m0*(2.0f*j1+j3))/(4.0f*j1+j3); if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) locked=0; break; case 3: // Both outputs locked m1=-m3/2.0f; m2=m1; m0=0; if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) locked^=1; if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) locked^=2; break; default: //qerr("Bug: pDifferential locked not in 0..3 (%d)",locked); m1=m2=0; break; } mt=m1+m2+m3; md=m2-m1+m0; // Calculate asymmetric acceleration accASymmetric=md/jw; #ifdef ND_OLD_NAMES accASymmetric=(torqueOut[1]-torqueOut[0]+torqueLock)/ (inertiaOut[0]+inertiaOut[1]); #endif // Calculate total acceleration based on all torques // (which is in fact the driveshaft rotational acceleration) accIn=mt/jt; #ifdef ND_OLD_NAMES accIn=(torqueIn+torqueOut[0]+torqueOut[1])/ (inertiaIn+inertiaOut[0]+inertiaOut[1]); #endif // Derive from these the acceleration of the 2 output parts accOut[1]=accIn+accASymmetric; accOut[0]=accIn-accASymmetric; // Add torque to body because of the accelerating drivetrain // This gives a bit of the GPL effect where your car rolls when // you throttle with the clutch disengaged. /* float tr=car->GetEngine()->GetTorqueReaction(); if(tr>0) { DVector3 torque(0,0,accIn*inertiaIn*tr); //qdbg("torque.z=%f\n",torque.z); car->GetBody()->AddBodyTorque(&torque); } */ #ifdef LTRACE qdbg("inertia: I%f, O %f, %f\n",inertiaIn,inertiaOut[0],inertiaOut[1]); qdbg("torqueBraking: I%f, O %f, %f\n",0,torqueBrakingOut[0], torqueBrakingOut[1]); qdbg("torque: I%f, O %f, %f, locking %f\n",m3,m1,m2,m0); qdbg("Vel: wheel0=%f, wheel1=%f\n",wheel[0]->GetRotationV(), wheel[1]->GetRotationV()); qdbg("Acc: asym %f, in %f, out %f, %f\n",accASymmetric,accIn, accOut[0],accOut[1]); #endif } float pDifferential::CalcLockingTorque() // Calculates the locking torque of the differential { float m0; switch(type) { case FREE: // No locking; both wheels run free m0=0; break; case VISCOUS: //velASymmetric=wheel[1]->GetRotationV()-wheel[0]->GetRotationV(); m0=-lockingCoeff*velASymmetric; #ifdef LTRACE qdbg(" velASymm=%f, lockCoeff=%f => m0=%f\n",velASymmetric,lockingCoeff,m0); #endif break; case SALISBURY: // Salisbury diff locks based on the ratio of reaction torques on // the tires. // Calculate torque bias ratio if(fabs(torqueOut[1])>D3_EPSILON) torqueBiasRatio=torqueOut[0]/torqueOut[1]; else if(fabs(torqueOut[0])>D3_EPSILON) torqueBiasRatio=torqueOut[1]/torqueOut[0]; else torqueBiasRatio=1; // Both wheels doing pretty much nothing // Get a number which always has a ratio>1 if(torqueBiasRatio<1.0)torqueBiasRatioAbs=1.0f/torqueBiasRatio; else torqueBiasRatioAbs=torqueBiasRatio; // Is the ratio exceeded? //xxxx continue here if(torqueIn>0) { // Power if(torqueBiasRatioAbs>maxBiasRatioPower); } m0=0; break; default: //qwarn("pDifferential:CalcLockingTorque(); unknown diff type"); m0=0; break; } return m0; } void pDifferential::CalcSingleDiffForces(float torqueIn,float inertiaIn) // Special version in case there is only 1 differential. // Differences with regular operating: // - 'torqueIn' is directly passed in from the driveline root (engine). // - 'inertiaIn' is directly passed from the driveline (engine's eff. inertia) // Calculates accelerations of the 3 sides of the differential // based on incoming torques and inertia's. // Also unlocks sides (only the wheels can be locked for now) // if the engine torques exceeds the reaction/braking torque // (if that side was locked, see Lock()) { // <NAME>'s naming convention float j1,j2,j3, // Inertia of output1/output2/input jw, // Total inertia of wheels jt, // Total inertia of all attached components jd; // Difference of wheel inertia's float m0, // Locking torque m1, // Output1 torque m2, // Output2 torque m3; // Input torque (from the engine probably) float mt, // Total net torque md; // Asymmetric torque (?) float det; // Check that everything is ok if(!engine)return; if(wheel[0]==0||wheel[1]==0)return; // Note that no ratios are used here; the input and outputs // are geared 1:1:1. This makes the formulas easier. To add // a differential ratio, the other functions for the input torques // take care of this. #ifdef LTRACE qdbg("RDiff:CalcSingleDiffForces(%.2f)\n",torqueIn); #endif // Retrieve current effective inertia // The base is the driveshaft; the accelerations and torques are // related to its position in the drivetrain. //inertiaIn=engine->GetInertiaAtDifferential(); //inertiaOut[0]=wheel[0]->GetInertia(); //inertiaOut[1]=wheel[1]->GetInertia(); // Retrieve torques at all ends // Notice that inside the diff, there can be a ratio. If this is 2 for // example, the driveshaft will rotate twice as fast as the wheel axles. //torqueIn=engine->GetTorqueAtDifferential(); // torqueOut[0]=wheel[0]->GetTorqueFeedbackTC()->x; //torqueOut[1]=wheel[1]->GetTorqueFeedbackTC()->x; // Retrieve potential braking torque; if bigger than the reaction // torque, the output will become unlocked. If not, the output is // locked. // Note that the braking torque already points in the opposite // direction of the output (mostly a wheel) rotation. This is contrary // to <NAME>'s approach, which only calculates the direction // in the formulae below. // torqueBrakingOut[0]=wheel[0]->GetTorqueBrakingTC()->x; // torqueBrakingOut[1]=wheel[1]->GetTorqueBrakingTC()->x; #ifdef LTRACE qdbg(" torqueIn=%f, torqueOut0=%f, 1=%f\n",torqueIn, torqueOut[0],torqueOut[1]); #endif // Proceed to Gregor's naming convention and algorithm // Determine locking m0=CalcLockingTorque(); #ifdef OBS switch(type) { case FREE: // No locking; both wheels run free m0=0; break; case VISCOUS: velASymmetric=wheel[1]->GetRotationV()-wheel[0]->GetRotationV(); m0=-lockingCoeff*velASymmetric; #ifdef LTRACE qdbg(" velASymm=%f, lockCoeff=%f => m0=%f\n",velASymmetric,lockingCoeff,m0); #endif break; case SALISBURY: // Salisbury diff locks based on the ratio of reaction torques on // the tires. // Calculate torque bias ratio if(fabs(torqueOut[1])>D3_EPSILON) torqueBiasRatio=torqueOut[0]/torqueOut[1]; else if(fabs(torqueOut[0])>D3_EPSILON) torqueBiasRatio=torqueOut[1]/torqueOut[0]; else torqueBiasRatio=1; // Both wheels doing pretty much nothing // Get a number which always has a ratio>1 if(torqueBiasRatio<1.0)torqueBiasRatioAbs=1.0f/torqueBiasRatio; else torqueBiasRatioAbs=torqueBiasRatio; // Is the ratio exceeded? //xxxx continue here if(torqueIn>0) { // Power if(torqueBiasRatioAbs>maxBiasRatioPower); } m0=0; break; default: m0=0; break; } #endif m3=torqueIn; // Entails engine braking already #ifdef LTRACE qdbg(" torqueIn=%f, locked=%d\n",m3,locked); #endif j1=inertiaOut[0]; j2=inertiaOut[1]; j3=inertiaIn; jw=j1+j2; jt=jw+j3; jd=j1-j2; // Inertia difference (of outputs) // Calculate determinant of 2x2 matrix det=4.0f*j1*j2+j3*jw; m3=torqueIn; switch(locked) { case 0: // No outputs locked m1=torqueOut[0]+torqueBrakingOut[0]; m2=torqueOut[1]+torqueBrakingOut[1]; //qdbg(" m1=%f, m2=%f\n",m1,m2); break; case 1: // Output 0 is locked, output 1 is unlocked m2=torqueOut[1]+torqueBrakingOut[1]; m1=(m2*j3-2.0f*m3*j2-m0*(2.0f*j2+j3))/(4.0f*j2+j3); if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) locked=0; break; case 2: // Output 1 is locked, output 0 is unlocked m1=torqueOut[0]+torqueBrakingOut[0]; m2=(m1*j3-2.0f*m3*j1+m0*(2.0f*j1+j3))/(4.0f*j1+j3); if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) locked=0; break; case 3: // Both outputs locked m1=-m3/2.0f; m2=m1; m0=0; if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) locked^=1; if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) locked^=2; break; default: //qerr("Bug: pDifferential locked not in 0..3 (%d)",locked); m1=m2=0; break; } mt=m1+m2+m3; md=m2-m1+m0; // Calculate asymmetric acceleration accASymmetric=md/jw; #ifdef ND_OLD_NAMES accASymmetric=(torqueOut[1]-torqueOut[0]+torqueLock)/ (inertiaOut[0]+inertiaOut[1]); #endif // Calculate total acceleration based on all torques // (which is in fact the driveshaft rotational acceleration) accIn=mt/jt; #ifdef ND_OLD_NAMES accIn=(torqueIn+torqueOut[0]+torqueOut[1])/ (inertiaIn+inertiaOut[0]+inertiaOut[1]); #endif // Derive from these the acceleration of the 2 output parts accOut[1]=accIn+accASymmetric; accOut[0]=accIn-accASymmetric; // Add torque to body because of the accelerating drivetrain // This gives a bit of the GPL effect where your car rolls when // you throttle with the clutch disengaged. /* float tr=car->GetEngine()->GetTorqueReaction(); if(tr>0) { DVector3 torque(0,0,accIn*inertiaIn*tr); //qdbg("torque.z=%f\n",torque.z); car->GetBody()->AddBodyTorque(&torque); } */ #ifdef LTRACE qdbg("inertia: I%f, O %f, %f\n",inertiaIn,inertiaOut[0],inertiaOut[1]); qdbg("torqueBraking: I%f, O %f, %f\n",0,torqueBrakingOut[0], torqueBrakingOut[1]); qdbg("torque: I%f, O %f, %f, locking %f\n",m3,m1,m2,m0); qdbg("Vel: wheel0=%f, wheel1=%f\n",wheel[0]->GetRotationV(), wheel[1]->GetRotationV()); qdbg("Acc: asym %f, in %f, out %f, %f\n",accASymmetric,accIn, accOut[0],accOut[1]); #endif } /************ * Integrate * ************/ void pDifferential::Integrate() // Maintain differential objects rotations { float rotAds; // Check that everything is ok if(!engine)return; if(wheel[0]==0||wheel[1]==0)return; // Driveshaft rotation rotAds=accIn; #ifdef OBS_DIRECTLY_LINKED_TO_WHEELS rotVdriveShaft+=rotAds*RR_TIMESTEP; #endif //rotVdriveShaft=(wheel[0]->GetRotationV()+wheel[1]->GetRotationV())/2.0f; } /* bool pDifferential::LoadState(QFile *f) { RDriveLineComp::LoadState(f); f->Read(&rotVdriveShaft,sizeof(rotVdriveShaft)); f->Read(&locked,sizeof(locked)); return TRUE; } bool pDifferential::SaveState(QFile *f) { RDriveLineComp::SaveState(f); f->Write(&rotVdriveShaft,sizeof(rotVdriveShaft)); f->Write(&locked,sizeof(locked)); return TRUE; } bool pDifferential::Load(QInfo *info,cstring path) // Read settings from the car file { char buf[256]; sprintf(buf,"%s.type",path); type=info->GetInt(buf); // Read the ratio sprintf(buf,"%s.ratio",path); if(info->PathExists(buf)) { SetRatio(info->GetFloat(buf)); //qdbg("Diff ratio (%s) = %.2f\n",buf,ratio); } else { // Backward compatible (v0.4.9 and before); use old gearbox setting qwarn("No differential ratio in car.ini; using gearbox.end_ratio instead"); qwarn("(this is obsolete; use differential.diff<x>.ratio from now on)"); SetRatio(info->GetFloat("gearbox.end_ratio")); } sprintf(buf,"%s.inertia",path); SetInertia(info->GetFloat(buf)); // Type-specific parameters if(type==VISCOUS) { // Viscous locking differential sprintf(buf,"%s.locking_coeff",path); lockingCoeff=info->GetFloat(buf); } else if(type==SALISBURY) { // Salisbury (known from GPL) sprintf(buf,"%s.power_angle",path); powerAngle=info->GetFloat(buf)/RR_RAD2DEG; sprintf(buf,"%s.coast_angle",path); coastAngle=info->GetFloat(buf)/RR_RAD2DEG; sprintf(buf,"%s.clutches",path); clutches=info->GetInt(buf); sprintf(buf,"%s.clutch_factor",path); clutchFactor=info->GetFloat(buf); // Calculate resulting constants maxBiasRatioPower=cos(powerAngle)*(1.0+2.0*clutches)*clutchFactor; maxBiasRatioCoast=cos(coastAngle)*(1.0+2.0*clutches)*clutchFactor; } return TRUE; } */<file_sep>#include "precomp.h" #include "vtPrecomp.h" #include "vtNetAll.h" #include "vtNetworkManager.h" #include <xDOStructs.h> #include "xMathTools.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" void vtNetworkManager::updateLocalRotation(xDistributedObject* distObject,CK3dEntity *target,xDistributedProperty*prop) { if (!distObject || !target || !prop)return; xDistributedQuatF*propValue = static_cast<xDistributedQuatF*>(prop); if (!propValue)return; xDistributed3DObject *dobj3D = static_cast<xDistributed3DObject*>(distObject); if (!dobj3D)return; switch(prop->getPropertyInfo()->mNativeType) { case E_DC_3D_NP_WORLD_ROTATION: { QuatF currentRot = propValue->mLastServerValue; VxQuaternion t(currentRot.x,currentRot.y,currentRot.z,currentRot.w); target->SetQuaternion(&t,NULL,false,TRUE); /* Point4F currentPos = propValue->mLastServerValue; Point4F velocity = propValue->mLastServerDifference; VxVector realPos; target->GetPosition(&realPos); Point3F realPos2(realPos.x,realPos.y,realPos.z); float oneWayTime = (distObject->GetNetInterface()->GetConnectionTime() / 1000.0f); oneWayTime +=oneWayTime * prop->getPredictionSettings()->getPredictionFactor(); Point3F predictedPos = currentPos + velocity * oneWayTime; Point3F realPosDiff = - predictedPos - realPos2 ; VxVector posNew(predictedPos.x,predictedPos.y,predictedPos.z); target->SetPosition(&posNew);*/ /* VxVector v = posNew - realPos; float current_d = Magnitude( v ); if( current_d < 0.001f ) { current_d = 0.001f; v.Set(0,0,0.001f); } float attenuation = 15.0f; // Get the distance wanted float wanted_d = 1.0f; wanted_d = current_d - wanted_d; float tmp; if(tmp = current_d * (attenuation+1.0f) ) { float f = wanted_d / tmp; v *= f; } */ //target->Translate(&v); break; } } } void vtNetworkManager::updateLocalPosition(xDistributedObject* distObject,CK3dEntity *target,xDistributedProperty*prop) { if (!distObject || !target || !prop)return; xDistributedPoint3F *propValue = static_cast<xDistributedPoint3F*>(prop); if (!propValue)return; xDistributed3DObject *dobj3D = static_cast<xDistributed3DObject*>(distObject); if (!dobj3D)return; switch(prop->getPropertyInfo()->mNativeType) { case E_DC_3D_NP_WORLD_POSITION: { Point3F currentPos = propValue->mLastServerValue; Point3F velocity = propValue->mLastServerDifference; VxVector realPos; target->GetPosition(&realPos); Point3F realPos2(realPos.x,realPos.y,realPos.z); float oneWayTime = (distObject->getNetInterface()->GetConnectionTime() / 1000.0f); oneWayTime +=oneWayTime * prop->getPredictionSettings()->getPredictionFactor(); Point3F predictedPos = currentPos + velocity * oneWayTime; Point3F realPosDiff = - predictedPos - realPos2 ; VxVector posNew(predictedPos.x,predictedPos.y,predictedPos.z); target->SetPosition(&posNew); /* VxVector v = posNew - realPos; float current_d = Magnitude( v ); if( current_d < 0.001f ) { current_d = 0.001f; v.Set(0,0,0.001f); } float attenuation = 15.0f; // Get the distance wanted float wanted_d = 1.0f; wanted_d = current_d - wanted_d; float tmp; if(tmp = current_d * (attenuation+1.0f) ) { float f = wanted_d / tmp; v *= f; } */ //target->Translate(&v); break; } } } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pLogger.h" #include "pErrorStream.h" static pErrorStream gErrorStream; pLogger::pLogger() { mErrorStream = &gErrorStream; } <file_sep>/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton interface for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { ID = 258, HBLOCK = 259, POUND = 260, STRING = 261, INCLUDE = 262, IMPORT = 263, INSERT = 264, CHARCONST = 265, NUM_INT = 266, NUM_FLOAT = 267, NUM_UNSIGNED = 268, NUM_LONG = 269, NUM_ULONG = 270, NUM_LONGLONG = 271, NUM_ULONGLONG = 272, TYPEDEF = 273, TYPE_INT = 274, TYPE_UNSIGNED = 275, TYPE_SHORT = 276, TYPE_LONG = 277, TYPE_FLOAT = 278, TYPE_DOUBLE = 279, TYPE_CHAR = 280, TYPE_WCHAR = 281, TYPE_VOID = 282, TYPE_SIGNED = 283, TYPE_BOOL = 284, TYPE_COMPLEX = 285, TYPE_TYPEDEF = 286, TYPE_RAW = 287, TYPE_NON_ISO_INT8 = 288, TYPE_NON_ISO_INT16 = 289, TYPE_NON_ISO_INT32 = 290, TYPE_NON_ISO_INT64 = 291, LPAREN = 292, RPAREN = 293, COMMA = 294, SEMI = 295, EXTERN = 296, INIT = 297, LBRACE = 298, RBRACE = 299, PERIOD = 300, CONST_QUAL = 301, VOLATILE = 302, REGISTER = 303, STRUCT = 304, UNION = 305, EQUAL = 306, SIZEOF = 307, MODULE = 308, LBRACKET = 309, RBRACKET = 310, ILLEGAL = 311, CONSTANT = 312, NAME = 313, RENAME = 314, NAMEWARN = 315, EXTEND = 316, PRAGMA = 317, FEATURE = 318, VARARGS = 319, ENUM = 320, CLASS = 321, TYPENAME = 322, PRIVATE = 323, PUBLIC = 324, PROTECTED = 325, COLON = 326, STATIC = 327, VIRTUAL = 328, FRIEND = 329, THROW = 330, CATCH = 331, EXPLICIT = 332, USING = 333, NAMESPACE = 334, NATIVE = 335, INLINE = 336, TYPEMAP = 337, EXCEPT = 338, ECHO = 339, APPLY = 340, CLEAR = 341, SWIGTEMPLATE = 342, FRAGMENT = 343, WARN = 344, LESSTHAN = 345, GREATERTHAN = 346, MODULO = 347, DELETE_KW = 348, LESSTHANOREQUALTO = 349, GREATERTHANOREQUALTO = 350, EQUALTO = 351, NOTEQUALTO = 352, QUESTIONMARK = 353, TYPES = 354, PARMS = 355, NONID = 356, DSTAR = 357, DCNOT = 358, TEMPLATE = 359, OPERATOR = 360, COPERATOR = 361, PARSETYPE = 362, PARSEPARM = 363, PARSEPARMS = 364, CAST = 365, LOR = 366, LAND = 367, OR = 368, XOR = 369, AND = 370, RSHIFT = 371, LSHIFT = 372, MINUS = 373, PLUS = 374, MODULUS = 375, SLASH = 376, STAR = 377, LNOT = 378, NOT = 379, UMINUS = 380, DCOLON = 381 }; #endif /* Tokens. */ #define ID 258 #define HBLOCK 259 #define POUND 260 #define STRING 261 #define INCLUDE 262 #define IMPORT 263 #define INSERT 264 #define CHARCONST 265 #define NUM_INT 266 #define NUM_FLOAT 267 #define NUM_UNSIGNED 268 #define NUM_LONG 269 #define NUM_ULONG 270 #define NUM_LONGLONG 271 #define NUM_ULONGLONG 272 #define TYPEDEF 273 #define TYPE_INT 274 #define TYPE_UNSIGNED 275 #define TYPE_SHORT 276 #define TYPE_LONG 277 #define TYPE_FLOAT 278 #define TYPE_DOUBLE 279 #define TYPE_CHAR 280 #define TYPE_WCHAR 281 #define TYPE_VOID 282 #define TYPE_SIGNED 283 #define TYPE_BOOL 284 #define TYPE_COMPLEX 285 #define TYPE_TYPEDEF 286 #define TYPE_RAW 287 #define TYPE_NON_ISO_INT8 288 #define TYPE_NON_ISO_INT16 289 #define TYPE_NON_ISO_INT32 290 #define TYPE_NON_ISO_INT64 291 #define LPAREN 292 #define RPAREN 293 #define COMMA 294 #define SEMI 295 #define EXTERN 296 #define INIT 297 #define LBRACE 298 #define RBRACE 299 #define PERIOD 300 #define CONST_QUAL 301 #define VOLATILE 302 #define REGISTER 303 #define STRUCT 304 #define UNION 305 #define EQUAL 306 #define SIZEOF 307 #define MODULE 308 #define LBRACKET 309 #define RBRACKET 310 #define ILLEGAL 311 #define CONSTANT 312 #define NAME 313 #define RENAME 314 #define NAMEWARN 315 #define EXTEND 316 #define PRAGMA 317 #define FEATURE 318 #define VARARGS 319 #define ENUM 320 #define CLASS 321 #define TYPENAME 322 #define PRIVATE 323 #define PUBLIC 324 #define PROTECTED 325 #define COLON 326 #define STATIC 327 #define VIRTUAL 328 #define FRIEND 329 #define THROW 330 #define CATCH 331 #define EXPLICIT 332 #define USING 333 #define NAMESPACE 334 #define NATIVE 335 #define INLINE 336 #define TYPEMAP 337 #define EXCEPT 338 #define ECHO 339 #define APPLY 340 #define CLEAR 341 #define SWIGTEMPLATE 342 #define FRAGMENT 343 #define WARN 344 #define LESSTHAN 345 #define GREATERTHAN 346 #define MODULO 347 #define DELETE_KW 348 #define LESSTHANOREQUALTO 349 #define GREATERTHANOREQUALTO 350 #define EQUALTO 351 #define NOTEQUALTO 352 #define QUESTIONMARK 353 #define TYPES 354 #define PARMS 355 #define NONID 356 #define DSTAR 357 #define DCNOT 358 #define TEMPLATE 359 #define OPERATOR 360 #define COPERATOR 361 #define PARSETYPE 362 #define PARSEPARM 363 #define PARSEPARMS 364 #define CAST 365 #define LOR 366 #define LAND 367 #define OR 368 #define XOR 369 #define AND 370 #define RSHIFT 371 #define LSHIFT 372 #define MINUS 373 #define PLUS 374 #define MODULUS 375 #define SLASH 376 #define STAR 377 #define LNOT 378 #define NOT 379 #define UMINUS 380 #define DCOLON 381 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 1349 "parser.y" { char *id; List *bases; struct Define { String *val; String *rawval; int type; String *qualifier; String *bitfield; Parm *throws; String *throwf; } dtype; struct { char *type; String *filename; int line; } loc; struct { char *id; SwigType *type; String *defarg; ParmList *parms; short have_parms; ParmList *throws; String *throwf; } decl; Parm *tparms; struct { String *op; Hash *kwargs; } tmap; struct { String *type; String *us; } ptype; SwigType *type; String *str; Parm *p; ParmList *pl; int ivalue; Node *node; } /* Line 1489 of yacc.c. */ #line 344 "y.tab.h" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif extern YYSTYPE yylval; <file_sep>#include "precomp.h" #include "vtNetworkManager.h" #include "VSLManagerSDK.h" #include "xNetInterface.h" #include "xNetworkFactory.h" #include "tnlRandom.h" #include "tnlSymmetricCipher.h" #include "tnlAsymmetricKey.h" #include "vtTools.h" #include "xNetworkTypes.h" CKObjectDeclaration *FillBehaviorArrayNetMessageWaiterDecl(); CKERROR CreateArrayNetMessageWaiterProto(CKBehaviorPrototype **); int ArrayNetMessageWaiter(const CKBehaviorContext& behcontext); CKERROR ArrayNetMessageWaiterCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 //int msgCounter = 0; CKObjectDeclaration *FillBehaviorArrayNetMessageWaiterDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Network Wait Array Message"); od->SetDescription("Waits for a Message from the Network."); od->SetCategory("TNL/Message"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x3bf873ad,0x5a2e47bd)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateArrayNetMessageWaiterProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateArrayNetMessageWaiterProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Network Wait Array Message"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Stop"); proto->DeclareInput("Next"); proto->DeclareOutput("Out"); proto->DeclareOutput("Message"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Message", CKPGUID_MESSAGE, "OnClick"); proto->DeclareInParameter("Array", CKPGUID_DATAARRAY, "netArray"); proto->DeclareInParameter("First Column", CKPGUID_INT, "0"); proto->DeclareInParameter("Append", CKPGUID_BOOL, "false"); proto->DeclareOutParameter("Sender ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Private", CKPGUID_BOOL, "false"); proto->DeclareOutParameter("Error", CKPGUID_INT, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(ArrayNetMessageWaiter); proto->SetBehaviorCallbackFct(ArrayNetMessageWaiterCB); *pproto = proto; return CK_OK; } int ArrayNetMessageWaiter(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); beh->ActivateInput(0,FALSE); int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); int Msg=vtTools::BehaviorTools::GetInputParameterValue<int>(beh,1); XString msgName(mm->GetMessageTypeName(Msg)); CKDataArray *array = static_cast<CKDataArray*>(vtTools::BehaviorTools::GetInputParameterValue<CKObject*>(beh,2)); int firstC = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,3); bool append = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,4); ////////////////////////////////////////////////////////////////////////// xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { return FALSE; } if(cin->GetConnection()) { if (!cin->isValid()) { return FALSE; } } ////////////////////////////////////////////////////////////////////////// using namespace vtTools; using namespace vtTools::Enums; XArrayNetworkMessageTypeIterator begin = GetNM()->GetArrayNetworkMessages().Begin(); XArrayNetworkMessageTypeIterator end = GetNM()->GetArrayNetworkMessages().End(); while (begin != end) { vtArrayNetworkMessage*msg = *begin; if (msg) { if ( msg->complete ) { vtArrayNetworkMessage::ArrayTypeIterator parBegin = msg->columns.begin(); vtArrayNetworkMessage::ArrayTypeIterator parEnd = msg->columns.end(); int subIndex=0; int startR = append ? array->GetRowCount() : 0; while(parBegin!=parEnd) { vtArrayNetworkMessage::ColumnType column = parBegin->second; for (int i = 0 ; i < column.size() ; i++ ) { CKParameter* para = column[i]; int value = 0 ; para->GetValue(&value); logprintf("msgarray value %d",value); if (append) { array->AddRow(); } array->SetElementValueFromParameter(startR,firstC,para); startR++; subIndex++; CK_ID id = para->GetID(); ctx()->DestroyObject(id); } parBegin++; } GetNM()->GetArrayNetworkMessages().Remove(begin); logprintf("removing array by bb message !"); begin = GetNM()->GetArrayNetworkMessages().Begin(); } } begin++; } /*int startC = 0 ; if (firstC < array->GetColumnCount()) { }*/ /*if (strcmp(msg->name.Str(),msgName.Str())) { continue; }*/ /*vtArrayNetworkMessage::ArrayTypeIterator parBegin = msg->columns.begin(); vtArrayNetworkMessage::ArrayTypeIterator parEnd = msg->columns.end(); int subIndex=0; while(parBegin!=parEnd) { vtArrayNetworkMessage::ColumnType column = parBegin->second; for (int i = 0 ; i < column.size() ; i++ ) { CKParameter *pin = column[i]; CK_ID id = pin->GetID(); ctx()->DestroyObject(id); } parBegin++; } GetArrayNetworkMessages().Remove(begin); logprintf("removing array message !"); begin = GetArrayNetworkMessages().Begin();*/ /* XNetworkMessagesTypeIterator begin = GetNM()->GetXNetworkMessages().Begin(); XNetworkMessagesTypeIterator end = GetNM()->GetXNetworkMessages().End(); if (!GetNM()->GetXNetworkMessages().Size()) { return CKBR_ACTIVATENEXTFRAME; } while (begin != end) { vtNetworkMessage*msg = *begin; if (msg) { if (strcmp(msg->name.Str(),msgType.Str())) { continue; } if ( msg->complete ) { //logprintf("broadcast message recieved:%a",msg->name.Str()); vtNetworkMessage::MessageParameterArrayTypeIterator parBegin = msg->m_RecievedParameters.begin(); vtNetworkMessage::MessageParameterArrayTypeIterator parEnd = msg->m_RecievedParameters.end(); int subIndex=0; while(parBegin!=parEnd) { CKParameter *pin = parBegin->second; CKParameterType pType = pin->GetType(); SuperType sType = ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); const char *pname = pam->ParameterTypeToName(pType); switch (sType) { case vtSTRING: { if ( (beh->GetOutputParameterCount() - BEH_OUT_MIN_COUNT ) + subIndex > 0 ) { CKParameterOut *pout = beh->GetOutputParameter(BEH_OUT_MIN_COUNT + subIndex ); if (pout) { if (pout->GetType() == pin->GetType() ) { pout->CopyValue(pin); } } CK_ID id = pin->GetID(); ctx->DestroyObject(id); } break; } case vtFLOAT: { if ( (beh->GetOutputParameterCount() - BEH_OUT_MIN_COUNT ) + subIndex > 0 ) { CKParameterOut *pout = beh->GetOutputParameter(BEH_OUT_MIN_COUNT + subIndex ); if (pout) { if (pout->GetType() == pin->GetType() ) { pout->CopyValue(pin); } } CK_ID id = pin->GetID(); ctx->DestroyObject(id); } break; } case vtINTEGER: { if ( (beh->GetOutputParameterCount() - BEH_OUT_MIN_COUNT ) + subIndex > 0 ) { CKParameterOut *pout = beh->GetOutputParameter(BEH_OUT_MIN_COUNT + subIndex ); if (pout) { if (pout->GetType() == pin->GetType() ) { pout->CopyValue(pin); } } CK_ID id = pin->GetID(); ctx->DestroyObject(id); } break; } default : XString err("wrong input parameter type: "); } subIndex++; parBegin++; } beh->ActivateOutput(1); beh->SetOutputParameterValue(0,&msg->srcUserID); GetNM()->GetXNetworkMessages().Remove(begin); begin = GetNM()->GetXNetworkMessages().Begin(); } } begin++; }*/ return CKBR_ACTIVATENEXTFRAME; } CKERROR ArrayNetMessageWaiterCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "ISession.h" #include "IMessages.h" #include "xLogger.h" #include "vtLogTools.h" #include "xMessageTypes.h" #include "xDistributedClient.h" CKObjectDeclaration *FillBehaviorNMWaiterDecl(); CKERROR CreateNMWaiterProto(CKBehaviorPrototype **); int NMWaiter(const CKBehaviorContext& behcontext); CKERROR NMWaiterCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 typedef enum BB_IT { BB_IT_IN, BB_IT_STOP, BB_IT_NEXT }; typedef enum BB_INPAR { BB_IP_CONNECTION_ID, BB_IP_MESSAGE, }; typedef enum BB_OT { BB_O_OUT, BB_O_MESSAGE, BB_O_ERROR, }; typedef enum BB_OP { BB_OP_SENDER_ID, BB_OP_PRIVATE, BB_OP_ERROR, }; CKObjectDeclaration *FillBehaviorNMWaiterDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NMWaiter"); od->SetDescription("Waits for a Message from the Network."); od->SetCategory("TNL/Message"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5707744b,0x43b2301c)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNMWaiterProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateNMWaiterProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NMWaiter"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInParameter("Connection ID", CKPGUID_INT, "-1"); proto->DeclareInParameter("Message", CKPGUID_MESSAGE, "OnClick"); proto->DeclareInput("In"); proto->DeclareInput("Stop"); proto->DeclareInput("Next"); proto->DeclareOutput("Out"); proto->DeclareOutput("Message"); proto->DeclareOutput("Error"); proto->DeclareOutParameter("Sender ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Private", CKPGUID_BOOL, "false"); proto->DeclareOutParameter("Error", CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(NMWaiter); proto->SetBehaviorCallbackFct(NMWaiterCB); *pproto = proto; return CK_OK; } int NMWaiter(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); ////////////////////////////////////////////////////////////////////////// //connection id + session name : using namespace vtTools::BehaviorTools; int connectionID = GetInputParameterValue<int>(beh,BB_IP_CONNECTION_ID); int Msg=-1; beh->GetInputParameterValue(BB_IP_MESSAGE,&Msg); XString msgType(mm->GetMessageTypeName(Msg)); ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { //bbError(E_NWE_NO_CONNECTION); return CKBR_ACTIVATENEXTFRAME; } if (!cin->getMyClient()) { //bbError(E_NWE_INTERN); //Error(beh,"No client object created",BB_OP_SESSION_ERROR,TRUE,BB_O_ERROR); return 0; } ISession *sInterface = cin->getSessionInterface(); IMessages *mInterface = cin->getMessagesInterface(); xDistributedClient *myClient = cin->getMyClient(); if (!myClient) { //bbError(E_NWE_INTERN); return CKBR_ACTIVATENEXTFRAME; } /* xDistributedSession *session = sInterface->get(myClient->getSessionID()); if (!session) { bbError(E_NWE_NO_SESSION); return 0; }*/ if (beh->IsInputActive(BB_IT_STOP)) { beh->ActivateInput(BB_IT_STOP,FALSE); beh->ActivateOutput(BB_O_OUT); return CKBR_OK; } xMessage *msg = mInterface->getNextInMessage(msgType.CStr()); if (!msg)return CKBR_ACTIVATENEXTFRAME; if ( beh->GetOutputParameterCount() > BEH_OUT_MIN_COUNT ) { CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); for (int i = BEH_OUT_MIN_COUNT ; i < beh->GetOutputParameterCount() ; i++ ) { CKParameterOut *ciIn = beh->GetOutputParameter(i); CKParameterType pType = ciIn->GetType(); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); int propID = i - BEH_OUT_MIN_COUNT; if (propID>msg->getNumParameters() ) { goto MESSAGE_END; } xDistributedProperty *prop = msg->getParameters().at(propID); if (!prop) goto MESSAGE_END; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); if (!propInfo) goto MESSAGE_END; if (xDistTools::ValueTypeToSuperType(propInfo->mValueType) !=sType ) continue; switch(propInfo->mValueType) { case E_DC_PTYPE_STRING: { xDistributedString * propValue = (xDistributedString*)prop; if (propValue) { TNL::StringPtr ovalue = propValue->mCurrentValue; CKParameterOut *pout = beh->GetOutputParameter(i); XString errorMesg(ovalue.getString()); pout->SetStringValue(errorMesg.Str()); } break; } case E_DC_PTYPE_FLOAT: { xDistributedPoint1F * dpoint3F = (xDistributedPoint1F*)prop; if (dpoint3F) { float vvalue = dpoint3F->mLastServerValue; beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_3DVECTOR: { xDistributedPoint3F * dpoint3F = (xDistributedPoint3F*)prop; if (dpoint3F) { VxVector vvalue = xMath::getFrom(dpoint3F->mLastServerValue); beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_2DVECTOR: { xDistributedPoint2F * dpoint3F = (xDistributedPoint2F*)prop; if (dpoint3F) { Vx2DVector vvalue = xMath::getFrom(dpoint3F->mLastServerValue); beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_INT: { xDistributedInteger * dpoint3F = (xDistributedInteger*)prop; if (dpoint3F) { int ovalue = dpoint3F->mLastServerValue; beh->SetOutputParameterValue(i,&ovalue); } break; } case E_DC_PTYPE_QUATERNION: { xDistributedQuatF * dpoint3F = (xDistributedQuatF*)prop; if (dpoint3F) { VxQuaternion vvalue = xMath::getFrom(dpoint3F->mLastServerValue); beh->SetOutputParameterValue(i,&vvalue); } break; } case E_DC_PTYPE_UNKNOWN: { bbError(E_NWE_INVALID_PARAMETER); break; } default : bbError(E_NWE_INVALID_PARAMETER); return CKBR_BEHAVIORERROR; } } } goto MESSAGE_END; MESSAGE_END: { //IDistributedObjects *doInterface = cin->getDistObjectInterface(); //xDistributedClient *dstClient = static_cast<xDistributedClient*>(doInterface->get(msg->getSrcUser())); //if (dstClient) //{ SetOutputParameterValue<int>(beh,BB_OP_SENDER_ID,msg->getSrcUser()); //} enableFlag(msg->getFlags(),E_MF_DELETED); beh->ActivateOutput(BB_O_MESSAGE); } return CKBR_ACTIVATENEXTFRAME; } CKERROR NMWaiterCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#include "CKAll.h" /***************************************************************************** * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR * A PARTICULAR PURPOSE. * * Copyright (C) 1993 - 1996 Microsoft Corporation. All Rights Reserved. * ****************************************************************************** * * SMFRead.C * * MIDI File access routines. * *****************************************************************************/ #include <windows.h> #include <windowsx.h> #include <mmsystem.h> #include <memory.h> #include "muldiv32.h" #include "smf.h" #include "smfi.h" static UINT grbChanMsgLen[] = { 0, /* 0x not a status byte */ 0, /* 1x not a status byte */ 0, /* 2x not a status byte */ 0, /* 3x not a status byte */ 0, /* 4x not a status byte */ 0, /* 5x not a status byte */ 0, /* 6x not a status byte */ 0, /* 7x not a status byte */ 3, /* 8x Note off */ 3, /* 9x Note on */ 3, /* Ax Poly pressure */ 3, /* Bx Control change */ 2, /* Cx Program change */ 2, /* Dx Chan pressure */ 3, /* Ex Pitch bend change */ 0, /* Fx SysEx (see below) */ } ; /****************************************************************************** * * smfBuildFileIndex * * Preliminary parsing of a MIDI file. * * ppSmf - Pointer to a returned SMF structure if the * file is successfully parsed. * * Returns * SMF_SUCCESS The events were successfully read. * SMF_NO_MEMORY Out of memory to build key frames. * SMF_INVALID_FILE A disk or parse error occured on the file. * * This function validates the format of and existing MIDI or RMI file * and builds the handle structure which will refer to it for the * lifetime of the instance. * * The file header information will be read and verified, and * smfBuildTrackIndices will be called on every existing track * to build keyframes and validate the track format. * *****************************************************************************/ SMFRESULT smfBuildFileIndex( PSMF * ppSmf) { SMFRESULT smfrc; UNALIGNED CHUNKHDR * pCh; FILEHDR FAR * pFh; DWORD idx; PSMF pSmf, pSmfTemp; PTRACK pTrk; WORD wMemory; DWORD dwLeft; HPBYTE hpbImage; DWORD idxTrack; EVENT event; BOOL fFirst; DWORD dwLength; HLOCAL hLocal; PTEMPOMAPENTRY pTempo; //assert(ppSmf != NULL); pSmf = *ppSmf; //assert(pSmf != NULL); /* MIDI data image is already in hpbImage (already extracted from ** RIFF header if necessary). */ /* Validate MIDI header */ dwLeft = pSmf->cbImage; hpbImage = pSmf->hpbImage; if (dwLeft < sizeof(CHUNKHDR)) return SMF_INVALID_FILE; pCh = (CHUNKHDR FAR *)hpbImage; dwLeft -= sizeof(CHUNKHDR); hpbImage += sizeof(CHUNKHDR); if (pCh->fourccType != FOURCC_MThd) return SMF_INVALID_FILE; dwLength = DWORDSWAP(pCh->dwLength); if (dwLength < sizeof(FILEHDR) || dwLength > dwLeft) return SMF_INVALID_FILE; pFh = (FILEHDR *)hpbImage; dwLeft -= dwLength; hpbImage += dwLength; pSmf->dwFormat = (DWORD)(WORDSWAP(pFh->wFormat)); pSmf->dwTracks = (DWORD)(WORDSWAP(pFh->wTracks)); pSmf->dwTimeDivision = (DWORD)(WORDSWAP(pFh->wDivision)); /* ** We've successfully parsed the header. Now try to build the track ** index. ** ** We only check out the track header chunk here; the track will be ** preparsed after we do a quick integretiy check. */ wMemory = sizeof(SMF) + (WORD)(pSmf->dwTracks*sizeof(TRACK)); pSmfTemp = (PSMF)LocalReAlloc((HLOCAL)pSmf, wMemory, LMEM_MOVEABLE|LMEM_ZEROINIT); if (NULL == pSmfTemp) { return SMF_NO_MEMORY; } pSmf = *ppSmf = pSmfTemp; pTrk = pSmf->rTracks; for (idx=0; idx<pSmf->dwTracks; idx++) { if (dwLeft < sizeof(CHUNKHDR)) return SMF_INVALID_FILE; pCh = (CHUNKHDR *)hpbImage; dwLeft -= sizeof(CHUNKHDR); hpbImage += sizeof(CHUNKHDR); if (pCh->fourccType != FOURCC_MTrk) return SMF_INVALID_FILE; pTrk->idxTrack = (DWORD)(hpbImage - pSmf->hpbImage); pTrk->smti.cbLength = DWORDSWAP(pCh->dwLength); if (pTrk->smti.cbLength > dwLeft) { return SMF_INVALID_FILE; } dwLeft -= pTrk->smti.cbLength; hpbImage += pTrk->smti.cbLength; pTrk++; } /* File looks OK. Now preparse, doing the following: ** (1) Build tempo map so we can convert to/from ticks quickly ** (2) Determine actual tick length of file ** (3) Validate all events in all tracks */ pSmf->tkPosition = 0; pSmf->fdwSMF &= ~SMF_F_EOF; for (pTrk = pSmf->rTracks, idxTrack = pSmf->dwTracks; idxTrack--; pTrk++) { pTrk->pSmf = pSmf; pTrk->tkPosition = 0; pTrk->cbLeft = pTrk->smti.cbLength; pTrk->hpbImage = pSmf->hpbImage + pTrk->idxTrack; pTrk->bRunningStatus = 0; pTrk->fdwTrack = 0; } while (SMF_SUCCESS == (smfrc = smfGetNextEvent(pSmf, (EVENT *)&event, MAX_TICKS))) { if (MIDI_META == event.abEvent[0] && MIDI_META_TEMPO == event.abEvent[1]) { if (3 != event.cbParm) { return SMF_INVALID_FILE; } if (pSmf->cTempoMap == pSmf->cTempoMapAlloc) { if (NULL != pSmf->hTempoMap) { LocalUnlock(pSmf->hTempoMap); } pSmf->cTempoMapAlloc += C_TEMPO_MAP_CHK; fFirst = FALSE; if (0 == pSmf->cTempoMap) { hLocal = LocalAlloc(LHND, (UINT)(pSmf->cTempoMapAlloc*sizeof(TEMPOMAPENTRY))); fFirst = TRUE; } else { hLocal = LocalReAlloc(pSmf->hTempoMap, (UINT)(pSmf->cTempoMapAlloc*sizeof(TEMPOMAPENTRY)), LHND); } if (NULL == hLocal) { return SMF_NO_MEMORY; } pSmf->pTempoMap = (PTEMPOMAPENTRY)LocalLock(pSmf->hTempoMap = hLocal); } if (fFirst && pSmf->tkPosition != 0) { /* Inserting first event and the absolute time is zero. ** Use defaults of 500,000 uSec/qn from MIDI spec */ pTempo = &pSmf->pTempoMap[pSmf->cTempoMap++]; pTempo->tkTempo = 0; pTempo->msBase = 0; pTempo->dwTempo = MIDI_DEFAULT_TEMPO; fFirst = FALSE; } pTempo = &pSmf->pTempoMap[pSmf->cTempoMap++]; pTempo->tkTempo = pSmf->tkPosition; if (fFirst) pTempo->msBase = 0; else { /* NOTE: Better not be here unless we're q/n format! */ pTempo->msBase = (pTempo-1)->msBase + muldiv32(pTempo->tkTempo-((pTempo-1)->tkTempo), (pTempo-1)->dwTempo, 1000L*pSmf->dwTimeDivision); } pTempo->dwTempo = (((DWORD)event.hpbParm[0])<<16)| (((DWORD)event.hpbParm[1])<<8)| ((DWORD)event.hpbParm[2]); } } if (0 == pSmf->cTempoMap) { hLocal = LocalAlloc(LHND, sizeof(TEMPOMAPENTRY)); if (!hLocal) return SMF_NO_MEMORY; pSmf->pTempoMap = (PTEMPOMAPENTRY)LocalLock(pSmf->hTempoMap = hLocal); pSmf->cTempoMap = 1; pSmf->cTempoMapAlloc = 1; pSmf->pTempoMap->tkTempo = 0; pSmf->pTempoMap->msBase = 0; pSmf->pTempoMap->dwTempo = MIDI_DEFAULT_TEMPO; } if (SMF_END_OF_FILE == smfrc || SMF_SUCCESS == smfrc) { pSmf->tkLength = pSmf->tkPosition; smfrc = SMF_SUCCESS; } return smfrc; } /****************************************************************************** * * smfGetNextEvent * * Read the next event from the given file. * * pSmf - File to read the event from. * * pEvent - Pointer to an event structure which will receive * basic information about the event. * * tkMax - Tick destination. An attempt to read past this * position in the file will fail. * * Returns * SMF_SUCCESS The events were successfully read. * SMF_END_OF_FILE There are no more events to read in this track. * SMF_REACHED_TKMAX No event was read because <p tkMax> was reached. * SMF_INVALID_FILE A disk or parse error occured on the file. * * This is the lowest level of parsing for a raw MIDI stream. The basic * information about one event in the file will be returned in pEvent. * * Merging data from all tracks into one stream is performed here. * * pEvent->tkDelta will contain the tick delta for the event. * * pEvent->abEvent will contain a description of the event. * pevent->abEvent[0] will contain * F0 or F7 for a System Exclusive message. * FF for a MIDI file meta event. * The status byte of any other MIDI message. (Running status will * be tracked and expanded). * * pEvent->cbParm will contain the number of bytes of paramter data * which is still in the file behind the event header already read. * This data may be read with <f smfGetTrackEventData>. Any unread * data will be skipped on the next call to <f smfGetNextTrackEvent>. * * Channel messages (0x8? - 0xE?) will always be returned fully in * pevent->abEvent. * * Meta events will contain the meta type in pevent->abEvent[1]. * * System exclusive events will contain only an 0xF0 or 0xF7 in * pevent->abEvent[0]. * * The following fields in pTrk are used to maintain state and must * be updated if a seek-in-track is performed: * * bRunningStatus contains the last running status message or 0 if * there is no valid running status. * * hpbImage is a pointer into the file image of the first byte of * the event to follow the event just read. * * dwLeft contains the number of bytes from hpbImage to the end * of the track. * * * Get the next due event from all (in-use?) tracks * * For all tracks * If not end-of-track * decode event delta time without advancing through buffer * event_absolute_time = track_tick_time + track_event_delta_time * relative_time = event_absolute_time - last_stream_time * if relative_time is lowest so far * save this track as the next to pull from, along with times * * If we found a track with a due event * Advance track pointer past event, saving ptr to parm data if needed * track_tick_time += track_event_delta_time * last_stream_time = track_tick_time * Else * Mark and return end_of_file * *****************************************************************************/ SMFRESULT smfGetNextEvent( PSMF pSmf, EVENT * pEvent, TICKS tkMax) { PTRACK pTrk; PTRACK pTrkFound; DWORD idxTrack; TICKS tkEventDelta; TICKS tkRelTime; TICKS tkMinRelTime; BYTE bEvent; DWORD dwGotTotal; DWORD dwGot; DWORD cbEvent; //assert(pSmf != NULL); //assert(pEvent != NULL); if (pSmf->fdwSMF & SMF_F_EOF) { return SMF_END_OF_FILE; } pTrkFound = NULL; tkMinRelTime = MAX_TICKS; for (pTrk = pSmf->rTracks, idxTrack = pSmf->dwTracks; idxTrack--; pTrk++) { if (pTrk->fdwTrack & SMF_TF_EOT) continue; if (!smfGetVDword(pTrk->hpbImage, pTrk->cbLeft, (DWORD *)&tkEventDelta)) { return SMF_INVALID_FILE; } tkRelTime = pTrk->tkPosition + tkEventDelta - pSmf->tkPosition; if (tkRelTime < tkMinRelTime) { tkMinRelTime = tkRelTime; pTrkFound = pTrk; } } if (!pTrkFound) { pSmf->fdwSMF |= SMF_F_EOF; return SMF_END_OF_FILE; } pTrk = pTrkFound; if (pSmf->tkPosition + tkMinRelTime >= tkMax) { return SMF_REACHED_TKMAX; } pTrk->hpbImage += (dwGot = smfGetVDword(pTrk->hpbImage, pTrk->cbLeft, (DWORD *)&tkEventDelta)); pTrk->cbLeft -= dwGot; /* We MUST have at least three bytes here (cause we haven't hit ** the end-of-track meta yet, which is three bytes long). Checking ** against three means we don't have to check how much is left ** in the track again for any short event, which is most cases. */ if (pTrk->cbLeft < 3) { return SMF_INVALID_FILE; } pTrk->tkPosition += tkEventDelta; pEvent->tkDelta = pTrk->tkPosition - pSmf->tkPosition; pSmf->tkPosition = pTrk->tkPosition; bEvent = *pTrk->hpbImage++; if (MIDI_MSG > bEvent) { if (0 == pTrk->bRunningStatus) { return SMF_INVALID_FILE; } dwGotTotal = 1; pEvent->abEvent[0] = pTrk->bRunningStatus; pEvent->abEvent[1] = bEvent; if (3 == grbChanMsgLen[(pTrk->bRunningStatus >> 4) & 0x0F]) { pEvent->abEvent[2] = *pTrk->hpbImage++; dwGotTotal++; } } else if (MIDI_SYSEX > bEvent) { pTrk->bRunningStatus = bEvent; dwGotTotal = 2; pEvent->abEvent[0] = bEvent; pEvent->abEvent[1] = *pTrk->hpbImage++; if (3 == grbChanMsgLen[(bEvent >> 4) & 0x0F]) { pEvent->abEvent[2] = *pTrk->hpbImage++; dwGotTotal++; } } else { pTrk->bRunningStatus = 0; if (MIDI_META == bEvent) { pEvent->abEvent[0] = MIDI_META; if (MIDI_META_EOT == (pEvent->abEvent[1] = *pTrk->hpbImage++)) { pTrk->fdwTrack |= SMF_TF_EOT; } dwGotTotal = 2; } else if (MIDI_SYSEX == bEvent || MIDI_SYSEXEND == bEvent) { pEvent->abEvent[0] = bEvent; dwGotTotal = 1; } else { return SMF_INVALID_FILE; } if (0 == (dwGot = smfGetVDword(pTrk->hpbImage, pTrk->cbLeft - 2, (DWORD *)&cbEvent))) { return SMF_INVALID_FILE; } pTrk->hpbImage += dwGot; dwGotTotal += dwGot; if (dwGotTotal + cbEvent > pTrk->cbLeft) { return SMF_INVALID_FILE; } pEvent->cbParm = cbEvent; pEvent->hpbParm = pTrk->hpbImage; pTrk->hpbImage += cbEvent; dwGotTotal += cbEvent; } //assert(pTrk->cbLeft >= dwGotTotal); pTrk->cbLeft -= dwGotTotal; return SMF_SUCCESS; } /****************************************************************************** * * smfGetVDword * * Reads a variable length DWORD from the given file. * * hpbImage - Pointer to the first byte of the VDWORD. * * dwLeft - Bytes left in image * * pDw - Pointer to a DWORD to store the result in. * track. * * Returns the number of bytes consumed from the stream. * * A variable length DWORD stored in a MIDI file contains one or more * bytes. Each byte except the last has the high bit set; only the * low 7 bits are significant. * *****************************************************************************/ DWORD smfGetVDword( HPBYTE hpbImage, DWORD dwLeft, DWORD * pDw) { BYTE b; DWORD dwUsed = 0; //assert(hpbImage != NULL); //assert(pDw != NULL); *pDw = 0; do { if (!dwLeft) { return 0; } b = *hpbImage++; dwLeft--; dwUsed++; *pDw = (*pDw << 7) | (b & 0x7F); } while (b&0x80); return dwUsed; } <file_sep>////////////////////////////////////////////////////////////////////////////////////////////////////////// // DataManager ////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "CKAll.h" #include "DataManager.h" DataManager::DataManager(CKContext *Context) : CKBaseManager(Context, DataManagerGUID, "DataManager") { Context->RegisterNewManager(this); _vPos.Set(0,0,0); } DataManager::~DataManager() { } CKERROR DataManager::OnCKInit() { #ifdef G_EXTERNAL_ACCESS _initSharedMemory(0); #endif return CK_OK; } CKERROR DataManager::PostProcess() { #ifdef G_EXTERNAL_ACCESS _SharedMemoryTickPost(0); #endif return CK_OK; } CKERROR DataManager::PreProcess() { #ifdef G_EXTERNAL_ACCESS _SharedMemoryTick(0); #endif return CK_OK; } <file_sep>// PBRootForm.cpp : implementation file // #include "stdafx2.h" #include "PBRootForm.h" // PBRootForm IMPLEMENT_DYNCREATE(PBRootForm, CFormView) PBRootForm::PBRootForm() : CFormView(PBRootForm::IDD) { } PBRootForm::~PBRootForm() { } void PBRootForm::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(PBRootForm, CFormView) END_MESSAGE_MAP() // PBRootForm diagnostics #ifdef _DEBUG void PBRootForm::AssertValid() const { CFormView::AssertValid(); } #ifndef _WIN32_WCE void PBRootForm::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif #endif //_DEBUG // PBRootForm message handlers <file_sep>/****************************************************************************** File : CustomPlayer.cpp Description: This file contains the CCustomPlayer class which is the "interface" with the Virtools SDK. All other files are Windows/MFC specific code. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ #include "CPStdAfx.h" #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #if defined(CUSTOM_PLAYER_STATIC) // include file used for the static configuration #include "CustomPlayerStaticLibs.h" #include "CustomPlayerRegisterDlls.h" #endif #include "vtTools.h" extern CCustomPlayerApp theApp; extern CCustomPlayer* thePlayer; BOOL CCustomPlayerApp::_CreateWindows() { RECT mainRect; int k = CCustomPlayer::Instance().WindowedWidth(); int k1 = CCustomPlayer::Instance().WindowedHeight(); // compute the main window rectangle, so the window is centered mainRect.left = (GetSystemMetrics(SM_CXSCREEN)-CCustomPlayer::Instance().WindowedWidth())/2; mainRect.right = CCustomPlayer::Instance().WindowedWidth()+mainRect.left; mainRect.top = (GetSystemMetrics(SM_CYSCREEN)-CCustomPlayer::Instance().WindowedHeight())/2; mainRect.bottom = CCustomPlayer::Instance().WindowedHeight()+mainRect.top; BOOL ret = AdjustWindowRect(&mainRect,WS_OVERLAPPEDWINDOW & ~(WS_SYSMENU|WS_SIZEBOX|WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_SIZEBOX),FALSE); DWORD dwStyle; // create the main window switch(GetPlayer().PGetApplicationMode()) { case normal: { m_MainWindow = CreateWindow(m_PlayerClass.CStr(),GetPlayer().GetPAppStyle()->g_AppTitle.Str(),(WS_EX_ACCEPTFILES|WS_OVERLAPPEDWINDOW) & ~(WS_SIZEBOX|WS_MAXIMIZEBOX), mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top, NULL,NULL,m_hInstance,NULL); //m_MainWindow = CreateWindowEx(WS_EX_ACCEPTFILES|WS_EX_TOPMOST,m_PlayerClass.CStr(),GetPlayer().GetPAppStyle()->g_AppTitle.Str(),WS_VISIBLE,mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top,NULL,NULL,m_hInstance,this); break; } case preview: { RECT rc; GetClientRect( GetPlayer().m_hWndParent, &rc ); dwStyle = WS_VISIBLE | WS_CHILD; AdjustWindowRect( &rc, dwStyle, FALSE ); m_MainWindow = GetPlayer().m_hWndParent; GetPlayer().m_WindowedWidth = rc.right - rc.left ; GetPlayer().m_WindowedHeight = rc.bottom - rc.top; m_RenderWindow = CreateWindowEx(WS_EX_TOPMOST,m_RenderClass.CStr(),"",(WS_CHILD|WS_VISIBLE)&~WS_CAPTION,rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,m_MainWindow,NULL,m_hInstance,this); } break; case popup: { dwStyle = (WS_OVERLAPPEDWINDOW); //m_MainWindow = CreateWindowEx( dwStyle , m_PlayerClass.CStr(), GetPlayer().GetPAppStyle()->g_AppTitle.Str(), WS_POPUP, mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top , m_MainWindow, NULL,m_hInstance, NULL ); m_MainWindow = CreateWindow(m_PlayerClass.CStr(),"asd",WS_POPUP,mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top,NULL,NULL,m_hInstance,NULL); break; } default: m_MainWindow = CreateWindow(m_PlayerClass.CStr(),GetPlayer().GetPAppStyle()->g_AppTitle.Str(),WS_OVERLAPPEDWINDOW & ~(WS_SIZEBOX|WS_MAXIMIZEBOX), mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top, NULL,NULL,m_hInstance,NULL); break; } // m_MainWindow = CreateWindow(m_PlayerClass.CStr(),"asd",WS_OVERLAPPEDWINDOW & ~(WS_SIZEBOX|WS_MAXIMIZEBOX), // mainRect.left,mainRect.top,mainRect.right-mainRect.left,mainRect.bottom-mainRect.top, // NULL,NULL,m_hInstance,NULL); if(!m_MainWindow) { return FALSE; } if(GetPlayer().PGetApplicationMode() != preview) { int w = CCustomPlayer::Instance().FullscreenWidth(); int h = CCustomPlayer::Instance().FullscreenHeight(); // create the render window if (( GetPlayer().GetEWindowInfo()->g_GoFullScreen )) { m_RenderWindow = CreateWindowEx(WS_EX_TOPMOST,m_RenderClass.CStr(),"",(WS_CHILD|WS_OVERLAPPED|WS_VISIBLE)&~WS_CAPTION, 0,0,CCustomPlayer::Instance().FullscreenWidth(),CCustomPlayer::Instance().FullscreenHeight(),m_MainWindow,NULL,m_hInstance,0); } else { m_RenderWindow = CreateWindowEx(WS_EX_TOPMOST,m_RenderClass.CStr(),"",(WS_CHILD|WS_OVERLAPPED|WS_VISIBLE)&~WS_CAPTION, 0,0,CCustomPlayer::Instance().WindowedWidth(),CCustomPlayer::Instance().WindowedHeight(),m_MainWindow,NULL,m_hInstance,0); } } if(!m_RenderWindow) { return FALSE; } return TRUE; } <file_sep>#include <StdAfx2.h> #include "PCommonDialog.h" #include "PBodySetup.h" #include "PBXMLSetup.h" #include "resource.h" #include "VITabCtrl.h" #include "VIControl.h" #include "..\..\include\interface\pbxmlsetup.h" void CPBXMLSetup::fillXMLLinks() { XMLExternLink.AddString("None"); XMLInternLink.AddString("None"); XMLExternLink.SetCurSel(0); XMLInternLink.SetCurSel(0); } int CPBXMLSetup::OnSelect(int before/* =-1 */) { return -1; } BOOL CPBXMLSetup::OnInitDialog() { fillXMLLinks(); CDialog::OnInitDialog(); /*getXMLSetup().SetMode(MultiParamEditDlg::MODELESSEDIT|MultiParamEditDlg::USER_CUSTOM_BUTTONS|MultiParamEditDlg::AUTOCLOSE_WHEN_MODELESS|MultiParamEditDlg::CREATEPARAM); //getXMLSetup().AttachControlSite(this,IDC_MAIN_VIEW_XML); CRect rcValue; GetWindowRect( &rcValue ); // Use picture box position. ScreenToClient( &rcValue ); */ return TRUE; } CPBXMLSetup::~CPBXMLSetup(){ _destroy();} void CPBXMLSetup::_destroy(){ ::CPSharedBase::_destroy();} CPBXMLSetup::CPBXMLSetup(CKParameter* Parameter,CK_CLASSID Cid) : CParameterDialog(Parameter,Cid) , CPSharedBase(this,Parameter) { setEditedParameter(Parameter); } CPBXMLSetup::CPBXMLSetup(CKParameter* Parameter,CWnd *parent,CK_CLASSID Cid) : CParameterDialog(Parameter,Cid) , CPSharedBase(this,Parameter) { setEditedParameter(Parameter); } void CPSharedBase::_dtrBodyXMLDlg(){} CPBXMLSetup*CPBXMLSetup::refresh(CKParameter*src){ return this;} HWND CPBXMLSetup::getDlgWindowHandle(UINT templateID) { HWND result = NULL; GetDlgItem(templateID,&result); return result; } LRESULT CPBXMLSetup::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: { break; } case WM_ERASEBKGND: { /*RECT r; GetClientRect(&r); CDC* pDC=CDC::FromHandle((HDC)wParam); pDC->FillSolidRect(&r,RGB(200,200,200)); return 1;*/ }break; case CKWM_OK: { //CEdit *valueText = (CEdit*)GetDlgItem(IDC_EDIT); /*CString l_strValue; valueText->GetWindowText(l_strValue); double d; if (sscanf(l_strValue,"%Lf",&d)) { parameter->SetValue(&d); }*/ } break; case CKWM_INIT: { RECT r; GetClientRect(&r); fillXMLLinks(); } break; } return CDialog::WindowProc(message, wParam, lParam); } void CPBXMLSetup::DoDataExchange(CDataExchange* pDX) { //CDialog::DoDataExchange(pDX); CParameterDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPBXMLSetup) DDX_Control(pDX, IDC_XINTERN_LINK2, XMLInternLink); DDX_Control(pDX, IDC_XEXTERN_LINK, XMLExternLink); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPBXMLSetup, CParameterDialog) ON_STN_CLICKED(IDC_XML_MAIN_VIEW, OnStnClickedXmlMainView) END_MESSAGE_MAP() void CPBXMLSetup::OnStnClickedXmlMainView() { // TODO: Add your control notification handler code here } <file_sep>#pragma once #include "CKAll.h" class vtGUID { private: CKGUID guid; public: CKGUID GetVirtoolsGUID() { return guid; } vtGUID( DWORD d1=0, DWORD d2=0 ):guid(d1,d2) {} XString ToString( void ) { XString laid; laid << DecimalToHex( guid.d1 ); laid << DecimalToHex( guid.d2 ); return laid; } bool FromString( const XString laid ) { if( laid.Length() != 16 ) return false; XString d1(laid); XString d2(laid); d1.Crop( 0, 8 ); d2.Crop( 8, 8 ); HexToDecimalHI( d1.Str(), guid.d1 ); HexToDecimalLO( d2.Str(), guid.d2 ); return true; } vtGUID & operator =( const CKGUID& ckguid ) { guid.d1 = ckguid.d1; guid.d2 = ckguid.d2; return *this; } operator XString() { return ToString(); } private: XString DecimalToHex( int decimal ) { XString hexStr; char hexstring[17]; itoa( decimal, hexstring, 16); int length = strlen(hexstring); if (length < 8) { int add = 8 - length; for (int i = 0; i < add; i++) { hexStr << "0"; } } hexStr << hexstring; return hexStr; } bool HexToDecimalHI (char* HexNumber, unsigned int& Number) { char* pStopString; Number = strtol (HexNumber, &pStopString, 16); return (bool)(Number != LONG_MAX); } bool HexToDecimalLO(char* HexNumber, unsigned int& Number) { char* pStopString; Number = strtoul(HexNumber, &pStopString, 16); return (bool)(Number != LONG_MAX); } }; <file_sep>#ifndef __X_SPLASH_H_ #define __X_SPLASH_H_ #include <BaseMacros.h> class CSplashScreenEx; namespace xSplash { MODULE_API CSplashScreenEx *GetSplash(); MODULE_API void CreateSplash(HINSTANCE hinst,int w,int h); MODULE_API void CreateSplashEx(CWnd *parent,int w,int h); MODULE_API void HideSplash(); MODULE_API void ShowSplash(); MODULE_API void SetText(const char* text); }//end of namespace xSplash #endif<file_sep>/******************************************************************** created: 2008/01/14 created: 14:1:2008 12:14 filename: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer\CustomPlayerDialogErrorPage.cpp file path: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer file base: CustomPlayerDialogErrorPage file ext: cpp author: mc007 purpose: Displays an Error Tab, the text is set by CustomPlayerDialog.InitDialog ! *********************************************************************/ #include <CPStdAfx.h> #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "resourceplayer.h" #include "CustomPlayerDialogErrorPage.h" #include "CustomPlayerDialog.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CErrorPage dialog CustomPlayerDialogErrorPage::CustomPlayerDialogErrorPage() : CPropertyPage(CustomPlayerDialogErrorPage::IDD) { //{{AFX_DATA_INIT(CErrorPage) //}}AFX_DATA_INIT } void CustomPlayerDialogErrorPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CErrorPage) //}}AFX_DATA_MAP DDX_Control(pDX, IDC_ERROR_RICHT_TEXT, m_ErrorRichText); } BEGIN_MESSAGE_MAP(CustomPlayerDialogErrorPage, CPropertyPage) //{{AFX_MSG_MAP(CErrorPage) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP ON_EN_SETFOCUS(IDC_ERROR_RICHT_TEXT, OnEnSetfocusErrorRichtText) ON_NOTIFY(EN_LINK, IDC_ERROR_RICHT_TEXT, OnEnLinkErrorRichtText) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CErrorPage message handlers void CustomPlayerDialogErrorPage::OnEnSetfocusErrorRichtText() { if (m_ErrorRichText) { CRect rc; m_ErrorRichText.GetWindowRect(rc); ScreenToClient(rc); DWORD newStyle= ES_CENTER; DWORD style= m_ErrorRichText.GetStyle(); style&= ~ES_CENTER; style|= newStyle; style|= WS_VSCROLL; DWORD exstyle= m_ErrorRichText.GetExStyle(); m_ErrorRichText.SetAutoURLDetect(); m_ErrorRichText.SetEventMask(ENM_LINK); m_ErrorRichText.SetFont(GetFont()); m_ErrorRichText.SetWindowText(errorText); m_ErrorRichText.UpdateData(); m_ErrorRichText.UpdateWindow(); m_ErrorRichText.HideCaret(); } } void CustomPlayerDialogErrorPage::OnEnLinkErrorRichtText(NMHDR *pNMHDR, LRESULT *pResult) { ENLINK *el= reinterpret_cast<ENLINK *>(pNMHDR); *pResult = 0; if (el->msg == WM_LBUTTONDOWN) { CString link; m_ErrorRichText.GetTextRange(el->chrg.cpMin, el->chrg.cpMax, link); ShellExecute(*this, NULL, link, NULL, _T(""), SW_SHOWNORMAL); } } <file_sep>#include "pch.h" #include "xString.h" xString::xString() // Default constructor, just creates an empty string. { Text = NULL; Len = Size = 0; } xString::xString(const xString& input) // Copy constructor, makes an instance an exact copy of { // another string. AssignFrom(input); } #ifdef _UNICODE #include <wchar.h> xString::xString(const TUnicodeChar *input) // Constructor building an ANSI string from a regular C { // string in Unicode format (used for doing conversions). if (input == NULL) // Early out if string is NULL { Text = NULL; Size = Len = 0; return; } Size = wcslen(input) + 1; // Use Unicode wcslen function Len = Size-1; Text = AllocStr(Size); for (int i=0 ; i<Len ; i++) // Convert Unicode->ANSI char-by-char Text[i] = (TAnsiChar)input[i]; Text[Len] = __xA('\0'); } #endif int xString::GetLength()const // Returns the length of the string currently { // held by an instance of the string class. return Len; } xString::~xString() // Destructor. The use of virtual is recommended in C++ { // for all destructors that can potentially be overloaded. if (Size && Text != NULL) // Free the memory used by the string FreeStr(Text); } //======================================================= // // Accessors // TChar* xString::GetString() // Returns a pointer to the actual string data. { return Text; } const TAnsiChar* xString::CStr() const // Returns a pointer to the actual string data. { return Text ? Text : NULL; } bool xString::IsNull()const // Returns true if a NULL string is held by an instance. { return (Text == NULL || !_tcslen(Text)); } bool xString::IsValidIndex(const int Index)const // Returns true if the character index { // specified is within the bounds of the string. return (Index >= 0 && Index < Len); } //======================================================= // // Regular transformation functions // int xString::Compare(const xString&ins, bool IgnoreCase) const { if (IsNull() && !ins.IsNull()) return 1; else if (!IsNull() && ins.IsNull()) return -1; else if (IsNull() && ins.IsNull()) return 0; if (IgnoreCase) return _tcsicmp(Text, ins.Text); else return _tcscmp(Text, ins.Text); } bool xString::Find(xString&Str, int& Pos, bool IgnoreCase)const // Finds a substring within this string. { // Returns true if found (position in Pos). if (IsNull() || Str.IsNull()) return false; // Define a function pointer that will be used to call the appropriate // compare function based on the value of IgnoreCase. int (* cmpfn)(const TCHAR*, const TCHAR*, size_t) = (IgnoreCase) ? _tcsnicmp : _tcsncmp; for (Pos=0 ; Pos<=(Len-Str.Len) ; Pos++) { if (cmpfn(&Text[Pos], Str.Text, Str.Len) == 0) return true; } return false; } void xString::Delete(int Pos, int Count) // Deletes the specified number of characters, { // starting at the specified position. if (Pos > Len || Count==0) // Start is outside string or nothing to delete? return; if (Pos + Count > Len) // Clamp Count to string length Count = (Len - Pos); // Characters are deleted by moving up the data following the region to delete. for (int i=Pos ; i<Len-Count ; i++) Text[i] = Text[i+Count]; Len -= Count; Text[Len] = __xT('\0'); Optimize(); } void xString::Insert(int Pos, TChar c) // Inserts a character at the given position in the string. { if (Pos<0 || Pos>Len) return; Grow(1); // Grow the string by one byte to be able to hold character // Move down rest of the string. // Copying overlapping memory blocks requires the use of memmove() instead of memcpy(). memmove((void *)&Text[Pos+1], (const void *)&Text[Pos], Len-Pos); Text[Pos] = c; Text[++Len] = __xT('\0'); } void xString::Insert(int Pos, const xString& input) // Inserts a complete string at the given { // location. if (Pos<0 || Pos>Len || input.IsNull()) return; TChar *New = AllocStr(input.Len + Len + 1); if (Pos > 0) // Set the string portion before the inserted string _tcsncpy(New, Text, Pos); _tcsncpy(&New[Pos], input.Text, input.Len); // Insert the string if (Len-Pos > 0) // Insert rest of orignal string _tcsncpy(&New[Pos+input.Len], &Text[Pos], Len-Pos); AssignFrom(New); // Copy new string back into stringobject } xString xString::GetSubString(int Start, int Count, xString& Dest) // Crops out a substring. { if (!IsValidIndex(Start) || Count <= 0) // Valid operation? { Dest = __xT(""); return Dest; } TChar *Temp = AllocStr(Count + 1); _tcsncpy(Temp, &Text[Start], Count); Temp[Count] = __xT('\0'); Dest = Temp; FreeStr(Temp); return Dest; } //======================================================= // // Special transformation functions // void xString::VarArg(TChar *Format, ...) // Allows you to fill a string object with data in the { // same way you use sprintf() TChar Buf[0x1000]; // Need lots of space va_list argptr; va_start(argptr, Format); #ifdef _UNICODE vswprintf(Buf, Format, argptr); #else vsprintf(Buf, Format, argptr); #endif va_end(argptr); Size = _tcslen(Buf) + 1; Len = _tcslen(Buf); FreeStr(Text); Text = AllocStr(Size); if (Len > 0) _tcscpy(Text, Buf); else Text[0] = __xT('\0'); } void xString::EatLeadingWhitespace() // Convenient function that removes all whitespace { // (tabs and spaces) at the beginning of a string. if (IsNull()) return; int i=0; for (i=0 ; i<Len ; i++) { if (Text[i] != 0x20 && Text[i] != 0x09) break; } Delete(0, i); } void xString::EatTrailingWhitespace() // Convenient function that removes all whitespace { // (tabs and spaces) from the end of a string. if (IsNull()) return; int i=0; for (i=Len-1 ; i>=0 ; i--) { if (Text[i] != 0x20 && Text[i] != 0x09) break; } Delete(i+1, Len-i-1); } //======================================================= // // Conversion functions // TAnsiChar* xString::ToAnsi(TAnsiChar *Buffer, int BufferLen) const // Converts the string to an ANSI string. { int i, ConvertLen; if (BufferLen <= 0) { Buffer = NULL; return Buffer; } if (BufferLen >= Len) ConvertLen = Len; else ConvertLen = BufferLen-1; for (i=0 ; i<ConvertLen ; i++) { #ifdef _UNICODE if (Text[i] > 255) // If character is a non-ANSI Unicode character, fill with Buffer[i] = 0x20; // space instead. else #endif Buffer[i] = (TAnsiChar)Text[i]; } Buffer[i] = __xA('\0'); return Buffer; } TUnicodeChar * xString::ToUnicode(TUnicodeChar *Buffer, int BufferLen) const // Converts the string { // to a Unicode string. int i, ConvertLen; if (BufferLen <= 0) { Buffer = NULL; return Buffer; } if (BufferLen >= Len) ConvertLen = Len; else ConvertLen = BufferLen-1; for (i=0 ; i<ConvertLen ; i++) Buffer[i] = (TUnicodeChar)Text[i]; Buffer[i] = __xU('\0'); return Buffer; } xString::operator TUnicodeChar*()const { TUnicodeChar*out =new TUnicodeChar[Size]; ToUnicode(out,Size); return out; } int xString::ToInt() const // Converts the string to an integer. { if (IsNull()) return 0; #ifdef _UNICODE return _wtoi(Text); // Unicode version of atoi #else return atoi(Text); // ANSI version of atoi #endif } //======================================================= // // Assignment operators // void xString::_attachRight(const TCHAR*rValue) { Optimize(); xString rBuffer(rValue); rBuffer.Optimize(); TChar *Temp = xString::AllocStr(Size + rBuffer.Size); // Allocate memory for new string if (Len) // Copy first string into dest _tcscpy(Temp, Text); if (rBuffer.Len) // Copy second string into dest _tcscpy(&Temp[Len], rBuffer.Text); Text = Temp; } xString& xString::operator<<(const void* iValue) { const TChar* rValue = static_cast<const TChar*>(iValue); if ( rValue ) { _attachRight(rValue); }else return *this; } xString& xString::operator<<(const int iValue) { xString buffer(""); #ifdef _UNICODE _itow(iValue,buffer.GetString(),10); #else _itot(iValue,buffer.GetString(),10); #endif _attachRight(buffer); return *this; } xString& xString::operator<<(const TChar* rValue) { Optimize(); xString rBuffer(rValue); rBuffer.Optimize(); return operator +=(rBuffer); const TChar* buffer = static_cast<const TChar*>(rValue); if ( buffer ) { _attachRight(buffer); delete buffer; }else return *this; } //======================================================= // // Concatenation operators // //friend xString operator +(const xString& Str1, const xString& Str2); // Concatenates two strings (see text) //friend xString operator +(const xString& Str1, const xString& Str2); // Concatenates two strings (see text) //======================================================= // // Access operators // TAnsiChar* xString::Str() { return operator TAnsiChar*(); } TChar& xString::operator [](int Pos) // Returns a character reference at a { // specific location. if (Pos < 0) // If underrun, just return first character return Text[0]; else if (Pos >= Len) // If overrun, expand string in accordance { Grow(Pos+2); return Text[Pos]; } else // Otherwise, just return character return Text[Pos]; } //======================================================= // // Protected low-level functions // void xString::Optimize() // Discards any unused space allocated for the string { Size = Len + 1; TChar *Temp = AllocStr(Size); _tcscpy(Temp, Text); FreeStr(Text); Text = Temp; } void xString::Grow(int Num) // Allocates some more memory so the string can hold an additional Num characters { Size += Num; TChar *Temp = AllocStr(Size); _tcscpy(Temp, Text); FreeStr(Text); Text = Temp; } void xString::AssignFrom(const xString& Str) // Does the hard work for all non-converting assignments { Size = Str.Size; Len = Str.Len; if (Size && Len) // No point copying an empty string { Text = AllocStr(Size); _tcscpy(Text, Str.Text); } else { Text = NULL; } } TChar * xString::AllocStr(int Size) // Allocates a new character array. You can modify this { // function if you for instance use a custom memory manager. //return new TChar[Size]; return (TChar *)calloc(Size, sizeof(TChar)); } void xString::FreeStr(TChar *Ptr) // Ditto { if (Ptr == NULL) return; //delete Ptr; //return; free(Ptr); } //======================================================= // // Concatenation function (must be global for reasons stated in the text) // /* xString::operator +(const xString& Str1, const TChar& Str2) { TChar *Temp = xString::AllocStr(Str1.Size + Str2.Size); // Allocate memory for new string if (Str1.Len) // Copy first string into dest _tcscpy(Temp, Str1.Text); if (Str2.Len) // Copy second string into dest _tcscpy(&Temp[Str1.Len], Str2.Text); xString Result = Temp; return Result; }*/<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorUserNameModifiedDecl(); CKERROR CreateUserNameModifiedProto(CKBehaviorPrototype **); int UserNameModified(const CKBehaviorContext& behcontext); CKERROR UserNameModifiedCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorUserNameModifiedDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NUserNameModified"); od->SetDescription("User changed name"); od->SetCategory("TNL/User Management"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x6f94031a,0x3e3a1714)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("<NAME>"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateUserNameModifiedProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } typedef enum BB_IT { BB_IT_IN, BB_IT_STOP, BB_IT_NEXT }; typedef enum BB_INPAR { BB_IP_CONNECTION_ID, BB_IP_USER_ID, }; typedef enum BB_OT { BB_O_OUT, BB_O_NAME_CHANGED, BB_O_ERROR }; typedef enum BB_OP { BB_OP_USER_ID, BB_OP_USER_NAME, BB_OP_ERROR }; CKERROR CreateUserNameModifiedProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NUserNameModified"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Stop"); proto->DeclareInput("Next"); proto->DeclareOutput("Out"); proto->DeclareOutput("User"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("User ID", CKPGUID_INT, "-1"); proto->DeclareOutParameter("User Name", CKPGUID_STRING, "-1"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(UserNameModified); proto->SetBehaviorCallbackFct(UserNameModifiedCB); *pproto = proto; return CK_OK; } int UserNameModified(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); int connectionID=-1; beh->GetInputParameterValue(0,&connectionID); XString userName((CKSTRING) beh->GetInputParameterReadDataPtr(1)); using namespace vtTools::BehaviorTools; bbNoError(E_NWE_OK); /************************************************************************/ /* */ /************************************************************************/ beh->ActivateInput(0,FALSE); using namespace vtTools::BehaviorTools; xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } if (!cin->getMyClient()) { bbError(E_NWE_INTERN); return 0; } xDistributedClient *myClient = cin->getMyClient(); if (!myClient) { bbError(E_NWE_INTERN); return 0; } vtConnection *con = cin->getConnection(); IDistributedObjects *doInterface = cin->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = cin->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { xDistributedClass *_class = dobj->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT) { xDistributedClient *client = static_cast<xDistributedClient*>(dobj); if (client) { if (client->getUserFlags() == USERNAME_CHANGED && client->getUserID() !=con->getUserID() ) { client->setUserFlags(USER_OK); int userID = client->getUserID(); beh->SetOutputParameterValue(0,&userID); CKParameterOut *pout = beh->GetOutputParameter(1); pout->SetStringValue(const_cast<char*>(client->getUserName().getString())); xLogger::xLog(ELOGINFO,E_LI_CLIENT,"User %d changed his name to %s",userID,client->getUserName().getString()); beh->ActivateOutput(1); } } } } } begin++; } /************************************************************************/ /* */ /************************************************************************/ if (beh->IsInputActive(1)) { beh->ActivateInput(1,FALSE); beh->ActivateOutput(0); return CKBR_OK; } return CKBR_ACTIVATENEXTFRAME; } CKERROR UserNameModifiedCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { /* CKParameterIn* pin = beh->GetInputParameter(0); if (!pin) { CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : failed to retrieve first input parameter"; behcontext.Context->OutputToConsole(str.Str(),TRUE); return CKBR_PARAMETERERROR; } if (pin->GetGUID()!=CKPGUID_MESSAGE) { pin->SetGUID(CKPGUID_MESSAGE,FALSE); CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : first input parameter type must be \"Message\"!"; behcontext.Context->OutputToConsole(str.Str(),TRUE); } pin = beh->GetInputParameter(1); if (!pin) { CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : failed to retrieve second input parameter"; behcontext.Context->OutputToConsole(str.Str(),TRUE); return CKBR_PARAMETERERROR; } if (!behcontext.ParameterManager->IsDerivedFrom(pin->GetGUID(),CKPGUID_OBJECT)) { pin->SetGUID(CKPGUID_BEOBJECT,FALSE); CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : second input parameter type must derived from \"BeObject\"!"; behcontext.Context->OutputToConsole(str.Str(),TRUE); }*/ } return CKBR_OK; }<file_sep>#ifndef __P_FLUID_H__ #define __P_FLUID_H__ #include "pTypes.h" #include "NxPlane.h" #include "pFluidFlags.h" #include "pTypes.h" class CK3dPointCloud; /** \addtogroup Fluid @{ */ /** \brief2 Describes an pFluidDesc. */ class MODULE_API pFluidDesc { public: /** \brief Sets the maximal number of particles for the fluid used in the simulation. If more particles are added directly, or more particles are emitted into the fluid after this limit is reached, they are simply ignored. */ int maxParticles; /** \brief Defines the number of particles which are reserved for creation at runtime. If pFluidDesc.flags.PFF_PriorityMode is set the oldest particles are removed until there are no more than (maxParticles - numReserveParticles) particles left. This removal is carried out for each simulation step, on particles which have a finite life time (i.e. > 0.0). The deletion guarantees a reserve of numReserveParticles particles which can be added for each simulaiton step. Note that particles which have equal lifetime can get deleted at the same time. In order to avoid this, the particle lifetimes can be varied randomly. This parameter must be smaller than pFluidDesc.maxParticles. */ int numReserveParticles; /** \brief The particle resolution given as particles per linear meter measured when the fluid is in its rest state (relaxed). Even if the particle system is simulated without particle interactions, this parameter defines the emission density of the emitters. */ float restParticlesPerMeter; /** \brief Target density for the fluid (water is about 1000). Even if the particle system is simulated without particle interactions, this parameter defines indirectly in combination with restParticlesPerMeter the mass of one particle ( mass = restDensity/(restParticlesPerMeter^3) ). The particle mass has an impact on the repulsion effect on emitters and actors. */ float restDensity; /** \brief Radius of sphere of influence for particle interaction. This parameter is relative to the rest spacing of the particles, which is defined by the parameter restParticlesPerMeter ( radius = kernelRadiusMultiplier/restParticlesPerMeter ). This parameter should be set around 2.0 and definitely below 2.5 for optimal performance and simulation quality. @see restParticlesPerMeter */ float kernelRadiusMultiplier; /** \brief Maximal distance a particle is allowed to travel within one timestep. This parameter is relative to the rest spacing of the particles, which is defined by the parameter restParticlesPerMeter: ( maximal travel distance = motionLimitMultiplier/restParticlesPerMeter ). Default value is 3.6 (i.e., 3.0 * kernelRadiusMultiplier). The value must not be higher than the product of packetSizeMultiplier and kernelRadiusMultiplier. @see restParticlesPerMeter */ float motionLimitMultiplier; /** \brief Defines the distance between particles and collision geometry, which is maintained during simulation. For the actual distance, this parameter is divided by the rest spacing of the particles, which is defined by the parameter restParticlesPerMeter: ( distance = collisionDistanceMultiplier/restParticlesPerMeter ). It has to be positive and not higher than packetSizeMultiplier*kernelRadiusMultiplier. Default value is 0.12 (i.e., 0.1 * kernelRadiusMultiplier). @see restParticlesPerMeter, kernelRadiusMultiplier */ float collisionDistanceMultiplier; /** \brief This parameter controls the parallelization of the fluid. The spatial domain is divided into so called packets, equal sized cubes, aligned in a grid. The parameter given defines the edge length of such a packet. This parameter is relative to the interaction radius of the particles, given as kernelRadiusMultiplier/restParticlesPerMeter. It has to be a power of two, no less than 4. */ int packetSizeMultiplier; /** \brief The stiffness of the particle interaction related to the pressure. This factor linearly scales the force which acts on particles which are closer to each other than the rest spacing. Setting this parameter appropriately is crucial for the simulation. The right value depends on many factors such as viscosity, damping, and kernelRadiusMultiplier. Values which are too high will result in an unstable simulation, whereas too low values will make the fluid appear "springy" (the fluid acts more compressible). Must be positive. */ float stiffness; /** \brief The viscosity of the fluid defines its viscous behavior. Higher values will result in a honey-like behavior. Viscosity is an effect which depends on the relative velocity of neighboring particles; it reduces the magnitude of the relative velocity. Must be positive. */ float viscosity; /** \brief The surfaceTension of the fluid defines an attractive force between particles Higher values will result in smoother surfaces. Must be nonnegative. */ float surfaceTension; /** \brief Velocity damping constant, which is globally applied to each particle. It generally reduces the velocity of the particles. Setting the damping to 0 will leave the particles unaffected. Must be nonnegative. */ float damping; /** \brief Defines a timespan for the particle "fade-in". This feature is experimental. When a particle is created it has no influence on the simulation. It takes fadeInTime until the particle has full influence. If set to zero, the particle has full influence on the simulation from start. <b>Default:</b> 0.0 <br> <b>Range:</b> [0,inf) */ float fadeInTime; /** \brief Acceleration (m/s^2) applied to all particles at all time steps. Useful to simulate smoke or fire. This acceleration is additive to the scene gravity. The scene gravity can be turned off for the fluid, using the flag PFF_DisableGravity. @see pFluid.getExternalAcceleration() pFluid.setExternalAcceleration() */ VxVector externalAcceleration; /** \brief Defines the plane the fluid particles are projected to. This parameter is only used if PFF_ProjectToPlane is set. <b>Default:</b> XY plane @see PFF_ProjectToPlane pFluid.getProjectionPlane() pFluid.setProjectionPlane() */ NxPlane projectionPlane; /** \brief Defines the restitution coefficient used for collisions of the fluid particles with static shapes. Must be between 0 and 1. A value of 0 causes the colliding particle to get a zero velocity component in the direction of the surface normal of the static shape at the collision location; i.e. it will not bounce. A value of 1 causes a particle's velocity component in the direction of the surface normal to invert; i.e. the particle bounces off the surface with the same velocity magnitude as it had before collision. (Caution: values near 1 may have a negative impact on stability) */ float restitutionForStaticShapes; /** \brief Defines the dynamic friction of the fluid regarding the surface of a static shape. Must be between 0 and 1. A value of 1 will cause the particle to lose its velocity tangential to the surface normal of the shape at the collision location; i.e. it will not slide along the surface. A value of 0 will preserve the particle's velocity in the tangential surface direction; i.e. it will slide without resistance on the surface. */ float dynamicFrictionForStaticShapes; /** \brief Defines the static friction of the fluid regarding the surface of a static shape. This feature is currently unimplemented! */ float staticFrictionForStaticShapes; /** \brief Defines the strength of attraction between the particles and static rigid bodies on collision. This feature is currently unimplemented! */ float attractionForStaticShapes; /** \brief Defines the restitution coefficient used for collisions of the fluid particles with dynamic shapes. Must be between 0 and 1. (Caution: values near 1 may have a negative impact on stability) @see restitutionForStaticShapes */ float restitutionForDynamicShapes; /** \brief Defines the dynamic friction of the fluid regarding the surface of a dynamic shape. Must be between 0 and 1. @see dynamicFrictionForStaticShapes */ float dynamicFrictionForDynamicShapes; /** \brief Defines the static friction of the fluid regarding the surface of a dynamic shape. This feature is currently unimplemented! */ float staticFrictionForDynamicShapes; /** \brief Defines the strength of attraction between the particles and the dynamic rigid bodies on collision. This feature is currently unimplemented! */ float attractionForDynamicShapes; /** \brief Defines a factor for the impulse transfer from fluid to colliding rigid bodies. Only has an effect if PFF_CollisionTwoway is set. <b>Default:</b> 0.2 <br> <b>Range:</b> [0,inf) @see PFF_CollisionTwoway pFluid.setCollisionResponseCoefficient() */ float collisionResponseCoefficient; /** \brief pFluidSimulationMethod flags. Defines whether or not particle interactions are considered in the simulation. @see pFluidSimulationMethod */ pFluidSimulationMethod simulationMethod; /** \brief pFluidCollisionMethod flags. Selects whether static collision and/or dynamic collision with the environment is performed. @see pFluidCollisionMethod */ pFluidCollisionMethod collisionMethod; /** \brief Sets which collision group this fluid is part of. <b>Default:</b> 0 pFluid.setCollisionGroup() */ int collisionGroup; /** \brief Sets the 128-bit mask used for collision filtering. <b>Default:</b> 0 @see NxGroupsMask pFluid.setGroupsMask() pFluid.getGroupsMask() */ NxGroupsMask groupsMask; /** \brief Flags defining certain properties of the fluid. @see pFluidFlag */ unsigned int flags; void* userData; //!< Will be copied to NxFluid::userData const char* name; //!< Possible debug name. The string is not copied by the SDK, only the pointer is stored. /** \brief Constructor sets to default. */ pFluidDesc(); /** \brief (Re)sets the structure to the default. */ void setToDefault(); /** \brief Returns true if the current settings are valid */ bool isValid() const; /** \brief Retrieve the fluid desc type. \return The fluid desc type. See #pFluidDescType */ xU16 getType() const; CK_ID worldReference; protected: NxFluidDescType type; }; struct pParticle { NxVec3 position; NxVec3 velocity; float density; float lifetime; unsigned int id; NxVec3 collisionNormal; }; /** \brief The fluid class represents the main module for the particle based fluid simulation. SPH (Smoothed Particle Hydrodynamics) is used to animate the particles. There are two kinds of particle interaction forces which govern the behavior of the fluid: <ol> <li> Pressure forces: These forces result from particle densities higher than the "rest density" of the fluid. The rest density is given by specifying the inter-particle distance at which the fluid is in its relaxed state. Particles which are closer than the rest spacing are pushed away from each other. <li> Viscosity forces: These forces act on neighboring particles depending on the difference of their velocities. Particles drag other particles with them which is used to simulate the viscous behaviour of the fluid. </ol> The fluid class manages a set of particles. Particles can be created in two ways: <ol> <li> Particles can be added by the user directly. <li> The user can add emitters to the fluid and configure the parameters of the emission. (See pFluidEmitter) </ol> Particles can be removed in two ways as well: <ol> <li> The user can specify a lifetime for the particles. When its lifetime expires, a particle is deleted. <li> Shapes can be configured to act as drains. When a particle intersects with a drain, the particle is deleted. (See pShapeFlag) </ol> Particles collide with static and dynamic shapes. Particles are also affected by the scene gravity and a user force, as well as global velocity damping. In order to render a fluid, the user can supply the fluid instance with a user buffer into which the particle state is written after each simuation step. For a good introduction to SPH fluid simulation, see http://graphics.ethz.ch/~mattmuel/publications/sca03.pdf @see pFluidDesc, pFluidEmitter, pFluidEmitterDesc, pShapeFlag */ class pFluid { public: pFluid(NxFluidDesc &desc, bool trackUserData, bool provideCollisionNormals, const VxVector& color, float particleSize); ~pFluid(); NxFluid* getNxFluid() { return mFluid; } pParticle* getParticles() { return mParticleBuffer; } unsigned getParticlesNum() { return mParticleBufferNum; } const unsigned* getCreatedIds() { return mCreatedParticleIds; } unsigned getCreatedIdsNum() { return mCreatedParticleIdsNum; } const unsigned* getDeletedIds() { return mDeletedParticleIds; } unsigned getDeletedIdsNum() { return mDeletedParticleIdsNum; } void setParticleSize(float size) { mParticleSize = size; } float getParticleSize() { return mParticleSize; } void draw(); NxFluid* getFluid() const { return mFluid; } void setFluid(NxFluid* val) { mFluid = val; } CK_ID getEntityID() const { return entityID; } void setEntityID(CK_ID val) { entityID = val; } void updateVirtoolsMesh(); CK3dEntity *getParticleObject(); pParticle* mParticleBuffer; /************************************************************************/ /* emitter operations : */ /************************************************************************/ /** \brief Creates an emitter for this fluid. pFluidEmitterDesc::isValid() must return true. \param desc The fluid emitter descriptor. See #pFluidEmitterDesc. \return The new fluid. @see pFluidEmitter */ pFluidEmitter* createEmitter(const pFluidEmitterDesc& desc); /** \brief Deletes the specified emitter. The emitter must belong to this fluid. Do not keep a reference to the deleted instance. Avoid release calls while the scene is simulating (in between simulate() and fetchResults() calls). \param emitter The emitter to release. */ void releaseEmitter(pFluidEmitter& emitter); /** \brief Returns the number of emitters. \return The number of emitters. */ int getNbEmitters()const; CK3dPointCloud* mPointCloud; CK3dPointCloud* getPointCloud() const { return mPointCloud; } void setPointCloud(CK3dPointCloud* val) { mPointCloud = val; } void updateCloud(); private: unsigned mParticleBufferNum; NxFluid* mFluid; VxVector mParticleColor; float mParticleSize; unsigned int mMaxParticles; CK_ID entityID; /** These fields are only relevant for tracking user particle data (MyParticle) */ bool mTrackUserData; pFluid* mMyParticleBuffer; unsigned int mCreatedParticleIdsNum; unsigned int* mCreatedParticleIds; unsigned int mDeletedParticleIdsNum; unsigned int* mDeletedParticleIds; //rendering float* mRenderBuffer; float* mRenderBufferUserData; protected: private: }; /** @} */ #endif <file_sep>/******************************************************************** created: 2007/10/29 created: 29:10:2007 15:16 filename: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src\xSystem3D.h file path: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src file base: xSystem3D file ext: h author: mc007 purpose: *********************************************************************/ #include <BaseMacros.h> namespace xSystem3DHelper { MODULE_API int xSGetAvailableTextureMem(); MODULE_API float xSGetPhysicalMemoryInMB(); MODULE_API int xSGetPhysicalGPUMemoryInMB(int device); MODULE_API void xSSaveAllDxPropsToFile(char*file); MODULE_API void xSGetDXVersion(char*& versionstring,int& minor); }<file_sep>copy X:\ProjectRoot\svn\cellador\virtools\vtPhysX\Doc\examples\*.cmo X:\ProjectRoot\svn\cellador\virtools\vtPhysX\Doc\doxyOutput\html /y copy X:\ProjectRoot\svn\cellador\virtools\vtPhysX\Doc\examples\vehicle\*.cmo X:\ProjectRoot\svn\cellador\virtools\vtPhysX\Doc\doxyOutput\html /y copy X:\ProjectRoot\svn\cellador\virtools\vtPhysX\Doc\scenes\*.cmo X:\ProjectRoot\svn\cellador\virtools\vtPhysX\Doc\doxyOutput\html /y copy X:\ProjectRoot\svn\cellador\virtools\vtPhysX\Doc\scenes\vehicle\*.cmo X:\ProjectRoot\svn\cellador\virtools\vtPhysX\Doc\doxyOutput\html /y doxygen .\doxyConfig.dox REM copy X:\ProjectRoot\vdev\Documentation\vtAgeia.CHM X:\ProjectRoot\vtmod_vtAgeia\Doc /y REM copy X:\ProjectRoot\vdev\Documentation\vtAgeia.CHM X:\ProjectRoot\vtmodsvn\Plugins\vtAgeia\Documentation /y <file_sep>cmake_minimum_required(VERSION 2.6) SET( CMAKE_CURRENT_SOURCE_DIR "./CMAKEFiles") SET( CMAKE_HOST_WIN32 "TRUE") #--------Looking for Dev 35 Directory ! Stored in variable "VTDEV35DIR" include ("CMakeFindMakeVTDev35.cmake") IF(VTDEV35DIR) MESSAGE(STATUS "\n\n\t Virtools Dev Directory 3.5 found : ${VTDEV35DIR} \n \n") ELSE(VTDEV35DIR) MESSAGE(ERROR "\n\n\t Virtools Dev Directory 3.5 NOT found !!! \n \n") ENDIF(VTDEV35DIR) file(APPEND "VTPaths.lua" "DEV35DIR=\"${VTDEV35DIR}\" \n" ) #--------Looking for Dev 40 Directory ! Stored in variable "VTDEV40DIR" include ("CMakeFindMakeVTDev40.cmake") IF(VTDEV40DIR) MESSAGE(STATUS "\n\n\t Virtools Dev Directory 4.0 found : ${VTDEV40DIR} \n \n") ELSE(VTDEV40DIR) MESSAGE(ERROR "\n\n\t Virtools Dev Directory 4.0 NOT found !!! \n \n") ENDIF(VTDEV40DIR) file(APPEND "VTPaths.lua" "DEV40DIR=\"${VTDEV40DIR}\" \n" ) #--------Looking for Dev 41 Directory ! Stored in variable "VTDEV41DIR" include ("CMakeFindMakeVTDev41.cmake") IF(VTDEV41DIR) MESSAGE(STATUS "\n\n\t Virtools Dev Directory 4.1 found : ${VTDEV41DIR} \n \n") ELSE(VTDEV41DIR) MESSAGE(ERROR "\n\n\t Virtools Dev Directory 4.1 NOT found !!! \n \n") ENDIF(VTDEV41DIR) file(APPEND "VTPaths.lua" "DEV41DIR=\"${VTDEV41DIR}\" \n" ) #--------Looking for Virtools WebaPlayer ! Stored in variable "WEBPLAYER" include ("CMakeFindMakeWebPlayer.cmake") IF(WEBPLAYER) MESSAGE(STATUS "\n\n\t Virtools Web Player found : ${WEBPLAYERDIR} \n \n") ELSE(WEBPLAYER) MESSAGE(ERROR "\n\n\t Virtools WebPlayer 4.1 NOT found !!! \n \n") ENDIF(WEBPLAYER) file(APPEND "VTPaths.lua" "WEBPLAYERDIR=\"${WEBPLAYERDIR}\" \n" ) <file_sep>#include "vtConnection.h" #include "xNetInterface.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "IDistributedObjectsInterface.h" #include "IDistributedClasses.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "xDistTools.h" #include "xDistributedSession.h" #include "xDistributedSessionClass.h" #include "xLogger.h" TNL_IMPLEMENT_NETCONNECTION(vtConnection, TNL::NetClassGroupGame, true); int userIDCounter = 0; //extern int sessionIDCounter; #include "ISession.h" #include "xDistributedSession.h" TNL_IMPLEMENT_RPC(vtConnection, s2cAddServerLogEntry, (TNL::StringPtr entry), (entry), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirServerToClient, 0) { } TNL_IMPLEMENT_RPC(vtConnection, c2sDeleteSession_RPC, (TNL::Int<16>sessionID), (sessionID), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirClientToServer, 1) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ISession *sInterface = nInterface->getSessionInterface(); IDistributedObjects *oInterface = nInterface->getDistObjectInterface(); //xLogger::xLog(ELOGINFO,XL_START,"server : deleting session%d",sessionID); xDistributedSession *session = sInterface->get(sessionID); if (!session) { xLogger::xLog(ELOGERROR,XL_START,"client : leaving user %d fails : session doesn't exists",getUserID()); } if (session) { if (!session->isClientJoined(getUserID())) { xLogger::xLog(ELOGINFO,XL_START,"client : deleting session fails, user not joined :%d ",getUserID()); return; } oInterface->deleteObject(session->getServerID()); //xLogger::xLog(ELOGINFO,XL_START,"client : user %d left session : %d ",client->getUserID(),session->getSessionID()); /*client->setSessionID(-1); client->getClientFlags().set(1 << E_CF_SESSION_JOINED,false); client->getClientFlags().set(1 << E_CF_DELETING,true); client->setUserFlags(USER_DELETED);*/ } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection, c2sLockSession_RPC, (TNL::Int<16>sessionID), (sessionID), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirClientToServer, 1) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ISession *sInterface = nInterface->getSessionInterface(); IDistributedObjects *oInterface = nInterface->getDistObjectInterface(); /* xDistributedClient *client = (xDistributedClient*)oInterface->getByUserID(userID,E_DC_BTYPE_CLIENT); if (!client) { xLogger::xLog(ELOGINFO,XL_START,"server : leaving user %d fails : client doesn't exists",userID); } if (client) { xDistributedSession *session = sInterface->get(sessionID); if (session) { if (!session->isClientJoined(userID)) { xLogger::xLog(ELOGINFO,XL_START,"server : leaving user fails :%d on session : %d , user not joined",client->getUserID(),session->getSessionID()); return; } session->removeUser(client); client->setSessionID(-1); setSessionID(-1); client->getClientFlags().set(1 << E_CF_SESSION_JOINED,false); xLogger::xLog(ELOGINFO,XL_START,"server : user %d left session %d",userID,sessionID); TNL::Vector<TNL::NetConnection* > con_list = getInterface()->getConnectionList(); for(int i = 0; i < con_list.size(); i++) { vtConnection *con = (vtConnection *)con_list[i]; con->s2cUserLeftSession_RPC(client->getUserID(),sessionID); } } }*/ } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection, s2cUserLeftSession_RPC, (TNL::Int<16>userID,TNL::Int<16>sessionID), (userID,sessionID), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirServerToClient, 0) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ISession *sInterface = nInterface->getSessionInterface(); IDistributedObjects *oInterface = nInterface->getDistObjectInterface(); if (!nInterface->getCurrentSession()) { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Client : leaving user %d failed : You not joined any Session",userID); } xDistributedClient *client = (xDistributedClient*)oInterface->getByUserID(userID,E_DC_BTYPE_CLIENT); if (!client) { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Removing user %d from session %d failed : client object doesn't exists",userID,sessionID); } if (client) { xDistributedSession *session = sInterface->get(sessionID); if (!session) { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Removing user %d from session %d failed : session doesn't exists",userID,sessionID); } if (session) { if (!session->isClientJoined(userID)) { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Removing user %d from session %d failed : \n\t %s",userID,sessionID,"user not present in this session !"); return; } session->removeUser(client); //xLogger::xLog(ELOGINFO,XL_START,"client : user %d left session : %d ",client->getUserID(),session->getSessionID()); xLogger::xLog(ELOGINFO,E_LI_SESSION,"Removed user %d from session %d !",userID,sessionID); client->setSessionID(-1); disableFlag(client->getClientFlags(),E_CF_SESSION_JOINED); enableFlag(client->getClientFlags(),E_CF_DELETING); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection, c2sLeaveSession_RPC, (TNL::Int<16>userID,TNL::Int<16>sessionID,TNL::Int<16>destroy), (userID,sessionID,destroy), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirClientToServer, 1) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ISession *sInterface = nInterface->getSessionInterface(); IDistributedObjects *oInterface = nInterface->getDistObjectInterface(); xDistributedClient *client = (xDistributedClient*)oInterface->getByUserID(userID,E_DC_BTYPE_CLIENT); if (client) { xDistributedSession *session = sInterface->get(sessionID); if (session) { if (getUserID()!=session->getUserID() && getUserID()!=userID ) { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Server : removing user %d from session :%d failed ! : you must be session master ! ",client->getUserID(),session->getSessionID()); return; } if (!session->isClientJoined(userID)) { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Server : leaving user fails :%d on session : %d , user not joined",client->getUserID(),session->getSessionID()); return; } session->removeUser(client); client->setSessionID(-1); setSessionID(-1); disableFlag(client->getClientFlags(),E_CF_SESSION_JOINED); //xLogger::xLog(ELOGINFO,XL_START,"server : user %d left session %d",userID,sessionID); xLogger::xLog(ELOGINFO,E_LI_SESSION,"Server : user %d left session %d",userID,sessionID); TNL::Vector<TNL::NetConnection* > con_list = getInterface()->getConnectionList(); for(int i = 0; i < con_list.size(); i++) { vtConnection *con = (vtConnection *)con_list[i]; con->s2cUserLeftSession_RPC(client->getUserID(),sessionID); } if (destroy && getUserID()==session->getUserID() ) { xLogger::xLog(ELOGINFO,E_LI_SESSION,"Server : session master %d left !, deleting session %d",userID,sessionID); sInterface->deleteSession(session->getSessionID()); //sessionIDCounter--; } } else { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Server : joining user %d on session : %d failed :\n\t \ , couldn't find session object !",userID,sessionID); } }else { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Server : joining user %d on session : %d failed :\n\t \ , couldn't find client object ",userID,sessionID); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection, c2sJoinSession_RPC, (TNL::Int<16>userID,TNL::Int<16>sessionID,TNL::StringPtr password), (userID,sessionID,password), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirClientToServer, 1) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ISession *sInterface = nInterface->getSessionInterface(); IDistributedObjects *oInterface = nInterface->getDistObjectInterface(); xDistributedClient *client = (xDistributedClient*)oInterface->getByUserID(userID,E_DC_BTYPE_CLIENT); if (client) { xDistributedSession *session = sInterface->get(sessionID); if (session) { if (session->isPrivate()) { if ( strcmp(session->getPassword().getString() , password.getString() ) ) { //xLogger::xLog(ELOGINFO,XL_START,"server : joining user fails :%d on session : %d , password incorrect",client->getUserID(),session->getSessionID()); xLogger::xLog(ELOGERROR,E_LI_SESSION,"Server : joining user %d on session : %d failed :\n\t , password incorrect",client->getUserID(),session->getSessionID()); return; } } if (session->isLocked()) { xLogger::xLog(ELOGWARNING,E_LI_SESSION,"Server : joining user %d on session : %d failed :, session locked",client->getUserID(),session->getSessionID()); return; } if (session->isClientJoined(userID)) { xLogger::xLog(ELOGWARNING,E_LI_SESSION,"Server : joining user %d on session %d failed : \n\t user already joined",client->getUserID(),session->getSessionID()); return; } session->addUser(client); TNL::Vector<TNL::NetConnection* > con_list = getInterface()->getConnectionList(); for(int i = 0; i < con_list.size(); i++) { vtConnection *con = (vtConnection *)con_list[i]; con->s2cUserJoinedSession_RPC(client->getUserID(),sessionID); } client->setSessionID(sessionID); setSessionID(sessionID); client->getClientFlags().set(1 << E_CF_SESSION_JOINED,true); //xLogger::xLog(ELOGINFO,XL_START,"server : joining user :%d on session : %d ",client->getUserID(),session->getSessionID()); xLogger::xLog(ELOGINFO,E_LI_SESSION,"Server : user :%d on session %d joined",client->getUserID(),session->getSessionID()); }else{ xLogger::xLog(ELOGERROR,E_LI_SESSION,"Server : joining user %d on session : %d failed :\n\t , couldn't find session object !",userID,sessionID); } }else { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Server : joining user %d on session : %d failed :\n\t , couldn't find client object ",userID,sessionID); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection, s2cUserJoinedSession_RPC, (TNL::Int<16>userID,TNL::Int<16>sessionID), (userID,sessionID), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirServerToClient, 0) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ISession *sInterface = nInterface->getSessionInterface(); IDistributedObjects *oInterface = nInterface->getDistObjectInterface(); xDistributedClient *client = (xDistributedClient*)oInterface->getByUserID(userID,E_DC_BTYPE_CLIENT); if (client) { xDistributedSession *session = sInterface->get(sessionID); if (session) { xLogger::xLog(XL_START,ELOGINFO,E_LI_SESSION,"session user size : %d ",session->getClientTable().size()); } if (session && !session->isClientJoined(client->getUserID())) { session->addUser(client); client->getClientFlags().set(1 << E_CF_SESSION_JOINED,true); client->getClientFlags().set(1 << E_CF_ADDING,true); client->getClientFlags().set(1 << E_CF_SESSION_DESTROYED,false); client->setSessionID(sessionID); if (userID == getUserID() ) { nInterface->setCurrentSession(session); xLogger::xLog(XL_START,ELOGINFO,E_LI_SESSION,"we entered session, user size : %d ",session->getClientTable().size()); xDistributedObjectsArrayType *distObjects = nInterface->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject *distObject = *begin; if (distObject) { xDistributedClass *_class = distObject->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT ) { xDistributedClient *distClient = static_cast<xDistributedClient*>(distObject); /* if (session->isClientJoined(distClient->getUserID())) { xLogger::xLog(ELOGINFO,E_LI_SESSION,"client %d is in table",distClient->getUserID()); } if (isFlagOn(distClient->getClientFlags(),E_CF_SESSION_JOINED)) { xLogger::xLog(ELOGINFO,E_LI_SESSION,"client %d is has joined flag",distClient->getUserID()); } */ if (distClient && distClient->getSessionID() ==session->getSessionID() ) { enableFlag(distClient->getClientFlags(),E_CF_SESSION_JOINED); enableFlag(distClient->getClientFlags(),E_CF_ADDING); } } } } begin++; } } xLogger::xLog(ELOGINFO,E_LI_SESSION,"Client : user :%d joined on session : %d ,table size : %d",client->getUserID(),session->getSessionID(),session->getClientTable().size()); } /*xLogger::xLog(ELOGERROR,E_LI_SESSION,"Client : joining user %d on session %d failed : \n\t \ Couldn't find Client object for user %d",client->getUserID(),session->getSessionID());*/ } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection, c2sCreateSession_RPC, (TNL::StringPtr name,TNL::Int<16>type,TNL::Int<16>maxUsers,TNL::StringPtr password), (name,type,maxUsers,password), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirClientToServer, 1) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ////////////////////////////////////////////////////////////////////////// //dist class xDistributedSessionClass *classTemplate = (xDistributedSessionClass*)cInterface->get(name.getString()); if (!classTemplate) { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Server : creating session %s by user %d failed : \n\t %s" \ ,name.getString(),getUserID(),"Session class not found "); return; } xLogger::xLog(ELOGINFO,E_LI_SESSION,"Server : Deploying session class for session :%s",classTemplate->getClassName().getString()); ////////////////////////////////////////////////////////////////////////// TNL::Vector<TNL::NetConnection* > con_list = getInterface()->getConnectionList(); for(int i = 0; i < con_list.size(); i++) { vtConnection *con = (vtConnection *)con_list[i]; if (con->getUserID() != getUserID() ) { nInterface->deploySessionClasses(con); } } ////////////////////////////////////////////////////////////////////////// //the distObject : IDistributedObjects *doInterface = nInterface->getDistObjectInterface(); xDistributedSession *distObject = (xDistributedSession*)doInterface->get( name.getString(),E_DC_BTYPE_SESSION); if (distObject) { xLogger::xLog(ELOGERROR,E_LI_SESSION,"Server :session %s already exists!",name.getString()); return; } distObject = new xDistributedSession(); distObject->setDistributedClass(classTemplate); distObject->setObjectFlags(E_DO_CREATION_COMPLETE); distObject->setEntityID(-1); distObject->setServerID(getGhostIndex(distObject)); nInterface->setDOCounter(nInterface->getDOCounter()+1); distObject->SetName(name.getString()); distObject->setNetInterface(nInterface); distObject->setUserID(getUserID()); nInterface->getDistributedObjects()->push_back(distObject); distObject->initProperties(); distObject->setMaxUsers(maxUsers); distObject->setPassword(<PASSWORD>); ((xDistributedSession*)distObject)->setPassword(password); float time = (float)Platform::getRealMilliseconds(); int uid = getUserID(); distObject->setCreationTime(time); xLogger::xLog(ELOGINFO,E_LI_SESSION,"Server : Client created session %s",name.getString()); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection, c2sDORequestOwnerShip, (TNL::S32 userID,TNL::Int<16>serverID), (userID,serverID), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirClientToServer, 1) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ////////////////////////////////////////////////////////////////////////// //the distObject : IDistributedObjects *doInterface = nInterface->getDistObjectInterface(); xDistributedObject *distObject = doInterface->get( serverID ); if (distObject) { xLogger::xLog(ELOGINFO,XL_START,"user : %d is requesting ownership for object :%d|currentOwner:%d",getUserID(),serverID,distObject->getUserID()); distObject->setUserID(userID); } if (distObject /*&& distObject->getUserID() != getUserID() */) { TNL::Vector<TNL::NetConnection* > con_list = getInterface()->getConnectionList(); for(int i = 0; i < con_list.size(); i++) { vtConnection *con = (vtConnection *)con_list[i]; con->s2cDOChangeOwnershipState(serverID,userID,E_DO_OS_OWNERCHANGED); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection, s2cDOChangeOwnershipState, (TNL::Int<16>serverID,TNL::S32 newOwnerID,TNL::S32 state), (serverID,newOwnerID,state), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirServerToClient, 0) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ////////////////////////////////////////////////////////////////////////// //the distObject : IDistributedObjects *doInterface = nInterface->getDistObjectInterface(); xDistributedObject *distObject = doInterface->get( serverID ); if (distObject) { xLogger::xLog(ELOGINFO,XL_START,"user. %d : ownerchange retrieved for obj :%d from user %d",getUserID(),serverID,newOwnerID ); //distObject->getOwnershipState().set( 1<<E_DO_OS_OWNERCHANGED ,distObject->getUserID() !=newOwnerID ); distObject->getOwnershipState().set( 1<<E_DO_OS_OWNERCHANGED ,true); distObject->setUserID(newOwnerID); distObject->getOwnershipState().set( 1<<E_DO_OS_OWNER, distObject->getUserID() == getUserID() ); distObject->getOwnershipState().set( 1 << E_DO_OS_BIND , !distObject->isOwner() ); distObject->getOwnershipState().set( 1 << E_DO_OS_RELEASED, newOwnerID ? true : false ); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void vtConnection::writePacket(TNL::BitStream *bstream,TNL::NetConnection::PacketNotify*notify) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); if(isConnectionToServer()) { U32 firstSendIndex = highSendIndex[0]; if(firstSendIndex < firstMoveIndex) firstSendIndex = firstMoveIndex; bstream->write(getControlCRC()); bstream->write(firstSendIndex); U32 skipCount = firstSendIndex - firstMoveIndex; U32 moveCount = 0 - skipCount; bstream->writeRangedU32(moveCount, 0, MaxPendingMoves); int updateCount =nInterface->getObjectUpdateCounter(); int flag = NO_UPDATE; if (updateCount) { mWriteTypeTracker=0; flag = GHOST_UPDATE; }else { ((GamePacketNotify *) notify)->updateType=NO_UPDATE; } //sending update flag : bstream->writeRangedU32(flag, 0, MaxPendingMoves); if (flag == GHOST_UPDATE) { //Sending object count : bstream->writeRangedU32(updateCount, 0, MaxPendingMoves); xDistributedObjectsArrayType *distObjects = nInterface->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject *cobj = *begin; if (cobj && cobj->getUpdateState()==E_DO_US_PENDING) { ////////////////////////////////////////////////////////////////////////// //writing out objects id : S32 ghostIndex = getGhostIndex(cobj); bstream->writeInt(ghostIndex, GhostConnection::GhostIdBitSize); ////////////////////////////////////////////////////////////////////////// //writing objects state : cobj->pack(bstream); cobj->setUpdateState(E_DO_US_SEND); } begin++; } } } else { S32 ghostIndex = -1; if(scopeObject.isValid()) { ghostIndex = getGhostIndex(scopeObject); } mCompressPointsRelative = bstream->writeFlag(ghostIndex != -1); if(bstream->writeFlag(getControlCRC() != mLastClientControlCRC)) { if(ghostIndex != -1) { bstream->writeInt(ghostIndex, GhostConnection::GhostIdBitSize); scopeObject->writeControlState(bstream); } } } //xLogger::xLog(ELOGINFO,XL_START,"pkt w"); Parent::writePacket(bstream, notify); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void vtConnection::readPacket(TNL::BitStream *bstream) { //xLogger::xLog(ELOGINFO,XL_START,"pkt"); xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedObjects *doInterface = nInterface->getDistObjectInterface(); bool replayControlObjectMoves = false; if(isConnectionToClient()) { bstream->read(&mLastClientControlCRC); U32 firstMove; bstream->read(&firstMove); U32 count = bstream->readRangedU32(0, MaxPendingMoves); count +=0; //retrieving update flag : U32 flag = bstream->readRangedU32(0, MaxPendingMoves); if ( flag == GHOST_UPDATE) { //xLogger::xLog(ELOGINFO,XL_START,"ghost update received"); //retrieve object counter : U32 ocounter = bstream->readRangedU32(0, MaxPendingMoves); for (unsigned int i = 0 ; i<ocounter ; i++ ) { U32 ghostIndex = bstream->readInt(GhostConnection::GhostIdBitSize); /*xDistributedClient *dstClient = static_cast<xDistributedClient*>(doInterface->getByUserID(getUserID(),E_DC_BTYPE_CLIENT)); if (dstClient) { xLogger::xLog(ELOGINFO,XL_START,"ghost update received from %d",getUserID()); dstClient->setLastUpdater(getUserID()); dstClient->unpack(bstream,getOneWayTime()); }*/ xDistributedObject *dobj = static_cast<xDistributedObject*>(resolveGhostParent(ghostIndex)); if (dobj) { dobj->setLastUpdater(ghostIndex); dobj->unpack(bstream,getOneWayTime()); //xLogger::xLog(ELOGINFO,XL_START,"ghost update received from %d for object :%d | foundbyIndex %d",getUserID(),getGhostIndex(dobj),dobj->getUserID()); } } } } else { bool controlObjectValid = bstream->readFlag(); mCompressPointsRelative = controlObjectValid; // CRC mismatch... if(bstream->readFlag()) { if(controlObjectValid) { U32 ghostIndex = bstream->readInt(GhostConnection::GhostIdBitSize); controlObject = (xDistributedClient*) resolveGhost(ghostIndex); controlObject->readControlState(bstream); replayControlObjectMoves = true; } else { controlObject = NULL; } } } Parent::readPacket(bstream); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection,c2sDeployDistributedClass, ( TNL::StringPtr className, TNL::Int<16>entityType, TNL::Vector<TNL::StringPtr>propertyNames, TNL::Vector<TNL::Int<16> >propertyNativeTypes, TNL::Vector<TNL::Int<16> >propertyValueTypes, TNL::Vector<TNL::Int<16> >predictionTypes), (className, entityType, propertyNames, propertyNativeTypes, propertyValueTypes, predictionTypes), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirClientToServer, 1) { unsigned int SizeProps = propertyNames.size(); xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); xDistributedClass *classTemplate = cInterface->get(className); if (!classTemplate) { classTemplate = cInterface ->createClass(className,entityType); } xLogger::xLog(XL_START,ELOGTRACE,E_LI_DISTRIBUTED_CLASS_DESCRIPTORS,"Server : Class deployment of %s received by user : %d" , className.getString(),getUserID() ); for (unsigned int i = 0 ; i < SizeProps ; i ++) { xDistributedPropertyInfo *dInfo = classTemplate->exists(propertyNames[i]); if (!dInfo) { dInfo = new xDistributedPropertyInfo( propertyNames[i] ,propertyValueTypes[i],propertyNativeTypes[i],predictionTypes[i]); classTemplate->getDistributedProperties()->push_back( dInfo); xLogger::xLog(XL_START,ELOGTRACE,E_LI_DISTRIBUTED_CLASS_DESCRIPTORS,"\t property attachment : %s | type : %s" , propertyNames[i].getString(), xDistTools::ValueTypeToString(propertyValueTypes[i]).getString()); // xLogger::xLogExtro(0,"\t property attachment : %s | type : %s" , propertyNames[i].getString(), xDistTools::ValueTypeToString(propertyValueTypes[i]).getString()); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection,s2cDeployDistributedClass, ( TNL::StringPtr className, TNL::Int<16>entityType, TNL::Vector<TNL::StringPtr>propertyNames, TNL::Vector<TNL::Int<16> >propertyNativeTypes, TNL::Vector<TNL::Int<16> >propertyValueTypes, TNL::Vector<TNL::Int<16> >predictionTypes), (className, entityType, propertyNames, propertyNativeTypes, propertyValueTypes, predictionTypes), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirServerToClient, 0) { unsigned int SizeProps = propertyNames.size(); xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); xDistributedClass *classTemplate = cInterface->get(className); if (!classTemplate) classTemplate = cInterface ->createClass(className,entityType); xLogger::xLog(ELOGINFO,E_LI_DISTRIBUTED_CLASS_DESCRIPTORS,"Class deployment of class %s recieved" , className.getString() ); for (unsigned int i = 0 ; i < SizeProps ; i ++) { xDistributedPropertyInfo *dInfo = classTemplate->exists(propertyNames[i]); if (!dInfo) { dInfo = new xDistributedPropertyInfo( propertyNames[i] ,propertyValueTypes[i],propertyNativeTypes[i],predictionTypes[i]); classTemplate->getDistributedProperties()->push_back( dInfo); //xLogger::xLog(ELOGINFO,XL_START,"\t property attachment : %s | type : %s" , propertyNames[i].getString(), xDistTools::ValueTypeToString(propertyValueTypes[i]).getString()); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection,c2sDOCreate, ( TNL::Int<16>userSrcID, TNL::StringPtr objectName, TNL::StringPtr className, TNL::Int<16>classType), (userSrcID, objectName, className, classType), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirClientToServer, 1) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ////////////////////////////////////////////////////////////////////////// //dist class xDistributedClass *classTemplate = cInterface->get(className); if (!classTemplate){ xLogger::xLog(ELOGERROR,E_LI_DISTRIBUTED_BASE_OBJECT,"Server : creating dist object %s by user %d failed! class %s not found!" ,objectName.getString(),getUserID(),className.getString()); classTemplate = cInterface ->createClass(className,classType); } ////////////////////////////////////////////////////////////////////////// //the distObject : IDistributedObjects *doInterface = nInterface->getDistObjectInterface(); xDistributedObject *distObject = doInterface->get( objectName.getString() ); IDistributedObjects *oInterface = nInterface->getDistObjectInterface(); xDistributedClient *client = (xDistributedClient*)oInterface->getByUserID(userSrcID,E_DC_BTYPE_CLIENT); if (!client) return; if (distObject) return; switch(classTemplate->getEnitityType()) { case E_DC_BTYPE_3D_ENTITY: { distObject = new xDistributed3DObject(); distObject->setDistributedClass(classTemplate); distObject->setObjectFlags(E_DO_CREATION_COMPLETE); distObject->setEntityID(-1); distObject->setServerID(getGhostIndex(distObject)); nInterface->setDOCounter(nInterface->getDOCounter()+1); distObject->SetName(objectName.getString()); distObject->setNetInterface(nInterface); distObject->setUserID(getUserID()); nInterface->getDistributedObjects()->push_back(distObject); distObject->initProperties(); int op = client->getSessionID(); distObject->setSessionID(client->getSessionID()); float time = (float)Platform::getRealMilliseconds(); int uid = getUserID(); distObject->setCreationTime(time); xLogger::xLog(ELOGERROR,E_LI_3DOBJECT,"Server : 3d object created by user %d | sessionID :%d",client->getUserID(),client->getSessionID()); } break; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection,c2sDODestroy, ( TNL::Int<16>userSrcID, TNL::Int<16>serverID, TNL::StringPtr className, TNL::Int<16>classType), (userSrcID, serverID, className, classType), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirClientToServer, 1) { xNetInterface *nInterface = static_cast<xNetInterface *>(getInterface()); IDistributedClasses *cInterface = nInterface->getDistributedClassInterface(); ////////////////////////////////////////////////////////////////////////// //dist class xDistributedClass *classTemplate = cInterface->get(className); if (!classTemplate) classTemplate = cInterface ->createClass(className,classType); ////////////////////////////////////////////////////////////////////////// //the distObject : IDistributedObjects *doInterface = nInterface->getDistObjectInterface(); xDistributedObject *distObject = doInterface->get( serverID ); if (!distObject) { xLogger::xLog(XL_START,ELOGERROR,E_LI_DISTRIBUTED_BASE_OBJECT,"Couldn't find object with server id :%d",serverID); return; } xLogger::xLog(ELOGINFO,E_LI_DISTRIBUTED_BASE_OBJECT,"Server : deleting dist object :%s %d",distObject->GetName().getString(),distObject->getServerID()); doInterface->deleteObject(distObject->getServerID()); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void vtConnection::connect(TNL::NetInterface *theInterface, const TNL::Address &address, bool requestKeyExchange, bool requestCertificate) { Parent::connect(theInterface,address,requestKeyExchange,requestCertificate); if (theInterface) { TNL::Vector<TNL::NetConnection* > con_list = getInterface()->getConnectionList(); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ vtConnection::vtConnection() { setTranslatesStrings(); m_UserName = "not set"; m_UserID =0; m_ConnectionID = 0; //setIsAdaptive(); // <-- Uncomment me if you want to use adaptive rate instead of fixed rate... highSendIndex[0] = 0; highSendIndex[1] = 0; highSendIndex[2] = 0; mLastClientControlCRC = 0; firstMoveIndex = 1; mMoveTimeCredit = 0; mWriteTypeTracker=0; mSessionID = -1; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool vtConnection::isDataToTransmit() { // we always want packets to be sent. return true; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void vtConnection::onConnectTerminated(NetConnection::TerminationReason reason, const char *string) { ((xNetInterface *) getInterface())->pingingServers = true; } /* ******************************************************************* * Function: onConnectionTerminated * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void vtConnection::onConnectionTerminated(NetConnection::TerminationReason reason, const char *edString) { //logprintf("%s - %s connection terminated - reason %d.", getNetAddressString(), isConnectionToServer() ? "server" : "client", reason); xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"%s - %s connection terminated - reason %d.", getNetAddressString(), isConnectionToServer() ? "Server" : "Client", reason); int userID = getUserID(); xNetInterface *ninterface = static_cast<xNetInterface*>(getInterface()); if (!ninterface->IsServer()) { xLogger::xLog(ELOGERROR,E_LI_CONNECTION,"Server connection terminated ! - reason %d.", reason); //ninterface->checkObjects(); ninterface->setConnection(NULL); enableFlag(ninterface->getInterfaceFlags(),E_NI_DESTROYED_BY_SERVER); } if (ninterface->IsServer()) { ISession *sInterface = ninterface->getSessionInterface(); IDistributedObjects *oInterface = ninterface->getDistObjectInterface(); xDistributedClient *client = (xDistributedClient*)oInterface->getByUserID(userID,E_DC_BTYPE_CLIENT); if (client) { xDistributedSession *session = sInterface->get(client->getSessionID()); if (session) { //logprintf("removing client from session"); session->removeUser(client); }else xLogger::xLog(ELOGWARNING,E_LI_CONNECTION,"User disconnected : couldn't find session object"); }else { xLogger::xLog(ELOGERROR,E_LI_CONNECTION,"User disconnected : couldn't find client object"); } //logprintf("removing client from database"); ninterface->removeClient(userID); //userIDCounter--;// } if(isConnectionToServer()) ((xNetInterface *) getInterface())->pingingServers = true; if (ninterface) { ninterface->setCheckObjects(true); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void vtConnection::onConnectionEstablished() { Parent::onConnectionEstablished(); //setSimulatedNetParams(0.0, 0.1); //TNL::GhostConnection::setPingTimeouts(1000,3); xNetInterface *netInterface = (xNetInterface *)getInterface(); if (!netInterface) return; if (!netInterface->getDistributedClassInterface())return; if(isInitiator()) { setGhostFrom(false); setGhostTo(true); xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Client - connected to server : %s", getNetAddressString()); netInterface->connectionToServer = this; } else { localAddress = TNL::Address(getNetAddressString()); xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Server : client %s connected", getNetAddressString()); xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Server : deploying session classes"); netInterface->deploySessionClasses(this); scopeObject = new xDistributedClient(); scopeObject->setObjectFlags(E_DO_CREATION_COMPLETE); scopeObject->setEntityID(userIDCounter); scopeObject->setUserID(userIDCounter); scopeObject->setServerID(-1); scopeObject->setCreationTime((float)Platform::getRealMilliseconds()); scopeObject->SetName("Client"); scopeObject->setOwnerConnection(this); setUserID(userIDCounter); scopeObject->setLocalAddress(getNetAddressString()); scopeObject->setUserName(getNetAddressString()); if (netInterface) { scopeObject->setNetInterface(netInterface); } xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); xDistributedClass *clientClass = netInterface->getDistributedClassInterface()->createClass("CLIENT CLASS",E_DC_BTYPE_CLIENT); scopeObject->setDistributedClass(clientClass); distObjects->push_back(scopeObject); setScopeObject(scopeObject); setGhostFrom(true); setGhostTo(false); activateGhosting(); //we call SetUserDetails on the client : s2cSetUserDetails(userIDCounter); userIDCounter++; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL_IMPLEMENT_RPC(vtConnection, s2cSetUserDetails, (TNL::Int<16>userID), (userID), NetClassGroupGameMask, RPCGuaranteedOrdered, RPCDirServerToClient, 0) { setUserID(userID); ((xNetInterface*)getInterface())->setMyUserID(userID); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void vtConnection::addUpdateObject(xDistributedObject*object) { for (int i=0 ; i < pendingObjects.size() ; i ++ ) { xDistributedObject *_cobj = pendingObjects[i]; if (_cobj) { if (object == _cobj) return; } } pendingObjects.push_back(object); object->setUpdateState( E_DO_US_PENDING ); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ TNL::U32 vtConnection::getControlCRC() { PacketStream stream; xDistributedClient*co= (xDistributedClient*) getScopeObject(); if(!co) return 0; stream.writeInt(getGhostIndex(co), GhostConnection::GhostIdBitSize); co->writeControlState(&stream); stream.zeroToByteBoundary(); return stream.calculateCRC(0, stream.getBytePosition()); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void vtConnection::packetReceived(TNL::GhostConnection::PacketNotify *notify) { for(; firstMoveIndex < ((GamePacketNotify *) notify)->firstUnsentMoveIndex; firstMoveIndex++) { pendingObjects.erase(U32(0)); } //mReadType = ((GamePacketNotify *) notify)->updateType; Parent::packetReceived(notify); if (mReadType == GHOST_UPDATE) { //xLogger::xLog(ELOGINFO,XL_START,"ghost update pkt!"); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void vtConnection::disconnectFromServer() { if (getConnectionState() == TNL::NetConnection::Connected) { //disconnect("no reason"); } }<file_sep>//////////////////////////////////////////////////////////////////////////////// // // ARTPlusMulti // ------------ // // Description: // The ARTPlus building block initialize the ARToolKitPlus for multi marker // detection. It should called once in your virtools project. Due to the fact, // that the number of pattern which can be detected, is set on compile time, // you can only detect 30 Pattern inside a video frame. If you want to detect // more, than you have to change the number and recompile (See line 185). // // Input Parameter: // IN_VIDEO_TEXTURE : The image, in with ARToolKitPlus // perform the detection // IN_CAMERA_PARAM_FILE : The filename of the camera parameter file // (look into ARToolKitPlus for description) // IN_NEAR_CLIP_PLANE : Near clip plane used by the camera // IN_FAR_CLIP_PLANE : Far clip plane used by the camera // (look into ARToolKitPlus for description) // IN_ENABLE_CAMERA_CORRECTION : // Flag which indicates that the ARToolKitPlusManager // should use the camera transformation matrix as // projection matrix // // Output Parameter: // OUT_CAMERA_TRANSFORM_MATRIX : // The camera transformation matrix. // OUT_ERROR_STRING : String which describe the error, if one occurs. If // there was no error the string will contain the word // "Success" (without the marks) // // Version 1.0 : First Release // // Known Bugs : None // // Copyright <NAME> <<EMAIL>>, University of Paderborn //////////////////////////////////////////////////////////////////////////////// // Input Parameter #define IN_VIDEO_TEXTURE 0 #define IN_CAMERA_PARAM_FILE 1 #define IN_MULTIMARKER_CONFIG_FILE 2 #define IN_NEAR_CLIP_PLANE 3 #define IN_FAR_CLIP_PLANE 4 #define IN_ENABLE_CAMERA_CORRECTION 5 // Output Parameter #define OUT_CAMERA_TRANSFORM_MATRIX 0 #define OUT_ERROR_STRING 1 // Output Signals #define OUTPUT_OK 0 #define OUTPUT_ERROR 1 #include "CKAll.h" #include "ARToolKitLogger.h" #include <ARToolKitPlus/TrackerMultiMarkerImpl.h> CKObjectDeclaration *FillBehaviorARTPlusMultiDecl(); CKERROR CreateARTPlusMultiProto(CKBehaviorPrototype **); void cleanUp(); int ARTPlusMulti(const CKBehaviorContext& BehContext); int ARTPlusMultiCallBack(const CKBehaviorContext& BehContext); bool ARTPlusMultiInitialized = false; bool ARTPlusMultiCorrectCamera = true; extern void argConvGlpara( float para[4][4], float gl_para[16] ); extern void argConvGlparaTrans( float para[4][4], float gl_para[16] ); ARToolKitPlus::TrackerMultiMarker *multiTracker = NULL; ARToolKitLogger multiLogger; CKObjectDeclaration *FillBehaviorARTPlusMultiDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Multi Marker Tracker"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetVersion(0x00010000); od->SetCreationFunction(CreateARTPlusMultiProto); od->SetDescription("Multi Marker Tracker"); od->SetCategory("ARToolKitPlus"); od->SetGuid(CKGUID(0xa59f1,0x3d486f81)); od->SetAuthorGuid(CKGUID(0x56495254,0x4f4f4c53)); od->SetAuthorName("<NAME>"); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateARTPlusMultiProto(CKBehaviorPrototype** pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Multi Marker Tracker"); if (!proto) { return CKERR_OUTOFMEMORY; } //--- Inputs declaration proto->DeclareInput("In"); //--- Outputs declaration proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); //--- Input Parameters declaration proto->DeclareInParameter("Video Image", CKPGUID_TEXTURE); proto->DeclareInParameter("Camera-Param File", CKPGUID_STRING, "c:\\LogitechPro4000.dat"); proto->DeclareInParameter("Multimarker Config File", CKPGUID_STRING, "c:\\markerboard_480-499.cfg"); proto->DeclareInParameter("Near Clip Plane", CKPGUID_FLOAT, "1.0"); proto->DeclareInParameter("Far Clip Plane", CKPGUID_FLOAT, "1000.0"); proto->DeclareInParameter("Enable Camera Correction", CKPGUID_BOOL, "TRUE"); //--- Output Parameters declaration proto->DeclareOutParameter("CameraMatrix", CKPGUID_MATRIX); proto->DeclareOutParameter("Error", CKPGUID_STRING, "Success"); //---- Local Parameters Declaration //---- Settings Declaration proto->SetBehaviorCallbackFct(ARTPlusMultiCallBack, CKCB_BEHAVIORATTACH|CKCB_BEHAVIORDETACH|CKCB_BEHAVIORDELETE|CKCB_BEHAVIOREDITED|CKCB_BEHAVIORSETTINGSEDITED|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORPRESAVE|CKCB_BEHAVIORPOSTSAVE|CKCB_BEHAVIORRESUME|CKCB_BEHAVIORPAUSE|CKCB_BEHAVIORRESET|CKCB_BEHAVIORRESET|CKCB_BEHAVIORDEACTIVATESCRIPT|CKCB_BEHAVIORACTIVATESCRIPT|CKCB_BEHAVIORREADSTATE, NULL); proto->SetFunction(ARTPlusMulti); *pproto = proto; return CK_OK; } int ARTPlusMulti(const CKBehaviorContext& BehContext) { CKBehavior* beh = BehContext.Behavior; float nearclip = 1.0f; float farclip = 1000.0f; float* buffer = NULL; float gl_matirx[4][4]; beh->ActivateInput(0,FALSE); if(ARTPlusMultiInitialized == false) { CKTexture* texture = NULL; CKSTRING camparam = NULL; CKSTRING multiConfig = NULL; float nearclip = 1.0f; float farclip = 1000.0f; CKBOOL enableCamCorr = TRUE; // Texture (Important, request the Object not the Value or the Ptr!!!) texture = CKTexture::Cast(beh->GetInputParameterObject(IN_VIDEO_TEXTURE)); if(texture == NULL) { beh->ActivateOutput(OUTPUT_ERROR); char string[] = "ERROR: No Texture Present"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKERR_NOTINITIALIZED; } int width = texture->GetWidth(); int height = texture->GetHeight(); int windowwidth = BehContext.CurrentRenderContext->GetWidth(); int windowheight = BehContext.CurrentRenderContext->GetHeight(); // Get camera parameter camparam = (CKSTRING)(beh->GetInputParameterReadDataPtr(IN_CAMERA_PARAM_FILE)); // Get multi marker config multiConfig = (CKSTRING)(beh->GetInputParameterReadDataPtr(IN_MULTIMARKER_CONFIG_FILE)); // Fetch value for NearClip beh->GetInputParameterValue(IN_NEAR_CLIP_PLANE, &nearclip); // Fetch value for FarClip beh->GetInputParameterValue(IN_FAR_CLIP_PLANE, &farclip); // create a tracker that does: // - 12x12 sized marker images // - samples at a maximum of 12x12 // - works with luminance (gray) images // - can load a maximum of 1 pattern // - can detect a maximum of 30 patterns in one image multiTracker = new ARToolKitPlus::TrackerMultiMarkerImpl<12,12,12,1,30>(width, height); // set a logger so we can output error messages multiTracker->setLogger(&multiLogger); multiTracker->setPixelFormat(ARToolKitPlus::PIXEL_FORMAT_ABGR); multiTracker->setLoadUndistLUT(true); multiTracker->setImageProcessingMode(ARToolKitPlus::IMAGE_FULL_RES); multiTracker->setUseDetectLite(false); if(!multiTracker->init(camparam, multiConfig, nearclip, farclip)) { printf("ERROR: init() failed\n"); delete multiTracker; multiTracker = NULL; beh->ActivateOutput(OUTPUT_ERROR); char string[] = "ERROR: init() failed"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKERR_NOTINITIALIZED; } // Get value for camera correction enable beh->GetInputParameterValue(IN_ENABLE_CAMERA_CORRECTION, &enableCamCorr); ARTPlusMultiCorrectCamera = enableCamCorr==TRUE?true:false; // let's use lookup-table undistortion for high-speed // note: LUT only works with images up to 1024x1024 multiTracker->setUndistortionMode(ARToolKitPlus::UNDIST_LUT); // RPP is more robust than ARToolKit's standard pose estimator multiTracker->setPoseEstimator(ARToolKitPlus::POSE_ESTIMATOR_RPP); ARTPlusMultiInitialized = true; } beh->ActivateOutput(OUTPUT_OK); buffer = (float *)multiTracker->getProjectionMatrix(); argConvGlpara(gl_matirx, buffer); VxMatrix mat = VxMatrix(gl_matirx); // set matrix beh->SetOutputParameterValue(OUT_CAMERA_TRANSFORM_MATRIX, &mat, 0); // set error string char string[] = "Success"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKBR_OK; } int ARTPlusMultiCallBack(const CKBehaviorContext& BehContext) { switch (BehContext.CallbackMessage) { case CKM_BEHAVIORATTACH: break; case CKM_BEHAVIORDETACH: break; case CKM_BEHAVIORDELETE: { cleanUp(); break; } case CKM_BEHAVIOREDITED: break; case CKM_BEHAVIORSETTINGSEDITED: break; case CKM_BEHAVIORLOAD: break; case CKM_BEHAVIORPRESAVE: break; case CKM_BEHAVIORPOSTSAVE: break; case CKM_BEHAVIORRESUME: break; case CKM_BEHAVIORPAUSE: break; case CKM_BEHAVIORRESET: { cleanUp(); break; } case CKM_BEHAVIORNEWSCENE: break; case CKM_BEHAVIORDEACTIVATESCRIPT: break; case CKM_BEHAVIORACTIVATESCRIPT: break; case CKM_BEHAVIORREADSTATE: break; } return CKBR_OK; } void cleanUp() { if(ARTPlusMultiInitialized) { multiTracker->cleanup(); delete multiTracker; ARTPlusMultiInitialized = false; } multiTracker = NULL; } <file_sep>#include "pch.h" #include "InitMan.h" #include "CKAll.h" #include "VSLManagerSDK.h" #include "Dll_Tools.h" #include "crypting.h" static InitMan *_im=NULL; extern InitMan* _im2=NULL; InitMan *manager=NULL; InitMan*InitMan::GetInstance() { return manager; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// InitMan::InitMan(CKContext* context):CKBaseManager(context,INIT_MAN_GUID,"mw tool manager")//Name as used in profiler { m_Context->RegisterNewManager(this); _im = this; _im2 = this; manager = this; } struct IntersectionDescription { // The Ray Itself VxRay m_Ray; VxVector m_RayEnd; float m_Depth; VxIntersectionDesc m_MinDesc; CK3dEntity* m_MinEntity; float m_MinDistance2; // square magnitude temporary distance to help us know which will be the nearest intersected object }; void Intersect2(CK3dEntity* Currentobject,IntersectionDescription* idesc,CKScene* scene); IntersectionDescription Intersect(CK3dEntity* Tobject,VxVector Direction,VxVector Origin,float Depth); VxVector GetRayDistance(CK3dEntity* ent,VxVector Direction,VxVector Origin,float Depth ){ IntersectionDescription desc = Intersect(ent,Direction,Origin,Depth); return VxVector(desc.m_MinDesc.IntersectionPoint); } IntersectionDescription Intersect(CK3dEntity* Tobject,VxVector Direction,VxVector Origin,float Depth){ Direction.Normalize(); IntersectionDescription idesc; // Ray Members idesc.m_Ray.m_Origin = Origin; idesc.m_Ray.m_Direction = Direction; idesc.m_RayEnd = Origin + Direction; idesc.m_Depth = Depth; // Nearest Members idesc.m_MinDistance2 = Depth*Depth; idesc.m_MinEntity = NULL; CKScene *scene = Tobject->GetCKContext()->GetCurrentScene(); CKAttributeManager* attman = Tobject->GetCKContext()->GetAttributeManager(); int collatt = attman->GetAttributeTypeByName("Moving Obstacle"); int flooratt = attman->GetAttributeTypeByName("Floor"); const XObjectPointerArray& Array = attman->GetAttributeListPtr(collatt); for (CKObject** it = Array.Begin(); it != Array.End(); ++it){ CK3dEntity *Currentobject = (CK3dEntity*)*it; if (Currentobject!=Tobject) Intersect2(Currentobject,&idesc,scene); } if (idesc.m_MinEntity && (idesc.m_MinDistance2 < Depth*Depth)) { VxVector IntersectionPoint; idesc.m_MinEntity->Transform(&IntersectionPoint,&idesc.m_MinDesc.IntersectionPoint); VxVector IntersectionNormal; idesc.m_MinEntity->TransformVector(&IntersectionNormal,&idesc.m_MinDesc.IntersectionNormal); IntersectionNormal.Normalize(); idesc.m_MinDistance2 = sqrtf(idesc.m_MinDistance2); return idesc; } return idesc; } void Intersect2(CK3dEntity* Currentobject,IntersectionDescription* idesc,CKScene* scene) { // not a 3D object //________________________________/ Rejection if not visible if (CKIsChildClassOf(Currentobject,CKCID_SPRITE3D)) { // Ray Inter VxIntersectionDesc Inter; VxVector IntersectionPoint; if ( Currentobject->RayIntersection(&idesc->m_Ray.m_Origin,&idesc->m_RayEnd,&Inter,NULL) ){ Currentobject->Transform(&IntersectionPoint, &Inter.IntersectionPoint); float Dist = SquareMagnitude( IntersectionPoint - idesc->m_Ray.m_Origin ); if ( Dist < idesc->m_MinDistance2){ idesc->m_MinDistance2 = Dist; idesc->m_MinEntity = Currentobject; idesc->m_MinDesc = Inter; } } return; // stop there } //________________________________/ Rejection by Bounding Sphere / Depth float radius = Currentobject->GetRadius(); VxVector pos; Currentobject->GetBaryCenter( &pos ); VxVector dif = pos-idesc->m_Ray.m_Origin; float Dist = SquareMagnitude( dif ); BOOL character = false; if( Dist < (idesc->m_Depth+radius)*(idesc->m_Depth+radius) ){ //______________________________/ Rejection by Sphere / Behind float s = DotProduct(dif, idesc->m_Ray.m_Direction); if( s+radius > 0.0f ){ //______________________________/ Rejection by Bounding Sphere / Segment if( radius*radius > Dist-s*s ){ //______________________________/ Rejection by Bounding Cube (in world) const VxBbox& box = Currentobject->GetBoundingBox(); VxVector IntersectionPoint; if (VxIntersect::RayBox(idesc->m_Ray,box)) { if(character) { int count = ((CKCharacter*)Currentobject)->GetBodyPartCount(); while( count ){ CKBodyPart* bp; if( bp = ((CKCharacter*)Currentobject)->GetBodyPart( --count ) ){ //______________________________/ Reject BodyPart by Bounding Cube (in world) if( VxIntersect::RayBox(idesc->m_Ray,bp->GetBoundingBox()) ) { // Ray Inter VxIntersectionDesc Inter; if ( bp->RayIntersection(&idesc->m_Ray.m_Origin,&idesc->m_RayEnd,&Inter,NULL) ){ bp->Transform(&IntersectionPoint, &Inter.IntersectionPoint); Dist = SquareMagnitude( IntersectionPoint - idesc->m_Ray.m_Origin ); if ( Dist < idesc->m_MinDistance2){ idesc->m_MinDistance2 = Dist; idesc->m_MinEntity = Currentobject; idesc->m_MinDesc = Inter; } } } } } } else { // Ray Inter VxIntersectionDesc Inter; if ( Currentobject->RayIntersection(&idesc->m_Ray.m_Origin,&idesc->m_RayEnd,&Inter,NULL) ){ Currentobject->Transform(&IntersectionPoint, &Inter.IntersectionPoint); Dist = SquareMagnitude( IntersectionPoint - idesc->m_Ray.m_Origin ); if ( Dist < idesc->m_MinDistance2){ idesc->m_MinDistance2 = Dist; idesc->m_MinEntity = Currentobject; idesc->m_MinDesc = Inter; } } } } } } } } //Saves an Object************************************************************************/ void LoadFile(CK3dEntity* ent, const char*str){ if (strlen(str)<=0) return; CKContext *ctx = ent->GetCKContext(); CKLevel* TheLevel=ctx->GetCurrentLevel(); CKRenderManager *rm = ctx->GetRenderManager(); CKRenderContext *rtx = rm->GetRenderContext(0); ctx->Pause(); ctx->Reset(); //ctx->ClearAll(); /* CKObjectArray *array=CreateCKObjectArray(); //-- Loads m_eptrs.The file and fills m_eptrs.The array with loaded objects CKERROR res=CK_OK; if ((res=ctx->Load((char*) str,array))==CK_OK) { //--- Add m_eptrs.The render context to m_eptrs.The level TheLevel->AddRenderContext(rtx,TRUE); //--- Take m_eptrs.The first camera we found and attach m_eptrs.The viewpoint to it. CK_ID* cam_ids=ctx->GetObjectsListByClassID(CKCID_CAMERA); if (!cam_ids) cam_ids=ctx->GetObjectsListByClassID(CKCID_TARGETCAMERA); if (cam_ids) { CKCamera *camera=(CKCamera *)ctx->GetObject(cam_ids[0]); if (camera) rtx->AttachViewpointToCamera(camera); } //--- Sets m_eptrs.The initial conditions for m_eptrs.The level TheLevel->LaunchScene(NULL); } */ // DeleteCKObjectArray(array); } void SaveObject(CKBeObject*beo,char *filename){ if (beo && strlen(filename)){ CKObjectArray* oa = CreateCKObjectArray(); oa->InsertAt(beo->GetID()); beo->GetCKContext()->Save(filename,oa,0xFFFFFFFF,NULL); } } /* void SaveObjectScipt(CKBeObject*beo,char *filename,int pos){ if (beo && strlen(filename)){ CKObjectArray* oa = CreateCKObjectArray(); if beo->GetScriptCount() && //savity check pos <=beo->GetScriptCount() && pos>=0 //index bound check ) oa->InsertAt( beo->GetScript(pos) ); beo->GetCKContext()->Save(filename,oa,0xFFFFFFFF,NULL); } } */ /**********************************/ #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <io.h> #include <stdio.h> #include <Windows.h> #include <tchar.h> #include <WTYPES.H> #include <BASETSD.H> #include <stdlib.h> #include <vector> /* void GetSDate(int& year,int&month, int&day){ SYSTEMTIME sys; GetSystemTime(&sys); RDateTime ft; ft.Set(sys); RDate currentRD = ft; year = currentRD.GetYear(); month = currentRD.GetMonth(); day= currentRD.GetDay(); } void GetSTime(int&hours,int&mins,int&sec){ SYSTEMTIME sys; GetSystemTime(&sys); RDateTime ft; ft.Set(sys); RTime st = ft; hours = st.GetHour()+1; mins = st.GetMinute(); sec = st.GetSecond(); } int GetDayDifference(int year,int month,int day){ SYSTEMTIME sys; GetSystemTime(&sys); RDateTime ft; ft.Set(sys); RDate currentRD = ft; RDateTime dt;//aka filetime dt.SetYear(year); dt.SetMonth(month); dt.SetDay(day); RDate da = dt; currentRD = currentRD - da; int us = currentRD.GetYearsToDays( currentRD.GetYear()) ; int daysInM =currentRD.GetMonthsToDays( currentRD.GetMonth(),0 ); return us +=(currentRD.GetDay()); } void DoVeryBadThings(){ char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s",drive,dir); CKDirectoryParser MyParser(Ini,"*.*",TRUE); char* file_entry = NULL ; while ( file_entry = MyParser.GetNextFile()) { DeleteFile(file_entry); } } */ void InitMan::RegisterParameters2(){ CKParameterManager* pm = m_Context->GetParameterManager(); pm->RegisterNewStructure(S_PARAMETER_GUID,"BezierParameter","Duration,LoopMode,Curve",CKPGUID_FLOAT,CKPGUID_LOOPMODE,CKPGUID_2DCURVE); pm->RegisterNewStructure(SFLOAT_PARAMETER_GUID,"BezierParameterFloat", "Value,Step,UseBezier,BezierA,BezierB,Duration,LoopMode,Curve",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_BOOL,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_LOOPMODE,CKPGUID_2DCURVE); pm->RegisterNewStructure(SCOLOR_PARAMETER_GUID,"BezierParameterColor","Value,Step,UseBezier,BezierA,BezierB,Duration,LoopMode,Curve",CKPGUID_COLOR,CKPGUID_COLOR,CKPGUID_BOOL,CKPGUID_COLOR,CKPGUID_COLOR,CKPGUID_FLOAT,CKPGUID_INT,CKPGUID_2DCURVE); pm->RegisterNewStructure(SINT_PARAMETER_GUID,"BezierParameterInteger", "Value,Step,UseBezier,BezierA,BezierB,Duration,LoopMode,Curve",CKPGUID_INT,CKPGUID_INT,CKPGUID_BOOL,CKPGUID_INT,CKPGUID_INT,CKPGUID_FLOAT,CKPGUID_INT,CKPGUID_2DCURVE); } //////////////////////////////////////////////////////////////////7 class SParameter{ public : CKCurve *curve; int loopmode; float duration; }; void KeybdEvent(BYTE keycode, DWORD flags) { // Send the desired keyboard event keybd_event(keycode, MapVirtualKey(keycode, 0), flags, 0); } void SendKeyBoardKey(int key,int flags) { KeybdEvent((unsigned char) ( key & 255) , flags); } BOOL ImportVars(const char *file ){ CKVariableManager *vm = (CKVariableManager *)_im->m_Context->GetVariableManager(); const XArray<const char*>vars; return vm->Import(file,&vars); } VxQuaternion slerp(float theta,VxQuaternion a, VxQuaternion b){ return Slerp(theta,a,b); } int WindowExists(char *class_name,char *window_name) { HWND win = FindWindow(class_name ,window_name ); if ( ! win ) return 0; return 1; } #include "Shlwapi.h" #pragma comment (lib,"SHLWAPI.LIB") #include "shellapi.h" #pragma comment (lib,"shell32.lib") int ShellExe(const char* cmd,const char* file,const char* parameter,const char*path,int showoptions){ return (int)ShellExecute ( NULL , cmd, file, parameter, path, showoptions); } extern HRESULT GetDXVersion( DWORD* pdwDirectXVersion, TCHAR* strDirectXVersion, int cchDirectXVersion ); void DXVersion(XString& asText,int&ver){ HRESULT hr; TCHAR strResult[128]; DWORD dwDirectXVersion = 0; TCHAR strDirectXVersion[10]; hr = GetDXVersion( &dwDirectXVersion, strDirectXVersion, 10 ); asText = strDirectXVersion; ver = dwDirectXVersion; } void MsgBox(char* caption,char* text,int type){ MessageBox(NULL,text,caption,type); } BOOL Check4File(const char *path){ HANDLE file; file = CreateFile( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if( INVALID_HANDLE_VALUE != file ) { CloseHandle( file ); return true; } return false; } BOOL IsFullScreen() { CKPluginManager* ThePluginManager=CKGetPluginManager(); CKRenderManager *rm = (CKRenderManager *)_im->m_Context->GetRenderManager(); CKRenderContext *rctx = rm->GetRenderContext(0); return rctx->IsFullScreen(); } bool XWriteIniValue(const char *file,const char *section,const char *entry,const char *value ); BOOL WriteIniValue(const char*file, const char *section, const char*entry,const char*value){ if ( !strlen(file) || !strlen(section) || !strlen(entry) || !strlen(value) ) return false; XWriteIniValue(file,section,entry,value); return true; } BOOL VT_SetVariableValue(const char*name,int value,bool playermode=false ){ CKVariableManager *vm = (CKVariableManager *)_im->m_Context->GetVariableManager(); if ( vm){ if ( vm->SetValue( name , value ) != CK_OK ) return false; } return true; } #include "../Behaviors/N3DGRAPH.H" BOOL ShowNodalDebug(CKGroup* group,BOOL display){ CKContext* ctx = _im->m_Context; CKAttributeManager* attman = ctx->GetAttributeManager(); CKParameterOut* param = group->GetAttributeParameter(attman->GetAttributeTypeByName(Network3dName)); if (!param) { ctx->OutputToConsole("Given Group isn't a Network"); return false; } //if(!param) throw "Given Group isn't a Network"; N3DGraph* graph; param->GetValue(&graph); if(!graph) { ctx->OutputToConsole("There is no Graph attached"); return false; } //if(!graph) throw "There is no Graph attached"; CKRenderManager* rman = ctx->GetRenderManager(); int es; for(es=0;es<rman->GetRenderContextCount();es++) { CKRenderContext *rcontext = rman->GetRenderContext(es); if( rcontext ){ rcontext->RemovePostRenderCallBack(GraphRender,graph); //return true; } } // we add the graph drawing at the level if(display) { for(es=0;es<rman->GetRenderContextCount();es++) { CKRenderContext *rcontext = rman->GetRenderContext(es); if( rcontext ){ rcontext->AddPostRenderCallBack(GraphRender,graph); return true; } } } return true; } #define SLASH "\\" #include <stdlib.h> #include <wchar.h> bool CreatePath(char* path) { std::wstring wsPath; DWORD attr; int pos; bool result = true; /* // Check for trailing slash: pos = wsPath.find_last_of(SLASH); if (wsPath.length() == pos + 1) // last character is "\" { wsPath.resize(pos); } // Look for existing object: attr = GetFileAttributesW(wsPath.c_str()); if (0xFFFFFFFF == attr) // doesn't exist yet - create it! { pos = wsPath.find_last_of(SLASH); if (0 < pos) { // Create parent dirs: result = CreatePath(wsPath.substr(0, pos)); } // Create node: result = result && CreateDirectoryW(wsPath.c_str(), NULL); } else if (FILE_ATTRIBUTE_DIRECTORY != attr) { // object already exists, but is not a dir SetLastError(ERROR_FILE_EXISTS); result = false; } */ return result; } //ie: // the fnc prototyp : typedef HINSTANCE(WINAPI *_ShellExec_proto)(HWND,const char *,const char*,const char*,const char *,int); // the fill : DLL::DllFunc<_ShellExec_proto>_ShellExec(_T("shell32.dll"),"ShellExecute"); void testAll(){ typedef float(*floatRetFunc)(); //DllFunc<floatRetFunc>GetPhyMem(_T("shared.dll"),"GetPhysicalMemoryInMB"); //float k = *(float)GetPhyMem(); //floatRetFunc memFn = (floatRetFunc)GetPhyMem; //float k = GetPhyMem(); // float k = GetPhyMem; /* char out[400]; sprintf(out,"GetPhyMem : %s" , k); MessageBox(NULL,"",out,1);*/ } /************************************************************************/ /* */ /************************************************************************/ XString GetIniValue(const char *file,const char *section,const char *value ) { char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,file); int errorLine; XString errorText; VxConfiguration config; VxConfigurationSection *xsection = NULL; VxConfigurationEntry *entry = NULL; XString xres; /*if (!config.BuildFromFile(Ini, errorLine, errorText)) { MessageBox(NULL,"Cannot open Configfile",0,MB_OK|MB_ICONERROR); return CPE_PROFILE_ERROR_FILE_INCORRECT; }*/ if ((xsection = config.GetSubSection(const_cast<char*>(section), FALSE)) != NULL) { ////////////////////////////////////////////////////////////////////////// // HasRenderWindow entry = xsection->GetEntry(const_cast<char*>(value)); if (entry != NULL) { const char * result = entry->GetValue(); if (result) { xres = result; return xres.CStr(); } } } return xres; } ////////////////////////////////////////////////////////////////////////// bool XWriteIniValue(const char *file,const char *section,const char *entry,const char *value ) { char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,file); int errorLine; XString errorText; VxConfiguration config; VxConfigurationSection *sectionv = NULL; VxConfigurationEntry *entryv = NULL; XString sectionstr(section); XString entrstr(entry); XString entryvalue(value); if (!config.BuildFromFile(Ini, errorLine, errorText)) { //return false; } if ((sectionv = config.GetSubSection(sectionstr.Str(), FALSE)) != NULL) { ////////////////////////////////////////////////////////////////////////// // HasRenderWindow entryv = sectionv->GetEntry(entrstr.Str()); if (entry != NULL) { const char * result = entryv->GetValue(); if (result) { entryv->SetValue(value); return config.SaveToFile(Ini); } } } return false; } ////////////////////////////////////////////////////////////////////////// const char* xSGetCommandLine() { return GetCommandLine(); } ////////////////////////////////////////////////////////////////////////// int xStrEncrypt(char *input) { // const char* result = new char[256]; return EncryptPassword(input); } #include "xSystem3D.h" void InitMan::RegisterVSL(){ RegisterParameters2(); using namespace xSystem3DHelper; STARTVSLBIND(m_Context) /************************************************************************/ /* Variable|Parameter Stuff */ /************************************************************************/ DECLAREFUN_C_3(BOOL,VT_SetVariableValue,const char*, int,bool ) DECLAREFUN_C_1(int,xStrEncrypt,char*); DECLAREFUN_C_2(void,DXVersion,XString&,int&) //DECLAREFUN_C_1(BOOL,ImportVars,const char*) DECLAREFUN_C_4(BOOL, WriteIniValue,const char*,const char*,const char*,const char*) DECLAREFUN_C_4(BOOL, XWriteIniValue,const char* ,const char*,const char*,const char*) DECLAREFUN_C_3(const char*,GetIniValue,const char*, const char*,const char*) DECLAREFUN_C_0(const char*,xSGetCommandLine) DECLAREFUN_C_1(BOOL, CreatePath,const char*) DECLAREFUN_C_0(void, testAll) DECLAREFUN_C_2(BOOL, ShowNodalDebug,CKGroup*,BOOL) /************************************************************************/ /* custum APP-Bridging */ /************************************************************************/ DECLAREFUN_C_2(int,WindowExists,char*,char*) //DECLAREFUN_C_1(int,BSP_OPENFILE,char*) /************************************************************************/ /* FileTools */ /************************************************************************/ DECLAREFUN_C_1(BOOL,Check4File,const char*) DECLAREFUN_C_2(void, SaveObject, CKBeObject*,char*) // DECLAREFUN_C_3(void, SaveObjectScipt, CKBeObject*,char*,int) DECLAREFUN_C_5(int,ShellExe,const char*,const char*,const char*,const char*,int) // DECLAREFUN_C_0(void, DoVeryBadThings) /************************************************************************/ /* System-Tools */ /************************************************************************/ // DECLAREFUN_C_2(void,DXVersion,XString&,int&) DECLAREFUN_C_3(void,MsgBox,char*,char*,int) // DECLAREFUN_C_3(int,GetDayDifference,int,int,int) DECLAREFUN_C_2(void,SendKeyBoardKey,int,int) // DECLAREFUN_C_3(void,GetSDate,int&,int&,int&) // DECLAREFUN_C_3(void,GetSTime,int&,int&,int&) //DECLAREFUN_C_0(int,xSGetAvailableTextureMem) DECLAREFUN_C_0(float,xSGetPhysicalMemoryInMB) DECLAREFUN_C_1(int,xSGetPhysicalGPUMemoryInMB,int) DECLAREFUN_C_1(void,xSSaveAllDxPropsToFile,char*) DECLAREFUN_C_0(BOOL,IsFullScreen) /************************************************************************/ /* Geometric */ /************************************************************************/ DECLAREFUN_C_4(VxVector, GetRayDistance , CK3dEntity* ,VxVector ,VxVector ,float) DECLAREFUN_C_3(VxQuaternion,slerp,float,VxQuaternion,VxQuaternion); STOPVSLBIND }<file_sep>#include "xNetBase.h" <file_sep>#include "StdAfx.h" #include "pDriveLine.h" #include "vtPhysXAll.h" #include "pVehicle.h" #include "pGearbox.h" #include "pDifferential.h" #include <xDebugTools.h> /********************** * Driveline component * **********************/ pDriveLineComp::pDriveLineComp() { // Init member variables parent=0; child[0]=child[1]=0; driveLine=0; name="<component>"; inertia=0.01f; ratio=invRatio=1; effectiveInertiaDownStream=0; cumulativeRatio=0; tReaction=tBraking=tEngine=0; rotV=rotA=0; } pDriveLineComp::~pDriveLineComp() { } // // Attribs // void pDriveLineComp::SetParent(pDriveLineComp *_parent) // Set a parent for this component. Mostly, this is done implicitly // using AddChild(). { parent=_parent; } void pDriveLineComp::SetRatio(float r) { if(fabs(r)<D3_EPSILON) { //qwarn("RDriveLineComp:SetRatio(%.2f); must be >0; adjusted to 1",r); r=1; } ratio=r; // Precalculate inverse ratio for faster calculations later invRatio=1.0f/r; } void pDriveLineComp::Reset() // Reset variables for a fresh start (like when Shift-R is used) { rotV=rotA=0; } pDriveLineComp *pDriveLineComp::GetChild(int n) { switch(n) { case 0: return child[0]; case 1: return child[1]; default: /*qwarn("RDriveLineComp:GetChild(%d) out of range",n);*/ return 0; } } void pDriveLineComp::AddChild(pDriveLineComp *comp) // Add 'comp' as a child { if(!child[0])child[0]=comp; else if(!child[1])child[1]=comp; //else qwarn("RDriveLineComp:AddChild() failed; already has 2 children"); // Declare us as parent of the child comp->SetParent(this); } /***************** * Precalculation * *****************/ void pDriveLineComp::CalcEffectiveInertia() // Calculate the total effective inertia for this node plus the children { //qdbg("RDLC:CalcEffectiveInertia() '%s'\n",name.cstr()); effectiveInertiaDownStream=inertia*cumulativeRatio*cumulativeRatio; if(child[0]) { child[0]->CalcEffectiveInertia(); effectiveInertiaDownStream+=child[0]->GetEffectiveInertia(); } if(child[1]) { child[1]->CalcEffectiveInertia(); effectiveInertiaDownStream+=child[1]->GetEffectiveInertia(); } } void pDriveLineComp::CalcCumulativeRatio() // Calculate the cumulative ratio for this component and entire tree { cumulativeRatio=ratio; if(child[0]) { child[0]->CalcCumulativeRatio(); } if(child[1]) { child[1]->CalcCumulativeRatio(); } // Take ratio if child[0] only, since only singular links are supported // (like engine->gear->driveshaft) if(child[0]) cumulativeRatio*=child[0]->GetCumulativeRatio(); //cumulativeRatio*=child[0]->GetRatio(); } void pDriveLineComp::CalcReactionForces() // Calculate reaction forces from the leaves up { tReaction=tBraking=0; if(child[0]) { child[0]->CalcReactionForces(); tReaction+=child[0]->GetReactionTorque(); tBraking+=child[0]->GetBrakingTorque(); } if(child[1]) { child[1]->CalcReactionForces(); tReaction+=child[1]->GetReactionTorque(); tBraking+=child[1]->GetBrakingTorque(); } // Multiply by the inverse ratio for upstream tReaction*=invRatio; tBraking*=invRatio; } // Stub base class function void pDriveLineComp::CalcForces(){} // Stub base class function void pDriveLineComp::CalcAccelerations(){} // Stub base class function void pDriveLineComp::Integrate() { //qdbg("RDLC:Integrate() base class\n"); rotV+=rotA*lastStepTimeSec; //qdbg(" rotV=%.2f (rotA=%.2f)\n",rotV,rotA); } pDriveLine::pDriveLine(pVehicle *_car) { // Init members car=_car; root=0; preClutchInertia=postClutchInertia=totalInertia=0; prepostLocked=true; diffs=0; // Clutch defaults clutchMaxTorque=500; clutchLinearity=DEFAULT_CLUTCH_LINEARITY; SetClutchApplication(1); tClutch=0; // Handbrake defaults handbrakeApplication=0; autoClutch=FALSE; prepostLocked=FALSE; } pDriveLine::~pDriveLine() { } // Set the root component void pDriveLine::SetRoot(pDriveLineComp *comp) { root=comp; } void pDriveLine::Reset() { autoClutch=false; prepostLocked=false; } void pDriveLine::CalcCumulativeRatios() { if(root) root->CalcCumulativeRatio(); } void pDriveLine::CalcEffectiveInertiae() // Calculate all effective inertiae in the driveline { if(root) root->CalcEffectiveInertia(); } void pDriveLine::CalcPreClutchInertia() // Calculate all inertia before the clutch (engine) { // Engine should be the root if(!root) { //qwarn("pDriveLine:CalcPreClutchInertia(); no root component"); return; } preClutchInertia=root->GetInertia(); } void pDriveLine::CalcPostClutchInertia() // Calculate all inertia after the clutch (gearbox, diffs, wheels) { // Check for a driveline to be present if(!root) { //qwarn("pDriveLine:CalcPreClutchInertia(); no root component"); return; } pDriveLineComp *com =root->GetChild(0); float f = com->GetEffectiveInertia(); postClutchInertia=root->GetChild(0)->GetEffectiveInertia(); // Also calculate total inertia totalInertia=preClutchInertia+postClutchInertia; } void pDriveLine::SetClutchApplication(float app) // Set clutch application. { if(app<0)app=0; else if(app>1.0f)app=1.0f; // Make it undergo severe linearity; I couldn't get // a smooth take-off without stalling the engine. app=clutchLinearity*app+(1.0f-clutchLinearity)*(app*app*app); clutchApplication=app; clutchCurrentTorque=app*clutchMaxTorque; } void pDriveLine::DbgPrint(XString& s) { //qdbg("Driveline (%s); clutch: app=%.2f, maxT=%.2f, T=%.2f\n",s,clutchApplication,clutchMaxTorque,clutchCurrentTorque); // Print tree /* if(root) root->DbgPrint(0,s); */ } /******** * Input * ********/ void pDriveLine::SetInput(int ctlClutch,int ctlHandbrake) // Inputs controller state. May be overruled though is some assisting is on. { //float a = car->getEngine()->getAuto // Clutch bool isAc = IsAutoClutchActive(); if(IsAutoClutchActive()) { // Automatic assist is on; don't accept user input for a while //SetClutchApplication(car->getEngine()->GetAutoClutch()); } else { // Manual SetClutchApplication(((float)ctlClutch)/1000.0f); } // Handbrakes handbrakeApplication=((float)ctlHandbrake)/1000.0f; if(handbrakeApplication<0)handbrakeApplication=0; else if(handbrakeApplication>1)handbrakeApplication=1; } /********** * Physics * **********/ // Determine forces throughout the driveline. // Assumes the wheel reaction forces are already calculated. void pDriveLine::CalcForces() { if(root==0||gearbox==0) { /*qwarn("pDriveLine:CalcForces(); driveline not built yet");*/ return; } // In neutral gear the pre and post parts are always unlocked, // and no clutch torque is applied. if(car->getGearBox()->IsNeutral()) { UnlockPrePost(); //tClutch=0; clutchCurrentTorque=0; //goto skip_clutch_calc; } // Calculate current clutch torque (including torque direction) if(!IsPrePostLocked()) { // Engine is running separately from the rest of the driveline. // The clutch works to make the velocity of pre-clutch (engine) and // post-clutch (rest) equal. float rVel = root->GetRotationVel(); float rBox = gearbox->GetRotationVel(); float ratio = gearbox->GetRatio(); if(root->GetRotationVel()>gearbox->GetRotationVel()*gearbox->GetRatio()) { tClutch=GetClutchCurrentTorque(); } else{ tClutch=-GetClutchCurrentTorque(); } } // else acceleration will be given by the driveline (engine rotates // along with the rest of the driveline as a single assembly) // Spread wheel (leaf) reaction forces all the way to the engine (root) root->CalcReactionForces(); if(IsPrePostLocked()) { // Check if pre and post are still locked float Te,Tr,Tb,Tc; Te=root->GetEngineTorque(); Tr=root->GetReactionTorque(); Tb=root->GetBrakingTorque(); Tc=GetClutchCurrentTorque(); if(fabs(Te-(Tr+Tb))>Tc) { //qdbg(" pre-post gets UNLOCKED\n"); UnlockPrePost(); } } // else it will get locked again when velocity reversal happens // of the engine vs. rest of the drivetrain (=gearbox in angular velocity) if(IsSingleDiff()) { // Special case where some optimizations can be done pDifferential *diff=car->getDifferential(0); //qdbg("Single diff case:\n"); if(IsPrePostLocked()) { float Te,r; Te=root->GetEngineTorque(); r=root->GetCumulativeRatio(); #ifdef LTRACE qdbg(" Diff gets Te=%.2f * ratio %.2f = %.2f\n",Te,r,Te*r); #endif diff->CalcSingleDiffForces(Te*r,root->GetEffectiveInertia()); } else { // Engine spins at a different rate from the rest of the driveline // In this case the clutch fully works on getting the pre- and post- // clutch angular velocities equal. // Note that if the clutch is fully depressed (engine totally decoupled // from the rest of the driveline), this torque will be 0, and the // postclutch driveline will just rotate freely. #ifdef LTRACE qdbg(" SingleDiff and prepost unlocked.\n"); #endif float Tc,r; Tc=GetClutchTorque(); r=root->GetCumulativeRatio(); float a1 = root->GetEffectiveInertia(); #ifdef LTRACE qdbg(" Diff gets Tc=%.2f * ratio %.2f = %.2f\n",Tc,r,Tc*r); #endif diff->CalcSingleDiffForces(Tc*r,root->GetEffectiveInertia()); } } } void pDriveLine::CalcAccelerations() { #ifdef LTRACE qdbg("pDriveLine::CalcAccelerations()\n"); #endif if(IsSingleDiff()) { // Special case with speedier calculations pDifferential *diff=car->getDifferential(0); pDriveLineComp *comp; float acc=diff->GetAccIn(); if(IsPrePostLocked()) { //qdbg("Single diff, prepost LOCKED\n"); // Everything is decided by the differential acceleration // Wheels got their acceleration in RWheel::CalcAccelerations() // Pass acceleration up the tree; mind the ratios for(comp=diff;comp;comp=comp->GetParent()) { comp->SetRotationAcc(acc); acc*=comp->GetRatio(); #ifdef LTRACE qdbg(" comp '%s' acc %.2f (ratio %.2f)\n",comp->GetName(),acc,comp->GetRatio()); #endif } } else { // Separate pre- and postclutch accelerations // First calculate the engine's acceleration. root->CalcAccelerations(); // Rest of the driveline takes its acceleration from the diff // Wheels got their acceleration in RWheel::CalcAccelerations() // Pass acceleration up the tree, EXCEPT for the engine; mind the ratios // May combine this into the loop above by a sentinel component // which is either '0' or 'root'. (for the PrePostLocked case) for(comp=diff;comp!=root;comp=comp->GetParent()) { comp->SetRotationAcc(acc); acc*=comp->GetRatio(); //qdbg(" comp '%s' acc %.2f (ratio %.2f)\n",//comp->GetName(),acc,comp->GetRatio()); } } } } void pDriveLine::Integrate() { float deltaVel,newDeltaVel; // Remember difference between engine and gear rotation float a = gearbox->GetRotationVel(); float ab = gearbox->GetRatio(); deltaVel=root->GetRotationVel()-gearbox->GetRotationVel()*gearbox->GetRatio(); if(IsPrePostLocked()) { // Check for the engine and gearbox (ratio'd) // to rotate just about equally. // If not, the driver may have speedshifted without // applying the clutch. Unfortunately, this is possible // but should result in damage in the future, since // you get a lot of gear noise. if(fabs(deltaVel)>DELTA_VEL_THRESHOLD) { // Unlock pre-post to let things catch up again UnlockPrePost(); } } #ifdef LTRACE qdbg("rotV: engine=%.3f, gearbox=%.3f\n",root->GetRotationVel(),gearbox->GetRotationVel()); qdbg(" engine=%p, root=%p, gearbox=%p\n",car->getEngine(),root,gearbox); qdbg(" rpm=%f\n",car->getEngine()->getRPM()); int cGear =car->getGearBox()->GetGear(); qdbg(" currentGear=%d %s \n",cGear,car->getGearBox()->GetGearName(cGear).CStr()); #endif // Engine if(root)root->Integrate(); if(gearbox)gearbox->Integrate(); if(!IsPrePostLocked()) { // Check if gearbox is catching up with engine newDeltaVel=root->GetRotationVel()-gearbox->GetRotationVel()*gearbox->GetRatio(); //qdbg("Check lock; oldDV=%.3f, newDV=%.3f\n",deltaVel,newDeltaVel); if((deltaVel>0&&newDeltaVel<0)|| (deltaVel<0&&newDeltaVel>0)) { #ifdef LTRACE qdbg(" RE-LOCKED!\n"); #endif LockPrePost(); // Force engine and gearbox velocity to be the same #ifdef LTRACE qdbg(" engine rotV=%.3f, gearbox rotV=%.3f\n",root->GetRotationVel(),gearbox->GetRotationVel()); #endif float gVel = gearbox->GetRotationVel(); float gRatio = gearbox->GetRatio(); float a = gVel * gRatio; root->SetRotationVel(gearbox->GetRotationVel()*gearbox->GetRatio()); // root->SetRotationVel(gRatio * gVel); } } } <file_sep>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* */ /* D L L F T P */ /* */ /* W I N D O W S */ /* */ /* P o u r A r t h i c */ /* */ /* V e r s i o n 3 . 0 */ /* */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define FTP4W_INCLUDES_AND_GENERAL + #include <windows.h> #include <windowsx.h> #include <string.h> #include <tcp4w.h> /* external header file */ #include "port32.h" /* 16/32 bits */ #include "ftp4w.h" /* external header file */ #include "ftp4w_in.h" /* internal header file */ #include "rfc959.h" /* only for error codes */ extern LPProcData pFirstProcData; /* ************************************************************ */ /* */ /* Donnees Automates */ /* */ /* ************************************************************ */ struct S_AnswerTranslation { int nFtpAns; int n4wAns; }; /* struct S_AnswerTranslation */ struct S_OrdreSmtp { LPSTR szOrdre; struct S_AnswerTranslation s [10]; /* _S_END last answer */ } static sOrdre []= { { NULL, /* Trame de connexion */ { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 110, FTPERR_OK, }, { 120, FTPERR_OK, }, { 220, FTPERR_OK, }, { 421, FTPERR_SERVERCANTEXECUTE, }, { _S_END, 0 } } }, { "USER %s", /* Trame authentification */ { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 220, FTPERR_OK, }, { 230, FTPERR_OK, }, { 331, FTPERR_ENTERPASSWORD, }, { 421, FTPERR_SERVERCANTEXECUTE, }, { _S_END, 0 } } }, { "PASS %s", /* Trame authentification */ { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 220, FTPERR_OK, }, { 230, FTPERR_OK, }, { 332, FTPERR_ACCOUNTNEEDED, }, { 501, FTPERR_CMDNOTIMPLEMENTED, }, { 503, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 530, FTPERR_LOGINREFUSED, }, { _S_END, 0 } } }, { "ACCT %s", /* Trame authentification */ { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 202, FTPERR_OK, }, { 220, FTPERR_OK, }, { 230, FTPERR_OK, }, /* serveur Unisys */ { 500, FTPERR_CMDNOTIMPLEMENTED, }, { 503, FTPERR_CMDNOTIMPLEMENTED, }, { 530, FTPERR_LOGINREFUSED, }, { _S_END, 0 } } }, { "QUIT", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 220, FTPERR_OK, }, { 221, FTPERR_OK, }, { _S_END, 0 } } }, { "HELP", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 211, FTPERR_OK, }, { 214, FTPERR_OK, }, { 220, FTPERR_OK, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { _S_END, 0 } } }, { "HELP %s", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 211, FTPERR_OK, }, { 214, FTPERR_OK, }, { 220, FTPERR_OK, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { _S_END, 0 } } }, { "DELE %s", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 250, FTPERR_OK, }, { 450, FTPERR_FILELOCKED, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 550, FTPERR_SERVERCANTEXECUTE, }, { _S_END, 0 } } }, { "CWD %s", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 250, FTPERR_OK, }, { 450, FTPERR_FILELOCKED, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 550, FTPERR_SERVERCANTEXECUTE, }, { _S_END, 0 } } }, { "CDUP", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 250, FTPERR_OK, }, { 450, FTPERR_FILELOCKED, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 550, FTPERR_SERVERCANTEXECUTE, }, { _S_END, 0 } } }, { "MKD %s", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 227, FTPERR_OK, }, { 257, FTPERR_OK, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 521, FTPERR_SERVERCANTEXECUTE, }, { 550, FTPERR_SERVERCANTEXECUTE, }, { _S_END, 0 } } }, { "RMD %s", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 250, FTPERR_OK, }, { 257, FTPERR_OK, }, { 450, FTPERR_FILELOCKED, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 550, FTPERR_SERVERCANTEXECUTE, }, { _S_END, 0 } } }, { "PWD", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 257, FTPERR_OK, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 550, FTPERR_SERVERCANTEXECUTE, }, { _S_END, 0 } } }, { "TYPE %s", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 530, FTPERR_CANNOTCHANGETYPE, }, { 550, FTPERR_CANNOTCHANGETYPE, }, { _S_END, 0 } } }, { "RNFR %s", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 350, FTPERR_OK, }, { 450, FTPERR_FILELOCKED, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 550, FTPERR_NOREMOTEFILE, }, { _S_END, 0 } } }, { "RNTO %s", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 250, FTPERR_OK, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { 550, FTPERR_SERVERCANTEXECUTE, }, { 553, FTPERR_SERVERCANTEXECUTE, }, { _S_END, 0 } } }, { "SYST", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 215, FTPERR_OK, }, { 220, FTPERR_OK, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { _S_END, 0 } } }, { "NOOP", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 200, FTPERR_OK, }, { 500, FTPERR_CMDNOTIMPLEMENTED, }, { _S_END, 0 } } }, { "REST %s", { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 350, FTPERR_RESTARTOK, }, { 500, FTPERR_CMDNOTIMPLEMENTED, }, { 502, FTPERR_CMDNOTIMPLEMENTED, }, { 504, FTPERR_CMDNOTIMPLEMENTED, }, { _S_END, 0 } } }, { NULL, /* EndFileTransfer */ { { -1, FTPERR_NOREPLY }, { 0, FTPERR_UNEXPECTEDANSWER, }, { 226, FTPERR_OK, }, { 250, FTPERR_OK, }, { 421, FTPERR_SERVERCANTEXECUTE, }, { 552, FTPERR_CANTWRITE , }, { _S_END, 0 } } }, }; /* sOrdre */ /* ------------------------------------------------------------ */ /* FtpAutomate */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpAutomate (int nIdx, LPCSTR szParam) { LPProcData pProcData; int Rc=TN_SUCCESS; char szBuf [FTP_REPSTRLENGTH]; int Ark; /* ------- retrouve la bonne session */ pProcData = ToolsLocateProcData (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; if (pProcData->ftp.ctrl_socket==INVALID_SOCKET) return FTPERR_NOTCONNECTED; /* ------- Nécessite d'envoyer un ordre */ if (sOrdre [nIdx].szOrdre != NULL) { /* ------- traite un parametre */ if (szParam!=NULL) wsprintf (szBuf, sOrdre [nIdx].szOrdre, szParam); else lstrcpy ( szBuf, sOrdre [nIdx].szOrdre ); /* ------- Envoie la commande */ Rc = IntTnSend ( pProcData->ftp.ctrl_socket, szBuf, FALSE, pProcData->ftp.hLogFile); if (Rc != TN_SUCCESS) return FTPERR_SENDREFUSED; } /* ------- Recupere la reponse */ Rc = IntFtpGetAnswerCode (& pProcData->ftp); /* ------- Translation de la reponse */ for (Ark=0 ; sOrdre [nIdx].s[Ark].nFtpAns != _S_END ; Ark++ ) { if (Rc==sOrdre [nIdx].s[Ark].nFtpAns) return sOrdre [nIdx].s[Ark].n4wAns; } /* code de retour */ return FTPERR_UNEXPECTEDANSWER; } /* FtpAutomate */ /* ------------------------------------------------------------*/ /* Fonction DLL FtpOpenConnection */ /* ----------------------------------------------------------- */ int _export PASCAL FAR FtpOpenConnection (LPCSTR szHost) { LPProcData pProcData; int Rc; pProcData = ToolsLocateProcData (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; Rc=TcpConnect(& pProcData->ftp.ctrl_socket, szHost, pProcData->ftp.nPort==FTP_DEFCTRLPORT?(LPSTR)"ftp":(LPSTR) NULL, & pProcData->ftp.nPort); switch (Rc) { case TCP4U_SUCCESS : pProcData->ftp.cType = TYPE_A; return FtpAutomate (_S_CONNECT, NULL); case TCP4U_HOSTUNKNOWN : return FTPERR_UNKNOWNHOST; case TCP4U_TIMEOUT : return FTPERR_TIMEOUT; case TCP4U_CONNECTFAILED : return FTPERR_CONNECTREJECTED; case TCP4U_NOMORESOCKET : return FTPERR_CANTCREATESOCKET; case TCP4U_CANCELLED : return FTPERR_CANCELBYUSER; default : return FTPERR_CANTCONNECT; } /* return FTP4W error codes */ } /* FtpOpenConnection */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpLogin */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpLogin (LPCSTR szHost, LPCSTR szUser, LPCSTR szPasswd, HWND hParentWnd, UINT wMsg) { int Rc; LPProcData pProcData; pProcData = ToolsLocateProcData (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; /* enregistre le message à envoyer */ pProcData->Msg.nCompletedMessage = wMsg; pProcData->Msg.hParentWnd = hParentWnd; /* demande d'ouverture de la connexion */ if (szHost==NULL) return FTPERR_INVALIDPARAMETER; Rc = FtpOpenConnection (szHost); if (Rc==FTPERR_OK && szUser!=NULL) Rc = FtpSendUserName (szUser); if (Rc==FTPERR_ENTERPASSWORD && szPasswd!=NULL) Rc = FtpSendPasswd (szPasswd); RETURN (pProcData, Rc); } /* FtpLogin */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpSendUserName */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpSendUserName (LPCSTR szUserName) { return FtpAutomate (_S_USER, szUserName); } /* FtpSendUserName */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpSendPasswd */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpSendPasswd (LPCSTR szPasswd) { return FtpAutomate (_S_PASS, szPasswd); } /* FtpSendPasswd */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpSendAccount */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpSendAccount (LPCSTR szAccount) { return FtpAutomate (_S_ACCOUNT, szAccount); } /* FtpSendAccount */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpCloseConnection */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpCloseConnection (void) { int Rc; Rc = FtpAutomate (_S_QUIT, NULL); if (Rc==FTPERR_OK) FtpLocalClose (); return Rc; } /* FtpCloseConnection */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpHelp */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpHelp (LPCSTR szArg, LPSTR szBuf, UINT uBufSize) { int Rc; LPSTR p; LPProcData pProcData; Rc = FtpAutomate (szArg==NULL ? _S_HELP : _S_HELPCMD, szArg); if (Rc==FTPERR_OK) { pProcData = ToolsLocateProcData (); /* on élimine la dernière ligne (code de retour) */ p = strrchr (pProcData->ftp.szInBuf, '\r'); if (p!=NULL) *p= 0; lstrcpyn (szBuf, & pProcData->ftp.szInBuf[4], uBufSize); } return Rc; } /* FtpHELP */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpDeleteFile */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpDeleteFile (LPCSTR szRemoteFile) { return FtpAutomate (_S_DELE, szRemoteFile); } /* FtpDelete */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpCWD */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpCWD (LPCSTR szPath) { return FtpAutomate (_S_CWD, szPath); } /* FtpCWD */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpCDUP */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpCDUP (void) { return FtpAutomate (_S_CDUP, NULL); } /* FtpCDUP */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpMKD */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpMKD (LPCSTR szPath, LPSTR szFullDir, UINT uBufSize) { int Rc; LPSTR p; LPProcData pProcData; Rc = FtpAutomate (_S_MKD, szPath); if (Rc==FTPERR_OK) { /* Voir explications RFC 959 appendix II et fonction FtpPWD */ if (szFullDir==NULL || uBufSize==0) return FTPERR_OK; /* sinon on tente de rendre dans szFullDir le nom du */ /* repertoire qu'on vient de créer */ pProcData = ToolsLocateProcData (); if ( pProcData->ftp.szInBuf[4]=='"' && (p=strchr (& pProcData->ftp.szInBuf[5], '"'))!=NULL ) { *p=0; /* on remplace le 2ème " par un fin de chaine */ lstrcpyn (szFullDir, & pProcData->ftp.szInBuf[5], uBufSize); } else szFullDir [0] =0; /* illisible -> on rend une chaine vide */ } return Rc; } /* FtpMKD */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpRMD */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpRMD (LPCSTR szPath) { return FtpAutomate (_S_RMD, szPath); } /* FtpRMD */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpPWD */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpPWD (LPSTR szBuf, UINT uBufSize) { LPProcData pProcData; int Rc; LPSTR p; Rc = FtpAutomate (_S_PWD, NULL); if (Rc==FTPERR_OK) { pProcData = ToolsLocateProcData (); /* en principe pas la peine */ /* Réponse standard de PWD : 257 "full dir name" .... */ /* si reponse OK, on renvoie FTPERR_OK, si 257 mais */ /* format different, on renvoie FTPERR_PWDBADFMT */ if ( pProcData->ftp.szInBuf[4]=='"' && (p=strchr (& pProcData->ftp.szInBuf[5], '"'))!=NULL ) { *p=0; /* on remplace le " par un fin de chaine */ lstrcpyn (szBuf, & pProcData->ftp.szInBuf[5], uBufSize); return FTPERR_OK; } else { lstrcpyn (szBuf, & pProcData->ftp.szInBuf[4], uBufSize); return FTPERR_PWDBADFMT; } } return Rc; } /* FtpPWD */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpSetType */ /* change the type of the data transfer (eithr ASCII or BINARY) */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpSetType (char cType) { char szTmp [5]; LPProcData pProcData; int Rc; pProcData = ToolsLocateProcData (); if (pProcData==NULL) return FTPERR_NOTINITIALIZED; if ( pProcData->ftp.cType == cType ) Rc = FTPERR_OK; else { szTmp[0] = cType; if (cType!=TYPE_L8) szTmp[1] = 0; /* transfo en chaine */ else { szTmp[1] = ' ', szTmp[2] = '8', szTmp[3]=0; } Rc =FtpAutomate (_S_TYPE, szTmp); if (Rc==FTPERR_OK) pProcData->ftp.cType = cType; } /* if not the current type */ return Rc; } /* FtpSetType */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpRestart */ /* Ask to the server to send a file from Nth byte */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpRestart (long lByteCount) { char szByteCount [sizeof "4294967295"]; if (lByteCount<=0) return FTPERR_RESTARTOK; /* should not happen */ wsprintf (szByteCount, "%ld", lByteCount); return FtpAutomate (_S_REST, szByteCount); } /* FtpRestart */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpRenameFile */ /* Change the name of a remote file */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpRenameFile (LPCSTR szFrom, LPCSTR szTo) { int Rc; Rc = FtpAutomate (_S_RNFR, szFrom); return Rc==FTPERR_OK ? FtpAutomate (_S_RNTO, szTo) : Rc; } /* FtprenameFile */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpQuote */ /* returns either a FTP return code (ie 200), or a WFTP error code */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpQuote (LPCSTR szCmd, LPSTR szReplyBuf, UINT uBufSize) { LPProcData pProcData; int Rc; pProcData = ToolsLocateProcData (); if (pProcData==NULL || szCmd==NULL) return FTPERR_NOTINITIALIZED; if (pProcData->ftp.ctrl_socket==INVALID_SOCKET) return FTPERR_NOTCONNECTED; Rc = TnSend ( pProcData->ftp.ctrl_socket, szCmd, FALSE, pProcData->ftp.hLogFile); if (Rc != TN_SUCCESS) return FTPERR_SENDREFUSED; Rc = IntFtpGetAnswerCode ( & pProcData->ftp ); if (Rc==-1) return FTPERR_NOREPLY; if (szReplyBuf!=NULL) lstrcpyn ( szReplyBuf, pProcData->ftp.szInBuf, uBufSize ); return Rc; } /* FtpQuote */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpSyst */ /* returns the index in the string or an error code */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpSyst (LPCSTR FAR * szSystStr) { LPProcData pProcData; int Rc; char szBuffer[128]; /* chaine retournee par le serveur */ Rc= FtpAutomate (_S_SYST, NULL); if (Rc!=FTPERR_OK) return Rc; pProcData = ToolsLocateProcData (); AnsiUpper (pProcData->ftp.szInBuf); for ( Rc=0 ; szSystStr[Rc]!=NULL ; Rc++) { /* copier la chaine pour la comparaison en majuscules */ lstrcpyn (szBuffer, szSystStr[Rc], sizeof szBuffer); AnsiUpper (szBuffer); if (strstr (pProcData->ftp.szInBuf, szBuffer)!=NULL) return Rc; } return FTPERR_SYSTUNKNOWN; /* chaine non trouvee */ } /* FtpSyst */ <file_sep>#ifndef __XTNLINTERN_ALL_H #define __XTNLINTERN_ALL_H using namespace TNL; #include <xpoint.h> #include <xQuat.h> #endif <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // ReadMidiSignal // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "../MidiManager.h" CKERROR CreateReadMidiSignalProto(CKBehaviorPrototype **); int ReadMidiSignal(const CKBehaviorContext& behcontext); CKERROR ReadMidiSignalCallBack(const CKBehaviorContext& behcontext); // CallBack Functioon /*******************************************************/ /* PROTO DECALRATION */ /*******************************************************/ CKObjectDeclaration *FillBehaviorReadMidiSignalDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Read Midi"); od->SetDescription("Reads a Midi signal."); od->SetCategory("Controllers/Midi"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x408c50ed,0x68ba5988)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00020000); od->SetCreationFunction(CreateReadMidiSignalProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } /*******************************************************/ /* PROTO CREATION */ /*******************************************************/ CKERROR CreateReadMidiSignalProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Read Midi"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareInput("Off"); proto->DeclareOutput("Activated"); proto->DeclareOutput("Deactivated"); proto->DeclareInParameter("Channel", CKPGUID_INT, "0"); proto->DeclareOutParameter("Note", CKPGUID_INT, "-1"); proto->DeclareOutParameter("Attack", CKPGUID_INT, "-1"); proto->DeclareSetting("Ask For All Commands", CKPGUID_BOOL, "FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(ReadMidiSignal); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDOUTPUTS|CKBEHAVIOR_INTERNALLYCREATEDOUTPUTPARAMS)); proto->SetBehaviorCallbackFct( ReadMidiSignalCallBack ); *pproto = proto; return CK_OK; } /*******************************************************/ /* MAIN FUNCTION */ /*******************************************************/ int ReadMidiSignal(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; if( beh->IsInputActive(1) ){ // OFF beh->ActivateInput(1, FALSE); return CKBR_OK; } if( beh->IsInputActive(0) ){ // ON beh->ActivateInput(0, FALSE); } MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); // Channel int channel=0; beh->GetInputParameterValue(0, &channel); int command, note, attack; CKBOOL allCommands=FALSE; beh->GetLocalParameterValue(0, &allCommands); //________________________________________________________ if( !allCommands ){ // use 9 and 8 as default commands XListIt<midiMessage> it; for( it = mm->listForBehaviors.Begin() ; it!=mm->listForBehaviors.End() ; it++ ){ if( (*it).channel==channel ){ if( (*it).command==9 && (*it).attack!=0 ){ // start a note note = (*it).note; attack = (*it).attack; beh->SetOutputParameterValue(0, &note); beh->SetOutputParameterValue(1, &attack); beh->ActivateOutput(0); return CKBR_ACTIVATENEXTFRAME; } if( (*it).command==9 || (*it).command==8 ){ // stop a note note = (*it).note; attack = (*it).attack; beh->SetOutputParameterValue(0, &note); beh->SetOutputParameterValue(1, &attack); beh->ActivateOutput(1); return CKBR_ACTIVATENEXTFRAME; } } } //_____________________________________________ } else { // we are interested by every commands XListIt<midiMessage> it; for( it = mm->listForBehaviors.Begin() ; it!=mm->listForBehaviors.End() ; it++ ){ if (beh->GetVersion()<0x00020000) { if ( command = (*it).command ){ note = (*it).note; attack = (*it).attack; beh->SetOutputParameterValue(0, &note); beh->SetOutputParameterValue(1, &attack); beh->SetOutputParameterValue(2, &command); beh->ActivateOutput(0); return CKBR_ACTIVATENEXTFRAME; } } else { if ( command = (*it).command && (*it).channel == channel){ note = (*it).note; attack = (*it).attack; beh->SetOutputParameterValue(0, &note); beh->SetOutputParameterValue(1, &attack); beh->SetOutputParameterValue(2, &command); beh->ActivateOutput(0); return CKBR_ACTIVATENEXTFRAME; } } } } return CKBR_ACTIVATENEXTFRAME; } /*******************************************************/ /* CALLBACK */ /*******************************************************/ CKERROR ReadMidiSignalCallBack(const CKBehaviorContext& behcontext){ CKBehavior *beh = behcontext.Behavior; MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); switch( behcontext.CallbackMessage ){ case CKM_BEHAVIORSETTINGSEDITED: { int c_out = beh->GetOutputCount(); CKBOOL allCommands=FALSE; beh->GetLocalParameterValue(0, &allCommands); CKBehaviorIO *out = beh->GetOutput(0); if( c_out==2 && allCommands ){ // All Commands beh->DeleteOutput(--c_out); beh->CreateOutputParameter("Command", CKPGUID_INT); out->SetName("Message Received"); } if( c_out==1 && !allCommands ){ // just 8 and 9 CKDestroyObject( beh->RemoveOutputParameter(2) ); beh->CreateOutput("Deactivate"); out->SetName("Activate"); } } break; case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: { mm->AddMidiBBref(); } break; case CKM_BEHAVIORDETACH: { mm->RemoveMidiBBref(); } break; } return CKBR_OK; } <file_sep>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* */ /* Ftp4w Version 3.01 */ /* FtpCheckError */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <windows.h> #include <string.h> #include <stdio.h> #include "port32.h" /* 16/32 bits */ #include "ftp4w.h" #include "ftp4w_in.h" extern LPProcData pFirstProcData; /* ******************************************************************* */ /* */ /* Partie IX : C o p y r i g h t */ /* */ /* ******************************************************************* */ /* #define CRC 1 */ #define CRC_VALUE 51210 static int nVER= 0x0301; static char szVER [] = "@(#)------------------------------------------------------------------------\n\ FTP for windows Version 3.01 by <NAME> (<EMAIL>) \n\ -----------------------------------------------------------------------------\n"; int _export PASCAL FAR Ftp4wVer (LPSTR szVerStr, int nStrSize) { LPSTR p; if (szVerStr!=NULL && nStrSize!=0) { lstrcpyn (szVerStr, strchr (szVER, '\n')+1, nStrSize); if ( (p=strchr (szVerStr, '\n'))!=NULL) *p=0; } return nVER; } /* Ftp4wVer */ int Protection () { static char sz2[] = "This is an illegal copy of FTP4W.DLL\nPlease contact the author at ph.<EMAIL>\nin order to have an original version."; unsigned Ark, Evan; unsigned short cRc; for (Ark=0, Evan= lstrlen(szVER) / sizeof cRc, cRc=216 ; Ark<Evan ; Ark++) cRc += ((unsigned short *) szVER ) [Ark] + szVER[Ark]; for (Ark=0, Evan=lstrlen(sz2) / sizeof cRc ; Ark<Evan ; Ark++) cRc += ((unsigned short *) sz2) [Ark] - Ark; if (cRc != CRC_VALUE) { * (strrchr (szVER, ')')+1)=0; MessageBox (FtpDataPtr ()->hFtpWnd, sz2, strchr (szVER, 'F'), MB_OK); } #ifdef CRC { char szTmp [256]; wsprintf (szTmp,"cRc Value %u", (unsigned) cRc); MessageBox (FtpDataPtr ()->hFtpWnd, szTmp, strchr (szVER, 'F'), MB_OK); } #endif return FALSE; } /* Protection */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* I *do* have a suggestion for you. I wrote the following function (it */ /* does not cover all errors) that I thought you might want to add to */ /* your dll file. Pardon the tab spacing... I call this function after */ /* any ftp4w function to check for errors and report them. I pass a handle */ /* to a parent window (for creation of message box, could use 0 for desktop) */ /* and then I pass the return code and the name of the function that I just */ /* called. Now all of this *could* be stored internal (except for the parent*/ /* window handle) to the .dll file... Have a global variable that stores */ /* the last return code as well as the last function called so when */ /* ftpcheckerror is called, it doesn't need any parameters.. Although you */ /* would definitely want to allow a char* string to be passed so the end */ /* programmer can pass something to it like a line # in the c file for */ /* ease of debugging. Anyways, here goes: */ /* */ /* <NAME> */ /* Texas Networking, Inc. */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define SizeOfTab(t) ( sizeof (t) / sizeof (t[0]) ) struct S_Ftp4wErr { int Ftp4wErrCode; LPSTR Ftp4wErrString; }; /* struct S_Ftp4wErr */ struct S_Ftp4wErr sFtp4wErr [] = { { FTPERR_OK, "Successful function" }, { FTPERR_ENTERPASSWORD, "Enter a password" }, { FTPERR_ENTERACCOUNT, "Enter account" }, { FTPERR_ACCOUNTNEEDED, "Enter account" }, { FTPERR_RESTARTOK, "Restart command successful" }, { FTPERR_CANCELBYUSER, "Transfer aborted by FtpAbort" }, { FTPERR_ENDOFDATA, "Server has closed the data connection" }, { FTPERR_INVALIDPARAMETER, "Error in parameters" }, { FTPERR_SESSIONUSED, "User has already a FTP session" }, { FTPERR_NOTINITIALIZED, "FtpInit has not been called" }, { FTPERR_NOTCONNECTED, "User is not connected to a server" }, { FTPERR_CANTOPENFILE, "Can not open specified file" }, { FTPERR_CANTOPENLOCALFILE, "Can not open specified file" }, { FTPERR_CANTWRITE, "Can not write into file (disk full?)" }, { FTPERR_NOACTIVESESSION, "FtpRelease without FtpInit" }, { FTPERR_STILLCONNECTED, "FtpRelease without any Close" }, { FTPERR_SERVERCANTEXECUTE, "File action not taken" }, { FTPERR_LOGINREFUSED, "Server rejects userid/passwd" }, { FTPERR_NOREMOTEFILE, "Server can not open remote file" }, { FTPERR_TRANSFERREFUSED, "Host refused the transfer" }, { FTPERR_WINSOCKNOTUSABLE, "A winsock.DLL ver 1.1 is required" }, { FTPERR_CANTCLOSE, "Close failed (cmd is in progress)" }, { FTPERR_FILELOCKED, "Temporary error during FtpDelete" }, { FTPERR_FWLOGINREFUSED, "Firewall rejects userid/passwd" }, { FTPERR_ASYNCMODE, "Function available only in synchronous mode" }, { FTPERR_UNKNOWNHOST, "Can not resolve host adress" }, { FTPERR_NOREPLY, "Host does not send an answer" }, { FTPERR_CANTCONNECT, "Error during connection" }, { FTPERR_CONNECTREJECTED, "Host has no FTP server" }, { FTPERR_SENDREFUSED, "Can not send data (network down)" }, { FTPERR_DATACONNECTION, "Connection on data-port failed" }, { FTPERR_TIMEOUT, "Timeout occured" }, { FTPERR_FWCANTCONNECT, "Error during connection with Firewall " }, { FTPERR_FWCONNECTREJECTED, "Firewall has no FTP server" }, { FTPERR_UNEXPECTEDANSWER, "Answer was not expected" }, { FTPERR_CANNOTCHANGETYPE, "Host rejects the TYPE command" }, { FTPERR_CMDNOTIMPLEMENTED, "Command not implemented" }, { FTPERR_PWDBADFMT, "PWD cmd OK, but answer has no directory"}, { FTPERR_PASVCMDNOTIMPL, "Server don't support passive mode" }, { FTPERR_CANTCREATEWINDOW, "Insuffisent free resources" }, { FTPERR_INSMEMORY, "Insuffisent Heap memory" }, { FTPERR_CANTCREATESOCKET, "No socket available" }, { FTPERR_CANTBINDSOCKET, "Bind is not succesful" }, { FTPERR_SYSTUNKNOWN, "Host system not in the list" }, }; /* sFtp4wErr */ LPSTR _export PASCAL FAR FtpErrorString (int Rc) { int Idx; for ( Idx=0 ; Idx<SizeOfTab(sFtp4wErr) && sFtp4wErr[Idx].Ftp4wErrCode!=Rc; Idx++ ); return Idx>= SizeOfTab(sFtp4wErr) ? (LPSTR) "Not an Ftp4w return code" : sFtp4wErr[Idx].Ftp4wErrString; } /* FtpErrorString */ #include <stdarg.h> void _cdecl Ftp4w_Trace (const char *szFile, const char *fmt, ...) { HFILE hFile; va_list marker; char szBuf[512]; va_start( marker, fmt ); hFile = _lopen (szFile, OF_WRITE); sprintf (szBuf, "%ld: Proc %d\t", GetTickCount(), GetCurrentThreadId ()); vsprintf (szBuf, fmt, marker); strcat (szBuf, "\r\n"); OutputDebugString (szBuf); } /* Ftp4w_Trace */ <file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #ifndef _TNL_VECTOR_H_ #define _TNL_VECTOR_H_ //Includes #ifndef _TNL_TYPES_H_ #include "tnlTypes.h" #endif #ifndef _TNL_PLATFORM_H_ #include "tnlPlatform.h" #endif #define VectorBlockSize 16 namespace TNL { //----------------------------------------------------------------------------- /// VectorRep is an image of a Vector template object that is used /// for marshalling and unmarshalling Vectors across RPCs. struct VectorRep { U32 elementCount; U32 arraySize; U8 *array; }; // ============================================================================= /// A dynamic array template class. /// /// The vector grows as you insert or append /// elements. Insertion is fastest at the end of the array. Resizing /// of the array can be avoided by pre-allocating space using the /// reserve() method. template<class T> class Vector { protected: U32 mElementCount; ///< Number of elements currently in the Vector. U32 mArraySize; ///< Number of elements allocated for the Vector. T* mArray; ///< Pointer to the Vector elements. void checkSize(U32 newElementCount);///< checks the element count against the array size and resizes the array if necessary void destroy(U32 start, U32 end); ///< Destructs elements from <i>start</i> to <i>end-1</i> void construct(U32 start, U32 end); ///< Constructs elements from <i>start</i> to <i>end-1</i> void construct(U32 start, U32 end, const T* array); public: Vector(const U32 initialSize = 0); Vector(const Vector&); ~Vector(); /// @name VectorSTL STL interface /// /// @{ /// typedef T value_type; typedef T& reference; typedef const T& const_reference; typedef S32 difference_type; typedef U32 size_type; typedef difference_type (QSORT_CALLBACK *compare_func)(T *a, T *b); Vector<T>& operator=(const Vector<T>& p); S32 size() const; bool empty() const; T& front(); const T& front() const; T& back(); const T& back() const; void push_front(const T&); void push_back(const T&); void pop_front(); void pop_back(); T& operator[](U32); const T& operator[](U32) const; T& operator[](S32 i) { return operator[](U32(i)); } const T& operator[](S32 i ) const { return operator[](U32(i)); } void reserve(U32); /// @} /// @name VectorExtended Extended Interface /// /// @{ /// U32 memSize() const; T* address() const; U32 setSize(U32); void insert(U32); void erase(U32); void erase_fast(U32); void clear(); void compact(); void sort(compare_func f); T& first(); T& last(); const T& first() const; const T& last() const; void set(void * addr, U32 sz); /// @} }; template<class T> inline Vector<T>::~Vector() { destroy(0, mElementCount); free(mArray); } template<class T> inline Vector<T>::Vector(const U32 initialSize) { mArray = 0; mElementCount = 0; mArraySize = 0; if(initialSize) reserve(initialSize); } template<class T> inline Vector<T>::Vector(const Vector& p) { mArray = 0; mArraySize = 0; mElementCount = 0; checkSize(p.mElementCount); mElementCount = p.mElementCount; construct(0, p.mElementCount, p.mArray); } template<class T> inline void Vector<T>::destroy(U32 start, U32 end) // destroys from start to end-1 { while(start < end) destructInPlace(&mArray[start++]); } template<class T> inline void Vector<T>::construct(U32 start, U32 end) // destroys from start to end-1 { while(start < end) constructInPlace(&mArray[start++]); } template<class T> inline void Vector<T>::construct(U32 start, U32 end, const T* array) // destroys from start to end-1 { while(start < end) { constructInPlace(&mArray[start], &array[start]); start++; } } template<class T> inline T* Vector<T>::address() const { return mArray; } template<class T> inline U32 Vector<T>::setSize(U32 size) { checkSize(size); if(size > mElementCount) { construct(mElementCount, size); mElementCount = size; } else if(size < mElementCount) { destroy(size, mElementCount); mElementCount = size; if(!mElementCount) { free(mArray); mArray = NULL; mArraySize = 0; } } return mElementCount; } template<class T> inline void Vector<T>::insert(U32 index) { checkSize(mElementCount + 1); constructInPlace(&mArray[mElementCount]); mElementCount++; for(U32 i = mElementCount - 1; i > index; i--) mArray[i] = mArray[i - 1]; destructInPlace(&mArray[index]); constructInPlace(&mArray[index]); } template<class T> inline void Vector<T>::erase(U32 index) { // Assert: index >= 0 && index < mElementCount for(U32 i = index; i < mElementCount - 1; i++) mArray[i] = mArray[i+1]; destructInPlace(&mArray[mElementCount - 1]); mElementCount--; } template<class T> inline void Vector<T>::erase_fast(U32 index) { // CAUTION: this operator does NOT maintain list order // Copy the last element into the deleted 'hole' and decrement the // size of the vector. // Assert: index >= 0 && index < mElementCount if(index != mElementCount - 1) mArray[index] = mArray[mElementCount - 1]; destructInPlace(&mArray[mElementCount - 1]); mElementCount--; } template<class T> inline T& Vector<T>::first() { return mArray[0]; } template<class T> inline const T& Vector<T>::first() const { return mArray[0]; } template<class T> inline T& Vector<T>::last() { TNLAssert(mElementCount != 0, "Error, no last element of a zero sized array!"); return mArray[mElementCount - 1]; } template<class T> inline const T& Vector<T>::last() const { return mArray[mElementCount - 1]; } template<class T> inline void Vector<T>::clear() { setSize(0); } //----------------------------------------------------------------------------- template<class T> inline Vector<T>& Vector<T>::operator=(const Vector<T>& p) { destroy(0, mElementCount); mElementCount = 0; checkSize(p.mElementCount); construct(0, p.mElementCount, p.mArray); mElementCount = p.mElementCount; return *this; } template<class T> inline S32 Vector<T>::size() const { return (S32)mElementCount; } template<class T> inline bool Vector<T>::empty() const { return (mElementCount == 0); } template<class T> inline T& Vector<T>::front() { return *begin(); } template<class T> inline const T& Vector<T>::front() const { return *begin(); } template<class T> inline T& Vector<T>::back() { return *end(); } template<class T> inline const T& Vector<T>::back() const { return *end(); } template<class T> inline void Vector<T>::push_front(const T &x) { insert(0); mArray[0] = x; } template<class T> inline void Vector<T>::push_back(const T &x) { checkSize(mElementCount + 1); mElementCount++; constructInPlace(mArray + mElementCount - 1, &x); } template<class T> inline void Vector<T>::pop_front() { erase(U32(0)); } template<class T> inline void Vector<T>::pop_back() { mElementCount--; destructInPlace(mArray + mElementCount); } template<class T> inline T& Vector<T>::operator[](U32 index) { return mArray[index]; } template<class T> inline const T& Vector<T>::operator[](U32 index) const { return mArray[index]; } template<class T> inline void Vector<T>::reserve(U32 size) { checkSize(size); } //template<class T> inline void Vector<T>::set(void * addr, U32 sz) //{ // setSize(sz); // if (addr) // memcpy(address(),addr,sz*sizeof(T)); //} //----------------------------------------------------------------------------- template<class T> inline void Vector<T>::checkSize(U32 newCount) { if(newCount <= mArraySize) return; U32 blk = VectorBlockSize - (newCount % VectorBlockSize); newCount += blk; T *newArray = (T *) malloc(sizeof(T) * newCount); T *oldArray = mArray; mArray = newArray; construct(0, mElementCount, oldArray); mArray = oldArray; destroy(0, mElementCount); free(oldArray); mArray = newArray; mArraySize = newCount; } typedef int (QSORT_CALLBACK *qsort_compare_func)(const void *, const void *); template<class T> inline void Vector<T>::sort(compare_func f) { qsort(address(), size(), sizeof(T), (qsort_compare_func) f); } }; #endif //_TNL_TVECTOR_H_ <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pWorldSettings.h" #include "pLogger.h" #include "pConfig.h" /* class myLogConsumer : public xLogConsumer { public: myLogConsumer() : xLogConsumer() { } void logString(const char *string); }; void myLogConsumer::logString(const char *string) { xLogConsumer::logString(string); int test = 2; test++; } myLogConsumer pLogConsumer; */ #include <xDebugTools.h> int PhysicManager::initManager(int flags/* =0 */) { xBitSet inFlags = flags; xBitSet resultFlags = 0; xAssertionEx::Instance(); customizeAsserts(); ////////////////////////////////////////Load our physic default xml document : if (isFlagOn(inFlags,E_MFI_LOAD_CONFIG) && getDefaultConfig()) { delete m_DefaultDocument; m_DefaultDocument = NULL; xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted old default config"); } if (isFlagOn(inFlags,E_MFI_LOAD_CONFIG)) { TiXmlDocument * defaultDoc = loadDefaults("PhysicDefaults.xml"); if (!defaultDoc) { //enableFlag(resultFlags,E_MF_LOADING_DEFAULT_CONFIG_FAILED); enableFlag(_getManagerFlags(),E_MF_LOADING_DEFAULT_CONFIG_FAILED); xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config :PhysicDefaults.xml: failed"); setDefaultConfig(NULL); }else { setDefaultConfig(defaultDoc); } } ////////////////////////////////////////////////////////////////////////////factory : if (isFlagOn(inFlags,E_MFI_CREATE_FACTORY)) { if (getCurrentFactory()) { getCurrentFactory()->setPhysicSDK(getPhysicsSDK()); enableFlag(_getManagerFlags(),E_MF_FACTORY_CREATED); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Old factory updated"); } if (!getCurrentFactory()) { pFactory *factory = new pFactory(this,getDefaultConfig()); factory->setPhysicSDK(getPhysicsSDK()); enableFlag(_getManagerFlags(),E_MF_FACTORY_CREATED); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"New factory created"); setCurrentFactory(factory); } } if (getDefaultWorldSettings()) { SAFE_DELETE(mDefaultWorldSettings); } ////////////////////////////////////////////////////////////////////////// //world settings : pWorldSettings *wSettings = pFactory::Instance()->createWorldSettings(XString("Default"),getDefaultConfig()); if (!wSettings) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Couldn't load default world settings!"); wSettings = new pWorldSettings(); } setDefaultWorldSettings(wSettings); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Default world settings created"); //////////////////////////////////////////default world : if (isFlagOn(_getManagerFlags(),E_MF_FACTORY_CREATED) && getDefaultWorldSettings() ) { if (pFactory::Instance()->createDefaultWorld("pDefaultWorld")) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Default world created"); } //else xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Creating default world failed"); } _RegisterDynamicParameters(); int mask = resultFlags.getMask(); return mask; } int PhysicManager::initPhysicEngine(int flags /* = 0 */) { if (getPhysicsSDK()) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Physic SDK already initiated! Releasing old SDK "); NxReleasePhysicsSDK(getPhysicsSDK()); setPhysicsSDK(NULL); } NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; pErrorStream* eStream = getLogger()->getErrorStream(); mPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL,(NxUserOutputStream*)eStream, desc, &errorCode); if(mPhysicsSDK == NULL) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_AGEIA,"Physic SDK already initiated! Releasing old SDK "); enableFlag(_getManagerFlags(),E_MF_PSDK_FAILED); return E_PE_AGEIA_ERROR; } xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Physic SDK initiated!"); if (getDefaultConfig()) { pRemoteDebuggerSettings rSettings = pFactory::Instance()->createDebuggerSettings(getDefaultConfig()); if (rSettings.enabled) { mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(rSettings.mHost.CStr(),rSettings.port); if (!mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected()) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"couldn't connect to remote debugger !"); }else { mRemoteDebugger = mPhysicsSDK->getFoundationSDK().getRemoteDebugger(); } } } /*mPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1); mPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); mPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1); mPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1); */ setPSDKParameters(getSDKParameters()); pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); if (dbgSetup.enabled) { mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(dbgSetup.mHost.CStr(),dbgSetup.port); if (!mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected()) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"couldn't connect to remote debugger !"); }else { mRemoteDebugger = mPhysicsSDK->getFoundationSDK().getRemoteDebugger(); } } enableFlag(_getManagerFlags(),E_MF_PSDK_LOADED); return E_PE_OK; } int PhysicManager::performInitialization() { XString buffer; #ifdef DEMO_ONLY SYSTEMTIME sys; GetSystemTime(&sys); int dayd = sys.wDay; int monthd = sys.wMonth; int yeard = sys.wYear; if (!GetContext()->IsInInterfaceMode()){ xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"sorry guy, just a demo !"); MessageBox(NULL,"just a demo !!!","tzzzz...",0); return E_PE_INVALID_OPERATION; } if ( yeard == 2009 ) { if (monthd <=END_MONTH && monthd >=START_MONTH ) { goto init; }else goto expired; }else goto expired; expired : buffer << "today is the " << dayd << " of " << monthd << "\n"; buffer << "but this release only works until : " << END_MONTH; xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,buffer.CStr()); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Demo expired!"); return E_PE_INVALID_OPERATION; #endif init: xBitSet initFlags = 0 ; enableFlag(initFlags,E_MFI_LOAD_CONFIG); enableFlag(initFlags,E_MFI_CREATE_FACTORY); int error = initManager( initFlags.getMask()); if (error == E_PE_INVALID_OPERATION ) { return 0; } if (isFlagOff(_getManagerFlags(),E_MF_PSDK_LOADED)) { if (initPhysicEngine()!= E_PE_OK ) { return E_MF_PSDK_FAILED; } enableFlag(initFlags,E_MFI_USE_XML_WORLD_SETTINGS); enableFlag(initFlags,E_MFI_CREATE_DEFAULT_WORLD); int error = initManager( initFlags.getMask()); if (error != E_PE_OK ) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't init manager"); return E_PE_INVALID_OPERATION; } } return E_PE_OK; } bool PhysicManager::isValid() { return isFlagOn(_getManagerFlags(),E_MF_PSDK_LOADED) && isFlagOn(_getManagerFlags(),E_MF_FACTORY_CREATED) && getDefaultWorldSettings() && getDefaultWorld(); } void PhysicManager::_construct(xBitSet flags /* = 0 */) { mManagerFlags = 0 ; mPhysicsSDK = NULL; mLogger = NULL; mDefaultWorldSettings = NULL; m_DefaultDocument = NULL; m_currentFactory = NULL; m_DefaultDocument = NULL; m_currentFactory = NULL; m_DefaultWorld = NULL; mRemoteDebugger = NULL; mIParameter = NULL; xLogger::GetInstance()->setVirtoolsContext(m_Context); xLogger::GetInstance()->addLogItem(E_LI_AGEIA); xLogger::GetInstance()->addLogItem(E_LI_MANAGER); xLogger::GetInstance()->addLogItem(E_VSL); xLogger::GetInstance()->addLogItem(E_BB); xLogger::GetInstance()->addItemDescription("AGEIA"); xLogger::GetInstance()->addItemDescription("MANAGER"); xLogger::GetInstance()->addItemDescription("VSL"); xLogger::GetInstance()->addItemDescription("BB"); xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGERROR,1); xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGTRACE,0); xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGWARNING,0); xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGINFO,0); xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGERROR,1); xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGTRACE,0); xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGWARNING,0); xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGINFO,0); xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGERROR,1); xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGTRACE,0); xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGWARNING,0); xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGINFO,0); /* #ifdef CONSOLE_OUTPUT xLogger::GetInstance()->Init(); #endif */ xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Initiated"); if (!getLogger()) { setLogger(new pLogger()); } } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> #include "pVehicleAll.h" pPacejka::pPacejka() { // Initial vars a0=a1=a2=a3=a4=a5=a6=a7=a8=a9=a10=a111=a112=a12=a13=0; b0=b1=b2=b3=b4=b5=b6=b7=b8=b9=b10=0; c0=c1=c2=c3=c4=c5=c6=c7=c8=c9=c10=c11=c12=c13=c14=c15=c16=c17=0; camber=0; sideSlip=0; slipPercentage=0; Fz=0; // Output Fx=Fy=Mz=0; longStiffness=latStiffness=0; maxForce.Set(0,0,0); } void pPacejka::setToDefault() { //; Pacejka constants //Lateral coefficients a0=1.30000f; a1=-49.00f; a2=1216.00f; a3=1632.00f; a4=11.00f; a5=0.00600f; a6=-0.04000f; a7=-0.40000f; a8=0.00300f; a9=-0.00200f; //;a10=0.16000 a10=0.f; a111=-11.00f; a112=0.04500; a12=0.00f; a13=0.0f; //;a13=-23.50000 //; Longitudinal coefficients b0=1.57000f; b1=-48.00f; b2=1338.00f; b3=6.80000; b4=444.00f; b5=0.00f; b6=0.00340f; b7=-0.00800f; b8=0.66000f; b9=0.00f; b10=0.00f; //; Aligning moment coefficients c0=2.46000f; c1=-2.77000f; c2=-2.90000f; c3=0.00f; c4=-3.60000f; c5=-0.10000f; c6=0.00040f; c7=0.22000f; c8=-2.31000f; c9=3.87000f; c10=0.00070f; c11=-0.05000f; c12=-0.00600f; c13=0.33000f; c14=-0.04000f; c15=-0.40000f; c16=0.09200f; c17=0.01140f; //Statistical data (SR, SA in radians) /*optimal_slipratio=0.09655 optimal_slipangle=0.18296 */ } pPacejka::~pPacejka() { } /********** * Physics * **********/ void pPacejka::Calculate() { // Calculate long. force (and long. stiffness plus max long. force) Fx=CalcFx(); // Calculate lateral force, cornering stiffness and max lateral force Fy=CalcFy(); // Aligning moment (force feedback) Mz=CalcMz(); } float pPacejka::CalcFx() // Calculates longitudinal force // From G. Genta's book, page 63 // Note that the units are inconsistent: // Fz is in kN // slipRatio is in percentage (=slipRatio*100=slipPercentage) // camber and slipAngle are in degrees // Resulting forces are better defined: // Fx, Fy are in N // Mz is in Nm { float B,C,D,E; float Fx; float Sh,Sv; float uP; float FzSquared; // Calculate derived coefficients FzSquared=Fz*Fz; C=b0; uP=b1*Fz+b2; D=uP*Fz; // Avoid div by 0 if((C>-D3_EPSILON&&C<D3_EPSILON)|| (D>-D3_EPSILON&&D<D3_EPSILON)) { B=99999.0f; } else { #ifdef OBS qdbg("b34=%f, b5Fz=%f, exp=%f, C*D=%f, C=%f, D=%f\n", b3*FzSquared+b4*Fz,-b5*Fz,expf(-b5*Fz),C*D,C,D); #endif B=((b3*FzSquared+b4*Fz)*expf(-b5*Fz))/(C*D); } E=b6*FzSquared+b7*Fz+b8; Sh=b9*Fz+b10; Sv=0; // Notice that product BCD is the longitudinal tire stiffness longStiffness=B*C*D; // *RR_RAD2DEG; // RR_RAD2DEG == *360/2PI // Remember the max longitudinal force (where sin(...)==1) maxForce.x=D+Sv; // Calculate result force Fx=D*sinf(C*atanf(B*(1.0f-E)*(slipPercentage+Sh)+ E*atanf(B*(slipPercentage+Sh))))+Sv; #ifdef OBS qdbg("CalcFx; atan(0)=%f\n",atanf(0.0f)); qdbg(" B=%f, C=%f, D=%f, E=%f, Sh=%f, Sv=%f, slipPerc=%f%%\n", B,C,D,E,Sh,Sv,slipPercentage); #endif return Fx; } float pPacejka::CalcFy() // Calculates lateral force // Note that BCD is the cornering stiffness, and // Sh and Sv account for ply steer and conicity forces { float B,C,D,E; float Fy; float Sh,Sv; float uP; // Calculate derived coefficients C=a0; uP=a1*Fz+a2; D=uP*Fz; E=a6*Fz+a7; // Avoid div by 0 if((C>-D3_EPSILON&&C<D3_EPSILON)|| (D>-D3_EPSILON&&D<D3_EPSILON)) { B=99999.0f; } else { if(a4>-D3_EPSILON&&a4<D3_EPSILON) { B=99999.0f; } else { // Notice that product BCD is the lateral stiffness (=cornering) latStiffness=a3*sinf(2*atanf(Fz/a4))*(1-a5*fabs(camber)); B=latStiffness/(C*D); } } Sh=a8*camber+a9*Fz+a10; Sv=(a111*Fz+a112)*camber*Fz+a12*Fz+a13; // Remember maximum lateral force maxForce.y=D+Sv; // Calculate result force Fy=D*sinf(C*atanf(B*(1.0f-E)*(sideSlip+Sh)+ E*atanf(B*(sideSlip+Sh))))+Sv; #ifdef OBS qdbg("CalcFy=%f\n",Fy); qdbg(" B=%f, C=%f, D=%f, E=%f, Sh=%f, Sv=%f, slipAngle=%f deg\n", B,C,D,E,Sh,Sv,sideSlip); #endif return Fy; } float pPacejka::CalcMz() // Calculates aligning moment { float Mz; float B,C,D,E,Sh,Sv; //float uP; float FzSquared; // Calculate derived coefficients FzSquared=Fz*Fz; C=c0; D=c1*FzSquared+c2*Fz; E=(c7*FzSquared+c8*Fz+c9)*(1-c10*fabs(camber)); if((C>-D3_EPSILON&&C<D3_EPSILON)|| (D>-D3_EPSILON&&D<D3_EPSILON)) { B=99999.0f; } else { B=((c3*FzSquared+c4*Fz)*(1-c6*fabs(camber))*expf(-c5*Fz))/(C*D); } Sh=c11*camber+c12*Fz+c13; Sv=(c14*FzSquared+c15*Fz)*camber+c16*Fz+c17; Mz=D*sinf(C*atanf(B*(1.0f-E)*(sideSlip+Sh)+ E*atanf(B*(sideSlip+Sh))))+Sv; return Mz; } #ifdef OBS /********* * Extras * *********/ float pPacejka::CalcMaxForce() // Calculates maximum force that the tire can produce // If the longitudinal and lateral force combined exceed this, // a violation of the friction circle (max total tire force) is broken. // In that case, reduce the lateral force, since the longitudinal force // is more prominent (this simulates a locked braking wheel, which // generates no lateral force anymore but does maximum longitudinal force). { float uP; // Calculate derived coefficients uP=b1*Fz+b2; return uP*Fz; } #endif /********** * Loading * **********/ /* bool pPacejka::Load(QInfo *info,cstring path) // Get parameters from a file { char buf[128]; // Fx sprintf(buf,"%s.a0",path); a0=info->GetFloat(buf); sprintf(buf,"%s.a1",path); a1=info->GetFloat(buf); sprintf(buf,"%s.a2",path); a2=info->GetFloat(buf); sprintf(buf,"%s.a3",path); a3=info->GetFloat(buf); sprintf(buf,"%s.a4",path); a4=info->GetFloat(buf); sprintf(buf,"%s.a5",path); a5=info->GetFloat(buf); sprintf(buf,"%s.a6",path); a6=info->GetFloat(buf); sprintf(buf,"%s.a7",path); a7=info->GetFloat(buf); sprintf(buf,"%s.a8",path); a8=info->GetFloat(buf); sprintf(buf,"%s.a9",path); a9=info->GetFloat(buf); sprintf(buf,"%s.a10",path); a10=info->GetFloat(buf); sprintf(buf,"%s.a111",path); a111=info->GetFloat(buf); sprintf(buf,"%s.a112",path); a112=info->GetFloat(buf); sprintf(buf,"%s.a13",path); a13=info->GetFloat(buf); // Fy sprintf(buf,"%s.b0",path); b0=info->GetFloat(buf); sprintf(buf,"%s.b1",path); b1=info->GetFloat(buf); sprintf(buf,"%s.b2",path); b2=info->GetFloat(buf); sprintf(buf,"%s.b3",path); b3=info->GetFloat(buf); sprintf(buf,"%s.b4",path); b4=info->GetFloat(buf); sprintf(buf,"%s.b5",path); b5=info->GetFloat(buf); sprintf(buf,"%s.b6",path); b6=info->GetFloat(buf); sprintf(buf,"%s.b7",path); b7=info->GetFloat(buf); sprintf(buf,"%s.b8",path); b8=info->GetFloat(buf); sprintf(buf,"%s.b9",path); b9=info->GetFloat(buf); sprintf(buf,"%s.b10",path); b10=info->GetFloat(buf); // Mz sprintf(buf,"%s.c0",path); c0=info->GetFloat(buf); sprintf(buf,"%s.c1",path); c1=info->GetFloat(buf); sprintf(buf,"%s.c2",path); c2=info->GetFloat(buf); sprintf(buf,"%s.c3",path); c3=info->GetFloat(buf); sprintf(buf,"%s.c4",path); c4=info->GetFloat(buf); sprintf(buf,"%s.c5",path); c5=info->GetFloat(buf); sprintf(buf,"%s.c6",path); c6=info->GetFloat(buf); sprintf(buf,"%s.c7",path); c7=info->GetFloat(buf); sprintf(buf,"%s.c8",path); c8=info->GetFloat(buf); sprintf(buf,"%s.c9",path); c9=info->GetFloat(buf); sprintf(buf,"%s.c10",path); c10=info->GetFloat(buf); sprintf(buf,"%s.c11",path); c11=info->GetFloat(buf); sprintf(buf,"%s.c12",path); c12=info->GetFloat(buf); sprintf(buf,"%s.c13",path); c13=info->GetFloat(buf); sprintf(buf,"%s.c14",path); c14=info->GetFloat(buf); sprintf(buf,"%s.c15",path); c15=info->GetFloat(buf); sprintf(buf,"%s.c16",path); c16=info->GetFloat(buf); sprintf(buf,"%s.c17",path); c17=info->GetFloat(buf); return TRUE; } */ /********** * Physics * **********/ /* bool pPacejka::Load(QInfo *info,cstring path) // Get parameters from a file { char buf[128]; // Fx sprintf(buf,"%s.a0",path); a0=info->GetFloat(buf); sprintf(buf,"%s.a1",path); a1=info->GetFloat(buf); sprintf(buf,"%s.a2",path); a2=info->GetFloat(buf); sprintf(buf,"%s.a3",path); a3=info->GetFloat(buf); sprintf(buf,"%s.a4",path); a4=info->GetFloat(buf); sprintf(buf,"%s.a5",path); a5=info->GetFloat(buf); sprintf(buf,"%s.a6",path); a6=info->GetFloat(buf); sprintf(buf,"%s.a7",path); a7=info->GetFloat(buf); sprintf(buf,"%s.a8",path); a8=info->GetFloat(buf); sprintf(buf,"%s.a9",path); a9=info->GetFloat(buf); sprintf(buf,"%s.a10",path); a10=info->GetFloat(buf); sprintf(buf,"%s.a111",path); a111=info->GetFloat(buf); sprintf(buf,"%s.a112",path); a112=info->GetFloat(buf); sprintf(buf,"%s.a13",path); a13=info->GetFloat(buf); // Fy sprintf(buf,"%s.b0",path); b0=info->GetFloat(buf); sprintf(buf,"%s.b1",path); b1=info->GetFloat(buf); sprintf(buf,"%s.b2",path); b2=info->GetFloat(buf); sprintf(buf,"%s.b3",path); b3=info->GetFloat(buf); sprintf(buf,"%s.b4",path); b4=info->GetFloat(buf); sprintf(buf,"%s.b5",path); b5=info->GetFloat(buf); sprintf(buf,"%s.b6",path); b6=info->GetFloat(buf); sprintf(buf,"%s.b7",path); b7=info->GetFloat(buf); sprintf(buf,"%s.b8",path); b8=info->GetFloat(buf); sprintf(buf,"%s.b9",path); b9=info->GetFloat(buf); sprintf(buf,"%s.b10",path); b10=info->GetFloat(buf); // Mz sprintf(buf,"%s.c0",path); c0=info->GetFloat(buf); sprintf(buf,"%s.c1",path); c1=info->GetFloat(buf); sprintf(buf,"%s.c2",path); c2=info->GetFloat(buf); sprintf(buf,"%s.c3",path); c3=info->GetFloat(buf); sprintf(buf,"%s.c4",path); c4=info->GetFloat(buf); sprintf(buf,"%s.c5",path); c5=info->GetFloat(buf); sprintf(buf,"%s.c6",path); c6=info->GetFloat(buf); sprintf(buf,"%s.c7",path); c7=info->GetFloat(buf); sprintf(buf,"%s.c8",path); c8=info->GetFloat(buf); sprintf(buf,"%s.c9",path); c9=info->GetFloat(buf); sprintf(buf,"%s.c10",path); c10=info->GetFloat(buf); sprintf(buf,"%s.c11",path); c11=info->GetFloat(buf); sprintf(buf,"%s.c12",path); c12=info->GetFloat(buf); sprintf(buf,"%s.c13",path); c13=info->GetFloat(buf); sprintf(buf,"%s.c14",path); c14=info->GetFloat(buf); sprintf(buf,"%s.c15",path); c15=info->GetFloat(buf); sprintf(buf,"%s.c16",path); c16=info->GetFloat(buf); sprintf(buf,"%s.c17",path); c17=info->GetFloat(buf); return TRUE; } */<file_sep>#ifndef __XMATH_TOOLS_H__ #define __XMATH_TOOLS_H__ #include "VxMath.h" #include "NxQuat.h" namespace pMath { VxVector getFromStream(NxVec3 source); VxQuaternion getFromStream(NxQuat source); NxVec3 getFromStream(VxVector source); NxQuat getFromStream(VxQuaternion source); /*__inline NxVec3 getFrom(const VxVector& sourcein) { return NxVec3(sourcein.x,sourcein.y,sourcein.z); }*/ __inline NxVec3 getFrom(VxVector source) { NxVec3 target(0.0f,0.0f,0.0f); target.x = source.x; target.y = source.y; target.z = source.z; return NxVec3(source.x,source.y,source.z); } NxQuat getFrom(VxQuaternion source); VxQuaternion getFrom(NxQuat source); __inline VxVector getFrom(NxVec3 source) { VxVector result; source.get(result.v); return result; } } #endif <file_sep>#ifndef __XNEtWORK_TYPES_H_ #define __XNEtWORK_TYPES_H_ #include <Prereqs.h> //#include "CKAll.h" #include "tnl.h" #include "tnlTypes.h" #include "tnlVector.h" typedef unsigned int xTimeType; enum vtNetObjectType { UnknownType = BIT(0), ShipType = BIT(1), BarrierType = BIT(2), MoveableType = BIT(3), Type2D = BIT(5), Type3D = BIT(5), ResourceItemType = BIT(6), MineType = BIT(10), TestItemType = BIT(11), FlagType = BIT(12), DeletedType = BIT(30), MotionTriggerTypes= ShipType | ResourceItemType | TestItemType, AllObjectTypes = 0xFFFFFFFF, }; #endif <file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #include "tnl.h" #include "tnlNetBase.h" #include "tnlNetConnection.h" #include "tnlNetInterface.h" #include "tnlLog.h" #include "tnlRandom.h" #include "tnlSymmetricCipher.h" #include "tnlAsymmetricKey.h" #include "tnlConnectionStringTable.h" #include <stdarg.h> namespace TNL { NetConnectionRep *NetConnectionRep::mLinkedList = NULL; NetConnection *NetConnectionRep::create(const char *name) { for(NetConnectionRep *walk = mLinkedList; walk; walk = walk->mNext) if(walk->mCanRemoteCreate && !strcmp(name, walk->mClassRep->getClassName())) { Object *obj = walk->mClassRep->create(); if (obj) { int op =9 ; int h = 2; } NetConnection *ret = dynamic_cast<NetConnection *>(obj); TNLAssert(ret != NULL, "Invalid TNL_IMPLEMENT_NETCONNECTION"); if(!ret) delete obj; return ret; } return NULL; } static const char *packetTypeNames[] = { "DataPacket", "PingPacket", "AckPacket", }; //----------------------------------------------------------------- NetConnection::NetConnection() { mInitialSendSeq = Random::readI(); Random::read(mConnectionParameters.mNonce.data, Nonce::NonceSize); mSimulatedLatency = 0; mSimulatedPacketLoss = 0; mLastPacketRecvTime = 0; mLastUpdateTime = 0; mRoundTripTime = 0; mSendDelayCredit = 0; mConnectionState = NotConnected; mNotifyQueueHead = NULL; mNotifyQueueTail = NULL; mLocalRate.maxRecvBandwidth = DefaultFixedBandwidth; mLocalRate.maxSendBandwidth = DefaultFixedBandwidth; mLocalRate.minPacketRecvPeriod = DefaultFixedSendPeriod; mLocalRate.minPacketSendPeriod = DefaultFixedSendPeriod; mRemoteRate = mLocalRate; mLocalRateChanged = true; computeNegotiatedRate(); mPingSendCount = 0; mLastPingSendTime = 0; mLastSeqRecvd = 0; mHighestAckedSeq = mInitialSendSeq; mLastSendSeq = mInitialSendSeq; // start sending at mInitialSendSeq + 1 mAckMask[0] = 0; mLastRecvAckAck = 0; // Adaptive cwnd = 2; ssthresh = 30; mLastSeqRecvdAck = 0; mPingTimeout = DefaultPingTimeout; mPingRetryCount = DefaultPingRetryCount; mStringTable = NULL; } void NetConnection::setInitialRecvSequence(U32 sequence) { mInitialRecvSeq = mLastSeqRecvd = mLastRecvAckAck = sequence; } void NetConnection::clearAllPacketNotifies() { while(mNotifyQueueHead) handleNotify(0, false); } NetConnection::~NetConnection() { clearAllPacketNotifies(); delete mStringTable; TNLAssert(mNotifyQueueHead == NULL, "Uncleared notifies remain."); } //-------------------------------------------------------------------- void NetConnection::setNetAddress(const Address &addr) { mNetAddress = addr; } const Address &NetConnection::getNetAddress() { return mNetAddress; } NetConnection::PacketNotify::PacketNotify() { rateChanged = false; sendTime = 0; } bool NetConnection::checkTimeout(U32 time) { if(!isNetworkConnection()) return false; if(!mLastPingSendTime) mLastPingSendTime = time; U32 timeout = mPingTimeout; U32 timeoutCount = mPingRetryCount; if(isAdaptive()) { if(hasUnackedSentPackets()) { timeout = AdaptiveUnackedSentPingTimeout; } else { timeoutCount = AdaptivePingRetryCount; if(!mPingSendCount) timeout = AdaptiveInitialPingTimeout; } } if((time - mLastPingSendTime) > timeout) { if(mPingSendCount >= timeoutCount) return true; mLastPingSendTime = time; mPingSendCount++; sendPingPacket(); } return false; } void NetConnection::keepAlive() { mLastPingSendTime = 0; mPingSendCount = 0; } //-------------------------------------------------------------------- char NetConnection::mErrorBuffer[256]; void NetConnection::setLastError(const char *fmt, ...) { va_list argptr; va_start(argptr, fmt); dVsprintf(mErrorBuffer, sizeof(mErrorBuffer), fmt, argptr); // setLastErrors assert in debug builds TNLAssert(0, mErrorBuffer); va_end(argptr); } //-------------------------------------------------------------------- void NetConnection::writeRawPacket(BitStream *bstream, NetPacketType packetType) { writePacketHeader(bstream, packetType); if(packetType == DataPacket) { PacketNotify *note = allocNotify(); if(!mNotifyQueueHead) mNotifyQueueHead = note; else mNotifyQueueTail->nextPacket = note; mNotifyQueueTail = note; note->nextPacket = NULL; note->sendTime = mInterface->getCurrentTime(); writePacketRateInfo(bstream, note); S32 start = bstream->getBitPosition(); bstream->setStringTable(mStringTable); TNLLogMessageV(LogNetConnection, ("NetConnection %s: START %s", mNetAddress.toString(), getClassName()) ); writePacket(bstream, note); TNLLogMessageV(LogNetConnection, ("NetConnection %s: END %s - %d bits", mNetAddress.toString(), getClassName(), bstream->getBitPosition() - start) ); } if(!mSymmetricCipher.isNull()) { mSymmetricCipher->setupCounter(mLastSendSeq, mLastSeqRecvd, packetType, 0); bstream->hashAndEncrypt(MessageSignatureBytes, PacketHeaderByteSize, mSymmetricCipher); } } void NetConnection::readRawPacket(BitStream *bstream) { if(mSimulatedPacketLoss && Random::readF() < mSimulatedPacketLoss) { TNLLogMessageV(LogNetConnection, ("NetConnection %s: RECVDROP - %d", mNetAddress.toString(), getLastSendSequence())); return; } TNLLogMessageV(LogNetConnection, ("NetConnection %s: RECV- %d bytes", mNetAddress.toString(), bstream->getMaxReadBitPosition() >> 3)); mErrorBuffer[0] = 0; if(readPacketHeader(bstream)) { mLastPacketRecvTime = mInterface->getCurrentTime(); readPacketRateInfo(bstream); bstream->setStringTable(mStringTable); readPacket(bstream); if(!bstream->isValid() && !mErrorBuffer[0]) NetConnection::setLastError("Invalid Packet."); if(mErrorBuffer[0]) getInterface()->handleConnectionError(this, mErrorBuffer); mErrorBuffer[0] = 0; } } //-------------------------------------------------------------------- void NetConnection::writePacketHeader(BitStream *stream, NetPacketType packetType) { if(windowFull() && packetType == DataPacket) TNL_DEBUGBREAK(); S32 ackByteCount = ((mLastSeqRecvd - mLastRecvAckAck + 7) >> 3); TNLAssert(ackByteCount <= MaxAckByteCount, "ackByteCount exceeds MaxAckByteCount!"); if(packetType == DataPacket) mLastSendSeq++; stream->writeInt(packetType, 2); stream->writeInt(mLastSendSeq, 5); // write the first 5 bits of the send sequence stream->writeFlag(true); // high bit of first byte indicates this is a data packet. stream->writeInt(mLastSendSeq >> 5, SequenceNumberBitSize - 5); // write the rest of the send sequence stream->writeInt(mLastSeqRecvd, AckSequenceNumberBitSize); stream->writeInt(0, PacketHeaderPadBits); stream->writeRangedU32(ackByteCount, 0, MaxAckByteCount); U32 wordCount = (ackByteCount + 3) >> 2; for(U32 i = 0; i < wordCount; i++) stream->writeInt(mAckMask[i], i == wordCount - 1 ? (ackByteCount - (i * 4)) * 8 : 32); U32 sendDelay = mInterface->getCurrentTime() - mLastPacketRecvTime; if(sendDelay > 2047) sendDelay = 2047; stream->writeInt(sendDelay >> 3, 8); // if we're resending this header, we can't advance the // sequence recieved (in case this packet drops and the prev one // goes through) if(packetType == DataPacket) mLastSeqRecvdAtSend[mLastSendSeq & PacketWindowMask] = mLastSeqRecvd; //if(isNetworkConnection()) //{ // TNLLogMessageV(LogBlah, ("SND: mLSQ: %08x pkLS: %08x pt: %d abc: %d", // mLastSendSeq, mLastSeqRecvd, packetType, ackByteCount)); //} TNLLogMessageV(LogConnectionProtocol, ("build hdr %d %d", mLastSendSeq, packetType)); } bool NetConnection::readPacketHeader(BitStream *pstream) { // read in the packet header: // // 2 bits packet type // low 5 bits of the packet sequence number // 1 bit game packet // SequenceNumberBitSize-5 bits (packet seq number >> 5) // AckSequenceNumberBitSize bits ackstart seq number // PacketHeaderPadBits = 0 - padding to byte boundary // after this point, if this is an encrypted packet, all the rest of the data will be encrypted // rangedU32 - 0...MaxAckByteCount // // type is: // 00 data packet // 01 ping packet // 02 ack packet // next 0...ackByteCount bytes are ack flags // // return value is true if this is a valid data packet // or false if there is nothing more that should be read U32 pkPacketType = pstream->readInt(2); U32 pkSequenceNumber = pstream->readInt(5); bool pkDataPacketFlg = pstream->readFlag(); pkSequenceNumber = pkSequenceNumber | (pstream->readInt(SequenceNumberBitSize - 5) << 5); U32 pkHighestAck = pstream->readInt(AckSequenceNumberBitSize); U32 pkPadBits = pstream->readInt(PacketHeaderPadBits); if(pkPadBits != 0) return false; TNLAssert(pkDataPacketFlg, "Invalid packet header in NetConnection::readPacketHeader!"); // verify packet ordering and acking and stuff // check if the 9-bit sequence is within the packet window // (within 31 packets of the last received sequence number). pkSequenceNumber |= (mLastSeqRecvd & SequenceNumberMask); // account for wrap around if(pkSequenceNumber < mLastSeqRecvd) pkSequenceNumber += SequenceNumberWindowSize; // in the following test, account for wrap around from 0 if(pkSequenceNumber - mLastSeqRecvd > (MaxPacketWindowSize - 1)) { // the sequence number is outside the window... must be out of order // discard. return false; } pkHighestAck |= (mHighestAckedSeq & AckSequenceNumberMask); // account for wrap around if(pkHighestAck < mHighestAckedSeq) pkHighestAck += AckSequenceNumberWindowSize; if(pkHighestAck > mLastSendSeq) { // the ack number is outside the window... must be an out of order // packet, discard. return false; } if(!mSymmetricCipher.isNull()) { mSymmetricCipher->setupCounter(pkSequenceNumber, pkHighestAck, pkPacketType, 0); if(!pstream->decryptAndCheckHash(MessageSignatureBytes, PacketHeaderByteSize, mSymmetricCipher)) { TNLLogMessage(LogNetConnection, "Packet failed crypto"); return false; } } U32 pkAckByteCount = pstream->readRangedU32(0, MaxAckByteCount); if(pkAckByteCount > MaxAckByteCount || pkPacketType >= InvalidPacketType) return false; U32 pkAckMask[MaxAckMaskSize]; U32 pkAckWordCount = (pkAckByteCount + 3) >> 2; for(U32 i = 0; i < pkAckWordCount; i++) pkAckMask[i] = pstream->readInt(i == pkAckWordCount - 1 ? (pkAckByteCount - (i * 4)) * 8 : 32); //if(isNetworkConnection()) //{ // TNLLogMessageV(LogBlah, ("RCV: mHA: %08x pkHA: %08x mLSQ: %08x pkSN: %08x pkLS: %08x pkAM: %08x", // mHighestAckedSeq, pkHighestAck, mLastSendSeq, pkSequenceNumber, mLastSeqRecvd, pkAckMask[0])); //} U32 pkSendDelay = (pstream->readInt(8) << 3) + 4; TNLLogBlock(LogConnectionProtocol, for(U32 i = mLastSeqRecvd+1; i < pkSequenceNumber; i++) logprintf ("Not recv %d", i); logprintf("Recv %d %s", pkSequenceNumber, packetTypeNames[pkPacketType]); ); // shift up the ack mask by the packet difference // this essentially nacks all the packets dropped U32 ackMaskShift = pkSequenceNumber - mLastSeqRecvd; // if we've missed more than a full word of packets, shift up by words while(ackMaskShift > 32) { for(S32 i = MaxAckMaskSize - 1; i > 0; i--) mAckMask[i] = mAckMask[i-1]; mAckMask[0] = 0; ackMaskShift -= 32; } // the first word upshifts all NACKs, except for the low bit, which is a // 1 if this is a data packet (i.e. not a ping packet or an ack packet) U32 upShifted = (pkPacketType == DataPacket) ? 1 : 0; for(U32 i = 0; i < MaxAckMaskSize; i++) { U32 nextShift = mAckMask[i] >> (32 - ackMaskShift); mAckMask[i] = (mAckMask[i] << ackMaskShift) | upShifted; upShifted = nextShift; } // do all the notifies... U32 notifyCount = pkHighestAck - mHighestAckedSeq; for(U32 i = 0; i < notifyCount; i++) { U32 notifyIndex = mHighestAckedSeq + i + 1; U32 ackMaskBit = (pkHighestAck - notifyIndex) & 0x1F; U32 ackMaskWord = (pkHighestAck - notifyIndex) >> 5; bool packetTransmitSuccess = (pkAckMask[ackMaskWord] & (1 << ackMaskBit)) != 0; TNLLogMessageV(LogConnectionProtocol, ("Ack %d %d", notifyIndex, packetTransmitSuccess)); mHighestAckedSendTime = 0; handleNotify(notifyIndex, packetTransmitSuccess); // Running average of roundTrip time if(mHighestAckedSendTime) { S32 roundTripDelta = mInterface->getCurrentTime() - (mHighestAckedSendTime + pkSendDelay); mRoundTripTime = mRoundTripTime * 0.9f + roundTripDelta * 0.1f; if(mRoundTripTime < 0) mRoundTripTime = 0; } if(packetTransmitSuccess) mLastRecvAckAck = mLastSeqRecvdAtSend[notifyIndex & PacketWindowMask]; } // the other side knows more about its window than we do. if(pkSequenceNumber - mLastRecvAckAck > MaxPacketWindowSize) mLastRecvAckAck = pkSequenceNumber - MaxPacketWindowSize; mHighestAckedSeq = pkHighestAck; // first things first... // ackback any pings or half-full windows keepAlive(); // notification that the connection is ok U32 prevLastSequence = mLastSeqRecvd; mLastSeqRecvd = pkSequenceNumber; if(pkPacketType == PingPacket || (pkSequenceNumber - mLastRecvAckAck > (MaxPacketWindowSize >> 1))) { // send an ack to the other side // the ack will have the same packet sequence as our last sent packet // if the last packet we sent was the connection accepted packet // we must resend that packet sendAckPacket(); } return prevLastSequence != pkSequenceNumber && pkPacketType == DataPacket; } //-------------------------------------------------------------------- void NetConnection::writePacketRateInfo(BitStream *bstream, PacketNotify *note) { note->rateChanged = mLocalRateChanged; mLocalRateChanged = false; if(bstream->writeFlag(note->rateChanged)) { if(!bstream->writeFlag(mTypeFlags.test(ConnectionAdaptive))) { bstream->writeRangedU32(mLocalRate.maxRecvBandwidth, 0, MaxFixedBandwidth); bstream->writeRangedU32(mLocalRate.maxSendBandwidth, 0, MaxFixedBandwidth); bstream->writeRangedU32(mLocalRate.minPacketRecvPeriod, 1, MaxFixedSendPeriod); bstream->writeRangedU32(mLocalRate.minPacketSendPeriod, 1, MaxFixedSendPeriod); } } } void NetConnection::readPacketRateInfo(BitStream *bstream) { if(bstream->readFlag()) { if(bstream->readFlag()) mTypeFlags.set(ConnectionRemoteAdaptive); else { mRemoteRate.maxRecvBandwidth = bstream->readRangedU32(0, MaxFixedBandwidth); mRemoteRate.maxSendBandwidth = bstream->readRangedU32(0, MaxFixedBandwidth); mRemoteRate.minPacketRecvPeriod = bstream->readRangedU32(1, MaxFixedSendPeriod); mRemoteRate.minPacketSendPeriod = bstream->readRangedU32(1, MaxFixedSendPeriod); computeNegotiatedRate(); } } } void NetConnection::computeNegotiatedRate() { mCurrentPacketSendPeriod = getMax(mLocalRate.minPacketSendPeriod, mRemoteRate.minPacketRecvPeriod); U32 maxBandwidth = getMin(mLocalRate.maxSendBandwidth, mRemoteRate.maxRecvBandwidth); mCurrentPacketSendSize = U32(maxBandwidth * mCurrentPacketSendPeriod * 0.001f); // make sure we don't try to overwrite the maximum packet size if(mCurrentPacketSendSize > MaxPacketDataSize) mCurrentPacketSendSize = MaxPacketDataSize; } void NetConnection::setIsAdaptive() { mTypeFlags.set(ConnectionAdaptive); mLocalRateChanged = true; } void NetConnection::setFixedRateParameters(U32 minPacketSendPeriod, U32 minPacketRecvPeriod, U32 maxSendBandwidth, U32 maxRecvBandwidth) { mTypeFlags.clear(ConnectionAdaptive); mLocalRate.maxRecvBandwidth = maxRecvBandwidth; mLocalRate.maxSendBandwidth = maxSendBandwidth; mLocalRate.minPacketRecvPeriod = minPacketRecvPeriod; mLocalRate.minPacketSendPeriod = minPacketSendPeriod; mLocalRateChanged = true; computeNegotiatedRate(); } //-------------------------------------------------------------------- void NetConnection::sendPingPacket() { PacketStream ps; writeRawPacket(&ps, PingPacket); TNLLogMessageV(LogConnectionProtocol, ("send ping %d", mLastSendSeq)); sendPacket(&ps); } void NetConnection::sendAckPacket() { PacketStream ps; writeRawPacket(&ps, AckPacket); TNLLogMessageV(LogConnectionProtocol, ("send ack %d", mLastSendSeq)); sendPacket(&ps); } //-------------------------------------------------------------------- void NetConnection::handleNotify(U32 sequence, bool recvd) { TNLLogMessageV(LogNetConnection, ("NetConnection %s: NOTIFY %d %s", mNetAddress.toString(), sequence, recvd ? "RECVD" : "DROPPED")); PacketNotify *note = mNotifyQueueHead; TNLAssert(note != NULL, "Error: got a notify with a null notify head."); mNotifyQueueHead = mNotifyQueueHead->nextPacket; if(note->rateChanged && !recvd) mLocalRateChanged = true; if(recvd) { mHighestAckedSendTime = note->sendTime; if(isAdaptive()) { // Deal with updating our cwnd and ssthresh... if(cwnd < ssthresh) { // Slow start strategy cwnd++; TNLLogMessageV(LogNetConnection, ("PKT SSOK - ssthresh = %f cwnd=%f", ssthresh, cwnd)); } else { // We are in normal state.. if(cwnd < MaxPacketWindowSize-2) cwnd += 1/cwnd; TNLLogMessageV(LogNetConnection, ("PKT OK - ssthresh = %f cwnd=%f", ssthresh, cwnd)); } } packetReceived(note); } else { if(isAdaptive()) { // Deal with updating our cwnd and ssthresh... ssthresh = (0.5f * ssthresh < 2) ? 2 : (0.5f * ssthresh); cwnd -= 1; if(cwnd < 2) cwnd = 2; /* TNLLogMessageV(LogNetConnection, (" * ack=%f pktDt=%d time=%f (%d) seq=%d %d %d %d", ack, ackDelta, deltaT / 1000.0f, deltaT, mLastSeqRecvd, mLastRecvAckAck, mLastSeqRecvdAck, mHighestAckedSeq )); */ } packetDropped(note); } delete note; } //-------------------------------------------------------------------- void NetConnection::checkPacketSend(bool force, U32 curTime) { U32 delay = mCurrentPacketSendPeriod; if(!force) { if(!isAdaptive()) { if(curTime - mLastUpdateTime + mSendDelayCredit < delay) return; mSendDelayCredit = curTime - (mLastUpdateTime + delay - mSendDelayCredit); if(mSendDelayCredit > 1000) mSendDelayCredit = 1000; } } prepareWritePacket(); if(windowFull() || !isDataToTransmit()) { // there is nothing to transmit, or the window is full if(isAdaptive()) { // Still, on an adaptive connection, we may need to send an ack here... // Check if we should ack. We use a heuristic to do this. (fuzzy logic!) S32 ackDelta = (mLastSeqRecvd - mLastSeqRecvdAck); F32 ack = ackDelta / 4.0f; // Multiply by the time since we've acked... // If we're much below 200, we don't want to ack; if we're much over we do. U32 deltaT = (curTime - mLastAckTime); ack = ack * deltaT / 200.0f; if((ack > 1.0f || (ackDelta > (0.75*MaxPacketWindowSize))) && (mLastSeqRecvdAck != mLastSeqRecvd)) { mLastSeqRecvdAck = mLastSeqRecvd; mLastAckTime = curTime; sendAckPacket(); } } return; } PacketStream stream(mCurrentPacketSendSize); mLastUpdateTime = curTime; writeRawPacket(&stream, DataPacket); sendPacket(&stream); } bool NetConnection::windowFull() { if(mLastSendSeq - mHighestAckedSeq >= (MaxPacketWindowSize - 2)) return true; if(isAdaptive()) return mLastSendSeq - mHighestAckedSeq >= cwnd; return false; } NetError NetConnection::sendPacket(BitStream *stream) { if(mSimulatedPacketLoss && Random::readF() < mSimulatedPacketLoss) { TNLLogMessageV(LogNetConnection, ("NetConnection %s: SENDDROP - %d", mNetAddress.toString(), getLastSendSequence())); return NoError; } TNLLogMessageV(LogNetConnection, ("NetConnection %s: SEND - %d bytes", mNetAddress.toString(), stream->getBytePosition())); // do nothing on send if this is a demo replay. if(isLocalConnection()) { // short circuit connection to the other side. // handle the packet, then force a notify. U32 size = stream->getBytePosition(); stream->reset(); stream->setMaxSizes(size, 0); mRemoteConnection->readRawPacket(stream); return NoError; } else { if(mSimulatedLatency) { mInterface->sendtoDelayed(getNetAddress(), stream, mSimulatedLatency); return NoError; } else return mInterface->sendto(getNetAddress(), stream); } } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // these are the virtual function defs for Connection - // if your subclass has additional data to read / write / notify, add it in these functions. void NetConnection::readPacket(BitStream *bstream) { } void NetConnection::prepareWritePacket() { } void NetConnection::writePacket(BitStream *bstream, PacketNotify *note) { } void NetConnection::packetReceived(PacketNotify *note) { if(mStringTable) mStringTable->packetReceived(&note->stringList); } void NetConnection::packetDropped(PacketNotify *note) { if(mStringTable) mStringTable->packetDropped(&note->stringList); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- void NetConnection::setTranslatesStrings() { if(!mStringTable) mStringTable = new ConnectionStringTable(this); } void NetConnection::setInterface(NetInterface *myInterface) { mInterface = myInterface; } NetInterface *NetConnection::getInterface() { return mInterface; } void NetConnection::setSymmetricCipher(SymmetricCipher *theCipher) { mSymmetricCipher = theCipher; } void NetConnection::connect(NetInterface *theInterface, const Address &address, bool requestKeyExchange, bool requestCertificate) { mConnectionParameters.mRequestKeyExchange = requestKeyExchange; mConnectionParameters.mRequestCertificate = requestCertificate; mConnectionParameters.mIsInitiator = true; setNetAddress(address); setInterface(theInterface); mInterface->startConnection(this); } void NetConnection::connectArranged(NetInterface *connectionInterface, const Vector<Address> &possibleAddresses, Nonce &nonce, Nonce &serverNonce, ByteBufferPtr sharedSecret, bool isInitiator, bool requestsKeyExchange, bool requestsCertificate) { mConnectionParameters.mRequestKeyExchange = requestsKeyExchange; mConnectionParameters.mRequestCertificate = requestsCertificate; mConnectionParameters.mPossibleAddresses = possibleAddresses; mConnectionParameters.mIsInitiator = isInitiator; mConnectionParameters.mIsArranged = true; mConnectionParameters.mNonce = nonce; mConnectionParameters.mServerNonce = serverNonce; mConnectionParameters.mArrangedSecret = sharedSecret; mConnectionParameters.mArrangedSecret->takeOwnership(); setInterface(connectionInterface); mInterface->startArrangedConnection(this); } void NetConnection::disconnect(const char *reason) { mInterface->disconnect(this, ReasonSelfDisconnect, reason); } void NetConnection::onConnectionEstablished() { if(isInitiator()) setIsConnectionToServer(); else setIsConnectionToClient(); } void NetConnection::onConnectionTerminated(TerminationReason, const char *) { } void NetConnection::onConnectTerminated(TerminationReason, const char *) { } void NetConnection::writeConnectRequest(BitStream *stream) { stream->write(U32(getNetClassGroup())); stream->write(U32(NetClassRep::getClassGroupCRC(getNetClassGroup()))); } bool NetConnection::readConnectRequest(BitStream *stream, const char **errorString) { U32 classGroup, classCRC; stream->read(&classGroup); stream->read(&classCRC); if(classGroup == getNetClassGroup() && classCRC == NetClassRep::getClassGroupCRC(getNetClassGroup())) return true; *errorString = "CHR_INVALID"; return false; } void NetConnection::writeConnectAccept(BitStream *stream) { stream; } bool NetConnection::readConnectAccept(BitStream *stream, const char **errorString) { stream; errorString; return true; } bool NetConnection::connectLocal(NetInterface *connectionInterface, NetInterface *serverInterface) { Object *co = Object::create(getClassName()); NetConnection *client = this; NetConnection *server = dynamic_cast<NetConnection *>(co); const char *error = NULL; PacketStream stream; if(!server) goto errorOut; client->setInterface(connectionInterface); client->getConnectionParameters().mIsInitiator = true; client->getConnectionParameters().mIsLocal = true; server->getConnectionParameters().mIsLocal = true; server->setInterface(serverInterface); server->setInitialRecvSequence(client->getInitialSendSequence()); client->setInitialRecvSequence(server->getInitialSendSequence()); client->setRemoteConnectionObject(server); server->setRemoteConnectionObject(client); stream.setBytePosition(0); client->writeConnectRequest(&stream); stream.setBytePosition(0); if(!server->readConnectRequest(&stream, &error)) goto errorOut; stream.setBytePosition(0); server->writeConnectAccept(&stream); stream.setBytePosition(0); if(!client->readConnectAccept(&stream, &error)) goto errorOut; client->setConnectionState(NetConnection::Connected); server->setConnectionState(NetConnection::Connected); client->onConnectionEstablished(); server->onConnectionEstablished(); connectionInterface->addConnection(client); serverInterface->addConnection(server); return true; errorOut: delete server; return false; } }; <file_sep>using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace WindowsApplication { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public void CreateVTWindow(IntPtr win) { vtWin = new vtWindow(); SWIGTYPE_p_long l = new SWIGTYPE_p_long(win, true); vtWin.CreateAsChild(l); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); if (vtWin != null) { vtWin.Terminate(0); } } //private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button sendmessage; private runme.vtPanel panel1; //some temp test values for messaging : private int m_intMTest = 0; private float m_floatMTest = 0; private String m_strMTest = ""; public int startWidth = 400; public int startHeight = 300; private System.Windows.Forms.Button sendMsgFloat; private System.Windows.Forms.Button sendMsgStr; public System.Windows.Forms.RichTextBox richTextBox1; private System.Windows.Forms.Button CheckVirtoolsMsgBtn; private System.Windows.Forms.Button Resize; private System.Windows.Forms.Button PauseBtn; private System.Windows.Forms.Button PlayBtn; public vtWindow vtWin = null; public vtWindow VtWin { get { return vtWin; } set { vtWin = value; } } public Form1() { InitializeComponent(); this.SuspendLayout(); //we init our player, be aware about "OwnerDrawed" entry in the player.ini! //you must set this to 1, otherwise its not correct displayed in this form ! CreateVTWindow(panel1.Handle); panel1.Init(this, vtWin); //we retrieve the players render bounds : int playerWidth = vtWin.GetWidth(); int playerHeight = vtWin.GetHeight(); // and we re-adjust our panel ! //this.panel1.Size = new System.Drawing.Size(playerWidth, playerHeight); vtWin.Run(); //System.Threading.Thread.Sleep(100); vtWin.UpdateRenderSize(playerWidth, playerHeight); this.PerformLayout(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.panel1 = new runme.vtPanel(); this.sendmessage = new System.Windows.Forms.Button(); this.sendMsgFloat = new System.Windows.Forms.Button(); this.sendMsgStr = new System.Windows.Forms.Button(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.CheckVirtoolsMsgBtn = new System.Windows.Forms.Button(); this.Resize = new System.Windows.Forms.Button(); this.PauseBtn = new System.Windows.Forms.Button(); this.PlayBtn = new System.Windows.Forms.Button(); this.SuspendLayout(); // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.panel1.Location = new System.Drawing.Point(344, 8); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(400, 300); this.panel1.TabIndex = 0; // // sendmessage // this.sendmessage.Location = new System.Drawing.Point(8, 8); this.sendmessage.Name = "sendmessage"; this.sendmessage.Size = new System.Drawing.Size(96, 24); this.sendmessage.TabIndex = 1; this.sendmessage.Text = "sendmessageInt"; this.sendmessage.Click += new System.EventHandler(this.sendmessage_Click); // // sendMsgFloat // this.sendMsgFloat.Location = new System.Drawing.Point(8, 40); this.sendMsgFloat.Name = "sendMsgFloat"; this.sendMsgFloat.Size = new System.Drawing.Size(96, 24); this.sendMsgFloat.TabIndex = 2; this.sendMsgFloat.Text = "sendMsgFloat"; this.sendMsgFloat.Click += new System.EventHandler(this.sendMsgFloat_Click); // // sendMsgStr // this.sendMsgStr.Location = new System.Drawing.Point(8, 72); this.sendMsgStr.Name = "sendMsgStr"; this.sendMsgStr.Size = new System.Drawing.Size(96, 24); this.sendMsgStr.TabIndex = 3; this.sendMsgStr.Text = "sendMsgStr"; this.sendMsgStr.Click += new System.EventHandler(this.sendMsgStr_Click); // // richTextBox1 // this.richTextBox1.Location = new System.Drawing.Point(8, 144); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.Size = new System.Drawing.Size(320, 160); this.richTextBox1.TabIndex = 4; this.richTextBox1.Text = "playerout"; // // CheckVirtoolsMsgBtn // this.CheckVirtoolsMsgBtn.Location = new System.Drawing.Point(120, 8); this.CheckVirtoolsMsgBtn.Name = "CheckVirtoolsMsgBtn"; this.CheckVirtoolsMsgBtn.Size = new System.Drawing.Size(120, 24); this.CheckVirtoolsMsgBtn.TabIndex = 5; this.CheckVirtoolsMsgBtn.Text = "CheckVirtoolsMsg"; this.CheckVirtoolsMsgBtn.Click += new System.EventHandler(this.button1_Click); // // Resize // this.Resize.Location = new System.Drawing.Point(120, 40); this.Resize.Name = "Resize"; this.Resize.Size = new System.Drawing.Size(120, 24); this.Resize.TabIndex = 6; this.Resize.Text = "Resize"; this.Resize.Click += new System.EventHandler(this.Resize_Click); // // PauseBtn // this.PauseBtn.Location = new System.Drawing.Point(120, 72); this.PauseBtn.Name = "PauseBtn"; this.PauseBtn.Size = new System.Drawing.Size(48, 24); this.PauseBtn.TabIndex = 7; this.PauseBtn.Text = "Pause"; this.PauseBtn.Click += new System.EventHandler(this.PauseBtn_Click); // // PlayBtn // this.PlayBtn.Location = new System.Drawing.Point(176, 72); this.PlayBtn.Name = "PlayBtn"; this.PlayBtn.Size = new System.Drawing.Size(40, 24); this.PlayBtn.TabIndex = 8; this.PlayBtn.Text = "Play"; this.PlayBtn.Click += new System.EventHandler(this.PlayBtn_Click); // // Form1 // this.AutoScale = false; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(768, 325); this.Controls.Add(this.PlayBtn); this.Controls.Add(this.PauseBtn); this.Controls.Add(this.Resize); this.Controls.Add(this.CheckVirtoolsMsgBtn); this.Controls.Add(this.richTextBox1); this.Controls.Add(this.sendMsgStr); this.Controls.Add(this.sendMsgFloat); this.Controls.Add(this.sendmessage); this.Controls.Add(this.panel1); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Form1"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> /// [STAThread] static void Main() { Application.Run(new Form1()); } /* protected override void WndProc(ref Message m) { base.WndProc(ref m); if (vtWin!=null) { SWIGTYPE_p_long win = new SWIGTYPE_p_long(m.HWnd,true); SWIGTYPE_p_long wp = new SWIGTYPE_p_long(m.WParam,true); SWIGTYPE_p_long lp = new SWIGTYPE_p_long(m.LParam ,true); vtWin.WndProc(win,m.Msg,wp,lp); } }*/ private void sendmessage_Click(object sender, System.EventArgs e) { if (vtWin != null) { //we send a message to our player : //when the player could'nt found the object by this name, then it sends //a broadcast message ! String objectName = "masterDummy"; //this message name should exist inside vt ! String messageName = "csharp"; //the function takes 3 reserved parameters. you can do what ever you want with it int id0 = 0; int id1 = 1; int id2 = 2; m_intMTest++; vtWin.SendMessage(objectName, messageName, id0, id1, id2, m_intMTest); //inside vt you only have to attach a MessageWaiter to the object and also //a GetMessageDataBB after the waiter with the appropriate output parameters : // int,int,int,int in this case here ! } } private void sendMsgFloat_Click(object sender, System.EventArgs e) { if (vtWin != null) { //we send a message to our player : //when the player could'nt found the object by this name, then it sends //a broadcast message ! String objectName = "masterDummy"; //this message name should exist inside vt ! String messageName = "csharpFloat"; //the function takes 3 reserved parameters. you can do what ever you want with it int id0 = 0; int id1 = 1; int id2 = 2; m_floatMTest += 0.23f; vtWin.SendMessage(objectName, messageName, id0, id1, id2, m_floatMTest); //inside vt you only have to attach a MessageWaiter to the object and also //a GetMessageDataBB after the waiter with the appropriate output parameters : // int,int,int,int in this case here ! } } private void sendMsgStr_Click(object sender, System.EventArgs e) { if (vtWin != null) { //we send a message to our player : //when the player could'nt found the object by this name, then it sends //a broadcast message ! String objectName = "masterDummy"; //this message name should exist inside vt ! String messageName = "csharpString"; //the function takes 3 reserved parameters. you can do what ever you want with it int id0 = 0; int id1 = 1; int id2 = 2; m_strMTest += "asdasd"; vtWin.SendMessage(objectName, messageName, id0, id1, id2, m_strMTest); //inside vt you only have to attach a MessageWaiter to the object and also //a GetMessageDataBB after the waiter with the appropriate output parameters : // int,int,int,int in this case here ! } } //check vtWin for new messages : private void button1_Click(object sender, System.EventArgs e) { if (vtWin.HasMessages() == 1) { String console = richTextBox1.Text; for (int nbMsg = 0; nbMsg < vtWin.GetNumMessages(); nbMsg++) { console += "\n message recieved : " + nbMsg + " name : " + vtWin.GetMessageName(nbMsg); for (int nbPar = 0; nbPar < vtWin.GetNumParameters(nbMsg); nbPar++) { int parType = vtWin.GetMessageParameterType(nbMsg, nbPar); switch (parType) { //string : case 1: { String value = vtWin.GetMessageValueStr(nbMsg, nbPar); console += "\n\t parameter attached : " + nbPar + " : type : " + vtWin.GetMessageParameterType(nbMsg, nbPar) + " value : " + value; break; } //float : case 2: { float value = vtWin.GetMessageValueFloat(nbMsg, nbPar); console += "\n\t parameter attached : " + nbPar + " : type : " + vtWin.GetMessageParameterType(nbMsg, nbPar) + " value : " + value; break; } //integer : case 3: { int value = vtWin.GetMessageValueInt(nbMsg, nbPar); console += "\n\t parameter attached : " + nbPar + " : type : " + vtWin.GetMessageParameterType(nbMsg, nbPar) + " value : " + value; break; } default: break; } } } //vtWin.DeleteMessage(0); //cleans incoming message by index vtWin.CleanMessages(); // pop everything ! richTextBox1.Text = console; } } private void Resize_Click(object sender, System.EventArgs e) { if (vtWin != null) { vtWin.Pause(); System.Threading.Thread.Sleep(50); this.SuspendLayout(); if (startWidth == 400) { startWidth = 640; startHeight = 480; } else { startWidth = 400; startHeight = 300; } //just a test this.panel1.Size = new System.Drawing.Size(startWidth, startHeight); vtWin.UpdateRenderSize(startWidth, startHeight); System.Threading.Thread.Sleep(2); vtWin.Play(); System.Threading.Thread.Sleep(2); this.PerformLayout(); } } private void PauseBtn_Click(object sender, System.EventArgs e) { if (vtWin != null) { vtWin.Pause(); } } private void PlayBtn_Click(object sender, System.EventArgs e) { if (vtWin != null) { vtWin.Play(); } } } }<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // CameraColorFilter // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorCameraColorFilterDecl(); CKERROR CreateCameraColorFilterProto(CKBehaviorPrototype **pproto); int CameraColorFilter(const CKBehaviorContext& behcontext); void CameraColorFilterRender(CKRenderContext *rc, void *arg); CKObjectDeclaration *FillBehaviorCameraColorFilterDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Camera Color Filter"); od->SetDescription("Adds a color filter to the Camera."); /* rem: <SPAN CLASS=in>On: </SPAN>activates the process.<BR> <SPAN CLASS=in>Off: </SPAN>deactivates the process.<BR> <BR> <SPAN CLASS=out>Exit On: </SPAN>is activated when the building block has been activated by "On".<BR> <SPAN CLASS=out>Exit Off: </SPAN>is activated when the building block has been activated by "Off".<BR> <BR> <SPAN CLASS=pin>Filter Color: </SPAN>color of the filter in RGBA.<BR> <SPAN CLASS=pin>Density: </SPAN>how dense the filter should be, in percent.<BR> <SPAN CLASS=pin>Hard Light: </SPAN>if FALSE, the filter color is added to the colors of the scene. If TRUE, the filter color is combined with the colors of the scene (resulting in greater opacity).<BR> <BR> This building block is useful to simulate infrared glasses or fade in/fade out effects.<BR> This building block does not need to be looped.<BR> */ od->SetCategory("Cameras/FX"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x00cd010b, 0x00dd010b)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateCameraColorFilterProto); od->SetCompatibleClassId(CKCID_CAMERA); return od; } CKERROR CreateCameraColorFilterProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Camera Color Filter"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareInput("Off"); proto->DeclareOutput("Exit On"); proto->DeclareOutput("Exit Off"); proto->DeclareInParameter("Filter Color", CKPGUID_COLOR,"255,0,0,0"); proto->DeclareInParameter("Density", CKPGUID_PERCENTAGE, "20" ); proto->DeclareInParameter("Hard Light", CKPGUID_BOOL,"FALSE" ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(CameraColorFilter); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int CameraColorFilter(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if(!beh) return CKBR_BEHAVIORERROR; if( beh->IsInputActive(1) ){ // we enter by 'OFF' beh->ActivateInput(1, FALSE); beh->ActivateOutput(1); return CKBR_OK; } if( beh->IsInputActive(0) ){ // we enter by 'ON' beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); } behcontext.CurrentRenderContext->AddPostRenderCallBack(CameraColorFilterRender,(void *)beh->GetID(),TRUE); //behcontext.CurrentRenderContext->AddPostRenderCallBack(CameraColorFilterRender,beh,TRUE); return CKBR_ACTIVATENEXTFRAME; } void CameraColorFilterRender(CKRenderContext *rc, void *arg){ CKBehavior* beh = (CKBehavior*)CKGetObject(rc->GetCKContext(),(CK_ID)arg); if (!beh) return; // CKBehavior* beh = (CKBehavior*)arg; if(rc->GetAttachedCamera() != beh->GetTarget()) return; // we get the input parameters VxColor fcolor(255,0,0,0); beh->GetInputParameterValue(0,&fcolor); // we get the density of the atmosphere float density = 20.0f; beh->GetInputParameterValue(1,&density); // we change the material according to the bool BOOL hardl = FALSE; beh->GetInputParameterValue(2,&hardl); if(hardl) { rc->SetState(VXRENDERSTATE_SRCBLEND, VXBLEND_SRCALPHA); rc->SetState(VXRENDERSTATE_DESTBLEND, VXBLEND_INVSRCALPHA); fcolor.a = density; } else { rc->SetState(VXRENDERSTATE_SRCBLEND, VXBLEND_ONE); rc->SetState(VXRENDERSTATE_DESTBLEND, VXBLEND_ONE); fcolor *= density; fcolor.a = 1.0f; } // SET STATES // we don't let write to the ZBuffer rc->SetTexture(NULL); rc->SetState(VXRENDERSTATE_CULLMODE, VXCULL_NONE); rc->SetState(VXRENDERSTATE_ALPHABLENDENABLE, TRUE); rc->SetState(VXRENDERSTATE_ZENABLE , FALSE); rc->SetState(VXRENDERSTATE_ZWRITEENABLE , FALSE); rc->SetState(VXRENDERSTATE_FILLMODE,VXFILL_SOLID); VxDrawPrimitiveData* data = rc->GetDrawPrimitiveStructure(CKRST_DP_VCT,4); // Positions VxRect rect; rc->GetViewRect(rect); data->Positions[0].Set(rect.left,rect.top,0.0f,1.0f); data->Positions[1].Set(rect.right,rect.top,0.0f,1.0f); data->Positions[2].Set(rect.right,rect.bottom,0.0f,1.0f); data->Positions[3].Set(rect.left,rect.bottom,0.0f,1.0f); // colors DWORD col = RGBAFTOCOLOR(&fcolor); VxFillStructure(4,data->Colors,4,&col); // indices CKWORD* indices = rc->GetDrawPrimitiveIndices(4); indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 3; rc->DrawPrimitive(VX_TRIANGLEFAN, indices, 4,data); // we let write to the ZBuffer rc->SetState(VXRENDERSTATE_ZWRITEENABLE , TRUE); rc->SetState(VXRENDERSTATE_ZENABLE , TRUE); } <file_sep>#ifndef __P_MISC_H__ #define __P_MISC_H__ #include "vtPhysXBase.h" namespace vtAgeia { VxVector BoxGetZero(CK3dEntity* ent); void SetEulerDirection(CK3dEntity* ent,VxVector direction); XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide,int parameterSubIndex); XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide); int getEnumIndex(CKParameterManager* pm,CKGUID parGuide,XString enumValue); int getHullTypeFromShape(NxShape *shape); CKGUID getEnumGuid(XString name); int getNbOfPhysicObjects(CK3dEntity *parentObject,int flags=0); bool calculateOffsets(CK3dEntity*source,CK3dEntity*target,VxQuaternion &quat,VxVector& pos); bool isChildOf(CK3dEntity*parent,CK3dEntity*test); CK3dEntity* findSimilarInSourceObject(CK3dEntity *parentOriginal,CK3dEntity* partentCopied,CK3dEntity *copiedObject,CK3dEntity*prev=NULL); CK3dEntity *getEntityFromShape(NxShape* shape); } #endif <file_sep>#ifndef SOFT_VERTEX_H #define SOFT_VERTEX_H namespace SOFTBODY { enum SoftVertexType { SVT_TETRA_VERTEX, SVT_TETRA_POSITION_VERTEX, SVT_TETRA_DEFORM_VERTEX, SVT_TETRA_GRAPHICS_VERTEX, }; class SoftVertexPool; SoftVertexPool *createSoftVertexPool(SoftVertexType type); bool releaseSoftVertexPool(SoftVertexPool *vpool); unsigned int getSoftVertexIndex(SoftVertexPool *vpool,const void *vertex); void * getSoftVertexPoolBuffer(SoftVertexPool *vpool,unsigned int &vcount); }; // END OF SOFTBODY NAMESPACE #endif <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPClothDominateVertexDecl(); CKERROR CreatePClothDominateVertexProto(CKBehaviorPrototype **pproto); int PClothDominateVertex(const CKBehaviorContext& behcontext); CKERROR PClothDominateVertexCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_VertexIndex, bbI_expireTime, bbI_domWeight, }; //************************************ // Method: FillBehaviorPClothDominateVertexDecl // FullName: FillBehaviorPClothDominateVertexDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPClothDominateVertexDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothDominateVertex"); od->SetCategory("Physic/Cloth"); od->SetDescription("Changes the weight of a vertex in the cloth solver for a period of time."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x92979b9,0x4ced0f82)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePClothDominateVertexProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePClothDominateVertexProto // FullName: CreatePClothDominateVertexProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePClothDominateVertexProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothDominateVertex"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PClothDominateVertex PClothDominateVertex is categorized in \ref Clothes <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Changes the weight of a vertex in the cloth solver for a period of time.<br> If this method is called for some vertex, the cloth solver will, during a time period of length expirationTime, assign a different weight to the vertex while internal cloth constraints (i.e. bending & stretching) are being resolved. With a high dominanceWeight, the modified vertex will force neighboring vertices to strongly accommodate their positions while its own is kept fairly constant. The reverse holds for smaller dominanceWeights. Using a dominanceWeight of +infinity has a similar effect as temporarily attaching the vertex to a global position. However, unlike using attachments, the velocity of the vertex is kept intact when using this method. \note The current implementation will not support the full range of dominanceWeights. All dominanceWeights > 0.0 are treated equally as being +infinity. \note An expiration time of 0.0 is legal and will result in dominance being applied throughout one substep before being discarded immediately. \note Having a large number of vertices dominant at once may result in a performance penalty. @see pCloth::dominateVertex() <h3>Technical Information</h3> \image html PClothDominateVertex.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>Target cloth reference. <BR> <BR> <SPAN CLASS="pin">Vertex Index: </SPAN>Index of the vertex. <BR> <SPAN CLASS="pin">Expiration Time: </SPAN>Time period where dominance will be active for this vertex. <BR> <BR> <SPAN CLASS="pin">Dominance Weight: </SPAN>Dominance weight for this vertex. <BR> <BR> */ proto->SetBehaviorCallbackFct( PClothDominateVertexCB ); proto->DeclareInParameter("Vertex Index",CKPGUID_INT); proto->DeclareInParameter("Expiration Time",CKPGUID_FLOAT); proto->DeclareInParameter("Dominance Weight",CKPGUID_FLOAT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PClothDominateVertex); *pproto = proto; return CK_OK; } //************************************ // Method: PClothDominateVertex // FullName: PClothDominateVertex // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PClothDominateVertex(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// pWorld *world = GetPMan()->getDefaultWorld(); if (!world) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pCloth *cloth = world->getCloth(target); if (!cloth) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } int vertexIndex = GetInputParameterValue<int>(beh,bbI_VertexIndex); float expTime = GetInputParameterValue<float>(beh,bbI_expireTime); float domWeight = GetInputParameterValue<float>(beh,bbI_domWeight); cloth->dominateVertex(vertexIndex,expTime,domWeight); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PClothDominateVertexCB // FullName: PClothDominateVertexCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PClothDominateVertexCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pWorldSettings.h" #include "NxUserNotify.h" #include "NxUserContactReport.h" #include "pWorldCallbacks.h" struct MyUserNotify : public NxUserNotify { public: virtual bool onJointBreak(NxReal breakingImpulse, NxJoint & brokenJoint) { pJoint *joint = static_cast<pJoint*>(brokenJoint.userData); if (joint) { pBrokenJointEntry *entry = new pBrokenJointEntry(); entry->joint = joint; entry->impulse = breakingImpulse; pWorld *world = joint->getWorld(); if (world) { world->getJointFeedbackList().PushBack(entry); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Joint break!"); } } return false; /*if((&brokenJoint) == gMyBreakableJoint) { cout << "BANG, The joint broke" << endl; return true; //delete the joint } return false; //don't delete the joint */ } virtual void onSleep(NxActor **actors, NxU32 count) { /* NX_ASSERT(count > 0); while (count--) { NxActor *thisActor = *actors; //Tag the actor as sleeping size_t currentFlag = (size_t)thisActor->userData; currentFlag |= gSleepFlag; thisActor->userData = (void*)currentFlag; actors++; }*/ } virtual void onWake(NxActor **actors, NxU32 count) { if (count >0) { while (count--) { NxActor *thisActor = *actors; if (thisActor) { pRigidBody *body = static_cast<pRigidBody*>(thisActor->userData); if (body) { body->getCollisions().Clear(); body->getTriggers().Clear(); } } //Tag the actor as non-sleeping /*size_t currentFlag = (size_t)thisActor->userData; currentFlag &= ~gSleepFlag; thisActor->userData = (void*)currentFlag;*/ actors++; } } } }myNotify; pWorld*pFactory::createWorld(CK3dEntity* referenceObject, pWorldSettings *worldSettings,pSleepingSettings *sleepSettings) { using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// //sanity checks : if (!referenceObject || !GetPMan() ) { return NULL; } if (!getPhysicSDK()) { //xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"No physic sdk loaded"); return NULL; } int worldAtt = GetPMan()->att_world_object; int surfaceAttribute = GetPMan()->att_surface_props; //exists ? Delete it ! pWorld *w = GetPMan()->getWorld(referenceObject->GetID()); if (w) { GetPMan()->deleteWorld(referenceObject->GetID()); } //our new world : pWorld *result = new pWorld(referenceObject); GetPMan()->getWorlds()->InsertUnique(referenceObject,result); result->initUserReports(); ////////////////////////////////////////////////////////////////////////// //there is no world settings attribute : if (!referenceObject->HasAttribute(worldAtt) ) { referenceObject->SetAttribute(worldAtt); using namespace vtTools; VxVector grav = worldSettings->getGravity(); float sWith = worldSettings->getSkinWith(); AttributeTools::SetAttributeValue<VxVector>(referenceObject,worldAtt,0,&grav); AttributeTools::SetAttributeValue<float>(referenceObject,worldAtt,1,&sWith); } if (!worldSettings) { worldSettings = pFactory::Instance()->createWorldSettings(XString("Default"),GetPMan()->getDefaultConfig()); } if (!worldSettings) { worldSettings = new pWorldSettings(); } ////////////////////////////////////////////////////////////////////////// //pSDK Scene creation : // Create a scene NxSceneDesc sceneDesc; sceneDesc.gravity = pMath::getFrom(worldSettings->getGravity()); sceneDesc.upAxis = 1; sceneDesc.flags |=NX_SF_ENABLE_ACTIVETRANSFORMS; sceneDesc.userNotify =&myNotify; sceneDesc.userContactReport = result->contactReport; NxScene *scene = NULL; if (getPhysicSDK()) { scene = getPhysicSDK()->createScene(sceneDesc); if(scene == NULL) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create scene!"); return NULL; } } result->setScene(scene); scene->setUserContactReport(result->contactReport); scene->setUserTriggerReport(result->triggerReport); NxMaterialDesc *materialDescr = NULL; NxMaterial *material = NULL; if (referenceObject->HasAttribute(surfaceAttribute)) { materialDescr = createMaterialFromEntity(referenceObject); material = result->getScene()->createMaterial(*materialDescr); material->userData = (void*)GetValueFromParameterStruct<int>(referenceObject->GetAttributeParameter(surfaceAttribute) ,E_MS_XML_TYPE); }else{ if (getDefaultDocument()) { materialDescr = createMaterialFromXML("Default",getDefaultDocument()); } if (materialDescr) { material = result->getScene()->createMaterial(*materialDescr); } if (!material) { materialDescr = new NxMaterialDesc(); materialDescr->setToDefault(); material = result->getScene()->getMaterialFromIndex(0); material->loadFromDesc(*materialDescr); } } int z = (int)material->userData; NxMaterial *zeroMaterial = result->getScene()->getMaterialFromIndex(0); zeroMaterial->setDirOfAnisotropy(material->getDirOfAnisotropy()); zeroMaterial->setStaticFriction(material->getStaticFriction()); zeroMaterial->setDynamicFriction(material->getDynamicFriction()); zeroMaterial->setStaticFrictionV(material->getStaticFrictionV()); zeroMaterial->setDynamicFrictionV(material->getDynamicFrictionV()); zeroMaterial->setFrictionCombineMode(material->getFrictionCombineMode()); zeroMaterial->setRestitutionCombineMode(material->getRestitutionCombineMode()); zeroMaterial->setFlags(material->getFlags()); zeroMaterial->userData = material->userData; if (!material) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create default material!"); } result->setDefaultMaterial(material); scene->userData = result; //NxConstraintDominance testDom(1.0, 1.0f); //result->getScene()->setDominanceGroupPair(1, 2,testDom ); //board - debris ////////////////////////////////////////////////////////////////////////// //there is no world settings attribute : /* if (!referenceObject->HasAttribute(GetPMan()->att_sleep_settings) ) { referenceObject->SetAttribute(GetPMan()->att_sleep_settings); using namespace vtTools; AttributeTools::SetAttributeValue<int>(referenceObject,GetPMan()->att_sleep_settings,0,&sSettings->m_SleepSteps); AttributeTools::SetAttributeValue<float>(referenceObject,GetPMan()->att_sleep_settings,1,&sSettings->m_AngularThresold); AttributeTools::SetAttributeValue<float>(referenceObject,GetPMan()->att_sleep_settings,2,&sSettings->m_LinearThresold); AttributeTools::SetAttributeValue<int>(referenceObject,GetPMan()->att_sleep_settings,3,&sSettings->m_AutoSleepFlag); } */ /* result->SleepingSettings(sSettings); ////////////////////////////////////////////////////////////////////////// result->Reference(referenceObject); result->Init(); */ result->_checkForDominanceConstraints(); result->_construct(); return result; //return NULL; } //************************************ // Method: CreateDefaultWorld // FullName: vtODE::pFactory::CreateDefaultWorld // Access: public // Returns: pWorld* // Qualifier: // Parameter: XString name //************************************ pWorld*pFactory::createDefaultWorld(XString name) { CK3dEntity *defaultWorldFrame = createFrame("pDefaultWorld"); pWorldSettings *wSettings = getManager()->getDefaultWorldSettings(); pWorld* world = createWorld(defaultWorldFrame,wSettings,NULL); getManager()->setDefaultWorld(world); return world; /* pSleepingSettings *sSettings = CreateSleepingSettings("Default",GetPMan()->DefaultDocument()); pWorldSettings *wSettings = createWorldSettings("Default",GetPMan()->DefaultDocument()); GetPMan()->DefaultSleepingSettings(*sSettings); GetPMan()->DefaultWorldSettings(*wSettings); pWorld* world = CreateWorld(defaultWorldFrame,&GetPMan()->DefaultWorldSettings(),&GetPMan()->DefaultSleepingSettings()); GetPMan()->DefaultWorld(world); */ // return world; return NULL; } <file_sep>/* * Tcp4u v 3.31 Last Revision 06/06/1997 3.1 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: tcp4u_err.c * Purpose: version and error management * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" /* ------------------------------------------------------------------ */ /* Compataibilite avec les anciennes fonctions */ /* ------------------------------------------------------------------ */ #ifdef _WINDOWS int API4U Tcp4wVer (LPSTR sz, UINT uSize) { return Tcp4uVer(sz,uSize); } LPSTR API4U Tcp4wErrorString (int Rc) { return Tcp4uErrorString(Rc); } #endif #ifdef UNIX int API4U Tcp4uxVer(LPSTR sz, UINT uSize) { return Tcp4uVer(sz,uSize); } LPSTR API4U Tcp4uxErrorString (int Rc) { return Tcp4uErrorString(Rc); } #endif /* ------------------------------------------------------------------ */ /* Informations sur la version */ /* ------------------------------------------------------------------ */ static LPCSTR szTcp4uVersion = #ifdef _WINDOWS # ifdef _WIN32 # ifdef TCP4W_DLL "@(#)DLL Tcp4u Win32 by Ph.Jounin Version 3.31"; # else "@(#)Lib Tcp4u Win32 by Ph.Jounin Version 3.31"; # endif /* DLL ? */ # else # ifdef TCP4W_DLL "@(#)DLL Tcp4u Win16 by Ph.Jounin Version 3.31"; # else "@(#)Lib Tcp4u Win16 by Ph.Jounin Version 3.31"; # endif /* DLL ? */ # endif /* WIN32 */ #endif /* _WINDOWS */ #ifdef UNIX "@(#)Tcp4u Unix by Ph.jounin Version 3.31"; #endif /* UNIX */ int nTcp4uVersion = 0x0331; /* ------------------------------------------------------------------ */ /* La fonction les retournant */ /* ------------------------------------------------------------------ */ int API4U Tcp4uVer (LPSTR szInfo, UINT uBufSize) { if (szInfo!=NULL) Strcpyn(szInfo, szTcp4uVersion + 4, uBufSize); return nTcp4uVersion; } /* Tcp4uVer */ /* ------------------------------------------------------ */ /* Fonction: */ /* Retourne un message texte donnant la cause de l'erreur */ /* Note: Certains messages sont specifiques a la version */ /* Windows... Peu importe */ /* ------------------------------------------------------ */ struct S_Tcp4Err { int Tcp4ErrCode; LPSTR Tcp4ErrString; }; /* struct S_Tcp4Err */ static struct S_Tcp4Err sTcp4Err [] = { { TCP4U_SUCCESS, (LPSTR) "Successful call" }, { TCP4U_ERROR, (LPSTR) "Network error" }, { TCP4U_TIMEOUT, (LPSTR) "Timeout in recv or accept" }, { TCP4U_HOSTUNKNOWN, (LPSTR) "Reference to Unknown host" }, { TCP4U_NOMORESOCKET, (LPSTR) "All sockets has been used up" }, { TCP4U_NOMORERESOURCE, (LPSTR) "No more free resource" }, { TCP4U_CONNECTFAILED, (LPSTR) "Connect function has failed" }, { TCP4U_UNMATCHEDLENGTH, (LPSTR) "TcpPPRecv : Error in length" }, { TCP4U_BINDERROR, (LPSTR) "Bind failed (Task already started or attempt to open privileged socket )" }, { TCP4U_OVERFLOW, (LPSTR) "Overflow during TcpPPRecv/TcpRecvUntilStr"}, { TCP4U_EMPTYBUFFER, (LPSTR) "TcpPPRecv receives 0 byte" }, { TCP4U_CANCELLED, (LPSTR) "Call cancelled by signal or TcpAbort" }, { TCP4U_INSMEMORY, (LPSTR) "Not enough memory to perform function" }, { TCP4U_BADPORT, (LPSTR) "Bad port number or alias" }, { TCP4U_SOCKETCLOSED, (LPSTR) "Host has closed connection" }, { TCP4U_FILE_ERROR, (LPSTR) "A file operation has failed" }, }; /* sTcp4Err */ LPSTR API4U Tcp4uErrorString (int Rc) { int Idx; Tcp4uLog (LOG4U_PROC, "Tcp4uErrorString"); for ( Idx=0 ; Idx<SizeOfTab(sTcp4Err) && sTcp4Err[Idx].Tcp4ErrCode!=Rc; Idx++ ); Tcp4uLog (LOG4U_EXIT, "Tcp4uErrorString"); return Idx>= SizeOfTab(sTcp4Err) ? (LPSTR) "Not an Tcp4 return code" : sTcp4Err[Idx].Tcp4ErrString; } /* Tcp4(w/ux)ErrorString */ <file_sep>#ifndef __PWORLDCALLBACKS_H__ #define __PWORLDCALLBACKS_H__ #include "vtPhysXAll.h" class pRayCastReport : public NxUserRaycastReport { public: bool onHit(const NxRaycastHit& hit); pWorld *mWorld; pWorld * getWorld() const { return mWorld; } void setWorld(pWorld * val) { mWorld = val; } int mCurrentBehavior; int getCurrentBehavior() const { return mCurrentBehavior; } void setCurrentBehavior(int val) { mCurrentBehavior = val; } pRayCastReport() { mWorld = NULL; mCurrentBehavior=-1; } } ; class pContactReport : public NxUserContactReport { public: virtual void onContactNotify(NxContactPair& pair, NxU32 events); pWorld *mWorld; pWorld * getWorld() const { return mWorld; } void setWorld(pWorld * val) { mWorld = val; } } ; class pContactModify : public NxUserContactModify { public: virtual bool onContactConstraint( NxU32& changeFlags, const NxShape* shape0, const NxShape* shape1, const NxU32 featureIndex0, const NxU32 featureIndex1, NxContactCallbackData& data); pWorld *mWorld; pWorld * getWorld() const { return mWorld; } void setWorld(pWorld * val) { mWorld = val; } } ; class pTriggerReport : public NxUserTriggerReport { public: void onTrigger(NxShape& triggerShape, NxShape& otherShape, NxTriggerFlag status); pWorld *mWorld; pWorld * getWorld() const { return mWorld; } void setWorld(pWorld * val) { mWorld = val; } }; #endif // __PWORLDCALLBACKS_H__<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SetClipping Camera // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorSetClippingDecl(); CKERROR CreateSetClippingProto(CKBehaviorPrototype **pproto); int SetClipping(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSetClippingDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Set Clipping Planes"); od->SetDescription("Sets the near and the far clipping plane of a camera."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Near Clip: </SPAN>the distance from the point of view of the Near clipping plane.<BR> <SPAN CLASS=pin>Far Clip: </SPAN>the distance from the point of view of the Far clipping plane.<BR> <BR> Reducing the <SPAN CLASS=pin>Far Clip</SPAN> will speed up rendering, as objects which are too far away and so non-visible will be removed from rendering process. A fog background can be added so that objects on the perimeter edge will not be clipped.<BR> Reducing the <SPAN CLASS=pin>Near Clip</SPAN> will avoid clipping objects that are too close from being clipped if the camera gets too close to an object resulting in the object clipping.<BR> Increasing the <SPAN CLASS=pin>Near Clip</SPAN> and reducing the <SPAN CLASS=pin>Far Clip</SPAN> will help to correct Z-Buffer inaccuracy in 3d scenes modeled with objects that are too large.<BR> */ od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x652316a2, 0x01aa09a9)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetClippingProto); od->SetCompatibleClassId(CKCID_CAMERA); od->SetCategory("Cameras/Basic"); return od; } CKERROR CreateSetClippingProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set Clipping Planes"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Near Clip", CKPGUID_FLOAT, "0.1"); proto->DeclareInParameter("Far Clip", CKPGUID_FLOAT, "200"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetClipping); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int SetClipping(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKCamera *cam = (CKCamera *) beh->GetTarget(); if( !cam ) return CKBR_OWNERERROR; float near_plane = 0.1f; beh->GetInputParameterValue(0, &near_plane); float far_plane = 200.0f; beh->GetInputParameterValue(1, &far_plane); cam->SetFrontPlane( near_plane ); cam->SetBackPlane( far_plane ); beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); return CKBR_OK; } <file_sep> using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace WindowsApplication { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public void CreateVTWindow(IntPtr win) { vtWin = new vtWindow(); SWIGTYPE_p_long l = new SWIGTYPE_p_long(win,true); vtWin.CreateAsChild(l); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing (e); if (vtWin!=null) { vtWin.Destroy(); } } private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button sendmessage; //some temp test values for messaging : private int m_intMTest=0; private float m_floatMTest=0; private String m_strMTest=""; private System.Windows.Forms.Button sendMsgFloat; private System.Windows.Forms.Button sendMsgStr; public vtWindow vtWin = null; public vtWindow VtWin { get { return vtWin; } set { vtWin = value; } } public Form1() { InitializeComponent(); this.SuspendLayout(); //we init our player, be aware about "OwnerDrawed" entry in the player.ini! //you must set this to 1, otherwise its not correct displayed in this form ! CreateVTWindow(panel1.Handle); //we retrieve the players render bounds : int playerWidth = vtWin.GetWidth(); int playerHeight = vtWin.GetHeight(); // and we re-adjust our panel ! this.panel1.Size = new System.Drawing.Size(playerWidth, playerHeight); this.panel1.Size=new System.Drawing.Size(playerWidth, playerHeight); vtWin.UpdateRenderSize(playerWidth, playerHeight); //and go ! vtWin.Run(); //vtWin.Show(1); this.PerformLayout(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.sendmessage = new System.Windows.Forms.Button(); this.sendMsgFloat = new System.Windows.Forms.Button(); this.sendMsgStr = new System.Windows.Forms.Button(); this.SuspendLayout(); // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Location = new System.Drawing.Point(120, 16); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(328, 232); this.panel1.TabIndex = 0; // // sendmessage // this.sendmessage.Location = new System.Drawing.Point(8, 8); this.sendmessage.Name = "sendmessage"; this.sendmessage.Size = new System.Drawing.Size(96, 24); this.sendmessage.TabIndex = 1; this.sendmessage.Text = "sendmessageInt"; this.sendmessage.Click += new System.EventHandler(this.sendmessage_Click); // // sendMsgFloat // this.sendMsgFloat.Location = new System.Drawing.Point(8, 40); this.sendMsgFloat.Name = "sendMsgFloat"; this.sendMsgFloat.Size = new System.Drawing.Size(96, 24); this.sendMsgFloat.TabIndex = 2; this.sendMsgFloat.Text = "sendMsgFloat"; this.sendMsgFloat.Click += new System.EventHandler(this.sendMsgFloat_Click); // // sendMsgStr // this.sendMsgStr.Location = new System.Drawing.Point(8, 72); this.sendMsgStr.Name = "sendMsgStr"; this.sendMsgStr.Size = new System.Drawing.Size(96, 24); this.sendMsgStr.TabIndex = 3; this.sendMsgStr.Text = "sendMsgStr"; this.sendMsgStr.Click += new System.EventHandler(this.sendMsgStr_Click); // // Form1 // //this.AutoScale = false; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(888, 645); this.Controls.Add(this.sendMsgStr); this.Controls.Add(this.sendMsgFloat); this.Controls.Add(this.sendmessage); this.Controls.Add(this.panel1); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Form1"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> /// [STAThread] static void Main() { Application.Run(new Form1()); } private void sendmessage_Click(object sender, System.EventArgs e) { if (vtWin!=null) { //we send a message to our player : //when the player could'nt found the object by this name, then it sends //a broadcast message ! String objectName = "masterDummy"; //this message name should exist inside vt ! String messageName = "csharp"; //the function takes 3 reserved parameters. you can do what ever you want with it int id0 =0; int id1 = 1; int id2 = 2; m_intMTest++; vtWin.SendMessage(objectName,messageName,id0,id1,id2,m_intMTest); //just a test this.panel1.Size=new System.Drawing.Size(400, 300); vtWin.UpdateRenderSize(400,300); //inside vt you only have to attach a MessageWaiter to the object and also //a GetMessageDataBB after the waiter with the appropriate output parameters : // int,int,int,int in this case here ! } } private void sendMsgFloat_Click(object sender, System.EventArgs e) { if (vtWin!=null) { //we send a message to our player : //when the player could'nt found the object by this name, then it sends //a broadcast message ! String objectName = "masterDummy"; //this message name should exist inside vt ! String messageName = "csharpFloat"; //the function takes 3 reserved parameters. you can do what ever you want with it int id0 =0; int id1 = 1; int id2 = 2; m_floatMTest+=0.23f; vtWin.SendMessage(objectName,messageName,id0,id1,id2,m_floatMTest); //inside vt you only have to attach a MessageWaiter to the object and also //a GetMessageDataBB after the waiter with the appropriate output parameters : // int,int,int,int in this case here ! } } private void sendMsgStr_Click(object sender, System.EventArgs e) { if (vtWin!=null) { //we send a message to our player : //when the player could'nt found the object by this name, then it sends //a broadcast message ! String objectName = "masterDummy"; //this message name should exist inside vt ! String messageName = "csharpString"; //the function takes 3 reserved parameters. you can do what ever you want with it int id0 =0; int id1 = 1; int id2 = 2; m_strMTest+="asdasd"; vtWin.SendMessage(objectName,messageName,id0,id1,id2,m_strMTest); //inside vt you only have to attach a MessageWaiter to the object and also //a GetMessageDataBB after the waiter with the appropriate output parameters : // int,int,int,int in this case here ! } } } }<file_sep>#include "xNetObject.h" #include <xNetInterface.h> #include "vtConnection.h" /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xNetObject::xNetObject() { mNetFlags.set(Ghostable); setNetInterface(NULL); mOwnerConnection = NULL; } void xNetObject::Destroy() { setNetInterface(NULL); SetName(""); } xNetObject::~xNetObject() { Destroy(); /* xDistributedObject *distObject = static_cast<xDistributedObject *>(this); if(distObject) { if (GetNetInterface()) { vtDistributedObjectsArrayType *distObjects = GetNetInterface()->getDistributedObjects(); if (distObjects) { distObjects->Remove((xDistributedObject*)this); //retrieve its class : distObject->SetNetInterface(NULL); distObject->SetName(""); } } }*/ } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xNetObject::xNetObject(TNL::StringPtr name) : m_Name(name) { mNetFlags.set(Ghostable); m_NetInterface = NULL; m_UserID = 0; mOwnerConnection = NULL; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #define PARAM_OP_TYPE_BGET_VELOCITY CKGUID(0x3b2a778c,0x293b206d) #define PARAM_OP_TYPE_BGET_AVELOCITY CKGUID(0x67ee7c4e,0x1e3b4d15) #define PARAM_OP_TYPE_BGET_TORQUE CKGUID(0x1ecd7ee4,0x4f0b7eda) #define PARAM_OP_TYPE_BGET_FORCE CKGUID(0x7dd13e61,0x40af4f99) #define PARAM_OP_TYPE_BGET_FRICTION CKGUID(0x482b3611,0x4b0a168c) #define PARAM_OP_TYPE_BGET_HTYPE CKGUID(0x68eb059e,0x26bb745a) #define PARAM_OP_TYPE_BGET_FIXED CKGUID(0x7bcd7379,0x5c950897) #define PARAM_OP_TYPE_BGET_KINEMATIC CKGUID(0x6cf414e6,0xf0a35ec) #define PARAM_OP_TYPE_BGET_GRAVITY CKGUID(0x63f81d10,0xd532a5a) #define PARAM_OP_TYPE_BGET_COLLISION CKGUID(0x57f61ee3,0xef1252a) #define PARAM_OP_TYPE_BGET_COLLISION_GROUP CKGUID(0xeea6d63,0x2d8a032d) #define PARAM_OP_TYPE_BGET_SLEEPING CKGUID(0x7ca42afe,0x2665435) #define PARAM_OP_TYPE_BIS_SUB_SHAPE_OF CKGUID(0x7ed952ce,0x5160083) #define PARAM_OP_TYPE_BGET_FLAGS CKGUID(0x19263740,0x5dd248a2) #define PARAM_OP_TYPE_BGET_MATERIAL CKGUID(0x1306375d,0x2bcc3cab) #define PARAM_OP_TYPE_BGET_ISPOBJECT CKGUID(0xa0d7467,0x76692667) #define PARAM_OP_TYPE_BGET_PVEL CKGUID(0x46bc47fc,0x1a4e6a83) #define PARAM_OP_TYPE_BGET_LPVEL CKGUID(0x1c7e07fa,0x430a084b) #define PARAM_OP_TYPE_BGET_MASS CKGUID(0x257d5234,0x362841d4) #define PARAM_OP_TYPE_BJ_ISCONNECTED CKGUID(0x51db16ef,0xfb772d0) #define PARAM_OP_TYPE_BJ_NBJOINTS CKGUID(0x29e20d6c,0x6ebc03d2) #define PARAM_OP_TYPE_BGET_LDAMP CKGUID(0x532052cd,0x97d4334) #define PARAM_OP_TYPE_BGET_LDAMPT CKGUID(0x7e6623dd,0x3beb16d1) #define PARAM_OP_TYPE_BGET_ADAMP CKGUID(0x6c620e3b,0x4c2344d8) #define PARAM_OP_TYPE_BGET_ADAMPT CKGUID(0x148b07eb,0x563c4ff7) void ParamOpBIsSubShape(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK_ID targetID_Sub; p2->GetValue(&targetID_Sub); int result=0; CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { if (target->isSubShape(static_cast<CK3dEntity*>(context->GetObject(targetID_Sub)))) { result = 1; } } } } res->SetValue(&result); } ////////////////////////////////////////////////////////////////////////// void ParamOpBGetLVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { VxVector vec = target->getLinearVelocity(); res->SetValue(&vec); } } } } void ParamOpBGetAVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { VxVector vec = target->getAngularVelocity(); res->SetValue(&vec); } } } } void ParamOpBGetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { VxVector vec = target->getLinearMomentum(); res->SetValue(&vec); } } } } void ParamOpBGetTorque(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { VxVector vec = target->getAngularMomentum(); res->SetValue(&vec); } } } } void ParamOpBisFixed(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { int value = target->getActor()->isDynamic(); res->SetValue(&value); } } } } void ParamOpBGetHType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { int value = target->getHullType(); res->SetValue(&value); } } } } void ParamOpBisKinematic(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { int value = target->isKinematic(); res->SetValue(&value); } } } } void ParamOpBisCollider(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { int value = target->isCollisionEnabled(ent); res->SetValue(&value); } } } } void ParamOpBisGravity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { int value = target->isAffectedByGravity(); res->SetValue(&value); } } } } void ParamOpBGetCollGroup(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { int value = target->getCollisionsGroup(); res->SetValue(&value); } } } } void ParamOpBIsSleeping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { int value = target->isSleeping(); res->SetValue(&value); } } } } void ParamOpBGetFlags(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { target->recalculateFlags(0); int value = target->getFlags(); res->SetValue(&value); } } } } void ParamOpBIsPObject(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); int result = 0; CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { result = 1; } } } res->SetValue(&result); } void ParamOpBGetPVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { VxVector point; p2->GetValue(&point); VxVector vec = target->getPointVelocity(point); res->SetValue(&vec); } } } } void ParamOpBGetLPVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { VxVector point; p2->GetValue(&point); VxVector vec = target->getLocalPointVelocity(point); res->SetValue(&vec); } } } } void ParamOpBGetMass(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { float vec = target->getMass(); res->SetValue(&vec); } } } } void ParamOpBJIsConnected(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK_ID targetIDB; p2->GetValue(&targetIDB); int result = - 1; CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); CK3dEntity *entB = static_cast<CK3dEntity*>(context->GetObject(targetIDB)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { pJoint *joint = target->isConnected(entB); if (joint) { result = joint->getType(); } } } } res->SetValue(&result); } void ParamOpBGetMaterial(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); CK_ID targetID2; p2->GetValue(&targetID2); CK3dEntity *ent2 = static_cast<CK3dEntity*>(context->GetObject(targetID2)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { pMaterial mat = target->getShapeMaterial(ent2); pFactory::Instance()->copyTo(res,mat); } } } } void ParamOpBGetNbJoints(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) { CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CK_ID targetID; p1->GetValue(&targetID); CK3dEntity *ent = static_cast<CK3dEntity*>(context->GetObject(targetID)); if (ent) { pWorld *world=GetPMan()->getWorldByBody(ent); if (world) { pRigidBody*target= world->getBody(ent); if (target) { int nbJoints = target->getNbJoints(); res->SetValue(&nbJoints); } } } } void PhysicManager::_RegisterParameterOperationsBody() { CKParameterManager *pm = m_Context->GetParameterManager(); pm->RegisterOperationType(PARAM_OP_TYPE_BJ_NBJOINTS, "bNbJoints"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BJ_NBJOINTS,CKPGUID_INT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetNbJoints); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_MATERIAL, "bMat"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_MATERIAL,VTS_MATERIAL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBGetMaterial); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_VELOCITY, "bVel"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_VELOCITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetLVelocity); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_AVELOCITY, "bAVel"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_AVELOCITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetAVelocity); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FORCE, "bForce"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FORCE,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetForce); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_TORQUE, "bTorque"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_TORQUE,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetTorque); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_HTYPE, "bHullType"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_HTYPE,VTE_COLLIDER_TYPE,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetHType); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FIXED, "bDynamic"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FIXED,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisFixed); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_KINEMATIC, "bKinematic"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_KINEMATIC,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisKinematic); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_GRAVITY, "bGravity"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_GRAVITY,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisGravity); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_COLLISION, "bCollider"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_COLLISION,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisCollider); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_COLLISION_GROUP, "bCollGroup"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_COLLISION_GROUP,CKPGUID_INT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetCollGroup); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_SLEEPING, "bSleeping"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_SLEEPING,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBIsSleeping); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FLAGS, "bFlags"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FLAGS,VTF_BODY_FLAGS,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetFlags); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_ISPOBJECT, "bRegistered"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_ISPOBJECT,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBIsPObject); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_PVEL, "bPointVel"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_PVEL,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_VECTOR,ParamOpBGetPVel); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_LPVEL, "bLPointVel"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_LPVEL,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_VECTOR,ParamOpBGetLPVel); pm->RegisterOperationType(PARAM_OP_TYPE_BGET_MASS, "bMass"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_MASS,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetMass); pm->RegisterOperationType(PARAM_OP_TYPE_BJ_ISCONNECTED, "bConnected"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BJ_ISCONNECTED,VTE_JOINT_TYPE,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBJIsConnected); pm->RegisterOperationType(PARAM_OP_TYPE_BIS_SUB_SHAPE_OF, "IsSubShape"); pm->RegisterOperationFunction(PARAM_OP_TYPE_BIS_SUB_SHAPE_OF,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBIsSubShape); } <file_sep>#include <StdAfx.h> #ifdef _DOC_ONLY_ #pragma message ("doc images only--------------------------------------------------------------------- ") #endif #ifdef DEMO_ONLY #pragma message ("demo only--------------------------------------------------------------------------- ") #endif #ifdef MODULE_BASE_EXPORTS #pragma message ("export dll---------------------------------------------------------------------------- ") #endif #ifdef DONGLE_VERSION #pragma message ("dongle ------------------------------------------------------------------------------ ") #endif <file_sep>#ifndef _pch_h_ #define _pch_h_ #ifndef SAFE_DELETE #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define VC_LEANMEAN #endif #if defined(_MSC_VER) && (_MSC_VER <= 1200) # pragma warning(disable : 4099) #endif #ifdef USEDIRECTX9 #include <d3d9.h> #include <d3dx9math.h> #include <d3dx9.h> #if defined(DEBUG) || defined(_DEBUG) #ifndef V #define V(x) { hr = x; if( FAILED(hr) ) { DXTrace( __FILE__, (DWORD)__LINE__, hr, #x, true ); } } #endif #ifndef V_RETURN #define V_RETURN(x) { hr = x; if( FAILED(hr) ) { return DXTrace( __FILE__, (DWORD)__LINE__, hr, #x, true ); } } #endif #else #ifndef V #define V(x) { hr = x; } #endif #ifndef V_RETURN #define V_RETURN(x) { hr = x; if( FAILED(hr) ) { return hr; } } #endif #endif #else // #include <d3dx8math.h> #endif #include <WTypes.h> #include <stdlib.h> #include <map> #include <vector> #ifdef VIRTOOLS_USER_SDK #include "CKAll.h" #endif /* #ifdef xGUIForwards #include <xGUI_ForwardsRefs.h> #endif */ /* #ifdef USE_ENIGMA #define ENIGMA_CLIENTSIDE // Set to import headers #include "Enigma/Source/Precompiled.h" #include "Enigma/Source/Enigma.h" #endif */ #ifdef D3D_DEBUG_INFO #ifndef DEBUG_VS // Uncomment this line to debug vertex shaders #define DEBUG_VS // Uncomment this line to debug pixel shaders #endif #ifndef DEBUG_PS // Uncomment this line to debug vertex shaders #define DEBUG_PS // Uncomment this line to debug pixel shaders #endif #ifdef D3D_DEBUG_INFO //const static long TryAtFirst = 0x00000080L; //const static bool ShaderDebugger = true ; #else //const static long TryAtFirst = 0x00000040L; //const static bool ShaderDebugger = false; #endif #endif #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBGet2Decl(); CKERROR CreatePBGet2Proto(CKBehaviorPrototype **pproto); int PBGet2(const CKBehaviorContext& behcontext); CKERROR PBGet2CB(const CKBehaviorContext& behcontext); enum bInputs { bbI_CollisionGroup, bbI_Kinematic, bbI_Gravity, bbI_Collision, bbI_MassOffset, bbI_ShapeOffset, }; //************************************ // Method: FillBehaviorPBGet2Decl // FullName: FillBehaviorPBGet2Decl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPBGet2Decl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBGetEx-Obsolete"); od->SetCategory("Physic/Body"); od->SetDescription("Retrieves physic related parameters."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x234334d3,0x70d06f74)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBGet2Proto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBGet2Proto // FullName: CreatePBGet2Proto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBGet2Proto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBGetEx-Obsolete"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /* PBGetEx PBGet2 is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Retrieves various physical informations.<br> <h3>Technical Information</h3> \image html PBGet2.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pout">Collisions Group: </SPAN>Which collision group this body is part of.See pRigidBody::getCollisionsGroup(). <BR> <SPAN CLASS="pout">Kinematic Object: </SPAN>The kinematic state. See pRigidBody::isKinematic(). <BR> <SPAN CLASS="pout">Gravity: </SPAN>The gravity state.See pRigidBody::isAffectedByGravity(). <BR> <SPAN CLASS="pout">Collision: </SPAN>Determines whether the body reacts to collisions.See pRigidBody::isCollisionEnabled(). <BR> <BR> <SPAN CLASS="setting">Collisions Group: </SPAN>Enables output for collisions group. <BR> <SPAN CLASS="setting">Kinematic Object: </SPAN>Enables output for kinematic object. <BR> <SPAN CLASS="setting">Gravity: </SPAN>Enables output for gravity. <BR> <SPAN CLASS="setting">Collision: </SPAN>Enables output for collision. <BR> <BR> <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBGetEx.cpp </SPAN> */ proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Kinematic",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Gravity",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Collision",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Mass Offset",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Pivot Offset",CKPGUID_BOOL,"FALSE"); proto->SetBehaviorCallbackFct( PBGet2CB ); proto->DeclareOutParameter("Collisions Group",CKPGUID_INT,"0"); proto->DeclareOutParameter("Kinematic Object",CKPGUID_BOOL,"FALSE"); proto->DeclareOutParameter("Gravity",CKPGUID_BOOL,"FALSE"); proto->DeclareOutParameter("Collision",CKPGUID_BOOL,"FALSE"); proto->DeclareOutParameter("Mass Offset",CKPGUID_VECTOR,"0.0f"); proto->DeclareOutParameter("Pivot Offset",CKPGUID_VECTOR,"0.0f"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBGet2); *pproto = proto; return CK_OK; } //************************************ // Method: PBGet2 // FullName: PBGet2 // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBGet2(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) { beh->ActivateOutput(0); return 0; } // body exists already ? clean and delete it : pRigidBody*result = world->getBody(target); if(result) { ////////////////////////////////////////////////////////////////////////// //linear damp : DWORD cGroup; beh->GetLocalParameterValue(bbI_CollisionGroup,&cGroup); if (cGroup) { int val = result->getCollisionsGroup(); SetOutputParameterValue<int>(beh,bbI_CollisionGroup,val); } DWORD kine; beh->GetLocalParameterValue(bbI_Kinematic,&kine); if (kine) { int val = result->isKinematic(); SetOutputParameterValue<int>(beh,bbI_Kinematic,val); } DWORD gravity; beh->GetLocalParameterValue(bbI_Gravity,&gravity); if (gravity) { int val = result->getActor()->readBodyFlag(NX_BF_DISABLE_GRAVITY); SetOutputParameterValue<int>(beh,bbI_Gravity,!val); } DWORD col; beh->GetLocalParameterValue(bbI_Collision,&col); if (col) { int val = result->isCollisionEnabled(); SetOutputParameterValue<int>(beh,bbI_Collision,val); } DWORD mass; beh->GetLocalParameterValue(bbI_MassOffset,&mass); if (mass) { VxVector val = result->getMassOffset(); SetOutputParameterValue<VxVector>(beh,bbI_MassOffset,val); } DWORD pivot; beh->GetLocalParameterValue(bbI_ShapeOffset,&pivot); if (mass) { // VxVector val = result->getPivotOffset(); // SetOutputParameterValue<VxVector>(beh,bbI_ShapeOffset,val); } } beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PBGet2CB // FullName: PBGet2CB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBGet2CB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD collGroup; beh->GetLocalParameterValue(bbI_CollisionGroup,&collGroup); beh->EnableOutputParameter(bbI_CollisionGroup,collGroup); DWORD kinematic; beh->GetLocalParameterValue(bbI_Kinematic,&kinematic); beh->EnableOutputParameter(bbI_Kinematic,kinematic); DWORD grav; beh->GetLocalParameterValue(bbI_Gravity,&grav); beh->EnableOutputParameter(bbI_Gravity,grav); DWORD coll; beh->GetLocalParameterValue(bbI_Collision,&coll); beh->EnableOutputParameter(bbI_Collision,coll); DWORD mOff; beh->GetLocalParameterValue(bbI_MassOffset,&mOff); beh->EnableOutputParameter(bbI_MassOffset,mOff); DWORD pOff; beh->GetLocalParameterValue(bbI_ShapeOffset,&pOff); beh->EnableOutputParameter(bbI_ShapeOffset,pOff); } break; } return CKBR_OK; } <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include <virtools/vtcxglobal.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "ISession.h" #include "IMessages.h" #include "xLogger.h" #include "vtLogTools.h" #include "xMessageTypes.h" #include "xDistributedClient.h" CKObjectDeclaration *FillBehaviorNCheckForLanServerDecl(); CKERROR CreateNCheckForLanServerProto(CKBehaviorPrototype **); int NCheckForLanServer(const CKBehaviorContext& behcontext); CKERROR NCheckForLanServerCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 typedef enum BB_IT { BB_IT_IN, BB_IT_STOP, BB_IT_NEXT }; typedef enum BB_INPAR { BB_IP_CONNECTION_ID, BB_IP_MESSAGE, }; typedef enum BB_OT { BB_O_OUT, BB_O_MESSAGE, BB_O_ERROR, }; typedef enum BB_OP { BB_OP_SENDER_ID, BB_OP_PRIVATE, BB_OP_ERROR, }; CKObjectDeclaration *FillBehaviorNCheckForLanServerDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NCheckForLanServer"); od->SetDescription("Waits for a Message from the Network."); od->SetCategory("TNL/Server"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x4bca58d9,0x3f4739fc)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNCheckForLanServerProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateNCheckForLanServerProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NCheckForLanServer"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInParameter("Timeout", CKPGUID_TIME, "5000"); proto->DeclareInput("In"); proto->DeclareInput("Off"); proto->DeclareOutput("Out"); proto->DeclareOutput("Server"); proto->DeclareOutParameter("Server Address", CKPGUID_STRING, ""); proto->DeclareLocalParameter("elapsed time", CKPGUID_FLOAT,0); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(NCheckForLanServer); proto->SetBehaviorCallbackFct(NCheckForLanServerCB); *pproto = proto; return CK_OK; } int NCheckForLanServer(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); vtNetworkManager *nman = GetNM(); ////////////////////////////////////////////////////////////////////////// //connection id + session name : using namespace vtTools::BehaviorTools; ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); float elapsedTime = 0.0f; beh->GetLocalParameterValue(0,&elapsedTime); if (!nman->GetClientNetInterface()) { nman->CreateClient(true,0,NULL); } if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); //reset elapsed time : elapsedTime = 0.0f; beh->SetLocalParameterValue(0,&elapsedTime); //TNL::Address addr("IP:255.255.255.0:28999"); TNL::Address broadcastAddress(IPProtocol, Address::Broadcast, 28999); if (GetNM()->GetClientNetInterface()) { //cin->getLocalLanServers().clear(); // nman->GetClientNetInterface()->sendPing(broadcastAddress,xNetInterface::Constants::ScanPingRequest); } } return CKBR_ACTIVATENEXTFRAME; } CKERROR NCheckForLanServerCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "Stream.h" #include "cooking.h" #include "IParameter.h" #include <xDebugTools.h> NxShape *pFactory::cloneShape(CK3dEntity *src,CK3dEntity *dst,CK3dEntity*dstBodyReference,int copyFlags,int bodyFlags/* =0 */) { if (!src || !dst ) return NULL; pRigidBody *srcBody = GetPMan()->getBody(src); if (!srcBody) return NULL; pRigidBody *dstBody = GetPMan()->getBody(dstBodyReference); if (!dstBody) return NULL; if (dstBody->isSubShape(dst)) return NULL; NxShape *srcShape = srcBody->getSubShape(src); if (!srcShape) return NULL; bool isSubShape=srcBody->isSubShape(src); pObjectDescr oDescr; int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); //---------------------------------------------------------------- // // Try to copy it directly from the source object // if ( !src->HasAttribute(attTypePBSetup) && isSubShape ) { pSubMeshInfo* sInfo = (pSubMeshInfo*)srcShape->userData; if (sInfo ) { const pObjectDescr &srcDescr = sInfo->initDescription; memcpy(&oDescr,&srcDescr,sizeof(pObjectDescr)); } } //---------------------------------------------------------------- // // Try to copy it directly from the source objects attribute // if (dst->HasAttribute(attTypePBSetup)) { //---------------------------------------------------------------- // // fill object description // CKParameterOut *par = dst->GetAttributeParameter(attTypePBSetup); if (!par) return 0; IParameter::Instance()->copyTo(&oDescr,par); oDescr.version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; } //---------------------------------------------------------------- // // adjust data // //---------------------------------------------------------------- // // find pivot settings // if ( (copyFlags & PB_CF_PIVOT_SETTINGS ) ) { //check in objects attribute int attPivot = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); } if (oDescr.flags & BF_SubShape) { if (oDescr.hullType == HT_Wheel) { VxVector loc; pWheel *wheel = createWheel(dstBodyReference,dst,oDescr.wheel,oDescr.convexCylinder,loc); if(wheel && wheel->castWheel2() ) return wheel->castWheel2()->getWheelShape(); else return NULL; }else if( oDescr.hullType != HT_Cloth) { srcBody->addSubShape(NULL,oDescr,dst); NxShape *result = srcBody->getSubShape(dst); if (result) { //---------------------------------------------------------------- // // Adjust mass // if ( ( copyFlags & PB_CF_MASS_SETTINGS) ) { /* srcBody->updateMassSettings(srcBody->getInitialDescription()->mass); result->updateMassSettings(oDescr.mass); else if(pFactory::Instance()->findSettings(oDescr.mass,referenceObject)) result->updateMassSettings(oDescr.mass); */ } return result; } } } return NULL; /* int sType = vtAgeia::getHullTypeFromShape(srcShape); switch(sType) { case HT_Sphere: { NxSphereShape *tShape = srcShape->isSphere(); NxSphereShapeDesc old; tShape->saveToDesc(old); } } */ } NxShape *pFactory::createShape(CK3dEntity *bodyReference,pObjectDescr descr,CK3dEntity *srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) { NxShape *result = NULL; if (!bodyReference || !mesh ) { return result; } pRigidBody *body=GetPMan()->getBody(bodyReference); if (!body) return NULL; NxActor *actor = body->getActor(); if (!actor) return NULL; int hType = descr.hullType; VxVector box_s = mesh->GetLocalBox().GetSize(); float density = descr.density; float skinWidth = descr.skinWidth; float radius = mesh->GetRadius(); NxQuat rot = pMath::getFrom(localRotation); NxVec3 pos = pMath::getFrom(localPos); CK_ID srcID = mesh->GetID(); pWheel *wheel = NULL; pSubMeshInfo *sInfo = NULL; switch(hType) { case HT_ConvexCylinder: { NxConvexShapeDesc shape; pConvexCylinderSettings &cSettings = descr.convexCylinder; iAssertW( ( descr.mask & OD_ConvexCylinder), pFactory::Instance()->findSettings(cSettings,srcReference), "Hull type has been set to convex cylinder but there is no descriptions \ passed or activated in the pObjectDescr::mask.Trying object attributes...."); if (cSettings.radius.reference) cSettings.radius.evaluate(cSettings.radius.reference); if (cSettings.height.reference) cSettings.height.evaluate(cSettings.height.reference); cSettings.radius.value = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); cSettings.height.value = cSettings.height.value > 0.0f ? cSettings.height.value : (box_s.v[cSettings.height.referenceAxis] * 0.5f); iAssertW( cSettings.isValid() , cSettings.setToDefault(),""); bool resultAssert = true; iAssertWR( pFactory::Instance()->_createConvexCylinderMesh(&shape,cSettings,srcReference),"",resultAssert); /* NxConvexShapeDesc shape; if (!_createConvexCylinder(&shape,srcReference)) xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); */ shape.density = density; shape.localPose.t = pos; shape.localPose.M = rot; shape.skinWidth = skinWidth; result = actor->createShape(shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Box: { NxBoxShapeDesc shape; shape.dimensions = pMath::getFrom(box_s)*0.5f; shape.density = density; shape.localPose.t = pos; shape.localPose.M = rot; shape.skinWidth = skinWidth; result = actor->createShape(shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Sphere: { NxSphereShapeDesc shape; shape.radius = radius; shape.density = density; shape.localPose.M = rot; shape.localPose.t = pMath::getFrom(localPos); if (skinWidth!=-1.0f) shape.skinWidth = skinWidth; result = actor->createShape(shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Mesh: { NxTriangleMeshDesc myMesh; myMesh.setToDefault(); pFactory::Instance()->createMesh(&actor->getScene(),mesh,myMesh); NxTriangleMeshShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); return NULL; } MemoryWriteBuffer buf; status = CookTriangleMesh(myMesh, buf); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); return NULL; } shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); shape.density = density; shape.localPose.M = rot; shape.localPose.t = pMath::getFrom(localPos); if (skinWidth!=-1.0f) shape.skinWidth = skinWidth; result = actor->createShape(shape); CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_ConvexMesh: { if (mesh->GetVertexCount()>=256 ) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshes allowed, by Ageia!"); goto nothing; } NxConvexMeshDesc myMesh; myMesh.setToDefault(); pFactory::Instance()->createConvexMesh(&actor->getScene(),mesh,myMesh); NxConvexShapeDesc shape; bool status = InitCooking(); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); goto nothing; } MemoryWriteBuffer buf; status = CookConvexMesh(myMesh, buf); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); goto nothing; } shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); shape.density = density; shape.localPose.M = rot; shape.localPose.t = pMath::getFrom(localPos); if (skinWidth!=-1.0f) shape.skinWidth = skinWidth; result = actor->createShape(shape); CloseCooking(); if (myMesh.points) { delete [] myMesh.points; } if (myMesh.triangles) { delete []myMesh.triangles; } break; } ////////////////////////////////////////////////////////////////////////// case HT_Capsule: { NxCapsuleShapeDesc shape; pCapsuleSettingsEx &cSettings = descr.capsule; iAssertW( ( descr.mask & OD_Capsule), pFactory::Instance()->findSettings(cSettings,srcReference), "Hull type has been set to convex cylinder but there is no descriptions \ passed or activated in the pObjectDescr::mask.Trying object attributes...."); bool resultAssert = true; if (cSettings.radius.reference) cSettings.radius.evaluate(cSettings.radius.reference); if (cSettings.height.reference) cSettings.height.evaluate(cSettings.height.reference); iAssertWR(cSettings.isValid(),cSettings.setToDefault(),resultAssert); shape.radius = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); shape.height = cSettings.height.value > 0.0f ? (cSettings.height.value-( 2*shape.radius)) : (box_s.v[cSettings.height.referenceAxis] - ( 2*shape.radius)) ; shape.density = density; shape.localPose.M = rot; shape.localPose.t = pos; shape.skinWidth = skinWidth; result = actor->createShape(shape); break; } ////////////////////////////////////////////////////////////////////////// case HT_Wheel: { pWheelDescr &wheelDescr = descr.wheel; CKParameterOut *wheelParameter = NULL; //---------------------------------------------------------------- // // determine wheel settings // if (!(descr.mask & OD_Wheel)) { wheelParameter = pFactory::Instance()->findSettings(wheelDescr,srcReference); } bool resultAssert = true; iAssertWR(wheelDescr.isValid(),wheelDescr.setToDefault(),resultAssert); //---------------------------------------------------------------- // // determine radius // if (wheelDescr.radius.reference == 0 && wheelDescr.radius.value == 0.0f ) { float radiusBestFit = 0.0f; if (box_s[0] > radiusBestFit) radiusBestFit = box_s[0]; if (box_s[1] > radiusBestFit) radiusBestFit = box_s[1]; if (box_s[2] > radiusBestFit) radiusBestFit = box_s[2]; wheelDescr.radius.value = radiusBestFit * 0.5f; } iAssertW(wheelDescr.radius.isValid(),wheelDescr.radius.evaluate(srcReference),""); if(!wheelDescr.radius.isValid()) wheelDescr.radius.value = srcReference->GetRadius(); VxVector box_s = mesh->GetLocalBox().GetSize(); float radius = wheelDescr.radius.value > 0.0f ? wheelDescr.radius.value : box_s.v[wheelDescr.radius.referenceAxis] * 0.5f; NxWheelShapeDesc shape; shape.setToDefault(); shape.radius = radius; shape.localPose.M = rot; shape.localPose.t = pos; float heightModifier = (wheelDescr.wheelSuspension + radius ) / wheelDescr.wheelSuspension; shape.suspension.spring = wheelDescr.springRestitution*heightModifier; shape.suspension.damper = wheelDescr.springDamping * heightModifier; shape.suspension.targetValue = wheelDescr.springBias * heightModifier; shape.suspensionTravel = wheelDescr.wheelSuspension; shape.inverseWheelMass = wheelDescr.inverseWheelMass; const pTireFunction& latFunc = wheelDescr.latFunc; const pTireFunction& longFunc = wheelDescr.longFunc; NxTireFunctionDesc lngTFD; lngTFD.extremumSlip = longFunc.extremumSlip ; lngTFD.extremumValue = longFunc.extremumValue; lngTFD.asymptoteSlip = longFunc.asymptoteSlip; lngTFD.asymptoteValue = longFunc.asymptoteValue; lngTFD.stiffnessFactor = longFunc.stiffnessFactor; NxTireFunctionDesc latTFD; latTFD.extremumSlip = latFunc.extremumSlip ; latTFD.extremumValue = latFunc.extremumValue; latTFD.asymptoteSlip = latFunc.asymptoteSlip; latTFD.asymptoteValue = latFunc.asymptoteValue; latTFD.stiffnessFactor = latFunc.stiffnessFactor; if ( !(wheelDescr.wheelFlags & WF_IgnoreTireFunction) ) { shape.lateralTireForceFunction =latTFD; shape.longitudalTireForceFunction = lngTFD; } shape.wheelFlags =wheelDescr.wheelShapeFlags; shape.density = density; shape.skinWidth = skinWidth; //---------------------------------------------------------------- // // evaluate wheel settings into attribute parameters // if (wheelParameter) { IParameter::Instance()->copyTo(wheelParameter,descr.wheel); } result = actor->createShape(shape); } } if(!result) { return NULL; } //---------------------------------------------------------------- // // add sub mesh meta // sInfo = new pSubMeshInfo(); sInfo->meshID = srcID; sInfo->mesh = mesh; sInfo->entID = srcReference->GetID(); sInfo->refObject = srcReference; result->setName(srcReference->GetName()); result->userData = (void*)sInfo; sInfo->initDescription = descr; //---------------------------------------------------------------- // // wheel extra data // if ( descr.hullType == HT_Wheel ) { sInfo->wheel = new pWheel2(body,&descr.wheel,srcReference); ((pWheel2*)sInfo->wheel)->setWheelShape((NxWheelShape*)result->isWheel()); sInfo->wheel->setEntID(srcReference->GetID()); ((pWheel2*)sInfo->wheel)->setEntity(srcReference); //((pWheel2*)wheel)->setEntity(static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(srcReference->GetID()))); sInfo->wheel->mWheelFlags = descr.wheel.wheelFlags; } //---------------------------------------------------------------- // // Material // if ((descr.mask & OD_Material)) body->updateMaterialSettings(descr.material,srcReference); else if(pFactory::Instance()->findSettings(descr.material,srcReference)) body->updateMaterialSettings(descr.material,srcReference); //---------------------------------------------------------------- // // Collision // if ((descr.mask & OD_Collision)) body->updateCollisionSettings(descr.collision,srcReference); else if(pFactory::Instance()->findSettings(descr.collision,srcReference)) body->updateCollisionSettings(descr.collision,srcReference); //---------------------------------------------------------------- // // Adjust pivot // if ( (descr.mask & OD_Pivot) ) { iAssertW1( descr.pivot.isValid(),descr.pivot.setToDefault()); body->updatePivotSettings(descr.pivot,srcReference); }else if(pFactory::Instance()->findSettings(descr.pivot,srcReference)) body->updatePivotSettings(descr.pivot,srcReference); //---------------------------------------------------------------- // // post // if (descr.flags & BF_TriggerShape ) { result->setFlag(NX_TRIGGER_ENABLE,TRUE); CKParameterOut *triggerAttributeParameter = srcReference->GetAttributeParameter(GetPMan()->att_trigger); if (triggerAttributeParameter) { int triggerFlags = vtTools::AttributeTools::GetValueFromAttribute<int>(srcReference,GetPMan()->att_trigger); result->setFlag(NX_TRIGGER_ON_ENTER,triggerFlags & NX_TRIGGER_ON_ENTER); result->setFlag(NX_TRIGGER_ON_STAY,triggerFlags & NX_TRIGGER_ON_STAY); result->setFlag(NX_TRIGGER_ON_LEAVE,triggerFlags & NX_TRIGGER_ON_LEAVE); } } //---------------------------------------------------------------- // // Mass // if ((descr.mask & OD_Mass)) body->updateMassSettings(descr.mass); else if(pFactory::Instance()->findSettings(descr.mass,srcReference)) body->updateMassSettings(descr.mass); return result; nothing : return NULL; } bool pFactory::_createConvexCylinderMesh(NxConvexShapeDesc *dstShapeDescription,pConvexCylinderSettings& srcSettings,CK3dEntity*referenceObject) { #ifdef _DEBUG assert(referenceObject); // <- should never happen ! #endif // _DEBUG bool result = false; /* srcSettings.radius.value *=0.5f; srcSettings.height.value *=0.5f; */ NxArray<NxVec3> points; NxVec3 center(0,0,0); NxVec3 frontAxis = getFrom(srcSettings.forwardAxis); // = wheelDesc->downAxis.cross(wheelDesc->wheelAxis); NxVec3 downAxis = getFrom(srcSettings.downAxis);//downAxis *=-1.0; // = wheelDesc->downAxis; NxVec3 wheelAxis = getFrom(srcSettings.rightAxis); // = wheelDesc->wheelAxis; //frontAxis.normalize(); frontAxis *= srcSettings.radius.value; //downAxis.normalize(); downAxis *= srcSettings.radius.value; //wheelAxis.normalize(); wheelAxis *= srcSettings.height.value; NxReal step; if(srcSettings.buildLowerHalfOnly) { if((srcSettings.approximation& 0x1) == 0) srcSettings.approximation++; step = (NxReal)(NxTwoPi) / (NxReal)(srcSettings.approximation*2); } else { step = (NxReal)(NxTwoPi) / (NxReal)(srcSettings.approximation); } for(NxU32 i = 0; i < srcSettings.approximation; i++) { NxReal iReal; if(srcSettings.buildLowerHalfOnly) { iReal = (i > (srcSettings.approximation >> 1))?(NxReal)(i+srcSettings.approximation):(NxReal)i; } else { iReal = (NxReal)i; } NxReal Sin, Cos; NxMath::sinCos(step * iReal, Sin, Cos); NxVec3 insPoint = (downAxis * -Cos) + (frontAxis * Sin); points.pushBack(insPoint + wheelAxis); points.pushBack(insPoint - wheelAxis); } NxConvexMeshDesc convexDesc; convexDesc.numVertices = points.size(); convexDesc.pointStrideBytes = sizeof(NxVec3); convexDesc.points = &points[0].x; // srcSettings.convexFlags |=NX_CF_COMPUTE_CONVEX; // convexDesc.flags |= srcSettings.convexFlags; int cf = CF_ComputeConvex; cf |= srcSettings.convexFlags; convexDesc.flags |= cf; // Cooking from memory bool status = InitCooking(); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't initiate cooking lib!"); return NULL; } MemoryWriteBuffer buf; int s = convexDesc.isValid(); if(CookConvexMesh(convexDesc, buf)) { //NxConvexShapeDesc convexShapeDesc; dstShapeDescription->meshData = getPhysicSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); dstShapeDescription->localPose.t = center; dstShapeDescription->localPose.M.setColumn(0, NxVec3( 1, 0, 0)); dstShapeDescription->localPose.M.setColumn(1, NxVec3( 0,-1, 0)); dstShapeDescription->localPose.M.setColumn(2, NxVec3( 0, 0, -1)); if(dstShapeDescription->meshData != NULL) { result = true; // NxU32 shapeNumber = actor->getNbShapes(); // result = actor->createShape(convexShapeDesc)->isConvexMesh(); // if (!result) { // xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); // } //wheel->wheelConvex->userData = wheel; } } CloseCooking(); return result; } NxShape * pFactory::_createConvexCylinder(NxActor *actor,int approximation,VxVector _forwardAxis,VxVector _downAxis,VxVector _rightAxis,float height,float radius,bool buildLowerHalf,int shapeFlags) { if (!actor || approximation<1 ) return NULL; NxConvexShape *result = NULL; NxArray<NxVec3> points; NxVec3 center(0,0,0); NxVec3 frontAxis = getFrom(_forwardAxis);// = wheelDesc->downAxis.cross(wheelDesc->wheelAxis); NxVec3 downAxis = getFrom(_downAxis);// = wheelDesc->downAxis; downAxis *=-1.0; NxVec3 wheelAxis = getFrom(_rightAxis);// = wheelDesc->wheelAxis; //frontAxis.normalize(); frontAxis *= radius; //downAxis.normalize(); downAxis *= radius; //wheelAxis.normalize(); wheelAxis *= height; NxReal step; if(buildLowerHalf) { if((approximation & 0x1) == 0) approximation++; step = (NxReal)(NxTwoPi) / (NxReal)(approximation*2); } else { step = (NxReal)(NxTwoPi) / (NxReal)(approximation); } for(NxU32 i = 0; i < approximation; i++) { NxReal iReal; if(buildLowerHalf) { iReal = (i > (approximation >> 1))?(NxReal)(i+approximation):(NxReal)i; } else { iReal = (NxReal)i; } NxReal Sin, Cos; NxMath::sinCos(step * iReal, Sin, Cos); NxVec3 insPoint = (downAxis * -Cos) + (frontAxis * Sin); points.pushBack(insPoint + wheelAxis); points.pushBack(insPoint - wheelAxis); } NxConvexMeshDesc convexDesc; convexDesc.numVertices = points.size(); convexDesc.pointStrideBytes = sizeof(NxVec3); convexDesc.points = &points[0].x; convexDesc.flags |= shapeFlags; //convexDesc.flags |= NX_CF_COMPUTE_CONVEX; // Cooking from memory bool status = InitCooking(); if (!status) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't initiate cooking lib!"); return NULL; } MemoryWriteBuffer buf; if(CookConvexMesh(convexDesc, buf)) { NxConvexShapeDesc convexShapeDesc; convexShapeDesc.meshData = actor->getScene().getPhysicsSDK().createConvexMesh(MemoryReadBuffer(buf.data)); convexShapeDesc.localPose.t = center; convexShapeDesc.localPose.M.setColumn(0, NxVec3( 1, 0, 0)); convexShapeDesc.localPose.M.setColumn(1, NxVec3( 0,-1, 0)); convexShapeDesc.localPose.M.setColumn(2, NxVec3( 0, 0, -1)); if(convexShapeDesc.meshData != NULL) { NxU32 shapeNumber = actor->getNbShapes(); result = actor->createShape(convexShapeDesc)->isConvexMesh(); if (!result) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); } //wheel->wheelConvex->userData = wheel; } } CloseCooking(); return result; } NxShapeDesc& pFactory::createShape(int hullType,CK3dEntity*ent,float density) { assert(ent); float radius = ent->GetRadius(); if (ent->GetRadius() < 0.001f ) { radius = 1.0f; } VxVector box_s= BoxGetZero(ent); switch(hullType) { case HT_Box: { NxBoxShapeDesc result; //result.setToDefault(); result.dimensions = pMath::getFrom(box_s); result.density = density; return result; } case HT_Sphere: { NxSphereShapeDesc result; //result.setToDefault(); result.localPose.t = NxVec3(0,radius,0); result.radius = radius; result.density = density; return result; } } NxBoxShapeDesc result; result.setToDefault(); result.dimensions = pMath::getFrom(box_s); return result; } <file_sep>#include "CKAll.h" #include "VSLManagerSDK.h" enum vtEventState { EEVT_STARTED, EEVT_FINISHED }; struct vtExternalEvent { unsigned long timeOfCreation; char command[MAX_PATH]; char commandArg[MAX_PATH]; vtEventState state; }; struct TSharedMemory { vtExternalEvent event; }; struct haptekMsg { XString command; int k; };<file_sep>xcopy .\examples\*.* .\doxyOutput\html /s /e /y doxygen doxyConfigAll.dox <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPVControlDecl(); CKERROR CreatePVControlProto(CKBehaviorPrototype **pproto); int PVControl(const CKBehaviorContext& behcontext); CKERROR PVControlCB(const CKBehaviorContext& behcontext); using namespace vtTools::BehaviorTools; enum bInTrigger { TI_DO, }; enum bOutputs { O_Flags, O_Gear, O_RPM, O_RPM_WHEELS, O_RATIO, }; enum bInputs { I_Acc, I_Steer, I_AnalogAcc, I_AnalogSteering, I_Handbrake, }; #define BB_SSTART 0 BBParameter pInMap3[] = { BB_SPIN(I_Acc,CKPGUID_FLOAT,"Acceleration","0"), BB_SPIN(I_Steer,CKPGUID_FLOAT,"Steering","0"), BB_SPIN(I_AnalogAcc,CKPGUID_BOOL,"Analog Acceleration","0"), BB_SPIN(I_AnalogSteering,CKPGUID_BOOL,"Analog Steering","0"), BB_SPIN(I_Handbrake,CKPGUID_BOOL,"Handbrake","0"), }; #define BBIMAP pInMap3 CKERROR PVControlCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(BBIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(BBIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(BBIMAP,BB_SSTART); break; } } return CKBR_OK; } //************************************ // Method: FillBehaviorPVControlDecl // FullName: FillBehaviorPVControlDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPVControlDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVControl"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Controls a vehicle by real values instead of input trigger"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x550d3ca3,0x27f10ac3)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVControlProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePVControlProto // FullName: CreatePVControlProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePVControlProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVControl"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /* PVControl PVControl is categorized in \ref Vehicles <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Controls a vehicle by real values instead of input trigger.<br> <h3>Technical Information</h3> \image html PVControl.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the vehicle. The entity needs to be physicalized before. It needs to have at least one wheel in its hierarchy. <BR> <BR> <SPAN CLASS="pin">Acceleration: </SPAN>The acceleration for this frame. <br> <b>Range:</b> [0,1] <br> <SPAN CLASS="pin">Steering: </SPAN>The steering for this frame. <br> <b>Range:</b> [-1,1] <BR> <SPAN CLASS="pin">Analog Acceleration: </SPAN>Switches between analog and digital acceleration. <br> <b>Range:</b> TRUE,FALSE] <BR> <SPAN CLASS="pin">Analog Steering: </SPAN>Switches between analog and digital steering. <br> <b>Range:</b> TRUE,FALSE] <BR> <SPAN CLASS="pin">Handbrake: </SPAN>Sets the handbrake status to enabled for this frame. <br> <b>Range:</b> TRUE,FALSE] <BR> <SPAN CLASS="setting">Acceleration: </SPAN>Enables input for acceleration. <BR> <SPAN CLASS="setting">Steering: </SPAN>Enables input for steering. <BR> <SPAN CLASS="setting">Analog Acceleration: </SPAN>Enables input for analog acceleration. <BR> <SPAN CLASS="setting">Analog Steering: </SPAN>Enables input for analog steering. <BR> <SPAN CLASS="setting">Handbrake: </SPAN>Enables input for handbrake. <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> The body must have a vehicle object. See #ref PVSet <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> */ proto->SetBehaviorCallbackFct( PVControlCB ); proto->DeclareOutParameter("Flags",VTF_VSTATE_FLAGS,"-1"); proto->DeclareOutParameter("Gear",CKPGUID_INT,"-1"); proto->DeclareOutParameter("RPM",CKPGUID_FLOAT,"-1"); proto->DeclareOutParameter("RPM Wheels",CKPGUID_FLOAT,"-1"); proto->DeclareOutParameter("Motor Ratio",CKPGUID_FLOAT,"-1"); BB_EVALUATE_SETTINGS(BBIMAP); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PVControl); *pproto = proto; return CK_OK; } //************************************ // Method: PVControl // FullName: PVControl // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ #define BBSParameter(A) DWORD s##A;\ beh->GetLocalParameterValue(A,&s##A) int PVControl(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbSErrorME(E_PE_REF); pRigidBody *body = NULL; BB_DECLARE_PIMAP; body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); float acc = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_Acc)); int accAnalog = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_AnalogAcc)); float steer = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_Steer)); int steerAnalog = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_AnalogSteering)); int handBrake = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_Handbrake)); BBSParameter(I_Acc); BBSParameter(I_AnalogAcc); BBSParameter(I_Steer); BBSParameter(I_AnalogSteering); BBSParameter(I_Handbrake); pVehicle *v = body->getVehicle(); if (!v) { bbSErrorME(E_PE_NoVeh); } if (sI_Acc && acc!=v->_cAcceleration) v->setControlState(E_VCS_ACCELERATION,acc); if (sI_AnalogAcc && accAnalog!=v->_cAnalogAcceleration) v->setControlMode(E_VCS_ACCELERATION,accAnalog ? E_VCSM_ANALOG : E_VCSM_DIGITAL); if (sI_Steer && steer!=v->_cSteering) v->setControlState(E_VCS_STEERING,steer); if (sI_AnalogSteering && steerAnalog!=v->_cAnalogSteering ) v->setControlMode(E_VCS_STEERING,steerAnalog ? E_VCSM_ANALOG : E_VCSM_DIGITAL); if (sI_Handbrake && handBrake ) v->setControlState(E_VCS_HANDBRAKE,handBrake == 1 ? true : false); DWORD flags = v->getStateFlags(); beh->SetOutputParameterValue(O_Flags,&flags); float ratio = v->_getGearRatio(); beh->SetOutputParameterValue(O_RATIO,&ratio); if (v->getGears()) { int g = v->getGears()->getGear(); beh->SetOutputParameterValue(O_Gear,&g); } if (v->getMotor()) { float rpm = v->getMotor()->getRpm(); beh->SetOutputParameterValue(O_RPM,&rpm); } beh->ActivateOutput(0); } return 0; }<file_sep>/******************************************************************** created: 2009/02/16 created: 16:2:2009 8:57 filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\vtPreReqs.h file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common file base: vtPreReqs file ext: h author: <NAME> purpose: Virtools Forward Declarations *********************************************************************/ #ifndef __PREREQUISITES_VIRTOOSLS_H__ #define __PREREQUISITES_VIRTOOSLS_H__ //################################################################ // // Common Types // class CKBeObject; class CKContext; class CKParameter; class CKParameterIn; class CKParameterOut; class CKParameterManager; class CKAttributeManager; //################################################################ // // 3D Types // class CKMesh; class CK3dEntity; class CK3dObject; class CK3dPointCloud; #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pWorldSettings.h" #include "NxUserNotify.h" #include "NxUserContactReport.h" #include "pWorldCallbacks.h" struct MyUserNotify : public NxUserNotify { public: /*virtual bool onJointBreak(NxReal breakingImpulse, NxJoint & brokenJoint) { return false; }*/ virtual bool onJointBreak(NxReal breakingImpulse, NxJoint & brokenJoint) { pJoint *joint = static_cast<pJoint*>(brokenJoint.userData); if (joint) { pBrokenJointEntry *entry = new pBrokenJointEntry(); //entry->joint = joint; entry->impulse = breakingImpulse; entry->jType =brokenJoint.getType(); if(joint->GetVTEntA()) entry->mAEnt = joint->GetVTEntA()->GetID(); if(joint->GetVTEntB()) entry->mBEnt = joint->GetVTEntB()->GetID(); GetPMan()->getJointFeedbackList().PushBack(entry); //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Joint break!"); ////////////////////////////////////////////////////////////////////////// // // retrieve body pointers and call callback scripts NxActor *a = NULL; pRigidBody *ab=NULL; NxActor *b = NULL; pRigidBody *bb=NULL; brokenJoint.getActors(&a,&b); bool isRemoved = false; if(a) { ab= static_cast<pRigidBody*>(a->userData); } if(b) bb= static_cast<pRigidBody*>(b->userData); if(ab) { //ab->onJointBreak(entry); //ab->hasBrokenJoint = true; if(!isRemoved) { isRemoved = true; } } if(bb) { //bb->onJointBreak(entry); //bb->hasBrokenJoint= true; } //joint->getJoint()->appData= NULL; //joint->getJoint()->userData= NULL; } return false; } virtual void onSleep(NxActor **actors, NxU32 count) { /* NX_ASSERT(count > 0); while (count--) { NxActor *thisActor = *actors; //Tag the actor as sleeping size_t currentFlag = (size_t)thisActor->userData; currentFlag |= gSleepFlag; thisActor->userData = (void*)currentFlag; actors++; }*/ if (count >0) { while (count--) { NxActor *thisActor = *actors; if (thisActor) { pRigidBody *body = static_cast<pRigidBody*>(thisActor->userData); if (body) { int flags = body->getFlags(); flags |=BF_Sleep; body->setFlags(flags); } } } } } virtual void onWake(NxActor **actors, NxU32 count) { if (count >0) { while (count--) { NxActor *thisActor = *actors; if (thisActor) { pRigidBody *body = static_cast<pRigidBody*>(thisActor->userData); if (body) { body->getCollisions().Clear(); body->getTriggers().Clear(); int flags = body->getFlags(); flags &=~BF_Sleep; body->setFlags(flags); } } actors++; } } } }myNotify; pWorld*pFactory::createWorld(CK3dEntity* referenceObject, pWorldSettings *worldSettings,pSleepingSettings *sleepSettings) { using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// //sanity checks : if (!referenceObject || !GetPMan() ) { return NULL; } if (!getPhysicSDK()) { //xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"No physic sdk loaded"); return NULL; } int worldAtt = GetPMan()->att_world_object; int surfaceAttribute = GetPMan()->att_surface_props; //exists ? Delete it ! pWorld *w = GetPMan()->getWorld(referenceObject->GetID()); if (w) { GetPMan()->deleteWorld(referenceObject->GetID()); } //our new world : pWorld *result = new pWorld(referenceObject); GetPMan()->getWorlds()->InsertUnique(referenceObject,result); result->initUserReports(); ////////////////////////////////////////////////////////////////////////// //there is no world settings attribute : if (!referenceObject->HasAttribute(worldAtt) ) { referenceObject->SetAttribute(worldAtt); using namespace vtTools; VxVector grav = worldSettings->getGravity(); float sWith = worldSettings->getSkinWith(); AttributeTools::SetAttributeValue<VxVector>(referenceObject,worldAtt,0,&grav); AttributeTools::SetAttributeValue<float>(referenceObject,worldAtt,1,&sWith); } worldSettings = pFactory::Instance()->createWorldSettings(XString("Default"),GetPMan()->getDefaultConfig()); if (!worldSettings) { worldSettings = new pWorldSettings(); } GetPMan()->setPhysicFlags(worldSettings->getPhysicFlags()); ////////////////////////////////////////////////////////////////////////// //pSDK Scene creation : // Create a scene NxSceneDesc sceneDesc; NxHWVersion hwCheck = getPhysicSDK()->getHWVersion(); if(GetPMan()->physicFlags & PMF_DONT_USE_HARDWARE ) { hwCheck = NX_HW_VERSION_NONE; } if(hwCheck != NX_HW_VERSION_NONE) { sceneDesc.simType = NX_SIMULATION_HW; } //SCE_SEARCHFORCOMPUTERS. sceneDesc.gravity = pMath::getFrom(worldSettings->getGravity()); sceneDesc.upAxis = 1; //sceneDesc.flags |=NX_SF_ENABLE_ACTIVETRANSFORMS/*|NX_SF_ENABLE_MULTITHREAD|NX_SF_SIMULATE_SEPARATE_THREAD*/; sceneDesc.flags = worldSettings->getSceneFlags(); sceneDesc.userNotify =&myNotify; sceneDesc.userContactReport = result->contactReport; sceneDesc.userContactModify = result->contactModify; NxScene *scene = NULL; if (getPhysicSDK()) { scene = getPhysicSDK()->createScene(sceneDesc); if(scene == NULL) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create scene!"); return NULL; } } NxCompartment *comp = NULL; if(hwCheck != NX_HW_VERSION_NONE) { NxCompartmentDesc cdesc; cdesc.type = NX_SCT_RIGIDBODY; #if defined(WIN32) && !defined(_XBOX) cdesc.deviceCode = NX_DC_PPU_AUTO_ASSIGN; #else cdesc.deviceCode = NX_DC_CPU; #endif comp = scene->createCompartment(cdesc); if (!comp) xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create scene's compartment"); } result->setScene(scene); scene->setUserContactReport(result->contactReport); scene->setUserTriggerReport(result->triggerReport); NxMaterialDesc *materialDescr = NULL; NxMaterial *material = NULL; if (referenceObject->HasAttribute(surfaceAttribute)) { materialDescr = createMaterialFromEntity(referenceObject); material = result->getScene()->createMaterial(*materialDescr); material->userData = (void*)GetValueFromParameterStruct<int>(referenceObject->GetAttributeParameter(surfaceAttribute) ,E_MS_XML_TYPE); }else{ if (getDefaultDocument()) { materialDescr = createMaterialFromXML("Default",getDefaultDocument()); } if (materialDescr) { material = result->getScene()->createMaterial(*materialDescr); } if (!material) { materialDescr = new NxMaterialDesc(); materialDescr->setToDefault(); material = result->getScene()->getMaterialFromIndex(0); material->loadFromDesc(*materialDescr); } if(material) { pMaterial *bmaterial = new pMaterial(); bmaterial->setToDefault(); copyTo(*bmaterial,material); material->userData = (void*)bmaterial; } } NxMaterial *zeroMaterial = result->getScene()->getMaterialFromIndex(0); zeroMaterial->setDirOfAnisotropy(material->getDirOfAnisotropy()); zeroMaterial->setStaticFriction(material->getStaticFriction()); zeroMaterial->setDynamicFriction(material->getDynamicFriction()); zeroMaterial->setStaticFrictionV(material->getStaticFrictionV()); zeroMaterial->setDynamicFrictionV(material->getDynamicFrictionV()); zeroMaterial->setFrictionCombineMode(material->getFrictionCombineMode()); zeroMaterial->setRestitutionCombineMode(material->getRestitutionCombineMode()); zeroMaterial->setFlags(material->getFlags()); if (!material) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create default material!"); } result->setDefaultMaterial(material); scene->userData = result; result->_checkForDominanceConstraints(); result->_construct(); if (comp) { result->setCompartment(comp); } return result; } //************************************ // Method: CreateDefaultWorld // FullName: vtODE::pFactory::CreateDefaultWorld // Access: public // Returns: pWorld* // Qualifier: // Parameter: XString name //************************************ pWorld*pFactory::createDefaultWorld(XString name) { CK3dEntity *defaultWorldFrame = createFrame("pDefaultWorld"); pWorldSettings *wSettings = getManager()->getDefaultWorldSettings(); pWorld* world = createWorld(defaultWorldFrame,wSettings,NULL); getManager()->setDefaultWorld(world); return world; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtStructHelper.h" //################################################################ // // Prototype // XString getDefaultValue(CKParameter *inputParameter) { CustomParametersArrayType& inputArray = GetPMan()->_getCustomStructures(); XString result; int s = inputArray.Size(); CustomParametersArrayIteratorType it = inputArray.Find(inputParameter->GetGUID()); if (it == inputArray.End()) return result; using namespace vtTools::ParameterTools; int x = 0; CustomStructure *cStruct = *it; if (cStruct) { cStruct->getArray().size(); } CKParameterTypeDesc *tdescr = GetPMan()->GetContext()->GetParameterManager()->GetParameterTypeDescription( inputParameter->GetType() ); if( (tdescr->dwFlags & CKPARAMETERTYPE_STRUCT) == 0x00000010 ) { int y = cStruct->getArray().size(); int y2 = cStruct->getArray().size(); }else{ } return result; } //################################################################ // // Not being used // void rigidBodyAttributeCallback(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg) { // recheckWorldsFunc(AttribType,Set,obj,arg); } //################################################################ // // Body functions // pRigidBody*PhysicManager::getBody(const char*name,int flags/* =0 */) { for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) { pWorld *w = *it; if(w) { int nbActors = w->getScene()->getNbActors(); NxActor** actors = w->getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { if (!strcmp(actor->getName(),name) ) { pRigidBody* body =static_cast<pRigidBody*>(actor->userData); if (body) { return body; } } } } } } return 0; } pRigidBody*PhysicManager::getBody(CK3dEntity *ent) { pWorld* w = getWorldByBody(ent); if (w) { pRigidBody *body = w->getBody(ent); if (body) { return body; } } return NULL; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorJD6SetParametersDecl(); CKERROR CreateJD6SetParametersProto(CKBehaviorPrototype **pproto); int JD6SetParameters(const CKBehaviorContext& behcontext); CKERROR JD6SetParametersCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_BodyA=0, bbI_BodyB, bbI_Anchor, bbI_AnchorRef, bbI_Axis, bbI_AxisRef }; //************************************ // Method: FillBehaviorJD6SetParametersDecl // FullName: FillBehaviorJD6SetParametersDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorJD6SetParametersDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6SetParameters"); od->SetCategory("Physic/D6"); od->SetDescription("Sets parameters in a D6 joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x4b8207b2,0x57964805)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJD6SetParametersProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreateJD6SetParametersProto // FullName: CreateJD6SetParametersProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreateJD6SetParametersProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6SetParameters"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In0"); proto->DeclareOutput("Out0"); proto->SetBehaviorCallbackFct( JD6SetParametersCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Drive Linear Velocity",CKPGUID_VECTOR); proto->DeclareInParameter("Drive Angular Velocity",CKPGUID_VECTOR); proto->DeclareInParameter("Drive Position",CKPGUID_VECTOR); proto->DeclareInParameter("Drive Orientation",CKPGUID_QUATERNION); proto->DeclareInParameter("Ratio",CKPGUID_FLOAT,"0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(JD6SetParameters); *pproto = proto; return CK_OK; } //************************************ // Method: JD6SetParameters // FullName: JD6SetParameters // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int JD6SetParameters(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); if(bodyA || bodyB) { pJointD6 *joint =static_cast<pJointD6*>(worldA->getJoint(target,targetB,JT_D6)); VxVector linVel = GetInputParameterValue<VxVector>(beh,1); VxVector aVel = GetInputParameterValue<VxVector>(beh,2); VxVector pos = GetInputParameterValue<VxVector>(beh,3); VxQuaternion rot = GetInputParameterValue<VxQuaternion>(beh,4); float ratio = GetInputParameterValue<float>(beh,5); joint->setDriveLinearVelocity(linVel); joint->setDriveAngularVelocity(aVel); joint->setRatio(ratio); joint->setDrivePosition(pos); joint->setDriveRotation(rot); } beh->ActivateOutput(0); } return 0; } //************************************ // Method: JD6SetParametersCB // FullName: JD6SetParametersCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR JD6SetParametersCB(const CKBehaviorContext& behcontext) { return CKBR_OK; }<file_sep> /******************************************************************** created: 2008/01/14 created: 14:1:2008 12:08 filename: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer\CustomPlayerApp.cpp file path: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer file base: CustomPlayerApp file ext: cpp author: mc007 purpose: *********************************************************************/ #include "CPStdAfx.h" #include "CustomPlayerDefines.h" #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "xSplash.h" // the unique (global) instance of the winapp CCustomPlayerApp theApp; extern CCustomPlayer* thePlayer; #include <xUtils.h> #include "CustomPlayerDialog.h" BEGIN_MESSAGE_MAP(CCustomPlayerApp, CWinApp) //{{AFX_MSG_MAP(CCustomPlayerApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() //////////////////////////////////////////////////////////////////////////////// // // CCustomPlayerApp: PUBLIC METHODS // //////////////////////////////////////////////////////////////////////////////// //************************************ // Method: GetInstance // FullName: CCustomPlayerApp::GetInstance // Access: protected static // Returns: CCustomPlayerApp* // Qualifier: //************************************ CCustomPlayerApp* CCustomPlayerApp::GetInstance() { if (theApp) { return &theApp; } else { return NULL; } } CCustomPlayerApp::CCustomPlayerApp() : m_MainWindow(0),m_RenderWindow(0), m_PlayerClass(MAINWINDOW_CLASSNAME),m_RenderClass(RENDERWINDOW_CLASSNAME), m_PlayerTitle(MAINWINDOW_TITLE), m_Config(0) { } CCustomPlayerApp::~CCustomPlayerApp() { // simply destroy the windows ... if (m_RenderWindow) { DestroyWindow(m_RenderWindow); } if (m_MainWindow) { DestroyWindow(m_MainWindow); } } int CCustomPlayerApp::ExitInstance() { if (thePlayer) { delete thePlayer; thePlayer = 0; } return CWinApp::ExitInstance(); } //////////////////////////////////////////////////////////////////////////////// // // CCustomPlayerApp: PROTECTED/PRIVATE METHODS // //////////////////////////////////////////////////////////////////////////////// void CCustomPlayerApp::_DisplaySplashWindow() { // display the splash windows centered. /* RECT rect; m_Splash = CreateDialog(theApp.m_hInstance,(LPCTSTR)IDD_SPLASH,NULL,(DLGPROC)_LoadingDlgWndProc); GetWindowRect(m_Splash,&rect); SetWindowPos(m_Splash,NULL,(GetSystemMetrics(SM_CXSCREEN)-(rect.right-rect.left))/2, (GetSystemMetrics(SM_CYSCREEN)-(rect.bottom-rect.top))/2,0,0,SWP_NOZORDER|SWP_NOSIZE); ShowWindow(m_Splash, SW_SHOW); UpdateWindow(m_Splash); */ } void CCustomPlayerApp::_PublishingRights() { // IMPORTANT: The following warning should be removed by you (in the source // code prior to compilation). // // This dialog box serves to remind you that publishing rights, a.k.a. runtime // fees, are due when building any custom executable (like the player you just // compiled). Contact <EMAIL> for more information. MessageBox(NULL,PUBLISHING_RIGHT_TEXT,PUBLISHING_RIGHT_TITLE,MB_OK|MB_ICONASTERISK); } BOOL CCustomPlayerApp::_LoadInternal(XString& oFilename) { // parameters are: // -disable_keys (or -d) : disable ALT+ENTER to switch from/to fullscreen // and ALT+F4 to close the application // -auto_fullscreen (or -f) : the player start automatically in fullscreen mode // -file filename : specify the file to load // -title title : specify the title of the main window // -width width : specify the width in windowed mode // -height height : specify the height in windowed mode // -fwidth fullscreenwidth : specify the width in fullscreen mode // -fheight fullscreeneight : specify the height in fullscreen mode // -fbpp fullscreenbpp : specify the bit per pixel in fullscreen mode // -rasterizer family,flags : specify the rasterizer family (see CKRST_RSTFAMILY) // and flags to choose the rasterizer (see CKRST_SPECIFICCAPS) // default values are: // - title = Virtools Custom Player // - width = 640 // - height = 480 // - fullscreen width = 640 // - fullscreen height = 480 // - fullscreen bpp = 32 // - rasterizer = CKRST_DIRECTX,CKRST_SPECIFICCAPS_HARDWARE|CKRST_SPECIFICCAPS_DX9 // Please note that if there are "space" characters in a parameter value the value must be between " " // *********************************************************************************************************************** // m_Config |= eAutoFullscreen; // KAM comment to go to windowed mode, uncomment to go directly to full screen // *********************************************************************************************************************** // parameter followed by values // -file oFilename = "a.vmo"; // -title m_PlayerTitle = "PlayGen Player"; // -width CCustomPlayer::Instance().WindowedWidth() = 800; // -height CCustomPlayer::Instance().WindowedHeight() = 600; // -fwidth CCustomPlayer::Instance().FullscreenWidth() = 800; // -fheight CCustomPlayer::Instance().FullscreenHeight() = 600; // -fbpp CCustomPlayer::Instance().FullscreenBpp() = 32; /* // -rasterizer else if (strncmp(token,"rasterizer",XMin((int)(ptr-token),(int)(sizeof("rasterizer")-1)))==0) { XString value; if (!_ComputeParamValue(ptr2,value)) { return FALSE; } int tmp = 0; int tmp2 = 0; if(sscanf(value.CStr(),"%d,%d",&tmp,&tmp2)==2) { CCustomPlayer::Instance().RasterizerFamily() = tmp; CCustomPlayer::Instance().RasterizerFlags() = tmp2; */ return TRUE; } BOOL CCustomPlayerApp::_ReadCommandLine(const char* iArguments, XString& oFilename) { // parameters are: // -disable_keys (or -d) : disable ALT+ENTER to switch from/to fullscreen // and ALT+F4 to close the application // -auto_fullscreen (or -f) : the player start automatically in fullscreen mode // -file filename : specify the file to load // -title title : specify the title of the main window // -width width : specify the width in windowed mode // -height height : specify the height in windowed mode // -fwidth fullscreenwidth : specify the width in fullscreen mode // -fheight fullscreeneight : specify the height in fullscreen mode // -fbpp fullscreenbpp : specify the bit per pixel in fullscreen mode // -rasterizer family,flags : specify the rasterizer family (see CKRST_RSTFAMILY) // and flags to choose the rasterizer (see CKRST_SPECIFICCAPS) // default values are: // - title = Virtools Custom Player // - width = 640 // - height = 480 // - fullscreen width = 640 // - fullscreen height = 480 // - fullscreen bpp = 32 // - rasterizer = CKRST_DIRECTX,CKRST_SPECIFICCAPS_HARDWARE|CKRST_SPECIFICCAPS_DX9 // Please note that if there are "space" characters in a parameter value the value must be between " " XStringTokenizer st(iArguments,"-"); const char* token = 0; const char* ptr = 0; const char* ptr2 = 0; while (token=st.NextToken(token)) { ptr = _NextBlank(token); ptr2 = _SkipBlank(ptr); // the parameter is not followed by a value if (*ptr2=='\0') { // -disable_keys (or -d) if (strncmp(token,"d",XMin((int)(ptr-token),(int)(sizeof("d")-1)))==0 || strncmp(token,"disable_keys",XMin((int)(ptr-token),(int)(sizeof("disable_keys")-1)))==0) { m_Config |= eDisableKeys; } // -auto_fullscreen (or -f) else if (strncmp(token,"f",XMin((int)(ptr-token),(int)(sizeof("f")-1)))==0 || strncmp(token,"auto_fullscreen",XMin((int)(ptr-token),(int)(sizeof("auto_fullscreen")-1)))==0) { m_Config |= eAutoFullscreen; } else { // unknow parameter return FALSE; } continue; } // parameter followed by values // -file if (strncmp(token,"file",XMin((int)(ptr-token),(int)(sizeof("file")-1)))==0) { if (!_ComputeParamValue(ptr2,oFilename)) { return FALSE; } } // -title else if (strncmp(token,"title",XMin((int)(ptr-token),(int)(sizeof("title")-1)))==0) { if (!_ComputeParamValue(ptr2,m_PlayerTitle)) { return FALSE; } } // -width else if (strncmp(token,"width",XMin((int)(ptr-token),(int)(sizeof("width")-1)))==0) { XString value; if (!_ComputeParamValue(ptr2,value)) { return FALSE; } int tmp = 0; if(sscanf(value.CStr(),"%d",&tmp)==1) { CCustomPlayer::Instance().WindowedWidth() = tmp; } } // -height else if (strncmp(token,"height",XMin((int)(ptr-token),(int)(sizeof("height")-1)))==0) { XString value; if (!_ComputeParamValue(ptr2,value)) { return FALSE; } int tmp = 0; if(sscanf(value.CStr(),"%d",&tmp)==1) { CCustomPlayer::Instance().WindowedHeight() = tmp; } } // -fwidth else if (strncmp(token,"fwidth",XMin((int)(ptr-token),(int)(sizeof("fwidth")-1)))==0) { XString value; if (!_ComputeParamValue(ptr2,value)) { return FALSE; } int tmp = 0; if(sscanf(value.CStr(),"%d",&tmp)==1) { CCustomPlayer::Instance().FullscreenWidth() = tmp; } } // -fheight else if (strncmp(token,"fheight",XMin((int)(ptr-token),(int)(sizeof("fheight")-1)))==0) { XString value; if (!_ComputeParamValue(ptr2,value)) { return FALSE; } int tmp = 0; if(sscanf(value.CStr(),"%d",&tmp)==1) { CCustomPlayer::Instance().FullscreenHeight() = tmp; } } // -fbpp else if (strncmp(token,"fbpp",XMin((int)(ptr-token),(int)(sizeof("fbpp")-1)))==0) { XString value; if (!_ComputeParamValue(ptr2,value)) { return FALSE; } int tmp = 0; if(sscanf(value.CStr(),"%d",&tmp)==1) { CCustomPlayer::Instance().FullscreenBpp() = tmp; } } // -rasterizer else if (strncmp(token,"rasterizer",XMin((int)(ptr-token),(int)(sizeof("rasterizer")-1)))==0) { XString value; if (!_ComputeParamValue(ptr2,value)) { return FALSE; } int tmp = 0; int tmp2 = 0; if(sscanf(value.CStr(),"%d,%d",&tmp,&tmp2)==2) { CCustomPlayer::Instance().RasterizerFamily() = tmp; CCustomPlayer::Instance().RasterizerFlags() = tmp2; } } else { // unknow parameter return FALSE; } } return TRUE; } BOOL CCustomPlayerApp::_ReadConfig(XString& oFilename, const char*& oBufferFile, XDWORD& oSize) { const char* cmdLine = GetCommandLine(); const char* ptr = 0; // the command line start with a '"' (it means the first parameters // contains at least one space) if (*cmdLine=='"') { // the first parameter is something like // "e:\directory name\customplayer.exe" // here we look for the second '"' to be after // the first parameter ptr = strchr(cmdLine+1,'"'); if (!ptr) { // cannot find it. // the command line is invalid return FALSE; } // move on the character after the second '"' ptr++; ptr = _SkipBlank(ptr); } else { // if there is no space in the first parameter, the // first space we can found is the one after the first parameter // if any ptr = strchr(cmdLine,' '); if (ptr) { ptr = _SkipBlank(ptr); } } /* if (ptr==0 || *ptr=='\0') { // there is no parameter on the command line (excepted the name of the exe) // try to read the "internal" configuration return _ReadInternalConfig(oBufferFile,oSize); } */ // any argument must begin with a '-' if (*ptr!='-') { return FALSE; } // read the command line return _ReadCommandLine(ptr,oFilename); } BOOL CCustomPlayerApp::_ReadInternalConfig(const char*& oBufferFile, XDWORD& oSize) { // NOTE: the internal configuration is not supported at this time // The idea behind "internal" configuration is to embed all data needed by the player // in the executable itself. The vmo and the parameters can be happend to the executable file. // In ouput oBufferFile must contains the address where the vmo is located in memory and // oSize must contains the size of the vmo in memory. return FALSE; } ATOM CCustomPlayerApp::_RegisterClass() { // register window classes WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; wcex.lpfnWndProc = (WNDPROC)_MainWindowWndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = m_hInstance; HICON icon = NULL; icon = (HICON) LoadImage(NULL,TEXT("app.ico"),IMAGE_ICON,16, 16,LR_LOADFROMFILE); if (icon) { wcex.hIcon = icon; }else{ wcex.hIcon = LoadIcon(IDI_VIRTOOLS); } wcex.hCursor = NULL; wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.lpszClassName = m_PlayerClass.CStr(); wcex.hIconSm = icon; WNDCLASS MyRenderClass; ZeroMemory(&MyRenderClass,sizeof(MyRenderClass)); MyRenderClass.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; MyRenderClass.lpfnWndProc = (WNDPROC)_MainWindowWndProc; MyRenderClass.hInstance = m_hInstance; MyRenderClass.lpszClassName = m_RenderClass.CStr(); ::RegisterClass(&MyRenderClass); return ::RegisterClassEx(&wcex); } #include <WindowsX.h> void CCustomPlayerApp::StartMove(LPARAM lParam) { nMMoveX = LOWORD(lParam); nMMoveY = HIWORD(lParam); } ////////////////////////////////////////////////////////////////////////// void CCustomPlayerApp::DoMMove(LPARAM lParam, WPARAM wParam) { if(wParam & MK_LBUTTON) { //if mouse is down; window is being dragged. RECT wnrect; GetWindowRect(this->m_MainWindow,&wnrect); //get window restraints MoveWindow(this->m_MainWindow,wnrect.left+(LOWORD(lParam)-nMMoveX),wnrect.top+(HIWORD(lParam)-nMMoveY),wnrect.right - wnrect.left,wnrect.bottom - wnrect.top,true); } } LRESULT CALLBACK CCustomPlayerApp::_MainWindowWndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) { switch(message) { case WM_DROPFILES: // Load any dropped file { /*char FileName[_MAX_PATH]; HDROP hdrop=(HDROP)wParam; DragQueryFile(hdrop,0,FileName,_MAX_PATH); GetPlayer().Reset(); GetPlayer().m_CKContext->ClearAll(); if (GetPlayer.m_RenderContext) { //GetPlayer.m_RenderContext->Clear(); } GetPlayer()._Load(FileName); GetPlayer()._FinishLoad(); break;*/ } case WM_MOUSEMOVE: { if (GetPlayer().GetPAppStyle()->g_MouseDrag==1) { GetApp()->DoMMove(lParam,wParam); } } case WM_ACTIVATEAPP: { CCustomPlayer& player = CCustomPlayer::Instance(); player.OnActivateApp(wParam); } break; // Minimum size of the player window case WM_GETMINMAXINFO: // this message is not very useful because // the main window of the player is not resizable ... // but perhaps it will change so we manage this message. { CCustomPlayer& player = CCustomPlayer::Instance(); if((LPMINMAXINFO)lParam) { ((LPMINMAXINFO)lParam)->ptMinTrackSize.x=player.MininumWindowedWidth(); ((LPMINMAXINFO)lParam)->ptMinTrackSize.y=player.MininumWindowedHeight(); } } break; // Sends a Message "OnClick" or "OnDblClick" if any object is under mouse cursor case WM_LBUTTONDBLCLK: case WM_LBUTTONDOWN: { CCustomPlayer& player = CCustomPlayer::Instance(); player.OnMouseClick(message); if (GetPlayer().GetPAppStyle()->g_MouseDrag==1) { GetApp()->StartMove(lParam); } } break; // Size and focus management case WM_SIZE: // if the window is maximized or minimized // we get/lost focus. { CCustomPlayer& player = CCustomPlayer::Instance(); if (wParam==SIZE_MINIMIZED) { player.OnFocusChange(FALSE); } else if (wParam==SIZE_MAXIMIZED) { player.OnFocusChange(TRUE); } } break; // Manage system key (ALT + KEY) case WM_SYSKEYDOWN: { CCustomPlayer& player = CCustomPlayer::Instance(); return player.OnSysKeyDownMainWindow(theApp.m_Config,(int)wParam); } break; // Repaint main frame case WM_PAINT: { CCustomPlayer& player = CCustomPlayer::Instance(); player.OnPaint(); } break; // The main windows has been closed by the user case WM_CLOSE: PostQuitMessage(0); break; // Focus management case WM_KILLFOCUS: case WM_SETFOCUS: { CCustomPlayer& player = CCustomPlayer::Instance(); player.OnFocusChange(message==WM_SETFOCUS); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return DefWindowProc(hWnd, message, wParam, lParam); } LRESULT CALLBACK CCustomPlayerApp::_LoadingDlgWndProc(HWND hDlg,UINT message,WPARAM wParam,LPARAM lParam) { switch (message) { case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; } <file_sep>#include <CKALL.h> CKERROR CreateKeyWaiter2BehaviorProto(CKBehaviorPrototype **pproto); int KeyWaiter2(const CKBehaviorContext& behcontext); int ReadKey2(const CKBehaviorContext& behcontext); CKERROR KeyWaiter2CallBack(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorKeyWaiter2Decl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Key Waiter2"); od->SetDescription("Waits for a key to be pressed."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Key: </SPAN>key to wait for. This is chosen in the parameter dialog box by first clicking "Select Key" and then pressing the key to wait for. The desired key will then appear to the right of "Select Key".<BR> <BR> <SPAN CLASS=setting>Wait For Any Key: </SPAN>if TRUE, the building block will wait any key to be pressed. The input parameter is deleted, and a output parameter is created; and in this case the output parameter retrieves the pressed key.<BR> Useful for "Press any key to continue..." capabilities.<BR> <BR> Waits for a key to be pressed. If the setting parameter 'Wait Any Key' is set to FALSE, this building block will wait for a specific given key (default), if set to TRUE, then it will wait for anykey to be pressed, retrieving this key as an output parameter.<BR> <BR> See Also: Switch On Key, Key Event.<BR> */ od->SetCategory("Controllers/Keyboard"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x60280837,0x38976869)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("mw"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateKeyWaiter2BehaviorProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->NeedManager(INPUT_MANAGER_GUID); return od; } CKERROR CreateKeyWaiter2BehaviorProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Key Waiter2"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("StopIt"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Key", CKPGUID_KEY); proto->DeclareSetting("Wait For Any Key", CKPGUID_BOOL, "FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(KeyWaiter2); proto->SetBehaviorCallbackFct(KeyWaiter2CallBack); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS|CKBEHAVIOR_INTERNALLYCREATEDOUTPUTPARAMS)); *pproto = proto; return CK_OK; } /*******************************************************/ /* CALLBACK */ /*******************************************************/ CKERROR KeyWaiter2CallBack(const CKBehaviorContext& behcontext){ CKBehavior* beh = behcontext.Behavior; switch( behcontext.CallbackMessage ){ case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { CKBOOL anyKey=FALSE; beh->GetLocalParameterValue(0, &anyKey); CKParameterIn *pin = beh->GetInputParameter(0); if( anyKey ){ // wait any Key beh->SetFunction(ReadKey2); if( pin ){ CKDestroyObject( beh->RemoveInputParameter(0) ); beh->CreateOutputParameter("Key", CKPGUID_KEY); } } else { // wait specific Key beh->SetFunction(KeyWaiter2); if( !pin ){ CKDestroyObject( beh->RemoveOutputParameter(0) ); beh->CreateInputParameter("Key", CKPGUID_KEY); } } } break; } return CKBR_OK; } /*******************************************************/ /* Main Function 1 */ /*******************************************************/ int KeyWaiter2(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKInputManager* input = (CKInputManager*)behcontext.Context->GetManagerByGuid(INPUT_MANAGER_GUID); if (!input){ behcontext.Context->OutputToConsoleEx("Can't get the Input Manager"); return CKBR_GENERICERROR; } if ( beh->IsInputActive( 1 ) ) { beh->ActivateInput( 0 , FALSE); beh->ActivateInput( 1 , FALSE); beh->ActivateOutput(0,FALSE); return CKBR_OK; } int key = 0; beh->GetInputParameterValue(0,&key); if( input->IsKeyDown(key) ){ // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0,TRUE); return CKBR_OK; } return CKBR_ACTIVATENEXTFRAME; } /*******************************************************/ /* Main Function 2 */ /*******************************************************/ int ReadKey2(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKInputManager* input = (CKInputManager*)behcontext.Context->GetManagerByGuid(INPUT_MANAGER_GUID); if (!input){ behcontext.Context->OutputToConsoleEx("Can't get the Input Manager"); return CKBR_GENERICERROR; } if ( beh->IsInputActive( 1 ) ) { beh->ActivateInput( 0 , FALSE); beh->ActivateInput( 1 , FALSE); beh->ActivateOutput(0,FALSE); return CKBR_OK; } CKDWORD key = 0; if(input->GetKeyFromBuffer(0,key) == KEY_PRESSED) { // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0,TRUE); // write the key beh->SetOutputParameterValue(0,&key); return CKBR_OK; } return CKBR_ACTIVATENEXTFRAME; } <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // General Camera Orbit // // Note : Defines some general functions for the // Camera Orbit Behaviors. // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #ifndef GENERALCAMERAORBIT_H #define GENERALCAMERAORBIT_H // Include the CK library // Defines a new type typedef void (*INPUTPROCESSFUNCTION) (VxVector* RotationAngles, CKBehavior* beh, CKInputManager *input, float delta, CKBOOL &Returns, CKBOOL &Stopping); // Infinite Value for reference #define INF 12345789 #define STEP 0.0001f // General Input Parameters #define IN_TARGET_POS 0 #define IN_TARGET_REF 1 #define IN_SPEED_MOVE 2 #define IN_SPEED_RETURN 3 #define IN_MIN_H 4 #define IN_MAX_H 5 #define IN_MIN_V 6 #define IN_MAX_V 7 #define IN_SPEED_ZOOM 8 #define IN_MIN_ZOOM 9 #define IN_MAX_ZOOM 10 // General Local Parameters and Settings #define LOCAL_INIT 0 #define LOCAL_ROT 1 #define LOCAL_STOPPING 2 #define LOCAL_LIMITS 3 #define LOCAL_RETURN 4 // Joystick Additional Settings #define LOCAL_JOY_NB 5 #define LOCAL_JOY_ZIN 6 #define LOCAL_JOY_ZOUT 7 #define LOCAL_JOY_INVERSE 8 #define LOCAL_JOY_THRESHOLD 9 // Mouse // Keyboard Additional Settings #define LOCAL_KEY_LEFT 5 #define LOCAL_KEY_RIGHT 6 #define LOCAL_KEY_UP 7 #define LOCAL_KEY_DOWN 8 #define LOCAL_KEY_ZIN 9 #define LOCAL_KEY_ZOUT 10 // Generic Additionnal Inputs #define INPUT_LEFT 2 #define INPUT_RIGHT 3 #define INPUT_UP 4 #define INPUT_DOWN 5 #define INPUT_ZOOMIN 6 #define INPUT_ZOOMOUT 7 #define LOCAL_RETURNING 5 // Defines the functions of this file. CKERROR FillGeneralCameraOrbitProto(CKBehaviorPrototype *proto); int GeneralCameraOrbit(const CKBehaviorContext& behcontext,INPUTPROCESSFUNCTION InputFunction); CKERROR GeneralCameraOrbitCallback(const CKBehaviorContext& behcontext); #endif <file_sep>SET devdir=X:\sdk\msvc8\Common7\IDE\ SET devexe=X:\sdk\msvc8\Common7\IDE\devenv.com SET solution=X:\ProjectRoot\svn\pearls-media\private\virtools\vtPhysX\build4\vs2005Dev41\vtPhysX.sln REM cd %devdir% %devexe% %solution% /out x:\log52005.txt /Build "ReleaseDemo" <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xLogger.h" CKObjectDeclaration *FillBehaviorDOBindDecl(); CKERROR CreateDOBindProto(CKBehaviorPrototype **); int DOBind(const CKBehaviorContext& behcontext); CKERROR DOBindCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorDOBindDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DOBind"); od->SetDescription("Binds an distributed object to a BeObject"); od->SetCategory("TNL/Distributed Objects"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x4691107e,0x59ae518d)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDOBindProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } enum bbIn { bbI_ON, }; enum bbOut { bbO_ON, bbO_ERROR }; enum bbPO_TIME { bbPO_ERROR }; CKERROR CreateDOBindProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("DOBind"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareOutput("Exit On"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Distributed Object ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Object", CKPGUID_BEOBJECT, "0"); proto->DeclareOutParameter("Error", CKPGUID_STRING, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETEROUTPUTS )); proto->SetFunction(DOBind); proto->SetBehaviorCallbackFct(DOBindCB); *pproto = proto; return CK_OK; } int DOBind(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterOut *pout = beh->GetOutputParameter(bbPO_ERROR); XString errorMesg("No network connection !"); ////////////////////////////////////////////////////////////////////////// //connection id : int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { errorMesg = "No network connection !"; pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(bbO_ERROR); return 0; } //we come in by input off : if (beh->IsInputActive(bbI_ON)) { beh->ActivateInput(bbI_ON,FALSE); int doID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,1); CKBeObject *beObject = (CKBeObject*)beh->GetInputParameterObject(2); if (!beObject) { errorMesg = "No Object given !"; pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(bbO_ERROR); return 0; } if (beObject) { CKSTRING oName = beObject->GetName(); int oID = beObject->GetID(); IDistributedObjects *doInterface = cin->getDistObjectInterface(); xDistributedObject *dObject = doInterface->get(doID); if (dObject) { ////////////////////////////////////////////////////////////////////////// switch(beObject->GetClassID()) { case CKCID_3DENTITY: { if (dObject->getDistributedClass()->getEnitityType() == E_DC_BTYPE_3D_ENTITY ) { dObject->setEntityID(oID); DWORD doFlags = dObject->getInterfaceFlags(); doFlags |=E_DO_BINDED; dObject->setInterfaceFlags(doFlags); errorMesg = "No error"; pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(bbO_ON); xLogger::xLog(ELOGINFO,XL_START,"binding object:% to dist object :%d",beObject->GetName(),doID); return 0; //beh->ActivateOutput(bbO_ERROR); }else { errorMesg = "Distributed object class doesn't match BeObject class"; pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(bbO_ERROR); return 0; } break; } } }else { errorMesg = "No distributed object found with this ID!"; pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(bbO_ERROR); return 0; } } beh->ActivateOutput(bbO_ON); } /* vtDistributedObjectsArrayType *distObjects = cin->getDistributedObjects(); vtDistObjectIt begin = distObjects->begin(); vtDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { xDistributedClass *_class = dobj->GetDistributedClass(); if (_class) { XString name(dobj->GetName().getString()); if (_class->GetEnitityType() == E_DC_BTYPE_3D_ENTITY ) { if (dobj->getInterfaceFlags() == E_DO_CREATED) { //output do's creation time float cTime = dobj->getCreationTime()/1000.0f; beh->SetOutputParameterValue(bbPO_TIME,&cTime); //output do's name CKParameterOut *pout = beh->GetOutputParameter(bbPO_NAME); pout->SetStringValue(name.Str()); //output do's network id int serverID = dobj->GetServerID(); beh->SetOutputParameterValue(bbPO_OID,&serverID); //output do's network id int userID = dobj->GetUserID(); beh->SetOutputParameterValue(bbPO_UID,&userID); //set do's interface flags dobj->setInterfaceFlags(E_DO_PROCESSED); CKParameterOut *poutE = beh->GetOutputParameter(bbPO_ERROR); XString errorMesg("No Error"); poutE->SetStringValue(errorMesg.Str()); beh->ActivateOutput(bbO_OBJECT); } } } } begin++; } */ return 0; } CKERROR DOBindCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#include "CPStdAfx.h" #ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. #define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif #include <afxwin.h> // MFC core and standard components #include <atlbase.h> // CComPtr, USES_CONVERSION #include "mdexceptions.h" #include "commonhelpers.h" CString GetShellExecuteError(UINT u) { CString s; switch (u) { case 0: s=_T("The operating system is out of memory or resources."); break; case ERROR_FILE_NOT_FOUND: s=_T("The specified file was not found."); break; case ERROR_PATH_NOT_FOUND: s=_T("The specified path was not found."); break; case ERROR_BAD_FORMAT: s=_T("The .exe file is invalid (non-Microsoft Win32 .exe or error in .exe image)."); break; case SE_ERR_ACCESSDENIED: s=_T("The operating system denied access to the specified file."); break; case SE_ERR_ASSOCINCOMPLETE:s=_T("The file name association is incomplete or invalid."); break; case SE_ERR_DDEBUSY: s=_T("The Dynamic Data Exchange (DDE) transaction could not be completed because other DDE transactions were being processed."); break; case SE_ERR_DDEFAIL: s=_T("The DDE transaction failed."); break; case SE_ERR_DDETIMEOUT: s=_T("The DDE transaction could not be completed because the request timed out."); break; case SE_ERR_DLLNOTFOUND: s=_T("The specified dynamic-link library (DLL) was not found."); break; case SE_ERR_NOASSOC: s=_T("There is no application associated with the given file name extension. This error will also be returned if you attempt to print a file that is not printable."); break; case SE_ERR_OOM: s=_T("There was not enough memory to complete the operation."); break; case SE_ERR_SHARE: s=_T("A sharing violation occurred"); break; default: s.Format(_T("Error Number %d"), u); break; } return s; } CString MyStrRetToString(const LPITEMIDLIST pidl, const STRRET *strret) { // StrRetToStr() is not always available (e.g. on Windows 98). // So we use an own function instead. USES_CONVERSION; CString s; switch (strret->uType) { case STRRET_CSTR: s= strret->cStr; break; case STRRET_OFFSET: s= A2T((char *)pidl + strret->uOffset); break; case STRRET_WSTR: s= W2T(strret->pOleStr); break; } return s; } void MyShellExecute(HWND hwnd, LPCTSTR lpOperation, LPCTSTR lpFile, LPCTSTR lpParameters, LPCTSTR lpDirectory, INT nShowCmd) throw (CException *) { CWaitCursor wc; UINT h= (UINT)ShellExecute(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd); if (h <= 32) MdThrowStringExceptionF(_T("ShellExecute failed: %1!s!"), GetShellExecuteError(h)); } CString GetBaseNameFromPath(LPCTSTR path) { CString s= path; int i= s.ReverseFind(_T('\\')); if (i < 0) return s; return s.Mid(i + 1); } bool FileExists(LPCTSTR path) { CFileFind finder; BOOL b= finder.FindFile(path); if (b) { finder.FindNextFile(); return !finder.IsDirectory(); } else { return false; } } CString LoadString(UINT resId) { return MAKEINTRESOURCE(resId); } CString GetAppFileName() { CString s; VERIFY(GetModuleFileName(NULL, s.GetBuffer(_MAX_PATH), _MAX_PATH)); s.ReleaseBuffer(); return s; } CString GetAppFolder() { CString s= GetAppFileName(); int i= s.ReverseFind(_T('\\')); ASSERT(i >= 0); s= s.Left(i); return s; } CString MyGetFullPathName(LPCTSTR relativePath) { LPTSTR dummy; CString buffer; DWORD len = _MAX_PATH; DWORD dw = GetFullPathName(relativePath, len, buffer.GetBuffer(len), &dummy); buffer.ReleaseBuffer(); while (dw >= len) { len+= _MAX_PATH; dw = GetFullPathName(relativePath, len, buffer.GetBuffer(len), &dummy); buffer.ReleaseBuffer(); } if (dw == 0) { TRACE("GetFullPathName(%s) failed: GetLastError returns %u\r\n", relativePath, GetLastError()); return relativePath; } return buffer; } <file_sep>#include "StdAfx.h" #include "virtools/vtcxglobal.h" #include "windows.h" #include "Python.h" #include "vt_python_funcs.h" #include "pyembed.h" #include "InitMan.h" CKObjectDeclaration *FillBehaviorDestroyPythonDecl(); CKERROR CreateDestroyPythonProto(CKBehaviorPrototype **); int DestroyPython(const CKBehaviorContext& behcontext); CKERROR DestroyPythonCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorDestroyPythonDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DestroyPython"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x78634039,0x1d845726)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDestroyPythonProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Python"); return od; } CKERROR CreateDestroyPythonProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("DestroyPython"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( DestroyPython ); *pproto = proto; return CK_OK; } int DestroyPython(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; beh->ActivateInput(0,FALSE); vt_python_man *pm = (vt_python_man*)ctx->GetManagerByGuid(INIT_MAN_GUID); DestroyPython(); beh->ActivateOutput(0); return CKBR_OK; } <file_sep>#include "XLoader.h" #include "InitGuid.h" #include "CKAll.h" #include "pCommon.h" #define X_PLUGIN_VERSION 0x0000001 #define X_READER_GUID CKGUID(0x499d11a7,0x24aa03b6) #ifdef CK_LIB #define RegisterBehSDatorDeclarations Register_SDatReader_BehaviorDeclarations #define InitInstance _SDatReader_InitInstance #define ExitInstance _SDatReader_ExitInstance #define CKGetPluginInfoCount CKGet_SDatReader_PluginInfoCount #define CKGetPluginInfo CKGet_SDatReader_PluginInfo #define g_PluginInfo g_SDatReader_PluginInfo #define CKGetReader CKGet_SDatReader_Reader #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #define CKGetReader CKGetReader #endif CKPluginInfo g_PluginInfo; /********************************************** Called by the engine when a file with the AVI extension is being loaded, a reader has to be created. ***********************************************/ CKDataReader *CKGetReader(int pos) { return new CKXReader(); } CKPluginInfo* CKGetPluginInfo(int index) { // Not Valid under Win NT 4 if (VxGetOs() == VXOS_WINNT4) return 0; g_PluginInfo.m_GUID=X_READER_GUID; g_PluginInfo.m_Extension="dae"; g_PluginInfo.m_Description="NxStream Parser"; g_PluginInfo.m_Author="<NAME>"; g_PluginInfo.m_Summary="Loads xml files, created by Maya/<NAME>"; g_PluginInfo.m_Version=X_PLUGIN_VERSION; g_PluginInfo.m_InitInstanceFct=NULL; // g_PluginInfo.m_Type=CKPLUGIN_MODEL_READER; // Plugin Type return &g_PluginInfo; } CKPluginInfo g_PluginInfos; int CKGetPluginInfoCount() { return 1; } CKPluginInfo* CKXReader::GetReaderInfo() { return &g_PluginInfo; } ///////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //------- Returns the name of a LPDIRECTXFILEOBJECT XString GetFileObjectName(LPDIRECTXFILEOBJECT obj) { if (!obj) return XString(""); DWORD NameSize = 0; if (FAILED(obj->GetName(NULL,&NameSize))) return XString(""); if (!NameSize) return XString(""); NameSize++; XString Temp(NameSize); if (FAILED(obj->GetName(Temp.Str(),&NameSize))) return XString(""); return Temp; } ////////////////////////////////////////////////////////////////////////// CKERROR CKXReader::Load(CKContext* context,CKSTRING FileName,CKObjectArray *array,CKDWORD LoadFlags,CKCharacter *carac) { if(!array) return CKERR_INVALIDPARAMETER; if(!FileName) return CKERR_INVALIDPARAMETER; HRESULT hr = S_OK; m_Context = context; m_LoadFlags = LoadFlags; m_FileName = FileName; XString filename(FileName); filename.Trim(); int ok = context->GetPathManager()->ResolveFileName(filename,DATA_PATH_IDX,-1); pSerializer *ser = pSerializer::Instance(); if (ser && ok==0 ) { ser->parseFile(filename.CStr(),0); //ser->loadCollection(filename.CStr()) } int t = 0; //LoadFromFileC(context,FileName,false,LoadFlags,array,"null"); return CK_OK; } ////////////////////////////////////////////////////////////////////////// BOOL CKXReader::LoadFromFileC(CKContext *ctx, XString filename, CKBOOL hidden, CKDWORD loadflags, CKObjectArray* targetArray, XString password) { CKBOOL result = false; return result; } <file_sep>/* * Tcp4u v 3.31 Last Revision 04/03/1998 3.30.02 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: tn4u.c * Purpose: telnet based-functions * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" /* ******************************************************************* */ /* */ /* Partie II : Lecture des trames de type Telnet */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------ */ /* TnReadLine : Lit une ligne de donnees (jusqu'à <LF>) */ /* retourne TN_ERROR, TN_TIMEOUT, TN_BUFFERFREED */ /* TN_OVERFLOW ou le nombre d'octets lus */ /* dans les deux derniers cas le buffer szBuf est */ /* renseigne. Si TN_SUCCESS il est <LF>-termine. */ /* ------------------------------------------------------------ */ int API4U TnReadLine (SOCKET s,LPSTR szBuf,UINT uBufSize,UINT uTimeOut,HFILE hf) { int Rc; Tcp4uLog (LOG4U_PROC, "TnReadLine"); Rc = InternalTnReadLine (s, szBuf, uBufSize, uTimeOut, hf); if (Rc==TN_SUCCESS) Tcp4uDump (szBuf, Strlen(szBuf), DUMP4U_RCVD); Tcp4uLog (LOG4U_EXIT, "TnReadLine"); return Rc; } /* TnReadLine */ int InternalTnReadLine (SOCKET s,LPSTR szBuf,UINT uBufSize,UINT uTimeOut, HFILE hf) { int Rc; if (s==INVALID_SOCKET || uBufSize==0) return TN_ERROR; /* ??? */ memset (szBuf, 0, uBufSize); Rc = InternalTcpRecvUntilStr (s, szBuf, & uBufSize, "\n", 1, TRUE, uTimeOut, hf); if (Rc>=TCP4U_SUCCESS && szBuf[uBufSize-1]=='\r') szBuf[uBufSize-1]=0 ; /* pas de translation des erreurs, timeout... */ return (Rc>=TCP4U_SUCCESS) ? TN_SUCCESS : Rc; } /* InternalTnReadLine */ /* ******************************************************************* */ /* */ /* Partie III : Etage Telnet Haut */ /* */ /* ******************************************************************* */ /* ------------------------------------------------------------ */ /* TnSend : Formatage d'une trame au format Telnet (terminée */ /* par <RC><LF> */ /* Retour par TN_ERROR, ou TN_SUCCESS. */ /* ------------------------------------------------------------ */ int API4U TnSend (SOCKET s, LPCSTR szString, BOOL bHighPriority, HFILE hf) { int Rc, Z; LPSTR p; Tcp4uLog (LOG4U_PROC, "TnSend"); Z = Strlen (szString)+sizeof ("\r\n")-1; p = Calloc (Z+1, 1); if (p==NULL) return TCP4U_INSMEMORY; Strcpy (p, szString); Strcat (p, "\r\n"); Rc = InternalTcpSend (s, p, Z, bHighPriority, hf); if (Rc==TCP4U_SUCCESS) Tcp4uDump (p, Z, DUMP4U_SENT); Free (p); Tcp4uLog (LOG4U_EXIT, "TnSend : return code %d", Rc); return Rc==TCP4U_SUCCESS ? TN_SUCCESS : TN_ERROR; } /* TnSend */ /* ------------------------------------------------------------ */ /* TnReadMultiLine : waits for a message from the remote peer */ /* This message can contain several lines */ /* As said in Telnet RFC, it depends on the */ /* 4th char. */ /* - A TN_XX code is returned */ /* 20.02.1998: A bug has been found and fixed by <NAME>.*/ /* The loop test was weak enough. */ /* 04.03.1998: rewritten according to the FTP spec (RFC 959) */ /* Should manage propoerly Text like : */ /* 123-First line */ /* Second line */ /* 234 A line beginning with numbers */ /* 123 The last line */ /* ------------------------------------------------------------ */ int API4U TnReadMultiLine (SOCKET ctrl_skt, LPSTR szInBuf, UINT uBufSize, UINT uTimeOut, HFILE hf) { int Rc, TnRc; unsigned nPos=0; Tcp4uLog (LOG4U_PROC, "TnReadMultiLine"); if (szInBuf==NULL || uBufSize==0) return TN_ERROR; memset (szInBuf, 0, uBufSize); do { /* add the <LF> character */ if (szInBuf[nPos] != 0) /* changed by Sergej */ { nPos+=Strlen (&szInBuf[nPos]); /* pointer sur la fin de ligne */ szInBuf[nPos++]='\n'; } Rc = InternalTnReadLine (ctrl_skt, &szInBuf[nPos], uBufSize-nPos-1, uTimeOut,hf); /* exit on - errors */ /* - buffer full */ /* - 3 digits at the beginning of the string */ /* not followed by HYPHEN */ } while ( nPos < uBufSize - 5 /* encore de la place (y compris pour \0) */ && Rc>=TCP4U_SUCCESS /* retour correct */ && ! (isdigit (szInBuf[nPos]) && szInBuf[nPos+3] != '-' ) ); /* supprime la derniere marque fin de ligne */ if (Rc>=TCP4U_SUCCESS) { Rc = TCP4U_SUCCESS; nPos+=Strlen (&szInBuf[nPos]); if (szInBuf[nPos-1]=='\r') szInBuf[nPos-1]=0; } /* translation du code de retour */ switch (Rc) { case TCP4U_TIMEOUT : TnRc = TN_TIMEOUT; break; case TCP4U_SUCCESS : Tcp4uDump (szInBuf, nPos, DUMP4U_RCVD); TnRc = TN_SUCCESS; break; case TCP4U_OVERFLOW : Tcp4uDump (szInBuf, nPos, "Overflow"); TnRc = TN_OVERFLOW; break; case TCP4U_SOCKETCLOSED : TnRc = TN_SOCKETCLOSED; break; case TCP4U_CANCELLED : TnRc = TN_CANCELLED; break; default : TnRc = TN_ERROR; break; } Tcp4uLog (LOG4U_EXIT, "TnReadMultiLine: return code %d", TnRc); return TnRc; } /* TnReadMultiLine */ /* ------------------------------------------------------------ */ /* TnSendMultiLine : Formatage d'une trame au format Telnet */ /* <LF> expanded into <RC><LF> */ /* Retour par TN_ERROR, ou TN_SUCCESS. */ /* ------------------------------------------------------------ */ int API4U TnSendMultiLine (SOCKET s, LPCSTR szString, BOOL bEnd, HFILE hf) { int Rc, Z; LPCSTR p; LPSTR pString; Tcp4uLog (LOG4U_PROC, "TnSendMultiLine"); /* counts the number of <LF> char */ for ( Z=0, p=szString ; *p!=0 ; p++, Z++ ) if (*p=='\n') Z++; /* put the string into a new writeable buffer */ pString = Calloc (Z+sizeof ("\r\n"), 1); if (pString==NULL) return TCP4U_INSMEMORY; for ( Z=0, p=szString ; *p!=0 ; p++, Z++ ) { if (*p=='\n' && (p>szString && *(p-1)!='\r')) pString[Z++] = '\r'; pString[Z] = *p; } if (bEnd) { pString[Z++] = '\r'; pString[Z++] = '\n'; } pString[Z] = 0; /* Job has been done, send the string and exit */ Rc = InternalTcpSend (s, pString, Z, FALSE, hf); if (Rc==TCP4U_SUCCESS) Tcp4uDump (pString, Z, DUMP4U_SENT); Free (pString); Tcp4uLog (LOG4U_EXIT, "TnSendMultiLine : return code %d", Rc); return Rc==TCP4U_SUCCESS ? TN_SUCCESS : TN_ERROR; } /* TnSendMultiLine */ /* ------------------------------------------------------------ */ /* TnGetAnswerCode : Attend une réponse du serveur et rend le */ /* code numérique (les 3 premiers octets) */ /* renvoyé par le serveur. */ /* - Retourne un nombre entre 100 et 999 si la */ /* fonction s'est bien passée, sinon un code */ /* d'erreur TN_ERROR, TN_TIMEOUT... */ /* ------------------------------------------------------------ */ int API4U TnGetAnswerCode (SOCKET ctrl_skt, LPSTR szInBuf, UINT uBufSize, UINT uTimeOut, HFILE hf) { int Rc; Tcp4uLog (LOG4U_PROC, "TnReadAnswerCode"); Rc = TnReadMultiLine (ctrl_skt, szInBuf, uBufSize, uTimeOut, hf); if (Rc==TN_SUCCESS) Rc = Tcp4uAtoi (szInBuf); Tcp4uLog (LOG4U_EXIT, "TnReadAnswerCode: return code %d", Rc); return Rc; } /* TnGetAnswerCode */ <file_sep>#ifndef __PMANAGERTYPES_H__ #define __PMANAGERTYPES_H__ #include "pNxSDKParameter.h" typedef enum pManagerFlags { PMF_DONT_DELETE_SCENES=1<<1, PMF_DONT_USE_HARDWARE=1<<2, }; struct pTriggerEntry { NxShape *shapeA; NxShape *shapeB; int triggerEvent; bool triggered; CK3dEntity *triggerBody; CK3dEntity *otherObject; CK3dEntity *triggerShapeEnt; pRigidBody *triggerBodyB; pRigidBody *otherBodyB; pTriggerEntry() { shapeA = shapeB = NULL; triggerShapeEnt =otherObject = triggerBody = NULL; triggerBodyB = otherBodyB = NULL; triggerEvent; triggered = false; } }; typedef XArray<pTriggerEntry>pTriggerArray; //################################################################ // // Help Structures, used by the manager only // //---------------------------------------------------------------- // //! \brief Container to maintain multiple worlds // typedef XHashTable<pWorld*,CK3dEntity*> pWorldMap; typedef XHashTable<pWorld*,CK3dEntity*>::Iterator pWorldMapIt; typedef XArray<CK_ID>pBodyList; typedef XArray<CK_ID>::Iterator pBodyListIterator; typedef XHashTable<pRigidBodyRestoreInfo*,CK_ID> pRestoreMap; typedef XHashTable<pRigidBodyRestoreInfo*,CK_ID>::Iterator pRestoreMapIt; //---------------------------------------------------------------- // //! \brief Function pointer. Used in custom parameter structures to populate // found xml types // typedef XString (pFactory::*PFEnumStringFunction)(const TiXmlDocument * doc); //---------------------------------------------------------------- // //! \brief Function pointer to link object registrations per attribute type // typedef int (*ObjectRegisterFunction)(CK3dEntity*,int,bool,bool); //---------------------------------------------------------------- // //! \brief Meta data for ObjectRegisterFunction. Used for attribute callbacks. // struct ObjectRegistration { CKGUID guid; ObjectRegisterFunction rFunc; ObjectRegistration(CKGUID _guid,ObjectRegisterFunction _func) : guid(_guid) , rFunc(_func) { } }; //---------------------------------------------------------------- // //! \brief Meta data for attributes callbacks when the scene is playing. <br> //! Virtools is not initializing the attributes parameter correctly. // Ths structur is used to track data to the next frame. // struct pAttributePostObject { CK_ID objectId; ObjectRegisterFunction func; int attributeID; pAttributePostObject() : objectId(-1) , func(NULL) , attributeID(-1){} pAttributePostObject(CK_ID _id,ObjectRegisterFunction _func,int _attributeID) : objectId(_id) , func(_func) , attributeID(_attributeID) { } }; //---------------------------------------------------------------- // //! \brief Container type to store objects with uninitialized attribute parameters. // typedef XArray<pAttributePostObject>PostRegistrationArrayType; typedef XArray<pAttributePostObject>::Iterator PostRegistrationArrayIteratorType; //---------------------------------------------------------------- // //! \brief Container to store custom function pointer per attribute type // typedef XHashTable<ObjectRegisterFunction,int>AttributeFunctionArrayType; typedef XHashTable<ObjectRegisterFunction,int>::Iterator AttributeFunctionArrayIteratorType; //---------------------------------------------------------------- // //! \brief CustomParametersArrayType is responsible to track custom structures and its default value. //! typedef XHashTable<vtTools::ParameterTools::CustomStructure*,CKGUID>CustomParametersArrayType; typedef XHashTable<vtTools::ParameterTools::CustomStructure*,CKGUID>::Iterator CustomParametersArrayIteratorType; struct pSDKParameters { float SkinWidth; float DefaultSleepLinVelSquared ; float DefaultSleepAngVel_squared; float BounceThreshold ; float DynFrictScaling ; float StaFrictionScaling; float MaxAngularVelocity ; float ContinuousCD ; float AdaptiveForce ; float CollVetoJointed ; float TriggerTriggerCallback ; float CCDEpsilon ; float SolverConvergenceThreshold ; float BBoxNoiseLevel ; float ImplicitSweepCacheSize ; float DefaultSleepEnergy ; float ConstantFluidMaxPackets ; float ConstantFluidMaxParticlesPerStep ; float AsynchronousMeshCreation ; float ForceFieldCustomKernelEpsilon ; float ImprovedSpringSolver ; int disablePhysics; pSDKParameters() { SkinWidth = 0.25f; DefaultSleepLinVelSquared = 0.15f*0.15f; DefaultSleepAngVel_squared = 0.15f*0.15f; BounceThreshold = -2.0f ; DynFrictScaling =1.0f; StaFrictionScaling = 1.0f; MaxAngularVelocity = 7.0f ; ContinuousCD = 0.0f; AdaptiveForce = 1.0f; CollVetoJointed = 1.0f; TriggerTriggerCallback= 1.0f ; CCDEpsilon = 0.01f; SolverConvergenceThreshold = 0.0f ; BBoxNoiseLevel =0.001f ; ImplicitSweepCacheSize = 5.0f ; DefaultSleepEnergy = 0.005f; ConstantFluidMaxPackets = 925.0f ; ConstantFluidMaxParticlesPerStep = 4096 ; ImprovedSpringSolver = 1.0f; disablePhysics = 0; } }; class pRemoteDebuggerSettings { public : XString mHost; int port; int enabled; pRemoteDebuggerSettings() { mHost= "localhost"; port = 5425; enabled = 0; } }; #endif // __PMANAGERTYPES_H__<file_sep>SET devdir=X:\sdk_ide\msvc8\Common7\IDE SET devexe=X:\sdk_ide\msvc8\Common7\IDE\devenv.exe SET solution=X:\ProjectRoot\svnLocal\local\vtPhysX\build4\vs2005\vtAgeia.sln cd %devdir% %devexe% %solution% /out x:\log.txt /Build "Debug|Win32" <file_sep> #include "xNetInterface.h" #include "vtConnection.h" #include <tnlAsymmetricKey.h> //#include "windows.h" TNL::RefPtr<xNetInterface>m_NetInterfaceServer = NULL; TNL::RefPtr<xNetInterface>GetServerInterface(){ return m_NetInterfaceServer;} const char *localBroadcastAddress = "IP:broadcast:28999"; const char *localHostAddress = "IP:127.0.0.1:28999"; const char *localServerAddress ="IP:Any:28999"; class DedicatedServerLogConsumer : public TNL::LogConsumer { public: void logString(const char *string) { //ctx()->OutputToConsoleEx("%s\n",string); printf("%s\n\n", string); } } gDedicatedServerLogConsumer; using namespace TNL; int main(int argc, const char **argv) { ////////////////////////////////////////////////////////////////////////// //set up logging : //TNLLogEnable(LogGhostConnection, true); TNLLogEnable(LogNetInterface,true); ////////////////////////////////////////////////////////////////////////// //create a server : //xNetworkFactory::xSCreateServerInterface(m_NetInterfaceServer,localServerAddress,localBroadcastAddress); TNL::Address *add = new TNL::Address("IP:Any:28999"); TNL::Address *addBC=new TNL::Address("IP:broadcast:28999"); m_NetInterfaceServer = new xNetInterface(true,*add,*addBC); TNL::AsymmetricKey *theKey = new TNL::AsymmetricKey(32); m_NetInterfaceServer->setPrivateKey(theKey); m_NetInterfaceServer->setRequiresKeyExchange(false); // m_NetInterfaceServer->GetDistObjectInterface()->SetNetworkInterface(m_NetInterfaceServer); if (m_NetInterfaceServer) { m_NetInterfaceServer->setAllowsConnections(true); //m_NetInterfaceServer->GetDistObjectInterface()->SetNetworkInterface(m_NetInterfaceServer); } //Sleep(2000); if (GetServerInterface()) { logprintf("\t Server Created"); } for (;;) { GetServerInterface()->tick(); TNL::Platform::sleep(1); } return 0; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBSetParDecl(); CKERROR CreatePBSetParProto(CKBehaviorPrototype **pproto); int PBSetPar(const CKBehaviorContext& behcontext); CKERROR PBSetParCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_CollisionGroup, bbI_GroupsMask, bbI_Flags, bbI_TFlags, bbI_LinDamp, bbI_AngDamp, bbI_MassOffset, bbI_ShapeOffset, }; #define BB_SSTART 0 BBParameter pInMap22[] = { BB_SPIN(bbI_CollisionGroup,CKPGUID_INT,"Collision Group",""), BB_SPIN(bbI_GroupsMask,VTS_FILTER_GROUPS,"Group Mask","0.0"), BB_SPIN(bbI_Flags,VTF_BODY_FLAGS,"Body Flags",""), BB_SPIN(bbI_TFlags,VTF_BODY_TRANS_FLAGS,"Transformation Lock Flags",""), BB_SPIN(bbI_LinDamp,CKPGUID_FLOAT,"Linear Damping","0.0"), BB_SPIN(bbI_AngDamp,CKPGUID_FLOAT,"Angular Damping",""), BB_SPIN(bbI_MassOffset,CKPGUID_VECTOR,"Mass Offset",""), BB_SPIN(bbI_ShapeOffset,CKPGUID_VECTOR,"Pivot Offset",""), }; #define gPIMAP pInMap22 //************************************ // Method: FillBehaviorPBSetParDecl // FullName: FillBehaviorPBSetParDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPBSetParDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetPar"); od->SetCategory("Physic/Body"); od->SetDescription("Sets physic parameters."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x137e7ec4,0x4ca85a4b)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBSetParProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBSetParProto // FullName: CreatePBSetParProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBSetParProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetPar"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PBSetPar PBSetPar is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies various physical parameters.<br> <h3>Technical Information</h3> \image html PBSetPar.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body or its sub shape. <BR> <SPAN CLASS="pin">Collisions Group: </SPAN>Which collision group this body or the sub shape is part of.See pRigidBody::setCollisionsGroup(). <BR> <SPAN CLASS="pin">Groupsmask: </SPAN>Sets 128-bit mask used for collision filtering. It can be sub shape specific.See comments for ::pGroupsMask and pRigidBody::setGroupsMask() <BR> <SPAN CLASS="pin">Flags: </SPAN>Changes essential physic behavior. See pRigidBody::setFlags() <br> - This flags can be changed after the bodies registration : - Gravity - See pRigidBody::ennableGravity() - Kinematic - See pRigidBody::setKinematic() - Trigger Shape - See pRigidBody::enableTriggerShape() - Collisions Notify - See pRigidBody::enableCollisionsNotify() - Sleep - pRigidBody::setSleeping() or pRigidBody::isSleeping() <SPAN CLASS="pin">Transformation Locks: </SPAN>Locks a translation or orientation in a specific dimension. <BR> <SPAN CLASS="pin">Linear Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Angular Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Mass Offset: </SPAN>The new mass center in the bodies local space. <BR> <SPAN CLASS="pin">Pivot Offset: </SPAN>Specifies the shapes position in the bodies local space. See pRigidBody::setLocalShapePosition(). <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBSetEx.cpp </SPAN> */ proto->SetBehaviorCallbackFct( PBSetParCB ); BB_EVALUATE_SETTINGS(pInMap22) proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBSetPar); *pproto = proto; return CK_OK; } //************************************ // Method: PBSetPar // FullName: PBSetPar // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBSetPar(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) bbErrorME("No valid world object found"); body = GetPMan()->getBody(target); if (!body) bbErrorME("Object not physicalized"); BB_DECLARE_PIMAP; /************************************************************************/ /* retrieve settings state */ /************************************************************************/ BBSParameter(bbI_CollisionGroup); BBSParameter(bbI_Flags); BBSParameter(bbI_TFlags); BBSParameter(bbI_GroupsMask); BBSParameter(bbI_LinDamp); BBSParameter(bbI_AngDamp); BBSParameter(bbI_MassOffset); BBSParameter(bbI_ShapeOffset); if (sbbI_GroupsMask) { NxGroupsMask mask1; CKParameter *fConst1 = beh->GetInputParameter(BB_IP_INDEX(bbI_GroupsMask))->GetRealSource(); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; NxShape *dstShape = NULL; NxShape *mainshape = body->getMainShape(); if (mainshape==NULL) { int op = 2; op++; } NxShape *inputShape = body->_getSubShapeByEntityID(target->GetID()); if (mainshape==inputShape) { dstShape = mainshape; }else{ dstShape = inputShape; } mask1.bits0 = GetValueFromParameterStruct<int>(fConst1,0); mask1.bits1 = GetValueFromParameterStruct<int>(fConst1,1); mask1.bits2 = GetValueFromParameterStruct<int>(fConst1,2); mask1.bits3 = GetValueFromParameterStruct<int>(fConst1,3); if (dstShape) { dstShape->setGroupsMask(mask1); } } if (sbbI_CollisionGroup) { int collGroup = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_CollisionGroup)); body->setCollisionsGroup(collGroup,target); } if (sbbI_Flags) { int flags = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_Flags)); body->updateFlags(flags,target); } if (sbbI_TFlags) { int tflags = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_TFlags)); body->lockTransformation(tflags); } if (sbbI_LinDamp) { float lDamp = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_LinDamp)); body->setLinearDamping(lDamp); } if (sbbI_AngDamp) { float aDamp= GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_AngDamp)); body->setAngularDamping(aDamp); } if (sbbI_MassOffset) { VxVector mOffset= GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(bbI_MassOffset)); body->setMassOffset(mOffset); } if (sbbI_ShapeOffset) { VxVector sOffset= GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(bbI_ShapeOffset)); body->setLocalShapePosition(sOffset,target); } } beh->ActivateOutput(0); return 0; } //************************************ // Method: PBSetParCB // FullName: PBSetParCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBSetParCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; } <file_sep>#pragma once //by default these functions are called in DistributedNetworkClassDialogcallback.cpp //if you do not use callback (do not have DistributedNetworkClassDialogcallback.cpp), you should call these functions manually //to add a menu in Virtools Dev main menu. void InitMenu(); //to remove the menu from Virtools Dev main menu void RemoveMenu(); //to fill menu with your own commands void UpdateMenu(); #define STR_MAINMENUNAME "DistributedNetworkClassDialog Menu" <file_sep>vtWindowConsole.exe -d=0 -mode=server<file_sep>#include <StdAfx.h> #include "pCommon.h" #include "pConfig.h" #include "gConfig.h" #pragma message(__FILE__ NXPHYSXLOADERDLL_API ) void FindResourceX(); #ifdef WebPack extern CKERROR InitInstanceCamera(CKContext* context); extern CKERROR ExitInstanceCamera(CKContext* context); extern int RegisterCameraBeh(XObjectDeclarationArray *reg); #endif //---------------------------------------------------------------- // //! \brief Switches between static library or dll // #ifdef CK_LIB #define RegisterBehaviorDeclarations Register_VTPHYSX_BehaviorDeclarations #define InitInstance _VTPHYSX_InitInstance #define ExitInstance _VTPHYSX_ExitInstance #define CKGetPluginInfoCount CKGet_VTPHYSX_PluginInfoCount #define CKGetPluginInfo CKGet_VTPHYSX_PluginInfo #define g_PluginInfo g_PluginInfo #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #endif /* ******************************************************************* * Function: CKERROR InitInstance( CKContext* theContext ) * * Description : If no manager is used in the plugin these functions * are optional and can be exported. Virtools will call * 'InitInstance' when loading the behavior library and * 'ExitInstance' when unloading it. It is a good place * to perform Attributes Types declaration, registering new * enums or new parameter types. * * Parameters : CKContext* theContext * * * Returns : CKERROR * ******************************************************************* */ CKERROR InitInstanceBB(CKContext* context) { return CK_OK; } CKERROR ExitInstanceBB(CKContext* context) { return CK_OK; } /* ******************************************************************* * Function: CKERROR InitInstance( CKContext* theContext ) * * Description : If no manager is used in the plugin these functions * are optional and can be exported. Virtools will call * 'InitInstance' when loading the behavior library and * 'ExitInstance' when unloading it. It is a good place * to perform Attributes Types declaration, registering new * enums or new parameter types. * * Parameters : CKContext* theContext * * * Returns : CKERROR * ******************************************************************* */ CKERROR InitInstanceIM(CKContext* context){ #ifdef Webpack InitInstanceCamera(context); #endif PhysicManager* PM =new PhysicManager(context); context->ActivateManager(PM,TRUE); #ifdef DONGLE_VERSION PM->_initResources(0); #endif #ifndef DONGLE_VERSION PM->DongleHasBasicVersion =1; #endif // _DEBUG if(PM->DongleHasBasicVersion) { PM->_RegisterDynamicParameters(); PM->_RegisterParameters(); PM->_RegisterVSL(); #ifdef HAS_FLUIDS PM->_RegisterFluid_VSL(); #endif // HAS_FLUIDS PM->_RegisterParameterOperations(); PM->_registerWatchers(context); } return CK_OK; } /* ******************************************************************* * Function: CKERROR ExitInstance( CKContext* theContext ) * * Description : This function will only be called if the dll is * unloaded explicitely by a user in Virtools Dev interface * Otherwise the manager destructor will be called by Virtools * runtime directly. * * Parameters : CKContext* theContext * * Returns : CKERROR * ******************************************************************* */ CKERROR ExitInstanceIM(CKContext* context){ PhysicManager* PM =(PhysicManager*)context->GetManagerByGuid(GUID_MODULE_MANAGER); delete PM; #ifdef Webpack ExitInstanceCamera(context); #endif return CK_OK; } CKPluginInfo g_PluginInfo[2]; #include "base_macros.h" /* ******************************************************************* * Function: CKPluginInfo* CKGetPluginInfo( int index ) * * Description : This function takes an index and returns a corresponding plugin desciptor * * Parameters : * index, index of the plugin information to get * * Returns : pointer to the requested plugin information * ******************************************************************* */ PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index); /* ******************************************************************* * Function: int CKGetPluginInfoCount() * * Description : Returns the number of plugins in this DLL * * Parameters : * None. * * Returns : Number of plugins defined in this DLL * ******************************************************************* */ int CKGetPluginInfoCount(){return 2;} PLUGIN_EXPORT void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg); PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) { g_PluginInfo[0].m_Author = VTCX_AUTHOR; g_PluginInfo[0].m_Description = VTCX_API_ENTRY("PhysX Building Blocks"); g_PluginInfo[0].m_Extension = ""; g_PluginInfo[0].m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo[0].m_Version = 0x000001; g_PluginInfo[0].m_InitInstanceFct = InitInstanceBB; g_PluginInfo[0].m_ExitInstanceFct = ExitInstanceBB; g_PluginInfo[0].m_GUID = GUID_MODULE_BUILDING_BLOCKS; g_PluginInfo[1].m_Author =VTCX_AUTHOR; g_PluginInfo[1].m_Description =VTCX_API_ENTRY("PhysX Manager"); g_PluginInfo[1].m_Extension = ""; g_PluginInfo[1].m_Type = CKPLUGIN_MANAGER_DLL; g_PluginInfo[1].m_Version = 0x000001; g_PluginInfo[1].m_InitInstanceFct = InitInstanceIM; g_PluginInfo[1].m_ExitInstanceFct = ExitInstanceIM; g_PluginInfo[1].m_GUID = GUID_MODULE_MANAGER; g_PluginInfo[1].m_Summary = VTCX_API_ENTRY("PhysX Physic Manager"); return &g_PluginInfo[Index]; } /* ******************************************************************* * Function: void RegisterBehaviorDeclarations( XObjectDeclarationArray *reg ) * * Description : * * Parameters : * param rw/r/w param description * * Returns : * ******************************************************************* */ void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) { //---------------------------------------------------------------- // // generic building blocks // #ifdef BBC_TOOLS RegisterBehavior(reg,FillBehaviorGetNextBBIdDecl); #endif /* #ifdef BBC_JOYSTICK RegisterBehavior(reg,FillBehaviorHasFFEffectsDecl); RegisterBehavior(reg,FillBehaviorJSetXYForceDecl); #endif */ /************************************************************************/ /* Bodies: */ /************************************************************************/ RegisterBehavior(reg,FillBehaviorPBPhysicalizeDecl); RegisterBehavior(reg,FillBehaviorPBAddTorqueDecl); RegisterBehavior(reg,FillBehaviorPBAddForceDecl); RegisterBehavior(reg,FillBehaviorPBAddForceAtLocalPosDecl); RegisterBehavior(reg,FillBehaviorPBAddLocalForceDecl); RegisterBehavior(reg,FillBehaviorPBAddLocalForceAtPosDecl); RegisterBehavior(reg,FillBehaviorPBAddLocalForceAtLocalPosDecl); RegisterBehavior(reg,FillBehaviorPBAddLocalTorqueDecl); RegisterBehavior(reg,FillBehaviorAddForceAtPosDecl); RegisterBehavior(reg,FillBehaviorPBSetDecl); RegisterBehavior(reg,FillBehaviorPBSet2Decl); RegisterBehavior(reg,FillBehaviorPBSetParDecl); RegisterBehavior(reg,FillBehaviorPBPhysicalizeExDecl); RegisterBehavior(reg,FillBehaviorPBAddShapeExDecl); RegisterBehavior(reg,FillBehaviorPBSetHardDecl); RegisterBehavior(reg,FillBehaviorPBGetDecl); RegisterBehavior(reg,FillBehaviorPBGet2Decl); RegisterBehavior(reg,FillBehaviorPBGetParameterDecl); RegisterBehavior(reg,FillBehaviorPBGetVelocitiesAndForcesDecl); RegisterBehavior(reg,FillBehaviorPBDestroyDecl); #ifdef BBC_JOINTS /************************************************************************/ /* D6 */ /************************************************************************/ RegisterBehavior(reg,FillBehaviorPJGroupBreakIteratorDecl); RegisterBehavior(reg,FillBehaviorJSetD6Decl); RegisterBehavior(reg,FillBehaviorJD6SetMotionModeDecl); RegisterBehavior(reg,FillBehaviorJD6SetSoftLimitDecl); RegisterBehavior(reg,FillBehaviorJD6SetDriveDecl); RegisterBehavior(reg,FillBehaviorJD6SetParametersDecl); /************************************************************************/ /* Joints */ /************************************************************************/ RegisterBehavior(reg,FillBehaviorJSetBallDecl); RegisterBehavior(reg,FillBehaviorPJSetBreakForcesDecl); RegisterBehavior(reg,FillBehaviorJSetFixedDecl); RegisterBehavior(reg,FillBehaviorPJIsBrokenDecl); RegisterBehavior(reg,FillBehaviorJDestroyDecl); RegisterBehavior(reg,FillBehaviorPJCreateDistanceJointDecl); RegisterBehavior(reg,FillBehaviorPJRevoluteDecl); RegisterBehavior(reg,FillBehaviorPJIteratorDecl); RegisterBehavior(reg,FillBehaviorPJPulleyDecl); RegisterBehavior(reg,FillBehaviorPJPrismaticDecl); RegisterBehavior(reg,FillBehaviorPJCylindricalDecl); RegisterBehavior(reg,FillBehaviorPJPointPlaneDecl); RegisterBehavior(reg,FillBehaviorPJPointOnLineDecl); RegisterBehavior(reg,FillBehaviorPJAddLimitPlaneDecl); #endif // BBC_JOINTS /************************************************************************/ /* collision */ /************************************************************************/ RegisterBehavior(reg,FillBehaviorPWSetCollisionGroupFlagDecl); RegisterBehavior(reg,FillBehaviorPCIgnorePairDecl); RegisterBehavior(reg,FillBehaviorCollisionsCheckADecl); RegisterBehavior(reg,FillBehaviorPBSetTriggerMaskDecl); RegisterBehavior(reg,FillBehaviorPCTriggerEventDecl); RegisterBehavior(reg,FillBehaviorPCGroupTriggerEventDecl); /************************************************************************/ /* Shapes : */ /************************************************************************/ RegisterBehavior(reg,FillBehaviorPBAddShapeDecl); RegisterBehavior(reg,FillBehaviorPBRemoveShapeDecl); RegisterBehavior(reg,FillBehaviorPBSetCallbackDecl); /************************************************************************/ /* Clothes : */ /************************************************************************/ #ifdef DONGLE_VERSION if(!PhysicManager::DongleHasAdvancedVersion) return; #endif #ifdef BBC_CLOTHES RegisterBehavior(reg,FillBehaviorPClothDecl); RegisterBehavior(reg,FillBehaviorPClothAttachToShapeDecl); //RegisterBehavior(reg,FillBehaviorPClothAttachToCoreDecl); RegisterBehavior(reg,FillBehaviorPClothAttachVertexToShapeDecl); RegisterBehavior(reg,FillBehaviorPClothAttachVertexToPositionDecl); RegisterBehavior(reg,FillBehaviorPClothFreeVertexDecl); RegisterBehavior(reg,FillBehaviorPClothDominateVertexDecl); RegisterBehavior(reg,FillBehaviorPClothDetachFromShapeDecl); RegisterBehavior(reg,FillBehaviorPClothDestroyDecl); RegisterBehavior(reg,FillBehaviorPClothAddForceAtPosDecl); RegisterBehavior(reg,FillBehaviorPClothAddForceAtVertexDecl); RegisterBehavior(reg,FillBehaviorPClothAddDirectedForceAtPosDecl); #endif RegisterBehavior(reg,FillBehaviorPWSetFilteringDecl); RegisterBehavior(reg,FillBehaviorPWRayCastAllShapeDecl); RegisterBehavior(reg,FillBehaviorPWRayCastAnyBoundsDecl); RegisterBehavior(reg,FillBehaviorPWOverlapSphereDecl); RegisterBehavior(reg,FillBehaviorPWOBBOverlapDecl); ////////////////////////////////////////////////////////////////////////// // // Vehicles and Wheels : #ifdef BBC_VEHICLES RegisterBehavior(reg,FillBehaviorPVWGetDecl); RegisterBehavior(reg,FillBehaviorPVWSetDecl); RegisterBehavior(reg,FillBehaviorPVSetDecl); RegisterBehavior(reg,FillBehaviorPVSetExDecl); RegisterBehavior(reg,FillBehaviorPVControlDecl); RegisterBehavior(reg,FillBehaviorPVSetMotorValuesDecl); RegisterBehavior(reg,FillBehaviorPVSetGearsDecl); RegisterBehavior(reg,FillBehaviorPVControl2Decl); RegisterBehavior(reg,FillBehaviorPVSetBreakSettingsDecl); RegisterBehavior(reg,FillBehaviorPVGetDecl); #endif /////////////////////////////////////////////////////////////////////////// // // Material RegisterBehavior(reg,FillBehaviorPBSetMaterialDecl); /////////////////////////////////////////////////////////////////////////// // // Material RegisterBehavior(reg,FillBehaviorPManagerDecl); RegisterBehavior(reg,FillBehaviorRegisterAttributeTypeDecl); RegisterBehavior(reg,FillBehaviorLogEntryDecl); RegisterBehavior(reg,FillBehaviorPMaterialIteratorDecl); #ifdef WebPack RegisterCameraBeh(reg); #endif } <file_sep>// Editor.cpp : Defines the initialization routines for the DLL. // #include "stdafx2.h" #include "vtAgeiaInterfaceEditor.h" #include "vtAgeiaInterfaceEditorDlg.h" #include "vtAgeiaInterfaceToolbarDlg.h" #include "vtAgeiaInterfaceCallback.h" #include "resource.h" #ifdef _MFCDEBUGNEW #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif vtAgeiaInterfaceEditorDlg* g_Editor = NULL; vtAgeiaInterfaceToolbarDlg* g_Toolbar = NULL; //---------------------------------------- //The Plugin Info structure that must be filled for Virtools Dev to load effectively the plugin PluginInfo g_PluginInfo0; //Returns the number of plugin contained in this dll //this function must be exported (have a .def file with its name or use __declspec( dllexport ) int GetVirtoolsPluginInfoCount() { return 1; } //returns the ptr of the (index)th plugininfo structure of this dll //this function must be exported (have a .def file with its name or use __declspec( dllexport ) PluginInfo* GetVirtoolsPluginInfo(int index) { switch(index) { case 0: return &g_PluginInfo0; } return NULL; } // // Note! // // If this DLL is dynamically linked against the MFC // DLLs, any functions exported from this DLL which // call into MFC must have the AFX_MANAGE_STATE macro // added at the very beginning of the function. // // For example: // // extern "C" BOOL PASCAL EXPORT ExportedFunction() // { // AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // normal function body here // } // // It is very important that this macro appear in each // function, prior to any calls into MFC. This means that // it must appear as the first statement within the // function, even before any object variable declarations // as their constructors may generate calls into the MFC // DLL. // // Please see MFC Technical Notes 33 and 58 for additional // details. // ///////////////////////////////////////////////////////////////////////////// // vtAgeiaInterfaceEditorApp BEGIN_MESSAGE_MAP(vtAgeiaInterfaceEditorApp, CWinApp) //{{AFX_MSG_MAP(vtAgeiaInterfaceEditorApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // vtAgeiaInterfaceEditorApp construction vtAgeiaInterfaceEditorApp::vtAgeiaInterfaceEditorApp() { mContext = NULL; pMan =NULL; } ///////////////////////////////////////////////////////////////////////////// // The one and only vtAgeiaInterfaceEditorApp object vtAgeiaInterfaceEditorApp theApp; BOOL vtAgeiaInterfaceEditorApp::InitInstance() { AfxOleInit(); // TODO: Add your specialized code here and/or call the base class if (GetCKContext(0)) { /*theApp.mContext = GetCKContext(0); PhysicManager *im = (PhysicManager*)getContext()->GetManagerByGuid(PhysicManager_GUID); if (im) { pMan = im; }*/ } strcpy(g_PluginInfo0.m_Name,"vtAgeiaInterface"); g_PluginInfo0.m_PluginType = PluginInfo::PT_EDITOR; //g_PluginInfo0.m_PluginType = (PluginInfo::PLUGIN_TYPE)(g_PluginInfo0.m_PluginType | PluginInfo::PTF_RECEIVENOTIFICATION); //EDITOR { g_PluginInfo0.m_EditorInfo.m_Guid[1] = 0xd07cc06a; g_PluginInfo0.m_EditorInfo.m_Guid[2] = 0x7ca4fc86; strcpy(g_PluginInfo0.m_EditorInfo.m_EditorName,"vtAgeiaEditor"); g_PluginInfo0.m_EditorInfo.m_CreateEditorDlgFunc = fCreateEditorDlg; g_PluginInfo0.m_EditorInfo.m_CreateToolbarDlgFunc = fCreateToolbarDlg; g_PluginInfo0.m_EditorInfo.m_bUnique = 1; g_PluginInfo0.m_EditorInfo.m_bIndestructible = 0; g_PluginInfo0.m_EditorInfo.m_bManageScrollbar = 0; g_PluginInfo0.m_EditorInfo.m_Width = 400; g_PluginInfo0.m_EditorInfo.m_Height = 200; g_PluginInfo0.m_EditorInfo.m_ToolbarHeight = 21; //InitImageList(); g_PluginInfo0.m_EditorInfo.m_IconList = &m_ImageList; g_PluginInfo0.m_EditorInfo.m_IconIndex = 0; g_PluginInfo0.m_PluginCallback = PluginCallback; } return CWinApp::InitInstance(); } int vtAgeiaInterfaceEditorApp::ExitInstance() { // TODO: Add your specialized code here and/or call the base class DeleteImageList(); return CWinApp::ExitInstance(); } void vtAgeiaInterfaceEditorApp::InitImageList() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); m_ImageList.Create(16, 16, ILC_COLOR8|ILC_MASK, 0, 2); // m_ImageList.Add(AfxGetApp()->LoadIcon(IDI_EDITORICON)); } void vtAgeiaInterfaceEditorApp::DeleteImageList() { m_ImageList.DeleteImageList(); } /* CWnd* thisSubParentWindow = CWnd::FromHandle((HWND)ParentWindow); MultiParamEditDlg pedit(GetCKContext(0), thisSubParentWindow); int s = pedit.GetMode(); pedit.SetMode(MultiParamEditDlg::AUTOCLOSE_WHEN_MODELESS|MultiParamEditDlg::MODELESSEDIT); CKParameterOut *commonParameter= GetParameterFromStruct(param,PS_COMMON_SETTINGS); pedit.AddParameter(commonParameter); //for (int i = 0; i < mfx->m_Params.Size(); ++i) // pedit.AddParameter(mfx->m_Params[i]); pedit.SetTitle("Material Shader Fx Params"); pedit.DoModal(); return pedit.GetSafeHwnd(); char name[256]; if (oriUIFunc && param) { //CWnd* thisSubParentWindow = CWnd::FromHandle((HWND)ParentWindow); CWnd* thisSubParentWindow = CWnd::FromHandle((HWND)ParentWindow); CString strMain; thisSubParentWindow->GetWindowText(strMain); if (thisSubParentWindow !=NULL ) { CWnd* bigParentWindow = thisSubParentWindow; for( CWnd* subParentWindow = bigParentWindow->GetWindow(GW_CHILD); subParentWindow ; subParentWindow = subParentWindow->GetWindow(GW_HWNDNEXT) ) { CString str; subParentWindow->GetWindowText(str); GetClassName( subParentWindow->m_hWnd, name, sizeof(name) ); XString _name(name); //if( strcmp(name,MFC_NAME_OF_DIALOG) ) continue; for( CWnd* child = subParentWindow->GetWindow(GW_CHILD) ; child ; child = child->GetWindow(GW_HWNDNEXT) ) { CString str2; child->GetWindowText(str); //GetClassName( child->m_hWnd, name, sizeof(name) ); //XString _name2(name); //if( strcmp(name,MFC_NAME_OF_DIALOG) ) continue; //CParameterDialog* otherParamDialog = (CParameterDialog*)(child->SendMessage( CKWM_GETPARAMDIALOG, 0, 0 )); //if( !otherParamDialog ) continue; CKParameterOut *commonParameter= GetParameterFromStruct(param,PS_COMMON_SETTINGS); if (commonParameter) { int p2=2; p2++; //SetParameterStructureValue<int>(commonParameter,PS_HULL_TYPE,HT_Mesh,false); } //--- From this point it should be a CParameterDialog... //CParameterDialog* otherParamDialog = (CParameterDialog*)(child->SendMessage( CKWM_GETPARAMDIALOG, 0, 0 )); //if( !otherParamDialog ) continue; } } } //MultiParamEditDlg test(param->GetCKContext(),ParentWindow); CKParameterOut *commonParameter= GetParameterFromStruct(param,PS_COMMON_SETTINGS); if (commonParameter) { //SetParameterStructureValue<int>(commonParameter,PS_HULL_TYPE,HT_Mesh,false); } //return (*oriUIFunc)(param,ParentWindow,rect); return ParentWindow; double d = 0.0; } */<file_sep>#ifndef __VT_BB_MACROS_H__ #define __VT_BB_MACROS_H__ //#ifndef __VT_TOOLS_H__ // #include <virtools/vt_tools.h> //#endif #ifndef __VT_BB_HELPER_H__ #include <virtools/vtBBHelper.h> #endif //---------------------------------------------------------------- // // The directive _DOC_ONLY_ is just for forcing in/out- parameters creation in dynamic building blocks. // This allows imagegen.exe to create the right pictures // //#define _DOC_ONLY_ 0 #ifdef _DOC_ONLY_ #define BB_SPIN(I,G,N,D) BBParameter(I,G,N,D,1) #else #define BB_SPIN(I,G,N,D) BBParameter(I,G,N,D) #endif #define BB_PIN(I,G,N,D) BBParameter(I,TRUE,G,N,D,1) #define BB_SPIN_ON(I,G,N,D) BBParameter(I,G,N,D,1) #define BB_DECLARE_PMAP BBParArray *pMap = static_cast<BBParArray *>(beh->GetAppData()) #define BB_CREATE_PMAP BBParArray *pMap = static_cast<BBParArray *>(beh->GetAppData());\ if(!pMap) pMap = new BBParArray(); \ beh->SetAppData(pMap) #define BB_DELETE_OLD_MAP if (beh->GetAppData()!=NULL){\ pMap = NULL;\ beh->SetAppData(NULL);\ }\ #define BB_CKECK_MAP if (pMap==NULL)\ {\ pMap = new BBParArray();\ }\ #define BB_CLEANUP BB_DELETE_OLD_MAP;\ BB_CKECK_MAP #define BB_CREATE_PIMAP BBParArray *pIMap = new BBParArray(); \ beh->SetAppData(pIMap) #define BB_DECLARE_PIMAP BBParArray *pIMap = static_cast<BBParArray *>(beh->GetAppData()) #define BB_PMAP_SIZE(SOURCE_MAP) (sizeof(SOURCE_MAP) / sizeof(SOURCE_MAP[0])) #define BB_DESTROY_PIMAP BB_DECLARE_PIMAP; \ BBHelper::destroyPIMap(beh,pIMap); \ #define BB_INIT_PIMAP(SOURCE_MAP,SETTING_START_INDEX) BB_CREATE_PMAP; \ BBHelper::initPIMap(beh,pMap,SOURCE_MAP,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX); #define BB_REMAP_PIMAP(SOURCE_MAP,SETTING_START_INDEX) BB_DECLARE_PIMAP;\ BBHelper::remapArray(beh,pIMap,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX) /************************************************************************/ /* */ /************************************************************************/ #define BB_EVALUATE_SETTINGS(A) for (int i = 0 ; i < BB_PMAP_SIZE(A) ; i ++) { \ if(!A[i].fixed)proto->DeclareSetting(A[i].name.Str(),CKPGUID_BOOL, A[i].condition==-1 ? "FALSE" : "TRUE" ); } \ #define BB_EVALUATE_PINS(A) for (int i = 0 ; i < BB_PMAP_SIZE(A) ; i ++) { \ if(A[i].fixed)proto->DeclareInParameter(A[i].name.Str(),A[i].guid,A[i].defaultValue.Str()); } \ #define BB_EVALUATE_OUTPUTS(A) for (int i = 0 ; i < BB_PMAP_SIZE(A) ; i ++) { \ proto->DeclareOutParameter(A[i].name.Str(),A[i].guid,A[i].defaultValue.Str()); } \ #define BB_EVALUATE_INPUTS(A) for (int i = 0 ; i < BB_PMAP_SIZE(A) ; i ++) { \ proto->DeclareInParameter(A[i].name.Str(),A[i].guid,A[i].defaultValue.Str()); } \ //################################################################ // // // #define BB_LOAD_PIMAP(SOURCE_MAP,SETTING_START_INDEX) BB_CLEANUP;\ BBHelper::loadPIMap(beh,pMap,SOURCE_MAP,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX); \ beh->SetAppData(pMap) #define BB_LOAD_POMAP(SOURCE_MAP,SETTING_START_INDEX) BB_CLEANUP;\ BBPOHelper::loadPOMap(beh,pMap,SOURCE_MAP,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX);\ beh->SetAppData(pMap) #define BB_IP_INDEX(A) BBHelper::getIndex(beh,pIMap,A) #define BBSParameter(A) int s##A;\ beh->GetLocalParameterValue(A,&s##A) #define BBSParameterM(A,B) int s##A;\ beh->GetLocalParameterValue(A-B,&s##A) /************************************************************************/ /* */ /************************************************************************/ #define BB_SPOUT(I,G,N,D) BBParameter(I,G,N,D) #define BB_SPOUT_ON(I,G,N,D) BBParameter(I,G,N,D,1) #define BB_INIT_PMAP(SOURCE_MAP,SETTING_START_INDEX) BB_CREATE_PMAP;\ BBPOHelper::initPMap(beh,pMap,SOURCE_MAP,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX) #define BB_REMAP_PMAP(SOURCE_MAP,SETTING_START_INDEX) BB_DECLARE_PMAP;\ BBPOHelper::remapArray(beh,pMap,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX) #define BB_DESTROY_PMAP BB_DECLARE_PMAP; \ BBPOHelper::destroyPMap(beh,pMap); \ #define BB_OP_INDEX(A) BBPOHelper::getIndex(beh,pMap,A) #define BB_O_SET_VALUE_IF(T,I,V) if (s##I)\ SetOutputParameterValue<T>(beh,BB_OP_INDEX(I),V) #endif<file_sep>/******************************************************************** created: 2009/02/16 created: 16:2:2009 10:41 filename: x:\ProjectRoot\svn\local\usr\include\virtools\vtBase.h file path: x:\ProjectRoot\svn\local\usr\include\virtools file base: vtBase file ext: h author: <NAME> purpose: Includes of Virtools base types. Do not include CKObjects !!! *********************************************************************/ #ifndef __VT_BASE_H__ #define __VT_BASE_H__ //################################################################ // // Base types // #include "XString.h" #include "CKTypes.h" #include "XHashTable.h" #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPJSetBreakForcesDecl(); CKERROR CreatePJSetBreakForcesProto(CKBehaviorPrototype **pproto); int PJSetBreakForces(const CKBehaviorContext& behcontext); CKERROR PJSetBreakForcesCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_BodyB, bbI_Type, bbI_MaxForce, bbI_MaxTorque }; //************************************ // Method: FillBehaviorPJSetBreakForcesDecl // FullName: FillBehaviorPJSetBreakForcesDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPJSetBreakForcesDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJSetBreakForces"); od->SetCategory("Physic/Joints"); od->SetDescription("Sets the maximum forces on a joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x3ace1062,0x265d33c5)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJSetBreakForcesProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJSetBreakForcesProto // FullName: CreatePJSetBreakForcesProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePJSetBreakForcesProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJSetBreakForces"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJSetBreakForces <br> PJSetBreakForces is categorized in \ref Joints <br> <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Sets a joint as breakable or unbreakable. <br> <h3>Technical Information</h3> Joints can be set to be breakable. This means that if a joint is tugged on with a large enough force, it will snap apart. To set a breakable joint, set the maxForce and maxTorque members of NxJointDesc to the desired values - the smaller the value, the more easily the joint will break. The maxForce defines the limit for linear forces that can be applied to a joint before it breaks, while the maxTorque defines the limit for angular forces. The exact behavior depends on the type of joint. It is possible to change these parameters for an existing joint using #pJoint::setBreakForces(). When a joint breaks, the \ref PJIsBroken will be called. <b> Maximum Force and maximum Torque</b> The distinction between maxForce and maxTorque is dependent on how the joint is implemented internally, which may not be obvious. For example, what appears to be an angular degree of freedom may be constrained indirectly by a linear constraint. Therefore, in most practical applications the user should set both maxTorque and maxForce to similar values. In the current implementation, the following joints use angular constraints: - \ref PJD6 - Only in the case where angular DOFs are locked. - \ref PJFixed - \ref PJPrismatic - \ref PJRevolute \image html PJSetBreakForces.png <SPAN CLASS="in">In: </SPAN> triggers the process <BR> <SPAN CLASS="out">Out: </SPAN> is activated when the process is completed. <BR> <SPAN CLASS="pin">Body B: </SPAN> The second body. Leave blank to create a joint constraint with the world. <BR> <SPAN CLASS="pin">Joint Type:</SPAN> The joint type. This helps the building block to identify a joint constraint. As usual there can be only one joint of the type x between two bodies. <BR> <SPAN CLASS="pin">Maximum Force:</SPAN> Maximum force the joint can withstand without breaking. - <b>Range:</b> (0,inf] <BR> <SPAN CLASS="pin">Maximum Torque:</SPAN> Maximum torque the joint can withstand without breaking. - <b>Range:</b> (0,inf] <BR> \Note If Maximum Force = 0.0 AND Maximum Torque = 0.0 the joint becomes unbreakable. <h3>VSL : Set break forces </h3><br> <SPAN CLASS="NiceCode"> \include pJSetBreakForces.vsl </SPAN> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pJoint::setBreakForces().<br> */ proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( PJSetBreakForcesCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Joint Type",VTE_JOINT_TYPE,"0"); proto->DeclareInParameter("Maximum Force",CKPGUID_FLOAT,"0"); proto->DeclareInParameter("Maximum Torque",CKPGUID_FLOAT,"0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PJSetBreakForces); *pproto = proto; return CK_OK; } //************************************ // Method: PJSetBreakForces // FullName: PJSetBreakForces // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJSetBreakForces(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A + B: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bbI_BodyB); int jointType = GetInputParameterValue<int>(beh,bbI_Type); float maxForce = GetInputParameterValue<float>(beh,bbI_MaxForce); float maxTorque = GetInputParameterValue<float>(beh,bbI_MaxTorque); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,jointType)) return CK_OK; // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A && B: pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); //at least one needs to be there if(bodyA || bodyB) { pJoint *joint = (worldA->getJoint(target,targetB,(JType)jointType)); if (joint) joint->setBreakForces(maxForce,maxTorque); } beh->ActivateOutput(0); } return 0; } //************************************ // Method: PJSetBreakForcesCB // FullName: PJSetBreakForcesCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJSetBreakForcesCB(const CKBehaviorContext& behcontext) { return CKBR_OK; }<file_sep>#ifndef __VT_BODY_STRUCTS_H__ #define __VT_BODY_STRUCTS_H__ ////////////////////////////////////////////////////////////////////////// // // @todo : old custom structures, classical registered // typedef enum E_PHYSIC_PARAMETER_STRUCT { E_PPS_HULLTYPE, E_PPS_BODY_FLAGS, E_PPS_DENSITY, E_PPS_SKIN_WIDTH, E_PPS_MASS_OFFSET, E_PPS_SHAPE_OFFSET, E_PPS_HIRARCHY, E_PPS_WORLD, E_PPS_NEW_DENSITY, E_PPS_TOTAL_MASS, E_PPS_COLL_GROUP }; typedef enum E_MATERIAL_STRUCT { E_MS_XML_TYPE, E_MS_DFRICTION, E_MS_SFRICTION, E_MS_RESTITUTION, E_MS_DFRICTIONV, E_MS_SFRICTIONV, E_MS_ANIS, E_MS_FCMODE, E_MS_RCMODE, E_MS_FLAGS, }; typedef enum E_RAY_CAST_STRUCT { E_RC_WORLD, E_RC_ORI, E_RC_ORI_REF, E_RC_DIR, E_RC_DIR_REF, E_RC_LENGTH, E_RC_GROUPS, E_RC_GROUPS_MASK, E_RC_SHAPES_TYPES }; typedef enum E_CLOTH_STRUCT { E_CS_THICKNESS, E_CS_DENSITY, E_CS_BENDING_STIFFNESS, E_CS_STRETCHING_STIFFNESS, E_CS_DAMPING_COEFFICIENT, E_CS_FRICTION, E_CS_PRESSURE, E_CS_TEAR_FACTOR, E_CS_COLLISIONRESPONSE_COEFFICIENT, E_CS_ATTACHMENTRESPONSE_COEFFICIENT, E_CS_ATTACHMENT_TEAR_FACTOR, E_CS_TO_FLUID_RESPONSE_COEFFICIENT, E_CS_FROM_FLUIDRESPONSE_COEFFICIENT, E_CS_MIN_ADHERE_VELOCITY, E_CS_SOLVER_ITERATIONS, E_CS_EXTERN_ALACCELERATION, E_CS_WIND_ACCELERATION, E_CS_WAKE_UP_COUNTER, E_CS_SLEEP_LINEAR_VELOCITY, E_CS_COLLISIONG_ROUP, E_CS_VALID_BOUNDS, E_CS_RELATIVE_GRID_SPACING, E_CS_FLAGS, E_CS_TEAR_VERTEX_COLOR, E_CS_WORLD_REFERENCE, E_CS_ATTACHMENT_FLAGS, }; typedef enum E_WCD_STRUCT { E_WCD_CPOINT, E_WCD_CNORMAL, E_WCD_LONG_DIR, E_WCD_LAT_DIR, E_WCD_CONTACT_FORCE, E_WCD_LONG_SLIP, E_WCD_LAT_SLIP, E_WCD_LONG_IMPULSE, E_WCD_LAT_IMPULSE, E_WCD_OTHER_MATERIAL_INDEX, E_WCD_C_POS, E_WCD_CONTACT_ENTITY, }; typedef enum E_VBT_STRUCT { E_VBT_0, E_VBT_1, E_VBT_2, E_VBT_3, E_VBT_4, E_VBT_5, E_VBT_6, E_VBT_7, E_VBT_8, E_VBT_9 }; typedef enum WHEEL_DESCR_STRUCT { E_WD_XML, E_WD_SUSPENSION, E_WD_SPRING_RES, E_WD_DAMP, E_WD_SPRING_BIAS, E_WD_MAX_BFORCE, E_WD_FSIDE, E_WD_FFRONT, E_WD_INVERSE_WHEEL_MASS, E_WD_FLAGS, E_WD_SFLAGS, E_WD_LAT_FUNC, E_WD_LONG_FUNC, }; typedef enum E_CAPSULE_STRUCT { E_CS_LENGTH_AXIS, E_CS_RADIUS_AXIS, E_CS_LENGTH, E_CS_RADIUS, }; ////////////////////////////////////////////////////////////////////////// // // New Structs // /** \brief Data mask to determine which parts of a rigid bodies description have to be evolved. */ enum pObjectDescrMask { /** \brief Description has XML settings */ OD_XML = (1 << 0), /** \brief Description has pivot override */ OD_Pivot = (1 << 1), /** \brief Description has mass override */ OD_Mass= (1 << 2), /** \brief Description has collisions settings */ OD_Collision = (1 << 3), /** \brief Description has CCD settings */ OD_CCD = (1 << 4), /** \brief Description has material settings */ OD_Material = (1 << 5), /** \brief Description has optimization settings */ OD_Optimization = (1 << 6), /** \brief Description has capsule override */ OD_Capsule = (1 << 7), /** \brief Description has convex cylinder override */ OD_ConvexCylinder = (1 << 8), /** \brief Description has wheel settings */ OD_Wheel = (1 << 9) }; enum PB_COPY_FLAGS { PB_CF_PHYSICS=1, PB_CF_SHARE_MESHES=(1<<1), PB_CF_PIVOT_SETTINGS=(1<<2), PB_CF_MASS_SETTINGS=(1<<3), PB_CF_COLLISION=(1<<4), PB_CF_CCD=(1<<5), PB_CF_MATERIAL=(1<<6), PB_CF_OPTIMIZATION=(1<<7), PB_CF_CAPSULE=(1<<8), PB_CF_CONVEX_CYLINDER=(1<<9), PB_CF_FORCE=(1<<10), PB_CF_VELOCITIES=(1<<11), PB_CF_JOINTS=(1<<12), PB_CF_LIMIT_PLANES=(1<<13), PB_CF_SWAP_JOINTS_REFERENCES=(1<<14), PB_CF_OVRRIDE_BODY_FLAGS=(1<<15), PB_CF_COPY_IC=(1<<16), PB_CF_RESTORE_IC=(1<<17), }; enum PS_B_COLLISON { PS_BC_GROUP, PS_BC_GROUPSMASK, PS_BC_SKINWITDH, PS_BC_CCD_SETUP }; enum PS_B_CCD { PS_B_CCD_MOTION_THRESHOLD, PS_B_CCD_FLAGS, PS_B_CCD_SCALE, PS_B_CCD_MESH_REFERENCE, }; enum PS_B_COLLISION_SETUP { PS_BCS_COLLISION_COMMON, PS_BCS_CCD, }; enum PS_B_DAMPING { PS_BD_LINEAR, PS_BD_ANGULAR, }; enum PS_B_SLEEPING { PS_BS_LINEAR_SLEEP, PS_BS_ANGULAR_SLEEP, PS_BS_THRESHOLD, }; enum PS_B_OPTIMISATION { PS_BO_LOCKS, PS_BO_DAMPING, PS_BO_SLEEPING, PS_BO_SOLVER_ITERATIONS, PS_BO_DOMINANCE_GROUP, PS_BO_COMPARTMENT_ID, }; enum PS_B_PIVOT { PS_BP_LINEAR, PS_BP_ANGULAR, PS_BP_REFERENCE, }; enum PS_B_MASS { PS_BM_DENSITY, PS_BM_TOTAL_MASS, PS_BM_PIVOT_POS, PS_BM_PIVOT_ROTATION, PS_BM_PIVOT_REFERENCE, }; enum PS_BODY_FULL { PS_BODY_XML, PS_BODY_HULL_TYPE, PS_BODY_FLAGS, }; enum PS_BODY_XML_SETUP { PS_INTERN_LINK, PS_EXTERN_LINK, PS_XML_MPORT_FLAGS, }; enum PS_BODY_COMMON { PS_BC_HULL_TYPE, PS_BC_DENSITY, PS_BC_FLAGS, /* PS_BC_TFLAGS,*/ PS_BC_WORLD }; enum PS_BODY_SETUP { PS_XML_SETUP, PS_COMMON_SETTINGS, /*PS_PIVOT, PS_MASS,*/ PS_COLLISION_SETTINGS, }; enum PS_AXIS_REFERENCED_LENGTH { PS_ARL_VALUE, PS_ARL_REF_OBJECT, PS_ARL_REF_OBJECT_AXIS, }; enum PS_CAPSULE { PS_BCAPSULE_RADIUS_REFERENCED_VALUE, PS_PCAPSULE_HEIGHT_REFERENCED_VALUE, }; enum PS_CUSTOM_CONVEX_CYLINDER_DESCR { PS_CC_APPROXIMATION, PS_CC_RADIUS_REFERENCED_VALUE, PS_CC_HEIGHT_REFERENCED_VALUE, PS_CC_FORWARD_AXIS, PS_CC_FORWARD_AXIS_REF, PS_CC_DOWN_AXIS, PS_CC_DOWN_AXIS_REF, PS_CC_RIGHT_AXIS, PS_CC_RIGHT_AXIS_REF, PS_CC_BUILD_LOWER_HALF_ONLY, PS_CC_EXTRA_SHAPE_FLAGS }; #endif <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SetCameraTarget for Camera // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorSetCameraTargetDecl(); CKERROR CreateSetCameraTargetProto(CKBehaviorPrototype **pproto); int SetCameraTarget(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSetCameraTargetDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Set Camera Target"); od->SetDescription("Makes a 3D Entity be the target of a camera."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Target: </SPAN>3D Entity to target.<BR> <BR> This building block doesn't need to be looped. (ie: the camera will constantly follow the selected object)<BR> <BR> */ /* warning: - if you delete the camera, the target will be deleted.<BR> */ od->SetCategory("Cameras/Basic"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x74123741, 0x4563ffff)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00020000); od->SetCreationFunction(CreateSetCameraTargetProto); od->SetCompatibleClassId(CKCID_TARGETCAMERA); return od; } CKERROR CreateSetCameraTargetProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set Camera Target"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Target", CKPGUID_3DENTITY ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetCameraTarget); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int SetCameraTarget(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKTargetCamera *cam = (CKTargetCamera *) beh->GetTarget(); if( !cam ) return CKBR_OWNERERROR; // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0,TRUE); // Get target CK3dEntity *ent = (CK3dEntity *) beh->GetInputParameterObject(0); if( beh->GetVersion()==0x0001000 ){ VxVector pos(0,0,0); ent->GetPosition( &pos ); CK3dEntity *target = cam->GetTarget(); target->SetPosition( &pos ); return CKBR_OK; } if (ent && (ent->GetClassID()==CKCID_3DENTITY)){ cam->SetTarget(ent); } else { cam->SetTarget(NULL); } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPClothDetachFromShapeDecl(); CKERROR CreatePClothDetachFromShapeProto(CKBehaviorPrototype **pproto); int PClothDetachFromShape(const CKBehaviorContext& behcontext); CKERROR PClothDetachFromShapeCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_ShapeReference, }; //************************************ // Method: FillBehaviorPClothDetachFromShapeDecl // FullName: FillBehaviorPClothDetachFromShapeDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPClothDetachFromShapeDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothDetachFromShape"); od->SetCategory("Physic/Cloth"); od->SetDescription("Detaches the cloth from a shape it has been attached to before. "); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0xf4b0609,0x75b453a3)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePClothDetachFromShapeProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePClothDetachFromShapeProto // FullName: CreatePClothDetachFromShapeProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePClothDetachFromShapeProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothDetachFromShape"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PClothDetachFromShape PClothDetachFromShape is categorized in \ref Clothes <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Detaches the cloth from a shape it has been attached to before<br> @see pCloth::detachFromShape() <h3>Technical Information</h3> \image html PClothDetachFromShape.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>Target cloth reference. <BR> <BR> <SPAN CLASS="pin">Shape Reference: </SPAN>Shape to which the cloth should be attached to. <BR> <BR> <SPAN CLASS="pin">Attachment Flags: </SPAN>One or two way interaction, tearable or non-tearable */ proto->SetBehaviorCallbackFct( PClothDetachFromShapeCB ); proto->DeclareInParameter("Shape Reference",CKPGUID_3DENTITY); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PClothDetachFromShape); *pproto = proto; return CK_OK; } //************************************ // Method: PClothDetachFromShape // FullName: PClothDetachFromShape // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PClothDetachFromShape(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// CK3dEntity*shapeReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_ShapeReference); if (!shapeReference) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pCloth *cloth = GetPMan()->getCloth(target->GetID()); if (!cloth) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } NxShape *shape = cloth->getWorld()->getShapeByEntityID(shapeReference->GetID()); if(shape) { cloth->detachFromShape((CKBeObject*)shapeReference); } beh->ActivateOutput(0); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PClothDetachFromShapeCB // FullName: PClothDetachFromShapeCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PClothDetachFromShapeCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#include "pch.h" #include "CKAll.h" CKObjectDeclaration *FillBehaviorGoFullScreenDecl(); CKERROR CreateGoFullScreenProto(CKBehaviorPrototype **pproto); int GoFullScreen(const CKBehaviorContext& behcontext); /************************************************************************/ /* */ /************************************************************************/ CKObjectDeclaration *FillBehaviorGoFullScreenDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("GoFullScreen"); od->SetCategory("Narratives/System"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x126046,0x718a4147)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("mw"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGoFullScreenProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateGoFullScreenProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("GoFullScreen"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Go"); proto->DeclareOutput("Out"); proto->DeclareInParameter("driver index",CKPGUID_INT); proto->DeclareInParameter("width",CKPGUID_INT); proto->DeclareInParameter("height",CKPGUID_INT); proto->DeclareInParameter("bpp",CKPGUID_INT); proto->DeclareInParameter("refreshrate",CKPGUID_INT); proto->DeclareInParameter("SwitchToFS",CKPGUID_BOOL); proto->DeclareInParameter("mode_index",CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(GoFullScreen); *pproto = proto; return CK_OK; } #include <windows.h> BOOL CALLBACK EnumProcessListFunc( HWND, LPARAM ); BOOL CALLBACK EnumProcessListFunc( HWND hWnd, LPARAM lParam ) { static DWORD dwCurrentProcessId; static BOOL fFirstTime = TRUE; static LONG MaxStrLen = 0; static TCHAR TextBuffer[256]; if( fFirstTime ) { fFirstTime = FALSE; dwCurrentProcessId = GetCurrentProcessId(); } if( hWnd ) { GetWindowText( hWnd, (LPTSTR) &TextBuffer, sizeof(TextBuffer)/sizeof(TCHAR) ); if( *TextBuffer ) { DWORD dwProcessId; /*GetWindowThreadProcessId( hWnd, &dwProcessId ); if( dwProcessId != dwCurrentProcessId ) { LRESULT Index; HWND hWndListBox = (HWND) lParam; //Index = ListBoxInsert( hWndListBox, &MaxStrLen, TextBuffer ); SendMessage( hWndListBox, LB_SETITEMDATA, (WPARAM) Index, (LPARAM) dwProcessId ); }*/ } } return( TRUE ); } BOOL CALLBACK EnumChildProc(HWND hwnd,LPARAM lParam) { if( hwnd ) { static TCHAR TextBuffer[256]; GetWindowText( hwnd, (LPTSTR) &TextBuffer, sizeof(TextBuffer)/sizeof(TCHAR) ); if( *TextBuffer ) { return true; } }else return FALSE; } int GoFullScreen(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; CKPluginManager* ThePluginManager=CKGetPluginManager(); CKRenderManager *rm = (CKRenderManager *)ctx->GetRenderManager(); CKRenderContext *rctx = rm->GetRenderContext(0); int rcount = rm->GetRenderContextCount(); int DriverIndex=0; beh->GetInputParameterValue(0, &DriverIndex); int width = 0; beh->GetInputParameterValue(1, &width); int height= 0; beh->GetInputParameterValue(2, &height); int bpp = 0; beh->GetInputParameterValue(3, &bpp); int rr = 0; beh->GetInputParameterValue(4, &rr); bool gOFS = false; beh->GetInputParameterValue(5, &gOFS); int mode = 0; beh->GetInputParameterValue(6, &mode); HWND m_hWndParent = (HWND)ctx->GetMainWindow(); //turn off if(rctx->IsFullScreen() && !gOFS ){ ctx->Pause(); rctx->StopFullScreen(); //ShowWindow(m_hWndParent ,SW_RESTORE); RECT m_hWndParent_rect ; GetWindowRect(m_hWndParent,&m_hWndParent_rect); /* if (m_hWndParent_rect.bottom!=0 && !rctx->IsFullScreen() ) { //allow the window to be resized LONG st = GetWindowLong(m_hWndParent,GWL_STYLE); st|=WS_THICKFRAME; SetWindowLong(m_hWndParent,GWL_STYLE,st); int Xpos=(GetSystemMetrics(SM_CXSCREEN)-width)/2; int Ypos=(GetSystemMetrics(SM_CYSCREEN)-height)/2; //reposition the window ::SetWindowPos(m_hWndParent,HWND_NOTOPMOST,Xpos,Ypos,m_hWndParent_rect.right - m_hWndParent_rect.left,m_hWndParent_rect.bottom - m_hWndParent_rect.top,NULL); } */ ////////////////////////////////////////////////////////////////////////// //restore the main window size (only in DirectX rasterizer->m_MainWindowRect.bottom not modified) if (m_hWndParent_rect.bottom!=0 && !rctx->IsFullScreen()) { //allow the window to be resized LONG st = GetWindowLong(m_hWndParent,GWL_STYLE); st|=WS_THICKFRAME; st&=~WS_SIZEBOX; SetWindowLong(m_hWndParent,GWL_STYLE,st); } //reposition the window m_hWndParent_rect.left = (GetSystemMetrics(SM_CXSCREEN)-width)/2; m_hWndParent_rect.right = width+m_hWndParent_rect.left; m_hWndParent_rect.top = (GetSystemMetrics(SM_CYSCREEN)-height)/2; m_hWndParent_rect.bottom = height+m_hWndParent_rect.top; BOOL ret = AdjustWindowRect(&m_hWndParent_rect,WS_OVERLAPPEDWINDOW & ~(WS_SYSMENU|WS_SIZEBOX|WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_SIZEBOX),FALSE); ::SetWindowPos(m_hWndParent,HWND_NOTOPMOST,m_hWndParent_rect.left,m_hWndParent_rect.top,m_hWndParent_rect.right - m_hWndParent_rect.left,m_hWndParent_rect.bottom - m_hWndParent_rect.top,NULL); // now we can show the main widnwos ShowWindow(m_hWndParent,SW_SHOW); SetFocus(m_hWndParent); rctx->Resize(0,0,width,height); HWND rWin = GetWindow(m_hWndParent,GW_CHILD); if( rWin ) { //static TCHAR TextBuffer[256]; //GetWindowText( rWin, (LPTSTR) &TextBuffer, sizeof(TextBuffer)/sizeof(TCHAR) ); ::SetWindowPos(rWin,NULL,0,0,width,height,SWP_NOMOVE|SWP_NOZORDER); //rctx->Resize(0,0,m_WindowedWidth,m_WindowedHeight); //MessageBox(NULL,TextBuffer,"",NULL); } //EnumChildWindows(m_hWndParent, (WNDENUMPROC) EnumProcessListFunc,NULL ); // and set the position of the render window in the main window //::SetWindowPos(m_RenderWindow,NULL,0,0,m_WindowedWidth,m_WindowedHeight,SWP_NOMOVE|SWP_NOZORDER); // and give the focus to the render window SetFocus(m_hWndParent); ctx->Play(); beh->ActivateOutput(0); return CKBR_OK; } if(!rctx->IsFullScreen() && gOFS ) { ctx->Pause(); int w,h,FSdriver; if (mode<0) rctx->GoFullScreen(w=width,h=height,bpp,FSdriver=DriverIndex,rr); else { VxDriverDesc *MainDesc=rm->GetRenderDriverDescription(DriverIndex); if (MainDesc) rctx->GoFullScreen(w=MainDesc->DisplayModes[mode].Width, h=MainDesc->DisplayModes[mode].Height, MainDesc->DisplayModes[mode].Bpp, FSdriver=DriverIndex,rr); } ctx->Play(); VxDriverDesc* Check_API_Desc=rm->GetRenderDriverDescription(DriverIndex); if (Check_API_Desc->Caps2D.Family==CKRST_DIRECTX && rctx->IsFullScreen()) { //store current size RECT g_mainwin_rect; GetWindowRect(m_hWndParent,&g_mainwin_rect); //Resize the window ::SetWindowPos(m_hWndParent,HWND_TOPMOST,0,0,w,h,NULL); //Prevent the window from beeing resized LONG st = GetWindowLong(m_hWndParent,GWL_STYLE); st&=(~WS_THICKFRAME); SetWindowLong(m_hWndParent,GWL_STYLE,st); } //ShowWindow(m_hWndParent,SW_SHOW|SW_MAXIMIZE); beh->ActivateOutput(0); } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPClothAttachToShapeDecl(); CKERROR CreatePClothAttachToShapeProto(CKBehaviorPrototype **pproto); int PClothAttachToShape(const CKBehaviorContext& behcontext); CKERROR PClothAttachToShapeCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_ShapeReference, bbI_AttachmentFlags, bbI_AttachToColliding, }; enum bSettings { bbS_USE_DEFAULT_WORLD, bbS_ADD_ATTRIBUTES }; //************************************ // Method: FillBehaviorPClothAttachToShapeDecl // FullName: FillBehaviorPClothAttachToShapeDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPClothAttachToShapeDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAttachToShape"); od->SetCategory("Physic/Cloth"); od->SetDescription("Attaches a cloth to a shape."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x2ca5453a,0x7dc1598f)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePClothAttachToShapeProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePClothAttachToShapeProto // FullName: CreatePClothAttachToShapeProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePClothAttachToShapeProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAttachToShape"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PClothAttachToShape PClothAttachToShape is categorized in \ref Clothes <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Attaches a cloth to a shape .<br> <h3>Technical Information</h3> \image html PClothAttachToShape.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>Target cloth reference. <BR> <BR> <SPAN CLASS="pin">Shape Reference: </SPAN>Shape to which the cloth should be attached to. @see pCloth::attachToShape() <BR> <BR> <SPAN CLASS="pin">Attachment Flags: </SPAN>One or two way interaction, tearable or non-tearable <b>Default:</b> PCAF_ClothAttachmentTwoway @see pClothAttachmentFlag <BR> <BR> <BR> <BR> <SPAN CLASS="pin">Attach to colliding shapes: </SPAN>Attaches the cloth to all shapes, currently colliding. This method only works with primitive and convex shapes. Since the inside of a general triangle mesh is not clearly defined. @see pCloth::attachToCollidingShapes() <BR> <BR> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include pCloth.cpp </SPAN> */ proto->SetBehaviorCallbackFct( PClothAttachToShapeCB ); proto->DeclareInParameter("Shape Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Attachment Flags",VTE_CLOTH_ATTACH_FLAGS); proto->DeclareInParameter("Attach to colliding shapes",CKPGUID_BOOL); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PClothAttachToShape); *pproto = proto; return CK_OK; } //************************************ // Method: PClothAttachToShape // FullName: PClothAttachToShape // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PClothAttachToShape(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// CK3dEntity*shapeReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_ShapeReference); if (!shapeReference) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pWorld *world = GetPMan()->getDefaultWorld(); if (!world) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pCloth *cloth = world->getCloth(target); if (!cloth) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } int flags = GetInputParameterValue<int>(beh,bbI_AttachmentFlags); int attachToColliders = GetInputParameterValue<int>(beh,bbI_AttachToColliding); NxShape *shape = world->getShapeByEntityID(shapeReference->GetID()); if(shape) { cloth->attachToShape((CKBeObject*)shapeReference,flags); } if (attachToColliders) { cloth->attachToCollidingShapes(flags); } beh->ActivateOutput(0); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PClothAttachToShapeCB // FullName: PClothAttachToShapeCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PClothAttachToShapeCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; }<file_sep>#ifndef __P_SDKP_SDK_PARAMETER_H__ #define __P_SDKP_SDK_PARAMETER_H__ /** \addtogroup PhysicSDK @{ */ /** \brief Parameters enums to be used as the 1st arg to setParameter or getParameter. @see PhysicManager.setParameter() PhysicManager.getParameter() */ typedef enum pSDKParameter { /* RigidBody-related parameters */ /** \brief Default value for pShape::skinWidth. <b>Range:</b> [0, inf)<br> <b>Default:</b> 0.025<br> <b>Unit:</b> distance. @see pShape.setSkinWidth */ pSDKP_SkinWidth = 1, /** \brief The default linear velocity, squared, below which objects start going to sleep. Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set. <b>Range:</b> [0, inf)<br> <b>Default:</b> (0.15*0.15) */ pSDKP_DefaultSleepLinVelSquared = 2, /** \brief The default angular velocity, squared, below which objects start going to sleep. Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set. <b>Range:</b> [0, inf)<br> <b>Default:</b> (0.14*0.14) */ pSDKP_DefaultSleepAngVelSquared = 3, /** \brief A contact with a relative velocity below this will not bounce. <b>Range:</b> (-inf, 0]<br> <b>Default:</b> -2 @see pMaterial */ pSDKP_BounceThreshold = 4, /** \brief This lets the user scale the magnitude of the dynamic friction applied to all objects. <b>Range:</b> [0, inf)<br> <b>Default:</b> 1 @see pMaterial */ pSDKP_DynFrictScaling = 5, /** \brief This lets the user scale the magnitude of the static friction applied to all objects. <b>Range:</b> [0, inf)<br> <b>Default:</b> 1 @see pMaterial */ pSDKP_StaFrictionScaling = 6, /** \brief See the comment for pRigidBody::setMaxAngularVelocity() for details. <b>Range:</b> [0, inf)<br> <b>Default:</b> 7 @see pRigidBody.setMaxAngularVelocity() */ pSDKP_MaxAngularVelocity = 7, /* Collision-related parameters: */ /** \brief Enable/disable continuous collision detection (0.0f to disable) <b>Range:</b> [0, inf)<br> <b>Default:</b> 0.0 @see NxPhysicsSDK.createCCDSkeleton() */ pSDKP_ContinuousCD = 8, /* General parameters and new parameters */ /** \brief Used to enable adaptive forces to accelerate convergence of the solver. <b>Range:</b> [0, inf)<br> <b>Default:</b> 1.0 */ pSDKP_AdaptiveForce = 68, /** \brief Controls default filtering for jointed bodies. True means collision is disabled. <b>Range:</b> {true, false}<br> <b>Default:</b> true @see pSDKP_JF_CollisionEnabled */ pSDKP_CollVetoJointed = 69, /** \brief Controls whether two touching triggers generate a callback or not. <b>Range:</b> {true, false}<br> <b>Default:</b> true @see NxUserTriggerReport */ pSDKP_TriggerTriggerCallback = 70, pSDKP_SelectHW_Algo = 71, /** \brief Distance epsilon for the CCD algorithm. <b>Range:</b> [0, inf)<br> <b>Default:</b> 0.01 */ pSDKP_CCDEpsilon = 73, /** \brief Used to accelerate solver. <b>Range:</b> [0, inf)<br> <b>Default:</b> 0 */ pSDKP_SolverConvergenceThreshold = 74, /** \brief Used to accelerate HW Broad Phase. <b>Range:</b> [0, inf)<br> <b>Default:</b> 0.001 */ pSDKP_BBoxNoiseLevel = 75, /** \brief Used to set the sweep cache size. <b>Range:</b> [0, inf)<br> <b>Default:</b> 5.0 */ pSDKP_ImplicitSweepCacheSize = 76, /** \brief The default sleep energy threshold. Objects with an energy below this threshold are allowed to go to sleep. Note: Only used when the pSDKP_BF_ENERGY_SLEEP_TEST flag is set. <b>Range:</b> [0, inf)<br> <b>Default:</b> 0.005 */ pSDKP_DefaultSleepEnergy = 77, /** \brief Constant for the maximum number of packets per fluid. Used to compute the fluid packet buffer size in NxFluidPacketData. <b>Range:</b> [925, 925]<br> <b>Default:</b> 925 @see NxFluidPacketData */ pSDKP_ConstantFluidMaxPackets = 78, /** \brief Constant for the maximum number of new fluid particles per frame. <b>Range:</b> [4096, 4096]<br> <b>Default:</b> 4096 */ pSDKP_ConstantFluidMaxParticlesPerStep = 79, /** \brief [Experimental] Disables scene locks when creating/releasing meshes. Prevents the SDK from locking all scenes when creating and releasing triangle meshes, convex meshes, height field meshes, softbody meshes and cloth meshes, which is the default behavior. Can be used to improve parallelism but beware of possible side effects. \warning Experimental feature. */ pSDKP_AsynchronousMeshCreation = 96, /** \brief Epsilon for custom force field kernels. This epsilon is used in custom force field kernels (NxSwTarget). Methods like recip() or recipSqrt() evaluate to zero if their input is smaller than this epsilon. <br> */ pSDKP_ForceFieldCustomKernelEpsilon = 97, /** \brief Enable/disable improved spring solver for joints and wheelshapes This parameter allows to enable/disable an improved version of the spring solver for joints and wheelshapes. \warning The parameter is introduced for legacy purposes only and will be removed in future versions (such that the improved spring solver will always be used). \note Changing the parameter will only affect newly created scenes but not existing ones. <b>Range:</b> {0: disabled, 1: enabled}<br> <b>Default:</b> 1 */ pSDKP_ImprovedSpringSolver = 98, /** \brief This is not a parameter, it just records the current number of parameters (as max(NxParameter)+1) for use in loops. When a new parameter is added this number should be assigned to it and then incremented. */ pSDKP_PARAMS_NUM_VALUES = 99, pSDKP_PARAMS_FORCE_DWORD = 0x7fffffff }; /** @} */ #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPVSetDecl(); CKERROR CreatePVSetProto(CKBehaviorPrototype **pproto); int PVSet(const CKBehaviorContext& behcontext); CKERROR PVSetCB(const CKBehaviorContext& behcontext); using namespace vtTools::BehaviorTools; enum bInputs { I_XML, I_Mass, I_CMass, I_MotorForce, I_DiffRatio, I_TEff, I_MaxVelocity, I_SteerMax, I_SteeringSteerPoint, I_SteerTurnPoint, I_DSDelta, }; #define BB_SSTART 0 BBParameter pInMap[] = { BB_SPIN(I_XML,VTE_XML_VEHICLE_SETTINGS,"Vehicle Settings","None"), BB_SPIN(I_Mass,CKPGUID_FLOAT,"Mass","1000"), BB_SPIN(I_CMass,CKPGUID_VECTOR,"Center of Mass","0,0,0"), BB_SPIN(I_MotorForce,CKPGUID_FLOAT,"Motor Force","2000.0"), BB_SPIN(I_DiffRatio,CKPGUID_FLOAT,"Differential Ratio","1.0"), BB_SPIN(I_TEff,CKPGUID_FLOAT,"Transmission Efficiency","0.5"), BB_SPIN(I_MaxVelocity,CKPGUID_FLOAT,"Max Velocity","1000"), BB_SPIN(I_SteerMax,CKPGUID_ANGLE,"Maximum Steer","15"), BB_SPIN(I_CMass,CKPGUID_VECTOR,"Steering Steer Point","0,0,0"), BB_SPIN(I_CMass,CKPGUID_VECTOR,"Steering Turn Point","0,0,0"), BB_SPIN(I_DSDelta,CKPGUID_FLOAT,"Digital Steering Delta","0.5"), }; #define gVSMap pInMap //#define BB_LOAD_PIMAP(SOURCE_MAP,SETTING_START_INDEX) BBHelper::loadPIMap(beh,pIMap,SOURCE_MAP,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX) CKERROR PVSetCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gVSMap,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gVSMap,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gVSMap,BB_SSTART); break; } } return CKBR_OK; } //************************************ // Method: FillBehaviorPVSetDecl // FullName: FillBehaviorPVSetDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPVSetDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVSet"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Modifies vehicle parameter."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0xb7e2395,0x7cfe4597)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVSetProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePVSetProto // FullName: CreatePVSetProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePVSetProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVSet"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! PVSet PVSet is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies various physical parameters.<br> <h3>Technical Information</h3> \image html PVSet.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pin">Collisions Group: </SPAN>Which collision group this body is part of.See pRigidBody::setCollisionsGroup(). <BR> <SPAN CLASS="pin">Kinematic Object: </SPAN>The kinematic state. See pRigidBody::setKinematic(). <BR> <SPAN CLASS="pin">Gravity: </SPAN>The gravity state.See pRigidBody::enableGravity(). <BR> <SPAN CLASS="pin">Collision: </SPAN>Determines whether the body reacts to collisions.See pRigidBody::enableCollision(). <BR> <SPAN CLASS="pin">Mass Offset: </SPAN>The new mass center in the bodies local space. <BR> <SPAN CLASS="pin">Pivot Offset: </SPAN>The initial shape position in the bodies local space. <BR> <SPAN CLASS="pin">Notify Collision: </SPAN>Enables collision notification.This is necessary to use collisions related building blocks. <BR> <SPAN CLASS="pin">Transformation Locks: </SPAN>Specifies in which dimension a a transformation lock should occour. <BR> <SPAN CLASS="pin">Linear Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Angular Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Filter Groups: </SPAN>Sets the filter mask of the initial or sub shape. <BR> <SPAN CLASS="setting">Collisions Group: </SPAN>Enables input for collisions group. <BR> <SPAN CLASS="setting">Kinematic Object: </SPAN>Enables input for kinematic object. <BR> <SPAN CLASS="setting">Gravity: </SPAN>Enables input for gravity. <BR> <SPAN CLASS="setting">Collision: </SPAN>Enables input for collision. <BR> <SPAN CLASS="setting">Mas Offset: </SPAN>Enables input for mass offset. <BR> <SPAN CLASS="setting">Pivot Offset: </SPAN>Enables input for pivot offset. <BR> <SPAN CLASS="setting">Notify Collision: </SPAN>Enables input for collision. <BR> <SPAN CLASS="setting">Linear Damping: </SPAN>Enables input for linear damping. <BR> <SPAN CLASS="setting">Angular Damping: </SPAN>Enables input for angular damping. <BR> <SPAN CLASS="setting">Filter Groups: </SPAN>Enables input for filter groups. <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBSetEx.cpp </SPAN> */ //proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); /*proto->DeclareSetting("Kinematic",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Gravity",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Collision",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Mass Offset",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Pivot Offset",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Notify Collision",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Transformation Locks",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Linear Damping",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Angular Damping",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Filter Groups",CKPGUID_BOOL,"FALSE"); */ proto->SetBehaviorCallbackFct( PVSetCB ); BB_EVALUATE_SETTINGS(pInMap); //---------------------------------------------------------------- // // We just want create the building block pictures // #ifdef _DOC_ONLY_ BB_EVALUATE_INPUTS(pInMap); #endif // _DOC_ONLY_ proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PVSet); *pproto = proto; return CK_OK; } //************************************ // Method: PVSet // FullName: PVSet // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ #define BBSParameter(A) DWORD s##A;\ beh->GetLocalParameterValue(A,&s##A) int PVSet(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbSErrorME(E_PE_REF); pRigidBody *body = NULL; BB_DECLARE_PIMAP; body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); int xmlValue = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_XML)); float mass = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_Mass)); float mForce = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_MotorForce)); float dRatio = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_DiffRatio)); float steerMax = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_SteerMax)); float dsDelta = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_DSDelta)); float tEff = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_TEff)); float maxVel = GetInputParameterValue<float>(beh,BB_IP_INDEX(I_MaxVelocity)); VxVector cMass = GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(I_CMass)); VxVector steeringSteerPoint = GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(I_SteeringSteerPoint)); VxVector steeringTurnPoint = GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(I_SteerTurnPoint)); BBSParameter(I_XML); BBSParameter(I_Mass); BBSParameter(I_MotorForce); BBSParameter(I_DiffRatio); BBSParameter(I_SteerMax); BBSParameter(I_DSDelta); BBSParameter(I_MaxVelocity); BBSParameter(I_CMass); BBSParameter(I_TEff); BBSParameter(I_SteeringSteerPoint); BBSParameter(I_SteerTurnPoint); pVehicle *v = body->getVehicle(); if (!v) { pVehicleDesc vdesc; vdesc.setToDefault(); //pVehicleGearDesc *gearDesc = vdesc.getGearDescription(); //gearDesc->setToCorvette(); //pVehicleMotorDesc *motorDesc = vdesc.getMotorDescr(); //motorDesc->setToCorvette(); v = pFactory::Instance()->createVehicle(target,vdesc); } if (!v) bbErrorME("Couldn't create vehicle"); if (sI_Mass) v->setMass(mass); if (sI_MotorForce) v->setMotorForce(mForce); if (sI_DiffRatio)v->setDifferentialRatio(dRatio); if (sI_SteerMax)v->setMaxSteering(steerMax) ; if (sI_DSDelta)v->setDigitalSteeringDelta(dsDelta); if (sI_MaxVelocity)v->setMaxVelocity(maxVel); if (sI_CMass)v->setCenterOfMass(cMass); if (sI_TEff)v->setTransmissionEfficiency(tEff); if(sI_SteeringSteerPoint)v->setSteeringSteerPoint(steeringSteerPoint); if(sI_SteerTurnPoint)v->setSteeringTurnPoint(steeringTurnPoint ); } beh->ActivateOutput(0); return 0; } //************************************ // Method: PVSetCB // FullName: PVSetCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ /* dx -0.99999821 float angle -0.21089047 float zPos 0.99999857 float dz 4.6712832 float xPos -0.99999821 float atan3 -0.21089047 float dx 1.0000019 float angle 0.21089132 float zPos 1.0000004 float dz 4.6712813 float xPos 1.0000019 float atan3 0.21089132 float */ /* // int indexA = BBHelper::getIndex(beh,pMap,bbI_AxleSpeed); // int indexB = BBHelper::getIndex(beh,pMap,bbI_Steer); /* EnablePInputBySettings(beh,bbI_AxleSpeed); EnablePInputBySettings(beh,bbI_Steer); EnablePInputBySettings(beh,bbI_MotorTorque); EnablePInputBySettings(beh,bbI_BrakeTorque); EnablePInputBySettings(beh,bbI_SuspensionSpring); EnablePInputBySettings(beh,bbI_SuspensionTravel); EnablePInputBySettings(beh,bbI_Radius); */ /* case CKM_BEHAVIORDETACH: { /* BB_DECLARE_PIMAP; while ( pIMap->getArray().size() ) { BBParameter *p=pIMap->getArray().at(0); pIMap->getArray().erase(pIMap->getArray().begin()); delete p; p = NULL; } break; */ // BB_DECLARE_PIMAP; // BBHelper::destroyPIMap(beh,pIMap,BB_PMAP_SIZE); <file_sep>#ifndef _NVFILEDIALOG_H_ #define _NVFILEDIALOG_H_ #pragma warning (disable : 4786) #include <string> #pragma warning (disable : 4786) #include <vector> #pragma warning (disable : 4786) #include <TCHAR.H> typedef std::basic_string<TCHAR> tstring; //////////// // Helper class to assist in loading files // // Usage : // // Just create a NV*FileDialog object on the stack, and call Open // // NVXFileDialog aDialog; // // std::string theFileName; // // if ( aDialog.Open( theFileName ) ) // { // // open the filename and read it in // } // // // That's it ! // // Use the NVTextureFileDialog for texture files, // // or use the NVFileDialog to do arbitrary filters // class NVFileDialog { private : OPENFILENAME mOpenFileName; std::vector< tstring > mFilterNames; std::vector< tstring > mFilterStrings; tstring mString; void Init() { memset( &mOpenFileName, 0x00, sizeof( mOpenFileName ) ); mOpenFileName.lStructSize = sizeof( mOpenFileName ); OSVERSIONINFO osinfo; memset( &osinfo, 0x00, sizeof( osinfo ) ); BOOL bSuccess = ::GetVersionEx( &osinfo ); if ( osinfo.dwMajorVersion >= 0x0500 ) { mOpenFileName.lStructSize += ( 3 * sizeof( DWORD ) ); } mString.erase( mString.begin(), mString.end() ); mOpenFileName.Flags = OFN_FILEMUSTEXIST | OFN_LONGNAMES | OFN_SHAREAWARE; mOpenFileName.nFilterIndex = 1; for (unsigned int i = 0; i < mFilterNames.size(); ++i ) { mString += mFilterNames[ i ]; mString += TCHAR(0x00); mString += mFilterStrings[ i ]; mString += TCHAR(0x00); } // Last element must be double terminated mString += TCHAR(0x00); mOpenFileName.lpstrFilter = mString.c_str(); } public : ~NVFileDialog(){;} NVFileDialog() { mFilterNames.push_back(TEXT("*.*")); mFilterStrings.push_back(TEXT("")); } void SetFilters( const std::vector< tstring >& theFilterNames, const std::vector< tstring >& theFilterStrings ) { assert( mFilterNames.size() == theFilterStrings.size() ); mFilterNames = theFilterNames; mFilterStrings = theFilterStrings; } void SetFilter( const tstring& theFilterName ) { mFilterNames.clear(); mFilterStrings.clear(); mFilterNames.push_back( theFilterName ); mFilterStrings.push_back( theFilterName ); } virtual bool Open( tstring& theResult ) { Init(); theResult.resize(1024); theResult[0] = 0; mOpenFileName.lpstrFile = &theResult[ 0 ]; mOpenFileName.nMaxFile = 1024; BOOL bSuccess = ::GetOpenFileName( &mOpenFileName ); return ( bSuccess == TRUE ); } }; class NVXFileDialog : public NVFileDialog { public : NVXFileDialog() { SetFilter(TEXT("*.x")); } }; class NVTextureFileDialog : public NVFileDialog { public : NVTextureFileDialog() { SetFilter(TEXT("*.bmp;*.tga;*.dds")); } }; #endif _NVFILEDIALOG_H_ <file_sep>#include "StdAfx.h" #include "vtPhysXAll.h" #include "pEngine.h" #include "pVehicleAll.h" #include <xDebugTools.h> // Local trace? //#define LTRACE #define DEF_SIZE .25 #define DEF_MAXRPM 5000 #define DEF_MAXPOWER 100 #define DEF_FRICTION 0 #define DEF_MAXTORQUE 340 // ~ F1 Jos Verstappen #define DEF_TORQUE 100 // In case no curve is present //#define LTRACE // If USE_HARD_REVLIMIT is used, any rpm above the max. RPM // returns a 0 engine torque. Although this works, it gives quite // hard rev limits (esp. when in 1st gear). Better is to supply // a curve which moves down to 0 torque when rpm gets above maxRPM, // so a more natural (smooth) balance is obtained (and turn // this define off) //#define USE_HARD_REVLIMIT pEngine::pEngine(pVehicle *_car) : pDriveLineComp() { SetName("engine"); ownerVehicle=_car; driveLine=ownerVehicle->getDriveLine(); initData(); } pEngine::~pEngine() { } void pEngine::initData() // initData all member variables { flags=0; size=DEF_SIZE; mass=0; torqueReaction=0; maxRPM=DEF_MAXRPM; idleRPM=900; stallRPM=350; startRPM=900; autoClutchRPM=idleRPM*1.5f; //autoClutch=0; starterTorque=300; idleThrottle=0.1f; throttleRange=1000.0-idleThrottle*1000.0; friction=0; brakingCoeff=0; position.Set(0,0,0); maxTorque=0; throttle=0; brakes=0; size = 0.25f; //QDELETE(crvTorque); clean(); } void pEngine::clean() // Reset engine before usage (after Shift-R for example) { torqueReaction=0; //torqueCurve.clear(); pDriveLineComp::Reset(); // No automatic clutch engaged //flags&=~AUTOCLUTCH_ACTIVE; //flags|=AUTOCLUTCH_ACTIVE; // Start engine (or not) and make it stable; AFTER RDLC:clean(), since that // sets the rotational velocity to 0. if(flags&START_STALLED) { // Start with the engine off EnableStall(); setRPM(0); } else { // Pre-start engine DisableStall(); setRPM(idleRPM); } } void pEngine::setRPM(float rpm) { // Convert to radians and seconds rotV=rpm*2*PI/60.0f; } /* float pEngine::GetGearRatio(int n) { pLinearInterpolation &ratios = ((pGearBox*)(driveLine->gearbox))->getGearRatios(); if ( n >=0 && n <ratios.getSize() ) { return ratios.getValueAtIndex(n); } return -1.0f; } */ void pEngine::preStep() // Precalculate known numbers to speed up calculations during gameplay { float minT,maxT; // Calculate idle throttle based on desired idle RPM maxT=GetMaxTorque(idleRPM); minT=GetMinTorque(idleRPM); if(fabs(minT)<D3_EPSILON) { // There's no engine braking, hm //qwarn("pEngine: engine braking torque at rpm=%.f is 0;"" that's not realistic",idleRPM); idleThrottle=0; } else { // Calculate throttle at which resulting engine torque would be 0 idleThrottle=-minT/(maxT-minT); } // Calculate effective throttle range so that the throttle axis // can be more quickly converted to a 0..1 number. // This also includes converting from the controllers integer 0..1000 // range to 0..1 floating point. throttleRange=(1.0-idleThrottle)/1000.0; // clean engine clean(); //qdbg(" idleThrottle=%f, idleRPM=%f\n",idleThrottle,idleRPM); //qdbg(" brakingCoeff=%f, minT=%f/maxT=%f\n",brakingCoeff,minT,maxT); } void pEngine::updateUserControl(int ctlThrottle) // Controller input from 0..1000 // Calculates resulting throttle. { // Convert throttle to 0..1 (mind idle throttle offset) throttle=((float)ctlThrottle)*throttleRange+idleThrottle; if(throttle>1)throttle=1; else if(throttle<0)throttle=0; //qdbg("pEngine:updateUserControl(); ctlT=%d, throttle=%f\n",ctlThrottle,throttle); //qdbg(" idleThrottle=%f, idleRPM=%f\n",idleThrottle,idleRPM); //qdbg("pEngine:updateUserControl(ctlClutch=%d)\n",ctlClutch); //#define ND_AUTO_CLUTCH //#ifdef ND_AUTO_CLUTCH // Only update clutch value when the ownerVehicle is not auto-shifting #ifdef ND_AUTO_CLUTCH float ctlClutch = driveLine->GetClutchApplication(); bool autoShiftStart =true; if(!autoShiftStart) { clutch=((float)ctlClutch)/1000.0f; if(clutch>1)clutch=1; else if(clutch<0)clutch=0; } //#else // Pass clutch on to driveline //driveLine->SetClutchApplication(((float)ctlClutch)/1000.0f); // Directly set clutch //clutch=((float)ctlClutch)/1000.0f; //if(clutch>1)clutch=1; //else if(clutch<0)clutch=0; #endif } float pEngine::GetMaxTorque(float rpm) // Returns the maximum torque generated at 'rpm' { if ( getVehicle()->getProcessOptions() & pVPO_Engine_UseHardRevlimit) { // Clip hard at max rpm (return 0 torque if rpm gets too high) if(rpm>maxRPM) return 0; } if(!torqueCurve.getSize()) { // No curve available, use a less realistic constant torque return DEF_TORQUE; } else { float t; // Find normalized torque in RPM-to-torque curve t=(float)torqueCurve.getValue(rpm); t = 1 / maxTorque *t; //qdbg("pEngine: rpm=%.2f => T=%.2f, (curve)maxTorque=%.2f\n",rpm,t,maxTorque); return maxTorque*t; } } // Returns the minimum torque generated at 'rpm' (engine braking). float pEngine::GetMinTorque(float rpm) { // If 0% throttle, this is the minimal torque which is generated // by the engine return -brakingCoeff*rpm/60.0f; } void pEngine::CalcForces() { float minTorque,maxTorque; float rpm=getRPM(); static int starterDelay; // Temp crap to avoid multiple starter smps if(starterDelay>0) starterDelay--; // Check starter; this section assumes CalcForces() is called // only once per simulation step. Although this may not be // the case in the future, it should not harm that much. if(IsStalled()) { // There's only some engine braking // Note this skips calculating min/maxTorque tEngine=GetMinTorque(rpm); //qdbg("Stalled; check starter=%d\n",RMGR->controls->control[RControls::T_STARTER]->value); bool starter = true; if(starter) { // Use the starter tEngine+=starterTorque; // Raise the starter sample volume if(starterDelay==0) { starterDelay=1000/ownerVehicle->_lastDT; } //#ifdef LTRACE // qdbg(" starting; T_starter=%f, tEngine=%f\n",starterTorque,tEngine); //#endif } //#ifdef LTRACE // qdbg("Stalled engine torque: %.3f\n",tEngine); //#endif } else { // Engine is running // Calculate minimal torque (if 0% throttle) minTorque=GetMinTorque(rpm); // Calculate maximum torque (100% throttle situation) maxTorque=GetMaxTorque(rpm); // The throttle accounts for how much of the torque is actually // produced. // NOTE: The output power then is 2*PI*rps*outputTorque // (rps=rpm/60; rotations per second). Nothing but a statistic now. tEngine=(maxTorque-minTorque)*throttle+minTorque; #ifdef LTRACE qdbg("minTorque=%f, maxTorque=%.f, throttle=%f => torque=%f\n",minTorque,maxTorque,throttle,tEngine); #endif } } void pEngine::CalcAccelerations() { if(!driveLine->IsPrePostLocked()) { // Engine moves separately from the rest of the driveLine rotA=(tEngine-driveLine->GetClutchTorque())/GetInertia(); } // else rotA is calculated in the driveline (passed up // from the wheels on to the root - the engine) } void pEngine::Integrate() // Step the engine. // Also looks at the stall state (you can kickstart the engine when driving). { float rpm=getRPM(); // This is normally done by RDriveLineComp, but avoid the function call float timeStep= lastStepTimeSec; rotV+=rotA*timeStep; // Deduce state of engine (stalling) /*if(IsStalled()) { // Turning back on? if(rpm>=startRPM) { DisableStall(); } } else { // Stalling? if(rpm<stallRPM) { EnableStall(); // Trigger sample? } }*/ int autoClutch = 1; // Auto-clutch assist if(autoClutch) { if(rpm<autoClutchRPM) { // Engage clutch (is picked up by the driveline) float autoClutch=(rpm-idleRPM)/(autoClutchRPM-idleRPM); //qdbg("Autoclutch %f\n",autoClutch); ownerVehicle->getDriveLine()->EnableAutoClutch(); //flags|=AUTOCLUTCH_ACTIVE; if(autoClutch<0)autoClutch=0; else if(autoClutch>1)autoClutch=1; ownerVehicle->getDriveLine()->SetClutchApplication(autoClutch); } else { // Turn off auto-clutch ownerVehicle->getDriveLine()->DisableAutoClutch(); } } //qdbg(" post rotV=%.2f\n",rotV); } void pEngine::setToDefault() { torqueCurve.clear(); torqueCurve.insert(500.f, 193.f); torqueCurve.insert(2000.f, 134.f); torqueCurve.insert(4000.f, 175.f); torqueCurve.insert(5000.f, 175.f); torqueCurve.insert(6000.f, 166.f); torqueCurve.insert(7000.f, 166.f); /* torqueCurve.insert(466.0f, 0.46f); torqueCurve.insert(900.0f, 0.75f); torqueCurve.insert(1466.0f, 0.89f); torqueCurve.insert(2600.0f, 0.985f); torqueCurve.insert(3500.0f, 1.0f); torqueCurve.insert(4466.0f, 0.987f); torqueCurve.insert(5133.333f,0.97f); torqueCurve.insert(6933.0f, 0.631f); torqueCurve.insert(7500.0f, 0.0f); */ char buf[128],fname[128]; position.Set(0,0,0); size = 0.0f; maxRPM = 6200; idleRPM = 700; mass = 180.0; torqueReaction=1.0f; maxTorque=280.0f; forceFeedbackScale = 100.0f; SetInertia(0.3f); timeScale = 1.0f; rotationalEndFactor = 1.0f; friction=0.01f; brakingCoeff=0.1f; starterTorque=25; stallRPM=100.0f; startRPM=900; //autoClutchRPM=1250.0f; autoClutchRPM=1000.0f; //flags|=AUTOMATIC; flags|=AUTOCLUTCH_ACTIVE; //flags|=HAS_STARTER; preStep(); } void pEngine::setTorqueCurve(pLinearInterpolation val) { torqueCurve = val; preStep(); } void pEngine::setBrakingCoeff(float val) { brakingCoeff = val; preStep(); } void pEngine::setFriction(float val) { friction = val; preStep(); } void pEngine::setStartRPM(float val) { startRPM = val; preStep(); } void pEngine::setIdleRPM(float val) { idleRPM = val; preStep(); } void pEngine::setStarterTorque(float val) { starterTorque = val; preStep(); } float pEngine::getEndTorqueForWheel(CK3dEntity *wheelReference) { return 1; } /*void pEngine::SetInertia(float i) { inertia = i; preStep(); }*/ void pEngine::setFlags(int val) { } /* bool pEngine::Load(QInfo *info,cstring path) // 'path' may be 0, in which case the default "engine" is used { char buf[128],fname[128]; QInfo *infoCurve; if(!path)path="engine"; // Location sprintf(buf,"%s.x",path); position.x=info->GetFloat(buf); sprintf(buf,"%s.y",path); position.y=info->GetFloat(buf); sprintf(buf,"%s.z",path); position.z=info->GetFloat(buf); sprintf(buf,"%s.size",path); size=info->GetFloat(buf,DEF_SIZE); // Physical attribs #ifdef OBS sprintf(buf,"%s.rolling_friction_coeff",path); rollingFrictionCoeff=info->GetFloat(buf); #endif sprintf(buf,"%s.mass",path); mass=info->GetFloat(buf); // Power/torque sprintf(buf,"%s.max_rpm",path); maxRPM=info->GetFloat(buf,DEF_MAXRPM); sprintf(buf,"%s.idle_rpm",path); idleRPM=info->GetFloat(buf,1000); // Torque reaction sprintf(buf,"%s.torque_reaction",path); torqueReaction=info->GetFloat(buf); // Torque curve or constant (curve is preferred) //sprintf(buf,"%s.constant_torque",path); sprintf(buf,"%s.max_torque",path); maxTorque=info->GetFloat(buf,DEF_MAXTORQUE); crvTorque=new QCurve(); sprintf(buf,"%s.curve_torque",path); info->GetString(buf,fname); //qdbg("fname_torque='%s', maxTorque=%.2f\n",fname,maxTorque); if(fname[0]) { infoCurve=new QInfo(RFindFile(fname,ownerVehicle->GetDir())); crvTorque->Load(infoCurve,"curve"); QDELETE(infoCurve); } else { // No torque curve //QDELETE(crvTorque); } // Check torque curve in that it makes sense and is usable if(!crvTorque) { //qwarn("No torque curve (torque.crv?) present; you really should have one"); } else { // Make sure it ends at 0 (assuming no engine will rev above 100,000 rpm) if(fabs(crvTorque->GetValue(100000))>D3_EPSILON) { //qwarn("The torque curve needs to end at 0 torque (is now %.2f)", crvTorque->GetValue(100000)); } } sprintf(buf,"%s.inertia.engine",path); SetInertia(info->GetFloat(buf)); //inertiaEngine=info->GetFloat(buf); #ifdef OBS sprintf(buf,"%s.inertia.final_drive",path); inertiaDriveShaft=info->GetFloat(buf); #endif sprintf(buf,"%s.friction",path); friction=info->GetFloat(buf,DEF_FRICTION); sprintf(buf,"%s.braking_coeff",path); brakingCoeff=info->GetFloat(buf); // Starter engine sprintf(buf,"%s.starter",path); if(info->GetInt(buf,1)) flags|=HAS_STARTER; sprintf(buf,"%s.start_stalled",path); if(info->GetInt(buf,1)) flags|=START_STALLED; sprintf(buf,"%s.starter_torque",path); starterTorque=info->GetFloat(buf); sprintf(buf,"%s.stall_rpm",path); stallRPM=info->GetFloat(buf); sprintf(buf,"%s.start_rpm",path); startRPM=info->GetFloat(buf); sprintf(buf,"%s.autoclutch_rpm",path); autoClutchRPM=info->GetFloat(buf); #ifdef OBS // Shifting sprintf(buf,"%s.shifting.automatic",path); if(info->GetInt(buf)) flags|=AUTOMATIC; //qdbg("Autoshift: flags=%d, buf='%s'\n",flags,buf); sprintf(buf,"%s.shifting.shift_up_rpm",path); shiftUpRPM=info->GetFloat(buf,3500); sprintf(buf,"%s.shifting.shift_down_rpm",path); shiftDownRPM=info->GetFloat(buf,2000); sprintf(buf,"%s.shifting.time_to_declutch",path); timeToDeclutch=info->GetInt(buf,500); sprintf(buf,"%s.shifting.time_to_clutch",path); timeToClutch=info->GetInt(buf,500); // Gearbox path="gearbox"; // ! sprintf(buf,"%s.gears",path); gears=info->GetInt(buf,4); for(i=0;i<gears;i++) { sprintf(buf,"%s.gear%d.ratio",path,i); gearRatio[i]=info->GetFloat(buf,1.0); sprintf(buf,"%s.gear%d.inertia",path,i); gearInertia[i]=info->GetFloat(buf); } sprintf(buf,"%s.end_ratio",path); endRatio=info->GetFloat(buf,3.0); #endif // Calculate static facts preStep(); return TRUE; } */ /* void pEngine::OnGfxFrame() { } void pEngine::DbgPrint(cstring s) { qdbg("pEngine state (%s):\n",s); qdbg(" rpm=%.2f, stalled: %d, idleThrottle: %.2f, Treaction=%.2f\n", getRPM(),IsStalled(),idleThrottle,torqueReaction); } bool pEngine::LoadState(QFile *f) { RDriveLineComp::LoadState(f); return TRUE; } bool pEngine::SaveState(QFile *f) { RDriveLineComp::LoadState(f); return TRUE; } */ <file_sep>/******************************************************************** created: 2007/11/28 created: 28:11:2007 15:43 filename: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Misc\CustomPlayerProfileXML.cpp file path: f:\ProjectRoot\current\vt_player\exKamPlayer\src\Misc file base: CustomPlayerProfileXML file ext: cpp author: mc007 purpose: *********************************************************************/ #include <CPStdAfx.h> #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" xEApplicationMode CCustomPlayer::PGetApplicationMode() { return m_AppMode; } xSApplicationWindowStyle * CCustomPlayer::GetPAppStyle() { return m_AWStyle; } xSEngineWindowInfo * CCustomPlayer::GetEWindowInfo() { return m_EngineWindowInfo; } /*USHORT CCustomPlayer::PLoadEnginePathProfile(const char* configFile) { return m_EPaths; }*/ xSEnginePaths* CCustomPlayer::GetEPathProfile() { return m_EPaths; } ////////////////////////////////////////////////////////////////////////// // // // // ////////////////////////////////////////////////////////////////////////// extern CCustomPlayer* thePlayer; USHORT CCustomPlayer::PLoadResourcePaths(const char* configFile,const char*section,int resourceType) { if (!this->m_CKContext)return -1; CKPathManager *pm = (CKPathManager*)this->m_CKContext->GetPathManager(); if (!pm)return -1; USHORT error = CPE_OK; char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,configFile); int errorLine; XString errorText; VxConfiguration config; VxConfigurationSection *tsection = NULL; VxConfigurationEntry *entry = NULL; if (!config.BuildFromFile(Ini, errorLine, errorText)) { MessageBox(NULL,"Cannot open Configfile",0,MB_OK|MB_ICONERROR); return CPE_PROFILE_ERROR_FILE_INCORRECT; } if ((tsection = config.GetSubSection((char*)section, FALSE)) != NULL) { ConstEntryIt it = tsection->BeginChildEntry(); VxConfigurationEntry *sEntry = NULL; char newPath[MAX_PATH]; while (sEntry=tsection->GetNextChildEntry(it)) { if (sEntry!=NULL) { const char * value = sEntry->GetValue(); sprintf(newPath,"%s%s%s",drive,dir,value); pm->AddPath(resourceType,XString(newPath)); } } } } //************************************ // Method: PLoadAppStyleProfile // FullName: CCustomPlayerApp::PLoadAppStyleProfile // Access: protected // Returns: USHORT // Qualifier: // Parameter: const char* configFile // Parameter: vtPlayer::Structs::xEApplicationWindowStyle& result //************************************ USHORT CCustomPlayer::PLoadAppStyleProfile(const char* configFile) { USHORT error = CPE_OK; char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,configFile); int errorLine; XString errorText; VxConfiguration config; VxConfigurationSection *section = NULL; VxConfigurationEntry *entry = NULL; if (!config.BuildFromFile(Ini, errorLine, errorText)) { MessageBox(NULL,"Cannot open Configfile",0,MB_OK|MB_ICONERROR); return CPE_PROFILE_ERROR_FILE_INCORRECT; } if ((section = config.GetSubSection("ApplicationConfiguration", FALSE)) != NULL) { ////////////////////////////////////////////////////////////////////////// // MouseDragsWindow entry = section->GetEntry("MouseDragsWindow"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_MouseDrag = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } ////////////////////////////////////////////////////////////////////////// // MouseDragsWindow entry = section->GetEntry("OwnerDrawed"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_OwnerDrawed = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } ////////////////////////////////////////////////////////////////////////// // HasRenderWindow entry = section->GetEntry("Render"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_Render = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; printf(value); } ////////////////////////////////////////////////////////////////////////// entry = section->GetEntry("AlwayOnTop"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_AOT = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } ////////////////////////////////////////////////////////////////////////// // CaptionBar entry = section->GetEntry("Title"); if (entry != NULL) { m_AWStyle->g_AppTitle = entry->GetValue(); } ////////////////////////////////////////////////////////////////////////// // Show Loading Progress : entry = section->GetEntry("ShowLoadingProcess"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_ShowLoadingProcess= tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } ////////////////////////////////////////////////////////////////////////// //splash entry = section->GetEntry("UseSplash"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_UseSplash = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } ////////////////////////////////////////////////////////////////////////// //ShowDialog entry = section->GetEntry("ShowDialog"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_ShowDialog = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } ////////////////////////////////////////////////////////////////////////// //ShowAboutTab entry = section->GetEntry("ShowAboutTab"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_ShowAboutTab = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } ////////////////////////////////////////////////////////////////////////// //ShowConfigTab entry = section->GetEntry("ShowConfigTab"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_ShowConfigTab= tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } ////////////////////////////////////////////////////////////////////////// //MinDirectXVersion entry = section->GetEntry("MinDirectXVersion"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_MinimumDirectXVersion= tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } ////////////////////////////////////////////////////////////////////////// //MinRAM entry = section->GetEntry("MinRAM"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_AWStyle->g_MiniumumRAM= tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } } return error; } //************************************ // Method: PLoadEngineWindowProperties // FullName: CCustomPlayerApp::PLoadEngineWindowProperties // Access: protected // Returns: USHORT // Qualifier: // Parameter: const char *configFile // Parameter: vtPlayer::Structs::xEEngineWindowInfo& result //************************************ USHORT CCustomPlayer::PLoadEngineWindowProperties(const char *configFile) { USHORT error = CPE_OK; char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,configFile); int errorLine; XString errorText; VxConfiguration config; VxConfigurationSection *section = NULL; VxConfigurationEntry *entry = NULL; if (!config.BuildFromFile(Ini, errorLine, errorText)) { MessageBox(NULL,"Cannot open Configfile",0,MB_OK|MB_ICONERROR); return CPE_PROFILE_ERROR_FILE_INCORRECT; } if ((section = config.GetSubSection("VideoSettings", FALSE)) != NULL) { // WindowWidth (optional) entry = section->GetEntry("WindowWidth"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_WidthW = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } // WindowHeight (optional) entry = section->GetEntry("WindowHeight"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_HeightW = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } // FullscreenWidth (optional) entry = section->GetEntry("FullscreenWidth"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_Width = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } // FullscreenHeight entry = section->GetEntry("FullscreenHeight"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_Height= tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } // FullscreenBpp : entry = section->GetEntry("Bpp"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_Bpp= tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } // FullscreenDriver : entry = section->GetEntry("FullScreenDriver"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_FullScreenDriver = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } // FullscreenDriver : entry = section->GetEntry("WindowedDriver"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_WindowedDriver = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } // RefreshRate : entry = section->GetEntry("RefreshRate"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_RefreshRate = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } //ScreenMode : entry = section->GetEntry("Mode"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_Mode = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } //AntiAlias : entry = section->GetEntry("AntiAlias"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->FSSA = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } //Fullscreen : entry = section->GetEntry("FullScreen"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_GoFullScreen = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } //HasResolutionMask : entry = section->GetEntry("HasResolutionMask"); if (entry != NULL) { const char * value = entry->GetValue(); int tmp = 0; if(sscanf(value,"%d",&tmp)==1) { m_EngineWindowInfo->g_HasResMask = tmp; } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } //HasResolutionMaskX : entry = section->GetEntry("XResolutions"); if (entry != NULL) { const char * value = entry->GetValue(); if(value) { XStringTokenizer tokizer(value, ","); const char*tok = NULL; while (tokizer.NextToken(tok)) { tok = tokizer.NextToken(tok); XString xtok(tok); m_EngineWindowInfo->g_ResMaskArrayX.PushBack(xtok.ToInt()); } } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } //HasResolutionMaskY : entry = section->GetEntry("YResolutions"); if (entry != NULL) { const char * value = entry->GetValue(); if(value) { XStringTokenizer tokizer(value, ","); const char*tok = NULL; while (tokizer.NextToken(tok)) { tok = tokizer.NextToken(tok); XString xtok(tok); m_EngineWindowInfo->g_ResMaskArrayY.PushBack(xtok.ToInt()); } } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } //Allowed OpenGL versions ; entry = section->GetEntry("OpenGLVersions"); if (entry != NULL) { const char * value = entry->GetValue(); if(value) { XStringTokenizer tokizer(value, ","); const char*tok = NULL; while (tokizer.NextToken(tok)) { tok = tokizer.NextToken(tok); XString xtok(tok); m_EngineWindowInfo->g_OpenGLMask.PushBack(xtok); } } else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } } ////////////////////////////////////////////////////////////////////////// //todo : m_FullscreenBpp = GetEngineWindowInfo()->g_Bpp; m_FullscreenHeight= GetEngineWindowInfo()->g_Height; m_FullscreenWidth = GetEngineWindowInfo()->g_Width; m_FullscreenRefreshRate = GetEngineWindowInfo()->g_RefreshRate; m_WindowedWidth = GetEngineWindowInfo()->g_WidthW; m_WindowedHeight = GetEngineWindowInfo()->g_HeightW; return error; } //************************************ // Method: PLoadEnginePathProfile // FullName: vtBaseWindow::PLoadEnginePathProfile // Access: public // Returns: USHORT // Qualifier: // Parameter: const char* configFile //************************************ USHORT CCustomPlayer::PLoadEnginePathProfile(const char* configFile) { USHORT error = CPE_OK; char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,configFile); int errorLine; XString errorText; VxConfiguration config; VxConfigurationSection *section = NULL; VxConfigurationEntry *entry = NULL; if (!config.BuildFromFile(Ini, errorLine, errorText)) { MessageBox(NULL,"Cannot open Configfile",0,MB_OK|MB_ICONERROR); return CPE_PROFILE_ERROR_FILE_INCORRECT; } if ((section = config.GetSubSection("Paths", FALSE)) != NULL) { // Disable hotkeys (optional) entry = section->GetEntry("RenderEngines"); if (entry != NULL) { GetEPathProfile()->RenderPath = entry->GetValue(); } entry = section->GetEntry("ManagerPath"); if (entry != NULL) { GetEPathProfile()->ManagerPath = entry->GetValue() ; } entry = section->GetEntry("BehaviorPath"); if (entry != NULL) { GetEPathProfile()->BehaviorPath = entry->GetValue(); } entry = section->GetEntry("PluginPath"); if (entry != NULL) { GetEPathProfile()->PluginPath = entry->GetValue(); } entry = section->GetEntry("LoadFile"); if (entry != NULL) { GetEPathProfile()->CompositionFile = entry->GetValue(); } entry = section->GetEntry("DecompressFile"); if (entry != NULL) { GetEPathProfile()->DecompressFile = entry->GetValue(); } entry = section->GetEntry("Installdirectory"); if (entry != NULL) { GetEPathProfile()->InstallDirectory = entry->GetValue(); } } section->Clear(); config.Clear(); return error; } USHORT CCustomPlayer::PSaveEngineWindowProperties(const char *configFile,const vtPlayer::Structs::xSEngineWindowInfo& input) { USHORT error = CPE_OK; char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,configFile); int errorLine; XString errorText; VxConfiguration config; VxConfigurationSection *section = NULL; VxConfigurationEntry *entry = NULL; if (!config.BuildFromFile(Ini, errorLine, errorText)) { MessageBox(NULL,"Cannot open Configfile",0,MB_OK|MB_ICONERROR); return CPE_PROFILE_ERROR_FILE_INCORRECT; } if ((section = config.GetSubSection("VideoSettings", FALSE)) != NULL) { // WindowWidth (optional) entry = section->GetEntry("WindowWidth"); if (entry != NULL) { entry->SetValue(input.g_WidthW); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // WindowHeight (optional) entry = section->GetEntry("WindowHeight"); if (entry != NULL) { entry->SetValue(input.g_HeightW); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // FullscreenHeight entry = section->GetEntry("FullscreenHeight"); if (entry != NULL) { entry->SetValue(input.g_Height); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // FullscreenWidth entry = section->GetEntry("FullscreenWidth"); if (entry != NULL) { entry->SetValue(input.g_Width); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // FSSA entry = section->GetEntry("AntiAlias"); if (entry != NULL) { entry->SetValue(input.FSSA); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // Bpp entry = section->GetEntry("Bpp"); if (entry != NULL) { entry->SetValue(input.g_Bpp); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // Driver entry = section->GetEntry("FullScreenDriver"); if (entry != NULL) { entry->SetValue(input.g_FullScreenDriver); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // Driver entry = section->GetEntry("WindowedDriver"); if (entry != NULL) { entry->SetValue(input.g_WindowedDriver); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // RefreshRate entry = section->GetEntry("RefreshRate"); if (entry != NULL) { entry->SetValue(input.g_RefreshRate); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // Mode entry = section->GetEntry("Mode"); if (entry != NULL) { entry->SetValue(input.g_Mode); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; // FullScreen entry = section->GetEntry("FullScreen"); if (entry != NULL) { entry->SetValue(input.g_GoFullScreen); }else error = CPE_PROFILE_ERROR_ENTRY_INCORRECT; } config.SaveToFile(Ini); return error; }<file_sep>/******************************************************************** created: 2009/04/13 created: 13:4:2009 21:58 filename: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Include\Core\gConfig.h file path: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Include\Core file base: gConfig file ext: h author: <NAME> purpose: Global configuration for this component *********************************************************************/ #ifndef __G_CONFIG_H__ #define __G_CONFIG_H__ /*! \brief Enables access from an external application. All related code needs to enabled by this macro */ //#define G_EXTERNAL_ACCESS #endif<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xDistributedSession.h" #include <vtTools.h> #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorNGetInterfacesDecl(); CKERROR CreateNGetInterfacesProto(CKBehaviorPrototype **); int NGetInterfaces(const CKBehaviorContext& behcontext); CKERROR NGetInterfacesCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorNGetInterfacesDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NGetInterfaces"); od->SetDescription("Returns all systems network devices"); od->SetCategory("TNL/Server"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5a6a0ae6,0x11f86ec3)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNGetInterfacesProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } typedef enum BB_IT { BB_IT_IN, BB_IT_NEXT, }; typedef enum BB_OT { BB_O_OUT, BB_O_INTERFACE, BB_O_ERROR, }; typedef enum BB_OP { BB_OP_INTERFACE_ADDRESS, BB_OP_ERROR }; CKERROR CreateNGetInterfacesProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NGetInterfaces"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareInput("Next"); proto->DeclareOutput("Exit"); proto->DeclareOutput("Interface"); proto->DeclareOutput("Error"); proto->DeclareOutParameter("Interface", CKPGUID_STRING, "FALSE"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareLocalParameter("current result", CKPGUID_POINTER, "0"); proto->DeclareLocalParameter("currentArrayIndex", CKPGUID_INT,0 ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(NGetInterfaces); proto->SetBehaviorCallbackFct(NGetInterfacesCB); *pproto = proto; return CK_OK; } typedef TNL::Vector<TNL::Address>interfaceList; int NGetInterfaces(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); using namespace vtTools::BehaviorTools; if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); bool isTemporary = false; xNetInterface *cin = GetNM()->GetServerNetInterface(); if (!cin) { cin = GetNM()->GetClientNetInterface(); } if (!cin) { GetNM()->CreateClient(true,0,NULL); cin = GetNM()->GetClientNetInterface(); isTemporary = true; } interfaceList *sResults = NULL; beh->GetLocalParameterValue(0,&sResults); if (!sResults) { sResults = new interfaceList(); }else sResults->clear(); int currentIndex=0; beh->SetLocalParameterValue(1,&currentIndex); if (cin) { TNL::Socket *socket = &cin->getSocket(); if (socket) { if (socket->isValid()) { socket->getInterfaceAddresses(sResults); } } } if (isTemporary) { GetNM()->SetClientNetInterface(NULL); } beh->SetLocalParameterValue(0,&sResults); if (sResults->size()) { beh->ActivateInput(BB_IT_NEXT); }else { beh->ActivateOutput(BB_O_OUT); return 0; } } ////////////////////////////////////////////////////////////////////////// if (beh->IsInputActive(1)) { beh->ActivateInput(1,FALSE); int currentIndex=0; beh->GetLocalParameterValue(1,&currentIndex); interfaceList *sResults = NULL; beh->GetLocalParameterValue(0,&sResults); if (!sResults) { beh->ActivateOutput(0); return 0; } if (currentIndex>=sResults->size()) { sResults->clear(); beh->ActivateOutput(BB_O_OUT); return 0; } TNL::Vector<TNL::Address>& list = *sResults; TNL::Address *addr = &list[currentIndex]; if (addr) { CKParameterOut *pout = beh->GetOutputParameter(BB_OP_INTERFACE_ADDRESS); pout->SetStringValue(const_cast<char*>(addr->toString())); } currentIndex++; beh->SetLocalParameterValue(1,&currentIndex); beh->ActivateOutput(1); } return CKBR_OK; } CKERROR NGetInterfacesCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtAttributeHelper.h" using namespace xUtils; using namespace vtAgeia; using namespace vtTools::ParameterTools; using namespace vtTools::AttributeTools; int registerJD6(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { return 0; } int registerJD6Drive(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { return 0; } int registerJLimitPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { //---------------------------------------------------------------- // // get and check objects // if (!target) return -1; CKParameterOut *attParameter = target->GetAttributeParameter(attributeType); if (!attParameter) return -1; CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; pRigidBody *body = GetPMan()->getBody(target); if (!body) return -1; CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(attParameter,PS_JLP_BODY_B_REF); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); if (set) { //---------------------------------------------------------------- // // post pone i ck-start-up or loading // if (isPostJob && GetPMan()->GetContext()->IsPlaying()) { pAttributePostObject postAttObject(target->GetID(),registerJLimitPlane,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); return true; } int jointType = GetValueFromParameterStruct<int>(attParameter,PS_JLP_JOINT_TYPE); //try to get the joint pJoint *joint = GetPMan()->getJoint(target,bodyBEnt,(JType)jointType); if (!joint) return -1; //---------------------------------------------------------------- // // we are on ck-play or SetAttribute-BB : Retrieve all parameters from the attribute : // VxVector limitPoint = GetValueFromParameterStruct<VxVector>(attParameter,PS_JLP_LIMIT_POINT); CK_ID limitPointRefID = GetValueFromParameterStruct<CK_ID>(attParameter,PS_JLP_LIMIT_POINT_REF); CK3dEntity *limiPointRef = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(limitPointRefID)); if (limiPointRef) limiPointRef->Transform(&limitPoint,&limitPoint); int isOnBodyB = GetValueFromParameterStruct<int>(attParameter,PS_JLP_IS_ON_BODY_B); float length = limitPoint.SquareMagnitude(); if (XAbs(limitPoint.SquareMagnitude()) >=0.01f) joint->setLimitPoint(limitPoint,isOnBodyB); // - Limit Point Normal VxVector limitPointNormal = GetValueFromParameterStruct<VxVector>(attParameter,PS_JLP_NORMAL); CK_ID limitPointNormalRefID = GetValueFromParameterStruct<CK_ID>(attParameter,PS_JLP_NORMAL_REF); CK3dEntity *limitPointNormalRef = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(limitPointNormalRefID)); if (limitPointNormalRef) { VxVector dir,up,right; limitPointNormalRef->GetOrientation(&dir,&up,&right); limitPointNormalRef->TransformVector(&limitPointNormal,&up); } // - Point in Plane VxVector PointInPlane = GetValueFromParameterStruct<VxVector>(attParameter,PS_JLP_PT_IN_PLANE); CK_ID PointInPlaneRefID = GetValueFromParameterStruct<CK_ID>(attParameter,PS_JLP_PT_IN_PLANE_REF); CK3dEntity *PointInPlaneRef = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(PointInPlaneRefID)); if (PointInPlaneRef) PointInPlaneRef->Transform(&PointInPlane,&PointInPlane); // - Restitution float res = GetValueFromParameterStruct<float>(attParameter,PS_JLP_RESTITUTION); // - Execute int result = joint->addLimitPlane(limitPointNormal,PointInPlane,res); return result; } } int registerJPointOnLine(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { using namespace vtTools::ParameterTools; CKParameterOut *pointInPlaneParameter = target->GetAttributeParameter(attributeType); CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; if (pointInPlaneParameter ) { pRigidBody *body = GetPMan()->getBody(target); if (!body)return -1; CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(pointInPlaneParameter,PS_JPOL_BODY_B); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); if (bodyB && bodyB->getWorld() != body->getWorld() ) return -1; if (set) { if (isPostJob && GetPMan()->GetContext()->IsPlaying()) { pAttributePostObject postAttObject(target->GetID(),registerJPointOnLine,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); return true; } if (bodyB && body->isConnected(bodyBEnt) ) return -1; VxVector anchor0 = GetValueFromParameterStruct<VxVector>(pointInPlaneParameter,PS_JPOL_ANCHOR); CK_ID anchor0RefID = GetValueFromParameterStruct<CK_ID>(pointInPlaneParameter,PS_JPOL_ANCHOR_REF); ////////////////////////////////////////////////////////////////////////// //anchor : CK3dEntity *a0Ref = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(anchor0RefID)); if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); int collision = GetValueFromParameterStruct<int>(pointInPlaneParameter,PS_JPOL_COLLISION); ////////////////////////////////////////////////////////////////////////// //axis VxVector axis = GetValueFromParameterStruct<VxVector>(pointInPlaneParameter,PS_JPOL_AXIS); CK_ID axisRefID = GetValueFromParameterStruct<CK_ID>(pointInPlaneParameter,PS_JPOL_AXIS_REF); CK3dEntity *axisRef = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(axisRefID)); if (axisRef) { VxVector dir,up,right; axisRef->GetOrientation(&dir,&up,&right); axisRef->TransformVector(&axis,&up); } pJointPointOnLine*joint = static_cast<pJointPointOnLine*>(pFactory::Instance()->createPointOnLineJoint(target,bodyBEnt,anchor0,axis)); if (joint) { joint->enableCollision(collision); float maxForce = GetValueFromParameterStruct<float>(pointInPlaneParameter,PS_JPOL_MAX_FORCE); float maxTorque = GetValueFromParameterStruct<float>(pointInPlaneParameter,PS_JPOL_MAX_TORQUE); joint->setBreakForces(maxForce,maxTorque); return 1; } return 0; }else { pJoint *joint = body->isConnected(bodyBEnt); if ( joint) { body->getWorld()->deleteJoint(joint); } pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_PointOnLine); if (joint2) { body->getWorld()->deleteJoint(joint); } return 1; } } return 0; } int registerJPointInPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { using namespace vtTools::ParameterTools; CKParameterOut *pointInPlaneParameter = target->GetAttributeParameter(attributeType); CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; if (pointInPlaneParameter ) { pRigidBody *body = GetPMan()->getBody(target); if (!body)return -1; CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(pointInPlaneParameter,PS_JPIP_BODY_B); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); if (bodyB && bodyB->getWorld() != body->getWorld() ) return -1; if (set) { if (isPostJob && GetPMan()->GetContext()->IsPlaying()) { pAttributePostObject postAttObject(target->GetID(),registerJPointInPlane,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); return true; } if (bodyB && body->isConnected(bodyBEnt) ) return -1; VxVector anchor0 = GetValueFromParameterStruct<VxVector>(pointInPlaneParameter,PS_JPIP_ANCHOR); CK_ID anchor0RefID = GetValueFromParameterStruct<CK_ID>(pointInPlaneParameter,PS_JPIP_ANCHOR_REF); ////////////////////////////////////////////////////////////////////////// //anchor : CK3dEntity *a0Ref = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(anchor0RefID)); if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); int collision = GetValueFromParameterStruct<int>(pointInPlaneParameter,PS_JPIP_COLLISION); ////////////////////////////////////////////////////////////////////////// //axis VxVector axis = GetValueFromParameterStruct<VxVector>(pointInPlaneParameter,PS_JPIP_AXIS); CK_ID axisRefID = GetValueFromParameterStruct<CK_ID>(pointInPlaneParameter,PS_JPIP_AXIS_REF); CK3dEntity *axisRef = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(axisRefID)); if (axisRef) { VxVector dir,up,right; axisRef->GetOrientation(&dir,&up,&right); axisRef->TransformVector(&axis,&up); } //pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) pJointPointInPlane*joint = static_cast<pJointPointInPlane*>(pFactory::Instance()->createPointInPlaneJoint(target,bodyBEnt,anchor0,axis)); if (joint) { joint->enableCollision(collision); float maxForce = GetValueFromParameterStruct<float>(pointInPlaneParameter,PS_JPIP_MAX_FORCE); float maxTorque = GetValueFromParameterStruct<float>(pointInPlaneParameter,PS_JPIP_MAX_TORQUE); joint->setBreakForces(maxForce,maxTorque); return 1; } return 0; }else { pJoint *joint = body->isConnected(bodyBEnt); if ( joint) { body->getWorld()->deleteJoint(joint); } pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_PointInPlane); if (joint2) { body->getWorld()->deleteJoint(joint); } return 1; } } return 0; } int registerJRevolute(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { int s = GetPMan()->getAttributePostObjects().Size(); using namespace vtTools::ParameterTools; CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; if (distanceParameter ) { pRigidBody *body = GetPMan()->getBody(target); if (!body)return -1; CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JREVOLUTE_BODY_B); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); if (bodyB && bodyB->getWorld() != body->getWorld() ) return -1; if (set) { if (isPostJob && GetPMan()->GetContext()->IsPlaying()) { pAttributePostObject postAttObject(target->GetID(),registerJRevolute,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); return true; } if (bodyB && body->isConnected(bodyBEnt) ) return -1; VxVector anchor0 = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JREVOLUTE_ANCHOR); CK_ID anchor0RefID = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JREVOLUTE_ANCHOR_REF); CK3dEntity *a0Ref = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(anchor0RefID)); if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); ////////////////////////////////////////////////////////////////////////// //axis VxVector axis = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JREVOLUTE_AXIS); CK_ID axisRefID = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JREVOLUTE_AXIS_REF); CK3dEntity *axisRef = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(axisRefID)); if (axisRef) { VxVector dir,up,right; axisRef->GetOrientation(&dir,&up,&right); axisRef->TransformVector(&axis,&up); } int collision = GetValueFromParameterStruct<int>(distanceParameter,PS_JREVOLUTE_COLLISION); int projectionMode = GetValueFromParameterStruct<int>(distanceParameter,PS_JREVOLUTE_PROJ_MODE); float projectionDistance= GetValueFromParameterStruct<float>(distanceParameter,PS_JREVOLUTE_PROJ_DISTANCE); float projectionAngle = GetValueFromParameterStruct<float>(distanceParameter,PS_JREVOLUTE_PROJ_ANGLE); pJointLimit limitHigh = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_LIMIT_HIGH)); pJointLimit limitLow= pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_LIMIT_LOW)); pSpring spring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_SPRING)); pMotor motor = pFactory::Instance()->createMotorFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_MOTOR)); pJointRevolute*joint = static_cast<pJointRevolute*>(pFactory::Instance()->createRevoluteJoint(target,bodyBEnt,anchor0,axis)); if (joint) { joint->enableCollision(collision); joint->setLowLimit(limitLow); joint->setHighLimit(limitHigh); joint->setSpring(spring); if (projectionMode!=0) { joint->setProjectionMode((ProjectionMode)projectionMode); joint->setProjectionDistance(projectionDistance); joint->setProjectionAngle(projectionAngle); } float maxForce = GetValueFromParameterStruct<float>(distanceParameter,PS_JREVOLUTE_MAX_FORCE); float maxTorque = GetValueFromParameterStruct<float>(distanceParameter,PS_JREVOLUTE_MAX_TORQUE); if (maxTorque !=0.0f || maxForce!=0.0f) { joint->setBreakForces(maxForce,maxTorque); } return true; } return 0; }else { pJoint *joint = body->isConnected(bodyBEnt); if ( joint) { body->getWorld()->deleteJoint(joint); } pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Revolute); if (joint2) { body->getWorld()->deleteJoint(joint); } } } return 0; } int registerJCylindrical(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { using namespace vtTools::ParameterTools; CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; if (distanceParameter ) { pRigidBody *body = GetPMan()->getBody(target); if (!body)return -1; CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JCYLINDRICAL_BODY_B); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); if (bodyB && bodyB->getWorld() != body->getWorld() ) return -1; if (set) { if (isPostJob && GetPMan()->GetContext()->IsPlaying()) { pAttributePostObject postAttObject(target->GetID(),registerJCylindrical,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); return true; } if (bodyB && body->isConnected(bodyBEnt) ) return -1; VxVector anchor0 = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JCYLINDRICAL_ANCHOR); CK_ID anchor0RefID = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JCYLINDRICAL_ANCHOR_REF); ////////////////////////////////////////////////////////////////////////// //anchor : CK3dEntity *a0Ref = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(anchor0RefID)); if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); int collision = GetValueFromParameterStruct<int>(distanceParameter,PS_JCYLINDRICAL_COLLISION); ////////////////////////////////////////////////////////////////////////// //axis VxVector axis = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JCYLINDRICAL_AXIS); CK_ID axisRefID = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JCYLINDRICAL_AXIS_REF); CK3dEntity *axisRef = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(axisRefID)); if (axisRef) { VxVector dir,up,right; axisRef->GetOrientation(&dir,&up,&right); axisRef->TransformVector(&axis,&up); } //pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) pJointCylindrical*joint = static_cast<pJointCylindrical*>(pFactory::Instance()->createCylindricalJoint(target,bodyBEnt,anchor0,axis)); if (joint) { joint->enableCollision(collision); float maxForce = GetValueFromParameterStruct<float>(distanceParameter,PS_JCYLINDRICAL_MAX_FORCE); float maxTorque = GetValueFromParameterStruct<float>(distanceParameter,PS_JCYLINDRICAL_MAX_TORQUE); //joint->setBreakForces(maxForce,maxTorque); return true; } return 0; }else { pJoint *joint = body->isConnected(bodyBEnt); if ( joint) { body->getWorld()->deleteJoint(joint); } pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Cylindrical); if (joint2) { body->getWorld()->deleteJoint(joint); } } } return 0; } int registerJPrismatic(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { using namespace vtTools::ParameterTools; CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; if (distanceParameter ) { pRigidBody *body = GetPMan()->getBody(target); if (!body)return -1; CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JPRISMATIC_BODY_B); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); if (bodyB && bodyB->getWorld() != body->getWorld() ) return -1; if (set) { if (isPostJob && GetPMan()->GetContext()->IsPlaying()) { pAttributePostObject postAttObject(target->GetID(),registerJPrismatic,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); return true; } if (bodyB && body->isConnected(bodyBEnt) ) return -1; VxVector anchor0 = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JPRISMATIC_ANCHOR); CK_ID anchor0RefID = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JPRISMATIC_ANCHOR_REF); ////////////////////////////////////////////////////////////////////////// //anchor : CK3dEntity *a0Ref = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(anchor0RefID)); if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); int collision = GetValueFromParameterStruct<int>(distanceParameter,PS_JPRISMATIC_COLLISION); ////////////////////////////////////////////////////////////////////////// //axis VxVector axis = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JPRISMATIC_AXIS); CK_ID axisRefID = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JPRISMATIC_AXIS_REF); CK3dEntity *axisRef = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(axisRefID)); if (axisRef) { VxVector dir,up,right; axisRef->GetOrientation(&dir,&up,&right); axisRef->TransformVector(&axis,&up); } //pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) pJointCylindrical*joint = static_cast<pJointCylindrical*>(pFactory::Instance()->createCylindricalJoint(target,bodyBEnt,anchor0,axis)); if (joint) { joint->enableCollision(collision); float maxForce = GetValueFromParameterStruct<float>(distanceParameter,PS_JCYLINDRICAL_MAX_FORCE); float maxTorque = GetValueFromParameterStruct<float>(distanceParameter,PS_JCYLINDRICAL_MAX_TORQUE); joint->setBreakForces(maxForce,maxTorque); return true; } return 0; }else { pJoint *joint = body->isConnected(bodyBEnt); if ( joint) { body->getWorld()->deleteJoint(joint); } pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Prismatic); if (joint2) { body->getWorld()->deleteJoint(joint); } } } return 0; } int registerJBall(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { using namespace vtTools::ParameterTools; CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; if (distanceParameter ) { pRigidBody *body = GetPMan()->getBody(target); if (!body)return -1; CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JBALL_BODY_B); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); if (bodyB && bodyB->getWorld() != body->getWorld() ) return -1; if (set) { if (isPostJob && GetPMan()->GetContext()->IsPlaying()) { pAttributePostObject postAttObject(target->GetID(),registerJBall,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); return true; } if (bodyB && body->isConnected(bodyBEnt) ) return -1; VxVector anchor0 = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JBALL_ANCHOR); CK_ID anchor0RefID = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JBALL_ANCHOR_REF); CK3dEntity *a0Ref = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(anchor0RefID)); if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); VxVector swingAxis = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JBALL_LIMIT_SWING_AXIS); int collision = GetValueFromParameterStruct<int>(distanceParameter,PS_JBALL_COLLISION); int projectionMode = GetValueFromParameterStruct<int>(distanceParameter,PS_JBALL_PROJ_MODE); float minDist = GetValueFromParameterStruct<float>(distanceParameter,PS_JBALL_PROJ_DISTANCE); pJointLimit swingLimit = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_SWING_LIMIT)); pJointLimit twistHighLimit = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_TWIST_HIGH)); pJointLimit twistHighLow = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_TWIST_LOW)); pSpring swingSpring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_SWING_SPRING)); pSpring twistSpring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_TWIST_SPRING)); pSpring jointSpring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_JOINT_SPRING)); pJointBall *joint = static_cast<pJointBall*>(pFactory::Instance()->createBallJoint(target,bodyBEnt,anchor0,swingAxis)); if (joint) { joint->setProjectionMode((ProjectionMode)projectionMode); joint->setProjectionDistance(minDist); joint->enableCollision(collision); float maxForce = GetValueFromParameterStruct<float>(distanceParameter,PS_JBALL_MAX_FORCE); float maxTorque = GetValueFromParameterStruct<float>(distanceParameter,PS_JBALL_MAX_TORQUE); joint->setBreakForces(maxForce,maxTorque); if (swingLimit.value !=-1.0f) { joint->setSwingLimit(swingLimit); joint->enableFlag(NX_SJF_SWING_LIMIT_ENABLED,true); } joint->setSwingLimit(swingLimit); if (twistHighLimit.value != 0.0f || twistHighLow.value !=0.0f ) { joint->setTwistHighLimit(twistHighLimit); joint->setTwistLowLimit(twistHighLow); joint->enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,true); } if (swingSpring.spring !=0.0f) { joint->setSwingSpring(swingSpring); joint->enableFlag(NX_SJF_SWING_SPRING_ENABLED,true); } if (twistSpring.spring =0.0f) { joint->setTwistSpring(twistSpring); joint->enableFlag(NX_SJF_TWIST_SPRING_ENABLED,true); } if (jointSpring.spring !=0.0f) { joint->setJointSpring(jointSpring); joint->enableFlag(NX_SJF_JOINT_SPRING_ENABLED,true); } return true; } return 0; }else { pJoint *joint = body->isConnected(bodyBEnt); if ( joint) { body->getWorld()->deleteJoint(joint); } pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Spherical); if (joint2) { body->getWorld()->deleteJoint(joint); } } } return 0; } int registerJFixed(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { using namespace vtTools::ParameterTools; CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); if (distanceParameter ) { pRigidBody *body = GetPMan()->getBody(target); if (!body)return -1; CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JFIXED_BODY_B); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); if (bodyB && bodyB->getWorld() != body->getWorld() ) return -1; if (set) { if ( isPostJob && GetPMan()->GetContext()->IsPlaying() ) { pAttributePostObject postAttObject(target->GetID(),registerJFixed,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); return true; } if (bodyB && body->isConnected(bodyBEnt) ) return -1; pJointFixed *joint = static_cast<pJointFixed*>(pFactory::Instance()->createFixedJoint(target,bodyBEnt)); if (joint) { float maxForce = GetValueFromParameterStruct<float>(distanceParameter,PS_JFIXED_MAX_FORCE); float maxTorque = GetValueFromParameterStruct<float>(distanceParameter,PS_JFIXED_MAX_TORQUE); joint->setBreakForces(maxForce,maxTorque); return true; } return 0; }else { pJoint *joint = body->isConnected(bodyBEnt); if ( joint) { body->getWorld()->deleteJoint(joint); } pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Fixed); if (joint2) { body->getWorld()->deleteJoint(joint); } } } return 0; } int registerJDistance(CK3dEntity *target,int attributeType,bool set,bool isPostJob) { using namespace vtTools::ParameterTools; CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. return -1; CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); if (distanceParameter ) { pRigidBody *body = GetPMan()->getBody(target); if (!body)return -1; CK_ID bodyBId = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JDISTANCE_BODY_B); CK3dEntity *bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(bodyBId)); pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); if (bodyB && bodyB->getWorld() != body->getWorld() ) return -1; if (set) { if (isPostJob && GetPMan()->GetContext()->IsPlaying()) { pAttributePostObject postAttObject(target->GetID(),registerJDistance,attributeType); GetPMan()->getAttributePostObjects().PushBack(postAttObject); int s = GetPMan()->getAttributePostObjects().Size(); return true; } if (bodyB && body->isConnected(bodyBEnt) ) return -1; VxVector anchor0 = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_A_POS); CK_ID anchor0RefID = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_A_REF); CK3dEntity *a0Ref = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(anchor0RefID)); if (a0Ref) a0Ref->TransformVector(&anchor0,&anchor0,a0Ref); VxVector anchor1 = GetValueFromParameterStruct<VxVector>(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_B_POS); CK_ID anchor1RefID = GetValueFromParameterStruct<CK_ID>(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_B_REF); CK3dEntity *a1Ref = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(anchor1RefID)); if (a1Ref) a1Ref->TransformVector(&anchor1,&anchor1,a1Ref); float maxDist = GetValueFromParameterStruct<float>(distanceParameter,PS_JDISTANCE_MAX_DISTANCE); float minDist = GetValueFromParameterStruct<float>(distanceParameter,PS_JDISTANCE_MIN_DISTANCE); pSpring spring = pFactory::Instance()->createSpringFromParameter( GetParameterFromStruct(distanceParameter,PS_JDISTANCE_SPRING) ); int collision = GetValueFromParameterStruct<int>(distanceParameter,PS_JDISTANCE_COLL); pJointDistance *joint = static_cast<pJointDistance*>(pFactory::Instance()->createDistanceJoint(target,bodyBEnt,anchor0,anchor1,minDist,maxDist,spring)); if (joint) { float maxForce = GetValueFromParameterStruct<float>(distanceParameter,PS_JDISTANCE_MAX_FORCE); float maxTorque = GetValueFromParameterStruct<float>(distanceParameter,PS_JDISTANCE_MAX_TORQUE); joint->setBreakForces(maxForce,maxTorque); joint->enableCollision(collision); #ifdef _DEBUG XString _errorStr; XString attName = GetPMan()->GetContext()->GetAttributeManager()->GetAttributeNameByType(attributeType); _errorStr << "Distance joint created on " << target->GetName() << " for attribute type : " << attName.Str(); xLogger::xLog(XL_START,ELOGINFO,E_LI_MANAGER,_errorStr.Str()); #endif return true; } return 0; }else { pJoint *joint = body->isConnected(bodyBEnt); if ( joint) { body->getWorld()->deleteJoint(joint); } pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Distance); if (joint2) { body->getWorld()->deleteJoint(joint); } } } return 0; } void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg) { CK3dEntity *ent = static_cast<CK3dEntity*>(obj); if (!ent)return; ObjectRegisterFunction myFn = static_cast<ObjectRegisterFunction>(arg); if (ent , myFn) { bool isPlaying = GetPMan()->GetContext()->IsPlaying(); int success = (*myFn)(ent,AttribType,Set,true); if (!success) { CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); XString error; error << "Registration Function failed for attribute" << attman->GetAttributeNameByType(AttribType) << " for Object : " << ent->GetName() ; xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,error.Str()); }else{ CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); XString error; error << "Registration Function succeeded for attribute" << attman->GetAttributeNameByType(AttribType) << " for Object : " << ent->GetName() ; xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.Str()); } } } <file_sep>#include "precomp.h" #include "vtNetworkManager.h" #include "VSLManagerSDK.h" #include "xNetInterface.h" #include "xNetworkFactory.h" #include "tnlRandom.h" #include "tnlSymmetricCipher.h" #include "tnlAsymmetricKey.h" #include "vtTools.h" CKObjectDeclaration *FillBehaviorSendArrayMessageDecl(); CKERROR CreateSendArrayMessageProto(CKBehaviorPrototype **); int SendArrayMessage(const CKBehaviorContext& behcontext); CKERROR SendArrayMessageCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 0 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorSendArrayMessageDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Network Send Array Message"); od->SetDescription("Sends the contents of an array as message to a Network."); od->SetCategory("TNL/Message"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x63db76e8,0x7b6549d3)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSendArrayMessageProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateSendArrayMessageProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Send Network Message"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Message", CKPGUID_MESSAGE, "OnClick"); proto->DeclareInParameter("Dest (User ID)", CKPGUID_INT, "0"); proto->DeclareInParameter("Array", CKPGUID_DATAARRAY, "0"); proto->DeclareInParameter("Starting Row", CKPGUID_INT, "0"); proto->DeclareInParameter("Ending Row", CKPGUID_INT, "-1"); proto->DeclareInParameter("Starting Column", CKPGUID_INT, "0"); proto->DeclareInParameter("Ending Column", CKPGUID_INT, "-1"); proto->DeclareSetting("Reliable", CKPGUID_BOOL, "true"); proto->DeclareSetting("Single", CKPGUID_BOOL, "false"); proto->DeclareSetting("Exclude Master", CKPGUID_BOOL, "false"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETERINPUTS )); proto->SetFunction(SendArrayMessage); proto->SetBehaviorCallbackFct(SendArrayMessageCB); *pproto = proto; return CK_OK; } int msgCounter3 = 0; int SendArrayMessage(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); using namespace vtTools::BehaviorTools; int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); int msgType = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,1); XString msgTypeStr(mm->GetMessageTypeName(msgType)); int dstID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,2); CKDataArray *array = static_cast<CKDataArray*>(vtTools::BehaviorTools::GetInputParameterValue<CKObject*>(beh,3)); int startRow = GetInputParameterValue<int>(beh,4); int endRow = GetInputParameterValue<int>(beh,5); int startCol = GetInputParameterValue<int>(beh,6); int endCol = GetInputParameterValue<int>(beh,7); ////////////////////////////////////////////////////////////////////////// //sanity checks : if (!array) { GetNM()->m_Context->OutputToConsoleEx("You must specify an array"); return FALSE; } if (endRow ==-1) { endRow = array->GetRowCount(); } if (endCol ==-1) { endCol = array->GetColumnCount(); } if (startRow < 0) { startRow = 0; } //if (startRow > endRow ) { startRow = 0; } if (startCol <0 ) { startCol = 0; } //if (startCol > endCol ) { startCol = 0; } xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { return FALSE; } if(cin->GetConnection()) { if (!cin->isValid()) { return FALSE; } } TNL::Vector<TNL::Int<16> > dstIDs; dstIDs.push_back(dstID); CKGUID cGuid = array->GetColumnParameterGuid(0); CKParameterManager *pm = ctx()->GetParameterManager(); int cType = pm->ParameterGuidToType(cGuid); for (int j = startCol ; j < endCol ; j++) { TNL::Vector<TNL::Int<16> >outVec; for (int i = startRow ; i < endRow ; i++) { int val = 0; array->GetElementValue(i,0,&val); outVec.push_back(val); } cin->GetConnection()->c2sArrayMsgInt( cin->GetConnection()->GetUserID(),dstIDs,cType,startRow,endRow,startCol,endCol,msgTypeStr.CStr(),msgCounter3,j,outVec ); } ////////////////////////////////////////////////////////////////////////// /* //logprintf("sending broadcast message :","" ); using namespace vtTools; using namespace vtTools::Enums; int bcount = beh->GetInputParameterCount(); int srcId = cin->GetConnection()->GetUserID(); for (int i = BEH_IN_INDEX_MIN_COUNT ; i < beh->GetInputParameterCount() ; i++ ) { CKParameterIn *ciIn = beh->GetInputParameter(i); CKParameterType pType = ciIn->GetType(); SuperType sType = ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); const char *pname = pam->ParameterTypeToName(pType); }*/ return CKBR_OK; } CKERROR SendArrayMessageCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <xDebugTools.h> #include "pDifferential.h" #include "pVehicleAll.h" #include "pWorldCallbacks.h" #define FRICTION_COEFF 100.0f #define MASS 12 #define TIRE_RATE 50000.0f #define WHEEL_PENETRATION_DEPTH -0.0258f #define WHEEL_SUSPENSION_FORCE VxVector(0,-1025.0f,0) #define RR_EPSILON_VELOCITY 0.001 // Wheel velocity #define OPT_SLIPVECTOR_USES_TANSA // Use full 3D patch for surface detection? #define USE_3D_PATCH #define ENV_INI "env.ini" // For method #3, slipVector (Gregor Veble), use tan(SA) or SA? #define OPT_SLIPVECTOR_USES_TANSA // Skid methods //#define SKID_METHOD_SEPARATE_LON_LAT //#define SKID_METHOD_SLIP_RA_VECTOR #define SKID_METHOD_Z_GREGOR // Point at which skidmarks appear #define SKIDMARK_SLIPRATIO 0.2 // Apply damping to slipRatio/slipAngle differential eq's at low speed? //#define DO_DAMPING_LAT //#define DO_DAMPING_LONG // Apply low-speed enhancements? (obsolete since 18-5-01) #define DO_LOW_SPEED // Distance (in m) to start with wheel ray-track intersection; this is // the height at which the ray is started to avoid getting a ray // that starts BENEATH the track surface and therefore not hitting it. #define DIST_INTERSECT 1.0 // Define the next symbol to check for wheel velocity reversal (vertically), // and if so, the wheel is stopped momentarily. Is used to rule out // incredibly high damper forces from pushing the wheel to full up or down. // Should perhaps not be needed anymore combined with the implicit integrator. // Note that this acts at the outermost positions of the wheel. #define DAMP_VERTICAL_VELOCITY_REVERSAL // Damp the wheel when crossing the equilibrium position? // As the wheel passes its center position, the spring force reverses. To // avoid adding energy into the system, when passing this position, damping // is used to avoid overaccelerating the tire to the other side. // Note that this acts when the wheel is near its center (rest) position, // contrast this with DAMP_VERTICAL_VELOCITY_REVERSAL. //#define DAMP_VERTICAL_EQUILIBRIUM_REVERSAL // Use implicit integration? This should be more stable with // high damper rates. #define INTEGRATE_IMPLICIT_VERTICAL // Gregor Veble combined slip algorithm? (instead of Pacejka) //#define DO_GREGOR #ifdef DO_GREGOR #undef DO_DAMPING_LAT #undef DO_DAMPING_LONG #endif // Delayed slip angle? //#define USE_SAE950311_LAT // If not using SAE950311, damp SA at low speed? (to avoid jittering) //#define USE_SA_DAMPING_AT_LOW_SPEED // Wheel locking results in force going the direction of -slipVector? //#define USE_WHEEL_LOCK_ADJUST void pWheel2::CalcDamping() { // Calculate damping of the tire at low speed, to avoid // oscillations. float u,v,b,B; if ( getVehicle()->getProcessOptions() & pVPO_Lat_Damping || getVehicle()->getProcessOptions() & pVPO_Long_Damping ) { if(!hadContact) return; u=velWheelTC.z; v=velWheelTC.x; if (getVehicle()->getProcessOptions() & pVPO_Lat_Damping) b=relaxationLengthLat; if (getVehicle()->getProcessOptions() & pVPO_Long_Damping) B=relaxationLengthLong; } if ( getVehicle()->getProcessOptions() & pVPO_Lat_Damping ) { // Calculate damping force, to be added later // Assumes CalcLoad() has already been called (for 'load' to be valid) //qdbg("u=%f, v=%f\n",u,v); //if(velWheelTC.LengthSquared()<dampingSpeed*dampingSpeed&&load>0) if(fabs(v)<dampingSpeed) //if(velWheelTC.Length()<dampingSpeed) //if(car->GetBody()->GetLinVel()->Length()<dampingSpeed) //if(car->GetBody()->GetRotVel()->y<dampingSpeed&&load>0) //if(load>0) //if(IsLowSpeed()==TRUE&&load>0) { NxVec3 grav;getBody()->getActor()->getScene().getGravity(grav); forceDampingTC.x=2.0f*dampingCoefficientLat*v* sqrt((load*(pacejka.GetCorneringStiffness()) /-grav.y*b)); forceDampingTC.x*=rollingCoeff; #ifdef OBS dampingFactorLat=(fabs(car->GetBody()->GetRotVel()->y))*1.0f; #endif //if(dampingFactorLat<0.1f)dampingFactorLat=0.1f; //(dampingSpeed-fabs(car->GetBody()->GetRotVel()->y))*1.0f; #ifdef OBS // Factor damping dampingCoefficient=1.0f; dampingFactorLat=dampingCoefficient*(dampingSpeed-fabs(v)); if(dampingFactorLat>1)dampingFactorLat=1; //slipAngle*=dampingFactorLat; dampingFactorLat=0; #endif //dampingFactorLat=fabs(v)*3; } NxVec3 grav;getBody()->getActor()->getScene().getGravity(grav); // Natural frequency (debug) float natFreq; natFreq=sqrtf(-grav.y*pacejka.GetCorneringStiffness()/load*b); // #ifdef OBS qdbg("W%d; natFreq=%f ~ %f Hz\n",wheelIndex,natFreq,natFreq/6.28f); car->GetBody()->GetLinVel()->DbgPrint("body linVel");#endif forceRoadTC.x=pacejka.GetFy(); //qdbg("Flat=%.2f, dampFlat=%.2f, cornStiffness=%.f, load %.f, v=%f\n", // forceRoadTC.x,forceDampingTC.x,pacejka.GetCorneringStiffness(),load,v); } if (getVehicle()->getProcessOptions() & pVPO_Long_Damping) { // Calculate damping force, to be added later // Assumes CalcLoad() has already been called (for 'load' to be valid) if(fabs(u)<dampingSpeed) //if(velWheelTC.Length()<dampingSpeed) //if(velWheelTC->LengthSquared()<dampingSpeed*dampingSpeed&&load>0) { //---------------------------------------------------------------- // // get wheel load // NxVec3 grav;getBody()->getActor()->getScene().getGravity(grav); forceDampingTC.z=2.0f*dampingCoefficientLong*u*sqrt((load*pacejka.GetLongitudinalStiffness())/(-grav.y*B)); forceDampingTC.z*=rollingCoeff; #ifdef OBS qdbg("Fz=%f, dampFlon=%f, longStiffness=%.f, load %.f, u=%f, v=%f,\n", pacejka.GetFx(),forceDampingTC.z,pacejka.GetLongitudinalStiffness(),load,u,v); #endif } //qdbg("dampFactorLong=%f\n",dampingFactorLong); } } float pWheel2::getMass() { return mass; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPJPrismaticDecl(); CKERROR CreatePJPrismaticProto(CKBehaviorPrototype **pproto); int PJPrismatic(const CKBehaviorContext& behcontext); CKERROR PJPrismaticCB(const CKBehaviorContext& behcontext); enum bbInputs { bI_ObjectB, bI_Anchor, bI_AnchorRef, bI_Axis, bI_AxisRef, bI_Coll }; //************************************ // Method: FillBehaviorPJPrismaticDecl // FullName: FillBehaviorPJPrismaticDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPJPrismaticDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJPrismatic"); od->SetCategory("Physic/Joints"); od->SetDescription("Sets/modifies a prismatic joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x2c270788,0x2d886425)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJPrismaticProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJPrismaticProto // FullName: CreatePJPrismaticProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePJPrismaticProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJPrismatic"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In0"); proto->DeclareOutput("Out0"); proto->SetBehaviorCallbackFct( PJPrismaticCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Anchor",CKPGUID_VECTOR); proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Axis",CKPGUID_VECTOR); proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Collision",CKPGUID_BOOL); /* proto->DeclareInParameter("Spring",VTS_JOINT_SPRING); proto->DeclareInParameter("High Limit",VTS_JLIMIT); proto->DeclareInParameter("Low Limit",VTS_JLIMIT); proto->DeclareInParameter("Motor",VTS_JOINT_MOTOR); */ /* proto->DeclareSetting("Spring",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Limit",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Motor",CKPGUID_BOOL,"FALSE"); */ proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PJPrismatic); *pproto = proto; return CK_OK; } //************************************ // Method: PJPrismatic // FullName: PJPrismatic // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJPrismatic(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Prismatic)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA && ! worldB ) { return 0; } if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); //anchor : VxVector anchor = GetInputParameterValue<VxVector>(beh,bI_Anchor); VxVector anchorOut = anchor; CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); if (anchorReference) { anchorReference->Transform(&anchorOut,&anchor); } //swing axis VxVector Axis = GetInputParameterValue<VxVector>(beh,bI_Axis); VxVector axisOut = Axis; CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); if (axisReference) { VxVector dir,up,right; axisReference->GetOrientation(&dir,&up,&right); axisReference->TransformVector(&axisOut,&up); } ////////////////////////////////////////////////////////////////////////// int col = GetInputParameterValue<int>(beh,bI_Coll); ////////////////////////////////////////////////////////////////////////// // pJointPrismatic *joint = static_cast<pJointPrismatic*>(worldA->getJoint(target,targetB,JT_Prismatic)); if(bodyA || bodyB) { ////////////////////////////////////////////////////////////////////////// //joint create ? if (!joint) { joint = static_cast<pJointPrismatic*>(pFactory::Instance()->createPrismaticJoint(target,targetB,anchorOut,axisOut)); } ////////////////////////////////////////////////////////////////////////// Modification : if (joint) { joint->setGlobalAxis(axisOut); joint->setGlobalAnchor(anchorOut); joint->enableCollision(col); } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: PJPrismaticCB // FullName: PJPrismaticCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJPrismaticCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { /* DWORD twistLimit; beh->GetLocalParameterValue(1,&twistLimit); beh->EnableInputParameter(bbI_HighLimit,twistLimit); beh->EnableInputParameter(bbI_LowLimit,twistLimit); DWORD springSwing; beh->GetLocalParameterValue(0,&springSwing); beh->EnableInputParameter(bbI_Spring,springSwing); DWORD motor; beh->GetLocalParameterValue(2,&motor); beh->EnableInputParameter(bbI_Motor,motor); */ break; } } return CKBR_OK; }<file_sep>#ifndef SOFT_MESH_EZM_H #define SOFT_MESH_EZM_H namespace SOFTBODY { class SoftMeshInterface; bool loadSoftMeshEZM(const char *oname,SoftMeshInterface *smi); }; // END OF SOFTBODY NAMESPACE #endif <file_sep>#if !defined(CUSTOMPLAYERSTATICDLLSEXTA_H) #define CUSTOMPLAYERSTATICDLLSEXTRA_H #if defined(CUSTOM_PLAYER_STATIC) #ifdef WIN32 #define CDECL_CALL __cdecl #else #define CDECL_CALL #endif /***************************************************/ /**** BEHAVIORS ***********************************/ CKPluginInfo* CDECL_CALL CKGet_TOOLS_PluginInfo(int index); void CDECL_CALL Register_TOOLS_BehaviorDeclarations(XObjectDeclarationArray *reg); CKPluginInfo* CDECL_CALL CKGet_WIDGETS_PluginInfo(int index); void CDECL_CALL Register_WIDGETS_BehaviorDeclarations(XObjectDeclarationArray *reg); CKPluginInfo* CDECL_CALL CKGet_VTPHYSX_PluginInfo(int index); void CDECL_CALL Register_VTPHYSX_BehaviorDeclarations(XObjectDeclarationArray *reg); //--------------------- Implementation -------------------------------------// //--------------------- of -------------------------------------// //--------------------- registration functions -----------------------------// /**************************************************************************** BEHAVIORS *******************************************************************************/ inline void RegisterToolsBehaviors(CKPluginManager& iPluginManager) { //--- 3D Tranfo iPluginManager.RegisterPluginInfo(0,CKGet_TOOLS_PluginInfo(0),Register_TOOLS_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_TOOLS_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("Tools",2); } inline void RegisterWidgetsBehaviors(CKPluginManager& iPluginManager) { //--- 3D Tranfo iPluginManager.RegisterPluginInfo(0,CKGet_WIDGETS_PluginInfo(0),Register_WIDGETS_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_WIDGETS_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("Widgets",1); } inline void RegisterPhysXBehaviors(CKPluginManager& iPluginManager) { //--- 3D Tranfo iPluginManager.RegisterPluginInfo(0,CKGet_VTPHYSX_PluginInfo(0),Register_VTPHYSX_BehaviorDeclarations,NULL); iPluginManager.RegisterPluginInfo(1,CKGet_VTPHYSX_PluginInfo(1),NULL,NULL); iPluginManager.RegisterNewStaticLibAsDll("vtPhysX",2); } inline void CustomPlayerRegisterBehaviorsExtra(CKPluginManager& iPluginManager) { #ifdef vtToolkit RegisterToolsBehaviors(iPluginManager); #endif #ifdef vtWidgets RegisterWidgetsBehaviors(iPluginManager); #endif #ifdef vtPhysX RegisterPhysXBehaviors(iPluginManager); #endif } #endif // CUSTOM_PLAYER_STATIC #endif // CUSTOMPLAYERSTATICDLLS_H<file_sep>#ifndef __PBODY_TAB_CONTRL_H__ #define __PBODY_TAB_CONTRL_H__ #include "VIControls.h" ///////////////////////////////////////////////////////////////////////////// // PBodyTabContrl window class PBodyTabContrl : public VITabCtrl { DECLARE_DYNCREATE(PBodyTabContrl) public: PBodyTabContrl(); public: enum { IDD = IDC_PBODY_TAB_PANE }; PBodyTabContrl(CWnd*win); virtual ~PBodyTabContrl(); CDialog *m_tabPages[1]; int m_tabCurrent; int m_nNumberOfPages; void _construct(); // Attributes public: // Operations public: void Init(); void SetRectangle(); protected: DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif <file_sep>/* * Tcp4u v 3.31 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: port.h * Purpose: Portability header file. Allow an uniq code * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ /* * Fichier d'equivalence Windows/Unix * ---------------------------------- * * Cette serie de declarations definit si necessaire * SOCKET -> un descripteur de socket * HTASK -> un descripteur de process * BOOL -> le type VRAI/FAUX * HFILE -> un descripteur de fichier * API4U -> le type des APIs * UINT -> unsigned int * DWORD -> entier 4 octets * far -> signification uniquement pour Windows 16 * TRUE * FALSE * NULL * CALLBACK * FARPROC * les fonctions : * GetCurrentTask -> rend un identifiant de tache * WSAIsBlocking() -> rend VRAI si une fonction bloquante en cours * WSACancelBlockingCall() * WSAGetLastError() * WSACleanup() * WSAIsBadWritePtr() * IsCancelled() -> L'ordre a-t-il ete interrompu * CloseSocket() * IoctlSocket() -> operation "de bas niveau" * Write -> ecriture dans un fichier HFILE * Close -> close et _hclose un fichier HFILE * Open -> open et _hopen un fichier HFILE * Strlen -> fonction standard C, lstrlen en Windows * Strcpy -> fonction standard C, lstrcpy en Windows * Strcat -> fonction standard C, lstrcat en Windows * Strcpyn -> lstrcpyn en Windows * Strcmpn -> lstrcmpn en Windows * Sprintf -> fonction standard C, wsprintf en Windows * Calloc -> Allocation de N*P octets * Free -> liberation des octets * OutputDebugString -> fprintf (stderr, ...) * et le fichier * TCP4U_INCLUDE -> include tcp4ux.h / tcp4w.h * * * Note: Sous Windows certaines definitions sont inutiles pour tcp4w, mais ce * fichier est aussi utilise par d'autres projets... * */ /* ****************************************************************** */ /* Common Declarations */ /* ****************************************************************** */ /* ****************************************************************** */ /* Declarations Windows */ /* ****************************************************************** */ /* #include LIBCO_VERS_H */ #ifdef _WINDOWS #define NEED_PROTO #define WRITE_CR 0 #define Write(fd,buf,len) _lwrite(fd,buf,len) #define Open(fic,mode) _lcreat(fic,mode) #define Close(fd) _lclose(fd) #define Sprintf wsprintf #define Strlen lstrlen #define Strcpy lstrcpy #define Strcat lstrcat #define Strcpy lstrcpy #define Strcpyn lstrcpyn #define IsCancelled() (WSAGetLastError()==WSAEINTR) #define Calloc(n,s) (void far *)GlobalAllocPtr(GMEM_SHARE | GMEM_ZEROINIT,n*s) #define Free(p) GlobalFreePtr (p) #define IoctlSocket ioctlsocket #define CloseSocket(s) closesocket(s) #define Strstr(s1,s2) strstr(s1,s2) #define Vsprintf wvsprintf #define SYSTEM_EOL "\r\n" /* ----------------------------------- */ /* 16 bits declarations */ /* ----------------------------------- */ #ifndef _WIN32 # define Unlink(fic) _unlink(fic) # define MAKEWORD(a, b) ((WORD)(((BYTE)(a)) | ((WORD)((BYTE)(b))) << 8)) #endif /* Windows 3.1 */ /* ----------------------------------- */ /* 32 bits redeclarations */ /* ----------------------------------- */ #ifdef _WIN32 # define Unlink(fic) DeleteFile(fic) # define _export # define GetCurrentTask() GetCurrentThread() # define WRITE OF_WRITE # define READ OF_READ # define IsTask(x) ( GetThreadPriority(x)!= THREAD_PRIORITY_ERROR_RETURN \ || GetLastError() != ERROR_INVALID_HANDLE) #endif /* Windows95 / Windows NT */ /* ----------------------------------- */ /* functions defined for compatibility */ /* ----------------------------------- */ HINSTANCE GetTaskInstance (HWND hParentWindow); #endif /* _WINDOWS */ /* ****************************************************************** */ /* Declarations Unix */ /* ****************************************************************** */ #ifdef UNIX #define GetCurrentTask() (int) getpid () #define WSACleanup() #define WSAGetLastError() errno #define IsBadWritePtr(a,b) FALSE #define WSAIsBlocking() FALSE #define WSACancelBlockingCall() #define IsCancelled() (errno==EINTR) #define Write(fd,buf,len) write(fd,buf,len) #define Open(fic,mode) open(fic,mode,0666) /* rw-rw-rw - umask */ #define Close(fd) close(fd) #define Sprintf sprintf #define Strlen strlen #define Strcpy strcpy #define Strcat strcat #define Strcpyn(a,b,n) strncpy(a,b,n-1), a[n-1]=0 #ifdef __cplusplus # define Calloc(n,s) (char *) calloc(n,s) #else /* c++ */ # define Calloc(n,s) calloc(n,s) #endif /* not c++ */ #define Free(p) free (p) #define IoctlSocket ioctl #define CloseSocket(s) close (s) #define Unlink(fic) unlink(fic) #define Strstr(s1,s2) strstr(s1,s2) #define Vsprintf vsprintf #define OutputDebugString(x) fputs (x, stderr) #ifndef FALSE # define FALSE (0==1) #endif /* FALSE */ #ifndef TRUE # define TRUE (1==1) #endif /* TRUE */ #ifndef NULL # define NULL ((void *) 0) #endif #define CALLBACK #define FARPROC HTTP4U_CALLBACK #ifndef min # define min(a,b) ((a)<(b)?(a):(b)) #endif #define WRITE_CR (O_WRONLY | O_CREAT | O_TRUNC) #define UINT unsigned int #define far #define SYSTEM_EOL "\r\n" #ifndef TYPE_SOCKET_DEF typedef unsigned int SOCKET; #define TYPE_SOCKET_DEF + #endif /* TYPE_SOCKET_DEF */ #ifndef TYPE_HTASK_DEF typedef unsigned int HTASK; #define TYPE_HTASK_DEF + #endif /* TYPE_HTASK_DEF */ #ifndef TYPE_BOOL_DEF typedef int BOOL; #define TYPE_BOOL_DEF + #endif /* TYPE_BOOL_DEF */ #ifndef TYPE_HFILE_DEF typedef int HFILE; #define TYPE_HFILE_DEF + #endif /* TYPE_HFILE_DEF */ #endif /* UNIX */ <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" pJointBall::pJointBall(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Spherical) { } pJointLimit pJointBall::getSwingLimit() { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return pJointLimit(); joint->saveToDesc(descr); return pJointLimit (descr.swingLimit.hardness,descr.swingLimit.restitution,descr.swingLimit.value); } pJointLimit pJointBall::getTwistHighLimit() { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return pJointLimit(); joint->saveToDesc(descr); return pJointLimit (descr.twistLimit.high.hardness,descr.twistLimit.high.restitution,descr.twistLimit.high.value); } pJointLimit pJointBall::getTwistLowLimit() { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return pJointLimit(); joint->saveToDesc(descr); return pJointLimit (descr.twistLimit.low.hardness,descr.twistLimit.low.restitution,descr.twistLimit.low.value); } pSpring pJointBall::getSwingSpring() { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return pSpring(); joint->saveToDesc(descr); return pSpring (descr.swingSpring.damper,descr.swingSpring.spring,descr.swingSpring.targetValue); } pSpring pJointBall::getTwistSpring() { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return pSpring(); joint->saveToDesc(descr); return pSpring (descr.twistSpring.damper,descr.twistSpring.spring,descr.twistSpring.targetValue); } pSpring pJointBall::getJointSpring() { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return pSpring(); joint->saveToDesc(descr); return pSpring (descr.jointSpring.damper,descr.jointSpring.spring,descr.jointSpring.targetValue); } void pJointBall::enableFlag(int flag,bool enable) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return; joint->saveToDesc(descr); if (enable) descr.flags |=flag; else descr.flags &=~flag; joint->loadFromDesc(descr); return ; } void pJointBall::setSwingLimitAxis( const VxVector& swingLimitAxis ) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.swingAxis = pMath::getFrom(swingLimitAxis); joint->loadFromDesc(descr); } void pJointBall::enableCollision( bool collision ) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (collision) { descr.jointFlags |= NX_JF_COLLISION_ENABLED; }else descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; joint->loadFromDesc(descr); } void pJointBall::setProjectionMode(ProjectionMode mode) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.projectionMode = (NxJointProjectionMode)mode; joint->loadFromDesc(descr); } void pJointBall::setProjectionDistance(float distance) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.projectionDistance= distance; joint->loadFromDesc(descr); } bool pJointBall::setSwingLimit( pJointLimit limit ) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return false ; joint->saveToDesc(descr); if ( limit.hardness != 0.0f || limit.restitution != 0.0f || limit.value !=0.0f ) { enableFlag(NX_SJF_SWING_LIMIT_ENABLED,1); NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; if (!sLimit.isValid())return false; descr.swingLimit= sLimit; joint->loadFromDesc(descr); return true; }else { enableFlag(NX_SJF_SWING_LIMIT_ENABLED,0); } return false; } bool pJointBall::setTwistHighLimit( pJointLimit limit ) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return false ; joint->saveToDesc(descr); if ( limit.hardness != 0.0f || limit.restitution != 0.0f || limit.value !=0.0f ) { enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,1); NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; if (!sLimit.isValid())return false; descr.twistLimit.high= sLimit; joint->loadFromDesc(descr); return true; } else { enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,0); } return 1; } bool pJointBall::setTwistLowLimit( pJointLimit limit ) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return false ; joint->saveToDesc(descr); if ( limit.hardness != 0.0f || limit.restitution != 0.0f || limit.value !=0.0f ) { enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,1); NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; if (!sLimit.isValid())return false; descr.twistLimit.low= sLimit; joint->loadFromDesc(descr); return true; } else { enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,0); } return 1; } void pJointBall::setAnchor( const VxVector& anchor ) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); joint->setGlobalAnchor(pMath::getFrom(anchor)); } bool pJointBall::setSwingSpring( pSpring spring ) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return false; joint->saveToDesc(descr); NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; if (!sLimit.isValid())return false; descr.swingSpring= sLimit; joint->loadFromDesc(descr); return 1; } bool pJointBall::setTwistSpring( pSpring spring ) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return false ; joint->saveToDesc(descr); NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; if (!sLimit.isValid())return false; descr.twistSpring= sLimit; joint->loadFromDesc(descr); return 1; } bool pJointBall::setJointSpring( pSpring spring ) { NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast<NxSphericalJoint*>(getJoint()); if (!joint)return false ; joint->saveToDesc(descr); NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; if (!sLimit.isValid())return false; descr.jointSpring= sLimit; joint->loadFromDesc(descr); return 1; } <file_sep>DEV35DIR="VTDEV35DIR-NOTFOUND" DEV40DIR="VTDEV40DIR-NOTFOUND" DEV41DIR="VTDEV41DIR-NOTFOUND" WEBPLAYERDIR="J:/Programme/Virtools/3D Life Player" <file_sep>#pragma once // PBRootForm form view class PBRootForm : public CFormView { DECLARE_DYNCREATE(PBRootForm) protected: PBRootForm(); // protected constructor used by dynamic creation virtual ~PBRootForm(); public: enum { IDD = PBRootMDI }; #ifdef _DEBUG virtual void AssertValid() const; #ifndef _WIN32_WCE virtual void Dump(CDumpContext& dc) const; #endif #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() }; <file_sep>/* * Tcp4u v 3.31 Last Revision 08/12/1997 3.31-01 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: tcp4_log.c * Purpose: Some logging / debugging * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" #include <stdarg.h> /* using a static integer is a bad choice for a DLL, since each app */ /* shares the same variable. However is will be boring to keep a */ /* context for each app. */ static unsigned uMaskTrace = 0; /* ------------------------------------------------------------------ */ /* fonctions de log */ /* ------------------------------------------------------------------ */ void API4U Tcp4uEnableLog (unsigned uMask) { uMaskTrace = uMask; } /* Tcp4uEnableLog */ void Tcp4uLog (unsigned uLevel, LPCSTR fmt, ...) { va_list marker; char szBuf[512]; if ( (uMaskTrace & uLevel) == 0) return; Sprintf (szBuf, "Proc %d\t", GetCurrentTask ()); switch (uLevel) { case LOG4U_ERROR : Sprintf (szBuf + Strlen (szBuf), "Error %d during ", WSAGetLastError()); break; case LOG4U_HIPROC : case LOG4U_PROC : Sprintf (szBuf + Strlen (szBuf), "entering "); break; case LOG4U_DBCALL : case LOG4U_CALL : Sprintf (szBuf + Strlen (szBuf), "calling "); break; case LOG4U_INTERN : Sprintf (szBuf + Strlen (szBuf), "internal "); break; case LOG4U_HIEXIT : case LOG4U_EXIT : Sprintf (szBuf + Strlen (szBuf), "exiting "); break; } va_start (marker, fmt); Vsprintf (szBuf + Strlen (szBuf), fmt, marker); va_end (marker); Strcat (szBuf, SYSTEM_EOL); OutputDebugString (szBuf); } /* Tcp4uLog */ /* -------------------------------------------------------------- */ /* dump a binary or text frame. The output is the debug window */ /* for Windows system and stderr for unix */ /* The code is a port of the xdump function from the cmu snmp lib */ /* Ajout du cast (unsigned char) */ /* -------------------------------------------------------------- */ void API4U Tcp4uDump (LPCSTR cp, int nLen, LPCSTR szPrefix) { int col, count, nPos; char szLine [128]; static const char tCvtHex[] = "0123456789ABCDEF"; /* dump enabled ? */ if ( (uMaskTrace & LOG4U_DUMP) == 0) return; if (nLen==0) /* Empty message -> has to be dumped */ { if (szPrefix!=NULL) Strcpyn (szLine, szPrefix, 20); else szLine[0]=0; Strcat (szLine, " Empty Message"); Strcat (szLine, SYSTEM_EOL); OutputDebugString (szLine); return; } count = 0; while (count < nLen) { if (szPrefix!=NULL) Strcpyn (szLine, szPrefix, 20); else szLine[0]=0; nPos = Strlen (szLine); szLine[nPos++] = ' '; for (col = 0 ; count + col < nLen && col < 16 ; col++) { if (col == 8) szLine[nPos++] = '-', szLine[nPos++] = ' ' ; szLine [nPos++] = tCvtHex [(unsigned char ) cp[count + col] >> 4]; szLine [nPos++] = tCvtHex [(unsigned char ) cp[count + col] & 0x0F]; szLine [nPos++] = ' '; } while(col++ < 16) /* pad end of buffer with zeros */ { if (col == 8) szLine[nPos++] = ' ', szLine[nPos++] = ' '; szLine[nPos++] = ' '; szLine[nPos++] = ' '; szLine[nPos++] = ' '; } szLine[nPos++] = ' '; szLine[nPos++] = ' '; for (col = 0; count + col < nLen && col < 16 ; col++) { szLine[nPos++] = isprint(cp[count + col]) ? cp[count + col] : '.'; } Strcpy (& szLine[nPos], SYSTEM_EOL); OutputDebugString (szLine); count += col; } /* while buffer nor printed */ } /* Tcp4uDump */ <file_sep>#ifndef __xDistributedPoint2F_H #define __xDistributedPoint2F_H #include "xPoint.h" #include "xDistributedProperty.h" #include "xTNLInternAll.h" #include <xNetworkTypes.h> class xDistributedPoint2F : public xDistributedProperty { public: typedef xDistributedProperty Parent; xDistributedPoint2F ( xDistributedPropertyInfo *propInfo, xTimeType maxWriteInterval, xTimeType maxHistoryTime ) : xDistributedProperty(propInfo) { mLastValue = Point2F(0.0f,0.0f); mCurrentValue= Point2F(0.0f,0.0f); mDifference = Point2F(0.0f,0.0f); mLastTime = 0; mCurrentTime = 0; mLastDeltaTime = 0 ; mFlags = 0; mThresoldTicker = 0; } ~xDistributedPoint2F(){} Point2F mLastValue; Point2F mCurrentValue; Point2F mDifference; Point2F mLastServerValue; Point2F mLastServerDifference; bool updateValue(Point2F value,xTimeType currentTime); Point2F getDiff(Point2F value); void pack(TNL::BitStream *bstream); void unpack(TNL::BitStream *bstream,float sendersOneWayTime); void updateGhostValue(TNL::BitStream *stream); void updateFromServer(TNL::BitStream *stream); virtual uxString print(TNL::BitSet32 flags); }; #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pErrorStream.h" namespace vtAgeia { void pErrorStream::reportError(NxErrorCode e, const char* message, const char* file, int line) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,message); } NxAssertResponse pErrorStream::reportAssertViolation(const char* message, const char* file, int line) { return NX_AR_CONTINUE; } void pErrorStream::print(const char* message) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,message); } } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBRemoveShapeDecl(); CKERROR CreatePBRemoveShapeProto(CKBehaviorPrototype **pproto); int PBRemoveShape(const CKBehaviorContext& behcontext); CKERROR PBRemoveShapeCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPBRemoveShapeDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBRemoveShape"); od->SetCategory("Physic/Body"); od->SetDescription("Removes a sub shape given by a mesh."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x25637ead,0x3a881190)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBRemoveShapeProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBRemoveShapeProto // FullName: CreatePBRemoveShapeProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ enum bInputs { bbI_Mesh=0, bbI_Density, bbI_TotalMass, }; CKERROR CreatePBRemoveShapeProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBRemoveShape"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PBRemoveShape PBRemoveShape is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Removes a sub shape. See also pRigidBody::addSubShape() .<br> <h3>Technical Information</h3> \image html PBRemoveShape.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target:</SPAN>The 3D Entity associated to the rigid body.<BR> <SPAN CLASS="pin">Mesh Reference:</SPAN>The mesh reference. Must be a Entity3D or a Mesh.<BR> <br> <SPAN CLASS="pin">New Density: </SPAN>Density scale factor of the shapes belonging to the body.If you supply a non-zero total mass, the bodies mass and inertia will first be computed as above and then scaled to fit this total mass. See #pRigidBody::updateMassFromShapes(). <br> <br> <SPAN CLASS="pin">Total Mass: </SPAN>Total mass if it has sub shapes.If you supply a non-zero density, the bodies mass and inertia will first be computed as above and then scaled by this factor.See #pRigidBody::updateMassFromShapes(). <br> <BR> <h3>Note</h3> The mesh reference can NOT be the initial shape of the target body. */ proto->DeclareInParameter("Reference",CKPGUID_BEOBJECT); proto->DeclareInParameter("Density",CKPGUID_FLOAT); proto->DeclareInParameter("Total Mass",CKPGUID_FLOAT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBRemoveShape); *pproto = proto; return CK_OK; } //************************************ // Method: PBRemoveShape // FullName: PBRemoveShape // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBRemoveShape(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) { beh->ActivateOutput(0); return 0; } pRigidBody*result = world->getBody(target); if(!result) { beh->ActivateOutput(0); return 0; } CKMesh *mesh = (CKMesh*)GetInputParameterValue<CKObject*>(beh,bbI_Mesh); float density = GetInputParameterValue<float>(beh,bbI_Density); float totalMass = GetInputParameterValue<float>(beh,bbI_TotalMass); result->removeSubShape(mesh,density,totalMass); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PBRemoveShapeCB // FullName: PBRemoveShapeCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBRemoveShapeCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#if !defined(EA_45F10106_0809_49c3_8B43_1556D139853F__INCLUDED_) #define EA_45F10106_0809_49c3_8B43_1556D139853F__INCLUDED_ namespace vtAgeia { class pWorldSettings { public: pWorldSettings(); VxVector getGravity() const{ return m_Gravity; } void setGravity(VxVector val){ m_Gravity = val; } float getSkinWith() const{ return m_SkinWith; } void setSkinWith(float val) { m_SkinWith = val; } bool isFixedTime() const { return fixedTime; } void setFixedTime(bool val) { fixedTime = val; } int getNumIterations() const { return numIterations; } void setNumIterations(int val) { numIterations = val; } float getFixedTimeStep() const { return fixedTimeStep; } void setFixedTimeStep(float val) { fixedTimeStep = val; } int getSceneFlags() const { return sceneFlags; } void setSceneFlags(int val) { sceneFlags = val; } int getPhysicFlags() const { return physicFlags; } void setPhysicFlags(int val) { physicFlags = val; } protected: float m_SkinWith; VxVector m_Gravity; float fixedTimeStep; int numIterations; bool fixedTime; int sceneFlags; int physicFlags; }; } #endif // !defined(EA_45F10106_0809_49c3_8B43_1556D139853F__INCLUDED_) <file_sep>#ifndef InitMAN_H #define InitMAN_H #include "CKBaseManager.h" #include "xNetConstants.h" #include <virtools/vtcxglobal.h> #include "vtGuids.h" #define NET_MAN_GUID CKGUID(0x21aa716b,0x57e37304) class xNetInterface; class vtConnection; class xDistributedObject; class xDistributedProperty; class vtNetworkManager : public CKBaseManager { public: //Ctor vtNetworkManager(CKContext* ctx); //Dtor ~vtNetworkManager(); int Init(); void initLogger(); xNetInterface* GetServerNetInterface(); void SetServerNetInterface(xNetInterface *cinterface); xNetInterface *GetClientNetInterface(); void SetClientNetInterface(xNetInterface *cinterface); XString m_LastLogEntry; XString GetLastLogEntry() const { return m_LastLogEntry; } void SetLastLogEntry(XString val) { m_LastLogEntry = val; } int CreateServer(bool deleteExisting,int port,const char *address); void DeleteServer(int flags); int CreateClient(bool deleteExisting,int port,const char *address); vtConnection *localConnection; int CreateLocalConnection(); int ConnectToServer(bool deleteExisting,const char *address); void UpdateDistributedObjects(DWORD flags); static vtNetworkManager* Instance(); static vtNetworkManager * Cast(CKBaseManager* iM) { return Instance();} // Initialization virtual CKERROR OnCKInit(); virtual CKERROR OnCKEnd(); virtual CKERROR OnCKReset(); virtual CKERROR PreProcess(); virtual CKERROR PostProcess(); virtual CKERROR PostClearAll(); virtual CKERROR OnCKPlay(); virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_OnCKInit| CKMANAGER_FUNC_PostProcess| CKMANAGER_FUNC_OnCKEnd| CKMANAGER_FUNC_OnCKReset| CKMANAGER_FUNC_PreProcess| CKMANAGER_FUNC_PostClearAll| CKMANAGER_FUNC_OnCKPlay; } /************************************************************************/ /* Parameter Functions */ /************************************************************************/ void Test(const char*); void RegisterVSL(); bool pLoaded; float m_CurrentDeltaTime; float getCurrentDeltaTime() const { return m_CurrentDeltaTime; } void setCurrentDeltaTime(float val) { m_CurrentDeltaTime = val; } float mCurrentThresholdTicker; float& getCurrentThresholdTicker(){ return mCurrentThresholdTicker; } void setCurrentThresholdTicker(float val) { mCurrentThresholdTicker = val; } void performGhostUpdates(); void updateLocalPosition(xDistributedObject* distObject,CK3dEntity *target,xDistributedProperty*prop); void updateLocalRotation(xDistributedObject* distObject,CK3dEntity *target,xDistributedProperty*prop); float m_MinTickTime; float getMinTickTime() const { return m_MinTickTime; } void setMinTickTime(float val) { m_MinTickTime = val; } void RegisterParameters(); protected: }; #define GetNM() vtNetworkManager::Instance() #define ctx() vtNetworkManager::Instance()->m_Context #endif <file_sep>/*! * <File comment goes here!!> * * Copyright (c) 2005 by <your name/ organization here> */ #include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPClothAttachToCoreDecl(); CKERROR CreatePClothAttachToCoreProto(CKBehaviorPrototype **pproto); int PClothAttachToCore(const CKBehaviorContext& behcontext); CKERROR PClothAttachToCoreCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_BodyReference, bbI_ImpulseThreshold, bbI_PenetrationDepth, bbI_MaxDeform, }; //************************************ // Method: FillBehaviorPClothAttachToCoreDecl // FullName: FillBehaviorPClothAttachToCoreDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ /*! * \brief * Write brief comment for FillBehaviorPClothAttachToCoreDecl here. * * \returns * Write description of return value here. * * \throws <exception class> * Description of criteria for throwing this exception. * * Write detailed description for FillBehaviorPClothAttachToCoreDecl here. * * \remarks * Write remarks for FillBehaviorPClothAttachToCoreDecl here. * * \see * Separate items with the '|' character. */ CKObjectDeclaration *FillBehaviorPClothAttachToCoreDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAttachToCore"); od->SetCategory("Physic/Cloth"); od->SetDescription("Surrounds a rigid body with a cloth."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x37d75f67,0x7041320f)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePClothAttachToCoreProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePClothAttachToCoreProto // FullName: CreatePClothAttachToCoreProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePClothAttachToCoreProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAttachToCore"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PClothAttachToCore PClothAttachToCore is categorized in \ref Clothes <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Attaches a cloth to a body.<br> Call this function only once right after the cloth is created. Turning cloth into metal and vice versa during the simulation is not recommended. This feature is well suited for volumetric objects like barrels. It cannot handle two dimensional flat pieces well. After this call, the cloth is infinitely stiff between collisions and simply moves with the body. At impacts with an impact impulse greater than impulseThreshold, the cloth is plastically deformed. Thus, a cloth with a core behaves like a piece of metal. The core body's geometry is adjusted automatically. Its size also depends on the cloth thickness. Thus, it is recommended to choose small values for the thickness. At impacts, colliding objects are moved closer to the cloth by the value provided in penetrationDepth which causes a more dramatic collision result. The core body must have at least one shape, and currently supported shapes are spheres, capsules, boxes and compounds of spheres. It is recommended to specify the density rather than the mass of the core body. This way the mass and inertia tensor are updated when the core deforms. The maximal deviation of cloth particles from their initial positions (modulo the global rigid body transforms translation and rotation) can be specified via the parameter maxDeformationDistance. Setting this parameter to zero means that the deformation is not limited. <h3>Technical Information</h3> \image html PClothAttachToCore.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>Target cloth reference. <BR> <BR> <SPAN CLASS="pin">Body Reference: </SPAN>The core body to attach the cloth to. @see pCloth::attachToCore() <BR> <SPAN CLASS="pin">Impulse Threshold: </SPAN>Threshold for when deformation is allowed. <BR> <SPAN CLASS="pin">Penetration Depth: </SPAN>Amount by which colliding objects are brought closer to the cloth. <BR> <SPAN CLASS="pin">Max Deformation Distance: </SPAN>Maximum deviation of cloth particles from initial position. <BR> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include pCloth.cpp </SPAN> */ proto->SetBehaviorCallbackFct( PClothAttachToCoreCB ); proto->DeclareInParameter("Body Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Impulse Threshold",CKPGUID_FLOAT); proto->DeclareInParameter("Penetration Depth",CKPGUID_FLOAT); proto->DeclareInParameter("Max Deformation Distance",CKPGUID_FLOAT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PClothAttachToCore); *pproto = proto; return CK_OK; } //************************************ // Method: PClothAttachToCore // FullName: PClothAttachToCore // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PClothAttachToCore(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// CK3dEntity*bodyReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_BodyReference); if (!bodyReference) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pRigidBody *body = GetPMan()->getBody(bodyReference); if (!body) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pWorld *world = body->getWorld(); if (!world) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } pCloth *cloth = world->getCloth(target); if (!cloth) { beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } float impulseThreshold = GetInputParameterValue<float>(beh,bbI_ImpulseThreshold); float penetrationDepth = GetInputParameterValue<float>(beh,bbI_PenetrationDepth); float maxDeform = GetInputParameterValue<int>(beh,bbI_MaxDeform); cloth->attachToCore(bodyReference,impulseThreshold,penetrationDepth,maxDeform); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PClothAttachToCoreCB // FullName: PClothAttachToCoreCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PClothAttachToCoreCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtAttributeHelper.h" bool isSceneObject2(CK3dEntity *object) { CKLevel *level = GetPMan()->GetContext()->GetCurrentLevel(); if(level) { for(int i = 0 ; i < level->GetSceneCount() ; i++ ) { CKScene *scene = level->GetScene(i); if(scene && scene->IsObjectHere(object)) return true; } } return false; } void PhysicManager::_checkObjectsByAttribute(CKScene *newScene) { CKAttributeManager* attman = m_Context->GetAttributeManager(); int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;//(sizeof(*getRegistrationTable()) / sizeof((getRegistrationTable())[0])); for (int fIndex = 0 ; fIndex < sizeJFuncMap ; fIndex ++) { std::vector<int>attributeIdList; pFactory::Instance()->findAttributeIdentifiersByGuid(getRegistrationTable()[fIndex].guid,attributeIdList); int attCount = attributeIdList.size(); for (int i = 0 ; i < attCount ; i++ ) { int currentAttType = attributeIdList.at(i); const XObjectPointerArray& Array = attman->GetAttributeListPtr( attributeIdList.at(i) ); for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { CK3dEntity *target = static_cast<CK3dEntity*>(*it); if (target) { XString error; error.Format("Registering :%s with %s",target->GetName(),attman->GetAttributeNameByType(currentAttType)); //if(!strcmp( target->GetName(),"smutan3-3" ) ) { // xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"problem case" ); } // CKScene *levelScene = GetContext()->GetCurrentLevel()->GetCurrentScene(); // we check as no scene is current in use if ( ( GetContext()->GetCurrentLevel()->GetLevelScene() == newScene && !isSceneObject2(target) ) || ( newScene && newScene->IsObjectHere(target) && newScene !=GetContext()->GetCurrentLevel()->GetLevelScene() ) || ( newScene && GetContext()->GetCurrentLevel()->GetCurrentScene() && GetContext()->GetCurrentLevel()->GetCurrentScene() == newScene && newScene !=GetContext()->GetCurrentLevel()->GetLevelScene() && newScene->IsObjectHere(target) ) || ( (physicFlags & PMF_DONT_DELETE_SCENES) ) ) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.CStr() ); (*getRegistrationTable()[fIndex].rFunc)(target,currentAttType,true,false); GetPMan()->getCheckList().PushBack(target->GetID()); } } } } } } void PhysicManager::_RegisterAttributeCallbacks() { if (!getAttributeFunctions().Size()) { return; } CKAttributeManager* attman = m_Context->GetAttributeManager(); AttributeFunctionArrayIteratorType it = getAttributeFunctions().Begin(); while(it != getAttributeFunctions().End()) { ObjectRegisterFunction myFn = (ObjectRegisterFunction)*it; if (myFn) { attman->SetAttributeCallbackFunction(it.GetKey(),PObjectAttributeCallbackFunc,myFn); } it++; } } void PhysicManager::cleanAttributePostObjects() { using namespace vtTools::ParameterTools; if (!getAttributePostObjects().Size()) return; CKAttributeManager* attman = m_Context->GetAttributeManager(); PostRegistrationArrayIteratorType it = getAttributePostObjects().Begin(); if (getAttributePostObjects().Size()) { if (!GetPMan()->isValid()){ xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Invalid world, performing initiation..."); GetPMan()->performInitialization(); } } while(it != getAttributePostObjects().End()) { pAttributePostObject& post = *it; CK3dEntity *refObject = static_cast<CK3dEntity*>(GetPMan()->m_Context->GetObject(post.objectId)); if (refObject) { ObjectRegisterFunction regFn = (ObjectRegisterFunction)post.func; if (regFn) { (*regFn)(refObject,post.attributeID,true,false); } } it++; } int s = getAttributePostObjects().Size(); getAttributePostObjects().Clear(); } void PhysicManager::populateAttributeFunctions() { getAttributeFunctions().Clear(); int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;// (sizeof(*getRegistrationTable()) / sizeof(ObjectRegistration)); for (int fIndex = 0 ; fIndex < sizeJFuncMap ; fIndex ++) { #ifdef _DEBUG //XString _errorStr; //getRegistrationTable()[fIndex].rFunc. //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.Str()); #endif std::vector<int>attributeIdList; pFactory::Instance()->findAttributeIdentifiersByGuid(getRegistrationTable()[fIndex].guid,attributeIdList); int attCount = attributeIdList.size(); for (int i = 0 ; i < attCount ; i++ ) { int currentAttType = attributeIdList.at(i); getAttributeFunctions().Insert(currentAttType,getRegistrationTable()[fIndex].rFunc); } } } ObjectRegistration*PhysicManager::getRegistrationTable() { return attributeFunctionMap; } <file_sep>#ifndef __XMESSAGE_TYPES_H_ #define __XMESSAGE_TYPES_H_ ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// #include "xPoint.h" #include "xMessage.h" class xMessageType { public : xMessageType() { type = -1; name =""; sessionID =-1; numParameters =-1; } int getType() const { return type; } void setType(int val) { type = val; } xNString getName() const { return name; } void setName(xNString val) { name = val; } int getNumParameters() const { return numParameters; } void setNumParameters(int val) { numParameters = val; } int getSessionID() const { return sessionID; } void setSessionID(int val) { sessionID = val; } protected : int type; xNString name; int numParameters; int sessionID; }; class xNetMessage { public : xNetMessage(){} virtual ~xNetMessage(){} int type; int getType() const { return type; } void setType(int val) { type = val; } }; ////////////////////////////////////////////////////////////////////////// template<class T>class xMessageData : public xNetMessage { public : typedef T* ValueRef; T value; T getValue(){return value;} void setValue(const T& _value ) { value = _value; } virtual ~xMessageData(){} }; ////////////////////////////////////////////////////////////////////////// class xMessageFloat : public xMessageData<TNL::F32> { public : xMessageFloat(){} }; ////////////////////////////////////////////////////////////////////////// class xMessageInt : public xMessageData<TNL::S32> { public : xMessageInt(){} }; ////////////////////////////////////////////////////////////////////////// class xMessageString : public xMessageData<TNL::StringPtr> { public : xMessageString(){} }; ////////////////////////////////////////////////////////////////////////// class xMessagePoint3F : public xMessageData<Point3F> { public : xMessagePoint3F(){} }; ////////////////////////////////////////////////////////////////////////// class xMessagePoint4F : public xMessageData<Point4F> { public : xMessagePoint4F(){} }; ////////////////////////////////////////////////////////////////////////// #endif<file_sep>#include <wtypes.h> #include "CKAll.h" HINSTANCE GetModulefromResource(HMODULE hModule,int name,char *tempfile); HMODULE GetParentModule(CK_PLUGIN_TYPE type,CKGUID guid); <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtAttributeHelper.h" NxShape *PhysicManager::getSubShape(CK3dEntity*referenceObject) { if (!referenceObject) return NULL; pRigidBody *body = getBody(referenceObject); if (!body) return NULL; return body->getSubShape(referenceObject); } NxCCDSkeleton* PhysicManager::getCCDSkeleton(CKBeObject *shapeReference) { pWorldMapIt it = getWorlds()->Begin(); int s = getWorlds()->Size(); while(it != getWorlds()->End()) { pWorld *w = *it; NxActor** actors = w->getScene()->getActors(); int nbActors = w->getScene()->getNbActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { NxU32 nbShapes = actor->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)actor->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(s->userData); if (sInfo) { } } } } } } return NULL; } void PhysicManager::createWorlds(int flags) { #ifdef _DEBUG //assert(m_DefaultSleepingSettings()); // assert(getWorlds()); #endif CKAttributeManager* attman = m_Context->GetAttributeManager(); const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_world_object); for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { CK3dEntity*target = static_cast<CK3dEntity*>(*it); pWorld *world = getWorld(target->GetID()); const char*name = target->GetName(); if (world == getDefaultWorld() ) { continue; } ////////////////////////////////////////////////////////////////////////// //world not registered : if (!world) { //at first we check for an attached sleeping settings attribute, when not, we use this->DefaultDefaultSleepingSettings // pSleepingSettings *sleepSettings = target->HasAttribute(att_sleep_settings) ? // pFactory::Instance()->GetSleepingSettingsFromEntity(target) : &this->DefaultSleepingSettings(); //we also retrieve objects world settings //pWorldSettings * worldSettings = pFactory::Instance()->GetWorldSettingsFromEntity(target); //now we can create the final world,the function initiates the world and also it inserts the world //in our m_pWorlds array ! //world = pFactory::Instance()->createWorld(target,worldSettings,sleepSettings); } } }; int PhysicManager::getNbWorlds(){ return getWorlds()->Size();} void PhysicManager::checkClothes() { if (!getNbObjects()) return; if (!isValid()) performInitialization(); if (!isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't make manager valid"); return; } ////////////////////////////////////////////////////////////////////////// // we iterate through all entities tagged with the physic attribute CKAttributeManager* attman = m_Context->GetAttributeManager(); const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_clothDescr); for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { CK3dEntity *target = static_cast<CK3dEntity*>(*it); if (target) { const char *bName = target->GetName(); // is the body registered in any world ? CK_ID wID = vtTools::AttributeTools::GetValueFromAttribute<CK_ID>(target,att_clothDescr,E_CS_WORLD_REFERENCE); CK3dEntity *worldReference = (CK3dEntity*)m_Context->GetObject(wID); pWorld *world = getWorld(wID); if (!worldReference) { continue; } if (getBody(target)) { continue; } if (world->getShapeByEntityID(target->GetID())) { continue; } if (world && worldReference) { pCloth *cloth = world->getCloth(target); if (!cloth) { pClothDesc *descr = pFactory::Instance()->createClothDescrFromParameter(target->GetAttributeParameter(att_clothDescr)); cloth = pFactory::Instance()->createCloth(target,*descr); if(cloth) { ////////////////////////////////////////////////////////////////////////// if (descr->flags & PCF_AttachToParentMainShape ) { if (target->GetParent()) { CK3dEntity *bodyReference = pFactory::Instance()->getMostTopParent(target); if (bodyReference) { pRigidBody *body = GetPMan()->getBody(bodyReference); if (body) { cloth->attachToShape((CKBeObject*)bodyReference,descr->attachmentFlags); } } } } ////////////////////////////////////////////////////////////////////////// if (descr->flags & PCF_AttachToCollidingShapes) { cloth->attachToCollidingShapes(descr->attachmentFlags); } } } } } } } void PhysicManager::checkWorlds() { if (!getNbObjects()) return; if (!isValid()) performInitialization(); if (!isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't make manager valid"); return; } ////////////////////////////////////////////////////////////////////////// // we iterate through all entities tagged with the physic attribute CKAttributeManager* attman = m_Context->GetAttributeManager(); const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_physic_object); for (CKObject** it = Array.Begin(); it != Array.End(); ++it) { CK3dEntity *target = static_cast<CK3dEntity*>(*it); if (target) { const char *bName = target->GetName(); // is the body registered in any world ? pRigidBody* body = getBody(target); if(!body) { //we retrieve the bodies target world : CK_ID wID = vtTools::AttributeTools::GetValueFromAttribute<CK_ID>(target,GetPAttribute(),E_PPS_WORLD); int flags = vtTools::AttributeTools::GetValueFromAttribute<CK_ID>(target,GetPAttribute(),E_PPS_BODY_FLAGS); if (flags & BF_SubShape) { continue; } pWorld *world = getWorld(wID) ? getWorld(wID) : getDefaultWorld(); if(world) { //now create the final rigid body : body = pFactory::Instance()->createRigidBodyFull(target,world->getReference()); } } } } checkClothes(); _checkObjectsByAttribute(); ////////////////////////////////////////////////////////////////////////// pWorldMapIt itx = getWorlds()->Begin(); while(itx != getWorlds()->End()) { pWorld *w = *itx; if (w) { w->checkList(); } itx++; } } pWorld *PhysicManager::getWorld(CK3dEntity *_o, CK3dEntity *body) { pWorld *result=NULL; ////////////////////////////////////////////////////////////////////////// // // Priorities : // 1. the given world by _o // 2. DefaultWorld // 3. body physic attribute // 4. created default world // ////////////////////////////////////////////////////////////////////////// // we try to get it over _o : if (_o) { result = getWorld(_o->GetID()); if (result && getWorld(_o->GetID())->getReference() ) { _o = result->getReference(); return result; } } ////////////////////////////////////////////////////////////////////////// //still nothing, we try to get the default world : result = getDefaultWorld(); if (result && getDefaultWorld()->getReference() ) { CK_ID id = getDefaultWorld()->getReference()->GetID(); _o = result->getReference(); return result; } ////////////////////////////////////////////////////////////////////////// //we try to get it over the bodies attribute : if (body) { if (body->HasAttribute(GetPAttribute())) { CK_ID id = vtTools::AttributeTools::GetValueFromAttribute<CK_ID>(body,GetPMan()->GetPAttribute(),E_PPS_WORLD); _o = static_cast<CK3dEntity*>(ctx()->GetObject(id)); if (_o) { result = getWorld(_o->GetID()); if (result && getWorld(_o->GetID())->getReference()) { _o = result->getReference(); return result; } _o = NULL; } } } ////////////////////////////////////////////////////////////////////////// //still nothing if (!getDefaultWorld()) { return NULL; //result = pFactory::Instance()->createDefaultWorld("pDefaultWorld"); /* if (result) { _o = getDefaultWorld()->getReference(); }else{ GetPMan()->performInitialization(); result = GetPMan()->getDefaultWorld(); _o = result->getReference(); } */ } return result; } void PhysicManager::destroyWorlds() { pWorldMapIt it = getWorlds()->Begin(); int s = getWorlds()->Size(); while(it != getWorlds()->End()) { pWorld *w = *it; if (w) { w->destroy(); if (w->getReference()) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"World destroyed :%s",w->getReference()->GetName()); } getWorlds()->Remove(w->getReference()); delete w; w = NULL; if (getWorlds()->Size()) { destroyWorlds(); } } } getWorlds()->Clear(); } pWorld*PhysicManager::getWorld(CK_ID _o) { pWorld *result = NULL; CK3dEntity *obj = static_cast<CK3dEntity*>(GetContext()->GetObject(_o)); if (obj) { if (getWorlds()->FindPtr(obj)) { return *getWorlds()->FindPtr(obj); } } return 0; } void PhysicManager::deleteWorld(CK_ID _o) { CK3dEntity *obj = static_cast<CK3dEntity*>(GetContext()->GetObject(_o)); if (obj) { pWorld *w = getWorld(_o); if (w) { w->destroy(); getWorlds()->Remove(obj); delete w; } } } pWorld*PhysicManager::getWorldByShapeReference(CK3dEntity *shapeReference) { if (!shapeReference) { return NULL; } for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) { pWorld *w = *it; if(w) { pRigidBody *body = w->getBody(pFactory::Instance()->getMostTopParent(shapeReference)); if (body) { if (body->isSubShape((CKBeObject*)shapeReference)) { return w; } } } } return 0; } pWorld*PhysicManager::getWorldByBody(CK3dEntity*ent) { if (!ent) { return NULL; } for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) { pWorld *w = *it; if(w) { //pRigidBody *body = w->getBody(pFactory::Instance()->getMostTopParent(ent)); pRigidBody *body = w->getBody(ent); if (body) { return w; } } } return 0; } pCloth *PhysicManager::getCloth(CK_ID entityID) { CK3dEntity *entity = (CK3dEntity*)m_Context->GetObject(entityID); if (!entityID) { return NULL; } for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) { pWorld *w = *it; if(w) { pCloth *cloth = w->getCloth(entity); if (cloth) { return cloth; } } } return NULL; } int PhysicManager::getNbObjects(int flags /* =0 */) { CKAttributeManager* attman = ctx()->GetAttributeManager(); int testAtt = -1; if (flags == 0) testAtt = GetPMan()->GetPAttribute(); int newPhysicObjectAttributeType = getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); // [3/31/2009 master] const XObjectPointerArray& Array = attman->GetAttributeListPtr(testAtt); int startSize = 0; startSize +=Array.Size(); startSize+=attman->GetAttributeListPtr(newPhysicObjectAttributeType).Size(); /* pWorldMapIt it = getWorlds()->Begin(); while(it != getWorlds()->End()) { pWorld *w = *it; if (w) { w->checkList(); } it++; } */ return startSize; }<file_sep># TNL Makefile # (c) 2003 GarageGames # # This makefile is for gcc-based projects, at the moment. # # Configuration # CC=g++ -g -DTNL_DEBUG -DTNL_ENABLE_LOGGING -I../libtomcrypt -W -w -fpermissive -DTNL_DEBUG -DTNL_ENABLE_LOGGING # -O2 OBJECTS=\ assert.o\ asymmetricKey.o\ bitStream.o\ byteBuffer.o\ certificate.o\ clientPuzzle.o\ connectionStringTable.o\ dataChunker.o\ eventConnection.o\ ghostConnection.o\ huffmanStringProcessor.o\ log.o\ netBase.o\ netConnection.o\ netInterface.o\ netObject.o\ netStringTable.o\ platform.o\ random.o\ rpc.o\ symmetricCipher.o\ tnlMethodDispatch.o\ journal.o\ udp.o\ vector.o\ CFLAGS= .cpp.o : $(CC) -c $(CFLAGS) $< default: $(OBJECTS) @echo Building libtnl.a ... ar rcv libtnl.a $(OBJECTS) clean: rm -f $(OBJECTS) libtnl.a <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #ifdef HAS_FLUIDS pFluid *pWorld::getFluid(CK_ID id) { int nbFluids= getScene()->getNbFluids(); NxFluid** fluids = getScene()->getFluids(); while(nbFluids--) { NxFluid* fluid = *fluids++; if(fluid->userData != NULL) { pFluid *vFluid = static_cast<pFluid*>(fluid->userData); if (vFluid) { if (vFluid->getEntityID() == id) { return vFluid; } } } } return NULL; } pFluid*pWorld::getFluid(CK3dEntity* entity) { if (!entity) { return NULL; } return getFluid(entity->GetID()); } void pWorld::updateFluids() { int nbFluids= getScene()->getNbFluids(); NxFluid** fluids = getScene()->getFluids(); while(nbFluids--) { NxFluid* fluid = *fluids++; if(fluid->userData != NULL) { pFluid *vFluid = static_cast<pFluid*>(fluid->userData); if (vFluid) { vFluid->updateVirtoolsMesh(); } } } } #endif<file_sep>#ifndef __P_FACTORY_H__ #define __P_FACTORY_H__ #include "vtPhysXBase.h" /** \brief Singleton class to create physic objects. */ class MODULE_API pFactory { public: //friend class PhysicManager; virtual ~pFactory(); void findAttributeIdentifiersByGuid(CKGUID guid,std::vector<int>&targetList); pFactory(); pFactory(PhysicManager* prm1,TiXmlDocument*prm2); int reloadConfig(const char *fName); TiXmlDocument* loadConfig(const char* filename); pWorldSettings *createWorldSettings(const XString nodeName="Default",const TiXmlDocument * doc = NULL); pWorldSettings *createWorldSettings(const char* nodeName,const char *filename); pWorldSettings*getWorldSettings(CK3dEntity*ent); pWorld* createDefaultWorld(XString name); const TiXmlElement*getFirstDocElement(const TiXmlElement *root); TiXmlDocument* getDefaultDocument() const { return m_DefaultDocument; } TiXmlDocument* getDocument(XString filename); NxPhysicsSDK* getPhysicSDK() { return mPhysicSDK; } void setPhysicSDK(NxPhysicsSDK* val) { mPhysicSDK = val; } PhysicManager * getManager() const { return mManager; } void setManager(PhysicManager * val) { mManager = val; } void setDefaultDocument(TiXmlDocument* val) { m_DefaultDocument = val; } void clean(); void destroy(); ////////////////////////////////////////////////////////////////////////// int copyTo(CKParameter *src,pDominanceSetupItem&dst); pSleepingSettings *CreateSleepingSettings(XString nodeName="Default", TiXmlDocument * doc = NULL); pSleepingSettings*CreateSleepingSettings(const char* nodeName,const char *filename); pSleepingSettings*getSleepingSettings(CK3dEntity*ent); pWorld *createWorld(CK3dEntity *referenceObject,pWorldSettings*worldSettings=NULL,pSleepingSettings*sleepSettings=NULL); pRemoteDebuggerSettings createDebuggerSettings(const TiXmlDocument * doc); /************************************************************************************************/ /** @name RigidBody */ //@{ pRigidBody *cloneRigidBody(CK3dEntity *src,CK3dEntity *dst,CKDependencies *deps,int copyFlags,int bodyFlags=0); NxShape *cloneShape(CK3dEntity *src,CK3dEntity *dst,CK3dEntity*dstBodyReference,int copyFlags,int bodyFlags=0); pJoint* cloneJoint(pJoint *src,CK3dEntity *srcReference,CK3dEntity *dstReference,int copyFlags); int cloneLimitPlanes(pJoint *src,pJoint *dst,CK3dEntity *srcReference,CK3dEntity *dstReference); void cloneJoints(CK3dEntity *src,CK3dEntity *dst,int copyFlags); pRigidBody *createRigidBodyFull(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject=NULL); pRigidBody *createBody(CK3dEntity *referenceObject,pObjectDescr descriction,CK3dEntity *worldReferenceObject=NULL); pRigidBody *createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject=NULL); pRigidBody *createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,NXU::NxActorDesc *desc,int flags); pRigidBody *createRigidBody(CK3dEntity *referenceObject,pObjectDescr& oDescr); pRigidBody *createBox(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags); pRigidBody *createCapsule(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags); int createSubShape(CK3dEntity*target,CK3dEntity*child); NxCCDSkeleton *createCCDSkeleton(CKBeObject *meshReference,int flags); //@} /************************************************************************************************/ /** @name Joints */ //@{ pJoint *createJoint(CK3dEntity*,CK3dEntity*,int); pJointDistance*createDistanceJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor0=VxVector(0,0,0),VxVector anchor1=VxVector(0,0,0),float minDistance=0.0f,float maxDistance=0.0f,pSpring sSettings=pSpring(),bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJDistance"); pJointD6* createD6Joint(CK3dEntity*a,CK3dEntity*b,VxVector globalAnchor=VxVector(0,0,0),VxVector globalAxis=VxVector(0,-1,0),bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f); pJointFixed* createFixedJoint(CK3dEntity*a,CK3dEntity*b,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJFixed"); pJointPulley*createPulleyJoint(CK3dEntity*a,CK3dEntity*b,VxVector pulley0,VxVector pulley1, VxVector anchor0, VxVector anchor1,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f); pJointBall *createBallJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector swingAxis,VxVector globalAxis=VxVector(0,1,0),bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJBall"); pJointPrismatic*createPrismaticJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJPrismatic"); pJointCylindrical*createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJCylindrical"); pJointRevolute *createRevoluteJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJRevolute"); pJointPointInPlane *createPointInPlaneJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJPointInPlane"); pJointPointOnLine *createPointOnLineJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJPointOnLine"); pJoint *GetJoint(CK3dEntity*,CK3dEntity*); pJoint *GetJoint(CK3dEntity*,int); pJointSettings *CreateJointSettings(const XString nodeName="Default",const TiXmlDocument * doc = NULL); pJointSettings *CreateJointSettings(const char* nodeName,const char *filename); int jointCheckPreRequisites(CK3dEntity*,CK3dEntity*,int); //@} ////////////////////////////////////////////////////////////////////////// //nx NxShapeDesc& createShape(int hullType,CK3dEntity*ent,float density = 1.0f); NxMaterialDesc* createMaterialFromXML(const char* nodeName="Default",const TiXmlDocument * doc = NULL); NxMaterialDesc* createMaterialFromEntity(CKBeObject*object); CKParameterOut* findSettings(pWheelDescr&dst,CKBeObject*src); bool findSettings(pMaterial&dst,CKBeObject*src); bool copyTo(pMaterial& dst,CKParameter*src); bool copyTo(pMaterial& dst,NxMaterial*src); bool copyTo(NxMaterial&dst,pMaterial*src); bool copyTo(CKParameterOut*dst,const pMaterial&src); bool copyTo(NxMaterialDesc&dst,const pMaterial&src); bool loadFrom(pMaterial& dst,const char* nodeName="Default",const TiXmlDocument * doc = NULL); bool loadMaterial(pMaterial&dst,const char* nodeName); pMaterial loadMaterial(const char* nodeName,int& error); ////////////////////////////////////////////////////////////////////////// //nx mesh : void createMesh(NxScene *scene,CKMesh *mesh,NxTriangleMeshDesc&descr,bool hardware=false); void createConvexMesh(NxScene *scene,CKMesh *mesh,NxConvexMeshDesc&descr,bool hardware=false); NxShape *createShape(CK3dEntity *bodyReference,pObjectDescr descr,CK3dEntity *srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); static pFactory* Instance(); pSpring createSpringFromParameter(CKParameter *par); pJointLimit createLimitFromParameter(CKParameter *par); pMotor createMotorFromParameter(CKParameter *par); pTireFunction createTireFuncFromParameter(CKParameter *par); pObjectDescr *createPObjectDescrFromParameter(CKParameter *par); /************************************************************************/ /* clothes : */ /************************************************************************/ pClothDesc *createClothDescrFromParameter(CKParameter *par); pCloth *createCloth(CK3dEntity *srcReference,pClothDesc descr); void copyToClothDescr(NxClothDesc* dst,pClothDesc src ); void copyTo(pDeformableSettings &dst,CKParameter*par); /************************************************************************/ /*Special Case Capsule : */ /************************************************************************/ bool copyTo(pCapsuleSettings&dst,CKParameter*src); bool findSettings(pCapsuleSettings&dst,CKBeObject *src); bool findSettings(pCapsuleSettingsEx&dst,CKBeObject *src); bool findSettings(pConvexCylinderSettings&dst,CKBeObject *src); bool findSettings(pCCDSettings&dst,CKBeObject *src); bool findSettings(pMassSettings&dst,CKBeObject *src); bool findSettings(pPivotSettings&dst,CKBeObject *src); bool findSettings(pOptimization&dst,CKBeObject *src); bool findSettings(pCollisionSettings&dst,CKBeObject*src); CKParameterOut* findSettingsParameter(CKBeObject *src,CKGUID guid); /************************************************************************/ /* fluids : */ /************************************************************************/ //pFluid*createFluid(CK3dEntity *srcReference ,pFluidDesc desc); //void copyToFluidDescr(NxFluidDesc &dst , pFluidDesc src ); //CK3dEntity *createFluidEntity(); //void initParticles(pFluidDesc &desc,NxParticleData&dst,CK3dEntity*srcReference,CK3dEntity*dstEntity); //void copyToEmitterDesc(NxFluidEmitterDesc&dst,pFluidEmitterDesc src); //CK3dPointCloud* createPointCloud(const pFluidDesc&descr); /************************************************************************/ /* Vehicle */ /************************************************************************/ pVehicle *createVehicle(CK3dEntity *body,pVehicleDesc descr); pVehicleMotor *createVehicleMotor(pVehicleMotorDesc descr); pVehicleGears *createVehicleGears(pVehicleGearDesc descr); pWheel *createWheelSubShape(pRigidBody *body,CK3dEntity* subEntity,CKMesh *mesh,pObjectDescr *descr,VxVector localPos, VxQuaternion localRotation,NxShape*dstShape); XString _getMaterialsAsEnumeration(const TiXmlDocument * doc); XString _getBodyXMLInternalEnumeration(const TiXmlDocument * doc); XString _getBodyXMLExternalEnumeration(const TiXmlDocument * doc); XString _getVehicleTireFunctionAsEnumeration(const TiXmlDocument * doc); XString _getVehicleWheelAsEnumeration(const TiXmlDocument * doc); XString _getVehicleSettingsAsEnumeration(const TiXmlDocument * doc); XString _getVehicleMotorSettingsAsEnumeration(const TiXmlDocument * doc); XString _getVehicleGearSettingsAsEnumeration(const TiXmlDocument * doc); XString _getEnumDescription(const TiXmlDocument * doc,XString identifier); int _getEnumIdentifier(const TiXmlDocument * doc,XString type); int _getEnumIndex(XString enumerationFull,XString enumValue); NxShape *createWheelShape(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CK3dEntity*srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); NxShape *_createWheelShape1(NxActor *actor,pWheel1 *dstWheel,pObjectDescr *descr,pWheelDescr *wheelDescr,CK3dEntity*srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); NxShape *_createWheelShape2(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CK3dEntity*srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); NxShape *createWheelShape(CK3dEntity*bodyReference,pWheelDescr wheelDescr,CK3dEntity*wheelReference); pWheel *createWheel(pRigidBody *body,pWheelDescr descr,CK3dEntity *wheelShapeReference); pWheel* createWheel(CK3dEntity *bodyReference,CK3dEntity*srcReference,pWheelDescr wheelDescr,pConvexCylinderSettings convexCylinder,VxVector localPositionOffset); NxShape *createWheelShape2(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr); NxShape *createWheelShape1(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr); NxShape *_createConvexCylinder(NxActor *actor,int approximation,VxVector _forwardAxis,VxVector _downAxis,VxVector _rightAxis,float height,float radius,bool buildLowerHalf,int shapeFlags); bool _createConvexCylinder(NxConvexShapeDesc* shape,CK3dEntity*dstBodyReference,pObjectDescr *oDescr=NULL); bool _createConvexCylinderMesh(NxConvexShapeDesc *dstShapeDescription,pConvexCylinderSettings& srcSettings,CK3dEntity*referenceObject); NxShape *_createConvexCylinder(const pConvexCylinderSettings& cylinderDescr,CK3dEntity *srcReference); int loadVehicleDescrFromXML(pVehicleDesc& dst,const char* nodeName/* =NULL */,const TiXmlDocument * doc /* = NULL */ ); ////////////////////////////////////////////////////////////////////////// // // Geometry related structures : // void copyTo(pAxisReferencedLength&dst,CKParameter*src,bool evaluate=true); bool copyTo(pConvexCylinderSettings&dst,CKParameter*src,bool evaluate=true); ////////////////////////////////////////////////////////////////////////// // // wheels int copyTo(pWheelDescr *dst,CKParameter *src); int loadFrom(pTireFunction& dst,const char* nodeName/* = */,const TiXmlDocument * doc /* = NULL */); int loadWheelDescrFromXML(pWheelDescr& dst,const char* nodeName/* =NULL */,const TiXmlDocument * doc /* = NULL */ ); bool loadFrom(pWheelDescr& dst,const char* nodeName/* =NULL */); int copyTo(CKParameterOut *dst,pWheelDescr *src); int copyTo(pWheelDescr &dst,CKParameterOut *src); int copyTo(CKParameterOut *dst,const pTireFunction& src); //contact data : int copyTo(CKParameterOut *dst,const pWheelContactData& src); ////////////////////////////////////////////////////////////////////////// // // // collision structures int copyTo(pGroupsMask &dst,CKParameter*src); int copyTo(CKParameterOut*dst,pGroupsMask src); CK3dEntity *getMostTopParent(CK3dEntity*ent); protected: PhysicManager *mManager; TiXmlDocument* m_DefaultDocument; NxPhysicsSDK* mPhysicSDK; VxVector _str2Vec(XString _in); int _str2MaterialFlag(XString _in); int _str2WheelFlag(XString _in); int _str2SceneFlags(XString _in); int _str2PhysicFlags(XString _in); int _str2WheelShapeFlag(XString _in); XString ResolveFileName(const char *input); int _str2CombineMode(const char*input); CK3dEntity *createFrame(const char* name); }; #endif // !defined(EA_10DFC1E8_486F_4770_9451_7898DBDAD59F__INCLUDED_) <file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #include "tnlBitStream.h" #include "tnlVector.h" #include "tnlNetBase.h" #include "tnlHuffmanStringProcessor.h" #include "tnlSymmetricCipher.h" #include <mycrypt.h> #include <math.h> namespace TNL { void BitStream::setMaxSizes(U32 maxReadSize, U32 maxWriteSize) { maxReadBitNum = maxReadSize << 3; maxWriteBitNum = maxWriteSize << 3; } void BitStream::setMaxBitSizes(U32 maxReadSize, U32 maxWriteSize) { maxReadBitNum = maxReadSize; maxWriteBitNum = maxWriteSize; } void BitStream::reset() { bitNum = 0; error = false; mCompressRelative = false; mStringBuffer[0] = 0; mStringTable = NULL; } U8 *BitStream::getBytePtr() { return getBuffer() + getBytePosition(); } void BitStream::writeClassId(U32 classId, U32 classType, U32 classGroup) { TNLAssert(classType < NetClassTypeCount, "Out of range class type."); TNLAssert(classId < NetClassRep::getNetClassCount(classGroup, classType), "Out of range class id."); writeInt(classId, NetClassRep::getNetClassBitSize(classGroup, classType)); } U32 BitStream::readClassId(U32 classType, U32 classGroup) { TNLAssert(classType < NetClassTypeCount, "Out of range class type."); U32 ret = readInt(NetClassRep::getNetClassBitSize(classGroup, classType)); if(ret >= NetClassRep::getNetClassCount(classGroup, classType)) return 0xFFFFFFFF; return ret; } bool BitStream::resizeBits(U32 newBits) { U32 newSize = ((maxWriteBitNum + newBits + 7) >> 3) + ResizePad; if(!resize(newSize)) { error = true; return false; } maxReadBitNum = newSize << 3; maxWriteBitNum = newSize << 3; return true; } bool BitStream::writeBits(U32 bitCount, const void *bitPtr) { if(!bitCount) return true; if(bitCount + bitNum > maxWriteBitNum) if(!resizeBits(bitCount + bitNum - maxWriteBitNum)) return false; U32 upShift = bitNum & 0x7; U32 downShift= 8 - upShift; const U8 *sourcePtr = (U8 *) bitPtr; U8 *destPtr = getBuffer() + (bitNum >> 3); // if this write is for <= 1 byte, and it will all fit in the // first dest byte, then do some special masking. if(downShift >= bitCount) { U8 mask = ((1 << bitCount) - 1) << upShift; *destPtr = (*destPtr & ~mask) | ((*sourcePtr << upShift) & mask); bitNum += bitCount; return true; } // check for byte aligned writes -- this will be // much faster than the shifting writes. if(!upShift) { bitNum += bitCount; for(; bitCount >= 8; bitCount -= 8) *destPtr++ = *sourcePtr++; if(bitCount) { U8 mask = (1 << bitCount) - 1; *destPtr = (*sourcePtr & mask) | (*destPtr & ~mask); } return true; } // the write destination is not byte aligned. U8 sourceByte; U8 destByte = *destPtr & (0xFF >> downShift); U8 lastMask = 0xFF >> (7 - ((bitNum + bitCount - 1) & 0x7)); bitNum += bitCount; for(;bitCount >= 8; bitCount -= 8) { sourceByte = *sourcePtr++; *destPtr++ = destByte | (sourceByte << upShift); destByte = sourceByte >> downShift; } if(bitCount == 0) { *destPtr = (*destPtr & ~lastMask) | (destByte & lastMask); return true; } if(bitCount <= downShift) { *destPtr = (*destPtr & ~lastMask) | ((destByte | (*sourcePtr << upShift)) & lastMask); return true; } sourceByte = *sourcePtr; *destPtr++ = destByte | (sourceByte << upShift); *destPtr = (*destPtr & ~lastMask) | ((sourceByte >> downShift) & lastMask); return true; } bool BitStream::readBits(U32 bitCount, void *bitPtr) { if(!bitCount) return true; if(bitCount + bitNum > maxReadBitNum) { error = true; return false; } U8 *sourcePtr = getBuffer() + (bitNum >> 3); U32 byteCount = (bitCount + 7) >> 3; U8 *destPtr = (U8 *) bitPtr; U32 downShift = bitNum & 0x7; U32 upShift = 8 - downShift; if(!downShift) { while(byteCount--) *destPtr++ = *sourcePtr++; bitNum += bitCount; return true; } U8 sourceByte = *sourcePtr >> downShift; bitNum += bitCount; for(; bitCount >= 8; bitCount -= 8) { U8 nextByte = *++sourcePtr; *destPtr++ = sourceByte | (nextByte << upShift); sourceByte = nextByte >> downShift; } if(bitCount) { if(bitCount <= upShift) { *destPtr = sourceByte; return true; } *destPtr = sourceByte | ( (*++sourcePtr) << upShift); } return true; } bool BitStream::setBit(U32 bitCount, bool set) { if(bitCount >= maxWriteBitNum) if(!resizeBits(bitCount - maxWriteBitNum + 1)) return false; if(set) *(getBuffer() + (bitCount >> 3)) |= (1 << (bitCount & 0x7)); else *(getBuffer() + (bitCount >> 3)) &= ~(1 << (bitCount & 0x7)); return true; } bool BitStream::testBit(U32 bitCount) { return (*(getBuffer() + (bitCount >> 3)) & (1 << (bitCount & 0x7))) != 0; } bool BitStream::writeFlag(bool val) { if(bitNum + 1 > maxWriteBitNum) if(!resizeBits(1)) return false; if(val) *(getBuffer() + (bitNum >> 3)) |= (1 << (bitNum & 0x7)); else *(getBuffer() + (bitNum >> 3)) &= ~(1 << (bitNum & 0x7)); bitNum++; return (val); } bool BitStream::write(const ByteBuffer *theBuffer) { U32 size = theBuffer->getBufferSize(); if(size > 1023) return false; writeInt(size, 10); return write(size, theBuffer->getBuffer()); } bool BitStream::read(ByteBuffer *theBuffer) { U32 size = readInt(10); theBuffer->takeOwnership(); theBuffer->resize(size); return read(size, theBuffer->getBuffer()); } U32 BitStream::readInt(U8 bitCount) { U32 ret = 0; readBits(bitCount, &ret); ret = convertLEndianToHost(ret); // Clear bits that we didn't read. if(bitCount == 32) return ret; else ret &= (1 << bitCount) - 1; return ret; } void BitStream::writeInt(U32 val, U8 bitCount) { val = convertHostToLEndian(val); writeBits(bitCount, &val); } void BitStream::writeFloat(F32 f, U8 bitCount) { writeInt(U32(f * ((1 << bitCount) - 1)), bitCount); } F32 BitStream::readFloat(U8 bitCount) { return readInt(bitCount) / F32((1 << bitCount) - 1); } void BitStream::writeSignedFloat(F32 f, U8 bitCount) { writeSignedInt(S32(f * ((1 << (bitCount - 1)) - 1)), bitCount); } F32 BitStream::readSignedFloat(U8 bitCount) { return readSignedInt(bitCount) / F32((1 << (bitCount - 1)) - 1); } void BitStream::writeSignedInt(S32 value, U8 bitCount) { if(writeFlag(value < 0)) writeInt(-value, bitCount - 1); else writeInt(value, bitCount - 1); } S32 BitStream::readSignedInt(U8 bitCount) { if(readFlag()) return -(S32)readInt(bitCount - 1); else return (S32)readInt(bitCount - 1); } void BitStream::writeNormalVector(const Point3f& vec, U8 bitCount) { F32 phi = F32(atan2(vec.x, vec.y) * FloatInversePi ); F32 theta = F32(atan2(vec.z, sqrt(vec.x*vec.x + vec.y*vec.y)) * Float2InversePi); writeSignedFloat(phi, bitCount+1); writeSignedFloat(theta, bitCount); } void BitStream::readNormalVector(Point3f *vec, U8 bitCount) { F32 phi = readSignedFloat(bitCount+1) * FloatPi; F32 theta = readSignedFloat(bitCount) * FloatHalfPi; vec->x = sin(phi)*cos(theta); vec->y = cos(phi)*cos(theta); vec->z = sin(theta); } Point3f BitStream::dumbDownNormal(const Point3f& vec, U8 bitCount) { U8 buffer[128]; BitStream temp(buffer, 128); temp.writeNormalVector(vec, bitCount); temp.setBitPosition(0); Point3f ret; temp.readNormalVector(&ret, bitCount); return ret; } void BitStream::writeNormalVector(const Point3f& vec, U8 angleBitCount, U8 zBitCount) { // if this is a z up or down vector, just write out a couple of bits // if z is -1 or 1, x and y must both be 0 // FIXME: this should test if the vec.z is within zBitCount precision of 1 // BJG - fixed, but may be inefficient. Lookup table? if(writeFlag(fabs(vec.z) >= (1.0f-(1.0f/zBitCount)))) writeFlag(vec.z < 0); else { // write out the z value and the angle that x and y make around the z axis writeSignedFloat( vec.z, zBitCount ); writeSignedFloat( atan2(vec.x,vec.y) * FloatInverse2Pi, angleBitCount ); } } void BitStream::readNormalVector(Point3f * vec, U8 angleBitCount, U8 zBitCount) { if(readFlag()) { vec->z = readFlag() ? -1.0f : 1.0f; vec->x = 0; vec->y = 0; } else { vec->z = readSignedFloat(zBitCount); F32 angle = Float2Pi * readSignedFloat(angleBitCount); F32 mult = (F32) sqrt(1.0f - vec->z * vec->z); vec->x = mult * cos(angle); vec->y = mult * sin(angle); } } //---------------------------------------------------------------------------- void BitStream::clearPointCompression() { mCompressRelative = false; } void BitStream::setPointCompression(const Point3f& p) { mCompressRelative = true; mCompressPoint = p; } static U32 gBitCounts[4] = { 16, 18, 20, 32 }; void BitStream::writePointCompressed(const Point3f& p,F32 scale) { // Same # of bits for all axis Point3f vec; F32 invScale = 1 / scale; U32 type; if(mCompressRelative) { vec.x = p.x - mCompressPoint.x; vec.y = p.y - mCompressPoint.y; vec.z = p.z - mCompressPoint.z; F32 dist = (F32) sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z) * invScale; if(dist < (1 << 15)) type = 0; else if(dist < (1 << 17)) type = 1; else if(dist < (1 << 19)) type = 2; else type = 3; } else type = 3; writeInt(type, 2); if (type != 3) { type = gBitCounts[type]; writeSignedInt(S32(vec.x * invScale),type); writeSignedInt(S32(vec.y * invScale),type); writeSignedInt(S32(vec.z * invScale),type); } else { write(p.x); write(p.y); write(p.z); } } void BitStream::readPointCompressed(Point3f* p,F32 scale) { // Same # of bits for all axis U32 type = readInt(2); if(type == 3) { read(&p->x); read(&p->y); read(&p->z); } else { type = gBitCounts[type]; p->x = (F32) readSignedInt(type); p->y = (F32) readSignedInt(type); p->z = (F32) readSignedInt(type); p->x = mCompressPoint.x + p->x * scale; p->y = mCompressPoint.y + p->y * scale; p->z = mCompressPoint.z + p->z * scale; } } void BitStream::readString(char buf[256]) { if(readFlag()) { S32 offset = readInt(8); HuffmanStringProcessor::readHuffBuffer(this, mStringBuffer + offset); strcpy(buf, mStringBuffer); } else { HuffmanStringProcessor::readHuffBuffer(this, buf); strcpy(mStringBuffer, buf); } } void BitStream::writeString(const char *string, U8 maxLen) { if(!string) string = ""; U8 j; for(j = 0; j < maxLen && mStringBuffer[j] == string[j] && string[j];j++) ; strncpy(mStringBuffer + j, string + j, maxLen - j); mStringBuffer[maxLen] = 0; if(writeFlag(j > 2)) { writeInt(j, 8); HuffmanStringProcessor::writeHuffBuffer(this, string + j, maxLen - j); } else HuffmanStringProcessor::writeHuffBuffer(this, string, maxLen); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- //---------------------------------------------------------------------------- void BitStream::readStringTableEntry(StringTableEntry *ste) { if(mStringTable) *ste = mStringTable->readStringTableEntry(this); else { char buf[256]; readString(buf); ste->set(buf); } } void BitStream::writeStringTableEntry(const StringTableEntry &ste) { if(mStringTable) mStringTable->writeStringTableEntry(this, ste); else writeString(ste.getString()); } //------------------------------------------------------------------------------ void BitStream::hashAndEncrypt(U32 hashDigestSize, U32 encryptStartOffset, SymmetricCipher *theCipher) { U32 digestStart = getBytePosition(); setBytePosition(digestStart); hash_state hashState; U8 hash[32]; // do a sha256 hash of the BitStream: sha256_init(&hashState); sha256_process(&hashState, getBuffer(), digestStart); sha256_done(&hashState, hash); // write the hash into the BitStream: write(hashDigestSize, hash); theCipher->encrypt(getBuffer() + encryptStartOffset, getBuffer() + encryptStartOffset, getBytePosition() - encryptStartOffset); } bool BitStream::decryptAndCheckHash(U32 hashDigestSize, U32 decryptStartOffset, SymmetricCipher *theCipher) { U32 bufferSize = getBufferSize(); U8 *buffer = getBuffer(); if(bufferSize < decryptStartOffset + hashDigestSize) return false; theCipher->decrypt(buffer + decryptStartOffset, buffer + decryptStartOffset, bufferSize - decryptStartOffset); hash_state hashState; U8 hash[32]; sha256_init(&hashState); sha256_process(&hashState, buffer, bufferSize - hashDigestSize); sha256_done(&hashState, hash); bool ret = !memcmp(buffer + bufferSize - hashDigestSize, hash, hashDigestSize); if(ret) resize(bufferSize - hashDigestSize); return ret; } //------------------------------------------------------------------------------ NetError PacketStream::sendto(Socket &outgoingSocket, const Address &addr) { return outgoingSocket.sendto(addr, buffer, getBytePosition()); } NetError PacketStream::recvfrom(Socket &incomingSocket, Address *recvAddress) { NetError error; S32 dataSize; error = incomingSocket.recvfrom(recvAddress, buffer, sizeof(buffer), &dataSize); setBuffer(buffer, dataSize); setMaxSizes(dataSize, 0); reset(); return error; } }; <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pVehicleAll.h" #include "pWorldSettings.h" #include <stdlib.h> #include <exception> using namespace vtTools::AttributeTools; void pWorld::_construct() { //mAllocator = new UserAllocator; //mCManager = NxCreateControllerManager(mAllocator); compartment = NULL; } void pWorld::destroyCloth(CK_ID id) { pCloth*cloth = getCloth(id); if (cloth) { delete cloth; } } pCloth *pWorld::getCloth(CK_ID id) { int nbClothes = getScene()->getNbCloths(); NxCloth** clothes = getScene()->getCloths(); while(nbClothes--) { NxCloth* cloth = *clothes++; if(cloth->userData != NULL) { pCloth *vCloth = static_cast<pCloth*>(cloth->userData); if (vCloth) { if (id == vCloth->getEntityID() ) { return vCloth; } } } } return NULL; } pCloth *pWorld::getCloth(CK3dEntity*reference) { if (!reference) { return NULL; } int nbClothes = getScene()->getNbCloths(); NxCloth** clothes = getScene()->getCloths(); while(nbClothes--) { NxCloth* cloth = *clothes++; if(cloth->userData != NULL) { pCloth *vCloth = static_cast<pCloth*>(cloth->userData); if (vCloth) { if (reference->GetID() == vCloth->getEntityID() ) { return vCloth; } } } } return NULL; } void pWorld::updateClothes() { int nbClothes = getScene()->getNbCloths(); NxCloth** clothes = getScene()->getCloths(); while(nbClothes--) { NxCloth* cloth = *clothes++; if(cloth->userData != NULL) { pCloth *vCloth = static_cast<pCloth*>(cloth->userData); if (vCloth) { vCloth->updateVirtoolsMesh(); } } } } int pWorld::getNbBodies() { int result = 0; if (!getScene()) { return result; } result+= getScene()->getNbActors(); return result; } int pWorld::getNbJoints() { int result = 0; if (!getScene()) { return result; } result+= getScene()->getNbJoints(); return result; } NxShape *pWorld::getShapeByEntityID(CK_ID id) { if (!getScene() ) { return NULL; } CK3dEntity *entA = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(id)); if (!entA) { return NULL; } int nbActors = getScene()->getNbActors(); if (!nbActors) { return NULL; } NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body =static_cast<pRigidBody*>(actor->userData); if (body) { NxU32 nbShapes = body->getActor()->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)body->getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *info = static_cast<pSubMeshInfo*>(s->userData); if (info) { CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(info->entID)); if (ent == entA ) { return s; } } } } } } } } return NULL; } pRigidBody* pWorld::getBodyFromSubEntity(CK3dEntity *sub) { if (!getScene() ) { return NULL; } int nbActors = getScene()->getNbActors(); if (!nbActors) { return NULL; } NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body =static_cast<pRigidBody*>(actor->userData); if (body) { NxU32 nbShapes = body->getActor()->getNbShapes(); if ( nbShapes ) { NxShape ** slist = (NxShape **)body->getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *info = static_cast<pSubMeshInfo*>(s->userData); if (info) { CK3dEntity *ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(info->entID)); if (ent) { if (sub == ent) { return body; } } } } } } } } } return NULL; } void pWorld::checkList() { if (!getScene() ) { return; } int nbActors = getScene()->getNbActors(); if (!nbActors) { return; } NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body = (pRigidBody*)actor->userData; if (body) { CK3dEntity * ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(body->getEntID())); if (!ent) { deleteBody(body); } } } } int nbClothes = getScene()->getNbCloths(); NxCloth** clothes = getScene()->getCloths(); while(nbClothes--) { NxCloth* cloth = *clothes++; if(cloth->userData != NULL) { pCloth *vCloth = static_cast<pCloth*>(cloth->userData); if (vCloth) { CK3dEntity * ent = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(vCloth->getEntityID())); if (!ent) { destroyCloth(vCloth->getEntityID()); } } } } } void pWorld::deleteBody(pRigidBody*body) { if(!body) return; CK_ID id = body->getEntID(); CK3dEntity *ent = (CK3dEntity*)GetPMan()->GetContext()->GetObject(id); if(!ent) return; GetPMan()->getRemovalList().PushBack(id); return; if (body) { body->destroy(); if (body->getWorld() && body->getWorld()->getScene() ) { for (int i = 0 ; i < body->getWorld()->getJointFeedbackList().Size(); i++ ) { pBrokenJointEntry *entry = *body->getWorld()->getJointFeedbackList().At(i); if (entry && entry->joint) { } } } SAFE_DELETE(body); } checkList(); } void pWorld::deleteJoint(pJoint*joint) { if (!joint) { return; } pWorld *world = joint->getWorld(); if (world && world->getScene() ) { for (int i = 0 ; i < GetPMan()->getJointFeedbackList().Size(); i++ ) { pBrokenJointEntry *entry = *world->getJointFeedbackList().At(i); if (entry && entry->joint == joint) { GetPMan()->getJointFeedbackList().EraseAt(i); break; } } joint->getJoint()->userData = NULL; world->getScene()->releaseJoint(*joint->getJoint()); delete joint; } } pJoint* pWorld::getJoint(CK3dEntity *_a, CK3dEntity *_b, JType type) { if (!getScene()) { return NULL; } pRigidBody *a = GetPMan()->getBody(_a); pRigidBody *b = GetPMan()->getBody(_b); //bodies have already a joint together ? if ( !a && !b) { return NULL; } if ( a == b) { return NULL; } if (a && !a->isValid() ) { return NULL; } if (a && !GetPMan()->getWorldByBody(_a)) { return NULL; } if (b && !GetPMan()->getWorldByBody(_b) ) { return NULL; } if (b && !b->isValid()) { return NULL; } if ( a && b ) { pWorld*worldA = GetPMan()->getWorldByBody(_a); pWorld*worldB = GetPMan()->getWorldByBody(_b); if (!worldA || !worldB || (worldA!=worldB) || !worldA->isValid() || !worldB->isValid() ) { return NULL; } } NxU32 jointCount = getScene()->getNbJoints(); if (jointCount) { NxArray< NxJoint * > joints; getScene()->resetJointIterator(); for (NxU32 i = 0; i < jointCount; ++i) { NxJoint *j = getScene()->getNextJoint(); if (type == JT_Any) { pJoint *mJoint = static_cast<pJoint*>( j->userData ); if ( mJoint ) { if (mJoint->GetVTEntA() == _a && mJoint->GetVTEntB() == _b ) { return mJoint; } CK3dEntity *inA = _b; CK3dEntity *inB = _a; if (mJoint->GetVTEntA() == inA && mJoint->GetVTEntB() == inB ) { return mJoint; } } } if ( j->getType() == type) { pJoint *mJoint = static_cast<pJoint*>( j->userData ); if ( mJoint ) { if (mJoint->GetVTEntA() == _a && mJoint->GetVTEntB() == _b ) { return mJoint; } CK3dEntity *inA = _b; CK3dEntity *inB = _a; if (mJoint->GetVTEntA() == inA && mJoint->GetVTEntB() == inB ) { return mJoint; } } } } } return NULL; } bool pWorld::isValid() { return getScene() ? true : false; } pRigidBody*pWorld::getBody(CK3dEntity*ent) { pRigidBody *result = NULL; if (!ent || !getScene() ) { return NULL; } int nbActors = getScene()->getNbActors(); NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body = (pRigidBody*)actor->userData; if (body && body->getEntID() == ent->GetID() ) { return body; } if (body && body->isSubShape(ent) ) { return body; } } } return NULL; } pWorld::pWorld(CK3dEntity* _o) { m_bCompletedLastFrame =true; m_fTimeSinceLastCallToSimulate = 0.0f; m_SleepingSettings = NULL; m_worldSettings =NULL; m_vtReference = _o; mScene = NULL; contactReport = NULL; triggerReport = NULL; contactModify = NULL; callMask = XCM_PreProcess | XCM_PostProcess; overrideMask = 0 ; compartment = NULL; } pWorld::~pWorld() { //m_worldSettings = NULL; //m_SleepingSettings =NULL; mScene = NULL; //m_vtReference =NULL; } void pWorld::destroy() { if (getScene()) { getScene()->setClothUserNotify(NULL); getScene()->setUserTriggerReport(NULL); getScene()->setUserContactModify(NULL); getScene()->setUserActorPairFiltering(NULL); getScene()->setUserContactReport(NULL); getScene()->setUserNotify(NULL); SAFE_DELETE(contactReport); SAFE_DELETE(triggerReport); SAFE_DELETE(raycastReport); SAFE_DELETE(contactModify); if(mDefaultMaterial) getScene()->releaseMaterial(*mDefaultMaterial); if(compartment) { //getScene()->re } //SAFE_DELETE() int nbActors = getScene()->getNbActors(); if (!nbActors)return; NxActor** actors = getScene()->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData != NULL) { pRigidBody* body = (pRigidBody*)actor->userData; if (body) { //body->getActor()->getCompartment()-> body->destroy(); if (body->GetVT3DObject()) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Body destroyed :"); } SAFE_DELETE(body); } } } } if (GetPMan()->getPhysicsSDK()) { GetPMan()->getPhysicsSDK()->releaseScene(*mScene); mScene = NULL; } if (m_SleepingSettings) { delete m_SleepingSettings; m_SleepingSettings = NULL; } if (m_worldSettings) { delete m_worldSettings; m_worldSettings = NULL; } } int pWorld::UpdateProperties(DWORD mode,DWORD flags){ return 0;} VxVector pWorld::getGravity() { NxVec3 grav; getScene()->getGravity(grav); return getFrom(grav); } void pWorld::setGravity(VxVector gravity) { getScene()->setGravity(getFrom(gravity)); } <file_sep>#ifndef __P_FLUID_FLAGS_ #define __P_FLUID_FLAGS_ /** \addtogroup Fluid @{ */ /** \brief Fluid flags */ enum pFluidFlag { /** \brief Enables debug visualization for the NxFluid. */ PFF_VISUALIZATION = (1<<0), /** \brief Disables scene gravity for the NxFluid. */ PFF_DisableGravity = (1<<1), /** \brief Enable/disable two way collision of fluid with the rigid body scene. In either case, fluid is influenced by colliding rigid bodies. If PFF_CollisionTwoway is not set, rigid bodies are not influenced by colliding pieces of fluid. Use pFluidDesc.collisionResponseCoefficient to control the strength of the feedback force on rigid bodies. @see NxFluidDesc.collisionResponseCoefficient */ PFF_CollisionTwoway = (1<<2), /** \brief Enable/disable execution of fluid simulation. */ PFF_Enabled = (1<<3), /** \brief Defines whether this fluid is simulated on the PPU. */ PFF_Hardware = (1<<4), /** \brief Enable/disable particle priority mode. If enabled, the oldest particles are deleted to keep a certain budget for new particles. Note that particles which have equal lifetime can get deleted at the same time. In order to avoid this, the particle lifetimes can be varied randomly. @see pFluidDesc.numReserveParticles */ PFF_PriorityMode = (1<<5), /** \brief Defines whether the particles of this fluid should be projected to a plane. This can be used to build 2D fluid applications, for instance. The projection plane is defined by the parameter pFluidDesc.projectionPlane. @see pFluidDesc.projectionPlane */ PFF_ProjectToPlane = (1<<6), /** \brief Forces fluid static mesh cooking format to parameters given by the fluid descriptor. Currently not implemented! */ PFF_ForceStrictCookingFormat = (1<<7), }; /** \brief Describes the particle simulation method Particles can be treated in two ways: either they are simulated considering interparticular forces (SPH), or they are simulated independently. In the latter case (with the simulation method set to PFS_NO_PARTICLE_INTERACTION), you still get collision between particles and static/dynamic shapes, damping, acceleration due to gravity, and the user force. */ enum pFluidSimulationMethod { /** \brief Enable simulation of inter particle forces. */ PFS_SPH = (1<<0), /** \brief Do not simulate inter particle forces. */ PFS_NoParticleInteraction = (1<<1), /** \brief Alternate between SPH and simple particles */ PFS_MixedMode = (1<<2), }; /** \brief The fluid collision method */ enum pFluidCollisionMethod { /** \brief collide with static objects */ PFCM_Static = (1<<0), /** \brief collide with dynamic objects */ PFCM_Dynamic = (1<<1), }; /** @} */ #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBSetHardDecl(); CKERROR CreatePBSetHardProto(CKBehaviorPrototype **pproto); int PBSetHard(const CKBehaviorContext& behcontext); CKERROR PBSetHardCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_Vel, bbI_AVel, bbI_Momentum, bbI_Torque, bbI_Pos, bbI_Rotation, }; #define BB_SSTART 0 BBParameter pInMap23[] = { BB_SPIN(bbI_Vel,CKPGUID_VECTOR,"Linear Velocity",""), BB_SPIN(bbI_AVel,CKPGUID_VECTOR,"Angular Velocity",""), BB_SPIN(bbI_Momentum,CKPGUID_VECTOR,"Linear Momentum",""), BB_SPIN(bbI_Torque,CKPGUID_VECTOR,"Angualar Momentum",""), BB_SPIN(bbI_Pos,CKPGUID_VECTOR,"Position",""), BB_SPIN(bbI_Rotation,CKPGUID_QUATERNION,"Rotation",""), }; #define gPIMAP pInMap23 //************************************ // Method: FillBehaviorPBSetHardDecl // FullName: FillBehaviorPBSetHardDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPBSetHardDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetHard"); od->SetCategory("Physic/Body"); od->SetDescription("Sets momentum,velocities and transformations."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x528d58e0,0x2fca203a)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBSetHardProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBSetHardProto // FullName: CreatePBSetHardProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBSetHardProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetHard"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PBSetHard PBSet is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies various physical parameters.<br> <h3>Technical Information</h3> \image html PBSetHard.png <SPAN CLASS="in">In:</SPAN>triggers the process <BR> <SPAN CLASS="out">Out:</SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated with the rigid body or its sub shape. <BR> <BR> <SPAN CLASS="pin">Linear Velocity: </SPAN>The linear velocity.See pRigidBody::setLinearVelocity(). <BR> <SPAN CLASS="pin">Angular Velocity: </SPAN>The angular velocity.See pRigidBody::setAngularVelocity(). <BR> <SPAN CLASS="pin">Agular Momentum: </SPAN>The angular momentum.See pRigidBody::getAngularMomentum(). <BR> <SPAN CLASS="pin">Linear Momentum: </SPAN>The linear momentum.See pRigidBody::getLinearMomentum(). <BR> <SPAN CLASS="pin">Position: </SPAN>The position.See pRigidBody::setPosition(). <BR> <SPAN CLASS="pin">Orientation: </SPAN>The new rotation.See pRigidBody::setRotation(). <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager . <br> <br> <SPAN CLASS="framedWhite"> The known building block <A HREF="Documentation.chm::/behaviors/3D%20Transformations/Set%20Position.html">"Set Position"</A> has new settings avaiable. Enable there "Update Physics" in order to transfer the new position on the body automatically! </SPAN> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBSet.cpp </SPAN> */ proto->SetBehaviorCallbackFct( PBSetHardCB ); BB_EVALUATE_SETTINGS(gPIMAP) proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBSetHard); *pproto = proto; return CK_OK; } //************************************ // Method: PBSetHard // FullName: PBSetHard // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBSetHard(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) { if (!body) bbErrorME("No valid world object found"); } body = GetPMan()->getBody(target); if (!body) bbErrorME("No Reference Object specified"); BB_DECLARE_PIMAP; /************************************************************************/ /* retrieve settings state */ /************************************************************************/ BBSParameter(bbI_Vel); BBSParameter(bbI_AVel); BBSParameter(bbI_Torque); BBSParameter(bbI_Momentum); BBSParameter(bbI_Pos); BBSParameter(bbI_Rotation); if (sbbI_Vel) { VxVector velocity= GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(bbI_Vel)); body->setLinearVelocity(velocity); } if (sbbI_AVel) { VxVector aVelocity= GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(bbI_AVel)); body->setAngularVelocity(aVelocity); } if (sbbI_Torque) { VxVector torque= GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(bbI_Torque)); body->setAngularMomentum(torque); } if (sbbI_Momentum) { VxVector momentum= GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(bbI_Momentum)); body->setLinearMomentum(momentum); } if (sbbI_Pos) { VxVector pos= GetInputParameterValue<VxVector>(beh,BB_IP_INDEX(bbI_Pos)); body->setPosition(pos,target); } if (sbbI_Rotation) { VxQuaternion rot= GetInputParameterValue<VxQuaternion>(beh,BB_IP_INDEX(bbI_Rotation)); body->setRotation(rot,target); } } beh->ActivateOutput(0); return 0; } //************************************ // Method: PBSetHardCB // FullName: PBSetHardCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBSetHardCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; } <file_sep>#ifndef __xDistributedPoint1F_H #define __xDistributedPoint1F_H #include "xDistributedProperty.h" class xDistributedPoint1F : public xDistributedProperty { public: typedef xDistributedProperty Parent; xDistributedPoint1F ( xDistributedPropertyInfo *propInfo, xTimeType maxWriteInterval, xTimeType maxHistoryTime ) : xDistributedProperty(propInfo) { mLastValue = 0.0f; mCurrentValue= 0.0f; mDifference = 0.0f; mLastTime = 0; mCurrentTime = 0; mLastDeltaTime = 0 ; mFlags = 0; mThresoldTicker = 0; } ~xDistributedPoint1F(){} TNL::F32 mLastValue; TNL::F32 mCurrentValue; TNL::F32 mDifference; TNL::F32 mLastServerValue; TNL::F32 mLastServerDifference; bool updateValue(TNL::F32 value,xTimeType currentTime); TNL::F32 getDiff(TNL::F32 value); void pack(TNL::BitStream *bstream); void unpack(TNL::BitStream *bstream,float sendersOneWayTime); void updateGhostValue(TNL::BitStream *stream); void updateFromServer(TNL::BitStream *stream); virtual uxString print(TNL::BitSet32 flags); }; #endif <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Generic Camera Orbit // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "GeneralCameraOrbit.h" CKObjectDeclaration *FillBehaviorGenericCameraOrbitDecl(); CKERROR CreateGenericCameraOrbitProto(CKBehaviorPrototype **pproto); int GenericCameraOrbit(const CKBehaviorContext& behcontext); void ProcessGenericInputs(VxVector* RotationAngles, CKBehavior* beh, CKInputManager *input, float delta, CKBOOL &Returns, CKBOOL &stopping); CKObjectDeclaration *FillBehaviorGenericCameraOrbitDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Generic Camera Orbit"); od->SetDescription("Makes a Camera orbit round a 3D Entity using input activation."); od->SetCategory("Cameras/Movement"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x104d0913,0x766563dd)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGenericCameraOrbitProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(INPUT_MANAGER_GUID); return od; } ////////////////////////////////////////////////////////////////////////////// // // Prototype creation // ////////////////////////////////////////////////////////////////////////////// CKERROR CreateGenericCameraOrbitProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Generic Camera Orbit"); if(!proto) return CKERR_OUTOFMEMORY; // General Description CKERROR error = FillGeneralCameraOrbitProto(proto); if (error != CK_OK) return (error); // Additionnal Inputs proto->DeclareInput("Move Left"); proto->DeclareInput("Move Right"); proto->DeclareInput("Move Up"); proto->DeclareInput("Move Down"); proto->DeclareInput("Zoom In"); proto->DeclareInput("Zoom Out"); // Additionnal Local proto->DeclareLocalParameter("Returning",CKPGUID_BOOL,"FALSE"); // Set the execution functions proto->SetFunction(GenericCameraOrbit); proto->SetBehaviorCallbackFct(GeneralCameraOrbitCallback,CKCB_BEHAVIORSETTINGSEDITED|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORCREATE); // return OK *pproto = proto; return CK_OK; } ////////////////////////////////////////////////////////////////////////////// // // Main Function // ////////////////////////////////////////////////////////////////////////////// int GenericCameraOrbit(const CKBehaviorContext& behcontext) { return ( GeneralCameraOrbit(behcontext,ProcessGenericInputs) ); } ////////////////////////////////////////////////////////////////////////////// // // Function that process the inputs // ////////////////////////////////////////////////////////////////////////////// void ProcessGenericInputs(VxVector* RotationAngles, CKBehavior* beh, CKInputManager *input, float delta, CKBOOL &Returns, CKBOOL &stopping) { // Is the move limited ? CKBOOL Limited = TRUE; beh->GetLocalParameterValue(LOCAL_LIMITS,&Limited); // In the behavioral engine, when the BB return CKBR_ACTIVATENEXTFRAME, and // is also called by another BB, it may happpen that it is called two times. // We could use priorities to avoid this problem, but we implement a more // automatic solution with this parameter. // The return will therefore happen after at least one frame without action. CKBOOL Returning = FALSE; beh->GetLocalParameterValue(LOCAL_RETURNING,&Returning); //////////////////// // Position Update //////////////////// // If the users is moving the camera if ( (beh->IsInputActive(INPUT_LEFT) || beh->IsInputActive(INPUT_RIGHT) || beh->IsInputActive(INPUT_UP) || beh->IsInputActive(INPUT_DOWN)) && !stopping) { // Not Returning if ( Returning ) { Returning = FALSE; beh->SetLocalParameterValue(LOCAL_RETURNING,&Returning); } // Get current time dependent speed angle. float SpeedAngle = 0.87f; beh->GetInputParameterValue(IN_SPEED_MOVE,&SpeedAngle); SpeedAngle *= delta / 1000; if (Limited) { float MinH = -PI/2; beh->GetInputParameterValue(IN_MIN_H, &MinH); float MaxH = PI/2; beh->GetInputParameterValue(IN_MAX_H, &MaxH); float MinV = -PI/2; beh->GetInputParameterValue(IN_MIN_V, &MinV); float MaxV = PI/2; beh->GetInputParameterValue(IN_MAX_V, &MaxV); if ( beh->IsInputActive(INPUT_LEFT) ) RotationAngles->x += XMin(SpeedAngle, MaxH - RotationAngles->x); if ( beh->IsInputActive(INPUT_RIGHT)) RotationAngles->x -= XMin(SpeedAngle, RotationAngles->x - MinH); if ( beh->IsInputActive(INPUT_UP) ) RotationAngles->y += XMin(SpeedAngle, MaxV - RotationAngles->y); if ( beh->IsInputActive(INPUT_DOWN) ) RotationAngles->y -= XMin(SpeedAngle, RotationAngles->y - MinV); } else { if( beh->IsInputActive(INPUT_LEFT) ) RotationAngles->x += SpeedAngle; if( beh->IsInputActive(INPUT_RIGHT) ) RotationAngles->x -= SpeedAngle; if( beh->IsInputActive(INPUT_UP) ) RotationAngles->y += SpeedAngle; if( beh->IsInputActive(INPUT_DOWN) ) RotationAngles->y -= SpeedAngle; } // Deactivates Inputs beh->ActivateInput(INPUT_LEFT,FALSE); beh->ActivateInput(INPUT_RIGHT,FALSE); beh->ActivateInput(INPUT_UP,FALSE); beh->ActivateInput(INPUT_DOWN,FALSE); } else if (Returns && ((RotationAngles->x != 0) || (RotationAngles->y != 0))) { if ( !Returning ) { Returning = TRUE; beh->SetLocalParameterValue(LOCAL_RETURNING,&Returning); return; } float ReturnSpeedAngle = 1.75f; beh->GetInputParameterValue(IN_SPEED_RETURN, &ReturnSpeedAngle); ReturnSpeedAngle *= delta / 1000; if( RotationAngles->x < 0 ) RotationAngles->x += XMin(ReturnSpeedAngle, -RotationAngles->x); if( RotationAngles->x > 0 ) RotationAngles->x -= XMin(ReturnSpeedAngle, RotationAngles->x); if( RotationAngles->y < 0 ) RotationAngles->y += XMin(ReturnSpeedAngle, -RotationAngles->y); if( RotationAngles->y > 0 ) RotationAngles->y -= XMin(ReturnSpeedAngle, RotationAngles->y); } // We are stopping and already stopped ! else if (stopping) RotationAngles->x = INF; //////////////// // Zoom Update //////////////// if ( (beh->IsInputActive(INPUT_ZOOMIN) || beh->IsInputActive(INPUT_ZOOMOUT)) && !stopping) { float ZoomSpeed = 40.0f; beh->GetInputParameterValue(IN_SPEED_ZOOM,&ZoomSpeed); ZoomSpeed *= delta / 1000; if (Limited) { float MinZoom = -40.0f; beh->GetInputParameterValue(IN_MIN_ZOOM, &MinZoom); float MaxZoom = 10.0f; beh->GetInputParameterValue(IN_MAX_ZOOM, &MaxZoom); if( beh->IsInputActive(INPUT_ZOOMIN) ) RotationAngles->z -= XMin(ZoomSpeed, RotationAngles->z + MaxZoom ); if( beh->IsInputActive(INPUT_ZOOMOUT) ) RotationAngles->z += XMin(ZoomSpeed, - MinZoom - RotationAngles->z); } else { if( beh->IsInputActive(INPUT_ZOOMIN) ) RotationAngles->z -= ZoomSpeed; if( beh->IsInputActive(INPUT_ZOOMOUT) ) RotationAngles->z += ZoomSpeed; } // Deactivates Inputs beh->ActivateInput(INPUT_ZOOMIN,FALSE); beh->ActivateInput(INPUT_ZOOMOUT,FALSE); } } <file_sep>/* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * lua.cxx * * Lua language module for SWIG. * ----------------------------------------------------------------------------- */ /* NEW LANGUAGE NOTE: * ver001 this is simply a copy of tcl8.cxx, which has been renamed * ver002 all non essential code commented out, program now does virtually nothing it prints to stderr the list of functions to wrap, but does not create the XXX_wrap.c file * ver003 added back top(), still prints the list of fns to stderr but now creates a rather empty XXX_wrap.c with some basic boilerplate code * ver004 very basic version of functionWrapper() also uncommented usage_string() to keep compiler happy this will start producing proper looking code soon (I hope) produced the wrapper code, but without any type conversion (in or out) generates a few warning because of no wrappering does not generate SWIG_init() reason for this is that lua.swg is empty we will need to add code into this to make it work * ver005/6 massive rework, basing work on the pike module instead of tcl (pike module it only 1/3 of the size)(though not as complete) * ver007 added simple type checking * ver008 INPUT, OUTPUT, INOUT typemaps handled (though not all types yet) * ver009 class support: ok for basic types, but methods still TDB (code is VERY messed up & needs to be cleaned) */ char cvsroot_lua_cxx[] = "$Id: lua.cxx 10076 2007-10-30 06:10:04Z mgossage $"; #include "swigmod.h" /**** Diagnostics: With the #define REPORT(), you can change the amount of diagnostics given This helps me search the parse tree & figure out what is going on inside SWIG (because its not clear or documented) */ #define REPORT(T,D) // no info: //#define REPORT(T,D) {Printf(stdout,T"\n");} // only title //#define REPORT(T,D) {Printf(stdout,T"\n");display_mapping(D);} // the works //#define REPORT(T,D) {Printf(stdout,T"\n");if(D)Swig_print_node(D);} // the works void display_mapping(DOH *d) { if (d == 0 || !DohIsMapping(d)) return; for (DohIterator it = DohFirst(d); it.item; it = DohNext(it)) { if (DohIsString(it.item)) Printf(stdout, " %s = %s\n", it.key, it.item); else if (DohIsMapping(it.item)) Printf(stdout, " %s = <mapping>\n", it.key); else if (DohIsSequence(it.item)) Printf(stdout, " %s = <sequence>\n", it.key); else Printf(stdout, " %s = <unknown>\n", it.key); } } /* NEW LANGUAGE NOTE:*********************************************** most of the default options are handled by SWIG you can add new ones here (though for now I have not bothered) NEW LANGUAGE NOTE:END ************************************************/ static const char *usage = (char *) "\ Lua Options (available with -lua)\n\ (coming soon.)\n\n"; /* NEW LANGUAGE NOTE:*********************************************** To add a new language, you need to derive your class from Language and the overload various virtual functions (more on this as I figure it out) NEW LANGUAGE NOTE:END ************************************************/ class LUA:public Language { private: File *f_runtime; File *f_header; File *f_wrappers; File *f_init; File *f_initbeforefunc; String *PrefixPlusUnderscore; String *s_cmd_tab; // table of command names String *s_var_tab; // table of global variables String *s_const_tab; // table of global constants String *s_methods_tab; // table of class methods String *s_attr_tab; // table of class atributes int have_constructor; int have_destructor; String *destructor_action; String *class_name; String *constructor_name; enum { NO_CPP, VARIABLE, MEMBER_FUNC, CONSTRUCTOR, DESTRUCTOR, MEMBER_VAR, CLASS_CONST, STATIC_FUNC, STATIC_VAR }current; public: /* --------------------------------------------------------------------- * LUA() * * Initialize member data * --------------------------------------------------------------------- */ LUA() { f_runtime = 0; f_header = 0; f_wrappers = 0; f_init = 0; f_initbeforefunc = 0; PrefixPlusUnderscore = 0; s_cmd_tab = s_var_tab = s_const_tab = 0; current=NO_CPP; } /* NEW LANGUAGE NOTE:*********************************************** This is called to initalise the system & read any command line args most of this is boilerplate code, except the command line args which depends upon what args your code supports NEW LANGUAGE NOTE:END ************************************************/ /* --------------------------------------------------------------------- * main() * * Parse command line options and initializes variables. * --------------------------------------------------------------------- */ virtual void main(int argc, char *argv[]) { /* Set location of SWIG library */ SWIG_library_directory("lua"); /* Look for certain command line options */ for (int i = 1; i < argc; i++) { if (argv[i]) { if (strcmp(argv[i], "-help") == 0) { // usage flags fputs(usage, stderr); } } } /* NEW LANGUAGE NOTE:*********************************************** This is the boilerplate code, setting a few #defines and which lib directory to use the SWIG_library_directory() is also boilerplate code but it always seems to be the first line of code NEW LANGUAGE NOTE:END ************************************************/ /* Add a symbol to the parser for conditional compilation */ Preprocessor_define("SWIGLUA 1", 0); /* Set language-specific configuration file */ SWIG_config_file("lua.swg"); /* Set typemap language */ SWIG_typemap_lang("lua"); /* Enable overloaded methods support */ allow_overloading(); } /* NEW LANGUAGE NOTE:*********************************************** After calling main, SWIG parses the code to wrap (I believe) then calls top() in this is more boilerplate code to set everything up and a call to Language::top() which begins the code generations by calling the member fns after all that is more boilerplate code to close all down (overall there is virtually nothing here that needs to be edited just use as is) NEW LANGUAGE NOTE:END ************************************************/ /* --------------------------------------------------------------------- * top() * --------------------------------------------------------------------- */ virtual int top(Node *n) { /* Get the module name */ String *module = Getattr(n, "name"); /* Get the output file name */ String *outfile = Getattr(n, "outfile"); /* Open the output file */ f_runtime = NewFile(outfile, "w"); if (!f_runtime) { FileErrorDisplay(outfile); SWIG_exit(EXIT_FAILURE); } f_init = NewString(""); f_header = NewString(""); f_wrappers = NewString(""); f_initbeforefunc = NewString(""); /* Register file targets with the SWIG file handler */ Swig_register_filebyname("header", f_header); Swig_register_filebyname("wrapper", f_wrappers); Swig_register_filebyname("runtime", f_runtime); Swig_register_filebyname("init", f_init); Swig_register_filebyname("initbeforefunc", f_initbeforefunc); /* NEW LANGUAGE NOTE:*********************************************** s_cmd_tab,s_var_tab & s_const_tab hold the names of the fns for registering with SWIG. These will be filled in when the functions/variables are wrapped & then added to the end of the wrappering code just before it is written to file NEW LANGUAGE NOTE:END ************************************************/ // Initialize some variables for the object interface s_cmd_tab = NewString(""); s_var_tab = NewString(""); // s_methods_tab = NewString(""); s_const_tab = NewString(""); current=NO_CPP; /* Standard stuff for the SWIG runtime section */ Swig_banner(f_runtime); // if (NoInclude) { // Printf(f_runtime, "#define SWIG_NOINCLUDE\n"); // } //String *init_name = NewStringf("%(title)s_Init", module); //Printf(f_header, "#define SWIG_init %s\n", init_name); //Printf(f_header, "#define SWIG_name \"%s\"\n", module); /* SWIG_import is a special function name for importing within Lua5.1 */ //Printf(f_header, "#define SWIG_import luaopen_%s\n\n", module); Printf(f_header, "#define SWIG_name \"%s\"\n", module); Printf(f_header, "#define SWIG_init luaopen_%s\n", module); Printf(f_header, "#define SWIG_init_user luaopen_%s_user\n\n", module); Printf(s_cmd_tab, "\nstatic const struct luaL_reg swig_commands[] = {\n"); Printf(s_var_tab, "\nstatic swig_lua_var_info swig_variables[] = {\n"); Printf(s_const_tab, "\nstatic swig_lua_const_info swig_constants[] = {\n"); Printf(f_wrappers, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); /* %init code inclusion, effectively in the SWIG_init function */ Printf(f_init, "void SWIG_init_user(lua_State* L)\n{\n"); Language::top(n); Printf(f_init, "}\n"); Printf(f_wrappers, "#ifdef __cplusplus\n}\n#endif\n"); // Done. Close up the module & write to the wrappers Printv(s_cmd_tab, tab4, "{0,0}\n", "};\n", NIL); Printv(s_var_tab, tab4, "{0,0,0}\n", "};\n", NIL); Printv(s_const_tab, tab4, "{0,0,0,0,0,0}\n", "};\n", NIL); Printv(f_wrappers, s_cmd_tab, s_var_tab, s_const_tab, NIL); SwigType_emit_type_table(f_runtime, f_wrappers); /* NEW LANGUAGE NOTE:*********************************************** this basically combines several of the strings together and then writes it all to a file NEW LANGUAGE NOTE:END ************************************************/ /* Close all of the files */ Delete(s_cmd_tab); Delete(s_var_tab); Delete(s_const_tab); Dump(f_header, f_runtime); Dump(f_wrappers, f_runtime); Dump(f_initbeforefunc, f_runtime); Wrapper_pretty_print(f_init, f_runtime); Delete(f_header); Delete(f_wrappers); Delete(f_init); Delete(f_initbeforefunc); Close(f_runtime); Delete(f_runtime); /* Done */ return SWIG_OK; } /* ------------------------------------------------------------ * importDirective() * ------------------------------------------------------------ */ virtual int importDirective(Node *n) { return Language::importDirective(n); } /* NEW LANGUAGE NOTE:*********************************************** This is it! you get this one right, and most of your work is done but its going to take soem file to get it working right quite a bit of this is generally boilerplate code (or stuff I dont understand) that which matters will have extra added comments NEW LANGUAGE NOTE:END ************************************************/ /* --------------------------------------------------------------------- * functionWrapper() * * Create a function declaration and register it with the interpreter. * --------------------------------------------------------------------- */ virtual int functionWrapper(Node *n) { // REPORT("functionWrapper",n); String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); SwigType *d = Getattr(n, "type"); ParmList *l = Getattr(n, "parms"); //Printf(stdout,"functionWrapper %s %s\n",name,iname); Parm *p; String *tm; int i; //Printf(stdout,"functionWrapper %s %s %d\n",name,iname,current); // int returnval=0; // number of arguments returned String *overname = 0; if (Getattr(n, "sym:overloaded")) { overname = Getattr(n, "sym:overname"); } else { if (!addSymbol(iname, n)) { Printf(stderr,"addSymbol(%s) failed\n",iname); return SWIG_ERROR; } } /* NEW LANGUAGE NOTE:*********************************************** the wrapper object holds all the wrappering code we need to add a couple of local variables NEW LANGUAGE NOTE:END ************************************************/ Wrapper *f = NewWrapper(); Wrapper_add_local(f, "SWIG_arg", "int SWIG_arg = -1"); String *wname = Swig_name_wrapper(iname); if (overname) { Append(wname, overname); } /* NEW LANGUAGE NOTE:*********************************************** the format of a lua fn is: static int wrap_XXX(lua_State* L){...} this line adds this into the wrappering code NEW LANGUAGE NOTE:END ************************************************/ Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL); /* NEW LANGUAGE NOTE:*********************************************** this prints the list of args, eg for a C fn int gcd(int x,int y); it will print int arg1; int arg2; int result; NEW LANGUAGE NOTE:END ************************************************/ /* Write code to extract function parameters. */ emit_args(d, l, f); /* Attach the standard typemaps */ emit_attach_parmmaps(l, f); Setattr(n, "wrap:parms", l); /* Get number of required and total arguments */ int num_arguments = emit_num_arguments(l); int num_required = emit_num_required(l); int varargs = emit_isvarargs(l); /* Which input argument to start with? */ // int start = (current == MEMBER_FUNC || current == MEMBER_VAR || current == DESTRUCTOR) ? 1 : 0; /* Offset to skip over the attribute name */ // int offset = (current == MEMBER_VAR) ? 1 : 0; /* NEW LANGUAGE NOTE:*********************************************** from here on in, it gets rather hairy this is the code to convert from the scripting language to C/C++ some of the stuff will refer to the typemaps code written in your swig file (lua.swg), and some is done in the code here I suppose you could do all the conversion on C, but it would be a nightmare to do NEW LANGUAGE NOTE:END ************************************************/ /* Generate code for argument marshalling */ // String *description = NewString(""); /* NEW LANGUAGE NOTE:*********************************************** argument_check is a new feature I added to check types of arguments: eg for int gcd(int,int) I want to check that arg1 & arg2 really are integers NEW LANGUAGE NOTE:END ************************************************/ String *argument_check = NewString(""); String *argument_parse = NewString(""); String *checkfn = NULL; // String *numoutputs=NULL; char source[64]; //Printf(argument_check, "//args must be %d..%d\n",num_required,num_arguments); Printf(argument_check, "SWIG_check_num_args(\"%s\",%d,%d)\n",name,num_required,num_arguments); for (i = 0, p = l; i < num_arguments; i++) { while (checkAttribute(p, "tmap:in:numinputs", "0")) { p = Getattr(p, "tmap:in:next"); } SwigType *pt = Getattr(p, "type"); String *ln = Getattr(p, "lname"); /* Look for an input typemap */ sprintf(source, "%d", i + 1); if ((tm = Getattr(p, "tmap:in"))) { Replaceall(tm, "$source", source); Replaceall(tm, "$target", ln); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); /* NEW LANGUAGE NOTE:*********************************************** look for a 'checkfn' typemap this an additional parameter added to the in typemap if found the type will be tested for this will result in code either in the argument_check or argument_parse string NEW LANGUAGE NOTE:END ************************************************/ if ((checkfn = Getattr(p, "tmap:in:checkfn"))) { if (i < num_required) { Printf(argument_check, "if(!%s(L,%s))", checkfn, source); } else { Printf(argument_check, "if(lua_gettop(L)>=%s && !%s(L,%s))", source, checkfn, source); } Printf(argument_check, " SWIG_fail_arg(\"%s\",%s,\"%s\");\n", name, source, SwigType_str(pt, 0)); } /* NEW LANGUAGE NOTE:*********************************************** lua states the number of arguments passed to a function using the fn lua_gettop() we can use this to deal with default arguments NEW LANGUAGE NOTE:END ************************************************/ if (i < num_required) { Printf(argument_parse, "%s\n", tm); } else { Printf(argument_parse, "if(lua_gettop(L)>=%s){%s}\n", source, tm); } p = Getattr(p, "tmap:in:next"); continue; } else { /* NEW LANGUAGE NOTE:*********************************************** // why is this code not called when I dont have a typemap? // instead of giving a warning, no code is generated NEW LANGUAGE NOTE:END ************************************************/ Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); break; } p = nextSibling(p); } // add all argcheck code Printv(f->code, argument_check, argument_parse, NIL); /* Check for trailing varargs */ if (varargs) { if (p && (tm = Getattr(p, "tmap:in"))) { Replaceall(tm, "$input", "varargs"); Printv(f->code, tm, "\n", NIL); } } /* Insert constraint checking code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { p = nextSibling(p); } } /* Insert cleanup code */ String *cleanup = NewString(""); for (p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { Replaceall(tm, "$source", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); p = Getattr(p, "tmap:freearg:next"); } else { p = nextSibling(p); } } /* Insert argument output code */ String *outarg = NewString(""); for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { // // managing the number of returning variables // if (numoutputs=Getattr(p,"tmap:argout:numoutputs")){ // int i=GetInt(p,"tmap:argout:numoutputs"); // printf("got argout:numoutputs of %d\n",i); // returnval+=GetInt(p,"tmap:argout:numoutputs"); // } // else returnval++; Replaceall(tm, "$source", Getattr(p, "lname")); Replaceall(tm, "$target", "result"); Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(outarg, tm, "\n", NIL); p = Getattr(p, "tmap:argout:next"); } else { p = nextSibling(p); } } /* Emit the function call */ emit_action(n, f); /* NEW LANGUAGE NOTE:*********************************************** FIXME: returns 1 if there is a void return type this is because there is a typemap for void NEW LANGUAGE NOTE:END ************************************************/ Printv(f->code, "SWIG_arg=0;\n", NIL); // Return value if necessary if ((tm = Swig_typemap_lookup_new("out", n, "result", 0))) { // managing the number of returning variables // if (numoutputs=Getattr(tm,"numoutputs")){ // int i=GetInt(tm,"numoutputs"); // printf("return numoutputs %d\n",i); // returnval+=GetInt(tm,"numoutputs"); // } // else returnval++; Replaceall(tm, "$source", "result"); if (GetFlag(n, "feature:new")) { Replaceall(tm, "$owner", "1"); } else { Replaceall(tm, "$owner", "0"); } Printf(f->code, "%s\n", tm); // returnval++; } else { Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name); } /* Output argument output code */ Printv(f->code, outarg, NIL); /* Output cleanup code */ Printv(f->code, cleanup, NIL); /* Look to see if there is any newfree cleanup code */ if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup_new("newfree", n, "result", 0))) { Replaceall(tm, "$source", "result"); Printf(f->code, "%s\n", tm); } } /* See if there is any return cleanup code */ if ((tm = Swig_typemap_lookup_new("ret", n, "result", 0))) { Replaceall(tm, "$source", "result"); Printf(f->code, "%s\n", tm); } /* Close the function */ Printv(f->code, "return SWIG_arg;\n", NIL); // add the failure cleanup code: Printv(f->code, "\nif(0) SWIG_fail;\n", NIL); Printv(f->code, "\nfail:\n", NIL); Printv(f->code, "$cleanup", "lua_error(L);\n", NIL); Printv(f->code, "return SWIG_arg;\n", NIL); Printf(f->code, "}\n"); /* Substitute the cleanup code */ Replaceall(f->code, "$cleanup", cleanup); /* Substitute the function name */ Replaceall(f->code, "$symname", iname); Replaceall(f->code, "$result", "result"); /* Dump the function out */ Wrapper_print(f, f_wrappers); Setattr(n, "wrap:name", wname); // you need this to make the overloading work /* NEW LANGUAGE NOTE:*********************************************** register the function in SWIG different language mappings seem to use different ideas NEW LANGUAGE NOTE:END ************************************************/ /* Now register the function with the interpreter. */ if (!Getattr(n, "sym:overloaded")) { // add_method(n, iname, wname, description); if (current==NO_CPP || current==STATIC_FUNC) // emit normal fns & static fns Printv(s_cmd_tab, tab4, "{ \"", iname, "\", ", Swig_name_wrapper(iname), "},\n", NIL); // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", iname, "\", (swig_wrapper_func) ", Swig_name_wrapper(iname), "},\n", NIL); } else { // Setattr(n,"wrap:name", wname); if (!Getattr(n, "sym:nextSibling")) { dispatchFunction(n); } } Delete(argument_check); Delete(argument_parse); Delete(cleanup); Delete(outarg); // Delete(description); Delete(wname); DelWrapper(f); return SWIG_OK; } /* ------------------------------------------------------------ * dispatchFunction() * * Emit overloading dispatch function * ------------------------------------------------------------ */ /* NEW LANGUAGE NOTE:*********************************************** This is an extra function used for overloading of functions it checks the args & then calls the relevant fn nost of the real work in again typemaps: look for %typecheck(SWIG_TYPECHECK_*) in the .swg file NEW LANGUAGE NOTE:END ************************************************/ void dispatchFunction(Node *n) { /* Last node in overloaded chain */ int maxargs; String *tmp = NewString(""); String *dispatch = Swig_overload_dispatch(n, "return %s(L);", &maxargs); /* Generate a dispatch wrapper for all overloaded functions */ Wrapper *f = NewWrapper(); String *symname = Getattr(n, "sym:name"); String *wname = Swig_name_wrapper(symname); //Printf(stdout,"Swig_overload_dispatch %s %s '%s' %d\n",symname,wname,dispatch,maxargs); Printv(f->def, "static int ", wname, "(lua_State* L) {", NIL); Wrapper_add_local(f, "argc", "int argc"); Printf(tmp, "int argv[%d]={1", maxargs + 1); for (int i = 1; i <= maxargs; i++) { Printf(tmp, ",%d", i + 1); } Printf(tmp, "}"); Wrapper_add_local(f, "argv", tmp); Printf(f->code, "argc = lua_gettop(L);\n"); Replaceall(dispatch, "$args", "self,args"); Printv(f->code, dispatch, "\n", NIL); Printf(f->code, "lua_pushstring(L,\"No matching function for overloaded '%s'\");\n", symname); Printf(f->code, "lua_error(L);return 0;\n"); Printv(f->code, "}\n", NIL); Wrapper_print(f, f_wrappers); //add_method(symname,wname,0); if (current==NO_CPP || current==STATIC_FUNC) // emit normal fns & static fns Printv(s_cmd_tab, tab4, "{ \"", symname, "\",", wname, "},\n", NIL); DelWrapper(f); Delete(dispatch); Delete(tmp); Delete(wname); } /* ------------------------------------------------------------ * variableWrapper() * ------------------------------------------------------------ */ virtual int variableWrapper(Node *n) { /* NEW LANGUAGE NOTE:*********************************************** Language::variableWrapper(n) will generate two wrapper fns Foo_get & Foo_set by calling functionWrapper() so we will just add these into the variable lists ideally we should not have registered these as functions, only WRT this variable will look into this later. NEW LANGUAGE NOTE:END ************************************************/ // REPORT("variableWrapper", n); String *iname = Getattr(n, "sym:name"); current=VARIABLE; // let SWIG generate the wrappers int result = Language::variableWrapper(n); current=NO_CPP; // normally SWIG will generate 2 wrappers, a get and a set // but in certain scenarios (immutable, or if its arrays), it will not String *getName = Swig_name_wrapper(Swig_name_get(iname)); String *setName = 0; // checking whether it can be set to or not appears to be a very error prone issue // I refered to the Language::variableWrapper() to find this out bool assignable=is_assignable(n) ? true : false; SwigType *type = Getattr(n, "type"); String *tm = Swig_typemap_lookup_new("globalin", n, iname, 0); if (!tm && SwigType_isarray(type)) assignable=false; Delete(tm); if (assignable) { setName = Swig_name_wrapper(Swig_name_set(iname)); } else { // how about calling a 'this is not settable' error message? setName = NewString("SWIG_Lua_set_immutable"); // error message //setName = NewString("0"); } // register the variable Printf(s_var_tab, "%s{ \"%s\", %s, %s },\n", tab4, iname, getName, setName); Delete(getName); Delete(setName); return result; } /* ------------------------------------------------------------ * constantWrapper() * ------------------------------------------------------------ */ virtual int constantWrapper(Node *n) { // REPORT("constantWrapper", n); String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); //String *nsname = !nspace ? Copy(iname) : NewStringf("%s::%s",ns_name,iname); String *nsname = Copy(iname); SwigType *type = Getattr(n, "type"); String *rawval = Getattr(n, "rawval"); String *value = rawval ? rawval : Getattr(n, "value"); String *tm; if (!addSymbol(iname, n)) return SWIG_ERROR; //if (nspace) Setattr(n,"sym:name",nsname); /* Special hook for member pointer */ if (SwigType_type(type) == T_MPOINTER) { String *wname = Swig_name_wrapper(iname); Printf(f_wrappers, "static %s = %s;\n", SwigType_str(type, wname), value); value = Char(wname); } if ((tm = Swig_typemap_lookup_new("consttab", n, name, 0))) { Replaceall(tm, "$source", value); Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); Printf(s_const_tab, "%s,\n", tm); } else if ((tm = Swig_typemap_lookup_new("constcode", n, name, 0))) { Replaceall(tm, "$source", value); Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); Replaceall(tm, "$nsname", nsname); Printf(f_init, "%s\n", tm); } else { Delete(nsname); Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n"); return SWIG_NOWRAP; } Delete(nsname); return SWIG_OK; } /* ------------------------------------------------------------ * nativeWrapper() * ------------------------------------------------------------ */ virtual int nativeWrapper(Node *n) { // REPORT("nativeWrapper", n); String *symname = Getattr(n, "sym:name"); String *wrapname = Getattr(n, "wrap:name"); if (!addSymbol(wrapname, n)) return SWIG_ERROR; Printv(s_cmd_tab, tab4, "{ \"", symname, "\",", wrapname, "},\n", NIL); // return Language::nativeWrapper(n); // this does nothing... return SWIG_OK; } /* ------------------------------------------------------------ * enumDeclaration() * ------------------------------------------------------------ */ virtual int enumDeclaration(Node *n) { return Language::enumDeclaration(n); } /* ------------------------------------------------------------ * enumvalueDeclaration() * ------------------------------------------------------------ */ virtual int enumvalueDeclaration(Node *n) { return Language::enumvalueDeclaration(n); } /* ------------------------------------------------------------ * classDeclaration() * ------------------------------------------------------------ */ virtual int classDeclaration(Node *n) { return Language::classDeclaration(n); } /* ------------------------------------------------------------ * classHandler() * ------------------------------------------------------------ */ virtual int classHandler(Node *n) { REPORT("classHandler", n); String *mangled_classname = 0; String *real_classname = 0; constructor_name = 0; have_constructor = 0; have_destructor = 0; destructor_action = 0; class_name = Getattr(n, "sym:name"); if (!addSymbol(class_name, n)) return SWIG_ERROR; real_classname = Getattr(n, "name"); mangled_classname = Swig_name_mangle(real_classname); // not sure exactly how this workswhat this works, // but tcl has a static hashtable of all classes emitted and then only emits code for them once. // this fixes issues in test suites: template_default2 & template_specialization static Hash *emitted = NewHash(); if (Getattr(emitted, mangled_classname)) return SWIG_NOWRAP; Setattr(emitted, mangled_classname, "1"); s_attr_tab = NewString(""); Printf(s_attr_tab, "static swig_lua_attribute swig_"); Printv(s_attr_tab, mangled_classname, "_attributes[] = {\n", NIL); s_methods_tab = NewString(""); Printf(s_methods_tab, "static swig_lua_method swig_"); Printv(s_methods_tab, mangled_classname, "_methods[] = {\n", NIL); // Generate normal wrappers Language::classHandler(n); SwigType *t = Copy(Getattr(n, "name")); SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' String *wrap_class = NewStringf("&_wrap_class_%s", mangled_classname); SwigType_remember_clientdata(t, wrap_class); String *rt = Copy(Getattr(n, "classtype")); SwigType_add_pointer(rt); // Register the class structure with the type checker // Printf(f_init,"SWIG_TypeClientData(SWIGTYPE%s, (void *) &_wrap_class_%s);\n", SwigType_manglestr(t), mangled_classname); if (have_destructor) { Printv(f_wrappers, "static void swig_delete_", class_name, "(void *obj) {\n", NIL); if (destructor_action) { Printv(f_wrappers, SwigType_str(rt, "arg1"), " = (", SwigType_str(rt, 0), ") obj;\n", NIL); Printv(f_wrappers, destructor_action, NIL); } else { if (CPlusPlus) { Printv(f_wrappers, " delete (", SwigType_str(rt, 0), ") obj;\n", NIL); } else { Printv(f_wrappers, " free((char *) obj);\n", NIL); } } Printf(f_wrappers, "}\n"); } Printf(s_methods_tab, " {0,0}\n};\n"); Printv(f_wrappers, s_methods_tab, NIL); Printf(s_attr_tab, " {0,0,0}\n};\n"); Printv(f_wrappers, s_attr_tab, NIL); Delete(s_methods_tab); Delete(s_attr_tab); // Handle inheritance // note: with the idea of class hireachied spread over multiple modules // cf test-suite: imports.i // it is not possible to just add the pointers to the base classes to the code // (as sometimes these classes are not present) // therefore we instead hold the name of the base class and a null pointer // at runtime: we can query the swig type manager & see if the class exists // if so, we can get the pointer to the base class & replace the null pointer // if the type does not exist, then we cannot... String *base_class = NewString(""); String *base_class_names = NewString(""); List *baselist = Getattr(n, "bases"); if (baselist && Len(baselist)) { Iterator b; int index = 0; b = First(baselist); while (b.item) { String *bname = Getattr(b.item, "name"); if ((!bname) || GetFlag(b.item, "feature:ignore") || (!Getattr(b.item, "module"))) { b = Next(b); continue; } // old code: (used the pointer to the base class) //String *bmangle = Swig_name_mangle(bname); //Printf(base_class, "&_wrap_class_%s", bmangle); //Putc(',', base_class); //Delete(bmangle); // new code: stores a null pointer & the name Printf(base_class, "0,"); Printf(base_class_names, "\"%s *\",", SwigType_namestr(bname)); b = Next(b); index++; } } Printv(f_wrappers, "static swig_lua_class *swig_", mangled_classname, "_bases[] = {", base_class, "0};\n", NIL); Delete(base_class); Printv(f_wrappers, "static char *swig_", mangled_classname, "_base_names[] = {", base_class_names, "0};\n", NIL); Delete(base_class_names); Printv(f_wrappers, "static swig_lua_class _wrap_class_", mangled_classname, " = { \"", class_name, "\", &SWIGTYPE", SwigType_manglestr(t), ",", NIL); if (have_constructor) { Printf(f_wrappers, "%s", Swig_name_wrapper(Swig_name_construct(constructor_name))); Delete(constructor_name); constructor_name = 0; } else { Printf(f_wrappers, "0"); } if (have_destructor) { Printv(f_wrappers, ", swig_delete_", class_name, NIL); } else { Printf(f_wrappers, ",0"); } Printf(f_wrappers, ", swig_%s_methods, swig_%s_attributes, swig_%s_bases, swig_%s_base_names };\n\n", mangled_classname, mangled_classname, mangled_classname, mangled_classname); // Printv(f_wrappers, ", swig_", mangled_classname, "_methods, swig_", mangled_classname, "_attributes, swig_", mangled_classname, "_bases };\n\n", NIL); // Printv(s_cmd_tab, tab4, "{ SWIG_prefix \"", class_name, "\", (swig_wrapper_func) SWIG_ObjectConstructor, &_wrap_class_", mangled_classname, "},\n", NIL); Delete(t); Delete(mangled_classname); return SWIG_OK; } /* ------------------------------------------------------------ * memberfunctionHandler() * ------------------------------------------------------------ */ virtual int memberfunctionHandler(Node *n) { String *name = Getattr(n, "name"); String *iname = GetChar(n, "sym:name"); //Printf(stdout,"memberfunctionHandler %s %s\n",name,iname); String *realname, *rname; current = MEMBER_FUNC; Language::memberfunctionHandler(n); current = NO_CPP; realname = iname ? iname : name; rname = Swig_name_wrapper(Swig_name_member(class_name, realname)); if (!Getattr(n, "sym:nextSibling")) { Printv(s_methods_tab, tab4, "{\"", realname, "\", ", rname, "}, \n", NIL); } Delete(rname); return SWIG_OK; } /* ------------------------------------------------------------ * membervariableHandler() * ------------------------------------------------------------ */ virtual int membervariableHandler(Node *n) { // REPORT("membervariableHandler",n); String *symname = Getattr(n, "sym:name"); String *gname, *sname; current = MEMBER_VAR; Language::membervariableHandler(n); current = NO_CPP; gname = Swig_name_wrapper(Swig_name_get(Swig_name_member(class_name, symname))); if (!GetFlag(n, "feature:immutable")) { sname = Swig_name_wrapper(Swig_name_set(Swig_name_member(class_name, symname))); } else { //sname = NewString("0"); sname = NewString("SWIG_Lua_set_immutable"); // error message } Printf(s_attr_tab,"%s{ \"%s\", %s, %s},\n",tab4,symname,gname,sname); Delete(gname); Delete(sname); return SWIG_OK; } /* ------------------------------------------------------------ * constructorHandler() * * Method for adding C++ member constructor * ------------------------------------------------------------ */ virtual int constructorHandler(Node *n) { // REPORT("constructorHandler", n); current = CONSTRUCTOR; Language::constructorHandler(n); current = NO_CPP; constructor_name = NewString(Getattr(n, "sym:name")); have_constructor = 1; return SWIG_OK; } /* ------------------------------------------------------------ * destructorHandler() * ------------------------------------------------------------ */ virtual int destructorHandler(Node *n) { current = DESTRUCTOR; Language::destructorHandler(n); current = NO_CPP; have_destructor = 1; destructor_action = Getattr(n, "wrap:action"); return SWIG_OK; } /* ----------------------------------------------------------------------- * staticmemberfunctionHandler() * * Wrap a static C++ function * ---------------------------------------------------------------------- */ virtual int staticmemberfunctionHandler(Node *n) { current = STATIC_FUNC; return Language::staticmemberfunctionHandler(n); current = NO_CPP; } /* ------------------------------------------------------------ * memberconstantHandler() * * Create a C++ constant * ------------------------------------------------------------ */ virtual int memberconstantHandler(Node *n) { // REPORT("memberconstantHandler",n); return Language::memberconstantHandler(n); } /* --------------------------------------------------------------------- * staticmembervariableHandler() * --------------------------------------------------------------------- */ virtual int staticmembervariableHandler(Node *n) { // REPORT("staticmembervariableHandler",n); current = STATIC_VAR; return Language::staticmembervariableHandler(n); current = NO_CPP; } /* --------------------------------------------------------------------- * external runtime generation * --------------------------------------------------------------------- */ /* This is to support the usage SWIG -external-runtime <filename> The code consists of two functions: String *runtimeCode() // returns a large string with all the runtimes in String *defaultExternalRuntimeFilename() // returns the default filename I am writing a generic solution, even though SWIG-Lua only has one file right now... */ String *runtimeCode() { String *s = NewString(""); const char *filenames[] = { "luarun.swg", 0 }; // must be 0 termiated String *sfile; for (int i = 0; filenames[i] != 0; i++) { sfile = Swig_include_sys(filenames[i]); if (!sfile) { Printf(stderr, "*** Unable to open '%s'\n", filenames[i]); } else { Append(s, sfile); Delete(sfile); } } return s; } String *defaultExternalRuntimeFilename() { return NewString("swigluarun.h"); } }; /* NEW LANGUAGE NOTE:*********************************************** in order to add you language into swig, you need to make the following changes: - write this file (obviously) - add into the makefile (not 100% clear on how to do this) - edit swigmain.cxx to add your module near the top of swigmain.cxx, look for this code & add you own codes ======= begin change ========== extern "C" { Language *swig_tcl(void); Language *swig_python(void); //etc,etc,etc... Language *swig_lua(void); // this is my code } //etc,etc,etc... swig_module modules[] = { {"-guile", swig_guile, "Guile"}, {"-java", swig_java, "Java"}, //etc,etc,etc... {"-Lua", swig_lua, "Lua"}, // this is my code {NULL, NULL, NULL} // this must come at the end of the list }; ======= end change ========== This is all that is needed NEW LANGUAGE NOTE:END ************************************************/ /* ----------------------------------------------------------------------------- * swig_lua() - Instantiate module * ----------------------------------------------------------------------------- */ extern "C" Language *swig_lua(void) { return new LUA(); } <file_sep>#ifndef SOFT_BODY_MATH_H #define SOFT_BODY_MATH_H #include <NxQuat.h> #include <NxVec3.h> namespace SOFTBODY { bool SBM_rayIntersectsTriangle(const float *point,const float *direction,const float *v0,const float *v1,const float *v2,float &t); float SBM_computeBoundingSphere(unsigned int vcount,const float *points,float *center); float SBM_computeSphereVolume(float r); bool SBM_rayIntersectsSphere(const float *point,const float *direction,const float *center,float radius,float &t); }; // END OF SOFTBODY NAMESPACE #endif <file_sep>/****************************************************************************** File : CustomPlayer.h Description: This file contains the CCustomPlayer class which is the "interface" with the Virtools SDK. All other files are Windows/MFC specific code. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ #if !defined(CUSTOMPLAYER_H) #define CUSTOMPLAYER_H //#include "resourceplayer.h" #include "CKAll.h" #include <vtcxglobal.h> #include <BaseMacros.h> #include "CustomPlayerStructs.h" //#include "CustomPlayerApp.h" /************************************************************************* Summary: This class defines the implementation of the Virtools Runtime/Player. Description: This class provides member functions for initializing the virtools runtime and for running it. Remarks: This class is a singleton. It means there is only one instance of it and you cannot instanciate it. To get an instance of the class use CCustomPlayer::Instance. See also: CCustomPlayerApp, Instance. *************************************************************************/ class MODULE_API CCustomPlayer { public : /************************************************************************* Summary: Retrieve the unique instance of the player. *************************************************************************/ static CCustomPlayer& Instance(); /************************************************************************* Summary: Release all data which has been created during the initializating and the execution of the player. *************************************************************************/ ~CCustomPlayer(); /************************************************************************* Summary: Initialize the player. Description: This function intialize the virtools engine (ck, render engine, ...) and load the composition Parameters: iMainWindow: the main window of the application. iRenderWindow: the render window. iConfig: the configuration of the player (see EConfigPlayer). iData: pointer to a string (if iDataSize==0) containing the name of the filename to load or pointer to the memory where the application is located (if iDataSize!=0). iDataSize: Size of the memory where the application is located if it is alredy in memory (can be null). *************************************************************************/ BOOL InitPlayer(HWND iMainWindow, HWND iRenderWindow, int iConfig, const void* iData, int iDataSize); void Terminate(int flags); /************************************************************************* Summary: Initialize the engine. Description: This function intialize the virtools engine (ck, render engine, ...) *************************************************************************/ int InitEngine(HWND iMainWindow); /************************************************************************* Summary: Play the composition. *************************************************************************/ void Play(); /************************************************************************* Summary: Pause the composition. *************************************************************************/ void Pause(); /************************************************************************* Summary: Reset the composition and play it. *************************************************************************/ void Reset(); /************************************************************************* Summary: Process one frame of the compisition *************************************************************************/ BOOL Process(int iConfig); /************************************************************************* Summary: Switch from fullscreen/windowed to windowed/fullscreen. Remarks: The player try to retrieve the resolution (fullscreen or windowed) from level attributes before switching. *************************************************************************/ BOOL SwitchFullscreen(); BOOL SwitchFullscreen(BOOL value); /************************************************************************* Summary: Change the current resolution (fullscreen or windowed Remarks: The player try to retrieve the resolution (fullscreen or windowed) from level attributes. If nothing has changed nothing is done. *************************************************************************/ BOOL ChangeResolution(); /************************************************************************* Summary: Manage the mouse clipping Parameters: TRUE to enable the mouse clipping. *************************************************************************/ BOOL ClipMouse(BOOL iEnable); /************************************************************************* Summary: Manage the WM_PAINT windows event. Description: In windowed mode we use the render context to render the scene. *************************************************************************/ void OnPaint(); /************************************************************************* Summary: Manage the mouse left button click. Description: Send a message (click or double click) to the object "picked" by the mouse, if any. *************************************************************************/ void OnMouseClick(int iMessage); /************************************************************************* Summary: Manage the focus changement. Description: - if the application is minimized (no focus) we paused it. - if the application is no more minimized (but was minimized) we restart it. - if the application focus is changin depending of the "Focus Lost Behavior" (see CKContext::GetFocusLostBehavior or the "Focus Lost Behavior" in the variable manager). *************************************************************************/ void OnFocusChange(BOOL iFocus); /************************************************************************* Summary: Manage the activty of the application. Description: If the application is deactivated while it is in fullscreen mode, we must switch to windowed mode. *************************************************************************/ void OnActivateApp(BOOL iActivate); /************************************************************************* Summary: Manage system keys (ALT + KEY) Description: If system keys are not diabled (see eDisableKeys) - ALT + ENTER -> SwitchFullscreen - ALT + F4 -> Quit the application *************************************************************************/ LRESULT OnSysKeyDownMainWindow(int iConfig, int iKey); /************************************************************************* Summary: Manage the activty of the application. Description: If the application is deactivated while it is in fullscreen mode, we must switch to windowed mode. *************************************************************************/ int DoSystemCheck(XString&errorText); void _InitContextAnd(); void _InitManagers(); void SetMainWindow(HWND _main){ m_MainWindow = _main;} xEApplicationMode m_AppMode; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // [11/28/2007 mc007] xSEngineWindowInfo *m_EngineWindowInfo; USHORT PLoadEngineWindowProperties(const char *configFile); xSEngineWindowInfo *GetEWindowInfo(); xSEnginePaths* m_EPaths; USHORT PLoadEnginePathProfile(const char* configFile); xSEnginePaths* GetEPathProfile(); xSApplicationWindowStyle *m_AWStyle; USHORT PLoadAppStyleProfile(const char* configFile); USHORT PLoadResourcePaths(const char* configFile,const char*section,int resourceType); xSApplicationWindowStyle *GetPAppStyle(); xEApplicationMode PGetApplicationMode(const char* pstrCommandLine); xEApplicationMode PGetApplicationMode(); xSEnginePointers *GetEnginePointers(); xSEngineWindowInfo *GetEngineWindowInfo(); void ShowSplash(); void SetSplashText(const char* text); void HideSplash(); USHORT PSaveEngineWindowProperties(const char *configFile,const vtPlayer::Structs::xSEngineWindowInfo& input); //////////////////////////////////////// // accessors int& RasterizerFamily(); int& RasterizerFlags(); int& WindowedWidth(); int& WindowedHeight(); int& MininumWindowedWidth(); int& MininumWindowedHeight(); int& FullscreenWidth(); int& FullscreenHeight(); int Driver(); int& FullscreenBpp(); CKRenderContext* GetRenderContext(); protected: enum DriverFlags { eFamily = 1, eDirectXVersion = 2, eSoftware = 4 }; enum PlayerState { eInitial = 0, ePlaying = 1, ePlaused = 2, eFocusLost = 3, eMinimized = 4 }; BOOL _InitPlugins(CKPluginManager& iPluginManager); int _InitRenderEngines(CKPluginManager& iPluginManager); public : CKERROR _Load(const char* str); CKERROR _Load(const void* iMemoryBuffer, int iBufferSize); BOOL _FinishLoad(); protected : void _MissingGuids(CKFile* iFile, const char* iResolvedFile); BOOL _GetWindowedResolution(); BOOL _GetFullScreenResolution(); void _SetResolutions(); BOOL _InitDriver(); BOOL _CheckDriver(VxDriverDesc* iDesc, int iFlags); BOOL _CheckFullscreenDisplayMode(BOOL iDoBest); int m_State; public: HWND m_MainWindow; HWND m_RenderWindow; HWND m_hWndParent; // ck objects (context, managers, ...) CKContext* m_CKContext; CKRenderContext* m_RenderContext; CKMessageManager* m_MessageManager; CKRenderManager* m_RenderManager; CKTimeManager* m_TimeManager; CKAttributeManager* m_AttributeManager; CKInputManager* m_InputManager; vtPlayer::Structs::xSEnginePointers m_EnginePointers; CKLevel* m_Level; // attributes // from an exemple about using this attributes see sample.cmo which is delivered with this player sample int m_QuitAttType; // attribut without type, name is "Quit" int m_SwitchFullscreenAttType; // attribut without type, name is "Switch Fullscreen" int m_SwitchResolutionAttType; // attribut without type, name is "Switch Resolution" int m_SwitchMouseClippingAttType; // attribut without type, name is "Switch Mouse Clipping" int m_WindowedResolutionAttType; // attribut which type is Vector 2D, name is "Windowed Resolution" int m_FullscreenResolutionAttType; // attribut which type is Vector 2D, name is "Fullscreen Resolution" int m_FullscreenBppAttType; // attribut which type is Integer, name is "Fullscreen Bpp" // messages int m_MsgClick; int m_MsgDoubleClick; // display configuration int m_RasterizerFamily; // see CKRST_RSTFAMILY int m_RasterizerFlags; // see CKRST_SPECIFICCAPS int m_WindowedWidth; // windowed mode width int m_WindowedHeight; // windowed mode height int m_MinWindowedWidth; // windowed mode minimum width int m_MinWindowedHeight; // windowed mode minumum height int m_FullscreenWidth; // fullscreen mode width int m_FullscreenHeight; // fullscreen mode height int m_FullscreenBpp; // fullscreen mode bpp int m_Driver; // index of the current driver BOOL m_FullscreenEnabled; // is fullscreen enable BOOL m_EatDisplayChange; // used to ensure we are not switching mode will we are already switching BOOL m_MouseClipped; // used to know if the mouse is acutally cliped RECT m_MainWindowRect; int m_FullscreenRefreshRate; // fullscreen mode bpp int m_LastError; XString m_LastErrorText; HINSTANCE m_hInstance; ATOM _RegisterClass(); int _CreateWindows(); // main windowproc LRESULT CALLBACK _MainWindowWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); static LRESULT _MainWindowWndProcStub( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); void StartMove(LPARAM lParam); void DoMMove(LPARAM lParam, WPARAM wParam); int nMMoveX, nMMoveY; //initial mouse position from window origin. HRESULT DoFrame(); int Tick(); int RunInThread(); void Stop(); HANDLE m_hThread; /************************************************************************/ /* */ /************************************************************************/ int SendMessage(char *targetObject,char *message,int id0,int id1,int id2,int value); int SendMessage(char *targetObject,char *message,int id0,int id1,int id2,float value); int SendMessage(char *targetObject,char *message,int id0,int id1,int id2,char* value); void RedirectLog(); XString m_oldText; //HWND m_Splash; // the window used to display the splash screen. XString m_PlayerClass; // the name of the windows class used for the main window. XString m_RenderClass; // the name of the windows class used for the render window. XString m_PlayerTitle; // the string display in the title bar of the main window. int m_Config; // the configuration of the player (see EConfigPlayer). HACCEL m_hAccelTable; private: // {secret} CCustomPlayer(); // {secret} CCustomPlayer(const CCustomPlayer&); // {secret} CCustomPlayer& operator=(const CCustomPlayer&); }; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // [11/28/2007 mc007] #define GetPlayer() CCustomPlayer::Instance() #endif // CUSTOMPLAYER_H<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorJD6SetMotionModeDecl(); CKERROR CreateJD6SetMotionModeProto(CKBehaviorPrototype **pproto); int JD6SetMotionMode(const CKBehaviorContext& behcontext); CKERROR JD6SetMotionModeCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_BodyA=0, bbI_BodyB, bbI_Anchor, bbI_AnchorRef, bbI_Axis, bbI_AxisRef }; //************************************ // Method: FillBehaviorJD6SetMotionModeDecl // FullName: FillBehaviorJD6SetMotionModeDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorJD6SetMotionModeDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6SetMotionMode"); od->SetCategory("Physic/D6"); od->SetDescription("Sets the motion freedom mode in a D6 joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x62dc4a7e,0x20736a5e)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJD6SetMotionModeProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreateJD6SetMotionModeProto // FullName: CreateJD6SetMotionModeProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreateJD6SetMotionModeProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6SetMotionMode"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In0"); proto->DeclareOutput("Out0"); proto->SetBehaviorCallbackFct( JD6SetMotionModeCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Motion Axis",VTE_JOINT_MOTION_MODE_AXIS,0); proto->DeclareInParameter("Motion Mode",VTE_JOINT_MOTION_MODE,0); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(JD6SetMotionMode); *pproto = proto; return CK_OK; } //************************************ // Method: JD6SetMotionMode // FullName: JD6SetMotionMode // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int JD6SetMotionMode(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); if(bodyA || bodyB) { pJointD6 *joint =static_cast<pJointD6*>(worldA->getJoint(target,targetB,JT_D6)); int motionAxis = GetInputParameterValue<int>(beh,1); D6MotionMode motionMode = GetInputParameterValue<D6MotionMode>(beh,2); if (joint) { switch(motionAxis) { case D6MA_Twist: joint->setTwistMotionMode(motionMode); break; case D6MA_Swing1: joint->setSwing1MotionMode(motionMode); break; case D6MA_Swing2: joint->setSwing2MotionMode(motionMode); break; case D6MA_X: joint->setXMotionMode(motionMode); break; case D6MA_Y: joint->setYMotionMode(motionMode); break; case D6MA_Z: joint->setZMotionMode(motionMode); break; } } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: JD6SetMotionModeCB // FullName: JD6SetMotionModeCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR JD6SetMotionModeCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD fmax; beh->GetLocalParameterValue(0,&fmax); if (fmax ) { beh->EnableInputParameter(6,fmax); beh->EnableInputParameter(7,fmax); }else { beh->EnableInputParameter(6,fmax); beh->EnableInputParameter(7,fmax); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (target && targetB) { // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) return CKBR_OK; // the physic object A and B : pRigidBody*bodyA= world->getBody(target); pRigidBody*bodyB= world->getBody(targetB); if(bodyA && bodyB) { // pJointHinge2 *joint = static_cast<pJointHinge2*>(bodyA->isConnected(targetB)); /* if (joint && joint->GetFeedBack()) { joint->SetFeedBack(NULL,0,0); }*/ } } } } break; } return CKBR_OK; } <file_sep>#include "xDistributedPoint1F.h" #include "xPredictionSetting.h" #include "xDistributedPropertyInfo.h" #include "xMathFnc2.h" uxString xDistributedPoint1F::print(TNL::BitSet32 flags) { return uxString(); } void xDistributedPoint1F::updateFromServer(TNL::BitStream *stream) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { TNL::F32 p; stream->read(&p); TNL::F32 v; stream->read(&v); mLastServerValue = p; mLastServerDifference = v; } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { TNL::F32 p; stream->read(&p); mCurrentValue = p; mLastServerValue = p; } setValueState(E_DV_UPDATED); } void xDistributedPoint1F::updateGhostValue(TNL::BitStream *stream) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { stream->write(mCurrentValue); stream->write(mDifference); } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { stream->write(mCurrentValue); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedPoint1F::unpack(TNL::BitStream *bstream,float sendersOneWayTime) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { sendersOneWayTime *= 0.001f; TNL::F32 p; bstream->read(&p); TNL::F32 v; bstream->read(&v); TNL::F32 predictedPos = p + v * sendersOneWayTime; setOwnersOneWayTime(sendersOneWayTime); mLastValue = mCurrentValue; mCurrentValue = predictedPos; mDifference= mCurrentValue - mLastValue; } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { TNL::F32 p; bstream->read(&p); mLastValue = p; mLastServerValue = p; mCurrentValue = p; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedPoint1F::pack(TNL::BitStream *bstream) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { bstream->write(mCurrentValue); bstream->write(mDifference); } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { bstream->write(mCurrentValue); } int flags = getFlags(); flags &= (~E_DP_NEEDS_SEND); setFlags(flags); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedPoint1F::updateValue(TNL::F32 value,xTimeType currentTime) { mLastTime = mCurrentTime; mCurrentTime = currentTime; mLastDeltaTime = mCurrentTime - mLastTime; mLastValue = mCurrentValue; mCurrentValue = value; mDifference = mCurrentValue - mLastValue; mThresoldTicker +=mLastDeltaTime; float lengthDiff = fabsf(mDifference); float timeDiffMs = ((float)mThresoldTicker) / 1000.f; int flags = getFlags(); flags =E_DP_OK; bool result = false; if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { if (lengthDiff > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime()) { flags =E_DP_NEEDS_SEND; result = true ; } } TNL::F32 serverDiff = mCurrentValue-mLastServerValue ; if ( fabsf( serverDiff) > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > (getPredictionSettings()->getMinSendTime() * 0.2f) ) { flags =E_DP_NEEDS_SEND; result = true ; } } if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime()) { mThresoldTicker2 = 0 ; mThresoldTicker = 0; } } if (getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { flags =E_DP_NEEDS_SEND; result = true ; } setFlags(flags); return result; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" using namespace vtAgeia; VxVector pJoint::getGlobalAxis(){ if (!getJoint()) return VxVector(-1,-1,-1); return getFrom(getJoint()->getGlobalAxis()); } void pJoint::setGlobalAxis(VxVector axis) { if (getJoint()) getJoint()->setGlobalAxis(getFrom(axis)); } VxVector pJoint::getGlobalAnchor(){ if (!getJoint()) return VxVector(-1,-1,-1); return getFrom(getJoint()->getGlobalAnchor()); } void pJoint::setGlobalAnchor(VxVector anchor) { if (getJoint()) getJoint()->setGlobalAnchor(getFrom(anchor)); } int pJoint::getNbLimitPlanes() { if (!getJoint()) return -1; NxJoint *j = getJoint(); j->resetLimitPlaneIterator(); int numLimitPlanes = 0; NxVec3 limitPoint; if ( j->hasMoreLimitPlanes() ) { NxVec3 planeNormal; NxReal planeD; NxReal restitution; bool ok = true; while ( ok ) { j->getNextLimitPlane( planeNormal, planeD, &restitution ); ++numLimitPlanes; ok = j->hasMoreLimitPlanes(); } } return numLimitPlanes; } ////////////////////////////////////////////////////////////////////////// pJointFixed::pJointFixed(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Fixed) { } pJoint::pJoint(pRigidBody* _a,pRigidBody* _b,int _type ) : m_SolidA(_a) , m_SolidB(_b) ,m_type((JType)_type) { m_vtObjectA = _a ? _a->GetVT3DObject() : NULL; m_vtObjectB = _b ? _b->GetVT3DObject() : NULL; mAID = _a ? _a->GetVT3DObject()->GetID() : -1 ; mBID = _b ? _b->GetVT3DObject()->GetID() : -1 ; mJoint = NULL; m_pWorld = NULL; } pJointD6*pJoint::castD6Joint() { if (getJoint()) { if (getJoint()->isD6Joint()) { return static_cast<pJointD6*>(this); } } return NULL; } pJointPulley* pJoint::castPulley() { if (getJoint()) { if (getJoint()->isPulleyJoint()) { return static_cast<pJointPulley*>(this); } } return NULL; } pJointDistance* pJoint::castDistanceJoint() { if (getJoint()) { if (getJoint()->isDistanceJoint()) { return static_cast<pJointDistance*>(this); } } return NULL; } pJointBall* pJoint::castBall() { if (getJoint()) { if (getJoint()->isSphericalJoint()) { return static_cast<pJointBall*>(this); } } return NULL; } pJointRevolute* pJoint::castRevolute() { if (getJoint()) { if (getJoint()->isRevoluteJoint()) { return static_cast<pJointRevolute*>(this); } } return NULL; } pJointPrismatic* pJoint::castPrismatic() { if (getJoint()) { if (getJoint()->isPrismaticJoint()) { return static_cast<pJointPrismatic*>(this); } } return NULL; } pJointCylindrical* pJoint::castCylindrical() { if (getJoint()) { if (getJoint()->isCylindricalJoint()) { return static_cast<pJointCylindrical*>(this); } } return NULL; } pJointPointInPlane* pJoint::castPointInPlane() { if (getJoint()) { if (getJoint()->isPointInPlaneJoint()) { return static_cast<pJointPointInPlane*>(this); } } return NULL; } pJointPointOnLine* pJoint::castPointOnLine() { if (getJoint()) { if (getJoint()->isPointOnLineJoint()) { return static_cast<pJointPointOnLine*>(this); } } return NULL; } /************************************************************************/ /* */ /************************************************************************/ int pJoint::addLimitPlane(const VxVector normal, VxVector pointInPlane, float restitution/* =0.0f */) { int res = -1; if (getJoint()){ res = getJoint()->addLimitPlane(pMath::getFrom(normal),pMath::getFrom(pointInPlane),restitution); } return res; } void pJoint::setLimitPoint( VxVector point,bool pointIsOnActor2/*=true*/ ) { if (getJoint()){ return getJoint()->setLimitPoint(getFrom(point),pointIsOnActor2); } } void pJoint::purgeLimitPlanes(){ if (getJoint()) getJoint()->purgeLimitPlanes();} void pJoint::resetLimitPlaneIterator(){ if (getJoint()) getJoint()->resetLimitPlaneIterator();} int pJoint::hasMoreLimitPlanes(){ if (getJoint()) return getJoint()->hasMoreLimitPlanes(); return false;} int pJoint::getNextLimitPlane (VxVector &planeNormal, float &planeD,float *restitution) { if (getJoint()) { NxVec3 n; int k =getJoint()->getNextLimitPlane(n,planeD,restitution); planeNormal = pMath::getFrom(n); return k; } return 0; } void pJoint::getBreakForces( float& maxForce,float& maxTorque ) { if (getJoint()) getJoint()->getBreakable(maxForce,maxTorque); } void pJoint::setBreakForces( float maxForce,float maxTorque ) { if (!getJoint()) return; if ( maxTorque !=0.0f && maxForce != 0.0f) getJoint()->setBreakable(maxForce,maxTorque); //if ( maxTorque =0.0f && maxForce = 0.0f) // getJoint()->setBreakable(,maxTorque); } void pJoint::setLocalAnchor0(VxVector anchor0) { if (getJoint()) { if(getJoint()->isRevoluteJoint()) { NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast<NxRevoluteJoint*>(getJoint()); if (!joint)return; joint->saveToDesc(descr); descr.localAnchor[0] = getFrom(anchor0); joint->loadFromDesc(descr); } } } /************************************************************************/ /* */ /************************************************************************/ <file_sep>#ifndef __PVEHICLETYPES_H__ #define __PVEHICLETYPES_H__ #include "pVTireFunction.h" #include "pLinearInterpolation.h" /** \addtogroup Vehicle @{ */ typedef enum FrictionCircleMethod { FC_GENTA, // Genta (page 52?) FC_VECTOR, // Vector reduction to fit circle FC_VOID, // Don't touch forces (for testing) FC_SLIPVECTOR // Gregor's method of combined Pacejka }; #define BREAK_TABLE_ENTRIES 10 class pVehicleBrakeTable { public: float brakeEntries[BREAK_TABLE_ENTRIES]; }; class MODULE_API pVehicleDesc { public: VxVector position; pVehicleGearDesc *gearDescription; pVehicleGearDesc * getGearDescription() { return gearDescription; } pVehicleMotorDesc *motorDescr; pVehicleMotorDesc * getMotorDescr() { return motorDescr; } float mass; float motorForce; float transmissionEfficiency; float differentialRatio; VxVector steeringTurnPoint; VxVector steeringSteerPoint; float steeringMaxAngle; VxVector centerOfMass; float digitalSteeringDelta; float maxVelocity; float digitalSteeringDeltaVelocityModifier; int xmlLinkID; XString xmlName; pRigidBody *body; void* userData; //---------------------------------------------------------------- // // Engine Related Parameters // float engineInertia; float engineFriction; float engineBrakingCoefficient; float engineMaximumTorque; //-RPMs float engineRpmMaximum; float engineRpmIdle; float engineRpmAutoClutch; float engineRpmStart; float engineRpmStall; int engineFlags; //-Engine Torque Curve pLinearInterpolation torqueCurve; int processFlags; pVehicleDesc(); void setToDefault(); bool isValid() const; }; typedef std::vector<pWheel*>WheelArrayType; /** @} */ #include "pLinearInterpolation.h" #endif // __PVEHICLETYPES_H__<file_sep>#include "CKAll.h" /***************************************************************************** * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR * A PARTICULAR PURPOSE. * * Copyright (C) 1993 - 1996 Microsoft Corporation. All Rights Reserved. * ****************************************************************************** * * SMF.C * * MIDI File access routines. * *****************************************************************************/ #include <windows.h> #include <windowsx.h> #include <mmsystem.h> #include <memory.h> #include "muldiv32.h" #include "smf.h" #include "smfi.h" static SMFRESULT smfInsertParmData( PSMF pSmf, TICKS tkDelta, LPMIDIHDR lpmh); /***************************************************************************** * * smfOpenFile * * This function opens a MIDI file for access. * * psofs - Specifies the file to open and associated * parameters. Contains a valid HSMF handle * on success. * * Returns * SMF_SUCCESS The specified file was opened. * * SMF_OPEN_FAILED The specified file could not be opened because it * did not exist or could not be created on the disk. * * SMF_INVALID_FILE The specified file was corrupt or not a MIDI file. * * SMF_NO_MEMORY There was insufficient memory to open the file. * * SMF_INVALID_PARM The given flags or time division in the * SMFOPENFILESTRUCT were invalid. * *****************************************************************************/ SMFRESULT smfOpenFile( PSMFOPENFILESTRUCT psofs) { HMMIO hmmio = (HMMIO)NULL; PSMF pSmf; SMFRESULT smfrc = SMF_SUCCESS; MMIOINFO mmioinfo; MMCKINFO ckRIFF; MMCKINFO ckDATA; //assert(psofs != NULL); //assert(psofs->pstrName != NULL); /* Verify that the file can be opened or created */ _fmemset(&mmioinfo, 0, sizeof(mmioinfo)); hmmio = mmioOpen(psofs->pstrName, &mmioinfo, MMIO_READ|MMIO_ALLOCBUF); if ((HMMIO)NULL == hmmio) { //DPF(1, "smfOpenFile: mmioOpen failed!"); return SMF_OPEN_FAILED; } /* Now see if we can create the handle structure */ pSmf = (PSMF)LocalAlloc(LPTR, sizeof(SMF)); if (NULL == pSmf) { //DPF(1, "smfOpenFile: LocalAlloc failed!"); smfrc = SMF_NO_MEMORY; goto smf_Open_File_Cleanup; } lstrcpy(pSmf->szName, psofs->pstrName); pSmf->fdwSMF = 0; pSmf->pTempoMap = NULL; /* Pull the entire file into a block of memory. */ _fmemset(&ckRIFF, 0, sizeof(ckRIFF)); if (0 == mmioDescend(hmmio, &ckRIFF, NULL, MMIO_FINDRIFF) && ckRIFF.fccType == FOURCC_RMID) { ckDATA.ckid = FOURCC_data; if (0 == mmioDescend(hmmio, &ckDATA, &ckRIFF, MMIO_FINDCHUNK)) { pSmf->cbImage = ckDATA.cksize; } else { //DPF(1, "smfOpenFile: Could not descend into RIFF DATA chunk!"); smfrc = SMF_INVALID_FILE; goto smf_Open_File_Cleanup; } } else { long x=mmioSeek(hmmio, 0L, SEEK_SET); pSmf->cbImage = mmioSeek(hmmio, 0L, SEEK_END); mmioSeek(hmmio, 0L, SEEK_SET); } if (NULL == (pSmf->hpbImage = (LPBYTE)GlobalAllocPtr(GMEM_MOVEABLE|GMEM_SHARE, pSmf->cbImage))) { //DPF(1, "smfOpenFile: No memory for image! [%08lX]", pSmf->cbImage); smfrc = SMF_NO_MEMORY; goto smf_Open_File_Cleanup; } if (pSmf->cbImage != (DWORD)mmioRead(hmmio, (char*)pSmf->hpbImage, pSmf->cbImage)) { //DPF(1, "smfOpenFile: Read error on image!"); smfrc = SMF_INVALID_FILE; goto smf_Open_File_Cleanup; } /* If the file exists, parse it just enough to pull out the header and ** build a track index. */ smfrc = smfBuildFileIndex((PSMF *)&pSmf); if (MMSYSERR_NOERROR != smfrc) { //DPF(1, "smfOpenFile: smfBuildFileIndex failed! [%lu]", (DWORD)smfrc); } smf_Open_File_Cleanup: mmioClose(hmmio, 0); if (SMF_SUCCESS != smfrc) { if (NULL != pSmf) { if (NULL != pSmf->hpbImage) { GlobalFreePtr(pSmf->hpbImage); } LocalFree((HLOCAL)pSmf); } } else { psofs->hSmf = (HSMF)pSmf; } return smfrc; } /***************************************************************************** * * smfCloseFile * * This function closes an open MIDI file. * * hSmf - The handle of the open file to close. * * Returns * SMF_SUCCESS The specified file was closed. * SMF_INVALID_PARM The given handle was not valid. * * Any track handles opened from this file handle are invalid after this * call. * *****************************************************************************/ SMFRESULT smfCloseFile( HSMF hSmf) { PSMF pSmf = (PSMF)hSmf; //assert(pSmf != NULL); /* ** Free up handle memory */ if (NULL != pSmf->hpbImage) GlobalFreePtr(pSmf->hpbImage); LocalFree((HLOCAL)pSmf); return SMF_SUCCESS; } /****************************************************************************** * * smfGetFileInfo This function gets information about the MIDI file. * * hSmf - Specifies the open MIDI file to inquire about. * * psfi - A structure which will be filled in with * information about the file. * * Returns * SMF_SUCCESS Information was gotten about the file. * SMF_INVALID_PARM The given handle was invalid. * *****************************************************************************/ SMFRESULT smfGetFileInfo( HSMF hSmf, PSMFFILEINFO psfi) { PSMF pSmf = (PSMF)hSmf; //assert(pSmf != NULL); //assert(psfi != NULL); /* ** Just fill in the structure with useful information. */ psfi->dwTracks = pSmf->dwTracks; psfi->dwFormat = pSmf->dwFormat; psfi->dwTimeDivision= pSmf->dwTimeDivision; psfi->tkLength = pSmf->tkLength; return SMF_SUCCESS; } /****************************************************************************** * * smfTicksToMillisecs * * This function returns the millisecond offset into the file given the * tick offset. * * hSmf - Specifies the open MIDI file to perform * the conversion on. * * tkOffset - Specifies the tick offset into the stream * to convert. * * Returns the number of milliseconds from the start of the stream. * * The conversion is performed taking into account the file's time division and * tempo map from the first track. Note that the same millisecond value * might not be valid at a later time if the tempo track is rewritten. * *****************************************************************************/ DWORD smfTicksToMillisecs( HSMF hSmf, TICKS tkOffset) { PSMF pSmf = (PSMF)hSmf; PTEMPOMAPENTRY pTempo; UINT idx; UINT uSMPTE; DWORD dwTicksPerSec; //assert(pSmf != NULL); if (tkOffset > pSmf->tkLength) { //DPF(1, "sTTM: Clipping ticks to file length!"); tkOffset = pSmf->tkLength; } /* SMPTE time is easy -- no tempo map, just linear conversion ** Note that 30-Drop means nothing to us here since we're not ** converting to a colonized format, which is where dropping ** happens. */ if (pSmf->dwTimeDivision & 0x8000) { uSMPTE = -(int)(char)((pSmf->dwTimeDivision >> 8)&0xFF); if (29 == uSMPTE) uSMPTE = 30; dwTicksPerSec = (DWORD)uSMPTE * (DWORD)(BYTE)(pSmf->dwTimeDivision & 0xFF); return (DWORD)muldiv32(tkOffset, 1000L, dwTicksPerSec); } /* Walk the tempo map and find the nearest tick position. Linearly ** calculate the rest (using MATH.ASM) */ pTempo = pSmf->pTempoMap; //assert(pTempo != NULL); for (idx = 0; idx < pSmf->cTempoMap; idx++, pTempo++) if (tkOffset < pTempo->tkTempo) break; pTempo--; /* pTempo is the tempo map entry preceding the requested tick offset. */ return pTempo->msBase + muldiv32(tkOffset-pTempo->tkTempo, pTempo->dwTempo, 1000L*pSmf->dwTimeDivision); } /****************************************************************************** * * smfMillisecsToTicks * * This function returns the nearest tick offset into the file given the * millisecond offset. * * hSmf - Specifies the open MIDI file to perform the * conversion on. * * msOffset - Specifies the millisecond offset into the stream * to convert. * * Returns the number of ticks from the start of the stream. * * The conversion is performed taking into account the file's time division and * tempo map from the first track. Note that the same tick value * might not be valid at a later time if the tempo track is rewritten. * If the millisecond value does not exactly map to a tick value, then * the tick value will be rounded down. * *****************************************************************************/ TICKS smfMillisecsToTicks( HSMF hSmf, DWORD msOffset) { PSMF pSmf = (PSMF)hSmf; PTEMPOMAPENTRY pTempo; UINT idx; UINT uSMPTE; DWORD dwTicksPerSec; TICKS tkOffset; //assert(pSmf != NULL); /* SMPTE time is easy -- no tempo map, just linear conversion ** Note that 30-Drop means nothing to us here since we're not ** converting to a colonized format, which is where dropping ** happens. */ if (pSmf->dwTimeDivision & 0x8000) { uSMPTE = -(int)(char)((pSmf->dwTimeDivision >> 8)&0xFF); if (29 == uSMPTE) uSMPTE = 30; dwTicksPerSec = (DWORD)uSMPTE * (DWORD)(BYTE)(pSmf->dwTimeDivision & 0xFF); return (DWORD)muldiv32(msOffset, dwTicksPerSec, 1000L); } /* Walk the tempo map and find the nearest millisecond position. Linearly ** calculate the rest (using MATH.ASM) */ pTempo = pSmf->pTempoMap; //assert(pTempo != NULL); for (idx = 0; idx < pSmf->cTempoMap; idx++, pTempo++) if (msOffset < pTempo->msBase) break; pTempo--; /* pTempo is the tempo map entry preceding the requested tick offset. */ tkOffset = pTempo->tkTempo + muldiv32(msOffset-pTempo->msBase, 1000L*pSmf->dwTimeDivision, pTempo->dwTempo); if (tkOffset > pSmf->tkLength) { //DPF(1, "sMTT: Clipping ticks to file length!"); tkOffset = pSmf->tkLength; } return tkOffset; } /****************************************************************************** * * smfReadEvents * * This function reads events from a track. * * hSmf - Specifies the file to read data from. * * lpmh - Contains information about the buffer to fill. * * tkMax - Specifies a cutoff point in the stream * beyond which events will not be read. * * Return@rdes * SMF_SUCCESS The events were successfully read. * SMF_END_OF_TRACK There are no more events to read in this track. * SMF_INVALID_FILE A disk error occured on the file. * * @xref <f smfWriteEvents> *****************************************************************************/ SMFRESULT smfReadEvents( HSMF hSmf, LPMIDIHDR lpmh, TICKS tkMax) { PSMF pSmf = (PSMF)hSmf; SMFRESULT smfrc; EVENT event; LPDWORD lpdw; DWORD dwTempo; //assert(pSmf != NULL); //assert(lpmh != NULL); /* ** Read events from the track and pack them into the buffer in polymsg ** format. ** ** If a SysEx or meta would go over a buffer boundry, split it. */ lpmh->dwBytesRecorded = 0; if (pSmf->dwPendingUserEvent) { smfrc = smfInsertParmData(pSmf, (TICKS)0, lpmh); if (SMF_SUCCESS != smfrc) { //DPF(1, "smfInsertParmData() -> %u", (UINT)smfrc); return smfrc; } } lpdw = (LPDWORD)(lpmh->lpData + lpmh->dwBytesRecorded); if (pSmf->fdwSMF & SMF_F_EOF) { return SMF_END_OF_FILE; } while(TRUE) { //assert(lpmh->dwBytesRecorded <= lpmh->dwBufferLength); /* If we know ahead of time we won't have room for the ** event, just break out now. We need 2 DWORD's for the ** terminator event and at least 2 DWORD's for any ** event we might store - this will allow us a full ** short event or the delta time and stub for a long ** event to be split. */ if (lpmh->dwBufferLength - lpmh->dwBytesRecorded < 4*sizeof(DWORD)) { break; } smfrc = smfGetNextEvent(pSmf, (SPEVENT)&event, tkMax); if (SMF_SUCCESS != smfrc) { /* smfGetNextEvent doesn't set this because smfSeek uses it ** as well and needs to distinguish between reaching the ** seek point and reaching end-of-file. ** ** To the user, however, we present the selection between ** their given tkBase and tkEnd as the entire file, therefore ** we want to translate this into EOF. */ if (SMF_REACHED_TKMAX == smfrc) { pSmf->fdwSMF |= SMF_F_EOF; } //DPF(1, "smfReadEvents: smfGetNextEvent() -> %u", (UINT)smfrc); break; } if (MIDI_SYSEX > EVENT_TYPE(event)) { *lpdw++ = (DWORD)event.tkDelta; *lpdw++ = 0; *lpdw++ = (((DWORD)MEVT_SHORTMSG)<<24) | ((DWORD)EVENT_TYPE(event)) | (((DWORD)EVENT_CH_B1(event)) << 8) | (((DWORD)EVENT_CH_B2(event)) << 16); lpmh->dwBytesRecorded += 3*sizeof(DWORD); } else if (MIDI_META == EVENT_TYPE(event) && MIDI_META_EOT == EVENT_META_TYPE(event)) { /* These are ignoreable since smfReadNextEvent() ** takes care of track merging */ } else if (MIDI_META == EVENT_TYPE(event) && MIDI_META_TEMPO == EVENT_META_TYPE(event)) { if (event.cbParm != 3) { //DPF(1, "smfReadEvents: Corrupt tempo event"); return SMF_INVALID_FILE; } dwTempo = (((DWORD)MEVT_TEMPO)<<24)| (((DWORD)event.hpbParm[0])<<16)| (((DWORD)event.hpbParm[1])<<8)| ((DWORD)event.hpbParm[2]); *lpdw++ = (DWORD)event.tkDelta; *lpdw++ = 0; *lpdw++ = dwTempo; lpmh->dwBytesRecorded += 3*sizeof(DWORD); } else if (MIDI_META != EVENT_TYPE(event)) { /* Must be F0 or F7 system exclusive or FF meta ** that we didn't recognize */ pSmf->cbPendingUserEvent = event.cbParm; pSmf->hpbPendingUserEvent = event.hpbParm; pSmf->fdwSMF &= ~SMF_F_INSERTSYSEX; switch(EVENT_TYPE(event)) { case MIDI_SYSEX: pSmf->fdwSMF |= SMF_F_INSERTSYSEX; ++pSmf->cbPendingUserEvent; /* Falling through... */ case MIDI_SYSEXEND: pSmf->dwPendingUserEvent = ((DWORD)MEVT_LONGMSG) << 24; break; } smfrc = smfInsertParmData(pSmf, event.tkDelta, lpmh); if (SMF_SUCCESS != smfrc) { //DPF(1, "smfInsertParmData[2] %u", (UINT)smfrc); return smfrc; } lpdw = (LPDWORD)(lpmh->lpData + lpmh->dwBytesRecorded); } } return (pSmf->fdwSMF & SMF_F_EOF) ? SMF_END_OF_FILE : SMF_SUCCESS; } /****************************************************************************** * * smfInsertParmData * * Inserts pending long data from a track into the given buffer. * * pSmf - Specifies the file to read data from. * * tkDelta - Specfices the tick delta for the data. * * lpmh - Contains information about the buffer to fill. * * Returns * SMF_SUCCESS The events were successfully read. * SMF_INVALID_FILE A disk error occured on the file. * * Fills as much data as will fit while leaving room for the buffer * terminator. * * If the long data is depleted, resets pSmf->dwPendingUserEvent so * that the next event may be read. * *****************************************************************************/ static SMFRESULT smfInsertParmData( PSMF pSmf, TICKS tkDelta, LPMIDIHDR lpmh) { DWORD dwLength; DWORD dwRounded; LPDWORD lpdw; //assert(pSmf != NULL); //assert(lpmh != NULL); /* Can't fit 4 DWORD's? (tkDelta + stream-id + event + some data) ** Can't do anything. */ //assert(lpmh->dwBufferLength >= lpmh->dwBytesRecorded); if (lpmh->dwBufferLength - lpmh->dwBytesRecorded < 4*sizeof(DWORD)) { if (0 == tkDelta) return SMF_SUCCESS; /* If we got here with a real delta, that means smfReadEvents screwed ** up calculating left space and we should flag it somehow. */ //DPF(1, "Can't fit initial piece of SysEx into buffer!"); return SMF_INVALID_FILE; } lpdw = (LPDWORD)(lpmh->lpData + lpmh->dwBytesRecorded); dwLength = lpmh->dwBufferLength - lpmh->dwBytesRecorded - 3*sizeof(DWORD); dwLength = __min(dwLength, pSmf->cbPendingUserEvent); *lpdw++ = (DWORD)tkDelta; *lpdw++ = 0L; *lpdw++ = (pSmf->dwPendingUserEvent & 0xFF000000L) | (dwLength & 0x00FFFFFFL); dwRounded = (dwLength + 3) & (~3L); if (pSmf->fdwSMF & SMF_F_INSERTSYSEX) { *((LPBYTE)lpdw++) = MIDI_SYSEX; pSmf->fdwSMF &= ~SMF_F_INSERTSYSEX; --dwLength; --pSmf->cbPendingUserEvent; } if (dwLength & 0x80000000L) { //DPF(1, "dwLength %08lX dwBytesRecorded %08lX dwBufferLength %08lX", dwLength, lpmh->dwBytesRecorded, lpmh->dwBufferLength); //DPF(1, "cbPendingUserEvent %08lX dwPendingUserEvent %08lX dwRounded %08lX", pSmf->cbPendingUserEvent, pSmf->dwPendingUserEvent, dwRounded); //DPF(1, "Offset into MIDI image %08lX", (DWORD)(pSmf->hpbPendingUserEvent - pSmf->hpbImage)); //DPF(1, "!hmemcpy is about to fault"); } hmemcpy(lpdw, pSmf->hpbPendingUserEvent, dwLength); if (0 == (pSmf->cbPendingUserEvent -= dwLength)) pSmf->dwPendingUserEvent = 0; lpmh->dwBytesRecorded += 3*sizeof(DWORD) + dwRounded; return SMF_SUCCESS; } /****************************************************************************** * * smfSeek * * This function moves the file pointer within a track * and gets the state of the track at the new position. It returns a buffer of * state information which can be used to set up to play from the new position. * * hSmf - Handle of file to seek within * * tkPosition - The position to seek to in the track. * * lpmh - A buffer to contain the state information. * * Returns * SMF_SUCCESS | The state was successfully read. * SMF_END_OF_TRACK | The pointer was moved to end of track and no state * information was returned. * SMF_INVALID_PARM | The given handle or buffer was invalid. * SMF_NO_MEMORY | There was insufficient memory in the given buffer to * contain all of the state data. * * The state information in the buffer includes patch changes, tempo changes, * time signature, key signature, * and controller information. Only the most recent of these paramters before * the current position will be stored. The state buffer will be returned * in polymsg format so that it may be directly transmitted over the MIDI * bus to bring the state up to date. * * The buffer is mean to be sent as a streaming buffer; i.e. immediately * followed by the first data buffer. If the requested tick position * does not exist in the file, the last event in the buffer * will be a MEVT_NOP with a delta time calculated to make sure that * the next stream event plays at the proper time. * * The meta events (tempo, time signature, key signature) will be the * first events in the buffer if they exist. * * Use smfGetStateMaxSize to determine the maximum size of the state * information buffer. State information that will not fit into the given * buffer will be lost. * * On return, the dwBytesRecorded field of lpmh will contain the * actual number of bytes stored in the buffer. * *****************************************************************************/ typedef struct tag_keyframe { /* ** Meta events. All FF's indicates never seen. */ BYTE rbTempo[3]; /* ** MIDI channel messages. FF indicates never seen. */ BYTE rbProgram[16]; BYTE rbControl[16*120]; } KEYFRAME, *PKEYFRAME; #define KF_EMPTY ((BYTE)0xFF) SMFRESULT smfSeek( HSMF hSmf, TICKS tkPosition, LPMIDIHDR lpmh) { PSMF pSmf = (PSMF)hSmf; PTRACK ptrk; DWORD idxTrack; SMFRESULT smfrc; EVENT event; LPDWORD lpdw; BYTE bEvent; UINT idx; UINT idxChannel; UINT idxController; static KEYFRAME kf; _fmemset(&kf, 0xFF, sizeof(kf)); pSmf->tkPosition = 0; pSmf->fdwSMF &= ~SMF_F_EOF; for (ptrk = pSmf->rTracks, idxTrack = pSmf->dwTracks; idxTrack--; ptrk++) { ptrk->pSmf = pSmf; ptrk->tkPosition = 0; ptrk->cbLeft = ptrk->smti.cbLength; ptrk->hpbImage = pSmf->hpbImage + ptrk->idxTrack; ptrk->bRunningStatus = 0; ptrk->fdwTrack = 0; } while (SMF_SUCCESS == (smfrc = smfGetNextEvent(pSmf, (SPEVENT)&event, tkPosition))) { if (MIDI_META == (bEvent = EVENT_TYPE(event))) { if (EVENT_META_TYPE(event) == MIDI_META_TEMPO) { if (event.cbParm != sizeof(kf.rbTempo)) return SMF_INVALID_FILE; hmemcpy((HPBYTE)kf.rbTempo, event.hpbParm, event.cbParm); } } else switch(bEvent & 0xF0) { case MIDI_PROGRAMCHANGE: kf.rbProgram[bEvent & 0x0F] = EVENT_CH_B1(event); break; case MIDI_CONTROLCHANGE: kf.rbControl[(((WORD)bEvent & 0x0F)*120) + EVENT_CH_B1(event)] = EVENT_CH_B2(event); break; } } if (SMF_REACHED_TKMAX != smfrc) { return smfrc; } /* Build lpmh from keyframe */ lpmh->dwBytesRecorded = 0; lpdw = (LPDWORD)lpmh->lpData; /* Tempo change event? */ if (KF_EMPTY != kf.rbTempo[0] || KF_EMPTY != kf.rbTempo[1] || KF_EMPTY != kf.rbTempo[2]) { if (lpmh->dwBufferLength - lpmh->dwBytesRecorded < 3*sizeof(DWORD)) return SMF_NO_MEMORY; *lpdw++ = 0; *lpdw++ = 0; *lpdw++ = (((DWORD)kf.rbTempo[0])<<16)| (((DWORD)kf.rbTempo[1])<<8)| ((DWORD)kf.rbTempo[2])| (((DWORD)MEVT_TEMPO) << 24); lpmh->dwBytesRecorded += 3*sizeof(DWORD); } /* Program change events? */ for (idx = 0; idx < 16; idx++) { if (KF_EMPTY != kf.rbProgram[idx]) { if (lpmh->dwBufferLength - lpmh->dwBytesRecorded < 3*sizeof(DWORD)) return SMF_NO_MEMORY; *lpdw++ = 0; *lpdw++ = 0; *lpdw++ = (((DWORD)MEVT_SHORTMSG) << 24) | ((DWORD)MIDI_PROGRAMCHANGE) | ((DWORD)idx) | (((DWORD)kf.rbProgram[idx]) << 8); lpmh->dwBytesRecorded += 3*sizeof(DWORD); } } /* Controller events? */ idx = 0; for (idxChannel = 0; idxChannel < 16; idxChannel++) { for (idxController = 0; idxController < 120; idxController++) { if (KF_EMPTY != kf.rbControl[idx]) { if (lpmh->dwBufferLength - lpmh->dwBytesRecorded < 3*sizeof(DWORD)) return SMF_NO_MEMORY; *lpdw++ = 0; *lpdw++ = 0; *lpdw++ = (((DWORD)MEVT_SHORTMSG << 24) | ((DWORD)MIDI_CONTROLCHANGE) | ((DWORD)idxChannel) | (((DWORD)idxController) << 8) | (((DWORD)kf.rbControl[idx]) << 16)); lpmh->dwBytesRecorded += 3*sizeof(DWORD); } idx++; } } /* Force all tracks to be at tkPosition. We are guaranteed that ** all tracks will be past the event immediately preceding tkPosition; ** this will force correct delta-ticks to be generated so that events ** on all tracks will line up properly on a seek into the middle of the ** file. */ for (ptrk = pSmf->rTracks, idxTrack = pSmf->dwTracks; idxTrack--; ptrk++) { ptrk->tkPosition = tkPosition; } return SMF_SUCCESS; } /****************************************************************************** * * smfGetStateMaxSize * * This function returns the maximum sizeof buffer that is needed to * hold the state information returned by f smfSeek. * * pdwSize - Gets the size in bytes that should be allocated * for the state buffer. * * Returns the state size in bytes. * *****************************************************************************/ DWORD smfGetStateMaxSize( VOID) { return 3*sizeof(DWORD) + /* Tempo */ 3*16*sizeof(DWORD) + /* Patch changes */ 3*16*120*sizeof(DWORD) + /* Controller changes */ 3*sizeof(DWORD); /* Time alignment NOP */ } <file_sep>//////////////////////////////////////////////////////////////////////////////// // // ARTPlus // ------- // // Description: // The ARTPlus building block initialize the ARToolKitPlus for Single marker // detection. It should called once in your virtools project. Due to the fact, // that the number of pattern which can be detected, is set on compile time, // you can only detect 20 Pattern inside a video frame. If you want to detect // more, than you have to change the number and recompile (See line 183). // // Input Parameter: // IN_VIDEO_TEXTURE : The image, in with ARToolKitPlus // perform the detection // IN_CAMERA_PARAM_FILE : The filename of the camera parameter file // (look into ARToolKitPlus for description) // IN_NEAR_CLIP_PLANE : Near clip plane used by the camera // IN_FAR_CLIP_PLANE : Far clip plane used by the camera // (look into ARToolKitPlus for description) // IN_ENABLE_CAMERA_CORRECTION : // Flag which indicates that the ARToolKitPlusManager // should use the camera transformation matrix as // projection matrix // // Output Parameter: // OUT_CAMERA_TRANSFORM_MATRIX : // The camera transformation matrix. // OUT_ERROR_STRING : String which describe the error, if one occurs. If // there was no error the string will contain the word // "Success" (without the marks) // // Version 1.0 : First Release // // Known Bugs : None // // Copyright <NAME> <<EMAIL>>, University of Paderborn //////////////////////////////////////////////////////////////////////////////// // Input Parameter #define IN_VIDEO_TEXTURE 0 #define IN_CAMERA_PARAM_FILE 1 #define IN_NEAR_CLIP_PLANE 2 #define IN_FAR_CLIP_PLANE 3 #define IN_ENABLE_CAMERA_CORRECTION 4 // Output Parameter #define OUT_CAMERA_TRANSFORM_MATRIX 0 #define OUT_ERROR_STRING 1 // Local Parameters #define LOCAL_TRACKER 0 // Output Signals #define OUTPUT_OK 0 #define OUTPUT_ERROR 1 #include "CKAll.h" #include "ARToolKitLogger.h" #include <ARToolKitPlus/TrackerSingleMarkerImpl.h> CKObjectDeclaration *FillBehaviorARTPlusDecl(); CKERROR CreateARTPlusProto(CKBehaviorPrototype **); void cleanUp(); int ARTPlus(const CKBehaviorContext& BehContext); int ARTPlusCallBack(const CKBehaviorContext& BehContext); bool ARTPlusInitialized = false; bool ARTPlusCorrectCamera = true; void argConvGlpara( float para[4][4], float gl_para[16] ); void argConvGlparaTrans( float para[4][4], float gl_para[16] ); ARToolKitPlus::TrackerSingleMarker *tracker = NULL; ARToolKitLogger logger; CKObjectDeclaration *FillBehaviorARTPlusDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Single Marker Tracker"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetVersion(0x00010000); od->SetCreationFunction(CreateARTPlusProto); od->SetDescription("Single Marker Tracker"); od->SetCategory("ARToolKitPlus"); od->SetGuid(CKGUID(0x6d8452a7, 0x94937df2)); od->SetAuthorGuid(CKGUID(0x56495254,0x4f4f4c53)); od->SetAuthorName("<NAME>"); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateARTPlusProto(CKBehaviorPrototype** pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Single Marker Tracker"); if (!proto) { return CKERR_OUTOFMEMORY; } //--- Inputs declaration proto->DeclareInput("In"); //--- Outputs declaration proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); //--- Input Parameters declaration proto->DeclareInParameter("Video Image", CKPGUID_TEXTURE); proto->DeclareInParameter("Camera-Param File", CKPGUID_STRING, "c:\\LogitechPro4000.dat"); proto->DeclareInParameter("Near Clip Plane", CKPGUID_FLOAT, "1.0"); proto->DeclareInParameter("Far Clip Plane", CKPGUID_FLOAT, "1000.0"); proto->DeclareInParameter("Enable Camera Correction", CKPGUID_BOOL, "TRUE"); //--- Output Parameters declaration proto->DeclareOutParameter("CameraMatrix", CKPGUID_MATRIX); proto->DeclareOutParameter("Error", CKPGUID_STRING, "Success"); //---- Local Parameters Declaration //proto->DeclareLocalParameter("ARTracker", CKPGUID_POINTER, NULL, 4); //---- Settings Declaration proto->SetBehaviorCallbackFct(ARTPlusCallBack, CKCB_BEHAVIORATTACH|CKCB_BEHAVIORDETACH|CKCB_BEHAVIORDELETE|CKCB_BEHAVIOREDITED|CKCB_BEHAVIORSETTINGSEDITED|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORPRESAVE|CKCB_BEHAVIORPOSTSAVE|CKCB_BEHAVIORRESUME|CKCB_BEHAVIORPAUSE|CKCB_BEHAVIORRESET|CKCB_BEHAVIORRESET|CKCB_BEHAVIORDEACTIVATESCRIPT|CKCB_BEHAVIORACTIVATESCRIPT|CKCB_BEHAVIORREADSTATE, NULL); proto->SetFunction(ARTPlus); *pproto = proto; return CK_OK; } int ARTPlus(const CKBehaviorContext& BehContext) { CKBehavior* beh = BehContext.Behavior; float nearclip = 1.0f; float farclip = 1000.0f; float* buffer = NULL; float gl_matirx[4][4]; beh->ActivateInput(0,FALSE); if(ARTPlusInitialized == false) { CKTexture* texture = NULL; CKSTRING camparam = NULL; float nearclip = 1.0f; float farclip = 1000.0f; CKBOOL enableCamCorr = TRUE; // Texture (Important, request the Object not the Value or the Ptr!!!) texture = CKTexture::Cast(beh->GetInputParameterObject(IN_VIDEO_TEXTURE)); if(texture == NULL) { beh->ActivateOutput(OUTPUT_ERROR); char string[] = "ERROR: No Texture Present"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKERR_NOTINITIALIZED; } int width = texture->GetWidth(); int height = texture->GetHeight(); int windowwidth = BehContext.CurrentRenderContext->GetWidth(); int windowheight = BehContext.CurrentRenderContext->GetHeight(); // Patternname camparam = (CKSTRING)(beh->GetInputParameterReadDataPtr(IN_CAMERA_PARAM_FILE)); // Fetch value for NearClip beh->GetInputParameterValue(IN_NEAR_CLIP_PLANE, &nearclip); // Fetch value for FarClip beh->GetInputParameterValue(IN_FAR_CLIP_PLANE, &farclip); // create a tracker that does: // - 12x12 sized marker images // - samples at a maximum of 12x12 // - works with luminance (gray) images // - can load a maximum of 10 pattern // - can detect a maximum of 12 patterns in one image tracker = new ARToolKitPlus::TrackerSingleMarkerImpl<12,12,12,20,20>(width, height); // set a logger so we can output error messages // tracker->setLogger(&logger); tracker->setPixelFormat(ARToolKitPlus::PIXEL_FORMAT_ABGR); tracker->setLoadUndistLUT(true); tracker->setImageProcessingMode(ARToolKitPlus::IMAGE_FULL_RES); // load a camera file. two types of camera files are supported: // - Std. ARToolKit // - MATLAB Camera Calibration Toolbox if(!tracker->init(camparam, nearclip, farclip)) // load std. ARToolKit camera file //if(!tracker->init("data/PGR_M12x0.5_2.5mm.cal", 1.0f, 1000.0f)) // load MATLAB file { printf("ERROR: init() failed\n"); delete tracker; tracker = NULL; beh->ActivateOutput(OUTPUT_ERROR); char string[] = "ERROR: init() failed"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKERR_NOTINITIALIZED; } // Fetch value for Camera Correction beh->GetInputParameterValue(IN_ENABLE_CAMERA_CORRECTION, &enableCamCorr); ARTPlusCorrectCamera = enableCamCorr==TRUE?true:false; // let's use lookup-table undistortion for high-speed // note: LUT only works with images up to 1024x1024 tracker->setUndistortionMode(ARToolKitPlus::UNDIST_LUT); // RPP is more robust than ARToolKit's standard pose estimator tracker->setPoseEstimator(ARToolKitPlus::POSE_ESTIMATOR_RPP); // beh->SetLocalParameterValue(LOCAL_TRACKER, (void *)tracker, 4); ARTPlusInitialized = true; } beh->ActivateOutput(OUTPUT_OK); // In development // ARToolKitPlus::TrackerSingleMarker *localTracker = (ARToolKitPlus::TrackerSingleMarker *)beh->GetLocalParameter(LOCAL_TRACKER); buffer = (float *)tracker->getProjectionMatrix(); argConvGlpara(gl_matirx, buffer); VxMatrix mat = VxMatrix(gl_matirx); // Set matrix beh->SetOutputParameterValue(OUT_CAMERA_TRANSFORM_MATRIX, &mat, 0); // Set error string char string[] = "Success"; beh->SetOutputParameterValue(OUT_ERROR_STRING, string, strlen(string)+1); return CKBR_OK; } int ARTPlusCallBack(const CKBehaviorContext& BehContext) { switch (BehContext.CallbackMessage) { case CKM_BEHAVIORATTACH: break; case CKM_BEHAVIORDETACH: break; case CKM_BEHAVIORDELETE: { cleanUp(); break; } case CKM_BEHAVIOREDITED: break; case CKM_BEHAVIORSETTINGSEDITED: break; case CKM_BEHAVIORLOAD: break; case CKM_BEHAVIORPRESAVE: break; case CKM_BEHAVIORPOSTSAVE: break; case CKM_BEHAVIORRESUME: break; case CKM_BEHAVIORPAUSE: break; case CKM_BEHAVIORRESET: { cleanUp(); break; } case CKM_BEHAVIORNEWSCENE: break; case CKM_BEHAVIORDEACTIVATESCRIPT: break; case CKM_BEHAVIORACTIVATESCRIPT: break; case CKM_BEHAVIORREADSTATE: break; } return CKBR_OK; } void cleanUp() { if(ARTPlusInitialized) { tracker->cleanup(); delete tracker; ARTPlusInitialized = false; } tracker = NULL; } void argConvGlpara( float para[4][4], float gl_para[16] ) { int i, j; for( j = 0; j < 4; j++ ) { for( i = 0; i < 4; i++ ) { para[j][i] = (gl_para[i*4+j]); } } } void argConvGlparaTrans( float para[4][4], float gl_para[16] ) { int i, j; for( j = 0; j < 4; j++ ) { for( i = 0; i < 4; i++ ) { para[i][j] = (gl_para[i*4+j]); } } } <file_sep>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* */ /* D L L F T P */ /* */ /* W I N D O W S */ /* */ /* P o u r A r t h i c */ /* */ /* V e r s i o n 3 . 0 */ /* */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define FTP4W_INCLUDES_AND_GENERAL + #include <windows.h> #include <windowsx.h> #include <tcp4w.h> /* external header file */ #include "port32.h" /* 16/32 bits */ #include "ftp4w.h" /* external header file */ #include "ftp4w_in.h" /* internal header file */ #include "rfc959.h" /* only for error codes */ extern LPProcData pFirstProcData; /* ******************************************************************* */ /* */ /* Partie V : Utilitaires Applicatifs */ /* */ /* ******************************************************************* */ /* ----------------------------------------------------------- */ /* ToolsLocateProcData : Retrouve la structure de données de */ /* la session */ /* ----------------------------------------------------------- */ LPProcData ToolsLocateProcData (void) { LPProcData pProcData; for ( pProcData = pFirstProcData ; pProcData != NULL && (*pProcData->fIdentifyThread)()!= pProcData->nThreadIdent ; pProcData = pProcData->Next ); return pProcData; } /* ToolsLocateProcData */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpDataPtr */ /* Renvoie un pointeur sur la structure */ /* ------------------------------------------------------------ */ LPProcData _export PASCAL FAR FtpDataPtr (void) { return ToolsLocateProcData (); } /* FtpDataPtr */ /* ------------------------------------------------------------ */ /* Fonction DLL FtpBufferPtr */ /* Renvoie un pointeur sur le buffer de donnees*/ /* ------------------------------------------------------------ */ LPSTR _export PASCAL FAR FtpBufferPtr (void) { return ToolsLocateProcData()->ftp.szInBuf; } /* FtpDataPtr */ /* -------------------------------------------------------------- */ /* Fonctions DLL de parametrage */ /* -------------------------------------------------------------- */ /* Remplace les defines suivants */ /* - FtpBytesTransferred() FtpDataPtr()->File.lPos */ /* - FtpBytesToBeTransferred() FtpDataPtr()->File.lTotal */ /* - FtpSetDefaultTimeOut(x) FtpDataPtr()->ftp.nTimeOut=x */ /* - FtpSetDefaultPort(x) FtpDataPtr()->ftp.nPort=x */ /* - FtpSetAsynchronousMode() FtpDataPtr()->File.bAsyncMode=TRUE */ /* - FtpSetSynchronousMode() FtpDataPtr()->File.bAsyncMode=FALSE*/ /* - FtpIsAsynchronousMode() FtpDataPtr()->File.bAsyncMode */ /* - FtpSetNewDelay(x) FtpDataPtr()->File.nDelay=x */ /* - FtpSetNewSlices(x,y) FtpDataPtr()->File.nAsyncAlone=x,\ */ /* FtpDataPtr()->File.nAsyncAlone=y */ /* -------------------------------------------------------------- */ /* redefinition of bad spelled functions */ long _export PASCAL FAR FtpBytesTransfered (void) { return FtpBytesTransferred(); } long _export PASCAL FAR FtpBytesToBeTransfered(void) { return FtpBytesToBeTransferred(); } /* the new functions */ long _export PASCAL FAR FtpBytesTransferred (void) {LPProcData p = ToolsLocateProcData(); return p==NULL ? 0 :p->File.lPos; } long _export PASCAL FAR FtpBytesToBeTransferred(void) {LPProcData p = ToolsLocateProcData(); return p==NULL ? 0 :p->File.lTotal; } void _export PASCAL FAR FtpSetDefaultTimeOut(int x) { ToolsLocateProcData()->ftp.nTimeOut=x; /* x seconds */ } void _export PASCAL FAR FtpSetDefaultPort(int x) { ToolsLocateProcData()->ftp.nPort=(short) x; } void _export PASCAL FAR FtpSetAsynchronousMode(void) { ToolsLocateProcData()->File.bAsyncMode=TRUE; } void _export PASCAL FAR FtpSetSynchronousMode(void) { ToolsLocateProcData()->File.bAsyncMode=FALSE; } BOOL _export PASCAL FAR FtpIsAsynchronousMode(void) { return ToolsLocateProcData()->File.bAsyncMode; } void _export PASCAL FAR FtpSetNewDelay(int x) { ToolsLocateProcData()->File.nDelay=x; /* x millisec */ } void _export PASCAL FAR FtpSetNewSlices(int x,int y) { LPProcData p = ToolsLocateProcData(); p->File.nAsyncAlone=x, p->File.nAsyncAlone=y; } void _export PASCAL FAR FtpSetPassiveMode (BOOL bPassif) { ToolsLocateProcData()->ftp.bPassif = bPassif; } void _export PASCAL FAR FtpLogTo (HFILE hLogFile) { ToolsLocateProcData()->ftp.hLogFile = hLogFile; } void _export PASCAL FAR FtpEnableDebugging (void) { Tcp4uEnableLog (0xFFFF); } /* ------------------------------------------------------------ */ /* Fonction DLL FtpSetVerboseMode */ /* ------------------------------------------------------------ */ int _export PASCAL FAR FtpSetVerboseMode (BOOL bMode, HWND hWnd, UINT wMsg) { LPProcData pProcData; pProcData = ToolsLocateProcData (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; pProcData->ftp.bVerbose = bMode; pProcData->VMsg.hVerboseWnd = hWnd; pProcData->VMsg.nVerboseMsg = wMsg; return FTPERR_OK; } /* SetVerboseMode */ <file_sep> ----------> DEV 35 Users - no cmo available ! 1.0 General Notes 1.1 Installation - copy from BuildingBlocks\vtTNL.dll to your dev\BuildingBlocks directory - for testing of your application I recommend : - copy the entire Dev-YOUR-VERSION directory into your dev directory ! - call vtNetServer.bat(a custom player in console mode) to start a cmo driven server or start "xConsoleServer.exe" (virtools independent server module !) 2.0 Usage - start the server : xConsoleServer.exe or the embedded one ! - create a session ( with password ) - join to this session - now you can send messages and attach parameters of the type : - Vector 2/3/4 - D - String (256 chars per message !) - int /float Documentation in progress ! ;-) 3.0 License issues : This distribution is for free and provided as it is ! Updates : Check vtmod svn details ! Bugs : please post it preferably on vtmod or theswapmeet. <file_sep>#ifndef __VTWINDOW_H_ #define __VTWINDOW_H_ #include <Windows.h> #include "BaseMacros.h" #include <BaseTyps.h> class CCustomPlayer; class vtWindow { public: vtWindow(); int CreateAsChild(long *parent); int Run(); int Init(); void ParseCommandLine(const char*cmdLine); void Destroy(); int Tick(); int DoFrame(); int Show(int ShowFlags); int GetWidth(); int GetHeight(); int UpdateRenderSize(int w,int h); //send a message to a certain object given by name or when not specified as broadcast int SendMessage(char *targetObject,char *message,int id0,int id1,int id2,int value); int SendMessage(char *targetObject,char *message,int id0,int id1,int id2,float value); int SendMessage(char *targetObject,char *message,int id0,int id1,int id2,char* value); //pseudo message sending to csharp : int HasMessages(); int GetNumMessages(); char *GetMessageName(int messageID); int GetNumParameters(int messageID); int GetMessageParameterType(int messageID,int parameterSubID); int GetMessageValueInt(int messageID,int parameterSubID); float GetMessageValueFloat(int messageID,int parameterSubID); char* GetMessageValueStr(int messageID,int parameterSubID); void CleanMessages(); void DeleteMessage(int messageID); void Pause(); void Play(); void LoadCompostion(char *file); void Terminate(int flags); int WndProc( long *hWnd, int uMsg, long * wParam, long* lParam ); protected: CCustomPlayer *m_Player; CONSOLE_SCREEN_BUFFER_INFO m_SavedConsoleInfo; private: }; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// #endif<file_sep>########################################################################################################## # VIRTOOLS 2001 # OpenGL List of Video cards with problems # # + To identify a video card you can either give the vendor,renderer and version of that card as found in # the caps file generated by engineTest.exe but it is specific to OpenGL or otherwise a card can be identified # by the description string given in the same file or in the preferences box in the interface... # + Each video card section must have a different name # # # Syntax: # # <VIDEO CARD>: Must be Set at the beginning of each video card, all others # tokens are optionnal (but we need at least Company/Renderer or DeviceDesc to know which card # we are talking about... # # Company : Company name # # Renderer: Useless if all the video cards from a vendor have the same problem otherwise name # of the chipset that causes the problem. # # DeviceDesc: Identification string given in the Interface or Engine Text that can be use instead of # giving the vendor & renderer (See Below for Examples) # # ExactVersion: To be set if only a specific version of the driver contains problems # # UpToVersion: To be set if driver before a given version contain problem: This indicates that the bug # was corrected in the given version number driver but not before... # # OnlyIn16Bpp: # OnlyIn32Bpp: Set this token if the problem only arises in specific resolution (16 or 32 bpp) # # Os: (SubSection) To be set if the problem only arises on specific Operating systems,this section contains the list of OS with problems # Available OS: # VXOS_WIN95,VXOS_WIN98,VXOS_WINNT4,VXOS_WIN2K,VXOS_WINXP,VXOS_MACOS9,VXOS_MACOSX,VXOS_LINUXX86 # # Bug_RGBA: (SubSection) This section is followed by a list of video texture pixel formats that present # Red & Blue swapping problem so that the rasterizer know it must invert them # when loading a texture with the given video format... # Available formats : # _32_ARGB8888,_32_RGB888,_24_RGB888,_16_RGB565,_16_RGB555,_16_ARGB1555,_16_ARGB4444,,_8_RGB332 # _8_ARGB2222,_DXT1,_DXT3,_DXT5 # # MaxTextureWidth,MaxTextureHeight: some drivers do not really support the maximum texture width they gave in their caps... # # Bug_ClampEdge: Some implementations present the ClampToEdge extension but do not seem to really implement it... # # </VIDEO CARD> # ##################################################################################################################### ################################################################################# # Ati Radeon : Texture format bug on less than 16 bit textures # with alpha information in OpenGL <ATI RADEON> Company = ATI Technologies Inc. Renderer = Radeon <Bug_RGBA> _16_ARGB1555 = 1 _16_ARGB4444 = 1 _8_ARGB2222 = 1 </Bug_RGBA> </ATI RADEON> ################################################################################# # Matrox G400 : Texture format bug on less than 16 bit textures # FALSE MaxtextureWidth (2048 does not work) <MATROX G400> Company = Matrox Graphics Inc. Renderer = Matrox G400 <Bug_RGBA> _16_RGB555 = 1 _16_RGB565 = 1 _16_ARGB1555 = 1 _16_ARGB4444 = 1 _8_RGB332 = 1 _8_ARGB2222 = 1 _DXT1 = 1 _DXT3 = 1 </Bug_RGBA> MaxTextureWidth = 1024 MaxTextureHeight = 1024 </MATROX G400> ################################################################################# # Matrox G200 : Texture format bug on less than 16 bit textures # Unsuppoted ClampEdge extension # FALSE MaxtextureWidth (2048 does not work) <MATROX G200> Company = Matrox Graphics Inc. Renderer = Matrox G200 <Bug_RGBA> _16_RGB555 = 1 _16_RGB565 = 1 _16_ARGB1555 = 1 _16_ARGB4444 = 1 _8_RGB332 = 1 _8_ARGB2222 = 1 _DXT1 = 1 _DXT3 = 1 _DXT5 = 1 </Bug_RGBA> Bug_ClampEdge = 1 MaxTextureWidth = 1024 MaxTextureHeight = 1024 </MATROX G200> ################################################################################# # 3DFX VOODOO5 : # FALSE MaxtextureWidth (2048 does not work) <VOODOO 5500AGP> Company = 3Dfx Interactive Inc. Renderer = 3Dfx/Voodoo5 (tm)/2 TMUs/32 MB SDRAM/KNI/ICD (Oct 24 2000) MaxTextureWidth = 1024 MaxTextureHeight = 1024 </VOODOO 5500AGP> ################################################################################# # Ati Rage Pro : Texture format bug on less than 16 bit textures # with alpha information in OpenGL <ATI RAGEPRO> Company = ATI Renderer = RagePRO <Os> VXOS_WIN2K = 1 </Os> <Bug_RGBA> _16_ARGB1555 = 1 _16_ARGB4444 = 1 _8_ARGB2222 = 1 _DXT1 = 1 _DXT3 = 1 </Bug_RGBA> </ATI RAGEPRO> ################################################################################# # Ati Rage Pro on W98 (different renderer name): Texture format bug on less than 16 bit textures # with alpha information in OpenGL <ATI RAGEPRO98> Company = ATI Renderer = RAGE PRO <Os> VXOS_WIN98 = 1 </Os> <Bug_RGBA> _32_ARGB8888 = 1 _32_RGB888 = 1 _16_ARGB1555 = 1 _16_ARGB4444 = 1 _8_ARGB2222 = 1 _DXT1 = 1 _DXT3 = 1 _DXT5 = 1 </Bug_RGBA> </ATI RAGEPRO98> ################################################################################# # Ati Rage Pro on WIN NT4 (different renderer name): Texture format bug on less than 16 bit textures # with alpha information in OpenGL <ATI RAGEPRONT> Company = ATI Renderer = RagePRO <Os> VXOS_WINNT4 = 1 </Os> <Bug_RGBA> _16_ARGB1555 = 1 _16_ARGB4444 = 1 _8_ARGB2222 = 1 _DXT1 = 1 _DXT3 = 1 </Bug_RGBA> </ATI RAGEPRONT> ################################################################################# # Power VR test : Texture format bug with DXT1 format Red Blue swapping <PowerVR KYRO1> Company = Imagination Technologies Renderer = PowerVR KYRO <Bug_RGBA> _DXT1 = 1 </Bug_RGBA> </PowerVR KYRO1> ################################################################################# # ATI Radeon test : Texture format bug with 1555 format Red Blue swapping <ATI Radeon DDR> Company = ATI Technologies Inc. Renderer = Radeon DDR x86/SSE <Os> VXOS_WINNT4 = 1 VXOS_WIN2K = 1 </Os> <Bug_RGBA> _16_ARGB1555 = 1 </Bug_RGBA> </ATI Radeon DDR> ################################################################################# # I740 feedback : Texture Red Blue swapping <Intel I740> Company = Intel Renderer = Intel740 <Os> VXOS_WIN98 = 1 </Os> <Bug_RGBA> _16_ARGB1555 = 1 _32_ARGB8888 = 1 _32_RGB888 = 1 _16_ARGB4444 = 1 _8_ARGB2222 = 1 _DXT1 = 1 _DXT3 = 1 _DXT5 = 1 </Bug_RGBA> </Intel I740> ################################################################################# # ATI Radeon test : Texture format bug with 1555 format Red Blue swapping <ATI All> Company = ATI Technologies Inc. # No renderer specified : all the ATI cards # Renderer = Radeon 7200 DDR x86/SSE <Os> VXOS_WINXP = 1 </Os> <Bug_RGBA> _16_ARGB1555 = 1 </Bug_RGBA> </ATI All> ################################################################################# # 3D Labs Wildcat test : # Texture format bug with 565 format Red Blue swapping # FALSE MaxtextureWidth (2048 does not work) ################################################################################# <3Dlabs WILDCAT VP> Company = 3Dlabs Renderer = Wildcat VP970 - GL2 <Bug_RGBA> _16_RGB565 = 1 _8_ARGB2222 = 1 </Bug_RGBA> MaxTextureWidth = 1024 MaxTextureHeight = 1024 </3Dlabs WILDCAT VP> <file_sep>#include "StdAfx.h" #include "vtcxglobal.h" #include "InitMan.h" #include "vt_python_funcs.h" #ifdef CK_LIB #define RegisterBehaviorDeclarations Register_TOOLS_BehaviorDeclarations #define InitInstance _TOOLS_InitInstance #define ExitInstance _TOOLS_ExitInstance #define CKGetPluginInfoCount CKGet_TOOLS_PluginInfoCount #define CKGetPluginInfo CKGet_TOOLS_PluginInfo #define g_PluginInfo g_TOOLS_PluginInfo #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #endif CKPluginInfo g_PluginInfo; vt_python_man *pym = NULL; PLUGIN_EXPORT int CKGetPluginInfoCount(){return 2;} CKERROR InitInstanc1e(CKContext* context); CKERROR InitInstance(CKContext* context) { CKParameterManager* pm = context->GetParameterManager(); vt_python_man* initman =new vt_python_man(context); pym = initman; pym->py = NULL; initman->pLoaded = false; initman->RegisterVSL(); return CK_OK; } CKERROR ExitInstance(CKContext* context) { vt_python_man* initman =(vt_python_man*)context->GetManagerByGuid(INIT_MAN_GUID); DestroyPython(); delete initman; return CK_OK; } #define INIT_BEH_GUID CKGUID(0x587c6467,0x4b970a1) PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) { switch (Index) { case 0: g_PluginInfo.m_Author = VTCX_AUTHOR; g_PluginInfo.m_Description = "Python Building Blocks"; g_PluginInfo.m_Extension = ""; g_PluginInfo.m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo.m_Version = 0x000001; g_PluginInfo.m_InitInstanceFct = NULL; g_PluginInfo.m_ExitInstanceFct = NULL; g_PluginInfo.m_GUID = INIT_BEH_GUID; g_PluginInfo.m_Summary = "Python Building Blocks"; break; case 1: g_PluginInfo.m_Author = VTCX_AUTHOR; g_PluginInfo.m_Description = "Python Manager"; g_PluginInfo.m_Extension = ""; g_PluginInfo.m_Type = CKPLUGIN_MANAGER_DLL; g_PluginInfo.m_Version = 0x000001; g_PluginInfo.m_InitInstanceFct = InitInstance; g_PluginInfo.m_ExitInstanceFct = ExitInstance; g_PluginInfo.m_GUID = INIT_MAN_GUID; g_PluginInfo.m_Summary = "Python Manager"; break; } return &g_PluginInfo; } PLUGIN_EXPORT void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg); void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) { RegisterBehavior(reg,FillBehaviorCallPythonFuncDecl); RegisterBehavior(reg,FillBehaviorCallPythonFuncDecl2); RegisterBehavior(reg,FillBehaviorLoadPythonDecl); RegisterBehavior(reg,FillBehaviorDestroyPythonDecl); RegisterBehavior(reg,FillBehaviorGetNextBBIdDecl); } <file_sep>#ifndef _XDISTRIBUTED_RECT_H_ #define _XDISTRIBUTED_RECT_H_ #include "xDistributedProperty.h" #include "xNetMath.h" class xDistributedRect : public xDistributedProperty { public: Point3F mData; protected: private: }; #endif<file_sep>#ifndef __P_VEHICLE_ALL_H__ #define __P_VEHICLE_ALL_H__ #include <stdlib.h> #include <limits.h> //using namespace std::numeric_limits; #define XFLT_EPSILON_MIN 0.00001f #define XFLT_EPSILON_MAX FLT_MAX #define xCheckFloat(n) ((fabs(n) > XFLT_EPSILON_MIN && n < XFLT_EPSILON_MAX ) ? n : 0.0f) typedef enum pVehicleProcessoptions { pVPO_Lat_Damping=(1<<0), pVPO_Long_Damping=(1<<1), pVPO_SA_Damping=(1<<2), pVPO_SA_Delay=(1<<3), pVPO_SV_Tansa=(1<<4), pVPO_SA_DownSettle=(1<<5), pVPO_CheckLowSpeed=(1<<6), pVPO_Wheel_LockAdjust=(1<<7), pVPO_Wheel_UsePHYSX_Load=(1<<8), pVPO_Wheel_UsePHYSX_CONTACT_DATA=(1<<9), pVPO_Wheel_DoGregor=(1<<10), pVPO_Wheel_DampVerticalVelocityReversal=(1<<11), pVPO_Wheel_IntegrateImplicitVertical=(1<12), pVPO_Wheel_DiffDirect=(1<<13), pVPO_Engine_UseHardRevlimit=(1<<14), pVPO_Forces_No_Lateral=(1<<15), }; #include "pEngine.h" #include "pVehicleTypes.h" #include "pGearbox.h" #include "pDifferential.h" #include "pSteer.h" #endif <file_sep>/*********************************************************************NVMH4**** Path: SDK\LIBS\inc\shared File: NV_StringFuncs.h Copyright NVIDIA Corporation 2002 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Comments: A collection of useful string functions, built upon std::string They are not all meant to be fast. Many return vectors of strings, which will require string copies and lots of work by the STL functions. For processing large strings or a lot of string data you will probably want to devise your own routines. A demo of using the functions is provided in: SDK\DEMOS\common\src\NV_StringFuncs ******************************************************************************/ #ifndef _NV_STRINGFUNCS_GJ_H #define _NV_STRINGFUNCS_GJ_H #pragma warning(disable : 4786) // STL warning #include <Windows.h> #include <string> #include <vector> #include <list> #include <stdlib.h> #include <tchar.h> // sfsizet is size type for the string class used typedef std::string::size_type sfsizet; typedef std::basic_string<TCHAR> tstring; namespace NVStringConv { // use as an alternative to wcstombs() std::string WStringToString( const std::wstring * in_pwstring ); std::string WStringToString( std::wstring & in_wstring ); std::string lpcwstrToString( LPCWSTR in_lpcwstr ); std::wstring StringToWString( const std::string * in_pString ); std::wstring StringToWString( std::string & in_String ); std::wstring lpcstrToWString( LPCSTR str ); }; // namespace NVStringConv ///////////////////////////////////////////////////////////////////// // macro to expand vector of anything into single string // example c is "%u " and the %<type> must match type held in vector // Example: // string dest; // vector< int > vint; // VEC_TO_STR( dest, vint, "%d " ); // #ifndef VEC_TO_STR #define VEC_TO_STR( a, b, c ) \ { \ for( int vectocnt = 0; vectocnt < b.size(); vectocnt++ ) \ { a += StrPrintf( c, b.at(vectocnt) ); \ } \ } #endif ////////////////////////// // Convert list of some type to vector of same type // L is list, V is vector, T is type // Example: // list< string > lStr; // vector< string > vStr; // lStr.push_back( "a" ); // lStr.push_back( "b" ); // LIST_TO_VEC( lStr, vStr, std::string ); #ifndef LIST_TO_VEC #define LIST_TO_VEC( L, V, T ) \ { \ std::list< T >::const_iterator ltovecmacroiter; \ for( ltovecmacroiter = L.begin(); ltovecmacroiter != L.end(); ltovecmacroiter++ ) \ { \ V.push_back( *ltovecmacroiter ); \ } \ } #endif ////////////////////////// // Convert vector of some type to list of same type // L is list, V is vector, T is type // #ifndef VEC_TO_LIST #define VEC_TO_LIST( V, L, T ) \ { \ for( int vtolistc=0; vtolistc < V.size(); vtolistc++ ) \ { L.push_back( V.at(vtolistc) ); \ } \ } #endif ///////////////////////////////////////////////////////////////////// // Create a string using va_args, just like printf, sprintf, etc. std::string StrPrintf( const char * szFormat, ... ); std::string StrToUpper( const std::string & strIn ); std::string StrToLower( const std::string & strIn ); // Writes each string in the vector to a single output // string, separating each by a space. std::string StrsToString( const std::vector< std::string > & vstrIn ); // same, but lets you specify the separator between strings std::string StrsToString( const std::vector< std::string > & vstrIn, const std::string & separator ); std::string StrsToString( const std::list< std::string > & lstrIn, const std::string & separator ); // Like CString::Replace() // Sequence and it's replacement can be different lengths or empty std::string StrReplace( const std::string & sequence_to_replace, const std::string & replacement_string, const std::string & strIn ); // same as above, only it modifies pOut and also returns pOut std::string * StrReplace( const std::string & sequence_to_replace, const std::string & replacement_string, const std::string & strIn, std::string * pOut, bool bVerbose = false ); // applies strtok repeatedly & acumulates ouput tokens // in output string separated by spaces std::string StrTokenize( const std::string & strIn, const std::string & delimiters ); // Same as above, but allows you to specify the separator between // tokens in the output std::string StrTokenize( const std::string & strIn, const std::string & delimiters, const std::string & output_separator ); sfsizet StrFindCaseless( const std::string & strSearchIn, sfsizet start_pos, const std::string & strSearchFor ); std::vector< sfsizet > StrFindAllCaseless( const std::string & strSearchIn, sfsizet start_pos, const std::string & strSearchFor ); std::vector< sfsizet > StrFindAll( const std::string & strSearchIn, sfsizet start_pos, const std::string & strSearchFor ); std::vector< std::string > StrSort( const std::vector< std::string > & vStrIn ); tstring GetFilenameFromFullPath( const tstring & full_path ); ///////////////////////////////////////////////////////////////////// /* More ideas for functions to implement SortCaseless Sort // case sensitive _stricmp - compare two strings without regard to case _strrev = reverse string */ #endif <file_sep>#include "stdafx.h" #include "DistributedNetworkClassDialogCallback.h" #include "DistributedNetworkClassDialogMenu.h" //static plugin interface that allow direct communication with Virtools Dev PluginInterface* s_Plugininterface = NULL; //main plugin callback for Virtools Dev void PluginCallback(PluginInfo::CALLBACK_REASON reason,PluginInterface* plugininterface) { switch(reason) { case PluginInfo::CR_LOAD: { s_Plugininterface = plugininterface; InitMenu(); UpdateMenu(); }break; case PluginInfo::CR_UNLOAD: { RemoveMenu(); s_Plugininterface = NULL; }break; case PluginInfo::CR_NEWCOMPOSITIONNAME: { }break; case PluginInfo::CR_NOTIFICATION: { }break; } } <file_sep>#include <StdAfx.h> #include "vtBaseManager.h" /* vtBaseManager::vtBaseManager(CKContext *context,CKGUID guid,char* name): CKBaseManager(context,guid,name) { } */ /* vtBaseManager::~vtBaseManager() { } */<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SetProjection Camera // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #define CKPGUID_PROJECTIONTYPE CKDEFINEGUID(0x1ee22148, 0x602c1ca1) CKObjectDeclaration *FillBehaviorSetProjectionDecl(); CKERROR CreateSetProjectionProto(CKBehaviorPrototype **pproto); int SetProjection(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSetProjectionDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Set Projection"); od->SetDescription("Sets the Projection Type of the Camera."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Projection Type: </SPAN>the type of projection you want to use - orthographic or perspective.<BR> <BR> Note : The orthographic mode is useful to render simple object when depth is not important since the vertices transformation is much simpler.<BR> <BR> See Also: 'Orthographic Zoom'.<BR> */ od->SetCategory("Cameras/Basic"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0xe444e666, 0x4eee6eee)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetProjectionProto); od->SetCompatibleClassId(CKCID_CAMERA); return od; } CKERROR CreateSetProjectionProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set Projection"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Projection Type", CKPGUID_PROJECTIONTYPE, "Orthographic"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetProjection); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int SetProjection(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKCamera *cam = (CKCamera *) beh->GetTarget(); if( !cam ) return CKBR_OWNERERROR; // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); // Get projection type int type=1; beh->GetInputParameterValue(0,&type); cam->SetProjectionType( type ); return CKBR_OK; } <file_sep>//////////////////////////////////////////////////////////////////////////////// // // ARPlusBehavior // -------------- // // Description: // Defines the initialization routines for the plugin DLL. Done by the Virtools // wizzard // // Version 1.0 : First Release // // Known Bugs : None // // Copyright <NAME> <<EMAIL>>, University of Paderborn //////////////////////////////////////////////////////////////////////////////// #include "CKAll.h" #include "ARToolKitPlusManager.h" //---------------------------------------------------------------- // //! \brief Switches between static library or dll // #ifdef CK_LIB #define RegisterBehaviorDeclarations Register_VTAR_BehaviorDeclarations #define InitInstance _VTAR_InitInstance #define ExitInstance _VTAR_ExitInstance #define CKGetPluginInfoCount CKGet_VTAR_PluginInfoCount #define CKGetPluginInfo CKGet_VTAR_PluginInfo #define g_PluginInfo g_PluginInfo #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #endif CKERROR InitInstance(CKContext* context) { #ifdef Webpack InitInstanceCamera(context); #endif new ARToolKitPlusManager(context); return CK_OK; } CKERROR ExitInstance(CKContext* context) { // This function will only be called if the dll is unloaded explicitely // by a user in Virtools Dev interface // Otherwise the manager destructor will be called by Virtools runtime directly delete context->GetManagerByGuid(ARToolKitPlusManagerGUID); #ifdef Webpack ExitInstanceCamera(context); #endif return CK_OK; } /************************************************************************/ /* */ /************************************************************************/ #ifdef WebPack extern CKERROR InitInstanceCamera(CKContext* context); extern CKERROR ExitInstanceCamera(CKContext* context); extern int RegisterCameraBeh(XObjectDeclarationArray *reg); #endif #ifdef WebPack #define GUID_MODULE_BUILDING_BLOCKS CKGUID(0x12d94eba,0x47057415) #else #define GUID_MODULE_BUILDING_BLOCKS CKGUID(0x6d8452a7, 0x94937df2) #endif /************************************************************************/ /* */ /************************************************************************/ #define PLUGIN_COUNT 2 CKPluginInfo g_PluginInfo[PLUGIN_COUNT]; int CKGetPluginInfoCount() { return PLUGIN_COUNT; } /* ******************************************************************* * Function: CKPluginInfo* CKGetPluginInfo( int index ) * * Description : This function takes an index and returns a corresponding plugin desciptor * * Parameters : * index, index of the plugin information to get * * Returns : pointer to the requested plugin information * ******************************************************************* */ PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index); PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) { int Plugin = 0; // Register ARTPlus g_PluginInfo[Plugin].m_Author = "<NAME>"; g_PluginInfo[Plugin].m_Description = "The ARTPlus building block initialize the ARToolKitPlus for Single marker detection"; g_PluginInfo[Plugin].m_Extension = ""; g_PluginInfo[Plugin].m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo[Plugin].m_Version = 0x00000001; g_PluginInfo[Plugin].m_InitInstanceFct = NULL; g_PluginInfo[Plugin].m_GUID = GUID_MODULE_BUILDING_BLOCKS; g_PluginInfo[Plugin].m_Summary = "ARToolKitPlus Tracker for Single Marker"; Plugin++; /* // Register ARTPlusPatternTransformation g_PluginInfo[Plugin].m_Author = "<NAME>"; g_PluginInfo[Plugin].m_Description = "Buildingblock that transforms a given object by the detected transformation matrix of the corrosponding pattern (single marker)"; g_PluginInfo[Plugin].m_Extension = ""; g_PluginInfo[Plugin].m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo[Plugin].m_Version = 0x00000001; g_PluginInfo[Plugin].m_InitInstanceFct = NULL; g_PluginInfo[Plugin].m_GUID = CKGUID(0x6b733302,0x12d23c1f); g_PluginInfo[Plugin].m_Summary = "ARToolKitPlus Pattern Transformation"; Plugin++; // Register ARToolKitPlusDetect g_PluginInfo[Plugin].m_Author = "<NAME>"; g_PluginInfo[Plugin].m_Description = "Buildingblock that detects pattern (single marker) in the given video image"; g_PluginInfo[Plugin].m_Extension = ""; g_PluginInfo[Plugin].m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo[Plugin].m_Version = 0x00000001; g_PluginInfo[Plugin].m_InitInstanceFct = NULL; g_PluginInfo[Plugin].m_GUID = CKGUID(0x1ff46552,0x6c31e58); g_PluginInfo[Plugin].m_Summary = "ARToolKitPlus Single Marker Detection"; Plugin++; //Register ARTPlusDetectionAndTransformation g_PluginInfo[Plugin].m_Author = "<NAME>"; g_PluginInfo[Plugin].m_Description = "Buildingblock that detects a pattern (single marker) and transforms the related Object"; g_PluginInfo[Plugin].m_Extension = ""; g_PluginInfo[Plugin].m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo[Plugin].m_Version = 0x00000001; g_PluginInfo[Plugin].m_InitInstanceFct = NULL; g_PluginInfo[Plugin].m_GUID = CKGUID(0x2f9e2472,0x639e208c); g_PluginInfo[Plugin].m_Summary = "ARToolKitPlus Single Marker Detection and Transformation"; Plugin++; // Register ARTPlusMulti g_PluginInfo[Plugin].m_Author = "<NAME>"; g_PluginInfo[Plugin].m_Description = "The ARTPlus building block initialize the ARToolKitPlus for multi marker detection"; g_PluginInfo[Plugin].m_Extension = ""; g_PluginInfo[Plugin].m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo[Plugin].m_Version = 0x00000001; g_PluginInfo[Plugin].m_InitInstanceFct = NULL; g_PluginInfo[Plugin].m_GUID = CKGUID(0xa59f1,0x3d486f81); g_PluginInfo[Plugin].m_Summary = "ARToolKitPlus Tracker for Multi Marker"; Plugin++; //Register ARTPlusMultiDetectionAndTransformation g_PluginInfo[Plugin].m_Author = "<NAME>"; g_PluginInfo[Plugin].m_Description = "Buildingblock that detects a pattern (multi marker) and transforms the related Object"; g_PluginInfo[Plugin].m_Extension = ""; g_PluginInfo[Plugin].m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo[Plugin].m_Version = 0x00000001; g_PluginInfo[Plugin].m_InitInstanceFct = NULL; g_PluginInfo[Plugin].m_GUID = CKGUID(0x61232b96,0x598d625a); g_PluginInfo[Plugin].m_Summary = "ARToolKitPlus Multi Marker Detection and Transformation"; Plugin++; */ // Register ARToolKitPlusManager g_PluginInfo[Plugin].m_Author = "<NAME>"; g_PluginInfo[Plugin].m_Description = "This manager is used for setting the right camera projection matrix if an ARToolKitPlus building block is used and the flag ARTPlus(Multi)CorrectCamera is set"; g_PluginInfo[Plugin].m_Extension = ""; g_PluginInfo[Plugin].m_Type = CKPLUGIN_MANAGER_DLL; g_PluginInfo[Plugin].m_Version = 0x00000001; g_PluginInfo[Plugin].m_InitInstanceFct = InitInstance; g_PluginInfo[Plugin].m_ExitInstanceFct = ExitInstance; g_PluginInfo[Plugin].m_GUID = ARToolKitPlusManagerGUID; g_PluginInfo[Plugin].m_Summary = "ARToolKitPlus Manager"; return &g_PluginInfo[Index]; } void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) { RegisterBehavior(reg, FillBehaviorARTPlusDecl); RegisterBehavior(reg, FillBehaviorARTPlusMultiDecl); RegisterBehavior(reg, FillBehaviorARToolKitPlusDetectDecl); RegisterBehavior(reg, FillBehaviorARTPlusPatternTransformationDecl); RegisterBehavior(reg, FillBehaviorARTPlusDetectionAndTransformationDecl); RegisterBehavior(reg, FillBehaviorARTPlusMultiDetectionAndTransformationDecl); #ifdef WebPack RegisterCameraBeh(reg); #endif } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" pJointPulley::pJointPulley(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Pulley) { } void pJointPulley::setLocalAnchorA(VxVector anchor) { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.localAnchor[0] = pMath::getFrom(anchor); joint->loadFromDesc(descr); } VxVector pJointPulley::getLocalAnchorA() { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return VxVector(); joint->saveToDesc(descr); return pMath::getFrom(descr.localAnchor[0]); } ////////////////////////////////////////////////////////////////////////// void pJointPulley::setLocalAnchorB(VxVector anchor) { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.localAnchor[1] = pMath::getFrom(anchor); joint->loadFromDesc(descr); } VxVector pJointPulley::getLocalAnchorB() { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return VxVector(); joint->saveToDesc(descr); return pMath::getFrom(descr.localAnchor[1]); } ////////////////////////////////////////////////////////////////////////// void pJointPulley::setPulleyA(VxVector pulley) { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.pulley[0] = pMath::getFrom(pulley); joint->loadFromDesc(descr); } VxVector pJointPulley::getPulleyA() { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return VxVector(); joint->saveToDesc(descr); return pMath::getFrom(descr.pulley[0]); } ////////////////////////////////////////////////////////////////////////// void pJointPulley::setPulleyB(VxVector pulley) { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.pulley[1] = pMath::getFrom(pulley); joint->loadFromDesc(descr); } VxVector pJointPulley::getPulleyB() { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return VxVector(); joint->saveToDesc(descr); return pMath::getFrom(descr.pulley[1]); } ////////////////////////////////////////////////////////////////////////// void pJointPulley::setStiffness(float stiffness) { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.stiffness= stiffness; joint->loadFromDesc(descr); } float pJointPulley::getStiffness() { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return -1.0f; joint->saveToDesc(descr); return descr.stiffness; } ////////////////////////////////////////////////////////////////////////// void pJointPulley::setRatio(float ratio) { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.ratio= ratio; joint->loadFromDesc(descr); } float pJointPulley::getRatio() { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return -1.0f; joint->saveToDesc(descr); return descr.ratio; } ////////////////////////////////////////////////////////////////////////// void pJointPulley::setDistance(float distance) { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.distance= distance; joint->loadFromDesc(descr); } float pJointPulley::getDistance() { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return -1.0f; joint->saveToDesc(descr); return descr.distance; } ////////////////////////////////////////////////////////////////////////// void pJointPulley::setRigid( bool rigid ) { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (rigid) { descr.flags|=NX_PJF_IS_RIGID; }else{ descr.flags&=~NX_PJF_IS_RIGID; } joint->loadFromDesc(descr); } bool pJointPulley::isRigid() { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return -1.0f; joint->saveToDesc(descr); return ( descr.flags & NX_PJF_IS_RIGID ); } ////////////////////////////////////////////////////////////////////////// pMotor pJointPulley::getMotor() { NxPulleyJointDesc descr; NxPulleyJoint *joint = static_cast<NxPulleyJoint*>(getJoint());joint->saveToDesc(descr); NxMotorDesc mDescr = descr.motor; pMotor result; result.freeSpin = mDescr.freeSpin; result.targetVelocity= mDescr.velTarget; result.maximumForce = mDescr.maxForce; return result; } void pJointPulley::setMotor(pMotor motor) { NxPulleyJointDesc descr; NxPulleyJoint *joint = static_cast<NxPulleyJoint*>(getJoint());joint->saveToDesc(descr); NxMotorDesc mDescr = descr.motor; if (motor.maximumForce!=0.0f && motor.targetVelocity !=0.0f ) { mDescr.freeSpin = motor.freeSpin; mDescr.velTarget= motor.targetVelocity; mDescr.maxForce= motor.maximumForce; descr.flags |= NX_PJF_MOTOR_ENABLED; joint->setMotor(mDescr); descr.motor = mDescr; }else{ descr.flags &=~NX_PJF_MOTOR_ENABLED; } int flagsNow = descr.flags; int isValid = descr.isValid(); joint->loadFromDesc(descr); } ////////////////////////////////////////////////////////////////////////// void pJointPulley::enableCollision( bool collision ) { NxPulleyJointDesc descr; NxPulleyJoint*joint = static_cast<NxPulleyJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (collision) { descr.jointFlags |= NX_JF_COLLISION_ENABLED; }else descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; joint->loadFromDesc(descr); } <file_sep>//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by CPResource.rc // #define IDD_ABOUTBOX 100 #define IDR_MAINFRAME 128 #define IDD_DIALOGSETUP 129 #define IDI_VIRTOOLS 135 #define IDR_LICENSE 137 #define IDR_ABOUT 138 #define IDD_DIALOGINIT 146 #define IDD_SPLASH 147 #define IDS_ABOUT_ABOUTTEXTss 200 #define IDS_ABOUT_THANKSTOTEXT 201 #define IDS_ABOUT_ABOUT 202 #define IDS_ABOUT_THANKSTO 203 #define IDS_ABOUT_LICENSEAGREEMENT 204 #define IDC_STATIC_LOADING 1000 #define IDC_FULLSCREENDRIVERLIST 1001 #define IDC_WINDOWEDDRIVERLIST 1002 #define IDC_FULLSCREENMODELIST 1003 #define IDC_FULLSCREEN32BITS 1004 #define IDC_STATIC_SPLASHLOADING 1005 #define IDC_COMBO1 1006 #define IDC_CB_WMODES 1006 #define IDC_WINSIZE 1007 #define IDCB_RRATE 1008 #define IDC_ERROR_RICHEDIT 1009 #define IDC_RICHEDIT21 1009 #define IDCB_BPP 1009 #define IDC_ERROR_RICHT_TEXT 1009 #define IDC_DRIVER_LIST 1011 #define IDC_TAB 1013 #define IDC_CB_BPPS 1013 #define IDC_CAPTION 1014 #define IDC_CB_RRATES 1014 #define IDC_CHECKB_FULLSCREEN 1015 #define IDC_RADIO1 1016 #define IDC_LIST1 1017 #define IDC_COMBO2 1018 #define IDC_CB_FSSA 1018 #define IDC_TEXT 1112 #define IDC_CB_FMODE 1112 #define IDD_STYLE 1310 #define IDC_RECTANGLE 1311 #define IDC_ROUND_RECTANGLE 1312 #define IDC_ELLIPSE 1313 #define IDC_FSSA_RADIO_0 1317 #define IDC_FSSA_RADIO_1 1318 #define IDR_MENU1 2101 #define IDD_ERROR 2110 #define IDD_ABOUTP 2700 #define IDD_DIALOG1 22770 #define IDD_DIALOG2 22771 #define TB_IDC_D3DC_WINDOWED_MODE 22773 #define IDC_SCREENSETTINGS 22774 #define TB_IDC_D3DC_FULLSCREEN_MODE 22775 #define IDC_LISTMODE 22776 #define IDC_LISTDRIVER 22777 #define IDC_CHECK1 22778 #define IDC_CHB_FULLSCREEN 22778 #define IDC_LISTMODE2 22779 #define IDC_FSSA_0 22779 #define IDC_CANCEL2 22780 #define IDC_FSS_SELCTION 22781 #define IDC_FSSA_1 22781 #define IDC_FSS_SELCTION2 22782 #define IDC_FSSA_2 22782 #define IDB_SPLASH 22783 #define ID_PLAYER_RESET 32770 #define ID_PLAYER_FULLSCREEN 32771 #define ID_PLAYER_QUIT 32772 #define ID_PLAYER_SETUP 32774 #define ID_PLAYER_WEBSITE 32775 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 105 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1019 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBSetMaterialDecl(); CKERROR CreatePBSetMaterialProto(CKBehaviorPrototype **pproto); int PBSetMaterial(const CKBehaviorContext& behcontext); CKERROR PBSetMaterialCB(const CKBehaviorContext& behcontext); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; enum bInputs { I_XML, I_DFRICTION, I_SFRICTION, I_RES, I_DFRICTIONV, I_SFRICTIONV, I_ANIS, I_FCMODE, I_RCMODE, I_FLAGS, }; CKERROR PBSetMaterialCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKContext *ctx = beh->GetCKContext(); switch(behcontext.CallbackMessage) { case CKM_BEHAVIORLOAD: case CKM_BEHAVIORATTACH: { DWORD outputResult = 0; beh->GetLocalParameterValue(1,&outputResult); beh->EnableOutputParameter(0,outputResult); break; } case CKM_BEHAVIORSETTINGSEDITED: { DWORD outputResult = 0; beh->GetLocalParameterValue(1,&outputResult); beh->EnableOutputParameter(0,outputResult); int fromParameter=0; beh->GetLocalParameterValue(0,&fromParameter); if (fromParameter) { if (beh->GetInputParameterCount() > 1 ) { while ( beh->GetInputParameterCount()) { CKDestroyObject(beh->RemoveInputParameter(0)); } beh->CreateInputParameter("Material Settings",VTS_MATERIAL); } } if (!fromParameter) { if (beh->GetInputParameterCount() < 2 ) { CKDestroyObject(beh->RemoveInputParameter(0)); beh->CreateInputParameter("XML Link",VTE_XML_MATERIAL_TYPE); beh->CreateInputParameter("Dynamic Friction",CKPGUID_FLOAT); beh->CreateInputParameter("Static Friction",CKPGUID_FLOAT); beh->CreateInputParameter("Restitution",CKPGUID_FLOAT); beh->CreateInputParameter("Dynamic Friction V",CKPGUID_FLOAT); beh->CreateInputParameter("Static Friction V",CKPGUID_FLOAT); beh->CreateInputParameter("Direction of Anisotropy ",CKPGUID_VECTOR); beh->CreateInputParameter("Friction Combine Mode",VTE_MATERIAL_COMBINE_MODE); beh->CreateInputParameter("Restitution Combine Mode",VTE_MATERIAL_COMBINE_MODE); beh->CreateInputParameter("Flags",VTF_MATERIAL_FLAGS); } } break; } } return CKBR_OK; } //************************************ // Method: FillBehaviorPBSetMaterialDecl // FullName: FillBehaviorPBSetMaterialDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration*FillBehaviorPBSetMaterialDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetMaterial"); od->SetCategory("Physic/Body"); od->SetDescription("Attaches and/or modifies the physic material of a rigid body or its sub shape"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x52523d82,0x5cb74a78)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBSetMaterialProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBSetMaterialProto // FullName: CreatePBSetMaterialProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBSetMaterialProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetMaterial"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Material Settings",VTS_MATERIAL,"NONE"); proto->DeclareSetting("From Material Parameter",CKPGUID_BOOL,"TRUE"); proto->DeclareSetting("Output Result",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Add Attribute",CKPGUID_BOOL,"FALSE"); proto->DeclareOutParameter("Result",VTS_MATERIAL); /*! \page PBSetMaterial PBSetMaterial is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies a rigid bodies physic material .<br> <h3>Technical Information</h3> \image html PBSetMaterial.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body or its sub shape. <BR> <SPAN CLASS="pin">XML Link: </SPAN> The name of the material stored in the chosen xml file. If set to "None" the values from the parameter struct will be used. The list of avaiable materials will be updated from PhysicDefaults.xml on Dev reset. <BR> <SPAN CLASS="pin">Dynamic Friction: </SPAN> Coefficient of dynamic friction -- should be in [0, +inf]. If set to greater than staticFriction, the effective value of staticFriction will be increased to match. If in the flags "Anisotropic" is set, then this value is used for the primary direction of anisotropy (U axis).<br> <b>Range:</b> [0,inf]<br> <b>Default:</b> 0.0 <SPAN CLASS="pin">Static Friction: </SPAN>Coefficient of static friction -- should be in [0, +inf] If in the flags "Anisotropic" is set, then this value is used for the primary direction of anisotropy (U axis) <b>Range:</b> [0,inf]<br> <b>Default:</b> 0.0 <SPAN CLASS="pin">Restitution: </SPAN>Coefficient of restitution -- 0 makes the object bounce as little as possible, higher values up to 1.0 result in more bounce. Note that values close to or above 1 may cause stability problems and/or increasing energy. <b>Range:</b> [0,1]<br> <b>Default:</b> 0.0 <SPAN CLASS="pin">Dynamic Friction V: </SPAN>Anisotropic dynamic friction coefficient for along the secondary (V) axis of anisotropy. This is only used if the flag Anisotropic is set. <b>Range:</b> [0,inf]<br> <b>Default:</b> 0.0 <SPAN CLASS="pin">Static Friction V : </SPAN>Anisotropic static friction coefficient for along the secondary (V) axis of anisotropy. This is only used if the flag Anisotropic is set. <b>Range:</b> [0,inf]<br> <b>Default:</b> 0.0 <SPAN CLASS="pin">Dir Of Anisotropy: </SPAN>Shape space direction (unit vector) of anisotropy. This is only used if flags Anisotropic is set. <b>Range:</b> direction vector<br> <b>Default:</b> 1.0f,0.0f,0.0f <SPAN CLASS="pin">Flags: </SPAN>Flags, a combination of the bits defined by the enum ::MaterialFlags. <SPAN CLASS="setting">From Material Parameter: </SPAN>Switches the input method between the custom parameter struct "pMaterial" and its enacpsulated input. The parameter "pMaterial" can be modified through parameter operations! <BR> <SPAN CLASS="setting">Output Result: </SPAN>Outputs a pMaterial parameter. This can be useful if a xml setup has be been chosen. <BR> <SPAN CLASS="setting">Add Attribute: </SPAN>Adds the resulting material as a parameter to the selected object. <BR> <h3>Warning</h3> - By default, each body or sub shape retrieves the worlds default material(PhysicDefaults.xml - Default). This building block creates or modifies a new material. - If the settings are invalid, the building block aborts and outputs a message in the console. - You can assign a material to a deformable or a cloth object. <br> <br> */ proto->SetBehaviorCallbackFct( PBSetMaterialCB ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PBSetMaterial); *pproto = proto; return CK_OK; } //************************************ // Method: PBSetMaterial // FullName: PBSetMaterial // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBSetMaterial(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbSErrorME(E_PE_REF); pRigidBody *body = GetPMan()->getBody(target); if (!body) body = GetPMan()->getBody(target); if( !body ) bbSErrorME(E_PE_REF); int fromStruct=0; beh->GetLocalParameterValue(0,&fromStruct); int output=0; beh->GetLocalParameterValue(1,&output); int AddAsAttribute=0; beh->GetLocalParameterValue(2,&AddAsAttribute); pMaterial mat; mat.setToDefault(); if (fromStruct) { CKParameter *mParameter = beh->GetInputParameter(0)->GetRealSource(); if (mParameter) { pFactory::Instance()->copyTo(mat,mParameter); } }else { mat.xmlLinkID = GetInputParameterValue<int>(beh,I_XML); mat.dynamicFriction = GetInputParameterValue<float>(beh,I_DFRICTION); mat.dynamicFrictionV = GetInputParameterValue<float>(beh,I_DFRICTIONV); mat.staticFriction = GetInputParameterValue<float>(beh,I_SFRICTION); mat.staticFrictionV = GetInputParameterValue<float>(beh,I_SFRICTIONV); mat.restitution = GetInputParameterValue<float>(beh,I_RES); mat.dirOfAnisotropy = GetInputParameterValue<VxVector>(beh,I_ANIS); mat.restitutionCombineMode = (CombineMode)GetInputParameterValue<int>(beh,I_RCMODE); mat.frictionCombineMode = (CombineMode)GetInputParameterValue<int>(beh,I_FCMODE); mat.flags = GetInputParameterValue<int>(beh,I_FLAGS); } XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,mat.xmlLinkID); if ( mat.xmlLinkID !=0 ) { bool err = pFactory::Instance()->loadFrom(mat,nodeName.Str(),pFactory::Instance()->getDefaultDocument()); if (!err) { XString error; error << "Couldn't load " << nodeName << " from XML!"; bbErrorME(error.Str()); } if (output) { pFactory::Instance()->copyTo(beh->GetOutputParameter(0),mat); } } if (!mat.isValid()) { XString error; error << "Material Settings " << nodeName << " are invalid!"; bbErrorME(error.Str()); } if (mat.isValid()) { body->setShapeMaterial(mat,target); if (AddAsAttribute) { if (!target->HasAttribute(GetPMan()->att_surface_props)) target->SetAttribute(GetPMan()->att_surface_props); pFactory::Instance()->copyTo(target->GetAttributeParameter(GetPMan()->att_surface_props),mat); } } } beh->ActivateOutput(0); return 0; } <file_sep>#include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "xDistributedPropertyInfo.h" /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedPropertyInfo* xDistributedClass::exists(int nativeType) { xDistributedPropertyInfo *result = NULL; if (getDistributedProperties() ==NULL ) return NULL; int size = getDistributedProperties()->size(); for (unsigned int i = 0 ; i < getDistributedProperties()->size() ; i ++ ) { xDistributedPropertyInfo * current = m_DistributedProperties->at(i); int nType = current->mNativeType ; if ( current->mNativeType == nativeType) { return current; } } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedPropertyInfo* xDistributedClass::exists(const char*name) { xDistributedPropertyInfo *result = NULL; if (!strlen(name))return result; for (unsigned int i = 0 ; i < getDistributedProperties()->size() ; i ++ ) { xDistributedPropertyInfo * current = m_DistributedProperties->at(i); if (!strcmp(current->mName.getString(),name)) { return current; } } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributed3DObjectClass*xDistributedClass::cast(xDistributedClass *_in){ return static_cast<xDistributed3DObjectClass*>(_in); } xNString xDistributedClass::getClassName() { return m_ClassName; } xDistributedClass::~xDistributedClass() { m_DistributedProperties->clear(); //delete m_DistributedProperties; } ////////////////////////////////////////////////////////////////////////// void xDistributedClass::setClassName(xNString name) { m_ClassName = name; } xDistributedClass::xDistributedClass() { m_DistributedProperties = new xDistributedPropertiesListType(); m_EnitityType = 0; m_NativeFlags = 0; } <file_sep>#include <StdAfx.h> #include "pCommon.h" #include "pWorldCallbacks.h" CKObjectDeclaration *FillBehaviorPJIteratorDecl(); CKERROR CreatePJIteratorProto(CKBehaviorPrototype **pproto); int PJIterator(const CKBehaviorContext& behcontext); CKERROR PJIteratorCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPJIteratorDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJIterator"); od->SetCategory("Physic/Joints"); od->SetDescription("Iterates through bodies joints"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x115941e7,0x15861d73)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJIteratorProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJIteratorProto // FullName: CreatePJIteratorProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ enum bInput { }; enum bbO { bbO_BodyB, bbO_Type, }; enum bbOT { bbOT_Finish, bbOT_Next, }; CKERROR CreatePJIteratorProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJIterators"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJIterator PJIterators is categorized in \ref Collision <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Performs a ray cast test. Outputs hit informations.<br> See <A HREF="PWRayCasts.cmo">PWRayCasts.cmo</A> for example. <h3>Technical Information</h3> \image html PJIterators.png <SPAN CLASS="in">In: </SPAN>Triggers the process. <BR> <SPAN CLASS="in">Next: </SPAN>Next Hit. <BR> <SPAN CLASS="out">Yes: </SPAN>Hit occured. <BR> <SPAN CLASS="out">No: </SPAN>No hits. <BR> <SPAN CLASS="out">Finish: </SPAN>Last hit. <BR> <SPAN CLASS="out">Next: </SPAN>Loop out. <BR> <SPAN CLASS="pin">Target: </SPAN>World Reference. pDefaultWorld! <BR> <SPAN CLASS="pin">Ray Origin: </SPAN>Start of the ray. <BR> <SPAN CLASS="pin">Ray Origin Reference: </SPAN>Reference object to determine the start of the ray. Ray Origin becomes transformed if an object is given. <BR> <SPAN CLASS="pin">Ray Direction: </SPAN>Direction of the ray. <BR> <SPAN CLASS="pin">Ray Direction Reference: </SPAN>Reference object to determine the direction of the ray. Ray Direction becomes transformed if an object is given. Up axis will be used then. <BR> <SPAN CLASS="Length">Length: </SPAN>Lenght of the ray. <BR> <SPAN CLASS="pin">Shapes Types: </SPAN>Adds static and/or dynamic shapes to the test. <BR> <SPAN CLASS="pin">Groups: </SPAN>Includes specific groups to the test. <BR> <SPAN CLASS="pin">Groups Mask: </SPAN>Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask <BR> <SPAN CLASS="pout">Touched Body: </SPAN>The touched body. <BR> <SPAN CLASS="pout">Impact Position: </SPAN>Hit point in world space. <BR> <SPAN CLASS="pout">Face Normal: </SPAN>Normal of the hit. <BR> <SPAN CLASS="pout">Face Index: </SPAN> <BR> <SPAN CLASS="pout">Distance: </SPAN>Distance between ray start and hit. <BR> <SPAN CLASS="pout">UV: </SPAN> not used yet ! <BR> <SPAN CLASS="pout">Material Index: </SPAN> Index of the internal physic material. <BR> <br> <br> Is utilizing #pWorld::raycastAllShapes() <br> */ proto->DeclareInput("In"); proto->DeclareInput("Next"); proto->DeclareOutput("Finish"); proto->DeclareOutput("LoopOut"); proto->DeclareLocalParameter("result", CKPGUID_POINTER); proto->DeclareLocalParameter("index", CKPGUID_INT); proto->DeclareOutParameter("Body B",CKPGUID_3DENTITY); proto->DeclareOutParameter("Joint Type",VTE_JOINT_TYPE); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct( PJIteratorCB ); proto->SetFunction(PJIterator); *pproto = proto; return CK_OK; } struct _pJoint { pJoint *_j; CK3dEntity *_b; }; typedef std::vector<_pJoint*>_pJointList; //************************************ // Method: PJIterator // FullName: PJIterator // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJIterator(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorldByBody(target); if (!world) bbErrorME("No valid world object found"); pRigidBody *body = NULL; body = GetPMan()->getBody(target); if (!body) bbErrorME("Object not physicalized"); /************************************************************************/ /* we come in by reset */ /************************************************************************/ if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); _pJointList *jarray = NULL; beh->GetLocalParameterValue(0,&jarray); if (jarray) { jarray->clear(); }else { jarray = new _pJointList(); } beh->SetLocalParameterValue(0,&jarray); int hitIndex = 0; beh->SetLocalParameterValue(1,&hitIndex); ////////////////////////////////////////////////////////////////////////// // get joint list int nbJoints = body->getNbJoints(); if (nbJoints) { NxU32 jointCount = world->getScene()->getNbJoints(); if (jointCount) { NxArray< NxJoint * > joints; world->getScene()->resetJointIterator(); for (NxU32 i = 0; i < jointCount; ++i) { NxJoint *j = world->getScene()->getNextJoint(); pJoint *mJoint = static_cast<pJoint*>( j->userData ); if ( mJoint ) { if (mJoint->GetVTEntA() == target || mJoint->GetVTEntB() == target ) { _pJoint *j = new _pJoint(); j->_j = mJoint; if (mJoint->GetVTEntA() == target ) { j->_b = mJoint->GetVTEntB(); } if (mJoint->GetVTEntB() == target ) { j->_b = mJoint->GetVTEntA(); } jarray->push_back(j); } } } } } if (nbJoints) { beh->ActivateOutput(bbOT_Next); beh->ActivateInput(1,TRUE); }else{ beh->ActivateOutput(bbOT_Finish); } } if( beh->IsInputActive(1) ) { beh->ActivateInput(1,FALSE); _pJointList *carray = NULL; beh->GetLocalParameterValue(0,&carray); ////////////////////////////////////////////////////////////////////////// if (carray) { if (carray->size()) { _pJoint *hit = carray->at(carray->size()-1); if (hit) { beh->SetOutputParameterObject(bbO_BodyB,hit->_b); SetOutputParameterValue<int>(beh,bbO_Type,hit->_j->getType()); carray->pop_back(); if (carray->size()) { beh->ActivateOutput(bbOT_Next); }else { beh->ActivateOutput(bbOT_Finish); } } } } } return 0; } //************************************ // Method: PJIteratorCB // FullName: PJIteratorCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJIteratorCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>/******************************************************************** created: 2009/02/16 created: 16:2:2009 20:25 filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\vtInterfaceEnumeration.h file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common file base: vtInterfaceEnumeration file ext: h author: <NAME> purpose: Declaration of enumerations with bindings in the interface : + VSL + Custom Enumeration Remarks The identifiers described here need to be consistent with types registered for the interface. All types are used by this SDK *********************************************************************/ #ifndef __VT_INTERFACE_ENUMERATION_H__ #define __VT_INTERFACE_ENUMERATION_H__ /** \addtogroup Callbacks @{ */ typedef enum pCallback { CB_OnDelete = (1<<0), CB_OnCopy = (1<<1), CB_OnPreProcess = (1<<2), CB_OnPostProcess = (1<<3), CB_OnContactNotify = (1<<4), CB_OnContactModify = (1<<5), CB_OnRayCastHit = (1<<6), CB_OnWheelContactModify = (1<<7), CB_OnTrigger = (1<<8), CB_OnJointBreak = (1<<9), CB_Max, }; typedef enum pWheelContactModifyFlags { CWCM_ContactPoint = (1<<0), CWCM_ContactNormal = (1<<1), CWCM_ContactPosition = (1<<2), CWCM_NormalForce = (1<<3), CWCM_OtherMaterialIndex = (1<<4), }; /** @} */ /** \addtogroup Collision @{ */ /** \brief Contact pair flags. @see NxUserContactReport.onContactNotify() NxActor::setContactReportThreshold */ typedef enum pContactPairFlags { CPF_IgnorePair = (1<<0), //!< disable contact generation for this pair CPF_OnStartTouch = (1<<1), //!< pair callback will be called when the pair starts to be in contact CPF_OnEndTouch = (1<<2), //!< pair callback will be called when the pair stops to be in contact CPF_OnTouch = (1<<3), //!< pair callback will keep getting called while the pair is in contact CPF_OnImpact = (1<<4), //!< [not yet implemented] pair callback will be called when it may be appropriate for the pair to play an impact sound CPF_OnRoll = (1<<5), //!< [not yet implemented] pair callback will be called when the pair is in contact and rolling. CPF_OnSlide = (1<<6), //!< [not yet implemented] pair callback will be called when the pair is in contact and sliding (and not rolling). CPF_Forces = (1<<7), //!< the (summed total) friction force and normal force will be given in the nxcontactpair variable in the contact report. CPF_OnStartTouchForceThreshold = (1<<8), //!< pair callback will be called when the contact force between two actors exceeds one of the actor-defined force thresholds CPF_OnEndTouchForceThreshold = (1<<9), //!< pair callback will be called when the contact force between two actors falls below the actor-defined force thresholds CPF_OnTouchForceThreshold = (1<<10), //!< pair callback will keep getting called while the contact force between two actors exceeds one of the actor-defined force thresholds CPF_ContactModification = (1<<16), //!< generate a callback for all associated contact constraints, making it possible to edit the constraint. this flag is not included in CPFall for performance reasons. \see nxusercontactmodify }; typedef enum pContactModifyMask { CMM_None = 0, //!< No changes made CMM_MinImpulse = (1<<0), //!< Min impulse value changed CMM_MaxImpulse = (1<<1), //!< Max impulse value changed CMM_Error = (1<<2), //!< Error vector changed CMM_Target = (1<<3), //!< Target vector changed CMM_LocalPosition0 = (1<<4), //!< Local attachment position in shape 0 changed CMM_LocalPosition1 = (1<<5), //!< Local attachment position in shape 1 changed CMM_LocalOrientation0 = (1<<6), //!< Local orientation (normal, friction direction) in shape 0 changed CMM_LocalOrientation1 = (1<<7), //!< Local orientation (normal, friction direction) in shape 1 changed CMM_StaticFriction0 = (1<<8), //!< Static friction parameter 0 changed. (Note: 0 does not have anything to do with shape 0/1) CMM_StaticFriction1 = (1<<9), //!< Static friction parameter 1 changed. (Note: 1 does not have anything to do with shape 0/1) CMM_DynamicFriction0 = (1<<10), //!< Dynamic friction parameter 0 changed. (Note: 0 does not have anything to do with shape 0/1) CMM_DynamicFriction1 = (1<<11), //!< Dynamic friction parameter 1 changed. (Note: 1 does not have anything to do with shape 0/1) CMM_Restitution = (1<<12), //!< Restitution value changed. CMM_Force32 = (1<<31) //!< Not a valid flag value, used by the enum to force the size to 32 bits. }; /** Specifies which informations should be generated(when used as hint flags for ray casting methods). */ enum pRaycastBit { RCH_Shape = (1<<0), //!< "shape" member of #NxRaycastHit is valid RCH_Impact = (1<<1), //!< "worldImpact" member of #NxRaycastHit is valid RCH_Normal = (1<<2), //!< "worldNormal" member of #NxRaycastHit is valid RCH_FaceIndex = (1<<3), //!< "faceID" member of #NxRaycastHit is valid RCH_Distance = (1<<4), //!< "distance" member of #NxRaycastHit is valid RCH_UV = (1<<5), //!< "u" and "v" members of #NxRaycastHit are valid RCH_FaceNormal = (1<<6), //!< Same as RCH_NORMAL but computes a non-smoothed normal RCH_Material= (1<<7), //!< "material" member of #NxRaycastHit is valid }; /** \brief Collision filtering operations. @see pGroupsMask */ enum pFilterOp { FO_And, FO_Or, FO_Xor, FO_Nand, FO_Nor, FO_NXor, FO_SwapAnd }; /** \brief Used to specify which types(static or dynamic) of shape to test against when used with raycasting and overlap test methods in pWorld. */ typedef enum pShapesType { /** \brief Hits static shapes. */ ST_Static= 1, /** \brief Hits dynamic shapes. */ ST_Dynamic= 2, /** \brief Hits dynamic and static shapes. */ ST_All = ST_Dynamic|ST_Static, }; /** \brief Flags which affect the behavior of NxShapes. @see pRigidBody.setTriggerFlags() */ typedef enum pTriggerFlags { /** \brief Disables trigger callback. */ TF_Disable = (1<<3), /** \brief Trigger callback will be called when a shape enters the trigger volume. */ TF_OnEnter = (1<<0), /** \brief Trigger callback will be called after a shape leaves the trigger volume. */ TF_OnLeave = (1<<1), /** \brief Trigger callback will be called while a shape is intersecting the trigger volume. */ TF_OnStay = (1<<2) }; /** @} */ typedef enum E_ENTITY_DATA_FLAGS { EDF_MATERIAL_PARAMETER, EDF_SLEEPING_PARAMETER, EDF_DAMPING_PARAMETER, EDF_DEFORMABLE_PARAMETER, EDF_OPTIMIZATION_PARAMETER, }; typedef enum WORLD_DATA_FLAGS { WDF_HAS_SURFACE_PARAMETER = 0x0001, WDF_HAS_SLEEPING_PARAMETER = 0x0002, WDF_HAS_DAMPING_PARAMETER = 0x0004 }; typedef enum WORLD_UPDATE_MODE { WUM_UPDATE_FROM_ATTRIBUTE = 0x0001 }; typedef enum WORLD_UPDATE_FLAGS { WUF_WORLD_SETTINGS = 0x0001, WUF_DAMPING_PARAMETER = 0x0002, WUF_SLEEPING_PARAMETER = 0x0004, WUF_SURFACE_SETTINGS = 0x0008, WUF_ALL_PARAMETERS = 0x0010, }; typedef enum BODY_UPDATE_FLAGS { BUF_PHY_PARAMETER = 0x0001, BUF_DAMPING_PARAMETER = 0x0002, BUF_SLEEPING_PARAMETER = 0x0004, BUF_JOINT_PARAMETERS = 0x0008, BUF_SURFACE_PARAMETERS = 0x0010, BUF_ALL_PARAMETERS = 0x0020, BUF_GEOMETRY = 0x0040, BUF_PIVOT = 0x0080, BUF_MASS = 0x0100, BUF_ALL = 0x0200 }; /** \addtogroup Joints @{ */ //! Identifies each type of joint. //! This enum is registered as a custom enumeration for the schematic interface as #pJointType.<br> typedef enum JType { JT_Any =-1,/*!<None*/ JT_Prismatic= 0,/*!<Permits a single translational degree of freedom. See #pJointPrismatic.*/ JT_Revolute,/*!<Also known as a hinge joint, permits one rotational degree of freedom. See #pJointRevolute.*/ JT_Cylindrical,/*!<Formerly known as a sliding joint, permits one translational and one rotational degree of freedom. See #pJointCylindrical.*/ JT_Spherical,/*!<Also known as a ball or ball and socket joint. See #pJointBall.*/ JT_PointOnLine,/*!<A point on one actor is constrained to stay on a line on another. */ JT_PointInPlane,/*!<A point on one actor is constrained to stay on a plane on another.*/ JT_Distance,/*!<A point on one actor maintains a certain distance range to another point on another actor. See #pJointDistance. */ JT_Pulley,/*!<A pulley joint. See #pJointPulley.*/ JT_Fixed,/*!<A "fixed" connection. See #pJointFixed. */ JT_D6,/*!< A 6 degree of freedom joint. See #pJointD6.*/ }; /** @} */ ////////////////////////////////////////////////////////////////////////// // BodyFlags typedef enum E_DEBUG_FLAGS { E_DEBUG_0, E_DEBUG_1, //ode-body-pos to virtools-entity pos E_DEBUG_2, //updates changes in dev´s interface mode inda geom space E_DEBUG_3, E_DEBUG_4, E_DEBUG_5 }; /** \addtogroup RigidBody @{ */ //! Enumeration is used : <br> //! -during body registration. <br> //! -through invoking of #pRigidBody::addSubShape().This needs to have BF_SubShape enabled then!.<br> //! -as member of #pObjectDescr.<br><br> //! This enum is registered as a custom flags for the schematic : #pBFlags.<br> typedef enum BodyFlags{ BF_Moving=1,/*!< Makes the body movable. this can not be altered after creation */ BF_Gravity=2,/*!< Enables gravity. See #pRigidBody::enableGravity() or \ref PBSetPar */ BF_Collision=4,/*!< Enables collisions response. See #pRigidBody::enableCollision() or \ref PBSetPar */ BF_Kinematic=8,/*!< Act as kinematic object. See #pRigidBody::setKinematic() or \ref PBSetPar */ BF_SubShape=16,/*!<Entities with a physic object attribute become physical on scene play. If flag enabled, the holding entity is understood as sub shape of the parent object */ BF_Hierarchy=32,/*!<Parse the entities hierarchy */ BF_AddAttributes=64,/*!<Adds the physic attribute on the entity.*/ BF_TriggerShape=128,/*!<Sets the trigger flag enabled(TF_OnEnter,TF_OnStay and TF_OnLeave). This can only be used if it is a sub shape ! This can be changed by \ref PCSetTriggerMask too*/ BF_Deformable=256,/*!<Creates a metal cloth. A deformable object can not be a sub shape ! */ BF_CollisionNotify=512,/*!< Enables using of collisions building blocks. Use or \ref PBSetPar to alter this */ BF_CollisionsForce=1024,/*!< Enables using of collisions building blocks. Use or \ref PBSetPar to alter this */ BF_ContactModify=2048,/*!< Enables using of collisions building blocks. Use or \ref PBSetPar to alter this */ BF_Sleep=4096/*!< Puts the rigid body to sleep */ }; /** \brief Flags which describe the format and behavior of a convex mesh. */ enum pConvexFlags { /** \brief Used to flip the normals if the winding order is reversed. The PhysX libraries assume that the face normal of a triangle with vertices [a,b,c] can be computed as: edge1 = b-a edge2 = c-a face_normal = edge1 x edge2. Note: this is the same as counterclockwise winding in a right handed graphics coordinate system. */ CF_FlipNormals = (1<<0), /** \brief Denotes the use of 16-bit vertex indices (otherwise, 32-bit indices are used) */ CF_16BitIndices = (1<<1), /** \brief Automatically recomputes the hull from the vertices. If this flag is not set, you must provide the entire geometry manually. */ CF_ComputeConvex = (1<<2), /** \brief Inflates the convex object according to skin width. Note: This flag is only used in combination with CF_ComputeConvex. */ CF_InflateConvex = (1<<3), /** \brief Instructs cooking to save normals uncompressed. The cooked hull data will be larger, but will load faster. */ CF_UncompressedNormals = (1<<6), }; /*\brief Enable/disable freezing for this body. \note This is an EXPERIMENTAL feature which doesn't always work on in all situations, e.g. for actors which have joints connected to them. To freeze an actor is a way to simulate that it is static. The actor is however still simulated as if it was dynamic, it's position is just restored after the simulation has finished. A much more stable way to make an actor temporarily static is to raise the #BF_Kinematic flag. */ typedef enum BodyLockFlags { BF_LPX=2, BF_LPY=4, BF_LPZ=8, BF_LRX=16, BF_LRY=32, BF_LRZ=64, }; //! Flags which control the behavior of a material. //! @see pMaterial typedef enum MaterialFlags { /** \brief Flag to enable anisotropic friction computation. For a pair of actors, anisotropic friction is used only if at least one of the two bodies materials are anisotropic. The anisotropic friction parameters for the pair are taken from the material which is more anisotropic (i.e. the difference between its two dynamic friction coefficients is greater). The anisotropy direction of the chosen material is transformed to world space: dirOfAnisotropyWS = shape2world * dirOfAnisotropy Next, the directions of anisotropy in one or more contact planes (i.e. orthogonal to the contact normal) have to be determined. The two directions are: uAxis = (dirOfAnisotropyWS ^ contactNormal).normalize() vAxis = contactNormal ^ uAxis This way [uAxis, contactNormal, vAxis] forms a basis. It may happen, however, that (dirOfAnisotropyWS | contactNormal).magnitude() == 1 and then (dirOfAnisotropyWS ^ contactNormal) has zero length. This happens when the contactNormal is coincident to the direction of anisotropy. In this case we perform isotropic friction. @see pMaterial.dirOfAnisotropy */ MF_Anisotropic=1, /** If this flag is set, friction computations are always skipped between shapes with this material and any other shape. It may be a good idea to use this when all friction is to be performed using the tire friction model (see ::pWheel2). @see pWheel2 */ MF_DisableFriction = 1 << 4, /** The difference between "normal" and "strong" friction is that the strong friction feature remembers the "friction error" between simulation steps. The friction is a force trying to hold objects in place (or slow them down) and this is handled in the solver. But since the solver is only an approximation, the result of the friction calculation can include a small "error" - e.g. a box resting on a slope should not move at all if the static friction is in action, but could slowly glide down the slope because of a small friction error in each simulation step. The strong friction counter-acts this by remembering the small error and taking it to account during the next simulation step. However, in some cases the strong friction could cause problems, and this is why it is possible to disable the strong friction feature by setting this flag. One example is raycast vehicles, that are sliding fast across the surface, but still need a precise steering behavior. It may be a good idea to reenable the strong friction when objects are coming to a rest, to prevent them from slowly creeping down inclines. Note: This flag only has an effect if the MF_DisableFriction bit is 0. @see pWheel2 */ MF_DisableStrongFriction = 1 << 5, }; //! Enumeration is used : <br> //! -during body registration. <br> //! -as member of #pObjectDescr.<br><br> //! This enum is registered as a custom flags for the schematic : #pBHullType.<br> typedef enum HullType { HT_Sphere = 0, /*!<A spherical shape type defined by the meshes radius. <br> */ HT_Box = 1, /*!<A box shape. The entities rotation is set to 0,0,0 (degree) temporary in order to determine the box dimension. It assumes the bodies pivot is aligned to the world frame. <br> */ HT_Capsule = 2, /*!<A capsule shape defined by length and radius. <br> Assuming bodies pivot is aligned to the world frame, the entities rotation is set to 0,0,0 (degree) temporary in order to determine the capsule parameters whereas :<br> capsule length = boxMeshSize.y - boxMeshSize.x and <br> capsule radius = boxMeshSize.x / 2 <br> <br> */ HT_Plane = 3, /*!<A plane shape. \todo : not implemented yet ! <br> */ HT_Mesh =4, /*!<A mesh shape.Its utilizing the NxTrianglemesh. \note The number of vertices is unlimited. <br> \note This mesh type will not create contact points with another trieangle meshs. Avoid this at any cost, otherwise Virtools will crash!<br> <br> */ HT_ConvexMesh =5, /*!<A convex mesh shape. \note The number of vertices is limited to 256 vertices. This is because of Ageia. <br> \note This type will create contact points with all other types! <br> */ HT_Heightfield=6, /*!<A plane shape. \todo : not implemented yet ! <br> */ HT_Wheel=7, /*!<A wheel shape. \todo : not implemented yet ! <br> */ HT_Cloth=8, /*!<A cloth shape. \todo : not implemented yet ! <br> */ HT_ConvexCylinder=9, /*!<A convex cylinder shape. <br> */ HT_Unknown, /*!<Indicates a unspecified type. <br> */ }; /** @} */ typedef enum E_LOG_ITEMS { E_LI_AGEIA, E_LI_MANAGER, E_VSL, E_BB, }; typedef enum E_PHYSIC_ERROR { E_PE_OK, E_PE_AGEIA_ERROR, E_PE_INVALID_PARAMETER, E_PE_INVALID_OPERATION, }; typedef enum E_MANAGER_FLAGS { E_MF_OK, E_MF_PSDK_LOADED, E_MF_PSDK_FAILED, E_MF_DEFAULT_WORLD_CREATED, E_MF_DEFAULT_CONFIG_LOADED, E_MF_LOADING_DEFAULT_CONFIG_FAILED, E_MF_FACTORY_CREATED, }; typedef enum E_MANAGER_INIT_FLAGS { E_MFI_LOAD_CONFIG, E_MFI_CREATE_FACTORY, E_MFI_CREATE_DEFAULT_WORLD, E_MFI_USE_XML_WORLD_SETTINGS }; /** \addtogroup RigidBody @{ */ //! This enum is registered as a custom flags for the schematic : #pBForceMode.<br> //! Enumeration to force related calls. //*! Is used for force related calls. Registered as custom enumeration #pBForceMode. */ enum ForceMode { FM_Force, /*!< parameter has unit of mass * distance/ time^2, i.e. a force*/ FM_Impulse, /*!< parameter has unit of mass * distance /time */ FM_VelocityChange, /*!< parameter has unit of distance / time, i.e. the effect is mass independent: a velocity change.*/ FM_SmoothImpulse, /*!< same as FM_Impulse but the effect is applied over all sub steps. Use this for motion controllers that repeatedly apply an impulse.*/ FM_SmoothVelocityChange, /*!< same as FM_VelocityChange but the effect is applied over all substeps. Use this for motion controllers that repeatedly apply an impulse.*/ FM_Acceleration /*!< parameter has unit of distance/ time^2, i.e. an acceleration. It gets treated just like a force except the mass is not divided out before integration.*/ }; //! This enum is registered as custom hidden enumeration for pCCDSettings- enum CCDFlags { CCD_Shared, /*!< Is reusing a ccd skeleton*/ }; /** @} */ /** \addtogroup RigidBody @{ */ //! Flag that determines the combine mode. When two bodies come in contact with each other, //! they each have materials with various coefficients, but we only need a single set of coefficients for the pair. //! Physics doesn't have any inherent combinations because the coefficients are determined empirically on a case by case basis. However, simulating this with a pairwise lookup table is often impractical. For this reason the following combine //! behaviors are available: CM_Average CM_Min CM_Multiply CM_Max //! The effective combine mode for the pair is max(material0.combineMode, material1.combineMode). enum CombineMode { CM_Average,/*!<Average: (a + b)/2.*/ CM_Min,/*!<Minimum: min(a,b). */ CM_Multiply,/*!<Multiply: a*b. */ CM_Max,/*!<Maximum: max(a,b).*/ }; /** @} */ typedef enum E_BODY_CREATION_FLAGS { E_BCF_USE_WORLD_DAMPING, E_BCF_USE_WORLD_SLEEP_SETTINGS, E_BCF_USE_WORLD_MATERIAL, E_BCF_CREATE_ATTRIBUTES }; /** \addtogroup D6 @{ */ //! Enumeration is used to specify the range of motions allowed for a DOF in a D6 joint. //! Registered as custom enumeration #pJD6MotionMode. typedef enum D6MotionMode { D6MM_Locked,/*!<The DOF is locked, it does not allow relative motion. */ D6MM_Limited,/*!<The DOF is limited, it only allows motion within a specific range. */ D6MM_Free,/*!<The DOF is free and has its full range of motions. */ }; /** @} */ /** \addtogroup D6 @{ */ //! Enumeration is used to specify a particular drive method. i.e. Having a position based goal or a velocity based goal. //! Registered as custom enumeration #pJD6DriveType. typedef enum D6DriveType { D6DT_Position = 1 <<0, /*!<Used to set a position goal when driving.<br> \note The appropriate target positions/orientations should be set. */ D6DT_Velocity = 1 << 1, /*!<Used to set a velocity goal when driving. <br> \note The appropriate target velocities should beset.*/ }; /** @} */ /** \addtogroup D6 @{ */ //! Enumeration is used to specify a particular degree of freedom.Registered as custom enumeration #pJD6Axis. typedef enum D6MotionAxis { D6MA_Twist,/*!<Rotational axis.*/ D6MA_Swing1,/*!<Rotational axis.*/ D6MA_Swing2,/*!<Rotational axis. */ D6MA_X,/*!<Linear axis.*/ D6MA_Y,/*!<Linear axis.*/ D6MA_Z/*!< Linear axis.*/ }; /** @} */ /** \addtogroup D6 @{ */ //! Enumeration is used to specify a particular axis for a soft limit. Registered as custom enumeration #pJD6LimitAxis. typedef enum D6LimitAxis { D6LA_Linear,/*!<Linear axis.*/ D6LA_Swing1,/*!<Rotational axis.*/ D6LA_Swing2,/*!<Rotational axis. */ D6LA_TwistHigh,/*!<Rotational axis. */ D6LA_TwistLow/*!<Rotational axis. */ }; /** @} */ /** \addtogroup D6 @{ */ //! Enumeration is used to specify a particular axis for drives. Registered as custom enumeration #pJD6DriveAxis. typedef enum D6DriveAxis { D6DA_Twist=0,/*!<Rotational axis.Twist is defined as the rotation about the x-axis */ D6DA_Swing=1,/*!<Rotational axis.Swing is defined as the rotation of the x-axis with respect to the y- and z-axis. */ D6DA_Slerp=2,/*!<Rotational axis. */ D6DA_X=3,/*!<Linear axis = joint axis */ D6DA_Y=4,/*!<Linear axis = joint normal axis. */ D6DA_Z=5,/*!<Linear axis = x-axis cross y-axis. */ }; /** @} */ /** \addtogroup Joints @{ */ /** Joint projection is a method for correcting large joint errors. Joint errors occur when a joint's constraint is violated - imagine the ball being pulled out of the socket in a spherical joint. Under normal circumstances, joint errors are small yet unavoidable due to the imprecise nature of floating point math and numerical integrators. The SDK applies minimal correcting forces to the simulation to try and reduce joint errors over time. However, if a joint error becomes very large, more drastic measures are necessary, such as joint projection. The SDK can, in some situations, project (or change) the position of objects directly to fix the joint error. But when projecting the joint it is not desirable to completely remove the joint error because the correcting forces, which also affect velocity, would become zero. */ typedef enum ProjectionMode { PM_None,/*!<Disables projection.*/ PM_MinPointDist,/*!<Performs both linear and angular projection. */ PM_MinLinearDist,/*!<Only projects linear distances, for improved performance.*/ }; /** @} */ /** \addtogroup Vehicle @{ */ /** Flags to describe the internal used shape types behavior. This can be done at any time with : <br> - building block \ref PVWSet - #pWheel::setShapeFlags */ /** Flags to describe the wheels control facility. This can be done at any time with : <br> - building block \ref PVWSet - #pWheel::setWheelFlags */ typedef enum VehicleFlags { VF_UseAdvance = (1 << 0), }; typedef enum WheelShapeFlags { /** \brief Determines whether the suspension axis or the ground contact normal is used for the suspension constraint. */ WSF_WheelAxisContactNormal = 1 << 0, /** \brief If set, the lateral slip velocity is used as the input to the tire function, rather than the slip angle. */ WSF_InputLatSlipVelocity = 1 << 1, /** \brief If set, the longitudinal slip velocity is used as the input to the tire function, rather than the slip ratio. */ WSF_InputLongSlipVelocity = 1 << 2, /** \brief If set, does not factor out the suspension travel and wheel radius from the spring force computation. This is the legacy behavior from the raycast capsule approach. */ WSF_UnscaledSpringBehavior = 1 << 3, /** \brief If set, the axle speed is not computed by the simulation but is rather expected to be provided by the user every simulation step via NxWheelShape::setAxleSpeed(). */ WSF_AxleSpeedOverride = 1 << 4, /** \brief If set, the wheels shape will emulate the legacy raycast capsule based wheel. See #pVWheelFunction */ WSF_EmulateLegacyWheel = 1 << 5, /** \brief If set, the shape will clamp the force in the friction constraints. See #pVWheelFunction */ WSF_ClampedFriction = 1 << 6, }; /** Flags to describe the wheels control facility. This can be done at any time with : <br> - building block \ref PVWSet - #pWheel::setWheelFlags */ typedef enum WheelFlags { /** \brief If set, the wheels shape will emulate the legacy raycast capsule based wheel. See #pVWheelFunction */ WF_SteerableInput = (1 << 0), WF_SteerableAuto = (1 << 1), WF_AffectedByHandbrake = (1 << 2), WF_Accelerated = (1 << 3), WF_VehicleControlled = (1 << 4), WF_AffectedByDifferential = (1 << 5), WF_IgnoreTireFunction = (1 << 6), WF_AllWheelFlags = WF_SteerableInput | WF_SteerableAuto | WF_AffectedByHandbrake | WF_Accelerated | WF_VehicleControlled | WF_AffectedByDifferential, }; typedef enum E_VEHICLE_STATE_FLAGS { E_VSF_HAS_GEARS=(1<<0), E_VSF_HAS_MOTOR=(1<<1), E_VSF_HAS_GROUND=(1<<2), E_VSF_IS_BRAKING=(1<<3), E_VSF_IS_BREAKPEDAL=(1<<4), E_VSF_BREAKPEDAL_CHANGED=(1<<5), E_VSF_ACC_PEDAL=(1<<6), E_VSF_RELEASING_BRAKE_PEDAL=(1<<7), }; /** @} */ typedef enum pParticleRenderType { PRT_Point, PRT_Sprite, }; typedef enum E_OBJECT_CREATION_FLAGS { E_OCF_ROTATION, E_OFC_POSITION, E_OFC_DIMENSION, E_OFC_PERISITENT, }; typedef enum xManagerCallMask { XCM_PreProcess = 1 << 0 , XCM_PostProcess = 1 << 0 }; #endif // __VTINTERFACEENUMERATION_H__<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "cooking.h" #include "Stream.h" #include "pConfig.h" void pFactory::copyTo(pDeformableSettings &dst,CKParameter*par) { if (!par) { return; } using namespace vtTools::ParameterTools; dst.ImpulsThresold = GetValueFromParameterStruct<float>(par,0); dst.PenetrationDepth = GetValueFromParameterStruct<float>(par,1); dst.MaxDeform = GetValueFromParameterStruct<float>(par,2); } pCloth* pFactory::createCloth(CK3dEntity *srcReference,pClothDesc descr) { #ifdef DONLGE if(!GetPMan()->DongleHasAdvancedVersion) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : no license !"); return NULL; } #endif if (!srcReference) { return NULL; } if (!srcReference->GetCurrentMesh()) { return NULL; } if (!descr.isValid()) { return NULL; } CK3dEntity*worldReference = (CK3dEntity*)GetPMan()->m_Context->GetObject(descr.worldReference); if (!worldReference) { if (GetPMan()->getDefaultWorld()) { worldReference = GetPMan()->getDefaultWorld()->getReference(); }else return NULL; } pWorld*world = GetPMan()->getWorld(worldReference->GetID()); if (!world) { return NULL; } pRigidBody *body = GetPMan()->getBody(srcReference); /* if (!body) { return NULL; } */ NxClothMeshDesc meshDesc; // if we want tearing we must tell the cooker // this way it will generate some space for particles that will be generated during tearing if (descr.flags & PCF_Tearable) meshDesc.flags |= NX_CLOTH_MESH_TEARABLE; pCloth *result = new pCloth(); result->generateMeshDesc(descr,&meshDesc,srcReference->GetCurrentMesh()); int mValid = meshDesc.isValid(); if (!result->cookMesh(&meshDesc)) { delete result; return NULL; } result->releaseMeshDescBuffers(&meshDesc); result->allocateClothReceiveBuffers(meshDesc.numVertices, meshDesc.numTriangles); NxClothDesc cDescr; copyToClothDescr(&cDescr,descr); cDescr.clothMesh = result->getClothMesh(); cDescr.meshData = *result->getReceiveBuffers(); VxMatrix v_matrix ; VxVector position,scale; VxQuaternion quat; v_matrix = srcReference->GetWorldMatrix(); Vx3DDecomposeMatrix(v_matrix,quat,position,scale); cDescr.globalPose.t = getFrom(position); cDescr.globalPose.M = getFrom(quat); NxCloth *cloth = world->getScene()->createCloth(cDescr); if (cloth) { result->setCloth(cloth); result->setEntityID(srcReference->GetID()); result->setWorld(GetPMan()->getDefaultWorld()); cloth->userData = result; if (meshDesc.points) { // delete []meshDesc.points; // delete []meshDesc.triangles; } if (descr.flags & PCF_AttachToParentMainShape ) { if (srcReference->GetParent()) { CK3dEntity *bodyReference = getMostTopParent(srcReference); if (bodyReference) { pRigidBody *body = GetPMan()->getBody(bodyReference); if (body) { result->attachToShape((CKBeObject*)bodyReference,descr.attachmentFlags); } } } } if (descr.flags & PCF_AttachToCollidingShapes) { result->attachToCollidingShapes(descr.attachmentFlags); } if (descr.flags & PCF_AttachToCore) { /* NxBodyDesc coreBodyDesc; coreBodyDesc.linearDamping = 0.2f; coreBodyDesc.angularDamping = 0.2f; NxActorDesc coreActorDesc; coreActorDesc.density = 0.1f; coreActorDesc.body = &coreBodyDesc; coreActorDesc.shapes.pushBack(new NxBoxShapeDesc()); NxActor *coreActor = world->getScene()->createActor(coreActorDesc); coreActor->userData =NULL; NxReal impulseThreshold = 50.0f; NxReal penetrationDepth = 0.5f; NxReal maxDeformationDistance = 0.5f; cloth->attachToCore(coreActor, impulseThreshold, penetrationDepth, maxDeformationDistance); */ // result->attachToCollidingShapes(descr.attachmentFlags); } return result; } if (meshDesc.points) { // delete []meshDesc.points; // delete []meshDesc.triangles; } return result; } pClothDesc* pFactory::createClothDescrFromParameter(CKParameter *par) { if (!par) return NULL; pClothDesc *descr = new pClothDesc(); using namespace vtTools::ParameterTools; descr->density = GetValueFromParameterStruct<float>(par,E_CS_DENSITY,false); descr->thickness = GetValueFromParameterStruct<float>(par,E_CS_THICKNESS,false); descr->bendingStiffness = GetValueFromParameterStruct<float>(par,E_CS_BENDING_STIFFNESS,false); descr->stretchingStiffness = GetValueFromParameterStruct<float>(par,E_CS_STRETCHING_STIFFNESS,false); descr->dampingCoefficient = GetValueFromParameterStruct<float>(par,E_CS_DAMPING_COEFFICIENT,false); descr->friction = GetValueFromParameterStruct<float>(par,E_CS_FRICTION,false); descr->pressure = GetValueFromParameterStruct<float>(par,E_CS_PRESSURE,false); descr->tearFactor = GetValueFromParameterStruct<float>(par,E_CS_TEAR_FACTOR,false); descr->collisionResponseCoefficient = GetValueFromParameterStruct<float>(par,E_CS_COLLISIONRESPONSE_COEFFICIENT,false); descr->attachmentResponseCoefficient = GetValueFromParameterStruct<float>(par,E_CS_ATTACHMENTRESPONSE_COEFFICIENT,false); descr->attachmentTearFactor = GetValueFromParameterStruct<float>(par,E_CS_ATTACHMENT_TEAR_FACTOR,false); descr->toFluidResponseCoefficient = GetValueFromParameterStruct<float>(par,E_CS_TO_FLUID_RESPONSE_COEFFICIENT,false); descr->fromFluidResponseCoefficient = GetValueFromParameterStruct<float>(par,E_CS_FROM_FLUIDRESPONSE_COEFFICIENT,false); descr->minAdhereVelocity = GetValueFromParameterStruct<float>(par,E_CS_MIN_ADHERE_VELOCITY,false); descr->solverIterations = GetValueFromParameterStruct<int>(par,E_CS_SOLVER_ITERATIONS,false); descr->externalAcceleration = GetValueFromParameterStruct<VxVector>(par,E_CS_EXTERN_ALACCELERATION,false); descr->windAcceleration = GetValueFromParameterStruct<VxVector>(par,E_CS_WIND_ACCELERATION,false); descr->wakeUpCounter = GetValueFromParameterStruct<float>(par,E_CS_WAKE_UP_COUNTER,false); descr->sleepLinearVelocity = GetValueFromParameterStruct<float>(par,E_CS_SLEEP_LINEAR_VELOCITY,false); descr->collisionGroup = GetValueFromParameterStruct<int>(par,E_CS_COLLISIONG_ROUP,false); descr->validBounds = GetValueFromParameterStruct<VxBbox>(par,E_CS_VALID_BOUNDS,false); descr->relativeGridSpacing = GetValueFromParameterStruct<float>(par,E_CS_RELATIVE_GRID_SPACING,false); descr->flags = GetValueFromParameterStruct<int>(par,E_CS_FLAGS,false); descr->tearVertexColor = GetValueFromParameterStruct<VxColor>(par,E_CS_TEAR_VERTEX_COLOR,false); descr->worldReference = GetValueFromParameterStruct<CK_ID>(par,E_CS_WORLD_REFERENCE,false); return descr; } void pFactory::copyToClothDescr(NxClothDesc* dst,pClothDesc src ) { dst->density = src.density ; dst->thickness = src.thickness ; dst->bendingStiffness = src.bendingStiffness; dst->stretchingStiffness = src.stretchingStiffness; dst->dampingCoefficient = src.dampingCoefficient; dst->friction = src.friction; dst->pressure = src.pressure; dst->tearFactor = src.tearFactor ; dst->collisionResponseCoefficient = src.collisionResponseCoefficient ; dst->attachmentResponseCoefficient = src.attachmentResponseCoefficient ; dst->attachmentTearFactor = src.attachmentTearFactor ; dst->toFluidResponseCoefficient = src.toFluidResponseCoefficient ; dst->fromFluidResponseCoefficient= src.fromFluidResponseCoefficient ; dst->minAdhereVelocity = src.minAdhereVelocity ; dst->solverIterations = src.solverIterations ; dst->externalAcceleration = getFrom(src.externalAcceleration) ; dst->windAcceleration = getFrom(src.windAcceleration); dst->wakeUpCounter = src.wakeUpCounter ; dst->sleepLinearVelocity = src.sleepLinearVelocity ; dst->collisionGroup = src.collisionGroup; dst->validBounds.set(getFrom(src.validBounds.Min) , getFrom(src.validBounds.Max)); dst->relativeGridSpacing = src.relativeGridSpacing; dst->flags =src.flags; }<file_sep>#ifndef __xPredictionSetting_h_ #define __xPredictionSetting_h_ class xPredictionSetting { public: xPredictionSetting() { m_MinSendTime =0.0f; m_MinDifference =0.0f; m_PredictionFactor = 0.0f; } float getMinSendTime() const { return m_MinSendTime; } void setMinSendTime(float val) { m_MinSendTime = val; } float getMinDifference() const { return m_MinDifference; } void setMinDifference(float val) { m_MinDifference = val; } float getPredictionFactor() const { return m_PredictionFactor; } void setPredictionFactor(float val) { m_PredictionFactor = val; } private: float m_MinSendTime; float m_MinDifference; float m_PredictionFactor; }; #endif <file_sep>/******************************************************************** created: 2009/01/05 created: 5:1:2009 18:18 filename: X:\ProjectRoot\svn\local\usr\include\virtools\vtCXGlobal.h file path: X:\ProjectRoot\svn\local\usr\include\virtools file base: vtCXGlobal file ext: h author: purpose: *********************************************************************/ #ifndef __VTCXGLOBAL_H__ #define __VTCXGLOBAL_H__ ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Platform Headers // //#include <virtools/vtCXPrecomp.h> ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Platform specific header switchs : // #ifdef _WIN32 #include <virtools/vtCXPlatform32.h> #endif ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Build switchs : // ////////////////////////////////////////////////////////////////////////// // DebugBuild is used to hide private building blocks, types, attributes,... #ifdef NDEBUG static const bool vtCXDebugBuild = true; #else static const bool vtCXDebugBuild = false; #endif ////////////////////////////////////////////////////////////////////////// // dll directives : #ifndef VTCX_API_EXPORT #define VTCX_API_EXPORT __declspec(dllexport) #endif #ifndef VTCX_API_INLINE #define VTCX_API_INLINE __inline #endif #ifndef VTCX_API_sCALL #define VTCX_API_sCALL __stdcall #endif #ifndef VTCX_API_cDECL #define VTCX_API_cDECL __cdecl #endif ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // API Specific Constants : // // #define MY_BB_CAT VTCX_API_CUSTOM_BB_CATEGORY(/MyPlug) leads to : "vtCX/MyPlug" #ifndef VTCX_AUTHOR #define VTCX_AUTHOR "Gu<NAME>" #endif #ifndef VTCX_AUTHOR_GUID #define VTCX_AUTHOR_GUID CKGUID(0x79ba75dd,0x41d77c63) #endif ////////////////////////////////////////////////////////////////////////// // // Error Identifiers : // ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // File System Specific : // #if defined (_LINUX) #define VTCX_FS_PATH_SEPERATOR '/' #define VTCX_FS_PATH_DRIVE_SEPARATOR ':' #define VTCX_FS_EOL "\n" //(0x0D) #endif #ifdef _WIN32 #define VTCX_FS_PATH_SEPERATOR '\\' #define VTCX_FS_PATH_DRIVE_SEPARATOR #define VTCX_FS_EOL "\r\n" //(0x0A 0x0D) #endif #if defined (macintosh) #define VTCX_FS_PATH_SEPERATOR '/' #define VTCX_FS_PATH_DRIVE_SEPARATOR #define VTCX_FS_EOL "\r" //(0x0A) #endif #define VTCX_FS_PATH_EXT_SEPARATOR '.' ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // #endif<file_sep>#include "precomp.h" #include "Manager/Manager.h" #include "virtools/vt_tools.h" CKObjectDeclaration *FillBehaviorSendCSMessageDecl(); CKERROR CreateSendCSMessageProto(CKBehaviorPrototype **); int SendMessage(const CKBehaviorContext& behcontext); CKERROR SendMessageCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 1 #define BEH_OUT_MIN_COUNT 0 #define BEH_OUT_MAX_COUNT 1 int msgCounter = 0; CKObjectDeclaration *FillBehaviorSendCSMessageDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Send CSMessage"); od->SetDescription("Stores a message in the CSManager "); od->SetCategory("CSharp/Message"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x2f0b513c,0xa4b1eb9)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSendCSMessageProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateSendCSMessageProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Send CSMessage"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Message", CKPGUID_STRING, "msg"); //proto->DeclareInParameter("Target User ID", CKPGUID_INT, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETERINPUTS )); proto->SetFunction(SendMessage); proto->SetBehaviorCallbackFct(SendMessageCB); *pproto = proto; return CK_OK; } int SendMessage(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); CSManager* cman =(CSManager*)ctx->GetManagerByGuid(INIT_MAN_GUID); XString msg((CKSTRING) beh->GetInputParameterReadDataPtr(0)); csMessage *msgout = new csMessage(); msgout->SetName(msg.CStr()); beh->ActivateInput(0,FALSE); using namespace vtTools; using namespace vtTools::Enums; int bcount = beh->GetInputParameterCount(); for (int i = BEH_IN_INDEX_MIN_COUNT ; i < beh->GetInputParameterCount() ; i++ ) { CKParameterIn *ciIn = beh->GetInputParameter(i); CKParameterType pType = ciIn->GetType(); SuperType sType = ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); const char *pname = pam->ParameterTypeToName(pType); switch (sType) { case vtSTRING: case vtFLOAT: case vtINTEGER: { msgout->AddParameter(ciIn->GetRealSource()); break; } default : XString err("wrong input parameter type: "); err << ciIn->GetName() << "Only Types derivated from Interger,Float or String are acceptable"; ctx->OutputToConsole(err.Str(),FALSE ); return CKBR_BEHAVIORERROR; } } cman->AddMessage(msgout); beh->ActivateOutput(0); return CKBR_OK; } CKERROR SendMessageCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by <NAME>, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.3" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Using locations. */ #define YYLSP_NEEDED 0 /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { ID = 258, HBLOCK = 259, POUND = 260, STRING = 261, INCLUDE = 262, IMPORT = 263, INSERT = 264, CHARCONST = 265, NUM_INT = 266, NUM_FLOAT = 267, NUM_UNSIGNED = 268, NUM_LONG = 269, NUM_ULONG = 270, NUM_LONGLONG = 271, NUM_ULONGLONG = 272, TYPEDEF = 273, TYPE_INT = 274, TYPE_UNSIGNED = 275, TYPE_SHORT = 276, TYPE_LONG = 277, TYPE_FLOAT = 278, TYPE_DOUBLE = 279, TYPE_CHAR = 280, TYPE_WCHAR = 281, TYPE_VOID = 282, TYPE_SIGNED = 283, TYPE_BOOL = 284, TYPE_COMPLEX = 285, TYPE_TYPEDEF = 286, TYPE_RAW = 287, TYPE_NON_ISO_INT8 = 288, TYPE_NON_ISO_INT16 = 289, TYPE_NON_ISO_INT32 = 290, TYPE_NON_ISO_INT64 = 291, LPAREN = 292, RPAREN = 293, COMMA = 294, SEMI = 295, EXTERN = 296, INIT = 297, LBRACE = 298, RBRACE = 299, PERIOD = 300, CONST_QUAL = 301, VOLATILE = 302, REGISTER = 303, STRUCT = 304, UNION = 305, EQUAL = 306, SIZEOF = 307, MODULE = 308, LBRACKET = 309, RBRACKET = 310, ILLEGAL = 311, CONSTANT = 312, NAME = 313, RENAME = 314, NAMEWARN = 315, EXTEND = 316, PRAGMA = 317, FEATURE = 318, VARARGS = 319, ENUM = 320, CLASS = 321, TYPENAME = 322, PRIVATE = 323, PUBLIC = 324, PROTECTED = 325, COLON = 326, STATIC = 327, VIRTUAL = 328, FRIEND = 329, THROW = 330, CATCH = 331, EXPLICIT = 332, USING = 333, NAMESPACE = 334, NATIVE = 335, INLINE = 336, TYPEMAP = 337, EXCEPT = 338, ECHO = 339, APPLY = 340, CLEAR = 341, SWIGTEMPLATE = 342, FRAGMENT = 343, WARN = 344, LESSTHAN = 345, GREATERTHAN = 346, MODULO = 347, DELETE_KW = 348, LESSTHANOREQUALTO = 349, GREATERTHANOREQUALTO = 350, EQUALTO = 351, NOTEQUALTO = 352, QUESTIONMARK = 353, TYPES = 354, PARMS = 355, NONID = 356, DSTAR = 357, DCNOT = 358, TEMPLATE = 359, OPERATOR = 360, COPERATOR = 361, PARSETYPE = 362, PARSEPARM = 363, PARSEPARMS = 364, CAST = 365, LOR = 366, LAND = 367, OR = 368, XOR = 369, AND = 370, RSHIFT = 371, LSHIFT = 372, MINUS = 373, PLUS = 374, MODULUS = 375, SLASH = 376, STAR = 377, LNOT = 378, NOT = 379, UMINUS = 380, DCOLON = 381 }; #endif /* Tokens. */ #define ID 258 #define HBLOCK 259 #define POUND 260 #define STRING 261 #define INCLUDE 262 #define IMPORT 263 #define INSERT 264 #define CHARCONST 265 #define NUM_INT 266 #define NUM_FLOAT 267 #define NUM_UNSIGNED 268 #define NUM_LONG 269 #define NUM_ULONG 270 #define NUM_LONGLONG 271 #define NUM_ULONGLONG 272 #define TYPEDEF 273 #define TYPE_INT 274 #define TYPE_UNSIGNED 275 #define TYPE_SHORT 276 #define TYPE_LONG 277 #define TYPE_FLOAT 278 #define TYPE_DOUBLE 279 #define TYPE_CHAR 280 #define TYPE_WCHAR 281 #define TYPE_VOID 282 #define TYPE_SIGNED 283 #define TYPE_BOOL 284 #define TYPE_COMPLEX 285 #define TYPE_TYPEDEF 286 #define TYPE_RAW 287 #define TYPE_NON_ISO_INT8 288 #define TYPE_NON_ISO_INT16 289 #define TYPE_NON_ISO_INT32 290 #define TYPE_NON_ISO_INT64 291 #define LPAREN 292 #define RPAREN 293 #define COMMA 294 #define SEMI 295 #define EXTERN 296 #define INIT 297 #define LBRACE 298 #define RBRACE 299 #define PERIOD 300 #define CONST_QUAL 301 #define VOLATILE 302 #define REGISTER 303 #define STRUCT 304 #define UNION 305 #define EQUAL 306 #define SIZEOF 307 #define MODULE 308 #define LBRACKET 309 #define RBRACKET 310 #define ILLEGAL 311 #define CONSTANT 312 #define NAME 313 #define RENAME 314 #define NAMEWARN 315 #define EXTEND 316 #define PRAGMA 317 #define FEATURE 318 #define VARARGS 319 #define ENUM 320 #define CLASS 321 #define TYPENAME 322 #define PRIVATE 323 #define PUBLIC 324 #define PROTECTED 325 #define COLON 326 #define STATIC 327 #define VIRTUAL 328 #define FRIEND 329 #define THROW 330 #define CATCH 331 #define EXPLICIT 332 #define USING 333 #define NAMESPACE 334 #define NATIVE 335 #define INLINE 336 #define TYPEMAP 337 #define EXCEPT 338 #define ECHO 339 #define APPLY 340 #define CLEAR 341 #define SWIGTEMPLATE 342 #define FRAGMENT 343 #define WARN 344 #define LESSTHAN 345 #define GREATERTHAN 346 #define MODULO 347 #define DELETE_KW 348 #define LESSTHANOREQUALTO 349 #define GREATERTHANOREQUALTO 350 #define EQUALTO 351 #define NOTEQUALTO 352 #define QUESTIONMARK 353 #define TYPES 354 #define PARMS 355 #define NONID 356 #define DSTAR 357 #define DCNOT 358 #define TEMPLATE 359 #define OPERATOR 360 #define COPERATOR 361 #define PARSETYPE 362 #define PARSEPARM 363 #define PARSEPARMS 364 #define CAST 365 #define LOR 366 #define LAND 367 #define OR 368 #define XOR 369 #define AND 370 #define RSHIFT 371 #define LSHIFT 372 #define MINUS 373 #define PLUS 374 #define MODULUS 375 #define SLASH 376 #define STAR 377 #define LNOT 378 #define NOT 379 #define UMINUS 380 #define DCOLON 381 /* Copy the first part of user declarations. */ #line 12 "parser.y" #define yylex yylex char cvsroot_parser_y[] = "$Id: parser.y 9847 2007-06-05 17:48:16Z olly $"; #include "swig.h" #include "cparse.h" #include "preprocessor.h" #include <ctype.h> /* We do this for portability */ #undef alloca #define alloca malloc /* ----------------------------------------------------------------------------- * Externals * ----------------------------------------------------------------------------- */ int yyparse(); /* NEW Variables */ static Node *top = 0; /* Top of the generated parse tree */ static int unnamed = 0; /* Unnamed datatype counter */ static Hash *extendhash = 0; /* Hash table of added methods */ static Hash *classes = 0; /* Hash table of classes */ static Symtab *prev_symtab = 0; static Node *current_class = 0; String *ModuleName = 0; static Node *module_node = 0; static String *Classprefix = 0; static String *Namespaceprefix = 0; static int inclass = 0; static char *last_cpptype = 0; static int inherit_list = 0; static Parm *template_parameters = 0; static int extendmode = 0; static int compact_default_args = 0; static int template_reduce = 0; static int cparse_externc = 0; static int max_class_levels = 0; static int class_level = 0; static Node **class_decl = NULL; /* ----------------------------------------------------------------------------- * Assist Functions * ----------------------------------------------------------------------------- */ /* Called by the parser (yyparse) when an error is found.*/ static void yyerror (const char *e) { (void)e; } static Node *new_node(const String_or_char *tag) { Node *n = NewHash(); set_nodeType(n,tag); Setfile(n,cparse_file); Setline(n,cparse_line); return n; } /* Copies a node. Does not copy tree links or symbol table data (except for sym:name) */ static Node *copy_node(Node *n) { Node *nn; Iterator k; nn = NewHash(); Setfile(nn,Getfile(n)); Setline(nn,Getline(n)); for (k = First(n); k.key; k = Next(k)) { String *ci; String *key = k.key; char *ckey = Char(key); if ((strcmp(ckey,"nextSibling") == 0) || (strcmp(ckey,"previousSibling") == 0) || (strcmp(ckey,"parentNode") == 0) || (strcmp(ckey,"lastChild") == 0)) { continue; } if (Strncmp(key,"csym:",5) == 0) continue; /* We do copy sym:name. For templates */ if ((strcmp(ckey,"sym:name") == 0) || (strcmp(ckey,"sym:weak") == 0) || (strcmp(ckey,"sym:typename") == 0)) { String *ci = Copy(k.item); Setattr(nn,key, ci); Delete(ci); continue; } if (strcmp(ckey,"sym:symtab") == 0) { Setattr(nn,"sym:needs_symtab", "1"); } /* We don't copy any other symbol table attributes */ if (strncmp(ckey,"sym:",4) == 0) { continue; } /* If children. We copy them recursively using this function */ if (strcmp(ckey,"firstChild") == 0) { /* Copy children */ Node *cn = k.item; while (cn) { Node *copy = copy_node(cn); appendChild(nn,copy); Delete(copy); cn = nextSibling(cn); } continue; } /* We don't copy the symbol table. But we drop an attribute requires_symtab so that functions know it needs to be built */ if (strcmp(ckey,"symtab") == 0) { /* Node defined a symbol table. */ Setattr(nn,"requires_symtab","1"); continue; } /* Can't copy nodes */ if (strcmp(ckey,"node") == 0) { continue; } if ((strcmp(ckey,"parms") == 0) || (strcmp(ckey,"pattern") == 0) || (strcmp(ckey,"throws") == 0) || (strcmp(ckey,"kwargs") == 0)) { ParmList *pl = CopyParmList(k.item); Setattr(nn,key,pl); Delete(pl); continue; } /* Looks okay. Just copy the data using Copy */ ci = Copy(k.item); Setattr(nn, key, ci); Delete(ci); } return nn; } /* ----------------------------------------------------------------------------- * Variables * ----------------------------------------------------------------------------- */ static char *typemap_lang = 0; /* Current language setting */ static int cplus_mode = 0; static String *class_rename = 0; /* C++ modes */ #define CPLUS_PUBLIC 1 #define CPLUS_PRIVATE 2 #define CPLUS_PROTECTED 3 /* include types */ static int import_mode = 0; void SWIG_typemap_lang(const char *tm_lang) { typemap_lang = Swig_copy_string(tm_lang); } void SWIG_cparse_set_compact_default_args(int defargs) { compact_default_args = defargs; } int SWIG_cparse_template_reduce(int treduce) { template_reduce = treduce; return treduce; } /* ----------------------------------------------------------------------------- * Assist functions * ----------------------------------------------------------------------------- */ static int promote_type(int t) { if (t <= T_UCHAR || t == T_CHAR) return T_INT; return t; } /* Perform type-promotion for binary operators */ static int promote(int t1, int t2) { t1 = promote_type(t1); t2 = promote_type(t2); return t1 > t2 ? t1 : t2; } static String *yyrename = 0; /* Forward renaming operator */ static String *resolve_node_scope(String *cname); Hash *Swig_cparse_features() { static Hash *features_hash = 0; if (!features_hash) features_hash = NewHash(); return features_hash; } static String *feature_identifier_fix(String *s) { if (SwigType_istemplate(s)) { String *tp, *ts, *ta, *tq; tp = SwigType_templateprefix(s); ts = SwigType_templatesuffix(s); ta = SwigType_templateargs(s); tq = Swig_symbol_type_qualify(ta,0); Append(tp,tq); Append(tp,ts); Delete(ts); Delete(ta); Delete(tq); return tp; } else { return NewString(s); } } /* Generate the symbol table name for an object */ /* This is a bit of a mess. Need to clean up */ static String *add_oldname = 0; static String *make_name(Node *n, String *name,SwigType *decl) { int destructor = name && (*(Char(name)) == '~'); if (yyrename) { String *s = NewString(yyrename); Delete(yyrename); yyrename = 0; if (destructor && (*(Char(s)) != '~')) { Insert(s,0,"~"); } return s; } if (!name) return 0; return Swig_name_make(n,Namespaceprefix,name,decl,add_oldname); } /* Generate an unnamed identifier */ static String *make_unnamed() { unnamed++; return NewStringf("$unnamed%d$",unnamed); } /* Return if the node is a friend declaration */ static int is_friend(Node *n) { return Cmp(Getattr(n,"storage"),"friend") == 0; } static int is_operator(String *name) { return Strncmp(name,"operator ", 9) == 0; } /* Add declaration list to symbol table */ static int add_only_one = 0; static void add_symbols(Node *n) { String *decl; String *wrn = 0; if (inclass && n) { cparse_normalize_void(n); } while (n) { String *symname = 0; /* for friends, we need to pop the scope once */ String *old_prefix = 0; Symtab *old_scope = 0; int isfriend = inclass && is_friend(n); int iscdecl = Cmp(nodeType(n),"cdecl") == 0; if (extendmode) { Setattr(n,"isextension","1"); } if (inclass) { String *name = Getattr(n, "name"); if (isfriend) { /* for friends, we need to add the scopename if needed */ String *prefix = name ? Swig_scopename_prefix(name) : 0; old_prefix = Namespaceprefix; old_scope = Swig_symbol_popscope(); Namespaceprefix = Swig_symbol_qualifiedscopename(0); if (!prefix) { if (name && !is_operator(name) && Namespaceprefix) { String *nname = NewStringf("%s::%s", Namespaceprefix, name); Setattr(n,"name",nname); Delete(nname); } } else { Symtab *st = Swig_symbol_getscope(prefix); String *ns = st ? Getattr(st,"name") : prefix; String *base = Swig_scopename_last(name); String *nname = NewStringf("%s::%s", ns, base); Setattr(n,"name",nname); Delete(nname); Delete(base); Delete(prefix); } Namespaceprefix = 0; } else { /* for member functions, we need to remove the redundant class scope if provided, as in struct Foo { int Foo::method(int a); }; */ String *prefix = name ? Swig_scopename_prefix(name) : 0; if (prefix) { if (Classprefix && (Equal(prefix,Classprefix))) { String *base = Swig_scopename_last(name); Setattr(n,"name",base); Delete(base); } Delete(prefix); } if (0 && !Getattr(n,"parentNode") && class_level) set_parentNode(n,class_decl[class_level - 1]); Setattr(n,"ismember","1"); } } if (!isfriend && inclass) { if ((cplus_mode != CPLUS_PUBLIC)) { int only_csymbol = 1; if (cplus_mode == CPLUS_PROTECTED) { Setattr(n,"access", "protected"); only_csymbol = !Swig_need_protected(n); } else { /* private are needed only when they are pure virtuals */ Setattr(n,"access", "private"); if ((Cmp(Getattr(n,"storage"),"virtual") == 0) && (Cmp(Getattr(n,"value"),"0") == 0)) { only_csymbol = !Swig_need_protected(n); } } if (only_csymbol) { /* Only add to C symbol table and continue */ Swig_symbol_add(0, n); if (add_only_one) break; n = nextSibling(n); continue; } } else { Setattr(n,"access", "public"); } } if (Getattr(n,"sym:name")) { n = nextSibling(n); continue; } decl = Getattr(n,"decl"); if (!SwigType_isfunction(decl)) { String *name = Getattr(n,"name"); String *makename = Getattr(n,"parser:makename"); if (iscdecl) { String *storage = Getattr(n, "storage"); if (Cmp(storage,"typedef") == 0) { Setattr(n,"kind","typedef"); } else { SwigType *type = Getattr(n,"type"); String *value = Getattr(n,"value"); Setattr(n,"kind","variable"); if (value && Len(value)) { Setattr(n,"hasvalue","1"); } if (type) { SwigType *ty; SwigType *tmp = 0; if (decl) { ty = tmp = Copy(type); SwigType_push(ty,decl); } else { ty = type; } if (!SwigType_ismutable(ty)) { SetFlag(n,"hasconsttype"); SetFlag(n,"feature:immutable"); } if (tmp) Delete(tmp); } if (!type) { Printf(stderr,"notype name %s\n", name); } } } Swig_features_get(Swig_cparse_features(), Namespaceprefix, name, 0, n); if (makename) { symname = make_name(n, makename,0); Delattr(n,"parser:makename"); /* temporary information, don't leave it hanging around */ } else { makename = name; symname = make_name(n, makename,0); } if (!symname) { symname = Copy(Getattr(n,"unnamed")); } if (symname) { wrn = Swig_name_warning(n, Namespaceprefix, symname,0); } } else { String *name = Getattr(n,"name"); SwigType *fdecl = Copy(decl); SwigType *fun = SwigType_pop_function(fdecl); if (iscdecl) { Setattr(n,"kind","function"); } Swig_features_get(Swig_cparse_features(),Namespaceprefix,name,fun,n); symname = make_name(n, name,fun); wrn = Swig_name_warning(n, Namespaceprefix,symname,fun); Delete(fdecl); Delete(fun); } if (!symname) { n = nextSibling(n); continue; } if (GetFlag(n,"feature:ignore")) { Swig_symbol_add(0, n); } else if (strncmp(Char(symname),"$ignore",7) == 0) { char *c = Char(symname)+7; SetFlag(n,"feature:ignore"); if (strlen(c)) { SWIG_WARN_NODE_BEGIN(n); Swig_warning(0,Getfile(n), Getline(n), "%s\n",c+1); SWIG_WARN_NODE_END(n); } Swig_symbol_add(0, n); } else { Node *c; if ((wrn) && (Len(wrn))) { String *metaname = symname; if (!Getmeta(metaname,"already_warned")) { SWIG_WARN_NODE_BEGIN(n); Swig_warning(0,Getfile(n),Getline(n), "%s\n", wrn); SWIG_WARN_NODE_END(n); Setmeta(metaname,"already_warned","1"); } } c = Swig_symbol_add(symname,n); if (c != n) { /* symbol conflict attempting to add in the new symbol */ if (Getattr(n,"sym:weak")) { Setattr(n,"sym:name",symname); } else { String *e = NewStringEmpty(); String *en = NewStringEmpty(); String *ec = NewStringEmpty(); int redefined = Swig_need_redefined_warn(n,c,inclass); if (redefined) { Printf(en,"Identifier '%s' redefined (ignored)",symname); Printf(ec,"previous definition of '%s'",symname); } else { Printf(en,"Redundant redeclaration of '%s'",symname); Printf(ec,"previous declaration of '%s'",symname); } if (Cmp(symname,Getattr(n,"name"))) { Printf(en," (Renamed from '%s')", SwigType_namestr(Getattr(n,"name"))); } Printf(en,","); if (Cmp(symname,Getattr(c,"name"))) { Printf(ec," (Renamed from '%s')", SwigType_namestr(Getattr(c,"name"))); } Printf(ec,"."); SWIG_WARN_NODE_BEGIN(n); if (redefined) { Swig_warning(WARN_PARSE_REDEFINED,Getfile(n),Getline(n),"%s\n",en); Swig_warning(WARN_PARSE_REDEFINED,Getfile(c),Getline(c),"%s\n",ec); } else if (!is_friend(n) && !is_friend(c)) { Swig_warning(WARN_PARSE_REDUNDANT,Getfile(n),Getline(n),"%s\n",en); Swig_warning(WARN_PARSE_REDUNDANT,Getfile(c),Getline(c),"%s\n",ec); } SWIG_WARN_NODE_END(n); Printf(e,"%s:%d:%s\n%s:%d:%s\n",Getfile(n),Getline(n),en, Getfile(c),Getline(c),ec); Setattr(n,"error",e); Delete(e); Delete(en); Delete(ec); } } } /* restore the class scope if needed */ if (isfriend) { Swig_symbol_setscope(old_scope); if (old_prefix) { Delete(Namespaceprefix); Namespaceprefix = old_prefix; } } Delete(symname); if (add_only_one) return; n = nextSibling(n); } } /* add symbols a parse tree node copy */ static void add_symbols_copy(Node *n) { String *name; int emode = 0; while (n) { char *cnodeType = Char(nodeType(n)); if (strcmp(cnodeType,"access") == 0) { String *kind = Getattr(n,"kind"); if (Strcmp(kind,"public") == 0) { cplus_mode = CPLUS_PUBLIC; } else if (Strcmp(kind,"private") == 0) { cplus_mode = CPLUS_PRIVATE; } else if (Strcmp(kind,"protected") == 0) { cplus_mode = CPLUS_PROTECTED; } n = nextSibling(n); continue; } add_oldname = Getattr(n,"sym:name"); if ((add_oldname) || (Getattr(n,"sym:needs_symtab"))) { if (add_oldname) { DohIncref(add_oldname); /* Disable this, it prevents %rename to work with templates */ /* If already renamed, we used that name */ /* if (Strcmp(add_oldname, Getattr(n,"name")) != 0) { Delete(yyrename); yyrename = Copy(add_oldname); } */ } Delattr(n,"sym:needs_symtab"); Delattr(n,"sym:name"); add_only_one = 1; add_symbols(n); if (Getattr(n,"partialargs")) { Swig_symbol_cadd(Getattr(n,"partialargs"),n); } add_only_one = 0; name = Getattr(n,"name"); if (Getattr(n,"requires_symtab")) { Swig_symbol_newscope(); Swig_symbol_setscopename(name); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); } if (strcmp(cnodeType,"class") == 0) { inclass = 1; current_class = n; if (Strcmp(Getattr(n,"kind"),"class") == 0) { cplus_mode = CPLUS_PRIVATE; } else { cplus_mode = CPLUS_PUBLIC; } } if (strcmp(cnodeType,"extend") == 0) { emode = cplus_mode; cplus_mode = CPLUS_PUBLIC; } add_symbols_copy(firstChild(n)); if (strcmp(cnodeType,"extend") == 0) { cplus_mode = emode; } if (Getattr(n,"requires_symtab")) { Setattr(n,"symtab", Swig_symbol_popscope()); Delattr(n,"requires_symtab"); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); } if (add_oldname) { Delete(add_oldname); add_oldname = 0; } if (strcmp(cnodeType,"class") == 0) { inclass = 0; current_class = 0; } } else { if (strcmp(cnodeType,"extend") == 0) { emode = cplus_mode; cplus_mode = CPLUS_PUBLIC; } add_symbols_copy(firstChild(n)); if (strcmp(cnodeType,"extend") == 0) { cplus_mode = emode; } } n = nextSibling(n); } } /* Extension merge. This function is used to handle the %extend directive when it appears before a class definition. To handle this, the %extend actually needs to take precedence. Therefore, we will selectively nuke symbols from the current symbol table, replacing them with the added methods */ static void merge_extensions(Node *cls, Node *am) { Node *n; Node *csym; n = firstChild(am); while (n) { String *symname; if (Strcmp(nodeType(n),"constructor") == 0) { symname = Getattr(n,"sym:name"); if (symname) { if (Strcmp(symname,Getattr(n,"name")) == 0) { /* If the name and the sym:name of a constructor are the same, then it hasn't been renamed. However---the name of the class itself might have been renamed so we need to do a consistency check here */ if (Getattr(cls,"sym:name")) { Setattr(n,"sym:name", Getattr(cls,"sym:name")); } } } } symname = Getattr(n,"sym:name"); DohIncref(symname); if ((symname) && (!Getattr(n,"error"))) { /* Remove node from its symbol table */ Swig_symbol_remove(n); csym = Swig_symbol_add(symname,n); if (csym != n) { /* Conflict with previous definition. Nuke previous definition */ String *e = NewStringEmpty(); String *en = NewStringEmpty(); String *ec = NewStringEmpty(); Printf(ec,"Identifier '%s' redefined by %%extend (ignored),",symname); Printf(en,"%%extend definition of '%s'.",symname); SWIG_WARN_NODE_BEGIN(n); Swig_warning(WARN_PARSE_REDEFINED,Getfile(csym),Getline(csym),"%s\n",ec); Swig_warning(WARN_PARSE_REDEFINED,Getfile(n),Getline(n),"%s\n",en); SWIG_WARN_NODE_END(n); Printf(e,"%s:%d:%s\n%s:%d:%s\n",Getfile(csym),Getline(csym),ec, Getfile(n),Getline(n),en); Setattr(csym,"error",e); Delete(e); Delete(en); Delete(ec); Swig_symbol_remove(csym); /* Remove class definition */ Swig_symbol_add(symname,n); /* Insert extend definition */ } } n = nextSibling(n); } } static void append_previous_extension(Node *cls, Node *am) { Node *n, *ne; Node *pe = 0; Node *ae = 0; if (!am) return; n = firstChild(am); while (n) { ne = nextSibling(n); set_nextSibling(n,0); /* typemaps and fragments need to be prepended */ if (((Cmp(nodeType(n),"typemap") == 0) || (Cmp(nodeType(n),"fragment") == 0))) { if (!pe) pe = new_node("extend"); appendChild(pe, n); } else { if (!ae) ae = new_node("extend"); appendChild(ae, n); } n = ne; } if (pe) prependChild(cls,pe); if (ae) appendChild(cls,ae); } /* Check for unused %extend. Special case, don't report unused extensions for templates */ static void check_extensions() { Iterator ki; if (!extendhash) return; for (ki = First(extendhash); ki.key; ki = Next(ki)) { if (!Strchr(ki.key,'<')) { SWIG_WARN_NODE_BEGIN(ki.item); Swig_warning(WARN_PARSE_EXTEND_UNDEF,Getfile(ki.item), Getline(ki.item), "%%extend defined for an undeclared class %s.\n", ki.key); SWIG_WARN_NODE_END(ki.item); } } } /* Check a set of declarations to see if any are pure-abstract */ static List *pure_abstract(Node *n) { List *abs = 0; while (n) { if (Cmp(nodeType(n),"cdecl") == 0) { String *decl = Getattr(n,"decl"); if (SwigType_isfunction(decl)) { String *init = Getattr(n,"value"); if (Cmp(init,"0") == 0) { if (!abs) { abs = NewList(); } Append(abs,n); Setattr(n,"abstract","1"); } } } else if (Cmp(nodeType(n),"destructor") == 0) { if (Cmp(Getattr(n,"value"),"0") == 0) { if (!abs) { abs = NewList(); } Append(abs,n); Setattr(n,"abstract","1"); } } n = nextSibling(n); } return abs; } /* Make a classname */ static String *make_class_name(String *name) { String *nname = 0; if (Namespaceprefix) { nname= NewStringf("%s::%s", Namespaceprefix, name); } else { nname = NewString(name); } if (SwigType_istemplate(nname)) { String *prefix, *args, *qargs; prefix = SwigType_templateprefix(nname); args = SwigType_templateargs(nname); qargs = Swig_symbol_type_qualify(args,0); Append(prefix,qargs); Delete(nname); Delete(args); Delete(qargs); nname = prefix; } return nname; } static List *make_inherit_list(String *clsname, List *names) { int i, ilen; String *derived; List *bases = NewList(); if (Namespaceprefix) derived = NewStringf("%s::%s", Namespaceprefix,clsname); else derived = NewString(clsname); ilen = Len(names); for (i = 0; i < ilen; i++) { Node *s; String *base; String *n = Getitem(names,i); /* Try to figure out where this symbol is */ s = Swig_symbol_clookup(n,0); if (s) { while (s && (Strcmp(nodeType(s),"class") != 0)) { /* Not a class. Could be a typedef though. */ String *storage = Getattr(s,"storage"); if (storage && (Strcmp(storage,"typedef") == 0)) { String *nn = Getattr(s,"type"); s = Swig_symbol_clookup(nn,Getattr(s,"sym:symtab")); } else { break; } } if (s && ((Strcmp(nodeType(s),"class") == 0) || (Strcmp(nodeType(s),"template") == 0))) { String *q = Swig_symbol_qualified(s); Append(bases,s); if (q) { base = NewStringf("%s::%s", q, Getattr(s,"name")); Delete(q); } else { base = NewString(Getattr(s,"name")); } } else { base = NewString(n); } } else { base = NewString(n); } if (base) { Swig_name_inherit(base,derived); Delete(base); } } return bases; } /* If the class name is qualified. We need to create or lookup namespace entries */ static Symtab *get_global_scope() { Symtab *symtab = Swig_symbol_current(); Node *pn = parentNode(symtab); while (pn) { symtab = pn; pn = parentNode(symtab); if (!pn) break; } Swig_symbol_setscope(symtab); return symtab; } static Node *nscope = 0; static Node *nscope_inner = 0; static String *resolve_node_scope(String *cname) { Symtab *gscope = 0; nscope = 0; nscope_inner = 0; if (Swig_scopename_check(cname)) { Node *ns; String *prefix = Swig_scopename_prefix(cname); String *base = Swig_scopename_last(cname); if (prefix && (Strncmp(prefix,"::",2) == 0)) { /* Use the global scope */ String *nprefix = NewString(Char(prefix)+2); Delete(prefix); prefix= nprefix; gscope = get_global_scope(); } if (!prefix || (Len(prefix) == 0)) { /* Use the global scope, but we need to add a 'global' namespace. */ if (!gscope) gscope = get_global_scope(); /* note that this namespace is not the "unnamed" one, and we don't use Setattr(nscope,"name", ""), because the unnamed namespace is private */ nscope = new_node("namespace"); Setattr(nscope,"symtab", gscope);; nscope_inner = nscope; return base; } /* Try to locate the scope */ ns = Swig_symbol_clookup(prefix,0); if (!ns) { Swig_error(cparse_file,cparse_line,"Undefined scope '%s'\n", prefix); } else { Symtab *nstab = Getattr(ns,"symtab"); if (!nstab) { Swig_error(cparse_file,cparse_line, "'%s' is not defined as a valid scope.\n", prefix); ns = 0; } else { /* Check if the node scope is the current scope */ String *tname = Swig_symbol_qualifiedscopename(0); String *nname = Swig_symbol_qualifiedscopename(nstab); if (tname && (Strcmp(tname,nname) == 0)) { ns = 0; cname = base; } Delete(tname); Delete(nname); } if (ns) { /* we will try to create a new node using the namespaces we can find in the scope name */ List *scopes; String *sname; Iterator si; String *name = NewString(prefix); scopes = NewList(); while (name) { String *base = Swig_scopename_last(name); String *tprefix = Swig_scopename_prefix(name); Insert(scopes,0,base); Delete(base); Delete(name); name = tprefix; } for (si = First(scopes); si.item; si = Next(si)) { Node *ns1,*ns2; sname = si.item; ns1 = Swig_symbol_clookup(sname,0); assert(ns1); if (Strcmp(nodeType(ns1),"namespace") == 0) { if (Getattr(ns1,"alias")) { ns1 = Getattr(ns1,"namespace"); } } else { /* now this last part is a class */ si = Next(si); ns1 = Swig_symbol_clookup(sname,0); /* or a nested class tree, which is unrolled here */ for (; si.item; si = Next(si)) { if (si.item) { Printf(sname,"::%s",si.item); } } /* we get the 'inner' class */ nscope_inner = Swig_symbol_clookup(sname,0); /* set the scope to the inner class */ Swig_symbol_setscope(Getattr(nscope_inner,"symtab")); /* save the last namespace prefix */ Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); /* and return the node name, including the inner class prefix */ break; } /* here we just populate the namespace tree as usual */ ns2 = new_node("namespace"); Setattr(ns2,"name",sname); Setattr(ns2,"symtab", Getattr(ns1,"symtab")); add_symbols(ns2); Swig_symbol_setscope(Getattr(ns1,"symtab")); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); if (nscope_inner) { if (Getattr(nscope_inner,"symtab") != Getattr(ns2,"symtab")) { appendChild(nscope_inner,ns2); Delete(ns2); } } nscope_inner = ns2; if (!nscope) nscope = ns2; } cname = base; Delete(scopes); } } Delete(prefix); } return cname; } /* Structures for handling code fragments built for nested classes */ typedef struct Nested { String *code; /* Associated code fragment */ int line; /* line number where it starts */ char *name; /* Name associated with this nested class */ char *kind; /* Kind of class */ int unnamed; /* unnamed class */ SwigType *type; /* Datatype associated with the name */ struct Nested *next; /* Next code fragment in list */ } Nested; /* Some internal variables for saving nested class information */ static Nested *nested_list = 0; /* Add a function to the nested list */ static void add_nested(Nested *n) { Nested *n1; if (!nested_list) nested_list = n; else { n1 = nested_list; while (n1->next) n1 = n1->next; n1->next = n; } } /* Dump all of the nested class declarations to the inline processor * However. We need to do a few name replacements and other munging * first. This function must be called before closing a class! */ static Node *dump_nested(const char *parent) { Nested *n,*n1; Node *ret = 0; n = nested_list; if (!parent) { nested_list = 0; return 0; } while (n) { Node *retx; SwigType *nt; /* Token replace the name of the parent class */ Replace(n->code, "$classname", parent, DOH_REPLACE_ANY); /* Fix up the name of the datatype (for building typedefs and other stuff) */ Append(n->type,parent); Append(n->type,"_"); Append(n->type,n->name); /* Add the appropriate declaration to the C++ processor */ retx = new_node("cdecl"); Setattr(retx,"name",n->name); nt = Copy(n->type); Setattr(retx,"type",nt); Delete(nt); Setattr(retx,"nested",parent); if (n->unnamed) { Setattr(retx,"unnamed","1"); } add_symbols(retx); if (ret) { set_nextSibling(retx,ret); Delete(ret); } ret = retx; /* Insert a forward class declaration */ /* Disabled: [ 597599 ] union in class: incorrect scope retx = new_node("classforward"); Setattr(retx,"kind",n->kind); Setattr(retx,"name",Copy(n->type)); Setattr(retx,"sym:name", make_name(n->type,0)); set_nextSibling(retx,ret); ret = retx; */ /* Make all SWIG created typedef structs/unions/classes unnamed else redefinition errors occur - nasty hack alert.*/ { const char* types_array[3] = {"struct", "union", "class"}; int i; for (i=0; i<3; i++) { char* code_ptr = Char(n->code); while (code_ptr) { /* Replace struct name (as in 'struct name {...}' ) with whitespace name will be between struct and opening brace */ code_ptr = strstr(code_ptr, types_array[i]); if (code_ptr) { char *open_bracket_pos; code_ptr += strlen(types_array[i]); open_bracket_pos = strchr(code_ptr, '{'); if (open_bracket_pos) { /* Make sure we don't have something like struct A a; */ char* semi_colon_pos = strchr(code_ptr, ';'); if (!(semi_colon_pos && (semi_colon_pos < open_bracket_pos))) while (code_ptr < open_bracket_pos) *code_ptr++ = ' '; } } } } } { /* Remove SWIG directive %constant which may be left in the SWIG created typedefs */ char* code_ptr = Char(n->code); while (code_ptr) { code_ptr = strstr(code_ptr, "%constant"); if (code_ptr) { char* directive_end_pos = strchr(code_ptr, ';'); if (directive_end_pos) { while (code_ptr <= directive_end_pos) *code_ptr++ = ' '; } } } } { Node *head = new_node("insert"); String *code = NewStringf("\n%s\n",n->code); Setattr(head,"code", code); Delete(code); set_nextSibling(head,ret); Delete(ret); ret = head; } /* Dump the code to the scanner */ start_inline(Char(n->code),n->line); n1 = n->next; Delete(n->code); free(n); n = n1; } nested_list = 0; return ret; } Node *Swig_cparse(File *f) { scanner_file(f); top = 0; yyparse(); return top; } static void single_new_feature(const char *featurename, String *val, Hash *featureattribs, char *declaratorid, SwigType *type, ParmList *declaratorparms, String *qualifier) { String *fname; String *name; String *fixname; SwigType *t = Copy(type); /* Printf(stdout, "single_new_feature: [%s] [%s] [%s] [%s] [%s] [%s]\n", featurename, val, declaratorid, t, ParmList_str_defaultargs(declaratorparms), qualifier); */ fname = NewStringf("feature:%s",featurename); if (declaratorid) { fixname = feature_identifier_fix(declaratorid); } else { fixname = NewStringEmpty(); } if (Namespaceprefix) { name = NewStringf("%s::%s",Namespaceprefix, fixname); } else { name = fixname; } if (declaratorparms) Setmeta(val,"parms",declaratorparms); if (!Len(t)) t = 0; if (t) { if (qualifier) SwigType_push(t,qualifier); if (SwigType_isfunction(t)) { SwigType *decl = SwigType_pop_function(t); if (SwigType_ispointer(t)) { String *nname = NewStringf("*%s",name); Swig_feature_set(Swig_cparse_features(), nname, decl, fname, val, featureattribs); Delete(nname); } else { Swig_feature_set(Swig_cparse_features(), name, decl, fname, val, featureattribs); } Delete(decl); } else if (SwigType_ispointer(t)) { String *nname = NewStringf("*%s",name); Swig_feature_set(Swig_cparse_features(),nname,0,fname,val, featureattribs); Delete(nname); } } else { /* Global feature, that is, feature not associated with any particular symbol */ Swig_feature_set(Swig_cparse_features(),name,0,fname,val, featureattribs); } Delete(fname); Delete(name); } /* Add a new feature to the Hash. Additional features are added if the feature has a parameter list (declaratorparms) * and one or more of the parameters have a default argument. An extra feature is added for each defaulted parameter, * simulating the equivalent overloaded method. */ static void new_feature(const char *featurename, String *val, Hash *featureattribs, char *declaratorid, SwigType *type, ParmList *declaratorparms, String *qualifier) { ParmList *declparms = declaratorparms; /* Add the feature */ single_new_feature(featurename, val, featureattribs, declaratorid, type, declaratorparms, qualifier); /* Add extra features if there are default parameters in the parameter list */ if (type) { while (declparms) { if (ParmList_has_defaultargs(declparms)) { /* Create a parameter list for the new feature by copying all but the last (defaulted) parameter */ ParmList* newparms = CopyParmListMax(declparms, ParmList_len(declparms)-1); /* Create new declaration - with the last parameter removed */ SwigType *newtype = Copy(type); Delete(SwigType_pop_function(newtype)); /* remove the old parameter list from newtype */ SwigType_add_function(newtype,newparms); single_new_feature(featurename, Copy(val), featureattribs, declaratorid, newtype, newparms, qualifier); declparms = newparms; } else { declparms = 0; } } } } /* check if a function declaration is a plain C object */ static int is_cfunction(Node *n) { if (!cparse_cplusplus || cparse_externc) return 1; if (Cmp(Getattr(n,"storage"),"externc") == 0) { return 1; } return 0; } /* If the Node is a function with parameters, check to see if any of the parameters * have default arguments. If so create a new function for each defaulted argument. * The additional functions form a linked list of nodes with the head being the original Node n. */ static void default_arguments(Node *n) { Node *function = n; if (function) { ParmList *varargs = Getattr(function,"feature:varargs"); if (varargs) { /* Handles the %varargs directive by looking for "feature:varargs" and * substituting ... with an alternative set of arguments. */ Parm *p = Getattr(function,"parms"); Parm *pp = 0; while (p) { SwigType *t = Getattr(p,"type"); if (Strcmp(t,"v(...)") == 0) { if (pp) { ParmList *cv = Copy(varargs); set_nextSibling(pp,cv); Delete(cv); } else { ParmList *cv = Copy(varargs); Setattr(function,"parms", cv); Delete(cv); } break; } pp = p; p = nextSibling(p); } } /* Do not add in functions if kwargs is being used or if user wants old default argument wrapping (one wrapped method per function irrespective of number of default arguments) */ if (compact_default_args || is_cfunction(function) || GetFlag(function,"feature:compactdefaultargs") || GetFlag(function,"feature:kwargs")) { ParmList *p = Getattr(function,"parms"); if (p) Setattr(p,"compactdefargs", "1"); /* mark parameters for special handling */ function = 0; /* don't add in extra methods */ } } while (function) { ParmList *parms = Getattr(function,"parms"); if (ParmList_has_defaultargs(parms)) { /* Create a parameter list for the new function by copying all but the last (defaulted) parameter */ ParmList* newparms = CopyParmListMax(parms,ParmList_len(parms)-1); /* Create new function and add to symbol table */ { SwigType *ntype = Copy(nodeType(function)); char *cntype = Char(ntype); Node *new_function = new_node(ntype); SwigType *decl = Copy(Getattr(function,"decl")); int constqualifier = SwigType_isconst(decl); String *ccode = Copy(Getattr(function,"code")); String *cstorage = Copy(Getattr(function,"storage")); String *cvalue = Copy(Getattr(function,"value")); SwigType *ctype = Copy(Getattr(function,"type")); String *cthrow = Copy(Getattr(function,"throw")); Delete(SwigType_pop_function(decl)); /* remove the old parameter list from decl */ SwigType_add_function(decl,newparms); if (constqualifier) SwigType_add_qualifier(decl,"const"); Setattr(new_function,"name", Getattr(function,"name")); Setattr(new_function,"code", ccode); Setattr(new_function,"decl", decl); Setattr(new_function,"parms", newparms); Setattr(new_function,"storage", cstorage); Setattr(new_function,"value", cvalue); Setattr(new_function,"type", ctype); Setattr(new_function,"throw", cthrow); Delete(ccode); Delete(cstorage); Delete(cvalue); Delete(ctype); Delete(cthrow); Delete(decl); { Node *throws = Getattr(function,"throws"); ParmList *pl = CopyParmList(throws); if (throws) Setattr(new_function,"throws",pl); Delete(pl); } /* copy specific attributes for global (or in a namespace) template functions - these are not templated class methods */ if (strcmp(cntype,"template") == 0) { Node *templatetype = Getattr(function,"templatetype"); Node *symtypename = Getattr(function,"sym:typename"); Parm *templateparms = Getattr(function,"templateparms"); if (templatetype) { Node *tmp = Copy(templatetype); Setattr(new_function,"templatetype",tmp); Delete(tmp); } if (symtypename) { Node *tmp = Copy(symtypename); Setattr(new_function,"sym:typename",tmp); Delete(tmp); } if (templateparms) { Parm *tmp = CopyParmList(templateparms); Setattr(new_function,"templateparms",tmp); Delete(tmp); } } else if (strcmp(cntype,"constructor") == 0) { /* only copied for constructors as this is not a user defined feature - it is hard coded in the parser */ if (GetFlag(function,"feature:new")) SetFlag(new_function,"feature:new"); } add_symbols(new_function); /* mark added functions as ones with overloaded parameters and point to the parsed method */ Setattr(new_function,"defaultargs", n); /* Point to the new function, extending the linked list */ set_nextSibling(function, new_function); Delete(new_function); function = new_function; Delete(ntype); } } else { function = 0; } } } /* ----------------------------------------------------------------------------- * tag_nodes() * * Used by the parser to mark subtypes with extra information. * ----------------------------------------------------------------------------- */ static void tag_nodes(Node *n, const String_or_char *attrname, DOH *value) { while (n) { Setattr(n, attrname, value); tag_nodes(firstChild(n), attrname, value); n = nextSibling(n); } } /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 1349 "parser.y" { char *id; List *bases; struct Define { String *val; String *rawval; int type; String *qualifier; String *bitfield; Parm *throws; String *throwf; } dtype; struct { char *type; String *filename; int line; } loc; struct { char *id; SwigType *type; String *defarg; ParmList *parms; short have_parms; ParmList *throws; String *throwf; } decl; Parm *tparms; struct { String *op; Hash *kwargs; } tmap; struct { String *type; String *us; } ptype; SwigType *type; String *str; Parm *p; ParmList *pl; int ivalue; Node *node; } /* Line 187 of yacc.c. */ #line 1728 "y.tab.c" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 216 of yacc.c. */ #line 1741 "y.tab.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int i) #else static int YYID (i) int i; #endif { return i; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss; YYSTYPE yyvs; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack, Stack, yysize); \ Stack = &yyptr->Stack; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 55 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 3822 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 127 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 148 /* YYNRULES -- Number of rules. */ #define YYNRULES 467 /* YYNRULES -- Number of states. */ #define YYNSTATES 903 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 381 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint16 yyprhs[] = { 0, 0, 3, 5, 9, 12, 16, 19, 25, 29, 32, 34, 36, 38, 40, 42, 44, 46, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 92, 100, 106, 110, 116, 122, 126, 129, 132, 138, 141, 147, 150, 155, 157, 159, 167, 175, 181, 182, 190, 192, 194, 197, 200, 202, 208, 214, 220, 224, 229, 233, 241, 250, 256, 260, 262, 264, 268, 270, 275, 283, 290, 292, 294, 302, 312, 321, 332, 338, 346, 353, 362, 364, 366, 372, 377, 383, 391, 393, 397, 404, 411, 420, 422, 425, 429, 431, 434, 438, 445, 451, 461, 464, 466, 468, 470, 471, 478, 484, 486, 491, 493, 495, 498, 504, 511, 516, 524, 533, 540, 542, 544, 546, 548, 550, 552, 553, 563, 564, 573, 575, 578, 583, 584, 591, 595, 597, 599, 601, 603, 605, 607, 609, 612, 614, 616, 618, 622, 624, 628, 633, 634, 641, 642, 648, 654, 657, 658, 665, 667, 669, 670, 674, 676, 678, 680, 682, 684, 686, 688, 690, 694, 696, 698, 700, 702, 704, 706, 708, 710, 712, 719, 726, 734, 743, 752, 760, 766, 769, 772, 775, 776, 784, 785, 792, 793, 802, 804, 806, 808, 810, 812, 814, 816, 818, 820, 822, 824, 826, 828, 831, 834, 837, 842, 845, 851, 853, 856, 858, 860, 862, 864, 866, 868, 870, 873, 875, 879, 881, 884, 891, 895, 897, 900, 902, 906, 908, 910, 912, 915, 921, 924, 927, 929, 932, 935, 937, 939, 941, 943, 946, 950, 952, 955, 959, 964, 970, 975, 977, 980, 984, 989, 995, 999, 1004, 1009, 1011, 1014, 1019, 1024, 1030, 1034, 1039, 1044, 1046, 1049, 1052, 1056, 1058, 1061, 1063, 1066, 1070, 1075, 1079, 1084, 1087, 1091, 1095, 1100, 1104, 1108, 1111, 1114, 1116, 1118, 1121, 1123, 1125, 1127, 1129, 1132, 1134, 1137, 1141, 1143, 1145, 1147, 1150, 1153, 1155, 1157, 1160, 1162, 1164, 1167, 1169, 1171, 1173, 1175, 1177, 1179, 1181, 1183, 1185, 1187, 1189, 1191, 1193, 1195, 1196, 1199, 1201, 1203, 1207, 1209, 1211, 1215, 1217, 1219, 1221, 1223, 1225, 1227, 1233, 1235, 1237, 1241, 1246, 1252, 1258, 1265, 1268, 1271, 1273, 1275, 1277, 1279, 1281, 1283, 1285, 1289, 1293, 1297, 1301, 1305, 1309, 1313, 1317, 1321, 1325, 1329, 1333, 1337, 1341, 1345, 1349, 1355, 1358, 1361, 1364, 1367, 1370, 1372, 1373, 1377, 1379, 1381, 1385, 1388, 1393, 1395, 1397, 1399, 1401, 1403, 1405, 1407, 1409, 1411, 1413, 1415, 1420, 1426, 1428, 1432, 1436, 1441, 1446, 1450, 1453, 1455, 1457, 1461, 1464, 1468, 1470, 1472, 1474, 1476, 1478, 1481, 1486, 1488, 1492, 1494, 1498, 1502, 1505, 1508, 1511, 1514, 1517, 1522, 1524, 1528, 1530, 1534, 1538, 1541, 1544, 1547, 1550, 1552, 1554, 1556, 1558, 1562, 1564, 1568, 1574, 1576, 1580, 1584, 1590, 1592, 1594 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int16 yyrhs[] = { 128, 0, -1, 129, -1, 107, 215, 40, -1, 107, 1, -1, 108, 215, 40, -1, 108, 1, -1, 109, 37, 212, 38, 40, -1, 109, 1, 40, -1, 129, 130, -1, 274, -1, 131, -1, 168, -1, 176, -1, 40, -1, 1, -1, 175, -1, 1, 106, -1, 132, -1, 134, -1, 135, -1, 136, -1, 137, -1, 138, -1, 141, -1, 142, -1, 145, -1, 146, -1, 147, -1, 148, -1, 149, -1, 150, -1, 153, -1, 155, -1, 158, -1, 160, -1, 165, -1, 166, -1, 167, -1, -1, 61, 271, 264, 43, 133, 193, 44, -1, 85, 164, 43, 162, 44, -1, 86, 162, 40, -1, 57, 3, 51, 237, 40, -1, 57, 231, 223, 220, 40, -1, 57, 1, 40, -1, 84, 4, -1, 84, 269, -1, 83, 37, 3, 38, 43, -1, 83, 43, -1, 83, 37, 3, 38, 40, -1, 83, 40, -1, 269, 43, 215, 44, -1, 269, -1, 139, -1, 88, 37, 140, 39, 272, 38, 4, -1, 88, 37, 140, 39, 272, 38, 43, -1, 88, 37, 140, 38, 40, -1, -1, 144, 271, 269, 54, 143, 129, 55, -1, 7, -1, 8, -1, 81, 4, -1, 81, 43, -1, 4, -1, 9, 37, 262, 38, 269, -1, 9, 37, 262, 38, 4, -1, 9, 37, 262, 38, 43, -1, 53, 271, 262, -1, 58, 37, 262, 38, -1, 58, 37, 38, -1, 80, 37, 3, 38, 211, 3, 40, -1, 80, 37, 3, 38, 211, 231, 223, 40, -1, 62, 152, 3, 51, 151, -1, 62, 152, 3, -1, 269, -1, 4, -1, 37, 3, 38, -1, 274, -1, 154, 223, 262, 40, -1, 154, 37, 272, 38, 223, 256, 40, -1, 154, 37, 272, 38, 269, 40, -1, 59, -1, 60, -1, 63, 37, 262, 38, 223, 256, 156, -1, 63, 37, 262, 39, 273, 38, 223, 256, 40, -1, 63, 37, 262, 157, 38, 223, 256, 156, -1, 63, 37, 262, 39, 273, 157, 38, 223, 256, 40, -1, 63, 37, 262, 38, 156, -1, 63, 37, 262, 39, 273, 38, 40, -1, 63, 37, 262, 157, 38, 156, -1, 63, 37, 262, 39, 273, 157, 38, 40, -1, 270, -1, 40, -1, 100, 37, 212, 38, 40, -1, 39, 262, 51, 273, -1, 39, 262, 51, 273, 157, -1, 64, 37, 159, 38, 223, 256, 40, -1, 212, -1, 11, 39, 215, -1, 82, 37, 161, 38, 162, 270, -1, 82, 37, 161, 38, 162, 40, -1, 82, 37, 161, 38, 162, 51, 164, 40, -1, 272, -1, 164, 163, -1, 39, 164, 163, -1, 274, -1, 231, 222, -1, 37, 212, 38, -1, 37, 212, 38, 37, 212, 38, -1, 99, 37, 212, 38, 40, -1, 87, 37, 263, 38, 267, 90, 216, 91, 40, -1, 89, 269, -1, 170, -1, 174, -1, 173, -1, -1, 41, 269, 43, 169, 129, 44, -1, 211, 231, 223, 172, 171, -1, 40, -1, 39, 223, 172, 171, -1, 43, -1, 220, -1, 229, 220, -1, 75, 37, 212, 38, 220, -1, 229, 75, 37, 212, 38, 220, -1, 211, 65, 3, 40, -1, 211, 65, 239, 43, 240, 44, 40, -1, 211, 65, 239, 43, 240, 44, 223, 171, -1, 211, 231, 37, 212, 38, 257, -1, 177, -1, 181, -1, 182, -1, 189, -1, 190, -1, 200, -1, -1, 211, 254, 264, 247, 43, 178, 193, 44, 180, -1, -1, 211, 254, 43, 179, 193, 44, 223, 171, -1, 40, -1, 223, 171, -1, 211, 254, 264, 40, -1, -1, 104, 90, 185, 91, 183, 184, -1, 104, 254, 264, -1, 170, -1, 177, -1, 197, -1, 182, -1, 181, -1, 199, -1, 186, -1, 187, 188, -1, 274, -1, 253, -1, 215, -1, 39, 187, 188, -1, 274, -1, 78, 264, 40, -1, 78, 79, 264, 40, -1, -1, 79, 264, 43, 191, 129, 44, -1, -1, 79, 43, 192, 129, 44, -1, 79, 3, 51, 264, 40, -1, 196, 193, -1, -1, 61, 43, 194, 193, 44, 193, -1, 142, -1, 274, -1, -1, 1, 195, 193, -1, 168, -1, 197, -1, 198, -1, 201, -1, 207, -1, 199, -1, 181, -1, 202, -1, 211, 264, 40, -1, 189, -1, 182, -1, 200, -1, 166, -1, 167, -1, 210, -1, 141, -1, 165, -1, 40, -1, 211, 231, 37, 212, 38, 257, -1, 124, 266, 37, 212, 38, 208, -1, 73, 124, 266, 37, 212, 38, 209, -1, 211, 106, 231, 228, 37, 212, 38, 209, -1, 211, 106, 231, 115, 37, 212, 38, 209, -1, 211, 106, 231, 37, 212, 38, 209, -1, 76, 37, 212, 38, 43, -1, 69, 71, -1, 68, 71, -1, 70, 71, -1, -1, 211, 254, 3, 43, 203, 206, 40, -1, -1, 211, 254, 43, 204, 206, 40, -1, -1, 211, 254, 264, 71, 250, 43, 205, 40, -1, 223, -1, 274, -1, 150, -1, 136, -1, 148, -1, 153, -1, 155, -1, 158, -1, 146, -1, 160, -1, 134, -1, 135, -1, 137, -1, 256, 40, -1, 256, 43, -1, 256, 40, -1, 256, 51, 237, 40, -1, 256, 43, -1, 211, 231, 71, 243, 40, -1, 41, -1, 41, 269, -1, 72, -1, 18, -1, 73, -1, 74, -1, 77, -1, 274, -1, 213, -1, 215, 214, -1, 274, -1, 39, 215, 214, -1, 274, -1, 232, 221, -1, 104, 90, 254, 91, 254, 264, -1, 45, 45, 45, -1, 217, -1, 219, 218, -1, 274, -1, 39, 219, 218, -1, 274, -1, 215, -1, 244, -1, 51, 237, -1, 51, 237, 54, 243, 55, -1, 51, 43, -1, 71, 243, -1, 274, -1, 223, 220, -1, 226, 220, -1, 220, -1, 223, -1, 226, -1, 274, -1, 228, 224, -1, 228, 115, 224, -1, 225, -1, 115, 224, -1, 264, 102, 224, -1, 228, 264, 102, 224, -1, 228, 264, 102, 115, 224, -1, 264, 102, 115, 224, -1, 264, -1, 124, 264, -1, 37, 264, 38, -1, 37, 228, 224, 38, -1, 37, 264, 102, 224, 38, -1, 224, 54, 55, -1, 224, 54, 243, 55, -1, 224, 37, 212, 38, -1, 264, -1, 124, 264, -1, 37, 228, 225, 38, -1, 37, 115, 225, 38, -1, 37, 264, 102, 225, 38, -1, 225, 54, 55, -1, 225, 54, 243, 55, -1, 225, 37, 212, 38, -1, 228, -1, 228, 227, -1, 228, 115, -1, 228, 115, 227, -1, 227, -1, 115, 227, -1, 115, -1, 264, 102, -1, 228, 264, 102, -1, 228, 264, 102, 227, -1, 227, 54, 55, -1, 227, 54, 243, 55, -1, 54, 55, -1, 54, 243, 55, -1, 37, 226, 38, -1, 227, 37, 212, 38, -1, 37, 212, 38, -1, 122, 229, 228, -1, 122, 228, -1, 122, 229, -1, 122, -1, 230, -1, 230, 229, -1, 46, -1, 47, -1, 48, -1, 232, -1, 229, 233, -1, 233, -1, 233, 229, -1, 229, 233, 229, -1, 234, -1, 29, -1, 27, -1, 31, 261, -1, 65, 264, -1, 32, -1, 264, -1, 254, 264, -1, 235, -1, 236, -1, 236, 235, -1, 19, -1, 21, -1, 22, -1, 25, -1, 26, -1, 23, -1, 24, -1, 28, -1, 20, -1, 30, -1, 33, -1, 34, -1, 35, -1, 36, -1, -1, 238, 243, -1, 3, -1, 274, -1, 240, 39, 241, -1, 241, -1, 3, -1, 3, 51, 242, -1, 274, -1, 243, -1, 244, -1, 231, -1, 245, -1, 269, -1, 52, 37, 231, 221, 38, -1, 246, -1, 10, -1, 37, 243, 38, -1, 37, 243, 38, 243, -1, 37, 243, 228, 38, 243, -1, 37, 243, 115, 38, 243, -1, 37, 243, 228, 115, 38, 243, -1, 115, 243, -1, 122, 243, -1, 11, -1, 12, -1, 13, -1, 14, -1, 15, -1, 16, -1, 17, -1, 243, 119, 243, -1, 243, 118, 243, -1, 243, 122, 243, -1, 243, 121, 243, -1, 243, 120, 243, -1, 243, 115, 243, -1, 243, 113, 243, -1, 243, 114, 243, -1, 243, 117, 243, -1, 243, 116, 243, -1, 243, 112, 243, -1, 243, 111, 243, -1, 243, 96, 243, -1, 243, 97, 243, -1, 243, 95, 243, -1, 243, 94, 243, -1, 243, 98, 243, 71, 243, -1, 118, 243, -1, 119, 243, -1, 124, 243, -1, 123, 243, -1, 231, 37, -1, 248, -1, -1, 71, 249, 250, -1, 274, -1, 251, -1, 250, 39, 251, -1, 255, 264, -1, 255, 252, 255, 264, -1, 69, -1, 68, -1, 70, -1, 66, -1, 67, -1, 253, -1, 49, -1, 50, -1, 73, -1, 274, -1, 229, -1, 75, 37, 212, 38, -1, 229, 75, 37, 212, 38, -1, 274, -1, 256, 258, 40, -1, 256, 258, 43, -1, 37, 212, 38, 40, -1, 37, 212, 38, 43, -1, 51, 237, 40, -1, 71, 259, -1, 274, -1, 260, -1, 259, 39, 260, -1, 264, 37, -1, 90, 216, 91, -1, 274, -1, 3, -1, 269, -1, 262, -1, 274, -1, 266, 265, -1, 101, 126, 266, 265, -1, 266, -1, 101, 126, 266, -1, 105, -1, 101, 126, 105, -1, 126, 266, 265, -1, 126, 266, -1, 126, 105, -1, 103, 266, -1, 3, 261, -1, 3, 268, -1, 101, 126, 3, 268, -1, 3, -1, 101, 126, 3, -1, 105, -1, 101, 126, 105, -1, 126, 3, 268, -1, 126, 3, -1, 126, 105, -1, 103, 3, -1, 269, 6, -1, 6, -1, 269, -1, 43, -1, 4, -1, 37, 272, 38, -1, 274, -1, 262, 51, 273, -1, 262, 51, 273, 39, 272, -1, 262, -1, 262, 39, 272, -1, 262, 51, 139, -1, 262, 51, 139, 39, 272, -1, 269, -1, 245, -1, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 1502, 1502, 1515, 1519, 1522, 1525, 1528, 1531, 1536, 1541, 1546, 1547, 1548, 1549, 1550, 1556, 1572, 1582, 1583, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1602, 1609, 1609, 1681, 1691, 1702, 1723, 1745, 1756, 1765, 1784, 1790, 1796, 1801, 1812, 1819, 1823, 1828, 1837, 1852, 1865, 1865, 1915, 1916, 1923, 1943, 1974, 1978, 1988, 1993, 2011, 2045, 2051, 2064, 2070, 2096, 2102, 2109, 2110, 2113, 2114, 2122, 2168, 2214, 2225, 2228, 2255, 2260, 2265, 2270, 2277, 2282, 2287, 2292, 2299, 2300, 2301, 2304, 2309, 2319, 2355, 2356, 2386, 2420, 2428, 2441, 2466, 2472, 2476, 2479, 2490, 2495, 2507, 2517, 2784, 2794, 2801, 2802, 2806, 2806, 2837, 2898, 2902, 2924, 2930, 2936, 2942, 2948, 2961, 2976, 2986, 3064, 3115, 3116, 3117, 3118, 3119, 3120, 3126, 3126, 3358, 3358, 3480, 3481, 3493, 3513, 3513, 3748, 3754, 3757, 3760, 3763, 3766, 3769, 3774, 3804, 3808, 3811, 3814, 3819, 3823, 3828, 3838, 3869, 3869, 3898, 3898, 3920, 3947, 3962, 3962, 3972, 3973, 3974, 3974, 3990, 3991, 4008, 4009, 4010, 4011, 4012, 4013, 4014, 4015, 4016, 4017, 4018, 4019, 4020, 4021, 4022, 4023, 4032, 4057, 4081, 4121, 4136, 4154, 4173, 4180, 4187, 4195, 4218, 4218, 4253, 4253, 4284, 4284, 4302, 4303, 4309, 4312, 4316, 4319, 4320, 4321, 4322, 4323, 4324, 4325, 4326, 4329, 4334, 4341, 4349, 4357, 4368, 4374, 4375, 4383, 4384, 4385, 4386, 4387, 4388, 4395, 4406, 4414, 4417, 4421, 4425, 4435, 4440, 4448, 4461, 4469, 4472, 4476, 4480, 4508, 4516, 4527, 4541, 4550, 4558, 4568, 4572, 4576, 4583, 4600, 4617, 4625, 4633, 4642, 4646, 4655, 4666, 4678, 4688, 4701, 4708, 4716, 4732, 4740, 4751, 4762, 4773, 4792, 4800, 4817, 4825, 4832, 4843, 4854, 4865, 4884, 4890, 4896, 4903, 4912, 4915, 4924, 4931, 4938, 4948, 4959, 4970, 4981, 4988, 4995, 4998, 5015, 5025, 5032, 5038, 5043, 5049, 5053, 5059, 5060, 5061, 5067, 5073, 5077, 5078, 5082, 5089, 5092, 5093, 5094, 5095, 5096, 5098, 5101, 5106, 5131, 5134, 5188, 5192, 5196, 5200, 5204, 5208, 5212, 5216, 5220, 5224, 5228, 5232, 5236, 5240, 5246, 5246, 5272, 5273, 5276, 5289, 5297, 5305, 5322, 5325, 5340, 5341, 5360, 5361, 5365, 5370, 5371, 5385, 5392, 5398, 5405, 5412, 5420, 5424, 5430, 5431, 5432, 5433, 5434, 5435, 5436, 5439, 5443, 5447, 5451, 5455, 5459, 5463, 5467, 5471, 5475, 5479, 5483, 5487, 5491, 5505, 5512, 5516, 5522, 5526, 5530, 5534, 5538, 5554, 5559, 5559, 5560, 5563, 5580, 5589, 5602, 5615, 5616, 5617, 5621, 5625, 5631, 5634, 5638, 5644, 5645, 5648, 5653, 5658, 5663, 5670, 5677, 5684, 5692, 5700, 5708, 5709, 5712, 5713, 5716, 5722, 5728, 5731, 5732, 5735, 5736, 5739, 5744, 5748, 5751, 5754, 5757, 5762, 5766, 5769, 5776, 5782, 5791, 5796, 5800, 5803, 5806, 5809, 5814, 5818, 5821, 5824, 5830, 5835, 5838, 5841, 5845, 5850, 5863, 5867, 5872, 5878, 5882, 5887, 5891, 5898, 5901, 5906 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "ID", "HBLOCK", "POUND", "STRING", "INCLUDE", "IMPORT", "INSERT", "CHARCONST", "NUM_INT", "NUM_FLOAT", "NUM_UNSIGNED", "NUM_LONG", "NUM_ULONG", "NUM_LONGLONG", "NUM_ULONGLONG", "TYPEDEF", "TYPE_INT", "TYPE_UNSIGNED", "TYPE_SHORT", "TYPE_LONG", "TYPE_FLOAT", "TYPE_DOUBLE", "TYPE_CHAR", "TYPE_WCHAR", "TYPE_VOID", "TYPE_SIGNED", "TYPE_BOOL", "TYPE_COMPLEX", "TYPE_TYPEDEF", "TYPE_RAW", "TYPE_NON_ISO_INT8", "TYPE_NON_ISO_INT16", "TYPE_NON_ISO_INT32", "TYPE_NON_ISO_INT64", "LPAREN", "RPAREN", "COMMA", "SEMI", "EXTERN", "INIT", "LBRACE", "RBRACE", "PERIOD", "CONST_QUAL", "VOLATILE", "REGISTER", "STRUCT", "UNION", "EQUAL", "SIZEOF", "MODULE", "LBRACKET", "RBRACKET", "ILLEGAL", "CONSTANT", "NAME", "RENAME", "NAMEWARN", "EXTEND", "PRAGMA", "FEATURE", "VARARGS", "ENUM", "CLASS", "TYPENAME", "PRIVATE", "PUBLIC", "PROTECTED", "COLON", "STATIC", "VIRTUAL", "FRIEND", "THROW", "CATCH", "EXPLICIT", "USING", "NAMESPACE", "NATIVE", "INLINE", "TYPEMAP", "EXCEPT", "ECHO", "APPLY", "CLEAR", "SWIGTEMPLATE", "FRAGMENT", "WARN", "LESSTHAN", "GREATERTHAN", "MODULO", "DELETE_KW", "LESSTHANOREQUALTO", "GREATERTHANOREQUALTO", "EQUALTO", "NOTEQUALTO", "QUESTIONMARK", "TYPES", "PARMS", "NONID", "DSTAR", "DCNOT", "TEMPLATE", "OPERATOR", "COPERATOR", "PARSETYPE", "PARSEPARM", "PARSEPARMS", "CAST", "LOR", "LAND", "OR", "XOR", "AND", "RSHIFT", "LSHIFT", "MINUS", "PLUS", "MODULUS", "SLASH", "STAR", "LNOT", "NOT", "UMINUS", "DCOLON", "$accept", "program", "interface", "declaration", "swig_directive", "extend_directive", "@1", "apply_directive", "clear_directive", "constant_directive", "echo_directive", "except_directive", "stringtype", "fname", "fragment_directive", "include_directive", "@2", "includetype", "inline_directive", "insert_directive", "module_directive", "name_directive", "native_directive", "pragma_directive", "pragma_arg", "pragma_lang", "rename_directive", "rename_namewarn", "feature_directive", "stringbracesemi", "featattr", "varargs_directive", "varargs_parms", "typemap_directive", "typemap_type", "tm_list", "tm_tail", "typemap_parm", "types_directive", "template_directive", "warn_directive", "c_declaration", "@3", "c_decl", "c_decl_tail", "initializer", "c_enum_forward_decl", "c_enum_decl", "c_constructor_decl", "cpp_declaration", "cpp_class_decl", "@4", "@5", "cpp_opt_declarators", "cpp_forward_class_decl", "cpp_template_decl", "@6", "cpp_temp_possible", "template_parms", "templateparameters", "templateparameter", "templateparameterstail", "cpp_using_decl", "cpp_namespace_decl", "@7", "@8", "cpp_members", "@9", "@10", "cpp_member", "cpp_constructor_decl", "cpp_destructor_decl", "cpp_conversion_operator", "cpp_catch_decl", "cpp_protection_decl", "cpp_nested", "@11", "@12", "@13", "nested_decl", "cpp_swig_directive", "cpp_end", "cpp_vend", "anonymous_bitfield", "storage_class", "parms", "rawparms", "ptail", "parm", "valparms", "rawvalparms", "valptail", "valparm", "def_args", "parameter_declarator", "typemap_parameter_declarator", "declarator", "notso_direct_declarator", "direct_declarator", "abstract_declarator", "direct_abstract_declarator", "pointer", "type_qualifier", "type_qualifier_raw", "type", "rawtype", "type_right", "primitive_type", "primitive_type_list", "type_specifier", "definetype", "@14", "ename", "enumlist", "edecl", "etype", "expr", "valexpr", "exprnum", "exprcompound", "inherit", "raw_inherit", "@15", "base_list", "base_specifier", "access_specifier", "templcpptype", "cpptype", "opt_virtual", "cpp_const", "ctor_end", "ctor_initializer", "mem_initializer_list", "mem_initializer", "template_decl", "idstring", "idstringopt", "idcolon", "idcolontail", "idtemplate", "idcolonnt", "idcolontailnt", "string", "stringbrace", "options", "kwargs", "stringnum", "empty", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint16 yyr1[] = { 0, 127, 128, 128, 128, 128, 128, 128, 128, 129, 129, 130, 130, 130, 130, 130, 130, 130, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 133, 132, 134, 135, 136, 136, 136, 137, 137, 138, 138, 138, 138, 139, 140, 140, 141, 141, 141, 143, 142, 144, 144, 145, 145, 146, 146, 146, 146, 147, 148, 148, 149, 149, 150, 150, 151, 151, 152, 152, 153, 153, 153, 154, 154, 155, 155, 155, 155, 155, 155, 155, 155, 156, 156, 156, 157, 157, 158, 159, 159, 160, 160, 160, 161, 162, 163, 163, 164, 164, 164, 165, 166, 167, 168, 168, 168, 169, 168, 170, 171, 171, 171, 172, 172, 172, 172, 173, 174, 174, 175, 176, 176, 176, 176, 176, 176, 178, 177, 179, 177, 180, 180, 181, 183, 182, 182, 184, 184, 184, 184, 184, 184, 185, 186, 186, 187, 187, 188, 188, 189, 189, 191, 190, 192, 190, 190, 193, 194, 193, 193, 193, 195, 193, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 197, 198, 198, 199, 199, 199, 200, 201, 201, 201, 203, 202, 204, 202, 205, 202, 206, 206, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 208, 208, 209, 209, 209, 210, 211, 211, 211, 211, 211, 211, 211, 211, 212, 213, 213, 214, 214, 215, 215, 215, 216, 217, 217, 218, 218, 219, 219, 220, 220, 220, 220, 220, 221, 221, 221, 222, 222, 222, 223, 223, 223, 223, 223, 223, 223, 223, 224, 224, 224, 224, 224, 224, 224, 224, 225, 225, 225, 225, 225, 225, 225, 225, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 227, 227, 227, 227, 227, 227, 227, 228, 228, 228, 228, 229, 229, 230, 230, 230, 231, 232, 232, 232, 232, 233, 233, 233, 233, 233, 233, 233, 233, 234, 235, 235, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 238, 237, 239, 239, 240, 240, 241, 241, 241, 242, 243, 243, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 245, 245, 245, 245, 245, 245, 245, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 247, 249, 248, 248, 250, 250, 251, 251, 252, 252, 252, 253, 253, 254, 254, 254, 255, 255, 256, 256, 256, 256, 257, 257, 257, 257, 257, 258, 258, 259, 259, 260, 261, 261, 262, 262, 263, 263, 264, 264, 264, 264, 264, 264, 265, 265, 265, 265, 266, 267, 267, 267, 267, 267, 267, 268, 268, 268, 268, 269, 269, 270, 270, 270, 271, 271, 272, 272, 272, 272, 272, 272, 273, 273, 274 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 3, 2, 3, 2, 5, 3, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 7, 5, 3, 5, 5, 3, 2, 2, 5, 2, 5, 2, 4, 1, 1, 7, 7, 5, 0, 7, 1, 1, 2, 2, 1, 5, 5, 5, 3, 4, 3, 7, 8, 5, 3, 1, 1, 3, 1, 4, 7, 6, 1, 1, 7, 9, 8, 10, 5, 7, 6, 8, 1, 1, 5, 4, 5, 7, 1, 3, 6, 6, 8, 1, 2, 3, 1, 2, 3, 6, 5, 9, 2, 1, 1, 1, 0, 6, 5, 1, 4, 1, 1, 2, 5, 6, 4, 7, 8, 6, 1, 1, 1, 1, 1, 1, 0, 9, 0, 8, 1, 2, 4, 0, 6, 3, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 1, 3, 4, 0, 6, 0, 5, 5, 2, 0, 6, 1, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 6, 7, 8, 8, 7, 5, 2, 2, 2, 0, 7, 0, 6, 0, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 4, 2, 5, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, 1, 2, 6, 3, 1, 2, 1, 3, 1, 1, 1, 2, 5, 2, 2, 1, 2, 2, 1, 1, 1, 1, 2, 3, 1, 2, 3, 4, 5, 4, 1, 2, 3, 4, 5, 3, 4, 4, 1, 2, 4, 4, 5, 3, 4, 4, 1, 2, 2, 3, 1, 2, 1, 2, 3, 4, 3, 4, 2, 3, 3, 4, 3, 3, 2, 2, 1, 1, 2, 1, 1, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 1, 1, 3, 1, 1, 3, 1, 1, 1, 1, 1, 1, 5, 1, 1, 3, 4, 5, 5, 6, 2, 2, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 2, 2, 2, 2, 2, 1, 0, 3, 1, 1, 3, 2, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 5, 1, 3, 3, 4, 4, 3, 2, 1, 1, 3, 2, 3, 1, 1, 1, 1, 1, 2, 4, 1, 3, 1, 3, 3, 2, 2, 2, 2, 2, 4, 1, 3, 1, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 1, 3, 5, 1, 3, 3, 5, 1, 1, 0 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint16 yydefact[] = { 467, 0, 0, 0, 0, 0, 10, 4, 467, 326, 334, 327, 328, 331, 332, 329, 330, 317, 333, 316, 335, 467, 320, 336, 337, 338, 339, 0, 307, 308, 309, 407, 408, 0, 404, 405, 0, 0, 435, 0, 0, 305, 467, 312, 315, 323, 324, 406, 0, 321, 433, 6, 0, 0, 467, 1, 15, 64, 60, 61, 0, 229, 14, 226, 467, 0, 0, 82, 83, 467, 467, 0, 0, 228, 230, 231, 0, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 11, 18, 19, 20, 21, 22, 23, 24, 25, 467, 26, 27, 28, 29, 30, 31, 32, 0, 33, 34, 35, 36, 37, 38, 12, 113, 115, 114, 16, 13, 130, 131, 132, 133, 134, 135, 0, 233, 467, 441, 426, 318, 0, 319, 0, 0, 3, 311, 306, 467, 340, 0, 0, 290, 304, 0, 256, 239, 467, 262, 467, 288, 284, 276, 253, 313, 325, 322, 0, 0, 431, 5, 8, 0, 234, 467, 236, 17, 0, 453, 227, 0, 0, 458, 0, 467, 0, 310, 0, 0, 0, 0, 78, 0, 467, 467, 0, 0, 467, 163, 0, 0, 62, 63, 0, 0, 51, 49, 46, 47, 467, 0, 467, 0, 467, 467, 0, 112, 467, 467, 0, 0, 0, 0, 0, 0, 276, 467, 0, 0, 356, 364, 365, 366, 367, 368, 369, 370, 0, 0, 0, 0, 0, 0, 0, 0, 247, 0, 242, 467, 351, 310, 0, 350, 352, 355, 353, 244, 241, 436, 434, 0, 314, 467, 290, 0, 0, 284, 321, 251, 249, 0, 296, 0, 350, 252, 467, 0, 263, 289, 268, 302, 303, 277, 254, 467, 0, 255, 467, 0, 286, 260, 285, 268, 291, 440, 439, 438, 0, 0, 235, 238, 427, 0, 428, 452, 116, 461, 0, 68, 45, 340, 0, 467, 70, 0, 0, 0, 74, 0, 0, 0, 98, 0, 0, 159, 0, 467, 161, 0, 0, 103, 0, 0, 0, 107, 257, 258, 259, 42, 0, 104, 106, 429, 0, 430, 54, 0, 53, 0, 0, 152, 467, 156, 406, 154, 145, 0, 427, 0, 0, 0, 0, 0, 0, 0, 268, 0, 467, 0, 343, 467, 467, 138, 322, 0, 0, 362, 388, 389, 363, 391, 390, 425, 0, 243, 246, 392, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 432, 0, 290, 284, 321, 0, 276, 300, 298, 286, 0, 276, 291, 0, 341, 297, 284, 321, 269, 467, 0, 301, 0, 281, 0, 0, 294, 0, 261, 287, 292, 0, 264, 437, 7, 467, 0, 467, 0, 0, 457, 0, 0, 69, 39, 77, 0, 0, 0, 0, 0, 0, 0, 160, 0, 0, 467, 467, 0, 0, 108, 0, 467, 0, 0, 0, 0, 0, 143, 0, 153, 158, 58, 0, 0, 0, 0, 79, 0, 126, 467, 0, 321, 0, 0, 122, 467, 0, 142, 394, 0, 393, 396, 357, 0, 304, 0, 467, 467, 386, 385, 383, 384, 0, 382, 381, 377, 378, 376, 380, 379, 372, 371, 375, 374, 373, 0, 0, 291, 279, 278, 292, 0, 0, 0, 268, 270, 291, 0, 273, 0, 283, 282, 299, 295, 0, 265, 293, 267, 237, 66, 67, 65, 0, 462, 463, 466, 465, 459, 43, 44, 0, 76, 73, 75, 456, 93, 455, 0, 88, 467, 454, 92, 0, 465, 0, 0, 99, 467, 197, 165, 164, 0, 226, 0, 0, 50, 48, 467, 41, 105, 444, 0, 446, 0, 57, 0, 0, 110, 467, 467, 467, 467, 0, 0, 346, 0, 345, 348, 467, 467, 0, 119, 121, 118, 0, 123, 171, 190, 0, 0, 0, 0, 230, 0, 217, 218, 210, 219, 188, 169, 215, 211, 209, 212, 213, 214, 216, 189, 185, 186, 173, 179, 183, 182, 0, 0, 174, 175, 178, 184, 176, 180, 177, 187, 0, 233, 467, 136, 358, 0, 304, 303, 0, 0, 0, 245, 0, 240, 280, 250, 271, 0, 275, 274, 266, 117, 0, 0, 0, 467, 0, 411, 0, 414, 0, 0, 0, 0, 90, 467, 0, 162, 227, 467, 0, 101, 0, 100, 0, 0, 0, 442, 0, 467, 0, 52, 146, 147, 150, 149, 144, 148, 151, 0, 157, 0, 0, 81, 0, 467, 0, 467, 340, 467, 129, 0, 467, 467, 0, 167, 199, 198, 200, 0, 0, 0, 166, 0, 0, 0, 321, 409, 395, 397, 0, 410, 0, 360, 359, 0, 354, 387, 272, 464, 460, 40, 0, 467, 0, 84, 465, 95, 89, 467, 0, 0, 97, 71, 0, 0, 109, 451, 449, 450, 445, 447, 0, 55, 56, 0, 59, 80, 347, 349, 344, 127, 0, 0, 0, 0, 0, 421, 467, 0, 0, 172, 0, 0, 467, 0, 0, 467, 0, 467, 203, 322, 181, 467, 402, 401, 403, 467, 399, 0, 361, 0, 0, 467, 96, 0, 91, 467, 86, 72, 102, 448, 443, 0, 128, 0, 419, 420, 422, 0, 415, 416, 124, 120, 467, 0, 467, 0, 139, 467, 0, 0, 0, 0, 201, 467, 467, 398, 0, 0, 94, 412, 0, 85, 0, 111, 417, 418, 0, 424, 125, 0, 0, 467, 0, 467, 467, 467, 225, 467, 0, 207, 208, 0, 400, 140, 137, 0, 413, 87, 423, 168, 467, 192, 0, 467, 0, 0, 191, 0, 204, 205, 141, 193, 0, 220, 221, 196, 467, 467, 202, 0, 222, 224, 340, 195, 194, 206, 0, 223 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 4, 5, 92, 93, 94, 549, 613, 614, 615, 616, 99, 339, 340, 617, 618, 589, 102, 103, 619, 105, 620, 107, 621, 551, 184, 622, 110, 623, 557, 447, 624, 314, 625, 323, 206, 334, 207, 626, 627, 628, 629, 435, 118, 602, 482, 119, 120, 121, 122, 123, 735, 485, 869, 630, 631, 587, 699, 343, 344, 345, 468, 632, 127, 454, 320, 633, 785, 717, 634, 635, 636, 637, 638, 639, 640, 862, 838, 894, 863, 641, 876, 886, 642, 643, 258, 167, 293, 168, 240, 241, 378, 242, 149, 150, 328, 151, 271, 152, 153, 154, 218, 40, 41, 243, 180, 43, 44, 45, 46, 263, 264, 362, 594, 595, 771, 245, 267, 247, 248, 488, 489, 645, 731, 732, 800, 47, 48, 733, 887, 713, 779, 820, 821, 132, 300, 337, 49, 163, 50, 582, 690, 249, 560, 175, 301, 546, 169 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -713 static const yytype_int16 yypact[] = { 621, 3162, 3212, 209, 89, 2717, -713, -713, -54, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -54, -713, -713, -713, -713, -713, 87, -713, -713, -713, -713, -713, 85, -713, -713, 7, 80, -713, 117, 3717, 353, 302, 353, -713, -713, 1331, -713, 85, -713, 127, -713, 171, 189, 3470, -713, 156, -713, -713, -713, 204, -713, -713, 259, 237, 3272, 250, -713, -713, 237, 263, 297, 312, -713, -713, -713, 323, -713, 36, 338, 332, 184, 348, 340, 465, 3519, 3519, 356, 371, 259, 376, 613, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, 237, -713, -713, -713, -713, -713, -713, -713, 987, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, 3569, -713, 1649, -713, -713, -713, 334, -713, 38, 656, -713, 353, -713, 1282, 378, 1771, 2381, 135, 244, 85, -713, -713, 192, 200, 192, 292, 281, 339, -713, -713, -713, -713, 446, 49, -713, -713, -713, 435, -713, 447, -713, -713, 178, -713, 105, 178, 178, -713, 464, 219, 1031, -713, 222, 85, 525, 537, -713, 178, 3420, 3470, 85, 470, 221, -713, 511, 547, -713, -713, 178, 554, -713, -713, -713, 558, 3470, 530, 305, 534, 539, 178, 259, 558, 3470, 3470, 85, 259, 412, 97, 178, 333, 481, 177, 1032, 341, -713, -713, -713, -713, -713, -713, -713, -713, 2381, 565, 2381, 2381, 2381, 2381, 2381, 2381, -713, 519, -713, 574, 583, 180, 1747, -1, -713, -713, 558, -713, -713, -713, 127, 535, -713, 1409, 273, 597, 600, 639, 552, -713, 585, 2381, -713, 1856, -713, 1747, 1409, 85, 301, 292, -713, -713, 527, -713, -713, 3470, 1893, -713, 3470, 2015, 135, 301, 292, 553, 822, -713, -713, 127, 601, 3470, -713, -713, -713, 623, 558, -713, -713, 134, 626, -713, -713, -713, 41, 192, -713, 630, 627, 637, 638, 483, 633, 653, -713, 661, 654, -713, 85, -713, -713, 669, 672, -713, 673, 681, 3519, -713, -713, -713, -713, -713, 3519, -713, -713, -713, 682, -713, -713, 509, 123, 688, 640, -713, 699, -713, 84, -713, -713, 31, 342, 198, 198, 641, 713, 94, 720, 97, 651, 822, 104, 721, -713, 2553, 1129, -713, 64, 1608, 3618, 1421, -713, -713, -713, -713, -713, -713, 1649, -713, -713, -713, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, 2381, -713, 656, 303, 91, 666, 357, -713, -713, -713, 303, 393, 676, 198, 2381, 1747, -713, 766, -9, -713, 3470, 2137, -713, 745, -713, 1978, 746, -713, 2100, 301, 292, 1091, 97, 301, -713, -713, 447, 218, -713, 178, 1867, -713, 749, 753, -713, -713, -713, 529, 916, 1728, 757, 3470, 1031, 758, -713, 762, 2806, -713, 611, 3519, 385, 771, 765, 539, 223, 772, 178, 3470, 773, -713, 3470, -713, -713, -713, 198, 365, 97, 23, -713, 1000, -713, 811, 777, 641, 781, 634, -713, 279, 1543, -713, -713, 778, -713, -713, 2381, 2259, 2503, -6, 302, 574, 1104, 1104, 1154, 1154, 2585, 1373, 1989, 1641, 2111, 1421, 628, 628, 685, 685, -713, -713, -713, 85, 676, -713, -713, -713, 303, 438, 2222, 488, 676, -713, 97, 786, -713, 2344, -713, -713, -713, -713, 97, 301, 292, 301, -713, -713, -713, 558, 2895, -713, 789, -713, 123, 790, -713, -713, 1543, -713, -713, 558, -713, -713, -713, 793, -713, 344, 558, -713, 780, 59, 521, 916, -713, 344, -713, -713, -713, 2984, 259, 3668, 647, -713, -713, 3470, -713, -713, 195, 707, -713, 744, -713, 799, 801, -713, 937, 699, -713, 344, 16, 97, 792, 319, -713, -713, 649, 3470, 1031, -713, -713, -713, 810, -713, -713, -713, 805, 782, 784, 794, 728, 446, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, -713, 817, 1543, -713, -713, -713, -713, -713, -713, -713, -713, 3321, 820, 795, -713, 1747, 2381, 2503, 2611, 2381, 828, 832, -713, 2381, -713, -713, -713, -713, 507, -713, -713, 301, -713, 178, 178, 835, 3470, 845, 797, 74, -713, 1867, 847, 178, 851, -713, 344, 846, -713, 558, 124, 1031, -713, 3519, -713, 855, 882, 88, -713, 95, 1649, 269, -713, -713, -713, -713, -713, -713, -713, -713, 3371, -713, 3073, 856, -713, 2381, 811, 860, 3470, -713, 824, -713, 880, 1129, 3470, 1543, -713, -713, -713, -713, 446, 884, 1031, -713, 3618, 903, 413, 885, -713, 887, -713, 718, -713, 1543, 1747, 1747, 2381, -713, 1868, -713, -713, -713, -713, 890, 3470, 893, -713, 558, 892, -713, 344, 965, 74, -713, -713, 894, 899, -713, -713, 195, -713, 195, -713, 841, -713, -713, 1145, -713, -713, -713, 1747, -713, -713, 634, 895, 917, 85, 397, -713, 192, 634, 905, -713, 1543, 921, 3470, 634, 37, 2553, 2381, 128, -713, 254, -713, 795, -713, -713, -713, 795, -713, 922, 1747, 920, 929, 3470, -713, 930, -713, 344, -713, -713, -713, -713, -713, 932, -713, 457, -713, 934, -713, 939, -713, -713, -713, -713, 192, 935, 3470, 942, -713, 3470, 946, 948, 949, 1735, -713, 1031, 795, -713, 85, 992, -713, -713, 951, -713, 954, -713, -713, -713, 85, -713, -713, 1543, 958, 344, 959, 3470, 3470, 649, -713, 1031, 960, -713, -713, 276, -713, -713, -713, 634, -713, -713, -713, -713, 344, -713, 512, 344, 963, 968, -713, 972, -713, -713, -713, -713, 421, -713, -713, -713, 344, 344, -713, 975, -713, -713, -713, -713, -713, -713, 979, -713 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -713, -713, -314, -713, -713, -713, -713, 10, 12, 21, 28, -713, 549, -713, 30, 35, -713, -713, -713, 52, -713, 53, -713, 54, -713, -713, 55, -713, 58, -545, -535, 62, -713, 63, -713, -296, 538, -84, 66, 67, 70, 76, -713, 436, -709, 311, -713, -713, -713, -713, 441, -713, -713, -713, -2, 5, -713, -713, -713, -713, 569, 451, 78, -713, -713, -713, -538, -713, -713, -713, 455, -713, 456, 90, -713, -713, -713, -713, -713, 182, -713, -713, -401, -713, -3, 201, -713, 612, 202, 359, -713, 557, 671, -48, 560, -713, -97, 662, -233, -87, -121, 8, -34, -713, 203, 45, -36, -713, 1003, -713, -288, -713, -713, -713, 349, -713, 848, -111, -423, -713, -713, -713, -713, 217, 265, -713, -200, -37, 262, -513, 205, -713, -713, 212, 1043, -59, -713, 694, -123, -75, -713, -712, 727, 494, -26, -167, -428, 0 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -468 static const yytype_int16 yytable[] = { 6, 204, 129, 124, 140, 130, 453, 141, 133, 158, 125, 667, 347, 217, 544, 95, 439, 96, 563, 677, 246, 133, 298, 544, 403, 272, 97, 408, 676, 524, 324, 459, 651, 98, 285, 100, 131, 298, -248, 8, 101, 8, 157, 182, 8, 671, 42, 42, 355, 814, 155, 815, 8, 679, 213, 259, 706, 104, 106, 108, 109, 524, 253, 111, 176, 298, 817, 112, 113, 176, 185, 114, 115, 826, 832, 116, 214, 705, 553, 831, 172, 117, 306, 126, 712, 470, 288, 290, 8, 55, -248, 761, 222, 525, 8, 128, 725, 8, 763, 42, 8, 254, 176, 277, 486, 280, 255, -467, 329, 652, -428, 298, 296, 275, 554, 189, 302, 555, 330, 403, 408, 541, 308, -155, 365, 592, 748, 312, 256, 298, 398, 250, 135, 137, 356, 487, 272, 36, 8, 285, 570, 38, 36, 252, 477, 144, 38, -342, 299, 336, 260, 157, 833, 157, 289, 274, 352, 139, 357, 147, 573, 885, 427, 147, 756, 754, 464, 431, 294, 259, 138, 837, 269, 436, 556, -155, 244, 520, 133, 784, 361, 295, 259, 8, 172, 437, 36, 42, 195, 144, 38, 133, 36, 762, 131, 36, 38, 802, 36, 38, 764, 8, 38, 39, 52, 331, 407, 335, 338, 811, 53, 164, 348, 155, 131, 807, 147, 142, 131, -467, 363, 270, 538, 353, 172, 295, 579, 196, 172, 165, 161, 143, 42, 42, 144, 305, 36, 278, 520, 808, 38, 171, 379, 143, 157, 750, 54, 828, 42, 460, 544, 145, 155, 162, 279, 166, 42, 42, 440, 270, 307, 539, 170, 145, 401, 172, 246, 347, 179, 542, 304, -467, 319, 766, 174, 704, 8, 414, 36, 272, 285, 36, 38, 419, 8, 38, 427, 181, 205, 205, 28, 29, 30, 285, 486, 146, 584, 847, 688, 36, 183, 42, 147, 38, 148, 8, 157, 535, 8, 131, 142, 131, 767, 353, 42, 796, 874, 483, 269, 884, 6, 689, 148, 42, 580, 839, 42, 144, 581, 281, 143, 484, 221, 239, 186, 144, 8, 42, 417, 142, 256, 191, 142, 877, 8, 469, 282, 712, 558, 187, 145, 133, 566, 143, 603, 418, 144, 144, 708, 144, 188, 133, 514, 709, 473, 157, 147, 490, 8, 194, 356, 172, 353, 145, 36, 590, 494, 198, 38, 251, 199, 192, 36, 200, 366, 197, 38, 561, 315, 316, 28, 29, 30, 208, 278, 517, 283, 148, 535, 28, 29, 30, 305, 36, 326, 270, 36, 38, 209, 42, 38, 279, 342, 211, 346, 351, 792, 146, 172, 669, 146, 262, 244, 777, 147, 574, 148, 147, 575, 148, 278, 518, 131, 294, 36, 6, 604, 823, 38, 36, 824, 287, 36, 38, -467, -467, 38, 279, 358, 8, 129, 124, 572, 130, 6, 130, 793, 270, 125, 650, 335, 895, 42, 95, 896, 96, 36, 678, -467, 201, 38, 172, 897, 291, 97, 278, 657, 890, 596, 420, 216, 98, 423, 100, 157, 644, 292, 147, 101, 148, 898, 899, 279, 42, 433, 157, 379, 849, 742, 743, 850, 274, 715, 155, 303, 104, 106, 108, 109, 42, 318, 111, 42, 36, 36, 112, 113, 38, 38, 114, 115, 445, 446, 116, 670, 417, 659, 352, 310, 117, 205, 126, 670, 550, 147, 172, 205, 723, 129, 124, 311, 130, 418, 128, 417, 741, 125, 462, 463, 644, 322, 95, 888, 96, 321, 889, 670, 325, 672, 674, 675, 418, 97, 670, 298, 479, 672, 129, 124, 98, 130, 100, 495, 327, 332, 125, 101, 752, 333, 239, 95, 246, 96, 360, 702, 697, 757, 130, 469, 6, 672, 97, 698, 104, 106, 108, 109, 672, 98, 111, 100, 758, 369, 112, 113, 101, 728, 114, 115, 901, 376, 116, 775, 377, 140, 650, 561, 117, 526, 126, 380, 42, 104, 106, 108, 109, 399, 788, 111, 61, 365, 128, 112, 113, 644, 405, 114, 115, 406, 411, 116, 432, 8, 42, 670, 734, 117, 786, 126, 147, 565, 553, 571, 172, 410, 428, 810, 274, 419, 205, 128, 434, 31, 32, 438, 222, 585, 483, 441, 346, 442, 365, 448, 599, 600, 443, 142, 601, 672, 34, 35, 484, 133, 73, 74, 75, 710, 684, 77, 444, 555, 449, 250, 144, 451, 28, 29, 30, 685, 450, 711, 129, 124, 212, 130, 31, 32, 455, 596, 125, 456, 457, 780, 42, 95, 157, 96, 644, 670, 458, 461, 8, 34, 35, 669, 97, 465, 136, 1, 2, 3, 466, 98, 825, 100, 644, 156, 244, 467, 101, 36, 864, 160, 471, 38, 870, 393, 394, 395, 396, 397, 472, 672, 476, 407, 42, 104, 106, 108, 109, 475, 42, 111, 148, 478, 864, 112, 113, 516, 8, 114, 115, 190, 193, 116, 683, 670, 687, 519, 853, 117, 157, 126, 529, 531, 644, 797, 798, 799, 547, 173, 42, 133, 548, 128, 564, 734, 834, 353, 714, 734, 567, 568, 269, 219, 395, 396, 397, 576, 577, 672, 202, 583, 586, 593, 597, 210, 284, 598, 36, 144, 646, 670, 38, 661, 8, 670, 157, 665, 666, 668, 673, 42, 691, 692, 42, 261, 693, 865, 734, 273, 670, 276, 707, 670, 694, 727, 716, 718, 286, 8, 42, 722, 719, 644, 720, 672, 670, 670, 356, 672, 724, 865, 8, -170, 721, 738, 36, 730, 745, 739, 38, 747, 219, 42, 672, 309, 42, 672, 744, 284, 407, 746, 317, 305, 760, 755, 751, 205, 753, 270, 672, 672, 759, 239, 778, 770, 305, 297, 156, 774, 297, 297, 42, 42, 768, 8, 349, 297, 354, 273, 776, 359, 297, 136, 219, 367, 783, 781, 8, 553, 787, 172, 36, 297, 795, 796, 38, 804, 789, 806, 675, 816, 818, 812, 297, 341, 429, 156, 813, 790, 350, 297, 827, 297, 426, 270, 805, 36, 430, 402, 404, 38, 305, 409, 61, 554, 819, 829, 555, 843, 36, 216, 415, 416, 38, 842, 844, 8, 147, 846, 148, 848, 851, 791, 216, 852, 273, 571, 854, 856, 273, 147, 858, 148, 859, 543, 860, 830, 871, 8, 835, 266, 268, 872, 8, 875, 878, 578, 354, 883, 891, 305, 8, 36, 809, 892, 845, 38, 73, 74, 75, 893, 452, 77, 900, 556, 36, 216, 902, 426, 38, 430, 695, 215, 147, 782, 148, 696, 305, 855, 216, 868, 857, 8, 8, 588, 356, 147, 703, 148, 91, 700, 701, 882, 537, 404, 404, 496, 159, 474, 765, 273, 654, 273, 653, 866, 773, 480, 879, 880, 840, 841, 873, 134, 881, 36, 686, 305, 364, 38, 0, 0, 0, 0, 0, 522, 0, 0, 368, 216, 370, 371, 372, 373, 374, 375, 147, 36, 148, 534, 536, 38, 36, 8, 515, 0, 38, 0, 0, 0, 36, 216, 0, 404, 38, 0, 216, 523, 147, 0, 148, 412, 0, 147, 533, 148, 0, 0, 0, 0, 0, 273, 273, 270, 0, 0, 422, 269, 0, 425, 0, 36, 36, 0, 522, 38, 38, 534, 219, 0, 0, 0, 219, 0, 144, 216, 216, 8, 0, 0, 0, 0, 147, 147, 148, 148, 0, 0, 0, 0, 540, 0, 297, 545, 404, 219, 273, 0, 0, 273, 552, 559, 562, 0, 28, 29, 30, 0, 0, 143, 0, 790, 0, 0, 0, 0, 660, 0, 156, 297, 0, 36, 0, 0, 663, 38, 0, 0, 591, 145, 0, 0, 0, 481, 0, 533, 0, 656, 0, 0, 0, 0, 0, 0, 270, 0, 0, 0, 273, 391, 392, 393, 394, 395, 396, 397, 273, 0, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 36, 0, 381, 382, 38, 0, 0, 0, 660, 0, 0, 0, 219, 521, 216, 0, 0, 0, 0, 0, 528, 147, 0, 148, 391, 392, 393, 394, 395, 396, 397, 0, 0, 0, 0, 0, 0, 0, 0, 8, 273, 0, 0, 0, 0, 559, 0, 219, 0, 0, 0, 0, 681, 0, 559, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 256, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31, 32, 0, 0, 0, 144, 729, 0, 647, 506, 513, 0, 0, 0, 0, 0, 33, 34, 35, 9, 10, 11, 12, 13, 14, 15, 16, 0, 18, 0, 20, 0, 0, 23, 24, 25, 26, 219, 0, 0, 0, 0, 0, 0, 0, 0, 219, 0, 0, 0, 0, 0, 36, 0, 0, 37, 38, 0, 0, 0, 0, 297, 297, 0, 0, 0, 257, 559, 0, 749, 0, 297, 219, 147, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 219, 0, 0, 219, 794, 0, 0, 0, 0, 801, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 256, 219, 0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31, 32, 0, 0, 219, 144, 0, 0, 0, 381, 382, 383, 384, 0, 822, 0, 33, 34, 35, 0, 0, 0, 0, 559, 0, 0, 480, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 736, 373, 0, 737, 0, 0, 0, 740, 0, 0, 0, 0, 0, 0, 36, 0, 0, 37, 38, 381, 382, 383, 384, 0, 0, 0, 0, 0, 400, 0, 0, 0, 0, 0, 0, 147, 219, 0, 0, 867, 219, 391, 392, 393, 394, 395, 396, 397, 605, 822, -467, 57, 0, 0, 58, 59, 60, 0, 0, 772, 219, 0, 0, 0, 0, 61, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, 0, 0, 0, 606, 63, 0, 803, -467, 0, -467, -467, -467, -467, -467, 0, 0, 0, 0, 0, 0, 65, 66, 67, 68, 607, 70, 71, 72, -467, -467, -467, 608, 609, 610, 0, 73, 611, 75, 0, 76, 77, 78, 0, 0, 0, 82, 0, 84, 85, 86, 87, 88, 89, 0, 0, 0, 0, 0, 0, 836, 0, 0, 90, 0, -467, 0, 491, 91, -467, -467, 0, 0, 8, 0, 0, 172, 0, 0, 0, 223, 224, 225, 226, 227, 228, 229, 230, 612, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 231, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31, 32, 0, 232, 381, 382, 383, 384, 385, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 0, 386, 387, 388, 389, 492, 391, 392, 393, 394, 395, 396, 493, 295, 0, 0, 172, 381, 382, 383, 384, 224, 225, 226, 227, 228, 229, 230, 0, 0, 0, 0, 36, 0, 0, 37, 38, 389, 390, 391, 392, 393, 394, 395, 396, 397, 233, 0, 0, 234, 235, 0, 0, 236, 237, 238, 8, 861, 0, 172, 0, 0, 0, 223, 224, 225, 226, 227, 228, 229, 230, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 231, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 232, 0, 0, 265, 0, 0, 381, 382, 383, 384, 385, 0, 0, 33, 34, 35, 0, 0, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 0, 0, 36, 172, 0, 0, 38, 0, 224, 225, 226, 227, 228, 229, 230, 0, 233, 0, 0, 234, 235, 0, 0, 236, 237, 238, 8, 0, 0, 172, 0, 0, 0, 223, 224, 225, 226, 227, 228, 229, 230, 413, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 231, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 232, 0, 0, 421, 0, 381, 382, 383, 384, 385, 0, 0, 0, 33, 34, 35, 0, 381, 382, 383, 384, 0, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 0, 0, 0, 36, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 0, 0, 234, 235, 0, 0, 236, 237, 238, 8, 0, 0, 172, 0, 0, 0, 223, 224, 225, 226, 227, 228, 229, 230, 530, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 231, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 232, 0, 0, 424, 0, 381, 382, 383, 384, 385, 0, 0, 0, 33, 34, 35, 381, 382, 383, 384, 0, 0, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 0, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 0, 0, 0, 0, 36, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 0, 0, 234, 235, 0, 0, 236, 237, 238, 8, 0, 0, 172, 0, 0, 0, 223, 224, 225, 226, 227, 228, 229, 230, 532, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 231, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 232, 0, 0, 527, 0, 381, 382, 383, 384, 385, 0, 0, 0, 33, 34, 35, 381, 382, 383, 384, 0, 0, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 0, 0, 0, 390, 391, 392, 393, 394, 395, 396, 397, 0, 0, 0, 0, 36, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 0, 0, 234, 235, 0, 0, 236, 237, 238, 8, 0, 0, 172, 0, 0, 0, 223, 224, 225, 226, 227, 228, 229, 230, 658, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 231, 648, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 232, 0, 0, 0, 0, 381, 382, 383, 384, 385, 0, 0, 0, 33, 34, 35, 0, 0, 0, 0, 0, 0, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 0, 0, 234, 235, 0, 0, 236, 237, 238, 8, 0, 0, 172, 0, 0, 0, 223, 224, 225, 226, 227, 228, 229, 230, 662, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 231, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 232, 0, 0, 0, 0, 381, 382, 383, 384, 385, 0, 0, 0, 33, 34, 35, 0, 0, 0, 0, 0, 0, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 0, 0, 234, 235, 0, 0, 236, 237, 238, 8, 0, 0, 172, 0, 0, 0, 223, 224, 225, 226, 227, 228, 229, 230, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 231, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 232, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31, 32, 36, 0, 0, 0, 38, 0, 0, 0, 0, 0, 8, 0, 0, 0, 33, 34, 35, 234, 235, 0, 0, 649, 237, 238, 0, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 36, 0, 655, 37, 38, 0, 31, 32, 0, 0, 0, 0, 0, 0, 352, 0, 0, 0, 0, 0, 0, 147, 33, 34, 35, 381, 382, 383, 384, 385, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 0, 0, 0, 0, 36, 0, 0, 0, 38, -2, 56, 0, -467, 57, 0, 0, 58, 59, 60, 0, 0, 0, 0, 0, 0, 147, 0, 61, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, 0, 0, 0, 62, 63, 0, 0, 0, 0, -467, -467, -467, -467, -467, 0, 0, 64, 0, 0, 0, 65, 66, 67, 68, 69, 70, 71, 72, -467, -467, -467, 0, 0, 0, 0, 73, 74, 75, 0, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 56, 0, -467, 57, 0, 0, 58, 59, 60, 90, 0, -467, 0, 0, 91, -467, 0, 61, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, 0, 0, 0, 62, 63, 0, 0, 569, 0, -467, -467, -467, -467, -467, 0, 0, 64, 0, 0, 0, 65, 66, 67, 68, 69, 70, 71, 72, -467, -467, -467, 0, 0, 0, 0, 73, 74, 75, 0, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 56, 0, -467, 57, 0, 0, 58, 59, 60, 90, 0, -467, 0, 0, 91, -467, 0, 61, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, 0, 0, 0, 62, 63, 0, 0, 664, 0, -467, -467, -467, -467, -467, 0, 0, 64, 0, 0, 0, 65, 66, 67, 68, 69, 70, 71, 72, -467, -467, -467, 0, 0, 0, 0, 73, 74, 75, 0, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 56, 0, -467, 57, 0, 0, 58, 59, 60, 90, 0, -467, 0, 0, 91, -467, 0, 61, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, 0, 0, 0, 62, 63, 0, 0, 680, 0, -467, -467, -467, -467, -467, 0, 0, 64, 0, 0, 0, 65, 66, 67, 68, 69, 70, 71, 72, -467, -467, -467, 0, 0, 0, 0, 73, 74, 75, 0, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 56, 0, -467, 57, 0, 0, 58, 59, 60, 90, 0, -467, 0, 0, 91, -467, 0, 61, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, -467, 0, 0, 0, 62, 63, 0, 0, 0, 0, -467, -467, -467, -467, -467, 0, 0, 64, 0, 769, 0, 65, 66, 67, 68, 69, 70, 71, 72, -467, -467, -467, 0, 0, 0, 0, 73, 74, 75, 0, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 7, 0, 8, 0, 0, 0, 0, 0, 0, 90, 0, -467, 0, 0, 91, -467, 0, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31, 32, 51, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31, 32, 36, 0, 0, 37, 38, 0, 0, 0, 0, 0, 177, 0, 178, 0, 33, 34, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 36, 0, 0, 37, 38, 28, 29, 30, 31, 32, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 36, 8, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 220, 34, 35, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 36, 8, 0, 0, 38, 726, 0, 0, 0, 313, 0, 0, 0, 0, 33, 34, 35, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31, 32, 0, 36, 8, 0, 0, 38, 726, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31, 32, 36, 8, 0, 37, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 203, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 36, 8, 0, 37, 38, 0, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 36, 8, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 34, 35, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 0, 36, 682, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 30, 31, 32, 36, 8, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 32, 0, 36, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 38 }; static const yytype_int16 yycheck[] = { 0, 85, 5, 5, 40, 5, 320, 41, 8, 43, 5, 549, 212, 110, 437, 5, 304, 5, 446, 564, 131, 21, 6, 446, 257, 146, 5, 260, 563, 38, 197, 327, 38, 5, 155, 5, 90, 6, 39, 3, 5, 3, 42, 69, 3, 558, 1, 2, 215, 761, 42, 763, 3, 566, 91, 142, 40, 5, 5, 5, 5, 38, 137, 5, 64, 6, 775, 5, 5, 69, 70, 5, 5, 782, 37, 5, 102, 590, 4, 788, 6, 5, 179, 5, 597, 54, 161, 162, 3, 0, 91, 3, 129, 102, 3, 5, 634, 3, 3, 54, 3, 138, 102, 151, 40, 153, 140, 43, 205, 115, 51, 6, 171, 147, 40, 79, 175, 43, 205, 352, 353, 435, 181, 39, 221, 102, 671, 186, 37, 6, 253, 131, 45, 126, 37, 71, 257, 101, 3, 260, 454, 105, 101, 105, 40, 54, 105, 43, 43, 208, 142, 151, 115, 153, 105, 147, 115, 40, 217, 122, 456, 870, 283, 122, 40, 678, 43, 290, 168, 256, 90, 43, 37, 39, 100, 91, 131, 410, 178, 717, 3, 3, 269, 3, 6, 51, 101, 142, 4, 54, 105, 191, 101, 105, 90, 101, 105, 735, 101, 105, 105, 3, 105, 1, 2, 205, 115, 207, 208, 754, 1, 40, 212, 205, 90, 750, 122, 37, 90, 39, 220, 124, 4, 215, 6, 3, 3, 43, 6, 40, 103, 51, 187, 188, 54, 37, 101, 37, 471, 752, 105, 37, 242, 51, 244, 673, 37, 785, 203, 333, 673, 71, 244, 126, 54, 54, 211, 212, 306, 124, 38, 43, 106, 71, 256, 6, 377, 467, 65, 436, 51, 91, 51, 4, 37, 589, 3, 269, 101, 400, 401, 101, 105, 275, 3, 105, 407, 37, 85, 86, 46, 47, 48, 414, 40, 115, 463, 810, 103, 101, 37, 256, 122, 105, 124, 3, 306, 428, 3, 90, 37, 90, 43, 305, 269, 39, 854, 365, 37, 43, 320, 126, 124, 278, 101, 71, 281, 54, 105, 37, 51, 365, 129, 131, 37, 54, 3, 292, 37, 37, 37, 3, 37, 856, 3, 345, 54, 860, 445, 37, 71, 351, 449, 51, 75, 54, 54, 54, 39, 54, 37, 361, 399, 44, 356, 365, 122, 367, 3, 37, 37, 6, 364, 71, 101, 472, 368, 37, 105, 45, 40, 43, 101, 43, 43, 37, 105, 446, 187, 188, 46, 47, 48, 37, 37, 38, 115, 124, 519, 46, 47, 48, 37, 101, 203, 124, 101, 105, 37, 364, 105, 54, 211, 37, 212, 3, 3, 115, 6, 75, 115, 43, 377, 711, 122, 40, 124, 122, 43, 124, 37, 38, 90, 433, 101, 435, 484, 40, 105, 101, 43, 102, 101, 105, 102, 103, 105, 54, 115, 3, 453, 453, 455, 453, 454, 455, 43, 124, 453, 493, 460, 40, 417, 453, 43, 453, 101, 564, 126, 4, 105, 6, 51, 38, 453, 37, 38, 878, 478, 278, 115, 453, 281, 453, 484, 485, 39, 122, 453, 124, 891, 892, 54, 448, 292, 495, 496, 40, 665, 666, 43, 493, 599, 495, 40, 453, 453, 453, 453, 464, 40, 453, 467, 101, 101, 453, 453, 105, 105, 453, 453, 38, 39, 453, 558, 37, 38, 115, 3, 453, 327, 453, 566, 4, 122, 6, 333, 612, 541, 541, 3, 541, 54, 453, 37, 38, 541, 38, 39, 549, 3, 541, 40, 541, 43, 43, 590, 3, 558, 38, 39, 54, 541, 597, 6, 364, 566, 570, 570, 541, 570, 541, 369, 43, 40, 570, 541, 674, 39, 377, 570, 692, 570, 102, 587, 587, 683, 587, 588, 589, 590, 570, 587, 541, 541, 541, 541, 597, 570, 541, 570, 685, 37, 541, 541, 570, 643, 541, 541, 897, 91, 541, 709, 39, 650, 649, 675, 541, 417, 541, 37, 576, 570, 570, 570, 570, 91, 724, 570, 18, 727, 541, 570, 570, 634, 38, 570, 570, 38, 54, 570, 40, 3, 598, 678, 645, 570, 722, 570, 122, 448, 4, 41, 6, 102, 102, 753, 649, 650, 456, 570, 38, 49, 50, 38, 702, 464, 715, 38, 467, 43, 768, 39, 39, 40, 38, 37, 43, 678, 66, 67, 715, 682, 72, 73, 74, 37, 40, 77, 51, 43, 38, 692, 54, 40, 46, 47, 48, 51, 38, 51, 704, 704, 90, 704, 49, 50, 38, 708, 704, 38, 38, 712, 668, 704, 715, 704, 717, 752, 38, 38, 3, 66, 67, 75, 704, 38, 33, 107, 108, 109, 91, 704, 781, 704, 735, 42, 692, 39, 704, 101, 838, 48, 102, 105, 842, 118, 119, 120, 121, 122, 38, 752, 102, 115, 710, 704, 704, 704, 704, 40, 716, 704, 124, 43, 862, 704, 704, 102, 3, 704, 704, 78, 79, 704, 572, 810, 576, 102, 827, 704, 781, 704, 38, 38, 785, 68, 69, 70, 40, 63, 746, 792, 40, 704, 38, 796, 789, 790, 598, 800, 43, 40, 37, 110, 120, 121, 122, 37, 44, 810, 84, 40, 40, 3, 38, 89, 155, 37, 101, 54, 43, 856, 105, 38, 3, 860, 827, 39, 39, 37, 51, 787, 126, 90, 790, 142, 38, 838, 839, 146, 875, 148, 51, 878, 44, 643, 37, 43, 155, 3, 806, 124, 71, 854, 71, 856, 891, 892, 37, 860, 44, 862, 3, 44, 71, 38, 101, 73, 668, 38, 105, 75, 179, 829, 875, 182, 832, 878, 44, 218, 115, 37, 189, 37, 3, 40, 40, 685, 38, 124, 891, 892, 38, 692, 71, 40, 37, 171, 205, 40, 174, 175, 858, 859, 702, 3, 213, 181, 215, 216, 710, 218, 186, 220, 221, 222, 716, 38, 3, 4, 37, 6, 101, 197, 40, 39, 105, 38, 726, 37, 39, 91, 38, 40, 208, 209, 115, 244, 40, 37, 214, 215, 38, 217, 283, 124, 746, 101, 287, 256, 257, 105, 37, 260, 18, 40, 40, 37, 43, 40, 101, 115, 269, 270, 105, 44, 38, 3, 122, 40, 124, 40, 39, 71, 115, 37, 283, 41, 44, 38, 287, 122, 37, 124, 37, 437, 38, 787, 38, 3, 790, 144, 145, 40, 3, 38, 38, 460, 305, 40, 38, 37, 3, 101, 40, 38, 806, 105, 72, 73, 74, 40, 319, 77, 40, 100, 101, 115, 40, 358, 105, 360, 587, 37, 122, 715, 124, 587, 37, 829, 115, 40, 832, 3, 3, 467, 37, 122, 588, 124, 104, 587, 587, 862, 433, 352, 353, 377, 46, 356, 692, 358, 496, 360, 495, 839, 708, 364, 858, 859, 796, 800, 851, 21, 860, 101, 573, 37, 37, 105, -1, -1, -1, -1, -1, 414, -1, -1, 231, 115, 233, 234, 235, 236, 237, 238, 122, 101, 124, 428, 429, 105, 101, 3, 401, -1, 105, -1, -1, -1, 101, 115, -1, 410, 105, -1, 115, 414, 122, -1, 124, 264, -1, 122, 115, 124, -1, -1, -1, -1, -1, 428, 429, 124, -1, -1, 279, 37, -1, 282, -1, 101, 101, -1, 473, 105, 105, 476, 445, -1, -1, -1, 449, -1, 54, 115, 115, 3, -1, -1, -1, -1, 122, 122, 124, 124, -1, -1, -1, -1, 434, -1, 436, 437, 471, 472, 473, -1, -1, 476, 444, 445, 446, -1, 46, 47, 48, -1, -1, 51, -1, 37, -1, -1, -1, -1, 525, -1, 495, 463, -1, 101, -1, -1, 533, 105, -1, -1, 472, 71, -1, -1, -1, 75, -1, 115, -1, 514, -1, -1, -1, -1, -1, -1, 124, -1, -1, -1, 525, 116, 117, 118, 119, 120, 121, 122, 533, -1, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 101, -1, 94, 95, 105, -1, -1, -1, 592, -1, -1, -1, 564, 411, 115, -1, -1, -1, -1, -1, 418, 122, -1, 124, 116, 117, 118, 119, 120, 121, 122, -1, -1, -1, -1, -1, -1, -1, -1, 3, 592, -1, -1, -1, -1, 564, -1, 599, -1, -1, -1, -1, 571, -1, 573, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, 45, 46, 47, 48, 49, 50, -1, -1, -1, 54, 643, -1, 491, 492, 493, -1, -1, -1, -1, -1, 65, 66, 67, 19, 20, 21, 22, 23, 24, 25, 26, -1, 28, -1, 30, -1, -1, 33, 34, 35, 36, 674, -1, -1, -1, -1, -1, -1, -1, -1, 683, -1, -1, -1, -1, -1, 101, -1, -1, 104, 105, -1, -1, -1, -1, 665, 666, -1, -1, -1, 115, 671, -1, 673, -1, 675, 709, 122, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, -1, -1, -1, 724, -1, -1, 727, 728, -1, -1, -1, -1, 733, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 753, -1, -1, -1, -1, -1, -1, 45, 46, 47, 48, 49, 50, -1, -1, 768, 54, -1, -1, -1, 94, 95, 96, 97, -1, 778, -1, 65, 66, 67, -1, -1, -1, -1, 754, -1, -1, 790, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 648, 649, -1, 651, -1, -1, -1, 655, -1, -1, -1, -1, -1, -1, 101, -1, -1, 104, 105, 94, 95, 96, 97, -1, -1, -1, -1, -1, 115, -1, -1, -1, -1, -1, -1, 122, 838, -1, -1, 841, 842, 116, 117, 118, 119, 120, 121, 122, 1, 851, 3, 4, -1, -1, 7, 8, 9, -1, -1, 707, 862, -1, -1, -1, -1, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, 40, 41, -1, 738, 44, -1, 46, 47, 48, 49, 50, -1, -1, -1, -1, -1, -1, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, -1, 72, 73, 74, -1, 76, 77, 78, -1, -1, -1, 82, -1, 84, 85, 86, 87, 88, 89, -1, -1, -1, -1, -1, -1, 791, -1, -1, 99, -1, 101, -1, 38, 104, 105, 106, -1, -1, 3, -1, -1, 6, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 124, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, 45, 46, 47, 48, 49, 50, -1, 52, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, -1, -1, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 3, -1, -1, 6, 94, 95, 96, 97, 11, 12, 13, 14, 15, 16, 17, -1, -1, -1, -1, 101, -1, -1, 104, 105, 114, 115, 116, 117, 118, 119, 120, 121, 122, 115, -1, -1, 118, 119, -1, -1, 122, 123, 124, 3, 40, -1, 6, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 52, -1, -1, 55, -1, -1, 94, 95, 96, 97, 98, -1, -1, 65, 66, 67, -1, -1, 94, 95, 96, 97, 98, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, -1, -1, 101, 6, -1, -1, 105, -1, 11, 12, 13, 14, 15, 16, 17, -1, 115, -1, -1, 118, 119, -1, -1, 122, 123, 124, 3, -1, -1, 6, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 55, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 52, -1, -1, 55, -1, 94, 95, 96, 97, 98, -1, -1, -1, 65, 66, 67, -1, 94, 95, 96, 97, -1, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, -1, -1, -1, 101, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, 115, -1, -1, 118, 119, -1, -1, 122, 123, 124, 3, -1, -1, 6, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 55, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 52, -1, -1, 55, -1, 94, 95, 96, 97, 98, -1, -1, -1, 65, 66, 67, 94, 95, 96, 97, -1, -1, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, -1, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, -1, -1, -1, -1, 101, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, 115, -1, -1, 118, 119, -1, -1, 122, 123, 124, 3, -1, -1, 6, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 55, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 52, -1, -1, 55, -1, 94, 95, 96, 97, 98, -1, -1, -1, 65, 66, 67, 94, 95, 96, 97, -1, -1, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, -1, -1, -1, 115, 116, 117, 118, 119, 120, 121, 122, -1, -1, -1, -1, 101, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, 115, -1, -1, 118, 119, -1, -1, 122, 123, 124, 3, -1, -1, 6, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 55, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 52, -1, -1, -1, -1, 94, 95, 96, 97, 98, -1, -1, -1, 65, 66, 67, -1, -1, -1, -1, -1, -1, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 101, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, 115, -1, -1, 118, 119, -1, -1, 122, 123, 124, 3, -1, -1, 6, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 55, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 52, -1, -1, -1, -1, 94, 95, 96, 97, 98, -1, -1, -1, 65, 66, 67, -1, -1, -1, -1, -1, -1, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 101, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, 115, -1, -1, 118, 119, -1, -1, 122, 123, 124, 3, -1, -1, 6, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 52, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, 45, 46, 47, 48, 49, 50, 101, -1, -1, -1, 105, -1, -1, -1, -1, -1, 3, -1, -1, -1, 65, 66, 67, 118, 119, -1, -1, 122, 123, 124, -1, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, 101, -1, 71, 104, 105, -1, 49, 50, -1, -1, -1, -1, -1, -1, 115, -1, -1, -1, -1, -1, -1, 122, 65, 66, 67, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, -1, -1, -1, -1, 101, -1, -1, -1, 105, 0, 1, -1, 3, 4, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, 122, -1, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, 40, 41, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, -1, 53, -1, -1, -1, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, -1, -1, -1, -1, 72, 73, 74, -1, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 1, -1, 3, 4, -1, -1, 7, 8, 9, 99, -1, 101, -1, -1, 104, 105, -1, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, 40, 41, -1, -1, 44, -1, 46, 47, 48, 49, 50, -1, -1, 53, -1, -1, -1, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, -1, -1, -1, -1, 72, 73, 74, -1, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 1, -1, 3, 4, -1, -1, 7, 8, 9, 99, -1, 101, -1, -1, 104, 105, -1, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, 40, 41, -1, -1, 44, -1, 46, 47, 48, 49, 50, -1, -1, 53, -1, -1, -1, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, -1, -1, -1, -1, 72, 73, 74, -1, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 1, -1, 3, 4, -1, -1, 7, 8, 9, 99, -1, 101, -1, -1, 104, 105, -1, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, 40, 41, -1, -1, 44, -1, 46, 47, 48, 49, 50, -1, -1, 53, -1, -1, -1, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, -1, -1, -1, -1, 72, 73, 74, -1, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 1, -1, 3, 4, -1, -1, 7, 8, 9, 99, -1, 101, -1, -1, 104, 105, -1, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, 40, 41, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, -1, 53, -1, 55, -1, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, -1, -1, -1, -1, 72, 73, 74, -1, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 1, -1, 3, -1, -1, -1, -1, -1, -1, 99, -1, 101, -1, -1, 104, 105, -1, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, 45, 46, 47, 48, 49, 50, 1, -1, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, 45, 46, 47, 48, 49, 50, 101, -1, -1, 104, 105, -1, -1, -1, -1, -1, 1, -1, 3, -1, 65, 66, 67, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, 101, -1, -1, 104, 105, 46, 47, 48, 49, 50, -1, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 101, 3, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, 101, 3, -1, -1, 105, 106, -1, -1, -1, 11, -1, -1, -1, -1, 65, 66, 67, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, 45, 46, 47, 48, 49, 50, -1, 101, 3, -1, -1, 105, 106, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, 45, 46, 47, 48, 49, 50, 101, 3, -1, 104, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 101, 3, -1, 104, 105, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, 101, 3, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, -1, 101, 3, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, -1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, 46, 47, 48, 49, 50, 101, 3, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 49, 50, -1, 101, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 101, -1, -1, -1, 105 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint16 yystos[] = { 0, 107, 108, 109, 128, 129, 274, 1, 3, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 45, 46, 47, 48, 49, 50, 65, 66, 67, 101, 104, 105, 215, 229, 230, 232, 233, 234, 235, 236, 253, 254, 264, 266, 1, 215, 1, 37, 0, 1, 4, 7, 8, 9, 18, 40, 41, 53, 57, 58, 59, 60, 61, 62, 63, 64, 72, 73, 74, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 99, 104, 130, 131, 132, 134, 135, 136, 137, 138, 141, 142, 144, 145, 146, 147, 148, 149, 150, 153, 154, 155, 158, 160, 165, 166, 167, 168, 170, 173, 174, 175, 176, 177, 181, 182, 189, 190, 200, 211, 274, 90, 261, 274, 261, 45, 264, 126, 90, 40, 233, 229, 37, 51, 54, 71, 115, 122, 124, 220, 221, 223, 225, 226, 227, 228, 264, 274, 229, 235, 264, 103, 126, 265, 40, 40, 212, 213, 215, 274, 106, 37, 6, 269, 37, 271, 274, 1, 3, 231, 232, 37, 271, 37, 152, 274, 37, 37, 37, 79, 264, 3, 43, 264, 37, 4, 43, 37, 37, 40, 43, 4, 269, 37, 164, 231, 162, 164, 37, 37, 269, 37, 90, 254, 271, 37, 115, 223, 228, 264, 65, 231, 254, 10, 11, 12, 13, 14, 15, 16, 17, 37, 52, 115, 118, 119, 122, 123, 124, 215, 216, 217, 219, 231, 232, 243, 244, 245, 246, 269, 274, 45, 105, 266, 254, 229, 37, 115, 212, 226, 228, 264, 43, 237, 238, 55, 243, 244, 243, 37, 124, 224, 227, 264, 228, 229, 264, 220, 37, 54, 220, 37, 54, 115, 224, 227, 264, 102, 266, 105, 266, 38, 39, 214, 274, 3, 262, 269, 6, 43, 262, 272, 262, 40, 51, 37, 223, 38, 262, 264, 3, 3, 262, 11, 159, 212, 212, 264, 40, 51, 192, 43, 3, 161, 272, 3, 212, 43, 222, 223, 226, 274, 40, 39, 163, 274, 262, 263, 274, 139, 140, 269, 212, 185, 186, 187, 215, 253, 274, 264, 269, 3, 115, 228, 264, 272, 37, 262, 115, 264, 102, 3, 239, 274, 37, 223, 43, 264, 243, 37, 243, 243, 243, 243, 243, 243, 91, 39, 218, 274, 37, 94, 95, 96, 97, 98, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 265, 91, 115, 228, 264, 225, 264, 38, 38, 115, 225, 264, 102, 54, 243, 55, 228, 264, 264, 37, 54, 228, 212, 55, 243, 212, 55, 243, 224, 227, 102, 115, 224, 265, 40, 215, 38, 169, 39, 51, 38, 237, 220, 38, 43, 38, 51, 38, 39, 157, 39, 38, 38, 40, 264, 129, 191, 38, 38, 38, 38, 162, 164, 38, 38, 39, 43, 38, 91, 39, 188, 274, 54, 102, 38, 228, 264, 40, 102, 40, 43, 212, 264, 75, 172, 220, 229, 179, 40, 71, 247, 248, 274, 38, 115, 122, 228, 231, 219, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 254, 264, 102, 38, 38, 102, 225, 243, 224, 264, 38, 102, 212, 55, 243, 38, 55, 38, 55, 115, 224, 227, 224, 214, 4, 43, 269, 129, 272, 139, 245, 269, 273, 40, 40, 133, 4, 151, 269, 4, 40, 43, 100, 156, 223, 269, 270, 262, 269, 273, 38, 215, 223, 43, 40, 44, 129, 41, 211, 162, 40, 43, 37, 44, 163, 3, 101, 105, 267, 40, 272, 215, 40, 183, 187, 143, 223, 269, 102, 3, 240, 241, 274, 38, 37, 39, 40, 43, 171, 75, 220, 1, 40, 61, 68, 69, 70, 73, 124, 134, 135, 136, 137, 141, 142, 146, 148, 150, 153, 155, 158, 160, 165, 166, 167, 168, 181, 182, 189, 193, 196, 197, 198, 199, 200, 201, 202, 207, 210, 211, 274, 249, 43, 243, 38, 122, 229, 38, 115, 221, 218, 71, 264, 38, 55, 38, 224, 38, 55, 224, 44, 39, 39, 193, 37, 75, 229, 256, 274, 51, 38, 39, 157, 156, 223, 256, 44, 269, 3, 231, 40, 51, 270, 212, 103, 126, 268, 126, 90, 38, 44, 170, 177, 181, 182, 184, 197, 199, 211, 188, 129, 256, 40, 51, 39, 44, 37, 51, 256, 257, 212, 223, 37, 195, 43, 71, 71, 71, 124, 266, 44, 193, 106, 231, 254, 264, 73, 250, 251, 255, 274, 178, 243, 243, 38, 38, 243, 38, 272, 272, 44, 212, 37, 75, 156, 269, 273, 40, 223, 38, 256, 40, 40, 223, 164, 38, 3, 3, 105, 3, 105, 216, 4, 43, 231, 55, 40, 242, 243, 241, 40, 223, 212, 237, 71, 258, 274, 38, 172, 212, 193, 194, 266, 37, 223, 231, 37, 71, 3, 43, 264, 40, 39, 68, 69, 70, 252, 264, 193, 243, 38, 212, 37, 157, 256, 40, 223, 156, 40, 40, 268, 268, 91, 171, 38, 40, 259, 260, 264, 40, 43, 220, 171, 38, 193, 37, 212, 171, 37, 115, 228, 212, 243, 43, 204, 71, 251, 255, 44, 40, 38, 212, 40, 256, 40, 40, 43, 39, 37, 220, 44, 212, 38, 212, 37, 37, 38, 40, 203, 206, 223, 274, 250, 264, 40, 180, 223, 38, 40, 260, 193, 38, 208, 256, 38, 212, 212, 257, 206, 40, 43, 171, 209, 256, 40, 43, 209, 38, 38, 40, 205, 40, 43, 51, 209, 209, 40, 237, 40 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (YYLEX_PARAM) #else # define YYLEX yylex () #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *bottom, yytype_int16 *top) #else static void yy_stack_print (bottom, top) yytype_int16 *bottom; yytype_int16 *top; #endif { YYFPRINTF (stderr, "Stack now"); for (; bottom <= top; ++bottom) YYFPRINTF (stderr, " %d", *bottom); YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, int yyrule) #else static void yy_reduce_print (yyvsp, yyrule) YYSTYPE *yyvsp; int yyrule; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { fprintf (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) ); fprintf (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, Rule); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) #else static void yydestruct (yymsg, yytype, yyvaluep) const char *yymsg; int yytype; YYSTYPE *yyvaluep; #endif { YYUSE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (void); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /* The look-ahead symbol. */ int yychar; /* The semantic value of the look-ahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { int yystate; int yyn; int yyresult; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* Look-ahead token as an internal (translated) token number. */ int yytoken = 0; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif /* Three stacks and their tools: `yyss': related to states, `yyvs': related to semantic values, `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss = yyssa; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) YYSIZE_T yystacksize = YYINITDEPTH; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss); YYSTACK_RELOCATE (yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a look-ahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to look-ahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a look-ahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } if (yyn == YYFINAL) YYACCEPT; /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the look-ahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 1502 "parser.y" { if (!classes) classes = NewHash(); Setattr((yyvsp[(1) - (1)].node),"classes",classes); Setattr((yyvsp[(1) - (1)].node),"name",ModuleName); if ((!module_node) && ModuleName) { module_node = new_node("module"); Setattr(module_node,"name",ModuleName); } Setattr((yyvsp[(1) - (1)].node),"module",module_node); check_extensions(); top = (yyvsp[(1) - (1)].node); } break; case 3: #line 1515 "parser.y" { top = Copy(Getattr((yyvsp[(2) - (3)].p),"type")); Delete((yyvsp[(2) - (3)].p)); } break; case 4: #line 1519 "parser.y" { top = 0; } break; case 5: #line 1522 "parser.y" { top = (yyvsp[(2) - (3)].p); } break; case 6: #line 1525 "parser.y" { top = 0; } break; case 7: #line 1528 "parser.y" { top = (yyvsp[(3) - (5)].pl); } break; case 8: #line 1531 "parser.y" { top = 0; } break; case 9: #line 1536 "parser.y" { /* add declaration to end of linked list (the declaration isn't always a single declaration, sometimes it is a linked list itself) */ appendChild((yyvsp[(1) - (2)].node),(yyvsp[(2) - (2)].node)); (yyval.node) = (yyvsp[(1) - (2)].node); } break; case 10: #line 1541 "parser.y" { (yyval.node) = new_node("top"); } break; case 11: #line 1546 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 12: #line 1547 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 13: #line 1548 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 14: #line 1549 "parser.y" { (yyval.node) = 0; } break; case 15: #line 1550 "parser.y" { (yyval.node) = 0; Swig_error(cparse_file, cparse_line,"Syntax error in input(1).\n"); exit(1); } break; case 16: #line 1556 "parser.y" { if ((yyval.node)) { add_symbols((yyval.node)); } (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 17: #line 1572 "parser.y" { (yyval.node) = 0; skip_decl(); } break; case 18: #line 1582 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 19: #line 1583 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 20: #line 1584 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 21: #line 1585 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 22: #line 1586 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 23: #line 1587 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 24: #line 1588 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 25: #line 1589 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 26: #line 1590 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 27: #line 1591 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 28: #line 1592 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 29: #line 1593 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 30: #line 1594 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 31: #line 1595 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 32: #line 1596 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 33: #line 1597 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 34: #line 1598 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 35: #line 1599 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 36: #line 1600 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 37: #line 1601 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 38: #line 1602 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 39: #line 1609 "parser.y" { Node *cls; String *clsname; cplus_mode = CPLUS_PUBLIC; if (!classes) classes = NewHash(); if (!extendhash) extendhash = NewHash(); clsname = make_class_name((yyvsp[(3) - (4)].str)); cls = Getattr(classes,clsname); if (!cls) { /* No previous definition. Create a new scope */ Node *am = Getattr(extendhash,clsname); if (!am) { Swig_symbol_newscope(); Swig_symbol_setscopename((yyvsp[(3) - (4)].str)); prev_symtab = 0; } else { prev_symtab = Swig_symbol_setscope(Getattr(am,"symtab")); } current_class = 0; } else { /* Previous class definition. Use its symbol table */ prev_symtab = Swig_symbol_setscope(Getattr(cls,"symtab")); current_class = cls; extendmode = 1; } Classprefix = NewString((yyvsp[(3) - (4)].str)); Namespaceprefix= Swig_symbol_qualifiedscopename(0); Delete(clsname); } break; case 40: #line 1637 "parser.y" { String *clsname; extendmode = 0; (yyval.node) = new_node("extend"); Setattr((yyval.node),"symtab",Swig_symbol_popscope()); if (prev_symtab) { Swig_symbol_setscope(prev_symtab); } Namespaceprefix = Swig_symbol_qualifiedscopename(0); clsname = make_class_name((yyvsp[(3) - (7)].str)); Setattr((yyval.node),"name",clsname); /* Mark members as extend */ tag_nodes((yyvsp[(6) - (7)].node),"feature:extend",(char*) "1"); if (current_class) { /* We add the extension to the previously defined class */ appendChild((yyval.node),(yyvsp[(6) - (7)].node)); appendChild(current_class,(yyval.node)); } else { /* We store the extensions in the extensions hash */ Node *am = Getattr(extendhash,clsname); if (am) { /* Append the members to the previous extend methods */ appendChild(am,(yyvsp[(6) - (7)].node)); } else { appendChild((yyval.node),(yyvsp[(6) - (7)].node)); Setattr(extendhash,clsname,(yyval.node)); } } current_class = 0; Delete(Classprefix); Delete(clsname); Classprefix = 0; prev_symtab = 0; (yyval.node) = 0; } break; case 41: #line 1681 "parser.y" { (yyval.node) = new_node("apply"); Setattr((yyval.node),"pattern",Getattr((yyvsp[(2) - (5)].p),"pattern")); appendChild((yyval.node),(yyvsp[(4) - (5)].p)); } break; case 42: #line 1691 "parser.y" { (yyval.node) = new_node("clear"); appendChild((yyval.node),(yyvsp[(2) - (3)].p)); } break; case 43: #line 1702 "parser.y" { if (((yyvsp[(4) - (5)].dtype).type != T_ERROR) && ((yyvsp[(4) - (5)].dtype).type != T_SYMBOL)) { SwigType *type = NewSwigType((yyvsp[(4) - (5)].dtype).type); (yyval.node) = new_node("constant"); Setattr((yyval.node),"name",(yyvsp[(2) - (5)].id)); Setattr((yyval.node),"type",type); Setattr((yyval.node),"value",(yyvsp[(4) - (5)].dtype).val); if ((yyvsp[(4) - (5)].dtype).rawval) Setattr((yyval.node),"rawval", (yyvsp[(4) - (5)].dtype).rawval); Setattr((yyval.node),"storage","%constant"); SetFlag((yyval.node),"feature:immutable"); add_symbols((yyval.node)); Delete(type); } else { if ((yyvsp[(4) - (5)].dtype).type == T_ERROR) { Swig_warning(WARN_PARSE_UNSUPPORTED_VALUE,cparse_file,cparse_line,"Unsupported constant value (ignored)\n"); } (yyval.node) = 0; } } break; case 44: #line 1723 "parser.y" { if (((yyvsp[(4) - (5)].dtype).type != T_ERROR) && ((yyvsp[(4) - (5)].dtype).type != T_SYMBOL)) { SwigType_push((yyvsp[(2) - (5)].type),(yyvsp[(3) - (5)].decl).type); /* Sneaky callback function trick */ if (SwigType_isfunction((yyvsp[(2) - (5)].type))) { SwigType_add_pointer((yyvsp[(2) - (5)].type)); } (yyval.node) = new_node("constant"); Setattr((yyval.node),"name",(yyvsp[(3) - (5)].decl).id); Setattr((yyval.node),"type",(yyvsp[(2) - (5)].type)); Setattr((yyval.node),"value",(yyvsp[(4) - (5)].dtype).val); if ((yyvsp[(4) - (5)].dtype).rawval) Setattr((yyval.node),"rawval", (yyvsp[(4) - (5)].dtype).rawval); Setattr((yyval.node),"storage","%constant"); SetFlag((yyval.node),"feature:immutable"); add_symbols((yyval.node)); } else { if ((yyvsp[(4) - (5)].dtype).type == T_ERROR) { Swig_warning(WARN_PARSE_UNSUPPORTED_VALUE,cparse_file,cparse_line,"Unsupported constant value\n"); } (yyval.node) = 0; } } break; case 45: #line 1745 "parser.y" { Swig_warning(WARN_PARSE_BAD_VALUE,cparse_file,cparse_line,"Bad constant value (ignored).\n"); (yyval.node) = 0; } break; case 46: #line 1756 "parser.y" { char temp[64]; Replace((yyvsp[(2) - (2)].str),"$file",cparse_file, DOH_REPLACE_ANY); sprintf(temp,"%d", cparse_line); Replace((yyvsp[(2) - (2)].str),"$line",temp,DOH_REPLACE_ANY); Printf(stderr,"%s\n", (yyvsp[(2) - (2)].str)); Delete((yyvsp[(2) - (2)].str)); (yyval.node) = 0; } break; case 47: #line 1765 "parser.y" { char temp[64]; String *s = NewString((yyvsp[(2) - (2)].id)); Replace(s,"$file",cparse_file, DOH_REPLACE_ANY); sprintf(temp,"%d", cparse_line); Replace(s,"$line",temp,DOH_REPLACE_ANY); Printf(stderr,"%s\n", s); Delete(s); (yyval.node) = 0; } break; case 48: #line 1784 "parser.y" { skip_balanced('{','}'); (yyval.node) = 0; Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated. Use %%exception instead.\n"); } break; case 49: #line 1790 "parser.y" { skip_balanced('{','}'); (yyval.node) = 0; Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated. Use %%exception instead.\n"); } break; case 50: #line 1796 "parser.y" { (yyval.node) = 0; Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated. Use %%exception instead.\n"); } break; case 51: #line 1801 "parser.y" { (yyval.node) = 0; Swig_warning(WARN_DEPRECATED_EXCEPT,cparse_file, cparse_line, "%%except is deprecated. Use %%exception instead.\n"); } break; case 52: #line 1812 "parser.y" { (yyval.node) = NewHash(); Setattr((yyval.node),"value",(yyvsp[(1) - (4)].id)); Setattr((yyval.node),"type",Getattr((yyvsp[(3) - (4)].p),"type")); } break; case 53: #line 1819 "parser.y" { (yyval.node) = NewHash(); Setattr((yyval.node),"value",(yyvsp[(1) - (1)].id)); } break; case 54: #line 1823 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 55: #line 1828 "parser.y" { Hash *p = (yyvsp[(5) - (7)].node); (yyval.node) = new_node("fragment"); Setattr((yyval.node),"value",Getattr((yyvsp[(3) - (7)].node),"value")); Setattr((yyval.node),"type",Getattr((yyvsp[(3) - (7)].node),"type")); Setattr((yyval.node),"section",Getattr(p,"name")); Setattr((yyval.node),"kwargs",nextSibling(p)); Setattr((yyval.node),"code",(yyvsp[(7) - (7)].str)); } break; case 56: #line 1837 "parser.y" { Hash *p = (yyvsp[(5) - (7)].node); String *code; skip_balanced('{','}'); (yyval.node) = new_node("fragment"); Setattr((yyval.node),"value",Getattr((yyvsp[(3) - (7)].node),"value")); Setattr((yyval.node),"type",Getattr((yyvsp[(3) - (7)].node),"type")); Setattr((yyval.node),"section",Getattr(p,"name")); Setattr((yyval.node),"kwargs",nextSibling(p)); Delitem(scanner_ccode,0); Delitem(scanner_ccode,DOH_END); code = Copy(scanner_ccode); Setattr((yyval.node),"code",code); Delete(code); } break; case 57: #line 1852 "parser.y" { (yyval.node) = new_node("fragment"); Setattr((yyval.node),"value",Getattr((yyvsp[(3) - (5)].node),"value")); Setattr((yyval.node),"type",Getattr((yyvsp[(3) - (5)].node),"type")); Setattr((yyval.node),"emitonly","1"); } break; case 58: #line 1865 "parser.y" { (yyvsp[(1) - (4)].loc).filename = Copy(cparse_file); (yyvsp[(1) - (4)].loc).line = cparse_line; scanner_set_location(NewString((yyvsp[(3) - (4)].id)),1); } break; case 59: #line 1869 "parser.y" { String *mname = 0; (yyval.node) = (yyvsp[(6) - (7)].node); scanner_set_location((yyvsp[(1) - (7)].loc).filename,(yyvsp[(1) - (7)].loc).line); if (strcmp((yyvsp[(1) - (7)].loc).type,"include") == 0) set_nodeType((yyval.node),"include"); if (strcmp((yyvsp[(1) - (7)].loc).type,"import") == 0) { mname = (yyvsp[(2) - (7)].node) ? Getattr((yyvsp[(2) - (7)].node),"module") : 0; set_nodeType((yyval.node),"import"); if (import_mode) --import_mode; } Setattr((yyval.node),"name",(yyvsp[(3) - (7)].id)); /* Search for the module (if any) */ { Node *n = firstChild((yyval.node)); while (n) { if (Strcmp(nodeType(n),"module") == 0) { if (mname) { Setattr(n,"name", mname); mname = 0; } Setattr((yyval.node),"module",Getattr(n,"name")); break; } n = nextSibling(n); } if (mname) { /* There is no module node in the import node, ie, you imported a .h file directly. We are forced then to create a new import node with a module node. */ Node *nint = new_node("import"); Node *mnode = new_node("module"); Setattr(mnode,"name", mname); appendChild(nint,mnode); Delete(mnode); appendChild(nint,firstChild((yyval.node))); (yyval.node) = nint; Setattr((yyval.node),"module",mname); } } Setattr((yyval.node),"options",(yyvsp[(2) - (7)].node)); } break; case 60: #line 1915 "parser.y" { (yyval.loc).type = (char *) "include"; } break; case 61: #line 1916 "parser.y" { (yyval.loc).type = (char *) "import"; ++import_mode;} break; case 62: #line 1923 "parser.y" { String *cpps; if (Namespaceprefix) { Swig_error(cparse_file, cparse_start_line, "%%inline directive inside a namespace is disallowed.\n"); (yyval.node) = 0; } else { (yyval.node) = new_node("insert"); Setattr((yyval.node),"code",(yyvsp[(2) - (2)].str)); /* Need to run through the preprocessor */ Setline((yyvsp[(2) - (2)].str),cparse_start_line); Setfile((yyvsp[(2) - (2)].str),cparse_file); Seek((yyvsp[(2) - (2)].str),0,SEEK_SET); cpps = Preprocessor_parse((yyvsp[(2) - (2)].str)); start_inline(Char(cpps), cparse_start_line); Delete((yyvsp[(2) - (2)].str)); Delete(cpps); } } break; case 63: #line 1943 "parser.y" { String *cpps; int start_line = cparse_line; skip_balanced('{','}'); if (Namespaceprefix) { Swig_error(cparse_file, cparse_start_line, "%%inline directive inside a namespace is disallowed.\n"); (yyval.node) = 0; } else { String *code; (yyval.node) = new_node("insert"); Delitem(scanner_ccode,0); Delitem(scanner_ccode,DOH_END); code = Copy(scanner_ccode); Setattr((yyval.node),"code", code); Delete(code); cpps=Copy(scanner_ccode); start_inline(Char(cpps), start_line); Delete(cpps); } } break; case 64: #line 1974 "parser.y" { (yyval.node) = new_node("insert"); Setattr((yyval.node),"code",(yyvsp[(1) - (1)].str)); } break; case 65: #line 1978 "parser.y" { String *code = NewStringEmpty(); (yyval.node) = new_node("insert"); Setattr((yyval.node),"section",(yyvsp[(3) - (5)].id)); Setattr((yyval.node),"code",code); if (Swig_insert_file((yyvsp[(5) - (5)].id),code) < 0) { Swig_error(cparse_file, cparse_line, "Couldn't find '%s'.\n", (yyvsp[(5) - (5)].id)); (yyval.node) = 0; } } break; case 66: #line 1988 "parser.y" { (yyval.node) = new_node("insert"); Setattr((yyval.node),"section",(yyvsp[(3) - (5)].id)); Setattr((yyval.node),"code",(yyvsp[(5) - (5)].str)); } break; case 67: #line 1993 "parser.y" { String *code; skip_balanced('{','}'); (yyval.node) = new_node("insert"); Setattr((yyval.node),"section",(yyvsp[(3) - (5)].id)); Delitem(scanner_ccode,0); Delitem(scanner_ccode,DOH_END); code = Copy(scanner_ccode); Setattr((yyval.node),"code", code); Delete(code); } break; case 68: #line 2011 "parser.y" { (yyval.node) = new_node("module"); if ((yyvsp[(2) - (3)].node)) { Setattr((yyval.node),"options",(yyvsp[(2) - (3)].node)); if (Getattr((yyvsp[(2) - (3)].node),"directors")) { Wrapper_director_mode_set(1); } if (Getattr((yyvsp[(2) - (3)].node),"templatereduce")) { template_reduce = 1; } if (Getattr((yyvsp[(2) - (3)].node),"notemplatereduce")) { template_reduce = 0; } } if (!ModuleName) ModuleName = NewString((yyvsp[(3) - (3)].id)); if (!import_mode) { /* first module included, we apply global ModuleName, which can be modify by -module */ String *mname = Copy(ModuleName); Setattr((yyval.node),"name",mname); Delete(mname); } else { /* import mode, we just pass the idstring */ Setattr((yyval.node),"name",(yyvsp[(3) - (3)].id)); } if (!module_node) module_node = (yyval.node); } break; case 69: #line 2045 "parser.y" { Swig_warning(WARN_DEPRECATED_NAME,cparse_file,cparse_line, "%%name is deprecated. Use %%rename instead.\n"); Delete(yyrename); yyrename = NewString((yyvsp[(3) - (4)].id)); (yyval.node) = 0; } break; case 70: #line 2051 "parser.y" { Swig_warning(WARN_DEPRECATED_NAME,cparse_file,cparse_line, "%%name is deprecated. Use %%rename instead.\n"); (yyval.node) = 0; Swig_error(cparse_file,cparse_line,"Missing argument to %%name directive.\n"); } break; case 71: #line 2064 "parser.y" { (yyval.node) = new_node("native"); Setattr((yyval.node),"name",(yyvsp[(3) - (7)].id)); Setattr((yyval.node),"wrap:name",(yyvsp[(6) - (7)].id)); add_symbols((yyval.node)); } break; case 72: #line 2070 "parser.y" { if (!SwigType_isfunction((yyvsp[(7) - (8)].decl).type)) { Swig_error(cparse_file,cparse_line,"%%native declaration '%s' is not a function.\n", (yyvsp[(7) - (8)].decl).id); (yyval.node) = 0; } else { Delete(SwigType_pop_function((yyvsp[(7) - (8)].decl).type)); /* Need check for function here */ SwigType_push((yyvsp[(6) - (8)].type),(yyvsp[(7) - (8)].decl).type); (yyval.node) = new_node("native"); Setattr((yyval.node),"name",(yyvsp[(3) - (8)].id)); Setattr((yyval.node),"wrap:name",(yyvsp[(7) - (8)].decl).id); Setattr((yyval.node),"type",(yyvsp[(6) - (8)].type)); Setattr((yyval.node),"parms",(yyvsp[(7) - (8)].decl).parms); Setattr((yyval.node),"decl",(yyvsp[(7) - (8)].decl).type); } add_symbols((yyval.node)); } break; case 73: #line 2096 "parser.y" { (yyval.node) = new_node("pragma"); Setattr((yyval.node),"lang",(yyvsp[(2) - (5)].id)); Setattr((yyval.node),"name",(yyvsp[(3) - (5)].id)); Setattr((yyval.node),"value",(yyvsp[(5) - (5)].str)); } break; case 74: #line 2102 "parser.y" { (yyval.node) = new_node("pragma"); Setattr((yyval.node),"lang",(yyvsp[(2) - (3)].id)); Setattr((yyval.node),"name",(yyvsp[(3) - (3)].id)); } break; case 75: #line 2109 "parser.y" { (yyval.str) = NewString((yyvsp[(1) - (1)].id)); } break; case 76: #line 2110 "parser.y" { (yyval.str) = (yyvsp[(1) - (1)].str); } break; case 77: #line 2113 "parser.y" { (yyval.id) = (yyvsp[(2) - (3)].id); } break; case 78: #line 2114 "parser.y" { (yyval.id) = (char *) "swig"; } break; case 79: #line 2122 "parser.y" { SwigType *t = (yyvsp[(2) - (4)].decl).type; Hash *kws = NewHash(); String *fixname; fixname = feature_identifier_fix((yyvsp[(2) - (4)].decl).id); Setattr(kws,"name",(yyvsp[(3) - (4)].id)); if (!Len(t)) t = 0; /* Special declarator check */ if (t) { if (SwigType_isfunction(t)) { SwigType *decl = SwigType_pop_function(t); if (SwigType_ispointer(t)) { String *nname = NewStringf("*%s",fixname); if ((yyvsp[(1) - (4)].ivalue)) { Swig_name_rename_add(Namespaceprefix, nname,decl,kws,(yyvsp[(2) - (4)].decl).parms); } else { Swig_name_namewarn_add(Namespaceprefix,nname,decl,kws); } Delete(nname); } else { if ((yyvsp[(1) - (4)].ivalue)) { Swig_name_rename_add(Namespaceprefix,(fixname),decl,kws,(yyvsp[(2) - (4)].decl).parms); } else { Swig_name_namewarn_add(Namespaceprefix,(fixname),decl,kws); } } Delete(decl); } else if (SwigType_ispointer(t)) { String *nname = NewStringf("*%s",fixname); if ((yyvsp[(1) - (4)].ivalue)) { Swig_name_rename_add(Namespaceprefix,(nname),0,kws,(yyvsp[(2) - (4)].decl).parms); } else { Swig_name_namewarn_add(Namespaceprefix,(nname),0,kws); } Delete(nname); } } else { if ((yyvsp[(1) - (4)].ivalue)) { Swig_name_rename_add(Namespaceprefix,(fixname),0,kws,(yyvsp[(2) - (4)].decl).parms); } else { Swig_name_namewarn_add(Namespaceprefix,(fixname),0,kws); } } (yyval.node) = 0; scanner_clear_rename(); } break; case 80: #line 2168 "parser.y" { String *fixname; Hash *kws = (yyvsp[(3) - (7)].node); SwigType *t = (yyvsp[(5) - (7)].decl).type; fixname = feature_identifier_fix((yyvsp[(5) - (7)].decl).id); if (!Len(t)) t = 0; /* Special declarator check */ if (t) { if ((yyvsp[(6) - (7)].dtype).qualifier) SwigType_push(t,(yyvsp[(6) - (7)].dtype).qualifier); if (SwigType_isfunction(t)) { SwigType *decl = SwigType_pop_function(t); if (SwigType_ispointer(t)) { String *nname = NewStringf("*%s",fixname); if ((yyvsp[(1) - (7)].ivalue)) { Swig_name_rename_add(Namespaceprefix, nname,decl,kws,(yyvsp[(5) - (7)].decl).parms); } else { Swig_name_namewarn_add(Namespaceprefix,nname,decl,kws); } Delete(nname); } else { if ((yyvsp[(1) - (7)].ivalue)) { Swig_name_rename_add(Namespaceprefix,(fixname),decl,kws,(yyvsp[(5) - (7)].decl).parms); } else { Swig_name_namewarn_add(Namespaceprefix,(fixname),decl,kws); } } Delete(decl); } else if (SwigType_ispointer(t)) { String *nname = NewStringf("*%s",fixname); if ((yyvsp[(1) - (7)].ivalue)) { Swig_name_rename_add(Namespaceprefix,(nname),0,kws,(yyvsp[(5) - (7)].decl).parms); } else { Swig_name_namewarn_add(Namespaceprefix,(nname),0,kws); } Delete(nname); } } else { if ((yyvsp[(1) - (7)].ivalue)) { Swig_name_rename_add(Namespaceprefix,(fixname),0,kws,(yyvsp[(5) - (7)].decl).parms); } else { Swig_name_namewarn_add(Namespaceprefix,(fixname),0,kws); } } (yyval.node) = 0; scanner_clear_rename(); } break; case 81: #line 2214 "parser.y" { if ((yyvsp[(1) - (6)].ivalue)) { Swig_name_rename_add(Namespaceprefix,(yyvsp[(5) - (6)].id),0,(yyvsp[(3) - (6)].node),0); } else { Swig_name_namewarn_add(Namespaceprefix,(yyvsp[(5) - (6)].id),0,(yyvsp[(3) - (6)].node)); } (yyval.node) = 0; scanner_clear_rename(); } break; case 82: #line 2225 "parser.y" { (yyval.ivalue) = 1; } break; case 83: #line 2228 "parser.y" { (yyval.ivalue) = 0; } break; case 84: #line 2255 "parser.y" { String *val = (yyvsp[(7) - (7)].str) ? NewString((yyvsp[(7) - (7)].str)) : NewString("1"); new_feature((yyvsp[(3) - (7)].id), val, 0, (yyvsp[(5) - (7)].decl).id, (yyvsp[(5) - (7)].decl).type, (yyvsp[(5) - (7)].decl).parms, (yyvsp[(6) - (7)].dtype).qualifier); (yyval.node) = 0; } break; case 85: #line 2260 "parser.y" { String *val = Len((yyvsp[(5) - (9)].id)) ? NewString((yyvsp[(5) - (9)].id)) : 0; new_feature((yyvsp[(3) - (9)].id), val, 0, (yyvsp[(7) - (9)].decl).id, (yyvsp[(7) - (9)].decl).type, (yyvsp[(7) - (9)].decl).parms, (yyvsp[(8) - (9)].dtype).qualifier); (yyval.node) = 0; } break; case 86: #line 2265 "parser.y" { String *val = (yyvsp[(8) - (8)].str) ? NewString((yyvsp[(8) - (8)].str)) : NewString("1"); new_feature((yyvsp[(3) - (8)].id), val, (yyvsp[(4) - (8)].node), (yyvsp[(6) - (8)].decl).id, (yyvsp[(6) - (8)].decl).type, (yyvsp[(6) - (8)].decl).parms, (yyvsp[(7) - (8)].dtype).qualifier); (yyval.node) = 0; } break; case 87: #line 2270 "parser.y" { String *val = Len((yyvsp[(5) - (10)].id)) ? NewString((yyvsp[(5) - (10)].id)) : 0; new_feature((yyvsp[(3) - (10)].id), val, (yyvsp[(6) - (10)].node), (yyvsp[(8) - (10)].decl).id, (yyvsp[(8) - (10)].decl).type, (yyvsp[(8) - (10)].decl).parms, (yyvsp[(9) - (10)].dtype).qualifier); (yyval.node) = 0; } break; case 88: #line 2277 "parser.y" { String *val = (yyvsp[(5) - (5)].str) ? NewString((yyvsp[(5) - (5)].str)) : NewString("1"); new_feature((yyvsp[(3) - (5)].id), val, 0, 0, 0, 0, 0); (yyval.node) = 0; } break; case 89: #line 2282 "parser.y" { String *val = Len((yyvsp[(5) - (7)].id)) ? NewString((yyvsp[(5) - (7)].id)) : 0; new_feature((yyvsp[(3) - (7)].id), val, 0, 0, 0, 0, 0); (yyval.node) = 0; } break; case 90: #line 2287 "parser.y" { String *val = (yyvsp[(6) - (6)].str) ? NewString((yyvsp[(6) - (6)].str)) : NewString("1"); new_feature((yyvsp[(3) - (6)].id), val, (yyvsp[(4) - (6)].node), 0, 0, 0, 0); (yyval.node) = 0; } break; case 91: #line 2292 "parser.y" { String *val = Len((yyvsp[(5) - (8)].id)) ? NewString((yyvsp[(5) - (8)].id)) : 0; new_feature((yyvsp[(3) - (8)].id), val, (yyvsp[(6) - (8)].node), 0, 0, 0, 0); (yyval.node) = 0; } break; case 92: #line 2299 "parser.y" { (yyval.str) = (yyvsp[(1) - (1)].str); } break; case 93: #line 2300 "parser.y" { (yyval.str) = 0; } break; case 94: #line 2301 "parser.y" { (yyval.str) = (yyvsp[(3) - (5)].pl); } break; case 95: #line 2304 "parser.y" { (yyval.node) = NewHash(); Setattr((yyval.node),"name",(yyvsp[(2) - (4)].id)); Setattr((yyval.node),"value",(yyvsp[(4) - (4)].id)); } break; case 96: #line 2309 "parser.y" { (yyval.node) = NewHash(); Setattr((yyval.node),"name",(yyvsp[(2) - (5)].id)); Setattr((yyval.node),"value",(yyvsp[(4) - (5)].id)); set_nextSibling((yyval.node),(yyvsp[(5) - (5)].node)); } break; case 97: #line 2319 "parser.y" { Parm *val; String *name; SwigType *t; if (Namespaceprefix) name = NewStringf("%s::%s", Namespaceprefix, (yyvsp[(5) - (7)].decl).id); else name = NewString((yyvsp[(5) - (7)].decl).id); val = (yyvsp[(3) - (7)].pl); if ((yyvsp[(5) - (7)].decl).parms) { Setmeta(val,"parms",(yyvsp[(5) - (7)].decl).parms); } t = (yyvsp[(5) - (7)].decl).type; if (!Len(t)) t = 0; if (t) { if ((yyvsp[(6) - (7)].dtype).qualifier) SwigType_push(t,(yyvsp[(6) - (7)].dtype).qualifier); if (SwigType_isfunction(t)) { SwigType *decl = SwigType_pop_function(t); if (SwigType_ispointer(t)) { String *nname = NewStringf("*%s",name); Swig_feature_set(Swig_cparse_features(), nname, decl, "feature:varargs", val, 0); Delete(nname); } else { Swig_feature_set(Swig_cparse_features(), name, decl, "feature:varargs", val, 0); } Delete(decl); } else if (SwigType_ispointer(t)) { String *nname = NewStringf("*%s",name); Swig_feature_set(Swig_cparse_features(),nname,0,"feature:varargs",val, 0); Delete(nname); } } else { Swig_feature_set(Swig_cparse_features(),name,0,"feature:varargs",val, 0); } Delete(name); (yyval.node) = 0; } break; case 98: #line 2355 "parser.y" { (yyval.pl) = (yyvsp[(1) - (1)].pl); } break; case 99: #line 2356 "parser.y" { int i; int n; Parm *p; n = atoi(Char((yyvsp[(1) - (3)].dtype).val)); if (n <= 0) { Swig_error(cparse_file, cparse_line,"Argument count in %%varargs must be positive.\n"); (yyval.pl) = 0; } else { (yyval.pl) = Copy((yyvsp[(3) - (3)].p)); Setattr((yyval.pl),"name","VARARGS_SENTINEL"); for (i = 0; i < n; i++) { p = Copy((yyvsp[(3) - (3)].p)); set_nextSibling(p,(yyval.pl)); Delete((yyval.pl)); (yyval.pl) = p; } } } break; case 100: #line 2386 "parser.y" { (yyval.node) = 0; if ((yyvsp[(3) - (6)].tmap).op) { String *code = 0; (yyval.node) = new_node("typemap"); Setattr((yyval.node),"method",(yyvsp[(3) - (6)].tmap).op); if ((yyvsp[(3) - (6)].tmap).kwargs) { Parm *kw = (yyvsp[(3) - (6)].tmap).kwargs; /* check for 'noblock' option, which remove the block braces */ while (kw) { String *name = Getattr(kw,"name"); if (name && (Cmp(name,"noblock") == 0)) { char *cstr = Char((yyvsp[(6) - (6)].str)); size_t len = Len((yyvsp[(6) - (6)].str)); if (len && cstr[0] == '{') { --len; ++cstr; if (len && cstr[len - 1] == '}') { --len; } /* we now remove the extra spaces */ while (len && isspace((int)cstr[0])) { --len; ++cstr; } while (len && isspace((int)cstr[len - 1])) { --len; } code = NewStringWithSize(cstr, len); break; } } kw = nextSibling(kw); } Setattr((yyval.node),"kwargs", (yyvsp[(3) - (6)].tmap).kwargs); } code = code ? code : NewString((yyvsp[(6) - (6)].str)); Setattr((yyval.node),"code", code); Delete(code); appendChild((yyval.node),(yyvsp[(5) - (6)].p)); } } break; case 101: #line 2420 "parser.y" { (yyval.node) = 0; if ((yyvsp[(3) - (6)].tmap).op) { (yyval.node) = new_node("typemap"); Setattr((yyval.node),"method",(yyvsp[(3) - (6)].tmap).op); appendChild((yyval.node),(yyvsp[(5) - (6)].p)); } } break; case 102: #line 2428 "parser.y" { (yyval.node) = 0; if ((yyvsp[(3) - (8)].tmap).op) { (yyval.node) = new_node("typemapcopy"); Setattr((yyval.node),"method",(yyvsp[(3) - (8)].tmap).op); Setattr((yyval.node),"pattern", Getattr((yyvsp[(7) - (8)].p),"pattern")); appendChild((yyval.node),(yyvsp[(5) - (8)].p)); } } break; case 103: #line 2441 "parser.y" { Hash *p; String *name; p = nextSibling((yyvsp[(1) - (1)].node)); if (p && (!Getattr(p,"value"))) { /* this is the deprecated two argument typemap form */ Swig_warning(WARN_DEPRECATED_TYPEMAP_LANG,cparse_file, cparse_line, "Specifying the language name in %%typemap is deprecated - use #ifdef SWIG<LANG> instead.\n"); /* two argument typemap form */ name = Getattr((yyvsp[(1) - (1)].node),"name"); if (!name || (Strcmp(name,typemap_lang))) { (yyval.tmap).op = 0; (yyval.tmap).kwargs = 0; } else { (yyval.tmap).op = Getattr(p,"name"); (yyval.tmap).kwargs = nextSibling(p); } } else { /* one-argument typemap-form */ (yyval.tmap).op = Getattr((yyvsp[(1) - (1)].node),"name"); (yyval.tmap).kwargs = p; } } break; case 104: #line 2466 "parser.y" { (yyval.p) = (yyvsp[(1) - (2)].p); set_nextSibling((yyval.p),(yyvsp[(2) - (2)].p)); } break; case 105: #line 2472 "parser.y" { (yyval.p) = (yyvsp[(2) - (3)].p); set_nextSibling((yyval.p),(yyvsp[(3) - (3)].p)); } break; case 106: #line 2476 "parser.y" { (yyval.p) = 0;} break; case 107: #line 2479 "parser.y" { Parm *parm; SwigType_push((yyvsp[(1) - (2)].type),(yyvsp[(2) - (2)].decl).type); (yyval.p) = new_node("typemapitem"); parm = NewParm((yyvsp[(1) - (2)].type),(yyvsp[(2) - (2)].decl).id); Setattr((yyval.p),"pattern",parm); Setattr((yyval.p),"parms", (yyvsp[(2) - (2)].decl).parms); Delete(parm); /* $$ = NewParm($1,$2.id); Setattr($$,"parms",$2.parms); */ } break; case 108: #line 2490 "parser.y" { (yyval.p) = new_node("typemapitem"); Setattr((yyval.p),"pattern",(yyvsp[(2) - (3)].pl)); /* Setattr($$,"multitype",$2); */ } break; case 109: #line 2495 "parser.y" { (yyval.p) = new_node("typemapitem"); Setattr((yyval.p),"pattern", (yyvsp[(2) - (6)].pl)); /* Setattr($$,"multitype",$2); */ Setattr((yyval.p),"parms",(yyvsp[(5) - (6)].pl)); } break; case 110: #line 2507 "parser.y" { (yyval.node) = new_node("types"); Setattr((yyval.node),"parms",(yyvsp[(3) - (5)].pl)); } break; case 111: #line 2517 "parser.y" { Parm *p, *tp; Node *n; Node *tnode = 0; Symtab *tscope = 0; int specialized = 0; (yyval.node) = 0; tscope = Swig_symbol_current(); /* Get the current scope */ /* If the class name is qualified, we need to create or lookup namespace entries */ if (!inclass) { (yyvsp[(5) - (9)].str) = resolve_node_scope((yyvsp[(5) - (9)].str)); } /* We use the new namespace entry 'nscope' only to emit the template node. The template parameters are resolved in the current 'tscope'. This is closer to the C++ (typedef) behavior. */ n = Swig_cparse_template_locate((yyvsp[(5) - (9)].str),(yyvsp[(7) - (9)].p),tscope); /* Patch the argument types to respect namespaces */ p = (yyvsp[(7) - (9)].p); while (p) { SwigType *value = Getattr(p,"value"); if (!value) { SwigType *ty = Getattr(p,"type"); if (ty) { SwigType *rty = 0; int reduce = template_reduce; if (reduce || !SwigType_ispointer(ty)) { rty = Swig_symbol_typedef_reduce(ty,tscope); if (!reduce) reduce = SwigType_ispointer(rty); } ty = reduce ? Swig_symbol_type_qualify(rty,tscope) : Swig_symbol_type_qualify(ty,tscope); Setattr(p,"type",ty); Delete(ty); Delete(rty); } } else { value = Swig_symbol_type_qualify(value,tscope); Setattr(p,"value",value); Delete(value); } p = nextSibling(p); } /* Look for the template */ { Node *nn = n; Node *linklistend = 0; while (nn) { Node *templnode = 0; if (Strcmp(nodeType(nn),"template") == 0) { int nnisclass = (Strcmp(Getattr(nn,"templatetype"),"class") == 0); /* if not a templated class it is a templated function */ Parm *tparms = Getattr(nn,"templateparms"); if (!tparms) { specialized = 1; } if (nnisclass && !specialized && ((ParmList_len((yyvsp[(7) - (9)].p)) > ParmList_len(tparms)))) { Swig_error(cparse_file, cparse_line, "Too many template parameters. Maximum of %d.\n", ParmList_len(tparms)); } else if (nnisclass && !specialized && ((ParmList_len((yyvsp[(7) - (9)].p)) < ParmList_numrequired(tparms)))) { Swig_error(cparse_file, cparse_line, "Not enough template parameters specified. %d required.\n", ParmList_numrequired(tparms)); } else if (!nnisclass && ((ParmList_len((yyvsp[(7) - (9)].p)) != ParmList_len(tparms)))) { /* must be an overloaded templated method - ignore it as it is overloaded with a different number of template parameters */ nn = Getattr(nn,"sym:nextSibling"); /* repeat for overloaded templated functions */ continue; } else { String *tname = Copy((yyvsp[(5) - (9)].str)); int def_supplied = 0; /* Expand the template */ Node *templ = Swig_symbol_clookup((yyvsp[(5) - (9)].str),0); Parm *targs = templ ? Getattr(templ,"templateparms") : 0; ParmList *temparms; if (specialized) temparms = CopyParmList((yyvsp[(7) - (9)].p)); else temparms = CopyParmList(tparms); /* Create typedef's and arguments */ p = (yyvsp[(7) - (9)].p); tp = temparms; while (p) { String *value = Getattr(p,"value"); if (def_supplied) { Setattr(p,"default","1"); } if (value) { Setattr(tp,"value",value); } else { SwigType *ty = Getattr(p,"type"); if (ty) { Setattr(tp,"type",ty); } Delattr(tp,"value"); } /* fix default arg values */ if (targs) { Parm *pi = temparms; Parm *ti = targs; String *tv = Getattr(tp,"value"); if (!tv) tv = Getattr(tp,"type"); while(pi != tp) { String *name = Getattr(ti,"name"); String *value = Getattr(pi,"value"); if (!value) value = Getattr(pi,"type"); Replaceid(tv, name, value); pi = nextSibling(pi); ti = nextSibling(ti); } } p = nextSibling(p); tp = nextSibling(tp); if (!p && tp) { p = tp; def_supplied = 1; } } templnode = copy_node(nn); /* We need to set the node name based on name used to instantiate */ Setattr(templnode,"name",tname); Delete(tname); if (!specialized) { Delattr(templnode,"sym:typename"); } else { Setattr(templnode,"sym:typename","1"); } if ((yyvsp[(3) - (9)].id)) { /* Comment this out for 1.3.28. We need to re-enable it later but first we need to move %ignore from using %rename to use %feature(ignore). String *symname = Swig_name_make(templnode,0,$3,0,0); */ String *symname = (yyvsp[(3) - (9)].id); Swig_cparse_template_expand(templnode,symname,temparms,tscope); Setattr(templnode,"sym:name",symname); } else { static int cnt = 0; String *nname = NewStringf("__dummy_%d__", cnt++); Swig_cparse_template_expand(templnode,nname,temparms,tscope); Setattr(templnode,"sym:name",nname); Delete(nname); Setattr(templnode,"feature:onlychildren", "typemap,typemapitem,typemapcopy,typedef,types,fragment"); } Delattr(templnode,"templatetype"); Setattr(templnode,"template",nn); tnode = templnode; Setfile(templnode,cparse_file); Setline(templnode,cparse_line); Delete(temparms); add_symbols_copy(templnode); if (Strcmp(nodeType(templnode),"class") == 0) { /* Identify pure abstract methods */ Setattr(templnode,"abstract", pure_abstract(firstChild(templnode))); /* Set up inheritance in symbol table */ { Symtab *csyms; List *baselist = Getattr(templnode,"baselist"); csyms = Swig_symbol_current(); Swig_symbol_setscope(Getattr(templnode,"symtab")); if (baselist) { List *bases = make_inherit_list(Getattr(templnode,"name"),baselist); if (bases) { Iterator s; for (s = First(bases); s.item; s = Next(s)) { Symtab *st = Getattr(s.item,"symtab"); if (st) { Setfile(st,Getfile(s.item)); Setline(st,Getline(s.item)); Swig_symbol_inherit(st); } } Delete(bases); } } Swig_symbol_setscope(csyms); } /* Merge in addmethods for this class */ /* !!! This may be broken. We may have to add the addmethods at the beginning of the class */ if (extendhash) { String *stmp = 0; String *clsname; Node *am; if (Namespaceprefix) { clsname = stmp = NewStringf("%s::%s", Namespaceprefix, Getattr(templnode,"name")); } else { clsname = Getattr(templnode,"name"); } am = Getattr(extendhash,clsname); if (am) { Symtab *st = Swig_symbol_current(); Swig_symbol_setscope(Getattr(templnode,"symtab")); /* Printf(stdout,"%s: %s %x %x\n", Getattr(templnode,"name"), clsname, Swig_symbol_current(), Getattr(templnode,"symtab")); */ merge_extensions(templnode,am); Swig_symbol_setscope(st); append_previous_extension(templnode,am); Delattr(extendhash,clsname); } if (stmp) Delete(stmp); } /* Add to classes hash */ if (!classes) classes = NewHash(); { if (Namespaceprefix) { String *temp = NewStringf("%s::%s", Namespaceprefix, Getattr(templnode,"name")); Setattr(classes,temp,templnode); Delete(temp); } else { String *qs = Swig_symbol_qualifiedscopename(templnode); Setattr(classes, qs,templnode); Delete(qs); } } } } /* all the overloaded templated functions are added into a linked list */ if (nscope_inner) { /* non-global namespace */ if (templnode) { appendChild(nscope_inner,templnode); Delete(templnode); if (nscope) (yyval.node) = nscope; } } else { /* global namespace */ if (!linklistend) { (yyval.node) = templnode; } else { set_nextSibling(linklistend,templnode); Delete(templnode); } linklistend = templnode; } } nn = Getattr(nn,"sym:nextSibling"); /* repeat for overloaded templated functions. If a templated class there will never be a sibling. */ } } Swig_symbol_setscope(tscope); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); } break; case 112: #line 2784 "parser.y" { Swig_warning(0,cparse_file, cparse_line,"%s\n", (yyvsp[(2) - (2)].id)); (yyval.node) = 0; } break; case 113: #line 2794 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); if ((yyval.node)) { add_symbols((yyval.node)); default_arguments((yyval.node)); } } break; case 114: #line 2801 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 115: #line 2802 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 116: #line 2806 "parser.y" { if (Strcmp((yyvsp[(2) - (3)].id),"C") == 0) { cparse_externc = 1; } } break; case 117: #line 2810 "parser.y" { cparse_externc = 0; if (Strcmp((yyvsp[(2) - (6)].id),"C") == 0) { Node *n = firstChild((yyvsp[(5) - (6)].node)); (yyval.node) = new_node("extern"); Setattr((yyval.node),"name",(yyvsp[(2) - (6)].id)); appendChild((yyval.node),n); while (n) { SwigType *decl = Getattr(n,"decl"); if (SwigType_isfunction(decl)) { Setattr(n,"storage","externc"); } n = nextSibling(n); } } else { Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", (yyvsp[(2) - (6)].id)); (yyval.node) = new_node("extern"); Setattr((yyval.node),"name",(yyvsp[(2) - (6)].id)); appendChild((yyval.node),firstChild((yyvsp[(5) - (6)].node))); } } break; case 118: #line 2837 "parser.y" { (yyval.node) = new_node("cdecl"); if ((yyvsp[(4) - (5)].dtype).qualifier) SwigType_push((yyvsp[(3) - (5)].decl).type,(yyvsp[(4) - (5)].dtype).qualifier); Setattr((yyval.node),"type",(yyvsp[(2) - (5)].type)); Setattr((yyval.node),"storage",(yyvsp[(1) - (5)].id)); Setattr((yyval.node),"name",(yyvsp[(3) - (5)].decl).id); Setattr((yyval.node),"decl",(yyvsp[(3) - (5)].decl).type); Setattr((yyval.node),"parms",(yyvsp[(3) - (5)].decl).parms); Setattr((yyval.node),"value",(yyvsp[(4) - (5)].dtype).val); Setattr((yyval.node),"throws",(yyvsp[(4) - (5)].dtype).throws); Setattr((yyval.node),"throw",(yyvsp[(4) - (5)].dtype).throwf); if (!(yyvsp[(5) - (5)].node)) { if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr((yyval.node),"code",code); Delete(code); } } else { Node *n = (yyvsp[(5) - (5)].node); /* Inherit attributes */ while (n) { String *type = Copy((yyvsp[(2) - (5)].type)); Setattr(n,"type",type); Setattr(n,"storage",(yyvsp[(1) - (5)].id)); n = nextSibling(n); Delete(type); } } if ((yyvsp[(4) - (5)].dtype).bitfield) { Setattr((yyval.node),"bitfield", (yyvsp[(4) - (5)].dtype).bitfield); } /* Look for "::" declarations (ignored) */ if (Strstr((yyvsp[(3) - (5)].decl).id,"::")) { /* This is a special case. If the scope name of the declaration exactly matches that of the declaration, then we will allow it. Otherwise, delete. */ String *p = Swig_scopename_prefix((yyvsp[(3) - (5)].decl).id); if (p) { if ((Namespaceprefix && Strcmp(p,Namespaceprefix) == 0) || (inclass && Strcmp(p,Classprefix) == 0)) { String *lstr = Swig_scopename_last((yyvsp[(3) - (5)].decl).id); Setattr((yyval.node),"name",lstr); Delete(lstr); set_nextSibling((yyval.node),(yyvsp[(5) - (5)].node)); } else { Delete((yyval.node)); (yyval.node) = (yyvsp[(5) - (5)].node); } Delete(p); } else { Delete((yyval.node)); (yyval.node) = (yyvsp[(5) - (5)].node); } } else { set_nextSibling((yyval.node),(yyvsp[(5) - (5)].node)); } } break; case 119: #line 2898 "parser.y" { (yyval.node) = 0; Clear(scanner_ccode); } break; case 120: #line 2902 "parser.y" { (yyval.node) = new_node("cdecl"); if ((yyvsp[(3) - (4)].dtype).qualifier) SwigType_push((yyvsp[(2) - (4)].decl).type,(yyvsp[(3) - (4)].dtype).qualifier); Setattr((yyval.node),"name",(yyvsp[(2) - (4)].decl).id); Setattr((yyval.node),"decl",(yyvsp[(2) - (4)].decl).type); Setattr((yyval.node),"parms",(yyvsp[(2) - (4)].decl).parms); Setattr((yyval.node),"value",(yyvsp[(3) - (4)].dtype).val); Setattr((yyval.node),"throws",(yyvsp[(3) - (4)].dtype).throws); Setattr((yyval.node),"throw",(yyvsp[(3) - (4)].dtype).throwf); if ((yyvsp[(3) - (4)].dtype).bitfield) { Setattr((yyval.node),"bitfield", (yyvsp[(3) - (4)].dtype).bitfield); } if (!(yyvsp[(4) - (4)].node)) { if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr((yyval.node),"code",code); Delete(code); } } else { set_nextSibling((yyval.node),(yyvsp[(4) - (4)].node)); } } break; case 121: #line 2924 "parser.y" { skip_balanced('{','}'); (yyval.node) = 0; } break; case 122: #line 2930 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); (yyval.dtype).qualifier = 0; (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } break; case 123: #line 2936 "parser.y" { (yyval.dtype) = (yyvsp[(2) - (2)].dtype); (yyval.dtype).qualifier = (yyvsp[(1) - (2)].str); (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } break; case 124: #line 2942 "parser.y" { (yyval.dtype) = (yyvsp[(5) - (5)].dtype); (yyval.dtype).qualifier = 0; (yyval.dtype).throws = (yyvsp[(3) - (5)].pl); (yyval.dtype).throwf = NewString("1"); } break; case 125: #line 2948 "parser.y" { (yyval.dtype) = (yyvsp[(6) - (6)].dtype); (yyval.dtype).qualifier = (yyvsp[(1) - (6)].str); (yyval.dtype).throws = (yyvsp[(4) - (6)].pl); (yyval.dtype).throwf = NewString("1"); } break; case 126: #line 2961 "parser.y" { SwigType *ty = 0; (yyval.node) = new_node("enumforward"); ty = NewStringf("enum %s", (yyvsp[(3) - (4)].id)); Setattr((yyval.node),"name",(yyvsp[(3) - (4)].id)); Setattr((yyval.node),"type",ty); Setattr((yyval.node),"sym:weak", "1"); add_symbols((yyval.node)); } break; case 127: #line 2976 "parser.y" { SwigType *ty = 0; (yyval.node) = new_node("enum"); ty = NewStringf("enum %s", (yyvsp[(3) - (7)].id)); Setattr((yyval.node),"name",(yyvsp[(3) - (7)].id)); Setattr((yyval.node),"type",ty); appendChild((yyval.node),(yyvsp[(5) - (7)].node)); add_symbols((yyval.node)); /* Add to tag space */ add_symbols((yyvsp[(5) - (7)].node)); /* Add enum values to id space */ } break; case 128: #line 2986 "parser.y" { Node *n; SwigType *ty = 0; String *unnamed = 0; int unnamedinstance = 0; (yyval.node) = new_node("enum"); if ((yyvsp[(3) - (8)].id)) { Setattr((yyval.node),"name",(yyvsp[(3) - (8)].id)); ty = NewStringf("enum %s", (yyvsp[(3) - (8)].id)); } else if ((yyvsp[(7) - (8)].decl).id) { unnamed = make_unnamed(); ty = NewStringf("enum %s", unnamed); Setattr((yyval.node),"unnamed",unnamed); /* name is not set for unnamed enum instances, e.g. enum { foo } Instance; */ if ((yyvsp[(1) - (8)].id) && Cmp((yyvsp[(1) - (8)].id),"typedef") == 0) { Setattr((yyval.node),"name",(yyvsp[(7) - (8)].decl).id); } else { unnamedinstance = 1; } Setattr((yyval.node),"storage",(yyvsp[(1) - (8)].id)); } if ((yyvsp[(7) - (8)].decl).id && Cmp((yyvsp[(1) - (8)].id),"typedef") == 0) { Setattr((yyval.node),"tdname",(yyvsp[(7) - (8)].decl).id); Setattr((yyval.node),"allows_typedef","1"); } appendChild((yyval.node),(yyvsp[(5) - (8)].node)); n = new_node("cdecl"); Setattr(n,"type",ty); Setattr(n,"name",(yyvsp[(7) - (8)].decl).id); Setattr(n,"storage",(yyvsp[(1) - (8)].id)); Setattr(n,"decl",(yyvsp[(7) - (8)].decl).type); Setattr(n,"parms",(yyvsp[(7) - (8)].decl).parms); Setattr(n,"unnamed",unnamed); if (unnamedinstance) { SwigType *cty = NewString("enum "); Setattr((yyval.node),"type",cty); Setattr((yyval.node),"unnamedinstance","1"); Setattr(n,"unnamedinstance","1"); Delete(cty); } if ((yyvsp[(8) - (8)].node)) { Node *p = (yyvsp[(8) - (8)].node); set_nextSibling(n,p); while (p) { SwigType *cty = Copy(ty); Setattr(p,"type",cty); Setattr(p,"unnamed",unnamed); Setattr(p,"storage",(yyvsp[(1) - (8)].id)); Delete(cty); p = nextSibling(p); } } else { if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr(n,"code",code); Delete(code); } } /* Ensure that typedef enum ABC {foo} XYZ; uses XYZ for sym:name, like structs. * Note that class_rename/yyrename are bit of a mess so used this simple approach to change the name. */ if ((yyvsp[(7) - (8)].decl).id && (yyvsp[(3) - (8)].id) && Cmp((yyvsp[(1) - (8)].id),"typedef") == 0) { String *name = NewString((yyvsp[(7) - (8)].decl).id); Setattr((yyval.node), "parser:makename", name); Delete(name); } add_symbols((yyval.node)); /* Add enum to tag space */ set_nextSibling((yyval.node),n); Delete(n); add_symbols((yyvsp[(5) - (8)].node)); /* Add enum values to id space */ add_symbols(n); Delete(unnamed); } break; case 129: #line 3064 "parser.y" { /* This is a sick hack. If the ctor_end has parameters, and the parms parameter only has 1 parameter, this could be a declaration of the form: type (id)(parms) Otherwise it's an error. */ int err = 0; (yyval.node) = 0; if ((ParmList_len((yyvsp[(4) - (6)].pl)) == 1) && (!Swig_scopename_check((yyvsp[(2) - (6)].type)))) { SwigType *ty = Getattr((yyvsp[(4) - (6)].pl),"type"); String *name = Getattr((yyvsp[(4) - (6)].pl),"name"); err = 1; if (!name) { (yyval.node) = new_node("cdecl"); Setattr((yyval.node),"type",(yyvsp[(2) - (6)].type)); Setattr((yyval.node),"storage",(yyvsp[(1) - (6)].id)); Setattr((yyval.node),"name",ty); if ((yyvsp[(6) - (6)].decl).have_parms) { SwigType *decl = NewStringEmpty(); SwigType_add_function(decl,(yyvsp[(6) - (6)].decl).parms); Setattr((yyval.node),"decl",decl); Setattr((yyval.node),"parms",(yyvsp[(6) - (6)].decl).parms); if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr((yyval.node),"code",code); Delete(code); } } if ((yyvsp[(6) - (6)].decl).defarg) { Setattr((yyval.node),"value",(yyvsp[(6) - (6)].decl).defarg); } Setattr((yyval.node),"throws",(yyvsp[(6) - (6)].decl).throws); Setattr((yyval.node),"throw",(yyvsp[(6) - (6)].decl).throwf); err = 0; } } if (err) { Swig_error(cparse_file,cparse_line,"Syntax error in input(2).\n"); exit(1); } } break; case 130: #line 3115 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 131: #line 3116 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 132: #line 3117 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 133: #line 3118 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 134: #line 3119 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 135: #line 3120 "parser.y" { (yyval.node) = 0; } break; case 136: #line 3126 "parser.y" { List *bases = 0; Node *scope = 0; (yyval.node) = new_node("class"); Setline((yyval.node),cparse_start_line); Setattr((yyval.node),"kind",(yyvsp[(2) - (5)].id)); if ((yyvsp[(4) - (5)].bases)) { Setattr((yyval.node),"baselist", Getattr((yyvsp[(4) - (5)].bases),"public")); Setattr((yyval.node),"protectedbaselist", Getattr((yyvsp[(4) - (5)].bases),"protected")); Setattr((yyval.node),"privatebaselist", Getattr((yyvsp[(4) - (5)].bases),"private")); } Setattr((yyval.node),"allows_typedef","1"); /* preserve the current scope */ prev_symtab = Swig_symbol_current(); /* If the class name is qualified. We need to create or lookup namespace/scope entries */ scope = resolve_node_scope((yyvsp[(3) - (5)].str)); Setfile(scope,cparse_file); Setline(scope,cparse_line); (yyvsp[(3) - (5)].str) = scope; /* support for old nested classes "pseudo" support, such as: %rename(Ala__Ola) Ala::Ola; class Ala::Ola { public: Ola() {} }; this should disappear when a proper implementation is added. */ if (nscope_inner && Strcmp(nodeType(nscope_inner),"namespace") != 0) { if (Namespaceprefix) { String *name = NewStringf("%s::%s", Namespaceprefix, (yyvsp[(3) - (5)].str)); (yyvsp[(3) - (5)].str) = name; Namespaceprefix = 0; nscope_inner = 0; } } Setattr((yyval.node),"name",(yyvsp[(3) - (5)].str)); Delete(class_rename); class_rename = make_name((yyval.node),(yyvsp[(3) - (5)].str),0); Classprefix = NewString((yyvsp[(3) - (5)].str)); /* Deal with inheritance */ if ((yyvsp[(4) - (5)].bases)) { bases = make_inherit_list((yyvsp[(3) - (5)].str),Getattr((yyvsp[(4) - (5)].bases),"public")); } if (SwigType_istemplate((yyvsp[(3) - (5)].str))) { String *fbase, *tbase, *prefix; prefix = SwigType_templateprefix((yyvsp[(3) - (5)].str)); if (Namespaceprefix) { fbase = NewStringf("%s::%s", Namespaceprefix,(yyvsp[(3) - (5)].str)); tbase = NewStringf("%s::%s", Namespaceprefix, prefix); } else { fbase = Copy((yyvsp[(3) - (5)].str)); tbase = Copy(prefix); } Swig_name_inherit(tbase,fbase); Delete(fbase); Delete(tbase); Delete(prefix); } if (strcmp((yyvsp[(2) - (5)].id),"class") == 0) { cplus_mode = CPLUS_PRIVATE; } else { cplus_mode = CPLUS_PUBLIC; } Swig_symbol_newscope(); Swig_symbol_setscopename((yyvsp[(3) - (5)].str)); if (bases) { Iterator s; for (s = First(bases); s.item; s = Next(s)) { Symtab *st = Getattr(s.item,"symtab"); if (st) { Setfile(st,Getfile(s.item)); Setline(st,Getline(s.item)); Swig_symbol_inherit(st); } } Delete(bases); } Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); cparse_start_line = cparse_line; /* If there are active template parameters, we need to make sure they are placed in the class symbol table so we can catch shadows */ if (template_parameters) { Parm *tp = template_parameters; while(tp) { String *tpname = Copy(Getattr(tp,"name")); Node *tn = new_node("templateparm"); Setattr(tn,"name",tpname); Swig_symbol_cadd(tpname,tn); tp = nextSibling(tp); Delete(tpname); } } if (class_level >= max_class_levels) { if (!max_class_levels) { max_class_levels = 16; } else { max_class_levels *= 2; } class_decl = realloc(class_decl, sizeof(Node*) * max_class_levels); if (!class_decl) { Swig_error(cparse_file, cparse_line, "realloc() failed\n"); } } class_decl[class_level++] = (yyval.node); inclass = 1; } break; case 137: #line 3240 "parser.y" { Node *p; SwigType *ty; Symtab *cscope = prev_symtab; Node *am = 0; String *scpname = 0; (yyval.node) = class_decl[--class_level]; inclass = 0; /* Check for pure-abstract class */ Setattr((yyval.node),"abstract", pure_abstract((yyvsp[(7) - (9)].node))); /* This bit of code merges in a previously defined %extend directive (if any) */ if (extendhash) { String *clsname = Swig_symbol_qualifiedscopename(0); am = Getattr(extendhash,clsname); if (am) { merge_extensions((yyval.node),am); Delattr(extendhash,clsname); } Delete(clsname); } if (!classes) classes = NewHash(); scpname = Swig_symbol_qualifiedscopename(0); Setattr(classes,scpname,(yyval.node)); Delete(scpname); appendChild((yyval.node),(yyvsp[(7) - (9)].node)); if (am) append_previous_extension((yyval.node),am); p = (yyvsp[(9) - (9)].node); if (p) { set_nextSibling((yyval.node),p); } if (cparse_cplusplus && !cparse_externc) { ty = NewString((yyvsp[(3) - (9)].str)); } else { ty = NewStringf("%s %s", (yyvsp[(2) - (9)].id),(yyvsp[(3) - (9)].str)); } while (p) { Setattr(p,"storage",(yyvsp[(1) - (9)].id)); Setattr(p,"type",ty); p = nextSibling(p); } /* Dump nested classes */ { String *name = (yyvsp[(3) - (9)].str); if ((yyvsp[(9) - (9)].node)) { SwigType *decltype = Getattr((yyvsp[(9) - (9)].node),"decl"); if (Cmp((yyvsp[(1) - (9)].id),"typedef") == 0) { if (!decltype || !Len(decltype)) { String *cname; name = Getattr((yyvsp[(9) - (9)].node),"name"); cname = Copy(name); Setattr((yyval.node),"tdname",cname); Delete(cname); /* Use typedef name as class name */ if (class_rename && (Strcmp(class_rename,(yyvsp[(3) - (9)].str)) == 0)) { Delete(class_rename); class_rename = NewString(name); } if (!Getattr(classes,name)) { Setattr(classes,name,(yyval.node)); } Setattr((yyval.node),"decl",decltype); } } } appendChild((yyval.node),dump_nested(Char(name))); } if (cplus_mode != CPLUS_PUBLIC) { /* we 'open' the class at the end, to allow %template to add new members */ Node *pa = new_node("access"); Setattr(pa,"kind","public"); cplus_mode = CPLUS_PUBLIC; appendChild((yyval.node),pa); Delete(pa); } Setattr((yyval.node),"symtab",Swig_symbol_popscope()); Classprefix = 0; if (nscope_inner) { /* this is tricky */ /* we add the declaration in the original namespace */ appendChild(nscope_inner,(yyval.node)); Swig_symbol_setscope(Getattr(nscope_inner,"symtab")); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols((yyval.node)); if (nscope) (yyval.node) = nscope; /* but the variable definition in the current scope */ Swig_symbol_setscope(cscope); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols((yyvsp[(9) - (9)].node)); } else { Delete(yyrename); yyrename = Copy(class_rename); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols((yyval.node)); add_symbols((yyvsp[(9) - (9)].node)); } Swig_symbol_setscope(cscope); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); } break; case 138: #line 3358 "parser.y" { String *unnamed; unnamed = make_unnamed(); (yyval.node) = new_node("class"); Setline((yyval.node),cparse_start_line); Setattr((yyval.node),"kind",(yyvsp[(2) - (3)].id)); Setattr((yyval.node),"storage",(yyvsp[(1) - (3)].id)); Setattr((yyval.node),"unnamed",unnamed); Setattr((yyval.node),"allows_typedef","1"); Delete(class_rename); class_rename = make_name((yyval.node),0,0); if (strcmp((yyvsp[(2) - (3)].id),"class") == 0) { cplus_mode = CPLUS_PRIVATE; } else { cplus_mode = CPLUS_PUBLIC; } Swig_symbol_newscope(); cparse_start_line = cparse_line; if (class_level >= max_class_levels) { if (!max_class_levels) { max_class_levels = 16; } else { max_class_levels *= 2; } class_decl = realloc(class_decl, sizeof(Node*) * max_class_levels); if (!class_decl) { Swig_error(cparse_file, cparse_line, "realloc() failed\n"); } } class_decl[class_level++] = (yyval.node); inclass = 1; Classprefix = NewStringEmpty(); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); } break; case 139: #line 3392 "parser.y" { String *unnamed; Node *n; Classprefix = 0; (yyval.node) = class_decl[--class_level]; inclass = 0; unnamed = Getattr((yyval.node),"unnamed"); /* Check for pure-abstract class */ Setattr((yyval.node),"abstract", pure_abstract((yyvsp[(5) - (8)].node))); n = new_node("cdecl"); Setattr(n,"name",(yyvsp[(7) - (8)].decl).id); Setattr(n,"unnamed",unnamed); Setattr(n,"type",unnamed); Setattr(n,"decl",(yyvsp[(7) - (8)].decl).type); Setattr(n,"parms",(yyvsp[(7) - (8)].decl).parms); Setattr(n,"storage",(yyvsp[(1) - (8)].id)); if ((yyvsp[(8) - (8)].node)) { Node *p = (yyvsp[(8) - (8)].node); set_nextSibling(n,p); while (p) { String *type = Copy(unnamed); Setattr(p,"name",(yyvsp[(7) - (8)].decl).id); Setattr(p,"unnamed",unnamed); Setattr(p,"type",type); Delete(type); Setattr(p,"storage",(yyvsp[(1) - (8)].id)); p = nextSibling(p); } } set_nextSibling((yyval.node),n); Delete(n); { /* If a proper typedef name was given, we'll use it to set the scope name */ String *name = 0; if ((yyvsp[(1) - (8)].id) && (strcmp((yyvsp[(1) - (8)].id),"typedef") == 0)) { if (!Len((yyvsp[(7) - (8)].decl).type)) { String *scpname = 0; name = (yyvsp[(7) - (8)].decl).id; Setattr((yyval.node),"tdname",name); Setattr((yyval.node),"name",name); Swig_symbol_setscopename(name); /* If a proper name was given, we use that as the typedef, not unnamed */ Clear(unnamed); Append(unnamed, name); n = nextSibling(n); set_nextSibling((yyval.node),n); /* Check for previous extensions */ if (extendhash) { String *clsname = Swig_symbol_qualifiedscopename(0); Node *am = Getattr(extendhash,clsname); if (am) { /* Merge the extension into the symbol table */ merge_extensions((yyval.node),am); append_previous_extension((yyval.node),am); Delattr(extendhash,clsname); } Delete(clsname); } if (!classes) classes = NewHash(); scpname = Swig_symbol_qualifiedscopename(0); Setattr(classes,scpname,(yyval.node)); Delete(scpname); } else { Swig_symbol_setscopename((char*)"<unnamed>"); } } appendChild((yyval.node),(yyvsp[(5) - (8)].node)); appendChild((yyval.node),dump_nested(Char(name))); } /* Pop the scope */ Setattr((yyval.node),"symtab",Swig_symbol_popscope()); if (class_rename) { Delete(yyrename); yyrename = NewString(class_rename); } Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols((yyval.node)); add_symbols(n); Delete(unnamed); } break; case 140: #line 3480 "parser.y" { (yyval.node) = 0; } break; case 141: #line 3481 "parser.y" { (yyval.node) = new_node("cdecl"); Setattr((yyval.node),"name",(yyvsp[(1) - (2)].decl).id); Setattr((yyval.node),"decl",(yyvsp[(1) - (2)].decl).type); Setattr((yyval.node),"parms",(yyvsp[(1) - (2)].decl).parms); set_nextSibling((yyval.node),(yyvsp[(2) - (2)].node)); } break; case 142: #line 3493 "parser.y" { if ((yyvsp[(1) - (4)].id) && (Strcmp((yyvsp[(1) - (4)].id),"friend") == 0)) { /* Ignore */ (yyval.node) = 0; } else { (yyval.node) = new_node("classforward"); Setfile((yyval.node),cparse_file); Setline((yyval.node),cparse_line); Setattr((yyval.node),"kind",(yyvsp[(2) - (4)].id)); Setattr((yyval.node),"name",(yyvsp[(3) - (4)].str)); Setattr((yyval.node),"sym:weak", "1"); add_symbols((yyval.node)); } } break; case 143: #line 3513 "parser.y" { template_parameters = (yyvsp[(3) - (4)].tparms); } break; case 144: #line 3513 "parser.y" { String *tname = 0; int error = 0; /* check if we get a namespace node with a class declaration, and retrieve the class */ Symtab *cscope = Swig_symbol_current(); Symtab *sti = 0; Node *ntop = (yyvsp[(6) - (6)].node); Node *ni = ntop; SwigType *ntype = ni ? nodeType(ni) : 0; while (ni && Strcmp(ntype,"namespace") == 0) { sti = Getattr(ni,"symtab"); ni = firstChild(ni); ntype = nodeType(ni); } if (sti) { Swig_symbol_setscope(sti); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); (yyvsp[(6) - (6)].node) = ni; } template_parameters = 0; (yyval.node) = (yyvsp[(6) - (6)].node); if ((yyval.node)) tname = Getattr((yyval.node),"name"); /* Check if the class is a template specialization */ if (((yyval.node)) && (Strchr(tname,'<')) && (!is_operator(tname))) { /* If a specialization. Check if defined. */ Node *tempn = 0; { String *tbase = SwigType_templateprefix(tname); tempn = Swig_symbol_clookup_local(tbase,0); if (!tempn || (Strcmp(nodeType(tempn),"template") != 0)) { SWIG_WARN_NODE_BEGIN(tempn); Swig_warning(WARN_PARSE_TEMPLATE_SP_UNDEF, Getfile((yyval.node)),Getline((yyval.node)),"Specialization of non-template '%s'.\n", tbase); SWIG_WARN_NODE_END(tempn); tempn = 0; error = 1; } Delete(tbase); } Setattr((yyval.node),"specialization","1"); Setattr((yyval.node),"templatetype",nodeType((yyval.node))); set_nodeType((yyval.node),"template"); /* Template partial specialization */ if (tempn && ((yyvsp[(3) - (6)].tparms)) && ((yyvsp[(6) - (6)].node))) { List *tlist; String *targs = SwigType_templateargs(tname); tlist = SwigType_parmlist(targs); /* Printf(stdout,"targs = '%s' %s\n", targs, tlist); */ if (!Getattr((yyval.node),"sym:weak")) { Setattr((yyval.node),"sym:typename","1"); } if (Len(tlist) != ParmList_len(Getattr(tempn,"templateparms"))) { Swig_error(Getfile((yyval.node)),Getline((yyval.node)),"Inconsistent argument count in template partial specialization. %d %d\n", Len(tlist), ParmList_len(Getattr(tempn,"templateparms"))); } else { /* This code builds the argument list for the partial template specialization. This is a little hairy, but the idea is as follows: $3 contains a list of arguments supplied for the template. For example template<class T>. tlist is a list of the specialization arguments--which may be different. For example class<int,T>. tp is a copy of the arguments in the original template definition. The patching algorithm walks through the list of supplied arguments ($3), finds the position in the specialization arguments (tlist), and then patches the name in the argument list of the original template. */ { String *pn; Parm *p, *p1; int i, nargs; Parm *tp = CopyParmList(Getattr(tempn,"templateparms")); nargs = Len(tlist); p = (yyvsp[(3) - (6)].tparms); while (p) { for (i = 0; i < nargs; i++){ pn = Getattr(p,"name"); if (Strcmp(pn,SwigType_base(Getitem(tlist,i))) == 0) { int j; Parm *p1 = tp; for (j = 0; j < i; j++) { p1 = nextSibling(p1); } Setattr(p1,"name",pn); Setattr(p1,"partialarg","1"); } } p = nextSibling(p); } p1 = tp; i = 0; while (p1) { if (!Getattr(p1,"partialarg")) { Delattr(p1,"name"); Setattr(p1,"type", Getitem(tlist,i)); } i++; p1 = nextSibling(p1); } Setattr((yyval.node),"templateparms",tp); Delete(tp); } #if 0 /* Patch the parameter list */ if (tempn) { Parm *p,*p1; ParmList *tp = CopyParmList(Getattr(tempn,"templateparms")); p = (yyvsp[(3) - (6)].tparms); p1 = tp; while (p && p1) { String *pn = Getattr(p,"name"); Printf(stdout,"pn = '%s'\n", pn); if (pn) Setattr(p1,"name",pn); else Delattr(p1,"name"); pn = Getattr(p,"type"); if (pn) Setattr(p1,"type",pn); p = nextSibling(p); p1 = nextSibling(p1); } Setattr((yyval.node),"templateparms",tp); Delete(tp); } else { Setattr((yyval.node),"templateparms",(yyvsp[(3) - (6)].tparms)); } #endif Delattr((yyval.node),"specialization"); Setattr((yyval.node),"partialspecialization","1"); /* Create a specialized name for matching */ { Parm *p = (yyvsp[(3) - (6)].tparms); String *fname = NewString(Getattr((yyval.node),"name")); String *ffname = 0; char tmp[32]; int i, ilen; while (p) { String *n = Getattr(p,"name"); if (!n) { p = nextSibling(p); continue; } ilen = Len(tlist); for (i = 0; i < ilen; i++) { if (Strstr(Getitem(tlist,i),n)) { sprintf(tmp,"$%d",i+1); Replaceid(fname,n,tmp); } } p = nextSibling(p); } /* Patch argument names with typedef */ { Iterator tt; List *tparms = SwigType_parmlist(fname); ffname = SwigType_templateprefix(fname); Append(ffname,"<("); for (tt = First(tparms); tt.item; ) { SwigType *rtt = Swig_symbol_typedef_reduce(tt.item,0); SwigType *ttr = Swig_symbol_type_qualify(rtt,0); Append(ffname,ttr); tt = Next(tt); if (tt.item) Putc(',',ffname); Delete(rtt); Delete(ttr); } Delete(tparms); Append(ffname,")>"); } { String *partials = Getattr(tempn,"partials"); if (!partials) { partials = NewList(); Setattr(tempn,"partials",partials); Delete(partials); } /* Printf(stdout,"partial: fname = '%s', '%s'\n", fname, Swig_symbol_typedef_reduce(fname,0)); */ Append(partials,ffname); } Setattr((yyval.node),"partialargs",ffname); Swig_symbol_cadd(ffname,(yyval.node)); } } Delete(tlist); Delete(targs); } else { /* Need to resolve exact specialization name */ /* add default args from generic template */ String *ty = Swig_symbol_template_deftype(tname,0); String *fname = Swig_symbol_type_qualify(ty,0); Swig_symbol_cadd(fname,(yyval.node)); Delete(ty); Delete(fname); } } else if ((yyval.node)) { Setattr((yyval.node),"templatetype",nodeType((yyvsp[(6) - (6)].node))); set_nodeType((yyval.node),"template"); Setattr((yyval.node),"templateparms", (yyvsp[(3) - (6)].tparms)); if (!Getattr((yyval.node),"sym:weak")) { Setattr((yyval.node),"sym:typename","1"); } add_symbols((yyval.node)); default_arguments((yyval.node)); /* We also place a fully parameterized version in the symbol table */ { Parm *p; String *fname = NewStringf("%s<(", Getattr((yyval.node),"name")); p = (yyvsp[(3) - (6)].tparms); while (p) { String *n = Getattr(p,"name"); if (!n) n = Getattr(p,"type"); Append(fname,n); p = nextSibling(p); if (p) Putc(',',fname); } Append(fname,")>"); Swig_symbol_cadd(fname,(yyval.node)); } } (yyval.node) = ntop; Swig_symbol_setscope(cscope); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); if (error) (yyval.node) = 0; } break; case 145: #line 3748 "parser.y" { Swig_warning(WARN_PARSE_EXPLICIT_TEMPLATE, cparse_file, cparse_line, "Explicit template instantiation ignored.\n"); (yyval.node) = 0; } break; case 146: #line 3754 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 147: #line 3757 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 148: #line 3760 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 149: #line 3763 "parser.y" { (yyval.node) = 0; } break; case 150: #line 3766 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 151: #line 3769 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 152: #line 3774 "parser.y" { /* Rip out the parameter names */ Parm *p = (yyvsp[(1) - (1)].pl); (yyval.tparms) = (yyvsp[(1) - (1)].pl); while (p) { String *name = Getattr(p,"name"); if (!name) { /* Hmmm. Maybe it's a 'class T' parameter */ char *type = Char(Getattr(p,"type")); /* Template template parameter */ if (strncmp(type,"template<class> ",16) == 0) { type += 16; } if ((strncmp(type,"class ",6) == 0) || (strncmp(type,"typename ", 9) == 0)) { char *t = strchr(type,' '); Setattr(p,"name", t+1); } else { /* Swig_error(cparse_file, cparse_line, "Missing template parameter name\n"); $$.rparms = 0; $$.parms = 0; break; */ } } p = nextSibling(p); } } break; case 153: #line 3804 "parser.y" { set_nextSibling((yyvsp[(1) - (2)].p),(yyvsp[(2) - (2)].pl)); (yyval.pl) = (yyvsp[(1) - (2)].p); } break; case 154: #line 3808 "parser.y" { (yyval.pl) = 0; } break; case 155: #line 3811 "parser.y" { (yyval.p) = NewParm(NewString((yyvsp[(1) - (1)].id)), 0); } break; case 156: #line 3814 "parser.y" { (yyval.p) = (yyvsp[(1) - (1)].p); } break; case 157: #line 3819 "parser.y" { set_nextSibling((yyvsp[(2) - (3)].p),(yyvsp[(3) - (3)].pl)); (yyval.pl) = (yyvsp[(2) - (3)].p); } break; case 158: #line 3823 "parser.y" { (yyval.pl) = 0; } break; case 159: #line 3828 "parser.y" { String *uname = Swig_symbol_type_qualify((yyvsp[(2) - (3)].str),0); String *name = Swig_scopename_last((yyvsp[(2) - (3)].str)); (yyval.node) = new_node("using"); Setattr((yyval.node),"uname",uname); Setattr((yyval.node),"name", name); Delete(uname); Delete(name); add_symbols((yyval.node)); } break; case 160: #line 3838 "parser.y" { Node *n = Swig_symbol_clookup((yyvsp[(3) - (4)].str),0); if (!n) { Swig_error(cparse_file, cparse_line, "Nothing known about namespace '%s'\n", (yyvsp[(3) - (4)].str)); (yyval.node) = 0; } else { while (Strcmp(nodeType(n),"using") == 0) { n = Getattr(n,"node"); } if (n) { if (Strcmp(nodeType(n),"namespace") == 0) { Symtab *current = Swig_symbol_current(); Symtab *symtab = Getattr(n,"symtab"); (yyval.node) = new_node("using"); Setattr((yyval.node),"node",n); Setattr((yyval.node),"namespace", (yyvsp[(3) - (4)].str)); if (current != symtab) { Swig_symbol_inherit(symtab); } } else { Swig_error(cparse_file, cparse_line, "'%s' is not a namespace.\n", (yyvsp[(3) - (4)].str)); (yyval.node) = 0; } } else { (yyval.node) = 0; } } } break; case 161: #line 3869 "parser.y" { Hash *h; (yyvsp[(1) - (3)].node) = Swig_symbol_current(); h = Swig_symbol_clookup((yyvsp[(2) - (3)].str),0); if (h && ((yyvsp[(1) - (3)].node) == Getattr(h,"sym:symtab")) && (Strcmp(nodeType(h),"namespace") == 0)) { if (Getattr(h,"alias")) { h = Getattr(h,"namespace"); Swig_warning(WARN_PARSE_NAMESPACE_ALIAS, cparse_file, cparse_line, "Namespace alias '%s' not allowed here. Assuming '%s'\n", (yyvsp[(2) - (3)].str), Getattr(h,"name")); (yyvsp[(2) - (3)].str) = Getattr(h,"name"); } Swig_symbol_setscope(Getattr(h,"symtab")); } else { Swig_symbol_newscope(); Swig_symbol_setscopename((yyvsp[(2) - (3)].str)); } Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); } break; case 162: #line 3887 "parser.y" { Node *n = (yyvsp[(5) - (6)].node); set_nodeType(n,"namespace"); Setattr(n,"name",(yyvsp[(2) - (6)].str)); Setattr(n,"symtab", Swig_symbol_popscope()); Swig_symbol_setscope((yyvsp[(1) - (6)].node)); (yyval.node) = n; Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols((yyval.node)); } break; case 163: #line 3898 "parser.y" { Hash *h; (yyvsp[(1) - (2)].node) = Swig_symbol_current(); h = Swig_symbol_clookup((char *)" ",0); if (h && (Strcmp(nodeType(h),"namespace") == 0)) { Swig_symbol_setscope(Getattr(h,"symtab")); } else { Swig_symbol_newscope(); /* we don't use "__unnamed__", but a long 'empty' name */ Swig_symbol_setscopename(" "); } Namespaceprefix = 0; } break; case 164: #line 3910 "parser.y" { (yyval.node) = (yyvsp[(4) - (5)].node); set_nodeType((yyval.node),"namespace"); Setattr((yyval.node),"unnamed","1"); Setattr((yyval.node),"symtab", Swig_symbol_popscope()); Swig_symbol_setscope((yyvsp[(1) - (5)].node)); Delete(Namespaceprefix); Namespaceprefix = Swig_symbol_qualifiedscopename(0); add_symbols((yyval.node)); } break; case 165: #line 3920 "parser.y" { /* Namespace alias */ Node *n; (yyval.node) = new_node("namespace"); Setattr((yyval.node),"name",(yyvsp[(2) - (5)].id)); Setattr((yyval.node),"alias",(yyvsp[(4) - (5)].str)); n = Swig_symbol_clookup((yyvsp[(4) - (5)].str),0); if (!n) { Swig_error(cparse_file, cparse_line, "Unknown namespace '%s'\n", (yyvsp[(4) - (5)].str)); (yyval.node) = 0; } else { if (Strcmp(nodeType(n),"namespace") != 0) { Swig_error(cparse_file, cparse_line, "'%s' is not a namespace\n",(yyvsp[(4) - (5)].str)); (yyval.node) = 0; } else { while (Getattr(n,"alias")) { n = Getattr(n,"namespace"); } Setattr((yyval.node),"namespace",n); add_symbols((yyval.node)); /* Set up a scope alias */ Swig_symbol_alias((yyvsp[(2) - (5)].id),Getattr(n,"symtab")); } } } break; case 166: #line 3947 "parser.y" { (yyval.node) = (yyvsp[(1) - (2)].node); /* Insert cpp_member (including any siblings) to the front of the cpp_members linked list */ if ((yyval.node)) { Node *p = (yyval.node); Node *pp =0; while (p) { pp = p; p = nextSibling(p); } set_nextSibling(pp,(yyvsp[(2) - (2)].node)); } else { (yyval.node) = (yyvsp[(2) - (2)].node); } } break; case 167: #line 3962 "parser.y" { if (cplus_mode != CPLUS_PUBLIC) { Swig_error(cparse_file,cparse_line,"%%extend can only be used in a public section\n"); } } break; case 168: #line 3966 "parser.y" { (yyval.node) = new_node("extend"); tag_nodes((yyvsp[(4) - (6)].node),"feature:extend",(char*) "1"); appendChild((yyval.node),(yyvsp[(4) - (6)].node)); set_nextSibling((yyval.node),(yyvsp[(6) - (6)].node)); } break; case 169: #line 3972 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 170: #line 3973 "parser.y" { (yyval.node) = 0;} break; case 171: #line 3974 "parser.y" { int start_line = cparse_line; skip_decl(); Swig_error(cparse_file,start_line,"Syntax error in input(3).\n"); exit(1); } break; case 172: #line 3979 "parser.y" { (yyval.node) = (yyvsp[(3) - (3)].node); } break; case 173: #line 3990 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 174: #line 3991 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); if (extendmode) { String *symname; symname= make_name((yyval.node),Getattr((yyval.node),"name"), Getattr((yyval.node),"decl")); if (Strcmp(symname,Getattr((yyval.node),"name")) == 0) { /* No renaming operation. Set name to class name */ Delete(yyrename); yyrename = NewString(Getattr(current_class,"sym:name")); } else { Delete(yyrename); yyrename = symname; } } add_symbols((yyval.node)); default_arguments((yyval.node)); } break; case 175: #line 4008 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 176: #line 4009 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 177: #line 4010 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 178: #line 4011 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 179: #line 4012 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 180: #line 4013 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 181: #line 4014 "parser.y" { (yyval.node) = 0; } break; case 182: #line 4015 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 183: #line 4016 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 184: #line 4017 "parser.y" { (yyval.node) = 0; } break; case 185: #line 4018 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 186: #line 4019 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 187: #line 4020 "parser.y" { (yyval.node) = 0; } break; case 188: #line 4021 "parser.y" {(yyval.node) = (yyvsp[(1) - (1)].node); } break; case 189: #line 4022 "parser.y" {(yyval.node) = (yyvsp[(1) - (1)].node); } break; case 190: #line 4023 "parser.y" { (yyval.node) = 0; } break; case 191: #line 4032 "parser.y" { if (Classprefix) { SwigType *decl = NewStringEmpty(); (yyval.node) = new_node("constructor"); Setattr((yyval.node),"storage",(yyvsp[(1) - (6)].id)); Setattr((yyval.node),"name",(yyvsp[(2) - (6)].type)); Setattr((yyval.node),"parms",(yyvsp[(4) - (6)].pl)); SwigType_add_function(decl,(yyvsp[(4) - (6)].pl)); Setattr((yyval.node),"decl",decl); Setattr((yyval.node),"throws",(yyvsp[(6) - (6)].decl).throws); Setattr((yyval.node),"throw",(yyvsp[(6) - (6)].decl).throwf); if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr((yyval.node),"code",code); Delete(code); } SetFlag((yyval.node),"feature:new"); } else { (yyval.node) = 0; } } break; case 192: #line 4057 "parser.y" { String *name = NewStringf("%s",(yyvsp[(2) - (6)].str)); if (*(Char(name)) != '~') Insert(name,0,"~"); (yyval.node) = new_node("destructor"); Setattr((yyval.node),"name",name); Delete(name); if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr((yyval.node),"code",code); Delete(code); } { String *decl = NewStringEmpty(); SwigType_add_function(decl,(yyvsp[(4) - (6)].pl)); Setattr((yyval.node),"decl",decl); Delete(decl); } Setattr((yyval.node),"throws",(yyvsp[(6) - (6)].dtype).throws); Setattr((yyval.node),"throw",(yyvsp[(6) - (6)].dtype).throwf); add_symbols((yyval.node)); } break; case 193: #line 4081 "parser.y" { String *name; char *c = 0; (yyval.node) = new_node("destructor"); /* Check for template names. If the class is a template and the constructor is missing the template part, we add it */ if (Classprefix && (c = strchr(Char(Classprefix),'<'))) { if (!Strchr((yyvsp[(3) - (7)].str),'<')) { (yyvsp[(3) - (7)].str) = NewStringf("%s%s",(yyvsp[(3) - (7)].str),c); } } Setattr((yyval.node),"storage","virtual"); name = NewStringf("%s",(yyvsp[(3) - (7)].str)); if (*(Char(name)) != '~') Insert(name,0,"~"); Setattr((yyval.node),"name",name); Delete(name); Setattr((yyval.node),"throws",(yyvsp[(7) - (7)].dtype).throws); Setattr((yyval.node),"throw",(yyvsp[(7) - (7)].dtype).throwf); if ((yyvsp[(7) - (7)].dtype).val) { Setattr((yyval.node),"value","0"); } if (Len(scanner_ccode)) { String *code = Copy(scanner_ccode); Setattr((yyval.node),"code",code); Delete(code); } { String *decl = NewStringEmpty(); SwigType_add_function(decl,(yyvsp[(5) - (7)].pl)); Setattr((yyval.node),"decl",decl); Delete(decl); } add_symbols((yyval.node)); } break; case 194: #line 4121 "parser.y" { (yyval.node) = new_node("cdecl"); Setattr((yyval.node),"type",(yyvsp[(3) - (8)].type)); Setattr((yyval.node),"name",(yyvsp[(2) - (8)].str)); Setattr((yyval.node),"storage",(yyvsp[(1) - (8)].id)); SwigType_add_function((yyvsp[(4) - (8)].type),(yyvsp[(6) - (8)].pl)); if ((yyvsp[(8) - (8)].dtype).qualifier) { SwigType_push((yyvsp[(4) - (8)].type),(yyvsp[(8) - (8)].dtype).qualifier); } Setattr((yyval.node),"decl",(yyvsp[(4) - (8)].type)); Setattr((yyval.node),"parms",(yyvsp[(6) - (8)].pl)); Setattr((yyval.node),"conversion_operator","1"); add_symbols((yyval.node)); } break; case 195: #line 4136 "parser.y" { SwigType *decl; (yyval.node) = new_node("cdecl"); Setattr((yyval.node),"type",(yyvsp[(3) - (8)].type)); Setattr((yyval.node),"name",(yyvsp[(2) - (8)].str)); Setattr((yyval.node),"storage",(yyvsp[(1) - (8)].id)); decl = NewStringEmpty(); SwigType_add_reference(decl); SwigType_add_function(decl,(yyvsp[(6) - (8)].pl)); if ((yyvsp[(8) - (8)].dtype).qualifier) { SwigType_push(decl,(yyvsp[(8) - (8)].dtype).qualifier); } Setattr((yyval.node),"decl",decl); Setattr((yyval.node),"parms",(yyvsp[(6) - (8)].pl)); Setattr((yyval.node),"conversion_operator","1"); add_symbols((yyval.node)); } break; case 196: #line 4154 "parser.y" { String *t = NewStringEmpty(); (yyval.node) = new_node("cdecl"); Setattr((yyval.node),"type",(yyvsp[(3) - (7)].type)); Setattr((yyval.node),"name",(yyvsp[(2) - (7)].str)); Setattr((yyval.node),"storage",(yyvsp[(1) - (7)].id)); SwigType_add_function(t,(yyvsp[(5) - (7)].pl)); if ((yyvsp[(7) - (7)].dtype).qualifier) { SwigType_push(t,(yyvsp[(7) - (7)].dtype).qualifier); } Setattr((yyval.node),"decl",t); Setattr((yyval.node),"parms",(yyvsp[(5) - (7)].pl)); Setattr((yyval.node),"conversion_operator","1"); add_symbols((yyval.node)); } break; case 197: #line 4173 "parser.y" { skip_balanced('{','}'); (yyval.node) = 0; } break; case 198: #line 4180 "parser.y" { (yyval.node) = new_node("access"); Setattr((yyval.node),"kind","public"); cplus_mode = CPLUS_PUBLIC; } break; case 199: #line 4187 "parser.y" { (yyval.node) = new_node("access"); Setattr((yyval.node),"kind","private"); cplus_mode = CPLUS_PRIVATE; } break; case 200: #line 4195 "parser.y" { (yyval.node) = new_node("access"); Setattr((yyval.node),"kind","protected"); cplus_mode = CPLUS_PROTECTED; } break; case 201: #line 4218 "parser.y" { cparse_start_line = cparse_line; skip_balanced('{','}'); } break; case 202: #line 4219 "parser.y" { (yyval.node) = 0; if (cplus_mode == CPLUS_PUBLIC) { if ((yyvsp[(6) - (7)].decl).id && strcmp((yyvsp[(2) - (7)].id), "class") != 0) { Nested *n = (Nested *) malloc(sizeof(Nested)); n->code = NewStringEmpty(); Printv(n->code, "typedef ", (yyvsp[(2) - (7)].id), " ", Char(scanner_ccode), " $classname_", (yyvsp[(6) - (7)].decl).id, ";\n", NIL); n->name = Swig_copy_string((yyvsp[(6) - (7)].decl).id); n->line = cparse_start_line; n->type = NewStringEmpty(); n->kind = (yyvsp[(2) - (7)].id); n->unnamed = 0; SwigType_push(n->type, (yyvsp[(6) - (7)].decl).type); n->next = 0; add_nested(n); } else { Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", (yyvsp[(2) - (7)].id)); if (strcmp((yyvsp[(2) - (7)].id), "class") == 0) { /* For now, just treat the nested class as a forward * declaration (SF bug #909387). */ (yyval.node) = new_node("classforward"); Setfile((yyval.node),cparse_file); Setline((yyval.node),cparse_line); Setattr((yyval.node),"kind",(yyvsp[(2) - (7)].id)); Setattr((yyval.node),"name",(yyvsp[(3) - (7)].id)); Setattr((yyval.node),"sym:weak", "1"); add_symbols((yyval.node)); } } } } break; case 203: #line 4253 "parser.y" { cparse_start_line = cparse_line; skip_balanced('{','}'); } break; case 204: #line 4254 "parser.y" { (yyval.node) = 0; if (cplus_mode == CPLUS_PUBLIC) { if (strcmp((yyvsp[(2) - (6)].id),"class") == 0) { Swig_warning(WARN_PARSE_NESTED_CLASS,cparse_file, cparse_line,"Nested class not currently supported (ignored)\n"); /* Generate some code for a new class */ } else if ((yyvsp[(5) - (6)].decl).id) { /* Generate some code for a new class */ Nested *n = (Nested *) malloc(sizeof(Nested)); n->code = NewStringEmpty(); Printv(n->code, "typedef ", (yyvsp[(2) - (6)].id), " " , Char(scanner_ccode), " $classname_", (yyvsp[(5) - (6)].decl).id, ";\n",NIL); n->name = Swig_copy_string((yyvsp[(5) - (6)].decl).id); n->line = cparse_start_line; n->type = NewStringEmpty(); n->kind = (yyvsp[(2) - (6)].id); n->unnamed = 1; SwigType_push(n->type,(yyvsp[(5) - (6)].decl).type); n->next = 0; add_nested(n); } else { Swig_warning(WARN_PARSE_NESTED_CLASS, cparse_file, cparse_line, "Nested %s not currently supported (ignored).\n", (yyvsp[(2) - (6)].id)); } } } break; case 205: #line 4284 "parser.y" { cparse_start_line = cparse_line; skip_balanced('{','}'); } break; case 206: #line 4285 "parser.y" { (yyval.node) = 0; if (cplus_mode == CPLUS_PUBLIC) { Swig_warning(WARN_PARSE_NESTED_CLASS,cparse_file, cparse_line,"Nested class not currently supported (ignored)\n"); } } break; case 207: #line 4302 "parser.y" { (yyval.decl) = (yyvsp[(1) - (1)].decl);} break; case 208: #line 4303 "parser.y" { (yyval.decl).id = 0; } break; case 209: #line 4309 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 210: #line 4312 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 211: #line 4316 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 212: #line 4319 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 213: #line 4320 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 214: #line 4321 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 215: #line 4322 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 216: #line 4323 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 217: #line 4324 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 218: #line 4325 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 219: #line 4326 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); } break; case 220: #line 4329 "parser.y" { Clear(scanner_ccode); (yyval.dtype).throws = (yyvsp[(1) - (2)].dtype).throws; (yyval.dtype).throwf = (yyvsp[(1) - (2)].dtype).throwf; } break; case 221: #line 4334 "parser.y" { skip_balanced('{','}'); (yyval.dtype).throws = (yyvsp[(1) - (2)].dtype).throws; (yyval.dtype).throwf = (yyvsp[(1) - (2)].dtype).throwf; } break; case 222: #line 4341 "parser.y" { Clear(scanner_ccode); (yyval.dtype).val = 0; (yyval.dtype).qualifier = (yyvsp[(1) - (2)].dtype).qualifier; (yyval.dtype).bitfield = 0; (yyval.dtype).throws = (yyvsp[(1) - (2)].dtype).throws; (yyval.dtype).throwf = (yyvsp[(1) - (2)].dtype).throwf; } break; case 223: #line 4349 "parser.y" { Clear(scanner_ccode); (yyval.dtype).val = (yyvsp[(3) - (4)].dtype).val; (yyval.dtype).qualifier = (yyvsp[(1) - (4)].dtype).qualifier; (yyval.dtype).bitfield = 0; (yyval.dtype).throws = (yyvsp[(1) - (4)].dtype).throws; (yyval.dtype).throwf = (yyvsp[(1) - (4)].dtype).throwf; } break; case 224: #line 4357 "parser.y" { skip_balanced('{','}'); (yyval.dtype).val = 0; (yyval.dtype).qualifier = (yyvsp[(1) - (2)].dtype).qualifier; (yyval.dtype).bitfield = 0; (yyval.dtype).throws = (yyvsp[(1) - (2)].dtype).throws; (yyval.dtype).throwf = (yyvsp[(1) - (2)].dtype).throwf; } break; case 225: #line 4368 "parser.y" { } break; case 226: #line 4374 "parser.y" { (yyval.id) = "extern"; } break; case 227: #line 4375 "parser.y" { if (strcmp((yyvsp[(2) - (2)].id),"C") == 0) { (yyval.id) = "externc"; } else { Swig_warning(WARN_PARSE_UNDEFINED_EXTERN,cparse_file, cparse_line,"Unrecognized extern type \"%s\".\n", (yyvsp[(2) - (2)].id)); (yyval.id) = 0; } } break; case 228: #line 4383 "parser.y" { (yyval.id) = "static"; } break; case 229: #line 4384 "parser.y" { (yyval.id) = "typedef"; } break; case 230: #line 4385 "parser.y" { (yyval.id) = "virtual"; } break; case 231: #line 4386 "parser.y" { (yyval.id) = "friend"; } break; case 232: #line 4387 "parser.y" { (yyval.id) = "explicit"; } break; case 233: #line 4388 "parser.y" { (yyval.id) = 0; } break; case 234: #line 4395 "parser.y" { Parm *p; (yyval.pl) = (yyvsp[(1) - (1)].pl); p = (yyvsp[(1) - (1)].pl); while (p) { Replace(Getattr(p,"type"),"typename ", "", DOH_REPLACE_ANY); p = nextSibling(p); } } break; case 235: #line 4406 "parser.y" { if (1) { set_nextSibling((yyvsp[(1) - (2)].p),(yyvsp[(2) - (2)].pl)); (yyval.pl) = (yyvsp[(1) - (2)].p); } else { (yyval.pl) = (yyvsp[(2) - (2)].pl); } } break; case 236: #line 4414 "parser.y" { (yyval.pl) = 0; } break; case 237: #line 4417 "parser.y" { set_nextSibling((yyvsp[(2) - (3)].p),(yyvsp[(3) - (3)].pl)); (yyval.pl) = (yyvsp[(2) - (3)].p); } break; case 238: #line 4421 "parser.y" { (yyval.pl) = 0; } break; case 239: #line 4425 "parser.y" { SwigType_push((yyvsp[(1) - (2)].type),(yyvsp[(2) - (2)].decl).type); (yyval.p) = NewParm((yyvsp[(1) - (2)].type),(yyvsp[(2) - (2)].decl).id); Setfile((yyval.p),cparse_file); Setline((yyval.p),cparse_line); if ((yyvsp[(2) - (2)].decl).defarg) { Setattr((yyval.p),"value",(yyvsp[(2) - (2)].decl).defarg); } } break; case 240: #line 4435 "parser.y" { (yyval.p) = NewParm(NewStringf("template<class> %s %s", (yyvsp[(5) - (6)].id),(yyvsp[(6) - (6)].str)), 0); Setfile((yyval.p),cparse_file); Setline((yyval.p),cparse_line); } break; case 241: #line 4440 "parser.y" { SwigType *t = NewString("v(...)"); (yyval.p) = NewParm(t, 0); Setfile((yyval.p),cparse_file); Setline((yyval.p),cparse_line); } break; case 242: #line 4448 "parser.y" { Parm *p; (yyval.p) = (yyvsp[(1) - (1)].p); p = (yyvsp[(1) - (1)].p); while (p) { if (Getattr(p,"type")) { Replace(Getattr(p,"type"),"typename ", "", DOH_REPLACE_ANY); } p = nextSibling(p); } } break; case 243: #line 4461 "parser.y" { if (1) { set_nextSibling((yyvsp[(1) - (2)].p),(yyvsp[(2) - (2)].p)); (yyval.p) = (yyvsp[(1) - (2)].p); } else { (yyval.p) = (yyvsp[(2) - (2)].p); } } break; case 244: #line 4469 "parser.y" { (yyval.p) = 0; } break; case 245: #line 4472 "parser.y" { set_nextSibling((yyvsp[(2) - (3)].p),(yyvsp[(3) - (3)].p)); (yyval.p) = (yyvsp[(2) - (3)].p); } break; case 246: #line 4476 "parser.y" { (yyval.p) = 0; } break; case 247: #line 4480 "parser.y" { (yyval.p) = (yyvsp[(1) - (1)].p); { /* We need to make a possible adjustment for integer parameters. */ SwigType *type; Node *n = 0; while (!n) { type = Getattr((yyvsp[(1) - (1)].p),"type"); n = Swig_symbol_clookup(type,0); /* See if we can find a node that matches the typename */ if ((n) && (Strcmp(nodeType(n),"cdecl") == 0)) { SwigType *decl = Getattr(n,"decl"); if (!SwigType_isfunction(decl)) { String *value = Getattr(n,"value"); if (value) { String *v = Copy(value); Setattr((yyvsp[(1) - (1)].p),"type",v); Delete(v); n = 0; } } } else { break; } } } } break; case 248: #line 4508 "parser.y" { (yyval.p) = NewParm(0,0); Setfile((yyval.p),cparse_file); Setline((yyval.p),cparse_line); Setattr((yyval.p),"value",(yyvsp[(1) - (1)].dtype).val); } break; case 249: #line 4516 "parser.y" { (yyval.dtype) = (yyvsp[(2) - (2)].dtype); if ((yyvsp[(2) - (2)].dtype).type == T_ERROR) { Swig_warning(WARN_PARSE_BAD_DEFAULT,cparse_file, cparse_line, "Can't set default argument (ignored)\n"); (yyval.dtype).val = 0; (yyval.dtype).rawval = 0; (yyval.dtype).bitfield = 0; (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } } break; case 250: #line 4527 "parser.y" { (yyval.dtype) = (yyvsp[(2) - (5)].dtype); if ((yyvsp[(2) - (5)].dtype).type == T_ERROR) { Swig_warning(WARN_PARSE_BAD_DEFAULT,cparse_file, cparse_line, "Can't set default argument (ignored)\n"); (yyval.dtype) = (yyvsp[(2) - (5)].dtype); (yyval.dtype).val = 0; (yyval.dtype).rawval = 0; (yyval.dtype).bitfield = 0; (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } else { (yyval.dtype).val = NewStringf("%s[%s]",(yyvsp[(2) - (5)].dtype).val,(yyvsp[(4) - (5)].dtype).val); } } break; case 251: #line 4541 "parser.y" { skip_balanced('{','}'); (yyval.dtype).val = 0; (yyval.dtype).rawval = 0; (yyval.dtype).type = T_INT; (yyval.dtype).bitfield = 0; (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } break; case 252: #line 4550 "parser.y" { (yyval.dtype).val = 0; (yyval.dtype).rawval = 0; (yyval.dtype).type = 0; (yyval.dtype).bitfield = (yyvsp[(2) - (2)].dtype).val; (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } break; case 253: #line 4558 "parser.y" { (yyval.dtype).val = 0; (yyval.dtype).rawval = 0; (yyval.dtype).type = T_INT; (yyval.dtype).bitfield = 0; (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } break; case 254: #line 4568 "parser.y" { (yyval.decl) = (yyvsp[(1) - (2)].decl); (yyval.decl).defarg = (yyvsp[(2) - (2)].dtype).rawval ? (yyvsp[(2) - (2)].dtype).rawval : (yyvsp[(2) - (2)].dtype).val; } break; case 255: #line 4572 "parser.y" { (yyval.decl) = (yyvsp[(1) - (2)].decl); (yyval.decl).defarg = (yyvsp[(2) - (2)].dtype).rawval ? (yyvsp[(2) - (2)].dtype).rawval : (yyvsp[(2) - (2)].dtype).val; } break; case 256: #line 4576 "parser.y" { (yyval.decl).type = 0; (yyval.decl).id = 0; (yyval.decl).defarg = (yyvsp[(1) - (1)].dtype).rawval ? (yyvsp[(1) - (1)].dtype).rawval : (yyvsp[(1) - (1)].dtype).val; } break; case 257: #line 4583 "parser.y" { (yyval.decl) = (yyvsp[(1) - (1)].decl); if (SwigType_isfunction((yyvsp[(1) - (1)].decl).type)) { Delete(SwigType_pop_function((yyvsp[(1) - (1)].decl).type)); } else if (SwigType_isarray((yyvsp[(1) - (1)].decl).type)) { SwigType *ta = SwigType_pop_arrays((yyvsp[(1) - (1)].decl).type); if (SwigType_isfunction((yyvsp[(1) - (1)].decl).type)) { Delete(SwigType_pop_function((yyvsp[(1) - (1)].decl).type)); } else { (yyval.decl).parms = 0; } SwigType_push((yyvsp[(1) - (1)].decl).type,ta); Delete(ta); } else { (yyval.decl).parms = 0; } } break; case 258: #line 4600 "parser.y" { (yyval.decl) = (yyvsp[(1) - (1)].decl); if (SwigType_isfunction((yyvsp[(1) - (1)].decl).type)) { Delete(SwigType_pop_function((yyvsp[(1) - (1)].decl).type)); } else if (SwigType_isarray((yyvsp[(1) - (1)].decl).type)) { SwigType *ta = SwigType_pop_arrays((yyvsp[(1) - (1)].decl).type); if (SwigType_isfunction((yyvsp[(1) - (1)].decl).type)) { Delete(SwigType_pop_function((yyvsp[(1) - (1)].decl).type)); } else { (yyval.decl).parms = 0; } SwigType_push((yyvsp[(1) - (1)].decl).type,ta); Delete(ta); } else { (yyval.decl).parms = 0; } } break; case 259: #line 4617 "parser.y" { (yyval.decl).type = 0; (yyval.decl).id = 0; (yyval.decl).parms = 0; } break; case 260: #line 4625 "parser.y" { (yyval.decl) = (yyvsp[(2) - (2)].decl); if ((yyval.decl).type) { SwigType_push((yyvsp[(1) - (2)].type),(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = (yyvsp[(1) - (2)].type); } break; case 261: #line 4633 "parser.y" { (yyval.decl) = (yyvsp[(3) - (3)].decl); SwigType_add_reference((yyvsp[(1) - (3)].type)); if ((yyval.decl).type) { SwigType_push((yyvsp[(1) - (3)].type),(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = (yyvsp[(1) - (3)].type); } break; case 262: #line 4642 "parser.y" { (yyval.decl) = (yyvsp[(1) - (1)].decl); if (!(yyval.decl).type) (yyval.decl).type = NewStringEmpty(); } break; case 263: #line 4646 "parser.y" { (yyval.decl) = (yyvsp[(2) - (2)].decl); (yyval.decl).type = NewStringEmpty(); SwigType_add_reference((yyval.decl).type); if ((yyvsp[(2) - (2)].decl).type) { SwigType_push((yyval.decl).type,(yyvsp[(2) - (2)].decl).type); Delete((yyvsp[(2) - (2)].decl).type); } } break; case 264: #line 4655 "parser.y" { SwigType *t = NewStringEmpty(); (yyval.decl) = (yyvsp[(3) - (3)].decl); SwigType_add_memberpointer(t,(yyvsp[(1) - (3)].str)); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 265: #line 4666 "parser.y" { SwigType *t = NewStringEmpty(); (yyval.decl) = (yyvsp[(4) - (4)].decl); SwigType_add_memberpointer(t,(yyvsp[(2) - (4)].str)); SwigType_push((yyvsp[(1) - (4)].type),t); if ((yyval.decl).type) { SwigType_push((yyvsp[(1) - (4)].type),(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = (yyvsp[(1) - (4)].type); Delete(t); } break; case 266: #line 4678 "parser.y" { (yyval.decl) = (yyvsp[(5) - (5)].decl); SwigType_add_memberpointer((yyvsp[(1) - (5)].type),(yyvsp[(2) - (5)].str)); SwigType_add_reference((yyvsp[(1) - (5)].type)); if ((yyval.decl).type) { SwigType_push((yyvsp[(1) - (5)].type),(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = (yyvsp[(1) - (5)].type); } break; case 267: #line 4688 "parser.y" { SwigType *t = NewStringEmpty(); (yyval.decl) = (yyvsp[(4) - (4)].decl); SwigType_add_memberpointer(t,(yyvsp[(1) - (4)].str)); SwigType_add_reference(t); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 268: #line 4701 "parser.y" { /* Note: This is non-standard C. Template declarator is allowed to follow an identifier */ (yyval.decl).id = Char((yyvsp[(1) - (1)].str)); (yyval.decl).type = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; } break; case 269: #line 4708 "parser.y" { (yyval.decl).id = Char(NewStringf("~%s",(yyvsp[(2) - (2)].str))); (yyval.decl).type = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; } break; case 270: #line 4716 "parser.y" { (yyval.decl).id = Char((yyvsp[(2) - (3)].str)); (yyval.decl).type = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; } break; case 271: #line 4732 "parser.y" { (yyval.decl) = (yyvsp[(3) - (4)].decl); if ((yyval.decl).type) { SwigType_push((yyvsp[(2) - (4)].type),(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = (yyvsp[(2) - (4)].type); } break; case 272: #line 4740 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(4) - (5)].decl); t = NewStringEmpty(); SwigType_add_memberpointer(t,(yyvsp[(2) - (5)].str)); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 273: #line 4751 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(1) - (3)].decl); t = NewStringEmpty(); SwigType_add_array(t,(char*)""); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 274: #line 4762 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(1) - (4)].decl); t = NewStringEmpty(); SwigType_add_array(t,(yyvsp[(3) - (4)].dtype).val); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 275: #line 4773 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(1) - (4)].decl); t = NewStringEmpty(); SwigType_add_function(t,(yyvsp[(3) - (4)].pl)); if (!(yyval.decl).have_parms) { (yyval.decl).parms = (yyvsp[(3) - (4)].pl); (yyval.decl).have_parms = 1; } if (!(yyval.decl).type) { (yyval.decl).type = t; } else { SwigType_push(t, (yyval.decl).type); Delete((yyval.decl).type); (yyval.decl).type = t; } } break; case 276: #line 4792 "parser.y" { /* Note: This is non-standard C. Template declarator is allowed to follow an identifier */ (yyval.decl).id = Char((yyvsp[(1) - (1)].str)); (yyval.decl).type = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; } break; case 277: #line 4800 "parser.y" { (yyval.decl).id = Char(NewStringf("~%s",(yyvsp[(2) - (2)].str))); (yyval.decl).type = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; } break; case 278: #line 4817 "parser.y" { (yyval.decl) = (yyvsp[(3) - (4)].decl); if ((yyval.decl).type) { SwigType_push((yyvsp[(2) - (4)].type),(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = (yyvsp[(2) - (4)].type); } break; case 279: #line 4825 "parser.y" { (yyval.decl) = (yyvsp[(3) - (4)].decl); if (!(yyval.decl).type) { (yyval.decl).type = NewStringEmpty(); } SwigType_add_reference((yyval.decl).type); } break; case 280: #line 4832 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(4) - (5)].decl); t = NewStringEmpty(); SwigType_add_memberpointer(t,(yyvsp[(2) - (5)].str)); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 281: #line 4843 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(1) - (3)].decl); t = NewStringEmpty(); SwigType_add_array(t,(char*)""); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 282: #line 4854 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(1) - (4)].decl); t = NewStringEmpty(); SwigType_add_array(t,(yyvsp[(3) - (4)].dtype).val); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 283: #line 4865 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(1) - (4)].decl); t = NewStringEmpty(); SwigType_add_function(t,(yyvsp[(3) - (4)].pl)); if (!(yyval.decl).have_parms) { (yyval.decl).parms = (yyvsp[(3) - (4)].pl); (yyval.decl).have_parms = 1; } if (!(yyval.decl).type) { (yyval.decl).type = t; } else { SwigType_push(t, (yyval.decl).type); Delete((yyval.decl).type); (yyval.decl).type = t; } } break; case 284: #line 4884 "parser.y" { (yyval.decl).type = (yyvsp[(1) - (1)].type); (yyval.decl).id = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; } break; case 285: #line 4890 "parser.y" { (yyval.decl) = (yyvsp[(2) - (2)].decl); SwigType_push((yyvsp[(1) - (2)].type),(yyvsp[(2) - (2)].decl).type); (yyval.decl).type = (yyvsp[(1) - (2)].type); Delete((yyvsp[(2) - (2)].decl).type); } break; case 286: #line 4896 "parser.y" { (yyval.decl).type = (yyvsp[(1) - (2)].type); SwigType_add_reference((yyval.decl).type); (yyval.decl).id = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; } break; case 287: #line 4903 "parser.y" { (yyval.decl) = (yyvsp[(3) - (3)].decl); SwigType_add_reference((yyvsp[(1) - (3)].type)); if ((yyval.decl).type) { SwigType_push((yyvsp[(1) - (3)].type),(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = (yyvsp[(1) - (3)].type); } break; case 288: #line 4912 "parser.y" { (yyval.decl) = (yyvsp[(1) - (1)].decl); } break; case 289: #line 4915 "parser.y" { (yyval.decl) = (yyvsp[(2) - (2)].decl); (yyval.decl).type = NewStringEmpty(); SwigType_add_reference((yyval.decl).type); if ((yyvsp[(2) - (2)].decl).type) { SwigType_push((yyval.decl).type,(yyvsp[(2) - (2)].decl).type); Delete((yyvsp[(2) - (2)].decl).type); } } break; case 290: #line 4924 "parser.y" { (yyval.decl).id = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; (yyval.decl).type = NewStringEmpty(); SwigType_add_reference((yyval.decl).type); } break; case 291: #line 4931 "parser.y" { (yyval.decl).type = NewStringEmpty(); SwigType_add_memberpointer((yyval.decl).type,(yyvsp[(1) - (2)].str)); (yyval.decl).id = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; } break; case 292: #line 4938 "parser.y" { SwigType *t = NewStringEmpty(); (yyval.decl).type = (yyvsp[(1) - (3)].type); (yyval.decl).id = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; SwigType_add_memberpointer(t,(yyvsp[(2) - (3)].str)); SwigType_push((yyval.decl).type,t); Delete(t); } break; case 293: #line 4948 "parser.y" { (yyval.decl) = (yyvsp[(4) - (4)].decl); SwigType_add_memberpointer((yyvsp[(1) - (4)].type),(yyvsp[(2) - (4)].str)); if ((yyval.decl).type) { SwigType_push((yyvsp[(1) - (4)].type),(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = (yyvsp[(1) - (4)].type); } break; case 294: #line 4959 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(1) - (3)].decl); t = NewStringEmpty(); SwigType_add_array(t,(char*)""); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 295: #line 4970 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(1) - (4)].decl); t = NewStringEmpty(); SwigType_add_array(t,(yyvsp[(3) - (4)].dtype).val); if ((yyval.decl).type) { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); } (yyval.decl).type = t; } break; case 296: #line 4981 "parser.y" { (yyval.decl).type = NewStringEmpty(); (yyval.decl).id = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; SwigType_add_array((yyval.decl).type,(char*)""); } break; case 297: #line 4988 "parser.y" { (yyval.decl).type = NewStringEmpty(); (yyval.decl).id = 0; (yyval.decl).parms = 0; (yyval.decl).have_parms = 0; SwigType_add_array((yyval.decl).type,(yyvsp[(2) - (3)].dtype).val); } break; case 298: #line 4995 "parser.y" { (yyval.decl) = (yyvsp[(2) - (3)].decl); } break; case 299: #line 4998 "parser.y" { SwigType *t; (yyval.decl) = (yyvsp[(1) - (4)].decl); t = NewStringEmpty(); SwigType_add_function(t,(yyvsp[(3) - (4)].pl)); if (!(yyval.decl).type) { (yyval.decl).type = t; } else { SwigType_push(t,(yyval.decl).type); Delete((yyval.decl).type); (yyval.decl).type = t; } if (!(yyval.decl).have_parms) { (yyval.decl).parms = (yyvsp[(3) - (4)].pl); (yyval.decl).have_parms = 1; } } break; case 300: #line 5015 "parser.y" { (yyval.decl).type = NewStringEmpty(); SwigType_add_function((yyval.decl).type,(yyvsp[(2) - (3)].pl)); (yyval.decl).parms = (yyvsp[(2) - (3)].pl); (yyval.decl).have_parms = 1; (yyval.decl).id = 0; } break; case 301: #line 5025 "parser.y" { (yyval.type) = NewStringEmpty(); SwigType_add_pointer((yyval.type)); SwigType_push((yyval.type),(yyvsp[(2) - (3)].str)); SwigType_push((yyval.type),(yyvsp[(3) - (3)].type)); Delete((yyvsp[(3) - (3)].type)); } break; case 302: #line 5032 "parser.y" { (yyval.type) = NewStringEmpty(); SwigType_add_pointer((yyval.type)); SwigType_push((yyval.type),(yyvsp[(2) - (2)].type)); Delete((yyvsp[(2) - (2)].type)); } break; case 303: #line 5038 "parser.y" { (yyval.type) = NewStringEmpty(); SwigType_add_pointer((yyval.type)); SwigType_push((yyval.type),(yyvsp[(2) - (2)].str)); } break; case 304: #line 5043 "parser.y" { (yyval.type) = NewStringEmpty(); SwigType_add_pointer((yyval.type)); } break; case 305: #line 5049 "parser.y" { (yyval.str) = NewStringEmpty(); if ((yyvsp[(1) - (1)].id)) SwigType_add_qualifier((yyval.str),(yyvsp[(1) - (1)].id)); } break; case 306: #line 5053 "parser.y" { (yyval.str) = (yyvsp[(2) - (2)].str); if ((yyvsp[(1) - (2)].id)) SwigType_add_qualifier((yyval.str),(yyvsp[(1) - (2)].id)); } break; case 307: #line 5059 "parser.y" { (yyval.id) = "const"; } break; case 308: #line 5060 "parser.y" { (yyval.id) = "volatile"; } break; case 309: #line 5061 "parser.y" { (yyval.id) = 0; } break; case 310: #line 5067 "parser.y" { (yyval.type) = (yyvsp[(1) - (1)].type); Replace((yyval.type),"typename ","", DOH_REPLACE_ANY); } break; case 311: #line 5073 "parser.y" { (yyval.type) = (yyvsp[(2) - (2)].type); SwigType_push((yyval.type),(yyvsp[(1) - (2)].str)); } break; case 312: #line 5077 "parser.y" { (yyval.type) = (yyvsp[(1) - (1)].type); } break; case 313: #line 5078 "parser.y" { (yyval.type) = (yyvsp[(1) - (2)].type); SwigType_push((yyval.type),(yyvsp[(2) - (2)].str)); } break; case 314: #line 5082 "parser.y" { (yyval.type) = (yyvsp[(2) - (3)].type); SwigType_push((yyval.type),(yyvsp[(3) - (3)].str)); SwigType_push((yyval.type),(yyvsp[(1) - (3)].str)); } break; case 315: #line 5089 "parser.y" { (yyval.type) = (yyvsp[(1) - (1)].type); /* Printf(stdout,"primitive = '%s'\n", $$);*/ } break; case 316: #line 5092 "parser.y" { (yyval.type) = (yyvsp[(1) - (1)].type); } break; case 317: #line 5093 "parser.y" { (yyval.type) = (yyvsp[(1) - (1)].type); } break; case 318: #line 5094 "parser.y" { (yyval.type) = NewStringf("%s%s",(yyvsp[(1) - (2)].type),(yyvsp[(2) - (2)].id)); } break; case 319: #line 5095 "parser.y" { (yyval.type) = NewStringf("enum %s", (yyvsp[(2) - (2)].str)); } break; case 320: #line 5096 "parser.y" { (yyval.type) = (yyvsp[(1) - (1)].type); } break; case 321: #line 5098 "parser.y" { (yyval.type) = (yyvsp[(1) - (1)].str); } break; case 322: #line 5101 "parser.y" { (yyval.type) = NewStringf("%s %s", (yyvsp[(1) - (2)].id), (yyvsp[(2) - (2)].str)); } break; case 323: #line 5106 "parser.y" { if (!(yyvsp[(1) - (1)].ptype).type) (yyvsp[(1) - (1)].ptype).type = NewString("int"); if ((yyvsp[(1) - (1)].ptype).us) { (yyval.type) = NewStringf("%s %s", (yyvsp[(1) - (1)].ptype).us, (yyvsp[(1) - (1)].ptype).type); Delete((yyvsp[(1) - (1)].ptype).us); Delete((yyvsp[(1) - (1)].ptype).type); } else { (yyval.type) = (yyvsp[(1) - (1)].ptype).type; } if (Cmp((yyval.type),"signed int") == 0) { Delete((yyval.type)); (yyval.type) = NewString("int"); } else if (Cmp((yyval.type),"signed long") == 0) { Delete((yyval.type)); (yyval.type) = NewString("long"); } else if (Cmp((yyval.type),"signed short") == 0) { Delete((yyval.type)); (yyval.type) = NewString("short"); } else if (Cmp((yyval.type),"signed long long") == 0) { Delete((yyval.type)); (yyval.type) = NewString("long long"); } } break; case 324: #line 5131 "parser.y" { (yyval.ptype) = (yyvsp[(1) - (1)].ptype); } break; case 325: #line 5134 "parser.y" { if ((yyvsp[(1) - (2)].ptype).us && (yyvsp[(2) - (2)].ptype).us) { Swig_error(cparse_file, cparse_line, "Extra %s specifier.\n", (yyvsp[(2) - (2)].ptype).us); } (yyval.ptype) = (yyvsp[(2) - (2)].ptype); if ((yyvsp[(1) - (2)].ptype).us) (yyval.ptype).us = (yyvsp[(1) - (2)].ptype).us; if ((yyvsp[(1) - (2)].ptype).type) { if (!(yyvsp[(2) - (2)].ptype).type) (yyval.ptype).type = (yyvsp[(1) - (2)].ptype).type; else { int err = 0; if ((Cmp((yyvsp[(1) - (2)].ptype).type,"long") == 0)) { if ((Cmp((yyvsp[(2) - (2)].ptype).type,"long") == 0) || (Strncmp((yyvsp[(2) - (2)].ptype).type,"double",6) == 0)) { (yyval.ptype).type = NewStringf("long %s", (yyvsp[(2) - (2)].ptype).type); } else if (Cmp((yyvsp[(2) - (2)].ptype).type,"int") == 0) { (yyval.ptype).type = (yyvsp[(1) - (2)].ptype).type; } else { err = 1; } } else if ((Cmp((yyvsp[(1) - (2)].ptype).type,"short")) == 0) { if (Cmp((yyvsp[(2) - (2)].ptype).type,"int") == 0) { (yyval.ptype).type = (yyvsp[(1) - (2)].ptype).type; } else { err = 1; } } else if (Cmp((yyvsp[(1) - (2)].ptype).type,"int") == 0) { (yyval.ptype).type = (yyvsp[(2) - (2)].ptype).type; } else if (Cmp((yyvsp[(1) - (2)].ptype).type,"double") == 0) { if (Cmp((yyvsp[(2) - (2)].ptype).type,"long") == 0) { (yyval.ptype).type = NewString("long double"); } else if (Cmp((yyvsp[(2) - (2)].ptype).type,"complex") == 0) { (yyval.ptype).type = NewString("double complex"); } else { err = 1; } } else if (Cmp((yyvsp[(1) - (2)].ptype).type,"float") == 0) { if (Cmp((yyvsp[(2) - (2)].ptype).type,"complex") == 0) { (yyval.ptype).type = NewString("float complex"); } else { err = 1; } } else if (Cmp((yyvsp[(1) - (2)].ptype).type,"complex") == 0) { (yyval.ptype).type = NewStringf("%s complex", (yyvsp[(2) - (2)].ptype).type); } else { err = 1; } if (err) { Swig_error(cparse_file, cparse_line, "Extra %s specifier.\n", (yyvsp[(1) - (2)].ptype).type); } } } } break; case 326: #line 5188 "parser.y" { (yyval.ptype).type = NewString("int"); (yyval.ptype).us = 0; } break; case 327: #line 5192 "parser.y" { (yyval.ptype).type = NewString("short"); (yyval.ptype).us = 0; } break; case 328: #line 5196 "parser.y" { (yyval.ptype).type = NewString("long"); (yyval.ptype).us = 0; } break; case 329: #line 5200 "parser.y" { (yyval.ptype).type = NewString("char"); (yyval.ptype).us = 0; } break; case 330: #line 5204 "parser.y" { (yyval.ptype).type = NewString("wchar_t"); (yyval.ptype).us = 0; } break; case 331: #line 5208 "parser.y" { (yyval.ptype).type = NewString("float"); (yyval.ptype).us = 0; } break; case 332: #line 5212 "parser.y" { (yyval.ptype).type = NewString("double"); (yyval.ptype).us = 0; } break; case 333: #line 5216 "parser.y" { (yyval.ptype).us = NewString("signed"); (yyval.ptype).type = 0; } break; case 334: #line 5220 "parser.y" { (yyval.ptype).us = NewString("unsigned"); (yyval.ptype).type = 0; } break; case 335: #line 5224 "parser.y" { (yyval.ptype).type = NewString("complex"); (yyval.ptype).us = 0; } break; case 336: #line 5228 "parser.y" { (yyval.ptype).type = NewString("__int8"); (yyval.ptype).us = 0; } break; case 337: #line 5232 "parser.y" { (yyval.ptype).type = NewString("__int16"); (yyval.ptype).us = 0; } break; case 338: #line 5236 "parser.y" { (yyval.ptype).type = NewString("__int32"); (yyval.ptype).us = 0; } break; case 339: #line 5240 "parser.y" { (yyval.ptype).type = NewString("__int64"); (yyval.ptype).us = 0; } break; case 340: #line 5246 "parser.y" { /* scanner_check_typedef(); */ } break; case 341: #line 5246 "parser.y" { (yyval.dtype) = (yyvsp[(2) - (2)].dtype); if ((yyval.dtype).type == T_STRING) { (yyval.dtype).rawval = NewStringf("\"%(escape)s\"",(yyval.dtype).val); } else if ((yyval.dtype).type != T_CHAR) { (yyval.dtype).rawval = 0; } (yyval.dtype).bitfield = 0; (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; scanner_ignore_typedef(); } break; case 342: #line 5272 "parser.y" { (yyval.id) = (yyvsp[(1) - (1)].id); } break; case 343: #line 5273 "parser.y" { (yyval.id) = (char *) 0;} break; case 344: #line 5276 "parser.y" { /* Ignore if there is a trailing comma in the enum list */ if ((yyvsp[(3) - (3)].node)) { Node *leftSibling = Getattr((yyvsp[(1) - (3)].node),"_last"); if (!leftSibling) { leftSibling=(yyvsp[(1) - (3)].node); } set_nextSibling(leftSibling,(yyvsp[(3) - (3)].node)); Setattr((yyvsp[(1) - (3)].node),"_last",(yyvsp[(3) - (3)].node)); } (yyval.node) = (yyvsp[(1) - (3)].node); } break; case 345: #line 5289 "parser.y" { (yyval.node) = (yyvsp[(1) - (1)].node); if ((yyvsp[(1) - (1)].node)) { Setattr((yyvsp[(1) - (1)].node),"_last",(yyvsp[(1) - (1)].node)); } } break; case 346: #line 5297 "parser.y" { SwigType *type = NewSwigType(T_INT); (yyval.node) = new_node("enumitem"); Setattr((yyval.node),"name",(yyvsp[(1) - (1)].id)); Setattr((yyval.node),"type",type); SetFlag((yyval.node),"feature:immutable"); Delete(type); } break; case 347: #line 5305 "parser.y" { (yyval.node) = new_node("enumitem"); Setattr((yyval.node),"name",(yyvsp[(1) - (3)].id)); Setattr((yyval.node),"enumvalue", (yyvsp[(3) - (3)].dtype).val); if ((yyvsp[(3) - (3)].dtype).type == T_CHAR) { SwigType *type = NewSwigType(T_CHAR); Setattr((yyval.node),"value",NewStringf("\'%(escape)s\'", (yyvsp[(3) - (3)].dtype).val)); Setattr((yyval.node),"type",type); Delete(type); } else { SwigType *type = NewSwigType(T_INT); Setattr((yyval.node),"value",(yyvsp[(1) - (3)].id)); Setattr((yyval.node),"type",type); Delete(type); } SetFlag((yyval.node),"feature:immutable"); } break; case 348: #line 5322 "parser.y" { (yyval.node) = 0; } break; case 349: #line 5325 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); if (((yyval.dtype).type != T_INT) && ((yyval.dtype).type != T_UINT) && ((yyval.dtype).type != T_LONG) && ((yyval.dtype).type != T_ULONG) && ((yyval.dtype).type != T_SHORT) && ((yyval.dtype).type != T_USHORT) && ((yyval.dtype).type != T_SCHAR) && ((yyval.dtype).type != T_UCHAR) && ((yyval.dtype).type != T_CHAR)) { Swig_error(cparse_file,cparse_line,"Type error. Expecting an int\n"); } if ((yyval.dtype).type == T_CHAR) (yyval.dtype).type = T_INT; } break; case 350: #line 5340 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 351: #line 5341 "parser.y" { Node *n; (yyval.dtype).val = (yyvsp[(1) - (1)].type); (yyval.dtype).type = T_INT; /* Check if value is in scope */ n = Swig_symbol_clookup((yyvsp[(1) - (1)].type),0); if (n) { /* A band-aid for enum values used in expressions. */ if (Strcmp(nodeType(n),"enumitem") == 0) { String *q = Swig_symbol_qualified(n); if (q) { (yyval.dtype).val = NewStringf("%s::%s", q, Getattr(n,"name")); Delete(q); } } } } break; case 352: #line 5360 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 353: #line 5361 "parser.y" { (yyval.dtype).val = NewString((yyvsp[(1) - (1)].id)); (yyval.dtype).type = T_STRING; } break; case 354: #line 5365 "parser.y" { SwigType_push((yyvsp[(3) - (5)].type),(yyvsp[(4) - (5)].decl).type); (yyval.dtype).val = NewStringf("sizeof(%s)",SwigType_str((yyvsp[(3) - (5)].type),0)); (yyval.dtype).type = T_ULONG; } break; case 355: #line 5370 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 356: #line 5371 "parser.y" { (yyval.dtype).val = NewString((yyvsp[(1) - (1)].str)); if (Len((yyval.dtype).val)) { (yyval.dtype).rawval = NewStringf("'%(escape)s'", (yyval.dtype).val); } else { (yyval.dtype).rawval = NewString("'\\0'"); } (yyval.dtype).type = T_CHAR; (yyval.dtype).bitfield = 0; (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } break; case 357: #line 5385 "parser.y" { (yyval.dtype).val = NewStringf("(%s)",(yyvsp[(2) - (3)].dtype).val); (yyval.dtype).type = (yyvsp[(2) - (3)].dtype).type; } break; case 358: #line 5392 "parser.y" { (yyval.dtype) = (yyvsp[(4) - (4)].dtype); if ((yyvsp[(4) - (4)].dtype).type != T_STRING) { (yyval.dtype).val = NewStringf("(%s) %s", SwigType_str((yyvsp[(2) - (4)].dtype).val,0), (yyvsp[(4) - (4)].dtype).val); } } break; case 359: #line 5398 "parser.y" { (yyval.dtype) = (yyvsp[(5) - (5)].dtype); if ((yyvsp[(5) - (5)].dtype).type != T_STRING) { SwigType_push((yyvsp[(2) - (5)].dtype).val,(yyvsp[(3) - (5)].type)); (yyval.dtype).val = NewStringf("(%s) %s", SwigType_str((yyvsp[(2) - (5)].dtype).val,0), (yyvsp[(5) - (5)].dtype).val); } } break; case 360: #line 5405 "parser.y" { (yyval.dtype) = (yyvsp[(5) - (5)].dtype); if ((yyvsp[(5) - (5)].dtype).type != T_STRING) { SwigType_add_reference((yyvsp[(2) - (5)].dtype).val); (yyval.dtype).val = NewStringf("(%s) %s", SwigType_str((yyvsp[(2) - (5)].dtype).val,0), (yyvsp[(5) - (5)].dtype).val); } } break; case 361: #line 5412 "parser.y" { (yyval.dtype) = (yyvsp[(6) - (6)].dtype); if ((yyvsp[(6) - (6)].dtype).type != T_STRING) { SwigType_push((yyvsp[(2) - (6)].dtype).val,(yyvsp[(3) - (6)].type)); SwigType_add_reference((yyvsp[(2) - (6)].dtype).val); (yyval.dtype).val = NewStringf("(%s) %s", SwigType_str((yyvsp[(2) - (6)].dtype).val,0), (yyvsp[(6) - (6)].dtype).val); } } break; case 362: #line 5420 "parser.y" { (yyval.dtype) = (yyvsp[(2) - (2)].dtype); (yyval.dtype).val = NewStringf("&%s",(yyvsp[(2) - (2)].dtype).val); } break; case 363: #line 5424 "parser.y" { (yyval.dtype) = (yyvsp[(2) - (2)].dtype); (yyval.dtype).val = NewStringf("*%s",(yyvsp[(2) - (2)].dtype).val); } break; case 364: #line 5430 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 365: #line 5431 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 366: #line 5432 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 367: #line 5433 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 368: #line 5434 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 369: #line 5435 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 370: #line 5436 "parser.y" { (yyval.dtype) = (yyvsp[(1) - (1)].dtype); } break; case 371: #line 5439 "parser.y" { (yyval.dtype).val = NewStringf("%s+%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote((yyvsp[(1) - (3)].dtype).type,(yyvsp[(3) - (3)].dtype).type); } break; case 372: #line 5443 "parser.y" { (yyval.dtype).val = NewStringf("%s-%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote((yyvsp[(1) - (3)].dtype).type,(yyvsp[(3) - (3)].dtype).type); } break; case 373: #line 5447 "parser.y" { (yyval.dtype).val = NewStringf("%s*%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote((yyvsp[(1) - (3)].dtype).type,(yyvsp[(3) - (3)].dtype).type); } break; case 374: #line 5451 "parser.y" { (yyval.dtype).val = NewStringf("%s/%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote((yyvsp[(1) - (3)].dtype).type,(yyvsp[(3) - (3)].dtype).type); } break; case 375: #line 5455 "parser.y" { (yyval.dtype).val = NewStringf("%s%%%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote((yyvsp[(1) - (3)].dtype).type,(yyvsp[(3) - (3)].dtype).type); } break; case 376: #line 5459 "parser.y" { (yyval.dtype).val = NewStringf("%s&%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote((yyvsp[(1) - (3)].dtype).type,(yyvsp[(3) - (3)].dtype).type); } break; case 377: #line 5463 "parser.y" { (yyval.dtype).val = NewStringf("%s|%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote((yyvsp[(1) - (3)].dtype).type,(yyvsp[(3) - (3)].dtype).type); } break; case 378: #line 5467 "parser.y" { (yyval.dtype).val = NewStringf("%s^%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote((yyvsp[(1) - (3)].dtype).type,(yyvsp[(3) - (3)].dtype).type); } break; case 379: #line 5471 "parser.y" { (yyval.dtype).val = NewStringf("%s << %s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote_type((yyvsp[(1) - (3)].dtype).type); } break; case 380: #line 5475 "parser.y" { (yyval.dtype).val = NewStringf("%s >> %s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = promote_type((yyvsp[(1) - (3)].dtype).type); } break; case 381: #line 5479 "parser.y" { (yyval.dtype).val = NewStringf("%s&&%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = T_INT; } break; case 382: #line 5483 "parser.y" { (yyval.dtype).val = NewStringf("%s||%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = T_INT; } break; case 383: #line 5487 "parser.y" { (yyval.dtype).val = NewStringf("%s==%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = T_INT; } break; case 384: #line 5491 "parser.y" { (yyval.dtype).val = NewStringf("%s!=%s",(yyvsp[(1) - (3)].dtype).val,(yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = T_INT; } break; case 385: #line 5505 "parser.y" { /* Putting >= in the expression literally causes an infinite * loop somewhere in the type system. Just workaround for now * - SWIG_GE is defined in swiglabels.swg. */ (yyval.dtype).val = NewStringf("%s SWIG_GE %s", (yyvsp[(1) - (3)].dtype).val, (yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = T_INT; } break; case 386: #line 5512 "parser.y" { (yyval.dtype).val = NewStringf("%s SWIG_LE %s", (yyvsp[(1) - (3)].dtype).val, (yyvsp[(3) - (3)].dtype).val); (yyval.dtype).type = T_INT; } break; case 387: #line 5516 "parser.y" { (yyval.dtype).val = NewStringf("%s?%s:%s", (yyvsp[(1) - (5)].dtype).val, (yyvsp[(3) - (5)].dtype).val, (yyvsp[(5) - (5)].dtype).val); /* This may not be exactly right, but is probably good enough * for the purposes of parsing constant expressions. */ (yyval.dtype).type = promote((yyvsp[(3) - (5)].dtype).type, (yyvsp[(5) - (5)].dtype).type); } break; case 388: #line 5522 "parser.y" { (yyval.dtype).val = NewStringf("-%s",(yyvsp[(2) - (2)].dtype).val); (yyval.dtype).type = (yyvsp[(2) - (2)].dtype).type; } break; case 389: #line 5526 "parser.y" { (yyval.dtype).val = NewStringf("+%s",(yyvsp[(2) - (2)].dtype).val); (yyval.dtype).type = (yyvsp[(2) - (2)].dtype).type; } break; case 390: #line 5530 "parser.y" { (yyval.dtype).val = NewStringf("~%s",(yyvsp[(2) - (2)].dtype).val); (yyval.dtype).type = (yyvsp[(2) - (2)].dtype).type; } break; case 391: #line 5534 "parser.y" { (yyval.dtype).val = NewStringf("!%s",(yyvsp[(2) - (2)].dtype).val); (yyval.dtype).type = T_INT; } break; case 392: #line 5538 "parser.y" { String *qty; skip_balanced('(',')'); qty = Swig_symbol_type_qualify((yyvsp[(1) - (2)].type),0); if (SwigType_istemplate(qty)) { String *nstr = SwigType_namestr(qty); Delete(qty); qty = nstr; } (yyval.dtype).val = NewStringf("%s%s",qty,scanner_ccode); Clear(scanner_ccode); (yyval.dtype).type = T_INT; Delete(qty); } break; case 393: #line 5554 "parser.y" { (yyval.bases) = (yyvsp[(1) - (1)].bases); } break; case 394: #line 5559 "parser.y" { inherit_list = 1; } break; case 395: #line 5559 "parser.y" { (yyval.bases) = (yyvsp[(3) - (3)].bases); inherit_list = 0; } break; case 396: #line 5560 "parser.y" { (yyval.bases) = 0; } break; case 397: #line 5563 "parser.y" { Hash *list = NewHash(); Node *base = (yyvsp[(1) - (1)].node); Node *name = Getattr(base,"name"); List *lpublic = NewList(); List *lprotected = NewList(); List *lprivate = NewList(); Setattr(list,"public",lpublic); Setattr(list,"protected",lprotected); Setattr(list,"private",lprivate); Delete(lpublic); Delete(lprotected); Delete(lprivate); Append(Getattr(list,Getattr(base,"access")),name); (yyval.bases) = list; } break; case 398: #line 5580 "parser.y" { Hash *list = (yyvsp[(1) - (3)].bases); Node *base = (yyvsp[(3) - (3)].node); Node *name = Getattr(base,"name"); Append(Getattr(list,Getattr(base,"access")),name); (yyval.bases) = list; } break; case 399: #line 5589 "parser.y" { (yyval.node) = NewHash(); Setfile((yyval.node),cparse_file); Setline((yyval.node),cparse_line); Setattr((yyval.node),"name",(yyvsp[(2) - (2)].str)); if (last_cpptype && (Strcmp(last_cpptype,"struct") != 0)) { Setattr((yyval.node),"access","private"); Swig_warning(WARN_PARSE_NO_ACCESS,cparse_file,cparse_line, "No access specifier given for base class %s (ignored).\n",(yyvsp[(2) - (2)].str)); } else { Setattr((yyval.node),"access","public"); } } break; case 400: #line 5602 "parser.y" { (yyval.node) = NewHash(); Setfile((yyval.node),cparse_file); Setline((yyval.node),cparse_line); Setattr((yyval.node),"name",(yyvsp[(4) - (4)].str)); Setattr((yyval.node),"access",(yyvsp[(2) - (4)].id)); if (Strcmp((yyvsp[(2) - (4)].id),"public") != 0) { Swig_warning(WARN_PARSE_PRIVATE_INHERIT, cparse_file, cparse_line,"%s inheritance ignored.\n", (yyvsp[(2) - (4)].id)); } } break; case 401: #line 5615 "parser.y" { (yyval.id) = (char*)"public"; } break; case 402: #line 5616 "parser.y" { (yyval.id) = (char*)"private"; } break; case 403: #line 5617 "parser.y" { (yyval.id) = (char*)"protected"; } break; case 404: #line 5621 "parser.y" { (yyval.id) = (char*)"class"; if (!inherit_list) last_cpptype = (yyval.id); } break; case 405: #line 5625 "parser.y" { (yyval.id) = (char *)"typename"; if (!inherit_list) last_cpptype = (yyval.id); } break; case 406: #line 5631 "parser.y" { (yyval.id) = (yyvsp[(1) - (1)].id); } break; case 407: #line 5634 "parser.y" { (yyval.id) = (char*)"struct"; if (!inherit_list) last_cpptype = (yyval.id); } break; case 408: #line 5638 "parser.y" { (yyval.id) = (char*)"union"; if (!inherit_list) last_cpptype = (yyval.id); } break; case 411: #line 5648 "parser.y" { (yyval.dtype).qualifier = (yyvsp[(1) - (1)].str); (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } break; case 412: #line 5653 "parser.y" { (yyval.dtype).qualifier = 0; (yyval.dtype).throws = (yyvsp[(3) - (4)].pl); (yyval.dtype).throwf = NewString("1"); } break; case 413: #line 5658 "parser.y" { (yyval.dtype).qualifier = (yyvsp[(1) - (5)].str); (yyval.dtype).throws = (yyvsp[(4) - (5)].pl); (yyval.dtype).throwf = NewString("1"); } break; case 414: #line 5663 "parser.y" { (yyval.dtype).qualifier = 0; (yyval.dtype).throws = 0; (yyval.dtype).throwf = 0; } break; case 415: #line 5670 "parser.y" { Clear(scanner_ccode); (yyval.decl).have_parms = 0; (yyval.decl).defarg = 0; (yyval.decl).throws = (yyvsp[(1) - (3)].dtype).throws; (yyval.decl).throwf = (yyvsp[(1) - (3)].dtype).throwf; } break; case 416: #line 5677 "parser.y" { skip_balanced('{','}'); (yyval.decl).have_parms = 0; (yyval.decl).defarg = 0; (yyval.decl).throws = (yyvsp[(1) - (3)].dtype).throws; (yyval.decl).throwf = (yyvsp[(1) - (3)].dtype).throwf; } break; case 417: #line 5684 "parser.y" { Clear(scanner_ccode); (yyval.decl).parms = (yyvsp[(2) - (4)].pl); (yyval.decl).have_parms = 1; (yyval.decl).defarg = 0; (yyval.decl).throws = 0; (yyval.decl).throwf = 0; } break; case 418: #line 5692 "parser.y" { skip_balanced('{','}'); (yyval.decl).parms = (yyvsp[(2) - (4)].pl); (yyval.decl).have_parms = 1; (yyval.decl).defarg = 0; (yyval.decl).throws = 0; (yyval.decl).throwf = 0; } break; case 419: #line 5700 "parser.y" { (yyval.decl).have_parms = 0; (yyval.decl).defarg = (yyvsp[(2) - (3)].dtype).val; (yyval.decl).throws = 0; (yyval.decl).throwf = 0; } break; case 424: #line 5716 "parser.y" { skip_balanced('(',')'); Clear(scanner_ccode); } break; case 425: #line 5722 "parser.y" { String *s = NewStringEmpty(); SwigType_add_template(s,(yyvsp[(2) - (3)].p)); (yyval.id) = Char(s); scanner_last_id(1); } break; case 426: #line 5728 "parser.y" { (yyval.id) = (char*)""; } break; case 427: #line 5731 "parser.y" { (yyval.id) = (yyvsp[(1) - (1)].id); } break; case 428: #line 5732 "parser.y" { (yyval.id) = (yyvsp[(1) - (1)].id); } break; case 429: #line 5735 "parser.y" { (yyval.id) = (yyvsp[(1) - (1)].id); } break; case 430: #line 5736 "parser.y" { (yyval.id) = 0; } break; case 431: #line 5739 "parser.y" { (yyval.str) = 0; if (!(yyval.str)) (yyval.str) = NewStringf("%s%s", (yyvsp[(1) - (2)].str),(yyvsp[(2) - (2)].str)); Delete((yyvsp[(2) - (2)].str)); } break; case 432: #line 5744 "parser.y" { (yyval.str) = NewStringf("::%s%s",(yyvsp[(3) - (4)].str),(yyvsp[(4) - (4)].str)); Delete((yyvsp[(4) - (4)].str)); } break; case 433: #line 5748 "parser.y" { (yyval.str) = NewString((yyvsp[(1) - (1)].str)); } break; case 434: #line 5751 "parser.y" { (yyval.str) = NewStringf("::%s",(yyvsp[(3) - (3)].str)); } break; case 435: #line 5754 "parser.y" { (yyval.str) = NewString((yyvsp[(1) - (1)].str)); } break; case 436: #line 5757 "parser.y" { (yyval.str) = NewStringf("::%s",(yyvsp[(3) - (3)].str)); } break; case 437: #line 5762 "parser.y" { (yyval.str) = NewStringf("::%s%s",(yyvsp[(2) - (3)].str),(yyvsp[(3) - (3)].str)); Delete((yyvsp[(3) - (3)].str)); } break; case 438: #line 5766 "parser.y" { (yyval.str) = NewStringf("::%s",(yyvsp[(2) - (2)].str)); } break; case 439: #line 5769 "parser.y" { (yyval.str) = NewStringf("::%s",(yyvsp[(2) - (2)].str)); } break; case 440: #line 5776 "parser.y" { (yyval.str) = NewStringf("::~%s",(yyvsp[(2) - (2)].str)); } break; case 441: #line 5782 "parser.y" { (yyval.str) = NewStringf("%s%s",(yyvsp[(1) - (2)].id),(yyvsp[(2) - (2)].id)); /* if (Len($2)) { scanner_last_id(1); } */ } break; case 442: #line 5791 "parser.y" { (yyval.str) = 0; if (!(yyval.str)) (yyval.str) = NewStringf("%s%s", (yyvsp[(1) - (2)].id),(yyvsp[(2) - (2)].str)); Delete((yyvsp[(2) - (2)].str)); } break; case 443: #line 5796 "parser.y" { (yyval.str) = NewStringf("::%s%s",(yyvsp[(3) - (4)].id),(yyvsp[(4) - (4)].str)); Delete((yyvsp[(4) - (4)].str)); } break; case 444: #line 5800 "parser.y" { (yyval.str) = NewString((yyvsp[(1) - (1)].id)); } break; case 445: #line 5803 "parser.y" { (yyval.str) = NewStringf("::%s",(yyvsp[(3) - (3)].id)); } break; case 446: #line 5806 "parser.y" { (yyval.str) = NewString((yyvsp[(1) - (1)].str)); } break; case 447: #line 5809 "parser.y" { (yyval.str) = NewStringf("::%s",(yyvsp[(3) - (3)].str)); } break; case 448: #line 5814 "parser.y" { (yyval.str) = NewStringf("::%s%s",(yyvsp[(2) - (3)].id),(yyvsp[(3) - (3)].str)); Delete((yyvsp[(3) - (3)].str)); } break; case 449: #line 5818 "parser.y" { (yyval.str) = NewStringf("::%s",(yyvsp[(2) - (2)].id)); } break; case 450: #line 5821 "parser.y" { (yyval.str) = NewStringf("::%s",(yyvsp[(2) - (2)].str)); } break; case 451: #line 5824 "parser.y" { (yyval.str) = NewStringf("::~%s",(yyvsp[(2) - (2)].id)); } break; case 452: #line 5830 "parser.y" { (yyval.id) = (char *) malloc(strlen((yyvsp[(1) - (2)].id))+strlen((yyvsp[(2) - (2)].id))+1); strcpy((yyval.id),(yyvsp[(1) - (2)].id)); strcat((yyval.id),(yyvsp[(2) - (2)].id)); } break; case 453: #line 5835 "parser.y" { (yyval.id) = (yyvsp[(1) - (1)].id);} break; case 454: #line 5838 "parser.y" { (yyval.str) = NewString((yyvsp[(1) - (1)].id)); } break; case 455: #line 5841 "parser.y" { skip_balanced('{','}'); (yyval.str) = NewString(scanner_ccode); } break; case 456: #line 5845 "parser.y" { (yyval.str) = (yyvsp[(1) - (1)].str); } break; case 457: #line 5850 "parser.y" { Hash *n; (yyval.node) = NewHash(); n = (yyvsp[(2) - (3)].node); while(n) { String *name, *value; name = Getattr(n,"name"); value = Getattr(n,"value"); if (!value) value = (String *) "1"; Setattr((yyval.node),name, value); n = nextSibling(n); } } break; case 458: #line 5863 "parser.y" { (yyval.node) = 0; } break; case 459: #line 5867 "parser.y" { (yyval.node) = NewHash(); Setattr((yyval.node),"name",(yyvsp[(1) - (3)].id)); Setattr((yyval.node),"value",(yyvsp[(3) - (3)].id)); } break; case 460: #line 5872 "parser.y" { (yyval.node) = NewHash(); Setattr((yyval.node),"name",(yyvsp[(1) - (5)].id)); Setattr((yyval.node),"value",(yyvsp[(3) - (5)].id)); set_nextSibling((yyval.node),(yyvsp[(5) - (5)].node)); } break; case 461: #line 5878 "parser.y" { (yyval.node) = NewHash(); Setattr((yyval.node),"name",(yyvsp[(1) - (1)].id)); } break; case 462: #line 5882 "parser.y" { (yyval.node) = NewHash(); Setattr((yyval.node),"name",(yyvsp[(1) - (3)].id)); set_nextSibling((yyval.node),(yyvsp[(3) - (3)].node)); } break; case 463: #line 5887 "parser.y" { (yyval.node) = (yyvsp[(3) - (3)].node); Setattr((yyval.node),"name",(yyvsp[(1) - (3)].id)); } break; case 464: #line 5891 "parser.y" { (yyval.node) = (yyvsp[(3) - (5)].node); Setattr((yyval.node),"name",(yyvsp[(1) - (5)].id)); set_nextSibling((yyval.node),(yyvsp[(5) - (5)].node)); } break; case 465: #line 5898 "parser.y" { (yyval.id) = (yyvsp[(1) - (1)].id); } break; case 466: #line 5901 "parser.y" { (yyval.id) = Char((yyvsp[(1) - (1)].dtype).val); } break; /* Line 1267 of yacc.c. */ #line 10054 "y.tab.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse look-ahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse look-ahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } if (yyn == YYFINAL) YYACCEPT; *++yyvsp = yylval; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #ifndef yyoverflow /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEOF && yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } #line 5908 "parser.y" SwigType *Swig_cparse_type(String *s) { String *ns; ns = NewStringf("%s;",s); Seek(ns,0,SEEK_SET); scanner_file(ns); top = 0; scanner_next_token(PARSETYPE); yyparse(); /* Printf(stdout,"typeparse: '%s' ---> '%s'\n", s, top); */ return top; } Parm *Swig_cparse_parm(String *s) { String *ns; ns = NewStringf("%s;",s); Seek(ns,0,SEEK_SET); scanner_file(ns); top = 0; scanner_next_token(PARSEPARM); yyparse(); /* Printf(stdout,"typeparse: '%s' ---> '%s'\n", s, top); */ Delete(ns); return top; } ParmList *Swig_cparse_parms(String *s) { String *ns; char *cs = Char(s); if (cs && cs[0] != '(') { ns = NewStringf("(%s);",s); } else { ns = NewStringf("%s;",s); } Seek(ns,0,SEEK_SET); scanner_file(ns); top = 0; scanner_next_token(PARSEPARMS); yyparse(); /* Printf(stdout,"typeparse: '%s' ---> '%s'\n", s, top); */ return top; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include <stdlib.h> #include <exception> #include "IParameter.h" PhysicManager *manager = NULL; using namespace xUtils; using namespace vtAgeia; void PhysicManager::_destruct(xBitSet flags /* = 0 */) { //################################################################ // // some sanity checks // assert(mIParameter); assert(m_Worlds); assert(manager); //################################################################ // // Clean instances : // SAFE_DELETE(mIParameter); } ////////////////////////////////////////////////////////////////////////// PhysicManager::PhysicManager(CKContext* context):CKPhysicManager(context,GUID_MODULE_MANAGER,VTCX_API_ENTRY("PhysicManager")) //Name as used in profiler { m_Context->RegisterNewManager(this); m_Worlds = new pWorldMap(); manager = this; _Hook3DBBs(); _HookGenericBBs(); _construct(); int ss = xLogger::GetInstance()->getItemDescriptions().size(); int ss2= xLogger::GetInstance()->getLogItems().size(); xLogger::xLog(ELOGERROR,E_BB,"No Reference Object specified"); timer = 0.0f; mPhysicsSDK = NULL; DongleHasBasicVersion=0; DongleHasAdvancedVersion=0; _LogErrors = _LogInfo = _LogTrace = _LogWarnings = _LogToConsole = 0; mIParameter = new IParameter(this); } ////////////////////////////////////////////////////////////////////////// void PhysicManager::cleanAll() { ////////////////////////////////////////////////////////////////////////// //destroy all worlds : if (getWorlds()->Size()) { destroyWorlds(); m_DefaultWorld = NULL; } ////////////////////////////////////////////////////////////////////////// //destroy default objects : ////////////////////////////////////////////////////////////////////////// //world settings : if (getDefaultWorldSettings()) { SAFE_DELETE(mDefaultWorldSettings); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted default world settings"); } ////////////////////////////////////////////////////////////////////////// //default configuration : if (m_DefaultDocument) { SAFE_DELETE(m_DefaultDocument); xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted default configuration"); } if (pFactory::Instance()) { pFactory::Instance()->reloadConfig("PhysicDefaults.xml"); } if (getPhysicsSDK()) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Physic SDK released "); NxReleasePhysicsSDK(getPhysicsSDK()); mPhysicsSDK = NULL; } _getManagerFlags() = 0 ; } void PhysicManager::doInit() { //CreateWorlds(0); } CKERROR PhysicManager::OnCKPause() { return CK_OK; } CKERROR PhysicManager::OnCKPlay() { int a = _LogErrors; int b = 0; xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGERROR,_LogErrors); xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGERROR,_LogErrors); xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGTRACE,_LogTrace); xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGWARNING,_LogWarnings); xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGINFO,_LogInfo); try { populateAttributeFunctions(); _RegisterAttributeCallbacks(); } catch(std::exception ex) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Error during Attribute List Populations"); } catch(...) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Error during Attribute List Populations"); //systemMessage("System Error"); } if (getNbObjects()) { _migrateOldCustomStructures(GetContext()->GetCurrentScene()); if ( isFlagOff(_getManagerFlags(),E_MF_PSDK_LOADED) && isFlagOff(_getManagerFlags(),E_MF_DEFAULT_WORLD_CREATED) && isFlagOff(_getManagerFlags(),E_MF_FACTORY_CREATED) ) { performInitialization(); checkWorlds(); } } return CK_OK; } CKERROR PhysicManager::PostClearAll() { return CK_OK; } CKERROR PhysicManager::OnCKInit() { bindVariables(); return CK_OK; } CKERROR PhysicManager::PreSave() { return CK_OK; } CKContext* PhysicManager::GetContext() { return manager->m_Context; } PhysicManager* PhysicManager::GetInstance() { if (manager) { return manager; } return NULL; } PhysicManager::~PhysicManager(){} CKERROR PhysicManager::OnPostCopy(CKDependenciesContext& context) { CKDependenciesContext dependencies_ctx(m_Context); // dependencies_ctx.SetOperationMode(CK_DEPENDENCIES_SAVE); /* dependencies_ctx.StartDependencies(iDep); //We scan the group and fill the dependencies context for (int i=0;i<iGrp->GetObjectCount();i++) { CKBeObject* object = iGrp->GetObject(i); object->PrepareDependencies(dependencies_ctx); } */ // Build a list of id to save return CK_OK; XObjectArray dependencies_list = context.FillDependencies(); int s = dependencies_list.Size(); //dependencies_list.PushBack(iGrp->GetID());//add group at the end //copy list of objects in ckobjectarray CKObjectArray* listToSave = CreateCKObjectArray(); XObjectArray::Iterator it1 = dependencies_list.Begin(); XObjectArray::Iterator it2 = dependencies_list.End(); while (it1!=it2) { CKObject* object = m_Context->GetObject(*it1); /*CK_ID cID = object->GetID(); listToSave->InsertRear(*it1++); CKSTRING name = object->GetName(); CK_ID id2 = context.RemapID(cID); CK_ID id3 = context.RemapID(cID);*/ } return CK_OK; } CKERROR PhysicManager::SequenceDeleted(CK_ID *objids,int count) { if (getNbObjects()) { if(GetContext()->IsPlaying()) checkWorlds(); } return CK_OK; } CKERROR PhysicManager::SequenceAddedToScene(CKScene *scn,CK_ID *objids,int count) { int isInLoad=GetContext()->IsInLoad(); int nbOfObjects = 0 ; if (!GetContext()->IsPlaying()) { CKAttributeManager* attman = m_Context->GetAttributeManager(); const XObjectPointerArray& Array = attman->GetAttributeListPtr(GetPAttribute()); nbOfObjects = Array.Size(); if (nbOfObjects) { _migrateOldCustomStructures(scn); } } if (getNbObjects()) { if(GetContext()->IsPlaying()){ /* for (int i = 0 ; i < count ; i++ ) { CK_ID dstId = objids[i]; CKBeObject * obj = GetContext()->GetObject() } */ checkWorlds(); } } return CK_OK; } CKERROR PhysicManager::SequenceToBeDeleted(CK_ID *objids,int count) { return CK_OK; } CKERROR PhysicManager::SequenceRemovedFromScene(CKScene *scn,CK_ID *objids,int count) { if (getNbObjects()) { if(GetContext()->IsPlaying()) checkWorlds(); } return CK_OK; } CKERROR PhysicManager::PreClearAll() { return CK_OK; } CKERROR PhysicManager::OnCKReset() { cleanAll(); _RegisterDynamicParameters(); return CK_OK; } CKERROR PhysicManager::OnCKEnd() { unBindVariables(); return 0; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "Stream.h" #include "cooking.h" #include "tinyxml.h" #include <xDebugTools.h> NxShape*pFactory::createWheelShape1(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr) { NxWheelShape *result = NULL; pRigidBody *body=GetPMan()->getBody(bodyReference); bool assertResult = true; iAssertWR(bodyReference && wheelReference && wheelDescr.isValid() && body && body->getActor(),"",assertResult); if (!assertResult) return NULL; NxActor *actor = body->getActor(); //---------------------------------------------------------------- // // prepare data : // CKMesh *mesh = wheelReference->GetCurrentMesh(); VxVector box_s = mesh->GetLocalBox().GetSize(); float radius = wheelDescr.radius.value > 0.0f ? wheelDescr.radius.value : box_s.v[wheelDescr.radius.referenceAxis] * 0.5f; VxQuaternion quatOffset; VxVector posOffset; vtAgeia::calculateOffsets(bodyReference,wheelReference,quatOffset,posOffset); CK_ID srcID = mesh->GetID(); //---------------------------------------------------------------- // // create convex cylinder : // NxConvexShapeDesc shape; bool resultAssert = true; iAssertW(wheelDescr.convexCylinder.isValid(),wheelDescr.convexCylinder.setToDefault(),""); iAssertW( pFactory::Instance()->_createConvexCylinderMesh(&shape,wheelDescr.convexCylinder,wheelReference),""); shape.localPose.M = pMath::getFrom(quatOffset); shape.localPose.t = pMath::getFrom(posOffset); actor->createShape(shape)->isConvexMesh(); /* NxConvexShapeDesc shape; if (!_createConvexCylinder(&shape,wheelReference)) xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); */ return NULL; }<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // TextureSinus // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// //#include "precomp.h" #include "CKAll.h" CKObjectDeclaration *FillBehaviorTextureSinusDecl(); CKERROR CreateTextureSinusProto(CKBehaviorPrototype **); int TextureSinus(const CKBehaviorContext& behcontext); CKERROR TextureSinusCallBackObject(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorTextureSinusDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Texture Sine2"); od->SetDescription("Produces a sinusoidal displacement on the UV coords of a mesh's material (or one of its channel)."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>X Amplitude: </SPAN>amplitude of sine displacement along the X axis of the texture <BR> <SPAN CLASS=pin>Y Amplitude: </SPAN>amplitude of sine displacement along the Y axis of the texture.<BR> <SPAN CLASS=pin>Velocity: </SPAN>radial speed expressed in radian/seconds.<BR> <SPAN CLASS=pin>Channel: </SPAN>if set to -1, the mapping is calculated only for the default material. Otherwise it is processed on the specified channel.<BR> <BR> */ /* warning: - The initial UV (mapping coordinates) on the mesh for this texture are saved when the building block is attached to the mesh (that's why we can't target this building block to another mesh than the one the building block is applied to), therefore you needn't to put Initials Conditions to the mesh if you wish to recover the initial mapping of the texture.<BR> - Beware, not all the building blocks work with this specification (eg: Texture Scroller need IC to recover the initials mapping).<BR> - The "Texture Sine" BB is a time based building block (i.e. it will execute at the same speed what ever the frame rate is [this means you needn't to add a per second building block in front of it]).<BR> */ od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x47e96252,0x632216fe)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateTextureSinusProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("Materials-Textures/Animation"); return od; } CKERROR CreateTextureSinusProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Texture Sine2"); proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("X Amplitude", CKPGUID_FLOAT,"0.1" ); proto->DeclareInParameter("Y Amplitude", CKPGUID_FLOAT ,"0.1"); proto->DeclareInParameter("Velocity", CKPGUID_FLOAT ,"1"); proto->DeclareInParameter("Channel", CKPGUID_INT, "-1"); proto->DeclareInParameter("target", CKPGUID_MESH, "-1"); proto->DeclareLocalParameter(NULL, CKPGUID_VOIDBUF ); // Data proto->DeclareLocalParameter(NULL, CKPGUID_FLOAT, "0.0" ); // Time proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(TextureSinus); proto->SetBehaviorCallbackFct(TextureSinusCallBackObject); *pproto = proto; return CK_OK; } int TextureSinus(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; // we get the amount value float xamp=0.1f; beh->GetInputParameterValue(0, &xamp); // we get the amount value float yamp=0.1f; beh->GetInputParameterValue(1, &yamp); float l= 1.0f; beh->GetInputParameterValue(2, &l); // we get the saved uv's VxUV* savedUV = (VxUV*) beh->GetLocalParameterReadDataPtr(0); // we get the interpolated mesh CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); int channel = -1; beh->GetInputParameterValue(3, &channel); int channelcount = mesh->GetChannelCount(); if (channel < -1 || channel >= channelcount) { beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } CKDWORD Stride; VxUV *uvarray = (VxUV*) mesh->GetModifierUVs(&Stride,channel); int pointsNumber = mesh->GetModifierUVCount(channel); float time; beh->GetLocalParameterValue(1, &time); float t; for( int i=0 ; i<pointsNumber ; i++, uvarray =(VxUV *)((BYTE *)uvarray + Stride)) { t = ((float)i/pointsNumber-0.5f)*4.0f+time*l; uvarray->u = savedUV[i].u + ( 0.5f - savedUV[i].u ) * xamp * cosf(t); uvarray->v = savedUV[i].v + ( 0.5f - savedUV[i].v ) * yamp * sinf(t); } mesh->ModifierUVMove(channel); float pi = 3.1415926535f; time += behcontext.DeltaTime * 0.001f; if(l*time > 2*pi) time -= (2*pi / l); beh->SetLocalParameterValue(1, &time); beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); return CKBR_OK; } /*******************************************************/ /* CALLBACK */ /*******************************************************/ CKERROR TextureSinusCallBackObject(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { #ifdef macintosh case CKM_BEHAVIORLOAD: { CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); if(!mesh) return 0; int nbvert = mesh->GetModifierUVCount(); // we get the saved uv's DWORD *savedUV = (DWORD *) beh->GetLocalParameterWriteDataPtr(0); for(int i=0;i<nbvert*2;i++){ savedUV[i] = ENDIANSWAP32(savedUV[i]); } } break; #endif case CKM_BEHAVIORATTACH: { // we get the mesh vertices CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); if(!mesh) return 0; CKDWORD Stride; VxUV *uvarray = (VxUV*) mesh->GetModifierUVs(&Stride); int nbvert = mesh->GetModifierUVCount(); VxUV *savedUV; savedUV = new VxUV[nbvert]; for(int i=0 ; i<nbvert ; i++, uvarray = (VxUV*)((BYTE*)uvarray + Stride) ){ savedUV[i] = *uvarray; } beh->SetLocalParameterValue(0, savedUV, nbvert * sizeof(VxUV) ); delete[] savedUV; } break; case CKM_BEHAVIORDETACH: { // we get the mesh vertices if(!beh) return 0; CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); if(!mesh) return 0; CKDWORD Stride; VxUV *uvarray = (VxUV*) mesh->GetModifierUVs(&Stride); int nbvert = mesh->GetModifierUVCount(); VxUV *savePos = (VxUV*) beh->GetLocalParameterWriteDataPtr(0); if(!savePos) return 0; for(int i=0 ; i<nbvert ; i++, uvarray = (VxUV*)((BYTE*)uvarray + Stride) ) { *uvarray = savePos[i]; } mesh->ModifierUVMove(); } } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "pCommon.h" #include "pWorldCallbacks.h" CKObjectDeclaration *FillBehaviorPWRayCastAllShapeDecl(); CKERROR CreatePWRayCastAllShapeProto(CKBehaviorPrototype **pproto); int PWRayCastAllShape(const CKBehaviorContext& behcontext); CKERROR PWRayCastAllShapeCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPWRayCastAllShapeDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PWRayCastAllShapes"); od->SetCategory("Physic/Collision"); od->SetDescription("Performs a ray cast test"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7a2308ad,0x7a777c6e)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePWRayCastAllShapeProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePWRayCastAllShapeProto // FullName: CreatePWRayCastAllShapeProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ enum bInput { //bbI_WorldRef, bbI_RayOri, bbI_RayOriRef, bbI_RayDir, bbI_RayDirRef, bbI_Length, bbI_ShapesType, bbI_Groups, bbI_Mask, }; enum bbS { bbS_Hints=2, bbS_Groups=3, bbS_Mask=4 }; enum bbO { bbO_Shape, bbO_Impact, bbO_Normal, bbO_FaceIndex, bbO_Distance, bbO_UV, bbO_Material }; enum bbOT { bbOT_Yes, bbOT_No, bbOT_Finish, bbOT_Next, }; CKERROR CreatePWRayCastAllShapeProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWRayCastAllShapes"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PWRayCastAllShapes PWRayCastAllShapes is categorized in \ref Collision <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Performs a ray cast test. Outputs hit informations.<br> See <A HREF="PWRayCasts.cmo">PWRayCasts.cmo</A> for example. <h3>Technical Information</h3> \image html PWRayCastAllShapes.png <SPAN CLASS="in">In: </SPAN>Triggers the process. <BR> <SPAN CLASS="in">Next: </SPAN>Next Hit. <BR> <SPAN CLASS="out">Yes: </SPAN>Hit occured. <BR> <SPAN CLASS="out">No: </SPAN>No hits. <BR> <SPAN CLASS="out">Finish: </SPAN>Last hit. <BR> <SPAN CLASS="out">Next: </SPAN>Loop out. <BR> <SPAN CLASS="pin">Target: </SPAN>World Reference. pDefaultWorld! <BR> <SPAN CLASS="pin">Ray Origin: </SPAN>Start of the ray. <BR> <SPAN CLASS="pin">Ray Origin Reference: </SPAN>Reference object to determine the start of the ray. Ray Origin becomes transformed if an object is given. <BR> <SPAN CLASS="pin">Ray Direction: </SPAN>Direction of the ray. <BR> <SPAN CLASS="pin">Ray Direction Reference: </SPAN>Reference object to determine the direction of the ray. Ray Direction becomes transformed if an object is given. Up axis will be used then. <BR> <SPAN CLASS="Length">Length: </SPAN>Lenght of the ray. <BR> <SPAN CLASS="pin">Shapes Types: </SPAN>Adds static and/or dynamic shapes to the test. <BR> <SPAN CLASS="pin">Groups: </SPAN>Includes specific groups to the test. <BR> <SPAN CLASS="pin">Groups Mask: </SPAN>Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask <BR> <SPAN CLASS="pout">Touched Body: </SPAN>The touched body. <BR> <SPAN CLASS="pout">Impact Position: </SPAN>Hit point in world space. <BR> <SPAN CLASS="pout">Face Normal: </SPAN>Normal of the hit. <BR> <SPAN CLASS="pout">Face Index: </SPAN> <BR> <SPAN CLASS="pout">Distance: </SPAN>Distance between ray start and hit. <BR> <SPAN CLASS="pout">UV: </SPAN> not used yet ! <BR> <SPAN CLASS="pout">Material Index: </SPAN> Index of the internal physic material. <BR> <br> <br> Is utilizing #pWorld::raycastAllShapes() <br> */ proto->DeclareInput("In"); proto->DeclareInput("Next"); proto->DeclareOutput("Yes"); proto->DeclareOutput("No"); proto->DeclareOutput("Finish"); proto->DeclareOutput("Next"); proto->DeclareInParameter("Ray Origin",CKPGUID_VECTOR); proto->DeclareInParameter("Ray Origin Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Ray Direction",CKPGUID_VECTOR); proto->DeclareInParameter("Ray Direction Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Length",CKPGUID_FLOAT); proto->DeclareInParameter("Shapes Type",VTF_SHAPES_TYPE); proto->DeclareInParameter("Groups",CKPGUID_INT); proto->DeclareInParameter("Filter Mask",VTS_FILTER_GROUPS); proto->DeclareLocalParameter("result", CKPGUID_POINTER); proto->DeclareLocalParameter("index", CKPGUID_INT); proto->DeclareSetting("RayCast Hints",VTF_RAY_HINTS,"0"); proto->DeclareSetting("Groups",CKPGUID_BOOL,"false"); proto->DeclareSetting("Groups Mask",CKPGUID_BOOL,"false"); proto->DeclareOutParameter("Touched Body",CKPGUID_3DENTITY); proto->DeclareOutParameter("Impact Position",CKPGUID_VECTOR); proto->DeclareOutParameter("Face Normal",CKPGUID_VECTOR); proto->DeclareOutParameter("Face Index",CKPGUID_INT); proto->DeclareOutParameter("Distance",CKPGUID_FLOAT); proto->DeclareOutParameter("UV",CKPGUID_2DVECTOR); proto->DeclareOutParameter("Material Index",CKPGUID_INT); //proto->DeclareSetting("Trigger on Enter",CKPGUID_BOOL,"FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct( PWRayCastAllShapeCB ); proto->SetFunction(PWRayCastAllShape); *pproto = proto; return CK_OK; } enum bOutputs { bbO_None, bbO_Enter, bbO_Stay, bbO_Leave, }; //************************************ // Method: PWRayCastAllShape // FullName: PWRayCastAllShape // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PWRayCastAllShape(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorld(target->GetID()); if (!world) { beh->ActivateOutput(bbOT_No); return 0; } NxScene *scene = world->getScene(); if (!scene) { beh->ActivateOutput(bbOT_No); return 0; } if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); pRayCastHits *carray = NULL; beh->GetLocalParameterValue(0,&carray); if (carray) { carray->clear(); }else { carray = new pRayCastHits(); } beh->SetLocalParameterValue(0,&carray); int hitIndex = 0; beh->SetLocalParameterValue(1,&hitIndex); ////////////////////////////////////////////////////////////////////////// CK3dEntity *rayOriRef= (CK3dEntity *) beh->GetInputParameterObject(bbI_RayOriRef); CK3dEntity *rayDirRef= (CK3dEntity *) beh->GetInputParameterObject(bbI_RayDirRef); //ori : VxVector ori = GetInputParameterValue<VxVector>(beh,bbI_RayOri); VxVector oriOut = ori; if (rayOriRef) { rayOriRef->Transform(&oriOut,&ori); } //dir : VxVector dir = GetInputParameterValue<VxVector>(beh,bbI_RayDir); VxVector dirOut = dir; if (rayDirRef) { VxVector dir,up,right; rayDirRef->GetOrientation(&dir,&up,&right); rayDirRef->TransformVector(&dirOut,&up); } float lenght = GetInputParameterValue<float>(beh,bbI_Length); int types = GetInputParameterValue<int>(beh,bbI_ShapesType); VxRay ray; ray.m_Direction = dirOut; ray.m_Origin = oriOut; pRayCastReport &report = *world->getRaycastReport(); report.setCurrentBehavior(beh->GetID()); pRaycastBit hints; beh->GetLocalParameterValue(bbS_Hints,&hints); DWORD groupsEnabled; DWORD groups = 0xffffffff; beh->GetLocalParameterValue(bbS_Groups,&groupsEnabled); if (groupsEnabled) { groups = GetInputParameterValue<int>(beh,bbI_Groups); } pGroupsMask *gmask = NULL; DWORD mask; beh->GetLocalParameterValue(bbS_Mask,&mask); if (mask) { CKParameter *maskP = beh->GetInputParameter(bbI_Mask)->GetRealSource(); gmask->bits0 = GetValueFromParameterStruct<int>(maskP,0); gmask->bits1 = GetValueFromParameterStruct<int>(maskP,1); gmask->bits2 = GetValueFromParameterStruct<int>(maskP,2); gmask->bits3 = GetValueFromParameterStruct<int>(maskP,3); } int nbShapes = world->raycastAllShapes(ray,(pShapesType)types,groups,lenght,hints,gmask); if (nbShapes) { beh->ActivateOutput(bbOT_Yes); beh->ActivateInput(1,TRUE); }else{ beh->ActivateOutput(bbOT_No); } } if( beh->IsInputActive(1) ) { beh->ActivateInput(1,FALSE); pRayCastHits *carray = NULL; beh->GetLocalParameterValue(0,&carray); ////////////////////////////////////////////////////////////////////////// if (carray) { if (carray->size()) { NxRaycastHit *hit = carray->at(carray->size()-1); if (hit) { pRaycastBit hints; beh->GetLocalParameterValue(bbS_Hints,&hints); ////////////////////////////////////////////////////////////////////////// // // if (hints & RCH_Shape) { NxShape *shape = hit->shape; if (shape) { pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(shape->userData); if (sInfo->entID) { CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); if (obj) { beh->SetOutputParameterObject(bbO_Shape,obj); } } } } ////////////////////////////////////////////////////////////////////////// // // if (hints & RCH_Distance) { beh->SetOutputParameterValue(bbO_Distance,&hit->distance); } if (hints & RCH_FaceIndex) { beh->SetOutputParameterValue(bbO_FaceIndex,&hit->internalFaceID); } if (hints & RCH_Impact) { VxVector vec = getFrom(hit->worldImpact); beh->SetOutputParameterValue(bbO_Impact,&vec); } if (hints & RCH_FaceNormal) { VxVector vec = getFrom(hit->worldNormal); beh->SetOutputParameterValue(bbO_Normal,&vec); } if (hints & RCH_Material) { int vec = hit->materialIndex; beh->SetOutputParameterValue(bbO_Material,&vec); } if (hints & RCH_FaceIndex) { int vec = hit->faceID; beh->SetOutputParameterValue(bbO_FaceIndex,&vec); } carray->pop_back(); if (carray->size()) { beh->ActivateOutput(bbOT_Next); }else { beh->ActivateOutput(bbOT_Finish); } } } } } return 0; } //************************************ // Method: PWRayCastAllShapeCB // FullName: PWRayCastAllShapeCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PWRayCastAllShapeCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD flags; beh->GetLocalParameterValue(bbS_Hints,&flags); beh->EnableOutputParameter(bbO_Shape,flags & RCH_Shape); beh->EnableOutputParameter(bbO_Impact,flags & RCH_Impact); beh->EnableOutputParameter(bbO_Normal,flags & RCH_Normal); beh->EnableOutputParameter(bbO_FaceIndex,flags & RCH_FaceIndex); beh->EnableOutputParameter(bbO_Distance,flags & RCH_Distance); beh->EnableOutputParameter(bbO_UV,flags & RCH_UV); beh->EnableOutputParameter(bbO_Material,flags & RCH_Material); DWORD groups; beh->GetLocalParameterValue(bbS_Groups,&groups); beh->EnableInputParameter(bbI_Groups,groups); DWORD mask; beh->GetLocalParameterValue(bbS_Mask,&mask); beh->EnableInputParameter(bbI_Mask,mask); } break; } return CKBR_OK; } <file_sep>#include "TetraGraphics.h" namespace SOFTBODY { TetraGraphicsInterface *gGraphicsInterface = 0; SoftFileInterface *gFileInterface=0; } <file_sep>#include "stdafx.h" #include "xSplash.h" #include "splashscreenex.h" //#include "../../CustomPlayerDefines.h" CSplashScreenEx *splash = NULL; LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); namespace xSplash { CSplashScreenEx *GetSplash() { return splash; } //************************************ // Method: HideSplash // FullName: xSplash::HideSplash // Access: public // Returns: void // Qualifier: //************************************ void HideSplash() { if (splash) { splash->Hide() ; delete splash; splash = NULL; } } //************************************ // Method: ShowSplash // FullName: xSplash::ShowSplash // Access: public // Returns: void // Qualifier: //************************************ void ShowSplash() { if (splash) { splash->Show() ; } } //************************************ // Method: SetText // FullName: xSplash::SetText // Access: public // Returns: void // Qualifier: // Parameter: const char* text //************************************ void SetText(const char* text) { if(splash) { splash->SetText(text); } } //************************************ // Method: CreateSplashEx // FullName: xSplash::CreateSplashEx // Access: public // Returns: void // Qualifier: // Parameter: CWnd *parent // Parameter: int w // Parameter: int h //************************************ void CreateSplashEx(CWnd *parent,int w,int h) { splash=new CSplashScreenEx(); splash->Create(parent,NULL,0,CSS_FADEIN | CSS_CENTERSCREEN | CSS_SHADOW|CSS_FADEOUT|CSS_HIDEONCLICK ); splash->SetBitmap(CPF_SPLASH_FILE,255,0,255); splash->SetTextFont(CPF_SPLASH_TEXT_TYPE,100,CSS_TEXT_NORMAL); int Xpos,Ypos; Xpos=(GetSystemMetrics(SM_CXSCREEN)-w)/2; Ypos=(GetSystemMetrics(SM_CYSCREEN)-h)/2; //splash->SetTextRect(CRect(125,60,291,104)); splash->SetTextColor(RGB(255,251,185)); splash->SetTextFormat(CPF_SPLASH_TEXT_FORMAT); splash->SetFadeInTime(2000); splash->SetFadeOutTime(3000); } //************************************ // Method: CreateSplash // FullName: xSplash::CreateSplash // Access: public // Returns: void // Qualifier: // Parameter: HINSTANCE hinst // Parameter: int w // Parameter: int h //************************************ void CreateSplash(HINSTANCE hinst,int w,int h) { splash=new CSplashScreenEx(); splash->Create(NULL,NULL,0,CSS_FADEIN | CSS_CENTERSCREEN | CSS_SHADOW|CSS_FADEOUT|CSS_HIDEONCLICK ); splash->SetBitmap("splash.bmp",255,0,255); splash->SetTextFont("MicrogrammaDBolExt",100,CSS_TEXT_NORMAL); int Xpos,Ypos; Xpos=(GetSystemMetrics(SM_CXSCREEN)-w)/2; Ypos=(GetSystemMetrics(SM_CYSCREEN)-h)/2; //splash->SetTextRect(CRect(125,60,291,104)); splash->SetTextColor(RGB(255,251,185)); splash->SetTextFormat(DT_SINGLELINE | DT_LEFT | DT_BOTTOM); splash->Show(); //splash=CreateDialog(hinst,(LPCTSTR)IDD_DIALOG2, NULL, (DLGPROC)About); /*::GetWindowRect(splash->getw,&rc); SetWindowPos(splash,NULL,(GetSystemMetrics(SM_CXSCREEN)-(rc.right-rc.left))/2, (GetSystemMetrics(SM_CYSCREEN)-(rc.bottom-rc.top))/2, 0,0,SWP_NOZORDER|SWP_NOSIZE); ShowWindow(splash, SW_SHOW); UpdateWindow(splash); */ } //************************************ // Method: About // FullName: xSplash::About // Access: public // Returns: LRESULT CALLBACK // Qualifier: // Parameter: HWND hDlg // Parameter: UINT message // Parameter: WPARAM wParam // Parameter: LPARAM lParam //************************************ LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; } }//end of namespace xSplash <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pFluid.h" #include "pFluidEmitter.h" #include "CK3dPointCloud.h" #ifdef HAS_FLUIDS pFluidEmitter*pFluid::createEmitter(const pFluidEmitterDesc& desc) { NxFluidEmitterDesc eDesc ; eDesc.setToDefault(); pFactory::Instance()->copyToEmitterDesc(eDesc,desc); int valid = eDesc.isValid(); if (!valid) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Emitter Description not Valid !"); return NULL; } CK3dEntity*entityReference = (CK3dEntity*)ctx()->GetObject(desc.entityReference); if (!entityReference) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"You must set a reference object ID in .referenceEntity"); return NULL; } eDesc.relPose.M.id(); eDesc.relPose.M.rotX(-NxHalfPiF32); eDesc.relPose.t = NxVec3(0,1.1f,0); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// NxFluidEmitter *emitter = getFluid()->createEmitter(eDesc); if (!emitter) return NULL; pFluidEmitter * result = new pFluidEmitter(); result->setEmitter(emitter); result->setFluid(this); result->setEntityReference(entityReference->GetID()); VxVector pos; if (desc.frameShape) { desc.frameShape->GetPosition(&pos); } emitter->setGlobalPosition(getFrom(pos)); emitter->userData = result; ////////////////////////////////////////////////////////////////////////// // // Render Settings : // pFluidRenderSettings *rSettings = new pFluidRenderSettings(ctx(),desc.entityReference,"pFluidEmitter"); rSettings->setToDefault(); rSettings->setEmitter(result); return result; } CK3dEntity*pFluid::getParticleObject() { CK3dEntity* result = (CK3dEntity*)ctx()->GetObject(entityID); return result; } void pFluid::updateVirtoolsMesh() { /* updateCloud(); return;*/ //todo, move this into a small billboard rendering lib. if (!mRenderBuffer) { unsigned sizeFloat = mMaxParticles * 3 * 4; mRenderBuffer = new float[sizeFloat]; if (mTrackUserData) { mRenderBufferUserData = new float[mMaxParticles * 4 * 4]; } } return ; CK3dEntity *dstEnt = getParticleObject(); CKMesh *mesh = getParticleObject()->GetCurrentMesh(); if (!dstEnt || !mesh ) { return; } if (mParticleBuffer) { for (int i = 0 ; i < mesh->GetVertexCount() ; i++) { pParticle *p = &mParticleBuffer[i]; if (p) { VxVector v = getFrom(p->position); VxVector outIV; getParticleObject()->InverseTransform(&outIV,&v); mesh->SetVertexPosition(i,&outIV); } } } mesh->VertexMove(); } pFluid::pFluid(NxFluidDesc &desc, bool trackUserData, bool provideCollisionNormals, const VxVector& color, float particleSize) : mParticleBufferNum(0), mParticleBuffer(NULL), mFluid(NULL), mTrackUserData(trackUserData), mMyParticleBuffer(NULL), mCreatedParticleIdsNum(0), mCreatedParticleIds(NULL), mDeletedParticleIdsNum(0), mDeletedParticleIds(NULL), mParticleColor(color), mParticleSize(particleSize), mRenderBuffer(NULL), mRenderBufferUserData(NULL) { mMaxParticles = desc.maxParticles; mParticleBuffer = new pParticle[mMaxParticles]; desc.userData = this; entityID = 0; //Setup particle write data. NxParticleData particleData; particleData.numParticlesPtr = &mParticleBufferNum; particleData.bufferPos = &mParticleBuffer[0].position.x; particleData.bufferPosByteStride = sizeof(pParticle); particleData.bufferVel = &mParticleBuffer[0].velocity.x; particleData.bufferVelByteStride = sizeof(pParticle); particleData.bufferDensity = &mParticleBuffer[0].density; particleData.bufferDensityByteStride = sizeof(pParticle); particleData.bufferLife = &mParticleBuffer[0].lifetime; particleData.bufferLifeByteStride = sizeof(pParticle); particleData.bufferId = &mParticleBuffer[0].id; particleData.bufferIdByteStride = sizeof(pParticle); if (provideCollisionNormals) { particleData.bufferCollisionNormal = &mParticleBuffer[0].collisionNormal.x; particleData.bufferCollisionNormalByteStride = sizeof(pParticle); } desc.particlesWriteData = particleData; //User data buffers if (mTrackUserData) { //mMyParticleBuffer = new MyParticle[mMaxParticles]; mCreatedParticleIds = new NxU32[mMaxParticles]; mDeletedParticleIds = new NxU32[mMaxParticles]; //Setup id write data. NxParticleIdData idData; //Creation idData.numIdsPtr = &mCreatedParticleIdsNum; idData.bufferId = mCreatedParticleIds; idData.bufferIdByteStride = sizeof(NxU32); desc.particleCreationIdWriteData = idData; //Deletion idData.numIdsPtr = &mDeletedParticleIdsNum; idData.bufferId = mDeletedParticleIds; idData.bufferIdByteStride = sizeof(NxU32); desc.particleDeletionIdWriteData = idData; } } pFluidDesc::pFluidDesc() { setToDefault(); } void pFluidDesc::setToDefault() { maxParticles = 500; numReserveParticles = 0; restParticlesPerMeter = 50.0f; restDensity = 1000.0f; kernelRadiusMultiplier = 1.2f; motionLimitMultiplier = 3.0f * kernelRadiusMultiplier; collisionDistanceMultiplier = 0.1f * kernelRadiusMultiplier; packetSizeMultiplier = 16; stiffness = 20.0f; viscosity = 6.0f; surfaceTension = 0.0f; damping = 0.0f; fadeInTime = 0.0f; externalAcceleration.Set(0.0f,0.0f,0.0f); projectionPlane.set(NxVec3(0.0f, 0.0f, 1.0f), 0.0f); restitutionForStaticShapes = 0.5f; dynamicFrictionForStaticShapes = 0.05f; staticFrictionForStaticShapes = 0.05f; attractionForStaticShapes = 0.0f; restitutionForDynamicShapes = 0.5f; dynamicFrictionForDynamicShapes = 0.5f; staticFrictionForDynamicShapes = 0.5f; attractionForDynamicShapes = 0.0f; collisionResponseCoefficient = 0.2f; simulationMethod = (pFluidSimulationMethod)(NX_F_SPH); collisionMethod =(pFluidCollisionMethod)(NX_F_STATIC|NX_F_DYNAMIC); collisionGroup = 0; groupsMask.bits0 = 0; groupsMask.bits1 = 0; groupsMask.bits2 = 0; groupsMask.bits3 = 0; flags = (pFluidFlag)(NX_FF_ENABLED); flags &= ~NX_FF_HARDWARE; userData = NULL; name = NULL; worldReference = 0 ; } bool pFluidDesc::isValid()const { if (kernelRadiusMultiplier < 1.0f) return false; if (restDensity <= 0.0f) return false; if (restParticlesPerMeter <= 0.0f) return false; if (packetSizeMultiplier < 4) return false; if (packetSizeMultiplier & ( packetSizeMultiplier - 1 ) ) return false; if (motionLimitMultiplier <= 0.0f) return false; if (motionLimitMultiplier > packetSizeMultiplier*kernelRadiusMultiplier) return false; if (collisionDistanceMultiplier <= 0.0f) return false; if (collisionDistanceMultiplier > packetSizeMultiplier*kernelRadiusMultiplier) return false; if (stiffness <= 0.0f) return false; if (viscosity <= 0.0f) return false; if (surfaceTension < 0.0f) return false; bool isNoInteraction = (simulationMethod & NX_F_NO_PARTICLE_INTERACTION) > 0; bool isSPH = (simulationMethod & NX_F_SPH) > 0; bool isMixed = (simulationMethod & NX_F_MIXED_MODE) > 0; if (!(isNoInteraction || isSPH || isMixed)) return false; if (isNoInteraction && (isSPH || isMixed)) return false; if (isSPH && (isNoInteraction || isMixed)) return false; if (isMixed && (isNoInteraction || isSPH)) return false; if (damping < 0.0f) return false; if (fadeInTime < 0.0f) return false; if (projectionPlane.normal.isZero()) return false; if (dynamicFrictionForDynamicShapes < 0.0f || dynamicFrictionForDynamicShapes > 1.0f) return false; if (staticFrictionForDynamicShapes < 0.0f || staticFrictionForDynamicShapes > 1.0f) return false; if (restitutionForDynamicShapes < 0.0f || restitutionForDynamicShapes > 1.0f) return false; if (attractionForDynamicShapes < 0.0f) return false; if (dynamicFrictionForStaticShapes < 0.0f || dynamicFrictionForStaticShapes > 1.0f) return false; if (staticFrictionForStaticShapes < 0.0f || staticFrictionForStaticShapes > 1.0f) return false; if (restitutionForStaticShapes < 0.0f || restitutionForStaticShapes > 1.0f) return false; if (attractionForStaticShapes < 0.0f) return false; if (collisionResponseCoefficient < 0.0f) return false; if (maxParticles > 32767) return false; if (maxParticles < 1) return false; if (numReserveParticles >= maxParticles) return false; if(collisionGroup >= 32) return false; // We only support 32 different collision groups return true; } void pFluid::updateCloud() { CK3dPointCloud *cloud = getPointCloud(); if (!cloud) return; CKMesh *mesh = getParticleObject()->GetCurrentMesh(); int count = mesh->GetVertexCount(); VxVector *points = new VxVector[count]; if (mParticleBuffer) { for (int i = 0 ; i < mesh->GetVertexCount() ; i++) { pParticle *p = &mParticleBuffer[i]; if (p) { points[i]= getFrom(p->position); } } } VxVector prec(0.5,0.5,0.5); VxVector a[10]; int b = cloud->CreateFromPointList(2,a,NULL,NULL,NULL,prec); if (b) { int op2=2; op2++; } } #endif // HAS_FLUIDS<file_sep>#ifndef __PJOINTTYPES_H__ #define __PJOINTTYPES_H__ /** \addtogroup Joints @{ */ /** \brief Describes a joint motor. Some joints can be motorized, this allows them to apply a force to cause attached actors to move. Joints which can be motorized: #pJointPulley #pJointRevolute is used for a similar purpose with pJointD6. */ class pMotor { public : /** The relative velocity the motor is trying to achieve.Default = 0.0f. */ float targetVelocity; /** The maximum force (or torque) the motor can exert.Default = 0.0f. */ float maximumForce; /** If true, motor will not brake when it spins faster than velTarget.Default = false. */ bool freeSpin; pMotor() { targetVelocity = 0.0f; maximumForce =0.0f; freeSpin = false; } }; /** \brief Describes a joint limit. pJointLimit is registered as custom structure #pJLimit and can be accessed or modified through parameter operations.<br> This is used for ball joints. \sa \ref PJBall. */ class pJointLimit { public: /** [not yet implemented!] Limit can be made softer by setting this to less than 1. Default = 0.0f; */ float hardness; /** The angle / position beyond which the limit is active. Default = 0.0f; */ float value; /** The limit bounce. Default = 0.0f; */ float restitution; pJointLimit() { hardness = 0.0f; value = 0.0f; restitution = 0.0f; } pJointLimit(float _h,float _r, float _v) { hardness = _h; restitution = _r; value = _v; } }; /** \brief Describes a joint soft limit for D6 usage. pJD6SoftLimit is registered as custom structure #pJD6SLimit and can be accessed or modified through parameter operations.<br> \sa #PJD6. */ class pJD6SoftLimit { public: /**\brief If spring is greater than zero, this is the damping of the spring. */ float damping; /**\brief If greater than zero, the limit is soft, i.e. a spring pulls the joint back to the limit. <b>Range:</b> [0,inf)<br> <b>Default:</b> 0.0 */ float spring; /**\brief The angle or position beyond which the limit is active. Which side the limit restricts depends on whether this is a high or low limit. <b>Unit:</b> Angular: Radians <b>Range:</b> Angular: (-PI,PI)<br> <b>Range:</b> Positional: [0.0,inf)<br> <b>Default:</b> 0.0 */ float value; /**\brief Controls the amount of bounce when the joint hits a limit. <br> <br> A restitution value of 1.0 causes the joint to bounce back with the velocity which it hit the limit. A value of zero causes the joint to stop dead. In situations where the joint has many locked DOFs (e.g. 5) the restitution may not be applied correctly. This is due to a limitation in the solver which causes the restitution velocity to become zero as the solver enforces constraints on the other DOFs. This limitation applies to both angular and linear limits, however it is generally most apparent with limited angular DOFs. Disabling joint projection and increasing the solver iteration count may improve this behavior to some extent. Also, combining soft joint limits with joint motors driving against those limits may affect stability. <b>Range:</b> [0,1]<br> <b>Default:</b> 0.0 */ float restitution; pJD6SoftLimit() { damping = 0.0f; spring = 0.0f; value = 0.0f; restitution = 0.0f; } pJD6SoftLimit(float _damping,float _spring,float _value,float _restitution) { damping = _damping; spring = _spring; value = _value; restitution = _restitution; } }; /** \brief Class used to describe drive properties for a #pJointD6. */ class pJD6Drive { public: /** Damper coefficient <b>Default:</b> 0 <b>Range:</b> [0,inf) */ float damping; /** Spring coefficient <b>Default:</b> 0 <b>Range:</b> (-inf,inf) */ float spring; /** The maximum force (or torque) the drive can exert. <b>Default:</b> FloatMax <b>Range:</b> [0,inf) */ float forceLimit; /** Type of drive to apply.See #D6DriveType. <b>Default:</b> FloatMax <b>Range:</b> [0,inf) */ int driveType; pJD6Drive() { damping = 0.0f; spring = 0.0f; forceLimit = 3.402823466e+38F; driveType = 0; } pJD6Drive(float _damping,float _spring,float _forceLimit,int _driveType) { damping = _damping; spring = _spring; forceLimit = _forceLimit; driveType = _driveType; } }; /** @} */ #endif // __PJOINTTYPES_H__<file_sep>#ifndef PATH_H #define PATH_H #include "CKALL.H" #include "windows.h" #include <STDLIB.H> #include <STRING.H> #include "Shlwapi.h" #pragma comment (lib,"SHLWAPI.LIB") class XPath { private: char path_separator_; char drive_separator_; char extension_separator_; public: XString data_; //ctors inline XPath(); XPath( const XPath& path ); XPath( const XString& filepath ); XPath( const XString& dirpath, const XString& filename ); XPath ( const XString& dirpath, const XString& base, const XString& extension ); XPath ( char drive, const XString& dirpath, const XString& filename ); XPath ( char drive, const XString& dirpath, const XString& base, const XString& extension ); //components XString operator[]( int index ) const; // Testing. bool absolute() const; bool relative() const; bool directory_path() const; bool has_directory() const; bool has_extension() const; bool has_drive() const; bool is_valid(); // Conversion. operator const char*() const; operator const XString&() const; // Comparison int operator==( const XPath& path ) const; int operator==( const XString& string ) const; int operator!=( const XPath& path ) const; int operator!=( const XString& string ) const; int operator<( const XPath& path ) const; int operator<( const XString& string ) const; XPath& operator=( const XString& filepath ); XPath& operator=( const XPath& path ); //used for the objectmode XPath& operator+=(CKBeObject *beo){ if(data_.Length() == 0)data_ = VxGetTempPath().CStr(); data_ << beo->GetName() << ".nmo"; return *this; } // Accessors. char* GetFileName(); char* GetPath(); char path_separator() const; char drive_separator() const; char extension_separator() const; int absolute_levels() const; protected: void init_separators(); // Common finds. size_t last_extension_separator() const; }; /************************************************************************/ /* protected funtions */ /************************************************************************/ inline void XPath::init_separators(){ path_separator_ = '\\'; drive_separator_ = ':'; extension_separator_ = '.'; } /************************************************************************/ /* ctors //ops // converts */ /************************************************************************/ inline XPath::XPath(const XString& dirpath, const XString& filename ){ init_separators(); data_ << dirpath <<path_separator_<< filename; } inline XPath::XPath(){ init_separators(); } inline XPath::XPath( const XString& filepath ) : data_( filepath ){ init_separators(); } inline XPath::XPath( const XPath& path ) : data_( path.data_ ){ init_separators(); } inline XPath::operator const XString&() const{ return data_; } inline XPath::operator const char*() const{ return data_.CStr(); } inline XPath& XPath::operator=( const XString& filepath ){ data_ = filepath; return *this; } inline XPath& XPath::operator=( const XPath& path ){ data_ = path.data_; return *this; } inline int XPath::operator==( const XPath& path ) const{ return data_ == path.data_; } inline int XPath::operator<( const XPath& path ) const{ return data_ < path.data_; } inline int XPath::operator<( const XString& string ) const{ return data_ < string; } inline int XPath::operator==( const XString& string ) const{ return data_ == string; } inline int operator==( const XString& string, const XPath& path ){ return path == string; } inline int XPath::operator!=( const XPath& path ) const{ return data_ != path.data_; } inline int XPath::operator!=( const XString& string ) const{ return data_ != string; } inline int operator!=( const XString& string, const XPath& path ){ return path != string; } /************************************************************************/ /* Functions */ /************************************************************************/ inline char XPath::extension_separator() const{ return extension_separator_; } inline bool XPath::has_drive() const{ return data_.Find( drive_separator(), 0 ) == 1; } inline bool XPath::has_extension() const{ return data_.Find(extension_separator_ , 0 ) == 1; } inline bool XPath::absolute() const{ return has_drive() || (data_.Find( path_separator(), 0 ) == 0); } inline bool XPath::relative() const{ return !absolute(); } /************************************************************************/ /* Get Components */ /************************************************************************/ /************************************************************************/ /* get components */ /************************************************************************/ #endif <file_sep>#include "xNetInterface.h" #include "vtConnection.h" #include "IDistributedClasses.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "IDistributedObjectsInterface.h" #include "IMessages.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "ISession.h" #include "xDistributedSession.h" #include "xDistributedSessionClass.h" #include "xLogger.h" #include "xNetConstants.h" void xNetInterface::setFixedRateParameters(TNL::U32 minPacketSendPeriod, TNL::U32 minPacketRecvPeriod, TNL::U32 maxSendBandwidth, TNL::U32 maxRecvBandwidth,bool global/* =false */) { if (minPacketRecvPeriod < 10) { minPacketRecvPeriod =10; } if (minPacketSendPeriod < 10) { minPacketSendPeriod = 10; } if (maxRecvBandwidth < 100 ) { maxRecvBandwidth = 100; } if (maxRecvBandwidth > 5000 ) { maxRecvBandwidth = 5000; } if (maxSendBandwidth< 100 ) { maxSendBandwidth = 100; } if (maxSendBandwidth > 5000 ) { maxSendBandwidth = 5000; } if (!IsServer()) { if (getConnection()) { getConnection()->setFixedRateParameters(minPacketSendPeriod,minPacketRecvPeriod,maxSendBandwidth,maxRecvBandwidth); } } if (global && IsServer()) { TNL::Vector<TNL::NetConnection* > con_list = getConnectionList(); for(int i = 0; i < con_list.size(); i++) { vtConnection *con = (vtConnection *)con_list[i]; con->setFixedRateParameters(minPacketSendPeriod,minPacketRecvPeriod,maxSendBandwidth,maxRecvBandwidth); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::enableLogLevel(int type,int verbosity,int value) { xLogger::GetInstance()->enableLoggingLevel(type,verbosity,value); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::initBaseClasses(int flags) { IDistributedClasses *cInterface = getDistributedClassInterface(); ////////////////////////////////////////////////////////////////////////// //dist class xDistributedSessionClass*classTemplate = (xDistributedSessionClass*)cInterface->get("Session Class"); //if (!classTemplate) // classTemplate = (xDistributedSessionClass*)cInterface ->createClass("Session Class",E_DC_BTYPE_SESSION); /* classTemplate->addProperty(E_DC_S_NP_MAX_USERS,E_PTYPE_RELIABLE); classTemplate->addProperty(E_DC_S_NP_PASSWORD,E_PTYPE_RELIABLE); classTemplate->addProperty(E_DC_S_NP_TYPE,E_PTYPE_RELIABLE); */ } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::updateDistributedObjects( int flags,float deltaTime ) { IDistributedObjects *doInterface = getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { xDistributedClass *_class = dobj->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_3D_ENTITY ) { xDistributed3DObject *dobj3D = static_cast<xDistributed3DObject*>(dobj); if (dobj3D) { dobj3D->update(deltaTime); } } } } begin++; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::createScopeObject() { return; if (!IsServer()) { /* vtConnection *con = getConnection(); if (con) { con->scopeObject = new xDistributedObject(); con->scopeObject->SetObjectFlags(E_DO_CREATION_COMPLETE); con->scopeObject->SetEntityID(-1); con->scopeObject->SetServerID(-1); con->scopeObject->SetCreationTime(0.0f); con->scopeObject->SetName("Client"); vtDistributedObjectsArrayType *distObjects = getDistributedObjects(); distObjects->PushBack(con->scopeObject); con->setScopeObject(con->scopeObject); logprintf("scope object created"); } */ } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::setConnection(vtConnection* val) { if (!IsServer() && getConnection()) { getConnection()->disconnect("asdasd"); } if (!IsServer()) { connectionToServer = val; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xNetInterface::isValid() { if (getConnection()) { if (getConnection()->getConnectionState() == TNL::NetConnection::Connected ) { return true; } } return false; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xNetInterface::xNetInterface(bool server, const TNL::Address &bindAddress, const TNL::Address &pingAddr) : TNL::NetInterface(bindAddress) { m_IsServer = server; pingingServers = !server; lastPingTime = 0; pingAddress = pingAddr; elapsedConnectionTime = 0.0f; connectionTimeOut = 2000.0f; connectionInProgress = false; m_isConnected = false; m_DistributedClassInterface = new IDistributedClasses(this); getDistributedClassInterface()->createClass("CLIENT CLASS",E_DC_BTYPE_CLIENT); m_DOCounter =0; m_DistObjectInterface = new IDistributedObjects(this); m_DistributedObjects = new xDistributedObjectsArrayType(); m_ObjectUpdateCounter = 0 ; m_NetworkMessages = new xNetworkMessageArrayType(); m_IMessages = new IMessages(this); mCheckObjects = false; connectionToServer = NULL; mISession = new ISession(this); mSessions = new xSessionArrayType(); mCurrentSession = NULL; mMyUserID = -1; mMyClient = NULL; mMessages = new xMessageArrayType(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::destroy() { ////////////////////////////////////////////////////////////////////////// //disconnect : if (IsServer()) { TNL::Vector<TNL::NetConnection* > con_list = getConnectionList(); for(int i = 0; i < con_list.size(); i++) { vtConnection *con = (vtConnection *)con_list[i]; con->disconnect("destroyed"); } }else { if (connectionToServer) { connectionToServer->disconnect("destroyed"); delete connectionToServer; connectionToServer = NULL; } } ////////////////////////////////////////////////////////////////////////// //cleanup dist objects : if (m_DistObjectInterface!=NULL) { m_DistObjectInterface->Destroy(); delete m_DistObjectInterface; m_DistObjectInterface = NULL; } if (m_DistributedObjects!=NULL) { m_DistributedObjects->clear(); delete m_DistributedObjects; m_DistributedObjects = NULL; } if (m_DistributedClassInterface) { m_DistributedClassInterface->getDistrutedClassesPtr()->clear(); m_DistributedClassInterface->destroy(); delete m_DistributedClassInterface; m_DistributedClassInterface = NULL; } if (getMessagesInterface()) { getMessagesInterface()->deleteAllOldMessages(); if (mMessages) { delete mMessages; mMessages = NULL; } } mMyClient = NULL; mMyUserID = -1; mInterfaceFlags = 0 ; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::sendPing(TNL::Address addr,int type) { TNL::PacketStream writeStream; writeStream.write(TNL::U8(type)); writeStream.sendto(mSocket, addr); xLogger::xLog(ELOGINFO,XL_START,"%s - sending ping ", addr.toString()); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::sendPing() { TNL::PacketStream writeStream; writeStream.write(TNL::U8(GamePingRequest)); writeStream.sendto(mSocket, pingAddress); xLogger::xLog(ELOGINFO,XL_START,"%s - sending ping ", pingAddress.toString()); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::tick() { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); if(pingingServers && (lastPingTime + PingDelayTime < currentTime)) { lastPingTime = currentTime; } float timeDelta = (currentTime - mLastTime) / 1000.f; mLastTime = (float)currentTime; mDeltaTime = mDeltaTime + timeDelta; if (!IsServer()) { if (getConnection() && isValid()) { if (getCurrentThresholdTicker() < 50) { calculateUpdateCounter(); } mLastSendTime = getConnection()->getOneWayTime(); mLastRoundTripTime = getConnection()->getRoundTripTime(); } } checkIncomingPackets(); processConnections(); if (getCheckObjects()) { checkObjects(); setCheckObjects(false); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::advanceTime(xTimeType timeNow,float deltaTime) { //return; mLastTime2 = timeNow; mLastDeltaTime2 = deltaTime; mCurrentThresholdTicker +=getCurrentThresholdTicker() +deltaTime; if (getCurrentThresholdTicker() > 50) { mCurrentThresholdTicker = 0.0f; } IDistributedObjects *doInterface = getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; xDistributedClass *_class = dobj->getDistributedClass(); if (_class && dobj ) { if (_class->getEnitityType() != E_DC_BTYPE_CLIENT ) { xDistributedPropertyArrayType &props = *dobj->getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; prop->advanceTime(mLastTime2,mLastDeltaTime2); } } } begin++; } getMessagesInterface()->advanceTime(deltaTime); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::handleInfoPacket(const TNL::Address &address, TNL::U8 packetType, TNL::BitStream *stream) { if (IsServer()) { TNL::PacketStream writeStream; if(packetType == GamePingRequest && IsServer()) { writeStream.write(TNL::U8(GamePingResponse)); writeStream.sendto(mSocket, address); xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Server : %s - sending ping response.", address.toString()); } if(packetType == ScanPingRequest && IsServer()) { writeStream.write(TNL::U8(ScanPingResponse)); writeStream.sendto(mSocket, address); xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Server : %s - sending scan ping response.", address.toString()); } else if(packetType == GamePingResponse && pingingServers ) { xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Client : %s - received ping response.", address.toString()); vtConnection *conn = new vtConnection(); conn->connect(this, address,true,false); // connect to the server through the game's network interface setConnection(conn); conn->m_NetInterface = this; conn->setInterface(this); xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Connecting to server: %s", address.toString()); pingingServers = false; } else if(packetType == ScanPingResponse ) { xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Client : %s - received scan ping response.", address.toString()); } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::processPacket(const TNL::Address &sourceAddress, TNL::BitStream *pStream) { Parent::processPacket(sourceAddress,pStream); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::removeClient(int clientID) { if(IsServer()) { IDistributedObjects *doInterface = getDistObjectInterface(); if (!doInterface)return; xDistributedObjectsArrayType *distObjects = getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject *distObject = *begin; if (distObject) { xDistributedClass *_class = distObject->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT ) { xDistributedClient *distClient = static_cast<xDistributedClient*>(distObject); if (distClient) { if (distClient->getUserID() == clientID ) { delete distClient; return; } } } } } begin++; } }else { xClientInfo *clientInfo = new xClientInfo(); clientInfo->userFlag = USER_DELETED; clientInfo->userID= clientID; getClientInfoTable().push_back(clientInfo); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::addDeleteObject(xDistributedObject* object) { if(!IsServer() && object) { xDistDeleteInfo* dinfo = new xDistDeleteInfo(); dinfo->entityID = object->getEntityID(); dinfo->serverID = object->getServerID(); dinfo->deleteState = E_DO_DS_DELETED ; getDistDeleteTable().push_back(dinfo); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::writeDistributedProperties(TNL::BitStream *bstream) { if(IsServer()) return; IDistributedObjects *doInterface = getDistObjectInterface(); if (!doInterface)return; xDistributedObjectsArrayType *distObjects = getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); if (getObjectUpdateCounter()) { bstream->writeFlag(E_C_CLIENT_OBJECT_UPDATE); bstream->writeRangedU32(getObjectUpdateCounter(), 0, 63 ); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ IDistributedClasses*xNetInterface::getDistributedClassInterface(){return m_DistributedClassInterface;} /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::calculateUpdateCounter() { if (IsServer()) { return; } IDistributedObjects *doInterface = getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); setObjectUpdateCounter(0); while (begin!=end) { xDistributedObject* dobj = *begin; xDistributedClass *_class = dobj->getDistributedClass(); if (_class && dobj ) { if (_class->getEnitityType() != E_DC_BTYPE_CLIENT ) { xDistributedPropertyArrayType &props = *dobj->getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; int blockIndex = prop->getBlockIndex(); dobj->getUpdateBits().set(BIT(blockIndex),prop->getFlags() & E_DP_NEEDS_SEND ); } } if (_class->getEnitityType() == E_DC_BTYPE_CLIENT ) { xDistributedClient *client = (xDistributedClient*)dobj; client->calculateUpdateBits(); } if (dobj->getUpdateBits().getMask()) { getObjectUpdateCounter()++; dobj->setUpdateState(E_DO_US_PENDING); }else { dobj->setUpdateState(E_DO_US_OK); } } begin++; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xNetInterface::getNumConnections() { int i = 0 ; TNL::Vector<TNL::NetConnection* > con_list = getConnectionList(); for(i = 0; i < con_list.size(); i++) { } return i; } void xNetInterface::checkConnections() { /*if (getNumConnections()==0) { getDistObjectInterface()->removeAll(getDistributedObjects()); //xLogger::xLog(ELOGINFO,XL_START,"no clients anymore: remove all objects!"); }*/ } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::disconnect(int connectionID) { if (IsServer())return; if (getConnection()) { getConnection()->disconnect("no reason"); setConnected(false); if (connectionToServer) { delete connectionToServer; connectionToServer = NULL; } } getDistObjectInterface()->removeAll(getDistributedObjects()); getClientInfoTable().clear(); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int xNetInterface::getNumDistributedObjects(int templateType) { int counter = 0 ; IDistributedObjects *doInterface = getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; xDistributedClass *_class = dobj->getDistributedClass(); if (_class && dobj ) { if (_class->getEnitityType() == templateType ) { counter ++; } } begin++; } return counter; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::checkObjects() { xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Server makes an object validation"); if (getConnectionList().size() ==0) { getDistObjectInterface()->removeAll(getDistributedObjects()); getDistributedClassInterface()->getDistrutedClassesPtr()->clear(); xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"Server : No clients anymore, ..delete all"); } checkSessions(); setCheckObjects(false); } void xNetInterface::checkSessions() { xLogger::xLog(ELOGINFO,E_LI_SESSION,"Server : Looking for invalid sessions "); IDistributedObjects *doInterface = getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; xDistributedClass *_class = dobj->getDistributedClass(); if (_class && dobj ) { if (_class->getEnitityType() == E_DC_BTYPE_SESSION ) { xDistributedSession *session = (xDistributedSession*)dobj; xDistributedClient *client = (xDistributedClient*)doInterface->getByUserID(dobj->getUserID(),E_DC_BTYPE_CLIENT); if (!client && session ) { xLogger::xLog(ELOGWARNING,E_LI_SESSION,"Server : Found invalid session object %s : deleting",session->GetName().getString()); ISession *sInterface = getSessionInterface(); sInterface->deleteSession(session->getSessionID()); begin =distObjects->begin(); return; //continue; } } } begin++; } setCheckObjects(false); } void xNetInterface::printObjects(int type, int flags) { switch(type) { case E_OT_DIST_OBJECT: { xLogger::xLog(ELOGINFO,E_LI_CPP,"Print all Objects : Num : %d",getDistributedObjects()->size()); xDistributedObjectsArrayType *distObjects = getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { char out[4096]; //xDistributedClass *_class = dobj->getDistributedClass(); TNL::BitSet32 opflags = xBIT(E_OPF_NAME); xBitSet stylePrintFlags = 0; stylePrintFlags.set(E_PSF_PRINT_LOG_TYPE,true); stylePrintFlags.set(E_PSF_PRINT_COMPONENT,true); //enableFlag(stylePrintFlags,E_PSF_PRINT_LOG_TYPE); //enableFlag(stylePrintFlags,E_PSF_PRINT_COMPONENT); enableFlag(opflags,E_OPF_NAME); enableFlag(opflags,E_OPF_GHOST_ID); /* enableFlag(opflags,E_OPF_USER_ID); enableFlag(opflags,E_OPF_SESSION_ID); enableFlag(opflags,E_OPF_CLASS);*/ uxString objString = dobj->print(opflags); //sprintf(out,"%s | usrID:%d | serverID:%d | sessionID:%d | class:%s | props :%d",dobj->GetName().getString(),dobj->getUserID(),dobj->getServerID(),dobj->getSessionID,_class ? _class->getClassName().getString() : "NOCLASS!",dobj->getDistributedPorperties()->size() ); //TNL::logprintf("\nsessionID:%d",dobj->getSessionID()); //xLogger::xLogExtro(0,"%s",objString.CStr()); xLogger::xLog(stylePrintFlags,ELOGINFO,E_LI_CPP,"%s",objString.CStr()); /*switch(_class->getEnitityType()) { case E_DC_BTYPE_CLIENT : { xDistributedClient *sobj = (xDistributedClient*)dobj; if (sobj) { int gIndex = dobj->getOwnerConnection() ? dobj->getOwnerConnection()->getGhostIndex(dobj) : getConnection()->getGhostIndex(dobj); xLogger::xLogExtro(0,"\n\t -->UserName : %s \n\tSessionID:%d \n\tIsJoined:%d \n\tGhostIndex:%d",sobj->getUserName().getString(),sobj->getSessionID(),isFlagOn(sobj->getClientFlags(),E_CF_SESSION_JOINED) ? 1 : 0,gIndex ); //xLogger::xLogExtro(0,"\n\t -->HasAddingFlag:%d",sobj->getUserName().getString(),sobj->getLocalAddress().getString(),sobj->getSessionID(),isFlagOn(sobj->getClientFlags(),E_CF_ADDING) ? 1 : 0); //xLogger::xLogExtro(0,"\n\t -->HasAddedFlag:%d",sobj->getUserName().getString(),sobj->getLocalAddress().getString(),sobj->getSessionID(),isFlagOn(sobj->getClientFlags(),E_CF_ADDED) ? 1 : 0); } }break; ////////////////////////////////////////////////////////////////////////// case E_DC_BTYPE_SESSION: { xDistributedSession*sobj = (xDistributedSession*)dobj; if (sobj) { xLogger::xLogExtro(0,"\n\t -->Session ID : %d \tLocked:%d \tNumUsers %d \tPrivate : %d \tMaster :%d \n\tFull:%d \n\tMaxPlayers:%d",sobj->getSessionID(),sobj->isLocked(),sobj->getNumUsers(),sobj->isPrivate(),sobj->getUserID(),sobj->isFull(),sobj->getMaxUsers() ); sobj-> } }break; }*/ } begin++; } } break; case E_OT_CLASS: { xLogger::xLog(ELOGINFO,E_LI_CPP,"Print all Classes : Num : %d ",getDistributedClassInterface()->getNumClasses()); xDistributedClassesArrayType *_classes = getDistributedClassInterface()->getDistrutedClassesPtr(); xDistClassIt begin = _classes->begin(); xDistClassIt end = _classes->end(); while (begin!=end) { xDistributedClass *_class = begin->second; if (_class) { char out[4096]; sprintf(out,"\t %s | type :%d | props : %d",_class->getClassName().getString(),_class->getEnitityType(),_class->getDistributedProperties()->size() ); xLogger::xLogExtro(0,"CLASS : %s",out); } begin++; } } } IMessages *mInterface = getMessagesInterface(); xLogger::xLog(ELOGINFO,E_LI_CPP,"Print Messages : Num : %d",mInterface->getMessages()->size()); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xNetInterface::deploySessionClasses(TNL::GhostConnection *connection) { IDistributedClasses *cInterface = getDistributedClassInterface(); xDistributedClassesArrayType *_classes = cInterface->getDistrutedClassesPtr(); xDistClassIt begin = _classes->begin(); xDistClassIt end = _classes->end(); while (begin!=end) { xDistributedClass *_class = begin->second; if (_class && _class->getEnitityType() == E_DC_BTYPE_SESSION ) { TNL::StringPtr className(_class->getClassName().getString()); xLogger::xLog(ELOGINFO,E_LI_DISTRIBUTED_CLASS_DESCRIPTORS,"\n deploying session class %s ",_class->getClassName().getString()); TNL::Int<16>entityType = _class->getEnitityType(); TNL::Vector<TNL::StringPtr>propertyNames; TNL::Vector<TNL::Int<16> >nativeTypes; TNL::Vector<TNL::Int<16> >valueTypes; TNL::Vector<TNL::Int<16> >predictionTypes; xDistributedPropertiesListType &props = *_class->getDistributedProperties(); for (unsigned int i = 0 ; i < props.size() ; i ++ ) { xDistributedPropertyInfo *dInfo = props[i]; propertyNames.push_back( TNL::StringPtr(dInfo->mName) ); nativeTypes.push_back(dInfo->mNativeType); valueTypes.push_back(dInfo->mValueType); predictionTypes.push_back(dInfo->mPredictionType); } ((vtConnection*)connection)->s2cDeployDistributedClass(className,entityType,propertyNames,nativeTypes,valueTypes,predictionTypes); } begin++; } }<file_sep>#pragma once #include "StdAfx2.h" #include "VIControls.h" #include "ParameterDialog.h" #include "CKShader.h" //#include "CUIKNotificationReceiver.h" //--- Include "GenericObjectParameterDialog.h" from CK2UI define IDDs to mak it compile #define IDD_GENOBJECTDIALOG 2011 #define IDD_BASEPARAMDIALOG 2000 #include "Parameters\GenericObjectParameterDialog.h" #include "resource.h" #include "PCommonDialog.h" //--- Some constants #define MFC_NAME_OF_DIALOG "#32770" #define CHECK_MATERIAL_TIMER 57 class CPBXMLSetup : public CParameterDialog ,public CPSharedBase { public: // virtual void PreSubclassWindow(); int m_paramType; CPBXMLSetup(CKParameter* Parameter,CWnd* parent = NULL); CPBXMLSetup(CKParameter* Parameter,CWnd *parent,CK_CLASSID Cid=CKCID_OBJECT); CPBXMLSetup(CKParameter* Parameter,CK_CLASSID Cid=CKCID_OBJECT); virtual ~CPBXMLSetup(); void _destroy(); //BOOL Create(CKParameter* Parameter,UINT nIDTemplate, CWnd* pParentWnd); //BOOL Init(CKParameter* Parameter,UINT nIDTemplate,CParameterDialog *parent); //BOOL OnInitDialog(); CPBXMLSetup* refresh(CKParameter*src); /************************************************************************/ /* Overrides */ /************************************************************************/ void OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); LRESULT OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam); /************************************************************************/ /* Accessors */ /************************************************************************/ CKParameter * getEditedParameter() const { return mParameter; } void setEditedParameter(CKParameter * val) { mParameter= val; } /************************************************************************/ /* Virtools mParameter transfer callbacks : */ /************************************************************************/ virtual BOOL On_UpdateFromParameter(CKParameter* p){ // if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); // if(!p) return FALSE; return TRUE; } virtual BOOL On_UpdateToParameter(CKParameter* p) { /* if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); if(!p) return FALSE; CString cstr;*/ return TRUE; } public: /************************************************************************/ /* Low Level passes */ /************************************************************************/ LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); /************************************************************************/ /* Logical Actions */ /************************************************************************/ virtual int OnSelect(int before=-1); void fillXMLLinks(); HWND getDlgWindowHandle(UINT templateID); /************************************************************************/ /* Members */ /************************************************************************/ // Hull Type VIComboBox XMLInternLink; VIStaticText XMLInternLinkLbl; VIComboBox XMLExternLink; VIStaticText XMLExternLinkLbl; CKParameter *mParameter; VIEdit editValue; VIStaticText textValue; VIComboBox type; enum { IDD = IDD_PB_XML_PARENT }; //{{AFX_VIRTUAL(CPBXMLSetup) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL //{{AFX_MSG(CPBXMLSetup) BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: afx_msg void OnStnClickedXmlMainView(); }; <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // GetCurrentCamera // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorGetCurrentCameraDecl(); CKERROR CreateGetCurrentCameraProto(CKBehaviorPrototype **pproto); int GetCurrentCamera(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorGetCurrentCameraDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Get Current Camera"); od->SetDescription("States the current camera in the active scene."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pout>Current Camera: </SPAN>the camera currently used in the main viewport.<BR> <BR> See Also: 'Set As Active Camera'.<BR> */ od->SetCategory("Cameras/Montage"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x368f22b1,0x222957e4)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGetCurrentCameraProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateGetCurrentCameraProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Get Current Camera"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutParameter("Current Camera",CKPGUID_CAMERA); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(GetCurrentCamera); *pproto = proto; return CK_OK; } int GetCurrentCamera(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); CKCamera* cam = behcontext.CurrentRenderContext->GetAttachedCamera(); beh->SetOutputParameterObject(0,cam); return CKBR_OK; } <file_sep>#ifndef __CSMANAGER_H_ #define __CSMANAGER_H_ #include "../virtools/vt_tools.h" #include "CKBaseManager.h" #include <stdlib.h> #include <map> #include <vector> #define INIT_MAN_GUID CKGUID(0x35824c8a,0x4e320ac4) class csMessage { public : csMessage(){} virtual ~csMessage() { } XString name; char*GetName(){ return name.Str() ; } void SetName(const char* _name) { name = _name; } typedef XArray<CKParameter*> MessageParameterArrayType; MessageParameterArrayType m_Parameters; int GetNumParameters(){ return m_Parameters.Size() ; } void AddParameter(CKParameter *pin){ m_Parameters.PushBack(pin); } }; typedef std::vector<csMessage*>csMessagesArrayType; class CSManager : public CKBaseManager { public: //Ctor CSManager(CKContext* ctx); //Dtor ~CSManager(); // Initialization virtual CKERROR OnCKInit(); virtual CKERROR OnCKReset(); virtual CKERROR PreProcess(); ////////////////////////////////////////////////////////////////////////// // int HasMessages() const { return m_HasMessages; } void SetHasMessages(int val) { m_HasMessages = val; } ////////////////////////////////////////////////////////////////////////// csMessagesArrayType m_CSMessages; csMessagesArrayType& GetCSMessages() { return m_CSMessages; } void AddMessage(csMessage*msg); __inline int GetNumMessages(); __inline char *GetMessageName(int messageID); __inline int GetNumParameters(int messageID); __inline int GetMessageParameterType(int messageID,int parameterSubID); __inline int GetMessageValueInt(int messageID,int parameterSubID); __inline float GetMessageValueFloat(int messageID,int parameterSubID); __inline char* GetMessageValueStr(int messageID,int parameterSubID); __inline void CleanMessages(); __inline void DeleteMessage(int messageID); virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_OnCKInit| CKMANAGER_FUNC_OnCKReset; } private: protected: int m_HasMessages; }; ////////////////////////////////////////////////////////////////////////// char* CSManager::GetMessageName(int messageID) { XString result; if (GetNumMessages() && messageID < GetNumMessages() ) { csMessage* msg = GetCSMessages().at(messageID); return msg->GetName(); } return result.Str(); } ////////////////////////////////////////////////////////////////////////// int CSManager::GetNumMessages() { //MessageBox(NULL,"","",1); return GetCSMessages().size(); } ////////////////////////////////////////////////////////////////////////// int CSManager::GetNumParameters(int messageID) { int result = -1; if (messageID < GetNumMessages()) { csMessage* msg = GetCSMessages().at(messageID); return msg->GetNumParameters(); } return result; } ////////////////////////////////////////////////////////////////////////// int CSManager::GetMessageParameterType(int messageID,int parameterSubID) { int result = -1; if (GetNumParameters(messageID)) { if (parameterSubID < GetNumParameters(messageID)) { csMessage* msg = GetCSMessages().at(messageID); CKParameter *par = *msg->m_Parameters.At(parameterSubID); if (par) { CKParameterManager *pam = static_cast<CKParameterManager *>(m_Context->GetParameterManager()); CKParameterType pType = par->GetType(); using namespace vtTools; using namespace vtTools::Enums; SuperType sType = ParameterTools::GetVirtoolsSuperType(m_Context,pam->ParameterTypeToGuid(pType)); switch (sType) { case vtSTRING: result=1; break; case vtFLOAT: result=2; break; case vtINTEGER: result=3; break; default : return -1; } } } } return result; } ////////////////////////////////////////////////////////////////////////// int CSManager::GetMessageValueInt(int messageID,int parameterSubID) { assert(GetMessageParameterType(messageID,parameterSubID)==3 ); int result = -1; if (GetNumParameters(messageID)) { if (parameterSubID < GetNumParameters(messageID)) { csMessage* msg = GetCSMessages().at(messageID); CKParameter *par = *msg->m_Parameters.At(parameterSubID); if (par) { par->GetValue(&result); } } } return result; } ////////////////////////////////////////////////////////////////////////// float CSManager::GetMessageValueFloat(int messageID,int parameterSubID) { assert(GetMessageParameterType(messageID,parameterSubID)==2 ); float result = -1.0f; if (GetNumParameters(messageID)) { if (parameterSubID < GetNumParameters(messageID)) { csMessage* msg = GetCSMessages().at(messageID); CKParameter *par = *msg->m_Parameters.At(parameterSubID); if (par) { par->GetValue(&result); } } } return result; } ////////////////////////////////////////////////////////////////////////// char*CSManager::GetMessageValueStr(int messageID,int parameterSubID) { assert(GetMessageParameterType(messageID,parameterSubID)==1 ); char* result = NULL; if (GetNumParameters(messageID)) { if (parameterSubID < GetNumParameters(messageID)) { csMessage* msg = GetCSMessages().at(messageID); CKParameter *par = *msg->m_Parameters.At(parameterSubID); if (par) { VxScratch sbuffer(par->GetDataSize() +1 ); CKSTRING buffer = (CKSTRING)sbuffer.Mem(); par->GetStringValue(buffer); return buffer; } } } return result; } ////////////////////////////////////////////////////////////////////////// void CSManager::CleanMessages() { for (int i = 0 ; i < GetNumMessages() ; i++ ) { csMessage* msg = GetCSMessages().at(i); for (int j = 0 ; j < GetNumParameters(i) ; j++ ) { msg->m_Parameters[j]=NULL; } msg->m_Parameters.Clear(); } GetCSMessages().erase(GetCSMessages().begin(),GetCSMessages().end()); } ////////////////////////////////////////////////////////////////////////// void CSManager::DeleteMessage(int messageID) { if (messageID < GetNumMessages() ) { csMessage* msg = GetCSMessages().at(messageID); for (int j = 0 ; j < GetNumParameters(messageID) ; j++ ) { msg->m_Parameters[j]=NULL; } msg->m_Parameters.Clear(); GetCSMessages().erase(GetCSMessages().begin() + messageID); } } #endif <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pSleepingSettings.h" #include "pWorldSettings.h" #include "tinyxml.h" TiXmlDocument*pFactory::loadConfig(const char* filename) { // load and check file char Ini[MAX_PATH]; char drive[MAX_PATH]; char dir[MAX_PATH]; char szPath[MAX_PATH]; GetModuleFileName(NULL,szPath,_MAX_PATH); _splitpath(szPath, drive, dir, NULL, NULL ); sprintf(Ini,"%s%s%s",drive,dir,filename); XString name(Ini); name << '\0'; m_DefaultDocument = new TiXmlDocument(filename); m_DefaultDocument ->LoadFile(Ini); m_DefaultDocument ->Parse(Ini); if (m_DefaultDocument->Error()) { delete m_DefaultDocument; m_DefaultDocument = NULL; return NULL; } // get the ogreode element. TiXmlNode* node = m_DefaultDocument->FirstChild( "vtPhysics" ); if (!node) { return NULL; } return m_DefaultDocument; } int pFactory::reloadConfig(const char *fName) { if (! fName || !strlen(fName))return -1; ////////////////////////////////////////Load our physic default xml document : if (getDefaultDocument()) { delete m_DefaultDocument; m_DefaultDocument = NULL; xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted old default config"); } TiXmlDocument * defaultDoc = loadConfig(fName); if (!defaultDoc) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config : PhysicDefaults.xml: failed"); setDefaultDocument(NULL); }else { setDefaultDocument(defaultDoc); } return 1; } pRemoteDebuggerSettings pFactory::createDebuggerSettings(const TiXmlDocument * doc) { pRemoteDebuggerSettings result; result.enabled = -1; /************************************************************************/ /* try to load settings from xml : */ /************************************************************************/ if (doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "Debugger" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),"Default" ) ) { for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) { if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) { const TiXmlElement *sube = (const TiXmlElement*)node; double v; int i=0; ////////////////////////////////////////////////////////////////////////// int res = sube->QueryIntAttribute("enabled",&i); if (res == TIXML_SUCCESS) { result.enabled = i ; } res = sube->QueryIntAttribute("port",&i); if (res == TIXML_SUCCESS) { result.port = i ; } ////////////////////////////////////////////////////////////////////////// const char* host = sube->Attribute("host"); if (strlen(host)) { //strcpy(result.mHost,host); result.mHost = host; } return result; } } } } } } } } return result; } //************************************ // Method: GetFirstDocElement // FullName: vtODE::pFactory::GetFirstDocElement // Access: public // Returns: const TiXmlElement* // Qualifier: // Parameter: const TiXmlElement *root //************************************ const TiXmlElement*pFactory::getFirstDocElement(const TiXmlElement *root) { if (!strcmp(root->Value(), "vtPhysics")) { return root; } for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling()) { if (child->Type() == TiXmlNode::ELEMENT) { const TiXmlElement *res = getFirstDocElement(child->ToElement ()); if (res) return res; } } return 0; } //************************************ // Method: GetDocument // FullName: vtPhysics::pFactory::GetDocument // Access: public // Returns: TiXmlDocument* // Qualifier: // Parameter: XString filename //************************************ TiXmlDocument* pFactory::getDocument(XString filename) { XString fname(filename.Str()); if ( fname.Length() ) { XString fnameTest = ResolveFileName(fname.CStr()); if ( fnameTest.Length()) { TiXmlDocument* result = new TiXmlDocument(fnameTest.Str()); result->LoadFile(fnameTest.Str()); result->Parse(fnameTest.Str()); TiXmlNode* node = result->FirstChild( "vtPhysics" ); if (!node) { GetPMan()->m_Context->OutputToConsoleEx("PFactory : Couldn't load Document : %s",filename.Str()); return NULL; }else { return result; } } } return NULL; } //************************************ // Method: CreateWorldSettings // FullName: vtPhysics::pFactory::CreateWorldSettings // Access: public // Returns: pWorldSettings* // Qualifier: // Parameter: const char* nodeName // Parameter: const char* filename //************************************ /*! * \brief * Write brief comment for createWorldSettings here. * * \param nodeName * Description of parameter nodeName. * * \param filename * Description of parameter filename. * * \returns * Write description of return value here. * * \throws <exception class> * Description of criteria for throwing this exception. * * Write detailed description for createWorldSettings here. * * \remarks * Write remarks for createWorldSettings here. * * \see * Separate items with the '|' character. */ pWorldSettings*pFactory::createWorldSettings(const char* nodeName, const char* filename) { XString fname(filename); XString nName(nodeName); if ( nName.Length() && fname.Length() ) { pWorldSettings *result = NULL; TiXmlDocument * document = getDocument(fname); if (document) { result =createWorldSettings(nodeName,document); if ( result) { delete document; return result; } } if (document) { result = new pWorldSettings(); result->setGravity(VxVector(0,-9.81,0)); result->setSkinWith(0.02f); return result; } } return NULL; } //************************************ // Method: CreateWorldSettings // FullName: vtPhysics::pFactory::CreateWorldSettings // Access: public // Returns: pWorldSettings* // Qualifier: // Parameter: XString nodeName // Parameter: TiXmlDocument * doc //************************************ pWorldSettings* pFactory::createWorldSettings(const XString nodeName/* = */, const TiXmlDocument * doc /* = NULL */) { pWorldSettings *result = new pWorldSettings(); /************************************************************************/ /* try to load settings from xml : */ /************************************************************************/ if (doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "world" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),nodeName.CStr() ) ) { for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) { if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) { const TiXmlElement *sube = (const TiXmlElement*)node; double v; ////////////////////////////////////////////////////////////////////////// int res = sube->QueryDoubleAttribute("SkinWith",&v); if (res == TIXML_SUCCESS) { result->setSkinWith((float)v); } ////////////////////////////////////////////////////////////////////////// const char* grav = sube->Attribute("Gravity"); VxVector vec = _str2Vec(grav); result->setGravity(vec); } } } } } } } } //result->setGravity(VxVector(0,-9.81,0)); //result->setSkinWith(0.02f); return result; } //************************************ // Method: CreateSleepingSettings // FullName: vtPhysics::pFactory::CreateSleepingSettings // Access: public // Returns: pSleepingSettings* // Qualifier: // Parameter: const char* nodeName // Parameter: const char *filename //************************************ pSleepingSettings*pFactory::CreateSleepingSettings(const char* nodeName,const char *filename) { XString fname(filename); XString nName(nodeName); if ( nName.Length() && fname.Length() ) { TiXmlDocument * document = getDocument(fname); if (document) { pSleepingSettings *result = CreateSleepingSettings(nodeName,document); if ( result) { delete document; return result; } } } return NULL; } //************************************ // Method: CreateSleepingSettings // FullName: vtPhysics::pFactory::CreateSleepingSettings // Access: public // Returns: pSleepingSettings* // Qualifier: // Parameter: XString nodeName // Parameter: TiXmlDocument * doc //************************************ pSleepingSettings*pFactory::CreateSleepingSettings(XString nodeName/* = */, TiXmlDocument * doc /* = NULL */) { pSleepingSettings *result = new pSleepingSettings(); /************************************************************************/ /* try to load settings from xml : */ /************************************************************************/ if (nodeName.Length() && doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "sleepsettings" ) ) { const TiXmlElement *element = (const TiXmlElement*)child; if (element->Type() == TiXmlNode::ELEMENT ) { if(!strcmp( element->Attribute("name"),nodeName.CStr() ) ) { ////////////////////////////////////////////////////////////////////////// int v; int res = element->QueryIntAttribute("SleepSteps",&v); if (res == TIXML_SUCCESS) { result->SleepSteps(v); } ////////////////////////////////////////////////////////////////////////// res = element->QueryIntAttribute("AutoSleepFlag",&v); if (res == TIXML_SUCCESS) { result->AutoSleepFlag(v); } ////////////////////////////////////////////////////////////////////////// float vF; res = element->QueryFloatAttribute("AngularThresold",&vF); if (res == TIXML_SUCCESS) { result->AngularThresold(vF); } ////////////////////////////////////////////////////////////////////////// res = element->QueryFloatAttribute("LinearThresold",&vF); if (res == TIXML_SUCCESS) { result->LinearThresold(vF); } return result; } } } } } } return result; } XString pFactory::_getEnumDescription(const TiXmlDocument *doc, XString identifier) { if (!doc) { return XString(""); } XString result("None=0"); int counter = 1; /************************************************************************/ /* try to load settings from xml : */ /************************************************************************/ if ( doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), identifier.Str() ) ) { const TiXmlElement *sube = (const TiXmlElement*)child; const char* matName = NULL; matName = sube->Attribute("name"); if (matName && strlen(matName)) { if (result.Length()) { result << ","; } result << matName; result << "=" << counter; counter ++; } } } } } return result; } XString pFactory::_getBodyXMLInternalEnumeration(const TiXmlDocument * doc) { return _getEnumDescription(doc,"Body"); } XString pFactory::_getBodyXMLExternalEnumeration(const TiXmlDocument * doc) { return _getEnumDescription(doc,"Body"); } XString pFactory::_getMaterialsAsEnumeration(const TiXmlDocument * doc) { if (!doc) { return XString(""); } XString result("None=0"); int counter = 1; /************************************************************************/ /* try to load settings from xml : */ /************************************************************************/ if ( doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "material" ) ) { const TiXmlElement *sube = (const TiXmlElement*)child; const char* matName = NULL; matName = sube->Attribute("name"); if (matName && strlen(matName)) { if (result.Length()) { result << ","; } result << matName; result << "=" << counter; counter ++; } } } } } return result; } //************************************ // Method: _str2CombineMode // FullName: vtAgeia::pFactory::_str2CombineMode // Access: protected // Returns: int // Qualifier: // Parameter: const char*input //************************************ int pFactory::_str2CombineMode(const char*input) { int result = -1; if (!strlen(input)) { return result; } if (!strcmp(input,"AVERAGE")) { return 0; } if (!strcmp(input,"MIN")) { return 1; } if (!strcmp(input,"MAX")) { return 3; } if (!strcmp(input,"MULTIPLY")) { return 2; } return result; }<file_sep>#ifndef _VTLOG_TOOLS_H_ #define _VTLOG_TOOLS_H_ #include "xLogger.h" ////////////////////////////////////////////////////////////////////////// // // // We different output channels for logging,debugging or assertions : // + console // + log file // + std::err class CKContext; class CKGUID; namespace vtTools { class BehaviorInfoTools { public : static const char*getBuildingBlockName(CKContext *ctx,CKGUID* guid); }; } #define XL_BB_NAME beh->GetPrototype()->GetName() #define XL_BB_OWNER_SCRIPT beh->GetOwnerScript()->GetName() #define XL_BB_OWNER_OBJECT beh->GetOwner() ? beh->GetOwner()->GetName() : "none" #define XL_BB_SIGNATURE ("\n\tScript : %s\n\tBuildingBlock : %s \n\tObject :%s Error :") #define XLOG_FMT(msg,extro) msg##extro #define XLOG_MERGE(var, fmt) (#var##fmt ) #define XLOG_MERGE2(var,fmt) (var##fmt) #define XLOG_BB_INFO xLogger::xLogExtro(0,XL_BB_SIGNATURE,XL_BB_OWNER_SCRIPT,XL_BB_NAME,XL_BB_OWNER_OBJECT) #define VTERROR_STRING(F) sErrorStrings[F] #define bbError(F) XLOG_BB_INFO; \ Error(beh,F,BB_OP_ERROR,VTERROR_STRING(F),TRUE,BB_O_ERROR,TRUE) #define bbNoError(F) Error(beh,F,BB_OP_ERROR,VTERROR_STRING(F),FALSE,BB_O_ERROR,FALSE) #define bbErrorMesg(F) xLogger::xLog(ELOGERROR,E_BB,F); \ XLOG_BB_INFO; #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPJGroupBreakIteratorDecl(); CKERROR CreatePJGroupBreakIteratorProto(CKBehaviorPrototype **pproto); int PJGroupBreakIterator(const CKBehaviorContext& behcontext); CKERROR PJGroupBreakIteratorCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPJGroupBreakIteratorDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJGroupBreakIterator"); od->SetCategory("Physic/Joints"); od->SetDescription("Enables trigger output for multiple objects when a joint got broken"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7a64881,0x3aca7f0c)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePJGroupBreakIteratorProto); od->SetCompatibleClassId(CKCID_GROUP); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePJGroupBreakIteratorProto // FullName: CreatePJGroupBreakIteratorProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePJGroupBreakIteratorProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJGroupBreakIterator"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJGroupBreakIterator PJGroupBreakIterator is categorized in \ref Collision <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Triggers outputs if the body enters,stays or leaves another body .<br> See <A HREF="pBTriggerEvent.cmo">pBTriggerEvent.cmo</A> for example. <h3>Technical Information</h3> \image html PJGroupBreakIterator.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">No Event: </SPAN>Nothing touched. <BR> <SPAN CLASS="out">Entering: </SPAN>Body entered. <BR> <SPAN CLASS="out">Leaving: </SPAN>Body leaved. <BR> <SPAN CLASS="out">Stay: </SPAN>Inside body . <BR> <SPAN CLASS="pin">Target Group: </SPAN>The group which the bb outputs triggers for. <BR> <SPAN CLASS="pout">Touched Object: </SPAN>The touched body. <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3><br> <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForce().<br> */ //proto->DeclareInParameter("Extra Filter",VTF_TRIGGER,"0"); //proto->DeclareInParameter("Remove Event",CKPGUID_BOOL,"0"); proto->DeclareInput("In"); proto->DeclareInput("Next"); proto->DeclareOutput("None"); proto->DeclareOutput("Break"); proto->DeclareOutParameter("Body A",CKPGUID_3DENTITY,0); proto->DeclareOutParameter("Body B",CKPGUID_3DENTITY,0); proto->DeclareOutParameter("Impulse",CKPGUID_FLOAT,0); proto->DeclareLocalParameter("currentIndex", CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PJGroupBreakIterator); *pproto = proto; return CK_OK; } enum bOutputs { bbO_None, bbO_Break, }; enum bInputs { bbI_Init, bbI_Next, }; bool isInGroup2(CKGroup *src, CK3dEntity* testObject) { if (src && testObject) { for (int i = 0 ; i < src->GetObjectCount() ; i++ ) { CK3dEntity *ent = (CK3dEntity*)src->GetObject(i); if(ent) { if (ent==testObject) { return true; } } } } return false; } //************************************ // Method: PJGroupBreakIterator // FullName: PJGroupBreakIterator // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJGroupBreakIterator(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; ////////////////////////////////////////////////////////////////////////// //the object : CKGroup *target = (CKGroup *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; int nbOfEvents = GetPMan()->getJointFeedbackList().Size(); /************************************************************************/ /* handle init */ /************************************************************************/ if( beh->IsInputActive(bbI_Init) ) { beh->ActivateInput(bbI_Init,FALSE); if (nbOfEvents) { beh->ActivateInput(bbI_Next,TRUE); } } /************************************************************************/ /* handle trigger 'next' */ /************************************************************************/ if( beh->IsInputActive(bbI_Next) && nbOfEvents ) { beh->ActivateInput(bbI_Next,FALSE); beh->ActivateOutput(bbO_Break,FALSE); CK3dEntity *bodyAEnt =NULL; //static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(entry->mAEnt)); CK3dEntity *bodyBEnt = NULL;//static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(entry->mBEnt)); pBrokenJointEntry *entry = *GetPMan()->getJointFeedbackList().At(0); bodyAEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(entry->mAEnt)); bodyBEnt = static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(entry->mBEnt)); if (isInGroup2(target,bodyAEnt) || isInGroup2(target,bodyBEnt)) { beh->SetOutputParameterObject(0,bodyAEnt); beh->SetOutputParameterObject(1,bodyBEnt); SetOutputParameterValue<float>(beh,2,entry->impulse); GetPMan()->getJointFeedbackList().EraseAt(0); beh->ActivateOutput(bbO_Break); return 0; } } /************************************************************************/ /* terminate */ /************************************************************************/ beh->ActivateOutput(bbO_None); return 0; } //************************************ // Method: PJGroupBreakIteratorCB // FullName: PJGroupBreakIteratorCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PJGroupBreakIteratorCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>FIND_PATH(VTDEV40DIR NAMES dev.exe devr.exe PATHS [HKEY_LOCAL_MACHINE\\SOFTWARE\\Virtools\\Dev\\4.0;InstallPath] ) MARK_AS_ADVANCED(CMAKE_MAKE_PROGRAM) SET(VTDEV40 1) <file_sep>################################################################################ # activate_licenses.ini: Virtools Addons License Management # This file contains the list of the Virtools Addon Components. # When using the FlexLM Server Installation,if you # do not want an Virtools addon to be loaded into Virtools # (i.e. its flexlm license to be checked-out), # simply comment it with a '#' before the component's name. ################################################################################ # Virtools Physics Pack Components #VirtoolsPhysicPackFeature # Virtools VR Pack Components #VRK #VRD #VRV #VRC #VRPackBetaFeatures # Virtools Server Components #VirtoolsVBS_C_DevFeature #VirtoolsVBS_C_MultiuserFeature #VirtoolsVBS_C_PeerFeature #VirtoolsVBS_C_DownloadFeature #VirtoolsVBS_C_DatabaseFeature # Virtools XBOX Kit Components #VirtoolsXboxPackUIFeature #VirtoolsXboxPackBBFeature # Virtools AI Pack Components #VirtoolsAIPackFeature # Office/XE/PCS Components #VirtoolsPCSBB #VirtoolsXMLManager #VirtoolsFilesMgt #VirtoolsEncryption #VirtoolsCapture #VirtoolsDynamicInterface # Virtools Vector Graphics #VirtoolsVectorGraphics<file_sep>/******************************************************************** created: 2008/01/14 created: 14:1:2008 11:57 filename: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer\CustomPlayerDialog.h file path: x:\junctions\ProjectRoot\vdev\Sdk\Samples\Runtime\kamplayer file base: CustomPlayerDialog file ext: h author: mc007 purpose: Dialog for the Custom Player : - sets the values in the player.ini - contains an about tab - contains an error tab when necessary *********************************************************************/ #pragma once #include "CustomPlayerDialogGraphicPage.h" #include "CustomPlayerDialogErrorPage.h" #include "CustomPlayerDialogAboutPage.h" class CustomPlayerDialog : public CPropertySheet { public: DECLARE_DYNAMIC(CustomPlayerDialog) //standard constructor, not used ! //CustomPlayerDialog(CWnd* pWndParent = NULL); // explicit constructor, the only one we use !, an error string is passed here, when strlen(errorText) >0 then we have an error tab ! CustomPlayerDialog(CWnd* pWndParent = NULL,CString errorText=""); CustomPlayerDialogGraphicPage m_GraphicPage; CustomPlayerDialogErrorPage m_errorPage; CustomPlayerDialogAboutPage m_aboutPage; CString m_ErrorText; // Overrides : // //************************************ // Method: OnInitDialog // FullName: CustomPlayerDialog::OnInitDialog // Access: public // Returns: BOOL // Qualifier: // Summary : // - fills the configuration tab //************************************ virtual BOOL OnInitDialog(); // Message Handlers protected: //{{AFX_MSG(CModalShapePropSheet) afx_msg void OnApplyNow(); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: }; <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pVehicleMotor.h" #include "pVehicleGears.h" #include <xDebugTools.h> #include "NxArray.h" #include "pEngine.h" #include "pGearbox.h" #include "pDifferential.h" void pVehicle::AddDifferential(pDifferential *diff) { if(differentials==MAX_DIFFERENTIAL) { xWarning("RCar::AddDifferential(); maximum (%d) exceeded"); return; } differential[differentials]=diff; differentials++; } int pVehicle::doEngine(int flags,float dt) { if (engine && gearbox && driveLine ) { engine->SetInput(_cAcceleration); engine->CalcForces(); driveLine->CalcForces(); driveLine->CalcAccelerations(); driveLine->Integrate(); for(int i=0;i<differentials;i++) { differential[i]->Integrate(); } } return 0; } int pVehicle::initEngine(int flags) { driveLine=new pDriveLine(this); engine=new pEngine(this); engine->setToDefault(); gearbox=new pGearBox(this); gearbox->setToDefault(); driveLine->SetRoot(engine); engine->AddChild(gearbox); driveLine->SetGearBox(gearbox); differentials = 0 ; //---------------------------------------------------------------- // // setup differential , a single one for the first // pDifferential *d = new pDifferential(this); d->setToDefault(); pWheel *w1 = NULL;int w1Index = -1; pWheel *w2 = NULL;int w2Index = -1; findDifferentialWheels(w1Index,w2Index); w1 = (w1Index !=-1) ? _wheels[w1Index] : NULL; w2 = (w2Index !=-1) ? _wheels[w2Index] : NULL; if ( !w1||!w2 || ( !w1&&!w2 ) ) { xError("Couldn't find differential wheels"); return -1; } d->wheel[0]=w1; w1->setDifferential(d,0); d->wheel[1]=w2; w2->setDifferential(d,1); d->engine = engine; AddDifferential(d); // Add differentials and wheels to the driveline // Note this code does NOT work for 3 diffs, need more work for that. driveLine->SetDifferentials(differentials); if(differentials>0) { // Hook first diff to the gearbox gearbox->AddChild(differential[0]); } // Make the wheels children of the differentials // A diff with 2 diffs as children is not yet supported. for(int i=0;i<differentials;i++) { differential[i]->AddChild(differential[i]->wheel[0]); differential[i]->AddChild(differential[i]->wheel[1]); } driveLine->CalcPreClutchInertia(); gearbox->SetGear(0); return 0; } //---------------------------------------------------------------- // // // float pVehicle::getTorque(int component) { if (isValidEngine()) { return GetEngine()->GetTorque(); } return -1.0f; } bool pVehicle::isStalled() { if (isValidEngine()) { return GetEngine()->IsStalled(); } return false; } float pVehicle::getRPM() { if (isValidEngine()) { return GetEngine()->GetRPM(); } return -1.0f; } int pVehicle::getGear() { if (isValidEngine()) { return GetGearBox()->GetGear(); } } bool pVehicle::hasDifferential() { return differentials; } bool pVehicle::isValidEngine() { return engine && gearbox && driveLine && differentials; } <file_sep>#ifndef __PREREQUISITES_3TH_PARTY_H__ #define __PREREQUISITES_3TH_PARTY_H__ //################################################################ // // External : TINY XML // class TiXmlNode; class TiXmlDocument; class TiXmlElement; //################################################################ // // External NxuStream // #endif<file_sep> /******************************************************************** created: 2007/10/29 created: 29:10:2007 15:16 filename: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src\xSystem3D.h file path: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src file base: xSystem3D file ext: h author: mc007 purpose: *********************************************************************/ #include "base_macros.h" namespace xSystem3DHelper { #ifdef __cplusplus extern "C" { #endif API_EXPORT int xSGetAvailableTextureMem(); API_EXPORT float xSGetPhysicalMemoryInMB(); API_EXPORT int xSGetPhysicalGPUMemoryInMB(int device); API_EXPORT void xSSaveAllDxPropsToFile(char*file); API_EXPORT void xSGetDXVersion(char*& versionstring,int& minor); #ifdef __cplusplus } #endif }<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" CKObjectDeclaration *FillBehaviorDOSetUserValueDecl(); CKERROR CreateDOSetUserValueProto(CKBehaviorPrototype **); int DOSetUserValue(const CKBehaviorContext& behcontext); CKERROR DOSetUserValueCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorDOSetUserValueDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("DOSetUserValue"); od->SetDescription("Sets a user value on distributed object"); od->SetCategory("TNL/Distributed Objects"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x3b345be9,0x2851018b)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateDOSetUserValueProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateDOSetUserValueProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("DOSetUserValue"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Exit In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Object", CKPGUID_BEOBJECT, "test"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareSetting("Class", CKPGUID_STRING, "My3DClass"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETERINPUTS )); proto->SetFunction(DOSetUserValue); proto->SetBehaviorCallbackFct(DOSetUserValueCB); *pproto = proto; return CK_OK; } int DOSetUserValue(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; ////////////////////////////////////////////////////////////////////////// //connection id : int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *obj= (CK3dEntity*)beh->GetInputParameterObject(1); if (!obj) { beh->ActivateOutput(1); return 0; } ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { CKParameterOut *pout = beh->GetOutputParameter(1); XString errorMesg("distributed object creation failed,no network connection !"); pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(1); return 0; } //use objects name, if not specified : CKSTRING name= obj->GetName(); IDistributedObjects*doInterface = cin->getDistObjectInterface(); IDistributedClasses*cInterface = cin->getDistributedClassInterface(); XString className((CKSTRING) beh->GetLocalParameterReadDataPtr(0)); xDistributedClass *_class = cInterface->get(className.CStr()); ////////////////////////////////////////////////////////////////////////// //dist class ok ? if (_class==NULL) { beh->ActivateOutput(1); ctx->OutputToConsoleEx("Distributed Class doesn't exists : %s",className.CStr()); return 0; } const char * cNAme = _class->getClassName().getString(); int classType = _class->getEnitityType(); /*using namespace vtTools; using namespace vtTools::Enums;*/ int bcount = beh->GetInputParameterCount(); ////////////////////////////////////////////////////////////////////////// //we come in by input 0 : if (beh->IsInputActive(0)) { CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); for (int i = BEH_IN_INDEX_MIN_COUNT ; i < beh->GetInputParameterCount() ; i++ ) { beh->ActivateInput(0,FALSE); xDistributedObject *dobj = doInterface->getByEntityID(obj->GetID()); if (!dobj ) { beh->ActivateOutput(0); return 0; } int dOID = dobj->getUserID(); int clientID = cin->getConnection()->getUserID(); if (dOID !=clientID) { beh->ActivateOutput(0); return 0; } CKParameterIn *ciIn = beh->GetInputParameter(i); CKParameterType pType = ciIn->GetType(); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); xDistributedPropertyArrayType &props = *dobj->getDistributedPorperties(); int propID = _class->getInternalUserFieldIndex(i - BEH_IN_INDEX_MIN_COUNT); if (propID==-1 || propID > props.size() ) { beh->ActivateOutput(1); return 0; } xDistributedProperty *prop = props[propID]; if (prop) { xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); if (propInfo) { if (xDistTools::ValueTypeToSuperType(propInfo->mValueType) ==sType ) { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); switch(propInfo->mValueType) { case E_DC_PTYPE_3DVECTOR: { xDistributedPoint3F * dpoint3F = (xDistributedPoint3F*)prop; if (dpoint3F) { VxVector vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(xMath::getFrom(vvalue),currentTime); } break; } case E_DC_PTYPE_FLOAT: { xDistributedPoint1F * dpoint3F = (xDistributedPoint1F*)prop; if (dpoint3F) { float vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(vvalue,currentTime); } break; } case E_DC_PTYPE_2DVECTOR: { xDistributedPoint2F * dpoint3F = (xDistributedPoint2F*)prop; if (dpoint3F) { Vx2DVector vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(xMath::getFrom(vvalue),currentTime); } break; } case E_DC_PTYPE_QUATERNION: { xDistributedQuatF * dpoint3F = (xDistributedQuatF*)prop; if (dpoint3F) { VxQuaternion vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(xMath::getFrom(vvalue),currentTime); } break; } case E_DC_PTYPE_STRING: { xDistributedString * dpoint3F = (xDistributedString*)prop; if (dpoint3F) { CKParameter *pin = beh->GetInputParameter(i)->GetRealSource(); if (pin) { VxScratch sbuffer(256); CKSTRING buffer = (CKSTRING)sbuffer.Mem(); pin->GetStringValue(buffer); bool update = dpoint3F->updateValue(TNL::StringPtr(buffer),currentTime); } } break; } case E_DC_PTYPE_INT: { xDistributedInteger * dpoint3F = (xDistributedInteger*)prop; if (dpoint3F) { int vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(vvalue,currentTime); } break; } } } } } } beh->ActivateOutput(0); } ////////////////////////////////////////////////////////////////////////// //we come in by loop : return 0; } CKERROR DOSetUserValueCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>// Editor.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include "DistributedNetworkClassDialogEditor.h" #include "DistributedNetworkClassDialogEditorDlg.h" #include "DistributedNetworkClassDialogToolbarDlg.h" #include "DistributedNetworkClassDialogCallback.h" #ifdef _MFCDEBUGNEW #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif DistributedNetworkClassDialogEditorDlg* g_Editor = NULL; DistributedNetworkClassDialogToolbarDlg* g_Toolbar = NULL; //---------------------------------------- //The Plugin Info structure that must be filled for Virtools Dev to load effectively the plugin PluginInfo g_PluginInfo0; //Returns the number of plugin contained in this dll //this function must be exported (have a .def file with its name or use __declspec( dllexport ) int GetVirtoolsPluginInfoCount() { return 1; } //returns the ptr of the (index)th plugininfo structure of this dll //this function must be exported (have a .def file with its name or use __declspec( dllexport ) PluginInfo* GetVirtoolsPluginInfo(int index) { switch(index) { case 0: return &g_PluginInfo0; } return NULL; } // // Note! // // If this DLL is dynamically linked against the MFC // DLLs, any functions exported from this DLL which // call into MFC must have the AFX_MANAGE_STATE macro // added at the very beginning of the function. // // For example: // // extern "C" BOOL PASCAL EXPORT ExportedFunction() // { // AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // normal function body here // } // // It is very important that this macro appear in each // function, prior to any calls into MFC. This means that // it must appear as the first statement within the // function, even before any object variable declarations // as their constructors may generate calls into the MFC // DLL. // // Please see MFC Technical Notes 33 and 58 for additional // details. // ///////////////////////////////////////////////////////////////////////////// // DistributedNetworkClassDialogEditorApp BEGIN_MESSAGE_MAP(DistributedNetworkClassDialogEditorApp, CWinApp) //{{AFX_MSG_MAP(DistributedNetworkClassDialogEditorApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // DistributedNetworkClassDialogEditorApp construction DistributedNetworkClassDialogEditorApp::DistributedNetworkClassDialogEditorApp() { } ///////////////////////////////////////////////////////////////////////////// // The one and only DistributedNetworkClassDialogEditorApp object DistributedNetworkClassDialogEditorApp theApp; BOOL DistributedNetworkClassDialogEditorApp::InitInstance() { // TODO: Add your specialized code here and/or call the base class strcpy(g_PluginInfo0.m_Name,"DistributedObjects"); g_PluginInfo0.m_PluginType = PluginInfo::PT_EDITOR; g_PluginInfo0.m_PluginType = (PluginInfo::PLUGIN_TYPE)(g_PluginInfo0.m_PluginType | PluginInfo::PTF_RECEIVENOTIFICATION); g_PluginInfo0.m_PluginCallback = PluginCallback; //EDITOR { g_PluginInfo0.m_EditorInfo.m_Guid[1] = 0x5f116b1f; g_PluginInfo0.m_EditorInfo.m_Guid[2] = 0x7771a950; strcpy(g_PluginInfo0.m_EditorInfo.m_EditorName,"DistributedNetworkClassDialog"); g_PluginInfo0.m_EditorInfo.m_CreateEditorDlgFunc = fCreateEditorDlg; g_PluginInfo0.m_EditorInfo.m_CreateToolbarDlgFunc = fCreateToolbarDlg; g_PluginInfo0.m_EditorInfo.m_bUnique = 1; g_PluginInfo0.m_EditorInfo.m_bIndestructible = false; g_PluginInfo0.m_EditorInfo.m_bManageScrollbar = 0; g_PluginInfo0.m_EditorInfo.m_Width = 800; g_PluginInfo0.m_EditorInfo.m_Height = 800; g_PluginInfo0.m_EditorInfo.m_ToolbarHeight = 21; InitImageList(); g_PluginInfo0.m_EditorInfo.m_IconList = &m_ImageList; g_PluginInfo0.m_EditorInfo.m_IconIndex = 0; } return CWinApp::InitInstance(); } int DistributedNetworkClassDialogEditorApp::ExitInstance() { // TODO: Add your specialized code here and/or call the base class DeleteImageList(); return CWinApp::ExitInstance(); } void DistributedNetworkClassDialogEditorApp::InitImageList() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); m_ImageList.Create(16, 16, ILC_COLOR8|ILC_MASK, 0, 2); m_ImageList.Add(AfxGetApp()->LoadIcon(IDI_EDITORICON)); } void DistributedNetworkClassDialogEditorApp::DeleteImageList() { m_ImageList.DeleteImageList(); } <file_sep>// racer/differential.h #ifndef __RACER_DIFFERENTIAL_H #define __RACER_DIFFERENTIAL_H #include "vtPhysXBase.h" #include "pDriveline.h" class pVehicle; class pWheel; class pEngine; class MODULE_API pDifferential : public pDriveLineComp // A differential that has 3 parts; 1 'input', and 2 'outputs'. // Actually, all parts work together in deciding what happens. { public: enum Type { FREE=0, // Free/open differential VISCOUS=1, // Viscous locking differential SALISBURY=2 // Grand Prix Legends type clutch locking }; enum Flags { //LINEAR_LOCKING=1 // Viscous diff is of linear (expensive) type }; void setToDefault(); protected: // Definition (static input) int type; int flags; // Behavior flags float lockingCoeff; // Coefficient for viscous diff // Salisbury diff float powerAngle,coastAngle; // Ramp angles int clutches; // Number of clutches in use float clutchFactor; // Scaling the effect of the clutches float maxBiasRatioPower; // Resulting max. bias ratio float maxBiasRatioCoast; // Resulting max. bias ratio // Input // Torque on the 3 parts float torqueIn; float torqueOut[2]; float torqueBrakingOut[2]; // Potential braking torque // Inertia of objects float inertiaIn; float inertiaOut[2]; // Limited slip differentials add a locking torque float torqueLock; // State float velASymmetric; // Difference in wheel rotation speed float torqueBiasRatio; // Relative difference in reaction T's float torqueBiasRatioAbs; // Always >=1 int locked; // Mask of locked ends // Output // Resulting accelerations float accIn, accASymmetric; float accOut[2]; float rotVdriveShaft; // Speed of driveshaft (in) pVehicle *car; public: // Input pEngine *engine; // Output members pWheel2 *wheel[2]; public: pDifferential(pVehicle *car); ~pDifferential(); void Reset(); //---------------------------------------------------------------- // // experimental // void SetTorqueIn(float torque); float GetTorqueOut(int n); float GetBreakTorqueOut(int n); void SetInertiaIn(float inertia); void SetInertiaOut(int n,float inertia); //---------------------------------------------------------------- // // standard // float GetAccIn() const { return accIn; } float GetAccASymmetric() const { return accASymmetric; } float GetAccOut(int n) const { return accOut[n]; } // Salisbury info float GetTorqueBiasRatio(){ return torqueBiasRatio; } float GetMaxBiasRatioPower(){ return maxBiasRatioPower; } float GetMaxBiasRatioCoast(){ return maxBiasRatioCoast; } float GetPowerAngle(){ return powerAngle; } float GetCoastAngle(){ return powerAngle; } int GetClutches(){ return clutches; } float GetClutchFactor(){ return clutchFactor; } // Other info float GetRotationalVelocityIn() const { return rotVdriveShaft; } void Lock(int wheel); bool IsLocked(int wheel) { if(locked&(1<<wheel))return true; return false; } float CalcLockingTorque(); void CalcSingleDiffForces(float torqueIn,float inertiaIn); void CalcForces(); void Integrate(); }; #endif <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Mimic // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorMimicDecl(); CKERROR CreateMimicProto(CKBehaviorPrototype **pproto); int Mimic(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorMimicDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Mimic"); od->SetDescription("Makes a 3D Entity copy the motion of another one."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Object: </SPAN>object to copy.<BR> <SPAN CLASS=pin>Copy Position: </SPAN>TRUE means the object's position will be copied.<BR> <SPAN CLASS=pin>Position Speed: </SPAN>how fast the 3D Entity is to copy the object's position. The higher the percentage, the faster the 3D Entity will do this.<BR> <SPAN CLASS=pin>Copy Orientation: </SPAN>TRUE means that 3D Entity will copy the object's orientation.<BR> <SPAN CLASS=pin>Orientation Speed: </SPAN>how fast the 3D Entity is to copy the object's orientation. The higher the percentage, the faster the 3D Entity will do this.<BR> <SPAN CLASS=pin>Copy Scale: </SPAN>TRUE means that the 3D Entity will copy the object's scale.<BR> <SPAN CLASS=pin>Scale Speed: </SPAN>how fast the 3D Entity is to copy the object's orientation. The higher the percentage, the faster the 3D Entity will do this.<BR> <SPAN CLASS=pin>Hierarchy: </SPAN>if TRUE, then this behavior will also apply to the 3D Entity's children.<BR> <BR> <SPAN CLASS=setting>Time Based: </SPAN>If checked, this building block will be Time and not Frame Rate dependant. Making this building block Time dependant has the advantage that compositions will run at the same rate on all computer configurations.<BR> <BR> This behavior needs to be looped, if you want the object to constantly mimic the target.<BR> */ /* warning: - If you want no attenuation during motion, you shouldn't use the 'Time Based' setting.<BR> - As a time dependant looping process this building block has to be looped with a 1 frame link delay. The reason of this is because the internally laps of time used is always equal to the duration of one global process of the building blocks.<BR> This means, if you use 2 or 3 frame link delay, the process will become frame dependant.<BR> Note: if you don't use any '... Speed' value (ie 100), the above remark is useless (because movement is instantaneous).<BR> */ od->SetCategory("3D Transformations/Constraint"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x1df50d81,0x53cc788f)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateMimicProto); od->SetCompatibleClassId(CKCID_3DENTITY); return od; } CKERROR CreateMimicProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Mimic2"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Object", CKPGUID_3DENTITY ); proto->DeclareInParameter("Copy Position", CKPGUID_BOOL , "TRUE"); proto->DeclareInParameter("Position Speed", CKPGUID_PERCENTAGE, "100"); proto->DeclareInParameter("add vec", CKPGUID_VECTOR); proto->DeclareInParameter("Copy Orientation", CKPGUID_BOOL , "TRUE"); proto->DeclareInParameter("Orientation Speed", CKPGUID_PERCENTAGE, "100"); proto->DeclareInParameter("add quat", CKPGUID_QUATERNION); proto->DeclareInParameter("Copy Scale", CKPGUID_BOOL , "TRUE"); proto->DeclareInParameter("Scale Speed", CKPGUID_PERCENTAGE, "100"); proto->DeclareInParameter("Hierarchy", CKPGUID_BOOL , "TRUE"); proto->DeclareSetting("Time Based", CKPGUID_BOOL, "TRUE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(Mimic); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int Mimic(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); // Get the Owner Object CK3dEntity *Ent1 = (CK3dEntity *) beh->GetTarget(); if( !Ent1 ) return CKBR_OWNERERROR; // Get the Object CK3dEntity *Ent2 = (CK3dEntity *) beh->GetInputParameterObject(0); if(!Ent2) return CKBR_OK; // hierarchy CKBOOL k = TRUE; beh->GetInputParameterValue(7, &k); k=!k; CKBOOL b; float f = 0.0; ///////////////////////////////////////////////////////////////////////////////////// // Time Based Setting Version ? CKBOOL time_based=FALSE; beh->GetLocalParameterValue(0, &time_based); // Mimic Position beh->GetInputParameterValue(1,&b); if(b) { beh->GetInputParameterValue(2,&f); if( time_based ) { f *= behcontext.DeltaTime * 0.07f; if (f > 1.0f) f = 1.0f; } VxVector p1,p2; Ent1->GetPosition(&p1); Ent2->GetPosition(&p2); VxVector addV; beh->GetInputParameterValue(3,&addV); p1 +=addV; p1 += (p2-p1) * f; Ent1->SetPosition(&p1,NULL,k); } // Mimic orientation beh->GetInputParameterValue(4,&b); if(b) { beh->GetInputParameterValue(5,&f); if( time_based ) { f *= behcontext.DeltaTime * 0.07f; if (f > 1.0f) f = 1.0f; } VxQuaternion quatA, quatB, quatC,quatD; beh->GetInputParameterValue(6,&quatD); VxVector scale1, scale2, scaleUnit(1,1,1); Ent1->GetScale(&scale1); Ent1->GetQuaternion(&quatA); Ent2->GetQuaternion(&quatB); quatC=Slerp(f, quatA, quatB); Ent1->SetQuaternion(&quatC,NULL,k); Ent1->SetScale(&scale1); } // Mimic Scale beh->GetInputParameterValue(7,&b); if(b) { beh->GetInputParameterValue(8,&f); if( time_based ) { f *= behcontext.DeltaTime * 0.07f; if (f > 1.0f) f = 1.0f; } VxVector p1,p2; Ent1->GetScale(&p1); Ent2->GetScale(&p2); p1 += (p2-p1) * f; Ent1->SetScale(&p1,k); } return CKBR_OK; } <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "ISession.h" #include "xDistributedSessionClass.h" #include "xDistributedSession.h" #include "xDistributedClient.h" CKObjectDeclaration *FillBehaviorNSCreateObjectDecl(); CKERROR CreateNSCreateObjectProto(CKBehaviorPrototype **); int NSCreateObject(const CKBehaviorContext& behcontext); CKERROR NSCreateObjectCB(const CKBehaviorContext& behcontext); #include "xLogger.h" #include "vtLogTools.h" #define BEH_IN_INDEX_MIN_COUNT 5 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 typedef enum BB_INPAR { BB_IP_CONNECTION_ID, BB_IP_SESSION_TYPE, BB_IP_SESSION_NAME, BB_IP_MAX_PLAYERS, BB_IP_PASSWORD }; typedef enum BB_OT { BB_O_CREATED, BB_O_WAITING, BB_O_ERROR }; typedef enum BB_OP { BB_OP_SESSION_ID, BB_OP_MAX_PLAYERS, BB_OP_ERROR }; CKObjectDeclaration *FillBehaviorNSCreateObjectDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NSCreate"); od->SetDescription("Creates a session"); od->SetCategory("TNL/Sessions"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5efe2bbd,0x20525241)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNSCreateObjectProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateNSCreateObjectProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NSCreate"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Create"); proto->DeclareOutput("Created"); proto->DeclareOutput("Waiting For Answer"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Connection ID", CKPGUID_INT, "0"); proto->DeclareInParameter("Session Type", CKPGUID_INT, "-1"); proto->DeclareInParameter("Session Name", CKPGUID_STRING, "test"); proto->DeclareInParameter("Maximum Players", CKPGUID_INT, "3"); proto->DeclareInParameter("Password", CKPGUID_STRING, "<PASSWORD>"); proto->DeclareOutParameter("Session ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Maximum Players", CKPGUID_INT, "0"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "Ok"); proto->DeclareSetting("Long Session", CKPGUID_BOOL, "TRUE"); proto->DeclareLocalParameter("Creation Status", CKPGUID_INT, "0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETERINPUTS)); proto->SetFunction(NSCreateObject); proto->SetBehaviorCallbackFct(NSCreateObjectCB); *pproto = proto; return CK_OK; } int NSCreateObject(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; ////////////////////////////////////////////////////////////////////////// //connection id + session name : using namespace vtTools::BehaviorTools; int connectionID = GetInputParameterValue<int>(beh,0); CKSTRING sessionName = GetInputParameterValue<CKSTRING>(beh,BB_IP_SESSION_NAME); ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } ////////////////////////////////////////////////////////////////////////// //we create one session class per session object : ISession *sInterface = cin->getSessionInterface(); xDistributedSession *session = sInterface->get(sessionName); IDistributedClasses *cInterface = cin->getDistributedClassInterface(); int creationStatus = E_DO_CREATION_INCOMPLETE; beh->SetLocalParameterValue(1,&creationStatus); /************************************************************************/ /* */ /************************************************************************/ if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); bbNoError(E_NWE_OK); xDistributedClient *myClient = cin->getMyClient(); if (!myClient) { bbError(E_NWE_INTERN); return 0; } if (isFlagOn(myClient->getClientFlags(),E_CF_SESSION_JOINED )) { bbError(E_NWE_SESSION_ALREADY_JOINED); return 0; } //we attach the building blocks parameter CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); for (int i = BEH_IN_INDEX_MIN_COUNT ; i < beh->GetInputParameterCount() ; i++ ) { CKParameterIn *ciIn = beh->GetInputParameter(i); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(ciIn->GetType())); if (xDistTools::SuperTypeToValueType(sType) == E_DC_PTYPE_UNKNOWN) { bbError(E_NWE_INVALID_PARAMETER); return 0; } } /************************************************************************/ /* SESSION CLASS CREATION ! */ /************************************************************************/ //pickup data int sessionType = GetInputParameterValue<int>(beh,BB_IP_SESSION_TYPE); int MaxPlayers = GetInputParameterValue<int>(beh,BB_IP_MAX_PLAYERS); CKSTRING password = GetInputParameterValue<CKSTRING>(beh,BB_IP_PASSWORD); //we create a session class, according sessions name and attached user parameters xDistributedSessionClass*sessionClass = (xDistributedSessionClass*)cInterface->get(sessionName); if (!sessionClass) { sessionClass = (xDistributedSessionClass*)cInterface ->createClass(sessionName,E_DC_BTYPE_SESSION); //we enable all native properties : sessionClass->addProperty(E_DC_S_NP_MAX_USERS,E_PTYPE_RELIABLE); if (strlen(password)) sessionClass->addProperty(E_DC_S_NP_PASSWORD,E_PTYPE_RELIABLE); sessionClass->addProperty(E_DC_S_NP_TYPE,E_PTYPE_RELIABLE); sessionClass->addProperty(E_DC_S_NP_LOCKED,E_PTYPE_RELIABLE); sessionClass->addProperty(E_DC_S_NP_NUM_USERS,E_PTYPE_RELIABLE); for (int i = BEH_IN_INDEX_MIN_COUNT ; i < beh->GetInputParameterCount() ; i++ ) { CKParameterIn *ciIn = beh->GetInputParameter(i); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(ciIn->GetType())); sessionClass->addProperty(ciIn->GetName(),xDistTools::SuperTypeToValueType(sType),E_PTYPE_RELIABLE); } } //now we deploy it on the server : cInterface->deployClass(sessionClass); /************************************************************************/ /* SESSION OBJECT CREATION */ /************************************************************************/ //create a session via rpc : sInterface->create(sessionName,MaxPlayers,password,sessionType); return CKBR_ACTIVATENEXTFRAME; } /************************************************************************/ /* */ /************************************************************************/ if ( session && session->getSessionFlags().test(1<< E_SF_INCOMPLETE) && session->getUserID() == cin->getConnection()->getUserID() && !session->getSessionFlags().test( 1 << E_SF_POPULATE_PARAMETERS ) ) { session->getSessionFlags().set( 1 << E_SF_POPULATE_PARAMETERS ); ////////////////////////////////////////////////////////////////////////// int MaxPlayers = GetInputParameterValue<int>(beh,BB_IP_MAX_PLAYERS); xDistributedInteger *pMaxUsers = (xDistributedInteger *)session->getProperty(E_DC_S_NP_MAX_USERS); pMaxUsers->updateValue(MaxPlayers,0); pMaxUsers->setFlags(E_DP_NEEDS_SEND); ////////////////////////////////////////////////////////////////////////// CKSTRING password = GetInputParameterValue<CKSTRING>(beh,BB_IP_PASSWORD); xDistributedString *pPass= (xDistributedString*)session->getProperty(E_DC_S_NP_PASSWORD); if (pPass) { pPass->updateValue(xNString(password),0); pPass->setFlags(E_DP_NEEDS_SEND); } ////////////////////////////////////////////////////////////////////////// int sessionType = GetInputParameterValue<int>(beh,BB_IP_SESSION_TYPE); xDistributedInteger *pType= (xDistributedInteger *)session->getProperty(E_DC_S_NP_TYPE); pType->updateValue(sessionType,0); pType->setFlags(E_DP_NEEDS_SEND); ////////////////////////////////////////////////////////////////////////// int sessionLocked = 0; xDistributedInteger *pLocked= (xDistributedInteger *)session->getProperty(E_DC_S_NP_LOCKED); pLocked->updateValue(sessionLocked,0); pLocked->setFlags(E_DP_NEEDS_SEND); ////////////////////////////////////////////////////////////////////////// if ( beh->GetInputParameterCount() > BEH_IN_INDEX_MIN_COUNT ) { xDistributedSessionClass *_class = (xDistributedSessionClass*)session->getDistributedClass(); CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); for (int i = BEH_IN_INDEX_MIN_COUNT ; i < beh->GetInputParameterCount() ; i++ ) { CKParameterIn *ciIn = beh->GetInputParameter(i); CKParameterType pType = ciIn->GetType(); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); xDistributedPropertyArrayType &props = *session->getDistributedPorperties(); int propID = _class->getInternalUserFieldIndex(i - BEH_IN_INDEX_MIN_COUNT); int startIndex = _class->getFirstUserField(); int pSize = props.size(); if (propID==-1 || propID > props.size() ) { beh->ActivateOutput(1); return 0; } xDistributedProperty *prop = props[propID]; if (prop) { //we set the update flag in the prop by hand : xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); if (propInfo) { int dType = xDistTools::ValueTypeToSuperType(propInfo->mValueType); if (xDistTools::ValueTypeToSuperType(propInfo->mValueType) ==sType ) { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); switch(propInfo->mValueType) { case E_DC_PTYPE_3DVECTOR: { xDistributedPoint3F * dpoint3F = (xDistributedPoint3F*)prop; if (dpoint3F) { VxVector vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(xMath::getFrom(vvalue),currentTime); } break; } case E_DC_PTYPE_FLOAT: { xDistributedPoint1F * dpoint3F = (xDistributedPoint1F*)prop; if (dpoint3F) { float vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(vvalue,currentTime); } break; } case E_DC_PTYPE_2DVECTOR: { xDistributedPoint2F * dpoint3F = (xDistributedPoint2F*)prop; if (dpoint3F) { Vx2DVector vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(xMath::getFrom(vvalue),currentTime); } break; } case E_DC_PTYPE_QUATERNION: { xDistributedQuatF * dpoint3F = (xDistributedQuatF*)prop; if (dpoint3F) { VxQuaternion vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(xMath::getFrom(vvalue),currentTime); } break; } case E_DC_PTYPE_STRING: { xDistributedString * dpoint3F = (xDistributedString*)prop; if (dpoint3F) { CKParameter *pin = beh->GetInputParameter(i)->GetRealSource(); if (pin) { VxScratch sbuffer(256); CKSTRING buffer = (CKSTRING)sbuffer.Mem(); pin->GetStringValue(buffer); bool update = dpoint3F->updateValue(TNL::StringPtr(buffer),currentTime); } } break; } case E_DC_PTYPE_INT: { xDistributedInteger * dpoint3F = (xDistributedInteger*)prop; if (dpoint3F) { int vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = dpoint3F->updateValue(vvalue,currentTime); } break; } } prop->setFlags(E_DP_NEEDS_SEND); } } } } } } /************************************************************************/ /* SESSION COMPLETE */ /************************************************************************/ if ( session && session->getSessionFlags().test(1<< E_SF_COMPLETE ) && session->getUserID() == cin->getConnection()->getUserID() ) { session->getSessionFlags().set( 1 << E_SF_INCOMPLETE,false ); session->getSessionFlags().set( 1 << E_SF_POPULATE_PARAMETERS,false ); int sessionID = session->getSessionID(); beh->SetOutputParameterValue(BB_OP_SESSION_ID,&sessionID); beh->ActivateOutput(BB_O_CREATED); return 0; } beh->ActivateOutput(BB_O_WAITING); return CKBR_ACTIVATENEXTFRAME; } CKERROR NSCreateObjectCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; } <file_sep>//////////////////////////////////////////////////////////////////////////////// // // ARToolKitPlusManager // -------------------- // // Description: // This manager is used for setting the right camera projection matrix if // an ARToolKitPlus building block is used and the flag // ARTPlus(Multi)CorrectCamera is set. // // // Version 1.0 : First Release // // Known Bugs : None // // Copyright <NAME> <<EMAIL>>, University of Paderborn //////////////////////////////////////////////////////////////////////////////// #include "CKAll.h" #include "ARToolKitPlusManager.h" #include <ARToolKitPlus/TrackerSingleMarker.h> #include <ARToolKitPlus/TrackerMultiMarker.h> extern bool ARTPlusInitialized; extern bool ARTPlusCorrectCamera; extern bool ARTPlusMultiInitialized; extern bool ARTPlusMultiCorrectCamera; extern ARToolKitPlus::TrackerSingleMarker *tracker; extern ARToolKitPlus::TrackerMultiMarker *multiTracker; extern void argConvGlpara( float para[4][4], float gl_para[16] ); extern void argConvGlparaTrans( float para[4][4], float gl_para[16] ); VxMatrix projectMat; ARToolKitPlusManager::ARToolKitPlusManager(CKContext *Context) : CKBaseManager(Context, ARToolKitPlusManagerGUID, "ARToolKitPlusManager") { Context->RegisterNewManager(this); } ARToolKitPlusManager::~ARToolKitPlusManager() { } //--- Called before the composition is reset. CKERROR ARToolKitPlusManager::OnCKReset() { return CKERR_NOTIMPLEMENTED; } //--- Called when the process loop is started. CKERROR ARToolKitPlusManager::OnCKPlay() { return CKERR_NOTIMPLEMENTED; } //--- Called when the process loop is paused. CKERROR ARToolKitPlusManager::OnCKPause() { return CKERR_NOTIMPLEMENTED; } //--- Called before the rendering of the 3D objects. CKERROR ARToolKitPlusManager::OnPreRender(CKRenderContext* dev) { if( (ARTPlusInitialized && ARTPlusCorrectCamera) || (ARTPlusMultiInitialized && ARTPlusMultiCorrectCamera) ) { float* buffer = NULL; float gl_matirx[4][4]; if(tracker!=NULL && ARTPlusInitialized) { buffer = (float *)tracker->getProjectionMatrix(); } else if (multiTracker!=NULL && ARTPlusMultiInitialized) { buffer = (float *)multiTracker->getProjectionMatrix(); } else { return CKERR_NOTINITIALIZED; } argConvGlparaTrans(gl_matirx, buffer); gl_matirx[1][1] = -gl_matirx[1][1]; VxMatrix mat = VxMatrix(gl_matirx); projectMat = dev->GetProjectionTransformationMatrix(); dev->SetProjectionTransformationMatrix(mat); } return CK_OK; } //--- Called after the rendering of the 3D objects. CKERROR ARToolKitPlusManager::OnPostRender(CKRenderContext* dev) { if(ARTPlusInitialized && ARTPlusCorrectCamera) { dev->SetProjectionTransformationMatrix(projectMat); } return CK_OK; } <file_sep>SET DEV40DIR="x:/sdk/dev4" SET DEV41DIR="x:/sdk/dev41R" SET DEV5DIR="x:/sdk/dev5GA" xcopy /c /r /y %DEV40DIR%\BuildingBlocks\vtPhysX.dll ..\Release\Author\Dev40\BuildingBlocks\ xcopy /c /r /y %DEV40DIR%\vtPhysXLib.dll ..\Release\Author\Dev40\ xcopy /c /r /y %DEV41DIR%\BuildingBlocks\vtPhysX.dll ..\Release\Author\Dev41\BuildingBlocks\ xcopy /c /r /y %DEV41DIR%\vtPhysXLib.dll ..\Release\Author\Dev41\ xcopy /c /r /y %DEV5DIR%\BuildingBlocks\vtPhysX.dll ..\Release\Author\Dev5\BuildingBlocks\ xcopy /c /r /y %DEV5DIR%\vtPhysXLib.dll ..\Release\Author\Dev5\ svn ci -m "batch upload: release demo" ..\Release\Author\ cd ..\Tools CreateAuthorZip.bat <file_sep>#include "SoftMeshPSK.h" namespace SOFTBODY { Callback_LoadSoftMeshPSK gUserLoadSoftMeshPSK = 0; };<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPCIgnorePairDecl(); CKERROR CreatePCIgnorePairProto(CKBehaviorPrototype **pproto); int PCIgnorePair(const CKBehaviorContext& behcontext); CKERROR PCIgnorePairCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPCIgnorePairDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PCIgnorePair"); od->SetCategory("Physic/Collision"); od->SetDescription("Enables/Disables collision between two bodies."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x63f648f7,0x13c7097f)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePCIgnorePairProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePCIgnorePairProto // FullName: CreatePCIgnorePairProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePCIgnorePairProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCIgnorePair"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In0"); proto->DeclareOutput("Out0"); proto->SetBehaviorCallbackFct( PCIgnorePairCB ); proto->DeclareInParameter("Object A",CKPGUID_3DENTITY); proto->DeclareInParameter("Object B",CKPGUID_3DENTITY); proto->DeclareInParameter("Ignore",CKPGUID_BOOL,"0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PCIgnorePair); *pproto = proto; return CK_OK; } //************************************ // Method: PCIgnorePair // FullName: PCIgnorePair // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PCIgnorePair(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; CK3dEntity *targetA = (CK3dEntity *) beh->GetInputParameterObject(0); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(1); int ignore = GetInputParameterValue<int>(beh,2); ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorld(target); if(world){ world->cIgnorePair(targetA,targetB,ignore); } beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PCIgnorePairCB // FullName: PCIgnorePairCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PCIgnorePairCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #ifndef _TNL_NETINTERFACE_H_ #define _TNL_NETINTERFACE_H_ #ifndef _TNL_VECTOR_H_ #include "tnlVector.h" #endif #ifndef _TNL_NETBASE_H_ #include "tnlNetBase.h" #endif #include "tnlClientPuzzle.h" #ifndef _TNL_NETOBJECT_H_ #include "tnlNetObject.h" #endif #ifndef _TNL_NETCONNECTION_H_ #include "tnlNetConnection.h" #endif namespace TNL { class AsymmetricKey; class Certificate; struct ConnectionParameters; /// NetInterface class. /// /// Manages all valid and pending notify protocol connections for a port/IP. If you are /// providing multiple services or servicing multiple networks, you may have more than /// one NetInterface. /// /// <b>Connection handshaking basic overview:</b> /// /// TNL does a two phase connect handshake to prevent a several types of /// Denial-of-Service (DoS) attacks. /// /// The initiator of the connection (client) starts the connection by sending /// a unique random nonce (number, used once) value to the server as part of /// the ConnectChallengeRequest packet. /// C->S: ConnectChallengeRequest, Nc /// /// The server responds to the ConnectChallengeRequest with a "Client Puzzle" /// that has the property that verifying a solution to the puzzle is computationally /// simple, but can be of a specified computational, brute-force difficulty to /// compute the solution itself. The client puzzle is of the form: /// secureHash(Ic, Nc, Ns, X) = Y >> k, where Ic is the identity of the client, /// and X is a value computed by the client such that the high k bits of the value /// y are all zero. The client identity is computed by the server as a partial hash /// of the client's IP address and port and some random data on the server. /// its current nonce (Ns), Nc, k, and the server's authentication certificate. /// S->C: ConnectChallengeResponse, Nc, Ns, Ic, Cs /// /// The client, upon receipt of the ConnectChallengeResponse, validates the packet /// sent by the server and computes a solution to the puzzle the server sent. If /// the connection is to be authenticated, the client can also validate the server's /// certificate (if it's been signed by a Certificate Authority), and then generates /// a shared secret from the client's key pair and the server's public key. The client /// response to the server consists of: /// C->S: ConnectRequest, Nc, Ns, X, Cc, sharedSecret(key1, sequence1, NetConnectionClass, class-specific sendData) /// /// The server then can validation the solution to the puzzle the client submitted, along /// with the client identity (Ic). /// Until this point the server has allocated no memory for the client and has /// verified that the client is sending from a valid IP address, and that the client /// has done some amount of work to prove its willingness to start a connection. /// As the server load increases, the server may choose to increase the difficulty (k) of /// the client puzzle, thereby making a resource depletion DoS attack successively more /// difficult to launch. /// /// If the server accepts the connection, it sends a connect accept packet that is /// encrypted and hashed using the shared secret. The contents of the packet are /// another sequence number (sequence2) and another key (key2). The sequence numbers /// are the initial send and receive sequence numbers for the connection, and the /// key2 value becomes the IV of the symmetric cipher. The connection subclass is /// also allowed to write any connection specific data into this packet. /// /// This system can operate in one of 3 ways: unencrypted, encrypted key exchange (ECDH), /// or encrypted key exchange with server and/or client signed certificates (ECDSA). /// /// The unencrypted communication mode is NOT secure. Packets en route between hosts /// can be modified without detection by the hosts at either end. Connections using /// the secure key exchange are still vulnerable to Man-in-the-middle attacks, but still /// much more secure than the unencrypted channels. Using certificate(s) signed by a /// trusted certificate authority (CA), makes the communications channel as securely /// trusted as the trust in the CA. /// /// <b>Arranged Connection handshaking:</b> /// /// NetInterface can also facilitate "arranged" connections. Arranged connections are /// necessary when both parties to the connection are behind firewalls or NAT routers. /// Suppose there are two clients, A and B that want to esablish a direct connection with /// one another. If A and B are both logged into some common server S, then S can send /// A and B the public (NAT'd) address, as well as the IP addresses each client detects /// for itself. /// /// A and B then both send "Punch" packets to the known possible addresses of each other. /// The punch packet client A sends enables the punch packets client B sends to be /// delivered through the router or firewall since it will appear as though it is a service /// response to A's initial packet. /// /// Upon receipt of the Punch packet by the "initiator" /// of the connection, an ArrangedConnectRequest packet is sent. /// if the non-initiator of the connection gets an ArrangedPunch /// packet, it simply sends another Punch packet to the /// remote host, but narrows down its Address range to the address /// it received the packet from. /// The ArrangedPunch packet from the intiator contains the nonce /// for the non-initiator, and the nonce for the initiator encrypted /// with the shared secret. /// The ArrangedPunch packet for the receiver of the connection /// contains all that, plus the public key/keysize or the certificate /// of the receiver. class NetInterface : public Object { friend class NetConnection; public: /// PacketType is encoded as the first byte of each packet. /// /// Subclasses of NetInterface can add custom, non-connected data /// packet types starting at FirstValidInfoPacketId, and overriding /// handleInfoPacket to process them. /// /// Packets that arrive with the high bit of the first byte set /// (i.e. the first unsigned byte is greater than 127), are /// assumed to be connected protocol packets, and are dispatched to /// the appropriate connection for further processing. enum PacketType { ConnectChallengeRequest = 0, ///< Initial packet of the two-phase connect process ConnectChallengeResponse = 1, ///< Response packet to the ChallengeRequest containing client identity, a client puzzle, and possibly the server's public key. ConnectRequest = 2, ///< A connect request packet, including all puzzle solution data and connection initiation data. ConnectReject = 3, ///< A packet sent to notify a host that a ConnectRequest was rejected. ConnectAccept = 4, ///< A packet sent to notify a host that a connection was accepted. Disconnect = 5, ///< A packet sent to notify a host that the specified connection has terminated. Punch = 6, ///< A packet sent in order to create a hole in a firewall or NAT so packets from the remote host can be received. ArrangedConnectRequest = 7, ///< A connection request for an "arranged" connection. FirstValidInfoPacketId = 8, ///< The first valid ID for a NetInterface subclass's info packets. BroadcastMessage = 9, ///< A connection request for an "arranged" connection. }; protected: Vector<NetConnection *> mConnectionList; ///< List of all the connections that are in a connected state on this NetInterface. Vector<NetConnection *> mConnectionHashTable; ///< A resizable hash table for all connected connections. This is a flat hash table (no buckets). Vector<NetConnection *> mPendingConnections; ///< List of connections that are in the startup state, where the remote host has not fully /// validated the connection. RefPtr<AsymmetricKey> mPrivateKey; ///< The private key used by this NetInterface for secure key exchange. RefPtr<Certificate> mCertificate; ///< A certificate, signed by some Certificate Authority, to authenticate this host. ClientPuzzleManager mPuzzleManager; ///< The object that tracks the current client puzzle difficulty, current puzzle and solutions for this NetInterface. /// @name NetInterfaceSocket Socket /// /// State regarding the socket this NetInterface controls. /// /// @{ /// Socket mSocket; ///< Network socket this NetInterface communicates over. /// @} U32 mCurrentTime; ///< Current time tracked by this NetInterface. bool mRequiresKeyExchange; ///< True if all connections outgoing and incoming require key exchange. U32 mLastTimeoutCheckTime; ///< Last time all the active connections were checked for timeouts. U8 mRandomHashData[12]; ///< Data that gets hashed with connect challenge requests to prevent connection spoofing. bool mAllowConnections; ///< Set if this NetInterface allows connections from remote instances. /// Structure used to track packets that are delayed in sending for simulating a high-latency connection. /// /// The DelaySendPacket is allocated as sizeof(DelaySendPacket) + packetSize; struct DelaySendPacket { DelaySendPacket *nextPacket; ///< The next packet in the list of delayed packets. Address remoteAddress; ///< The address to send this packet to. U32 sendTime; ///< Time when we should send the packet. U32 packetSize; ///< Size, in bytes, of the packet data. U8 packetData[1]; ///< Packet data. }; DelaySendPacket *mSendPacketList; ///< List of delayed packets pending to send. enum NetInterfaceConstants { ChallengeRetryCount = 4, ///< Number of times to send connect challenge requests before giving up. ChallengeRetryTime = 2500, ///< Timeout interval in milliseconds before retrying connect challenge. ConnectRetryCount = 4, ///< Number of times to send connect requests before giving up. ConnectRetryTime = 2500, ///< Timeout interval in milliseconds before retrying connect request. PunchRetryCount = 6, ///< Number of times to send groups of firewall punch packets before giving up. PunchRetryTime = 2500, ///< Timeout interval in milliseconds before retrying punch sends. TimeoutCheckInterval = 1500, ///< Interval in milliseconds between checking for connection timeouts. PuzzleSolutionTimeout = 30000, ///< If the server gives us a puzzle that takes more than 30 seconds, time out. }; /// Computes an identity token for the connecting client based on the address of the client and the /// client's unique nonce value. U32 computeClientIdentityToken(const Address &theAddress, const Nonce &theNonce); /// Finds a connection instance that this NetInterface has initiated. NetConnection *findPendingConnection(const Address &address); /// Adds a connection the list of pending connections. void addPendingConnection(NetConnection *conn); /// Removes a connection from the list of pending connections. void removePendingConnection(NetConnection *conn); /// Finds a connection by address from the pending list and removes it. void findAndRemovePendingConnection(const Address &address); /// Adds a connection to the internal connection list. void addConnection(NetConnection *connection); /// Remove a connection from the list. void removeConnection(NetConnection *connection); /// Begins the connection handshaking process for a connection. Called from NetConnection::connect() void startConnection(NetConnection *conn); /// Sends a connect challenge request on behalf of the connection to the remote host. void sendConnectChallengeRequest(NetConnection *conn); /// Handles a connect challenge request by replying to the requestor of a connection with a /// unique token for that connection, as well as (possibly) a client puzzle (for DoS prevention), /// or this NetInterface's public key. void handleConnectChallengeRequest(const Address &addr, BitStream *stream); /// Sends a connect challenge request to the specified address. This can happen as a result /// of receiving a connect challenge request, or during an "arranged" connection for the non-initiator /// of the connection. void sendConnectChallengeResponse(const Address &addr, Nonce &clientNonce, bool wantsKeyExchange, bool wantsCertificate); /// Processes a ConnectChallengeResponse, by issueing a connect request if it was for /// a connection this NetInterface has pending. void handleConnectChallengeResponse(const Address &address, BitStream *stream); /// Continues computation of the solution of a client puzzle, and issues a connect request /// when the solution is found. void continuePuzzleSolution(NetConnection *conn); /// Sends a connect request on behalf of a pending connection. void sendConnectRequest(NetConnection *conn); /// Handles a connection request from a remote host. /// /// This will verify the validity of the connection token, as well as any solution /// to a client puzzle this NetInterface sent to the remote host. If those tests /// pass, it will construct a local connection instance to handle the rest of the /// connection negotiation. void handleConnectRequest(const Address &address, BitStream *stream); /// Sends a connect accept packet to acknowledge the successful acceptance of a connect request. void sendConnectAccept(NetConnection *conn); /// Handles a connect accept packet, putting the connection associated with the /// remote host (if there is one) into an active state. void handleConnectAccept(const Address &address, BitStream *stream); /// Sends a connect rejection to a valid connect request in response to possible error /// conditions (server full, wrong password, etc). void sendConnectReject(ConnectionParameters *theParams, const Address &theAddress, const char *reason); /// Handles a connect rejection packet by notifying the connection object /// that the connection was rejected. void handleConnectReject(const Address &address, BitStream *stream); /// Begins the connection handshaking process for an arranged connection. void startArrangedConnection(NetConnection *conn); /// Sends Punch packets to each address in the possible connection address list. void sendPunchPackets(NetConnection *conn); /// Handles an incoming Punch packet from a remote host. void handlePunch(const Address &theAddress, BitStream *stream); /// Sends an arranged connect request. void sendArrangedConnectRequest(NetConnection *conn); /// Handles an incoming connect request from an arranged connection. void handleArrangedConnectRequest(const Address &theAddress, BitStream *stream); /// Handles an incoming connect request from an arranged connection. void handleBroadcastMessage(const Address &theAddress, BitStream *stream); /// Dispatches a disconnect packet for a specified connection. void handleDisconnect(const Address &address, BitStream *stream); /// Handles an error reported while reading a packet from this remote connection. void handleConnectionError(NetConnection *theConnection, const char *errorString); /// Disconnects the given connection and removes it from the NetInterface void disconnect(NetConnection *conn, NetConnection::TerminationReason reason, const char *reasonString); /// @} public: /// @param bindAddress Local network address to bind this interface to. NetInterface(const Address &bindAddress); ~NetInterface(); /// Returns the address of the first network interface in the list that the socket on this NetInterface is bound to. Address getFirstBoundInterfaceAddress(); /// Sets the private key this NetInterface will use for authentication and key exchange void setPrivateKey(AsymmetricKey *theKey); /// Requires that all connections use encryption and key exchange void setRequiresKeyExchange(bool requires) { mRequiresKeyExchange = requires; } /// Sets the public certificate that validates the private key and stores /// information about this host. If no certificate is set, this interface can /// still initiate and accept encrypted connections, but they will be vulnerable to /// man in the middle attacks, unless the remote host can validate the public key /// in another way. void setCertificate(Certificate *theCertificate); /// Returns whether or not this NetInterface allows connections from remote hosts. bool doesAllowConnections() { return mAllowConnections; } /// Sets whether or not this NetInterface allows connections from remote hosts. void setAllowsConnections(bool conn) { mAllowConnections = conn; } /// Returns the Socket associated with this NetInterface Socket &getSocket() { return mSocket; } /// Sends a packet to the remote address over this interface's socket. NetError sendto(const Address &address, BitStream *stream); /// Sends a packet to the remote address after millisecondDelay time has elapsed. /// /// This is used to simulate network latency on a LAN or single computer. void sendtoDelayed(const Address &address, BitStream *stream, U32 millisecondDelay); /// Dispatch function for processing all network packets through this NetInterface. void checkIncomingPackets(); /// Processes a single packet, and dispatches either to handleInfoPacket or to /// the NetConnection associated with the remote address. virtual void processPacket(const Address &address, BitStream *packetStream); /// Handles all packets that don't fall into the category of connection handshake or game data. virtual void handleInfoPacket(const Address &address, U8 packetType, BitStream *stream); /// Checks all connections on this interface for packet sends, and for timeouts and all valid /// and pending connections. void processConnections(); /// Returns the list of connections on this NetInterface. Vector<NetConnection *> &getConnectionList() { return mConnectionList; } /// looks up a connected connection on this NetInterface NetConnection *findConnection(const Address &remoteAddress); /// returns the current process time for this NetInterface U32 getCurrentTime() { return mCurrentTime; } }; }; #endif <file_sep>#include "CKAll.h" CKObjectDeclaration *FillBehaviorGetTime2Decl(); CKERROR CreateGetTime2Proto(CKBehaviorPrototype **pproto); int GetTime2(const CKBehaviorContext& behcontext); /************************************************************************/ /* */ /************************************************************************/ CKObjectDeclaration *FillBehaviorGetTime2Decl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("GetTime"); od->SetDescription("Logics/Tools"); od->SetCategory("a"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x33ce78ad,0x6e4a5d37)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGetTime2Proto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateGetTime2Proto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("GetTime"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Create Zip File"); proto->DeclareOutput("Zip File created"); proto->DeclareOutParameter("Hour", CKPGUID_INT); proto->DeclareOutParameter("Minutes", CKPGUID_INT); proto->DeclareOutParameter("Seconds", CKPGUID_INT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(GetTime2); *pproto = proto; return CK_OK; } int GetTime2(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; //int hour,minute,second; //SYSTEMTIME lpSystemTime; /* GetSystemTime( &lpSystemTime ); hour = lpSystemTime.wHour; minute = lpSystemTime.wMinute; second = lpSystemTime.wSecond; beh->SetOutputParameterValue(0,&hour); beh->SetOutputParameterValue(1,&minute); beh->SetOutputParameterValue(2,&second); beh->ActivateOutput(0); */ return 0; } <file_sep>pFactory pf = getPFactory(); pObjectDescr descr; descr.flags = BF_Moving + BF_Gravity + BF_Collision; descr.density = 1.0f; descr.hullType = HT_Box; descr.shapeOffset = pivotOffset; pRigidBody body = pf.createBody(entity,descr); <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedSession.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "ISession.h" #include "IMessages.h" #include "xLogger.h" #include "vtLogTools.h" #include "xMessageTypes.h" CKObjectDeclaration *FillBehaviorNMSendDecl(); CKERROR CreateNMSendProto(CKBehaviorPrototype **); int NMSend(const CKBehaviorContext& behcontext); CKERROR NMSendCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 0 #define BEH_OUT_MAX_COUNT 1 typedef enum BB_IT { BB_IT_IN, }; typedef enum BB_INPAR { BB_IP_CONNECTION_ID, BB_IP_MESSAGE, }; typedef enum BB_OT { BB_O_OUT, BB_O_ERROR, }; typedef enum BB_OP { BB_OP_ERROR, }; CKObjectDeclaration *FillBehaviorNMSendDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NMSend"); od->SetDescription("Sends a message over network"); od->SetCategory("TNL/Message"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x51a072f,0x6aec1386)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNMSendProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } CKERROR CreateNMSendProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NMSend"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareOutput("Error"); proto->DeclareInParameter("Message", CKPGUID_MESSAGE, "OnClick"); proto->DeclareInParameter("Target User ID", CKPGUID_INT, "0"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR); proto->DeclareSetting("Ignore Session Master", CKPGUID_BOOL, "FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETERINPUTS )); proto->SetFunction(NMSend); proto->SetBehaviorCallbackFct(NMSendCB); *pproto = proto; return CK_OK; } int NMSend(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); using namespace vtTools::BehaviorTools; bbNoError(E_NWE_OK); beh->ActivateInput(0,FALSE); int Msg=-1; beh->GetInputParameterValue(0,&Msg); XString msgType(mm->GetMessageTypeName(Msg)); xNString mName = msgType.CStr(); int targetID=0; beh->GetInputParameterValue(1,&targetID); int ignoreSessionMaster = 0; beh->GetLocalParameterValue(0,&ignoreSessionMaster); bbNoError(E_NWE_OK); //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } if (!cin->getMyClient()) { bbError(E_NWE_INTERN); return 0; } ISession *sInterface = cin->getSessionInterface(); IMessages *mInterface = cin->getMessagesInterface(); xDistributedClient *myClient = cin->getMyClient(); if (!myClient) { bbError(E_NWE_INTERN); return 0; } xDistributedSession *session = sInterface->get(myClient->getSessionID()); if (!session) { bbError(E_NWE_NO_SUCH_SESSION); return 0; } if (!isFlagOn(myClient->getClientFlags(),E_CF_SESSION_JOINED)) { bbError(E_NWE_NO_SESSION); return 0; } if (session->getUserID() == myClient->getUserID() && session->getNumUsers()==1 ) { bbError(E_NWE_INTERN); return 0; } int bcount = beh->GetInputParameterCount(); int srcId = cin->getConnection()->getUserID(); xMessage *msg = new xMessage(); msg->setName(mName); msg->setSrcUser( myClient->getServerID() ); msg->setIgnoreSessionMaster(ignoreSessionMaster); msg->setDstUser(targetID); if (targetID !=-1) { IDistributedObjects *doInterface = cin->getDistObjectInterface(); xDistributedClient *dstClient = static_cast<xDistributedClient*>(doInterface->getByUserID(targetID,E_DC_BTYPE_CLIENT)); if (dstClient) { if (dstClient->getUserID() == myClient->getUserID()) { bbError(E_NWE_INTERN); delete msg; return 0; } msg->setDstUser(dstClient->getUserID()); }else{ bbError(E_NWE_NO_SUCH_USER); delete msg; return 0; } } for (int i = BEH_IN_INDEX_MIN_COUNT ; i < beh->GetInputParameterCount() ; i++ ) { CKParameterIn *ciIn = beh->GetInputParameter(i); CKParameterType pType = ciIn->GetType(); int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType)); const char *pname = pam->ParameterTypeToName(pType); xDistributedPropertyInfo *dInfo = new xDistributedPropertyInfo( ciIn->GetName() , xDistTools::SuperTypeToValueType(sType) , -1 ,E_PTYPE_RELIABLE); switch (sType) { case vtSTRING: { CKParameter *pin = beh->GetInputParameter(i)->GetRealSource(); if (pin) { xDistributedString *prop = new xDistributedString(dInfo,30,3000); VxScratch sbuffer(256); CKSTRING buffer = (CKSTRING)sbuffer.Mem(); pin->GetStringValue(buffer); prop->updateValue(TNL::StringPtr(buffer),0); msg->getParameters().push_back(prop); prop->setFlags(E_DP_NEEDS_SEND); } break; } case vtFLOAT: { xDistributedPoint1F * prop = new xDistributedPoint1F(dInfo,30,3000); if (prop) { float vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = prop->updateValue(vvalue,0); msg->getParameters().push_back(prop); prop->setFlags(E_DP_NEEDS_SEND); } break; } case vtINTEGER: { xDistributedInteger * prop = new xDistributedInteger(dInfo,30,3000); if (prop) { int vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = prop->updateValue(vvalue,0); msg->getParameters().push_back(prop); prop->setFlags(E_DP_NEEDS_SEND); } break; } case vtVECTOR: { xDistributedPoint3F * prop = new xDistributedPoint3F(dInfo,30,3000); if (prop) { VxVector vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = prop->updateValue(xMath::getFrom(vvalue),0); msg->getParameters().push_back(prop); prop->setFlags(E_DP_NEEDS_SEND); } break; } case vtVECTOR2D: { xDistributedPoint2F * prop = new xDistributedPoint2F(dInfo,30,3000); if (prop) { Vx2DVector vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = prop->updateValue(xMath::getFrom(vvalue),0); msg->getParameters().push_back(prop); prop->setFlags(E_DP_NEEDS_SEND); } break; } case vtQUATERNION: { xDistributedQuatF * prop = new xDistributedQuatF(dInfo,30,3000); if (prop) { VxQuaternion vvalue; beh->GetInputParameterValue(i,&vvalue); bool update = prop->updateValue(xMath::getFrom(vvalue),0); msg->getParameters().push_back(prop); prop->setFlags(E_DP_NEEDS_SEND); } break; } case vtUNKNOWN: { bbError(E_NWE_INVALID_PARAMETER); break; } default : bbError(E_NWE_INVALID_PARAMETER); return CKBR_BEHAVIORERROR; } } enableFlag(msg->getFlags(),E_MF_OUTGOING); mInterface->addMessage(msg); beh->ActivateOutput(0); return CKBR_OK; } CKERROR NMSendCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #ifndef _TNL_TYPES_H_ #define _TNL_TYPES_H_ //-------------------------------------- // Enable Asserts in all debug builds #if defined(TNL_DEBUG) #ifndef TNL_ENABLE_ASSERTS #define TNL_ENABLE_ASSERTS #endif #endif #include <stdlib.h> //inline void* operator new(size_t size, void* ptr) { return ptr; } #include <new> namespace TNL { #ifndef NULL # define NULL 0 #endif //------------------------------------------------------------------------------ //-------------------------------------- Basic Types... /// @defgroup BasicTypes Basic Compiler Independent Types /// These types are defined so that we know exactly what we have, sign and bit wise. /// /// The number represents number of bits, the letters represent <b>S</b>igned, /// <b>U</b>nsigned, or <b>F</b>loating point (implicitly signed). /// @{ typedef signed char S8; ///< Compiler independent signed char (8bit integer). typedef unsigned char U8; ///< Compiler independent unsigned char (8bit integer). typedef signed short S16; ///< Compiler independent signed 16-bit short integer. typedef unsigned short U16; ///< Compiler independent unsigned 16-bit short integer. typedef signed int S32; ///< Compiler independent signed 32-bit integer. typedef unsigned int U32; ///< Compiler independent unsigned 32-bit integer. typedef float F32; ///< Compiler independent 32-bit float. typedef double F64; ///< Compiler independent 64-bit float. /// @} /// NetType serves as a base class for all bit-compressed versions of /// the base types that can be transmitted using TNL's RPC mechanism. /// In general, the type names are self-explanatory, providing simple /// wrappers on the original base types. The template argument for bit /// counts or numeric ranges is necessary because TNL parses the actual /// function prototype as a string in order to determine how many bits /// to use for each RPC parameter. /// /// Template parameters to the NetType templates can be either integer /// constants or enumeration values. If enumeration values are used, /// the TNL_DECLARE_RPC_ENUM or TNL_DECLARE_RPC_MEM enum macros must /// be used to register the enumerations with the RPC system. struct NetType { }; /// Unsigned integer bit-level RPC template wrapper. /// /// When an Int<X> is in the parameter list for an RPC method, that parameter will /// be transmitted using X bits. template<U32 bitCount> struct Int : NetType { U32 value; Int(U32 val=0) { value = val; } operator U32() const { return value; } U32 getPrecisionBits() { return bitCount; } }; /// Signed integer bit-level RPC template wrapper. /// /// When a SignedInt<X> is in the parameter list for an RPC method, that parameter will /// be transmitted using X bits. template<U32 bitCount> struct SignedInt : NetType { S32 value; SignedInt(S32 val=0) { value = val; } operator S32() const { return value; } U32 getPrecisionBits() { return bitCount; } }; /// Floating point 0...1 value bit-level RPC template wrapper. /// /// When a Float<X> is in the parameter list for an RPC method, that parameter will /// be transmitted using X bits. template<U32 bitCount> struct Float : NetType { F32 value; Float(F32 val=0) { value = val; } operator F32() const { return value; } U32 getPrecisionBits() { return bitCount; } }; /// Floating point -1...1 value bit-level RPC template wrapper. /// /// When a SignedFloat<X> is in the parameter list for an RPC method, that parameter will /// be transmitted using X bits. template<U32 bitCount> struct SignedFloat : NetType { F32 value; SignedFloat(F32 val=0) { value = val; } operator F32() const { return value; } U32 getPrecisionBits() { return bitCount; } }; /// Unsigned ranged integer bit-level RPC template wrapper. /// /// The RangedU32 is used to specify a range of valid values for the parameter /// in the parameter list for an RPC method. template<U32 rangeStart, U32 rangeEnd> struct RangedU32 : NetType { U32 value; RangedU32(U32 val=rangeStart) { value = val; } operator U32() const { return value; } }; //------------------------------------------------------------------------------ //-------------------------------------- Type constants... /// @defgroup BasicConstants Global Constants /// /// Handy constants! /// @{ #define __EQUAL_CONST_F F32(0.000001) ///< Constant float epsilon used for F32 comparisons static const F32 FloatOne = F32(1.0); ///< Constant float 1.0 static const F32 FloatHalf = F32(0.5); ///< Constant float 0.5 static const F32 FloatZero = F32(0.0); ///< Constant float 0.0 static const F32 FloatPi = F32(3.14159265358979323846); ///< Constant float PI static const F32 Float2Pi = F32(2.0 * 3.14159265358979323846); ///< Constant float 2*PI static const F32 FloatInversePi = F32(1.0 / 3.14159265358979323846); ///< Constant float 1 / PI static const F32 FloatHalfPi = F32(0.5 * 3.14159265358979323846); ///< Constant float 1/2 * PI static const F32 Float2InversePi = F32(2.0 / 3.14159265358979323846);///< Constant float 2 / PI static const F32 FloatInverse2Pi = F32(0.5 / 3.14159265358979323846);///< Constant float 2 / PI static const F32 FloatSqrt2 = F32(1.41421356237309504880f); ///< Constant float sqrt(2) static const F32 FloatSqrtHalf = F32(0.7071067811865475244008443f); ///< Constant float sqrt(0.5) static const S8 S8_MIN = S8(-128); ///< Constant Min Limit S8 static const S8 S8_MAX = S8(127); ///< Constant Max Limit S8 static const U8 U8_MAX = U8(255); ///< Constant Max Limit U8 static const S16 S16_MIN = S16(-32768); ///< Constant Min Limit S16 static const S16 S16_MAX = S16(32767); ///< Constant Max Limit S16 static const U16 U16_MAX = U16(65535); ///< Constant Max Limit U16 static const S32 S32_MIN = S32(-2147483647 - 1); ///< Constant Min Limit S32 static const S32 S32_MAX = S32(2147483647); ///< Constant Max Limit S32 static const U32 U32_MAX = U32(0xffffffff); ///< Constant Max Limit U32 static const F32 F32_MIN = F32(1.175494351e-38F); ///< Constant Min Limit F32 static const F32 F32_MAX = F32(3.402823466e+38F); ///< Constant Max Limit F32 //---------------------------------------------------------------------------------- // Identify the compiler and OS specific stuff we need: //---------------------------------------------------------------------------------- #if defined (_MSC_VER) typedef signed _int64 S64; typedef unsigned _int64 U64; #ifndef TNL_COMPILER_VISUALC #define TNL_COMPILER_VISUALC _MSC_VER #endif #if _MSC_VER < 1200 // No support for old compilers # error "VC: Minimum Visual C++ 6.0 or newer required" #else //_MSC_VER >= 1200 # define TNL_COMPILER_STRING "VisualC++" #endif #define for if(false) {} else for ///< Hack to work around Microsoft VC's non-C++ compliance on variable scoping // disable warning caused by memory layer // see msdn.microsoft.com "Compiler Warning (level 1) C4291" for more details #pragma warning(disable: 4291) // disable performance warning of integer to bool conversions #pragma warning(disable: 4800) #elif defined(__MWERKS__) && defined(_WIN32) typedef signed long long S64; ///< Compiler independent signed 64-bit integer typedef unsigned long long U64; ///< Compiler independent unsigned 64-bit integer #define TNL_COMPILER_STRING "Metrowerks CW Win32" #elif defined(__GNUC__) typedef signed long long S64; ///< Compiler independent signed 64-bit integer typedef unsigned long long U64; ///< Compiler independent unsigned 64-bit integer #if defined(__MINGW32__) # define TNL_COMPILER_STRING "GCC (MinGW)" # define TNL_COMPILER_MINGW #elif defined(__CYGWIN__) # define TNL_COMPILER_STRING "GCC (Cygwin)" # define TNL_COMPILER_MINGW #else # define TNL_COMPILER_STRING "GCC " #endif #else # error "TNL: Unknown Compiler" #endif //---------------------------------------------------------------------------------- // Identify the target Operating System //---------------------------------------------------------------------------------- #if defined (_XBOX) || defined(__XBOX__) # define TNL_OS_STRING "XBox" # define TNL_OS_XBOX # define FN_CDECL __cdecl #elif defined(__WIN32__) || defined(_WIN32) || defined(__CYGWIN__) # define TNL_OS_STRING "Win32" # define TNL_OS_WIN32 #ifdef TNL_COMPILER_MINGW # define FN_CDECL #else # define FN_CDECL __cdecl #endif #elif defined(linux) # define TNL_OS_STRING "Linux" # define TNL_OS_LINUX # define FN_CDECL #elif defined(__OpenBSD__) # define TNL_OS_STRING "OpenBSD" # define TNL_OS_OPENBSD # define FN_CDECL #elif defined(__FreeBSD__) # define TNL_OS_STRING "FreeBSD" # define TNL_OS_FREEBSD # define FN_CDECL #elif defined(__APPLE__) # define TNL_OS_MAC # define TNL_OS_MAC_OSX # define FN_CDECL #else # error "TNL: Unsupported Operating System" #endif //---------------------------------------------------------------------------------- // Identify the target CPU and assembly language options //---------------------------------------------------------------------------------- #if defined(_M_IX86) || defined(i386) # define TNL_CPU_STRING "Intel x86" # define TNL_CPU_X86 # define TNL_LITTLE_ENDIAN # define TNL_SUPPORTS_NASM # if defined (__GNUC__) # if __GNUC__ == 2 # define TNL_GCC_2 # elif __GNUC__ == 3 # define TNL_GCC_3 # else # error "TNL: Unsupported version of GCC (see tnlMethodDispatch.cpp)" # endif # define TNL_SUPPORTS_GCC_INLINE_X86_ASM # elif defined (__MWERKS__) # define TNL_SUPPORTS_MWERKS_INLINE_X86_ASM # else # define TNL_SUPPORTS_VC_INLINE_X86_ASM # endif #elif defined(__ppc__) # define TNL_CPU_STRING "PowerPC" # define TNL_CPU_PPC # define TNL_BIG_ENDIAN # ifdef __GNUC__ # define TNL_SUPPORTS_GCC_INLINE_PPC_ASM # endif #else # error "TNL: Unsupported Target CPU" #endif /// @} ///@defgroup ObjTrickery Object Management Trickery /// /// These functions are to construct and destruct objects in memory /// without causing a free or malloc call to occur. This is so that /// we don't have to worry about allocating, say, space for a hundred /// NetAddresses with a single malloc call, calling delete on a single /// NetAdress, and having it try to free memory out from under us. /// /// @{ /// Constructs an object that already has memory allocated for it. template <class T> inline T* constructInPlace(T* p) { return new(p) T; } /// Copy constructs an object that already has memory allocated for it. template <class T> inline T* constructInPlace(T* p, const T* copy) { return new(p) T(*copy); } /// Destructs an object without freeing the memory associated with it. template <class T> inline void destructInPlace(T* p) { p->~T(); } /// @} /// @name GeneralMath Math Helpers /// /// Some general numeric utility functions. /// /// @{ /// Determines if number is a power of two. inline bool isPow2(const U32 number) { return (number & (number - 1)) == 0; } /// Determines the binary logarithm of the input value rounded down to the nearest power of 2. inline U32 getBinLog2(U32 value) { F32 floatValue = F32(value); return (*((U32 *) &floatValue) >> 23) - 127; } /// Determines the binary logarithm of the next greater power of two of the input number. inline U32 getNextBinLog2(U32 number) { return getBinLog2(number) + (isPow2(number) ? 0 : 1); } /// Determines the next greater power of two from the value. If the value is a power of two, it is returned. inline U32 getNextPow2(U32 value) { return isPow2(value) ? value : (1 << (getBinLog2(value) + 1)); } /// @defgroup MinMaxFuncs Many version of min and max /// /// We can't use template functions because MSVC6 chokes. /// /// So we have these... /// @{ #define DeclareTemplatizedMinMax(type) \ inline type getMin(type a, type b) { return a > b ? b : a; } \ inline type getMax(type a, type b) { return a > b ? a : b; } DeclareTemplatizedMinMax(U32) DeclareTemplatizedMinMax(S32) DeclareTemplatizedMinMax(U16) DeclareTemplatizedMinMax(S16) DeclareTemplatizedMinMax(U8) DeclareTemplatizedMinMax(S8) DeclareTemplatizedMinMax(F32) DeclareTemplatizedMinMax(F64) /// @} inline void writeU32ToBuffer(U32 value, U8 *buffer) { buffer[0] = value >> 24; buffer[1] = value >> 16; buffer[2] = value >> 8; buffer[3] = value; } inline U32 readU32FromBuffer(const U8 *buf) { return (U32(buf[0]) << 24) | (U32(buf[1]) << 16) | (U32(buf[2]) << 8 ) | U32(buf[3]); } inline void writeU16ToBuffer(U16 value, U8 *buffer) { buffer[0] = value >> 8; buffer[1] = (U8) value; } inline U16 readU16FromBuffer(const U8 *buffer) { return (U16(buffer[0]) << 8) | U16(buffer[1]); } inline U32 fourByteAlign(U32 value) { return (value + 3) & ~3; } #define BIT(x) (1 << (x)) ///< Returns value with bit x set (2^x) }; #endif //_TNL_TYPES_H_ <file_sep>#ifndef __XNETWORKSETTINGS_H #define __XNETWORKSETTINGS_H #include "precomp.h" struct xNetworkSettings { XString name; int port; bool isServer; TNL::Address bindAddress; TNL::Address pingAddr; }; #endif <file_sep>#ifndef __VT_X_ALL_H__ #define __VT_X_ALL_H__ /******************************************************************** created: 2008/12/05 created: 5:12:2008 0:34 filename: x:\ProjectRoot\localSVN\usr\include\vtXAll.h file path: x:\ProjectRoot\localSVN\usr\include file base: vtXAll file ext: h author: mc007 purpose: collective header file, includes all generic vt helper classes *********************************************************************/ #include <virtools/vtTools.h> //#include <virtools/vtBBHelper.h> //#include <virtools/vtBBMacros.h> using namespace vtTools; using namespace BehaviorTools; //#include <virtools/vtBBMacros.h> #include "vtLogTools.h" #include "vtStructHelper.h" /* #define VTD_PREFIX <virtools/ ifdef VTD_PREFIX #define VTSHEADERDIR VTD_PREFIX #else #define VTSHEADERDIR < #endif #define DIRMERGE(A##B) #define VTFILE_INC DIRMERGE(A) */ #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" void pVehicleGearDesc::setToCorvette() { forwardGearRatios[0] = 1.66f; forwardGearRatios[1] = 1.78f; forwardGearRatios[2] = 1.30f; forwardGearRatios[3] = 1; forwardGearRatios[4] = 0.74f; forwardGearRatios[5] = 0.50f; nbForwardGears = 6; backwardGearRatio = -2.90f; } void pVehicleGearDesc::setToDefault() { //forwardGears.clear(); } bool pVehicleGearDesc::isValid() const { if (nbForwardGears > getMaxNumOfGears()) { fprintf(stderr, "NxVehicleGearDesc::isValid(): nbForwardGears(%d) is bigger than max (%d)\n", nbForwardGears, getMaxNumOfGears()); return false; } if (nbForwardGears <= 0) { fprintf(stderr, "NxVehicleGearDesc::isValid(): nbForwardGears(%d) smaller or equal 0\n", nbForwardGears); return false; } if (backwardGearRatio > 0) { fprintf(stderr, "NxVehilceGearDesc::isValid(): backwardGearRatio(%2.3f) is bigger than 0, make it negative\n", backwardGearRatio); return false; } for (int i = 0; i < nbForwardGears; i++) { if (forwardGearRatios[i] < 0) { fprintf(stderr, "NxVehilceGearDesc::isValid(): forwardGearRatios[%d] (%2.3f) has value smaller 0\n", i, forwardGearRatios[i]); return false; } } return true; } float pVehicleGears::getCurrentRatio() const { return getRatio(_curGear); } float pVehicleGears::getRatio(NxI32 gear) const { if (gear > 0) return _forwardGearRatios[gear-1]; //return _forwardGears[gear-1]; if (gear == -1) return _backwardGearRatio; return 0; } <file_sep>#ifndef __VC_WARNINGS_H__ #define __VC_WARNINGS_H__ #pragma warning( disable : 4311 ) #pragma warning( disable : 4244 ) #pragma warning( disable : 4267 ) #pragma warning( disable : 4275 ) #pragma warning( disable : 4311) #pragma warning( disable : 4099) #pragma warning( disable : 4996) #endif <file_sep>#include "IMessages.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xMessageTypes.h" #include "xDistributedClient.h" #include "xLogger.h" #include "vtLogTools.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" int msgIDCounter=0; /* { if (getThresoldTicker() < getMinSendTime()) { TNL::logprintf("flood detected : %f",getThresoldTicker()); return; } ////////////////////////////////////////////////////////////////////////// xMessage*currentMessage = myClient->getCurrentMessage(); if (currentMessage) { if (isFlagOn(currentMessage->getFlags(),E_MF_SENT)) { //xLogger::xLog(XL_START,ELOGINFO,E_LI_MESSAGES,"message was sent by client,removing"); enableFlag(currentMessage->getFlags(),E_MF_DELETED); currentMessage =NULL; myClient->setCurrentOutMessage(NULL); // enableFlag(myClient->getClientFlags(),E_CF_NM_SENT); // disableFlag(myClient->getClientFlags(),E_CF_NM_SENDING); // setThresoldTicker(getMinSendTime() + 10.0f); } } xMessage *mOut = getNextOutMessage(); if (mOut ==NULL) { return; } TNL::logprintf("msg :ticker time : %f",getThresoldTicker()); if (isFlagOn(myClient->getClientFlags(),E_CF_NM_SENDING)) { //xLogger::xLog(XL_START,ELOGWARNING,E_LI_MESSAGES,"busy!"); return; }else { setThresoldTicker(0.0f); } ////////////////////////////////////////////////////////////////////////// enableFlag(mOut->getFlags(),E_MF_SENDING); enableFlag(myClient->getClientFlags(),E_CF_NM_SENDING); if (mOut->getDstUser()==-1) { enableFlag(mOut->getFlags(),E_MF_SEND_TO_ALL); } myClient->setCurrentOutMessage(mOut); }*/ void IMessages::writeToStream(xMessage *msg,TNL::BitStream *bstream,TNL::BitSet32 flags) { bstream->writeRangedU32(msg->getParameters().size(),0,16); bstream->writeString(msg->getName().getString(),strlen(msg->getName().getString())); if (isFlagOn(flags,E_MWF_SEND_SRC_USER_ID)) { bstream->writeInt(msg->getSrcUser(), GhostConnection::GhostIdBitSize); } bstream->writeFlag(isFlagOn(msg->getFlags(),E_MF_SEND_TO_ALL)); bstream->writeFlag(msg->getIgnoreSessionMaster()); if (!isFlagOn(msg->getFlags(),E_MF_SEND_TO_ALL) && isFlagOn(flags,E_MWF_SEND_TARGET_USER_ID)) bstream->writeInt(msg->getDstUser(),GhostConnection::GhostIdBitSize); ////////////////////////////////////////////////////////////////////////// xDistributedPropertyArrayType *props = &msg->getParameters(); for (unsigned int i = 0 ; i < props->size() ; i++ ) { xDistributedProperty *prop = props->at(i); xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); bstream->writeRangedU32(propInfo->mValueType,0,10); if (isFlagOn(flags,E_MWF_UPDATE_SERVER)) { prop->pack(bstream); } if (isFlagOn(flags,E_MWF_UPDATE_GHOST)) { prop->updateGhostValue(bstream); } } /*xDistributedClient *myClient = getNetInterface()->getMyClient(); if (myClient ) { enableFlag(myClient->getClientFlags(),E_CF_NM_SENT); disableFlag(myClient->getClientFlags(),E_CF_NM_SENDING); }*/ setThresoldTicker(getMinSendTime() + 10.0f); msg->setSendCount(msg->getSendCount() +1 ); //TNL::logprintf("msg written :%d tTime: %f | dst : %d",msg->getMessageID(),getThresoldTicker(),msg->getDstUser()); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xMessage* IMessages::readFromStream(TNL::BitStream *bstream,TNL::BitSet32 flags) { ////////////////////////////////////////////////////////////////////////// xMessage *msg = new xMessage(); int parSize = bstream->readRangedU32(0,16); char mName[256];bstream->readString(mName); msg->setName(mName); U32 ghostSrcIndex = 0 ; S32 ghostDstIndex =0; ////////////////////////////////////////////////////////////////////////// if (isFlagOn(flags,E_MRF_READ_SRC_USER_ID)) { ghostSrcIndex = bstream->readInt(GhostConnection::GhostIdBitSize); //TNL::logprintf("reading msg: \t reading src id :%d",ghostSrcIndex); msg->setSrcUser(ghostSrcIndex); } ////////////////////////////////////////////////////////////////////////// bool sendToAll = bstream->readFlag(); bool ignoreSessionMaster= bstream->readFlag(); msg->setIgnoreSessionMaster(ignoreSessionMaster); if (sendToAll) { enableFlag(msg->getFlags(),E_MF_SEND_TO_ALL); msg->setDstUser(-1); } if ( !isFlagOn(msg->getFlags(),E_MF_SEND_TO_ALL) && isFlagOn(flags,E_MRF_READ_TARGET_USER_ID) ) { ghostDstIndex = bstream->readInt(GhostConnection::GhostIdBitSize); msg->setDstUser(ghostDstIndex); } ////////////////////////////////////////////////////////////////////////// for (int i = 0 ; i < parSize ; i ++ ) { int valType = bstream->readRangedU32(0,10); xDistributedPropertyInfo *dInfo = new xDistributedPropertyInfo( "NoName" , valType , -1 ,E_PTYPE_RELIABLE); xDistributedProperty *prop = NULL; switch(valType) { case E_DC_PTYPE_STRING : { prop = new xDistributedString(dInfo,30,3000); break; } case E_DC_PTYPE_FLOAT: { prop = new xDistributedPoint1F(dInfo,30,3000); break; } case E_DC_PTYPE_INT: { prop = new xDistributedInteger(dInfo,30,3000); break; } case E_DC_PTYPE_2DVECTOR: { prop = new xDistributedPoint2F(dInfo,30,3000); break; } case E_DC_PTYPE_3DVECTOR : { prop = new xDistributedPoint3F(dInfo,30,3000); break; } case E_DC_PTYPE_QUATERNION: { prop = new xDistributedQuatF(dInfo,30,3000); break; } } if (isFlagOn(flags,E_MRF_UPDATE_BY_GHOST)) { prop->unpack(bstream,0.0f); } if (isFlagOn(flags,E_MRF_SERVER_UPDATE)) { prop->updateFromServer(bstream); } msg->getParameters().push_back(prop); } //TNL::logprintf("msg recieved :%d",msg->getMessageID()); return msg; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IMessages::addMessage(xMessage*msg) { xDistributedClient *myClient = getNetInterface()->getMyClient(); if (!myClient ) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MESSAGES,"no client object"); return; } if (!msg) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MESSAGES,"invalid input message"); return; } enableFlag(msg->getFlags(),E_MF_NEW); enableFlag(msg->getFlags(),E_MF_OUTGOING); getMessages()->push_back(msg); msg->setMessageID(msgIDCounter); msgIDCounter ++; if (msg->getDstUser()==-1) { enableFlag(msg->getFlags(),E_MF_SEND_TO_ALL); } return; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IMessages::advanceTime(float deltaTime) { xMessageArrayType *messages = getMessages(); float time = getThresoldTicker() +deltaTime ; setThresoldTicker( time ); xMessageArrayIterator begin = messages->begin(); xMessageArrayIterator end = messages->end(); while (begin!=end) { xMessage* _cmsg = *begin; if (_cmsg && !isFlagOn(_cmsg->getFlags(),E_MF_DELETED) ) { _cmsg->setLifeTime( _cmsg->getLifeTime() + deltaTime ); } begin++; } } int IMessages::getNumOutMessages() { xMessageArrayType *messages = getMessages(); xMessageArrayIterator begin = messages->begin(); xMessageArrayIterator end = messages->end(); int result = 0; while (begin!=end) { xMessage* _cmsg = *begin; if (_cmsg ) { if (!isFlagOn(_cmsg->getFlags(),E_MF_DELETED) && isFlagOn(_cmsg->getFlags(),E_MF_NEW) && isFlagOn(_cmsg->getFlags(),E_MF_OUTGOING) && !isFlagOn(_cmsg->getFlags(),E_MF_SENT) ) { result ++; } } begin++; } return result; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IMessages::checkMessages() { xMessageArrayType *messages = getMessages(); xMessageArrayIterator begin = messages->begin(); xMessageArrayIterator end = messages->end(); while (begin!=end) { xMessage* _cmsg = *begin; if (_cmsg ) { if ( _cmsg->getLifeTime() > getMessageTimeout() ) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MESSAGES,"msg expired %f | timout : %f",_cmsg->getLifeTime(),getMessageTimeout() ); enableFlag(_cmsg->getFlags(),E_MF_DELETED); } } begin++; } if (!getNetInterface()->IsServer() && !getNumOutMessages()) { if (getNetInterface()->getMyClient()) { xDistributedClient *client = getNetInterface()->getMyClient(); disableFlag(client->getClientFlags(),E_CF_NM_SENDING); client->setCurrentOutMessage(NULL); setThresoldTicker(getMinSendTime() + 10.0f); } } if (!getNetInterface()->IsServer() &&getNumOutMessages()) { if (getNetInterface()->getMyClient()) { xDistributedClient *client = getNetInterface()->getMyClient(); xMessage *mOut = getNextOutMessage(); if (mOut && getThresoldTicker() > getMinSendTime() ) { //TNL::logprintf("push next message %d",mOut->getMessageID()); //client->setUpdateState(E_DO_US_PENDING); client->setCurrentOutMessage(mOut); setThresoldTicker(0.0f); } } } if (getNetInterface()->IsServer()) { if (getNumOutMessages()) { xMessage *mOut = getNextOutMessage(); xDistributedClient *client = mOut->getClientSource(); if (mOut && client && client->getCurrentMessage()==NULL && getThresoldTicker() > getMinSendTime() ) { //TNL::logprintf("push next message %d",mOut->getMessageID()); if (mOut->getClientSource()) { mOut->getClientSource()->setCurrentOutMessage(mOut); mOut->getClientSource()->setMaskBits(1<<xDistributedClient::MessageMask); setThresoldTicker(0.0f); } } } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int IMessages::getNumMessagesOfType(int type) { int counter = 0 ; xMessageArrayType *messages = getMessages(); xMessageArrayIterator begin = messages->begin(); xMessageArrayIterator end = messages->end(); while (begin!=end) { xMessage* _cmsg = *begin; if (_cmsg ) { if ( isFlagOn(_cmsg->getFlags(),type) ) { counter++; } } begin++; } return counter; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IMessages::deleteAllOldMessages() { int numMessages = getNumMessagesOfType(E_MF_DELETED); if (!numMessages) { return; } xMessageArrayType *messages = getMessages(); xMessageArrayIterator begin = messages->begin(); xMessageArrayIterator end = messages->end(); while (begin!=end) { xMessage* _cmsg = *begin; if (_cmsg ) { if ( isFlagOn(_cmsg->getFlags(),E_MF_DELETED) ) { if (isFlagOn(_cmsg->getFlags(),E_MF_OUTGOING) && !isFlagOn(_cmsg->getFlags(),E_MF_SENT)) { xLogger::xLog(XL_START,ELOGTRACE,E_LI_MESSAGES,"message never sent %d %f",_cmsg->getMessageID(),_cmsg->getLifeTime()); } if (getNetInterface()->IsServer()) { xDistributedClient *client = _cmsg->getClientSource(); if (client) { client->setCurrentOutMessage(NULL); } } getMessages()->erase(begin); delete _cmsg; _cmsg = NULL; if (getNumMessagesOfType(E_MF_DELETED)) { // xLogger::xLog(XL_START,ELOGTRACE,E_LI_MESSAGES,"check again"); deleteAllOldMessages(); } return; } } begin++; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IMessages::deleteMessage(xMessage*msg) { if (!msg )return; enableFlag(msg->getFlags(),E_MF_DELETED); return; /* xDistributedPropertyArrayIterator begin = msg.getParameters().begin(); xDistributedPropertyArrayIterator end = msg.getParameters().end(); while (begin!=end) { xDistributedProperty *prop = *begin; if (prop) { xDistributedPropertyInfo *info = prop->m_PropertyInfo; if (info) { delete info; prop->m_PropertyInfo=NULL; } msg.getParameters().erase(begin); delete prop; begin = msg.getParameters().begin(); int size = msg.getParameters().size(); if (size) continue; else break; } begin++; }*/ /*msg.getParameters().clear(); delete msg.getParameters();*/ delete msg; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void IMessages::removeMessage(xMessage*msg) { if (!msg) return; xMessageArrayType *messages = getMessages(); xMessageArrayIterator begin = messages->begin(); xMessageArrayIterator end = messages->end(); while (begin!=end) { xMessage* _cmsg = *begin; if (_cmsg && _cmsg ==msg) { enableFlag(_cmsg->getFlags(),E_MF_DELETED); } begin++; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xMessage*IMessages::getNextInMessage(xNString mName) { for(int i = 0 ; i < getMessages()->size() ; i++) { xMessage *msg = getMessages()->at(i); if (isFlagOn(msg->getFlags(),E_MF_NEW) && isFlagOn(msg->getFlags(),E_MF_INCOMING) && isFlagOn(msg->getFlags(),E_MF_FINISH) && !strcmp(msg->getName().getString(),mName.getString() ) ) { return msg; } } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xMessage*IMessages::getNextInMessage() { for(int i = 0 ; i < getMessages()->size() ; i++) { xMessage *msg = getMessages()->at(i); if (isFlagOn(msg->getFlags(),E_MF_NEW) && isFlagOn(msg->getFlags(),E_MF_INCOMING) && isFlagOn(msg->getFlags(),E_MF_FINISH) ) { return msg; } } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xMessage*IMessages::getNextOutMessage() { for(int i = 0 ; i < getMessages()->size() ; i++) { xMessage *msg = getMessages()->at(i); if (isFlagOn(msg->getFlags(),E_MF_NEW) && isFlagOn(msg->getFlags(),E_MF_OUTGOING) && !isFlagOn(msg->getFlags(),E_MF_SENT) && !isFlagOn(msg->getFlags(),E_MF_DELETED) ) { return msg; } } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xMessageArrayType* IMessages::getMessages() { if (getNetInterface()) { return getNetInterface()->getMessages(); } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ IMessages::IMessages(xNetInterface *ninterface) : mNetInterface(ninterface) { setMessageTimeout(5000); mMinSendTime = 30; mThresoldTicker = getMinSendTime() + 10.0f; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ <file_sep>// rsteer.h #ifndef __PVEHICLE_STEER_H__ #define __PVEHICLE_STEER_H__ #include "vtPhysXBase.h" #include "pVehicleTypes.h" class pVehicleSteer { pVehicle *car; // Physical float lock; // Maximum angle (radians) VxVector position; float radius; float xa; // Rotation towards the driver's face // State (output) float angle; // -lock .. +lock // Input int axisInput; // Controller position (axis) public: pVehicleSteer(pVehicle *car); ~pVehicleSteer(); float GetAngle(){ return angle; } float GetLock(){ return lock; } void SetAngle(float _angle){ angle=_angle; } // For replays void setToDefault(); void SetInput(int axisPos); float getLock() const { return lock; } void setLock(float val) { lock = val; } void Integrate(); }; #endif <file_sep>#include <StdAfx.h> #include "pCommon.h" #include "IParameter.h" #include <xDebugTools.h> CKObjectDeclaration *FillBehaviorPVSetBreakSettingsDecl(); CKERROR CreatePVSetBreakSettingsProto(CKBehaviorPrototype **pproto); int PVSetBreakSettings(const CKBehaviorContext& behcontext); CKERROR PVSetBreakSettingsCB(const CKBehaviorContext& behcontext); enum bInputs { bbI_XML_Link, bbI_BreakFlags, bbI_BSmallPressure, bbI_BMediumPressure, bbI_BHighPressure, bbI_BMediumTime, bbI_BHighTime, bbI_BTableSmall, bbI_BTableMedium, bbI_BTableHigh, }; #define BB_SSTART bbI_BTableSmall BBParameter pInMap233[] = { BB_PIN(bbI_XML_Link,VTE_BRAKE_XML_LINK,"XML Link","Stub"), BB_PIN(bbI_BreakFlags,VTF_BRAKE_FLAGS,"Use Break Table","Use Table"), BB_PIN(bbI_BSmallPressure,CKPGUID_FLOAT,"Break Pressure : Small ","0.1f"), BB_PIN(bbI_BMediumPressure,CKPGUID_FLOAT,"Break Pressure : Medium ","0.3f"), BB_PIN(bbI_BHighPressure,CKPGUID_FLOAT,"Break Pressure : High","1.0f"), BB_PIN(bbI_BMediumTime,CKPGUID_TIME,"Medium Apply Time","1.5"), BB_PIN(bbI_BHighTime,CKPGUID_TIME,"High Apply Time","3.5"), BB_SPIN(bbI_BTableSmall,VTS_BRAKE_TABLE,"Break Table : Small",""), BB_SPIN(bbI_BTableMedium,VTS_BRAKE_TABLE,"Break Table : Medium",""), BB_SPIN(bbI_BTableHigh,VTS_BRAKE_TABLE,"Break Table : High",""), }; #define gPIMAP pInMap233 CKObjectDeclaration *FillBehaviorPVSetBreakSettingsDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVSetBreakSettings"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Sets custom break behavior."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x719d41c2,0x46b76965)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVSetBreakSettingsProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePVSetBreakSettingsProto // FullName: CreatePVSetBreakSettingsProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePVSetBreakSettingsProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVSetBreakSettings"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /* PVSetBreakSettings PVSetBreakSettings is categorized in \ref Body <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Registers an object in the physic engine.<br> See <A HREF="PVSetBreakSettingsSamples.cmo">PVSetBreakSettings.cmo</A> for example. <h3>Technical Information</h3> \image html PVSetBreakSettings.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed <BR> <BR> <SPAN CLASS="pin">Target:</SPAN>The 3D Entity associated to the rigid body <BR> */ BB_EVALUATE_PINS(gPIMAP) BB_EVALUATE_SETTINGS(gPIMAP) proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct( PVSetBreakSettingsCB ); proto->SetFunction(PVSetBreakSettings); *pproto = proto; return CK_OK; } //************************************ // Method: PVSetBreakSettings // FullName: PVSetBreakSettings // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PVSetBreakSettings(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // objects // CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbSErrorME(E_PE_REF); //the world reference, optional used CK3dEntity*worldRef = NULL; //the world object, only used when reference has been specified pWorld *world = NULL; //final object description pObjectDescr *oDesc = new pObjectDescr(); pRigidBody *body = NULL; pVehicle *v = NULL; XString errMesg; //---------------------------------------------------------------- // // sanity checks // body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); v = body->getVehicle(); if (!v) bbSErrorME(E_PE_NoVeh); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Collecting data. Stores all settings in a pObjectDescr. // //get the parameter array BB_DECLARE_PIMAP; v->setBreakFlags(GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_BreakFlags))); //---------------------------------------------------------------- // // brake pressures // float pressureSmall = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_BSmallPressure)); iAssertW( pressureSmall >=0.0f && pressureSmall <=1.0f , _FLT_ASSIGMENT(pressureSmall,0.1f) ,""); float pressureMedium = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_BMediumPressure)); iAssertW( pressureMedium>=0.0f && pressureMedium<=1.0f , _FLT_ASSIGMENT(pressureMedium,0.3f) ,""); float pressureHigh = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_BHighPressure)); iAssertW( pressureHigh >=0.0f && pressureHigh<=1.0f , _FLT_ASSIGMENT(pressureHigh,1.0f) ,""); v->setBreakPressure(BL_Small,pressureSmall); v->setBreakPressure(BL_Medium,pressureMedium); v->setBreakPressure(BL_High,pressureHigh); //---------------------------------------------------------------- // // brake table // BBSParameterM(bbI_BTableSmall,BB_SSTART); if(sbbI_BTableSmall) IParameter::Instance()->copyTo(v->mSmallBrakeTable,beh->GetInputParameter(BB_IP_INDEX(bbI_BTableSmall))->GetRealSource()); BBSParameterM(bbI_BTableMedium,BB_SSTART); if(sbbI_BTableMedium) IParameter::Instance()->copyTo(v->mMediumBrakeTable,beh->GetInputParameter(BB_IP_INDEX(bbI_BTableMedium))->GetRealSource()); BBSParameterM(bbI_BTableHigh,BB_SSTART); if(sbbI_BTableHigh) IParameter::Instance()->copyTo(v->mHighBrakeTable,beh->GetInputParameter(BB_IP_INDEX(bbI_BTableHigh))->GetRealSource()); //---------------------------------------------------------------- // // brake wait time // v->mBrakeMediumThresold = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_BMediumTime)); v->mBrakeHighThresold = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_BHighTime)); //---------------------------------------------------------------- // // error out // errorFound: { beh->ActivateOutput(0); return CKBR_GENERICERROR; } //---------------------------------------------------------------- // // All ok // allOk: { beh->ActivateOutput(0); return CKBR_OK; } return 0; } //************************************ // Method: PVSetBreakSettingsCB // FullName: PVSetBreakSettingsCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PVSetBreakSettingsCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; }<file_sep>#include "StdAfx.h" #include "InitMan.h" #include "vt_python_funcs.h" //#include "VSLManagerSDK.h" /*#include <iostream> #include "pyembed.h" */ extern vt_python_man *pym; ////////////////////////////////////////////////////////////////////////// vt_python_man::~vt_python_man(){} ////////////////////////////////////////////////////////////////////////// vt_python_man* vt_python_man::GetPyMan() { return pym; } //************************************ // Method: PostProcess // FullName: vt_python_man::PostProcess // Access: public // Returns: CKERROR // Qualifier: //************************************ CKERROR vt_python_man::PostProcess() { if (m_stdErr.Length()) { m_Context->OutputToConsoleEx("\nPyErr:%s",m_stdErr.Str(),FALSE); m_stdErr =""; } if (m_stdOut.Length()) { m_Context->OutputToConsoleEx("\nPyOut:%s",m_stdOut.Str(),FALSE); m_stdOut=""; } return CK_OK; } //************************************ // Method: PreProcess // FullName: vt_python_man::PreProcess // Access: public // Returns: CKERROR // Qualifier: //************************************ CKERROR vt_python_man::PreProcess() { //m_Context->OutputToConsoleEx("Py std::error : %s",m_stdErr); //m_Context->OutputToConsoleEx("Py std::out : %s",m_stdOut); return CK_OK; } CKERROR vt_python_man::PostClearAll(){ return CK_OK; } ////////////////////////////////////////////////////////////////////////// CKERROR vt_python_man::OnCKEnd(){ return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CKERROR vt_python_man::OnCKReset(){ /*if(py) { delete py; py = NULL; }*/ ClearModules(); DestroyPython(); return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CKERROR vt_python_man::OnCKPlay() { return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CKERROR vt_python_man::OnCKInit(){ m_Context->ActivateManager((CKBaseManager*) this,true); /* int argc = 1; char *cmd =GetCommandLineA(); char *c1[1]; c1[0]=new char[5]; strcpy(c1[0],cmd);*/ //py = new Python(argc,c1); /*if(py) { delete py; py = NULL; }*/ //RegisterVSL(); return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <file_sep>#ifndef __X_ASSERT_CUSTOMIZATION_H__ #define __X_ASSERT_CUSTOMIZATION_H__ #include "xPlatform.h" struct xAssertInfo { public: E_ASSERTION_FAILURE_SEVERITY failureSeverity; char *assertionExpression; char *assertionFileName; int assertionSourceLine; char *assertionPostMessage; void *postAction; bool result; xAssertInfo() : failureSeverity(AFS__MAX) , assertionExpression(NULL), assertionFileName(NULL), assertionSourceLine(0), assertionPostMessage(NULL), postAction(NULL), result(false) { } /* xAssertInfo() : { failureSeverity = AFS__MAX; assertionExpression = NULL; assertionFileName = NULL; assertionSourceLine = 0; assertionSourceObject = NULL; assertionPostMessage = NULL; postAction = NULL; result = false; } */ xAssertInfo( E_ASSERTION_FAILURE_SEVERITY _failureSeverity, char *_assertionExpression, char *_assertionFileName, int _assertionSourceLine, char *_assertionPostMessage, void* _postAction, bool _result) { assertionExpression = _assertionExpression; assertionFileName = _assertionFileName; assertionSourceLine = _assertionSourceLine; assertionPostMessage = _assertionPostMessage; postAction = _postAction; failureSeverity = _failureSeverity; result = _result; } }; #endif<file_sep>/****************************************************************************** File : CustomPlayer.cpp Description: This file contains the CCustomPlayer class which is the "interface" with the Virtools SDK. All other files are Windows/MFC specific code. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ #include "CPStdAfx.h" #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "vtTools.h" #if defined(CUSTOM_PLAYER_STATIC) // include file used for the static configuration #include "CustomPlayerStaticLibs.h" #include "CustomPlayerRegisterDlls.h" #endif #include "xSplash.h" extern CCustomPlayerApp theApp; extern CCustomPlayer* thePlayer; BOOL CCustomPlayerApp::InitInstance() { // register the windows class the main and the render window _RegisterClass(); // read the configuration const char* fileBuffer = 0; XDWORD fileSize = 0; // read the configuration //XString filename; // retrieve the unique instance of the player (CCustomPlayer class) CCustomPlayer& player = CCustomPlayer::Instance(); player.PLoadEngineWindowProperties(CUSTOM_PLAYER_CONFIG_FILE); player.PLoadEnginePathProfile(CUSTOM_PLAYER_CONFIG_FILE); player.PLoadAppStyleProfile(CUSTOM_PLAYER_CONFIG_FILE); player.m_AppMode = player.PGetApplicationMode(GetCommandLine()); // sets player.m_AppMode = full; //m_Config |= eAutoFullscreen; // create the main and the render window //we only create windows when we want to render something ! if (GetPlayer().GetPAppStyle()->IsRenderering()) { if(!_CreateWindows()) { MessageBox(NULL,FAILED_TO_CREATE_WINDOWS,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } } XString filename(GetPlayer().GetEPathProfile()->CompositionFile); if(!_ReadConfig(filename,fileBuffer,fileSize)) { /*MessageBox(NULL,CANNOT_READ_CONFIG,INIT_ERROR,MB_OK|MB_ICONERROR);*/ //return FALSE; } //XString filename("tetris1.cmo"); // initialize the player if(!player.InitPlayer(m_MainWindow,m_RenderWindow,m_Config,filename.Length()==0?fileBuffer:filename.CStr(),filename.Length()==0?fileSize:0)) { return FALSE; } // [12/17/2007 mc007] // as the player is ready we destroy the splash screen window //DestroyWindow(m_Splash); if (GetPlayer().GetPAppStyle()->IsRenderering()) { if (GetPlayer().GetEWindowInfo()->g_GoFullScreen) { // we are a auto fullscreen mode // so we hide the main window ShowWindow(m_MainWindow,SW_HIDE); UpdateWindow(m_MainWindow); // we show the render window ShowWindow(m_RenderWindow,theApp.m_nCmdShow); UpdateWindow(m_RenderWindow); // and set the focus to it SetFocus(m_RenderWindow); GetPlayer().m_EatDisplayChange = TRUE; } else { // we are in windowed mode // so we show the main window ShowWindow(m_MainWindow,theApp.m_nCmdShow); UpdateWindow(m_MainWindow); // the render window too ShowWindow(m_RenderWindow,theApp.m_nCmdShow); UpdateWindow(m_RenderWindow); // and set the focus to it SetFocus(m_RenderWindow); } } // we reset the player to start it player.Reset(); /////////////////////////////////////////////////////////////////////////// // NOTE: other important things to read after initialization // - the main loop of the player is executed by CCustomPlayerApp::Run // - the windowproc of the main and render window is // CCustomPlayerApp::_MainWindowWndProc // - but the main part of the application is implemented by the // CCustomPlayer class. /////////////////////////////////////////////////////////////////////////// return TRUE; } int CCustomPlayerApp::Run() { MSG msg; while(1) { if(PeekMessage(&msg, NULL,0,0,PM_REMOVE)) { if(msg.message==WM_QUIT) { return CWinApp::Run(); } else if(!TranslateAccelerator(msg.hwnd,m_hAccelTable,&msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } else { // process the player if(!CCustomPlayer::Instance().Process(m_Config)) { PostQuitMessage(0); return CWinApp::Run(); } } } return msg.wParam; }<file_sep>#ifndef __P_FLUID_EMITTER_DESC_H__ #define __P_FLUID_EMITTER_DESC_H__ /** \addtogroup fluids @{ */ /** \brief Flags which control the behavior of fluid emitters. @see pFluidEmitter */ enum pFluidEmitterFlag { /** \brief Flags whether the emitter should be visualized for debugging or not. */ PFEF_Visualization = (1<<0), /** \brief This flag specifies whether the emission should cause a force on the shapes body that the emitter is attached to. */ PFEF_ForceOnBody = (1<<2), /** \brief If set, the velocity of the shapes body is added to the emitted particle velocity. This is the default behavior . */ PFEF_AddBodyVelocity = (1<<3), /** \brief Flag to start and stop the emission. On default the emission is enabled. */ PFEF_Enabled = (1<<4), }; /** \brief Flags to specify the shape of the area of emission. Exactly one flag should be set at any time. */ enum pEmitterShape { PFES_Rectangular = (1<<0), PFES_Ellipse = (1<<1) }; /** \brief Flags to specify the emitter's type of operation. Exactly one flag should be set at any time. @see pFluidEmitter */ enum pEmitterType { PFET_ConstantPressure = (1<<0), PFET_ConstantFlowRate = (1<<1) }; /** \brief Descriptor for pFluidEmitter class. Used for saving and loading the emitter state. */ class MODULE_API pFluidEmitterDesc { public: CK_ID entityReference; /** \brief A pointer to the shape to which the emitter is attached to. If this pointer is set to NULL, the emitter is attached to the world frame. The shape must be in the same scene as the emitter. */ CK3dEntity* frameShape; /** \brief The emitter's mode of operation. Either the simulation enforces constant pressure or constant flow rate at the emission site, given the velocity of emitted particles. @see NxEmitterType */ pEmitterType type; /** \brief The maximum number of particles which are emitted from this emitter. If the total number of particles in the fluid already hit the maxParticles parameter of the fluid, this maximal values can't be reached. If set to 0, the number of emitted particles is unrestricted. */ int maxParticles; /** \brief The emitter's shape can either be rectangular or elliptical. @see pEmitterShape */ pEmitterShape shape; /** \brief The sizes of the emitter in the directions of the first and the second axis of its orientation frame (relPose). The dimensions are actually the radii of the size. */ float dimensionX; float dimensionY; /** \brief Random vector with values for each axis direction of the emitter orientation. The values have to be positive and describe the maximal random particle displacement in each dimension. The z value describes the randomization in emission direction. The emission direction is specified by the third orientation axis of relPose. */ VxVector randomPos; /** \brief Random angle deviation from emission direction. The emission direction is specified by the third orientation axis of relPose. <b>Unit:</b> Radians */ float randomAngle; /** \brief The velocity magnitude of the emitted fluid particles. */ float fluidVelocityMagnitude; /** \brief The rate specifies how many particles are emitted per second. The rate is only considered in the simulation if the type is set to PFET_ConstantFlowRate. @see NxEmitterType */ float rate; /** \brief This specifies the time in seconds an emitted particle lives. If set to 0, each particle will live until it collides with a drain. */ float particleLifetime; /** \brief Defines a factor for the impulse transfer from attached emitter to body. Only has an effect if PFEF_ForceOnBody is set. <b>Default:</b> 1.0 <br> <b>Range:</b> [0,inf) @see PFEF_ForceOnBody NxFluidEmitter.setRepulsionCoefficient() */ float repulsionCoefficient; /** \brief A combination of pFluidEmitterFlags. @see pFluidEmitterFlag */ pFluidEmitterFlag flags; ~pFluidEmitterDesc(); /** \brief (Re)sets the structure to the default. */ void setToDefault(); /** \brief Returns true if the current settings are valid */ bool isValid() const; /** \brief Constructor sets to default. */ pFluidEmitterDesc(); }; /** @} */ #endif <file_sep>#ifndef ZCALLBCK_H #define ZCALLBCK_H //#include "StdAfx.h" #include <windows.h> #define MAX_FILES 4096 #pragma pack (push) struct CZipCallbackData { DWORD m_hwndHandle; HWND m_pCaller; long int m_liVersion; BOOL m_bIsOperationZip; long int m_liActionCode; long int m_liErrorCode; long int m_liFileSize; char m_pszFileNameOrMsg[512]; }; #pragma pack (pop) typedef BOOL (__stdcall *ZFunctionPtrType) (CZipCallbackData*); #endif ZCALLBCK_H // ZCALLBCK_H <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" //#include "pVehicle.h" PhysicManager *ourMan = NULL; typedef ForceMode PForceMode; typedef D6MotionMode PJMotion; typedef D6DriveType PDriveType; pRigidBody *getBody(CK3dEntity*ent){ pRigidBody *body = GetPMan()->getBody(ent); if (body) { return body; }else{ return NULL; } } void __newpSpring(BYTE *iAdd) { new (iAdd) pSpring(); } void __newpSoftLimit(BYTE *iAdd) { new (iAdd) pJD6SoftLimit(); } void __newpDrive(BYTE *iAdd) { new (iAdd) pJD6Drive(); } void __newpJointLimit(BYTE *iAdd) { new (iAdd) pJointLimit(); } void __newpMotor(BYTE *iAdd) { new (iAdd) pMotor(); } pSerializer *GetSerializer() { return pSerializer::Instance(); } void __newpClothDescr(BYTE *iAdd) { new(iAdd)pClothDesc(); } #define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) void PhysicManager::_RegisterVSL() { _RegisterVSLCommon(); ourMan = GetPMan(); _RegisterVSLCommon(); _RegisterVSLVehicle(); STARTVSLBIND(m_Context) ////////////////////////////////////////////////////////////////////////// // // Bindings for pVehicle related classes : // // DECLAREENUM("pClothAttachmentFlag") DECLAREENUMVALUE("pClothAttachmentFlag", "PCAF_ClothAttachmentTwoway" ,1 ) DECLAREENUMVALUE("pClothAttachmentFlag", "PCAF_ClothAttachmentTearable" ,2 ) DECLAREENUM("pClothFlag") DECLAREENUMVALUE("pClothFlag", "PCF_Pressure" ,1 ) DECLAREENUMVALUE("pClothFlag", "PCF_Static",2) DECLAREENUMVALUE("pClothFlag", "PCF_DisableCollision",4) DECLAREENUMVALUE("pClothFlag", "PCF_SelfCollision",8) DECLAREENUMVALUE("pClothFlag", "PCF_Gravity",32) DECLAREENUMVALUE("pClothFlag", "PCF_Bending",64) DECLAREENUMVALUE("pClothFlag", "PCF_BendingOrtho",128) DECLAREENUMVALUE("pClothFlag", "PCF_Damping",256) DECLAREENUMVALUE("pClothFlag", "PCF_CollisionTwoway",512) DECLAREENUMVALUE("pClothFlag", "PCF_TriangleCollision",2048) DECLAREENUMVALUE("pClothFlag", "PCF_Tearable",4096) DECLAREENUMVALUE("pClothFlag", "PCF_Hardware",8192) DECLAREENUMVALUE("pClothFlag", "PCF_ComDamping",16384) DECLAREENUMVALUE("pClothFlag", "PCF_ValidBounds",32768) DECLAREENUMVALUE("pClothFlag", "PCF_FluidCollision",65536) DECLAREENUMVALUE("pClothFlag", "PCF_DisableDynamicCCD",131072) DECLAREENUMVALUE("pClothFlag", "PCF_AddHere",262144) DECLAREENUMVALUE("pClothFlag", "PCF_AttachToParentMainShape",524288) DECLAREENUMVALUE("pClothFlag", "PCF_AttachToCollidingShapes",1048576) DECLAREENUMVALUE("pClothFlag", "PCF_AttachToCore",2097152) DECLAREENUMVALUE("pClothFlag", "PCF_AttachAttributes",4194304) DECLAREOBJECTTYPE(pClothDesc) DECLAREMEMBER(pClothDesc,float,thickness) DECLAREMEMBER(pClothDesc,float,density) DECLAREMEMBER(pClothDesc,float,bendingStiffness) DECLAREMEMBER(pClothDesc,float,stretchingStiffness) DECLAREMEMBER(pClothDesc,float,dampingCoefficient) DECLAREMEMBER(pClothDesc,float,friction) DECLAREMEMBER(pClothDesc,float,pressure) DECLAREMEMBER(pClothDesc,float,tearFactor) DECLAREMEMBER(pClothDesc,float,collisionResponseCoefficient) DECLAREMEMBER(pClothDesc,float,attachmentResponseCoefficient) DECLAREMEMBER(pClothDesc,float,attachmentTearFactor) DECLAREMEMBER(pClothDesc,float,toFluidResponseCoefficient) DECLAREMEMBER(pClothDesc,float,fromFluidResponseCoefficient) DECLAREMEMBER(pClothDesc,float,minAdhereVelocity) DECLAREMEMBER(pClothDesc,int,solverIterations) DECLAREMEMBER(pClothDesc,VxVector,externalAcceleration) DECLAREMEMBER(pClothDesc,VxVector,windAcceleration) DECLAREMEMBER(pClothDesc,float,wakeUpCounter) DECLAREMEMBER(pClothDesc,float,sleepLinearVelocity) DECLAREMEMBER(pClothDesc,int,collisionGroup) DECLAREMEMBER(pClothDesc,VxBbox,validBounds) DECLAREMEMBER(pClothDesc,float,relativeGridSpacing) DECLAREMEMBER(pClothDesc,pClothFlag,flags) DECLAREMEMBER(pClothDesc,pClothAttachmentFlag,attachmentFlags) DECLAREMEMBER(pClothDesc,VxColor,tearVertexColor) DECLAREMEMBER(pClothDesc,CK_ID,worldReference) DECLAREMETHOD_0(pClothDesc,void,setToDefault) DECLARECTOR_0(__newpClothDescr) ////////////////////////////////////////////////////////////////////////// // // Vehicle : // DECLAREMETHOD_1(pVehicle,void,updateVehicle,float) DECLAREMETHOD_5(pVehicle,void,setControlState,float,bool,float,bool,bool) DECLAREMETHOD_1(pVehicle,pWheel*,getWheel,CK3dEntity*) DECLAREMETHOD_0(pVehicle,pVehicleMotor*,getMotor) DECLAREMETHOD_0(pVehicle,pVehicleGears*,getGears) DECLAREMETHOD_0(pVehicle,void,gearUp) DECLAREMETHOD_0(pVehicle,void,gearDown) DECLAREMETHOD_0(pVehicleGears,int,getGear) ////////////////////////////////////////////////////////////////////////// //motor : DECLAREMETHOD_0(pVehicleMotor,float,getRpm) DECLAREMETHOD_0(pVehicleMotor,float,getTorque) DECLAREMETHOD_0(pWheel,pWheel1*,castWheel1) DECLAREMETHOD_0(pWheel,pWheel2*,castWheel2) DECLAREMETHOD_0(pWheel,float,getWheelRollAngle) DECLAREMETHOD_0(pWheel2,float,getRpm) DECLAREMETHOD_0(pWheel2,float,getAxleSpeed) DECLAREMETHOD_0(pWheel2,float,getSuspensionTravel) DECLAREMETHOD_0(pWheel2,VxVector,getGroundContactPos) ////////////////////////////////////////////////////////////////////////// // // Bindings for pVehicle related classes : // // ////////////////////////////////////////////////////////////////////////// // // Bindings for pVehicle related classes : // // DECLAREOBJECTTYPE(pJointLimit) DECLARECTOR_0(__newpJointLimit) DECLAREMEMBER(pJointLimit,float,hardness) DECLAREMEMBER(pJointLimit,float,restitution) DECLAREMEMBER(pJointLimit,float,value) DECLAREOBJECTTYPE(pJD6Drive) DECLARECTOR_0(__newpDrive) DECLAREMEMBER(pJD6Drive,float,damping) DECLAREMEMBER(pJD6Drive,float,spring) DECLAREMEMBER(pJD6Drive,float,forceLimit) DECLAREMEMBER(pJD6Drive,int,driveType) DECLAREOBJECTTYPE(pJD6SoftLimit) DECLARECTOR_0(__newpSoftLimit) DECLAREMEMBER(pJD6SoftLimit,float,damping) DECLAREMEMBER(pJD6SoftLimit,float,spring) DECLAREMEMBER(pJD6SoftLimit,float,value) DECLAREMEMBER(pJD6SoftLimit,float,restitution) DECLAREOBJECTTYPE(pSpring) DECLARECTOR_0(__newpSpring) //DECLARECTOR_3(__newpSpringSettings3,float,float,float) DECLAREMEMBER(pSpring,float,damper) DECLAREMEMBER(pSpring,float,spring) DECLAREMEMBER(pSpring,float,targetValue) DECLAREOBJECTTYPE(pMotor) DECLARECTOR_0(__newpMotor) DECLAREMEMBER(pMotor,float,maximumForce) DECLAREMEMBER(pMotor,float,targetVelocity) DECLAREMEMBER(pMotor,float,freeSpin) ////////////////////////////////////////////////////////////////////////// // // Serializer : // DECLAREPOINTERTYPE(pSerializer) DECLAREFUN_C_0(pSerializer*, GetSerializer) DECLAREMETHOD_2(pSerializer,void,overrideBody,pRigidBody*,int) DECLAREMETHOD_2(pSerializer,int,loadCollection,const char*,int) DECLAREMETHOD_1(pSerializer,int,saveCollection,const char*) DECLAREMETHOD_2(pSerializer,void,parseFile,const char*,int) ////////////////////////////////////////////////////////////////////////// // // Factory // ////////////////////////////////////////////////////////////////////////// // // ENUMERATION // DECLAREENUM("D6DriveType") DECLAREENUMVALUE("D6DriveType", "D6DT_Position" ,1 ) DECLAREENUMVALUE("D6DriveType", "D6DT_Velocity" ,2 ) DECLAREENUM("PForceMode") DECLAREENUMVALUE("PForceMode", "PFM_Force" , 0) DECLAREENUMVALUE("PForceMode", "PFM_Impulse" , 1) DECLAREENUMVALUE("PForceMode", "PFM_VelocityChange" , 2) DECLAREENUMVALUE("PForceMode", "PFM_SmoothImpulse" , 3) DECLAREENUMVALUE("PForceMode", "PFM_SmoothVelocityChange" , 4) DECLAREENUMVALUE("PForceMode", "PFM_Acceleration" , 5) DECLAREENUM("D6MotionMode") DECLAREENUMVALUE("D6MotionMode", "D6MM_Locked" , 0) DECLAREENUMVALUE("D6MotionMode", "D6MM_Limited" , 1) DECLAREENUMVALUE("D6MotionMode", "D6MM_Free" , 2) DECLAREENUM("JType") DECLAREENUMVALUE("JType", "JT_Any" , -1) DECLAREENUMVALUE("JType", "JT_Prismatic" , 0) DECLAREENUMVALUE("JType", "JT_Revolute" , 1) DECLAREENUMVALUE("JType", "JT_Cylindrical" , 2) DECLAREENUMVALUE("JType", "JT_Spherical" , 3) DECLAREENUMVALUE("JType", "JT_PointOnLine" , 4) DECLAREENUMVALUE("JType", "JT_PointInPlane" , 5) DECLAREENUMVALUE("JType", "JT_Distance" , 6) DECLAREENUMVALUE("JType", "JT_Pulley" , 7) DECLAREENUMVALUE("JType", "JT_Fixed" ,8 ) DECLAREENUMVALUE("JType", "JT_D6" ,9 ) ////////////////////////////////////////////////////////////////////////// // // Bindings for pVehicle related classes : // // DECLAREMETHOD_2(pFactory,pVehicle*,createVehicle,CK3dEntity*,pVehicleDesc) //DECLAREMETHOD_0(pVehicle,float,getWheelRollAngle) //DECLAREMETHOD_0(pVehicle,float,getRpm) ////////////////////////////////////////////////////////////////////////// // // JOINT CREATION // DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointDistance*,createDistanceJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,VxVector(),VxVector,VxVector(),float,0.0f,float,0.0f,pSpring,pSpring()) DECLAREMETHOD_5(pFactory,pJointD6*,createD6Joint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,bool) DECLAREMETHOD_2(pFactory,pJointFixed*,createFixedJoint,CK3dEntity*,CK3dEntity*) DECLAREMETHOD_3_WITH_DEF_VALS(pFactory,pRigidBody*,createBody,CK3dEntity*,NODEFAULT,pObjectDescr,NODEFAULT,CK3dEntity*,NULL) DECLAREMETHOD_2(pFactory,pRigidBody*,createRigidBody,CK3dEntity*,pObjectDescr&) DECLAREMETHOD_2(pFactory,bool,loadMaterial,pMaterial&,const char*) DECLAREMETHOD_2(pFactory,pMaterial,loadMaterial,const char*,int&) DECLAREMETHOD_2(pFactory,bool,loadFrom,pWheelDescr&,const char*) DECLAREMETHOD_5(pFactory,pWheel*,createWheel,CK3dEntity *,CK3dEntity*,pWheelDescr,pConvexCylinderSettings,VxVector) DECLAREMETHOD_6(pFactory,pJointPulley*,createPulleyJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointBall*,createBallJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointRevolute*,createRevoluteJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointPrismatic*,createPrismaticJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointCylindrical*,createCylindricalJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointPointInPlane*,createPointInPlaneJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointPointOnLine*,createPointOnLineJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_2(pFactory,pCloth*,createCloth,CK3dEntity*,pClothDesc) ////////////////////////////////////////////////////////////////////////// // // Cloth // DECLAREMETHOD_4(pCloth,void,attachToCore,CK3dEntity*,float,float,float) DECLAREMETHOD_2(pCloth,void,attachToShape,CK3dEntity*,pClothAttachmentFlag) ////////////////////////////////////////////////////////////////////////// // // MANAGER // DECLAREMETHOD_0(PhysicManager,pWorld*,getDefaultWorld) DECLAREMETHOD_1(PhysicManager,pRigidBody*,getBody,CK3dEntity*) DECLAREMETHOD_1(PhysicManager,pWorld*,getWorldByBody,CK3dEntity*) DECLAREMETHOD_1(PhysicManager,pWorld*,getWorld,CK_ID) DECLAREMETHOD_1(PhysicManager,int,getAttributeTypeByGuid,CKGUID) DECLAREMETHOD_1(CK3dEntity,CKBOOL,HasAttribute,int) DECLAREMETHOD_3_WITH_DEF_VALS(PhysicManager,pJoint*,getJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NULL,JType,JT_Any) // DECLAREMETHOD_0(PhysicManager,void,makeDongleTest) ////////////////////////////////////////////////////////////////////////// // // World // DECLAREMETHOD_1(pWorld,pRigidBody*,getBody,CK3dEntity*) DECLAREMETHOD_1(pWorld,pVehicle*,getVehicle,CK3dEntity*) DECLAREMETHOD_3(pWorld,pJoint*,getJoint,CK3dEntity*,CK3dEntity*,JType) DECLAREMETHOD_3(pWorld,void,setFilterOps,pFilterOp,pFilterOp,pFilterOp) DECLAREMETHOD_1(pWorld,void,setFilterBool,bool) DECLAREMETHOD_1(pWorld,void,setFilterConstant0,const pGroupsMask&) DECLAREMETHOD_1(pWorld,void,setFilterConstant1,const pGroupsMask&) // DECLAREMETHOD_5_WITH_DEF_VALS(pWorld,bool,raycastAnyBounds,const VxRay&,NODEFAULT,pShapesType,NODEFAULT,pGroupsMask,NODEFAULT,int,0xffffffff,float,NX_MAX_F32) DECLAREMETHOD_8(pWorld,bool,overlapSphereShapes,CK3dEntity*,const VxSphere&,CK3dEntity*,pShapesType,CKGroup*,int,const pGroupsMask*,BOOL) //(const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,unsigned int groups=0xffffffff, float maxDist=NX_MAX_F32); ////////////////////////////////////////////////////////////////////////// // // JOINT :: Revolute // DECLAREMETHOD_0(pJoint,pJointRevolute*,castRevolute) DECLAREMETHOD_1(pJointRevolute,void,setGlobalAnchor,const VxVector&) DECLAREMETHOD_1(pJointRevolute,void,setGlobalAxis,const VxVector&) DECLAREMETHOD_1(pJointRevolute,void,setSpring,pSpring) DECLAREMETHOD_1(pJointRevolute,void,setHighLimit,pJointLimit) DECLAREMETHOD_1(pJointRevolute,void,setLowLimit,pJointLimit) DECLAREMETHOD_1(pJointRevolute,void,setMotor,pMotor) DECLAREMETHOD_0(pJointRevolute,pSpring,getSpring) DECLAREMETHOD_0(pJointRevolute,pJointLimit,getLowLimit) DECLAREMETHOD_0(pJointRevolute,pJointLimit,getHighLimit) DECLAREMETHOD_0(pJointRevolute,pMotor,getMotor) DECLAREMETHOD_1(pJointRevolute,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT :: Ball // DECLAREMETHOD_0(pJoint,pJointBall*,castBall) DECLAREMETHOD_1(pJointBall,void,setAnchor,VxVector) DECLAREMETHOD_1(pJointBall,void,setSwingLimitAxis,VxVector) DECLAREMETHOD_1(pJointBall,bool,setSwingLimit,pJointLimit) DECLAREMETHOD_1(pJointBall,bool,setTwistHighLimit,pJointLimit) DECLAREMETHOD_1(pJointBall,bool,setTwistLowLimit,pJointLimit) DECLAREMETHOD_0(pJointBall,pJointLimit,getSwingLimit) DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistHighLimit) DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistLowLimit) DECLAREMETHOD_1(pJointBall,bool,setSwingSpring,pSpring) DECLAREMETHOD_1(pJointBall,bool,setTwistSpring,pSpring) DECLAREMETHOD_1(pJointBall,void,setJointSpring,pSpring) DECLAREMETHOD_0(pJointBall,pSpring,getSwingSpring) DECLAREMETHOD_0(pJointBall,pSpring,getTwistSpring) DECLAREMETHOD_0(pJointBall,pSpring,getJointSpring) DECLAREMETHOD_1(pJointBall,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT Prismatic // // DECLAREMETHOD_0(pJoint,pJointPrismatic*,castPrismatic) DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointPrismatic,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT Cylindrical // // DECLAREMETHOD_0(pJoint,pJointCylindrical*,castCylindrical) DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointCylindrical,void,enableCollision,int) ////////////////////////////////////////////////////////////////////////// // // JOINT Point In Plane // // DECLAREMETHOD_0(pJoint,pJointPointInPlane*,castPointInPlane) DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointPointInPlane,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT Point In Plane // // DECLAREMETHOD_0(pJoint,pJointPointOnLine*,castPointOnLine) DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointPointOnLine,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT BASE // // DECLAREMETHOD_1(pJoint,void,setLocalAnchor0,VxVector) DECLAREMETHOD_2(pJoint,void,setBreakForces,float,float) DECLAREMETHOD_2(pJoint,void,getBreakForces,float&,float&) DECLAREMETHOD_3(pJoint,int,addLimitPlane,VxVector,VxVector,float) DECLAREMETHOD_2_WITH_DEF_VALS(pJoint,void,setLimitPoint,VxVector,NODEFAULT,bool,true) DECLAREMETHOD_0(pJoint,void,purgeLimitPlanes) DECLAREMETHOD_0(pJoint,void,resetLimitPlaneIterator) DECLAREMETHOD_0(pJoint,int,hasMoreLimitPlanes) DECLAREMETHOD_3(pJoint,int,getNextLimitPlane,VxVector&,float&,float&) DECLAREMETHOD_0(pJoint,int,getType) ////////////////////////////////////////////////////////////////////////// // // JOINT :: DISTANCE // DECLAREMETHOD_0(pJoint,pJointDistance*,castDistanceJoint) DECLAREMETHOD_1(pJointDistance,void,setMinDistance,float) DECLAREMETHOD_1(pJointDistance,void,setMaxDistance,float) DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor0,VxVector) DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor1,VxVector) DECLAREMETHOD_1(pJointDistance,void,setSpring,pSpring) DECLAREMETHOD_0(pJointDistance,float,getMinDistance) DECLAREMETHOD_0(pJointDistance,float,getMaxDistance) DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor0) DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor1) DECLAREMETHOD_0(pJointDistance,pSpring,getSpring) DECLAREMETHOD_1(pJointDistance,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // <NAME> // DECLAREMETHOD_0(pJoint,pJointPulley*,castPulley) DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorA,VxVector) DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorB,VxVector) DECLAREMETHOD_1(pJointPulley,void,setPulleyA,VxVector) DECLAREMETHOD_1(pJointPulley,void,setPulleyB,VxVector) DECLAREMETHOD_1(pJointPulley,void,setStiffness,float) DECLAREMETHOD_1(pJointPulley,void,setRatio,float) DECLAREMETHOD_1(pJointPulley,void,setRigid,int) DECLAREMETHOD_1(pJointPulley,void,setDistance,float) DECLAREMETHOD_1(pJointPulley,void,setMotor,pMotor) DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorA) DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorB) DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyA) DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyB) DECLAREMETHOD_0(pJointPulley,float,getStiffness) DECLAREMETHOD_0(pJointPulley,float,getRatio) DECLAREMETHOD_0(pJointPulley,float,getDistance) DECLAREMETHOD_1(pJointPulley,void,enableCollision,bool) DECLAREMETHOD_0(pJointPulley,pMotor,getMotor) ////////////////////////////////////////////////////////////////////////// // // JOINT D6 // DECLAREMETHOD_0(pJoint,pJointD6*,castD6Joint) DECLAREMETHOD_1(pJointD6,void,setTwistMotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setSwing1MotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setSwing2MotionMode,D6MotionMode) DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) DECLAREMETHOD_1(pJointD6,void,setXMotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setYMotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setZMotionMode,D6MotionMode) DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) ////////////////////////////////////////////////////////////////////////// //softwLimits DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getLinearLimit) DECLAREMETHOD_1(pJointD6,int,setLinearLimit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing1Limit) DECLAREMETHOD_1(pJointD6,int,setSwing1Limit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing2Limit) DECLAREMETHOD_1(pJointD6,int,setSwing2Limit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistHighLimit) DECLAREMETHOD_1(pJointD6,int,setTwistHighLimit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistLowLimit) DECLAREMETHOD_1(pJointD6,int,setTwistLowLimit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6Drive,getXDrive) DECLAREMETHOD_1(pJointD6,int,setXDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getYDrive) DECLAREMETHOD_1(pJointD6,int,setYDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getZDrive) DECLAREMETHOD_1(pJointD6,int,setZDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getSwingDrive) DECLAREMETHOD_1(pJointD6,int,setSwingDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getTwistDrive) DECLAREMETHOD_1(pJointD6,int,setTwistDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getSlerpDrive) DECLAREMETHOD_1(pJointD6,int,setSlerpDrive,pJD6Drive) DECLAREMETHOD_1(pJointD6,void,setDrivePosition,VxVector) DECLAREMETHOD_1(pJointD6,void,setDriveRotation,VxQuaternion) DECLAREMETHOD_1(pJointD6,void,setDriveLinearVelocity,VxVector) DECLAREMETHOD_1(pJointD6,void,setDriveAngularVelocity,VxVector) DECLAREMETHOD_1(pJointD6,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // Rigid Body Exports // // /************************************************************************/ /* Forces */ /************************************************************************/ DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addForce,const VxVector&,NODEFAULT, PForceMode, 0,bool,true) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addTorque,const VxVector&,NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalForce,const VxVector&,NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalTorque,const VxVector&,NODEFAULT, PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtPos, const VxVector&,NODEFAULT,const VxVector&,NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtLocalPos,const VxVector,NODEFAULT, const VxVector&, NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtPos, const VxVector&, NODEFAULT,const VxVector&,NODEFAULT, PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtLocalPos, const VxVector&, NODEFAULT,const VxVector&, NODEFAULT,PForceMode,0,bool,true) /************************************************************************/ /* Momentum */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setAngularMomentum,const VxVector&) DECLAREMETHOD_1(pRigidBody,void,setLinearMomentum,const VxVector&) DECLAREMETHOD_0(pRigidBody,VxVector,getAngularMomentum) DECLAREMETHOD_0(pRigidBody,VxVector,getLinearMomentum) /************************************************************************/ /* Pose : */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setPosition,const VxVector&) DECLAREMETHOD_1(pRigidBody,void,setRotation,const VxQuaternion&) DECLAREMETHOD_1(pRigidBody,void,translateLocalShapePosition,VxVector) /************************************************************************/ /* Velocity : */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setLinearVelocity,const VxVector&) DECLAREMETHOD_1(pRigidBody,void,setAngularVelocity,const VxVector&) DECLAREMETHOD_0(pRigidBody,float,getMaxAngularSpeed) DECLAREMETHOD_0(pRigidBody,VxVector,getLinearVelocity) DECLAREMETHOD_0(pRigidBody,VxVector,getAngularVelocity) /************************************************************************/ /* Mass */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setMassOffset,VxVector) DECLAREMETHOD_1(pRigidBody,void,setMaxAngularSpeed,float) /************************************************************************/ /* Hull */ /************************************************************************/ DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) DECLAREMETHOD_0(pRigidBody,pWorld*,getWorld) DECLAREMETHOD_1(pRigidBody,pJoint*,isConnected,CK3dEntity*) //DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) DECLAREMETHOD_1_WITH_DEF_VALS(pRigidBody,float,getMass,CK3dEntity*,NULL) DECLAREMETHOD_0(pRigidBody,int,getHullType) DECLAREMETHOD_2(pRigidBody,void,setGroupsMask,CK3dEntity*,const pGroupsMask&) DECLAREMETHOD_0(pRigidBody,int,getFlags) DECLAREMETHOD_1(pRigidBody,VxVector,getPointVelocity,VxVector) DECLAREMETHOD_1(pRigidBody,VxVector,getLocalPointVelocity,VxVector) DECLAREMETHOD_0(pRigidBody,bool,isCollisionEnabled) DECLAREMETHOD_1(pRigidBody,void,setKinematic,int) DECLAREMETHOD_0(pRigidBody,int,isKinematic) DECLAREMETHOD_1(pRigidBody,void,enableGravity,int) DECLAREMETHOD_0(pRigidBody,bool,isAffectedByGravity) DECLAREMETHOD_1(pRigidBody,void,setSleeping,int) DECLAREMETHOD_0(pRigidBody,int,isSleeping) DECLAREMETHOD_1(pRigidBody,void,setLinearDamping,float) DECLAREMETHOD_1(pRigidBody,void,setAngularDamping,float) DECLAREMETHOD_1(pRigidBody,void,lockTransformation,BodyLockFlags) DECLAREMETHOD_1(pRigidBody,int,isBodyFlagOn,int) DECLAREMETHOD_1(pRigidBody,void,setSolverIterationCount,int) DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setCollisionsGroup,int,NODEFAULT,CK3dEntity*,) DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,enableCollision,bool,NODEFAULT,CK3dEntity*,NULL) DECLAREMETHOD_0(pRigidBody,int,getCollisionsGroup) DECLAREMETHOD_2(pRigidBody,int,updateMassFromShapes,float,float) DECLAREMETHOD_5_WITH_DEF_VALS(pRigidBody,int,addSubShape,CKMesh*,NULL,pObjectDescr,NODEFAULT,CK3dEntity*,NULL,VxVector,VxVector(),VxQuaternion,VxQuaternion()) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,int,removeSubShape,CKMesh*,NODEFAULT,float,0.0,float,0.0) STOPVSLBIND } <file_sep>swig.exe -c++ -csharp vtCSWindow.i <file_sep>#ifndef __PREREQS_H_ #define __PREREQS_H_ struct xNetworkSettings; class xNetInterface; class vtConnection; class xNetworkFactory; class xNetObject; class IMessages; class xDistributedClass; class xDistributed3DObjectClass; class IDistributedClasses; class xDistributedProperty; class xDistributedPropertyInfo; class xDistributedObject; class xDistributedClient; class xDistributed3DObject; struct x3DObjectData; class vtNetworkManager; class IDistributedObjects; class xPredictionSetting; //class Extrapolator; //class vtDistributedObjectsArrayType; namespace TNL { class NetInterface; class GhostConnection; class BitStream; } #include "tnlNetBase.h" #include <tnlString.h> //using namespace TNL; typedef TNL::StringPtr xNString; #include "stdlib.h" #include "map" #include <vector> #include <deque> #endif <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // MidiEvent // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "../MidiManager.h" CKERROR CreateMidiEventBehaviorProto(CKBehaviorPrototype **); int MidiEvent(const CKBehaviorContext& behcontext); CKERROR MidiEventCallBack(const CKBehaviorContext& behcontext); // CallBack Functioon /*******************************************************/ /* PROTO DECALRATION */ /*******************************************************/ CKObjectDeclaration *FillBehaviorMidiEventDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Midi Event"); od->SetDescription("Gets a Midi event ON/OFF."); od->SetCategory("Controllers/Midi"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7c652f90,0x64404377)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateMidiEventBehaviorProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } /*******************************************************/ /* PROTO CREATION */ /*******************************************************/ CKERROR CreateMidiEventBehaviorProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Midi Event"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("On"); proto->DeclareInput("Off"); proto->DeclareOutput("Activated"); proto->DeclareOutput("Deactivated"); proto->DeclareInParameter("Channel", CKPGUID_INT, "0"); proto->DeclareInParameter("Note 1", CKPGUID_INT, "0"); proto->DeclareLocalParameter(NULL, CKPGUID_BOOL, "FALSE"); // Combination was ok proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(MidiEvent); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_VARIABLEPARAMETERINPUTS)); proto->SetBehaviorCallbackFct( MidiEventCallBack ); *pproto = proto; return CK_OK; } /*******************************************************/ /* MAIN FUNCTION */ /*******************************************************/ int MidiEvent(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; if( beh->IsInputActive(1) ){ // OFF beh->ActivateInput(1, FALSE); return CKBR_OK; } CKBOOL combiWasOK = FALSE; if( beh->IsInputActive(0) ){ // ON beh->ActivateInput(0, FALSE); beh->SetLocalParameterValue(0, &combiWasOK); } else { beh->GetLocalParameterValue(0, &combiWasOK); } MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); // Channel int channel=0; beh->GetInputParameterValue(0, &channel); int note, count = beh->GetInputParameterCount(); //--- test if all input notes are activated or not for( int a=1 ; a<count ; a++ ){ beh->GetInputParameterValue(a, &note); if( !mm->IsNoteActive(note, channel) ) break; } if( a==count ){ // All notes are pressed if( !combiWasOK ){ beh->ActivateOutput(0); combiWasOK = TRUE; beh->SetLocalParameterValue(0, &combiWasOK); return CKBR_ACTIVATENEXTFRAME; } } else { // Not all notes are pressed if( combiWasOK ){ beh->ActivateOutput(1); combiWasOK = FALSE; beh->SetLocalParameterValue(0, &combiWasOK); return CKBR_ACTIVATENEXTFRAME; } } return CKBR_ACTIVATENEXTFRAME; } /*******************************************************/ /* CALLBACK */ /*******************************************************/ CKERROR MidiEventCallBack(const CKBehaviorContext& behcontext){ CKBehavior *beh = behcontext.Behavior; MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); switch( behcontext.CallbackMessage ){ case CKM_BEHAVIOREDITED: { int c_pin = beh->GetInputParameterCount(); char name[20]; CKParameterIn *pin; for( int a=2 ; a<c_pin ; a++){ pin = beh->GetInputParameter(a); sprintf( name, "Note %d", a); pin->SetName( name ); pin->SetGUID( CKPGUID_INT ); } } break; case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: { mm->AddMidiBBref(); } break; case CKM_BEHAVIORDETACH: { mm->RemoveMidiBBref(); } break; } return CKBR_OK; } <file_sep><?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <CodeBlocks_layout_file> <ActiveTarget name="Debug" /> <File name="..\..\..\Manager\IDistributedObjectsInterface.cpp" open="1" top="1" tabpos="1"> <Cursor position="5191" topLine="200" /> </File> <File name="..\..\..\Manager\xDistributed3DObjectClass.cpp" open="0" top="0" tabpos="0"> <Cursor position="167" topLine="0" /> </File> <File name="..\..\..\Manager\xDistributed3DObjectClass.h" open="0" top="0" tabpos="0"> <Cursor position="235" topLine="0" /> </File> </CodeBlocks_layout_file> <file_sep>/****************************************************************************** File : CustomPlayer.cpp Description: This file contains the CCustomPlayer class which is the "interface" with the Virtools SDK. All other files are Windows/MFC specific code. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ /* int le = GetLastError(); XString buf; buf.Format("le:%d",le); MessageBox(NULL,buf.Str(),"",1); */ #include "CPStdAfx.h" #include "CustomPlayer.h" #include "CustomPlayerApp.h" #include "CustomPlayerDefines.h" #include "CustomPlayerDialog.h" #if defined(CUSTOM_PLAYER_STATIC) // include file used for the static configuration #include "CustomPlayerStaticLibs.h" #include "CustomPlayerRegisterDlls.h" #include "CustomPlayerRegisterDllsExtra.h" #endif extern CCustomPlayerApp theApp; extern CCustomPlayer* thePlayer; extern CKERROR LoadCallBack(CKUICallbackStruct& loaddata,void*); int CCustomPlayer::InitEngine(HWND iMainWindow) { m_MainWindow = iMainWindow; // start the Virtools Engine CKStartUp(); // retrieve the plugin manager ... CKPluginManager* pluginManager = CKGetPluginManager(); // ... to intialize plugins ... if (!_InitPlugins(*pluginManager)) { MessageBox(NULL,UNABLE_TO_INIT_PLUGINS,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } // ... and the render engine. int renderEngine = _InitRenderEngines(*pluginManager); if (renderEngine==-1) { MessageBox(NULL,UNABLE_TO_LOAD_RENDERENGINE,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } XString inifile = CKGetStartPath(); inifile << "CompositionPrefs_R_Hi.ini"; CKERROR res = CKCreateContext(&m_CKContext,m_MainWindow,inifile.Str()); if (res!=CK_OK) { MessageBox(NULL,UNABLE_TO_INIT_CK,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } // retrieve the main managers which will be used by the player m_MessageManager = m_CKContext->GetMessageManager(); m_RenderManager = m_CKContext->GetRenderManager(); m_TimeManager = m_CKContext->GetTimeManager(); m_AttributeManager = m_CKContext->GetAttributeManager(); m_InputManager = (CKInputManager*)m_CKContext->GetManagerByGuid(INPUT_MANAGER_GUID); if (!m_MessageManager || !m_RenderManager || !m_TimeManager || !m_AttributeManager || !m_InputManager) { MessageBox(NULL,UNABLE_TO_INIT_MANAGERS,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } // initialize the display driver using the player configuration (resolution, rasterizer, ...) if (!_InitDriver()) { MessageBox(NULL,UNABLE_TO_INIT_DRIVER,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } return TRUE; } BOOL CCustomPlayer::InitPlayer(HWND iMainWindow, HWND iRenderWindow, int iConfig, const void* iData,int iDataSize) { // keep a reference on the main/render window m_MainWindow = iMainWindow; m_RenderWindow = iRenderWindow; // start the Virtools Engine //CKInitCustomPlayer(false); CKStartUp(); ////////////////////////////////////////////////////////////////////////// // we have unmet requirements ? XString errorText; int hasError = DoSystemCheck(errorText); ////////////////////////////////////////////////////////////////////////// // show splash when we have no error and we are not in the explicit configuration mode ( invoked by : "CustomPlayer.exe -c ") : if( GetPAppStyle()->UseSplash() && !hasError && PGetApplicationMode() != config ) { ShowSplash(); } // retrieve the plugin manager ... CKPluginManager* pluginManager = CKGetPluginManager(); ////////////////////////////////////////////////////////////////////////// // ... to intialize plugins ... if (!_InitPlugins(*pluginManager)) { MessageBox(NULL,UNABLE_TO_INIT_PLUGINS,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } ////////////////////////////////////////////////////////////////////////// // ... and the render engine. int renderEngine = _InitRenderEngines(*pluginManager); if (renderEngine==-1) { MessageBox(NULL,UNABLE_TO_LOAD_RENDERENGINE,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } ////////////////////////////////////////////////////////////////////////// // now create the CK context XString inifile = CKGetStartPath(); inifile << "CompositionPrefs_R_Hi.ini"; CKERROR res = CKCreateContext(&m_CKContext,m_MainWindow,inifile.Str()); if (res!=CK_OK) { MessageBox(NULL,UNABLE_TO_INIT_CK,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } #if defined(CUSTOM_PLAYER_STATIC) // if the player is not static char BehaviorPath[_MAX_PATH]; char szPath[_MAX_PATH]; VxGetModuleFileName(NULL,szPath,_MAX_PATH); CKPathSplitter ps(szPath); sprintf(BehaviorPath,"%s%s%s",ps.GetDrive(),ps.GetDir(),GetEPathProfile()->BehaviorPath.Str()); pluginManager->ParsePlugins(BehaviorPath); #endif ////////////////////////////////////////////////////////////////////////// // adding load callback if(GetPAppStyle()->UseSplash() && !m_LastError && PGetApplicationMode() != config ) { if (GetPAppStyle()->ShowLoadingProcess()) { m_CKContext->SetInterfaceMode(FALSE,LoadCallBack,NULL); } } // retrieve the main managers which will be used by the player m_MessageManager = m_CKContext->GetMessageManager(); m_RenderManager = m_CKContext->GetRenderManager(); m_TimeManager = m_CKContext->GetTimeManager(); m_AttributeManager = m_CKContext->GetAttributeManager(); m_EnginePointers.TheMessageManager = m_MessageManager; m_EnginePointers.TheRenderManager = m_RenderManager; m_EnginePointers.TheTimeManager = m_TimeManager; m_EnginePointers.TheCKContext = m_CKContext; //We have an error, show our dialog : if (hasError) { AfxInitRichEdit2(); CustomPlayerDialog k(NULL,CString(errorText.Str())); k.DoModal(); if (CPA_ABORT_ON_ERROR) { return FALSE; } } m_InputManager = (CKInputManager*)m_CKContext->GetManagerByGuid(INPUT_MANAGER_GUID); if (!m_MessageManager || !m_RenderManager || !m_TimeManager || !m_AttributeManager || !m_InputManager) { MessageBox(NULL,UNABLE_TO_INIT_MANAGERS,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } // initialize the display driver using the player configuration (resolution, rasterizer, ...) if (!_InitDriver()) { MessageBox(NULL,UNABLE_TO_INIT_DRIVER,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } PLoadResourcePaths(CUSTOM_PLAYER_CONFIG_FILE,"Textures",0); PLoadResourcePaths(CUSTOM_PLAYER_CONFIG_FILE,"Data",1); PLoadResourcePaths(CUSTOM_PLAYER_CONFIG_FILE,"Music",2); // now load the composition if (iDataSize) { // if iDataSize is not null it means the composition is already in memory if (_Load(iData,iDataSize)!=CK_OK) { MessageBox(NULL,"Unable to load composition from memory.","Initialization Error",MB_OK|MB_ICONERROR); return FALSE; } } else if (_Load((const char*)iData)!=CK_OK) { // else we load it from a file (iData contains the filename) MessageBox(NULL,"Unable to load composition from file.","Initialization Error",MB_OK|MB_ICONERROR); return FALSE; } //GetPlayer().HideSplash(); //show our dialog ? if (GetPAppStyle()->g_ShowDialog) { AfxInitRichEdit2(); CustomPlayerDialog k(NULL,CString(errorText.Str())); k.DoModal(); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // update of our member variables vtPlayer::Structs::xSEnginePointers* ep = GetPlayer().GetEnginePointers(); vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); m_WindowedHeight = ewinfo->g_HeightW; m_WindowedWidth = ewinfo->g_WidthW; m_FullscreenWidth = ewinfo->g_Width; m_FullscreenHeight = ewinfo->g_Height; if(ewinfo->g_GoFullScreen) m_Driver = ewinfo->g_FullScreenDriver; else m_Driver = ewinfo->g_WindowedDriver; m_FullscreenBpp = ewinfo->g_Bpp; ////////////////////////////////////////////////////////////////////////// CKVariableManager *vm = (CKVariableManager *)m_EnginePointers.TheCKContext->GetVariableManager(); vm->SetValue("CK2_3D/Antialias", GetEWindowInfo()->FSSA * 2 ); if(PGetApplicationMode() != config) { if (GetPlayer().GetPAppStyle()->IsRenderering()) { ////////////////////////////////////////////////////////////////////////// // create the render context if (GetEWindowInfo()->g_GoFullScreen) { // in fullscreen we specify the rendering size using a rectangle (CKRECT) CKRECT rect; rect.left = 0; rect.top = 0; rect.right = m_FullscreenWidth; rect.bottom = m_FullscreenHeight; // create the render context m_RenderContext = m_RenderManager->CreateRenderContext(m_RenderWindow,GetEWindowInfo()->g_FullScreenDriver,&rect,TRUE,m_FullscreenBpp); // set the position of the render window ::SetWindowPos(m_RenderWindow,NULL,0,0,m_FullscreenWidth,m_FullscreenHeight,SWP_NOMOVE|SWP_NOZORDER); // resize the render context if (m_RenderContext) { m_RenderContext->Resize(0,0,m_FullscreenWidth,m_FullscreenHeight); } } else { ////////////////////////////////////////////////////////////////////////// // [2/18/2008 mc007] // we only repositioning the window when we are not displayed by a hosting application like // a charp panel ! if (!GetPAppStyle()->g_OwnerDrawed) { LONG st = GetWindowLong(m_MainWindow,GWL_STYLE); st|=WS_THICKFRAME; st&=~WS_SIZEBOX; SetWindowLong(m_MainWindow,GWL_STYLE,st); //reposition the window m_MainWindowRect.left = (GetSystemMetrics(SM_CXSCREEN)-m_WindowedWidth)/2; m_MainWindowRect.right = m_WindowedWidth+m_MainWindowRect.left; m_MainWindowRect.top = (GetSystemMetrics(SM_CYSCREEN)-m_WindowedHeight)/2; m_MainWindowRect.bottom = m_WindowedHeight+m_MainWindowRect.top; BOOL ret = AdjustWindowRect(&m_MainWindowRect,WS_OVERLAPPEDWINDOW & ~(WS_SYSMENU|WS_SIZEBOX|WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_SIZEBOX),FALSE); ::SetWindowPos(m_MainWindow,0,m_MainWindowRect.left,m_MainWindowRect.top,m_MainWindowRect.right - m_MainWindowRect.left,m_MainWindowRect.bottom - m_MainWindowRect.top,NULL); // set the position of the render window ::SetWindowPos(m_RenderWindow,NULL,0,0,m_WindowedWidth,m_WindowedHeight,SWP_NOMOVE|SWP_NOZORDER); } // create the render context m_RenderContext = m_RenderManager->CreateRenderContext(m_RenderWindow,m_Driver,0,FALSE); // resize the render context if (m_RenderContext) { m_RenderContext->Resize(0,0,m_WindowedWidth,m_WindowedHeight); } } ////////////////////////////////////////////////////////////////////////// // when somebody changed any resolution in the configuration tab , we should update our windows : //store current size /* GetWindowRect(m_MainWindow,&m_MainWindowRect); LONG st = GetWindowLong(m_MainWindow,GWL_STYLE); st|=WS_THICKFRAME; st&=~WS_SIZEBOX; SetWindowLong(m_MainWindow,GWL_STYLE,st); //reposition the window m_MainWindowRect.left = (GetSystemMetrics(SM_CXSCREEN)-m_WindowedWidth)/2; m_MainWindowRect.right = m_WindowedWidth+m_MainWindowRect.left; m_MainWindowRect.top = (GetSystemMetrics(SM_CYSCREEN)-m_WindowedHeight)/2; m_MainWindowRect.bottom = m_WindowedHeight+m_MainWindowRect.top; BOOL ret = AdjustWindowRect(&m_MainWindowRect,WS_OVERLAPPEDWINDOW & ~(WS_SYSMENU|WS_SIZEBOX|WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_SIZEBOX),FALSE); ::SetWindowPos(m_MainWindow,0,m_MainWindowRect.left,m_MainWindowRect.top,m_MainWindowRect.right - m_MainWindowRect.left,m_MainWindowRect.bottom - m_MainWindowRect.top,NULL); // and set the position of the render window in the main window ::SetWindowPos(m_RenderWindow,NULL,0,0,m_WindowedWidth,m_WindowedHeight,SWP_NOMOVE|SWP_NOZORDER); m_RenderContext->Resize(0,0,GetEWindowInfo()->g_GoFullScreen ? m_FullscreenWidth : m_WindowedWidth, GetEWindowInfo()->g_GoFullScreen ? m_FullscreenHeight : m_WindowedHeight);*/ if (!m_RenderContext) { MessageBox(NULL,UNABLE_TO_CREATE_RENDERCONTEXT,INIT_ERROR,MB_OK|MB_ICONERROR); return FALSE; } ////////////////////////////////////////////////////////////////////////// // clear the render view m_RenderContext->Clear(); m_RenderContext->BackToFront(); m_RenderContext->Clear(); } // finalize the loading if (!_FinishLoad()) { return FALSE; } } return TRUE; } BOOL CCustomPlayer::_InitDriver() { int count = m_RenderManager->GetRenderDriverCount(); int i = 0; // first, we try to get exactly what is required int checkFlags = eFamily | eDirectXVersion | eSoftware; for (i=0;i<count;++i) { VxDriverDesc* desc = m_RenderManager->GetRenderDriverDescription(i); if (!desc) { continue; } if (_CheckDriver(desc,checkFlags)) { m_Driver = i; _CheckFullscreenDisplayMode(TRUE); return TRUE; } } if (m_RasterizerFamily == CKRST_OPENGL) { return FALSE; } // if we did not find a driver, // we only check family and software flags checkFlags &= ~eDirectXVersion; for (i=0;i<count;++i) { VxDriverDesc* desc = m_RenderManager->GetRenderDriverDescription(i); if (!desc) { continue; } if (_CheckDriver(desc,checkFlags)) { m_Driver = i; _CheckFullscreenDisplayMode(TRUE); return TRUE; } } return FALSE; } BOOL CCustomPlayer::_InitPlugins(CKPluginManager& iPluginManager) { char szPath[_MAX_PATH]; char BehaviorPath[_MAX_PATH]; #if !defined(CUSTOM_PLAYER_STATIC) // if the player is not static char PluginPath[_MAX_PATH]; char RenderPath[_MAX_PATH]; char ManagerPath[_MAX_PATH]; VxGetModuleFileName(NULL,szPath,_MAX_PATH); CKPathSplitter ps(szPath); sprintf(PluginPath,"%s%s%s",ps.GetDrive(),ps.GetDir(),GetEPathProfile()->PluginPath.Str()); sprintf(RenderPath,"%s%s%s",ps.GetDrive(),ps.GetDir(),GetEPathProfile()->RenderPath.Str()); sprintf(ManagerPath,"%s%s%s",ps.GetDrive(),ps.GetDir(),GetEPathProfile()->ManagerPath.Str()); sprintf(BehaviorPath,"%s%s%s",ps.GetDrive(),ps.GetDir(),GetEPathProfile()->BehaviorPath.Str()); // we initialize plugins by parsing directories iPluginManager.ParsePlugins(RenderPath); iPluginManager.ParsePlugins(ManagerPath); iPluginManager.ParsePlugins(BehaviorPath); iPluginManager.ParsePlugins(PluginPath); #else // else if the player is static // we initialize plugins by manually register them // for an exemple look at CustomPlayerRegisterDlls.h CustomPlayerRegisterRenderEngine(iPluginManager); CustomPlayerRegisterReaders(iPluginManager); CustomPlayerRegisterManagers(iPluginManager); CustomPlayerRegisterBehaviors(iPluginManager); CustomPlayerRegisterBehaviorsExtra(iPluginManager); VxGetModuleFileName(NULL,szPath,_MAX_PATH); CKPathSplitter ps(szPath); sprintf(BehaviorPath,"%s%s%s",ps.GetDrive(),ps.GetDir(),GetEPathProfile()->BehaviorPath.Str()); //iPluginManager.ParsePlugins(BehaviorPath); #endif return TRUE; } int CCustomPlayer::_InitRenderEngines(CKPluginManager& iPluginManager) { // here we look for the render engine (ck2_3d) int count = iPluginManager.GetPluginCount(CKPLUGIN_RENDERENGINE_DLL); for (int i=0;i<count;i++) { CKPluginEntry* desc = iPluginManager.GetPluginInfo(CKPLUGIN_RENDERENGINE_DLL,i); CKPluginDll* dll = iPluginManager.GetPluginDllInfo(desc->m_PluginDllIndex); #if !defined(CUSTOM_PLAYER_STATIC) XWORD pos = dll->m_DllFileName.RFind(DIRECTORY_SEP_CHAR); if (pos==XString::NOTFOUND) continue; XString str = dll->m_DllFileName.Substring(pos+1); if (strnicmp(str.CStr(),"ck2_3d",strlen("ck2_3d"))==0) return i; #else if (dll->m_DllFileName.ICompare("ck2_3d")==0) return i; #endif } return -1; } <file_sep>#include "ISession.h" #include "xDistributedSessionClass.h" #include "xDistributedSession.h" #include "IDistributedObjectsInterface.h" #include "xNetInterface.h" #include "xDistributedClient.h" #include "xDistributedInteger.h" #include "xLogger.h" #include "vtLogTools.h" void ISession::deleteSession(int sessionID) { xNetInterface *netInterface = getNetInterface(); if ( netInterface && netInterface->IsServer()) { xDistributedSession *session = get(sessionID); if (session) { IDistributedObjects *doInterface = netInterface->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject *distObject = *begin; if (distObject) { xDistributedClass *_class = distObject->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT ) { xDistributedClient *distClient = static_cast<xDistributedClient*>(distObject); if (distClient && distClient->getSessionID() == sessionID ) { distClient->setSessionID(-1); disableFlag(distClient->getClientFlags(),E_CF_SESSION_JOINED); } } } } begin++; } doInterface->deleteObject((xDistributedObject*)session); }else xLogger::xLog(XL_START,ELOGERROR,E_LI_SESSION,"couldn't find session %d",sessionID); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void ISession::unlockSession(int userID,int sessionID) { xNetInterface *netInterface = getNetInterface(); if ( netInterface && !netInterface->IsServer() && netInterface->isValid()) { xDistributedSession *session = get(sessionID); if ( session) { if (session->getUserID() != userID) { xLogger::xLog(XL_START,ELOGERROR,E_LI_SESSION,"User %d must be session master !",userID); return; } int sessionLocked = 0; xDistributedInteger *pLocked= (xDistributedInteger *)session->getProperty(E_DC_S_NP_LOCKED); pLocked->updateValue(sessionLocked,0); pLocked->setFlags(E_DP_NEEDS_SEND); return ; } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void ISession::lockSession(int userID,int sessionID) { xNetInterface *netInterface = getNetInterface(); if ( netInterface && !netInterface->IsServer() && netInterface->isValid()) { xDistributedSession *session = get(sessionID); if ( session) { if (session->getUserID() != userID) { xLogger::xLog(XL_START,ELOGERROR,E_LI_SESSION,"User %d must be session master !",userID); return; } int sessionLocked = 1; xDistributedInteger *pLocked= (xDistributedInteger *)session->getProperty(E_DC_S_NP_LOCKED); pLocked->updateValue(sessionLocked,0); pLocked->setFlags(E_DP_NEEDS_SEND); return ; } } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int ISession::removeClient(xDistributedClient*client,int sessionID,bool destroy/* =false */) { xNetInterface *netInterface = getNetInterface(); if (client && netInterface && !netInterface->IsServer() && netInterface->isValid()) { vtConnection *con = netInterface->getConnection(); xDistributedSession *session = get(sessionID); xDistributedClient *myClient = netInterface->getMyClient(); if ( con && session && myClient ) { if (session->getUserID() !=myClient->getUserID() && myClient->getUserID()!=client->getUserID() ) { xLogger::xLog(XL_START,ELOGERROR,E_LI_SESSION,"You must be session master to remove a client !"); return -1; } xLogger::xLog(XL_START,ELOGINFO,E_LI_SESSION,"Removing user :%d from session %d",client->getUserID(),sessionID); ////////////////////////////////////////////////////////////////////////// con->c2sLeaveSession_RPC(client->getUserID(),sessionID,destroy); client->getClientFlags().set(1 << E_CF_DELETING,true); client->getClientFlags().set(1 << E_CF_DELETED,false); } }else { return -1; } ////////////////////////////////////////////////////////////////////////// //its our self who leaves the session //we must remove all other clients from the dist array : xDistributedClient *myClient = netInterface->getMyClient(); if (myClient && myClient->getUserID() == client->getUserID() && netInterface->getCurrentSession() ) { IDistributedObjects *doInterface = netInterface->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = netInterface->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject *distObject = *begin; if (distObject) { xDistributedClass *_class = distObject->getDistributedClass(); if (_class) { if (_class->getEnitityType() == E_DC_BTYPE_CLIENT ) { xDistributedClient *distClient = static_cast<xDistributedClient*>(distObject); if (distClient) { if (distClient->getUserID() != myClient->getUserID() && distClient->getSessionID()==sessionID ) { distClient->getClientFlags().set(1 << E_CF_DELETING,true); distClient->getClientFlags().set(1 << E_CF_DELETED,false); } } } } } begin++; } } return 0; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int ISession::joinClient(xDistributedClient*client, int sessionID,xNString password) { xNetInterface *netInterface = getNetInterface(); if (netInterface && !netInterface->IsServer() && netInterface->isValid()) { xDistributedSession *session = get(sessionID); if (session) { vtConnection *con = netInterface->getConnection(); if ( con) { con->c2sJoinSession_RPC(client->getUserID(),sessionID,password); return 0; } } } return -1; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedSession*ISession::get(int sessionID) { if (!getNetInterface()) { return NULL; } if (!getNetInterface()->getDistributedObjects())return NULL; xDistributedObjectsArrayType *distObjects = getNetInterface()->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj && dobj->getDistributedClass() && dobj->getDistributedClass()->getEnitityType() == E_DC_BTYPE_SESSION ) { xDistributedSession *session = static_cast<xDistributedSession*>(dobj); if (session && session->getSessionID() == sessionID) return session; } begin++; } return NULL; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedSession*ISession::getByUserID(int userID) { if (!getNetInterface()) { return NULL; } if (!getNetInterface()->getDistributedObjects())return NULL; return static_cast<xDistributedSession*>(getNetInterface()->getDistObjectInterface()->getByUserID(userID,E_DC_BTYPE_SESSION)); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ xDistributedSession* ISession::get(xNString name) { if (!getNetInterface()) { return NULL; } if (!getNetInterface()->getDistributedObjects())return NULL; xDistributedObjectsArrayType *distObjects = getNetInterface()->getDistributedObjects(); return static_cast<xDistributedSession*>(getNetInterface()->getDistObjectInterface()->get(name,E_DC_BTYPE_SESSION)); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int ISession::create(xNString name,int maxUsers,xNString password,int type) { int result = -1 ; if (getNetInterface() && getNetInterface()->isValid() && !getNetInterface()->IsServer() ) { vtConnection *con = getNetInterface()->getConnection(); con->c2sCreateSession_RPC(name,type,maxUsers,password); } return result ; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pWorldSettings.h" #include <assert.h> std::vector<pDominanceSetupItem*>&_getValidDominanceGroups(std::vector<pDominanceSetupItem*>&_inputGroups,pDominanceSetupItem *testItem) { std::vector<pDominanceSetupItem*> result; if (!_inputGroups.size()) return result; /* g1A + g1A g1A != g1B ! g2A + g2B 1 2 3 1 : 1 - 2 2 : 1 - 3 */ for (int i = 0 ; i < _inputGroups.size() ; i++) { pDominanceSetupItem* cItem =_inputGroups[i]; if ( cItem == testItem ) { result.push_back(cItem); continue; } if ( cItem->dominanceGroup0 != testItem->dominanceGroup0 ) { } } } void pWorld::_checkForDominanceConstraints() { #ifndef _DEBUG assert(getReference()); assert(getScene()); #endif int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS); if (!getReference()->HasAttribute(att)) return; CKParameterOut *domPar = getReference()->GetAttributeParameter(att); if(!domPar) return; using namespace vtTools::ParameterTools; using namespace vtTools::AttributeTools; CKParameterOut *d1 = GetParameterFromStruct(domPar,PS_WDS_ITEM1); CKParameterOut *d2 = GetParameterFromStruct(domPar,PS_WDS_ITEM2); CKParameterOut *d3 = GetParameterFromStruct(domPar,PS_WDS_ITEM3); CKParameterOut *d4 = GetParameterFromStruct(domPar,PS_WDS_ITEM4); CKParameterOut *d5 = GetParameterFromStruct(domPar,PS_WDS_ITEM5); pDominanceSetupItem item1; pDominanceSetupItem item2; pDominanceSetupItem item3; pDominanceSetupItem item4; pDominanceSetupItem item5; int error = pFactory::Instance()->copyTo(d1,item1); error = pFactory::Instance()->copyTo(d2,item2); error = pFactory::Instance()->copyTo(d3,item3); error = pFactory::Instance()->copyTo(d4,item4); error = pFactory::Instance()->copyTo(d5,item5); std::vector<pDominanceSetupItem*> allDominanceItems; //################################################################ // // gather all in an array // int a = item1.dominanceGroup0; int a1 = item1.dominanceGroup1; if (item1.dominanceGroup0 !=0 && item1.dominanceGroup1 !=0 && (item1.dominanceGroup0 != item1.dominanceGroup1 ) ) allDominanceItems.push_back(&item1); if (item2.dominanceGroup0 !=0 && item2.dominanceGroup1 !=0 && (item2.dominanceGroup0 != item1.dominanceGroup1 ) ) allDominanceItems.push_back(&item2); if (item3.dominanceGroup0 !=0 && item3.dominanceGroup1 !=0 && (item3.dominanceGroup0 != item3.dominanceGroup1 ) ) allDominanceItems.push_back(&item3); if (item4.dominanceGroup0 !=0 && item4.dominanceGroup1 !=0 && (item4.dominanceGroup0 != item4.dominanceGroup1 ) ) allDominanceItems.push_back(&item4); if (item5.dominanceGroup0 !=0 && item5.dominanceGroup1 !=0 && (item5.dominanceGroup0 != item5.dominanceGroup1 ) ) allDominanceItems.push_back(&item5); //std::vector<pDominanceSetupItem*>_validDominanceItems1 = _getValidDominanceGroups(allDominanceItems,&item1); //int s = _validDominanceItems1.size(); for (int i = 0 ; i < allDominanceItems.size() ; i++) { pDominanceSetupItem* cItem = allDominanceItems[i]; NxConstraintDominance cD1( cItem->constraint.dominanceA , cItem->constraint.dominanceB ); getScene()->setDominanceGroupPair(cItem->dominanceGroup0, cItem->dominanceGroup1,cD1); } } namespace vtAgeia { pWorldSettings::pWorldSettings() : m_Gravity(VxVector(0.0f,-9.81f,0.0f)) , m_SkinWith(0.1) { } }<file_sep>#include "StdAfx.h" #include "pVehicleAll.h" // Paint the stub wheel? //#define DO_PAINT_STUB #define DEF_LOCK 2 #define DEF_RADIUS .20 #define DEF_XA 20 // Input scaling //#define MAX_INPUT 1000 void pVehicleSteer::setToDefault() { radius = 10.0; xa = 0.0f; lock = 80.0f; } pVehicleSteer::pVehicleSteer(pVehicle *_car) { car=_car; angle=0; lock=5; xa=0; position.Set(0,0,0); radius=DEF_RADIUS; axisInput=0; } pVehicleSteer::~pVehicleSteer() { } /* bool pVehicleSteer::Load(QInfo *info,cstring path) // 'path' may be 0, in which case the default "steer" is used { char buf[128]; if(!path)path="steer"; // Location sprintf(buf,"%s.x",path); position.x=info->GetFloat(buf); sprintf(buf,"%s.y",path); position.y=info->GetFloat(buf); sprintf(buf,"%s.z",path); position.z=info->GetFloat(buf); sprintf(buf,"%s.radius",path); radius=info->GetFloat(buf,DEF_RADIUS); sprintf(buf,"%s.xa",path); xa=info->GetFloat(buf,DEF_XA); // Physical attribs sprintf(buf,"%s.lock",path); lock=info->GetFloat(buf,DEF_LOCK)/RR_RAD_DEG_FACTOR; // Model (was new'ed in the ctor) model->Load(info,path); if(!model->IsLoaded()) { // Stub gfx quad=gluNewQuadric(); } //qdbg("RSteer: r=%f, xa=%f\n",radius,xa); return TRUE; } */ /******* * Dump * *******/ /* bool RSteer::LoadState(QFile *f) { f->Read(&angle,sizeof(angle)); // 'axisInput'? return TRUE; } bool RSteer::SaveState(QFile *f) { f->Write(&angle,sizeof(angle)); return TRUE; } */ /********** * Attribs * **********/ /******** * Paint * ********/ /********** * Animate * **********/ void pVehicleSteer::Integrate() { //qdbg("RSteer: steerPos=%d => angle=%f deg\n",axisInput,angle*RR_RAD_DEG_FACTOR); } /******** * Input * ********/ void pVehicleSteer::SetInput(int steerPos) // 'steerPos' is the angle of the input steering wheel // ranging from -1000..+1000 { float a; // Clip if(steerPos<-1000) steerPos=-1000; else if(steerPos>1000) steerPos=1000; axisInput=steerPos; // Take controller position a=((float)axisInput)*lock/1000.0; //qdbg("RSteer: axisInput=%d, a=%f,lock=%f\n",axisInput,a,lock); // Set this directly as the steering wheel's angles // But notice that because of counterclockwise angles being >0, // the sign is reversed angle=a; } <file_sep>static char* sErrorStrings[]= { "OK", "\t Intern :", "\t No connection :", "\t Not joined to a session:", "\t Session needs right password:", "\t Session is locked:", "\t Session already exists:", "\t Session is full:", "\t You must be session master:", "\t Invalid parameter :", "\t There is not such user :", "\t Distributed class already exists :", "\t Couldn't connect to any server :", "\t You already joined to a session :", "\t No such session :" };<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "NXU_helper.h" // NxuStream helper functions. #include "NXU_PhysicsInstantiator.h" void pRigidBody::updateWheels(float step) { NxVec3 _localVelocity; bool _breaking=false; /* _computeMostTouchedActor(); NxVec3 relativeVelocity; if (_mostTouchedActor == NULL || !_mostTouchedActor->isDynamic()) { relativeVelocity = getActor()->getLinearVelocity(); } else { relativeVelocity = getActor()->getLinearVelocity() - _mostTouchedActor->getLinearVelocity(); } NxQuat rotation = getActor()->getGlobalOrientationQuat(); NxQuat global2Local; _localVelocity = relativeVelocity; rotation.inverseRotate(_localVelocity); char master[512]; */ int nbShapes = getActor()->getNbShapes(); NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *sinfo = static_cast<pSubMeshInfo*>(s->userData); if (sinfo && sinfo->wheel !=NULL) { pWheel *wheel = sinfo->wheel; pWheel2* wheel2 = dynamic_cast<pWheel2*>(wheel); if (wheel->getWheelFlag(WF_VehicleControlled)) { continue; } wheel->_tick(step / GetPMan()->GetContext()->GetTimeManager()->GetTimeScaleFactor()); /* NxWheelShape *wShape = wheel2->getWheelShape(); if (!wShape) continue; ////////////////////////////////////////////////////////////////////////// // // // NxWheelContactData wcd; NxShape* contactShape = wShape->getContact(wcd); if (contactShape) { NxVec3 relativeVelocity; if ( !contactShape->getActor().isDynamic()) { relativeVelocity = getActor()->getLinearVelocity(); } else { relativeVelocity = getActor()->getLinearVelocity() - contactShape->getActor().getLinearVelocity(); } NxQuat rotation = getActor()->getGlobalOrientationQuat(); _localVelocity = relativeVelocity; rotation.inverseRotate(_localVelocity); _breaking = NxMath::abs(_localVelocity.z) < ( 0.1 ); // wShape->setAxleSpeed() } float rollAngle = wheel2->getWheelRollAngle(); rollAngle+=wShape->getAxleSpeed() * (step* 0.01f); while (rollAngle > NxTwoPi) //normally just 1x rollAngle-= NxTwoPi; while (rollAngle< -NxTwoPi) //normally just 1x rollAngle+= NxTwoPi; wheel2->setWheelRollAngle(rollAngle); NxMat34& wheelPose = wShape->getGlobalPose(); NxReal stravel = wShape->getSuspensionTravel(); NxReal radius = wShape->getRadius(); //have ground contact? if( contactShape && wcd.contactPosition <= (stravel + radius) ) { wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + wheel2->getRadius(), wheelPose.t.z ); } else { wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - wheel2->getSuspensionTravel(), wheelPose.t.z ); } float rAngle = wheel2->getWheelRollAngle(); float steer = wShape->getSteerAngle(); NxMat33 rot, axisRot, rollRot; rot.rotY( wShape->getSteerAngle() ); axisRot.rotY(0); rollRot.rotX(rAngle); wheelPose.M = rot * wheelPose.M * axisRot * rollRot; wheel2->setWheelPose(wheelPose); */ } } } /* //motorTorque *= 0.1f; brakeTorque *= 500.0f; if(handBrake && getWheelFlag(E_WF_AFFECTED_BY_HANDBRAKE)) brakeTorque = 1000.0f; if(getWheelFlag(E_WF_ACCELERATED)) mWheelShape->setMotorTorque(motorTorque); mWheelShape->setBrakeTorque(brakeTorque); mWheelPose = mWheelShape->getGlobalPose(); NxWheelContactData wcd; NxShape* s = mWheelShape->getContact(wcd); NxReal stravel = mWheelShape->getSuspensionTravel(); NxReal radius = mWheelShape->getRadius(); //have ground contact? if( s && wcd.contactPosition <= (stravel + radius) ) { mWheelPose.t = NxVec3( mWheelPose.t.x, wcd.contactPoint.y + radius, mWheelPose.t.z ); } else { mWheelPose.t = NxVec3( mWheelPose.t.x, mWheelPose.t.y - stravel, mWheelPose.t.z ); } NxMat33 rot, axisRot, rollRot; rot.rotY( mWheelShape->getSteerAngle() ); //rot.rotX(0); axisRot.rotY(0); rollRot.rotX(_wheelRollAngle); mWheelPose.M = rot * mWheelPose.M * axisRot * rollRot; */ } bool pRigidBody::hasWheels() { bool result = false; if (!getActor()) { return false; } int nbShapes = getActor()->getNbShapes(); NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *sinfo = static_cast<pSubMeshInfo*>(s->userData); if (sinfo && sinfo->wheel !=NULL) { return true; } } } return result; } int pRigidBody::getNbWheels() { int result = 0; if (!getActor()) { return NULL; } int nbShapes = getActor()->getNbShapes(); NxShape ** slist = (NxShape **)getActor()->getShapes(); for (NxU32 j=0; j<nbShapes; j++) { NxShape *s = slist[j]; if (s) { pSubMeshInfo *sinfo = static_cast<pSubMeshInfo*>(s->userData); if (sinfo && sinfo->wheel !=NULL) { result ++; } } } return result; } pWheel2 *pRigidBody::getWheel2(CK3dEntity* subShapeReference) { return static_cast<pWheel2*>(getWheel(subShapeReference)); } pWheel *pRigidBody::getWheel(CK3dEntity* subShapeReference) { pWheel *result = NULL; if (!subShapeReference) { return result; } NxShape *subShape = _getSubShapeByEntityID(subShapeReference->GetID()); if (!subShape) return result; pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(subShape->userData); if (sInfo && sInfo->wheel) { return sInfo->wheel; } /* NxWheelShape *wheel = static_cast<NxWheelShape*>(subShape->isWheel()); if (wheel) { pSubMeshInfo *sInfo = static_cast<pSubMeshInfo*>(subShape->userData); if (sInfo && sInfo->wheel) { return sInfo->wheel; } } */ return result; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtStructHelper.h" #include "vtAttributeHelper.h" using namespace vtTools::AttributeTools; int PhysicManager::getAttributeTypeByGuid(CKGUID guid) { CKContext *ctx = GetPMan()->GetContext(); CKAttributeManager *attMan = ctx->GetAttributeManager(); CKParameterManager *parMan = ctx->GetParameterManager(); int cCount = attMan->GetAttributeCount(); for(int i = 0 ; i < cCount ; i++) { CKSTRING name = attMan->GetAttributeNameByType(i); if ( parMan->ParameterTypeToGuid(attMan->GetAttributeParameterType(i)) == guid ) { return i; } } return -1; } void PhysicManager::_RegisterDynamicEnumeration(XString file,XString enumerationName,CKGUID enumerationGuid,PFEnumStringFunction enumFunc,BOOL hidden) { TiXmlDocument * defaultDoc = loadDefaults(file.Str()); if (!defaultDoc) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config :PhysicDefaults.xml: failed"); } CKParameterManager *pm = m_Context->GetParameterManager(); CKAttributeManager* attman = m_Context->GetAttributeManager(); if (!getCurrentFactory()) { pFactory *factory = new pFactory(this,getDefaultConfig()); setCurrentFactory(factory); } pFactory *factory = pFactory::Instance(); XString outList; if (defaultDoc) outList = (factory->*enumFunc)(getDefaultConfig()); if (!outList.Length()) outList<< "None=0"; CKParameterType pType = pm->ParameterGuidToType(enumerationGuid); if (pType==-1) pm->RegisterNewEnum(enumerationGuid,enumerationName.Str(),outList.Str()); else{ pm->ChangeEnumDeclaration(enumerationGuid,outList.Str()); } CKParameterTypeDesc* param_type = pm->GetParameterTypeDescription(enumerationGuid); if (param_type && hidden) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"%s settings from xml detected : %s",enumerationName.Str(),outList.Str()); } void PhysicManager::_RegisterDynamicParameters() { TiXmlDocument * defaultDoc = loadDefaults("PhysicDefaults.xml"); if (!defaultDoc) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config :PhysicDefaults.xml: failed"); } //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Default xml configuration loaded"); CKParameterManager *pm = m_Context->GetParameterManager(); CKAttributeManager* attman = m_Context->GetAttributeManager(); if (!getCurrentFactory()) { pFactory *factory = new pFactory(this,getDefaultConfig()); setCurrentFactory(factory); } int pType = 0; ////////////////////////////////////////////////////////////////////////// // // Material ! // /* XString materialList; if (defaultDoc) { materialList = pFactory::Instance()->_getMaterialsAsEnumeration(getDefaultConfig()); }else{ materialList << "None=0"; } int pType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); if (pType==-1) pm->RegisterNewEnum(VTE_XML_MATERIAL_TYPE,"pMaterialType",materialList.Str()); else{ pm->ChangeEnumDeclaration(VTE_XML_MATERIAL_TYPE,materialList.Str()); } xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"materials : %s",materialList.Str()); */ _RegisterDynamicEnumeration("PhysicDefaults.xml","pMaterialType",VTE_XML_MATERIAL_TYPE,&pFactory::_getMaterialsAsEnumeration,true); _RegisterDynamicEnumeration("PhysicDefaults.xml","pBodyXMLInternalLink",VTS_PHYSIC_ACTOR_XML_SETTINGS_INTERN,&pFactory::_getBodyXMLInternalEnumeration,false); _RegisterDynamicEnumeration("PhysicDefaults.xml","pBodyXMLExternalLink",VTS_PHYSIC_ACTOR_XML_SETTINGS_EXTERN,&pFactory::_getBodyXMLExternalEnumeration,false); ////////////////////////////////////////////////////////////////////////// // // Vehicle Settings // XString vSListStr; if (defaultDoc) vSListStr= pFactory::Instance()->_getVehicleSettingsAsEnumeration(getDefaultConfig()); if (!vSListStr.Length()) vSListStr << "None=0"; pType = pm->ParameterGuidToType(VTE_XML_VEHICLE_SETTINGS); if (pType==-1) pm->RegisterNewEnum(VTE_XML_VEHICLE_SETTINGS,"pVehicleSettingsLink",vSListStr.Str()); else{ pm->ChangeEnumDeclaration(VTE_XML_VEHICLE_SETTINGS,vSListStr.Str()); } xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"vehicle settings : %s",vSListStr.Str()); ////////////////////////////////////////////////////////////////////////// // // Wheel Settings // XString wSListStr; if (defaultDoc) wSListStr = pFactory::Instance()->_getVehicleWheelAsEnumeration(getDefaultConfig()); if (!wSListStr.Length()) wSListStr << "None=0"; pType = pm->ParameterGuidToType(VTE_XML_WHEEL_SETTINGS); if (pType==-1) pm->RegisterNewEnum(VTE_XML_WHEEL_SETTINGS,"pWheelSettingsLink",wSListStr.Str()); else{ pm->ChangeEnumDeclaration(VTE_XML_WHEEL_SETTINGS,wSListStr.Str()); } xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"wheel vehicle settings : %s",wSListStr.Str()); CKParameterTypeDesc* param_type; param_type=pm->GetParameterTypeDescription(VTE_XML_WHEEL_SETTINGS); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; ////////////////////////////////////////////////////////////////////////// // // Wheel Tire Function // XString wTListStr; if (defaultDoc) wTListStr = pFactory::Instance()->_getVehicleTireFunctionAsEnumeration(getDefaultConfig()); if (!wTListStr.Length()) wTListStr << "None=0"; pType = pm->ParameterGuidToType(VTE_XML_TIRE_SETTINGS); if (pType==-1) pm->RegisterNewEnum(VTE_XML_TIRE_SETTINGS,"pWheelSettingsLink",wTListStr.Str()); else{ pm->ChangeEnumDeclaration(VTE_XML_TIRE_SETTINGS,wTListStr.Str()); } xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"wheel tire force settings : %s",wTListStr.Str()); param_type=pm->GetParameterTypeDescription(VTE_XML_TIRE_SETTINGS); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; //_getVehicleTireFunctionAsEnumeration /*param_type=pm->GetParameterTypeDescription(CKPGUID_EVOLUTIONS); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; */ _RegisterDynamicEnumeration("PhysicDefaults.xml","pMaterialType",VTE_XML_MATERIAL_TYPE,&pFactory::_getMaterialsAsEnumeration,true); } void recheckWorldsFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg) { int s = GetPMan()->getNbObjects(); if (AttribType == GetPMan()->GetPAttribute()) { pRigidBody *body = body = GetPMan()->getBody(pFactory::Instance()->getMostTopParent((CK3dEntity*)obj)); if (body) { if (Set) if (!body->isSubShape(obj)) body->_checkForNewSubShapes(); else body->_checkForRemovedSubShapes(); } } //CKParameterOut *pout = obj->GetAttributeParameter(GetPMan()->att_physic_object); } using namespace vtTools::ParameterTools; vtTools::ParameterTools::StructurMember PBRigidBodyMemberMap[] = { STRUCT_ATTRIBUTE(VTE_COLLIDER_TYPE,"Geometry","Sphere"), STRUCT_ATTRIBUTE(VTF_BODY_FLAGS,"Physic Flags","Moving Object,World Gravity,Enabled,Collision"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Density","1.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Skin Width","-1.0"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Mass Offset","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Pivot Offset","0.0,0.0,0.0"), STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Hierarchy","FALSE"), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"World","pDefaultWorld"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Total Mass","-1.0"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"New Density","-1.0"), STRUCT_ATTRIBUTE(CKPGUID_INT,"Collision Group","0"), }; //pm->RegisterNewStructure(VTS_PHYSIC_PARAMETER,"pObject", ",Mass Offset,Pivot Offset,Hierarchy,World,New Density,Total Mass,Collision Group", //VTE_COLLIDER_TYPE,VTF_BODY_FLAGS,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_INT); void PhysicManager::_RegisterParameters() { CKParameterManager *pm = m_Context->GetParameterManager(); CKAttributeManager* attman = m_Context->GetAttributeManager(); attman->AddCategory("Physic"); _RegisterWorldParameters(); _RegisterBodyParameters(); _RegisterBodyParameterFunctions(); /************************************************************************/ /* clothes : */ /************************************************************************/ pm->RegisterNewFlags(VTE_CLOTH_FLAGS,"pClothFlags","Pressure=1,Static=2,DisableCollision=4,SelfCollision=8,Gravity=32,Bending=64,BendingOrtho=128,Damping=256,CollisionTwoway=512,TriangleCollision=2048,Tearable=4096,Hardware=8192,ComDamping=16384,ValidBounds=32768,FluidCollision=65536,DisableCCD=131072,AddHere=262144,AttachToParentMainShape=524288,AttachToCollidingShapes=1048576,AttachToCore=2097152,AttachAttributes=4194304"); pm->RegisterNewFlags(VTE_CLOTH_ATTACH_FLAGS,"pClothAttachFlags","Twoway=1,Tearable=2"); pm->RegisterNewStructure(VTS_CLOTH_DESCR,"pClothDesc","Thickness,Density,Bending Stiffness,Stretching Stiffness,Damping Coefficient,Friction,Pressure,Tear Factor,Collision Response Coefficient,Attachment Response Coefficient,Attachment Tear Factor,To Fluid Response Coefficient,From Fluid Response Coefficient,Min Adhere Velocity,Solver Iterations,External Acceleration,Wind Acceleration,Wake Up Counter,Sleep Linear Velocity,Collision Group,Valid Bounds,Relative Grid Spacing,Flags,Tear Vertex Color,World Reference,Attachment Flags",CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_INT, CKPGUID_VECTOR, CKPGUID_VECTOR, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_INT, CKPGUID_BOX, CKPGUID_FLOAT, VTE_CLOTH_FLAGS, CKPGUID_COLOR, CKPGUID_3DENTITY, VTE_CLOTH_ATTACH_FLAGS); att_clothDescr= attman->RegisterNewAttributeType("Cloth",VTS_CLOTH_DESCR,CKCID_BEOBJECT); attman->SetAttributeCategory(att_clothDescr,"Physic"); attman->SetAttributeDefaultValue(att_clothDescr,"0.01f;1.0f;1.0f;1.0f;0.5f;0.5f;1.0f;1.5f;0.2f; 0.2f;1.5f;1.0f;1.0f;1.0f;5;0.0f,0.0f,0.0f;0.0f,0.0f,0.0f;0.4f;-1.0f;0;0.0f,0.0f,0.0f,0.0f,0.0f,0.0f;0.25;Gravity;255,255,255,255;pDefaultWorld;Twoway"); pm->RegisterNewStructure(VTS_CLOTH_METAL_DESCR,"pDeformableSettings","Impulse Threshold,Penetration Depth,Maximal Deformation Distance",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT); CKParameterTypeDesc* param_type=pm->GetParameterTypeDescription(VTS_CLOTH_METAL_DESCR); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; att_deformable = attman->RegisterNewAttributeType("Deformable Settings",VTS_CLOTH_METAL_DESCR,CKCID_BEOBJECT); attman->SetAttributeCategory(att_deformable,"Physic"); //attman->SetAttributeCallbackFunction(att_clothDescr,recheckWorldsFunc,NULL); /************************************************************************/ /* material */ /************************************************************************/ pm->RegisterNewFlags(VTF_MATERIAL_FLAGS,"pMaterialFlags","Anisotropic=1,Disable Friction=16,Disable Strong Friction=32"); pm->RegisterNewEnum(VTE_MATERIAL_COMBINE_MODE,"pFrictionCombineMode","Average=0,Min=1,Multiply=2,Max=3"); pm->RegisterNewStructure(VTS_MATERIAL,"pMaterial","XML Link,DynamicFriction,Static Friction,Restitution,Dynamic Friction V,Static Friction V,Direction of Anisotropy,Friction Combine Mode,Restitution Combine Mode,Flags",VTE_XML_MATERIAL_TYPE,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_VECTOR,VTE_MATERIAL_COMBINE_MODE,VTE_MATERIAL_COMBINE_MODE,VTF_MATERIAL_FLAGS); att_surface_props= attman->RegisterNewAttributeType("Material",VTS_MATERIAL,CKCID_BEOBJECT); attman->SetAttributeCategory(att_surface_props,"Physic"); attman->SetAttributeCallbackFunction(att_surface_props,recheckWorldsFunc,NULL); /************************************************************************/ /* Collision */ /************************************************************************/ att_trigger= attman->RegisterNewAttributeType("Trigger",VTF_TRIGGER,CKCID_BEOBJECT); attman->SetAttributeCategory(att_trigger,"Physic"); pm->RegisterNewFlags(VTF_RAY_HINTS,"pRayCastHints","Shape=1,Impact=2,Normal=4,Face Index=8,Distance=16,UV=32,Face Normal=64,Material=128"); pm->RegisterNewStructure(VTS_RAYCAST,"pRayCast","World Reference,Ray Origin,Ray Origin Reference,Ray Direction,Ray Direction Reference,Length,Groups,Groups Mask,Shape Types",CKPGUID_3DENTITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_FLOAT,CKPGUID_INT,VTS_FILTER_GROUPS,VTF_SHAPES_TYPE); /************************************************************************/ /* Vehicle : */ /************************************************************************/ // //pm->RegisterNewStructure(VTS_WHEEL_CONTACT,"pWheelContactData","Contact Point,Contact Normal,Longitudes Direction,Lateral Direction,Contact Force,Longitudes Slip,Lateral Slip, Longitudes Impulse,Lateral Impulse,Other Material,Contact Position, Contact Entity",CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_VECTOR, CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_FLOAT,CKPGUID_3DENTITY); //REGISTER_CUSTOM_STRUCT("pJDistance",PS_JDISTANCE_MEMBERS,VTS_JOINT_DISTANCE,gSMapJDistance,FALSE); _RegisterVehicleParameters(); _RegisterJointParameters(); //registerWatchers(); } XString getEnumDescription(CKParameterManager* pm,CKBeObject *object,int index) { XString result="None"; int pType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); if ( enumStruct ) { for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) { if(i == index) { result = enumStruct->GetEnumDescription(i); } } } return result; } int getEnumIndexByDescription(CKParameterManager* pm,XString descr) { int result =0; int pType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); if ( enumStruct ) { for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) { if (!strcmp(enumStruct->GetEnumDescription(i),descr.CStr())) { return i; } } } return result; } <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPWSetFilteringDecl(); CKERROR CreatePWSetFilteringProto(CKBehaviorPrototype **pproto); int PWSetFiltering(const CKBehaviorContext& behcontext); CKERROR PWSetFilteringCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPWSetFilteringDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PWSetFiltering"); od->SetCategory("Physic/Collision"); od->SetDescription("Sets the worlds filter settings for contact generation."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7ae099f,0x1f8e6949)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePWSetFilteringProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePWSetFilteringProto // FullName: CreatePWSetFilteringProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ enum bInput { bbI_FBool, bbI_FOp0, bbI_FOp1, bbI_FOp2, bbI_FConst0, bbI_FConst1, }; CKERROR CreatePWSetFilteringProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWSetFiltering"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PWSetFiltering PWSetFiltering is categorized in \ref Collision <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Sets the worlds filter settings for contact generation.<br> See <A HREF="pWFiltering.cmo">pWFiltering.cmo</A> for example. <h3>Technical Information</h3> \image html PWSetFiltering.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <SPAN CLASS="pin">Target: </SPAN>The world reference. Choose pDefaultWord if there are no multiple worlds in use. <BR> <SPAN CLASS="pin">Filter Bool: </SPAN>Setups filtering's boolean value. <BR> <SPAN CLASS="pin">Filter Op 0: </SPAN>Setups filtering operation. <BR> <SPAN CLASS="pin">Filter Op 1: </SPAN>Setups filtering operation. <BR> <SPAN CLASS="pin">Filter Op 2: </SPAN>Setups filtering operation. <BR> <SPAN CLASS="pin">Filter Constant 0: </SPAN>Setups filtering's K0 value. <BR> <SPAN CLASS="pin">Filter Constant 1: </SPAN>Setups filtering's K1 value. <BR> <h3>Note</h3><br> See \ref CollisionFiltering for more details. <br> <br> Is utilizing #pWorld .<br> */ proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Filter Bool",CKPGUID_BOOL,"true"); proto->DeclareInParameter("Filter Op 0",VTE_FILTER_OPS,"Or"); proto->DeclareInParameter("Filter Op 1",VTE_FILTER_OPS,"Or"); proto->DeclareInParameter("Filter Op 2",VTE_FILTER_OPS,"And"); proto->DeclareInParameter("Filter Constant 0",VTS_FILTER_GROUPS,"0"); proto->DeclareInParameter("Filter Constant 1",VTS_FILTER_GROUPS,"0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PWSetFiltering); *pproto = proto; return CK_OK; } enum bOutputs { bbO_None, bbO_Enter, bbO_Stay, bbO_Leave, }; //************************************ // Method: PWSetFiltering // FullName: PWSetFiltering // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PWSetFiltering(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorld(target->GetID()); if (!world) { beh->ActivateOutput(0); return 0; } NxScene *scene = world->getScene(); if (!scene) { return 0; } int filterBool = GetInputParameterValue<int>(beh,bbI_FBool); int fOP0 = GetInputParameterValue<int>(beh,bbI_FOp0); int fOP1 = GetInputParameterValue<int>(beh,bbI_FOp1); int fOP2 = GetInputParameterValue<int>(beh,bbI_FOp2); CKParameter *fConst0 = beh->GetInputParameter(bbI_FConst0)->GetRealSource(); NxGroupsMask mask0; mask0.bits0 = GetValueFromParameterStruct<int>(fConst0,0); mask0.bits1 = GetValueFromParameterStruct<int>(fConst0,1); mask0.bits2 = GetValueFromParameterStruct<int>(fConst0,2); mask0.bits3 = GetValueFromParameterStruct<int>(fConst0,3); CKParameter *fConst1 = beh->GetInputParameter(bbI_FConst1)->GetRealSource(); NxGroupsMask mask1; mask1.bits0 = GetValueFromParameterStruct<int>(fConst1,0); mask1.bits1 = GetValueFromParameterStruct<int>(fConst1,1); mask1.bits2 = GetValueFromParameterStruct<int>(fConst1,2); mask1.bits3 = GetValueFromParameterStruct<int>(fConst1,3); scene->setFilterBool(filterBool); scene->setFilterOps((NxFilterOp)fOP0,(NxFilterOp)fOP1,(NxFilterOp)fOP2); scene->setFilterConstant0(mask0); scene->setFilterConstant1(mask1); //scene->raycastAnyShape() beh->ActivateOutput(0); return 0; } //************************************ // Method: PWSetFilteringCB // FullName: PWSetFilteringCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PWSetFilteringCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pConfig.h" #include <xTime.h> int demoTimerExpired=0; float absTime = 0.0f; float lastAbsTime = 0.0f; #include "Timing.h" static float gTimestepMultiplier = 1.0f; float getCurrentTime() { unsigned int currentTime = timeGetTime(); return (float)(currentTime)*0.001f; } float getElapsedTime() { static LARGE_INTEGER previousTime; static LARGE_INTEGER freq; static bool init = false; if(!init){ QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&previousTime); init=true; } LARGE_INTEGER currentTime; QueryPerformanceCounter(&currentTime); unsigned long long elapsedTime = currentTime.QuadPart - previousTime.QuadPart; previousTime = currentTime; return (float)(elapsedTime)/(freq.QuadPart); } int PhysicManager::_checkResetList() { int result = 0 ; pRestoreMapIt it = _getRestoreMap()->Begin(); while(it != _getRestoreMap()->End()) { CK_ID id = it.GetKey(); CK3dEntity * ent = (CK3dEntity*)GetPMan()->GetContext()->GetObject(id); if(ent) { pRigidBody* body = GetPMan()->getBody(ent); if (body) { body->onICRestore(ent,*it); _getRestoreMap()->Remove(it.GetKey()); //_getRestoreMap()->Remove(it.GetKey()); it =_getRestoreMap()->Begin(); result++; continue; } }else { _getRestoreMap()->Remove(it.GetKey()); it =_getRestoreMap()->Begin(); result++; continue; } it++; } //_getRestoreMap()->Clear(); /* for (CK3dEntity** it = resetList.Begin(); it != resetList.End(); ++it) { pRigidBody* body = GetPMan()->getBody(*it); if (body) { body->onICRestore(*it,true); } } */ // resetList.Clear(); return result; } float PhysicManager::getLastTimeStep(int flags) { NxF32 elapsedTime = getElapsedTime(); elapsedTime*= GetContext()->GetTimeManager()->GetTimeScaleFactor(); elapsedTime*=10.0f; if(elapsedTime <= 0) elapsedTime = 0; return elapsedTime; } void PhysicManager::advanceTime(float time) { timer +=time; float timeNow = timer; mLastStepTime = time; int op= 30 ; op++; /* float TimeStep = 1.0f / 60.0f; if(gFixedStep) gScene->setTiming(TimeStep, 1, NX_TIMESTEP_FIXED); else gScene->setTiming(TimeStep, 1, NX_TIMESTEP_VARIABLE); */ } void PhysicManager::update(float stepsize) { advanceTime(stepsize); /* float a= time->GetSpanMS(); float b= time->GetRealTime(); time->Update(); */ int lastTime; int curTime,diffTime,maxTime; // Calculate time from last to current situation // time->Update(); curTime=time->GetRealTime(); lastTime=time->GetLastSimTime(); diffTime=curTime-lastTime; //maxTime=lastTime+maxSimTimePerFrame; #ifdef SESSION_LIMIT #ifndef REDIST if (timer >(SESSION_MAX)) { if (demoTimerExpired==0) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Demo expires after 15 mins"); demoTimerExpired = 1; } return ; } #endif #endif #ifdef REDIST if (m_Context->IsInInterfaceMode()) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"This is a redist Dll"); return; } #pragma message("-------------------------------PManager ::Update REDIST" ) #endif //CKTimeProfiler(const char* iTitle, CKContext* iContext, int iStartingCount = 4): //CKTimeProfiler MyProfiler("PhysX Step",GetContext(),8); float elapsedTime = getLastTimeStep(0);//(0.5) float msTimeNow = lastStepTimeMS;//(50.0) //_checkResetList(); pWorldMapIt it = getWorlds()->Begin(); while(it != getWorlds()->End()) { pWorld *w = *it; w->step(elapsedTime); //w->step(lastStepTimeMS); it++; } /* if (checkPhysics) { checkWorlds(); checkPhysics = false; } */ /*if (checkPhysics) { _checkObjectsByAttribute(GetContext()->GetCurrentLevel()->GetCurrentScene()); checkPhysics = false; }*/ //float pTime = MyProfiler //float a = pTime; } CKERROR PhysicManager::PostProcess() { advanceTime(lastStepTimeSec); if(sceneWasChanged) { //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"sceneWasChanged"); sceneWasChanged = 0; } pWorldMapIt it = getWorlds()->Begin(); while(it != getWorlds()->End()) { pWorld *w = *it; w->onPostProcess(); it++; } cleanAttributePostObjects(); _cleanTriggers(); getJointFeedbackList().Clear(); return CK_OK; } CKERROR PhysicManager::PreProcess() { float timeCtx = GetContext()->GetTimeManager()->GetLastDeltaTimeFree(); update(timeCtx); pWorldMapIt it = getWorlds()->Begin(); while(it != getWorlds()->End()) { pWorld *w = *it; w->onPreProcess(); it++; } return CK_OK; } void PhysicManager::_cleanTriggers() { /* int nbEntries = getTriggers().Size() ; for (int i = 0 ; i < getTriggers().Size(); i++ ) { pTriggerEntry &entry = *getTriggers().At(i); { if (entry.triggered) { getTriggers().RemoveAt(i); i = 0; } } } */ getTriggers().Clear(); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" CKPhysicManager::CKPhysicManager(CKContext *Context,CKGUID guid,char* name):CKBaseManager(Context,GUID_MODULE_MANAGER,"PhysicManager") { }<file_sep>STRING resultPath; STRING vDev35Path,vDev40Path,vDev41Path,WebPlayerPath; STRING vDev35RPath,vDev40RPath,vDev41RPath,WebPlayerRPath; NUMBER gSetupType; STRING gSetupTypeStr; NUMBER gPXVER; STRING gPXVER_STR; NUMBER vtA35,vtA40,vtA41; //export prototype GetVPath( NUMBER, STRING ); export prototype SdAskDestPath22( STRING, STRING, STRING); <file_sep>#ifndef __VTPRECOMP_H_ #define __VTPRECOMP_H_ #include "VxMath.h" #include "CKAll.h" #include "vtNetworkManager.h" #include "tnl.h" #undef min #undef max #endif <file_sep>//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by vtAgeiaInterface.rc // #define IDD_DIALOG1 2000 #define IDC_EDIT 2001 #define IDC_PARAM_NAME 2006 #define IDC_LBL_HTYPE 10000 #define IDC_BFLAGS_MOVING 10001 #define IDC_LBL_FLAGS 10002 #define IDC_BFLAGS_DEFORMABLE 10003 #define IDC_BFLAGS_GRAV 10004 #define IDC_BFLAGS_KINEMATIC 10005 #define IDC_BFLAGS_COLL 10006 #define IDC_BFLAGS_COLL_NOTIFY 10007 #define IDC_BFLAGS_TRIGGER 10008 #define IDC_BFLAGS_SSHAPE 10009 #define IDC_BFLAGS_HIERARCHY 10010 #define IDD_EDITOR 10011 #define IDC_FLAGS_BG 10012 #define IDI_EDITORICON 10013 #define IDC_FLEX_FRAME 10014 #define IDC_HULLTYPE 10015 #define IDC_BFLAGS_TRIGGEREX 10018 #define IDC_TRACKTEST 10019 #define IDC_TRACKTEST_TREE 10019 #define IDC_BFLAGS_TEST 10020 #define IDC_BFLAGS_SLEEP 10021 #define IDC_TREE1 10021 #define IDD_PBCOMMON 10022 #define IDC_TAB1 10022 #define IDD_TOOLBAR 10023 #define IDD_PBCOMMON_DEFORMABLE 10024 #define IDC_MAINTAB 10025 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 10006 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 10023 #define _APS_NEXT_SYMED_VALUE 10000 #endif #endif <file_sep>#if !defined( _CONSTREAM_H ) #define _CONSTREAM_H // // Note that ConStream uses the standard C++ libraries that ship with // Visual C++ 5.0 and later, not the older libraries with the .h suffix. // The library would require some modifications to work with the older // libraries. // #include <stdio.h> #include <stdlib.h> #include <iostream> #include <WTypes.h> #include <fstream> //using namespace std; // // The ConStream class is derived from what we normally think of as ostream, // which means you can use standard insertion operators to write to it. Of // course, this includes insertion operators for user defined classes. At // all times, a ConStream object is either writing out to to a FILE // object attached to the NUL device, or a FILE object attached to a console // created using the Win32 API. Which of the two is in use depends on whether // or not the ConStream object has had its Open() or Close() method called. // #define MAX_BUFFER 4096 class ConStream : public std::basic_ostream<char> { public : ConStream(); virtual ~ConStream(); void Open(); void Close(); protected : HANDLE m_hConsole; std::basic_filebuf<char> *m_FileBuf; std::basic_filebuf<char> m_Nul; FILE *m_fNul; FILE *m_fConsole; public: int lastLine; char* buf; int hConHandle; long lStdHandle; FILE *fp; }; #endif // !defined( _CONSTREAM_H ) <file_sep>/* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * php4.cxx * * Php language module for SWIG. * ----------------------------------------------------------------------------- */ /* FIXME: PHP5 OO wrapping TODO list: * * Short term: * * Sort out auto-renaming of method and class names which are reserved * words (e.g. empty, clone, exception, etc.) vs -php4/-php5 in some * sane way. * * Sort out wrapping of static member variables in OO PHP5 (which first may * mean we need to sort them out for PHP4!) * * Medium term: * * Handle default parameters on overloaded methods in PHP where possible. * (Mostly done - just need to handle cases of overloaded methods with * default parameters...) * This is an optimisation - we could handle this case using a PHP * default value, but currently we treat it as we would for a default * value which is a compound C++ expression (i.e. as if we had a * method with two overloaded forms instead of a single method with * a default parameter value). * * Long term: * * Option to generate code to work with PHP4 instead ("public $_cPtr;" -> * "var $_cPtr;", "abstract" -> "", no static class functions - but making * these changes gives a segfault with make check...) * Sort out locale-dependent behaviour of strtod() - it's harmless unless * SWIG ever sets the locale and DOH/base.c calls atof, so we're probably * OK currently at least. */ /* * TODO: Replace remaining stderr messages with Swig_error or Swig_warning * (may need to add more WARN_PHP4_xxx codes...) */ char cvsroot_php4_cxx[] = "$Id: php4.cxx 10099 2007-11-10 21:10:17Z wsfulton $"; #include "swigmod.h" #include <ctype.h> #include <errno.h> static const char *usage = (char *) "\ PHP Options (available with -php4 or -php5)\n\ -cppext - cpp file extension (default to .cpp)\n\ -noproxy - Don't generate proxy classes.\n\ -prefix <prefix> - Prepend <prefix> to all class names in PHP5 wrappers\n\ -make - Create simple makefile\n\ -phpfull - Create full make files\n\ -withincs <incs> - With -phpfull writes needed incs in config.m4\n\ -withlibs <libs> - With -phpfull writes needed libs in config.m4\n\ -withc <files> - With -phpfull makes extra C files in Makefile.in\n\ -withcxx <files> - With -phpfull makes extra C++ files in Makefile.in\n\ \n"; /* The original class wrappers for PHP4 store the pointer to the C++ class in * the object property _cPtr. If we use the same name for the member variable * which we put the pointer to the C++ class in, then the flat function * wrappers will automatically pull it out without any changes being required. * FIXME: Isn't using a leading underscore a bit suspect here? */ #define SWIG_PTR "_cPtr" static int constructors = 0; static String *NOTCLASS = NewString("Not a class"); static Node *classnode = 0; static String *module = 0; static String *cap_module = 0; static String *prefix = 0; static String *withlibs = 0; static String *withincs = 0; static String *withc = 0; static String *withcxx = 0; static String *shadow_classname = 0; static int gen_extra = 0; static int gen_make = 0; static File *f_runtime = 0; static File *f_h = 0; static File *f_phpcode = 0; static String *phpfilename = 0; static String *s_header; static String *s_wrappers; static String *s_init; static String *r_init; // RINIT user code static String *s_shutdown; // MSHUTDOWN user code static String *r_shutdown; // RSHUTDOWN user code static String *s_vinit; // varinit initialization code. static String *s_vdecl; static String *s_cinit; // consttab initialization code. static String *s_oinit; static String *s_entry; static String *cs_entry; static String *all_cs_entry; static String *pragma_incl; static String *pragma_code; static String *pragma_phpinfo; static String *s_oowrappers; static String *s_fakeoowrappers; static String *s_phpclasses; /* Variables for using PHP classes */ static Node *current_class = 0; static Hash *shadow_get_vars; static Hash *shadow_set_vars; #define NATIVE_CONSTRUCTOR 1 #define ALTERNATIVE_CONSTRUCTOR 2 static int native_constructor = 0; static Hash *zend_types = 0; static int shadow = 1; static bool class_has_ctor = false; static String *wrapping_member_constant = NULL; // These static variables are used to pass some state from Handlers into functionWrapper static enum { standard = 0, memberfn, staticmemberfn, membervar, staticmembervar, constructor, destructor } wrapperType = standard; extern "C" { static void (*r_prevtracefunc) (SwigType *t, String *mangled, String *clientdata) = 0; } void SwigPHP_emit_resource_registrations() { Iterator ki; if (!zend_types) return; ki = First(zend_types); if (ki.key) Printf(s_oinit, "\n/* Register resource destructors for pointer types */\n"); while (ki.key) if (1 /* is pointer type */ ) { DOH *key = ki.key; Node *class_node = ki.item; String *human_name = key; // Write out destructor function header Printf(s_wrappers, "/* NEW Destructor style */\nstatic ZEND_RSRC_DTOR_FUNC(_wrap_destroy%s) {\n", key); // write out body if ((class_node != NOTCLASS)) { String *destructor = Getattr(class_node, "destructor"); human_name = Getattr(class_node, "sym:name"); if (!human_name) human_name = Getattr(class_node, "name"); // Do we have a known destructor for this type? if (destructor) { Printf(s_wrappers, " %s(rsrc, SWIGTYPE%s->name TSRMLS_CC);\n", destructor, key); } else { Printf(s_wrappers, " /* No destructor for class %s */\n", human_name); } } else { Printf(s_wrappers, " /* No destructor for simple type %s */\n", key); } // close function Printf(s_wrappers, "}\n"); // declare le_swig_<mangled> to store php registration Printf(s_vdecl, "static int le_swig_%s=0; /* handle for %s */\n", key, human_name); // register with php Printf(s_oinit, "le_swig_%s=zend_register_list_destructors_ex" "(_wrap_destroy%s,NULL,(char *)(SWIGTYPE%s->name),module_number);\n", key, key, key); // store php type in class struct Printf(s_oinit, "SWIG_TypeClientData(SWIGTYPE%s,&le_swig_%s);\n", key, key); ki = Next(ki); } } class PHP:public Language { int php_version; public: PHP(int php_version_):php_version(php_version_) { } /* Test to see if a type corresponds to something wrapped with a shadow class. */ String *is_shadow(SwigType *t) { String *r = 0; Node *n = classLookup(t); if (n) { r = Getattr(n, "php:proxy"); // Set by classDeclaration() if (!r) { r = Getattr(n, "sym:name"); // Not seen by classDeclaration yet, but this is the name } } return r; } /* ------------------------------------------------------------ * main() * ------------------------------------------------------------ */ virtual void main(int argc, char *argv[]) { int i; SWIG_library_directory("php4"); SWIG_config_cppext("cpp"); for (i = 1; i < argc; i++) { if (argv[i]) { if (strcmp(argv[i], "-phpfull") == 0) { gen_extra = 1; Swig_mark_arg(i); } else if (strcmp(argv[i], "-dlname") == 0) { Printf(stderr, "*** -dlname is no longer supported\n*** if you want to change the module name, use -module instead.\n"); SWIG_exit(EXIT_FAILURE); } else if (strcmp(argv[i], "-prefix") == 0) { if (argv[i + 1]) { prefix = NewString(argv[i + 1]); Swig_mark_arg(i); Swig_mark_arg(i + 1); i++; } else { Swig_arg_error(); } } else if (strcmp(argv[i], "-withlibs") == 0) { if (argv[i + 1]) { withlibs = NewString(argv[i + 1]); Swig_mark_arg(i); Swig_mark_arg(i + 1); i++; } else { Swig_arg_error(); } } else if (strcmp(argv[i], "-withincs") == 0) { if (argv[i + 1]) { withincs = NewString(argv[i + 1]); Swig_mark_arg(i); Swig_mark_arg(i + 1); i++; } else { Swig_arg_error(); } } else if (strcmp(argv[i], "-withc") == 0) { if (argv[i + 1]) { withc = NewString(argv[i + 1]); Swig_mark_arg(i); Swig_mark_arg(i + 1); i++; } else { Swig_arg_error(); } } else if (strcmp(argv[i], "-withcxx") == 0) { if (argv[i + 1]) { withcxx = NewString(argv[i + 1]); Swig_mark_arg(i); Swig_mark_arg(i + 1); i++; } else { Swig_arg_error(); } } else if (strcmp(argv[i], "-cppext") == 0) { if (argv[i + 1]) { SWIG_config_cppext(argv[i + 1]); Swig_mark_arg(i); Swig_mark_arg(i + 1); i++; } else { Swig_arg_error(); } } else if ((strcmp(argv[i], "-noshadow") == 0) || (strcmp(argv[i], "-noproxy") == 0)) { shadow = 0; Swig_mark_arg(i); } else if (strcmp(argv[i], "-make") == 0) { gen_make = 1; Swig_mark_arg(i); } else if (strcmp(argv[i], "-help") == 0) { fputs(usage, stdout); } } } Preprocessor_define((void *) "SWIGPHP 1", 0); if (php_version == 4) { Preprocessor_define((void *) "SWIGPHP4 1", 0); } else if (php_version == 5) { Preprocessor_define((void *) "SWIGPHP5 1", 0); } SWIG_typemap_lang("php4"); /* DB: Suggest using a language configuration file */ SWIG_config_file("php4.swg"); allow_overloading(); } void create_simple_make(void) { File *f_make; f_make = NewFile((void *) "makefile", "w"); Printf(f_make, "CC=gcc\n"); Printf(f_make, "CXX=g++\n"); Printf(f_make, "CXX_SOURCES=%s\n", withcxx); Printf(f_make, "C_SOURCES=%s\n", withc); Printf(f_make, "OBJS=%s_wrap.o $(C_SOURCES:.c=.o) $(CXX_SOURCES:.cxx=.o)\n", module); Printf(f_make, "MODULE=%s.so\n", module); Printf(f_make, "CFLAGS=-fpic\n"); Printf(f_make, "LDFLAGS=-shared\n"); Printf(f_make, "PHP_INC=`php-config --includes`\n"); Printf(f_make, "EXTRA_INC=\n"); Printf(f_make, "EXTRA_LIB=\n\n"); Printf(f_make, "$(MODULE): $(OBJS)\n"); if (CPlusPlus || (withcxx != NULL)) { Printf(f_make, "\t$(CXX) $(LDFLAGS) $(OBJS) -o $@ $(EXTRA_LIB)\n\n"); } else { Printf(f_make, "\t$(CC) $(LDFLAGS) $(OBJS) -o $@ $(EXTRA_LIB)\n\n"); } Printf(f_make, "%%.o: %%.cpp\n"); Printf(f_make, "\t$(CXX) $(EXTRA_INC) $(PHP_INC) $(CFLAGS) -c $<\n"); Printf(f_make, "%%.o: %%.cxx\n"); Printf(f_make, "\t$(CXX) $(EXTRA_INC) $(PHP_INC) $(CFLAGS) -c $<\n"); Printf(f_make, "%%.o: %%.c\n"); Printf(f_make, "\t$(CC) $(EXTRA_INC) $(PHP_INC) $(CFLAGS) -c $<\n"); Close(f_make); } void create_extra_files(String *outfile) { File *f_extra; static String *configm4 = 0; static String *makefilein = 0; static String *credits = 0; configm4 = NewStringEmpty(); Printv(configm4, SWIG_output_directory(), "config.m4", NIL); makefilein = NewStringEmpty(); Printv(makefilein, SWIG_output_directory(), "Makefile.in", NIL); credits = NewStringEmpty(); Printv(credits, SWIG_output_directory(), "CREDITS", NIL); // are we a --with- or --enable- int with = (withincs || withlibs) ? 1 : 0; // Note Makefile.in only copes with one source file // also withincs and withlibs only take one name each now // the code they generate should be adapted to take multiple lines /* Write out Makefile.in */ f_extra = NewFile(makefilein, "w"); if (!f_extra) { FileErrorDisplay(makefilein); SWIG_exit(EXIT_FAILURE); } Printf(f_extra, "# $Id: php4.cxx 10099 2007-11-10 21:10:17Z wsfulton $\n\n" "LTLIBRARY_NAME = %s.la\n", module); // C++ has more and different entries to C in Makefile.in if (!CPlusPlus) { Printf(f_extra, "LTLIBRARY_SOURCES = %s %s\n", Swig_file_filename(outfile), withc); Printf(f_extra, "LTLIBRARY_SOURCES_CPP = %s\n", withcxx); } else { Printf(f_extra, "LTLIBRARY_SOURCES = %s\n", withc); Printf(f_extra, "LTLIBRARY_SOURCES_CPP = %s %s\n", Swig_file_filename(outfile), withcxx); Printf(f_extra, "LTLIBRARY_OBJECTS_X = $(LTLIBRARY_SOURCES_CPP:.cpp=.lo) $(LTLIBRARY_SOURCES_CPP:.cxx=.lo)\n"); } Printf(f_extra, "LTLIBRARY_SHARED_NAME = %s.la\n", module); Printf(f_extra, "LTLIBRARY_SHARED_LIBADD = $(%s_SHARED_LIBADD)\n\n", cap_module); Printf(f_extra, "include $(top_srcdir)/build/dynlib.mk\n"); Printf(f_extra, "\n# patch in .cxx support to php build system to work like .cpp\n"); Printf(f_extra, ".SUFFIXES: .cxx\n\n"); Printf(f_extra, ".cxx.o:\n"); Printf(f_extra, "\t$(CXX_COMPILE) -c $<\n\n"); Printf(f_extra, ".cxx.lo:\n"); Printf(f_extra, "\t$(CXX_PHP_COMPILE)\n\n"); Printf(f_extra, ".cxx.slo:\n"); Printf(f_extra, "\t$(CXX_SHARED_COMPILE)\n\n"); Printf(f_extra, "\n# make it easy to test module\n"); Printf(f_extra, "testmodule:\n"); Printf(f_extra, "\tphp -q -d extension_dir=modules %s\n\n", Swig_file_filename(phpfilename)); Close(f_extra); /* Now config.m4 */ // Note: # comments are OK in config.m4 if you don't mind them // appearing in the final ./configure file // (which can help with ./configure debugging) // NOTE2: phpize really ought to be able to write out a sample // config.m4 based on some simple data, I'll take this up with // the php folk! f_extra = NewFile(configm4, "w"); if (!f_extra) { FileErrorDisplay(configm4); SWIG_exit(EXIT_FAILURE); } Printf(f_extra, "dnl $Id: php4.cxx 10099 2007-11-10 21:10:17Z wsfulton $\n"); Printf(f_extra, "dnl ***********************************************************************\n"); Printf(f_extra, "dnl ** THIS config.m4 is provided for PHPIZE and PHP's consumption NOT\n"); Printf(f_extra, "dnl ** for any part of the rest of the %s build system\n", module); Printf(f_extra, "dnl ***********************************************************************\n\n"); if (!with) { // must be enable then Printf(f_extra, "PHP_ARG_ENABLE(%s, whether to enable %s support,\n", module, module); Printf(f_extra, "[ --enable-%s Enable %s support])\n\n", module, module); } else { Printf(f_extra, "PHP_ARG_WITH(%s, for %s support,\n", module, module); Printf(f_extra, "[ --with-%s[=DIR] Include %s support.])\n\n", module, module); // These tests try and file the library we need Printf(f_extra, "dnl THESE TESTS try and find the library and header files\n"); Printf(f_extra, "dnl your new php module needs. YOU MAY NEED TO EDIT THEM\n"); Printf(f_extra, "dnl as written they assume your header files are all in the same place\n\n"); Printf(f_extra, "dnl ** are we looking for %s_lib.h or something else?\n", module); if (withincs) Printf(f_extra, "HNAMES=\"%s\"\n\n", withincs); else Printf(f_extra, "HNAMES=\"\"; # %s_lib.h ?\n\n", module); Printf(f_extra, "dnl ** Are we looking for lib%s.a or lib%s.so or something else?\n", module, module); if (withlibs) Printf(f_extra, "LIBNAMES=\"%s\"\n\n", withlibs); else Printf(f_extra, "LIBNAMES=\"\"; # lib%s.so ?\n\n", module); Printf(f_extra, "dnl IF YOU KNOW one of the symbols in the library and you\n"); Printf(f_extra, "dnl specify it below then we can have a link test to see if it works\n"); Printf(f_extra, "LIBSYMBOL=\"\"\n\n"); } // Now write out tests to find thing.. they may need to extend tests Printf(f_extra, "if test \"$PHP_%s\" != \"no\"; then\n\n", cap_module); // Ready for when we add libraries as we find them Printf(f_extra, " PHP_SUBST(%s_SHARED_LIBADD)\n\n", cap_module); if (withlibs) { // find more than one library Printf(f_extra, " for LIBNAME in $LIBNAMES ; do\n"); Printf(f_extra, " LIBDIR=\"\"\n"); // For each path element to try... Printf(f_extra, " for i in $PHP_%s $PHP_%s/lib /usr/lib /usr/local/lib ; do\n", cap_module, cap_module); Printf(f_extra, " if test -r $i/lib$LIBNAME.a -o -r $i/lib$LIBNAME.so ; then\n"); Printf(f_extra, " LIBDIR=\"$i\"\n"); Printf(f_extra, " break\n"); Printf(f_extra, " fi\n"); Printf(f_extra, " done\n\n"); Printf(f_extra, " dnl ** and $LIBDIR should be the library path\n"); Printf(f_extra, " if test \"$LIBNAME\" != \"\" -a -z \"$LIBDIR\" ; then\n"); Printf(f_extra, " AC_MSG_RESULT(Library files $LIBNAME not found)\n"); Printf(f_extra, " AC_MSG_ERROR(Is the %s distribution installed properly?)\n", module); Printf(f_extra, " else\n"); Printf(f_extra, " AC_MSG_RESULT(Library files $LIBNAME found in $LIBDIR)\n"); Printf(f_extra, " PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $LIBDIR, %s_SHARED_LIBADD)\n", cap_module); Printf(f_extra, " fi\n"); Printf(f_extra, " done\n\n"); } if (withincs) { // Find more than once include Printf(f_extra, " for HNAME in $HNAMES ; do\n"); Printf(f_extra, " INCDIR=\"\"\n"); // For each path element to try... Printf(f_extra, " for i in $PHP_%s $PHP_%s/include $PHP_%s/includes $PHP_%s/inc $PHP_%s/incs /usr/local/include /usr/include; do\n", cap_module, cap_module, cap_module, cap_module, cap_module); // Try and find header files Printf(f_extra, " if test \"$HNAME\" != \"\" -a -r $i/$HNAME ; then\n"); Printf(f_extra, " INCDIR=\"$i\"\n"); Printf(f_extra, " break\n"); Printf(f_extra, " fi\n"); Printf(f_extra, " done\n\n"); Printf(f_extra, " dnl ** Now $INCDIR should be the include file path\n"); Printf(f_extra, " if test \"$HNAME\" != \"\" -a -z \"$INCDIR\" ; then\n"); Printf(f_extra, " AC_MSG_RESULT(Include files $HNAME not found)\n"); Printf(f_extra, " AC_MSG_ERROR(Is the %s distribution installed properly?)\n", module); Printf(f_extra, " else\n"); Printf(f_extra, " AC_MSG_RESULT(Include files $HNAME found in $INCDIR)\n"); Printf(f_extra, " PHP_ADD_INCLUDE($INCDIR)\n"); Printf(f_extra, " fi\n\n"); Printf(f_extra, " done\n\n"); } if (CPlusPlus) { Printf(f_extra, " # As this is a C++ module..\n"); } Printf(f_extra, " PHP_REQUIRE_CXX\n"); Printf(f_extra, " AC_CHECK_LIB(stdc++, cin)\n"); if (with) { Printf(f_extra, " if test \"$LIBSYMBOL\" != \"\" ; then\n"); Printf(f_extra, " old_LIBS=\"$LIBS\"\n"); Printf(f_extra, " LIBS=\"$LIBS -L$TEST_DIR/lib -lm -ldl\"\n"); Printf(f_extra, " AC_CHECK_LIB($LIBNAME, $LIBSYMBOL, [AC_DEFINE(HAVE_TESTLIB,1, [ ])],\n"); Printf(f_extra, " [AC_MSG_ERROR(wrong test lib version or lib not found)])\n"); Printf(f_extra, " LIBS=\"$old_LIBS\"\n"); Printf(f_extra, " fi\n\n"); } Printf(f_extra, " AC_DEFINE(HAVE_%s, 1, [ ])\n", cap_module); Printf(f_extra, "dnl AC_DEFINE_UNQUOTED(PHP_%s_DIR, \"$%s_DIR\", [ ])\n", cap_module, cap_module); Printf(f_extra, " PHP_EXTENSION(%s, $ext_shared)\n", module); // and thats all! Printf(f_extra, "fi\n"); Close(f_extra); /* CREDITS */ f_extra = NewFile(credits, "w"); if (!f_extra) { FileErrorDisplay(credits); SWIG_exit(EXIT_FAILURE); } Printf(f_extra, "%s\n", module); Close(f_extra); } /* ------------------------------------------------------------ * top() * ------------------------------------------------------------ */ virtual int top(Node *n) { String *filen; String *s_type; /* Initialize all of the output files */ String *outfile = Getattr(n, "outfile"); /* main output file */ f_runtime = NewFile(outfile, "w"); if (!f_runtime) { FileErrorDisplay(outfile); SWIG_exit(EXIT_FAILURE); } Swig_banner(f_runtime); /* sections of the output file */ s_init = NewString("/* init section */\n"); r_init = NewString("/* rinit section */\n"); s_shutdown = NewString("/* shutdown section */\n"); r_shutdown = NewString("/* rshutdown section */\n"); s_header = NewString("/* header section */\n"); s_wrappers = NewString("/* wrapper section */\n"); s_type = NewStringEmpty(); /* subsections of the init section */ s_vinit = NewString("/* vinit subsection */\n"); s_vdecl = NewString("/* vdecl subsection */\n"); s_cinit = NewString("/* cinit subsection */\n"); s_oinit = NewString("/* oinit subsection */\n"); pragma_phpinfo = NewStringEmpty(); s_phpclasses = NewString("/* PHP Proxy Classes */\n"); /* Register file targets with the SWIG file handler */ Swig_register_filebyname("runtime", f_runtime); Swig_register_filebyname("init", s_init); Swig_register_filebyname("rinit", r_init); Swig_register_filebyname("shutdown", s_shutdown); Swig_register_filebyname("rshutdown", r_shutdown); Swig_register_filebyname("header", s_header); Swig_register_filebyname("wrapper", s_wrappers); /* Set the module name */ module = Copy(Getattr(n, "name")); cap_module = NewStringf("%(upper)s", module); if (!prefix) prefix = NewStringEmpty(); /* PHP module file */ filen = NewStringEmpty(); Printv(filen, SWIG_output_directory(), module, ".php", NIL); phpfilename = NewString(filen); f_phpcode = NewFile(filen, "w"); if (!f_phpcode) { FileErrorDisplay(filen); SWIG_exit(EXIT_FAILURE); } Printf(f_phpcode, "<?php\n\n"); Swig_banner(f_phpcode); Printf(f_phpcode, "// Try to load our extension if it's not already loaded.\n"); Printf(f_phpcode, "if (!extension_loaded(\"%s\")) {\n", module); Printf(f_phpcode, " if (strtolower(substr(PHP_OS, 0, 3)) === 'win') {\n"); Printf(f_phpcode, " if (!dl('php_%s.dll')) return;\n", module); Printf(f_phpcode, " } else {\n"); Printf(f_phpcode, " // PHP_SHLIB_SUFFIX is available as of PHP 4.3.0, for older PHP assume 'so'.\n"); Printf(f_phpcode, " // It gives 'dylib' on MacOS X which is for libraries, modules are 'so'.\n"); Printf(f_phpcode, " if (PHP_SHLIB_SUFFIX === 'PHP_SHLIB_SUFFIX' || PHP_SHLIB_SUFFIX === 'dylib') {\n"); Printf(f_phpcode, " if (!dl('%s.so')) return;\n", module); Printf(f_phpcode, " } else {\n"); Printf(f_phpcode, " if (!dl('%s.'.PHP_SHLIB_SUFFIX)) return;\n", module); Printf(f_phpcode, " }\n"); Printf(f_phpcode, " }\n"); Printf(f_phpcode, "}\n\n"); /* sub-sections of the php file */ pragma_code = NewStringEmpty(); pragma_incl = NewStringEmpty(); /* Initialize the rest of the module */ Printf(s_oinit, "ZEND_INIT_MODULE_GLOBALS(%s, %s_init_globals, %s_destroy_globals);\n", module, module, module); /* start the header section */ Printf(s_header, "ZEND_BEGIN_MODULE_GLOBALS(%s)\n", module); Printf(s_header, "const char *error_msg;\n"); Printf(s_header, "int error_code;\n"); Printf(s_header, "ZEND_END_MODULE_GLOBALS(%s)\n", module); Printf(s_header, "ZEND_DECLARE_MODULE_GLOBALS(%s)\n", module); Printf(s_header, "#ifdef ZTS\n"); Printf(s_header, "#define SWIG_ErrorMsg() TSRMG(%s_globals_id, zend_%s_globals *, error_msg )\n", module, module); Printf(s_header, "#define SWIG_ErrorCode() TSRMG(%s_globals_id, zend_%s_globals *, error_code )\n", module, module); Printf(s_header, "#else\n"); Printf(s_header, "#define SWIG_ErrorMsg() (%s_globals.error_msg)\n", module); Printf(s_header, "#define SWIG_ErrorCode() (%s_globals.error_code)\n", module); Printf(s_header, "#endif\n\n"); Printf(s_header, "static void %s_init_globals(zend_%s_globals *globals ) {\n", module, module); Printf(s_header, " globals->error_msg = default_error_msg;\n"); Printf(s_header, " globals->error_code = default_error_code;\n"); Printf(s_header, "}\n"); Printf(s_header, "static void %s_destroy_globals(zend_%s_globals * globals) { (void)globals; }\n", module, module); Printf(s_header, "\n"); Printf(s_header, "static void SWIG_ResetError() {\n"); Printf(s_header, " TSRMLS_FETCH();\n"); Printf(s_header, " SWIG_ErrorMsg() = default_error_msg;\n"); Printf(s_header, " SWIG_ErrorCode() = default_error_code;\n"); Printf(s_header, "}\n"); Printf(s_header, "#define SWIG_name \"%s\"\n", module); /* Printf(s_header,"#ifdef HAVE_CONFIG_H\n"); Printf(s_header,"#include \"config.h\"\n"); Printf(s_header,"#endif\n\n"); */ Printf(s_header, "#ifdef __cplusplus\n"); Printf(s_header, "extern \"C\" {\n"); Printf(s_header, "#endif\n"); Printf(s_header, "#include \"php.h\"\n"); Printf(s_header, "#include \"php_ini.h\"\n"); Printf(s_header, "#include \"ext/standard/info.h\"\n"); Printf(s_header, "#include \"php_%s.h\"\n", module); Printf(s_header, "#ifdef __cplusplus\n"); Printf(s_header, "}\n"); Printf(s_header, "#endif\n\n"); /* Create the .h file too */ filen = NewStringEmpty(); Printv(filen, SWIG_output_directory(), "php_", module, ".h", NIL); f_h = NewFile(filen, "w"); if (!f_h) { FileErrorDisplay(filen); SWIG_exit(EXIT_FAILURE); } Swig_banner(f_h); Printf(f_h, "\n\n"); Printf(f_h, "#ifndef PHP_%s_H\n", cap_module); Printf(f_h, "#define PHP_%s_H\n\n", cap_module); Printf(f_h, "extern zend_module_entry %s_module_entry;\n", module); Printf(f_h, "#define phpext_%s_ptr &%s_module_entry\n\n", module, module); Printf(f_h, "#ifdef PHP_WIN32\n"); Printf(f_h, "# define PHP_%s_API __declspec(dllexport)\n", cap_module); Printf(f_h, "#else\n"); Printf(f_h, "# define PHP_%s_API\n", cap_module); Printf(f_h, "#endif\n\n"); Printf(f_h, "#ifdef ZTS\n"); Printf(f_h, "#include \"TSRM.h\"\n"); Printf(f_h, "#endif\n\n"); Printf(f_h, "PHP_MINIT_FUNCTION(%s);\n", module); Printf(f_h, "PHP_MSHUTDOWN_FUNCTION(%s);\n", module); Printf(f_h, "PHP_RINIT_FUNCTION(%s);\n", module); Printf(f_h, "PHP_RSHUTDOWN_FUNCTION(%s);\n", module); Printf(f_h, "PHP_MINFO_FUNCTION(%s);\n\n", module); /* start the function entry section */ s_entry = NewString("/* entry subsection */\n"); /* holds all the per-class function entry sections */ all_cs_entry = NewString("/* class entry subsection */\n"); cs_entry = NULL; Printf(s_entry, "/* Every non-class user visible function must have an entry here */\n"); Printf(s_entry, "static zend_function_entry %s_functions[] = {\n", module); /* start the init section */ Printv(s_init, "zend_module_entry ", module, "_module_entry = {\n" "#if ZEND_MODULE_API_NO > 20010900\n" " STANDARD_MODULE_HEADER,\n" "#endif\n", NIL); Printf(s_init, " (char*)\"%s\",\n", module); Printf(s_init, " %s_functions,\n", module); Printf(s_init, " PHP_MINIT(%s),\n", module); Printf(s_init, " PHP_MSHUTDOWN(%s),\n", module); Printf(s_init, " PHP_RINIT(%s),\n", module); Printf(s_init, " PHP_RSHUTDOWN(%s),\n", module); Printf(s_init, " PHP_MINFO(%s),\n", module); Printf(s_init, "#if ZEND_MODULE_API_NO > 20010900\n"); Printf(s_init, " NO_VERSION_YET,\n"); Printf(s_init, "#endif\n"); Printf(s_init, " STANDARD_MODULE_PROPERTIES\n"); Printf(s_init, "};\n"); Printf(s_init, "zend_module_entry* SWIG_module_entry = &%s_module_entry;\n\n", module); if (gen_extra) { Printf(s_init, "#ifdef COMPILE_DL_%s\n", cap_module); } Printf(s_init, "#ifdef __cplusplus\n"); Printf(s_init, "extern \"C\" {\n"); Printf(s_init, "#endif\n"); // We want to write "SWIGEXPORT ZEND_GET_MODULE(%s)" but ZEND_GET_MODULE // in PHP5 has "extern "C" { ... }" around it so we can't do that. Printf(s_init, "SWIGEXPORT zend_module_entry *get_module(void) { return &%s_module_entry; }\n", module); Printf(s_init, "#ifdef __cplusplus\n"); Printf(s_init, "}\n"); Printf(s_init, "#endif\n\n"); if (gen_extra) { Printf(s_init, "#endif\n\n"); } /* We have to register the constants before they are (possibly) used * by the pointer typemaps. This all needs re-arranging really as * things are being called in the wrong order */ Printf(s_init, "#define SWIG_php_minit PHP_MINIT_FUNCTION(%s)\n", module); /* Emit all of the code */ Language::top(n); SwigPHP_emit_resource_registrations(); // Printv(s_init,s_resourcetypes,NIL); /* We need this after all classes written out by ::top */ Printf(s_oinit, "CG(active_class_entry) = NULL;\n"); Printf(s_oinit, "/* end oinit subsection */\n"); Printf(s_init, "%s\n", s_oinit); /* Constants generated during top call */ Printf(s_cinit, "/* end cinit subsection */\n"); Printf(s_init, "%s\n", s_cinit); Clear(s_cinit); Delete(s_cinit); Printf(s_init, " return SUCCESS;\n"); Printf(s_init, "}\n\n"); // Now do REQUEST init which holds any user specified %rinit, and also vinit Printf(s_init, "PHP_RINIT_FUNCTION(%s)\n{\n", module); Printf(s_init, "%s\n", r_init); /* finish our init section which will have been used by class wrappers */ Printf(s_vinit, "/* end vinit subsection */\n"); Printf(s_init, "%s\n", s_vinit); Clear(s_vinit); Delete(s_vinit); Printf(s_init, " return SUCCESS;\n"); Printf(s_init, "}\n\n"); Printv(s_init, "PHP_MSHUTDOWN_FUNCTION(", module, ")\n" "{\n", s_shutdown, "#ifdef ZTS\n" " ts_free_id(", module, "_globals_id);\n" "#endif\n" " return SUCCESS;\n" "}\n\n", NIL); Printf(s_init, "PHP_RSHUTDOWN_FUNCTION(%s)\n{\n", module); Printf(s_init, "%s\n", r_shutdown); Printf(s_init, " return SUCCESS;\n"); Printf(s_init, "}\n\n"); Printf(s_init, "PHP_MINFO_FUNCTION(%s)\n{\n", module); Printf(s_init, "%s", pragma_phpinfo); Printf(s_init, "}\n"); Printf(s_init, "/* end init section */\n"); Printf(f_h, "#endif /* PHP_%s_H */\n", cap_module); Close(f_h); String *type_table = NewStringEmpty(); SwigType_emit_type_table(f_runtime, type_table); Printf(s_header, "%s", type_table); Delete(type_table); /* Oh dear, more things being called in the wrong order. This whole * function really needs totally redoing. */ Printf(s_header, "/* end header section */\n"); Printf(s_wrappers, "/* end wrapper section */\n"); Printf(s_vdecl, "/* end vdecl subsection */\n"); Printv(f_runtime, s_header, s_vdecl, s_wrappers, NIL); Printv(f_runtime, all_cs_entry, "\n\n", s_entry, "{NULL, NULL, NULL}\n};\n\n", NIL); Printv(f_runtime, s_init, NIL); Delete(s_header); Delete(s_wrappers); Delete(s_init); Delete(s_vdecl); Delete(all_cs_entry); Delete(s_entry); Close(f_runtime); Printf(f_phpcode, "%s\n%s\n", pragma_incl, pragma_code); if (s_fakeoowrappers) { Printf(f_phpcode, "abstract class %s {", Len(prefix) ? prefix : module); Printf(f_phpcode, "%s", s_fakeoowrappers); Printf(f_phpcode, "}\n\n"); Delete(s_fakeoowrappers); s_fakeoowrappers = NULL; } Printf(f_phpcode, "%s\n?>\n", s_phpclasses); Close(f_phpcode); if (gen_extra) { create_extra_files(outfile); } else if (gen_make) { create_simple_make(); } return SWIG_OK; } /* Just need to append function names to function table to register with PHP. */ void create_command(String *cname, String *iname) { // This is for the single main zend_function_entry record if (shadow && php_version == 4) { if (wrapperType != standard) return; } Printf(f_h, "ZEND_NAMED_FUNCTION(%s);\n", iname); String * s = cs_entry; if (!s) s = s_entry; Printf(s, " SWIG_ZEND_NAMED_FE(%(lower)s,%s,NULL)\n", cname, iname); } /* ------------------------------------------------------------ * dispatchFunction() * ------------------------------------------------------------ */ void dispatchFunction(Node *n) { /* Last node in overloaded chain */ int maxargs; String *tmp = NewStringEmpty(); String *dispatch = Swig_overload_dispatch(n, "return %s(INTERNAL_FUNCTION_PARAM_PASSTHRU);", &maxargs); int has_this_ptr = (wrapperType == memberfn && shadow && php_version == 4); /* Generate a dispatch wrapper for all overloaded functions */ Wrapper *f = NewWrapper(); String *symname = Getattr(n, "sym:name"); String *wname = Swig_name_wrapper(symname); create_command(symname, wname); Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL); Wrapper_add_local(f, "argc", "int argc"); Printf(tmp, "zval **argv[%d]", maxargs); Wrapper_add_local(f, "argv", tmp); Printf(f->code, "argc = ZEND_NUM_ARGS();\n"); if (has_this_ptr) { Printf(f->code, "argv[0] = &this_ptr;\n"); Printf(f->code, "zend_get_parameters_array_ex(argc,argv+1);\n"); Printf(f->code, "argc++;\n"); } else { Printf(f->code, "zend_get_parameters_array_ex(argc,argv);\n"); } Replaceall(dispatch, "$args", "self,args"); Printv(f->code, dispatch, "\n", NIL); Printf(f->code, "SWIG_ErrorCode() = E_ERROR;\n"); Printf(f->code, "SWIG_ErrorMsg() = \"No matching function for overloaded '%s'\";\n", symname); Printv(f->code, "zend_error(SWIG_ErrorCode(),SWIG_ErrorMsg());\n", NIL); Printv(f->code, "}\n", NIL); Wrapper_print(f, s_wrappers); DelWrapper(f); Delete(dispatch); Delete(tmp); Delete(wname); } /* ------------------------------------------------------------ * functionWrapper() * ------------------------------------------------------------ */ /* Helper method for PHP::functionWrapper */ bool is_class(SwigType *t) { Node *n = classLookup(t); if (n) { String *r = Getattr(n, "php:proxy"); // Set by classDeclaration() if (!r) r = Getattr(n, "sym:name"); // Not seen by classDeclaration yet, but this is the name if (r) return true; } return false; } virtual int functionWrapper(Node *n) { String *name = GetChar(n, "name"); String *iname = GetChar(n, "sym:name"); SwigType *d = Getattr(n, "type"); ParmList *l = Getattr(n, "parms"); String *nodeType = Getattr(n, "nodeType"); int newobject = GetFlag(n, "feature:new"); Parm *p; int i; int numopt; String *tm; Wrapper *f; bool mvr = (shadow && php_version == 4 && wrapperType == membervar); bool mvrset = (mvr && (Strcmp(iname, Swig_name_set(Swig_name_member(shadow_classname, name))) == 0)); String *wname; int overloaded = 0; String *overname = 0; if (Cmp(nodeType, "destructor") == 0) { // We just generate the Zend List Destructor and let Zend manage the // reference counting. There's no explicit destructor, but the user can // just do `$obj = null;' to remove a reference to an object. return CreateZendListDestructor(n); } // Test for overloading; if (Getattr(n, "sym:overloaded")) { overloaded = 1; overname = Getattr(n, "sym:overname"); } else { if (!addSymbol(iname, n)) return SWIG_ERROR; } wname = Swig_name_wrapper(iname); if (overname) { Printf(wname, "%s", overname); } // if PHP4, shadow and variable wrapper we want to snag the main contents // of this function to stick in to the property handler... if (mvr) { String *php_function_name = NewString(iname); if (Strcmp(iname, Swig_name_set(Swig_name_member(shadow_classname, name))) == 0) { Setattr(shadow_set_vars, php_function_name, name); } if (Strcmp(iname, Swig_name_get(Swig_name_member(shadow_classname, name))) == 0) { Setattr(shadow_get_vars, php_function_name, name); } Delete(php_function_name); } f = NewWrapper(); numopt = 0; String *outarg = NewStringEmpty(); String *cleanup = NewStringEmpty(); if (mvr) { // do prop[gs]et header if (mvrset) { Printf(f->def, "static int _wrap_%s(zend_property_reference *property_reference, pval *value) {\n", iname); } else { Printf(f->def, "static pval _wrap_%s(zend_property_reference *property_reference) {\n", iname); } } else { // regular header // Not issued for overloaded functions or static member variables. if (!overloaded && wrapperType != staticmembervar) { create_command(iname, wname); } Printv(f->def, "ZEND_NAMED_FUNCTION(", wname, ") {\n", NIL); } emit_args(d, l, f); /* Attach standard typemaps */ emit_attach_parmmaps(l, f); // wrap:parms is used by overload resolution. Setattr(n, "wrap:parms", l); int num_arguments = emit_num_arguments(l); int num_required = emit_num_required(l); numopt = num_arguments - num_required; int has_this_ptr = (wrapperType == memberfn && shadow && php_version == 4); if (num_arguments - has_this_ptr > 0) { String *args = NewStringf("zval **args[%d]", num_arguments - has_this_ptr); Wrapper_add_local(f, "args", args); Delete(args); args = NULL; } // This generated code may be called: // 1) as an object method, or // 2) as a class-method/function (without a "this_ptr") // Option (1) has "this_ptr" for "this", option (2) needs it as // first parameter // NOTE: possible we ignore this_ptr as a param for native constructor Printf(f->code, "SWIG_ResetError();\n"); if (has_this_ptr) Printf(f->code, "/* This function uses a this_ptr*/\n"); if (native_constructor) { if (native_constructor == NATIVE_CONSTRUCTOR) { Printf(f->code, "/* NATIVE Constructor */\n"); } else { Printf(f->code, "/* ALTERNATIVE Constructor */\n"); } } if (mvr && !mvrset) { Wrapper_add_local(f, "_return_value", "zval _return_value"); Wrapper_add_local(f, "return_value", "zval *return_value=&_return_value"); } if (numopt > 0) { // membervariable wrappers do not have optional args Wrapper_add_local(f, "arg_count", "int arg_count"); Printf(f->code, "arg_count = ZEND_NUM_ARGS();\n"); Printf(f->code, "if(arg_count<%d || arg_count>%d ||\n", num_required, num_arguments); Printf(f->code, " zend_get_parameters_array_ex(arg_count,args)!=SUCCESS)\n"); Printf(f->code, "\tWRONG_PARAM_COUNT;\n\n"); } else if (!mvr) { int num = num_arguments - has_this_ptr; if (num == 0) { Printf(f->code, "if(ZEND_NUM_ARGS() != 0) {\n"); } else { Printf(f->code, "if(ZEND_NUM_ARGS() != %d || zend_get_parameters_array_ex(%d, args) != SUCCESS) {\n", num, num); } Printf(f->code, "WRONG_PARAM_COUNT;\n}\n\n"); } /* Now convert from php to C variables */ // At this point, argcount if used is the number of deliberately passed args // not including this_ptr even if it is used. // It means error messages may be out by argbase with error // reports. We can either take argbase into account when raising // errors, or find a better way of dealing with _thisptr. // I would like, if objects are wrapped, to assume _thisptr is always // _this and not the first argument. // This may mean looking at Language::memberfunctionHandler for (i = 0, p = l; i < num_arguments; i++) { String *source; /* Skip ignored arguments */ //while (Getattr(p,"tmap:ignore")) { p = Getattr(p,"tmap:ignore:next");} while (checkAttribute(p, "tmap:in:numinputs", "0")) { p = Getattr(p, "tmap:in:next"); } SwigType *pt = Getattr(p, "type"); if (mvr) { // do we assert that numargs=2, that i<2 if (i == 0) { source = NewString("&(property_reference->object)"); } else { source = NewString("&value"); } } else { if (i == 0 && has_this_ptr) { source = NewString("&this_ptr"); } else { source = NewStringf("args[%d]", i - has_this_ptr); } } String *ln = Getattr(p, "lname"); /* Check if optional */ if (i >= num_required) { Printf(f->code, "\tif(arg_count > %d) {\n", i); } if ((tm = Getattr(p, "tmap:in"))) { Replaceall(tm, "$source", source); Replaceall(tm, "$target", ln); Replaceall(tm, "$input", source); Setattr(p, "emit:input", source); Printf(f->code, "%s\n", tm); if (i == 0 && Getattr(p, "self")) { Printf(f->code, "\tif(!arg1) SWIG_PHP_Error(E_ERROR, \"this pointer is NULL\");\n"); } p = Getattr(p, "tmap:in:next"); if (i >= num_required) { Printf(f->code, "}\n"); } continue; } else { Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); } if (i >= num_required) { Printf(f->code, "\t}\n"); } Delete(source); } /* Insert constraint checking code */ for (p = l; p;) { if ((tm = Getattr(p, "tmap:check"))) { Replaceall(tm, "$target", Getattr(p, "lname")); Printv(f->code, tm, "\n", NIL); p = Getattr(p, "tmap:check:next"); } else { p = nextSibling(p); } } /* Insert cleanup code */ for (i = 0, p = l; p; i++) { if ((tm = Getattr(p, "tmap:freearg"))) { Replaceall(tm, "$source", Getattr(p, "lname")); Printv(cleanup, tm, "\n", NIL); p = Getattr(p, "tmap:freearg:next"); } else { p = nextSibling(p); } } /* Insert argument output code */ for (i = 0, p = l; p; i++) { if ((tm = Getattr(p, "tmap:argout"))) { Replaceall(tm, "$source", Getattr(p, "lname")); // Replaceall(tm,"$input",Getattr(p,"lname")); Replaceall(tm, "$target", "return_value"); Replaceall(tm, "$result", "return_value"); Replaceall(tm, "$arg", Getattr(p, "emit:input")); Replaceall(tm, "$input", Getattr(p, "emit:input")); Printv(outarg, tm, "\n", NIL); p = Getattr(p, "tmap:argout:next"); } else { p = nextSibling(p); } } /* emit function call */ emit_action(n, f); if ((tm = Swig_typemap_lookup_new("out", n, "result", 0))) { Replaceall(tm, "$input", "result"); Replaceall(tm, "$source", "result"); Replaceall(tm, "$target", "return_value"); Replaceall(tm, "$result", "return_value"); Replaceall(tm, "$owner", newobject ? "1" : "0"); Printf(f->code, "%s\n", tm); // Are we returning a wrapable object? if (shadow && php_version == 4 && is_shadow(d) && (SwigType_type(d) != T_ARRAY)) { // Make object. Printf(f->code, "{\n/* Wrap this return value */\n"); Printf(f->code, "zval *_cPtr;\n"); Printf(f->code, "ALLOC_ZVAL(_cPtr);\n"); Printf(f->code, "*_cPtr = *return_value;\n"); Printf(f->code, "INIT_ZVAL(*return_value);\n"); if (native_constructor == NATIVE_CONSTRUCTOR) { Printf(f->code, "add_property_zval(this_ptr,\"" SWIG_PTR "\",_cPtr);\n"); } else { String *shadowrettype = SwigToPhpType(d, iname, true); Printf(f->code, "object_init_ex(return_value,ptr_ce_swig_%s);\n", shadowrettype); Delete(shadowrettype); Printf(f->code, "add_property_zval(return_value,\"" SWIG_PTR "\",_cPtr);\n"); } Printf(f->code, "}\n"); } } else { Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name); } if (outarg) { Printv(f->code, outarg, NIL); } if (cleanup) { Printv(f->code, cleanup, NIL); } /* Look to see if there is any newfree cleanup code */ if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup_new("newfree", n, "result", 0))) { Printf(f->code, "%s\n", tm); Delete(tm); } } /* See if there is any return cleanup code */ if ((tm = Swig_typemap_lookup_new("ret", n, "result", 0))) { Printf(f->code, "%s\n", tm); Delete(tm); } if (mvr) { if (!mvrset) { Printf(f->code, "return _return_value;\n"); } else { Printf(f->code, "return SUCCESS;\n"); } } else { Printf(f->code, "return;\n"); } /* Error handling code */ Printf(f->code, "fail:\n"); Printv(f->code, cleanup, NIL); Printv(f->code, "zend_error(SWIG_ErrorCode(),SWIG_ErrorMsg());", NIL); Printf(f->code, "}\n"); Replaceall(f->code, "$cleanup", cleanup); Replaceall(f->code, "$symname", iname); Wrapper_print(f, s_wrappers); // wrap:name is used by overload resolution Setattr(n, "wrap:name", wname); if (overloaded && !Getattr(n, "sym:nextSibling")) { dispatchFunction(n); } Delete(wname); wname = NULL; if (!(shadow && php_version == 5)) { DelWrapper(f); return SWIG_OK; } // Handle getters and setters. if (wrapperType == membervar) { const char *p = Char(iname); if (strlen(p) > 4) { p += strlen(p) - 4; String *varname = Getattr(n, "membervariableHandler:sym:name"); if (strcmp(p, "_get") == 0) { Setattr(shadow_get_vars, varname, iname); } else if (strcmp(p, "_set") == 0) { Setattr(shadow_set_vars, varname, iname); } } } // Only look at non-overloaded methods and the last entry in each overload // chain (we check the last so that wrap:parms and wrap:name have been set // for them all). if (overloaded && Getattr(n, "sym:nextSibling") != 0) return SWIG_OK; if (!s_oowrappers) s_oowrappers = NewStringEmpty(); if (newobject || wrapperType == memberfn || wrapperType == staticmemberfn || wrapperType == standard) { bool handle_as_overload = false; String **arg_names; String **arg_values; // Method or static method or plain function. const char *methodname = 0; String *output = s_oowrappers; if (newobject) { class_has_ctor = true; methodname = "__construct"; } else if (wrapperType == memberfn) { methodname = Char(Getattr(n, "memberfunctionHandler:sym:name")); } else if (wrapperType == staticmemberfn) { methodname = Char(Getattr(n, "staticmemberfunctionHandler:sym:name")); } else { // wrapperType == standard methodname = Char(iname); if (!s_fakeoowrappers) s_fakeoowrappers = NewStringEmpty(); output = s_fakeoowrappers; } bool really_overloaded = overloaded ? true : false; int min_num_of_arguments = emit_num_required(l); int max_num_of_arguments = emit_num_arguments(l); // For a function with default arguments, we end up with the fullest // parmlist in full_parmlist. ParmList *full_parmlist = l; Hash *ret_types = NewHash(); Setattr(ret_types, d, d); if (overloaded) { // Look at all the overloaded versions of this method in turn to // decide if it's really an overloaded method, or just one where some // parameters have default values. Node *o = Getattr(n, "sym:overloaded"); while (o) { if (o == n) { o = Getattr(o, "sym:nextSibling"); continue; } SwigType *d2 = Getattr(o, "type"); if (!d2) { assert(constructor); } else if (!Getattr(ret_types, d2)) { Setattr(ret_types, d2, d2); } ParmList *l2 = Getattr(o, "wrap:parms"); int num_arguments = emit_num_arguments(l2); int num_required = emit_num_required(l2); if (num_required < min_num_of_arguments) min_num_of_arguments = num_required; if (num_arguments > max_num_of_arguments) { max_num_of_arguments = num_arguments; full_parmlist = l2; } o = Getattr(o, "sym:nextSibling"); } o = Getattr(n, "sym:overloaded"); while (o) { if (o == n) { o = Getattr(o, "sym:nextSibling"); continue; } ParmList *l2 = Getattr(o, "wrap:parms"); Parm *p = l, *p2 = l2; if (wrapperType == memberfn) { p = nextSibling(p); p2 = nextSibling(p2); } while (p && p2) { if (Cmp(Getattr(p, "type"), Getattr(p2, "type")) != 0) break; if (Cmp(Getattr(p, "name"), Getattr(p2, "name")) != 0) break; String *value = Getattr(p, "value"); String *value2 = Getattr(p2, "value"); if (value && !value2) break; if (!value && value2) break; if (value) { if (Cmp(value, value2) != 0) break; } p = nextSibling(p); p2 = nextSibling(p2); } if (p && p2) break; // One parameter list is a prefix of the other, so check that all // remaining parameters of the longer list are optional. if (p2) p = p2; while (p && Getattr(p, "value")) p = nextSibling(p); if (p) break; o = Getattr(o, "sym:nextSibling"); } if (!o) { // This "overloaded method" is really just one with default args. really_overloaded = false; if (l != full_parmlist) { l = full_parmlist; if (wrapperType == memberfn) l = nextSibling(l); } } } if (wrapperType == memberfn) { // Allow for the "this" pointer. --min_num_of_arguments; --max_num_of_arguments; } arg_names = (String **) malloc(max_num_of_arguments * sizeof(String *)); if (!arg_names) { /* FIXME: How should this be handled? The rest of SWIG just seems * to not bother checking for malloc failing! */ fprintf(stderr, "Malloc failed!\n"); exit(1); } for (i = 0; i < max_num_of_arguments; ++i) { arg_names[i] = NULL; } arg_values = (String **) malloc(max_num_of_arguments * sizeof(String *)); if (!arg_values) { /* FIXME: How should this be handled? The rest of SWIG just seems * to not bother checking for malloc failing! */ fprintf(stderr, "Malloc failed!\n"); exit(1); } for (i = 0; i < max_num_of_arguments; ++i) { arg_values[i] = NULL; } Node *o; if (overloaded) { o = Getattr(n, "sym:overloaded"); } else { o = n; } while (o) { int argno = 0; Parm *p = Getattr(o, "wrap:parms"); if (wrapperType == memberfn) p = nextSibling(p); while (p) { assert(0 <= argno && argno < max_num_of_arguments); String *&pname = arg_names[argno]; const char *pname_cstr = GetChar(p, "name"); if (!pname_cstr) { // Unnamed parameter, e.g. int foo(int); } else if (pname == NULL) { pname = NewString(pname_cstr); } else { size_t len = strlen(pname_cstr); size_t spc = 0; size_t len_pname = strlen(Char(pname)); while (spc + len <= len_pname) { if (strncmp(pname_cstr, Char(pname) + spc, len) == 0) { char ch = ((char *) Char(pname))[spc + len]; if (ch == '\0' || ch == ' ') { // Already have this pname_cstr. pname_cstr = NULL; break; } } char *p = strchr(Char(pname) + spc, ' '); if (!p) break; spc = (p + 4) - Char(pname); } if (pname_cstr) { Printf(pname, " or_%s", pname_cstr); } } String *value = NewString(Getattr(p, "value")); if (Len(value)) { /* Check that value is a valid constant in PHP (and adjust it if * necessary, or replace it with "?" if it's just not valid). */ SwigType *type = Getattr(p, "type"); switch (SwigType_type(type)) { case T_BOOL: { if (Strcmp(value, "true") == 0 || Strcmp(value, "false") == 0) break; char *p; errno = 0; int n = strtol(Char(value), &p, 0); Clear(value); if (errno || *p) { Append(value, "?"); } else if (n) { Append(value, "true"); } else { Append(value, "false"); } break; } case T_CHAR: case T_SCHAR: case T_SHORT: case T_INT: case T_LONG: { char *p; errno = 0; (void) strtol(Char(value), &p, 0); if (errno || *p) { Clear(value); Append(value, "?"); } break; } case T_UCHAR: case T_USHORT: case T_UINT: case T_ULONG: { char *p; errno = 0; (void) strtoul(Char(value), &p, 0); if (errno || *p) { Clear(value); Append(value, "?"); } break; } case T_FLOAT: case T_DOUBLE:{ char *p; errno = 0; /* FIXME: strtod is locale dependent... */ double val = strtod(Char(value), &p); if (errno || *p) { Clear(value); Append(value, "?"); } else if (strchr(Char(value), '.') == NULL) { // Ensure value is a double constant, not an integer one. Append(value, ".0"); double val2 = strtod(Char(value), &p); if (errno || *p || val != val2) { Clear(value); Append(value, "?"); } } break; } case T_REFERENCE: case T_USER: case T_ARRAY: Clear(value); Append(value, "?"); break; case T_STRING: if (Len(value) < 2) { // How can a string (including "" be less than 2 characters?) Clear(value); Append(value, "?"); } else { const char *v = Char(value); if (v[0] != '"' || v[Len(value) - 1] != '"') { Clear(value); Append(value, "?"); } // Strings containing "$" require special handling, but we do // that later. } break; case T_VOID: assert(false); break; case T_POINTER: { const char *v = Char(value); if (v[0] == '(') { // Handle "(void*)0", "(TYPE*)0", "(char*)NULL", etc. v += strcspn(v + 1, "*()") + 1; if (*v == '*') { do { v++; v += strspn(v, " \t"); } while (*v == '*'); if (*v++ == ')') { v += strspn(v, " \t"); String * old = value; value = NewString(v); Delete(old); } } } if (Strcmp(value, "NULL") == 0 || Strcmp(value, "0") == 0 || Strcmp(value, "0L") == 0) { Clear(value); Append(value, "null"); } else { Clear(value); Append(value, "?"); } break; } } if (!arg_values[argno]) { arg_values[argno] = value; value = NULL; } else if (Cmp(arg_values[argno], value) != 0) { // If a parameter has two different default values in // different overloaded forms of the function, we can't // set its default in PHP. Flag this by setting its // default to `?'. Delete(arg_values[argno]); arg_values[argno] = NewString("?"); } } else if (arg_values[argno]) { // This argument already has a default value in another overloaded // form, but doesn't in this form. So don't try to do anything // clever, just let the C wrappers resolve the overload and set the // default values. // // This handling is safe, but I'm wondering if it may be overly // conservative (FIXME) in some cases. It seems it's only bad when // there's an overloaded form with the appropriate number of // parameters which doesn't want the default value, but I need to // think about this more. Delete(arg_values[argno]); arg_values[argno] = NewString("?"); } Delete(value); p = nextSibling(p); ++argno; } if (!really_overloaded) break; o = Getattr(o, "sym:nextSibling"); } /* Clean up any parameters which haven't yet got names, or whose * names clash. */ Hash *seen = NewHash(); /* We need $this to refer to the current class, so can't allow it * to be used as a parameter. */ Setattr(seen, "this", seen); /* We use $r to store the return value, so disallow that as a parameter * name in case the user uses the "call-time pass-by-reference" feature * (it's deprecated and off by default in PHP5 and even later PHP4 * versions apparently, but we want to be maximally portable). */ Setattr(seen, "r", seen); for (int argno = 0; argno < max_num_of_arguments; ++argno) { String *&pname = arg_names[argno]; if (pname) { Replaceall(pname, " ", "_"); } else { /* We get here if the SWIG .i file has "int foo(int);" */ pname = NewStringEmpty(); Printf(pname, "arg%d", argno + 1); } // Check if we've already used this parameter name. while (Getattr(seen, pname)) { // Append "_" to clashing names until they stop clashing... Printf(pname, "_"); } Setattr(seen, Char(pname), seen); if (arg_values[argno] && Cmp(arg_values[argno], "?") == 0) { handle_as_overload = true; } } Delete(seen); seen = NULL; String *invoke = NewStringEmpty(); String *prepare = NewStringEmpty(); String *args = NewStringEmpty(); if (!handle_as_overload && !(really_overloaded && max_num_of_arguments > min_num_of_arguments)) { Printf(invoke, "%s(", iname); if (wrapperType == memberfn) { Printf(invoke, "$this->%s", SWIG_PTR); } for (int i = 0; i < max_num_of_arguments; ++i) { if (i) Printf(args, ","); if (i || wrapperType == memberfn) Printf(invoke, ","); String *value = arg_values[i]; if (value) { const char *v = Char(value); if (v[0] == '"') { /* In a PHP double quoted string, $ needs to be escaped as \$. */ Replaceall(value, "$", "\\$"); } Printf(args, "$%s=%s", arg_names[i], value); } else { Printf(args, "$%s", arg_names[i]); } Printf(invoke, "$%s", arg_names[i]); } Printf(invoke, ")"); } else { int i; for (i = 0; i < min_num_of_arguments; ++i) { if (i) Printf(args, ","); Printf(args, "$%s", arg_names[i]); } String *invoke_args = NewStringEmpty(); if (wrapperType == memberfn) { Printf(invoke_args, "$this->%s", SWIG_PTR); if (min_num_of_arguments > 0) Printf(invoke_args, ","); } Printf(invoke_args, "%s", args); bool had_a_case = false; int last_handled_i = i - 1; for (; i < max_num_of_arguments; ++i) { if (i) Printf(args, ","); const char *value = Char(arg_values[i]); // FIXME: (really_overloaded && handle_as_overload) is perhaps a // little conservative, but it doesn't hit any cases that it // shouldn't for Xapian at least (and we need it to handle // "Enquire::get_mset()" correctly). bool non_php_default = ((really_overloaded && handle_as_overload) || !value || strcmp(value, "?") == 0); if (non_php_default) value = "null"; Printf(args, "$%s=%s", arg_names[i], value); if (non_php_default) { if (!had_a_case) { Printf(prepare, "\t\tswitch (func_num_args()) {\n"); had_a_case = true; } Printf(prepare, "\t\t"); while (last_handled_i < i) { Printf(prepare, "case %d: ", ++last_handled_i); } if (Cmp(d, "void") != 0) Printf(prepare, "$r="); Printf(prepare, "%s(%s); break;\n", iname, invoke_args); } if (i || wrapperType == memberfn) Printf(invoke_args, ","); Printf(invoke_args, "$%s", arg_names[i]); } Printf(prepare, "\t\t"); if (had_a_case) Printf(prepare, "default: "); if (Cmp(d, "void") != 0) Printf(prepare, "$r="); Printf(prepare, "%s(%s);\n", iname, invoke_args); if (had_a_case) Printf(prepare, "\t\t}\n"); Delete(invoke_args); Printf(invoke, "$r"); } Printf(output, "\n"); if (wrapperType == memberfn || newobject) { Printf(output, "\tfunction %s(%s) {\n", methodname, args); // We don't need this code if the wrapped class has a copy ctor // since the flat function new_CLASSNAME will handle it for us. if (newobject && !Getattr(current_class, "allocate:copy_constructor")) { SwigType *t = Getattr(current_class, "classtype"); String *mangled_type = SwigType_manglestr(SwigType_ltype(t)); Printf(s_oowrappers, "\t\tif (is_resource($%s) && get_resource_type($%s) == \"_p%s\") {\n", arg_names[0], arg_names[0], mangled_type); Printf(s_oowrappers, "\t\t\t$this->%s=$%s;\n", SWIG_PTR, arg_names[0]); Printf(s_oowrappers, "\t\t\treturn;\n"); Printf(s_oowrappers, "\t\t}\n"); } } else { Printf(output, "\tstatic function %s(%s) {\n", methodname, args); } Delete(args); args = NULL; for (int i = 0; i < max_num_of_arguments; ++i) { Delete(arg_names[i]); } free(arg_names); arg_names = NULL; Printf(output, "%s", prepare); if (newobject) { Printf(output, "\t\t$this->%s=%s;\n", SWIG_PTR, invoke); } else if (Cmp(d, "void") == 0) { if (Cmp(invoke, "$r") != 0) Printf(output, "\t\t%s;\n", invoke); } else if (is_class(d)) { if (Cmp(invoke, "$r") != 0) Printf(output, "\t\t$r=%s;\n", invoke); if (Len(ret_types) == 1) { Printf(output, "\t\treturn is_resource($r) ? new %s%s($r) : $r;\n", prefix, Getattr(classLookup(d), "sym:name")); } else { Printf(output, "\t\tif (!is_resource($r)) return $r;\n"); Printf(output, "\t\tswitch (get_resource_type($r)) {\n"); Iterator i = First(ret_types); while (i.item) { SwigType *ret_type = i.item; i = Next(i); Printf(output, "\t\t"); String *mangled = NewString("_p"); Printf(mangled, "%s", SwigType_manglestr(ret_type)); Node *class_node = Getattr(zend_types, mangled); if (!class_node) { /* This is needed when we're returning a pointer to a type * rather than returning the type by value or reference. */ class_node = current_class; Delete(mangled); mangled = NewString(SwigType_manglestr(ret_type)); class_node = Getattr(zend_types, mangled); } if (i.item) { Printf(output, "case \"%s\": ", mangled); } else { Printf(output, "default: "); } const char *classname = GetChar(class_node, "sym:name"); if (!classname) classname = GetChar(class_node, "name"); if (classname) Printf(output, "return new %s%s($r);\n", prefix, classname); else Printf(output, "return $r;\n"); Delete(mangled); } Printf(output, "\t\t}\n"); } } else { Printf(output, "\t\treturn %s;\n", invoke); } Printf(output, "\t}\n"); Delete(prepare); Delete(invoke); free(arg_values); } DelWrapper(f); return SWIG_OK; } /* ------------------------------------------------------------ * globalvariableHandler() * ------------------------------------------------------------ */ virtual int globalvariableHandler(Node *n) { char *name = GetChar(n, "name"); char *iname = GetChar(n, "sym:name"); SwigType *t = Getattr(n, "type"); String *tm; /* First do the wrappers such as name_set(), name_get() * as provided by the baseclass's implementation of variableWrapper */ if (Language::globalvariableHandler(n) == SWIG_NOWRAP) { return SWIG_NOWRAP; } if (!addSymbol(iname, n)) return SWIG_ERROR; SwigType_remember(t); /* First link C variables to PHP */ tm = Swig_typemap_lookup_new("varinit", n, name, 0); if (tm) { Replaceall(tm, "$target", name); Printf(s_vinit, "%s\n", tm); } else { Printf(stderr, "%s: Line %d, Unable to link with type %s\n", input_file, line_number, SwigType_str(t, 0)); } /* Now generate PHP -> C sync blocks */ /* tm = Swig_typemap_lookup_new("varin", n, name, 0); if(tm) { Replaceall(tm, "$symname", iname); Printf(f_c->code, "%s\n", tm); } else { Printf(stderr,"%s: Line %d, Unable to link with type %s\n", input_file, line_number, SwigType_str(t, 0)); } */ /* Now generate C -> PHP sync blocks */ /* if(!GetFlag(n,"feature:immutable")) { tm = Swig_typemap_lookup_new("varout", n, name, 0); if(tm) { Replaceall(tm, "$symname", iname); Printf(f_php->code, "%s\n", tm); } else { Printf(stderr,"%s: Line %d, Unable to link with type %s\n", input_file, line_number, SwigType_str(t, 0)); } } */ return SWIG_OK; } /* ------------------------------------------------------------ * constantWrapper() * ------------------------------------------------------------ */ virtual int constantWrapper(Node *n) { String *name = GetChar(n, "name"); String *iname = GetChar(n, "sym:name"); SwigType *type = Getattr(n, "type"); String *rawval = Getattr(n, "rawval"); String *value = rawval ? rawval : Getattr(n, "value"); String *tm; if (!addSymbol(iname, n)) return SWIG_ERROR; SwigType_remember(type); if ((tm = Swig_typemap_lookup_new("consttab", n, name, 0))) { Replaceall(tm, "$source", value); Replaceall(tm, "$target", name); Replaceall(tm, "$value", value); Printf(s_cinit, "%s\n", tm); } if (shadow && php_version == 5) { String *enumvalue = GetChar(n, "enumvalue"); String *set_to = iname; if (!enumvalue) { enumvalue = GetChar(n, "enumvalueex"); } if (enumvalue) { // Check for a simple constant expression which is valid in PHP. // If we find one, initialise the const member with it; otherwise // we initialise it using the C/C++ wrapped constant. const char *p; for (p = Char(enumvalue); *p; ++p) { if (!isdigit((unsigned char)*p) && !strchr(" +-", *p)) { // FIXME: enhance to handle `<previous_enum> + 1' which is what // we get for enums that don't have an explicit value set. break; } } if (!*p) set_to = enumvalue; } if (wrapping_member_constant) { if (!s_oowrappers) s_oowrappers = NewStringEmpty(); Printf(s_oowrappers, "\n\tconst %s = %s;\n", wrapping_member_constant, set_to); } else { if (!s_fakeoowrappers) s_fakeoowrappers = NewStringEmpty(); Printf(s_fakeoowrappers, "\n\tconst %s = %s;\n", name, set_to); } } return SWIG_OK; } /* * PHP::pragma() * * Pragma directive. * * %pragma(php4) code="String" # Includes a string in the .php file * %pragma(php4) include="file.pl" # Includes a file in the .php file */ virtual int pragmaDirective(Node *n) { if (!ImportMode) { String *lang = Getattr(n, "lang"); String *type = Getattr(n, "name"); String *value = Getattr(n, "value"); if (Strcmp(lang, "php4") == 0) { if (Strcmp(type, "code") == 0) { if (value) { Printf(pragma_code, "%s\n", value); } } else if (Strcmp(type, "include") == 0) { if (value) { Printf(pragma_incl, "include \"%s\";\n", value); } } else if (Strcmp(type, "phpinfo") == 0) { if (value) { Printf(pragma_phpinfo, "%s\n", value); } } else { Swig_warning(WARN_PHP4_UNKNOWN_PRAGMA, input_file, line_number, "Unrecognized pragma <%s>.\n", type); } } } return Language::pragmaDirective(n); } /* ------------------------------------------------------------ * classDeclaration() * ------------------------------------------------------------ */ virtual int classDeclaration(Node *n) { if (!Getattr(n, "feature:onlychildren")) { String *symname = Getattr(n, "sym:name"); Setattr(n, "php:proxy", symname); } return Language::classDeclaration(n); } /* ------------------------------------------------------------ * classHandler() * ------------------------------------------------------------ */ virtual int classHandler(Node *n) { constructors = 0; //SwigType *t = Getattr(n, "classtype"); current_class = n; // String *use_class_name=SwigType_manglestr(SwigType_ltype(t)); if (shadow && php_version == 4) { char *rename = GetChar(n, "sym:name"); if (!addSymbol(rename, n)) return SWIG_ERROR; shadow_classname = NewString(rename); cs_entry = NewStringEmpty(); Printf(cs_entry, "/* Function entries for %s */\n", shadow_classname); Printf(cs_entry, "static zend_function_entry %s_functions[] = {\n", shadow_classname); if (Strcmp(shadow_classname, module) == 0) { Printf(stderr, "class name cannot be equal to module name: %s\n", module); SWIG_exit(1); } shadow_get_vars = NewHash(); shadow_set_vars = NewHash(); /* Deal with inheritance */ List *baselist = Getattr(n, "bases"); if (baselist) { Iterator base = First(baselist); while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } base = Next(base); if (base.item) { /* Warn about multiple inheritance for additional base class(es) */ while (base.item) { if (GetFlag(base.item, "feature:ignore")) { base = Next(base); continue; } String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0); String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0); Swig_warning(WARN_PHP4_MULTIPLE_INHERITANCE, input_file, line_number, "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Php4.\n", proxyclassname, baseclassname); base = Next(base); } } } /* Write out class init code */ Printf(s_vdecl, "static zend_class_entry ce_swig_%s;\n", shadow_classname); Printf(s_vdecl, "static zend_class_entry* ptr_ce_swig_%s=NULL;\n", shadow_classname); } else if (shadow && php_version == 5) { char *rename = GetChar(n, "sym:name"); if (!addSymbol(rename, n)) return SWIG_ERROR; shadow_classname = NewString(rename); shadow_get_vars = NewHash(); shadow_set_vars = NewHash(); /* Deal with inheritance */ List *baselist = Getattr(n, "bases"); if (baselist) { Iterator base = First(baselist); while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } base = Next(base); if (base.item) { /* Warn about multiple inheritance for additional base class(es) */ while (base.item) { if (GetFlag(base.item, "feature:ignore")) { base = Next(base); continue; } String *proxyclassname = SwigType_str(Getattr(n, "classtypeobj"), 0); String *baseclassname = SwigType_str(Getattr(base.item, "name"), 0); Swig_warning(WARN_PHP4_MULTIPLE_INHERITANCE, input_file, line_number, "Warning for %s proxy: Base %s ignored. Multiple inheritance is not supported in Php4.\n", proxyclassname, baseclassname); base = Next(base); } } } } classnode = n; Language::classHandler(n); classnode = 0; if (shadow && php_version == 4) { DOH *key; String *s_propget = NewStringEmpty(); String *s_propset = NewStringEmpty(); List *baselist = Getattr(n, "bases"); Iterator ki, base; // If no constructor was generated (abstract class) we had better // generate a constructor that raises an error about instantiating // abstract classes if (Getattr(n, "abstract") && constructors == 0) { // have to write out fake constructor which raises an error when called abstractConstructorHandler(n); } Printf(s_oinit, "/* Define class %s */\n", shadow_classname); Printf(s_oinit, "INIT_OVERLOADED_CLASS_ENTRY(ce_swig_%s,\"%(lower)s\",%s_functions,", shadow_classname, shadow_classname, shadow_classname); Printf(s_oinit, "NULL,_wrap_propget_%s,_wrap_propset_%s);\n", shadow_classname, shadow_classname); // ******** Write property SET handlers Printf(s_header, "static int _wrap_propset_%s(zend_property_reference *property_reference, pval *value);\n", shadow_classname); Printf(s_header, "static int _propset_%s(zend_property_reference *property_reference, pval *value);\n", shadow_classname); Printf(s_propset, "static int _wrap_propset_%s(zend_property_reference *property_reference, pval *value) { \n", shadow_classname); Printf(s_propset, " zval * _value;\n"); Printf(s_propset, " zend_llist_element *element = property_reference->elements_list->head;\n"); Printf(s_propset, " zend_overloaded_element *property=(zend_overloaded_element *)element->data;\n"); Printf(s_propset, " if (_propset_%s(property_reference, value)==SUCCESS) return SUCCESS;\n", shadow_classname); Printf(s_propset, " /* set it ourselves as it is %s */\n", shadow_classname); Printf(s_propset, " MAKE_STD_ZVAL(_value);\n"); Printf(s_propset, " *_value=*value;\n"); Printf(s_propset, " INIT_PZVAL(_value);\n"); Printf(s_propset, " zval_copy_ctor(_value);\n"); Printf(s_propset, " return add_property_zval_ex(property_reference->object,Z_STRVAL_P(&(property->element)),1+Z_STRLEN_P(&(property->element)),_value);\n"); Printf(s_propset, "}\n"); Printf(s_propset, "static int _propset_%s(zend_property_reference *property_reference, pval *value) {\n", shadow_classname); if (baselist) { base = First(baselist); } else { base.item = NULL; } while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } ki = First(shadow_set_vars); key = ki.key; // Print function header; we only need to find property name if there // are properties for this class to look up... if (key || !base.item) { // or if we are base class and set it ourselves Printf(s_propset, " /* get the property name */\n"); Printf(s_propset, " zend_llist_element *element = property_reference->elements_list->head;\n"); Printf(s_propset, " zend_overloaded_element *property=(zend_overloaded_element *)element->data;\n"); Printf(s_propset, " char *propname=Z_STRVAL_P(&(property->element));\n"); } else { if (base.item) { Printf(s_propset, " /* No extra properties for subclass %s */\n", shadow_classname); } else { Printf(s_propset, " /* No properties for base class %s */\n", shadow_classname); } } while (ki.key) { key = ki.key; Printf(s_propset, " if (strcmp(propname,\"%s\")==0) return _wrap_%s(property_reference, value);\n", ki.item, key); ki = Next(ki); } // If the property wasn't in this class, try the handlers of each base // class (if any) in turn until we succeed in setting the property or // have tried all base classes. if (base.item) { Printf(s_propset, " /* Try base class(es) */\n"); while (base.item) { Printf(s_propset, " if (_propset_%s(property_reference, value)==SUCCESS) return SUCCESS;\n", GetChar(base.item, "sym:name")); base = Next(base); while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } } } Printf(s_propset, " return FAILURE;\n}\n\n"); // ******** Write property GET handlers Printf(s_header, "static pval _wrap_propget_%s(zend_property_reference *property_reference);\n", shadow_classname); Printf(s_header, "static int _propget_%s(zend_property_reference *property_reference, pval *value);\n", shadow_classname); Printf(s_propget, "static pval _wrap_propget_%s(zend_property_reference *property_reference) {\n", shadow_classname); Printf(s_propget, " pval result;\n"); Printf(s_propget, " pval **_result;\n"); Printf(s_propget, " zend_llist_element *element = property_reference->elements_list->head;\n"); Printf(s_propget, " zend_overloaded_element *property=(zend_overloaded_element *)element->data;\n"); Printf(s_propget, " result.type = IS_NULL;\n"); Printf(s_propget, " if (_propget_%s(property_reference, &result)==SUCCESS) return result;\n", shadow_classname); Printf(s_propget, " /* return it ourselves */\n"); Printf(s_propget, " if (zend_hash_find(Z_OBJPROP_P(property_reference->object),Z_STRVAL_P(&(property->element)),1+Z_STRLEN_P(&(property->element)),(void**)&_result)==SUCCESS) {\n"); Printf(s_propget, " zval *_value;\n"); Printf(s_propget, " MAKE_STD_ZVAL(_value);"); Printf(s_propget, " *_value=**_result;\n"); Printf(s_propget, " INIT_PZVAL(_value);\n"); Printf(s_propget, " zval_copy_ctor(_value);\n"); Printf(s_propget, " return *_value;\n"); Printf(s_propget, " }\n"); Printf(s_propget, " result.type = IS_NULL;\n"); Printf(s_propget, " return result;\n"); Printf(s_propget, "}\n"); Printf(s_propget, "static int _propget_%s(zend_property_reference *property_reference, pval *value) {\n", shadow_classname); if (baselist) { base = First(baselist); } else { base.item = NULL; } while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } ki = First(shadow_get_vars); key = ki.key; // Print function header; we only need to find property name if there // are properties for this class to look up... if (key || !base.item) { // or if we are base class... Printf(s_propget, " /* get the property name */\n"); Printf(s_propget, " zend_llist_element *element = property_reference->elements_list->head;\n"); Printf(s_propget, " zend_overloaded_element *property=(zend_overloaded_element *)element->data;\n"); Printf(s_propget, " char *propname=Z_STRVAL_P(&(property->element));\n"); } else { if (base.item) { Printf(s_propget, " /* No extra properties for subclass %s */\n", shadow_classname); } else { Printf(s_propget, " /* No properties for base class %s */\n", shadow_classname); } } while (ki.key) { key = ki.key; Printf(s_propget, " if (strcmp(propname,\"%s\")==0) {\n", ki.item); Printf(s_propget, " *value=_wrap_%s(property_reference);\n", key); Printf(s_propget, " return SUCCESS;\n"); Printf(s_propget, " }\n"); ki = Next(ki); } // If the property wasn't in this class, try the handlers of each base // class (if any) in turn until we succeed in setting the property or // have tried all base classes. if (base.item) { Printf(s_propget, " /* Try base class(es). */\n"); while (base.item) { Printf(s_propget, " if (_propget_%s(property_reference, value)==SUCCESS) return SUCCESS;\n", GetChar(base.item, "sym:name")); base = Next(base); while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } } } Printf(s_propget, " return FAILURE;\n}\n\n"); // wrappers generated now... // add wrappers to output code Printf(s_wrappers, "/* property handler for class %s */\n", shadow_classname); Printv(s_wrappers, s_propget, s_propset, NIL); // Save class in class table if (baselist) { base = First(baselist); } else { base.item = NULL; } while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } if (base.item) { Printf(s_oinit, "if (! (ptr_ce_swig_%s=zend_register_internal_class_ex(&ce_swig_%s,&ce_swig_%s,NULL TSRMLS_CC))) zend_error(E_ERROR,\"Error registering wrapper for class %s\");\n", shadow_classname, shadow_classname, GetChar(base.item, "sym:name"), shadow_classname); } else { Printf(s_oinit, "if (! (ptr_ce_swig_%s=zend_register_internal_class_ex(&ce_swig_%s,NULL,NULL TSRMLS_CC))) zend_error(E_ERROR,\"Error registering wrapper for class %s\");\n", shadow_classname, shadow_classname, shadow_classname); } Printf(s_oinit, "\n"); // Write the enum initialisation code in a static block // These are all the enums defined within the C++ class. Delete(shadow_classname); shadow_classname = NULL; Delete(shadow_set_vars); shadow_set_vars = NULL; Delete(shadow_get_vars); shadow_get_vars = NULL; Printv(all_cs_entry, cs_entry, " { NULL, NULL, NULL}\n};\n", NIL); Delete(cs_entry); cs_entry = NULL; } else if (shadow && php_version == 5) { DOH *key; List *baselist = Getattr(n, "bases"); Iterator ki, base; if (baselist) { base = First(baselist); while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } } else { base.item = NULL; } if (Getattr(n, "abstract")) { Printf(s_phpclasses, "abstract "); } Printf(s_phpclasses, "class %s%s ", prefix, shadow_classname); if (base.item) { String *baseclass = Getattr(base.item, "sym:name"); if (!baseclass) baseclass = Getattr(base.item, "name"); Printf(s_phpclasses, "extends %s%s ", prefix, baseclass); } Printf(s_phpclasses, "{\n\tpublic $%s=null;\n", SWIG_PTR); // Write property SET handlers ki = First(shadow_set_vars); if (ki.key) { // This class has setters. // FIXME: just ignore setting an unknown property name for now. Printf(s_phpclasses, "\n\tfunction __set($var,$value) {\n"); // FIXME: tune this threshold... if (Len(shadow_set_vars) <= 2) { // Not many setters, so avoid call_user_func. while (ki.key) { key = ki.key; Printf(s_phpclasses, "\t\tif ($var == '%s') return %s($this->%s,$value);\n", key, ki.item, SWIG_PTR); ki = Next(ki); } } else { Printf(s_phpclasses, "\t\t$func = '%s_'.$var.'_set';\n", shadow_classname); Printf(s_phpclasses, "\t\tif (function_exists($func)) call_user_func($func,$this->%s,$value);\n", SWIG_PTR); } Printf(s_phpclasses, "\t}\n"); /* Create __isset for PHP 5.1 and later; PHP 5.0 will just ignore it. */ Printf(s_phpclasses, "\n\tfunction __isset($var) {\n"); // FIXME: tune this threshold, but it should probably be different to // that for __set() and __get() as we don't need to call_user_func() // here... if (Len(shadow_set_vars) == 1) { // Only one setter, so just check the name. Printf(s_phpclasses, "\t\treturn "); while (ki.key) { key = ki.key; Printf(s_phpclasses, "$var == '%s'", ki.key); ki = Next(ki); if (ki.key) Printf(s_phpclasses, " || "); } Printf(s_phpclasses, ";\n"); } else { Printf(s_phpclasses, "\t\treturn function_exists('%s_'.$var.'_set');\n", shadow_classname); } Printf(s_phpclasses, "\t}\n"); } // Write property GET handlers ki = First(shadow_get_vars); if (ki.key) { // This class has getters. Printf(s_phpclasses, "\n\tfunction __get($var) {\n"); // FIXME: tune this threshold... if (Len(shadow_get_vars) <= 2) { // Not many getters, so avoid call_user_func. while (ki.key) { key = ki.key; Printf(s_phpclasses, "\t\tif ($var == '%s') return %s($this->%s);\n", key, ki.item, SWIG_PTR); ki = Next(ki); } } else { Printf(s_phpclasses, "\t\t$func = '%s_'.$var.'_get';\n", shadow_classname); Printf(s_phpclasses, "\t\tif (function_exists($func)) return call_user_func($func,$this->%s);\n", SWIG_PTR); } // Reading an unknown property name gives null in PHP. Printf(s_phpclasses, "\t\treturn null;\n"); Printf(s_phpclasses, "\t}\n"); } if (!class_has_ctor) { Printf(s_phpclasses, "\tfunction __construct($h) {\n"); Printf(s_phpclasses, "\t\t$this->%s=$h;\n", SWIG_PTR); Printf(s_phpclasses, "\t}\n"); } if (s_oowrappers) { Printf(s_phpclasses, "%s", s_oowrappers); Delete(s_oowrappers); s_oowrappers = NULL; } class_has_ctor = false; Printf(s_phpclasses, "}\n\n"); Delete(shadow_classname); shadow_classname = NULL; Delete(shadow_set_vars); shadow_set_vars = NULL; Delete(shadow_get_vars); shadow_get_vars = NULL; } return SWIG_OK; } /* ------------------------------------------------------------ * memberfunctionHandler() * ------------------------------------------------------------ */ virtual int memberfunctionHandler(Node *n) { char *name = GetChar(n, "name"); char *iname = GetChar(n, "sym:name"); wrapperType = memberfn; this->Language::memberfunctionHandler(n); wrapperType = standard; // Only declare the member function if // we are doing shadow classes, and the function // is not overloaded, or if it is overloaded, it is the dispatch function. if (shadow && php_version == 4 && (!Getattr(n, "sym:overloaded") || !Getattr(n, "sym:nextSibling"))) { char *realname = iname ? iname : name; String *php_function_name = Swig_name_member(shadow_classname, realname); create_command(realname, Swig_name_wrapper(php_function_name)); } return SWIG_OK; } /* ------------------------------------------------------------ * membervariableHandler() * ------------------------------------------------------------ */ virtual int membervariableHandler(Node *n) { wrapperType = membervar; Language::membervariableHandler(n); wrapperType = standard; return SWIG_OK; } /* ------------------------------------------------------------ * staticmembervariableHandler() * ------------------------------------------------------------ */ virtual int staticmembervariableHandler(Node *n) { wrapperType = staticmembervar; Language::staticmembervariableHandler(n); wrapperType = standard; SwigType *type = Getattr(n, "type"); String *name = Getattr(n, "name"); String *iname = Getattr(n, "sym:name"); /* A temporary(!) hack for static member variables. * Php currently supports class functions, but not class variables. * Until it does, we convert a class variable to a class function * that returns the current value of the variable. E.g. * * class Example { * public: * static int ncount; * }; * * would be available in php as Example::ncount() */ // If the variable is const, then it's wrapped as a constant with set/get functions. if (SwigType_isconst(type)) return SWIG_OK; // This duplicates the logic from Language::variableWrapper() to test if the set wrapper // is made. int assignable = is_assignable(n); if (assignable) { String *tm = Swig_typemap_lookup_new("globalin", n, name, 0); if (!tm && SwigType_isarray(type)) { assignable = 0; } } String *class_iname = Swig_name_member(Getattr(current_class, "sym:name"), iname); create_command(iname, Swig_name_wrapper(class_iname)); Wrapper *f = NewWrapper(); Printv(f->def, "ZEND_NAMED_FUNCTION(", Swig_name_wrapper(class_iname), ") {\n", NIL); String *mget = Swig_name_wrapper(Swig_name_get(class_iname)); String *mset = Swig_name_wrapper(Swig_name_set(class_iname)); if (assignable) { Printf(f->code, "if (ZEND_NUM_ARGS() > 0 ) {\n"); Printf(f->code, " %s( INTERNAL_FUNCTION_PARAM_PASSTHRU );\n", mset); Printf(f->code, " // need some error checking here?\n"); Printf(f->code, " // Set the argument count to 0 for the get call\n"); Printf(f->code, " ht = 0;\n"); Printf(f->code, "}\n"); } Printf(f->code, "%s( INTERNAL_FUNCTION_PARAM_PASSTHRU );\n", mget); Printf(f->code, "}\n"); Wrapper_print(f, s_wrappers); Delete(class_iname); Delete(mget); Delete(mset); DelWrapper(f); return SWIG_OK; } /* ------------------------------------------------------------ * staticmemberfunctionHandler() * ------------------------------------------------------------ */ virtual int staticmemberfunctionHandler(Node *n) { char *name = GetChar(n, "name"); char *iname = GetChar(n, "sym:name"); wrapperType = staticmemberfn; Language::staticmemberfunctionHandler(n); wrapperType = standard; if (shadow && php_version == 4) { String *symname = Getattr(n, "sym:name"); char *realname = iname ? iname : name; String *php_function_name = Swig_name_member(shadow_classname, realname); create_command(symname, Swig_name_wrapper(php_function_name)); } return SWIG_OK; } String * SwigToPhpType(SwigType *t, String_or_char *pname, int shadow_flag) { String *ptype = 0; if (shadow_flag) { ptype = PhpTypeFromTypemap((char *) "pstype", t, pname, (char *) ""); } if (!ptype) { ptype = PhpTypeFromTypemap((char *) "ptype", t, pname, (char *) ""); } if (ptype) return ptype; /* Map type here */ switch (SwigType_type(t)) { case T_CHAR: case T_SCHAR: case T_UCHAR: case T_SHORT: case T_USHORT: case T_INT: case T_UINT: case T_LONG: case T_ULONG: case T_FLOAT: case T_DOUBLE: case T_BOOL: case T_STRING: case T_VOID: break; case T_POINTER: case T_REFERENCE: case T_USER: if (shadow_flag && is_shadow(t)) { return NewString(Char(is_shadow(t))); } break; case T_ARRAY: /* TODO */ break; default: Printf(stderr, "SwigToPhpType: unhandled data type: %s\n", SwigType_str(t, 0)); break; } return NewStringEmpty(); } String *PhpTypeFromTypemap(char *op, SwigType *t, String_or_char *pname, String_or_char *lname) { String *tms; tms = Swig_typemap_lookup(op, t, pname, lname, (char *) "", (char *) "", NULL); if (!tms) { return NULL; } char *start = Char(tms); while (isspace(*start) || *start == '{') { start++; } char *end = start; while (*end && *end != '}') { end++; } return NewStringWithSize(start, end - start); } int abstractConstructorHandler(Node *n) { String *iname = GetChar(n, "sym:name"); if (shadow && php_version == 4) { Wrapper *f = NewWrapper(); String *wname = NewStringf("_wrap_new_%s", iname); create_command(iname, wname); Printf(f->def, "ZEND_NAMED_FUNCTION(_wrap_new_%s) {\n", iname); Printf(f->def, " zend_error(E_ERROR,\"Cannot create swig object type: %s as the underlying class is abstract\");\n", iname); Printf(f->def, "}\n\n"); Wrapper_print(f, s_wrappers); DelWrapper(f); Delete(wname); } return SWIG_OK; } /* ------------------------------------------------------------ * constructorHandler() * ------------------------------------------------------------ */ virtual int constructorHandler(Node *n) { char *name = GetChar(n, "name"); char *iname = GetChar(n, "sym:name"); if (shadow && php_version == 4) { if (iname && strcmp(iname, Char(shadow_classname)) == 0) { native_constructor = NATIVE_CONSTRUCTOR; } else { native_constructor = ALTERNATIVE_CONSTRUCTOR; } } else { native_constructor = 0; } constructors++; wrapperType = constructor; Language::constructorHandler(n); wrapperType = standard; if (shadow && php_version == 4) { if (!Getattr(n, "sym:overloaded") || !Getattr(n, "sym:nextSibling")) { char *realname = iname ? iname : name; String *php_function_name = Swig_name_construct(realname); create_command(realname, Swig_name_wrapper(php_function_name)); } } native_constructor = 0; return SWIG_OK; } /* ------------------------------------------------------------ * CreateZendListDestructor() * ------------------------------------------------------------ */ //virtual int destructorHandler(Node *n) { //} int CreateZendListDestructor(Node *n) { String *name = GetChar(Swig_methodclass(n), "name"); String *iname = GetChar(n, "sym:name"); SwigType *d = Getattr(n, "type"); ParmList *l = Getattr(n, "parms"); String *destructorname = NewStringEmpty(); Printf(destructorname, "_%s", Swig_name_wrapper(iname)); Setattr(classnode, "destructor", destructorname); Wrapper *df = NewWrapper(); Printf(df->def, "/* This function is designed to be called by the zend list destructors */\n"); Printf(df->def, "/* to typecast and do the actual destruction */\n"); Printf(df->def, "static void %s(zend_rsrc_list_entry *rsrc, const char *type_name TSRMLS_DC) {\n", destructorname); Wrapper_add_localv(df, "value", "swig_object_wrapper *value=(swig_object_wrapper *) rsrc->ptr", NIL); Wrapper_add_localv(df, "ptr", "void *ptr=value->ptr", NIL); Wrapper_add_localv(df, "newobject", "int newobject=value->newobject", NIL); emit_args(d, l, df); emit_attach_parmmaps(l, df); // Get type of first arg, thing to be destructed // Skip ignored arguments Parm *p = l; //while (Getattr(p,"tmap:ignore")) {p = Getattr(p,"tmap:ignore:next");} while (checkAttribute(p, "tmap:in:numinputs", "0")) { p = Getattr(p, "tmap:in:next"); } SwigType *pt = Getattr(p, "type"); Printf(df->code, " efree(value);\n"); Printf(df->code, " if (! newobject) return; /* can't delete it! */\n"); Printf(df->code, " arg1 = (%s)SWIG_ZTS_ConvertResourceData(ptr,type_name,SWIGTYPE%s TSRMLS_CC);\n", SwigType_lstr(pt, 0), SwigType_manglestr(pt)); Printf(df->code, " if (! arg1) zend_error(E_ERROR, \"%s resource already free'd\");\n", Char(name)); emit_action(n, df); Printf(df->code, "}\n"); Wrapper_print(df, s_wrappers); return SWIG_OK; } /* ------------------------------------------------------------ * memberconstantHandler() * ------------------------------------------------------------ */ virtual int memberconstantHandler(Node *n) { wrapping_member_constant = Getattr(n, "name"); Language::memberconstantHandler(n); wrapping_member_constant = NULL; return SWIG_OK; } }; /* class PHP */ /* ----------------------------------------------------------------------------- * swig_php() - Instantiate module * ----------------------------------------------------------------------------- */ static PHP *maininstance = 0; // We use this function to be able to write out zend_register_list_destructor_ex // lines for most things in the type table // NOTE: it's a function NOT A PHP::METHOD extern "C" void typetrace(SwigType *ty, String *mangled, String *clientdata) { Node *class_node; if (!zend_types) { zend_types = NewHash(); } // we want to know if the type which reduced to this has a constructor if ((class_node = maininstance->classLookup(ty))) { if (!Getattr(zend_types, mangled)) { // OK it may have been set before by a different SwigType but it would // have had the same underlying class node I think // - it is certainly required not to have different originating class // nodes for the same SwigType Setattr(zend_types, mangled, class_node); } } else { // a non-class pointer Setattr(zend_types, mangled, NOTCLASS); } if (r_prevtracefunc) (*r_prevtracefunc) (ty, mangled, (String *) clientdata); } static Language *new_swig_php(int php_version) { maininstance = new PHP(php_version); if (!r_prevtracefunc) { r_prevtracefunc = SwigType_remember_trace(typetrace); } else { Printf(stderr, "php Typetrace vector already saved!\n"); assert(0); } return maininstance; } extern "C" Language *swig_php4(void) { return new_swig_php(4); } extern "C" Language *swig_php5(void) { return new_swig_php(5); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" pJointPointInPlane::pJointPointInPlane(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_PointInPlane) { } void pJointPointInPlane::setGlobalAnchor(VxVector anchor) { NxPointInPlaneJointDesc descr; NxPointInPlaneJoint*joint = static_cast<NxPointInPlaneJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.setGlobalAnchor(getFrom(anchor)); joint->loadFromDesc(descr); } void pJointPointInPlane::setGlobalAxis(VxVector axis) { NxPointInPlaneJointDesc descr; NxPointInPlaneJoint*joint = static_cast<NxPointInPlaneJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.setGlobalAxis(getFrom(axis)); joint->loadFromDesc(descr); } void pJointPointInPlane::enableCollision(int collision) { NxPointInPlaneJointDesc descr; NxPointInPlaneJoint*joint = static_cast<NxPointInPlaneJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (collision) { descr.jointFlags |= NX_JF_COLLISION_ENABLED; }else descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; joint->loadFromDesc(descr); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" //#include "pVehicle.h" PhysicManager *ourMan = NULL; void __newpClothDescr(BYTE *iAdd) { new(iAdd)pClothDesc(); } void PhysicManager::_RegisterVSLCloth() { ourMan = GetPMan(); STARTVSLBIND(m_Context) DECLAREOBJECTTYPE(pClothDesc) DECLAREMEMBER(pClothDesc,float,thickness) DECLAREMEMBER(pClothDesc,float,density) DECLAREMEMBER(pClothDesc,float,bendingStiffness) DECLAREMEMBER(pClothDesc,float,stretchingStiffness) DECLAREMEMBER(pClothDesc,float,dampingCoefficient) DECLAREMEMBER(pClothDesc,float,friction) DECLAREMEMBER(pClothDesc,float,pressure) DECLAREMEMBER(pClothDesc,float,tearFactor) DECLAREMEMBER(pClothDesc,float,collisionResponseCoefficient) DECLAREMEMBER(pClothDesc,float,attachmentResponseCoefficient) DECLAREMEMBER(pClothDesc,float,attachmentTearFactor) DECLAREMEMBER(pClothDesc,float,toFluidResponseCoefficient) DECLAREMEMBER(pClothDesc,float,fromFluidResponseCoefficient) DECLAREMEMBER(pClothDesc,float,minAdhereVelocity) DECLAREMEMBER(pClothDesc,int,solverIterations) DECLAREMEMBER(pClothDesc,VxVector,externalAcceleration) DECLAREMEMBER(pClothDesc,VxVector,windAcceleration) DECLAREMEMBER(pClothDesc,float,wakeUpCounter) DECLAREMEMBER(pClothDesc,float,sleepLinearVelocity) DECLAREMEMBER(pClothDesc,int,collisionGroup) DECLAREMEMBER(pClothDesc,VxBbox,validBounds) DECLAREMEMBER(pClothDesc,float,relativeGridSpacing) DECLAREMEMBER(pClothDesc,pClothFlag,flags) DECLAREMEMBER(pClothDesc,pClothAttachmentFlag,attachmentFlags) DECLAREMEMBER(pClothDesc,VxColor,tearVertexColor) DECLAREMEMBER(pClothDesc,CK_ID,worldReference) DECLAREMETHOD_0(pClothDesc,void,setToDefault) DECLARECTOR_0(__newpClothDescr) DECLAREPOINTERTYPE(pWorld) DECLAREPOINTERTYPE(pRigidBody) DECLAREPOINTERTYPEALIAS(pRigidBody,"pBody") ////////////////////////////////////////////////////////////////////////// // // Serializer : // DECLAREPOINTERTYPE(pSerializer) DECLAREFUN_C_0(pSerializer*, GetSerializer) DECLAREMETHOD_2(pSerializer,void,overrideBody,pRigidBody*,int) DECLAREMETHOD_2(pSerializer,int,loadCollection,const char*,int) DECLAREMETHOD_1(pSerializer,int,saveCollection,const char*) DECLAREMETHOD_2(pSerializer,void,parseFile,const char*,int) ////////////////////////////////////////////////////////////////////////// // // Joints : // DECLAREPOINTERTYPE(pJoint) DECLAREPOINTERTYPE(pJointFixed) DECLAREPOINTERTYPE(pJointDistance) DECLAREPOINTERTYPE(pJointD6) DECLAREPOINTERTYPE(pJointPulley) DECLAREPOINTERTYPE(pJointBall) DECLAREPOINTERTYPE(pJointRevolute) DECLAREPOINTERTYPE(pJointPrismatic) DECLAREPOINTERTYPE(pJointCylindrical) DECLAREPOINTERTYPE(pJointPointInPlane) DECLAREPOINTERTYPE(pJointPointOnLine) DECLAREINHERITANCESIMPLE("pJoint","pJointDistance") DECLAREINHERITANCESIMPLE("pJoint","pJointD6") DECLAREINHERITANCESIMPLE("pJoint","pJointFixed") DECLAREINHERITANCESIMPLE("pJoint","pJointPulley") DECLAREINHERITANCESIMPLE("pJoint","pJointBall") DECLAREINHERITANCESIMPLE("pJoint","pJointRevolute") DECLAREINHERITANCESIMPLE("pJoint","pJointPrismatic") DECLAREINHERITANCESIMPLE("pJoint","pJointCylindrical") DECLAREINHERITANCESIMPLE("pJoint","pJointPointOnLine") DECLAREINHERITANCESIMPLE("pJoint","pJointPointInPlane") ////////////////////////////////////////////////////////////////////////// // // Factory // DECLAREPOINTERTYPE(pFactory) DECLAREFUN_C_0(pFactory,getPFactory) ////////////////////////////////////////////////////////////////////////// // // ENUMERATION // DECLAREENUM("D6DriveType") DECLAREENUMVALUE("D6DriveType", "D6DT_Position" ,1 ) DECLAREENUMVALUE("D6DriveType", "D6DT_Velocity" ,2 ) DECLAREENUM("PForceMode") DECLAREENUMVALUE("PForceMode", "PFM_Force" , 0) DECLAREENUMVALUE("PForceMode", "PFM_Impulse" , 1) DECLAREENUMVALUE("PForceMode", "PFM_VelocityChange" , 2) DECLAREENUMVALUE("PForceMode", "PFM_SmoothImpulse" , 3) DECLAREENUMVALUE("PForceMode", "PFM_SmoothVelocityChange" , 4) DECLAREENUMVALUE("PForceMode", "PFM_Acceleration" , 5) DECLAREENUM("D6MotionMode") DECLAREENUMVALUE("D6MotionMode", "D6MM_Locked" , 0) DECLAREENUMVALUE("D6MotionMode", "D6MM_Limited" , 1) DECLAREENUMVALUE("D6MotionMode", "D6MM_Free" , 2) DECLAREENUM("JType") DECLAREENUMVALUE("JType", "JT_Any" , -1) DECLAREENUMVALUE("JType", "JT_Prismatic" , 0) DECLAREENUMVALUE("JType", "JT_Revolute" , 1) DECLAREENUMVALUE("JType", "JT_Cylindrical" , 2) DECLAREENUMVALUE("JType", "JT_Spherical" , 3) DECLAREENUMVALUE("JType", "JT_PointOnLine" , 4) DECLAREENUMVALUE("JType", "JT_PointInPlane" , 5) DECLAREENUMVALUE("JType", "JT_Distance" , 6) DECLAREENUMVALUE("JType", "JT_Pulley" , 7) DECLAREENUMVALUE("JType", "JT_Fixed" ,8 ) DECLAREENUMVALUE("JType", "JT_D6" ,9 ) ////////////////////////////////////////////////////////////////////////// // // Bindings for pVehicle related classes : // // DECLAREMETHOD_2(pFactory,pVehicle*,createVehicle,CK3dEntity*,pVehicleDesc) //DECLAREMETHOD_0(pVehicle,float,getWheelRollAngle) //DECLAREMETHOD_0(pVehicle,float,getRpm) ////////////////////////////////////////////////////////////////////////// // // JOINT CREATION // DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointDistance*,createDistanceJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,VxVector(),VxVector,VxVector(),float,0.0f,float,0.0f,pSpring,pSpring()) DECLAREMETHOD_5(pFactory,pJointD6*,createD6Joint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,bool) DECLAREMETHOD_2(pFactory,pJointFixed*,createFixedJoint,CK3dEntity*,CK3dEntity*) DECLAREMETHOD_3_WITH_DEF_VALS(pFactory,pRigidBody*,createBody,CK3dEntity*,NODEFAULT,pObjectDescr,NODEFAULT,CK3dEntity*,NULL) DECLAREMETHOD_6(pFactory,pJointPulley*,createPulleyJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointBall*,createBallJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointRevolute*,createRevoluteJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointPrismatic*,createPrismaticJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointCylindrical*,createCylindricalJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointPointInPlane*,createPointInPlaneJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_4(pFactory,pJointPointOnLine*,createPointOnLineJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) DECLAREMETHOD_2(pFactory,pCloth*,createCloth,CK3dEntity*,pClothDesc) ////////////////////////////////////////////////////////////////////////// // // Cloth // DECLAREMETHOD_4(pCloth,void,attachToCore,CK3dEntity*,float,float,float) DECLAREMETHOD_2(pCloth,void,attachToShape,CK3dEntity*,pClothAttachmentFlag) ////////////////////////////////////////////////////////////////////////// // // MANAGER // DECLAREFUN_C_0(CKGUID, GetPhysicManagerGUID) DECLAREOBJECTTYPE(PhysicManager) DECLARESTATIC_1(PhysicManager,PhysicManager*,Cast,CKBaseManager* iM) DECLAREFUN_C_0(PhysicManager*, GetPhysicManager) DECLAREMETHOD_0(PhysicManager,pWorld*,getDefaultWorld) DECLAREMETHOD_1(PhysicManager,pRigidBody*,getBody,CK3dEntity*) DECLAREMETHOD_1(PhysicManager,pWorld*,getWorldByBody,CK3dEntity*) DECLAREMETHOD_1(PhysicManager,pWorld*,getWorld,CK_ID) DECLAREMETHOD_3_WITH_DEF_VALS(PhysicManager,pJoint*,getJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NULL,JType,JT_Any) // DECLAREMETHOD_0(PhysicManager,void,makeDongleTest) ////////////////////////////////////////////////////////////////////////// // // World // DECLAREMETHOD_1(pWorld,pRigidBody*,getBody,CK3dEntity*) DECLAREMETHOD_1(pWorld,pVehicle*,getVehicle,CK3dEntity*) DECLAREMETHOD_3(pWorld,pJoint*,getJoint,CK3dEntity*,CK3dEntity*,JType) DECLAREMETHOD_3(pWorld,void,setFilterOps,pFilterOp,pFilterOp,pFilterOp) DECLAREMETHOD_1(pWorld,void,setFilterBool,bool) DECLAREMETHOD_1(pWorld,void,setFilterConstant0,const pGroupsMask&) DECLAREMETHOD_1(pWorld,void,setFilterConstant1,const pGroupsMask&) // DECLAREMETHOD_5_WITH_DEF_VALS(pWorld,bool,raycastAnyBounds,const VxRay&,NODEFAULT,pShapesType,NODEFAULT,pGroupsMask,NODEFAULT,int,0xffffffff,float,NX_MAX_F32) DECLAREMETHOD_8(pWorld,bool,overlapSphereShapes,CK3dEntity*,const VxSphere&,CK3dEntity*,pShapesType,CKGroup*,int,const pGroupsMask*,BOOL) //(const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,unsigned int groups=0xffffffff, float maxDist=NX_MAX_F32); ////////////////////////////////////////////////////////////////////////// // // JOINT :: Revolute // DECLAREMETHOD_0(pJoint,pJointRevolute*,castRevolute) DECLAREMETHOD_1(pJointRevolute,void,setGlobalAnchor,const VxVector&) DECLAREMETHOD_1(pJointRevolute,void,setGlobalAxis,const VxVector&) DECLAREMETHOD_1(pJointRevolute,void,setSpring,pSpring) DECLAREMETHOD_1(pJointRevolute,void,setHighLimit,pJointLimit) DECLAREMETHOD_1(pJointRevolute,void,setLowLimit,pJointLimit) DECLAREMETHOD_1(pJointRevolute,void,setMotor,pMotor) DECLAREMETHOD_0(pJointRevolute,pSpring,getSpring) DECLAREMETHOD_0(pJointRevolute,pJointLimit,getLowLimit) DECLAREMETHOD_0(pJointRevolute,pJointLimit,getHighLimit) DECLAREMETHOD_0(pJointRevolute,pMotor,getMotor) DECLAREMETHOD_1(pJointRevolute,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT :: Ball // DECLAREMETHOD_0(pJoint,pJointBall*,castBall) DECLAREMETHOD_1(pJointBall,void,setAnchor,VxVector) DECLAREMETHOD_1(pJointBall,void,setSwingLimitAxis,VxVector) DECLAREMETHOD_1(pJointBall,bool,setSwingLimit,pJointLimit) DECLAREMETHOD_1(pJointBall,bool,setTwistHighLimit,pJointLimit) DECLAREMETHOD_1(pJointBall,bool,setTwistLowLimit,pJointLimit) DECLAREMETHOD_0(pJointBall,pJointLimit,getSwingLimit) DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistHighLimit) DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistLowLimit) DECLAREMETHOD_1(pJointBall,bool,setSwingSpring,pSpring) DECLAREMETHOD_1(pJointBall,bool,setTwistSpring,pSpring) DECLAREMETHOD_1(pJointBall,void,setJointSpring,pSpring) DECLAREMETHOD_0(pJointBall,pSpring,getSwingSpring) DECLAREMETHOD_0(pJointBall,pSpring,getTwistSpring) DECLAREMETHOD_0(pJointBall,pSpring,getJointSpring) DECLAREMETHOD_1(pJointBall,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT Prismatic // // DECLAREMETHOD_0(pJoint,pJointPrismatic*,castPrismatic) DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointPrismatic,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT Cylindrical // // DECLAREMETHOD_0(pJoint,pJointCylindrical*,castCylindrical) DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointCylindrical,void,enableCollision,int) ////////////////////////////////////////////////////////////////////////// // // JOINT Point In Plane // // DECLAREMETHOD_0(pJoint,pJointPointInPlane*,castPointInPlane) DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointPointInPlane,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT Point In Plane // // DECLAREMETHOD_0(pJoint,pJointPointOnLine*,castPointOnLine) DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAnchor,VxVector) DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAxis,VxVector) DECLAREMETHOD_1(pJointPointOnLine,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT BASE // // DECLAREMETHOD_1(pJoint,void,setLocalAnchor0,VxVector) DECLAREMETHOD_2(pJoint,void,setBreakForces,float,float) DECLAREMETHOD_2(pJoint,void,getBreakForces,float&,float&) DECLAREMETHOD_3(pJoint,int,addLimitPlane,VxVector,VxVector,float) DECLAREMETHOD_2_WITH_DEF_VALS(pJoint,void,setLimitPoint,VxVector,NODEFAULT,bool,true) DECLAREMETHOD_0(pJoint,void,purgeLimitPlanes) DECLAREMETHOD_0(pJoint,void,resetLimitPlaneIterator) DECLAREMETHOD_0(pJoint,int,hasMoreLimitPlanes) DECLAREMETHOD_3(pJoint,int,getNextLimitPlane,VxVector&,float&,float&) DECLAREMETHOD_0(pJoint,int,getType) ////////////////////////////////////////////////////////////////////////// // // JOINT :: DISTANCE // DECLAREMETHOD_0(pJoint,pJointDistance*,castDistanceJoint) DECLAREMETHOD_1(pJointDistance,void,setMinDistance,float) DECLAREMETHOD_1(pJointDistance,void,setMaxDistance,float) DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor0,VxVector) DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor1,VxVector) DECLAREMETHOD_1(pJointDistance,void,setSpring,pSpring) DECLAREMETHOD_0(pJointDistance,float,getMinDistance) DECLAREMETHOD_0(pJointDistance,float,getMaxDistance) DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor0) DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor1) DECLAREMETHOD_0(pJointDistance,pSpring,getSpring) DECLAREMETHOD_1(pJointDistance,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // JOINT PULLEY // DECLAREMETHOD_0(pJoint,pJointPulley*,castPulley) DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorA,VxVector) DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorB,VxVector) DECLAREMETHOD_1(pJointPulley,void,setPulleyA,VxVector) DECLAREMETHOD_1(pJointPulley,void,setPulleyB,VxVector) DECLAREMETHOD_1(pJointPulley,void,setStiffness,float) DECLAREMETHOD_1(pJointPulley,void,setRatio,float) DECLAREMETHOD_1(pJointPulley,void,setRigid,int) DECLAREMETHOD_1(pJointPulley,void,setDistance,float) DECLAREMETHOD_1(pJointPulley,void,setMotor,pMotor) DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorA) DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorB) DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyA) DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyB) DECLAREMETHOD_0(pJointPulley,float,getStiffness) DECLAREMETHOD_0(pJointPulley,float,getRatio) DECLAREMETHOD_0(pJointPulley,float,getDistance) DECLAREMETHOD_1(pJointPulley,void,enableCollision,bool) DECLAREMETHOD_0(pJointPulley,pMotor,getMotor) ////////////////////////////////////////////////////////////////////////// // // JOINT D6 // DECLAREMETHOD_0(pJoint,pJointD6*,castD6Joint) DECLAREMETHOD_1(pJointD6,void,setTwistMotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setSwing1MotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setSwing2MotionMode,D6MotionMode) DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) DECLAREMETHOD_1(pJointD6,void,setXMotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setYMotionMode,D6MotionMode) DECLAREMETHOD_1(pJointD6,void,setZMotionMode,D6MotionMode) DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) ////////////////////////////////////////////////////////////////////////// //softwLimits DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getLinearLimit) DECLAREMETHOD_1(pJointD6,int,setLinearLimit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing1Limit) DECLAREMETHOD_1(pJointD6,int,setSwing1Limit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing2Limit) DECLAREMETHOD_1(pJointD6,int,setSwing2Limit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistHighLimit) DECLAREMETHOD_1(pJointD6,int,setTwistHighLimit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistLowLimit) DECLAREMETHOD_1(pJointD6,int,setTwistLowLimit,pJD6SoftLimit) DECLAREMETHOD_0(pJointD6,pJD6Drive,getXDrive) DECLAREMETHOD_1(pJointD6,int,setXDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getYDrive) DECLAREMETHOD_1(pJointD6,int,setYDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getZDrive) DECLAREMETHOD_1(pJointD6,int,setZDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getSwingDrive) DECLAREMETHOD_1(pJointD6,int,setSwingDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getTwistDrive) DECLAREMETHOD_1(pJointD6,int,setTwistDrive,pJD6Drive) DECLAREMETHOD_0(pJointD6,pJD6Drive,getSlerpDrive) DECLAREMETHOD_1(pJointD6,int,setSlerpDrive,pJD6Drive) DECLAREMETHOD_1(pJointD6,void,setDrivePosition,VxVector) DECLAREMETHOD_1(pJointD6,void,setDriveRotation,VxQuaternion) DECLAREMETHOD_1(pJointD6,void,setDriveLinearVelocity,VxVector) DECLAREMETHOD_1(pJointD6,void,setDriveAngularVelocity,VxVector) DECLAREMETHOD_1(pJointD6,void,enableCollision,bool) ////////////////////////////////////////////////////////////////////////// // // Rigid Body Exports // // /************************************************************************/ /* Forces */ /************************************************************************/ DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addForce,const VxVector&,NODEFAULT, PForceMode, 0,bool,true) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addTorque,const VxVector&,NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalForce,const VxVector&,NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalTorque,const VxVector&,NODEFAULT, PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtPos, const VxVector&,NODEFAULT,const VxVector&,NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtLocalPos,const VxVector,NODEFAULT, const VxVector&, NODEFAULT,PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtPos, const VxVector&, NODEFAULT,const VxVector&,NODEFAULT, PForceMode,0,bool,true) DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtLocalPos, const VxVector&, NODEFAULT,const VxVector&, NODEFAULT,PForceMode,0,bool,true) /************************************************************************/ /* Momentum */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setAngularMomentum,const VxVector&) DECLAREMETHOD_1(pRigidBody,void,setLinearMomentum,const VxVector&) DECLAREMETHOD_0(pRigidBody,VxVector,getAngularMomentum) DECLAREMETHOD_0(pRigidBody,VxVector,getLinearMomentum) /************************************************************************/ /* Pose : */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setPosition,const VxVector&) DECLAREMETHOD_1(pRigidBody,void,setRotation,const VxQuaternion&) DECLAREMETHOD_1(pRigidBody,void,translateLocalShapePosition,VxVector) /************************************************************************/ /* Velocity : */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setLinearVelocity,const VxVector&) DECLAREMETHOD_1(pRigidBody,void,setAngularVelocity,const VxVector&) DECLAREMETHOD_0(pRigidBody,float,getMaxAngularSpeed) DECLAREMETHOD_0(pRigidBody,VxVector,getLinearVelocity) DECLAREMETHOD_0(pRigidBody,VxVector,getAngularVelocity) /************************************************************************/ /* Mass */ /************************************************************************/ DECLAREMETHOD_1(pRigidBody,void,setMassOffset,VxVector) DECLAREMETHOD_1(pRigidBody,void,setMaxAngularSpeed,float) /************************************************************************/ /* Hull */ /************************************************************************/ DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) DECLAREMETHOD_0(pRigidBody,pWorld*,getWorld) DECLAREMETHOD_1(pRigidBody,pJoint*,isConnected,CK3dEntity*) //DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) DECLAREMETHOD_1_WITH_DEF_VALS(pRigidBody,float,getMass,CK3dEntity*,NULL) DECLAREMETHOD_0(pRigidBody,int,getHullType) DECLAREMETHOD_2(pRigidBody,void,setGroupsMask,CK3dEntity*,const pGroupsMask&) DECLAREMETHOD_0(pRigidBody,int,getFlags) DECLAREMETHOD_1(pRigidBody,VxVector,getPointVelocity,VxVector) DECLAREMETHOD_1(pRigidBody,VxVector,getLocalPointVelocity,VxVector) DECLAREMETHOD_1(pRigidBody,void,enableCollision,bool) DECLAREMETHOD_0(pRigidBody,bool,isCollisionEnabled) DECLAREMETHOD_1(pRigidBody,void,setKinematic,int) DECLAREMETHOD_0(pRigidBody,int,isKinematic) DECLAREMETHOD_1(pRigidBody,void,enableGravity,int) DECLAREMETHOD_0(pRigidBody,bool,isAffectedByGravity) DECLAREMETHOD_1(pRigidBody,void,setSleeping,int) DECLAREMETHOD_0(pRigidBody,int,isSleeping) DECLAREMETHOD_1(pRigidBody,void,setLinearDamping,float) DECLAREMETHOD_1(pRigidBody,void,setAngularDamping,float) DECLAREMETHOD_1(pRigidBody,void,lockTransformation,BodyLockFlags) DECLAREMETHOD_1(pRigidBody,int,isBodyFlagOn,int) DECLAREMETHOD_1(pRigidBody,void,setSolverIterationCount,int) DECLAREMETHOD_1(pRigidBody,void,setCollisionsGroup,int) DECLAREMETHOD_0(pRigidBody,int,getCollisionsGroup) DECLAREMETHOD_2(pRigidBody,int,updateMassFromShapes,float,float) DECLAREMETHOD_5_WITH_DEF_VALS(pRigidBody,int,addSubShape,CKMesh*,NULL,pObjectDescr,NODEFAULT,CK3dEntity*,NULL,VxVector,VxVector(),VxQuaternion,VxQuaternion()) DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,int,removeSubShape,CKMesh*,NODEFAULT,float,0.0,float,0.0) /* DECLAREENUM("WORLD_UPDATE_MODE") DECLAREENUMVALUE("WORLD_UPDATE_MODE", "WUM_UPDATE_FROM_ATTRIBUTE" , 0x0001) DECLAREENUM("WORLD_UPDATE_FLAGS") DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_WORLD_SETTINGS" , 0x0001) DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_DAMPING_PARAMETER" , 0x0002) DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_SLEEPING_PARAMETER" , 0x0004) DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_SURFACE_SETTINGS" , 0x0008) DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_ALL_PARAMETERS" , 0x0010) DECLAREENUM("BODY_UPDATE_FLAGS") DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_PHY_PARAMETER" , 0x0001) DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_DAMPING_PARAMETER" , 0x0002) DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_SLEEPING_PARAMETER" , 0x0004) DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_JOINT_PARAMETERS" , 0x0008) DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_ALL_PARAMETERS" , 0x0010) DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_GEOMETRY" , 0x0020) DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_PIVOT" , 0x0040) DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_MASS" , 0x0080) DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_ALL" , 0x0100) DECLAREENUM("JType") DECLAREENUMVALUE("JType", "JT_NONE" , 0) DECLAREENUMVALUE("JType", "JT_BALL" , 1) DECLAREENUMVALUE("JType", "JT_HINGE" , 2) DECLAREENUMVALUE("JType", "JT_SLIDER" , 3) DECLAREENUMVALUE("JType", "JT_CONTACT" , 4) DECLAREENUMVALUE("JType", "JT_UNIVERSAL" , 5) DECLAREENUMVALUE("JType", "JT_HINGE2" , 6) DECLAREENUMVALUE("JType", "JT_FIXED" , 7) DECLAREENUMVALUE("JType", "JT_MOTOR" ,8 ) DECLAREENUM("J_LIMITPARAMETER"); DECLAREENUMVALUE("J_LIMITPARAMETER", "JLoStop" , 0); DECLAREENUMVALUE("J_LIMITPARAMETER", "JHiStop", 1); DECLAREENUMVALUE("J_LIMITPARAMETER", "JVel" , 2); DECLAREENUMVALUE("J_LIMITPARAMETER", "JFMax" , 3); DECLAREENUMVALUE("J_LIMITPARAMETER", "JFudgeFactor" , 4); DECLAREENUMVALUE("J_LIMITPARAMETER", "JBounce" , 5); DECLAREENUMVALUE("J_LIMITPARAMETER", "JCFM" , 6); DECLAREENUMVALUE("J_LIMITPARAMETER", "JStopERP" , 7); DECLAREENUMVALUE("J_LIMITPARAMETER", "JStopCFM" , 8); DECLAREENUMVALUE("J_LIMITPARAMETER", "JSuspensionERP" , 9); DECLAREENUMVALUE("J_LIMITPARAMETER", "JSuspensionCFM" , 10); DECLAREENUMVALUE("J_LIMITPARAMETER", "JERP" , 11); DECLAREENUM("J_MOTOR_AXIS_TYPE") DECLAREENUMVALUE("J_MOTOR_AXIS_TYPE", "AXIS_GLOBAL_FRAME" , 0) DECLAREENUMVALUE("J_MOTOR_AXIS_TYPE", "AXIS_FIRST_BODY" , 1) DECLAREENUMVALUE("J_MOTOR_AXIS_TYPE", "AXIS_SECOND_BODY" , 2) */ /* DECLAREOBJECTTYPE(pSleepingSettings) DECLARECTOR_0(__newvtSleepingSettings) DECLAREMETHODC_0(pSleepingSettings,int,SleepSteps) DECLAREMETHOD_1(pSleepingSettings,void,SleepSteps,int) DECLAREMETHODC_0(pSleepingSettings,float,AngularThresold) DECLAREMETHOD_1(pSleepingSettings,void,AngularThresold,float) DECLAREMETHODC_0(pSleepingSettings,float,LinearThresold) DECLAREMETHOD_1(pSleepingSettings,void,LinearThresold,float) DECLAREMETHODC_0(pSleepingSettings,int,AutoSleepFlag) DECLAREMETHOD_1(pSleepingSettings,void,AutoSleepFlag,int) DECLAREOBJECTTYPE(pWorldSettings) DECLARECTOR_0(__newvtWorldSettings) DECLAREMETHODC_0(pWorldSettings,VxVector,Gravity) DECLAREMETHOD_1(pWorldSettings,void,Gravity,VxVector) DECLAREMETHODC_0(pWorldSettings,float,ContactSurfaceLayer) DECLAREMETHOD_1(pWorldSettings,void,ContactSurfaceLayer,float) DECLAREMETHODC_0(pWorldSettings,float,ERP) DECLAREMETHOD_1(pWorldSettings,void,ERP,float) DECLAREMETHODC_0(pWorldSettings,float,CFM) DECLAREMETHOD_1(pWorldSettings,void,CFM,float) DECLAREMETHODC_0(pWorldSettings,float,MaximumContactCorrectVelocity) DECLAREMETHOD_1(pWorldSettings,void,MaximumContactCorrectVelocity,float) DECLAREOBJECTTYPE(pJointSettings) DECLARECTOR_0(__newvtJointSettings) DECLAREFUN_C_1(int,TestWS,pWorldSettings) DECLAREMETHODC_0(pWorld,pSleepingSettings*,SleepingSettings) DECLAREMETHOD_1(pWorld,void,SleepingSettings,pSleepingSettings*) DECLAREMETHODC_0(pWorld,pWorldSettings*,WorldSettings) DECLAREMETHOD_1(pWorld,void,WorldSettings,pWorldSettings*) DECLAREMETHOD_0(pWorld,int,NumJoints) */ ////////////////////////////////////////////////////////////////////////// //collision /* DECLAREMETHOD_0(pRigidBody,float,GetFriction) DECLAREMETHOD_1(pRigidBody,void,SetFriction,float) DECLAREMETHOD_1(pRigidBody,void,SetPosition,VxVector) DECLAREMETHOD_1(pRigidBody,void,SetQuaternion, VxQuaternion) DECLAREMETHOD_0(pRigidBody,VxBbox,GetAABB) DECLAREMETHOD_0(pRigidBody,float,GetLastHFHeight) DECLAREMETHOD_0(pRigidBody,int,GetLastHFColor) DECLAREMETHOD_0(pRigidBody,Vx2DVector,GetLastHCoord) */ // Velocity : //DECLAREMETHOD_1(pRigidBody,void,setLinearVel,VxVector) //DECLAREMETHOD_1(pRigidBody,void,setAngularVel, VxVector) /* //DECLAREMETHOD_0(pRigidBody,VxVector,GetLinearVel) //DECLAREMETHOD_0(pRigidBody,VxVector,GetAngularVel) // Forces : */ //DECLAREMETHOD_2(pRigidBody,void,addForce, VxVector , PForceMode ) ////////////////////////////////////////////////////////////////////////// //rotation axis : /* DECLAREMETHOD_2(pFactory,pWorldSettings*,CreateWorldSettings,const char *,const char*) DECLAREMETHOD_2_WITH_DEF_VALS(pFactory,pWorldSettings*,CreateWorldSettings,const char *,"Default",const char*,"PhysicDefaults.xml") DECLAREMETHOD_2(pFactory,pSleepingSettings*,CreateSleepingSettings,const char *,const char*) ////////////////////////////////////////////////////////////////////////// //world : DECLAREMETHOD_3(pFactory,pWorld*,CreateWorld,CK3dEntity*,pWorldSettings*,pSleepingSettings*) ////////////////////////////////////////////////////////////////////////// //bodies : DECLAREMETHOD_3(pFactory,pRigidBody*,CreateRigidBody,CK3dEntity*,pWorld*,pSleepingSettings*) DECLAREMETHOD_3(pFactory,pRigidBody*,CreateRigidBody,CK3dEntity*,CK3dEntity*,pSleepingSettings*) DECLAREMETHOD_3_WITH_DEF_VALS(pFactory,pRigidBody*,CreateBall,CK3dEntity*,NULL,CK3dEntity*,NULL,pSleepingSettings*,NULL) DECLAREMETHOD_3(pFactory,pRigidBody*,CreateRigidBodyFull,CK3dEntity*,pWorld*,pSleepingSettings*) DECLAREMETHOD_8_WITH_DEF_VALS(pFactory,pRigidBody*,CreateBody,CK3dEntity*,NULL,CK3dEntity*,NULL,pSleepingSettings*,NULL,int,(BodyFlags)(BF_MOVING|BF_P2V|BF_WORLD_GRAVITY|BF_ENABLED|BF_COLLISION),int,HT_BOX,float,1.0f,float,0.0f,float,1.0f) ////////////////////////////////////////////////////////////////////////// //joint DECLAREMETHOD_2(pRigidBody,pJoint*,IsConnected, CK3dEntity*,int) ////////////////////////////////////////////////////////////////////////// //collision : DECLAREMETHOD_4(pWorld,CK3dEntity*,CIsInCollision,CK3dEntity*,VxVector&,VxVector&,float&) DECLAREMETHOD_5(pWorld,CK3dEntity*,CIsInCollision,CK3dEntity*,CKGroup*,VxVector&,VxVector&,float&) DECLAREMETHOD_5(pWorld,bool,CIsInCollision,CK3dEntity*,CK3dEntity*,VxVector&,VxVector&,float&) DECLAREMETHOD_8(pWorld,CK3dEntity*,CRayCollision,VxVector ,CK3dEntity*,VxVector,CK3dEntity*,float,bool,VxVector&, VxVector&) DECLAREMETHOD_2(pWorld,int,CIsInCollision,CK3dEntity*,CK3dEntity*) // DECLAREMETHOD_7(PhysicManager,int,CTestRayCollision,CKGroup*,VxVector,VxVector,float,VxVector*,VxVector*,CK3dEntity**) */ /* DECLAREMETHODC_0(PhysicManager,pWorldSettings,DefaultWorldSettings) DECLAREMETHOD_1(PhysicManager,void,DefaultWorldSettings,pWorldSettings) DECLAREMETHODC_0(PhysicManager,pSleepingSettings,DefaultSleepingSettings) DECLAREMETHOD_1(PhysicManager,void,DefaultSleepingSettings,pSleepingSettings) DECLAREMETHOD_0(PhysicManager,void,CheckWorlds) DECLARESTATIC_0(pWorld,pWorld*,GetDefault) */ STOPVSLBIND } PhysicManager*GetPhysicManager() { return GetPMan(); } /* void __newvtWorldSettings(BYTE *iAdd) { new (iAdd) pWorldSettings(); } void __newvtSleepingSettings(BYTE *iAdd) { new (iAdd) pSleepingSettings(); } void __newvtJointSettings(BYTE *iAdd) { new (iAdd) pJointSettings(); } int TestWS(pWorldSettings pWS) { VxVector grav = pWS.Gravity(); return 2; } pFactory* GetPFactory(); pFactory* GetPFactory() { return pFactory::Instance(); } extern pRigidBody*getBody(CK3dEntity*ent); */<file_sep>#include "stdafx2.h" #include "vtAgeiaInterfaceCallback.h" #include "vtAgeiaInterfaceKeyboardShortcuts.h" #include "vtAgeiaInterfaceMenu.h" #include "PCommonDialog.h" #include "vtBodyStructs.h" #include "PBodySetup.h" //static plugin interface that allow direct communication with Virtools Dev PluginInterface* s_Plugininterface = NULL; WIN_HANDLE CKActorUIFunc(CKParameter* param,WIN_HANDLE parent,CKRECT *rect); WIN_HANDLE CKDoubleUIFunc (CKParameter *param,WIN_HANDLE ParentWindow,CKRECT *rect); /* AFX_STATIC UINT _afxMsgMouseWheel = (((::GetVersion() & 0x80000000) && LOBYTE(LOWORD(::GetVersion()) == 4)) || (!(::GetVersion() & 0x80000000) && LOBYTE(LOWORD(::GetVersion()) == 3))) ? ::RegisterWindowMessage(MSH_MOUSEWHEEL) : 0; */ //ON_REGISTERED_MESSAGE(_afxMsgMouseWheel, OnRegisteredMouseWheel)*/ //ON_BN_CLICKED(IDC_BFLAGS_DEFORMABLE, OnBnClickedBflagsDeformable) WIN_HANDLE CKActorUIFunc (CKParameter *param,WIN_HANDLE ParentWindow,CKRECT *rect) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); /* // Initialize OLE libraries if (!AfxOleInit()) { //AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } */ // CMultiDocTemplate* pDocTemplate; /* pDocTemplate = new CMultiDocTemplate(IDR_DRAWCLTYPE, RUNTIME_CLASS(CDrawDoc), RUNTIME_CLASS(CSplitFrame), RUNTIME_CLASS(CDrawView)); pDocTemplate->SetContainerInfo(IDR_DRAWCLTYPE_CNTR_IP); AddDocTemplate(pDocTemplate); */ CPBCommonDialog *Dlg = new CPBCommonDialog(param); Dlg->m_Context = param->GetCKContext(); HWND win = (HWND)ParentWindow; //Dlg->HType.SetCurSel(0); CKRECT &rect2= *rect; HWND result = NULL; //CPBParentDialog *Dlg = new CPBParentDialog(param,CWnd::FromHandle(win)); //CPBodyCfg *Dlg = new CPBodyCfg(param); if (param && win && Dlg ) { Dlg->Create( IDD_PBCOMMON, CWnd::FromHandle(win)); result = CreateParameterDialog( win, Dlg, 0, PARAMETER_PICKALL, 0, PARAMETER_NORESIZE); } if (result) { return result; } return NULL; } //main plugin callback for Virtools Dev void PluginCallback(PluginInfo::CALLBACK_REASON reason,PluginInterface* plugininterface) { CKContext* ctx = GetCKContext(0); CKParameterManager *pm = ctx->GetParameterManager(); { //--- Set UI Function of Shader Param CKParameterTypeDesc *param_desc = pm->GetParameterTypeDescription(VTF_PHYSIC_BODY_COMMON_SETTINGS); if( !param_desc ) return; param_desc->UICreatorFunction = CKActorUIFunc; //param_desc->UICreatorFunction = CKDoubleUIFunc; } switch(reason) { case PluginInfo::CR_LOAD: { s_Plugininterface = plugininterface; //InitParameters(reason,plugininterface); /*InitMenu(); UpdateMenu(); RegisterKeyboardShortcutCategory(); RegisterKeyboardShortcuts();*/ }break; case PluginInfo::CR_UNLOAD: { //RemoveMenu(); //UnregisterKeyboardShortcutCategory(); s_Plugininterface = NULL; }break; case PluginInfo::CR_NEWCOMPOSITIONNAME: { // InitMenu(); }break; case PluginInfo::CR_NOTIFICATION: { }break; } } <file_sep>/******************************************************************** created: 2009/05/01 created: 1:5:2009 19:35 filename: x:\ProjectRoot\svn\local\usr\include\xAssertion.h file path: x:\ProjectRoot\svn\local\usr\include file base: xAssertion file ext: h author: <NAME> purpose: *********************************************************************/ #ifndef __X_ASSERTION_H__ #define __X_ASSERTION_H__ #include "xPlatform.h" #include "xLogger.h" #include "xAssertCustomization.h" extern void assert_notify_failure(const char* str); // may also take extern xAssertInfo* getLastAssertInfo(); extern xAssertInfo* assertFailed(); bool TestCustomizations_Asserts(); bool customizeAsserts(); #include "vtPhysXBase.h" #ifdef _DEBUG #include <assert.h> #endif void xCONVENTION_CALLBACK updateAssertHandlerData( E_ASSERTION_FAILURE_SEVERITY _failureSeverity, char *_assertionExpression, char *_assertionFileName, int _assertionSourceLine, char *_assertionPostMessage, void* _postAction, bool _result); void xCONVENTION_CALLBACK tickAssertHandlerData(); //---------------------------------------------------------------- // // Assertion checks customization // typedef void (xCONVENTION_CALLBACK *CAssertionFailedProcedure)( E_ASSERTION_FAILURE_SEVERITY fsFailureSeverity, const char *szAssertionExpression, const char *szAssertionFileName, unsigned int uiAssertionSourceLine ); //typedef void (xCONVENTION_CALLBACK *CPostCallback)(); typedef void (xCONVENTION_CALLBACK *xErrorHandlerFn) ( E_ASSERTION_FAILURE_SEVERITY m_fsFailureSeverity, char *m_szAssertionExpression, char *m_szAssertionFileName, int m_uiAssertionSourceLine, char *szAssertionPostMessage, void* postAction, bool result ); class xAssertionEx { public: static CAssertionFailedProcedure getAssertFailureCustomHandler() { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"invoked"); // xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Null"); return g_fnAssertFailureHandler; } static void CustomizeAssertionChecks(CAssertionFailedProcedure fnAssertionFailureProcedure) { xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"invoked"); // xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Null"); g_fnAssertFailureHandler = fnAssertionFailureProcedure; } //xErrorHandlerFn xCONVENTION_API getErrorHandler(); //---------------------------------------------------------------- // // // static xErrorHandlerFn getErrorHandler() { ///xAssertInfo *testData = getLastAssertInfo(); //xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"invoked"); return g_fnAssertHandler; } static void updateErrorHandler(xErrorHandlerFn fnFailureProcedure) { g_fnAssertHandler = fnFailureProcedure; //xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"invoked"); } //void xCONVENTION_API setErrorHandler(xErrorHandlerFn fnFailureProcedure); static void swapBuffer(xAssertInfo&newData); static xAssertionEx *Instance(); xAssertionEx(); private: static CAssertionFailedProcedure g_fnAssertFailureHandler; static xErrorHandlerFn g_fnAssertHandler; }; #define xAssertRouted(Assertion) if(Assertion){}else assert_notify_failure(#Assertion) #define XASSERT_HANDLER(Assertion) (false || (Assertion) \ || (xAssertionEx::getAssertFailureCustomHandler() \ && (xAssertionEx::getAssertFailureCustomHandler()( \ AFS_ASSERT, #Assertion, __FILE__, __LINE__), true))) #define xCHECK_HANDLER(Assertion) ((bConditionValue = false || (Assertion)\ || (xAssertionEx::getAssertFailureCustomHandler() \ && (xAssertionEx::getAssertFailureCustomHandler()( \ AFS_CHECK, #Assertion, __FILE__, __LINE__), true))) #define _xAssertHandler(Assertion) (false || (Assertion) || \ (xAssertionEx::getErrorHandler() &&\ (xAssertionEx::getErrorHandler()( AFS_ASSERT, #Assertion, __FILE__, __LINE__,"asdasd",NULL,TRUE), true))) /*#define _xAssert(Assertion) (false || (Assertion) || (xAssertionEx::getErrorHandler() \ && (xAssertionEx::getErrorHandler()( \ AFS_ASSERT, #Assertion, __FILE__, __LINE__,"","",FALSE), true))) */ #define xAssert(Assertion) xAssertRouted(XASSERT_HANDLER(Assertion)) #define xVerify(Assertion) xAssert(Assertion) #define xCheck(Assertion) { \ bool bConditionValue; \ assert(xCHECK_HANDLER(Assertion)); \ (void)(bConditionValue || (*(int *)0 = 0)); \ #define xVerify(Assertion) _xAssertHandler(Assertion) /* #define xVerify(Assertion) { \ bool bConditionValue=False; \ xAssert(xVerifyHandlerEx(Assertion)); \ (void)(bConditionValue || (*(int *)0 = 0)); \ } */ /* #define xVerify(Assertion) { \ bool bConditionValue; \ assert(xVerifyHandlerEx(Assertion)); \ (void)(bConditionValue || (*(int *)0 = 0)); \ } //#define xAssert(Assertion) assert(XASSERT_HANDLER(Assertion)) //#define xVerify(Assertion) assert(xVerifyHandlerEx(Assertion)) /* /* //extern xErrorHandlerFn xAssertionEx::g_fnAssertHandler; */ /* #define xASSERT_HANDLER(Condition) (false || (Condition) \ || (xAssertionEx::GetAssertFailureCustomHandler() \ && (xAssertionEx::GetAssertFailureCustomHandler()( \ AFS_ASSERT, #Condition, __FILE__, __LINE__), true))) #define xAssert(Condition) XASSERT(xASSERT_HANDLER(Condition)) */ //#define xVerify(Condition) xAssert(Condition) //#define XASSERT(Condition) assert(xASSERT_HANDLER(Condition)) /* #define xVerifyHandlerEx(Condition,Message,Object,PostAction,Result) (false || (Condition,Message,Object,PostAction,Result) \ || (xAssertionEx::CVerifyChecks2() \ && (xAssertionEx::CVerifyChecks2()( \ AFS_ASSERT, #Condition, __FILE__, __LINE__,Message,Object,PostAction,Result), true))) */ /* #define xVerifyAndCorrect(Condition,Message,Object,PostAction,Result) { \ bool bConditionValue; \ xAssert(xVerifyHandlerEx(Condition,Message,Object,PostAction,Result)); \ (void)(bConditionValue || (*(int *)0 = 0)); \ } */ /* #define xCheck(Condition) { \ bool bConditionValue; \ XASSERT(xCHECK_HANDLER(Condition)); \ (void)(bConditionValue || (*(int *)0 = 0)); \ } */ /* #define xVerifyHandlerEx(Conditio1n,Message,Object,PostAction,Result) (false || (Condition,Message,Object,PostAction,Result) \ || (xAssertionEx::CVerifyChecks2() \ && (xAssertionEx::CVerifyChecks2()( \ AFS_ASSERT, #Condition, __FILE__, __LINE__,Message,Object,PostAction,Result), true))) */ /* #define xVerifyHandler(Condition) (false || (Condition) \ || (xAssertionEx::GetAssertFailureCustomHandler() \ && (xAssertionEx::GetAssertFailureCustomHandler()( \ AFS_ASSERT, #Condition, __FILE__, __LINE__), true))) */ /* #define xVerifyHandler(Condition,Message,Object,PostAction,Result) (false || (Condition,Message,Object,PostAction,Result) \ || (xAssertionEx::CVerifyChecks() \ && (xAssertionEx::CVerifyChecks()(\ AFS_ASSERT, #Condition ,__FILE__, __LINE__,Message,Object,PostAction,Result), true))) */ /* #define xVerifyHandler(Condition,Message,Object,PostAction,Result) (false || (Condition || (xAssertionEx::CVerifyChecks() \ && (xAssertionEx::CVerifyChecks()( AFS_ASSERT, #Condition ,\ __FILE__, __LINE__,Message,Object,PostAction,Result), true))) */ /* #define xCHECK_HANDLER(Condition) ((bConditionValue = false || (Condition)) \ || (xAssertionEx::GetAssertFailureCustomHandler() \ && (xAssertionEx::GetAssertFailureCustomHandler()( \ AFS_CHECK, #Condition, __FILE__, __LINE__), true))) */ /* #define xCHECK_HANDLER_MO(Condition) ((bConditionValue = false || (Condition)) \ || (xAssertionEx::GetAssertFailureCustomHandler() \ && (xAssertionEx::GetAssertFailureCustomHandler()( \ AFS_CHECK, #Condition, __FILE__, __LINE__), true))) */ /* /* #define xCheckMO(Condition) { \ bool bConditionValue; \ XASSERT(xCHECK_HANDLER(Condition)); \ (void)(bConditionValue || (*(int *)0 = 0)); \ } */ //---------------------------------------------------------------- // // Release Code : // //#define xAssert(Condition) ((void)0) //#define xVerify(Condition) ((void)(Condition)) /* #define xVerifyAndCorrect(Condition) { \ bool bConditionValue = true; \ xAssert(xVerifyHandlerEx(Condition)); \ (void)(bConditionValue || (*(int *)0 = 0)); } */ /* #define xVerifyHandlerEx(Condition) (false||(Condition) \ || (xAssertionEx::GetVerifyCustomHandler() \ && (xAssertionEx::GetVerifyCustomHandler()( \ AFS_ASSERT, #Condition, __FILE__, __LINE__), true))) */ /* #define xVerifyHandlerEx(Condition) (false || (Condition)) \ || (xAssertionEx::CVerifyChecks2() \ && (xAssertionEx::CVerifyChecks2()( \ AFS_ASSERT, #Condition, __FILE__, __LINE__), true))) */ //#define xVerifyAndCorrect(Condition,Message,Object,PostAction,Result) xAssert(XASSERT_HANDLER(Condition,Message,Object,PostAction,Result)) //#define xVerify(Condition) xAssert(Condition) /*#define xVerifyAndCorrect(Condition,Message,Object,PostAction,Result)xAssert(Condition)*/ #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #ifdef HAS_FLUIDS #include "pFluidRenderSettings.h" pFluidRenderSettings::pFluidRenderSettings(CKContext* ctx,CK_ID entity,char* name) { m_Context = ctx; m_InteractorsFlags = 0; m_StartSize = 0; m_StartSizeVar = 0; m_EndSize = 0; m_EndSizeVar = 0; m_StartColor.r = 0.6f; m_StartColor.g = 0.6f; m_StartColor.b = 0.8f; m_StartColor.b = 1.0f; m_StartColorVar.r = 0.0f; m_StartColorVar.g = 0.0f; m_StartColorVar.b = 0.0f; m_StartColorVar.a = 0.0f; m_EndColor.r = 0.0f; m_EndColor.g = 0.0f; m_EndColor.b = 0.0f; m_EndColor.a = 0.0f; m_EndColorVar.r = 0.0f; m_EndColorVar.g = 0.0f; m_EndColorVar.b = 0.0f; m_EndColorVar.a = 0.0f; m_InitialTextureFrame = 0; m_InitialTextureFrameVariance = 0; m_SpeedTextureFrame = 0; m_SpeedTextureFrameVariance = 0; m_TextureFrameCount = 0; m_TextureFrameloop = FALSE; m_EvolutionsFlags = 0; m_VariancesFlags = 0; m_InteractorsFlags = 0; m_DeflectorsFlags = 0; m_RenderMode = 3; m_Behavior = NULL; mRenderType = PRT_Point; m_Mesh = 0; m_Entity = entity; CK3dEntity* ent = (CK3dEntity*)m_Context->GetObject(m_Entity); if (ent) m_EntityBbox = ent->GetBoundingBox(TRUE); m_Texture = 0; m_Group = 0; m_MessageType = -1; } void pFluidRenderSettings::setToDefault() { } #endif // HAS_FLUIDS<file_sep>#include <StdAfx.h> #include "pMisc.h" #include "pCommon.h" namespace vtAgeia { int getHullTypeFromShape(NxShape *shape) { int result = - 1; if (!shape) { return result; } int nxType = shape->getType(); switch (nxType) { case NX_SHAPE_PLANE: return HT_Plane; case NX_SHAPE_BOX: return HT_Box; case NX_SHAPE_SPHERE: return HT_Sphere; case NX_SHAPE_CONVEX: return HT_ConvexMesh; case NX_SHAPE_CAPSULE: return HT_Capsule; case NX_SHAPE_MESH: return HT_Mesh; } return -1; } XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide,int parameterSubIndex) { XString result="None"; int pType = pm->ParameterGuidToType(parGuide); CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); if ( enumStruct ) { for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) { if(i == parameterSubIndex) { result = enumStruct->GetEnumDescription(i); } } } return result; } //************************************ // Method: BoxGetZero // FullName: vtAgeia::BoxGetZero // Access: public // Returns: VxVector // Qualifier: // Parameter: vt3DObject ent //************************************ VxVector BoxGetZero(CK3dEntity* ent) { VxVector box_s= VxVector(1,1,1); if (ent) { VxMatrix mat = ent->GetWorldMatrix(); VxVector g; Vx3DMatrixToEulerAngles(mat,&g.x,&g.y,&g.z); SetEulerDirection(ent,VxVector(0,0,0)); CKMesh *mesh = ent->GetCurrentMesh(); if (mesh!=NULL) { box_s = mesh->GetLocalBox().GetSize(); } SetEulerDirection(ent,g); } return box_s; } //************************************ // Method: SetEulerDirection // FullName: vtAgeia::SetEulerDirection // Access: public // Returns: void // Qualifier: // Parameter: CK3dEntity* ent // Parameter: VxVector direction //************************************ void SetEulerDirection(CK3dEntity* ent,VxVector direction) { VxVector dir,up,right; VxMatrix mat; Vx3DMatrixFromEulerAngles(mat,direction.x,direction.y,direction.z); dir=(VxVector)mat[2]; up=(VxVector)mat[1]; right=(VxVector)mat[0]; ent->SetOrientation(&dir,&up,&right,NULL,FALSE); } } <file_sep>vtPlayerConsole.exe -d=1<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPBDestroyDecl(); CKERROR CreatePBDestroyProto(CKBehaviorPrototype **pproto); int PBDestroy(const CKBehaviorContext& behcontext); CKERROR PBDestroyCB(const CKBehaviorContext& behcontext); //************************************ // Method: FillBehaviorPBDestroyDecl // FullName: FillBehaviorPBDestroyDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorPBDestroyDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PBDestroy"); od->SetCategory("Physic/Body"); od->SetDescription("Removes an entity from the physic engine."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x72519cc,0x1f2d16da)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePBDestroyProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePBDestroyProto // FullName: CreatePBDestroyProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePBDestroyProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBDestroy"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In0"); proto->DeclareOutput("Out0"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct( PBDestroyCB ); proto->SetFunction(PBDestroy); *pproto = proto; return CK_OK; } //************************************ // Method: PBDestroy // FullName: PBDestroy // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBDestroy(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *referenceObject = (CK3dEntity *) beh->GetTarget(); if( !referenceObject ) return CKBR_OWNERERROR; pWorld *world=GetPMan()->getWorldByBody(referenceObject); if (world) { pRigidBody*bodyA= world->getBody(referenceObject); if (bodyA) { world->deleteBody(bodyA); } } beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); } return 0; } //************************************ // Method: PBDestroyCB // FullName: PBDestroyCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PBDestroyCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { } break; } return CKBR_OK; } <file_sep> #include "CKAll.h" #include "InitMan.h" #include "VSLManagerSDK.h" InitMan::~InitMan(){} CKERROR InitMan::PreProcess(){ PerformMessages(); return CK_OK; } CKERROR InitMan::PostClearAll(){ return CK_OK; } ////////////////////////////////////////////////////////////////////////// CKERROR InitMan::OnCKEnd(){ return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CKERROR InitMan::OnCKReset(){ return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CKERROR InitMan::OnCKPlay() { return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CKERROR InitMan::OnCKInit(){ m_Context->ActivateManager((CKBaseManager*) this,true); return CK_OK; } #include "InitMan.h" #include "ResourceTools.h" bool InitMan::AddFileEntry(XString ArchiveName,XString FileEntry){ if (strlen(FileEntry.Str()) == 0)return FALSE; ZiJoIt it = zili.find(ArchiveName); if ( it == zili.end()) it = zili.insert(zili.end(),std::make_pair(ArchiveName,new XFileList())); it->second->push_back(FileEntry); return TRUE; } int InitMan::GetUnzipDllVersion(){ return m_GetUnzipDllVersion(); } int InitMan::GetZipDllVersion(){ return m_GetZipDllVersion(); } BOOL __stdcall DefaultZipCallback(CZipCallbackData *pData){ return FALSE; } void InitMan::SetDefaultZipValues(CZipParams * pParams){ pParams->m_hwndHandle = NULL; pParams->m_pCaller = NULL; pParams->m_liVersion = GetZipDllVersion(); pParams->m_pfCallbackFunction = DefaultZipCallback; pParams->m_bTraceEnabled = FALSE; pParams->m_pszZipPassword = NULL; pParams->m_bSuffix = FALSE; pParams->m_bEncrypt = FALSE; pParams->m_bSystem = FALSE; pParams->m_bVolume = FALSE; pParams->m_bExtra = FALSE; pParams->m_bNoDirEntries = FALSE; pParams->m_bDate = FALSE; pParams->m_bVerboseEnabled = FALSE; pParams->m_bQuiet = FALSE; pParams->m_bLevel = 9; pParams->m_bComprSpecial = FALSE; pParams->m_bCRLF_LF = FALSE; pParams->m_bJunkDir = FALSE; pParams->m_bRecurse = FALSE; pParams->m_bGrow = TRUE; pParams->m_bForce = FALSE; pParams->m_bMove = FALSE; pParams->m_bDeleteEntries = FALSE; pParams->m_bUpdate = FALSE; pParams->m_bFreshen = FALSE; pParams->m_bJunkSFX = FALSE; pParams->m_bLatestTime = FALSE; for (int j=0; j<8; j++) pParams->m_cDate[j] = 0; pParams->m_liFileCount = 0; pParams->m_pszArchiveFileName = NULL; pParams->m_liSeven = 7; } void InitMan::SetDefaultUnZipValues(CUnzipParams * pParams) { pParams->m_wndHandle = NULL; pParams->m_pCaller = NULL; pParams->m_liVersion = GetUnzipDllVersion(); pParams->m_pfCallbackFunction = DefaultZipCallback; pParams->m_bTraceEnabled = FALSE; pParams->m_bPromptToOverwrite = FALSE; pParams->m_pszZipPassword = NULL; pParams->m_bTest = FALSE; pParams->m_bComments = FALSE; pParams->m_bConvert = FALSE; pParams->m_bQuiet = FALSE; pParams->m_bVerboseEnabled = FALSE; pParams->m_bUpdate = FALSE; pParams->m_bFreshen = FALSE; pParams->m_bDirectories = TRUE; pParams->m_bOverwrite = TRUE; pParams->m_liFileCount = 0; pParams->m_pszArchiveFileName = NULL; pParams->m_liSeven = 7; } BOOL InitMan::UnLoadZipDll(){ FreeLibrary(m_ZipDllHandle); m_ZipDllHandle = 0; m_ZipDllExec = 0; m_GetZipDllVersion = 0; if(DeleteFile(ZipDllTempFile))return TRUE; return FALSE; } BOOL InitMan::UnLoadUnZipDll(){ FreeLibrary(m_UnzipDllHandle); m_ZipDllHandle = 0; m_ZipDllExec = 0; m_GetZipDllVersion = 0; if(DeleteFile(UnZipDllTempFile))return TRUE; return FALSE; } BOOL InitMan::LoadZipDll(){ /* HMODULE mod =GetParentModule(CKPLUGIN_MANAGER_DLL,INIT_MAN_GUID); if (mod) m_ZipDllHandle = GetModulefromResource(mod,ZIP_DLL,ZipDllTempFile); */ m_ZipDllHandle = LoadLibrary("ZIP.DLL"); if (!m_ZipDllHandle)return FALSE; m_GetZipDllVersion = (CGetZipDllVersion)GetProcAddress(m_ZipDllHandle, "GetZipDllVersion"); if (!m_GetZipDllVersion)return FALSE; m_ZipDllExec = (CZipDllExec)GetProcAddress(m_ZipDllHandle, "ZipDllExec"); if (!m_ZipDllExec)return FALSE; return TRUE; } BOOL InitMan::LoadUnzipDll(){ /* HMODULE mod =GetParentModule(CKPLUGIN_MANAGER_DLL,INIT_MAN_GUID); if (mod)m_UnzipDllHandle = GetModulefromResource(mod,UNZIP_DLL,UnZipDllTempFile);*/ m_UnzipDllHandle = LoadLibrary("UNZIP.DLL"); if (!m_UnzipDllHandle)return FALSE; m_GetUnzipDllVersion = (CGetUnzipDllVersion)GetProcAddress(m_UnzipDllHandle, "GetUnzDllVersion"); if (!m_GetUnzipDllVersion)return FALSE; m_UnzipDllExec = (CUnzipDllExec)GetProcAddress(m_UnzipDllHandle, "UnzDllExec"); if (!m_UnzipDllExec)return FALSE; return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <file_sep>/******************************************************************** created: 2009/04/13 created: 13:4:2009 22:08 filename: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Include\Core\Common\MemoryFileMappingPrerequisites.h file path: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Include\Core\Common file base: MemoryFileMappingPrerequisites file ext: h author: <NAME> purpose: Forward decalarations for memory file mappings *********************************************************************/ #ifndef __MEMORY_FILE_MAPPING_PREREQUISITES_H__ #define __MEMORY_FILE_MAPPING_PREREQUISITES_H__ struct vtExternalEvent; struct TSharedMemory; struct haptekMsg; #endif<file_sep>#pragma once #ifndef __GLOBAL_ARTP__ #define __GLOBAL_ARTP__ #endif<file_sep>/////////////////////////////////////////////////////////// // dSleepingSettings.h // Implementation of the Class dSleepingSettings // Created on: 18-Jan-2008 17:15:31 /////////////////////////////////////////////////////////// #if !defined(EA_7D481C15_2B93_4925_B66E_6FAF4DED2A2A__INCLUDED_) #define EA_7D481C15_2B93_4925_B66E_6FAF4DED2A2A__INCLUDED_ namespace vtAgeia { class pSleepingSettings { public: pSleepingSettings() { m_AngularThresold = 0.1f; m_LinearThresold = 0.1f; m_SleepSteps = 0 ; m_AutoSleepFlag = 1; m_SleepTime = 0.0f; } virtual ~pSleepingSettings(){} int SleepSteps() const { return m_SleepSteps; } void SleepSteps(int val) { m_SleepSteps = val; } float AngularThresold() const { return m_AngularThresold; } void AngularThresold(float val) { m_AngularThresold = val; } int AutoSleepFlag() const { return m_AutoSleepFlag; } void AutoSleepFlag(int val) { m_AutoSleepFlag = val; } float LinearThresold() const { return m_LinearThresold; } void LinearThresold(float val) { m_LinearThresold = val; } float m_AngularThresold; int m_AutoSleepFlag; float m_LinearThresold; int m_SleepSteps; float m_SleepTime; }; } #endif // !defined(EA_7D481C15_2B93_4925_B66E_6FAF4DED2A2A__INCLUDED_) <file_sep>#pragma once // PBDodyTab class PBDodyTab : public CTabCtrl { DECLARE_DYNAMIC(PBDodyTab) public: PBDodyTab(); virtual ~PBDodyTab(); virtual void OnFinalRelease(); protected: DECLARE_MESSAGE_MAP() DECLARE_DISPATCH_MAP() DECLARE_INTERFACE_MAP() }; <file_sep>#define NOMINMAX #if defined(WIN32) #include <windows.h> #include <GL/gl.h> #include <GL/glut.h> #elif defined(__APPLE__) #include <OpenGL/gl.h> #include <GLUT/glut.h> #endif #include <stdio.h> #include "OrthographicDrawing.h" // Physics code #undef random #include "NxPhysics.h" #include "NxVehicle.h" enum CreationModes { MODE_NONE, MODE_CAR, MODE_TRUCK }; extern NxPhysicsSDK* gPhysicsSDK; extern NxScene* gScene; extern NxSpringDesc wheelSpring; extern bool keyDown[256]; extern NxUserContactReport * carContactReport; //void initCar(); //void createCar(const NxVec3& pos); void createCarWithDesc(const NxVec3& pos, bool frontWheelDrive, bool backWheelDrive, bool corvetteMotor, bool monsterTruck, bool oldStyle, NxPhysicsSDK* physicsSDK); void createCart(const NxVec3& pos, bool frontWheelDrive, bool backWheelDrive, bool oldStyle); NxVehicleDesc* createTruckPullerDesc(const NxVec3& pos, NxU32 nbGears, bool oldStyle); NxVehicleDesc* createTruckTrailer1(const NxVec3& pos, NxReal length, bool oldStyle); NxVehicleDesc* createFullTruckDesc(const NxVec3& pos, NxReal length, NxU32 nbGears, bool has4Axes, bool oldStyle); NxVehicleDesc* createTwoAxisTrailer(const NxVec3& pos, NxReal length, bool oldStyle); NxVehicle* createTruckPuller(const NxVec3& pos, NxU32 nbGears, bool oldStyle); NxVehicle* createFullTruck(const NxVec3& pos, NxU32 nbGears, bool has4Axes, bool oldStyle); NxVehicle* createTruckWithTrailer1(const NxVec3& pos, NxU32 nbGears, bool oldStyle); NxVehicle* createFullTruckWithTrailer2(const NxVec3& pos, NxU32 nbGears, bool oldStyle); //void tickCar(); void InitTerrain(); void RenderTerrain(); void RenderAllActors(); void renderHUD(OrthographicDrawing& orthoDraw); <file_sep># MAKEFILE for linux GCC # # <NAME> # Modified by <NAME> # # NOTE: This should later be replaced by autoconf/automake scripts, but for # the time being this is actually pretty clean. The only ugly part is # handling CFLAGS so that the x86 specific optimizations don't break # a build. This is easy to remedy though, for those that have problems. # The version VERSION=0.92 #ch1-01-1 # Compiler and Linker Names #CC=gcc #LD=ld # Archiver [makes .a files] #AR=ar #ARFLAGS=r #ch1-01-1 # optimize for SIZE #CFLAGS += -Os #ch1-01-3 # Compilation flags. Note the += does not write over the user's CFLAGS! CFLAGS += -c -I./ -Wall -Wsign-compare -W -Wshadow -Wno-unused-parameter -DLTC_SOURCE # optimize for SPEED CFLAGS += -O3 -funroll-loops #add -fomit-frame-pointer. v3.2 is buggy for certain platforms! CFLAGS += -fomit-frame-pointer # optimize for SIZE CFLAGS += -Os # compile for DEBUGING #CFLAGS += -g3 #ch1-01-3 #These flags control how the library gets built. #Output filenames for various targets. LIBNAME=libtomcrypt.a TEST=test HASH=hashsum CRYPT=encrypt SMALL=small PROF=x86_prof TV=tv_gen #LIBPATH-The directory for libtomcrypt to be installed to. #INCPATH-The directory to install the header files for libtomcrypt. #DATAPATH-The directory to install the pdf docs. DESTDIR= LIBPATH=/usr/lib INCPATH=/usr/include DATAPATH=/usr/share/doc/libtomcrypt/pdf #List of objects to compile. #Leave MPI built-in or force developer to link against libtommath? MPIOBJECT=mpi.o OBJECTS=keyring.o gf.o mem.o sprng.o ecc.o base64.o dh.o rsa.o \ bits.o yarrow.o cfb.o ofb.o ecb.o ctr.o cbc.o hash.o tiger.o sha1.o \ md5.o md4.o md2.o sha256.o sha512.o xtea.o aes.o des.o \ safer_tab.o safer.o safer+.o rc4.o rc2.o rc6.o rc5.o cast5.o noekeon.o blowfish.o crypt.o \ prime.o twofish.o packet.o hmac.o strings.o rmd128.o rmd160.o skipjack.o omac.o dsa.o $(MPIOBJECT) TESTOBJECTS=demos/test.o HASHOBJECTS=demos/hashsum.o CRYPTOBJECTS=demos/encrypt.o SMALLOBJECTS=demos/small.o PROFS=demos/x86_prof.o TVS=demos/tv_gen.o #Files left over from making the crypt.pdf. LEFTOVERS=*.dvi *.log *.aux *.toc *.idx *.ilg *.ind #Compressed filenames COMPRESSED=crypt.tar.bz2 crypt.zip crypt.tar.gz #Header files used by libtomcrypt. HEADERS=tommath.h mycrypt_cfg.h mycrypt_gf.h mycrypt_kr.h \ mycrypt_misc.h mycrypt_prng.h mycrypt_cipher.h mycrypt_hash.h \ mycrypt_macros.h mycrypt_pk.h mycrypt.h mycrypt_argchk.h mycrypt_custom.h #The default rule for make builds the libtomcrypt library. default:library mycrypt.h mycrypt_cfg.h #These are the rules to make certain object files. rsa.o: rsa.c rsa_sys.c ecc.o: ecc.c ecc_sys.c dh.o: dh.c dh_sys.c aes.o: aes.c aes_tab.c twofish.o: twofish.c twofish_tab.c sha512.o: sha512.c sha384.c sha256.o: sha256.c sha224.c #This rule makes the libtomcrypt library. library: $(LIBNAME) $(LIBNAME): $(OBJECTS) $(AR) $(ARFLAGS) $@ $(OBJECTS) #This rule makes the test program included with libtomcrypt test: library $(TESTOBJECTS) $(CC) $(TESTOBJECTS) $(LIBNAME) -o $(TEST) $(WARN) #This rule makes the hash program included with libtomcrypt hashsum: library $(HASHOBJECTS) $(CC) $(HASHOBJECTS) $(LIBNAME) -o $(HASH) $(WARN) #makes the crypt program crypt: library $(CRYPTOBJECTS) $(CC) $(CRYPTOBJECTS) $(LIBNAME) -o $(CRYPT) $(WARN) #makes the small program small: library $(SMALLOBJECTS) $(CC) $(SMALLOBJECTS) $(LIBNAME) -o $(SMALL) $(WARN) x86_prof: library $(PROFS) $(CC) $(PROFS) $(LIBNAME) -o $(PROF) tv_gen: library $(TVS) $(CC) $(TVS) $(LIBNAME) -o $(TV) #This rule installs the library and the header files. This must be run #as root in order to have a high enough permission to write to the correct #directories and to set the owner and group to root. install: library docs install -d -g root -o root $(DESTDIR)$(LIBPATH) install -d -g root -o root $(DESTDIR)$(INCPATH) install -d -g root -o root $(DESTDIR)$(DATAPATH) install -g root -o root $(LIBNAME) $(DESTDIR)$(LIBPATH) install -g root -o root $(HEADERS) $(DESTDIR)$(INCPATH) install -g root -o root crypt.pdf $(DESTDIR)$(DATAPATH) #This rule cleans the source tree of all compiled code, not including the pdf #documentation. clean: rm -f $(OBJECTS) $(TESTOBJECTS) $(HASHOBJECTS) $(CRYPTOBJECTS) $(SMALLOBJECTS) $(LEFTOVERS) $(LIBNAME) rm -f $(TEST) $(HASH) $(COMPRESSED) $(PROFS) $(PROF) $(TVS) $(TV) rm -f *.a *.dll *stackdump *.lib *.exe *.obj demos/*.obj demos/*.o *.bat *.txt #This builds the crypt.pdf file. Note that the rm -f *.pdf has been removed #from the clean command! This is because most people would like to keep the #nice pre-compiled crypt.pdf that comes with libtomcrypt! We only need to #delete it if we are rebuilding it. docs: crypt.tex rm -f crypt.pdf $(LEFTOVERS) latex crypt > /dev/null makeindex crypt > /dev/null pdflatex crypt > /dev/null rm -f $(LEFTOVERS) #beta beta: clean cd .. ; rm -rf crypt* libtomcrypt-$(VERSION)-beta ; mkdir libtomcrypt-$(VERSION)-beta ; \ cp -R ./libtomcrypt/* ./libtomcrypt-$(VERSION)-beta/ ; tar -c libtomcrypt-$(VERSION)-beta/* > crypt-$(VERSION)-beta.tar ; \ bzip2 -9vv crypt-$(VERSION)-beta.tar ; zip -9 -r crypt-$(VERSION)-beta.zip libtomcrypt-$(VERSION)-beta/* #zipup the project (take that!) zipup: clean docs cd .. ; rm -rf crypt* libtomcrypt-$(VERSION) ; mkdir libtomcrypt-$(VERSION) ; \ cp -R ./libtomcrypt/* ./libtomcrypt-$(VERSION)/ ; tar -c libtomcrypt-$(VERSION)/* > crypt-$(VERSION).tar ; \ bzip2 -9vv crypt-$(VERSION).tar ; zip -9 -r crypt-$(VERSION).zip libtomcrypt-$(VERSION)/* <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Orbit // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorOrbitDecl(); CKERROR CreateOrbitProto(CKBehaviorPrototype **pproto); int Orbit(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorOrbitDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Camera Orbit"); od->SetDescription("Makes a Camera orbit round a 3D Entity."); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Target: </SPAN>3D Entity to target.<BR> <SPAN CLASS=pin>Distance: </SPAN>current distance between the Camera and its target.<BR> <BR> The following keys are used by default to move the Camera around its target:<BR> <BR> <FONT COLOR=#FFFFFF>Page Up: </FONT>Zoom in.<BR> <FONT COLOR=#FFFFFF>Page Down: </FONT>Zoom out.<BR> <FONT COLOR=#FFFFFF>Up and Down Arrows: </FONT>Rotate around the view X axis.<BR> <FONT COLOR=#FFFFFF>Left and Right Arrows: </FONT>Rotate around the view Y axis.<BR> <FONT COLOR=#FFFFFF>RIGHT SHIFT: </FONT>Velocity x 2.<BR> The arrow keys are the inverted T arrow keys and not the ones of the numeric keypad.<BR> <BR> <SPAN CLASS=setting>Key Zoom in: </SPAN>Key used to zoom in.<BR> <SPAN CLASS=setting>Key Zoom out: </SPAN>Key used to zoom in.<BR> <SPAN CLASS=setting>Key Rotate Up: </SPAN>Key used to rotate up.<BR> <SPAN CLASS=setting>Key Rotate Down: </SPAN>Key used to rotate down.<BR> <SPAN CLASS=setting>Key Rotate Left: </SPAN>Key used to rotate left.<BR> <SPAN CLASS=setting>Key Rotate Right: </SPAN>Key used to rotate right.<BR> <SPAN CLASS=setting>Key Speed x2: </SPAN>Key used to speed up motion by 2.<BR> <BR> */ od->SetCategory("Cameras/Movement"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x777d999e, 0xdef777d8)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateOrbitProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(INPUT_MANAGER_GUID); return od; } CKERROR CreateOrbitProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Camera Orbit"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Target", CKPGUID_3DENTITY ); proto->DeclareOutParameter("Distance", CKPGUID_FLOAT ); proto->DeclareSetting("Key Zoom In", CKPGUID_KEY,"Numpad -"); proto->DeclareSetting("Key Zoom Out", CKPGUID_KEY,"Numpad +"); proto->DeclareSetting("Key Rotate Up", CKPGUID_KEY,"Up Arrow"); proto->DeclareSetting("Key Rotate Down", CKPGUID_KEY,"Down Arrow"); proto->DeclareSetting("Key Rotate Left", CKPGUID_KEY,"Left Arrow"); proto->DeclareSetting("Key Rotate Right", CKPGUID_KEY,"Right Arrow"); proto->DeclareSetting("Key Speed x2", CKPGUID_KEY,"Right Shift"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(Orbit); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int Orbit(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; // Set IO states beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); CKCamera *cam = (CKCamera *) beh->GetTarget(); if( !cam ) return CKBR_OWNERERROR; // Get Key Codes int key_zoomin=0; beh->GetLocalParameterValue(0, &key_zoomin); if(!key_zoomin) key_zoomin=CKKEY_PRIOR; int key_zoomout=0; beh->GetLocalParameterValue(1, &key_zoomout); if(!key_zoomout) key_zoomout=CKKEY_NEXT; int key_rotateup=0; beh->GetLocalParameterValue(2, &key_rotateup); if(!key_rotateup) key_rotateup=CKKEY_UP; int key_rotatedown=0; beh->GetLocalParameterValue(3, &key_rotatedown); if(!key_rotatedown) key_rotatedown=CKKEY_DOWN; int key_rotateleft=0; beh->GetLocalParameterValue(4, &key_rotateleft); if(!key_rotateleft) key_rotateleft=CKKEY_LEFT; int key_rotateright=0; beh->GetLocalParameterValue(5, &key_rotateright); if(!key_rotateright) key_rotateright=CKKEY_RIGHT; int key_speedx2=0; beh->GetLocalParameterValue(6, &key_speedx2); if(!key_speedx2) key_speedx2=CKKEY_RSHIFT; // Object to follow CK3dEntity *ent = (CK3dEntity *) beh->GetInputParameterObject(0); VxVector pos_tar; float radius; if( ent ){ ent->GetPosition( &pos_tar ); radius = ent->GetRadius(); } else { radius = 10.0f; pos_tar = VxVector::axis0(); } if( radius <= 0.01f ) radius = 0.01f; VxVector pos; // Get the Target of camera CK3dEntity *tar; CKBOOL CameraHasTarget = CKIsChildClassOf( cam, CKCID_TARGETCAMERA ) && (tar=((CKTargetCamera*)cam)->GetTarget()); if( CameraHasTarget ){ tar->SetPosition( &pos_tar ); } else { tar = ent; } //________________// Left / Right / Up / Down cam->GetPosition( &pos, NULL); pos -= pos_tar; CKInputManager *input = (CKInputManager*)behcontext.Context->GetManagerByGuid(INPUT_MANAGER_GUID); if( !input ) return CKBR_GENERICERROR; float d = Magnitude( pos ); float ratio = (input->IsKeyDown(key_speedx2))? .003f:.001f; // float s = d * radius * ratio; float s = d * behcontext.DeltaTime * ratio; VxVector dep(0.0f); if( input->IsKeyDown(key_rotateup) ) dep.y = s; if( input->IsKeyDown(key_rotatedown) ) dep.y += -s; if( input->IsKeyDown(key_rotateleft) ) dep.x = -s; if( input->IsKeyDown(key_rotateright) ) dep.x += s; cam->Translate( &dep, cam, FALSE); //________________// Forward / Backward cam->GetPosition( &pos, NULL); pos -= pos_tar; float tmp = Magnitude( pos ); dep.x = 0.0f; dep.y = 0.0f; dep.z = tmp - d; if( input->IsKeyDown(key_zoomin) ) dep.z += s; if( input->IsKeyDown(key_zoomout) ) dep.z += -s; cam->Translate( &dep, cam, FALSE); //________________// Output Distance d = tmp - dep.z; beh->SetOutputParameterValue(0, &d ); //________________// Look At target if( !CameraHasTarget ){ cam->LookAt( &pos_tar ); } return CKBR_OK; } <file_sep>#include "xDistributedPoint3F.h" #include "xMathStream.h" #include "xPredictionSetting.h" #include "xDistributedPropertyInfo.h" uxString xDistributedPoint3F::print(TNL::BitSet32 flags) { return uxString(); } void xDistributedPoint3F::updateFromServer(xNStream *stream) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { TNL::Point3f p; stream->readPointCompressed(&p,1.0f); Point3F realPos(p.x,p.y,p.z); TNL::Point3f v; stream->readPointCompressed(&v,1.0f); Point3F velocity(v.x,v.y,v.z); mLastServerValue = realPos; mLastServerDifference = velocity; } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { TNL::Point3f p; stream->readPointCompressed(&p,1.0f); Point3F realPos(p.x,p.y,p.z); mLastServerValue = realPos; } setValueState(E_DV_UPDATED); //xLogger::xLog(ELOGINFO,XL_START,"\n vel: %f,%f,%f",velocity.x,velocity.y,velocity.z ); } void xDistributedPoint3F::updateGhostValue(xNStream *stream) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { TNL::Point3f p; p.x = mCurrentValue.x; p.y = mCurrentValue.y; p.z = mCurrentValue.z; stream->writePointCompressed(p,1.0f); TNL::Point3f v; v.x = mDifference.x; v.y = mDifference.y; v.z = mDifference.z; stream->writePointCompressed(v,1.0f); } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { TNL::Point3f p; p.x = mCurrentValue.x; p.y = mCurrentValue.y; p.z = mCurrentValue.z; stream->writePointCompressed(p,1.0f); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedPoint3F::unpack(xNStream *bstream,float sendersOneWayTime) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { sendersOneWayTime *= 0.001f; TNL::Point3f p; bstream->readPointCompressed(&p,1.0f); Point3F realPos(p.x,p.y,p.z); TNL::Point3f v; bstream->readPointCompressed(&v,1.0f); Point3F velocity(v.x,v.y,v.z); Point3F predictedPos = realPos + velocity * sendersOneWayTime; setOwnersOneWayTime(sendersOneWayTime); mLastValue = mCurrentValue; mCurrentValue = predictedPos; mDifference= mCurrentValue - mLastValue; } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { TNL::Point3f p; bstream->readPointCompressed(&p,1.0f); Point3F realPos(p.x,p.y,p.z); mLastValue = realPos; mLastServerValue = realPos; mCurrentValue = realPos; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedPoint3F::pack(xNStream *bstream) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { TNL::Point3f p; p.x = mCurrentValue.x; p.y = mCurrentValue.y; p.z = mCurrentValue.z; bstream->writePointCompressed(p,1.0f); TNL::Point3f v; v.x = mDifference.x; v.y = mDifference.y; v.z = mDifference.z; bstream->writePointCompressed(v,1.0f); } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { TNL::Point3f p; p.x = mCurrentValue.x; p.y = mCurrentValue.y; p.z = mCurrentValue.z; bstream->writePointCompressed(p,1.0f); } int flags = getFlags(); flags &= (~E_DP_NEEDS_SEND); setFlags(flags); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedPoint3F::updateValue(Point3F value,xTimeType currentTime) { mLastTime = mCurrentTime; mCurrentTime = currentTime; mLastDeltaTime = mCurrentTime - mLastTime; mLastValue = mCurrentValue; mCurrentValue = value; mDifference = mCurrentValue - mLastValue; mThresoldTicker +=mLastDeltaTime; float lengthDiff = fabsf(mDifference.len()); float timeDiffMs = ((float)mThresoldTicker) / 1000.f; int flags = getFlags(); flags =E_DP_OK; bool result = false; if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { if (lengthDiff > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime()) { flags =E_DP_NEEDS_SEND; result = true ; //xLogger::xLog(ELOGINFO,XL_START,"mThresoldTicker2: %f",mThresoldTicker2); } } Point3F serverDiff = mCurrentValue-mLastServerValue ; if ( fabsf( serverDiff.len()) > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > (getPredictionSettings()->getMinSendTime() * 0.2f) ) { flags =E_DP_NEEDS_SEND; result = true ; //xLogger::xLog(ELOGINFO,XL_START,"mThresoldTicker2: %f",mThresoldTicker2); } } if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime()) { mThresoldTicker2 = 0 ; mThresoldTicker = 0; } } if (getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { flags =E_DP_NEEDS_SEND; result = true ; mLastValue = value; mCurrentValue = value; } setFlags(flags); return result; }<file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #include "tnl.h" #include "tnlEventConnection.h" #include "tnlBitStream.h" #include "tnlLog.h" #include "tnlNetInterface.h" namespace TNL { ClassChunker<EventConnection::EventNote> EventConnection::mEventNoteChunker; EventConnection::EventConnection() { // event management data: mNotifyEventList = NULL; mSendEventQueueHead = NULL; mSendEventQueueTail = NULL; mUnorderedSendEventQueueHead = NULL; mUnorderedSendEventQueueTail = NULL; mWaitSeqEvents = NULL; mNextSendEventSeq = FirstValidSendEventSeq; mNextRecvEventSeq = FirstValidSendEventSeq; mLastAckedEventSeq = -1; mEventClassCount = 0; mEventClassBitSize = 0; } EventConnection::~EventConnection() { while(mNotifyEventList) { EventNote *temp = mNotifyEventList; mNotifyEventList = temp->mNextEvent; temp->mEvent->notifyDelivered(this, true); mEventNoteChunker.free(temp); } while(mUnorderedSendEventQueueHead) { EventNote *temp = mUnorderedSendEventQueueHead; mUnorderedSendEventQueueHead = temp->mNextEvent; temp->mEvent->notifyDelivered(this, true); mEventNoteChunker.free(temp); } while(mSendEventQueueHead) { EventNote *temp = mSendEventQueueHead; mSendEventQueueHead = temp->mNextEvent; temp->mEvent->notifyDelivered(this, true); mEventNoteChunker.free(temp); } } void EventConnection::writeConnectRequest(BitStream *stream) { Parent::writeConnectRequest(stream); stream->write(NetClassRep::getNetClassCount(getNetClassGroup(), NetClassTypeEvent)); } bool EventConnection::readConnectRequest(BitStream *stream, const char **errorString) { if(!Parent::readConnectRequest(stream, errorString)) return false; U32 classCount; stream->read(&classCount); U32 myCount = NetClassRep::getNetClassCount(getNetClassGroup(), NetClassTypeEvent); if(myCount <= classCount) mEventClassCount = myCount; else { mEventClassCount = classCount; if(!NetClassRep::isVersionBorderCount(getNetClassGroup(), NetClassTypeEvent, mEventClassCount)) return false; } mEventClassVersion = NetClassRep::getClass(getNetClassGroup(), NetClassTypeEvent, mEventClassCount-1)->getClassVersion(); mEventClassBitSize = getNextBinLog2(mEventClassCount); return true; } void EventConnection::writeConnectAccept(BitStream *stream) { Parent::writeConnectAccept(stream); stream->write(mEventClassCount); } bool EventConnection::readConnectAccept(BitStream *stream, const char **errorString) { if(!Parent::readConnectAccept(stream, errorString)) return false; stream->read(&mEventClassCount); U32 myCount = NetClassRep::getNetClassCount(getNetClassGroup(), NetClassTypeEvent); if(mEventClassCount > myCount) return false; if(!NetClassRep::isVersionBorderCount(getNetClassGroup(), NetClassTypeEvent, mEventClassCount)) return false; mEventClassBitSize = getNextBinLog2(mEventClassCount); return true; } void EventConnection::processEvent(NetEvent *theEvent) { if(getConnectionState() == NetConnection::Connected) theEvent->process(this); } void EventConnection::packetDropped(PacketNotify *pnotify) { Parent::packetDropped(pnotify); EventPacketNotify *notify = static_cast<EventPacketNotify *>(pnotify); EventNote *walk = notify->eventList; EventNote **insertList = &mSendEventQueueHead; EventNote *temp; while(walk) { switch(walk->mEvent->mGuaranteeType) { case NetEvent::GuaranteedOrdered: // It was a guaranteed ordered packet, reinsert it back into // mSendEventQueueHead in the right place (based on seq numbers) TNLLogMessageV(LogEventConnection, ("EventConnection %s: DroppedGuaranteed - %d", getNetAddressString(), walk->mSeqCount)); while(*insertList && (*insertList)->mSeqCount < walk->mSeqCount) insertList = &((*insertList)->mNextEvent); temp = walk->mNextEvent; walk->mNextEvent = *insertList; if(!walk->mNextEvent) mSendEventQueueTail = walk; *insertList = walk; insertList = &(walk->mNextEvent); walk = temp; break; case NetEvent::Guaranteed: // It was a guaranteed packet, put it at the top of // mUnorderedSendEventQueueHead. temp = walk->mNextEvent; walk->mNextEvent = mUnorderedSendEventQueueHead; mUnorderedSendEventQueueHead = walk; if(!walk->mNextEvent) mUnorderedSendEventQueueTail = walk; walk = temp; break; case NetEvent::Unguaranteed: // Or else it was an unguaranteed packet, notify that // it was _not_ delivered and blast it. walk->mEvent->notifyDelivered(this, false); temp = walk->mNextEvent; mEventNoteChunker.free(walk); walk = temp; } } } void EventConnection::packetReceived(PacketNotify *pnotify) { Parent::packetReceived(pnotify); EventPacketNotify *notify = static_cast<EventPacketNotify *>(pnotify); EventNote *walk = notify->eventList; EventNote **noteList = &mNotifyEventList; while(walk) { EventNote *next = walk->mNextEvent; if(walk->mEvent->mGuaranteeType != NetEvent::GuaranteedOrdered) { walk->mEvent->notifyDelivered(this, true); mEventNoteChunker.free(walk); walk = next; } else { while(*noteList && (*noteList)->mSeqCount < walk->mSeqCount) noteList = &((*noteList)->mNextEvent); walk->mNextEvent = *noteList; *noteList = walk; noteList = &walk->mNextEvent; walk = next; } } while(mNotifyEventList && mNotifyEventList->mSeqCount == mLastAckedEventSeq + 1) { mLastAckedEventSeq++; EventNote *next = mNotifyEventList->mNextEvent; TNLLogMessageV(LogEventConnection, ("EventConnection %s: NotifyDelivered - %d", getNetAddressString(), mNotifyEventList->mSeqCount)); mNotifyEventList->mEvent->notifyDelivered(this, true); mEventNoteChunker.free(mNotifyEventList); mNotifyEventList = next; } } void EventConnection::writePacket(BitStream *bstream, PacketNotify *pnotify) { Parent::writePacket(bstream, pnotify); EventPacketNotify *notify = static_cast<EventPacketNotify *>(pnotify); if(mConnectionParameters.mDebugObjectSizes) bstream->writeInt(DebugChecksum, 32); EventNote *packQueueHead = NULL, *packQueueTail = NULL; while(mUnorderedSendEventQueueHead) { if(bstream->isFull()) break; // get the first event EventNote *ev = mUnorderedSendEventQueueHead; bstream->writeFlag(true); S32 start = bstream->getBitPosition(); if(mConnectionParameters.mDebugObjectSizes) bstream->advanceBitPosition(BitStreamPosBitSize); S32 classId = ev->mEvent->getClassId(getNetClassGroup()); bstream->writeInt(classId, mEventClassBitSize); ev->mEvent->pack(this, bstream); TNLLogMessageV(LogEventConnection, ("EventConnection %s: WroteEvent %s - %d bits", getNetAddressString(), ev->mEvent->getDebugName(), bstream->getBitPosition() - start)); if(mConnectionParameters.mDebugObjectSizes) bstream->writeIntAt(bstream->getBitPosition(), BitStreamPosBitSize, start); if(bstream->getBitSpaceAvailable() < MinimumPaddingBits) { // rewind to before the event, and break out of the loop: bstream->setBitPosition(start - 1); bstream->clearError(); break; } // dequeue the event and add this event onto the packet queue mUnorderedSendEventQueueHead = ev->mNextEvent; ev->mNextEvent = NULL; if(!packQueueHead) packQueueHead = ev; else packQueueTail->mNextEvent = ev; packQueueTail = ev; } bstream->writeFlag(false); S32 prevSeq = -2; while(mSendEventQueueHead) { if(bstream->isFull()) break; // if the event window is full, stop processing if(mSendEventQueueHead->mSeqCount > mLastAckedEventSeq + 126) break; // get the first event EventNote *ev = mSendEventQueueHead; S32 eventStart = bstream->getBitPosition(); bstream->writeFlag(true); if(!bstream->writeFlag(ev->mSeqCount == prevSeq + 1)) bstream->writeInt(ev->mSeqCount, 7); prevSeq = ev->mSeqCount; if(mConnectionParameters.mDebugObjectSizes) bstream->advanceBitPosition(BitStreamPosBitSize); S32 start = bstream->getBitPosition(); S32 classId = ev->mEvent->getClassId(getNetClassGroup()); bstream->writeInt(classId, mEventClassBitSize); ev->mEvent->pack(this, bstream); ev->mEvent->getClassRep()->addInitialUpdate(bstream->getBitPosition() - start); TNLLogMessageV(LogEventConnection, ("EventConnection %s: WroteEvent %s - %d bits", getNetAddressString(), ev->mEvent->getDebugName(), bstream->getBitPosition() - start)); if(mConnectionParameters.mDebugObjectSizes) bstream->writeIntAt(bstream->getBitPosition(), BitStreamPosBitSize, start - BitStreamPosBitSize); if(bstream->getBitSpaceAvailable() < MinimumPaddingBits) { // rewind to before the event, and break out of the loop: bstream->setBitPosition(eventStart); bstream->clearError(); break; } // dequeue the event: mSendEventQueueHead = ev->mNextEvent; ev->mNextEvent = NULL; if(!packQueueHead) packQueueHead = ev; else packQueueTail->mNextEvent = ev; packQueueTail = ev; } for(EventNote *ev = packQueueHead; ev; ev = ev->mNextEvent) ev->mEvent->notifySent(this); notify->eventList = packQueueHead; bstream->writeFlag(0); } void EventConnection::readPacket(BitStream *bstream) { Parent::readPacket(bstream); if(mConnectionParameters.mDebugObjectSizes) { U32 sum = bstream->readInt(32); TNLAssert(sum == DebugChecksum, "Invalid checksum."); } S32 prevSeq = -2; EventNote **waitInsert = &mWaitSeqEvents; bool unguaranteedPhase = true; while(true) { bool bit = bstream->readFlag(); if(unguaranteedPhase && !bit) { unguaranteedPhase = false; bit = bstream->readFlag(); } if(!unguaranteedPhase && !bit) break; S32 seq = -1; if(!unguaranteedPhase) // get the sequence { if(bstream->readFlag()) seq = (prevSeq + 1) & 0x7f; else seq = bstream->readInt(7); prevSeq = seq; } U32 endingPosition; if(mConnectionParameters.mDebugObjectSizes) endingPosition = bstream->readInt(BitStreamPosBitSize); U32 classId = bstream->readInt(mEventClassBitSize); if(classId >= mEventClassCount) { setLastError("Invalid packet."); return; } NetEvent *evt = (NetEvent *) Object::create(getNetClassGroup(), NetClassTypeEvent, classId); if(!evt) { setLastError("Invalid packet."); return; } // check if the direction this event moves is a valid direction. if( (evt->getEventDirection() == NetEvent::DirUnset) || (evt->getEventDirection() == NetEvent::DirServerToClient && isConnectionToClient()) || (evt->getEventDirection() == NetEvent::DirClientToServer && isConnectionToServer()) ) { setLastError("Invalid Packet."); return; } evt->unpack(this, bstream); if(mErrorBuffer[0]) return; if(mConnectionParameters.mDebugObjectSizes) { TNLAssert(endingPosition == bstream->getBitPosition(), avar("unpack did not match pack for event of class %s.", evt->getClassName()) ); } if(unguaranteedPhase) { processEvent(evt); delete evt; if(mErrorBuffer[0]) return; continue; } seq |= (mNextRecvEventSeq & ~0x7F); if(seq < mNextRecvEventSeq) seq += 128; EventNote *note = mEventNoteChunker.alloc(); note->mEvent = evt; note->mSeqCount = seq; TNLLogMessageV(LogEventConnection, ("EventConnection %s: RecvdGuaranteed %d", getNetAddressString(), seq)); while(*waitInsert && (*waitInsert)->mSeqCount < seq) waitInsert = &((*waitInsert)->mNextEvent); note->mNextEvent = *waitInsert; *waitInsert = note; waitInsert = &(note->mNextEvent); } while(mWaitSeqEvents && mWaitSeqEvents->mSeqCount == mNextRecvEventSeq) { mNextRecvEventSeq++; EventNote *temp = mWaitSeqEvents; mWaitSeqEvents = temp->mNextEvent; TNLLogMessageV(LogEventConnection, ("EventConnection %s: ProcessGuaranteed %d", getNetAddressString(), temp->mSeqCount)); processEvent(temp->mEvent); mEventNoteChunker.free(temp); if(mErrorBuffer[0]) return; } } bool EventConnection::postNetEvent(NetEvent *theEvent) { S32 classId = theEvent->getClassId(getNetClassGroup()); if(U32(classId) >= mEventClassCount && getConnectionState() == Connected) return false; theEvent->notifyPosted(this); EventNote *event = mEventNoteChunker.alloc(); event->mEvent = theEvent; event->mNextEvent = NULL; if(event->mEvent->mGuaranteeType == NetEvent::GuaranteedOrdered) { event->mSeqCount = mNextSendEventSeq++; if(!mSendEventQueueHead) mSendEventQueueHead = event; else mSendEventQueueTail->mNextEvent = event; mSendEventQueueTail = event; } else { event->mSeqCount = InvalidSendEventSeq; if(!mUnorderedSendEventQueueHead) mUnorderedSendEventQueueHead = event; else mUnorderedSendEventQueueTail->mNextEvent = event; mUnorderedSendEventQueueTail = event; } return true; } bool EventConnection::isDataToTransmit() { return mUnorderedSendEventQueueHead || mSendEventQueueHead || Parent::isDataToTransmit(); } }; <file_sep>#ifndef VT_BASE_MANAGER_H__ #define VT_BASE_MANAGER_H__ "$Id:$" #include "BaseMacros.h" #include "CKBaseManager.h" class MODULE_API vtBaseManager : public CKBaseManager { public: virtual CKERROR OnCKInit()=0; virtual CKERROR PostClearAll()=0; virtual CKERROR PreSave()=0; virtual CKERROR OnCKReset()=0; virtual CKERROR PreProcess()=0; virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_PostClearAll| CKMANAGER_FUNC_OnCKInit| CKMANAGER_FUNC_PreSave| CKMANAGER_FUNC_PostLoad| CKMANAGER_FUNC_OnCKReset| CKMANAGER_FUNC_PreProcess; } virtual void RegisterParameters()=0; virtual void RegisterVSL()=0; vtBaseManager(CKContext *context,CKGUID guid,char* name) : CKBaseManager(context,guid,name) {}; ~vtBaseManager(){}; }; // CK2 VERSION ... #endif <file_sep>#include <StdAfx.h> #include "xTime.h" #include <pch.h> xTime::xTime() { // Default time span span=0.01; spanMS=10; tmr=new QTimer(); Reset(); } xTime::~xTime() { SAFE_DELETE(tmr); } /********** * Attribs * **********/ void xTime::AddSimTime(int msecs) // Another 'msecs' of time was simulated { curSimTime+=msecs; } #ifdef OBS_INLINED void xTime::SetLastSimTime(int t) // 't' is the time to which the sim has been simulated // This is set after a number of integrations to remember the last // time for the next graphics frame (calculating the distance in time to 'now') { lastSimTime=t; } #endif void xTime::SetSpan(int ms) // Set integration step time in milliseconds { spanMS=ms; span=((float)ms)/1000.0f; } /************* * Start/stop * *************/ void xTime::Start() // Start the real timer { tmr->Start(); } void xTime::Stop() // Stop the real timer { tmr->Stop(); } void xTime::Reset() // Reset the real timer (to 0) { tmr->Reset(); curRealTime=0; curSimTime=0; lastSimTime=0; } /********* * Update * *********/ void xTime::Update() // Update the real timing { curRealTime=tmr->GetMilliSeconds(); } <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xDistributedSession.h" #include <vtTools.h> #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorNServerStopDecl(); CKERROR CreateNServerStopProto(CKBehaviorPrototype **); int NServerStop(const CKBehaviorContext& behcontext); CKERROR NServerStopCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorNServerStopDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NServerStop"); od->SetDescription("Stops an embedded server"); od->SetCategory("TNL/Server"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x5c357547,0x34836669)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNServerStopProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } typedef enum BB_IT { BB_IT_IN, BB_IT_OFF, BB_IT_NEXT, }; typedef enum BB_INPAR { BB_IP_ADDRESS, BB_IP_MAXCLIENTS, }; typedef enum BB_OT { BB_O_OUT, BB_O_ERROR, }; typedef enum BB_OP { BB_OP_SERVER_ADDRESS, BB_OP_ERROR }; CKERROR CreateNServerStopProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NServerStop"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(NServerStop); proto->SetBehaviorCallbackFct(NServerStopCB); *pproto = proto; return CK_OK; } int NServerStop(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); using namespace vtTools::BehaviorTools; if (beh->IsInputActive(0)) { bool result = true; beh->ActivateInput(0,FALSE); xNetInterface *cin = GetNM()->GetServerNetInterface(); if (cin) { GetNM()->SetServerNetInterface(NULL); return 0; } beh->ActivateOutput(0); return CKBR_OK; } return 0; } CKERROR NServerStopCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" pJointDistance::pJointDistance(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Distance) { } void pJointDistance::setMinDistance(float distance) { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.minDistance=distance; if (distance !=0.0f) { descr.flags |=NX_DJF_MIN_DISTANCE_ENABLED; }else descr.flags &=~NX_DJF_MIN_DISTANCE_ENABLED; joint->loadFromDesc(descr); } void pJointDistance::setMaxDistance(float distance) { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.maxDistance=distance; if (distance !=0.0f) { descr.flags |=NX_DJF_MAX_DISTANCE_ENABLED; }else descr.flags &=~NX_DJF_MAX_DISTANCE_ENABLED; joint->loadFromDesc(descr); } void pJointDistance::setLocalAnchor1(VxVector anchor) { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.localAnchor[1] =getFrom(anchor); joint->loadFromDesc(descr); } void pJointDistance::setLocalAnchor0(VxVector anchor) { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); descr.localAnchor[0] =getFrom(anchor); joint->loadFromDesc(descr); } void pJointDistance::enableCollision(int collision) { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return ; joint->saveToDesc(descr); if (collision) { descr.jointFlags |= NX_JF_COLLISION_ENABLED; }else descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; joint->loadFromDesc(descr); } bool pJointDistance::setSpring( pSpring spring ) { NxDistanceJointDesc descr; NxDistanceJoint *joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return false; joint->saveToDesc(descr); NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; if (!sLimit.isValid())return false; descr.spring= sLimit; if(spring.spring!=0.0f || spring.damper!=0.0f ) descr.flags|=NX_DJF_SPRING_ENABLED; else descr.flags &=~NX_DJF_SPRING_ENABLED; joint->loadFromDesc(descr); return true; } VxVector pJointDistance::getLocalAnchor0() { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return VxVector(); joint->saveToDesc(descr); return getFrom(descr.localAnchor[0]); } VxVector pJointDistance::getLocalAnchor1() { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return VxVector(); joint->saveToDesc(descr); return getFrom(descr.localAnchor[1]); } float pJointDistance::getMinDistance() { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return -1.0f; joint->saveToDesc(descr); return descr.minDistance; } float pJointDistance::getMaxDistance() { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); if (!joint)return -1.0f; joint->saveToDesc(descr); return descr.maxDistance; } pSpring pJointDistance::getSpring() { NxDistanceJointDesc descr; NxDistanceJoint*joint = static_cast<NxDistanceJoint*>(getJoint()); pSpring result; if (!joint)result; joint->saveToDesc(descr); result.spring = descr.spring.spring; result.damper = descr.spring.damper; result.targetValue = descr.spring.targetValue; return result; }<file_sep>#include "CPStdAfx.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "vtTools.h" #if defined(CUSTOM_PLAYER_STATIC) #include "CustomPlayerStaticLibs.h" #include "CustomPlayerRegisterDlls.h" #endif #include "xSplash.h" extern CCustomPlayer* thePlayer; #include <WindowsX.h> void CCustomPlayer::Terminate(int flags) { try { if (!m_CKContext) { return; } m_CKContext->Pause(); m_CKContext->Reset(); m_CKContext->ClearAll(); if (m_EnginePointers.TheRenderManager && m_RenderContext ) { m_EnginePointers.TheRenderManager->DestroyRenderContext(m_RenderContext); } m_RenderContext = NULL; CKCloseContext(m_CKContext); CKShutdown(); m_CKContext = NULL; DestroyWindow(m_RenderWindow); DestroyWindow(m_MainWindow); Stop(); PostQuitMessage(0); exit(0); } catch(...) { } //VxGetCurrentDirectory(cDir); //bool res = RunAndForgetProcess2("playerS.exe",cDir ,&ret); //MSGBOX("post quit : now "); //PostQuitMessage(0); //MSGBOX("post quit"); } void CCustomPlayer::StartMove(LPARAM lParam) { nMMoveX = LOWORD(lParam); nMMoveY = HIWORD(lParam); } ////////////////////////////////////////////////////////////////////////// void CCustomPlayer::DoMMove(LPARAM lParam, WPARAM wParam) { if(wParam & MK_LBUTTON) { //if mouse is down; window is being dragged. RECT wnrect; GetWindowRect(this->m_MainWindow,&wnrect); //get window restraints MoveWindow(this->m_MainWindow,wnrect.left+(LOWORD(lParam)-nMMoveX),wnrect.top+(HIWORD(lParam)-nMMoveY),wnrect.right - wnrect.left,wnrect.bottom - wnrect.top,true); } } LRESULT CCustomPlayer::_MainWindowWndProcStub(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ){ return thePlayer->_MainWindowWndProc(hWnd,uMsg,wParam,lParam);} LRESULT CALLBACK CCustomPlayer::_MainWindowWndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) { switch(message) { case WM_DROPFILES: // Load any dropped file { char FileName[_MAX_PATH]; HDROP hdrop=(HDROP)wParam; DragQueryFile(hdrop,0,FileName,_MAX_PATH); Reset(); _Load(FileName); _FinishLoad(); break; } case WM_MOUSEMOVE: { // we allow window dragging enabled in the player.ini file ! if (GetPAppStyle()->g_MouseDrag==1) { DoMMove(lParam,wParam); } } case WM_ACTIVATEAPP: { OnActivateApp(wParam); } break; // Minimum size of the player window case WM_GETMINMAXINFO: // this message is not very useful because // the main window of the player is not resizable ... // but perhaps it will change so we manage this message. { CCustomPlayer& player = CCustomPlayer::Instance(); if((LPMINMAXINFO)lParam) { ((LPMINMAXINFO)lParam)->ptMinTrackSize.x=MininumWindowedWidth(); ((LPMINMAXINFO)lParam)->ptMinTrackSize.y=MininumWindowedHeight(); } } break; // Sends a Message "OnClick" or "OnDblClick" if any object is under mouse cursor case WM_LBUTTONDBLCLK: case WM_LBUTTONDOWN: { OnMouseClick(message); // [2/18/2008 mc007] // we allow window dragging enabled in the player.ini file ! if (GetPAppStyle()->g_MouseDrag) { StartMove(lParam); } } break; // Size and focus management case WM_SIZE: // if the window is maximized or minimized // we get/lost focus. { if (wParam==SIZE_MINIMIZED) { OnFocusChange(FALSE); } else if (wParam==SIZE_MAXIMIZED) { OnFocusChange(TRUE); } } break; // Manage system key (ALT + KEY) case WM_SYSKEYDOWN: { // return OnSysKeyDownMainWindow(theApp.m_Config,(int)wParam); } break; // Repaint main frame case WM_PAINT: { OnPaint(); } break; // The main windows has been closed by the user case WM_CLOSE: PostQuitMessage(0); break; // Focus management case WM_KILLFOCUS: case WM_SETFOCUS: { OnFocusChange(message==WM_SETFOCUS); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return DefWindowProc(hWnd, message, wParam, lParam); } static DWORD WINAPI runner(LPVOID lpParam){ GetPlayer().DoFrame(); return TRUE;} void CCustomPlayer::Stop() { if (m_hThread) { TerminateThread(m_hThread,0); Sleep(50); m_hThread = NULL; } } int CCustomPlayer::RunInThread() { DWORD threadId, thirdParam = 0; m_hThread = CreateThread( NULL, // no security attributes 0, // use default stack size runner, // thread function &thirdParam, // argument to thread function 0, // use default creation flags &threadId); // returns the thread identifier return 123; } int CCustomPlayer::Tick() { MSG msg; GetMessage(&msg, NULL, 0, 0); TranslateMessage(&msg); DispatchMessage(&msg); return Process(m_Config); } #include <stdio.h> #include <conio.h> HRESULT CCustomPlayer::DoFrame() { BOOL bGotMsg; MSG msg; msg.message = WM_NULL; while ( msg.message != WM_QUIT ) { if (kbhit()) { char message[400]; gets(message); if (!strcmp(message,"exit")) { Terminate(0); } SendMessage("Level","ConsoleMessage",1,1,1,message); while (kbhit()){ getch(); } } bGotMsg = PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ); if( bGotMsg ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else Process(m_Config); } return S_OK; } CKERROR LogRedirect(CKUICallbackStruct& loaddata,void*) { if(loaddata.Reason == CKUIM_OUTTOCONSOLE || loaddata.Reason == CKUIM_OUTTOINFOBAR || loaddata.Reason == CKUIM_DEBUGMESSAGESEND ) { //printf ("oldString : %s\n",GetPlayer().m_oldText.CStr()); //printf ("newString : %s\n",loaddata.ConsoleString); if (GetPlayer().m_oldText.Compare(loaddata.ConsoleString)) { printf ("%s\n",loaddata.ConsoleString); GetPlayer().m_oldText = loaddata.ConsoleString; //GetPlayer().m_CKContext->OutputToConsoleEx("log:%s",GetPlayer().m_oldText); } //char buffer[MAX_PATH]; /*if (GetPlayer().m_oldText.Compare(loaddata.ConsoleString)) { //printf (loaddata.ConsoleString); GetPlayer().m_oldText = loaddata.ConsoleString; }*/ } return CK_OK; } void CCustomPlayer::RedirectLog() { m_oldText =""; m_CKContext->SetInterfaceMode(FALSE,LogRedirect,NULL); } CKERROR LoadCallBack(CKUICallbackStruct& loaddata,void*) { if (GetPlayer().GetPAppStyle()->UseSplash() && GetPlayer().GetPAppStyle()->ShowLoadingProcess()) { if(loaddata.Reason == CKUIM_LOADSAVEPROGRESS ){ if (loaddata.NbObjetsLoaded % 10 == 0) { float progress = (static_cast<float>(loaddata.NbObjetsLoaded) / static_cast<float>(loaddata.NbObjetsToLoad)) ; progress *=100; int out = static_cast<int>(progress); XString percStr; percStr.Format("Load... %d %s",out,"%"); if (xSplash::GetSplash()) { GetPlayer().SetSplashText(percStr.Str()); if (progress > 99.9F) { GetPlayer().HideSplash(); //Sleep(3000); } } } } } return CK_OK; } void CCustomPlayer::Reset() { // mark the player as playing m_State = ePlaying; // reset m_CKContext->Reset(); // and play m_CKContext->Play(); } void CCustomPlayer::Pause() { // mark the play as paused m_State = ePlaused; // pause m_CKContext->Pause(); } void CCustomPlayer::Play() { // mark the player as playing m_State = ePlaying; // play m_CKContext->Play(); } BOOL CCustomPlayer::Process(int iConfig) { // just to be sure we check the player is ready and playing if (!m_CKContext || !m_CKContext->IsPlaying()) { Sleep(10); return TRUE; } float beforeRender = 0; float beforeProcess = 0; // retrieve the time to wait in milliseconds to perfom a rendering or a process loop // so that the time manager limits are respected. m_TimeManager->GetTimeToWaitForLimits(beforeRender,beforeProcess); if (beforeProcess<=0) { // ok to process m_TimeManager->ResetChronos(FALSE,TRUE); m_CKContext->Process(); } if (beforeRender<=0) { // ok to render m_TimeManager->ResetChronos(TRUE,FALSE); if (GetPlayer().GetPAppStyle()->IsRenderering()) m_RenderContext->Render(); } // now we check if the composition has not change the state of a "control" attribute // quit has been set if (m_Level->HasAttribute(m_QuitAttType)) { // we remove it (so it is not "here" the next frame) m_Level->RemoveAttribute(m_QuitAttType); // MessageBox(NULL,"","a",1); // and return FALSE to quit return FALSE; } // switch fullscreen has been set if (m_Level->HasAttribute(m_SwitchFullscreenAttType)) { //bool goFS;// = vtTools::AttributeTools::GetValueFromAttribute<bool>(m_Level,m_SwitchFullscreenAttType); /*CKParameterOut* pout = m_Level->GetAttributeParameter(m_SwitchFullscreenAttType); if (!pout) { return FALSE; }*/ // we remove it (so it is not "here" the next frame) m_Level->RemoveAttribute(m_SwitchFullscreenAttType); // and switch fullscreen (ie goes from fullscreen to windowed // or to windowed from fullscreen) // if(goFS) if (GetPlayer().GetPAppStyle()->IsRenderering()) SwitchFullscreen(); } // switch resolution has been set if (m_Level->HasAttribute(m_SwitchResolutionAttType)) { // we remove it (so it is not "here" the next frame) m_Level->RemoveAttribute(m_SwitchResolutionAttType); // and we change the resolution ChangeResolution(); } // switch resolution has been set if (m_Level->HasAttribute(m_SwitchMouseClippingAttType)) { // we remove it (so it is not "here" the next frame) m_Level->RemoveAttribute(m_SwitchMouseClippingAttType); m_MouseClipped = !m_MouseClipped; ClipMouse(m_MouseClipped); } return TRUE; } <file_sep>#pragma once #include "StdAfx2.h" #include "VIControls.h" #include "ParameterDialog.h" //#include "CUIKNotificationReceiver.h" //--- Include "GenericObjectParameterDialog.h" from CK2UI define IDDs to mak it compile #include "resource.h" #include "PCommonDialog.h" #include "afxwin.h" //--- Some constants #define MFC_NAME_OF_DIALOG "#32770" #define CHECK_MATERIAL_TIMER 57 class CPBodyCfg : public CParameterDialog { public: // virtual void PreSubclassWindow(); int m_paramType; CPBodyCfg(CKParameter* Parameter,CK_CLASSID Cid=CKCID_OBJECT); virtual ~CPBodyCfg(); void _destroy(); //virtual BOOL Create(UINT nIDTemplate, CWnd* pParentWnd); virtual void Init(CParameterDialog *parent); CParameterDialog* refresh(CKParameter*src); void initSplitter(); /************************************************************************/ /* Overrides */ /************************************************************************/ void OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); LRESULT OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam); /************************************************************************/ /* Accessors */ /************************************************************************/ CKParameter * getEditedParameter() const { return mParameter; } void setEditedParameter(CKParameter * val) { mParameter= val; } /************************************************************************/ /* Virtools mParameter transfer callbacks : */ /************************************************************************/ virtual BOOL On_UpdateFromParameter(CKParameter* p){ // if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); // if(!p) return FALSE; return TRUE; } virtual BOOL On_UpdateToParameter(CKParameter* p) { /* if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); if(!p) return FALSE; CString cstr;*/ return TRUE; } // associated resource id : enum { IDD = IDD_PBCOMMON }; virtual int OnSelect(int before=-1); //{{AFX_VIRTUAL(CPBodyCfg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL //{{AFX_MSG(CPBodyCfg) //}}AFX_MSG public: CParameterDialog *dlgDeformableSettings; //VITrackCtrl mTestViControl; //VITreeCtrl mTestViControl; VITabCtrl mTestViControl; CParameterDialog *mParent; /************************************************************************/ /* Low Level passes */ /************************************************************************/ LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); /************************************************************************/ /* Members */ /************************************************************************/ // Hull Type VIComboBox HType; VIStaticText LBL_HType; void fillHullType(); // Body main Flags VIStaticText LBL_Flags; VICheckButton BF_Move; VICheckButton BF_Grav; VICheckButton BF_Collision; VICheckButton BF_CollisionNotify; VICheckButton BF_Kinematic; VICheckButton BF_TriggerShape; VICheckButton BF_SubShape; VICheckButton BF_Sleep; VICheckButton BF_Hierarchy; VICheckButton BF_Deformable; VIStaticRectangle BF_BG_Rect; VIStaticRectangle BF_FLEX_Rect; void fillFlags(); // Transformation Lock Flags VIStaticText LBL_TransformationLockFlags; VICheckButton TF_POS; VICheckButton TF_ROT; VICheckButton TF_PX; VICheckButton TF_RX; VICheckButton TF_PY; VICheckButton TF_RY; VICheckButton TF_PZ; VICheckButton TF_RZ; void fillTransformationFlags(); public: CKParameter *mParameter; VIEdit editValue; VIStaticText textValue; VIComboBox type; DECLARE_MESSAGE_MAP() afx_msg void OnTcnSelchangeMaintab(NMHDR *pNMHDR, LRESULT *pResult); CComboBox UserLevel; afx_msg void OnCbnSelchangeHulltype2(); afx_msg void OnStnClickedLblFlags(); afx_msg void OnStnClickedDynaFlagsRect(); }; <file_sep>copy /y .\examples\*.cmo .\doxyOutput\html doxygen .\doxyConfigPagesOnly.dox cd .\doxyOutput\ vtPhysX.CHM REM copy X:\ProjectRoot\vdev\Documentation\vtAgeia.CHM X:\ProjectRoot\vtmod_vtAgeia\Doc /y REM copy X:\ProjectRoot\vdev\Documentation\vtAgeia.CHM X:\ProjectRoot\vtmodsvn\Plugins\vtAgeia\Documentation /y REM exit <file_sep>import vt def init(): print("initiated") vt.ActivateOut(bid,0,1) def loop(): print("loop in activated") vt.ActivateOut(bid,1,1) #--------------------------- PyFuncEx enters here : -------------------------------# def vTest(): #-------call init when the first bb input is triggered : if vt.IsInputActive(bid,0) : init() #-------call loop when the second bb input is triggered : if vt.IsInputActive(bid,1) : loop()<file_sep>#ifndef __vtDistributedProperty_h_ #define __vtDistributedProperty_h_ class vtDistributedProperty { public: vtDistributedProperty(); vtDistributedProperty(int type); virtual ~vtDistributedProperty(); XString GetName() const { return m_Name; } void SetName(XString val) { m_Name = val; } DWORD GetType() const { return m_Type; } void SetType(DWORD val) { m_Type = val; } protected: XString m_Name; DWORD m_Type; private: }; #endif<file_sep>/* * Tcp4u v 3.31 Last Revision 27/02/1998 3.30.02 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: util.c * Purpose: A few utilities functions * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" /* this definition will be enough for our use */ #undef toupper #define toupper(x) ( (x) & 0xDF ) /* ------------------------------------------------------------------------- */ /* Conversion d'un nom de machine en adresse IP */ /* Le nom est soit une "dotted address" soit un alias */ /* return : INADDR_NONE or IP address */ /* ------------------------------------------------------------------------- */ struct in_addr Tcp4uGetIPAddr (LPCSTR szHost) { struct hostent far * lpHostEnt; struct in_addr sin_addr; Tcp4uLog (LOG4U_INTERN, "Tcp4uGetIPAddr host %s", szHost); sin_addr.s_addr = inet_addr (szHost); /* doted address */ if (sin_addr.s_addr==INADDR_NONE) /* si pas une doted address */ { /* regarder le fichier hosts */ Tcp4uLog (LOG4U_CALL, "gethostbyname host %s", szHost); lpHostEnt = gethostbyname (szHost); if (lpHostEnt!=NULL) memcpy (& sin_addr.s_addr, lpHostEnt->h_addr, lpHostEnt->h_length); else { Tcp4uLog (LOG4U_ERROR, "gethostbyname host %s", szHost); } } return sin_addr; } /* Tcp4uGetIPAddr */ /* -------------------------------------- */ /* a self-made atoi */ /* -------------------------------------- */ /* Note: ne pas utiliser la fonction isdigit: qui donne des */ /* resultats errones en Windows */ #define IsDigit(x) ( (x)>='0' && (x)<='9') int Tcp4uAtoi (LPCSTR p) { int n; Tcp4uLog (LOG4U_INTERN, "Tcp4uAtoi"); for (n=0 ; IsDigit (*p) ; p++) { n *= 10; n += (*p - '0'); } return n; } /* tcp4u_atoi */ long Tcp4uAtol (LPCSTR p) { long n; Tcp4uLog (LOG4U_INTERN, "Tcp4uAtol"); for (n=0 ; IsDigit (*p) ; p++) { n *= 10; n += (*p - '0'); } return n; } /* Tcp4uAtol */ /* a unix function which is not available under Windows */ /* should have same proto than strncmp */ /* adapted from the GNU strncasecmp */ int Tcp4uStrncasecmp (LPCSTR s1, LPCSTR s2, size_t n) { char c1, c2; for ( ; n!=0 ; --n) { c1 = *s1++; c2 = *s2++; if (toupper (c1)!=toupper(c2)) return toupper (c1) - toupper(c2); if (c1==0) return 0; } return 0; } /* Strncasecmp */ /* ------------------------------------------------------------------------- */ /* a case-insentive strstr */ /* ------------------------------------------------------------------------- */ LPSTR Tcp4uStrIStr (LPCSTR s1, LPCSTR s2) { size_t nLength = Strlen(s2); for (;;) { while (*s1!=0 && toupper(*s1)!=toupper(*s2) ) s1++; if (*s1==0) return NULL; if (Tcp4uStrncasecmp (s1, s2, nLength)==0) return (LPSTR) s1; s1++; } } /* Tcp4uStrIStr */ <file_sep>#include <CPStdAfx.h> #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "resourceplayer.h" #include "CustomPlayerDialogGraphicPage.h" #include "CustomPlayerDialog.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif extern void _UpdateResolutionLists(HWND hwndDlg,int DriverId); ///////////////////////////////////////////////////////////////////////////// // CStylePage dialog CustomPlayerDialogGraphicPage::CustomPlayerDialogGraphicPage() : CPropertyPage(CustomPlayerDialogGraphicPage::IDD) , m_FullScreen(FALSE) , m_FSSA(0) { //{{AFX_DATA_INIT(CStylePage) //}}AFX_DATA_INIT } void CustomPlayerDialogGraphicPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CStylePage) //}}AFX_DATA_MAP DDX_Control(pDX, IDC_CB_WMODES, m_windowMode); DDX_Control(pDX, IDC_DRIVER_LIST, m_Driver); DDX_Control(pDX, IDC_CB_FMODE, m_FModes); DDX_Control(pDX, IDC_CB_BPPS, m_Bpps); DDX_Control(pDX, IDC_CB_RRATES, m_RRates); DDX_Control(pDX, IDC_CHECKB_FULLSCREEN, m_FullScreenBtn); DDX_Control(pDX, IDC_CB_FSSA, m_CB_FSSA); } BEGIN_MESSAGE_MAP(CustomPlayerDialogGraphicPage, CPropertyPage) //{{AFX_MSG_MAP(CStylePage) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP ON_LBN_SELCHANGE(IDC_DRIVER_LIST, OnLbnSelchangeDriverList) ON_CBN_SELCHANGE(IDC_COMBO1, OnCbnSelchangeCombo1) ON_CBN_SELCHANGE(IDC_CB_FMODE, OnCbnSelchangeCbFmode) ON_CBN_SELCHANGE(IDC_CB_BPPS, OnCbnSelchangeCbBpps) ON_CBN_SELCHANGE(IDC_CB_RRATES, OnCbnSelchangeCbRrates) ON_BN_CLICKED(IDC_CHECKB_FULLSCREEN, OnBnClickedCheckbFullscreen) ON_CBN_SELCHANGE(IDC_CB_FSSA, OnCbnSelchangeCbFssa) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CStylePage message handlers void CustomPlayerDialogGraphicPage::OnLbnSelchangeDriverList() { m_Bpps.ResetContent(); m_RRates.ResetContent(); m_windowMode.ResetContent(); m_FModes.ResetContent(); _UpdateResolutionLists(NULL, m_Driver.GetCurSel()); SetModified(); // TODO: Add your control notification handler code here } void CustomPlayerDialogGraphicPage::OnCbnSelchangeCombo1() { SetModified(); } void CustomPlayerDialogGraphicPage::OnCbnSelchangeCbFmode() { SetModified(); } void CustomPlayerDialogGraphicPage::OnCbnSelchangeCbBpps() { SetModified(); } void CustomPlayerDialogGraphicPage::OnCbnSelchangeCbRrates() { SetModified(); } void CustomPlayerDialogGraphicPage::OnBnClickedCheckbFullscreen() { vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); ewinfo->g_GoFullScreen = m_FullScreenBtn.GetCheck(); if (ewinfo->g_GoFullScreen) { if (ewinfo->g_FullScreenDriver < m_Driver.GetCount() ) { m_Driver.SetCurSel( ewinfo->g_FullScreenDriver ); } }else { if (ewinfo->g_WindowedDriver < m_Driver.GetCount() ) { m_Driver.SetCurSel( ewinfo->g_WindowedDriver ); } } SetModified(); } void CustomPlayerDialogGraphicPage::OnCbnSelchangeCbFssa() { SetModified(); } void CustomPlayerDialogGraphicPage::OnOK() { vtPlayer::Structs::xSEnginePointers* ep = GetPlayer().GetEnginePointers(); vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); ////////////////////////////////////////////////////////////////////////// CString bpp; m_Bpps.GetLBText(m_Bpps.GetCurSel(),bpp); XString oBpp(bpp); ewinfo->g_Bpp = oBpp.ToInt(); ////////////////////////////////////////////////////////////////////////// CString rr; m_RRates.GetLBText(m_RRates.GetCurSel(),rr); XString oRR(rr); ewinfo->g_RefreshRate= oRR.ToInt(); ////////////////////////////////////////////////////////////////////////// CString fssa; m_CB_FSSA.GetLBText(m_CB_FSSA.GetCurSel(),fssa); XString oFSSA(fssa); ewinfo->FSSA= oFSSA.ToInt(); ////////////////////////////////////////////////////////////////////////// ewinfo->g_GoFullScreen = m_FullScreenBtn.GetCheck(); if (ewinfo->g_GoFullScreen) { ewinfo->g_FullScreenDriver = m_Driver.GetCurSel(); }else ewinfo->g_WindowedDriver = m_Driver.GetCurSel(); ////////////////////////////////////////////////////////////////////////// CString fmode; m_FModes.GetLBText(m_FModes.GetCurSel(),fmode); XStringTokenizer tokizer(fmode, "x"); const char*tok = NULL; tok = tokizer.NextToken(tok); XString width(tok); tok = tokizer.NextToken(tok); XString height(tok); ewinfo->g_Width = width.ToInt(); ewinfo->g_Height = height.ToInt(); { CString wmode; m_windowMode.GetLBText(m_windowMode.GetCurSel(),wmode); XStringTokenizer tokizer(wmode, "x"); const char*tok = NULL; tok = tokizer.NextToken(tok); XString width(tok); tok = tokizer.NextToken(tok); XString height(tok); ewinfo->g_WidthW = width.ToInt(); ewinfo->g_HeightW = height.ToInt(); } //GetApp()->PSaveEngineWindowProperties(CUSTOM_PLAYER_CONFIG_FILE,*GetPlayer().GetEngineWindowInfo()); }<file_sep>#ifndef __P_CONFIG_H__ #define __P_CONFIG_H__ #define SESSION_MAX 9000000 #define START_MONTH 7 #define END_MONTH 12 /* ////////////////////////////////////////////////////////////////////////// #if defined (ReleaseDemo) #define SESSION_LIMIT #define MONTH_LIMIT #ifndef AUTHOR #define AUTHOR #endif #define DEMO_ONLY #endif #if defined (ReleaseFree) #define MONTH_LIMIT #define AUTHOR #endif #if defined (ReleaseRedist) #define REDIST #undef DEMO_ONLY #endif #if defined (ReleaseDongle) #define DONGLE_VERSION #undef DEMO_ONLY #endif */ #endif<file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #ifndef _TNL_GHOSTCONNECTION_H_ #define _TNL_GHOSTCONNECTION_H_ #ifndef _TNL_EVENTCONNECTION_H_ #include "tnlEventConnection.h" #endif #ifndef _TNL_RPC_H_ #include "tnlRPC.h" #endif namespace TNL { struct GhostInfo; /// GhostConnection is a subclass of EventConnection that manages the transmission /// (ghosting) and updating of NetObjects over a connection. /// /// The GhostConnection is responsible for doing scoping calculations (on the server side) /// and transmitting most-recent ghost information to the client. /// /// Ghosting is the most complex, and most powerful, part of TNL's capabilities. It /// allows the information sent to clients to be very precisely matched to what they need, so that /// no excess bandwidth is wasted. Each GhostConnection has a <b>scope object</b> that is responsible /// for determining what other NetObject instances are relevant to that connection's client. Each time /// GhostConnection sends a packet, NetObject::performScopeQuery() is called on the scope object, which /// calls GhostConnection::objectInScope() for each relevant object. /// /// Each object that is in scope, and in need of update (based on its maskbits) is given a priority /// ranking by calling that object's getUpdatePriority() method. The packet is then filled with /// updates, ordered by priority. This way the most important updates get through first, with less /// important updates being sent as space is available. /// /// There is a cap on the maximum number of ghosts that can be active through a GhostConnection at once. /// The enum GhostIdBitSize (defaults to 10) determines how many bits will be used to transmit the ID for /// each ghost, so the maximum number is 2^GhostIdBitSize or 1024. This can be easily raised; see the /// GhostConstants enum. /// /// Each object ghosted is assigned a ghost ID; the client is <b>only</b> aware of the ghost ID. This acts /// to enhance simulation security, as it becomes difficult to map objects from one connection to another, /// or to reliably identify objects from ID alone. IDs are also reassigned based on need, making it hard /// to track objects that have fallen out of scope (as any object which the player shouldn't see would). /// /// resolveGhost() is used on the client side, and resolveObjectFromGhostIndex() on the server side, to /// convert ghost IDs to object references. /// /// @see NetObject for more information on network object functionality. class GhostConnection : public EventConnection { typedef EventConnection Parent; friend class ConnectionMessageEvent; public: /// GhostRef tracks an update sent in one packet for the ghost of one NetObject. /// /// When we are notified that a pack is sent/lost, this is used to determine what /// updates need to be resent and so forth. struct GhostRef { U32 mask; ///< The mask of bits that were updated in this packet U32 ghostInfoFlags; ///< GhostInfo::Flags bitset, determes if the ghost is in a /// special processing mode (created/deleted) GhostInfo *ghost; ///< The ghost information for the object on the connection that sent /// the packet this GhostRef is attached to GhostRef *nextRef; ///< The next ghost updated in this packet GhostRef *updateChain; ///< A pointer to the GhostRef on the least previous packet that /// updated this ghost, or NULL, if no prior packet updated this ghost }; /// Notify structure attached to each packet with information about the ghost updates in the packet struct GhostPacketNotify : public EventConnection::EventPacketNotify { GhostRef *ghostList; ///< list of ghosts updated in this packet GhostPacketNotify() { ghostList = NULL; } }; protected: /// Override of EventConnection's allocNotify, to use the GhostPacketNotify structure. PacketNotify *allocNotify() { return new GhostPacketNotify; } /// Override to properly update the GhostInfo's for all ghosts that had upates in the dropped packet. void packetDropped(PacketNotify *notify); /// Override to update flags associated with the ghosts updated in this packet. void packetReceived(PacketNotify *notify); /// Performs the scoping query in order to determine if there is data to send from this GhostConnection. void prepareWritePacket(); /// Override to write ghost updates into each packet. void writePacket(BitStream *bstream, PacketNotify *notify); /// Override to read updated ghost information from the packet stream. void readPacket(BitStream *bstream); /// Override to check if there is data pending on this GhostConnection. bool isDataToTransmit(); //---------------------------------------------------------------- // ghost manager functions/code: //---------------------------------------------------------------- public: GhostInfo **mGhostArray; ///< Array of GhostInfo structures used to track all the objects ghosted by this side of the connection. /// /// For efficiency, ghosts are stored in three segments - the first segment contains GhostInfos /// that have pending updates, the second ghostrefs that need no updating, and last, free /// GhostInfos that may be reused. S32 mGhostZeroUpdateIndex; ///< Index in mGhostArray of first ghost with 0 update mask (ie, with no updates). S32 mGhostFreeIndex; ///< index in mGhostArray of first free ghost. bool mGhosting; ///< Am I currently ghosting objects over? bool mScoping; ///< Am I currently allowing objects to be scoped? U32 mGhostingSequence; ///< Sequence number describing this ghosting session. NetObject **mLocalGhosts; ///< Local ghost array for remote objects, or NULL if mGhostTo is false. GhostInfo *mGhostRefs; ///< Allocated array of ghostInfos, or NULL if mGhostFrom is false. GhostInfo **mGhostLookupTable; ///< Table indexed by object id->GhostInfo, or NULL if mGhostFrom is false. SafePtr<NetObject> mScopeObject; ///< The local NetObject that performs scoping queries to determine what /// objects to ghost to the client. void clearGhostInfo(); void deleteLocalGhosts(); bool validateGhostArray(); void freeGhostInfo(GhostInfo *); /// Notifies subclasses that the remote host is about to start ghosting objects. virtual void onStartGhosting(); /// Notifies subclasses that the server has stopped ghosting objects on this connection. virtual void onEndGhosting(); public: GhostConnection(); ~GhostConnection(); void setGhostFrom(bool ghostFrom); ///< Sets whether ghosts transmit from this side of the connection. void setGhostTo(bool ghostTo); ///< Sets whether ghosts are allowed from the other side of the connection. bool doesGhostFrom() { return mGhostArray != NULL; } ///< Does this GhostConnection ghost NetObjects to the remote host? bool doesGhostTo() { return mLocalGhosts != NULL; } ///< Does this GhostConnection receive ghosts from the remote host? /// Returns the sequence number of this ghosting session. U32 getGhostingSequence() { return mGhostingSequence; } enum GhostConstants { GhostIdBitSize = 10, ///< Size, in bits, of the integer used to transmit ghost IDs GhostLookupTableSizeShift = 10, ///< The size of the hash table used to lookup source NetObjects by remote ghost ID is 1 << GhostLookupTableSizeShift. MaxGhostCount = (1 << GhostIdBitSize), ///< Maximum number of ghosts that can be active at any one time. GhostCountBitSize = GhostIdBitSize + 1, ///< Size of the field needed to transmit the total number of ghosts. GhostLookupTableSize = (1 << GhostLookupTableSizeShift), ///< Size of the hash table used to lookup source NetObjects by remote ghost ID. GhostLookupTableMask = (GhostLookupTableSize - 1), ///< Hashing mask for table lookups. }; void setScopeObject(NetObject *object); ///< Sets the object that is queried at each packet to determine /// what NetObjects should be ghosted on this connection. NetObject *getScopeObject() { return (NetObject*)mScopeObject; }; ///< Returns the current scope object. void objectInScope(NetObject *object); ///< Indicate that the specified object is currently in scope. /// /// Method called by the scope object to indicate that the specified object is in scope. void objectLocalScopeAlways(NetObject *object); ///< The specified object should be always in scope for this connection. void objectLocalClearAlways(NetObject *object); ///< The specified object should not be always in scope for this connection. NetObject *resolveGhost(S32 id); ///< Given an object's ghost id, returns the ghost of the object (on the client side). NetObject *resolveGhostParent(S32 id); ///< Given an object's ghost id, returns the source object (on the server side). void ghostPushNonZero(GhostInfo *gi); ///< Moves the specified GhostInfo into the range of the ghost array for non-zero updateMasks. void ghostPushToZero(GhostInfo *gi); ///< Moves the specified GhostInfo into the range of the ghost array for zero updateMasks. void ghostPushZeroToFree(GhostInfo *gi); ///< Moves the specified GhostInfo into the range of the ghost array for free (unused) GhostInfos. inline void ghostPushFreeToZero(GhostInfo *info); ///< Moves the specified GhostInfo from the free area into the range of the ghost array for zero updateMasks. S32 getGhostIndex(NetObject *object); ///< Returns the client-side ghostIndex of the specified server object, or -1 if the object is not available on the client. /// Returns true if the object is available on the client. bool isGhostAvailable(NetObject *object) { return getGhostIndex(object) != -1; } void resetGhosting(); ///< Stops ghosting objects from this GhostConnection to the remote host, which causes all ghosts to be destroyed on the client. void activateGhosting(); ///< Begins ghosting objects from this GhostConnection to the remote host, starting with the GhostAlways objects. bool isGhosting() { return mGhosting; } ///< Returns true if this connection is currently ghosting objects to the remote host. void detachObject(GhostInfo *info); ///< Notifies the GhostConnection that the specified GhostInfo should no longer be scoped to the client. /// RPC from server to client before the GhostAlwaysObjects are transmitted TNL_DECLARE_RPC(rpcStartGhosting, (U32 sequence)); /// RPC from client to server sent when the client receives the rpcGhostAlwaysActivated TNL_DECLARE_RPC(rpcReadyForNormalGhosts, (U32 sequence)); /// RPC from server to client sent to notify that ghosting should stop TNL_DECLARE_RPC(rpcEndGhosting, ()); }; //---------------------------------------------------------------------------- /// Each GhostInfo structure tracks the state of a single NetObject's ghost for a single GhostConnection. struct GhostInfo { // NOTE: // if the size of this structure changes, the // NetConnection::getGhostIndex function MUST be changed // to reflect. NetObject *obj; ///< The real object on the server. U32 updateMask; ///< The current out-of-date state mask for the object for this connection. GhostConnection::GhostRef *lastUpdateChain; ///< The GhostRef for this object in the last packet it was updated in, /// or NULL if that last packet has been notified yet. GhostInfo *nextObjectRef; ///< Next GhostInfo for this object in the doubly linked list of GhostInfos across /// all connections that scope this object GhostInfo *prevObjectRef; ///< Previous GhostInfo for this object in the doubly linked list of GhostInfos across /// all connections that scope this object GhostConnection *connection; ///< The connection that owns this GhostInfo GhostInfo *nextLookupInfo; ///< Next GhostInfo in the hash table for NetObject*->GhostInfo* U32 updateSkipCount; ///< How many times this object has NOT been updated in writePacket U32 flags; ///< Current flag status of this object for this connection. F32 priority; ///< Priority for the update of this object, computed after the scoping process has run. U32 index; ///< Fixed index of the object in the mGhostRefs array for the connection, and the ghostId of the object on the client. S32 arrayIndex; ///< Position of the object in the mGhostArray for the connection, which changes as the object is pushed to zero, non-zero and free. enum Flags { InScope = BIT(0), ///< This GhostInfo's NetObject is currently in scope for this connection. ScopeLocalAlways = BIT(1), ///< This GhostInfo's NetObject is always in scope for this connection. NotYetGhosted = BIT(2), ///< This GhostInfo's NetObject has not been sent to or constructed on the remote host. Ghosting = BIT(3), ///< This GhostInfo's NetObject has been sent to the client, but the packet it was sent in hasn't been acked yet. KillGhost = BIT(4), ///< The ghost of this GhostInfo's NetObject should be destroyed ASAP. KillingGhost = BIT(5), ///< The ghost of this GhostInfo's NetObject is in the process of being destroyed. /// Flag mask - if any of these are set, the object is not yet available for ghost ID lookup. NotAvailable = (NotYetGhosted | Ghosting | KillGhost | KillingGhost), }; }; inline void GhostConnection::ghostPushNonZero(GhostInfo *info) { TNLAssert(info->arrayIndex >= mGhostZeroUpdateIndex && info->arrayIndex < mGhostFreeIndex, "Out of range arrayIndex."); TNLAssert(mGhostArray[info->arrayIndex] == info, "Invalid array object."); if(info->arrayIndex != mGhostZeroUpdateIndex) { mGhostArray[mGhostZeroUpdateIndex]->arrayIndex = info->arrayIndex; mGhostArray[info->arrayIndex] = mGhostArray[mGhostZeroUpdateIndex]; mGhostArray[mGhostZeroUpdateIndex] = info; info->arrayIndex = mGhostZeroUpdateIndex; } mGhostZeroUpdateIndex++; //TNLAssert(validateGhostArray(), "Invalid ghost array!"); } inline void GhostConnection::ghostPushToZero(GhostInfo *info) { TNLAssert(info->arrayIndex < mGhostZeroUpdateIndex, "Out of range arrayIndex."); TNLAssert(mGhostArray[info->arrayIndex] == info, "Invalid array object."); mGhostZeroUpdateIndex--; if(info->arrayIndex != mGhostZeroUpdateIndex) { mGhostArray[mGhostZeroUpdateIndex]->arrayIndex = info->arrayIndex; mGhostArray[info->arrayIndex] = mGhostArray[mGhostZeroUpdateIndex]; mGhostArray[mGhostZeroUpdateIndex] = info; info->arrayIndex = mGhostZeroUpdateIndex; } //TNLAssert(validateGhostArray(), "Invalid ghost array!"); } inline void GhostConnection::ghostPushZeroToFree(GhostInfo *info) { TNLAssert(info->arrayIndex >= mGhostZeroUpdateIndex && info->arrayIndex < mGhostFreeIndex, "Out of range arrayIndex."); TNLAssert(mGhostArray[info->arrayIndex] == info, "Invalid array object."); mGhostFreeIndex--; if(info->arrayIndex != mGhostFreeIndex) { mGhostArray[mGhostFreeIndex]->arrayIndex = info->arrayIndex; mGhostArray[info->arrayIndex] = mGhostArray[mGhostFreeIndex]; mGhostArray[mGhostFreeIndex] = info; info->arrayIndex = mGhostFreeIndex; } //TNLAssert(validateGhostArray(), "Invalid ghost array!"); } inline void GhostConnection::ghostPushFreeToZero(GhostInfo *info) { TNLAssert(info->arrayIndex >= mGhostFreeIndex, "Out of range arrayIndex."); TNLAssert(mGhostArray[info->arrayIndex] == info, "Invalid array object."); if(info->arrayIndex != mGhostFreeIndex) { mGhostArray[mGhostFreeIndex]->arrayIndex = info->arrayIndex; mGhostArray[info->arrayIndex] = mGhostArray[mGhostFreeIndex]; mGhostArray[mGhostFreeIndex] = info; info->arrayIndex = mGhostFreeIndex; } mGhostFreeIndex++; //TNLAssert(validateGhostArray(), "Invalid ghost array!"); } }; #endif <file_sep>//----------------------------------------------------------------------------------- // // Torque Network Library // Copyright (C) 2004 GarageGames.com, Inc. // For more information see http://www.opentnl.org // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // For use in products that are not compatible with the terms of the GNU // General Public License, alternative licensing options are available // from GarageGames.com. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------------------ #ifndef _TNL_PLATFORM_H_ #define _TNL_PLATFORM_H_ #ifndef _TNL_TYPES_H_ #include "tnlTypes.h" #endif namespace TNL { /// Platform specific functionality is gathered here to enable easier porting. /// /// If you are embedding TNL in a complex application, you may want to replace /// these with hooks to your own code - for instance the alerts really should /// bring up an actual message box; currently they just emit a log item. namespace Platform { /// Prints a string to the OS specific debug log. void outputDebugString(const char *string); /// Stops the program in the debugger, if it is being debugged. void debugBreak(); /// Forces the program to exit immediately. /// /// @note This is probably a bit strong for a networking library. -- BJG void forceQuit(); /// Brings up a dialog window with a message and an "OK" button void AlertOK(const char *windowTitle, const char *message); /// Brings up a dialog window with the message, and "OK" and "Cancel" buttons bool AlertOKCancel(const char *windowTitle, const char *message); /// Brings up a dialog window with the message, and "Retry" and "Cancel" buttons bool AlertRetry(const char *windowTitle, const char *message); /// Elapsed time in milliseconds. /// /// Usually since last reboot, but it varies from platform to platform. It is /// guaranteed to always increase, however, up to the limit of a U32 - about /// 7 weeks worth of time. If you are developing a server you want to run for longer /// than that, prepared to see wraparounds. U32 getRealMilliseconds(); /// Returns a high-precision time value, in a platform-specific time value S64 getHighPrecisionTimerValue(); /// Converts a high precision timer delta into milliseconds F64 getHighPrecisionMilliseconds(S64 timerDelta); /// Put the process to sleep for the specified millisecond interva. void sleep(U32 msCount); /// checks the status of the memory allocation heap bool checkHeap(); }; #define TIME_BLOCK(name,block) { S64 st = Platform::getHighPrecisionTimerValue(); {block} S64 delta = Platform::getHighPrecisionTimerValue() - st; F64 ms = Platform::getHighPrecisionMilliseconds(delta); /*logprintf("Timer: %s Elapsed: %g ms", #name, ms);*/ } #if defined (TNL_SUPPORTS_VC_INLINE_X86_ASM) || defined (TNL_SUPPORTS_MWERKS_INLINE_X86_ASM) #define TNL_DEBUGBREAK() { __asm { int 3 }; } #elif defined(TNL_SUPPORTS_GCC_INLINE_X86_ASM) #define TNL_DEBUGBREAK() { asm ( "int $3"); } #else /// Macro to do in-line debug breaks, used for asserts. Does inline assembly where appropriate #define TNL_DEBUGBREAK() Platform::debugBreak(); #endif #define TNL_CHECK_HEAP() { bool status = TNL::Platform::checkHeap(); if(!status) TNL_DEBUGBREAK(); } extern bool atob(const char *str); ///< String to boolean conversion. /// Printf into string with a buffer size. /// /// This will print into the specified string until the buffer size is reached. extern int dSprintf(char *buffer, U32 bufferSize, const char *format, ...); /// Vsprintf with buffer size argument. /// /// This will print into the specified string until the buffer size is reached. extern int dVsprintf(char *buffer, U32 bufferSize, const char *format, void *arglist); ///< compiler independent inline char dToupper(const char c) { if (c >= char('a') && c <= char('z')) return char(c + 'A' - 'a'); else return c; } ///< Converts an ASCII character to upper case. inline char dTolower(const char c) { if (c >= char('A') && c <= char('Z')) return char(c - 'A' + 'a'); else return c; } ///< Converts an ASCII character to lower case. #define QSORT_CALLBACK FN_CDECL }; #include <string.h> #include <stdlib.h> #if defined (__GNUC__) int stricmp(const char *str1, const char *str2); int strnicmp(const char *str1, const char *str2, unsigned int len); #endif #endif <file_sep>#ifndef __P_CONSTANTS_H__ #define __P_CONSTANTS_H__ #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorJSetBallDecl(); CKERROR CreateJSetBallProto(CKBehaviorPrototype **pproto); int JSetBall(const CKBehaviorContext& behcontext); CKERROR JSetBallCB(const CKBehaviorContext& behcontext); enum bbInputs { bI_ObjectB, bI_Anchor, bI_AnchorRef, bbI_SwingAxis, bbI_PMode, bbI_PDistance, bbI_Collision, bbI_SwingLimit, bbI_TwistHighLimit, bbI_TwistLowLimit, bbI_SwingSpring, bbI_TwistSpring, bbI_JointSpring }; //************************************ // Method: FillBehaviorJSetBallDecl // FullName: FillBehaviorJSetBallDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorJSetBallDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJBall"); od->SetCategory("Physic/Joints"); od->SetDescription("Sets/modifies a ball joint."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x2df921e4,0x20295f52)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJSetBallProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreateJSetBallProto // FullName: CreateJSetBallProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreateJSetBallProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJBall"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJBall <br> PJBall is categorized in \ref Joints <br> <br>See <A HREF="pJBall.cmo">pJBall.cmo</A>. <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Creates or modifies a sphere joint. <br> <br> DOFs removed: 3<br> DOFs remaining: 3<br> <br> \image html sphericalJoint.png A spherical joint is the simplest kind of joint. It constrains two points on two different bodies from coinciding. This point, located in world space, is the only parameter that has to be specified (the other parameters are optional). Specifying the anchor point (point that is forced to coincide) in world space guarantees that the point in the local space of each body will coincide when the point is transformed back from local into world space. By attaching a series of spherical joints and bodies, chains/ropes can be created. Another example for a common spherical joint is a person's shoulder, which is quite limited in its range of motion. <h3>Technical Information</h3> \image html PJBall.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Body B: </SPAN>The second body. Leave blank to create a joint constraint with the world. <BR> <BR> <SPAN CLASS="pin">Anchor:</SPAN>A point in world space coordinates. See pJointBall::setAnchor(). <BR> <SPAN CLASS="pin">Anchor Reference: </SPAN>A helper entity to transform a local anchor into the world space. <BR> <SPAN CLASS="pin">Swing Limt Axis: </SPAN>Limit axis defined in the joint space of body a. See pJointBall::setSwingLimitAxis(). <BR> <SPAN CLASS="pin">Projection Mode: </SPAN>Joint projection mode. See pJointBall::setProjectionMode() and #ProjectionMode. <BR> <BR> <SPAN CLASS="pin">Projection Distance: </SPAN>If any joint projection is used, it is also necessary to set projectionDistance to a small value greater than zero. When the joint error is larger than projectionDistance the SDK will change it so that the joint error is equal to projectionDistance. Setting projectionDistance too small will introduce unwanted oscillations into the simulation. <br> <SPAN CLASS="pin">Collision :</SPAN>Enable Collision. See pJointRevolute::enableCollision(). <BR> <br> <SPAN CLASS="pin">Swing Limit: </SPAN>Swing limit of the twist axis. <BR> <br> <SPAN CLASS="pin">Twist High Limit: </SPAN>Higher rotation limit around twist axis. See pJointBall::setTwistHighLimit(). <BR> <br> <SPAN CLASS="pin">Twist Low Limit: </SPAN>Lower rotation limit around twist axis. See pJointBall::setTwistLowLimit(). <BR> <br> <SPAN CLASS="pin">Swing Spring: </SPAN>.The spring that works against swinging. See pJointBall::setSwingSpring(). <BR> <SPAN CLASS="pin">Twist Spring: </SPAN>.The spring that works against twisting. See pJointBall::setTwistSpring(). <BR> <SPAN CLASS="pin">Joint Spring: </SPAN>.The spring that lets the joint get pulled apart. See pJointBall::setJointSpring(). <BR> <BR> <BR> <SPAN CLASS="setting">Swing Limit: </SPAN>Enables parameter input for swing limit. <BR> <SPAN CLASS="setting">Twist High Limit: </SPAN>Enables parameter input for high twist limit. <BR> <SPAN CLASS="setting">Twist Low Limit: </SPAN>Enables parameter input for low twist limit. <BR> <SPAN CLASS="setting">Swing Spring: </SPAN>.Enables parameter input for swing spring. <BR> <SPAN CLASS="setting">Twist Spring: </SPAN>.Enables parameter input for twist spring. <BR> <SPAN CLASS="setting">Joint Spring: </SPAN>.Enables parameter input for joint spring. <BR> <h4>Spherical Joint Limits</h4> Spherical joints allow limits that can approximate the physical limits of motion on a human arm. It is possible to specify a cone which limits how far the arm can swing from a given axis. In addition, a twist limit can be specified which controls how much the arm is allowed to twist around its own axis. \image html sphericalLimits.png NOTE: There are similar restrictions on the twist limits for spherical joints as there are for revolute joints. <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>VSL : Creation </h3><br> <SPAN CLASS="NiceCode"> \include PJSetBall.vsl </SPAN> <br> <h3>VSL : Limit Modification </h3><br> <SPAN CLASS="NiceCode"> \include PJSetBallLimits.vsl </SPAN> <br> <br> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createJointBall().<br> */ proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->SetBehaviorCallbackFct( JSetBallCB ); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->DeclareInParameter("Anchor",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY,"0.0f"); proto->DeclareInParameter("Limit Swing Axis",CKPGUID_VECTOR,"0.0f"); proto->DeclareInParameter("Projection Mode",VTE_JOINT_PROJECTION_MODE,"0"); proto->DeclareInParameter("Projection Distance",CKPGUID_FLOAT,"0"); proto->DeclareInParameter("Collision",CKPGUID_BOOL,"TRUE"); proto->DeclareInParameter("Swing Limit",VTS_JLIMIT,""); proto->DeclareInParameter("Twist High Limit",VTS_JLIMIT); proto->DeclareInParameter("Twist Low Limit",VTS_JLIMIT); proto->DeclareInParameter("Swing Spring",VTS_JOINT_SPRING); proto->DeclareInParameter("Twist Spring",VTS_JOINT_SPRING); proto->DeclareInParameter("Joint Spring",VTS_JOINT_SPRING); proto->DeclareSetting("Swing Limit",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Twist Limit",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Swing Spring",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Twist Spring",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Joint Spring",CKPGUID_BOOL,"FALSE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(JSetBall); *pproto = proto; return CK_OK; } //************************************ // Method: JSetBall // FullName: JSetBall // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int JSetBall(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Spherical)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA && ! worldB ) { return 0; } if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); //anchor : VxVector anchor = GetInputParameterValue<VxVector>(beh,bI_Anchor); VxVector anchorOut = anchor; CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); if (anchorReference) { anchorReference->Transform(&anchorOut,&anchor); } //swing axis VxVector swingAxis = GetInputParameterValue<VxVector>(beh,bbI_SwingAxis); ProjectionMode mode =GetInputParameterValue<ProjectionMode>(beh,bbI_PMode); float distance = GetInputParameterValue<float>(beh,bbI_PDistance); int coll = GetInputParameterValue<int>(beh,bbI_Collision); ////////////////////////////////////////////////////////////////////////// //swing limit : pJointLimit sLimit; DWORD swingLimit; beh->GetLocalParameterValue(0,&swingLimit); if (swingLimit) { CKParameterIn *par = beh->GetInputParameter(bbI_SwingLimit); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { sLimit = pFactory::Instance()->createLimitFromParameter(rPar); } } } ////////////////////////////////////////////////////////////////////////// //twist limit high : pJointLimit tLimitH; DWORD twistLimit; beh->GetLocalParameterValue(1,&twistLimit); if (twistLimit) { CKParameterIn *par = beh->GetInputParameter(bbI_TwistHighLimit); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { tLimitH = pFactory::Instance()->createLimitFromParameter(rPar); } } } ////////////////////////////////////////////////////////////////////////// //twist limit low : pJointLimit tLimitL; if (twistLimit) { CKParameterIn *par = beh->GetInputParameter(bbI_TwistLowLimit); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { tLimitL = pFactory::Instance()->createLimitFromParameter(rPar); } } } ////////////////////////////////////////////////////////////////////////// DWORD swingSpring; pSpring sSpring; beh->GetLocalParameterValue(2,&swingSpring); if (swingSpring) { CKParameterIn *par = beh->GetInputParameter(bbI_SwingSpring); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { sSpring = pFactory::Instance()->createSpringFromParameter(rPar); } } } ////////////////////////////////////////////////////////////////////////// DWORD twistSpring; pSpring tSpring; beh->GetLocalParameterValue(3,&twistSpring); if (twistSpring) { CKParameterIn *par = beh->GetInputParameter(bbI_TwistSpring); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { tSpring= pFactory::Instance()->createSpringFromParameter(rPar); } } } ////////////////////////////////////////////////////////////////////////// // DWORD jointSpring; pSpring jSpring; beh->GetLocalParameterValue(4,&jointSpring); if (jointSpring) { CKParameterIn *par = beh->GetInputParameter(bbI_JointSpring); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { jSpring = pFactory::Instance()->createSpringFromParameter(rPar); } } } pJointBall *joint = static_cast<pJointBall*>(worldA->getJoint(target,targetB,JT_Spherical)); if(bodyA || bodyB) { ////////////////////////////////////////////////////////////////////////// //joint create ? if (!joint) { joint = static_cast<pJointBall*>(pFactory::Instance()->createBallJoint(target,targetB,anchorOut,swingAxis)); } ////////////////////////////////////////////////////////////////////////// Modification : if (joint) { joint->setAnchor(anchorOut); joint->setSwingLimitAxis(swingAxis); joint->setProjectionMode(mode); joint->setProjectionDistance(distance); joint->enableCollision(coll); ////////////////////////////////////////////////////////////////////////// if(swingLimit) { joint->setSwingLimit(sLimit); } joint->enableFlag(NX_SJF_SWING_LIMIT_ENABLED,swingLimit); ////////////////////////////////////////////////////////////////////////// if (twistLimit) { joint->setTwistHighLimit(tLimitH); joint->setTwistLowLimit(tLimitL); } joint->enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,twistLimit); ////////////////////////////////////////////////////////////////////////// if (swingSpring) { joint->setSwingSpring(sSpring); } joint->enableFlag(NX_SJF_SWING_SPRING_ENABLED,swingSpring); ////////////////////////////////////////////////////////////////////////// if (twistSpring) { joint->setTwistSpring(tSpring); } joint->enableFlag(NX_SJF_TWIST_SPRING_ENABLED,twistSpring); ////////////////////////////////////////////////////////////////////////// if (jointSpring) { joint->setJointSpring(jSpring); } joint->enableFlag(NX_SJF_JOINT_SPRING_ENABLED,jointSpring); } } beh->ActivateOutput(0); } return 0; } //************************************ // Method: JSetBallCB // FullName: JSetBallCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR JSetBallCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD swingLimit; beh->GetLocalParameterValue(0,&swingLimit); beh->EnableInputParameter(bbI_SwingLimit,swingLimit); DWORD twistLimit; beh->GetLocalParameterValue(1,&twistLimit); beh->EnableInputParameter(bbI_TwistHighLimit,twistLimit); beh->EnableInputParameter(bbI_TwistLowLimit,twistLimit); DWORD springSwing; beh->GetLocalParameterValue(2,&springSwing); beh->EnableInputParameter(bbI_SwingSpring,springSwing); DWORD twistSwing; beh->GetLocalParameterValue(3,&twistSwing); beh->EnableInputParameter(bbI_TwistSpring,twistSwing); DWORD jointSwing; beh->GetLocalParameterValue(4,&jointSwing); beh->EnableInputParameter(bbI_JointSpring,jointSwing); break; } } return CKBR_OK; }<file_sep>#ifndef __xDistributedObject_h #define __xDistributedObject_h #include "xNetObject.h" #include "xNetTypes.h" class xDistributed3DObject; class xDistributedClass; class xDistributedProperty; class xDistributedObject : public xNetObject { typedef xNetObject Parent; public: xDistributedObject(); virtual ~xDistributedObject(); enum MaskBits { InitialMask = (1 << 0), ///< This mask bit is never set explicitly, so it can be used for initialization data. }; int getEntityID() const { return m_EntityID; } void setEntityID(int val) { m_EntityID = val; } int getGhostDebugID() const { return m_GhostDebugID; } void setGhostDebugID(int val) { m_GhostDebugID = val; } void getOwnership(); xDistributedClass * getDistributedClass() { return m_DistributedClass; } void setDistributedClass(xDistributedClass * val) { m_DistributedClass = val; } int getObjectFlags() { return m_ObjectFlags; } void setObjectFlags(int val) { m_ObjectFlags = val; } int getServerID() const { return m_ServerID; } void setServerID(int val) { m_ServerID = val; } float getCreationTime() const { return m_creationTime; } void setCreationTime(float val) { m_creationTime = val; } float getCreationTimeout() const { return m_creationTimeout; } void setCreationTimeout(float val) { m_creationTimeout = val; } int getInterfaceFlags() const { return m_InterfaceFlags; } void setInterfaceFlags(int val) { m_InterfaceFlags = val; } int& getUpdateFlags() { return m_UpdateFlags; } void setUpdateFlags(int val) { m_UpdateFlags = val; } TNL::BitSet32& getUpdateBits() { return m_UpdateBits; } void setUpdateBits(TNL::BitSet32 val) { m_UpdateBits = val; } TNL::BitSet32& getGhostUpdateBits(){ return m_GhostUpdateBits; } void setGhostUpdateBits(TNL::BitSet32 val) { m_GhostUpdateBits = val; } virtual void writeControlState(xNStream *stream); virtual void readControlState(xNStream * bstream){} virtual void initProperties(); virtual void destroy(); xDistributed3DObject *cast(xDistributedObject* _in); xDistributedPropertyArrayType *m_DistrtibutedPorperties; xDistributedPropertyArrayType * getDistributedPorperties(){ return m_DistrtibutedPorperties; } void setDistributedPorperties(xDistributedPropertyArrayType * val) { m_DistrtibutedPorperties = val; } virtual void pack(xNStream *bstream); virtual void unpack(xNStream *bstream,float sendersOneWayTime); virtual void prepare(); TNL::U32 getGhostID() const { return mGhostID; } void setGhostID(TNL::U32 val) { mGhostID = val; } int getUpdateState() const { return m_UpdateState; } void setUpdateState(int val) { m_UpdateState = val; } TNL::BitSet32& getOwnershipState() { return m_OwnershipState; } void setOwnershipState(TNL::BitSet32 val) { m_OwnershipState = val; } bool isOwner(){ return getOwnershipState().test( 1<<E_DO_OS_OWNER ); } void changeOwnership(int newUserID,int state); int getSessionID() const { return mSessionID; } void setSessionID(int val) { mSessionID = val; } //virtual void performScopeQuery(TNL::GhostConnection *connection); virtual bool onGhostAdd(TNL::GhostConnection *theConnection); virtual void onGhostAvailable(TNL::GhostConnection *theConnection); virtual xDistributedProperty *getProperty(int nativeType); virtual xDistributedProperty *getUserProperty(const char*name); int getLastUpdater() const { return mLastUpdater; } void setLastUpdater(int val) { mLastUpdater = val; } TNL::BitSet32& getObjectStateFlags() { return mObjectStateFlags; } void setObjectStateFlags(TNL::BitSet32 val) { mObjectStateFlags = val; } virtual uxString print(TNL::BitSet32 flags); virtual TNL::U32 packUpdate(TNL::GhostConnection *connection, TNL::U32 updateMask, TNL::BitStream *stream); virtual void unpackUpdate(TNL::GhostConnection *connection, TNL::BitStream *stream); protected: int m_ObjectFlags; int m_InterfaceFlags; int m_UpdateFlags; int m_UpdateState; TNL::BitSet32 m_UpdateBits; TNL::BitSet32 m_GhostUpdateBits; TNL::U32 mGhostID; int m_EntityID; int m_GhostDebugID; int m_ServerID; float m_creationTime; TNL::BitSet32 m_OwnershipState; float m_creationTimeout; xDistributedClass *m_DistributedClass; TNL::BitSet32 mObjectStateFlags; int mSessionID; int mLastUpdater; }; #endif <file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedClient.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xDistributedSession.h" #include <vtTools.h> #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorNServerIsRunningDecl(); CKERROR CreateNServerIsRunningProto(CKBehaviorPrototype **); int NServerIsRunning(const CKBehaviorContext& behcontext); CKERROR NServerIsRunningCB(const CKBehaviorContext& behcontext); #define BEH_IN_INDEX_MIN_COUNT 2 #define BEH_OUT_MIN_COUNT 3 #define BEH_OUT_MAX_COUNT 1 CKObjectDeclaration *FillBehaviorNServerIsRunningDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NServerIsRunning"); od->SetDescription("Checks for the embedded servers state"); od->SetCategory("TNL/Server"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x3d40087,0xe265210)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateNServerIsRunningProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } typedef enum BB_IT { BB_IT_IN, BB_IT_OFF, BB_IT_NEXT, }; typedef enum BB_INPAR { BB_IP_ADDRESS, BB_IP_MAXCLIENTS, }; typedef enum BB_OT { BB_O_OUT, BB_O_ERROR, }; typedef enum BB_OP { BB_OP_SERVER_ADDRESS, BB_OP_ERROR }; CKERROR CreateNServerIsRunningProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NServerIsRunning"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Yes"); proto->DeclareOutput("No"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(NServerIsRunning); proto->SetBehaviorCallbackFct(NServerIsRunningCB); *pproto = proto; return CK_OK; } int NServerIsRunning(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); using namespace vtTools::BehaviorTools; if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); xNetInterface *cin = GetNM()->GetServerNetInterface(); if (cin) { TNL::Socket *socket = &cin->getSocket(); if (socket) { if (socket->isValid()) { beh->ActivateOutput(0); return CKBR_OK; } } } beh->ActivateOutput(1); return CKBR_OK; } return CKBR_OK; } CKERROR NServerIsRunningCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { } return CKBR_OK; }<file_sep> /* Some code about firewall: This code does not work */ #include <windows.h> #include <ftp4w.h> /* Fin de fonction asynchrone/synchrone */ #define RETURN(pD,x) \ { if( (! IsBadWritePtr(pD,sizeof *pD)) && pD->File.bAsyncMode ) \ { PostMessage(pD->Msg.hParentWnd,pD->Msg.nCompletedMessage,TRUE,x); \ return FTPERR_OK; } \ else { return x; } } #define SizeOfTab(t) ( sizeof (t) / sizeof (t[0]) ) #define TN_SUCCESS 1 /* -------------------------------------- */ /* debugging info */ /* -------------------------------------- */ #define DBG_FIREWALL + #ifdef DBG_FIREWALL static void wMsgBox (char *szStr, char *szArg, int nArg) { char szDbg[256]; LPProcData pProcData; pProcData = FtpDataPtr(); if (szArg==NULL) wsprintf (szDbg, szStr, nArg); else if (nArg==11111) wsprintf (szDbg, szStr, szArg); else wsprintf (szDbg, szStr, szArg, nArg); MessageBox (pProcData->hParentWnd, szDbg, "Ftp4w", MB_OK); } /* wMsgBox */ #else # define wMsgBox(a,b,c) #endif /* DBG_FIREWALL */ /* Note: two undocumented functions are used in this code: */ /* - IntTnSend which sends a message to the remote host on */ /* socket S */ /* - IntFtpGetAnswerCode which waits for an answer from the */ /* server and returns the 3 digits code sent by the server */ int PASCAL FAR IntFtpGetAnswerCode (LPFtpData pFtpData); int PASCAL FAR IntTnSend (SOCKET s, LPSTR szString, BOOL bHighPriority, HFILE hf); /* ------------------------------------------------------------ */ /* Fonction DLL FtpFirewallLogin */ /* ------------------------------------------------------------ */ struct S_Firewall { int nType; BOOL bFWUserPwd; LPSTR szCmd; LPSTR szUserStr; }; /* struct S_Firewall */ static struct S_Firewall sFirewall[] = { { FTP4W_FWSITE, TRUE, "SITE %s", "USER %s" }, { FTP4W_FWPROXY, FALSE, "OPEN %s", "USER %s" }, { FTP4W_FWUSERWITHLOGON, TRUE, NULL, "USER %s@%s" }, { FTP4W_FWUSERNOLOGON, FALSE, NULL, "USER %s@%s" }, }; /* struct S_Firewall sFirewall */ int PASCAL FAR FtpFirewallLogin( LPSTR szFWHost, LPSTR szFWUser, LPSTR szFWPasswd, LPSTR szRemHost,LPSTR szRemUser,LPSTR szRemPasswd, int nFirewallType, HWND hParentWnd, UINT wMsg) { int Idx; int Rc; LPProcData pProcData; char szTnS[256]; /* Reads data structure */ pProcData = FtpDataPtr (); if (pProcData == NULL) return FTPERR_NOTINITIALIZED; /* The message to be sent in async mode */ pProcData->Msg.nCompletedMessage = wMsg; pProcData->Msg.hParentWnd = hParentWnd; /* ýcheck parameters */ if (szFWHost==NULL || szRemHost==NULL) return FTPERR_INVALIDPARAMETER; /* Get FW structure */ for (Idx=0 ; Idx<SizeOfTab(sFirewall) && sFirewall[Idx].nType!=nFirewallType; Idx++ ); if (Idx >= SizeOfTab(sFirewall)) return FTPERR_INVALIDPARAMETER; wMsgBox ("Index DB sFirewall: %d", NULL, Idx); /* open connection with firewall */ Rc = FtpOpenConnection (szFWHost); wMsgBox ("Retour FtpOpenConnection: %d", NULL, Rc); if (Rc==FTPERR_CANTCONNECT) Rc=FTPERR_FWCANTCONNECT; if (Rc==FTPERR_CONNECTREJECTED) Rc=FTPERR_FWCONNECTREJECTED; if (Rc!=FTPERR_OK) RETURN (pProcData, Rc); if (sFirewall[Idx].bFWUserPwd) { if (Rc==FTPERR_OK && szFWUser!=NULL) Rc =FtpSendUserName(szFWUser); if (Rc==FTPERR_ENTERPASSWORD && szFWPasswd!=NULL) Rc = FtpSendPasswd (szFWPasswd); if (Rc==FTPERR_LOGINREFUSED) Rc=FTPERR_FWLOGINREFUSED; if (Rc!=FTPERR_OK) RETURN (pProcData, Rc); wMsgBox ("Retour Firewall LOGON: %d", NULL, Rc); } /* Log on fiirewall */ /* Connection with the remote destination */ if (sFirewall[Idx].szCmd!=NULL) { wsprintf (szTnS, sFirewall[Idx].szCmd, szRemHost); Rc = IntTnSend (pProcData->ftp.ctrl_socket, szTnS, FALSE, pProcData->ftp.hLogFile); if (Rc!=TN_SUCCESS) RETURN (pProcData, FTPERR_SENDREFUSED) if ( IntFtpGetAnswerCode (& pProcData->ftp)/100 != 2 ) RETURN (pProcData, FTPERR_CANTCONNECT); } /* szCmd pas NULL -> SITE ou PROXY */ /* Authentification */ wsprintf (szTnS, sFirewall[Idx].szUserStr, szRemUser, szRemHost); Rc = IntTnSend (pProcData->ftp.ctrl_socket, szTnS, FALSE, pProcData->ftp.hLogFile); if (Rc!=TN_SUCCESS) RETURN (pProcData, FTPERR_SENDREFUSED) Rc = IntFtpGetAnswerCode (& pProcData->ftp); wMsgBox ("Retour UserStr FWUSER: %d", NULL, Rc); /* analyses returned message */ switch (Rc) { case 230 : RETURN (pProcData, FTPERR_OK); break; case 331 : Rc = FtpSendPasswd (szRemPasswd); wMsgBox ("Retour UserStr PASSWD: %d", NULL, Rc); RETURN (pProcData, Rc); break; default : RETURN (pProcData, FTPERR_CANTCONNECT); break; } /* User */ } /* FtpFirewallLogin */ <file_sep>/******************************************************************** created: 2009/02/17 created: 17:2:2009 8:14 filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\include\core\Common\vtParameterSubItemIdentifiers_Joints.h file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\include\core\Common file base: vtParameterSubItemIdentifiers_Joints file ext: h author: <NAME> purpose: Joint parameter items for custom structures. *********************************************************************/ #ifndef __VTPARAMETERSUBITEMIDENTIFIERS_JOINTS_H__ #define __VTPARAMETERSUBITEMIDENTIFIERS_JOINTS_H__ enum PS_JPOINT_ON_LINE_MEMBERS { PS_JPOL_BODY_B, PS_JPOL_ANCHOR, PS_JPOL_ANCHOR_REF, PS_JPOL_AXIS, PS_JPOL_AXIS_REF, PS_JPOL_COLLISION, PS_JPOL_MAX_FORCE, PS_JPOL_MAX_TORQUE, }; enum PS_JPOINT_IN_PLANE_MEMBERS { PS_JPIP_BODY_B, PS_JPIP_ANCHOR, PS_JPIP_ANCHOR_REF, PS_JPIP_AXIS, PS_JPIP_AXIS_REF, PS_JPIP_COLLISION, PS_JPIP_MAX_FORCE, PS_JPIP_MAX_TORQUE, }; enum PS_JREVOLUTE { PS_JREVOLUTE_BODY_B, PS_JREVOLUTE_ANCHOR, PS_JREVOLUTE_ANCHOR_REF, PS_JREVOLUTE_AXIS, PS_JREVOLUTE_AXIS_REF, PS_JREVOLUTE_COLLISION, PS_JREVOLUTE_PROJ_MODE, PS_JREVOLUTE_PROJ_DISTANCE, PS_JREVOLUTE_PROJ_ANGLE, PS_JREVOLUTE_SPRING, PS_JREVOLUTE_LIMIT_HIGH, PS_JREVOLUTE_LIMIT_LOW, PS_JREVOLUTE_MOTOR, PS_JREVOLUTE_MAX_FORCE, PS_JREVOLUTE_MAX_TORQUE, }; enum PS_JCYLINDRICAL_MEMBERS { PS_JCYLINDRICAL_BODY_B, PS_JCYLINDRICAL_ANCHOR, PS_JCYLINDRICAL_ANCHOR_REF, PS_JCYLINDRICAL_AXIS, PS_JCYLINDRICAL_AXIS_REF, PS_JCYLINDRICAL_COLLISION, PS_JCYLINDRICAL_MAX_FORCE, PS_JCYLINDRICAL_MAX_TORQUE, }; enum PS_JPRISMATIC_MEMBERS { PS_JPRISMATIC_BODY_B, PS_JPRISMATIC_ANCHOR, PS_JPRISMATIC_ANCHOR_REF, PS_JPRISMATIC_AXIS, PS_JPRISMATIC_AXIS_REF, PS_JPRISMATIC_COLLISION, PS_JPRISMATIC_MAX_FORCE, PS_JPRISMATIC_MAX_TORQUE, }; enum PS_JBALL_MEMBERS { PS_JBALL_BODY_B, PS_JBALL_ANCHOR, PS_JBALL_ANCHOR_REF, PS_JBALL_GLOBAL_AXIS, PS_JBALL_GLOBAL_AXIS_REF, PS_JBALL_LIMIT_SWING_AXIS, PS_JBALL_PROJ_MODE, PS_JBALL_PROJ_DISTANCE, PS_JBALL_COLLISION, PS_JBALL_SWING_LIMIT, PS_JBALL_TWIST_HIGH, PS_JBALL_TWIST_LOW, PS_JBALL_SWING_SPRING, PS_JBALL_TWIST_SPRING, PS_JBALL_JOINT_SPRING, PS_JBALL_MAX_FORCE, PS_JBALL_MAX_TORQUE, }; enum PS_JFIXED_MEMBERS { PS_JFIXED_BODY_B, PS_JFIXED_MAX_FORCE, PS_JFIXED_MAX_TORQUE, }; enum PS_JDISTANCE_MEMBERS { PS_JDISTANCE_BODY_B, PS_JDISTANCE_LOCAL_ANCHOR_A_POS, PS_JDISTANCE_LOCAL_ANCHOR_A_REF, PS_JDISTANCE_LOCAL_ANCHOR_B_POS, PS_JDISTANCE_LOCAL_ANCHOR_B_REF, PS_JDISTANCE_COLL, PS_JDISTANCE_MIN_DISTANCE, PS_JDISTANCE_MAX_DISTANCE, PS_JDISTANCE_SPRING, PS_JDISTANCE_MAX_FORCE, PS_JDISTANCE_MAX_TORQUE, }; enum PS_JLIMIT_PLANE_MEMBERS { PS_JLP_BODY_B_REF, PS_JLP_JOINT_TYPE, PS_JLP_RESTITUTION, PS_JLP_IS_ON_BODY_B, PS_JLP_LIMIT_POINT, PS_JLP_LIMIT_POINT_REF, PS_JLP_NORMAL, PS_JLP_NORMAL_REF, PS_JLP_PT_IN_PLANE, PS_JLP_PT_IN_PLANE_REF, }; enum PS_D6_AXIS_ITEM { PS_D6_AXIS_ITEM_MODE, PS_D6_AXIS_ITEM_LIMIT, }; enum PS_D6 { PS_JD6_BODY_B, PS_JD6_ANCHOR, PS_JD6_ANCHOR_REF, PS_JD6_AXIS, PS_JD6_AXIS_REF, PS_JD6_AXIS_MASK, PS_JD6_X, PS_JD6_Y, PS_JD6_Z, PS_JD6_TWIST_SWING1, PS_JD6_TWIST_SWING2, PS_JD6_TWIST_LOW, PS_JD6_TWIST_HIGH, }; #endif<file_sep>/* * Tcp4u v 3.31 Creation 10/07/1997 Last Revision 16/10/1997 3.11 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: udp4u.h * Purpose: main functions for udp protocol management * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #ifndef UDP4UX_API #ifndef _WINSOCKAPI_ /* winsock.h has not been loaded -> unix */ # include <sys/types.h> # include <netinet/in.h> #endif #ifdef __cplusplus extern "C" { /* Assume C declarations for C++ */ #endif /* __cplusplus */ struct sUdpData { SOCKET UdpSock; /* Socket descriptor */ struct sockaddr_in saSendAddr; /* destination */ struct sockaddr_in saRecvAddr; /* last received frame header */ struct in_addr saFilter; /* Fileter en reception */ BOOL bSemiConnected; /* received only from SendAddr */ }; /* struct sUdpData */ typedef struct sUdpData UDPSOCK; typedef UDPSOCK far * LPUDPSOCK; /* different modes */ #define UDP4U_CLIENT 45 #define UDP4U_SERVER 56 int API4U UdpInit (LPUDPSOCK far *pUdp, LPCSTR szHost, unsigned short uRemotePort, unsigned short uLocalPort); int API4U UdpCleanup (LPUDPSOCK Udp); int API4U UdpSend (LPUDPSOCK Udp, LPCSTR sData, int nDataSize, BOOL bHighPriority, HFILE hLogFile); int API4U UdpRecv (LPUDPSOCK pUdp, LPSTR sData, int nDataSize, unsigned uTimeOut, HFILE hLogFile); int API4U UdpBind (LPUDPSOCK pUdp, BOOL bFilter, int nMode); unsigned short API4U Udp4uServiceToPort (LPCSTR szService); #ifdef __cplusplus } /* End of extern "C" */ #endif /* ifdef __cplusplus */ #define UDP4UX_API loaded #endif /* ifndef UDP4UX_API */ <file_sep>#include "precomp.h" #include "vtPrecomp.h" #include "vtNetAll.h" #include "xNetInterface.h" #include "tnlRandom.h" #include "tnlSymmetricCipher.h" #include "tnlAsymmetricKey.h" #include <pch.h> #include <vtNetAll.h> #include "xLogger.h" class vtLogConsumer : public xLogConsumer { public: void logString(const char *string) { XString newLog(string); if (GetNM()->GetLastLogEntry().Compare(newLog)) { if ( string && strlen(string) < 255) { GetNM()->SetLastLogEntry(string); ctx()->OutputToConsoleEx(newLog.Str()); } //printf("%s\n", string); } } }gVTLogger; class DedicatedServerLogConsumer : public TNL::LogConsumer { public: void logString(const char *string) { gVTLogger.logString(string); /* XString newLog(string); if (GetNM()->GetLastLogEntry().Compare(newLog)) { if ( string && strlen(string) < 255) { GetNM()->SetLastLogEntry(string); ctx()->OutputToConsoleEx(newLog.Str()); } //printf("%s\n", string); } */ } } gDedicatedServerLogConsumer; void vtNetworkManager::initLogger() { xLogger::GetInstance()->addLogItem(E_LI_SESSION); //xLogger::GetInstance()->enableLoggingLevel(E_LI_SESSION,ELOGINFO,1); //xLogger::GetInstance()->enableLoggingLevel(E_LI_SESSION,ELOGTRACE,1); xLogger::GetInstance()->addLogItem(E_LI_CLIENT); xLogger::GetInstance()->addLogItem(E_LI_3DOBJECT); xLogger::GetInstance()->addLogItem(E_LI_2DOBJECT); xLogger::GetInstance()->addLogItem(E_LI_DISTRIBUTED_BASE_OBJECT); xLogger::GetInstance()->addLogItem(E_LI_DISTRIBUTED_CLASS_DESCRIPTORS); xLogger::GetInstance()->addLogItem(E_LI_MESSAGES); xLogger::GetInstance()->addLogItem(E_LI_ARRAY_MESSAGES); xLogger::GetInstance()->addLogItem(E_LI_CONNECTION); xLogger::GetInstance()->addLogItem(E_LI_NET_INTERFACE); xLogger::GetInstance()->addLogItem(E_LI_GHOSTING); xLogger::GetInstance()->addLogItem(E_LI_STATISTICS); xLogger::GetInstance()->addLogItem(E_LI_BUILDINGBLOCKS); xLogger::GetInstance()->addLogItem(E_LI_VSL); xLogger::GetInstance()->addLogItem(E_LI_CPP); xLogger::GetInstance()->addLogItem(E_LI_ASSERTS); xLogger::GetInstance()->addLogItem(E_LI_PREDICTION); xLogger::GetInstance()->addLogItem(E_LI_SERVER_MESSAGES); xLogger::GetInstance()->addItemDescription("Session"); xLogger::GetInstance()->addItemDescription("Client"); xLogger::GetInstance()->addItemDescription("3dObject"); xLogger::GetInstance()->addItemDescription("2dObject"); xLogger::GetInstance()->addItemDescription("DistBase Object"); xLogger::GetInstance()->addItemDescription("DistClassDescr"); xLogger::GetInstance()->addItemDescription("Messages"); xLogger::GetInstance()->addItemDescription("ArrayMessages"); xLogger::GetInstance()->addItemDescription("Connection"); xLogger::GetInstance()->addItemDescription("NetInterface"); xLogger::GetInstance()->addItemDescription("Ghosting"); xLogger::GetInstance()->addItemDescription("Stats"); xLogger::GetInstance()->addItemDescription("BB"); xLogger::GetInstance()->addItemDescription("VSL"); xLogger::GetInstance()->addItemDescription("CPP"); xLogger::GetInstance()->addItemDescription("Asserts"); xLogger::GetInstance()->addItemDescription("Prediction"); xLogger::GetInstance()->addItemDescription("ServerMsg"); }<file_sep>#ifndef __XMATH_STREAM_H__ #define __XMATH_STREAM_H__ #ifndef _XNET_TYPES_H_ #include "xNetTypes.h" #endif #ifndef _XPOINT_H_ #include "xPoint.h" #endif #ifndef _XQUAT_H_ #include "xQuat.h" #endif namespace xMath { namespace stream { inline bool mathRead(TNL::BitStream& stream, Point2F* p) { bool success = stream.read(&p->x); success &= stream.read(&p->y); return success; } inline bool mathRead(TNL::BitStream& stream, Point3F* p) { bool success = stream.read(&p->x); success &= stream.read(&p->y); success &= stream.read(&p->z); return success; } inline bool mathRead(TNL::BitStream& stream, Point4F* p) { bool success = stream.read(&p->x); success &= stream.read(&p->y); success &= stream.read(&p->z); success &= stream.read(&p->w); return success; } inline bool mathRead(TNL::BitStream& stream, Point3D* p) { bool success = stream.read(&p->x); success &= stream.read(&p->y); success &= stream.read(&p->z); return success; } /* inline bool mathRead(TNL::BitStream& stream, PlaneF* p) { bool success = stream.read(&p->x); success &= stream.read(&p->y); success &= stream.read(&p->z); success &= stream.read(&p->d); return success; } inline bool mathRead(TNL::BitStream& stream, Box3F* b) { bool success = mathRead(stream, &b->min); success &= mathRead(stream, &b->max); return success; } inline bool mathRead(TNL::BitStream& stream, SphereF* s) { bool success = mathRead(stream, &s->center); success &= stream.read(&s->radius); return success; } /*inline bool mathRead(TNL::BitStream& stream, RectI* r) { bool success = mathRead(stream, &r->point); success &= mathRead(stream, &r->extent); return success; } inline bool mathRead(TNL::BitStream& stream, RectF* r) { bool success = mathRead(stream, &r->point); success &= mathRead(stream, &r->extent); return success; } inline bool mathRead(TNL::BitStream& stream, MatrixF* m) { bool success = true; F32* pm = *m; for (U32 i = 0; i < 16; i++) success &= stream.read(&pm[i]); return success; } */ inline bool mathRead(TNL::BitStream& stream, QuatF* q) { bool success = stream.read(&q->x); success &= stream.read(&q->y); success &= stream.read(&q->z); success &= stream.read(&q->w); return success; } /************************************************************************/ /* */ /************************************************************************/ inline bool mathWrite(TNL::BitStream& stream, const Point2I& p) { bool success = stream.write(p.x); success &= stream.write(p.y); return success; } inline bool mathWrite(TNL::BitStream& stream, const Point3I& p) { bool success = stream.write(p.x); success &= stream.write(p.y); success &= stream.write(p.z); return success; } inline bool mathWrite(TNL::BitStream& stream, const Point2F& p) { bool success = stream.write(p.x); success &= stream.write(p.y); return success; } inline bool mathWrite(TNL::BitStream& stream, const Point3F& p) { bool success = stream.write(p.x); success &= stream.write(p.y); success &= stream.write(p.z); return success; } inline bool mathWrite(TNL::BitStream& stream, const Point4F& p) { bool success = stream.write(p.x); success &= stream.write(p.y); success &= stream.write(p.z); success &= stream.write(p.w); return success; } inline bool mathWrite(TNL::BitStream& stream, const Point3D& p) { bool success = stream.write(p.x); success &= stream.write(p.y); success &= stream.write(p.z); return success; } /* inline bool mathWrite(TNL::BitStream& stream, const PlaneF& p) { bool success = stream.write(p.x); success &= stream.write(p.y); success &= stream.write(p.z); success &= stream.write(p.d); return success; } inline bool mathWrite(TNL::BitStream& stream, const Box3F& b) { bool success = mathWrite(stream, b.min); success &= mathWrite(stream, b.max); return success; } inline bool mathWrite(TNL::BitStream& stream, const SphereF& s) { bool success = mathWrite(stream, s.center); success &= stream.write(s.radius); return success; } inline bool mathWrite(TNL::BitStream& stream, const MatrixF& m) { bool success = true; const F32* pm = m; for (U32 i = 0; i < 16; i++) success &= stream.write(pm[i]); return success; } */ inline bool mathWrite(TNL::BitStream& stream, const QuatF& q) { bool success = stream.write(q.x); success &= stream.write(q.y); success &= stream.write(q.z); success &= stream.write(q.w); return success; } } } #endif<file_sep>#ifndef NX_INTERFACE_H #define NX_INTERFACE_H /*----------------------------------------------------------------------------*\ | | Public Interface to Ageia PhysX Technology | | www.ageia.com | \*----------------------------------------------------------------------------*/ enum NxInterfaceType { NX_INTERFACE_STATS, NX_INTERFACE_LAST }; class NxInterface { public: virtual int getVersionNumber(void) const = 0; virtual NxInterfaceType getInterfaceType(void) const = 0; protected: virtual ~NxInterface(){}; }; #endif //AGCOPYRIGHTBEGIN /////////////////////////////////////////////////////////////////////////// // Copyright (c) 2005 AGEIA Technologies. // All rights reserved. www.ageia.com /////////////////////////////////////////////////////////////////////////// //AGCOPYRIGHTEND <file_sep>#include <StdAfx.h> #include "pCommon.h" #include "IParameter.h" #include "pVehicleAll.h" #include <xDebugTools.h> CKObjectDeclaration *FillBehaviorPVSetMotorValuesDecl(); CKERROR CreatePVSetMotorValuesProto(CKBehaviorPrototype **pproto); int PVSetMotorValues(const CKBehaviorContext& behcontext); CKERROR PVSetMotorValuesCB(const CKBehaviorContext& behcontext); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; enum bInputs { I_XML, I_Flags, I_Clutch, I_maxRPM, I_minRPM, I_maxTorque, I_intertia, I_engineFriction, I_breakCoeff, I_GroundForceFeedBackScale, I_tList, }; #define BB_SSTART 0 BBParameter pInMap5[] = { BB_SPIN(I_XML,VTE_XML_VMOTOR_SETTINGS,"XML Link","None"), BB_SPIN(I_Flags,VTF_VEHICLE_ENGINE_FLAGS,"Flags","None"), BB_SPIN(I_Clutch,CKPGUID_FLOAT,"Clutch","None"), BB_SPIN(I_maxRPM,CKPGUID_FLOAT,"Maximum RPM","None"), BB_SPIN(I_minRPM,CKPGUID_FLOAT,"Minimum RPM","None"), BB_SPIN(I_maxTorque,CKPGUID_FLOAT,"Maximum Torque","None"), BB_SPIN(I_intertia,CKPGUID_FLOAT,"Inertia","None"), BB_SPIN(I_engineFriction,CKPGUID_FLOAT,"Friction","1.0f"), BB_SPIN(I_breakCoeff,CKPGUID_FLOAT,"Break Factor","0.0f"), BB_SPIN(I_GroundForceFeedBackScale,CKPGUID_FLOAT,"Ground Force Scale","0.0f"), BB_SPIN(I_tList,VTS_VMOTOR_TVALUES,"Torque per RPM","None"), }; #define gPIMAP pInMap5 CKERROR PVSetMotorValuesCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORLOAD: { BB_LOAD_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PIMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PIMAP(gPIMAP,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PIMAP(gPIMAP,BB_SSTART); break; } } return CKBR_OK; } //************************************ // Method: FillBehaviorPVSetMotorValuesDecl // FullName: FillBehaviorPVSetMotorValuesDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration*FillBehaviorPVSetMotorValuesDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVMotor"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Modifies motor parameters of a vehicle controller"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x7b044c81,0xde9489a)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVSetMotorValuesProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePVSetMotorValuesProto // FullName: CreatePVSetMotorValuesProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePVSetMotorValuesProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVMotor"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); //BB_EVALUATE_PINS(gPIMAP) BB_EVALUATE_SETTINGS(gPIMAP); /*! PVMotor PVSetMotorValues is categorized in \ref Vehicle <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Modifies various physical parameters.<br> <h3>Technical Information</h3> \image html PVMotor.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pin">Collisions Group: </SPAN>Which collision group this body is part of.See pRigidBody::setCollisionsGroup(). <BR> <SPAN CLASS="pin">Kinematic Object: </SPAN>The kinematic state. See pRigidBody::setKinematic(). <BR> <SPAN CLASS="pin">Gravity: </SPAN>The gravity state.See pRigidBody::enableGravity(). <BR> <SPAN CLASS="pin">Collision: </SPAN>Determines whether the body reacts to collisions.See pRigidBody::enableCollision(). <BR> <SPAN CLASS="pin">Mass Offset: </SPAN>The new mass center in the bodies local space. <BR> <SPAN CLASS="pin">Pivot Offset: </SPAN>The initial shape position in the bodies local space. <BR> <SPAN CLASS="pin">Notify Collision: </SPAN>Enables collision notification.This is necessary to use collisions related building blocks. <BR> <SPAN CLASS="pin">Transformation Locks: </SPAN>Specifies in which dimension a a transformation lock should occour. <BR> <SPAN CLASS="pin">Linear Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Angular Damping: </SPAN>The new linear damping scale. <BR> <SPAN CLASS="pin">Filter Groups: </SPAN>Sets the filter mask of the initial or sub shape. <BR> <SPAN CLASS="setting">Collisions Group: </SPAN>Enables input for collisions group. <BR> <SPAN CLASS="setting">Kinematic Object: </SPAN>Enables input for kinematic object. <BR> <SPAN CLASS="setting">Gravity: </SPAN>Enables input for gravity. <BR> <SPAN CLASS="setting">Collision: </SPAN>Enables input for collision. <BR> <SPAN CLASS="setting">Mas Offset: </SPAN>Enables input for mass offset. <BR> <SPAN CLASS="setting">Pivot Offset: </SPAN>Enables input for pivot offset. <BR> <SPAN CLASS="setting">Notify Collision: </SPAN>Enables input for collision. <BR> <SPAN CLASS="setting">Linear Damping: </SPAN>Enables input for linear damping. <BR> <SPAN CLASS="setting">Angular Damping: </SPAN>Enables input for angular damping. <BR> <SPAN CLASS="setting">Filter Groups: </SPAN>Enables input for filter groups. <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBSetEx.cpp </SPAN> */ //proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); proto->SetBehaviorCallbackFct( PVSetMotorValuesCB ); //proto->DeclareSetting("Output Curve",CKPGUID_BOOL,"TRUE"); //proto->DeclareSetting("Automatic Gears",CKPGUID_BOOL,"TRUE"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PVSetMotorValues); *pproto = proto; return CK_OK; } int PVSetMotorValues(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbSErrorME(E_PE_REF); pRigidBody *body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); pVehicle *v = body->getVehicle(); if (!v) bbSErrorME(E_PE_NoVeh); if (!v->isValidEngine()) bbErrorME("Vehicle is not complete"); pEngine *engine = v->getEngine(); if (!engine) bbErrorME("No valid engine"); CK2dCurve* pOCurve = NULL; //optional BB_DECLARE_PIMAP;//retrieves the parameter input configuration array BBSParameter(I_XML);//our bb settings concated as s##I_XML BBSParameter(I_Flags); BBSParameter(I_Clutch); BBSParameter(I_tList); BBSParameter(I_maxRPM); BBSParameter(I_minRPM); BBSParameter(I_maxTorque); BBSParameter(I_intertia); BBSParameter(I_engineFriction); BBSParameter(I_breakCoeff); BBSParameter(I_GroundForceFeedBackScale); if (sI_XML){ int xmlLink = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_XML)); } if (sI_GroundForceFeedBackScale) engine->setForceFeedbackScale(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_GroundForceFeedBackScale))); if (sI_Flags) engine->setFlags(GetInputParameterValue<int>(beh,BB_IP_INDEX(I_Flags))); if (sI_Clutch) engine->setClutch(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_Clutch))); if (sI_maxTorque) engine->setMaxTorque(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_maxTorque))); if (sI_maxTorque) engine->setMaxTorque(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_maxTorque))); if (sI_maxRPM) engine->setMaxRPM(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_maxRPM))); if (sI_minRPM) engine->setIdleRPM(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_minRPM))); if (sI_engineFriction) engine->setFriction(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_engineFriction))); if (sI_intertia) engine->SetInertia(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_intertia))); if (sI_breakCoeff) engine->setBrakingCoeff(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_breakCoeff))); if (sI_tList){ CKParameterIn *inP = beh->GetInputParameter(BB_IP_INDEX(I_tList)); CKParameter *pout= inP->GetDirectSource(); if (pout) { if (engine->getTorqueCurve()) { pLinearInterpolation &curve = *engine->getTorqueCurve(); curve.clear(); IParameter::Instance()->copyTo(curve,pout); engine->preStep(); } } //engine->setTorqueCurve(); } ////////////////////////////////////////////////////////////////////////// //a optinal curve to display ratio between horse power and rpm /* DWORD outputCurve; beh->GetLocalParameterValue(BB_PMAP_SIZE(gPIMAP),&outputCurve);//special settings ! if (outputCurve) beh->GetOutputParameterValue(0,&pOCurve); */ ////////////////////////////////////////////////////////////////////////// // // Checking we have to replace of the entire motor object ! // if (sI_tList) { float maxInputRPM =0.0f; float maxInputNM =0.0f; ////////////////////////////////////////////////////////////////////////// // // this is only a test run ! pLinearInterpolation nTable; //getNewTorqueTable(beh,nTable,maxInputRPM,maxInputNM,NULL); if (nTable.getSize() ) { /* if (pOCurve) { while (pOCurve->GetControlPointCount()) { pOCurve->DeleteControlPoint(pOCurve->GetControlPoint(0)); pOCurve->Update(); } } */ ////////////////////////////////////////////////////////////////////////// // we just copy into the motor we can get ! ////////////////////////////////////////////////////////////////////////// // we make a new torque ratios //getNewTorqueTable(beh,mDesc->torqueCurve,maxInputRPM,maxInputNM,pOCurve); /* if (!mDesc->isValid()) bbErrorME("motor description was invalid, aborting update "); if (!motor) { motor = pFactory::Instance()->createVehicleMotor(*mDesc); v->setMotor(motor); }else { if (mDesc->torqueCurve.getSize()) { motor->loadNewTorqueCurve(mDesc->torqueCurve); } }*/ } } ////////////////////////////////////////////////////////////////////////// // // Flexibility : // /* if (sI_minRDown && motor )motor->setMinRpmToGearDown(mDDown); if (sI_maxRUp && motor )motor->setMaxRpmToGearUp(mDUp); if (sI_maxR && motor )motor->setMaxRpm(maxR); if (sI_minR && motor )motor->setMinRpm(minR); */ if ( pOCurve ) { /* #ifdef _DEBUG XString error; error << "t curve created with " << pOCurve->GetControlPointCount() << " with l : " << pOCurve->GetLength(); bbErrorME(error.CStr()); #endif */ /* for (int i = 0 ; i < pOCurve->GetControlPointCount() ; i++) { CK2dCurvePoint* point = pOCurve->GetControlPoint(i); point->SetLinear(true); } pOCurve->Update(); beh->SetOutputParameterValue(0,&pOCurve); */ } //delete mDesc; //mDesc = NULL; } beh->ActivateOutput(0); return 0; } //somebody wants to enter new torque values : //if (outputCurve && sI_tList ) // beh->GetOutputParameterValue(0,&pOCurve); /* if (sI_tList) { float maxInputRPM =0.0f; float maxInputNM =0.0f; pLinearInterpolation torqueCurve; CKParameterIn *inP = beh->GetInputParameter(BB_IP_INDEX(I_tList)); CKParameter *pout= inP->GetDirectSource(); if (pout) { float rpm = 0.0f; float nm = 0.0f; bool maximaFound = false; bool dataCollected = false; evaluate: for (int i = 0 ; i < 6 ; i++) { CK_ID* paramids = static_cast<CK_ID*>(pout->GetReadDataPtr()); CKParameter * sub = static_cast<CKParameterOut*>(GetPMan()->m_Context->GetObject(paramids[i])); if (sub) { rpm = GetValueFromParameterStruct<float>(sub,0,false); nm = GetValueFromParameterStruct<float>(sub,1,false); if ( rpm >0.0f && nm > 0.0f ) { if (rpm > maxInputRPM) maxInputRPM = rpm; if (nm > maxInputNM) maxInputNM = nm; if (maximaFound || !outputCurve ) { torqueCurve.insert(rpm,nm); dataCollected =true; } if (maximaFound && outputCurve ) { pOCurve->AddControlPoint(Vx2DVector(rpm/maxInputRPM , nm/maxInputNM) ); dataCollected =true; } } } } if (dataCollected) { goto end; } if ( maxInputRPM >0.0f && maxInputNM> 0.0f ) { maximaFound = true; goto evaluate; } end : if (dataCollected ) { if (outputCurve) beh->SetOutputParameterValue(0,&pOCurve); ////////////////////////////////////////////////////////////////////////// if (!motor) { mDesc = new pVehicleMotorDesc(); mDesc->setToDefault(); mDesc->maxRpmToGearUp = sI_maxRUp ? mDUp : mDesc->maxRpmToGearUp; mDesc->minRpmToGearDown = sI_minRDown = mDDown : mDesc->minRpmToGearDown ; mDesc->torqueCurve = torqueCurve; motor = pFactory::Instance()->createVehicleMotor(*mDesc); v->setMotor(motor); } } } } */<file_sep>#pragma once // DistributedNetworkClassDialogToolbarDlg.h : header file // //toolbar dialog creation function, to be called by Virtools Dev DllToolbarDlg* fCreateToolbarDlg(HWND parent); ///////////////////////////////////////////////////////////////////////////// // ToolbarDlg dialog class DistributedNetworkClassDialogToolbarDlg : public DllToolbarDlg { public: //called on creation of the dialog by Virtools Dev interface //the PluginInterface will be avalaible only when the OnInterfaceInit() has been called virtual void OnInterfaceInit(); //called on destruction of the dialog by Virtools Dev interface virtual void OnInterfaceEnd(); //callback for receiving notification virtual HRESULT ReceiveNotification(UINT MsgID,DWORD Param1=0,DWORD Param2=0,CKScene* Context=NULL); // Construction public: DistributedNetworkClassDialogToolbarDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(DistributedNetworkClassDialogToolbarDlg) enum { IDD = IDD_TOOLBAR }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(DistributedNetworkClassDialogToolbarDlg) public: virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(DistributedNetworkClassDialogToolbarDlg) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" BOOL PhysicManager::checkDemo(CK3dEntity* a) { return true; /* if (!a) { return false; } //VxVector scale = vtODE::math::BoxGetZero(a); /*if ( scale.x > 400 || scale.y > 100 || scale.z > 400 ) { return false; } if (GetPMan()->DefaultWorld() && GetPMan()->DefaultWorld()->NumBodies() > 30 ) { return false; } //return true; CKMesh *mesh = (CKMesh *)a->GetCurrentMesh(); if (mesh) { int vcount = mesh->GetVertexCount(); if (vcount ==960 ||vcount ==559 || vcount ==4096 ||vcount ==106 ||vcount ==256 || vcount ==17 || vcount ==24 || vcount == 266 || vcount == 841 ) { return true; } } return false; */ }<file_sep>#include "StdAfx.h" #include "InitMan.h" #include "vt_python_funcs.h" #include <iostream> using std::cout; #include <sstream> #include "pyembed.h" #include "PythonModule.h" //************************************ // Method: ClearModules // FullName: vt_python_man::ClearModules // Access: public // Returns: void // Qualifier: //************************************ void vt_python_man::ClearPythonModules() { /* PModulesIt begin = GetPModules().begin(); PModulesIt end = GetPModules().end(); while(begin!=end) { if (begin->second) { Py_XDECREF(begin->second); begin->second = NULL; } begin++; } GetPModules().clear(); */ } /* void vt_python_man::CallPyModule(CK_ID id,XString func,const Arg_mmap& args,long& ret) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr(),args,ret); } } } void vt_python_man::CallPyModule(CK_ID id,XString func,const Arg_mmap& args,double& ret) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr(),args,ret); } } } void vt_python_man::CallPyModule(CK_ID id,XString func,const Arg_mmap& args,std::string& ret) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr(),args,ret); } } } void vt_python_man::CallPyModule(CK_ID id,Arg_mmap *args,XString func) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr()); } } } void vt_python_man::CallPyModule(CK_ID id,XString func) { CKObject* obj = m_Context->GetObject(id); if(obj) { PyObject *module = GetPModule(id); if (module) { this->py->call(module,func.CStr()); } } }*/ //************************************ // Method: RemovePModule // FullName: vt_python_man::RemovePModule // Access: public // Returns: void // Qualifier: // Parameter: CK_ID id //************************************ /* void vt_python_man::DestroyPythonModule(CK_ID bid) { CKObject* obj = m_Context->GetObject(id); if(obj) { PModulesIt it = GetPModules().find(id); if(it != GetPModules().end() ) { if (it->second) { Py_DECREF(it->second); it->second = NULL; GetPModules().erase(it); } } } } */ //************************************ // Method: GetPModule // FullName: vt_python_man::GetPModule // Access: public // Returns: PyObject* // Qualifier: // Parameter: CK_ID id //************************************ PythonModule* vt_python_man::GetPythonModule(CK_ID bid) { /*CKObject* obj = m_Context->GetObject(id); if(obj) { PModulesIt it = GetPModules().find(id); if(it != GetPModules().end() ) { return it->second; }else { return NULL; } }*/ return NULL; } //************************************ // Method: InsertPModule // FullName: vt_python_man::InsertPModule // Access: public // Returns: void // Qualifier: // Parameter: CK_ID id // Parameter: XString name // Parameter: bool reload //************************************ PythonModule* vt_python_man::CreatePythonModule(char*file,char*func,CK_ID bid) { /*CKObject* obj = m_Context->GetObject(id); if(obj) { if (GetPModule(id)) { RemovePModule(id); } //bit = BArray.insert(BArray.end(),std::make_pair(target,bodyI)); PModulesIt it = GetPModules().find(id); if(it == GetPModules().end() ) { try { PyObject* namep = PyString_FromString( name.CStr() ); PyObject* module = PyImport_Import(namep); if (reload) PyImport_ReloadModule(module); Py_DECREF(namep); GetPModules().insert( GetPModules().end(),std::make_pair(id,module ) ); if (!module) { std::ostringstream oss; m_Context->OutputToConsoleEx("PyErr : \t Failed to load module" ); return NULL; } return module; } catch (Python_exception ex) { m_Context->OutputToConsoleEx("PyErr : \t %s",(CKSTRING)ex.what()); std::cout << ex.what() << "pyexeption in beh : "; PyErr_Clear(); //beh->ActivateOutput(1,TRUE); } //GetPModules().insert( GetPModules().end(),std::make_pair(id,module ) ); //return module; } } */ return NULL; } <file_sep>#ifndef __VTNET_CONFIG_H_ #define __VTNET_CONFIG_H_ //#define HAS_DISTOBJECTS 0 //#undef HAS_DISTOBJECTS #define OUTPUT_ON_VIRTOOLS_CONSOLE 1 #endif<file_sep>// // 3DTrans.cpp : Defines the initialization routines for the DLL. // #include "CKAll.h" #include "MidiManager.h" #ifdef macintosh #include "BehaviorExport.h" #endif #ifdef CK_LIB #define RegisterBehaviorDeclarations Register_MidiBehaviors_BehaviorDeclarations #define InitInstance _MidiBehaviors_InitInstance #define ExitInstance _MidiBehaviors_ExitInstance #define CKGetPluginInfoCount CKGet_MidiBehaviors_PluginInfoCount #define CKGetPluginInfo CKGet_MidiBehaviors_PluginInfo #define g_PluginInfo g_MidiBehaviors_PluginInfo #else #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations #define InitInstance InitInstance #define ExitInstance ExitInstance #define CKGetPluginInfoCount CKGetPluginInfoCount #define CKGetPluginInfo CKGetPluginInfo #define g_PluginInfo g_PluginInfo #endif CKERROR InitInstance(CKContext* context); CKERROR ExitInstance(CKContext* context); void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg); #define MIDI_BEHAVIOR CKGUID(0x58176f2d,0x6b80544c) #define CKOGUID_ISNOTEACTIVE CKDEFINEGUID(0x25d70112,0x683835b8) CKPluginInfo g_PluginInfo[2]; int CKGetPluginInfoCount() { return 2; } CKPluginInfo* CKGetPluginInfo(int Index) { g_PluginInfo[0].m_Author = "Virtools"; g_PluginInfo[0].m_Description = "Midi Building Blocks"; g_PluginInfo[0].m_Extension = ""; g_PluginInfo[0].m_Type = CKPLUGIN_BEHAVIOR_DLL; g_PluginInfo[0].m_Version = 0x000001; g_PluginInfo[0].m_InitInstanceFct = NULL; g_PluginInfo[0].m_ExitInstanceFct = NULL; g_PluginInfo[0].m_GUID = MIDI_BEHAVIOR; g_PluginInfo[0].m_Summary = "Midi Building Blocks"; g_PluginInfo[1].m_Author = "Virtools"; g_PluginInfo[1].m_Description = "Midi Manager"; g_PluginInfo[1].m_Extension = ""; g_PluginInfo[1].m_Type = CKPLUGIN_MANAGER_DLL; g_PluginInfo[1].m_Version = 0x000001; g_PluginInfo[1].m_InitInstanceFct = InitInstance; g_PluginInfo[1].m_ExitInstanceFct = ExitInstance; g_PluginInfo[1].m_GUID = MIDI_MANAGER_GUID; g_PluginInfo[1].m_Summary = "Midi Manager"; return &g_PluginInfo[Index]; } /**********************************************************************************/ /**********************************************************************************/ /////////////////////// /// Param Op /// /////////////////////// void BoolIsNoteActiveIntInt (CKContext *ctx, CKParameterOut *res, CKParameterIn *p1, CKParameterIn *p2){ int note; p1->GetValue(&note); int channel; p2->GetValue(&channel); MidiManager *mm = (MidiManager *) ctx->GetManagerByGuid( MIDI_MANAGER_GUID ); CKBOOL isNoteActive=mm->IsNoteActive(note, channel); res->SetValue(&isNoteActive); } //////////////////////// // Initializations // //////////////////////// CKERROR InitInstance(CKContext* ctx) { CKParameterManager *pm = ctx->GetParameterManager(); //--- register a new Operation Type pm->RegisterOperationType(CKOGUID_ISNOTEACTIVE, "Is Note Active"); //--- register a new Parameter Operation pm->RegisterOperationFunction(CKOGUID_ISNOTEACTIVE ,CKPGUID_BOOL, CKPGUID_INT, CKPGUID_INT, BoolIsNoteActiveIntInt); new MidiManager(ctx); return CK_OK; } CKERROR ExitInstance(CKContext* ctx) { CKParameterManager *pm = ctx->GetParameterManager(); //--- register a new Operation Type pm->UnRegisterOperationType(CKOGUID_ISNOTEACTIVE); MidiManager* man=(MidiManager*)ctx->GetManagerByGuid(MIDI_MANAGER_GUID); delete man; return CK_OK; } //////////////////////////////// // Behaviors Registrations // //////////////////////////////// void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) { RegisterBehavior(reg, FillBehaviorReadMidiSignalDecl); RegisterBehavior(reg, FillBehaviorMidiEventDecl); RegisterBehavior(reg, FillBehaviorSwitchOnMidiDecl); RegisterBehavior(reg, FillBehaviorMidiPlayerDecl); RegisterBehavior(reg, FillBehaviorSetMidiOutPortDecl); RegisterBehavior(reg, FillBehaviorGetMidiINDevicesDecl); RegisterBehavior(reg, FillBehaviorGetMidiOutDevicesDecl ); RegisterBehavior(reg, FillBehaviorSetInMidiPortDecl); RegisterBehavior(reg, FillBehaviorSendMidiSignalDecl ); } CRITICAL_SECTION gMidiCS; #if !defined(CK_LIB) BOOL WINAPI DllMain(HINSTANCE hinstDLL, // handle to the DLL module DWORD fdwReason, // reason for calling function LPVOID lpvReserved // reserved ){ switch(fdwReason){ case DLL_PROCESS_ATTACH: InitializeCriticalSection(&gMidiCS); break; case DLL_PROCESS_DETACH: DeleteCriticalSection(&gMidiCS); break; } return TRUE; } #endif<file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPVWGetDecl(); CKERROR CreatePVWGetProto(CKBehaviorPrototype **pproto); int PVWGet(const CKBehaviorContext& behcontext); CKERROR PVWGetCB(const CKBehaviorContext& behcontext); using namespace vtTools; using namespace BehaviorTools; enum bbI_Inputs { bbI_BodyReference, }; #define BB_SSTART 0 enum bbOutputs { O_AxleSpeed, O_WheelRollAngle, O_RPM, O_SteerAngle, O_MotorTorque, O_BreakTorque, O_Suspension, O_SuspensionTravel, O_Radius, O_WFlags, O_WSFlags, O_LatFunc, O_LongFunc, O_Contact, }; BBParameter pOutMap[] = { BB_SPOUT(O_AxleSpeed,CKPGUID_FLOAT,"Axle Speed","0.0"), BB_SPOUT(O_WheelRollAngle,CKPGUID_FLOAT,"Roll Angle","0.0"), BB_SPOUT(O_RPM,CKPGUID_FLOAT,"RPM","0.0"), BB_SPOUT(O_SteerAngle,CKPGUID_ANGLE,"Steer Angle","0.0"), BB_SPOUT(O_MotorTorque,CKPGUID_FLOAT,"Motor Torque","0.0"), BB_SPOUT(O_BreakTorque,CKPGUID_FLOAT,"Break Torque","0.0"), BB_SPOUT(O_Suspension,VTS_JOINT_SPRING,"Suspension Spring","0.0"), BB_SPOUT(O_SuspensionTravel,CKPGUID_FLOAT,"Suspension Spring","0.0"), BB_SPOUT(O_Radius,CKPGUID_FLOAT,"Radius","0.0"), BB_SPOUT(O_WFlags,VTS_PHYSIC_WHEEL_FLAGS,"Wheel Flags","0.0"), BB_SPOUT(O_WSFlags,VTF_VWSHAPE_FLAGS,"Wheel Shape Flags","0.0"), BB_SPOUT(O_LatFunc,VTF_VWTIRE_SETTINGS,"Lateral Force Settings","0.0"), BB_SPOUT(O_LongFunc,VTF_VWTIRE_SETTINGS,"Longitudinal Force Settings","0.0"), BB_SPOUT(O_Contact,VTS_WHEEL_CONTACT,"Contact Data","0.0"), //BB_SPOUT(O_LongFunc,VTF_VWTIRE_SETTINGS,"Longitudinal Force Settings","0.0"), }; #define gOPMap pOutMap CKERROR PVWGetCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; int cb = behcontext.CallbackMessage; BB_DECLARE_PMAP; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { BB_LOAD_POMAP(gOPMap,BB_SSTART); break; } case CKM_BEHAVIORDETACH: { BB_DESTROY_PMAP; break; } case CKM_BEHAVIORATTACH: { BB_INIT_PMAP(gOPMap,BB_SSTART); break; } case CKM_BEHAVIORSETTINGSEDITED: { BB_REMAP_PMAP(gOPMap,BB_SSTART); break; } } return CKBR_OK; } CKObjectDeclaration *FillBehaviorPVWGetDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PVWGet"); od->SetCategory("Physic/Vehicle"); od->SetDescription("Retrieves wheel related parameters."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x24b704e4,0x65ed5fad)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePVWGetProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePVWGetProto // FullName: CreatePVWGetProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreatePVWGetProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVWGet"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); /*! \page PVWGet PVWGet is categorized in \ref Vehicle <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Retrieves various physical informations.<br> <h3>Technical Information</h3> \image html PVWGet.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>The 3D Entity associated to the rigid body. <BR> <BR> <SPAN CLASS="pout">Collisions Group: </SPAN>Which collision group this body is part of.See pRigidBody::getCollisionsGroup(). <BR> <SPAN CLASS="pout">Kinematic Object: </SPAN>The kinematic state. See pRigidBody::isKinematic(). <BR> <SPAN CLASS="pout">Gravity: </SPAN>The gravity state.See pRigidBody::isAffectedByGravity(). <BR> <SPAN CLASS="pout">Collision: </SPAN>Determines whether the body reacts to collisions.See pRigidBody::isCollisionEnabled(). <BR> <BR> <SPAN CLASS="setting">Collisions Group: </SPAN>Enables output for collisions group. <BR> <SPAN CLASS="setting">Kinematic Object: </SPAN>Enables output for kinematic object. <BR> <SPAN CLASS="setting">Gravity: </SPAN>Enables output for gravity. <BR> <SPAN CLASS="setting">Collision: </SPAN>Enables output for collision. <BR> <BR> <BR> <BR> <h3>Warning</h3> The body must be dynamic. <br> <br> <h3>Note</h3> Is utilizing #pRigidBody #pWorld #PhysicManager.<br> <h3>VSL</h3><br> <SPAN CLASS="NiceCode"> \include PBGetEx.cpp </SPAN> */ //proto->DeclareInParameter("World Reference",CKPGUID_3DENTITY,"pDefaultWorld"); //proto->DeclareInParameter("Body Reference",CKPGUID_3DENTITY,"Body"); /*proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Kinematic",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Gravity",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Collision",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Mass Offset",CKPGUID_BOOL,"FALSE"); proto->DeclareSetting("Pivot Offset",CKPGUID_BOOL,"FALSE"); proto->DeclareOutParameter("Collisions Group",CKPGUID_INT,"0"); proto->DeclareOutParameter("Kinematic Object",CKPGUID_BOOL,"FALSE"); proto->DeclareOutParameter("Gravity",CKPGUID_BOOL,"FALSE"); proto->DeclareOutParameter("Collision",CKPGUID_BOOL,"FALSE"); proto->DeclareOutParameter("Mass Offset",CKPGUID_VECTOR,"0.0f"); proto->DeclareOutParameter("Pivot Offset",CKPGUID_VECTOR,"0.0f"); */ proto->SetBehaviorCallbackFct( PVWGetCB ); BB_EVALUATE_SETTINGS(gOPMap); //---------------------------------------------------------------- // // We just want create the building block pictures // #ifdef _DOC_ONLY_ BB_EVALUATE_OUTPUTS(gOPMap); #endif // _DOC_ONLY_ proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(PVWGet); *pproto = proto; return CK_OK; } //************************************ // Method: PVWGet // FullName: PVWGet // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PVWGet(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; body = GetPMan()->getBody(target); if (!body) bbErrorME("No Reference Object specified"); pWheel *wheel = body->getWheel(target); if (!wheel)bbErrorME("pWheel object doesnt exist!"); pWheel2 *wheel2 = wheel->castWheel2(); //if (!wheel2)bbErrorME("Couldnt cast a pWheel2 object"); BB_DECLARE_PMAP; /************************************************************************/ /* retrieve settings state */ /***** *******************************************************************/ BBSParameter(O_AxleSpeed); BBSParameter(O_WheelRollAngle); BBSParameter(O_RPM); BBSParameter(O_SteerAngle); BBSParameter(O_MotorTorque); BBSParameter(O_BreakTorque); BBSParameter(O_Suspension); BBSParameter(O_SuspensionTravel); BBSParameter(O_Radius); BBSParameter(O_WFlags); BBSParameter(O_WSFlags); BBSParameter(O_LatFunc); BBSParameter(O_LongFunc); BBSParameter(O_Contact); BB_O_SET_VALUE_IF(float,O_AxleSpeed,wheel2->getAxleSpeed()); BB_O_SET_VALUE_IF(float,O_WheelRollAngle,wheel->getWheelRollAngle()); BB_O_SET_VALUE_IF(float,O_RPM,wheel2->getRpm()); if (wheel2) { BB_O_SET_VALUE_IF(float,O_SteerAngle,wheel2->GetHeading()); } /* BB_O_SET_VALUE_IF(float,O_SteerAngle,wheel2->rotationV.x);*/ BB_O_SET_VALUE_IF(float,O_MotorTorque,wheel2->getWheelShape()->getMotorTorque()); BB_O_SET_VALUE_IF(float,O_BreakTorque,wheel2->getWheelShape()->getBrakeTorque()); BB_O_SET_VALUE_IF(float,O_SuspensionTravel,wheel2->getWheelShape()->getSuspensionTravel()); BB_O_SET_VALUE_IF(float,O_Radius,wheel2->getWheelShape()->getRadius()); BB_O_SET_VALUE_IF(int,O_WFlags,wheel->mWheelFlags); BB_O_SET_VALUE_IF(int,O_WSFlags,wheel2->getWheelShape()->getWheelFlags()); if (wheel2){ if (sO_LatFunc) { NxTireFunctionDesc tf = wheel2->getWheelShape()->getLateralTireForceFunction(); CKParameterOut *pout = beh->GetOutputParameter(BB_OP_INDEX(O_LatFunc)); if (pout) { vtTools::ParameterTools::SetParameterStructureValue<float>(pout,1,tf.extremumSlip); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,2,tf.extremumValue); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,3,tf.asymptoteSlip); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,4,tf.asymptoteValue); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,5,tf.stiffnessFactor); } } if (sO_LongFunc) { NxTireFunctionDesc tf = wheel2->getWheelShape()->getLongitudalTireForceFunction(); CKParameterOut *pout = beh->GetOutputParameter(BB_OP_INDEX(O_LongFunc)); if (pout) { vtTools::ParameterTools::SetParameterStructureValue<float>(pout,1,tf.extremumSlip); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,2,tf.extremumValue); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,3,tf.asymptoteSlip); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,4,tf.asymptoteValue); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,5,tf.stiffnessFactor); } } } if (wheel2) { if (sO_Suspension) { NxSpringDesc s = wheel2->getWheelShape()->getSuspension(); CKParameterOut *pout = beh->GetOutputParameter(BB_OP_INDEX(O_Suspension)); if (pout) { vtTools::ParameterTools::SetParameterStructureValue<float>(pout,0,s.damper); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,1,s.spring); vtTools::ParameterTools::SetParameterStructureValue<float>(pout,2,s.targetValue); } } if (sO_Contact) { pWheelContactData cData = *wheel2->getContact(); CKParameterOut *pout = beh->GetOutputParameter(BB_OP_INDEX(O_Contact)); if (pout) { pFactory::Instance()->copyTo(pout,cData); } } } } beh->ActivateOutput(0); return 0; } //************************************ // Method: PVWGetCB // FullName: PVWGetCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ <file_sep>#ifndef __VT_STRUCT_HELPER_H__ #define __VT_STRUCT_HELPER_H__ namespace vtTools { namespace ParameterTools { struct StructurMember { CKGUID guid; XString name; XString defaultValue; CKObject *par; StructurMember() { guid = CKGUID(0,0); name = ""; defaultValue = ""; } StructurMember(CKGUID _guid,XString _name,XString _defaultValue) : guid(_guid) , name(_name) , defaultValue(_defaultValue) { } }; class CustomStructure { public : CustomStructure(){} CustomStructure(XString name,CKGUID guid,StructurMember members[],int size) : mGuid(guid) , mName(name) { for (int i = 0 ; i < size ; i ++) { StructurMember *p=new StructurMember(members[i].guid,members[i].name,members[i].defaultValue); getArray().push_back(p); } } std::vector<StructurMember*>pars; std::vector<StructurMember*>&getArray() { return pars; } CKGUID mGuid; XString mName; }; class StructHelper { public : static XArray<CKGUID>getMemberGuids(CustomStructure _inStructure) { XArray<CKGUID>result; int size = _inStructure.getArray().size(); for (int i = 0 ; i < size ; i ++) { StructurMember *m=_inStructure.getArray().at(i); result.PushBack(m->guid); } return result; } static XString getLabelNames(CustomStructure _inStructure) { XString result; int size = _inStructure.getArray().size(); for (int i = 0 ; i < size ; i ++) { StructurMember *m=_inStructure.getArray().at(i); result << m->name.CStr(); if (i != size -1) { result << ","; } } return result; } static XString getDefaultValue(CustomStructure _inStructure) { XString result; int size = _inStructure.getArray().size(); for (int i = 0 ; i < size ; i ++) { StructurMember *m=_inStructure.getArray().at(i); result << m->defaultValue.CStr(); if (i != size -1) { result << ";"; } } return result; } }; } } #define STRUCT_ATTRIBUTE(G,N,D) vtTools::ParameterTools::StructurMember(G,N,D) #define DECLARE_STRUCT(T,N,G,A,S) CustomStructure cs##T(N,G,A,S) #define STRUCT_SIZE(SOURCE_MAP) (sizeof(SOURCE_MAP) / sizeof(SOURCE_MAP[0])) #define STRUCT_MEMBER_NAMES(SRC) vtTools::ParameterTools::StructHelper::getLabelNames(cs##SRC) #define STRUCT_MEMBER_GUIDS(SRC) vtTools::ParameterTools::StructHelper::getMemberGuids(cs##SRC) #define STRUCT_MEMBER_DEFAULTS(SRC) vtTools::ParameterTools::StructHelper::getDefaultValue(cs##SRC) #define REGISTER_CUSTOM_STRUCT(NAME,ENUM_TYPE,GUID,MEMBER_ARRAY,HIDDEN) DECLARE_STRUCT(ENUM_TYPE,NAME,GUID,MEMBER_ARRAY,STRUCT_SIZE(MEMBER_ARRAY)); \ XArray<CKGUID> ListGuid##ENUM_TYPE = STRUCT_MEMBER_GUIDS(ENUM_TYPE);\ pm->RegisterNewStructure(GUID,NAME,STRUCT_MEMBER_NAMES(ENUM_TYPE).Str(),ListGuid##ENUM_TYPE);\ CKParameterTypeDesc* param_type##ENUM_TYPE=pm->GetParameterTypeDescription(GUID);\ if (param_type##ENUM_TYPE && HIDDEN) param_type##ENUM_TYPE->dwFlags|=CKPARAMETERTYPE_HIDDEN;\ _getCustomStructures().Insert(GUID,(CustomStructure*)&MEMBER_ARRAY) #define REGISTER_STRUCT_AS_ATTRIBUTE(NAME,ENUM_TYPE,CATEGORY,GUID,CLASS,MEMBER_ARRAY,USE_DEFAULTS) int att##ENUM_TYPE = attman->RegisterNewAttributeType(NAME,GUID,CLASS);\ attman->SetAttributeCategory(att##ENUM_TYPE,CATEGORY);\ if(USE_DEFAULTS)\ attman->SetAttributeDefaultValue(att##ENUM_TYPE,STRUCT_MEMBER_DEFAULTS(ENUM_TYPE).Str()); #endif <file_sep>#ifndef __P_ATTRIBUTE_HELPER_H__ #define __P_ATTRIBUTE_HELPER_H__ #define PHYSIC_BODY_CAT "Physic" #define ATT_FUNC_TABLE_SIZE 12 #include "vtParameterGuids.h" #include "pManagerTypes.h" //################################################################ // // Declaration of rigid body related attribute callback function // int registerRigidBody(CK3dEntity *target,int attributeType,bool set,bool isPostJob); //################################################################ // // Declaration of various joint attribute callback functions // int registerJDistance(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJFixed(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJBall(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJPrismatic(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJCylindrical(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJPointInPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJPointOnLine(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJRevolute(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJD6(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJD6Drive(CK3dEntity *target,int attributeType,bool set,bool isPostJob); int registerJLimitPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob); //---------------------------------------------------------------- // //! \brief The global map of parameter type and registration function // static ObjectRegistration attributeFunctionMap[] = { ObjectRegistration(VTS_PHYSIC_ACTOR,registerRigidBody), ObjectRegistration(VTS_JOINT_DISTANCE,registerJDistance), ObjectRegistration(VTS_JOINT_FIXED,registerJFixed), ObjectRegistration(VTS_JOINT_BALL,registerJBall), ObjectRegistration(VTS_JOINT_PRISMATIC,registerJPrismatic), ObjectRegistration(VTS_JOINT_POINT_IN_PLANE,registerJPointInPlane), ObjectRegistration(VTS_JOINT_POINT_ON_LINE,registerJPointOnLine), ObjectRegistration(VTS_JOINT_CYLINDRICAL,registerJCylindrical), ObjectRegistration(VTS_JOINT_REVOLUTE,registerJRevolute), ObjectRegistration(VTS_JOINT_D6,registerJD6), ObjectRegistration(VTS_JOINT_D6_DRIVES,registerJD6Drive), ObjectRegistration(VTS_PHYSIC_JLIMIT_PLANE,registerJLimitPlane), }; //################################################################ // // Misc prototypes // //---------------------------------------------------------------- // //! \brief This is the attribute callback function which is expected from Virtools. // We only use this as dispatcher function because we have our own sub set. // void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); //################################################################ // // OLD // //---------------------------------------------------------------- // //! \brief this has become obselete // void recheckWorldsFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); // --> old ! void rigidBodyAttributeCallback(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); //-->new ! #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #ifdef HAS_FLUIDS #include "pFluid.h" int RenderParticles_P(CKRenderContext *dev,CKRenderObject *obj,void *arg) { CK3dEntity* ent = (CK3dEntity *)obj; pFluid *fluid = (pFluid*)arg; if (!ent) return 0; if (!fluid) return 0; CKMesh *mesh = ent->GetCurrentMesh(); int vCount = mesh->GetVertexCount(); VxDrawPrimitiveData* data = dev->GetDrawPrimitiveStructure(CKRST_DP_TR_CL_VC,vCount); VxMatrix oldmatrix = dev->GetWorldTransformationMatrix(); dev->SetWorldTransformationMatrix(oldmatrix*ent->GetInverseWorldMatrix()); // we don't let write to the ZBuffer dev->SetTexture(NULL); dev->SetState(VXRENDERSTATE_ZWRITEENABLE , FALSE); dev->SetState(VXRENDERSTATE_SRCBLEND, VXBLEND_SRCALPHA); dev->SetState(VXRENDERSTATE_DESTBLEND, VXBLEND_ONE); dev->SetState(VXRENDERSTATE_ALPHABLENDENABLE, TRUE); dev->SetTextureStageState(CKRST_TSS_STAGEBLEND,0,1); float averageSize = 1 * 2.0f; float minSize = 4.0f; float maxSize = 10000.0f; float pointScaleA = 1.0f; float pointScaleB = 1.0f; float pointScaleC = 1.0f; /************************************************************************/ /* */ /************************************************************************/ dev->SetState(VXRENDERSTATE_SPECULARENABLE, FALSE); dev->SetState(VXRENDERSTATE_FILLMODE, VXFILL_SOLID); dev->SetState(VXRENDERSTATE_SHADEMODE, VXSHADE_GOURAUD); dev->SetTextureStageState(CKRST_TSS_TEXTUREMAPBLEND,VXTEXTUREBLEND_MODULATEALPHA); dev->SetTextureStageState(CKRST_TSS_MAGFILTER , VXTEXTUREFILTER_LINEAR); dev->SetTextureStageState(CKRST_TSS_MINFILTER , VXTEXTUREFILTER_LINEARMIPLINEAR); // States dev->SetState(VXRENDERSTATE_WRAP0 , 0); dev->SetState(VXRENDERSTATE_CULLMODE, VXCULL_NONE); dev->SetState(VXRENDERSTATE_SRCBLEND, VXBLEND_SRCALPHA); dev->SetState(VXRENDERSTATE_DESTBLEND, VXBLEND_ONE); dev->SetState(VXRENDERSTATE_ALPHABLENDENABLE, TRUE); dev->SetState(VXRENDERSTATE_ZWRITEENABLE , FALSE); dev->SetTextureStageState(CKRST_TSS_STAGEBLEND,0,1); dev->SetTextureStageState(CKRST_TSS_TEXTURETRANSFORMFLAGS, 0); dev->SetTextureStageState(CKRST_TSS_TEXCOORDINDEX, 0); dev->SetState(VXRENDERSTATE_POINTSPRITEENABLE, TRUE); dev->SetState(VXRENDERSTATE_POINTSIZE, *(DWORD*)&averageSize); dev->SetState(VXRENDERSTATE_POINTSIZE_MIN,*(DWORD*)&minSize); dev->SetState(VXRENDERSTATE_POINTSIZE_MAX,*(DWORD*)&maxSize); dev->SetState(VXRENDERSTATE_POINTSCALEENABLE, TRUE); dev->SetState(VXRENDERSTATE_POINTSCALE_A,*(DWORD*)&pointScaleA); dev->SetState(VXRENDERSTATE_POINTSCALE_B,*(DWORD*)&pointScaleB); dev->SetState(VXRENDERSTATE_POINTSCALE_C,*(DWORD*)&pointScaleC); XPtrStrided<VxVector4> positions(data->Positions); XPtrStrided<DWORD> colors(data->Colors); pParticle *particles = fluid->getParticles(); for (int i = 0 ; i < vCount ; i++) { VxColor color; color.Set(1.0f); pParticle *p = &(fluid->mParticleBuffer[i]); VxVector posi = getFrom(p->position); *positions = VxVector4(posi.x,posi.y,posi.z,0); *colors = RGBAFTOCOLOR(&(color)); // next point //p = p->next; ++colors; ++positions; } // The drawing dev->DrawPrimitive(VX_POINTLIST,(WORD*)NULL,vCount,data); dev->SetState(VXRENDERSTATE_ZWRITEENABLE , TRUE); dev->SetWorldTransformationMatrix(oldmatrix); return 0; } #endif<file_sep>@ECHO OFF rmdir .\CMakeFiles /s /q del .\*.vcproj /q /f del *.sln /q /f del CMakeCache.txt /q /f del cmake_install.cmake /q /f @ECHO ON <file_sep>#include "Path.h" char* XPath::GetFileName(){ char *pc = data_.Str(); int LastBackSlash =-1; int iChar = 0; while(pc[iChar] != 0){ if(pc[iChar] == '\\')LastBackSlash = iChar; iChar++; } return pc + LastBackSlash +1; } char* XPath::GetPath(){ char* PathCopy = data_.Str(); PathRemoveFileSpec(PathCopy); return PathCopy; } #include <STDLIB.H> int XPath::absolute_levels()const{ //count path_sepīs /* using namespace std; string s = data_.CStr(); string::iterator cit = find(s.begin(),s.end(),path_separator_); int n = 0;//;-) or how do you make this? while ( cit != s.end()){ ++n; cit = find(cit+1 ,s.end(),path_separator_); }*/ return 1; } <file_sep>// vtAgeiaInterfaceEditorDlg.cpp : implementation file // #include "stdafx2.h" #include "vtAgeiaInterfaceEditor.h" #include "vtAgeiaInterfaceEditorDlg.h" #include "vtAgeiaInterfaceKeyboardShortcuts.h" #include "vtAgeiaInterfaceCallback.h" #ifdef _MFCDEBUGNEW #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif extern vtAgeiaInterfaceEditorApp theApp; DllEditorDlg* fCreateEditorDlg(HWND parent) { HRESULT r = CreateDllDialog(parent,IDD_EDITOR,&g_Editor); return (DllEditorDlg*)g_Editor; } ///////////////////////////////////////////////////////////////////////////// // vtAgeiaInterfaceEditorDlg dialog vtAgeiaInterfaceEditorDlg::vtAgeiaInterfaceEditorDlg(CWnd* pParent /*=NULL*/) : DllEditorDlg(vtAgeiaInterfaceEditorDlg::IDD, pParent) { mContext = NULL; pMan = NULL; //{{AFX_DATA_INIT(vtAgeiaInterfaceEditorDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void vtAgeiaInterfaceEditorDlg::DoDataExchange(CDataExchange* pDX) { DllEditorDlg::DoDataExchange(pDX); //{{AFX_DATA_MAP(vtAgeiaInterfaceEditorDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(vtAgeiaInterfaceEditorDlg, DllEditorDlg) //{{AFX_MSG_MAP(vtAgeiaInterfaceEditorDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // vtAgeiaInterfaceEditorDlg message handlers LRESULT vtAgeiaInterfaceEditorDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { // TODO: Add your specialized code here and/or call the base class switch (message) { case WM_KEYDOWN: { KeyboardShortcutManager* ksm = GetInterface()->GetKeyboardShortcutManager(); /*int commandID = ksm->TestKS(STR_CATEGORY,wParam); if (commandID) OnGlobalKeyboardShortcut(commandID); */ }break; } return DllEditorDlg::WindowProc(message, wParam, lParam); } BOOL vtAgeiaInterfaceEditorDlg::SaveData(CKInterfaceObjectManager* iom) { if( !iom ) return FALSE; const int chunkCount = iom->GetChunkCount(); CKStateChunk* chunk = iom->GetChunk( 0 ); if( !chunk ) return FALSE; int a = 0 ; return TRUE; } BOOL vtAgeiaInterfaceEditorDlg::LoadData(CKInterfaceObjectManager* iom) { if( !iom ) return FALSE; const int chunkCount = iom->GetChunkCount(); CKStateChunk* chunk = iom->GetChunk( 0 ); if( !chunk ) return FALSE; chunk->StartRead(); chunk->CloseChunk(); return TRUE; } BOOL vtAgeiaInterfaceEditorDlg::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class /*if ( pMsg->message >= WM_MOUSEFIRST && pMsg->message <= WM_MOUSELAST) { MSG msg; ::CopyMemory(&msg, pMsg, sizeof(MSG)); m_wndToolTip.RelayEvent(pMsg); } */ /*switch(pMsg->message) { case WM_MOUSEMOVE: { break; } case WM_SYSKEYDOWN: case WM_KEYDOWN: { }break; }*/ return DllEditorDlg::PreTranslateMessage(pMsg); } BOOL vtAgeiaInterfaceEditorDlg::OnInitDialog() { DllEditorDlg::OnInitDialog(); // TODO: Add extra initialization here //EnableToolTips(TRUE); //CreateTooltip(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } //this is the almost equivalent of OnInitDialog you should use if you want to //use the PluginInterface with GetInterface or if you want to be sure the toolbar is present void vtAgeiaInterfaceEditorDlg::OnInterfaceInit() { if (theApp.mContext && theApp.pMan) { init(theApp.mContext,theApp.pMan); } //sample code : here we ask to listen to the _CKFILELOADED notification //which is send when a file is loaded from Virtools Dev's user interface ObserveNotification(CUIK_NOTIFICATION_CKFILELOADED); ObserveNotification(CUIK_NOTIFICATION_LEVEL_LOADED); ObserveNotification(CUIK_NOTIFICATION_CKFILELOADED); ObserveNotification(CUIK_NOTIFICATION_PRECKFILELOADED); ObserveNotification(CUIK_NOTIFICATION_OBJECTROTCHANGED); ObserveNotification(CUIK_NOTIFICATION_OBJECTPOSCHANGED); ObserveNotification(CUIK_NOTIFICATION_SELECTIONCHANGED); ObserveNotification(CUIK_NOTIFICATION_UPDATESETUP); ObserveNotification(CUIK_NOTIFICATION_OBJECTPARAMSCHANGED); } void vtAgeiaInterfaceEditorDlg::objectSelChanged(DWORD par1,DWORD par2) { /* if (getContext()) { getContext()->OutputToConsoleEx("sel changed :"); return ; CKBeObject *object = (CKBeObject*)mContext->GetObject(par1); if (object) { CKSTRING name = object->GetName(); getContext()->OutputToConsoleEx("sel changed : %s",name); } }*/ } void vtAgeiaInterfaceEditorDlg::objectPosChanged(CK_ID objID) { int id = objID; ///MessageBox("asdasd","asdasd",1); /* if (mContext) { CKBeObject *object = (CKBeObject*)mContext->GetObject(objID); if (objID) { int a = 0 ; CKSTRING name = object->GetName(); CKSTRING name2 = object->GetName(); } } */ } void vtAgeiaInterfaceEditorDlg::init(CKContext *ctx,PhysicManager *pm) { pMan = pm; mContext = ctx; } //called on WM_DESTROY void vtAgeiaInterfaceEditorDlg::OnInterfaceEnd() { } HRESULT vtAgeiaInterfaceEditorDlg::ReceiveNotification(UINT MsgID,DWORD Param1,DWORD Param2,CKScene* Context) { switch(MsgID) { //sample code : case CUIK_NOTIFICATION_CKFILELOADED: { }break; case CUIK_NOTIFICATION_OBJECTPOSCHANGED: { //objectPosChanged(Param1); } case CUIK_NOTIFICATION_SELECTIONCHANGED: { //objectSelChanged(Param1,Param2); break; } case CUIK_NOTIFICATION_UPDATESETUP: { //objectSelChanged(Param1,Param2); break; } case CUIK_NOTIFICATION_OBJECTPARAMSCHANGED: { //objectSelChanged(Param1,Param2); break; } break; } return 0; } void vtAgeiaInterfaceEditorDlg::CreateTooltip() { m_wndToolTip.Create(this); m_wndToolTip.Activate(TRUE); //delay after which the tooltip apppear, value of 1 is immediate, 0 is default (that is 500 for windows) m_wndToolTip.SetDelayTime(500); //change tooltip back color //m_wndToolTip.SetTipBkColor(CZC_176); //change tooltip text color //m_wndToolTip.SetTipTextColor(CZC_BLACK); //for each control you want to add a tooltip on, add the following line //m_wndToolTip.AddTool(CWnd* target,const char* tooltip_string); //delay after which the tooltip will auto close itself m_wndToolTip.SetDelayTime(TTDT_AUTOPOP,5000); m_wndToolTip.SetWindowPos(&(CWnd::wndTopMost),0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); //if you want multiline tooltip, you must add the following line (note that this represent the max tooltip width in pixel) m_wndToolTip.SendMessage(TTM_SETMAXTIPWIDTH, 0, 500); } int vtAgeiaInterfaceEditorDlg::OnGlobalKeyboardShortcut(int commandID) { return 0; //return 1 if successfull/keyboard shortcut has been processed } int vtAgeiaInterfaceEditorDlg::OnLocalKeyboardShortcut(int commandID) { return 0; //return 1 if successfull/keyboard shortcut has been processed } void vtAgeiaInterfaceEditorDlg::OnCustomMenu(CMenu* menu,int startingCommandID,int endingCommandID) { menu->AppendMenu(0,0 /*base ID*/ + startingCommandID,"Sample Command 1"); menu->AppendMenu(0,1 /*base ID*/ + startingCommandID,"Sample Command 2"); } void vtAgeiaInterfaceEditorDlg::OnCustomMenu(int commandID) { switch(commandID) { case 0: AfxMessageBox("sample command 1 called"); break; case 1: AfxMessageBox("sample command 2 called"); break; } } <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // AddNodalLink // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "N3dGraph.h" CKObjectDeclaration *FillBehaviorAddNodalLinkDecl(); CKERROR CreateAddNodalLinkProto(CKBehaviorPrototype **); int AddNodalLink(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorAddNodalLinkDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Create Nodal Edge"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x47ea2c5c,0x5b6b2b81)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateAddNodalLinkProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("3D Transformations/Nodal Path"); return od; } CKERROR CreateAddNodalLinkProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("Create Nodal Edge"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Nodal Path",CKPGUID_GROUP); proto->DeclareInParameter("Start Node",CKPGUID_3DENTITY); proto->DeclareInParameter("End Node",CKPGUID_3DENTITY); proto->DeclareInParameter("Difficult",CKPGUID_FLOAT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( AddNodalLink ); *pproto = proto; return CK_OK; } int AddNodalLink(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; CKAttributeManager* attman = ctx->GetAttributeManager(); beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); CKGroup* group = (CKGroup*)beh->GetInputParameterObject(0); CKParameterOut* param = group->GetAttributeParameter(attman->GetAttributeTypeByName(Network3dName)); if(!param) throw "Given Group isn't a Network"; N3DGraph* graph; param->GetValue(&graph); CK3dEntity* s = (CK3dEntity*)beh->GetInputParameterObject(1); CK3dEntity* e = (CK3dEntity*)beh->GetInputParameterObject(2); float b; beh->GetInputParameterValue(3,&b); graph->InsertEdge(s,e,b); beh->ActivateOutput(0); return CKBR_OK; } <file_sep>#ifndef __P_CALLBACK_SIGNATURE_H__ #define __P_CALLBACK_SIGNATURE_H__ #include "pCommon.h" #include "IParameter.h" #include "vtBBHelper.h" #include "xDebugTools.h" //---------------------------------------------------------------- // // wheel contact modify callback inputs // typedef enum bInputsWheelContactModifyCallback { bbIWC_SrcObject, bbIWC_Point, bbIWC_Normal, bbIWC_Position, bbIWC_NormalForce, bbIWC_OtherMaterialIndex, bbIWC_Stub0, bbIWC_Stub1, }; static BBParameter pInMapWheelContactModifyCallback[]= { BB_PIN(bbIWC_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), BB_PIN(bbIWC_Point,CKPGUID_VECTOR,"point",""), BB_PIN(bbIWC_Normal,CKPGUID_VECTOR,"normal",""), BB_PIN(bbIWC_Position,CKPGUID_FLOAT,"position",""), BB_PIN(bbIWC_NormalForce,CKPGUID_FLOAT,"normalForce",""), BB_PIN(bbIWC_OtherMaterialIndex,CKPGUID_INT,"otherMaterialIndex",""), BB_PIN(bbIWC_Stub0,CKPGUID_INT,"stub0",""), BB_PIN(bbIWC_Stub1,CKPGUID_INT,"stub1",""), }; //---------------------------------------------------------------- // // wheel contact modify callback outputs // typedef enum bOutputsWheelContactModifyCallback { bbOWC_CreateContact, bbOWC_ModificationFlags, bbOWC_Point, bbOWC_Normal, bbOWC_Position, bbOWC_NormalForce, bbOWC_OtherMaterialIndex, bbOWC_Stub0, bbOWC_Stub1, }; static BBParameter pOutMapWheelContactModifyCallback[]= { BB_PIN(bbOWC_CreateContact,CKPGUID_BOOL,"createContact",""), BB_PIN(bbOWC_ModificationFlags,VTF_WHEEL_CONTACT_MODIFY_FLAGS,"modificationFlags",""), BB_PIN(bbOWC_Point,CKPGUID_VECTOR,"_point",""), BB_PIN(bbOWC_Normal,CKPGUID_VECTOR,"_normal",""), BB_PIN(bbOWC_Position,CKPGUID_FLOAT,"_position",""), BB_PIN(bbOWC_NormalForce,CKPGUID_FLOAT,"_normalForce",""), BB_PIN(bbOWC_OtherMaterialIndex,CKPGUID_INT,"_otherMaterialIndex",""), BB_PIN(bbOWC_Stub0,CKPGUID_INT,"_stub0",""), BB_PIN(bbOWC_Stub1,CKPGUID_INT,"_stub1",""), }; //---------------------------------------------------------------- // // contact modify callback ( has input and output ) // typedef enum bInputsContactModifyCallback { bbICM_SrcObject, bbICM_OtherObject, bbICM_MinImpulse, bbICM_MaxImpulse, bbICM_Error, bbICM_Target, bbICM_LP0, bbICM_LP1, bbICM_LO0, bbICM_LO1, bbICM_SF0, bbICM_SF1, bbICM_DF0, bbICM_DF1, bbICM_Restitution, }; static BBParameter pInMapContactModifyCallback[]= { BB_PIN(bbICM_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), BB_PIN(bbICM_OtherObject,CKPGUID_3DENTITY,"otherObject",""), BB_PIN(bbICM_MinImpulse,CKPGUID_FLOAT,"minImpulse",""), BB_PIN(bbICM_MaxImpulse,CKPGUID_FLOAT,"maxImpulse",""), BB_PIN(bbICM_Error,CKPGUID_VECTOR,"error",""), BB_PIN(bbICM_Target,CKPGUID_VECTOR,"target",""), BB_PIN(bbICM_LP0,CKPGUID_VECTOR,"localPosition0",""), BB_PIN(bbICM_LP1,CKPGUID_VECTOR,"localPosition1",""), BB_PIN(bbICM_LO0,CKPGUID_QUATERNION,"localOrientation0",""), BB_PIN(bbICM_LO0,CKPGUID_QUATERNION,"localOrientation1",""), BB_PIN(bbICM_SF0,CKPGUID_FLOAT,"staticFriction0",""), BB_PIN(bbICM_SF1,CKPGUID_FLOAT,"staticFriction1",""), BB_PIN(bbICM_DF0,CKPGUID_FLOAT,"dynamicFriction0",""), BB_PIN(bbICM_DF0,CKPGUID_FLOAT,"dynamicFriction1",""), BB_PIN(bbICM_DF0,CKPGUID_FLOAT,"restitution",""), }; //---------------------------------------------------------------- // // contact modify callback ( has input and output ) // typedef enum bOutputsContactModifyCallback { bbOCM_ModifyFlags, bbOCM_CreateContact, bbOCM_MinImpulse, bbOCM_MaxImpulse, bbOCM_Error, bbOCM_Target, bbOCM_LP0, bbOCM_LP1, bbOCM_LO0, bbOCM_LO1, bbOCM_SF0, bbOCM_SF1, bbOCM_DF0, bbOCM_DF1, bbOCM_Restitution, }; static BBParameter pOutMapContactModifyCallback[]= { BB_PIN(bbOCM_ModifyFlags,VTF_CONTACT_MODIFY_FLAGS,"_modifyFlags",""), BB_PIN(bbOCM_CreateContact,CKPGUID_BOOL,"createContact",""), BB_PIN(bbOCM_MinImpulse,CKPGUID_FLOAT,"_minImpulse",""), BB_PIN(bbOCM_MaxImpulse,CKPGUID_FLOAT,"_maxImpulse",""), BB_PIN(bbOCM_Error,CKPGUID_VECTOR,"_error",""), BB_PIN(bbOCM_Target,CKPGUID_VECTOR,"_target",""), BB_PIN(bbOCM_LP0,CKPGUID_VECTOR,"_localPosition0",""), BB_PIN(bbOCM_LP1,CKPGUID_VECTOR,"_localPosition1",""), BB_PIN(bbOCM_LO0,CKPGUID_QUATERNION,"_localOrientation0",""), BB_PIN(bbOCM_LO0,CKPGUID_QUATERNION,"_localOrientation1",""), BB_PIN(bbOCM_SF0,CKPGUID_FLOAT,"_staticFriction0",""), BB_PIN(bbOCM_SF1,CKPGUID_FLOAT,"_staticFriction1",""), BB_PIN(bbOCM_DF0,CKPGUID_FLOAT,"_dynamicFriction0",""), BB_PIN(bbOCM_DF0,CKPGUID_FLOAT,"_dynamicFriction1",""), BB_PIN(bbOCM_DF0,CKPGUID_FLOAT,"_restitution",""), }; //---------------------------------------------------------------- // // contact notify callback // typedef enum bInputsContactCallback { bbI_SrcObject, bbI_EventType, bbI_NormalForce, bbI_FForce, bbI_Point, bbI_PointNormalForce, bbI_FaceNormal, bbI_FaceIndex, bbI_Distance, bbI_OtherObject, }; static BBParameter pInMapContactCallback[]= { BB_PIN(bbI_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), BB_PIN(bbI_EventType,VTF_COLLISIONS_EVENT_MASK,"eventType",""), BB_PIN(bbI_FaceNormal,CKPGUID_VECTOR,"sumNormalForce",""), BB_PIN(bbI_FForce,CKPGUID_VECTOR,"sumFrictionForce",""), BB_PIN(bbI_Point,CKPGUID_VECTOR,"point",""), BB_PIN(bbI_PointNormalForce,CKPGUID_FLOAT,"pointNormalForce",""), BB_PIN(bbI_FaceNormal,CKPGUID_VECTOR,"faceNormal",""), BB_PIN(bbI_FaceIndex,CKPGUID_INT,"faceIndex",""), BB_PIN(bbI_Distance,CKPGUID_FLOAT,"distance",""), BB_PIN(bbI_OtherObject,CKPGUID_3DENTITY,"otherObject",""), }; //---------------------------------------------------------------- // // trigger // typedef enum bInputsTriggerCallback { bbIT_SrcObject, bbIT_EventType, bbIT_OtherObject, }; static BBParameter pInMapTriggerCallback[]= { BB_PIN(bbIT_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), BB_PIN(bbIT_EventType,VTF_TRIGGER,"eventType",""), BB_PIN(bbIT_OtherObject,CKPGUID_3DENTITY,"otherObject",""), }; //---------------------------------------------------------------- // // trigger // typedef enum bInputsRaycastHitCallback { bbRH_SrcObject, bbRH_OtherObject, bbRH_WorldImpact, bbRH_WorldNormal, bbRH_FIndex, bbRH_FInternalIdex, bbRH_Distance, bbRH_UV, bbRH_Material, bbRH_Flags, }; typedef enum bInputsJointBreakCallback { bbJB_SrcObject, bbJB_OtherObject, bbJB_Force, }; static BBParameter pInMapRaycastHitCallback[]= { BB_PIN(bbRH_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), BB_PIN(bbRH_OtherObject,CKPGUID_3DENTITY,"otherObject",""), BB_PIN(bbRH_WorldImpact,CKPGUID_VECTOR,"impact",""), BB_PIN(bbRH_WorldNormal,CKPGUID_VECTOR,"normal",""), BB_PIN(bbRH_FIndex,CKPGUID_INT,"faceIndex",""), BB_PIN(bbRH_FInternalIdex,CKPGUID_INT,"faceInternalIndex",""), BB_PIN(bbRH_Distance,CKPGUID_FLOAT,"distance",""), BB_PIN(bbRH_UV,CKPGUID_2DVECTOR,"uv",""), BB_PIN(bbRH_Material,CKPGUID_INT,"material",""), BB_PIN(bbRH_Flags,VTF_RAY_HINTS,"flags",""), }; static BBParameter pInMapJointBreakCallback[]= { BB_PIN(bbJB_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), BB_PIN(bbJB_OtherObject,CKPGUID_3DENTITY,"otherObject",""), BB_PIN(bbJB_Force,CKPGUID_FLOAT,"Break Force",""), }; #endif<file_sep>#include "xDistributedPoint2F.h" #include "xMathStream.h" #include "xPredictionSetting.h" #include "xDistributedPropertyInfo.h" uxString xDistributedPoint2F::print(TNL::BitSet32 flags) { return uxString(); } void xDistributedPoint2F::updateFromServer(TNL::BitStream *stream) { xMath::stream::mathRead(*stream,&mLastServerValue); if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) xMath::stream::mathRead(*stream,&mLastServerDifference); setValueState(E_DV_UPDATED); } void xDistributedPoint2F::updateGhostValue(TNL::BitStream *stream) { xMath::stream::mathWrite(*stream,mCurrentValue); if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) xMath::stream::mathWrite(*stream,mDifference); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedPoint2F::unpack(TNL::BitStream *bstream,float sendersOneWayTime) { if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { sendersOneWayTime *= 0.001f; Point2F p; xMath::stream::mathRead(*bstream,&p); Point2F v; xMath::stream::mathRead(*bstream,&v); Point2F predictedPos = p + v * sendersOneWayTime; setOwnersOneWayTime(sendersOneWayTime); mLastValue = mCurrentValue; mCurrentValue = predictedPos; mDifference= mCurrentValue - mLastValue; } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { Point2F p; xMath::stream::mathRead(*bstream,&p); mLastValue = mCurrentValue; mLastServerValue =p; mCurrentValue = p; } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ void xDistributedPoint2F::pack(TNL::BitStream *bstream) { xMath::stream::mathWrite(*bstream,mCurrentValue); if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) xMath::stream::mathWrite(*bstream,mDifference); int flags = getFlags(); flags &= (~E_DP_NEEDS_SEND); setFlags(flags); } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ bool xDistributedPoint2F::updateValue(Point2F value,xTimeType currentTime) { bool result = false; mLastTime = mCurrentTime; mCurrentTime = currentTime; mLastDeltaTime = mCurrentTime - mLastTime; mLastValue = mCurrentValue; mCurrentValue = value; mDifference = mCurrentValue - mLastValue; mThresoldTicker +=mLastDeltaTime; float lengthDiff = fabsf(mDifference.len()); float timeDiffMs = ((float)mThresoldTicker) / 1000.f; int flags = getFlags(); flags =E_DP_OK; if (this->getPropertyInfo()->mPredictionType == E_PTYPE_PREDICTED) { if (lengthDiff > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime()) { flags =E_DP_NEEDS_SEND; result = true ; } } Point2F serverDiff = mCurrentValue-mLastServerValue ; if ( fabsf( serverDiff.len() ) > getPredictionSettings()->getMinDifference() ) { if (mThresoldTicker2 > (getPredictionSettings()->getMinSendTime() * 0.2f) ) { flags =E_DP_NEEDS_SEND; result = true ; } } if (mThresoldTicker2 > getPredictionSettings()->getMinSendTime()) { mThresoldTicker2 = 0 ; mThresoldTicker = 0; } } if (this->getPropertyInfo()->mPredictionType == E_PTYPE_RELIABLE) { flags =E_DP_NEEDS_SEND; result = true ; mLastValue = value; mCurrentValue = value; } setFlags(flags); return result; }<file_sep>#include "CKAll.h" #include "vtNetworkManager.h" #include <vtTools.h> #include "xDistTools.h" #include "xDistTypesAll.h" #include "xMathTools.h" #include "xDistributed3DObject.h" #include "xDistributedProperty.h" #include "xDistributedPropertyInfo.h" #include "xNetInterface.h" #include "vtConnection.h" #include "xDistributedBaseClass.h" #include "xDistributed3DObjectClass.h" #include "IDistributedClasses.h" #include "xDOStructs.h" #include "IDistributedObjectsInterface.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint3F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedString.h" #include "xDistributedInteger.h" #include "xLogger.h" #include "vtLogTools.h" CKObjectDeclaration *FillBehaviorConnectToServerDecl(); CKERROR CreateConnectToServerProto(CKBehaviorPrototype **); int ConnectToServer(const CKBehaviorContext& behcontext); CKERROR ConnectToServerCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorConnectToServerDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("NConnect"); od->SetDescription("Connects to a Server"); od->SetCategory("TNL/Server"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x69b86522,0x34cf3563)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateConnectToServerProto); od->SetCompatibleClassId(CKCID_OBJECT); return od; } typedef enum BB_INPAR { BB_IP_HOSTS, BB_IP_MODULES, BB_IP_LOGIN, BB_IP_PASSWORD }; typedef enum BB_OT { BB_O_CONNECTED, BB_O_WAITING, BB_O_TIME_OUT, BB_O_ERROR, BB_O_IN_USE, }; typedef enum BB_OP { BB_OP_CONNECTION_ID, BB_OP_HOST, BB_OP_PORT, BB_OP_ERROR, BB_OP_MAX_PLAYERS, BB_OP_CLIENT_ID }; CKERROR CreateConnectToServerProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("NConnect"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Connect"); proto->DeclareOutput("Connected"); proto->DeclareOutput("Waiting for Answer"); proto->DeclareOutput("Timeout"); proto->DeclareOutput("Error"); proto->DeclareOutput("Connection In Use"); proto->DeclareInParameter("Hosts", CKPGUID_DATAARRAY, "Hosts"); proto->DeclareInParameter("Modules", CKPGUID_DATAARRAY, "Modules"); proto->DeclareInParameter("Login", CKPGUID_STRING, "Player"); proto->DeclareInParameter("Password", CKPGUID_STRING, "Player"); proto->DeclareOutParameter("Connection ID", CKPGUID_INT, "-1"); proto->DeclareOutParameter("Host", CKPGUID_STRING, "None"); proto->DeclareOutParameter("Port", CKPGUID_INT, "-1"); proto->DeclareOutParameter("Error", VTE_NETWORK_ERROR, "0"); proto->DeclareOutParameter("Client ID", CKPGUID_INT, "-1"); proto->DeclareSetting("Connection Timeout", CKPGUID_FLOAT,"2000"); proto->DeclareLocalParameter("currentArrayIndex", CKPGUID_INT,0 ); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(ConnectToServer); proto->SetBehaviorCallbackFct(ConnectToServerCB); *pproto = proto; return CK_OK; } #include "vtLogTools.h" int ConnectToServer(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; using namespace vtTools::BehaviorTools; vtNetworkManager *nman = GetNM(); bbNoError(E_NWE_OK); CKDataArray* hostsarray = static_cast<CKDataArray*>(beh->GetInputParameterObject(0)); if (!hostsarray) { bbError(E_NWE_INVALID_PARAMETER); return FALSE; } int arrayIndex = 0; beh->GetLocalParameterValue(1,&arrayIndex); float timeOut = 0.0f; beh->GetLocalParameterValue(0,&timeOut); /************************************************************************/ /* */ /************************************************************************/ if (!nman->GetClientNetInterface()) { nman->CreateClient(true,0,NULL); nman->GetClientNetInterface()->setConnectionTimeOut(timeOut); } float elapsed = nman->GetClientNetInterface()->getElapsedConnectionTime() + behcontext.DeltaTime; nman->GetClientNetInterface()->setElapsedConnectionTime(elapsed); if (arrayIndex > hostsarray->GetRowCount() -1 ) { arrayIndex = 0; beh->SetLocalParameterValue(1,&arrayIndex); bbError(E_NWE_NO_SERVER); return FALSE; } if (nman->GetClientNetInterface()->isConnected()) { beh->ActivateOutput(4); return FALSE; } /************************************************************************/ /* first start ? */ /************************************************************************/ if (!nman->GetClientNetInterface()->isConnectionInProgress()) { CKCHAR fixedBuffer[256]; CKSTRING hosts = fixedBuffer; hostsarray->GetElementStringValue(arrayIndex,0,hosts); TNL::Address addr(hosts); if (strlen(hosts)) { xLogger::xLog(ELOGINFO,E_LI_CONNECTION,"connecting to server:%s",fixedBuffer); } nman->ConnectToServer(true,hosts); nman->GetClientNetInterface()->sendPing(hosts); nman->GetClientNetInterface()->setConnectionInProgress(true); } /************************************************************************/ /* we are already trying to connect : */ /************************************************************************/ if(nman->GetClientNetInterface()->isConnectionInProgress()) { if (nman->GetClientNetInterface()->getConnection()) { ///////////////////////////////////////////////////////////////////////// //connection established ? if (nman->GetClientNetInterface()->isValid()) { nman->GetClientNetInterface()->setConnectionInProgress(false); TNL::Address addr = nman->GetClientNetInterface()->getConnection()->getNetAddress(); arrayIndex = 0; beh->SetLocalParameterValue(1,&arrayIndex); nman->GetClientNetInterface()->setConnected(true); /************************************************************************/ /* we set the connection parameters : */ /************************************************************************/ CKCHAR fixedBuffer[256]; CKSTRING hosts = fixedBuffer; hostsarray->GetElementStringValue(arrayIndex,0,hosts); CKParameterOut *pout = beh->GetOutputParameter(1); pout->SetStringValue(hosts); ////////////////////////////////////////////////////////////////////////// int userID = nman->GetClientNetInterface()->getConnection()->getUserID(); int connectionID = nman->GetClientNetInterface()->getConnectionList().size(); beh->SetOutputParameterValue(0,&connectionID); beh->SetOutputParameterValue(4,&userID); beh->ActivateOutput(0); return CKBR_OK; } ////////////////////////////////////////////////////////////////////////// // we check the time out if (nman->GetClientNetInterface()->getElapsedConnectionTime() > nman->GetClientNetInterface()->getConnectionTimeOut() ) { // nman->GetClientNetInterface()->setElapsedConnectionTime(0.0f); nman->GetClientNetInterface()->setConnectionInProgress(false); //we delete all our data : if (nman->GetClientNetInterface()->getConnection()) { nman->GetClientNetInterface()->getConnection()->disconnect("keiner"); nman->GetClientNetInterface()->setConnection(NULL); } //more hosts ? if (arrayIndex < hostsarray->GetRowCount() ) { arrayIndex++; beh->SetLocalParameterValue(1,&arrayIndex); //beh->ActivateOutput(2); }else { xLogger::xLog(ELOGWARNING,E_LI_CONNECTION,"No server was available"); bbError(E_NWE_NO_SERVER); arrayIndex = 0; beh->SetLocalParameterValue(1,&arrayIndex); beh->ActivateOutput(2); return FALSE; } }else { beh->ActivateOutput(1); } } } return CKBR_ACTIVATENEXTFRAME; } CKERROR ConnectToServerCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (!beo) { return CKBR_OWNERERROR; } if (behcontext.CallbackMessage==CKM_BEHAVIORATTACH) { int arrayIndex = 0; beh->SetLocalParameterValue(1,&arrayIndex); } return CKBR_OK; }<file_sep>#include <CPStdAfx.h> #include "CustomPlayerApp.h" #include "CustomPlayer.h" #include "CustomPlayerDefines.h" #include "resourceplayer.h" #include "CustomPlayerDialogGraphicPage.h" #include "CustomPlayerDialog.h" IMPLEMENT_DYNAMIC(CustomPlayerDialog, CPropertySheet) BEGIN_MESSAGE_MAP(CustomPlayerDialog, CPropertySheet) //{{AFX_MSG_MAP(CModalShapePropSheet) ON_COMMAND(ID_APPLY_NOW, OnApplyNow) //}}AFX_MSG_MAP END_MESSAGE_MAP() CustomPlayerDialogAboutPage*aboutPage=NULL; CustomPlayerDialogGraphicPage *stylePage=NULL; CustomPlayerDialogErrorPage *errorPage=NULL; //************************************ // Method: CModalShapePropSheet // FullName: CModalShapePropSheet::CModalShapePropSheet // Access: public // Returns: // Qualifier: : CPropertySheet(AFX_IDS_APP_TITLE, pWndParent) // Parameter: CWnd* pWndParent // Parameter: int displayErrorPage // Parameter: CString errorText //************************************ CustomPlayerDialog::CustomPlayerDialog(CWnd* pWndParent,CString errorText) : CPropertySheet(AFX_IDS_APP_TITLE, pWndParent) { if (GetPlayer().GetPAppStyle()->g_ShowConfigTab) { AddPage(&m_GraphicPage); stylePage = &m_GraphicPage; } if (strlen(errorText)) { AddPage(&m_errorPage); errorPage = &m_errorPage; m_ErrorText = errorText; m_errorPage.errorText = errorText; } if (GetPlayer().GetPAppStyle()->g_ShowAboutTab) { AddPage(&m_aboutPage); aboutPage = &m_aboutPage; } } bool _checkOpenGLVersion(XString driverName) { vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); XArray<XString>::Iterator begin = ewinfo->g_OpenGLMask.Begin(); XArray<XString>::Iterator end = ewinfo->g_OpenGLMask.End(); while(begin!=end) { XString supportedOpenglVersionString = *begin; if (supportedOpenglVersionString.Length()) { if (driverName.Contains(supportedOpenglVersionString)) { return true; } } begin++; } return false; } //************************************ // Method: _UpdateDriverList // FullName: _UpdateDriverList // Access: public // Returns: void // Qualifier: // Parameter: int DriverId //************************************ void _UpdateDriverList(int DriverId) { vtPlayer::Structs::xSEnginePointers* ep = GetPlayer().GetEnginePointers(); vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); int count = GetPlayer().GetEnginePointers()->TheRenderManager->GetRenderDriverCount(); ////////////////////////////////////////////////////////////////////////// //we fill the driver list : for (int i=0;i<count;i++) { VxDriverDesc *desc=ep->TheRenderManager->GetRenderDriverDescription(i); XString driverName = desc->DriverName.CStr(); ////////////////////////////////////////////////////////////////////////// //we are using an OpenGL version restriction, the versions are specified in the player.ini seperated by a comma : 1.1,2.0 if (driverName.Contains("OpenGL")) { if (!_checkOpenGLVersion(driverName)) { continue; } } ////////////////////////////////////////////////////////////////////////// //we add it to the drivers combo box : stylePage->m_Driver.AddString(desc->DriverName.CStr()); //we set the driver in the listbox to driver we found in the player.ini if (i==DriverId) { stylePage->m_Driver.SetCurSel(i); } } } void _UpdateResolutionLists(HWND hwndDlg,int DriverId) { vtPlayer::Structs::xSEnginePointers* ep = GetPlayer().GetEnginePointers(); vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); int count = GetPlayer().GetEnginePointers()->TheRenderManager->GetRenderDriverCount(); int i=0; char ChaineW[256]; bool driverfound = false; int targetDriver = ewinfo->g_GoFullScreen ? ewinfo->g_FullScreenDriver : ewinfo->g_WindowedDriver ; VxDriverDesc *MainDesc=ep->TheRenderManager->GetRenderDriverDescription(targetDriver); XArray<int>bpps;//temporary storage to avoid doubles in the list XArray<int>rrates;//temporary storage to avoid doubles in the list XArray<int>modes;//temporary storage to avoid doubles in the list ////////////////////////////////////////////////////////////////////////// //we only display window resolutions according to the current display settings: HDC hdc; PAINTSTRUCT ps ; hdc = BeginPaint (hwndDlg, &ps) ; int currentDesktopBpp = GetDeviceCaps (hdc, BITSPIXEL) ; int currentDesktopRRate = GetDeviceCaps (hdc, VREFRESH) ; EndPaint(hwndDlg,&ps); ////////////////////////////////////////////////////////////////////////// //we fill the bpp list for (i=0;i<MainDesc->DisplayModes.Size();i++) { XArray<int>::Iterator it = bpps.Find(MainDesc->DisplayModes[i].Bpp); if( it == bpps.End() ) { bpps.PushBack(MainDesc->DisplayModes[i].Bpp); sprintf(ChaineW,"%d",MainDesc->DisplayModes[i].Bpp); stylePage->m_Bpps.AddString(ChaineW); if (ewinfo->g_Bpp== MainDesc->DisplayModes[i].Bpp) { stylePage->m_Bpps.SetCurSel(stylePage->m_Bpps.GetCount()-1); } } ////////////////////////////////////////////////////////////////////////// // we fill the refresh list : it = rrates.Find(MainDesc->DisplayModes[i].RefreshRate); if( it == rrates.End() ) { rrates.PushBack(MainDesc->DisplayModes[i].RefreshRate); sprintf(ChaineW,"%d",MainDesc->DisplayModes[i].RefreshRate); stylePage->m_RRates.AddString(ChaineW); if (ewinfo->g_RefreshRate == MainDesc->DisplayModes[i].RefreshRate) { stylePage->m_RRates.SetCurSel(stylePage->m_RRates.GetCount()-1); } } ////////////////////////////////////////////////////////////////////////// //we fill the resolution list, pseudo code : // create a string of the resolution given by the description "MainDesc", : "WidthHeight" or ie.: "800600" XString mode;mode<<MainDesc->DisplayModes[i].Width<<MainDesc->DisplayModes[i].Height; // have a look in temporary array whether it already exists : it = modes.Find(mode.ToInt()); // the iterator couldn't find the resolution, so add it to the modes (full screen + windowed) combo box if( it == modes.End() ) { // create the final string for combo box item : sprintf(ChaineW,"%d x %d",MainDesc->DisplayModes[i].Width,MainDesc->DisplayModes[i].Height); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //we have a resolution restriction ? if (ewinfo->g_HasResMask) { // in the player.ini file you have two entries : "XResolutions" and "YResolutions", ie.: // XResolutions = 1024,800 // YResolutions = 768,600 // where you must have always an appropriate value for x or y ! // we check that the given width from the MainDescr is in the resolution mask "ewinfo->g_ResMaskArrayX" // which is filled during the startup in the function CCustomPlayer::PLoadEngineWindowProperties (CustomPlayerProfileXML.cpp) XArray<int>::Iterator itx = ewinfo->g_ResMaskArrayX.Find( MainDesc->DisplayModes[i].Width); // if not, we just skip the current MainDescr : if(itx==ewinfo->g_ResMaskArrayX.End()) { continue; }else { //Ok, the given width is in the mask, so we also check that height matches : // we take the appropriate y value from the mask y-array : int widthsIndex = ewinfo->g_ResMaskArrayX.GetPosition(MainDesc->DisplayModes[i].Width) ; int appropriateYValue = *ewinfo->g_ResMaskArrayY.At(widthsIndex); if(appropriateYValue !=MainDesc->DisplayModes[i].Height ) { //No !, so we can skip the MainDescr. continue; } } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // add the modes string representation to our temp array : modes.PushBack(mode.ToInt()); // create the final string for combo box item : //sprintf(ChaineW,"%d x %d",MainDesc->DisplayModes[i].Width,MainDesc->DisplayModes[i].Height); // now add it to full screen resolution combo box : stylePage->m_FModes.AddString(ChaineW); //and to the windowed resolution combo box : stylePage->m_windowMode.AddString(ChaineW); // the current resolution equals the player.ini full screen value? so we set it as the selected one in the combo box : if (ewinfo->g_Height == MainDesc->DisplayModes[i].Height && ewinfo->g_Width == MainDesc->DisplayModes[i].Width ) { stylePage->m_FModes.SetCurSel( stylePage->m_FModes.GetCount()-1 ); } // the current resolution equals the player.ini windowed resolution value ? so we set it as the selected one in the combo box : if (ewinfo->g_HeightW == MainDesc->DisplayModes[i].Height && ewinfo->g_WidthW == MainDesc->DisplayModes[i].Width ) { stylePage->m_windowMode.SetCurSel( stylePage->m_windowMode.GetCount()-1 ); } }else { // add the modes string representation to our temp array : modes.PushBack(mode.ToInt()); // create the final string for combo box item : //sprintf(ChaineW,"%d x %d",MainDesc->DisplayModes[i].Width,MainDesc->DisplayModes[i].Height); // now add it to full screen resolution combo box : stylePage->m_FModes.AddString(ChaineW); //and to the windowed resolution combo box : stylePage->m_windowMode.AddString(ChaineW); // the current resolution equals the player.ini full screen value? so we set it as the selected one in the combo box : if (ewinfo->g_Height == MainDesc->DisplayModes[i].Height && ewinfo->g_Width == MainDesc->DisplayModes[i].Width ) { stylePage->m_FModes.SetCurSel( stylePage->m_FModes.GetCount()-1 ); } // the current resolution equals the player.ini windowed resolution value ? so we set it as the selected one in the combo box : if (ewinfo->g_HeightW == MainDesc->DisplayModes[i].Height && ewinfo->g_WidthW == MainDesc->DisplayModes[i].Width ) { stylePage->m_windowMode.SetCurSel( stylePage->m_windowMode.GetCount()-1 ); } } } } } BOOL CustomPlayerDialog::OnInitDialog() { BOOL bResult = CPropertySheet::OnInitDialog(); // add the preview window to the property sheet. CRect rectWnd; GetWindowRect(rectWnd); SetWindowPos(NULL, 0, 0, rectWnd.Width() , rectWnd.Height(), SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); CenterWindow(); if(GetPlayer().GetPAppStyle()->g_ShowConfigTab) { vtPlayer::Structs::xSEnginePointers* ep = GetPlayer().GetEnginePointers(); vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); if(ewinfo->g_GoFullScreen) _UpdateDriverList(ewinfo->g_FullScreenDriver); else _UpdateDriverList(ewinfo->g_WindowedDriver); if(ewinfo->g_GoFullScreen) { _UpdateResolutionLists(NULL,ewinfo->g_FullScreenDriver); if (ewinfo->g_FullScreenDriver < stylePage->m_Driver.GetCount() ) { stylePage->m_Driver.SetCurSel( ewinfo->g_FullScreenDriver); } } else{ _UpdateResolutionLists(NULL,ewinfo->g_WindowedDriver); if (ewinfo->g_WindowedDriver < stylePage->m_Driver.GetCount() ) { stylePage->m_Driver.SetCurSel( ewinfo->g_WindowedDriver ); } } m_errorPage.errorText = m_ErrorText; stylePage->m_CB_FSSA.AddString("0"); stylePage->m_CB_FSSA.AddString("1"); stylePage->m_CB_FSSA.AddString("2"); stylePage->m_CB_FSSA.AddString("4"); stylePage->m_CB_FSSA.AddString("8"); stylePage->m_CB_FSSA.SetCurSel(ewinfo->FSSA/2); stylePage->m_CB_FSSA.UpdateData(); stylePage->m_Bpps.SetCurSel(ewinfo->g_Bpp); stylePage->m_FullScreenBtn.SetCheck(ewinfo->g_GoFullScreen); } if(GetPlayer().GetPAppStyle()->g_ShowAboutTab) { this->SetActivePage((CPropertyPage*)&m_aboutPage); } if ( m_ErrorText.GetLength() ) { this->SetActivePage((CPropertyPage*)&m_errorPage); } return bResult; } void CustomPlayerDialog::OnApplyNow() { Default(); vtPlayer::Structs::xSEnginePointers* ep = GetPlayer().GetEnginePointers(); vtPlayer::Structs::xSEngineWindowInfo* ewinfo = GetPlayer().GetEngineWindowInfo(); ////////////////////////////////////////////////////////////////////////// CString bpp; stylePage->m_Bpps.GetLBText(stylePage->m_Bpps.GetCurSel(),bpp); XString oBpp(bpp); ewinfo->g_Bpp = oBpp.ToInt(); ////////////////////////////////////////////////////////////////////////// CString rr; stylePage->m_RRates.GetLBText(stylePage->m_RRates.GetCurSel(),rr); XString oRR(rr); ewinfo->g_RefreshRate= oRR.ToInt(); ////////////////////////////////////////////////////////////////////////// CString fssa; stylePage->m_CB_FSSA.GetLBText(stylePage->m_CB_FSSA.GetCurSel(),fssa); XString oFSSA(fssa); ewinfo->FSSA= oFSSA.ToInt(); if (ewinfo->g_GoFullScreen) ewinfo->g_FullScreenDriver = stylePage->m_Driver.GetCurSel(); else ewinfo->g_WindowedDriver = stylePage->m_Driver.GetCurSel(); ////////////////////////////////////////////////////////////////////////// ewinfo->g_GoFullScreen = stylePage->m_FullScreenBtn.GetCheck(); ////////////////////////////////////////////////////////////////////////// CString fmode; stylePage->m_FModes.GetLBText(stylePage->m_FModes.GetCurSel(),fmode); XStringTokenizer tokizer(fmode, "x"); const char*tok = NULL; tok = tokizer.NextToken(tok); XString width(tok); tok = tokizer.NextToken(tok); XString height(tok); ewinfo->g_Width = width.ToInt(); ewinfo->g_Height = height.ToInt(); { CString wmode; stylePage->m_windowMode.GetLBText(stylePage->m_windowMode.GetCurSel(),wmode); XStringTokenizer tokizer(wmode, "x"); const char*tok = NULL; tok = tokizer.NextToken(tok); XString width(tok); tok = tokizer.NextToken(tok); XString height(tok); ewinfo->g_WidthW = width.ToInt(); ewinfo->g_HeightW = height.ToInt(); } GetPlayer().PSaveEngineWindowProperties(CUSTOM_PLAYER_CONFIG_FILE,*GetPlayer().GetEngineWindowInfo()); } <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SetNodalDifficult // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "N3dGraph.h" CKObjectDeclaration *FillBehaviorSetNodalDifficultDecl(); CKERROR CreateSetNodalDifficultProto(CKBehaviorPrototype **); int SetNodalDifficult(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSetNodalDifficultDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("SetNodalDifficult"); od->SetDescription(""); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x77a61036,0x47496bde)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetNodalDifficultProto); od->SetCompatibleClassId(CKCID_BEOBJECT); od->SetCategory("3D Transformations/Nodal Path"); return od; } CKERROR CreateSetNodalDifficultProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = NULL; proto = CreateCKBehaviorPrototype("SetNodalDifficult"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Nodal Path",CKPGUID_GROUP); proto->DeclareInParameter("Node",CKPGUID_3DENTITY); proto->DeclareInParameter("Difficult",CKPGUID_FLOAT); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction( SetNodalDifficult ); *pproto = proto; return CK_OK; } int SetNodalDifficult(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; CKAttributeManager* attman = ctx->GetAttributeManager(); beh->ActivateInput(0,FALSE); beh->ActivateOutput(0); CKGroup* group = (CKGroup*)beh->GetInputParameterObject(0); CKParameterOut* param = group->GetAttributeParameter(attman->GetAttributeTypeByName(Network3dName)); if(!param) throw "Given Group isn't a Network"; N3DGraph* graph; param->GetValue(&graph); CK3dEntity* s = (CK3dEntity*)beh->GetInputParameterObject(1); float b; beh->GetInputParameterValue(2,&b); graph->SetDifficult(s,b); beh->ActivateOutput(0); return CKBR_OK; } <file_sep>#ifndef __P_FLUID_RENDER_SETTINGS_H__ #define __P_FLUID_RENDER_SETTINGS_H__ #include "pTypes.h" class MODULE_API pFluidRenderSettings { public: pFluidRenderSettings(); // Constructor pFluidRenderSettings(CKContext* ctx,CK_ID entity,char* name); // the emitter 3d entity CK_ID m_Entity; CK_ID m_Texture; CK_ID m_Group; int m_MessageType; VxBbox m_EntityBbox; pParticleRenderType mRenderType; int m_MaximumParticles; // total number of particles int totalParticles; // particles already emitted int particleCount; // emits per frame int emitsPerFrame; // emits variation int emitsVar; // medium lifeSpan float m_Life; // life variation float m_LifeVariation; // trailing particles int m_TrailCount; // historic of recent particles. // render callback int (*m_RenderParticlesCallback)(CKRenderContext *dev,CKRenderObject *mov,void *arg); void SetState(CKRenderContext* dev,CKBOOL gouraud = FALSE); // NULL terminated linked list // the particles pool BYTE* m_BackPool; // start size float m_StartSize; float m_StartSizeVar; // end size float m_EndSize; float m_EndSizeVar; // Blend Modes VXBLEND_MODE m_SrcBlend; VXBLEND_MODE m_DestBlend; // Colors ///////////// VxColor m_StartColor; VxColor m_StartColorVar; VxColor m_EndColor; VxColor m_EndColorVar; // Texture ///////////// int m_InitialTextureFrame; int m_InitialTextureFrameVariance; int m_SpeedTextureFrame; int m_SpeedTextureFrameVariance; int m_TextureFrameCount; int m_TextureFrameloop; // FLAGS int m_EvolutionsFlags; int m_VariancesFlags; int m_InteractorsFlags; int m_DeflectorsFlags; int m_RenderMode; // Mesh CK_ID m_Mesh; // Context CKContext* m_Context; pFluidEmitter* mEmitter; pFluidEmitter* getEmitter() const { return mEmitter; } void setEmitter(pFluidEmitter* val) { mEmitter = val; } void setToDefault(); struct ParticleHistoric { inline ParticleHistoric() {} inline ParticleHistoric(unsigned int size) : start(0), count(0) { particles.Resize(size); } int start; int count; XArray<pParticle*> particles; }; // Old particles. XClassArray<ParticleHistoric> old_pos; ParticleHistoric &GetParticleHistoric(pParticle *part); CKBehavior* m_Behavior; volatile bool hasBeenRendered; //used for cases where we compute once and render twice volatile bool hasBeenEnqueud; //used for cases where we compute once and render twice protected: private: }; #endif<file_sep>#ifndef _XSTRING_H__ #define _XSTRING_H__ #include <tchar.h> #include <wchar.h> #include <stdlib.h> #include <string> typedef char TAnsiChar; #ifdef _WIN32 typedef wchar_t TUnicodeChar; #else typedef unsigned short TUnicodeChar; #endif // // Define an alias for the native character data type // #ifdef _UNICODE typedef TUnicodeChar TChar; #else typedef TAnsiChar TChar; #endif // // This macro creates an ASCII string (actually a no-op) // #define __xA(x) (x) // // This macro creates a Unicode string by adding the magic L before the string // #define __xU(x) (L##x) // // Define an alias for building a string in the native format // #ifdef _UNICODE #define __xT __xU #else #define __xT __xA #endif class xString { public: // typedef xString uniStringPtr; //======================================================= // // Construction and destruction // //======================================================= // // Accessors // TChar *GetString(); const TAnsiChar *CStr() const; int GetLength()const; bool IsNull() const; bool IsValidIndex(const int Index)const ; //======================================================= // // Regular transformation functions // int Compare(const xString& ins, bool IgnoreCase = false)const; bool Find(xString& Str, int& Pos, bool IgnoreCase=false) const ; void Delete(int Pos, int Count); void Insert(int Pos, TChar c); void Insert(int Pos, const xString& input); xString GetSubString(int Start, int Count, xString& Dest); // Crops out a substring. //======================================================= // // Special transformation functions // void VarArg(TChar *Format, ...); void EatLeadingWhitespace(); void EatTrailingWhitespace() ; //======================================================= // // Conversion functions // TAnsiChar *ToAnsi(TAnsiChar *Buffer, int BufferLen) const; TUnicodeChar *ToUnicode(TUnicodeChar *Buffer, int BufferLen) const; int ToInt() const; //======================================================= xString(); xString(const xString& input); xString(const TUnicodeChar *input); xString(int size) { Size = size; Len = size -1; Text = AllocStr(Size); } virtual ~xString(); //======================================================= // // Concatenation operators // // Concatenates two strings (see text) friend xString operator +(const xString& Str1, const xString& Str2); // Concatenates two strings (see text) /* xString& operator +(const TChar& Str,const xString& Str1); xString& operator +(const char left[],const xString &right); xString& operator +(const xString &right,const char left[]); xString& operator +(const xString &right); */ /* xString& operator +=(const xString& String) // Adds another string to the end of the { // current one. if (String.Len > 0) { Grow(String.Len); _tcsncpy(&Text[Len], String.Text, String.Len); Len += String.Len; } }*/ //xString& operator +=(const char input[]); void AssignFrom(const TAnsiChar *String) // Constructor building a Unicode string from a regular C { // string in ANSI format (used for doing conversions). if (String == NULL) // Early out if string is NULL { Text = NULL; Size = Len = 0; return; } Size = strlen(String) + 1; // Use ANSI strlen function Len = Size-1; Text = AllocStr(Size); for (int i=0 ; i<Len ; i++) // Convert ANSI->Unicode char-by-char Text[i] = (TUnicodeChar)String[i]; Text[Len] = __xA('\0'); } xString& operator +=(const xString& String) // Adds another string to the end of the { EatLeadingWhitespace(); EatTrailingWhitespace(); //Insert(Len,String); int len2 = strlen(CStr()); std::string a1; a1+=CStr(); a1+= String.CStr(); FreeStr(Text); AssignFrom(a1.c_str()); return *this; // current one. if (String.Len > 0) { Grow(String.Len); strncpy(&Text[Len], String.Text, 2); Len += String.Len; } return *this; } /*xString& operator +=(const char* String) // Adds another string to the end of the { return *this << xString(String); }*/ //======================================================= // // Access operators // TAnsiChar*Str(); operator TAnsiChar*() { /*TAnsiChar*out =new TAnsiChar[Size]; ToAnsi(out,Size); return out ? out : NULL ;*/ return Text; } operator TUnicodeChar *() const; TChar& xString::operator [](int Pos); // // Assignment operators // void operator =(const xString& String) // Sets this string to the contents of another string. { AssignFrom(String); } #ifndef _UNICODE void operator =(const TAnsiChar *String) // Sets this string to the contents of a character array { // in ANSI format (only included in Unicode builds) if (String == NULL) { Text = NULL; Size = Len = 0; return; } Size = strlen(String) + 1; // Use ANSI strlen function Len = Size-1; Text = AllocStr(Size); for (int i=0 ; i<Len ; i++) // Convert ANSI->Unicode char-by-char Text[i] = (TUnicodeChar)String[i]; Text[Len] = __xA('\0'); } xString(const TAnsiChar *String) // Constructor building a Unicode string from a regular C { // string in ANSI format (used for doing conversions). if (String == NULL) // Early out if string is NULL { Text = NULL; Size = Len = 0; return; } Size = strlen(String) + 1; // Use ANSI strlen function Len = Size-1; Text = AllocStr(Size); for (int i=0 ; i<Len ; i++) // Convert ANSI->Unicode char-by-char Text[i] = (TUnicodeChar)String[i]; Text[Len] = __xA('\0'); } #else void operator =(const TUnicodeChar *String) // Sets this string to the contents of a character array { // in Unicode format (only included in ANSI builds) if (String == NULL) { Text = NULL; Size = Len = 0; return; } Size = wcslen(String) + 1; // Use Unicode wcslen function Len = Size-1; Text = AllocStr(Size); for (int i=0 ; i<Len ; i++) // Convert Unicode->ANSI char-by-char Text[i] = (TAnsiChar)String[i]; Text[Len] = __xA('\0'); } #endif //======================================================= // // Comparison operators (operates through Compare()). // Functions exist for comparing both string objects and character arrays. // bool operator < (const xString& Str) const { return (bool)(Compare(Str) == -1); } bool operator > (const xString& Str) const { return (bool)(Compare(Str) == 1); } bool operator <=(const xString& Str) const { return (bool)(Compare(Str) != 1); } bool operator >=(const xString& Str) const { return (bool)(Compare(Str) != -1); } bool operator ==(const xString& Str) const { return (bool)(Compare(Str) == 0); } bool operator !=(const xString& Str) const { return (bool)(Compare(Str) != 0); } bool operator < (const TChar *Chr) const { return (bool)(Compare(xString(Chr)) == -1); } bool operator > (const TChar *Chr) const { return (bool)(Compare(xString(Chr)) == 1); } bool operator <=(const TChar *Chr) const { return (bool)(Compare(xString(Chr)) != 1); } bool operator >=(const TChar *Chr) const { return (bool)(Compare(xString(Chr)) != -1); } bool operator ==(const TChar *Chr) const { return (bool)(Compare(xString(Chr)) == 0); } bool operator !=(const TChar *Chr) const { return (bool)(Compare(xString(Chr)) != 0); } // Concatenation operator xString& operator << (const TChar* rValue); void _attachRight(const TCHAR*rValue); // Concatenation operator xString& operator << (const char iValue); // Concatenation operator xString& operator << (const int iValue); // Concatenation operator //xString& operator << (const signed iValue); // Concatenation operator xString& operator << (const unsigned int iValue); // Concatenation operator xString& operator << (const float iValue); // Concatenation operator xString& operator << (const void* iValue); //======================================================= // // Protected low-level functions // void AssignFrom(const xString& Str); void AssignFrom(const TUnicodeChar *Str); protected: void Optimize(); void Grow(int Num); static TChar *AllocStr(int Size); static void FreeStr(TChar *Ptr); //======================================================= // // Protected data members // //protected: TChar *Text; // The actual character array int Size; // Number of bytes allocated for string int Len; // Number of characters in string }; #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "vtAttributeHelper.h" #include <vtStructHelper.h> using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; vtTools::ParameterTools::StructurMember breakTable[] = { STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"0","250"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"1","250"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"2","300"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"3","350"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"4","450"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"5","575"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"6","625"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"7","700"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"8","1000"), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"9","1000"), }; vtTools::ParameterTools::StructurMember myStructWheelContactData[] = { STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Contact Point",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Contact Normal",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Longitudes Direction",""), STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Lateral Direction",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Contact Force",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Longitudes Slip",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Lateral Slip",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Longitudes Impulse",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Lateral Impulse",""), STRUCT_ATTRIBUTE(VTS_MATERIAL,"Other Material",""), STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Contact Pos",""), STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Colliding Entity",""), }; void PhysicManager::_RegisterVehicleParameters() { CKParameterManager *pm = m_Context->GetParameterManager(); CKAttributeManager* attman = m_Context->GetAttributeManager(); CKParameterTypeDesc* param_type = NULL; //################################################################ // // Tire Function // pm->RegisterNewStructure(VTF_VWTIRE_SETTINGS,"pTireFunction", "XML Link,Extremum Slip,Extremum Value,Asymptote Slip,Asymptote Value,Stiffness Factor", VTE_XML_TIRE_SETTINGS,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT); //################################################################ // // Motor related // pm->RegisterNewStructure(VTS_VMOTOR_ENTRY,"RPM / Newton Meter","RPM,Newton Meter",CKPGUID_FLOAT,CKPGUID_FLOAT); param_type=pm->GetParameterTypeDescription(VTS_VMOTOR_ENTRY); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; pm->RegisterNewStructure(VTS_VMOTOR_TVALUES,"pVehicleMotor Torques","1,2,3,4,5,6,7", VTS_VMOTOR_ENTRY,VTS_VMOTOR_ENTRY, VTS_VMOTOR_ENTRY,VTS_VMOTOR_ENTRY, VTS_VMOTOR_ENTRY,VTS_VMOTOR_ENTRY, VTS_VMOTOR_ENTRY); pm->RegisterNewStructure(VTS_VGEAR_RATIO_ENTRY,"Gear / Ratio","Gear,Ratio",CKPGUID_INT,CKPGUID_FLOAT); param_type=pm->GetParameterTypeDescription(VTS_VGEAR_RATIO_ENTRY); if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; pm->RegisterNewStructure(VTS_VGEAR_RATIOS,"pVehicleGear List","1,2,3,4,5,6,7", VTS_VGEAR_RATIO_ENTRY,VTS_VGEAR_RATIO_ENTRY, VTS_VGEAR_RATIO_ENTRY,VTS_VGEAR_RATIO_ENTRY, VTS_VGEAR_RATIO_ENTRY,VTS_VGEAR_RATIO_ENTRY, VTS_VGEAR_RATIO_ENTRY); //################################################################ // // Vehicle Common // pm->RegisterNewFlags(VTF_VSTATE_FLAGS,"pVehicleStateFlags","Is Moving=1,Is Accelerated=2,Is Accelerated Forward=4,Is Accelerated Backward=8,All Wheels On Ground=16,Is Falling=32,Handbrake=64,Is Braking=128,Is Steering=256,Has Gearbox=512,Has Motor=1024"); pm->RegisterNewEnum(VTE_BRAKE_LEVEL,"pVehicleBreakLevel","No Break=-1,Small=0,Medium=1,High=2"); pm->RegisterNewEnum(VTE_BRAKE_XML_LINK,"pVehicleXMLBrakeSettings","Stub=1"); pm->RegisterNewEnum(VTE_VEHICLE_XML_LINK,"pVehicleXMLLink","Stub=1"); pm->RegisterNewFlags(VTF_BRAKE_FLAGS,"pVehicleBreakFlags","Use Table=1,Auto Break=2"); REGISTER_CUSTOM_STRUCT("pVehicleBreakTable",E_VBT_STRUCT,VTS_BRAKE_TABLE,breakTable,FALSE); //################################################################ // // Wheel // REGISTER_CUSTOM_STRUCT("pWheelContactData",E_WCD_STRUCT,VTS_WHEEL_CONTACT,myStructWheelContactData,FALSE); pm->RegisterNewFlags(VTS_PHYSIC_WHEEL_FLAGS,"pWheelFlags","Steerable Input=1,Steerable Auto=2,Affected By Handbrake=4,Accelerated=8,Controlled by Vehicle=16,Affected by Differential=32,Ignore Tire Function=64"); //pm->RegisterNewFlags(VTS_PHYSIC_WHEEL_FLAGS,"pWheelFlags","Steerable Input=1,Steerable Auto=2,Affected By Handbrake=4,Accelerated=8,Build Lower Half=256,Use Wheel Shape=512,Controlled by Vehicle"); pm->RegisterNewFlags(VTF_VWSHAPE_FLAGS,"pWheelShapeFlags","AxisContactNormal=1,InputLateralSlip=2,InputLongitudinal=4,UnscaledSpringBehavior=8,EmulateLegacyWheel=32,ClampedFriction=64"); pm->RegisterNewStructure(VTS_PHYSIC_WHEEL_DESCR,"pWheelDescr", "XML Link,Suspension,Spring Restitution,Spring Bias,Spring Damping,Maximum Brake Force,Friction To Side,Friction To Front,Inverse Wheel Mass,Wheel Flags,Wheel Shape Flags,Lateral Force Settings,Longitudinal Force Settings", VTE_XML_WHEEL_SETTINGS, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, VTS_PHYSIC_WHEEL_FLAGS, VTF_VWSHAPE_FLAGS, VTF_VWTIRE_SETTINGS, VTF_VWTIRE_SETTINGS); att_wheelDescr = attman->RegisterNewAttributeType("pWheel",VTS_PHYSIC_WHEEL_DESCR,CKCID_BEOBJECT); attman->SetAttributeCategory(att_wheelDescr ,"Physic"); } <file_sep>#ifndef __xDistributed3DObject_h #define __xDistributed3DObject_h #include "xDistributedObject.h" class x3DObjectData; class xDistributedProperty; namespace TNL { class GhostConnection; } class xDistributed3DObject : public xDistributedObject { typedef xDistributedObject Parent; public: xDistributed3DObject(); ~xDistributed3DObject(); enum MaskBits { InitialMask = BIT(0), ///< This mask bit is never set explicitly, so it can be used for initialization data. PositionMask = BIT(1), ///< This mask bit is set when the position information changes on the server. }; void doInitUpdate(); void updateAll(); void onGhostRemove(); bool onGhostAdd(TNL::GhostConnection *theConnection); void onGhostAvailable(TNL::GhostConnection *theConnection); TNL::U32 packUpdate(TNL::GhostConnection *connection, TNL::U32 updateMask, TNL::BitStream *stream); void unpackUpdate(TNL::GhostConnection *connection, TNL::BitStream *stream); void performScopeQuery(TNL::GhostConnection *connection); TNL_DECLARE_RPC(c2sGetOwnerShip,(TNL::U32 userSrcID)); virtual void destroy(); virtual void update(float time); virtual void initProperties(); void pack(TNL::BitStream *bstream); void unpack(TNL::BitStream *bstream,float sendersOneWayTime); void prepare(); xDistributedProperty *getProperty(int nativeType); xDistributedProperty *getUserProperty(const char*name); uxString print(TNL::BitSet32 flags); protected: TNL::StringPtr m_localAddress; public: TNL_DECLARE_CLASS(xDistributed3DObject); }; #endif <file_sep>#pragma once // PBodyMainMDIEx frame with splitter class PBodyMainMDIEx : public CMDIChildWndEx { DECLARE_DYNCREATE(PBodyMainMDIEx) protected: PBodyMainMDIEx(); // protected constructor used by dynamic creation virtual ~PBodyMainMDIEx(); CSplitterWnd m_wndSplitter; public: virtual void OnFinalRelease(); protected: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); DECLARE_MESSAGE_MAP() DECLARE_DISPATCH_MAP() DECLARE_INTERFACE_MAP() }; <file_sep>#ifndef __base_macros_h__ #define __base_macros_h__ #ifndef API_EXPORT #define API_EXPORT __declspec(dllexport) #endif #ifndef API_INLINE #define API_INLINE __inline #endif #ifndef API_sCALL #define API_sCALL __stdcall #endif #ifndef API_cDECL #define API_cDECL __cdecl #endif #endif<file_sep>#ifndef SKINNED_MESH_H #define SKINNED_MESH_H class NxMat34; class NxScene; class NxPhysicsSDK; class NxShape; // Creates the illusion of a soft body simulation by mapping a deformable mesh to a set of constrained rigid bodies. // Can also be used for ragdoll graphics. namespace NXU { class NxuPhysicsCollection; }; namespace SOFTBODY { class SkinnedMeshInstance; class SkinnedMesh; class SoftMeshSystem; SkinnedMesh *sm_CreateSkinnedMesh(const char *fname); SkinnedMeshInstance *sm_CreateSkinnedMeshInstance(SkinnedMesh *model,NxScene *scene,const NxMat34 *rootNode); void sm_ReleaseSkinnedMeshInstance(SkinnedMeshInstance *fb); void sm_ReleaseSkinnedMesh(SkinnedMesh *fm); void sm_RenderSkinnedMeshInstance(SkinnedMeshInstance *fb); bool sm_MatchSkinnedMesh(const SkinnedMesh *model,const char *name); // true if these are the same names. void sm_onDeviceReset(SkinnedMesh *fsm,void *device); SoftMeshSystem * sm_locateRenderContext(NxShape *shape); // builds a rendering context for a shape of this type. }; #endif <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorJSetFixedDecl(); CKERROR CreateJSetFixedProto(CKBehaviorPrototype **pproto); int JSetFixed(const CKBehaviorContext& behcontext); CKERROR JSetFixedCB(const CKBehaviorContext& behcontext); //************************************ // Method: FillBehaviorJSetFixedDecl // FullName: FillBehaviorJSetFixedDecl // Access: public // Returns: CKObjectDeclaration * // Qualifier: //************************************ CKObjectDeclaration *FillBehaviorJSetFixedDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PJFixed"); od->SetCategory("Physic/Joints"); od->SetDescription("Creates a Fixed Joint between world('None') or an entity."); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x2d80b0a,0x3d5a0caf)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreateJSetFixedProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreateJSetFixedProto // FullName: CreateJSetFixedProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ CKERROR CreateJSetFixedProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJFixed"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PJFixed <br> PJFixed is categorized in \ref Joints <br> <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Creates a fixed joint between a two bodies or the world. <br> <br> \image html fixedJoint.png <h3>Technical Information</h3> \image html PJFixed.png The fixed joint effectively glues two bodies together with no remaining degrees of freedom for relative motion. It is useful to set it to be breakable (see Breakable Joint) to simulate simple fracture effects. An example for a fixed joint is a factory chimney divided into sections, each section held together with fixed joints. When the chimney is hit, it will break apart and topple over by sections rather than unrealistically falling over in one piece. DOFs removed: 6 DOFs remaining: 0 <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="out">Out: </SPAN>is activated when the process is completed. <BR> <BR> <SPAN CLASS="pin">Body B: </SPAN>The second body. Leave blank to create a joint constraint with the world. <BR> <BR> <h3>VSL : Creation </h3><br> <SPAN CLASS="NiceCode"> \include pJFixed.vsl </SPAN> <br> Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createJointFixed().<br> */ proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetFunction(JSetFixed); proto->SetBehaviorCallbackFct( JSetFixedCB); *pproto = proto; return CK_OK; } //************************************ // Method: JSetFixed // FullName: JSetFixed // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int JSetFixed(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Fixed)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); if(bodyA || bodyB) { pJointFixed*joint =static_cast<pJointFixed*>(worldA->getJoint(target,targetB,JT_Fixed)); if (!joint) { joint = static_cast<pJointFixed*>(pFactory::Instance()->createFixedJoint(target,targetB)); } beh->ActivateOutput(0); } } return 0; } //************************************ // Method: JSetFixedCB // FullName: JSetFixedCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR JSetFixedCB(const CKBehaviorContext& behcontext) { return CKBR_OK; }<file_sep>/******************************************************************** created: 2006/01/18 created: 18:1:2006 17:12 filename: e:\public\vt midi\MidiManager.cpp file path: e:\public\vt midi file base: MidiManager file ext: cpp purpose: midi low-level-stuff *********************************************************************/ #include "CKAll.h" #include "MidiManager.h" #include "MidiSound/MidiSound.h" // Constructor MidiManager::MidiManager(CKContext *ctx):CKMidiManager(ctx,"Midi Manager") { memset(noteState,0,sizeof(noteState)); ctx->RegisterNewManager(this); } // Destructor MidiManager::~MidiManager() { } //----------------------------- // Midi Callback Function //----------------------------- void CALLBACK MidiInProc( HMIDIIN hMidiIn, UINT wMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2 ){ MidiManager *mm = (MidiManager *) dwInstance; if (!mm->midiDeviceIsOpen) return; midiMessage tmp; tmp.channel = (BYTE)((dwParam1 & 0x0F)); tmp.command = (BYTE)((dwParam1 & 0xF0) >> 4); tmp.note = (BYTE)((dwParam1 & 0xFF00) >> 8); tmp.attack = (BYTE)((dwParam1 & 0xFF0000) >> 16); tmp.time = dwParam2; mm->listFromCallBack.PushBack(tmp); if( tmp.command==9 && tmp.attack!=0 ){ // note activated mm->ActivateNote(tmp.note, tmp.channel, TRUE); return; } if( tmp.command==9 || tmp.command==8 ){ // note deactivated mm->ActivateNote(tmp.note, tmp.channel, FALSE); return; } } void CALLBACK MidiOutProc( HMIDIIN hMidiIn, UINT wMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2 ){ MidiManager *mm = (MidiManager *) dwInstance; } //------------------- // Midi Note State //------------------- void MidiManager::ActivateNote( int note, int channel, CKBOOL state){ int notedec = note>>3; int dec = abs( (channel<<4) + notedec ); if( dec>=MIDI_MAXNOTES ) dec = MIDI_MAXNOTES-1; if( state ){ noteState[dec] |= 1 << (note-(notedec<<3)); } else { noteState[dec] &= ~(1 << (note-(notedec<<3))); } } CKBOOL MidiManager::IsNoteActive(int note, int channel){ int notedec = note>>3; int dec = abs( (channel<<4) + notedec ); if( dec>=MIDI_MAXNOTES ) dec = MIDI_MAXNOTES-1; if( noteState[dec] & (1 << (note-(notedec<<3))) ) return TRUE; return FALSE; } //------------------ //------------------ // Manager Events //------------------ //------------------ CKERROR MidiManager::OnCKPlay() { if( m_Context->IsReseted() ){ // to be sure it's not a un-resume PLAY if (midiDeviceBBrefcount) { if (OpenMidiIn(DesiredmidiDevice)!=CK_OK || OpenMidiOut(DesiredmidiOutDevice)!=CK_OK ) { //m_Context->OutputToConsole("Trying to open default port (0)"); if( DesiredmidiDevice!=0 ){ if( OpenMidiIn(0)!=CK_OK) { //m_Context->OutputToConsole("Unable to open Default port (0)"); return CKERR_INVALIDOPERATION; } } } } } return CK_OK; } CKERROR MidiManager::OnCKInit() { midiDeviceHandle = 0; midiDeviceOutHandle = 0 ; midiDeviceIsOpen = FALSE; midiOutDeviceIsOpen = FALSE; midiCurrentDevice = 0; midiCurrentOutDevice = 0; DesiredmidiDevice = 0; DesiredmidiOutDevice= 0; midiDeviceBBrefcount = 0; int midiDeviceCount = midiInGetNumDevs(); int midiOutDeviceCount = midiOutGetNumDevs(); if( !midiDeviceCount ){ m_Context->OutputToConsole("No Midi Device !"); return CK_OK; } MIDIINCAPS tmp; // get midi devices infos for( int a=0 ; a< midiDeviceCount ; a++ ){ midiInGetDevCaps(a, &tmp,sizeof(tmp) ); } MIDIOUTCAPS tmpO; // get midi out devices infos for( int z=0 ; z< midiOutDeviceCount ; z++ ){ midiOutGetDevCaps(z, &tmpO,sizeof(tmpO) ); } return CK_OK; } CKERROR MidiManager::OnCKEnd() { return CK_OK; } CKERROR MidiManager::OnCKReset() { if (midiDeviceIsOpen ) return CloseMidiIn(); return CK_OK; } CKERROR MidiManager::CloseMidiIn() { if( midiDeviceHandle && midiDeviceIsOpen ){ if (midiInStop( midiDeviceHandle )== MMSYSERR_NOERROR) { if (midiInClose(midiDeviceHandle) == MMSYSERR_NOERROR) { midiDeviceIsOpen = FALSE; return CK_OK; } } } return CKERR_INVALIDOPERATION; } CKERROR MidiManager::CloseMidiOut() { if( midiDeviceOutHandle && midiOutDeviceIsOpen ){ if (midiOutClose(midiDeviceOutHandle) == MMSYSERR_NOERROR) { midiOutDeviceIsOpen = FALSE; return CK_OK; } } return CKERR_INVALIDOPERATION; } CKERROR MidiManager::OpenMidiOut(int DesiredmidiDevice) { if(midiOutDeviceIsOpen) { m_Context->OutputToConsole("Midi Out Device Already open",false); return CKERR_INVALIDOPERATION; } MMRESULT mr; mr = midiOutOpen( &midiDeviceOutHandle, DesiredmidiOutDevice, 0, 0, CALLBACK_NULL); if(!midiDeviceOutHandle|| (mr!=MMSYSERR_NOERROR) ) { m_Context->OutputToConsole("Failed to open Desired Midi Out Device"); return CKERR_INVALIDOPERATION; } midiOutDeviceIsOpen = TRUE; midiCurrentOutDevice = DesiredmidiOutDevice; if (mr!=MMSYSERR_NOERROR){ m_Context->OutputToConsole("Failed to Start Desired Midi Out Device"); return CKERR_INVALIDOPERATION; } return CK_OK; } CKERROR MidiManager::OpenMidiIn(int DesiredmidiDevice) { if(midiDeviceIsOpen) { m_Context->OutputToConsole("Midi Device Already open"); return CKERR_INVALIDOPERATION; } MMRESULT mr; //midiDeviceHandle = NULL; mr = midiInOpen( &midiDeviceHandle, DesiredmidiDevice, (DWORD)MidiInProc, (unsigned long)this, CALLBACK_FUNCTION|MIDI_IO_STATUS ); if(!midiDeviceHandle || (mr!=MMSYSERR_NOERROR) ) { m_Context->OutputToConsole("Failed to open Desired Midi IN Device"); return CKERR_INVALIDOPERATION; } midiDeviceIsOpen = TRUE; midiCurrentDevice = DesiredmidiDevice; ZeroMemory(&noteState, MIDI_MAXNOTES); mr = midiInStart( midiDeviceHandle ); if (mr!=MMSYSERR_NOERROR){ m_Context->OutputToConsole("Failed to Start Desired Midi IN Device"); return CKERR_INVALIDOPERATION; } return CK_OK; } CKERROR MidiManager::PostClearAll() { midiDeviceBBrefcount = 0; return CK_OK; } CKERROR MidiManager::PreProcess() { listFromCallBack.Swap(listForBehaviors); return CK_OK; } CKERROR MidiManager::PostProcess() { ////////////////////////////////////////////////////////////////////////// listForBehaviors.Clear(); if (midiDeviceIsOpen && (midiCurrentDevice!=DesiredmidiDevice)) { MMRESULT mreset; mreset = midiInReset(midiDeviceHandle); if (mreset != MMSYSERR_NOERROR) { m_Context->OutputToConsole("Unable to Reset the current Midi Device, before opening a new Midi device",false); return CKERR_INVALIDOPERATION; } if (CloseMidiIn()!= CK_OK) return CKERR_INVALIDOPERATION; midiDeviceIsOpen = FALSE; if (OpenMidiIn(DesiredmidiDevice)!=CK_OK) return CKERR_INVALIDOPERATION; } ////////////////////////////////////////////////////////////////////////// if (midiOutDeviceIsOpen && (midiCurrentOutDevice!=DesiredmidiOutDevice)) { MMRESULT mreset; mreset = midiOutReset(midiDeviceOutHandle); if (mreset != MMSYSERR_NOERROR) { m_Context->OutputToConsole("Unable to Reset the current Midi Out Device, before opening a new Midi Out device",false); return CKERR_INVALIDOPERATION; } if (CloseMidiOut()!= CK_OK) return CKERR_INVALIDOPERATION; midiOutDeviceIsOpen = FALSE; if (OpenMidiOut(DesiredmidiOutDevice)!=CK_OK){ m_Context->OutputToConsole("couldn't attach new midi out device"); return CKERR_INVALIDOPERATION; } } return CK_OK; } // Midi Sound Functions CKERROR MidiManager::SetSoundFileName(void* source,CKSTRING filename) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->SetSoundFileName(filename); } CKSTRING MidiManager::GetSoundFileName(void* source) { MidiSound* ms = (MidiSound*)source; if (!ms) return NULL; return (CKSTRING)ms->GetSoundFileName(); } CKERROR MidiManager::Play(void* source) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->Start(); } CKERROR MidiManager::Restart(void* source) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->Restart(); } CKERROR MidiManager::Stop(void* source) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->Stop(); } CKERROR MidiManager::Pause(void* source,CKBOOL pause) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->Pause(); } CKBOOL MidiManager::IsPlaying(void* source) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->IsPlaying(); } CKBOOL MidiManager::IsPaused(void* source) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->IsPaused(); } void* MidiManager::Create(void* hwnd) { return new MidiSound(hwnd); } void MidiManager::Release(void* source) { CloseFile(source); delete ((MidiSound*)(source)); } CKERROR MidiManager::OpenFile(void* source) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->OpenFile(); } CKERROR MidiManager::CloseFile(void* source) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->CloseFile(); } CKERROR MidiManager::Preroll(void* source) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->Preroll(); } CKERROR MidiManager::Time(void* source,CKDWORD* pTicks) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->Time((DWORD*)pTicks); } CKDWORD MidiManager::MillisecsToTicks(void* source,CKDWORD msOffset) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->MillisecsToTicks(msOffset); } CKDWORD MidiManager::TicksToMillisecs(void* source,CKDWORD tkOffset) { MidiSound* ms = (MidiSound*)source; if (!ms) return CKERR_INVALIDPARAMETER; return ms->TicksToMillisecs(tkOffset); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" void PhysicManager::reloadXMLDefaultFile(const char*fName) { if (! fName || !strlen(fName))return; ////////////////////////////////////////Load our physic default xml document : if (getDefaultConfig()) { delete m_DefaultDocument; m_DefaultDocument = NULL; xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted old default config"); } TiXmlDocument * defaultDoc = loadDefaults(XString(fName)); if (!defaultDoc) { enableFlag(_getManagerFlags(),E_MF_LOADING_DEFAULT_CONFIG_FAILED); xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config : PhysicDefaults.xml: failed"); setDefaultConfig(NULL); }else { setDefaultConfig(defaultDoc); } }<file_sep>dofile("ModuleConfig.lua") -- Prepares a Visual Studio Project function createDummyProject (packageConfig) project(packageConfig.Name) kind "StaticLib" language "C++" premake.buildconfigs() -- External Virtools Directories ? If not, the variables from ModuleConfig.lua will be used ! -- This assumes that the virtools headers and libs are in inside the module path : Dependencies\vt\... if _OPTIONS["ExternalVTDirectory"] then dofile(_OPTIONS["ExternalVTDirectory"]) end return premake.CurrentContainer end -- Modifies an project according to a supplied package config function evaluateConfigs(prj,packageConfig) for cfg in premake.eachconfig(prj) do configuration(cfg.name) if packageConfig.TargetSuffix then setfields("targetdir", getBinDir(1).."/"..cfg.name.."/".._OPTIONS["Dev"]..packageConfig.TargetSuffix) else setfields("targetdir", getBinDir(1).."/"..cfg.name.."/".._OPTIONS["Dev"]) end if packageConfig.Language then setfields("language", packageConfig.Language) end cfgDefine = { } cfgLinks = { } --~ Handling Virtools Packages if table.contains(packageConfig.Defines,"VIRTOOLS_USER_SDK") then -- Compile to Virtools Dev directory ? : if _OPTIONS["DeployDirect"] =="TRUE" then setfields("targetdir", getVTDirectory():lower()..packageConfig.TargetSuffix ) end -- No?, then we compile to ../Bin/CfgName/Dev-Version and add a post compile step`which copies all stuff to dev if (_OPTIONS["DeployDirect"]==nil and packageConfig.PostCommand and packageConfig.Type == "SharedLib") then setfields("postbuildcommands", packageConfig.PostCommand) end if _OPTIONS["Static"] =="TRUE" then cfgDefine = table.join( cfgDefine, { "VX_LIB" ; "CK_LIB" ; "VNK_LI" ; "VSU_LIB" ; "VSM_LIB" ; "VSS_LIB" ; "CUSTOM_PLAYER_STATIC";"_AFXDLL" } ) if (packageConfig.Type=="WindowApp") or ( packageConfig.StaticOptions and (table.contains(packageConfig.StaticOptions,"vtstatic")) ) then cfgLinks = table.join( cfgLinks, { "VxMathStatic" ; "CK2Static" ; "CKZlibStatic" } ) end else cfgDefine = table.join( cfgDefine, { "MODULE_BASE_EXPORTS" } ) cfgLinks = table.join( cfgLinks, { "VxMath" ; "CK2" } ) end end if _OPTIONS["Static"] =="TRUE" then cfgDefine = table.join( cfgDefine, { "MODULE_STATIC" } ) else cfgDefine = table.join( cfgDefine, { "MODULE_BASE_EXPORTS" } ) end setfields("objdir", OUTPUT_PATH_OFFSETT_TO_TMP.."/".._ACTION.."/"..prj.name.."/"..cfg.name ) -- If the compilation is intended as end-user distribution, please define ReleaseRedist -- Otherwise the end user can use OUR building blocks for authoring. This is explicitly -- restricted and a license violation towards VTMOD if cfg.name == "ReleaseRedist" then cfgDefine = table.join( cfgDefine, { "ReleaseRedist" ; "VIRTOOLS_RUNTIME_VERSION" } ) end if cfg.name == "ReleaseDemo" then cfgDefine = table.join( cfgDefine, { "ReleaseDemo" } ) end -- Solving a Premake Bug if cfg.name == "Debug" then cfgDefine = table.join( cfgDefine, { "DEBUG" ; "_DEBUG" } ) setfields("flags", "Symbols" ) else cfgDefine = table.join( cfgDefine, { "NDEBUG" } ) setfields("flags", "Optimize" ) end if cfg.name == "ReleaseDebug" then setfields("flags", "Symbols" ) end -- Visual Studio 2005 specific if ( _ACTION == "vs2005") then cfgDefine = table.join( cfgDefine, { "_CRT_SECURE_NO_DEPRECATE" } ) end -- web player fix if _OPTIONS["ExtraDefines"] and _OPTIONS["ExtraDefines"]=="WebPack" then packageConfig.Defines = table.join(packageConfig.Defines,{ "WebPack" }) --cfgDefine = table.join( cfgDefine, { "ReleaseRedist" ; "VIRTOOLS_RUNTIME_VERSION" } ) end setfields("buildoptions", table.join( packageConfig.Options ) ) setfields("defines", table.join( table.join(packageConfig.Defines),cfgDefine ) ) setfields("links", table.join( table.join(packageConfig.links),cfgLinks) ) end end function createStaticPackage (packageConfig) lastProject = createDummyProject(packageConfig) lastProject.name = packageConfig.Name setfields("location","./".._ACTION.._OPTIONS["Dev"]) setfields("files",table.join(packageConfig.Files)) --if table.contains(packageConfig.Defines,"VIRTOOLS_USER_SDK") then if (_OPTIONS["Static"] =="TRUE" and packageConfig.Type=="SharedLib" ) then if ( packageConfig.StaticOptions and (table.contains(packageConfig.StaticOptions,"convert")) ) then packageConfig.Type ="StaticLib" end end --end setfields("kind",packageConfig.Type) setfields("links", table.join( packageConfig.Libs ) ) --~ Handling a Virtools Package if table.contains(packageConfig.Defines,"VIRTOOLS_USER_SDK") then --~ Virtools Include Directories if _OPTIONS["ExtraDefines"] and _OPTIONS["ExtraDefines"]=="WebPack" then packageConfig.Libs = table.join(packageConfig.Libs,{ "Camera" }) setfields("links", table.join( packageConfig.Libs ) ) end DevIncludeDir = { getVTDirectory():lower().."/SDK/Includes" } packageConfig.Includes = table.join(packageConfig.Includes,DevIncludeDir) --~ Virtools Library Directories DevLibDir = { getVTDirectory():lower().."/SDK/Lib/Win32/Release" } packageConfig.LibDirectories = table.join(packageConfig.LibDirectories,DevLibDir) -- Handling Static ---- end setfields("includedirs", table.join(packageConfig.Includes)) setfields("libdirs", table.join( packageConfig.LibDirectories ) ) if packageConfig.ExludeFiles then setfields("excludes",table.join(packageConfig.ExludeFiles)) end evaluateConfigs(lastProject,packageConfig) end function getVTDirectory() if _OPTIONS["Dev"] == "Dev35" then return DEV35DIR end if _OPTIONS["Dev"] == "Dev40" then return DEV40DIR end if _OPTIONS["Dev"] == "Dev41" then return DEV41DIR end if _OPTIONS["Dev"] == "Dev5" then return DEV5DIR end return DEV40DIR end function setfields (name, value) local kind = premake.fields[name].kind local scope = premake.fields[name].scope local allowed = premake.fields[name].allowed if (kind == "string") then return premake.setstring(scope, name, value, allowed) elseif (kind == "path") then return premake.setstring(scope, name, path.getabsolute(value)) elseif (kind == "list") then return premake.setarray(scope, name, value, allowed) elseif (kind == "dirlist") then return premake.setdirarray(scope, name, value) elseif (kind == "filelist") then return premake.setfilearray(scope, name, value) end end function getBinDir(oneUp) res= OUTPUT_PATH_OFFSETT_TO_PROJECTFILES if oneUp==1 then res= OUTPUT_PATH_OFFSETT_TO_PROJECTFILES_MINUS_ONE end return res end newoption { trigger = "Static", value = "false", description = "Compiles static library or output" } newoption { trigger = "Dev", value = "Dev40", description = "Sets the Virtools version" } newoption { trigger = "DeployDirect", value = "TRUE", description = "Compiles to ../Bin/ConfigName/DevVersion/ or to DEV_XX_BIN" } newoption { trigger = "ExternalVTDirectory", value = "TRUE", description = "Uses the Virtools directories, specified in VTPaths.lua or ModuleConfig.lua(DEVXXDIR)" } newoption { trigger = "ExtraDefines", value = "", description = "Adds additional macro directives", } <file_sep>#include "xDistributedPropertyInfo.h" <file_sep>#include <StdAfx.h> #include "pCommon.h" CKObjectDeclaration *FillBehaviorPWOBBOverlapDecl(); CKERROR CreatePWOBBOverlapProto(CKBehaviorPrototype **pproto); int PWOBBOverlap(const CKBehaviorContext& behcontext); CKERROR PWOBBOverlapCB(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorPWOBBOverlapDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("PWOBBOverlap"); od->SetCategory("Physic/Collision"); od->SetDescription("Performs an overlap test against masked shape groups.Outputs an object only!"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x16a46d79,0xa951a4a)); od->SetAuthorGuid(VTCX_AUTHOR_GUID); od->SetAuthorName(VTCX_AUTHOR); od->SetVersion(0x00010000); od->SetCreationFunction(CreatePWOBBOverlapProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(GUID_MODULE_MANAGER); return od; } //************************************ // Method: CreatePWOBBOverlapProto // FullName: CreatePWOBBOverlapProto // Access: public // Returns: CKERROR // Qualifier: // Parameter: CKBehaviorPrototype **pproto //************************************ enum bInput { //bbI_WorldRef, bbI_SIZE, bbI_Center, bbI_Ref, bbI_ShapesType, bbI_Accurate, bbI_Groups, bbI_Mask, }; enum bbS { bbS_Result=0, bbS_Index, bbS_Size, bbS_Groups=3, bbS_Mask=4 }; enum bbOT { bbOT_Yes, bbOT_No, bbOT_Finish, bbOT_Next, }; CKERROR CreatePWOBBOverlapProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWOBBOverlap"); if(!proto) return CKERR_OUTOFMEMORY; /*! \page PWOBBOverlap PWOBBOverlap is categorized in \ref Collision <h3>Description</h3> Apply to a <A HREF="Documentation.chm::/beobjects/1_ck3dentity.html">3DEntity</A><br> Performs an overlap test against masked shape groups.<br> See <A HREF="PWOverlaps.cmo">PWOverlaps.cmo</A> for example. <h3>Technical Information</h3> \image html PWOBBOverlap.png <SPAN CLASS="in">In: </SPAN>triggers the process <BR> <SPAN CLASS="in">Next: </SPAN>Iterate through next hit. <BR> <BR> <SPAN CLASS="out">Yes: </SPAN>Hit occured. <BR> <SPAN CLASS="out">No: </SPAN>No hits. <BR> <SPAN CLASS="out">Finish: </SPAN>Last hit. <BR> <SPAN CLASS="out">Next: </SPAN>Loop out. <BR> <BR> <SPAN CLASS="pin">Target: </SPAN>World Reference. pDefaultWorld! <BR> <SPAN CLASS="pin">Size: </SPAN>The box dimension. <BR> <SPAN CLASS="pin">Center: </SPAN>The box center in world space.If shape reference is given, then its transforming this value in its local space. <BR> <SPAN CLASS="pin">Shapes Types: </SPAN>Adds static and/or dynamic shapes to the test. <BR> <SPAN CLASS="pin">Accurate: </SPAN>True to test the sphere against the actual shapes, false to test against the AABBs only. <BR> <SPAN CLASS="pin">Groups: </SPAN>Includes specific groups to the test. <BR> <SPAN CLASS="pin">Groups Mask: </SPAN>Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask <BR> <br> <h3>Note</h3><br> <br> <br> Is utilizing #pWorld::overlapOBBShapes()<br> */ proto->DeclareInput("In"); proto->DeclareInput("Next"); proto->DeclareOutput("Yes"); proto->DeclareOutput("No"); proto->DeclareOutput("Finish"); proto->DeclareOutput("Next"); proto->DeclareInParameter("Size",CKPGUID_VECTOR); proto->DeclareInParameter("Center",CKPGUID_VECTOR); proto->DeclareInParameter("Shape Reference",CKPGUID_3DENTITY); proto->DeclareInParameter("Shapes Type",VTF_SHAPES_TYPE); proto->DeclareInParameter("Accurate",CKPGUID_BOOL); proto->DeclareInParameter("Groups",CKPGUID_INT); proto->DeclareInParameter("Filter Mask",VTS_FILTER_GROUPS); proto->DeclareLocalParameter("result", CKPGUID_GROUP); proto->DeclareLocalParameter("index", CKPGUID_INT); proto->DeclareLocalParameter("size", CKPGUID_INT); proto->DeclareSetting("Groups",CKPGUID_BOOL,"false"); proto->DeclareSetting("Groups Mask",CKPGUID_BOOL,"false"); proto->DeclareOutParameter("Touched Body",CKPGUID_3DENTITY); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); proto->SetBehaviorCallbackFct( PWOBBOverlapCB ); proto->SetFunction(PWOBBOverlap); *pproto = proto; return CK_OK; } //************************************ // Method: PWOBBOverlap // FullName: PWOBBOverlap // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PWOBBOverlap(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorld(target->GetID()); if (!world) { beh->ActivateOutput(bbOT_No); return 0; } NxScene *scene = world->getScene(); if (!scene) { beh->ActivateOutput(bbOT_No); return 0; } if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CKGroup *carray = (CKGroup*)beh->GetLocalParameterObject(bbS_Result); if (carray) { //carray->clear(); carray->Clear(); }else { CK_OBJECTCREATION_OPTIONS creaoptions = (CK_OBJECTCREATION_OPTIONS)(CK_OBJECTCREATION_NONAMECHECK|CK_OBJECTCREATION_DYNAMIC); carray = (CKGroup*)ctx()->CreateObject(CKCID_GROUP,"asdasd",creaoptions); } beh->SetLocalParameterObject(0,carray); int hitIndex = 0; beh->SetLocalParameterValue(bbS_Index,&hitIndex); int hitSize = 0; beh->SetLocalParameterValue(bbS_Size,&hitSize); ////////////////////////////////////////////////////////////////////////// int types = GetInputParameterValue<int>(beh,bbI_ShapesType); int accurate = GetInputParameterValue<int>(beh,bbI_Accurate); DWORD groupsEnabled; DWORD groups = 0xffffffff; beh->GetLocalParameterValue(bbS_Groups,&groupsEnabled); if (groupsEnabled) { groups = GetInputParameterValue<int>(beh,bbI_Groups); } pGroupsMask *gmask = NULL; DWORD mask; beh->GetLocalParameterValue(bbS_Mask,&mask); if (mask) { CKParameter *maskP = beh->GetInputParameter(bbI_Mask)->GetRealSource(); gmask->bits0 = GetValueFromParameterStruct<int>(maskP,0); gmask->bits1 = GetValueFromParameterStruct<int>(maskP,1); gmask->bits2 = GetValueFromParameterStruct<int>(maskP,2); gmask->bits3 = GetValueFromParameterStruct<int>(maskP,3); } VxVector size = GetInputParameterValue<VxVector>(beh,bbI_SIZE); VxVector center = GetInputParameterValue<VxVector>(beh,bbI_Center); VxBbox box; box.SetCenter(center,size/2); box.SetDimension(center,size); CK3dEntity *shape = (CK3dEntity*)beh->GetInputParameterObject(bbI_Ref); int nbShapes = world->overlapOBBShapes(box,shape,(pShapesType)types,carray,groups,gmask,accurate); if (nbShapes) { beh->ActivateOutput(bbOT_Yes); beh->ActivateInput(1,TRUE); }else{ beh->ActivateOutput(bbOT_No); } } if( beh->IsInputActive(1) ) { beh->ActivateInput(1,FALSE); CKGroup *carray = (CKGroup*)beh->GetLocalParameterObject(bbS_Result); ////////////////////////////////////////////////////////////////////////// if (carray) { if (carray->GetObjectCount()) { CKBeObject *hit = carray->GetObject(carray->GetObjectCount()-1); if (hit) { beh->SetOutputParameterObject(0,hit); carray->RemoveObject(hit); if (carray->GetObjectCount()) { beh->ActivateOutput(bbOT_Next); }else { beh->ActivateOutput(bbOT_Finish); CKDestroyObject(carray); } } }else{ beh->ActivateOutput(bbOT_Finish); CKDestroyObject(carray); } }else { beh->ActivateOutput(bbOT_Finish); CKDestroyObject(carray); } } return 0; } //************************************ // Method: PWOBBOverlapCB // FullName: PWOBBOverlapCB // Access: public // Returns: CKERROR // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ CKERROR PWOBBOverlapCB(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { case CKM_BEHAVIORATTACH: case CKM_BEHAVIORLOAD: case CKM_BEHAVIORSETTINGSEDITED: { DWORD groups; beh->GetLocalParameterValue(bbS_Groups,&groups); beh->EnableInputParameter(bbI_Groups,groups); DWORD mask; beh->GetLocalParameterValue(bbS_Mask,&mask); beh->EnableInputParameter(bbI_Mask,mask); } break; } return CKBR_OK; } <file_sep>#ifndef SOFT_SKELETON_H #define SOFT_SKELETON_H namespace NXU { class NxuSkeleton; }; class NxActor; namespace SOFTBODY { class SoftSkeleton; // create a bone mapping skeleton between a list of actors and the bones in a graphics skeleton. SoftSkeleton * createSoftSkeleton(unsigned int acount,NxActor **alist,NXU::NxuSkeleton *skeleton); const float ** getTransforms(SoftSkeleton *sk); // synchronizes the actors with graphics skeleton and rebuilds the graphics transforms. void releaseSoftSkeleton(SoftSkeleton *sk); void debugRender(SoftSkeleton *sk); }; // end of namespace #endif <file_sep>#ifndef __P_VEHICLE_H__ #define __P_VEHICLE_H__ #include "vtPhysXBase.h" #include "pWheel.h" #include "NxArray.h" #include "NxUserContactReport.h" #include "pVehicleGears.h" #include "pVTireFunction.h" #include "pReferencedObject.h" #include "pCallbackObject.h" class pEngine; class pGearBox; class pDifferential; class pDriveLine; class pVehicleSteer; /** \addtogroup Vehicle @{ */ typedef std::vector<pWheel*>WheelArrayType; /** \brief A abstract base class for a vehicle object. */ typedef enum pVehicleControlStateItem { E_VCS_ACCELERATION, E_VCS_STEERING, E_VCS_HANDBRAKE, E_VCS_BRAKING, E_VCS_GUP, E_VCS_GDOWN, E_VCS_TCLUTCH, E_VCS_STARTER, E_VCS_BRAKES, }; enum ControlTypes // Which kind of controls do we have? { T_STEER_LEFT,T_STEER_RIGHT, T_THROTTLE,T_BRAKES, T_SHIFTUP,T_SHIFTDOWN, T_CLUTCH, T_HANDBRAKE, T_STARTER, T_HORN, MAX_CONTROLLER_TYPE }; typedef enum pVehicleControlStateItemMode { E_VCSM_ANALOG, E_VCSM_DIGITAL, }; typedef enum pVehicleBreakCase { BC_NoUserInput, BC_DirectionChange, BC_UserBreak, BC_Handbrake, BC_NumBreakCases, }; typedef enum pVehicleBreakLevel { BL_NoBreak=-1, BL_Small, BL_Medium, BL_High, BL_NumBreakLevels, }; typedef enum { VBF_UseTable=(1<<0), VBF_Autobreak=(1<<1), }; enum VehicleStatus { VS_IsMoving=(1<<0), VS_IsAccelerated=(1<<1), VS_IsAcceleratedForward=(1<<2), VS_IsAcceleratedBackward=(1<<3), VS_AllWheelsOnGround=(1<<4), VS_IsFalling=(1<<5), VS_Handbrake=(1<<6), VS_IsBraking=(1<<7), VS_IsSteering=(1<<8), VS_HasGearBox=(1<<9), VS_HasMotor=(1<<10), VS_IsRollingForward=(1<<11), VS_IsRollingBackward=(1<<12), }; class MODULE_API pVehicle : public xEngineObjectAssociation<CK3dEntity*>, public pCallbackObject { public: //---------------------------------------------------------------- // // new engine code // enum Max { MAX_WHEEL=8, MAX_DIFFERENTIAL=3, // Enough for a 4WD Jeep MAX_WING=10, // Front, rear and perhaps others MAX_CAMERA=10 // Max #camera's around car }; pEngine *engine; pGearBox *gearbox; pDifferential *differential[MAX_DIFFERENTIAL]; int differentials; pDriveLine *driveLine; pVehicleSteer *steer; float motorTorque; float breakTorque; //---------------------------------------------------------------- // // public access // pDifferential *getDifferential(int n){ return differential[n]; } pEngine *getEngine(){ return engine; } pDriveLine *getDriveLine(){ return driveLine; } pGearBox *getGearBox(){ return gearbox; } pVehicleSteer * getSteer() { return steer; } void setSteer(pVehicleSteer * val) { steer = val; } void findDifferentialWheels(int& wheel1Index,int& wheel2Index); int getNbDifferentials(){ return differentials; } void addDifferential(pDifferential *diff); float getRPM(); bool isStalled(); bool isAutoClutch(); bool isAutoShifting(); int getGear(); bool isValidEngine(); bool hasDifferential(); bool shiftUp(); bool shiftDown(); int setGear(int gear); float getTorque(int component); //---------------------------------------------------------------- // // control // void setControlState(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake); void setControlState(int parameter,float value); void setControlMode(int parameter,int mode); void getControlState(int parameter,float &value,int &mode); //---------------------------------------------------------------- // // internal // int initEngine(int flags); int doEngine(int flags,float dt); void preCalculate(); void calcForces(); void integrate(); void postStep(); void cleanup(); void PreCalcDriveLine(); void calculateForces(); void preAnimate(); void postAnimate(); void setClutch(float clutch); float getClutch(); //---------------------------------------------------------------- // // manager calls // void step(float dt); void advanceTime(float lastDeltaMS); //---------------------------------------------------------------- // // manager calls // int onPreProcess(); int onPostProcess(); void processPostScript(); void processPreScript(); XString debugPrint(int mask); //---------------------------------------------------------------- // // Break functions // bool useBreakTable; int breakFlags; int breakConditionLevels[BC_NumBreakCases]; float mBreakPressures[BL_NumBreakLevels]; float mBrakeTable[BL_NumBreakLevels][BREAK_TABLE_ENTRIES]; //!< Brake Table to take advantage of a certain brake lvl at any one time pVehicleBrakeTable mSmallBrakeTable; pVehicleBrakeTable mMediumBrakeTable; pVehicleBrakeTable mHighBrakeTable; bool mBreakLastFrame; float mTimeBreaking; float mBrakeMediumThresold; float mBrakeHighThresold; void setBreakPressure(int breakLevel,float pressure); float getBreakPressure(int breakLevel); int getBreakFlags() const { return breakFlags; } void setBreakFlags(int val) { breakFlags = val; } bool isUsingBreakTable() const { return useBreakTable; } void setUsingBreakTable(bool val) { useBreakTable = val; } pVehicleBreakCase calculateBreakCase(int currentAccelerationStatus); void setBreakCaseLevel(pVehicleBreakCase breakCase,pVehicleBreakLevel level); pVehicleBreakLevel getBreaklevelForCase(pVehicleBreakCase breakCase) { return (pVehicleBreakLevel)breakConditionLevels[breakCase]; } float getBrakeTorque(); void setMeasurementWheel(CK3dEntity*wheelReference); float getBrakeAmount(pVehicleBreakLevel brakeLevel); float getBrakeAmountFromTable(pVehicleBreakLevel brakeLevel); float getBrakeSmallPressure() {return mBreakPressures[BL_Small];} float getBrakeMediumPressure() {return mBreakPressures[BL_Medium];} float getBrakeHighPressure() {return mBreakPressures[BL_High];} float getBrakeMediumApplyTime() {return mBrakeMediumThresold;} float getBrakeHighApplyTime() {return mBrakeHighThresold;} //---------------------------------------------------------------- // // misc // int mVSFlags; float _cSteering; float _cAcceleration; int _cShiftStateUp; int _cShiftStateDown; bool _cAnalogSteering; bool _cAnalogAcceleration; bool _cHandbrake; NxArray<pWheel*> _wheels; //WheelArrayType _wheels; //NxArray<pWheel*> getWheels() const { return _wheels; } NxArray<pWheel*>& getWheels() { return _wheels; } int& getStateFlags() { return mVSFlags; } void setVSFlags(int val) { mVSFlags = val; } void printAllToConsole(); //---------------------------------------------------------------- // // old code // pVehicleGears* _vehicleGears; pVehicleMotor* _vehicleMotor; pVehicleMotor* getMotor() const { return _vehicleMotor; } void setMotor(pVehicleMotor* val) { _vehicleMotor = val; } pVehicleGears* getGears() const { return _vehicleGears; } void setGears(pVehicleGears* val) { _vehicleGears = val; } float _steeringWheelState; float _accelerationPedal; float _brakePedal; bool _brakePedalChanged; bool _handBrake; float _acceleration; float _digitalSteeringDelta; float _mass; float _lastDT; VxVector _centerOfMass; VxVector _steeringTurnPoint; VxVector _steeringSteerPoint; float getMass(); void setMass(float val) { _mass = val; } VxVector getCenterOfMass() const { return _centerOfMass; } void setCenterOfMass(VxVector val) { _centerOfMass = val; } float getDigitalSteeringDelta() const { return _digitalSteeringDelta; } void setDigitalSteeringDelta(float val) { _digitalSteeringDelta = val; } VxVector getSteeringTurnPoint() const { return _steeringTurnPoint; } void setSteeringTurnPoint(VxVector val) { _steeringTurnPoint = val; } VxVector getSteeringSteerPoint() const { return _steeringSteerPoint; } void setSteeringSteerPoint(VxVector val) { _steeringSteerPoint = val; } float getMotorForce() const { return _motorForce; } void setMotorForce(float val) { _motorForce = val; } float _transmissionEfficiency; float _steeringMaxAngleRad; float _motorForce; NxVec3 _localVelocity; bool _braking; bool _releaseBraking; float _maxVelocity; NxMaterial* _carMaterial; float _cameraDistance; NxActor* _mostTouchedActor; bool mAutomaticMode; float _differentialRatio; float getTransmissionEfficiency() const { return _transmissionEfficiency; } void setTransmissionEfficiency(float val) { _transmissionEfficiency = val; } float getDifferentialRatio() const { return _differentialRatio; } void setDifferentialRatio(float val) { _differentialRatio = val; } float getMaxVelocity() const { return _maxVelocity; } void setMaxVelocity(float val) { _maxVelocity = val; } bool getAutomaticMode() const { return mAutomaticMode; } float getMPH(int type=0); void setAutomaticMode(bool autoMode); void _computeMostTouchedActor(); void _computeLocalVelocity(); float _computeAxisTorque(); float _computeAxisTorqueV2(); float _computeRpmFromWheels(); float _computeMotorRpm(float rpm); void _updateRpms(); float _getGearRatio(); void _controlSteering(float steering, bool analogSteering); void _controlAcceleration(float acceleration, bool analogAcceleration); float getMaxSteering() const { return _steerMax; } void setMaxSteering(float val) { _steerMax = val; } float _steerMax; int _nbTouching; int _nbNotTouching; int _nbHandbrakeOn; int _currentStatus; int flags; int _calculateCurrentStatus(); int _calculateReaction(); int _calculateNextSteering(); int _performSteering(float dt); void doSteering(); int _performAcceleration(float dt); float calculateBraking(float dt); pRigidBody *mBody; NxActor *mActor; public : pVehicle(); pVehicle(pVehicleDesc descr,CK3dEntity *referenceObject); pRigidBody * getBody() const { return mBody; } void setBody(pRigidBody * val) { mBody = val; } void setToDefault(); int initWheels(int flags); void updateWheels(int flags= 0); void handleContactPair(NxContactPair* pair, int carIndex); void updateVehicle(float lastTimeStepSize); void control (float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake); void updateControl(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake); void gearUp(); void gearDown(); void standUp(); float getDriveVelocity(); float getMaxVelocity() { return _maxVelocity; } int getNbWheels() { return _wheels.size(); } const pWheel* getWheel(int i); pWheel*getWheel(CK3dEntity* wheelReference); NxActor *getActor(); void setActor(NxActor * val) { mActor = val; } int load(const pVehicleDesc& src ); }; /** @} */ #endif<file_sep>#ifndef __VT_WORLD_STRUCTS_H__ #define __VT_WORLD_STRUCTS_H__ enum PS_W_DOMINANCE_CONSTRAINT { PS_WDC_A, PS_WDC_B, }; enum PS_W_DOIMINANCE { PS_WD_GROUP_A, PS_WD_GROUP_B, PS_WD_CONSTRAINT, }; enum PS_W_DOIMINANCE_SETUP { PS_WDS_ITEM1, PS_WDS_ITEM2, PS_WDS_ITEM3, PS_WDS_ITEM4, PS_WDS_ITEM5, }; #endif<file_sep>#ifndef __xDistributedInteger_H #define __xDistributedInteger_H #include "xDistributedProperty.h" class xDistributedInteger : public xDistributedProperty { public: typedef xDistributedProperty Parent; xDistributedInteger ( xDistributedPropertyInfo *propInfo, xTimeType maxWriteInterval, xTimeType maxHistoryTime ) : xDistributedProperty(propInfo) { mLastValue=0; mCurrentValue=0; mLastTime = 0; mCurrentTime = 0; mLastDeltaTime = 0 ; mFlags = 0; mThresoldTicker = 0; mLastServerValue = 0 ; mLastServerDifference = 0; mDifference = 0; } ~xDistributedInteger(){} TNL::S32 mLastValue; TNL::S32 mCurrentValue; TNL::S32 mDifference; TNL::S32 mLastServerValue; TNL::S32 mLastServerDifference; bool updateValue(TNL::S32 value,xTimeType currentTime); void pack(TNL::BitStream *bstream); void unpack(TNL::BitStream *bstream,float sendersOneWayTime); void updateGhostValue(TNL::BitStream *stream); void updateFromServer(TNL::BitStream *stream); virtual uxString print(TNL::BitSet32 flags); }; #endif <file_sep>#pragma once //----------------------------------------------------------------------------- //CATEGORY FLAGS--------------------------------------------------------------- #define FIXED KeyboardShortcutManager::KSCategory::FIXED #define GLOBAL KeyboardShortcutManager::KSCategory::GLOBAL #define ACTIVE KeyboardShortcutManager::KSCategory::ACTIVE #define HIDDEN KeyboardShortcutManager::KSCategory::HIDDEN //Notes : // //for Global shortcuts, you can check for them in WindowProc // on WM_KEYDOWN // VirtoolsExternalPlugin::KeyboardShortcutManager* ksm = GetInterface()->GetKeyboardShortcutManager(); // int commandID = ksm->TestKS(STR_CATEGORY,pMsg->wParam); // //for Local shortcuts you can check for them in PreTranslateMessage // on WM_SYSKEYDOWN (for alt+key or F10) or WM_KEYDOWN // VirtoolsExternalPlugin::KeyboardShortcutManager* ksm = GetInterface()->GetKeyboardShortcutManager(); // int commandID = ksm->TestKS(STR_CATEGORY,pMsg->wParam); //category name under which you want to have your keyboard shortcuts #define STR_CATEGORY "vtAgeiaInterface Keyboard Shortcuts Category" //command ids sample - command ID min must be 1 #define CID_A 1 #define CID_B 2 //names of these commands, sample #define STR_A "Command A" #define STR_B "Command B" //command ids sample end //IMPORTANT! //by default these functions are called in vtAgeiaInterfacecallback.cpp //if you do not use callback (do not have vtAgeiaInterfacecallback.cpp), you should call these functions manually //register keyboard shortcut category (shortcuts of this category will be saved when Virtools Dev is closed) int RegisterKeyboardShortcutCategory(); //unregister keyboard shortcut category (shortcuts of this category will be saved no more when Virtools Dev is closed) int UnregisterKeyboardShortcutCategory(); //register keyboard shortcuts for your editor. Fill this function int RegisterKeyboardShortcuts(); //function that returns command name from its command id //used in RegisterActionEditorKSCategory, as a callback for the keyboard shortcut category //to know the command name //Note : in ksm->RegisterCategory, // you can set the callback to NULL (change "GetCommandName" into "NULL" // but you should then put directly names into keyboard shortcuts you register in that category // see in RegisterActionEditorKS(); // ks.key = 'A'; // ks.flags = ks.KS_CONTROL|ks.KS_SHIFT|ks.KS_ALT; // ks.commandID = CID_A; // ks.name = "Command A"; //LINE TO ADD TO SET NAME DIRECTLY // ksm->RegisterKS(index,ks); // but in that case, it will be less easy to integrate into popup menus const char* GetCommandName(int commandID); //function that returns command name <tab> <current keyboard shortcut> //usefull for popup menus const char* GetCommandMenuName(int commandID,XString &name); /* //here the sample code to fill a menu #define MENUSTR(commandID) GetActionEditorMenuName(commandID,name) POINT p; GetCursorPos(&p); XString name; CKVIPopupMenu menu; menu.AddItem(MENUSTR(CID_A),CID_A); menu.AddItem(MENUSTR(CID_B),CID_B); m_ActionMenu.AddSeparator(); menu.Show(p.x,p.y); */<file_sep>#include "precomp.h" #include "vtPrecomp.h" #include "vtNetAll.h" #include "vtNetworkManager.h" #include <xDOStructs.h> #include "xMathTools.h" //#undef TNL::Point3F int counter = 0 ; #include "xDistributedPoint3F.h" #include "xDistributedPoint4F.h" #include "xDistributedPoint2F.h" #include "xDistributedPoint1F.h" #include "xDistributedSession.h" void vtNetworkManager::performGhostUpdates() { ////////////////////////////////////////////////////////////////////////// //this is to store states in our dist objects xNetInterface *nInterface = GetClientNetInterface(); if (!nInterface) return; IDistributedObjects *doInterface = nInterface->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = nInterface->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); if (nInterface->IsServer())return; ////////////////////////////////////////////////////////////////////////// while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj) { xDistributedClass *_class = dobj->getDistributedClass(); if (_class != NULL ) { /************************************************************************/ /* */ /************************************************************************/ if (_class->getEnitityType() == E_DC_BTYPE_SESSION ) { xDistributedSession*session = static_cast<xDistributedSession*>(dobj); if (session) { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); xDistributedPropertyArrayType &props = *session->getDistributedPorperties(); int gFlags = session->getGhostUpdateBits().getMask(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); dobj->getGhostUpdateBits().set(1 << prop->getBlockIndex(),false); } } } /************************************************************************/ /* */ /************************************************************************/ if (_class->getEnitityType() == E_DC_BTYPE_3D_ENTITY ) { xDistributed3DObject *dobj3D = static_cast<xDistributed3DObject*>(dobj); if (dobj3D) { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); xDistributedPropertyArrayType &props = *dobj3D->getDistributedPorperties(); int gFlags = dobj->getGhostUpdateBits().getMask(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if ( blockIndex < _class->getFirstUserField() && dobj->getGhostUpdateBits().testStrict(1<<blockIndex)) { CK3dEntity *ghostDebug = (CK3dEntity*)m_Context->GetObject(dobj3D->getGhostDebugID()); CK3dEntity *bindObject = (CK3dEntity*)m_Context->GetObject(dobj3D->getEntityID()); switch(propInfo->mNativeType) { ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// case E_DC_3D_NP_WORLD_POSITION: { xDistributedPoint3F *propValue = static_cast<xDistributedPoint3F*>(prop); Point3F currentPos = propValue->mLastServerValue; Point3F velocity = propValue->mLastServerDifference; /************************************************************************/ /* we are updated by remote : */ /************************************************************************/ if (bindObject && dobj3D->getInterfaceFlags() & E_DO_BINDED && dobj3D->getUserID() != nInterface->getConnection()->getUserID() ) { updateLocalPosition(dobj,bindObject,prop); } if (ghostDebug) { if (propValue) { VxVector realPos; ghostDebug->GetPosition(&realPos); Point3F realPos2(realPos.x,realPos.y,realPos.z); float oneWayTime = (dobj3D->getNetInterface()->GetConnectionTime() / 1000.0f); oneWayTime +=oneWayTime * prop->getPredictionSettings()->getPredictionFactor(); Point3F predictedPos = currentPos + velocity * oneWayTime; Point3F realPosDiff = - predictedPos - realPos2 ; VxVector posNew(predictedPos.x,predictedPos.y,predictedPos.z); //VxVector posNew2 = realPos + ( posNew - realPos )*0.5; ghostDebug->SetPosition(&posNew); ////////////////////////////////////////////////////////////////////////// } } break; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// case E_DC_3D_NP_WORLD_ROTATION: { if (bindObject && dobj3D->getInterfaceFlags() & E_DO_BINDED && dobj3D->getUserID() != nInterface->getConnection()->getUserID() ) { updateLocalRotation(dobj,bindObject,prop); } if (ghostDebug) { xDistributedQuatF*propValue = static_cast<xDistributedQuatF*>(prop); if (propValue) { /* Point3F currentPos = propValue->mLastServerValue; Point3F velocity = propValue->mLastServerDifference; VxVector realPos; ghostDebug->GetPosition(&realPos); Point3F realPos2(realPos.x,realPos.y,realPos.z); float oneWayTime = (dobj3D->GetNetInterface()->GetConnectionTime() / 1000.0f); oneWayTime +=oneWayTime * prop->getPredictionSettings()->getPredictionFactor(); Point3F predictedPos = currentPos + velocity * oneWayTime; Point3F realPosDiff = - predictedPos - realPos2 ; VxVector posNew(predictedPos.x,predictedPos.y,predictedPos.z); //VxVector posNew2 = realPos + ( posNew - realPos )*0.5; ghostDebug->SetPosition(&posNew); */ } } break; } } dobj->getGhostUpdateBits().set(1 << prop->getBlockIndex(),false); } } } } } } begin++; } } void vtNetworkManager::UpdateDistributedObjects(DWORD flags) { ////////////////////////////////////////////////////////////////////////// //this is to store states in our dist objects xNetInterface *nInterface = GetClientNetInterface(); if (!nInterface) return; IDistributedObjects *doInterface = nInterface->getDistObjectInterface(); xDistributedObjectsArrayType *distObjects = nInterface->getDistributedObjects(); xDistObjectIt begin = distObjects->begin(); xDistObjectIt end = distObjects->end(); nInterface->setObjectUpdateCounter(0); if (nInterface->IsServer())return; ////////////////////////////////////////////////////////////////////////// while (begin!=end) { xDistributedObject* dobj = *begin; if (dobj && dobj->getOwnershipState().test(1<<E_DO_OS_OWNER) ) { xDistributedClass *_class = dobj->getDistributedClass(); if (_class != NULL ) { XString name(dobj->GetName().getString()); XString cName = _class->getClassName().getString(); int entType = _class->getEnitityType(); if (_class->getEnitityType() == E_DC_BTYPE_SESSION) { dobj->setUpdateState( E_DO_US_OK ); } if (_class->getEnitityType() == E_DC_BTYPE_3D_ENTITY ) { xDistributed3DObject *dobj3D = static_cast<xDistributed3DObject*>(dobj); if (dobj3D) { CK3dEntity *entity = (CK3dEntity*)m_Context->GetObject(dobj3D->getEntityID()); ////////////////////////////////////////////////////////////////////////// //if the object is ours then store the last known position in the state info : int oID = dobj3D->getUserID(); int myID = nInterface->getConnection()->getUserID(); DWORD oFlags = dobj->getObjectFlags(); DWORD iFlags = dobj3D->getInterfaceFlags(); if (entity) { TNL::U32 currentTime = TNL::Platform::getRealMilliseconds(); dobj->setUpdateState( E_DO_US_OK ); xDistributedPropertyArrayType &props = *dobj3D->getDistributedPorperties(); for (unsigned int i = 0 ; i < props.size() ; i++ ) { xDistributedProperty *prop = props[i]; xDistributedPropertyInfo*propInfo = prop->getPropertyInfo(); int blockIndex = prop->getBlockIndex(); if (propInfo) { switch(propInfo->mNativeType) { case E_DC_3D_NP_WORLD_POSITION : { xDistributedPoint3F * dpoint3F = (xDistributedPoint3F*)prop; if (dpoint3F) { VxVector posW; entity->GetPosition(&posW); bool update = dpoint3F->updateValue(xMath::getFrom(posW),currentTime); } break; } case E_DC_3D_NP_WORLD_ROTATION: { xDistributedQuatF * dpoint3F = (xDistributedQuatF*)prop; if (dpoint3F) { VxQuaternion vquat; entity->GetQuaternion(&vquat); bool update = dpoint3F->updateValue(xMath::getFrom(vquat),currentTime); } break; } } } } } } } } } begin++; } } <file_sep>/****************************************************************************** File : CustomPlayer.h Description: This file contains the CCustomPlayer class which is the "interface" with the Virtools SDK. All other files are Windows/MFC specific code. Virtools SDK Copyright (c) Virtools 2005, All Rights Reserved. ******************************************************************************/ #if !defined(CUSTOMPLAYER_H) #define CUSTOMPLAYER_H #include "CustomPlayerApp.h" /************************************************************************* Summary: This class defines the implementation of the Virtools Runtime/Player. Description: This class provides member functions for initializing the virtools runtime and for running it. Remarks: This class is a singleton. It means there is only one instance of it and you cannot instanciate it. To get an instance of the class use CCustomPlayer::Instance. See also: CCustomPlayerApp, Instance. *************************************************************************/ class CCustomPlayer { public : /************************************************************************* Summary: Retrieve the unique instance of the player. *************************************************************************/ static CCustomPlayer& Instance(); /************************************************************************* Summary: Release all data which has been created during the initializating and the execution of the player. *************************************************************************/ ~CCustomPlayer(); /************************************************************************* Summary: Initialize the player. Description: This function intialize the virtools engine (ck, render engine, ...) and load the composition Parameters: iMainWindow: the main window of the application. iRenderWindow: the render window. iConfig: the configuration of the player (see EConfigPlayer). iData: pointer to a string (if iDataSize==0) containing the name of the filename to load or pointer to the memory where the application is located (if iDataSize!=0). iDataSize: Size of the memory where the application is located if it is alredy in memory (can be null). *************************************************************************/ BOOL InitPlayer(HWND iMainWindow, HWND iRenderWindow, int iConfig, const void* iData, int iDataSize); /************************************************************************* Summary: Initialize the engine. Description: This function intialize the virtools engine (ck, render engine, ...) *************************************************************************/ int InitEngine(HWND iMainWindow); /************************************************************************* Summary: Play the composition. *************************************************************************/ void Play(); /************************************************************************* Summary: Pause the composition. *************************************************************************/ void Pause(); /************************************************************************* Summary: Reset the composition and play it. *************************************************************************/ void Reset(); /************************************************************************* Summary: Process one frame of the compisition *************************************************************************/ BOOL Process(int iConfig); /************************************************************************* Summary: Switch from fullscreen/windowed to windowed/fullscreen. Remarks: The player try to retrieve the resolution (fullscreen or windowed) from level attributes before switching. *************************************************************************/ BOOL SwitchFullscreen(); /************************************************************************* Summary: Change the current resolution (fullscreen or windowed Remarks: The player try to retrieve the resolution (fullscreen or windowed) from level attributes. If nothing has changed nothing is done. *************************************************************************/ BOOL ChangeResolution(); /************************************************************************* Summary: Manage the mouse clipping Parameters: TRUE to enable the mouse clipping. *************************************************************************/ BOOL ClipMouse(BOOL iEnable); /************************************************************************* Summary: Manage the WM_PAINT windows event. Description: In windowed mode we use the render context to render the scene. *************************************************************************/ void OnPaint(); /************************************************************************* Summary: Manage the mouse left button click. Description: Send a message (click or double click) to the object "picked" by the mouse, if any. *************************************************************************/ void OnMouseClick(int iMessage); /************************************************************************* Summary: Manage the focus changement. Description: - if the application is minimized (no focus) we paused it. - if the application is no more minimized (but was minimized) we restart it. - if the application focus is changin depending of the "Focus Lost Behavior" (see CKContext::GetFocusLostBehavior or the "Focus Lost Behavior" in the variable manager). *************************************************************************/ void OnFocusChange(BOOL iFocus); /************************************************************************* Summary: Manage the activty of the application. Description: If the application is deactivated while it is in fullscreen mode, we must switch to windowed mode. *************************************************************************/ void OnActivateApp(BOOL iActivate); /************************************************************************* Summary: Manage system keys (ALT + KEY) Description: If system keys are not diabled (see eDisableKeys) - ALT + ENTER -> SwitchFullscreen - ALT + F4 -> Quit the application *************************************************************************/ LRESULT OnSysKeyDownMainWindow(int iConfig, int iKey); /************************************************************************* Summary: Manage the activty of the application. Description: If the application is deactivated while it is in fullscreen mode, we must switch to windowed mode. *************************************************************************/ int DoSystemCheck(); void _InitContextAnd(); void _InitManagers(); void SetMainWindow(HWND _main){ m_MainWindow = _main;} vtPlayer::Structs::xEApplicationMode m_AppMode; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // [11/28/2007 mc007] xSEngineWindowInfo m_EngineWindowInfo; USHORT PLoadEngineWindowProperties(const char *configFile); xSEngineWindowInfo& GetEWindowInfo(){return m_EngineWindowInfo;} xSEnginePaths m_EPaths; USHORT PLoadEnginePathProfile(const char* configFile); xSEnginePaths& GetEPathProfile(){return m_EPaths;} xSApplicationWindowStyle m_AWStyle; USHORT PLoadAppStyleProfile(const char* configFile); xSApplicationWindowStyle&GetPAppStyle(){ return m_AWStyle;} xEApplicationMode PGetApplicationMode(const char* pstrCommandLine); xEApplicationMode PGetApplicationMode(){return m_AppMode;} API_INLINE vtPlayer::Structs::xSEnginePointers *GetEnginePointers(); API_INLINE vtPlayer::Structs::xSEngineWindowInfo *GetEngineWindowInfo(); void ShowSplash(); void SetSplashText(const char* text); void HideSplash(); //////////////////////////////////////// // accessors int& RasterizerFamily(); int& RasterizerFlags(); int& WindowedWidth(); int& WindowedHeight(); int& MininumWindowedWidth(); int& MininumWindowedHeight(); int& FullscreenWidth(); int& FullscreenHeight(); int Driver(); int& FullscreenBpp(); CKRenderContext* GetRenderContext(); protected: enum DriverFlags { eFamily = 1, eDirectXVersion = 2, eSoftware = 4 }; enum PlayerState { eInitial = 0, ePlaying = 1, ePlaused = 2, eFocusLost = 3, eMinimized = 4 }; BOOL _FinishLoad(); BOOL _InitPlugins(CKPluginManager& iPluginManager); int _InitRenderEngines(CKPluginManager& iPluginManager); CKERROR _Load(const char* str); CKERROR _Load(const void* iMemoryBuffer, int iBufferSize); void _MissingGuids(CKFile* iFile, const char* iResolvedFile); BOOL _GetWindowedResolution(); BOOL _GetFullScreenResolution(); void _SetResolutions(); BOOL _InitDriver(); BOOL _CheckDriver(VxDriverDesc* iDesc, int iFlags); BOOL _CheckFullscreenDisplayMode(BOOL iDoBest); int m_State; public: HWND m_MainWindow; HWND m_RenderWindow; // ck objects (context, managers, ...) CKContext* m_CKContext; CKRenderContext* m_RenderContext; CKMessageManager* m_MessageManager; CKRenderManager* m_RenderManager; CKTimeManager* m_TimeManager; CKAttributeManager* m_AttributeManager; CKInputManager* m_InputManager; vtPlayer::Structs::xSEnginePointers m_EnginePointers; CKLevel* m_Level; // attributes // from an exemple about using this attributes see sample.cmo which is delivered with this player sample int m_QuitAttType; // attribut without type, name is "Quit" int m_SwitchFullscreenAttType; // attribut without type, name is "Switch Fullscreen" int m_SwitchResolutionAttType; // attribut without type, name is "Switch Resolution" int m_SwitchMouseClippingAttType; // attribut without type, name is "Switch Mouse Clipping" int m_WindowedResolutionAttType; // attribut which type is Vector 2D, name is "Windowed Resolution" int m_FullscreenResolutionAttType; // attribut which type is Vector 2D, name is "Fullscreen Resolution" int m_FullscreenBppAttType; // attribut which type is Integer, name is "Fullscreen Bpp" // messages int m_MsgClick; int m_MsgDoubleClick; // display configuration int m_RasterizerFamily; // see CKRST_RSTFAMILY int m_RasterizerFlags; // see CKRST_SPECIFICCAPS int m_WindowedWidth; // windowed mode width int m_WindowedHeight; // windowed mode height int m_MinWindowedWidth; // windowed mode minimum width int m_MinWindowedHeight; // windowed mode minumum height int m_FullscreenWidth; // fullscreen mode width int m_FullscreenHeight; // fullscreen mode height int m_FullscreenBpp; // fullscreen mode bpp int m_Driver; // index of the current driver BOOL m_FullscreenEnabled; // is fullscreen enable BOOL m_EatDisplayChange; // used to ensure we are not switching mode will we are already switching BOOL m_MouseClipped; // used to know if the mouse is acutally cliped RECT m_MainWindowRect; int m_FullscreenRefreshRate; // fullscreen mode bpp int m_LastError; XString m_LastErrorText; private: // {secret} CCustomPlayer(); // {secret} CCustomPlayer(const CCustomPlayer&); // {secret} CCustomPlayer& operator=(const CCustomPlayer&); }; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // [11/28/2007 mc007] #define GetPlayer() CCustomPlayer::Instance() ////////////////////////////////////////////////////////////////////////// //************************************ // Method: GetEnginePointers // FullName: CCustomPlayer::GetEnginePointers // Access: public // Returns: vtPlayer::Structs::xSEnginePointers* // Qualifier: //************************************ vtPlayer::Structs::xSEnginePointers* CCustomPlayer::GetEnginePointers() { return &m_EnginePointers; } //************************************ // Method: GetEngineWindowInfo // FullName: CCustomPlayer::GetEngineWindowInfo // Access: public // Returns: vtPlayer::Structs::xSEngineWindowInfo* // Qualifier: //************************************ vtPlayer::Structs::xSEngineWindowInfo* CCustomPlayer::GetEngineWindowInfo() { return &m_EngineWindowInfo; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// inline int& CCustomPlayer::RasterizerFamily() { return m_RasterizerFamily; } inline int& CCustomPlayer::RasterizerFlags() { return m_RasterizerFlags; } inline int& CCustomPlayer::WindowedWidth() { return m_WindowedWidth; } inline int& CCustomPlayer::WindowedHeight() { return m_WindowedHeight; } inline int& CCustomPlayer::MininumWindowedWidth() { return m_MinWindowedWidth; } inline int& CCustomPlayer::MininumWindowedHeight() { return m_MinWindowedHeight; } inline int& CCustomPlayer::FullscreenWidth() { return m_FullscreenWidth; } inline int& CCustomPlayer::FullscreenHeight() { return m_FullscreenHeight; } inline int CCustomPlayer::Driver() { return m_Driver; } inline int& CCustomPlayer::FullscreenBpp() { return m_FullscreenBpp; } inline CKRenderContext* CCustomPlayer::GetRenderContext() { return m_RenderContext; } #endif // CUSTOMPLAYER_H<file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // SetFOV Camera // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" CKObjectDeclaration *FillBehaviorSetFOVDecl(); CKERROR CreateSetFOVProto(CKBehaviorPrototype **pproto); int SetFOV(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorSetFOVDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Set FOV"); od->SetDescription("Sets the Field Of View of the camera"); /* rem: <SPAN CLASS=in>In: </SPAN>triggers the process.<BR> <SPAN CLASS=out>Out: </SPAN>is activated when the process is completed.<BR> <BR> <SPAN CLASS=pin>Angle: </SPAN>field of view angle, expressed in radians.<BR> <BR> See Also: 'Set Zoom'.<BR> */ od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0xaaaacccc, 0xaaaacccc)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateSetFOVProto); od->SetCompatibleClassId(CKCID_CAMERA); od->SetCategory("Cameras/Basic"); return od; } CKERROR CreateSetFOVProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set FOV"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Angle", CKPGUID_ANGLE, "0:50"); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(SetFOV); proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); *pproto = proto; return CK_OK; } int SetFOV(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKCamera *cam = (CKCamera *) beh->GetTarget(); if( !cam ) return CKBR_OWNERERROR; float angle = 50.0f*PI/180; beh->GetInputParameterValue(0, &angle); cam->SetFov( angle ); beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); return CKBR_OK; } <file_sep>#include "precomp.h" #include "vtPrecomp.h" #include "vtNetAll.h" #include "xLogger.h" int liftimeMax = 2000; static vtNetworkManager *_im; extern xNetInterface* GetNetInterfaceServer(); extern xNetInterface *GetNetInterfaceClient(); extern void SetNetInterfaceClient(xNetInterface *cInterface); extern void SetNetInterfaceServer(xNetInterface *cInterface); vtNetworkManager::vtNetworkManager(CKContext* context):CKBaseManager(context,NET_MAN_GUID,"vtNetworkManager")//Name as used in profiler { m_Context->RegisterNewManager(this); localConnection = NULL; _im = this; mCurrentThresholdTicker = 0.0f; m_MinTickTime = 10.0f; initLogger(); TNL::logprintf("asdasdd"); xLogger::xLog(ELOGINFO,XL_START,"binding object"); /* xBitSet test = xLogger::GetInstance()->getLogLevel(E_LI_SESSION); bool f = test.test(1 << ELOGWARNING); bool f2 = test.test(1 << ELOGTRACE); int h =2;*/ //xLogger::GetInstance()->SetLogVerbosity(ELOGINFO); //xLogger::GetInstance()->SetLogVerbosity(ELOGERROR); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// vtNetworkManager*vtNetworkManager::Instance(){ return _im;} /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ vtNetworkManager::~vtNetworkManager() { if (GetServerNetInterface()) { SetServerNetInterface(NULL); } if (GetClientNetInterface()) { SetClientNetInterface(NULL); } } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ CKERROR vtNetworkManager::PostProcess() { if(GetClientNetInterface() && isFlagOn(GetNetInterfaceClient()->getInterfaceFlags(),E_NI_DESTROYED_BY_SERVER) ) { //TNL::logprintf("server left"); SetClientNetInterface(NULL); return 0; } mCurrentThresholdTicker =getCurrentThresholdTicker() + m_Context->GetTimeManager()->GetLastDeltaTime(); if (getCurrentThresholdTicker() > getMinTickTime() ) { mCurrentThresholdTicker = 0.0f; } /************************************************************************/ /* advance subsystems time : */ /************************************************************************/ if (GetServerNetInterface()) { //GetServerNetInterface()->advanceTime(TNL::Platform::getRealMilliseconds(),m_Context->GetTimeManager()->GetLastDeltaTime()); GetServerNetInterface()->getMessagesInterface()->advanceTime(m_Context->GetTimeManager()->GetLastDeltaTime()); } if(GetClientNetInterface()) { GetClientNetInterface()->advanceTime(TNL::Platform::getRealMilliseconds(),m_Context->GetTimeManager()->GetLastDeltaTime()); } /************************************************************************/ /* passing app values to distributed values, position,etc.... */ /************************************************************************/ if(GetClientNetInterface()) { if(GetClientNetInterface()->isValid()) { if (getCurrentThresholdTicker() < getMinTickTime() ) { UpdateDistributedObjects(0); } } GetClientNetInterface()->getMessagesInterface()->checkMessages(); GetClientNetInterface()->getMessagesInterface()->deleteAllOldMessages(); } /************************************************************************/ /* */ /************************************************************************/ if (GetServerNetInterface()) { GetServerNetInterface()->tick(); GetServerNetInterface()->getMessagesInterface()->checkMessages(); GetServerNetInterface()->getMessagesInterface()->deleteAllOldMessages(); } if(GetClientNetInterface()) { GetClientNetInterface()->tick(); } if(GetClientNetInterface() && GetClientNetInterface()->isValid()) { if (getCurrentThresholdTicker() < getMinTickTime() ) { performGhostUpdates(); } } return CK_OK; } //************************************ // Method: PreProcess // FullName: vt_python_man::PreProcess // Access: public // Returns: CKERROR // Qualifier: //************************************ CKERROR vtNetworkManager::PreProcess() { return CK_OK; } /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ CKERROR vtNetworkManager::PostClearAll(){ return CK_OK; } CKERROR vtNetworkManager::OnCKEnd(){ return CK_OK;} /* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ CKERROR vtNetworkManager::OnCKReset() { if (GetNetInterfaceClient()) { SetClientNetInterface(NULL); } if (GetNetInterfaceServer()) { SetServerNetInterface(NULL); } return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CKERROR vtNetworkManager::OnCKPlay() { return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CKERROR vtNetworkManager::OnCKInit(){ m_Context->ActivateManager((CKBaseManager*) this,true); return CK_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void vtNetworkManager::Test(const char*inpo) { xNetInterface *si= GetServerNetInterface(); if (si) { using namespace TNL; Socket *socket = &si->getSocket(); if (socket) { bool o = socket->isValid(); int o1 =0; } int csize = si->getConnectionList().size(); int op = 9 ; } }<file_sep>#ifndef _ISESSION_H_ #define _ISESSION_H_ #include "xNetTypes.h" class xNetInterface; class xDistributedSession; class xDistributedClient; class ISession { public: ISession(xNetInterface *nInterface) :mNetInterface(nInterface) {} xNetInterface * getNetInterface() const { return mNetInterface; } int create(xNString name,int maxUsers,xNString password,int type); xDistributedSession *get(xNString name); xDistributedSession *getByUserID(int userID); xDistributedSession *get(int sessionID); void deleteSession(int sessionID); int getNumSessions(); int joinClient(xDistributedClient*client, int sessionID,xNString password); int removeClient(xDistributedClient*client,int sessionID,bool destroy=false); void removeClient(int clientID); void lockSession(int userID,int sessionID); void unlockSession(int userID,int sessionID); uxString print(TNL::BitSet32 flags); protected: private: xNetInterface *mNetInterface; }; #endif<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "Stream.h" #include "cooking.h" #include "tinyxml.h" #include <xDebugTools.h> pWheel* pFactory::createWheel(CK3dEntity *bodyReference,CK3dEntity*srcReference,pWheelDescr wheelDescr,pConvexCylinderSettings convexCylinder,VxVector localPositionOffset) { //---------------------------------------------------------------- // // main objects // pRigidBody *body= GetPMan()->getBody(bodyReference); pWheel *wheel = NULL; bool assertCondition = true; iAssertWR(bodyReference,"",assertCondition); iAssertWR(body,"",assertCondition); iAssertWR(srcReference,"",assertCondition); if (!assertCondition) return NULL; iAssertWR(wheelDescr.isValid(),wheelDescr.setToDefault(),assertCondition); //---------------------------------------------------------------- // // adjust wheel description data // iAssertW(wheelDescr.radius.isValid(),wheelDescr.radius.evaluate(srcReference),""); if(!wheelDescr.radius.isValid()) wheelDescr.radius.value = srcReference->GetRadius(); pObjectDescr objectDescription; objectDescription.hullType = HT_Wheel; objectDescription.density = 1.0f; objectDescription.flags = (BodyFlags)(BF_SubShape|BF_Collision); objectDescription.setWheel(wheelDescr); objectDescription.mask|=OD_Wheel; if(body->addCollider(objectDescription,srcReference)) { NxShape*wheelShape = body->getSubShape(srcReference); //---------------------------------------------------------------- // // handle wheel types // //if( wheelShape && wheelShape->isWheel() && wheelDescr.wheelFlags & WF_UseWheelShape) //WF_UseWheelShape if( wheelShape && wheelShape->isWheel() ) { wheel = (pWheel*)createWheel(body,wheelDescr,srcReference); ((pWheel2*)wheel)->setWheelShape((NxWheelShape*)wheelShape); wheel->setEntID(srcReference->GetID()); // ((pWheel2*)wheel)->setEntity(static_cast<CK3dEntity*>(GetPMan()->GetContext()->GetObject(srcReference->GetID()))); ((pSubMeshInfo*)(wheelShape->userData))->wheel = wheel; wheel->setFlags(wheelDescr.wheelFlags); } } return wheel; } NxShape*pFactory::createWheelShape2(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr) { NxWheelShape *result = NULL; bool assertResult = true; pRigidBody *body=GetPMan()->getBody(bodyReference); iAssertWR(bodyReference && wheelReference && wheelDescr.isValid() && body ,"",assertResult); if (!assertResult) return NULL; CKMesh *mesh = wheelReference->GetCurrentMesh(); VxVector box_s = mesh->GetLocalBox().GetSize(); float radius = wheelDescr.radius.value > 0.0f ? wheelDescr.radius.value : box_s.v[wheelDescr.radius.referenceAxis] * 0.5f; VxQuaternion quatOffset; VxVector posOffset; vtAgeia::calculateOffsets(bodyReference,wheelReference,quatOffset,posOffset); CK_ID srcID = mesh->GetID(); NxWheelShapeDesc shape; shape.setToDefault(); shape.radius = radius; shape.localPose.M = pMath::getFrom(quatOffset); shape.localPose.t = pMath::getFrom(posOffset); float heightModifier = (wheelDescr.wheelSuspension + radius ) / wheelDescr.wheelSuspension; shape.suspension.spring = wheelDescr.springRestitution*heightModifier; shape.suspension.damper = wheelDescr.springDamping * heightModifier; shape.suspension.targetValue = wheelDescr.springBias * heightModifier; shape.suspensionTravel = wheelDescr.wheelSuspension; shape.inverseWheelMass = wheelDescr.inverseWheelMass; const pTireFunction& latFunc = wheelDescr.latFunc; const pTireFunction& longFunc = wheelDescr.longFunc; NxTireFunctionDesc lngTFD; lngTFD.extremumSlip = longFunc.extremumSlip ; lngTFD.extremumValue = longFunc.extremumValue; lngTFD.asymptoteSlip = longFunc.asymptoteSlip; lngTFD.asymptoteValue = longFunc.asymptoteValue; lngTFD.stiffnessFactor = longFunc.stiffnessFactor; NxTireFunctionDesc latTFD; latTFD.extremumSlip = latFunc.extremumSlip ; latTFD.extremumValue = latFunc.extremumValue; latTFD.asymptoteSlip = latFunc.asymptoteSlip; latTFD.asymptoteValue = latFunc.asymptoteValue; latTFD.stiffnessFactor = latFunc.stiffnessFactor; shape.lateralTireForceFunction =latTFD; shape.longitudalTireForceFunction = lngTFD; shape.wheelFlags =wheelDescr.wheelShapeFlags; result = (NxWheelShape*)body->getActor()->createShape(shape); return (NxShape*)result; } NxShape *pFactory::_createWheelShape1(NxActor *actor,pWheel1 *dstWheel,pObjectDescr *descr,pWheelDescr *wheelDescr,CK3dEntity*srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) { #ifdef _DEBUG assert(dstWheel); assert(descr); assert(wheelDescr); assert(srcReference || mesh ); #endif // _DEBUG NxShape *result = NULL; //################################################################ // // some setup data // NxQuat rot = pMath::getFrom(localRotation); NxVec3 pos = getFrom(localPos); CK_ID srcID = mesh->GetID(); NxConvexShapeDesc shape; if (!_createConvexCylinder(&shape,srcReference)) xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); shape.density = descr->density; shape.localPose.t = pMath::getFrom(localPos); shape.localPose.M = rot; if (descr->skinWidth!=-1.0f) shape.skinWidth = descr->skinWidth; //################################################################ // // Create the convex shape : // dstWheel->setWheelConvex(actor->createShape(shape)->isConvexMesh()); //if (!_createConvexCylinder(shape,srcReference)) // xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); //################################################################ // // Find the wheels cylinder description pConvexCylinderSettings cylDescr; findSettings(cylDescr,srcReference); cylDescr.radius.value *=0.5f; //################################################################ // // Create a joint spring for the suspension // NxReal heightModifier = (wheelDescr->wheelSuspension + cylDescr.radius.value) / wheelDescr->wheelSuspension; if (wheelDescr->wheelSuspension < 1) heightModifier = 1.f / wheelDescr->wheelSuspension; NxSpringDesc wheelSpring; wheelSpring.spring = wheelDescr->springRestitution*heightModifier; wheelSpring.damper = wheelDescr->springDamping*heightModifier; wheelSpring.targetValue = wheelDescr->springBias*heightModifier; //################################################################ // // The original code creates a material here ! We skip this ! // //######################### //################################################################ // // The wheel capsule is perpendicular to the floor // NxVec3 forwardAxis = getFrom(cylDescr.forwardAxis); NxVec3 downAxis = getFrom(cylDescr.downAxis); NxVec3 wheelAxis = getFrom(cylDescr.rightAxis); NxMaterialDesc materialDesc; materialDesc.restitution = 0.0f; materialDesc.dynamicFriction = wheelDescr->frictionToSide; materialDesc.staticFriction = 2.0f; materialDesc.staticFrictionV = wheelDescr->frictionToFront*4; materialDesc.dynamicFrictionV = wheelDescr->frictionToFront; materialDesc.dirOfAnisotropy = forwardAxis; materialDesc.frictionCombineMode = NX_CM_MULTIPLY; materialDesc.flags |= NX_MF_ANISOTROPIC; dstWheel->material = actor->getScene().createMaterial(materialDesc); NxCapsuleShapeDesc capsuleShape; capsuleShape.radius = cylDescr.radius.value * 0.1f; capsuleShape.height = wheelDescr->wheelSuspension + cylDescr.radius.value; capsuleShape.flags = NX_SWEPT_SHAPE; //capsuleShape.localPose.M.setColumn(0, NxVec3( 1, 0, 0)); //capsuleShape.localPose.M.setColumn(1, NxVec3( 0,-1, 0)); //capsuleShape.localPose.M.setColumn(2, NxVec3( 0, 0,-1)); //rotate 180 degrees around x axis to cast downward! capsuleShape.materialIndex = dstWheel->material->getMaterialIndex(); capsuleShape.localPose.M.setColumn(0, forwardAxis); capsuleShape.localPose.M.setColumn(1, downAxis); capsuleShape.localPose.M.setColumn(2, wheelAxis); if(wheelDescr->wheelSuspension >= 1) { capsuleShape.localPose.t = pos + downAxis*(cylDescr.radius.value); } else { capsuleShape.localPose.t = pos + (-1.0f *downAxis)*((cylDescr.radius.value + wheelDescr->wheelSuspension)*0.5f); } //################################################################ // // Finalize // result = dstWheel->getWheelConvex(); if (!capsuleShape.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Capsule shape description during wheel1 construction was invalid"); } dstWheel->setWheelCapsule(actor->createShape(capsuleShape)->isCapsule()); dstWheel->_radius = cylDescr.radius.value; dstWheel->_turnAngle = 0; dstWheel->_turnVelocity = 0; dstWheel->_perimeter = dstWheel->_radius * NxTwoPi; dstWheel->_maxSuspension = wheelDescr->wheelSuspension; dstWheel->_wheelWidth = cylDescr.height.value; dstWheel->_maxPosition = localPos; dstWheel->_frictionToFront = wheelDescr->frictionToFront; dstWheel->_frictionToSide = wheelDescr->frictionToSide; NxU32 contactReportFlags = actor->getContactReportFlags(); contactReportFlags |=NX_NOTIFY_ON_TOUCH; actor->setContactReportFlags(contactReportFlags); return dstWheel->getWheelCapsule(); } pWheel *pFactory::createWheelSubShape(pRigidBody *body,CK3dEntity* subEntity,CKMesh *mesh,pObjectDescr *descr,VxVector localPos, VxQuaternion localRotation,NxShape*dstShape) { //################################################################ // // Sanity checks // #ifdef _DEBUG assert(body && subEntity && descr ); // Should never occur ! #endif // _DEBUG XString errorStr; //################################################################ // // Retrieve the wheel setting from attribute // int attTypeWheelSettings = GetPMan()->att_wheelDescr; int attTypeConvexCylinderSettings = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR); if (!subEntity->HasAttribute(attTypeWheelSettings)) { errorStr.Format("Object %s has been set as wheel but there is no wheel attribute attached",subEntity->GetName()); xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorStr.CStr()); return NULL; } pWheelDescr *wDescr = new pWheelDescr(); CKParameterOut *par = subEntity->GetAttributeParameter(attTypeWheelSettings); if (par) { int err = copyTo(wDescr,par); if (!wDescr->isValid() ) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Wheel Description is invalid"); SAFE_DELETE(wDescr); return NULL; } } //################################################################ // // Construct the final wheel object basing on the type of the wheel // pWheel *result = NULL; //if(wDescr->wheelFlags & WF_UseWheelShape) { result = new pWheel2(body,wDescr,subEntity); /*else { //################################################################ // Wheel type 1 specified, check there is also a override for the convex cylinder if (!subEntity->HasAttribute(attTypeConvexCylinderSettings)) { errorStr.Format("Object %s has been created with default settings for convex cylinder shape",subEntity->GetName()); xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,errorStr.CStr()); } result = new pWheel1(body,wDescr); }*/ //################################################################ // // Create the wheel shape // //if(wDescr->wheelFlags & WF_UseWheelShape){ dstShape=_createWheelShape2(body->getActor(),descr,wDescr,subEntity,mesh,localPos,localRotation); ((pWheel2*)result)->setWheelShape((NxWheelShape*)dstShape); // } /*else { dstShape=_createWheelShape1(body->getActor(),(pWheel1*)result,descr,wDescr,subEntity,mesh,localPos,localRotation); }*/ if (!dstShape) { errorStr.Format("Couldn't create wheel shape for object %s",subEntity->GetName()); xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,errorStr.CStr()); SAFE_DELETE(wDescr); SAFE_DELETE(result); return NULL; } //################################################################ // // Finalize wheel setup // result->setEntID(subEntity->GetID()); return result; } pTireFunction pFactory::createTireFuncFromParameter(CKParameter *par) { pTireFunction result; result.setToDefault(); if (!par) { return result; } result.extremumSlip = vtTools::ParameterTools::GetValueFromParameterStruct<float>(par,1); result.extremumValue = vtTools::ParameterTools::GetValueFromParameterStruct<float>(par,2); result.asymptoteSlip = vtTools::ParameterTools::GetValueFromParameterStruct<float>(par,3); result.asymptoteValue= vtTools::ParameterTools::GetValueFromParameterStruct<float>(par,4); result.stiffnessFactor = vtTools::ParameterTools::GetValueFromParameterStruct<float>(par,5); /************************************************************************/ /* Lat Tire Func from XML ? */ /************************************************************************/ int xmlLinkId = vtTools::ParameterTools::GetValueFromParameterStruct<int>(par,0); if (xmlLinkId!=0) { XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,xmlLinkId ); loadFrom(result,nodeName.CStr(),getDefaultDocument()); if (!result.isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Latitude Tire Function was incorrect, setting to default"); result.setToDefault(); }else{ copyTo((CKParameterOut*)par,result); } } if (!result.isValid()) { result.setToDefault(); } return result; } int pFactory::copyTo(pWheelDescr *dst,CKParameter *src) { int result = 1; if (!src || !dst) { return NULL; } using namespace vtTools::ParameterTools; dst->setToDefault(); dst->wheelSuspension = GetValueFromParameterStruct<float>(src,E_WD_SUSPENSION); dst->springRestitution= GetValueFromParameterStruct<float>(src,E_WD_SPRING_RES); dst->springBias = GetValueFromParameterStruct<float>(src,E_WD_SPRING_BIAS); dst->springDamping= GetValueFromParameterStruct<float>(src,E_WD_DAMP); dst->maxBrakeForce= GetValueFromParameterStruct<float>(src,E_WD_MAX_BFORCE); dst->frictionToSide= GetValueFromParameterStruct<float>(src,E_WD_FSIDE); dst->frictionToFront= GetValueFromParameterStruct<float>(src,E_WD_FFRONT); CKParameterOut *pOld = GetParameterFromStruct(src,E_WD_INVERSE_WHEEL_MASS); if (pOld) { if (pOld->GetGUID() == CKPGUID_FLOAT) { dst->inverseWheelMass= GetValueFromParameterStruct<float>(src,E_WD_INVERSE_WHEEL_MASS); } if (pOld->GetGUID() == CKPGUID_INT) { dst->wheelApproximation= GetValueFromParameterStruct<int>(src,E_WD_INVERSE_WHEEL_MASS); } } //dst->wheelApproximation= GetValueFromParameterStruct<int>(float,E_WD_INVERSE_WHEEL_MASS); dst->wheelFlags= (WheelFlags)GetValueFromParameterStruct<int>(src,E_WD_FLAGS); dst->wheelShapeFlags=(WheelShapeFlags) GetValueFromParameterStruct<int>(src,E_WD_SFLAGS); CKParameterOut *parLatFunc = GetParameterFromStruct(src,E_WD_LAT_FUNC); CKParameterOut *parLongFunc = GetParameterFromStruct(src,E_WD_LONG_FUNC); /************************************************************************/ /* XML Setup ? */ /************************************************************************/ int xmlLinkId= GetValueFromParameterStruct<int>(src,E_WD_XML); bool wIsXML=false; bool latIsXML= false; bool longIsXML=false; XString nodeName; if ( xmlLinkId !=0 ) { nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_WHEEL_SETTINGS,xmlLinkId); loadWheelDescrFromXML(*dst,nodeName.CStr(),getDefaultDocument()); wIsXML =true; if (!dst->isValid()) { xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Wheel Description was invalid"); } if (dst->latFunc.xmlLink!=0) { latIsXML=true; } if (dst->longFunc.xmlLink!=0) { longIsXML=true; } } if (!latIsXML) { dst->latFunc = createTireFuncFromParameter(parLatFunc); } if (!longIsXML) { dst->longFunc= createTireFuncFromParameter(parLongFunc); } if (wIsXML) { copyTo((CKParameterOut*)src,dst); } if (longIsXML) { copyTo(GetParameterFromStruct(src,E_WD_LONG_FUNC),dst->longFunc); } if (latIsXML) { copyTo(GetParameterFromStruct(src,E_WD_LAT_FUNC),dst->latFunc); } return result; } NxShape *pFactory::_createWheelShape2(NxActor *actor, pObjectDescr *descr, pWheelDescr *wheelDescr, CK3dEntity*srcReference,CKMesh *mesh, VxVector localPos, VxQuaternion localRotation) { NxWheelShape *result = NULL; if (!actor || !descr || !mesh ) { return result; } int hType = descr->hullType; VxVector box_s = mesh->GetLocalBox().GetSize(); float density = descr->density; float skinWidth = descr->skinWidth; float radius = box_s.x*0.5f; NxQuat rot = pMath::getFrom(localRotation); CK_ID srcID = mesh->GetID(); NxWheelShapeDesc shape; shape.setToDefault(); shape.radius = box_s.z*0.5f; shape.density = density; shape.localPose.M = rot; shape.localPose.t = pMath::getFrom(localPos); if (skinWidth!=-1.0f) shape.skinWidth = skinWidth; float heightModifier = (wheelDescr->wheelSuspension + radius ) / wheelDescr->wheelSuspension; shape.suspension.spring = wheelDescr->springRestitution*heightModifier; shape.suspension.damper = wheelDescr->springDamping * heightModifier; shape.suspension.targetValue = wheelDescr->springBias * heightModifier; shape.suspensionTravel = wheelDescr->wheelSuspension; //shape.lateralTireForceFunction.stiffnessFactor *= wheelDescr->frictionToSide; //shape.longitudalTireForceFunction.stiffnessFactor*=wheelDescr->frictionToFront; shape.inverseWheelMass = wheelDescr->inverseWheelMass; const pTireFunction& latFunc = wheelDescr->latFunc; const pTireFunction& longFunc = wheelDescr->longFunc; NxTireFunctionDesc lngTFD; lngTFD.extremumSlip = longFunc.extremumSlip ; lngTFD.extremumValue = longFunc.extremumValue; lngTFD.asymptoteSlip = longFunc.asymptoteSlip; lngTFD.asymptoteValue = longFunc.asymptoteValue; lngTFD.stiffnessFactor = longFunc.stiffnessFactor; NxTireFunctionDesc latTFD; latTFD.extremumSlip = latFunc.extremumSlip ; latTFD.extremumValue = latFunc.extremumValue; latTFD.asymptoteSlip = latFunc.asymptoteSlip; latTFD.asymptoteValue = latFunc.asymptoteValue; latTFD.stiffnessFactor = latFunc.stiffnessFactor; if ( !(wheelDescr->wheelFlags & WF_IgnoreTireFunction) ) { shape.lateralTireForceFunction =latTFD; shape.longitudalTireForceFunction = lngTFD; } //shape.wheelFlags = wheelDescr->wheelFlags; //shape.wheelFlags |= (NxWheelShapeFlags(NX_WF_WHEEL_AXIS_CONTACT_NORMAL)); //shape.shapeFlags = wheelDescr->wheelShapeFlags; shape.wheelFlags =wheelDescr->wheelShapeFlags; /* if (wheelDescr->wheelFlags & (WF_Accelerated|WF_UseWheelShape) ) { int isValid = shape.isValid(); } */ int isValid = shape.isValid(); result = (NxWheelShape*)actor->createShape(shape); if (result) { //result->setWheelFlags(wheelDescr->wheelFlags); //pWheel::getWheelFlag() /* if ( & E_WF_VEHICLE_CONTROLLED ) { int isValid = shape.isValid(); } */ } return (NxShape*)result; } NxShape *pFactory::createWheelShape(NxActor *actor, pObjectDescr *descr, pWheelDescr *wheelDescr, CK3dEntity*srcReference,CKMesh *mesh, VxVector localPos, VxQuaternion localRotation) { // if(wheelDescr->wheelFlags & WF_UseWheelShape){ return _createWheelShape2(actor,descr,wheelDescr,srcReference,mesh,localPos,localRotation); /*}else return NULL;//_createWheelShape1(actor,descr,wheelDescr,srcReference,mesh,localPos,localRotation); */ return NULL; } pWheel*pFactory::createWheel(pRigidBody *body,pWheelDescr descr,CK3dEntity *wheelShapeReference) { pWheel *result = NULL; if (!body || !body->isValid() ) { return result; } //if(descr.wheelFlags & WF_UseWheelShape) { result = new pWheel2(body,&descr,wheelShapeReference); /* }else { result = new pWheel1(body,&descr); } */ if (result) { result->setFlags(descr.wheelFlags); }// return result; } XString pFactory::_getVehicleTireFunctionAsEnumeration(const TiXmlDocument * doc) { if (!doc) { return XString(""); } XString result("None=0"); int counter = 1; /************************************************************************/ /* */ /************************************************************************/ if ( doc) { const TiXmlElement *root = getFirstDocElement(doc->RootElement()); for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) { if ( (child->Type() == TiXmlNode::ELEMENT)) { XString name = child->Value(); if (!strcmp(child->Value(), "tireFunction" ) ) { const TiXmlElement *sube = (const TiXmlElement*)child; const char* vSName = NULL; vSName = sube->Attribute("name"); if (vSName && strlen(vSName)) { if (result.Length()) { result << ","; } result << vSName; result << "=" << counter; counter ++; } } } } } return result; } int pFactory::copyTo(pWheelDescr &dst,CKParameterOut *src) { if (!src)return false; using namespace vtTools::ParameterTools; int result = 0; //SetParameterStructureValue<float>(dst,E_WD_SPRING_BIAS,src.,false); return result; } int pFactory::copyTo(CKParameterOut *dst,const pTireFunction& src) { if (!dst)return false; using namespace vtTools::ParameterTools; int result = 0; SetParameterStructureValue<int>(dst,0,src.xmlLink,false); SetParameterStructureValue<float>(dst,1,src.extremumSlip,false); SetParameterStructureValue<float>(dst,2,src.extremumValue,false); SetParameterStructureValue<float>(dst,3,src.asymptoteSlip,false); SetParameterStructureValue<float>(dst,4,src.asymptoteValue,false); SetParameterStructureValue<float>(dst,5,src.stiffnessFactor,false); return result; } int pFactory::copyTo(CKParameterOut *dst,pWheelDescr *src) { if (!src)return false; using namespace vtTools::ParameterTools; int result = 0; SetParameterStructureValue<float>(dst,E_WD_SPRING_BIAS,src->springBias,false); SetParameterStructureValue<float>(dst,E_WD_SPRING_RES,src->springRestitution,false); SetParameterStructureValue<float>(dst,E_WD_DAMP,src->springDamping,false); SetParameterStructureValue<float>(dst,E_WD_MAX_BFORCE,src->maxBrakeForce,false); SetParameterStructureValue<float>(dst,E_WD_FFRONT,src->frictionToFront,false); SetParameterStructureValue<float>(dst,E_WD_FSIDE,src->frictionToSide,false); SetParameterStructureValue<int>(dst,E_WD_FLAGS,src->wheelFlags,false); SetParameterStructureValue<int>(dst,E_WD_SFLAGS,src->wheelShapeFlags,false); SetParameterStructureValue<float>(dst,E_WD_INVERSE_WHEEL_MASS,src->inverseWheelMass,false); return result; } int pFactory::copyTo(CKParameterOut *dst,const pWheelContactData& src) { if (!dst)return false; using namespace vtTools::ParameterTools; int result = 0; SetParameterStructureValue<VxVector>(dst,E_WCD_CPOINT,src.contactPoint,false); SetParameterStructureValue<VxVector>(dst,E_WCD_CNORMAL,src.contactNormal,false); SetParameterStructureValue<VxVector>(dst,E_WCD_LONG_DIR,src.longitudalDirection,false); SetParameterStructureValue<VxVector>(dst,E_WCD_LAT_DIR,src.lateralDirection,false); SetParameterStructureValue<float>(dst,E_WCD_CONTACT_FORCE,src.contactForce,false); SetParameterStructureValue<float>(dst,E_WCD_LONG_SLIP,src.longitudalSlip,false); SetParameterStructureValue<float>(dst,E_WCD_LAT_SLIP,src.lateralSlip,false); SetParameterStructureValue<float>(dst,E_WCD_LONG_IMPULSE,src.longitudalImpulse,false); SetParameterStructureValue<float>(dst,E_WCD_LAT_IMPULSE,src.lateralImpulse,false); SetParameterStructureValue<float>(dst,E_WCD_C_POS,src.contactPosition,false); if (src.contactEntity) { SetParameterStructureValue<CK_ID>(dst,E_WCD_CONTACT_ENTITY,src.contactEntity->GetID(),false); } CKParameter *materialParameter = vtTools::ParameterTools::GetParameterFromStruct(dst,E_WCD_OTHER_MATERIAL_INDEX,false); pFactory::Instance()->copyTo((CKParameterOut*)materialParameter,src.otherMaterial); return result; } bool pFactory::loadFrom(pWheelDescr& dst,const char* nodeName) { return loadWheelDescrFromXML(dst,nodeName,getDefaultDocument()); }<file_sep>/*********************************************************************NVMH4**** Path: SDK\LIBS\inc\shared File: NV_StringFuncs.cpp Copyright NVIDIA Corporation 2002 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Comments: See NV_StringFuncs.h for comments. ******************************************************************************/ #include "3D\NV_StringFuncs.h" #include "3D\NV_Common.h" #include "3D\NV_Error.h" #pragma warning(disable : 4786) #include <string> #include <vector> #include <list> #include <string.h> #include <stdio.h> #include <stdarg.h> namespace NVStringConv { // use as an alternative to wcstombs() std::string WStringToString( const std::wstring * in_pwstring ) { if( in_pwstring == NULL ) return( "" ); return( lpcwstrToString( in_pwstring->c_str() )); } std::string WStringToString( std::wstring & in_wstring ) { return( lpcwstrToString( in_wstring.c_str() )); } std::string lpcwstrToString( LPCWSTR in_lpcwstr ) { //@ consider using windows.h WideCharToMultiByte(..) char * mbBuf; size_t sz; sz = 2 * wcslen( in_lpcwstr ); mbBuf = new char[sz]; if( mbBuf == NULL ) return( "" ); wcstombs( mbBuf, in_lpcwstr, sz ); // convert the string std::string outstr; outstr = mbBuf; delete [] mbBuf; return( outstr ); } std::wstring StringToWString( const std::string * in_pString ) { std::wstring wstr = L""; if( in_pString != NULL ) wstr = lpcstrToWString( in_pString->c_str() ); return( wstr ); } std::wstring StringToWString( std::string & in_String ) { return( lpcstrToWString( in_String.c_str() )); } std::wstring lpcstrToWString( LPCSTR lpstr ) { int nLen = MultiByteToWideChar( CP_ACP, 0, lpstr, -1, NULL, NULL); LPWSTR lpszW = new WCHAR[nLen+1]; MultiByteToWideChar( CP_ACP, 0, lpstr, -1, lpszW, nLen); lpszW[nLen] = '\0'; std::wstring wstr; wstr.reserve( nLen ); wstr.insert( 0, lpszW ); // wstr = lpszW; delete[] lpszW; return( wstr ); } }; // namespace NVStringConv //--------------------------------------------------------------------------- // Create a string using va_args, just like printf, sprintf, etc. std::string StrPrintf( const char * szFormat, ... ) { std::string out; const int bufsz = 2048; char buffer[ bufsz ]; va_list args; va_start( args, szFormat ); _vsnprintf( buffer, bufsz, szFormat, args ); va_end( args ); buffer[bufsz-1] = '\0'; // terminate in case of overflow out = buffer; return( out ); } std::string StrToUpper( const std::string & strIn ) { unsigned int i; std::string out; out.reserve( strIn.size() ); for( i=0; i < strIn.size(); i++ ) { out += toupper( strIn.at(i) ); } return( out ); } std::string StrToLower( const std::string & strIn ) { unsigned int i; std::string out; out.reserve( strIn.size() ); for( i=0; i < strIn.size(); i++ ) { out += tolower( strIn.at(i) ); } return( out ); } std::string StrsToString( const std::vector< std::string > & vstrIn ) { return( StrsToString( vstrIn, " " )); } // same as above, but lets you specify the separator std::string StrsToString( const std::vector< std::string > & vstrIn, const std::string & separator ) { std::string out; out.reserve( vstrIn.size() * 5 ); // rough estimate, 5 chars per string unsigned int i; for( i=0; i < vstrIn.size(); i++ ) { out += vstrIn.at(i) + separator; } return( out ); } std::string StrsToString( const std::list< std::string > & lstrIn, const std::string & separator ) { std::string out; out.reserve( lstrIn.size() * 5 ); std::list< std::string>::const_iterator p; for( p = lstrIn.begin(); p != lstrIn.end(); p++ ) { out += (*p) + separator; } return( out ); } std::string * StrReplace( const std::string & sequence_to_replace, const std::string & replacement_string, const std::string & strIn, std::string * pOut, bool bVerbose ) { if( pOut == NULL ) return( pOut ); if( & strIn == pOut ) { // can't have strIn and pOut point to the same thing // have to copy the input string std::string incpy = strIn; return( StrReplace( sequence_to_replace, replacement_string, incpy, pOut )); } // Similar functionality to CString::Replace(), but no MFC required. unsigned int i; std::vector< size_t > vpos; std::string::size_type pos; pos = 0; *pOut = ""; do { pos = strIn.find( sequence_to_replace, pos ); if( pos != std::string::npos ) { vpos.push_back( pos ); pos++; } } while( pos != std::string::npos ); if( bVerbose ) { FMsg("found at "); for( i=0; i < vpos.size(); i++ ) { FMsg("%d ", vpos.at(i) ); } FMsg("\n"); } size_t last_pos = 0; size_t repl_size = sequence_to_replace.size(); pOut->reserve( strIn.size() + vpos.size() * replacement_string.size() - vpos.size() * repl_size ); // last_pos marks character which should be included // in the output string for( i=0; i < vpos.size(); i++ ) { *pOut += strIn.substr( last_pos, vpos.at(i) - last_pos ); last_pos = vpos.at(i) + repl_size; *pOut += replacement_string; } // add remainder of orig string to the end *pOut += strIn.substr( last_pos, strIn.size() - last_pos ); return( pOut ); } std::string StrReplace( const std::string & sequence_to_replace, const std::string & replacement_string, const std::string & strIn ) { std::string out; StrReplace( sequence_to_replace, replacement_string, strIn, &out ); return( out ); } std::string StrTokenize( const std::string & strIn, const std::string & delimiters ) { // applies strtok repeatedly & acumulates ouput tokens // in output string separated by spaces return( StrTokenize( strIn, delimiters, " " )); } std::string StrTokenize( const std::string & strIn, const std::string & delimiters, const std::string & output_separator ) { // Same as above, but allows you to specify the separator between // tokens in the output // No trailing separator is added std::string out; char * token; char * copy = new char[strIn.size()+2]; // +2 just to be safe! strcpy( copy, strIn.c_str() ); token = strtok( copy, delimiters.c_str() ); while( token != NULL ) { out += token; token = strtok( NULL, delimiters.c_str() ); // If there's another token, add the separator // This means there is no trailing separator. if( token != NULL ) { out += output_separator; } } delete[] copy; return( out ); } sfsizet StrFindCaseless( const std::string & strSearchIn, sfsizet start_pos, const std::string & strSearchFor ) { sfsizet outpos = std::string::npos; std::string sin = StrToUpper( strSearchIn ); std::string sfor = StrToUpper( strSearchFor ); outpos = sin.find( sfor, start_pos ); return( outpos ); } std::vector< sfsizet > StrFindAllCaseless( const std::string & strSearchIn, sfsizet start_pos, const std::string & strSearchFor ) { std::vector< sfsizet > out; sfsizet pos = start_pos; std::string sin = StrToUpper( strSearchIn ); std::string sfor = StrToUpper( strSearchFor ); while( pos != std::string::npos ) { pos = sin.find( sfor, pos ); if( pos != std::string::npos ) { out.push_back( pos ); pos++; } } return( out ); } std::vector< sfsizet > StrFindAll( const std::string & strSearchIn, sfsizet start_pos, const std::string & strSearchFor ) { std::vector< sfsizet > out; sfsizet pos = start_pos; while( pos != std::string::npos ) { pos = strSearchIn.find( strSearchFor, pos ); if( pos != std::string::npos ) { out.push_back( pos ); pos++; } } return( out ); } std::vector< std::string> StrSort( const std::vector< std::string > & vStrIn ) { std::vector< std::string > vOut; std::list< std::string > lstr; unsigned int i; for( i=0; i < vStrIn.size(); i++ ) { lstr.push_back( vStrIn.at(i) ); } lstr.sort(); std::list< std::string>::const_iterator p; for( p = lstr.begin(); p != lstr.end(); p++ ) { vOut.push_back( *p ); } return( vOut ); } //------------------------------------------------------------------- // Reduce a full or relative path name to just a lone filename. // Example: // name = GetFilenameFromFullPath( "C:\MyFiles\project1\texture.dds" ); // name is "texture.dds" // Returns the input string if no path info was found & removed. //------------------------------------------------------------------- tstring GetFilenameFromFullPath( const tstring & full_path ) { size_t pos; pos = full_path.find_last_of( '\\', full_path.length() ); if( pos == tstring::npos ) pos = full_path.find_last_of( '/', full_path.length() ); if( pos == tstring::npos ) return( full_path ); tstring name; name = full_path.substr( pos+1, full_path.length() ); return( name ); } <file_sep>#include "CKAll.h" CKObjectDeclaration *FillBehaviorGetAdaptersModieDecl(); CKERROR CreateGetAdaptersModieProto(CKBehaviorPrototype **pproto); int GetAdaptersModie(const CKBehaviorContext& behcontext); /************************************************************************/ /* */ /************************************************************************/ CKObjectDeclaration *FillBehaviorGetAdaptersModieDecl(){ CKObjectDeclaration *od = CreateCKObjectDeclaration("GetAdaptersModie"); od->SetDescription("Add Objects"); od->SetCategory("Narratives/System"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x17ad4ca4,0x5bab3ee7)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("mw"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateGetAdaptersModieProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateGetAdaptersModieProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("GetAdaptersModie"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("Start"); proto->DeclareInput("Finish"); proto->DeclareOutput("Finish"); proto->DeclareOutput("LoopOut"); proto->DeclareInParameter("driver index",CKPGUID_INT); proto->DeclareOutParameter("modie index",CKPGUID_INT); proto->DeclareOutParameter("width",CKPGUID_INT); proto->DeclareOutParameter("height",CKPGUID_INT); proto->DeclareOutParameter("bpp",CKPGUID_INT); proto->DeclareOutParameter("refresh rate",CKPGUID_INT); proto->DeclareOutParameter("modie count",CKPGUID_INT); proto->SetFunction(GetAdaptersModie); *pproto = proto; return CK_OK; } int indexDD = 0; int GetAdaptersModie(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; CKPluginManager* ThePluginManager=CKGetPluginManager(); CKRenderManager *rm = (CKRenderManager *)ctx->GetRenderManager(); int DriverIndex=0; beh->GetInputParameterValue(0, &DriverIndex); VxDriverDesc *desc=rm->GetRenderDriverDescription(DriverIndex); int mocount = desc->DisplayModes.Size(); int countDD =rm->GetRenderDriverCount(); if( beh->IsInputActive(0) ) { beh->ActivateInput(0, FALSE); indexDD = 0; beh->SetOutputParameterValue(5,&mocount); return CKBR_OK; } if ( indexDD >=mocount-1 /*|| DriverIndex < countDD */) { indexDD = 0; beh->ActivateOutput(0,TRUE); return CKBR_OK; } if( beh->IsInputActive(1) ) { beh->ActivateInput(1, FALSE); beh->SetOutputParameterValue(1,&desc->DisplayModes[indexDD].Width); beh->SetOutputParameterValue(2,&desc->DisplayModes[indexDD].Height); beh->SetOutputParameterValue(3,&desc->DisplayModes[indexDD].Bpp); beh->SetOutputParameterValue(4,&desc->DisplayModes[indexDD].RefreshRate); beh->SetOutputParameterValue(0,&indexDD); indexDD++; beh->ActivateOutput(1,TRUE); return CKBR_OK; } return CKBR_OK; } <file_sep>direct x library files from March 2009, needed for joystick plugins <file_sep>#include <WTypes.h> #include "vt_tools.h" /* ******************************************************************* * Function: IsNumeric() * * Description : Check each character of the string If a character at a certain position is not a digit, then the string is not a valid natural number * Parameters : char*Str,r : the string to test * Returns : int * ******************************************************************* */ int vtTools::ParameterTools:: IsNumeric(const char* Str,vtTools::Enums::SuperType superType) { bool dotAlreadyFound = false; //allow empty strings : if(strlen(Str) == 0 ) { return true; } using namespace vtTools::Enums; for(unsigned int i = 0; i < strlen(Str); i++) { if( Str[i] < '0' || Str[i] > '9' ) { if ( ( Str[i] == '.' || Str[i] == ',') ) { if (superType == vtINTEGER ) { return false; } if (dotAlreadyFound) { return false; } dotAlreadyFound = true; continue; } if (!(i == 0 && Str[i]== '-')) { return false; } } } return true; } /* ******************************************************************* * Function: CreateWidgetInfo() * * Description : CreateWidgetInfo returns an handy info about an parameter type an a given string value of this parameter. * Parameters : CKContext* context, r : the virtools context. CKParameterType parameterType, r : the type to test. XString stringValue,r : the string value of the given type. * Returns : WidgetInfo ******************************************************************* */ vtTools::Structs::WidgetInfo* vtTools::ParameterTools:: CreateWidgetInfo(CKContext* context, CKParameterType parameterType, XString stringValue) { using namespace vtTools::Structs; using namespace vtTools::Enums; using namespace vtTools::ParameterTools; CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); CKGUID guid =pm->ParameterTypeToGuid(parameterType); WidgetInfo* result = new WidgetInfo(); result->parameterInfo = GetParameterInfo(context,parameterType); CKParameterLocal *localCopy = context->CreateCKParameterLocal("buffer",guid,TRUE); localCopy->SetStringValue(stringValue.Str()); switch(result->parameterInfo.superType) { ////////////////////////////////////////////////////////////////////////// color ////////////////////////////////////////////////////////////////////////// case vtCOLOUR: { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); VxColor realValue; localCopy->GetValue(&realValue); DWORD32 dColor = realValue.GetRGBA(); int r = ColorGetRed(dColor); int g = ColorGetGreen(dColor); int b = ColorGetBlue(dColor); int a = ColorGetAlpha(dColor); item->value << r << "," << g << "," << b << "," << a; item->widgetType = EVT_WIDGET_COLOR_SELECTION; result->items.PushBack(item); break; } ////////////////////////////////////////////////////////////////////////// integer ////////////////////////////////////////////////////////////////////////// case vtFLOAT: { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); float realValue; localCopy->GetValue(&realValue); item->value << realValue; item->widgetType = EVT_WIDGET_EDIT_TEXT; result->items.PushBack(item); break; } ////////////////////////////////////////////////////////////////////////// integer ////////////////////////////////////////////////////////////////////////// case vtINTEGER: { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); int realValue; localCopy->GetValue(&realValue); item->value << realValue; item->widgetType = EVT_WIDGET_EDIT_TEXT; result->items.PushBack(item); break; } ////////////////////////////////////////////////////////////////////////// bool ////////////////////////////////////////////////////////////////////////// case vtBOOL: { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); CKBOOL realValue; localCopy->GetValue(&realValue); item->value << realValue; item->widgetType = EVT_WIDGET_CHECK_BUTTON; result->items.PushBack(item); break; } ////////////////////////////////////////////////////////////////////////// string or file ////////////////////////////////////////////////////////////////////////// case vtFile : { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); item->value = stringValue; item->widgetType = EVT_WIDGET_FILE_SELECTION; result->items.PushBack(item); break; } case vtSTRING: { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); item->value = stringValue; item->widgetType = EVT_WIDGET_EDIT_TEXT; result->items.PushBack(item); break; } ////////////////////////////////////////////////////////////////////////// box ////////////////////////////////////////////////////////////////////////// case vtBOX: { for (int i = 0 ; i < 6 ; i ++ ) { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); VxBbox realValue; localCopy->GetValue(&realValue); item->widgetType = EVT_WIDGET_EDIT_TEXT; switch(i) { case 0: item->value << realValue.v[i]; item->label = "min x: "; break; case 1: item->value << realValue.v[i]; item->label = "min y: "; break; case 2: item->value << realValue.v[i]; item->label = "min z: "; break; case 3: item->value << realValue.v[i]; item->label = "max x: "; break; case 4: item->value << realValue.v[i]; item->label = "max y: "; break; case 5: item->value << realValue.v[i]; item->label = "max z: "; break; } result->items.PushBack(item); } break; } ////////////////////////////////////////////////////////////////////////// rectangle ////////////////////////////////////////////////////////////////////////// case vtRECTANGLE: { for (int i = 0 ; i < 4 ; i ++ ) { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); VxRect realValue; localCopy->GetValue(&realValue); item->widgetType = EVT_WIDGET_EDIT_TEXT; switch(i) { case 0: item->value << realValue.left; item->label = "Left: "; break; case 1: item->value << realValue.top; item->label = "Top: "; break; case 2: item->value << realValue.right; item->label = "Right: "; break; case 3: item->value << realValue.bottom; item->label = "Bottom: "; break; } result->items.PushBack(item); } break; } ////////////////////////////////////////////////////////////////////////// vector 2 ////////////////////////////////////////////////////////////////////////// case vtVECTOR2D: { for (int i = 0 ; i < 2 ; i ++ ) { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); Vx2DVector VectorValue; localCopy->GetValue(&VectorValue); item->value << VectorValue[i]; item->widgetType = EVT_WIDGET_EDIT_TEXT; switch(i) { case 0: item->label = "x: "; break; case 1: item->label = "y: "; } result->items.PushBack(item); } break; } ////////////////////////////////////////////////////////////////////////// vector 3 ////////////////////////////////////////////////////////////////////////// case vtVECTOR: { for (int i = 0 ; i < 3 ; i ++ ) { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); VxVector VectorValue; localCopy->GetValue(&VectorValue); item->value << VectorValue[i]; item->widgetType = EVT_WIDGET_EDIT_TEXT; switch(i) { case 0: item->label = "x"; break; case 1: item->label = "y"; break; case 2: item->label = "z"; break; } result->items.PushBack(item); } break; } ////////////////////////////////////////////////////////////////////////// vector4 ////////////////////////////////////////////////////////////////////////// case vtQUATERNION: { for (int i = 0 ; i < 4 ; i ++ ) { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); VxQuaternion realValue; localCopy->GetValue(&realValue); item->value << realValue[i]; item->widgetType = EVT_WIDGET_EDIT_TEXT; switch(i) { case 0: item->label = "x: "; break; case 1: item->label = "y: "; break; case 2: item->label = "z: "; break; case 3: item->label = "w: "; break; } result->items.PushBack(item); } break; } ////////////////////////////////////////////////////////////////////////// enumeration ////////////////////////////////////////////////////////////////////////// case vtENUMERATION: { CKEnumStruct *enumStruct = pm->GetEnumDescByType(parameterType); if ( enumStruct ) { for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); item->value = enumStruct->GetEnumDescription(i); item->widgetType = EVT_WIDGET_COMBO_BOX; result->items.PushBack(item); } } break; } ////////////////////////////////////////////////////////////////////////// flags ////////////////////////////////////////////////////////////////////////// case vtFLAGS: { CKFlagsStruct*flagStruct = pm->GetFlagsDescByType(parameterType); if ( flagStruct ) { for (int i = 0 ; i < flagStruct->GetNumFlags() ; i ++ ) { WidgetInfo::WidgetInfoItem *item = new WidgetInfo::WidgetInfoItem(); item->value = flagStruct->GetFlagDescription(i); item->widgetType = EVT_WIDGET_CHECK_BUTTON; result->items.PushBack(item); } } break; } } return result; } /* ******************************************************************* * Function: GetParameterMemberInfo() * * Description : GetParameterMemberInfo returns the type super type of the used structure members. Example : vtVECTOR returns vtFLOAT * * Parameters : CKContext* context, r : the virtools context. CKParameterType parameterType, r : the type to test. * Returns : SuperType * ******************************************************************* */ vtTools::Enums::SuperType vtTools::ParameterTools::GetParameterMemberInfo(CKContext* context,CKParameterType parameterType) { assert ( context ); using namespace vtTools::Enums; using namespace vtTools::ParameterTools; SuperType superType = GetVirtoolsSuperType(context,context->GetParameterManager()->ParameterTypeToGuid(parameterType)); switch(superType) { case vtENUMERATION: return vtSTRING; case vtBOOL: case vtFLAGS: return vtBOOL; case vtCOLOUR: return vtCOLOUR; case vtFile: return vtFile; case vtINTEGER: return vtINTEGER; case vtFLOAT: return vtFLOAT; case vtSTRING: return vtSTRING; case vtVECTOR2D: case vtRECTANGLE: case vtVECTOR: case vtBOX: case vtQUATERNION: case vtMATRIX: return vtFLOAT; default: return vtSTRING; } } /* ******************************************************************* * Function: GetParameterInfo() * * Description : GetParameterInfo returns an info about a virtools type. Example : Vector4D returns : result.horizontalItems = 4 ; result.verticalItems = 1 ; result.memberType = vtFLOAT result.superType = vtQUATERNION; * Parameters : CKContext* context, r : the virtools context. CKParameterType parameterType, r : the type to test. * Returns : ParameterInfo * ******************************************************************* */ vtTools::Structs::ParameterInfo vtTools::ParameterTools::GetParameterInfo(CKContext* context,CKParameterType parameterType) { assert(context); using namespace vtTools::Structs; using namespace vtTools::Enums; using namespace vtTools::ParameterTools; CKParameterManager *pm = static_cast<CKParameterManager *>(context->GetParameterManager()); ParameterInfo result; result.memberType = vtTools::ParameterTools::GetParameterMemberInfo(context,parameterType); result.superType = vtTools::ParameterTools::GetVirtoolsSuperType(context,pm->ParameterTypeToGuid(parameterType)); switch(result.superType) { case vtFLAGS: { CKFlagsStruct *flagStruct = pm->GetFlagsDescByType(parameterType); if (flagStruct) { result.horizontalItems = 1 ; result.verticalItems = flagStruct->GetNumFlags() ; } break; } case vtENUMERATION: { CKEnumStruct* enumStruct = pm->GetEnumDescByType(parameterType); if (enumStruct) { result.horizontalItems = 1 ; result.verticalItems = enumStruct->GetNumEnums(); break; } } case vtBOOL: case vtINTEGER: case vtFLOAT: case vtFile: case vtSTRING: result.horizontalItems = 1; result.verticalItems = 1; break; case vtVECTOR2D: result.horizontalItems = 2; result.verticalItems = 1; break; case vtRECTANGLE: result.horizontalItems = 2; result.verticalItems = 2; break; case vtVECTOR: result.horizontalItems = 3; result.verticalItems = 1; break; case vtBOX: result.horizontalItems = 3; result.verticalItems = 2; break; case vtQUATERNION: case vtCOLOUR: result.horizontalItems = 4; result.verticalItems = 1; break; case vtMATRIX: result.horizontalItems = 4; result.verticalItems = 4; break; default: { result.horizontalItems = 0; result.verticalItems = 0; break; } } return result; } /* ******************************************************************* * Function: GetWidgetType() * * Description : GetWidgetType returns the type of the GBLWidget which should used for a specific virtools super type. Example : vtBOOL = CheckBox vtENUMERATION = ComboBox * Parameters : SuperType superType, r : the given virtools super type * Returns : EWidgetType * ******************************************************************* */ vtTools::Enums::EVTWidgetType vtTools::ParameterTools::GetWidgetType(vtTools::Enums::SuperType superType) { using namespace vtTools::Enums; switch(superType) { case vtENUMERATION: return EVT_WIDGET_COMBO_BOX; case vtFLAGS: case vtBOOL: return EVT_WIDGET_CHECK_BUTTON; case vtINTEGER: case vtFLOAT: case vtSTRING: case vtVECTOR2D: case vtRECTANGLE: case vtVECTOR: case vtBOX: case vtQUATERNION: case vtMATRIX: return EVT_WIDGET_EDIT_TEXT; case vtCOLOUR: return EVT_WIDGET_COLOR_SELECTION; case vtFile: return EVT_WIDGET_FILE_SELECTION; default: return EVT_WIDGET_EDIT_TEXT; } } /* ******************************************************************* * Function:GetVirtoolsSuperType() * * Description : GetVirtoolsSuperType returns the base type of virtools parameter. This is very useful if want to determine whether a parameter can be used for network of database. * * Parameters : CKContext *ctx, r : the virtools context CKGUID guid, r : the guid of the parameter * * Returns : SuperType, * ******************************************************************* */ vtTools::Enums::SuperType vtTools::ParameterTools:: GetVirtoolsSuperType(CKContext *ctx, const CKGUID guid) { assert(ctx); using namespace vtTools::Enums; CKParameterTypeDesc *tdescr = ctx->GetParameterManager()->GetParameterTypeDescription(guid); CKParameterManager *pm = static_cast<CKParameterManager *>(ctx->GetParameterManager()); if ( (pm->GetEnumDescByType(pm->ParameterGuidToType(guid))) ) { return vtENUMERATION; } // parameter is a flag if ( (pm->GetFlagsDescByType(pm->ParameterGuidToType(guid))) ) { return vtFLAGS; } // is a bool : if( (ctx->GetParameterManager()->ParameterGuidToType(guid)) == ctx->GetParameterManager()->ParameterGuidToType(CKPGUID_BOOL)) return vtBOOL; /*// is a file : if( (ctx->GetParameterManager()->ParameterGuidToType(guid)) == ctx->GetParameterManager()->ParameterGuidToType(GBLCO_FILE_TYPE)) return vtFile;*/ // is a string : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_STRING)) return vtSTRING; // is a float : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_FLOAT)) return vtFLOAT; // is a integer : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_INT)) return vtINTEGER; // is a VxVector : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_VECTOR)) return vtVECTOR; // is a Vx2DVector : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_2DVECTOR)) return vtVECTOR2D; // is a VxColor : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_COLOR)) return vtCOLOUR; // is a VxMatrix : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_MATRIX)) return vtMATRIX; // is a VxQuaternion : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_QUATERNION)) return vtQUATERNION; // is a Rectangle : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_RECT)) return vtRECTANGLE; // is a Box : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_BOX)) return vtBOX; // is a CKObject : if(ctx->GetParameterManager()->IsDerivedFrom(guid,CKPGUID_OBJECT)) return vtOBJECT; return vtUNKNOWN; } /* ******************************************************************* * Function: TypeIsSerializable() * Description : Returns true if the given type can be stored as string. + It also checks custom virtools structures recursive. + hidden Structs or parameter types are skipped ! * * Parameters : CKContext *ctx, r : the virtools context CKParameterType type, r : the type * Returns : bool * ******************************************************************* */ bool vtTools::ParameterTools:: TypeIsSerializable( CKContext *ctx, CKParameterType type) { assert(ctx); CKParameterTypeDesc *tdescr = ctx->GetParameterManager()->GetParameterTypeDescription(type); bool result = false; if(tdescr) { using namespace vtTools::Enums; using namespace vtTools::ParameterTools; // return isNotHidden AND isNotCKBeObject AND isNotUnknown OR isValidStruct : // return ( ! (tdescr->dwFlags & CKPARAMETERTYPE_HIDDEN) && // internally type (GetVirtoolsSuperType(ctx,tdescr->Guid) != vtOBJECT ) && // objects not allowed ! (GetVirtoolsSuperType(ctx,tdescr->Guid) != vtUNKNOWN ) // also possible !! ) || ( ( ( (tdescr->dwFlags & CKPARAMETERTYPE_STRUCT) == 0x00000010 ) ? // parameter is a custom struct IsValidStruct(ctx,tdescr->Guid) : false //check the struct ) ); } return result; } /* ******************************************************************* * Function: IsValidStruct() * * Description : Like TypeIsSerializable, even checks a custom virtools structure, recursive. * * Parameters : CKContext *ctx,r : the virtools context CKGUID type,r : the type to check * Returns : bool * ******************************************************************* */ bool vtTools::ParameterTools:: IsValidStruct(CKContext *ctx,CKGUID type) { assert(ctx); CKParameterManager* pm = ctx->GetParameterManager(); CKStructStruct *data = pm->GetStructDescByType(pm->ParameterGuidToType(type)); bool result = true; if (data) for (int i=0;i<data->NbData;++i) if(vtTools::ParameterTools::TypeIsSerializable(ctx,pm->ParameterGuidToType(data->GetSubParamGuid(i)))) continue; else result = false; return result; } /* ******************************************************************* * Function: TypeCheckedParameterCopy() * * Description : Copies the source parameter to a destination parameter. On a type mismatch * it tries to copy as string. This also works for nested virtools structures. See SuperType for supported types. * * Parameters : CKParameter*dest,rw : the destination parameter CKParameter*src,r : the source parameter * Returns : bool = true if succesful. * todo:: return checked diff * ******************************************************************* */ int vtTools::ParameterTools:: TypeCheckedParameterCopy( CKParameter*dest, CKParameter*src) { using vtTools::ParameterTools::TypeIsSerializable; /* return ( (TypeIsOk AND CopyIsOk == CK_OK ) OR (TypeIsSerializable && CopyByStringIsOk== CK_OK ) ) */ return ( src && // useful //ok, compare the type : dest->GetGUID() == src->GetGUID() && //type match, store new value : ( dest->CopyValue(src) == CK_OK ) ) || /* canceled ? try a string : */ ( TypeIsSerializable(src->GetCKContext(),src->GetType()) && ( dest->SetStringValue( static_cast<CKSTRING>(src->GetReadDataPtr())) ==CK_OK ) );; } /* ******************************************************************* * Function: CompareStringRep() * * Description : This function compares the string representation of the CKParameters * * Parameters : CKParameter* valueA,r : the first parameter CKParameter* valueB,r : the second parameter * Returns : int (like strcmp) * ******************************************************************* */ int vtTools::ParameterTools:: CompareStringRep(CKParameter*valueA, CKParameter*valueB) { assert(valueA && valueB); VxScratch sbufferA(valueA->GetDataSize()); CKSTRING bufferA = (CKSTRING)sbufferA.Mem(); valueA->GetStringValue(bufferA); VxScratch sbufferB(valueB->GetDataSize()); CKSTRING bufferB = (CKSTRING)sbufferB.Mem(); valueB->GetStringValue(bufferB); return strcmp( bufferA,bufferB ); } /* ******************************************************************* * Function: GetParameterAsString() * * Description : Returns the string value of a CKParameter. * * Parameters : CKParameter*src ,r the given parameter * Returns : CKSTRING * ******************************************************************* */ CKSTRING vtTools::ParameterTools::GetParameterAsString( CKParameter*src) { assert(src); VxScratch scratch(src->GetDataSize()); CKSTRING out2 = (CKSTRING)scratch.Mem(); src->GetStringValue(out2); return out2; }<file_sep>#ifndef __VT_TNL_ALL_H_ #define __VT_TNL_ALL_H_ #include <tnl.h> #include <tnlTypes.h> #include <tnlVector.h> #include <xNetInterface.h> #include <vtConnection.h> #endif<file_sep> #ifndef N3DGRAPH_H #define N3DGRAPH_H #include "CKALL.h" #include <CK3dEntity.h> #include <CKGroup.h> #pragma warning (disable : 4786) #include <XList.h> #define N3DGRAPHSTART_IDENTIFIER 2000666 #define N3DGRAPH_VERSION1 1 #define N3DGRAPH_VERSION2 2 #define STATEBASICACTIVITY 1 #define STATEDYNAMICACTIVITY 2 #define LISTNONE 0 #define LISTOPEN 1 #define LISTCLOSE 2 struct N3DEdge; struct N3DState; struct N3DAStar { N3DAStar():g(0.0f),h(0.0f),f(0.0f),parent(NULL) {;} // cheapest cost of arriving to node n float g; // heuristic estimate of the cost to the goal float h; // cost of node n float f; // index of the parent state N3DState* parent; }; struct N3DState { N3DState():m_Edges(NULL),m_Data(0),m_Occupier(0),m_Flag(0){}; // list of transitions N3DEdge* m_Edges; // Pointer on Associated Entity CK_ID m_Data; // Pointer on Associated Entity CK_ID m_Occupier; // AStar structure N3DAStar m_AStar; // List flag : LISTOPEN, LISTCLOSE or LISTNONE DWORD m_Flag; // Node Position VxVector m_Position; }; struct N3DExtent { // Node ID CK_ID m_Node; // Node Extent CKRECT m_Rect; }; struct N3DEdge { N3DEdge():m_Successor(-1),m_Active(TRUE),m_Difficulty(0),m_Next(NULL) {}; // state successor int m_Successor; // activity int m_Active; // terrain difficulty float m_Distance; // terrain difficulty float m_Difficulty; // Next Edge N3DEdge* m_Next; }; struct N3DDisplayStructure { N3DDisplayStructure(CKContext* context):m_Node(0),m_EndNode(0) { m_Group = (CKGroup *)context->CreateObject(CKCID_GROUP,"Graph Path"); } ~N3DDisplayStructure() { for (void** ptr=m_NodeExtents.Begin();ptr!=m_NodeExtents.End();ptr++) delete (N3DExtent*)*ptr; CKDestroyObject(m_Group); } // Nodes extents XVoidArray m_NodeExtents; // group of nodes to go CKGroup* m_Group; // node selected CK_ID m_Node; // end node for the link selected CK_ID m_EndNode; }; class N3DGraph { public: // Constructor N3DGraph(CKContext* context); ~N3DGraph(); // Cleanification method void Clean(); void SetDifficult(CK3dEntity *ent, float diff); // Test Method int GraphEmpty() const; // Data Access Methods int GetStatesNumber() const; N3DState* GetState(int i); int GetEdgesNumber() const; CK3dEntity* GetSafeEntity(N3DState* s); // int GetWeight(const CK3dEntity& v1, const CK3dEntity& v2); // Find the State Index by the associated data int SeekPosition(CK_ID e) const; int SeekPosition(N3DState* e) const; // Get the successors of State i N3DEdge* GetSuccessorsList(int i); // Graph Modification // insertion N3DState* InsertState(CK3dEntity* e); N3DEdge* InsertEdge(CK3dEntity* s,CK3dEntity* e,float d); // Activity void ActivateEdge(CK3dEntity* s,CK3dEntity* e,BOOL a,BOOL dyn=TRUE); void ActivateState(CK3dEntity* s,BOOL a); void ResetActivity(); BOOL IsEdgeActive(CK3dEntity* s,CK3dEntity* e); // Occupation BOOL SetOccupier(CK3dEntity* s,CK3dEntity* o); CK3dEntity* GetOccupier(CK3dEntity* s); // deletion void DeleteState(CK_ID e); void DeleteEdge(CK3dEntity* s,CK3dEntity* e); void CreateFromChunk(CKStateChunk*); void SaveToChunk(CKStateChunk*); // Path finding CK3dEntity* FindPath(CK3dEntity* start,CK3dEntity* goal,CKGroup* path,BOOL basic=FALSE,BOOL occupation=FALSE); // Distance update void UpdateDistance(); // Author highlight display void StartDisplay() {if(m_Display) delete m_Display;m_Display = new N3DDisplayStructure(m_Context);} void StopDisplay() {delete m_Display;m_Display=NULL;} N3DDisplayStructure* GetDisplay() {return m_Display;} CKGroup* GetPath() {if(m_Display) return m_Display->m_Group;else return NULL;} XVoidArray* GetExtentsList() {if(m_Display) return &m_Display->m_NodeExtents;else return NULL;} private: // methods void TestAndReallocate(int i=1); // insertion in a queue void PushOnOpen(XList<N3DState*>& open,N3DState* n); // return en edge pointer, NULL if not found N3DEdge* EdgeSeek(CK_ID s,CK_ID e); // same thing with the indice of the start node // N3DEdge* EdgeSeek(int s,CK_ID e); // Create a State N3DEdge* CreateEdge(int e,float d,float dist); // Find the node Containing the Entity e N3DState* StateSeek(CK_ID e); // retreive the distance between 2 nodes float GetDistance(N3DState* n1,N3DState* n2); // members // list of vertices N3DState* m_States; // graph size int m_Size; // edge number; int m_EdgeNumber; // Graph allocated size int m_AllocatedSize; // Display structure (for selected items highlighting) N3DDisplayStructure* m_Display; CKContext* m_Context; }; extern char* Network3dName; void GraphRender(CKRenderContext* ctx,void *arg); #endif<file_sep>#ifndef __vtNetTypes_h_ #define __vtNetTypes_h_ #include <Prereqs.h> #include <vtNetStructs.h> #include <vtNetEnums.h> #include <stdlib.h> #include <map> #include <vector> /********************************************************************/ /************************************************************************/ /* Enumeration to identify an distributed objects creation state /* */ /* */ /* */ /************************************************************************/ #endif <file_sep>#include "CKAll.h" CKObjectDeclaration *FillBehaviorAddAttributesDecl(); CKERROR CreateAddAttributesProto(CKBehaviorPrototype **); int AddAttributes(const CKBehaviorContext& behcontext); CKERROR SetAttributeCallBack(const CKBehaviorContext& behcontext); CKObjectDeclaration *FillBehaviorAddAttributesDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Add Attribute by Substring"); od->SetCategory("Logics/Attribute"); od->SetType( CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x290f0795,0x16743e10)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateAddAttributesProto); od->SetCompatibleClassId(CKCID_BEOBJECT); return od; } CKERROR CreateAddAttributesProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Add Attribute by Substring"); if(!proto) return CKERR_OUTOFMEMORY; proto->DeclareInput("In"); proto->DeclareOutput("Out"); proto->DeclareInParameter("Attribute",CKPGUID_ATTRIBUTE); proto->DeclareInParameter("Key Substring", CKPGUID_STRING, "PM_"); proto->DeclareInParameter("Class", CKPGUID_CLASSID); proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); proto->SetFunction(AddAttributes); proto->SetBehaviorCallbackFct( SetAttributeCallBack ); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS)); *pproto = proto; return CK_OK; } int AddAttributes(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; char string[512]; beh->GetInputParameterValue(1,&string); int Attribute=-1; beh->GetInputParameterValue(0,&Attribute); CKLevel* level = ctx->GetCurrentLevel(); CK_CLASSID C_ID; beh->GetInputParameterValue(2,&C_ID); XObjectPointerArray myarray=level->ComputeObjectList(C_ID); for (CKObject** it = myarray.Begin(); it != myarray.End(); ++it) { CKObject *obj = *it; if (obj) { if (obj->GetName()) { if (strstr(obj->GetName(),string)) { CK3dEntity *ent = (CK3dEntity *)*it; ent->SetAttribute(Attribute); CKParameterOut* pout = ent->GetAttributeParameter(Attribute); if(pout) { CKParameter* real; CKParameterIn* tpin = (CKParameterIn*)beh->GetInputParameter(3); if(tpin && (real=tpin->GetRealSource())) pout->CopyValue(real); } } } } } return CKBR_OK; } CKERROR SetAttributeCallBack(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; switch( behcontext.CallbackMessage ){ case CKM_BEHAVIOREDITED: { CKAttributeManager* Manager = behcontext.AttributeManager; int Attribute=-1; beh->GetInputParameterValue(0,&Attribute); int ParamType = Manager->GetAttributeParameterType(Attribute); if(ParamType != -1) { // we test if there is a parameter attached beh->EnableInputParameter(2,TRUE); CKParameterIn* pin = beh->GetInputParameter(3); if (pin) { if (pin->GetType()!=ParamType){ pin->SetType( ParamType ); } } else beh->CreateInputParameter("Attribute Value",ParamType); } else beh->EnableInputParameter(3,FALSE); } } beh->ActivateOutput(0); return CKBR_OK; } <file_sep> /* *************************************************************** */ /* */ /* */ /* */ /* FTP4W.DLL (Version 3.0) */ /* */ /* */ /* By <NAME> (SNCF 30.12.98) */ /* Internet <EMAIL> */ /* Copyright SNCF 94-97 */ /* *************************************************************** */ #ifndef _FTP4W_API_ #include <winsock.h> #ifdef __cplusplus extern "C" { /* Assume C declarations for C++ */ #endif /* __cplusplus */ #define FTP_DATABUFFER 4096 /* a good value for X25/Ethernet/Token Ring */ /* ----------------------------------------------------------- */ /* ASCII or binary transfer */ #define TYPE_A 'A' #define TYPE_I 'I' #define TYPE_L8 'L' #define TYPE_DEFAULT 0 /* actions requested by user */ #define FTP4W_STORE_ON_SERVER 65 #define FTP4W_APPEND_ON_SERVER 87 #define FTP4W_GET_FROM_SERVER 223 /* Firewall Types */ #define FTP4W_FWSITE 100 #define FTP4W_FWPROXY 103 #define FTP4W_FWUSERWITHLOGON 106 #define FTP4W_FWUSERNOLOGON 109 /* ----------------------------------------------------------- */ /* Return codes of FTP functions */ /* ----------------------------------------------------------- */ /* success */ #define FTPERR_OK 0 /* succesful function */ /* OK but waits for further parameters */ #define FTPERR_ENTERPASSWORD 1 /* userid need a password */ #define FTPERR_ENTERACCOUNT 2 /* user/pass OK but account required */ #define FTPERR_ACCOUNTNEEDED 2 /* user/pass OK but account required */ #define FTPERR_RESTARTOK 3 /* Restart command successful */ #define FTPERR_ENDOFDATA 4 /* server has closed the data-conn */ #define FTPERR_CANCELBYUSER -1 /* Transfer aborted by user FtpAbort */ /* user's or programmer's Errors */ #define FTPERR_INVALIDPARAMETER 1000 /* Error in parameters */ #define FTPERR_SESSIONUSED 1001 /* User has already a FTP session */ #define FTPERR_NOTINITIALIZED 1002 /* FtpInit has not been call */ #define FTPERR_NOTCONNECTED 1003 /* User is not connected to a server */ #define FTPERR_CANTOPENFILE 1004 /* can not open specified file */ #define FTPERR_CANTOPENLOCALFILE FTPERR_CANTOPENFILE #define FTPERR_CANTWRITE 1005 /* can't write into file (disk full?)*/ #define FTPERR_NOACTIVESESSION 1006 /* FtpRelease without FtpInit */ #define FTPERR_STILLCONNECTED 1007 /* FtpRelease without any Close */ #define FTPERR_SERVERCANTEXECUTE 1008 /* file action not taken */ #define FTPERR_LOGINREFUSED 1009 /* Server rejects usrid/passwd */ #define FTPERR_NOREMOTEFILE 1010 /* server can not open file */ #define FTPERR_TRANSFERREFUSED 1011 /* Host refused the transfer */ #define FTPERR_WINSOCKNOTUSABLE 1012 /* A winsock.DLL ver 1.1 is required */ #define FTPERR_CANTCLOSE 1013 /* Close failed (cmd is in progress) */ #define FTPERR_FILELOCKED 1014 /* temporary error during FtpDelete */ #define FTPERR_FWLOGINREFUSED 1015 /* Firewallrejects usrid/passwd */ #define FTPERR_ASYNCMODE 1016 /* FtpMGet only in synchronous mode */ /* TCP errors */ #define FTPERR_UNKNOWNHOST 2001 /* can not resolve host adress */ #define FTPERR_NOREPLY 2002 /* host does not send an answer */ #define FTPERR_CANTCONNECT 2003 /* Error during connection */ #define FTPERR_CONNECTREJECTED 2004 /* host has no FTP server */ #define FTPERR_SENDREFUSED 2005 /* can't send data (network down) */ #define FTPERR_DATACONNECTION 2006 /* connection on data-port failed */ #define FTPERR_TIMEOUT 2007 /* timeout occured */ #define FTPERR_FWCANTCONNECT 2008 /* Error during connection with FW */ #define FTPERR_FWCONNECTREJECTED 2009 /* Firewall has no FTP server */ /* FTP server errors */ #define FTPERR_UNEXPECTEDANSWER 3001 /* answer was not expected */ #define FTPERR_CANNOTCHANGETYPE 3002 /* host rejects the TYPE command */ #define FTPERR_CMDNOTIMPLEMENTED 3003 /* host recognize but can't exec cmd*/ #define FTPERR_PWDBADFMT 3004 /* PWD cmd OK, but answer has no " */ #define FTPERR_PASVCMDNOTIMPL 3005 /* Server don't support passive mode*/ /* Resource errors */ #define FTPERR_CANTCREATEWINDOW 5002 /* Insufficent free resources */ #define FTPERR_INSMEMORY 5003 /* Insuffisent Heap memory */ #define FTPERR_CANTCREATESOCKET 5004 /* no more socket */ #define FTPERR_CANTBINDSOCKET 5005 /* bind is not succesful */ #define FTPERR_SYSTUNKNOWN 5006 /* host system not in the list */ /* **************************************************************** */ /* */ /* P R O T O T Y P E S */ /* */ /* **************************************************************** */ LPSTR PASCAL FAR FtpBufferPtr (void); LPSTR PASCAL FAR FtpErrorString (int Rc); int PASCAL FAR WEP (int nType); int PASCAL FAR Ftp4wVer (LPSTR szVerStr, int nStrSize); /* change default parameters */ int PASCAL FAR FtpSetVerboseMode (BOOL bVerboseMode, HWND hVerboseWnd, UINT wMsg); long PASCAL FAR FtpBytesTransferred (void); long PASCAL FAR FtpBytesToBeTransferred(void); void PASCAL FAR FtpSetDefaultTimeOut (int nTo_in_sec); void PASCAL FAR FtpSetDefaultPort(int nDefPort); void PASCAL FAR FtpSetAsynchronousMode(void); void PASCAL FAR FtpSetSynchronousMode(void); BOOL PASCAL FAR FtpIsAsynchronousMode(void); void PASCAL FAR FtpSetNewDelay(int x); void PASCAL FAR FtpSetNewSlices(int x,int y) ; void PASCAL FAR FtpSetPassiveMode (BOOL bPassive); void PASCAL FAR FtpLogTo (HFILE hLogFile); /* mispelled functions - only for backwards compatibilty */ long PASCAL FAR FtpBytesTransfered (void); long PASCAL FAR FtpBytesToBeTransfered(void); /* Init functions */ int PASCAL FAR FtpRelease (void); int PASCAL FAR FtpInit (HWND hParentWnd); int PASCAL FAR FtpMtInit ( HWND hParentWnd, DWORD (FAR *f)(void) ); int PASCAL FAR FtpFlush (void); /* Connection */ int PASCAL FAR FtpLogin (LPCSTR szHost, LPCSTR szUser, LPCSTR szPasswd, HWND hParentWnd, UINT wMsg); int PASCAL FAR FtpOpenConnection (LPCSTR szHost); int PASCAL FAR FtpCloseConnection (void); int PASCAL FAR FtpLocalClose (void); /* authentification */ int PASCAL FAR FtpSendUserName (LPCSTR szUserName); int PASCAL FAR FtpSendPasswd (LPCSTR szPasswd); int PASCAL FAR FtpSendAccount (LPCSTR szAccount); /* commands */ int PASCAL FAR FtpHelp (LPCSTR szArg, LPSTR szBuf, UINT uBufSize); int PASCAL FAR FtpDeleteFile (LPCSTR szRemoteFile); int PASCAL FAR FtpRenameFile (LPCSTR szFrom, LPCSTR szTo); int PASCAL FAR FtpQuote (LPCSTR szCmd, LPSTR szReplyBuf, UINT uBufSize); int PASCAL FAR FtpSyst (LPCSTR FAR *szSystemStr); int PASCAL FAR FtpSetType(char cType); int PASCAL FAR FtpCWD (LPCSTR szPath); int PASCAL FAR FtpCDUP (void); int PASCAL FAR FtpPWD (LPSTR szBuf, UINT uBufSize); int PASCAL FAR FtpMKD (LPCSTR szPath, LPSTR szFullDir, UINT uBufSize); int PASCAL FAR FtpRMD (LPCSTR szPath); /* file transfer */ int PASCAL FAR FtpAbort (void); int PASCAL FAR FtpSendFile (LPCSTR szLocal, LPCSTR szRemote, char cType, BOOL bNotify, HWND hParentWnd, UINT wMsg); int PASCAL FAR FtpAppendToRemoteFile (LPCSTR szLocal, LPCSTR szRemote,char cType, BOOL bNotify, HWND hParentWnd, UINT wMsg); int PASCAL FAR FtpRecvFile (LPCSTR szRemote, LPCSTR szLocal, char cType, BOOL bNotify, HWND hParentWnd, UINT wMsg); int PASCAL FAR FtpAppendToLocalFile (LPCSTR szLocal, LPCSTR szRemote,char cType, BOOL bNotify, HWND hParentWnd, UINT wMsg); DWORD PASCAL FAR FtpGetFileSize (void); int PASCAL FAR FtpMGet (LPCSTR szFilter, char cType, BOOL bNotify, BOOL (CALLBACK *f) (LPCSTR szRemFile, LPCSTR szLocalFile, int Rc) ); int PASCAL FAR FtpRestart (long lByteCount); int PASCAL FAR FtpRestartSendFile (HFILE hLocal, LPCSTR szRemote, char cType, BOOL bNotify, long lByteCount, HWND hParentWnd, UINT wMsg); int PASCAL FAR FtpRestartRecvFile (LPCSTR szRemote, HFILE hLocal, char cType, BOOL bNotify, long lByteCount, HWND hParentWnd, UINT wMsg); /* Directory */ int PASCAL FAR FtpDir (LPCSTR szDef, LPCSTR szLocalFile, BOOL bLongDir, HWND hParentWnd, UINT wMsg); /* Advanced function */ int PASCAL FAR FtpOpenDataConnection (LPCSTR szRemote,int nAction,char cType); int PASCAL FAR FtpRecvThroughDataConnection (LPSTR szBuf, unsigned int far *lpBufSize); int PASCAL FAR FtpSendThroughDataConnection(LPCSTR szBuf,unsigned int uBufSize); int PASCAL FAR FtpCloseDataConnection (void); /* Firewall function: Not Available */ int PASCAL FAR FtpFirewallLogin(LPCSTR szFWHost, LPCSTR szFWUser, LPCSTR szFWPass, LPCSTR szRemHost,LPCSTR szRemUser,LPCSTR szRemPass, int nFirewallType, HWND hParentWnd, UINT wMsg); /* hidden exported functions */ int PASCAL FAR IntFtpGetAnswerCode (); int PASCAL FAR FtpAutomate (int nIdx, LPCSTR szParam); /* _______________________________________________________________ */ #ifdef __cplusplus } /* End of extern "C" */ #endif /* ifdef __cplusplus */ #define _FTP4W_API_ loaded #endif /* ifndef FTP4W_API */ <file_sep>#ifndef __VT_GUIDS_H #define __VT_GUIDS_H #define PARAM_OP_TYPE_GET_ERROR_TEXT CKGUID(0xbc339b6,0x795302cc) #define VTE_NETWORK_ERROR CKGUID(0x6fca5bf6,0x77ed61e8) #endif<file_sep>DEV35DIR="c:/sdk/dev35" DEV40DIR="c:/sdk/dev4" DEV41DIR="c:/sdk/dev41R" DEV5DIR="c:/sdk/dev5GA" WEBPLAYERDIR="c:/Programme/Virtools/3D Life Player" <file_sep>#include "stdafx2.h" #include "vtAgeiaInterfaceEditor.h" #include "vtAgeiaInterfaceEditorDlg.h" #include "vtAgeiaInterfaceKeyboardShortcuts.h" void GlobalKSCallback(int commandID) { if (g_Editor) g_Editor->OnGlobalKeyboardShortcut(commandID); } int RegisterKeyboardShortcutCategory() { KeyboardShortcutManager* ksm = s_Plugininterface->GetKeyboardShortcutManager(); if (ksm) { //remove the comments delimiters to register global keyboard shortcut category //that will be detected by the application whatever the focused window is. int index = ksm->RegisterCategory(STR_CATEGORY,NULL,ACTIVE/*+GLOBAL*/,NULL,NULL/*GlobalKSCallback*/,GetCommandName); if (index>=0) return 1; } return 0; } int UnregisterKeyboardShortcutCategory() { KeyboardShortcutManager* ksm = s_Plugininterface->GetKeyboardShortcutManager(); if (ksm) { return ksm->UnregisterCategory(STR_CATEGORY); } return 0; } int RegisterKeyboardShortcuts() { KeyboardShortcutManager* ksm = s_Plugininterface->GetKeyboardShortcutManager(); KeyboardShortcutManager::KS ks; int index = ksm->GetCategoryIndex(STR_CATEGORY); //sample code to register Ctrl+shift+alt+A with commandid_a and B with commandid_b ks.key = 'A'; ks.flags = ks.KS_CONTROL|ks.KS_SHIFT|ks.KS_ALT; ks.commandID = CID_A; ksm->RegisterKS(index,ks); ks.key = 'B'; ks.flags = 0; ks.commandID = CID_B; ksm->RegisterKS(index,ks); //end sample code return 1; } const char* GetCommandName(int commandID) { //sample code switch(commandID) { case CID_A: return STR_A; case CID_B: return STR_B; } //sample code return NULL; } const char* GetCommandMenuName(int commandID,XString &name) { name=""; const char* cstr = GetCommandName(commandID); if (!cstr) return NULL; name = cstr; KeyboardShortcutManager* ksm = s_Plugininterface->GetKeyboardShortcutManager(); if (ksm) { ksm->GetKSName( STR_CATEGORY, commandID, name, FALSE/*do not clear string*/, TRUE/*add tab to string if string not empty*/); } return name.CStr(); } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "Stream.h" #include "cooking.h" pCloth::~pCloth() { if (!getCloth()) { return; } getWorld()->getScene()->releaseCloth(*mCloth); //getWorld()->getScene()-> releaseReceiveBuffers(); setEntityID(-1); } void pCloth::detachFromShape(CKBeObject *shape) { if (!shape) { return; } NxShape *aShape = getWorld()->getShapeByEntityID(shape->GetID()); if (aShape) { getCloth()->detachFromShape(aShape); } } void pCloth::dominateVertex(int vertexId, float expirationTime, float dominanceWeight) { getCloth()->dominateVertex(vertexId,expirationTime,dominanceWeight); } void pCloth::freeVertex(const int vertexId) { getCloth()->freeVertex(vertexId); } void pCloth::attachVertexToGlobalPosition(const int vertexId, const VxVector &pos) { getCloth()->attachVertexToGlobalPosition(vertexId,getFrom(pos)); } void pCloth::attachVertexToShape(int vertexId, CKBeObject *shape, const VxVector &localPos, int attachmentFlags) { if (!shape) { return; } if (!getWorld()) return; NxShape *aShape = getWorld()->getShapeByEntityID(shape->GetID()); if (aShape) { getCloth()->attachVertexToShape(vertexId,aShape,getFrom(localPos),attachmentFlags); } } void pCloth::attachToCore(CK3dEntity *body, float impulseThreshold, float penetrationDepth, float maxDeformationDistance) { pRigidBody *rbody = GetPMan()->getBody(body); if (!body) { return ; } if (rbody->getWorld() != getWorld() ) { return; } getCloth()->attachToCore(rbody->getActor(),impulseThreshold,penetrationDepth,maxDeformationDistance); } void pCloth::attachToCollidingShapes(int attachmentFlags) { mCloth->attachToCollidingShapes(attachmentFlags); } void pCloth::attachToShape(CKBeObject *shape, int attachmentFlags) { if (!shape) { return; } if (!getWorld()) return; NxShape *aShape = getWorld()->getShapeByEntityID(shape->GetID()); if (aShape) { getCloth()->attachToShape(aShape,attachmentFlags); } } void pCloth::setCollisionResponseCoefficient(float coefficient) { mCloth->setCollisionResponseCoefficient(coefficient); } void pCloth::addDirectedForceAtPos(const VxVector& position, const VxVector& force, float radius, ForceMode mode /* = FM_Force */) { mCloth->addDirectedForceAtPos(getFrom(position),getFrom(force),(NxForceMode)mode ); } void pCloth::addForceAtVertex(const VxVector& force, int vertexId, ForceMode mode /* = FM_Force */) { mCloth->addForceAtVertex(getFrom(force),vertexId,(NxForceMode)mode); } void pCloth::addForceAtPos(const VxVector& position, float magnitude, float radius, ForceMode mode /* = FM_Force */) { mCloth->addForceAtPos(getFrom(position),magnitude,radius,(NxForceMode)mode); } void pCloth::wakeUp(float wakeCounterValue /* = NX_SLEEP_INTERVAL */) { mCloth->wakeUp(wakeCounterValue); } void pCloth::putToSleep() { mCloth->putToSleep(); } void pCloth::setFlags(int flags) { mCloth->setFlags(flags); } void pCloth::setSleepLinearVelocity(float threshold) { mCloth->setSleepLinearVelocity(threshold); } void pCloth::setExternalAcceleration(VxVector acceleration) { mCloth->setExternalAcceleration(getFrom(acceleration)); } void pCloth::setWindAcceleration(VxVector acceleration) { mCloth->setWindAcceleration(getFrom(acceleration)); } void pCloth::setMinAdhereVelocity(float velocity) { mCloth->setMinAdhereVelocity(velocity); } void pCloth::setToFluidResponseCoefficient(float coefficient) { mCloth->setToFluidResponseCoefficient(coefficient); } void pCloth::setFromFluidResponseCoefficient(float coefficient) { mCloth->setFromFluidResponseCoefficient(coefficient); } void pCloth::setAttachmentResponseCoefficient(float coefficient) { mCloth->setAttachmentResponseCoefficient(coefficient); } void pCloth::setVelocity(const VxVector& velocity, int vertexId) { mCloth->setVelocity(getFrom(velocity),vertexId); } void pCloth::setValidBounds(const VxBbox& validBounds) { NxBounds3 box; box.set( getFrom(validBounds.Min), getFrom(validBounds.Max)); mCloth->setValidBounds(box); } void pCloth::setGroup(int collisionGroup) { mCloth->setGroup(collisionGroup); } void pCloth::setSolverIterations(int iterations) { mCloth->setSolverIterations(iterations); } void pCloth::setThickness(float thickness) { mCloth->setThickness(thickness); } void pCloth::setAttachmentTearFactor(float factor) { mCloth->setAttachmentTearFactor(factor); } void pCloth::setTearFactor(float factor) { mCloth->setTearFactor(factor); } void pCloth::setPressure(float pressure) { mCloth->setPressure(pressure); } void pCloth::setFriction(float friction) { mCloth->setFriction(friction); } void pCloth::setDampingCoefficient(float dampingCoefficient) { mCloth->setDampingCoefficient(dampingCoefficient); } void pCloth::setStretchingStiffness(float stiffness) { mCloth->setStretchingStiffness(stiffness); } void pCloth::setBendingStiffness(float stiffness) { mCloth->setBendingStiffness(stiffness); } void pCloth::updateVirtoolsMesh() { NxMeshData *data = getReceiveBuffers(); CK3dEntity *srcEntity =(CK3dEntity*) GetPMan()->GetContext()->GetObject(getEntityID()); if (!srcEntity) { return; } /* if (getCloth()->isSleeping()) { return; } */ CKMesh *mesh = srcEntity->GetCurrentMesh(); NxReal *vertices = (NxReal*)data->verticesPosBegin; VxVector pos; srcEntity->GetPosition(&pos); for (int i = 0 ; i< mesh->GetVertexCount() ; i++ ) { VxVector v; v.x = vertices[i * 3]; v.y = vertices[i * 3 + 1]; v.z = vertices[i * 3 + 2]; VxVector outIV; srcEntity->InverseTransform(&outIV,&v); mesh->SetVertexPosition(i,&outIV); } int t = 3; } bool pCloth::cookMesh(NxClothMeshDesc* desc) { // we cook the mesh on the fly through a memory stream // we could also use a file stream and pre-cook the mesh MemoryWriteBuffer wb; int dValid = desc->isValid(); bool status = InitCooking(); if (!status) { xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); return NULL; } bool success = CookClothMesh(*desc, wb); if (!success) return false; MemoryReadBuffer rb(wb.data); mClothMesh = GetPMan()->getPhysicsSDK()->createClothMesh(rb); CloseCooking(); return true; } bool pCloth::generateMeshDesc(pClothDesc cDesc,NxClothMeshDesc *desc, CKMesh*mesh) { if (!mesh) { return false; } int numVerts = mesh->GetVertexCount(); int numFaces = mesh->GetFaceCount(); // allocate flag buffer if(desc->vertexFlags == 0) desc->vertexFlags = malloc(sizeof(NxU32)*desc->numVertices); // create tear lines NxU32* flags = (NxU32*)desc->vertexFlags; NxReal *vertices = new float[3 * numVerts]; //NxVec3 *verts = new NxVec3[numVerts]; for (int i = 0 ; i< numVerts ; i++ ) { VxVector v; mesh->GetVertexPosition(i,&v); vertices[i * 3] = v.x; vertices[i * 3 + 1] =v.y; vertices[i * 3 + 2] = v.z; if (desc->flags & NX_CLOTH_MESH_TEARABLE) { DWORD vColor = mesh->GetVertexColor(i); DWORD cColor = RGBAFTOCOLOR(&cDesc.tearVertexColor); if (vColor == cColor ) { int op2 =0; flags[i] = NX_CLOTH_VERTEX_TEARABLE; int k = 0 ; k++; } } } NxU32 *indices2 = new NxU32[numFaces*3]; for(int j = 0 ; j < numFaces ; j++) { int findicies[3]; mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); indices2[ j *3 ] = findicies[0]; indices2[ j *3 + 1 ] = findicies[1]; indices2[ j *3 + 2 ] = findicies[2]; } desc->numVertices = numVerts; desc->pointStrideBytes = sizeof(NxReal)*3; desc->points = vertices; desc->numTriangles = numFaces; desc->triangles = indices2; desc->triangleStrideBytes = sizeof(NxU32)*3; desc->flags = 0; desc->vertexMasses = 0; desc->vertexFlags = 0; desc->flags = NX_CLOTH_MESH_WELD_VERTICES; desc->weldingDistance = 0.0001f; return true; } void pCloth::allocateClothReceiveBuffers(int numVertices, int numTriangles) { // here we setup the buffers through which the SDK returns the dynamic cloth data // we reserve more memory for vertices than the initial mesh takes // because tearing creates new vertices // the SDK only tears cloth as long as there is room in these buffers mReceiveBuffers = new NxMeshData(); NxU32 maxVertices = 3 * numVertices; mReceiveBuffers->verticesPosBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices); mReceiveBuffers->verticesNormalBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices); mReceiveBuffers->verticesPosByteStride = sizeof(NxVec3); mReceiveBuffers->verticesNormalByteStride = sizeof(NxVec3); mReceiveBuffers->maxVertices = maxVertices; mReceiveBuffers->numVerticesPtr = (NxU32*)malloc(sizeof(NxU32)); // the number of triangles is constant, even if the cloth is torn NxU32 maxIndices = 3*numTriangles; mReceiveBuffers->indicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxIndices); mReceiveBuffers->indicesByteStride = sizeof(NxU32); mReceiveBuffers->maxIndices = maxIndices; mReceiveBuffers->numIndicesPtr = (NxU32*)malloc(sizeof(NxU32)); // the parent index information would be needed if we used textured cloth NxU32 maxParentIndices = maxVertices; mReceiveBuffers->parentIndicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxParentIndices); mReceiveBuffers->parentIndicesByteStride = sizeof(NxU32); mReceiveBuffers->maxParentIndices = maxParentIndices; mReceiveBuffers->numParentIndicesPtr = (NxU32*)malloc(sizeof(NxU32)); // init the buffers in case we want to draw the mesh // before the SDK as filled in the correct values *mReceiveBuffers->numVerticesPtr = 0; *mReceiveBuffers->numIndicesPtr = 0; } void pCloth::releaseReceiveBuffers() { // Parent Indices is always allocated /* free (mReceiveBuffers.parentIndicesBegin); mReceiveBuffers.setToDefault();*/ } void pCloth::releaseMeshDescBuffers(const NxClothMeshDesc* desc) { NxVec3* p = (NxVec3*)desc->points; NxU32* t = (NxU32*)desc->triangles; NxReal* m = (NxReal*)desc->vertexMasses; NxU32* f = (NxU32*)desc->vertexFlags; free(p); free(t); free(m); free(f); } pCloth::pCloth() { } /*----------------------------------------------------------------------------*/ pClothDesc::pClothDesc() { //setToDefault(); } /*----------------------------------------------------------------------------*/ void pClothDesc::setToDefault() { thickness = 0.01f; density = 1.0f; bendingStiffness = 1.0f; stretchingStiffness = 1.0f; dampingCoefficient = 0.5f; friction = 0.5f; pressure = 1.0f; tearFactor = 1.5f; attachmentTearFactor = 1.5f; attachmentResponseCoefficient = 0.2f; attachmentTearFactor = 1.5f; collisionResponseCoefficient = 0.2f; toFluidResponseCoefficient = 1.0f; fromFluidResponseCoefficient = 1.0f; minAdhereVelocity = 1.0f; flags = PCF_Gravity|PCF_CollisionTwoway; solverIterations = 5; wakeUpCounter = NX_SLEEP_INTERVAL; sleepLinearVelocity = -1.0f; collisionGroup = 0; forceFieldMaterial = 0; externalAcceleration =VxVector(0.0f, 0.0f, 0.0f); windAcceleration=VxVector(0.0f, 0.0f, 0.0f); groupsMask.bits0 = 0; groupsMask.bits1 = 0; groupsMask.bits2 = 0; groupsMask.bits3 = 0; validBounds = VxBbox(); relativeGridSpacing = 0.25f; tearVertexColor.Set(1.0f); } /*----------------------------------------------------------------------------*/ bool pClothDesc::isValid() const { // if (flags & NX_CLF_SELFCOLLISION) return false; // not supported at the moment if(thickness < 0.0f) return false; if(density <= 0.0f) return false; if(bendingStiffness < 0.0f || bendingStiffness > 1.0f) return false; if(stretchingStiffness <= 0.0f || stretchingStiffness > 1.0f) return false; if(pressure < 0.0f) return false; if(tearFactor <= 1.0f) return false; if(attachmentTearFactor <= 1.0f) return false; if(solverIterations < 1) return false; if(friction < 0.0f || friction > 1.0f) return false; if(dampingCoefficient < 0.0f || dampingCoefficient > 1.0f) return false; if(collisionResponseCoefficient < 0.0f) return false; if(wakeUpCounter < 0.0f) return false; if(attachmentResponseCoefficient < 0.0f || attachmentResponseCoefficient > 1.0f) return false; if(toFluidResponseCoefficient < 0.0f) return false; if(fromFluidResponseCoefficient < 0.0f) return false; if(minAdhereVelocity < 0.0f) return false; if(relativeGridSpacing < 0.01f) return false; if(collisionGroup >= 32) return false; // We only support 32 different collision groups return true; } <file_sep>#ifndef __X_PLATFORM__ #define __X_PLATFORM__ enum E_ASSERTION_FAILURE_SEVERITY { AFS__MIN, AFS_ASSERT=AFS__MIN, AFS_CHECK, AFS__MAX, }; //---------------------------------------------------------------- // // host identifier // #define xTARGET_OS_GENUNIX 1 #define xTARGET_OS_WINDOWS 2 #define xTARGET_OS_QNX 3 #define xTARGET_OS_MAC 4 //---------------------------------------------------------------- // // base types // #if !defined(__LINE__) extern const unsigned int __LINE__; #endif #if !defined(__FILE__) extern const char *const __FILE__; #endif //---------------------------------------------------------------- // // Determine platform // #if defined(_WINDOWS) || defined(_WIN32) #define xTARGET_OS xTARGET_OS_WINDOWS #elif defined(__QNX__) #define xTARGET_OS xTARGET_OS_QNX #elif defined(__APPLE__) #define xTARGET_OS xTARGET_OS_MAC #endif //---------------------------------------------------------------- // // determine call convention // #if xTARGET_OS == xTARGET_OS_WINDOWS #define xCONVENTION_METHOD #define xCONVENTION_API __stdcall #define xCONVENTION_CALLBACK __stdcall #else // #if xTARGET_OS != xTARGET_OS_WINDOWS #define xCONVENTION_METHOD #define xCONVENTION_API #define xCONVENTION_CALLBACK #endif //---------------------------------------------------------------- // // cpu bandwidth // #if !defined(xTARGET_BITS) #if defined(_LP64) || defined(_WIN64) #define xTARGET_BITS xTARGET_BITS_64 #else #define xTARGET_BITS xTARGET_BITS_32 #endif #else // #if defined(xTARGET_BITS) #if xTARGET_BITS <= 0 || xTARGET_BITS >= xTARGET_BITS__MAX #error Please define a valid value for xTARGET_BITS #endif #endif //---------------------------------------------------------------- // // determine compiler // #define xCOMPILER__OTHER 1 #define xCOMPILER_GCC 2 #define xCOMPILER_MSVC 3 #define xCOMPILER__MAX 4 #define xCOMPILER_VERSION__OTHER 1 #define xCOMPILER_VERSION_MSVC1998 2 #define xCOMPILER_VERSION_GCCLT4 3 #define xCOMPILER_VERSION__MAX 4 ////////////////////////////////////////////////////////////////////////// #if !defined(xCOMPILER) #if defined(__GNUC__) #define xCOMPILER xCOMPILER_GCC #if __GNUC__ < 4 #define xCOMPILER_VERSION xCOMPILER_VERSION_GCCLT4 #endif #elif defined(_MSC_VER) #define xCOMPILER xCOMPILER_MSVC #if _MSC_VER <= 1200 #define xCOMPILER_VERSION xCOMPILER_VERSION_MSVC1998 #endif #else #define xCOMPILER xCOMPILER__OTHER #endif #else #if xCOMPILER <= 0 || xCOMPILER >= xCOMPILER__MAX #error Please define a valid value for xCOMPILER #endif #endif #if !defined(xCOMPILER_VERSION) #define xCOMPILER_VERSION xCOMPILER_VERSION__OTHER #endif #if xCOMPILER_VERSION <= 0 || xCOMPILER_VERSION >= xCOMPILER_VERSION__MAX #error Please define a valid value for xCOMPILER_VERSION #endif //---------------------------------------------------------------- // // inline , always inline // #if !defined(_xINLINES_DEFINED) #define _xINLINES_DEFINED #if xCOMPILER == xCOMPILER_GCC #define xALWAYSINLINE_PRE__DEFINITION inline #define xALWAYSINLINE_IN__DEFINITION __attribute__((always_inline)) #elif xCOMPILER == xCOMPILER_MSVC #define xALWAYSINLINE_PRE__DEFINITION __forceinline #define xALWAYSINLINE_IN__DEFINITION #else #define xALWAYSINLINE_PRE__DEFINITION inline #define xALWAYSINLINE_IN__DEFINITION #endif #if defined(_DEBUG) #define xALWAYSINLINE_PRE inline #define xALWAYSINLINE_IN #define xINLINE inline #else #define xALWAYSINLINE_PRE xALWAYSINLINE_PRE__DEFINITION #define xALWAYSINLINE_IN xALWAYSINLINE_IN__DEFINITION #define xINLINE inline #endif #endif // #if !defined(_xINLINES_DEFINED) #endif<file_sep>/* * Tcp4u v 3.31 Last Revision 06/06/1997 3.10 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: http4u.c * Purpose: manage http 1.0 protocol * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" /******************************* * Http4u miscellaneous define *******************************/ #ifdef UNIX # define trace 1 #else # define trace 0 #endif /******************************* * Http4u global variables *******************************/ struct S_http4u_errors { enum HTTP4_RETURN_CODE eErr; LPCSTR sErr; } tHttp4uErrors[] = { {HTTP4U_BAD_URL, "Url does not conform to Http protocol.", }, {HTTP4U_TCP_CONNECT, "can't reach the http server.", }, {HTTP4U_HOST_UNKNOWN, "can not resolve host address", }, {HTTP4U_TCP_FAILED, "call to Tcp4u library failed.", }, {HTTP4U_FILE_ERROR, "file stream error.", }, {HTTP4U_INSMEMORY, "insuffisant memory.", }, {HTTP4U_BAD_PARAM, "bad parameter in the function call.", }, {HTTP4U_OVERFLOW, "user buffer so little .", }, {HTTP4U_CANCELLED, "tranfser aborted.", }, {HTTP4U_NO_CONTENT, "data is empty.", }, {HTTP4U_MOVED, "request moved to other server.", }, {HTTP4U_BAD_REQUEST, "bad request received by the server.", }, {HTTP4U_FORBIDDEN, "request forbidden.", }, {HTTP4U_NOT_FOUND, "destination file not found.", }, {HTTP4U_PROTOCOL_ERROR, "protocol error.", }, {HTTP4U_UNDEFINED, "miscellaneous error.", }, {HTTP4U_TIMEOUT, "timeout in TCP dialog.", }, {HTTP4U_SUCCESS, "Successful call." }, }; /*###################################################################### *## *## NAME: Http4uErrorString *## *## PURPOSE: Writes a message explaining a function error *## *####################################################################*/ LPCSTR API4U Http4uErrorString( int msg_code /* le code d'erreur de Http4U */ ) { int Idx; LPCSTR p; Tcp4uLog (LOG4U_HIPROC, "Http4uErrorString"); for ( Idx=0 ; Idx<SizeOfTab(tHttp4uErrors) && tHttp4uErrors[Idx].eErr!=msg_code; Idx++ ); p = Idx>= SizeOfTab(tHttp4uErrors) ? (LPSTR) "Not an Http4u return code" : tHttp4uErrors[Idx].sErr; Tcp4uLog (LOG4U_HIEXIT, "Http4uErrorString"); return p; } /* END Http4uErrorString */ <file_sep>///////////////////////////////////////////////////// ///////////////////////////////////////////////////// // // Mouse Camera Orbit // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// #include "CKAll.h" #include "GeneralCameraOrbit.h" #define CKPGUID_MOUSEBUTTON CKDEFINEGUID(0x1ff24d5a,0x122f2c1f) CKObjectDeclaration *FillBehaviorMouseCameraOrbitDecl(); CKERROR CreateMouseCameraOrbitProto(CKBehaviorPrototype **pproto); int MouseCameraOrbit(const CKBehaviorContext& behcontext); void ProcessMouseInputs(VxVector* RotationAngles, CKBehavior* beh, CKInputManager *input, float delta, CKBOOL &Returns, CKBOOL &stopping); CKERROR MouseCameraOrbitCallback(const CKBehaviorContext& context); CKObjectDeclaration *FillBehaviorMouseCameraOrbitDecl() { CKObjectDeclaration *od = CreateCKObjectDeclaration("Mouse Camera Orbit"); od->SetDescription("Makes a Camera orbit round a 3D Entity using Mouse."); /* rem: <SPAN CLASS=in>On: </SPAN>activates the process.<BR> <SPAN CLASS=in>Off: </SPAN>deactivates the process.<BR> <BR> <SPAN CLASS=out>Exit On: </SPAN>is activated if the building block is activated.<BR> <SPAN CLASS=out>Exit Off: </SPAN>is activated if the building block is deactivated.<BR> <BR> <SPAN CLASS=pin>Target Position: </SPAN>Position we are turning around.<BR> <SPAN CLASS=pin>Target Referential: </SPAN>Referential where the position is defined.<BR> <SPAN CLASS=pin>Move Speed: </SPAN>Speed in angle per second used when the user moves the camera.<BR> <SPAN CLASS=pin>Return Speed: </SPAN>Speed in angle per second used when the camera returns.<BR> <SPAN CLASS=pin>Min Horizontal: </SPAN>Minimal angle allowed on the horizontal rotation. Must have a negative value.<BR> <SPAN CLASS=pin>Max Horizontal:</SPAN>Maximal angle allowed on the horizontal rotation. Must have a positive value.<BR> <SPAN CLASS=pin>Min Vertical: </SPAN>Minimal angle allowed on the vertical rotation. Must have a negative value.<BR> <SPAN CLASS=pin>Max Vertical: </SPAN>Maximal angle allowed on the vertical rotation. Must have a positive value.<BR> <SPAN CLASS=pin>Zoom Speed: </SPAN>Speed of the zoom in distance per second.<BR> <SPAN CLASS=pin>Zoom Min: </SPAN>Minimum zoom value allowed. Must have a negative value.<BR> <SPAN CLASS=pin>Zoom Max: </SPAN>Maximum zoom value allowed. Must have a positive value.<BR> <BR> The following keys are used by default to move the Camera around its target:<BR> <BR> <FONT COLOR=#FFFFFF>Page Up: </FONT>Zoom in.<BR> <FONT COLOR=#FFFFFF>Page Down: </FONT>Zoom out.<BR> <FONT COLOR=#FFFFFF>Up and Down Arrows: </FONT>Rotate vertically.<BR> <FONT COLOR=#FFFFFF>Left and Right Arrows: </FONT>Rotate horizontally.<BR> The arrow keys are the inverted T arrow keys and not the ones of the numeric keypad.<BR> <BR> <SPAN CLASS=setting>Returns: </SPAN>Does the camera systematically returns to its original position.<BR> <SPAN CLASS=setting>Key Rotate Left: </SPAN>Key used to rotate left.<BR> <SPAN CLASS=setting>Key Rotate Right: </SPAN>Key used to rotate right.<BR> <SPAN CLASS=setting>Key Rotate Up: </SPAN>Key used to rotate up.<BR> <SPAN CLASS=setting>Key Rotate Down: </SPAN>Key used to rotate down.<BR> <SPAN CLASS=setting>Key Zoom in: </SPAN>Key used to zoom in.<BR> <SPAN CLASS=setting>Key Zoom out: </SPAN>Key used to zoom in.<BR> <BR> */ od->SetCategory("Cameras/Movement"); od->SetType(CKDLL_BEHAVIORPROTOTYPE); od->SetGuid(CKGUID(0x2356342f,0x9542674f)); od->SetAuthorGuid(VIRTOOLS_GUID); od->SetAuthorName("Virtools"); od->SetVersion(0x00010000); od->SetCreationFunction(CreateMouseCameraOrbitProto); od->SetCompatibleClassId(CKCID_3DENTITY); od->NeedManager(INPUT_MANAGER_GUID); return od; } ////////////////////////////////////////////////////////////////////////////// // // Prototype creation // ////////////////////////////////////////////////////////////////////////////// CKERROR CreateMouseCameraOrbitProto(CKBehaviorPrototype **pproto) { CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Mouse Camera Orbit"); if(!proto) return CKERR_OUTOFMEMORY; // General Description CKERROR error = FillGeneralCameraOrbitProto(proto); if (error != CK_OK) return (error); // Additional Input and Output proto->DeclareInput("Resume"); proto->DeclareOutput("Exit Resume"); proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS) (CKBEHAVIOR_TARGETABLE|CKBEHAVIOR_INTERNALLYCREATEDINPUTS|CKBEHAVIOR_INTERNALLYCREATEDOUTPUTS)); // Set the execution functions proto->SetFunction(MouseCameraOrbit); proto->SetBehaviorCallbackFct(MouseCameraOrbitCallback,CKCB_BEHAVIORSETTINGSEDITED|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORCREATE); // return OK *pproto = proto; return CK_OK; } ////////////////////////////////////////////////////////////////////////////// // // Main Function // ////////////////////////////////////////////////////////////////////////////// int MouseCameraOrbit(const CKBehaviorContext& behcontext) { return ( GeneralCameraOrbit(behcontext,ProcessMouseInputs) ); } ////////////////////////////////////////////////////////////////////////////// // // Function that process the inputs // ////////////////////////////////////////////////////////////////////////////// void ProcessMouseInputs(VxVector* RotationAngles, CKBehavior* beh, CKInputManager *input, float delta, CKBOOL &Returns, CKBOOL &stopping) { // Is the move limited ? CKBOOL Limited = TRUE; beh->GetLocalParameterValue(LOCAL_LIMITS,&Limited); // Gets the mouse displacement informations VxVector mouseDisplacement; input->GetMouseRelativePosition(mouseDisplacement); //////////////////// // Resume Input //////////////////// if ( Returns && beh->IsInputActive(2) ) { // Input / Output Status beh->ActivateInput(2, FALSE); beh->ActivateOutput(2); // We're not stopping anymore stopping = FALSE; beh->SetLocalParameterValue(LOCAL_STOPPING,&stopping); } //////////////////// // Position Update //////////////////// // If the users is moving the camera if ( !stopping ) { float SpeedAngle = 0.87f; beh->GetInputParameterValue(IN_SPEED_MOVE,&SpeedAngle); SpeedAngle *= delta / 1000; if (Limited) { float MinH = -PI/2; beh->GetInputParameterValue(IN_MIN_H, &MinH); float MaxH = PI/2; beh->GetInputParameterValue(IN_MAX_H, &MaxH); float MinV = -PI/2; beh->GetInputParameterValue(IN_MIN_V, &MinV); float MaxV = PI/2; beh->GetInputParameterValue(IN_MAX_V, &MaxV); RotationAngles->x -= mouseDisplacement.x * SpeedAngle; RotationAngles->x = XMin(RotationAngles->x, MaxH); RotationAngles->x = XMax(RotationAngles->x, MinH); RotationAngles->y -= mouseDisplacement.y * SpeedAngle; RotationAngles->y = XMin(RotationAngles->y, MaxV); RotationAngles->y = XMax(RotationAngles->y, MinV); } else { RotationAngles->x -= mouseDisplacement.x * SpeedAngle; RotationAngles->y -= mouseDisplacement.y * SpeedAngle; } } else if (Returns && ((RotationAngles->x != 0) || (RotationAngles->y != 0))) { float ReturnSpeedAngle = 1.75f; beh->GetInputParameterValue(IN_SPEED_RETURN, &ReturnSpeedAngle); ReturnSpeedAngle *= delta / 1000; if( RotationAngles->x < 0 ) RotationAngles->x += XMin(ReturnSpeedAngle, -RotationAngles->x); if( RotationAngles->x > 0 ) RotationAngles->x -= XMin(ReturnSpeedAngle, RotationAngles->x); if( RotationAngles->y < 0 ) RotationAngles->y += XMin(ReturnSpeedAngle, -RotationAngles->y); if( RotationAngles->y > 0 ) RotationAngles->y -= XMin(ReturnSpeedAngle, RotationAngles->y); } //////////////// // Zoom Update //////////////// if ( (mouseDisplacement.z != 0) && !stopping ) { float ZoomSpeed = 40.0f; beh->GetInputParameterValue(IN_SPEED_ZOOM,&ZoomSpeed); ZoomSpeed *= delta / 10000; if (Limited) { float MinZoom = -40.0f; beh->GetInputParameterValue(IN_MIN_ZOOM, &MinZoom); float MaxZoom = 10.0f; beh->GetInputParameterValue(IN_MAX_ZOOM, &MaxZoom); RotationAngles->z -= mouseDisplacement.z * ZoomSpeed; RotationAngles->z = XMin(RotationAngles->z, -MinZoom); RotationAngles->z = XMax(RotationAngles->z, -MaxZoom); } else RotationAngles->z -= mouseDisplacement.z * ZoomSpeed; } } ////////////////////////////////////////////////////////////////////////////// // // Mouse Specific Callback Function // ////////////////////////////////////////////////////////////////////////////// CKERROR MouseCameraOrbitCallback(const CKBehaviorContext& context) { CKBehavior* beh = context.Behavior; switch(context.CallbackMessage) { case CKM_BEHAVIORCREATE: case CKM_BEHAVIORLOAD: { VxVector InitialAngles(INF,INF,INF); beh->SetLocalParameterValue(LOCAL_INIT,&InitialAngles); } break; case CKM_BEHAVIORSETTINGSEDITED: { // Update the needed input for "returns" CKBOOL Returns = TRUE; beh->GetLocalParameterValue(LOCAL_RETURN,&Returns); beh->EnableInputParameter(IN_SPEED_RETURN, Returns); if ( Returns && (beh->GetInputCount() == 2) ) { beh->AddInput("Resume"); beh->AddOutput("Exit Resume"); } else if (!Returns && (beh->GetOutputCount() == 3) ) { beh->DeleteInput(2); beh->DeleteOutput(2); } // Updates the needed inputs for limiting the move CKBOOL Limited = TRUE; beh->GetLocalParameterValue(LOCAL_LIMITS,&Limited); beh->EnableInputParameter(IN_MIN_H,Limited); beh->EnableInputParameter(IN_MAX_H,Limited); beh->EnableInputParameter(IN_MIN_V,Limited); beh->EnableInputParameter(IN_MAX_V,Limited); beh->EnableInputParameter(IN_MIN_ZOOM,Limited); beh->EnableInputParameter(IN_MAX_ZOOM,Limited); } break; default: break; } return CKBR_OK; } <file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "VSLManagerSDK.h" //#include "pVehicle.h" PhysicManager *ourMan = NULL; CKGUID GetPhysicManagerGUID() { return GUID_MODULE_MANAGER;} void __newpVehicleDescr(BYTE *iAdd) { new (iAdd)pVehicleDesc(); } void __newpVehicleMotorDesc(BYTE *iAdd) { new (iAdd)pVehicleMotorDesc(); } void __newpVehicleGearDesc(BYTE *iAdd) { new(iAdd)pVehicleGearDesc(); } ////////////////////////////////////////////////////////////////////////// #define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) void PhysicManager::_RegisterVSL() { ourMan = GetPMan(); int z = D6DT_Position; int y = D6DT_Velocity; STARTVSLBIND(m_Context) DECLAREPOINTERTYPE(pVehicleMotorDesc) DECLAREMEMBER(pVehicleMotorDesc,float,maxRpmToGearUp) DECLAREMEMBER(pVehicleMotorDesc,float,minRpmToGearDown) DECLAREMEMBER(pVehicleMotorDesc,float,maxRpm) DECLAREMEMBER(pVehicleMotorDesc,float,minRpm) DECLAREMETHOD_0(pVehicleMotorDesc,void,setToCorvette) DECLAREPOINTERTYPE(pVehicleGearDesc) DECLAREMEMBER(pVehicleGearDesc,int,nbForwardGears) DECLAREMETHOD_0(pVehicleGearDesc,void,setToDefault) DECLAREMETHOD_0(pVehicleGearDesc,void,setToCorvette) DECLAREMETHOD_0(pVehicleGearDesc,bool,isValid) DECLAREOBJECTTYPE(pWheelDescr) DECLARECTOR_0(__newpWheelDescr) DECLAREOBJECTTYPE(pVehicleDesc) DECLARECTOR_0(__newpVehicleDescr) DECLAREMEMBER(pVehicleDesc,float,digitalSteeringDelta) DECLAREMEMBER(pVehicleDesc,VxVector,steeringSteerPoint) DECLAREMEMBER(pVehicleDesc,VxVector,steeringTurnPoint) DECLAREMEMBER(pVehicleDesc,float,steeringMaxAngle) DECLAREMEMBER(pVehicleDesc,float,transmissionEfficiency) DECLAREMEMBER(pVehicleDesc,float,differentialRatio) DECLAREMEMBER(pVehicleDesc,float,maxVelocity) DECLAREMEMBER(pVehicleDesc,float,motorForce) DECLAREMETHOD_0(pVehicleDesc,pVehicleGearDesc*,getGearDescription) DECLAREMETHOD_0(pVehicleDesc,pVehicleMotorDesc*,getMotorDescr) DECLAREMETHOD_0(pVehicleDesc,void,setToDefault) DECLAREPOINTERTYPE(pWheel) DECLAREPOINTERTYPE(pVehicle) DECLAREPOINTERTYPE(pVehicleMotor) DECLAREPOINTERTYPE(pVehicleGears) DECLAREPOINTERTYPE(pWheel1) DECLAREPOINTERTYPE(pWheel2) DECLAREINHERITANCESIMPLE("pWheel","pWheel1") DECLAREINHERITANCESIMPLE("pWheel","pWheel2") ////////////////////////////////////////////////////////////////////////// // // Vehicle : // DECLAREMETHOD_1(pVehicle,void,updateVehicle,float) DECLAREMETHOD_5(pVehicle,void,setControlState,float,bool,float,bool,bool) DECLAREMETHOD_1(pVehicle,pWheel*,getWheel,CK3dEntity*) DECLAREMETHOD_0(pVehicle,pVehicleMotor*,getMotor) DECLAREMETHOD_0(pVehicle,pVehicleGears*,getGears) DECLAREMETHOD_0(pVehicle,void,gearUp) DECLAREMETHOD_0(pVehicle,void,gearDown) DECLAREMETHOD_0(pVehicleGears,int,getGear) ////////////////////////////////////////////////////////////////////////// //motor : DECLAREMETHOD_0(pVehicleMotor,float,getRpm) DECLAREMETHOD_0(pVehicleMotor,float,getTorque) DECLAREMETHOD_0(pWheel,pWheel1*,castWheel1) DECLAREMETHOD_0(pWheel,pWheel2*,castWheel2) DECLAREMETHOD_0(pWheel,float,getWheelRollAngle) DECLAREMETHOD_0(pWheel2,float,getRpm) DECLAREMETHOD_0(pWheel2,float,getAxleSpeed) DECLAREMETHOD_0(pWheel2,float,getSuspensionTravel) DECLAREMETHOD_0(pWheel2,VxVector,getGroundContactPos) DECLAREMETHOD_2(pFactory,pVehicle*,createVehicle,CK3dEntity*,pVehicleDesc) ////////////////////////////////////////////////////////////////////////// // // MANAGER // DECLAREFUN_C_0(CKGUID, GetPhysicManagerGUID) DECLAREOBJECTTYPE(PhysicManager) DECLARESTATIC_1(PhysicManager,PhysicManager*,Cast,CKBaseManager* iM) DECLAREFUN_C_0(PhysicManager*, GetPhysicManager) DECLAREMETHOD_0(PhysicManager,pWorld*,getDefaultWorld) DECLAREMETHOD_1(PhysicManager,pRigidBody*,getBody,CK3dEntity*) DECLAREMETHOD_1(PhysicManager,pWorld*,getWorldByBody,CK3dEntity*) DECLAREMETHOD_1(PhysicManager,pWorld*,getWorld,CK_ID) DECLAREMETHOD_3_WITH_DEF_VALS(PhysicManager,pJoint*,getJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NULL,JType,JT_Any) // DECLAREMETHOD_0(PhysicManager,void,makeDongleTest) ////////////////////////////////////////////////////////////////////////// // // World // DECLAREMETHOD_1(pWorld,pRigidBody*,getBody,CK3dEntity*) DECLAREMETHOD_1(pWorld,pVehicle*,getVehicle,CK3dEntity*) DECLAREMETHOD_3(pWorld,pJoint*,getJoint,CK3dEntity*,CK3dEntity*,JType) DECLAREMETHOD_3(pWorld,void,setFilterOps,pFilterOp,pFilterOp,pFilterOp) DECLAREMETHOD_1(pWorld,void,setFilterBool,bool) DECLAREMETHOD_1(pWorld,void,setFilterConstant0,const pGroupsMask&) DECLAREMETHOD_1(pWorld,void,setFilterConstant1,const pGroupsMask&) // DECLAREMETHOD_5_WITH_DEF_VALS(pWorld,bool,raycastAnyBounds,const VxRay&,NODEFAULT,pShapesType,NODEFAULT,pGroupsMask,NODEFAULT,int,0xffffffff,float,NX_MAX_F32) DECLAREMETHOD_8(pWorld,bool,overlapSphereShapes,CK3dEntity*,const VxSphere&,CK3dEntity*,pShapesType,CKGroup*,int,const pGroupsMask*,BOOL) //(const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,unsigned int groups=0xffffffff, float maxDist=NX_MAX_F32); STOPVSLBIND } PhysicManager*GetPhysicManager() { return GetPMan(); } /* void __newvtWorldSettings(BYTE *iAdd) { new (iAdd) pWorldSettings(); } void __newvtSleepingSettings(BYTE *iAdd) { new (iAdd) pSleepingSettings(); } void __newvtJointSettings(BYTE *iAdd) { new (iAdd) pJointSettings(); } int TestWS(pWorldSettings pWS) { VxVector grav = pWS.Gravity(); return 2; } pFactory* GetPFactory(); pFactory* GetPFactory() { return pFactory::Instance(); } extern pRigidBody*getBody(CK3dEntity*ent); */<file_sep>#include <StdAfx.h> #include "vtPhysXAll.h" #include "pMathTools.h" namespace pMath { VxQuaternion getFromStream(NxQuat source) { VxQuaternion result; result.x = source.x; result.y = source.z; result.z = source.y; result.w = source.w; return result; } VxVector getFromStream(NxVec3 source) { VxVector result; result.x = source.x; result.y = source.z; result.z = source.y; return result; } NxQuat getFrom(VxQuaternion source) { NxQuat result; result.setx(-source.x); result.sety(-source.y); result.setz(-source.z); result.setw(source.w); return result; } VxQuaternion getFrom(NxQuat source) { VxQuaternion result; source.getXYZW(result.v); result.x = -result.x; result.z = -result.z; result.y = -result.y; return result; } } <file_sep>/* * Tcp4u v 3.31 Last Revision 27/06/1997 3.30 * *=========================================================================== * * Project: Tcp4u, Library for tcp protocol * File: http4u_url.c * Purpose: everything which deals with URLs * *=========================================================================== * * This software is Copyright (c) 1996-1998 by <NAME> and <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * If you make modifications to this software that you feel * increases it usefulness for the rest of the community, please * email the changes, enhancements, bug fixes as well as any and * all ideas to me. This software is going to be maintained and * enhanced as deemed necessary by the community. * * * <NAME> (<EMAIL>) */ #include "build.h" #define SLASH '/' #define PERIOD ':' #define HTTP_SERVICE "http" #define HTTP_PORT 80 /* ------------------------------------------------------------------------- */ /* HttpIsValidURL: Retourne TRUE si l'URL est valide. De plus les differents */ /* composants de l'URL sont retournes a l'utilisateur */ /* ------------------------------------------------------------------------- */ BOOL API4U HttpIsValidURL (LPCSTR szURL, unsigned short far *lpPort, LPSTR szService, int uServiceSize, LPSTR szHost, int uHostSize, LPSTR szFile, int uFileSize ) { LPCSTR p, q; int ServerLength; Tcp4uLog (LOG4U_HIPROC, "HttpIsValidURL"); szHost[0]=0; /* default service : HTTP */ Strcpyn (szService, HTTP_SERVICE, uServiceSize); /* if URL begins with "service:" do the job then forget it */ p = Tcp4uStrIStr (szURL, "://"); if (p!=NULL) { Strcpyn (szService, szURL, min ((int) (p - szURL + 1), uServiceSize) ); szURL = p+1; } /* The same if URL begins with "//" */ if (szURL[0]==SLASH && szURL[1]==SLASH) szURL+=2; /* URL is now either "Host:Port/File" or "Host/File" */ for (p=szURL ; *p!=0 && *p!=SLASH ; p++); if (*p==0) p=NULL; if (szFile!=NULL) Strcpyn (szFile, p==NULL ? "/" : p, uFileSize); /* search for port which should be before File */ if (p==NULL) p = szURL + Strlen(szURL) - 1; /* last character */ for (q=p ; q>szURL && *q!=':' ; q--); if (q==szURL) q=NULL; /* -> : not found */ *lpPort = q==NULL ? HTTP_PORT : Tcp4uAtoi (q+1); /* Host is to be copied */ ServerLength = p==NULL ? Strlen (szURL) : (q==NULL ? (p-szURL) : (q-szURL) ); Strcpyn (szHost, szURL, min (ServerLength+1, uHostSize)); Tcp4uLog (LOG4U_HIEXIT, "HttpIsValidURL"); return szHost[0]!=0; /* rejects if no host specified otherwise accepts anything */ } /* HttpIsValidURL */ #ifdef TEST main (int argc, char *argv[]) { char szService[10], szHost[10], szFichier[30]; /* short string to test limits */ unsigned short usPort; int Rc; /* ------------------------------init */ memset (szService, 0, sizeof szService); memset (szHost, 0, sizeof szHost); memset (szFichier, 0, sizeof szFichier); usPort = -1; /* ------------------------------init */ Rc=HttpIsValidURL(argv[1], &usPort, szService, 10, szHost, 10, szFichier, 30); printf ("l'URL <%s> est-elle valide ? .... %s\n", argv[1], Rc ? "oUi" : "Non"); { printf ("Port : %d\n", usPort); printf ("Serveur : <%s>\n", szHost); printf ("Service : <%s>\n", szService); printf ("Fichier : <%s>\n", szFichier); } } #endif
6ec31b9f564cf79640f74e87c08f98fff0e49d58
[ "Makefile", "C#", "XML", "C", "INI", "CMake", "Logos", "Batchfile", "Rascal", "Text", "Python", "C++", "Lua" ]
795
Makefile
gbaumgart/vt
d1a0b0afa5b1500eee6dfe5191870868f24135f8
714dcfe12642556631cc42064b88f095778cd91e
refs/heads/master
<repo_name>jonnathanpena/BluOrk_Landing<file_sep>/src/app/providers/url.providers.ts import { Injectable } from '@angular/core'; @Injectable() export class ULRProvider { public dominio: String = 'http://www.hotspotg.com/bluork/api/'; /* USERS */ public getAllUsers() { return this.dominio + 'users/getAll.php'; } public getUserByEmail() { return this.dominio + 'users/getByEmail.php'; } public getUserById() { return this.dominio + 'users/getById.php'; } public insertUser() { return this.dominio + 'users/insert.php'; } public updateUser() { return this.dominio + 'users/update.php'; } public updatePassword() { return this.dominio + 'users/cambiarClave.php'; } /* END USERS */ } <file_sep>/src/app/login/login.component.ts import { Component, OnInit} from '@angular/core'; import notify from 'devextreme/ui/notify'; import { LoginProvider } from './login.providers'; import { AuthService, FacebookLoginProvider, GoogleLoginProvider } from 'angular-6-social-login'; @Component({ templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { usuario: any; guardando: boolean; constructor( private services: LoginProvider, private socialAuthService: AuthService ) {} ngOnInit() { this.usuario = { email_users: '', clave: '', remember: 0 }; this.guardando = false; /*this.services.allUsers().subscribe((response: Response) => { console.log('respuesta', response); });*/ } login(e) { e.preventDefault(); this.services.userByEmail(this.usuario).subscribe(response => { if (response['data'].length > 0) { if (response['data'][0]['password_users'] === this.usuario.clave) { console.log('puede ingresar'); } else { notify('Usuario y/o Clave no coinciden', 'error', 2000); } } else { notify('Usuario no registrado', 'error', 2000); this.cancelar(); } }); } cancelar() { this.ngOnInit(); } remember(e) { if (this.usuario.remember === 0) { this.usuario.remember = 1; } else { this.usuario.remember = 0; } } public socialSignIn(socialPlatform: string) { let socialPlatformProvider; if (socialPlatform === 'facebook') { socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID; } else if (socialPlatform === 'google') { socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID; } this.socialAuthService.signIn(socialPlatformProvider).then( (userData) => { console.log(socialPlatform + ' sign in data : ' , userData); // Now sign-in with userData // ... } ); } } <file_sep>/src/app/signup/signup.component.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { Routes, RouterModule } from '@angular/router'; import { SignUpRoutes } from './signup.routing'; import { SignUpComponent } from './signup.component'; import { ULRProvider } from '../providers/url.providers'; import { SignUpProvider } from './signup.providers'; import { DxTextBoxModule, DxValidatorModule, DxValidationSummaryModule, DxButtonModule } from 'devextreme-angular'; @NgModule({ imports: [ CommonModule, RouterModule.forChild(SignUpRoutes), FormsModule, DxTextBoxModule, DxValidatorModule, DxValidationSummaryModule, DxButtonModule ], declarations: [ SignUpComponent ], providers: [ ULRProvider, SignUpProvider ] }) export class SignUpModule {} <file_sep>/src/app/signup/signup.component.ts import { Component, OnInit} from '@angular/core'; import notify from 'devextreme/ui/notify'; import { SignUpProvider } from './signup.providers'; @Component({ templateUrl: './signup.component.html', styleUrls: ['./signup.component.scss'] }) export class SignUpComponent implements OnInit { usuario: any; guardando: boolean; constructor( private services: SignUpProvider ) {} ngOnInit() { this.usuario = { firstName_users: '', lastName_users: '', email_users: '', password_users: '', confirme: '' }; this.guardando = false; /*this.services.allUsers().subscribe((response: Response) => { console.log('respuesta', response); });*/ } signup(e) { e.preventDefault(); this.guardando = true; if (this.usuario.password_users !== this.usuario.confirme) { this.usuario.password_users = ''; this.usuario.confirme = ''; notify('Las claves no coinciden', 'error', 2000); this.guardando = false; } else { this.consultaExistencia(); } } consultaExistencia() { this.services.userByEmail(this.usuario).subscribe( response => this.insert(response) ); } insert(response) { if (response.data.length > 0) { notify('Email ya registrado', 'error', 2000); } else { this.services.insertUser(this.usuario).subscribe(resp => this.postInsert(resp)); } } postInsert(response) { if (response > 0) { notify('Usuario registrado exitosamente', 'success', 2000); } else { notify('Algo malo sucedió, por favor, intente nuevamente', 'error', 2000); } this.cancelar(); } cancelar() { this.usuario = { firstName_users: '', lastName_users: '', email_users: '', password_users: '', confirme: '' }; this.guardando = false; } } <file_sep>/src/app/signup/signup.providers.ts import { ULRProvider } from '../providers/url.providers'; import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http'; @Injectable() export class SignUpProvider { httpOptions: any = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'my-auth-token' }) }; constructor( private urlProvider: ULRProvider, private http: HttpClient ) {} public allUsers() { return this.http.get(this.urlProvider.getAllUsers()); } public userByEmail(objeto: any) { return this.http.post(this.urlProvider.getUserByEmail(), JSON.stringify(objeto), this.httpOptions); } public userById(objeto: any) { return this.http.post(this.urlProvider.getUserById(), JSON.stringify(objeto), this.httpOptions); } public insertUser(objeto: any) { return this.http.post(this.urlProvider.insertUser(), JSON.stringify(objeto), this.httpOptions); } public updateUser(objeto: any) { return this.http.post(this.urlProvider.updateUser(), JSON.stringify(objeto), this.httpOptions); } }
373d4353c4951031a59a3dccc7898e0cdc87de60
[ "TypeScript" ]
5
TypeScript
jonnathanpena/BluOrk_Landing
22a875b0cc73835f5554a13169208697947150cf
5c99488c8fb200d76e5e4dafde97185d6569e903
refs/heads/master
<file_sep>$error:#df3c31; p { font-size: 20px; } .circulo { padding-top: 25px; padding-left: 25px; height:100px; width:100px; border-radius:100px; border: 2px solid $error; mat-icon { font-size: 45px; color: $error !important; } }<file_sep>$light:#b8b6b4; $dark: rgb(15, 18, 20); .borderless td, .borderless th { border: none; } select { background-color: $dark !important; color: $light !important; border: 2px solid $dark !important; } .basic { color: #ffffff; } .gold { color: rgb(209, 149, 71); } .silver { color: rgb(143, 142, 142); } .bronce { color: #946b41; } .gold-b { background-color: rgb(209, 149, 71); } .silver-b { background-color: rgb(146, 146, 146); } .bronce-b { background-color: #865829; } tr:hover { cursor: pointer; color: white !important; } tr { border: 2px solid #1e212b; } <file_sep>//Login - María var pass = '<PASSWORD>'; var emailValido = '<EMAIL>'; var emailInvalido = '<EMAIL>'; describe('Login', () => { beforeEach(() => { // Abrimos la web cy.visit('https://pfg-survivor.netlify.app'); // Click botón login cy.get('#btn-login').click(); }); it('Validación correcta', () => { // Submit del formulario cy.get('#login').submit(); // Se muestran los mensajes de validación cy.contains('Este campo es obligatorio.'); // Hacemos captura de pantalla cy.screenshot(); }); it('Login correcto', () => { // Email cy.get('#email').type(emailValido).should('have.value', emailValido); // Contraseña cy.get('#pass').type(pass).should('have.value', pass); // Submit del formulario cy.get('#login').submit(); // Espera 3s cy.wait(3000); // La url ahora debe contener /home cy.url().should('include', '/home'); // Espera 3s cy.wait(3000); // Hacemos captura de pantalla cy.screenshot(); }); it('Login incorrecto', () => { // Email cy.get('#email').type(emailInvalido).should('have.value', emailInvalido); // Contraseña cy.get('#pass').type(pass).should('have.value', pass); // Submit del formulario cy.get('#login').submit(); // Alerta login incorrecto cy.contains('No se ha podido iniciar sesión. Revise sus credenciales.'); // Espera 1s cy.wait(1000); // Hacemos captura de pantalla cy.screenshot(); }); });<file_sep>//Login - María var emailValido = '<EMAIL>'; var emailInvalido = '<EMAIL>'; describe('Contraseña olvidada', () => { beforeEach(() => { // Abrimos la web cy.visit('https://pfg-survivor.netlify.app'); // Click botón registro cy.get('#btn-login').click(); // Click he olvidado la contraseña cy.get('#forgotPass').click(); }); it('Validación correcta', () => { // Submit del formulario cy.get('#passOlvidada').submit(); // Se muestran los mensajes de validación cy.contains('Este campo es obligatorio.'); // Hacemos captura de pantalla cy.screenshot(); }); it('Correo enviado correctamente', () => { // Espera 1s cy.wait(1000); // Email cy.get('#email').type(emailValido).should('have.value', emailValido); // Submit del formulario cy.get('#passOlvidada').submit(); // Alerta email enviado correctamente cy.contains('Se ha enviado un mensaje al correo electrónico para restablecer la contraseña.'); // Espera 1s cy.wait(1000); // Hacemos captura de pantalla cy.screenshot(); }); it('Email invalido', () => { // Espera 1s cy.wait(1000); // Email cy.get('#email').type(emailInvalido).should('have.value', emailInvalido); // Submit del formulario cy.get('#passOlvidada').submit(); // Alerta email no registrado en la aplicación cy.contains('No hay ningún usuario registrado con el correo electrónico solicitado.'); // Espera 1s cy.wait(1000); // Hacemos captura de pantalla cy.screenshot(); }); });<file_sep>import { TestBed } from '@angular/core/testing'; import { AngularFireModule } from '@angular/fire'; import { AngularFireAuthModule } from '@angular/fire/auth'; import { RouterTestingModule } from '@angular/router/testing'; import { environment } from 'src/environments/environment'; import { HomeComponent } from '../views/home/home.component'; import { HttpClientModule } from '@angular/common/http'; import { ChatService } from './chat.service'; describe('ChatService', () => { let service: ChatService; beforeEach(() => { TestBed.configureTestingModule({ imports: [ AngularFireModule.initializeApp(environment.firebaseConfig), AngularFireAuthModule, RouterTestingModule, HttpClientModule, RouterTestingModule.withRoutes([ { path: 'home', component: HomeComponent } ]) ], }); service = TestBed.inject(ChatService); }); it('should be created', () => { expect(service).toBeTruthy(); }); }); <file_sep>import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import firebase from 'firebase/app'; import 'firebase/firestore'; import { environment } from 'src/environments/environment'; import * as _ from "lodash"; import { AngularFireStorage } from '@angular/fire/storage'; import { Subject } from 'rxjs'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ChatService { msgEnviar = ''; // Variable ngmodel de enviar mensaje !!!Cambiar userAuth: any | null; // Usuario guardado en session local storage friends = []; // Lista de amigos messagesFriends = []; // Array de mensajes de tus amigos messagesWithFriend = []; // Array de mensajes de amigos ya convertidos: mensajes que se van mostrando en cada chat uidFriendSelected = ''; // Amigo seleccionado al cambiar de chat chatEnabled = false; // Se activa cuando se pulsa un chat, permite ver los mensajes listeningSnapsMessages = []; // Array que contiene los escuchas de los mensajes de los amigos para poder desactivarlos al cerrar sesión listeningFriends = []; // Array que contiene las escuchas de los amigos para poder desactivarlos al cerrar sesión messagesWithoutRead = []; // Mensajes de cada chat sin leer gotAllMessages: boolean = false; // Comprueba si ya se han obtenido todos los mensajes (sin leer) al recargar la página friendSelected: any; // Guarda toda la información el usuario seleccionado urlImg: any; // Guarda la url de la imagen del chat para mostrarla en el modal suggestedFriends = []; // Sugerencias de amigos "Amigos de mis amigos" sentRequested = []; // Array que contiene los uid que el usuario mandó solicitud msgsWithoutReadNotif = []; // Mensajes sin leer para las notificaciones del chat urlImgsChat = []; // URL de las imágenes que el usuario ha compartido con cada chat // Avisa al componente de que se ha recibido/enviado un nuevo mensaje para que el scroll baje automáticamente private countdownEndSource = new Subject<void>(); public countdownEnd$ = this.countdownEndSource.asObservable(); nFriends: number = 0; tokenUser: string = ''; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~CONSTRUCTOR~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ constructor( public firestorage: AngularFireStorage, private http: HttpClient) { } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Obtiene el usuario almacenado en localStorage, el cual se almacena al iniciar sesión */ getUser() { this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); this.tokenUser = this.userAuth['stsTokenManager']['accessToken']; } /** * Vacía los mensajes al cerrar sesión */ cleanMessages() { this.messagesWithoutRead = []; this.msgsWithoutReadNotif = []; } /** * Marcar como conectado/desconectado * @param type 1: conectado / 2: desconectado */ setStatusOnOff(type: number) { this.getUser(); var status; if (type == 1) { status = 'online'; } else { status = 'offline'; } const url = environment.dirBack + "updateStatus/" + this.userAuth.uid; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.put(url, { 'user': this.userAuth, status: status }, { headers: headers }) .subscribe(() => { }); } /** * Suena mensaje dependiendo del tipo * @param type 1: mensaje sin leer / 2: borrar mensaje / 3: borrar chat */ sonidito(type: number) { if (type == 1) { var audio = new Audio('../../assets/tonos/tono-mensaje.mp3'); } else if (type == 2) { var audio = new Audio('../../assets/tonos/tono-delete.mp3'); } else if (type == 3) { var audio = new Audio('../../assets/tonos/tono-delete-chat.mp3'); } audio.play(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~GET FRIENDS & LISTEN FRIENDS~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Cargar amigos */ getFriends() { this.friends = []; this.getUser(); var contAmigos; // Obtener nº de amigos -> Si obtiene 0 vuelve a la vista si no pone en escucha los mensajes this.getFriendsData(this.userAuth.uid) .subscribe( (response) => { contAmigos = response['message'].length; if (contAmigos == 0) { this.gotAllMessages = true; return; } }); this.listenFriends(contAmigos); } /** * Pone en escucha la lista de amigos */ listenFriends(contAmigos) { this.getUser(); var db = firebase.firestore(); var query = db.collection('users').doc(this.userAuth.uid).collection('friends') var unsubscribe = query.onSnapshot(snapshot => { snapshot.docChanges().forEach((change, index) => { // Obtener nº de amigos si se añade un nuevo amigo, no se pase a poner en esucucha a los mensajes hasta obtenerlos todos this.getFriendsData(this.userAuth.uid) .subscribe( (response) => { this.nFriends = response['message'].length; // Amigo borrado if (change.type === 'removed') { this.friends.forEach((user, i) => { if (user.uid == change.doc.id) { this.friends.splice(i, 1); } }); this.closeChat(); } // Cargando todos los amigos o nuevo amigo añadido else { // Obtener datos generales this.getUserData(change.doc.id) .subscribe( (responseUser) => { // Obtener fecha inicio de amistad this.getFriendShipData(change.doc.id) .subscribe( (responseDataFriend) => { const friend = { 'uid': responseUser['message'].uid, 'status': responseUser['message'].status, 'displayName': responseUser['message'].displayName, 'photoURL': responseUser['message'].photoURL, 'email': responseUser['message'].email, 'coins': responseUser['message'].coins, 'friendshipDate': responseDataFriend['message'] } this.friends.push(friend); // Pone en escucha la información del amigo this.listenDataFriend(change.doc.id); // var pos = this.friends.length - 1; // this.listenFriendMessages(friend, pos); // Ultima pos del array -> obtiene los amigos sugeridos if (this.nFriends == index + 1) { this.getSuggestedFriends(); this.stopListeningReListenFM(2); //this.listenFriendMessages(); }else { // Se ha añadido un nuevo amigo if (contAmigos != this.nFriends) { this.getSuggestedFriends(); this.stopListeningReListenFM(2); } } }); }); } }); }); }); this.listeningFriends.push(unsubscribe); } /** * Obtiene información de amigos del usuario logeado (uids -> nº de amigos) * @returns */ getFriendsData(userUID) { const url = `${environment.dirBack}getFriendsUID/${userUID}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.get(url, { headers: headers }); } /** * Obtiene la información del amigo * @param userUID * @returns */ getUserData(userUID) { const url = `${environment.dirBack}getUser/${userUID}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.get(url, { headers: headers }); } /** * Obtiene la información de la relación de amistad (fecha de inicio) * @param userUID * @returns */ getFriendShipData(userUID) { const url = `${environment.dirBack}getDataFriendship/${this.userAuth.uid}/${userUID}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.get(url, { headers: headers }); } /** * Pone en escucha los datos del usuario * Para ver actualizado su estado (online/offline) entre otros * @param userUID */ listenDataFriend(userUID) { var db = firebase.firestore(); var unsubscribe = db.collection("users").doc(userUID) .onSnapshot({ includeMetadataChanges: true }, (doc) => { // Buscar usuario y actualizar sus datos this.friends.forEach(friend => { if (friend.uid == userUID) { friend.status = doc.data().status; friend.email = doc.data().email; friend.displayName = doc.data().displayName; friend.coins = doc.data().coins; } }); }); this.listeningFriends.push(unsubscribe); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUGGESTED FRIENDS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Sugerencias de amigos "Amigos de mis amigos" */ getSuggestedFriends() { this.suggestedFriends = []; if (this.friends.length == 0) { return }; // Obtener peticiones de amistad enviadas this.getSentFriendsRequests() .subscribe( (response) => { this.sentRequested = response['message']; // Recorrer mis amigos para buscar los amigos de cada uno this.friends.forEach(friend => { // Obtener amigos de mi amigo this.getFriendsData(friend.uid) .subscribe( (response) => { var friendsUID = response['message']; // Buscamos si el usuario está entre los amigos del usuario friendsUID.forEach(user => { // Excluyendo al usuario logeado if (user.uid != this.userAuth.uid) { var encontrado = this.searchUserArrays(user); if (!encontrado) { // Se crea el amigo sugerido con datos vacíos ya que tarda en obtener los datos y al buscarlo en el array de // sugeridos todavía no lo encuentra y duplica la información const suggestedFriend = { 'uid': user.uid, 'status': '', 'displayName': '', 'photoURL': '', 'email': '', 'coins': '', 'relation': 'unknown' } this.suggestedFriends.push(suggestedFriend); var pos = this.suggestedFriends.length - 1; this.getUserData(user.uid) .subscribe( (response) => { this.suggestedFriends[pos].status = response['message'].status; this.suggestedFriends[pos].displayName = response['message'].displayName; this.suggestedFriends[pos].photoURL = response['message'].photoURL; this.suggestedFriends[pos].email = response['message'].email; this.suggestedFriends[pos].coins = response['message'].coins; }); } } }); }); }); }); } /** * Busca a un usuario en la lista de amigos, sugeridos y peticiones enviadas * @param user * @returns true: encontrado / false: no encontrado */ searchUserArrays(user) { var encontrado = false; // Recorro la lista de mis amigos this.friends.forEach(friend => { if (friend.uid == user.uid) { encontrado = true; } }); // Recorro la lista de peticiones de amistad enviadas this.sentRequested.forEach(uidRequested => { if (uidRequested == user.uid) { encontrado = true; } }); // Recorro la lista de sugerencias this.suggestedFriends.forEach(suggestedFriend => { if (suggestedFriend.uid == user.uid) { encontrado = true; } }); return encontrado; } /** * Obtiene las peticiones de amistad enviadas del usuario logeado * Para que estos usuarios no aparezcan en recomendados * @returns */ getSentFriendsRequests() { const url = `${environment.dirBack}getSentFriendsRequests/${this.userAuth.uid}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.get(url, { headers: headers }); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~LISTEN FRIEND MESSAGES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Pone en escucha los mensajes de todos los amigos * para recibir en tiempo real cualquier cambio */ listenFriendMessages() { var db = firebase.firestore(); this.getUser(); this.messagesFriends = []; this.messagesWithoutRead = []; this.msgsWithoutReadNotif = []; var msgs = []; var msg: any; var read = true; if (this.friends.length > 0) { this.friends.forEach((friend, index) => { msgs = []; var query = db.collection('users').doc(this.userAuth.uid).collection('friends') .doc(friend.uid).collection('messages') .orderBy('timestamp', 'asc') var unsubscribe = query.onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { // Mensaje eliminado if (change.type === 'removed') { read = false; this.messagesFriends.forEach(user => { if (user.uid == friend.uid) { user.messages.forEach((message, index) => { if (message.id == change.doc.id) { console.log('Mensaje borrado: ', message.id); user.messages.splice(index, 1); // Si todavía no está leido -> Descontar uno del contador de mensajes sin leer if (message.isRead == false && message.uid == friend.uid) { // !!! this.messagesWithoutRead.forEach(msg => { if (msg.uid == friend.uid) { var n = msg.messages - 1; msg.messages = n; } }); } } }); } }); } // Mensaje actualizado (marcado como leído) else if (change.type === 'modified') { read = false; this.messagesFriends.forEach(user => { if (user.uid == this.uidFriendSelected) { user.messages.forEach(message => { if (message.id == change.doc.id) { console.log('Mensaje actualizado: ', message.id); message.isRead = true; } }); } }); } // Mensaje añadido/recibido else { read = true; var h = ''; h += change.doc.data().timestamp.toDate(); // var year = h.substring(11, 15); const message = { 'id': change.doc.id, 'uid': change.doc.data().uid, 'displayName': change.doc.data().displayName, 'text': change.doc.data().text, 'imageURL': change.doc.data().imageURL, 'isRead': change.doc.data().isRead, 'storageRef': change.doc.data().storageRef, 'timestamp': h.substring(16, 21), 'day': h.substring(8, 11) + h.substring(4, 7) } msgs.push(message); msg = message; } }); if (read) { this.addMessages(friend, msg, msgs); msgs = []; } // Obtener nº mensajes sin leer panel de notificaciones this.countMessagesWithoutRead(friend, index); // Ha terminado de obtener los mensajes if (this.friends.length - 1 == index && this.gotAllMessages == false) { console.log(this.msgsWithoutReadNotif); this.gotAllMessages = true; console.log('Termine'); } }); // Añadir al array para poder dejar de escuchar al cerrar sesión y q al volver a entrar no vuelva a escuchar y x lo tanto haya duplicidad de mensajes this.listeningSnapsMessages.push(unsubscribe); }); } } /** * Añade un mensaje al array de mensajes totales y pendientes por leer * @param friend * @param msg * @param msgs */ addMessages(friend, msg, msgs) { var db = firebase.firestore(); var encontrado = false; // Cargar nuevo mensaje if (this.messagesFriends.length > 0) { this.messagesFriends.forEach(user => { // Cargar un solo mensaje al enviar o recibir if (user.uid == friend.uid || user.uid == this.userAuth.uid) { encontrado = true; user.messages[user.messages.length] = msg; // Recibes nuevo mensaje: evento para bajar scroll this.countdownEndSource.next(); // Comprobar el chat que tengo abierto db.collection("users").doc(this.userAuth.uid).get() .then((doc) => { // En caso de no tener el chat abierto añadimos un mensaje más sin leer if (doc.data().chatOpen != friend.uid) { if (msg.uid == friend.uid && msg.isRead == false) { this.messagesWithoutRead.forEach(msg => { if (msg.uid == friend.uid) { var n = msg.messages + 1; msg.messages = n; } }); console.log('Mensajes sin leer:', this.messagesWithoutRead); this.sonidito(1); } } }); } }); } // Cargar mensajes inicialmente if (!encontrado) { //console.log('CARGAR MENSAJES INICIALES', friend.uid); //console.log(friend.uid, msgs); this.messagesFriends.push({ 'uid': friend.uid, 'displayName': friend.displayName, 'photoURL': friend.photoURL, 'messages': msgs }); console.log(this.messagesFriends); // Se suman aquellos mensajes sin leer y cuyo uid sea del amig var cont = 0; msgs.forEach(msg => { if (msg.uid == friend.uid && msg.isRead == false) { cont++; } }); this.messagesWithoutRead.push({ 'uid': friend.uid, 'displayName': friend.displayName, 'photoURL': friend.photoURL, 'messages': cont }); // console.log('M<NAME> LEER', this.messagesWithoutRead.length); } } /** * Array de mensajes lista de notificación * @param friend * @param index */ countMessagesWithoutRead(friend, index) { //console.log('Hay mensajes sin leer', this.messagesWithoutRead); if (this.messagesWithoutRead[index]) { setTimeout(() => { if (this.messagesWithoutRead[index].messages > 0) { var enc = false; //console.log('Hay mensajes sin leer', this.messagesWithoutRead[index].uid); this.msgsWithoutReadNotif.forEach(msg => { if (msg.uid == this.messagesWithoutRead[index].uid) { enc = true; var ms = this.messagesWithoutRead[index].messages; msg.messages = ms++; } }); if (!enc) { this.msgsWithoutReadNotif.push({ 'uid': friend.uid, 'messages': this.messagesWithoutRead[index].messages }); } } //Buscarlo y borrarlo else { this.msgsWithoutReadNotif.forEach((msg, index2) => { if (msg.uid == this.messagesWithoutRead[index].uid) { this.msgsWithoutReadNotif.splice(index2, 1); } }); } }, 500); } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~CHAT WITH FRIEND~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Abrir mensajes de un chat con amigo * En caso de que los mensajes no estén leídos los marca como leidos * @param friend amigo seleccionado */ chatWith(friend: any) { this.messagesWithFriend = []; this.uidFriendSelected = friend.uid; this.friendSelected = friend; console.log('MENSAJES AMIGOS', this.messagesFriends); this.messagesFriends.forEach(user => { if (user.uid == friend.uid) { this.messagesWithFriend = user.messages; console.log('Mensajes del chat abierto: ', this.messagesWithFriend); // Marcar chat abierto this.setChatOpen(user.uid); // Poner en leído los mensajes del chat correspondiente this.messagesWithFriend.forEach(msg => { if (msg.uid != this.userAuth.uid && msg.isRead == false) { this.setMessagesRead(user.uid, msg.id); msg.isRead = true; } }); // Marcar en leído en el array que notifica cuantos mensajes te faltan x leer this.messagesWithoutRead.forEach(msg => { if (msg.uid == user.uid) { msg.messages = 0; } }); } }); this.chatEnabled = true; } /** * Guardar el chat que tiene el usuario abierto * @param uidFriend */ setChatOpen(uidFriend) { const url = `${environment.dirBack}setChatOpen/${this.userAuth.uid}/${uidFriend}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.put(url, { headers: headers }) .subscribe(() => { }); } /** * Marca en leído el mensaje en ambos usuarios * @param uidFriend * @param idMsg */ setMessagesRead(uidFriend, idMsg) { const url = `${environment.dirBack}setMessagesRead/${this.userAuth.uid}/${uidFriend}/${idMsg}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.put(url, { headers: headers }) .subscribe(() => { }); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~SEND MESSAGE TO FRIEND~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Enviar mensaje al amigo cuyo chat tienes abierto */ sendMessageFriend() { var msg = this.msgEnviar; this.msgEnviar = ''; const url = `${environment.dirBack}sendMessage/${this.userAuth.uid}/${this.uidFriendSelected}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.put(url, { 'user': this.userAuth, 'message': msg }, { headers: headers }) .subscribe( (response) => { var msgid = response['message']; this.checkUserChat(msgid); }); } /** * Comprueba si el usuario tiene el chat abierto, en caso de tenerlo * marca los mensajes como leídos * @param msgid */ checkUserChat(msgid: any) { const url = `${environment.dirBack}checkUserChat/${this.userAuth.uid}/${this.uidFriendSelected}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.get(url, { headers: headers }) .subscribe( (response) => { var open = response['message']; if (open) { this.setMessagesRead(this.uidFriendSelected, msgid); } }); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~SEND IMAGE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Enviar imágen en un chat * @param event */ sendImg(event) { var file = event.target.files[0]; var imgName = Math.floor(Math.random() * 100000000); var filePathUser = `images/${this.userAuth.uid}/${this.uidFriendSelected}/${imgName}`; var filePathFriend = `images/${this.uidFriendSelected}/${this.userAuth.uid}/${imgName}`; // Subir imagen storage loged user this.firestorage.ref(filePathUser).put(file).then(fileSnapshot => { fileSnapshot.ref.getDownloadURL() .then(url => { // Añadir firestore loged user this.sendImgFriend(this.userAuth, this.uidFriendSelected, url, imgName) .subscribe( (response) => { var msgid = response['message']; // Subir imagen storage friend this.firestorage.ref(filePathFriend).put(file).then(fileSnapshot => { fileSnapshot.ref.getDownloadURL() .then(url => { // Añadir firestore friend this.sendImgWithId(msgid, this.userAuth, this.uidFriendSelected, url, imgName) .subscribe(() => { // Comprobar chat abierto marcar leídos this.checkUserChat(msgid); }); }); }); }); }); }); } /** * Enviar imagen a amigo * @param emisor * @param receptorUID * @param url * @param nombreImg * @returns */ sendImgFriend(emisor: any, receptorUID: any, urlPhoto: string, namePhoto: any) { const url = `${environment.dirBack}sendImgFriend/${emisor.uid}/${receptorUID}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.put(url, { 'user': emisor, 'urlPhoto': urlPhoto, 'namePhoto': namePhoto }, { headers: headers }); } /** * Enviar imagen a amigo estableciendole el id al mensaje para que sea el mismo en ambos mensajes * @param id * @param emisor * @param receptorUID * @param url * @param nombreImg * @returns */ sendImgWithId(id: string, emisor: any, receptorUID: any, urlPhoto: string, namePhoto: any) { const url = `${environment.dirBack}sendImgFriendId/${emisor.uid}/${receptorUID}/${id}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.put(url, { 'user': emisor, 'urlPhoto': urlPhoto, 'namePhoto': namePhoto }, { headers: headers }); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DELETE MESSAGES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Elimina un mensaje * @param message mensaje seleccionado para borrar * @param type 1: eliminar para mi // 2: eliminar para todos */ deleteMsgs(message: any, type: number) { this.sonidito(2); // Eliminar para mi this.deleteMessages(this.userAuth.uid, this.uidFriendSelected, message); // Eliminar para todos if (type == 2) { this.deleteMessages(this.uidFriendSelected, this.userAuth.uid, message); } } /** * Elimina un mensaje del chat, en el caso que tenga foto asociada la * elimina también del storage * @param uidEmisor * @param uidReceptor * @param message */ deleteMessages(uidEmisor: string, uidReceptor: string, message: any) { var photoName = null; if (message.storageRef) { photoName = message.storageRef; } const url = `${environment.dirBack}deleteMessage/${uidEmisor}/${uidReceptor}/${message.id}/${photoName}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.delete(url, { headers: headers }) .subscribe(() => { }); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~CLOSE CHAT~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Cierra el chat abierto */ closeChat() { this.getUser(); this.uidFriendSelected = ''; this.chatEnabled = false; var uidFriend = 'none'; const url = `${environment.dirBack}setChatOpen/${this.userAuth.uid}/${uidFriend}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.put(url, { headers: headers }) .subscribe( (response) => { console.log('RESPONSE: ', response); }); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~STOP LISTENING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Parar escucha de los mensajes del amigo. Este método se llama al cerrar sesión y * a la hora de cargar los amigos, así en caso de que se añada una nuevo, se reiniciará la escucha */ stopListeningReListenFM(type: number) { this.listeningSnapsMessages.forEach(unsubscribe => { unsubscribe(); }); if(type == 2) { this.listenFriendMessages(); } } /** * Parar escucha los amigos. Este método se llama al cerrar sesión */ stopListeningFriends() { this.listeningFriends.forEach(unsubscribe => { unsubscribe(); }); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~DELETE CHAT~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Vacia el chat del usuario logeado * @param deleteImg boolean: borrar imagenes tmb o no */ deleteChat(deleteImg: boolean) { const url = `${environment.dirBack}deleteChat/${this.userAuth.uid}/${this.uidFriendSelected}/${deleteImg}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.delete(url, { headers: headers }) .subscribe( (response) => { this.sonidito(3); console.log(response); }); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GET IMAGES WITH USER ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Cargar imágenes de un chat */ getImagenesChat() { this.urlImgsChat = []; const url = environment.dirBack + "getImgsChat"; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.post(url, { 'uid': this.userAuth.uid, uidFriend: this.uidFriendSelected }, { headers: headers }); } } <file_sep>FROM alpine:3.10 # Variables de entorno ENV HOME=/PFG-Survivor ENV ANGULAR_CLI_VERSION=8.1.0 RUN mkdir $HOME WORKDIR $HOME # Instalación node npm angular RUN apk add --update nodejs nodejs-npm RUN npm install -g @angular/cli@$ANGULAR_CLI_VERSION COPY ./ /PFG-Survivor # Puertos EXPOSE 4200 # Comandos de entrada cuando el contenedor se lanze CMD sh -c "npm install; npm run start" <file_sep>$online:#4caf50; $offline:#f44336; $fondo-chat: #21252e; $scroll: #50667e; .border-green { border: 2px solid $online; } .border-red { border: 2px solid $offline; } .morePhotos { cursor: pointer; height: 120px; display: block; text-align: center; } mat-icon { font-size: 40px; margin-right: 16px; margin-top: 20px; } .photos { max-height: 700px; overflow-y: auto; &::-webkit-scrollbar { width: 11px; } &::-webkit-scrollbar-track { background: $fondo-chat; border-radius: 20px; } &::-webkit-scrollbar-thumb { background-color: $scroll; border-radius: 20px; } &::-webkit-scrollbar-thumb:hover { box-shadow: 0 0 2px 1px rgba(0, 0, 0, 0.2); } }<file_sep>export const environment = { production: true, firebaseConfig: { apiKey: "<KEY>", authDomain: "pfg-survivor-cd919.firebaseapp.com", projectId: "pfg-survivor-cd919", storageBucket: "pfg-survivor-cd919.appspot.com", messagingSenderId: "530404504797", appId: "1:530404504797:web:a2efd13f039584133dd734", measurementId: "G-XSHMWHFTZ6" }, SESSION_KEY_USER_AUTH: 'AUTH_USER_123456789', dirBack: 'https://survivorback.herokuapp.com/api/' }; <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { AuthService } from 'src/app/services/auth.service'; import { LoginComponent } from '../login/login.component'; @Component({ selector: 'app-pass', templateUrl: './pass.component.html', styleUrls: ['./pass.component.scss'] }) export class PassComponent implements OnInit { passOlvidada: FormGroup; msg: string = null; constructor(public ngmodal: NgbModal, public activeModal: NgbActiveModal, private formBuilder: FormBuilder, public auth: AuthService) { this.passOlvidada = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]] }); } ngOnInit(): void { } get formPassOlvidada() { return this.passOlvidada.controls; } onSubmit() { if (this.passOlvidada.invalid) { return; } this.auth.sendPasswordResetEmail() .subscribe( (response) => { console.log('Correo enviado:', response['message']); this.auth.emailPass = ''; this.activeModal.close(); const modalRef = this.ngmodal.open(LoginComponent, { size: 'md' }); modalRef.componentInstance.msgPassword = 'Se ha enviado un mensaje al correo electrónico para restablecer la contraseña.'; }, (error) => { var code = error['error']['message'].code; if (code === 'auth/too-many-requests') { this.msg = 'Hemos bloqueado todas las solicitudes de este dispositivo debido a una actividad inusual. Vuelve a intentarlo más tarde.' }else if(code === 'auth/user-not-found'){ this.msg = 'No hay ningún usuario registrado con el correo electrónico solicitado.'; } }); } /** * Cierra modal contraseña olvidada y abre modal Login */ backLogin(){ this.activeModal.close(); this.ngmodal.open(LoginComponent, { size: 'md' }); } } <file_sep>import { Injectable } from '@angular/core'; import { environment } from 'src/environments/environment'; import { AuthService } from './auth.service'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ShopService { items = []; constructor(private auth: AuthService, private http: HttpClient) {} /** * Recupera los items disponibles en la tienda */ getItems() { const url = environment.dirBack + "getItems"; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.get(url, { headers: headers }) .subscribe( (response) => { this.items = response['message']; // Si el usuario está logeado obtenemos si tiene el arma comprada o no if (this.auth.user) { console.log('Items user', this.auth.itemsLogedUser); this.items.forEach(itemShop => { this.auth.itemsLogedUser.forEach(myitem => { if (itemShop.id == myitem.id) { itemShop.owned = true; itemShop.obtainedDate = myitem.obtainedDate; } }); }); } }); } /** * Comprueba si el usuario puede comprar o no el arma con las monedas que tiene * @param item * @returns */ checkItem(item: any) { var canBuy = true; if (item.price > this.auth.user.coins) { canBuy = false; } return canBuy; } /** * Comprar item * @param item */ buyItem(item: any) { const url = environment.dirBack + "buyItem"; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.put(url, { 'user': this.auth.user, 'item': item }, { headers: headers }) .subscribe( (response) => { console.log(response['message']); // Actualizar estado del item en la tienda this.items.forEach(itemShop => { if (itemShop.id == item.id) { itemShop.owned = true; itemShop.obtainedDate = 'Ahora mismo'; } }); // Añadir item & restar monedas this.auth.addItem(item); var coinsRestantes = this.auth.user.coins - item.price; this.auth.setCoins(coinsRestantes); }); } } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filtroAmigos' }) export class FiltroAmigosPipe implements PipeTransform { transform(value: any, arg: any): any { if(arg === '') return value; const amigosFilter = []; for(const amigo of value) { var amigoF = amigo.displayName.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase(); var busqueda = arg.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase(); if(amigoF.indexOf(busqueda) > -1) { amigosFilter.push(amigo); } } return amigosFilter; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; import { FriendsService } from 'src/app/services/friends.service'; import { environment } from 'src/environments/environment'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { userAuth: any | null; cargar: boolean = false; pathDownload: string = '../../../assets/videogame/Survivor1.0.0.apk'; constructor(public auth: AuthService, public friendService: FriendsService, public chat: ChatService, private _sanitizer: DomSanitizer) { this.getUser(); console.log('CONSTRUCTOR HOME'); if (this.auth.loginRecharge && this.userAuth != null) { this.chat.closeChat(); this.auth.getUser(); } } ngOnInit(): void { } ngAfterViewChecked() { } ngOnDestroy() { } getUser() { this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); } getVideoIframe(url) { var video, results; if (url === null) { return ''; } results = url.match('[\\?&]v=([^&#]*)'); video = (results === null) ? url : results[1]; return this._sanitizer.bypassSecurityTrustResourceUrl('https://www.youtube.com/embed/' + video); } } <file_sep>import { Injectable } from '@angular/core'; import { AngularFireAuth } from '@angular/fire/auth'; import firebase from 'firebase/app'; import { Router } from '@angular/router'; import { environment } from 'src/environments/environment'; import { ChatService } from './chat.service'; import { FriendsService } from './friends.service'; import { RankingsService } from './rankings.service'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class AuthService { // Variables // Login emailLogin = ''; passLogin = ''; // Registro emailRegistro = ''; nombreRegistro = ''; passRegistro = ''; // Pass olvidada emailPass = ''; // User user = null; loginRecharge: boolean = true; userAuth: any | null; providerId: string = null; itemsLogedUser = []; itemsUser = []; constructor(public auth: AngularFireAuth, private router: Router, private chat: ChatService, private friends: FriendsService, private rankings: RankingsService, private http: HttpClient) { } /** * Método que se llama desde los constructores de los componentes para en el caso de haber * recargado volver a establecer esta variable a false */ setRechargeFalse() { this.loginRecharge = false; } addItem(item) { this.itemsLogedUser.push(item); } setCoins(coins) { this.user.coins = coins; } setPhoto(photoURL) { this.user.photoURL = photoURL; } setName(name) { this.user.displayName = name; } setEmail(email) { this.user.email = email; } getProviderID() { this.providerId = null; this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); this.providerId = this.userAuth.providerData[0].providerId; } /** * Método que llama a todos los métodos necesarios para obtener todos los datos para iniciar sesión * Amigos, escuchar mensajes de amigos, peticiones de amistad... * @param user */ prepareLogin(user: any) { localStorage.setItem(environment.SESSION_KEY_USER_AUTH, JSON.stringify(user)); this.updateUserData(user); this.loginRecharge = false; this.getItemsUser(1); this.friends.listenFriendsRequests(); this.friends.listenSentFriendsRequests(); this.chat.getFriends(); this.rankings.stopListeningRankingsItems(); this.rankings.setGetRankingsTrue(); this.rankings.getPositionRankings(); this.rankings.getPositionRankingCoins(); this.router.navigate(['home']); } getItemsUser(type: number, uid?: string) { if (type == 1) { this.itemsLogedUser = []; this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); uid = this.userAuth.uid; } else { this.itemsUser = []; } const url = environment.dirBack + "getItemsUser"; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); this.http.post(url, { 'uid': uid }, { headers: headers }) .subscribe( (response) => { var items = response['message']; if (type == 1) { this.itemsLogedUser = items; } else { this.itemsUser = items; } }); } /** * Registro con email y contraseña * @returns */ registro() { const url = environment.dirBack + "registro"; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.post(url, { 'email': this.emailRegistro, 'pass': <PASSWORD>, 'name': this.nombreRegistro }, { headers: headers }); } /** * Login con email y contraseña * @returns */ login() { const url = environment.dirBack + "login"; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.post(url, { 'email': this.emailLogin, 'pass': this.<PASSWORD>Login }, { headers: headers }); } /** * Login con cuenta de Google */ loginGoogle() { return this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()); } /** * Login con cuenta de Facebook */ loginFacebook() { return this.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider()); } /** * Añadir foto de Facebook al usuario cuando se logea por 1º vez * @param user */ updateProfileFB(user) { if (user.user.photoURL.startsWith('https://graph.facebook.com/')) { user.user.updateProfile({ photoURL: user.additionalUserInfo.profile['picture']['data']['url'] }).then(() => { this.prepareLogin(user.user); }); } else { this.prepareLogin(user.user); } } /** * Guardar usuario en base de datos * @param user */ updateUserData(user: any) { const url = environment.dirBack + "updateUserLogin"; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); this.http.post(url, { 'user': user }, { headers: headers }) .subscribe( (response) => { console.log('USER:', response); this.getUser(); }); } /** * Obtener los datos del usuario logeado */ getUser() { this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); var token = this.userAuth['stsTokenManager']['accessToken']; const url = `${environment.dirBack}getUser/${this.userAuth.uid}`; let headers = new HttpHeaders({ Authorization: `Bearer ${token}` }); this.http.get(url, { headers: headers }) .subscribe( (response) => { this.user = { 'uid': response['message'].uid, 'status': response['message'].status, 'displayName': response['message'].displayName, 'photoURL': response['message'].photoURL, 'email': response['message'].email, 'coins': response['message'].coins, } }); } /** * Envía correo al email introducido donde se le permite cambiar la contraseña de la cuenta. */ sendPasswordResetEmail() { const url = environment.dirBack + "sendPasswordResetEmail"; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.post(url, { 'email': this.emailPass }, { headers: headers }); } /** * Cerrar sesión cuenta */ logout() { this.user = null; this.auth.signOut(); this.setRechargeFalse(); this.rankings.stopListeningRankingsItems(); this.chat.setStatusOnOff(2); this.chat.stopListeningReListenFM(1); this.chat.stopListeningFriends(); this.friends.stopListeningRequests(); this.chat.closeChat(); this.friends.resetSearchFriends(); this.rankings.setGetRankingsTrue(); this.chat.cleanMessages(); this.limpiarFormularios(); setTimeout(() => { localStorage.removeItem(environment.SESSION_KEY_USER_AUTH) }, 500); this.router.navigate(['home']); } /** * Método que limpia los inputs de los formularios login/registro/pass */ limpiarFormularios() { this.emailLogin = ''; this.nombreRegistro = ''; this.passLogin = ''; this.emailRegistro = ''; this.passRegistro = ''; } } <file_sep>import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-confirm-modal', templateUrl: './confirm-modal.component.html', styleUrls: ['./confirm-modal.component.scss'] }) export class ConfirmModalComponent implements OnInit { @Input() public msg: any; @Output() confirm: EventEmitter<any> = new EventEmitter(); constructor(public ngmodal: NgbModal, public activeModal: NgbActiveModal) { } ngOnInit(): void { } accept() { const del = document.getElementById("deleteAll") as HTMLInputElement; this.confirm.emit(del.checked); this.activeModal.close(); } cancel() { this.activeModal.close(); } } <file_sep>import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AmigosComponent } from './views/amigos/amigos.component'; import { ComunidadComponent } from './views/comunidad/comunidad.component'; import { HomeComponent } from './views/home/home.component'; import { LoginComponent } from './views/login/login.component'; import { PerfilComponent } from './views/perfil/perfil.component'; import { RankingsComponent } from './views/rankings/rankings.component'; import { RegistroComponent } from './views/registro/registro.component'; import { TiendaComponent } from './views/tienda/tienda.component'; const routes: Routes = [ /* { path: '', redirectTo: '/home', pathMatch: 'full' }, */ {path: '', component: HomeComponent}, {path: 'home', component: HomeComponent}, {path: 'perfil', component: PerfilComponent}, {path: 'login', component: LoginComponent}, {path: 'registro', component: RegistroComponent}, {path: 'tienda', component: TiendaComponent}, {path: 'rankings', component: RankingsComponent}, {path: 'amigos', component: AmigosComponent}, {path: 'comunidad', component: ComunidadComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrService } from 'ngx-toastr'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; import { FriendsService } from 'src/app/services/friends.service'; import { RankingsService } from 'src/app/services/rankings.service'; import { UserComponent } from '../user/user.component'; @Component({ selector: 'app-comunidad', templateUrl: './comunidad.component.html', styleUrls: ['./comunidad.component.scss'] }) export class ComunidadComponent implements OnInit { palabraBuscar: string = ''; constructor(public friendService: FriendsService, public chat: ChatService, public auth: AuthService, public toastr: ToastrService, public rankings: RankingsService, public ngmodal: NgbModal) { // Has recargado... cargar de nuevo amigos y mensajes asociados, peticiones de amistad if (this.auth.loginRecharge) { this.auth.setRechargeFalse(); this.rankings.getPositionRankings(); this.rankings.getPositionRankingCoins(); this.auth.getUser(); this.auth.getItemsUser(1); this.chat.getFriends(); this.chat.closeChat(); this.friendService.listenFriendsRequests(); this.friendService.listenSentFriendsRequests(); } } ngOnInit(): void { } ngAfterViewInit() { document.getElementById('buscarAmigoAgregar') .addEventListener('change', this.updateValue.bind(this)); } updateValue(e) { this.palabraBuscar = e.target.value; this.friendService.searchFriends(e.target.value); } openProfileUser(user: any) { this.auth.getItemsUser(2, user.uid); const modalRef = this.ngmodal.open(UserComponent, { size: 'lg' }); modalRef.componentInstance.user = user; modalRef.componentInstance.addUser = 'search'; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ToastrService } from 'ngx-toastr'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; import { FriendsService } from 'src/app/services/friends.service'; import { RankingsService } from 'src/app/services/rankings.service'; import { ShopService } from 'src/app/services/shop.service'; import { environment } from 'src/environments/environment'; @Component({ selector: 'app-tienda', templateUrl: './tienda.component.html', styleUrls: ['./tienda.component.scss'] }) export class TiendaComponent implements OnInit { userAuth: any | null; constructor(public auth: AuthService, public friendService: FriendsService, public chat: ChatService, public shop: ShopService, public rankings: RankingsService, public toastr: ToastrService) { this.getUser(); if (this.auth.loginRecharge && this.userAuth != null) { this.rankings.getPositionRankings(); this.rankings.getPositionRankingCoins(); this.auth.setRechargeFalse(); this.auth.getUser(); this.auth.getItemsUser(1); this.chat.getFriends(); this.chat.closeChat(); this.friendService.listenFriendsRequests(); this.friendService.listenSentFriendsRequests(); } this.shop.getItems(); } ngOnInit(): void {} getUser() { this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); } /** * Comprar item * @param item */ buyItem(item: any) { var canBuy; canBuy = this.shop.checkItem(item); if (canBuy) { // Confirmación comprar this.shop.buyItem(item); } else { this.toastr.warning(`No tienes suficientes monedas para comprar ${item.name}`); } } } <file_sep><div class="container margin-header pt-3"> <div class="text-center"> <h1 class="text-white">Tienda Survivor</h1> <h3 *ngIf="auth.user" class="text-light">Saldo: {{auth.user.coins}} <img class="mb-2" src="../../../assets/imgs/coin.png" alt="" width="20px"> </h3> </div> <div class="row"> <div class="col-lg-4 col-md-6 col-12" *ngFor="let item of shop.items"> <!--Objeto tienda--> <div class="card mt-4 w-100 bg-success text-white" style="width: 18rem; "> <!--Imagen arma--> <div class="img-hover-zoom"> <img class="h-100 card-img-top" src="{{item.img}}" alt="{{item.name}}"> </div> <div class="card-body"> <!--Información arma--> <h5 class="card-title d-flex"> {{item.name}} <div class="card-text ml-2 "> - {{item.price}} <img *ngIf="item.available" class="" src="../../../assets/imgs/coin.png" alt="" width="15px" height="15px"> <span *ngIf="!item.available">€</span> </div> </h5> <p class="card-text text-light">{{item.description}}</p> <!--Si el usuario ha iniciado sesión--> <ng-container *ngIf="auth.user"> <!--Comprar arma o arma ya obtenida--> <div class="float-right"> <ng-container *ngIf="item.available"> <div *ngIf="item.owned" class="mt-2 enpropiedad"> En propiedad </div> <button *ngIf="!item.owned" (click)="buyItem(item)" class="btn btn-primary"> Comprar </button> </ng-container> <div *ngIf="!item.available" class="mt-2 text-white"> Próximamente... </div> </div> </ng-container> </div> </div> </div> </div> </div><file_sep>@media only screen and (max-width:988px) { #videogame { height: 500px !important; margin-top: 15vh; } #trailer { width: 470px; } }<file_sep>import { Injectable } from '@angular/core'; import firebase from 'firebase/app'; import { environment } from 'src/environments/environment'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class RankingsService { getRankings: boolean = true; rankingCoins = []; lvlRankings = []; logedUserRankings = []; unsubscribeListeners = []; userAuth: any | null; logedUserRankingCoins = []; top = 7; constructor(private http: HttpClient) { } /** * Obtiene el usuario almacenado en localStorage, el cual se almacena al iniciar sesión */ getUser() { this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); } /** * Establecer false variable para obtener rankings */ setGetRankingsFalse() { this.getRankings = false; } /** * Establecer a true variable para obtener rankings */ setGetRankingsTrue() { this.getRankings = true; } //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ /** * Obtener rankings de monedas */ getRankingCoins() { console.log('Cargar ranking coins...'); this.rankingCoins = []; this.getUser(); var query = firebase.firestore().collection('users') .orderBy('coins', 'desc') .limit(this.top) var unsubscribe = query.onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { // Monedas han cambiado if (change.type === 'modified') { // Modificar en el array el valor this.rankingCoins.forEach(user => { if (user.uid == change.doc.id) { user.coins = change.doc.data().coins; } }); // Re ordenar array por nº de monedas this.rankingCoins.sort(function (o1, o2) { if (o1.coins < o2.coins) { return 1; } else if (o1.coins > o2.coins) { return -1; } return 0; }); } // Cargar ususario else if (change.type == 'added') { // Hay cambios en el podium monedas if (this.rankingCoins.length == this.top) { this.podiumCoinsChanges(); } // Cargar usuario else { const user = { 'uid': change.doc.id, 'displayName': change.doc.data().displayName, 'email': change.doc.data().email, 'photoURL': change.doc.data().photoURL, 'coins': change.doc.data().coins, 'me': false } this.rankingCoins.push(user); if (this.userAuth != undefined) { if (change.doc.id == this.userAuth.uid) { user.me = true; } } } } }); }); this.unsubscribeListeners.push(unsubscribe); } /** * Cambios en el podium de monedas -> reordenar usuarios */ podiumCoinsChanges() { this.getUser(); var uid; if (this.userAuth == undefined || this.userAuth == null) { uid = null; } else { uid = this.userAuth.uid; } const url = `${environment.dirBack}getPodiumCoins/${uid}`; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); this.http.get(url, { headers: headers }) .subscribe( (response) => { this.rankingCoins = response['message']; }); } /** * Obtener posicion del usuario logeado en ranking monedas */ getPositionRankingCoins() { this.getUser(); this.logedUserRankingCoins = []; var query = firebase.firestore().collection('users').orderBy('coins', 'desc') query.onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { // Obtener pos del usuario logeado if (change.doc.id === this.userAuth.uid) { var cont = 1; query.get() .then(doc => { doc.forEach(docU => { if (docU.id == change.doc.id) { this.logedUserRankingCoins[0] = cont; this.logedUserRankingCoins[1] = docU.data().coins; } cont++; }); }); } }); }); } //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ /** * Obtener rankings de todos los niveles */ getRankingsLevels() { this.lvlRankings = []; this.getUser(); const url = `${environment.dirBack}getLevelRankings`; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); this.http.get(url, { headers: headers }) .subscribe( (response) => { this.lvlRankings = response['message']; // Ponemos en escucha los rankings de los niveles disponibles this.lvlRankings.forEach(level => { // QUERY var query = firebase.firestore().collection('rankings').doc(level.id).collection('users') .limit(this.top) // PUNTUACION this.listenPunctuationRanking(query, level); // ENEMIGOS this.listenEnemiesRanking(query, level); // TIEMPO this.listenTimeRanking(query, level); console.log(this.lvlRankings); }); }); } /** * Escucha del ranking (top) de los stats de puntuacion de un nivel * @param query * @param level */ listenPunctuationRanking(query, level) { var unsubscribe = query.orderBy('punctuation', 'desc') .onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { // Datos modificados del usuario if (change.type === 'modified') { // Update puntuacion this.lvlRankings[level.Nivel - 1].RankingPuntuacion.forEach(user => { if (user.uid == change.doc.id) { user.punctuation = change.doc.data().punctuation; } }); } // Cargar ususario puntuacion else if (change.type == 'added') { // Cambios podium puntuacion if (this.lvlRankings[level.Nivel - 1].RankingPuntuacion.length == this.top) { this.podiumLevelsChanges(level, 1); } // Cargar usuario else { this.searchInfoUser(change.doc, level, 1); } } // Re-Ordenar ranking puntuacion this.lvlRankings[level.Nivel - 1].RankingPuntuacion.sort(function (o1, o2) { if (o1.punctuation < o2.punctuation) { return 1; } else if (o1.punctuation > o2.punctuation) { return -1; } return 0; }); }); }); this.unsubscribeListeners.push(unsubscribe); } /** * Escucha del ranking (top) de los stats de enemigos matados de un nivel * @param query * @param level */ listenEnemiesRanking(query, level) { var unsubscribe = query.orderBy('enemiesKilled', 'desc') .onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { if (change.type === 'modified') { // Update Enemigos matados this.lvlRankings[level.Nivel - 1].RankingEnemigos.forEach(user => { if (user.uid == change.doc.id) { user.enemiesKilled = change.doc.data().enemiesKilled; } }); } // Cargar ususario enemigos else if (change.type == 'added') { // Cambios podium enemigos if (this.lvlRankings[level.Nivel - 1].RankingEnemigos.length == this.top) { this.podiumLevelsChanges(level, 2); } // Cargar usuario else { this.searchInfoUser(change.doc, level, 2); } } // Re-Ordenar ranking enemigos this.lvlRankings[level.Nivel - 1].RankingEnemigos.sort(function (o1, o2) { if (o1.enemiesKilled < o2.enemiesKilled) { return 1; } else if (o1.enemiesKilled > o2.enemiesKilled) { return -1; } return 0; }); }); }); this.unsubscribeListeners.push(unsubscribe); } /** * Escucha del ranking (top) de los stats de tiempo sobrevivido de un nivel * @param query * @param level */ listenTimeRanking(query, level) { var unsubscribe = query.orderBy('time', 'desc') .onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { if (change.type === 'modified') { // Update Tiempo aguantado this.lvlRankings[level.Nivel - 1].RankingTiempo.forEach(user => { if (user.uid == change.doc.id) { user.time = change.doc.data().time; } }); } // Cargar ususario tiempo else if (change.type == 'added') { // Cambios podium tiempo if (this.lvlRankings[level.Nivel - 1].RankingTiempo.length == this.top) { this.podiumLevelsChanges(level, 3); } // Cargar usuario else { this.searchInfoUser(change.doc, level, 3); } } // Re-Ordenar ranking tiempo this.lvlRankings[level.Nivel - 1].RankingTiempo.sort(function (o1, o2) { if (o1.time < o2.time) { return 1; } else if (o1.time > o2.time) { return -1; } return 0; }); }); }); this.unsubscribeListeners.push(unsubscribe); } /** * Crea usuario con todos sus datos * @param userD infor usuario * @param doc pos array niveles * @param type 1: puntuacion / 2: enemigos / 3: tiempo */ searchInfoUser(userD: any, level: any, type: number) { var uid = userD.id.trim(); const user = { 'uid': uid, 'enemiesKilled': userD.data().enemiesKilled, 'punctuation': userD.data().punctuation, 'time': userD.data().time, 'photoURL': '', 'displayName': '', 'coins': '', 'email': '', 'me': false } if (type == 1) { this.lvlRankings[level.Nivel - 1].RankingPuntuacion.push(user); } else if (type == 2) { this.lvlRankings[level.Nivel - 1].RankingEnemigos.push(user); } else if (type == 3) { this.lvlRankings[level.Nivel - 1].RankingTiempo.push(user); } // Buscar información del usuario para buscar su nombre, foto de perfil... const url = `${environment.dirBack}getUser/${userD.id}`; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); this.http.get(url, { headers: headers }) .subscribe( (response) => { user.photoURL = response['message'].photoURL; user.displayName = response['message'].displayName; user.coins = response['message'].coins; user.email = response['message'].email; if (this.userAuth != undefined) { if (userD.id == this.userAuth.uid) { user.me = true; } } }); } /** * El podium de algun nivel ha cambiado, se reobtienen las posiciones * @param doc pos array niveles * @param type 1: puntuacion / 2: enemigos / 3: tiempo */ podiumLevelsChanges(level: any, type: number) { // QUERY var query = firebase.firestore().collection('rankings').doc(level.id).collection('users') .limit(this.top) var orderBy = ''; if (type == 1) { this.lvlRankings[level.Nivel - 1].RankingPuntuacion = []; orderBy = 'punctuation'; } else if (type == 2) { this.lvlRankings[level.Nivel - 1].RankingEnemigos = []; orderBy = 'enemiesKilled'; } else if (type == 3) { this.lvlRankings[level.Nivel - 1].RankingTiempo = []; orderBy = 'time'; } query.orderBy(orderBy, 'desc').get() .then(docUser => { docUser.forEach(docU => { this.searchInfoUser(docU, level, type); }); }); } /** * Obtener posicion del usuario logeado en todos los rankings */ getPositionRankings() { this.logedUserRankings = []; this.getUser(); const url = `${environment.dirBack}getLevelRankings`; let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); this.http.get(url, { headers: headers }) .subscribe( (response) => { this.logedUserRankings = response['message']; this.logedUserRankings.forEach(level => { // QUERY var query = firebase.firestore().collection('rankings').doc(level.id).collection('users'); this.listenPunctuationGlobal(query, level); this.listenEnemiesGlobal(query, level); this.listenTimeGlobal(query, level); console.log(this.logedUserRankings); }); }); } /** * Escucha de todos los usuarios de los stats de puntuacion de un nivel * @param query * @param level */ listenPunctuationGlobal(query, level) { query.orderBy('punctuation', 'desc') .onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { // Obtener pos del usuario logeado if (change.doc.id == this.userAuth.uid) { var cont = 1; query.orderBy('punctuation', 'desc').get() .then(docUser => { docUser.forEach(docU => { if (docU.id == change.doc.id) { this.logedUserRankings[level.Nivel - 1].RankingPuntuacion[0] = cont; } cont++; }); }); this.logedUserRankings[level.Nivel - 1].RankingPuntuacion[1] = change.doc.data().punctuation; } }); }); } /** * Escucha de todos los usuarios de los stats de enemigos matados de un nivel * @param query * @param level */ listenEnemiesGlobal(query, level) { query.orderBy('enemiesKilled', 'desc') .onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { // Obtener pos del usuario logeado if (change.doc.id == this.userAuth.uid) { var cont = 1; query.orderBy('enemiesKilled', 'desc').get() .then(docUser => { docUser.forEach(docU => { if (docU.id == change.doc.id) { this.logedUserRankings[level.Nivel - 1].RankingEnemigos[0] = cont; } cont++; }); }); this.logedUserRankings[level.Nivel - 1].RankingEnemigos[1] = change.doc.data().enemiesKilled; } }); }); } /** * Escucha de todos los usuarios de los stats de tiempo sobrevivido de un nivel * @param query * @param level */ listenTimeGlobal(query, level) { query.orderBy('time', 'desc') .onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { // Obtener pos del usuario logeado if (change.doc.id == this.userAuth.uid) { var cont = 1; query.orderBy('time', 'desc').get() .then(docUser => { docUser.forEach(docU => { if (docU.id == change.doc.id) { this.logedUserRankings[level.Nivel - 1].RankingTiempo[0] = cont; } cont++; }); }); this.logedUserRankings[level.Nivel - 1].RankingTiempo[1] = change.doc.data().time; } }); }); } /** * Dejar de escuchar los listeners para que no haya duplicidad de escucha */ stopListeningRankingsItems() { this.unsubscribeListeners.forEach(unsubscribe => { unsubscribe(); }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; import { FriendsService } from 'src/app/services/friends.service'; import { PerfilService } from 'src/app/services/perfil.service'; import { RankingsService } from 'src/app/services/rankings.service'; import { environment } from 'src/environments/environment'; @Component({ selector: 'app-rankings', templateUrl: './rankings.component.html', styleUrls: ['./rankings.component.scss'] }) export class RankingsComponent implements OnInit { userAuth: any | null; rankingMonedas: boolean = true; stats: number = 0; ranking: any; constructor(public auth: AuthService, public perfilService: PerfilService, public friendService: FriendsService, public chat: ChatService, public rankings: RankingsService) { this.getUser(); if (this.rankings.getRankings == true) { this.rankings.setGetRankingsFalse(); this.rankings.getRankingCoins(); this.rankings.getRankingsLevels(); } if (this.auth.loginRecharge && this.userAuth != null) { this.rankings.getPositionRankings(); this.rankings.getPositionRankingCoins(); this.auth.setRechargeFalse(); this.auth.getUser(); this.auth.getItemsUser(1); this.chat.getFriends(); this.chat.closeChat(); this.friendService.listenFriendsRequests(); this.friendService.listenSentFriendsRequests(); } } ngOnInit(): void { } getUser() { this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); } onChange(value: any) { if (value == 0) { this.rankingMonedas = true; } else { this.rankingMonedas = false; } this.rankings.lvlRankings.forEach(ranking => { if (value == ranking.Nivel) { this.ranking = ranking; } }); } onChangeStats(value: any) { if (value == 0) { this.stats = 0; } else if (value == 1) { this.stats = 1; } else { this.stats = 2; } } }<file_sep>import { Component, Input, OnInit } from '@angular/core'; import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; import { FriendsService } from 'src/app/services/friends.service'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.scss'] }) export class UserComponent implements OnInit { @Input() public user: any; @Input() public addUser: string; @Input() public msgs: string; profile: boolean = true; constructor( public ngmodal: NgbModal, public activeModal: NgbActiveModal, public friendService: FriendsService, public chat: ChatService, public auth: AuthService) { } ngOnInit(): void { } /** * Eliminar amigo * @param uid */ deleteFriend(uid: string) { this.friendService.deleteFriend(uid); this.activeModal.close(); } /** * Gestión peticiones de amistad * @param uid * @param type * 1: aceptar solicitud de amistad, * 2: denegar solicitud de amistad, * 3: enviar solicitud de amistad, * 4: cancelar envio solicitud de amistad */ friendRequest(uid: string, type: number) { if (type == 1) { this.friendService.acceptFriendRequest(uid); } else if (type == 2) { this.friendService.deleteFriendRequest(uid); } else if (type == 3) { this.friendService.sendFriendRequest(uid); } else if (type == 4) { this.friendService.cancelFriendRequest(uid); } this.activeModal.close(); } seePhotos() { this.profile = false; } seeProfile() { this.profile = true; } } <file_sep>//$fondo-chat: #275757; $fondo-chat: #21252e; $header-input: rgba(0,0,0,0.3); $mymsg: #F5F5F5; $othermsg: #82ccdd; $online:#4caf50; $offline:#f44336; .h-70 { height: 70vh; } .mat-menu-item .mat-icon-no-color, .mat-menu-item-submenu-trigger::after { color: #a5a5a5; } .circulo { height:10px; width:10px; border-radius:50px; } .badge { font-size: 12px; border-radius: 25px; padding: 6px 8px; background-color: #ac3027; } .circuloChat { padding-top: 25px; padding-left: 25px; height:100px; width:100px; border-radius:100px; mat-icon { font-size: 50px; } } .noFriends { height: 230px; mat-icon { font-size: 50px; } } .green { background: $online; } .border-green { border: 2px solid $online; } .red { background: $offline; } .border-red { border: 2px solid $offline; } .menuOP:hover { background: $fondo-chat; } .column-friends { max-height: 77vh; overflow-y: auto; .friendSelected { background: $fondo-chat; } .friend-description { color: white; padding: 10px 15px; display: flex; align-items: center; vertical-align: baseline; justify-content: center; transition: .3s ease; border-bottom: 1.5px solid $fondo-chat; img { width: 60px; height: 60px; border-radius: 40px; } .text { width: 80%; span { font-size: 20px; margin-left: 20px; } div span { font-size: 14px; color: rgba(255,255,255,0.6); } } &:hover { background: $fondo-chat; cursor: pointer; } } } .card { max-height: 87vh; min-height: 87vh; border: none; border-radius: 0px; .card-header { background-color: $header-input; position: relative; border-bottom: 0; .user_img { height: 70px; width: 70px; &:hover { cursor: pointer; } } .user_info { margin-top: auto; margin-bottom: auto; margin-left: 15px; & span { font-size: 20px; color: white; } & p { font-size: 12px; color: rgba(255,255,255,0.6); } } } .card-body { overflow-y: auto; .chat-bubble { padding: 10px 14px; margin: 10px 30px; border-radius: 13px; position: relative; animation: fadeIn 1s ease-in; word-break: break-all; &:after { content: ''; position: absolute; top: 50%; width: 0; height: 0; border: 20px solid transparent; border-bottom: 0; margin-top: -10px; } &--left { background-color: $othermsg; .msg_time { min-width: 100px; position: absolute; left: 0; bottom: -19px; color: rgba(255,255,255,0.5); font-size: 12px; } &:after { left: 0; border-right-color: $othermsg; border-left: 0; margin-left: -20px; } } &--right { background-color: $mymsg; .msg_time_send { min-width: 100px; position: absolute; right:0; padding-left: 5px; bottom: -19px; color: rgba(255,255,255,0.5); font-size: 12px; } &:after { right: 0; border-left-color: $mymsg; border-right: 0; margin-right: -20px; } } } } .card-footer { border-radius: 0 0 15px 15px; border-top: 0; .attach_btn { border-radius: 15px 0 0 15px; background-color: $header-input; border:0; color: white; cursor: pointer; } .type_msg { background-color: $header-input; border:0 ; color:white; height: 60px; overflow-y: auto; &:focus{ box-shadow:none; outline:0px; } } .send_btn { border-radius: 0 15px 15px 0; background-color: $header-input; border:0 ; color: white; cursor: pointer; } } } img { align-self: center; } .img-chat { width: 400px; height: 300px; } @media only screen and (min-width:0px) and (max-width: 773px) { .display-none, .chat-bubble--left:after, .chat-bubble--right:after { display: none; } .img-chat { width: 280px; height: 260px; } .chat-bubble.chat-bubble--right.ml-auto, .chat-bubble.chat-bubble--left.mr-auto { margin: 0px; } .chat-bubble.chat-bubble--left.img-class,.chat-bubble.chat-bubble--right.img-class { background-color: transparent; padding: 0; img { border-radius: 20px; } } } @media only screen and (min-width:773px) and (max-width: 1179px) { .img-chat { width: 280px; height: 260px; } } @media only screen and (min-width:773px) { .noneSearch100 { display: none; } }<file_sep>import { FiltroAmigosPipe } from './filtro-amigos.pipe'; describe('FiltroAmigosPipe', () => { it('create an instance', () => { const pipe = new FiltroAmigosPipe(); expect(pipe).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ToastrService } from 'ngx-toastr'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; import { FriendsService } from 'src/app/services/friends.service'; import { PerfilService } from 'src/app/services/perfil.service'; import { RankingsService } from 'src/app/services/rankings.service'; @Component({ selector: 'app-perfil', templateUrl: './perfil.component.html', styleUrls: ['./perfil.component.scss'] }) export class PerfilComponent implements OnInit { msg: string = null; name: FormGroup; email: FormGroup; pass: FormGroup; enabledName: boolean = false; enabledEmail: boolean = false; enabledPass: boolean = false; hide1 = true; hide2 = true; constructor(public auth: AuthService, public perfilService: PerfilService, public toastr: ToastrService, public chat: ChatService, public friendService: FriendsService, private formBuilder: FormBuilder, private rankings: RankingsService) { this.name = this.formBuilder.group({ name: ['', [Validators.required, Validators.minLength(3)]] }); this.email = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]] }); this.pass = this.formBuilder.group({ password: ['', [Validators.required, Validators.minLength(6)]], confirmPassword: ['', [Validators.required, Validators.pattern]] }); this.auth.getProviderID(); // Has recargado... cargar de nuevo amigos y mensajes asociados, peticiones de amistad if (this.auth.loginRecharge) { this.rankings.getPositionRankings(); this.rankings.getPositionRankingCoins(); this.auth.setRechargeFalse(); this.auth.getUser(); this.auth.getItemsUser(1); this.chat.getFriends(); this.chat.closeChat(); this.friendService.listenFriendsRequests(); this.friendService.listenSentFriendsRequests(); } } ngOnInit(): void { } get formName() { return this.name.controls; } get formEmail() { return this.email.controls; } get formPass() { return this.pass.controls; } /** * Submit formulario cambiar nombre * @returns */ updateName() { if (this.name.invalid) { return; } this.enableDisableUpdateName(2); this.perfilService.updateDisplayName(this.name.value.name); this.name.reset(); } /** * Submit formulario cambiar email * @returns */ updateEmail() { if (this.email.invalid) { return; } this.perfilService.updateEmail(this.email.value.email) .subscribe( (response) => { console.log('RESPONSE', response); this.toastr.success(`Correo electrónico actualizado`); this.auth.setEmail(this.email.value.email); this.enableDisableUpdateEmail(2); this.email.reset(); }, (error) => { var code = error['error']['message'].code; if (code === 'auth/requires-recent-login') { this.msg = 'Debes relogearte para poder cambiar el email.'; } else if (code === 'auth/email-already-in-use') { this.msg = 'El email introducido ya está registrado'; } }); } /** * Submit formulario cambiar contraseña * @returns */ updatePass() { if (this.pass.invalid) { return; } this.perfilService.updatePass(this.pass.value.password) .subscribe( (response) => { console.log('RESPONSE', response); this.toastr.success(`Contraseña actualizada`); this.enableDisableUpdatePass(2); this.pass.reset(); }, (error) => { console.log('Ha ocurrido un error actualizando la contraseña', error); }); } /** * Activar o desactivar cambiar nombre * @param type 1: Activar | 2: Desactivar */ enableDisableUpdateName(type: number) { if (type == 1) { this.enabledName = true; this.enabledPass = false; this.enabledEmail = false; } else { this.enabledName = false; } } /** * Activar o desactivar cambiar email * @param type 1: Activar | 2: Desactivar */ enableDisableUpdateEmail(type: number) { if (type == 1) { this.enabledEmail = true; this.enabledPass = false; this.enabledName = false; } else { this.enabledEmail = false; this.msg = ''; } } /** * Activar o desactivar cambiar contraseña * @param type 1: Activar | 2: Desactivar */ enableDisableUpdatePass(type: number) { if (type == 1) { this.enabledPass = true; this.enabledEmail = false; this.enabledName = false; } else { this.enabledPass = false; this.msg = ''; } } openFileSelection() { document.getElementById('file').click(); } } <file_sep>echo '*********************************************************' echo '********************BUILDING IMAGE***********************' echo '*********************************************************' docker build -t meryjv00/angular_alpine:0.0.1 . echo '*********************************************************' echo '*******************STARTING CONTAINER********************' echo '*********************************************************' docker run -d --name PFG-Survivor -p 4200:4200 meryjv00/angular_alpine:0.0.1 # DESARROLLO # -v $(pwd):/PFG-Survivor echo '**********************************************************' echo '********************APP READY*****************************' echo '******************LOCALHOST:4200**************************' echo '**********************************************************' # Volver a reejecutar docker aparece este error: 'can't stat '/home/maria/Escritorio/PFG-Survivor/.config'' # Ejecutar: # sudo rm -rf .config # sudo rm -rf .npm # sudo rm -rf node_modules # Volver a lanzar init.sh <file_sep>import { Component, OnInit, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { Subscription } from 'rxjs'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; import { FriendsService } from 'src/app/services/friends.service'; import { RankingsService } from 'src/app/services/rankings.service'; import { ConfirmModalComponent } from '../confirm-modal/confirm-modal.component'; import { UserComponent } from '../user/user.component'; @Component({ selector: 'app-amigos', templateUrl: './amigos.component.html', styleUrls: ['./amigos.component.scss'] }) export class AmigosComponent implements OnInit { chatFriends: FormGroup; @ViewChild('scrollMe') private myScrollContainer: ElementRef; disableScrollDown = false; urlImg = ''; filtroAmigo = ''; // En esucha si se envian nuevos mensajes para que el scroll baje automáticamente @Output() onComplete = new EventEmitter(); countdownEndRef: Subscription = null; constructor(public chat: ChatService, private formBuilder: FormBuilder, public auth: AuthService, public friends: FriendsService, public rankings: RankingsService, public ngmodal: NgbModal) { this.chatFriends = this.formBuilder.group({ text: ['', [Validators.required]], }); // Has recargado... cargar de nuevo amigos y mensajes asociados, peticiones de amistad if (this.auth.loginRecharge) { this.auth.getUser(); this.rankings.getPositionRankings(); this.rankings.getPositionRankingCoins(); this.auth.setRechargeFalse(); this.auth.getItemsUser(1); this.chat.getFriends(); this.chat.closeChat(); this.friends.listenFriendsRequests(); this.friends.listenSentFriendsRequests(); } } get formChat() { return this.chatFriends.controls; } ngOnInit(): void { this.countdownEndRef = this.chat.countdownEnd$.subscribe(() => { this.onComplete.emit(); this.disableScrollDown = false; }); } ngOnDestroy() { this.chat.urlImgsChat = []; } ngAfterViewChecked() { this.scrollToBottom(); } onScroll() { let element = this.myScrollContainer.nativeElement let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight if (this.disableScrollDown && atBottom) { this.disableScrollDown = false } else { this.disableScrollDown = true } } scrollToBottom(): void { if (this.disableScrollDown) { return } try { this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; } catch (err) { } } onSubmit() { if (this.chatFriends.invalid) { return; } this.chat.sendMessageFriend(); } openFileSelection() { document.getElementById('file').click(); } chatWith(friend) { this.disableScrollDown = false; this.chat.chatWith(friend); } enableScollDown() { this.disableScrollDown = false; } saveImgModal(urlImg: string) { this.urlImg = urlImg; } openProfileUser(user: any) { this.chat.getImagenesChat() .subscribe( (response) => { console.log(response['message']); this.chat.urlImgsChat = response['message']; const modalRef = this.ngmodal.open(UserComponent, { size: 'lg' }); modalRef.componentInstance.user = user; modalRef.componentInstance.addUser = 'see'; modalRef.componentInstance.msgs = this.chat.messagesWithFriend.length; }, (error) => { console.log(error); } ); } openConfirmModal() { const modalRef = this.ngmodal.open(ConfirmModalComponent, { size: 'xs' }); modalRef.componentInstance.msg = `Eliminar archivos multimedia con ${this.chat.friendSelected.displayName}`; modalRef.componentInstance["confirm"].subscribe((event: any) => { this.chat.deleteChat(event); }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AuthService } from '../services/auth.service'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { LoginComponent } from '../views/login/login.component'; import { RegistroComponent } from '../views/registro/registro.component'; import { ChatService } from '../services/chat.service'; import { FriendsService } from '../services/friends.service'; import { UserComponent } from '../views/user/user.component'; @Component({ selector: 'app-menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.scss'] }) export class MenuComponent implements OnInit { pathLogo: string = '../../../assets/imgs/logo.png'; constructor(public auth: AuthService, public ngmodal: NgbModal, public friendService: FriendsService, public chat: ChatService) { } ngOnInit(): void { } openLogin() { this.ngmodal.open(LoginComponent, { size: 'md' }); } openRegistro() { this.ngmodal.open(RegistroComponent, { size: 'md' }); } openProfileUser(user: any) { this.auth.getItemsUser(2, user.uid); const modalRef = this.ngmodal.open(UserComponent, { size: 'lg' }); modalRef.componentInstance.user = user; modalRef.componentInstance.addUser = 'add'; } } <file_sep>import { Injectable } from '@angular/core'; import { AngularFireStorage } from '@angular/fire/storage'; import firebase from 'firebase/app'; import 'firebase/firestore'; import { Subject } from 'rxjs'; import { environment } from 'src/environments/environment'; import { ChatService } from './chat.service'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class FriendsService { userAuth: any | null; users = []; // Recoge los usuarios friendsRequests = []; sentFriendsRequests = []; listeningItems = []; newFriendInfo: any = ''; tokenUser: string = ''; private newFriend = new Subject<void>(); public newFriend$ = this.newFriend.asObservable(); constructor(public firestorage: AngularFireStorage, public chat: ChatService, private http: HttpClient) { } /** * Obtiene el usuario almacenado en localStorage, el cual se almacena al iniciar sesión */ getUser() { this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); this.tokenUser = this.userAuth['stsTokenManager']['accessToken']; } /** * Vacía el array users (usuarios obtenidos del buscador de amigos) */ resetSearchFriends() { this.users = []; } /** * Búsqueda de nuevos amigos * @param value */ searchFriends(value: string) { this.getUser(); this.resetSearchFriends(); if (value.length >= 1) { const url = environment.dirBack + "getUsers/" + value + "/" + this.userAuth.uid; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.get(url, { headers: headers }) .subscribe( (response) => { this.users = response['message']; this.users.forEach(user => { // Comprobar si ya está entre mis amigos this.chat.friends.forEach(friend => { if (user.uid == friend.uid) { // Usuario encontrado ya está en mi lista de amigos user.relation = 'friends'; } }); // Comprobar si ya le he enviado solicitud this.sentFriendsRequests.forEach(friend => { if (user.uid == friend.uid) { // Usuario encontrado ya ha sido enviada una solicitud user.relation = 'sentRequest'; } }); }); }); } } /** * Envía solicitud de amistad al usuario seleccionado * @param uid */ sendFriendRequest(uid: string) { this.getUser(); const url = `${environment.dirBack}sendFriendRequest/${this.userAuth.uid}/${uid}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.put(url, { headers: headers }) .subscribe( (response) => { console.log('Response:', response); // Actualizar relación: solicitud enviada this.users.forEach(friend => { if (friend.uid == uid) { friend.relation = 'sentRequest'; } }); // Eliminar de amigos sugeridos this.chat.suggestedFriends.forEach((friendSuggested, index) => { if (friendSuggested.uid == uid) { this.chat.suggestedFriends.splice(index, 1); } }); }); } /** * Eliminar amigo, es decir, dejar de ser amigos * @param uid */ deleteFriend(uid: string) { this.getUser(); const url = `${environment.dirBack}deleteFriend/${this.userAuth.uid}/${uid}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.delete(url, { headers: headers }) .subscribe( (response) => { console.log('Response:', response); }); } /** * Aceptar solicitud de amistad -> os convertis en amigos * @param uid */ acceptFriendRequest(uid: string) { this.getUser(); const url = `${environment.dirBack}acceptFriendRequest/${this.userAuth.uid}/${uid}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.put(url, { headers: headers }) .subscribe( (response) => { console.log('Response:', response); this.sentFriendsRequests.forEach(sentFriend => { if (sentFriend.uid == uid) { this.deleteRequests(uid,this.userAuth.uid).subscribe(() => {}); } }); // Eliminar de amigos sugeridos this.chat.suggestedFriends.forEach((friendSuggested, index) => { if (friendSuggested.uid == uid) { this.chat.suggestedFriends.splice(index, 1); } }); this.deleteFriendRequest(uid); }); } /** * Rechazar solicitud de amistad * @param uid */ deleteFriendRequest(uid: string) { this.getUser(); this.deleteRequests(this.userAuth.uid,uid) .subscribe( (response) => { console.log('Response:', response); this.friendsRequests.forEach((friend, index) => { if (friend.uid == uid) { this.friendsRequests.splice(index, 1); } }); }); } deleteRequests(uidUser, uidFriend) { const url = `${environment.dirBack}deleteFriendRequest/${uidUser}/${uidFriend}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.delete(url, { headers: headers }) } /** * Cancelar envío de la solicitud de amistad * @param uid */ cancelFriendRequest(uid: string) { this.deleteRequests(uid, this.userAuth.uid) .subscribe( (response) => { console.log('Response:', response); this.sentFriendsRequests.forEach((friend, index) => { if (friend.uid == uid) { this.sentFriendsRequests.splice(index, 1); } }); this.users.forEach(friend => { if (friend.uid == uid) { friend.relation = 'unknown'; } }); }); } /** * Pone en escucha las peticiones de amistad que te envian */ listenFriendsRequests() { var db = firebase.firestore(); this.friendsRequests = []; this.getUser(); var query = db.collection('users').doc(this.userAuth.uid).collection('friendsRequests') var unsubscribe = query.onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { // Peticion de amistad borrada if (change.type === 'removed') { this.friendsRequests.forEach((friend, index) => { if (friend.uid == change.doc.id) { this.friendsRequests.splice(index, 1); } }); this.friendRequestDeleted(change); } // Peticion de amistad recogida else { if (change.doc.id != this.userAuth.uid) { this.loadFriendRequest(change, 1); } } }); //console.log('Solicitudes de amistad', this.friendsRequests); }); this.listeningItems.push(unsubscribe); } /** * Pone en escucha las peticiones de amistad que he enviado */ listenSentFriendsRequests() { var db = firebase.firestore(); this.sentFriendsRequests = []; this.getUser(); var query = db.collection('users').doc(this.userAuth.uid).collection('sentFriendsRequests') var unsubscribe = query.onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { // Peticion de amistad enviada borrada if (change.type === 'removed') { this.sentFriendsRequests.forEach((friend, index) => { if (friend.uid == change.doc.id) { this.sentFriendsRequests.splice(index, 1); } }); this.friendRequestDeleted(change); } // Peticion de amistad enviada recogida else { if (change.doc.id != this.userAuth.uid) { this.loadFriendRequest(change, 2); } } }); //console.log('Solicitudes de amistad enviadas', this.sentFriendsRequests); }); this.listeningItems.push(unsubscribe); } /** * Solicitud de amistad borrada, puede haberla rechazado o denegado. * Comprobaremos si ahora somos amigos * @param change */ friendRequestDeleted(change: any) { var encontrado = false; const url = `${environment.dirBack}getFriendsUID/${this.userAuth.uid}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.get(url, { headers: headers }) .subscribe( (response) => { var friendsUID = response['message']; // Buscamos si el usuario está entre los amigos del usuario friendsUID.forEach(user => { if (user.uid == change.doc.id) { encontrado = true; this.newFriendInfo = user.uid; } }); // Evento de nuevo amigo if (encontrado) { const url = `${environment.dirBack}getUser/${this.newFriendInfo}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.get(url, { headers: headers }) .subscribe( (response) => { this.newFriendInfo = response['message'].displayName; console.log('He aceptado solicitud'); this.newFriend.next(); }); } this.users.forEach(friend => { friend.relation = 'unknown'; if (friend.uid == change.doc.id) { if (encontrado) { friend.relation = 'friends'; } } }); }); } /** * Añadir petición de amistad * @param change doc usuario a buscar * @param type 1: peticion de amistad recibida / 2: peticion de amistad enviada */ loadFriendRequest(change: any, type: number) { const url = `${environment.dirBack}getUser/${change.doc.id}`; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.get(url, { headers: headers }) .subscribe( (response) => { const friend = { 'uid': response['message'].uid, 'status': response['message'].status, 'displayName': response['message'].displayName, 'photoURL': response['message'].photoURL, 'email': response['message'].email, 'coins': response['message'].coins, } if (type == 1) { this.friendsRequests.push(friend); this.chat.sonidito(1); } else if (type == 2) { this.sentFriendsRequests.push(friend); } }); } /** * Para de escuchar las peticiones de amistad tantoo las que se envian como las que se reciben. * Este método se llama al cerrar sesión */ stopListeningRequests() { this.listeningItems.forEach(unsubscribe => { unsubscribe(); }); } } <file_sep>import { Component, EventEmitter, Output } from '@angular/core'; import { ToastrService } from 'ngx-toastr'; import { Subscription } from 'rxjs'; import { environment } from 'src/environments/environment'; import { AuthService } from './services/auth.service'; import { ChatService } from './services/chat.service'; import { FriendsService } from './services/friends.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'PFG-Survivor'; userAuth: any | null; @Output() onCompleteFriends = new EventEmitter(); newFriend: Subscription = null; constructor(public friendService: FriendsService, public chat: ChatService, public auth: AuthService, public toastr: ToastrService) { } ngOnInit(): void { this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); // Usuario logeado if (this.userAuth != null) { console.log('INIT APP'); // Marcar como conectado this.chat.setStatusOnOff(1); // Subscribe New Friend -> Alert this.newFriend = this.friendService.newFriend$.subscribe(() => { this.onCompleteFriends.emit(); this.toastr.success('Ahora ' + this.friendService.newFriendInfo + ' y tú sois amigos'); }); // Cierre navegador window.addEventListener("unload", event => { console.log('CIERRE NAVEGADOR'); this.chat.setStatusOnOff(2); this.chat.closeChat(); }); } } } <file_sep># Proyecto Fin de Grado - DAW & DAM - Juega nuestros diferentes niveles 🎮 - Supera tus records 💯 - Sobrevive a los enemigos 👽 - Consigue monedas 💰 - Conoce gente nueva 👬 - Chatea con amigos ⌨️ - Recibe notificaciones 🚨 - Compra objetos 🔫 - Y mucho más 🔥 ``` https://pfg-survivor.netlify.app ``` ``` https://survivorback.herokuapp.com ``` ### Documentación 📰 - KANBAN: https://github.com/meryjv00/PFG-Survivor/projects/1 - WIKI: https://github.com/meryjv00/PFG-Survivor/wiki ### Repositorios 📦 El proyecto consta de tres repositorios: - [FRONTEND SURVIVOR](https://github.com/meryjv00/PFG-Survivor) - (Angular y SASS) - [BACKEND SURVIVOR](https://github.com/meryjv00/PFG-Survivor-Back) - (NodeJS y Firebase) - [VIDEOGAME SURVIVOR](https://github.com/DiegoS3/Survivor) - (Unity) ### Código fuente Videojuego 👨‍💻: [source] ### Videos 📹 - Vídeo explicativo: [video] - Trailer: [trailer] ### Manuales Usuario 📕 - WEB: [ManualWeb] - VIDEOJUEGO: [ManualVideo] ### Despliegue docker 🧱 Requisitos: - Docker y docker compose Para desplegar el entorno de producción siempre y cuando cumplas los requisitos, solo tendrás que ejecutar los scripts (iniciar.sh) de los correspondientes repositorios. En el repositorio del front hay dos scripts con diferentes alternativas, puedes ejecutar el de tu preferencia. ### Planificación tareas 📜 https://trello.com/b/rb3vJOeO/proyecto-fin-de-grado-dam-daw ### Autores 🖋 * **<NAME>** - [meryjv00](https://github.com/meryjv00) * **<NAME>** - [DiegoS3](https://github.com/DiegoS3) [source]: https://drive.google.com/file/d/1osHOYslKC93BuPduVjzo8Q13FT_9kyTs/view?usp=sharing [video]: https://youtu.be/i52JLuK1n9A [trailer]: https://youtu.be/eNcuMn3SGqU [ManualWeb]: https://meryjv00.github.io/PFG-Survivor/ [ManualVideo]: https://diegos3.github.io/Survivor/ <file_sep>import { TestBed } from '@angular/core/testing'; import { AngularFireModule } from '@angular/fire'; import { AngularFireAuthModule } from '@angular/fire/auth'; import { RouterTestingModule } from '@angular/router/testing'; import { environment } from 'src/environments/environment'; import { HomeComponent } from '../views/home/home.component'; import { AuthService } from './auth.service'; import { HttpClientModule } from '@angular/common/http'; describe('AuthService', () => { let service: AuthService; beforeEach(() => { TestBed.configureTestingModule({ imports: [ AngularFireModule.initializeApp(environment.firebaseConfig), AngularFireAuthModule, RouterTestingModule, HttpClientModule, RouterTestingModule.withRoutes([ { path: 'home', component: HomeComponent } ]) ], }); service = TestBed.inject(AuthService); }); it('should be created', () => { expect(service).toBeTruthy(); }); describe('Casos login', () => { it('Login correcto', (done: DoneFn) => { service.emailLogin = '<EMAIL>'; service.passLogin = '<PASSWORD>'; service.login().subscribe( (response) => { var user = response['message']; var code = response['status']; expect(user).not.toBeNull(); expect(code).toBe(200); expect(service.emailLogin).toBe(user.email); done(); }); }); it('Login email incorrecto', (done: DoneFn) => { service.emailLogin = 'kk<PASSWORD> <EMAIL>'; service.passLogin = '<PASSWORD>'; service.login().subscribe( () => { }, (error) => { var code = error['error']['message'].code; expect(code).toBe('auth/user-not-found'); done(); }); }); it('Login pass incorrecta', (done: DoneFn) => { service.emailLogin = '<EMAIL>'; service.passLogin = '<PASSWORD>'; service.login().subscribe( () => { }, (error) => { var code = error['error']['message'].code; expect(code).toBe('auth/wrong-password'); done(); }); }); }); describe('Casos Registro', () => { it('Registro correcto', (done: DoneFn) => { service.emailRegistro = '<EMAIL>'; service.passRegistro = '<PASSWORD>'; service.registro().subscribe( (response) => { var user = response['message']; var code = response['status']; expect(user).not.toBeNull(); expect(code).toBe(200); expect(service.emailRegistro).toBe(user.email); done(); }); }); it('Correo electrónico ya registrado', (done: DoneFn) => { service.emailRegistro = '<EMAIL>'; service.passRegistro = '<PASSWORD>'; service.registro().subscribe( () => { }, (error) => { var code = error['error']['message'].code; expect(code).toBe('auth/email-already-in-use'); done(); }); }); }); }); <file_sep>/* You can add global styles to this file, and also import other style files */ @import 'scss/customTheme.scss'; @import '~bootstrap/scss/bootstrap'; @font-face { font-family: mandali; src: url(assets/fonts/Mandali-Regular.ttf) format("opentype"); }<file_sep>import { Component, Input, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { AuthService } from 'src/app/services/auth.service'; import { RegistroComponent } from '../registro/registro.component'; import { ToastrService } from 'ngx-toastr'; import { PassComponent } from '../pass/pass.component'; import { ChatService } from 'src/app/services/chat.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { // Variables login: FormGroup; hide = true; msg: string = null; @Input() public msgPassword: any; constructor(private formBuilder: FormBuilder, public auth: AuthService, public ngmodal: NgbModal, public activeModal: NgbActiveModal, public toastr: ToastrService, public chat: ChatService) { this.login = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]], password: ['', [Validators.required]] }); } ngOnInit(): void { } get formLogin() { return this.login.controls; } /** * Login con email y contraseña * @returns */ onSubmit() { if (this.login.invalid) { return; } // var btnlog = document.getElementById("btnlogin") as HTMLInputElement; // btnlog.disabled = true; this.auth.login() .subscribe( (response) => { console.log('Login éxito'); var user = response['message']; this.auth.prepareLogin(user); this.toastr.success('Bienvenido/a!'); this.activeModal.close(); }, (error) => { var code = error['error']['message'].code; if (code === 'auth/wrong-password' || code === 'auth/user-not-found') { this.msg = 'No se ha podido iniciar sesión. Revise sus credenciales.'; } else if (code === 'auth/too-many-requests') { this.msg = 'El acceso a esta cuenta se ha desactivado temporalmente debido a muchos intentos fallidos de inicio de sesión. \ Intentalo más tarde o restaura tu contraseña.'; } }); } /** * Login con cuenta de Google */ loginGoogle() { this.auth.loginGoogle() .then(response => { var user = response.user; this.auth.prepareLogin(user); this.toastr.success('Bienvenido/a!'); this.activeModal.close(); }) .catch(error => { console.log("Error al logear con Google: ", error.code); }); } /** * Login con cuenta de Facebook */ loginFacebook() { this.auth.loginFacebook() .then(user => { this.auth.updateProfileFB(user); this.toastr.success('Bienvenido/a!'); this.activeModal.close(); }) .catch(error => { console.log("Error al logear con Facebook: ", error.code); if (error.code === 'auth/account-exists-with-different-credential') { this.msg = 'Ya existe una cuenta con esta dirección de correo electrónico pero con diferentes credenciales de inicio de sesión. \ Intenta iniciar sesión mediante correo electrónico o Google.'; } }); } /** * Cierra modal login y abre modal registro */ openRegistro() { this.activeModal.close(); this.ngmodal.open(RegistroComponent, { size: 'md' }); } /** * Cierra modal login y abre modal contraseña olvidada */ openPassOlvidada() { this.activeModal.close(); this.ngmodal.open(PassComponent, { size: 'lg' }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrService } from 'ngx-toastr'; import { AuthService } from 'src/app/services/auth.service'; import { LoginComponent } from '../login/login.component'; @Component({ selector: 'app-registro', templateUrl: './registro.component.html', styleUrls: ['./registro.component.scss'] }) export class RegistroComponent implements OnInit { // Variables registro: FormGroup; hide1 = true; hide2 = true; msg: string = null; constructor(private formBuilder: FormBuilder, public auth: AuthService, public ngmodal: NgbModal, public activeModal: NgbActiveModal, public toastr: ToastrService) { this.registro = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]], nombre: ['', [Validators.required, Validators.minLength(3)]], password: ['', [Validators.required, Validators.minLength(6)]], confirmPassword: ['', [Validators.required, Validators.pattern]] }); } ngOnInit(): void { } get formRegistro() { return this.registro.controls; } /** * Registro con email y contraseña * @returns */ onSubmit() { if (this.registro.invalid) { return; } // var btnregistro = document.getElementById("btnregistro") as HTMLInputElement; // btnregistro.disabled = true; this.auth.registro() .subscribe( (response) => { console.log('Login éxito'); var user = response['message']; this.auth.prepareLogin(user); this.toastr.success('Bienvenido/a!'); this.activeModal.close(); }, (error) => { var code = error['error']['message'].code; if (code === 'auth/email-already-in-use') { this.msg = 'El correo electrónico introducido ya está registrado.' } }); } /** * Login con cuenta de Google */ loginGoogle() { this.auth.loginGoogle() .then(response => { var user = response.user; this.auth.prepareLogin(user); this.toastr.success('Bienvenido/a!'); this.activeModal.close(); }) .catch(error => { console.log("Error al logear con Google: ", error); }); } /** * Login con cuenta de Facebook */ loginFacebook() { this.auth.loginFacebook() .then(response => { var user = response.user; this.auth.updateProfileFB(response); this.toastr.success('Bienvenido/a!'); this.activeModal.close(); }) .catch(error => { console.log("Error al logear con Facebook: ", error.code); if (error.code === 'auth/account-exists-with-different-credential') { this.msg = 'Ya existe una cuenta con esta dirección de correo electrónico pero con diferentes credenciales de inicio de sesión. \ Intenta iniciar sesión mediante correo electrónico o Google.'; } }) } /** * Cierra modal registro y abre modal login */ openLogin() { this.activeModal.close(); this.ngmodal.open(LoginComponent, { size: 'md' }); } } <file_sep>// This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false, firebaseConfig: { apiKey: "<KEY>", authDomain: "pfg-survivor-cd919.firebaseapp.com", projectId: "pfg-survivor-cd919", storageBucket: "pfg-survivor-cd919.appspot.com", messagingSenderId: "530404504797", appId: "1:530404504797:web:a2efd13f039584133dd734", measurementId: "G-XSHMWHFTZ6" }, SESSION_KEY_USER_AUTH: 'AUTH_USER_123456789', dirBack: 'http://localhost:6060/api/' }; /* * For easier debugging in development mode, you can import the following file * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. * * This import should be commented out in production mode because it will have a negative impact * on performance if an error is thrown. */ // import 'zone.js/dist/zone-error'; // Included with Angular CLI. <file_sep>import { Injectable } from '@angular/core'; import { AngularFireStorage } from '@angular/fire/storage'; import { AuthService } from './auth.service'; import { Router } from '@angular/router'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class PerfilService { userAuth: any | null; // Usuario guardado en session storage para obtener bien los datos al recargar la pagina tokenUser:string = ''; constructor(public firestorage: AngularFireStorage, public auth: AuthService, public router: Router, private http: HttpClient) { } /** * Obtiene el usuario almacenado en localStorage, el cual se almacena al iniciar sesión */ getUser() { this.userAuth = localStorage.getItem(environment.SESSION_KEY_USER_AUTH); this.userAuth = JSON.parse(this.userAuth); this.tokenUser = this.userAuth['stsTokenManager']['accessToken']; } /** * Cambiar nombre * @param name */ updateDisplayName(name: string) { this.getUser(); const url = environment.dirBack + "updateName/" + this.userAuth.uid; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.put(url, { 'name': name }, { headers: headers }) .subscribe( (response) => { console.log('RESPONSE', response); this.auth.setName(name); }); } /** * Cambiar foto de perfil * @param event */ updateProfileImage(event) { this.getUser(); if (event.target.files[0]) { var file = event.target.files[0]; // Subir imágen a storage this.firestorage.ref('profileImages/' + this.userAuth.uid).put(file).then(fileSnapshot => { return fileSnapshot.ref.getDownloadURL() .then(photoURL => { // Actualizar imágen a el usuario const url = environment.dirBack + "updateProfilePhoto/" + this.userAuth.uid; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); this.http.post(url, { 'user': this.userAuth, 'photoURL': photoURL }, { headers: headers }).subscribe(()=>{ this.auth.setPhoto(photoURL); }); }); }); } } /** * Cambiar email de inicio de sesión * @param email * @returns */ updateEmail(email: string) { this.getUser(); const url = environment.dirBack + "updateEmail/" + this.userAuth.uid; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.put(url, { 'email': email }, { headers: headers }); } /** * Cambiar contraseña de inicio de sesión * @param pass * @returns */ updatePass(pass: string) { this.getUser(); const url = environment.dirBack + "updatePass/" + this.userAuth.uid; let headers = new HttpHeaders({ Authorization: `Bearer ${this.tokenUser}` }); return this.http.put(url, { 'pass': pass }, { headers: headers }); } } <file_sep>echo '*********************************************************' echo '*******************STARTING CONTAINERS*******************' echo '*********************************************************' docker-compose down docker-compose build docker-compose up -d echo '**********************************************************' echo '********************APP READY*****************************' echo '*******************LOCALHOST:4200*************************' echo '**********************************************************' # En caso de error: error checking context: 'can't stat directorio. EJ: '/home/maria/Escritorio/frontmaria/.config''. # Ejecutar: # sudo rm -rf .config # sudo rm -rf .npm # sudo rm -rf node_modules # Volver a lanzar init.sh
a2215cbebd91ff95011b93878e0b6148b4b0743c
[ "SCSS", "HTML", "Shell", "Markdown", "Dockerfile", "JavaScript", "TypeScript" ]
39
SCSS
meryjv00/PFG-Survivor
db07a6e30039345c943d9b3d7ff6a633cd368094
0610fefa82d7d0a732f50cda3200e9a29f78f2fe
refs/heads/master
<file_sep>--- layout: post title: "Ruby on Rails Project" date: 2021-02-02 23:58:15 +0000 permalink: ruby_on_rails_project --- As the Rails module is gradually coming to end, now is the time to start thinking about the final project. When it came to this module, it wasn't much different from the previous module when we were studying up on the Sinatra framework. There were much similarities between Sinatra and Rails, which made learning Rails all that much more simple. However, with Rails being a much bigger framework than Sinatra, of cource Rails would have its own way of doing things. When it came down to the final project for the Rails module, some of the requirements were very similar, but not identical to the Sinatra final project, except for the fact that the project had to be built using the Rails framework. The set up process for the project was quick, easy, and similar to Sinatra; just setting up the models and their associations, along with the migration files for setting up the database. Then, came the part where Rails differs from Sinatra; although both frameworks are built around the MVC architecture, Rails, of course, does things differently than Sinatra. After the models came setting up the controllers and linking each controller action with the corresponding route. Sinatra does not use routes like Rails does. Next, came setting up the views files using partials for setting up forms that could be used across different pages. Once I got the basic backbone of the project came my favorite part: setting up sessions and authentications for the different types of users. The idea of my Rails project is that there are two types of users: a student or a professor, so upon initially accessing the website, the user will be prompted to sign in as a student or to sign in as a professor. If the user is signing in as a student, then they will see a student login form, but if the user is a professor, then that user will see a professor sign in form. Basically, the two different users will see a similar login form, however, the idea is that upon signing in, a student has less admin credentials when being compared to a professor. Overall, if you didn't struggle and had fun with Sinatra, then you'll definitely love Rails and it'll be a breeze. So far, it has been my favorite module of the cohort and I can't wait to see what the rest of the program has to offer with JavaScript being the next module. <file_sep># Site settings author: <NAME> title: First Mile Struggles header-img: img/home-bg.png email: <EMAIL> copyright_name: <NAME> description: > # this means to ignore newlines until "baseurl:" The start baseurl: "" # the subpath of your site, e.g. /blog twitter_username: github_username: Jzweifel15 # Build settings markdown: kramdown highlighter: rouge permalink: pretty paginate: 5 exclude: ["less","node_modules","Gruntfile.js","package.json","README.md"] gems: [jekyll-paginate, jekyll-feed] <file_sep>--- layout: post title: "Commonalities between Real life and Code" date: 2021-01-29 21:58:00 +0000 permalink: commonalities_between_real_life_and_code --- Hello everybody, Since going through the cohort and learning how to properly code, all I now see is code. I continuously point out little aspects and events in my life by saying in my head how it can be coded. For example, if im hungry, I'll say something nerdy like, "if hungry -> go get food; else if smelly -> take shower; else -> do nothing". Not sure if i'm the only one doing this, but ever since I started working with code and on smaller projects, I definitely think in code, probably more than I should, but i'm going to go out on a limb and say that this is a good thing since we're all aspiring software engineers in the making. <file_sep>--- layout: post title: "JavaScript/Rails Project" date: 2021-02-04 07:21:12 +0000 permalink: javascript_rails_project --- Hello Everyone, It felt like just last week we were finishing our Rails portfolio projects and wrapping up the third module of the cohort. Now, we're already in project week for the fourth module (JavaScript) and getting ready to enter the two-weeks of project assessments at the time i'm writing this blog post. I sincerely enjoyed the JavaScript module. I had already heard about JavaScript being a very important language to understand when it comes working on the front-end of web applications, and before Flatiron, I had always intended to try to take it up on my own time to learn JavaScript, but never really got around to it. I primarily thought JavaScript was used for animations and other little things that sometimes wasn't always necessary to have in every website or that could easily be done using CSS keyframes. However, after going through this fourth module, I was completely wrong. There is much more that can go on behind the scenes if you're wanting to build your own full-stack web application. Going through the readings and completing the labs is always helpful. However, I also did some other research of my own on JavaScript and tried to work with as much as I could, incorporating my own little test projects to work through its quirks and tricks because I know just how important JavaScript is and anyone reading this, I would highly recommend doing your own research on JavaScript as well. Not saying the lessons weren't helpful. Without the lessons, I would not have known what to look up and research. I just wanted to take everything the readings and labs had to offer in this fourth module and go one step further by doing a little extra research on each topic that I was currently on. When it comes to this project, the requirements were very straightforward and I had no questions to ask. Once I had an idea, I went to the drawing board and started building out the project. For this project, you're definitely going to spend more time working on your front-end than you will with the back-end. The back-end portion was pretty straightforward and the only time I really spent in the back-end was by changing up my database making sure I had all the tables and columns that I wanted for my project and ensuring I had the proper seed data to work with. Originally, I was going to pull from a third-party API, but had really no luck finding any end-points to pull from, so I just created some of my own dummy data to work with. I didn't want to spend too much time trying to find something that really didn't matter all too much; I wanted to ensure I actually got the project working, and if I had time later, could implement this functionality instead of saturating the database with data that it doesn't really need. Even after doing my own research and little test projects with JavaScript, this project gave me quite a bit of trouble; but, I think that's typically to be expected in the field of software development. If anyone goes into this career not expecting there to be headaches, then I hate to be a burden, but you're in the wrong career field. Anyways, the main problem I was having wasn't pulling the data from the back-end; that was actually the easiest part of the project, but was actually getting little, certain functionality (that I wanted to be precise) to work. I think I spent a whole two days trying to figure out what I was doing wrong, but didn't get anywhere. I was able to get the functionality "half," working, and by "half," I mean that it did what I wanted it to do up to a certain point, but once that point was reached, it was downhill from there. It was a small little bug that didn't necessarily crash the project or make the project not work properly, but it was just a little qwirk that I didn't like because, I might be somewhat of a perfectionist, and just wanted my project to be "perfect," in my eyes. All-in-all, I still can't believe that we're already at the end of the fourth module, which is the second-to-last module of the cohort!!! Once this module is officially over, it'll be a new year (at the time this blog is being made, we are 2-weeks out from 2021) and we'll have a little less than two-months of my cohort. I must say, I learned a lot while going through this cohort with Flatiron. Not only have I learned the ins-and-outs of being a full-stack web developer, but I also learned how to be a software engineer. I leanred how to also teach myself; that way, if I ever wanted to pursue a different path in this field (rather than web development), I know how to teach myself and what I should do in order to sufficiently and efficiently study and research. With that being said, we're in the end-game now... <file_sep>--- layout: post title: "Final Portfolio Project: React/Redux" date: 2021-02-21 19:58:39 +0000 permalink: final_portfolio_project_react_redux --- So, how was React/Redux... well, honestly for me, it was 50/50. I thoroughly enjoyed learning and using the React framework. However, when it comes to Redux... well, even though we're in project mode, I can tell you, I'm still struggling to understand how to use it. I understand its purpose and the reasons for using it, but it's the understanding exactly how to properly use it. At the time of writing this blog, I still have plenty of time to do some more research on Redux and to review all of the labs, readings, and code-alongs from the curriculum to hopefully better understand Redux. So, overall, React was very much my friend, where Redux was, not necessarily an enemy, but just kind of a nuisance. For my final project for this final module of the cohort, I will be making a fitness tracker for those gym-monkies that are out there. This web application will allow the user to keep track of their daily workouts; you can log the number of sets and repetitions for each exercise that you carryout within a particular workout. Not only can the application keep track of your workouts, but you can also keep track of the meals you eat and your calorie consumption for a full day based on the particular foods you have entered for the day. This project of course will utilize full CRUD functionality, allowing a user to enter new workouts and new meals for a particular day, but if they also need to either edit or delete a particular workout/meal, then they can definitely do so. I will also be incorporating a component that will be a calculator/tracker of the user's Body Mass Index (BMI), as well as, a component that will contain a line graph that can be used to view how their BMI has changed over the course of either a week, a month, or a year depending on how long the user has an account, of course. Roughly 10-months ago when I first started my cohort, I have been dreaming of this day. The day where my cohort officially enters the "end-game." We are officially in, not just final project mode for the module, but the final-final project mode, where the end of this project will officially mark the end of the software engineering curriculum for my cohort. Once everyone passes their project review, we'll officially be in the "job hunt." The reason I put "job hunt," in quotation marks is because, where I'm sure most, if not all, of my cohort-mates will be transitioning straight into a job after their time at Flatiron schools, myself, however, will actually be continuing my education after graduating Flatiron. I have the opportunity to attend a community college around where I live to pursue a 2-year, Associates of Applied Science in Computer Science degree. Most people would probably ask, "well, you don't really need a college degree to become a software engineer, so why bother?" That is a great question and I'm glad you asked. The only reason why I have decided to pursue this path after Flatiron is because my employer offers tuition assistance to associates who have worked at least one full year at the company, and in the middle of my cohort, I actually hit my one year anniversary with my employer. So, not only will my employer be providing assistance to help pay for this degree, but they'll actually be covering... what for it... 95% of the tuition for this degree. Yes, I promise you that number is correct... they'll be providing 95% of the tuition, so I won't even need to apply for any loans/financial aid, since that last 5% will be a small amount that I can just pay for myself, so I will have absolutely no debt after finishing this degree program, which makes it even better. So, if I were to find a job and leave my current employer, I may never have this opportunity again, so I figured I would utilize it while I can, even if it means putting off the official job hunt for a little while longer. So, for all of my cohort-mates, I wish you all the best of luck with your final projects and your projects reviews, as well as, your hunting for a job to officially start your new careers as software engineers. To those who are just starting or in the middle of your cohorts at Flatiron, I wish you all the best of luck with the rest of your cohort and with your job hunt, as well when you get to that point. <file_sep>--- layout: post title: "Sinatra Project" date: 2021-02-02 01:41:16 +0000 permalink: sinatra_project --- The second module of the Part-time Online Software Engineering Cohort for Flatiron Schools was primarily about creating and setting up databases for web-applications that use an MVC (Model, View, Controller) layout, using RESTful naming patterns to perform CRUD (Create, Read, Update, Destroy) actions on those databases, and sending HTTP requests to a local server to display a View that shows the user certain data from the database based on those requests. In this module I have learned so much about creating relationships amongst different Models and setting up associations for those models to a database. One of the most important things that I learned during this module was how to use the Sinatra Gem. Sinatra, in Ruby, is a library that allows any programmer [that knows how to properly use the gem] to build a somewhat smaller MVC web-application. Even though Sinatra was learned more towards the end of this module, everything before it was important to understand in order to successfully comprehend how to properly use Sinatra. Now, that we're in project week for our second portfolio project it was time to show off what I had learned from this module. We had to create a web-application (using Sinatra of course) that utilizes an MVC layout, has more than one model that can be created/associated to a database, uses the RESTful naming patterns for routes to transition from view-to-view, and successfully perform CRUD actions on a database. For my project, I decided to create a small music playlist creator. This application will allow anyone to sign up (or, sign in if you already have an account) and create your own playlist filled with the music you love. A user can create as many playlists as they want with however many songs they want to add and can name their playlist whatever they want. If they want to add a song to an existing playlist, they can edit/update an already existing playlist, or if the user just does not want the playlist on their homescreen anymore, they can simply delete/destroy the playlist from existence. Of course with any project, one of the hardest parts is actually figuring out where to start. For anyone wanting to create a Sinatra application, there is actually this really nice, extremely helpful and time-saving gem called 'Corneal' that I highly recommend any Rubyist downloads locally to their computer. The Corneal gem actually sets up everything you'll need to get started building your Sinatra application right away without any headaches. All you'll need to type into your terminal (after installing the gem of course) is "corneal new [APP-NAME]" where "[APP-NAME]" is the whatever you want to name your project. After you type all that in, you'll see a bunch of files and folders automatically created for you. Just open the new directory in your favorite code editor and get started. Like I said, I learned a lot from this module, however, I definitely learned the most by actually trying to build my own project. I ran into all sorts of problems (as any software engineer does when working on any project), but being able to troubleshoot these errors/bugs within my own code allowed me to really think/brainstorm logical soultions that would eventually lead to the problem being solved. Overall, I'm very proud of my code and my complete project. I spent a lot of time working on it the past two-weeks and I can't wait to move on to the next module of the cohort (assuming my project review goes well). <file_sep>--- layout: post title: "Ruby CLI Project" date: 2021-01-31 00:31:05 +0000 permalink: ruby_cli_project --- The first portfolio project that is due for the first module when participating in the Flatiron School's Software Engineering program is building a command line interface Ruby gem that scrapes data from a webpage and allows any user to interact with that data in some way. I decided to create a gem that would allow any user to see the top grossing movies of all time. This gem would scrape data from the Rotten Tomatoes webpage where they have a list of 50 movies in order starting from the #1 top grossing movie and working its way down. When I first started this project, I had a small idea of where to start, so what I did was first look for a website that my gem was to scrape data from and after about 10-15 minutes of searching, I came across the Rotten Tomatoes webpage, which is where my gem scrapes from. I played around with the website for a while, finding the data I needed and how I was going to go about getting that data and displaying it in a nice, organized manner to the user. When it comes to working on any project, I have learned that just playing around with code can go a long way. I probably spent a good, 4-5 hours just messing with the Nokogiri and Open-URI modules to scrape different data from the website, then another couple of hours iterating through that data to display it how I wanted it to be layed out to the user. Next, was actually starting to build the project and this was where I was stumped because I had never actually built my own Ruby gem and had no idea where to start. Thankfully, Flatiron provides some very helpful resources that allowed me to get a small blueprint (or, rough draft) of my project formed. This blueprint consisted of hardcoding some of the data, but it was to get my project off the ground and into the air. I knew that later down the road major changes were going to be made, but I felt much better than before knowing that I at least had a baby project started. As of Tuesday, June 23rd of 20202, I have officially completed my first portfolio project for the part-time online software engineering program at Flatiron. We were required to build a ruby gem that allowed any user to interact with an interface of data using the command line. This data had to come from a webpage of our choice, but we were not allowed to hardcode this data. We had to either scrape this data from the website or request this data from the websites API. For my project, I decided to scrape my data. My project, called Top_Movies_Cli scrapes data from the Rotten Tomatoes webpage on the top 50 highest grossing (most money made) movies of all time, turns each movie into a Movie object using some corresponding information that can be found for each movie on the webpage, like the movie's title, value, release date, and a description of the movie. Anyone who uses this gem will have access to seeing the list of movies and can interact with this data by choosing and typing a number one through fifty to select a movie, which the gem will spit back out the corresponding information for that movie. Although my project is plain and simple, and the project does not do very much, I am still very proud of my project. It was a giant headache in the making, but it always feels so good when it finally works and does what you're expecting of it to do. Hopefully, this small little project is just the first step to something much, much bigger in the future. <file_sep>--- layout: post title: "Why Did I Decide to Learn Software Development" date: 2021-01-29 21:53:11 +0000 permalink: why_did_i_decide_to_learn_software_development --- Hello everybody, I decided to learn software development because it has always been a dream of mine to get into some type of technical field where I can help people. In the realm of computer science, there are many paths that can be taken when learning how to program. Software development is not the only career path that I plan to look into upon going through my cohort, but becoming a software engineer is definitely a big one. Especially, how high the deman is for SEs. I'm hoping that one day, with the knowledge that I obtain, I can one day give back to those who are wanting to do the same thing.
040ba39228920db22cb3b88444da5482315d8718
[ "Markdown", "YAML" ]
8
Markdown
Jzweifel15/Jzweifel15.github.io
4c780b08e0e416d269fa5ef0854072906f5efef0
547239bdc4c25c45ea7b73ecedafbc4c4841957b
refs/heads/master
<file_sep>import 'package:flutter/material.dart'; class ActiveTrip extends StatelessWidget { final Color color; const ActiveTrip({Key key, this.color}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Column( children: <Widget>[ Expanded( flex: 1, child: SizedBox(), ), Container( alignment: Alignment.center, child: Text('No Active Trip', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500,color: Colors.red[200])), ), Expanded( flex: 1, child: SizedBox(), ), ], ), ); } }<file_sep>import 'package:flutter/material.dart'; class LogoContainer extends StatelessWidget { @override Widget build(BuildContext context) { appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset('assets/icpep.png', fit: BoxFit.contain, height: 30, ), Container( padding: const EdgeInsets.all(8.0), child: Text('ICpEP Singapore')) ], ), ); } } <file_sep>import 'package:flutter/material.dart'; class LogoContainer extends StatelessWidget { @override Widget build(BuildContext context) { AssetImage assetImage = AssetImage('assets/images/ct_logo.png'); Image image = Image(image: assetImage); return Container( child: image ); } }
dab6b435c27efc62b7f65e7f9e4ba95947ea9e56
[ "Dart" ]
3
Dart
itlog/ct_icpep
687ab9e63c9c31acd694c1b3e5ddb72ba56af778
0527338c3e31b1155329572c8066e4f33c012019
refs/heads/master
<file_sep># Lecture 6 (1/26) #Lin177 Recall issue with infinite nucleus from Lecture 5. * Use Length? * No, that’s not principled. Language not actually based on magic value like length. Want to model what we think is happening linguistically ``` nucleus([A,B]) :- phone(A), not(cns(A)), phone(B), not(cns(B)), not(A = B). ``` Recall the issue of excluding the ‘err’ sound: ``` onset([A]) :- phone(A), cns(A), alv(A), not(pal(A)). oneset([A]) :- phone(A), cns(A), not(alv(A)). ``` * Not great. It would be better to have one natural class that gives all solutions. But prof is not sure if this is possible given our syllable properties. * The problem on the homework is a little easier, presumably… -> Chapter on phenetics ends on english syllables, and goes into semantics. - - - - # Semantics ## The Procedural Definition of Semantics “The planet closest to the sun” -> Mercury “The planet Mercury” -> Mercury -> This meaning is called the **Reference** Both of these phrases refer to Mercury, but do they mean the same thing? Not necessarily. * The method we use to get to the meaning is different * The procedure to get to meaning is affected by the current state of the world. * So we have to make some sort of distinction or else “The President of the US” would always mean <NAME> (the horror!) -> This procedure is called the **Sense**. * specific entities are given with underlines: Sid -> _Sid_ Nancy -> _Nancy_ * In this particular universe, there is only one sid and one nancy * Next, we can add relation between S & N loves -> (Nancy -> Sid) -> (Sid -> Nancy) * Given any english sentence, and leaf of the sentence structure, we can evaluate it to a true or false. “<NAME> Nancy” Sid Sid true For each phrase type, there’s a particular thing you are looking for: * Nouns: looking for entities * Verbs: looking for relations * Sentences: looking for T/F -> See example above * You can see how Prolog will be very good at this * The way Prolog handles procedure/variable bindings is identical to the way we are relating things in this procedural definition of semantics ## Expressing References in Prolog ``` Reference :: (Reference is 3+2). Reference :: (Reference is 1+4). ``` * Note how it distinguishes the difference between reference and expression. ``` num(0). num(N) :- num(M), N is M + 1. ``` * The set of all positive integers. * If you do a `findall`, it’ll find all numbers until it runs out of memory. * In linguistic, we need to do a better job referencing infinite sets. Because lots of things are an infinite set in linguistics ``` Reference :: (findall(A, num(A), Reference)). ``` * Can’t evaluate it (because will run out of memory). * But we can still express it in a principled way. %: Not exactly sure what the point of this is, but presumably it will come up later… <file_sep># Lecture 9 (2/5) #Lin177 Coding Challenge in class. Turn in on HW4 for extra points (or something). I, being the kiss-ass I am, showed off my program in class, and he said it was basically correct: ```Prolog word(make, [verb]). word(made, [verb]). word(cat, [noun]). word(tend, [noun]). word(done, [verb]). prefix(Word, Prefixed) :- word(Word, [verb]), atom_concat(pre, Word, Prefixed). ``` <file_sep># Lecture 4 (1/19) #Lin177 Make sure you can do the following in prolog: 1. Run swipl 2. open a file 3. consult within a file - - - - ## Homework 1 Intro All questions adapted from text. 1. Tons of examples to choose from 2. Sound alike and mean different Mean alike but sound differently -> actually more difficult 3. See excursive given in the book * You’ll see it’s very similar to spanish, but slightly different * Modify spanish program, not writing something from scratch * similar enough that edits are fine 4. Don’t overthink this. * The solution to 4 is incredibly short * presumably translate from spanish to english, then english to japanese * Could this be one line? - - - - # More stuff about Properties of Phones * We don’t normally want just one sound in isolation: `phone(X), cns(X)` * Gives one at a time * We want the full set of solutions: * “Natural Class” * The overlap between different features ``` findall( Variable, Conditions we want to be true, // can be more than one in parenthetical block Output Variable ) EX: ?- findall(X, (phone(X), cns(X), ant(X)), Y). Y = [p, b, m, t, n, f...]. ``` You may find that Prolog truncates this output. To fix this, there is a program called Full Display `[‘fulldisplay.swipl’]` if it doesn’t work, get new version ``` findall(X), (phone(X), not(cns(X))), Y). # note the use of not(cns(X)) to select vowels ``` # More About Syllables * Remember “Strengths” having a complex coda * In Japanese, the only possible coda is a nasal, no complex coda allowed * Reason for odd syllable arrangement when pronouncing foreign words * Spice (english) -> su | spi | su (follows japanese syllabic rules) * If you break rules, you have things that are “unpronouceable” * How many possible syllables are there in English? * A Lot! But there are rules that restrict range * `tranz` is a syllable * Can we have `tlanz`? No! ### Page 64 & 65: Rules of English Syllables ``` R1. The sequence of an onset and a rhyme is a syllable. ``` ``` R2. Any consonantic nonnasal phone is an onset (so p, b, t, d, k, g, f, v, θ, ð, s, z, ʃ, ʒ, č, ǰ, j, l, ɹ, j, w, h are all onsets). ``` ``` R3. Any nonvelar nasal phone is an onset (so m and n are both onsets). ``` ``` R4. Any nonsonorant, noncontinuant, nonpalatal phone followed by an al- veolar palatal phone is an onset (so pɹ, bɹ, tɹ, dɹ, kɹ, and gɹ are all on- sets). ``` ``` R5. Any nonsonorant, noncontinuant, noncoronal phone followed by a son- orant, nonnasal, alveolar, nonpalatal phone is an onset (so pl, bl, kl, and gl are all onsets). ``` ``` R6. Any nonsonorant, noncontinuant, nonlabial, nonpalatal phone followed by a velar continuant phone is an onset (so tw, dw, kw, and gw are all onsets). ``` ``` R7. Any nonvoiced, continuant, labial phone followed by a sonorant con- tinuant alveolar phone is an onset (so fl and fɹ are both onsets). ``` ``` R8. Any nonvoiced, continuant, nonalveolar, coronal phone followed by an alveolar palatal phone is an onset (so θɹ and ðɹ are both onsets). ``` ``` R9. Any nonvoiced, continuant, alveolar phone followed by a consonantic, sonorant, nonnasal, nonpalatal phone is an onset (so sl and sw are both onsets). ``` ``` R10. Any nonvoiced, continuant, alveolar phone followed by a nasal non- velar phone is an onset (so sm and sn are both onsets). ``` ``` R11. Any nonvoiced, continuant, alveolar phone followed by an onset headed by a nonvoiced, noncontinuant, nonpalatal is an onset (so sx is an onset if x is itself an onset–albeit one that begins with p, t, or k). ``` ``` R12. The sequence of a nucleus and a coda is a rhyme. ``` ``` R13. Any nonconsonantic phone is a nucleus (so i, ɪ, u, ʊ, e, o, ə, ʌ, a and æ are all nuclei). ``` ``` R14. Any mid noncentral phone followed by a consonantic, sonorant, nonnasal, nonalveolar phone is a nucleus (so ej, ew, oj, and ow are all nuclei). ``` ``` R15. Any low back phone followed by a consonantic, sonorant, non-nasal, nonalveolar phone is a nucleus (so aj and aw are both nuclei). ``` ``` R16. Any nonsonorant phone is a coda (so p, b, t, d, k, g, f, v, θ, ð, s, z, ʃ, ʒ, č, ǰ, j, l, ɹ, and h are all codas). ``` ``` R17. Any nasal phone is a coda (so m, n, and ŋ are all codas). R18. Any liquid phone is a coda (so l and ɹ are both codas). ``` -> All of these rules are loaded into `syllable.swipl` -> He’s going over this now. <file_sep># Lecture 3 (1/17) #Lin177 * Spanish Program diagrammed out on page 36 of the textbook -> You can rewrite this as rules and postulates * eva is Postulate 1 (P1) * Transitive very is Postulate 6 (P6) * This is shown on page 38 of the textbook * You end up with the derivational history of the program in simple expression: `R4(P1,R3(P6,R2(P2)))` - - - - * First Homework has a problem very similar to this * Homework will go up tomorrow * Due Monday * Mostly material from chapter 1, with one question about Phentics that’s easy - - - - # Chapter 2: Phonetics (the sounds themselves) Every language has unique set of sounds -> “Phones” * IPA (international Phonetic alphabet) tries to give a symbol to all human sounds * Hundreds of symbols ### How do you split up these sounds? * Look at anatomical differences in producing sounds #### Constances * Voicing * Place * Manner Complete or partial closure * “puh” closes completely * “shhh” obsctructs air to make noise #### Vowels * height * frontness * tense/lax * Sheet (tense) * Shit (lax) ``` properties.swipl # Defines set of properties (explained on page 58 in text) ``` The properties we have in mind are the following: ## Consonant Properties ``` • CONSONANTIC: This property is true of sounds articulated with some degree of obstruction in the oral cavity; it therefore applies to all of the consonants (but none of the vowels) of Section 2 above. ``` ``` • SONORANT: This property applies to sounds which are naturally (or normally, or most effortlessly) voiced (see below). In English, the class of sonorants includes nothing but the vowels, the nasals (m, n, ŋ), the lateral (l), the approximant (ɹ), and the glides (j, w). ``` ``` • NASAL: This property holds only of sounds which resonate in the nasal (rather than the oral) cavity. Consequently, in English, it applies only to m, n, and ŋ. ``` ``` • VOICED: This property characterizes sounds that involve vibrating vocal folds (the lip-like organs in the larynx, which is commonly known as Adam's apple). Thus, in English, it applies only to b, d, g, v, ð, z, ʒ, ǰ— as well as to all sonorants. ``` ``` • CONTINUANT: This property is true of phones throughout the articula- tion of which the air flows uninterrupted. In English it is true of all phones other than the stops (p, b, t, d, k, g, m, n, ŋ) and the affricates (č, ǰ). * We can extend past some length * Anything you can control the length of ``` ``` • LABIAL: This property applies only to the phones that involve the lips. It therefore describes, in English, the bilabials (p, b, m), the labiodentals (f, v), the lip-rounded glide (w), and nothing else. ``` ``` • ALVEOLAR: This property holds of phones which are articulated at the alveolar ridge. Thus, in English, it holds only of t, d, n, s, z, l, and ɹ. 6 I am indebted to my colleague <NAME> for help with deciding on this set of properties. ``` ``` • PALATAL: This property characterizes the phones articulated at the pal- ate (or roof of the mouth). In English it holds of the palatals proper (ʃ, ʒ, č, ǰ, j) and the alveopalatal (ɹ), which is both alveolar and palatal. ``` -> Hard to recognize, probably should memorize sounds as palatal ``` • ANTERIOR: This property is true of phones articulated with an obstruc- tion at the alveolar ridge or before. In English it therefore applies to all labial (p, b, m, f, v) and alveolar (t, d, n, s, z, l, ɹ) consonantic phones. ``` ``` • VELAR: This property applies to sounds articulated at the velum (or soft palate)—the veil like continuation of the palate. In English, these would be k, g, ŋ, and w. ``` ``` • CORONAL: This property holds of phones involving the tip (or crown) of the tongue. Thus, in English, it is true of the interdentals (θ, ð), the al- veolars (t, d, n, s, z, l, ɹ), and the palatals (ʃ, ʒ, č, ǰ, j, ɹ). ``` ``` • SIBILANT: This property characterizes ‘whistling’ (or s-like) phones. In English, these phones are only s, z, ʃ, ʒ, č, ǰ. ``` ## Vowel Properties ``` • HIGH: This property is true of vowels articulated with the tongue in a relatively high position. Consequently, it applies in English only to i, ɪ, u, and ʊ. ``` ``` • MID: This property applies to vowels articulated with the tongue at middle height. In English, this describes only e, o, ə, and ʌ. ``` ``` • LOW: This property holds of vowels articulated with the tongue in a relatively low position. In English, this property is extremely discrimi- nating, as it is true only of two phones: a and æ. ``` ``` • BACK: This property characterizes vowels articulated with the tongue in a relatively back position. In English, this describes only u, ʊ, o, and a. ``` ``` • CENTRAL: This property is true of vowels articulated with the tongue at mid-back (or mid-front) position. In English, this property, too, is ex- tremely discriminating, as it is true only of two phones: ə and ʌ. ``` ``` • TENSED: This property applies to vowels articulated with relatively high muscular tension. Again, only two phones satisfy this property in Eng- lish. They are i and u. ``` ``` • STRESSED: This property holds of vowels that may serve as syllabic nuclei. In English they are all except ə. ``` ## Properties.swipl * first call in phone.swipl * gives it all the possible symbols * need to use unicode values throughout * cns/1 rules are consonantic * voi/1 rules are voices * cnt/1 Etc. etc. -> Let’s run it: ```Prolog ?- ['properties.swipl']. true ?- phone(A). A = p ; A = b ; etc. etc. ?- cnt(A). A = f ; A = v ; etc. etc. ?- vel(A), snt(A). # a sound that has both of these properties A = w ; etc. ?- mid(A), bck(A). A = o ; false. ``` -> That’s pretty much all we need for the phonetics * the symbols and the properties of the sounds ## Syllables Some things to mention before we continue * one of the most important things in Phonology is the syllable * Syllable structure is arbitrary to a language ### Parts of a Syllable * Onset * Nucleus (rime) * the most sonorant part of the syllable * any sound with sonorant property * Coda (rime) EX: “ton” * onset: ’t’ * nucleus: ^ (uh) * Coda: ’n’ EX: “tahn” * pronounceable, but not an actual word * add complex onset, ‘tr’ * tron, that’s a word * add complex coda: ’ns’ * trons <file_sep># Lecture 5 (1/24) #Lin177 ## Homework 1 Answers 1. Any recursive word 2. Bear (n.), bear (v.) Lawyer, attorney / car, automobile 3. Best way to approach that is to edit the spanish program into the japanese program 4. consult japanese.swipl and spanish.swipl ``` spanishjapanese(A,B) :- spanish(A,_,English,_), japanese(B,_,English,_). ``` - - - - ## Homework 2 * in back of book: page 331, there’s a list of prolog tutorials * Highly recommended that you do one of these 1. structural description: derivational history: signature: draw it out 2. create `trilingual/1` rule need some kind of predicate to verify a given person 3. 4. eleven english words. express the parts of speech Not terribly easy, for things like too we would want to use this information to make valid sentences 5. must be principled - - - - ## Syllable.swipl * defines onset, rhyme. What makes a valid english syllable ``` ?- findall(X, syllable(X), Y). -> giant list of syllables -> number of syllables > number of words ?- findall(X,syllable(X), Y), length(Y, Length). Length = 20608 ``` # Syllables in Japanese onset: cns nucleus: not(cns(X)). (any vowel) coda: nas(X) (only a nasal) ``` :- ['properties.swipl']. onset([A]) :- phone(A), cns(A). %any sound that is a consonant onset([]). nucleus([A]) :- phone(A), not(cns(A)). nucleus([A, B]) :- nucleus(A), nucleus(B). % two nuclei in sequence is an allowable nucleus % NOTE: This causes infinite recursion. This will be adressed on Friday coda([A]) :- phone(A), nas(A). coda([]). rime(A) :- nucleus(B), coda(C), append(B, C, A). syllable(A) :- onset(B), rime(C), append(B,C,A). ``` <file_sep># Lecture 7 (1/31) #Lin177 * Review homework assignment * Preview next homework ## Homework 2 1. structural description, similar to diagram in book derivational history: same structure, given in Postulates (P) and Rules (R) signature: combine with parentheses 2. Trilingual program: * :/ 3. Why ill-informed facts. * atoms cannot contain spaces * capital letters are reserved for variable definitions * missing period * statements may not begin with numbers 4. Parts of speech. fine. 5. `spanish([nino],[noun, masculine, singlular],[boy],[property, male, single]).` * “something like this is fine” :/ ## Next Assignment (HW 3) * looking at properties of prolog syntax more closely * head and tail 1. Just evaluate and give the outcome from Prolog. For the ones that don’t work. find out why 2. explain what the prolog program (in prose). Basically explain the head and tail relationship. 3. same thing. explain why it works in prose. - - - - # More on the Semantics Model Some property vocabulary: * **Unary predicate** property of single element. something like `male(fred)`. * **Binary predicate** property of two elements. Lot’s we can do with these. * `parent(bob, sally)`. * <file_sep># Lecture 2 (1/12) #Lin177 ## Prolog Spanish Example (from book) Make rules: * Noun Phrase (subject) -> Noun * Noun Phrase (object) -> Noun (accusative) * Verb Phrase -> Verb + Noun Phrase (object) * Subject -> N.Phrase (sub) + Verb Phrase ## More Prolog * Atoms * facts. building blocks not further defined * lowercase * Lists [] * Just means that there can be one or more things * Variables * Capital Letters<file_sep># Lecture 1 (1/10) #Lin177 * Week 1, focus is getting Prolog installed (not coding till next week) * We are going to start with an overview of Linguistics - - - - ## What is a Language? -> can give examples easily -> but harder to give a general definition -> We are going to split a language into multiple pieces, model them independently ### For every language we have: * Sounds * Signs * Combinations -> Combinations of signs -> words -> sentences -> whatever 1. Phonetics * The “gestures” of languages * put mouth in a certain position, coordinate air, make a sound * The articulation of sound, or the acoustics of a sound 2. Phonology * The perception of sounds… * “Pot” * Starts with voiceless articulation of “Puh” * Needs a certain amount of air puff, otherwise people will perceive it as “Bot” * Perception of sounds depends on this kind of Phonology, spelling isn’t enough 3. Morphology * the Study of words * more than just grouping sounds: * “Add an ’s’ to a group to make it plural” * Pot + s -> add s sound * Pan + s -> add z sound * Church + s -> add es sound -> So it’s more complicated. Can’t simply put an s on something. 4. Syntax * Word order * There’s all kinds of patterns: Subject-Verb-Object is an example * Is there a principled way of writing a sentence in correct order? 3. Semantic * Word meaning * All kinds of complications: * Difference between “chair” and “stool”? * There’s some precise difference between chair and stool that people agree on, but hard to define. * Hardest one to deal with in Computational Linguistics, but there is a way to do it. We’ll get there later. -> So “What is a language?” is too hard, but we can discuss “What are the morphological properties of a language?” * Note: Every language is going to have some set of sounds, but every language is different * So every property in a given language is arbitrarily different. * However, there are some shared elements: * Almost all languages have vowels, but that depends on how you look at it I don’t really know what he’s talking about right now, but I don’t think it matters. ## Why are we using Prolog? * Closer to what we think the mind is doing. Not procedural. * Obviously, you wouldn’t write Siri in Prolog, but we’re able to focus more on the Linguistics this way. * We are going to try to come up with a “grammar” to model a language… ## Goals of our Grammar 1. Explicit * set of specific rules * Enough details that our Prolog declarations create a functioning program 2. Accuracy * Needs to be recognizable as a real language * There will come a time where we have our rules all set up and the program spits out garbage. Caused by either too many or not enough rules. 3. Principled-ness * We want to do what we think the mind is doing. * We don’t want to take shortcuts * Antithetical to regular programming where we optimize to get the same result faster * Don’t just make a series of hacky rules to generate the outcome we want 4. Simplicity * We want the solution to be as simple as possible * But needs to be principled! ## Introduction to Prolog * We are not giving Prolog commands to execute * We are giving Prolog a set of facts, some proceudure finds solutions based on facts we give it ``` testword.swipl word(blah). %blah is a word word(X-blah) :- word(X). %something is a word if followed by blah ``` ``` swipl ?- ['testword.swipl']. true. ?- word(Y). % give me all solutions that are a word blah ; blah-blah ; blah-blah-blah ; ... ``` - - - - -> He’s explaining `spanish.swipl` (which is posted online)
c524e73e6c09e392c16605ff626da87482857625
[ "Markdown" ]
8
Markdown
andrewthecope/Lin177-Notes
87488bb1ae0308e840e13c8d32c9ef0331b90732
4fead44b6563796206658b3dbe8de20e1a975347
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace OGL.Models { public class Advertisement { [Key] [Display(Name = "Id")] public int Id { get; set; } [Display(Name = "Advertisement content")] [MaxLength(500)] [Required] public string Content { get; set; } [Display(Name = "Advertisement title")] [MaxLength(72)] [Required] public string Title { get; set; } [Display(Name = "Add date")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)] [Required] public DateTime AddDateTime { get; set; } [Required] public string ApplicationUserId { get; set; } public virtual ICollection<Advertisement_Category> Advertisement_Category { get; set; } public virtual ApplicationUser ApplicationUser { get; set; } public Advertisement() { Advertisement_Category = new HashSet<Advertisement_Category>(); } } }<file_sep># OGL ASP.NET MVC Simple learning project - advertisement service Project is based on: `C# 6.0 i MVC 5 - Tworzenie nowoczesnych portali internetowych` by `<NAME>` and `<NAME>` - `Helion`. <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace OGL.Models { public class Category { [Key] [Display(Name = "Id")] public int Id { get; set; } [Display(Name = "Category name")] [Required] public string Name { get; set; } [Display(Name = "Parent id")] [Required] public int ParentId { get; set; } #region SEO [Display(Name = "Title in Google")] [MaxLength(72)] public string MetaTitle { get; set; } [Display(Name = "Description in Google")] [MaxLength(160)] public string MetaDescription { get; set; } [Display(Name = "Tags for Google")] [MaxLength(160)] public string MetaTags { get; set; } [Display(Name = "Page content")] [MaxLength(500)] public string Content { get; set; } #endregion public virtual ICollection<Advertisement_Category> Advertisement_Category { get; set; } public Category() { Advertisement_Category = new HashSet<Advertisement_Category>(); } } }<file_sep>using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System.Data.Entity.ModelConfiguration.Conventions; namespace OGL.Models { public class OglContext : IdentityDbContext { public DbSet<Category> Category { get; set; } public DbSet<Advertisement> Advertisement { get; set; } public DbSet<ApplicationUser> ApplicationUser { get; set; } public DbSet<Advertisement_Category> Advertisement_Category { get; set; } public OglContext() : base("DefaultConnection") { } public static OglContext Create() { return new OglContext(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // disable auto tables rename when generating database from code model modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); // disable default cascade delete and configure fluent api modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); modelBuilder.Entity<Advertisement>() .HasRequired(x => x.ApplicationUser) .WithMany(x => x.Advertisement) .HasForeignKey(x => x.ApplicationUserId) .WillCascadeOnDelete(true); } } }
613a2b80cbc28454fb70b3625f232e9445e68694
[ "C#", "Markdown" ]
4
C#
gabr/OGL
ca21d373f14ec505099cde4b9e98564cd4b3a311
34e048b8b01c8f163ae8c1ef9ae25d98970af47f
refs/heads/master
<file_sep>#!/usr/bin/env bash ssserver -m chacha20-ietf-poly1305 \ -p 443 \ -k password \ $* <file_sep># docker-shadowsocks A light shadowsocks server. ``` # docker run -d \ --restart=always \ -p <outport>:443 \ abreto/shadowsocks[ -k <password>][ --workers <workers>] ``` <file_sep># Shadowsocks FROM ubuntu LABEL maintainer="Abreto<<EMAIL>>" RUN apt-get update && apt-get install -qy \ git \ python-pip \ python-pysodium RUN pip install git+https://github.com/shadowsocks/shadowsocks.git@master WORKDIR /bootstrap COPY entrypoint.sh . EXPOSE 443 ENTRYPOINT [ "bash", "entrypoint.sh" ]
37d78fce9ea4dd74a523c6d8c643718bce8e6723
[ "Markdown", "Shell", "Dockerfile" ]
3
Markdown
Abreto/docker-shadowsocks
a649b2227d35b20f662e92b1c2bbd34588309fbc
6f61d4759c29d4d208bd22c7eb4adc32908189c1
refs/heads/master
<repo_name>oriyanh/Bridge-AI<file_sep>/trick.py from copy import copy from typing import Dict, KeysView, ValuesView, ItemsView from cards import Suit, Card from players import POSITIONS, Player, PositionEnum class Trick: """ A set of 4 cards played by each player in turn, during the play of a deal. """ def __init__(self, trick, starting_suit=None): self.trick: Dict[Player, Card] = trick self.starting_suit = starting_suit # type: Suit def __len__(self): return len(self.trick) def __copy__(self): trick = Trick({}) for player, card in self.trick.items(): trick.add_card(copy(player), card) return trick def create_from_other_players(self, players): new_trick = Trick({}, self.starting_suit) if self.trick is None: return new_trick for player in players: card = self.trick.get(player) if card: new_trick.add_card(player, card) return new_trick def players(self) -> KeysView[Player]: """ Get all players with cards in current trick. :return: Iterable of all players. """ return self.trick.keys() def cards(self) -> ValuesView[Card]: """ Get all cards in current trick. :return: Iterable of all cards. """ return self.trick.values() def items(self) -> ItemsView[Player, Card]: """ Get all pairs of players and their cards in current trick. :return: Iterable of all pairs. """ return self.trick.items() def add_card(self, player: Player, card: Card) -> None: """ Add player's action to trick. :param player: The player placing the action. :param card: The action being played. :return: None """ assert (player not in self.trick) if not self.trick: self.starting_suit = card.suit self.trick[player] = card def get_card(self, player: Player) -> Card: """ Get the action that a player played. :param player: The player who's action in wanted. :return: The played action. """ return self.trick.get(player) def get_winner(self) -> PositionEnum: """ If all players played - return player with highest action. :return: Winning player. """ assert (len(self.trick) == len(POSITIONS)) relevant_players = [] for player, card in self.items(): if card.is_trump or card.suit == self.starting_suit: relevant_players.append(player) return max(relevant_players, key=self.trick.get).position def reset(self) -> None: """ Reset trick. :return: None """ self.trick: Dict[Player, Card] = {} self.starting_suit = None <file_sep>/README.md # Double Dummy Bridge Solver In this project we try to create a sophisticated computer agent to play the Contact Bridge card game. Our goal is to develop an agent that is tough to play against, with fast reaction time so it is able to play in real time against humans. We approached this as a search problem, and implemented search-tree heuristics based on Minimax and Monte Carlo Tree Search.<br> Implemented as a final project for the "Introduction to Aritifical Intelligence" course of the Hebrew University of Jerusalem.<br> # Running Instructions * Create a `virtualenv` with `python3.7` - `virtualenv -p python3.7 venv` * Activate virtual environment - `source venv/bin/activate.csh` if using `tcsh`; if using `bash`, use `source venv/bin/activate` * `pip install -r requirements.txt` to install project dependencies. * To run a match, run `python3.7 match.py --agent1 <agent arguments> --agent2 <agent arguments> --num_games <int> --verbose_mode <0/1>` where each agent encoding is of the form described in match.py’s documentation. * When done, run `deactivate` to deactivate the virtual environment We encourage you to try and run match.py with some of the following arguments preferably from a console outside of an IDE (during the game press the Enter key to perform the next action): Simple vs Simple: * `--agent1 Random --agent2 Random` * `--agent1 HighestFirst --agent2 SoftLongGreedy` AlphaBeta vs Simple: * `--agent1 AlphaBeta-ShortGreedyEvaluation-5 --agent2 LowestFirst` * `--agent1 AlphaBeta-LongGreedyEvaluation-10 --agent2 Random` * `--agent1 AlphaBeta-HandEvaluation-5 --agent2 HighestFirst` * `--agent1 AlphaBeta-CountOfTricksWon-10 --agent2 HighestFirst` MCTS vs Simple: * `--agent1 MCTS-simple-HardLongGreedy-50 --agent2 HardShortGreedy` * `--agent1 MCTS-stochastic-Random-500 --agent2 SoftShortGreedy` * `--agent1 MCTS-pure-LowestFirst-250 --agent2 Random` If you wish to run games automatically without seeing each game state and without pressing Enter after each move, add the argument “--verbose_mode 0”. For more arguments, refer to `match.py`. <br> # Authors * <NAME> * <NAME> * <NAME> * <NAME> <br> <file_sep>/match.py """ run with the following arguments: --agent1 <agent> --agent2 <agent> --num_games <int> Where each agent encoding is of in one of the following forms: Simple-<simple_agent_names> AlphaBeta-<ab_evaluation_agent_names>-<depth> MCTS-<'simple'/'stochastic'/'pure'>-<simple_agent_names>-<num_simulations> Human Optional arguments: --name_games - defaults to 100 --verbose_mode - if 0, will only print end result of match with no user interaction. If 1, enter interactive mode. --seed - if a number >= 0, set random seed of match for reproducibility. Else, use system default value. """ import os import sys import numpy as np from argparse import ArgumentParser, ArgumentTypeError from time import perf_counter from tqdm import tqdm from game import Game from multi_agents import * from trick import Trick class Match: """ Represents a series of games of bridge, with same opponents.""" def __init__(self, agent: IAgent, other_agent: IAgent, num_games: int, verbose_mode: bool = True, cards_in_hand: int = 13): self.agent = agent self.other_agent = other_agent self.num_games = num_games self.verbose_mode = verbose_mode self.cards_in_hand = cards_in_hand self.games_counter: List[int] = [0, 0, ] # [Team 0, Team 1] def __str__(self): ret = "" ret += f"Total score: " \ f"{self.games_counter[0]:02} - {self.games_counter[1]:02}\n" return ret def run(self) -> None: """ Main match runner. :return: None """ start_t = perf_counter() for _ in tqdm(range(self.num_games), leave=False, disable=self.verbose_mode, file=sys.stdout): curr_game = create_game(self.agent, self.other_agent, self.games_counter, self.verbose_mode, cards_in_hand=self.cards_in_hand) curr_game.run() self.games_counter[curr_game.winning_team] += 1 end_t = perf_counter() if self.verbose_mode: os.system('clear' if 'linux' in sys.platform else 'cls') print(self) print(self) print(f"Total time for match: {end_t - start_t} seconds; " f"Average {(end_t - start_t) / float(self.num_games)} " f"seconds per game") def create_game(agent, other_agent, games_counter, verbose_mode, from_db=False, cards_in_hand=13): """ Returns Game object, either new random game or a game initialized from game DB""" if from_db: pass # todo(maryna): create single game from db. pay attention to players # initialization + the iterator. trick_counter = [0, 0, ] # [Team 0, Team 1] previous_tricks = [] game = Game(agent, other_agent, games_counter, trick_counter, verbose_mode, previous_tricks, Trick({}), cards_in_hand=cards_in_hand) return game def parse_args(): """ Parses command line arguments. Returns namespace of arguments.""" parser = ArgumentParser() parser.add_argument('--agent1', required=True) parser.add_argument('--agent2', required=True) parser.add_argument('--num_games', type=int, default=100) parser.add_argument('--cards_in_hand', type=int, default=13) parser.add_argument('--verbose_mode', type=int, default=1) parser.add_argument('--seed', type=int, default=-1) return parser.parse_args() def str_to_agent(agent_str): agent_str = agent_str.split('-') if agent_str[0] == "Simple": # Simple agent if agent_str[1] in simple_agent_names: return SimpleAgent( simple_func_names[simple_agent_names.index( agent_str[1])]) else: print("Bad arguments for Simple agent. Should be:\n" "Simple-<agent name>") return -1 elif agent_str[0] == "AlphaBeta": # AlphaBeta agent if agent_str[1] in simple_agent_names: return AlphaBetaAgent( evaluation_function=ab_evaluation_func_names[ ab_evaluation_agent_names.index(agent_str[1])], depth=int(agent_str[2])) else: print("Bad arguments for AlphaBeta agent. Should be:\n" "AlphaBeta-<ab_evaluation_agent_names>-<depth>") return -1 elif agent_str[0] == "MCTS": # MCTS agent if agent_str[1] == 'simple': return SimpleMCTSAgent( action_chooser_function=simple_func_names[ simple_agent_names.index(agent_str[2])], num_simulations=int(agent_str[3])) elif agent_str[1] == 'stochastic': return StochasticSimpleMCTSAgent( action_chooser_function=simple_func_names[ simple_agent_names.index(agent_str[2])], num_simulations=int(agent_str[3])) elif agent_str[1] == 'pure': return PureMCTSAgent( action_chooser_function=simple_func_names[ simple_agent_names.index(agent_str[2])], num_simulations=int(agent_str[3])) else: print("Bad arguments for MCTS agent. Should be:\n" "MCTS-<'simple'/'stochastic'/'pure'>-" "<simulated agent name>-<num_of_simulations>") return -1 elif agent_str[0] == "Human": # Human agent return HumanAgent() else: raise ArgumentTypeError() def run_match(): try: a0 = str_to_agent(args.agent1) a1 = str_to_agent(args.agent2) except ArgumentTypeError: print("ArgumentTypeError: Bad arguments usage", file=sys.stderr) print(f"USAGE: run with the following arguments - ", file=sys.stderr) print(" python3.7 match.py --agent1 <agent> --agent2 <agent> [--cards_in_hand <int> --num_games <int> --verbose_mode <int> --seed <int>]\n" "Where each agent encoding is of in one of the following forms:\n" "* Simple-<simple_agent_names>\n" "* AlphaBeta-<ab_evaluation_agent_names>-<depth>\n" "* MCTS-<'simple'/'stochastic'/'pure'>-<simple_agent_names>-<num_simulations>\n" "* Human", file=sys.stderr) exit(1) match = Match(agent=a0, other_agent=a1, num_games=args.num_games, verbose_mode=bool(args.verbose_mode), cards_in_hand=args.cards_in_hand) match.run() if __name__ == '__main__': args = parse_args() if args.seed >= 0: np.random.seed(args.seed) run_match() input("Press Enter button to exit") <file_sep>/multi_agents.py import numpy as np from abc import ABC, abstractmethod from collections import defaultdict from concurrent.futures.thread import ThreadPoolExecutor from copy import copy from queue import Queue from typing import Dict, List, Set from cards import Card from game import SimulatedGame from players import is_players_in_same_team, get_legal_actions, PLAYERS_CYCLE from state import State simple_func_names = [ 'highest_first_action', 'lowest_first_action', 'random_action', 'hard_short_greedy_action', 'hard_long_greedy_action', 'soft_short_greedy_action', 'soft_long_greedy_action', ] simple_agent_names = [ 'HighestFirst', 'LowestFirst', 'Random', 'HardShortGreedy', 'HardLongGreedy', 'SoftShortGreedy', 'SoftLongGreedy', ] ab_evaluation_func_names = [ 'greedy_evaluation_function1', 'greedy_evaluation_function2', 'hand_evaluation_heuristic', 'count_tricks_won_evaluation_function', ] ab_evaluation_agent_names = [ 'ShortGreedyEvaluation', 'LongGreedyEvaluation', 'HandEvaluation', 'CountOfTricksWon', ] def lookup(name, namespace): """ Get a method or class from any imported module from its name. Usage: lookup(functionName, globals()) :returns: method/class reference :raises Exception: If the number of classes/methods existing in namespace with name is != 1 """ dots = name.count('.') if dots > 0: module_name, obj_name = '.'.join(name.split('.')[:-1]), name.split('.')[-1] module = __import__(module_name) return getattr(module, obj_name) else: modules = [obj for obj in namespace.values() if str(type(obj)) == "<type 'module'>"] options = [getattr(module, name) for module in modules if name in dir(module)] options += [obj[1] for obj in namespace.items() if obj[0] == name] if len(options) == 1: return options[0] if len(options) > 1: raise Exception('Name conflict for %s') raise Exception('%s not found as a method or class' % name) class IAgent(ABC): """ Interface for bridge-playing agents.""" @abstractmethod def __init__(self, target): self.target = target # TODO [oriyan] Not completely sure what this should be - # it is only used in one place compared to a player's score. # Do we need this? Investigate later. @abstractmethod def get_action(self, state: State) -> Card: """ Pick a action to play based on the environment and a programmed strategy. :param state: :return: The action to play. """ raise NotImplementedError # ------------------------------------SimpleAgent------------------------------------- # class SimpleAgent(IAgent): """ Deterministic agent that plays according to input action.""" def __init__(self, action_chooser_function='random_action', target=None): """ :param str action_chooser_function: name of action to take, or a function. Function should map State -> Card :param target: See comment in IAgent's constructor """ if isinstance(action_chooser_function, str): self.action_chooser_function = lookup(action_chooser_function, globals()) else: self.action_chooser_function = action_chooser_function super().__init__(target) def get_action(self, state): return self.action_chooser_function(state) def random_action(state): """ Picks random action. :param State state: :returns Card: action to take """ return np.random.choice(state.get_legal_actions()) def lowest_first_action(state): """ Always picks the lowest value action. :param State state: :returns Card: action to take """ return min(state.get_legal_actions()) def highest_first_action(state): """ Always picks the highest value action :param State state: :returns Card: action to take """ return max(state.get_legal_actions()) def hard_short_greedy_action(state): """ If can beat current trick cards - picks highest value action available. If cannot - picks lowest value action. :param State state: :returns Card: action to take """ legal_moves = state.get_legal_actions() best_move = max(legal_moves) if len(state.trick) == 0: # Trick is empty - play best action. return best_move best_in_current_trick = max(state.trick.cards()) worst_move = min(legal_moves) if best_move > best_in_current_trick: # Can be best in current trick. return best_move else: # Cannot win - play worst action. return worst_move def hard_long_greedy_action(state): """ If can beat current trick cards - picks highest value action available. If cannot - picks lowest value action. :param State state: :returns Card: action to take """ legal_moves = state.get_legal_actions() best_move = max(legal_moves) worst_move = min(legal_moves) # pick a first card in trick that possibly could lead to win if len(state.trick) == 0: # Trick is empty - play best action. cards = starting_trick_cards(state) if len(cards) > 0: return max(cards) return worst_move best_in_current_trick = max(state.trick.cards()) # if there are cards in the trick- try to play a winning card against the hands of the # opponent and the cards in the trick op_cards = get_opponents_legal_card(state) if op_cards is not None: opponent_best = max(op_cards) card_to_win = max([opponent_best, best_in_current_trick]) if best_move > card_to_win: return best_move # if the opponent has no legal card, try to get the trick elif best_move > best_in_current_trick: return best_move # Cannot win - play worst action. return worst_move def soft_short_greedy_action(state): """ If can beat current trick cards - picks the lowest value action available that can become the current best in trick. If cannot - picks lowest value action. :param State state: :returns Card: action to take """ legal_moves = state.get_legal_actions() worst_move = min(legal_moves) best_move = max(legal_moves) if len(state.trick) == 0: # Trick is empty - play worst action. return worst_move best_in_current_trick = max(state.trick.cards()) if best_move > best_in_current_trick: # Can be best in current trick. weakest_wining_move = min(filter(lambda move: move > best_in_current_trick, legal_moves)) return weakest_wining_move return worst_move # Cannot win - play worst action. def soft_long_greedy_action(state): """ If can beat current trick cards - picks the lowest value action available that can become the current best in trick. If cannot - picks lowest value action. :param State state: :returns Card: action to take """ legal_moves = state.get_legal_actions() worst_move = min(legal_moves) best_move = max(legal_moves) # pick a first card in trick that possibly could lead to win if len(state.trick) == 0: # Trick is empty - play worst action. cards = starting_trick_cards(state) if len(cards) > 0: return min(cards) return worst_move best_in_current_trick = max(state.trick.cards()) # if there are cards in the trick- try to play a winning card against the hands of the # opponent and the cards in the trick op_cards = get_opponents_legal_card(state) if op_cards is not None: opponent_best = max(op_cards) card_to_win = max([opponent_best, best_in_current_trick]) wining_moves = list(filter(lambda move: move > card_to_win, legal_moves)) if len(wining_moves) > 0: return min(wining_moves) # if the opponent has no legal card, try to get the trick elif best_move > best_in_current_trick: weakest_wining_move = min(filter(lambda move: move > best_in_current_trick, legal_moves)) return weakest_wining_move # Cannot win - play worst action. return worst_move def get_opponents_legal_card(state): """ used unly in case the trick is initialized and the current player in the trick has an opponent that will play the trick later. :param state: :return: the cards of the opponent of the current player """ i = len(state.trick) op_cards = None if i == 1 or i == 2: opponent = state.players_pos[PLAYERS_CYCLE[state.curr_player.position]] op_cards = get_legal_actions(state.trick.starting_suit, opponent, state.already_played) return op_cards def starting_trick_cards(state): """ pick the cards for openning the trick, trying to win it. The list will hold the following cards: If current player has a winning card against all other hands of player. If the teammate of the current player has a winning card of a suit the current player will play If the other players has no cards in the suit If the other teammate doesn't have cards in suit but can win against other trumps :param state: :return: """ curr_player_moves = state.get_legal_actions() # all opponent's hands united to single list of cards to observe opp_reg_cards, opp_trump_cards, teammate_reg_cards, teammate_trump_cards = \ get_hand_trump_opponent_teammate(state) cards = [] for card in curr_player_moves: # the opponent has cards of the current suit. trump cards are part of legal cards, # hence the highest card is both from the suit or from trump card. if opp_reg_cards.get(card.suit.suit_type) is not None: best_curr = card if len(teammate_trump_cards) > 0: best_curr = max([teammate_trump_cards[-1], card]) if teammate_reg_cards.get(card.suit.suit_type): best_curr = max([teammate_reg_cards[card.suit.suit_type][-1], best_curr]) best_opp = opp_reg_cards[card.suit.suit_type][-1] if len(opp_trump_cards) > 0: best_opp = max(best_opp, opp_trump_cards[-1]) # if the best card of curr team is winning against the strongest legal card of the # opponent- the card suggested to open the trick if best_curr > best_opp: cards.append(card) else: # the opponent has no cards of the suit. hence he will play trump card or a card # from other suit. only trump card could possibly win the trick if len(teammate_trump_cards) > 0: if len(opp_trump_cards) > 0: best_curr = teammate_trump_cards[-1] best_opp = opp_trump_cards[-1] if best_curr > best_opp: cards.append(card) else: cards.append(card) else: if not len(opp_trump_cards) > 0: cards.append(card) return cards def get_hand_trump_opponent_teammate(state): opp1 = state.players_pos[PLAYERS_CYCLE[state.curr_player.position]] teammate = state.players_pos[PLAYERS_CYCLE[opp1.position]] opp2 = state.players_pos[PLAYERS_CYCLE[teammate.position]] # the following hands are sorted. 1st card is the smallest opp1_reg_cards, opp1_trump_cards = opp1.hand.get_cards_sorted_by_suits(state.already_played) opp2_reg_cards, opp2_trump_cards = opp2.hand.get_cards_sorted_by_suits(state.already_played) opp1_reg_cards.update(opp2_reg_cards) opp_reg_cards = opp1_reg_cards opp_trump_cards = opp1_trump_cards + opp2_trump_cards teammate_reg_cards, teammate_trump_cards = teammate.hand.get_cards_sorted_by_suits( state.already_played) return opp_reg_cards, opp_trump_cards, teammate_reg_cards, teammate_trump_cards def add_randomness_to_action(func, epsilon): """ Wraps a `State->Card` function with a randomizing factor - w.p. epsilon, action is chosen at random. :param func: `State->Card` function :param float epsilon: Probability of choosing action at random. In range [0,1] :returns: Function mapping `State->Card` with additional randomizing factor """ def randomized_action(state): if np.random.rand() < epsilon: return random_action(state) return func(state) return randomized_action # ---------------------------MultiAgentSearchAgent--------------------------- # class MultiAgentSearchAgent(IAgent): """Abstract agent implementing IAgent that searches a game tree""" def __init__(self, evaluation_function='score_evaluation_function', depth=2, target=None): """ :param evaluation_function: function mapping (State, *args) -> Card , where *args is determined by the agent itself. :param int depth: -1 for full tree, any other number > 1 for depth bounded tree :param target: """ self.evaluation_function = lookup(evaluation_function, globals()) self.depth = depth super().__init__(target) def get_action(self, state): return NotImplementedError class AlphaBetaAgent(MultiAgentSearchAgent): """ Agent implementing AlphaBeta pruning (with MinMax tree search)""" def __init__(self, evaluation_function='count_tricks_won_evaluation_function', depth=2, target=None): super().__init__(evaluation_function, depth, target) def get_action(self, state): legal_moves = state.get_legal_actions() successors = [state.get_successor(action=action) for action in legal_moves] if self.depth == 0: scores = [self.evaluation_function(successor) for successor in successors] best_score = max(scores) best_indices = [index for index in range(len(scores)) if scores[index] == best_score] chosen_index = np.random.choice(best_indices) # Pick randomly among the best return legal_moves[chosen_index] else: a, b = -np.inf, np.inf chosen_index = 0 for i, successor in enumerate(successors): next_child_score = self.score(successor, self.depth, 1, False, a, b) if next_child_score > a: chosen_index = i a = next_child_score if b <= a: break return legal_moves[chosen_index] def score(self, state, max_depth, curr_depth, is_max, a, b): """ Recursive method returning score for current state (the node in search tree). :param State state: State of game :param int max_depth: Max tree depth to search :param int curr_depth: Current depth in search tree :param bool is_max: True if current player is Max player, False if Min player :param float a: Current alpha score :param float b: Current beta score :returns float: Score for current state (the node) """ if curr_depth >= max_depth: return self.evaluation_function(state, is_max, self.target) # get current player moves curr_player = state.curr_player legal_moves = state.get_legal_actions() if not legal_moves: return self.evaluation_function(state, is_max, self.target) possible_states = [state.get_successor(action=action) for action in legal_moves] if is_max: for next_state in possible_states: next_player = next_state.curr_player is_next_max = True if is_players_in_same_team(curr_player, next_player) else False next_depth = curr_depth if is_next_max else curr_depth + 1 if not is_next_max: b = min((b, self.score(next_state, max_depth, next_depth, is_next_max, a, b))) else: a = max((a, self.score(next_state, max_depth, next_depth, is_next_max, a, b))) if b <= a: break return a for next_state in possible_states: next_player = next_state.curr_player is_next_max = False if is_players_in_same_team(curr_player, next_player) else True next_depth = curr_depth + 1 if is_next_max else curr_depth if is_next_max: a = max((a, self.score(next_state, max_depth, next_depth, is_next_max, a, b))) else: b = min((b, self.score(next_state, max_depth, next_depth, is_next_max, a, b))) if b <= a: break return b def is_target_reached_evaluation_function(state, is_max=True, target=None): """ Score of state is 1 if current player is Max player and target has been reached. 0 Otherwise. :param State state: game state :param bool is_max: is max player :param target: :returns float: score of state """ if not target: return 0 # if max return True if met the score of the team of the current player # else return if the opposite team met the required score player_score = state.get_score(is_max) if target <= player_score: return 1 return 0 def count_tricks_won_evaluation_function(state, is_max=True, target=None): """ weighted score of current state with respect to is_max, and number of tricks this player has won. :param State state: game state :param bool is_max: is max player :param target: :returns float: score of state """ return state.get_score(is_max) def greedy_evaluation_function1(state, is_max=True, target=None): """ returns a value for the gives state, calculated by count of legal moves of the current player, ignoring the hands of other players. :param State state: game state :param bool is_max: is max player :param target: :returns float: score of state """ value = state.get_score(is_max) if len(state.trick) == 0: # Trick is empty - play worst action. return value greedy_moves_count = greedy_legal_moves_count1(state) return 13 * value + greedy_moves_count def greedy_evaluation_function2(state, is_max=True, target=None): """ returns a value for the gives state, calculated by count of legal winning moves by observing the hands of all the players in the game. :param State state: game state :param bool is_max: is max player :param target: :returns float: score of state """ value = state.get_score(is_max) greedy_moves_count = greedy_legal_moves_count2(state) return 13 * value + greedy_moves_count def greedy_legal_moves_count1(state): legal_moves = state.get_legal_actions() best_move = max(legal_moves) best_in_current_trick = max(state.trick.cards()) if best_move > best_in_current_trick: # Can be best in current trick. count_wining_moves = len(list(filter(lambda move: move > best_in_current_trick, legal_moves))) return count_wining_moves return 0 def greedy_legal_moves_count2(state): legal_moves = state.get_legal_actions() wining_moves_count= 0 i = len(state.trick) if i == 0: cards = starting_trick_cards(state) wining_moves_count = 1 if len(cards) > 0 else 0 else: best_in_current_trick = max(state.trick.cards()) if i == 1 or i == 2: opponent_legal_cards = get_opponents_legal_card(state) opponent_best = max(opponent_legal_cards) card_to_win = max([opponent_best, best_in_current_trick]) wining_moves = list(filter(lambda move: move > card_to_win, legal_moves)) teammate = state.players_pos[PLAYERS_CYCLE[PLAYERS_CYCLE[state.curr_player.position]]] teammate_legal_moves = get_legal_actions(state.trick.starting_suit, teammate, state.already_played) teammate_wining_moves = list(filter(lambda move: move > card_to_win, teammate_legal_moves)) wining_moves_count = 2 * len(wining_moves) + len(teammate_wining_moves) wining_moves_count = 1 if wining_moves_count > 0 else 0 if i == 3: best_move = max(legal_moves) if best_move > best_in_current_trick: wining_moves_count = len(list(filter(lambda move: move > best_in_current_trick, legal_moves))) wining_moves_count = 1 if wining_moves_count > 0 else 0 return wining_moves_count def hand_evaluation_heuristic(state, is_max=True, target=None): """ returns the value of the hand, evaluated by giving highest value for each card, and taking advantage of hands containing more cards of a same suit. :param state: :param is_max: :param target: :return: """ value = state.get_score(is_max) hand_value = state.curr_player.hand.get_hand_value(state.already_played) return 13 * value + hand_value # ---------------------------------MCTSAgent--------------------------------- # class SimpleMCTSAgent(IAgent): """ Agent implementing simplified version of MCTS - only looks at end-results of simulation, without backpropogation. Our agent's local decision rule is decided by `action_chooser_function`, while the opponent's local decisions are chosen randomly.""" def __init__(self, action_chooser_function='random_action', num_simulations=100): """ :param str action_chooser_function: See `super().__init__()` docstring :param int num_simulations: How many simulations for rollout """ self.action_chooser_function = lookup(action_chooser_function, globals()) self.num_simulations_total = 0 self.action_value = defaultdict(lambda: 0) # type: Dict[Card, int] # Maps values of playable actions self.num_simulations = num_simulations self.executor = ThreadPoolExecutor() super().__init__(None) def get_action(self, state): action = self.rollout(state, self.num_simulations) return action def rollout(self, state, num_simulations): """ Performs `num_simulations` rollouts - i.e. stochastically simulate `num_simlations` games. :param State state: Current state of the game :param int num_simulations: How many games to simulate. Our agent's choices are made according to `action_chooser_function` while the opoonent's are chosen randomly. :returns Card: Best action """ legal_actions = state.get_legal_actions() rollout_actions = np.random.choice(legal_actions, # Pre-select initial actions size=num_simulations, replace=True) best_action = np.random.choice(legal_actions) # Simulate games on separate threads games = [SimulatedGame(SimpleAgent(self.action_chooser_function), SimpleAgent('random_action'), False, state, action) for action in rollout_actions] futures = [self.executor.submit(game.run) for game in games] futures_queue = Queue(num_simulations) for future in futures: futures_queue.put(future) # Poll threads for termination. Each future's return value is a boolean. while not futures_queue.empty(): future = futures_queue.get() futures_queue.task_done() if future.running(): futures_queue.put(future) else: assert future.result() # Collect results for game in games: assert game.winning_team != -1 winning_team = game.teams[game.winning_team] if winning_team.has_player(state.curr_player): self.action_value[game.starting_action] += 1 self.num_simulations_total += 1 # Choose best action for action in legal_actions: best_action = action if self.action_value[action] > self.action_value[best_action] \ else best_action return best_action class StochasticSimpleMCTSAgent(SimpleMCTSAgent): """ Same as `SimpleMCTSAgent`, but with randomness injected into our agent's choices within simulations.""" def __init__(self, action_chooser_function='random_action', num_simulations=100, epsilon=0.1): """ :param action_chooser_function: See `super().__init__()` docstring :param num_simulations: See `super().__init__()` docstring :param float epsilon: Value in range [0,1]. w.p. `epsilon` our agent chooses random action. """ assert 0 <= epsilon <= 1 super().__init__(action_chooser_function, num_simulations) self.epsilon = epsilon self.action_chooser_function = add_randomness_to_action(self.action_chooser_function, self.epsilon) class PureMCTSAgent(SimpleMCTSAgent): """ Implements the full MCTS algorithm, in context of Bridge.""" def __init__(self, action_chooser_function='random_action', num_simulations=100): """ :param str action_chooser_function: See `super().__init__()` docstring :param int num_simulations: How many simulations for rollout """ self.action_chooser_function = lookup(action_chooser_function, globals()) super().__init__(action_chooser_function, num_simulations) # self.root = None # type: MCTSNode self.root = None # type: MCTSNode def get_action(self, state): if not state.prev_tricks: # New game, first play for current player, create new root # self.roots[state.curr_player] = MCTSNode(state) self.root = MCTSNode(state) else: # Need to remove impossible paths from tree self.prune_tree(state) # Prepare tree for evaluation of best move # root = self.roots[state.curr_player] root = self.root for _ in range(0, self.num_simulations): # Exploration stage expanded_node = self.explore(root) # Rollout stage reward = expanded_node.rollout() # Backpropogation stage expanded_node.backpropagate(reward) # Exploitation stage best_child = root.best_child(uct_param=1.4) best_action = best_child.parent_action return best_action def prune_tree(self, state): """ Removes unreachable paths from tree, and updates root node. :param State state: current game state """ if not state.prev_tricks: # new game, no need for pruning return # Evaluates plays since last time current player played prev_trick = state.prev_tricks[-1] curr_trick = state.trick actions = [] for player in state.players: action = prev_trick.get_card(player) if not action: action = curr_trick.get_card(player) assert action is not None actions.append(action) current_root = self.root next_root = None # Traverse tree according to order of play. # Tree may not contain this path due to nature of MCTS, in which case we create a new tree. for child in current_root.children: if child.parent_action in actions: next_root = child break if next_root is None: self.root = MCTSNode(state) return current_root = next_root actions.remove(current_root.parent_action) next_root = None for child in current_root.children: if child.player_pos == state.curr_player.position \ and child.parent_action in actions: next_root = child break if next_root is None: # This means the last move did not lead to current player, # so we need to create a new tree self.root = MCTSNode(state) return # This path exists in old tree, make this node the root, # and eliminate illegal paths current_root = next_root assert current_root.player_pos == state.curr_player.position self._make_root_node(current_root, state) def _make_root_node(self, node, state): """ Updates `player`'s root node to be `node`. :param MCTSNode node: New root for `player` :param Player player: Player whose root we are changing :param State state: Current game state """ node.parent_action = None node.parent = None new_children = [] for child in node.children: if child.parent_action not in state.already_played: new_children.append(child) node.children = new_children untried_actions = set() tried_actions = set() for action in node.untried_actions: if action not in state.already_played: untried_actions.add(action) else: tried_actions.add(action) node._untried_actions = untried_actions node._tried_actions.update(tried_actions) self.root = node def explore(self, root): """ Explores tree, choosing a leaf node for rollout stage. Expands leaf node if not terminal. :param MCTSNode root: Root to explore :returns MCTSNode: node on which to perform rollout """ current_node = root while not current_node.is_terminal: if not current_node.is_fully_expanded: return current_node.expand() else: current_node = current_node.best_child() return current_node class MCTSNode: """ Node in search tree for Pure MCTS""" def __init__(self, state, parent=None, parent_action=None, action_chooser_func='random_action'): """ :param State state: current game state :param MCTSNode parent: Parent of node. If None, this node is assumed to be a root node. :param Card parent_action: If `parent` is not None, this is the action made by parent that lead to this node. Else, value is ignored. :param str action_chooser_function: See `super().__init__()` docstring """ if isinstance(action_chooser_func, str): self.action_chooser_func = lookup(action_chooser_func, globals()) else: self.action_chooser_func = action_chooser_func self.state = copy(state) self.parent = parent self.children = [] if not self.parent: # Is root node self.parent_action = None if self.state.teams[0].has_player(self.state.curr_player): self.team = self.state.teams[0] else: self.team = self.state.teams[1] else: self.team = parent.team self.parent_action = parent_action self._number_of_visits = 0. self._results = defaultdict(lambda: 0) # type: Dict[int, int] # maps team# to no. of wins self._untried_actions = None # type: Set[Card] self._tried_actions = set() # type: Set[Card] self.max_player = 1 if self.team.has_player(self.state.curr_player) else -1 self.player_pos = state.curr_player.position def best_child(self, uct_param=1.4): """ Returns child node with best UCT upper bound value :param float uct_param: Scaling factor for UCT value calculation. Default 1.4 ~ sqrt(2) :returns MCTSNode: best child node """ choices_weights = [self.UCT_value(child, uct_param) for child in self.children] child_idx = int(np.argmax(choices_weights)) return self.children[child_idx] def UCT_value(self, node, uct_param): """ Calculates UCT value for node :param MCTSNode node: node for calculation :param float uct_param: Scaling factor for UCT value calculation :returns float: UCT value """ return (node.q_value / node.num_visits) + \ uct_param * np.sqrt((2 * np.log(self.num_visits) / node.num_visits)) def rollout_policy(self, possible_moves): """ Chooses "arm" of root node on which to perform rollout ("arm" as in the "Multi armed bandit" problem). Action is chosen at random. :param List[Card] possible_moves: List of "arms" :returns Card: chosen "arm", i.e. action to take for rollout """ return np.random.choice(possible_moves) @property def untried_actions(self) -> List[Card]: """ List of actions still unexplored""" if self._untried_actions is None: self._untried_actions = set(self.state.curr_player.hand.cards) return list(self._untried_actions.intersection(self.state.get_legal_actions())) @property def q_value(self) -> int: """ Difference between wins and losses count for current node""" wins = self._results[self.max_player] loses = self._results[-1 * self.max_player] return wins - loses @property def num_visits(self) -> float: """ Number of time node was visited, updated each rollout""" return self._number_of_visits def expand(self): """ Expands a child node that wasn't explored yet. Assumes not all children were explored. :returns MCTSNode: Child node for exploration """ action = self.untried_actions.pop() next_state = self.state.get_successor(action) assert action not in self.state.already_played assert action in self.state.curr_player.hand.cards child_node = MCTSNode(next_state, parent=self, parent_action=action) self.children.append(child_node) self._untried_actions.remove(action) self._tried_actions.add(action) return child_node @property def is_terminal(self) -> bool: """ Is current node a terminal node""" return self.state.is_game_over def rollout(self): """ Performs single rollout on current node - i.e. simulates a single game with current state as initial state. """ if self.is_terminal: reward = 1 if self.team.has_player(self.state.curr_player) else -1 return reward current_rollout_state = self.state possible_moves = current_rollout_state.get_legal_actions() action = self.rollout_policy(possible_moves) game = SimulatedGame(SimpleAgent(self.action_chooser_func), SimpleAgent('random_action'), False, current_rollout_state, action) assert game.run() winning_team_idx = game.winning_team winning_team = current_rollout_state.teams[winning_team_idx] reward = 1 if self.team == winning_team else -1 return reward @property def is_fully_expanded(self) -> bool: """ Whether all children of node were previously expanded""" return len(self.untried_actions) == 0 def backpropagate(self, result) -> None: """ Backpropogates result of single rollout up the tree. :param int result: 1 if max player won in rollout, -1 if min player won. """ self._number_of_visits += 1. self._results[result] += 1. if self.parent is not None: self.parent.backpropagate(result) # ---------------------------------HumanAgent-------------------------------- # class HumanAgent(IAgent): """ Ask user for action, in format of <face><suit>. <face> can be entered as a number or a lowercase/uppercase letter. <suit> can be entered as an ASCII of suit or a lowercase/uppercase letter. """ def __init__(self): super().__init__(self) def get_action(self, state): while True: inp = input() if inp == '': print(f"<EnterKey> is not a valid action, try again") continue try: card_suit, card_number = inp[:-1], inp[-1] action = Card(card_number, card_suit, state.trump) legal_moves = state.get_legal_actions() if action in legal_moves: return action else: print(f"{card_suit, card_number} " f"is not a legal card to play, try again") except ValueError or IndexError or TypeError: print(f"{inp} is not a valid action, try again") <file_sep>/players.py from copy import copy from enum import Enum from typing import List from cards import Hand, Card PositionEnum = Enum("PlayersEnum", ['N', 'E', 'S', 'W']) POSITIONS = list(PositionEnum) TEAMS = [(PositionEnum.N, PositionEnum.S), (PositionEnum.W, PositionEnum.E)] PLAYERS_CYCLE = {PositionEnum.N: PositionEnum.E, PositionEnum.E: PositionEnum.S, PositionEnum.S: PositionEnum.W, PositionEnum.W: PositionEnum.N} TEAMMATES = {PositionEnum.N: PositionEnum.S, PositionEnum.S: PositionEnum.N, PositionEnum.E: PositionEnum.W, PositionEnum.W: PositionEnum.E} class Player: """ Represents one of the 4 players in the game.""" def __init__(self, position: PositionEnum, hand: Hand): """ :param position: Position of player :param hand: Initial hand of player """ self.position = position self.hand = hand self.played = set() def __copy__(self): hand = copy(self.hand) player = Player(self.position, hand) player.played = set(self.played) return player def play_card(self, card: Card) -> None: """ Plays card from hand. card is no longer available.""" assert card not in self.played self.hand.play_card(card) self.played.add(card) def get_legal_actions(self, trick, already_played) -> List[Card]: """ Returns list of legal actions for player in current trick :param Trick trick: Current trick :param already_played: Set of cards already used in state, used for unit testing. :returns: legal actions for player: """ legal_actions = self.hand.get_cards_from_suite(trick.starting_suit, already_played) assert self.played.isdisjoint(legal_actions) assert already_played.isdisjoint(legal_actions) if not legal_actions: legal_actions = self.hand.cards assert already_played.isdisjoint(legal_actions) return legal_actions def __str__(self): return self.position.name def __eq__(self, other): return self.position == other.position def __hash__(self): return hash(self.position) def get_legal_actions(suit, player, already_played) -> List[Card]: legal_actions = player.hand.get_cards_from_suite(suit, already_played) if not legal_actions: legal_actions = player.hand.cards else: trump_cards = [card for card in player.hand.cards if card.is_trump] legal_actions.extend(trump_cards) return legal_actions class Team: """ Team of two players sitting on opposite sides of table.""" def __init__(self, p0: Player, p1: Player): self.players = [p0, p1] self.teammate = {p0.position: p1, # todo [ORIYAN] Possibly remove? p1.position: p0} # todo(maryna): maybe add the score directly into the team object? def __copy__(self): p0, p1 = self.players[0], self.players[1] copy_p0, copy_p1 = copy(p0), copy(p1) return Team(copy_p0, copy_p1) def __str__(self): return f"{self.players[0]}{self.players[1]}" def has_player(self, p: Player) -> bool: """ Is player `p` on the team """ return p in self.players def get_players(self) -> List[Player]: return self.players # more useful to be outside as static method. def get_teammate(self, p: Player) -> Player: assert (p in self.players) return self.teammate[p.position] def __hash__(self) -> int: return hash(frozenset(self.players)) def __eq__(self, other) -> bool: return frozenset(self.teammate.keys()).issubset(other.teammate.keys()) def is_players_in_same_team(p1: Player, p2: Player) -> bool: if (p1.position, p2.position) in TEAMS or (p2.position, p1.position) in TEAMS: return True return False <file_sep>/state.py from copy import copy from typing import Dict, List from cards import Card, TrumpType from players import PLAYERS_CYCLE, Player, Team from trick import Trick class State: """ Current state of the game of Bridge.""" def __init__(self, trick: Trick, teams: List[Team], players: List[Player], prev_tricks: List[Trick], score: Dict[Team, int], curr_player=None, trump: TrumpType=TrumpType.NT) -> None: self.trick = trick self.teams = teams self.players = players self.prev_tricks = prev_tricks self.score = score # tricks won by teams self.curr_player = curr_player self.players_pos = {player.position: player for player in self.players} self.already_played = set() self.trump = trump def get_successor(self, action: Card): """ :param action: Card to play :returns State: Resulting state of game if playing `action` """ assert (action in self.get_legal_actions()) teams = [copy(self.teams[i]) for i in range(len(self.teams))] score = {teams[i]: self.score[team] for i, team in enumerate(self.teams)} players = teams[0].get_players() + teams[1].get_players() trick = self.trick.create_from_other_players(players) curr_player = [p for p in players if p == self.curr_player][0] successor = State(trick, teams, players, self.prev_tricks, score, curr_player, trump=self.trump) successor.apply_action(action) return successor def apply_action(self, card: Card, is_real_game: bool = False) -> Trick: """ :param card: Action to apply on current state :param is_real_game: indicator to differentiate a state used in simulation of a game by the object Game, from a state used within tree search. :returns Trick: Trick status after applying card. """ assert (len(self.trick) < len(self.players_pos)) assert card not in self.already_played prev_num_cards = len(self.curr_player.hand.cards) self.curr_player.play_card(card) curr_num_cards = len(self.curr_player.hand.cards) assert prev_num_cards != curr_num_cards self.trick.add_card(self.curr_player, card) self.already_played.add(card) assert self.already_played.isdisjoint(self.curr_player.hand.cards) curr_trick = self.trick if len(self.trick) == len(self.players_pos): # last card played - open new trick if is_real_game: self.prev_tricks.append(copy(self.trick)) winner_position = self.trick.get_winner() self.curr_player = self.players_pos[winner_position] i = 0 if self.teams[0].has_player(self.curr_player) else 1 self.score[self.teams[i]] += 1 self.trick = Trick({}) else: assert self.curr_player in self.players_pos.values() assert self.curr_player in self.players # print(f"Mapping of position->next player: {repr(self.players_pos)}") self.curr_player = self.players_pos[PLAYERS_CYCLE[self.curr_player.position]] assert self.curr_player in self.players_pos.values() assert self.curr_player in self.players return curr_trick def get_legal_actions(self) -> List[Card]: legal_actions = self.curr_player.get_legal_actions(self.trick, self.already_played) assert self.already_played.isdisjoint(legal_actions) return legal_actions def get_score(self, curr_team_indicator) -> int: """ Returns score of team :param curr_team_indicator: if true return the score of the team of the current player, else return the score of the opposite player. used in alpha-beta search tree to indicate score of max-min players :returns: current score of team """ # assume there are 2 teams i, j = (0, 1) if self.teams[0].has_player(self.curr_player) else (1, 0) curr_team, other_team = self.teams[i], self.teams[j] if curr_team_indicator: return self.score[curr_team] return self.score[other_team] def __copy__(self): trick = copy(self.trick) prev_tricks = [copy(trick) for trick in self.prev_tricks] teams = [copy(team) for team in self.teams] score = {teams[0]: self.score[self.teams[0]], teams[1]: self.score[self.teams[1]]} players = [copy(player) for player in self.players] curr_player_pos = self.curr_player.position state = State(trick, teams, players, prev_tricks, score, None, trump=self.trump) state.curr_player = state.players_pos[curr_player_pos] played = set(self.already_played) state.already_played = played return state @property def is_game_over(self) -> bool: for player in self.players: if len(player.hand.cards) != 0: return False return True <file_sep>/validation.py import numpy as np from collections import defaultdict from copy import deepcopy from itertools import cycle, islice from typing import Tuple, List, TextIO from cards import Card, SUITS, SuitType, TrumpType, Hand from game import SimulatedGame from multi_agents import IAgent, SimpleAgent, AlphaBetaAgent from players import Player, PositionEnum, POSITIONS, PLAYERS_CYCLE, TEAMS, Team from state import State from trick import Trick np.seterr(divide='ignore', invalid='ignore') TEAMS_CYCLE = {TEAMS[0]: TEAMS[1], TEAMS[1]: TEAMS[0]} PLAYERS_DICT = {'N': 0, 'E': 1, 'S': 2, 'W': 3} class TrickValidation(Trick): """ Class of Trick, with added characteristic of order of cards given by remembering the starting player. """ def __init__(self): super().__init__({}) self.first_position = None def add_first_position(self, position: PositionEnum): self.first_position = position class DataGame: """ Class which stores a recorded game, with option to take a snapshot from any point in it. """ def __init__(self, players: List[Player], tricks: List[TrickValidation], winner: Tuple[PositionEnum], trump: TrumpType): self.players = players self.tricks = tricks self.winner = winner self.trump = trump def position_to_player(self, position: PositionEnum): for p in self.players: if p.position == position: return p else: raise ValueError("something wrong in self.players") def snapshot(self, trick_idx: int, position: PositionEnum) -> \ Tuple[List[Player], Trick, Card]: """ Image of one moment in game, in trick_idx trick, when player should play :param trick_idx: first trick is 0 :param position: the player to commit its turn now :return: current hands situation (ordered list of players), trick on desk and the chosen card (by player in given position). """ if trick_idx >= len(self.tricks): raise IndexError(f"trick_idx argument has to be smaller then " f"{len(self.tricks)}") # Load initial hands situation curr_hands = deepcopy(self.players) # Remove cards from all last tricks from hands for i in range(trick_idx): for j, p in enumerate(curr_hands): curr_hands[j].hand.play_card(self.tricks[i].trick[p]) # Remove cards of current trick from hands of all players which play # before given player. In addition, store these cards curr_pos = self.tricks[trick_idx].first_position curr_player = self.position_to_player(curr_pos) curr_trick = Trick({}) while curr_player.position != position: curr_hands[PLAYERS_DICT[curr_player.position.name]].play_card( self.tricks[trick_idx].trick[curr_player]) curr_trick.add_card( curr_player, self.tricks[trick_idx].trick[curr_player]) curr_player = self.players[PLAYERS_DICT[ PLAYERS_CYCLE[curr_player.position].name]] chosen_card = self.tricks[trick_idx].trick[curr_player] return curr_hands, curr_trick, chosen_card def all_relevant_snapshots(self) -> \ Tuple[List[List[Player]], List[Trick], List[Card]]: """ Get all relevant data from DataGame: snapshots from all tricks, for the positions of both winners. :return: tuple of 3 elements: 1. list of all sets-of-hands during game, one set-of-hands for every trick 2. list of all open cards in specific trick, one set-of-cards for every trick 3. list of all real cards the player should act, one for every trick all above are *concatenation* of results of both winners. For example, cards_list = [cards_list_winner_1] + [cards_list_winner_2] """ winners_indices = [w.value - 1 for w in self.winner] # List of hands and trick for every winner hands_list_1: List[List[Player]] = [] curr_hands = deepcopy(self.players) for trick_idx in range(len(self.tricks)): hands_list_1.append(deepcopy(curr_hands)) for player_idx, player in enumerate(curr_hands): curr_hands[player_idx].hand.play_card( self.tricks[trick_idx].trick[player]) hands_list_2 = deepcopy(hands_list_1) trick_list_1: List[Trick] = [] trick_list_2: List[Trick] = [] trick_list = [trick_list_1, trick_list_2] chosen_cards_list_1: List[Card] = [] chosen_cards_list_2: List[Card] = [] chosen_cards_list = [chosen_cards_list_1, chosen_cards_list_2] for winner_idx, winner_list in enumerate([hands_list_1, hands_list_2]): for trick_idx, hands in enumerate(winner_list): curr_player = self.position_to_player( self.tricks[trick_idx].first_position) curr_trick = Trick({}) while curr_player.position != POSITIONS[winners_indices[winner_idx]]: winner_list[trick_idx][ PLAYERS_DICT[curr_player.position.name]].play_card( self.tricks[trick_idx].trick[curr_player]) curr_trick.add_card( curr_player, self.tricks[trick_idx].trick[curr_player]) curr_player = self.players[PLAYERS_DICT[ PLAYERS_CYCLE[curr_player.position].name]] trick_list[winner_idx].append(curr_trick) chosen_cards_list[winner_idx].append( self.tricks[trick_idx].trick[curr_player]) return hands_list_1 + hands_list_2, trick_list_1 + trick_list_2, \ chosen_cards_list_1 + chosen_cards_list_2 class Parser: def __init__(self, file_paths: List[str]): self.games: List[DataGame] = [] for file in file_paths: self.games += (self.parse_file(file)) def parse_file(self, file_name: str) -> List[DataGame]: """ Get a path of PBN file, and parse it to list of DataGame objects """ games = [] with open(file_name) as f: for line in f: if line[1:6] == "Deal ": players_line = line elif line[1:9] == "Declarer": win_team, trump = self._parse_winners_and_trump(line, f) if trump is None: continue players = self._parse_players(players_line[7:-3], trump) elif line[1:5] == "Play": tricks = self._parse_tricks(line, f, players) if len(tricks) == 0 or trump is None: # delete empty games continue games.append(DataGame(players, tricks, win_team, trump)) return games @staticmethod def _parse_players(line: str, trump: TrumpType) -> List[Player]: """ Helper for parse_file. Example: line is such - [Deal "E:AK872.KQJT.K.Q94 QT95.85.AQJ2.AK7 4.A962.96.J86532 J63.743.T87543.T"] And the result is list of Player object. First is Player(PositionEnum.E, Hand) such that Hand is list contain A, K, 8, 7, 2 faces of suit ♠, ect. :param line: line from PBN file, which starts with "[Deal " :return: list of 4 Player objects, sorted by (N, E, S, W) """ player_str, all_hands_str = line.split(':') next_position = POSITIONS[PLAYERS_DICT[player_str]] players = [None, None, None, None] players_str = all_hands_str.split(' ') # spaces separate every two players for p in players_str: curr_position = next_position cards_str = p.split('.') # dots separate every two suits cards = [] for i, suit in enumerate(cards_str): for face in suit: cards.append(Card(face=face, suit=SuitType(SUITS[i]).name, trump=trump)) next_position = PLAYERS_CYCLE[curr_position] players[curr_position.value - 1] = Player(curr_position, Hand(cards)) return players @staticmethod def _parse_winners_and_trump(line: str, f: TextIO) -> \ Tuple[Tuple[PositionEnum], TrumpType]: """ Helper for parse_file. Example: for sequential 3 lines [Declarer "E"], [Contract "4H"], [Result "10"] the result is that trump is ♥ and the team east-west is the winner. :param line: line from PBN file, which starts with "[Declarer" :param f: TextIO object, of the PBN file that read :return: tuple of Enums of winners, and the trump suit. """ # Irregular situations if line[11] == '\"' or line[11] == '^': return None, None declarer = POSITIONS[PLAYERS_DICT[line[11]]] declare_team = TEAMS[0] if declarer in TEAMS[0] else TEAMS[1] bid_line = f.readline() obligation = int(bid_line[11]) + 6 if (bid_line[12:-3] == "NT") or (bid_line[12:-4] == "NT"): trump = TrumpType.NT else: trump = TrumpType[bid_line[12]] res_line = f.readline() result = int(res_line[8:-2].split('\"')[1][-1]) win_team = declare_team if result >= obligation else TEAMS_CYCLE[declare_team] return win_team, trump @staticmethod def _parse_tricks(player_line: str, f: TextIO, players: List[Player]) -> \ List[TrickValidation]: """ Helper for parse_file. Example: for sequential lines [Play "W"], HT H3 HA H6, C2 C3 C9 CJ, ..., * the meaning is that W starts the first trick with card 10♥, then N with 3♥, E with A♥ and S with 6♥. The winner was E, so he starts the next trick with 9♣ and so on. (Order of cards in file is not the order of game! First player in every line is [Play <>], and the winner is inferred from line before) :param player_line: line from PBN file, which starts with "["Play" :param f: TextIO object, of the PBN file that read :param players: list of 4 Player objects, sorted by (N, E, S, W) :return: list of all tricks of a game """ first_position = POSITIONS[PLAYERS_DICT[player_line[7]]] iter_num = islice(cycle([0, 1, 2, 3]), PLAYERS_DICT[player_line[7]], None) curr_player = players[next(iter_num)] tricks = [] trick_line = f.readline() while trick_line[0] != '*': curr_trick = TrickValidation() cards = trick_line.split(' ') # Irregular situations if '-' in cards or '-\n' in cards or len(cards) != 4: break for c in cards: curr_trick.add_card(curr_player, Card(face=c[1], suit=c[0])) curr_player = players[next(iter_num)] curr_trick.add_first_position(first_position) tricks.append(curr_trick) first_position = curr_trick.get_winner() trick_line = f.readline() return tricks def validate_agent_action(dg: DataGame, trick_idx: int, position: PositionEnum, agent: IAgent) -> bool: curr_hands, curr_trick, chosen_card = dg.snapshot(trick_idx, position) teams = [Team(curr_hands[0], curr_hands[2]), Team(curr_hands[1], curr_hands[3])] curr_state = State(trick=curr_trick, teams=teams, players=curr_hands, prev_tricks=dg.tricks[:trick_idx], score=dict.fromkeys(teams), curr_player=curr_hands[position.value - 1]) sg = SimulatedGame(agent=agent, other_agent=None, verbose_mode=False, state=curr_state) played_card = sg.play_single_move() print(f"Expected: {chosen_card}, Actual: {played_card}") return played_card == chosen_card def validate_agent_per_data_game(agent: IAgent, dg: DataGame, min_tricks: int=0)\ -> Tuple[np.ndarray, np.ndarray]: """ Validate a agent by comparing its performances to data. :param agent: IAgent to check vs the data :param dg: DataGame object :param min_tricks: minimum tricks index to start validation from :return: tuple of 2 arrays for experiences and succeeds. each element in each array represents the number of played tricks (== 13 - (#card in hand)) """ all_hands, all_tricks, chosen_cards = dg.all_relevant_snapshots() tricks_num = len(all_hands) // 2 checks, succeeds = np.zeros(12), np.zeros(12) for pos_idx, position in enumerate(dg.winner): for trick_idx in range(min_tricks, tricks_num): curr_hands = all_hands[pos_idx * tricks_num + trick_idx] curr_trick = all_tricks[pos_idx * tricks_num + trick_idx] chosen_card = chosen_cards[pos_idx * tricks_num + trick_idx] # Create teams, such that first team is the winner teams = [Team(curr_hands[0], curr_hands[2]), Team(curr_hands[1], curr_hands[3])] if curr_hands[0].position not in dg.winner: teams[0], teams[1] = teams[1], teams[0] curr_state = State(trick=curr_trick, teams=teams, players=curr_hands, prev_tricks=dg.tricks[:trick_idx], score=defaultdict.fromkeys(teams, 0), curr_player=curr_hands[position.value - 1]) sg = SimulatedGame(agent=agent, other_agent=SimpleAgent('soft_long_greedy_action'), verbose_mode=False, state=curr_state) validation = 'simple' if isinstance(agent, SimpleAgent) else '' played_card = sg.play_single_move(validation=validation) if played_card == chosen_card: succeeds[trick_idx] += 1 checks[trick_idx] += 1 return checks, succeeds <file_sep>/game.py import os import sys import numpy as np from copy import copy from typing import List from cards import Deck, TrumpType from players import POSITIONS, Player, PositionEnum, TEAMS, Team from state import State from trick import Trick class Game: def __init__(self, agent, other_agent, games_counter: List[int], tricks_counter: List[int], verbose_mode: bool = True, previous_tricks: List[Trick] = None, curr_trick: Trick = None, starting_pos: PositionEnum = None, trump=None, cards_in_hand=13): # todo(oriyan/maryna): think how to reproduce game from database - # or randomly generate new game self.cards_in_hand=cards_in_hand self.agent = agent # type: IAgent self.other_agent = other_agent # type: IAgent self.games_counter = games_counter self.verbose_mode = verbose_mode if trump is None: trump = np.random.choice(TrumpType) else: trump = TrumpType.from_str(trump) self.trump = trump # type: TrumpType self.deck = Deck(self.trump) hands = self.deck.deal(cards_in_hand=cards_in_hand) self.players = {pos: Player(pos, hand) for pos, hand in zip(POSITIONS, hands)} self.teams = [Team(self.players[pos1], self.players[pos2]) for pos1, pos2 in TEAMS] self.curr_trick = curr_trick self.previous_tricks = previous_tricks self.tricks_counter = tricks_counter self.winning_team: int = -1 if starting_pos is None: starting_pos = np.random.choice(POSITIONS) self.curr_player = self.players[starting_pos] self._state = None def __str__(self): ret = "" ret += f"Match score: " \ f"{self.teams[0]}:{self.games_counter[0]:02} - " \ f"{self.teams[1]}:{self.games_counter[1]:02}\n" ret += f"Game score: " \ f"{self.teams[0]}:{self.tricks_counter[0]:02} - " \ f"{self.teams[1]}:{self.tricks_counter[1]:02}\n" ret += f"Trump Suite: {self.trump.value}\n" ret += f"Current trick: " for player, card in self.curr_trick.items(): ret += f"{player}:{card} " if len(self.curr_trick) == 4: ret += f", {self.players[self.curr_trick.get_winner()]} won trick." ret += f"\n" for player in self.players.values(): ret += f"\n{player}\n{player.hand}" return ret def run(self) -> bool: """ Main game runner. :return: None """ score = {self.teams[0]: 0, self.teams[1]: 0} initial_state = State(self.curr_trick, self.teams, list(self.players.values()), self.previous_tricks, score, self.curr_player, trump=self.trump) self._state = initial_state self.previous_tricks = self._state.prev_tricks self.game_loop() return True def game_loop(self) -> None: while max(self.tricks_counter) < np.ceil(self.cards_in_hand / 2): # Winner is determined. for i in range(len(POSITIONS)): # Play all hands self.play_single_move() if self.verbose_mode: self.show() if self.verbose_mode: self.show() # Game ended, calc result. self.winning_team = int(np.argmax(self.tricks_counter)) def play_single_move(self) -> None: """ Called when its' the givens' player turn. The player will pick a action to play and it will be taken out of his hand a placed into the trick. """ if self.teams[0].has_player(self.curr_player): card = self.agent.get_action(self._state) else: card = self.other_agent.get_action(self._state) assert(card is not None) curr_trick = self._state.apply_action(card, True) self.curr_trick = curr_trick self.curr_player = self._state.curr_player # Current player of state is trick winner self.tricks_counter = [self._state.score[self._state.teams[0]], self._state.score[self._state.teams[1]]] def show(self) -> None: """ Update GUI :return: None """ os.system('clear' if 'linux' in sys.platform else 'cls') print(self) input() class SimulatedGame(Game): """ Simulates a game with a non-empty state""" def __init__(self, agent, other_agent, verbose_mode: bool = True, state: State = None, starting_action=None): """ :param State state: Initial game state. :param Card starting_action: Initial play of current player. If None, chosen according to `agent`'s policy. """ state_copy = copy(state) self.players = {player.position: player for player in state_copy.players} self.teams = state_copy.teams self.tricks_counter = [state_copy.score[state_copy.teams[0]], state_copy.score[state_copy.teams[1]]] self.starting_action = starting_action self.first_play = True self.agent = agent # type: IAgent self.other_agent = other_agent # type: IAgent self.games_counter = [0, 0] self.verbose_mode = verbose_mode self.trump = state_copy.trump self.deck = Deck(self.trump) self.curr_trick = state_copy.trick self.previous_tricks = state_copy.prev_tricks self.winning_team: int = -1 self.curr_player = state_copy.curr_player self._state = state_copy def play_single_move(self, validation=''): if self.first_play and self.starting_action is not None: card = self.starting_action self.first_play = False elif self.teams[0].has_player(self.curr_player): card = self.agent.get_action(self._state) else: card = self.other_agent.get_action(self._state) if validation == 'simple': return card curr_trick = self._state.apply_action(card, True) self.curr_trick = curr_trick self.curr_player = self._state.curr_player # Current player of state is trick winner self.tricks_counter = [self._state.score[self._state.teams[0]], self._state.score[self._state.teams[1]]] return card def game_loop(self) -> None: if len(self.curr_trick.cards()) > 0: for card in self.curr_trick.cards(): self._state.already_played.add(card) for _ in range(13 - len(self._state.prev_tricks)): for __ in range(4 - len(self.curr_trick.cards())): # Play all hands self.play_single_move() if self.verbose_mode: self.show() if max(self.tricks_counter) >= 7: # Winner is determined. break self.winning_team = int(np.argmax(self.tricks_counter)) def run(self) -> bool: self.game_loop() return True <file_sep>/cards.py """ This module holds classes that represent cards and their derivative classes. """ import numpy as np from copy import copy from enum import Enum from typing import List FACES = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A', ] face_value = {'A': 4.5, 'K': 3, 'Q': 1.5, 'J': 0.75, 'T': 0.25, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0} SUITS = ['♠', '♥', '♦', '♣', ] SUITS_ALT = {'S': '♠', 'H': '♥', 'D': '♦', 'C': '♣'} class SuitType(Enum): """ Enum representing card suit""" Spades = '♠' S = '♠' Hearts = '♥' H = '♥' Diamonds = '♦' D = '♦' Clubs = '♣' C = '♣' @staticmethod def from_str(suit: str): """ Parses string into SuitType object :param suit: Suit string to parse into SuitType :returns SuitType: parsed suit :raises ValueError: If `suit` is unsupported. """ try: suit_key = suit.capitalize() return SuitType[suit_key] except KeyError: raise ValueError(f"Unsupported Suit {suit}. " f"Must be one of {set(suit.name for suit in list(SuitType))}") class TrumpType(Enum): """ Enum representing match's trump suit""" Spades = '♠' S = '♠' Hearts = '♥' H = '♥' Diamonds = '♦' D = '♦' Clubs = '♣' C = '♣' NoTrump = 'NT' NT = 'NT' @staticmethod def from_str(suit: str): """ Parses string into SuitType object :param suit: Suit string to parse into SuitType :returns SuitType: parsed suit :raises ValueError: If `suit` is unsupported. """ if suit.upper() == 'NT': return TrumpType.NT if suit == 'NoTrump': return TrumpType.NoTrump try: suit_key = suit.capitalize() return TrumpType[suit_key] except KeyError: raise ValueError(f"Unsupported Suit {suit}. " f"Must be one of {set(suit.name for suit in list(TrumpType))}") class Suit: suit_type: SuitType trump_suit: TrumpType = TrumpType.NT def __init__(self, suit_type: SuitType, trump_suit: TrumpType = TrumpType.NT) -> None: self.suit_type = suit_type self.trump_suit = trump_suit self.is_trump = self.trump_suit.value == self.suit_type.value def __repr__(self) -> str: return self.suit_type.value def __eq__(self, other): if isinstance(other, str): return self.suit_type.value == other return self.suit_type.value == other.suit_type.value def __ne__(self, other): return self.suit_type.value != other.suit_type.value def __lt__(self, other): if self != other: if self.is_trump: return False if other.is_trump: return True return SUITS.index(self.suit_type.value) > SUITS.index( other.suit_type.value) return False def __gt__(self, other): return other < self def __le__(self, other): return self < other or self == other def __ge__(self, other): return other <= self def __hash__(self) -> int: return hash(self.suit_type) class Card: """ A playing card. """ def __init__(self, face: str, suit: str, trump: TrumpType = TrumpType.NT): """ :param face: value of card - one of {'2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'} :param suit: suit of card, one of {'S' or 'Spades', 'C' or 'Clubs', 'D' or 'Diamonds, 'H' or 'Hearts'} :raises ValueError: If `face` or `suit` are unsupported. """ suit_type = SuitType.from_str(suit) self.suit = Suit(suit_type, trump_suit=trump) self.is_trump = self.suit.is_trump if face.capitalize() not in FACES: raise ValueError( f"Unsupported Card Value {face}, must be one of {set(FACES)}") self.face = face.capitalize() def __copy__(self): new_card = Card(self.face, self.suit.suit_type.name, self.suit.trump_suit) new_card.is_trump = self.is_trump return new_card def __repr__(self): return f"{self.face}{self.suit}" def __eq__(self, other): return self.face == other.face and self.suit == other.suit def __ne__(self, other): return not (self == other) def __lt__(self, other): if other.is_trump and not self.is_trump: return True if self.is_trump and not other.is_trump: return False if self.suit == other.suit: return FACES.index(self.face) < FACES.index(other.face) return SUITS.index(self.suit.suit_type.value) < SUITS.index( self.suit.suit_type.value) and \ FACES.index(self.face) < FACES.index(other.face) def __gt__(self, other): return other < self def __le__(self, other): return not (other < self) def __ge__(self, other): return not (self < other) def __hash__(self) -> int: return hash((self.suit, self.face)) class Deck: """ Deck of cards.""" def __init__(self, trump: TrumpType = TrumpType.NT): self.trump = trump self.cards = [] for face in FACES: for suit in SUITS_ALT: card = Card(face, suit, self.trump) self.cards.append(card) def deal(self, cards_in_hand=13, recreate_game=''): """ Returns 4 randomly dealt Hands, one for each player in the game. :param recreate_game: if supplied, will allow recreating a set of hands from a database. Currently unsupported. :returns List[Hand]: 4 hands """ if not recreate_game: cards = np.random.choice(self.cards, 4*cards_in_hand, replace=False) shuffled_deck = \ np.random.permutation(cards).reshape(4, cards_in_hand).tolist() hands = [Hand(cards) for cards in shuffled_deck] return hands # todo(oriyan/mar): create new deck from database representation class Hand: """ A Player's hand . Holds their cards.""" def __init__(self, cards: List[Card]): """ Initial hand of player is initialized with list of Card object.""" self.cards = cards assert len(set(cards)) == len(cards) def __len__(self): return len(self.cards) def __copy__(self): cards = [copy(card) for card in self.cards] return Hand(cards) def play_card(self, card: Card): """ Plays card from hand. After playing this card, it is no longer available in the player's hand.""" assert card in self.cards prev_num_cards = len(self.cards) self.cards.remove(card) assert len(self.cards) != prev_num_cards def get_cards_from_suite(self, suite: Suit, already_played): """ Returns all cards from player's hand that are from `suite`. If None, returns all cards.""" if suite is None: cards = self.cards assert already_played.isdisjoint(cards) return self.cards cards = list(filter(lambda card: card.suit == suite, self.cards)) assert already_played.isdisjoint(cards) return cards def get_cards_not_from_suite(self, suite: Suit): """ Returns all cards from player's hand that are not from `suite`. If None, returns all cards.""" if suite is None: return self.cards cards = list(filter(lambda card: card.suit != suite, self.cards)) return cards def get_cards_sorted_by_suits(self, already_played): sorted_hand = dict() trump = [] for card in self.cards: if not sorted_hand.get(card.suit.suit_type): sorted_suit = sorted(self.get_cards_from_suite(card.suit, already_played)) if card.is_trump: trump = sorted_suit else: sorted_hand[card.suit.suit_type] = sorted_suit return sorted_hand, trump def get_hand_value(self, already_played): """ calculated following the steps: 1. HCP value of the hand 2. adjust of HCP 3. adjust suit lenght 4. adjust hands with top five cards of a suit 5. total starting points (added in the heuristic) :param already_played: :return: """ hand_value = 0 adjust_suit_lenght = 0 aces_10s_count = 0 queens_jecks_count = 0 hand_values_by_suits = dict() for card in self.cards: if not hand_values_by_suits.get(card.suit.suit_type): card_of_suit = self.get_cards_from_suite(card.suit, already_played) if len(card_of_suit) > 0: adjust_suit_lenght += max([0, len(card_of_suit) - 4]) values_of_card = [face_value[card.face] for card in card_of_suit if face_value[card.face] != 0] hand_values_by_suits[card.suit.suit_type] = values_of_card for suit, values in hand_values_by_suits.items(): if len(values) > 0: hand_value += sum(values) aces_10s_count += values.count(0.25) # tens aces_10s_count += values.count(4.5) # aces queens_jecks_count += values.count(1.5) # queens queens_jecks_count += values.count(0.75) # jacks if len(values) == 5: # adjust rule 4 hand_value += 3 adjust_hand_value_value = abs(aces_10s_count - queens_jecks_count) sign = 1 if aces_10s_count > queens_jecks_count else -1 if adjust_hand_value_value > 2: hand_value += sign if adjust_hand_value_value > 5: hand_value += sign return hand_value def __str__(self): ret = "" for suit in SUITS: ret += f"{suit}: " for card in self.cards: if card.suit == suit: ret += f"{card.face} " ret += f"\n" return ret <file_sep>/compare_agents.py import time import matplotlib.patheffects as path_effects import matplotlib.pyplot as plt from match import * from multi_agents import simple_func_names, simple_agent_names, \ ab_evaluation_func_names, ab_evaluation_agent_names NUM_CARDS = 13 GAMES_PER_MATCH = 100 def compare_simple_agents(): def run_all_simple_actions_matches(results_matrix): for i in range(len(simple_func_names)): for j in range(len(simple_func_names)): # For each pair of agents agent0, agent1 = \ simple_func_names[i], \ simple_func_names[j] print(f"{simple_agent_names[i]} vs. " f"{simple_agent_names[j]}") # Run match curr_match = Match(SimpleAgent(agent0), SimpleAgent(agent1), GAMES_PER_MATCH, False) curr_match.run() # Print match result and update scores table print(f"Score: {curr_match.games_counter[0]:02} -" f" {curr_match.games_counter[1]:02}\n") results_matrix[i, j] = 100 * curr_match.games_counter[ 0] / GAMES_PER_MATCH return results_matrix def display_table_simple_agents(results_matrix): fig, ax = plt.subplots(dpi=600) ax.imshow(results_matrix, cmap='plasma', vmin=0, vmax=100) ax.set_xticks(np.arange(len(simple_agent_names))) ax.set_yticks(np.arange(len(simple_agent_names))) ax.set_xticklabels(simple_agent_names) ax.set_yticklabels(simple_agent_names) plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") for i in range(len(simple_agent_names)): for j in range(len(simple_agent_names)): text = ax.text( j, i, f"{results_matrix[i, j]:04.1f}", ha="center", va="center", color="w") text.set_path_effects( [path_effects.Stroke(linewidth=2, foreground='black'), path_effects.Normal()]) title = "Simple vs Simple Agents\n" + \ f"y-axis win %, higher is better" ax.set_title(title, fontsize=16, fontweight="bold") fig.tight_layout() plt.show() print() start_time = time.time() results = np.empty((len(simple_func_names), len(simple_func_names))) results[:] = np.nan run_all_simple_actions_matches(results) display_table_simple_agents(results) print(f"--- Graph generation took " f"{int(time.time() - start_time)} seconds ---") def compare_simple_agents_vs_ab_agents(depth, ab_first=True): def run_all_simple_agents_vs_ab_matches(depth, results_matrix): for i in range(len(ab_evaluation_func_names)): for j in range(len(simple_func_names)): ab_agent = AlphaBetaAgent(ab_evaluation_func_names[i], depth) simple_agent = SimpleAgent(simple_func_names[j]) print(f"{ab_evaluation_agent_names[i]} vs. " f"{simple_agent_names[j]}") if ab_first: curr_match = Match(ab_agent, simple_agent, num_games=GAMES_PER_MATCH, verbose_mode=False, cards_in_hand=NUM_CARDS) else: curr_match = Match(simple_agent, ab_agent, num_games=GAMES_PER_MATCH, verbose_mode=False, cards_in_hand=NUM_CARDS) curr_match.run() print(f"Score: {curr_match.games_counter[0]:02} -" f" {curr_match.games_counter[1]:02}\n") results_matrix[i, j] = \ 100 * curr_match.games_counter[0] / GAMES_PER_MATCH if not ab_first: results_matrix = 100 - results_matrix return results_matrix def display_table_simple_agents_vs_ab(depth, results_matrix): fig, ax = plt.subplots(dpi=600) ax.imshow(results_matrix, cmap='plasma', vmin=0, vmax=100) ax.set_xticks(np.arange(len(simple_agent_names))) ax.set_yticks(np.arange(len(ab_evaluation_agent_names))) ax.set_xticklabels(simple_agent_names) ax.set_yticklabels(ab_evaluation_agent_names) plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") for i in range(len(simple_agent_names)): for j in range(len(ab_evaluation_agent_names)): text = ax.text( i, j, f"{results_matrix[j, i]:04.1f}", ha="center", va="center", color="w") text.set_path_effects( [path_effects.Stroke(linewidth=2, foreground='black'), path_effects.Normal()]) title = f"AlphaBeta vs Simple Agents\n" \ f"{'AlphaBeta' if ab_first else 'Simple'} agent play first\n" \ f"y-axis win %, depth={depth}" ax.set_title(title, fontsize=16, fontweight="bold") fig.tight_layout() plt.show() print() start_time = time.time() results = np.empty((len(ab_evaluation_func_names), len(simple_func_names))) results[:] = np.nan run_all_simple_agents_vs_ab_matches(depth, results) display_table_simple_agents_vs_ab(depth, results) print(f"--- Graph generation took " f"{int(time.time() - start_time)} seconds ---") def run_all_simple_agents_vs_mcts(agent_cls, num_cards=13, **kwargs): results = np.empty((len(simple_func_names), len(simple_func_names))) results[:] = np.nan for i in range(len(simple_func_names)): for j in range(len(simple_func_names)): agent0 = simple_func_names[i] print(f"{agent_cls.__name__} ({simple_func_names[j]} rule) vs. {simple_agent_names[i]}") curr_match = Match(agent_cls(simple_func_names[j], **kwargs), SimpleAgent(agent0), GAMES_PER_MATCH, False, cards_in_hand=num_cards) curr_match.run() print(f"Score: {curr_match.games_counter[0]:02} -" f" {curr_match.games_counter[1]:02}\n") results[j, i] = 100 * curr_match.games_counter[0] / GAMES_PER_MATCH display_table_simple_agents_vs_MCTS(results, agent_cls, num_cards=num_cards, **kwargs) def display_table_simple_agents_vs_MCTS(results, agent_cls, num_simulations=1, epsilon=None, num_cards=13): fig, ax = plt.subplots(dpi=300) im = ax.imshow(results, cmap='plasma', vmin=0, vmax=100) ax.set_xticks(np.arange(len(simple_agent_names))) ax.set_yticks(np.arange(len(simple_agent_names))) mcts_agent_names = [f"{agent_cls.__name__}({name})" for name in simple_agent_names] title = f"Win % of {agent_cls.__name__} vs normal agent\n" \ f"{GAMES_PER_MATCH} games, {num_cards} cards, {num_simulations} sims." ax.set_title(title, fontsize=12, fontweight="bold") ax.set_xticklabels(simple_agent_names, fontsize=8) ax.set_yticklabels(mcts_agent_names, fontsize=8) plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") for i in range(len(simple_agent_names)): for j in range(len(simple_agent_names)): text = ax.text( j, i, f"{results[i, j]:3.0f}%", ha="center", va="center", color="w", fontsize=8) text.set_path_effects( [path_effects.Stroke(linewidth=2, foreground='black'), path_effects.Normal()]) fig.tight_layout() plot_dir = os.path.join(os.getcwd(), 'plots') os.makedirs(plot_dir, exist_ok=True) plot_fname = os.path.join(plot_dir, f"{agent_cls.__name__}_" f"_{GAMES_PER_MATCH}games_{num_cards}cards_{num_simulations}sims" f"{f'_{epsilon:1.2}eps' if epsilon else ''}.jpg") plt.tight_layout() plt.savefig(plot_fname) plt.show() LEGAL_AGENT_TYPES =["AB", "MCTS", "SIMPLE"] def parse_args(): parser = ArgumentParser() parser.add_argument('--agent', required=True, type=str, choices=LEGAL_AGENT_TYPES, dest='agent') parser.add_argument('--games', default=100, type=int) parser.add_argument('--simulations', default=1000, type=int) parser.add_argument('--cards', default=5, type=int) parser.add_argument('--depth', default=5, type=int) parser.add_argument('--epsilon', default=0., type=float) args = parser.parse_args() return args def mcts_main(num_games, num_simulations, num_cards, epsilon): global GAMES_PER_MATCH GAMES_PER_MATCH = num_games MCTS_classes = [SimpleMCTSAgent, PureMCTSAgent] for agent_cls in MCTS_classes: run_all_simple_agents_vs_mcts(agent_cls, num_simulations=num_simulations, num_cards=num_cards) run_all_simple_agents_vs_mcts(StochasticSimpleMCTSAgent, num_simulations=num_simulations, num_cards=num_cards, epsilon=epsilon) def ab_main(num_games, num_cards, depth): global GAMES_PER_MATCH, NUM_CARDS GAMES_PER_MATCH = num_games NUM_CARDS = num_cards compare_simple_agents_vs_ab_agents(depth=5, ab_first=True) compare_simple_agents_vs_ab_agents(depth=5, ab_first=False) compare_simple_agents_vs_ab_agents(depth=10, ab_first=True) compare_simple_agents_vs_ab_agents(depth=10, ab_first=False) compare_simple_agents_vs_ab_agents(depth=15, ab_first=True) compare_simple_agents_vs_ab_agents(depth=15, ab_first=False) if __name__ == '__main__': args = parse_args() if args.agent.upper() == 'MCTS': mcts_main(args.games, args.simulations, args.cards, args.epsilon) if args.agent.upper() == 'AB': ab_main(args.games, args.cards, args.depth) if args.agent.upper() == 'SIMPLE': compare_simple_agents() <file_sep>/requirements.txt numpy~=1.17.4 tqdm~=4.47.0 matplotlib~=3.1.2<file_sep>/tests_validation.py import os from validation import * from multi_agents import SimpleAgent, AlphaBetaAgent, SimpleMCTSAgent, \ StochasticSimpleMCTSAgent, PureMCTSAgent from compare_agents import simple_func_names, simple_agent_names, \ ab_evaluation_func_names, ab_evaluation_agent_names import numpy as np import matplotlib.pyplot as plt from time import perf_counter def test_snapshot(): file = "bridge_data_1/Aulpll23.pbn" # file = "bridge_data_1/Dkofro20.pbn" files = Parser([file]) # out = files.games[0].snapshot(0, POSITIONS[0]) # out = files.games[0].snapshot(0, POSITIONS[2]) # out = files.games[0].snapshot(1, POSITIONS[2]) out = files.games[0].snapshot(1, POSITIONS[0]) # out = games[0].snapshot(6, POSITIONS[0]) return out def test_all_snapshots_single_game(): file = "bridge_data_1/Aulpll23.pbn" games = Parser([file]) # out = games.games[0].all_relevant_snapshots() # out = games.games[2].all_relevant_snapshots() # out = games.games[4].all_relevant_snapshots() out = games.games[6].all_relevant_snapshots() return out def load_all_game(): games_dir = os.path.join(os.getcwd(), 'bridge_data_1') files_name = os.listdir(games_dir) pbn_files = [] for file in files_name: if file[-3:] == 'pbn': pbn_files.append(os.path.join('bridge_data_1', file)) files = Parser(np.random.permutation(pbn_files).tolist()) print("succeed loading") return files def test_valid_games(): games = load_all_game() for i, g in enumerate(games.games): trick_idx = max(0, len(g.tricks) - 1) g.snapshot(trick_idx, POSITIONS[0]) print("all are valid") def test_all_snapshots(): games = load_all_game() for i, g in enumerate(games.games): g.all_relevant_snapshots() print("all snapshots for all games done") return def games_length(): games = load_all_game() histogram = np.zeros(12) for g in games.games: histogram[len(g.tricks) - 1] += 1 print(histogram) plt.bar(np.arange(12) + 1, histogram) plt.title("Number of Tricks Histogram") plt.xlabel("# tricks") plt.ylabel("# games") plt.show() def test_validate_agent_action(): curr_agent = SimpleAgent('highest_first_action') file = "bridge_data_1/Aulpll23.pbn" files = Parser([file]) return validate_agent_action(dg=files.games[4], trick_idx=1, position=PositionEnum.N, agent=curr_agent) def test_validate_agent_by_the_whole_game(): curr_agent = SimpleAgent('highest_first_action') file = "bridge_data_1/Aulpll23.pbn" files = Parser([file]) return validate_agent_per_data_game(agent=curr_agent, dg=files.games[4]) def display_results(agents_scores: List[np.ndarray], names: List[str], num_of_games: int, min_tricks_num: int=0): labels = [i for i in range(13 - min_tricks_num, 1, -1)] x = np.arange(len(labels)) # the label locations num_agents = len(agents_scores) width = 1 / (num_agents+2) # the width of the bars fig, ax = plt.subplots() rects_list = [] for i in range(num_agents): rects_list.append(ax.bar(x + ((i - ((num_agents-1) / 2)) * width), agents_scores[i], width, label=names[i])) ax.set_ylabel('Match success rate (%)') ax.set_xlabel('Hand size (cards)') ax.set_title(f'Scores by trick and agent\n (data from {num_of_games} games)') ax.set_title(f'Prediction success rate as func. of # cards in hand\naveraged over {num_of_games} games') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend(loc='best') ax.set_ylim([0, 119]) fig.tight_layout() plt.show() def run_validation(agents_list: List[IAgent], num_of_games: int, min_tricks: int=0) -> List[np.ndarray]: """ :param agents_list: :param num_of_games: if 0: run all games :param min_tricks: trick index to start validation from (0 for start of game) :return: list of arrays, one for every agent. the array is consist of 12 entries, each represents the score of agent respectivly to the number of remaining cards in its hand. """ agents_scores = [np.zeros(12) for _ in agents_list] games = load_all_game() if num_of_games == 0: num_of_games = len(games.games) for agent_idx, agent in enumerate(agents_list): start = perf_counter() all_checks, all_succeeds = np.zeros(12), np.zeros(12) for i in range(num_of_games): curr_checks, curr_succeeds = validate_agent_per_data_game( agent, games.games[i], min_tricks) all_checks += curr_checks all_succeeds += curr_succeeds if (i+1) % 25 == 0: print(f"Finished {i+1}/{num_of_games} games for agent {agent.__class__.__name__}") agents_scores[agent_idx] = (all_succeeds / all_checks) * 100 print(f"agent {agent_idx}: {(perf_counter() - start)/num_of_games} seconds/game, {num_of_games} games") print(agents_scores) return agents_scores if __name__ == '__main__': ### Tests # test_snapshot() # test_all_snapshots_single_game() # test_validate_agent_action() # test_load_all_game() # test_valid_games() # test_all_snapshots() # games_length() # test_validate_agent_by_the_whole_game() num_of_games = 1 # how many data_games to use for validation minimum_round = 8 # trick index to start validation from (0 for start of game) ### Run Simple agents # agents_list = [SimpleAgent(kind) for kind in simple_func_names] # agents_scores_list = run_validation(agents_list, num_of_games, min_tricks_num) # display_results(agents_scores_list, simple_agent_names, num_of_games) ### Run AB agents # agents_list = [AlphaBetaAgent(kind, depth=12) for kind in ab_evaluation_func_names] # agents_scores_list = run_validation(agents_list, num_of_games, min_tricks_num) # display_results([agent[min_tricks_num:] for agent in agents_scores_list], # ab_evaluation_agent_names, num_of_games, min_tricks_num) ### Run MTCs (choose one agents_list every time not to be a comment) num_of_simulations = 10 agents_list = [SimpleMCTSAgent(kind, num_simulations=num_of_simulations) for kind in simple_func_names] agent_names = [f"{agent_cls.__class__.__name__}({func_name})" for agent_cls, func_name in zip(agents_list, simple_func_names)] # agents_list = [StochasticSimpleMCTSAgent(kind, num_simulations=num_of_simulations) # for kind in simple_func_names] # agents_list = [PureMCTSAgent(kind, num_simulations=num_of_simulations) # for kind in simple_func_names] agents_scores_list = run_validation(agents_list, num_of_games, minimum_round) display_results([agent[minimum_round:] for agent in agents_scores_list], agent_names, num_of_games, minimum_round)
bc243e76c3325268e8a1e835e6813d5d79a3c952
[ "Markdown", "Text", "Python" ]
12
Markdown
oriyanh/Bridge-AI
c613ffb08d774fa17145133eec3d5f0c6022c70d
ef740d8ac596b1482002ddd80a1b02a61700471e
refs/heads/master
<repo_name>basit-7/File_Handling_in_Python<file_sep>/README.md <b><c>File Handling</c></b> - .txt file are imported in .ipynb - file_handling.ipynb is the example and their explanation - try_it_yourself.ipynb us the exercise part.
d62f8f209777dd8b08b70bfbfb123f966444e6f8
[ "Markdown" ]
1
Markdown
basit-7/File_Handling_in_Python
3c57d9a48db44324650aa751614f5a237e3bb688
4cd9d9e4b1f8dd394a8052ba7dcbfbb1c8236b94
refs/heads/master
<file_sep>export default { song_current: state => state.song_current, playlist_list: state => state.playlist_list }; <file_sep><template> <a v-bind:class="cls" class="collection-item" role="listitem" href=""> {{ opt.name }} <span class="right">{{ opt.length | t }}</span> </a> </template> <script> export default { name: 'ListItem', props: { opt: { type: Object, required: true }, num: { type: Number, required: true } }, computed: { current() { return this.$store.getters['currentList/song_current']; } }, methods: { cls() { return this.current.PlayingFile === 1 + this.num ? 'active' : ''; } } }; </script> <style lang="scss"> </style> <file_sep>export default { update_time: 10, song_current: '', playlist_crc: '', volume: 50, track_position: 0, track_length: 0, player_status: { status: 'OK', RepeatFile: '0', RandomFile: '0' }, playlist_list: [ { name: '1 <NAME> - Travelin Alone', length: '236559' }, { name: '2 <NAME> - Travelin Alone', length: '236559' }, { name: '3 <NAME> - Travelin Alone', length: '236559' }, { name: '4 <NAME> - Travelin Alone', length: '236559' }, { name: '5 <NAME> - Travelin Alone', length: '236559' }, { name: '6 <NAME> - Travelin Alone', length: '236559' }, { name: '7 <NAME> - Travelin Alone', length: '236559' }, { name: '8 <NAME> - Travelin Alone', length: '236559' }, { name: '9 <NAME> - Travelin Alone', length: '236559' }, { name: '10 <NAME> - Travelin Alone', length: '236559' }, { name: '11 <NAME> - Travelin Alone', length: '236559' }, { name: '12 <NAME> - Travelin Alone', length: '236559' }, { name: '13 <NAME> - Travelin Alone', length: '236559' }, { name: '14 <NAME> - Travelin Alone', length: '236559' } ] }; <file_sep>const fs = require('fs'); const path = require('path'); const getDirName = require('path').dirname; const mkdirp = require('mkdirp'); let file = process.argv.slice(2)[0]; if (!file) { const _red = '\u001b\[31m'; const _cyan = '\u001b\[36m'; const _green = '\u001b\[32m'; const _off = '\u001b\[0m'; console.log(''); console.log(`${_red}Empty file name!!!${_off}`); console.log('example:'); const example = [ _cyan, path.basename(process.argv[0]), ' ', path.basename(process.argv[1]), ' ', _green, 'Component-name', _off ].join(''); console.log(` ${example}`); console.log(''); process.exit(1); } file = path.normalize(file); file = path.join(__dirname, 'src', 'components', file); if (!(/.*\.vue$/).test(file)) { file += '.vue'; } // Get template const content = require('./create-tmpl').tmp(file); writeFile(file, content) .then(() => { console.log(`\n \uD83D\uDC4D ${file}\n`); }) .catch((err) => { console.log('\uD83D\uDC80'); console.log(err); }); /** * Functions ====== */ function writeFile(path, contents) { return new Promise((resolve, reject) => { mkdirp(getDirName(path), function(err) { if (err) { return reject(err); } fs.writeFile(path, contents, 'utf8', (err) => { if (err) { return reject(err); } resolve(); }); }); }); } <file_sep><template> <div class="page-footer"> <div class="container"> <div class="row"> <div class="col s12 control-bar"> <div class="range-field"> <input type="range" min="0" max="100" /> </div> <div class="volume-field"> <div class="card-title">1 <NAME> - Travelin Alone</div> <volume-component></volume-component> </div> <button role="button" class="btn-flat"> <i class="material-icons">skip_previous</i> </button> <button role="button" class="btn-flat"> <i class="material-icons">play_arrow</i> <!-- <i class="material-icons">pause</i> --> </button> <button role="button" class="btn-flat"> <i class="material-icons">skip_next</i> </button> <div class="right"> <button role="button" class="btn-flat btn-w-min active"> <i class="material-icons">repeat</i> </button> <button role="button" class="btn-flat btn-w-min"> <i class="material-icons">shuffle</i> </button> </div> </div> </div> </div> </div> </template> <script> import VolumeComponent from './Volume.vue'; export default { name: 'ControllBar', components: { VolumeComponent } }; </script> <style lang="scss"> .page-footer { background-color: #fff; box-shadow: 0 0 2px 2px rgba(0, 0, 0, .29); height: 130px; position: fixed; bottom: 0; left: 0; right: 0; padding-top: 0; } .btn-flat { padding: 0 1.2rem; } .btn-w-min { padding-right: .2rem; padding-left: .2rem; } #app .btn-flat * { color: #a2a2a2; } #app .btn-flat.active * { color: #26a59a; } .volume-field { display: flex; align-items: center; flex-direction: row; flex-wrap: nowrap; justify-content: space-between; } .card-title { font-size: 15px; color: #000; } .btn-flat:first-of-type { padding-left: 0; } .row .col.control-bar { padding: 0 26px; } </style> <file_sep># aimp-web-ctl-vue > A Vue.js project [Material](https://getmdl.io/components/index.html#layout-section) [Icon](https://material.io/icons) [Vue-resource](https://github.com/pagekit/vue-resource) [Style of controls](http://nisnom.com/veb-razrabotki/effekt-kak-by-vdavlivayushhihsya-knopok-pri-nazhatii/) *** [-] get_playlist_list [] get_version_string [] get_version_number [] get_update_time - получение настроек обновления [] get_playlist_songs [] get_playlist_crc [-] get_player_status [] get_song_current [] get_volume [] get_track_position [] get_track_length [] get_custom_status [] set_volume [] set_track_position [] set_custom_status [] set_song_play [] set_song_position - меняем позицицю песни, и обновляем список песен [] set_custom_status [] set_player_status [] player_play [] player_pause [] player_stop [] player_prevous [] player_next [] playlist_sort [] playlist_add_file [] playlist_del_file [] playlist_queue_add [] playlist_queue_remove ==== get_track_position get_volume get_song_current get_player_status get_playlist_crc <file_sep><template> <div> <div class="title-wrap"> <div role="banner" class="title">Мой лист</div> </div> <div class="menu"> <input role="menu" class="checkbox" type="checkbox" id="menuButton"> <label class="button" for="menuButton"><span class="crocodile"></span></label> <div class="body"> <div role="navigation" class="body-container"> <a class="link" href="">Один</a> <a class="link" href="">Два</a> <a class="link" href="">Три</a> <a class="link" href="">Четыре</a> </div> </div> </div> </div> </template> <script> export default { name: 'Menu', data () { return {}; } }; </script> <style lang="scss"> .title-wrap{ position: fixed; top: 0; right: 0; left: 0; background-color: rgba(255,255,255, .8); z-index: 1; border-bottom: 1px solid #ddd; .title { padding: 4px 10px; } } .menu { display: -webkit-flex; display: flex; -webkit-justify-content: space-between; justify-content: space-between; box-sizing: border-box; .body { display: block; position: fixed; top: 0; left: 0; height: 100%; width: 100%; background: rgba(0,0,0,0.8); transform: translateX(-100%); transition: transform 0.5s linear; will-change: transform; z-index: 100; .body-container { padding: 10px; .link { display: block; color: rgb(38, 165, 154); margin-bottom: 20px; font-size: 15px; } } } .checkbox { position: absolute; left: -50px; &:checked + .button + .body{ transform: translateX(0); z-index: 1; } &:checked + .button { animation: menuButton 0.4s linear; & .crocodile { background-color:transparent; transition-delay: 0.1s; } & .crocodile:before { transform: rotate(45deg) translateX(7px) translateY(6px); transition-delay: 0.1s; } & .crocodile:after { transform: rotate(-45deg) translateX(5px) translateY(-5px); transition-delay: 0.1s; } } } .button { display: block; width: 50px; height: 50px; border-radius: 100%; background: rgb(38, 165, 154); text-align: center; line-height: 50px; color: #fff; padding: 0; font-size: 20px; position: fixed; right: 10px; top: 10px; z-index: 2; outline:none; will-change: transform; z-index: 101; &:after, &:before { content: none; } &:focus{ outline:none; } & .crocodile, & .crocodile:before, & .crocodile:after { position:absolute; top:50%; left:50%; height:3px; width:26px; border-radius:10px; cursor:pointer; background:#fff; display:block; content:''; transition: transform 0.3s ease-in-out 0s; will-change: transform; } & .crocodile { margin: -1px 0 0 -13px; transition: background-color 0.2s ease 0s; &:before { margin: -10px 0 0 -13px; } &:after { margin: 6px 0 0 -13px; } } } } @keyframes menuButton { 0% { transform: scaleX(0); } 25% { transform: scaleX(-1); } 75% { transform: scaleX(0); } 100% { transform: scaleX(-1); } } </style> <file_sep><template> <div> <div v-bind:class="{volume_open: show}" class="volume volume_bottom volume_show-equalizer"> <div class="volume__holder"></div> <div class="volume__control"> <div class="volume__bar"> <div class="d-slider-vert volume__slider"> <input class="slider-v" type="range" orient="vertical" value="20" min="0" max="100"> </div> </div> </div> <div role="button" v-on:click="open" class="volume__btn"> <div class="volume__icon"></div> </div> </div> </div> </template> <script> export default { name: 'Volume', data() { return { show: false }; }, methods: { open() { this.show = !this.show; } } }; </script> <style lang="scss"> input[type=range][orient=vertical].slider-v{ transform: rotate(270deg); width: 130px; left: -50px; top: 60px; } .d-slider-vert{display:block;position:relative;width:32px;height:136px;} .volume{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:inline-block;position:relative;line-height:0;} .volume__btn{opacity:.4;position:relative;display:inline-block;cursor:pointer;} .volume__icon{position:relative;background:url(/static/volume.svg) center center no-repeat;background-position:0 0;display:inline-block;width:28px;height:28px;margin:6px;-webkit-box-sizing:border-box;box-sizing:border-box;} .volume__control{display:block;position:absolute;width:44px;height:198px;background:#fff;right:-2px;border:1px #e0e0e0 solid;border-radius:3px;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-box-shadow:0 15px 30px rgba(0, 0, 0, 0.2);box-shadow:0 15px 30px rgba(0, 0, 0, 0.2);opacity:0;z-index:-1;} .volume__control:after,.volume__control:before{display:block;position:absolute;content:"";width:0;height:0;border-style:solid;} .volume__control:before{right:16px;} .volume__control:after{right:18px;} .volume__bar{display:block;position:absolute;top:0;right:0;width:42px;height:100%;background:#f7f6f4;z-index:1;} .volume__slider.d-slider-vert{position:absolute;bottom:31px;left:50%;margin-left:-16px;} .volume__holder{display:none;position:absolute;width:100%;height:80px;left:0;} .volume_show-equalizer .volume__control{height:176px;} .volume_show-equalizer .volume__bar{bottom:37px;} .volume_open .volume__btn{opacity:1;} .volume_open .volume__control{opacity:1;z-index:10;} .volume_open .volume__holder{display:block;} .volume_bottom .volume__control{margin-bottom:65px;bottom:-500px;} .volume_bottom .volume__control:before{bottom:-6px;border-width:6px 6px 0 6px;border-color:#e0e0e0 transparent transparent transparent;} .volume_bottom .volume__control:after{bottom:-5px;border-width:5px 4px 0 4px;border-color:#f7f6f4 transparent transparent transparent;} .volume_bottom .volume__holder{bottom:0;} .volume_bottom.volume_open .volume__control{-webkit-animation:volume_bottom__expand 100ms ease-out;animation:volume_bottom__expand 100ms ease-out;bottom:10px;} </style> <file_sep>import api from './../api'; export default { GET_STATUS(context) { return Promise.all([ api('get_player_status').then(data => context.commit('status', data)) ]); }, GET_PLAYLIST_LIST(context, action) { return api('get_playlist_list', action.payload).then(data => { context.commit('playlist_list', data); }); } }; /* get_playlist_list get_song_current get_volume get_player_status get_playlist_crc */ <file_sep>export default { HOST: 'http://localhost', API: ':38475/' }; <file_sep><template> <div class="container"> <div> <Menu></Menu> <div role="main"> <div role="listbox" class="collection listbox"> <list-item v-for="(v, i) in list" v-bind:key="i" :opt="v" :num="i"></list-item> </div> </div> </div> </div> </template> <script> import ListItem from './ListItem.vue'; import Menu from './Menu.vue'; export default { name: 'Playlist', components: { ListItem, Menu }, data () { return {}; }, computed: { list() { return this.$store.getters['playlist_list']; } } }; </script> <style lang="scss"> .listbox { margin-top: 30px; } </style> <file_sep><template> <div id="app"> <router-view class="router" tag="main" /> <controll-bar tag="footer"></controll-bar> </div> </template> <script> import ControllBar from '@/components/ControllBar/ControllBar'; export default { name: 'app', components: { ControllBar } }; </script> <style lang="scss"> @import './style/materialize-css/sass/materialize.scss'; @import './style/fonts/material-icons.scss'; * { color: #666; } .router { position: fixed; left: 0; top: 0; right: 0; height: calc(100vh - 130px); overflow-y: auto; } input[type=range] { border: none; } @media only screen and (max-width: 600px) { .container{ width: 100%; } } </style> <file_sep>import Vue from 'vue'; import Router from 'vue-router'; import Playlist from '@/components/Playlist/Playlist'; Vue.use(Router); export default new Router({ routes: [ { path: '/', name: 'playlist', component: Playlist } ] });
001b0bb7c9df50537d6db5f7aef82cd591efabd9
[ "Markdown", "Vue", "JavaScript" ]
13
Markdown
avil13/aimp-web-ctl-vue
6a0c3bb943be4c1d94ed11f114c4e6fba30730ce
98a9d80ea95d076f2534667d1ffd4b4f9eaed59a
refs/heads/master
<repo_name>sudddy/Just-Copy<file_sep>/README.md # Just-Copy CHROME EXTENSION JUST COPY - Copy all tab links in just one click. You can perform any of the following : 1. Copy Links from Current Window Tabs 2. Copy Links from Other Window Tabs 3. Copy Selected Links #Developed by Sudharsan. #Design by <NAME> https://dribbble.com/Lakshmi_Narasimhan Watch how it works: YouTube - https://www.youtube.com/watch?v=1am6ACqPUmo&feature=youtu.be For Non-Chrome OS Users: HOW TO USE: 1. Download this project using "Clone or Download" option. 2. Goto "Chrome://extensions" in Google Chrome. 3. Enable Developer Mode options in right corner. 4. Then, Click on "Load unpacked Extension" and upload the downloaded folder. 5. Now you will see the "JUST COPY" Extension added to your chrome.
df42ee8698c7d749610ab16a77367842ccdc6a46
[ "Markdown" ]
1
Markdown
sudddy/Just-Copy
9bdfec74f79324c7bc74e878dbac7cb9d934eeb6
17fc1555c9a7298189abbaeab4c7526f5bd51668
refs/heads/master
<file_sep>////////// // // File: VRMovies.h // // Contains: Support for QuickTime movie playback in VR nodes. // // Written by: <NAME> // // Copyright: © 1997 by Apple Computer, Inc., all rights reserved. // // Change History (most recent first): // // <2> 10/21/02 era building Mach-O // <1> 12/11/96 rtm first file // ////////// #pragma once ////////// // // header files // ////////// #ifdef __MACH__ #include <Carbon/Carbon.h> #include <QuickTime/QuickTime.h> #else #ifndef __MOVIES__ #include <Movies.h> #endif #ifndef __MEDIAHANDLERS__ #include <MediaHandlers.h> #endif #ifndef __QDOFFSCREEN__ #include <QDOffscreen.h> #endif #ifndef __COLORPICKER__ #include <ColorPicker.h> #endif #ifndef __FIXMATH__ #include <FixMath.h> #endif #ifndef __QUICKTIMEVR__ #include <QuickTimeVR.h> #endif #endif #ifndef __QTVRUtilities__ #include "QTVRUtilities.h" #endif #ifndef __QTUtilities__ #include "QTUtilities.h" #endif #if TARGET_OS_WIN32 #ifndef _INC_COMMDLG #include <commdlg.h> #endif #endif #include "ComApplication.h" #include "ComFramework.h" ////////// // // compiler macros // ////////// #define RECT_WIDTH(rect) ((rect).right-(rect).left) #define RECT_HEIGHT(rect) ((rect).bottom-(rect).top) ////////// // // constants // ////////// #define kDefaultEmbMovieWidth QTVRUtils_DegreesToRadians(20.0) #define kColorPickerTextStringID 128 ////////// // // function prototypes // ////////// ApplicationDataHdl VRMoov_InitWindowData (WindowObject theWindowObject); void VRMoov_DumpWindowData (WindowObject theWindowObject); Boolean VRMoov_GetEmbeddedMovie (WindowObject theWindowObject); Boolean VRMoov_LoadEmbeddedMovie (FSSpec *theMovieFile, WindowObject theWindowObject); void VRMoov_LoopEmbeddedMovie (Movie theMovie); void VRMoov_DumpEmbeddedMovie (WindowObject theWindowObject); OSErr VRMoov_InstallBackBufferImagingProc (QTVRInstance theInstance, WindowObject theWindowObject); OSErr VRMoov_CalcImagingMatrix (WindowObject theWindowObject, Rect *theBBufRect); OSErr VRMoov_SetupDecompSeq (WindowObject theWindowObject, GWorldPtr theDestGWorld); OSErr VRMoov_RemoveDecompSeq (WindowObject theWindowObject); PASCAL_RTN OSErr VRMoov_BackBufferImagingProc (QTVRInstance theInstance, Rect *theRect, UInt16 theAreaIndex, UInt32 theFlagsIn, UInt32 *theFlagsOut, long theRefCon); float VRMoov_GetEmbeddedMovieWidth (WindowObject theWindowObject); void VRMoov_SetEmbeddedMovieWidth (WindowObject theWindowObject, float theWidth); void VRMoov_GetEmbeddedMovieCenter (WindowObject theWindowObject, QTVRFloatPoint *theCenter); void VRMoov_SetEmbeddedMovieCenter (WindowObject theWindowObject, const QTVRFloatPoint *theCenter); float VRMoov_GetEmbeddedMovieScale (WindowObject theWindowObject); void VRMoov_SetEmbeddedMovieScale (WindowObject theWindowObject, float theScale); void VRMoov_SetChromaColor (WindowObject theWindowObject); PASCAL_RTN OSErr VRMoov_UncoverProc (Movie theMovie, RgnHandle theRegion, long theRefCon); PASCAL_RTN Boolean VRMoov_ColorDialogEventFilter (EventRecord *theEvent); void VRMoov_SetVideoGraphicsMode (Movie theMovie, ApplicationDataHdl theAppData, Boolean theSetVGM); short VRMoov_GetVideoGraphicsPixelDepth (Movie theMovie); #if TARGET_OS_WIN32 void VRMoov_MacRGBToWinRGB (RGBColorPtr theRGBColor, COLORREF *theColorRef); void VRMoov_WinRGBToMacRGB (RGBColorPtr theRGBColor, COLORREF theColorRef); #endif<file_sep>////////// // // File: VRMovies.c // // Contains: Support for QuickTime movie playback in VR nodes. // // Written by: <NAME> // Some code borrowed from QTVRSamplePlayer by <NAME>. // // Copyright: © 1996-1998 by Apple Computer, Inc., all rights reserved. // // Change History (most recent first): // // <16> 03/20/00 rtm made changes to get things running under CarbonLib // <15> 06/23/99 rtm added VRMoov_MacRGBToWinRGB and VRMoov_WinRGBToMacRGB // <14> 06/22/99 rtm more work on matrices; now everything works okay (AFAICT) // <13> 06/21/99 rtm added call to UpdateMovie to back buffer imaging procedure // <12> 06/18/99 rtm got movie matrices working correctly; added color picking to Windows // <11> 06/17/99 rtm reworked geometry of back buffer yet again; now we copy from the // offscreen GWorld to back buffer using use DecompressSequenceFrameS // <10> 05/16/99 rtm added VRMoov_DumpWindowData; further work on geometry of back buffer // <9> 05/15/99 rtm reworked geometry handling to support horizontal back buffer in QT 4.0 // <8> 05/04/98 rtm added automatic rotation of movie // <7> 03/06/97 rtm started to implement video masking // <6> 03/05/97 rtm added VRMoov_SetChromaColor; added fChromaColor to app data record // <5> 03/04/97 rtm fixed compositing problems at back buffer edges // <4> 03/03/97 rtm added VRMoov_SetVideoGraphicsMode to handle compositing // without using an offscreen GWorld // <3> 02/27/97 rtm further development: borrowed some ideas from QTVRSamplePlayer; // added VRMoov_SetEmbeddedMovieWidth etc. // <2> 12/12/96 rtm further development: borrowed some ideas from BoxMoov demo // <1> 12/11/96 rtm first file // // This code draws the QuickTime movie frames into the back buffer, either directly // or indirectly (via an offscreen GWorld). Direct drawing gives the best performance, // but indirect drawing is necessary for some visual effects. // ////////// // TO DO: // + finish video masking by custom 'hide' hot spots (so video goes *behind* such hot spots) // + verify that everything works okay if *images* are used instead of movies (scaling seems to be a problem) ////////// // // header files // ////////// #include "VRMovies.h" ////////// // // constants // ////////// const RGBColor kClearColor = {0x0000, 0xffff, 0x0000}; // the default chroma key color const RGBColor kBlackColor = {0x0000, 0x0000, 0x0000}; const RGBColor kWhiteColor = {0xffff, 0xffff, 0xffff}; ////////// // // global variables // ////////// #if TARGET_OS_MAC UserEventUPP gColorFilterUPP = NULL; // UPP to our custom color picker dialog event filter #endif ////////// // // VRMoov_InitWindowData // Initialize any window-specific data. // ////////// ApplicationDataHdl VRMoov_InitWindowData (WindowObject theWindowObject) { #pragma unused(theWindowObject) ApplicationDataHdl myAppData; myAppData = (ApplicationDataHdl)NewHandleClear(sizeof(ApplicationDataRecord)); if (myAppData != NULL) { (**myAppData).fMovie = NULL; (**myAppData).fOffscreenGWorld = NULL; (**myAppData).fOffscreenPixMap = NULL; (**myAppData).fPrevBBufGWorld = NULL; (**myAppData).fMovieCenter.x = 0.0; (**myAppData).fMovieCenter.y = 0.0; (**myAppData).fMovieScale = 1.0; (**myAppData).fMovieWidth = kDefaultEmbMovieWidth; (**myAppData).fUseOffscreenGWorld = false; (**myAppData).fUseMovieCenter = true; (**myAppData).fQTMovieHasSound = false; (**myAppData).fCompositeMovie = false; (**myAppData).fUseHideRegion = false; (**myAppData).fChromaColor = kClearColor; (**myAppData).fHideRegion = NULL; (**myAppData).fBackBufferIsHoriz = false; (**myAppData).fImageDesc = NULL; (**myAppData).fImageSequence = 0; SetIdentityMatrix(&(**myAppData).fMovieMatrix); SetIdentityMatrix(&(**myAppData).fOrigMovieMatrix); // create a new routine descriptor (**myAppData).fBackBufferProc = NewQTVRBackBufferImagingUPP(VRMoov_BackBufferImagingProc); } #if TARGET_OS_MAC if (gColorFilterUPP == NULL) gColorFilterUPP = NewUserEventUPP(VRMoov_ColorDialogEventFilter); #endif return(myAppData); } ////////// // // VRMoov_DumpWindowData // Dispose of any window-specific data. // ////////// void VRMoov_DumpWindowData (WindowObject theWindowObject) { ApplicationDataHdl myAppData = NULL; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) return; VRMoov_DumpEmbeddedMovie(theWindowObject); DisposeQTVRBackBufferImagingUPP((**myAppData).fBackBufferProc); } /////////// // // VRMoov_GetEmbeddedMovie // Get the QuickTime movie to be embedded in a panorama. // Returns a Boolean to indicate success (true) or failure (false). // ////////// Boolean VRMoov_GetEmbeddedMovie (WindowObject theWindowObject) { FSSpec myFSSpec; OSType myTypeList = kQTFileTypeMovie; OSErr myErr = paramErr; // do some preliminary parameter checking if (theWindowObject == NULL) return(false); if (!QTFrame_IsWindowObjectOurs(theWindowObject)) return(false); // elicit the movie file from user myErr = QTFrame_GetOneFileWithPreview(1, (QTFrameTypeListPtr)&myTypeList, &myFSSpec, NULL); if (myErr != noErr) { VRMoov_DumpEmbeddedMovie(theWindowObject); // clean up any existing embedded movie return(false); } return(VRMoov_LoadEmbeddedMovie(&myFSSpec, theWindowObject)); } ////////// // // VRMoov_LoadEmbeddedMovie // Load the QuickTime movie in the specified file. // Returns a Boolean to indicate success (true) or failure (false). // ////////// Boolean VRMoov_LoadEmbeddedMovie (FSSpec *theMovieFile, WindowObject theWindowObject) { short myMovieFileRef; Movie myMovie; GWorldPtr myGWorld = NULL; Rect myRect; ApplicationDataHdl myAppData = NULL; OSErr myErr = paramErr; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) goto bail; HLock((Handle)myAppData); ////////// // // open the movie file and the movie // ////////// myErr = OpenMovieFile(theMovieFile, &myMovieFileRef, fsRdPerm); if (myErr != noErr) goto bail; myErr = NewMovieFromFile(&myMovie, myMovieFileRef, NULL, (StringPtr)NULL, newMovieActive, NULL); if (myErr != noErr) goto bail; ////////// // // get the movie geometry // ////////// GetMovieBox(myMovie, &myRect); GetMovieMatrix(myMovie, &(**myAppData).fOrigMovieMatrix); MacOffsetRect(&myRect, -myRect.left, -myRect.top); SetMovieBox(myMovie, &myRect); // keep track of the movie and movie rectangle (in our app-specific data structure) (**myAppData).fMovie = myMovie; (**myAppData).fMovieBox = myRect; // determine the orientation of the back buffer (**myAppData).fBackBufferIsHoriz = QTVRUtils_IsBackBufferHorizontal((**theWindowObject).fInstance); // get rid of any existing offscreen graphics world if ((**myAppData).fOffscreenGWorld != NULL) { DisposeGWorld((**myAppData).fOffscreenGWorld); (**myAppData).fOffscreenGWorld = NULL; } // clear out any existing custom cover/uncover functions and reset the video media graphics mode // (these may have been modified for direct-screen drawing) SetMovieCoverProcs(myMovie, NULL, NULL, 0L); VRMoov_SetVideoGraphicsMode(myMovie, myAppData, false); ////////// // // if necessary, create an offscreen graphics world // // this is where we'll image the movie before copying it into the back buffer // when we want to do special effects // ////////// if ((**myAppData).fUseOffscreenGWorld) { myErr = NewGWorld(&myGWorld, 0, &myRect, NULL, NULL, 0); (**myAppData).fOffscreenGWorld = myGWorld; (**myAppData).fOffscreenPixMap = GetGWorldPixMap(myGWorld); // make an image description, which is needed by DecompressSequenceBegin LockPixels((**myAppData).fOffscreenPixMap); MakeImageDescriptionForPixMap((**myAppData).fOffscreenPixMap, &((**myAppData).fImageDesc)); UnlockPixels((**myAppData).fOffscreenPixMap); } else { // set the video media graphics mode to drop out the chroma key color in a movie; // we also need to install an uncover function that doesn't erase the uncovered region if ((**myAppData).fCompositeMovie) { VRMoov_SetVideoGraphicsMode(myMovie, myAppData, true); SetMovieCoverProcs(myMovie, NewMovieRgnCoverUPP(VRMoov_UncoverProc), NULL, (long)theWindowObject); } } ////////// // // install the back-buffer imaging procedure // ////////// if ((**theWindowObject).fInstance != NULL) myErr = VRMoov_InstallBackBufferImagingProc((**theWindowObject).fInstance, theWindowObject); // start the movie playing in a loop VRMoov_LoopEmbeddedMovie(myMovie); bail: // we don't want to edit the embedded movie, so we can close the movie file if (myMovieFileRef != 0) CloseMovieFile(myMovieFileRef); HUnlock((Handle)myAppData); return(myErr == noErr); } ////////// // // VRMoov_LoopEmbeddedMovie // Start the QuickTime movie playing in a loop. // ////////// void VRMoov_LoopEmbeddedMovie (Movie theMovie) { TimeBase myTimeBase; // throw the movie into loop mode myTimeBase = GetMovieTimeBase(theMovie); SetTimeBaseFlags(myTimeBase, GetTimeBaseFlags(myTimeBase) | loopTimeBase); // start playing the movie StartMovie(theMovie); } ////////// // // VRMoov_DumpEmbeddedMovie // Stop any existing embedded movie from playing and then clean up. // ////////// void VRMoov_DumpEmbeddedMovie (WindowObject theWindowObject) { ApplicationDataHdl myAppData; if (theWindowObject == NULL) goto bail; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) goto bail; // if we have an embedded movie, stop it from playing and dispose of it if ((**myAppData).fMovie != NULL) { StopMovie((**myAppData).fMovie); DisposeMovie((**myAppData).fMovie); (**myAppData).fMovie = NULL; } // get rid of any existing offscreen graphics world if ((**myAppData).fOffscreenGWorld != NULL) { DisposeGWorld((**myAppData).fOffscreenGWorld); (**myAppData).fOffscreenGWorld = NULL; } // clear the existing back buffer imaging proc QTVRSetBackBufferImagingProc((**theWindowObject).fInstance, NULL, 0, NULL, 0); // clear out any other movie-specific data (**myAppData).fPrevBBufGWorld = NULL; MacSetRect(&(**myAppData).fPrevBBufRect, 0, 0, 0, 0); MacSetRect(&(**myAppData).fMovieBox, 0, 0, 0, 0); SetIdentityMatrix(&(**myAppData).fMovieMatrix); SetIdentityMatrix(&(**myAppData).fOrigMovieMatrix); if ((**myAppData).fImageDesc != NULL) { DisposeHandle((Handle)(**myAppData).fImageDesc); (**myAppData).fImageDesc = NULL; } VRMoov_RemoveDecompSeq(theWindowObject); // make sure the back buffer is clean QTVRRefreshBackBuffer((**theWindowObject).fInstance, 0); bail: return; } ////////// // // VRMoov_InstallBackBufferImagingProc // Install a back buffer imaging procedure. // (This routine might sometimes be called to move or resize the area of interest within the panorama.) // ////////// OSErr VRMoov_InstallBackBufferImagingProc (QTVRInstance theInstance, WindowObject theWindowObject) { ApplicationDataHdl myAppData; QTVRAreaOfInterest myArea; float myWidth, myHeight; OSErr myErr = noErr; ////////// // // initialize; clean up any existing back buffer procedure // ////////// if ((theInstance == NULL) || (theWindowObject == NULL)) return(paramErr); myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) return(paramErr); HLock((Handle)myAppData); // remove any existing back buffer imaging procedure if ((**myAppData).fBackBufferProc != NULL) QTVRSetBackBufferImagingProc(theInstance, NULL, 0, NULL, 0); ////////// // // set the area of interest // // the panAngle and tiltAngle fields define the top-left corner, in panorama space, of the area of interest; // so here we do not have to worry about whether the back buffer is oriented vertically or horizontally // ////////// // the application data structure holds the desired width, center, size, and scale of the movie myWidth = (**myAppData).fMovieWidth * (**myAppData).fMovieScale; myHeight = myWidth * (((float)(**myAppData).fMovieBox.bottom) / ((float)(**myAppData).fMovieBox.right)); if ((**myAppData).fUseMovieCenter) { // use the stored movie center myArea.panAngle = (**myAppData).fMovieCenter.x + (myWidth/2); myArea.tiltAngle = (**myAppData).fMovieCenter.y + (myHeight/2); } else { // center the movie on the current pan and tilt angles myArea.panAngle = QTVRGetPanAngle(theInstance) + (myWidth/2); myArea.tiltAngle = QTVRGetTiltAngle(theInstance) + (myHeight/2); } myArea.width = myWidth; myArea.height = myHeight; ////////// // // set the back buffer flags and install the back buffer procedure // ////////// // make sure we get called on every idle event, so we can keep playing the embedded movie; // also make sure we get called on every back buffer update if ((**myAppData).fCompositeMovie) myArea.flags = kQTVRBackBufferEveryIdle | kQTVRBackBufferEveryUpdate | kQTVRBackBufferAlwaysRefresh; else myArea.flags = kQTVRBackBufferEveryIdle | kQTVRBackBufferEveryUpdate; // if the back buffer is oriented horizontally, set the appropriate flag if ((**myAppData).fBackBufferIsHoriz) myArea.flags |= kQTVRBackBufferHorizontal; // install our procedure myErr = QTVRSetBackBufferImagingProc(theInstance, (**myAppData).fBackBufferProc, 1, &myArea, (SInt32)theWindowObject); HUnlock((Handle)myAppData); return(myErr); } ////////// // // VRMoov_CalcImagingMatrix // Calculate the movie matrix required to draw the embedded movie into the specified rectangle. // ////////// OSErr VRMoov_CalcImagingMatrix (WindowObject theWindowObject, Rect *theBBufRect) { ApplicationDataHdl myAppData = NULL; Rect myDestRect = *theBBufRect; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) return(paramErr); // reset the current movie matrix with the original movie matrix of the embedded movie; // we need to preserve that matrix in our calculations below if we are not drawing the // movie into an offscreen GWorld (**myAppData).fMovieMatrix = (**myAppData).fOrigMovieMatrix; // in general, it's easiest to construct the desired matrix by first doing the scaling // and then doing the rotation and translation (if necessary); so we need to swap the // right and bottom edges of the back buffer rectangle before doing the scaling, if a // rotation will also be necessary if (!(**myAppData).fBackBufferIsHoriz) { myDestRect.bottom = theBBufRect->right; myDestRect.right = theBBufRect->bottom; } // set up the scaling matrix // (MapMatrix concatenates the new matrix to the existing matrix, whereas RectMatrix first // sets the existing matrix to the identity matrix) if ((**myAppData).fUseOffscreenGWorld) RectMatrix(&(**myAppData).fMovieMatrix, &(**myAppData).fMovieBox, &myDestRect); else MapMatrix(&(**myAppData).fMovieMatrix, &(**myAppData).fMovieBox, &myDestRect); // add a rotation and translation, if necessary if (!(**myAppData).fBackBufferIsHoriz) { RotateMatrix(&(**myAppData).fMovieMatrix, Long2Fix(-90), 0, 0); TranslateMatrix(&(**myAppData).fMovieMatrix, 0, Long2Fix(RECT_HEIGHT(*theBBufRect))); } return(noErr); } ////////// // // VRMoov_SetupDecompSeq // Set up the decompression sequence for DecompressionSequenceFrameS. // // This needs to be called whenever either the rectangle or the GWorld of the back buffer changes. // ////////// OSErr VRMoov_SetupDecompSeq (WindowObject theWindowObject, GWorldPtr theDestGWorld) { ApplicationDataHdl myAppData = NULL; short myMode = srcCopy; OSErr myErr = noErr; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) return(paramErr); // make sure we don't have a decompression sequence already open VRMoov_RemoveDecompSeq(theWindowObject); // set up the transfer mode if ((**myAppData).fCompositeMovie) myMode = srcCopy | transparent; // set up the image decompression sequence myErr = DecompressSequenceBegin( &(**myAppData).fImageSequence, (**myAppData).fImageDesc, (CGrafPtr)theDestGWorld, NULL, NULL, // entire source image &(**myAppData).fMovieMatrix, myMode, NULL, // no mask 0, (**(**myAppData).fImageDesc).spatialQuality, NULL); return(myErr); } ////////// // // VRMoov_RemoveDecompSeq // Remove the decompression sequence for DecompressionSequenceFrameS. // ////////// OSErr VRMoov_RemoveDecompSeq (WindowObject theWindowObject) { ApplicationDataHdl myAppData = NULL; OSErr myErr = paramErr; if (theWindowObject != NULL) { myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData != NULL) if ((**myAppData).fImageSequence != 0) { myErr = CDSequenceEnd((**myAppData).fImageSequence); (**myAppData).fImageSequence = 0; } } return(myErr); } ////////// // // VRMoov_BackBufferImagingProc // The back buffer imaging procedure: get a frame of movie and image it into the back buffer. // Also, do any additional compositing that might be desired. // ////////// PASCAL_RTN OSErr VRMoov_BackBufferImagingProc (QTVRInstance theInstance, Rect *theRect, UInt16 theAreaIndex, UInt32 theFlagsIn, UInt32 *theFlagsOut, long theRefCon) { #pragma unused(theAreaIndex) WindowObject myWindowObject = (WindowObject)theRefCon; ApplicationDataHdl myAppData = NULL; Movie myMovie = NULL; Boolean myIsDrawing = theFlagsIn & kQTVRBackBufferRectVisible; GWorldPtr myBBufGWorld, myMovGWorld; GDHandle myBBufGDevice, myMovGDevice; Rect myRect; OSErr myErr = paramErr; ////////// // // initialize; make sure that we've got the data we need to continue // ////////// // assume we're not going to draw anything *theFlagsOut = 0; if ((theInstance == NULL) || (myWindowObject == NULL)) goto bail; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(myWindowObject); if (myAppData == NULL) goto bail; HLock((Handle)myAppData); myMovie = (**myAppData).fMovie; if (myMovie == NULL) { // we don't have an embedded movie, so remove this back-buffer imaging procedure VRMoov_DumpEmbeddedMovie(myWindowObject); goto bail; } ////////// // // make sure that the movie GWorld is set correctly; // note that we call SetMovieGWorld only if we have to (for performance reasons) // ////////// // get the current graphics world // (on entry, the current graphics world is [usually] set to the back buffer) GetGWorld(&myBBufGWorld, &myBBufGDevice); // get the embedded movie's graphics world GetMovieGWorld(myMovie, &myMovGWorld, &myMovGDevice); if ((**myAppData).fUseOffscreenGWorld) { // we're using an offscreen graphics world, so set movie's GWorld to be that offscreen graphics world if (myMovGWorld != (**myAppData).fOffscreenGWorld) SetMovieGWorld(myMovie, (**myAppData).fOffscreenGWorld, GetGWorldDevice((**myAppData).fOffscreenGWorld)); } else { // we're not using an offscreen graphics world, so set movie GWorld to be the back buffer; if ((myMovGWorld != myBBufGWorld) || (myMovGDevice != myBBufGDevice)) SetMovieGWorld(myMovie, myBBufGWorld, myBBufGDevice); } ////////// // // make sure the movie rectangle and movie matrix are set correctly // ////////// if (myIsDrawing) { // if we weren't previously visible, make sure we are now GetMovieBox(myMovie, &myRect); if (EmptyRect(&myRect)) SetMovieBox(myMovie, &(**myAppData).fMovieBox); // when no offscreen GWorld is being used... if (!(**myAppData).fUseOffscreenGWorld) { // ...make sure the movie matrix is set correctly... if (!MacEqualRect(theRect, &(**myAppData).fPrevBBufRect)) { VRMoov_CalcImagingMatrix(myWindowObject, theRect); SetMovieMatrix(myMovie, &(**myAppData).fMovieMatrix); } // ...and, if we are compositing, force QuickTime to draw a movie frame when MoviesTask is called // (since the previous frame was automatically erased from the back buffer by QuickTime VR) if ((**myAppData).fCompositeMovie) UpdateMovie(myMovie); } } else { // if we're not visible, set the movie rectangle to an empty rectangle // so we're not wasting time trying to draw a movie frame MacSetRect(&myRect, 0, 0, 0, 0); SetMovieBox(myMovie, &myRect); } ////////// // // draw a new movie frame into the movie's graphics world (and play movie sound) // ////////// MoviesTask(myMovie, 1L); // MoviesTask(myMovie, 0); // if we got here, everything is okay so far myErr = noErr; ////////// // // perform any additional compositing // ////////// // that is, draw, using the current chroma key color, anything to be dropped out of the image; // note that this technique works *only* if we're using an offscreen graphics world if ((**myAppData).fUseOffscreenGWorld && (**myAppData).fCompositeMovie && myIsDrawing) { RGBColor myColor; // since we're using an offscreen graphics world, make sure we draw there SetGWorld((**myAppData).fOffscreenGWorld, GetGWorldDevice((**myAppData).fOffscreenGWorld)); // set up compositing environment GetForeColor(&myColor); RGBForeColor(&(**myAppData).fChromaColor); // do the drawing if ((**myAppData).fHideRegion != NULL) MacPaintRgn((**myAppData).fHideRegion); // restore original drawing environment RGBForeColor(&myColor); // restore original graphics world SetGWorld(myBBufGWorld, myBBufGDevice); } ////////// // // if we're using an offscreen graphics world, copy it into the back buffer // ////////// if (myIsDrawing) { if ((**myAppData).fUseOffscreenGWorld) { PixMapHandle myPixMap; // if anything relevant to DecompressSequenceFrameS has changed, reset the decompression sequence if ((myBBufGWorld != (**myAppData).fPrevBBufGWorld) || !(MacEqualRect(theRect, &(**myAppData).fPrevBBufRect))) { VRMoov_CalcImagingMatrix(myWindowObject, theRect); VRMoov_SetupDecompSeq(myWindowObject, myBBufGWorld); } myPixMap = GetGWorldPixMap((**myAppData).fOffscreenGWorld); LockPixels(myPixMap); // set the chroma key color, if necessary if ((**myAppData).fCompositeMovie) RGBBackColor(&(**myAppData).fChromaColor); // copy the image from the offscreen graphics world into the back buffer myErr = DecompressSequenceFrameS( (**myAppData).fImageSequence, #if TARGET_CPU_68K StripAddress(GetPixBaseAddr(myPixMap)), #else GetPixBaseAddr(myPixMap), #endif (**(**myAppData).fImageDesc).dataSize, 0, NULL, NULL); // reset the chroma key color; // we need to do this because the buffer we just drew into might NOT actually // be the real back buffer (see Virtual Reality Programming With QuickTime VR, p. 1-154); // the copy between the intermediate buffer and the back buffer respects the current back color. if ((**myAppData).fCompositeMovie) RGBBackColor(&kWhiteColor); UnlockPixels(myPixMap); } } ////////// // // finish up // ////////// // keep track of the GWorld and rectangle passed to us this time (**myAppData).fPrevBBufGWorld = myBBufGWorld; (**myAppData).fPrevBBufRect = *theRect; // if we drew something, tell QuickTime VR if (myIsDrawing) *theFlagsOut = kQTVRBackBufferFlagDidDraw; bail: HUnlock((Handle)myAppData); return(myErr); } ////////// // // VRMoov_GetEmbeddedMovieWidth // Get the width of the embedded movie. // ////////// float VRMoov_GetEmbeddedMovieWidth (WindowObject theWindowObject) { ApplicationDataHdl myAppData; float myWidth; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) myWidth = 0; else myWidth = (**myAppData).fMovieWidth; return(myWidth); } ////////// // // VRMoov_SetEmbeddedMovieWidth // Set the width of the embedded movie. // ////////// void VRMoov_SetEmbeddedMovieWidth (WindowObject theWindowObject, float theWidth) { ApplicationDataHdl myAppData; QTVRInstance myInstance; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) return; myInstance = (**theWindowObject).fInstance; if (myInstance == NULL) return; // install the desired width in our application data structure (**myAppData).fMovieWidth = theWidth; // clear out the existing area of interest QTVRRefreshBackBuffer(myInstance, 0); // reinstall the back buffer imaging procedure VRMoov_InstallBackBufferImagingProc(myInstance, theWindowObject); } ////////// // // VRMoov_GetEmbeddedMovieCenter // Get the center of the embedded movie. // ////////// void VRMoov_GetEmbeddedMovieCenter (WindowObject theWindowObject, QTVRFloatPoint *theCenter) { ApplicationDataHdl myAppData; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) { theCenter->x = 0.0; theCenter->y = 0.0; } else { theCenter->x = (**myAppData).fMovieCenter.x; theCenter->y = (**myAppData).fMovieCenter.y; } } ////////// // // VRMoov_SetEmbeddedMovieCenter // Set the center of the embedded movie. // ////////// void VRMoov_SetEmbeddedMovieCenter (WindowObject theWindowObject, const QTVRFloatPoint *theCenter) { ApplicationDataHdl myAppData; QTVRInstance myInstance; float myX, myY; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) return; myInstance = (**theWindowObject).fInstance; if (myInstance == NULL) return; myX = theCenter->x; myY = theCenter->y; // subject the values passed in to the current view constraints QTVRWrapAndConstrain(myInstance, kQTVRPan, myX, &myX); QTVRWrapAndConstrain(myInstance, kQTVRTilt, myY, &myY); // install the desired center in our application data structure (**myAppData).fMovieCenter.x = myX; (**myAppData).fMovieCenter.y = myY; // clear out the existing area of interest QTVRRefreshBackBuffer(myInstance, 0); // reinstall the back buffer imaging procedure VRMoov_InstallBackBufferImagingProc(myInstance, theWindowObject); } ////////// // // VRMoov_GetEmbeddedMovieScale // Get the scale of the embedded movie. // ////////// float VRMoov_GetEmbeddedMovieScale (WindowObject theWindowObject) { ApplicationDataHdl myAppData; float myScale; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) myScale = 0; else myScale = (**myAppData).fMovieScale; return(myScale); } ////////// // // VRMoov_SetEmbeddedMovieScale // Set the scale factor of the embedded movie. // ////////// void VRMoov_SetEmbeddedMovieScale (WindowObject theWindowObject, float theScale) { ApplicationDataHdl myAppData; QTVRInstance myInstance; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) return; myInstance = (**theWindowObject).fInstance; if (myInstance == NULL) return; // install the desired scale factor in our application data structure (**myAppData).fMovieScale = theScale; // clear out the existing area of interest QTVRRefreshBackBuffer(myInstance, 0); // reinstall the back buffer imaging procedure VRMoov_InstallBackBufferImagingProc(myInstance, theWindowObject); } ////////// // // VRMoov_SetChromaColor // Set the chroma key color for a window object: // display color picker dialog and remember the newly-selected color. // ////////// void VRMoov_SetChromaColor (WindowObject theWindowObject) { #if TARGET_OS_MAC ColorPickerInfo myColorInfo; #endif #if TARGET_OS_WIN32 static CHOOSECOLOR myColorRec; static COLORREF myColorRef[16]; #endif ApplicationDataHdl myAppData; myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindowObject(theWindowObject); if (myAppData == NULL) return; #if TARGET_OS_MAC // pass in existing color myColorInfo.theColor.color.rgb.red = (**myAppData).fChromaColor.red; myColorInfo.theColor.color.rgb.green = (**myAppData).fChromaColor.green; myColorInfo.theColor.color.rgb.blue = (**myAppData).fChromaColor.blue; // not much here... myColorInfo.theColor.profile = 0L; myColorInfo.dstProfile = 0L; myColorInfo.flags = 0L; myColorInfo.placeWhere = kCenterOnMainScreen; myColorInfo.pickerType = 0L; myColorInfo.eventProc = gColorFilterUPP; myColorInfo.colorProc = NULL; myColorInfo.colorProcData = 0L; GetIndString(myColorInfo.prompt, kColorPickerTextStringID, 1); // set Edit menu info myColorInfo.mInfo.editMenuID = kEditMenuResID; myColorInfo.mInfo.undoItem = MENU_ITEM(IDM_EDITUNDO); myColorInfo.mInfo.cutItem = MENU_ITEM(IDM_EDITCUT); myColorInfo.mInfo.copyItem = MENU_ITEM(IDM_EDITCOPY); myColorInfo.mInfo.pasteItem = MENU_ITEM(IDM_EDITPASTE); myColorInfo.mInfo.clearItem = MENU_ITEM(IDM_EDITCLEAR); // call Color Picker if ((PickColor(&myColorInfo) == noErr) && (myColorInfo.newColorChosen)) { // install the newly chosen color in the palette (**myAppData).fChromaColor.red = myColorInfo.theColor.color.rgb.red; (**myAppData).fChromaColor.green = myColorInfo.theColor.color.rgb.green; (**myAppData).fChromaColor.blue = myColorInfo.theColor.color.rgb.blue; } #endif #if TARGET_OS_WIN32 myColorRec.lStructSize = sizeof(CHOOSECOLOR); myColorRec.hwndOwner = NULL; myColorRec.hInstance = NULL; VRMoov_MacRGBToWinRGB(&(**myAppData).fChromaColor, &(myColorRec.rgbResult)); myColorRec.lpCustColors = myColorRef; myColorRec.Flags = CC_RGBINIT | CC_FULLOPEN; myColorRec.lCustData = 0; myColorRec.lpfnHook = NULL; myColorRec.lpTemplateName = NULL; // call Common Color dialog if (ChooseColor(&myColorRec)) { // install the newly chosen color in the palette VRMoov_WinRGBToMacRGB(&(**myAppData).fChromaColor, myColorRec.rgbResult); } #endif } ////////// // // VRMoov_ColorDialogEventFilter // Handle events before they get passed to the Color Picker dialog box. // ////////// PASCAL_RTN Boolean VRMoov_ColorDialogEventFilter (EventRecord *theEvent) { #if TARGET_OS_WIN32 #pragma unused(theEvent) #endif Boolean myEventHandled = false; OSErr myErr = noErr; #if TARGET_OS_MAC switch (theEvent->what) { case updateEvt: { if ((WindowPtr)theEvent->message != FrontWindow()) { QTFrame_HandleEvent(theEvent); myEventHandled = true; } break; } case nullEvent: { // do idle-time processing for all open windows in our window list WindowObject myWindowObject = NULL; ApplicationDataHdl myAppData = NULL; WindowReference myWindow = NULL; myWindow = QTFrame_GetFrontMovieWindow(); while (myWindow != NULL) { myWindowObject = (WindowObject)QTFrame_GetWindowObjectFromWindow(myWindow); myAppData = (ApplicationDataHdl)QTFrame_GetAppDataFromWindow(myWindow); if ((myWindowObject != NULL) && (myAppData != NULL)) if ((**myAppData).fMovie != NULL) QTVRUpdate((**myWindowObject).fInstance, kQTVRCurrentMode); myWindow = QTFrame_GetNextMovieWindow(myWindow); } myEventHandled = false; break; } case kHighLevelEvent: myErr = AEProcessAppleEvent(theEvent); if (myErr != noErr) myEventHandled = true; break; default: myEventHandled = false; break; } #endif return(myEventHandled); } ////////// // // VRMoov_UncoverProc // The uncover function of the embedded movie. // ////////// PASCAL_RTN OSErr VRMoov_UncoverProc (Movie theMovie, RgnHandle theRegion, long theRefCon) { #pragma unused(theMovie, theRegion, theRefCon) return(noErr); } ////////// // // VRMoov_SetVideoGraphicsMode // Set the video media graphics mode of the embedded movie. // ////////// void VRMoov_SetVideoGraphicsMode (Movie theMovie, ApplicationDataHdl theAppData, Boolean theSetVGM) { long myTrackCount; short myIndex; Track myTrack = NULL; Media myMedia = NULL; OSType myMediaType; if ((theMovie == NULL) || (theAppData == NULL)) return; myTrackCount = GetMovieTrackCount(theMovie); for (myIndex = 1; myIndex <= myTrackCount; myIndex++) { myTrack = GetMovieIndTrack(theMovie, myIndex); myMedia = GetTrackMedia(myTrack); GetMediaHandlerDescription(myMedia, &myMediaType, NULL, NULL); if (myMediaType == VideoMediaType) { if (theSetVGM) MediaSetGraphicsMode(GetMediaHandler(myMedia), srcCopy | transparent, &(**theAppData).fChromaColor); else MediaSetGraphicsMode(GetMediaHandler(myMedia), srcCopy, &kWhiteColor); } } return; } ////////// // // VRMoov_GetVideoGraphicsPixelDepth // Return the highest pixel depth supported by a QuickTime movie. // ////////// short VRMoov_GetVideoGraphicsPixelDepth (Movie theMovie) { long myTrackCount; short myIndex; Track myMovieTrack = NULL; Media myMedia; OSType myMediaType; short myQuality; myTrackCount = GetMovieTrackCount(theMovie); for (myIndex = 1; myIndex <= myTrackCount; myIndex++) { myMovieTrack = GetMovieIndTrack(theMovie, myIndex); myMedia = GetTrackMedia(myMovieTrack); GetMediaHandlerDescription(myMedia, &myMediaType, NULL, NULL); if (myMediaType == VideoMediaType) { myQuality = GetMediaQuality(myMedia); if (myQuality >> 5) return(32); if (myQuality >> 4) return(16); if (myQuality >> 3) return(8); if (myQuality >> 2) return(4); if (myQuality >> 1) return(2); if (myQuality >> 0) return(1); } } return(0); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Color conversion utilities. // // Macintosh usually represents colors using an RGBColor structure, where each color component is a 16-bit // unsigned integer. Windows represents colors using a 32-bit unsigned COLORREF, where each color component // occupies 8 bits. The following two functions allow us to convert from Mac to Windows colors and back. We // need to do this because we use Mac-style colors when doing compositing. // /////////////////////////////////////////////////////////////////////////////////////////////////////////// #if TARGET_OS_WIN32 #define kMaxMacRGBValue 0xffff #define kMaxWinRGBValue 0x00ff #define MAC_TO_WIN_COMP(color) (color*((float)kMaxWinRGBValue/(float)kMaxMacRGBValue)) #define WIN_TO_MAC_COMP(color) (color*((float)kMaxMacRGBValue/(float)kMaxWinRGBValue)) ////////// // // VRMoov_MacRGBToWinRGB // Convert an RGBColor structure into a COLORREF value. // ////////// void VRMoov_MacRGBToWinRGB (RGBColorPtr theRGBColor, COLORREF *theColorRef) { *theColorRef = RGB( (BYTE)MAC_TO_WIN_COMP(theRGBColor->red), (BYTE)MAC_TO_WIN_COMP(theRGBColor->green), (BYTE)MAC_TO_WIN_COMP(theRGBColor->blue)); } ////////// // // VRMoov_WinRGBToMacRGB // Convert a COLORREF value into an RGBColor structure. // ////////// void VRMoov_WinRGBToMacRGB (RGBColorPtr theRGBColor, COLORREF theColorRef) { theRGBColor->red = (unsigned long)WIN_TO_MAC_COMP(GetRValue(theColorRef)); theRGBColor->green = (unsigned long)WIN_TO_MAC_COMP(GetGValue(theColorRef)); theRGBColor->blue = (unsigned long)WIN_TO_MAC_COMP(GetBValue(theColorRef)); } #endif // TARGET_OS_WIN32 <file_sep>README - VRMovies VRMovies uses the QuickTime VR API to provide support for playing QuickTime movies in a panorama. PowerPC, 680x0, and Windows versions are provided. Enjoy, QuickTime Team <file_sep>////////// // // File: ComApplication.h // // Contains: Functions that could be overridden in a specific application. // // Written by: <NAME> // // Copyright: © 1999 by Apple Computer, Inc., all rights reserved. // // Change History (most recent first): // // <2> 10/21/02 era building Mach-O // <1> 11/05/99 rtm first file; based on earlier sample code // ////////// #pragma once #ifndef __ComApplication__ #define __ComApplication__ ////////// // // header files // ////////// #ifdef __MACH__ #include <Carbon/Carbon.h> #include <QuickTime/QuickTime.h> #else #ifndef __QUICKTIMEVR__ #include <QuickTimeVR.h> #endif #ifndef __TEXTUTILS__ #include <TextUtils.h> #endif #ifndef __SCRIPT__ #include <Script.h> #endif #if TARGET_OS_MAC #ifndef __APPLEEVENTS__ #include <AppleEvents.h> #endif #endif #endif #if TARGET_OS_MAC #include "MacFramework.h" #endif #if TARGET_OS_WIN32 #include "WinFramework.h" #endif #ifndef __QTUtilities__ #include "QTUtilities.h" #endif #include "ComResource.h" ////////// // // constants // ////////// ////////// // // structures // ////////// // application-specific data typedef struct ApplicationDataRecord { Movie fMovie; // the embedded movie to play GWorldPtr fOffscreenGWorld; // the offscreen graphics world used for imaging embedded movies PixMapHandle fOffscreenPixMap; // the pixmap of the offscreen graphics world GWorldPtr fPrevBBufGWorld; // the previous offscreen graphics world used for the back buffer Rect fPrevBBufRect; // the previous rectangle of the area of interest QTVRFloatPoint fMovieCenter; // the center in the panorama of the movie screen (in angles: x = pan; y = tilt) Rect fMovieBox; // the movie box float fMovieScale; // a scale factor for the movie rectangle float fMovieWidth; // the width (in radians) of the embedded movie Boolean fUseOffscreenGWorld;// use an offscreen GWorld? Boolean fUseMovieCenter; // use the specified movie center? Boolean fQTMovieHasSound; // does the embedded movie have a sound track? Boolean fCompositeMovie; // does the embedded movie need to be composited? Boolean fUseHideRegion; // use the specified movie hide region? QTVRBackBufferImagingUPP fBackBufferProc; // a routine descriptor for our back buffer routine RGBColor fChromaColor; // the color for chroma key compositing RgnHandle fHideRegion; // the region that obscures the embedded movie MatrixRecord fMovieMatrix; // the matrix we use to (optionally) rotate the movie MatrixRecord fOrigMovieMatrix; // the movie's original matrix Boolean fBackBufferIsHoriz; // is the backbuffer oriented horizontally? ImageDescriptionHandle fImageDesc; // image description for DecompressSequenceFrameS ImageSequence fImageSequence; // image sequence for DecompressSequenceFrameS } ApplicationDataRecord, *ApplicationDataPtr, **ApplicationDataHdl; ////////// // // function prototypes // ////////// #if TARGET_OS_MAC void QTApp_InstallAppleEventHandlers (void); PASCAL_RTN OSErr QTApp_HandleOpenApplicationAppleEvent (const AppleEvent *theMessage, AppleEvent *theReply, long theRefcon); PASCAL_RTN OSErr QTApp_HandleOpenDocumentAppleEvent (const AppleEvent *theMessage, AppleEvent *theReply, long theRefcon); PASCAL_RTN OSErr QTApp_HandlePrintDocumentAppleEvent (const AppleEvent *theMessage, AppleEvent *theReply, long theRefcon); PASCAL_RTN OSErr QTApp_HandleQuitApplicationAppleEvent (const AppleEvent *theMessage, AppleEvent *theReply, long theRefcon); #endif // TARGET_OS_MAC // the other function prototypes are in the file MacFramework.h or WinFramework.h #endif // __ComApplication__
13a5cf8be702451a7bc5917dcbd1ee153a5e32fc
[ "Text", "C" ]
4
Text
fruitsamples/vrmovies.win
948bed3b2786009e85671785166cef85ba3580ba
33195405d1818745ea1af3fa865db16332c18329
refs/heads/master
<repo_name>jaimeneto85/hicamera<file_sep>/README.md # HiCamera Módulo para gerenciamento de câmera para fotos, vídeos e enviar da galeria para o React Native. O objetivo do módulo é tornar mais prático o recurso visual de visualizar e selecionar imagens e/ou vídeo do aparelho. ## Dependências - `react-native-camera` - `fotoapparat` ## CameraVideo Módulo que retorna component com a Câmera ativa. Uso: ``` import {CameraVideo} from 'hicamera' ``` ##### Props * [containerStyle](#containerStyle) * [cameraStyle](#cameraStyle) * [cameraType](#cameraType) <!-- * [quality](#quality) --> * [orientation](#orientation) * [maxDuration](#maxDuration) ###### containerStyle `Object` estilo da View que leva a câmera ###### cameraStyle `Object` estilo da Câmera em si ###### cameraType `Integer` valor `0` (default) ou `1`, onde representa: - `0` camera traseira - `1` camera dianteira <!-- ###### quality `Object` estilo da Câmera em si --> ###### orientation `String` orientação da câmera. Valores: "portrait", "portraitUpsideDown", "landscapeLeft" or "landscapeRight" ###### maxDuration `Integer` valor máximo (em segundos) da gravação do vídeo. Sem atribuir a propriedade, o vídeo só é encerrado quando o usuário escolher ##### Methods * getVideo * onStartRecording * onStopRecording ## CameraPhoto ## Gallery Módulo que retorna as fotos do aparelho. Uso: ``` import {Gallery} from 'hicamera' ``` ##### Props * [itemStyle](#itemStyle) * [title](#title) * [titleStyle](#titleStyle) * [containerStyle](#containerStyle) * [galleryType](#galleryType) * [group](#group) * [filterBy](#filterBy) * [selectedStyle](#selectedStyle) * [selectedComponent](#selectedComponent) * [maxSelect](#maxSelect) * [overwriteSelected](#overwriteSelected) ###### itemStyle `Object` estilo de cada item de mídia a ser apresentado na galeria ###### title `String` título a ser exibido no topo da galeria (não enviar a propriedade faz com que o título não exista) ###### titleStyle `Object` estilo do título do componente ###### containerStyle `Object` estilo de todo componente ###### galleryType `String` Utilize uma das opções: 'All', 'Photos', 'Videos' 'Photos' é o valor default ###### group - Album - All - Event - Faces - Library - PhotoStream - SavedPhotos // default ###### filterBy `String` or `null` Utilize para filtrar o retorno das mídias de acordo com o álbum escolhido. Exemplo: ```javascript <TouchableOpacity onPress={() => this.setState({filter: 'MyAlbum'})}> <Text>Ver MyAlbum</Text> </TouchableOpacity> <Gallery filterBy={this.state.filter} /> ``` ###### selectedStyle `Object` Estilo para os items selecionados ###### selectedComponent `JSX` or `null` React Component para elemento que aparecerá junto à mídia selecionada. Recomendo utilizar style com position *absolute* ###### maxSelect `Number` Máximo de items que podem ser selecionados (default: 1) - precisa ser maior ou igual a 1 ###### overwriteSelected `Boolean` Quando o número máximo de items for maior que 1, você pode escolher o comportamento. - `true` quando o número de items ultrapassa o limite, ele começa a substituir os items selecionados, acrescentando o último - `false` (default) quando o número de items atinge o limite, os próximos toques se tornam sem ação (para selecionar novos) - para desselecionar o toque continua funcionando. ##### Methods * getAlbums * selectedItems ###### getAlbums Método que retorna os albums do dispositivo. Assim, é possível utilizar a propriedade filterBy Exemplo: ```javascript _getAlbums = (albums) => { this.setState({albums}) } <Gallery getAlbums={this._getAlbums}> ``` ###### selectedItems Método que retorna um array com os items selecionados. Exemplo: ```javascript _selectedItems = (items) => { this.setState({itemsSelected: items}) } <Gallery selectedItems={this._selectedItems}> ```
016989a8a861f33534b26f95afd3a4e8588fe4c0
[ "Markdown" ]
1
Markdown
jaimeneto85/hicamera
387a3590f747a8ca2243a2c58606495b33bfa44b
1b68d961d8d0f397c9b27f06a6409febe73cacc5
refs/heads/master
<repo_name>fabiaov/loja<file_sep>/loja/index.php <html> <?php include("cabecalho.php"); include("logica-usuario.php"); ?> <h1>Bem vindo à loja do Fabio!!</h1> <?php if(usuarioEstaLogado()){ ?> <p class="text-success">Você esta logado como <?=usuarioLogado()?>. <a href="logout.php"><button class="btn btn-primary">Deslogar</button></a></p> <?php } else {?> <h2>Login</h2> <form action="login.php" method="post"> <table class="table"> <tr> <td>Email:</td> <td><input class="form-control" type="email" name="email"></td> </tr> <tr> <td>Senha:</td> <td><input class="form-control" type="<PASSWORD>" name="senha"></td> </tr> <tr> <td><button class="btn btn-primary">Login</button></td> </tr> </table> </form> <?php } ?> <?php include ("rodape.php") ?> </html<file_sep>/loja/banco-categoria.php <?php function listaCategorias($conexao){ $categorias = array(); $query = "select * from categorias"; // query que busca no banco de dados pega todos os elementos da tabela $resultado = mysqli_query($conexao, $query); // msqli_query executa essa query que busca do banco de dados e executa while($categoria = mysqli_fetch_assoc($resultado)){ array_push($categorias, $categoria); //fazemos um while para cada linha da tabela que o mysqli_query = $resultado vai nos trazer nisso usamos a $categoria = mysqli_fetch_assoc($resultado) para associar o resultado e jogar na variavel categoria , dentro do while fazemos o array_push ($categorias, $categoria); pois pedimos pra ele jogar o resultado de $categoria em $categorias. } return $categorias; }<file_sep>/loja/cabecalho.php <?php error_reporting(E_ALL ^ E_NOTICE); include("mostra-alerta.php"); ?> <html> <head> <title>Minha loja</title> <meta charset="utf-8"> <link href="css/bootstrap.css" rel="stylesheet" /> <link href="css/loja.css" rel="stylesheet" /> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <!-- primeira coisa vai ser um menu ele é uma <div> navbar é o nome da classe do bootstrap --> <div class="container"> <!-- tudo que for fazer do bootstrap no menu ou seja dentro do menu vou colocar dentro do meu container --> <div class="navbar-header"> <!-- coloco o nome da loja e um link pra pagina da loja --> <a class="navbar-brand" href="index.php">Minha Loja</a> <!--a class navbar-brand link de navegação, href="" => dentro do "" vc coloca o nomedapagina.php pra qual o header vai direcionar para a pagina do link que está dentro do href--> </div> <div> <ul class="nav navbar-nav"> <!-- lista de opções --> <li><a href="produto-formulario.php">Adiciona Produto </a></li> <!-- cada item é um <li> --> <li><a href="sobre.php">Sobre</a></li> <li><a href="produto-lista.php">Produtos</a></li> </ul> </div> </div> </div> <div class="container"> <div class="principal"> <?php mostraAlerta("success"); ?> <?php mostraAlerta("danger"); ?> <!-- fim cabecalho.php -->
67de2f623e690875567c599a86b534f793ccd999
[ "PHP" ]
3
PHP
fabiaov/loja
038667729e504ada440d6daf2176d0f2ed6cf3f9
19028be924f569156513804fe183f709ac1adc50
refs/heads/master
<file_sep>(function() { if (/*@cc_on!@*/0) { // execute only in Internet Explorer var elements = [ "abbr", // for IE 6 "mark", "meter", "progress", "time"//, ], i = elements.length; while (i--) { document.createElement(elements[i]); } } })(); <file_sep>(function() { if (/*@cc_on!@*/0) { // execute only in Internet Explorer var elements = [ "article", "aside", "footer", "header", "hgroup", "nav", "section"//, ], i = elements.length; while (i--) { document.createElement(elements[i]); } } })();
9124beb19f58e050202d664ed5a5b9b307006a17
[ "JavaScript" ]
2
JavaScript
cgriego/html5-scaffold
02061fea3559b1721abb460feb0b62c66a009ec3
eed524149e9c11e408bed68558d49f686f083d7f
refs/heads/master
<repo_name>gobinbash/next-apollo-auth<file_sep>/server/services/passport.js const passport = require('passport') const mongoose = require('mongoose') const User = require('../models/User') const GitHubStrategy = require('passport-github').Strategy passport.use( new GitHubStrategy( { clientID: process.env.GithubClientID, clientSecret: process.env.GithubClientSecret, callbackURL: process.env.GithubCallbackURL }, (accessToken, refreshToken, profile, cb) => { const { email, name } = profile._json // Auto-link account User.findOne({ email }) .then(user => { if (!user) { let data = { email, fullname: name, providers: ['github'] } User.create(data).then(user => cb(null, user)) } else { // Update Provider to DB if not added User.findOneAndUpdate( { email, providers: { $ne: 'github' } }, { $push: { providers: 'github' } } ).exec() return cb(null, user) } }) .catch(err => cb(err)) } ) ) passport.use(User.createStrategy()) passport.serializeUser(User.serializeUser()) passport.deserializeUser(User.deserializeUser())
ebfcdd24110ba90648b4d41732812132fb1d4c0e
[ "JavaScript" ]
1
JavaScript
gobinbash/next-apollo-auth
30d3d5cc23f751ce789d35a2ec7d28f3aefe4def
e58f6741aa46b6516def42c066519dbf11817ed9
refs/heads/main
<file_sep># RepoLearning4 tomcatnew
e46ee3a47d7d08b72ec2f894473a3b39d15c197e
[ "Markdown" ]
1
Markdown
jason0429hebei/RepoLearning4
5ba29fa880be7be96ad88405d5b53bfffea7833d
557417295d3c1fbf183461480ee40e31da4911fb
refs/heads/main
<file_sep>#### Introdução A Flora Energia é uma empresa de tecnologia energética, sustentável e acessível a todos. A Flora gera energia em suas fazendas sustentáveis e injeta na rede elétrica, recebendo em troca créditos da distribuidora. O público alvo da Flora são os consumidores de baixa tensão com contas até R$ 50.000,00 reais, tipicamente o consumo residencial, que ao aderir à solução passa a ter descontos na conta de Energia Elétrica e a pagar uma parte de serviço à Flora de forma que a soma dos pagamentos sempre resulte menor que a fatura normal do consumidor. Para que o cliente (consumidor que se enquadra no público alvo) faça adesão à solução ou mesmo solicite informações sobre quais serão seus descontos, é necessário que a Flora conheça seu perfil de consumo entre outras informações constantes na fatura desse cliente. **A estória de usuário enxergada para esse projeto é: Preciso de uma aplicação para extrair dados de campos específicos da fatura e disponibilizar os dados em um banco que pode ser acessado via uma API(Application Programming Interface).** Dessa forma, como trata-se de uma solução tipificada como varejo, a quantidade de clientes e potenciais clientes que terão suas faturas analisadas é absurdamente alta, fazendo-se necessário um processo automatizado que elimine desperdícios de tempo e dinheiro. Outro ponto importantíssimo é proporcionar uma boa experiência ao cliente por meio de um processo simples e rápido solicitação de informações e a adesão facilitada. Uma possível limitação na automação desse processo é a qualidade do artefato enviado pelo cliente, no caso, a fatura de Energia Elétrica. #### Linguagens, Frameworks e Infraestrutura * A linguagem escolhida foi o Python, por ser a linguagem mais consagrada no quesito extração e tratamento de dados. * Foi adotado o Framework Flask, uma vez que a forma mais evidente de entregar a solução proposta é via WEB. * A extração de dados via OCR(Optical Character Recognition) foi feita usando a API do google conhecida como Vision. A escolha foi feita por conta de sua precisão, uma vez erros de leitura em valores podem ter alto impacto no negócio. Precificação de uso da API Vision em https://cloud.google.com/vision/pricing#example . * O Banco de Dados escolhido foi o MongoDB, por proporcionar alta velocidade de leitura/gravação e facilitar a expansão da solução depois que ela já estiver em produção. Em um momento futuro, pode-se considerar a indexação do MongoDB com Elasticsearch, para buscas mais rápidas e inteligentes. * Apesar de ser um MVP(Minimum Viable Product), no quesito infraestrutura, esse projeto é pensado para em um momento posterior, ser implantado em soluções nativas de nuvem, baseada em microsserviços, usando soluções escaláveis e de alta performance, como é o caso de containers em kubernetes preferencialmente em nuvem pública. #### Especificações A solução foi solicitada no modelo de API, dessa forma os serviços podem ser consumidos por aplicações WEB, aplicativos Mobile (smartphones etc) e inclusive sistemas integrados corporativos(ERPs). O microsserviço tratado por esse MVP é responsável por receber de forma eletrônica a fatura do cliente, extrair os dados necessários usando tecnologia OCR e gravar esses dados em um banco de dados NoSQL, no caso o MongoDB. ##### Demonstração Para facilitar a demonstração, foi disponibilizada uma interface web para upload da fatura e verificação dos dados extraídos. Como o objetivo é apenas teste, não foram aplicados efeitos visuais nem folhas de estilo. Não foi implantado o mecanismo de autenticação. #### Código Fonte ##### Estrutura de pastas e arquivos O projeto foi escrito tendo como objetivo a simplicidade, com uma visão minimalista. A estrutura de arquivos e pastas foi definida para a pasta **templates** abrigar a página de teste de envio de arquivos (apesar de isso poder ser feito pelo Postman por exemplo). A Pasta conta-images, guarda localmente uma cópia do arquivo enviado. O arquivo **db.py**, contém as informações para conexão com o banco de dados MongoDB, que está online no AtlasDB usando o free Tier. O arquivo googlekey.json contém as credenciais da service account utilizada para autorizar o uso da API Vision do google, nesse caso, foi criada a conta de e-mail <EMAIL> e configurado o período de avaliação gratuito de 90 dias do GCP(Google Cloud Platform). O requirements.txt contém os requisitos para o projeto funcionar. Por último, mas não menos importante, o **server.py**, que é o arquivo principal onde estão as rotas e a lógica da API (não foi aplicado o padrão MVC). <file_sep>from flask import Flask, render_template, request from werkzeug.utils import secure_filename from google.cloud import vision from google.oauth2 import service_account from numpy import asarray from pdf2image import convert_from_path import io import re import pandas as pd import json import os import db as d app = Flask(__name__) APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # Rota que apresenta os botões de envio da conta @app.route('/flora/conta/', methods=['GET']) def conta_upload_file(): return render_template('upload.html') # Rota para envio da conta @app.route('/flora/conta/upload', methods=['POST']) def conta_upload(): # Credenciais service account google para uso da API os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = \ r'/home/user/Documentos/path_to_your_key/googleKey.json' client = vision.ImageAnnotatorClient() # Caminho para a pasta local target = os.path.join(APP_ROOT, 'conta-images/') # Cria a pasta se ela não existir if not os.path.isdir(target): os.mkdir(target) # Nome da collection no banco conta_db_table = d.mongo.db.contas if request.method == 'POST': # Envio de multiplas contas for upload in request.files.getlist("conta_image"): filename = secure_filename(upload.filename) destination = "/".join([target, filename]) upload.save(destination) # converte o pdf para uma imagem, geralmente a conta só tem uma página pages = convert_from_path(destination, 500) for page in pages: page.save('fatura.png', 'PNG') # identificando a imagem da fatura usando a biblioteca io e colocando em content with io.open('fatura.png', 'rb') as image_file: content = image_file.read() # prepara a imagem para a api image = vision.types.Image(content=content) # faz OCR response = client.text_detection(image=image) # pega o texto da ocr texts = response.text_annotations # identifica as posições das bouding box com as informações desejadas em texts a_dict = ['124','137','138','202','234','349','350','365','366','375','376', \ '384','385','387','388','390','391','393','394','396','397','400','401', \ '403','404','406','407','426','416','427','428','440','447','452'] # coloca a legenda de cada posição b_dict = ['conta_mes','vencimento','total','tusd','te','mes0','consumomes0', \ 'mes2','consumomes2','mes3','consumomes3','mes4','consumomes4','mes5', \ 'consumomes5','mes6','consumomes6','mes7','consumomes7','mes8','consumomes8', \ 'mes9','consumomes9','mes10','consumomes10','mes11','consumomes11','mes12', \ 'consumomes12','mes13','consumomes13','saldo','saldo_pm','part'] lst={} # fazer um loop em text para pegar cada parte de texto que a ocr indentificou for i, text in enumerate(texts): # faz um loop em a_dict para pegar as posições pré definimos for j, key in enumerate(a_dict): # transforma o que está em a_dict em numero key=int(key) # pega a posição definida manualmente dentro do ocr total, eliminando o que não é desejado if key == i: # retorna a informação associada a posição definida manualmente texto=text.description # coloca um label na posição descricao=b_dict[j] # insere tudo em um dicionário lst.update({descricao: texto}) # coloca a informação no mongodb conta_db_table.insert({'conta_image': lst}) return {'Geral': {'conta_mes': lst['conta_mes'], 'VENCIMENTO': lst['vencimento'], \ 'TOTAL_A_PAGAR': lst['total']}, 'Operacao': {'ENERGIA_ATIVA_FORNECIDA': lst['tusd'], \ 'ENERGIA_ATIVA_INJETADA': lst['te']}, 'Informacoes': {'Saldo': lst['saldo'], \ 'Saldo_a_expirar': lst['saldo_pm'], 'Participacao': lst['part']}, \ 'Historico': {lst['mes2']: lst['consumomes2'], lst['mes3']: lst['consumomes3'], \ lst['mes4']: lst['consumomes4'], lst['mes5']: lst['consumomes5'], \ lst['mes6']: lst['consumomes6'], lst['mes7']: lst['consumomes7'], \ lst['mes8']: lst['consumomes8'], lst['mes9']: lst['consumomes9'], \ lst['mes10']: lst['consumomes10'], lst['mes11']: lst['consumomes11'], \ lst['mes12']: lst['consumomes12'], lst['mes13']: lst['consumomes13']}} if __name__ == '__main__': app.run()<file_sep>from flask_pymongo import PyMongo import server as s s.app.config['MONGO_DBNAME'] = 'samuka' s.app.config['MONGO_URI'] = 'mongodb+srv://user:password@cluster0.daw3o.mongodb.net/flora?retryWrites=true&w=majority' mongo = PyMongo(s.app)
2cdc1abeeb536bef3726f5838d05c01bd6e8fad5
[ "Markdown", "Python" ]
3
Markdown
batistasamuel/flask_ocr_api_google_vision
a62e9665b5b4923e902f2f1d8e17a04c09836619
369ead843696112194fd6406db61bda5b3098e15
refs/heads/master
<repo_name>Luc-Darme/source_symfony<file_sep>/userBundle/Entity/ProjectApplication.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * ProjectApplication * * @ORM\Table() * @ORM\Entity(repositoryClass="eclore\userBundle\Entity\ProjectApplicationRepository") */ class ProjectApplication { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * * @ORM\ManyToOne(targetEntity="eclore\userBundle\Entity\Young", inversedBy="appliedProjects") */ private $young; /** * * @ORM\ManyToOne(targetEntity="eclore\userBundle\Entity\Project", inversedBy="projectApplications") */ private $project; /** * @var string * * @ORM\Column(name="status", type="string") */ private $status; /** * @var date * * @ORM\Column(name="statusDate", type="date") */ private $statusDate; /** * @var string * * @ORM\Column(name="message", type="string") */ private $message; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set young * * @param string $message * @return ProjectApplication */ public function setMessage($message) { $this->message = $message; return $this; } /** * Get message * * @return string */ public function getMessage() { return $this->message; } /** * Set young * * @param \stdClass $young * @return ProjectApplication */ public function setYoung($young) { $this->young = $young; return $this; } /** * Get young * * @return \stdClass */ public function getYoung() { return $this->young; } /** * Set project * * @param \stdClass $project * @return ProjectApplication */ public function setProject($project) { $this->project = $project; $project->addProjectApplication($this); return $this; } /** * Get project * * @return \stdClass */ public function getProject() { return $this->project; } /** * set status * * @param string */ public function setStatus($status) { $this->status = $status; } public function __toString() { return $this->id."";//$this->young->__toString()." - ".$this->project->__toString(); } /** * Get status * * @return string */ public function getStatus() { return $this->status; } /** * set statusDate * * @param date */ public function setStatusDate($statusDate) { $this->statusDate = $statusDate; } /** * Get statusDate * * @return array */ public function getStatusDate() { return $this->statusDate; } } <file_sep>/userBundle/Entity/Young.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Young * * @ORM\Table() * @ORM\Entity(repositoryClass="eclore\userBundle\Entity\YoungRepository") */ class Young { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string * * @ORM\OneToOne(targetEntity="eclore\userBundle\Entity\User", inversedBy="young") */ protected $user; /** * @var array * * @ORM\OneToMany(targetEntity="eclore\userBundle\Entity\ProjectApplication", mappedBy="young") */ private $appliedProjects; /** * @var array * * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\Institution", inversedBy="youngs") */ protected $institutions; public function __construct() { $this->institutions = new \Doctrine\Common\Collections\ArrayCollection(); $this->appliedProjects = new \Doctrine\Common\Collections\ArrayCollection(); } public function __toString() { return $this->getUser()->__toString(); } public function getPAByStatus($stat) { return $this->appliedProjects->filter(function($p) use ($stat){return $p->getStatus()==$stat;}); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set user * * @param string $user * @return InstitutionMember */ public function setUser($user) { $this->user = $user; $user->setYoung($this); return $this; } /** * Get username * * @return string */ public function getUser() { return $this->user; } /** * Add institutions * * @param eclore\userBundle\Entity\Institution $institution */ public function addInstitution(\eclore\userBundle\Entity\Institution $institution) { $this->institutions[] = $institution; $institution->addYoung($this); } /** * Remove institutions * * @param eclore\userBundle\Entity\Institution $institution */ public function removeInstitution(\eclore\userBundle\Entity\Institution $institution) { $this->institutions->removeElement($institution); } /** * Get institutions * * @return array */ public function getInstitutions() { return $this->institutions; } /** * Add applied projects * * @param eclore\userBundle\Entity\ProjectApplication $projectApplication */ public function addAppliedProject(\eclore\userBundle\Entity\ProjectApplication $projectApplication) { $this->appliedProjects[] = $projectApplication; } /** * Remove applied projects * * @param eclore\userBundle\Entity\ProjectApplication $projectApplication */ public function removeAppliedProject(\eclore\userBundle\Entity\ProjectApplication $projectApplication) { $this->appliedProjects->removeElement($projectApplication); } /** * Get appliedProjects * * @return array */ public function getAppliedProjects() { return $this->appliedProjects; } public function hasApplied($project) { foreach($project->getProjectApplications() as $PA){ if($PA->getYoung()->getId() == $this->getId()) return True; } return false; } public function getCurrentProjects() { $res=array(); foreach($this->getAppliedProjects() as $PA) if($PA->getProject()->isStarted()) $res[]=$PA->getProject(); return $res; } } <file_sep>/userBundle/Resources/views/page_lambda.html.twig {%if form is defined %} {% form_theme form 'ecloreuserBundle:Form:fields.html.twig' %} {%endif%} <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{%block title%}{% endblock %}</title> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/css/lambda/menu.css')}}" type="text/css" /> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/css/lambda/lambda.css')}}" type="text/css" /> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/css/lambda/footer.css')}}" type="text/css" /> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/css/lambda/form.css')}}" type="text/css" /> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/js/lambda/chosen/jquery-ui.min.css')}}" type="text/css" /> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/js/lambda/chosen/chosen.min.css')}}" type="text/css" /> </head> <body> <script src="{{ asset('bundles/ecloreuser/js/lambda/jquery.min.js')}}"> </script> <script src="{{ asset('bundles/ecloreuser/js/lambda/jquery.easing.min.js')}}"> </script> <script src="{{ asset('bundles/ecloreuser/js/lambda/anim_lambda.js')}}"> </script> <script src="{{ asset('bundles/ecloreuser/js/lambda/anim_menu.js')}}"> </script> <script src="{{ asset('bundles/ecloreuser/js/lambda/chosen/jquery-ui.min.js')}}"> </script> <script src="{{ asset('bundles/ecloreuser/js/lambda/chosen/chosen.jquery.min.js')}}"> </script> <div style="position:relative; min-height:100%;"> <header id="menuhaut" style="width:100%" style="z-index:100;"> <!-- {% block menu %} {% endblock %} --> <div class='bandeau_haut'> <img src='{{ asset("bundles/ecloreuser/images/bandeau_haut.jpg")}}' class='bandeau'> <img src='{{ asset("bundles/ecloreuser/images/fondu_image_chapeau.png")}}' id='fonduimg'> <div class="menu {{color}}" style='position:absolute; top : 63%; width:80% ;'> {% include 'ecloreuserBundle::menu.html.twig' %} </div> </div> <a href="/" class='logo'><img src='{{ asset("bundles/ecloreuser/images/logo.png")}}'></a> </header> <div id="tamponmenu"> </div> <div class='page'> <div class='page_chapeau'> <img src='{{ asset("bundles/ecloreuser/images/chapeau_contenu_"~color~".png")}}' class='chapeau'> <div class='chapeau_texte'> <img src='{{ asset("bundles/ecloreuser/images/symbole_eclore.png")}}' class='symbole_eclore'> <span class='chapeau_texte'>{{first}}</span> {%if second is defined %} <img src='{{ asset("bundles/ecloreuser/images/flechedroite.png")}}' class='fleche_gauche'> <span class='chapeau_texte'>{{second}}</span> {%endif%} </div> </div> <div class='page_content'> <div id="infobulle"> {% for key, messages in app.session.flashbag.all() %} {% for message in messages %} <div class="alert-{{ key }}">{{ message|trans({}, 'FOSUserBundle') }}</div> {% endfor %} {% endfor %} </div> {%block content %} {%endblock%} </div> </div> <div id='menu_bas'></div> <footer class="{{color}}"> <a href="https://plus.google.com/u/0/108771494758848918220? rel=author" style="display:hidden;"></a> <ul> <li> <h3> <a href="{{path('ecloreuser_sitemap')}}"> Plan du site </a> </h3> <li> <h3><a href="#">Mentions légales</a> </h3> </li> <li> <h3> <a href="{{path('ecloreuser_statuts')}}">Nos statuts</a> </h3> </li> <li><h3> <a href="mailto:<EMAIL>">Nous contacter</a> </h3> </li> </ul> </footer> <script src="{{ asset('bundles/ecloreuser/js/lambda/jquery.carouFredSel-6.2.1-packed.js')}}" type="text/javascript"></script> </div> </body> </html> <file_sep>/userBundle/Timeline/TimelineSpread.php <?php namespace eclore\userBundle\Timeline; use Spy\Timeline\Spread\SpreadInterface; use Spy\Timeline\Model\ActionInterface; use Spy\Timeline\Spread\Entry\EntryCollection; use Spy\Timeline\Spread\Entry\EntryUnaware; use Symfony\Component\DependencyInjection\Container; use Spy\Timeline\Spread\Entry\Entry; class TimelineSpread implements SpreadInterface { protected $container; protected $informedUsers; CONST USER_CLASS = 'eclore\userBundle\Entity\User'; public function __construct(Container $container) { $this->container = $container; } public function supports(ActionInterface $action) { // here you define what actions you want to support, you have to return a boolean. return true; } public function process(ActionInterface $action, EntryCollection $coll) { //common part to all spreads $subjectId = $action->getSubject()->getIdentifier(); $complementId = $action->getComponent('complement')->getIdentifier(); $em = $this->container->get('doctrine')->getManager(); //reps $userRep = $em->getRepository('ecloreuserBundle:User'); $projectRep = $em->getRepository('ecloreuserBundle:Project'); $assoRep = $em->getRepository('ecloreuserBundle:Association'); $instMRep = $em->getRepository('ecloreuserBundle:InstitutionMember'); $this->informedUsers=array(); if($action->getVerb() == 'mark_young'){ //markedYoung $user = $userRep->find($complementId); if(isset($user) && $user->getPrivacyLevel() != 2){ $this->informsYoungInstM($user); } }elseif(($action->getVerb() == 'take_part' || $action->getVerb() == 'apply')){ //validatedPA or newPA $user = $userRep->find($subjectId); $project = $projectRep->find($complementId); if(isset($user) && isset($project) && $user->getPrivacyLevel() != 2){ // informs project $coll->add(new Entry($action->getComponent('complement'))); $this->informsUserContacts($user); $this->informsYoungInstM($user); // informs projects responsibles foreach($project->getResponsibles() as $assoM) $this->informedUsers[]=$assoM->getUser()->getId(); } }elseif($action->getVerb() == 'contact'){ //contactAck $ackUser = $userRep->find($subjectId); $requestingUser = $userRep->find($complementId); if(isset($ackUser) && isset($requestingUser)){ // informs requestingUser if($requestingUser->getPrivacyLevel() != 2){ $this->informedUsers[]=$requestingUser->getId(); $this->informsUserContacts($requestingUser); } if($ackUser->getPrivacyLevel() != 2){ $this->informsUserContacts($ackUser); } $this->informsUserContacts($ackUser); } }elseif($action->getVerb() == 'mark_project'){ //markedProject $user = $userRep->find($subjectId); $project = $projectRep->find($complementId); if(isset($project) && isset($user) && $user->getPrivacyLevel() != 2){ // informs project $coll->add(new Entry($action->getComponent('complement'))); $this->informsYoungInstM($user); // informs project responsibles foreach($project->getResponsibles() as $resp) $this->informedUsers[]=$resp->getUser()->getId(); } }elseif($action->getVerb() == 'be_rejected'){ //rejectedPA $user = $userRep->find($subjectId); $project = $projectRep->find($complementId); if(isset($user) && isset($project) && $user->getPrivacyLevel() != 2){ $this->informsYoungInstM($user); // informs projects responsibles foreach($project->getResponsibles() as $assoM) $this->informedUsers[]=$assoM->getUser()->getId(); } }elseif($action->getVerb() == 'create_project'){ //newProject $asso = $assoRep->find($subjectId); $project = $projectRep->find($complementId); if(isset($project) && isset($asso)){ // informs project $coll->add(new Entry($action->getComponent('complement'))); // informs all instM foreach($instMRep->findAll() as $instM) $this->informedUsers[]=$instM->getUser()->getId(); // informs all assoM of asso foreach($asso->getMembers() as $assoM) $this->informedUsers[]=$assoM->getUser()->getId(); // informs youngs who took part in one of asso projects foreach($asso->getProjects() as $proj) foreach($proj->getProjectApplications() as $PA) $this->informedUsers[]=$PA->getYoung()->getUser()->getId(); } }elseif($action->getVerb() == 'registered'){ //newUser $user = $userRep->find($subjectId); if(isset($user) && $user->getPrivacyLevel() != 2){ if($user->hasRole('ROLE_YOUNG')){ $this->informsYoungInstM($user); // informs youngs from inst foreach($user->getYoung()->getInstitutions() as $inst) foreach($inst->getYoungs() as $yg) $this->informedUsers[]=$yg->getUser()->getId(); }elseif($user->hasRole('ROLE_ASSOM')){ //informs other assom foreach($user->getAssoM()->getAssociations() as $asso) foreach($asso->getMembers() as $assoM) $this->informedUsers[]=$assoM->getUser()->getId(); }elseif($user->hasRole('ROLE_INSTM')){ // informs other instm foreach($user->getInstM()->getInstitutions() as $inst) foreach($inst->getMembers() as $instM) $this->informedUsers[]=$instM->getUser()->getId(); // informs young of inst foreach($user->getInstM()->getInstitutions() as $inst) foreach($inst->getYoungs() as $yg) $this->informedUsers[]=$yg->getUser()->getId(); } } } //informs every required users foreach(array_unique($this->informedUsers) as $id) $coll->add(new EntryUnAware(self::USER_CLASS, $id)); } public function informsYoungInstM($user){ foreach($user->getYoung()->getInstitutions() as $inst) foreach($inst->getMembers() as $instM) $this->informedUsers[]=$instM->getUser()->getId(); $this->informedUsers[]=$user->getId(); } public function informsUserContacts($user){ foreach($user->getContacts() as $people) $this->informedUsers[]=$people->getId(); $this->informedUsers[]=$user->getId(); } }<file_sep>/userBundle/Resources/views/AssoM/edit-asso.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Mettre à jour le profil de l'association{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite"> {{ form(form) }} </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Resources/views/AssoM/manage-application.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite"> Bienvenue {{app.user.username}} !<br> Vous êtes dans l'espace d'administration de la candidature de {{pa.young}} au projet {{pa.project}}. <br> Etat de la candidature: {{pa.status|PAStatus}} <br>Derniere communication: {{pa.message}} <br> Date de dernière modification: {{pa.statusDate|date("d/m/Y")}} <br> {% if pa.status == 'PENDING' or (pa.status=='VALIDATED' and pa.project.isFinished) %} {{ form(form) }} {%endif%} </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Resources/views/Static/sitemap.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Le réseau Eclore{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} <h1>Un peu perdu ?</h1> Le site du réseau Eclore est divisé en deux parties: <ol> <li>Une partie publique, où vous avez accès aux actualités du réseau. Vous y trouverez principalement: <a href="/">la page générale d'accueil et de présentation</a>, <a href="{{path('ecloreuser_rechercherProjet')}}">la page pour rechercher un projet parmi ceux déjà déposés</a>, <a href="{{path('fos_user_registration_register')}}">la page de connexion/inscription à votre espace membre</a> </li> <li>Une partie privée (votre espace membre), où vous avez accès en plus aux fonctionnalités du réseau, comme: <a href="{{path('user_annuaire')}}">votre annuaire</a>, <a href="{{path('assom_registerProject')}}">la page pour proposer un projet si vous faites partie d'une association</a>, <a href="{{path('fos_user_profile_show')}}">la gestion de votre profil</a>, <a href="{{path('ecloreuser_home')}}">la gestion générale de votre activité (projets/candidatures)</a> </li> </ol> Note: le site ayant été lancé il y a peu de temps, nous vous serions reconnaissants de signaler toute erreur rencontrée en nous <a href="mailto:<EMAIL>?subject=Erreur">envoyant un mail</a>. Merci ! {% endblock %} <file_sep>/userBundle/Form/Type/ProfileFormType.php <?php namespace eclore\userBundle\Form\Type; use Symfony\Component\Form\FormBuilderInterface; use FOS\UserBundle\Form\Type\ProfileFormType as BaseType; use eclore\userBundle\Form\ImageType; use Symfony\Component\DependencyInjection\Container; class ProfileFormType extends BaseType { protected $container; public function __construct($user_class, Container $container) { parent::__construct($user_class); $this->container = $container; } public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('birthDate', 'date', array( 'widget' => 'choice', 'years'=>range((int)date("Y")-100, (int)date("Y")), 'label'=>"Date de naissance")) ->add('lastName', 'text', array( 'label'=>" Nom de famille :")) ->add('firstName', 'text', array( 'label'=>" Prénom :")) ->add('mobile','text', array( 'label'=>"Numéro de téléphone :")) ->add('quality','text', array( 'label'=>"Votre situation actuelle (par exemple: 2ème année de BTS, président d'association, etc...)")) ->add('privacyLevel', 'choice', array('choices'=>$this->container->getParameter('privacyLevels'), 'label'=>"Confidentialité de vos données personnelles")) ->add('headshot', new ImageType(), array( 'label'=>"Photo de profil")) ; } public function getName() { return 'eclore_user_profile'; } } ?><file_sep>/userBundle/Resources/views/Static/mentions.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Le réseau Eclore{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} Mentions légales {% endblock %}<file_sep>/userBundle/Resources/views/Profile/show_content.html.twig {% trans_default_domain 'FOSUserBundle' %} <h1> Mes informations profil</h1> <div class="fos_user_user_show"> <div class="colgauche"> Image de profil: <img src="{{app.request.basepath}}/{{ user.getHeadshotWebPath }}" width='100'> </div> <div class="coldroite"> <p>{{ 'profile.show.username'|trans }}: {{ user.username }}</p> <p>{{ 'profile.show.email'|trans }}: {{ user.email }}</p> <p>Téléphone: {{ user.mobile }}</p> <p>Date de naissance: {{ user.birthDate|date('d/m/Y') }}</p> <p>Prénom: {{ user.firstName }}</p> <p>Nom: {{ user.lastName }}</p> <p>Niveau de confidentialité: {{ user.privacyLevel|privacyLevels }}</p> {%if app.user.hasRole('ROLE_ASSOM') or app.user.hasRole('ROLE_INSTM') or app.user.hasRole('ROLE_YOUNG')%} <p>Situation : {{ user.quality }}</p> {%endif%} </div> <div class="clearboth"></div> <a href="{{ path('fos_user_profile_edit') }}">Modifier mes informations</a> <br> <a href="{{ path('fos_user_change_password') }}">Modifier mon mot de passe</a> </div><file_sep>/userBundle/Resources/views/AssoM/Temp web/manage-project.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite"> {% set rejected = proj.PAByStatus('REJECTED') %} {% set validated = proj.PAByStatus('VALIDATED') %} {% set pending = proj.PAByStatus('PENDING') %} Bienvenue {{app.user.username}} !<br> Vous êtes dans l'espace d'administration du projet {{proj.projectName}}. <br> Nom du projet: {{proj}}<br> Description: {{proj.description}}<br> Date de début: {{proj.startdate|date("m-d-Y")}}<br> Date de fin: {{proj.enddate|date("m-d-Y")}}<br> Localisation: {{proj.address}}<br> Responsables du projet: {{proj.responsibles|join(', ') }}<br> Statut du projet: {%if not proj.enabled%} Ce projet est en attente de validation de la part des administrateurs. Vous serez averti de sa validation. {%else%} {%if proj.isFinished %} Terminé. {%elseif not proj.isFinished and proj.isStarted %} En cours. {%else%} Publié. {%endif%} <br> <a href="{{ path('assom_editProject', { 'id': proj.id }) }}"> Modifier ce projet </a> <br> Statut sur les participants: {%if not proj.isFinished%} {%if proj.isFull %}Ce projet possède le nombre de participants requis. {%else%}{{proj.required - proj.getPAByStatus('VALIDATED')|length}} participants encore souhaités. {%endif%} {%else%} Merci de clôturer les candidatures des jeunes ayant participé.<br> {%endif%} <br> {%if not proj.isFinished%} {% if validated|length >0 %} Candidatures à clôturer: <ul> {% for pa in validated %} <li>{{pa.young}} <a href="{{ path('assom_manageApplication', { 'id': pa.id }) }}">Clôturer</a></li> {% endfor %} </ul> {% else %} Pas de candidatures à clôturer {% endif %} {%else%} {% if pending|length >0 %} <br> Candidatures à traiter: <ul> {% for pa in pending %} <li>{{pa.young}} <a href="{{ path('assom_manageApplication', { 'id': pa.id }) }}">Manager</a></li> {% endfor %} </ul> {% else %} Pas de candidatures à traiter. {% endif %} <br> {% if validated|length >0 %} Candidatures validées: <ul> {% for pa in validated %} <li>{{pa.young}} <a href="{{ path('assom_manageApplication', { 'id': pa.id }) }}">Manager</a></li> {% endfor %} </ul> {% else %} Pas de candidatures validées. {% endif %} <br> {% if rejected|length >0 %} Candidatures rejetées: <ul> {% for pa in rejected %} <li>{{pa.young}} <a href="{{ path('assom_manageApplication', { 'id': pa.id }) }}">Manager</a></li> {% endfor %} </ul> {% else %} Pas de candidatures rejetées. {% endif %} <br> Si vous souhaitez modifier ce projet, le supprimer, ou ajouter des responsables, merci de contacter le réseau à <EMAIL> {%endif%} {%endif%} </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Entity/ProjectRepository.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\EntityRepository; /** * ProjectRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ProjectRepository extends EntityRepository { public function getAvailableProjects() {// returns projects enabled with count(applications)< required $qb = $this->_em->createQueryBuilder(); $projects = $qb->select('n') ->from($this->_entityName, 'n') ->where('n.enabled = :enabled') ->setParameter('enabled', true) ->getQuery()->getResult(); foreach($projects as $proj) if($proj->getPAByStatus('VALIDATED')->count() >= $proj->getRequired()) $projects->remove($proj); return $projects; } } <file_sep>/userBundle/Resources/views/InstM/display-young.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite"> <h1> Fiche de suivi de {{young}}.</h1> <!-- <h2> Participe actuellement aux projets suivants :</h2> <ul> {%for proj in young.getCurrentProjects %} <li> <div class="wrapper_el_projets"> <a href="" class="expandlink" onclick="return false"> <div class="projet_el_liste_haut"> <div class="hautgauche"> <img src="{{ asset('bundles/ecloreuser/images/projets/proj1.png') }}"></img></div> <div class="hautdroit"> <h2> <span>{{pa.project}} </span> </h2> <span class="soustitre"> <span>{{pa.project.association}} , à {{pa.project.city}}, jusqu'au {{pa.project.endDate|date('d/m/Y')}}</br> <span>{{proj.shortDescription}}</span> </div> </div> <div class="projet_el_liste_bas"> <span>{{pa.project.description}}</span> </div> </a> </div> </li> {%endfor%} </ul> --> <h2> {{young}} est inscrit aux projets suivants :</h2> <ul> {%for pa in young.getPAByStatus('VALIDATED') %} <li> <div class="wrapper_el_projets"> <a href="" class="expandlink" onclick="return false"> <div class="projet_el_liste_haut"> <div class="hautgauche"> <img src="{{ asset('bundles/ecloreuser/images/projets/proj1.png') }}"></img></div> <div class="hautdroit"> <h2> <span>{{pa.project}} </span> </h2> <span class="soustitre"> <span>{{pa.project.association}} , à {{pa.project.city}}, jusqu'au {{pa.project.endDate|date('d/m/Y')}}</br> <span>{{proj.shortDescription}}</span> </div> </div> <div class="projet_el_liste_bas"> <span>{{pa.project.description}}</span> </div> </a> </div> </li> {%endfor%} </ul> <h2>Historique de ses projets :</h2> <ul> {%for pa in young.getPAByStatus('MARKED') %} <li> <div class="wrapper_el_projets"> <a href="" class="expandlink" onclick="return false"> <div class="projet_el_liste_haut"> <div class="hautgauche"> <img src="{{ asset('bundles/ecloreuser/images/projets/proj1.png') }}"></img></div> <div class="hautdroit"> <h2> <span>{{pa.project}} </span> </h2> <span class="soustitre"> <span>{{pa.project.association}} , à {{pa.project.city}}, jusqu'au {{pa.project.endDate|date('d/m/Y')}}</br> <span>{{proj.shortDescription}}</span> </div> </div> <div class="projet_el_liste_bas"> <span>{{pa.project.description}}</span> </div> </a> </div> </li> {%endfor%} </ul> </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Resources/public/css/lambda/menu.css .menu { width:100%; height:3.7em; margin:0em 0 0 0px ; left: -2px; color:#fff; z-index:300; } .menu.bleu { background: url("../../images/menu_fond_bleu.png") no-repeat 0 0 ; background-size: 100% 3.7em; } .menu.vert { background: url("../../images/menu_fond_vert.png") no-repeat 0 0 ; background-size: 100% 3.7em; } .menu.orange { background: url("../../images/menu_fond_orange.png") no-repeat 0 0 ; background-size: 100% 3.7em; } .menu ul { margin:0; padding:0.5em 2em 0 0; } .menu a { color:#fff; text-decoration: none; } .menu h3 { margin-top:-0em; } .menu li { padding: 0 0.1em 0 0.1em; height:2.3em; float:left; text-align:center; overflow:hidden; background: url('../../images/fond_sousmenu.png') no-repeat; position:relative; border-left:1px solid #fff; z-index:21; } .menu.bleu li { background: url('../../images/fond_sousmenu_bleu.png') no-repeat; } .menu.vert li { background: url('../../images/fond_sousmenu_vert.png') no-repeat; } .menu.orange li { background: url('../../images/fond_sousmenu_orange.png') no-repeat; } .menu li a { /* z-index must be higher than .hover class */ z-index:20; padding-top:0.3em; /* display as block and set the height according to the height of the menu to make the whole LI clickable */ display:block; height:2.2em; width:100%; position:relative; } .menu li a .hover { /* mouseover image */ background:url(../../images/fondhover_sousmenu.png) no-repeat center center; background-size: 100% 100%; /* must be postion absolute */ position:absolute; opacity:0.8; /* width, height, left and top to fill the whole LI item */ width:100%; height:2.6em; left:0em; top:-0.4em; /* display under the Anchor tag */ z-index:0; /*hide it by default */ display:none; } .menu.bleu li a .hover { background:url(../../images/fondhover_sousmenu_bleu.png) no-repeat center center; background-size: 100% 100%; } .menu.vert li a .hover { background:url(../../images/fondhover_sousmenu_vert.png) no-repeat center center; background-size: 100% 100%; } .menu.orange li a .hover { background:url(../../images/fondhover_sousmenu_orange.png) no-repeat center center; background-size: 100% 100%; } .sousmenu span{ position : absolute ; left:0; width:100%; z-index : 30; } @media screen and (min-width: 1400px) { .menu li{ width:200px; } } @media screen and (max-width: 1400px) { .menu li{ width:150px; font-size:0.8em; } } <file_sep>/userBundle/Resources/views/index_simple.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Réseau Eclore !{% endblock %} {%set color='vert'%} {%set first='Bienvenue !'%} {% block content %} <div id="menugauche"> {% if is_granted('IS_AUTHENTICATED_REMEMBERED') %} <ul> <a href="{{ path('ecloreuser_home') }}"> <li class="menugauche_el1"> Mon espace </li> </a></ul> {%else%} <ul> <a href="{{ path('fos_user_security_login') }}"> <li class="menugauche_el5"> Je me connecte !</li> </a></ul> <ul> <a href="{{ path('fos_user_registration_register') }}"> <li class="menugauche_el6"> Je m'inscris ! </li> </a></ul> {%endif%} </div> <div class="coldroite"> <h1> Bienvenue sur le réseau Éclore ! </h1> Ce site est appelé à grandir dans les semaines qui viennent mais vous pouvez d'ores et déjà vous inscrire et déposer des projets. <ul> <li > <div class="wrapper_el_projets"> <a href="" class="expandlink" onclick="return false"> <div class="projet_el_liste_haut"> <div class="hautgauche"> <img src="/bundles/ecloreuser/images/exovo_etude.png"></img></div> <div class="hautdroit"> <h2> <span> Qui sommes-nous ? </span> </h2> <span class="soustitre"> <span> Des jeunes convaincus de la valeur de l'engagement associatif ! </span> </span></br> </div> </div> <div class="projet_el_liste_bas"> <span>Nous sommes 6 jeunes bénévoles d'environ 25 ans, étudiants, jeunes professionnels, passés par des associations variées qui nous ont fait confiance et convaincus que cela a été une chance pour notre propre parcours. Nous apportons ainsi nos différentes expériences au réseau Éclore pour partager cette chance avec tous les jeunes. </span> </div> </a> </div> </li> </ul> <ul> <li > <div class="wrapper_el_projets"> <a href="" class="expandlink" onclick="return false"> <div class="projet_el_liste_haut"> <div class="hautgauche"> <img src="/bundles/ecloreuser/images/exovo_reseau.png"></img></div> <div class="hautdroit"> <h2> <span> A qui s'adresse le réseau Éclore ? </span> </h2> <span class="soustitre"> <span> Aux associations voulant impliquer des jeunes dans leur action et aux jeunes souhaitant s'engager dans le monde associatif. </span> </span></br> </div> </div> <div class="projet_el_liste_bas"> <span> Le réseau s’adresse à la fois aux associations qui souhaitent impliquer dans leurs projets de jeunes bénévoles, et aux jeunes souhaitant s’engager dans le milieu associatif. Il vise à mettre en relation des jeunes et des projets associatifs locaux, afin de promouvoir l’engagement bénévole dans la société civile et de développer les liens entre les associations et les nouvelles générations.</span> </div> </a> </div> </li> </ul> <ul> <li > <div class="wrapper_el_projets"> <a href="" class="expandlink" onclick="return false"> <div class="projet_el_liste_haut"> <div class="hautgauche"> <img src="/bundles/ecloreuser/images/exovo_curieux.png"></img></div> <div class="hautdroit"> <h2> <span> Y a-t-il des contraintes ? </span> </h2> <span class="soustitre"> <span> Seulement celles de respecter notre charte et de croire en la jeunesse. </span> </span></br> </div> </div> <div class="projet_el_liste_bas"> <span>Toute association engagée dans un projet vers les autres, de même que tout jeune désireux de s’engager dans un tel projet, peut s’inscrire au réseau Éclore, si elle ou il adhère à la charte et aux valeurs du réseau.</span> </div> </a> </div> </li> </ul> </div> <div class="colgauche lienrezo"> <a href="http://www.facebook.com/reseau.eclore" target="_blank"> <img src="/bundles/ecloreuser/images/icone_fb.png" alt="Lien Facebook"> </a> <a href="https://twitter.com/ResEclore" target="_blank"> <img src="/bundles/ecloreuser/images/icone_twitter.png" alt="Lien Twitter"> </a> <a href="http://reseau-eclore.tumblr.com/" target="_blank"> <img src="/bundles/ecloreuser/images/icone_tumblr.png" alt="Lien Tumblr"> </a> </div> {% endblock %}<file_sep>/userBundle/Extensions/Twig/templateFunctionsHelper.php <?php namespace eclore\userBundle\Extensions\Twig; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Security\Core\SecurityContext; class templateFunctionsHelper extends \Twig_Extension { private $container; private $context; public function __construct(ContainerInterface $container, SecurityContext $context) { $this->container = $container; $this->context = $context; } public function getFilters() { return array( 'printName' => new \Twig_Filter_Method($this, 'printName', array('is_safe' => array('html'))), 'printAsso' => new \Twig_Filter_Method($this, 'printAsso', array('is_safe' => array('html'))), 'printInst' => new \Twig_Filter_Method($this, 'printInst', array('is_safe' => array('html'))), 'PAStatus' => new \Twig_Filter_Method($this, 'PAStatus', array('is_safe' => array('html'))), 'privacyLevels' => new \Twig_Filter_Method($this, 'privacyLevels', array('is_safe' => array('html'))), 'printDate' => new \Twig_Filter_Method($this, 'printDate', array('is_safe' => array('html'))) ); } public function printName($user2) { $first = "<a href='".$this->container->get('router')->generate('displayMember', array('id'=>$user2->getId()))."'>"; if(!$this->context->isGranted('IS_AUTHENTICATED_REMEMBERED')) return $first.$user2->getUsername()."</a>"; $user=$this->context->getToken()->getUser(); if($user->getContacts()->contains($user2)) return $first.$user2->__toString()."</a>"; if($user->getId() == $user2->getId()) return $first."vous</a>"; return $first.$user2->getUsername()."</a>"; } public function printInst($inst) { return "<a href='".$this->container->get('router')->generate('displayInst', array('id'=>$inst->getId()))."'>".$inst->getInstitutionName()."</a>"; } public function printAsso($asso) { return "<a href='".$this->container->get('router')->generate('displayAsso', array('id'=>$asso->getId()))."'>".$asso->getAssociationName()."</a>"; } public function printDate($date) { return $date->format('d/m/Y'); } public function PAStatus($status) { return $this->container->getParameter('PAStatus')[$status]; } public function privacyLevels($pl) { return $this->container->getParameter('privacyLevels')[$pl]; } public function getName() { return 'templateFunctions'; } } ?><file_sep>/userBundle/Resources/views/Members/display-member.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} <div id="menugauche"> <img src="{{app.request.basepath}}/{{u.getHeadshotWebPath }}" width='100%'> </div> <div class="coldroite"> <h1>{{u.username}}</h1> {%if is_granted("IS_AUTHENTICATED_REMEMBERED") and u in app.user.contacts and u.privacyLevel != 2 %} <div class="soustitre"> {{u}}, {{u.age}} ans, téléphone: {{u.mobile}}, email: {{u.email}}</div> {% if u.hasRole('ROLE_ASSOM') %} Fonction: {{u.assoM.quality}}<br> Associations: {{u.assoM.associations|join(', ')}}<br> {%elseif u.hasRole('ROLE_INSTM') %} Fonction: {{u.instM.quality}}<br> Institutions: {{u.instM.institutions|join(', ')}}<br> {%elseif u.hasRole('ROLE_YOUNG') %} Institutions: {{u.young.institutions|join(', ')}}<br> {%endif%} {%elseif contactRequested %} Vous avez déjà envoyé une demande de contact à cette utilisateur. {%else%} <a href="{{ path('user_send_contactNot', {'id':u.id})}}">Envoyer une demande de contact</a> {%endif%} </div> {% endblock %} <file_sep>/userBundle/Resources/views/Profile/albums.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite"> Vos albums photo<br> {%if app.user.albums|length>0 %} {%for album in app.user.albums %} <div style='border:1px dashed grey;'>{{album.name}} ({{album.pictures|length}} photos)<br> <a href="{{ path('user_removealbum', { 'id': album.id }) }}">Supprimer l'album</a> {%if album.pictures|length > 0 %} {%for pic in album.pictures %} <img src="{{app.request.basepath}}/{{ pic.getWebPath }}" width='500'> <a href="{{ path('user_removepic', {'id': pic.id }) }}">Supprimer</a> {%endfor%} {%endif%} </div> {%endfor%} {%else%} Vous n'avez pas d'albums. {%endif%} <a href="{{ path('user_createalbum') }}">Créer un album</a> </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Controller/AssoMController.php <?php namespace eclore\userBundle\Controller; use eclore\userBundle\Entity\User; use eclore\userBundle\Entity\Project; use eclore\userBundle\Entity\ProjectApplication; use eclore\userBundle\Form\ProjectRegisterType; use eclore\userBundle\Form\AssoEditType; use eclore\userBundle\Form\ProjectType; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use eclore\userBundle\Entity\Notification; use eclore\userBundle\Timeline\TimelineEvents; use eclore\userBundle\Timeline\MarkedEvent; use eclore\userBundle\Timeline\PAEvent; use Symfony\Component\EventDispatcher\Event; class AssoMController extends Controller { public function editAssoAction($id, Request $request) { $user = $this->get('security.context')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:Association'); $asso = $repository->find($id); if(!$asso || !$user->getAssoM()->getAssociations()->contains($asso)){ $this->get('session')->getFlashBag()->add( 'notice', 'Vous n \'êtes pas concerné par cette page!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } if($user->hasRole('ROLE_TBC')){ $this->get('session')->getFlashBag()->add( 'notice', 'Votre profil doit être validé par le réseau avant de pouvoir effectuer cette action. Il devrait l\'être rapidement.'); return $this->redirect($this->generateUrl('ecloreuser_home')); } $form = $this->container->get('form.factory')->create(new AssoEditType(), $asso); if('POST' === $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $this->getDoctrine()->getManager()->persist($asso); $this->getDoctrine()->getManager()->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'L\'association a été correctement mise à jour!'); return $this->redirect($this->generateUrl('displayAsso', array('id'=>$asso->getId()))); } } return $this->render('ecloreuserBundle:AssoM:edit-asso.html.twig', array('form' => $form->createView())); } public function displayHomeAction() { $user = $this->get('security.context')->getToken()->getUser(); //get timeline $actionManager = $this->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($user); $timelineManager = $this->get('spy_timeline.timeline_manager'); $timeline = $timelineManager->getTimeline($subject, array('page' => 1, 'max_per_page' => '10', 'paginate' => true)); return $this->render('ecloreuserBundle:AssoM:home.html.twig', array('timeline_coll'=>$timeline)); } public function manageProjectAction($id) { $user = $this->get('security.context')->getToken()->getUser(); $repository = $this->getDoctrine() ->getManager() ->getRepository('ecloreuserBundle:Project'); $project = $repository->find($id); // verification que le projet est bien managé par $user if(!$project || !$user->getAssoM()->getManagedProjects()->contains($project)) { $this->get('session')->getFlashBag()->add( 'notice', 'Vous n \'êtes pas responsable de ce projet!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } return $this->render('ecloreuserBundle:AssoM:manage-project.html.twig', array('proj'=>$project)); } public function manageApplicationAction($id) { $request = $this->getRequest(); $user = $this->get('security.context')->getToken()->getUser(); $em = $repository = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:ProjectApplication'); $PA = $repository->find($id); // verifie que la candidature concerne bien un projet managé par $user if(!$PA || !$user->getAssoM()->getManagedProjects()->contains($PA->getProject())) { $this->get('session')->getFlashBag()->add( 'notice', 'Cette candidature ne concerne pas un de vos projets!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } // creation formulaires validation/rejet ou cloture $recomm = new Notification(); $formbuilder = $this->createFormBuilder($recomm); if($PA->getStatus() == 'VALIDATED' && $PA->getProject()->isFinished()){ $formbuilder->add('message', 'textarea', array('required'=>false)) ->add('terminate','submit'); }elseif($PA->getStatus() == 'PENDING'){ $formbuilder->add('message', 'textarea', array('required'=>false)) ->add('validate','submit') ->add('reject','submit'); } $form = $formbuilder->getForm(); $form->handleRequest($request); if($form->isValid()) { $PA->setStatusDate(new \DateTime); $PA->setMessage($recomm->getMessage()); if ($form->has('validate') && $form->get('validate')->isClicked()){ $PA->setStatus('VALIDATED'); $event = new PAEvent($PA); $this->get('event_dispatcher')->dispatch(TimelineEvents::onValidatedPA, $event); } elseif ($form->has('reject') && $form->get('reject')->isClicked()){ $PA->setStatus('REJECTED'); $event = new PAEvent($PA); $this->get('event_dispatcher')->dispatch(TimelineEvents::onRejectedPA, $event); } elseif ($form->has('terminate') && $form->get('terminate')->isClicked()) { //cloture candidature $PA->setStatus('TERMINATED'); // creation recommandation $recomm->setSender($user); $recomm->setProject($PA->getProject()); $recomm->addReceiver($PA->getYoung()->getUser()); $recomm->setInitDate(new \DateTime()); $recomm->setType('RECOMMENDATION'); $em->persist($recomm); $event = new MarkedEvent($PA); $this->get('event_dispatcher')->dispatch(TimelineEvents::onMarkedYoung, $event); } $em->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'Mise à jour effectuée!'); } $choices=array('PENDING'=>'En attente de validation', 'VALIDATED'=>'Validée', 'REJECTED'=>'Rejetée', 'WITHDRAWN'=>'Retirée', 'TERMINATED'=>'Clôturée', 'MARKED'=>'Avis jeune enregistré'); return $this->render('ecloreuserBundle:AssoM:manage-application.html.twig', array('pa'=>$PA, 'form'=>$form->createView())); } public function registerProjectAction(Request $request) {$user = $this->get('security.context')->getToken()->getUser(); if($user->hasRole('ROLE_TBC')){ $this->get('session')->getFlashBag()->add( 'notice', 'Votre profil doit être validé par le réseau avant de pouvoir effectuer cette action. Il devrait l\'être rapidement.'); return $this->redirect($this->generateUrl('ecloreuser_home')); } // create project registration forms $project = new Project(); $form = $this->createForm(new ProjectRegisterType($this->get('security.context'), $this->container), $project); $project->addResponsible($this->get('security.context')->getToken()->getUser()->getAssoM()); if('POST' === $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $this->getDoctrine()->getManager()->persist($project); $this->getDoctrine()->getManager()->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'Le projet a été correctement créé! Il est soumis à validation.'); //event dispatcher $event = new Event(); $this->container->get('event_dispatcher')->dispatch(TimelineEvents::onPendingValidation, $event); return $this->redirect($this->generateUrl('assom_manageProject', array('id'=>$project->getId()))); } } return $this->render('ecloreuserBundle:AssoM:register-project.html.twig', array('form' => $form->createView())); } public function editProjectAction($id, Request $request) { $user = $this->get('security.context')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:Project'); $proj = $repository->find($id); if(!$proj || !$user->getAssoM()->getManagedProjects()->contains($proj)){ $this->get('session')->getFlashBag()->add( 'notice', 'Vous n \'êtes pas concerné par cette page!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } $form = $this->container->get('form.factory')->create(new ProjectRegisterType($this->get('security.context'), $this->container), $proj); if('POST' === $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $this->getDoctrine()->getManager()->persist($proj); $this->getDoctrine()->getManager()->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'Le projet a été correctement mis à jour!'); return $this->redirect($this->generateUrl('assom_manageProject', array('id'=>$proj->getId()))); } } return $this->render('ecloreuserBundle:AssoM:register-project.html.twig', array('form' => $form->createView())); } } <file_sep>/userBundle/Resources/views/Profile/annuaire.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite"> <h1> Gestion de vos contacts </h1> {%if contact_not|length>0 %} <h2> Demandes de contact à gérer </h2> <ul> {% for notif in contact_not %} <li>{{notif.initDate|date('d-m-Y')}} de {{notif.sender}}: {{notif.message}} <a href="{{path('user_acknowledge_contact', {'id' : notif.id, 'action' : 'ack'})}}">Accepter</a> <a href="{{path('user_acknowledge_contact', {'id' : notif.id, 'action' : 'nack'})}}">Refuser</a> </li> {% endfor %} </ul> {%else%} {%endif%} {%if app.user.contacts|length>0 %} {%if app.user.getContactsByRole('ROLE_YOUNG')|length > 0 %} <h2> Jeunes </h2> {%for contact in app.user.getContactsByRole('ROLE_YOUNG') %} <div class="colquarter contact"> <div class="imgtitle"> <img src="{{app.request.basepath}}/{{ contact.getHeadshotWebPath }}" width='80%'> </div> <h3> {{contact|printName}} </h3> {{contact.mobile}}, {{contact.email}}</br> {{contact.young.institutions|join(', ')}}</br> <a href="{{path('displayMember', {'id':contact.id})}}">Détails...</a> <a href="{{path('user_removeContact', {'id':contact.id})}}">Supprimer</a> </div> {%endfor%} {%endif%} {%if app.user.getContactsByRole('ROLE_ASSOM')|length > 0 %} <h2> Membres associatifs</h2> {%for contact in app.user.getContactsByRole('ROLE_ASSOM') %} <div class="colquarter contact"> <div class="imgtitle contact"> <img src="{{app.request.basepath}}/{{ contact.getHeadshotWebPath }}" width='80%'> </div> <h3> {{contact|printName}} </h3> {{contact.mobile}}, {{contact.email}}</br> {{contact.assoM.associations|join(', ')}}</br> <a href="{{path('displayMember', {'id':contact.id})}}">Détails...</a> <a href="{{path('user_removeContact', {'id':contact.id})}}">Supprimer</a> </div> {%endfor%} {%endif%} {%if app.user.getContactsByRole('ROLE_INSTM')|length > 0 %} <h2> Membres institutionnels </h2> {%for contact in app.user.getContactsByRole('ROLE_INSTM') %} <div class="colquarter contact"> <div class="imgtitle "> <img src="{{app.request.basepath}}/{{ contact.getHeadshotWebPath }}" width='80%'> </div> <h3> {{contact|printName}} </h3> {{contact.mobile}}, {{contact.email}}</br> {{contact.instM.institutions|join(', ')}}</br> <a href="{{path('displayMember', {'id':contact.id})}}">Détails...</a> <a href="{{path('user_removeContact', {'id':contact.id})}}">Supprimer</a> </div> {%endfor%} {%endif%} {%else%} Pas encore de contacts dans votre annuaire. {%endif%} </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Admin/ProjectApplicationAdmin.php <?php namespace eclore\userBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; use eclore\userBundle\Entity\ProjectApplication; class ProjectApplicationAdmin extends Admin { // Fields to be shown on create/edit forms protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('young', 'entity', array('class'=>'ecloreuserBundle:Young')) ->add('project', 'entity', array('class'=>'ecloreuserBundle:Project')) ->add('message', 'textarea') ->add('status', 'choice', array('choices'=>$this->getConfigurationPool()->getContainer()->getParameter('PAStatus'))) ->add('statusDate') ; } // Fields to be shown on filter forms /*protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('young', 'entity', array('class'=>'ecloreuserBundle:Young')) ->add('project', 'entity', array('class'=>'ecloreuserBundle:Project')) ->add('status') ->add('statusDate') ; }*/ // Fields to be shown on lists protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('id') ->add('young', 'entity', array('class'=>'ecloreuserBundle:Young')) ->add('project', 'entity', array('class'=>'ecloreuserBundle:Project')) ->add('status', 'choice', array('choices'=>$this->getConfigurationPool()->getContainer()->getParameter('PAStatus'))) ->add('statusDate') ->add('_action', 'actions', array( 'actions' => array( 'show' => array(), 'edit' => array(), 'delete' => array(), ) )) ; } }<file_sep>/userBundle/Resources/views/Young/home.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite home"> <h1> Bienvenue <span class="subject">{{app.user.username}}</span> ! </h1> Tu es dans ton espace membre. <h2> Actualités récentes </h2> <ul> {% for action in timeline_coll %} <li>{{ timeline_render(action) }}</li> {% endfor %} </ul> <br> {% if timeline_coll|length <1 %} Pas d'actualités. {%endif%} </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Resources/views/Projects/temp web/show-project.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Rechercher un projet{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} Nom du projet: {{proj}}<br> Description: {{proj.description}}<br> Date de début: {{proj.startdate|date("m-d-Y")}}<br> Date de fin: {{proj.enddate|date("m-d-Y")}}<br> Localisation: {{proj.address}}<br> {%set validated = proj.PAByStatus('VALIDATED') %} {%set terminated = proj.PAByStatus('TERMINATED') %} {%set marked = proj.PAByStatus('MARKED') %} {% if is_granted("IS_AUTHENTICATED_REMEMBERED") %} {%if app.user.hasRole('ROLE_YOUNG') and not app.user.young.hasApplied(proj)%} <a href="{{ path('young_apply',{'id': proj.id}) }}">Candidater à ce projet!</a> {%endif%} {% if date(proj.enddate) < date() %} Ce projet est terminé.<br> {{validated|length+terminated|length+marked|length}} participants. {%else%} Jeunes inscrits à ce projet:<ul> {%for part in validated%} <li>{{part.young.user|printName}}</li> {%endfor%} </ul> {%endif%} {%else%} {{validated|length}} participants enregistrés. {% endif %} <br> {% for action in timeline_coll %} {{ timeline_render(action) }}<br> {% endfor %} <br> {{timeline_coll|length}} actions in timeline. {% endblock %} <file_sep>/userBundle/Admin/ImageAdmin.php <?php namespace eclore\userBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Show\ShowMapper; class ImageAdmin extends Admin { /** * @param ListMapper $listMapper */ protected function configureListFields(ListMapper $listMapper) { $listMapper ->add('id') ->add('ext') ->add('file', 'entity', array('class'=>'ecloreuserBundle:Image', 'template' => 'ecloreuserBundle:Admin:list_image.html.twig')) ->add('_action', 'actions', array( 'actions' => array( 'show' => array(), 'edit' => array(), 'delete' => array(), ) )) ; } /** * @param FormMapper $formMapper */ protected function configureFormFields(FormMapper $formMapper) { $image = $this->getSubject(); $fileFieldOptions = array(); if ($image && ($webPath = $image->getWebPath())) { $container = $this->getConfigurationPool()->getContainer(); $fullPath = $container->get('request')->getBasePath().'/'.$webPath; $fileFieldOptions['help'] = '<img src="'.$fullPath.'" class="admin-preview" />'; } $formMapper ->add('file', 'file', $fileFieldOptions) ; } /** * @param ShowMapper $showMapper */ protected function configureShowFields(ShowMapper $showMapper) { $showMapper ->add('id') ->add('ext') ->add('file', 'entity', array('class'=>'ecloreuserBundle:Image','template' => 'ecloreuserBundle:Admin:show_image.html.twig')) ; } } <file_sep>/userBundle/Entity/Institution.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Institution * * @ORM\Table() * @ORM\Entity */ class Institution { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="institutionName", type="string", length=255) */ private $institutionName; /** * @var string * * @ORM\Column(name="description", type="text") */ private $description; /** * @var string * * @ORM\Column(name="location", type="string", length=255) */ private $location; /** * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\InstitutionMember", mappedBy="institutions") */ private $members; /** * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\Young", mappedBy="institutions") */ private $youngs; /** * @ORM\OneToOne(targetEntity="eclore\userBundle\Entity\Image", cascade={"persist", "remove"}) */ private $headshot; public function __toString() { return $this->getInstitutionName(); } public function getHeadshot() { return $this->headshot; } public function setHeadshot(\eclore\userBundle\Entity\Image $headshot) { return $this->headshot = $headshot; } public function __construct() { $this->members = new \Doctrine\Common\Collections\ArrayCollection(); $this->youngs = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set institutionName * * @param string $institutionName * @return Institution */ public function setInstitutionName($institutionName) { $this->institutionName = $institutionName; return $this; } /** * Get institutionName * * @return string */ public function getInstitutionName() { return $this->institutionName; } /** * Set description * * @param string $description * @return Institution */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set location * * @param string $location * @return Institution */ public function setLocation($location) { $this->location = $location; return $this; } /** * Get location * * @return string */ public function getLocation() { return $this->location; } /** * Add Members * * @param eclore\userBundle\Entity\InstitutionMember $member */ public function addMember(\eclore\userBundle\Entity\InstitutionMember $member) { $this->members[] = $member; } /** * Remove Members * * @param eclore\userBundle\Entity\InstitutionMember $member */ public function removeMember(\eclore\userBundle\Entity\InstitutionMember $member) { $this->members->removeElement($member); } /** * Get Members * * @return array */ public function getMembers() { return $this->members; } /** * Add young * * @param eclore\userBundle\Entity\Young $young */ public function addYoung(\eclore\userBundle\Entity\Young $young) { $this->youngs[] = $young; } /** * Remove young * * @param eclore\userBundle\Entity\Young $young */ public function removeYoung(\eclore\userBundle\Entity\Young $young) { $this->youngs->removeElement($young); } /** * Get youngs * * @return array */ public function getYoungs() { return $this->youngs; } } <file_sep>/userBundle/Resources/public/js/accueil/anim.js $(document).ready(function(){ // Scrolling down when clicking on the word --------------------------------------- /* $('a[href*=#]').each(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname && this.hash.replace(/#/,'') ) { // remove the hash in front of the anchor part of the url, basically making sure that we are at an anchor var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']'); var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; if ($target) { var targetOffset = $target.offset().top; $(this).click(function() { $("#nav li a").removeClass("active"); $(this).addClass('active'); $('html, body').animate({scrollTop: targetOffset}, 2000); return false; }); } } }); */ // ------------------------------------------------------------------------------------------- // ----------------------Animation for the onglet effect of the site ---------------- // ------------------------------------------------------------------------------------------- var $window = $(window); var winHeight = $window.height(); var winWidth = $window.width(); var $eclore = $('#eclore'); var $reseau = $('#reseau'); var $proj = $('#projet'); var $cloud = $('#cloud'); var $container = $('#container'); var $footer = $('footer'); var $descrmod = $('div.descr.mod'); var $descrbleu = $('div.descr.bleu'); var $descrvert = $('.descr.vert'); var $descrorange = $('.descr.orange'); var $ongletbleu = $('a.onglet.bleu'); var $ongletvert = $('a.onglet.vert'); var $ongletorange = $('a.onglet.orange'); var $ongletorange = $('a.onglet.orange'); var $descriptions = $('.descriptions'); var $onglets = $('.onglet'); var isdeveloped = 0; // Animating the word cloud and the onglet------------------------- function colorOngletIn(col){ var descr = ".descr.mod"; ChangeCol($(descr),col) } function colorIn(n){ var fore = $('.cloud_f')[n]; $('#cloud_bkg').stop().animate({opacity: 0.2},{queue:false, duration:2000, easing: 'easeOutExpo'}); $(fore).stop().fadeIn('2000'); }; function colorOut(){ $('#cloud_bkg').stop().animate({opacity: 1},{queue:false, duration:2000, easing: 'easeOutExpo'}); $('.cloud_f').stop().fadeOut('2000') }; //When mouse rolls over $('#area_projet').mouseover( function(){colorOngletIn('bleu');colorIn(0);} ); $('#area_reseau').mouseover( function(){colorOngletIn('orange');colorIn(2);} ); $('#area_eclore').mouseover( function(){colorOngletIn('vert');colorIn(1);} ); $ongletbleu.mouseover( function(){colorOngletIn('bleu');colorIn(0);} ); $ongletorange.mouseover( function(){colorOngletIn('orange');colorIn(2);} ); $ongletvert.mouseover( function(){colorOngletIn('vert');colorIn(1);} ); //When mouse is removed $('#navarea a').mouseout(function(){ colorOut() ; }); $onglets.mouseout(function(){ colorOut() ; }); // Auxilliary Changing color of an element -------------------------------------------------------- function ChangeCol($el,col) { $el.addClass(col).removeClass('bleu').removeClass('orange').removeClass('vert').addClass(col); } // Auxilliary function swapping the onglet place -------------------------------------------------------- function swaponglet(col) { var descri = ".descriptions."+ col; var ongl = ".onglet."+ col; $(descri).insertBefore('.descriptions:nth-child(1)'); $(ongl).insertBefore('.onglet:nth-child(1)'); //alert(ongl); } // main function function devpanel(col) { var $element ; var descrel; if (col == 'bleu'){$element = $proj; $descrel = $descrbleu;}; if (col == 'orange'){$element = $reseau; $descrel = $descrorange;}; if (col == 'vert'){$element = $eclore; $descrel = $descrvert}; $descrmod.css('display','none'); $descrbleu.css('display','none');$descrvert.css('display','none');$descrorange.css('display','none'); $descrel.css('display','inline-block'); if (isdeveloped == 0) { $container.css('left','-'+ winWidth +'px'); $element.css('display','inline-block');$cloud.css('display','none');$container.css('width',''); $container.animate({left: 0},{queue:false, duration:3000, easing: 'easeOutExpo'}); // change footer color and launch specific animation ChangeCol($footer,col);ChangeCol($('.menu'),col);swaponglet(col);LauchCarouProj();LauchCarouActu(); //change the height of the left line $descriptions.css('height',$element.css('height')); // mark that the onglet are developed isdeveloped = 1; } if (isdeveloped == 1) { $descrmod.css('display','none'); $eclore.css('display','none');$proj.css('display','none');$reseau.css('display','none'); $element.css('display','inline-block'); ChangeCol($footer,col);ChangeCol($('.menu'),col);swaponglet(col);LauchCarouProj();LauchCarouActu(); $descriptions.css('height',$element.css('height')); } }; //-------- Basic CSS change $ongletbleu.click( function() { devpanel('bleu'); }); $ongletvert.click( function() { devpanel('vert'); }); $ongletorange.click( function() { devpanel('orange'); }); $(area_projet).click( function() { devpanel('bleu'); }); $(area_reseau).click( function() { devpanel('orange'); }); $(area_eclore).click( function() { devpanel('vert'); }); // Animation for the parallax (scrolling effect) part of the site --------------------------------------- /* var $window = $(window); var $proj = $('#projet'); var $banproj = $('#banner_projet'); var $wordproj = $('#word_projet'); var $reseau = $('#reseau'); var $banreseau = $('#banner_reseau'); var $wordreseau = $('#word_reseau'); var $eclore = $('#eclore'); var $baneclore = $('#banner_eclore'); var $wordeclore = $('#word_eclore'); var windowHeight = $window.height(); function newPos($el, windowHeight, scrollpos, vel, origin){ var x = $el.css('backgroundPosition').slice(0,$el.css('backgroundPosition').indexOf(' ')).trim(); // var baseunit = windowHeight; // alert((scrollpos - origin) * vel); return x + ' ' + ( (scrollpos - origin) * (vel-1) ) + "px"; // adjuster start } function Move(){ var pos = $window.scrollTop(); // alert(newPos($banproj, windowHeight, pos, 300, 200)); // $banproj.css('backgroundPosition', '' + newPos($banproj, windowHeight, pos, -0.95, 58.8 )); $wordproj.css('backgroundPosition', '' + newPos($wordproj, windowHeight, pos, 0.2 , 1460)); // $banreseau.css('backgroundPosition', '' + newPos($banreseau, windowHeight, pos, -0.95, 140+58.8 )); $wordreseau.css('backgroundPosition', '' + newPos($wordreseau, windowHeight, pos, 0.2 , 2625 )); // $baneclore.css('backgroundPosition', '' + newPos($baneclore, windowHeight, pos, -0.95, 280+58.8 )); $wordeclore.css('backgroundPosition', '' + newPos($wordeclore, windowHeight, pos, 0.2 , 3940 )); } $window.resize(function(){ Move(); }); $window.bind('scroll', function(){ Move(); }); $(function() { Move(); }); */ function LauchCarouProj() { $('#projcarousel').carouFredSel({ auto : { items : 3, duration : 1000, easing : "easeInOutCubic", }, items : 3, responsive : true, prev : { button : "#carousel_prev", key : "left", items : 1, easing : "easeInOutCubic", duration : 750 }, next : { button : "#carousel_next", key : "right", items : 1, easing : "easeInOutCubic", duration : 1250 } }); } function LauchCarouActu() { $("#foccarousel").carouFredSel({ responsive : true, scroll : { fx : "crossfade" , duration : 1500, }, items : { visible : 1, height : 390, } }); } $('#tweet').tweecool({ //settings username : 'ResEclore', limit : 4 }); // Using custom configuration });<file_sep>/userBundle/Resources/views/AssoM/register-project.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Enregistrer un projet{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script src="{{ asset('bundles/ecloreuser/js/register-project/1_jquery.ui.addresspicker.js') }}"></script> <script src="{{ asset('bundles/ecloreuser/js/register-project/2_jquery.xdomainrequest.min.js') }}"></script> <div class="coldroite"> {{ form(form) }} <div id='map'></div> <style> #map { border: 1px solid #DDD; width:300px; height: 300px; float:left; margin: 0px 0 0 10px; -webkit-box-shadow: #AAA 0px 0px 15px; } .ui-menu .ui-menu-item a { font-size: 12px; } .ui-autocomplete-input{ font-size: 14px; width: 300px; height: 24px; margin-bottom: 5px; border: 1px solid #DDD !important; padding-top: 0px !important; } </style> <script> $(function() { var addresspickerMap = $( ".addressPickerInput" ).addresspicker({ regionBias: "fr", mapOptions: { zoom: 4, center: new google.maps.LatLng(46, 2), scrollwheel: false, mapTypeId: google.maps.MapTypeId.ROADMAP }, elements: { map: "#map", lat: ".addressPickerLat", lng: ".addressPickerLng", locality: '.addressPickerCity', country: '.addressPickerCountry', postal_code: '.addressPickerPostcode' } }); var gmarker = addresspickerMap.addresspicker( "marker"); gmarker.setVisible(true); addresspickerMap.addresspicker("updatePosition"); }); </script> </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Resources/views/Registration/email.html.twig {% block subject %} Confirmation d'inscription {% endblock %} {% block body_html %} Bonjour {{user.username}},<br><br> Merci de cliquer sur <a href='{{confirmationUrl}}'>ce lien</a> pour confirmer votre inscription! <br><br> L'équipe du Réseau Eclore {% endblock %} <file_sep>/userBundle/Resources/views/Admin/email-pending-validation.html.twig {% block subject %} du nouveau à valider! {% endblock %} {% block body_html %} salut ! <br> il y a du nouveau à valider <a href="{{path('admin_page')}}">dans la partie admin !</a> <br> L'admin {% endblock %} <file_sep>/userBundle/Resources/views/InstM/home.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite home"> <h1> Bienvenue <span class="subject">{{app.user.username}}</span> ! </h1> Vous êtes dans votre espace membre. Vous pouvez y voir le parcours des jeunes qui appartiennent à votre établissement. <br> {% for inst in instM.institutions %} <h2> Jeunes membre de : {{inst|printInst}} </h2> {% if inst.youngs|length > 0 %} <ul> {% for young in inst.youngs %} <li>{{young}}, <a href="{{ path('instm_displayYoung', { 'id': young.id }) }}">Manager</a></li> {% endfor %} </ul> {% endif %} {% endfor %} <h2> Actualités récentes </h2> <ul> {% for action in timeline_coll %} <li>{{ timeline_render(action) }}</li> {% endfor %} </ul> <br> {% if timeline_coll|length == 0 %} Pas d'actualités. {%endif%} </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Timeline/ContactAckEvent.php <?php namespace eclore\userBundle\Timeline; use Symfony\Component\EventDispatcher\Event; use eclore\userBundle\Entity\User; class ContactAckEvent extends Event { protected $requestingUser; protected $ackUser; public function __construct(User $requestingUser, User $ackUser) { $this->requestingUser = $requestingUser; $this->ackUser = $ackUser; } public function getRequestingUser() { return $this->requestingUser; } public function getAckUser() { return $this->ackUser; } }<file_sep>/userBundle/Resources/views/Timeline/verbs/mark_young.html.twig <li> <div class="iconeactu icone_recom"> </div> {{ timeline_component_render(timeline, 'subject') }} a évalué {{ timeline_component_render(timeline,'complement') }} </li><file_sep>/userBundle/Resources/views/Resetting/email.html.twig {% block subject %} Réinitialisation de votre mot de passe {% endblock %} {% block body_html %} Bonjour {{user.username}}!<br><br> Pour réinitialiser votre mot de passe, merci de cliquer sur <a href='{{confirmationUrl}}'>ce lien</a>. <br><br> Cordialement, <br><br> L'équipe du Réseau Eclore {% endblock %} <file_sep>/userBundle/Entity/Association.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Association * * @ORM\Table() * @ORM\Entity */ class Association { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="associationName", type="string", length=255) */ private $associationName; /** * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\AssociationMember", mappedBy="associations") */ private $members; /** * @ORM\OneToMany(targetEntity="eclore\userBundle\Entity\Project", mappedBy="association") */ private $projects; /** * @var string * * @ORM\Column(name="description", type="text") */ private $description; /** * @var string * * @ORM\Column(name="location", type="string", length=255) */ private $location; /** * @ORM\OneToOne(targetEntity="eclore\userBundle\Entity\Image", cascade={"persist", "remove"}) */ private $headshot; public function __construct() { $this->members = new \Doctrine\Common\Collections\ArrayCollection(); $this->projects = new \Doctrine\Common\Collections\ArrayCollection(); } public function __toString() { return $this->getAssociationName(); } public function getHeadshot() { return $this->headshot; } public function setHeadshot(\eclore\userBundle\Entity\Image $headshot) { return $this->headshot = $headshot; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set associationName * * @param string $associationName * @return Association */ public function setAssociationName($associationName) { $this->associationName = $associationName; return $this; } /** * Get associationName * * @return string */ public function getAssociationName() { return ucwords($this->associationName); } /** * Set description * * @param string $description * @return Association */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set location * * @param string $location * @return Institution */ public function setLocation($location) { $this->location = $location; return $this; } /** * Get location * * @return string */ public function getLocation() { return $this->location; } /** * Add Projects * * @param eclore\userBundle\Entity\Project $project */ public function addProject(\eclore\userBundle\Entity\Project $project) { $this->projects[] = $project; } /** * Remove Projects * * @param eclore\userBundle\Entity\Project $project */ public function removeProject(\eclore\userBundle\Entity\Project $project) { $this->projects->removeElement($project); } /** * Get Projects * * @return array */ public function getProjects() { return $this->projects; } /** * Add Members * * @param eclore\userBundle\Entity\AssociationMember $member */ public function addMember(\eclore\userBundle\Entity\AssociationMember $member) { $this->members[] = $member; } /** * Remove Members * * @param eclore\userBundle\Entity\AssociationMember $member */ public function removeMember(\eclore\userBundle\Entity\AssociationMember $member) { $this->members->removeElement($member); } /** * Get Members * * @return array */ public function getMembers() { return $this->members; } public function getHeadshotWebPath() { if($this->headshot==null) return 'uploads/img/symbole_eclore.png'; return $this->headshot->getWebPath(); } } <file_sep>/userBundle/Form/ProjectType.php <?php namespace eclore\userBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\Security\Core\SecurityContext; use Symfony\Component\DependencyInjection\Container; class ProjectType extends AbstractType { private $securityContext; protected $container; public function __construct(SecurityContext $securityContext, Container $container) { $this->securityContext = $securityContext; $this->container = $container; } public function buildForm(FormBuilderInterface $builder, array $options) { $user = $this->securityContext->getToken()->getUser(); $data; foreach($user->getAssoM()->getAssociations() as $value) { $data[$value->getId()]=$value; } $builder ->add('projectName' , 'text', array('label' => ' Intitulé du projet :')) ->add('shortDescription' , 'textarea', array('label' => ' Votre projet en une phrase !') ) ->add('description' , 'textarea', array('label' => 'Décrivez plus précisement le projet :')) ->add('association', 'entity', array('class' => 'eclore\userBundle\Entity\Association', 'choices' => $data)) ->add('labels', 'entity', array('class' => 'eclore\userBundle\Entity\ProjectLabels', 'label' => ' Catégorie :')) ->add('startDate', 'date', array( 'widget' => 'choice', 'years'=>range((int)date("Y"), (int)date("Y")+50) , 'label' => ' Date de début du projet')) ->add('endDate', 'date', array( 'widget' => 'choice', 'years'=>range((int)date("Y"), (int)date("Y")+50) , 'label' => ' Date de fin du projet')) ->add('address', 'text', array('attr' => array('class'=>'addressPickerInput') , 'label' => "Lieu du projet") ) ->add('required', 'text', array('label' => ' Nombre souhaité de jeunes :')) ->add('investmentRequired', 'choice', array('choices'=>$this->container->getParameter('investmentRequired'), 'label' => ' Investissement nécessaire :')) ->add('projectApplications', 'entity', array('class'=>'ecloreuserBundle:ProjectApplication', 'property'=>'id', 'multiple'=>true, 'required'=>false)) ->add('lat', 'hidden', array('attr' => array('class'=>'addressPickerLat'))) ->add('lng', 'hidden', array('attr' => array('class'=>'addressPickerLng'))) ->add('city', 'hidden', array('attr' => array('class'=>'addressPickerCity'))) ->add('country', 'hidden', array('attr' => array('class'=>'addressPickerCountry'))) ->add('postcode', 'hidden', array('attr' => array('class'=>'addressPickerPostcode'))) ->add('responsibles', 'entity', array('class' => 'eclore\userBundle\Entity\AssociationMember', 'multiple'=>true)) ->add('save', 'submit' , array( 'label' => 'Déposer le projet !' )) ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'eclore\userBundle\Entity\Project' )); } public function getName() { return 'eclore_userbundle_projecttype'; } }<file_sep>/userBundle/Controller/RegistrationProfileController.php <?php namespace eclore\userBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use eclore\userBundle\Entity\Young; use eclore\userBundle\Entity\AssociationMember; use eclore\userBundle\Entity\InstitutionMember; use eclore\userBundle\Timeline\TimelineEvents; use eclore\userBundle\Timeline\NewUserEvent; use Symfony\Component\EventDispatcher\Event; class RegistrationProfileController extends Controller { public function registerProfileAction(Request $request) { $user = $this->container->get('security.context')->getToken()->getUser(); $token = $this->get('security.context')->getToken(); // create young registration forms $young = new Young(); $youngFormBuilder = $this->get('form.factory')->createNamedBuilder('young', 'form', $young); $youngFormBuilder ->setMethod('POST') ->add('institutions', 'entity', array('class'=>'ecloreuserBundle:Institution', 'property'=>'institutionName', 'multiple'=>true, 'label'=>'A quelle(s) institution(s) es-tu rattaché ?', 'empty_data'=>'Aucune.')) ->add('quality', 'textarea', array('mapped'=>false, 'label'=>'Tes activités')) ->add('submitYoung', 'submit', array('label'=>'Finir l\'inscription')); // create institutionmember registration forms $instM = new InstitutionMember(); $instMFormBuilder = $this->get('form.factory')->createNamedBuilder('instM', 'form', $instM); $instMFormBuilder ->setMethod('POST') ->add('institutions', 'entity', array('class'=>'ecloreuserBundle:Institution', 'property'=>'institutionName', 'multiple'=>true, 'label'=>'De quelles institutions faites-vous partie ?')) ->add('quality', 'textarea', array('mapped'=>false, 'label'=>'Quel est vôtre rôle dans dans cette (ces) institution(s) ?')) ->add('submitInstM', 'submit', array('label'=>'Finir l\'inscription')); // create associationmember registration forms $assoM = new AssociationMember(); $assoMFormBuilder = $this->get('form.factory')->createNamedBuilder('assoM', 'form', $assoM); $assoMFormBuilder ->setMethod('POST') ->add('associations', 'entity', array('class'=>'ecloreuserBundle:Association', 'property'=>'associationName', 'multiple'=>true, 'label'=>'De quelles associations faites-vous partie ?')) ->add('quality', 'textarea', array('mapped'=>false, 'label'=>'Quel est vôtre rôle dans dans cette (ces) association(s) ?')) ->add('submitAssoM', 'submit', array('label'=>'Finir l\'inscription')); $instMForm = $instMFormBuilder->getForm(); $assoMForm = $assoMFormBuilder->getForm(); $youngForm = $youngFormBuilder->getForm(); if('POST' === $request->getMethod()) { if ($request->request->has('young')) { $youngForm->bind($request); if ($youngForm->isValid()) { $user->setQuality($youngForm->get('quality')->getData()); $young->setUser($user); $em = $this->getDoctrine()->getManager(); $em->persist($young); $user->addRole("ROLE_YOUNG"); $em->persist($user); $em->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'Votre profil a été correctement créé!'); //event dispatcher $event = new NewUserEvent($user); $this->container->get('event_dispatcher')->dispatch(TimelineEvents::onNewUser, $event); // Generate new token with new roles $token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken( $user, null, 'main', $user->getRoles() ); $this->container->get('security.context')->setToken($token); // Get the userManager and refresh user $userManager = $this->container->get('fos_user.user_manager'); $userManager->refreshUser($user); return $this->redirect($this->generateUrl('ecloreuser_younghome')); } } if ($request->request->has('instM')) { $instMForm->bind($request); if ($instMForm->isValid()) { $user->setQuality($instMForm->get('quality')->getData()); $instM->setUser($user); $em = $this->getDoctrine()->getManager(); $em->persist($instM); $user->addRole("ROLE_TBC"); $user->addRole("ROLE_INSTM"); $em->persist($user); $em->flush(); // Generate new token with new roles $token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken( $user, null, 'main', $user->getRoles() ); $this->container->get('security.context')->setToken($token); // Get the userManager and refresh user $userManager = $this->container->get('fos_user.user_manager'); $userManager->refreshUser($user); $this->get('session')->getFlashBag()->add( 'notice', 'Votre profil a correctement été créé!'); //event dispatcher $event = new Event(); $this->container->get('event_dispatcher')->dispatch(TimelineEvents::onPendingValidation, $event); return $this->redirect($this->generateUrl('ecloreuser_home')); } } if ($request->request->has('assoM')) { $assoMForm->bind($request); if ($assoMForm->isValid()) { $user->setQuality($assoMForm->get('quality')->getData()); $assoM->setUser($user); $em = $this->getDoctrine()->getManager(); $em->persist($assoM); $user->addRole("ROLE_TBC"); $user->addRole("ROLE_ASSOM"); $em->persist($user); $em->flush(); // Generate new token with new roles $token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken( $user, null, 'main', $user->getRoles() ); $this->container->get('security.context')->setToken($token); // Get the userManager and refresh user $userManager = $this->container->get('fos_user.user_manager'); $userManager->refreshUser($user); $this->get('session')->getFlashBag()->add( 'notice', 'Votre profil a correctement été créé!'); //event dispatcher $event = new Event(); $this->container->get('event_dispatcher')->dispatch(TimelineEvents::onPendingValidation, $event); return $this->redirect($this->generateUrl('ecloreuser_home')); } } } return $this->render('ecloreuserBundle:Registration:registerProfile.html.twig', array( 'youngForm' => $youngForm->createView(),'instMForm' => $instMForm->createView(), 'assoMForm' => $assoMForm->createView(), )); } } <file_sep>/userBundle/Entity/InstitutionMember.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * InstitutionMember * * @ORM\Table() * @ORM\Entity(repositoryClass="eclore\userBundle\Entity\InstitutionMemberRepository") */ class InstitutionMember { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string * * @ORM\OneToOne(targetEntity="eclore\userBundle\Entity\User", inversedBy="instM") */ protected $user; /** * @var array * * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\Institution", inversedBy="members") */ protected $institutions; public function __toString() { return $this->getUser()->__toString()." (".implode('; ',array_map(function($elem){return $elem->__toString();},$this->getInstitutions()->toArray())).")"; } public function __construct() { $this->institutions = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set user * * @param string $user * @return InstitutionMember */ public function setUser($user) { $this->user = $user; $user->setInstM($this); return $this; } /** * Get username * * @return string */ public function getUser() { return $this->user; } /** * Add institutions * * @param eclore\userBundle\Entity\Institution $institution */ public function addInstitution(\eclore\userBundle\Entity\Institution $institution) { $this->institutions[] = $institution; $institution->addMember($this); } /** * Remove institutions * * @param eclore\userBundle\Entity\Institution $institution */ public function removeInstitution(\eclore\userBundle\Entity\Institution $institution) { $institutions->removeMember($this); $this->institutions->removeElement($institution); } /** * Get institutions * * @return array */ public function getInstitutions() { return $this->institutions; } } <file_sep>/userBundle/Controller/HomeController.php <?php namespace eclore\userBundle\Controller; use eclore\userBundle\Entity\User; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class HomeController extends Controller { public function dispatchHomeAction() { $user = $this->get('security.context')->getToken()->getUser(); if($user->hasRole('ROLE_YOUNG') || $user->hasRole('ROLE_ASSOM') || $user->hasRole('ROLE_INSTM')){ // redirect user to his home if($user->hasRole('ROLE_YOUNG'))return $this->redirect($this->generateUrl('ecloreuser_younghome')); if($user->hasRole('ROLE_INSTM'))return $this->redirect($this->generateUrl('ecloreuser_instmhome')); if($user->hasRole('ROLE_ASSOM'))return $this->redirect($this->generateUrl('ecloreuser_assomhome')); } elseif($user->hasRole('ROLE_TBC')){ // user role is awaiting confirmation return $this->render('ecloreuserBundle:Registration:waitConfirmation.html.twig'); } // user has not any role yet, he must create at least one. return $this->forward('ecloreuserBundle:RegistrationProfile:registerProfile'); } } <file_sep>/userBundle/Entity/NewsPostRepository.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\EntityRepository; /** * NewsPostRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class NewsPostRepository extends EntityRepository { public function getCurrentNewsPosts() { $qb = $this->_em->createQueryBuilder(); $qb->select('a') ->from('ecloreuserBundle:NewsPost', 'a') ->where('a.endDate > :datecourant') ->setParameter('datecourant', new \Datetime(date('Y-m-d'))) ->orderBy('a.id', 'DESC'); return $qb->getQuery() ->getResult(); } } <file_sep>/userBundle/Form/AlbumType.php <?php namespace eclore\userBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use eclore\userBundle\Form\ImageType; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class AlbumType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name', 'text') ->add('pictures', 'collection', array('type' => new ImageType(), 'allow_add' => true, 'allow_delete' => true, 'required' => false, 'by_reference' => false)) ->add('save', 'submit') ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'eclore\userBundle\Entity\Album' )); } public function getName() { return 'eclore_userbundle_albumtype'; } }<file_sep>/userBundle/Entity/Album.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Album * * @ORM\Table() * @ORM\Entity */ class Album { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\ManyToOne(targetEntity="eclore\userBundle\Entity\User", inversedBy="albums") */ private $owner; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @ORM\OneToMany(targetEntity="eclore\userBundle\Entity\Image", cascade={"remove", "persist"}, mappedBy="album") */ private $pictures; public function __construct() { $this->pictures = new \Doctrine\Common\Collections\ArrayCollection(); } public function __toString() { return $this->name; } /** * Get id * * @return integer */ public function getId() { return $this->id; } public function addPicture(\eclore\userBundle\Entity\Image $image) { $this->pictures[] = $image; $image->setAlbum($this); } public function removePicture(\eclore\userBundle\Entity\Image $image) { $this->pictures->removeElement($image); } public function getPictures() { return $this->pictures; } public function setPictures($pics) { foreach ($pics as $pic) { $this->addPicture($pic); } } /** * Set owner * * @param \stdClass $owner * @return Album */ public function setOwner($owner) { $this->owner = $owner; $owner->addAlbum($this); return $this; } /** * Get owner * * @return \stdClass */ public function getOwner() { return $this->owner; } /** * Set name * * @param string $name * @return Album */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } } <file_sep>/userBundle/Resources/views/Registration/registerProfile.html.twig {% extends "FOSUserBundle::layout.html.twig" %} {% block fos_user_content %} <h1> Votre inscription est presque terminée ! </h1> <p> Afin de profitez des possibilités du réseau Eclore, reliez votre compte à une institution ou à une association. </p> <div id="typeprofil"> <div id="choix_type_membre"> <label class="required" for="typemembre">Quel est votre profil ? </label> <select name="fos_choix_type_membre" id="fos_choix_type_membre" > <option value="-1" selected> Choisissez... </option> <option value="0"> Jeune </option> <option value="1"> Membre d'une institution</option> <option value="2"> Membre d'association</option> </select> </div> </div> <div id="defprofil"> {{ form(youngForm) }} {{ form(instMForm) }} {{ form(assoMForm) }} <a href="{{ path('create_asso') }}">Votre association n'est pas dans la liste ? Créez là !</a><br> <a href="{{ path('create_inst') }}">Votre institution n'est pas dans la liste ? Créez là !</a> </div> {% endblock fos_user_content %} <file_sep>/userBundle/Resources/views/Projects/temp web/rechercher.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Rechercher un projet{% endblock %} {%set color='vert'%} {%set first='Les projets'%} {%set second='Rechercher un projet'%} {% block content %} ceci est la page de recherche des projets<br> <div id='loading'>Chargement en cours... <img src="{{ asset('bundles/ecloreuser/images/ajax-loader.gif') }}"/> </div> <div id='search_zone' style='display:none;'> Filtrer par label: <select id='label_select' multiple='multiple' data-placeholder="Labels..." style='width:10em''> </select> <br> Filtrer par association: <select id='association_select' multiple='multiple' data-placeholder="Associations..." style='width:10em'> </select> <br> Trier: <select id='tri' data-placeholder="Trier..."> <option value="project_name+">Nom: croissant</option> <option value="project_name-">Nom: décroissant</option> <option value="duration+">Durée: croissant</option> <option value="duration-">Durée: décroissant</option> <option value="start_date+">Date de début: croissant</option> <option value="start_date-">Date de début: décroissant</option> <option value="end_date+">Date de fin: croissant</option> <option value="end_date-">Date de fin: décroissant</option> </select> <br> <div id='results' class='projets'> </div> </div> <br> <input type='text' id='loc'><input type='button' id='loc_submit' value='chercher'><br> <div id="map-canvas" style="width:800px; height:300px; border:1px solid grey;"/> <script type="text/javascript"> var url = "{{path('ecloreuser_rechercherProjet')}}" var voirProjetUrl = "{{path('show_project',{'id':0})}}" var logoProjet = "{{asset('bundles/ecloreuser/images/projets/proj1.png')}}" </script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBLfY0Ipd6nAQNg2sk8h9G4oeNltMGhoCI&sensor=true"></script> <script src="{{ asset('bundles/ecloreuser/js/projects/2_map.js')}}"> </script> {% endblock %} <file_sep>/userBundle/Resources/views/Admin/show_headshot.html.twig {% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %} {% block field%} {%if object.headshot is not null %} <img src="{{app.request.basepath}}/{{ object.headshot.getWebPath }}" class="admin-view"> {%else%} Pas de photo {%endif%} {% endblock %}<file_sep>/userBundle/Controller/MembersController.php <?php namespace eclore\userBundle\Controller; use eclore\userBundle\Entity\User; use eclore\userBundle\Entity\Association; use eclore\userBundle\Entity\Institution; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use eclore\userBundle\Form\AssoEditType; use eclore\userBundle\Form\InstEditType; class MembersController extends Controller { public function displayMemberAction($id) { $securityContext = $this->container->get('security.context'); $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:User'); $user2 = $repository->find($id); // verifie que le user existe et n'est pas terminé. if(!$user2 || $user2->getPrivacyLevel() == 2) { $this->get('session')->getFlashBag()->add( 'notice', 'Ce profil n\'existe pas'); return $this->redirect($this->generateUrl('ecloreuser_home')); } $contactRequested=False; if( $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') ){ $user = $this->get('security.context')->getToken()->getUser(); //check que une demande de contact n'existe pas deja. $rep = $em->getRepository('ecloreuserBundle:Notification'); $contactRequested = $rep->contactRequested($user, $user2); } return $this->render('ecloreuserBundle:Members:display-member.html.twig', array('u'=>$user2, 'contactRequested'=>$contactRequested)); } public function displayAssoAction($id) { $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:Association'); $asso = $repository->find($id); if(!$asso) { $this->get('session')->getFlashBag()->add( 'notice', 'Cette association n\'existe pas'); return $this->redirect($this->generateUrl('ecloreuser_homepage')); } return $this->render('ecloreuserBundle:Members:display-asso.html.twig', array('asso'=>$asso)); } public function createAssoAction(Request $request) { $asso = new Association(); $form = $this->container->get('form.factory')->create(new AssoEditType(), $asso); if('POST' === $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $this->getDoctrine()->getManager()->persist($asso); $this->getDoctrine()->getManager()->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'L\'association a été correctement crée!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } } return $this->render('ecloreuserBundle:Members:create-asso.html.twig', array('form' => $form->createView())); } public function createInstAction(Request $request) { $inst = new Institution(); $form = $this->container->get('form.factory')->create(new InstEditType(), $inst); if('POST' === $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $this->getDoctrine()->getManager()->persist($inst); $this->getDoctrine()->getManager()->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'L\'association a été correctement crée!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } } return $this->render('ecloreuserBundle:Members:create-inst.html.twig', array('form' => $form->createView())); } public function displayInstAction($id) { $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:Institution'); $inst = $repository->find($id); if(!$inst) { $this->get('session')->getFlashBag()->add( 'notice', 'Cette association n\'existe pas'); return $this->redirect($this->generateUrl('ecloreuser_homepage')); } return $this->render('ecloreuserBundle:Members:display-inst.html.twig', array('inst'=>$inst)); } } <file_sep>/userBundle/Controller/InstMController.php <?php namespace eclore\userBundle\Controller; use eclore\userBundle\Entity\User; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class InstMController extends Controller { public function editInstAction($id, Request $request) { $user = $this->get('security.context')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:Institution'); $inst = $repository->find($id); if(!$inst || !$user->getInstM()->getInstitutions()->contains($inst)){ $this->get('session')->getFlashBag()->add( 'notice', 'Vous n \'êtes pas concerné par cette page!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } if($user->hasRole('ROLE_TBC')){ $this->get('session')->getFlashBag()->add( 'notice', 'Votre profil doit être validé par le réseau avant de pouvoir effectuer cette action. Il devrait l\'être rapidement.'); return $this->redirect($this->generateUrl('ecloreuser_home')); } $form = $this->container->get('form.factory')->create(new InstEditType(), $inst); if('POST' === $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $this->getDoctrine()->getManager()->persist($asso); $this->getDoctrine()->getManager()->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'L\'institution a été correctement mise à jour!'); return $this->redirect($this->generateUrl('displayInst', array('id'=>$inst->getId()))); } } return $this->render('ecloreuserBundle:InstM:edit-inst.html.twig', array('form' => $form->createView())); } public function displayHomeAction() { $user = $this->get('security.context')->getToken()->getUser(); //get timeline $actionManager = $this->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($user); $timelineManager = $this->get('spy_timeline.timeline_manager'); $timeline = $timelineManager->getTimeline($subject, array('page' => 1, 'max_per_page' => '10', 'paginate' => true)); return $this->render('ecloreuserBundle:InstM:home.html.twig', array('instM'=>$user->getInstM(),'timeline_coll'=>$timeline)); } public function displayYoungAction($id) { $user = $this->get('security.context')->getToken()->getUser(); $repository = $this->getDoctrine() ->getManager() ->getRepository('ecloreuserBundle:Young'); $young = $repository->find($id); if($user->getInstM()->getInstitutions() ->forAll(function($k, $i) use ($young){return !$i->getYoungs()->contains($young);})) { $this->get('session')->getFlashBag()->add( 'notice', 'Vous n \'êtes pas responsable de ce jeune!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } return $this->render('ecloreuserBundle:InstM:display-young.html.twig', array('young'=>$young)); } } <file_sep>/userBundle/Resources/views/Admin/show_image.html.twig {% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %} {% block field%} <img src="{{app.request.basepath}}/{{ object.getWebPath }}" class="admin-view"> {% endblock %}<file_sep>/userBundle/Entity/AssociationMember.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * AssociationMember * * @ORM\Table() * @ORM\Entity(repositoryClass="eclore\userBundle\Entity\AssociationMemberRepository") */ class AssociationMember { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string * * @ORM\OneToOne(targetEntity="eclore\userBundle\Entity\User", inversedBy="assoM") */ protected $user; /** * @var array * * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\Association", inversedBy="members") */ protected $associations; /** * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\Project", inversedBy="responsibles") */ private $managedProjects; public function __toString() { return $this->getUser()->__toString()." (".implode('; ',array_map(function($elem){return $elem->__toString();},$this->getAssociations()->toArray())).")"; } public function __construct() { $this->associations = new \Doctrine\Common\Collections\ArrayCollection(); $this->managedProjects = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set user * * @param string $user * @return InstitutionMember */ public function setUser($user) { $this->user = $user; $user->setAssoM($this); return $this; } /** * Get username * * @return string */ public function getUser() { return $this->user; } /** * Add associations * * @param eclore\userBundle\Entity\Association $association */ public function addAssociation(\eclore\userBundle\Entity\Association $association) { $this->associations[] = $association; $association->addMember($this); } /** * Remove associations * * @param eclore\userBundle\Entity\Association $association */ public function removeAssociation(\eclore\userBundle\Entity\Association $association) { $association->removeMember($this); $this->associations->removeElement($association); } /** * Get associations * * @return array */ public function getAssociations() { return $this->associations; } /** * Add proj * * \eclore\userBundle\Entity\Project $project */ public function addManagedProject(\eclore\userBundle\Entity\Project $project) { $this->managedProjects[] = $project; } /** * Remove proj * * \eclore\userBundle\Entity\Project $project */ public function removeManagedProjects(\eclore\userBundle\Entity\Project $project) { $this->managedProjects->removeElement($project); } /** * Get proj * * @return array */ public function getManagedProjects() { return $this->managedProjects; } } <file_sep>/userBundle/Resources/views/Timeline/verbs/contact.html.twig <li> <div class="iconeactu icone_annuaire" > </div> {{ timeline_component_render(timeline, 'subject') }} est en contact avec {{ timeline_component_render(timeline,'complement') }} </li><file_sep>/userBundle/Admin/NotificationAdmin.php <?php namespace eclore\userBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; class NotificationAdmin extends Admin { // Fields to be shown on create/edit forms protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('type', 'choice', array('choices'=>$this->getConfigurationPool()->getContainer()->getParameter('Notification'))) ->add('message', 'textarea') ->add('initDate') ->add('project', 'entity', array('class'=>'ecloreuserBundle:Project', 'required'=>false)) ->add('sender', 'entity', array('class'=>'ecloreuserBundle:User')) ->add('receivers', 'entity', array('class'=>'ecloreuserBundle:User', 'multiple'=>true)) ; } // Fields to be shown on filter forms /*protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('user') ->add('schoolSituation') ->add('institutions') ->add('appliedProjects') ->add('friends') ; }*/ // Fields to be shown on lists protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('id') ->add('type', 'choice', array('choices'=>$this->getConfigurationPool()->getContainer()->getParameter('Notification'))) ->add('message', 'textarea') ->add('initDate') ->add('project', 'entity', array('class'=>'ecloreuserBundle:Project', 'required'=>false)) ->add('sender', 'entity', array('class'=>'ecloreuserBundle:User')) ->add('receivers', 'entity', array('class'=>'ecloreuserBundle:User', 'multiple'=>true)) ->add('_action', 'actions', array( 'actions' => array( 'show' => array(), 'edit' => array(), 'delete' => array(), ) )) ; } }<file_sep>/userBundle/Resources/config/params_choicelist.yml parameters: PAStatus: PENDING: 'En attente de validation' VALIDATED: 'Validée' REJECTED: 'Rejetée' TERMINATED: 'Clôturée' MARKED: 'Avis jeune enregistré' Notification: MARK: 'Avis jeune' CONTACT: 'Demande de contact' RECOMMENDATION: 'Recommandation' privacyLevels: 0: 'Tout le monde peut voir mon profil réduit, mais pas mes activités' 1: 'Mes contacts peuvent voir mon profil complet et mes activités' 2: 'Invisible' investmentRequired: 1: 'Week-end seulement' 0: 'Soirs de semaine et Week-end' 2: 'Jours de semaine et WE' <file_sep>/userBundle/Resources/views/menu_user.html.twig <div id="menugauche"> {% if is_granted('IS_AUTHENTICATED_REMEMBERED') %} <ul> <a href="{{ path('ecloreuser_home') }}"> <li class="menugauche_el1"> Mon espace </li> </a></ul> <ul> <a href="{{ path('fos_user_profile_show') }}"> <li class="menugauche_profil"> Mon profil </li> </a></ul> <ul> <a href="{{ path('user_annuaire') }}"> <li class="menugauche_annuaire"> Mon annuaire </li> </a></ul> <!-- <ul> <a href="{{ path('user_albums') }}"> <li class="menugauche_photo"> Mes photos </li> </a></ul> --> {%if app.user.hasRole('ROLE_YOUNG') %} <ul> <a href="{{ path('user_recomm') }}"> <li class="menugauche_recom"> Mes recommandations </li> </a> </ul> <ul> <a href="{{ path('young_projects') }}"> <li class="menugauche_projets"> Mes projets </li> </a></ul> {%elseif app.user.hasRole('ROLE_ASSOM') %} <ul> <a href="{{ path('user_recomm') }}"> <li class="menugauche_avis"> Mes avis </li> </a></ul> <ul> <a href="{{ path('assom_projects') }}"> <li class="menugauche_projets"> Mes projets </li> </a></ul> <ul> <a href="{{ path('assom_registerProject') }}"> <li class="menugauche_el6"> Créer un projet </li> </a></ul> {%endif%} {%else%} <ul> <a href="{{ path('fos_user_registration_register') }}"> <li class="menugauche_el6"> Inscription </li> </a></ul> <ul> <a href="{{ path('fos_user_security_login') }}"> <li class="menugauche_el5"> Connexion </li> </a></ul> {%endif%} </div> <file_sep>/userBundle/Resources/views/Projects/rechercher.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Rechercher un projet{% endblock %} {%set color='bleu'%} {%set first='Les projets'%} {%set second='Rechercher un projet'%} {% block content %} <h1> Rechercher un projet </h1> <div id='loading'>Chargement en cours... <img src="{{ asset('bundles/ecloreuser/images/ajax-loader.gif') }}"/> </div> <div id='search_zone' style='display:none;'> <div class="filtre"> Filtrer par label: <select id='label_select' multiple='multiple' data-placeholder="Labels..."> </select> </div> <div class="filtre"> Filtrer par association: <select id='association_select' multiple='multiple' data-placeholder="Associations..."> </select> </div> <div class="recherche"> <input type='text' id='loc'><input type='button' id='loc_submit' value='Autour de ma ville...'></div> <div class="clearboth"></div> <div class="blocktri"> Trier: <select id='tri' data-placeholder="Trier..."> <option value="project_name+">Nom: croissant</option> <option value="project_name-">Nom: décroissant</option> <option value="duration+">Durée: croissant</option> <option value="duration-">Durée: décroissant</option> <option value="start_date+">Date de début: croissant</option> <option value="start_date-">Date de début: décroissant</option> <option value="end_date+">Date de fin: croissant</option> <option value="end_date-">Date de fin: décroissant</option> </select> </div> </div> <div id='results' class='projets'> </div> <div id="map-canvas" style=" height:500px; border:1px solid grey;"/> </div> <script type="text/javascript"> var url = "{{path('ecloreuser_rechercherProjet')}}" var voirProjetUrl = "{{path('show_project',{'id':0})}}" var logoProjet = "{{asset('bundles/ecloreuser/images/projets/proj1.png')}}" var webPath = "{{app.request.basepath}}" </script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBLfY0Ipd6nAQNg2sk8h9G4oeNltMGhoCI&sensor=true"></script> <script src="{{ asset('bundles/ecloreuser/js/projects/2_map.js')}}"> </script> {% endblock %} <file_sep>/userBundle/Resources/views/Registration/waitConfirmation.html.twig {% extends "ecloreuserBundle::layout.html.twig" %} {% block title %}Espace membre{% endblock %} {% block fos_user_content %} Bienvenue {{app.user.username}} !<br> Vuos venez d'enregistrer votre profil. <br> Une fois que l'équipe du réseau l'aura validé, vous aurez accès à l'ensemble des fonctionnalités du user. <br> Un email vous sera envoyé dès que votre profil aura été validé. {% endblock fos_user_content %} <file_sep>/userBundle/Resources/views/Members/display-inst.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} <h1>{{inst.institutionName}}</h1> <div class="soustitre"> {{inst.location}} </div> {{inst.description}} <p> {%if inst.youngs|length ==0 %} Aucun jeune n'est inscrit dans cette institution. {%else%} Jeunes inscrits dans cette institution: <ul> {%for membre in inst.youngs %} {%if membre.user.privacyLevel != 2 %} <li>{{membre.user|printName}}</li> {%endif%} {%endfor%} </ul> {%endif%} </p> <p> {%if inst.members|length ==0 %} Aucun membre n'est inscrit dans cette institution. {%else%} Membres de cette institution: <ul> {%for membre in inst.members %} {%if membre.user.privacyLevel != 2 %} <li>{{membre.user|printName}}</li> {%endif%} {%endfor%} </ul> {%endif%} </p> </div> {% endblock %} <file_sep>/userBundle/Entity/NewsPost.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * NewsPost * * @ORM\Table() * @ORM\Entity */ class NewsPost { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="title", type="string", length=255) */ private $title; /** * @var \DateTime * * @ORM\Column(name="publishDate", type="date") */ private $publishDate; /** * @var \DateTime * * @ORM\Column(name="endDate", type="date") */ private $endDate; /** * @var string * * @ORM\Column(name="header", type="text") */ private $header; /** * @var string * * @ORM\Column(name="text", type="text") */ private $text; /** * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\Image", cascade={"persist"}) */ private $pictures; public function __construct() { $this->pictures = new \Doctrine\Common\Collections\ArrayCollection(); } public function addPicture(\eclore\userBundle\Entity\Image $image) { $this->pictures[] = $image; } public function removePicture(\eclore\userBundle\Entity\Image $image) { $this->pictures->removeElement($image); } public function getPictures() { return $this->pictures; } public function setPictures($pics) { foreach ($pics as $pic) { $this->addPicture($pic); } } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set title * * @param string $title * @return NewsPost */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } /** * Set publishDate * * @param \DateTime $date * @return NewsPost */ public function setPublishDate($publishDate) { $this->publishDate = $publishDate; return $this; } /** * Get publishDate * * @return \DateTime */ public function getPublishDate() { return $this->publishDate; } public function setEndDate($endDate) { $this->endDate = $endDate; return $this; } public function getEndDate() { return $this->endDate; } /** * Set header * * @param string $header * @return NewsPost */ public function setHeader($header) { $this->header = $header; return $this; } /** * Get header * * @return string */ public function getHeader() { return $this->header; } /** * Set text * * @param string $text * @return NewsPost */ public function setText($text) { $this->text = $text; return $this; } /** * Get text * * @return string */ public function getText() { return $this->text; } } <file_sep>/userBundle/Controller/StaticController.php <?php namespace eclore\userBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class StaticController extends Controller { public function indexAction() { $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:Project'); $projs = $repository->findBy(array(), array('id'=>'DESC')); $repository = $em->getRepository('ecloreuserBundle:NewsPost'); $posts = $repository->findBy(array(), array('id'=>'DESC')); return $this->render('ecloreuserBundle::index.html.twig', array('projs'=>$projs, 'posts'=>$posts)); } public function displayNewsPostAction($id) { $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:NewsPost'); $post = $repository->find($id); if(!$post){ $this->get('session')->getFlashBag()->add( 'notice', 'Cette page n\'existe pas!'); return $this->redirect($this->generateUrl('ecloreuser_homepage')); } return $this->render('ecloreuserBundle:Static:newspost.html.twig', array('post' => $post)); } public function displayNewsPostsAction() { $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:NewsPost'); $posts = $repository->getCurrentNewsPosts(); return $this->render('ecloreuserBundle:Static:newsposts.html.twig', array('posts' => $posts)); } } <file_sep>/userBundle/Resources/views/Timeline/verbs/registered.html.twig <li> <div class="iconeactu icone_annuaire" > </div> {{ timeline_component_render(timeline, 'subject') }} a rejoint le réseau. </li><file_sep>/userBundle/Resources/views/Young/manage-application.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mes projets'%} {%set second='Manager ma candidature'%} {% block content %} <h1> Administration de votre candidature au projet {{pa.project}} </h1> <br> Etat de la candidature: {{pa.status|PAStatus}}. La dernière modification remonte au {{pa.statusDate|date("d/m/Y")}}. {%if pa.message|length >0 %} <h3> Derniere communication : </h3> {{pa.message}} {%endif%} {% if pa.status == "TERMINATED" %} {{ form(form) }} {%endif%} {% endblock %} <file_sep>/userBundle/Form/temp web/AssoEditType.php <?php namespace eclore\userBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use eclore\userBundle\Form\ImageType; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\DependencyInjection\Container; class AssoEditType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('associationName', 'text', array('label' => " Nom de l'association :")) ->add('description','textarea', array('label' => " Quelles sont les activités de votre association ?")) ->add('location', 'text', array('attr' => array('class'=>'addressPickerInput') , 'label' => "Adresse de l'association") ) ->add('headshot', new ImageType(), array('required'=>false, , 'label' => "Logo de l'association")) ->add('save', 'submit') ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'eclore\userBundle\Entity\Association' )); } public function getName() { return 'eclore_user_assoedittype'; } }<file_sep>/userBundle/Resources/views/Static/en-construction.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Le réseau Eclore{% endblock %} {%set color='vert'%} {%set first='Réseau Eclore'%} {% block content %} <div class="coldroite"> <img src="{{ asset('bundles/ecloreuser/images/exovo_sueur.png') }}" style="width : 20% ; margin-right :5%; float:left; "> <h1> Cette page est encore en construction </h1> <a class="underlined" onclick="event.preventDefault();history.back();" href="#">Retournez à la page précédente</a> </div> {% endblock %}<file_sep>/userBundle/Admin/UserAdmin.php <?php namespace eclore\userBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Show\ShowMapper; use eclore\userBundle\Form\ImageType; class UserAdmin extends Admin { /** * @param DatagridMapper $datagridMapper */ /*protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('username') ->add('email') ->add('enabled') ->add('lastLogin') ->add('locked') ->add('expired') ->add('roles') ->add('credentialsExpired') ->add('birthDate') ->add('lastName') ->add('firstName') ->add('registrationDate') ->add('mobile') ->add('location') ->add('lastSeenDate') ; }*/ /** * @param ListMapper $listMapper */ protected function configureListFields(ListMapper $listMapper) {$roles; foreach($this->getConfigurationPool()->getContainer() ->getParameter('security.role_hierarchy.roles') as $key=>$value) { $roles[$key]=$key; } $listMapper ->add('username') ->add('email') ->add('young') ->add('instM') ->add('assoM') ->add('quality') ->add('enabled') ->add('locked') ->add('expired') ->add('albums') ->add('roles', 'choice', array('choices'=>$roles,'multiple'=>true )) ->add('credentialsExpired') ->add('lastName') ->add('firstName') ->add('birthDate', 'date') ->add('contacts', 'entity', array('class'=>'ecloreuserBundle:User', 'multiple'=>true, 'required' =>false)) ->add('_action', 'actions', array( 'actions' => array( 'show' => array(), 'edit' => array(), 'delete' => array(), ) )) ; } /** * @param FormMapper $formMapper */ protected function configureFormFields(FormMapper $formMapper) {$roles; foreach($this->getConfigurationPool()->getContainer() ->getParameter('security.role_hierarchy.roles') as $key=>$value) { $roles[$key]=$key; } $headshot = $this->getSubject()->getHeadshot(); $fileFieldOptions = array('required'=>false, 'help'=>'Pas de photo'); if ($headshot && ($webPath = $headshot->getWebPath())) { $container = $this->getConfigurationPool()->getContainer(); $fullPath = $container->get('request')->getBasePath().'/'.$webPath; $fileFieldOptions['help'] = '<img src="'.$fullPath.'" class="admin-preview" />'; } $formMapper ->add('username') ->add('usernameCanonical') ->add('young', 'entity', array('class'=>'ecloreuserBundle:Young', 'required' => false ) ) ->add('instM', 'entity', array('class'=>'ecloreuserBundle:InstitutionMember', 'required' => false ) ) ->add('assoM', 'entity', array('class'=>'ecloreuserBundle:AssociationMember', 'required' => false ) ) ->add('email') ->add('quality') ->add('emailCanonical') ->add('enabled', 'checkbox', array('required' => false )) ->add('locked', 'checkbox', array('required' => false )) ->add('expired', 'checkbox', array('required' => false )) ->add('roles', 'choice', array('choices'=>$roles,'multiple'=>true )) ->add('credentialsExpired', 'checkbox', array('required' => false )) ->add('credentialsExpireAt', 'date', array( 'widget' => 'single_text', 'required'=>false)) ->add('birthDate', 'date', array( 'widget' => 'choice', 'years'=>range((int)date("Y")-100, (int)date("Y")))) ->add('lastName') ->add('firstName') ->add('mobile') ->add('headshot', new ImageType(), $fileFieldOptions) ->add('lastSeenDate', 'date') ->add('contacts', 'entity', array('class'=>'ecloreuserBundle:User', 'multiple'=>true, 'required' =>false)) ; } /** * @param ShowMapper $showMapper */ protected function configureShowFields(ShowMapper $showMapper) { $showMapper ->add('username') ->add('usernameCanonical') ->add('email') ->add('emailCanonical') ->add('enabled') ->add('quality') ->add('salt') ->add('password') ->add('lastLogin', 'date') ->add('locked') ->add('expired') ->add('expiresAt', 'date') ->add('confirmationToken') ->add('passwordRequestedAt', 'date') ->add('roles') ->add('credentialsExpired') ->add('credentialsExpireAt', 'date') ->add('id') ->add('birthDate', 'date') ->add('lastName') ->add('firstName') ->add('registrationDate', 'date') ->add('mobile') ->add('headshot', 'entity', array('class'=>'ecloreuserBundle:Image', 'required' =>false, 'template' => 'ecloreuserBundle:Admin:show_headshot.html.twig')) ->add('lastSeenDate', 'date') ->add('contacts', 'entity', array('class'=>'ecloreuserBundle:User', 'multiple'=>true, 'required' =>false)) ; } } <file_sep>/userBundle/Resources/public/js/lambda/anim_lambda.js $(function () { $('.wrapper_el_projets').click(function(){ $('.wrapper_el_projets').css({"border" : "", "border-radius": "", "box-shadow" : " 1px 1px 2px 2px #fff" }); $(this).css({"border" : " 1px solid #ccc", "border-radius": " 5px", "box-shadow" : " 1px 1px 2px 2px #ccc" }); $('.projet_el_liste_bas').css({"display" : "none"}); $(this).children('.expandlink').children('.projet_el_liste_bas').css('display','block'); }); $("#defprofil>form>div").hide(); $('#fos_choix_type_membre').change(function(){ $("#defprofil>form>div").fadeOut(100); if ($('#fos_choix_type_membre').val() == 0){ $("#young").fadeIn(100); } if ($('#fos_choix_type_membre').val() == 1){ $("#instM").fadeIn(100); } if ($('#fos_choix_type_membre').val() == 2){ $("#assoM").fadeIn(100); } }) $('#assoM_associations').data("placeholder","Rechercher...").chosen({width: "60%"}); $('#young_institutions').data("placeholder","Rechercher...").chosen({width: "60%"}); $('#instM_institutions').data("placeholder","Rechercher...").chosen({width: "60%"}); }); <file_sep>/userBundle/Timeline/TimelineEvents.php <?php namespace eclore\userBundle\Timeline; final class TimelineEvents { //dispatch rules: //to user1 and user2 contacts OK const onContactAck = 'ecloreuser.timeline.contact_ack'; //to young contacts, its inst instM, Project responsibles. to project. OK const onValidatedPA = 'ecloreuser.timeline.validated_PA'; //to young contacts, its inst instM, Project responsibles OK const onNewPA = 'ecloreuser.timeline.new_PA'; //to young inst instM, Project responsibles OK const onRejectedPA = 'ecloreuser.timeline.rejected_PA'; //to all instM and young that took part in a project of this asso. to project and asso. OK const onNewProject = 'ecloreuser.timeline.new_project'; //to project responsible, instM from young, project OK const onMarkedProject = 'ecloreuser.timeline.marked_project'; //to instM from young OK const onMarkedYoung = 'ecloreuser.timeline.marked_young'; // assoM:to assoM of same asso OK // instM:to instM of same inst, youngs of same inst OK // young:to young's inst instM and young from inst OK const onNewUser = 'ecloreuser.timeline.new_user'; // when something needs to be validated by admin, send an email const onPendingValidation = 'ecloreuser.timeline.pending_validation'; } <file_sep>/userBundle/Resources/views/Timeline/verbs/take_part.html.twig <li > <div class="iconeactu icone_projets"> </div> {{ timeline_component_render(timeline, 'subject') }} participe au projet {{ timeline_component_render(timeline,'complement') }} </li><file_sep>/userBundle/Timeline/TimelineListener.php <?php namespace eclore\userBundle\Timeline; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\DependencyInjection\Container; class TimelineListener { protected $container; public function __construct(Container $container) { $this->container = $container; } public function onContactAck(ContactAckEvent $event) { $actionManager = $this->container->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($event->getAckUser()); $complement = $actionManager->findOrCreateComponent($event->getRequestingUser()); $action = $actionManager->create($subject, 'contact', array('complement' => $complement)); $actionManager->updateAction($action); } public function onValidatedPA(PAEvent $event) { $actionManager = $this->container->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($event->getPA()->getYoung()->getUser()); $complement = $actionManager->findOrCreateComponent($event->getPA()->getProject()); $action = $actionManager->create($subject, 'take_part', array('complement' => $complement)); $actionManager->updateAction($action); } public function onNewPA(PAEvent $event) { $actionManager = $this->container->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($event->getPA()->getYoung()->getUser()); $complement = $actionManager->findOrCreateComponent($event->getPA()->getProject()); $action = $actionManager->create($subject, 'apply', array('complement' => $complement)); $actionManager->updateAction($action); //send email email-newPA.html.twig /* $template = $this->container->get('twig')->loadTemplate('ecloreuserBundle:AssoM:email-newPA.html.twig'); $subject = $template->renderBlock('subject', array('project'=>$event->getPA()->getProject())); $htmlBody = $template->renderBlock('body_html', array('project'=>$event->getPA()->getProject())); $resps_emails = [] foreach($event->getPA()->getProject()->getResponsibles() as $resp) $resps_emails[]=$resp->getUser()->getEmail(); $message = \Swift_Message::newInstance() ->setSubject($subject) ->setFrom('<EMAIL>') ->setTo($resps_emails) ->setBody($htmlBody, 'text/html'); $this->container->get('mailer')->send($message); */ } public function onRejectedPA(PAEvent $event) { $actionManager = $this->container->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($event->getPA()->getYoung()->getUser()); $complement = $actionManager->findOrCreateComponent($event->getPA()->getProject()); $action = $actionManager->create($subject, 'be_rejected', array('complement' => $complement)); $actionManager->updateAction($action); } public function onNewProject(NewProjectEvent $event) { $actionManager = $this->container->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($event->getProject()->getAssociation()); $complement = $actionManager->findOrCreateComponent($event->getProject()); $action = $actionManager->create($subject, 'create_project', array('complement' => $complement)); $actionManager->updateAction($action); } public function onMarkedProject(MarkedEvent $event) { $actionManager = $this->container->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($event->getPA()->getYoung()->getUser()); $complement = $actionManager->findOrCreateComponent($event->getPA()->getProject()); $action = $actionManager->create($subject, 'mark_project', array('complement' => $complement)); $actionManager->updateAction($action); } public function onMarkedYoung(MarkedEvent $event) { $actionManager = $this->container->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($event->getPA()->getProject()->getAssociation()); $complement = $actionManager->findOrCreateComponent($event->getPA()->getYoung()->getUser()); $action = $actionManager->create($subject, 'mark_young', array('complement' => $complement)); $actionManager->updateAction($action); } public function onNewUser(NewUserEvent $event) { $actionManager = $this->container->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($event->getUser()); $complement = $actionManager->findOrCreateComponent($event->getUser()); $action = $actionManager->create($subject, 'registered', array('complement' => $complement)); $actionManager->updateAction($action); } public function onPendingValidation(Symfony\Component\EventDispatcher\Event $event) { $message = \Swift_Message::newInstance(); $template = $this->container->get('twig')->loadTemplate('ecloreuserBundle:Admin:email-pending-validation.html.twig'); $subject = $template->renderBlock('subject', array('subject' => 'subject')); $htmlBody = $template->renderBlock('body_html',array('body_html' => 'body_html')); $message = \Swift_Message::newInstance() ->setSubject($subject) ->setFrom('<EMAIL>') ->setTo('<EMAIL>') ->setBody($htmlBody, 'text/html'); $this->container->get('mailer')->send($message); } } <file_sep>/userBundle/Resources/views/Static/newspost.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Le réseau Eclore{% endblock %} {%set color='orange'%} {%set first='Actualité'%} {%set second= post.title %} {% block content %} <div class="colgauche"> {#{%for pic in post.pictures %}#} {%if post.pictures|length >0 %} <img src="{{app.request.basepath}}/{{ post.pictures|first.getWebPath }}" width='100%'> {%endif%} {#{%endfor%}#} </div> <div class="coldroite"> <h1> {{post.header}} </h1> <span class="soustitre"> Publiée le {{post.publishDate|date("m-d-Y")}} </span> </br> {{post.text}} </div> {% endblock %}<file_sep>/userBundle/Entity/Notification.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Notification * * @ORM\Table() * @ORM\Entity(repositoryClass="eclore\userBundle\Entity\NotificationRepository") */ class Notification { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var \stdClass * * @ORM\ManyToOne(targetEntity="eclore\userBundle\Entity\User", inversedBy="notifications") */ private $sender; /** * @var array * * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\User") */ private $receivers; /** * @var \stdClass * * @ORM\ManyToOne(targetEntity="eclore\userBundle\Entity\Project") */ private $project; /** * @var string * * @ORM\Column(name="type", type="string", length=255) */ private $type; /** * @var \DateTime * * @ORM\Column(name="initDate", type="date") */ private $initDate; /** * @var string * * @ORM\Column(name="message", type="text") */ private $message; public function __construct() { $this->initDate = new \DateTime(); $this->receivers = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set sender * * @param \stdClass $sender * @return Notification */ public function setSender($sender) { $this->sender = $sender; $sender->addNotification($this); return $this; } /** * Get sender * * @return \stdClass */ public function getSender() { return $this->sender; } /** * Set type * * @param string $type * @return Notification */ public function setType($type) { $this->type = $type; return $this; } /** * Get type * * @return string */ public function getType() { return $this->type; } /** * Set initDate * * @param \DateTime $initDate * @return Notification */ public function setInitDate($initDate) { $this->initDate = $initDate; return $this; } /** * Get initDate * * @return \DateTime */ public function getInitDate() { return $this->initDate; } /** * Set message * * @param string $message * @return Notification */ public function setMessage($message) { $this->message = $message; return $this; } /** * Get message * * @return string */ public function getMessage() { return $this->message; } public function setProject($project) { $this->project = $project; return $this; } /** * Get message * * @return string */ public function getProject() { return $this->project; } public function addReceiver($receiver) { $this->receivers[] = $receiver; } /** * Remove institutions * * @param \eclore\userBundle\Entity\User $receiver */ public function removeReceiver($receiver) { $this->receivers->removeElement($receiver); } /** * Get institutions * * @return array */ public function getReceivers() { return $this->receivers; } } <file_sep>/userBundle/Resources/views/AssoM/manage-project.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite"> {% set rejected = proj.PAByStatus('REJECTED') %} {% set validated = proj.PAByStatus('VALIDATED') %} {% set pending = proj.PAByStatus('PENDING') %} <h1> Espace d'administration du projet {{proj.projectName}}. </h1> <div class="wrapper_el_projets"> <a href="" class="expandlink" onclick="return false"> <div class="projet_el_liste_haut"> <div class="hautgauche"> <img src="{{ asset('bundles/ecloreuser/images/projets/proj1.png') }}"></img></div> <div class="hautdroit"> <h2> <span>{{proj.projectName}} ({{proj.getPAByStatus('PENDING')|length + (proj.isFinished ? proj.getPAByStatus('VALIDATED')|length : 0)}} notifications)</span> </h2> <span class="soustitre"> <span>{{proj.getDuration|number_format}} jours, </span> <span>{{proj.address}}</span>, <span> Responsable: {{proj.responsibles|join(', ') }}</span></br> <span>{{proj.shortDescription}}</span> </div> </div> <div class="projet_el_liste_bas"> <span>{{proj.description}}</span> </div> </a> </div> </br> <a href="{{ path('assom_editProject', { 'id': proj.id }) }}"> Modifier ce projet </a> </br> <h2> Statut du projet </h2> {%if not proj.enabled%} Ce projet est en attente de validation de la part des administrateurs. Vous serez averti de sa validation. {%else%} <div class="colquarter statutproj"> <div class="imgtitle icone_annuaire"> </div> {%if proj.isFinished %} Terminé. {%elseif (not proj.isFinished) and proj.isStarted %} En cours. {%else%} Publié. {%endif%} </div> <div class="colquarter participants"> <div class="imgtitle icone_recom"> </div> {%if not proj.isFinished%} {%if proj.isFull %}Ce projet possède le nombre de participants requis. {%else%}{{proj.required - proj.getPAByStatus('VALIDATED')|length}} participants encore souhaités. {%endif%} {%else%} Merci de clôturer les candidatures des jeunes ayant participé.</br> {%endif%} </div> <div class="colhalf candidatures"> <div class="imgtitle icone_newprojet"> </div> {%if proj.isFinished%} {% if validated|length >0 %} Candidatures à clôturer: <ul> {% for pa in validated %} <li>{{pa.young}} <a href="{{ path('assom_manageApplication', { 'id': pa.id }) }}">Clôturer</a></li> {% endfor %} </ul> {% else %} {% endif %} {%else%} {% if pending|length >0 %} <br> Candidatures à traiter: <ul> {% for pa in pending %} <li>{{pa.young}} <a href="{{ path('assom_manageApplication', { 'id': pa.id }) }}">Manager</a></li> {% endfor %} </ul> {% else %} Pas de candidatures à traiter. {% endif %} </br> {% if validated|length >0 %} Candidatures validées: <ul> {% for pa in validated %} <li>{{pa.young}} <a href="{{ path('assom_manageApplication', { 'id': pa.id }) }}">Manager</a></li> {% endfor %} </ul> {% else %} {# Pas de candidatures validées. #} {% endif %} </br> {% if rejected|length >0 %} Candidatures rejetées: <ul> {% for pa in rejected %} <li>{{pa.young}} <a href="{{ path('assom_manageApplication', { 'id': pa.id }) }}">Manager</a></li> {% endfor %} </ul> {% else %} {# Pas de candidatures rejetées. #} {% endif %} {%endif%} </div> Si vous souhaitez supprimer ce projet, ou ajouter des responsables, merci de contacter le réseau à <EMAIL> </div> <div class="clearboth"></div> {%endif%} <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Resources/views/AssoM/email-newPA.html.twig {% block subject %} Nouvelle candidature au projet {{project.projectName}} {% endblock %} {% block body_html %} à mettre à jour avec le design prévu {% endblock %} <file_sep>/userBundle/Resources/views/Admin/home.html.twig {% block title %}Administration{% endblock%} {% block content %} {% for key, messages in app.session.flashbag.all() %} {% for message in messages %} <div class="alert-{{ key }}"> {{ message|trans({}, 'FOSUserBundle') }} </div> {% endfor %} {% endfor %} <a href="{{ path('sonata_admin_dashboard') }}">Accéder à la plateforme de gestion des enregistrements</a> <br> {% if assoMs |length>0 or instMs|length>0 %} <h3>Profils en attente de validation</h3> {% if assoMs |length>0 %} <h4>Membres d'associations</h4> <table> {% for assoM in assoMs %} <tr><td>{{assoM}}</td><td>{{assoM.user.quality}}</td> <td>{{assoM.user.registrationDate|date("m-d-Y")}}</td> <td><a href="{{ path('admin_validate_profile', { 'type': 'AssoM', 'id': assoM.id }) }}">Valider</a></td></tr> {% endfor%} </table> {%endif%} <br> {% if instMs |length>0%} <h4>Membres d'institutions</h4> <table> {% for instM in instMs %} <tr><td>{{instM}}</td><td>{{instM.user.quality}}</td> <td>{{instM.user.registrationDate|date("m-d-Y")}}</td> <td><a href="{{ path('admin_validate_profile', { 'type': 'InstM', 'id': instM.id }) }}">Valider</a></td></tr> {% endfor%} </table> {%endif%} {%endif%} {% if projects|length>0 %} <br> <h3>Projets en attente de validation</h3> <table> {% for proj in projects %} <tr><td>{{proj}}</td><td>{{proj.association}}</td><td>{{proj.description}}</td> <td>{{proj.responsibles|join(', ') }}</td><td>{{proj.startDate|date("m-d-Y")}}</td> <td><a href="{{ path('admin_validate_project', { 'id': proj.id }) }}">Valider</a></td></tr> {% endfor%} </table> {%endif%} {% endblock %}<file_sep>/userBundle/Resources/views/Block/overviewBlock.html.twig {% extends 'SonataBlockBundle:Block:block_base.html.twig' %} {% block block %} <h5>Bienvenue dans la plateforme de gestion des enregistrements</h5> Sont enregistrés à ce jour: <ul> <li>{{count.proj}} projets</li> <li>{{count.pa}} candidatures</li> <li>{{count.young}} jeunes</li> <li>{{count.image}} images</li> <li>{{count.asso}} associations totalisant {{count.assoM}} membres</li> <li>{{count.inst}} institutions totalisant {{count.instM}} membres</li> </ul> <br><br> <a href="{{ path('admin_page') }}">Page de démarrage</a> {% endblock %}<file_sep>/userBundle/Block/overviewBlockService.php <?php namespace eclore\userBundle\Block; use Sonata\BlockBundle\Block\BlockContextInterface; use Symfony\Component\HttpFoundation\Response; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Validator\ErrorElement; use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; use Sonata\BlockBundle\Model\BlockInterface; use Sonata\BlockBundle\Block\BaseBlockService; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Doctrine\ORM\EntityManager; class overviewBlockService extends BaseBlockService {private $em; /** * {@inheritdoc} */ public function buildEditForm(FormMapper $form, BlockInterface $block) { } public function __construct($name, EngineInterface $templating, EntityManager $entityManager) { parent::__construct($name, $templating); $this->em = $entityManager; } public function execute(BlockContextInterface $blockContext, Response $response = null) { $data = array('proj'=>'ecloreuserBundle:Project', 'pa'=>'ecloreuserBundle:ProjectApplication', 'assoM'=>'ecloreuserBundle:AssociationMember', 'instM'=>'ecloreuserBundle:InstitutionMember', 'asso'=>'ecloreuserBundle:Association', 'inst'=>'ecloreuserBundle:Institution', 'young'=>'ecloreuserBundle:Young', 'image'=>'ecloreuserBundle:Image'); $count; foreach($data as $key=>$value) $count[$key]= $this->em->getRepository($value) ->createQueryBuilder('p') ->select('COUNT(p)') ->getQuery() ->getSingleScalarResult(); return $this->renderResponse($blockContext->getTemplate(), array( 'block' => $blockContext->getBlock(), 'settings' => $blockContext->getSettings(), 'count' => $count ), $response); } /** * {@inheritdoc} */ public function validateBlock(ErrorElement $errorElement, BlockInterface $block) { // TODO: Implement validateBlock() method. } /** * {@inheritdoc} */ public function getName() { return 'Overview'; } /** * {@inheritdoc} */ public function setDefaultSettings(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'template' => 'ecloreuserBundle:Block:overviewBlock.html.twig' )); } } <file_sep>/userBundle/Resources/public/js/projects/Temp web/2_map.js var geocoder; var map; var objects; var labels=[]; var associations=[]; var markers = []; var infowindows = []; var colors = ["808080", "336666", "357723"]; default_location=new google.maps.LatLng(48.817348,2.371005); var previousOpen=-1; function initialize() { var mapOptions = { zoom: 10, center: default_location, scaleControl: true } map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); } //functions for displaying and removing markers function addMarker(obj) { lat=obj.lat lng=obj.lng descr=obj.description+"<br><a href='"+voirProjetUrl+obj.id+"'>Plus de détails...</a>" titre =obj.project_name id = obj.id start_date = new Date(obj.start_date*1000); end_date = new Date(obj.end_date*1000); asso = obj.association.associationName var content = '<b>'+titre+' ('+asso+') du '+start_date.toLocaleDateString()+' au '+end_date.toLocaleDateString()+'</b><br>'+descr var infowindow = new google.maps.InfoWindow({content: content, maxWidth: 500}); var marker = new google.maps.Marker({ position: new google.maps.LatLng(lat,lng), map: map, icon: "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"+colors[id % colors.length], title: titre}); google.maps.event.addListener(marker, 'click', function() {infowindow.open(map,marker);}); markers[id]=marker infowindows[id]=infowindow } function setAllMap(map) { for (var key in markers) { markers[key].setMap(map); } } function deleteMarkers() { setAllMap(null); markers = []; infowindows = []; } function codeAddress(address) { //returns [lat, lng] from adress return geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng())); map.setZoom(10) } else { alert("Geocode was not successful for the following reason: " + status); } }); } function showMarkers(){ deleteMarkers() var filteredDivs = $("#example div.item "); $.each(filteredDivs, function (index, div) { addMarker(objects[parseInt(div.attr('id'))]) }); setAllMap(map) } function getDuration(obj){ return parseInt((obj.end_date - obj.start_date)/86400.0) } function sortJSON(data, key, way) { data.sort(function(a, b) { var x; var y; switch(key){ case 'duration': x = getDuration(a); y = getDuration(b); break; case 'association': x = a.association.associationName; y = b.association.associationName; break; default: x = a[key]; y = b[key]; } if (way === '+' ) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } if (way === '-') { return ((x > y) ? -1 : ((x < y) ? 1 : 0)); } }); return data } function filterData(data){ if($("#label_select").val() != null) data = $.grep(data, function(proj, i){return $("#label_select").val().indexOf(proj.labels.id+"") > -1}); if($("#association_select").val() != null) data = $.grep(data, function(proj, i){return $("#association_select").val().indexOf(proj.association.id+"") > -1}); return data } function sortData(data){ critere = $('#tri').val(); data = sortJSON(data, critere.substring(0, critere.length-1), critere.charAt(critere.length-1)); return data } function displayProjects(data){ data = filterData(data) data = sortData(data) deleteMarkers() $("#results").empty() $.each(data, function(idx, obj){ addMarker(obj) start_date = new Date(obj.start_date*1000) $("#results").append( '<ul class="item" id="'+obj.id+'"><li> <div class="wrapper_el_projets"><a href="" class="expandlink" onclick="return false">'+ '<div class="projet_el_liste_haut">'+ '<div class="hautgauche"> <img src='+logoProjet+'></img></div> '+ '<div class="hautdroit"> <h2> <span>'+obj.project_name+'</span> </h2>'+ '<span class="soustitre"> <span>'+getDuration(obj)+' jours ('+start_date.toLocaleDateString()+ ' - '+end_date.toLocaleDateString()+') </span> <span>'+obj.address+'</span></br>'+ '<span>'+obj.short_description+'</span></div></div><div class="projet_el_liste_bas">'+ '<span>'+obj.description+'</span></div></a></div></li></ul> ' ) }); if(data.length==0)$("#results").append('Pas de résultats.'); } function populate(id, table, id_select, option){ if(table.indexOf(id) == -1){ $(id_select).append(option) table.push(id) } } $(document).ready(function() { google.maps.event.addDomListener(window, 'load', initialize); geocoder = new google.maps.Geocoder(); var request = $.ajax({ url: url, type: "POST", dataType: "json" }); //chargement resultats request.done(function( data ) { objects = data $.each(data, function(idx, obj){ //populate label selection tool populate(obj.labels.id, labels, "#label_select", "<option value="+obj.labels.id+">"+obj.labels.name+"</option>") populate(obj.association.id, associations, "#association_select", "<option value="+obj.association.id+">"+obj.association.associationName+"</option>") }); displayProjects(data) //label selection tool $("#label_select").change(function(){displayProjects(data)}); //association selection tool $("#association_select").change(function(){displayProjects(data)}); //tri tool $("#tri").change(function(){displayProjects(data)}); //centrer la carte sur ce projet et ouvrir l'infowindow $("#results ul.item ").click( function() { var i = parseInt($(this).attr('id')) map.setCenter(markers[i].getPosition()); if(previousOpen != -1){infowindows[previousOpen].close();} infowindows[i].open(map,markers[i]); previousOpen = i }); //showMarkers() $("#loading").fadeOut() $("#search_zone").fadeIn() $("#label_select").chosen(); $("#association_select").chosen(); $("#tri").data("placeholder","Trier les projets...").chosen(); }); request.fail(function( jqXHR, textStatus ) { $('#results').html( "Request failed: " + textStatus+jqXHR.status ); $("#loading").fadeOut() $("#search_zone").fadeIn() }); $("#loc_submit").click(function(){ if($("#loc").val() !=""){ codeAddress($("#loc").val()); } }); $("#loc").keyup(function(event){ if(event.keyCode == 13){ $("#loc_submit").click(); } }); });<file_sep>/userBundle/Resources/views/Static/newsposts.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Le réseau Eclore{% endblock %} {%set color='orange'%} {%set first='Actualité'%} {%set second='Toutes les actualités' %} {% block content %} <div class="colgauche"> {%for post in posts %} post {%endfor%} {% endblock %} <file_sep>/userBundle/Resources/views/Members/display-asso.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} <div id="menugauche"> <img src="{{app.request.basepath}}/{{ asso.getHeadshotWebPath }}" width='100%'> </div> <div class="coldroite"> <h1>{{asso.associationName}}</h1> <div class="soustitre"> {{asso.location}} </div> {{asso.description}} <p> {%if asso.members|length ==0 %} Cette association n'a pas de membres. {%else%} Membres de cette association: <ul> {%for membre in asso.members %} {%if membre.user.privacyLevel != 2 %} <li>{{membre.user|printName}}</li> {%endif%} {%endfor%} </ul> {%endif%} </p> </div> {% endblock %} <file_sep>/userBundle/Form/ProjectRegisterType.php <?php namespace eclore\userBundle\Form; use Doctrine\ORM\EntityManager; use NoxLogic\DemoBundle\Entity\Province; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\Security\Core\SecurityContext; class ProjectRegisterType extends ProjectType { public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder->remove('projectApplications'); $builder->remove('responsibles'); } public function getName() { return 'eclore_userbundle_projectregistertype'; } }<file_sep>/userBundle/Entity/User.php <?php // src/eclore/UserBundle/Entity/User.php namespace eclore\userBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="eclore_user") */ class User extends BaseUser { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var \DateTime * * @ORM\Column(name="birthDate", type="date") */ private $birthDate; /** * @var string * * @ORM\Column(name="lastName", type="string", length=255) */ private $lastName; /** * @var string * * @ORM\Column(name="firstName", type="string", length=255) */ private $firstName; /** * @var integer * * @ORM\Column(name="privacyLevel", type="integer") */ protected $privacyLevel; /** * @var \DateTime * * @ORM\Column(name="registrationDate", type="date") */ private $registrationDate; /** * @var array * * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\User") */ private $contacts; /** * @var array * * @ORM\OneToMany(targetEntity="eclore\userBundle\Entity\Notification", mappedBy="sender") */ private $notifications; /** * @var string * * @ORM\Column(name="mobile", type="string", length=20) */ private $mobile; /** * @var \DateTime * * @ORM\Column(name="lastSeenDate", type="date") */ private $lastSeenDate; /** * @ORM\OneToOne(targetEntity="eclore\userBundle\Entity\Young", mappedBy = "user", cascade={"remove", "persist"}) */ private $young; /** * @ORM\OneToOne(targetEntity="eclore\userBundle\Entity\InstitutionMember", mappedBy = "user", cascade={"remove", "persist"}) */ private $instM; /** * @ORM\OneToOne(targetEntity="eclore\userBundle\Entity\AssociationMember", mappedBy = "user", cascade={"remove", "persist"}) */ private $assoM; /** * @ORM\OneToOne(targetEntity="eclore\userBundle\Entity\Image", cascade={"persist", "remove"}) */ private $headshot; /** * @ORM\OneToMany(targetEntity="eclore\userBundle\Entity\Album", cascade={"remove"}, mappedBy="owner") */ private $albums; /** * @var string * * @ORM\Column(name="quality", type="text") */ private $quality; public function __construct() { parent::__construct(); $this->contacts = new \Doctrine\Common\Collections\ArrayCollection(); $this->notifications = new \Doctrine\Common\Collections\ArrayCollection(); $this->albums = new \Doctrine\Common\Collections\ArrayCollection(); $this->lastSeenDate = new \DateTime(); $this->registrationDate = new \DateTime(); } public function getHeadshot() { return $this->headshot; } public function setHeadshot(\eclore\userBundle\Entity\Image $headshot) { return $this->headshot = $headshot; } public function getPrivacyLevel() { return $this->privacyLevel; } public function setPrivacyLevel($lvl) { return $this->privacyLevel = $lvl; } public function getYoung() { return $this->young; } public function getAssoM() { return $this->assoM; } public function getInstM() { return $this->instM; } public function setYoung(\eclore\userBundle\Entity\Young $young) { $this->young = $young; return $this; } public function setAssoM(\eclore\userBundle\Entity\AssociationMember $assoM) { $this->assoM = $assoM; return $this; } public function setInstM(\eclore\userBundle\Entity\InstitutionMember $instM) { $this->instM = $instM; return $this; } public function __toString() { return $this->getFirstName()." ".$this->getLastName(); } public function getExpiresAt() { return $this->expiresAt; } public function getCredentialsExpireAt() { return $this->credentialsExpireAt; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set birthDate * * @param \DateTime $birthDate * @return Member */ public function setBirthDate($birthDate) { $this->birthDate = $birthDate; return $this; } /** * Get birthDate * * @return \DateTime */ public function getBirthDate() { return $this->birthDate; } /** * Set lastName * * @param string $lastName * @return Member */ public function setLastName($lastName) { $this->lastName = ucfirst($lastName); return $this; } /** * Get lastName * * @return string */ public function getLastName() { return $this->lastName; } /** * Set firstName * * @param string $firstName * @return Member */ public function setFirstName($firstName) { $this->firstName = ucfirst($firstName); return $this; } /** * Get firstName * * @return string */ public function getFirstName() { return $this->firstName; } /** * Set registrationDate * * @param \DateTime $registrationDate * @return Member */ public function setRegistrationDate($registrationDate) { $this->registrationDate = $registrationDate; return $this; } /** * Get registrationDate * * @return \DateTime */ public function getRegistrationDate() { return $this->registrationDate; } /** * Set mobile * * @param string $mobile * @return Member */ public function setMobile($mobile) { $this->mobile = $mobile; return $this; } /** * Get mobile * * @return string */ public function getMobile() { return $this->mobile; } /** * Set lastSeenDate * * @param \DateTime $lastSeenDate * @return Member */ public function setLastSeenDate($lastSeenDate) { $this->lastSeenDate = $lastSeenDate; return $this; } /** * Get lastSeenDate * * @return \DateTime */ public function getLastSeenDate() { return $this->lastSeenDate; } /** * Add contacts * * @param eclore\userBundle\Entity\User $user */ public function addContact(\eclore\userBundle\Entity\User $user) { if(!$this->contacts->contains($user)) $this->contacts[] = $user; } /** * Remove contacts * * @param eclore\userBundle\Entity\User $user */ public function removeContact(\eclore\userBundle\Entity\User $user) { $this->contacts->removeElement($user); } /** * Get contacts * * @return array */ public function getContacts() { return $this->contacts; } public function addAlbum(\eclore\userBundle\Entity\Album $album) { $this->albums[] = $album; } public function removeAlbum(\eclore\userBundle\Entity\Album $album) { $this->albums->removeElement($album); } public function getAlbums() { return $this->albums; } public function addNotification(\eclore\userBundle\Entity\Notification $notification) { $this->notifications[] = $notification; } public function removeNotification(\eclore\userBundle\Entity\Notification $notification) { $this->notifications->removeElement($notification); } public function getNotifications() { return $this->notifications; } /** * Set quality * * @param string $quality * @return User */ public function setQuality($quality) { $this->quality = $quality; return $this; } /** * Get quality * * @return string */ public function getQuality() { return $this->quality; } public function getAge() { $today = new \DateTime; return (int)(($today->format('U') - $this->getBirthDate()->format('U'))/(365*24*3600)); } public function getContactsByRole($role) { $res=array(); foreach($this->getContacts() as $contact) if($contact->hasRole($role)) $res[]=$contact; return $res; } public function getHeadshotWebPath() { if($this->headshot==null) return 'uploads/img/defaultHeadshot.jpg'; return $this->headshot->getWebPath(); } }<file_sep>/userBundle/Admin/NewsPostAdmin.php <?php namespace eclore\userBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Show\ShowMapper; use eclore\userBundle\Form\ImageType; class NewsPostAdmin extends Admin { /** * @param ListMapper $listMapper */ protected function configureListFields(ListMapper $listMapper) { $listMapper ->add('title') ->add('publishDate') ->add('endDate') ->add('header') ->add('text') ->add('pictures', 'entity', array('class'=>'ecloreuserBundle:Image', 'multiple'=>true, 'required' =>false)) ->add('_action', 'actions', array( 'actions' => array( 'show' => array(), 'edit' => array(), 'delete' => array(), ) )) ; } /** * @param FormMapper $formMapper */ protected function configureFormFields(FormMapper $formMapper) { $images = $this->getSubject()->getPictures(); $fileFieldOptions = array('type' => new ImageType(), 'allow_add' => true, 'allow_delete' => true, 'required' => false, 'by_reference' => false, 'help'=>''); foreach($images as $image) if ($image && ($webPath = $image->getWebPath())) { $container = $this->getConfigurationPool()->getContainer(); $fullPath = $container->get('request')->getBasePath().'/'.$webPath; $fileFieldOptions['help'] .= '<img src="'.$fullPath.'" class="admin-preview" />'; } $formMapper ->add('title') ->add('publishDate') ->add('endDate') ->add('header') ->add('text') ->add('pictures', 'collection', $fileFieldOptions) ; } /** * @param ShowMapper $showMapper */ protected function configureShowFields(ShowMapper $showMapper) { $showMapper ->add('title') ->add('publishDate') ->add('endDate') ->add('header') ->add('text') ->add('pictures', 'entity', array('class'=>'ecloreuserBundle:Image', 'multiple'=>true, 'required' =>false, 'template' => 'ecloreuserBundle:Admin:show_album_pictures.html.twig')) ; } } <file_sep>/userBundle/Form/InstEditType.php <?php namespace eclore\userBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use eclore\userBundle\Form\ImageType; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\DependencyInjection\Container; class InstEditType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('institutionName','text' , array('label' => 'Nom de l\'institution :')) ->add('description','textarea' , array('label' => 'Courte description :')) ->add('location', 'text', array('attr' => array('class'=>'addressPickerInput') , 'label' => "Adresse de l'institution :") ) ->add('headshot', new ImageType(), array('required'=>false, 'label' => 'Logo :')) ->add('save', 'submit', array( 'label' => 'Ajouter' ) ) ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'eclore\userBundle\Entity\Institution' )); } public function getName() { return 'eclore_user_instedittype'; } }<file_sep>/userBundle/Resources/views/index.html.twig <!DOCTYPE html> <html> <head> <title>Le Réseau Éclore, des jeunes pour des projets associatifs</title> <meta charset='utf-8' /> <meta name="description" content="Découvrez les actions associatives pensées pour les jeunes autour de chez vous et proposez vos projets !"/> <meta name="keywords" content="Réseau, Eclore, jeunes, projets, association, dialogue, gratuité, respect, apporter" /> <meta name="robots" content="index, follow, all" /> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <meta name="viewport" content="width=device-width" /> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/css/lambda/menu.css')}}" type="text/css" /> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/css/accueil/accueil.css')}}" type="text/css" /> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/css/accueil/footer.css')}}" type="text/css" /> <link rel="stylesheet" href="{{ asset('bundles/ecloreuser/css/accueil/content.css')}}" type="text/css" /> </head> <body> <!-- Le menu du haut, le logo et les icônes des réseaux sociaux -----------------------------------------------------------------------------------------------------------------------------> <header> <div id="menuhaut" style="width:80%" style="z-index:100;"> <!-- {% block menu %} {% endblock %} --> <div class="menu bleu" style='position:absolute; top : 63%;'> {% include 'ecloreuserBundle::menu.html.twig' %} </div> <div class="lienrezo"> <a href="http://www.facebook.com/reseau.eclore" target="_blank"> <img src="{{ asset('bundles/ecloreuser/images/icone_fb.png')}}" alt="Lien Facebook"> </a> <a href="https://twitter.com/ResEclore" target="_blank"> <img src="{{ asset('bundles/ecloreuser/images/icone_twitter.png')}}" alt="Lien Twitter"> </a> <a href="http://reseau-eclore.tumblr.com/" target="_blank"> <img src="{{ asset('bundles/ecloreuser/images/icone_tumblr.png')}}" alt="Lien Tumblr"> </a> </div> </div> </header> <a href="{{path('ecloreuser_homepage')}}" id="logo"> <img src="{{ asset('bundles/ecloreuser/images/logo.png')}}" alt="Logo de l'association" style="width:100%"> </a> <div style='clear:both'></div> <!-- Le corps du site -----------------------------------------------------------------------------------------------------------------------------> <div id="wrapper"> <section id="cloud"> <div id="navarea"> <a id="area_projet" href="#" title="Lien vers les projets" ></a> <a id="area_reseau" href="#" title="Lien vers le réseau"></a> <a id="area_eclore" href="#" title="Lien vers la présentation du réseau Éclore"></a> </div> <div id="cloud_bkg"> </div> <div class="cloud_f" id="cloud_bleu"> </div> <div class="cloud_f" id="cloud_vert"> </div> <div class="cloud_f" id="cloud_orange"> </div> </section> <div id="container" style="width:210px;"> <section id="projet" class="content"> <div id="banner_projet" class="banner"> <div class="textbanner"> <h1>Trouvez ou déposez un projet !</h1> </div> </div> <article id="inscription"> <h2> Rejoignez le réseau </h2> <div id="boutoninscription"> {% if not is_granted('IS_AUTHENTICATED_REMEMBERED') %} <a href="{{ path('fos_user_registration_register') }}" > Inscrivez-vous </a> Déjà inscrit(e) ? <a href="{{ path('fos_user_security_login') }}" > Connectez-vous </a> {%else%} <a href="{{ path('ecloreuser_home') }}" "> Accédez à votre espace </a> {%endif%} </div> </article> <article id="recherche"> <h2> Rechercher un projet</h2> <div id="boutoninscription"> <div id="rechercheprojets"> <a href="{{ path('ecloreuser_rechercherProjet') }}">Accéder à la zone de recherche</a> </div> </div> </article> <article id="derniersprojets"> <h2> Les derniers projets ajoutés </h2> <div class="projetcarousel"> <div id="projcarousel"> {%for proj in projs %} <div class="elprojetcarousel"> <div class="elprojet_haut"> <img src="{{ asset('bundles/ecloreuser/images/projets/proj1.png')}}" alt="Image de description du projet"> </img> <div> <ul> <li>{{proj.city}}</li> </ul><ul> <li>Projet de {{proj.getDuration//12}} mois</li> </ul> </div> <img src="{{ asset('bundles/ecloreuser/images/separation_bleu.png')}}" alt="Image de description du projet"> </img> </div> <h3>{{proj.projectName}}</h3> <p> {{proj.shortDescription}}</p> </div> {%endfor%} </div> <div class="clearfix"></div> <a class="prev" id="carousel_prev" href="#"> <span>prev</span> </a> <a class="next" id="carousel_next" href="#"><span>next</span></a> </div> </article> </section> <section id="reseau" class="content"> <div id="banner_reseau" class="banner"> <div class="textbanner"> <h1>Découvrez la vie du réseau</h1> </div> </div> <article id="focus"> <div id="foccarousel"> <div id="foccarousel"> {%for post in posts %} {%if post.pictures|length >0 %} <div class="elfoccarousel"> <img src="{% if post.pictures|length >1 %} {{app.request.basepath}}/{{ post.pictures[1].getWebPath }} {% else %} {{app.request.basepath}}/{{ post.pictures|first.getWebPath }} {% endif %} " alt="Image 1 du focus"> </img> <div class="elfoccarousel_banner">{{post.title}}</div> </div> {%endif%} {%endfor%} </div> </div> <div class="clearfix"></div> </article> <article id="actualite"> <h2> Les actualités du réseau </h2> {%for post in posts %} <div class="elactualite" id="actu1"> <img class="img_elactualite" src="{{ asset('bundles/ecloreuser/images/cadre_photo_actu.png')}}" alt="Cadre de l'image de présention de l'actualité"> </img> <h3>{{post.title}}</h3> <p>{{post.header}}</p> <div> <a href="{{ path('displayNewsPost', {'id': post.id }) }}"> voir plus >> </a> <img class="sep_elactualite" src="{{ asset('bundles/ecloreuser/images/separation_orange.png')}}" alt="Barre de séparation"> </img> </div> </div> {%endfor%} <div class="lienrezo" style="position: relative; top:50px;"> <a href="http://www.facebook.com/reseau.eclore" target="_blank"> <img src="{{ asset('bundles/ecloreuser/images/icone_fb_orange.png')}}" alt="Lien Facebook"> </a> <a href="https://twitter.com/ResEclore" target="_blank"> <img src="{{ asset('bundles/ecloreuser/images/icone_twitter_orange.png')}}" alt="Lien Twitter"> </a> <a href="http://reseau-eclore.tumblr.com/" target="_blank"> <img src="{{ asset('bundles/ecloreuser/images/icone_tumblr_orange.png')}}" alt="Lien Tumblr"> </a> </div> </article> <!-- <article class="filactu"> <h2> Fil Twitter</h2> </article> --> <article class="filactu" id="tweet" > </article> </section> <section id="eclore" class="content"> <div id="banner_eclore" class="banner"> <div class="textbanner"> <h1>Le réseau Éclore veut développer l'engagement des jeunes comme acteurs du milieu associatif</h1> </div> </div> <article id="videopres" style="color:#fff; font-size:1.5em; text-align:center;"> <p > Vidéo de présentation (à venir) ;) </p> <img src="{{ asset('bundles/ecloreuser/images/exovo_sueur.png')}}" style="width : 15% ; display: inline;"> </article> <article id="presasso"> <div class="presasso_el"> <img src="{{ asset('bundles/ecloreuser/images/exovo_etude.png')}}" alt="Mascotte d'Eclore en étudiant"> </img> Nous sommes 6 jeunes autour de 25 ans, étudiants, jeunes professionnels, passés par des associations variées qui nous ont fait confiance et convaincus que cela a été une chance pour notre propre parcours. Nous apportons ainsi nos différentes expériences au réseau Éclore pour partager cette chance avec tous les jeunes. </div> <div class="presasso_el"> <img src="{{ asset('bundles/ecloreuser/images/exovo_reseau.png')}}" alt="Mascotte d'Eclore en réseau"> </img> Le réseau s’adresse à la fois aux associations qui souhaitent impliquer dans leurs projets des jeunes bénévoles, et aux jeunes souhaitant s’engager dans le milieu associatif. Il vise à mettre en relation des jeunes et des projets associatifs locaux, afin de promouvoir l’engagement bénévole dans la société civile et de développer les liens entre les associations et les nouvelles générations. </div> <div class="presasso_el"> <img src="{{ asset('bundles/ecloreuser/images/exovo_cote.png')}}" alt="Mascotte d'Eclore de coté"> </img> Toute association engagée dans un projet vers les autres, de même que tout jeune désireux de s’engager dans un tel projet, peut s’inscrire au réseau Éclore, si elle ou il adhère à la charte et aux valeurs du réseau. </div> </article> </section> <section class="descriptions"> <div class="descr mod bleu" > <div class="textedescr"> </div> </div> <div class="descr bleu" > <div class="textedescr"> </div> </div> <div class="descr orange" > <div class="textedescr"> </div> </div> <div class="descr vert" > <div class="textedescr"> </div> </div> </section> <section class="onglets"> <a href="#" class="onglet bleu" > </a> <a href="#" class="onglet orange" > </a> <a href="#" class="onglet vert" > </a> </section> </div> </div> <footer class="bleu" style=''> <a href="https://plus.google.com/u/0/108771494758848918220? rel=author" style="display:hidden;"></a> <ul> <li> <h3> <a href="{{ path('ecloreuser_sitemap') }}"> Plan du site </a> </h3> <li> <h3><a href="{{ path('ecloreuser_mentions') }}">Mention légales</a> </h3> </li> <li> <h3> <a href="{{ path('ecloreuser_statuts') }}">Nos statuts</a> </h3> </li> <li><h3> <a href="mailto:<EMAIL>?subject=Contact">Nous contacter</a> </h3> </li> </ul> </footer> <script src="{{ asset('bundles/ecloreuser/js/lambda/jquery.min.js')}}"> </script> <script src="{{ asset('bundles/ecloreuser/js/lambda/jquery.easing.min.js')}}"> </script> <script src="{{ asset('bundles/ecloreuser/js/lambda/jquery.carouFredSel-6.2.1-packed.js')}}" type="text/javascript"></script> <script src="{{ asset('bundles/ecloreuser/js/accueil/anim.js')}}"> </script> <script src="{{ asset('bundles/ecloreuser/js/lambda/anim_menu.js')}}"> </script> <script src="{{ asset('bundles/ecloreuser/js/accueil/tweecool.min.js')}}"> </script> </body> </html> <file_sep>/userBundle/Resources/views/AssoM/Temp web/projects.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite projets"> <h1> Mes projets </h1> {% if app.user.assoM.managedProjects|length > 0 %} {% for proj in app.user.assoM.managedProjects %} <ul> <li > <div class="wrapper_el_projets"> <a href="" class="expandlink" onclick="return false"> <div class="projet_el_liste_haut"> <div class="hautgauche"> <img src="{{ asset('bundles/ecloreuser/images/projets/proj1.png') }}"></img></div> <div class="hautdroit"> <h2> <span>{{proj.projectName}} ({{proj.getPAByStatus('PENDING')|length + (proj.isFinished ? proj.getPAByStatus('VALIDATED')|length : 0)}} notifications)</span> </h2> <span class="soustitre"> <span>{{proj.getDuration}} jours, </span> <span>{{proj.address}}</span></br> <span>{{proj.shortDescription}}</span> </div> </div> <div class="projet_el_liste_bas"> <span>{{proj.description}}</span> </div> </a> </div> <a href="{{ path('assom_editProject', { 'id': proj.id }) }}"> Modifier ce projet </a> - <a href="{{ path('assom_manageProject', { 'id': proj.id }) }}"> Manager les candidatures </a> </li> </ul> {%endfor%} {%else%} Pas de projets pour l'instant...<a href="{{ path('assom_registerProject') }}"> Créer un projet! </a> {%endif%} </div> {% endblock %}<file_sep>/userBundle/Resources/views/Registration/register.html.twig {% extends "FOSUserBundle::layout.html.twig" %} {% block fos_user_content %} <h1> Inscription </h1> Bonjour ! Bienvenue sur le réseau Éclore. L'inscription est totalement gratuite et vous permet de candidater ou de déposer des projets associatifs. {% include "FOSUserBundle:Registration:register_content.html.twig" %} {% endblock fos_user_content %} <file_sep>/userBundle/Admin/AssociationAdmin.php <?php namespace eclore\userBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Show\ShowMapper; use eclore\userBundle\Form\ImageType; class AssociationAdmin extends Admin { // Fields to be shown on create/edit forms protected function configureFormFields(FormMapper $formMapper) { $headshot = $this->getSubject()->getHeadshot(); $fileFieldOptions = array('required'=>false, 'help'=>'Pas de photo'); if ($headshot && ($webPath = $headshot->getWebPath())) { $container = $this->getConfigurationPool()->getContainer(); $fullPath = $container->get('request')->getBasePath().'/'.$webPath; $fileFieldOptions['help'] = '<img src="'.$fullPath.'" class="admin-preview" />'; } $formMapper ->add('associationName') ->add('headshot', new ImageType(), $fileFieldOptions) ->add('description') ->add('location') ->add('members', 'entity', array('class'=>'ecloreuserBundle:AssociationMember', 'multiple'=>true, 'required'=>false)) ->add('projects', 'entity', array('class'=>'ecloreuserBundle:Project', 'multiple'=>true, 'required'=>false)) ; } // Fields to be shown on filter forms /*protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('associationName') ->add('description') ->add('location') ; }*/ // Fields to be shown on lists protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('associationName') ->add('description') ->add('location') ->add('members', 'entity', array('class'=>'ecloreuserBundle:AssociationMember', 'multiple'=>true, 'required'=>false)) ->add('projects', 'entity', array('class'=>'ecloreuserBundle:Project', 'multiple'=>true, 'required'=>false)) ->add('_action', 'actions', array( 'actions' => array( 'show' => array(), 'edit' => array(), 'delete' => array(), ) )) ; } protected function configureShowFields(ShowMapper $showMapper) { $showMapper ->add('associationName') ->add('headshot', 'entity', array('class'=>'ecloreuserBundle:Image', 'required' =>false, 'template' => 'ecloreuserBundle:Admin:show_headshot.html.twig')) ->add('description') ->add('location') ->add('members', 'entity', array('class'=>'ecloreuserBundle:AssociationMember', 'multiple'=>true, 'required'=>false)) ->add('projects', 'entity', array('class'=>'ecloreuserBundle:Project', 'multiple'=>true, 'required'=>false)) ; } }<file_sep>/userBundle/Resources/views/Timeline/verbs/mark_project.html.twig <li > <div class="iconeactu icone_avis" > </div> {{ timeline_component_render(timeline, 'subject') }} a évalué {{ timeline_component_render(timeline,'complement') }} </li><file_sep>/userBundle/Entity/NotificationRepository.php <?php namespace eclore\userBundle\Entity; use Doctrine\ORM\EntityRepository; /** * NotificationRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class NotificationRepository extends EntityRepository { public function findByReceiverAndType($user, $type) { $qb = $this->_em->createQueryBuilder(); $qb->select('n') ->from($this->_entityName, 'n') ->where('n.type = :type') ->setParameter('type', $type) ->join('n.receivers', 'r') ->andWhere($qb->expr()->in('r.id',$user->getId())) ->orderBy('n.initDate', 'DESC'); return $qb->getQuery()->getResult(); } public function findBySenderAndType($user, $type) { $qb = $this->_em->createQueryBuilder(); $qb->select('n') ->from($this->_entityName, 'n') ->where('n.type = :type') ->setParameter('type', $type) ->join('n.sender', 'r') ->andWhere('r.id = :id') ->setParameter('id', $user->getId()) ->orderBy('n.initDate', 'DESC'); return $qb->getQuery()->getResult(); } public function contactRequested($user1, $user2) { $rep = $this->_em->getRepository('ecloreuserBundle:Notification'); $ct_not_recby1 = $rep->findByReceiverAndType($user1, 'CONTACT'); $ct_not_recby2 = $rep->findByReceiverAndType($user2, 'CONTACT'); foreach($ct_not_recby1 as $ct_not) if($ct_not->getSender()->getId() == $user2->getId()) return True; foreach($ct_not_recby2 as $ct_not) if($ct_not->getSender()->getId() == $user1->getId()) return True; return False; } } <file_sep>/userBundle/Entity/Project.php <?php namespace eclore\userBundle\Entity; use Symfony\Component\Validator\ExecutionContextInterface; use JMS\Serializer\Annotation as Serializer; use JMS\Serializer\Annotation\Exclude; use JMS\Serializer\Annotation\Type; use Doctrine\ORM\Mapping as ORM; /** * Project * * @ORM\Table() * @ORM\Entity(repositoryClass="eclore\userBundle\Entity\ProjectRepository") */ class Project { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var integer * * @ORM\Column(name="required", type="integer") */ private $required; /** * @var string * * @ORM\Column(name="projectName", type="string", length=255) */ private $projectName; /** * @var boolean * @Exclude * @ORM\Column(name="enabled", type="boolean") */ private $enabled; /** * @var string * * @ORM\Column(name="description", type="text") */ private $description; /** * @var string * * @ORM\Column(name="shortDescription", type="text") */ private $shortDescription; /** * @ORM\ManyToMany(targetEntity="eclore\userBundle\Entity\AssociationMember", mappedBy="managedProjects") * @Exclude */ private $responsibles; /** * @var integer * * @ORM\Column(name="investmentRequired", type="integer") */ protected $investmentRequired; /** * @ORM\ManyToOne(targetEntity="eclore\userBundle\Entity\Association", inversedBy="projects") * @Serializer\Accessor(getter="getReducedAssociation") * @Type("array") */ private $association; /** * @ORM\OneToMany(targetEntity="eclore\userBundle\Entity\ProjectApplication", mappedBy="project") * @Serializer\Accessor(getter="getProjectApplicationsCount") * @Type("integer") */ private $projectApplications; /** * @var \DateTime * * @ORM\Column(name="startDate", type="date") * @Serializer\Accessor(getter="getStartDateTimestamp") * @Type("integer") */ private $startDate; /** * @var \DateTime * * @ORM\Column(name="endDate", type="date") * @Serializer\Accessor(getter="getEndDateTimestamp") * @Type("integer") */ private $endDate; /** * @ORM\ManyToOne(targetEntity="eclore\userBundle\Entity\ProjectLabels") */ private $labels; /** * @var string * * @ORM\Column(name="address", type="string", length=255) */ private $address; /** * @var string * * @ORM\Column(name="city", type="string", length=255) */ private $city; /** * @var string * * @ORM\Column(name="postcode", type="string", length=255, nullable=true) */ private $postcode; /** * @var string * * @ORM\Column(name="country", type="string", length=255, nullable=true) */ private $country; /** * @var string * * @ORM\Column(name="lat", type="string", length=255) */ private $lat; /** * @var string * * @ORM\Column(name="lng", type="string", length=255) */ private $lng; public function getProjectApplicationsCount() { return count($this->getPAByStatus('VALIDATED')); } public function getReducedAssociation() { return array('id'=>$this->getAssociation()->getId(), 'associationName'=>$this->getAssociation()->getAssociationName(), 'associationHeadshot'=>$this->getAssociation()->getHeadshotWebPath()); } public function getStartDateTimestamp() { return $this->getStartDate()->format('U'); } public function getEndDateTimestamp() { return $this->getEndDate()->format('U'); } public function getInvestmentRequired() { return $this->investmentRequired; } public function setInvestmentRequired($inv) { return $this->investmentRequired = $inv; } public function getPAByStatus($stat) { return $this->projectApplications->filter(function($p) use ($stat){return $p->getStatus()==$stat;}); } public function __construct() { $this->projectApplications = new \Doctrine\Common\Collections\ArrayCollection(); $this->responsibles = new \Doctrine\Common\Collections\ArrayCollection(); $this->enabled=False; } public function __toString() { return $this->getProjectName(); } public function hasResponsible($resp) {$data; foreach($this->getResponsibles() as $value) $data[]=$value->getId(); return in_array($resp->getId(), $data); } /** * Get id * * @return integer */ public function getId() { return $this->id; } public function getRequired() { return $this->required; } public function setRequired($required) { return $this->required = $required; } /** * Set projectName * * @param string $projectName * @return Project */ public function setProjectName($projectName) { $this->projectName = $projectName; return $this; } /** * Get projectName * * @return string */ public function getProjectName() { return $this->projectName; } public function setShortDescription($shortDescription) { $this->shortDescription = $shortDescription; return $this; } public function getShortDescription() { return $this->shortDescription; } /** * Set description * * @param string $description * @return Project */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set responsibles * * @param \eclore\userBundle\Entity\AssociationMember $responsible * @return Project */ public function addResponsible(\eclore\userBundle\Entity\AssociationMember $responsible) { $this->responsibles[] = $responsible; $responsible->addManagedProject($this); return $this; } /** * remove responsibles * * @param \eclore\userBundle\Entity\AssociationMember $responsible * @return Project */ public function removeResponsible(\eclore\userBundle\Entity\AssociationMember $responsible) { $this->responsibles->removeElement($responsible); return $this; } /** * Get responsible * * @return \stdClass */ public function getResponsibles() { return $this->responsibles; } /** * Set association * * @param \eclore\userBundle\Entity\Association $association * @return Project */ public function setAssociation(\eclore\userBundle\Entity\Association $association) { $this->association = $association; $association->addProject($this); return $this; } /** * Get association * * @return Association */ public function getAssociation() { return $this->association; } /** * Set startDate * * @param \DateTime $startDate * @return Project */ public function setStartDate($startDate) { $this->startDate = $startDate; return $this; } /** * Get startDate * * @return \DateTime */ public function getStartDate() { return $this->startDate; } /** * Set endDate * * @param \DateTime $endDate * @return Project */ public function setEndDate($endDate) { $this->endDate = $endDate; return $this; } /** * Get endDate * * @return \DateTime */ public function getEndDate() { return $this->endDate; } /** * Set labels * * @param \eclore\userBundle\Entity\ProjectLabels $labels * @return Project */ public function setLabels(\eclore\userBundle\Entity\ProjectLabels $labels) { $this->labels = $labels; return $this; } /** * Get labels * * @return \eclore\userBundle\Entity\ProjectLabels */ public function getLabels() { return $this->labels; } /** * Set address * * @param string $address * @return Project */ public function setAddress($address) { $this->address = $address; return $this; } /** * Get address * * @return string */ public function getAddress() { return $this->address; } /** * Add ProjectApplications * * @param eclore\userBundle\Entity\ProjectApplication $projectApplication */ public function addProjectApplication(\eclore\userBundle\Entity\ProjectApplication $projectApplication) { $this->projectApplications[] = $projectApplication; } /** * Remove ProjectApplications * * @param eclore\userBundle\Entity\ProjectApplication $projectApplication */ public function removeProjectApplication(\eclore\userBundle\Entity\ProjectApplication $projectApplication) { $this->projectApplications->removeElement($projectApplication); } /** * Get ProjectApplications * * @return array */ public function getProjectApplications() { return $this->projectApplications; } public function setCity($city) { $this->city = $city; return $this; } public function getCity() { return $this->city; } public function setCountry($country) { $this->country = $country; return $this; } public function getCountry() { return $this->country; } public function setPostcode($postcode) { $this->postcode = $postcode; return $this; } public function getPostcode() { return $this->postcode; } public function setLat($lat) { $this->lat = $lat; return $this; } public function getLat() { return $this->lat; } public function setLng($lng) { $this->lng = $lng; return $this; } public function getLng() { return $this->lng; } public function isFinished() { $today = new \DateTime(); return $today->format('U') > $this->getEndDate()->format('U'); } public function isStarted() { $today = new \DateTime(); return $today->format('U') >= $this->getStartDate()->format('U'); } /** * Set enabled * * @param boolean $enabled * @return Test */ public function setEnabled($enabled) { $this->enabled = $enabled; return $this; } /** * Get enabled * * @return boolean */ public function getEnabled() { return $this->enabled; } //validators public function isResponsiblesValid() { // vérifie si les responsables sont de la meme association foreach($this->getResponsibles() as $resp) if(!$resp->getAssociations()->contains($this->getAssociation())) return False; } public function isEndDateValid() { return $this->getEndDate()->format('U') >= $this->getStartDate()->format('U'); } public function getDuration() { return (int) ($this->getEndDate()->format('U') - $this->getStartDate()->format('U'))/86400; } public function isFull() { return count($this->getPAByStatus('VALIDATED')) >= $this->getRequired(); } } <file_sep>/userBundle/Admin/ProjectAdmin.php <?php namespace eclore\userBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Show\ShowMapper; use Sonata\AdminBundle\Validator\ErrorElement; class ProjectAdmin extends Admin { // Fields to be shown on create/edit forms protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('startDate', 'date', array( 'widget' => 'choice', 'years'=>range((int)date("Y")-50, (int)date("Y")+50))) ->add('endDate', 'date', array( 'widget' => 'choice', 'years'=>range((int)date("Y")-50, (int)date("Y")+50))) ->add('enabled', 'checkbox', array('required'=> false)) ->add('address') ->add('city') ->add('postcode', 'text', array('required'=> false)) ->add('country', 'text', array('required'=> false)) ->add('lat') ->add('lng') ->add('shortDescription') ->add('description') ->add('projectName') ->add('required') ->add('investmentRequired', 'choice', array('choices'=>$this->getConfigurationPool()->getContainer()->getParameter('investmentRequired'))) ->add('projectApplications', 'entity', array('class'=>'ecloreuserBundle:ProjectApplication', 'property'=>'id', 'multiple'=>true, 'required'=>false)) ->add('labels', 'entity', array('class' => 'eclore\userBundle\Entity\ProjectLabels')) ->add('responsibles', 'entity', array('class' => 'eclore\userBundle\Entity\AssociationMember', 'multiple'=>true)) ->add('association', 'entity', array('class' => 'eclore\userBundle\Entity\Association')) ; } // Fields to be shown on filter forms /*protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('startDate') ->add('endDate') ->add('location') ->add('description') ->add('projectName') ->add('labels', 'entity', array('class' => 'eclore\userBundle\Entity\ProjectLabels')) ->add('responsible', 'entity', array('class' => 'eclore\userBundle\Entity\AssociationMember')) ->add('association', 'entity', array('class' => 'eclore\userBundle\Entity\Association')) ; }*/ // Fields to be shown on lists protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('id') ->add('startDate') ->add('endDate') ->add('enabled') ->add('city') ->add('shortDescription') ->add('projectName') ->add('required') ->add('labels', 'entity', array('class' => 'eclore\userBundle\Entity\ProjectLabels')) ->add('responsibles', 'entity', array('class' => 'eclore\userBundle\Entity\AssociationMember')) ->add('association', 'entity', array('class' => 'eclore\userBundle\Entity\Association')) ->add('_action', 'actions', array( 'actions' => array( 'show' => array(), 'edit' => array(), 'delete' => array(), ) )) ; } protected function configureShowFields(ShowMapper $showMapper) { $showMapper->add('startDate', 'date') ->add('endDate', 'date') ->add('enabled') ->add('address') ->add('city') ->add('postcode') ->add('country') ->add('lat') ->add('lng') ->add('shortDescription') ->add('description') ->add('projectName') ->add('required') ->add('investmentRequired', 'choice', array('choices'=>$this->getConfigurationPool()->getContainer()->getParameter('investmentRequired'))) ->add('projectApplications', 'entity', array('class'=>'ecloreuserBundle:ProjectApplication', 'property'=>'id', 'multiple'=>true, 'required'=>false)) ->add('labels', 'entity', array('class' => 'eclore\userBundle\Entity\ProjectLabels')) ->add('responsibles', 'entity', array('class' => 'eclore\userBundle\Entity\AssociationMember', 'multiple'=>true)) ->add('association', 'entity', array('class' => 'eclore\userBundle\Entity\Association')) ; } } <file_sep>/userBundle/Controller/AdminController.php <?php namespace eclore\userBundle\Controller; use eclore\userBundle\Entity\User; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use eclore\userBundle\Timeline\TimelineEvents; use eclore\userBundle\Timeline\NewUserEvent; use eclore\userBundle\Timeline\NewProjectEvent; class AdminController extends Controller { public function indexAction() { $assoMs = $this->getDoctrine() ->getManager() ->getRepository('ecloreuserBundle:AssociationMember') ->findByRole('ROLE_TBC'); $instMs = $this->getDoctrine() ->getManager() ->getRepository('ecloreuserBundle:InstitutionMember') ->findByRole('ROLE_TBC'); $projects = $this->getDoctrine() ->getManager() ->getRepository('ecloreuserBundle:Project') ->findByEnabled(False); return $this->render('ecloreuserBundle:Admin:home.html.twig', array('assoMs'=>$assoMs, 'instMs'=>$instMs, 'projects'=>$projects)); } public function validateProfileAction($type, $id) { $formatted_type = 'InstitutionMember'; if($type=='AssoM')$formatted_type = 'AssociationMember'; $em = $this->getDoctrine()->getManager(); $profile = $em->getRepository('ecloreuserBundle:'.$formatted_type) ->find($id); if(!$profile || !$profile->getUser()->hasRole('ROLE_TBC')) { $this->get('session')->getFlashBag()->add( 'notice', 'Erreur: le profil est déjà validé ou n\'existe pas.'); } elseif($profile->getUser()->hasRole('ROLE_TBC')) { $profile->getUser()->removeRole('ROLE_TBC'); $this->get('session')->getFlashBag()->add( 'notice', 'Profil validé! L\'utilisateur a été averti.'); $em->persist($profile->getUser()); $em->flush(); //event dispatcher $event = new NewUserEvent($profile->getUser()); $this->container->get('event_dispatcher')->dispatch(TimelineEvents::onNewUser, $event); // Generate new token with new roles $token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken( $profile->getUser(), null, 'main', $profile->getUser()->getRoles() ); $this->container->get('security.context')->setToken($token); // Get the userManager and refresh user $userManager = $this->container->get('fos_user.user_manager'); $userManager->refreshUser($profile->getUser()); // send mail to user $profile->getUser()->getEmail(); } return $this->redirect($this->generateUrl('admin_page')); } public function validateProjectAction($id) { $em = $this->getDoctrine()->getManager(); $project = $em->getRepository('ecloreuserBundle:Project') ->find($id); if(!$project || $project->getEnabled()) { $this->get('session')->getFlashBag()->add( 'notice', 'Erreur: le projet est déjà validé ou n\'existe pas.'); } elseif(!$project->getEnabled()) { $project->setEnabled(True); $this->get('session')->getFlashBag()->add( 'notice', 'Projet validé! Le responsable a été averti.'); $em->flush(); // event dispatcher $event = new NewProjectEvent($project); $this->container->get('event_dispatcher')->dispatch(TimelineEvents::onNewProject, $event); } return $this->redirect($this->generateUrl('admin_page')); } } <file_sep>/userBundle/Timeline/PAEvent.php <?php namespace eclore\userBundle\Timeline; use Symfony\Component\EventDispatcher\Event; use eclore\userBundle\Entity\ProjectApplication; class PAEvent extends Event { protected $PA; public function __construct(ProjectApplication $PA) { $this->PA = $PA; } public function getPA() { return $this->PA; } }<file_sep>/userBundle/Controller/YoungController.php <?php namespace eclore\userBundle\Controller; use eclore\userBundle\Entity\User; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use eclore\userBundle\Entity\ProjectApplication; use eclore\userBundle\Entity\Notification; use eclore\userBundle\Entity\Action; use eclore\userBundle\Timeline\TimelineEvents; use eclore\userBundle\Timeline\MarkedEvent; use eclore\userBundle\Timeline\PAEvent; class YoungController extends Controller { public function displayHomeAction() { $user = $this->get('security.context')->getToken()->getUser(); //get timeline $actionManager = $this->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($user); $timelineManager = $this->get('spy_timeline.timeline_manager'); $timeline = $timelineManager->getTimeline($subject, array('page' => 1, 'max_per_page' => '10', 'paginate' => true)); return $this->render('ecloreuserBundle:Young:home.html.twig', array('timeline_coll'=>$timeline)); } public function applyAction($id) { $request = $this->getRequest(); $user = $this->get('security.context')->getToken()->getUser(); $em =$this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:Project'); $project = $repository->find($id); // verifie que le projet existe et n'est pas terminé. if(!$project || $project->isFinished() || !$project->getEnabled() || $project->isFull()) { $this->get('session')->getFlashBag()->add( 'notice', 'Ce projet n\'existe pas, est terminé, ou tu as déja candidaté!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } // verifie que $user a mis une evaluation a toutes ses candidatures if($user->getYoung()->getPAByStatus('TERMINATED')->count() > 0) { $this->get('session')->getFlashBag()->add( 'notice', 'Tu dois donner ton avis sur tes précédents projets avant de pouvoir candidater!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } // verifie que $user n'a pas deja candidaté if($user->getYoung()->hasApplied($project)) { $this->get('session')->getFlashBag()->add( 'notice', 'Tu as déjà candidaté à ce projet!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } //cree le formulaire $PA = new ProjectApplication(); $form = $this->createFormBuilder($PA) ->add('message', 'textarea') ->add('save', 'submit') ->getForm(); $form->handleRequest($request); if ($form->isValid()) { $PA->setYoung($user->getYoung()); $PA->setStatus('PENDING'); $PA->setStatusDate(new \DateTime); $PA->setProject($project); $this->getDoctrine()->getManager()->persist($PA); $this->getDoctrine()->getManager()->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'Ta candidature a bien été envoyée !'); // automatically connect young and project responsibles... TBC foreach($PA->getProject()->getResponsibles() as $resp) {$resp->getUser()->addContact($user); $user->addContact($resp->getUser()); $em->persist($resp->getUser()); } $em->persist($user); $em->flush(); // event dispatcher $event = new PAEvent($PA); $this->container->get('event_dispatcher')->dispatch(TimelineEvents::onNewPA, $event); return $this->redirect($this->generateUrl('ecloreuser_home')); } return $this->render('ecloreuserBundle:Young:apply.html.twig', array('proj'=>$project,'form' => $form->createView())); } public function manageApplicationAction($id) { $request = $this->getRequest(); $user = $this->get('security.context')->getToken()->getUser(); $em =$this->getDoctrine()->getManager(); $repository = $em->getRepository('ecloreuserBundle:ProjectApplication'); $PA = $repository->find($id); // verifie que la candidature concerne bien $user if(!$PA || $PA->getYoung()->getId() != $user->getYoung()->getId()) { $this->get('session')->getFlashBag()->add( 'notice', 'Cette candidature n\'existe pas ou ne te concerne pas!'); return $this->redirect($this->generateUrl('ecloreuser_home')); } //creation formulaire $recomm = new Notification(); $formbuilder = $this->createFormBuilder($recomm); $formbuilder->add('message', 'textarea') ->add('mark','submit'); $form = $formbuilder->getForm(); $form->handleRequest($request); if($form->isValid()) { $PA->setStatusDate(new \DateTime); $PA->setMessage($recomm->getMessage()); //cloture candidature coté jeune $PA->setStatus('MARKED'); // event dispatcher $event = new MarkedEvent($PA); $this->container->get('event_dispatcher')->dispatch(TimelineEvents::onMarkedProject, $event); // creation note $recomm->setSender($user); $recomm->setProject($PA->getProject()); foreach($PA->getProject()->getResponsibles() as $resp) $recomm->addReceiver($resp->getUser()); $recomm->setInitDate(new \DateTime()); $recomm->setType('MARK'); $em->persist($recomm); $em = $this->getDoctrine()->getManager(); $em->flush(); $this->get('session')->getFlashBag()->add( 'notice', 'Avis enregistré!'); } return $this->render('ecloreuserBundle:Young:manage-application.html.twig', array('pa'=>$PA,'form'=>$form->createView())); } } <file_sep>/userBundle/Timeline/NewProjectEvent.php <?php namespace eclore\userBundle\Timeline; use Symfony\Component\EventDispatcher\Event; use eclore\userBundle\Entity\Project; class NewProjectEvent extends Event { protected $project; public function __construct(Project $project) { $this->project = $project; } public function getProject() { return $this->project; } }<file_sep>/userBundle/Form/Type/RegistrationFormType.php <?php namespace eclore\userBundle\Form\Type; use Symfony\Component\Form\FormBuilderInterface; use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType; use eclore\userBundle\Form\ImageType; use Symfony\Component\DependencyInjection\Container; class RegistrationFormType extends BaseType { protected $container; public function __construct($user_class, Container $container) { parent::__construct($user_class); $this->container = $container; } public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder->add('birthDate', 'date', array( 'widget' => 'choice', 'years'=>range((int)date("Y")-100, (int)date("Y")), 'label' => 'Date de naissance :')) ->add('lastName' , 'text' , array('label' => 'Nom :') ) ->add('firstName' , 'text' , array('label' => 'Prénom :')) ->add('mobile' ,'text', array('label' => 'Numéro de téléphone : ')) ->remove('quality') ->add('privacyLevel', 'choice', array('choices'=>$this->container->getParameter('privacyLevels') , 'label' => 'Paramètres de confidentialité :')) ->add('headshot', new ImageType(), array('required'=>false , 'label' => 'Photo de profil : ')) ; } public function getName() { return 'eclore_user_registration'; } } ?><file_sep>/config.yml imports: - { resource: parameters.yml } - { resource: security.yml } - { resource: @ecloreuserBundle/Resources/config/services.yml } spy_timeline: paginator: ~ drivers: orm: object_manager: doctrine.orm.entity_manager classes: query_builder: ~ # Spy\TimelineBundle\Driver\ORM\QueryBuilder\QueryBuilder timeline: eclore\userBundle\Entity\Timeline action: eclore\userBundle\Entity\Action component: eclore\userBundle\Entity\Component action_component: eclore\userBundle\Entity\ActionComponent filters: data_hydrator: priority: 20 service: spy_timeline.filter.data_hydrator filter_unresolved: false locators: - spy_timeline.filter.data_hydrator.locator.doctrine_orm duplicate_key: ~ spread: on_subject: true # DEFAULT IS TRUE Spread each action on subject too on_global_context: true # Spread automatically on global context deployer: spy_timeline.spread.deployer.default delivery: immediate render: path: 'ecloreuserBundle:Timeline/verbs' framework: #esi: ~ translator: { fallback: "%locale%" } secret: "%secret%" router: resource: "%kernel.root_dir%/config/routing.yml" strict_requirements: ~ form: ~ csrf_protection: ~ validation: enabled: true api: 2.4 enable_annotations: true templating: engines: ['twig'] #assets_version: SomeVersionScheme default_locale: "%locale%" trusted_hosts: ~ trusted_proxies: ~ session: # handler_id set to null will use default session handler from php.ini handler_id: ~ fragments: ~ http_method_override: true # Twig Configuration twig: debug: "%kernel.debug%" strict_variables: "%kernel.debug%" # Assetic Configuration assetic: debug: "%kernel.debug%" read_from: "%kernel.root_dir%/../www" bundles: [ecloreuserBundle] #java: /usr/bin/java filters: cssrewrite: ~ #closure: # jar: "%kernel.root_dir%/Resources/java/compiler.jar" #yui_css: # jar: "%kernel.root_dir%/Resources/java/yuicompressor-2.4.8.jar" #yui_js: # jar: "%kernel.root_dir%/Resources/java/yuicompressor-2.4.8.jar" # Doctrine Configuration doctrine: dbal: driver: "%database_driver%" host: "%database_host%" port: "%database_port%" dbname: "%database_name%" user: "%database_user%" password: "%<PASSWORD>%" charset: UTF8 # if using pdo_sqlite as your database driver, add the path in parameters.yml # e.g. database_path: "%kernel.root_dir%/data/data.db3" # path: "%database_path%" orm: auto_generate_proxy_classes: "%kernel.debug%" auto_mapping: true # Swiftmailer Configuration swiftmailer: transport: "%mailer_transport%" host: "%mailer_host%" username: "%mailer_user%" password: "%<PASSWORD>%" spool: { type: memory } fos_user: db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel' firewall_name: main user_class: eclore\userBundle\Entity\User service: mailer: fos_user.mailer.twig_swift user_provider : fos_user.user_provider.username from_email: address: <EMAIL> sender_name: "<NAME>" profile: form: type: eclore_user_profile registration: form: type: eclore_user_registration confirmation: enabled: false template: ecloreuserBundle:Registration:email.html.twig resetting: token_ttl: 86400 email: template: ecloreuserBundle:Resetting:email.html.twig #Sonata Block Bundle sonata_block: default_contexts: [cms] blocks: sonata.admin.block.admin_list: contexts: [admin] sonata.block.service.text: ~ sonata.block.service.action: ~ sonata.block.service.rss: ~ sonata.block.service.overview: ~ sonata_admin: title: "Plateforme de gestion des enregistrements" #title_logo: ~ dashboard: blocks: # display a dashboard block - { position: left, type: sonata.admin.block.admin_list } - { position: right, type: sonata.block.service.overview } <file_sep>/userBundle/Resources/views/Young/projects.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite"> <h1> Mes projets </h1> <br> {% set pending = app.user.young.PAByStatus('PENDING') %} {% set validated = app.user.young.PAByStatus('VALIDATED') %} {% set rejected = app.user.young.PAByStatus('REJECTED') %} {% set terminated = app.user.young.PAByStatus('TERMINATED') %} {% set marked = app.user.young.PAByStatus('MARKED') %} {%if pending|length == 0 and validated|length == 0%} Vous n'avez pas encore candidaté à un projet. Vous pouvez chercher dans <a href="{{ path('ecloreuser_rechercherProjet') }}"> notre base de donnée </a> un projet associatif qui vous convienne. {%endif%} {%if pending|length > 0%} <div class="colquarter"> <h3> Candidatures en attente de réponse :</h3> <ul> {% for pa in pending %} <li><a href="{{ path('young_manage', { 'id': pa.id }) }}">{{pa.project}} ({{pa.project.association}})</a></li> {% endfor %} </ul> </div> {%else%} <!-- Pas de candidatures en attente de réponse. --> {%endif%} {%if terminated|length > 0%} <div class="colquarter"> <h3> Donne ton avis ! </h3> <ul> {% for pa in terminated %} <li><a href="{{ path('young_manage', { 'id': pa.id }) }}">{{pa.project}}</a></li> {% endfor %} </ul> </div> {%else%} <!-- Pas de projets en attente de notation de ta part. --> {%endif%} {%if marked|length > 0%} <div class="colquarter"> <h3> Projets terminés :</h3> <ul> {% for pa in marked %} <li><a href="{{ path('young_manage', { 'id': pa.id }) }}">{{pa.project}}</a></li> {% endfor %} </ul> </div> {%else%} <!-- Pas de projets terminés.--> {%endif%} {%if validated|length > 0%} <div class="colquarter"> <h3> Candidatures validées : </h3> <ul> {% for pa in validated %} <li><a href="{{ path('young_manage', { 'id': pa.id }) }}">{{pa.project}}</a></li> {% endfor %} </ul> </div> {%else%} <!-- Pas de candidatures validées.--> {%endif%} {%if rejected|length > 0%} <div class="colquarter"> <h3> Candidatures rejetées : </h3> <ul> {% for pa in rejected %} <li><a href="{{ path('young_manage', { 'id': pa.id }) }}">{{pa.project}}</a></li> {% endfor %} </ul> N'hésitez pas à contacter l'association pour demander des précisions. </div> {%else%} <!-- Pas de candidatures rejetées.--> {%endif%} </div> <div class="clearboth"></div> {% endblock %}<file_sep>/userBundle/Resources/views/Projects/show-project.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Rechercher un projet{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} <h1> {{proj}} </h1> <div class="soustitre"> Du {{proj.startdate|date("m-d-Y")}} au {{proj.enddate|date("m-d-Y")}}. {{proj.address}} </div> <div> {{proj.description}} </div> <div> Responsable du projet: {%for resp in proj.responsibles%}{{resp.user|printName}} {%endfor%}</div> <div> {%set validated = proj.PAByStatus('VALIDATED') %} {%set terminated = proj.PAByStatus('TERMINATED') %} {%set marked = proj.PAByStatus('MARKED') %} {%if (is_granted("IS_AUTHENTICATED_REMEMBERED") and app.user.hasRole('ROLE_YOUNG')) or not is_granted("IS_AUTHENTICATED_REMEMBERED")%} <a href="{{ path('young_apply',{'id': proj.id}) }}"> Candidater à ce projet!</a> {%endif%} {% if is_granted("IS_AUTHENTICATED_REMEMBERED") %} {% if date(proj.enddate) < date() %} Ce projet est terminé.<br> {{validated|length+terminated|length+marked|length}} participants. {%else%} </br></br> {% if validated|length+terminated|length+marked|length > 0 %} Jeunes inscrits à ce projet:<ul> {%for part in validated%} {%if part.young.user.privacyLevel != 2%} <li>{{part.young.user|printName}}</li> {%endif%} {%endfor%} </ul> {% endif%} {%endif%} {%else%} {{validated|length}} participants enregistrés. {% endif %} <br> </div> <div class="colgauche asideleft"> <div> <img src="{{app.request.basepath}}/{{ proj.association.getHeadshotWebPath }}" width='70%'> </div> <div> Projet porté par {{proj.association}} <br> <a href="{{ path('displayAsso',{'id': proj.association.Getid()}) }}"> Découvrir cette association </a> </div> </div> <div class="coldroite" style="padding-left:4em; width:60%;"> <h2> Action récentes liées à ce projets</h2> {% for action in timeline_coll %} {{ timeline_render(action) }}<br> {% endfor %} </div> <div class="clearboth"></div> {% endblock %} <file_sep>/userBundle/Controller/ProfileController.php <?php namespace eclore\userBundle\Controller; use eclore\userBundle\Entity\User; use eclore\userBundle\Entity\Album; use eclore\userBundle\Entity\Notification; use FOS\UserBundle\Controller\ProfileController as Controller; use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Event\FormEvent; use FOS\UserBundle\Event\FilterUserResponseEvent; use FOS\UserBundle\Event\GetResponseUserEvent; use FOS\UserBundle\Model\UserInterface; use Symfony\Component\DependencyInjection\ContainerAware; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\Util\StringUtils; use Symfony\Component\HttpFoundation\RedirectResponse; use eclore\userBundle\Timeline\TimelineEvents; use eclore\userBundle\Timeline\ContactAckEvent; use eclore\userBundle\Form\ImageType; use eclore\userBundle\Form\AlbumType; class ProfileController extends Controller { public function showAlbumsAction() { return $this->container->get('templating')->renderResponse('ecloreuserBundle:Profile:albums.html.twig'); } public function removeAlbumAction($id) { $em = $rep = $this->container->get('doctrine')->getManager(); $rep = $em->getRepository('ecloreuserBundle:Album'); $album = $rep->find($id); $user = $this->container->get('security.context')->getToken()->getUser(); if($album->getOwner()->getId() != $user->getId()) $this->container->get('session')->getFlashBag()->add( 'notice', 'Vous n\'êtes pas concerné par cet album!'); else { $em->remove($album); $em->flush(); $this->container->get('session')->getFlashBag()->add( 'notice', 'L\'album a été supprimé.'); } return new RedirectResponse($this->container->get('router')->generate('user_albums')); } public function removePicAction($id) { $em = $rep = $this->container->get('doctrine')->getManager(); $rep = $em->getRepository('ecloreuserBundle:Image'); $image = $rep->find($id); $user = $this->container->get('security.context')->getToken()->getUser(); if($image->getAlbum()->getOwner()->getId() != $user->getId()) $this->container->get('session')->getFlashBag()->add( 'notice', 'Vous n\'êtes pas concerné par cette image!'); else { $em->remove($image); $em->flush(); $this->container->get('session')->getFlashBag()->add( 'notice', 'L\'image a été supprimée.'); } return new RedirectResponse($this->container->get('router')->generate('user_albums')); } public function createAlbumAction(Request $request) { $user = $this->container->get('security.context')->getToken()->getUser(); $em = $this->container->get('doctrine')->getManager(); $album = new Album(); $form = $this->container->get('form.factory')->create(new AlbumType(), $album); if('POST' === $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $album->setOwner($user); $em->persist($album); $em->flush(); $this->container->get('session')->getFlashBag()->add( 'notice', 'L\'album a correctement été créé.'); return new RedirectResponse($this->container->get('router')->generate('user_albums')); } } return $this->container->get('templating')->renderResponse('ecloreuserBundle:Profile:create-album.html.twig', array('form'=> $form->createView())); } public function getAnnuaireAction() { $user = $this->container->get('security.context')->getToken()->getUser(); $rep = $this->container->get('doctrine') ->getManager() ->getRepository('ecloreuserBundle:Notification'); $contact_not = $rep->findByReceiverAndType($user, 'CONTACT'); $contact_send = $rep->findBySenderAndType($user, 'CONTACT'); return $this->container->get('templating')->renderResponse('ecloreuserBundle:Profile:annuaire.html.twig', array('contact_not'=>$contact_not, 'contact_send'=>$contact_send)); } public function getRecommendationsAction() { $user = $this->container->get('security.context')->getToken()->getUser(); $rep = $this->container->get('doctrine') ->getManager() ->getRepository('ecloreuserBundle:Notification'); $notType = 'MARK'; if($user->hasRole('ROLE_YOUNG'))$notType = 'RECOMMENDATION'; $recomm = $rep->findByReceiverAndType($user, $notType); return $this->container->get('templating')->renderResponse('ecloreuserBundle:Profile:recommendations.html.twig', array('recomm'=>$recomm)); } public function acknowledgeContactAction($id, $action) { $user = $this->container->get('security.context')->getToken()->getUser(); $em = $this->container->get('doctrine')->getManager(); $rep = $em->getRepository('ecloreuserBundle:Notification'); $contacts_not = $rep->findByReceiverAndType($user, 'CONTACT'); $contact_not; // recupere la contact_not foreach($contacts_not as $ct) if($ct->getId() == $id) $contact_not = $ct; // si la not n'existe pas if(!isset($contact_not)) { $this->container->get('session')->getFlashBag()->add( 'notice', 'Vous n\'êtes pas concerné par cette notification.'); } else{ if(StringUtils::equals($action, 'ack')){ $user2 = $contact_not->getSender(); $user->addContact($user2); $user2->addContact($user); $em->persist($user); $em->persist($user2); $this->container->get('session')->getFlashBag()->add( 'notice', 'Ce contact a été ajouté à votre annuaire.'); // event dispatcher $event = new ContactAckEvent($user2, $user); $this->container->get('event_dispatcher')->dispatch(TimelineEvents::onContactAck, $event); }else{ $this->container->get('session')->getFlashBag()->add( 'notice', 'Notification supprimée.'); } $em->remove($contact_not); $em->flush(); } return new RedirectResponse($this->container->get('router')->generate('user_annuaire')); } public function sendDemandAction($id) { $user = $this->container->get('security.context')->getToken()->getUser(); $em = $this->container->get('doctrine')->getManager(); $rep = $em->getRepository('ecloreuserBundle:User'); $user2 = $rep->find($id); $rep = $em->getRepository('ecloreuserBundle:Notification'); // si $user2 n'existe pas ou ets en mode invisible if(!$user2 || $user2->getPrivacyLevel() == 2) { $this->container->get('session')->getFlashBag()->add( 'notice', 'Cet utilisateur n\'existe pas!'); } //si une demande de contact existe deja entre les deux ou qu'ils sont deja contacts elseif($user->getContacts()->contains($user2) || $rep->contactRequested($user, $user2) || ($user->getId() == $user2->getId())) { $this->container->get('session')->getFlashBag()->add( 'notice', 'Cette personne est déjà dans vos contacts ou vous avez déjà une demande de contact en attente pour cette personne!'); } else { $not = new Notification(); $not->setType('CONTACT'); $not->setSender($user); $not->setMessage(''); $not->addReceiver($user2); $em->persist($not); $this->container->get('session')->getFlashBag()->add( 'notice', 'La demande a bien été envoyée.'); $em->flush(); } return new RedirectResponse($this->container->get('router')->generate('user_annuaire')); } public function removeContactAction($id) { $user = $this->container->get('security.context')->getToken()->getUser(); $em = $this->container->get('doctrine')->getManager(); $rep = $em->getRepository('ecloreuserBundle:User'); $user2 = $rep->find($id); // si $user2 n'existe pas if(!$user2) { $this->container->get('session')->getFlashBag()->add( 'notice', 'Cet utilisateur n\'existe pas!'); } //si user2 n'est pas contact de user elseif(!$user->getContacts()->contains($user2)) { $this->container->get('session')->getFlashBag()->add( 'notice', 'Cette personne n\'est pas dans vos contacts!'); } else { $user->removeContact($user2); $user2->removeContact($user); $em->persist($user); $em->persist($user2); $this->container->get('session')->getFlashBag()->add( 'notice', 'Contact supprimé.'); $em->flush(); } return new RedirectResponse($this->container->get('router')->generate('user_annuaire')); } public function editAction(Request $request) { $user = $this->container->get('security.context')->getToken()->getUser(); if (!is_object($user) || !$user instanceof UserInterface) { throw new AccessDeniedException('This user does not have access to this section.'); } /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */ $dispatcher = $this->container->get('event_dispatcher'); $event = new GetResponseUserEvent($user, $request); $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event); if (null !== $event->getResponse()) { return $event->getResponse(); } /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */ $formFactory = $this->container->get('fos_user.profile.form.factory'); $form = $formFactory->createForm(); if(!$user->hasRole('ROLE_YOUNG')&&!$user->hasRole('ROLE_INSTM')&&!$user->hasRole('ROLE_ASSOM')) $form->remove('quality'); $form->setData($user); if ('POST' === $request->getMethod()) { $form->bind($request); if ($form->isValid()) { /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */ $userManager = $this->container->get('fos_user.user_manager'); $event = new FormEvent($form, $request); $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event); $userManager->updateUser($user); $em = $this->container->get('doctrine')->getEntityManager(); $em->persist($user); $em->flush(); if (null === $response = $event->getResponse()) { $url = $this->container->get('router')->generate('fos_user_profile_show'); $response = new RedirectResponse($url); } $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response)); return $response; } } return $this->container->get('templating')->renderResponse( 'FOSUserBundle:Profile:edit.html.'.$this->container->getParameter('fos_user.template.engine'), array('form' => $form->createView()) ); } } <file_sep>/userBundle/Resources/public/js/lambda/anim_menu.js $(document).ready(function(){ // Unfolding the menu --------------------------------------- // We start by adding data to each node corresponding to the value they have to expand var menu1 = $("div[class*='menu'] ul li")[0]; var menu2 = $("div[class*='menu'] ul li")[1]; var menu3 = $("div[class*='menu'] ul li")[2]; //var menu4 = $("div[class*='menu'] ul li")[3]; $.data(menu1, 'taillef', {l: 8.9}); $.data(menu2, 'taillef', {l: 8.9}); $.data(menu3, 'taillef', {l: 8.9}); //$.data(menu4, 'taillef', {l: 11.4}); //$.data(menu1,'taillef').l; //When mouse rolls over $("div[class*='menu'] ul li:lt(3)").mouseover(function(){ $(this).stop().animate({height: $.data(this,'taillef').l +'em'},{queue:false, duration:600, easing: 'easeOutExpo'}) }); //When mouse is removed $("div[class*='menu'] ul li:lt(3)").mouseout(function(){ $(this).stop().animate({height:'2.5em'},{queue:false, duration:600, easing: 'easeOutExpo'}) }); $('<div class="hover"> </div>').appendTo($('div[class*="menu"] ul li h3~a')); //$('<li>Deuxième élément bis</li>').insertAfter($('li')); $('div[class*="menu"] ul li h3~a').hover( //Mouseover, fadeIn the hidden hover class function(){ $(this).children('div').stop(true,true).fadeIn('2000');}, //Mouseout, fadeOut the hover class function(){ $(this).children('div').stop(true,true).fadeOut('2000'); } ) ; });<file_sep>/userBundle/Resources/views/menu.html.twig <ul> <li> <h3> <a href="{{path('ecloreuser_homepage')}}">Accueil</a> </h3> <a href="{{path('ecloreuser_leReseau')}}" class="sousmenu"> <span>Qui sommes nous ? </span> </a> <a href="mailto:<EMAIL>" class="sousmenu"><span>Nous contacter</span> </a> </li> <li> <h3> <a href="#">Les projets</a> </h3> <a href="{{path('ecloreuser_rechercherProjet')}}" class="sousmenu"> <span>Rechercher un projet</span></a> {% if is_granted('IS_AUTHENTICATED_REMEMBERED') and app.user.hasRole('ROLE_ASSOM') %} <a href="{{path('assom_registerProject')}}" class="sousmenu"> <span>Proposer un projet</span></a> {%endif%} </li> <li><h3> <a href="#">Le réseau</a> </h3> <a href="{{path('displayNewsPost' , {'id': 1})}}" class="sousmenu"><span>Les actualités</span></a> <a href="{{path('ecloreuser_leReseau')}}" class="sousmenu"><span>Vie du réseau</span></a> <a href="{{path('ecloreuser_leReseau')}}" class="sousmenu"><span>Témoignages </span></a> </li> {%if is_granted('IS_AUTHENTICATED_REMEMBERED') %} <li> <h3><a href="{{path('ecloreuser_home')}}">Mon espace</a><h3> </li> <li> <h3><a href="{{path('fos_user_security_logout')}}">Déconnexion</a><h3> </li> {%else%} <li> <h3><a href="{{path('fos_user_registration_register')}}"> M'inscrire </a><h3> </li> <li> <h3><a href="{{path('fos_user_security_login')}}">Me connecter</a><h3> </li> {%endif%} </ul> <file_sep>/userBundle/Timeline/NewUserEvent.php <?php namespace eclore\userBundle\Timeline; use Symfony\Component\EventDispatcher\Event; use eclore\userBundle\Entity\User; class NewUserEvent extends Event { protected $user; public function __construct(User $user) { $this->user = $user; } public function getUser() { return $this->user; } }<file_sep>/userBundle/Resources/views/Static/statuts.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Le réseau Eclore{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} <h1> Nos statuts </h1> <h2> Article 1 - Constitution et dénomination </h2> Il est formé entre les adhérents aux présents statuts une association régie par la loi du 1er juillet 1901 et le décret du 16 août 1901, ayant pour titre « Réseau Éclore » (ci-après « l'association »). <h2>Article 2 - Objet</h2> L’association « Réseau Éclore » a pour objet de susciter et de faciliter l’investissement de jeunes dans les milieux associatifs et dans le développement de nouveaux projets. Pour cela, elle développe une connaissance des milieux associatifs et de leurs besoins, elle fait la promotion de l’engagement auprès de jeunes et les met en relation avec les associations et lanceurs de projet. Enfin, elle veille sur la nature de la collaboration réalisée, et accompagne les jeunes, y compris dans la valorisation de cette expérience. <h2>Article 3 - Siège social</h2> Le siège social est fixé à Ivry-sur-Seine. Il pourra être transféré sur simple décision du Conseil d'Administration. <h2>Article 4 - Durée de l'association</h2> La durée de l'association est illimitée. <h2>Article 5 - Composition </h2> L'association se compose de : </br> 1° - membres fondateurs ;</br> 2° - membres d'honneur ;</br> 3° - membres actifs ;</br> 4° - membres associés.</br></br> Tous participent à l’Assemblée générale.</br> Les membres fondateurs sont les personnes qui ont participé à la création de l’association. Ils sont dispensés du versement d’une cotisation. Ils disposent d’une voix délibérative aux assemblées générales et sont éligibles à toutes les instances.</br> Les membres d’honneur sont les personnes qui ont rendu des services signalés à l’association ou qui ont apporté une contribution financière ou matérielle importante à l’association. Ils sont dispensés du versement d’une cotisation. Ils disposent d’une voix consultative uniquement aux assemblées générales et ne sont pas éligibles.</br> Les membres actifs sont les personnes impliquées dans la vie de l’association. Ils versent une cotisation annuelle fixée par le Conseil d’administration. Ils disposent d’une voix délibérative aux assemblées générales et sont éligibles à toutes les instances.</br> Les membres associés sont les personnes physiques ou morales qui bénéficient des activités de l’association, sans s’impliquer de façon active dans sa gestion. Elles versent une cotisation annuelle fixée par le Conseil d’administration. Les personnes morales sont représentées par leur représentant légal ou toute autre personne dûment habilitée à cet effet. Elles disposent d’une voix consultative aux assemblées générales. Un certain nombre de sièges peut leur être réservé en conseil d’administration. <h2>Article 6 - Admission</h2> Pour être membre d'honneur ou membre actif, il faut être agréé par le Bureau qui statue lors de chacune de ses réunions sur les demandes d'adhésion présentées ainsi que sur la qualité de membre correspondante. En cas de refus, le Bureau n'a pas à motiver sa décision. Pour être membre associé, il faut être impliqué dans des projets de l’association. Le règlement intérieur précise les conditions de l’admission. <h2>Article 7 - Perte de la qualité de membre </h2> La qualité de membre se perd par :</br> 1°- la démission ;</br> 2° - le décès ;</br> 3° - le non-versement de la cotisation annuelle pour les membres actifs et pour les membres associés le cas échéant ;</br> 4° - la fin de l’implication dans des projets de l’association pour les membres associés, dans des conditions précisées par le règlement intérieur ;</br> 5° - la radiation prononcée par le Conseil d'administration pour motif grave, l'intéressé ayant été préalablement invité à fournir des explications au Conseil d'administration. Le non-respect des valeurs de l'association peut constituer un motif grave.</br> <h2>Article 8 - Ressources</h2> Les ressources de l’association comprennent :</br> - des cotisations annuelles des membres actifs et associés, et éventuellement de cotisations exceptionnelles de tout membre.</br> - des subventions allouées par l’État, les collectivités locales, les établissements publics ou tout tiers autorisé ;</br> - des dons manuels des personnes physiques et morales ;</br> - des produits des activités commerciales et manifestations liées à l'objet ;</br> - toute autre ressource autorisée par la loi.</br> <h2>Article 9 - Assemblée générale ordinaire</h2> L’assemblée générale ordinaire comprend tous les membres de l’association. L’assemblée générale ordinaire se réunit chaque année sur convocation du Conseil d'administration ou du quart des membres délibérants de l'association. Quinze jours au moins avant la date fixée, les membres de l’association sont convoqués par les soins du secrétaire, qui indique l'ordre du jour. </br> L'Assemblée entend les rapports sur la situation morale et financière de l'association et délibère. Elle ne délibère que sur les questions mises à l'ordre du jour et pourvoit s'il y a lieu au renouvellement des membres du Conseil d'administration. L'Assemblée délibère valablement quel que soit le nombre de membres présents. Tout membre de l'association peut s'y faire représenter par un autre en renseignant le pouvoir joint à la convocation. Le vote par correspondance n'est pas admis. Les décisions sont prises à main levée, à la majorité des suffrages exprimés par les membres présents ou représentés. Le scrutin secret peut être également demandé par au moins deux membres présents. <h2>Article 10 - Assemblée générale extraordinaire</h2> L'assemblée générale extraordinaire a seule compétence pour modifier les statuts, décider de la dissolution de l'association et de l'attribution des biens de l'association ou de sa fusion avec toute autre association poursuivant un but analogue. Elle doit être convoquée à la demande du Président ou à la demande de la moitié des membres ayant le droit de vote, suivant les modalités prévues par l'article 9. L'assemblée générale extraordinaire ne délibère valablement que si la moitié des membres ayant le droit de vote sont présents ou représentés. <h2>Article 11 - Le Conseil d'administration</h2> L'association est administrée par un Conseil. Le Conseil d'administration met en œuvre les orientations décidées par l'Assemblée générale ; il décide de la tenue des assemblées générales et en adopte, sur proposition du bureau, l'ordre du jour ; il prend la décision d'ester en justice pour la sauvegarde des intérêts de l'association. Le Conseil d'administration est composé :</br> 1° du bureau ;</br> 2° de représentants élus pour une durée de un an renouvelable en leur groupe respectivement par :</br> a) - les membres fondateurs et actifs ;</br> b) - les membres associés, pouvant être divisés en plusieurs sous-groupes, chaque sous-groupe élisant ses représentants ;</br> Le nombre de représentants élus de chaque catégorie est fixé par l’assemblée générale sur proposition du Bureau ;</br> 3° de personnes nommées par le conseil d'administration, sur proposition du président, et dans la limite de trois personnes, pour une durée de un an renouvelable.</br> </br> Le nombre d'administrateurs ne peut excéder quinze personnes. En cas de vacance de poste, le Conseil d'administration peut pourvoir provisoirement au remplacement de ses membres. Les pouvoirs des membres ainsi nommés prennent fin à l'époque où devait normalement expirer le mandat des membres remplacés. </br> Le Conseil d’administration se réunit autant de fois que l’intérêt de l’association l’exige et au moins à trois reprises dans l’année sur convocation du Président de l’association. Les convocations sont adressées au plus tard dix jours avant la réunion. Elles mentionnent l’ordre du jour de la réunion arrêté par le Président de l’association en accord avec le secrétaire de l’association. En cas d’urgence, dûment justifiée par le Président, le délai de convocation peut être ramené à cinq jours. Chaque administrateur dispose d’une voix délibérative. Tout administrateur absent ou empêché peut donner à un autre administrateur mandat de le représenter. Aucun membre ne peut être porteur de plus de un mandat, en sus du sien. Le Conseil d’administration délibère valablement en présence de la moitié de ses membres présents ou représentés. Les décisions sont prises à la majorité des suffrages exprimés des membres présents ou représentés. En cas de partage des voix, celle du président est prépondérante. </br> Si l’association a moins de deux ans d’existence ou si le nombre de ses membres ne dépasse pas 30, l’assemblée générale peut décider de ne pas élire de Conseil d’administration. Dans ce cas, le Bureau assume les responsabilités du Conseil d’administration. Cette décision doit être renouvelée à chaque nouvelle assemblée générale. <h2>Article 12 - Le Bureau</h2> Le Bureau assure le fonctionnement permanent de l'association et décide des actions de l'association à engager dans le cadre des orientations définies par le Conseil d'administration. Le Bureau est élu en bloc par l'Assemblée générale pour une durée de un an renouvelable. Le Bureau est composé de, au minimum :</br> 1° - un Président ;</br> 2° - un Trésorier ;</br> 3° - un Secrétaire.</br> Le nombre de membres du Bureau ne peut excéder dix personnes. </br></br> PRÉSIDENT Le président du Bureau est chargé d'exécuter les décisions du Bureau et d’assurer le bon fonctionnement de l’association. Il représente l’association dans tous les actes de la vie civile et est investi de tous les pouvoirs à cet effet. Il a notamment qualité pour agir en justice au nom de l'association. Le Président convoque les assemblées générales et les réunions du Bureau.</br> Il fait ouvrir et fonctionner au nom de l’association, auprès de toute banque ou tout établissement de crédit, tout compte. Il peut déléguer à un autre membre ou à un permanent de l’association certains des pouvoirs ci-dessus énoncés. </br></br> TRÉSORIER Le trésorier est chargé de la gestion de l’association. Il perçoit les recettes, effectue les paiements, sous le contrôle du président. Il tient une comptabilité régulière de toutes les opérations et rend compte à l’assemblée générale qui statue sur la gestion. Comme le président, il fait ouvrir et fonctionner au nom de l’association, auprès de toute banque ou tout établissement de crédit, tout compte. </br></br> SECRÉTAIRE Le secrétaire est chargé de tout ce qui concerne la correspondance et les archives. Il rédige les procès-verbaux de réunions des assemblées et du Conseil d’administration et en assure la transcription sur les registres, notamment le registre spécial prévu par la loi et le registre des délibérations. Il est en charge, en général, de toutes les écritures concernant le fonctionnement de l’association, à l’exception de celles qui concernent la comptabilité. </br></br> En cas de vacance, le Bureau pourvoit provisoirement au remplacement du ou des membres parmi les membres éligibles de l’association. Le remplacement définitif des membres ainsi cooptés intervient à la plus proche assemblée générale et leurs pouvoirs prennent fin durant cette même assemblée générale. Le Bureau se réunit au moins une fois tous les six mois et aussi souvent que l’intérêt de l’association l’exige, sur convocation du Président ou à la demande de au moins deux membres du Bureau. Tout membre du Bureau qui, sans excuse, n’aura pas assisté à trois réunions consécutives, pourra être considéré comme démissionnaire. La présence de la moitié des membres est nécessaire pour la validité des délibérations. Si ce quorum n’est pas atteint, le Bureau est à nouveau convoqué à quelques jours d’intervalle et peut alors délibérer quel que soit le nombre de membres présents ou représentés. Les décisions sont prises à la majorité des voix ; en cas de partage, la voix du président est prépondérante. Le secrétaire décide des règles de vote au sein du Bureau. <h2>Article 13 - Valeurs de l'association</h2> Les valeurs de l'association sont :</br> 1°- l’entraide ;</br> 2°- le respect ;</br> 3°- la fraternité ;</br> 4°- le dialogue ;</br> 5°- la gratuité.</br> <h2>Article 14 – Règlement Intérieur</h2> Un règlement intérieur peut être établi par le bureau qui le fait alors soumettre à l’assemblée générale. Ce règlement éventuel est destiné à fixer les divers points non prévus par les statuts notamment ceux relatifs à l’administration interne de l’association. <h2>Article 15 – Dissolution</h2> La dissolution de l'association est prononcée par l'Assemblée générale convoquée spécialement à cet effet. En cas de dissolution, l’Assemblée générale extraordinaire désigne un ou plusieurs liquidateurs qui seront chargés de la liquidation des biens de l’Association et dont elle détermine les pouvoirs. L’actif net subsistant sera obligatoirement attribuée à une ou plusieurs associations poursuivant des buts similaires et qui seront nommément désignées par l’Assemblée générale extraordinaire, conformément à l'article 9 de la loi du 1er juillet 1901 et au décret du 16 août 1901. {% endblock %}<file_sep>/userBundle/Resources/config/services.yml parameters: # ecloreuser.example.class: eclore\userBundle\Example services: eclore.twig.extension: class: eclore\userBundle\Extensions\Twig\templateFunctionsHelper arguments: [@service_container, @security.context] tags: - { name: twig.extension } ecloreuser.image_type_extension: class: eclore\userBundle\Form\Extension\ImageTypeExtension tags: - { name: form.type_extension, alias: file } ecloreuser.admin.album: class: eclore\userBundle\Admin\AlbumAdmin tags: - { name: sonata.admin, manager_type: orm, group: "Entités", label: "Album" } arguments: [~, eclore\userBundle\Entity\Album, SonataAdminBundle:CRUD] calls: - [ setTranslationDomain, [ecloreuserBundle]] ecloreuser.admin.project: class: eclore\userBundle\Admin\ProjectAdmin tags: - { name: sonata.admin, manager_type: orm, group: "Entités", label: "Projets" } arguments: [~, eclore\userBundle\Entity\Project, SonataAdminBundle:CRUD] calls: - [ setTranslationDomain, [ecloreuserBundle]] ecloreuser.admin.projectlabels: class: eclore\userBundle\Admin\ProjectLabelsAdmin tags: - { name: sonata.admin, manager_type: orm, group: "Entités", label: "Labels de projets" } arguments: [~, eclore\userBundle\Entity\ProjectLabels, SonataAdminBundle:CRUD] calls: - [ setTranslationDomain, [ecloreuserBundle]] ecloreuser.admin.projectapplication: class: eclore\userBundle\Admin\ProjectApplicationAdmin tags: - { name: sonata.admin, manager_type: orm, group: "Entités", label: "Candidatures" } arguments: [~, eclore\userBundle\Entity\ProjectApplication, SonataAdminBundle:CRUD] calls: - [ setTranslationDomain, [ecloreuserBundle]] eclore_user.registration.form.type: class: eclore\userBundle\Form\Type\RegistrationFormType arguments: [%fos_user.model.user.class%, @service_container] tags: - { name: form.type, alias: eclore_user_registration } eclore_user.profile.form.type: class: eclore\userBundle\Form\Type\ProfileFormType arguments: [%fos_user.model.user.class%, @service_container] tags: - { name: form.type, alias: eclore_user_profile } ecloreuser.admin.associationmember: class: eclore\userBundle\Admin\AssociationMemberAdmin tags: - { name: sonata.admin, manager_type: orm, group: "Profils", label: "AssociationMember" } arguments: [~, eclore\userBundle\Entity\AssociationMember, SonataAdminBundle:CRUD] calls: - [ setTranslationDomain, [ecloreuserBundle]] ecloreuser.admin.institutionmember: class: eclore\userBundle\Admin\InstitutionMemberAdmin tags: - { name: sonata.admin, manager_type: orm, group: "Profils", label: "InstitutionMember" } arguments: [~, eclore\userBundle\Entity\InstitutionMember, SonataAdminBundle:CRUD] calls: - [ setTranslationDomain, [ecloreuserBundle]] ecloreuser.admin.institution: class: eclore\userBundle\Admin\InstitutionAdmin tags: - { name: sonata.admin, manager_type: orm, group: "Groupes", label: "Institution" } arguments: [~, eclore\userBundle\Entity\Institution, SonataAdminBundle:CRUD] calls: - [ setTranslationDomain, [ecloreuserBundle]] ecloreuser.admin.association: class: eclore\userBundle\Admin\AssociationAdmin tags: - { name: sonata.admin, manager_type: orm, group: "Groupes", label: "Association" } arguments: [~, eclore\userBundle\Entity\Association, SonataAdminBundle:CRUD] calls: - [ setTranslationDomain, [ecloreuserBundle]] ecloreuser.admin.user: class: eclore\userBundle\Admin\UserAdmin arguments: [~, eclore\userBundle\Entity\User, SonataAdminBundle:CRUD] tags: - {name: sonata.admin, manager_type: orm, group: "Membres", label: User} ecloreuser.admin.young: class: eclore\userBundle\Admin\YoungAdmin arguments: [~, eclore\userBundle\Entity\Young, SonataAdminBundle:CRUD] tags: - {name: sonata.admin, manager_type: orm, group: "Profils", label: "Jeune"} ecloreuser.admin.notification: class: eclore\userBundle\Admin\NotificationAdmin arguments: [~, eclore\userBundle\Entity\Notification, SonataAdminBundle:CRUD] tags: - {name: sonata.admin, manager_type: orm, group: "Entités", label: "Notifications"} ecloreuser.admin.image: class: eclore\userBundle\Admin\ImageAdmin arguments: [~, eclore\userBundle\Entity\Image, SonataAdminBundle:CRUD] tags: - {name: sonata.admin, manager_type: orm, group: "Entités", label: Image} sonata.block.service.overview: class: eclore\userBundle\Block\overviewBlockService arguments: ["sonata.block.service.overview", @templating, @doctrine.orm.entity_manager] tags: - {name: sonata.block, } spy_timeline.timeline_spread: class: eclore\userBundle\Timeline\TimelineSpread arguments: [@service_container] tags: - {name: spy_timeline.spread} ecloreuser.timeline_listener: class: eclore\userBundle\Timeline\TimelineListener arguments: [@service_container] tags: - { name: kernel.event_listener, event: ecloreuser.timeline.contact_ack, method: onContactAck } - { name: kernel.event_listener, event: ecloreuser.timeline.validated_PA, method: onValidatedPA } - { name: kernel.event_listener, event: ecloreuser.timeline.new_PA, method: onNewPA } - { name: kernel.event_listener, event: ecloreuser.timeline.rejected_PA, method: onRejectedPA } - { name: kernel.event_listener, event: ecloreuser.timeline.new_project, method: onNewProject } - { name: kernel.event_listener, event: ecloreuser.timeline.marked_young, method: onMarkedYoung } - { name: kernel.event_listener, event: ecloreuser.timeline.marked_project, method: onMarkedProject } - { name: kernel.event_listener, event: ecloreuser.timeline.new_user, method: onNewUser } - { name: kernel.event_listener, event: ecloreuser.timeline.pending_validation, method: onPendingValidation } ecloreuser.admin.news_post: class: eclore\userBundle\Admin\NewsPostAdmin arguments: [~, eclore\userBundle\Entity\NewsPost, SonataAdminBundle:CRUD] tags: - {name: sonata.admin, manager_type: orm, group: admin, label: NewsPost} <file_sep>/userBundle/Controller/ProjectsController.php <?php namespace eclore\userBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class ProjectsController extends Controller { public function rechercherAction() { $request = $this->container->get('request'); if($request->isXmlHttpRequest()) { $projects = $this->getDoctrine() ->getManager() ->createQuery('select p FROM ecloreuserBundle:Project p WHERE p.endDate > :date AND p.enabled = :enabled') ->setParameter('date', new \DateTime()) ->setParameter('enabled', true) ->getResult(); $serializer = $this->container->get('jms_serializer'); $response = new Response(); $response->setContent($serializer->serialize($projects, 'json')); $response->headers->set('Content-Type', 'application/json'); return $response; /* [{"id":1,"project_name":"sdfgdsg","description":"sdrgsdg", "association":{"id":1,"associationName":"banqure alim"}, "project_applications":0,"start_date":"2014-01-01T00:00:00+0000","end_date":"2017-01-01T00:00:00+0000", "labels":{"id":1,"name":"social"},"address":"Aix-en-Provence, France","city":"Aix-en-Provence", "country":"France","lat":"43.529742","lng":"5.4474270000000615"}] */ }else { $repository = $this->getDoctrine() ->getManager() ->getRepository('ecloreuserBundle:ProjectLabels'); $labels = $repository->findAll(); return $this->render('ecloreuserBundle:Projects:rechercher.html.twig'); } } public function showProjectAction($id) { $repository = $this->getDoctrine() ->getManager() ->getRepository('ecloreuserBundle:Project'); $project = $repository->find($id); //get timeline $actionManager = $this->get('spy_timeline.action_manager'); $subject = $actionManager->findOrCreateComponent($project); $timelineManager = $this->get('spy_timeline.timeline_manager'); $timeline = $timelineManager->getTimeline($subject, array('page' => 1, 'max_per_page' => '10', 'paginate' => true)); return $this->render('ecloreuserBundle:Projects:show-project.html.twig', array('proj'=>$project, 'timeline_coll'=>$timeline)); } } <file_sep>/userBundle/Resources/views/Profile/recommendations.html.twig {% extends "ecloreuserBundle::page_lambda.html.twig" %} {% block title %}Espace membre{% endblock %} {%set color='vert'%} {%set first='Mon Éclore'%} {%set second='Espace personnel'%} {% block content %} {%include "ecloreuserBundle::menu_user.html.twig"%} <div class="coldroite"> <h1> Mes recommandations </h1> {%if app.user.hasRole('ROLE_YOUNG')%} Ces recommandations sont visibles par les responsables des projets auxquels vous postulez. N'hésitez pas à les utiliser également hors du réseau Eclore ! <br><br> {%endif%} {%if recomm|length>0 %} {% for rec in recomm %} <h2> Recommandation de {{rec.sender}} en date du {{rec.initDate|date('m/d/Y')}}. </h2> <div class="soustitre">{{rec.project}}</div> {{rec.message}} {%endfor%} {%else%} Pas encore de recommandations. {%endif%} </div> <div class="clearboth"></div> {% endblock %}
a248e675b26b8b64211eaaf210634223aebd18d3
[ "Twig", "YAML", "JavaScript", "PHP", "CSS" ]
104
Twig
Luc-Darme/source_symfony
f3549d63c144fa47cbcb79bcc696977bcfda027a
9b132682efe97c18d0378d9e2f2ad5593e0293c1
refs/heads/master
<file_sep>/** * Paper Card (pseudo) */ .card display: block position: relative background: $white border-radius: 2px margin: 0 0 $base-spacing padding: $base-spacing @extend %shadow h2 margin-bottom: $base-spacing @media screen and (min-width: 800px) margin: 1vh auto width: 75% @media screen and (min-width: 1200px) margin: 1vh auto width: 50%<file_sep>const initialState = { loading: false, scroll: 0 } export default (state = initialState, action) => { // console.log(action) // console.log(state) switch (action.type) { case 'LOADING': return Object.assign({}, state, { loading: true }) case 'NOT_LOADING': return Object.assign({},state,{ loading: false }) case 'SAVESCROLL': return Object.assign({},state,{ scroll: action.scroll }) default: return state } } <file_sep>.btn text-align: right text-transform: small-caps a color: $black padding: 10px margin: 13px border: 1px solid $black border-radius: 5px cursor: pointer a:hover color: $white background: $black padding: 10px margin: 13px border: 1px solid $white border-radius: 5px cursor: pointer <file_sep>/** * `Home` Page Component */ .page__home ul padding-left: 2 * $base-spacing .content display: block .url float: right line-height: 3em .logo display: inline-block width: 10% height: 2em object-fit: contain // float: right .read float: left width: 49% display: inline-block .small font-size: 0.8em display: inline-block width: 50% text-align: right .card min-height: 110px display: block .refresh-background background-color: #D91E36 width: 50px height: 50px border-radius: 50% position: fixed bottom: 5% right: 5% cursor: pointer .refresh line-height: 50px color: white // padding: 14px transform: translateX(12.5px) img width: 110% max-height: 110px // border-radius: 3px // float: right // right: 1% // top: 1% // position: absolute object-fit: cover display: block margin: $base-unit auto // max-width: 60 * $base-spacing // 960 img.loader width: 100px height: auto display: block margin: 10vh auto position: relative <file_sep>const initialState = { articles: [], sources: [], remoteSources: [] } export default (state = initialState, action) => { // console.log(action) // console.log(state.articles[action.id]) // let sources switch (action.type) { case 'LOADED': let newArticles = action.articles.sort((a,b)=>{ if (new Date(a.publishedAt) < new Date(b.publishedAt)) return 1 if (new Date(a.publishedAt) > new Date(b.publishedAt)) return -1 return 0 }) // console.log('LOADED NEWS') return Object.assign({}, state,{ articles: newArticles }) case 'CLEAR': return { articles: [] } case 'ADD SOURCE': let sources = state.sources.concat([action.source]) // console.log('added source', sources) return Object.assign({}, state, { sources }) case 'REMOVE SOURCE': sources = state.sources.filter(source=>source!==action.source) // console.log('removed source', sources) return Object.assign({}, state, { sources }) case 'LOAD REMOTE SOURCES': return Object.assign({}, state, { remoteSources: action.remoteSources }) case 'READ': let readArticles = state.articles.map((article, index)=>{ if(index === action.id){ article['read'] = true return article }else{ return article } }) return Object.assign({}, state, { articles: readArticles }) default: // console.log('DEFAULT NEWS'); return state } } <file_sep>/** * `Article` Page Component */ .page__settings .logo-container display: flex justify-content: center flex-wrap: wrap .logo width: 120px height: 120px object-fit: contain align-self: center margin: 5px padding: 10px border-radius: 5px .glow box-shadow: 0px 0px 10px #3fb0ac <file_sep>require("babel-polyfill"); import { render } from 'preact'; import 'whatwg-fetch'; import './index.sass'; let elem, App; function init() { App = require('./views').default; elem = render(App, document.getElementById('root'), elem); } init(); if (process.env.NODE_ENV === 'production') { // cache all assets if browser supports serviceworker require('offline-plugin/runtime').install(); if ('serviceWorker' in navigator && location.protocol === 'https:') { // navigator.serviceWorker.register('/service-worker.js'); } // add Google Analytics (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-X', 'auto'); ga('send', 'pageview'); } else { // use preact's devtools require('preact/devtools'); // listen for HMR if (module.hot) { module.hot.accept('./views', init); } } <file_sep>/** * `Article` Page Component */ .page__article h1 text-transform: capitalize margin-bottom: $base-spacing small display: block text-indent: $base-spacing font-size: 65% opacity: 0.65 font-style: italic .back, p display: block margin-bottom: $base-spacing img display: block margin: 10px auto border-radius: 5px width: 33% height: auto @media screen and (min-width: 800px) margin: 1vh auto width: 75% @media screen and (min-width: 1200px) margin: 1vh auto width: 50% @media screen and (max-width: 320px) img width: 80% height: auto @media screen and (max-width: 540px) img width: 80% height: auto <file_sep>// Ya need sum cawfee! If yous know what im sayin! Spoken like a tru New Yorka. 'use strict' const admin = require('firebase-admin'); const fetch = require('node-fetch'); const {NEWSAPI_KEY, MERCURY_KEY, FB_URL} = require('./secrets.json'); const serviceAccount = require('./sa.json'); // const serviceAccount = JSON.parse(SA) admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://newscraper-21f8a.firebaseio.com" }) const database = admin.database(); database.ref('/news').set({}); //fetch sources in a promise const fetchSources = () => new Promise(resolve => { fetch(`https://newsapi.org/v2/sources?country=us&language=en&apiKey=${NEWSAPI_KEY}`) .then(r=>r.json()) .then(data=>resolve(data.sources.map(source=> source.id))); }); const fetchHeadlines = source => new Promise(resolve => { fetch(`https://newsapi.org/v2/top-headlines?pageSize=100&sources=${source}&apiKey=${NEWSAPI_KEY}`) .then(r=>r.json()) .then(data=>resolve(data.articles)); }); const scrapeContent = article => new Promise(resolve => { let options = { headers: { 'x-api-key': MERCURY_KEY } } fetch(`https://mercury.postlight.com/parser?url=${article.url}`,options) .then(r=>r.json()) .then(data=> { article['content'] = data['content']; article['word_count'] = data['word_count']; resolve(article); }) .catch(err=>{ console.log(err); resolve(article); }) }); //take advantage of the async await cycle to //avoid callback hell async function worker(){ let sources = await fetchSources(); console.log('SOURCES', sources.length); let articles = { length: 0 }; console.log('Working on it...'); for(let i=0; i < sources.length; i++) { console.log('trying', sources[i]); let tempArticles = await fetchHeadlines(sources[i]); console.log(tempArticles.length); if(!tempArticles) continue; console.log('scraping...'); let scrapedArticles = []; for(let j=0; j < tempArticles.length; j++) { let tempArticle = tempArticles[j]; tempArticle = await scrapeContent(tempArticle); if (tempArticle['content']) { scrapedArticles.push(JSON.stringify(tempArticle)); } } articles[sources[i]] = scrapedArticles; articles.length += articles[sources[i]].length; } database.ref('/news').set(articles) .then(snap=>{ console.log(articles.length, ' items set!'); process.exit(); }) .catch(r=>console.log(r)); } worker(); <file_sep>/** * Nav / Header */ $header-height: 10 * $base-unit .home-button left: 0 float: left .cog-button right: 0 float: right .header position: absolute height: $header-height width: 100% padding: 0 top: 0 left: 0 right: 0 background: $primary @extend %shadow z-index: 50 .material-icons font-size: 36px transform: translateY(13px) h1 // position: absolute margin: 0 auto padding: 0 $base-spacing font-size: 24px line-height: $header-height font-weight: 400 color: $white nav font-size: 100% a position: absolute top: 0 display: inline-block height: $header-height line-height: $header-height padding: 0 $base-spacing text-align: center min-width: 50px background: rgba($white, 0) will-change: background-color text-decoration: none color: $offwhite &:hover, &:active background: rgba($white, 0.3) @media screen and (max-width: 401px) nav a padding: 0 $base-spacing/2 min-width: $base-spacing*2 @media screen and (max-width: 321px) h1 font-size: 18px <file_sep>import { take, call, put, takeEvery, takeLatest } from 'redux-saga/effects'; //BAD SCOPING IDK. TODO OPTIMIZE let articles = [] let sources = [] let userSources = [] export function* helloSaga() { // console.log('Hello Sagas!'); } export async function fetchSources(){ // console.log('in fetch sources'); let returnData; await fetch('https://newsapi.org/v1/sources?language=en&country=us').then(r=>r.json()).then(data=> returnData = data); // console.log(returnData); return returnData.sources; } export async function fetchNews(source){ // console.log('in fetch'); let returnData; await fetch('https://newscraper-21f8a.firebaseio.com/news/'+source+'.json').then(r=>r.json()).then(data=> returnData = data); let transformedArticles = []; if (returnData) transformedArticles = returnData.map(d=>JSON.parse(d)); return transformedArticles; } export function* loadSources() { // console.log('in the saga for loading news'); // yield put({type: 'LOADING'}) try { sources = yield fetchSources(); yield put({ type: 'LOAD REMOTE SOURCES', remoteSources: sources}) }catch(e){ // console.log(e) } } export function* loadNews(action) { // console.log('got it'); yield put({type: 'LOADING'}); try{ // console.log('this far'); articles = [] userSources = [].concat(action.sources); // console.log(articles); while (userSources.length > 0 ){ articles = articles.concat(yield fetchNews(userSources.pop())) } yield put({type: 'LOADED', articles}); yield put({type: 'NOT_LOADING'}); } catch(e){ console.log(e); yield put({type: 'NOT_LOADING'}); } } export function* watchLoadNews(){ yield takeLatest('LOAD', loadNews); yield takeLatest('LOAD SOURCES', loadSources); } export default function* rootSaga() { yield [ helloSaga(), watchLoadNews() ] } <file_sep>// Worker ants are proud of this file. 'use strict' const admin = require('firebase-admin') const request = require('request') const {NEWSAPI_KEY, MERCURY_KEY, FB_URL} = require('./secrets.json') const serviceAccount = require('./sa.json') // const serviceAccount = JSON.parse(SA) admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://newscraper-21f8a.firebaseio.com" }) const database = admin.database(); database.ref('/news').set({}) //fetch sources request.get(`https://newsapi.org/v2/sources?country=us&language=en&apiKey=${NEWSAPI_KEY}`, (err, response, data) => { data = JSON.parse(data) let sourcelist = data.sources.map(source=> source.id); let final = {length: 0} console.log(sourcelist.length, "SOURCES") request.get(`https://newsapi.org/v2/top-headlines?pageSize=100&sources=${sourcelist.toString()}&apiKey=${NEWSAPI_KEY}`, (err, response, body) => { let data = JSON.parse(body) console.log(data.totalResults, "RESULTS") data.articles.map((article, articlesIndex) => { let options = { url: `https://mercury.postlight.com/parser?url=${article.url}`, headers: { 'x-api-key': MERCURY_KEY } } request.get(options, (err, response, scraped) => { article['content'] = JSON.parse(scraped)['content'] let tmpArticle = JSON.stringify(article); if (final[article.source.id]) { final[article.source.id].push(tmpArticle); } else { final[article.source.id] = [tmpArticle]; } final.length++; if (final.length === data.articles.length) { database.ref('/news').set(final) .then(snap=>{ console.log('set!'); process.exit(); }).catch(r=>console.log(r)); console.log(final.length, "ITEMS") } }) }) }) }) <file_sep># NewScraper 2.0 ![screen](screenshot.png) Progressive web app for reading fresh news offline in the **subway** from various news sources. Open [NewScraper 2.0](https://newscraper.surge.sh) on your phone and add it to your homescreen to see the magic! ## Tech Stack - [Webtask](https://webtask.io) - [Preact-JS Starter](https://github.com/lukeed/preact-starter) - For this awesome offline ready boilerplate. [Preact](https://preactjs.com/) Isn't that different from React, it only weighs 3KB! - [The News Api](http://newsapi.org) - Awesome news aggregation api. I'll definitely expand this app to take full advantage of the many sources here. - [Mercury Api](https://mercury.postlight.com/web-parser/) - Amazing time saver, it goes and builds a _readable_ version of whatever article you supply it. _Think pocket/instapaper._ ## Running/Deploying #### Installation - `git clone` to clone this repo. - `npm install` (or `yarn` if you're hip like me). #### Running Locally - Make sure you have the `MERCURY_KEY` and `NEWS_API` keys in the file called `secrets.json`. - If you're working on the worker, save your firebase-admin sevice account as `sa.json`. - `npm run watch` #### Deploying - Run `npm run build`, this will spit out the production front-end in `dist` for you to serve on static hosting. ## To-Do - More news sources. √ - Loading bar because I'm masochistic? _(I heard they were super hard.)_ - Transitions between views. - Refine service worker, to make it more reliable. √ - Style for iOS devices (Ew! But needed for dumb iPhone X). <file_sep>import { h } from 'preact'; export default function (props) { return <div className="card">{ props.children }</div> } <file_sep>import { h } from 'preact'; import Card from '../tags/card'; const links = [{ name: 'lukeed/preact-starter', desc: 'A Webpack2 starter for building SPA / PWA / offline front-end apps with Preact', href: 'https://github.com/lukeed/preact-starter' }, { name: 'developit/preact', desc: 'Fast 3kb React alternative with the same ES6 API. Components & Virtual DOM.', href: 'https://www.npmjs.com/package/preact' }, { name: 'developit/preact-router', desc: 'URL router for Preact.', href: 'https://www.npmjs.com/package/preact-router' }, { name: 'webpack/webpack', desc: 'A bundler for javascript and friends. Allows for code splitting & asynchronous lazy-loading.', href: 'https://github.com/webpack/webpack' }, { name: 'FormidableLabs/webpack-dashboard', desc: 'A CLI dashboard for webpack-dev-server', href: 'https://github.com/FormidableLabs/webpack-dashboard' }, { name: 'zeit/now', desc: 'Free (OSS) realtime global deployments', href: 'https://zeit.co/now' }, { name: 'zeit/serve', desc: 'Single-command HTTP directory listing and file serving', href: 'https://github.com/zeit/serve' }]; export default function (props) { return ( <div className="page page__credit"> <Card> <h1>Credits:</h1> <p>Resources used within boilerplate:</p> </Card> <nav> { links.map(obj => <a className="card" href={ obj.href } target="_blank" rel="noopener"> <strong>{ obj.name }</strong> <em>{ obj.desc }</em> </a> ) } </nav> </div> ) } <file_sep>import { h } from 'preact'; import { Link } from 'preact-router'; import Card from '../tags/card'; import Button from '../tags/button'; import CardLink from '../tags/card-link'; import {connect} from 'react-redux' import timeago from 'timeago.js'; const mapStateToProps = state =>({ news: state.news.articles, sources: state.news.sources, ui: state.ui }) const mapDispatchToProps = dispatch =>({ load: (sources)=> { // console.log('map state') dispatch({type: 'LOAD', sources}) }, read: id=> dispatch({type: 'READ', id: id}), saveScroll: ()=> dispatch({type: 'SAVESCROLL', scroll: window.scrollY}) }) const Home = ({ui,news, sources, load, saveScroll, read}) => { console.log(sources) setTimeout(()=>window.scrollTo(0,ui.scroll),50) const imgError = e =>{ e.target.style.display = "none" } if(ui.loading){ return ( <div className="page page__home"> <div className="loader-container"> <br/> <center><h2>This takes a bit, hold onto your socks <br/>( ͡° ͜ʖ ͡°)</h2></center> <img className="loader" src="/img/loader.gif" alt="loading" /> </div> </div> ) }else{ return ( <div className="page page__home"> {news.length == 0 ? <div> <h2>Hey! Welcome to my app! <br/></h2> <p> <b>Newscraper</b> is an app for reading news from popular news sources offline.</p> <p>You should add it to your homescreen for the best experience!</p> <br/> <center> <h3> <Link href="/settings">Pick your favorite sources!</Link> </h3> </center> </div> : <h2>Latest News <br/></h2> } {news.map((article,index)=>{ //only return lengthy things, helps filter out weird stuff from hacker news if (article.content && article.content.length < 100) return null return( <CardLink href={ `/article/${index}`}> <div onClick={()=>{read(index);saveScroll()}} className="content"> <p class="url small">{article.url.split("/")[2]}</p> <img class="logo" onError={imgError} src={"//logo.clearbit.com/"+article.url.split("/")[2]} /> <h3>{article.title}</h3> {article.urlToImage ? <img onError={e=>e.target.src = "/img/na.jpg"} src={"//api.rethumb.com/v1/square/300/"+article.urlToImage} /> : <img src="/img/na.jpg" /> } <p>{article.description}</p> <p className="read">{article['read'] ? '✅' : ''}</p> <p className="small">{ timeago().format(new Date(article.publishedAt)) }</p> </div> </CardLink> ) })} <br /> <div onClick={()=>load(sources)} class="refresh-background"> <i class="refresh material-icons nav-icon md-36">refresh</i> </div> <br /> </div> ) } } export default connect(mapStateToProps,mapDispatchToProps)(Home) <file_sep>import { h } from 'preact'; import { Link } from 'preact-router'; export default function (props) { return ( <div className='btn'> <a onClick={props.callback}> {props.name} </a> </div> ) } <file_sep>/** * Reusable values */ $purple: #34465d $black: #173e43 $offwhite: md-color('grey', '100') $white: #FFF $primary: $purple $base-unit: 6px $base-spacing: 2 * $base-unit <file_sep>import { h } from 'preact'; import { Link } from 'preact-router'; const extraHeader = () => { if(navigator.userAgent.includes('iPhone')||navigator.userAgent.includes('iPad')){ return ( { height: '72px', paddingTop: '12px' } ) }else{ return {} } } export default function () { return ( <header style={extraHeader()} className="header"> <h1 className="center">NewScraper 2.0</h1> <nav> <Link class="home-button" href="/"><i class="material-icons nav-icon md-36">home</i></Link> <Link class="cog-button" href="/settings"><i class="material-icons nav-icon md-36">settings</i></Link> </nav> </header> ) } <file_sep>import { h } from 'preact'; import { Link } from 'preact-router'; import Card from '../tags/card'; import {connect} from 'react-redux' const mapStateToProps = state =>({ sources: state.news.sources, remoteSources: state.news.remoteSources }) const mapDispatchToProps = dispatch =>({ addSource: (source)=> { dispatch({type: 'ADD SOURCE', source}) }, removeSource: (source)=> { dispatch({type: 'REMOVE SOURCE', source}) }, loadSources: ()=> dispatch({type: 'LOAD SOURCES'}) }) // const sources = fetchSources().sources // const categories = {} // sources.map(source=>{ // categories[source.category] = '' // }) // categories = Object.keys(categories) const Settings = ({addSource, removeSource, loadSources, sources, remoteSources}) => { // <---- (props) let checkButton; remoteSources.length == 0 ? loadSources() : checkButton = true; const imgError = e =>{ e.target.style.display = "none" } return ( <div className="page page__settings"> <div class="logo-container"> {remoteSources.map(item=> sources.indexOf(item.id) >= 0 ? <img onClick={()=>removeSource(item.id)} class="logo glow" onError={imgError} src={"//logo.clearbit.com/"+item.url.split("/")[2]} /> : <img onClick={()=>addSource(item.id)} class="logo" onError={imgError} src={"//logo.clearbit.com/"+item.url.split("/")[2]} /> )} </div> </div> ) } export default connect(mapStateToProps, mapDispatchToProps)(Settings)
ff6b2081ed8bd94a80820c01b20cf81b55d31d95
[ "Markdown", "Sass", "JavaScript" ]
20
Markdown
fizal619/newscraper-pwa
319312218e0f8b5bb7571e4ccb2c437a24ea9345
cced0c08781439226d8c594f7cff8703c42c894d
refs/heads/master
<file_sep>libsvm-csharp ============= Public source of C# implementation of libsvm by <NAME> http://www.matthewajohnson.org/
9be23329a0cd716abc14a6bb441b55f01f544047
[ "Markdown" ]
1
Markdown
Termina1/libsvm-csharp
ed79b74a8ee8670a2b50bbe3246dc3c930a0c8f1
a560f9e64c0b1d216e132104871ab98658a043a9
refs/heads/master
<repo_name>jwodder/botw-checklist<file_sep>/Makefile checklist.pdf : checklist.tex pdflatex checklist.tex pdflatex checklist.tex checklist.tex : mklist.py checklist.json python3 mklist.py clean : rm -f *.aux *.log checklist.tex <file_sep>/mklist.py #!/usr/bin/env python3 from collections import defaultdict from contextlib import redirect_stdout from itertools import groupby import json from operator import itemgetter import re WEAPON_SPACE_START = 9 WEAPON_SPACE_MAX = WEAPON_SPACE_START + 11 BOW_SPACE_START = 5 BOW_SPACE_MAX = BOW_SPACE_START + 8 SHIELD_SPACE_START = 4 SHIELD_SPACE_MAX = SHIELD_SPACE_START + 16 with open('checklist.json') as fp: data = json.load(fp) def classify(iterable, field): classed = defaultdict(list) for obj in iterable: classed[obj[field]].append(obj) return classed shrines_by_region = classify(data["shrines"], 'region') for v in shrines_by_region.values(): v.sort(key=itemgetter("name")) quests_by_region = classify(data["side_quests"], 'region') for v in quests_by_region.values(): v.sort(key=itemgetter("name")) with open('checklist.tex', 'w') as fp, redirect_stdout(fp): print(r''' \documentclass[10pt]{article} \usepackage{amssymb} \usepackage{bbding} \usepackage{enumitem} \usepackage[margin=1in]{geometry} \usepackage{longtable} \usepackage{multicol} \usepackage{tikz} \newcommand{\dlc}{\emph} \newcommand{\amiibo}{\emph} \newsavebox\ltmcbox \raggedcolumns \makeatletter \newlength{\chest@width} \setlength{\chest@width}{1em} \newlength{\chest@height} \setlength{\chest@height}{\dimexpr\chest@width*618/1000\relax} \newlength{\chest@roundness} \setlength{\chest@roundness}{\dimexpr\chest@width/5\relax} \newlength{\chest@latchsize} \setlength{\chest@latchsize}{\dimexpr\chest@width/5\relax} \newlength{\chest@latchHeight} \setlength{\chest@latchHeight}{\dimexpr\chest@height/2\relax} \newcommand{\chest}{ \tikz{ \draw (0,0) [rounded corners=\chest@roundness] -- (0, \chest@height) -- (\chest@width, \chest@height) [sharp corners] -- (\chest@width, 0) -- (0,0); \node (latch) at (\dimexpr\chest@width/2, \chest@latchHeight) [circle,minimum width=\chest@latchsize,inner sep=0,draw] {}; \draw ( 0, \chest@latchHeight) -- (latch.west); \draw (\chest@width, \chest@latchHeight) -- (latch.east); } } \makeatother \begin{document} ''') print(r'\begin{multicols}{2}') print(r'\section*{Main Quests}') print(r'\begin{itemize}[label=$\square$]') for quest in data["main_quests"]: print(r'\item', quest) for quest in data["dlc_main_quests"]: print(r'\item \dlc{', quest, '}', sep='') print(r'\end{itemize}') print(r'\columnbreak') print(r'\section*{Recovered Memories}') print(r'\begin{itemize}[label=$\square$]') for i, mem in enumerate(data["memories"], start=1): print(r'\item ', i, '. ', mem, sep='') print(r'\end{itemize}') print(r'\end{multicols}') for region in data["regions"]: print(r'\section*{' + region["tower"] + ' Region}') print(r'\begin{itemize}[label=$\square$]') print(r'\item Activate', region["tower"]) print(r'\end{itemize}') if quests_by_region[region["name"]]: print(r'\begin{multicols}{2}') print(r'\subsection*{Shrines}') else: print(r'\begin{multicols}{2}[\subsection*{Shrines}]') print(r'\begin{itemize}[label=$\square$\thinspace\protect\chest]') for shrine in shrines_by_region[region["name"]]: if not shrine["dlc"]: print(r'\item {name} \emph{{({trial})}}'.format(**shrine)) if shrine["quest"] is not None: print(r'\begin{itemize}[label=$\square$]') print(r'\item Shrine Quest:', shrine["quest"]) print(r'\end{itemize}') print(r'\end{itemize}') if quests_by_region[region["name"]]: print(r'\columnbreak') print(r'\subsection*{Side Quests}') print(r'\begin{itemize}[label=$\square$]') for quest in quests_by_region[region["name"]]: print(r'\item', quest["name"]) print(r'\end{itemize}') print(r'\end{multicols}') assert all((quest["region"] is None) == quest.get("dlc", False) for quest in data["side_quests"]) print(r'\section*{DLC Side Quests}') print(r'\begin{itemize}[label=$\square$]') for quest in quests_by_region[None]: print(r'\item \dlc{', quest["name"], '}', sep='') print(r'\end{itemize}') print(r'\newpage') print(r'\begin{multicols}{2}[\section*{Enhance Armor}]') # <https://tex.stackexchange.com/a/46001/7280> print(r'\setbox\ltmcbox\vbox{\makeatletter\col@number\@ne') print(r'\begin{longtable}{r|ccccc}') boxes = r' & $\square$' + r' & \FiveStarOpen' * 4 + r'\\' armor_sets = classify(data["enhanceable_armor"], 'set') ### TODO: Sort by headgear name instead of set name: for aset in sorted(k for k in armor_sets.keys() if k is not None): chest,head,legs = sorted(armor_sets[aset], key=itemgetter("body_part")) if chest["amiibo"]: pre, post = r'\amiibo{', '}' else: pre, post = '', '' print(pre, head["name"], post, boxes, sep='') print(pre, chest["name"], post, boxes, sep='') print(pre, legs["name"], post, boxes, sep='') print(r'\hline') for armor in sorted(armor_sets[None], key=itemgetter("name")): if armor["amiibo"]: print(r'\amiibo{', armor["name"], '}', boxes, sep='') else: print(armor["name"], boxes, sep='') print(r'\end{longtable}') print(r'\unskip\unpenalty\unpenalty}\unvbox\ltmcbox') print(r'\end{multicols}') max_spaces = max(WEAPON_SPACE_MAX, BOW_SPACE_MAX, SHIELD_SPACE_MAX) print(r'\section*{Expand Inventory}') print(r'\begin{tabular}{r|', r'@{\enskip}'.join('c' * max_spaces), '}', sep='') for i in range(1, max_spaces+1): print('&', i, end='') print(r'\\ \hline') for label, start, maxxed in [ ('Weapons', WEAPON_SPACE_START, WEAPON_SPACE_MAX), ('Bows', BOW_SPACE_START, BOW_SPACE_MAX), ('Shields', SHIELD_SPACE_START, SHIELD_SPACE_MAX), ]: print(label, '& --' * start, r'& $\square$' * (maxxed - start), '& ' * (max_spaces - maxxed), r'\\') print(r'\end{tabular}') print(r'\section*{Overworld Mini-bosses}') for sg, pl, key, species in [ ('Hinox', 'Hinoxes', 'hinoxes', 'Hinox'), ('Talus', 'Taluses', 'taluses', 'Stone Talus'), ('Molduga', 'Moldugas', 'moldugas', 'Molduga'), ]: print(r'\subsection*{', pl, '}', sep='') print(r'\begin{itemize}[label=$\square$]') for boss in data[key]: ### TODO: Sort print(r'\item', boss["region"], '---', boss["display_location"]) if boss["species"] != species: m = re.fullmatch( r'{} \((.+)\)'.format(re.escape(species)), boss["species"], ) if m: print('(', m.group(1), ')', sep='') else: print('(', boss["species"], ')', sep='') print(r'\item Get Medal of Honor:', sg, 'from Kilton') print(r'\end{itemize}') print(r'\section*{Other}') print(r'\begin{itemize}[label=$\square$]') for other in data["other"]: print(r'\item', other["name"]) print(r"\item Find dogs' buried treasures:") print(r'\begin{itemize}[label=$\square$]') for dog in data["dogs"]: print(r'\item', dog["location"]) if dog.get("item_qty"): print(r'({item} $\times {item_qty}$)'.format_map(dog)) else: print(r'({item})'.format_map(dog)) print(r'\end{itemize}') print(r'\end{itemize}') print(r'\newpage') print(r'\section*{Hyrule Compendium}') print(r'\begin{multicols}{2}') for section, entries in groupby(data["compendium"], itemgetter("section")): print(r'\subsection*{', section, '}', sep='') print(r'\begin{itemize}[label=$\square$]') for e in entries: number = e["dlc_number"] master = e["dlc_master_number"] name = e["name"] if number is None: number = '---' name = r'\textbf{' + e["name"] + '}' else: number = str(number).rjust(3, '~') if e["number"] is None: name = r'\dlc{' + e["name"] + '}' print(r'\item ', number, r'/\textbf{', master, '}. ', name, sep='') print(r'\end{itemize}') print(r'\end{multicols}') ### TODO: DLC shrines print(r'\end{document}')
29c57c8d78f4ada821aa8749e428654a16862350
[ "Makefile", "Python" ]
2
Makefile
jwodder/botw-checklist
dc2640447819d03ef55789ba481aac9a5f2ce823
0293ddfd7fc5a6d293a1c5c3cdac983e213fa219
refs/heads/master
<file_sep>#define the model of the dataset or it is python dict configuration file SWARM_DESCRIPTION = { "includedFields": [ #information regarding the fields { "fieldName": "timestamp", "fieldType": "datetime" }, { "fieldName": "kw_energy_consumption", "fieldType": "float", "maxValue": 53.0, "minValue": 0.0 } ], "streamDef": { #defines fro where the input is coming from "info": "kw_energy_consumption", "version": 1, "streams": [ { "info": "Rec Center", "source": "file://rec-center-hourly.csv",#source file i.e csv file "columns": [ "*" #all the columns ] } ] }, "inferenceType": "TemporalMultiStep",#type of prediction "inferenceArgs": { "predictionSteps": [#how many steps of future we want to predict 1 ], "predictedField": "kw_energy_consumption"#field which is to be predicted }, "iterationCount": -1,#-1 indicates all rows 1 indicates 1 row "swarmSize": "medium"#small is for debugging medium is fine large takes a lot of time and evaluates more models } <file_sep># htm-NuPIC- Machine learning using HTM <file_sep>from nupic.frameworks.opf.modelfactory import ModelFactory from model_params import model_params from nupic.data.inference_shifter import InferenceShifter import nupic_output import datetime import csv DATE_FORMAT = "%m/%d/%y %H:%M" def createModel(): print("executing") model = ModelFactory.create(model_params.MODEL_PARAMS) model.enableInference({ "predictedField": "kw_energy_consumption" }) return model def runModel(model): print("executing") inputFilePath = "rec-center-hourly.csv" inputFile = open(inputFilePath, "rb") csvReader = csv.reader(inputFile) csvReader.next() csvReader.next() csvReader.next() shifter = InferenceShifter() output = nupic_output.NuPICPlotOutput(["Rec Center"]) counter = 0 for row in csvReader: counter += 1 if counter % 100 == 0: print("Read %i lines ..."%counter) timestamp = datetime.datetime.strptime(row[0], DATE_FORMAT) consumption = float(row[1]) result = model.run({ "timestamp": timestamp, "kw_energy_consumption": consumption }) result = shifter.shift(result) prediction = result.inferences["multiStepBestPredictions"][1] output.write([timestamp], [consumption], [prediction]) inputFile.close() output.close() def runHotGym(): print("executing") model = createModel() runModel(model) if __name__ == "__main__": runHotGym()
fcb5de11bab5218a9173896bdc83b714dda049b4
[ "Markdown", "Python" ]
3
Markdown
nattesharan/htm-NuPIC-
4ffc010bbb1f73e944158a5051248c3fdc9341fc
188838b9d4aaf14ffe0fbb87cc8b0052d43ad950
refs/heads/master
<file_sep>from copy import deepcopy from .visualization import Visualization from .data import Data from .values import ValueRef from .properties import PropertySet from .scales import DataRef, Scale from .marks import MarkProperties, MarkRef, Mark from .axes import Axis try: import pandas as pd except ImportError: pd = None try: import numpy as np except ImportError: np = None # TODO: list of factories: # - line # - bar # - stairs # - stem # - pie # - area # - polar # - rose # - compass # - box # - semilog / loglog # - hist # - contour # - scatter # - map class BarFactory(object): def __init__(self, x_scale=None, y_scale=None, mark=None, width=None, height=None): if x_scale: self.x_scale = x_scale else: self.x_scale = Scale( name='x', range='width', type='ordinal', domain=DataRef(data='table', field='data.x')) if y_scale: self.y_scale = y_scale else: self.y_scale = Scale( name='y', range='height', type='linear', nice=True, domain=DataRef(data='table', field='data.y')) if mark: self.mark = mark else: self.mark = Mark( type='rect', from_=MarkRef(data='table'), properties=MarkProperties( enter=PropertySet( x=ValueRef(scale='x', field='data.x'), y=ValueRef(scale='y', field='data.y'), width=ValueRef(scale='x', band=True, offset=-1), y2=ValueRef(scale='y', value=0)), update=PropertySet(fill=ValueRef(value='steelblue')))) self.width = width or 400 self.height = height or 200 self.padding = {'top': 10, 'left': 30, 'bottom': 20, 'right': 10} self.x_axis = Axis(type='x', scale='x') self.y_axis = Axis(type='y', scale='y') def __call__(self, x, y, color=None, make_copies=True): vis = Visualization(width=self.width, height=self.height, padding=self.padding) vis.data.append(Data.from_iters(x=x, y=y)) if make_copies: maybe_copy = deepcopy else: maybe_copy = lambda x: x vis.scales.extend(maybe_copy([self.x_scale, self.y_scale])) vis.axes.extend(maybe_copy([self.x_axis, self.y_axis])) vis.marks.extend(maybe_copy([self.mark])) if color: vis.marks[0].properties.update.fill.value = color return vis @property def color(self): return self.mark.properties.update.fill.value @color.setter def color(self, value): self.mark.properties.update.fill.value = value
6b8c8eb9b5ffe7075ec4a7c99f9a952d7060271e
[ "Python" ]
1
Python
gauden/vincent
50262c7f26c6396cda324c5491d83ed1ebc6949e
b896d4c237c1964489a52012fc16b6e60b7e527a
refs/heads/main
<repo_name>dangpham3040/Dubaothoitiet<file_sep>/settings.gradle include ':app' rootProject.name = "Dubaothoitiet"
a10211020ee61de78d434e9f360590d74bc2df9b
[ "Gradle" ]
1
Gradle
dangpham3040/Dubaothoitiet
eb589b2d555df6ae48ac9d1a7201fa69ddcd5001
c1a0bb05d4257e5a621c51c0caf082680d5ea29d
refs/heads/master
<repo_name>jaeyoungchun/singularity-test-repos<file_sep>/README.md # singularity-test-repos Test repositories for Singularity binary images - bwa - samtools NOTE: you might need `git lfs` for big files.<file_sep>/.gitattributes images/bwa.img filter=lfs diff=lfs merge=lfs -text images/samtools.img filter=lfs diff=lfs merge=lfs -text
47511fefd860c99a70eca23e95a5bbf9af0c0e25
[ "Git Attributes", "Markdown" ]
2
Git Attributes
jaeyoungchun/singularity-test-repos
aac44ed5db2b89d674ae7795d66091c1b28ea6ea
9104f07e3d4fe1ef7f205d73efafa8de0ee92ad8
refs/heads/master
<file_sep># 达令 ------------------- [TOC] ## 达令介绍 >达令™是一家专注于全球好货的电商APP,与海外300多家知名品牌直接签约,商品都是全职买手从世界各地搜罗来的精品好货 —— [达令](https://baike.baidu.com/item/%E8%BE%BE%E4%BB%A4/17543007?fr=aladdin) ###技术栈 >vue2 + vuex + vue-router + webpack + ES6 ### 项目运行 >#####克隆到本地 git clone https://github.com/LImengna123/daling.git >##### 安装依赖 npm install >#####开启本地服务器localhost:8080 npm run dev >##### 发布环境 npm run build
d0d833b32548c4f6827c4e5ed4473c71e1eca9df
[ "Markdown" ]
1
Markdown
LImengna123/daling
02c0a0211c1a7c49ecd7690f70151307f31744e8
488b2d707d0624230f1b731a4ae4bdad743b176e
refs/heads/master
<file_sep>package gall.api; import gall.impl.Image; import java.util.Set; /** * Created by W on 13.06.2014. */ public interface GalleryDAO { void setGalleryExisting(String login); void removeAll(int id); String searchForGallery(String login); int putImg(int userId, String imgFilePath); Set<Image> getAllImg(int userId); Image viewImg(int imgId); } <file_sep><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <html> <head> <link rel="stylesheet" type="text/css" href="http://localhost:8080/css/main.css"> </head> <body> <title>${message}</title> <div id="container" style="height:768px;width:1024px"> <div id="banner" style="background-image:url('http://localhost:8080/img/title.gif');height:90px;width:1024px;"> <br> <b style="color:grey;" >Welcome <b class="white"> ${login} </b> ! <a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/user_info"><img class="icon_1" src='http://localhost:8080/img/home.gif' alt="Home" title="Home"></a> <a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/logOut"><img class="icon_1" src='http://localhost:8080/img/logOut.gif' alt="Log Out" title="Log Out"></a> <a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/remove"><img class="icon_1" src='http://localhost:8080/img/delete.gif' alt="Remove Account" title="Remove Account"></a> </b> </div> <div id="user_inf" style="background-color:#F5FFFA;height:628px;width:444px;float:left;" ><br> <div class="border_1"><br> <form name="edit_information" action="edit" method="POST"> <b style="color:grey;">User information: </b><br><br> <label><span>Name: </span><input type="text" name="name" value=${name}></label> <label><span>Surname: </span><input type="text" name="surname" value=${surname}></label> <label><span>Category: </span><input type="text" name="cat" value= ${category} readonly> </label> <label><span> </span> <label><select name="category" style="width:152px;font-family:arial;color:grey;Font-size:12px;"> <option>All</option> <option>IT</option> <option>Graphic Design</option> <option>Architecture</option> <option>Web design</option> <option>Handmade</option> <option>Scientific research</option> <option>Education</option> <option>Media&Art</option> <option>Social&welfare </option> <option>Food&service </option> <option>Marketing&sales </option> <option>HR</option> <option>Half-day work</option> <option>Work for students</option> <option>Work at home</option> </select></label> <label><span>Occupation: </span><input type="text" name="occupation" value= ${occupation}> </label> <label><span>Location: </span><input type="text" name="location" value=${location}> </label> <label><span>E-mail: </span><input type="email" name="mail" value=${mail}> </label> <c:choose> <c:when test="${sex==mail}"> <label><span>Sex: </span> <select name="sex" style="width:152px;font-family:arial;color:grey;Font-size:12px;"> <option selected>Mail</option> <option>Female</option> </select></label> </c:when> <c:otherwise> <label><span>Sex: </span> <select name="sex" style="width:152px;font-family:arial;color:grey;Font-size:12px;"> <option >Mail</option> <option selected>Female</option> </select></label> </c:otherwise> </c:choose> <p style="font-family:arial;color:red;font-size:10px;">${errorMessage}</p><br> <label><span><input type="submit" value="Save"></span></label> <br> </form> </div> <br> <div class="border_2"><br> <a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/serviceError"><img class="displayed"src='http://localhost:8080/img/CV.gif' alt="Add CV" title="Add CV"></a> </br> </div> </div> <div id="links" style="background-color:#FFFFFF;height:50px;width:580px;float:left;"> <p style="font-family:arial;font-size:14px;"><a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/vacancy">Vacancy</a> | <a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/search">Search</a> | <a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/welcome">Home>></a></p> </div> <div id="gallery" style="background-color:#FFFFFF;text-align:justify;max-height:578px;overflow:auto;width:580px;float:left;"> <p style="font-family:arial;color:red;font-size:10px;">${errorMessage}</p><br> <c:if test="${portfolio eq 'available'}"> <b><a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/upload_images"><img class="icon_1" src='http://localhost:8080/img/add_img.gif' alt="Add images" title="Add images"></a> <a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/remove_all_img"><img class="icon_1" src='http://localhost:8080/img/delete_img.gif' alt="Remove all" title="Remove all"></a> </b> <c:forEach items="${files}" var="id"> <a href="image/${login}/${id}"><img src="image/${login}/${id}" alt="${id}" ></a> </c:forEach> </c:if> <c:if test="${portfolio eq 'none'}"> <a href="http://localhost:8080/PortfolioGallery-1.0-SNAPSHOT/upload_images"><img class= "displayed_1" src='http://localhost:8080/img/gallery.gif' alt="Create Portfolio Gallery" title="Create Portfolio Gallery"></a> </c:if> </div> <div id="border" style="background-image:url('http://localhost:8080/img/border.gif');height:50px;clear:both;text-align:left;"> <br> <p style="font-family:arial;color:grey;font-size:12px;">Copyright (c)maret</p> </div> </div> </body> </html><file_sep>package gall.impl; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by W on 14.06.2014. */ public class GalleryRowMapper implements RowMapper { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Image image = new Image(); image.setId(rs.getInt("ID")); image.setUserId(rs.getInt("user_ID")); image.setImgFilePath(rs.getString("img")); return image; } } <file_sep>package gall.impl; import gall.api.GalleryDAO; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*; /** * Created by W on 13.06.2014. */ public class JDBCGalleryDAO extends JdbcDaoSupport implements GalleryDAO { @Override public void setGalleryExisting(String login) { String sql = "UPDATE account " + "SET gallery = 'available'" + " WHERE login = ?"; getJdbcTemplate().update(sql, new Object[]{login}); } @Override public void removeAll(int id) { String sqlForGallery = "DELETE FROM gallery WHERE user_ID = ?"; getJdbcTemplate().update(sqlForGallery, new Object[]{id}); String sqlForAccount = "UPDATE account " + "SET gallery = null" + " WHERE ID = ?"; getJdbcTemplate().update(sqlForAccount, new Object[]{id}); } @Override public String searchForGallery(String login) { String sql = "SELECT gallery FROM account WHERE login = ?"; String galleryStatus = getJdbcTemplate().queryForObject( sql, new Object[]{login}, String.class); return galleryStatus; } @Override public int putImg(final int userId, final String imgFilePath) { final String sql = "INSERT INTO gallery " + "(img, user_ID) VALUES (?, ?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); getJdbcTemplate().update( new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(sql, new String[]{"ID"}); ps.setString(1, imgFilePath); ps.setInt(2, userId); return ps; } }, keyHolder ); return keyHolder.getKey().intValue(); } @Override @SuppressWarnings("rawtypes") public Set<Image> getAllImg(int userId) { String sql = "SELECT * FROM gallery WHERE user_ID = ?"; Set<Image> images = new HashSet<Image>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql, new Object[]{userId}); for (Map row : rows) { Image img = new Image(); img.setId(Integer.parseInt(String.valueOf(row.get("ID")))); img.setUserId(Integer.parseInt(String.valueOf(row.get("user_ID")))); img.setImgFilePath((String) row.get("img")); images.add(img); } return images; } @Override @SuppressWarnings({"unchecked"}) public Image viewImg(int imgId) { String sql = "SELECT * FROM gallery WHERE ID = ?"; Image image = null; try { image = (Image) getJdbcTemplate().queryForObject(sql, new Object[]{imgId}, new GalleryRowMapper()); } catch (IncorrectResultSizeDataAccessException e) { image = null; } return image; } } <file_sep>package com.web.controll; import account.except.NotAllFieldsFilledException; import account.impl.NullValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import vacancy.api.VacancyManagement; import vacancy.except.NoVacancyException; import vacancy.impl.Vacancy; import java.util.HashMap; import java.util.Map; /** * Created with IntelliJ IDEA. * User: W * Date: 18.03.14 * Time: 10:28 * To change this template use File | Settings | File Templates. */ @Controller public class VacancyController { @Autowired @Qualifier("VacancyManagementBean") public VacancyManagement vacancyManagement; @RequestMapping(value = "/vacancy", method = RequestMethod.GET) public String openVacancyPage(ModelMap model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String login = auth.getName(); model.addAttribute("login", login); model.addAttribute("message", "Vacancies"); return "vacancies"; } @RequestMapping(value = "/view_vacancy", method = RequestMethod.GET) public String viewVacancy(@RequestParam("vacancy_id") String id, ModelMap model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String login = auth.getName(); Integer vacancyId = Integer.valueOf(id); model.addAttribute("login", login); model.addAttribute("message", "View vacancy"); try { Vacancy vacancy = vacancyManagement.viewVacancy(vacancyId); Map<String, String> vacancyInf = new HashMap<String, String>(); vacancyInf.put("vacancy_name", vacancy.getName()); vacancyInf.put("category", vacancy.getCategory()); vacancyInf.put("occupation", vacancy.getOccupation()); vacancyInf.put("location", vacancy.getLocation()); vacancyInf.put("tell", vacancy.getTell()); vacancyInf.put("mail", vacancy.getMail()); vacancyInf.put("body", vacancy.getBody()); model.addAllAttributes(vacancyInf); } catch (NoVacancyException e) { model.addAttribute("errorMessage", "You must fill all fields!"); return "view_vacancy"; } return "view_vacancy"; } @RequestMapping(value = "/open_vacancy", method = RequestMethod.POST) public String openVacancy(@RequestParam("name") String name, @RequestParam("category") String category, @RequestParam("location") String location, @RequestParam("occupation") String occupation, @RequestParam("tell") String tell, @RequestParam("mail") String mail, @RequestParam("content") String body, ModelMap model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String login = auth.getName(); model.addAttribute("login", login); model.addAttribute("message", "Vacancies"); try { NullValidator.checkNull(name, location, occupation, mail, tell, body); Vacancy vacancy = vacancyManagement.openNewVacancy(name, category, occupation, location, tell, mail, body); model.addAttribute("Message", "You have opened new vacancy "); model.addAttribute("id", vacancy.getId()); Map<String, String> vacancyInf = new HashMap<String, String>(); vacancyInf.put("vacancy_name", vacancy.getName()); vacancyInf.put("category", vacancy.getCategory()); vacancyInf.put("occupation", vacancy.getOccupation()); vacancyInf.put("location", vacancy.getLocation()); vacancyInf.put("tell", vacancy.getTell()); vacancyInf.put("mail", vacancy.getMail()); model.addAllAttributes(vacancyInf); } catch (NotAllFieldsFilledException e) { model.addAttribute("errorMessage", "You must fill all fields!"); return "vacancies"; } return "vacancy_open_success"; } @RequestMapping(value = "/search_for_vacancies", method = RequestMethod.GET, produces = "application/json") @ResponseBody public Map<Integer, Vacancy> viewVacancyList(@RequestParam("category") String category, @RequestParam("occupation") String occupation, @RequestParam("location") String location) { Map<Integer, Vacancy> vacancies = null; try { if ((occupation.equals("")) && (location.equals(""))) { if (!category.equals("All")) { vacancies = vacancyManagement.searchByCategory(category); } else { vacancies = vacancyManagement.showAllVacancies(); } } if ((!occupation.equals("")) && (location.equals(""))) { if (!category.equals("All")) { vacancies = vacancyManagement.searchByCategoryOccupation(category, occupation); } else { vacancies = vacancyManagement.searchByOccupation(occupation); } } if ((occupation.equals("")) && (!location.equals(""))) { if (!category.equals("All")) { vacancies = vacancyManagement.searchByCategoryLocation(category, location); } else { vacancies = vacancyManagement.searchByLocation(location); } } if ((!occupation.equals("")) && (!location.equals(""))) { if (!category.equals("All")) { vacancies = vacancyManagement.searchByCategoryOccupationLocation(category, occupation, location); } else { vacancies = vacancyManagement.searchByOccupationAndLocation(occupation, location); } } } catch (NoVacancyException e) { vacancies = null; } return vacancies; } } <file_sep>package account.except; /** * Created with IntelliJ IDEA. * User: W * Date: 15.01.14 * Time: 13:05 * To change this template use File | Settings | File Templates. */ public class AuthorityException extends Exception { private String message; public AuthorityException() { this.message = ErrorMessage.IncorrectPasswords.getErrorMassage(); } public static enum ErrorMessage { IncorrectPasswords("Passwords do not match" + "\n"); private String errorMassage; ErrorMessage(String errorMassage) { this.errorMassage = errorMassage; } private String getErrorMassage() { return errorMassage; } } @Override public String toString() { return message; } } <file_sep>package account.impl; import account.api.AccountDAO; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.support.JdbcDaoSupport; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by W on 18.04.2014. */ public class JDBCAccountDAO extends JdbcDaoSupport implements AccountDAO { @Override public void putAccountToBase(Account account) { String sql = "INSERT INTO account " + "(login, password_hash, name, surname, category, occupation, location, mail, sex) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; getJdbcTemplate().update(sql, new Object[]{account.getLogin(), account.getPasswordHash(), account.getName(), account.getSurname(), account.getCategory(), account.getOccupation(), account.getLocation(), account.getMail(), account.getSex()}); } @Override public void updateAccount(int id, String login, String newName, String newSurname, String newCategory, String newOccupation, String newLocation, String newSex, String newMail) { String sql = "UPDATE account " + "SET login = ?, name = ?, surname = ?, category = ?, occupation = ?, location = ?, mail = ?, sex = ?" + " WHERE id = ?"; getJdbcTemplate().update(sql, new Object[]{login, newName, newSurname, newCategory, newOccupation, newLocation, newMail, newSex, id}); } @Override public String getPasswordFromBase(String login) { String sql = "SELECT password_hash FROM account WHERE login = ?"; String password_hash = getJdbcTemplate().queryForObject( sql, new Object[]{login}, String.class); return password_hash; } @Override @SuppressWarnings({"unchecked"}) public Account getAccountFromBase(String login) { String sql = "SELECT * FROM account WHERE login = ?"; Account account = null; try { account = (Account) getJdbcTemplate().queryForObject(sql, new Object[]{login}, new AccountRowMapper()); } catch (IncorrectResultSizeDataAccessException e) { account = null; } return account; } @Override @SuppressWarnings("rawtypes") public Map<String, Account> getAllEmp() { String sql = "SELECT * FROM account"; Map<String, Account> accounts = new HashMap<String, Account>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql); for (Map row : rows) { Account account = new Account(); account.setId(Integer.parseInt(String.valueOf(row.get("ID")))); account.setLogin((String) row.get("login")); account.setName((String) row.get("name")); account.setSurname((String) row.get("surname")); account.setCategory((String) row.get("category")); account.setOccupation((String) row.get("occupation")); account.setLocation((String) row.get("location")); account.setMail((String) row.get("mail")); account.setSex((String) row.get("sex")); account.setCv((String) row.get("cv")); accounts.put((String) row.get("login"), account); } return accounts; } @Override public void removeAccountFromBase(String login) { String sql = "DELETE FROM account WHERE login = ?"; getJdbcTemplate().update(sql, new Object[]{login}); } @Override public Map<String, Account> getByCategory(String category) { String sql = "SELECT * FROM account WHERE category = ?"; Map<String, Account> accounts = new HashMap<String, Account>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql, new Object[]{category}); for (Map row : rows) { Account account = new Account(); account.setId(Integer.parseInt(String.valueOf(row.get("ID")))); account.setLogin((String) row.get("login")); account.setName((String) row.get("name")); account.setSurname((String) row.get("surname")); account.setCategory((String) row.get("category")); account.setOccupation((String) row.get("occupation")); account.setLocation((String) row.get("location")); account.setMail((String) row.get("mail")); account.setSex((String) row.get("sex")); account.setCv((String) row.get("cv")); accounts.put((String) row.get("login"), account); } return accounts; } @Override public Map<String, Account> getByLocation(String location) { String sql = "SELECT * FROM account WHERE location = ?"; Map<String, Account> accounts = new HashMap<String, Account>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql, new Object[]{location}); for (Map row : rows) { Account account = new Account(); account.setId(Integer.parseInt(String.valueOf(row.get("ID")))); account.setLogin((String) row.get("login")); account.setName((String) row.get("name")); account.setSurname((String) row.get("surname")); account.setCategory((String) row.get("category")); account.setOccupation((String) row.get("occupation")); account.setLocation((String) row.get("location")); account.setMail((String) row.get("mail")); account.setSex((String) row.get("sex")); account.setCv((String) row.get("cv")); accounts.put((String) row.get("login"), account); } return accounts; } @Override public Map<String, Account> getByOccupation(String occupation) { String sql = "SELECT * FROM account WHERE occupation = ?"; Map<String, Account> accounts = new HashMap<String, Account>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql, new Object[]{occupation}); for (Map row : rows) { Account account = new Account(); account.setId(Integer.parseInt(String.valueOf(row.get("ID")))); account.setLogin((String) row.get("login")); account.setName((String) row.get("name")); account.setSurname((String) row.get("surname")); account.setCategory((String) row.get("category")); account.setOccupation((String) row.get("occupation")); account.setLocation((String) row.get("location")); account.setMail((String) row.get("mail")); account.setSex((String) row.get("sex")); account.setCv((String) row.get("cv")); accounts.put((String) row.get("login"), account); } return accounts; } @Override public Map<String, Account> getByOccupationLocation(String occupation, String location) { String sql = "SELECT * FROM account WHERE occupation = ? AND location = ?"; Map<String, Account> accounts = new HashMap<String, Account>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql, new Object[]{occupation, location}); for (Map row : rows) { Account account = new Account(); account.setId(Integer.parseInt(String.valueOf(row.get("ID")))); account.setLogin((String) row.get("login")); account.setName((String) row.get("name")); account.setSurname((String) row.get("surname")); account.setCategory((String) row.get("category")); account.setOccupation((String) row.get("occupation")); account.setLocation((String) row.get("location")); account.setMail((String) row.get("mail")); account.setSex((String) row.get("sex")); account.setCv((String) row.get("cv")); accounts.put((String) row.get("login"), account); } return accounts; } @Override public Map<String, Account> getByCategoryLocation(String category, String location) { String sql = "SELECT * FROM account WHERE category = ? AND location = ?"; Map<String, Account> accounts = new HashMap<String, Account>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql, new Object[]{category, location}); for (Map row : rows) { Account account = new Account(); account.setId(Integer.parseInt(String.valueOf(row.get("ID")))); account.setLogin((String) row.get("login")); account.setName((String) row.get("name")); account.setSurname((String) row.get("surname")); account.setCategory((String) row.get("category")); account.setOccupation((String) row.get("occupation")); account.setLocation((String) row.get("location")); account.setMail((String) row.get("mail")); account.setSex((String) row.get("sex")); account.setCv((String) row.get("cv")); accounts.put((String) row.get("login"), account); } return accounts; } @Override public Map<String, Account> getByCategoryOccupation(String category, String occupation) { String sql = "SELECT * FROM account WHERE category = ? AND occupation = ?"; Map<String, Account> accounts = new HashMap<String, Account>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql, new Object[]{category, occupation}); for (Map row : rows) { Account account = new Account(); account.setId(Integer.parseInt(String.valueOf(row.get("ID")))); account.setLogin((String) row.get("login")); account.setName((String) row.get("name")); account.setSurname((String) row.get("surname")); account.setCategory((String) row.get("category")); account.setOccupation((String) row.get("occupation")); account.setLocation((String) row.get("location")); account.setMail((String) row.get("mail")); account.setSex((String) row.get("sex")); account.setCv((String) row.get("cv")); accounts.put((String) row.get("login"), account); } return accounts; } @Override public Map<String, Account> getByCategoryOccupationLocation(String category, String occupation, String location) { String sql = "SELECT * FROM account WHERE category = ? AND occupation = ? AND location = ?"; Map<String, Account> accounts = new HashMap<String, Account>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql, new Object[]{category, occupation, location}); for (Map row : rows) { Account account = new Account(); account.setId(Integer.parseInt(String.valueOf(row.get("ID")))); account.setLogin((String) row.get("login")); account.setName((String) row.get("name")); account.setSurname((String) row.get("surname")); account.setCategory((String) row.get("category")); account.setOccupation((String) row.get("occupation")); account.setLocation((String) row.get("location")); account.setMail((String) row.get("mail")); account.setSex((String) row.get("sex")); account.setCv((String) row.get("cv")); accounts.put((String) row.get("login"), account); } return accounts; } @Override public Map<String, Account> getByLogin(String userLogin) { String sql = "SELECT * FROM account WHERE login = ? "; Map<String, Account> accounts = new HashMap<String, Account>(); List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql, new Object[]{userLogin}); for (Map row : rows) { Account account = new Account(); account.setId(Integer.parseInt(String.valueOf(row.get("ID")))); account.setLogin((String) row.get("login")); account.setName((String) row.get("name")); account.setSurname((String) row.get("surname")); account.setCategory((String) row.get("category")); account.setOccupation((String) row.get("occupation")); account.setLocation((String) row.get("location")); account.setMail((String) row.get("mail")); account.setSex((String) row.get("sex")); account.setCv((String) row.get("cv")); accounts.put((String) row.get("login"), account); } return accounts; } } <file_sep>package vacancy.impl; import account.impl.Account; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by W on 18.04.2014. */ @SuppressWarnings("rawtypes") public class VacancyRowMapper implements RowMapper { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Vacancy vacancy = new Vacancy(); vacancy.setId(rs.getInt("ID")); vacancy.setName(rs.getString("name")); vacancy.setCategory(rs.getString("category")); vacancy.setOccupation(rs.getString("occupation")); vacancy.setLocation(rs.getString("location")); vacancy.setMail(rs.getString("mail")); vacancy.setTell(rs.getString("tell")); vacancy.setBody(rs.getString("body")); return vacancy; } } <file_sep>package com.web.controll; import account.api.AccountManagement; import account.impl.Account; import com.web.config.FileUpload; import gall.api.GalleryManagement; import gall.except.AvailabilityGalleryException; import gall.impl.Image; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.util.*; /** * Created by W on 02.06.2014. */ @Controller public class ImgUploadController { @Autowired @Qualifier("GalleryManagementBean") public GalleryManagement galleryManagement; @Autowired @Qualifier("AccountManagementBean") public AccountManagement management; @RequestMapping(value = "/upload_images", method = RequestMethod.GET) public String openUploadingPage(ModelMap model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String login = auth.getName(); model.addAttribute("login", login); model.addAttribute("message", "Uploading page"); return "upload_img"; } @RequestMapping(value = "/upload_file", method = RequestMethod.POST) public String uploadFile(@ModelAttribute("uploadForm") FileUpload uploadForm, ModelMap model) throws IllegalStateException, IOException { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String login = auth.getName(); MultipartFile[] uploadedFiles = uploadForm.getFiles(); List<MultipartFile> files = Arrays.asList(uploadedFiles); model.addAttribute("login", login); int userId = management.viewAccount(login).getId(); try { List<Integer> imagesId = galleryManagement.addImg(login, files, userId); if (imagesId.isEmpty() == false) { model.addAttribute("files", imagesId); model.addAttribute("login", login); model.addAttribute("user_login", login); model.addAttribute("Message", "Files have been successfully uploaded!"); return "uploading_success"; } else { model.addAttribute("errorMessage", "No files have been uploaded"); return "upload_img"; } } catch (IOException e) { model.addAttribute("errorMessage", "Sorry, request can't be processed."); return "upload_img"; } catch (AvailabilityGalleryException e) { model.addAttribute("errorMessage", "Sorry, request can't be processed. Please return to your account home-page and try create gallery again."); return "upload_img"; } } @RequestMapping(value = "/remove_all_img", method = RequestMethod.GET) public String removeAll(ModelMap model) throws IllegalStateException, IOException { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String login = auth.getName(); Account account = management.viewAccount(login); galleryManagement.removeGallery(login, account.getId()); List<Integer> imgIds = new ArrayList<Integer>(); String galleryStatus = galleryManagement.checkGalleryStatus(login); if (galleryStatus != null) { Set<Image> images = galleryManagement.viewAllImg(account.getId()); for (Image image : images) { int imageId = image.getId(); imgIds.add(imageId); } model.addAttribute("portfolio", "available"); model.addAttribute("files", imgIds); } else { model.addAttribute("portfolio", "none"); } Map<String, String> userInf = new HashMap<String, String>(); userInf.put("login", login); userInf.put("message", "User information"); userInf.put("name", account.getName()); userInf.put("surname", account.getSurname()); userInf.put("category", account.getCategory()); userInf.put("occupation", account.getOccupation()); userInf.put("mail", account.getMail()); userInf.put("location", account.getLocation()); userInf.put("sex", account.getSex()); model.addAllAttributes(userInf); model.addAttribute("message", "User information"); return "user_info"; } @RequestMapping(value = "/image/{login}/{id}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody public byte[] displayJPGImage(@PathVariable("id") String id, @PathVariable("login") String login) throws IOException { int ImgId = Integer.valueOf(id); try { byte[] bytes = galleryManagement.displayImg(login, ImgId); return bytes; } catch (IOException e) { return null; } } } <file_sep>PortfolioGallery "PortfolioGallery" is java-based enterprise application which uses next technologies: - Java core as server-side - Spring Framework (including Spring Security, Spring MVC and Spring IoC) - HTML, CSS, JavaScript (JQuery/Ajax) within JSP as front-end - MySQL database with JDBC --------------------------------------------------------------------------- Web-application is employment\portfolio site which provides next functionalities: - Registration/Authorization to manage user information (as employee) - Post vacancies depends of categories and other selections - Create and fill up portfolio (add and remove images) - Search for vacancies - Search for users in various ways to find employees <file_sep>package account.except; /** * Created with IntelliJ IDEA. * User: W * Date: 17.01.14 * Time: 14:14 * To change this template use File | Settings | File Templates. */ public class IncorrectInputException extends Exception { private String messege; public IncorrectInputException(String errorMassage) { this.messege = errorMassage; } public IncorrectInputException() { this.messege = ErrorMessage.WrongPassword.getErrorMassage(); } public IncorrectInputException(ErrorMessage enumMember) { this.messege = enumMember.getErrorMassage(); } public static enum ErrorMessage { WrongPassword("Password must be not shorter than 6 symbols" + "\n"), PasswordsDoNotMatch("Passwords do not match" + "\n"); private String errorMessage; private ErrorMessage(String errorMassage) { this.errorMessage = errorMassage; } private String getErrorMassage() { return errorMessage; } } @Override public String toString() { return messege; } }<file_sep>package vacancy.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Created by W on 05.04.2014. */ @Component public class Vacancy { private int id; private String category; private String occupation; private String location; private String tell; private String mail; private String body; private String name; public Vacancy(String name, String category, String occupation, String location, String tell, String mail, String body) { this.category = category; this.occupation = occupation; this.location = location; this.tell = tell; this.mail = mail; this.body = body; this.name = name; } public Vacancy() { } public int getId() { return id; } public String getName() { return name; } public String getCategory() { return category; } public String getOccupation() { return occupation; } public String getLocation() { return location; } public String getTell() { return tell; } public String getMail() { return mail; } public String getBody() { return body; } public void setName(String name) { this.name = name; } @Autowired public void setId(int id) { this.id = id; } @Autowired public void setCategory(String category) { this.category = category; } @Autowired public void setOccupation(String occupation) { this.occupation = occupation; } @Autowired public void setLocation(String location) { this.location = location; } @Autowired public void setTell(String tell) { this.tell = tell; } @Autowired public void setMail(String mail) { this.mail = mail; } @Autowired public void setBody(String body) { this.body = body; } } <file_sep>package gall.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Created by W on 13.06.2014. */ @Component public class Image { private String imgFilePath; private int id; private int userId; public Image() { } public Image(String imgFilePath, int id, int userId) { this.imgFilePath = imgFilePath; this.id = id; this.userId = userId; } public String getImgFilePath() { return imgFilePath; } public int getId() { return id; } public int getUserId() { return userId; } @Autowired public void setImgFilePath(String imgFilePath) { this.imgFilePath = imgFilePath; } @Autowired public void setId(int id) { this.id = id; } @Autowired public void setUserId(int userId) { this.userId = userId; } } <file_sep>package account.impl; import account.api.AccountManagement; import account.except.AuthorityException; import account.except.AvailabilityAccountException; import account.except.IncorrectInputException; import account.except.NotAllFieldsFilledException; import gall.except.AvailabilityGalleryException; import gall.impl.GalleryManagementImpl; import gall.impl.JDBCGalleryDAO; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Map; /** * Created with IntelliJ IDEA. * User: W * Date: 14.01.14 * Time: 13:35 * To change this template use File | Settings | File Templates. */ @Component @Qualifier("AccountManagementBean") public class AccountManagementImpl implements AccountManagement { private JDBCAccountDAO accountDAO; private GalleryManagementImpl galleryManagement; public AccountManagementImpl() { } @Autowired public void setAccountDAO(JDBCAccountDAO accountDAO) { this.accountDAO = accountDAO; } @Autowired public void setGalleryManagement(GalleryManagementImpl galleryManagement) { this.galleryManagement = galleryManagement; } @Override public Account registerNewAccount(String login, String password, String comfPassword, String name, String surname, String category, String occupation, String location, String sex, String mail) throws IncorrectInputException, NotAllFieldsFilledException, AvailabilityAccountException { Account presentAccount = accountDAO.getAccountFromBase(login); if (presentAccount != null) { throw new AvailabilityAccountException(); } if (!password.equals(comfPassword)) { throw new IncorrectInputException(IncorrectInputException.ErrorMessage.PasswordsDoNotMatch); } Account account = new Account(login, name, surname, category, occupation, location, sex, mail, password); accountDAO.putAccountToBase(account); return account; } @Override public String changePassword(String login, String oldPassword, String newPassword) throws IncorrectInputException, AuthorityException { String accountPassword = accountDAO.getPasswordFromBase(login); if (PasswordValidator.isPasswordValid(newPassword) == false) { throw new IncorrectInputException(IncorrectInputException.ErrorMessage.WrongPassword); } ShaPasswordEncoder passwordEnc = new ShaPasswordEncoder(512); String encodedPassword = passwordEnc.encodePassword(oldPassword, login); PasswordValidator.checkPassword(encodedPassword, accountPassword); Account account = accountDAO.getAccountFromBase(login); account.setPasswordHash(encodedPassword); String response = "Password has been successfully changed " + "\n"; return response; } @Override public Map<String, Account> searchByCategoryOccupation(String category, String occupation) throws AvailabilityAccountException { Map<String, Account> employees = accountDAO.getByCategoryOccupation(category, occupation); if (employees.isEmpty() == true) { throw new AvailabilityAccountException(AvailabilityAccountException.ErrorMessage.AccountNotExist); } return employees; } @Override public Map<String, Account> searchByOccupation(String occupation) throws AvailabilityAccountException { Map<String, Account> employees = accountDAO.getByOccupation(occupation); if (employees.isEmpty() == true) { throw new AvailabilityAccountException(AvailabilityAccountException.ErrorMessage.AccountNotExist); } return employees; } @Override public Map<String, Account> searchByCategory(String category) throws AvailabilityAccountException { Map<String, Account> employees = accountDAO.getByCategory(category); return employees; } @Override public Map<String, Account> searchByCategoryLocation(String category, String location) throws AvailabilityAccountException { Map<String, Account> employees = accountDAO.getByCategoryLocation(category, location); if (employees.isEmpty() == true) { throw new AvailabilityAccountException(AvailabilityAccountException.ErrorMessage.AccountNotExist); } return employees; } @Override public Map<String, Account> searchByLocation(String location) throws AvailabilityAccountException { Map<String, Account> employees = accountDAO.getByLocation(location); if (employees.isEmpty() == true) { throw new AvailabilityAccountException(AvailabilityAccountException.ErrorMessage.AccountNotExist); } return employees; } @Override public Map<String, Account> searchByLogin(String login) throws AvailabilityAccountException { Map<String, Account> employees = accountDAO.getByLogin(login); if (employees.isEmpty() == true) { throw new AvailabilityAccountException(AvailabilityAccountException.ErrorMessage.AccountNotExist); } return employees; } @Override public Map<String, Account> searchByCategoryOccupationLocation(String category, String occupation, String location) throws AvailabilityAccountException { Map<String, Account> employees = accountDAO.getByCategoryOccupationLocation(category, occupation, location); for (Map.Entry<String, Account> entry : employees.entrySet()) { if (employees.isEmpty() == true) { throw new AvailabilityAccountException(AvailabilityAccountException.ErrorMessage.AccountNotExist); } } return employees; } @Override public Map<String, Account> searchByOccupationLocation(String occupation, String location) throws AvailabilityAccountException { Map<String, Account> employees = accountDAO.getByOccupationLocation(occupation, location); if (employees.isEmpty() == true) { throw new AvailabilityAccountException(AvailabilityAccountException.ErrorMessage.AccountNotExist); } return employees; } @Override public Map<String, Account> showAllEmp() throws AvailabilityAccountException { Map<String, Account> employees = accountDAO.getAllEmp(); if (employees.isEmpty() == true) { throw new AvailabilityAccountException(AvailabilityAccountException.ErrorMessage.AccountNotExist); } return employees; } @Override public void removeAccount(String login) throws AvailabilityGalleryException, IOException { Account account = accountDAO.getAccountFromBase(login); String galleryStatus = galleryManagement.checkGalleryStatus(login); if (galleryStatus != null) { boolean isRemoved = galleryManagement.removeGallery(account.getLogin(), account.getId()); if (isRemoved == true) accountDAO.removeAccountFromBase(login); { } } } @Override public void updateUserInformation(int id, String login, String newName, String newSurname, String newCategory, String newOccupation, String newLocation, String newSex, String newMail) { accountDAO.updateAccount(id, login, newName, newSurname, newCategory, newOccupation, newLocation, newSex, newMail); } public String getUserPasswordHash(String login) { String accountPassword = accountDAO.getPasswordFromBase(login); return accountPassword; } @Override public Account viewAccount(String login) { Account account = accountDAO.getAccountFromBase(login); return account; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>groupId</groupId> <artifactId>PortfolioGallery</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <repositories> <repository> <id>java.net</id> <url>http://search.maven.org/</url> </repository> <repository> <id>spring-libs-snapshot</id> <name>Spring Snapshot Repository</name> <url>http://repo.springsource.org/snapshot</url> </repository> </repositories> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://www.mydomain.com:1234/mymanager</url> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.kenai.nbpwr</groupId> <artifactId>junit</artifactId> <version>4.7-201002241900</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3</version> </dependency> <dependency> <groupId>org.apache.directory.studio</groupId> <artifactId>org.apache.commons.codec</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.2.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>3.2.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>3.2.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>3.2.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>3.2.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-javaconfig</artifactId> <version>1.0.0.CI-SNAPSHOT</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.compass-project</groupId> <artifactId>compass</artifactId> <version>2.2.0</version> </dependency> <!-- Apache Commons Upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!-- Apache Commons Upload --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> </project> <file_sep> package com.web.controll; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created with IntelliJ IDEA. * User: W * Date: 14.03.14 * Time: 11:36 * To change this template use File | Settings | File Templates. */ @Controller public class HelloController { @RequestMapping(value = "/welcome", method = RequestMethod.GET) public String openWelcomePage( ModelMap model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String login = auth.getName(); model.addAttribute("login", login); model.addAttribute("message", "Welcome to Portfolio database!"); return "hello"; } } <file_sep>package account.impl; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by W on 18.04.2014. */ @SuppressWarnings("rawtypes") public class AccountRowMapper implements RowMapper { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Account account = new Account(); account.setId(rs.getInt("ID")); account.setLogin(rs.getString("login")); account.setName(rs.getString("name")); account.setSurname(rs.getString("surname")); account.setCategory(rs.getString("category")); account.setOccupation(rs.getString("occupation")); account.setLocation(rs.getString("location")); account.setMail(rs.getString("mail")); account.setSex(rs.getString("sex")); account.setCv(rs.getString("cv")); account.setGallery(rs.getString("gallery")); return account; } } <file_sep>package vacancy.except; /** * Created by W on 05.04.2014. */ public class NoVacancyException extends Exception{ private String massage; public NoVacancyException() { this.massage = ErrorMassage.NoVacancy.getErrorMassage(); } public static enum ErrorMassage { NoVacancy("There are no vacancies for your request" + "\n"); private String errorMassage; private ErrorMassage(String errorMassage) { this.errorMassage = errorMassage; } private String getErrorMassage() { return errorMassage; } } @Override public String toString() { return massage; } }<file_sep>package account.except; /** * Created with IntelliJ IDEA. * User: W * Date: 21.01.14 * Time: 12:03 * To change this template use File | Settings | File Templates. */ public class AvailabilityAccountException extends Exception { private String message; public AvailabilityAccountException() { this.message = ErrorMessage.AccountExists.getErrorMessage(); } public AvailabilityAccountException(ErrorMessage enumMember) { this.message = enumMember.getErrorMessage(); } public static enum ErrorMessage { AccountExists("Account is already exist. Please, choose another login" + "\n"), AccountNotExist("Account is not exist" + "\n"); private String errorMessage; private ErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } private String getErrorMessage() { return errorMessage; } } @Override public String toString() { return message; } }
8f538a9d81d7f48600b6e08cafa59f230c05a749
[ "Java", "Markdown", "Java Server Pages", "Maven POM" ]
19
Java
maretOlia/PortfolioGallery
f63a3eb5bb82833e3374c583d258626240167eed
100bcbdc55abffc7c41f329bb3331a3de5ca41d8
refs/heads/master
<file_sep><template> <v-card> <v-card-title class="headline primary--text">Data Capture</v-card-title> <v-container fill-height> <v-layout fill-height> <v-flex xs12 align-end flexbox> <v-text-field box v-model="rawLog" name="input-7-1" label="What Happened This Day" multi-line ></v-text-field> <v-btn @click="submit">submit </v-btn> </v-flex> </v-layout> </v-container> </v-card> </template> <script> export default { created() { this.$store.dispatch("fetchAllSuppliers"); }, data: () => ({ rawLog: "Got shoes for R70 from Mike. Bought R70 worth Cement, Lime, and Soda from usual guys. Got Sugar for R34 from PickNPay. Got Sweet Melon for R45 from Spar. Tonight, after a breakthrough year for America, our economy is growing and creating jobs at the fastest pace since 1999. Got R90.00 worth of Peas from Bluff Checkers" }), methods: { submit() { this.$store.dispatch("newRawLog", this.rawLog); } } }; </script> <file_sep><template> <v-app> <v-toolbar app> <v-toolbar-title>Company Data</v-toolbar-title> <v-spacer></v-spacer> <v-btn :to="{name: 'Suppliers'}">Suppliers</v-btn> </v-toolbar> <v-content> <router-view/> </v-content> <v-footer fixed app> <span>&copy; 2018</span> </v-footer> </v-app> </template> <script> export default { data () { return { } }, name: 'App' } </script> <file_sep><template> <v-form ref="form" v-model="valid"> <v-text-field v-model="name" :rules="nameRules" :counter="10" label="Name" required ></v-text-field> <v-text-field v-model="nickName" :rules="nameRules" :counter="10" label="Nick-Name" ></v-text-field> <v-text-field v-model="email" :rules="emailRules" label="E-mail" required ></v-text-field> <v-btn :disabled="!valid" @click="submit" > submit </v-btn> </v-form> </template> <script> export default { data: () => ({ valid: false, name: "", nameRules: [ v => !!v || "Name is required", v => v.length <= 40 || "Name must be less than 40 characters" ], nickName: "", email: "", emailRules: [ v => !!v || "E-mail is required", v => /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || "E-mail must be valid" ] }), methods: { submit() { if (this.$refs.form.validate()) { // Native form submission is not yet supported this.$store.dispatch("captureNewSupplier", { name: this.name, email: this.email, nickName: this.nickName }); //this.$store.dispatch('triggerTest', true) } } } }; </script> <file_sep>import Vue from 'vue' import Vuex from 'vuex' import activityLog from './modules/nlpLog' import pouchLayer from './modules/pouchLayer' /**Because of the code below I could actually programattically initialize the nlp plugin * //my object var sendData = { field1: value1, field2: value2 }; //add element sendData['field3'] = value3; */ Vue.use(Vuex) export default new Vuex.Store({ modules: { activityLog, pouchLayer } })<file_sep>import Vue from 'vue' import Router from 'vue-router' import DailyLog from '@/components/DailyLog' import Suppliers from '@/components/Suppliers' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'DailyLog', component: DailyLog }, { path: '/suppliers', name: 'Suppliers', component: Suppliers } ] }) <file_sep>import crud from '@/api/pouchDB' var suppliersJSON = '[{ "name": "<NAME>", "email": "<EMAIL>", "nickName": "<NAME>", "_id": "supplier_Bluff Hardware Store", "_rev": "1-902f6f7a7ae54976a637639c9fcab4ab" }, { "name": "<NAME>", "email": "<EMAIL>", "nickName": "<NAME>", "_id": "supplier_Bluff Hardware Store", "_rev": "1-902f6f7a7ae54976a637639c9fcab4ab" }, { "name": "<NAME>", "email": "<EMAIL>", "nickName": "Checkers", "_id": "supplier_Checkers Bluff", "_rev": "1-4f1aab0865a44bc9886f6878af3797c3" }]' var suppliersArray = JSON.parse(suppliersJSON) console.log("suppliers Array ", suppliersArray) const state = { testRemoteDispatch: false, suppliers: [], supplierTags: {} }; const getters = { testRemoteDispatch(state) { return state.testRemoteDispatch; }, suppliers(state) { return state.suppliers; }, }; const mutations = { testRemoteDispatch(state, payload) { // mutate state console.log("testRemoteDispatch was: ", state.testRemoteDispatch); state.testRemoteDispatch = payload; console.log("testRemoteDispatch is now: ", state.testRemoteDispatch); }, suppliers(state, payload) { // mutate state state.suppliers = payload; console.log('suppliers updated', JSON.stringify(state.suppliers)) }, }; const actions = { // Dialogue actions testRemoteDispatch: ({ commit }, payload) => { commit("testRemoteDispatch", payload); }, captureNewSupplier: ({ dispatch }, payload) => { payload._id = "supplier_" + payload.name crud.create(payload) crud.info() dispatch('fetchAllSuppliers') let supplierTags = { _id: 'supTags', [payload.nickName]: 'Supplier' } console.log('supplierTags', supplierTags) }, updateExistingSupplier: ({ commit }, payload) => { crud.update(payload) }, fetchAllSuppliers: ({ commit }) => { crud.getAllType('supplier_').then(result => { console.log('fetchAllSuppliers', result) commit("suppliers", result) var newWords = {} //var words = Object.assign(newWord) result.forEach(function (element) { var strName = String(element.name).toLowerCase() var strNick = String(element.nickName).toLowerCase() newWords = Object.assign(newWords, { [strName]: 'Supplier', [strNick]: 'Supplier' }) }); commit('supplierTags', newWords) console.log("new words", newWords) }) } }; export default { state, mutations, actions, getters } <file_sep><template> <main> <v-container fluid fill-width> <v-layout column> <v-flex xs12> <v-container fluid grid-list-md> <v-layout row wrap justify-center> <v-flex xs12 md8 > <v-card v-if="!gotFin"> <v-card-title class="headline primary--text">Introduction</v-card-title> <v-container fill-height> <v-layout fill-height> <v-flex xs12 align-end flexbox> <p> This is a little app I'm working on to take my daily activity logs captured on pen and paper; and turn them into useable data. </p> <p> What makes this possible is a great super-lean Natural Language Programming (NLP) library called <a href="https://nlp-compromise.github.io/#docs" target="blank">Compromise</a>. Also thanks to the great newbie support received on their slack channel - in particular a night-lark SuperUser of the library, who goes by Aurielle. </p> <p> Next I must find out how to plug in one of those microphone speech-to-text buttons, so that the user can simply dictate into the box by voice. </p> <p> So then it's voice-to-text and text-to-spreadsheet. Woot! <emoji emoji="fist" :size="15"></emoji><emoji emoji="nerd_face" :size="20"></emoji> </p> </v-flex> </v-layout> </v-container> </v-card> </v-flex> <v-flex xs12 md8> <log-input></log-input> </v-flex> <v-flex xs12 md8> <v-card v-if="gotFin"> <v-card-title class="headline primary--text">Data Output</v-card-title> <v-container fill-height> <v-layout fill-height> <v-flex xs12 align-end flexbox> <template > <v-flex> <p> First we pull out those sentences that mention money (eg. R90) And attempt to make the distinction between money coming in, and money going out. </p> </v-flex> <log-output></log-output> <v-flex> <br> <p> Then we turn it into a Data-table. </p> </v-flex> <fin-table></fin-table> </template> </v-flex> </v-layout> </v-container> </v-card> </v-flex> </v-layout> </v-container> </v-flex> </v-layout> <missing-supplier></missing-supplier> </v-container> </main> </template> <script> import LogInput from "@/components/DailyLog/LogInput"; import LogOutput from "@/components/DailyLog/LogOutput"; import FinTable from "@/components/DailyLog/FinTable"; import MissingSupplier from "@/components/DailyLog/MissingSupplier"; export default { computed: { gotFin() { return this.$store.getters.gotFin; } }, components: { LogOutput, LogInput, FinTable, MissingSupplier } }; </script>
20293a68af9b56d8c50663d14a7f21ccd579f06b
[ "Vue", "JavaScript" ]
7
Vue
L-K-Mist/nlpTextToTables
085f69e7b79211b51e0db4059bf06350f180e956
80186798caeade945d93c9e2d3e28b5109cb2894
refs/heads/master
<repo_name>rezadim/pos<file_sep>/app/Database/Seeds/SupplierSeeder.php <?php namespace App\Database\Seeds; class SupplierSeeder extends \CodeIgniter\Database\Seeder { public function run() { $data1 = [ 'supplier_name'=>'Dimas', 'supplier_phone_number'=>'0987654321', 'supplier_address'=>'Sukoharjo, Jawa Tengah' ]; $data2 = [ 'supplier_name'=>'Putra', 'supplier_phone_number'=>'09876654323', 'supplier_address'=>'Sukoharjo, Jawa Tengah' ]; $this->db->table('suppliers')->insert($data1); $this->db->table('suppliers')->insert($data2); } }<file_sep>/app/Database/Migrations/2020-11-25-030158_suppliers.php <?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; class Suppliers extends Migration { public function up() { $this->forge->addField([ 'supplier_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'auto_increment'=>true ], 'supplier_name' => [ 'type'=>'VARCHAR', 'constraint'=>'100' ], 'supplier_phone_number' => [ 'type'=>'VARCHAR', 'constraint'=>'100', 'null'=>true ], 'supplier_address' => [ 'type'=>'TEXT', 'null'=>true ] ]); $this->forge->addKey('supplier_id', true); $this->forge->createTable('suppliers'); } //-------------------------------------------------------------------- public function down() { $this->forge->dropTable('suppliers', true); } } <file_sep>/app/Views/sale/show.php <?= view('templates/header'); ?> <?= view('templates/sidebar'); ?> <div class="content-wrapper"> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Detail Sale</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"> <a href="#">Home</a> </li> <li class="breadcrumb-item"> <a href="#">Sales</a> </li> <li class="breadcrumb-item active">Detail Sale</li> </ol> </div> </div> </div> </div> <div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-body"> <?php if(!empty(session()->getFlashdata('success'))): ?> <div class="alert alert-success"> <?= session()->getFlashdata('success'); ?> </div> <?php endif;?> <?php if(!empty(session()->getFlashdata('info'))): ?> <div class="alert alert-info"> <?= session()->getFlashdata('info'); ?> </div> <?php endif;?> <?php if(!empty(session()->getFlashdata('warning'))): ?> <div class="alert alert-warning"> <?= session()->getFlashdata('warning'); ?> </div> <?php endif;?> <div class="table-responsive"> <table class="table table-bordered table-hovered"> <thead> <th>Sale Id</th> <th>Total Purchase</th> <th>Created At</th> </thead> <tbody> <tr> <td><?= $sale['trx_sale_id']; ?></td> <td><?= "Rp.".number_format($sale['total_sale']); ?></td> <td><?= $sale['sale_created_at']; ?></td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="col-md-12"> <div class="card"> <div class="card-header"> Produk Pesanan <!-- <a href="<?= base_url('purchase/create'); ?>" class="btn btn-primary float-right">Tambah Pesanan</a> --> <button type="button" class="btn btn-primary float-right" data-toggle="modal" data-target="#createPembelian"> Tambah Pesanan </button> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered table-hovered"> <thead> <th width="10px" class="text-center">#</th> <th>Product</th> <th>Quantity</th> <th>Price</th> <th>Subtotal</th> <th>Action</th> </thead> <tbody> <?php $no=0; foreach($saleDetail as $key=>$row): ?> <tr> <td class="text-center"><?= ++$no; ?></td> <td><?= $row['product_name']; ?></td> <td><?= $row['sale_quantity']; ?></td> <td><?= "Rp.".number_format($row['sale_price']); ?></td> <td><?= $row['sale_subtotal']; ?></td> <td class="text-center"> <a href="<?= base_url('sale/edit/'.$row['trx_sale_id']); ?>" class="btn btn-sm btn-success"> <li class="fa fa-edit"></li> </a> <a href="<?= base_url('sale/delete/'.$row['trx_sale_id']); ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin???');"> <li class="fa fa-trash-alt"></li> </a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </div> <?= view('templates/footer'); ?> <!-- Modal --> <div class="modal fade" id="createPembelian" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Tambah Pesanan</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="<?= base_url('sale/storeSale'); ?>" method="post"> <input type="hidden" name="trx_sale_id" value="<?= $sale['trx_sale_id']; ?>"> <!-- --> <div class="form-group"> <label>Product</label> <select name="product_id" class="form-control"> <?php foreach($products as $p): ?> <option value="<?= $p['product_id']; ?>"><?= $p['product_name']; ?></option> <?php endforeach; ?> </select> </div> <div class="form-group"> <label>Quantity</label> <input type="number" name="sale_quantity" class="form-control"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary float-right">Add</button> </form> </div> </div> </div> </div><file_sep>/app/Database/Migrations/2020-11-25-031354_trx_purchase_details.php <?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; class TrxPurchaseDetails extends Migration { public function up() { $this->db->enableForeignKeyChecks(); $this->forge->addField([ 'purchase_detail_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'auto_increment'=>true ], 'trx_purchase_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'null'=>true ], 'product_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'null'=>true, 'unsigned'=>true ], 'purchase_quantity' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ], 'purchase_price' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ], 'purchase_subtotal' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ] ]); $this->forge->addKey('purchase_detail_id', true); $this->forge->addForeignKey('trx_purchase_id', 'trx_purchases', 'trx_purchase_id', 'CASCADE', 'CASCADE'); $this->forge->addForeignKey('product_id', 'products', 'product_id', 'CASCADE', 'CASCADE'); $this->forge->createTable('trx_purchase_details'); } //-------------------------------------------------------------------- public function down() { $this->forge->dropTable('trx_purchase_details', true); } } <file_sep>/app/Views/supplier/index.php <?= view('templates/header'); ?> <?= view('templates/sidebar'); ?> <div class="content-wrapper"> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Suppliers</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"> <a href="#">Home</a> </li> <li class="breadcrumb-item active">Suppliers</li> </ol> </div> </div> </div> </div> <div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-header"> List Suppliers <a href="<?= base_url('supplier/create'); ?>" class="btn btn-primary float-right">Tambah</a> </div> <div class="card-body"> <?php if(!empty(session()->getFlashdata('success'))): ?> <div class="alert alert-success"> <?= session()->getFlashdata('success'); ?> </div> <?php endif;?> <?php if(!empty(session()->getFlashdata('info'))): ?> <div class="alert alert-info"> <?= session()->getFlashdata('info'); ?> </div> <?php endif;?> <?php if(!empty(session()->getFlashdata('warning'))): ?> <div class="alert alert-warning"> <?= session()->getFlashdata('warning'); ?> </div> <?php endif;?> <div class="table-responsive"> <table class="table table-bordered table-hovered"> <thead> <th width="10px" class="text-center">#</th> <th>Supplier Name</th> <th>Phone Number</th> <th>Address</th> <th>Action</th> </thead> <tbody> <?php $no=0; foreach($suppliers as $key => $row):?> <tr> <td class="text-center"><?= ++$no; ?></td> <td><?= $row['supplier_name']; ?></td> <td><?= $row['supplier_phone_number']; ?></td> <td><?= $row['supplier_address']; ?></td> <td class="text-center"> <a href="<?= base_url('supplier/show/'.$row['supplier_id']); ?>" class="btn btn-sm btn-info"> <li class="fa fa-eye"></li> </a> <a href="<?= base_url('supplier/edit/'.$row['supplier_id']); ?>" class="btn btn-sm btn-success"> <li class="fa fa-edit"></li> </a> <a href="<?= base_url('supplier/delete/'.$row['supplier_id']); ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin???');"> <li class="fa fa-trash-alt"></li> </a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </div> <?= view('templates/footer'); ?><file_sep>/app/Controllers/Purchase.php <?php namespace App\Controllers; use CodeIgniter\Controller; use App\Models\Purchase_model; use App\Models\PurchaseDetail_model; use App\Models\Supplier_model; use App\Models\Product_model; class Purchase extends Controller { public function __construct() { $this->purchase = new Purchase_model(); $this->supplier = new Supplier_model(); $this->purchaseDetail = new PurchaseDetail_model(); $this->product = new Product_model(); } public function index() { $data['purchases'] = $this->purchase->getPurchase(); return view('purchase/index', $data); } public function create() { $data['suppliers'] = $this->supplier->findAll(); return view('purchase/create', $data); } public function store() { $validation = \Config\Services::validation(); $data = [ 'supplier_id'=>$this->request->getPost('supplier_id'), 'purchase_created_at'=>date('Y-m-d H:i:s') ]; if($validation->run($data, 'purchase') == false){ session()->setFlashdata('errors', $validation->getErrors()); return redirect()->to(base_url('purchase/create')); }else{ $save = $this->purchase->insertPurchase($data); if($save){ session()->setFlashdata('success', 'Created'); return redirect()->to(base_url('purchase')); } } } public function delete($id) { $delete = $this->purchase->deletePurchase($id); if($delete){ session()->setFlashdata('warning', 'Deleted'); return redirect()->to(base_url('purchase')); } } public function show($id) { $data['purchase'] = $this->purchase->getPurchase($id); $data['purchaseDetail'] = $this->purchaseDetail->getPurchaseDetail($id); $data['products'] = $this->product->findAll(); return view('purchase/show', $data); } public function storePurchase() { $validation = \Config\Services::validation(); $trx_purchase_id = $this->request->getPost('trx_purchase_id'); $qty = $this->request->getPost('purchase_quantity'); $price = $this->request->getPost('purchase_price'); $data = [ 'trx_purchase_id'=>$trx_purchase_id, 'product_id'=>$this->request->getPost('product_id'), 'purchase_quantity'=>$qty, 'purchase_price'=>$price, 'purchase_subtotal'=>$qty*$price ]; if($validation->run($data, 'purchaseDetail') == false){ session()->setFlashdata('errors', $validation->getErros()); }else{ $save = $this->purchaseDetail->insertPurchaseDetail($data); if($save){ session()->setFlashdata('success', 'Created'); return redirect()->to(base_url('purchase/show/'.$trx_purchase_id)); } } } public function deletePurchase($id) { $trx_purchase_id = $this->request->getPost('trx_purchase_id'); $delete = $this->purchaseDetail->deletePurchaseDetail($id); if($delete){ session()->setFlashdata('warning', 'Deleted'); return redirect()->to(base_url('purchase/show/'.$trx_purchase_id)); } } }<file_sep>/app/Controllers/Sale.php <?php namespace App\Controllers; use CodeIgniter\Controller; use App\Models\Sale_model; use App\Models\SaleDetail_model; use App\Models\Product_model; class Sale extends Controller { public function __construct() { $this->sale = new Sale_model(); $this->saleDetail = new SaleDetail_model(); $this->product = new Product_model(); } public function index() { $data['sales'] = $this->sale->getSale(); return view('sale/index', $data); } public function create() { return view('sale/create'); } public function store() { $validation = \Config\Services::validation(); $data = [ 'sale_created_at'=>$this->request->getPost('sale_created_at') ]; if($validation->run($data, 'sale') == false){ session()->setFlashdata('errors', $validation->getErrors()); return redirect()->to(base_url('sale/create')); }else{ $save = $this->sale->insertSale($data); if($save){ session()->setFlashdata('success', 'Created'); return redirect()->to(base_url('sale')); } } } public function delete($id) { $delete = $this->sale->deleteSale($id); if($delete){ session()->setFlashdata('warning', 'Deleted'); return redirect()->to(base_url('sale')); } } public function show($id) { $data['sale'] = $this->sale->getSale($id); $data['saleDetail'] = $this->saleDetail->getSaleDetail($id); $data['products'] = $this->product->findAll(); return view('sale/show', $data); } public function storeSale() { $validation = \Config\Services::validation(); $trx_sale_id = $this->request->getPost('trx_sale_id'); $qty = $this->request->getPost('sale_quantity'); $price = 0; $data = [ 'trx_sale_id'=>$trx_sale_id, 'product_id'=>$this->request->getPost('product_id'), 'sale_quantity'=>$qty, 'sale_subtotal'=>$qty*$price ]; if($validation->run($data, 'saleDetail') == false){ session()->setFlashdata('errors', $validation->getErrors()); }else{ $save = $this->saleDetail->insertSaleDetail($data); if($save){ session()->setFlashdata('success', 'Created'); return redirect()->to(base_url('sale/show/'.$trx_sale_id)); } } } }<file_sep>/app/Config/Validation.php <?php namespace Config; class Validation { //-------------------------------------------------------------------- // Setup //-------------------------------------------------------------------- /** * Stores the classes that contain the * rules that are available. * * @var array */ public $ruleSets = [ \CodeIgniter\Validation\Rules::class, \CodeIgniter\Validation\FormatRules::class, \CodeIgniter\Validation\FileRules::class, \CodeIgniter\Validation\CreditCardRules::class, ]; /** * Specifies the views that are used to display the * errors. * * @var array */ public $templates = [ 'list' => 'CodeIgniter\Validation\Views\list', 'single' => 'CodeIgniter\Validation\Views\single', ]; //-------------------------------------------------------------------- // Rules //-------------------------------------------------------------------- public $product = [ 'product_code'=>'required' ]; public $product_errors = [ 'product_code' => ['required'=>'Kode Produk harus diisi'] ]; public $purchase = [ 'supplier_id'=>'required' ]; public $purchase_errors = [ 'supplier_id' => ['required'=>'Supplier harus diisi'] ]; public $sale = [ 'sale_created_at' => 'required' ]; public $sale_errors = [ 'sale_created_at'=>['required'=>'Sale ID harus diisi'] ]; public $supplier = [ 'supplier_name'=>'required' ]; public $supplier_errors = [ 'supplier_name'=>['required'=>'Nama Supplier harus diisi'] ]; public $purchaseDetail = [ 'product_id'=>'required' ]; public $purchaseDetail_errors = [ 'product_id'=>['required'=>'Product harus diisi'] ]; public $saleDetail = [ 'product_id' => 'required' ]; public $saleDetail_errors = [ 'product_id'=>['required'=>'Product harus diisi'] ]; } <file_sep>/db_workshop_pos.sql -- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Waktu pembuatan: 15 Des 2020 pada 03.34 -- Versi server: 10.4.14-MariaDB -- Versi PHP: 7.4.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `db_workshop_pos` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `migrations` -- CREATE TABLE `migrations` ( `id` bigint(20) UNSIGNED NOT NULL, `version` varchar(255) NOT NULL, `class` text NOT NULL, `group` varchar(255) NOT NULL, `namespace` varchar(255) NOT NULL, `time` int(11) NOT NULL, `batch` int(11) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data untuk tabel `migrations` -- INSERT INTO `migrations` (`id`, `version`, `class`, `group`, `namespace`, `time`, `batch`) VALUES (167, '2020-11-25-021322', 'App\\Database\\Migrations\\Categories', 'default', 'App', 1606532500, 1), (168, '2020-11-25-021741', 'App\\Database\\Migrations\\Products', 'default', 'App', 1606532500, 1), (169, '2020-11-25-023526', 'App\\Database\\Migrations\\Users', 'default', 'App', 1606532500, 1), (170, '2020-11-25-024217', 'App\\Database\\Migrations\\TrxSales', 'default', 'App', 1606532501, 1), (171, '2020-11-25-025249', 'App\\Database\\Migrations\\TrxSaleDetails', 'default', 'App', 1606532501, 1), (172, '2020-11-25-030158', 'App\\Database\\Migrations\\Suppliers', 'default', 'App', 1606532502, 1), (173, '2020-11-25-030603', 'App\\Database\\Migrations\\TrxPurchases', 'default', 'App', 1606532502, 1), (174, '2020-11-25-031354', 'App\\Database\\Migrations\\TrxPurchaseDetails', 'default', 'App', 1606532503, 1); -- -------------------------------------------------------- -- -- Struktur dari tabel `products` -- CREATE TABLE `products` ( `product_id` bigint(100) UNSIGNED NOT NULL, `product_code` varchar(100) DEFAULT NULL, `product_name` varchar(100) DEFAULT NULL, `purchase_price` bigint(100) NOT NULL DEFAULT 0, `sale_price` bigint(100) NOT NULL DEFAULT 0, `stock` bigint(100) NOT NULL DEFAULT 0, `product_description` text DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data untuk tabel `products` -- INSERT INTO `products` (`product_id`, `product_code`, `product_name`, `purchase_price`, `sale_price`, `stock`, `product_description`) VALUES (1, '1q2w3e', 'T-Shirt', 20000, 0, 10, 'All Size'), (2, '4e5r6t', 'Hoodie', 30000, 0, 31, 'All Size'), (3, '4r5t6y', 'Celana Panjang', 10000, 0, 0, 'plplpl'); -- -------------------------------------------------------- -- -- Struktur dari tabel `suppliers` -- CREATE TABLE `suppliers` ( `supplier_id` bigint(100) NOT NULL, `supplier_name` varchar(100) NOT NULL, `supplier_phone_number` varchar(100) DEFAULT NULL, `supplier_address` text DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data untuk tabel `suppliers` -- INSERT INTO `suppliers` (`supplier_id`, `supplier_name`, `supplier_phone_number`, `supplier_address`) VALUES (1, 'Dimas', '0987654321', 'Sukoharjo, Jawa Tengah'), (2, 'Putra', '09876654323', 'Sukoharjo, Jawa Tengah'); -- -------------------------------------------------------- -- -- Struktur dari tabel `trx_purchases` -- CREATE TABLE `trx_purchases` ( `trx_purchase_id` bigint(100) NOT NULL, `supplier_id` bigint(100) DEFAULT NULL, `total_purchase` bigint(100) NOT NULL DEFAULT 0, `purchase_created_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data untuk tabel `trx_purchases` -- INSERT INTO `trx_purchases` (`trx_purchase_id`, `supplier_id`, `total_purchase`, `purchase_created_at`) VALUES (1, 1, 0, '2020-11-27 10:27:27'); -- -------------------------------------------------------- -- -- Struktur dari tabel `trx_purchase_details` -- CREATE TABLE `trx_purchase_details` ( `purchase_detail_id` bigint(100) NOT NULL, `trx_purchase_id` bigint(100) DEFAULT NULL, `product_id` bigint(100) UNSIGNED DEFAULT NULL, `purchase_quantity` bigint(100) NOT NULL DEFAULT 0, `purchase_price` bigint(100) NOT NULL DEFAULT 0, `purchase_subtotal` bigint(100) NOT NULL DEFAULT 0 ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data untuk tabel `trx_purchase_details` -- INSERT INTO `trx_purchase_details` (`purchase_detail_id`, `trx_purchase_id`, `product_id`, `purchase_quantity`, `purchase_price`, `purchase_subtotal`) VALUES (7, 1, 1, 15, 20000, 0), (8, 1, 2, 40, 30000, 0); -- -- Trigger `trx_purchase_details` -- DELIMITER $$ CREATE TRIGGER `deletePurchase` AFTER DELETE ON `trx_purchase_details` FOR EACH ROW UPDATE products SET stock = stock-OLD.purchase_quantity WHERE product_id = OLD.product_id $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `purchasePrice` AFTER INSERT ON `trx_purchase_details` FOR EACH ROW UPDATE products SET purchase_price = NEW.purchase_price WHERE product_id = NEW.product_id $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `stockProducts` AFTER INSERT ON `trx_purchase_details` FOR EACH ROW UPDATE products SET stock = stock+NEW.purchase_quantity WHERE product_id = NEW.product_id $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `totalPurchase_afterDelete` AFTER DELETE ON `trx_purchase_details` FOR EACH ROW UPDATE trx_purchases SET total_purchase = total_purchase-OLD.purchase_subtotal WHERE trx_purchase_id = OLD.trx_purchase_id $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `totalPurchases` AFTER INSERT ON `trx_purchase_details` FOR EACH ROW UPDATE trx_purchases SET total_purchase = total_purchase+NEW.purchase_subtotal WHERE trx_purchase_id = NEW.trx_purchase_id $$ DELIMITER ; -- -------------------------------------------------------- -- -- Struktur dari tabel `trx_sales` -- CREATE TABLE `trx_sales` ( `trx_sale_id` bigint(100) UNSIGNED NOT NULL, `total_sale` bigint(100) NOT NULL DEFAULT 0, `sale_created_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data untuk tabel `trx_sales` -- INSERT INTO `trx_sales` (`trx_sale_id`, `total_sale`, `sale_created_at`) VALUES (3, 0, '2020-12-25 16:06:50'); -- -------------------------------------------------------- -- -- Struktur dari tabel `trx_sale_details` -- CREATE TABLE `trx_sale_details` ( `sale_detail_id` bigint(100) NOT NULL, `trx_sale_id` bigint(100) UNSIGNED DEFAULT NULL, `product_id` bigint(100) UNSIGNED DEFAULT NULL, `sale_quantity` bigint(100) NOT NULL DEFAULT 0, `sale_subtotal` bigint(100) NOT NULL DEFAULT 0 ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data untuk tabel `trx_sale_details` -- INSERT INTO `trx_sale_details` (`sale_detail_id`, `trx_sale_id`, `product_id`, `sale_quantity`, `sale_subtotal`) VALUES (4, 3, 1, 5, 0), (5, 3, 2, 9, 0); -- -- Trigger `trx_sale_details` -- DELIMITER $$ CREATE TRIGGER `deleteSale` AFTER DELETE ON `trx_sale_details` FOR EACH ROW UPDATE products SET stock = stock+OLD.sale_quantity WHERE product_id = OLD.product_id $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `stockAfterSale` AFTER INSERT ON `trx_sale_details` FOR EACH ROW UPDATE products SET stock = stock-NEW.sale_quantity WHERE product_id = NEW.product_id $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `totalSale_afterDelete` AFTER DELETE ON `trx_sale_details` FOR EACH ROW UPDATE trx_sales SET total_sale = total_sale+OLD.sale_subtotal WHERE trx_sale_id = OLD.trx_sale_id $$ DELIMITER ; DELIMITER $$ CREATE TRIGGER `totalSales` BEFORE INSERT ON `trx_sale_details` FOR EACH ROW UPDATE trx_sales SET total_sale = total_sale+NEW.sale_subtotal WHERE trx_sale_id = NEW.trx_sale_id $$ DELIMITER ; -- -------------------------------------------------------- -- -- Struktur dari tabel `users` -- CREATE TABLE `users` ( `user_id` bigint(100) NOT NULL, `username` varchar(100) NOT NULL, `password` varchar(255) NOT NULL, `user_created_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data untuk tabel `users` -- INSERT INTO `users` (`user_id`, `username`, `password`, `user_created_at`) VALUES (1, 'admin', '123', '2020-11-27 21:02:24'), (2, 'user', '123', '2020-11-27 21:02:24'); -- -- Indexes for dumped tables -- -- -- Indeks untuk tabel `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indeks untuk tabel `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`product_id`); -- -- Indeks untuk tabel `suppliers` -- ALTER TABLE `suppliers` ADD PRIMARY KEY (`supplier_id`); -- -- Indeks untuk tabel `trx_purchases` -- ALTER TABLE `trx_purchases` ADD PRIMARY KEY (`trx_purchase_id`), ADD KEY `trx_purchases_supplier_id_foreign` (`supplier_id`); -- -- Indeks untuk tabel `trx_purchase_details` -- ALTER TABLE `trx_purchase_details` ADD PRIMARY KEY (`purchase_detail_id`), ADD KEY `trx_purchase_details_trx_purchase_id_foreign` (`trx_purchase_id`), ADD KEY `trx_purchase_details_product_id_foreign` (`product_id`); -- -- Indeks untuk tabel `trx_sales` -- ALTER TABLE `trx_sales` ADD PRIMARY KEY (`trx_sale_id`); -- -- Indeks untuk tabel `trx_sale_details` -- ALTER TABLE `trx_sale_details` ADD PRIMARY KEY (`sale_detail_id`), ADD KEY `trx_sale_details_trx_sale_id_foreign` (`trx_sale_id`), ADD KEY `trx_sale_details_product_id_foreign` (`product_id`); -- -- Indeks untuk tabel `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`); -- -- AUTO_INCREMENT untuk tabel yang dibuang -- -- -- AUTO_INCREMENT untuk tabel `migrations` -- ALTER TABLE `migrations` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=175; -- -- AUTO_INCREMENT untuk tabel `products` -- ALTER TABLE `products` MODIFY `product_id` bigint(100) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT untuk tabel `suppliers` -- ALTER TABLE `suppliers` MODIFY `supplier_id` bigint(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT untuk tabel `trx_purchases` -- ALTER TABLE `trx_purchases` MODIFY `trx_purchase_id` bigint(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT untuk tabel `trx_purchase_details` -- ALTER TABLE `trx_purchase_details` MODIFY `purchase_detail_id` bigint(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT untuk tabel `trx_sales` -- ALTER TABLE `trx_sales` MODIFY `trx_sale_id` bigint(100) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT untuk tabel `trx_sale_details` -- ALTER TABLE `trx_sale_details` MODIFY `sale_detail_id` bigint(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT untuk tabel `users` -- ALTER TABLE `users` MODIFY `user_id` bigint(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- Ketidakleluasaan untuk tabel pelimpahan (Dumped Tables) -- -- -- Ketidakleluasaan untuk tabel `trx_purchases` -- ALTER TABLE `trx_purchases` ADD CONSTRAINT `trx_purchases_supplier_id_foreign` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`supplier_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ketidakleluasaan untuk tabel `trx_purchase_details` -- ALTER TABLE `trx_purchase_details` ADD CONSTRAINT `trx_purchase_details_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `trx_purchase_details_trx_purchase_id_foreign` FOREIGN KEY (`trx_purchase_id`) REFERENCES `trx_purchases` (`trx_purchase_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Ketidakleluasaan untuk tabel `trx_sale_details` -- ALTER TABLE `trx_sale_details` ADD CONSTRAINT `trx_sale_details_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `trx_sale_details_trx_sale_id_foreign` FOREIGN KEY (`trx_sale_id`) REFERENCES `trx_sales` (`trx_sale_id`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/app/Models/Supplier_model.php <?php namespace App\Models; use CodeIgniter\Model; class Supplier_model extends Model { protected $table = 'suppliers'; public function getSupplier($id = false) { if($id === false){ return $this->db->table($this->table)->get()->getResultArray(); }else{ return $this->db->table($this->table)->where(['supplier_id'=>$id])->get()->getRowArray(); } } public function insertSupplier($data) { return $this->db->table($this->table)->insert($data); } public function updateSupplier($data, $id) { return $this->db->table($this->table)->update($data, ['supplier_id'=>$id]); } public function deleteSupplier($id) { return $this->db->table($this->table)->delete(['supplier_id'=>$id]); } }<file_sep>/app/Controllers/Supplier.php <?php namespace App\Controllers; use CodeIgniter\Controller; use App\Models\Supplier_model; class Supplier extends Controller { public function __construct() { $this->model = new Supplier_model(); } public function index() { $data['suppliers'] = $this->model->getSupplier(); return view('supplier/index', $data); } public function create() { return view('supplier/create'); } public function store() { $validation = \Config\Services::validation(); $data = [ 'supplier_name'=>$this->request->getPost('supplier_name'), 'supplier_phone_number'=>$this->request->getPost('supplier_phone_number'), 'supplier_address'=>$this->request->getPost('supplier_address') ]; if($validation->run($data, 'supplier') == false){ session()->setFlashdata('errors', $validation->getErrors()); return redirect()->to(base_url('supplier/create')); }else{ $save = $this->model->insertSupplier($data); if($save){ session()->setFlashdata('success', 'Created'); return redirect()->to(base_url('supplier')); } } } public function edit($id) { $data['supplier'] = $this->model->getSupplier($id); return view('supplier/edit', $data); } public function update() { $validation = \Config\Services::validation(); $id = $this->request->getPost('supplier_id'); $data = [ 'supplier_name'=>$this->request->getPost('supplier_name'), 'supplier_phone_number'=>$this->request->getPost('supplier_phone_number'), 'supplier_address'=>$this->request->getPost('supplier_address') ]; if($validation->run($data, 'supplier') == false){ session()->setFlashdata('errors', $validation->getErrors()); return redirect()->to(base_url('supplier/ceate')); }else{ $update = $this->model->updateSupplier($data, $id); if($update){ session()->setFlashdata('info', 'Updated'); return redirect()->to(base_url('supplier')); } } } public function delete($id) { $delete = $this->model->deleteSupplier($id); if($delete){ session()->setFlashdata('warning', 'Deleted'); return redirect()->to(base_url('supplier')); } } }<file_sep>/app/Views/report/index.php <?= view('templates/header'); ?> <?= view('templates/sidebar'); ?> <div class="content-wrapper"> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Report</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"> <a href="#">Home</a> </li> <li class="breadcrumb-item active">Report</li> </ol> </div> </div> </div> </div> <div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-header"> List Report <a href="<?= base_url('purchase/create'); ?>" class="btn btn-primary float-right">Tambah</a> </div> <div class="card-body"> <?php if(!empty(session()->getFlashdata('success'))): ?> <div class="alert alert-success"> <?= session()->getFlashdata('success'); ?> </div> <?php endif;?> <?php if(!empty(session()->getFlashdata('info'))): ?> <div class="alert alert-info"> <?= session()->getFlashdata('info'); ?> </div> <?php endif;?> <?php if(!empty(session()->getFlashdata('warning'))): ?> <div class="alert alert-warning"> <?= session()->getFlashdata('warning'); ?> </div> <?php endif;?> </div> </div> </div> </div> </div> </div> </div> <?= view('templates/footer'); ?><file_sep>/app/Models/SaleDetail_model.php <?php namespace App\Models; use CodeIgniter\Model; class SaleDetail_model extends Model { protected $table = 'trx_sale_details'; public function getSaleDetail($id) { return $this->db->table($this->table)->join('trx_sales', 'trx_sales.trx_sale_id = trx_sale_details.trx_sale_id', 'CASCADE', 'CASCADE')->join('products', 'products.product_id = trx_sale_details.product_id', 'CASCADE', 'CASCADE', 'full')->where('trx_sale_details.trx_sale_id', $id)->get()->getResultArray(); } public function insertSaleDetail($data) { return $this->db->table($this->table)->insert($data); } public function deleteSaleDetail($id) { return $this->db->table($this->table)->delete(['sale_detail_id'=>$id]); } }<file_sep>/app/Controllers/Report.php <?php namespace App\Controllers; use CodeIgniter\Controller; use App\Models\Purchase_model; use App\Models\PurchaseDetail_model; use App\Models\Sale_model; use App\Models\SaleDetail_model; use App\Models\Product_model; use App\Models\Supplier_model; class Report extends Controller { public function __construct() { $this->purchase = new Purchase_model(); $this->purchaseDetail = new PurchaseDetail_model(); $this->sale = new Sale_model(); $this->saleDetail = new SaleDetail_model(); $this->product = new Product_model(); $this->supplier = new Supplier_model(); } public function index() { return view('report/index'); } }<file_sep>/app/Views/purchase/show.php <?= view('templates/header'); ?> <?= view('templates/sidebar'); ?> <div class="content-wrapper"> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Detail Purchase</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"> <a href="#">Home</a> </li> <li class="breadcrumb-item"> <a href="#">Purchases</a> </li> <li class="breadcrumb-item active">Detail Purchase</li> </ol> </div> </div> </div> </div> <div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered table-hovered"> <thead> <th>Purchase Id</th> <th>Supplier</th> <th>Total Purchase</th> <th>Created At</th> </thead> <tbody> <tr> <td><?= $purchase['trx_purchase_id']; ?></td> <td><?= $purchase['supplier_name']; ?></td> <td><?= "Rp.".number_format($purchase['total_purchase']); ?></td> <td><?= $purchase['purchase_created_at']; ?></td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="col-md-12"> <div class="card"> <div class="card-header"> Produk Pembelian <button type="button" class="btn btn-primary float-right" data-toggle="modal" data-target="#createPesanan"> Tambah Pembelian </button> </div> <div class="card-body"> <div class="table-responsive"> <?php if(!empty(session()->getFlashdata('success'))): ?> <div class="alert alert-success"> <?= session()->getFlashdata('success'); ?> </div> <?php endif;?> <?php if(!empty(session()->getFlashdata('info'))): ?> <div class="alert alert-info"> <?= session()->getFlashdata('info'); ?> </div> <?php endif;?> <?php if(!empty(session()->getFlashdata('warning'))): ?> <div class="alert alert-warning"> <?= session()->getFlashdata('warning'); ?> </div> <?php endif;?> <table class="table table-bordered table-hovered"> <thead> <th width="10px" class="text-center">#</th> <th>Product</th> <th>Quantity</th> <th>Price</th> <th>Subtotal</th> <th>Action</th> </thead> <tbody> <input type="hidden" name="trx_purchase_id" value="<?= $purchase['trx_purchase_id']; ?>"> <?php $no=0; foreach($purchaseDetail as $key=>$row): ?> <tr> <td class="text-center"><?= ++$no; ?></td> <td><?= $row['product_name']; ?></td> <td><?= $row['purchase_quantity']; ?></td> <td><?= "Rp.".number_format($row['purchase_price']); ?></td> <td><?= $row['purchase_subtotal']; ?></td> <td class="text-center"> <a href="<?= base_url('purchase/edit/'.$row['purchase_detail_id']); ?>" class="btn btn-sm btn-success"> <li class="fa fa-edit"></li> </a> <a href="<?= base_url('purchase/deletePurchase/'.$row['purchase_detail_id']); ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin???');"> <li class="fa fa-trash-alt"></li> </a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </div> <?= view('templates/footer'); ?> <!-- Modal --> <div class="modal fade" id="createPesanan" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Tambah Pesanan</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="<?= base_url('purchase/storePurchase'); ?>" method="post"> <input type="hidden" name="trx_purchase_id" value="<?= $purchase['trx_purchase_id']; ?>"> <div class="form-group"> <label>Product</label> <select name="product_id" class="form-control"> <?php foreach($products as $p): ?> <option value="<?= $p['product_id']; ?>"><?= $p['product_name']; ?></option> <?php endforeach; ?> </select> </div> <div class="form-group"> <label>Quantity</label> <input type="number" name="purchase_quantity" class="form-control"> </div> <div class="form-group"> <label>Price</label> <input type="number" name="purchase_price" class="form-control"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary float-right">Add</button> </form> </div> </div> </div> </div><file_sep>/app/Database/Migrations/2020-11-25-024217_trx_sales.php <?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; class TrxSales extends Migration { public function up() { $this->db->enableForeignKeyChecks(); $this->forge->addField([ 'trx_sale_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'unsigned'=>true, 'auto_increment'=>true ], 'total_sale' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ], 'sale_created_at'=>[ 'type'=>'DATETIME', 'null'=>true ] ]); $this->forge->addKey('trx_sale_id', true); $this->forge->createTable('trx_sales'); } //-------------------------------------------------------------------- public function down() { $this->forge->dropTable('trx_sales', true); } } <file_sep>/app/Database/Migrations/2020-11-25-030603_trx_purchases.php <?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; class TrxPurchases extends Migration { public function up() { $this->db->enableForeignKeyChecks(); $this->forge->addField([ 'trx_purchase_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'auto_increment'=>true ], 'supplier_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'null'=>true ], 'total_purchase' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ], 'purchase_created_at' => [ 'type'=>'DATETIME', 'null'=>true ] ]); $this->forge->addKey('trx_purchase_id', true); $this->forge->addForeignKey('supplier_id', 'suppliers', 'supplier_id', 'CASCADE', 'CASCADE'); $this->forge->createTable('trx_purchases'); } //-------------------------------------------------------------------- public function down() { $this->forge->dropTable('trx_purchases', true); } } <file_sep>/app/Models/PurchaseDetail_model.php <?php namespace App\Models; use CodeIgniter\Model; class PurchaseDetail_model extends Model { protected $table = 'trx_purchase_details'; public function getPurchaseDetail($id = false) { if($id === false){ return $this->db->table($this->table)->join('trx_purchases', 'trx_purchases.trx_purchase_id = trx_purchase_details.trx_purchase_id', 'CASCADE', 'CASCADE')->join('products', 'products.product_id = trx_purchase_details.product_id', 'CASCADE', 'CASCADE')->get()->getResultArray(); }else{ return $this->db->table($this->table)->join('trx_purchases', 'trx_purchases.trx_purchase_id = trx_purchase_details.trx_purchase_id', 'CASCADE', 'CASCADE')->join('products', 'products.product_id = trx_purchase_details.product_id', 'CASCADE', 'CASCADE')->where('trx_purchase_details.trx_purchase_id', $id)->get()->getResultArray(); } } public function insertPurchaseDetail($data) { return $this->db->table($this->table)->insert($data); } public function deletePurchaseDetail($id) { return $this->db->table($this->table)->delete(['purchase_detail_id'=>$id]); } }<file_sep>/app/Database/Migrations/2020-11-25-021741_products.php <?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; class Products extends Migration { public function up() { $this->db->enableForeignKeyChecks(); $this->forge->addField([ 'product_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'unsigned'=>true, 'auto_increment'=>true ], 'product_code' => [ 'type'=>'VARCHAR', 'constraint'=>'100', 'null'=>true ], 'product_name' => [ 'type'=>'VARCHAR', 'constraint'=>'100', 'null'=>true ], 'purchase_price' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ], 'sale_price' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ], 'stock' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ], 'product_description' => [ 'type'=>'TEXT', 'null'=>true ] ]); $this->forge->addKey('product_id', true); // $this->forge->addForeignKey('category_id', 'categories', 'category_id', 'CASCADE', 'CASCADE'); $this->forge->createTable('products'); } //-------------------------------------------------------------------- public function down() { $this->forge->dropTable('products', true); } } <file_sep>/app/Database/Seeds/UserSeeder.php <?php namespace App\Database\Seeds; class UserSeeder extends \CodeIgniter\Database\Seeder { public function run() { $data1 = [ 'username'=>'admin', 'password'=>'123', 'user_created_at'=>date('Y-m-d H:i:s') ]; $data2 = [ 'username'=>'user', 'password'=>'123', 'user_created_at'=>date('Y-m-d H:i:s') ]; $this->db->table('users')->insert($data1); $this->db->table('users')->insert($data2); } }<file_sep>/app/Controllers/Product.php <?php namespace App\Controllers; use CodeIgniter\Controller; use App\Models\Product_model; class Product extends Controller { public function __construct() { $this->model = new Product_model(); } public function index() { $data['products'] = $this->model->getProduct(); return view('product/index', $data); } public function create() { return view('product/create'); } public function store() { $validation = \Config\Services::validation(); $data = [ 'product_code'=>$this->request->getPost('product_code'), 'product_name'=>$this->request->getPost('product_name'), 'sale_price'=>$this->request->getPost('sale_price'), 'stock'=>$this->request->getPost('stock'), 'product_description'=>$this->request->getPost('product_description') ]; if($validation->run($data, 'product') == false){ session()->setFlashdata('errors', $validation->getErrors()); return redirect()->to(base_url('product/create')); }else{ $save = $this->model->insertProduct($data); if($save){ session()->setFlashdata('success', 'Created'); return redirect()->to(base_url('product')); } } } public function edit($id) { $data['product'] = $this->model->getProduct($id); return view('product/edit', $data); } public function update() { $validation = \Config\Services::validation(); $id = $this->request->getPost('product_id'); $data = [ 'product_code'=>$this->request->getPost('product_code'), 'product_name'=>$this->request->getPost('product_name'), 'sale_price'=>$this->request->getPost('sale_price'), 'stock'=>$this->request->getPost('stock'), 'product_description'=>$this->request->getPost('product_description') ]; if($validation->run($data, 'product') == false){ session()->setFlashdata('errors', $validation->getErrors()); return redirect()->to(base_url('product/edit')); }else{ $update = $this->model->updateProduct($data, $id); if($update){ session()->setFlashdata('info', 'Updatedd'); return redirect()->to(base_url('product')); } } } public function delete($id) { $delete = $this->model->deleteProduct($id); if($delete){ session()->setFlashdata('warning', 'Deleted'); return redirect()->to(base_url('product')); } } }<file_sep>/app/Models/Purchase_model.php <?php namespace App\Models; use CodeIgniter\Model; class Purchase_model extends Model { protected $table = 'trx_purchases'; public function getPurchase($id = false) { if($id === false){ return $this->db->table($this->table)->join('suppliers', 'suppliers.supplier_id = trx_purchases.supplier_id', 'CASCADE', 'cascade')->get()->getResultArray(); }else{ return $this->db->table($this->table)->join('suppliers', 'suppliers.supplier_id = trx_purchases.supplier_id', 'CASCADE', 'CASCADE')->where(['trx_purchases.trx_purchase_id'=>$id])->get()->getRowArray(); } } public function insertPurchase($data) { return $this->db->table($this->table)->insert($data); } public function deletePurchase($id) { return $this->db->table($this->table)->delete(['purchase_id'=>$id]); } } <file_sep>/app/Models/Sale_model.php <?php namespace App\Models; use CodeIgniter\Model; class Sale_model extends Model { protected $table = 'trx_sales'; public function getSale($id = false) { if($id === false){ return $this->db->table($this->table)->get()->getResultArray(); }else{ return $this->db->table($this->table)->where('trx_sale_id', $id)->get()->getRowArray(); } } public function insertSale($data) { return $this->db->table($this->table)->insert($data); } public function deleteSale($id) { return $this->db->table($this->table)->delete(['trx_sale_id'=>$id]); } }<file_sep>/app/Database/Migrations/2020-11-25-025249_trx_sale_details.php <?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; class TrxSaleDetails extends Migration { public function up() { $this->db->enableForeignKeyChecks(); $this->forge->addField([ 'sale_detail_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'auto_increment'=>true ], 'trx_sale_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'null'=>true, 'unsigned'=>true ], 'product_id' => [ 'type'=>'BIGINT', 'constraint'=>100, 'null'=>true, 'unsigned'=>true ], 'sale_quantity' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ], 'sale_subtotal' => [ 'type'=>'BIGINT', 'constraint'=>100, 'default'=>0 ] ]); $this->forge->addKey('sale_detail_id', true); $this->forge->addForeignKey('trx_sale_id', 'trx_sales', 'trx_sale_id', 'CASCADE', 'CASCADE'); $this->forge->addForeignKey('product_id', 'products', 'product_id', 'CASCADE', 'CASCADE'); $this->forge->createTable('trx_sale_details'); } //-------------------------------------------------------------------- public function down() { $this->forge->dropTable('trx_sale_details', true); } } <file_sep>/app/Database/Seeds/ProductSeeder.php <?php namespace App\Database\Seeds; class ProductSeeder extends \CodeIgniter\Database\Seeder { public function run() { $data1 = [ 'product_code'=>'1q2w3e', 'product_name'=>'T-Shirt', 'purchase_price'=>0, 'sale_price'=>0, 'stock'=>0, 'product_description'=>'All Size' ]; $data2 = [ 'product_code'=>'4e5r6t', 'product_name'=>'Hoodie', 'purchase_price'=>0, 'sale_price'=>0, 'stock'=>0, 'product_description'=>'All Size' ]; $this->db->table('products')->insert($data1); $this->db->table('products')->insert($data2); } }
18daf939efd7be9ca8fda2d57bacefa540605908
[ "SQL", "PHP" ]
25
SQL
rezadim/pos
ccaf2020553528c190b2a7a549d945b8a515dc92
8300173401d96e80a65c62e6b8b5e48f6efe362a
refs/heads/master
<file_sep>package com.epam.train; import java.util.ArrayList; import java.util.List; public class Train { private List<Carriage> train = new ArrayList<Carriage>(); public Train() { this.train.add(Carriage.LOCOMOTIVE); } public void add(Carriage carriage) { this.train.add(carriage); } public void add(Carriage carriage, int count) { for (int i = 0; i < count; i++) this.train.add(carriage); } public void remove(Carriage carriage) { this.train.remove(carriage); } public void removeAll(Carriage carriage) { ArrayList<Carriage> temp = (ArrayList<Carriage>) this.train; ArrayList<Carriage> trainClone = (ArrayList<Carriage>) temp.clone(); for (Carriage i : this.train) { if (i.equals(carriage)) trainClone.remove(i); } this.train = trainClone; } public int getWeight() { int weight = 0; for (Carriage i : this.train) { weight += i.getWeight(); } return weight; } public int getForce() { int force = 0; for (Carriage i : this.train) { force += i.getForce(); } return force; } public int length() { return this.train.size(); } } <file_sep>package com.epam.train; public class Main { public static void main(String[] args) { Train train = new Train(); train.add(Carriage.COUPE, 20); TrainStation trainStation = new TrainStation(); System.out.println(trainStation.canLet(train)); } } <file_sep>package com.epam.train; public class TrainStation { private double resistance; private double minSpeedUp; public TrainStation() { this.resistance = 0.1; this.minSpeedUp = 0.01; } public TrainStation(double resistance, double minSpeedUp) { this.resistance = resistance; this.minSpeedUp = minSpeedUp; } public boolean canLet(Train train) { double weight = train.getWeight(); double force = train.getForce(); double speedUp = (force - weight*this.resistance)/weight; String message = (speedUp > this.minSpeedUp? "Success: " : "Fail: ") + "speed-up = %.4f m/s^2\n"; System.out.printf(message, speedUp); return speedUp > this.minSpeedUp; } public void setMinSpeedUp(double minSpeedUp) { this.minSpeedUp = minSpeedUp; } public void setResistance(double resistance) { this.resistance = resistance; } public double getMinSpeedUp() { return minSpeedUp; } public double getResistance() { return resistance; } }
93f9a95fd9f12fc9a2043961fc2046243984c210
[ "Java" ]
3
Java
OnjeyGray/Train
3252d289ce9fec34de03df2e5858d36e10808663
85a8acd7da75014c80166e31c6039601cea97b6b
refs/heads/main
<file_sep>#!/usr/bin/env python import rospy import threading from std_msgs.msg import Float64, String from geometry_msgs.msg import Pose from numpy import sign class transControlNode(): def __init__(self): rospy.init_node("trans_control") self.data_lock = threading.RLock() self.strategy = "follow" self.control_frequency = 20.0 rospy.Timer(rospy.Duration(1.0/self.control_frequency), self.trans_control) self.vorsteuerung = -0.05 # Parameter static self.xy_p_gain = 0.21 self.xy_i_gain = 0.16 self.xy_d_gain = 0.1 # Dynamic Parameter self.vertical_p_gain = 0.375 self.vertical_i_gain = 0.09 self.vertical_d_gain = 0.1 self.setpoint_buf_len = 5 self.i_buf_len = 20 self.i_buf = Pose() self.i_buf.position.x = [0.0] * self.i_buf_len self.i_buf.position.y = [0.0] * self.i_buf_len self.i_buf.position.z = [0.0] * self.i_buf_len self.setpoint_buf = Pose() self.setpoint_buf.position.x = [0.0] * self.setpoint_buf_len self.setpoint_buf.position.y = [0.0] * self.setpoint_buf_len self.setpoint_buf.position.z = [0.0] * self.setpoint_buf_len self.pos_setpoint = Pose() self.pos_setpoint.position.x = 0.0 self.pos_setpoint.position.y = 0.0 self.pos_setpoint.position.z = -0.5 self.pos = self.pos_setpoint self.sensor_time = rospy.get_time() # rospy.loginfo(self.setpoint_buf.position.x) # rospy.loginfo(self.i_buf.position.z) self.thrust = 0.0 self.vertical_thrust = 0.0 self.lateral_thrust = 0.0 self.thrust_pub = rospy.Publisher("thrust", Float64, queue_size=1) self.vertical_thrust_pub = rospy.Publisher("vertical_thrust", Float64, queue_size=1) self.lateral_thrust_pub = rospy.Publisher("lateral_thrust", Float64, queue_size=1) self.setpoint_sub = rospy.Subscriber("pos_setpoint", Pose, self.on_setpoint, queue_size=1) self.pos_sub = rospy.Subscriber("robot_pos", Pose, self.pos_callback, queue_size=1) self.depth_sub = rospy.Subscriber("depth", Float64, self.depth_callback, queue_size=1) self.strategy_sub = rospy.Subscriber("strategy", String, self.strategy_callback, queue_size=1) # Reconfigure Options via subscriber self.kp_dyn_sub = rospy.Subscriber("kp_xy", Float64, self.kp_xy_callback, queue_size=1) self.ki_dyn_sub = rospy.Subscriber("ki_xy", Float64, self.ki_xy_callback, queue_size=1) self.kd_dyn_sub = rospy.Subscriber("kd_xy", Float64, self.kd_xy_callback, queue_size=1) # Reconfigure Options via subscriber self.kp_sta_sub = rospy.Subscriber("kp_vert", Float64, self.kp_vert_callback, queue_size=1) self.ki_sta_sub = rospy.Subscriber("ki_vert", Float64, self.ki_vert_callback, queue_size=1) self.kd_sta_sub = rospy.Subscriber("kd_vert", Float64, self.kd_vert_callback, queue_size=1) self.vor_static_sub = rospy.Subscriber("vor", Float64, self.vor_callback, queue_size=1) def strategy_callback(self, msg): self.strategy = msg.data #self.trans_control() def kp_xy_callback(self, msg): with self.data_lock: if msg.data >= 0: self.xy_p_gain = msg.data else: rospy.logwarn("Received negative Kp") def ki_xy_callback(self, msg): with self.data_lock: if msg.data >= 0: self.xy_i_gain = msg.data else: rospy.logwarn("Received negative Ki") def kd_xy_callback(self, msg): with self.data_lock: if msg.data >= 0: self.xy_d_gain = msg.data else: rospy.logwarn("Received negative Kd") def kp_vert_callback(self, msg): with self.data_lock: if msg.data >= 0: self.vertical_p_gain = msg.data else: rospy.logwarn("Received negative dyn Kp") def ki_vert_callback(self, msg): with self.data_lock: if msg.data >= 0: self.vertical_i_gain = msg.data else: rospy.logwarn("Received negative dyn Ki") def kd_vert_callback(self, msg): with self.data_lock: if msg.data >= 0: self.vertical_d_gain = msg.data else: rospy.logwarn("Received self.vertical_thrustnegative dyn Kd") def vor_callback(self, msg): with self.data_lock: self.vorsteuerung = msg.data def on_setpoint(self, msg): with self.data_lock: # if not self.isRegion(msg.position): self.pos_setpoint = msg self.setpoint_buf.position = self.setBuffer(self.setpoint_buf.position, self.pos_setpoint.position, self.setpoint_buf_len) #self.trans_control() def pos_callback(self, msg): with self.data_lock: self.pos.position.x = msg.position.x self.pos.position.y = msg.position.y # self.pos.position.z = msg.position.z self.sensor_time = rospy.get_time() #self.trans_control() def depth_callback(self, msg): with self.data_lock: self.pos.position.z = msg.data # self.sensor_time = rospy.get_time() #self.trans_control() def setBuffer(self, buf, msgAppend, len): for i in range(0, len-1): buf.x[i] = buf.x[i+1] for i in range(0, len-1): buf.y[i] = buf.y[i+1] for i in range(0, len-1): buf.z[i] = buf.z[i+1] buf.x[-1] = msgAppend.x buf.y[-1] = msgAppend.y buf.z[-1] = msgAppend.z return buf def publish(self): # rospy.loginfo("Hallo") msg_thrust = Float64() msg_thrust.data = self.thrust self.thrust_pub.publish(msg_thrust) msg_vertical_thrust = Float64() msg_vertical_thrust.data = self.vertical_thrust self.vertical_thrust_pub.publish(msg_vertical_thrust) msg_lateral_thrust = Float64() msg_lateral_thrust.data = self.lateral_thrust self.lateral_thrust_pub.publish(msg_lateral_thrust) def trans_control(self, *args): if rospy.get_time() - self.sensor_time > 5: rospy.logwarn("Sensor Timeout") self.thrust = 0.0 self.setGains(self.setpoint_buf.position.z) self.vertical_thrust = self.getThrust(self.pos.position.z, self.pos_setpoint.position.z, self.i_buf.position.z, True) self.lateral_thrust = 0.0 self.publish() return elif self.strategy == "search": # rospy.loginfo("searching") self.thrust = 0.0 self.vertical_thrust = self.vorsteuerung self.lateral_thrust = 0.0 self.publish() return # rospy.loginfo("following") i_buf_Append = Pose() i_buf_Append.position.x = self.pos_setpoint.position.x - self.pos.position.x i_buf_Append.position.y = self.pos_setpoint.position.y - self.pos.position.y i_buf_Append.position.z = self.pos_setpoint.position.z - self.pos.position.z self.i_buf.position = self.setBuffer(self.i_buf.position, i_buf_Append.position, self.i_buf_len) """ if sign(self.i_buf) == sign(self.i_buf): i_buf_tmp = [j for j in self.i_buf] else: i_buf_tmp = [0 for j in self.i_buf] """ # rospy.loginfo("following") self.setGains(True) # rospy.loginfo(self.pos_setpoint.position) self.lateral_thrust = -self.getThrust(self.pos.position.x, self.pos_setpoint.position.x, self.i_buf.position.x, False) self.setGains(True) self.thrust = self.getThrust(self.pos.position.y, self.pos_setpoint.position.y, self.i_buf.position.y, False) self.setGains(False) self.vertical_thrust = self.getThrust(self.pos.position.z, self.pos_setpoint.position.z, self.i_buf.position.z, True) """ if self.isRegion(self.pos.position.z) == 1: self.vertical_thrust = -0.4 elif self.isRegion(self.pos.position.z) == -1: self.vertical_thrust = 0.4 """ self.publish() def getThrust(self, pos, setpoint, i_buf, vor_activate): thrust = (self.act_p_gain * (setpoint - pos) + self.act_i_gain * sum(i_buf) * (1.0/self.control_frequency) + self.act_d_gain * (i_buf[-1] - i_buf[-2])) if vor_activate: thrust += self.vorsteuerung if abs(thrust) > 1: thrust = sign(thrust) return thrust def isRegion(self, setpoint): if setpoint.z > -0.1 or setpoint.x > 0.1 or setpoint.y > 0.1: return 1 elif setpoint.z < -0.8 or setpoint.x < 1.9 or setpoint.y < 3.2: return -1 else: return 0 def setGains(self, dirXY): if dirXY: self.act_p_gain = self.xy_p_gain self.act_i_gain = self.xy_i_gain self.act_d_gain = self.xy_d_gain else: self.act_p_gain = self.vertical_p_gain self.act_i_gain = self.vertical_i_gain self.act_d_gain = self.vertical_d_gain def publish(self): # rospy.loginfo("Hallo") msg_thrust = Float64() msg_thrust.data = self.thrust self.thrust_pub.publish(msg_thrust) msg_vertical_thrust = Float64() msg_vertical_thrust.data = self.vertical_thrust self.vertical_thrust_pub.publish(msg_vertical_thrust) msg_lateral_thrust = Float64() msg_lateral_thrust.data = self.lateral_thrust self.lateral_thrust_pub.publish(msg_lateral_thrust) def run(self): rospy.spin() def main(): node = transControlNode() node.run() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy import numpy as np import threading from std_msgs.msg import Int16, String from mavros_msgs.srv import CommandBool from geometry_msgs.msg import Pose class strategyNode(): def __init__(self): rospy.init_node("strategy_planer") self.data_lock = threading.RLock() self.tagNumber = 0 self.tag_threshold = 3 self.pos_threshold = 0.1 self.pos_threshold_y= 0.1 self.actual_pos = np.array([10.0, 10.0, 10.0]) self.lock = False self.strategy_pub = rospy.Publisher("strategy", String, queue_size=1) self.setpoint_sub = rospy.Subscriber("number_tags", Int16, self.tag_callback, queue_size=1) self.doArm = rospy.get_param("~doArm", False) if self.doArm: self.arm_vehicle() self.setpoint_sub = rospy.Subscriber("ring_pos", Pose, self.pos_callback, queue_size=1) self.strategy_frequency = 5.0 rospy.Timer(rospy.Duration(1.0/self.strategy_frequency), self.update_strategy) def tag_callback(self, msg): # with self.data_lock: self.tagNumber = msg.data def pos_callback(self, msg): #with self.data_lock: self.actual_pos[0] = msg.position.x self.actual_pos[1] = msg.position.y self.actual_pos[2] = msg.position.z def update_strategy(self, *args): msg = String() if self.lock: msg.data = "rescue" self.strategy_pub.publish(msg) return if self.tagNumber < self.tag_threshold: msg.data = "search" elif abs(self.actual_pos[0]) > self.pos_threshold or abs(self.actual_pos[2]) > self.pos_threshold: msg.data = "approach" elif self.actual_pos[1] > self.pos_threshold_y: msg.data = "stich" else: msg.data = "rescue" self.lock = True self.strategy_pub.publish(msg) def arm_vehicle(self): # wait until the arming serivce becomes available rospy.wait_for_service("mavros/cmd/arming") # connect to the service arm = rospy.ServiceProxy("mavros/cmd/arming", CommandBool) # call the service to arm the vehicle until call was successfull while not arm(True).success: rospy.logwarn("Could not arm vehicle. Keep trying.") rospy.sleep(1.0) rospy.loginfo("Armed successfully.") def run(self): rospy.spin() def main(): node = strategyNode() node.run() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy from std_msgs.msg import Float64 import numpy as np class DepthSetpointNode(): def __init__(self): rospy.init_node("depth_setpoints") self.setpoint_pub = rospy.Publisher("depth_setpoint", Float64, queue_size=1) def run(self): mode = 'step' if mode == 'const': rate = rospy.Rate(50.0) while not rospy.is_shutdown(): msg = Float64() # fill msg with example setpoint msg.data = -0.5 self.setpoint_pub.publish(msg) rate.sleep() elif mode == 'sin': rate = rospy.Rate(10.0) while not rospy.is_shutdown(): xs = np.linspace(0, 2*np.pi, num=200) for x in xs: msg = Float64() # fill msg with example setpoint msg.data = 0.2*np.sin(x) - 0.4 self.setpoint_pub.publish(msg) rate.sleep() elif mode == 'step': rate = rospy.Rate(5.0) while not rospy.is_shutdown(): xs = np.linspace(0, 2*np.pi, num=200) for x in xs: msg = Float64() # fill msg with example setpoint msg.data = 0.4*float(x < np.pi) - 0.6 self.setpoint_pub.publish(msg) rate.sleep() else: pass # TODO: add ros logger error def main(): node = DepthSetpointNode() node.run() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy from std_msgs.msg import Float64 from sensor_msgs.msg import FluidPressure depth_buf = [-0.5] * 5 depth_buf_len = 5 def pressure_callback(msg, depth_pub): pascal_per_meter = 9.81*1000.0 depth_tmp = - (msg.fluid_pressure - 101325) / pascal_per_meter depth_buf.append(depth_tmp) if len(depth_buf) > depth_buf_len: depth_buf.pop(0) depth = sum(depth_buf) / len(depth_buf) depth_msg = Float64() # depth_raw_msg = Float64() # depth_msg.data = depth depth_msg.data = depth # offset, water level is zero # depth_raw_msg.data = depth_tmp + 10 depth_pub.publish(depth_msg) # depth_raw_pub.publish(depth_raw_msg) def main(): rospy.init_node("depth_calculator") depth_pub = rospy.Publisher("depth", Float64, queue_size=1) # depth_raw_pub = rospy.Publisher("depth_raw", Float64, queue_size=1) rospy.Subscriber("pressure", FluidPressure, pressure_callback, (depth_pub)) rospy.spin() if __name__ == "__main__": main() <file_sep>#pragma once #include <range_sensor/RangeMeasurement.h> #include <range_sensor/RangeMeasurementArray.h> #include <ros/ros.h> #include <gazebo/common/Plugin.hh> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <ignition/math.hh> #include <sdf/sdf.hh> #include <vector> namespace gazebo { static constexpr auto kDefaultPubRate = 7.0; static constexpr auto kDefaultRangesTopic = "tag_detections_sim"; static constexpr auto kDefaultRangesNoise = 0.1; static constexpr auto kDefaultFov = 90; static constexpr auto kDefaultViewingAngle = 140; static constexpr auto kDefaultDropProb = 0.05; static constexpr auto kDefaultMaxDetectionDist = 5.0; static constexpr auto kDefaultDistDropProbExponent = 2.0; class RangesPlugin : public ModelPlugin { public: RangesPlugin(); virtual ~RangesPlugin(); protected: virtual void Load(physics::ModelPtr model, sdf::ElementPtr sdf); virtual void OnUpdate(const common::UpdateInfo &); void getSdfParams(sdf::ElementPtr sdf); range_sensor::RangeMeasurement GetRangeMsg( int id, ignition::math::Vector3d sensor_to_tag); bool IsDetected(ignition::math::Vector3d sensor_to_tag, ignition::math::Vector3d body_x_axis); bool IsDetected_bottom(ignition::math::Vector3d sensor_to_tag, ignition::math::Vector3d body_z_axis); double GetDistanceDropProp(double dist); private: std::string namespace_; physics::ModelPtr model_; physics::WorldPtr world_; event::ConnectionPtr update_connection_; std::string ranges_topic_; double range_noise_std_; double max_fov_angle_; double max_viewing_angle_; double drop_prob_; double max_detection_dist_; double dist_drop_prob_exponent_; ros::NodeHandle *node_handle_; ros::Publisher ranges_pub_; double pub_rate_; std::default_random_engine random_generator_; std::normal_distribution<double> standard_normal_distribution_; std::uniform_real_distribution<double> uniform_real_distribution_; common::Time last_pub_time_; common::Time last_time_; ignition::math::Vector3d pos_tag_1_; ignition::math::Vector3d pos_tag_2_; ignition::math::Vector3d pos_tag_3_; ignition::math::Vector3d pos_tag_4_; ignition::math::Vector3d tag_axis_; ignition::math::Vector3d tag_axis_bottom_; bool initialized_; std::vector<ignition::math::Vector3d> floor_tags_; }; } // namespace gazebo <file_sep>#!/usr/bin/env python import rospy from std_msgs.msg import Float64, Int16 from geometry_msgs.msg import Pose from nav_msgs.msg import Odometry class groundTruthTestNode(): def __init__(self): rospy.init_node("ground_truth_compare") self.pos = Pose() self.pos.position.x = 0.0 self.pos.position.y = 0.0 self.pos.position.z = 0.0 self.pos.orientation.x = 0.0 self.pos.orientation.y = 0.0 self.pos.orientation.z = 0.0 self.pos.orientation.w = 0.0 self.number_tags = 4 self.range_sub = rospy.Subscriber("/ground_truth/state", Odometry, self.posCallback, queue_size=1) self.pos_pub = rospy.Publisher("robot_pos", Pose, queue_size=1) self.err_x_pub = rospy.Publisher("pos_err_x", Float64, queue_size=1) self.err_y_pub = rospy.Publisher("pos_err_y", Float64, queue_size=1) self.err_z_pub = rospy.Publisher("pos_err_z", Float64, queue_size=1) self.tag_pub = rospy.Publisher("number_tags", Int16, queue_size=1) def posCallback(self, msg): # rospy.loginfo("Hallo1") self.pos.position.x = msg.pose.pose.position.x self.pos.position.y = msg.pose.pose.position.y self.pos.position.z = msg.pose.pose.position.z self.pos.orientation.x = msg.pose.pose.orientation.x self.pos.orientation.y = msg.pose.pose.orientation.y self.pos.orientation.z = msg.pose.pose.orientation.z self.pos.orientation.w = msg.pose.pose.orientation.w self.pos_pub.publish(self.pos) msg = Int16() msg.data = self.number_tags self.tag_pub.publish(msg) def run(self): rospy.spin() def main(): rospy.loginfo("Hallo0") node = groundTruthTestNode() node.run() if __name__ == "__main__": main() <file_sep>cmake_minimum_required(VERSION 3.0.2) project(depth_controller) find_package(catkin REQUIRED COMPONENTS message_generation std_msgs ) # add_message_files( # FILES # ) # generate_messages( # DEPENDENCIES # std_msgs #) catkin_package( # INCLUDE_DIRS include # LIBRARIES depth_controller # CATKIN_DEPENDS other_catkin_pkg # DEPENDS system_lib ) include_directories( # include # ${catkin_INCLUDE_DIRS} ) <file_sep>#!/usr/bin/env python import tf.transformations as tf import numpy as np import rospy from nav_msgs.msg import Odometry from geometry_msgs.msg import PoseWithCovarianceStamped, Vector3 class YawTranslator(): def __init__(self): rospy.init_node("yaw_translator") self.pose_sub = rospy.Subscriber("/ground_truth/state", Odometry, self.simCallback, queue_size=1) self.angle_pub = rospy.Publisher("/nav_controller/angle", Vector3, queue_size=1) self.angle = Vector3() self.angle.x = 0.0 self.angle.y = 0.0 self.angle.z = 0.0 def simCallback(self, msg): orient = msg.pose.pose.orientation quat = np.array([orient.x, orient.y, orient.z, orient.w]) euler = tf.euler_from_quaternion(quat, axes='sxyz') self.angle.x = euler[0] self.angle.y = euler[1] self.angle.z = euler[2] self.publish() def publish(self): angleMsg = Vector3() angleMsg.x = self.angle.x angleMsg.y = self.angle.y angleMsg.z = self.angle.z self.angle_pub.publish(angleMsg) def run(self): rospy.spin() def main(): node = YawTranslator() node.run() if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python import tf.transformations as tf import numpy as np import rospy import threading from nav_msgs.msg import Odometry from geometry_msgs.msg import PoseWithCovarianceStamped, Vector3, Pose class ringTranslator(): def __init__(self): rospy.init_node("ring_translator") self.pose_sub = rospy.Subscriber("/ground_truth/state", Odometry, self.simCallback, queue_size=1) self.rob_sub = rospy.Subscriber("robot_pos_ls", Pose, self.rob_callback, queue_size=1) self.ring_sub = rospy.Subscriber("ring_pos", Pose, self.pos_callback, queue_size=1) self.ring_pub = rospy.Publisher("ringWorld", Pose, queue_size=1) self.euler = np.zeros(3) self.pos = np.zeros(3) self.ring_abs = np.zeros(3) self.ring_rel = np.zeros(3) def simCallback(self, msg): orient = msg.pose.pose.orientation quat = np.array([orient.x, orient.y, orient.z, orient.w]) self.euler = tf.euler_from_quaternion(quat, axes='sxyz') def rob_callback(self, msg): pos = msg.position self.pos = np.array([pos.x, pos.y, pos.z]) def pos_callback(self, msg): pos = msg.position self.ring_rel = np.array([-pos.x, pos.y, -pos.z])-\ np.array([0.0, -0.1, -0.1]) self.transform() def transform(self): # R = tf.euler_matrix(-self.euler[0], -self.euler[1], -self.euler[2], 'sxyz') # print(self.euler) yaw = -(self.euler[2]-np.pi/2) R = np.array([[np.cos(yaw), -np.sin(yaw), 0], [np.sin(yaw), np.cos(yaw), 0], [0, 0, 1]]) ring_rel_tank = np.matmul(R, self.ring_rel) self.ring_abs = ring_rel_tank + self.pos #- \ # np.array([0.2, -0.25, 0.2]) # print(self.ring_abs) # print(ring_rel_tank, self.ring_rel) self.publish() def publish(self): msg = Pose() msg.position.x = self.ring_abs[0] msg.position.y = self.ring_abs[1] msg.position.z = self.ring_abs[2] self.ring_pub.publish(msg) def run(self): rospy.spin() def main(): node = ringTranslator() node.run() if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python import rospy from bluerov_sim.msg import ActuatorCommands from mavros_msgs.msg import MotorSetpoint class MixerNode(): def __init__(self, name): rospy.init_node(name) self.thrusters = self.init_mixing() self.motor_setpoint_pub = rospy.Publisher( "mavros/setpoint_motor/setpoint", MotorSetpoint, queue_size=1) rospy.Subscriber("~actuator_commands", ActuatorCommands, self.actuator_callback, queue_size=1) def actuator_callback(self, msg): output = MotorSetpoint() output.header.stamp = rospy.Time.now() for i, thruster in enumerate(self.thrusters): output.setpoint[i] = ( thruster["roll"] * msg.roll + thruster["pitch"] * msg.pitch + thruster["yaw"] * msg.yaw + thruster["thrust"] * msg.thrust + thruster["lateral_thrust"] * msg.lateral_thrust + thruster["vertical_thrust"] * msg.vertical_thrust) self.motor_setpoint_pub.publish(output) def init_mixing(self): thruster = [None] * 8 # roll, pitch, yaw, thrust, lateral thrust, vertical thrust thruster[0] = dict(roll=0.0, pitch=0.0, yaw=1.0, thrust=1.0, lateral_thrust=1.0, vertical_thrust=0.0) thruster[1] = dict(roll=0.0, pitch=0.0, yaw=-1.0, thrust=1.0, lateral_thrust=-1.0, vertical_thrust=0.0) thruster[2] = dict(roll=0.0, pitch=0.0, yaw=1.0, thrust=1.0, lateral_thrust=-1.0, vertical_thrust=0.0) thruster[3] = dict(roll=0.0, pitch=0.0, yaw=-1.0, thrust=1.0, lateral_thrust=1.0, vertical_thrust=0.0) thruster[4] = dict(roll=-1.0, pitch=-1.0, yaw=0.0, thrust=0.0, lateral_thrust=0.0, vertical_thrust=1.0) thruster[5] = dict(roll=-1.0, pitch=1.0, yaw=0.0, thrust=0.0, lateral_thrust=0.0, vertical_thrust=-1.0) thruster[6] = dict(roll=1.0, pitch=-1.0, yaw=0.0, thrust=0.0, lateral_thrust=0.0, vertical_thrust=-1.0) thruster[7] = dict(roll=1.0, pitch=1.0, yaw=0.0, thrust=0.0, lateral_thrust=0.0, vertical_thrust=1.0) return thruster def main(): node = MixerNode("mixer") rospy.spin() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy import threading from std_msgs.msg import Float64 # from mavros_msgs.msg import MotorSetpoint from mavros_msgs.srv import CommandBool from numpy import sign class depthControllerNode(): def __init__(self): rospy.init_node("depthController") self.arm_vehicle() self.data_lock = threading.RLock() self.roll_pub = rospy.Publisher("roll", Float64, queue_size=1) self.pitch_pub = rospy.Publisher("pitch", Float64, queue_size=1) self.yaw_pub = rospy.Publisher("yaw", Float64, queue_size=1) self.thrust_pub = rospy.Publisher("thrust", Float64, queue_size=1) self.vertical_thrust_pub = rospy.Publisher("vertical_thrust", Float64, queue_size=1) self.lateral_thrust_pub = rospy.Publisher("lateral_thrust", Float64, queue_size=1) self.roll = 0.0 self.pitch = 0.0 self.yaw = 0.0 self.thrust = 0.0 self.vertical_thrust = 0.0 self.lateral_thrust = 0.0 self.setpoint_sub = rospy.Subscriber("depth_setpoint", Float64, self.on_setpoint, queue_size=1) # self.setpointMotor_sub = rospy.Subscriber("mavros/setpoint_motor/setpoint", # MotorSetpoint, # self.on_setpoint_, # queue_size=1) self.depth_sub = rospy.Subscriber("depth", Float64, self.depth_callback, queue_size=1) rospy.Timer(rospy.Duration(secs=5), self.control) """ # Parameter Theory -> not working self.Kp_krit = 2.32 self.T_krit = 2.8 self.p_gain = 0.6 * self.Kp_krit self.i_gain = self.p_gain / (0.5 * self.T_krit) self.d_gain = 0.125 * self.p_gain * self.T_krit """ # Parameter static self.static_p_gain = 0.4 self.static_i_gain = 0.5 self.static_d_gain = 0.1 self.static_vorsteuerung = -0.05 # Dynamic Parameter self.dynamic_p_gain = 0.8 self.dynamic_i_gain = 0.2 self.dynamic_d_gain = 0.4 self.dynamic_vorsteuerung_up = 0.05 self.dynamic_vorsteuerung_down = -0.1 # Reconfigure Options via subscriber self.kp_dyn_sub = rospy.Subscriber("kp_dyn", Float64, self.kp_dyn_callback, queue_size=1) self.ki_dyn_sub = rospy.Subscriber("ki_dyn", Float64, self.ki_dyn_callback, queue_size=1) self.kd_dyn_sub = rospy.Subscriber("kd_dyn", Float64, self.kd_dyn_callback, queue_size=1) # Reconfigure Options via subscriber self.kp_sta_sub = rospy.Subscriber("kp_sta", Float64, self.kp_sta_callback, queue_size=1) self.ki_sta_sub = rospy.Subscriber("ki_sta", Float64, self.ki_sta_callback, queue_size=1) self.kd_sta_sub = rospy.Subscriber("kd_sta", Float64, self.kd_sta_callback, queue_size=1) self.i_buf = [0.0] * 10 self.setpoint_buf = [0.0] * 5 self.depth_setpoint = -0.5 self.depth = self.depth_setpoint self.depth_old = self.depth self.depth_buf = [self.depth] self.depth_buffer_len = 5 self.sensor_time = rospy.get_time() def publish(self): msg_roll = Float64() msg_roll.data = self.roll self.roll_pub.publish(msg_roll) msg_pitch = Float64() msg_pitch.data = self.pitch self.pitch_pub.publish(msg_pitch) msg_yaw = Float64() msg_yaw.data = self.yaw self.yaw_pub.publish(msg_yaw) msg_thrust = Float64() msg_thrust.data = self.thrust self.thrust_pub.publish(msg_thrust) msg_vertical_thrust = Float64() msg_vertical_thrust.data = self.vertical_thrust self.vertical_thrust_pub.publish(msg_vertical_thrust) msg_lateral_thrust = Float64() msg_lateral_thrust.data = self.lateral_thrust self.lateral_thrust_pub.publish(msg_lateral_thrust) def on_setpoint(self, msg): with self.data_lock: if not self.isRegion(msg.data): self.depth_setpoint = msg.data self.setpoint_buf.append(self.depth_setpoint) self.setpoint_buf.pop(0) self.control() def kp_dyn_callback(self, msg): with self.data_lock: self.dynamic_p_gain = msg.data def ki_dyn_callback(self, msg): with self.data_lock: self.dynamic_i_gain = msg.data def kd_dyn_callback(self, msg): with self.data_lock: self.dynamic_d_gain = msg.data def kp_sta_callback(self, msg): with self.data_lock: self.static_p_gain = msg.data def ki_sta_callback(self, msg): with self.data_lock: self.static_i_gain = msg.data def kd_sta_callback(self, msg): with self.data_lock: self.static_d_gain = msg.data def depth_callback(self, msg): with self.data_lock: self.depth = msg.data self.sensor_time = rospy.get_time() self.control() # might be redundant if only self.run is used def control(self, *args): if rospy.get_time() - self.sensor_time > 5: rospy.logwarn("Sensor Timeout") self.vertical_thrust = 0 self.publish() return if self.isStatic(): self.act_p_gain = self.static_p_gain self.act_i_gain = self.static_i_gain self.act_d_gain = self.static_d_gain self.act_vorsteuerung = self.static_vorsteuerung else: self.act_p_gain = self.dynamic_p_gain self.act_i_gain = self.dynamic_i_gain self.act_d_gain = self.dynamic_d_gain if self.depth_setpoint > self.depth: self.act_vorsteuerung = self.dynamic_vorsteuerung_up else: self.act_vorsteuerung = self.dynamic_vorsteuerung_down self.i_buf.append(self.depth_setpoint - self.depth) self.i_buf.pop(0) self.vertical_thrust = \ self.act_p_gain * (self.depth_setpoint - self.depth) +\ self.act_i_gain * sum(self.i_buf) / len(self.i_buf) +\ self.act_d_gain * (self.i_buf[-4] - self.i_buf[-1])\ + self.act_vorsteuerung # self.depth_old = self.depth_setpoint - self.depth if abs(self.vertical_thrust) > 1: self.vertical_thrust = sign(self.vertical_thrust) if self.isRegion(self.depth) == 1: self.vertical_thrust = -0.1 elif self.isRegion(self.depth) == -1: self.vertical_thrust = 0.1 self.publish() def isRegion(self, setpoint): if setpoint > -0.1: return 1 elif setpoint < -0.8: return -1 else: return 0 def isStatic(self): if self.i_buf[-4] == self.i_buf[-1]: return True else: return True def arm_vehicle(self): # wait until the arming serivce becomes available rospy.wait_for_service("mavros/cmd/arming") # connect to the service arm = rospy.ServiceProxy("mavros/cmd/arming", CommandBool) # call the service to arm the vehicle until service call was successfull while not arm(True).success: rospy.logwarn("Could not arm vehicle. Keep trying.") rospy.sleep(1.0) rospy.loginfo("Armed successfully.") def run(self): rospy.spin() def main(): node = depthControllerNode() node.run() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy import threading from std_msgs.msg import Float64, Int16 from geometry_msgs.msg import Vector3, Pose from nav_msgs.msg import Odometry import numpy as np class NavigationNode(): def __init__(self): rospy.init_node("navigationNode") self.data_lock = threading.RLock() self._useGT = rospy.get_param("~useGT", False) self.ring_sub = rospy.Subscriber("ring_pos", Pose, self.ringCallback, queue_size=1) # use ground truth localization or not if not self._useGT: self.pos_sub = rospy.Subscriber("robot_pos", Pose, self.posCallback, queue_size=1) else: self.gt_sub = rospy.Subscriber("/ground_truth/state", Odometry, self.gtCallback, queue_size=1) self.num_tag = rospy.Subscriber("number_tags", Int16, self.numTagsCallback, queue_size=1) self.setpoint_pub = rospy.Publisher("pos_setpoint", Pose, queue_size=1) self.x = np.array([0.7, 2.0, -0.5]) self.xr = np.zeros(3) self.numTags = 0 self.setpoint = np.zeros(3) def ringCallback(self, msg): with self.data_lock: self.xr[0] = msg.position.x self.xr[1] = msg.position.y self.xr[2] = msg.position.z def posCallback(self, msg): with self.data_lock: self.x[0] = msg.position.x self.x[1] = msg.position.y self.x[2] = msg.position.z def gtCallback(self, msg): with self.data_lock: self.x[0] = msg.pose.pose.position.x self.x[1] = msg.pose.pose.position.y self.x[2] = msg.pose.pose.position.z def numTagsCallback(self, msg): with self.data_lock: self.numTags = msg.data def getSetpoint(self): _tol = 0.1 # first move to correct x and z position, # then move towards # finally, move up if abs(self.xr[0]) > _tol or abs(self.xr[2]) > _tol: self.setpoint[0] = self.x[0] - self.xr[0] self.setpoint[2] = self.x[2] - self.xr[2] elif abs(self.xr[1]) > _tol: self.setpoint = self.x - self.xr else: self.setpoint = self.x self.setpoint[2] = -0.1 msg = Pose() msg.position.x = self.setpoint[0] msg.position.y = self.setpoint[1] msg.position.z = self.setpoint[2] self.setpoint_pub.publish def main(): node = NavigationNode() rospy.spin() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy import threading from std_msgs.msg import Float64 from mavros_msgs.msg import MotorSetpoint class MixerNode(): def __init__(self): rospy.init_node("mixer") self.setpoint_pub = rospy.Publisher("mavros/setpoint_motor/setpoint", MotorSetpoint, queue_size=1) self.data_lock = threading.RLock() self.thruster = self.init_mixing() self.roll = 0.0 self.pitch = 0.0 self.yaw = 0.0 self.thrust = 0.0 self.vertical_thrust = 0.0 self.lateral_thrust = 0.0 self.roll_sub = rospy.Subscriber("roll", Float64, self.on_roll, queue_size=1) self.pitch_sub = rospy.Subscriber("pitch", Float64, self.on_pitch, queue_size=1) self.yaw_sub = rospy.Subscriber("yaw", Float64, self.on_yaw, queue_size=1) self.thrust_sub = rospy.Subscriber("thrust", Float64, self.on_thrust, queue_size=1) self.vertical_thrust_sub = rospy.Subscriber("vertical_thrust", Float64, self.on_vertical_thrust, queue_size=1) self.lateral_thrust_sub = rospy.Subscriber("lateral_thrust", Float64, self.on_lateral_thrust) def run(self): rate = rospy.Rate(50.0) while not rospy.is_shutdown(): msg = self.mix() self.setpoint_pub.publish(msg) rate.sleep() def on_roll(self, msg): with self.data_lock: self.roll = msg.data def on_pitch(self, msg): with self.data_lock: self.pitch = msg.data def on_yaw(self, msg): with self.data_lock: self.yaw = msg.data def on_thrust(self, msg): with self.data_lock: self.thrust = msg.data def on_vertical_thrust(self, msg): with self.data_lock: self.vertical_thrust = msg.data def on_lateral_thrust(self, msg): with self.data_lock: self.lateral_thrust = msg.data def mix(self): msg = MotorSetpoint() msg.header.stamp = rospy.Time.now() with self.data_lock: for i in range(8): msg.setpoint[i] = ( self.roll * self.thruster[i]["roll"] + self.pitch * self.thruster[i]["pitch"] + self.yaw * self.thruster[i]["yaw"] + self.thrust * self.thruster[i]["thrust"] + self.vertical_thrust * self.thruster[i]["vertical_thrust"] + self.lateral_thrust * self.thruster[i]["lateral_thrust"]) return msg def init_mixing(self): thruster = [None] * 8 # roll, pitch, yaw, thrust, lateral thrust, vertical thrust thruster[0] = dict(roll=0.0, pitch=0.0, yaw=1.0, thrust=1.0, lateral_thrust=1.0, vertical_thrust=0.0) thruster[1] = dict(roll=0.0, pitch=0.0, yaw=-1.0, thrust=1.0, lateral_thrust=-1.0, vertical_thrust=0.0) thruster[2] = dict(roll=0.0, pitch=0.0, yaw=1.0, thrust=1.0, lateral_thrust=-1.0, vertical_thrust=0.0) thruster[3] = dict(roll=0.0, pitch=0.0, yaw=-1.0, thrust=1.0, lateral_thrust=1.0, vertical_thrust=0.0) thruster[4] = dict(roll=-1.0, pitch=-1.0, yaw=0.0, thrust=0.0, lateral_thrust=0.0, vertical_thrust=1.0) thruster[5] = dict(roll=-1.0, pitch=1.0, yaw=0.0, thrust=0.0, lateral_thrust=0.0, vertical_thrust=-1.0) thruster[6] = dict(roll=1.0, pitch=-1.0, yaw=0.0, thrust=0.0, lateral_thrust=0.0, vertical_thrust=-1.0) thruster[7] = dict(roll=1.0, pitch=1.0, yaw=0.0, thrust=0.0, lateral_thrust=0.0, vertical_thrust=1.0) return thruster def main(): node = MixerNode() node.run() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy import numpy as np from apriltag_ros.msg import AprilTagDetectionArray from range_sensor.msg import RangeMeasurementArray, RangeMeasurement class RangeSensorNode(): def __init__(self): rospy.init_node("range_sensor") self.range_pub = rospy.Publisher("ranges", RangeMeasurementArray, queue_size=1) self.simulation = rospy.get_param("~sim", True) rospy.Subscriber("tag_detections_sim", RangeMeasurementArray, self.on_sim_dist, queue_size=1) def on_sim_dist(self, msg): self.range_pub.publish(msg) def on_apriltag(self, tag_array_msg): num_tags = len(tag_array_msg.detections) range_array_msg = RangeMeasurementArray() range_array_msg.header = tag_array_msg.header # if tags are detected if num_tags: for i, tag in enumerate(tag_array_msg.detections): range_msg = RangeMeasurement() # tag id -> our numbers for each anchor if tag.id[0] == 0: range_msg.id = 1 elif tag.id[0] == 2: range_msg.id = 2 elif tag.id[0] == 3: range_msg.id = 3 elif tag.id[0] == 4: range_msg.id = 4 range_msg.range = np.sqrt(tag.pose.pose.pose.position.x**2 + tag.pose.pose.pose.position.y**2 + tag.pose.pose.pose.position.z**2) range_msg.header = tag_array_msg.header range_array_msg.measurements.append(range_msg) self.range_pub.publish(range_array_msg) def main(): node = RangeSensorNode() while not rospy.is_shutdown(): rospy.spin() if __name__ == "__main__": main() <file_sep>#include <gazebo_pressure_plugin.h> namespace gazebo { GZ_REGISTER_MODEL_PLUGIN(PressurePlugin) PressurePlugin::PressurePlugin() : ModelPlugin(), baro_rnd_y2_(0.0), baro_rnd_use_last_(false) {} PressurePlugin::~PressurePlugin() { update_connection_->~Connection(); } void PressurePlugin::getSdfParams(sdf::ElementPtr sdf) { namespace_.clear(); if (sdf->HasElement("robotNamespace")) { namespace_ = sdf->GetElement("robotNamespace")->Get<std::string>(); } if (sdf->HasElement("pubRate")) { pub_rate_ = sdf->GetElement("pubRate")->Get<double>(); } else { pub_rate_ = kDefaultPubRate; gzwarn << "[pressure_plugin] Using default publication rate of " << pub_rate_ << "Hz\n"; } if (sdf->HasElement("pressureTopic")) { pressure_topic_ = sdf->GetElement("pressureTopic")->Get<std::string>(); } else { pressure_topic_ = kDefaultPressureTopic; } if (sdf->HasElement("noise")) { pressure_noise_ = sdf->GetElement("noise")->Get<double>(); } else { pressure_noise_ = kDefaultPressureNoise; } } void PressurePlugin::Load(physics::ModelPtr model, sdf::ElementPtr sdf) { getSdfParams(sdf); model_ = model; world_ = model_->GetWorld(); last_time_ = world_->SimTime(); last_pub_time_ = world_->SimTime(); if (!ros::isInitialized()) { ROS_FATAL_STREAM("Ros node for gazebo not initialized"); return; } node_handle_ = new ros::NodeHandle(namespace_); update_connection_ = event::Events::ConnectWorldUpdateBegin( boost::bind(&PressurePlugin::OnUpdate, this, _1)); pressure_pub_ = node_handle_->advertise<sensor_msgs::FluidPressure>(pressure_topic_, 1); } void PressurePlugin::OnUpdate(const common::UpdateInfo &) { common::Time current_time = world_->SimTime(); double dt = (current_time - last_pub_time_).Double(); if (dt > 1.0 / pub_rate_) { sensor_msgs::FluidPressure msg; double z_height = model_->GetLink("pressure_sensor_link")->WorldPose().Pos().Z(); msg.header.stamp = ros::Time::now(); msg.header.frame_id = "map"; // pressure increases by 10 kPa/m water depth. // pressure decreases roughly 100 Pa/8m in air. double msl_pressure = 101325.0; if (z_height > 0) msg.fluid_pressure = msl_pressure - z_height * 12.5; else msg.fluid_pressure = msl_pressure - z_height * 10000; // generate Gaussian noise sequence using polar form of Box-Muller // transformation double x1, x2, w, y1; if (!baro_rnd_use_last_) { do { x1 = 2.0 * standard_normal_distribution_(random_generator_) - 1.0; x2 = 2.0 * standard_normal_distribution_(random_generator_) - 1.0; w = x1 * x1 + x2 * x2; } while (w >= 1.0); w = sqrt((-2.0 * log(w)) / w); // calculate two values - the second value can be used next time because // it is uncorrelated y1 = x1 * w; baro_rnd_y2_ = x2 * w; baro_rnd_use_last_ = true; } else { // no need to repeat the calculation - use the second value from last // update y1 = baro_rnd_y2_; baro_rnd_use_last_ = false; } // apply noise. double noise = pressure_noise_ * y1; msg.fluid_pressure += noise; pressure_pub_.publish(msg); last_pub_time_ = current_time; } } } // namespace gazebo <file_sep>#!/usr/bin/env python import rospy from visualization_msgs.msg import Marker from nav_msgs.msg import Odometry class VisualizerNode(): def __init__(self): rospy.init_node("rviz_visualizer") self.bluerov_marker_pub = rospy.Publisher("bluerov_marker", Marker, queue_size=30) self.ground_truth_sub = rospy.Subscriber("ground_truth/state", Odometry, self.on_ground_truth) def run(self): rospy.spin() def publish_marker(self, pose, header): msg = Marker() msg.header = header msg.ns = "bluerov_ns" msg.id = 27 msg.type = Marker.MESH_RESOURCE msg.pose = pose msg.mesh_resource = "package://bluerov_sim/models/uuv_bluerov2_heavy/meshes/BlueROV2heavy.dae" msg.color.a = 1.0 msg.color.r = 1.0 msg.color.g = 1.0 msg.color.b = 1.0 msg.scale.x = 1 msg.scale.y = 1 msg.scale.z = 1 self.bluerov_marker_pub.publish(msg) def on_ground_truth(self, msg): self.publish_marker(msg.pose.pose, msg.header) def main(): node = VisualizerNode() node.run() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy import threading from std_msgs.msg import Float64, Int16 from geometry_msgs.msg import Vector3, Pose from apriltag_ros.msg import AprilTagDetectionArray from range_sensor.msg import RangeMeasurementArray from nav_msgs.msg import Odometry import tf.transformations as trans from scipy.optimize import minimize, least_squares import numpy as np from numpy.linalg import norm p = [] tank_bound_lower = np.array([0.0, 0.0, -1.3]) tank_bound_upper = np.array([2.0, 4.0, 0.0]) for j in range(9): for i in range(7): p.append(np.array([1.56-i*0.25, 0.06+j*0.39375, -1.3])) p = np.array(p) class localizationNodeLS(): def __init__(self): rospy.init_node("localizationNodeLS") self.data_lock = threading.RLock() self.range_sub = rospy.Subscriber("ranges", RangeMeasurementArray, self.rangeCallback, queue_size=1) self.pos_pub = rospy.Publisher("robot_pos_ls", Pose, queue_size=1) #self.tag_num_pub = rospy.Publisher("number_tags", Int16, queue_size=1) self.x0 = np.zeros(3) self.avg_buf = [] self.avg_dist_buf = [[] for _ in range(63)] self.avg_buf_len = 3 self.avg_buf_len_dist = 5 def rangeCallback(self, msg): with self.data_lock: dists = np.zeros(63) for measure in msg.measurements: if measure.id >= 5: id = measure.id-4 dists[id-1] = measure.range #tagNumerMsg = Int16() #tagNumerMsg.data = len([1 for dist in dists if dist != 0]) #self.tag_num_pub.publish(tagNumerMsg) for i in range(63): if dists[i] != 0: self.avg_dist_buf[i].append(dists[i]) if len(self.avg_dist_buf[i]) > self.avg_buf_len_dist: self.avg_dist_buf[i].pop(0) if len(self.avg_dist_buf[i]) > 0: dists[i] = sum(self.avg_dist_buf[i]) / \ len(self.avg_dist_buf[i]) self.x0 = self.optimization(dists, self.x0) self.avg_buf.append(self.x0) if len(self.avg_buf) > self.avg_buf_len: self.avg_buf.pop(0) self.x0 = sum(self.avg_buf) / len(self.avg_buf) poseMsg = Pose() poseMsg.position.x = self.x0[0] poseMsg.position.y = self.x0[1] poseMsg.position.z = self.x0[2] self.pos_pub.publish(poseMsg) # def depth_callback(self, msg): # with self.data_lock: # self.depth = msg.data # def gt_callback(self, msg): # with self.data_lock: # self.z_gt = msg.pose.pose.position.z+0.08 def optimization(self, dists, x0): def objective_function(x): return np.array([norm(p[i]-x)-dists[i] for i in range(63) if dists[i] != 0]) return least_squares(objective_function, x0, ftol=1e-7, bounds=(tank_bound_lower, tank_bound_upper)).x def main(): node = localizationNodeLS() rospy.spin() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy import pygame import rospkg import os from bluerov_sim.msg import ActuatorCommands from mavros_msgs.srv import CommandBool class Text(object): def __init__(self, font_name=None, size=30, text="empty text"): self.font_name = font_name self.font_size = size self.color_fg = (255, 255, 255) self.color_bg = (0, 0, 0) self._aa = True self._text = text self.font = pygame.font.SysFont(font_name, size) self.screen = pygame.display.get_surface() self.dirty = True self.image = None self.rect = None self._render() def _render(self): self.dirty = False self.image = self.font.render(self._text, self.aa, self.color_fg) self.rect = self.image.get_rect() def draw(self): if self.dirty or (self.image is None): self._render() self.screen.blit(self.image, self.rect) @property def text(self): return self._text @text.setter def text(self, text): if text != self._text: self.dirty = True self._text = text @property def aa(self): return self._aa @aa.setter def aa(self, aa): self.dirty = True self._aa = aa class TextGrid(object): def __init__(self, layout, padding, size): self.texts = [] for row in range(layout[0]): row_list = [] for col in range(layout[1]): row_list.append(Text("dejavusansmono", size, "{}x{}".format(row, col))) self.texts.append(row_list) self.padding = padding self.font_size = size self.screen = pygame.display.get_surface() self.layout = layout self.draw() def draw(self): self.dirty = False col_widths = self.get_column_widths() row_heights = self.get_row_heights() x_col_offsets = [self.padding[0]] * self.layout[1] y_row_offsets = [self.padding[1]] * self.layout[0] for col in range(1, self.layout[1]): x_col_offsets[col] = x_col_offsets[ col - 1] + self.padding[0] + col_widths[col - 1] for row in range(1, self.layout[0]): y_row_offsets[row] = y_row_offsets[ row - 1] + self.padding[1] + row_heights[row - 1] for row in range(self.layout[0]): for col in range(self.layout[1]): self.texts[row][col].rect.top = y_row_offsets[row] self.texts[row][col].rect.left = x_col_offsets[col] self.texts[row][col].draw() def get_column_widths(self): widths = [] for col in range(self.layout[1]): max_width = 0 for row in range(self.layout[0]): if self.texts[row][col].rect.width > max_width: max_width = self.texts[row][col].rect.width widths.append(max_width) return widths def get_row_heights(self): heights = [] for row in range(self.layout[0]): max_height = 0 for col in range(self.layout[1]): if self.texts[row][col].rect.height > max_height: max_height = self.texts[row][col].rect.height heights.append(max_height) return heights def set_text(self, row, col, string): self.texts[row][col].text = string class KeyboardControlNode(): WINDOW_SIZE = (640, 200) DISPLAY_FLAGS = pygame.DOUBLEBUF def __init__(self, name): pygame.init() pygame.mixer.quit() rospy.init_node(name) self.arm_vehicle() self.thrust = 0.0 self.thrust_stepsize = 0.1 self.thrust_scaler = 0.4 self.lateral_thrust = 0.0 self.lateral_thrust_stepsize = 0.1 self.lateral_thrust_scaler = 0.4 self.vertical_thrust = 0.0 self.vertical_thrust_stepsize = 0.1 self.vertical_thrust_scaler = 0.4 self.yaw_rate = 0.0 self.yaw_rate_stepsize = 0.1 self.yaw_rate_scaler = 0.2 # create GUI self.screen = self.init_display() self.text_grid = self.init_text_grid() self.controls = self.init_controls() self.actuator_pub = rospy.Publisher("mixer/actuator_commands", ActuatorCommands, queue_size=1) def arm_vehicle(self): rospy.wait_for_service("mavros/cmd/arming") arm = rospy.ServiceProxy("mavros/cmd/arming", CommandBool) while not arm(True).success: rospy.logwarn_throttle(1, "Could not arm vehicle. Keep trying.") rospy.loginfo("Armed successfully.") def disarm_vehicle(self): rospy.wait_for_service("mavros/cmd/arming") arm = rospy.ServiceProxy("mavros/cmd/arming", CommandBool) arm(False) def init_display(self): screen = pygame.display.set_mode(self.WINDOW_SIZE, self.DISPLAY_FLAGS) vehicle_name = rospy.get_namespace().strip("/") pygame.display.set_caption( "Keyboard Control of {}".format(vehicle_name)) icon_path = os.path.join(self.get_resource_path(), "icon.png") icon = pygame.image.load(icon_path) pygame.display.set_icon(icon) return screen def init_text_grid(self): text_grid = TextGrid((4, 2), (5, 5), 30) text_grid.set_text(0, 0, "Thrust Scaling (1/2):") text_grid.set_text(0, 1, "0.0") text_grid.set_text(1, 0, "Yaw Scaling(3/4):") text_grid.set_text(1, 1, "0.0") text_grid.set_text(2, 0, "Vertical Thrust Scaling(5/6):") text_grid.set_text(2, 1, "0.0") text_grid.set_text(3, 0, "Lateral Thrust Scaling(7/8):") text_grid.set_text(3, 1, "0.0") text_grid.draw() return text_grid def update_text_grid(self): self.text_grid.set_text(0, 1, "{:.2f}".format(self.thrust_scaler)) self.text_grid.set_text(1, 1, "{:.2f}".format(self.yaw_rate_scaler)) self.text_grid.set_text(2, 1, "{:.2f}".format(self.vertical_thrust_scaler)) self.text_grid.set_text(3, 1, "{:.2f}".format(self.lateral_thrust_scaler)) self.text_grid.draw() def run(self): rate = rospy.Rate(30.0) while not rospy.is_shutdown(): self.handle_events() self.screen.fill((0, 0, 0)) self.update_text_grid() pygame.display.flip() self.publish_message() rate.sleep() def set_thrust(self, value): value *= self.thrust_scaler self.thrust = max(-1, min(1, value)) def set_yaw_rate(self, value): value *= self.yaw_rate_scaler self.yaw_rate = max(-1, min(1, value)) def set_vertical_thrust(self, value): value *= self.vertical_thrust_scaler self.vertical_thrust = max(-1, min(1, value)) def set_lateral_thrust(self, value): value *= self.lateral_thrust_scaler self.lateral_thrust = max(-1, min(1, value)) def increase_thrust_scaler(self, value): self.thrust_scaler += value self.thrust_scaler = max(0, min(1, self.thrust_scaler)) def increase_yaw_rate_scaler(self, value): self.yaw_rate_scaler += value self.yaw_rate_scaler = max(0, min(1, self.yaw_rate_scaler)) def increase_vertical_thrust_scaler(self, value): self.vertical_thrust_scaler += value self.vertical_thrust_scaler = max(0, min(1, self.vertical_thrust_scaler)) def increase_lateral_thrust_scaler(self, value): self.lateral_thrust_scaler += value self.lateral_thrust_scaler = max(0, min(1, self.lateral_thrust_scaler)) def init_controls(self): controls = { pygame.K_q: dict( pressed=False, changed=False, description="Turn left.", pressed_callback=(lambda: self.set_yaw_rate(1)), released_callback=(lambda: self.set_yaw_rate(0)), ), pygame.K_e: dict( pressed=False, changed=False, description="Turn right.", pressed_callback=(lambda: self.set_yaw_rate(-1)), released_callback=(lambda: self.set_yaw_rate(0)), ), pygame.K_UP: dict( pressed=False, changed=False, description="Positive vertical thrust.", pressed_callback=(lambda: self.set_vertical_thrust(1)), released_callback=(lambda: self.set_vertical_thrust(0)), ), pygame.K_DOWN: dict( pressed=False, changed=False, description="Negative vertical thrust.", pressed_callback=(lambda: self.set_vertical_thrust(-1)), released_callback=(lambda: self.set_vertical_thrust(0)), ), pygame.K_a: dict( pressed=False, changed=False, description="Positive lateral thrust.", pressed_callback=(lambda: self.set_lateral_thrust(1)), released_callback=(lambda: self.set_lateral_thrust(0)), ), pygame.K_d: dict( pressed=False, changed=False, description="Negative lateral thrust.", pressed_callback=(lambda: self.set_lateral_thrust(-1)), released_callback=(lambda: self.set_lateral_thrust(0)), ), pygame.K_w: dict( pressed=False, changed=False, description="Forward thrust.", pressed_callback=(lambda: self.set_thrust(1)), released_callback=(lambda: self.set_thrust(0)), ), pygame.K_s: dict( pressed=False, changed=False, description="Backward thrust.", pressed_callback=(lambda: self.set_thrust(-1)), released_callback=(lambda: self.set_thrust(0)), ), pygame.K_1: dict( pressed=False, changed=False, description="Decrease forward thrust.", pressed_callback=( lambda: self.increase_thrust_scaler(-self.thrust_stepsize)), ), pygame.K_2: dict( pressed=False, changed=False, description="Increase forward thrust.", pressed_callback=( lambda: self.increase_thrust_scaler(self.thrust_stepsize)), ), pygame.K_3: dict( pressed=False, changed=False, description="Decrease yaw rate.", pressed_callback=(lambda: self.increase_yaw_rate_scaler( -self.yaw_rate_stepsize)), ), pygame.K_4: dict( pressed=False, changed=False, description="Increase yaw rate.", pressed_callback=(lambda: self.increase_yaw_rate_scaler( self.yaw_rate_stepsize)), ), pygame.K_5: dict( pressed=False, changed=False, description="Decrease vertical thrust.", pressed_callback=(lambda: self.increase_vertical_thrust_scaler( -self.vertical_thrust_stepsize)), ), pygame.K_6: dict( pressed=False, changed=False, description="Increase vertical thrust.", pressed_callback=(lambda: self.increase_vertical_thrust_scaler( self.vertical_thrust_stepsize)), ), pygame.K_7: dict( pressed=False, changed=False, description="Decrease lateral thrust.", pressed_callback=(lambda: self.increase_lateral_thrust_scaler( -self.lateral_thrust_stepsize)), ), pygame.K_8: dict( pressed=False, changed=False, description="Increase lateral thrust.", pressed_callback=(lambda: self.increase_lateral_thrust_scaler( self.lateral_thrust_stepsize)), ), } return controls def print_controls(self, controls): print("Controls:") for key in controls: print("{}: {}".format(pygame.key.name(key), controls[key]["description"])) def get_resource_path(self): res_path = rospkg.RosPack().get_path("bluerov_sim") res_path = os.path.join(res_path, "res") return res_path def print_current_values(self): print("thrust: {}\nyaw_rate: {}\nlateral_thrust: {}\n" "vertical_thrust: {}".format(self.thrust, self.yaw_rate, self.lateral_thrust, self.vertical_thrust)) def handle_events(self): events = pygame.event.get() for event in events: if event.type == pygame.KEYDOWN: if event.key in self.controls: control = self.controls[event.key] if "pressed_callback" in control: control["pressed_callback"]() elif event.type == pygame.KEYUP: if event.key in self.controls: control = self.controls[event.key] if "released_callback" in control: control["released_callback"]() elif event.type == pygame.QUIT: pygame.quit() rospy.signal_shutdown("Quitting") def publish_message(self): msg = ActuatorCommands() msg.header.stamp = rospy.Time.now() msg.thrust = self.thrust msg.yaw = self.yaw_rate msg.lateral_thrust = self.lateral_thrust msg.vertical_thrust = self.vertical_thrust self.actuator_pub.publish(msg) def main(): node = KeyboardControlNode("keyboard") node.run() if __name__ == "__main__": main() <file_sep><launch> <!-- Posix SITL environment launch script --> <!-- launchs PX4 SITL and spawns vehicle --> <arg name="camera" default="false" /> <!-- vehicle pose --> <arg name="x" default="0" /> <arg name="y" default="0" /> <arg name="z" default="0" /> <arg name="R" default="0" /> <arg name="P" default="0" /> <arg name="Y" default="0" /> <!-- vehcile model and config --> <arg name="est" value="ekf2" /> <arg unless="$(arg camera)" name="vehicle" value="uuv_bluerov2_heavy" /> <arg if="$(arg camera)" name="vehicle" value="uuv_bluerov2_heavy_cam" /> <arg name="px4_vehicle" value="uuv_bluerov2_heavy" /> <arg name="ID" value="0" /> <env name="PX4_SIM_MODEL" value="$(arg px4_vehicle)" /> <env name="PX4_ESTIMATOR" value="$(arg est)" /> <arg name="mavlink_udp_port" value="14560" /> <arg name="mavlink_tcp_port" value="4560" /> <arg name="fcu_url" value="udp://:14540@localhost:14580" /> <!-- PX4 configs --> <!-- generate sdf vehicle model --> <arg name="cmd" value="xmlstarlet ed -d '//plugin[@name=&quot;mavlink_interface&quot;]/mavlink_tcp_port' -s '//plugin[@name=&quot;mavlink_interface&quot;]' -t elem -n mavlink_tcp_port -v $(arg mavlink_tcp_port) $(find bluerov_sim)/models/$(arg vehicle)/$(arg vehicle).sdf" /> <param command="$(arg cmd)" name="model_description" /> <!-- PX4 SITL --> <arg name="px4_command_arg1" value="" /> <node name="sitl_$(arg ID)" pkg="px4" type="px4" args="$(find px4)/build/px4_sitl_default/etc -s etc/init.d-posix/rcS $(arg px4_command_arg1) -i $(arg ID) -w sitl_$(arg vehicle)_$(arg ID)"/> <!-- spawn vehicle --> <node name="$(arg vehicle)_$(arg ID)_spawn" output="screen" pkg="gazebo_ros" type="spawn_model" args="-sdf -param model_description -model $(arg vehicle)_$(arg ID) -x $(arg x) -y $(arg y) -z $(arg z) -R $(arg R) -P $(arg P) -Y $(arg Y)" /> <!-- MAVROS --> <include file="$(find mavros)/launch/px4.launch"> <arg name="fcu_url" value="$(arg fcu_url)" /> <arg name="gcs_url" value=""/> <arg name="tgt_system" value="$(eval 1 + arg('ID'))" /> <arg name="tgt_component" value="1" /> <arg name="log_output" value="log" /> </include> </launch> <file_sep>#!/usr/bin/env python import rospy import threading from std_msgs.msg import Float64, Int16 from geometry_msgs.msg import Vector3, Pose from apriltag_ros.msg import AprilTagDetectionArray from range_sensor.msg import RangeMeasurementArray from nav_msgs.msg import Odometry import tf.transformations as trans from scipy.optimize import minimize, least_squares import numpy as np from numpy.linalg import norm __radius_ring__ = np.sqrt(2.0*0.12**2.0) def node_at_angle(phi): r = __radius_ring__ return r*np.array([np.cos(phi), 0.0, np.sin(phi)]) tag1 = node_at_angle(np.pi/4.0) tag2 = node_at_angle(3.0*np.pi/4.0) tag3 = node_at_angle(-3.0*np.pi/4.0) tag4 = node_at_angle(-np.pi/4.0) p = np.array([tag1, tag2, tag3, tag4]) # tank_bound_lower = np.array([-1.6, 0.0, -1.0]) # tank_bound_upper = np.array([1.6, 3.35, 1.0]) tank_bound_lower = np.array([-4.0, 0.0, -1.0]) tank_bound_upper = np.array([4.0, 4.0, 1.0]) hook_offset = np.array([0.0, -0.1, -0.15]) class localizationNode(): def __init__(self): rospy.init_node("ringLocalizationNode") self.data_lock = threading.RLock() self.range_sub = rospy.Subscriber("ranges", RangeMeasurementArray, self.rangeCallback, queue_size=1) self.pos_pub = rospy.Publisher("ring_pos", Pose, queue_size=1) self.tag_num_pub = rospy.Publisher("number_tags", Int16, queue_size=1) self.x0 = np.array([0.0, 1.0, 0.0]) self.avg_buf = [] self.avg_dist_buf = [[] for _ in range(4)] self.avg_buf_len = 3 self.avg_buf_len_dist = 5 def rangeCallback(self, msg): with self.data_lock: dists = np.zeros(4) for measure in msg.measurements: if measure.id < 5: id = measure.id dists[id-1] = measure.range tagNumerMsg = Int16() tagNumerMsg.data = len([1 for dist in dists if dist != 0]) self.tag_num_pub.publish(tagNumerMsg) for i in range(4): if dists[i] != 0: self.avg_dist_buf[i].append(dists[i]) if len(self.avg_dist_buf[i]) > self.avg_buf_len_dist: self.avg_dist_buf[i].pop(0) if len(self.avg_dist_buf[i]) > 0: dists[i] = sum(self.avg_dist_buf[i]) / \ len(self.avg_dist_buf[i]) if len([1 for d in dists if d != 0]) < 3: return self.x0 = self.optimization(dists, self.x0) # self.avg_buf.append(self.x0) # if len(self.avg_buf) > self.avg_buf_len: # self.avg_buf.pop(0) # self.x0 = sum(self.avg_buf) / len(self.avg_buf) poseMsg = Pose() poseMsg.position.x = self.x0[0] + hook_offset[0] poseMsg.position.y = self.x0[1] + hook_offset[1] poseMsg.position.z = self.x0[2] + hook_offset[2] self.pos_pub.publish(poseMsg) def optimization(self, dists, x0): def objective_function(x): return np.array([norm(p[i]-x)-dists[i] for i in range(4) if dists[i] != 0]) return least_squares(objective_function, x0, ftol=1e-7, bounds=(tank_bound_lower, tank_bound_upper)).x # return least_squares(objective_function, x0, ftol=1e-7).x def main(): node = localizationNode() rospy.spin() if __name__ == "__main__": main() <file_sep>cmake_minimum_required(VERSION 2.8.3) project(bluerov_sim) find_package(catkin REQUIRED COMPONENTS gazebo_ros gazebo_plugins roscpp std_msgs message_generation range_sensor ) add_compile_options(-std=c++14) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GAZEBO_CXX_FLAGS}") find_package(gazebo REQUIRED) add_message_files( FILES ActuatorCommands.msg ) generate_messages( DEPENDENCIES std_msgs ) link_directories(${GAZEBO_LIBRARY_DIRS}) include_directories(include ${catkin_INCLUDE_DIRS} ${GAZEBO_INCLUDE_DIRS} ${Boost_INCLUDE_DIR}) catkin_package( # INCLUDE_DIRS include DEPENDS roscpp gazebo_ros CATKIN_DEPENDS message_runtime ) add_library(gazebo_pressure_plugin plugins/gazebo_pressure_plugin.cpp) add_dependencies(gazebo_pressure_plugin ${catkin_EXPORTED_TARGETS}) target_link_libraries(gazebo_pressure_plugin ${catkin_LIBRARIES} ${GAZEBO_LIBRARIES}) add_library(gazebo_range_sensor_plugin plugins/gazebo_range_sensor_plugin.cpp) add_dependencies(gazebo_range_sensor_plugin ${catkin_EXPORTED_TARGETS}) target_link_libraries(gazebo_range_sensor_plugin ${catkin_LIBRARIES} ${GAZEBO_LIBRARIES}) <file_sep>#!/usr/bin/env python import rospy import threading from std_msgs.msg import Float64, Int16 from geometry_msgs.msg import Vector3, Pose from apriltag_ros.msg import AprilTagDetectionArray from range_sensor.msg import RangeMeasurementArray, RangeMeasurement from nav_msgs.msg import Odometry import tf.transformations as trans # from scipy.optimize import minimize, least_squares import numpy as np from numpy.linalg import norm,inv p = [] tank_bound_lower = np.array([0.0, 0.0, -1.3]) tank_bound_upper = np.array([2.0, 4.0, 0.0]) for j in range(9): for i in range(7): p.append(np.array([1.56-i*0.25, 0.06+j*0.39375, -1.3])) range_buf = np.zeros(len(p)) tank_bound_lower = np.array([0.0, 0.0, -1.0]) tank_bound_upper = np.array([1.6, 3.35, 0.0]) xref = np.array([t[0] for t in p]) yref = np.array([t[1] for t in p]) zref = np.array([t[2] for t in p]) class localizationNode(): def __init__(self): rospy.init_node("localizationNode", log_level = rospy.DEBUG) self.data_lock = threading.RLock() self.range_sub = rospy.Subscriber("ranges", RangeMeasurementArray, self.rangeCallback, queue_size=1) self.depth_sub = rospy.Subscriber("depth", Float64, self.depth_callback, queue_size=1) self.groundTruth_sub = rospy.Subscriber("/ground_truth/state", Odometry, self.gt_callback, queue_size=1) self.z_gt = 0.0 self.pos_pub = rospy.Publisher("robot_pos", Pose, queue_size=1) self.range_est_pub = rospy.Publisher("range_estimates", RangeMeasurementArray, queue_size=1) self.range_meas_pub = rospy.Publisher("range_measurements", RangeMeasurementArray, queue_size=1) self.x0 = np.zeros(3) self.Sigma0 = np.diag([0.01, 0.01, 0.01]) self.avg_buf = [] self.avg_dist1_buf = [] self.avg_dist2_buf = [] self.avg_dist3_buf = [] self.avg_dist4_buf = [] self.avg_buf_len = 10 self.avg_buf_len_dist = 10 self.y = 0.0 def rangeCallback(self, msg): with self.data_lock: dists = np.zeros(63) for measure in msg.measurements: if measure.id >= 5: id = measure.id-4 dists[id-1] = measure.range (self.x0, self.Sigma0) = kalmanP(dists, self.depth * 1.0e4, self.x0, self.Sigma0) x0 = self.x0 poseMsg = Pose() poseMsg.position.x = x0[0] poseMsg.position.y = x0[1] poseMsg.position.z = x0[2] # Output the estimated range measurement based on the position estimate range_est_array_msg = RangeMeasurementArray() for i in range(len(p)): x_diff = x0[0] - p[i][0] y_diff = x0[1] - p[i][1] z_diff = x0[2] - p[i][2] range_est_msg = RangeMeasurement() range_est_msg.id = i range_est_msg.range = np.sqrt(x_diff**2 + y_diff**2 + z_diff**2) range_est_array_msg.measurements.append(range_est_msg) # Output the true range measurements. When no new measurement is received, the last value is held. range_meas_array_msg = RangeMeasurementArray() for i in range(len(p)-1): range_meas_msg = RangeMeasurement() range_meas_msg.id = i if(dists[i]): range_meas_msg.range = dists[i] range_buf[i] = dists[i] else: range_meas_msg.range = range_buf[i] range_meas_array_msg.measurements.append(range_meas_msg) self.range_est_pub.publish(range_est_array_msg) self.range_meas_pub.publish(range_meas_array_msg) self.pos_pub.publish(poseMsg) def depth_callback(self, msg): with self.data_lock: self.depth = msg.data # self.sensor_time = rospy.get_time() def gt_callback(self, msg): with self.data_lock: self.z_gt = msg.pose.pose.position.z+0.08 def kalmanP(dists, pressure, x0, Sigma0): # Parameters Q = np.diag([0.01, 0.01, 0.01]) # system noise covariance # Output and measurement noise covariance matrix calculation for up to 4 AprilTag distances and the pressure sensor reading iter = np.array(range(dists.shape[0]))[dists != 0] num_tags = iter.shape[0] C = np.zeros((num_tags + 1, 3)) measurement_covs = np.zeros(num_tags + 1) for i in range(num_tags): C[i,0] = (x0[0] - p[iter[i]][0]) / dists[iter[i]] C[i,1] = (x0[1] - p[iter[i]][1]) / dists[iter[i]] C[i,2] = (x0[2] - p[iter[i]][2]) / dists[iter[i]] measurement_covs[i] = 0.1 # covariance of a distance measurement C[num_tags, 0] = 0 C[num_tags, 1] = 0 C[num_tags, 2] = 1.0e-4 # pressure divided by pascals per meter measurement_covs[num_tags] = 0.2 # covariance of a depth measurement. Should account for the offset between camera and pressure sensor R = np.diag(measurement_covs) # Predicted state. For the P Kalman filter, the predicted state (position) is the same as the last position. x_pred = x0 # Predicted covariance Sigma. For the P Kalman filter, the system noise covariance is simply added. Sigma_pred = Sigma0 + Q # Calculation of predicted measurements h = np.zeros(num_tags + 1) for i in range(num_tags): h[i] = np.sqrt(np.float_power((x_pred[0] - p[iter[i]][0]),2) + np.float_power((x_pred[1] - p[iter[i]][1]),2) + np.float_power((x_pred[2] - p[iter[i]][2]),2)) h[num_tags] = pressure / 1.0e4 # Correction K = Sigma_pred.dot(np.transpose(C)).dot(inv(C.dot(Sigma_pred).dot(np.transpose(C)) + R)) z = np.append(dists[dists!=0], [pressure]) x1 = x_pred + np.matmul(K,(z - h)) Sigma1 = (np.eye(3) - K.dot(C)).dot(Sigma_pred) return x1, Sigma1 def main(): node = localizationNode() rospy.spin() if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import rospy from geometry_msgs.msg import Pose from std_msgs.msg import Float64 import numpy as np class PosSetpointNode(): def __init__(self): rospy.init_node("pos_setpoint") self.setpoint_pub = rospy.Publisher("pos_setpoint", Pose, queue_size=1) def run(self): mode = 'const' if mode == 'const': rate = rospy.Rate(50.0) while not rospy.is_shutdown(): msg1 = Pose() # fill msg with example setpoint msg1.position.x = 1.0 msg1.position.y = 3.0 msg1.position.z = -0.5 self.setpoint_pub.publish(msg1) rate.sleep() elif mode == 'sin': rate = rospy.Rate(10.0) while not rospy.is_shutdown(): xs = np.linspace(0, 2*np.pi, num=200) for x in xs: msg = Pose() # fill msg with example setpoint msg.data = 0.2*np.sin(x) - 0.4 self.setpoint_pub.publish(msg) rate.sleep() elif mode == 'step': rate = rospy.Rate(10.0) while not rospy.is_shutdown(): xs = np.linspace(0, 2*np.pi, num=400) for x in xs: msg1 = Pose() msg1.position.x = 1.0 + 0.5*float(x < np.pi) msg1.position.y = 1.0 + 1.0*float(x < np.pi) msg1.position.z = -0.5 - 0.5*float(x < np.pi) self.setpoint_pub.publish(msg1) rate.sleep() else: pass # TODO: add ros logger error def main(): node = PosSetpointNode() node.run() if __name__ == "__main__": main() <file_sep>#include <gazebo_range_sensor_plugin.h> #include <math.h> namespace gazebo { GZ_REGISTER_MODEL_PLUGIN(RangesPlugin) RangesPlugin::RangesPlugin() : ModelPlugin() {} RangesPlugin::~RangesPlugin() { update_connection_->~Connection(); } void RangesPlugin::getSdfParams(sdf::ElementPtr sdf) { namespace_.clear(); if (sdf->HasElement("robotNamespace")) { namespace_ = sdf->GetElement("robotNamespace")->Get<std::string>(); } if (sdf->HasElement("pubRate")) { pub_rate_ = sdf->GetElement("pubRate")->Get<double>(); } else { pub_rate_ = kDefaultPubRate; gzwarn << "[ranges_plugin] Using default publication rate of " << pub_rate_ << "Hz\n"; } if (sdf->HasElement("rangesTopic")) { ranges_topic_ = sdf->GetElement("rangesTopic")->Get<std::string>(); } else { ranges_topic_ = kDefaultRangesTopic; } if (sdf->HasElement("rangeNoiseStd")) { range_noise_std_ = sdf->GetElement("rangeNoiseStd")->Get<double>(); } else { range_noise_std_ = kDefaultRangesNoise; gzwarn << "[ranges_plugin] Using default noise " << kDefaultRangesNoise << "\n"; } if (sdf->HasElement("fovCamera")) { // we'll check visibility using half the fov angle max_fov_angle_ = sdf->GetElement("fovCamera")->Get<double>() / 2.0 * (M_PI / 180.0); } else { max_fov_angle_ = (kDefaultFov / 2.0) * (M_PI / 180.0); gzwarn << "[ranges_plugin] Using default field of view angle " << kDefaultFov << "\n"; } if (sdf->HasElement("viewingAngle")) { // we'll check visibility using half the viewing angle max_viewing_angle_ = sdf->GetElement("viewingAngle")->Get<double>() / 2.0 * (M_PI / 180.0); } else { max_viewing_angle_ = (kDefaultViewingAngle / 2.0) * (M_PI / 180.0); gzwarn << "[ranges_plugin] Using default viewing angle " << kDefaultViewingAngle << "\n"; } if (sdf->HasElement("dropProb")) { drop_prob_ = sdf->GetElement("dropProb")->Get<double>(); } else { drop_prob_ = kDefaultDropProb; gzwarn << "[ranges_plugin] Using default probability " << kDefaultDropProb << " for dropping measurements\n"; } if (sdf->HasElement("maxDetectionDist")) { max_detection_dist_ = sdf->GetElement("maxDetectionDist")->Get<double>(); } else { max_detection_dist_ = kDefaultMaxDetectionDist; gzwarn << "[ranges_plugin] Using default max detection distance " << kDefaultMaxDetectionDist << "\n"; } if (sdf->HasElement("maxDetectionDist")) { dist_drop_prob_exponent_ = sdf->GetElement("maxDetectionDist")->Get<double>(); } else { dist_drop_prob_exponent_ = kDefaultDistDropProbExponent; gzwarn << "[ranges_plugin] Using default Exponent " << kDefaultDistDropProbExponent << " for probability that too far away measurements are dropped \n"; } } void RangesPlugin::Load(physics::ModelPtr model, sdf::ElementPtr sdf) { getSdfParams(sdf); model_ = model; world_ = model_->GetWorld(); last_time_ = world_->SimTime(); last_pub_time_ = world_->SimTime(); if (!ros::isInitialized()) { ROS_FATAL_STREAM("ROS node for gazebo not initialized"); return; } node_handle_ = new ros::NodeHandle(namespace_); update_connection_ = event::Events::ConnectWorldUpdateBegin( boost::bind(&RangesPlugin::OnUpdate, this, _1)); ranges_pub_ = node_handle_->advertise<range_sensor::RangeMeasurementArray>( ranges_topic_, 1); initialized_ = false; tag_axis_ = ignition::math::Vector3d(0.0, 1.0, 0.0); tag_axis_bottom_ = ignition::math::Vector3d(0.0, 0.0, -1.0); } void RangesPlugin::OnUpdate(const common::UpdateInfo &) { common::Time current_time = world_->SimTime(); double dt = (current_time - last_pub_time_).Double(); if (true || !initialized_) { auto model = world_->ModelByName("ring"); if (model && model->GetChildLink("tag_1_link")) { pos_tag_1_ = world_->ModelByName("ring") ->GetChildLink("tag_1_link") ->WorldPose() .Pos(); // gzmsg << "[ranges plugin] Tag 1 Position at "<< pos_tag_1_ << " \n"; } if (model && model->GetChildLink("tag_2_link")) { pos_tag_2_ = world_->ModelByName("ring") ->GetChildLink("tag_2_link") ->WorldPose() .Pos(); // gzmsg << "[ranges plugin] Tag 2 Position at "<< pos_tag_2_ << " \n"; } if (model && model->GetChildLink("tag_3_link")) { pos_tag_3_ = world_->ModelByName("ring") ->GetChildLink("tag_3_link") ->WorldPose() .Pos(); // gzmsg << "[ranges plugin] Tag 3 Position at "<< pos_tag_3_ << " \n"; } if (model && model->GetChildLink("tag_4_link")) { pos_tag_4_ = world_->ModelByName("ring") ->GetChildLink("tag_4_link") ->WorldPose() .Pos(); // gzmsg << "[ranges plugin] Tag 4 Position at "<< pos_tag_4_ << " \n"; initialized_ = true; } // Generate Grid for floor AprilTags for(double j=0.0; j<9.0 ; ++j){ for(double i=0.0; i<7.0; ++i){ auto tmp_tag = ignition::math::Vector3d(1.56-i*0.25, 0.06+j*0.39375, -1.3); floor_tags_.push_back(tmp_tag); //gzmsg << "[ranges plugin] Tag " << i+j*7.0 << " pos at " << tmp_tag << "\n"; } } } if ((dt > 1.0 / pub_rate_) && (initialized_)) { range_sensor::RangeMeasurementArray msg_array; msg_array.measurements.clear(); msg_array.header.stamp = ros::Time::now(); msg_array.header.frame_id = "map"; // get world pose ignition::math::Vector3d pos_sensor = model_->GetLink("range_sensor_link")->WorldPose().Pos(); // gzmsg << "[ranges_plugin] Pos Tag 1 " << pos_sensor << " \n"; // get orientation of body x-axis ignition::math::Vector3d x_unit_vector(1.0, 0.0, 0.0); ignition::math::Vector3d body_x_axis = model_->GetLink("range_sensor_link") ->WorldPose() .Rot() .RotateVector(x_unit_vector); ignition::math::Vector3d z_unit_vector(0.0, 0.0, -1.0); ignition::math::Vector3d body_z_axis = model_->GetLink("range_sensor_link") ->WorldPose() .Rot() .RotateVector(z_unit_vector); ignition::math::Vector3d tag_axis_ = world_->ModelByName("ring") ->GetChildLink("base_link") ->WorldPose() .Rot() .RotateVector(z_unit_vector); // gzmsg << "Tag axis: " << tag_axis_ << "\n"; // ignition::math::Vector3d pos_ring = // model_->GetLink("ring::base_link")->WorldPose().Pos(); auto model_ring = world_->ModelByName("ring"); ignition::math::Vector3d pos_ring; if(model_ring && model_ring->GetChildLink("base_link")){ pos_ring = world_->ModelByName("ring") ->GetChildLink("base_link") ->WorldPose() .Pos(); //gzmsg << "[ranges_plugin] Ring" << pos_ring << "\n"; } // auto pos_tag_1_abs = pos_ring + pos_tag_1_; // auto pos_tag_2_abs = pos_ring + pos_tag_2_; // auto pos_tag_3_abs = pos_ring + pos_tag_3_; // auto pos_tag_4_abs = pos_ring + pos_tag_4_; // tag 1 ignition::math::Vector3d sensor_to_tag_1 = pos_tag_1_ - pos_sensor; if (IsDetected(sensor_to_tag_1, body_x_axis)) { range_sensor::RangeMeasurement msg = GetRangeMsg(1, sensor_to_tag_1); msg_array.measurements.push_back(msg); } // tag 2 ignition::math::Vector3d sensor_to_tag_2 = pos_tag_2_ - pos_sensor; if (IsDetected(sensor_to_tag_2, body_x_axis)) { range_sensor::RangeMeasurement msg = GetRangeMsg(2, sensor_to_tag_2); msg_array.measurements.push_back(msg); } // tag 3 ignition::math::Vector3d sensor_to_tag_3 = pos_tag_3_ - pos_sensor; if (IsDetected(sensor_to_tag_3, body_x_axis)) { range_sensor::RangeMeasurement msg = GetRangeMsg(3, sensor_to_tag_3); msg_array.measurements.push_back(msg); } // tag 4 ignition::math::Vector3d sensor_to_tag_4 = pos_tag_4_ - pos_sensor; if (IsDetected(sensor_to_tag_4, body_x_axis)) { range_sensor::RangeMeasurement msg = GetRangeMsg(4, sensor_to_tag_4); msg_array.measurements.push_back(msg); } for(int i=0; i<63; ++i){ ignition::math::Vector3d tmp_to_tag = floor_tags_.at(i) - pos_sensor; if (IsDetected_bottom(tmp_to_tag, body_z_axis)) { range_sensor::RangeMeasurement msg = GetRangeMsg(i+5, tmp_to_tag); msg_array.measurements.push_back(msg); } } ranges_pub_.publish(msg_array); last_pub_time_ = current_time; } } bool RangesPlugin::IsDetected(ignition::math::Vector3d sensor_to_tag, ignition::math::Vector3d body_x_axis) { // tag might not be visible, determine whether tag is in fov of camera double fov_angle = acos(sensor_to_tag.Dot(body_x_axis) / (sensor_to_tag.Length() * body_x_axis.Length())); // camera might not be facing tag from front double viewing_angle = acos(tag_axis_.Dot(body_x_axis) / (tag_axis_.Length() * body_x_axis.Length())); bool is_visible = (fov_angle < max_fov_angle_) && (viewing_angle < max_viewing_angle_); // measurement might be dropped for whatever reason double p = uniform_real_distribution_(random_generator_); // additional drop probability that increases with distance to tag double p_dist = uniform_real_distribution_(random_generator_); double drop_prob_dist = GetDistanceDropProp(sensor_to_tag.Length()); bool is_not_dropped = (p > drop_prob_) && (p_dist > drop_prob_dist); return is_visible && is_not_dropped; //return true; } bool RangesPlugin::IsDetected_bottom(ignition::math::Vector3d sensor_to_tag, ignition::math::Vector3d body_z_axis ) { // determine fov angle for both x and y double fov_angle = acos(sensor_to_tag.Dot(body_z_axis) / (sensor_to_tag.Length() * body_z_axis.Length())); double viewing_angle = acos(tag_axis_bottom_.Dot(body_z_axis) / (tag_axis_bottom_.Length() * body_z_axis.Length())); bool is_visible = (fov_angle < max_fov_angle_) && (viewing_angle < max_viewing_angle_); //gzmsg << "[ranges_plugin] (fov, view) " << fov_angle << ", " << viewing_angle << "\n"; // measurement might be dropped for whatever reason double p = uniform_real_distribution_(random_generator_); // additional drop probability that increases with distance to tag double p_dist = uniform_real_distribution_(random_generator_); double drop_prob_dist = GetDistanceDropProp(sensor_to_tag.Length()); bool is_not_dropped = (p > drop_prob_) && (p_dist > drop_prob_dist); return is_visible && is_not_dropped; // return true; } range_sensor::RangeMeasurement RangesPlugin::GetRangeMsg( int id, ignition::math::Vector3d sensor_to_tag) { range_sensor::RangeMeasurement msg; msg.header.stamp = ros::Time::now(); msg.header.frame_id = "map"; msg.id = id; double distance = sensor_to_tag.Length(); // add noise double noise = standard_normal_distribution_(random_generator_) * range_noise_std_; msg.range = distance + noise; return msg; } double RangesPlugin::GetDistanceDropProp(double dist) { double p = (1.0 / pow(max_detection_dist_, dist_drop_prob_exponent_)) * pow(dist, dist_drop_prob_exponent_); if (p > 1.0) { p = 1.0; } return p; } } // namespace gazebo <file_sep>#pragma once #include <ros/ros.h> #include <sensor_msgs/FluidPressure.h> #include <gazebo/common/Plugin.hh> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <ignition/math.hh> #include <sdf/sdf.hh> namespace gazebo { static constexpr auto kDefaultPubRate = 50.0; static constexpr auto kDefaultPressureTopic = "pressure"; static constexpr auto kDefaultPressureNoise = 100.0; class PressurePlugin : public ModelPlugin { public: PressurePlugin(); virtual ~PressurePlugin(); protected: virtual void Load(physics::ModelPtr model, sdf::ElementPtr sdf); virtual void OnUpdate(const common::UpdateInfo &); void getSdfParams(sdf::ElementPtr sdf); private: std::string namespace_; physics::ModelPtr model_; physics::WorldPtr world_; event::ConnectionPtr update_connection_; std::string pressure_topic_; double pressure_noise_; ros::NodeHandle *node_handle_; ros::Publisher pressure_pub_; double pub_rate_; std::default_random_engine random_generator_; std::normal_distribution<double> standard_normal_distribution_; common::Time last_pub_time_; common::Time last_time_; double baro_rnd_y2_; bool baro_rnd_use_last_; }; } // namespace gazebo <file_sep>#!/usr/bin/env python import numpy as np import rospy from std_msgs.msg import Int16 from geometry_msgs.msg import Pose class alarmNode(): def __init__(self): rospy.init_node("alarmNode") self.tagNumber = 0 self.tag_threshold = 3 self.ring_sub = rospy.Subscriber("ringWorld", Pose, self.alarm_callback, queue_size=1) self.setpoint_sub = rospy.Subscriber("number_tags", Int16, self.tag_callback, queue_size=1) def tag_callback(self, msg): self.tagNumber = msg.data if self.tagNumber > 0 and self.tagNumber <= self.tag_threshold: rospy.loginfo("Maybe I found something") def alarm_callback(self, msg): self.actual_pos = np.array([msg.position.x, msg.position.y, msg.position.z]) if self.tagNumber > self.tag_threshold: rospy.logwarn("Alarm!!!!!!!!! Object found at:") rospy.logwarn(self.actual_pos) def run(self): rospy.spin() def main(): node = alarmNode() node.run() if __name__ == '__main__': main()<file_sep>#!/usr/bin/env python import rospy import threading from std_msgs.msg import Float64, String from geometry_msgs.msg import Pose, Vector3 import numpy as np class rotControlNode(): def __init__(self): rospy.init_node("rot_control") self.data_lock = threading.RLock() self.strategy = "search" self.search_thrust = 0.09 self.dirLock = False self.yaw_thrust = 0.0 self.yaw = 0.0 self.yaw_setpoint = 0.0 self.rot_p_gain = 0.08 self.rot_i_gain = 0.0 self.rot_d_gain = 0.0 self.yaw_pub = rospy.Publisher("yaw", Float64, queue_size=1) self.depth_sub = rospy.Subscriber("/nav_controller/angle", Vector3, self.rot_callback, queue_size=1) self.strategy_sub = rospy.Subscriber("strategy", String, self.strategy_callback, queue_size=1) # Reconfigure Options via subscriber self.search_thrust_sub = rospy.Subscriber("search_thrust", Float64, self.search_thrust_callback, queue_size=1) self.rot_control_frequency = 20.0 rospy.Timer(rospy.Duration(1.0/self.rot_control_frequency), self.rot_control) def strategy_callback(self, msg): self.strategy = msg.data if self.strategy != "search" and not self.dirLock: if self.yaw <= 0.1: self.yaw_setpoint = 0.0 elif 0.1 < self.yaw <= np.pi/2: self.yaw_setpoint = 1.5707 elif np.pi/2 < self.yaw <= np.pi: self.yaw_setpoint = np.pi elif np.pi < self.yaw <= 3*np.pi/2: self.yaw_setpoint = 3*np.pi/2 else: self.yaw_setpoint = 0.0 self.dirLock = True def rot_callback(self, msg): self.roll = msg.x self.pitch = msg.y self.yaw = msg.z def search_thrust_callback(self, msg): with self.data_lock: self.search_thrust = msg.data # might be redundant if only self.run is used def rot_control(self, *args): rospy.loginfo(self.yaw_setpoint) if not self.dirLock: self.roll_thrust = 0.0 self.pitch_thrust = 0.0 self.yaw_thrust = self.search_thrust else: self.yaw_thrust = (self.rot_p_gain * (self.yaw_setpoint - self.yaw)) self.publish() def publish(self): msg_yaw = Float64() msg_yaw.data = self.yaw_thrust self.yaw_pub.publish(msg_yaw) def run(self): rospy.spin() def main(): node = rotControlNode() node.run() if __name__ == "__main__": main()
485ebc2821699db03fcdbf4e323c3f8a213427c0
[ "XML", "CMake", "C++", "Python" ]
27
XML
CarlGiest/FormulasAndVehicles
f14daa2d07fa7abbf360ec7a045b2539c6d4ccf0
5cf9039f72a8205142139bd3ddcc3c55270a8760
refs/heads/main
<file_sep># sms_spam_collection libraries: * numpy * sklearn * pandas * seaborn * pipeline * stopwords usage: * sms_spam.py * spam.csv <file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import scipy as sp get_ipython().run_line_magic('matplotlib', 'inline') sms = pd.read_csv("...../Downloads/project/spam.csv") sms.head() sms = sms.drop('2', 1) sms = sms.drop('3', 1) sms = sms.drop('4', 1) sms.head() sms = sms.rename(columns = {'v1':'label','v2':'message'}) sms.groupby('label').describe() sms['length'] = sms['message'].apply(len) sms.head() sms['length'].plot(bins=100, kind='hist') count_Class=pd.value_counts(sms["label"], sort= True) count_Class.plot(kind = 'bar',color = ["green","red"]) plt.title('Bar Plot') plt.show(); sms.length.describe() sms[sms['length'] == 910]['message'].iloc[0] sms.hist(column='length', by='label', bins=50,figsize=(12,4)) #nlp import string from nltk.corpus import stopwords def text_process(mess): nopunc = [char for char in mess if char not in string.punctuation] nopunc = ''.join(nopunc) return [word for word in nopunc.split() if word.lower() not in stopwords.words('english')] sms['message'].head(5).apply(text_process) from sklearn.feature_extraction.text import CountVectorizer bow_transformer = CountVectorizer(analyzer=text_process).fit(sms['message']) print(len(bow_transformer.vocabulary_)) sms_bow = bow_transformer.transform(sms['message']) print('Shape of Sparse Matrix: ', sms_bow.shape) print('Amount of Non-Zero occurences: ', sms_bow.nnz) sparsity = (100.0 * sms_bow.nnz / (sms_bow.shape[0] * sms_bow.shape[1])) print('sparsity: {}'.format(round(sparsity))) from sklearn.feature_extraction.text import TfidfTransformer tfidf_transformer = TfidfTransformer().fit(sms_bow) sms_tfidf = tfidf_transformer.transform(sms_bow) print(sms_tfidf.shape) #naive bayes from sklearn.naive_bayes import MultinomialNB spam_detect_model = MultinomialNB().fit(sms_tfidf, sms['label']) all_predictions = spam_detect_model.predict(sms_tfidf) print(all_predictions) from sklearn.metrics import classification_report print (classification_report(sms['label'], all_predictions)) from sklearn.model_selection import train_test_split msg_train, msg_test, label_train, label_test = train_test_split(sms['message'], sms['label'], test_size=0.2) print(len(msg_train), len(msg_test), len(msg_train) + len(msg_test)) # DATA PIPELINE from sklearn.pipeline import Pipeline pipeline = Pipeline([ ('bow', CountVectorizer(analyzer=text_process)), # strings to token integer counts ('tfidf', TfidfTransformer()), # integer counts to weighted TF-IDF scores ('classifier', MultinomialNB()), # train on TF-IDF vectors w/ Naive Bayes classifier ]) pipeline.fit(msg_train,label_train) predictions = pipeline.predict(msg_test) print(classification_report(predictions,label_test))
123dadc08c965e59812cc1e8db4f01f6a37f3a62
[ "Markdown", "Python" ]
2
Markdown
Abarnakumar28/sms_spam_collection
e865391bd34c02c00928c775d782e90126b28950
87ba2243f674cc0c693982a064ed449971865970
refs/heads/master
<repo_name>blueeyes007/workshops<file_sep>/DataScienceTools/demos/reports/1980_census2.tex \documentclass{article} \title{My Report} \begin{document} \maketitle \section{Population of the United States in 1980} The 1980 Census reported $\input{output/1980_census_sum2.tex}$ people living in the United States. \end{document}
2cc26b13bef263563e90d4236ea9d4745799763a
[ "TeX" ]
1
TeX
blueeyes007/workshops
e6b6f9e65aff024b7ccb2b5e7bd8745f446fcd88
0b90356993986e18701fdf972fdab97510698aab
refs/heads/master
<repo_name>miadea/portfolio-website-builder<file_sep>/app/components/css/page-design.less #websiteDesign { } <file_sep>/app/components/html/Art.jsx import React from 'react'; class Body extends React.Component { render() { return( <div id="Art" className="page-content"> <div className="content-wrapper content-title"> <div className="position"> <h3>Art</h3> <h3 className="content-subtitle">I create digital art that mainly foccuses on character design and personal projects.</h3> </div> </div> <div className="image-wrapper"> <img src="images/sampleSite.png"></img> </div> </div> ) }} module.exports = Body <file_sep>/app/components/css/page-footer.less .page-footer { background-color: black; .footer-wrapper{ display: flex; } .footer-style{ font-family: 'Josefin Sans', sans-serif; font-size: 1.5rem; color: white; padding: 0 20px; margin-left: auto; margin-right: auto; letter-spacing: 3px; } .made-by{ background-color: #333333; color: gray; display: flex; padding: 10px; font-size: 0.8rem; } } <file_sep>/app/index.jsx import React from 'react'; import {render} from 'react-dom'; import Header from './components/html/Header.jsx'; import Footer from './components/html/Footer.jsx'; import Design from './components/html/Design.jsx'; import Photos from './components/html/Photos.jsx'; import Art from './components/html/Art.jsx'; import BackToTop from './components/html/BackToTop.jsx'; import './components/css/main.less'; import "normalize-css"; class App extends React.Component { constructor() { super() this.state = { lang: 'es' } } render () { let lang = this.state.lang return (<div id="top" className='test'> <Header /> <Design /> <Photos /> <Art /> <Footer /> {/* <BackToTop /> */} </div>); } onChange(lang) { this.setState({lang}) } } render(<App/>, document.getElementById('app')); <file_sep>/app/components/css/page-header.less .page-header { background-image: url("https://photos.smugmug.com/WF/Emma-Stoumen-Portfolio/Details/n-F9VBR9/i-H8M6qPn/0/X3/i-H8M6qPn-X3.jpg"); background-position: center; background-size: cover; background-repeat: no-repeat; height: 100vh; display: flex; flex-direction: column; } .page-header .title-wrapper { flex-grow: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; } .page-header .title { font-size: 6rem; font-family: 'Josefin Sans', sans-serif; animation: fadein 4s; } @keyframes fadein { from { opacity: 0; } to { opacity: 1; } } <file_sep>/app/components/css/page-art.less #Art { } <file_sep>/app/components/css/navbar.less .navStyle { padding: 20px 0; font-family: 'Josefin Sans', sans-serif; font-size: 2rem; } .navStyle ul { list-style-type: none; margin: 0; padding: 0; } .navStyle li { display: inline; } .navStyle a { color: black; text-align: center; text-decoration: none; padding: 20px; } .navStyle a:hover{ background-color: rgba(0,0,0,0.1); } // #segment-header a{ // display: block; // color: white; // text-align: center; // padding: 14px 16px; // } <file_sep>/app/components/html/Header.jsx import React from 'react'; class Header extends React.Component { render () { return( <div className="page-header"> <nav className="navStyle"> <div> <ul> <li><a href="#websiteDesign">Website Design</a></li> <li><a href="#Photos">Photography</a></li> <li><a href="#Art">Art</a></li> </ul> </div> </nav> <div className="title-wrapper"> <h1 className="title"><NAME></h1> </div> </div> ) } } module.exports = Header <file_sep>/app/components/html/Design.jsx import React from 'react'; class Body extends React.Component { render() { return( <div id="websiteDesign" className="page-content"> <div className="content-wrapper content-title"> <div className="position"> <h3>Website Design</h3> <h3 className="content-subtitle">I create and design modern websites. I focus on marketing websites for companies.</h3> </div> </div> <div className="image-wrapper"> <img src="sampleSite.png"></img> </div> </div> ) }} module.exports = Body <file_sep>/app/components/css/main.less @import url('https://fonts.googleapis.com/css?family=Josefin+Sans:300|Raleway:200|Work+Sans:200'); @import "./page-header.less"; @import "./navbar.less"; @import "./page-footer.less"; @import "./page-design.less"; @import "./page-photos.less"; @import "./page-art.less"; html, body, #app { margin: 0; padding: 0; font-size: 16px; transition: font-size 0.5s; } @media screen and (max-width: 1024px) { html, body { font-size: 70%; } } @media screen and (max-width: 667px) { html, body { font-size: 60%; } } .page-content{ height: 50vh; background-color: #ccc; display: flex; .image-wrapper{ width: 50vw; } .content-wrapper{ width: 50vw; display: flex; flex-direction: column; align-items: center; justify-content: center; border-style: solid; border-width: 5px 0px 10px 0px; border-color: gray; border-radius: 2px; } .position{ max-width: 70%; } .content-title{ background-color: #333; color: white; font-family: 'Josefin Sans', sans-serif; font-size: 2rem; } .content-subtitle{ font-size: 1.5rem; font-family: 'Work Sans', sans-serif; } .block{ border-style: solid; border-color: black; border-width: 20px; border-radius: 20px; background-color: black; } }
87c4ce56de779f61db5c6c0b3cc8939b5fa5ba3b
[ "JavaScript", "Less" ]
10
JavaScript
miadea/portfolio-website-builder
8b6ec66a7a8f0f9bda845764b1a7ed36239cdcfc
2c46281d35c2dbff79257d43c3a5ca5af3ea28aa
refs/heads/master
<repo_name>therealjedeye98/Crime-Data-Assignment<file_sep>/mainfile.py ######## #modules ######## import csv import sys import collections import datetime ######## #enter csv ######## path = "crime.csv" datafile = open(path) #, newline='' # reader function to parse csv data from file reader = csv.reader(datafile) #first line is header header = next(reader) #next function extracts first line #now we read data data = [row for row in reader] ######## ######## #functions ######## def date_to_day(date): date_format = date.split(' ')[0].split('-') day = int(date_format[0]) month = int(date_format[1]) year = int('20'+date_format[2]) born = datetime.date(year, month, day) return born.strftime("%A") def num_2015(): num_crimes_2015 = 0 for i in range(len(data)): #python find() returns -1 if not found if data[i][7].find("-15") != -1: num_crimes_2015 = num_crimes_2015 + 1 print(num_crimes_2015) def shootings_2018(): num_shootings_2018=0 for i in range(len(data)): if (data[i][6] != '') and (data[i][7].find("-18") != -1): num_shootings_2018 = num_shootings_2018 + 1 print(num_shootings_2018) def larceny_2017(): num_larceny = 0 for i in range(len(data)): if (data[i][2].find("Larceny") != -1) and (data[i][7].find("-17") != -1): num_larceny = num_larceny + 1 print(num_larceny) def drugviolation_AB(): num_violations = 0 for i in range(len(data)): if (data[i][4].find("A") != -1) or (data[i][4].find("B") != -1): if (data[i][2].find("Drug Violation") != -1): num_violations = num_violations + 1 print(num_violations) def common_codes(): data.sort(reverse=True) new_list = [] for i in range(len(data)): if data[i][7].find("-16") != -1: new_list.append(data[i][1]) new_list.sort(reverse=True) c = collections.Counter(new_list) c = [key for key, _ in c.most_common(2)] print(c[0]) return(c[1]) def most_robberies(): #empty array to store collection of most array = [] for b in ["-18", "-17", "-16", "-15", "-14"]: counter = 0 for i in range(len(data)): if (data[i][2].find("Robbery") != -1) and (data[i][7].find(b) != -1): counter = counter + 1 array.append([counter, b]) array.sort(reverse=True) print('20'+array[0][1][1:] + '\n20'+ array[1][1][1:]) def crime_streets(): data.sort(reverse=True) new_list = [] for i in range(len(data)): if data[i][9].find(" ") != -1: new_list.append(data[i][9]) new_list.sort(reverse=True) c = collections.Counter(new_list) c = [key for key, _ in c.most_common(3)] print(c[0]) print(c[1]) print(c[2]) def offense_codes(): list2 = [] districts = ["A","E","C"] for i in range(len(data)): if data[i][4].find(districts[0]) != -1: if date_to_day(str(data[i][7][0:8])) == "Friday" or date_to_day(str(data[i][7][0:8])) == "Saturday" or date_to_day(str(data[i][7][0:8])) == "Sunday": list2.append(data[i][1]) if data[i][4].find(districts[1]) != -1: if date_to_day(str(data[i][7][0:8])) == "Friday" or date_to_day(str(data[i][7][0:8])) == "Saturday" or date_to_day(str(data[i][7][0:8])) == "Sunday": list2.append(data[i][1]) if data[i][4].find(districts[2]) != -1: if date_to_day(str(data[i][7][0:8])) == "Friday" or date_to_day(str(data[i][7][0:8])) == "Saturday" or date_to_day(str(data[i][7][0:8])) == "Sunday": list2.append(data[i][1]) list2.sort(reverse=True) #powerful function c = collections.Counter(list2) c = [key for key, _ in c.most_common(3)] num1code = str(c[0]) num2code = str(c[1]) num3code = str(c[2]) topcodes = [num1code,num2code,num3code] ## convert offense codes to offense code groups printarray1 = [] printarray2 = [] printarray3 = [] for i in range(len(data)): if data[i][1] == topcodes[0]: printarray1.append(data[i][2]) else: continue for i in range(len(data)): if data[i][1] == topcodes[1]: printarray2.append(data[i][2]) else: continue for i in range(len(data)): if data[i][1] == topcodes[2]: printarray3.append(data[i][2]) else: continue print(printarray1[0]) print(printarray2[0]) print(printarray3[0]) ######## #cases ####### #condition 0 - student number input = sys.argv[1] if input == 'studentnumber': student_no = 3726450 print(student_no) #condition 1 - number of crimes in 2015 if input == '1': num_2015() #condition 2 - number of shootings in 2018 if input == '2': shootings_2018() #condition 3 - number of larcony if input == '3': larceny_2017() #condition 4 - number of drug violations in district A and B if input == '4': drugviolation_AB() #condition 5 - most common codes in 2016 if input == '5': print(common_codes()) #condition 6 - two years with most robberies if input == '6': most_robberies() #condition 7 - top three non null streets in terms of incidents reported if input == "7": crime_streets() #condition 8 - if input == "8": offense_codes() ########
7d4fcbc28d08de7359c16358d1de15f23e2e05c6
[ "Python" ]
1
Python
therealjedeye98/Crime-Data-Assignment
41e46d489624ecc4a041a9d966a0ecd2e25ed9d0
8f76e339dba23f8ccbf75aa905e43ab09fb81e6b
refs/heads/main
<file_sep># Learn Rust by Building Real Applications Coded (& improved) on the [Learn Rust by Building Real Applications](https://www.udemy.com/course/rust-fundamentals) course. See [Repository](https://github.com/gavadinov/Learn-Rust-by-Building-Real-Applications). <file_sep>use std::io::{BufRead, Write}; use std::num::ParseFloatError; pub fn prompt<R, W>(mut reader: R, mut writer: W, question: &str) -> String where R: BufRead, W: Write, { write!(&mut writer, "{}", question).expect("Unable to write"); writer.flush().expect("Unable to flush"); let mut s = String::new(); reader.read_line(&mut s).expect("Unable to read"); s } pub fn get_value(s: &String) -> Result<f32, ParseFloatError> { s.trim().parse::<f32>() } #[cfg(test)] mod tests { use super::{get_value, prompt}; #[test] fn it_should_get_input() { let input = b"100.0"; let mut output = Vec::new(); let answer = prompt(&input[..], &mut output, "Enter your weight (kg): "); let output = String::from_utf8(output).expect("Not UTF-8"); assert_eq!("Enter your weight (kg): ", output); assert_eq!("100.0", answer); } #[test] fn it_should_get_value() { let result = get_value(&String::from("100.0")); let expected = Ok(100.0); assert_eq!(result, expected); } #[test] fn it_should_not_get_value() { let result = get_value(&String::from("test")); assert!(result.is_err()); } } <file_sep>use std::io; mod input; mod weight; fn main() { let stdio = io::stdin(); let input = stdio.lock(); let output = io::stdout(); let user_input = input::prompt(input, output, "Enter your weight (kg): "); let f = input::get_value(&user_input).expect("Failed to parse"); let mars_weight = weight::get_on_mars(f); println!("Weight on Mars : {}kg", mars_weight); } <file_sep>pub fn get_on_mars(weight: f32) -> f32 { (weight / 9.81) * 3.711 } #[cfg(test)] mod tests { use super::get_on_mars; #[test] fn it_should_get_on_mars() { let result = get_on_mars(100.0); assert_eq!(result, 37.828747); } }
532c2e8e2ba4a24ca4b6a619aa91c63ee823f003
[ "Markdown", "Rust" ]
4
Markdown
qdelettre/Learn-Rust-by-Building-Real-Applications-Mars-Calc
9cf47c36bd553ffbb94cc88b1096f39a0d6c9afb
0686420362e68846084e17cb9c2123e5a043b723
refs/heads/master
<file_sep>#!/bin/bash CLONE_URL=<EMAIL>:freechipsproject/chisel-template.git TEMP_NAME=$(cat /dev/urandom | tr -cd 'a-zA-Z0-9' | head -c 32) PROGNAME=$(basename $0) usage() { echo "Usage: $PROGNAME [OPTIONS] DIR_NAME" echo echo "Options:" echo "-h, --help: show this" echo " --ssh: use ssh to clone chisel-template repository" echo " --https: use https to clone chisel-template repository" echo exit 1 } while (( $# > 0 )) do case "$1" in "-h" | "--help" ) usage exit 1 ;; "--ssh" ) CLONE_URL=<EMAIL>:freechipsproject/chisel-template.git shift 1 ;; "--https" ) CLONE_URL=https://github.com/freechipsproject/chisel-template.git shift 1 ;; *) TEMPLATE_NAME="$TEMPLATE_NAME $1" shift 1 ;; esac done if [ -z "$TEMPLATE_NAME" ]; then echo "specify project name" exit 1 else git clone "$CLONE_URL" $TEMP_NAME if [ $? -ne 0 ]; then exit 1 fi fi EXECUTE_DIR=$PWD for NAME in $TEMPLATE_NAME; do cd $EXECUTE_DIR if [ -e "$NAME" ]; then echo "$NAME has already existed" else cp -rf ./$TEMP_NAME ./$NAME rm -rf ./$NAME/.git rm -rf ./$NAME/src/{main,test}/scala/gcd cd ./$NAME git init fi done cd $EXECUTE_DIR rm -rf ./$TEMP_NAME <file_sep># chisel-init This shell script using [chisel-template](https://github.com/freechipsproject/chisel-template) to initialize chisel3 project ## how to use You can create project with project name directory ``` chisel-init "project-name" ``` If you typed like above, project-name directory is created in your current directory
fb7335e0878857ec420fe69699151ad7a70f44b9
[ "Markdown", "Shell" ]
2
Markdown
yxnan/chisel-init
8ef572c7c93be81c7ac68dc8aa99e21cfeac19d1
af2982287528c579b252e924296caf25f85b14d3
refs/heads/master
<file_sep>create index gnafid_idx on location_table(gnafid); create index unitnumber_idx on location_table(unitnumber); create index levelnumber_idx on location_table(levelnumber); create index lotnumber_idx on location_table(lotnumber); create index roadnumber1_idx on location_table(roadnumber1); create index roadnumber2_idx on location_table(roadnumber2); create index roadname_idx on location_table(roadname varchar_pattern_ops); create index localityname_idx on location_table(localityname varchar_pattern_ops); create index postcode_idx on location_table(postcode); create index state_idx on location_table(statecode); create index lat_idx on location_table(latitude); create index long_idx on location_table(longitude); create index addresssitename_idx on location_table(addresssitename varchar_pattern_ops); <file_sep>create table LOCATION_TABLE as select * from LOCATION_VIEW; create index POSTCODE_IDX on LOCATION_TABLE(postcode); create index LOCALITY_IDX on LOCATION_TABLE(localityname); create index GNAF_IDX on LOCATION_TABLE(gnafid); create index RDNUM1_IDX on LOCATION_TABLE(roadnumber1); create index RDNUM2_IDX on LOCATION_TABLE(roadnumber2); create index ROADNAME_IDX on LOCATION_TABLE(roadname); create index SITENAME_IDX on LOCATION_TABLE(addresssitename); create index LOTNUM_IDX on LOCATION_TABLE(lotnumber); create index UNITNUM_IDX on LOCATION_TABLE(unitnumber); create index LAT_IDX on LOCATION_TABLE(latitude); create index LONG_IDX on LOCATION_TABLE(longitude); <file_sep>#!/bin/bash ############################################################ # # # load-mysql.sh # # # # Loads GNAF data to a MySQL database # # 19/08/2020 # # # ############################################################ MYSQL_HOST="10.0.1.208" MYSQL_USER="rjk" MYSQL_PASS="<PASSWORD>" MYSQL_DB="gnaf" AUT=$1 AUT_REGEX="Authority_Code_([[:upper:]_]+)_psv\.psv" DAT=$2 DAT_REGEX="(ACT|NSW|NT|QLD|SA|OT|TAS|VIC|WA)_([[:upper:][:digit:]_]+)_psv\.psv" echo "*** creating tables ***" mysql --host=$MYSQL_HOST --user=$MYSQL_USER --password=$MYSQL_PASS $MYSQL_DB < create_tables_ansi.sql echo "" echo "*** Working on Authority codes ***" echo "Authority files in folder $AUT" echo "" if [[ -d "$AUT" ]]; then echo "Authority codes is a folder" for aut_file in $AUT/*.psv; do echo "Got AUT file: $aut_file" if [[ "$aut_file" =~ $AUT_REGEX ]]; then TABLE_NAME=${BASH_REMATCH[1]} echo "Table name: $TABLE_NAME" echo "LOAD DATA LOCAL INFILE '$aut_file' INTO TABLE $TABLE_NAME COLUMNS TERMINATED BY '|' LINES TERMINATED BY '\r\n' IGNORE 1 LINES" | mysql --local-infile=1 --host=$MYSQL_HOST --user=$MYSQL_USER --password=$MYSQL_PASS $MYSQL_DB fi done else echo "Authority codes is not a folder" exit -1 fi echo "" echo "*** Working on data files ***" echo "Data files in folder $DAT" echo "" if [[ -d "$DAT" ]]; then echo "Data files is a folder" for dat_file in $DAT/*.psv; do echo "Got DAT file: $dat_file" if [[ "$dat_file" =~ $DAT_REGEX ]]; then TABLE_NAME=${BASH_REMATCH[2]} echo "Table name: $TABLE_NAME" echo "LOAD DATA LOCAL INFILE '$dat_file' INTO TABLE $TABLE_NAME COLUMNS TERMINATED BY '|' LINES TERMINATED BY '\r\n' IGNORE 1 LINES" | mysql --local-infile=1 --host=$MYSQL_HOST --user=$MYSQL_USER --password=$MYSQL_PASS $MYSQL_DB fi done fi echo "" echo "*** creating the PK indexes ***" #mysql --host=$MYSQL_HOST --user=$MYSQL_USER --password=$MYSQL_PASS $MYSQL_DB < add_pk.sql <file_sep>#!/bin/bash ############################################################ # # # load-postgres.sh # # # # Loads GNAF data to a postgres database # # 21/08/2020 # # # ############################################################ PG_HOST="127.0.0.1" PG_USER="rjk" PG_PASS="<PASSWORD>" PG_DB="gnaf" AUT=$1 AUT_REGEX="Authority_Code_([[:upper:]_]+)_psv\.psv" DAT=$2 DAT_REGEX="(ACT|NSW|NT|QLD|SA|OT|TAS|VIC|WA)_([[:upper:][:digit:]_]+)_psv\.psv" echo "*** creating tables ***" PGPASSWORD=$PG_PASS psql -h $PG_HOST -U $PG_USER -d $PG_DB -a -f create_tables_ansi.sql echo "" echo "*** Working on Authority codes ***" echo "Authority files in folder $AUT" echo "" if [[ -d "$AUT" ]]; then echo "Authority codes is a folder" for aut_file in $AUT/*.psv; do echo "Got AUT file: $aut_file" if [[ "$aut_file" =~ $AUT_REGEX ]]; then TABLE_NAME=${BASH_REMATCH[1]} echo "Table name: $TABLE_NAME" echo "\copy $TABLE_NAME FROM '$aut_file' DELIMITER '|' CSV HEADER" | PGPASSWORD=$PG_PASS psql -h $PG_HOST -U $PG_USER -d $PG_DB fi done else echo "Authority codes is not a folder" exit -1 fi echo "" echo "*** Working on data files ***" echo "Data files in folder $DAT" echo "" if [[ -d "$DAT" ]]; then echo "Data files is a folder" for dat_file in $DAT/*.psv; do echo "Got DAT file: $dat_file" if [[ "$dat_file" =~ $DAT_REGEX ]]; then TABLE_NAME=${BASH_REMATCH[2]} echo "Table name: $TABLE_NAME" echo "\copy $TABLE_NAME FROM '$dat_file' DELIMITER '|' CSV HEADER" | PGPASSWORD=$PG_PASS psql -h $PG_HOST -U $PG_USER -d $PG_DB fi done fi echo "" echo "*** creating the PK indexes ***" #mysql --host=$MYSQL_HOST --user=$MYSQL_USER --password=$MYSQL_PASS $MYSQL_DB < add_pk.sql <file_sep>ALTER TABLE ADDRESS_ALIAS ADD CONSTRAINT ADDRESS_ALIAS_PK PRIMARY KEY (address_alias_pid); ALTER TABLE ADDRESS_ALIAS_TYPE_AUT ADD CONSTRAINT ADDRESS_ALIAS_TYPE_AUT_PK PRIMARY KEY (code); ALTER TABLE ADDRESS_CHANGE_TYPE_AUT ADD CONSTRAINT ADDRESS_CHANGE_TYPE_AUT_PK PRIMARY KEY (code); ALTER TABLE ADDRESS_DEFAULT_GEOCODE ADD CONSTRAINT ADDRESS_DEFAULT_GEOCODE_PK PRIMARY KEY (address_default_geocode_pid); ALTER TABLE ADDRESS_DETAIL ADD CONSTRAINT ADDRESS_DETAIL_PK PRIMARY KEY (address_detail_pid); ALTER TABLE ADDRESS_FEATURE ADD CONSTRAINT ADDRESS_FEATURE_PK PRIMARY KEY (address_feature_id); ALTER TABLE ADDRESS_MESH_BLOCK_2011 ADD CONSTRAINT ADDRESS_MESH_BLOCK_2011_PK PRIMARY KEY (address_mesh_block_2011_pid); ALTER TABLE ADDRESS_MESH_BLOCK_2016 ADD CONSTRAINT ADDRESS_MESH_BLOCK_2016_PK PRIMARY KEY (address_mesh_block_2016_pid); ALTER TABLE ADDRESS_SITE ADD CONSTRAINT ADDRESS_SITE_PK PRIMARY KEY (address_site_pid); ALTER TABLE ADDRESS_SITE_GEOCODE ADD CONSTRAINT ADDRESS_SITE_GEOCODE_PK PRIMARY KEY (address_site_geocode_pid); ALTER TABLE ADDRESS_TYPE_AUT ADD CONSTRAINT ADDRESS_TYPE_AUT_PK PRIMARY KEY (code); ALTER TABLE FLAT_TYPE_AUT ADD CONSTRAINT FLAT_TYPE_AUT_PK PRIMARY KEY (code); ALTER TABLE GEOCODED_LEVEL_TYPE_AUT ADD CONSTRAINT GEOCODED_LEVEL_TYPE_AUT_PK PRIMARY KEY (code); ALTER TABLE GEOCODE_RELIABILITY_AUT ADD CONSTRAINT GEOCODE_RELIABILITY_AUT_PK PRIMARY KEY (code); ALTER TABLE GEOCODE_TYPE_AUT ADD CONSTRAINT GEOCODE_TYPE_AUT_PK PRIMARY KEY (code); ALTER TABLE LEVEL_TYPE_AUT ADD CONSTRAINT LEVEL_TYPE_AUT_PK PRIMARY KEY (code); ALTER TABLE LOCALITY ADD CONSTRAINT LOCALITY_PK PRIMARY KEY (locality_pid); ALTER TABLE LOCALITY_ALIAS ADD CONSTRAINT LOCALITY_ALIAS_PK PRIMARY KEY (locality_alias_pid); ALTER TABLE LOCALITY_ALIAS_TYPE_AUT ADD CONSTRAINT LOCALITY_ALIAS_TYPE_AUT_PK PRIMARY KEY (code); ALTER TABLE LOCALITY_CLASS_AUT ADD CONSTRAINT LOCALITY_CLASS_AUT_PK PRIMARY KEY (code); ALTER TABLE LOCALITY_NEIGHBOUR ADD CONSTRAINT LOCALITY_NEIGHBOUR_PK PRIMARY KEY (locality_neighbour_pid); ALTER TABLE LOCALITY_POINT ADD CONSTRAINT LOCALITY_POINT_PK PRIMARY KEY (locality_point_pid); ALTER TABLE MB_2011 ADD CONSTRAINT MB_2011_PK PRIMARY KEY (mb_2011_pid); ALTER TABLE MB_2016 ADD CONSTRAINT MB_2016_PK PRIMARY KEY (mb_2016_pid); ALTER TABLE MB_MATCH_CODE_AUT ADD CONSTRAINT MB_MATCH_CODE_AUT_PK PRIMARY KEY (code); ALTER TABLE PRIMARY_SECONDARY ADD CONSTRAINT PRIMARY_SECONDARY_PK PRIMARY KEY (primary_secondary_pid); ALTER TABLE PS_JOIN_TYPE_AUT ADD CONSTRAINT PS_JOIN_TYPE_AUT_PK PRIMARY KEY (code); ALTER TABLE STATE ADD CONSTRAINT STATE_PK PRIMARY KEY (state_pid); ALTER TABLE STREET_CLASS_AUT ADD CONSTRAINT STREET_CLASS_AUT_PK PRIMARY KEY (code); ALTER TABLE STREET_LOCALITY ADD CONSTRAINT STREET_LOCALITY_PK PRIMARY KEY (street_locality_pid); ALTER TABLE STREET_LOCALITY_ALIAS ADD CONSTRAINT STREET_LOCALITY_ALIAS_PK PRIMARY KEY (street_locality_alias_pid); ALTER TABLE STREET_LOCALITY_ALIAS_TYPE_AUT ADD CONSTRAINT STREET_LOCALITY_ALIAS_TYPE__PK PRIMARY KEY (code); ALTER TABLE STREET_LOCALITY_POINT ADD CONSTRAINT STREET_LOCALITY_POINT_PK PRIMARY KEY (street_locality_point_pid); ALTER TABLE STREET_SUFFIX_AUT ADD CONSTRAINT STREET_SUFFIX_AUT_PK PRIMARY KEY (code); ALTER TABLE STREET_TYPE_AUT ADD CONSTRAINT STREET_TYPE_AUT_PK PRIMARY KEY (code); <file_sep>create index ADDRESS_DETAIL_PID on ADDRESS_DETAIL(address_detail_pid); create index ADDRESS_DEFAULT_GEOCODE_PID on ADDRESS_DEFAULT_GEOCODE(address_detail_pid); create index STREET_LOCALITY_PID on STREET_LOCALITY(street_locality_pid); create index LOCALITY_PID on LOCALITY(locality_pid); create index STATE_PID on STATE(state_pid); create index FLAT_TYPE_AUT_CODE on FLAT_TYPE_AUT(code); create index LEVEL_TYPE_AUT_CODE on LEVEL_TYPE_AUT(code); create index STREET_SUFFIX_AUT_CODE on STREET_SUFFIX_AUT(code); create index STREET_CLASS_AUT_CODE on STREET_CLASS_AUT(code); create index STREET_TYPE_AUT_CODE on STREET_TYPE_AUT(code); create index GEOCODE_TYPE_AUT_CODE on GEOCODE_TYPE_AUT(code); create index GEOCODED_LEVEL_TYPE_AUT_CODE on GEOCODED_LEVEL_TYPE_AUT(code) <file_sep># gnaf Some utilities for loading GNAF data into a database Not much order to this yet, it needs to be cleaned up. You can find the GNAF dataset here https://data.gov.au/dataset/ds-dga-19432f89-dc3a-4ef3-b943-5326ef1dbecc/details You can also find another of my projects which uses this data here: https://github.com/richardjkendall/location-service <file_sep>drop view if exists LOCATION_VIEW; create or replace view LOCATION_VIEW as select ad.address_detail_pid as gnafid, ad.building_name as addresssitename, ad.flat_type_code as unittypecode, concat(ad.flat_number, ad.flat_number_suffix) as unitnumber, ad.level_type_code as leveltypecode, concat(ad.level_number, ad.level_number_suffix) as levelnumber, concat(ad.lot_number, ad.lot_number_suffix) as lotnumber, concat(ad.number_first, ad.number_first_suffix) as roadnumber1, concat(ad.number_last, ad.number_last_suffix) as roadnumber2, sl.street_name as roadname, sta.name as roadtypecode, l.locality_name as localityname, ad.postcode as postcode, st.state_abbreviation as statecode, adg.latitude as latitude, adg.longitude as longitude from ADDRESS_DETAIL ad left join LOCALITY l on l.locality_pid = ad.locality_pid left join STREET_LOCALITY sl on sl.street_locality_pid = ad.street_locality_pid left join STREET_TYPE_AUT sta on sta.code = sl.street_type_code left join STATE st on st.state_pid = l.state_pid left join ADDRESS_DEFAULT_GEOCODE adg on adg.address_detail_pid = ad.address_detail_pid where ad.confidence > -1;
e952bd7fb033997f2389db057a3ef0b8378fd6bf
[ "Markdown", "SQL", "Shell" ]
8
Markdown
richardjkendall/gnaf
b32ee1c6beb3e2a17f747d2c4e048b670762044b
b43cd69b2e2995c337d4f9e6ae070b936a34e608
refs/heads/master
<file_sep>## React Boilerplate This is a react boilerplate codebase built off of [Create React App](https://github.com/facebook/create-react-app) to get you started quicker. It includes ESLint setup with recommended react settings and Prettier installed for correct automatic formatting along with SASS for SCSS. Additionally, react-router has been added in for a more component driven implementation which will allow you to add multiple components/pages relatively easily and quickly should you so desire. ### Getting Started In order to get started, you must install all the dependencies locally by running #### `yarn install` Once you have done this, you can get it started by running #### `yarn start` This will run the app in the development mode (with hot reloading). You can then view it at [http://localhost:3000](http://localhost:3000) in the browser. #### `yarn build` This will create the static files needed in order to host the web app online <file_sep>import React, { Component } from 'react'; export class Home extends Component { constructor(props) { super(props); this.state = { message: 'Click on the button' }; this.updateText = this.updateText.bind(this); } updateText() { const thisContext = this; this.setState({ message: 'Thanks for clicking the button' }); setTimeout(function () { thisContext.setState({ message: 'Click on the button' }); }, 3000); } render() { return ( <div className="mt-5"> <h4>{this.state.message}</h4> <button className="mt-4" onClick={this.updateText}> CLICK ME </button> </div> ); } } export default Home;
51e65475296930a5068deccc155d17fc047b92f2
[ "Markdown", "JavaScript" ]
2
Markdown
HazAnwar/React-Boilerplate
77029263023eb57324a9f9f28e6af971f7c8232b
d9df500224ef18ad412cb84504ba90058c14ac6c
refs/heads/master
<file_sep>/** * Created by hong-drmk on 2017/7/19. */ import React, { PureComponent, PropTypes } from 'react' import { SectionList, Text, View, TouchableOpacity } from 'react-native' import type { Props as FlatListProps } from 'FlatList' type DataBase = { title: string, onPress: (info: { item: DataBase, index: number }) => void } type RequiredProps = { sections: Array } type Props = RequiredProps & FlatListProps class List extends PureComponent { props: Props render() { return ( <SectionList keyExtractor={(item, index) => index} sections={this.props.sections} renderItem={({ item, index }) => ( <TouchableOpacity style={{ height: 44, justifyContent: 'center', padding: 10 }} onPress={item.onPress}> <Text>{index} {item.title}</Text> </TouchableOpacity> )} renderSectionHeader={({ section }) => ( <View style={{ backgroundColor: 'black', padding: 10 }}> <Text style={{ color: 'white' }}>{section.key}</Text> </View> )} ItemSeparatorComponent={SeparatorComponent} {...this.props} /> ) } } class SeparatorComponent extends React.PureComponent { render() { return <View style={{ height: 0.5, backgroundColor: 'gray' }} /> } } export default List<file_sep>## 笔记草稿 ``` 创建 project react-native init AwesomeProject cd AwesomeProject react-native run-ios ``` ``` npm start 启动packager服务 react-native run-ios 启动应用 ``` ``` "Unable to resolve module" 或者 缺少模块时 1. watchman watch-del-all 2. rm -rf node_modules && npm install 3. npm start -- --reset-cache 4. npm install <pkg>@<version> ``` ``` babel-polyfill Babel默认只转换新的JavaScript句法(syntax),而不转换新的API,比如Iterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise等全局对象,以及一些定义在全局对象上的方法(比如Object.assign)都不会转码。 举例来说,ES6在Array对象上新增了Array.from方法。Babel就不会转码这个方法。如果想让这个方法运行,必须使用babel-polyfill,为当前环境提供一个垫片。 http://www.ruanyifeng.com/blog/2016/01/babel.html ``` ``` Components - React.Component - React.PureComponent React提出的组件的概念,把UI隔离独立出来,让它可重用、独立使用。React.Component 是一个抽象基类, 一般需要继承它来使用。 React.PureComponent 很像 React.Component ,但是实现了 shouldComponentUpdate()  方法来浅比较 props 和 state , 可以用它这个特性来提高性能。注意它是浅比较,适合简单数据结构的比较。如果是复杂数据结构发生了变化,默认实现会返回false,不会更新页面。 有关组件更新的更多知识(https://segmentfault.com/a/1190000007811296) ``` ``` 函数的prototype属性 __proto__ 与 prototype Object.getPrototypeOf  - {实例}.__proto__ - {函数}.prototype ``` ``` ListView 源码 - 渲染使用ScrollView.js - 懒加载item - 用xcode调试时发现,RCTView始终保持subview一个均衡的个数。(ScrollView 的 removeClippedSubviews 属性,移除看不见的子视图) - RCTView的subview不复用 ``` ``` ScrollView 源码 - removeClippedSubviews 属性可以移除看不见的子视图,但是不能复用 ``` ``` FlatList - 渲染可视区域的上下一部分视图 - 设置 removeClippedSubviews 属性了才可以移除看不见的子视图 ``` ``` SectionList - 同FlatList一样,渲染可视区域的上下一部分视图 - 设置 removeClippedSubviews 属性了才可以移除看不见的子视图 ``` ``` 动画 - requestAnimationFrame 它接受一个函数作为唯一的参数,并且在下一次重绘之前调用此函数。 - setNativeProps setNativeProps方法可以使我们直接修改基于原生视图的组件的属性,而不需要使用setState来重新渲染整个组件树。 - LayoutAnimation 优点: 1、效果非常的流畅,而且动画的过程很柔和,丝毫没有生硬的感觉。 2、可以灵活的配置动画参数,基本能满足单个动画的需求。 缺点: 1、如果要实现‘组合顺序’动画,比如先缩小50%、再向左平移100像素,那么就比较麻烦了,需要监听上一个动画的结束事件,再进行下一个。那么问题来了,configureNext第二个参数是可以监听动画结束的,但是只在IOS平台有效! 2、如果动画的效果更为复杂,比如同时执行动画,再顺序执行,对于编程来讲,需要做的事情很多,复杂度也大大提升。 - Animated ``` ``` 关于绑定this,为什么箭头函数不用绑定this? 继承的函数也不用绑定this? ``` ``` 关于绑定this对象,call()、apply()、bind() 等方法 /** @param {Object} [thisArg] @param {Array} [argArray] @return {*} */ Function.prototype.apply = function(thisArg,argArray) {}; /** @param {Object} [thisArg] @param {...*} [args] @return {*} */ Function.prototype.call = function(thisArg,args) {}; Function = {}; /** @param {T} thisArg @param {...*} [arg] @return {function(this:T)} @template T */ Function.prototype.bind = function(thisArg,arg) {}; apply() 第二个参数是数组, call() 第二个参数是reset参数, bind() 第二个参数是reset参数, 返回值是函数 函数在哪里调用才决定了this到底引用的是啥 箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。 ``` ``` 获取屏幕尺寸 import { Dimensions } from ‘react-native’ Dimensions.get('window').height ``` ``` 获取组件尺寸 import { UIManager, findNodeHandle } from ‘react-native’ const handle = findNodeHandle(this.textInput) UIManager.measure(handle, (x, y, width, height, pageX, pageY) => { //在这获取 }) ``` <file_sep>/** * Created by hong-drmk on 2017/8/18. */ import React, { Component } from 'react' import { Animated, View, Button, } from 'react-native' class Simple extends Component { constructor(props) { super(props) this.state = { /* 1. 初始化动画值 * */ fadeAnim: new Animated.Value(0) } } render() { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Animated.Text style={{ /* 2. 将动画值绑定到style的属性 * */ opacity: this.state.fadeAnim }}> Simple Animated Used Animated.timing </Animated.Text> <Button title="touch me" onPress={() => { /* 3. 处理动画值,并启动动画 * */ Animated.timing( this.state.fadeAnim, { duration: 1000, toValue: 1 } ).start() }} /> </View> ) } } export default Simple<file_sep>文档在这里: - [Animations](https://github.com/liuyanhongwl/react_common/blob/master/react-native/files/animations.md):react native 的常用动画方式<file_sep>/** * Created by hong-drmk on 2017/8/18. */ import React, { Component } from 'react' import { Animated, PanResponder, Text, } from 'react-native' class TouchEvent extends Component { constructor(props) { super(props) this.state = { animValue: new Animated.Value(0) } this.panRespander = PanResponder.create({ onStartShouldSetResponder: () => true, onStartShouldSetPanResponderCapture: () => true, onPanResponderMove: Animated.event([{ nativeEvent: { pageX: this.state.animValue } }]) }) } render() { return ( <Animated.View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: this.state.animValue.interpolate({ inputRange: [0, 300], outputRange: ['#FFFFF0', '#FF0000'] }) }} {...this.panRespander.panHandlers}> <Text style={{ fontSize: 30 }}>横向滑动我</Text> </Animated.View> ) } } export default TouchEvent<file_sep>/** * Created by hong-drmk on 2017/8/18. */ import React, { Component } from 'react' import { Animated, ScrollView, View, } from 'react-native' class ScrollEvent extends Component { constructor(props) { super(props) this.state = { offsetYAnim: new Animated.Value(0) } } render() { return ( <ScrollView style={{ flex: 1, backgroundColor: 'lightgray' }} /* 将事件映射到值 * */ onScroll={Animated.event([{ nativeEvent: { contentOffset: { y: this.state.offsetYAnim } } }])} scrollEventThrottle={100} > <Animated.View style={{ width: '100%', height: 300, backgroundColor: 'skyblue', transform: [{ scale: this.state.offsetYAnim.interpolate({ inputRange: [0, 300], outputRange: [1, 0.6] }) }] }} /> <View style={{ width: '100%', height: 300, backgroundColor: 'red' }} /> <View style={{ width: '100%', height: 300, backgroundColor: 'green' }} /> <View style={{ width: '100%', height: 300, backgroundColor: 'orange' }} /> </ScrollView> ) } } export default ScrollEvent<file_sep>/** * Created by hong-drmk on 2017/8/21. */ import React, { Component } from 'react' import { View, Button, Text, LayoutAnimation, } from 'react-native' class SimpleLayoutAnimation extends Component { constructor(props) { super(props) this.state = { size: 60, bigTag: false, //标志位 } } item = (title, subtitle, onPress) => { return ( <View style={{ flexDirection: 'row', alignItems: 'center' }}> <Button title={title} onPress={onPress} /> <Text> {subtitle}</Text> </View> ) } render() { return ( <View style={{ alignItems: 'center' }}> <View style={{ backgroundColor: 'skyblue', width: this.state.size, height: this.state.size, borderRadius: this.state.size / 2.0, }} /> <View style={{ backgroundColor: 'red', width: 100, height:100 }} /> <View style={{ backgroundColor: 'skyblue', width: this.state.size, height: this.state.size, borderRadius: this.state.size / 2.0, }} /> { this.item('linear', 'configureNext', () => { //设置动画在下一次render/layout cycle //直接使用configureNext方法配置参数 LayoutAnimation.configureNext({ duration: 1000, create: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.opacity, }, update: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.scaleXY, } }) this.setState({ size: this.state.bigTag ? 60 : 100, bigTag: !this.state.bigTag, }) }) } { this.item('easeInEaseOut', 'configureNext + create', () => { //使用create方法快捷生成configureNext所需的config参数 LayoutAnimation.configureNext( LayoutAnimation.create(1000, LayoutAnimation.Types.easeInEaseOut, LayoutAnimation.Properties.scaleXY) ) this.setState({ size: this.state.bigTag ? 60 : 100, bigTag: !this.state.bigTag, }) }) } { this.item('spring', 'configureNext + Presets', () => { //使用easeInEaseOut、linear、spring方法快捷生成configureNext所需的config参数 LayoutAnimation.configureNext( LayoutAnimation.Presets.spring ) this.setState({ size: this.state.bigTag ? 60 : 100, bigTag: !this.state.bigTag, }) }) } { this.item('spring', 'spring', () => { //直接使用easeInEaseOut、linear、spring方法 LayoutAnimation.spring() this.setState({ size: this.state.bigTag ? 60 : 100, bigTag: !this.state.bigTag, }) }) } </View> ) } } export default SimpleLayoutAnimation
fa3fddd92ece90edc537f5a2ef8523e930b757c5
[ "Markdown", "JavaScript" ]
7
Markdown
liuyanhongwl/react-native-demos
f557253afa731087a971591fc7b528e46a7b5b6b
03ffcf5cd7219643811b4f2567b85c5443d480b4
refs/heads/master
<file_sep># t-repo HTML+CSS --> t-repo > Test > task_1 > test-page > test-page.html Table editor on AngularJS --> t-repo > Test > task_2 > table-redactor.html
658d39045cc4817fdb2ddeb672a609d903069724
[ "Markdown" ]
1
Markdown
bo2d/t-repo
412ad6ca032ace3d4b74c51994803d1dd43f324f
4384b40863a169a757832022aadf3dbbbab39800
refs/heads/master
<file_sep>from enum import Enum from collections import deque class Entity: player_entity = 0 textured_list = [] dirty_textured_list = [] moveable_list = [] collidable_list = [] def setDirty(self): if self.dirty: return Entity.dirty_textured_list.append(self) self.dirty = True def unsetDirty(self, rect): if not self.dirty: return Entity.dirty_textured_list.remove(self) self.clean_rect = rect self.dirty = False def __init__(self, eid, type_list, components_list): self.eid = eid self.dirty = False self.clean_rect = 0 #Parse Components for component in components_list: if isinstance(component.componentType, ComponentNames): setattr(self, component.componentType.name, component.value) elif isinstance(component.componentType, str): setattr(self, component.componentType, component.value) else: raise TypeError("BROKEN ENTITY with eid " + str(eid) + "\n!!The Component name should be either a Component Type, or a string!!") #Check if the entity has Positinal components passed, if not raise error try: self.POS_X self.POS_Y except AttributeError: raise ValueError("BROKEN ENTITY with eid " + str(self.eid) + "\nThis Entity has a missing Position Component!") #Parse types and check for missing type specific components for type in type_list: if type == EntityType.COLLIDABLE: #TODO COLLISION LOGIC AND SHIT Entity.collidable_list.append(self) if type == EntityType.MOVEABLE: try: self.VELOCITY_X self.VELOCITY_Y except AttributeError: raise ValueError("BROKEN ENTITY with eid " + str(self.eid) + "\nMISSING VELOCITY COMPONENTS") try: self.ACCELERATION_X self.ACCELERATION_Y except AttributeError: raise ValueError("BROKEN ENTITY with eid " + str(self.eid) + "\nMISSING ACCELERATION COMPONENTS!!! ") try: self.VELOCITY_CAP_X self.VELOCITY_CAP_Y except AttributeError: raise ValueError("BROKEN ENTITY with eid " + str(self.eid) + "\nMISSING VELOCITY_CAP COMPONENTS!!") Entity.moveable_list.append(self) if type == EntityType.TEXTURED: try: self.TEXTURE except AttributeError: raise ValueError("BROKEN ENTITY with eid " + str(self.eid) + "\nMISSING TEXTURE COMPONENT!!!") Entity.textured_list.append(self) if type == EntityType.PLAYER_ENTITY: Entity.player_entity = self self.setDirty() class Component: def __init__(self, componentType, value): self.componentType = componentType self.value = value class EntityType(Enum): MOVEABLE = 1 TEXTURED = 2 COLLIDABLE = 3 PLAYER_ENTITY = 4 class ComponentNames(Enum): TEXTURE = "texture" POS_X = "PosX" POS_Y = "PosY" VELOCITY_Y = "VelocityY" VELOCITY_X = "VelocityX" ACCELERATION_X = "AccelerationX" ACCELERATION_Y = "AccelerationY" VELOCITY_CAP_X = "VelocityCapX" VELOCITY_CAP_Y = "VelocityCapY" def __str__(self): return self.name <file_sep>import Game.settings from Game.controlls import doKeys import Game.ecs as ECS import pygame.time as time from collections import deque # temp import pygame.image render_clock = time.Clock() def init(): pepega = pygame.image.load("./smol_pepega.png").convert_alpha() ECS.Entity(1, [ECS.EntityType.TEXTURED, ECS.EntityType.MOVEABLE, ECS.EntityType.PLAYER_ENTITY], [ ECS.Component(ECS.ComponentNames.TEXTURE, pepega), ECS.Component(ECS.ComponentNames.POS_X, 100.0), ECS.Component(ECS.ComponentNames.POS_Y, 150.0), ECS.Component(ECS.ComponentNames.VELOCITY_X, 0.0), ECS.Component(ECS.ComponentNames.VELOCITY_Y, 0.0), ECS.Component(ECS.ComponentNames.ACCELERATION_X, 0.05), ECS.Component(ECS.ComponentNames.ACCELERATION_Y, 0.05), ECS.Component(ECS.ComponentNames.VELOCITY_CAP_X, 0.15), ECS.Component(ECS.ComponentNames.VELOCITY_CAP_Y, 0.15) ]) ECS.Entity(2, [ECS.EntityType.TEXTURED, ECS.EntityType.MOVEABLE], [ ECS.Component(ECS.ComponentNames.TEXTURE, pepega), ECS.Component(ECS.ComponentNames.POS_X, 10.0), ECS.Component(ECS.ComponentNames.POS_Y, 350.0), ECS.Component(ECS.ComponentNames.VELOCITY_X, 0.1), ECS.Component(ECS.ComponentNames.VELOCITY_Y, 0), ECS.Component(ECS.ComponentNames.ACCELERATION_X, 0), ECS.Component(ECS.ComponentNames.ACCELERATION_Y, 0), ECS.Component(ECS.ComponentNames.VELOCITY_CAP_X, 1), ECS.Component(ECS.ComponentNames.VELOCITY_CAP_Y, 1) ]) def draw(screen): render_clock.tick(Game.settings.fps_limit) rects = deque() for entity in ECS.Entity.dirty_textured_list: if entity.clean_rect != 0: rects.append(screen.fill((0, 0, 0), entity.clean_rect)) rect = screen.blit(entity.TEXTURE, (int(entity.POS_X), int(entity.POS_Y))) rects.append(rect) entity.unsetDirty(rect) # TODO this impacts performance heavily! OPTIMIZE!!!! pygame.display.update(rects) #print(render_clock.get_fps()) #print(getattr(player, ECS.ComponentNames.VELOCITY_X.value)) pass <file_sep>from enum import Enum import pygame.locals import Game.ecs as ECS class KeyFunctions(Enum): NONE = 0x00 #ADD KEYS HERE STRAFE_RIGHT = 0x01 STRAFE_LEFT = 0x02 UP = 0x03 DOWN = 0x04 pressed_keys = set() #TODO make this read json setting_keys = { KeyFunctions.STRAFE_LEFT: 97, KeyFunctions.STRAFE_RIGHT: 100, #KeyFunctions.STRAFE_LEFT: 276, #KeyFunctions.STRAFE_RIGHT: 275 KeyFunctions.UP: 119, KeyFunctions.DOWN: 115 } def isPressed(key_function): return setting_keys.get(key_function, 0x404) in pressed_keys # MOVEMENT LOGIC #No longer check for missing key setting, might add later ##### X AXIS def StrafeLeft(velocityX, VelocityCapX, AccelerationX): if not velocityX <= -VelocityCapX: ECS.Entity.player_entity.VELOCITY_X = velocityX - AccelerationX ECS.Entity.player_entity.setDirty() print(velocityX) pass def StrafeRight(velocityX, VelocityCapX, AccelerationX): if not velocityX >= VelocityCapX: ECS.Entity.player_entity.VELOCITY_X = velocityX + AccelerationX ECS.Entity.player_entity.setDirty() print(velocityX) pass #TODO implement momentum? def StrafeSlow(velocityX): if velocityX == 0: return if velocityX < 0: ECS.Entity.player_entity.VELOCITY_X = 0 elif velocityX > 0: ECS.Entity.player_entity.VELOCITY_X = 0 print("SLOW") pass ##### Y AXIS def Up(velocityY, VelocityCapY, AccelerationY): if not velocityY <= -VelocityCapY: ECS.Entity.player_entity.VELOCITY_Y = velocityY - AccelerationY ECS.Entity.player_entity.setDirty() def Down(velocityY, VelocityCapY, AccelerationY): if not velocityY >= VelocityCapY: ECS.Entity.player_entity.VELOCITY_Y = velocityY + AccelerationY ECS.Entity.player_entity.setDirty() def SlowY(velocityY): if velocityY == 0: return if velocityY < 0: ECS.Entity.player_entity.VELOCITY_Y = 0 elif velocityY > 0: ECS.Entity.player_entity.VELOCITY_Y = 0 #checks pressed keys and call their functions def doKeys(): #check pressed keys here strafe_left_pressed = isPressed(KeyFunctions.STRAFE_LEFT) strafe_right_pressed = isPressed(KeyFunctions.STRAFE_RIGHT) up_pressed = isPressed(KeyFunctions.UP) down_pressed = isPressed(KeyFunctions.DOWN) #TODO get rid of getatts velocityX = ECS.Entity.player_entity.VELOCITY_X velocityY = ECS.Entity.player_entity.VELOCITY_Y VelocityCapX = ECS.Entity.player_entity.VELOCITY_CAP_X VelocityCapY = ECS.Entity.player_entity.VELOCITY_CAP_Y AccelerationX = ECS.Entity.player_entity.ACCELERATION_X AccelerationY = ECS.Entity.player_entity.ACCELERATION_Y #slow down/stop if no keys pressed (x axis) if not strafe_left_pressed and not strafe_right_pressed: StrafeSlow(velocityX) else: if strafe_left_pressed: StrafeLeft(velocityX, VelocityCapX, AccelerationX) if strafe_right_pressed: StrafeRight(velocityX, VelocityCapX, AccelerationX) if not up_pressed and not down_pressed: SlowY(velocityY) else: if up_pressed: Up(velocityY, VelocityCapY, AccelerationY) if down_pressed: Down(velocityY, VelocityCapY, AccelerationY) def KeyDown(event): pressed_keys.add(event.key) #if setting_keys.get(event.key, KeyFunctions.NONE) == KeyFunctions.STRAFE_LEFT: def KeyUp(event): pressed_keys.remove(event.key) <file_sep>window_caption = "FORSAAAAAAAAAAAAN" window_size = (0, 0) gameTime_running = True gameRenderer_running = True fps_limit = 0 <file_sep># What is pEngine? Its supposed to be a "game engine". The goal of this project was to make a PyGame Engine which is easily modifiable, so you can test out and learn stuff!. ## How do you use it? 1. Clone this repo 2. Modify code. Comments and the docs should help you out. 3. run it! ``python main.py`` (build for python3) ## TODO List - [ ] Collision Detection - [ ] Level support - [ ] Move all settings to json files - [ ] Project Documentation - and a lot of stuff<file_sep>import Game.settings as Settings import Game.ecs as ECS import Game.controlls import pygame.time as time game_clock = time.Clock() def tick(): dt = game_clock.tick(0) Game.controlls.doKeys() doMovement(dt) # moves all entities by their velocity def doMovement(dt): for entity in ECS.Entity.moveable_list: PosX = entity.POS_X PosY = entity.POS_Y VelocityX = entity.VELOCITY_X VelocityY = entity.VELOCITY_Y entity.POS_X = PosX + VelocityX * dt entity.POS_Y = PosY + VelocityY * dt entity.setDirty() <file_sep>#!/usr/bin/python import pygame from Game import settings as Settings from Game import renderer as Renderer from Game.events import handle as HandleEvent import Game.gametime # def main(): pygame.init() pygame.display.set_caption(Settings.window_caption) screen = pygame.display.set_mode(Settings.window_size, pygame.DOUBLEBUF) #TODO make this level dependant, aka, multiple level support and shit Renderer.init() while Settings.gameRenderer_running: for event in pygame.event.get(): HandleEvent(event) Game.gametime.tick() Renderer.draw(screen) pygame.quit() if __name__ == "__main__": main() <file_sep>import pygame.locals, pygame.key import Game.settings, Game.controlls def handle(event): if(event.type == pygame.QUIT): quitGame() if(event.type == pygame.KEYDOWN): Game.controlls.KeyDown(event) if(event.type == pygame.KEYUP): Game.controlls.KeyUp(event) pass def quitGame(): Game.settings.gameTime_running = False Game.settings.gameRenderer_running = False
d14da20df44d7771e96989d21311ca8e8c2a2130
[ "Markdown", "Python" ]
8
Markdown
KrDimitrov/pEngine
d3c8f47b9599b51e12bb8e92de849f9bbd2cd8c7
42ae7b1a30f5cd6bf397c6ba0663210d87789150
refs/heads/master
<file_sep>/** * Created by Brandon on 10/27/2016. */ import './profiles.js';<file_sep># final-project-mockup ![](https://github.com/brandon-chun/final-project-mockup/master/doc/home-page.png) ![](https://github.com/brandon-chun/final-project-mockup/master/doc/events-page.png) ![](https://github.com/brandon-chun/final-project-mockup/master/doc/profile-page.png))<file_sep>/** * Created by Brandon on 10/27/2016. */ import { ReactiveDict } from 'meteor/reactive-dict'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { _ } from 'meteor/underscore'; import { Profiles, ProfilesSchema } from '../../api/profiles/profiles.js'; /* eslint-disable object-shorthand, no-unused-vars */ const displaySuccessMessage = 'displaySuccessMessage'; const displayErrorMessages = 'displayErrorMessages'; Template.Profile_Page.onCreated(function onCreated() { this.autorun(() => { this.subscribe('Profiles'); }); this.messageFlags = new ReactiveDict(); this.messageFlags.set(displaySuccessMessage, false); this.messageFlags.set(displayErrorMessages, false); this.context = ProfilesSchema.namedContext('Profile_Page'); }); Template.Profile_Page.helpers({ profileField(fieldName) { const profile = Profiles.findOne(FlowRouter.getParam('_id')); // See https://dweldon.silvrback.com/guards to understand '&&' in next line. return profile && profile[fieldName]; }, errorClass() { return Template.instance().messageFlags.get(displayErrorMessages) ? 'error' : ''; }, displayFieldError(fieldName) { const errorKeys = Template.instance().context.invalidKeys(); return _.find(errorKeys, (keyObj) => keyObj.name === fieldName); }, }); // Template.Edit_Student_Data_Page.onRendered(function enableSemantic() { // const template = this; // template.subscribe('StudentData', () => { // // Use this template.subscribe callback to guarantee that the following code executes after subscriptions OK. // Tracker.afterFlush(() => { // // Use Tracker.afterFlush to guarantee that the DOM is re-rendered before calling JQuery. // template.$('select.ui.dropdown').dropdown(); // template.$('.ui.selection.dropdown').dropdown(); // template.$('select.dropdown').dropdown(); // template.$('.ui.checkbox').checkbox(); // template.$('.ui.radio.checkbox').checkbox(); // }); // }); // }); Template.Profile_Page.events({ 'submit .profile-data-form'(event, instance) { event.preventDefault(); // Get name (text field) const name = event.target.name.value; // Get bio (text area). const email = event.target.email.value; const bio = event.target.bio.value; const updatedProfile = { name, email, bio }; // Clear out any old validation errors. instance.context.resetValidation(); // Invoke clean so that newStudentData reflects what will be inserted. ProfilesSchema.clean(updatedProfile); // Determine validity. instance.context.validate(updatedProfile); if (instance.context.isValid()) { Profiles.update(FlowRouter.getParam('_id'), { $set: updatedProfile }); instance.messageFlags.set(displayErrorMessages, false); FlowRouter.go('Profile_Page'); } else { instance.messageFlags.set(displayErrorMessages, true); } }, }); <file_sep>import './accounts.js'; <file_sep>import { Mongo } from 'meteor/mongo'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; /* eslint-disable object-shorthand */ export const Profiles = new Mongo.Collection('Profiles'); /** * Create the schema for Stuff */ export const ProfilesSchema = new SimpleSchema({ name: { label: 'name', type: String, optional: false, max: 2000, }, email: { label: 'email', type: String, optional: false, max: 200, }, bio: { label: 'bio', type: String, optional: true, defaultValue: '', max: 500, }, }); Profiles.attachSchema(ProfilesSchema);
83f13ad1d7089f264163a19a8c43456671157286
[ "Markdown", "JavaScript" ]
5
Markdown
brandon-chun/final-project-mockup
fea35388edffc2b24d0401999cf8d1fd5f1a4dc2
297b5e11f197f1c524607209d473c1b193cdc037
refs/heads/master
<repo_name>16348104/16348104.github.com<file_sep>/java/src/inherited/PassTest.java package inherited; /** * Created by xdx on 2015/10/31. */ public class PassTest { private int i;// Integer public static void method(PassTest passTest) {// 形式参数 类类型 System.out.println("b: i = " + passTest.i); passTest.i += 1000; System.out.println("c: i = " + passTest.i); } // public static void test(String string) { // string += "test"; // } // public static void integerTest(Integer i) { // i++; // } public static void main(String[] args) { PassTest passTest = new PassTest(); // passTest.i = 0; System.out.println("a: i = " + passTest.i); method(passTest);// 实际参数 System.out.println("d: i = " + passTest.i); String string = "测试"; // test(string); // System.out.println(string); int i = 0; // integerTest(i); System.out.println(i); } } <file_sep>/java/src/BooleanDemo.java /** * Created by Administrator on 2015/10/18. */ public class BooleanDemo { public static void main(String[] args) { boolean a = true; boolean b = true; boolean c = false; boolean d = false; System.out.println("---- & ----"); System.out.println(a & b);// true System.out.println(a & c); System.out.println(c & a); System.out.println(c & d); System.out.println("---- | ----"); System.out.println(a | b); System.out.println(a | c); System.out.println(c | a); System.out.println(c | d);// false System.out.println("---- ^ ----"); System.out.println(a ^ b);// false System.out.println(a ^ c); System.out.println(c ^ a); System.out.println(c ^ d);// false System.out.println("---- ! ----"); System.out.println(!a);// false System.out.println(!c);// true System.out.println("---- && ----"); System.out.println(a && b);//true System.out.println(a && c); System.out.println(c && a); System.out.println(c && d); System.out.println("---- || ----"); System.out.println(a || b); System.out.println(a || c); System.out.println(c || a); System.out.println(c || d);//false System.out.println("------------"); int x = 0; int y = 1; // System.out.println(x > y); // System.out.println(x++); // System.out.println(x); System.out.println((x > y) && (x++ > 0)); System.out.println("x = " + x); } } <file_sep>/java/src/AssignDemo.java /** * Created by Administrator on 2015/10/18. */ public class AssignDemo { public static void main(String[] args) { int x = 1; x |= 2;// x = (x + 100)按照位运算执行 ; System.out.println(x); int y = -1; } } <file_sep>/java/src/exercise/E31.java package exercise; /** * Created by xdx on 2015/11/24. * 将一个数组逆序输出。 */ public class E31 { public static void main(String[] args) { int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; System.out.println("原数组:"); for (int i = 0; i < a.length; i++) { System.out.print( a[i]); } System.out.println(); int len = a.length; for (int i = 0; i < len / 2; i++) { int tem = a[i]; a[i] = a[a.length - i - 1]; a[a.length-i-1]=tem; } System.out.println("倒序数组:"); for (int i = 0; i < a.length; i++) { System.out.print(a[i]); } } } <file_sep>/DB/dict.sql DROP DATABASE IF EXISTS demo4; CREATE DATABASE demo4; DROP TABLE IF EXISTS demo4.word; CREATE TABLE demo4.word ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '词汇编号', english TEXT COMMENT '词汇', phonetic_uk VARCHAR(255) COMMENT '发声', phonetic_us VARCHAR(255) COMMENT '发声', audio_uk_male VARCHAR(255) COMMENT '英语女声', audio_uk_female VARCHAR(255) COMMENT '英语男声', audio_us_male VARCHAR(255) COMMENT '美语女声', audio_us_female VARCHAR(255) COMMENT '英语男声' ) COMMENT '单词表'; SHOW FULL COLUMNS FROM demo4.word; DROP TABLE IF EXISTS demo4.word_defination; CREATE TABLE demo4.word_defination ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键id', word_id INT(11) UNSIGNED COMMENT '词性标号', chinese TEXT COMMENT '词汇中文解释', part_of_speach VARCHAR(255) COMMENT '发音' ) COMMENT '词性表'; ALTER TABLE demo4.word_defination ADD CONSTRAINT fk_char_word FOREIGN KEY (word_id) REFERENCES demo4.word (id); SHOW FULL COLUMNS FROM demo4.word_defination; DROP TABLE IF EXISTS demo4.word_sentence; CREATE TABLE demo4.word_sentence ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键id', word_id INT(11) UNSIGNED COMMENT '例句表号', chinese_sentence TEXT COMMENT '中文例句', english_sentence TEXT COMMENT '英语例句', audio_male VARCHAR(255) COMMENT '女生发音', audio_female VARCHAR(255) COMMENT '男生发音', source VARCHAR(255) COMMENT '网站来源' ) COMMENT '例句表'; ALTER TABLE demo4.word_sentence ADD CONSTRAINT fk_exa_ex FOREIGN KEY (word_id) REFERENCES demo4.word (id); SHOW FULL COLUMNS FROM demo4.word_sentence; DROP TABLE IF EXISTS demo4.word_root; CREATE TABLE demo4.word_root ( id INT(11) UNSIGNED AUTO_INCREMENT COMMENT '主键id', word_id INT(11) UNSIGNED COMMENT '单词表号', prefix TEXT COMMENT '前缀', suffix TEXT COMMENT '后缀', chinese VARCHAR(255) COMMENT '中文意思', PRIMARY KEY (id, word_id) ) COMMENT '词根表'; ALTER TABLE demo4.word_root ADD CONSTRAINT fk__wordid FOREIGN KEY (word_id) REFERENCES demo4.word (id); SHOW FULL COLUMNS FROM demo4.word_root; <file_sep>/java/src/abst/Shape.java package abst; /** * Created by xdx on 2015/10/27. */ public abstract class Shape { abstract double Periemter(); abstract double Area(); } <file_sep>/DB/day2.sql CREATE DATABASE demo; CREATE TABLE demo.student ( id INT(11) PRIMARY KEY, name VARCHAR(20) NOT NULL, age INT(3) UNIQUE, sex CHAR(1) DEFAULT '男' ); DELETE FROM demo.student WHERE id = 2015003; UPDATE demo.student SET id = 2015003 WHERE id = 2015002; DROP TABLE demo.sc; DROP TABLE demo.student; SELECT * FROM demo.student; CREATE TABLE demo.course ( id INT(11) PRIMARY KEY, name VARCHAR(20) ); INSERT INTO demo.course VALUES (1, 'Java SE'); INSERT INTO demo.course VALUES (2, 'MySQL'); INSERT INTO demo.course VALUES (3, 'HTML'); SELECT * FROM demo.course; CREATE TABLE demo.sc ( sid INT(11), cid INT(11), grade INT(3), # PRIMARY KEY (sid, cid), CONSTRAINT fk_sc_sid FOREIGN KEY (sid) REFERENCES demo.student (id) ON DELETE CASCADE, # 级联 CONSTRAINT fk_sc_cid FOREIGN KEY (cid) REFERENCES demo.course (id) ON UPDATE SET NULL ); DROP TABLE demo.sc; INSERT INTO demo.sc VALUES (2015003, 2, NULL); INSERT INTO demo.sc VALUES (2, 2, NULL); INSERT INTO demo.sc VALUES (2, 1, NULL); INSERT INTO demo.sc VALUES (2, 1, NULL); SELECT * FROM demo.sc; DESC demo.student; DROP TABLE demo.student; INSERT INTO demo.student (id, name, age) VALUES (2015001, '张三', 18); INSERT INTO demo.student VALUES (2015002, '李四', 19, '女'); INSERT INTO demo.student (name, age, sex) VALUES ('王二', 20, '男'); UPDATE demo.student SET name = '李四', age = 20; DELETE FROM demo.student; SELECT * FROM demo.student; SELECT name, sex FROM demo.student; SELECT DISTINCT sex FROM demo.student; SELECT * FROM demo.student WHERE sex = '男'; SELECT * FROM demo.student WHERE age BETWEEN 19 AND 20; SELECT * FROM demo.student WHERE name LIKE '_三'; SELECT * FROM demo.student ORDER BY convert(sex USING gbk) DESC; # an v # asc = ascend # desc = descend # result set DESC scott.dept; # department DESC scott.emp; # employee DESC scott.salgrade; # salary grade SELECT * FROM scott.emp; SELECT * FROM scott.dept; SELECT * FROM scott.salgrade; SELECT * FROM scott.emp WHERE ENAME IN ('king', 'scott', 'adams'); SELECT * FROM scott.emp WHERE ENAME = 'king' OR ENAME = 'scott' OR ENAME = 'adams'; SELECT * FROM scott.emp WHERE EMPNO NOT BETWEEN 7500 AND 7788; SELECT ename AS n FROM scott.emp AS e WHERE e.ENAME = 'allen'; SELECT * FROM scott.emp LIMIT 0, 50; CREATE TABLE demo.test ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, text VARCHAR(255) ); DROP TABLE demo.test; INSERT INTO demo.test (text) VALUES ('asdf...'); INSERT INTO demo.test VALUES (2147483648, 'test...'); SELECT * FROM demo.test;<file_sep>/java/src/exercise/E11.java package exercise; /** * Created by dell on 2015/10/29. * 有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? * 程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。 */ public class E11 { } <file_sep>/DB/day1.sql CREATE DATABASE demo; USE demo; CREATE TABLE demo.s ( sno INT(8) UNSIGNED AUTO_INCREMENT PRIMARY KEY, sname VARCHAR(20) NOT NULL, ssex CHAR(1) DEFAULT '男', city VARCHAR(20) DEFAULT 'beijing', sage INT(3) ); INSERT INTO s VALUES (200201,'李勇','男','la',18); INSERT INTO s VALUES (200202 ,'刘晨','男','la',19); INSERT INTO s VALUES (200203,'张丽','女','la',20); DESC demo.s; DROP TABLE demo.s; SELECT * FROM s; # ALTER TABLE demo.s # del; CREATE TABLE Course ( cno INT(8) UNSIGNED AUTO_INCREMENT PRIMARY KEY , cname VARCHAR(20) NOT NULL # cpno VARCHAR(4) DEFAULT 'null' ); DESC demo.Course; DROP TABLE Course; INSERT INTO demo.Course VALUES (NULL ,'java se'); INSERT INTO demo.Course VALUES (2,'html'); INSERT INTO demo.Course VALUES (3,'mysql'); SELECT * FROM demo.Course; CREATE TABLE demo.sc( sno INT(8) UNSIGNED, cno INT(8) UNSIGNED, grade INT(4) # PRIMARY KEY (sno,cno), # FOREIGN KEY (sno) REFERENCES s(sno) ON DELETE SET NULL , # FOREIGN KEY (cno) REFERENCES Course(cno) ON UPDATE SET NULL ); DROP TABLE Course; DESC Course; INSERT INTO demo.sc VALUES (200201,2,90); SELECT * FROM demo.sc; <file_sep>/java/src/ConditionDemo.java /** * Created by Administrator on 2015/10/18. */ public class ConditionDemo { public static void main(String[] args) { boolean x = (100%1000>10)?true:false; System.out.println(x); System.out.println("-----------"); int a = 100; int b = 1; String s1 = "hello,"; String s2 = " world!"; System.out.println(a + b); System.out.println(s1 + s2); System.out.println((b + a) + "..."+ a); } } <file_sep>/java/src/abst/Square.java package abst; /** * Created by Administrator on 2015/10/25. * 正方 */ public class Square extends Shape { private double a; public Square(double a) { this.a = a; } @Override public double Periemter() { return a*4; } @Override public double Area() { return Math.pow(a, 2); } // public double getA() { // return a; // } // // public void setA(int a) { // this.a = a; // } } <file_sep>/java/src/encapsulation/Calulate.java package encapsulation; /** * Created by Administrator on 2015/10/25. */ public class Calulate { private int x; private int y; public void add() { } } <file_sep>/java/src/io/ReadAndWriteTest2.java package io; import java.io.*; /** * Created by xdx on 2015/11/12. */ public class ReadAndWriteTest2 { public static void main(String[] args) { BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null; try { bufferedInputStream = new BufferedInputStream(new FileInputStream("f:/jquery-1.11.3.js")); bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("java/src/io/io")); int i; while ((i = bufferedInputStream.read()) != -1) { bufferedOutputStream.write(i); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedInputStream.close(); bufferedOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("done"); } } <file_sep>/java/src/Interface/DImpl.java package Interface; /** * Created by Administrator on 2015/10/31. */ public class DImpl extends Object implements A, B, C { @Override public void a() { } @Override public void b() { } @Override public void c() { } public static void main(String[] args) { } } <file_sep>/java/src/exercise/E37.java package exercise; import java.util.Scanner; /** * Created by XDX on 2015/11/25. * 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。 */ public class E37 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); System.out.println("请输入人数:"); // boolean [] arry=new boolean arry[true]; int count = 0; int total = 0; int index = 0; while ( total>1) { // if() { // count++; // } } } } <file_sep>/java/src/IfDemo.java /** * Created by Administrator on 2015/10/18. */ public class IfDemo { public static void main(String[] args) { int grade = 75; char c='优'; if (grade >= 85) { System.out.println("85-100"); } else if (grade >= 60) { System.out.println("60-70"); } else if (grade >= 75) { System.out.println("75-85"); } else { System.out.println("0-60"); } switch (c){ case'优': System.out.println("85-100"); } } } <file_sep>/java/src/generic/Compute.java package generic; import java.io.Serializable; /** * Created by Administrator on 2015/11/1. */ public class Compute<T extends Object & Serializable & Comparable, S> { public String add(T x, S y) { return String.valueOf(x) + String.valueOf(y); } public static void main(String[] args) { Compute<Double, Boolean> co = new Compute<Double, Boolean>(); // Compute <Integer>co= new Compute<>(); System.out.println(co.add(2.5, false)); } } <file_sep>/DB/exercise.sql # 1、查找部门30中员工的详细信息。 SELECT * FROM scott.emp WHERE DEPTNO = 30; # 2、找出从事clerk工作的员工的编号、姓名、部门号。 SELECT EMPNO, ENAME, DEPTNO FROM scott.emp WHERE JOB = 'clerk'; # 3、检索出奖金多于基本工资的员工信息。 SELECT * FROM scott.emp WHERE COMM > SAL; # 4、检索出奖金多于基本工资20%的员工信息。 SELECT * FROM scott.emp WHERE COMM > SAL * 0.3; # 5、希望看到10部门的经理或者20部门的职员(clerk)的信息。 SELECT * FROM scott.emp WHERE (EMPNO = 10 AND JOB = 'MANAGER') OR (EMPNO = 20 AND JOB = 'clerk'); # 6、找出10部门的经理、20部门的职员或者既不是经理也不是职员但是工资(基本工资 + 奖金)高于2000元的员工信息。 SELECT * FROM scott.emp WHERE (EMPNO = 10 AND JOB = 'MANAGER') OR (EMPNO = 20 AND JOB = 'CLERK') OR (JOB NOT IN ('CLERK', 'MANAGER') AND (SAL + ifnull(COMM, 0) > 2000)); # 7、找出获得奖金的员工的工作。 SELECT DISTINCT JOB FROM scott.emp WHERE COMM <> 0; # 8、找出奖金少于100或者没有获得奖金的员工的信息。 SELECT * FROM scott.emp WHERE COMM < 100 OR COMM IS NULL; # 9、查找员工雇佣日期中当月的最后一天雇佣的。 SELECT * FROM scott.emp WHERE HIREDATE = last_day(HIREDATE); # 10、检索出雇佣年限超过12年的员工信息。 # 11、找出姓名以A、B、S开始的员工信息。 # 12、找到名字长度为7个字符的员工信息。 # 13、名字中不包含R字符的员工信息。 # 14、找出员工名字的前3个字符。 # 15、将名字中A改为a。 # 16、将员工的雇佣日期拖后10年。 # 17、返回员工的详细信息并按姓名排序。 # 18、返回员工的信息并按员工的工作年限降序排列。 # 19、返回员工的信息并按工作降序工资升序排列。 # 20、返回员工的姓名、雇佣年份和月份并且按月份和雇佣日期排序。 # 21、计算员工的日薪(按30天)。 # 22、找出2月份雇佣的员工。 # 23、至今为止,员工被雇佣的天数。 # 24、找出姓名中包含A的员工信息。 # 25、计算出员工被雇佣了多少年、多少月、多少日。 # PART II # 1. 返回拥有员工的部门名、部门号。 SELECT DISTINCT d.DEPTNO, e.DEPTNO FROM scott.emp AS e, scott.dept AS d WHERE e.DEPTNO = d.DEPTNO; # 2. 工资水平多于smith的员工信息。 # 3. 返回员工和所属经理的姓名。 # 4. 返回雇员的雇佣日期早于其经理雇佣日期的员工及其经理姓名。 # 5. 返回员工姓名及其所在的部门名称。 # 6. 返回从事clerk工作的员工姓名和所在部门名称。 # 7. 返回部门号及其本部门的最低工资。 # 8. 返回销售部(sales)所有员工的姓名。 # 9. 返回工资水平多于平均工资的员工。 # 10. 返回与SCOTT从事相同工作的员工。 # 11. 返回与30部门员工工资水平相同的员工姓名与工资。 # 12. 返回工资高于30部门所有员工工资水平的员工信息。 # 13. 返回部门号、部门名、部门所在位置及其每个部门的员工总数。 # 14. 返回员工的姓名、所在部门名及其工资。 # 15. 返回雇员表中不再同一部门但是从事相同工作的员工信息。 # 16. 返回员工的详细信息。(包括部门名) # 17. 返回员工工作及其从事此工作的最低工资。 # 18. 返回不同部门经理的最低工资。<file_sep>/DB/sample.sql CREATE DATABASE IF NOT EXISTS scott; USE scott; /*Table structure for table dept */ DROP TABLE IF EXISTS dept; CREATE TABLE dept ( DEPTNO int(2) NOT NULL, DNAME varchar(14) DEFAULT NULL, LOC varchar(13) DEFAULT NULL, PRIMARY KEY (DEPTNO) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table dept */ insert into dept(DEPTNO,DNAME,LOC) values (10,'ACCOUNTING','NEW YORK'),(20,'RESEARCH','DALLAS'),(30,'SALES','CHICAGO'),(40,'OPERATIONS','BOSTON'); /*Table structure for table emp */ DROP TABLE IF EXISTS emp; CREATE TABLE emp ( EMPNO int(4) NOT NULL, ENAME varchar(10) DEFAULT NULL, JOB varchar(9) DEFAULT NULL, MGR int(4) DEFAULT NULL, HIREDATE date DEFAULT NULL, SAL double(7,2) DEFAULT NULL, COMM double(7,2) DEFAULT NULL, DEPTNO int(2) DEFAULT NULL, PRIMARY KEY (EMPNO), KEY FK_emp_deptno (DEPTNO), CONSTRAINT FK_emp_deptno FOREIGN KEY (DEPTNO) REFERENCES dept (DEPTNO) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table emp */ insert into emp(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7499,'ALLEN','SALESMAN',7698,'1981-02-20',1600.00,300.00,30),(7521,'WARD','SALESMAN',7698,'1981-02-22',1250.00,500.00,30),(7566,'JONES','MANAGER',7839,'1981-04-02',2975.00,NULL,20),(7654,'MARTIN','SALESMAN',7698,'1981-09-28',1250.00,1400.00,30),(7698,'BLAKE','MANAGER',7839,'1981-05-01',2850.00,NULL,30),(7782,'CLARK','MANAGER',7839,'1981-06-09',2450.00,NULL,10),(7788,'SCOTT','ANALYST',7566,'1987-07-13',3000.00,NULL,20),(7839,'KING','PRESIDENT',NULL,'1981-11-17',5000.00,NULL,10),(7844,'TURNER','SALESMAN',7698,'1981-09-08',1500.00,0.00,30),(7876,'ADAMS','CLERK',7788,'1987-07-13',1100.00,NULL,20),(7900,'JAMES','CLERK',7698,'1981-12-03',950.00,NULL,30),(7902,'FORD','ANALYST',7566,'1981-12-03',3000.00,NULL,20),(7934,'MILLER','CLERK',7782,'1982-01-23',1300.00,NULL,10); /*Table structure for table salgrade */ DROP TABLE IF EXISTS salgrade; CREATE TABLE salgrade ( GRADE int(11) DEFAULT NULL, LOSAL int(11) DEFAULT NULL, HISAL int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table salgrade */ insert into salgrade(GRADE,LOSAL,HISAL) values (1,700,1200),(2,1201,1400),(3,1401,2000),(4,2001,3000),(5,3001,9999); <file_sep>/java/src/abst/Rectangle.java package abst; /** * Created by Administrator on 2015/10/25. * 长方 */ public class Rectangle extends Shape { private int a; private int b; public Rectangle(int a, int b) { this.a = a; this.b = b; } @Override public double Area(){ return a * b; } @Override public double Periemter() { return (a+b)*2; } } <file_sep>/java/src/exercise/E13.java package exercise; /** * Created by dell on 2015/10/28. * 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? */ public class E13 { } <file_sep>/README.md # 16348104.github.com<file_sep>/java/src/Interface/Shape.java package Interface; /** * Created by Administrator on 2015/10/31. */ public interface Shape { } <file_sep>/DB/day3.sql CREATE DATABASE demo2; DROP DATABASE IF EXISTS demo2; DROP TABLE IF EXISTS demo2.TABLE_1; CREATE TABLE demo2.TABLE_1 ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) COMMENT '用户名', password VARCHAR(255) COMMENT '密码' COMMENT '管理员' ); DROP TABLE IF EXISTS demo2.TABLE_2; CREATE TABLE demo2.TABLE_2 ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, activity_name VARCHAR(255) COMMENT '活动名' COMMENT '活动表' ); DROP TABLE IF EXISTS demo2.enroll; CREATE TABLE demo2.enroll ( id INT(11), actvity_id VARCHAR(255) COMMENT '活动', CONSTRAINT fk_en_acid FOREIGN KEY (actvity_id) REFERENCES demo2.TABLE_2 (id), student_number INT(11) COMMENT '学号', student_name INT(255) COMMENT '学生名' COMMENT '注册活动' ); # ------------------- CREATE DATABASE demo3; DROP DATABASE IF EXISTS demo3; DROP TABLE IF EXISTS demo3.dept; CREATE TABLE demo3.dept ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) ); DROP TABLE IF EXISTS demo3.student; CREATE TABLE demo3.student ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), dept_id INT(11) UNSIGNED ); ALTER TABLE demo3.student ADD CONSTRAINT fk_stu_id FOREIGN KEY (dept_id) REFERENCES demo3.dept (id); INSERT INTO demo3.dept VALUES (NULL, 'EE'); INSERT INTO demo3.dept VALUES (NULL, 'CS'); INSERT INTO demo3.dept VALUES (NULL, 'SS'); SELECT * FROM demo3.dept; INSERT INTO demo3.student VALUES (NULL, 's001', 1); INSERT INTO demo3.student VALUES (NULL, 's002', 2); INSERT INTO demo3.student VALUES (NULL, 's003', NULL); INSERT INTO demo3.student VALUES (NULL, 's003', 0); SELECT * FROM demo3.student; ALTER TABLE demo3.dept MODIFY name TEXT; DESC demo3.dept; ALTER TABLE demo3.student CHANGE name Sname VARCHAR(255); DESC demo3.student; SELECT Sname name FROM demo3.student s , demo3.dept d WHERE demo3.dept.id=demo3.<file_sep>/java/src/DB/day1.sql CREATE DATABASE demo; CREATE TABLE demo.student ( id INT(11), name VARCHAR(20), age INT(3), sex CHAR(1) ); INSERT INTO demo.student VALUES (2015001, '张三', 18, '男'); INSERT INTO demo.student VALUES (2015002, '李四', 19, '女'); INSERT INTO demo.student VALUES (2015003, '王二', 20, '男'); UPDATE demo.student SET name = '李四', age = 20; DELETE FROM demo.student; SELECT * FROM demo.student; SELECT name, sex FROM demo.student; SELECT DISTINCT sex FROM demo.student; SELECT * FROM demo.student WHERE sex = '男' ; SELECT * FROM demo.student WHERE age BETWEEN 19 AND 20 ; SELECT * FROM demo.student WHERE name LIKE '%三%' ; SELECT * FROM demo.student ORDER BY sex,name DESC ; # asc = ascend # desc = descend # result set <file_sep>/java/src/oop/StaticTest.java package oop; /** * Created by xdx on 2015/11/5. */ public class StaticTest { private String name; private int age; public static void m1() { } public static void m2() { m1(); } public StaticTest(String name, int age) {//alt+insert this.name = name; this.age = age; } public static void main(String[] args) { } } <file_sep>/java/src/collection/VectorTest.java package collection; import java.util.Vector; /** * Created by xdx on 2015/11/6. */ public class VectorTest { public static void main(String[] args) { Vector<String> vector = new Vector<String>(); vector.add("a"); vector.add("s"); vector.add("d"); vector.add("f"); vector.add("dghghghghghghg"); System.out.println(vector.size()); System.out.println(vector.get(4)); vector.clear(); System.out.println(vector.size()); Vector<Integer> vector1 = new Vector<Integer>(); vector1.add(100); System.out.println(vector1.get(0)); } } <file_sep>/java/src/exception/IOExceptionTest.java package exception; import java.io.IOException; /** * Created by xdx on 2015/11/5. */ public class IOExceptionTest { public static void test() throws IOException { throw new IOException(); } public static void main(String[] args) { try { test(); } catch (IOException e) { e.printStackTrace(); } System.out.println("hello"); } } <file_sep>/java/src/oop/Human.java package oop; /** * Created by Administrator on 2015/10/24. */ public class Human { int age; char sex; String fuse; boolean marry; // void study() { // // } void sleep() { } public Human() { } public Human(int age, char sex, String fuse, boolean marry) { this.age = age; this.sex = sex; this.fuse = fuse; this.marry = marry; } void print() { System.out.println(age + " " + sex + " "); } } <file_sep>/java/src/string/TestString.java package string; import java.util.Scanner; /** * Created by Administrator on 2015/10/31. */ public class TestString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); // String str = "abc"; char[] c = str.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] >= 'a' && c[i] <= 'z') { c[i] -= 32; } } System.out.println(new String(c)); String[] strings = {"a", "bc", "def"}; for (int i = 0; i < strings.length; i++) { System.out.println(strings[i]); } for (String s : strings) { System.out.println(s); } // for (String string : strings) {// 迭代 循环 // System.out.println(string); // } } } <file_sep>/java/src/exercise/E6.java package exercise;//输入两个正整数m和n,求其最大公约数和最小公倍数。 import java.util.Scanner; public class E6 { public static void main(String[] args) { int n, m,r,m1,n1; Scanner scan=new Scanner(System.in); System.out.println("请输入整数(m>0): "); m1=scan.nextInt(); System.out.println("请输入整数(n>0): "); n1=scan.nextInt(); if(m1>n1) { m=m1; n=n1; } else { m=n1; n=m1; } do{ r=m%n; m=n; n=r; }while(r!=0); System.out.println(m1+"和"+n1+"的最大公约数= "+m+",最小公倍数="+m1*n1/m); } } <file_sep>/java/src/Interface/A.java package Interface; /** * Created by Administrator on 2015/10/31. */ public interface A { void a(); } <file_sep>/JAVAWEB/web/classic.jsp <%-- Created by IntelliJ IDEA. User: xdx Date: 2015/12/1 Time: 21:48 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page language="java" contentType="text/html;charset=UTF-8" %> <%! String getDate() { return new java.util.Date().toString(); } int count = 10; %> <html> <head> <title>一个典型的JSP</title> </head> <body> <%@include file="header.jsp" %> <div style="text-align: center;"> <table align="center"> <tr style="background: #777;"> <td> ---------------- </td> </tr> <% String color1 = "#99ccff"; String color2 = "#88cc33"; for (int i = 1; i <= count; i++) { String color; if (i % 2 == 0) { color = color1; } else { color = color2; } out.println("<tr style=\"background:" + color + ";\"><td>----------------</td></tr>"); } %> </table> <hr/> 当前时间是: <%--下面是是使用表达式的例子--%> <%=getDate()%> </div> </body> </html> <file_sep>/java/src/inherited/TeatHuman.java package inherited; /** * Created by dell on 2015/10/30. */ public class TeatHuman extends Human { public static void main(String[] args) { TeatHuman th=new TeatHuman(); th.marry = false; } } <file_sep>/java/src/io/FileT.java package io; import java.io.File; import java.util.Date; /** * Created by xdx on 2015/11/12. */ public class FileT { public static void main(String[] args) { File f = new File("java/src/io/rat"); if (f.isDirectory()) { String files[] = f.list(); for (String s : files) { System.out.println(s); } } else { System.out.println(f.exists()); System.out.println(f.isAbsolute()); System.out.println(f.isHidden()); System.out.println(f.getAbsoluteFile()); System.out.println(f.getAbsolutePath()); System.out.println(f.getName()); System.out.println(f.length()); System.out.println(new Date(f.lastModified())); } } } <file_sep>/java/src/io/IuputstreamTest.java package io; import exception.IOExceptionTest; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; /** * Created by Administrator on 2015/11/7. */ public class IuputstreamTest { public static void main(String[] args) { InputStream input = null; try { input = new FileInputStream("java/src/io/q"); int i; while ((i = input.read()) != -1) { System.out.print((char) i); } } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/java/src/io/RandomAccessFileTest.java package io; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; /** * Created by xdx on 2015/11/10. */ public class RandomAccessFileTest { public static void main(String[] args) { RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile("java/src/io/rat.txt", "rw"); for (int i = 0; i < 10; i++) { randomAccessFile.writeDouble(i); } randomAccessFile.seek(8); randomAccessFile.writeDouble(12.34); randomAccessFile = new RandomAccessFile("java/src/io/rat.txt", "r"); for (int i = 0; i <10; i++) { System.out.println("val: "+randomAccessFile.readDouble()); } } catch (java.io.IOException e) { e.printStackTrace(); } finally { if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException e) { e.printStackTrace(); } } } } }<file_sep>/java/src/exercise/E21.java package exercise; /** * Created by XDX on 2015/11/26. * 求1+2!+3!+…+20!的和 */ public class E21 { public static void main(String[] args) { long fun=0; int s = 1; for (int i = 1; i <= 20; i++) { s*=i; fun += s; } System.out.println(fun); } } <file_sep>/JavaScript/JS/1.js function test() { var x = prompt("请输入年-月-日:", "1990-01-01"); test(); arlt(x); }<file_sep>/CSS/1.css * { margin: 0; padding: 0; } body { font-size: 16px; font-family: Arial, Helvetica, sans-serif; color: #46626F; background-color: #f3f3f3; /*text-align:center;*/ /*margin:0px auto;*/ } form { border: 2px solid #AAAAAA; border-radius: 15px; padding: 3px 6px 3px 6px; margin: 5px; font: 14px Arial; } input { color: #00008B; background-color: #ADD8E6; border: 1px solid #00008B; border-radius: 5px; } select { width: 80px; color: #00008B; background-color: #ADD8E6; border: 1px solid #00008B; border-radius: 2px; } textarea { width: 200px; hegiht: 40px; color: #00008B; background-color: #ADD8E6; border: 1px solid #00008B; border-radius: 5px; } input.txt { border: 1px inset #00008B; background-color: #ADD8E6; } input.btn { color: #00008B; background-color: #ADD8E6; border: 1px outset #00008B; padding: 1px 2px 1px 2px; margin: 10px; } p { margin: 10px 5px; padding: 5px; } a { font-family: Arial; text-align: center; margin: 1px; } a:link, a:visited { color: #46626F; /*padding: 4px 10px 4px 10px;*/ /*background-color: #f2f8ff;*/ text-decoration: none; /*border-top: 1px solid #EEEEEE;*/ /*border-left: 1px solid #EEEEEE;*/ /*border-bottom: 1px solid #717171;*/ /*border-right: 1px solid #717171;*/ } a:hover { color: #ff5a5a; padding: 5px 8px 3px 12px; background-color: #fff9fc; border-top: 1px solid #717171; border-left: 1px solid #717171; border-bottom: 1px solid #EEEEEE; border-right: 1px solid #EEEEEE; } div#container { margin: 0px auto; /*line-height:150%;*/ } div#header, div#footer { padding: 0.5em; color: white; background-color: #99bbbb; clear: left; text-align: center } #content { /*width:100%;*/ /*text-align-all:center;*/ line-height: 150%; margin: auto; } h1.header { padding: 0; } <file_sep>/java/src/exercise/E19.java package exercise; /** * Created by dell on 2015/10/29. * 打印出如下图案(菱形) x xxx xxxxx xxxxxxx xxxxx xxx x 要求只使用以下三种语句 1. System.out.print(" ") 2. System.out.print("x"); 3. System.out.println("x") */ public class E19 { public static void main(String args[]) { for (int i = 1; i <= 4; i++) { for (int j = 1; j <=4 - i; j++) { System.out.print(" "); } for (int k = 1; k <= 2 * i - 1; k++) { System.out.print("x"); } System.out.println(); } for (int i = 3; i >= 1; i--) { for (int j = 1; j <= 4 - i; j++) { System.out.print(" "); } for (int k = 1; k <= 2 * i - 1; k++) { System.out.print("x"); } System.out.println(); } } } <file_sep>/java/src/io/ReaderT.java package io; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; /** * Created by Administrator on 2015/11/7. */ public class ReaderT { public static void main(String[] args) { Reader reader = null; try { reader = new FileReader("java/src/io/data"); int i = reader.read(); while (i != -1) { System.out.print((char) i); i = reader.read(); } } catch (IOException e) { e.printStackTrace(); } finally { if ( reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
454485b1383f01ee9abd8969cad717b2466cbfd4
[ "Java Server Pages", "Java", "Markdown", "SQL", "JavaScript", "CSS" ]
42
Java Server Pages
16348104/16348104.github.com
50fc38fb2c26595ee621ef5c8a350c23f65841d6
44a88c3e31f8dff6934fa3a7592d8ad2a182bbef
refs/heads/master
<file_sep>DOCKER_NAMESPACE = armbuild/ NAME = scw-distrib-voidlinux VERSION = latest VERSION_ALIASES = rpi2-20150713 rpi2 TITLE = Void Linux DESCRIPTION = Void Linux SOURCE_URL = https://github.com/scaleway/image-voidlinux SHELL = /bin/bash all: help ## ## Image tools (https://github.com/scaleway/image-tools) ## all: docker-rules.mk docker-rules.mk: wget -qO - http://j.mp/scw-builder | bash -include docker-rules.mk <file_sep>## -*- docker-image-name: "armbuild/scw-distrib-voidlinux:latest" -*- FROM armbuild/voidlinux:rpi2-20150713 MAINTAINER Scaleway <<EMAIL>> (@scaleway) # Environment ENV SCW_BASE_IMAGE armbuild/scw-voidlinux:latest
1f447d7808f01ab5625fd605d18ea5b4317dde93
[ "Makefile", "Dockerfile" ]
2
Makefile
QuentinPerez/image-voidlinux
d083dbbcadc9e933d5f0e4e0eb11c443df72b88e
dd6934ed9ddb415589a69ad5248f650d0186a8c2
refs/heads/master
<repo_name>ssl7/GoogleAuthP12_COM<file_sep>/GoogleAuth_P12/GoogleJsonWebToken.cs using System; using System.Text; using System.Collections.Specialized; using System.Web.Script.Serialization; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Net; using System.Runtime.InteropServices; namespace GoogleAuth_P12 { [Guid("87377FB4-E5D8-43CD-884B-947F612C84D0")] internal interface IGoogleJsonWebToken { [DispId(1)] // описываем методы которые можно будет вызывать из вне string GetAccessToken(string clientIdEMail, string keyFilePath, string scope, string proxyUrl = "", int proxyPort = 0, string proxyUser = "", string proxyPsw = ""); } [Guid("3289EB18-AF34-4A6B-A7DA-101B57782EAD"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IMyEvents { } [Guid("292758BB-DBC7-47EE-9B3B-4720EEBCC0F6"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(IMyEvents))] public class GoogleJsonWebToken : IGoogleJsonWebToken { public string GetAccessToken(string clientIdEMail, string keyFilePath, string scope, string proxyUrl = "", int proxyPort = 0, string proxyUser = "", string proxyPsw = "") { // certificate var certificate = new X509Certificate2(keyFilePath, "notasecret"); // header var header = new { typ = "JWT", alg = "RS256" }; // claimset var times = GetExpiryAndIssueDate(); var claimset = new { iss = clientIdEMail, scope = scope, aud = "https://accounts.google.com/o/oauth2/token", iat = times[0], exp = times[1], }; JavaScriptSerializer ser = new JavaScriptSerializer(); // encoded header var headerSerialized = ser.Serialize(header); var headerBytes = Encoding.UTF8.GetBytes(headerSerialized); var headerEncoded = Convert.ToBase64String(headerBytes); // encoded claimset var claimsetSerialized = ser.Serialize(claimset); var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized); var claimsetEncoded = Convert.ToBase64String(claimsetBytes); // input var input = headerEncoded + "." + claimsetEncoded; var inputBytes = Encoding.UTF8.GetBytes(input); // signiture var rsa = certificate.PrivateKey as RSACryptoServiceProvider; var cspParam = new CspParameters { KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName, KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2 }; var aescsp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false }; var signatureBytes = aescsp.SignData(inputBytes, "SHA256"); var signatureEncoded = Convert.ToBase64String(signatureBytes); // jwt var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded; var client = new WebClient(); client.Encoding = Encoding.UTF8; client.UseDefaultCredentials = true; client.Proxy = WebRequest.GetSystemWebProxy(); if (proxyUrl != "") { //"srv-tmg.volna.dmn" //3128 WebProxy proxy = new WebProxy(proxyUrl, proxyPort); if (proxyUser != "") { proxy.Credentials = new NetworkCredential(proxyUser, proxyPsw); } client.Proxy = proxy; } var uri = "https://accounts.google.com/o/oauth2/token"; var content = new NameValueCollection(); content["assertion"] = jwt; content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"; string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content)); //var result = ser.Deserialize<dynamic>(response); //return result; return response; } private static int[] GetExpiryAndIssueDate() { var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var issueTime = DateTime.UtcNow; var iat = (int)issueTime.Subtract(utc0).TotalSeconds; var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds; return new[] { iat, exp }; } } }
5930c9d74d2334d242c76f6ea8942c51f15d2cf5
[ "C#" ]
1
C#
ssl7/GoogleAuthP12_COM
2befc370673e752225b7f93504dadd73046f9350
0d17f47963c689ffc561a01dea7b39c6bb7f0890
refs/heads/master
<repo_name>nnlawrence/NoDB-11<file_sep>/server/controller.js let players = [ { id: 1, name: '<NAME>', position: 'Guard', image: 'https://www.stickpng.com/assets/images/5841b075a6515b1e0ad75a72.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUiS1vpy3nF7AoB8PUeslglYaEafl7RSig-wVlAJbajPiR2fGgEQ' }, { id: 2, name: '<NAME>', position: 'Guard', image: 'https://i-love-png.com/images/curry_png_355899.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRteYYlwwYlQhM_jUiXReGUOkOqpbDZFvP2-mT8HJ0BoUzEH-XxqQ' }, { id: 3, name: '<NAME>', position: 'Forward', image: 'https://i.dlpng.com/static/png/314717_preview.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSmP3SH8iSRpw5r49LWj86p321cueThhbMsGw8n5q2GEHka2obJ' }, { id: 4, name: '<NAME>', position: 'Guard', image: 'https://www.stickpng.com/assets/images/5845603892a07640e262dc40.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRtACyTukJfCUipJ_0eD00FcAR2XAgcskhyJoruLImxBVVkf7Tqxw' }, { id: 5, name: '<NAME>', position: 'Center', image: 'https://i.dlpng.com/static/png/4776493-shaquille-oneal-png-92-images-in-collection-page-1-shaquille-o-neal-png-384_384_preview.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQSFonAtA6iRkdrySvcDrU6lpyHfZOgMIJ8z-_eMQiIMT3TqPcqHQ' }, { id: 6, name: '<NAME>', position: 'Forward', image: 'https://i.dlpng.com/static/png/5237789-kawhi-leonard-png-95-images-in-collection-page-2-kawhi-leonard-png-3840_2560_preview.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS6ncofTT2B8EslvHsadSnPxLLRSmaMezwF5p5k04I_ioQ4ubJdhw' }, { id: 7, name: '<NAME>', position: 'Guard', image: 'https://www.stickpng.com/assets/thumbs/584564ed7c25fb418d2c2997.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQc1j95KI_z6JbF_U0KiMOd9yKgYYFWz0eZO6Aadzxe0BUPFsOo7A' }, { id: 8, name: '<NAME>', position: 'Center', image: 'https://img.pngio.com/collection-of-wilt-chamberlain-png-35-images-in-collection-wilt-chamberlain-png-384_384.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRHjmydEYqsRJ3Ga7hE9Ypt17onU-ZlaL3S4tEvJZ8eeK7KilCQ' }, { id: 9, name: '<NAME>', position: 'Guard', image: 'https://img.pngio.com/allen-iverson-png-95-images-in-collection-page-2-allen-iverson-png-384_384.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT3IfYX5gegbdaLY3lHr24H-x52w7eHmdjoa2wKALOVAMNLnM4cKA' }, { id: 10, name: '<NAME>', position: 'Center', image: 'https://i.dlpng.com/static/png/5038905-download-1495-tim-duncan-nba-png-full-size-png-image-pngkit-tim-duncan-png-399_590_preview.png' //'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTfzqA7im5PeEA_z4Azoe8TejgmzlFBwXXoqlrx_yHoJWJrEuBi' } ] let selectedPlayers = [] module.exports = { getPlayers: (req, res) => { res.status(200).send(players) }, createPlayer: (req, res)=>{ players.length? id = players[players.length - 1].id + 1 : id = 0 const newPlayer = { name: req.body.name, position: req.body.position, image: req.body.image, id } players.push(newPlayer) res.status(200).send(players) }, updatePlayer: (req, res) => { console.log('hit updated Player', req.body) const {id} = req.params const updatedPlayer = req.body let myPlayer = players.findIndex(player => { return player.id === +id }) players[myPlayer] = updatedPlayer console.log('hit send', players) res.status(200).send(players) }, deletePlayer: (req, res) => { console.log('player') const {id} = req.params players = players.filter((players)=> players.id !== +id) res.status(200).send(players) } }<file_sep>/server/index.js const express = require('express') const app = express() const ctrl = require('./controller') const cors = require('cors') app.use(express.json()) app.use(cors()) app.get('/api/players', ctrl.getPlayers) app.post('/api/players', ctrl.createPlayer) app.put('/api/players/:id', ctrl.updatePlayer) app.delete('/api/players/:id', ctrl.deletePlayer) const port = 8080 app.listen(8080, () => { console.log('server running') })<file_sep>/src/router.js import React from 'react' import {Switch, Route} from 'react-router-dom'; import Stats from './components/Stats' export default ( <Switch> <Route path='/stats' component={Stats} /> </Switch> )<file_sep>/src/App.js import React, { Component } from 'react'; import 'reset-css' import axios from 'axios' import './App.css' //components import Player from './components/Player' import PlayerSelected from './components/PlayerSelected' import {Link} from 'react-router-dom' // //stylesheets // const title = 'Open Gem' class App extends Component { constructor(props) { super(props); this.state = { players: [], name: '', position: '', selectedPlayer: [] } } componentDidMount(){ this.getPlayers() } getPlayers = () => { axios.get('api/players') .then((response) => { this.setState({ players: response.data }) }) .catch(err =>{ console.log(err) }) } handleImage = (val) => { this.setState({ playerImage: val }) } handleName = (val) => { this.setState({ playerName: val }) } handlePosition = (val) => { this.setState({ playerPosition: val }) } handleSelectPlayer = (player) => { this.setState({ selectedPlayer: [...this.state.selectedPlayer, player] }) } handleAddPlayer = () => { axios.post('/api/players', {name: this.state.playerName, position: this.state.playerPosition, image: this.state.playerImage}) .then(res => { this.setState({ players: res.data }) }) this.setState({playerName: ''}) this.setState({playerPosition: ''}) this.setState({playerImage: ''}) } handleDeletePlayer = (id) => { axios.delete(`/api/players/${id}`) .then(res => { this.setState({ players: res.data }) }) .catch(err =>{ console.log(err) }) } updatePlayer = async(data) => { await this.setState({ players: data },() => {console.log(this.state.players)}) } removeFromTeam = (index) => { let newTeam = this.state.selectedPlayer.filter((e, i) => { if(i !== index){ return true } }) this.setState({ selectedPlayer: newTeam }) } render() { console.log(this.state.selectedPlayer) const mappedPlayers = this.state.players.map((players, index) => { return <Player key={index} players={players} selectPlayer={this.handleSelectPlayer} deleteFunc={this.handleDeletePlayer}/> }) const mappedSelectedPlayer = this.state.selectedPlayer.map((selectedPlayer, index) => { return <PlayerSelected key={index} selectedPlayer={selectedPlayer}updatePlayer={this.updatePlayer} removePlayer = {this.removeFromTeam} selectPlayer={this.handleSelectPlayer} index={index}/> }) return ( <div className="App"> {/* <header className='top-header'> <div className="title">Open Gem <img src="https://png.pngtree.com/thumb_back/fh260/back_pic/03/59/19/2157a40289c9d05.jpg" alt='basketball' /></div> </header> */} <nav> <img id="nba" src="https://cdn.freebiesupply.com/images/large/2x/nba-logo-transparent.png" alt="nba" width={25} height={42} /> <div className="button-ol-container"> <ol className="button">Home</ol> <ol className="button">MyTeam</ol> <Link to='/stats'><ol className="button">Stats</ol></Link> <ol className="button">More</ol> </div> </nav> <div className="players-container-header"> </div> <div className="parent-div"> <div className="player-objects"> {mappedPlayers} </div> <div className="drafted-container"> <div className="add-a"> <input id="txtPos" placeholder="Name" onChange={(e)=>this.handleName (e.target.value)} value={this.state.playerName}></input> <input id="txtPos" placeholder="Position" onChange={(e)=>this.handlePosition (e.target.value)} value={this.state.playerPosition}></input> <input id="txtPos" placeholder="Image" onChange={(e)=>this.handleImage (e.target.value)} value={this.state.playerImage}></input> <button onClick={this.handleAddPlayer}>Add Player</button> </div> <header className="build">Team Builder</header> <div className='team'> {mappedSelectedPlayer} </div> </div> </div> {/* <div className="add-a"> <input id="txtPos" placeholder="Name" onChange={(e)=>this.handleName (e.target.value)} value={this.state.playerName}></input> <input id="txtPos" placeholder="Position" onChange={(e)=>this.handlePosition (e.target.value)} value={this.state.playerPosition}></input> <input id="txtPos" placeholder="Image" onChange={(e)=>this.handleImage (e.target.value)} value={this.state.playerImage}></input> <button onClick={this.handleAddPlayer}>Add Player</button> </div> */} </div> ); } } export default App; <file_sep>/src/components/Player.js import React from 'react' import axios from 'axios' // import './Player.css' // import PlayerSelected from './PlayerSelected'; class Player extends React.Component { constructor(){ super() this.state={ edit: false, editName: '', editPosition: '', editImage: '', } } handleToggle = () => { this.setState({ edit: !this.state.edit }) } handleInput=(val)=>{ this.setState({ editName: val }) } handleUpdatePlayer=(id)=>{ let updatedPlayer = { id, name: this.state.editName, position: this.props.selectedPlayer.position, image: this.props.selectedPlayer.image } axios.put(`/api/players/${id}`, updatedPlayer) .then(res =>{ this.props.updatePlayer(res.data) // this.props.selectPlayer(this.props.players) this.handleToggle() }) } render() { console.log(this.state.edit) const {id, name, position, image} = this.props.players const {deletePlayer} = this.props return ( <div className="player-container"> <div id="btnflx"><button onClick={() => this.props.selectPlayer(this.props.players)}>Draft</button> <button onClick={() => this.props.deleteFunc(id)}>Retire</button> <button onClick={this.handleToggle}>Edit</button> </div><div> <h3>{name}</h3> <p>{position}</p> </div> <img src={image} alt="get"></img> </div> ) } } // const Player = (props) => { // const {id, name, position, image} = props.players // const {deletePlayer} = props // return ( // <div className="player-container"> // <div id="btnflx"><button onClick={() => props.selectPlayer(props.players)}>Draft</button> // <button onClick={() => props.deleteFunc(id)}>Retire</button> // </div><div> // <h3>{name}</h3> // <p>{position}</p> // </div> // <img className="pic" src={image}></img> // </div> // ) // } //edit functionality for name input of players array // {this.state.edit ? ( // <button onClick={() => this.save()}>Save</button> // ) : ( // <button onClick={this.handleToggle}>Edit</button> // )} // </div> // {this.state.edit ? ( // <div> // <input /> // <p>{position}</p> // <img src={image} alt="get"></img> // </div> // ) : ( // <div> // <div> // <h3>{name}</h3> // <p>{position}</p> // </div> // <img src={image} alt="get"></img> // </div> // )} // </div> // ); // } // } //<NAME> https://pngimage.net/wp-content/uploads/2018/06/magic-johnson-png-5.png export default Player
248fe54f4f7177f8772dcb16fa6e23227336179c
[ "JavaScript" ]
5
JavaScript
nnlawrence/NoDB-11
243663fdea5da58b0e9ecd0969f562c16bd7de02
543a81b3ee1f371a209618a92892cbd9ef98ad28
refs/heads/master
<repo_name>harrytran998/Docker-Beginer<file_sep>/Dockerfile FROM busybox RUN echo "XXXX" CMD echo "WDA"
87f2116ca3d90689c1460e3df104217f322ce785
[ "Dockerfile" ]
1
Dockerfile
harrytran998/Docker-Beginer
4f235c8b83dad7011bd6443fd548c12706f3d99e
77e3e4f22322ad34cab48342a0693b5b167603ca
refs/heads/master
<file_sep># victorsonde.github.io Journal of Digital Adventures
4c52e93e29d66a9ca1783a5562787f9a37eccb9b
[ "Markdown" ]
1
Markdown
victorsonde/victorsonde.github.io
9661ef9430b2b97b959bbdd2b3c44927138e0435
e71505a6b5342ced9f97938387b8863e30f77e6c
refs/heads/main
<file_sep>package gestioncv.web; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.enterprise.context.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import gestioncv.model.Activity; import gestioncv.model.Nature; import gestioncv.model.Person; import gestioncv.services.IPersonDao; import lombok.Getter; @Named("cvView") @SessionScoped public class CvView implements Serializable { private static final long serialVersionUID = 1L; @Inject private IPersonDao personDao; /* Donn�es utilis�es dans les vues */ private @Getter Collection<Person> persons; private @Getter Person selectedPerson; private @Getter boolean showEditButtons; public Collection<Activity> getSelectedPersonEducations() { return filterActivitiesByNature(selectedPerson, Nature.EDUCATION); } public Collection<Activity> getSelectedPersonProfessionalExperiences() { return filterActivitiesByNature(selectedPerson, Nature.PROFESSIONAL_EXPERIENCE); } public Collection<Activity> getSelectedPersonProjects() { return filterActivitiesByNature(selectedPerson, Nature.PROJECT); } public Collection<Activity> getSelectedPersonOtherActivities() { return filterActivitiesByNature(selectedPerson, Nature.OTHER); } private Collection<Activity> filterActivitiesByNature(Person person, Nature nature) { if (person != null) { return person.getCv().stream() .filter(activity -> nature.equals(activity.getNature())) .collect(Collectors.toList()); } return new ArrayList<Activity>(); } @PostConstruct public void init() { this.persons = personDao.findAll(); } /** * Contrôleur responsable de gérer les accès à la page d'affichage des détails * d'un CV. * * @param id * @return */ public String show(int id) { updateSelectedPerson(personDao.find(id)); return "cv-detail?faces-redirect=true"; } public String showEditPage() { return "person-form"; } public String savePerson(Person person) { if (person.getId() != 0) { updateSelectedPerson(personDao.update(person)); } else { updateSelectedPerson(personDao.add(person)); } // TODO: faire en sorte que la mise-�-jour soit visible au sein de la collection return "cv-detail"; } /** * La modification de selectedPerson doit être effectuée uniquement à l'aide de * cette méthode afin de pouvoir appliquer des effets secondaires comme, par * exemple, dicter l'affichage des boutons de modifications de CVs. * * @param newSelectedPerson */ private void updateSelectedPerson(Person newSelectedPerson) { selectedPerson = newSelectedPerson; FacesContext context = FacesContext.getCurrentInstance(); ExternalContext externalContext = context.getExternalContext(); Person loggedInUser = (Person) externalContext.getSessionMap().get("user"); // Effets secondaires de la mise à jour de selectedPerson if (selectedPerson != null && loggedInUser != null && selectedPerson.getId() == loggedInUser.getId()) { showEditButtons = true; } else { showEditButtons = false; } } }<file_sep>DROP TABLE IF EXISTS `Activity`, `Person`; <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>AA_Gestion_de_CV</groupId> <artifactId>AA_Gestion_de_CV</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <release>14</release> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> </configuration> </plugin> <!-- Pour que Maven traite les tests Junit 5 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <!-- JUnit 5 requires Surefire version 2.22.0 or higher --> <version>2.22.2</version> </plugin> </plugins> </build> <dependencies> <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter --> <!-- Provides everything you need to write JUnit 5 Jupiter tests. --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.7.0-M1</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.junit.platform/junit-platform-runner --> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-runner</artifactId> <version>1.7.0</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>3.6.28</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mockito/mockito-junit-jupiter --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>3.6.28</version> <scope>test</scope> </dependency> <!-- Pour utiliser Lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency> <!-- Fin utilisation de Lombok --> <!-- Pour utiliser HyperSQL --> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.4.1</version> <scope>test</scope> </dependency> <!-- Fin utilisation HyperSQL --> <!-- Pour utiliser MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <!-- Fin utilisation MySQL --> <!-- Pour utiliser Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.25.Final</version> </dependency> <!-- nécessaire pour Hibernate --> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.4.0-b180830.0438</version> </dependency> <!-- Apache commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.11</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.myfaces.core/myfaces-impl --> <dependency> <groupId>org.apache.myfaces.core</groupId> <artifactId>myfaces-impl</artifactId> <version>2.3.6</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.myfaces.core</groupId> <artifactId>myfaces-api</artifactId> <version>2.3.6</version> <scope>provided</scope> </dependency> <!-- UI --> <dependency> <groupId>org.primefaces</groupId> <artifactId>primefaces</artifactId> <version>8.0</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>font-awesome</artifactId> <version>5.15.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.4.25.Final</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.19</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.xbean/xbean-asm7-shaded --> <!-- MAJ d'un composant de TomEE pour le support de java 14 --> <dependency> <groupId>org.apache.xbean</groupId> <artifactId>xbean-asm7-shaded</artifactId> <version>4.16</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.tomee/openejb-junit --> <dependency> <groupId>org.apache.tomee</groupId> <artifactId>openejb-junit</artifactId> <version>8.0.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.tomee/tomee-myfaces --> <dependency> <groupId>org.apache.tomee</groupId> <artifactId>tomee-myfaces</artifactId> <version>8.0.3</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-impl</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-spec</artifactId> <version>1.2.5</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-validator/commons-validator --> <dependency> <groupId>commons-validator</groupId> <artifactId>commons-validator</artifactId> <version>1.6</version> </dependency> </dependencies> </project><file_sep>package gestioncv.services; import java.util.Collection; public interface IDao<T> { T find(Class<T> clazz, Object id); Collection<T> findAll(Class<T> clazz); /** * Ajoute l'entité passée en paramètre en base de données. * * @param entity * @return */ T add(T entity); T update(T entity); void remove(Class<T> clazz, Object pk); } <file_sep>package gestioncv.servicesTests; import static org.junit.Assert.assertEquals; import org.apache.commons.lang3.NotImplementedException; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThrows; import java.util.Collection; import java.util.Collections; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doNothing; import gestioncv.model.Person; import gestioncv.services.IPersonDao; import gestioncv.services.impl.Dao; import gestioncv.services.impl.PersonDao; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) public class PersonDaoTest{ @InjectMocks @Spy PersonDao personDao; @Test public void testFindAllSuccess() { Collection<Person> persons = Collections.singletonList(Person.builder().id(10).build()); doReturn(persons).when(personDao).findAll(Person.class); personDao.findAll(); verify(personDao).findAll(Person.class); } @Test public void testFind() { int id = 10 ; Person person = Person.builder().id(id).build(); doReturn(person).when(personDao).find(id); Person foundedPerson = personDao.find(id); verify(personDao).find(id); assertEquals(id, foundedPerson.getId()); } @Test public void testRemove() { int id = 10 ; doNothing().when(personDao).remove(Person.class,id); personDao.remove(id); verify(personDao).remove(Person.class,id); } @Test public void testFindPersonsByActivityTitle() { String title = "activity title"; assertThrows(NotImplementedException.class, () -> personDao.findPersonsByActivityTitle(title)); } }<file_sep>package gestioncv.model; import java.io.Serializable; import java.time.LocalDate; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.validation.constraints.Email; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @Entity @Builder @AllArgsConstructor public class Person implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Size(min = 2, max = 255, message = "le nom doit contenir entre 2 et 255 caractères") @NotNull(message = "le nom est requis") @Column(nullable = false, length = 255) private String lastName; @Size(min = 2, max = 255, message = "le prénom doit contenir entre 2 et 255 caractères") @NotNull(message = "le prénom est requis") @Column(nullable = false, length = 255) private String firstName; @Max(value = 255, message = "le site web ne doit pas contenir plus de 255 caractères") @Column(length = 255) // TODO: valider le site web private String website; @NotNull(message = "l'email est requis") @Email(message = "merci de saisir un email valide") @Column(nullable = false, length = 255, unique = true) private String email; @NotNull(message = "la date de naissance est requise") @Column(nullable = false) private LocalDate dateOfBirth; // TODO: valider le mot de passe lorsque le hachage aura été défini @Column(nullable = false, length = 102) private String password; @OneToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE }, fetch = FetchType.LAZY, mappedBy = "owner") private Collection<Activity> cv; } <file_sep>package gestioncv.services.impl; import java.util.Collection; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import gestioncv.services.IDao; public abstract class Dao<T> implements IDao<T> { @PersistenceContext(unitName = "myData") protected EntityManager em; @Override public T find(Class<T> clazz, Object id) { return em.find(clazz, id); } @Override public Collection<T> findAll(Class<T> clazz) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<T> cq = builder.createQuery(clazz); Root<T> root = cq.from(clazz); cq.select(root); return em.createQuery(cq).getResultList(); } @Override public T add(T entity) { em.persist(entity); return entity; } @Override public T update(T entity) { return em.merge(entity); } @Override public void remove(Class<T> clazz, Object pk) { T entity = em.find(clazz, pk); if (entity != null) { em.remove(entity); } } } <file_sep>import javax.ejb.embeddable.EJBContainer; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; /* * Cette classe regroupe les outils nécessaires afin de faciliter * l'écriture des tests unitaires sur les instances CDI et EJB. */ public class BaseJunit5 { /* * Le nom de votre application (en clair le nom de votre projet) */ public final String BASE = "java:global/gestion-de-cv"; /* * Le conteneur qui va regrouper à la fois les instances CDI et les EJB. */ public static EJBContainer container; /* * Création du conteneur avant les tests. */ @BeforeAll static public void beforeAll() throws Exception { if (container == null) { System.out.println("\nSTARTING CONTAINER\n"); container = EJBContainer.createEJBContainer(); // prevoir la fermeture Thread t = new Thread(BaseJunit5::afterAll); Runtime.getRuntime().addShutdownHook(t); } } static public void afterAll() { System.out.println("\nSTOPPING CONTAINER\n"); container.close(); container = null; } /* * Injecter dans le conteneur l'instance du test afin de réaliser les * initialisations et les injections nécessaires. */ @BeforeEach public void before() throws Exception { container.getContext().bind("inject", this); } /* * Utiliser l'API JNDI (Java Naming and Directory Interface) pour trouver une * instance à partir de son nom. */ public <T> T lookup(String name, Class<T> theClass) { try { Object o = container.getContext().lookup(name); return theClass.cast(o); } catch (Exception e) { throw new RuntimeException(e); } } }<file_sep>/* Icarus Theme */ /* pt-sans-regular */ @font-face { font-family: 'PT_Sans'; font-weight: normal; src: url("\#{resource['primefaces-icarus:fonts/pt_sans-web-regular.eot']}"); /* IE9 Compat Modes */ src: url("\#{resource['primefaces-icarus:fonts/pt_sans-web-regular.eot']}#iefix") format('embedded-opentype'), /* IE6-IE8 */ url("\#{resource['primefaces-icarus:fonts/pt_sans-web-regular.woff2']}") format('woff2'), /* Super Modern Browsers */ url("\#{resource['primefaces-icarus:fonts/pt_sans-web-regular.woff']}") format('woff'), /* Modern Browsers */ url("\#{resource['primefaces-icarus:fonts/pt_sans-web-regular.ttf']}") format('truetype'), /* Safari, Android, iOS */ url("\#{resource['primefaces-icarus:fonts/pt_sans-web-regular.svg']}#PT_Sans") format('svg'); /* Legacy iOS */ } /* pt-sans-700 */ @font-face { font-family: 'PT_Sans'; font-weight: bold; src: url("\#{resource['primefaces-icarus:fonts/pt_sans-web-bold.eot']}"); /* IE9 Compat Modes */ src: url("\#{resource['primefaces-icarus:fonts/pt_sans-web-bold.eot']}#iefix") format('embedded-opentype'), /* IE6-IE8 */ url("\#{resource['primefaces-icarus:fonts/pt_sans-web-bold.woff2']}") format('woff2'), /* Super Modern Browsers */ url("\#{resource['primefaces-icarus:fonts/pt_sans-web-bold.woff']}") format('woff'), /* Modern Browsers */ url("\#{resource['primefaces-icarus:fonts/pt_sans-web-bold.ttf']}") format('truetype'), /* Safari, Android, iOS */ url("\#{resource['primefaces-icarus:fonts/pt_sans-web-bold.svg']}#PT_Sans") format('svg'); /* Legacy iOS */ } @import "../_variables"; @import "../_icons"; /* Component containers ----------------------------------*/ .ui-widget { font-family: 'PT_Sans', sans-serif; font-size: 14px; } .ui-widget-content { border: 1px solid $grey; background: #fff; color: $blackLight; } .ui-widget-content a { color: $blackLight; } .ui-widget-header { border: 1px solid $blackLight; background: $blackLight; color: #fff; font-weight: bold; } .ui-widget-header a { color: #fff; } /* Interaction states ----------------------------------*/ .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid $grey; background: #fff; color: $blackLight; } .ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: $blackLight; text-decoration: none; } .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover { border: 1px solid $greyDark; background-color: $grey; color: #fff; } .ui-state-hover a, .ui-state-hover a:hover { color: #fff; text-decoration: none; } .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid $regularColor; color: $blackLight; -moz-box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12); -webkit-box-shadow:0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12); box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12); outline: 0 none; } .ui-state-focus a, .ui-state-focus a:hover { color: $blackLight; text-decoration: none; } .ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid $regularColor; background: $regularColor; color: #fff; } .ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #fff; text-decoration: none; } .ui-widget:active { outline: none; } /* Interaction Cues ----------------------------------*/ .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { background: $regularColor; border-color: $darkColor; color: #fff; } .ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-widget-header .ui-state-highlight a { color: #fff; } .ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid $error; } .ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter: Alpha(Opacity=35); background-image: none; } /* Misc visuals ----------------------------------*/ /* Corner radius */ .ui-corner-tl { -moz-border-radius-topleft: 3px; -webkit-border-top-left-radius: 3px; border-top-left-radius: 3px; } .ui-corner-tr { -moz-border-radius-topright: 3px; -webkit-border-top-right-radius: 3px; border-top-right-radius: 3px; } .ui-corner-bl { -moz-border-radius-bottomleft: 3px; -webkit-border-bottom-left-radius: 3px; border-bottom-left-radius: 3px; } .ui-corner-br { -moz-border-radius-bottomright: 3px; -webkit-border-bottom-right-radius: 3px; border-bottom-right-radius: 3px; } .ui-corner-top { -moz-border-radius-topleft: 3px; -webkit-border-top-left-radius: 3px; border-top-left-radius: 3px; -moz-border-radius-topright: 3px; -webkit-border-top-right-radius: 3px; border-top-right-radius: 3px; } .ui-corner-bottom { -moz-border-radius-bottomleft: 3px; -webkit-border-bottom-left-radius: 3px; border-bottom-left-radius: 3px; -moz-border-radius-bottomright: 3px; -webkit-border-bottom-right-radius: 3px; border-bottom-right-radius: 3px; } .ui-corner-right { -moz-border-radius-topright: 3px; -webkit-border-top-right-radius: 3px; border-top-right-radius: 3px; -moz-border-radius-bottomright: 3px; -webkit-border-bottom-right-radius: 3px; border-bottom-right-radius: 3px; } .ui-corner-left { -moz-border-radius-topleft: 3px; -webkit-border-top-left-radius: 3px; border-top-left-radius: 3px; -moz-border-radius-bottomleft: 3px; -webkit-border-bottom-left-radius: 3px; border-bottom-left-radius: 3px; } .ui-corner-all { -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; } /* Overlays */ .ui-widget-overlay { background-color: #666666; opacity: .50; filter: Alpha(Opacity=50); } .ui-widget-shadow { margin: -5px 0 0 -5px; padding: 5px; background-color: #000000; opacity: .20; filter: Alpha(Opacity=20); -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; } /* ThemeRoller Icons */ .ui-icon { width: 16px; height: 16px; } /* ====== Forms ====== */ /* Inputs */ .ui-inputfield, .ui-widget-content .ui-inputfield, .ui-widget-header .ui-inputfield { -webkit-transition: .2s; -moz-transition: .2s; -o-transition: .2s; transition: .2s; background: #fff; color: $blackLight; &.ui-state-focus { -moz-box-shadow: 0px 0px 5px $regularColor; -webkit-box-shadow: 0px 0px 5px $regularColor; box-shadow: 0px 0px 5px $regularColor; } &.ui-state-hover { color: $blackLight; } } body { .ui-inputgroup { height: 100%; .ui-inputgroup-addon, .ui-inputgroup-addon-checkbox { padding: $inputPadding; border-color: $inputGroupBorderColor; background-color: $inputGroupBgColor; color: $inputGroupTextColor; min-width: $inputGroupAddonMinWidth; &:first-child { @include border-radius-left($borderRadius); } &:last-child { @include border-radius-right($borderRadius); } } .ui-button-text-only { margin: 0; } .ui-inputgroup-addon-checkbox { padding: 0; position: relative; .ui-chkbox { vertical-align: baseline; position: absolute; top: 50%; left: 50%; margin-top: -1 * $checkboxHeight / 2; margin-left: -1 * $checkboxWidth / 2; } } } } @media (max-width : 768px) { .ui-inputfield.ui-inputtextarea{ -webkit-transition: none; -moz-transition: none; -o-transition: none; transition: none; } } /* Button */ .ui-button { -webkit-transition: background-color .2s; -moz-transition: background-color .2s; -o-transition: background-color .2s; transition: background-color .2s; &.ui-state-default { background: $regularColor; border: none; border-bottom: 5px solid $darkColor; &.ui-widget { color: #fff; } } &.ui-state-hover { background: $lightColor; border-bottom: 5px solid $regularColor; } &.ui-state-active { background: $darkColor; border-bottom: 5px solid $darkColor; } &.ui-button-text-icon-left { .ui-button-text { color: #fff; padding-top: 5px; padding-bottom: 4px; } .ui-button-icon-left { &.ui-icon-check { color: #fff; &.ui-icon-check { @include icon-override("\f00c"); } } } } &.ui-button-text-icon-right { .ui-button-icon-right { color: #fff; } .ui-button-text { color: #fff; } } &.ui-button-icon-only { .ui-button-icon-left { color: #fff; .ui-button-text { color: #fff; padding-top: 10px; padding-bottom: 10px; } } } &.ui-widget { &.ui-button-text-only { .ui-button-text { color: #fff; } } } } /* SelectButton */ .ui-selectonebutton, .ui-selectmanybutton { &.ui-buttonset { .ui-button { border-bottom: 0 none; border-right: 1px solid $greyDark; &:last-child { border-right: 1px solid transparent; } &.ui-state-default { background: $grey; } &.ui-state-hover { background: $greyDark; } &.ui-state-active { background: $regularColor; border-right: 1px solid $darkColor; } } } } .ui-fluid { .ui-selectonebutton, .ui-selectmanybutton { &.ui-buttonset.ui-buttonset-3 { .ui-button { width: 33.33%; } } &.ui-buttonset.ui-buttonset-6 { .ui-button { width: 16.66%; } } } } @media (max-width : 640px) { .ui-fluid { .ui-selectonebutton, .ui-selectmanybutton { border: 1px solid $greyDark; &.ui-buttonset { .ui-button { border-bottom: 1px solid $greyDark; border-right: 0 none; border-radius: 3px; &:last-child { border-bottom: 1px solid transparent; } &.ui-state-default { background: $grey; } &.ui-state-hover { background: $greyDark; } &.ui-state-active { background: $regularColor; border-right: 0 none; border-bottom: 1px solid $darkColor; } } &.ui-buttonset-6, &.ui-buttonset-3 { .ui-button { width: 100%; } } } } } } .ui-selectbooleanbutton { &.ui-button { border-bottom: 0 none; &.ui-state-default { background: $grey; } &.ui-state-hover { background: $greyDark; } &.ui-state-active { background: $regularColor; } } } /* Colored Buttons */ /*Green Button*/ .ui-button { &.green-button { background-color: $greenButton; border-color: $greenButtonBorder; &.ui-state-hover { background-color: $greenButtonHover; } &.ui-state-active { background-color: $greenButtonActive; } } } /*Red Button*/ .ui-button { &.red-button { background-color: $redButton; border-color: $redButtonBorder; &.ui-state-hover { background-color: $redButtonHover; } &.ui-state-active { background-color: $redButtonActive; } } } /*Blue Button */ .ui-button { &.blue-button { background-color: $blue; border-color: $blueDark; &.ui-state-hover { background-color: $blueLight; } &.ui-state-active { background-color: $blueDark; } } } /*Aqua Button*/ .ui-button { &.aqua-button { background-color: $aquaButton; border-color: $aquaButtonBorder; &.ui-state-hover { background-color: $aquaButtonHover; } &.ui-state-active { background-color: $aquaButtonActive; } } } /*Navy Button*/ .ui-button { &.navy-button { background-color: $navyButton; border-color: $navyButtonBorder; &.ui-state-hover { background-color: $navyButtonHover; } &.ui-state-active { background-color: $navyButtonActive; } } } /*Black Button*/ .ui-button { &.black-button { background-color: $blackButton; border-color: $blackButtonBorder; &.ui-state-hover { background-color: $blackButtonHover; } &.ui-state-active { background-color: $blackButtonActive; } } } /*Grey Button*/ .ui-button { &.gray-button { background-color: $greyButton; border-color: $greyButtonBorder; &.ui-button { span.ui-button-text { color: $greyButtonText; } } &.ui-state-hover { background-color: $greyButtonHover; } &.ui-state-active { background-color: $greyButtonActive; } } } /* Password */ .ui-password-panel { background: $lightColor; border-color: $regularColor; color: $blackLight; } /* Checkbox */ .ui-chkbox { .ui-chkbox-icon { font-size: 12px; margin-left: 1px; @include icon-override("\f00c"); visibility: hidden; } .ui-chkbox-box { cursor: pointer; .ui-icon-closethick { @include icon-override("\f00d"); margin-left: 2px; } &.ui-state-hover { background-color: $bg-greyLight; } &.ui-state-active { background-color: $regularColor; .ui-chkbox-icon { @include icon-override("\f00c"); color: #fff; visibility: visible; } .ui-icon-closethick { @include icon-override("\f00d"); } } &.ui-state-focus { background-color: $lightColor; .ui-icon-check { @include icon-override("\f00c"); color: #fff; visibility: visible; } .ui-icon-closethick { @include icon-override("\f00d"); } } &[data-iconstates] { overflow: hidden; } } } .ui-chips { .ui-chips-container { width: 155px; padding: 0px; } } .ui-fluid { .ui-chips, .ui-chips-container { width: 100%; } } /* ManyCheckbox */ .ui-selectmanycheckbox, .ui-selectoneradio { .ui-grid-row { > div { padding: 4px; } } } /* RadioButtons */ .ui-radiobutton { .ui-radiobutton-icon { @include icon-override(" "); margin-left: 4px; font-size: 10px; margin-top: 2.45px; } .ui-radiobutton-box { cursor: pointer; &.ui-state-hover { background-color: $bg-greyLight; } &.ui-state-active,&.ui-state-focus { background-color: $regularColor; .ui-icon-bullet { @include icon-override("\f111"); color: #fff; font-size: 10px; } } } } /* Dropdown */ .ui-selectonemenu { .ui-selectonemenu-trigger { &.ui-state-default { background: $grey; color: #fff; border-bottom: 5px solid $greyDark; box-sizing: border-box; width: 32px; padding: 0 6px; .ui-icon { @include icon-override("\f107"); font-size: 16px; color: #fff; padding-left: 2px; text-align: center; } } &.ui-state-hover { background: $greyDark; } &.ui-corner-right { @include border-radius-right(0); } } input.ui-selectonemenu-label { padding: 6.5px 4px; } } .ui-selectonemenu-panel { .ui-selectonemenu-items-wrapper { .ui-selectonemenu-items { padding: 0; .ui-selectonemenu-item { border-left: 5px solid transparent; padding: 8px 8px; border-radius: 0; margin: 0; &.ui-state-highlight { background: $regularColor; border-color: $darkColor; color: #fff; } &.ui-state-hover { background: $grey; border-color: $greyDark; color: #fff; } } .ui-selectonemenu-item-group { padding: 5px 0 0 12px; font-size: 16px; background: $greyDark; color: white; border-radius: 0; } } } } .ui-selectmanymenu, .ui-selectonelistbox { .ui-selectlistbox-filter-container { margin: .2em; .ui-selectlistbox-filter { width: 100%; box-sizing: border-box; } } &.ui-inputfield { padding: 0; .ui-selectlistbox-list { .ui-selectlistbox-item { margin: 0; padding: 5px; border-left: 5px solid transparent; border-radius: 0; &.ui-state-hover { border-left: 5px solid $greyDark; } &.ui-state-highlight { border-left: 5px solid $darkColor; .ui-chkbox { .ui-chkbox-box { border-color: $lightColor; } } } .ui-chkbox { vertical-align: middle; margin-right: 5px; } } } } } /* MultiSelectListBox */ .ui-multiselectlistbox { .ui-multiselectlistbox-list { .ui-multiselectlistbox-item { border-left: 5px solid transparent; margin: 0; padding: 5px; &.ui-state-highlight { border-color: $darkColor; background: $regularColor; color: #fff; } &.ui-state-hover { border-color: $greyDark; background: $grey; color: #fff; } } } } /* AutoComplete */ .ui-autocomplete { .ui-autocomplete-dropdown { &.ui-button { background-color: $grey; border-color: $greyDark; right: -4px; .ui-icon-triangle-1-s { @include icon-override("\f107"); font-size: 16px; color: #fff; } &.ui-state-hover { background: $greyDark; } } } } .ui-autocomplete-panel { .ui-autocomplete-items { &.ui-autocomplete-list { padding: 0; line-height: 1.5; } .ui-autocomplete-item { border-left: 5px solid #ffffff; @include border-radius(0px); &.ui-state-highlight { background: $regularColor; border-color: $darkColor; } &:first-child { margin-top: 0; } &:last-child { margin-bottom: 0; } } } } /* SelectCheckBoxMenu */ .ui-selectcheckboxmenu { .ui-selectcheckboxmenu-trigger { box-sizing: border-box; &.ui-state-default { width: 32px; background-color: $grey; border-bottom: 5px solid $greyDark; } &.ui-state-hover { background-color: $greyDark; } span { &.ui-icon { @include icon-override("\f107"); font-size: 16px; color: #fff; padding: 0 0 2px 8px; } } &.ui-corner-right { @include border-radius-right(0); } } label.ui-selectcheckboxmenu-label { padding: 4px 36px 4px 5px; background-color: #fff; color: $blackLight; } &.ui-selectcheckboxmenu-multiple { padding-top: 1px; padding-bottom: 1px; .ui-selectcheckboxmenu-multiple-container { &.ui-inputfield { border: 0 none; padding-right: 32px; } .ui-selectcheckboxmenu-token { margin: 1px 2px; } } .ui-selectcheckboxmenu-trigger { .ui-icon { top: auto; margin-top: 3px; } } } } .ui-selectcheckboxmenu-panel { .ui-selectcheckboxmenu-header { .ui-chkbox { margin-top: 2px; .ui-chkbox-icon { margin-top: 2px; } } .ui-selectcheckboxmenu-filter-container { .ui-icon { color: $blackLight; } } .ui-selectcheckboxmenu-close { text-align: center; font-size: 16px; margin-top: 2px; } } } /* Input Switch */ .ui-inputswitch { .ui-inputswitch-off { background-color: $grey; span { color: #fff; padding: 0; } } .ui-inputswitch-on { &.ui-state-active { background-color: $regularColor; } span { color: #fff; } } } //toggleSwitch body { .ui-toggleswitch { height: 26px; width: 3.5em; .ui-toggleswitch-slider { @include transition(background-color .3s); background-color: #a8acb1; color: #ffffff; border: 1px solid $greyBorder; @include border-radius(3px); overflow: hidden; &:before { background-color: #ffffff; border: 1px solid transparent; @include transition(.3s); @include border-radius(0); width: calc(3em / 2); height: 22px; left: auto; bottom: auto; } } &.ui-toggleswitch-checked { .ui-toggleswitch-slider { border: 1px solid $regularColor; background: $regularColor; color: #fff; &:before { @include translateX(calc(2em - 4px)); @include translateXForIE(2em, -4px); } } } &.ui-toggleswitch-focus { .ui-toggleswitch-slider { &:before { border: 1px solid $regularColor; color: $blackLight; -moz-box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12); -webkit-box-shadow:0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12); box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12); outline: 0 none; } } } } } /* Spinner */ .ui-spinner { .ui-spinner-button { width: 22px; &.ui-spinner-up { background-color: $grey; border: 3px solid $grey; cursor: pointer; box-sizing: border-box; .ui-button-text { .ui-icon { left: 0; top: 4px; @include icon-override("\f106"); font-size: 15px; color: #fff; } } &.ui-state-hover { background-color: $greyDark; border-color: $greyDark; } &.ui-state-active { background-color: $greyDark; border-color: $greyDark; } } &.ui-spinner-down { background-color: $grey; border: 3px solid $grey; cursor: pointer; box-sizing: border-box; .ui-button-text { .ui-icon { left: 0; @include icon-override("\f107"); font-size: 15px; color: #fff; } } &.ui-state-hover { background-color: $greyDark; border-color: $greyDark; } &.ui-state-active { background-color: $greyDark; border-color: $greyDark; } } } .ui-spinner-input { &.ui-inputfield { &.ui-state-default { font-family: 'PT_Sans', sans-serif; font-size: 14px; padding-right: 28px; } } } } /* Slider */ .ui-slider { background-color: $grey; .ui-slider-handle { border-radius: 100%; } } /* SelectOneListBox */ .ui-selectonelistbox { &.ui-inputfield { padding: 0; .ui-selectlistbox-listcontainer { .ui-selectlistbox-list { .ui-selectlistbox-item { margin: 0; padding: 5px; border-left: 5px solid transparent; border-radius: 0; &.ui-state-hover { border-left: 5px solid $greyDark; } &.ui-state-highlight { border-left: 5px solid $darkColor; } } } } } } /* SplitButton */ .ui-splitbutton { .ui-icon-disk { @include icon-override("\f0c7"); } .ui-splitbutton-menubutton { height: 100%; box-sizing: border-box; .ui-icon { @include icon-override("\f107"); font-size: 16px; color: #fff; padding: 0 0 2px 0; } } } /* Calendar */ .ui-datepicker { &.ui-widget-content { padding: 0; td { .ui-state-default { border: none; &.ui-state-hover { background: $greyLight; } &.ui-state-active { background: $regularColor; color: #fff; } } } .ui-datepicker-header { .ui-datepicker-prev { cursor: pointer; span { @include icon-override("\f060"); font-size: 15px; color: #fff; overflow: hidden; width: 13px; padding-left: 1px; } } .ui-datepicker-next { cursor: pointer; span { @include icon-override("\f061"); font-size: 15px; color: #fff; overflow: hidden; width: 13px; padding-left: 2px; } } } .ui-datepicker-calendar { td { &.ui-datepicker-today { a { background: $greyLight; color: $blackLight; } } a { font-size: 16px; text-align: center; } } } } } .ui-calendar { &.ui-trigger-calendar { .ui-datepicker-trigger { box-sizing: border-box; vertical-align: top; border-bottom-width: 2px; @include border-radius-left(0); .ui-icon-calendar { @include icon-override("\f073"); font-size: 12px; color: #fff; padding-top: 2px; } } } .ui-inputfield { &.ui-corner-all { @include border-radius-right(0); } } } .ui-fluid { .ui-calendar { position:relative; input.hasDatepicker { padding-right: 2.4em; } .ui-datepicker-trigger { border-bottom-width: 3px; position: absolute; right: -2px; width: 2.4em; .ui-button-text { padding: 0.26em; } } .ui-inputfield { &.ui-corner-all { @include border-radius-right(3px); } } &.ui-trigger-calendar { .ui-button-icon-only { .ui-button-text { padding: 0.26em; } } } } } /* DatePicker */ .p-datepicker-panel { @include border-radius(3px); overflow: hidden; &:not(.ui-datepicker-inline), .ui-datepicker-group { border: 0 none; @include border-radius(0); } .ui-datepicker-header { .ui-datepicker-prev, .ui-datepicker-next { outline: 0 none; &:hover { background-color: $grey; color: #fff; } } } table { td { a { &:hover { background: $greyLight; } &.ui-state-active { background: $regularColor; color: #fff; } } a,span { width: 100%; @include box-sizing(border-box); } &.ui-datepicker-today { a { background: $greyLight; color: $blackLight; } } } } &.ui-datepicker-multiple-month { .ui-datepicker-group { @include border-radius(0); width: 17em; .ui-datepicker-header { @include border-radius(0); } &:first-child { .ui-datepicker-header { @include border-radius-left(3px); } } &:last-child { .ui-datepicker-header { @include border-radius-right(3px); } } .ui-datepicker-calendar-container { padding: 0 5px; } } } &.ui-datepicker-monthpicker { .ui-monthpicker { .ui-monthpicker-month { color: $blackLight; @include box-sizing(border-box); &:hover { background: $greyLight; } &.ui-state-active { background: $regularColor; color: #fff; } } } } .ui-timepicker { font-weight: normal; border: 0 none; @include border-radius-top(0); .ui-picker-up { color: #ffffff; @include icon_override("\f077"); display: block; margin-bottom: .2em; span { display: none; } &:hover { background-color: $grey; color: #fff; } } .ui-picker-down { color: #ffffff; @include icon_override("\f078"); display: block; margin-top: .2em; span { display: none; } &:hover { background-color: $grey; color: #fff; } } } .ui-datepicker-buttonbar { border: 0 none; @include border-radius-top(0); .ui-button { width: auto; &:focus { border: 1px solid $regularColor; color: $blackLight; -moz-box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12); -webkit-box-shadow:0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12); box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12); outline: 0 none; } &:hover { background: $lightColor; border-bottom: 5px solid $regularColor; } } } } /* ====== DATA ======*/ /* Datatable */ .ui-datatable { .ui-datatable-header { &.ui-widget-header { background: $blackLight; border: none; padding: 10px; } } thead { th { &.ui-state-default { background-color: $greyLight; border-color: $greyBorder; color: $blackLight; } .ui-selectonemenu-trigger, .ui-selectcheckboxmenu-trigger { background: $grey; border: none; border-bottom: 5px solid $greyDark; .ui-icon { padding: 0; } &.ui-state-hover { background: $greyDark; } } &.ui-sortable-column { &.ui-state-hover { background: $blackLight; color: #fff; .ui-sortable-column-icon { &.ui-icon { &.ui-icon-carat-2-n-s:before { color: #fff; } } } } &.ui-state-active { background: $regularColor; color: #fff; .ui-sortable-column-icon { &.ui-icon { &.ui-icon-triangle-1-n:before { color: #fff; } &.ui-icon-triangle-1-s:before { color: #fff; } } } } .ui-sortable-column-icon { &.ui-icon { &.ui-icon-carat-2-n-s { font-size: 13px; color: $grey; padding: 2px 0 0 2px; vertical-align: middle; } &.ui-icon-triangle-1-n { font-size: 13px; color: $grey; padding: 2px 0 0 2px; vertical-align: middle; } &.ui-icon-triangle-1-s { font-size: 13px; color: $grey; padding: 2px 0 0 2px; vertical-align: middle; } } } } } } tfoot { td { &.ui-state-default { background-color: $greyLight; border-color: $greyBorder; color: $blackLight; } } } tbody { &.ui-datatable-data { .ui-button { &.ui-state-default { background: $regularColor; border-bottom: 5px solid $darkColor; } &.ui-state-hover { background: $darkColor; } } tr.ui-widget-header { border-color: $greyBorder; > .ui-state-default { background-color: $greyLight; border-color: $greyBorder; color: $blackLight; } } tr.ui-widget-content { border-color: $greyBorder; &.ui-datatable-selectable { &.ui-state-hover { background-color: $grey; color: #fff; } &.ui-state-highlight { background: $regularColor; color: #fff; .ui-radiobutton-box { border-color: $lightColor; .ui-radiobutton-icon { margin-left: -0.2px; } } .ui-chkbox-box { border-color: $lightColor; } } } &.ui-datatable-odd { background-color: $bg-greyLight; } &.ui-row-editing { td { background: $orange; border-color: $orange; .ui-icon-check { @include icon-override('\f00c'); } .ui-icon-close { @include icon-override('\f00d'); } } .ui-inputfield { width: 100%!important; box-sizing: border-box; } } td { .ui-icon { &.ui-icon-pencil { @include icon-override('\f040'); } } &.ui-cell-editing { background: $orange; border-color: $orange; .ui-inputfield { width: 100%!important; box-sizing: border-box; } } } } } } &.ui-datatable-scrollable { .ui-datatable-scrollable-header, .ui-datatable-scrollable-footer { background-color: $greyLight; } } } /* DataGrid */ .ui-datagrid { .ui-widget-header { &.ui-datagrid-header { background: $blackLight; } } .ui-paginator { &.ui-widget-header { border-color: $grey; } } .ui-datagrid-content { .ui-grid-row { .ui-datagrid-column { .ui-panel { .ui-widget-header { background: $blackLight; } } } } } } /* Paginator */ .ui-paginator { &.ui-widget-header { background: #fff; border-color: $greyBorder; > .ui-state-default { vertical-align: middle; border: none; color: $greyDark; @include border-radius(0); &.ui-state-hover { border: none; background: none; border-bottom: 5px solid $grey; } &.ui-state-active { border: none; background: none; border-bottom: 5px solid $regularColor; } } .ui-icon { color: $greyDark; } .ui-paginator-first { border-bottom: 5px solid #fff; .ui-icon { &.ui-icon-seek-first { @include icon-override("\f100"); width: 10px; overflow: hidden; font-size: 16px; font-weight: bold; padding-top: 0; height: 16px; } } } .ui-paginator-prev { border-bottom: 5px solid #fff; .ui-icon { &.ui-icon-seek-prev { @include icon-override("\f104"); width: 6px; overflow: hidden; font-size: 16px; font-weight: bold; padding-top: 0; height: 16px; } } } .ui-paginator-next { border-bottom: 5px solid #fff; .ui-icon { &.ui-icon-seek-next { @include icon-override("\f105"); width: 6px; overflow: hidden; font-size: 16px; font-weight: bold; height: 16px; } } } .ui-paginator-last { border-bottom: 5px solid #fff; .ui-icon { &.ui-icon-seek-end { @include icon-override("\f101"); width: 10px; overflow: hidden; font-size: 16px; font-weight: bold; height: 16px; } } } .ui-paginator-current { color: $greyDark; } .ui-paginator-pages { vertical-align: middle; .ui-paginator-page { @include border-radius(0); &.ui-state-default { border: none; color: $greyDark; border-bottom: 5px solid transparent; } &.ui-state-hover { border: none; background: none; border-bottom: 5px solid $grey; } &.ui-state-active { border: none; background: none; border-bottom: 5px solid $regularColor; } } } > .ui-paginator-rpp-options { &.ui-state-hover { border: 0 none; } } } } /* DATALIST */ .ui-datalist { .ui-paginator { &.ui-widget-header { border-color: $grey; } } .ui-datalist-header { &.ui-widget-header { background: $blackLight; } } } /* DataView */ .ui-dataview { .ui-paginator { @include border-radius(0); &.ui-widget-header { border-color: $grey; } } .ui-dataview-header { background: $blackLight; .ui-dataview-layout-options { .ui-button-icon-only { width: 2.5em; } } } } /* PickList */ .ui-picklist { .ui-picklist-list { .ui-picklist-item { border-left: 5px solid transparent; border-radius: 0; margin: 0; &.ui-state-hover { background-color: $grey; border-color: $greyDark; color: #fff; } &.ui-state-highlight { background: $regularColor; border-color: $darkColor; color: #fff; .ui-chkbox { .ui-chkbox-box { border-color: #f6bb4e; } } } } } .ui-picklist-buttons { .ui-icon { font-size: 16px; } .ui-icon-arrow-1-n { @include icon-override("\f106"); } .ui-icon-arrowstop-1-n { @include icon-override("\f102"); } .ui-icon-arrow-1-s { @include icon-override("\f107"); } .ui-icon-arrowstop-1-s { @include icon-override("\f103"); } .ui-icon-arrow-1-e { @include icon-override("\f105"); } .ui-icon-arrowstop-1-e { @include icon-override("\f101"); } .ui-icon-arrow-1-w { @include icon-override("\f104"); } .ui-icon-arrowstop-1-w { @include icon-override("\f100"); } } .ui-picklist-filter-container { .ui-icon { @include icon-override("\f002"); font-size: 14px; color: $greyDark; padding-top: 2px; } .ui-picklist-caption { &.ui-widget-header { background: $blackLight; } } .ui-picklist-list { &.ui-widget-content { .ui-picklist-item { border-left: 3px solid transparent; border-radius: 0; margin: 0; &.ui-state-hover { background: $grey; color: #fff; border-color: $greyDark; } &.ui-state-highlight { background: $regularColor; border-color: $darkColor; color: #fff; } } } } } } @media (max-width : 640px) { .ui-picklist { .ui-picklist-buttons { .ui-icon-arrow-1-e { @include icon-override("\f107"); } .ui-icon-arrowstop-1-e { @include icon-override("\f103"); } .ui-icon-arrow-1-w { @include icon-override("\f106"); } .ui-icon-arrowstop-1-w { @include icon-override("\f102"); } } } } /* OrderList */ .ui-orderlist { .ui-orderlist-controls { .ui-button { &.ui-button-icon-only { .ui-button-icon-left { &.ui-icon-arrow-1-n { @include icon-override("\f106"); font-size: 16px; color: #fff; } &.ui-icon-arrowstop-1-n { @include icon-override("\f102"); font-size: 16px; color: #fff; } &.ui-icon-arrow-1-s { @include icon-override("\f107"); font-size: 16px; color: #fff; } &.ui-icon-arrowstop-1-s { @include icon-override("\f103"); font-size: 16px; color: #fff; } } } } } &.ui-grid-responsive { .ui-grid-row { .ui-orderlist-controls { margin-right: 0; padding-right: 10px; } } } .ui-orderlist-caption { &.ui-widget-header { background: $blackLight; width: 200px; } } .ui-orderlist-list { &.ui-widget-content { .ui-orderlist-item { border-left: 5px solid transparent; border-radius: 0; margin: 0; &.ui-state-hover { background-color: $grey; border-color: $greyDark; color: #fff; } &.ui-state-highlight { background: $regularColor; border-color: $darkColor; color: #fff; } } } } } /* Carousel */ .ui-carousel { &.ui-widget { padding: 0; } .ui-carousel-header { &.ui-widget-header { background: $blackLight; border: none; margin: 0; border-radius: 0; .ui-carousel-button { &.ui-icon-circle-triangle-e { @include icon-override("\f0a9"); font-size: 16px; color: #fff; padding: 0 0 2px 4px; } &.ui-icon-circle-triangle-w { @include icon-override("\f0a8"); font-size: 16px; color: #fff; padding: 0 0 2px 4px; } } } .ui-carousel-page-links { margin-top: 3.4px; .ui-icon-radio-off { @include icon-override("\f10c"); text-decoration: none; } .ui-icon-radio-on { @include icon-override("\f111"); color: $regularColor; } } } .ui-carousel-viewport { .ui-carousel-items { .ui-carousel-item { &.ui-widget-content { border: 1px solid $greyBorder; padding-top: 35px; } } } } .ui-carousel-footer { &.ui-widget-header { margin: 0; @include border-radius(0); } } } /* Tree */ .ui-tree { .ui-treenode { .ui-treenode-content { .ui-tree-toggler { &.ui-icon { &.ui-icon-triangle-1-e { @include icon-override("\f105"); font-size: 14px; color: $blackLight; text-align: center; vertical-align: middle; } &.ui-icon-triangle-1-s { @include icon-override("\f107"); font-size: 14px; color: $blackLight; text-align: center; vertical-align: middle; } } } .ui-treenode-icon { vertical-align: middle; margin-top: 2px; margin-left: 5px; } .ui-treenode-label { margin-top: 0px; vertical-align: middle; } .ui-chkbox { vertical-align: middle; .ui-icon-minus { @include icon-override("\f068"); color: $regularColor; padding-left: 1px; visibility: visible; } .ui-icon-check { color: $regularColor; visibility: visible; } } } } } /* TreeTable */ .ui-treetable { .ui-treetable-header { &.ui-widget-header { background: $blackLight; } } &.ui-treetable-scrollable { .ui-treetable-scrollable-header { background-color: $greyLight; } } th.ui-state-default { background: $greyLight; border-color: $greyBorder; color: $blackLight; &.ui-sortable-column { .ui-sortable-column-icon { &.ui-icon-carat-2-n-s { font-size: 12px; color: $grey; padding: 3px 0 0 3px; vertical-align: middle; } &.ui-icon-triangle-1-n { font-size: 12px; color: $grey; padding: 3px 0 0 3px; vertical-align: middle; } &.ui-icon-triangle-1-s { font-size: 12px; color: $grey; padding: 3px 0 0 3px; vertical-align: middle; } } &.ui-state-active { background: $regularColor; color: #fff; .ui-sortable-column-icon { &.ui-icon { &.ui-icon-carat-2-n-s { &:before { color: #fff; } } &.ui-icon-triangle-1-n:before { color: #fff; } &.ui-icon-triangle-1-s:before { color: #fff; } } } } } } tbody { &.ui-treetable-data { tr.ui-widget-content { box-sizing: border-box; border-color: $greyBorder; &.ui-treetable-selectable-node { .ui-chkbox { &.ui-selection { margin-left: 2px; margin-right: 4px; vertical-align: middle; .ui-chkbox-box { .ui-icon-check { visibility: visible; } .ui-icon-minus { @include icon-override("\f068"); visibility: visible; color: $regularColor; padding-left: 2px; padding-top: 1px; } } } } .ui-treetable-toggler { &.ui-icon-triangle-1-e { @include icon-override("\f105"); font-size: 14px; padding: 3px 0 0 5px; width: 10px; } &.ui-icon-triangle-1-s { @include icon-override("\f107"); font-size: 14px; padding: 3px 0 0 5px; width: 10px; } } } &.ui-state-hover { background-color: $grey; color: #fff; } &.ui-state-highlight { .ui-chkbox-box { .ui-icon-check { color: $regularColor; } } } } } } .ui-paginator.ui-paginator-bottom { border-top: 1px solid $greyBorder; } } /* ====== PANELS ======*/ /* Panel */ .ui-panel { &.ui-widget-content { padding: 0px; } .ui-panel-titlebar { padding: 0px; -moz-border-radius-topleft: 2px; -webkit-border-top-left-radius: 2px; border-top-left-radius: 2px; -moz-border-radius-topright: 2px; -webkit-border-top-right-radius: 2px; border-top-right-radius: 2px; -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; .ui-panel-titlebar-icon { height: 16px; .ui-icon { text-align: center; display: inline-block; padding-top: 2px; } } } } /* Accordion */ .ui-accordion { .ui-accordion-header { border-left: 5px solid transparent; &.ui-state-default { background: $greyLight; color: #fff; .ui-icon { margin-top: -10px; &.ui-icon-triangle-1-e { @include icon-override("\f105"); font-size: 16px; color: #fff; padding-left: 8px; } } } &.ui-state-hover { background: $darkColor; .ui-icon { background-image: none; } } &.ui-state-active { background: $regularColor; border-color: $darkColor; .ui-icon { &.ui-icon-triangle-1-s { @include icon-override("\f107"); font-size: 16px; color: #fff; padding-left: 5px; } } } } } /* TabView */ .ui-tabs { &.ui-tabs-scrollable { .ui-icon { &.ui-icon-carat-1-w { @include icon-override("\f053"); margin: 7px 0 0 7px; } &.ui-icon-carat-1-e { @include icon-override("\f054"); margin: 7px 0 0 7px; } } } &.ui-tabs-top { padding: 0; .ui-tabs-nav { &.ui-widget-header { padding: 0; .ui-state-default { top: 0; border: none; border-bottom: 5px solid $blackLight; background: $blackLight; margin: 0; border-radius: 0; .ui-icon-close { @include icon-override("\f00d"); font-size: 12px; color: $grey; margin-top:2px; } a { outline: 0 none; color: #fff; } &.ui-tabs-selected { background: $regularColor; border-color: $darkColor; &.ui-state-hover { background: $regularColor; border-color: $darkColor; } .ui-icon { &:before { color: #fff; } } } &.ui-state-hover { background: $grey; border-color: $greyDark; .ui-icon { &:before { color: #fff; } } } } } } } &.ui-tabs-left { padding: 0; .ui-tabs-nav { padding: 0; .ui-state-default { margin: 0; background: $blackLight; border: none; border-bottom: 5px solid transparent; width: 100%; border-radius: 0; a { outline: 0 none; color: #fff; } &.ui-tabs-selected { &.ui-state-active { background: $regularColor; border-bottom: 5px solid $darkColor; } } &.ui-state-hover { background: $grey; border-color: $greyDark; } } } } &.ui-tabs-bottom { .ui-tabs-nav { &.ui-widget-header { .ui-state-default { background: $blackLight; margin: 0; border: none; border-bottom: 5px solid transparent; a { outline: 0 none; color: #fff; } &.ui-tabs-selected { &.ui-state-active { background: $regularColor; border-color: $darkColor; } } &.ui-state-hover { background: $grey; border-color: $greyDark; } } } } } } /* Ribbon */ .ui-ribbon { .ui-button { &.ui-state-default { background: $regularColor; } } } /* ToolBar */ .ui-toolbar { background: $blackLight; &.ui-widget-header { border-color: $greyLight; } .ui-separator { margin-right: 5px; } } /* FieldSet */ .ui-fieldset { &.ui-widget-content { .ui-fieldset-legend { &.ui-state-default { background: $blackLight; color: #fff; } .ui-fieldset-toggler { margin-top: 0.1em; &.ui-icon-minusthick { @include icon-override("\f068"); } &.ui-icon-plusthick { @include icon-override("\f067"); } } } } } /* ====== MENUs ======*/ /* Breadcrumb */ .ui-breadcrumb { &.ui-widget-header { background: $blackLight; border-color: $black; color: #fff; ul { .ui-menuitem-link { text-decoration: none; margin-top: 5px; &.ui-icon-home { @include icon-override("\f015"); font-size: 12px; color: $greyLight; text-align: center; margin-top: 7px; overflow: hidden; height: 12px; } .ui-menuitem-text { color: $greyLight; } } .ui-breadcrumb-chevron { @include icon-override("\f054"); font-size: 12px; color: $greyLight; text-align: center; margin-top: 7px; } } } } /* MENU */ .ui-menu { &.ui-widget { /* menu button specific */ .ui-menuitem { &.ui-state-hover { background: $greyLight; color: $blackLight; border-color: transparent; .ui-menuitem-link { color: $blackLight; } } } .ui-menuitem-link { width:100%; box-sizing: border-box; padding-left: 8px; @include border-radius(0); &.ui-state-hover { background: $greyLight; color: $blackLight; border-color: transparent; } } } .ui-menu-list { li.ui-widget-header { margin: 0; width: 100%; border-radius: 0; box-sizing: border-box; h3 { padding-left: 8px; } .ui-icon-triangle-1-s { @include icon-override("\f107"); color: #fff; padding-left: 4px; } .ui-icon-triangle-1-e { @include icon-override("\f105"); color: #fff; padding-left: 4px; } &.ui-state-hover { color: $regularColor; background-color: $blackLight; .ui-icon { &.ui-icon-triangle-1-s:before { color: $regularColor; } &.ui-icon-triangle-1-e:before { color: $regularColor; } } } } } &.ui-menubar { .ui-menuitem { &.ui-menubar-options { padding: 2px; } .ui-inputfield { &.ui-inputtext { width: inherit; } } .ui-menuitem-link { .ui-menuitem-icon { &.ui-icon:before { color: $regularColor; } } .ui-menuitem-icon { margin-right: 5px; } .ui-icon-triangle-1-e { @include icon-override("\f054"); font-size: 12px; color: $grey; margin: 2px -5px 0 5px; } .ui-icon-triangle-1-s { @include icon-override("\f078"); font-size: 12px; color: $grey; margin: 2px -5px 0 5px; } } } .ui-menu-list { &.ui-menu-child { .ui-menuitem-link { width:100%; box-sizing: border-box; padding: .3em 0 .3em .3em; } } } } &.ui-tieredmenu { .ui-menu-list { .ui-menuitem { &.ui-menu-parent { margin: 0; &.ui-menuitem-active { background: $regularColor; a { color: $blackLight; .ui-icon { &.ui-icon-triangle-1-e:before { color: $blackLight; } } } } .ui-icon { &.ui-icon-triangle-1-e { @include icon-override("\f054"); font-size: 12px; color: $grey; margin-right: -5px; margin-top: 2px; } } } } } } &.ui-slidemenu { .ui-slidemenu-wrapper { .ui-slidemenu-content { .ui-menu-list { .ui-menuitem { &.ui-menu-parent { .ui-icon { &.ui-icon-triangle-1-e { @include icon-override("\f105"); font-size: 12px; color: $grey; padding-left: 4px; } } } } } } .ui-slidemenu-backward { width: 97.5%; border-radius: 0; margin-bottom: 0; } } } } /* MenuButton */ .ui-menubutton { .ui-button { .ui-icon-triangle-1-s { @include icon-override("\f107"); margin-top: -6px; } } } .ui-panelmenu { .ui-panelmenu-header { &.ui-state-default { background-color: $blackLight; a { color: #fff; padding-left: 2em; } .ui-icon { &.ui-icon-triangle-1-e { @include icon-override("\f105"); font-size: 14px; color: #fff; margin-left: 4px; } &.ui-icon-triangle-1-s { @include icon-override("\f107"); font-size: 14px; color: #fff; margin-left: 4px; } } } &.ui-state-hover { a { color: $regularColor; } .ui-icon { &.ui-icon-triangle-1-e { &:before { color: $regularColor; } } &.ui-icon-triangle-1-s { background-image: none; &:before { color: $regularColor; } } } } &.ui-state-active { background-color: $regularColor; .ui-icon { &.ui-icon-triangle-1-e { &:before { color: #fff; } } &.ui-icon-triangle-1-s { background-image: none; &:before { color: #fff; } } } } } .ui-panelmenu-icon { background-image: none; color: $blackLight; width:20px; padding-left:4px; &.ui-icon-triangle-1-e { @include icon-override("\f105"); } &.ui-icon-triangle-1-s { @include icon-override("\f107"); } } .ui-menuitem-link { width:100%; box-sizing: border-box; @include border-radius(0); padding: .3em 0em .3em .8em; &.ui-state-hover { color: $blackLight; background: $greyLight; border-color: transparent; } } } /* TabMenu */ .ui-tabmenu { &.ui-widget-content { border: none; .ui-tabmenu-nav { &.ui-widget-header { padding: 0; background: transparent; li { background: transparent; border: none; border-bottom: 5px solid transparent; margin: 0; top: 0; a { padding: 0.7em 1em 0.5em 0.2em; } .ui-menuitem-text { color: $greyDark; margin-top: 13px; } .ui-menuitem-icon { color: $greyDark; } &.ui-state-active { border-color: $darkColor; } &.ui-state-hover { border-color: $grey; } } } } } } /* Steps */ .ui-steps { &.ui-widget { margin-bottom: 30px; @include border-radius(3px); .ui-steps-item { .ui-menuitem-link { height: 10px; padding: 0 1em; } .ui-steps-number { background-color: $lightColor; color: #fff; display: inline-block; width: 30px; border-radius: 10px; margin-top: -14px; margin-bottom: 10px; } &.ui-state-highlight { .ui-steps-title { color: $blackLight; } } } } } /* MegaMenu */ .ui-megamenu { &.ui-megamenu-vertical { .ui-menuitem { width: 100%; } .ui-submenu-link { &.ui-menuitem-link { width:100%; box-sizing: border-box; &.ui-state-hover { background: $greyLight; border-color: transparent; } } } } .ui-menu-list { .ui-widget-header { span { padding-left: 8px; } } } } /* Scroll Panel*/ .ui-scrollpanel-container { .ui-scrollpanel-drag { &.ui-state-highlight { background: $regularColor; } } } /* FileUpload */ .ui-fileupload { .ui-button-text-icon-left { .ui-icon { margin-top: -6px; } } .ui-icon-plusthick { @include icon-override("\f067"); } .ui-icon-arrowreturnthick-1-n { @include icon-override("\f093"); } .ui-icon-cancel { @include icon-override("\f00d"); } .ui-icon-close { @include icon-override("\f00d"); } } .ui-fileupload-simple { .ui-icon-plusthick { @include icon-override("\f067"); } } /* ProgressBar */ .ui-progressbar { .ui-progressbar-value { background-color: $lightColor; } } /* Messages */ .ui-messages { &.ui-widget { ul { display: inline-block; margin-left: 0; } } } /* Info */ .ui-messages .ui-messages-info, .ui-message.ui-message-info { color: #fff; background: $info; border-color: $info; } .ui-messages .ui-messages-info-icon,.ui-message .ui-message-info-icon { @include icon-override("\f05a"); font-size: 20px; color: #fff; padding: 4px; } .ui-message .ui-message-info-icon { padding: 0px; font-size: 18px; } /* Error */ .ui-messages .ui-messages-error, .ui-message.ui-message-error { color: #fff; background: $error; border-color: $error; } .ui-messages .ui-messages-error-icon,.ui-message .ui-message-error-icon { @include icon-override("\f056"); font-size: 20px; color: #fff; padding: 4px; } .ui-message .ui-message-error-icon { padding: 0px; font-size: 18px; } /* Warn */ .ui-messages .ui-messages-warn, .ui-message.ui-message-warn { color: #fff; background: $warning; border-color: $warning; } .ui-messages .ui-messages-warn-icon,.ui-message .ui-message-warn-icon { @include icon-override("\f071"); font-size: 20px; color: #fff; padding: 4px; } .ui-message .ui-message-warn-icon { padding: 0px; font-size: 18px; } /* Fatal */ .ui-messages .ui-messages-fatal, .ui-message.ui-message-fatal { color: #fff; background: $error; border-color: $error; } .ui-messages .ui-messages-fatal-icon,.ui-message .ui-message-fatal-icon { @include icon-override("\f056"); font-size: 20px; color: #fff; padding: 4px; } .ui-message .ui-message-fatal-icon { padding: 0px; font-size: 18px; } .ui-messages-close { span { @include icon-override("\f00d"); font-size: 14px; color: #fff; } } /* Growl */ .ui-growl { .ui-state-highlight { &.ui-growl-info { color: #fff; background: $info; border-color: $info; .ui-growl-image-info { @include icon-override("\f05a"); font-size: 36px; color: #fff; padding: 4px; } } &.ui-growl-error { color: #fff; background: $error; border-color: $error; .ui-growl-image-error { @include icon-override("\f056"); font-size: 36px; color: #fff; padding: 4px; } } &.ui-growl-warn { color: #fff; background: $warning; border-color: $warning; .ui-growl-image-warn { @include icon-override("\f071"); font-size: 36px; color: #fff; padding: 4px; } } &.ui-growl-fatal { color: #fff; background: $error; border-color: $error; .ui-growl-image-fatal { @include icon-override("\f056"); font-size: 36px; color: #fff; padding: 4px; } } } .ui-growl-icon-close { @include icon-override("\f00d"); font-size: 14px; color: #fff; } } /* Schedule */ .fc { .ui-button { &.ui-state-default { width: auto; } } &.fc-ltr { .ui-widget-content { background-color: #ffffff; .ui-state-highlight { background: $lightColor; border-color: $regularColor; } } .fc-event { background: $greenLight; border-color: $greenLight; } .fc-view-container { .fc-view { .ui-widget-header { background: $lightColor; border-color: $greyLight; } } } .fc-toolbar { background: $blackLight; margin-bottom: 0; padding: 40px 0; color: #fff; .ui-button { &.ui-state-default { background: $blackLight; border-color: $blackLight; color: #fff; } &.ui-state-active { color: $regularColor; } } .fc-prev-button { .ui-icon { @include icon-override("\f060"); font-size: 16px; color: #fff; } } .fc-next-button { .ui-icon { @include icon-override("\f061"); font-size: 16px; color: #fff; } } } } td, th { border-color: $greyLight; } } /* Dialog */ .ui-dialog { .ui-dialog-titlebar { @include border-radius-top(0); &.ui-widget-header { border-bottom: 5px solid $regularColor; } .ui-dialog-titlebar-icon { text-decoration: none; width: 16px; margin-top: .3em; &.ui-state-hover { color: $regularColor; border-color: transparent; background-color: transparent; } } .ui-dialog-titlebar-close { span { @include icon-override("\f00d"); } } .ui-dialog-titlebar-maximize { .ui-icon-extlink { @include icon-override("\f065"); } .ui-icon-newwin { @include icon-override("\f066"); } } .ui-dialog-titlebar-minimize { .ui-icon-minus { @include icon-override("\f068"); } .ui-icon-plus { @include icon-override("\f067"); } } } > .ui-icon-gripsmall-diagonal-se { @include icon-override("\f065"); opacity: .5; -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)"; -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } } .ui-confirm-dialog { .ui-confirm-dialog-severity { float: none; vertical-align: middle; margin-right: 10px; &.ui-icon-alert { @include icon-override("\f071"); font-size: 20px; width: 20px; height: 20px; } } .ui-confirm-dialog-message { vertical-align: middle; margin-top: 0px; } } /*sidebar*/ .ui-sidebar { .ui-sidebar-close { &:hover { padding: 1px; } } .ui-button { width: auto; } } /* Lightbox */ .ui-lightbox { .ui-lightbox-nav-left { height: 30px; .ui-icon-carat-1-w { @include icon-override("\f053"); width: 10px; margin-top: 8px; } } .ui-lightbox-nav-right { height: 30px; .ui-icon-carat-1-e { @include icon-override("\f054"); width: 10px; margin-top: 8px; } } .ui-lightbox-caption { .ui-lightbox-close { .ui-icon-closethick { @include icon-override("\f00d"); margin-top: 5px; } &.ui-state-hover { color: $regularColor; border-color: transparent; background-color: transparent; } } } } .ui-galleria { .ui-galleria-nav-prev { &.ui-icon-circle-triangle-w { @include icon-override("\f0a8"); &:hover { color: $regularColor; } } } .ui-galleria-nav-next { &.ui-icon-circle-triangle-e { @include icon-override("\f0a9"); &:hover { color: $regularColor; } } } } .ui-panelgrid { &.ui-panelgrid-blank { .ui-grid-responsive { .ui-grid-row { border: 0 none; } } } } .ui-overlaypanel { .ui-overlaypanel-close { height: 16px; .ui-icon { text-align: center; display: inline-block; } } } .ui-columntoggler { .ui-columntoggler-close { height: 16px; .ui-icon { text-align: center; display: inline-block; } } } .ui-fluid { .ui-wizard-navbar { .ui-button { width: auto; } } } @import '../_theme_styles.scss';<file_sep>package generator.model; public enum Nature { PROFESSIONAL_EXPERIENCE, EDUCATION, PROJECT, OTHER; } <file_sep>package generator.services; import java.time.LocalDate; import org.apache.commons.lang3.RandomUtils; import com.thedeanda.lorem.Lorem; import com.thedeanda.lorem.LoremIpsum; import generator.model.Activity; import generator.model.Nature; import generator.model.Person; public class RandomActivityFactory { private Lorem lorem = LoremIpsum.getInstance(); private static int availableId = 1; private final static int MIN_AGE = 16; public Activity create(Person owner) { Activity activity = new Activity(); activity.setId(createId()); activity.setOwner(owner); activity.setYear(createYear(owner)); activity.setTitle(createTitle()); activity.setDescription(createDescription()); activity.setWebAddress(createWebAddress(activity.getTitle())); activity.setNature(createNature()); return activity; } private int createId() { return availableId++; } public int createYear(Person owner) { int minYear = owner.getDateOfBirth().getYear() + MIN_AGE; int maxYear = LocalDate.now().getYear(); return RandomUtils.nextInt(minYear, maxYear - 1); } public String createTitle() { return lorem.getTitle(2, 4); } public String createDescription() { return lorem.getHtmlParagraphs(2, 3); } private String createWebAddress(String title) { String escapedTitle = title.replace(' ', '-').toLowerCase(); return "https://www." + escapedTitle + ".com"; } private Nature createNature() { Nature[] natures = Nature.values(); int randomIndex = RandomUtils.nextInt(0, natures.length); return natures[randomIndex]; } } <file_sep>package generator.model; import java.io.Serializable; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor public class Activity implements Serializable { private static final long serialVersionUID = 1L; private int id; private int year; private String title; private String description; private String webAddress; private Nature nature; private Person owner; } <file_sep>#------------------------------------------------------------ # Script MySQL. #------------------------------------------------------------ #------------------------------------------------------------ # Table: Person #------------------------------------------------------------ CREATE TABLE Person( id Int Auto_increment NOT NULL , lastName Varchar (255) NOT NULL , firstName Varchar (255) NOT NULL , website Varchar (255) , dateOfBirth Date NOT NULL , password V<PASSWORD> (102) NOT NULL , email Varchar (255) NOT NULL ,CONSTRAINT Person_AK UNIQUE (email) ,CONSTRAINT Person_PK PRIMARY KEY (id) )ENGINE=InnoDB; #------------------------------------------------------------ # Table: Activity #------------------------------------------------------------ CREATE TABLE Activity( id Int Auto_increment NOT NULL , year Smallint NOT NULL , title Varchar (255) NOT NULL , description Varchar (10000) , webAddress Varchar (255) , nature Enum ("PROFESSIONAL_EXPERIENCE","EDUCATION","PROJECT","OTHER") NOT NULL , ownerId Int NOT NULL ,CONSTRAINT Activity_PK PRIMARY KEY (id) ,CONSTRAINT Activity_Person_FK FOREIGN KEY (ownerId) REFERENCES Person(id) )ENGINE=InnoDB; <file_sep>package gestioncv.servicesTests; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import java.util.Collection; import java.util.Collections; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import gestioncv.model.Activity; import gestioncv.services.impl.ActivityDao; @ExtendWith(MockitoExtension.class) public class ActivityDaoTest { @InjectMocks @Spy ActivityDao activityDao; @Test public void testFindAllSuccess() { Collection<Activity> activities = Collections.singletonList(Activity.builder().id(10).build()); doReturn(activities).when(activityDao).findAll(Activity.class); activityDao.findAll(); verify(activityDao).findAll(Activity.class); } @Test public void testFind() { int id = 10 ; Activity activity = Activity.builder().id(id).build(); doReturn(activity).when(activityDao).find(id); Activity foundedActivity = activityDao.find(id); verify(activityDao).find(id); assertEquals(id, foundedActivity.getId()); } @Test public void testRemove() { int id = 10 ; doNothing().when(activityDao).remove(Activity.class,id); activityDao.remove(id); verify(activityDao).remove(Activity.class,id); } } <file_sep>## Créer un compte administrateur et une BDD spécifiques au projet Créer un compte spécifique au projet permet d'éviter les fuites de mots de passe personnels et assure que chaque membre du projet partage la même version du fichier `persistence.xml`. La procédure suivante indique comment créer une base de données pour le projet ainsi que son compte administrateur : 1. Se connecter au CLI mysql ```bash $ sudo mysql ``` 2. Créer la base de données du projet ```mysql CREATE DATABASE Gestion-de-CVs; ``` 3. Créer l'utilisateur `gestion-cv-admin` ```mysql CREATE USER 'gestion-cv-admin'@'localhost' IDENTIFIED WITH caching_sha2_password BY '<PASSWORD>'; ``` > Il n'est pas nécessaire de modifier le mot de passe `<PASSWORD>`. Ce mot de passe n'est pas sensible, il est utilisé uniquement pour travailler temporairement en environnement de développement. Il peut donc être partagé sur Github sans problème. 3. Attribuer à l'utilisateur tous les privilèges sur la base de données ```mysql GRANT ALL PRIVILEGES ON `Gestion-de-CVs`.* TO 'gestion-cv-admin'@'localhost'; ``` 4. Appliquer les privilèges pour qu'ils soient fonctionnels immédiatement ```mysql FLUSH PRIVILEGES; ``` ## Préparer la base de données de développement ### Créer le schéma des tables Le code SQL présent dans le fichier `database/databaseSetup.sql` décrit le schéma des tables de la base de données. Il a été généré à l'aide du logiciel JMerise et à partir du Modèle Conceptuel des Données suivant : <img src="MCD.png" alt="MCD" style="zoom: 67%;" /> Pour créer les tables en bases de données, se placer dans le dossier `database` et exécuter la commande suivante : ```bash $ sudo mysql -p Gestion-de-CVs < databaseSetup.sql ``` ### Peupler la base de données L'application à développer doit supporter environ 100 000 personnes (et leurs activités). Afin de vérifier cette contrainte, un générateur de personnes / activités a été développé et a permit de générer le fichier `database/insertQueries-0.sql`. La base de données peut ainsi être peuplée avec la commande suivante : ```bash $ sudo mysql -p Gestion-de-CVs < insertQueries-0.sql ``` <file_sep>/** * PrimeFaces Icarus Layout */ PrimeFaces.widget.Icarus = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.wrapper = $(document.body).children('.wrapper'); this.menubar = $('#sidebar-wrapper'); this.sidebarNav = this.menubar.children('.sidebar-nav'); this.menubarElement = this.menubar.get(0); this.menubarContainer = this.menubar.find('ul.sidebar-nav-container'); this.slimToggleButton = $('#slim-menu-button'); this.content = $('#main-wrapper'); this.menulinks = this.menubarContainer.find('a.menuLink'); this.expandedMenuitems = this.expandedMenuitems || []; this.focusedItem = null; this.focusedTopItem = null; this.restoreMenuState(); this.bindEvents(); }, toggleMenu: function() { if(this.isDesktop()) { this.wrapper.toggleClass('slim-menu'); this.menubar.removeClass('normalize-menu'); } else { this.menubar.toggleClass('normalize-menu'); if(this.menubar.hasClass('normalize-menu')) this.wrapper.removeClass('slim-menu'); else this.wrapper.addClass('slim-menu'); } this.transitionControl(); $(window).trigger('resize'); }, bindEvents: function() { var $this = this; this.sidebarNav.nanoScroller({flash: true}); this.slimToggleButton.off('click.toggleButton').on('click.toggleButton', function(e) { $this.toggleMenu(); e.preventDefault(); }); this.menulinks.off('click.menuLinks').on('click.menuLinks',function(e) { var menuitemLink = $(this), menuitem = menuitemLink.parent(), hasSubmenuContainer = menuitemLink.next().is('ul'), isActive = menuitem.hasClass('active-menu-parent'); if($this.menubar.width() < 60) { $this.toggleMenu(); if(!isActive) { $this.activateMenuitem(menuitem); } } else if(hasSubmenuContainer) { if(isActive) $this.deactivateMenuitem(menuitem); else $this.activateMenuitem(menuitem); } else if(!isActive) { $this.activateMenuitem(menuitem); } if(hasSubmenuContainer) { e.preventDefault(); } $this.saveMenuState(); setTimeout(function() { $(".nano").nanoScroller(); }, 750); }); //remove transitions on IOS if(this.isIOS()) { this.menubar.find('a').addClass('notransition'); } //workaround for firefox bug of not resetting scrolltop if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { $(window).on('resize', function() { $this.menubarElement.scrollTop = 0; }); } $(document.body).on('click', function(e) { if(!$this.topbarLinkClick && $this.topbarItems) { $this.topbarItems.filter('.active').removeClass('active').children().removeClass('active-link'); $this.profileImage.parent().removeClass('active'); } $this.topbarLinkClick = false; }); $(function() { $this.topbarItems = $('#top-bar').find('> .top-menu > .top-bar-icon'); $this.topbarLinks = $this.topbarItems.find('> a'); $this.topbarLinks.on('click', function(e) { $this.topbarLinkClick = true; var link = $(this), item = link.parent(), submenu = item.children('ul'); item.siblings('.active').removeClass('active'); $this.profileImage.parent().removeClass('active'); if(submenu.length) { submenu.addClass(''); item.toggleClass('active'); link.toggleClass('active-link'); e.preventDefault(); } }); $this.profileImage = $('#profile-image'); $this.profileImageMobile = $('#profile-image-mobile'); $this.profileImage.on('click', function(e) { $this.topbarLinkClick = true; var link = $(this); $this.topbarItems.filter('.active').removeClass('active').children().removeClass('active-link'); link.parent().toggleClass('active'); e.preventDefault(); }); $this.profileImageMobile.on('click', function(e) { $this.topbarLinkClick = true; var link = $(this); $this.topbarItems.filter('.active').removeClass('active').children().removeClass('active-link'); link.parent().toggleClass('active'); e.preventDefault(); }); }); }, deactivateSiblings: function(menuitem) { var activeSiblings = this.findActiveSiblings(menuitem), $this = this; for(var i = 0; i< activeSiblings.length; i++) { var activeSibling = activeSiblings[i]; activeSibling.removeClass('active-menu-parent'); this.removeMenuitem(activeSibling); activeSibling.find('ul.active-menu').slideUp(300, function() { $(this).removeClass('active-menu').removeAttr('style'); }); activeSibling.find('a.active-menu').removeClass('active-menu'); activeSibling.find('li.active-menu-parent').each(function() { var menuitem = $(this); menuitem.removeClass('active-menu-parent'); $this.removeMenuitem(menuitem); }); } }, activateMenuitem: function(menuitem) { this.deactivateSiblings(menuitem); menuitem.addClass('active-menu-parent').children('.menuLink').addClass('active-menu').next('ul').slideDown(300, function() { $(this).addClass('active-menu').removeAttr('style'); }); this.addMenuitem(menuitem.attr('id')); }, deactivateMenuitem: function(menuitem) { menuitem.removeClass('active-menu-parent').children('.menuLink').removeClass('active-menu').next('ul').slideUp(300, function() { $(this).removeClass('active-menu').removeAttr('style'); }); this.removeMenuitem(menuitem); }, findActiveSiblings: function(menuitem) { var $this = this, siblings = menuitem.siblings('li'), activeSiblings = []; siblings.each(function () { if ($.inArray($(this).attr('id'), $this.expandedMenuitems) !== -1 || $(this).hasClass('active-menu-parent')) { activeSiblings.push($(this)); } }); return activeSiblings; }, restoreMenuState: function () { var menucookie = $.cookie('icarus_activemenuitem'); if (menucookie) { this.expandedMenuitems = menucookie.split(','); for (var i = 0; i < this.expandedMenuitems.length; i++) { var id = this.expandedMenuitems[i]; if (id) { var menuitem = $("#" + this.expandedMenuitems[i].replace(/:/g, "\\:")); menuitem.addClass('active-menu-parent'); menuitem.children('a').addClass('active-menu'); menuitem.children('ul').addClass('active-menu'); } } } }, removeMenuitem: function (menuitem) { var id = menuitem.attr('id'); this.expandedMenuitems = $.grep(this.expandedMenuitems, function (value) { return value !== id; }); var submenu = menuitem.children('ul.sidebar-submenu-container'); if(submenu && submenu.length) { var activeMenu = submenu.children('.active-menu-parent'); if(activeMenu && activeMenu.length) { activeMenu.removeClass('active-menu-parent'); activeMenu.children('a,ul').removeClass('active-menu'); this.removeMenuitem(activeMenu); } } }, addMenuitem: function (id) { if ($.inArray(id, this.expandedMenuitems) === -1) { this.expandedMenuitems.push(id); } }, saveMenuState: function() { $.cookie('icarus_activemenuitem', this.expandedMenuitems.join(','), {path:'/'}); }, clearMenuState: function() { $.removeCookie('icarus_activemenuitem', {path:'/'}); }, isIOS: function() { return ( navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false ); }, closeMenu: function() { this.menubarContainer.find('.sidebar-submenu-container.active-menu').hide().removeClass('active-menu'); this.menubarContainer.find('a.active-menu,li.active-menu-parent').removeClass('active-menu active-menu-parent'); var nano = $(".nano"); if(nano && nano.length) { $(".nano").nanoScroller({ stop: true }); } }, isTablet: function() { var width = window.innerWidth; return width <= 1024 && width > 640; }, isDesktop: function() { return window.innerWidth > 1024; }, isMobile: function() { return window.innerWidth <= 640; }, transitionControl: function() { var $this = this; if(!this.isMobile()) { this.menubar.addClass('wrapperTransition'); setTimeout(function(){ $this.menubar.removeClass('wrapperTransition'); },301); } } }); /*! * jQuery Cookie Plugin v1.4.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2006, 2014 <NAME> * Released under the MIT license */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD (Register as an anonymous module) define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS module.exports = factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function ($) { var pluses = /\+/g; function encode(s) { return config.raw ? s : encodeURIComponent(s); } function decode(s) { return config.raw ? s : decodeURIComponent(s); } function stringifyCookieValue(value) { return encode(config.json ? JSON.stringify(value) : String(value)); } function parseCookieValue(s) { if (s.indexOf('"') === 0) { // This is a quoted cookie as according to RFC2068, unescape... s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } try { // Replace server-side written pluses with spaces. // If we can't decode the cookie, ignore it, it's unusable. // If we can't parse the cookie, ignore it, it's unusable. s = decodeURIComponent(s.replace(pluses, ' ')); return config.json ? JSON.parse(s) : s; } catch(e) {} } function read(s, converter) { var value = config.raw ? s : parseCookieValue(s); return $.isFunction(converter) ? converter(value) : value; } var config = $.cookie = function (key, value, options) { // Write if (arguments.length > 1 && !$.isFunction(value)) { options = $.extend({}, config.defaults, options); if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setMilliseconds(t.getMilliseconds() + days * 864e+5); } return (document.cookie = [ encode(key), '=', stringifyCookieValue(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // Read var result = key ? undefined : {}, // To prevent the for loop in the first place assign an empty array // in case there are no cookies at all. Also prevents odd result when // calling $.cookie(). cookies = document.cookie ? document.cookie.split('; ') : [], i = 0, l = cookies.length; for (; i < l; i++) { var parts = cookies[i].split('='), name = decode(parts.shift()), cookie = parts.join('='); if (key === name) { // If second argument (value) is a function it's a converter... result = read(cookie, value); break; } // Prevent storing a cookie that we couldn't decode. if (!key && (cookie = read(cookie)) !== undefined) { result[name] = cookie; } } return result; }; config.defaults = {}; $.removeCookie = function (key, options) { // Must not alter options, thus extending a fresh object... $.cookie(key, '', $.extend({}, options, { expires: -1 })); return !$.cookie(key); }; })); /* Issue #924 is fixed for 5.3+ and 6.0. (compatibility with 5.3) */ if(window['PrimeFaces'] && window['PrimeFaces'].widget.Dialog) { PrimeFaces.widget.Dialog = PrimeFaces.widget.Dialog.extend({ enableModality: function() { this._super(); $(document.body).children(this.jqId + '_modal').addClass('ui-dialog-mask'); }, syncWindowResize: function() {} }); }
40c9d164c018417691299bbdccb217939f7161f3
[ "SCSS", "Java", "Markdown", "SQL", "JavaScript", "Maven POM" ]
16
SCSS
VictoriaNiaba/AA-Gestion-de-CVs
b46344634f6ee24d35faf4ffac643beb17b766f8
afd99fb32a95dc38c668e8e5affcb27622ac9705
refs/heads/master
<file_sep><!DOCTYPE html> <?php //var_dump($data); ?> <html> <head> <meta charset="utf-8"> <title>Super Blog</title> <script src="lib/jquery/jquery-1.12.0.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <style type="text/css"> .col-md-3, .col-md-1, .col-md-2, .col-md-12, .col-md-10 { border: 1px solid; text-align: center; } table { width: 100%; margin: 10px; } table, tr, td { border: 1px solid; padding: 10px; } th { padding: 10px; text-align: center; border: 1px solid; } .text-align-left { text-align: left; } </style> </head> <body> <div class="container" style="border:1px solid;"> <?php if (isset($user_data)){ ?> <h1>Hello <?=$user_data['true_auth']['login'];?>!</h1> <? } ?> <div class="row"> <div class="col-md-10" style="border:1px solid;"> class="col-md-10" </div> <div class="col-md-2" style="border:1px solid;"> <form action="" method="POST"> <div> <input name="exit" type="submit" value="Выход"> </div> </form> </div> </div> <div class="row"> <div class="col-md-12"> class="col-md-12 </div> </div> <div class="row"> <div class="col-md-2"> <div class="header"> Menu </div> </div> <div class="col-md-10"> <div class="header"> Наши статьи </div> <table> <th> Автор </th> <th> Статья </th> <th> Дата добавления </th> <th> Действия </th> <?php foreach ($data['articles'] as $dataKey => $article) { var_dump($article); ?> <tr> <td> <?=$article['login'];?> </td> <td class="text-align-left"> Название : <?=$article['title'];?><br> </td> <td> <?=$article['date'];?> </td> <td> <form> <input type="submit" name="edit" value="<?=$article['id'];?>"><br> <input type="submit" name="delete" value="<?=$article['id'];?>"> </form> </td> </tr> <?php } ?> </table> </div> </div> </div> </body> </html><file_sep><?php Class Model { private $registry; function __construct($registry) { $this->registry = $registry; } function auth($user_data){ $user_data['name'] = trim($user_data['name']); $user_data['pass'] = trim($user_data['pass']); $query = $this->registry['db']->query("SELECT * FROM users WHERE login = '". $user_data['name'] ."' AND password = '". $user_data['pass'] ."' "); $auth = $query->fetch(PDO::FETCH_ASSOC); if ($user_data['remember'] == true) { $_SESSION['hash'] = $_COOKIE['PHPSESSID']; }else{ $_SESSION['hash'] = ''; } $data_execute[] = $_SESSION['hash']; $data_execute[] = $auth['id']; $up = $this->registry['db']->prepare("UPDATE `users` SET `hash` = ? WHERE `id` = ? "); $up->execute($data_execute); unset($_SESSION['hash']); return $auth; } function user_get($param){ $query = $this->registry['db']->query("SELECT * FROM users WHERE hash = '". $param ."' "); $result = $query->fetchAll(); return $result; } function getArticles(){ // Достаем статьи а автора $query = $this->registry['db']->query("SELECT *, u.login as users FROM article AS a LEFT JOIN users u ON a.user_id = u.id ORDER BY a.id DESC "); // $query = $this->registry['db']->query("SELECT * FROM super_blog.article sa // WHERE sa.user_id // IN (SELECT id FROM super_blog.users su WHERE su.id = sa.user_id)"); $query->setFetchMode(PDO::FETCH_ASSOC); $results = $query->fetchAll(); if (empty($results)) { return false; } return $results; } // function getTags(){ // //// Достаем теги к статье // $query2 = $this->registry['db']->query("SELECT name FROM tags AS t // LEFT JOIN article_tags AS at // ON t.id = at.tag_id // "); // $query2->setFetchMode(PDO::FETCH_ASSOC); // $results[] = $query2->fetchALl(); // // if (empty($results)) { // return false; // } // // return $results; // } } ?><file_sep><? if (isset($user_data) && !empty($user_data[0]['login'])){ $login = $user_data[0]['login']; $password = $user_data[0]['password']; $hash = $user_data[0]['hash']; }else { $login = ''; $password = ''; $hash = ''; } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Авторизация</title> </head> <body> <div> Пожалуйста авторизуйтесь </div> <form action="" method="POST"> <input type="text" name="name" value="<?=$login;?>"><br> <input type="password" name="pass" value="<?=$password;?>"><br> <label><input type="checkbox" name="remember" <?=$checked = (empty($hash)) ? '' : 'checked';?>>Запомнить меня</label><br> <input type="submit" name="send" value="Войти" > </form> <form action="index.php" method="POST"> <div> <input name="home" type="submit" value="Главная страница"> <div> </form> </body> </html><file_sep><?php Class Controller_Index Extends Controller_Base { function index() { // $this->registry['model']->get();' $this->registry['template']->show('index'); } } ?><file_sep><?php error_reporting(E_ALL); session_start(); header('Content-Type: text/html; charset=utf-8'); define ('DIRSEP', DIRECTORY_SEPARATOR); // Узнаём путь до файлов $site_path = realpath(dirname(__FILE__) . DIRSEP . '.' . DIRSEP) . DIRSEP ; define ('site_path', $site_path); // Startup require_once($site_path . 'startup' . DIRSEP . 'startup.php'); # Соединяемся с БД $db = new PDO('mysql:host=localhost;dbname=super_blog', 'root', ''); //excellent $registry->set ('db', $db); //В этом примере мы сначала создаём новый экземпляр библиотеки PDO и соединяемся с нашей БД MySQL. Потом делаем переменную $db доступной глобально при помощи класса Registry. # Загружаем объект Template $template = new Template($registry); $registry->set ('template', $template); $model = new Model($registry); $registry->set ('model', $model); # Загружаем router $router = new Router($registry); $registry->set ('router', $router); $router->setPath (site_path . 'controllers'); $router->delegate(); ?><file_sep># php_level_2 Lessons GeekBrains at the php level 2 <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Super Blog</title> <script src="lib/jquery/jquery-1.12.0.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> </head> <body> <header> <a href="admin">Admin-Panel</a> </header> <content></content> <footer></footer> </body> </html><file_sep><?php Class Controller_Admin Extends Controller_Base { function index() { // Кнопка ВЫХОД if (isset($_POST['exit'])) { unset($_SESSION['true_auth']); } if (isset($_SESSION['true_auth']) && $_SESSION['true_auth'] != null) { $data = array(); $data['articles'] = $this->registry['model']->getArticles(); // $data['tags'] = $this->registry['model']->getTags(); // var_dump($data); $this->registry['template']->set('data', $data); $this->registry['template']->set('user_data', $_SESSION); $this->registry['template']->show('admin'); } else { if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send'])) { if (isset($_POST['name'])) { $name = $_POST['name']; }else{ $name = ''; } if (isset($_POST['pass'])) { $pass = $_POST['pass']; }else{ $pass = ''; } if (isset($_POST['remember'])) { $remember = $_POST['remember']; }else{ $remember = ''; } $user_data = array( 'name' => $name, 'pass' => $pass, 'remember' => $remember ); $auth = $this->registry['model']->auth($user_data); } if (isset($auth) && $auth != NULL) { $_SESSION['true_auth'] = $auth; // $this->registry['template']->show('admin'); header('Location: admin'); } $_SESSION['user'] = $this->registry['model']->user_get($_COOKIE['PHPSESSID']); $this->registry['template']->set('user_data', $_SESSION['user']); $this->registry['template']->show('auth'); } } } ?>
3345f7953e0e1180331ad5656a03e7880ffce02e
[ "Markdown", "Hack", "PHP" ]
8
Markdown
Takagero/php_level_2
3e6b3dea2cddcabe715e2c62a0cc0830e3f4df2c
989fa0f3d5fd988e964bc72176df6b69835e78eb
refs/heads/master
<file_sep>#!/usr/bin/perl use LWP::UserAgent; use IO::Pipe; use Getopt::Std; my $agent = new LWP::UserAgent; my $opt_string = 'c:u:z:s:p:r:C:h:H:vdt'; getopts($opt_string, \%opt) or usage(); sub usage() { print STDERR "Usage: ./zabbix_haproxy [arguments]\n"; print STDERR "This program reads the HAProxy config file for special notations and uses this info\n"; print STDERR "to send data about certain hosts in haproxy to zabbix.\n"; print STDERR "\n"; print STDERR "The haproxy config has 'frontend' sections and 'server' lines. These lines are annotated\n"; print STDERR "with a special comment which tells this script that the frontend or server is tagged for\n"; print STDERR "zabbix.\n"; print STDERR "\n"; print STDERR "Example config line where the frontend named 'irc-galleria' (the former) is sent to zabbix\n"; print STDERR "host named 'irc-galleria' (the later).\n"; print STDERR "frontend irc-galleria # @zabbix_frontend(irc-galleria)\n"; print STDERR "\n"; print STDERR "Another example for a server where server named suomirock is sent to zabbix host named\n"; print STDERR "suomirock.web.pri\n"; print STDERR " server suomirock 10.3.0.24:80 check weight 16 maxconn 200 # @zabbix_server(suomirock.web.pri)\n"; print STDERR "\n"; print STDERR "All hosts in zabbix must be tagged to use Template_HAProxyItem\n"; print STDERR "\n"; print STDERR "Command line arguments: You need to supply at least -c, -u and -s arguments.\n"; print STDERR " -c <filename> HAProxy config file\n"; print STDERR " -u <url> URL where the haproxy statistics are. ex: http://foobar.com/haproxy?stats;csv\n"; print STDERR " -s <hostname> Zabbix server host.\n"; print STDERR " -p <port> Zabbix trapper port. DEFAULT: 10051\n"; print STDERR " -z <full path> Path to zabbix_sender OPTIONAL\n"; print STDERR " -C <user>:<pass> HTTP Authentication username and password OPTIONAL\n"; print STDERR " -H <host>:<port> Hostname where the realm is active if HTTP Authentication is to be used. Defaults to host in -u <url> OPTIONAL\n"; print STDERR " -r <realm> HTTP Authentication basic realm, defaults to \"HAProxy Statistics\" OPTIONAL\n"; print STDERR " -h <hostname> Optional Host: <hostname> header parameter.\n"; print STDERR " -v turn verbose mode on.\n"; print STDERR " -d turn debug mode on (prints more than verbose).\n"; print STDERR " -t Just test, dont send anything to zabbix server.\n"; exit; } my $verbose = $opt{v} || $opt{d}; my $debug = $opt{d}; my $just_test = $opt{t}; # # CONFIGURATION # # Location of the haproxy config file #my $haproxy_conf = '/tmp/galtsu.cfg'; my $haproxy_conf = $opt{c} or usage(); # Url where the CVS haproxy stats can be fetched my $url = $opt{u} or usage();; # Host header in the http request my $host_header = $opt{h}; my $http_realm = $opt{r} ? $opt{r} : 'HAProxy Statistics'; my $http_host = $opt{H}; if (!$http_host) { if ($url =~ m|^http://(.+?)(:\d+)?/|) { $http_host = $1 . ($2 ? $2 : ':80'); } } if ($http_host !~ /:\d+/) { $http_host .= ':80'; } if ($opt{C}) { # Setup basic authentication my ($user, $pass) = split(/:/, $opt{C}); $verbose and print "Using basic authentication: server: $http_host, realm \"$http_realm\", username: $user, password: $<PASSWORD>"; $agent->credentials($http_host, $http_realm, $user => $pass); } # Path to zabbix_sender command my $zabbix_sender_path = $opt{z} ? $opt{z} : "zabbix_sender"; # Zabbix server my $zabbix_server = $opt{s} or usage(); # Zabbix trapper port my $zabbix_port = $opt{p} ? $opt{p} : 10051; $verbose and print "Using zabbix server at $zabbix_server:$zabbix_port\n"; # END OF CONFIGURATION # These are read from the haproxy config file. example from config where the frontend 'ircgalerie' (the former) will be mapped to zabbix host named 'ircgalerie' (the later) #frontend ircgalerie # @zabbix_frontend(ircgalerie) # bind 172.16.31.10:80 # ............. my %track_frontends = (); my %track_servers = (); parse_haproxy_conf($haproxy_conf); my $finished = 0; my $timeout = 2; $SIG{CHLD} = sub { wait, $finished = 1 }; my $pipe = new IO::Pipe; my $pid = fork; if($pid == 0) { $pipe->writer; my $response; if ($host_header) { $verbose and print "Using host header: $host_header\n"; $response = $agent->get($url, Host => $host_header); } else { $response = $agent->get($url); } if (!$response->is_success) { $pipe->print("FAILURE, response code: " . $response->status_line); } $pipe->print($response->content); exit; } $pipe->reader; sleep($timeout); my %proxies = (); my %backends = (); my %frontends = (); my %nodes = (); if($finished) { my $first_line = 1; foreach my $line ($pipe->getlines) { if ($first_line and $line =~ /^FAILURE, response code:/) { print STDERR "$line"; exit(1); } $first_line = 0; $debug and print "Got line $line"; if ($line =~ /^#/) { next; } my $data = parse_line($line); $proxies{$$data{pxname}}{$$data{svname}} = $data; } } else { kill(9, $pid); print "-1\n"; die("Could not get data from url $url"); } # Parse out all backends and frontends while (($pxname, $nodes) = each(%proxies)) { #print "proxy: $pxname\n"; while (($svname, $data) = each (%$nodes)) { #print "-- svname: " . $$data{svname} . "\n"; if ($$data{svname} eq "BACKEND") { #print "Found backend $pxname\n"; $backends{$pxname} = $data; } elsif ($$data{svname} eq "FRONTEND") { #print "Found frontend $pxname\n"; $frontends{$pxname} = $data; } else { $nodes{$$data{svname}} = $data; } } } # Print out all backend aggregates #while (($pxname, $data) = each(%backends)) { # print "Backend $pxname.\n"; # print_data($data); #} # Send frontends while (($haproxy_name, $zabbix_name) = each(%track_frontends)) { $verbose and print "Sending data for frontend $haproxy_name into zabbix host $zabbix_name\n"; send_data($zabbix_name, $frontends{$haproxy_name}); } # Send servers while (($haproxy_name, $data) = each(%nodes)) { if (exists $track_servers{$haproxy_name}) { $zabbix_name = $track_servers{$haproxy_name}; $verbose and print "Sending data for server $haproxy_name into zabbix host $zabbix_name\n"; send_data($zabbix_name, $data); } } sub print_data { my $data = shift; print " Sessions, current : " . $$data{scur} . "\n"; print " Sessions, max : " . $$data{smax} . "\n"; print " Sessions, total : " . $$data{stot} . "\n"; print " Traffic, in : " . $$data{bin} . "\n"; print " Traffic, out : " . $$data{bout} . "\n"; print " Responses: 1xx : " . $$data{hrsp_1xx} . "\n"; print " Responses: 2xx : " . $$data{hrsp_2xx} . "\n"; print " Responses: 3xx : " . $$data{hrsp_3xx} . "\n"; print " Responses: 4xx : " . $$data{hrsp_4xx} . "\n"; print " Responses: 5xx : " . $$data{hrsp_5xx} . "\n"; } # Sends tracked values to zabbix server from a single node # Argument: key which is used to get the node sub send_data { my $zabbix_name = shift; my $data = shift; #$verbose and print "Sending data for zabbix name $zabbix_name. pxname: " . $$data{pxname} . ", svname: " . $$data{svname} . "\n"; send_data_item($zabbix_name, 'pxname', $$data{pxname}); send_data_item($zabbix_name, 'svname', $$data{svname}); send_data_item($zabbix_name, 'req_rate', $$data{req_rate}); send_data_item($zabbix_name, 'hrsp_1xx', $$data{hrsp_1xx}); send_data_item($zabbix_name, 'hrsp_2xx', $$data{hrsp_2xx}); send_data_item($zabbix_name, 'hrsp_3xx', $$data{hrsp_3xx}); send_data_item($zabbix_name, 'hrsp_4xx', $$data{hrsp_4xx}); send_data_item($zabbix_name, 'hrsp_5xx', $$data{hrsp_5xx}); send_data_item($zabbix_name, 'rate', $$data{rate}); send_data_item($zabbix_name, 'wretr', $$data{wretr}); send_data_item($zabbix_name, 'eresp', $$data{eresp}); send_data_item($zabbix_name, 'econ', $$data{econ}); send_data_item($zabbix_name, 'ereq', $$data{ereq}); send_data_item($zabbix_name, 'bin', $$data{bin}); send_data_item($zabbix_name, 'bout', $$data{bout}); send_data_item($zabbix_name, 'stot', $$data{stot}); send_data_item($zabbix_name, 'smax', $$data{smax}); send_data_item($zabbix_name, 'scur', $$data{scur}); } # Send a single data item to zabbix server. # Argument: server/host/node name in zabbix # Argument: name of the parameter (like svname, bin, bout etc) # Argument: value/data sub send_data_item { my $zabbix_name = shift; my $param = shift; my $value = shift; if ($value eq "") { return; } my $var = 'haproxy.' . $param; my $cmd = "$zabbix_sender_path -z $zabbix_server -p $zabbix_port -s \"$zabbix_name\" -k $var -o $value"; $debug and print "Command: $cmd\n"; if (!$just_test) { `$cmd`; } } sub parse_line { my $line = shift; chomp $line; my @raw = split(/,/, $line); my %data = (); my $i = 0; foreach $key (split(/,/, "pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,hrsp_1xx,hrsp_2xx,hrsp_3xx,hrsp_4xx,hrsp_5xx,hrsp_other,hanafail,req_rate,req_rate_max,req_tot,cli_abrt,srv_abrt")) { my $value = @raw[$i++]; $data{$key} = $value; } return \%data; } sub parse_haproxy_conf() { my $filename = shift; open (FILE, $filename) or die("Could not open haproxy config file at $filename"); while (<FILE>) { my $line = $_; if ($line =~ /^(?:frontend|listen)[[:space:]]+([^[:space:]]+).+#.*@zabbix_frontend\((.+)\)/) { $debug and print "found frontend mapping $1 to $2\n"; $track_frontends{$1} = $2; } if ($line =~ /server[[:space:]]+([^[:space:]]+).+#.*@zabbix_server\((.+)\)/) { $debug and print "found server mapping $1 to $2\n"; $track_servers{$1} = $2; } } }
1c0b146f42bf0a63fbe60a45dffb8fb435c94b9d
[ "Perl" ]
1
Perl
garo/zabbix_haproxy
fae4bbe4d68930831a773de5f005cdeb24864800
28a6e8d2cd13818938a89cbd7cce0f80c63ea635
refs/heads/main
<file_sep>import random word_bank = ['bunny', 'hello', 'onomatopoeia', 'periodt'] def hangman_game(attempts): word = random.choice(word_bank) print('🎮 START ... 🎉🎉') guesses = '' wrong_guesses = 0 correct_guesses = 0 turns = attempts while turns > 0: guess = str(input("Enter guess:")) guesses += guess print(word) # print([c for c in guesses if c in word]) # print('wrong', [c for c in guesses if c not in word]) correct = [c if c in guesses else '-' for c in word] print() print('👉', ''.join(correct)) print() if guess in word: print('✔. # turns left: ', turns) # correct_guesses = len([[c for c in guesses if c in word]]) correct_guesses += 1 if guess not in word: turns -= 1 print('❌. # turns left: ', turns) # wrong_guesses = len([c for c in guesses if c not in word]) wrong_guesses += 1 if word == ''.join(correct): print('🎉🎉🎉 YAY') break if turns == 0: return "💀💀💀 TRY AGAIN" print('HANGMAN') attempts = int(input("# Wrong guesses you want:")) print(hangman_game(attempts))
18e8638e8903890326f2f29be8f598433886069e
[ "Python" ]
1
Python
ruvvet/hman_challenge
14b0b22c9a4d8f248c3e5cf2a48062cb15ece4fd
9c42a7be4854ef141bf65cb7597fc36f522e623f
refs/heads/master
<file_sep># gnu-gdb-xpack A binary xPack with GNU GDB.
a409978cab0095121c4c2d14362b0b00ffbb611f
[ "Markdown" ]
1
Markdown
316792668/gnu-gdb-xpack
c2c08d8b83f88907a8a609c66402bea4908a40e2
e525a5f3daf740d9a9a48fb1dcc4f0f1677eab2a
refs/heads/master
<file_sep># BC15-WaveRelease2 BC Wave 2 Release development This is for the development purpose only You can check in and check out the code as and when you need, Yes offcourse and this has been tested sucessfully.
fa8433cc6ce9398df32f900607107fa42aa89e14
[ "Markdown" ]
1
Markdown
subhashatCBR/BC15-WaveRelease2
af6e57c4a38d08f36ddf4fd1201cae96f8ae3c6f
82ed526817a742180a97eddfdf9fc23b2aa5ff83
refs/heads/master
<repo_name>armstrong0919/VRGame_RTS<file_sep>/Assets/_Script/UnitStates/Unit_StateManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IMoveable { void Set_MoveTarget(Vector3 target_pos); } public class Unit_StateManager : MonoBehaviour { public UnitProperties UnitProperties; [HideInInspector] public Vector3 TargetPosition; Base_UnitState currentstatus; UnitState_Retarget _retarget; public UnitState_Retarget Get_RetargetState { get { return _retarget; } } UnitState_Move _move; public UnitState_Move Get_MoveState { get { return _move; } } UnitState_Idle _idle; public UnitState_Idle Get_IdleState { get { return _idle; } } private void Start() { _retarget = new UnitState_Retarget(this); _move = new UnitState_Move(this); _idle = new UnitState_Idle(this); currentstatus = _idle; } public void Update() { currentstatus.UpdateState(); } public void To_State(Base_UnitState nextstate) { Debug.Log(currentstatus.GetType() + ":" + nextstate.GetType()); currentstatus.EndState(); currentstatus = nextstate; currentstatus.StartState(); } public void Set_MoveTarget(Vector3 target_pos) { TargetPosition = target_pos; To_State(Get_RetargetState); } } <file_sep>/Assets/_Script/UnitStates/Base_UnitState.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class Base_UnitState { protected Unit_StateManager Owner; public Base_UnitState(Unit_StateManager _unit_ower) { Owner = _unit_ower; } public abstract void StartState(); public abstract void UpdateState(); public abstract void EndState(); } <file_sep>/Assets/_Script/UnitStates/UnitState_Retarget.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class UnitState_Retarget : Base_UnitState { float timer; float dist; public UnitState_Retarget(Unit_StateManager _input_owner) : base(_input_owner) { } public override void EndState() { } Vector3 direction; Quaternion target_rot; float angle; public override void StartState() { timer = 0.0f; } public override void UpdateState() { Owner.transform.Translate(0, 0, Owner.UnitProperties.MovementSpeed * Time.deltaTime); timer += Time.deltaTime * Owner.UnitProperties.RotationSpeed; direction = Owner.TargetPosition - Owner.transform.position; target_rot = Quaternion.LookRotation(direction); Owner.transform.rotation = Quaternion.Lerp(Owner.transform.rotation, target_rot, timer); //Owner.transform.rotation = Quaternion.RotateTowards(Owner.transform.rotation, target_rot, Owner.UnitProperties.RotationSpeed * direction.magnitude * 2); if (target_rot == Owner.transform.rotation) Owner.To_State(Owner.Get_MoveState); if(Vector3.Distance(Owner.transform.position, Owner.TargetPosition) < Owner.transform.localScale.x / 2) Owner.To_State(Owner.Get_IdleState); } }<file_sep>/Assets/_Script/UnitStates/UnitState_Idle.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class UnitState_Idle : Base_UnitState { public UnitState_Idle(Unit_StateManager _input_owner) : base(_input_owner) { } public override void EndState() { } public override void StartState() { } public override void UpdateState() { } }<file_sep>/Assets/_Script/SetDestination.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using OVR; public abstract class DestinationPointer { protected SetDestination _dest; public DestinationPointer(SetDestination _destination) { _dest = _destination; } public abstract Vector3 SetPointer(); public abstract void UpdatePointer(); } public class BasicPointer : DestinationPointer { public BasicPointer(SetDestination _destination ) : base(_destination) { } public override Vector3 SetPointer() { return _dest.ControlObj.position; } public override void UpdatePointer() { #if UNITY_EDITOR if (Input.GetKeyDown(KeyCode.Space)) _dest.Send_MoveOrder(); #endif if(OVRInput.GetDown( OVRInput.Button.SecondaryIndexTrigger)) _dest.Send_MoveOrder(); } } public class ExtensionPointer : DestinationPointer { public float PressSpeed = 3.0f; public ExtensionPointer(SetDestination _destination) : base(_destination) { } public override Vector3 SetPointer() { return destination; } float dist_extend; Vector3 destination; public override void UpdatePointer() { #if UNITY_EDITOR if (Input.GetKey(KeyCode.Space)) { dist_extend += Time.deltaTime * PressSpeed; destination = _dest.ControlObj.TransformPoint(0,0,dist_extend); _dest.DebugObj.position = destination; } if(Input.GetKeyUp(KeyCode.Space)) _dest.Send_MoveOrder(); #endif if (OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger)) { dist_extend += Time.deltaTime * PressSpeed; destination = _dest.ControlObj.TransformPoint(0, 0, dist_extend); _dest.DebugObj.position = destination; } if (OVRInput.GetUp(OVRInput.Button.SecondaryIndexTrigger)) { _dest.Send_MoveOrder(); destination = Vector3.zero; dist_extend = 0.0f; } } } public class TwoStepPointer : DestinationPointer { bool has_hit; Vector3 return_val; Vector3 first_hit_point; public TwoStepPointer(SetDestination _destination) : base(_destination) { } public override Vector3 SetPointer() { return return_val; } public override void UpdatePointer() { #if UNITY_EDITOR if(Input.GetKeyDown(KeyCode.Space)) { RaycastHit hit; Ray new_ray = new Ray(_dest.ControlObj.position, _dest.ControlObj.forward); if (Physics.Raycast(new_ray,out hit)) { if (hit.collider.gameObject == HorizontalFloor.Singleton.gameObject) { first_hit_point = hit.point; _dest.DebugObj.position = first_hit_point; has_hit = true; } } } if(Input.GetKey(KeyCode.Space)) { Vector3 hitpoint_noheight = new Vector3(first_hit_point.x, 0, first_hit_point.z); Vector3 controller_noheight = new Vector3(_dest.ControlObj.position.x, 0, _dest.ControlObj.position.z); float _distance = Vector3.Distance(hitpoint_noheight, controller_noheight); float euler_y = _dest.ControlObj.eulerAngles.x; float rad = euler_y * Mathf.Deg2Rad; float height = euler_y > 0 ? Mathf.Tan(rad) * _distance * -1 : Mathf.Tan(rad) * _distance; Debug.Log(_distance + ":" + euler_y + ":" + height + ":" + _dest.ControlObj.position.y); return_val = new Vector3(first_hit_point.x, _dest.ControlObj.position.y + height, first_hit_point.z); _dest.DebugObj.position = return_val; //return_val = new Vector3(first_hit_point.x, _dest.DestinationObj.position.y, first_hit_point.z); } if (Input.GetKeyUp(KeyCode.Space) && has_hit) { _dest.DebugObj.position = return_val; _dest.Send_MoveOrder(); has_hit = false; } #endif if (OVRInput.GetDown(OVRInput.Button.SecondaryIndexTrigger)) { RaycastHit hit; Ray new_ray = new Ray(_dest.ControlObj.position, _dest.ControlObj.forward); if (Physics.Raycast(new_ray, out hit)) { if (hit.collider.gameObject == HorizontalFloor.Singleton.gameObject) { first_hit_point = hit.point; _dest.DebugObj.position = first_hit_point; has_hit = true; } } } if (OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger)) { Vector3 hitpoint_noheight = new Vector3(first_hit_point.x, 0, first_hit_point.z); Vector3 controller_noheight = new Vector3(_dest.ControlObj.position.x, 0, _dest.ControlObj.position.z); float _distance = Vector3.Distance(hitpoint_noheight, controller_noheight); float euler_y = _dest.ControlObj.eulerAngles.x; float rad = euler_y * Mathf.Deg2Rad; float height = euler_y > 0 ? Mathf.Tan(rad) * _distance * -1 : Mathf.Tan(rad) * _distance; Debug.Log(_distance + ":" + euler_y + ":" + height + ":" + _dest.ControlObj.position.y); return_val = new Vector3(first_hit_point.x, _dest.ControlObj.position.y + height, first_hit_point.z); _dest.DebugObj.position = return_val; //return_val = new Vector3(first_hit_point.x, _dest.DestinationObj.position.y, first_hit_point.z); } if (OVRInput.GetUp(OVRInput.Button.SecondaryIndexTrigger)) { _dest.DebugObj.position = return_val; _dest.Send_MoveOrder(); has_hit = false; } } } public class SetDestination : MonoBehaviour { public Transform ControlObj; public Transform DebugObj; private DestinationPointer _movecontrol; private void Start() { _movecontrol = new TwoStepPointer(this); } // Update is called once per frame void Update() { Debug.DrawLine(ControlObj.position, ControlObj.forward * 100, Color.green); _movecontrol.UpdatePointer(); } public void Send_MoveOrder() { foreach (Unit_StateManager _unit in OculusPlayerController.Singleton.Selected_MovableObject) _unit.Set_MoveTarget(_movecontrol.SetPointer()); } } <file_sep>/Assets/_Script/UnitStates/UnitState_Move.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class UnitState_Move : Base_UnitState { public UnitState_Move(Unit_StateManager _input_owner) : base(_input_owner) { } public override void EndState() { } public override void StartState() { } public override void UpdateState() { Owner.transform.Translate(0, 0, Owner.UnitProperties.MovementSpeed * Time.deltaTime); Vector3 _relative_pos = Owner.transform.InverseTransformPoint( Owner.TargetPosition); if (_relative_pos.z < 0) Owner.To_State(Owner.Get_IdleState); } } <file_sep>/Assets/_Script/UnitProperties.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class UnitProperties { public float MovementSpeed; public float RotationSpeed; }
6f529e99515e2a168d664bed9c5b68dcc7b71cb7
[ "C#" ]
7
C#
armstrong0919/VRGame_RTS
1bd1d9f2c09ff8851395280ad2c40be66cbe1d33
44ecfe282bc9db21dfddb0e16b824505c1278a32
refs/heads/master
<file_sep>@font-face { font-family: 'Montserrat'; font-style: normal; font-weight: 400; src: local('Montserrat Regular'), local('Montserrat-Regular'), url('../fonts/montserrat-v14-latin-regular.woff2') format('woff2'), url('../fonts/montserrat-v14-latin-regular.woff') format('woff'); } @font-face { font-family: 'Montserrat'; font-style: normal; font-weight: 700; src: local('Montserrat Bold'), local('Montserrat-Bold'), url('../fonts/montserrat-v14-latin-700.woff2') format('woff2'), url('../fonts/montserrat-v14-latin-700.woff') format('woff'); } @font-face { font-family: 'Roboto'; font-style: italic; font-weight: 300; src: local('Roboto Light Italic'), local('Roboto-LightItalic'), url('../fonts/roboto-v20-latin-300italic.woff2') format('woff2'), url('../fonts/roboto-v20-latin-300italic.woff') format('woff'); } @font-face { font-family: 'Roboto'; font-style: normal; font-weight: 400; src: local('Roboto'), local('Roboto-Regular'), url('../fonts/roboto-v20-latin-regular.woff2') format('woff2'), url('../fonts/roboto-v20-latin-regular.woff') format('woff'); } @font-face { font-family: 'Kaushan Script'; font-style: normal; font-weight: 400; src: url('../fonts/kaushan-script-v8-latin-regular.eot'); src: local('Kaushan Script'), local('KaushanScript-Regular'), url('../fonts/kaushan-script-v8-latin-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/kaushan-script-v8-latin-regular.woff2') format('woff2'), url('../fonts/kaushan-script-v8-latin-regular.woff') format('woff'), url('../fonts/kaushan-script-v8-latin-regular.ttf') format('truetype'), url('../fonts/kaushan-script-v8-latin-regular.svg#KaushanScript') format('svg'); } body, body * { margin: 0px; padding: 0px; } ul,ol{ list-style-type: none; } .main-wrapper{ width:1200px; margin:0 auto; } .header{ min-height: 1000px; background-image: -webkit-gradient(linear,left bottom, left top,from(rgba(251,227,137,0.9)) ,to(rgba(243,129,129,0.9)) ), url("../img/bg.jpg"); background-image: -o-linear-gradient(bottom,rgba(251,227,137,0.9) ,rgba(243,129,129,0.9) ), url("../img/bg.jpg"); background-image: linear-gradient(0deg,rgba(251,227,137,0.9) ,rgba(243,129,129,0.9) ), url("../img/bg.jpg"); background-size: cover; } @media(-webkit-min-device-pixel-ratio:2), (-o-min-device-pixel-ratio:2/1), (min-resolution:192dpi){ .header{ background-image: -webkit-gradient(linear,left bottom, left top,from(rgba(251,227,137,0.9)) ,to(rgba(243,129,129,0.9)) ), url("../img/bg@2x.jpg"); background-image: -o-linear-gradient(bottom,rgba(251,227,137,0.9) ,rgba(243,129,129,0.9) ), url("../img/bg@2x.jpg"); background-image: linear-gradient(0deg,rgba(251,227,137,0.9) ,rgba(243,129,129,0.9) ), url("../img/bg@2x.jpg"); } } .navigation{ display: -webkit-box; display: -ms-flexbox; display: flex; min-height:50px; -webkit-box-pack:justify; -ms-flex-pack:justify; justify-content:space-between; -webkit-box-align: baseline; -ms-flex-align: baseline; align-items: baseline; } .header__navigation-pos{ margin-bottom: 120px; padding-top: 20px; } .logo{ display:block; font-size: 30px; color: #ffffff; font-family: "Montserrat"; font-weight: 700; } .navigation__menu{ display: -webkit-box; display: -ms-flexbox; display: flex; } .main-menu{ display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack:justify; -ms-flex-pack:justify; justify-content:space-between; width: 480px; margin-right: 50px; } .main-menu__item{ font-size: 14px; font-family: "Montserrat"; font-weight: 400; text-align: center; text-transform: uppercase; padding-bottom: 10px; border-bottom: 3px solid rgba(252, 227, 138, 0); -webkit-transition: border 0.2s linear ; -o-transition: border 0.2s linear ; transition: border 0.2s linear ; } .main-menu__item:hover{ border-bottom: 3px solid rgba(252, 227, 138, 1); } .main-menu__link:hover{ color: #fce38a; } .main-menu__link{ text-decoration: none; color: #ffffff; } .add-search-menu{ display: -webkit-box; display: -ms-flexbox; display: flex; width: 80px; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; } .add-search-menu__item{ width: 18px; height: 18px; } .button-cart{ border: none; background: none; } .add-search-menu__item{ fill: #ffffff; } .add-search-menu__item:hover{ fill:#fce38a; cursor: pointer; } .header__title{ width: 820px; font-size: 150px; line-height: 140px; color: #ffffff; font-family: "Montserrat"; font-weight: 700; text-align: center; text-transform: uppercase; margin: 0 auto; letter-spacing: -5.4px; margin-bottom: 112px; } .header__pre-title{ font-size: 72px; color: #ffffff; font-family: "Kaushan Script"; font-weight: 400; text-align: center; display: block; text-transform: none; letter-spacing:0.2px; margin-bottom: 8px; } .load-more{ width: 160px; height: 40px; background-color: rgba(0,0,0,0); border: 3px solid #ffffff; display: block; margin: 0 auto; font-size: 14px; color: #ffffff; font-family: "Montserrat"; font-weight: 700; text-align: center; text-transform: uppercase; } .load-more:hover{ cursor: pointer; border: 3px solid #f38181; color: #f38181; } .main-section{ padding-top: 40px; } .main-title_pre{ display: block; font-size: 24px; color: #333333; font-family: "Kaushan Script"; font-weight: 400; text-align: center; margin-bottom: 10px; text-transform: none; } .main-title{ text-align: center; margin-bottom:60px; font-size: 30px; color: #333333; font-family: "Montserrat"; font-weight: 700; text-transform: uppercase; } .main-title::after{ display: block; content:''; width: 60px; height: 3px; background-color: #f38181; margin: 0 auto; margin-top:34px; } .servises{ padding: 40px 10px; } .servise-list{ display:-webkit-box; display:-ms-flexbox; display:flex; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; list-style: none; -ms-flex-wrap: wrap; flex-wrap: wrap; } .servise-list__item{ -webkit-box-sizing: border-box; box-sizing: border-box; display: block; width:382px; padding-left: 82px; position:relative; } .servise-list__item:not(:nth-last-of-type(-n+3)){ margin-bottom:92px; } .servise-list__title{ text-transform: uppercase; font-size: 14px; color: #333333; font-family: "Montserrat"; font-weight: 400; margin-bottom:15px; } .servise-list__descr{ font-size: 15px; line-height: 24px; color: #999999; font-family: "Roboto"; font-weight: 400; } .servise-list__item:before{ display:block; content:""; width:32px; height:32px; position: absolute; left:22px; top:5px; background-position: center; background-repeat: no-repeat; } .servise-list__item_icon-clock:before{ background-image: url("../img/icon-servises/icon-clock.svg"); } .servise-list__item_icon-wave:before{ background-image: url("../img/icon-servises/icon-wave.svg"); } .servise-list__item_icon-monitor:before{ background-image: url("../img/icon-servises/icon-monitor.svg"); } .servise-list__item_icon-book:before{ background-image: url("../img/icon-servises/icon-book.svg"); } .servise-list__item_icon-house:before{ background-image: url("../img/icon-servises/icon-house.svg"); } .servise-list__item_icon-focus:before{ background-image: url("../img/icon-servises/icon-focus.svg"); } .team{ padding-bottom:56px; } .team__description{ width:980px; margin:0 auto; font-size: 15px; line-height: 24px; color: #999999; font-family: "Roboto"; font-weight: 400; text-align: center; margin-bottom:74px; } .team-list{ list-style-type: none; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack:justify; -ms-flex-pack:justify; justify-content:space-between; } .team-list__photo{ width:380px; height:470px; margin-bottom:30px; } .team-list__item{ position: relative; font-size: 14px; width:380px; color: #333333; font-family: "Montserrat"; font-weight: 400; text-align: center; text-transform: uppercase; margin-bottom:13px; } .team-list__item-position{ position:relative; font-size: 15px; line-height: 24px; color: #999999; font-family: "Roboto"; font-weight: 300; font-style: italic; text-align: center; } .team-list__overlay{ position: absolute; width:380px; height:470px; /* background-color: #f38181; */ left:0px; top:0px; opacity: 0; -webkit-transition: all 0.2s linear; -o-transition: all 0.2s linear; transition: all 0.2s linear; } .team-list__overlay_pavel{ background-image: -webkit-gradient(linear,left top, left bottom,from(rgba(243,129,129,0.9)),to(rgba(251,227,137,0.9))), url("../img/team-pavel.png"); background-image: -o-linear-gradient(rgba(243,129,129,0.9),rgba(251,227,137,0.9)), url("../img/team-pavel.png"); background-image: linear-gradient(rgba(243,129,129,0.9),rgba(251,227,137,0.9)), url("../img/team-pavel.png"); } .team-list__overlay_artem{ background-image: -webkit-gradient(linear,left top, left bottom,from(rgba(243,129,129,0.9)),to(rgba(251,227,137,0.9))), url("../img/team-artem.png"); background-image: -o-linear-gradient(rgba(243,129,129,0.9),rgba(251,227,137,0.9)), url("../img/team-artem.png"); background-image: linear-gradient(rgba(243,129,129,0.9),rgba(251,227,137,0.9)), url("../img/team-artem.png"); } .team-list__overlay_igor{ background-image: -webkit-gradient(linear,left top, left bottom,from(rgba(243,129,129,0.9)),to(rgba(251,227,137,0.9))), url("../img/team-igor.png"); background-image: -o-linear-gradient(rgba(243,129,129,0.9),rgba(251,227,137,0.9)), url("../img/team-igor.png"); background-image: linear-gradient(rgba(243,129,129,0.9),rgba(251,227,137,0.9)), url("../img/team-igor.png"); } .team-list__overlay:hover{ left:-10px; top:-10px; -webkit-box-shadow: 10px 10px 0 #95e1d3; box-shadow: 10px 10px 0 #95e1d3; opacity: 1; } .social-list{ height: inherit; list-style-type: none; display:-webkit-box; display:-ms-flexbox; display:flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .social-list__link{ display: -webkit-box; display: -ms-flexbox; display: flex; width: 56px; height: 56px; background-color: #fce38a; margin-right: 1px; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-transition: background-color 0.2s linear; -o-transition: background-color 0.2s linear; transition: background-color 0.2s linear; } .social-list__link:hover{ background-color: #f38181; fill:#fce38a; } .social-list__icon{ width: 26px; height: 26px; fill:#f38181; } .social-list__link:hover .social-list__icon{ fill:#ffffff; } .footer{ display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; -webkit-box-align: center; -ms-flex-align: center; align-items: center; min-height: 62px; border-top: 1px solid #e5e5e5;; } .form-imail{ display: -webkit-box; display: -ms-flexbox; display: flex; } .copyright{ font-size: 14px; color: #333333; font-family: "Montserrat"; font-weight: 400; } .copyright span{ color:#f38181; } .form-imail__input{ width: 230px; height: 40px; border: 1px solid #e7e7e7; -webkit-box-sizing: border-box; box-sizing: border-box; padding-left: 12px; } .form-imail__input::-webkit-input-placeholder{ font-size: 15px; line-height: 24px; color: #cccccc; font-family: "Roboto"; font-weight: 300; font-style: italic; } .form-imail__input::-moz-placeholder{ font-size: 15px; line-height: 24px; color: #cccccc; font-family: "Roboto"; font-weight: 300; font-style: italic; } .form-imail__input:-ms-input-placeholder{ font-size: 15px; line-height: 24px; color: #cccccc; font-family: "Roboto"; font-weight: 300; font-style: italic; } .form-imail__input::-ms-input-placeholder{ font-size: 15px; line-height: 24px; color: #cccccc; font-family: "Roboto"; font-weight: 300; font-style: italic; } .form-imail__input::placeholder{ font-size: 15px; line-height: 24px; color: #cccccc; font-family: "Roboto"; font-weight: 300; font-style: italic; } .form-imail__button{ width: 150px; height: 40px; background-color: #95e1d3; font-size: 14px; color: #ffffff; font-family: "Montserrat"; font-weight: 700; text-align: center; text-transform: uppercase; border:0; } .form-imail__button:hover{ cursor:pointer; }
2cb5e343e287b4424a496a9de41ffe373b962b56
[ "CSS" ]
1
CSS
LysakArtem/goit-html-css-module10
9da581eb40ba586027b264af9e16ba70fa286a51
86ebcf1f57c9e54c689a97c94801e04dc2020478
refs/heads/master
<repo_name>lightyblog/django-lightyblog<file_sep>/lightyblog/admin.py # -*- coding: utf-8 -*- #///////////////////////////////////////////////////////////////// from django.contrib import admin #----------------------------------------------------------------- from lightyblog.models import Article #///////////////////////////////////////////////////////////////// # Enalbed for easy debugging, while coding class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'message', 'is_approved', 'created') ordering = ('-created',) admin.site.register(Article, ArticleAdmin) <file_sep>/lightyblog/templates/adminpanel/delete.html {% extends "theme.html" %} {% load i18n %} {% block head %} {% if success %} <script type="text/javascript">setTimeout(function() {window.location = "{% url 'admin:index'%}list-article/";}, 3000);</script> {% endif %} {% endblock %} {% block adminIndex %} <h2 class="dark-grey"> <img src="/static/img/face.png" alt=""/> Lightyblog &#187 <span class="magenta">{{post.title}}</span> &#187 <span class="light-red">{% trans 'Deleted' %}</span> </h2> <hr/> {% if success %} <div class="alert alert-danger center"> <img src="/static/img/yellow.png" alt=""/> <br/><br/> {% trans 'The article was deleted successfully!' %} </div> {% endif %} {% endblock %} <file_sep>/lightyblog/templates/theme.html {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="author" content="<NAME>"> <link rel="shortcut icon" href="favicon.ico"> <title>Lightyblog &#187; {% block themeTitle %} {% endblock %} </title> <meta name="description" content="{% block themeDescription %} {% endblock %}"> <link rel="stylesheet" href="/static/css/bootstrap.min.css" type="text/css"/> <link rel="stylesheet" href="/static/css/lightyblog.css" type="text/css"/> <script src="/static/js/jquery.min.js"></script> {% block head %}{% endblock %} </head> <body> <div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'lightyblog.views.index' %}"> <span class="light-yellow">Lightyblog</span> &#187; <span class="white">{% trans 'A minimalistic demo-app' %}</span> </a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="{% url 'lightyblog.views.create' %}"><span class="light-green">{% trans 'Create article' %}</span></a></li> <li><a href="{% url 'lightyblog.views.list' %}"><span class="magenta">{% trans 'My articles' %}</span></a></li> {% endif %} <li><a href="{% url 'lightyblog.views.latest' %}"><span class="light-blue">{% trans 'Published' %}</span></a></li> <li><a href="{% url 'lightyblog.views.index' %}#/the-assignment">{% trans 'The assignment' %}</a></li> <li><a href="{% url 'lightyblog.views.index' %}#/the-approach">{% trans 'The approach' %}</a></li> <li><a href="{% url 'lightyblog.views.index' %}#/web-goodies">{% trans 'Web goodies' %}</a></li> {% if user.is_authenticated %} <li><a href="{% url 'admin:index' %}list-article/"><span class="light-yellow">@{{user.username}}</span></a></li> <li><a href="{% url 'admin:logout' %}"><span class="light-red">{% trans 'Logout' %}</span></a></li> {% else %} <li><a href="{% url 'lightyblog.views.index' %}#/the-author">{% trans 'Author' %}</a></li> <li><a href="{% url 'django.contrib.auth.views.login' %}"><span class="light-green">{% trans 'Login' %}</span></a></li> {% endif %} </ul> </div> </div> </div> {% block presentationIndex %}{% endblock %} <div class="container"> {% block coreIndex %}{% endblock %} {% block adminIndex %}{% endblock %} {% block loginIndex %}{% endblock %} </div> <div class="footer"> <div class="foo-container"> <br/><p>Lightyblog &copy; 2014</p> </div> </div> </body> </html> <file_sep>/lightyblog/templates/404.html {% extends "theme.html" %} {% load i18n %} {% block head %}{% endblock %} {% block coreIndex %} <p class="center lead"> <img src="/static/img/orange.png"/> <br/> <span class="black">{% trans 'Sorry, page was not found!' %}</span> </p> {% endblock %} <file_sep>/lightyblog/urls.py #///////////////////////////////////////////////////////////////// from django.conf.urls import patterns, include, url #///////////////////////////////////////////////////////////////// # Django Admin from django.contrib import admin admin.autodiscover() #///////////////////////////////////////////////////////////////// # Lightyblog - App urls urlpatterns = patterns('', url(r'^$', 'lightyblog.views.index',), url(r'^article/(?P<articleid>\d+)/$', 'lightyblog.views.article'), url(r'^latest-article/$', 'lightyblog.views.latest'), url(r'^admin/list-article/', 'lightyblog.views.list',), url(r'^admin/create-article/', 'lightyblog.views.create',), url(r'^admin/edit-article/(?P<articleid>\d+)/$', 'lightyblog.views.edit',), url(r'^admin/delete-article/(?P<articleid>\d+)/$', 'lightyblog.views.delete',), ) #///////////////////////////////////////////////////////////////// # Django Admin urls urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^login/', 'django.contrib.auth.views.login'), ) <file_sep>/lightyblog/forms.py # -*- coding: utf-8 -*- import datetime #///////////////////////////////////////////////////////////////// from django import forms from django.conf import settings from django.utils.timezone import utc #----------------------------------------------------------------- from lightyblog.models import Article #///////////////////////////////////////////////////////////////// class ArticleForm(forms.Form): """ Very basic form that will allow creation of new articles. """ # Article details # Captcha is recommended for avoiding muplitple entries being posted. title = forms.CharField(max_length=70, min_length=10, required=True) message = forms.CharField(widget=forms.Textarea) is_approved = forms.BooleanField(required=False) #///////////////////////////////////////////////////////////////// def save_article(us,ti,me,ap): """ Basic method to save a new article. Error handling can be optimized to be more, user friendly. Logging for debugging. """ # Create django date for storing article cr = datetime.datetime.utcnow().replace(tzinfo=utc) # Advance error handing would be advised here. try: msg = Article(owner=us, title=ti, message=me, is_approved=ap, created=cr) msg.save() return True except: return False #///////////////////////////////////////////////////////////////// # Returns article's existing details def get_article(articleid): """ Basic method to get data from database for editing an article. Error handling can be optimized further. Logging for debugging. """ # Initialize form = None # Get the article object based on id. try: article = Article.objects.get(id=articleid) # Generate form with database data form = ArticleForm(initial = { 'title': article.title, 'message': article.message, 'is_approved': article.is_approved, }) except: # Loggin + correct error handling should be added. pass return form #///////////////////////////////////////////////////////////////// # Update the article. def update_article(article,ti,me,ap): """ Basic method for applying changes / updating an article. Error handling can be optimized further. Logging for debugging. """ # Create django date for uddating article up = datetime.datetime.utcnow().replace(tzinfo=utc) # Apply changes and save try: article.title = ti article.message = me article.is_approved = ap article.created = up article.save() return True except: # Loggin + correct error handling should be added. return False #///////////////////////////////////////////////////////////////// # Delete the article. def delete_article(article): """ Basic method for deleting an article. Logging for debugging. """ try: article.delete() return True except: # Loggin + correct error handling should be added. return False <file_sep>/lightyblog/settings.py #///////////////////////////////////////////////////////////////// import os #----------------------------------------------------------------- from djangoappengine.settings_base import * #----------------------------------------------------------------- #///////////////////////////////////////////////////////////////// ADMINS = (('Lightyblog', '<EMAIL>'),) MANAGERS = ADMINS #///////////////////////////////////////////////////////////////// # Activate django-dbindexer for the default database DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': DATABASES['default']} AUTOLOAD_SITECONF = 'indexes' #///////////////////////////////////////////////////////////////// # Get project directories ROOT_DIR = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) #///////////////////////////////////////////////////////////////// # Login/Admin settings LOGIN_REDIRECT_URL = '/admin/list-article' LOGIN_URL = '/login/' FORCE_SCRIPT_NAME = '' #///////////////////////////////////////////////////////////////// ALLOWED_HOSTS = ['high-hue-532.appspot.com'] TIME_ZONE = 'Europe/London' #///////////////////////////////////////////////////////////////// LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True USE_TZ = False SITE_ID = 1 #///////////////////////////////////////////////////////////////// MEDIA_ROOT = '' MEDIA_URL = '' #///////////////////////////////////////////////////////////////// # Static files and paths STATIC_ROOT = PROJECT_DIR + '/static/' STATIC_URL = '/static/' STATICFILES_DIRS = ( PROJECT_DIR + '/static/', ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) #///////////////////////////////////////////////////////////////// # Secret random key SECRET_KEY = '<KEY>' #///////////////////////////////////////////////////////////////// # Template loaders TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) #///////////////////////////////////////////////////////////////// # Middlewares MIDDLEWARE_CLASSES = ( # This loads the index definitions, so it has to come first 'autoload.middleware.AutoloadMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) #///////////////////////////////////////////////////////////////// ROOT_URLCONF = 'lightyblog.urls' #///////////////////////////////////////////////////////////////// # Template directories TEMPLATE_DIRS = ( PROJECT_DIR + '/templates/', ) #///////////////////////////////////////////////////////////////// # APPS INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', # 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'djangotoolbox', 'autoload', 'dbindexer', 'lightyblog', # djangoappengine should come last, so it can override a few manage.py commands 'djangoappengine', ) #///////////////////////////////////////////////////////////////// # logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } <file_sep>/README.md django-lightyblog ================= A django lightweight demo-app for running a minimalistic blog on google-app-engine Live demo ------------------------------------ Google App Engine: http://high-hue-532.appspot.com/ Username: <b>admin</b> | Password: <b><PASSWORD>> Web goodies used: <a href="http://getbootstrap.com/">Bootstrap 3.0 » templates</a> <br/> <a href="http://jmpressjs.github.io/jmpress.js/">jmpress » presentation</a> <br/> <a href="http://django-nonrel.org/">django-norel » collection of packages</a> <br/> Repo contains the full project folder, at it was pushed on the appspot.com for the demo. Screenshots ------------------------------------ ![Admin Listing Articles](https://github.com/lightyblog/django-lightyblog/blob/master/lightyblog/doc/screenshots/lightyblog-admin.png) ![Bootstrap Login](https://github.com/lightyblog/django-lightyblog/blob/master/lightyblog/doc/screenshots/lightyblog-login.png) ![Blog Published Articles](https://github.com/lightyblog/django-lightyblog/blob/master/lightyblog/doc/screenshots/lightyblog-articles.png) ![Editing Articles](https://github.com/lightyblog/django-lightyblog/blob/master/lightyblog/doc/screenshots/lightyblog-editing.png) <file_sep>/lightyblog/models.py # -*- coding: utf-8 -*- #///////////////////////////////////////////////////////////////// from django.db import models #----------------------------------------------------------------- from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ #///////////////////////////////////////////////////////////////// # Articles class Article(models.Model): """ Minimalistic class that models a blogging article post. Only very basic fields were added, since it is just PoC. """ # Relate each article with a user owner = models.ForeignKey(User, verbose_name = _(u'User'), related_name='article_owner') # Article basic information title = models.CharField(max_length=70, verbose_name = _(u'Title')) message = models.TextField(verbose_name = _(u'Article text')) created = models.DateField(verbose_name = _(u'Creation date'), auto_now_add=True) # Only approved posts will be visible is_approved = models.BooleanField(default=False, verbose_name = _(u'Approve articles')) # Some naming class Meta: verbose_name = _(u'Lightyblog articles') verbose_name_plural = _(u'Lightyblog articles') def __unicode__(self): return self.title <file_sep>/lightyblog/views.py # -*- coding: UTF-8 -*- #/////////////////////////////////////////////////// from django.shortcuts import render from django.http import Http404 from django.conf import settings from django.contrib.auth.decorators import login_required #--------------------------------------------------- from lightyblog.models import Article from lightyblog.forms import ArticleForm from lightyblog.forms import save_article, get_article from lightyblog.forms import delete_article, update_article #/////////////////////////////////////////////////// # The presentation link template def index(request): """ A view that was added only for presentation context, that aims to help the developers to understand the reason of creating the Lightyblog demo-app. """ return render(request, 'core/index.html') #/////////////////////////////////////////////////// # Preview of articles based on id, sidebar indexing def article(request, articleid): """ Articles view that returns the 10 latest articles. If an exception is raised, then it returns a 404 error (for now). Logging should be added in order to catch the exception errors. Preview item becomes, the chosen id. """ try: # Logic can be optimized, if it was production code (TODOs - use get(id) instead). articles = Article.objects.all().filter(is_approved=True).order_by('-created')[:10] preview = Article.objects.all().filter(id=articleid)[:1] return render(request, 'core/articles.html', { 'preview':preview, 'articles':articles },) except: raise Http404 #/////////////////////////////////////////////////// # Preview the latest article def latest(request): """ Articles view that returns the 10 latest articles. If an exception is raised, then it returns a 404 error (for now). Logging should be added in order to catch the exception errors. Preview item becomes, the 3 latest articles. """ try: articles = Article.objects.all().filter(is_approved=True).order_by('-created')[:10] preview = Article.objects.all().filter(is_approved=True).order_by('-created')[:6] return render(request, 'core/articles.html', { 'preview':preview, 'articles':articles },) except: # It should be logging instead (404 debugging reasons) raise Http404 #///////////////////////////////////////////////////////////////// @login_required def create(request): """ Custom view that create a new article. """ # Initialize title = message = '' is_approved = False # Create the article form form = ArticleForm() # Check for post request if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): # Getting User's Input title = form.cleaned_data['title'] message = form.cleaned_data['message'] is_approved = form.cleaned_data['is_approved'] # Save article success = save_article(request.user,title,message,is_approved) if success: return render(request, 'adminpanel/create.html', { 'form':form, 'success':success},) # Return initial form return render(request, 'adminpanel/create.html', {'form': form, }) #///////////////////////////////////////////////////////////////// @login_required def edit(request, articleid): """ Custom view that edits the article based on id. """ # Initialize post = form = None try: post = Article.objects.get(id=articleid) form = get_article(articleid) except: # It should be logging instead (debugging reasons) pass # The concept of restricting someone to edit, it not the owner # but get the article id by viewing the source. # Obviously, that's a fast way to do it if request.user.id != post.owner.id: raise Http404 # Check for post request if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): # Getting User's Input title = form.cleaned_data['title'] message = form.cleaned_data['message'] is_approved = form.cleaned_data['is_approved'] # Update article success = update_article(post,title,message,is_approved) if success: return render(request, 'adminpanel/edit.html', { 'form':form, 'post':post, 'success':success},) return render(request, 'adminpanel/edit.html', { 'form':form, 'post':post, }) #///////////////////////////////////////////////////////////////// @login_required def delete(request, articleid): """ Custom view that deletes the article based on id. Could add confirmation before deleting, but I just decided to keep it simple. """ # Initialize post = None success = False try: post = Article.objects.get(id=articleid) except: # It should be logging (debugging reasons) pass # The idea of restricting someone to edit, it not the owner # but get the article id by viewing the source. # Obviously, that's a fast way to do it. if request.user.id != post.owner.id: raise Http404 else: success = delete_article(post) return render(request,'adminpanel/delete.html', { 'post':post, 'success':success, }) #///////////////////////////////////////////////////////////////// @login_required def list(request): """ Custom view that lists all user's articles. """ try: posts = Article.objects.all().filter(owner__id=request.user.id) except: # It should be logging instead (404 debugging reasons) raise Http404 return render(request,'adminpanel/list.html', { 'posts':posts, }) <file_sep>/lightyblog/templates/adminpanel/list.html {% extends "theme.html" %} {% load i18n %} {% block head %}{% endblock %} {% block adminIndex %} <h2 class="dark-grey"> <img src="/static/img/face.png" alt=""/> Lightyblog &#187 <span class="magenta">{% trans 'My articles' %}</span> </h2> {% if posts %} <table class="table"><tbody> {% for post in posts %} <tr> <td class="center put-middle"> {{post.created}} </td> <td class="put-middle title"> <a href="{% url 'lightyblog.views.article' post.id %}"> {{post.title}} </a> </td> <td> <a href="{% url 'lightyblog.views.edit' post.id %}" class="btn btn-primary btn-block">{% trans 'Edit' %}</a> </td> <td> <a href="{% url 'lightyblog.views.delete' post.id %}" class="btn btn-danger btn-block">{% trans 'Delete' %}</a> </td> </tr> {% endfor %} </tbody></table> {% else %} <hr/> <p class="lead center blue"> {% trans 'You do not have any articles published!' %} <br/><br/> <img src="/static/img/yellow.png" alt=""/> </p> {% endif %} {% endblock %} <file_sep>/settings.py from lightyblog.settings import *
9e971ff79e2246aa1592e809b8b18601651e36cb
[ "Markdown", "HTML", "Python" ]
12
Markdown
lightyblog/django-lightyblog
d1d6e102b2835043f4f9dd1ff6001d20b895a430
ce7544a3198a376b23649698c66349b75600d2f4
refs/heads/main
<repo_name>AhYunCH/MusicInd.<file_sep>/login.php <!DOCTYPE html> <html> <?php $user = $_POST["username"]; $pw = $_POST["password"]; $username1 = "MARY"; $username2 = "PETER"; $password1 = "<PASSWORD>"; $password2 = "<PASSWORD>"; $log = 0; if ($user == "MARY" && $pw == "Aa123456" || $user == "PETER" && $pw == "Bb123456"){ echo "<h1><center> Login successful </center></h1>"; echo("<button onclick=\"location.href='MusicInd.html'\">Main Page</button>"); }else { echo "<h1> Login failed. Invalid username or password.</h1>"; echo("<button onclick=\"location.href='LoginPage.html'\">Login Page</button>"); } ?> </html>
208f41c53fe72ceddc7327f80cf2d5231ae3051d
[ "PHP" ]
1
PHP
AhYunCH/MusicInd.
29cb9256ad84a9f0bfd2c1da95d72e35839f5d92
af039136a4354875d6faac8aace80b7430ea41a8
refs/heads/master
<repo_name>BenitezAxel/portfolio<file_sep>/confirmacion_envio.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Contacto</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://getbootstrap.com/docs/4.5/dist/js/bootstrap.bundle.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:100,200,300,400,500,600,700,800,900&display=swap"> <link rel="stylesheet" href="css/fontawesome/css/all.min.css"> <link rel="stylesheet" href="css/fontawesome/css/fontawesome.min.css"> <link rel="stylesheet" href="css/estilos.css"> </head> <body> <header> <?php include_once("menu.php"); ?> </header> <section id="contacto"> <div class="container"> <div class="row mb-5"> <div class="col-12 mb-5 py-5"> <h1>¡Gracias por <br>contactarte!</h1> <div class="row mb-5"> <div class="col-5 mb-5 py-4"> <h2>Te responderemos a la brevedad</h2> </div> </div> </div> </div> </div> </section> <?php include_once("footer.php"); ?> </body> </html><file_sep>/css/estilos.css body{ font-family: 'Montserrat', sans-serif; background-color: #eeeeee; } nav{ width: max-content; margin: auto; } nav .nav-link{ color: #4b4b4b; text-transform:uppercase; font-size: 20px; text-align: center; margin-top: 15px; margin-left: 10px; } nav .nav-link:hover{ color: #0056b3; text-decoration: none; } nav .active:hover{ text-decoration: none; } nav .active{ font-weight: bold; text-decoration: underline; } nav .nav-item{ width: 250px; } h1{ font-size: 55px; font-weight: 800; } h2{ font-size: 30px; font-weight: 700; } .btn{ background-color: black !important; color: #eeeeee; border-radius: 0; transition: color .15s; display: inline-block; line-height: 1.5; text-align: center; } .btn:hover{ color: black; background-color: white !important; border: 1px solid black; } .form-control{ background-color:#eeeeee; border: 0; border-bottom: 1px solid #4b4b4b; border-radius: 0; font-size: 18px; } footer{ background-color: white; } footer a{ color: black; text-decoration: underline; } footer i{ font-size: 35px; border: 1px solid; height: 55px; width: 55px; text-align: center; padding: 8px 0 0 0; border-radius: 80px; margin: 0 15px; } .text-left{ text-decoration: underline; font-weight: bold; } .text-right a{ font-weight: bold; } #proyectos h2{ font-size: 22px; font-weight: 500; margin-block-start: 1em; margin-block-end: 1em; margin-inline-start: 0px; margin-inline-end: 0px; display: block; } #proyectos h3{ margin-block-start: 1em; margin-block-end: 1em; margin-inline-start: 0px; margin-inline-end: 0px; display: block; margin-bottom: .5rem; line-height: 1.2; } #proyectos p{ font-size: 17px; margin-block-start: 1em; margin-block-end: 1em; margin-inline-start: 0px; margin-inline-end: 0px; display: block; } #proyectos img{ height: 260px; width: 100%; } #proyectos .img-fluid{ max-width: 100%; } #proyectos .btn{ background-color: black; color: #eeeeee; border-radius: 0; transition: color .15s; display: inline-block; line-height: 1.5; text-align: center; } #proyectos .btn:hover{ color: black; background-color: white; border: 1px solid black; } #sobre-mi h2{ font-weight: 500; font-size: 22px; line-height: 40px; margin-bottom: .5rem; margin-block-start: 0.83em; margin-block-end: 0.83em; margin-inline-start: 0px; margin-inline-end: 0px; } #sobre-mi h1{ font-size: 55px; line-height: 40px; margin-block-start: 0.83em; margin-block-end: 0.83em; margin-inline-start: 0px; margin-inline-end: 0px; padding-bottom: 10px; } #sobre-mi .btn{ background-color: black; color: #eeeeee; border-radius: 0; transition: color .15s; display: inline-block; line-height: 1.5; text-align: center; } #sobre-mi .btn:hover{ color: black; background-color: white; border: 1px solid black; } #sobre-mi .img-circle{ margin: 1em auto; display: block; background-color: #fff; padding: 10px; border-radius: 50%; } #sobre-mi .img-fluid{ max-width: 100%; height: auto; } #sobre-mi i{ background-color: black; color: white; padding: 30px; font-size: 40px; } #sobre-mi .bg-white{ min-height: 300px; background-color: white !important; color: #212529; text-align: left; font-size: 1rem; font-weight: 400; line-height: 1.5; } #experiencia{ background-color: rgb(45, 45, 45); } #experiencia h2{ color: white; font-size: 45px; line-height: 1.2; margin-bottom: 30px; } #experiencia h3{ color: white; font-size: 20px; line-height: 1.2; margin-bottom: 50px; } #experiencia h4{ color: white; font-size: 20px; line-height: 1.2; margin-bottom: 50px; } #home{ background-image: url(../images/Fondos-06.png); background-repeat: repeat; background-size: 100%; height: 81vh; } #home .container-fluid{ width: 100%; padding-left: 15px; padding-right: 15px; margin-left: auto; margin-right: auto; } #home h2{ font-size: 22px; line-height: 40px; color: rgb(45, 45, 45); font-weight: 500; margin-top: 25px; } #home .btn{ background-color: black; color: #eeeeee; border-radius: 0; transition: color .15s; display: inline-block; line-height: 1.5; text-align: center; margin-top: 25px; } #home .btn:hover{ color: black; background-color: white; border: 1px solid black; } <file_sep>/sobre-mi.php <?php $pg = "sobremi"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sobre Mi</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://getbootstrap.com/docs/4.5/dist/js/bootstrap.bundle.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:100,200,300,400,500,600,700,800,900&display=swap"> <link rel="stylesheet" href="css/fontawesome/css/all.min.css"> <link rel="stylesheet" href="css/fontawesome/css/fontawesome.min.css"> <link rel="stylesheet" href="css/estilos.css"> </head> <body> <header> <?php include_once("menu.php"); ?> </header> <section id="sobre-mi"> <div class="container"> <div class="row mt-5"> <div class="col-sm-7 col-12"> <h1>Sobre mi</h1> <h2>Apasionado por la tecnología y gestión de proyectos. Soy una persona en constante movimiento esforzandome y aprendiendo sobre nuevas tecnologías, para ofrecer un mejor rendimiento en las diferentes tareas que se me presenten.</h2> <a href="" class="btn my-4" target="_blank">Descargar CV</a> </div> <div class="col-sm-3 col-9 mx-5"> <img src="images/perfil.jpg" alt="<NAME>" class="img-fluid img-circle"> </div> </div> <div class="row my-sm-4 my-3"> <div class="col-sm-6 col-12 px-2 my-2"> <div class="bg-white"> <div class="p-3"> <i class="fas fa-code"> </i> </div> <div class="row px-3"> <div class="col-12"> <h3>PROGRAMACION</h3> </div> </div> <div class="row p-3"> <div class="col-12"> <p>HTML, CSS, Bootstrap, C#.</p> </div> </div> </div> </div> <div class="col-sm-6 col-12 px-2 my-2"> <div class="bg-white"> <div class="p-3"> <i class="fas fa-database"> </i> </div> <div class="row px-3"> <div class="col-12"> <h3>BASE DE DATOS</h3> </div> </div> <div class="row p-3"> <div class="col-12"> <p>MySQL.</p> </div> </div> </div> </div> <div class="col-sm-6 col-12 px-2 my-2"> <div class="bg-white"> <div class="p-3"> <i class="fas fa-server"> </i> </div> <div class="row px-3"> <div class="col-12"> <h3>SERVIDORES</h3> </div> </div> <div class="row p-3"> <div class="col-12"> <p>XAMPP.</p> </div> </div> </div> </div> <div class="col-sm-6 col-12 px-2 my-2"> <div class="bg-white"> <div class="p-3"> <i class="fas fa-language"> </i> </div> <div class="row px-3"> <div class="col-12"> <h3>IDIOMAS</h3> </div> </div> <div class="row p-3"> <div class="col-12"> <p>INGLES - Principiante A1</p> <br> "ESPAÑOL - Nativo" </div> </div> </div> </div> <div class="col-sm-6 col-12 px-2 my-2"> <div class="bg-white"> <div class="p-3"> <i class="fas fa-window-restore"> </i> </div> <div class="row px-3"> <div class="col-12"> <h3>SOFTWARE</h3> </div> </div> <div class="row p-3"> <div class="col-12"> <p>GitHub, Visual Code, Sublime, Filezilla, SSH Putty, MySQL Workbench, Adobe Photoshop, MS Office, Google Docs. </p> </div> </div> </div> </div> <div class="col-sm-6 col-12 px-2 my-2"> <div class="bg-white"> <div class="p-3"> <i class="fas fa-puzzle-piece"> </i> </div> <div class="row px-3"> <div class="col-12"> <h3>HOBBIES</h3> </div> </div> <div class="row p-3"> <div class="col-12"> <p>Escuchar musica, Armado de PC.</p> </div> </div> </div> </div> </div> </section> <section id="experiencia"> <div class="container py-sm-5 py-4"> <div class="row"> <div class="col-12 py-4"> <h2>Experiencia Laboral</h2> </div> </div> <div class="row py-2"> <div class="col-12 col-sm-2"> <h3>2019 - 2020 -<br> La Rambla</h3> </div> <div class="col-12 col-sm-2"> <img src="images/rambla.jpg" alt="La Rambla" class="img-responsive py-3 py-sm-0" width="120" title="La Rambla"> </div> <div class="col-12 col-sm-8"> <h4>"Realice todo tipo de tareas relacionadas a la gastronomia, como limpieza del establecimiento, bachero, ayudante de cocina y delivery"</h4> </div> </div> </div> </div> </section> <?php include_once("footer.php"); ?> </body> </html><file_sep>/index.php <?php $pg ="inicio";?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Inicio</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://getbootstrap.com/docs/4.5/dist/js/bootstrap.bundle.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:100,200,300,400,500,600,700,800,900&display=swap"> <link rel="stylesheet" href="css/fontawesome/css/all.min.css"> <link rel="stylesheet" href="css/fontawesome/css/fontawesome.min.css"> <link rel="stylesheet" href="css/estilos.css"> </head> <body> <div id="home" class="container-fluid"> <div class="container"> <?php include_once("menu.php"); ?> </div> <div class="container"> <section> <div class="row py-5"> <div class="col-10"> <h1>Hola! <br> Bievenido a mi web </h1> <h2><NAME></h2> <a href="proyectos.php" class="btn mt-sm-4">Conoce mis proyectos</a> </div> </div> </section> </div> </div> <?php include_once("footer.php"); ?> </body> </html><file_sep>/proyectos.php <?php $pg ="proyectos";?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Proyectos</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://getbootstrap.com/docs/4.5/dist/js/bootstrap.bundle.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:100,200,300,400,500,600,700,800,900&display=swap"> <link rel="stylesheet" href="css/fontawesome/css/all.min.css"> <link rel="stylesheet" href="css/fontawesome/css/fontawesome.min.css"> <link rel="stylesheet" href="css/estilos.css"> </head> <body> <header> <?php include_once("menu.php"); ?> </header> <section id="proyectos"> <div class="container"> <div class="row mt-5"> <div class="col-12"> <h1>Mis proyectos</h1> </div> </div> <div class="row"> <div class="col-12 py-2"> <h2>Estos son algunos de los trabajos que he realizado:</h2> </div> </div> <div class="row my-sm-4 my-3"> <div class="col-sm-6 col-12 mb-4 px-2"> <div class="bg-white"> <img src="images/abmclientes.png" alt="abmclientes" class="img-fluid"> <div class="row p-3"> <div class="col-12"> <h3>ABM Clientes</h3> </div> </div> <div class="row p-3"> <div class="col-11"> <p>Alta, Baja, modificación de un registro de clientes empleando:. Realizado en HTML, CSS, PHP, Bootstrap y Json. </p> </div> </div> <div class="row p-3"> <div class="col-6"> <a href="abmclientes" class="btn" target="_blank">Ver online</a> </div> <div class="col-6 text-right"> <a href="https://github.com/BenitezAxel/ABMClientes" target="_blank">Codigo fuente</a> </div> </div> </div> </div> <div class="col-sm-6 col-12 px-2"> <div class="bg-white"> <img src="images/abmventas.png" alt="ABM Ventas" class="img-fluid"> <div class="row p-3"> <div class="col-12"> <h3>Sistema de Gestion de ventas</h3> </div> </div> <div class="row p-3"> <div class="col-12"> <p>Sistema de gestión de clientes, productos y ventas. Realizado en HTML, CSS, PHP, MVC, Bootstrap, Js, Ajax, jQuery y MySQL de base de datos. </p> </div> </div> <div class="row p-3"> <div class="col-6"> <a href="abmventas/login.php" class="btn" target="_blank">Ver online</a> </div> <div class="col-6 text-right"> <a href="https://github.com/BenitezAxel/ABMVentas" target="_blank">Codigo fuente</a> </div> </div> </div> </div> <div class="col-sm-6 col-12 px-2 mt-4 mt-sm-0"> <div class="bg-white"> <img src="images/sistema-admin.png" alt="sistema-admin" class="img-fluid"> <div class="row p-3"> <div class="col-12"> <h3>Proyecto integrador</h3> </div> </div> <div class="row p-3"> <div class="col-12"> <p>Proyecto Full Stack desarrollado en PHP, Laravel, Javascript, jQuery, AJAX, HTML, CSS, con panel administrador, gestor de usuarios, módulo de permisos y funcionalidades a fines.</p> </div> </div> <div class="row p-3"> <div class="col-6"> <a href="sistema/abmventas/abmcliente.php" class="btn" target="_blank">Ver online</a> </div> <div class="col-6 text-right"> <a href="https://github.com/BenitezAxel/portfolio1" target="_blank">Codigo fuente</a> </div> </div> </div> </div> </div> </div> </section> <?php include_once("footer.php"); ?> </body> </html><file_sep>/footer.php <footer> <div class="container"> <div class="row py-5"> <div class="col-sm-4 col-12 text-left"> <a href="index.php">&#169;Todos los derechos reservados<br><?php echo date("Y"); ?></a> </div> <div class="col-sm-4 col-12 text-center"> <a href="" target="_blank"><i class="fab fa-whatsapp"></i></a> <a href="" target="_blank"><i class="fab fa-facebook"></i></a> <a href="" target="_blank"><i class="fab fa-instagram"></i></a> </div> <div class="col-sm-4 col-12 text-right"> Patrocinado por <br><a href="https://depcsuite.com/" target="_blank">DePC Suite</a> </div> </div> </div> </footer>
7aa58900afde89aa644b8f79c157ba285e742324
[ "CSS", "PHP" ]
6
CSS
BenitezAxel/portfolio
725b8f5f3905a0d8981d1d463dff284d33fb8bc5
c73ed1b1c2ddc94d8f57cc8e461b980936cc4a26
refs/heads/main
<repo_name>pratyushjs/holofy<file_sep>/src/App.js import React, { useEffect, useState } from "react"; import "./App.css"; import DragNDrop from "./components/DragNDrop"; const defaultData = [ { title: "group 1", items: [1] }, { title: "group 2", items: [] }, { title: "group 3", items: [] }, { title: "group 4", items: [] }, ]; function App() { const [data, setData] = useState(); useEffect(() => { if (localStorage.getItem("List")) { console.log(localStorage.getItem("List")); setData(JSON.parse(localStorage.getItem("List"))); } else { setData(defaultData); } }, [setData]); return ( <div className="App"> <DragNDrop data={data} /> </div> ); } export default App;
1fae89bf81ee1eb2b727acdedac4a492be98606c
[ "JavaScript" ]
1
JavaScript
pratyushjs/holofy
d0d7f120c52f47440cb4c4425e68e5e146dc6fb7
692a84dac1a39253dfd556bab840d99684f67f61
refs/heads/main
<file_sep># clean-node-api Curso Gratuito de NodeJS onde aprendi mais sobre TDD, Clean Architecture e Design Patterns.
0c3723c835dc8dc4cee17757008271cb0a8207ce
[ "Markdown" ]
1
Markdown
moutlender/clean-node-api
6e6b674505ecb685495da13fc61f26f93675ab98
28f5ff6ee1bfb05b014c23abfdbb36ef85b8fef1
refs/heads/main
<file_sep>package main import ( "encoding/xml" "github.com/tlarsen7572/goalteryx/sdk" ) type Configuration struct { Text1 string Text2 string OutputField string } type DiceCoefficientPlugin struct { configuration Configuration provider sdk.Provider hasError bool text1 sdk.IncomingStringField text2 sdk.IncomingStringField outgoingInfo *sdk.OutgoingRecordInfo scoreField sdk.OutgoingFloatField output sdk.OutputAnchor } func (p *DiceCoefficientPlugin) Init(provider sdk.Provider) { p.provider = provider err := xml.Unmarshal([]byte(provider.ToolConfig()), &p.configuration) if err != nil { p.sendError(err) return } p.output = provider.GetOutputAnchor(`Output`) } func (p *DiceCoefficientPlugin) OnInputConnectionOpened(connection sdk.InputConnection) { var err error incomingInfo := connection.Metadata() p.text1, err = incomingInfo.GetStringField(p.configuration.Text1) if err != nil { p.sendError(err) return } p.text2, err = incomingInfo.GetStringField(p.configuration.Text2) if err != nil { p.sendError(err) return } editor := incomingInfo.Clone() outgoingField := editor.AddDoubleField(p.configuration.OutputField, `Dice Coefficient (Go)`) p.outgoingInfo = editor.GenerateOutgoingRecordInfo() p.scoreField, _ = p.outgoingInfo.FloatFields[outgoingField] p.output.Open(p.outgoingInfo) } func (p *DiceCoefficientPlugin) OnRecordPacket(connection sdk.InputConnection) { packet := connection.Read() for packet.Next() { p.outgoingInfo.CopyFrom(packet.Record()) text1, isNull1 := p.text1.GetValue(packet.Record()) text2, isNull2 := p.text2.GetValue(packet.Record()) if isNull1 || isNull2 { p.scoreField.SetFloat(0) p.output.Write() continue } score := CalculateDiceCoefficient(text1, text2) p.scoreField.SetFloat(score) p.output.Write() } p.output.UpdateProgress(connection.Progress()) } func (p *DiceCoefficientPlugin) OnComplete() { } func (p *DiceCoefficientPlugin) sendError(err error) { p.hasError = true p.provider.Io().Error(err.Error()) } <file_sep># Copyright (C) 2021 Alteryx, Inc. All rights reserved. # # Licensed under the ALTERYX SDK AND API LICENSE AGREEMENT; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.alteryx.com/alteryx-sdk-and-api-license-agreement # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Example pass through tool.""" from ayx_plugin_sdk.core import ( InputConnectionBase, Plugin, ProviderBase, register_plugin, FieldType, RecordPacket, ) def dice_coefficient(a, b): if a is None or b is None: return 0.0 if not len(a) or not len(b): return 0.0 """ quick case for true duplicates """ if a == b: return 1.0 """ if a != b, and a or b are single chars, then they can't possibly match """ if len(a) == 1 or len(b) == 1: return 0.0 """ use python list comprehension, preferred over list.append() """ a_bigram_list = [a[i:i + 2] for i in range(len(a) - 1)] b_bigram_list = [b[i:i + 2] for i in range(len(b) - 1)] a_bigram_list.sort() b_bigram_list.sort() # assignments to save function calls lena = len(a_bigram_list) lenb = len(b_bigram_list) # initialize match counters matches = i = j = 0 while (i < lena and j < lenb): if a_bigram_list[i] == b_bigram_list[j]: matches += 1 i += 1 j += 1 elif a_bigram_list[i] < b_bigram_list[j]: i += 1 else: j += 1 score = float(2 * matches) / float(lena + lenb) return score class python_dice_coefficient(Plugin): """A sample Plugin that passes data from an input connection to an output connection.""" def __init__(self, provider: ProviderBase): """Construct the AyxRecordProcessor.""" self.name = "Pass through" self.provider = provider self.text1 = provider.tool_config['Text1'] self.text2 = provider.tool_config['Text2'] self.outputField = provider.tool_config['OutputField'] self.output_anchor = self.provider.get_output_anchor("Output") self.output_metadata = None def on_input_connection_opened(self, input_connection: InputConnectionBase) -> None: """Initialize the Input Connections of this plugin.""" if input_connection.metadata is None: raise RuntimeError("Metadata must be set before setting containers.") input_connection.max_packet_size = 1000 self.output_metadata = input_connection.metadata.clone() self.output_metadata.add_field(self.outputField, FieldType.double, source="Dice Coefficient (Python)") self.output_anchor.open(self.output_metadata) def on_record_packet(self, input_connection: InputConnectionBase) -> None: """Handle the record packet received through the input connection.""" packet = input_connection.read() df = packet.to_dataframe() df[self.outputField] = df.apply(self.score_row, axis=1) out_packet = RecordPacket.from_dataframe(df=df, metadata=self.output_metadata) self.output_anchor.write(out_packet) def on_complete(self) -> None: """Handle for when the plugin is complete.""" def score_row(self, row): return dice_coefficient(row[self.text1], row[self.text2]) AyxPlugin = register_plugin(python_dice_coefficient) <file_sep>module go_dice_coefficient go 1.15 require github.com/tlarsen7572/goalteryx v0.5.6 <file_sep>package main_test import ( "encoding/xml" "github.com/tlarsen7572/goalteryx/sdk" "math" "testing" ) import dc "go_dice_coefficient" func TestConfigUnmarshal(t *testing.T) { configStr := `<Configuration> <Text1>First</Text1> <Text2>Second</Text2> <OutputField>Match Score</OutputField> </Configuration>` config := dc.Configuration{} err := xml.Unmarshal([]byte(configStr), &config) if err != nil { t.Fatalf(`expected no error but got: %v`, err.Error()) } if config.Text1 != `First` { t.Fatalf(`expected 'First' but got '%v'`, config.Text1) } if config.Text2 != `Second` { t.Fatalf(`expected 'Second' but got '%v'`, config.Text1) } if config.OutputField != `Match Score` { t.Fatalf(`expected 'Match Score' but got '%v'`, config.Text1) } } func TestScoreCalc(t *testing.T) { score := dc.CalculateDiceCoefficient(`<NAME>`, `<NAME>`) if score != 1.0 { t.Fatalf(`expected 1 but got %v`, score) } score = dc.CalculateDiceCoefficient(``, `<NAME>`) if score != 0.0 { t.Fatalf(`expected 0 but got %v`, score) } score = dc.CalculateDiceCoefficient(`<NAME>`, ``) if score != 0.0 { t.Fatalf(`expected 0 but got %v`, score) } score = dc.CalculateDiceCoefficient(`<NAME>`, `a`) if score != 0.0 { t.Fatalf(`expected 0 but got %v`, score) } score = dc.CalculateDiceCoefficient(`<NAME>`, `<NAME>`) if math.Abs(score-0.83333) > 0.0001 { t.Fatalf(`expected 0.833333333333333 but got %v`, score) } score = dc.CalculateDiceCoefficient(`Hello World`, `How are you`) if score != 0 { t.Fatalf(`expected 0 but got %v`, score) } score = dc.CalculateDiceCoefficient(`night`, `nacht`) if math.Abs(score-0.25) > 0.0001 { t.Fatalf(`expected 0.25 but got %v`, score) } score = dc.CalculateDiceCoefficient(`AA`, `AAAA`) if math.Abs(score-0.5) > 0.0001 { t.Fatalf(`expected 0.5 but got %v`, score) } score = dc.CalculateDiceCoefficient(`AAAA`, `AAAAAA`) if math.Abs(score-0.75) > 0.0001 { t.Fatalf(`expected 0.75 but got %v`, score) } score = dc.CalculateDiceCoefficient(`12121212`, `12345678`) if math.Abs(score-0.142857) > 0.0001 { t.Fatalf(`expected 0.142857 but got %v`, score) } } func TestEndToEnd(t *testing.T) { config := `<Configuration> <Text1>Text1</Text1> <Text2>Text2</Text2> <OutputField>Match Score</OutputField> </Configuration>` plugin := &dc.DiceCoefficientPlugin{} runner := sdk.RegisterToolTest(plugin, 1, config) runner.ConnectInput(`Input`, `testdata.txt`) output := runner.CaptureOutgoingAnchor(`Output`) runner.SimulateLifecycle() scores, ok := output.Data[`Match Score`] if !ok { t.Fatalf(`expected a Match Score field but it did not exist`) } if len(scores) != 6 { t.Fatalf(`expected 6 rows but got %v`, len(scores)) } if scores[0] != 0.25 { t.Fatalf(`expected first row score to be 0.25 but got %v`, scores[0]) } if scores[3] != 0.0 { t.Fatalf(`expected fourth row score to be 0 but got %v`, scores[3]) } } <file_sep>package main import "sort" func CalculateDiceCoefficient(text1 string, text2 string) float64 { if text1 == `` || text2 == `` { return 0 } if text1 == text2 { return 1 } if len(text1) == 0 || len(text2) == 0 { return 0 } bigrams1 := generateSortedBigrams(text1) bigrams2 := generateSortedBigrams(text2) return scoreBigrams(bigrams1, bigrams2) } type bigram struct { digit1 rune digit2 rune } func (b bigram) equals(other bigram) bool { return b.digit1 == other.digit1 && b.digit2 == other.digit2 } func (b bigram) lessThan(other bigram) bool { return b.digit1 < other.digit1 || (b.digit1 == other.digit1 && b.digit2 < other.digit2) } func generateSortedBigrams(text string) []bigram { start := 0 runes := []rune(text) bigrams := make([]bigram, len(runes)-1) for end := 1; end < len(runes); end++ { bigrams[start] = bigram{runes[start], runes[end]} start++ } sort.Slice(bigrams, func(i int, j int) bool { return bigrams[i].lessThan(bigrams[j]) }) return bigrams } func scoreBigrams(bigrams1 []bigram, bigrams2 []bigram) float64 { i1 := 0 i2 := 0 matches := 0 for i1 < len(bigrams1) && i2 < len(bigrams2) { if bigrams1[i1].equals(bigrams2[i2]) { matches++ i1++ i2++ continue } if bigrams1[i1].lessThan(bigrams2[i2]) { i1++ continue } i2++ } return float64(matches*2) / float64(len(bigrams1)+len(bigrams2)) } <file_sep>package main import "C" import ( "github.com/tlarsen7572/goalteryx/sdk" "unsafe" ) func main() {} //export PluginEntry func PluginEntry(toolId C.int, xmlProperties unsafe.Pointer, engineInterface unsafe.Pointer, pluginInterface unsafe.Pointer) C.long { plugin := &DiceCoefficientPlugin{} return C.long(sdk.RegisterTool(plugin, int(toolId), xmlProperties, engineInterface, pluginInterface)) } <file_sep>import AlteryxPythonSDK as Sdk import xml.etree.ElementTree as Et class AyxPlugin: def __init__(self, n_tool_id: int, alteryx_engine: object, output_anchor_mgr: object): # Default properties self.n_tool_id: int = n_tool_id self.alteryx_engine: Sdk.AlteryxEngine = alteryx_engine self.output_anchor_mgr: Sdk.OutputAnchorManager = output_anchor_mgr self.label = "Dice Coefficient" # Custom properties self.Output: Sdk.OutputAnchor = None self.OutputField: str = None self.Text1: str = None self.Text2: str = None def pi_init(self, str_xml: str): xml_parser = Et.fromstring(str_xml) self.OutputField = xml_parser.find("OutputField").text if 'OutputField' in str_xml else '' self.Text1 = xml_parser.find("Text1").text if 'Text1' in str_xml else '' self.Text2 = xml_parser.find("Text2").text if 'Text2' in str_xml else '' # Getting the output anchor from Config.xml by the output connection name self.Output = self.output_anchor_mgr.get_output_anchor('Output') def pi_add_incoming_connection(self, str_type: str, str_name: str) -> object: return IncomingInterface(self) def pi_add_outgoing_connection(self, str_name: str) -> bool: return True def pi_push_all_records(self, n_record_limit: int) -> bool: return False def pi_close(self, b_has_errors: bool): return def display_error_msg(self, msg_string: str): self.alteryx_engine.output_message(self.n_tool_id, Sdk.EngineMessageType.error, msg_string) def display_info_msg(self, msg_string: str): self.alteryx_engine.output_message(self.n_tool_id, Sdk.EngineMessageType.info, msg_string) class IncomingInterface: def __init__(self, parent: AyxPlugin): # Default properties self.parent: AyxPlugin = parent # Custom properties self.InInfo: Sdk.RecordInfo = None self.OutInfo: Sdk.RecordInfo = None self.Creator: Sdk.RecordCreator = None self.Copier: Sdk.RecordCopier = None self.ScoreField: Sdk.Field = None self.Text1Field: Sdk.Field = None self.Text2Field: Sdk.Field = None def ii_init(self, record_info_in: Sdk.RecordInfo) -> bool: self.InInfo = record_info_in self.Text1Field = record_info_in.get_field_by_name(self.parent.Text1) self.Text2Field = record_info_in.get_field_by_name(self.parent.Text2) self.OutInfo = self.InInfo.clone() self.ScoreField = self.OutInfo.add_field(self.parent.OutputField, Sdk.FieldType.double, source=self.parent.label) self.Creator = self.OutInfo.construct_record_creator() self.Copier = Sdk.RecordCopier(self.OutInfo, self.InInfo) index = 0 while index < self.InInfo.num_fields: self.Copier.add(index, index) index += 1 self.Copier.done_adding() self.parent.Output.init(self.OutInfo) return True def ii_push_record(self, in_record: Sdk.RecordRef) -> bool: self.Creator.reset() self.Copier.copy(self.Creator, in_record) text1 = self.Text1Field.get_as_string(in_record) text2 = self.Text2Field.get_as_string(in_record) self.ScoreField.set_from_double(self.Creator, dice_coefficient(text1, text2)) out_record = self.Creator.finalize_record() self.parent.Output.push_record(out_record) return True def ii_update_progress(self, d_percent: float): # Inform the Alteryx engine of the tool's progress. self.parent.alteryx_engine.output_tool_progress(self.parent.n_tool_id, d_percent) def ii_close(self): self.parent.Output.assert_close() return def dice_coefficient(a, b): if a is None or b is None: return 0.0 if not len(a) or not len(b): return 0.0 """ quick case for true duplicates """ if a == b: return 1.0 """ if a != b, and a or b are single chars, then they can't possibly match """ if len(a) == 1 or len(b) == 1: return 0.0 """ use python list comprehension, preferred over list.append() """ a_bigram_list = [a[i:i + 2] for i in range(len(a) - 1)] b_bigram_list = [b[i:i + 2] for i in range(len(b) - 1)] a_bigram_list.sort() b_bigram_list.sort() # assignments to save function calls lena = len(a_bigram_list) lenb = len(b_bigram_list) # initialize match counters matches = i = j = 0 while (i < lena and j < lenb): if a_bigram_list[i] == b_bigram_list[j]: matches += 1 i += 1 j += 1 elif a_bigram_list[i] < b_bigram_list[j]: i += 1 else: j += 1 score = float(2 * matches) / float(lena + lenb) return score
843e62e2b83047823d48947a505b402d6193a660
[ "Go Module", "Python", "Go" ]
7
Go Module
tlarsen7572/ayx_dice_coefficient
8daee3e7f3709690bcba0e94d4eda43a783bf0da
3a8561ffc0abe5d5c5c809fdfa1952aaf31d3837
refs/heads/main
<repo_name>mplumer/book-search-engine<file_sep>/README.md # Book Search Engine ## Description Book Search Engine is an Apollo and React based application that allows users to browse Google Books API and choose books to save and display in their own, unique account pages. ## Link to Deployed Application * [Book Search Engine](https://quiet-cliffs-01279.herokuapp.com/) ### User Story * AS AN avid reader * I WANT to search for new books to read * SO THAT I can keep a list of books to purchase ## Table of Contents * [Installation](#installation) * [Usage](#usage) * [License](#license) * [Contributing](#contributing) * [Questions](#questions) ## Link to Github Repository * [Book Search Engine](https://github.com/mplumer/book-search-engine) ![Screenshot](client/public/assets/images/Screenshot2.png) ![Screenshot](client/public/assets/images/Screenshot1.png) ### Installation Follow the deployed application link: https://quiet-cliffs-01279.herokuapp.com/. ### Usage Type the title of a book that interests you into the search bar field. After clicking the search button, click the save button of books you want to keep in your wishlist. ### License MIT ### Contributing Book Search Engine is an open source project that was built from cloned, front-end starter code at the University of Texas Web Development Bootcamp, and anyone is encouraged to contribute by cloning or forking the code and working to improve its function and versatility. ### Questions ##### Interested in other projects from this developer? Visit the following GitHub page: https://github.com/mplumer ##### Send any questions to the following email address: <EMAIL>
2004aa13416742cb16158e834ecf80cefb0a7d4f
[ "Markdown" ]
1
Markdown
mplumer/book-search-engine
67695c05b3557012291025799688049ca37417c3
12a4c63341da098887bc0692ea0c23767cd7b68e
refs/heads/master
<repo_name>MehulKK/FirebaseImageUpload<file_sep>/app/src/main/java/com/firebaseimageupload/activity/UploadImageActivity.java package com.firebaseimageupload.activity; import android.Manifest; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.firebaseimageupload.R; import com.firebaseimageupload.extras.Constants; import com.firebaseimageupload.extras.Utils; import com.firebaseimageupload.models.ImageUpload; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.IOException; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Mehul on 30-Apr-17. */ public class UploadImageActivity extends AppCompatActivity implements View.OnClickListener { //constant to track image chooser intent private static final int PICK_IMAGE_REQUEST = 234; private static final int REQUEST_READ_PERMISSION = 101; @BindView(R.id.imageView) ImageView imageView; @BindView(R.id.buttonUpload) Button buttonUpload; @BindView(R.id.textViewShow) TextView textViewShow; @BindView(R.id.buttonChoose) Button buttonChoose; @BindView(R.id.editText) EditText editText; @BindView(R.id.toolbar2) Toolbar toolbar; //uri to store file private Uri filePath; //firebase objects private StorageReference storageReference; private DatabaseReference mDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_upload); ButterKnife.bind(this); init(); } private void init(){ storageReference = FirebaseStorage.getInstance().getReference(); mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS); buttonChoose.setOnClickListener(this); buttonUpload.setOnClickListener(this); textViewShow.setOnClickListener(this); setSupportActionBar(toolbar); } private void showFileChooser() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); } private void uploadFile() { //checking if file is available if (filePath != null) { //displaying progress dialog while image is uploading final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle("Uploading"); progressDialog.show(); //getting the storage reference StorageReference sRef = storageReference.child(Constants.STORAGE_PATH_UPLOADS + System.currentTimeMillis() + "." + Utils.getFileExtension(UploadImageActivity.this,filePath)); //adding the file to reference sRef.putFile(filePath) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { //dismissing the progress dialog progressDialog.dismiss(); //displaying success toast Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show(); //creating the upload object to store uploaded image details ImageUpload upload = new ImageUpload(editText.getText().toString().trim(), taskSnapshot.getDownloadUrl().toString()); //adding an upload to firebase database String uploadId = mDatabase.push().getKey(); mDatabase.child(uploadId).setValue(upload); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { progressDialog.dismiss(); Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show(); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { //displaying the upload progress double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount(); progressDialog.setMessage("Uploaded " + ((int) progress) + "%..."); } }); } else { //display an error if no file is selected Toast.makeText(UploadImageActivity.this, "Please select File", Toast.LENGTH_LONG).show(); } } @Override public void onClick(View view) { if (view == buttonChoose) { requestPermission(); } else if (view == buttonUpload) { uploadFile(); } else if (view == textViewShow) { startActivity(new Intent(UploadImageActivity.this, ShowImagesActivity.class)); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } private void requestPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_PERMISSION); } else { showFileChooser(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == REQUEST_READ_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) { showFileChooser(); } } }
c7db219abd22eb2016a2b19177279bc9a1e3296a
[ "Java" ]
1
Java
MehulKK/FirebaseImageUpload
050de22480c7dfeaf70bb4f8fc6c2cc9ac6ee908
7b9b61b8c11c276be9283fe0e814fbae433fc50c
refs/heads/main
<repo_name>nickgraffis/tomato-timer<file_sep>/README.md # tomato-timer Fun Tomato timer
215d331740783894659f399138be1bdc126e8cc4
[ "Markdown" ]
1
Markdown
nickgraffis/tomato-timer
c63fd359c1203b581377429751fd5f6d27e20958
e52ecdace03972858c04e48766679ce059e37e72
refs/heads/main
<file_sep>""" This file is for models creation, which consults options and creates each encoder and decoder accordingly. """ import torch import torch.nn as nn import onmt import onmt.io import onmt.Models import onmt.modules from onmt.Models import NMTModel, MeanEncoder, RNNEncoder, \ StdRNNDecoder, InputFeedRNNDecoder, MirrorModel, MirrorLight, Mirror_Encshare, MirrorLow_Encshare, Input_Z_FeedRNNDecoder, Input_Z_RNNDecoder, MirrorLow from onmt.modules import Embeddings, ImageEncoder, CopyGenerator, \ TransformerEncoder, TransformerDecoder, \ CNNEncoder, CNNDecoder, AudioEncoder from onmt.Utils import use_gpu def make_embeddings(opt, word_dict, feature_dicts, for_encoder=True): """ Make an Embeddings instance. Args: opt: the option in current environment. word_dict(Vocab): words dictionary. feature_dicts([Vocab], optional): a list of feature dictionary. for_encoder(bool): make Embeddings for encoder or decoder? """ if for_encoder: embedding_dim = opt.src_word_vec_size else: embedding_dim = opt.tgt_word_vec_size word_padding_idx = word_dict.stoi[onmt.io.PAD_WORD] num_word_embeddings = len(word_dict) feats_padding_idx = [feat_dict.stoi[onmt.io.PAD_WORD] for feat_dict in feature_dicts] num_feat_embeddings = [len(feat_dict) for feat_dict in feature_dicts] return Embeddings(word_vec_size=embedding_dim, position_encoding=opt.position_encoding, feat_merge=opt.feat_merge, feat_vec_exponent=opt.feat_vec_exponent, feat_vec_size=opt.feat_vec_size, dropout=opt.dropout, word_padding_idx=word_padding_idx, feat_padding_idx=feats_padding_idx, word_vocab_size=num_word_embeddings, feat_vocab_sizes=num_feat_embeddings) def make_encoder(opt, embeddings,ctx=False): """ Various encoder dispatcher function. Args: opt: the option in current environment. embeddings (Embeddings): vocab embeddings for this encoder. """ if opt.encoder_type == "transformer": return TransformerEncoder(opt.enc_layers, opt.rnn_size, opt.dropout, embeddings) elif opt.encoder_type == "cnn": return CNNEncoder(opt.enc_layers, opt.rnn_size, opt.cnn_kernel_width, opt.dropout, embeddings) elif opt.encoder_type == "mean": return MeanEncoder(opt.enc_layers, embeddings) else: # "rnn" or "brnn" if ctx: return RNNEncoder(opt.rnn_type, opt.ctx_bid, opt.enc_layers, opt.rnn_size, opt.dropout, embeddings) else: return RNNEncoder(opt.rnn_type, opt.brnn, opt.enc_layers, opt.rnn_size, opt.dropout, embeddings) def make_decoder(opt, embeddings): """ Various decoder dispatcher function. Args: opt: the option in current environment. embeddings (Embeddings): vocab embeddings for this decoder. """ if opt.decoder_type == "transformer": return TransformerDecoder(opt.dec_layers, opt.rnn_size, opt.global_attention, opt.copy_attn, opt.dropout, embeddings) elif opt.decoder_type == "cnn": return CNNDecoder(opt.dec_layers, opt.rnn_size, opt.global_attention, opt.copy_attn, opt.cnn_kernel_width, opt.dropout, embeddings) elif opt.input_feed: if opt.input_feed_with_ctx: return Input_Z_FeedRNNDecoder(opt.rnn_type, opt.brnn, opt.dec_layers, opt.rnn_size, opt.global_attention, opt.coverage_attn, opt.context_gate, opt.copy_attn, opt.dropout, embeddings, opt.z_dim) else: return Input_Z_RNNDecoder(opt.rnn_type, opt.brnn, opt.dec_layers, opt.rnn_size, opt.global_attention, opt.coverage_attn, opt.context_gate, opt.copy_attn, opt.dropout, embeddings, opt.z_dim) else: return StdRNNDecoder(opt.rnn_type, opt.brnn, opt.dec_layers, opt.rnn_size, opt.global_attention, opt.coverage_attn, opt.context_gate, opt.copy_attn, opt.dropout, embeddings) def load_test_model(opt, dummy_opt,): checkpoint = torch.load(opt.model, map_location=lambda storage, loc: storage) fields = onmt.io.load_fields_from_vocab( checkpoint['vocab'], data_type=opt.data_type) model_opt = checkpoint['opt'] for arg in dummy_opt: if arg not in model_opt: model_opt.__dict__[arg] = dummy_opt[arg] model = make_mirror_model(model_opt, fields, use_gpu(opt), checkpoint, model_opt.mirror_type) model.eval() model.generator_cxz2y.eval() model.generator_cyz2x.eval() model.generator_cz2x.eval() model.generator_cz2y.eval() return fields, model, model_opt def load_mmi_model(opt, dummy_opt): checkpoint = torch.load(opt.mmi_model, map_location=lambda storage, loc: storage) fields = onmt.io.load_fields_from_vocab( checkpoint['vocab'], data_type=opt.data_type) model_opt = checkpoint['opt'] for arg in dummy_opt: if arg not in model_opt: model_opt.__dict__[arg] = dummy_opt[arg] model = make_base_model(model_opt, fields, use_gpu(opt), checkpoint) model.eval() model.generator.eval() return fields, model, model_opt def make_base_model(model_opt, fields, gpu, checkpoint=None): """ Args: model_opt: the option loaded from checkpoint. fields: `Field` objects for the model. gpu(bool): whether to use gpu. checkpoint: the model gnerated by train phase, or a resumed snapshot model from a stopped training. Returns: the NMTModel. """ assert model_opt.model_type in ["text", "img", "audio"], \ ("Unsupported model type %s" % (model_opt.model_type)) # Make encoder. if model_opt.model_type == "text": src_dict = fields["src"].vocab feature_dicts = onmt.io.collect_feature_vocabs(fields, 'src') src_embeddings = make_embeddings(model_opt, src_dict, feature_dicts) encoder = make_encoder(model_opt, src_embeddings) elif model_opt.model_type == "img": encoder = ImageEncoder(model_opt.enc_layers, model_opt.brnn, model_opt.rnn_size, model_opt.dropout) elif model_opt.model_type == "audio": encoder = AudioEncoder(model_opt.enc_layers, model_opt.brnn, model_opt.rnn_size, model_opt.dropout, model_opt.sample_rate, model_opt.window_size) # Make decoder. tgt_dict = fields["tgt"].vocab feature_dicts = onmt.io.collect_feature_vocabs(fields, 'tgt') tgt_embeddings = make_embeddings(model_opt, tgt_dict, feature_dicts, for_encoder=False) # Share the embedding matrix - preprocess with share_vocab required. if model_opt.share_embeddings: # src/tgt vocab should be the same if `-share_vocab` is specified. if src_dict != tgt_dict: raise AssertionError('The `-share_vocab` should be set during ' 'preprocess if you use share_embeddings!') tgt_embeddings.word_lut.weight = src_embeddings.word_lut.weight decoder = make_decoder(model_opt, tgt_embeddings) # Make NMTModel(= encoder + decoder). model = NMTModel(encoder, decoder) model.model_type = model_opt.model_type # Make Generator. if not model_opt.copy_attn: generator = nn.Sequential( nn.Linear(model_opt.rnn_size, len(fields["tgt"].vocab)), nn.LogSoftmax()) if model_opt.share_decoder_embeddings: generator[0].weight = decoder.embeddings.word_lut.weight else: generator = CopyGenerator(model_opt.rnn_size, fields["tgt"].vocab) # Load the model states from checkpoint or initialize them. if checkpoint is not None: print('Loading model parameters.') model.load_state_dict(checkpoint['model']) generator.load_state_dict(checkpoint['generator']) else: if model_opt.param_init != 0.0: print('Intializing model parameters.') for p in model.parameters(): p.data.uniform_(-model_opt.param_init, model_opt.param_init) for p in generator.parameters(): p.data.uniform_(-model_opt.param_init, model_opt.param_init) if hasattr(model.encoder, 'embeddings'): model.encoder.embeddings.load_pretrained_vectors( model_opt.pre_word_vecs_enc, model_opt.fix_word_vecs_enc) if hasattr(model.decoder, 'embeddings'): model.decoder.embeddings.load_pretrained_vectors( model_opt.pre_word_vecs_dec, model_opt.fix_word_vecs_dec) # Add generator to model (this registers it as parameter of model). model.generator = generator # Make the whole model leverage GPU if indicated to do so. if gpu: model.cuda() else: model.cpu() return model def make_mirror_model(model_opt, fields, gpu, checkpoint=None, mirror_type='mirror'): """ Args: model_opt: the option loaded from checkpoint. fields: `Field` objects for the model. gpu(bool): whether to use gpu. checkpoint: the model gnerated by train phase, or a resumed snapshot model from a stopped training. Returns: the NMTModel. """ assert model_opt.model_type in ["text", "img", "audio"], \ ("Unsupported model type %s" % (model_opt.model_type)) # Make encoder. # if model_opt.model_type == "text": src_dict = fields["src"].vocab feature_dicts = onmt.io.collect_feature_vocabs(fields, 'src') src_embeddings = make_embeddings(model_opt, src_dict, feature_dicts) # src_embeddings_ctx = make_embeddings(model_opt, src_dict, # feature_dicts) src_embeddings_ctx = src_embeddings encoder_utt = make_encoder(model_opt, src_embeddings) # encoder_utt_y = make_encoder(model_opt, src_embeddings) encoder_utt_y = None encoder_ctx = make_encoder(model_opt, src_embeddings_ctx, ctx=True) # Make decoder. tgt_dict = fields["tgt"].vocab feature_dicts = onmt.io.collect_feature_vocabs(fields, 'tgt') tgt_embeddings = make_embeddings(model_opt, tgt_dict, feature_dicts, for_encoder=False) tgt_embeddings_2 = make_embeddings(model_opt, tgt_dict, feature_dicts, for_encoder=False) tgt_embeddings_3 = make_embeddings(model_opt, tgt_dict, feature_dicts, for_encoder=False) tgt_embeddings_4 = make_embeddings(model_opt, tgt_dict, feature_dicts, for_encoder=False) # Share the embedding matrix - preprocess with share_vocab required. if model_opt.share_embeddings: # src/tgt vocab should be the same if `-share_vocab` is specified. print("encoder and decoder will share the embedding") if src_dict != tgt_dict: raise AssertionError('The `-share_vocab` should be set during ' 'preprocess if you use share_embeddings!') tgt_embeddings = src_embeddings tgt_embeddings.word_lut.weight = src_embeddings.word_lut.weight tgt_embeddings_2.word_lut.weight = src_embeddings.word_lut.weight tgt_embeddings_3.word_lut.weight = src_embeddings.word_lut.weight tgt_embeddings_4.word_lut.weight = src_embeddings.word_lut.weight src_embeddings_ctx.word_lut.weight = src_embeddings.word_lut.weight decoder_1 = make_decoder(model_opt, tgt_embeddings) decoder_2 = make_decoder(model_opt, tgt_embeddings_2) decoder_3 = make_decoder(model_opt, tgt_embeddings_3) decoder_4 = make_decoder(model_opt, tgt_embeddings_4) # Make NMTModel(= encoder + decoder). if mirror_type=='mirror': model = MirrorModel(encoder_utt, encoder_utt_y, encoder_ctx, decoder_1, decoder_2, decoder_3, decoder_4, opt=model_opt) elif mirror_type=='mirror_light': model = MirrorLight(encoder_utt, encoder_utt_y, encoder_ctx, decoder_1, decoder_2, decoder_3, decoder_4, opt=model_opt) elif mirror_type=='mirror_low': model = MirrorLow(encoder_utt, encoder_utt_y, encoder_ctx, decoder_1, decoder_2, decoder_3, decoder_4, opt=model_opt) elif mirror_type=='mirror_low_encshare': model = MirrorLow_Encshare(encoder_utt, decoder_1, decoder_2, decoder_3, decoder_4, opt=model_opt) else: raise ValueError("no such model type: {}".format(mirror_type)) model.model_type = model_opt.model_type # Make Generator. generator_cxz2y = make_generator(model_opt, model.decoder_cxz2y, fields, 'tgt') generator_cz2x = make_generator(model_opt, model.decoder_cz2x, fields, 'tgt_back') generator_cyz2x = make_generator(model_opt, model.decoder_cyz2x, fields, 'tgt_back') generator_cz2y = make_generator(model_opt, model.decoder_cz2y, fields, 'tgt') # Add generator to model (this registers it as parameter of model). model.generator_cxz2y = generator_cxz2y model.generator_cz2x = generator_cz2x model.generator_cyz2x = generator_cyz2x model.generator_cz2y = generator_cz2y # Load the model states from checkpoint or initialize them. # careful: fix the loading module later if checkpoint is not None: print('Loading model parameters.') model.load_state_dict(checkpoint['model']) # generator.load_state_dict(checkpoint['generator']) else: if model_opt.param_init != 0.0: print('Intializing model parameters.') for p in model.parameters(): p.data.uniform_(-model_opt.param_init, model_opt.param_init) # for p in generator_cxz2y.parameters(): # p.data.uniform_(-model_opt.param_init, model_opt.param_init) # for p in generator_cz2x.parameters(): # p.data.uniform_(-model_opt.param_init, model_opt.param_init) # for p in generator_cyz2x.parameters(): # p.data.uniform_(-model_opt.param_init, model_opt.param_init) # for p in generator_cz2y.parameters(): # p.data.uniform_(-model_opt.param_init, model_opt.param_init) if hasattr(model.encoder, 'embeddings'): model.encoder.embeddings.load_pretrained_vectors( model_opt.pre_word_vecs_enc, model_opt.fix_word_vecs_enc) if hasattr(model.encoder_ctx, 'embeddings'): model.encoder_ctx.embeddings.load_pretrained_vectors( model_opt.pre_word_vecs_enc, model_opt.fix_word_vecs_enc) if hasattr(model.decoder_cxz2y, 'embeddings'): model.decoder_cxz2y.embeddings.load_pretrained_vectors( model_opt.pre_word_vecs_dec, model_opt.fix_word_vecs_dec) if hasattr(model.decoder_cz2x, 'embeddings'): model.decoder_cz2x.embeddings.load_pretrained_vectors( model_opt.pre_word_vecs_dec, model_opt.fix_word_vecs_dec) if hasattr(model.decoder_cyz2x, 'embeddings'): model.decoder_cyz2x.embeddings.load_pretrained_vectors( model_opt.pre_word_vecs_dec, model_opt.fix_word_vecs_dec) if hasattr(model.decoder_cz2y, 'embeddings'): model.decoder_cz2y.embeddings.load_pretrained_vectors( model_opt.pre_word_vecs_dec, model_opt.fix_word_vecs_dec) # Make the whole model leverage GPU if indicated to do so. if gpu: model.cuda() else: model.cpu() return model def make_generator(model_opt, decoder, fields, des='tgt'): # Make Generator. if not model_opt.copy_attn: generator = nn.Sequential( nn.Linear(model_opt.rnn_size, len(fields[des].vocab)), nn.LogSoftmax(dim=-1)) if model_opt.share_decoder_embeddings: generator[0].weight = decoder.embeddings.word_lut.weight else: generator = CopyGenerator(model_opt.rnn_size, fields[des].vocab) return generator <file_sep>import onmt.io import onmt.translate import onmt.Models import onmt.Loss from onmt.Trainer import Trainer, Statistics, MirrorStatistics from onmt.Optim import Optim # For flake8 compatibility __all__ = [onmt.Loss, onmt.Models, Trainer, Optim, Statistics, MirrorStatistics, onmt.io, onmt.translate] <file_sep>from __future__ import division import torch # Beam decoding with KL divergence import numpy as np from scipy.stats import entropy class Beam(object): """ Class for managing the internals of the beam search process. Takes care of beams, back pointers, and scores. Args: size (int): beam size pad, bos, eos (int): indices of padding, beginning, and ending. vocab (vocab): vocab of the target syntax_topics_model (Syntax and Topics module): This is an object of the class which will have the topics and classes word probabilities source (list): list of source indices which will be the source sentence targets (list of list): list of taget sentences each of which is a list of indices of the full hypothesis generated till now n_best (int): nbest size to use cuda (bool): use gpu global_scorer (:obj:`GlobalScorer`) """ def __init__(self, size, pad, bos, eos, vocab, syntax_topics_model, source, n_best=1, cuda=False, global_scorer=None, min_length=0): self.use_cuda = cuda self.size = size # self.tt = torch.cuda if cuda else torch self.tt = torch # The score for each translation on the beam. self.scores = self.tt.FloatTensor(size).zero_() if self.use_cuda: self.scores = self.scores.cuda() self.all_scores = [] # The backpointers at each time-step. self.prev_ks = [] # The outputs at each time-step. self.next_ys = [self.tt.LongTensor(size) .fill_(pad)] if self.use_cuda: self.next_ys = [self.tt.LongTensor(size) .fill_(pad).cuda()] self.next_ys[0][0] = bos ##NOTE: speical marker which tells which class is the previous word from self.next_ys_topic_prior_sum = [] # Store the sum of the topic prior for the entire hypothesis self.next_ys_class_prior_sum = [] # Store the sum of the class prior for the entire hypothesis self.TOPIC_FLAG = 0 self.CLASS_FLAG = 1 # Has EOS topped the beam yet. self._eos = eos self.eos_top = False # The attentions (matrix) for each time. self.attn = [] # Time and k pair for finished. self.finished = [] self.n_best = n_best # Information for global scoring. self.global_scorer = global_scorer self.global_state = {} # Minimum prediction length self.min_length = min_length ##NOTE: Custom code self.vocab = vocab self.finished_marker = [-1]*size self.syntax_topics_model = syntax_topics_model self.source = [self.vocab.itos[word_id] for word_id in source] # Compute the topic prior probability for the source sentence self.source_topic_prior = np.zeros(self.syntax_topics_model.num_topics+1, dtype=np.float) print self.source self.src_topic_word_count = 0 for word in self.source: word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word) if word_topic_prior[self.syntax_topics_model.num_topics] != 1.0: print word self.src_topic_word_count += 1 self.source_topic_prior += word_topic_prior self.source_class_prior = np.zeros(self.syntax_topics_model.num_classes, dtype=np.float) for word in self.source: self.source_class_prior += self.syntax_topics_model.get_class_prior_for_word(word) self.source_topic_prior /= len(self.source) self.source_class_prior /= len(self.source) self.beta = 0.0 # Additive smoothing self.source_topic_prior += self.beta self.source_class_prior += self.beta print(self.source_topic_prior) print(self.source_class_prior) self.L = 50 # Number of words to be chosen for the similarity consideration # temp = np.zeros_like(self.source_topic_prior) + self.beta # least_KL = entropy(self.source_topic_prior, temp) self.alpha = 1.5 # Multiplicative factor for topic KL divergence self.gamma = 1.5 # Multiplicative factor for class KL divergence # self.alpha = 8/least_KL # multiplicative factor for the KL divergence # print vocab.itos[0] # print vocab.itos[bos] # print vocab.itos[self._eos] # print vocab.__dict__.keys() # print vocab.unk_init # print type(vocab) self.topic_KL_flag = False self.class_KL_flag = True def print_hyp(self, hyp, class_or_topic = None): for i, word_id in enumerate(hyp): if class_or_topic: print "{}_{} ".format(self.vocab.itos[word_id], class_or_topic[i]), else: print "{} ".format(self.vocab.itos[word_id]), ##NOTE: Custom function for debugging def print_all_words_in_beam(self): # Uses the vocab and prints the list of next_ys for i in range(self.size): timestep = len(self.next_ys) # if self.finished_marker[i] != -1: # timestep = self.finished_marker[i] if timestep > 1: hyp, _ = self.get_hyp(timestep, i) # print hyp # print type(hyp) self.print_hyp(hyp) print "$$$" # print "" def print_received_targets(self): for i in range(len(self.targets)): self.print_hyp(self.targets[i]) print "" print "############### Received Targets ############" def print_the_top_choices(self, best_choices): w, h = best_choices.size() for i in range(w): for j in range(h): print "{} ".format(self.vocab.itos[best_choices[i,j]]), print "" def get_current_state(self): "Get the outputs for the current timestep." return self.next_ys[-1] def get_current_origin(self): "Get the backpointers for the current timestep." return self.prev_ks[-1] def advance(self, word_probs, attn_out): print "Advancing beam" """ Given prob over words for every last beam `wordLk` and attention `attn_out`: Compute and update the beam search. Parameters: * `word_probs`- probs of advancing from the last step (K x words) * `attn_out`- attention at the last step Returns: True if beam search is complete. """ num_words = word_probs.size(1) # force the output to be longer than self.min_length cur_len = len(self.next_ys) if cur_len < self.min_length: for k in range(len(word_probs)): word_probs[k][self._eos] = -1e20 # Sum the previous scores. if len(self.prev_ks) > 0: beam_scores = word_probs + \ self.scores.unsqueeze(1).expand_as(word_probs) # Don't let EOS have children. for i in range(self.next_ys[-1].size(0)): if self.next_ys[-1][i] == self._eos: beam_scores[i] = -1e20 else: beam_scores = word_probs[0] #TODO: 1) find the last word for each beam # 2) For each possible hypothesis find the Topic modeling probability # 3) Weighted add the syntax and topic scores to beam_scores and just calculate the next_ys and backpointers as normal if len(self.prev_ks) > 0: per_beam_words = self.next_ys[-1] if self.topic_KL_flag: per_beam_hyp_topic_prior_sum = self.next_ys_topic_prior_sum[-1] if self.class_KL_flag: per_beam_hyp_class_prior_sum = self.next_ys_class_prior_sum[-1] if self.topic_KL_flag: topic_KL_divergence_scores = self.tt.zeros_like(beam_scores) if self.class_KL_flag: class_KL_divergence_scores = self.tt.zeros_like(beam_scores) for i in range(self.size): if self.topic_KL_flag: hyp_topic_prior = per_beam_hyp_topic_prior_sum[i] if self.class_KL_flag: hyp_class_prior = per_beam_hyp_class_prior_sum[i] len_hyp = len(self.next_ys) # Includes current word because we want to skip the count added by the start word <bos> for j in range(num_words): word = self.vocab.itos[j] #KL divergence for Topic Priors if self.topic_KL_flag: word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word) hyp_topic_prior_sum = (hyp_topic_prior + word_topic_prior) + self.beta # topic_KL_divergence_scores[i][j] = entropy(self.source_topic_prior, hyp_topic_prior_sum) topic_KL_divergence_scores[i][j] = self.syntax_topics_model.KL_divergence(self.source_topic_prior, hyp_topic_prior_sum) if topic_KL_divergence_scores[i][j] == float('Inf'): print word print topic_KL_divergence_scores[i][j] print self.source_topic_prior print hyp_topic_prior_sum #KL divergence for Class Priors if self.class_KL_flag: if "<unk>" in word: class_KL_divergence_scores[i][j] = 1000000.0 continue word_class_prior = self.syntax_topics_model.get_class_prior_for_word(word) hyp_class_prior_sum = (hyp_class_prior + word_class_prior) + self.beta # class_KL_divergence_scores[i][j] = entropy(self.source_class_prior, hyp_class_prior_sum) class_KL_divergence_scores[i][j] = self.syntax_topics_model.KL_divergence(self.source_class_prior, hyp_class_prior_sum) if class_KL_divergence_scores[i][j] == float('Inf'): print word print class_KL_divergence_scores[i][j] print self.source_class_prior print hyp_class_prior_sum #TODO: Convert the zeros to max KL divergence if self.topic_KL_flag: max_topic_KL = topic_KL_divergence_scores.mean() for i in range(self.size): for j in range(num_words): word = self.vocab.itos[j] if "<unk>" in word: topic_KL_divergence_scores[i][j] = 1000000.0 continue if topic_KL_divergence_scores[i][j] == 0.0: topic_KL_divergence_scores[i][j] = max_topic_KL print "########\n", max_topic_KL, "\n#########" # Manually discourage unk by setting large negative syntax_topic_probability # if "<unk>" in word: # syntax_topic_score, best_class_or_topic, class_or_topic = -1000000.0, -1, "C" # else: # syntax_topic_score, best_class_or_topic, class_or_topic = self.syntax_topics_model.get_log_prob(word, 0 if per_beam_words_class_or_topic[i] == self.TOPIC_FLAG else per_beam_words_class_or_topic_number[i]) overall_scores = beam_scores - ((self.alpha * topic_KL_divergence_scores) if self.topic_KL_flag else 0.0) - ((self.gamma * class_KL_divergence_scores) if self.class_KL_flag else 0.0) # print "Overall Score" # print overall_scores # print overall_scores.size() size = int(overall_scores.size(1)) # print "Size of the overall_scores = ", size flat_beam_scores = overall_scores.view(-1) best_scores, best_scores_id = flat_beam_scores.topk(self.size, 0, True, True) # We will debug the individual scores of the best candidates word_prob_best_scores = self.tt.zeros_like(best_scores) for i in range(self.size): word_prob_best_scores[i] = beam_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size] if self.topic_KL_flag: topic_KL_divergence_best_scores = self.tt.zeros_like(best_scores) for i in range(self.size): topic_KL_divergence_best_scores[i] = topic_KL_divergence_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size] if self.class_KL_flag: class_KL_divergence_best_scores = self.tt.zeros_like(best_scores) for i in range(self.size): class_KL_divergence_best_scores[i] = class_KL_divergence_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size] print best_scores print word_prob_best_scores # print topic_KL_divergence_best_scores # print class_KL_divergence_best_scores if self.topic_KL_flag: print self.alpha print self.alpha * topic_KL_divergence_best_scores if self.class_KL_flag: print self.gamma print self.gamma * class_KL_divergence_best_scores if self.topic_KL_flag: KL_size = int(topic_KL_divergence_scores.size(1)) # print "Size of the overall_scores = ", size flat_beam_scores = topic_KL_divergence_scores.view(-1) debug_size = 25 best_topic_KL_scores, best_topic_KL_scores_id = flat_beam_scores.topk(debug_size, 0, False, True) print "Best words from topic KL" for i in range(debug_size): # print best_topic_KL_scores_id[i], best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size word = self.vocab.itos[best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size] word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word) # print word, word_topic_prior, entropy(self.source_topic_prior, word_topic_prior + self.beta), \ print word, \ overall_scores[int(best_topic_KL_scores_id[i] / KL_size)][best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size], \ best_topic_KL_scores[i], \ topic_KL_divergence_scores[int(best_topic_KL_scores_id[i] / KL_size)][best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size] # class_KL_divergence_scores[int(best_topic_KL_scores_id[i] / KL_size)][best_topic_KL_scores_id[i] - int(best_topic_KL_scores_id[i] / KL_size) * KL_size], \ # print word_prob_best_scores + self.alpha * syntax_topic_best_scores prev_k = best_scores_id / num_words # Update next_ys_topic_prior_sum for all beams if self.topic_KL_flag: best_hyp_topic_prior_sum = list() for i in range(self.size): word = self.vocab.itos[best_scores_id[i] - int(best_scores_id[i] / size) * size] word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word) if word_topic_prior[self.syntax_topics_model.num_topics] != 1.0: best_hyp_topic_prior_sum.append(self.next_ys_topic_prior_sum[-1][int(best_scores_id[i] / size)] + word_topic_prior) else: # Add the word_topic_prior only if its a topic word best_hyp_topic_prior_sum.append(self.next_ys_topic_prior_sum[-1][int(best_scores_id[i] / size)]) self.next_ys_topic_prior_sum.append(best_hyp_topic_prior_sum) # Update next_ys_class_prior_sum for all beams if self.class_KL_flag: best_hyp_class_prior_sum = list() for i in range(self.size): word = self.vocab.itos[best_scores_id[i] - int(best_scores_id[i] / size) * size] word_class_prior = self.syntax_topics_model.get_class_prior_for_word(word) best_hyp_class_prior_sum.append(self.next_ys_class_prior_sum[-1][int(best_scores_id[i] / size)] + word_class_prior) self.next_ys_class_prior_sum.append(best_hyp_class_prior_sum) self.prev_ks.append(prev_k) self.next_ys.append((best_scores_id - prev_k * num_words)) self.attn.append(attn_out.index_select(0, prev_k)) # exit() self.print_all_words_in_beam() print "############## After new words chosen ###########" else: # beam_scores is only V dimensional vector # Thus for every word add the KL divergence score to the beam score if self.topic_KL_flag: topic_KL_divergence_scores = self.tt.zeros_like(beam_scores) if self.class_KL_flag: class_KL_divergence_scores = self.tt.zeros_like(beam_scores) for i in range(num_words): word = self.vocab.itos[i] if "<unk>" in word: if self.topic_KL_flag: topic_KL_divergence_scores[i] = 1000000.0 if self.class_KL_flag: class_KL_divergence_scores[i] = 1000000.0 beam_scores[i] = -1000000.0 continue # KL for Topic priors of the first word if self.topic_KL_flag: word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word) word_topic_prior += self.beta # topic_KL_divergence_scores[i] = entropy(self.source_topic_prior, word_topic_prior) topic_KL_divergence_scores[i] = self.syntax_topics_model.KL_divergence(self.source_topic_prior, word_topic_prior) # KL for Class priors of the first word if self.class_KL_flag: word_class_prior = self.syntax_topics_model.get_class_prior_for_word(word) word_class_prior += self.beta # class_KL_divergence_scores[i] = entropy(self.source_class_prior, word_class_prior) class_KL_divergence_scores[i] = self.syntax_topics_model.KL_divergence(self.source_class_prior, word_class_prior) overall_scores = beam_scores - ((self.alpha * topic_KL_divergence_scores) if self.topic_KL_flag else 0.0) - ((self.gamma * class_KL_divergence_scores) if self.class_KL_flag else 0.0) # flat_beam_scores = overall_scores.view(-1) flat_beam_scores = beam_scores.view(-1) # For the first iteration use only the word probabilities best_scores, best_scores_id = flat_beam_scores.topk(self.size, 0, True, True) self.all_scores.append(self.scores) # self.scores = best_scores # will store the word_prob + the KL divergence for hypothesis self.scores = best_scores # will store the word_prob log prob for hypothesis # best_scores_id is flattened, beam * word array, so calculate which # word and beam each score came from size = int(overall_scores.size(0)) prev_k = best_scores_id / num_words # Update next_ys_topic_prior_sum for all beams if self.topic_KL_flag: best_hyp_topic_prior_sum = list() for i in range(self.size): word = self.vocab.itos[best_scores_id[i]] word_topic_prior = self.syntax_topics_model.get_topic_prior_for_word(word) if word_topic_prior[self.syntax_topics_model.num_topics] != 1.0: best_hyp_topic_prior_sum.append(word_topic_prior) else: # starting word is a syntax word. Therefore we will set the prior to zeros best_hyp_topic_prior_sum.append(np.zeros((self.syntax_topics_model.num_topics+1), dtype=np.float)) self.next_ys_topic_prior_sum.append(best_hyp_topic_prior_sum) # Update next_ys_class_prior_sum for all beams if self.class_KL_flag: best_hyp_class_prior_sum = list() for i in range(self.size): word = self.vocab.itos[best_scores_id[i]] word_class_prior = self.syntax_topics_model.get_class_prior_for_word(word) best_hyp_class_prior_sum.append(word_class_prior) self.next_ys_class_prior_sum.append(best_hyp_class_prior_sum) self.prev_ks.append(prev_k) self.next_ys.append((best_scores_id - prev_k * num_words)) self.attn.append(attn_out.index_select(0, prev_k)) if self.global_scorer is not None: self.global_scorer.update_global_state(self) for i in range(self.next_ys[-1].size(0)): if self.next_ys[-1][i] == self._eos: s = self.scores[i] timestep = len(self.next_ys) if self.global_scorer is not None: global_scores = self.global_scorer.score(self, self.scores) s = global_scores[i] self.finished.append((s, len(self.next_ys) - 1, i)) # TODO: Experimental!! Dividing the finished scores by their lenghts to be fair # self.finished.append((s/float(len(self.next_ys) - 1), len(self.next_ys) - 1, i)) ##NOTE: Custom code if self.finished_marker[i] == -1: # print "SET AND FORGET FOR ", i, "#$#$#$#$##$" self.finished_marker[i] = len(self.next_ys) - 1 # End condition is when top-of-beam is EOS and no global score. if self.next_ys[-1][0] == self._eos: # self.all_scores.append(self.scores) self.eos_top = True ##NOTE: Debugging # print word_probs, "$$" # print self.get_current_state(), "$$" # self.print_all_words_in_beam() # print "############## Beam Advance ###########" def done(self): return self.eos_top and len(self.finished) >= self.n_best def sort_finished(self, minimum=None): if minimum is not None: i = 0 # Add from beam until we have minimum outputs. while len(self.finished) < minimum: s = self.scores[i] if self.global_scorer is not None: global_scores = self.global_scorer.score(self, self.scores) s = global_scores[i] self.finished.append((s, len(self.next_ys) - 1, i)) # print self.finished # exit() self.finished.sort(key=lambda a: -a[0]) scores = [sc for sc, _, _ in self.finished] ks = [(t, k) for _, t, k in self.finished] return scores, ks def get_hyp_with_class(self, timestep, k): """ Walk back to construct the full hypothesis while also storing the class/topic number """ hyp, class_or_topic = [], [] # print len(self.next_ys), len(self.next_class_or_topics), len(self.next_class_or_topic_numbers) for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1): hyp.append(self.next_ys[j+1][k]) class_or_topic.append("{}{}".format("C" if self.next_class_or_topics[j][k] == 1 else "T", self.next_class_or_topic_numbers[j][k])) k = self.prev_ks[j][k] class_or_topic.reverse() return hyp[::-1], class_or_topic def get_hyp(self, timestep, k): """ Walk back to construct the full hypothesis. """ hyp, attn = [], [] for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1): hyp.append(self.next_ys[j+1][k]) attn.append(self.attn[j][k]) k = self.prev_ks[j][k] return hyp[::-1], torch.stack(attn[::-1]) class GNMTGlobalScorer(object): """ NMT re-ranking score from "Google's Neural Machine Translation System" :cite:`wu2016google` Args: alpha (float): length parameter beta (float): coverage parameter """ def __init__(self, alpha, beta): self.alpha = alpha self.beta = beta def score(self, beam, logprobs): "Additional term add to log probability" cov = beam.global_state["coverage"] pen = self.beta * torch.min(cov, cov.clone().fill_(1.0)).log().sum(1) l_term = (((5 + len(beam.next_ys)) ** self.alpha) / ((5 + 1) ** self.alpha)) return (logprobs / l_term) + pen def update_global_state(self, beam): "Keeps the coverage vector as sum of attens" if len(beam.prev_ks) == 1: beam.global_state["coverage"] = beam.attn[-1] else: beam.global_state["coverage"] = beam.global_state["coverage"] \ .index_select(0, beam.prev_ks[-1]).add(beam.attn[-1]) <file_sep># Improving Response Quality with Backward Reasoningin Open-domain Dialogue Systems This is the codebase for paper: "[Improving Response Quality with Backward Reasoningin Open-domain Dialogue Systems](https://arxiv.org/abs/2105.00079)". ## Requirements: * **Pytorch-1.1** * Python 2.7 * CUDA 9.2+ (For GPU) #### The main function for training is in train.py To process a new dataset, run: ``` $ python -u preprocess.py -train_src $train_src -train_tgt $train_tgt -train_ctx $train_ctx -valid_src $valid_src -valid_tgt $valid_tgt -valid_ctx $valid_ctx -save_data /daily_dialog/pair_daily -dynamic_dict -share_vocab -src_seq_length 45 -ctx_seq_length 100 -tgt_seq_length 45 ``` $train_tgt is the path of target response in training set (utt at step t); $train_src is the path of source utteracne in training set (utt at step t-1); $train_ctx is the context utt (utt at step t-2). To train a new model, just run: ``` $ python train.py -data data/mirror_dailydialog -save_model /model_dir/model_prefix -gpuid 0 -encoder_type rnn -param_init 0.08 -batch_size 128 -learning_rate 0.001 -optim adam -max_grad_norm 2 -word_vec_size 300 -enc_layers 2 -dec_layers 2 -rnn_size 1000 -epochs 65 -learning_rate_decay 0.98 -z_dim 100 -start_decay_at 3 -kl_balance 0.2 -mirror_type mirror -share_embeddings ``` More hyper-parameter options can be found in file opts.py. Since this code is based on the open-nmt framework, you can go through the open-nmt instructions or the file README_OpenNMT.md if you want. To generate the responses with a trained model, just run: ``` python -u translate.py -model $model -src $test_src -tgt $test_tgt -ctx $test_ctx -output $mirror_output_2 -attn_debug -beam_size 10 -n_best 1 -batch_size 1 -verbose -gpu 0 -use_dc -1 ``` $mirror_output_2 is for the file to save generated dialogues. If you use the code in this repository, feel free to cite our publication [Improving Response Quality with Backward Reasoningin Open-domain Dialogue Systems](https://arxiv.org/abs/2105.00079): ``` @article{li2021mirror, title={Improving Response Quality with Backward Reasoningin Open-domain Dialogue Systems}, author={<NAME> <NAME> <NAME>}, journal={SIGIR 2021}, year={2021} } ``` <file_sep>from __future__ import division import torch import numpy as np #Adding the topic and syntax probability scores to the scores from Decoder class Beam(object): """ Class for managing the internals of the beam search process. Takes care of beams, back pointers, and scores. Args: size (int): beam size pad, bos, eos (int): indices of padding, beginning, and ending. vocab (vocab): vocab of the target syntax_topics_model (Syntax and Topics module): This is an object of the class which will have the topics and classes word probabilities source (list): list of source indices which will be the source sentence targets (list of list): list of taget sentences each of which is a list of indices of the full hypothesis generated till now n_best (int): nbest size to use cuda (bool): use gpu global_scorer (:obj:`GlobalScorer`) """ def __init__(self, size, pad, bos, eos, vocab, syntax_topics_model, source, n_best=1, cuda=False, global_scorer=None, min_length=0): self.size = size self.use_cuda = cuda # self.tt = torch.cuda if cuda else torch self.tt = torch # The score for each translation on the beam. self.scores = self.tt.FloatTensor(size).zero_() if self.use_cuda: self.scores = self.scores.cuda() self.all_scores = [] # The backpointers at each time-step. self.prev_ks = [] # The outputs at each time-step. self.next_ys = [self.tt.LongTensor(size) .fill_(pad)] if self.use_cuda: self.next_ys = [self.tt.LongTensor(size) .fill_(pad).cuda()] self.next_ys[0][0] = bos self.next_ys_topic_prior_sum = [] # Store the sum of the weighted topic prior for the entire hypothesis # Has EOS topped the beam yet. self._eos = eos self.eos_top = False # The attentions (matrix) for each time. self.attn = [] # Time and k pair for finished. self.finished = [] self.n_best = n_best # Information for global scoring. self.global_scorer = global_scorer self.global_state = {} # Minimum prediction length self.min_length = min_length ##NOTE: Custom code self.vocab = vocab self.finished_marker = [-1]*size self.syntax_topics_model = syntax_topics_model self.source = [self.vocab.itos[word_id] for word_id in source] print self.source self.source_topic_prior = np.zeros(self.syntax_topics_model.num_topics, dtype=np.float) word_prev = "<s>" for word in self.source: self.source_topic_prior += self.syntax_topics_model.get_weighted_topic_word_probability(word, word_prev) word_prev = word print self.source_topic_prior self.L = 50 # Number of words to be chosen for the similarity consideration # Note: alpha 0.5 was used for the interpolation objective # self.alpha = 0.5 # multiplicative factor for the Syntax Topic log probability self.alpha = 2.5 # multiplicative factor for the Syntax Topic log probability self.iteration_multiplier = 0.25 # print vocab.itos[0] # print vocab.itos[bos] # print vocab.itos[self._eos] # print vocab.__dict__.keys() # print vocab.unk_init # print type(vocab) def print_hyp(self, hyp, class_or_topic = None): for i, word_id in enumerate(hyp): if class_or_topic: print "{}_{} ".format(self.vocab.itos[word_id], class_or_topic[i]), else: print "{} ".format(self.vocab.itos[word_id]), ##NOTE: Custom function for debugging def print_all_words_in_beam(self): # Uses the vocab and prints the list of next_ys for i in range(self.size): timestep = len(self.next_ys) # if self.finished_marker[i] != -1: # timestep = self.finished_marker[i] if timestep > 1: hyp, _ = self.get_hyp(timestep, i) self.print_hyp(hyp) print "$$$" # print "" def print_received_targets(self): for i in range(len(self.targets)): self.print_hyp(self.targets[i]) print "" print "############### Received Targets ############" def print_the_top_choices(self, best_choices): w, h = best_choices.size() for i in range(w): for j in range(h): print "{} ".format(self.vocab.itos[best_choices[i,j]]), print "" def get_current_state(self): "Get the outputs for the current timestep." return self.next_ys[-1] def get_current_origin(self): "Get the backpointers for the current timestep." return self.prev_ks[-1] def advance(self, word_probs, attn_out): print "Advancing beam" """ Given prob over words for every last beam `wordLk` and attention `attn_out`: Compute and update the beam search. Parameters: * `word_probs`- probs of advancing from the last step (K x words) * `attn_out`- attention at the last step Returns: True if beam search is complete. """ num_words = word_probs.size(1) # force the output to be longer than self.min_length cur_len = len(self.next_ys) if cur_len < self.min_length: for k in range(len(word_probs)): word_probs[k][self._eos] = -1e20 # Sum the previous scores. if len(self.prev_ks) > 0: beam_scores = word_probs + \ self.scores.unsqueeze(1).expand_as(word_probs) # Don't let EOS have children. for i in range(self.next_ys[-1].size(0)): if self.next_ys[-1][i] == self._eos: beam_scores[i] = -1e20 else: beam_scores = word_probs[0] #TODO: 1) find the last word for each beam # 2) For each possible hypothesis find the Topic modeling probability as Source sentence weighted topic prior * current word weighted topic prior # 3) Weighted add the syntax and topic scores to beam_scores and just calculate the next_ys and backpointers as normal if len(self.prev_ks) > 0: per_beam_words = self.next_ys[-1] per_beam_prev_topic_probability = self.next_ys_topic_prior_sum[-1] # print "Next iter" syntax_topic_scores = self.tt.zeros_like(beam_scores) for i in range(self.size): word_prev = self.vocab.itos[per_beam_words[i]] hyp_topic_probability = per_beam_prev_topic_probability[i] for j in range(num_words): word = self.vocab.itos[j] # Manually discourage unk by setting large negative syntax_topic_probability if "<unk>" in word: unk_id = j syntax_topic_score = (self.syntax_topics_model.get_weighted_topic_word_probability(word, word_prev) + hyp_topic_probability).dot(self.source_topic_prior) syntax_topic_scores[i][j] = syntax_topic_score syntax_topic_scores /= float(len(self.source) + len(self.next_ys)) # Note: Probability interpolation doesn't work because the model then chooses all the sentences mainly from the RNN and barely any words from the topic part are chosen # overall_scores = self.tt.log(self.tt.exp(beam_scores) + self.alpha * syntax_topic_scores) iteration = len(self.prev_ks) overall_scores = beam_scores + self.alpha * np.tanh(iteration * self.iteration_multiplier) * self.tt.log(syntax_topic_scores) # adaptive_alpha = beam_scores.max() / self.tt.log(syntax_topic_scores).max() * 0.5 # overall_scores = beam_scores + adaptive_alpha * self.tt.log(syntax_topic_scores) beam_mean = beam_scores.topk(30)[0].mean() syntax_topic_scores_mean = self.tt.log(syntax_topic_scores.topk(30)[0]).mean() # print adaptive_alpha # print beam_mean, syntax_topic_scores_mean, beam_mean / syntax_topic_scores_mean # print beam_scores.max(), self.tt.log(syntax_topic_scores).max(), beam_scores.max() / self.tt.log(syntax_topic_scores).max() # print beam_scores.min(), self.tt.log(syntax_topic_scores).min(), beam_scores.min() / self.tt.log(syntax_topic_scores).min() for i in range(self.size): overall_scores[i][unk_id] = -100000.0 # print "Overall Score" # print overall_scores # print overall_scores.size() # self.print_all_words_in_beam() # print "############## Before new words chosen ###########" size = int(overall_scores.size(1)) # print "Size of the overall_scores = ", size flat_beam_scores = overall_scores.view(-1) best_scores, best_scores_id = flat_beam_scores.topk(self.size, 0, True, True) # We will debug the individual scores of the best candidates word_prob_best_scores = self.tt.zeros_like(best_scores) for i in range(self.size): word_prob_best_scores[i] = beam_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size] syntax_topic_best_scores = self.tt.zeros_like(best_scores) for i in range(self.size): syntax_topic_best_scores[i] = syntax_topic_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size] print best_scores print word_prob_best_scores print syntax_topic_best_scores print self.alpha, self.alpha * np.tanh(iteration * self.iteration_multiplier) print self.alpha * np.tanh(iteration * self.iteration_multiplier) * self.tt.log(syntax_topic_best_scores) # print word_prob_best_scores + self.alpha * syntax_topic_best_scores size = int(overall_scores.size(1)) prev_k = best_scores_id / num_words best_hyp_topic_prior_sum = list() for i in range(self.size): word = self.vocab.itos[best_scores_id[i] - int(best_scores_id[i] / size) * size] word_prev_id = self.next_ys[-1][int(best_scores_id[i] / size)] word_prev = self.vocab.itos[word_prev_id] word_topic_prior = self.syntax_topics_model.get_weighted_topic_word_probability(word, word_prev) best_hyp_topic_prior_sum.append(self.next_ys_topic_prior_sum[-1][int(best_scores_id[i] / size)] + word_topic_prior) self.next_ys_topic_prior_sum.append(best_hyp_topic_prior_sum) self.prev_ks.append(prev_k) self.next_ys.append((best_scores_id - prev_k * num_words)) self.attn.append(attn_out.index_select(0, prev_k)) # exit() self.print_all_words_in_beam() print "############## After new words chosen ###########" else: # beam_scores is only V dimensional vector # Thus for every word add the syntax_topic probability to the beam score syntax_topic_scores = self.tt.zeros_like(beam_scores) for i in range(num_words): word = self.vocab.itos[i] if "<unk>" in word: unk_id = i syntax_topic_score = self.syntax_topics_model.get_weighted_topic_word_probability(word, "<s>").dot(self.source_topic_prior) syntax_topic_scores[i] = syntax_topic_score # overall_scores = beam_scores + self.alpha * self.tt.log(syntax_topic_scores) overall_scores = beam_scores print "Unk id is", unk_id overall_scores[unk_id] = -100000.0 flat_beam_scores = overall_scores.view(-1) best_scores, best_scores_id = flat_beam_scores.topk(self.size, 0, True, True) self.all_scores.append(self.scores) self.scores = best_scores # will store the word_prob + the topic log prob for hypothesis # best_scores_id is flattened, beam * word array, so calculate which # word and beam each score came from size = int(overall_scores.size(0)) prev_k = best_scores_id / num_words # next_class_or_topic = self.tt.zeros_like(prev_k) # for i in range(self.size): # next_class_or_topic[i] = int(class_or_topics[best_scores_id[i]]) # print prev_k # print overall_scores # print next_class_or_topic # print next_class_or_topic_number # print best_scores_id best_hyp_topic_prior_sum = list() for i in range(self.size): word = self.vocab.itos[best_scores_id[i]] word_topic_prior = self.syntax_topics_model.get_weighted_topic_word_probability(word, "<s>") best_hyp_topic_prior_sum.append(word_topic_prior) self.next_ys_topic_prior_sum.append(best_hyp_topic_prior_sum) self.prev_ks.append(prev_k) self.next_ys.append((best_scores_id - prev_k * num_words)) self.attn.append(attn_out.index_select(0, prev_k)) if self.global_scorer is not None: self.global_scorer.update_global_state(self) for i in range(self.next_ys[-1].size(0)): if self.next_ys[-1][i] == self._eos: s = self.scores[i] timestep = len(self.next_ys) if self.global_scorer is not None: global_scores = self.global_scorer.score(self, self.scores) s = global_scores[i] self.finished.append((s, len(self.next_ys) - 1, i)) # TODO: Experimental!! Dividing the finished scores by their lenghts to be fair # self.finished.append((s/float(len(self.next_ys) - 1), len(self.next_ys) - 1, i)) ##NOTE: Custom code if self.finished_marker[i] == -1: # print "SET AND FORGET FOR ", i, "#$#$#$#$##$" self.finished_marker[i] = len(self.next_ys) - 1 # End condition is when top-of-beam is EOS and no global score. if self.next_ys[-1][0] == self._eos: # self.all_scores.append(self.scores) self.eos_top = True ##NOTE: Debugging # print word_probs, "$$" # print self.get_current_state(), "$$" # self.print_all_words_in_beam() # print "############## Beam Advance ###########" def done(self): return self.eos_top and len(self.finished) >= self.n_best def sort_finished(self, minimum=None): if minimum is not None: i = 0 # Add from beam until we have minimum outputs. while len(self.finished) < minimum: s = self.scores[i] if self.global_scorer is not None: global_scores = self.global_scorer.score(self, self.scores) s = global_scores[i] self.finished.append((s, len(self.next_ys) - 1, i)) # print self.finished # exit() self.finished.sort(key=lambda a: -a[0]) scores = [sc for sc, _, _ in self.finished] ks = [(t, k) for _, t, k in self.finished] return scores, ks def get_hyp_with_class(self, timestep, k): """ Walk back to construct the full hypothesis while also storing the class/topic number """ hyp, class_or_topic = [], [] # print len(self.next_ys), len(self.next_class_or_topics), len(self.next_class_or_topic_numbers) for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1): hyp.append(self.next_ys[j+1][k]) class_or_topic.append("{}{}".format("C" if self.next_class_or_topics[j][k] == 1 else "T", self.next_class_or_topic_numbers[j][k])) k = self.prev_ks[j][k] class_or_topic.reverse() return hyp[::-1], class_or_topic def get_hyp(self, timestep, k): """ Walk back to construct the full hypothesis. """ hyp, attn = [], [] for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1): hyp.append(self.next_ys[j+1][k]) attn.append(self.attn[j][k]) k = self.prev_ks[j][k] return hyp[::-1], torch.stack(attn[::-1]) class GNMTGlobalScorer(object): """ NMT re-ranking score from "Google's Neural Machine Translation System" :cite:`wu2016google` Args: alpha (float): length parameter beta (float): coverage parameter """ def __init__(self, alpha, beta): self.alpha = alpha self.beta = beta def score(self, beam, logprobs): "Additional term add to log probability" cov = beam.global_state["coverage"] pen = self.beta * torch.min(cov, cov.clone().fill_(1.0)).log().sum(1) l_term = (((5 + len(beam.next_ys)) ** self.alpha) / ((5 + 1) ** self.alpha)) return (logprobs / l_term) + pen def update_global_state(self, beam): "Keeps the coverage vector as sum of attens" if len(beam.prev_ks) == 1: beam.global_state["coverage"] = beam.attn[-1] else: beam.global_state["coverage"] = beam.global_state["coverage"] \ .index_select(0, beam.prev_ks[-1]).add(beam.attn[-1]) <file_sep>import codecs import numpy as np import timeit import math class SyntaxTopicModel(object): """This class is the partial implementation of "Integrating Topics and Syntax" <NAME> et al. We will only use the trained model to get the probabilities of different topics and classes """ def read_vocabulary(self): self.vocab_itos = list() self.vocab_stoi = dict() with codecs.open(self.vocabulary_file, "r", "utf-8") as reader: # Each line is a word and its frequency i = 0 for line in reader: line = line.strip() line_spl = line.split() if line_spl[0] == "UNknown": line_spl[0] = "<unk>" self.vocab_itos.append(line_spl[0]) self.vocab_stoi[line_spl[0]] = i i += 1 def read_documents(self, max_documents = None): self.documents = list() with open(self.documents_file, "r") as reader: for i, line in enumerate(reader): if max_documents and i > max_documents: break self.documents.append(np.fromstring(line, dtype=np.int, sep=' ')) def read_assignments_file(self, filename, variable, t_or_c, max_documents = None): # First line is the number of documents and number of topics/classes # Then rest of the lines are word labels for each document with open(filename, "r") as reader: first_line = next(reader) self.n_docs, num_classes_or_topics = first_line.split() self.n_docs = int(self.n_docs) if t_or_c == 'T': self.num_topics = int(num_classes_or_topics) elif t_or_c == 'C': self.num_classes = int(num_classes_or_topics) else: print "Incorrect T or C choice. Given parameter value =", t_or_c exit() for i, line in enumerate(reader): if max_documents and i > max_documents: break variable.append(np.fromstring(line.strip(), dtype=np.int, sep=' ')) def run_counts(self): self.n_docs = len(self.documents) self.vocab_size = len(self.vocab_itos) # We want the following probabilities # P(w|C) a V * n_C dimensional matrix which gives probability of word given the class count(word_class)/count(class) # P(w|T) a V * n_T dimensional matrix which gives probability of word given the topic count(word_topic)/count(topic) # P(T|w) a n_T * V dimensional matrix which gives probability of Topic given the word count(word_topic)/count(word in all topic) # P(C_|C) a n_C * n_C dimensional matrix which is the transition probability of going from a class to another class # Calculate counts import os CACHE_FOLDER = "/your/folder/folder_dc_mmi/syntax_topic_cache" self.num_word_in_class_cache_file = os.path.join(CACHE_FOLDER, "num_word_in_class_cache.npy") self.num_word_in_topic_cache_file = os.path.join(CACHE_FOLDER, "num_word_in_topic_cache.npy") self.num_transitions_cache_file = os.path.join(CACHE_FOLDER, "num_transitions_cache.npy") if not self.recount and os.path.isfile(self.num_word_in_class_cache_file) and os.path.isfile(self.num_word_in_topic_cache_file) and os.path.isfile(self.num_transitions_cache_file): # if possible load from cache print "WARNING: Reloading stuff from cache!!" self.num_word_in_class = np.load(self.num_word_in_class_cache_file) self.num_word_in_topic = np.load(self.num_word_in_topic_cache_file) self.num_transitions = np.load(self.num_transitions_cache_file) else: # Compute from the data self.num_word_in_class = np.zeros((self.vocab_size, self.num_classes), dtype=np.float) self.num_word_in_topic = np.zeros((self.vocab_size, self.num_topics), dtype=np.float) self.num_transitions = np.zeros((self.num_classes, self.num_classes), dtype=np.float) for doc_id, document in enumerate(self.documents): prev_class = -1 for i, word_id in enumerate(document): class_assign = self.class_assignments[doc_id][i] topic_assign = self.topic_assignments[doc_id][i] if class_assign == 0: # Topics class self.num_word_in_topic[word_id][topic_assign] += 1 self.num_word_in_class[word_id][class_assign] += 1 if prev_class != -1: self.num_transitions[prev_class][class_assign] += 1 prev_class = class_assign # Save in cache np.save(self.num_word_in_class_cache_file, self.num_word_in_class) np.save(self.num_word_in_topic_cache_file, self.num_word_in_topic) np.save(self.num_transitions_cache_file, self.num_transitions) # Smooth the word counts by additive smoothing self.num_word_in_class += self.alpha self.num_word_in_topic += self.alpha # self.num_transitions += self.alpha # Calculate the desired probabilities from counts self.P_w_given_c = np.nan_to_num(self.num_word_in_class / np.sum(self.num_word_in_class, axis=0)) self.P_w_given_t = np.nan_to_num(self.num_word_in_topic / np.sum(self.num_word_in_topic, axis=0)) self.P_t_given_w = np.nan_to_num(self.num_word_in_topic.T / np.sum(self.num_word_in_topic.T, axis=0)) self.P_c_given_w = np.nan_to_num(self.num_word_in_class.T / np.sum(self.num_word_in_class.T, axis=0)) self.P_c_given_prev_c = self.num_transitions.T / np.sum(self.num_transitions, axis=1) # Calcualte the probability of Topic class for the next word given previous word # Summation(P(C=0| C_prev) * P(C_prev|word)) self.P_t_given_w_prev = self.P_c_given_prev_c[0,:].dot(self.P_c_given_w) print(self.P_t_given_w_prev.shape) print "Transition probability matrix" print(self.P_c_given_prev_c) print(np.sum(self.P_c_given_prev_c, axis=0)) print(np.sum(self.P_c_given_prev_c, axis=1)) def read_stop_words(self, stop_words_file): stop_words = set() with open(stop_words_file, "r") as reader: for line in reader: line = line.strip() if line: line_spl = line.split("'") if len(line_spl) == 2: stop_words.add(line_spl[0]) stop_words.add("'" + line_spl[1]) else: stop_words.add(line) return stop_words def __init__(self, vocabulary_file, documents_file, class_assignment_file, topic_assignment_file, stop_words_file, max_documents = None, recount = False): start = timeit.default_timer() self.max_documents = max_documents self.vocabulary_file = vocabulary_file self.read_vocabulary() self.documents_file = documents_file self.read_documents(self.max_documents) self.class_assignment_file = class_assignment_file self.topic_assignment_file = topic_assignment_file self.class_assignments = list() self.read_assignments_file(self.class_assignment_file, self.class_assignments, "C", self.max_documents) self.START_CLASS = self.num_classes - 2 self.END_CLASS = self.num_classes - 1 self.topic_assignments = list() self.read_assignments_file(self.topic_assignment_file, self.topic_assignments, "T", self.max_documents) self.stop_words_file = stop_words_file self.stop_words = self.read_stop_words(self.stop_words_file) self.cache = dict() # A dictionary of tuples which will cache the (word_id, prev_class) pair values self.recount = recount # Tells whether to recompute the counts from read data self.alpha = 0.01 # Smoothing the word counts self.beta = 0.000001 # Smoothing for the topic prior of the stop words self.run_counts() print "Total time taken for Syntax and Topics Model initialization = {}sec".format(timeit.default_timer() - start) def get_word_id(self, word): # Given a word check in vocabulary and return the correct word id if present # if the word is of the format word + _ + tag then change it to word # print word word = word.rsplit('_', 1)[0] # print word, "$$" if word in self.vocab_stoi: # print "Hit", word return self.vocab_stoi[word] return self.vocab_stoi["<unk>"] def clear_cache(): self.cache = dict() def get_class_prior_for_word(self, word): word_id = self.get_word_id(word) return self.P_c_given_w[:, word_id] def get_topic_prior_for_word(self, word): word_id = self.get_word_id(word) # class_probs = self.P_c_given_w[:, word_id] # if class_probs[0] == np.max(class_probs) and any(c.isalpha() for c in word) and "<unk>" not in word: # if word == "handsomer": # print word not in self.stop_words # print any(c.isalpha() for c in word) # print "<unk>" not in word # print np.array(self.P_t_given_w[:,word_id]) # print self.vocab_itos[word_id] # print word_id # print self.num_word_in_topic[word_id] # print self.num_word_in_class[word_id] if word not in self.stop_words and any(c.isalpha() for c in word) and "<unk>" not in word and "s>" not in word: prior = list(self.P_t_given_w[:,word_id]) prior.append(self.beta) return np.array(prior) else: prior = np.full((self.num_topics+1), self.beta, dtype=np.float) prior[self.num_topics] = 1.0 return np.array(prior) # Return log probability and the chosen class/topic and type of return def get_log_prob(self, word, prev_class): # retun log(P(w|C)*P(C|prev_class)) word_id = self.get_word_id(word) if (word_id, prev_class) in self.cache: return self.cache[(word_id, prev_class)] probs_for_classes = self.P_w_given_c[word_id,:] * self.P_c_given_prev_c[:,prev_class] probs_for_classes[0] = 0.0 best_class = np.argmax(probs_for_classes) best_class_prob = probs_for_classes[best_class] probs_for_topics = self.P_w_given_t[word_id,:] * self.P_c_given_prev_c[0,prev_class] # 0 is the topics class best_topic = np.argmax(probs_for_topics) best_topic_prob = self.beta * probs_for_topics[best_topic] return_val = -1000000.0 if best_topic_prob > best_class_prob: try: # print "Hit", best_topic_prob, best_class_prob, word, prev_class return_val = (math.log(best_topic_prob), best_topic, "T") except ValueError: if best_topic_prob == 0.0: return_val = (-1000000.0, -1, "T") else: print "Best topic prob is for word {} is topic{} and the value is {}".format(word, best_topic, best_topic_prob) print prev_class print probs_for_classes print probs_for_topics exit() else: try: return_val = (math.log(best_class_prob), best_class, "C") except ValueError: if best_class_prob == 0.0: return_val = (-1000000.0, -1, "C") else: print "Best class prob is for word {} is class{} and the value is {}".format(word, best_class, best_class_prob) print prev_class print probs_for_classes print probs_for_topics exit() self.cache[(word_id, prev_class)] = return_val return return_val def KL_divergence(self, P1, P2): a = np.asarray(P1, dtype=np.float) b = np.asarray(P2, dtype=np.float) # Want to do all the computations in 2 loops sum_a = 0.0 sum_b = 0.0 for i in range(a.shape[0]): if a[i] != 0.0 and b[i] != 0.0: sum_a += a[i] sum_b += b[i] if sum_a == 0.0 or sum_b == 0.0: return 0.0 sum = 0.0 for i in range(a.shape[0]): if a[i] != 0.0 and b[i] != 0.0: sum += a[i]/sum_a * np.log((a[i] / sum_a) / (b[i] / sum_b)) return sum # return np.sum(np.where(a != 0, a * np.log(a / b), 0)) def get_weighted_topic_word_probability(self, word, word_prev): word_id = self.get_word_id(word) word_prev_id = self.get_word_id(word_prev) # We hope that this prior will be small for stop words automatically # prior = list(self.P_t_given_w[:,word_id] * self.P_c_given_w_prev[word_prev_id]) prior = list(self.P_t_given_w[:,word_id] * self.P_c_given_w[0,word_id]) return np.array(prior) <file_sep>from __future__ import division import torch import numpy as np from scipy import spatial # Compute the weights for each word based on the formula in the paper def getWordWeights(weightfile, a=1e-3): if a <=0: # when the parameter makes no sense, use unweighted a = 1.0 word2weight = {} N = 0 with open(weightfile, "r") as reader: for line in reader: line = line.strip() if line: line = line.split() if(len(line) == 2): word2weight[line[0]] = float(line[1]) N += float(line[1]) else: print(line) for key, value in word2weight.iteritems(): word2weight[key] = a / (a + value/N) return word2weight # Gen the word embeddings def getWordEmbeddings(embeddings_file): embeddings = {} with open(embeddings_file, "r") as reader: for line in reader: line = line.strip() line = line.split(" ", 1) embeddings[line[0].strip()] = np.fromstring(line[1], dtype=np.float, sep=" ") print(len(embeddings)) return embeddings def lookupEmbedding(embeddings, w): w = w.lower() # convert hashtag to word if len(w) > 1 and w[0] == '#': w = w.replace("#","") if w in embeddings: return embeddings[w] elif 'UUUNKKK' in embeddings: return embeddings['UUUNKKK'] else: return embeddings[-1] class SIFEmbedding(object): """ Sentence embedding generator class which implements the weighted averaging technique specified in https://openreview.net/pdf?id=SyK00v5xx Args: tgt_vocab (Vocab): This is the target vocab. We want the reweighted embeddings for these words embeddings_file (string): String of the file which contains the original PSL word embeddings weights_file (string): wikipedia word frequencies which will help us estimate unigram probabilities pc_file (string): Numpy file which contains the first principal component of sentence embeddings of the sample of sentences from training data """ def __init__(self, tgt_vocab, embeddings_file, weights_file, pc_file, pad_word_id, a=1e-3): self.vocab = tgt_vocab self.embeddings = getWordEmbeddings(embeddings_file) self.word2weight = getWordWeights(weights_file, a) # Initialize embeddings and weights for the target vocab # itov: index to embedding self.itov = list() for i in range(len(self.vocab.itos)): self.itov.append(lookupEmbedding(self.embeddings, self.vocab.itos[i])) # itow: index to weight self.itow = list() for i in range(len(self.vocab.itos)): # initialize the weight only if its corresponding embedding is present if self.vocab.itos[i] in self.embeddings and self.vocab.itos[i] in self.word2weight: self.itow.append(self.word2weight[self.vocab.itos[i]]) else: self.itow.append(1.0) # no re weighting self.pc = np.load(pc_file) # pc in the shape of (1, 300) # print self.pc.shape self.dim = self.pc.shape[1] self.pad_word_id = pad_word_id self.cache = dict() def clear_cache(self): self.cache = dict() """ Args: word_ids (list): list of word indices of the sentence """ def sentence_embedding(self, word_ids): # 1) Find the weighted average of the list of words given in the arguments # print word_ids # for word_id in word_ids.data: # print word_id word_embs = np.array([self.itov[word_id] for word_id in word_ids if word_id != self.pad_word_id]) word_weights = [self.itow[word_id] for word_id in word_ids if word_id != self.pad_word_id] emb = np.average(word_embs, axis=0, weights=word_weights) # 2) Remove the first principal component from this embedding # NOTE: futher code is shamefully copied from the SIF_embddings.py file. Don't complain if it looks ugly X = emb.reshape(1, self.dim) XX = X - X.dot(self.pc.transpose()) * self.pc emb = XX.reshape(self.dim) return emb def remove_pad_word(self, sent): return tuple([word_id for word_id in sent if word_id != self.pad_word_id]) """ Args: sent1 (list): List of word indices of the first sentence sent2 (list): List of word indices of the second sentence """ def Similarity(self, sent1, sent2): # Cache the sent1 because it is repeating sent1 = self.remove_pad_word(sent1) sent2 = self.remove_pad_word(sent2) if len(sent1) == 0 or len(sent1) == 0: return 0.0 if sent1 in self.cache: emb1 = self.cache[sent1] else: emb1 = self.sentence_embedding(sent1) self.cache[sent1] = emb1 emb2 = self.sentence_embedding(sent2) cos_similarity = 1 - spatial.distance.cosine(emb1, emb2) return cos_similarity """ Args: targets (list of list): List of target sentences (which are essentially list of word indices) sent (list): List of word indices """ def Targets_Similarity(self, targets, sent, max_flag=True): similarity = list() if len(targets) == 0: return 0.0 for i in range(len(targets)): similarity.append(self.Similarity(targets[i], sent)) similarity = np.array(similarity) if max_flag: return np.max(similarity) else: return np.avg(similarity) <file_sep>from __future__ import division import torch import torch.nn as nn from torch.autograd import Variable from torch.nn.utils.rnn import pack_padded_sequence as pack from torch.nn.utils.rnn import pad_packed_sequence as unpack import logging import onmt from onmt.Utils import aeq class Pack(dict): def __getattr__(self, name): return self[name] def add(self, **kwargs): for k, v in kwargs.items(): self[k] = v def copy(self): pack = Pack() for k, v in self.items(): if type(v) is list: pack[k] = list(v) else: pack[k] = v return pack class EncoderBase(nn.Module): """ Base encoder class. Specifies the interface used by different encoder types and required by :obj:`onmt.Models.NMTModel`. .. mermaid:: graph BT A[Input] subgraph RNN C[Pos 1] D[Pos 2] E[Pos N] end F[Context] G[Final] A-->C A-->D A-->E C-->F D-->F E-->F E-->G """ def _check_args(self, input, lengths=None, hidden=None): s_len, n_batch, n_feats = input.size() if lengths is not None: n_batch_, = lengths.size() aeq(n_batch, n_batch_) def forward(self, input, lengths=None, hidden=None): """ Args: input (:obj:`LongTensor`): padded sequences of sparse indices `[src_len x batch x nfeat]` lengths (:obj:`LongTensor`): length of each sequence `[batch]` hidden (class specific): initial hidden state. Returns:k (tuple of :obj:`FloatTensor`, :obj:`FloatTensor`): * final encoder state, used to initialize decoder `[layers x batch x hidden]` * contexts for attention, `[src_len x batch x hidden]` """ raise NotImplementedError class MeanEncoder(EncoderBase): """A trivial non-recurrent encoder. Simply applies mean pooling. Args: num_layers (int): number of replicated layers embeddings (:obj:`onmt.modules.Embeddings`): embedding module to use """ def __init__(self, num_layers, embeddings): super(MeanEncoder, self).__init__() self.num_layers = num_layers self.embeddings = embeddings def forward(self, input, lengths=None, hidden=None): "See :obj:`EncoderBase.forward()`" self._check_args(input, lengths, hidden) emb = self.embeddings(input) s_len, batch, emb_dim = emb.size() mean = emb.mean(0).expand(self.num_layers, batch, emb_dim) return (mean, mean), emb class RNNEncoder(EncoderBase): """ A generic recurrent neural network encoder. Args: rnn_type (:obj:`str`): style of recurrent unit to use, one of [RNN, LSTM, GRU, SRU] bidirectional (bool) : use a bidirectional RNN num_layers (int) : number of stacked layers hidden_size (int) : hidden size of each layer dropout (float) : dropout value for :obj:`nn.Dropout` embeddings (:obj:`onmt.modules.Embeddings`): embedding module to use """ def __init__(self, rnn_type, bidirectional, num_layers, hidden_size, dropout=0.0, embeddings=None): super(RNNEncoder, self).__init__() assert embeddings is not None num_directions = 2 if bidirectional else 1 assert hidden_size % num_directions == 0 hidden_size = hidden_size // num_directions self.embeddings = embeddings self.no_pack_padded_seq = False # Use pytorch version when available. if rnn_type == "SRU": # SRU doesn't support PackedSequence. self.no_pack_padded_seq = True self.rnn = onmt.modules.SRU( input_size=embeddings.embedding_size, hidden_size=hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional) else: self.rnn = getattr(nn, rnn_type)( input_size=embeddings.embedding_size, hidden_size=hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional) def forward(self, input, lengths=None, hidden=None): "See :obj:`EncoderBase.forward()`" self._check_args(input, lengths, hidden) emb = self.embeddings(input) s_len, batch, emb_dim = emb.size() packed_emb = emb if lengths is not None and not self.no_pack_padded_seq: # Lengths data is wrapped inside a Variable. lengths = lengths.view(-1).tolist() packed_emb = pack(emb, lengths) outputs, hidden_t = self.rnn(packed_emb, hidden) if lengths is not None and not self.no_pack_padded_seq: outputs = unpack(outputs)[0] return hidden_t, outputs class RNNDecoderBase(nn.Module): """ Base recurrent attention-based decoder class. Specifies the interface used by different decoder types and required by :obj:`onmt.Models.NMTModel`. .. mermaid:: graph BT A[Input] subgraph RNN C[Pos 1] D[Pos 2] E[Pos N] end G[Decoder State] H[Decoder State] I[Outputs] F[Context] A--emb-->C A--emb-->D A--emb-->E H-->C C-- attn --- F D-- attn --- F E-- attn --- F C-->I D-->I E-->I E-->G F---I Args: rnn_type (:obj:`str`): style of recurrent unit to use, one of [RNN, LSTM, GRU, SRU] bidirectional_encoder (bool) : use with a bidirectional encoder num_layers (int) : number of stacked layers hidden_size (int) : hidden size of each layer attn_type (str) : see :obj:`onmt.modules.GlobalAttention` coverage_attn (str): see :obj:`onmt.modules.GlobalAttention` context_gate (str): see :obj:`onmt.modules.ContextGate` copy_attn (bool): setup a separate copy attention mechanism dropout (float) : dropout value for :obj:`nn.Dropout` embeddings (:obj:`onmt.modules.Embeddings`): embedding module to use """ def __init__(self, rnn_type, bidirectional_encoder, num_layers, hidden_size, attn_type="general", coverage_attn=False, context_gate=None, copy_attn=False, dropout=0.0, embeddings=None): super(RNNDecoderBase, self).__init__() # Basic attributes. self.decoder_type = 'rnn' self.bidirectional_encoder = bidirectional_encoder self.num_layers = num_layers self.hidden_size = hidden_size self.embeddings = embeddings self.dropout = nn.Dropout(dropout) # Build the RNN. self.rnn = self._build_rnn(rnn_type, self._input_size, hidden_size, num_layers, dropout) # Set up the context gate. self.context_gate = None if context_gate is not None: self.context_gate = onmt.modules.context_gate_factory( context_gate, self._input_size, hidden_size, hidden_size, hidden_size ) # Set up the standard attention. self._coverage = coverage_attn self.attn = onmt.modules.GlobalAttention( hidden_size, coverage=coverage_attn, attn_type=attn_type ) # Set up a separated copy attention layer, if needed. self._copy = False if copy_attn: self.copy_attn = onmt.modules.GlobalAttention( hidden_size, attn_type=attn_type ) self._copy = True def forward(self, input, context, state, context_lengths=None): """ Args: input (`LongTensor`): sequences of padded tokens `[tgt_len x batch x nfeats]`. context (`FloatTensor`): vectors from the encoder `[src_len x batch x hidden]`. state (:obj:`onmt.Models.DecoderState`): decoder state object to initialize the decoder context_lengths (`LongTensor`): the padded source lengths `[batch]`. Returns: (`FloatTensor`,:obj:`onmt.Models.DecoderState`,`FloatTensor`): * outputs: output from the decoder `[tgt_len x batch x hidden]`. * state: final hidden state from the decoder * attns: distribution over src at each tgt `[tgt_len x batch x src_len]`. """ # Args Check assert isinstance(state, RNNDecoderState) input_len, input_batch, _ = input.size() contxt_len, contxt_batch, _ = context.size() aeq(input_batch, contxt_batch) # END Args Check # Run the forward pass of the RNN. hidden, outputs, attns, coverage = self._run_forward_pass( input, context, state, context_lengths=context_lengths) # Update the state with the result. final_output = outputs[-1] state.update_state(hidden, final_output.unsqueeze(0), coverage.unsqueeze(0) if coverage is not None else None) # Concatenates sequence of tensors along a new dimension. outputs = torch.stack(outputs) for k in attns: attns[k] = torch.stack(attns[k]) return outputs, state, attns def _fix_enc_hidden(self, h): """ The encoder hidden is (layers*directions) x batch x dim. We need to convert it to layers x batch x (directions*dim). """ # logging.info("hidden size: {}".format(h.size())) #(8, 256, 500) if self.bidirectional_encoder: h = torch.cat([h[0:h.size(0):2], h[1:h.size(0):2]], 2) # logging.info("hidden size: {}".format(h.size())) #(4, 256, 1000) return h def init_decoder_state(self, src, context, enc_hidden): if isinstance(enc_hidden, tuple): # LSTM return RNNDecoderState(context, self.hidden_size, tuple([self._fix_enc_hidden(enc_hidden[i]) for i in range(len(enc_hidden))])) else: # GRU return RNNDecoderState(context, self.hidden_size, self._fix_enc_hidden(enc_hidden)) class StdRNNDecoder(RNNDecoderBase): """ Standard fully batched RNN decoder with attention. Faster implementation, uses CuDNN for implementation. See :obj:`RNNDecoderBase` for options. Based around the approach from "Neural Machine Translation By Jointly Learning To Align and Translate" :cite:`Bahdanau2015` Implemented without input_feeding and currently with no `coverage_attn` or `copy_attn` support. """ def _run_forward_pass(self, input, context, state, context_lengths=None): """ Private helper for running the specific RNN forward pass. Must be overriden by all subclasses. Args: input (LongTensor): a sequence of input tokens tensors of size (len x batch x nfeats). context (FloatTensor): output(tensor sequence) from the encoder RNN of size (src_len x batch x hidden_size). state (FloatTensor): hidden state from the encoder RNN for initializing the decoder. context_lengths (LongTensor): the source context lengths. Returns: hidden (Variable): final hidden state from the decoder. outputs ([FloatTensor]): an array of output of every time step from the decoder. attns (dict of (str, [FloatTensor]): a dictionary of different type of attention Tensor array of every time step from the decoder. coverage (FloatTensor, optional): coverage from the decoder. """ assert not self._copy # TODO, no support yet. assert not self._coverage # TODO, no support yet. # Initialize local and return variables. outputs = [] attns = {"std": []} coverage = None emb = self.embeddings(input) # Run the forward pass of the RNN. if isinstance(self.rnn, nn.GRU): rnn_output, hidden = self.rnn(emb, state.hidden[0]) else: rnn_output, hidden = self.rnn(emb, state.hidden) # Result Check input_len, input_batch, _ = input.size() output_len, output_batch, _ = rnn_output.size() aeq(input_len, output_len) aeq(input_batch, output_batch) # END Result Check # Calculate the attention. attn_outputs, attn_scores = self.attn( rnn_output.transpose(0, 1).contiguous(), # (output_len, batch, d) context.transpose(0, 1), # (contxt_len, batch, d) context_lengths=context_lengths ) attns["std"] = attn_scores # Calculate the context gate. if self.context_gate is not None: outputs = self.context_gate( emb.view(-1, emb.size(2)), rnn_output.view(-1, rnn_output.size(2)), attn_outputs.view(-1, attn_outputs.size(2)) ) outputs = outputs.view(input_len, input_batch, self.hidden_size) outputs = self.dropout(outputs) else: outputs = self.dropout(attn_outputs) # (input_len, batch, d) # Return result. return hidden, outputs, attns, coverage def _build_rnn(self, rnn_type, input_size, hidden_size, num_layers, dropout): """ Private helper for building standard decoder RNN. """ # Use pytorch version when available. if rnn_type == "SRU": return onmt.modules.SRU( input_size, hidden_size, num_layers=num_layers, dropout=dropout) return getattr(nn, rnn_type)( input_size, hidden_size, num_layers=num_layers, dropout=dropout) @property def _input_size(self): """ Private helper returning the number of expected features. """ return self.embeddings.embedding_size class InputFeedRNNDecoder(RNNDecoderBase): """ Input feeding based decoder. See :obj:`RNNDecoderBase` for options. Based around the input feeding approach from "Effective Approaches to Attention-based Neural Machine Translation" :cite:`Luong2015` .. mermaid:: graph BT A[Input n-1] AB[Input n] subgraph RNN E[Pos n-1] F[Pos n] E --> F end G[Encoder] H[Context n-1] A --> E AB --> F E --> H G --> H """ def _run_forward_pass(self, input, context, state, context_lengths=None): """ See StdRNNDecoder._run_forward_pass() for description of arguments and return values. """ # Additional args check. output = state.input_feed.squeeze(0) output_batch, _ = output.size() input_len, input_batch, _ = input.size() aeq(input_batch, output_batch) # END Additional args check. # Initialize local and return variables. outputs = [] attns = {"std": []} if self._copy: attns["copy"] = [] if self._coverage: attns["coverage"] = [] emb = self.embeddings(input) assert emb.dim() == 3 # len x batch x embedding_dim hidden = state.hidden coverage = state.coverage.squeeze(0) \ if state.coverage is not None else None # Input feed concatenates hidden state with # input at every time step. for i, emb_t in enumerate(emb.split(1)): emb_t = emb_t.squeeze(0) emb_t = torch.cat([emb_t, output], 1) rnn_output, hidden = self.rnn(emb_t, hidden) attn_output, attn = self.attn( rnn_output, context.transpose(0, 1), context_lengths=context_lengths) if self.context_gate is not None: # TODO: context gate should be employed # instead of second RNN transform. output = self.context_gate( emb_t, rnn_output, attn_output ) output = self.dropout(output) else: output = self.dropout(attn_output) outputs += [output] attns["std"] += [attn] # Update the coverage attention. if self._coverage: coverage = coverage + attn \ if coverage is not None else attn attns["coverage"] += [coverage] # Run the forward pass of the copy attention layer. if self._copy: _, copy_attn = self.copy_attn(output, context.transpose(0, 1)) attns["copy"] += [copy_attn] # Return result. return hidden, outputs, attns, coverage def _build_rnn(self, rnn_type, input_size, hidden_size, num_layers, dropout): assert not rnn_type == "SRU", "SRU doesn't support input feed! " \ "Please set -input_feed 0!" if rnn_type == "LSTM": stacked_cell = onmt.modules.StackedLSTM else: stacked_cell = onmt.modules.StackedGRU return stacked_cell(num_layers, input_size, hidden_size, dropout) @property def _input_size(self): """ Using input feed by concatenating input with attention vectors. """ return self.embeddings.embedding_size + self.hidden_size class NMTModel(nn.Module): """ Core trainable object in OpenNMT. Implements a trainable interface for a simple, generic encoder + decoder model. Args: encoder (:obj:`EncoderBase`): an encoder object decoder (:obj:`RNNDecoderBase`): a decoder object multi<gpu (bool): setup for multigpu support """ def __init__(self, encoder, decoder, multigpu=False): self.multigpu = multigpu super(NMTModel, self).__init__() self.encoder = encoder self.decoder = decoder def forward(self, src, tgt, lengths, dec_state=None): """Forward propagate a `src` and `tgt` pair for training. Possible initialized with a beginning decoder state. Args: src (:obj:`Tensor`): a source sequence passed to encoder. typically for inputs this will be a padded :obj:`LongTensor` of size `[len x batch x features]`. however, may be an image or other generic input depending on encoder. tgt (:obj:`LongTensor`): a target sequence of size `[tgt_len x batch]`. lengths(:obj:`LongTensor`): the src lengths, pre-padding `[batch]`. dec_state (:obj:`DecoderState`, optional): initial decoder state Returns: (:obj:`FloatTensor`, `dict`, :obj:`onmt.Models.DecoderState`): * decoder output `[tgt_len x batch x hidden]` * dictionary attention dists of `[tgt_len x batch x src_len]` * final decoder state """ tgt = tgt[:-1] # exclude last target from inputs enc_hidden, context = self.encoder(src, lengths) enc_state = self.decoder.init_decoder_state(src, context, enc_hidden) out, dec_state, attns = self.decoder(tgt, context, enc_state if dec_state is None else dec_state, context_lengths=lengths) if self.multigpu: # Not yet supported on multi-gpu dec_state = None attns = None return out, attns, dec_state class DecoderState(object): """Interface for grouping together the current state of a recurrent decoder. In the simplest case just represents the hidden state of the model. But can also be used for implementing various forms of input_feeding and non-recurrent models. Modules need to implement this to utilize beam search decoding. """ def detach(self): for h in self._all: if h is not None: h.detach_() def beam_update(self, idx, positions, beam_size): for e in self._all: a, br, d = e.size() sent_states = e.view(a, beam_size, br // beam_size, d)[:, :, idx] sent_states.data.copy_( sent_states.data.index_select(1, positions)) class RNNDecoderState(DecoderState): def __init__(self, context, hidden_size, rnnstate): """ Args: context (FloatTensor): output from the encoder of size len x batch x rnn_size. hidden_size (int): the size of hidden layer of the decoder. rnnstate (Variable): final hidden state from the encoder. transformed to shape: layers x batch x (directions*dim). input_feed (FloatTensor): output from last layer of the decoder. coverage (FloatTensor): coverage output from the decoder. """ if not isinstance(rnnstate, tuple): self.hidden = (rnnstate,) else: self.hidden = rnnstate self.coverage = None # Init the input feed. batch_size = context.size(1) h_size = (batch_size, hidden_size) self.input_feed = Variable(context.data.new(*h_size).zero_(), requires_grad=False).unsqueeze(0) @property def _all(self): return self.hidden + (self.input_feed,) def update_state(self, rnnstate, input_feed, coverage): if not isinstance(rnnstate, tuple): self.hidden = (rnnstate,) else: self.hidden = rnnstate self.input_feed = input_feed self.coverage = coverage def repeat_beam_size_times(self, beam_size): """ Repeat beam_size times along batch dimension. """ vars = [Variable(e.data.repeat(1, beam_size, 1)) for e in self._all] self.hidden = tuple(vars[:-1]) self.input_feed = vars[-1] class MirrorModel(nn.Module): """ Core trainable object in OpenNMT. Implements a trainable interface for a simple, generic encoder + decoder model. Args: encoder (:obj:`EncoderBase`): an encoder object decoder (:obj:`RNNDecoderBase`): a decoder object multi<gpu (bool): setup for multigpu support This func only support LSTM now. """ def __init__(self, encoder_utt, encoder_utt_y, encoder_ctx, decoder_cxz2y, decoder_cz2x, decoder_cyz2x, decoder_cz2y,multigpu=False, opt=None): self.multigpu = multigpu super(MirrorModel, self).__init__() self.bidirectional_encoder = opt.brnn self.bidirectional_ctx_encoder = opt.ctx_bid self.hidden_size = opt.rnn_size self.encoder = encoder_utt # self.encoder_y = encoder_utt_y self.encoder_y = encoder_utt self.encoder_ctx = encoder_ctx self.decoder_cxz2y = decoder_cxz2y self.decoder_cz2x = decoder_cz2x self.decoder_cyz2x = decoder_cyz2x self.decoder_cz2y = decoder_cz2y self.encoder_state_fix_xy = EncoderStateFix(opt) self.encoder_state_fix_ctx = EncoderStateFix(opt) self.encoder2z = EncoderState2Z(opt) self.decoder_init_builder = BuildDecoderState(opt) # self.encoder_state_fix_xy = EncoderStateFix_test(opt) # self.encoder_state_fix_ctx = EncoderStateFix_test(opt) # self.encoder2z = EncoderState2Z_test(opt) # self.decoder_init_builder = BuildDecoderState_test(opt) self.cz_no_c=opt.cz_no_c # self.ctx_att_always=opt.ctx_att_always def _fix_enc_hidden(self, h): """ The encoder hidden is (layers*directions) x batch x dim. We need to convert it to layers x batch x (directions*dim). """ # logging.info("hidden size: {}".format(h.size())) #(8, 256, 500) if self.bidirectional_encoder: h = torch.cat([h[0:h.size(0):2], h[1:h.size(0):2]], 2) # logging.info("hidden size: {}".format(h.size())) #(4, 256, 1000) return h def _fix_ctx_enc_hidden(self, h): """ The encoder hidden is (layers*directions) x batch x dim. We need to convert it to layers x batch x (directions*dim). """ # logging.info("hidden size: {}".format(h.size())) #(8, 256, 500) if self.bidirectional_ctx_encoder: h = torch.cat([h[0:h.size(0):2], h[1:h.size(0):2]], 2) # logging.info("hidden size: {}".format(h.size())) #(4, 256, 1000) return h def reshape_enc_hidden(self, enc_hidden, ctx_enc=False): if ctx_enc: if isinstance(enc_hidden, tuple): # LSTM enc_hidden_shaped = tuple([self._fix_ctx_enc_hidden(enc_hidden[i]) for i in range(len(enc_hidden))]) else: # GRU enc_hidden_shaped = self._fix_ctx_enc_hidden(enc_hidden) else: if isinstance(enc_hidden, tuple): # LSTM enc_hidden_shaped = tuple([self._fix_enc_hidden(enc_hidden[i]) for i in range(len(enc_hidden))]) else: # GRU enc_hidden_shaped = self._fix_enc_hidden(enc_hidden) #(4, 256, 1000) return enc_hidden_shaped def forward(self, src, tgt, ctx, lengths, src_back, tgt_back, lengths_back, lengths_ctx, dec_state_cxz2y=None, dec_state_cyz2x=None, dec_state_cz2x=None, dec_state_cz2y=None, ctx_cat=True): """Forward propagate a `src` and `tgt` pair for training. Possible initialized with a beginning decoder state. Args: src (:obj:`Tensor`): a source sequence passed to encoder. typically for inputs this will be a padded :obj:`LongTensor` of size `[len x batch x features]`. however, may be an image or other generic input depending on encoder. tgt (:obj:`LongTensor`): a target sequence of size `[tgt_len x batch]`. lengths(:obj:`LongTensor`): the src lengths, pre-padding `[batch]`. dec_state (:obj:`DecoderState`, optional): initial decoder state Returns: (:obj:`FloatTensor`, `dict`, :obj:`onmt.Models.DecoderState`): * decoder output `[tgt_len x batch x hidden]` * dictionary attention dists of `[tgt_len x batch x src_len]` * final decoder state """ # self.ctx_bid = True tgt = tgt[:-1] # exclude last target from inputs tgt_back = tgt_back[:-1] enc_hidden_x, context_x = self.encoder(src,) # enc_hidden_y, context_y = self.encoder(src_back,) enc_hidden_y, context_y = self.encoder_y(src_back,) enc_hidden_ctx, context_ctx = self.encoder_ctx(ctx) # logging.info("enc_hidden shape: {},{}, context shape:{}".format(enc_hidden[0].shape, enc_hidden[1].shape, context.shape)) # (4*2, 256, 500), (4*2, 256, 500) , (40, 256, 1000) enc_hidden_x_shaped = self.reshape_enc_hidden(enc_hidden_x, False) enc_hidden_y_shaped = self.reshape_enc_hidden(enc_hidden_y, False) enc_hidden_ctx_shaped = self.reshape_enc_hidden(enc_hidden_ctx, True) #(4, 256, 1000) enc_hidden_x = self.encoder_state_fix_xy(enc_hidden_x_shaped) enc_hidden_y = self.encoder_state_fix_xy(enc_hidden_y_shaped) enc_hidden_ctx = self.encoder_state_fix_ctx(enc_hidden_ctx_shaped) # print(enc_hidden_x.shape) # print(enc_hidden_y.shape) # print(enc_hidden_ctx.shape) # (256, 800) # test: (256, rnn=1000) enc_hidden_cxy = torch.cat([enc_hidden_ctx, enc_hidden_x, enc_hidden_y], -1) # (256, 2400) # test: (256, 3*rnn=3000) rec_z, rec_mu, rec_logvar = self.encoder2z.cxy2z(enc_hidden_cxy) prior_z, prior_mu, prior_logvar = self.encoder2z.c2z(enc_hidden_ctx) # (256, z_dim) enc_hidden_cxz = torch.cat([enc_hidden_ctx, enc_hidden_x, rec_z], -1) enc_hidden_cyz = torch.cat([enc_hidden_ctx, enc_hidden_y, rec_z], -1) if not self.cz_no_c: enc_hidden_cz = torch.cat([enc_hidden_ctx, rec_z], -1) else: enc_hidden_cz = rec_z enc_hidden_cxz, enc_hidden_cyz, enc_hidden_cz = self.decoder_init_builder(enc_hidden_cxz, enc_hidden_cyz, enc_hidden_cz) # print(context_x.shape) # print(context_y.shape) # print(context_ctx.shape) # print(lengths.shape) # print(lengths) # print(lengths_back.shape) # print(lengths_back) # print(lengths_ctx.shape) # print(lengths_ctx) if not ctx_cat: enc_state_cxz = RNNDecoderState(context_x, self.hidden_size, enc_hidden_cxz) enc_state_cyz = RNNDecoderState(context_y, self.hidden_size, enc_hidden_cyz) enc_state_cz = RNNDecoderState(context_ctx, self.hidden_size, enc_hidden_cz) out_cxz2y, dec_state_cxz2y, attns_cxz2y = self.decoder_cxz2y(tgt, context_x, enc_state_cxz if dec_state_cxz2y is None else dec_state_cxz2y, context_lengths=lengths) out_cyz2x, dec_state_cyz2x, attns_cyz2x = self.decoder_cyz2x(tgt_back, context_y, enc_state_cyz if dec_state_cyz2x is None else dec_state_cyz2x, context_lengths=lengths_back) else: ################################################# context_ctx_x = torch.cat([context_ctx, context_x], 0) context_ctx_y = torch.cat([context_ctx, context_y], 0) lengths_ctx_x = lengths_ctx + lengths lengths_ctx_y = lengths_ctx + lengths_back enc_state_cxz = RNNDecoderState(context_ctx_x, self.hidden_size, enc_hidden_cxz) enc_state_cyz = RNNDecoderState(context_ctx_y, self.hidden_size, enc_hidden_cyz) enc_state_cz = RNNDecoderState(context_ctx, self.hidden_size, enc_hidden_cz) out_cxz2y, dec_state_cxz2y, attns_cxz2y = self.decoder_cxz2y(tgt, context_ctx_x, enc_state_cxz if dec_state_cxz2y is None else dec_state_cxz2y) out_cyz2x, dec_state_cyz2x, attns_cyz2x = self.decoder_cyz2x(tgt_back, context_ctx_y, enc_state_cyz if dec_state_cyz2x is None else dec_state_cyz2x,) ###################################################### out_cz2x, dec_state_cz2x, attns_cz2x = self.decoder_cz2x(tgt_back, context_ctx, enc_state_cz if dec_state_cz2x is None else dec_state_cz2x, context_lengths=lengths_ctx) out_cz2y, dec_state_cz2y, attns_cz2y = self.decoder_cz2y(tgt, context_ctx, enc_state_cz if dec_state_cz2y is None else dec_state_cz2y, context_lengths=lengths_ctx) kl_loss = self.encoder2z.kl_loss(rec_mu, rec_logvar, prior_mu, prior_logvar) results = Pack( out_cxz2y=out_cxz2y, dec_state_cxz2y=dec_state_cxz2y, attns_cxz2y=attns_cxz2y, out_cyz2x=out_cyz2x, dec_state_cyz2x=dec_state_cyz2x, attns_cyz2x=attns_cyz2x, out_cz2x=out_cz2x, dec_state_cz2x=dec_state_cz2x, attns_cz2x=attns_cz2x, out_cz2y=out_cz2y, dec_state_cz2y=dec_state_cz2y, attns_cz2y=attns_cz2y, kl_loss=kl_loss.sum() ) return results def forward_beam(self, src, ctx, lengths, lengths_ctx, ctx_cat=True): enc_hidden_x, context_x = self.encoder(src,) # enc_hidden_y, context_y = self.encoder(src_back, lengths_back) # enc_hidden_ctx, context_ctx = self.encoder_ctx(ctx, lengths_ctx) enc_hidden_ctx, context_ctx = self.encoder_ctx(ctx) context_ctx_x = torch.cat([context_ctx, context_x], 0) # logging.info("enc_hidden shape: {},{}, context shape:{}".format(enc_hidden[0].shape, enc_hidden[1].shape, context.shape)) # (4*2, 256, 500), (4*2, 256, 500) , (40, 256, 1000) enc_hidden_x_shaped = self.reshape_enc_hidden(enc_hidden_x, False) enc_hidden_ctx_shaped = self.reshape_enc_hidden(enc_hidden_ctx, True) #(4, 256, 1000) enc_hidden_x = self.encoder_state_fix_xy(enc_hidden_x_shaped) enc_hidden_ctx = self.encoder_state_fix_ctx(enc_hidden_ctx_shaped) # (256, 800) prior_z, prior_mu, prior_logvar = self.encoder2z.c2z(enc_hidden_ctx) # (256, z_dim) enc_hidden_cxz = torch.cat([enc_hidden_ctx, enc_hidden_x, prior_z], -1) enc_hidden_cxz = self.decoder_init_builder.forward_single(enc_hidden_cxz) if ctx_cat: enc_state_cxz = RNNDecoderState(context_ctx_x, self.hidden_size, enc_hidden_cxz) return enc_state_cxz, context_ctx_x else: enc_state_cxz = RNNDecoderState(context_x, self.hidden_size, enc_hidden_cxz) return enc_state_cxz, context_x def decode_beam(self, tgt, context_x, dec_state_cxz2y, lengths, ctx_cat=True): if ctx_cat: out_cxz2y, dec_state_cxz2y, attns_cxz2y = self.decoder_cxz2y(tgt, context_x, dec_state_cxz2y) else: out_cxz2y, dec_state_cxz2y, attns_cxz2y = self.decoder_cxz2y(tgt, context_x, dec_state_cxz2y, context_lengths=lengths) return out_cxz2y, dec_state_cxz2y, attns_cxz2y class EncoderStateFix(nn.Module): """ This func only support LSTM now. """ def __init__(self,opt): super(EncoderStateFix, self).__init__() if opt.rnn_type=='LSTM': self.encoder2z_layer1_h = nn.Sequential( nn.Linear(opt.rnn_size, 100), nn.ReLU() ) self.encoder2z_layer1_c = nn.Sequential( nn.Linear(opt.rnn_size, 100), nn.ReLU() ) else: self.encoder2z_layer1_h = nn.Sequential( nn.Linear(opt.rnn_size, 200), nn.ReLU() ) def forward(self, encoder_hidden): #(4, 256, 1000) if isinstance(encoder_hidden, tuple): batch_size = encoder_hidden[0].size(1) h1 = self.encoder2z_layer1_h(encoder_hidden[0]) c1 = self.encoder2z_layer1_c(encoder_hidden[1]) h1 = h1.transpose(0,1).contiguous().view(batch_size, -1) c1 = c1.transpose(0,1).contiguous().view(batch_size, -1) hc = torch.cat([h1, c1], -1) # 256, 800 # 800 = num_layer * 100 * 2 else: batch_size = encoder_hidden.size(1) h1 = self.encoder2z_layer1_h(encoder_hidden) hc = h1.transpose(0,1).contiguous().view(batch_size, -1) # 256, 800 # 800 = num_layer * 200 return hc class EncoderState2Z(nn.Module): """ """ def __init__(self,opt): super(EncoderState2Z, self).__init__() enc_size = opt.enc_layers * 200 z_dim = opt.z_dim self.cxy2z_layer = nn.Sequential( nn.Linear(enc_size * 3, z_dim * 2), nn.ReLU() ) self.cxy2z_mu = nn.Linear(z_dim * 2, z_dim) self.cxy2z_logvar = nn.Linear(z_dim * 2, z_dim) # Prior Net self.c2z_layer = nn.Sequential( nn.Linear(enc_size, z_dim * 2), nn.ReLU() ) self.c2z_mu = nn.Linear(z_dim * 2, z_dim) self.c2z_logvar = nn.Linear(z_dim * 2, z_dim) def reparameterize(self, mu, logvar): std = torch.exp(0.5*logvar) eps = Variable(torch.rand(std.size()).cuda()) # eps = torch.rand(std.size()) # eps = torch.rand(std.size()).cuda() return mu + std * eps def kl_loss(self, mu1, logvar1, mu2, logvar2): # mu1, logvar1 -> RecognitionNet # mu2, logvar2 -> PriorNet kld = -0.5 * torch.sum(1 + logvar1 - logvar2 - torch.exp(logvar1)/torch.exp(logvar2) - torch.pow(mu1 - mu2, 2)/torch.exp(logvar2),-1) return kld def kl_loss_gaussian(self, mu1, logvar1): # mu2=0, logvar2=0 kld = -0.5 * torch.sum(1 + logvar1 - mu1.pow(2) - logvar1.exp(),-1) return kld def cxy2z(self, hidden): hidden_ = self.cxy2z_layer(hidden) mu = self.cxy2z_mu(hidden_) logvar = self.cxy2z_logvar(hidden_) z = self.reparameterize(mu, logvar) return z, mu, logvar def c2z(self, hidden): hidden_ = self.c2z_layer(hidden) mu = self.c2z_mu(hidden_) logvar = self.c2z_logvar(hidden_) z = self.reparameterize(mu, logvar) return z, mu, logvar class BuildDecoderState(nn.Module): """ """ def __init__(self,opt): super(BuildDecoderState, self).__init__() enc_size = opt.enc_layers * 200 z_dim = opt.z_dim decoder_size = opt.dec_layers * opt.rnn_size self.rnn_size, self.num_layer = opt.rnn_size, opt.dec_layers self.rnn_type=opt.rnn_type self.cz_no_c=opt.cz_no_c if opt.rnn_type=='GRU': self.cxz2y = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) # 256 * 1700 -> 256 * 4000 self.cyz2x = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) self.cz2xy = nn.Sequential( nn.Linear(enc_size + z_dim, decoder_size), nn.ReLU() ) else: self.cxz2y_h = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) # 256 * 1700 -> 256 * 4000 self.cyz2x_h = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) if not self.cz_no_c: self.cz2xy_h = nn.Sequential( nn.Linear(enc_size + z_dim, decoder_size), nn.ReLU() ) else: self.cz2xy_h = nn.Sequential( nn.Linear(z_dim, decoder_size), nn.ReLU() ) self.cxz2y_c = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) # 256 * 1700 -> 256 * 4000 self.cyz2x_c = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) if not self.cz_no_c: self.cz2xy_c = nn.Sequential( nn.Linear(enc_size + z_dim, decoder_size), nn.ReLU() ) else: self.cz2xy_c = nn.Sequential( nn.Linear(z_dim, decoder_size), nn.ReLU() ) def forward(self, cxz, cyz, cz): if self.rnn_type=='GRU': cxz_, cyz_, cz_ = self.cxz2y(cxz), self.cyz2x(cyz), self.cz2xy(cz) cxz_ = cxz_.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cyz_ = cyz_.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cz_ = cz_.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() # (4, 256, 1000) elif self.rnn_type=='LSTM': cxz_h, cyz_h, cz_h = self.cxz2y_h(cxz), self.cyz2x_h(cyz), self.cz2xy_h(cz) cxz_c, cyz_c, cz_c = self.cxz2y_c(cxz), self.cyz2x_c(cyz), self.cz2xy_c(cz) cxz_h = cxz_h.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cyz_h = cyz_h.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cz_h = cz_h.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cxz_c = cxz_c.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cyz_c = cyz_c.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cz_c = cz_c.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cxz_ = tuple([cxz_h, cxz_c]) cyz_ = tuple([cyz_h, cyz_c]) cz_ = tuple([cz_h, cz_c]) else: raise ValueError("the rnn type: {} is not supported".format(opt.rnn_type)) return cxz_, cyz_, cz_ def forward_single(self, cxz): if self.rnn_type=='GRU': cxz_ = self.cxz2y(cxz) cxz_ = cxz_.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() # (4, 256, 1000) elif self.rnn_type=='LSTM': cxz_h = self.cxz2y_h(cxz) cxz_c = self.cxz2y_c(cxz) cxz_h = cxz_h.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cxz_c = cxz_c.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cxz_ = tuple([cxz_h, cxz_c]) else: raise ValueError("the rnn type: {} is not supported".format(opt.rnn_type)) return cxz_ #### %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ##### class MirrorLow(MirrorModel): def __init__(self, encoder_utt, encoder_ctx, decoder_cxz2y, decoder_cz2x, decoder_cyz2x, decoder_cz2y,multigpu=False, opt=None): super(MirrorLow, self).__init__(encoder_utt, encoder_ctx, decoder_cxz2y, decoder_cz2x, decoder_cyz2x, decoder_cz2y, multigpu, opt) self.encoder2z = EncoderState2zLow(opt) def forward(self, src, tgt, ctx, lengths, src_back, tgt_back, lengths_back, lengths_ctx, dec_state_cxz2y=None, dec_state_cyz2x=None, dec_state_cz2x=None, dec_state_cz2y=None, ctx_cat=True): """Forward propagate a `src` and `tgt` pair for training. """ tgt = tgt[:-1] # exclude last target from inputs tgt_back = tgt_back[:-1] enc_hidden_x, context_x = self.encoder(src,) # enc_hidden_y, context_y = self.encoder(src_back, lengths_back) enc_hidden_y, context_y = self.encoder(src_back,) # enc_hidden_ctx, context_ctx = self.encoder_ctx(ctx, lengths_ctx) enc_hidden_ctx, context_ctx = self.encoder_ctx(ctx) # logging.info("enc_hidden shape: {},{}, context shape:{}".format(enc_hidden[0].shape, enc_hidden[1].shape, context.shape)) # (4*2, 256, 500), (4*2, 256, 500) , (40, 256, 1000) enc_hidden_x_shaped = self.reshape_enc_hidden(enc_hidden_x, False) enc_hidden_y_shaped = self.reshape_enc_hidden(enc_hidden_y, False) enc_hidden_ctx_shaped = self.reshape_enc_hidden(enc_hidden_ctx, True) #(4, 256, 1000) enc_hidden_x = self.encoder_state_fix_xy(enc_hidden_x_shaped) enc_hidden_y = self.encoder_state_fix_xy(enc_hidden_y_shaped) enc_hidden_ctx = self.encoder_state_fix_ctx(enc_hidden_ctx_shaped) # (256, 800) enc_hidden_cxy = torch.cat([enc_hidden_ctx, enc_hidden_x, enc_hidden_y], -1) enc_hidden_cx = torch.cat([enc_hidden_ctx, enc_hidden_x], -1) enc_hidden_cy = torch.cat([enc_hidden_ctx, enc_hidden_y], -1) # (256, 2400) rec_z, rec_mu, rec_logvar = self.encoder2z.cxy2z(enc_hidden_cxy) prior_z_cx, prior_mu_cx, prior_logvar_cx = self.encoder2z.cx2z(enc_hidden_cx) prior_z_cy, prior_mu_cy, prior_logvar_cy = self.encoder2z.cy2z(enc_hidden_cy) # (256, z_dim) enc_hidden_cxz = torch.cat([enc_hidden_ctx, enc_hidden_x, rec_z], -1) enc_hidden_cyz = torch.cat([enc_hidden_ctx, enc_hidden_y, rec_z], -1) if not self.cz_no_c: enc_hidden_cz = torch.cat([enc_hidden_ctx, rec_z], -1) else: enc_hidden_cz = rec_z enc_hidden_cxz, enc_hidden_cyz, enc_hidden_cz = self.decoder_init_builder(enc_hidden_cxz, enc_hidden_cyz, enc_hidden_cz) if not ctx_cat: enc_state_cxz = RNNDecoderState(context_x, self.hidden_size, enc_hidden_cxz) enc_state_cyz = RNNDecoderState(context_y, self.hidden_size, enc_hidden_cyz) enc_state_cz = RNNDecoderState(context_ctx, self.hidden_size, enc_hidden_cz) # if not self.ctx_att_always: out_cxz2y, dec_state_cxz2y, attns_cxz2y = self.decoder_cxz2y(tgt, context_x, enc_state_cxz if dec_state_cxz2y is None else dec_state_cxz2y, context_lengths=lengths) out_cyz2x, dec_state_cyz2x, attns_cyz2x = self.decoder_cyz2x(tgt_back, context_y, enc_state_cyz if dec_state_cyz2x is None else dec_state_cyz2x, context_lengths=lengths_back) else: context_ctx_x = torch.cat([context_ctx, context_x], 0) context_ctx_y = torch.cat([context_ctx, context_y], 0) lengths_ctx_x = lengths_ctx + lengths lengths_ctx_y = lengths_ctx + lengths_back enc_state_cxz = RNNDecoderState(context_ctx_x, self.hidden_size, enc_hidden_cxz) enc_state_cyz = RNNDecoderState(context_ctx_y, self.hidden_size, enc_hidden_cyz) enc_state_cz = RNNDecoderState(context_ctx, self.hidden_size, enc_hidden_cz) out_cxz2y, dec_state_cxz2y, attns_cxz2y = self.decoder_cxz2y(tgt, context_ctx_x, enc_state_cxz if dec_state_cxz2y is None else dec_state_cxz2y) out_cyz2x, dec_state_cyz2x, attns_cyz2x = self.decoder_cyz2x(tgt_back, context_ctx_y, enc_state_cyz if dec_state_cyz2x is None else dec_state_cyz2x,) out_cz2x, dec_state_cz2x, attns_cz2x = self.decoder_cz2x(tgt_back, context_ctx, enc_state_cz if dec_state_cz2x is None else dec_state_cz2x, context_lengths=lengths_ctx) out_cz2y, dec_state_cz2y, attns_cz2y = self.decoder_cz2y(tgt, context_ctx, enc_state_cz if dec_state_cz2y is None else dec_state_cz2y, context_lengths=lengths_ctx) kl_loss_cx2z = 0.5 * self.encoder2z.kl_loss(rec_mu, rec_logvar, prior_mu_cx, prior_logvar_cx) kl_loss_cy2z = 0.5 * self.encoder2z.kl_loss(rec_mu, rec_logvar, prior_mu_cx, prior_logvar_cx) # kl_loss_cy2z = 0.5 * self.encoder2z.kl_loss(rec_mu, rec_logvar, prior_mu_cy, prior_logvar_cy) results = Pack( out_cxz2y=out_cxz2y, dec_state_cxz2y=dec_state_cxz2y, attns_cxz2y=attns_cxz2y, out_cyz2x=out_cyz2x, dec_state_cyz2x=dec_state_cyz2x, attns_cyz2x=attns_cyz2x, out_cz2x=out_cz2x, dec_state_cz2x=dec_state_cz2x, attns_cz2x=attns_cz2x, out_cz2y=out_cz2y, dec_state_cz2y=dec_state_cz2y, attns_cz2y=attns_cz2y, kl_loss=kl_loss_cx2z.sum() + kl_loss_cy2z.sum() ) return results def forward_beam(self, src, ctx, lengths, lengths_ctx, ctx_cat=True): enc_hidden_x, context_x = self.encoder(src,) # enc_hidden_y, context_y = self.encoder(src_back, lengths_back) # enc_hidden_ctx, context_ctx = self.encoder_ctx(ctx, lengths_ctx) enc_hidden_ctx, context_ctx = self.encoder_ctx(ctx) # logging.info("enc_hidden shape: {},{}, context shape:{}".format(enc_hidden[0].shape, enc_hidden[1].shape, context.shape)) # (4*2, 256, 500), (4*2, 256, 500) , (40, 256, 1000) context_ctx_x = torch.cat([context_ctx, context_x], 0) enc_hidden_x_shaped = self.reshape_enc_hidden(enc_hidden_x, False) enc_hidden_ctx_shaped = self.reshape_enc_hidden(enc_hidden_ctx, True) #(4, 256, 1000) enc_hidden_x = self.encoder_state_fix_xy(enc_hidden_x_shaped) enc_hidden_ctx = self.encoder_state_fix_ctx(enc_hidden_ctx_shaped) # (256, 800) enc_hidden_cx = torch.cat([enc_hidden_ctx, enc_hidden_x], -1) prior_z, prior_mu, prior_logvar = self.encoder2z.cx2z(enc_hidden_cx) # (256, z_dim) enc_hidden_cxz = torch.cat([enc_hidden_ctx, enc_hidden_x, prior_z], -1) enc_hidden_cxz = self.decoder_init_builder.forward_single(enc_hidden_cxz) # enc_state_cxz = RNNDecoderState(context_x, self.hidden_size, enc_hidden_cxz) if ctx_cat: enc_state_cxz = RNNDecoderState(context_ctx_x, self.hidden_size, enc_hidden_cxz) return enc_state_cxz, context_ctx_x else: enc_state_cxz = RNNDecoderState(context_x, self.hidden_size, enc_hidden_cxz) return enc_state_cxz, context_x # return enc_state_cxz, context_x class EncoderState2zLow(nn.Module): """ """ def __init__(self,opt): super(EncoderState2zLow, self).__init__() enc_size = opt.enc_layers * 200 z_dim = opt.z_dim self.cxy2z_layer = nn.Sequential( nn.Linear(enc_size * 3, z_dim * 2), nn.ReLU() ) self.cxy2z_mu = nn.Linear(z_dim * 2, z_dim) self.cxy2z_logvar = nn.Linear(z_dim * 2, z_dim) # Prior Net self.cx2z_layer = nn.Sequential( nn.Linear(enc_size * 2, z_dim * 2), nn.ReLU() ) self.cx2z_mu = nn.Linear(z_dim * 2, z_dim) self.cx2z_logvar = nn.Linear(z_dim * 2, z_dim) self.cy2z_layer = nn.Sequential( nn.Linear(enc_size * 2, z_dim * 2), nn.ReLU() ) self.cy2z_mu = nn.Linear(z_dim * 2, z_dim) self.cy2z_logvar = nn.Linear(z_dim * 2, z_dim) def reparameterize(self, mu, logvar): std = torch.exp(0.5*logvar) eps = Variable(torch.rand(std.size()).cuda()) # eps = torch.rand(std.size()) # eps = torch.rand(std.size()).cuda() return mu + std * eps def kl_loss(self, mu1, logvar1, mu2, logvar2): # mu1, logvar1 -> RecognitionNet # mu2, logvar2 -> PriorNet kld = -0.5 * torch.sum(1 + logvar1 - logvar2 - torch.exp(logvar1)/torch.exp(logvar2) - torch.pow(mu1 - mu2, 2)/torch.exp(logvar2),-1) return kld def kl_loss_gaussian(self, mu1, logvar1): # mu2=0, logvar2=0 kld = -0.5 * torch.sum(1 + logvar1 - mu1.pow(2) - logvar1.exp(),-1) return kld def cxy2z(self, hidden): hidden_ = self.cxy2z_layer(hidden) mu = self.cxy2z_mu(hidden_) logvar = self.cxy2z_logvar(hidden_) z = self.reparameterize(mu, logvar) return z, mu, logvar def cx2z(self, hidden): hidden_ = self.cx2z_layer(hidden) mu = self.cx2z_mu(hidden_) logvar = self.cx2z_logvar(hidden_) z = self.reparameterize(mu, logvar) return z, mu, logvar def cy2z(self, hidden): hidden_ = self.cy2z_layer(hidden) mu = self.cy2z_mu(hidden_) logvar = self.cy2z_logvar(hidden_) z = self.reparameterize(mu, logvar) return z, mu, logvar class Mirror_Encshare(MirrorModel): def __init__(self, encoder_utt, decoder_cxz2y, decoder_cz2x, decoder_cyz2x, decoder_cz2y,multigpu=False, opt=None): super(Mirror_Encshare, self).__init__(encoder_utt, None, decoder_cxz2y, decoder_cz2x, decoder_cyz2x, decoder_cz2y, multigpu, opt) self.encoder_ctx = encoder_utt class MirrorLow_Encshare(MirrorLow): def __init__(self, encoder_utt, decoder_cxz2y, decoder_cz2x, decoder_cyz2x, decoder_cz2y,multigpu=False, opt=None): super(MirrorLow_Encshare, self).__init__(encoder_utt, None, decoder_cxz2y, decoder_cz2x, decoder_cyz2x, decoder_cz2y, multigpu, opt) self.encoder_ctx = encoder_utt ########################## TEST ########################## class EncoderStateFix_test(nn.Module): """ This func only support LSTM now. """ def __init__(self,opt): super(EncoderStateFix_test, self).__init__() if opt.rnn_type=='LSTM': self.encoder2z_layer1_h = nn.Sequential( nn.Linear(opt.rnn_size, opt.rnn_size//2), nn.ReLU() ) self.encoder2z_layer1_c = nn.Sequential( nn.Linear(opt.rnn_size, opt.rnn_size//2), nn.ReLU() ) else: self.encoder2z_layer1_h = nn.Sequential( nn.Linear(opt.rnn_size, opt.rnn_size), nn.ReLU() ) def forward(self, encoder_hidden): #(4, 256, 1000) # (1, 256, 1000) if isinstance(encoder_hidden, tuple): batch_size = encoder_hidden[0].size(1) h1 = self.encoder2z_layer1_h(encoder_hidden[0][-1].unsqueeze(0)) c1 = self.encoder2z_layer1_c(encoder_hidden[1][-1].unsqueeze(0)) h1 = h1.transpose(0,1).contiguous().view(batch_size, -1) c1 = c1.transpose(0,1).contiguous().view(batch_size, -1) hc = torch.cat([h1, c1], -1) # 256, 1000 # 1000 = 1 * 500 * 2 else: batch_size = encoder_hidden.size(1) h1 = self.encoder2z_layer1_h(encoder_hidden[-1].unsqueeze(0)) hc = h1.transpose(0,1).contiguous().view(batch_size, -1) # 256, 1000 # 1000 = 1 * 1000 return hc class EncoderState2Z_test(nn.Module): """ """ def __init__(self,opt): super(EncoderState2Z_test, self).__init__() enc_size = opt.rnn_size z_dim = opt.z_dim self.cxy2z_layer = nn.Sequential( nn.Linear(enc_size * 3, z_dim * 2), nn.ReLU() ) self.cxy2z_mu = nn.Linear(z_dim * 2, z_dim) self.cxy2z_logvar = nn.Linear(z_dim * 2, z_dim) # Prior Net self.c2z_layer = nn.Sequential( nn.Linear(enc_size, z_dim * 2), nn.ReLU() ) self.c2z_mu = nn.Linear(z_dim * 2, z_dim) self.c2z_logvar = nn.Linear(z_dim * 2, z_dim) def reparameterize(self, mu, logvar): std = torch.exp(0.5*logvar) eps = Variable(torch.rand(std.size()).cuda()) # eps = torch.rand(std.size()) # eps = torch.rand(std.size()).cuda() return mu + std * eps def kl_loss(self, mu1, logvar1, mu2, logvar2): # mu1, logvar1 -> RecognitionNet # mu2, logvar2 -> PriorNet kld = -0.5 * torch.sum(1 + logvar1 - logvar2 - torch.exp(logvar1)/torch.exp(logvar2) - torch.pow(mu1 - mu2, 2)/torch.exp(logvar2),-1) return kld def kl_loss_gaussian(self, mu1, logvar1): # mu2=0, logvar2=0 kld = -0.5 * torch.sum(1 + logvar1 - mu1.pow(2) - logvar1.exp(),-1) return kld def cxy2z(self, hidden): hidden_ = self.cxy2z_layer(hidden) mu = self.cxy2z_mu(hidden_) logvar = self.cxy2z_logvar(hidden_) z = self.reparameterize(mu, logvar) return z, mu, logvar def c2z(self, hidden): hidden_ = self.c2z_layer(hidden) mu = self.c2z_mu(hidden_) logvar = self.c2z_logvar(hidden_) z = self.reparameterize(mu, logvar) return z, mu, logvar class BuildDecoderState_test(nn.Module): """ """ def __init__(self,opt): super(BuildDecoderState_test, self).__init__() enc_size = opt.rnn_size z_dim = opt.z_dim decoder_size = opt.dec_layers * opt.rnn_size self.rnn_size, self.num_layer = opt.rnn_size, opt.dec_layers self.rnn_type=opt.rnn_type self.cz_no_c=opt.cz_no_c if opt.rnn_type=='GRU': self.cxz2y = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) # 256 * 1700 -> 256 * 4000 self.cyz2x = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) self.cz2xy = nn.Sequential( nn.Linear(enc_size + z_dim, decoder_size), nn.ReLU() ) else: self.cxz2y_h = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) # 256 * 1700 -> 256 * 4000 self.cyz2x_h = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) if not self.cz_no_c: self.cz2xy_h = nn.Sequential( nn.Linear(enc_size + z_dim, decoder_size), nn.ReLU() ) else: self.cz2xy_h = nn.Sequential( nn.Linear(z_dim, decoder_size), nn.ReLU() ) self.cxz2y_c = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) # 256 * 1700 -> 256 * 4000 self.cyz2x_c = nn.Sequential( nn.Linear(enc_size * 2 + z_dim, decoder_size), nn.ReLU() ) if not self.cz_no_c: self.cz2xy_c = nn.Sequential( nn.Linear(enc_size + z_dim, decoder_size), nn.ReLU() ) else: self.cz2xy_c = nn.Sequential( nn.Linear(z_dim, decoder_size), nn.ReLU() ) def forward(self, cxz, cyz, cz): if self.rnn_type=='GRU': cxz_, cyz_, cz_ = self.cxz2y(cxz), self.cyz2x(cyz), self.cz2xy(cz) cxz_ = cxz_.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cyz_ = cyz_.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cz_ = cz_.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() # (4, 256, 1000) elif self.rnn_type=='LSTM': cxz_h, cyz_h, cz_h = self.cxz2y_h(cxz), self.cyz2x_h(cyz), self.cz2xy_h(cz) cxz_c, cyz_c, cz_c = self.cxz2y_c(cxz), self.cyz2x_c(cyz), self.cz2xy_c(cz) cxz_h = cxz_h.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cyz_h = cyz_h.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cz_h = cz_h.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cxz_c = cxz_c.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cyz_c = cyz_c.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cz_c = cz_c.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cxz_ = tuple([cxz_h, cxz_c]) cyz_ = tuple([cyz_h, cyz_c]) cz_ = tuple([cz_h, cz_c]) else: raise ValueError("the rnn type: {} is not supported".format(opt.rnn_type)) return cxz_, cyz_, cz_ def forward_single(self, cxz): if self.rnn_type=='GRU': cxz_ = self.cxz2y(cxz) cxz_ = cxz_.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() # (4, 256, 1000) elif self.rnn_type=='LSTM': cxz_h = self.cxz2y_h(cxz) cxz_c = self.cxz2y_c(cxz) cxz_h = cxz_h.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cxz_c = cxz_c.view(-1, self.num_layer, self.rnn_size).transpose(0,1).contiguous() cxz_ = tuple([cxz_h, cxz_c]) else: raise ValueError("the rnn type: {} is not supported".format(opt.rnn_type)) return cxz_ <file_sep>from onmt.translate.Translator import Translator from onmt.translate.Translation import Translation, TranslationBuilder from onmt.translate.Beam import Beam, GNMTGlobalScorer, MMIGlobalScorer from onmt.translate.SIFEmbedding import SIFEmbedding from onmt.translate.SyntaxTopicModel import SyntaxTopicModel __all__ = [Translator, Translation, Beam, GNMTGlobalScorer, TranslationBuilder, MMIGlobalScorer, SIFEmbedding, SyntaxTopicModel] <file_sep>from __future__ import division import torch from torch.autograd import Variable import onmt.io import numpy as np #Adding the topic and syntax probability scores to the scores from Decoder class Beam(object): """ Class for managing the internals of the beam search process. Takes care of beams, back pointers, and scores. Args: size (int): beam size pad, bos, eos (int): indices of padding, beginning, and ending. vocab (vocab): vocab of the target syntax_topics_model (Syntax and Topics module): This is an object of the class which will have the topics and classes word probabilities source (list): list of source indices which will be the source sentence targets (list of list): list of taget sentences each of which is a list of indices of the full hypothesis generated till now n_best (int): nbest size to use cuda (bool): use gpu global_scorer (:obj:`GlobalScorer`) """ def __init__(self, size, pad, bos, eos, vocab, similarity_scorer, syntax_topics_model, source, n_best=1, cuda=False, global_scorer=None, min_length=0, use_dc=False): self.size = size self.use_cuda = cuda self.use_dc=use_dc # self.tt = torch.cuda if cuda else torch self.tt = torch # The score for each translation on the beam. self.scores = self.tt.FloatTensor(size).zero_() if self.use_cuda: self.scores = self.scores.cuda() self.all_scores = [] # The backpointers at each time-step. self.prev_ks = [] # The outputs at each time-step. self.next_ys = [self.tt.LongTensor(size) .fill_(pad)] if self.use_cuda: self.next_ys = [self.tt.LongTensor(size).fill_(pad).cuda()] self.next_ys[0][0] = bos self.next_ys_topic_prior_sum = [] # Store the sum of the weighted topic prior for the entire hypothesis # Has EOS topped the beam yet. self._eos = eos self.eos_top = False self._bos = bos # The attentions (matrix) for each time. self.attn = [] # Time and k pair for finished. self.finished = [] self.n_best = n_best # Information for global scoring. self.global_scorer = global_scorer self.global_state = {} # Minimum prediction length self.min_length = min_length # self.min_length = 10 ##NOTE: Custom code self.vocab = vocab self.finished_marker = [-1]*size self.similarity_scorer = similarity_scorer self.syntax_topics_model = syntax_topics_model self.source = source self.source_text = [self.vocab.itos[word_id] for word_id in source] print self.source_text self.source_topic_prior = np.zeros(self.syntax_topics_model.num_topics, dtype=np.float) word_prev = "<s>" for word in self.source_text: self.source_topic_prior += self.syntax_topics_model.get_weighted_topic_word_probability(word, word_prev) word_prev = word self.source_topic_prior /= float(np.linalg.norm(self.source_topic_prior)) # print self.source_topic_prior self.L = 1000 # Number of words to be chosen for the similarity consideration # Note: alpha 0.5 was used for the interpolation objective # self.alpha = 0.5 # multiplicative factor for the Syntax Topic log probability # self.alpha = 1.0 # multiplicative factor for the Syntax Topic log probability self.alpha = 1.5 # multiplicative factor for the Syntax Topic log probability, dc use this one # self.alpha = 0.0 # multiplicative factor for the Syntax Topic log probability # self.iteration_multiplier = 0.75 self.iteration_multiplier = 1 #TODO: Changing similarity to 0 and seeing the changes # self.gamma = 0. self.gamma = 2.0 # dc used this one # self.gamma = 0.0 self.delta = 3.5 # repeatition penalty # self.delta = 2.5 # repeatition penalty # self.delta = 0.0 # repeatition penalty self.theta = 0.05 # short length response penalty in final scoring if not self.use_dc: self.delta = 0.0 # repeatition penalty self.theta = 0.0 self.alpha = 0.0 self.gamma = 0.0 # import os # stop_words_file = os.path.join("data", "syntax_topics_models", "stop_words_short.txt") # self.stop_words_set = self.read_words_from_file(stop_words_file) # self.stop_words_set.add("<unk>") # topic_words_file = os.path.join("data", "syntax_topics_models", "top10_topic_words.txt") # self.topic_words_set = self.read_words_from_file(topic_words_file) # print self.stop_words_set # print self.topic_words_set # print vocab.itos[0] # print vocab.itos[bos] # print vocab.itos[self._eos] # print vocab.__dict__.keys() # print vocab.unk_init # print type(vocab) # Temporary code for reading stop words and topic words list from files. Will be used to draw the figure later def read_words_from_file(self, filename): words_set = set() with open(filename, "r") as reader: for line in reader: line = line.strip() if line and line != "UNknown": words_set.add(line) return words_set def print_hyp(self, hyp, class_or_topic = None): for i, word_id in enumerate(hyp): if class_or_topic: print "{}_{} ".format(self.vocab.itos[word_id], class_or_topic[i]), else: print "{} ".format(self.vocab.itos[word_id]), ##NOTE: Custom function for debugging def print_all_words_in_beam(self): # Uses the vocab and prints the list of next_ys for i in range(self.size): timestep = len(self.next_ys) # if self.finished_marker[i] != -1: # timestep = self.finished_marker[i] if timestep > 1: hyp, _ = self.get_hyp(timestep, i) self.print_hyp(hyp) print "$$$" # print "" def print_received_targets(self): for i in range(len(self.targets)): self.print_hyp(self.targets[i]) print "" print "############### Received Targets ############" def print_the_top_choices(self, best_choices): w, h = best_choices.size() for i in range(w): for j in range(h): print "{} ".format(self.vocab.itos[best_choices[i,j]]), print "" def get_current_state(self): "Get the outputs for the current timestep." return self.next_ys[-1] def get_current_origin(self): "Get the backpointers for the current timestep." return self.prev_ks[-1] def delay_function(self, iteration): if iteration<=1: return 0.3 else: return 1 # http://www.wolframalpha.com/input/?i=y%3D(tanh((x-3))+%2B1)%2F2 # return (np.tanh((iteration-3.0) * self.iteration_multiplier) + 1)/2.0 def delay_function2(self, iteration): if iteration<=2: return .8 elif iteration<=5: return 0.6 else: return 0.2 def advance(self, word_probs, attn_out): # print "Advancing beam" """ Given prob over words for every last beam `wordLk` and attention `attn_out`: Compute and update the beam search. Parameters: * `word_probs`- probs of advancing from the last step (K x words) * `attn_out`- attention at the last step Returns: True if beam search is complete. """ num_words = word_probs.size(1) # force the output to be longer than self.min_length cur_len = len(self.next_ys) if cur_len < self.min_length: for k in range(len(word_probs)): word_probs[k][self._eos] = -1e20 # Sum the previous scores. if len(self.prev_ks) > 0: beam_scores = word_probs + \ self.scores.unsqueeze(1).expand_as(word_probs) # Don't let EOS have children. for i in range(self.next_ys[-1].size(0)): if self.next_ys[-1][i] == self._eos: beam_scores[i] = -1e20 else: beam_scores = word_probs[0] #TODO: 1) find the last word for each beam # 2) For each possible hypothesis find the Topic modeling probability as Source sentence weighted topic prior * current word weighted topic prior # 3) Weighted add the syntax and topic scores to beam_scores and just calculate the next_ys and backpointers as normal if len(self.prev_ks) > 0: per_beam_best_scores, per_beam_best_scores_ids = beam_scores.topk(self.L) # Tensors to store the similarity scores source_similarity_scores = self.tt.zeros_like(per_beam_best_scores) # source_similarity_scores = torch.zeros_like(per_beam_best_scores).cuda() per_beam_words = self.next_ys[-1] per_beam_prev_topic_probability = self.next_ys_topic_prior_sum[-1] # print "Next iter" syntax_topic_scores = self.tt.zeros_like(per_beam_best_scores) # syntax_topic_scores = torch.zeros_like(per_beam_best_scores).cuda() # We want to penalize the words which are occuring again in the sentence repetition_penalty = self.tt.zeros_like(per_beam_best_scores) # repetition_penalty = torch.zeros_like(per_beam_best_scores).cuda() timestep = len(self.next_ys) unk_ids = list() # timestep_no = None # if timestep == timestep_no: # beam_no = 6 # stop_words_scores = dict() # topic_words_scores = dict() for i in range(self.size): if not self.use_dc: break word_prev = self.vocab.itos[per_beam_words[i]] hyp_topic_probability = per_beam_prev_topic_probability[i] # Generate the curret hypothesis of this beam hyp, _ = self.get_hyp(timestep, i) # Now we append a dummy value which will be replaced below as the final word in the hypothesis hyp.append(0) for j in range(self.L): word_id = per_beam_best_scores_ids[i,j] hyp[-1] = word_id word = self.vocab.itos[word_id] # Manually discourage unk by setting large negative syntax_topic_probability if "<unk>" in word: unk_ids.append((i,j)) syntax_topic_score = -100000.0 syntax_topic_scores[i,j] = -100000.0 source_similarity_scores[i,j] = -100000.0 else: syntax_topic_score = (self.syntax_topics_model.get_weighted_topic_word_probability(word, word_prev) + hyp_topic_probability).dot(self.source_topic_prior) syntax_topic_scores[i,j] = syntax_topic_score source_similarity_scores[i,j] = self.similarity_scorer.Similarity(self.source, hyp) # if timestep == timestep_no: # # Temporary code for the first figure in the paper # if word in self.stop_words_set: # stop_words_scores[word] = per_beam_best_scores[beam_no,j] # if word in self.topic_words_set: # topic_words_scores[word] = per_beam_best_scores[beam_no,j] # if "</s>" in word: # # print syntax_topic_scores[i,j], self.tt.max(syntax_topic_scores), self.tt.min(syntax_topic_scores) # syntax_topic_scores[i,j] /= 4.0 # Count the number of times the word has occured in the hypothesis # reweight it with syntax topic score so that score is high only for topic words repetition_penalty[i,j] = abs(hyp[:-1].count(word_id) * self.alpha * syntax_topic_score) # if timestep == timestep_no: # # print hypothesis # curr_hyp, _ = self.get_hyp(len(self.next_ys) - 1,beam_no) # word_hyp = self.hyp_to_words(curr_hyp) # print word_hyp # import operator # sorted_topic_words_scores = sorted(topic_words_scores.items(), key=operator.itemgetter(1), reverse=True) # sorted_stop_words_scores = sorted(stop_words_scores.items(), key=operator.itemgetter(1), reverse=True) # for i, (word, score) in enumerate(sorted_stop_words_scores): # if i == 20: # break # print word, ":", score # print "" # for i, (word, score) in enumerate(sorted_topic_words_scores): # # if i == 20: # # break # print word, ":", score # print "" # exit() syntax_topic_scores /= float(len(self.source) + len(self.next_ys)) # Note: Probability interpolation doesn't work because the model then chooses all the sentences mainly from the RNN and barely any words from the topic part are chosen # overall_scores = self.tt.log(self.tt.exp(beam_scores) + self.alpha * syntax_topic_scores) iteration = len(self.prev_ks) # overall_scores = per_beam_best_scores + (self.delay_function(iteration) * self.alpha * self.tt.log(syntax_topic_scores)) + (self.gamma * iteration * source_similarity_scores) - self.delta * repetition_penalty overall_scores = per_beam_best_scores # adaptive_alpha = beam_scores.max() / self.tt.log(syntax_topic_scores).max() * 0.5 # overall_scores = beam_scores + adaptive_alpha * self.tt.log(syntax_topic_scores) for i, j in unk_ids: overall_scores[i,j] = -1000000.0 beam_mean = beam_scores.topk(30)[0].mean() syntax_topic_scores_mean = self.tt.log(syntax_topic_scores.topk(30)[0]).mean() # print adaptive_alpha # print beam_mean, syntax_topic_scores_mean, beam_mean / syntax_topic_scores_mean # print beam_scores.max(), self.tt.log(syntax_topic_scores).max(), beam_scores.max() / self.tt.log(syntax_topic_scores).max() # print beam_scores.min(), self.tt.log(syntax_topic_scores).min(), beam_scores.min() / self.tt.log(syntax_topic_scores).min() # print "Overall Score" # print overall_scores # print overall_scores.size() # self.print_all_words_in_beam() # print "############## Before new words chosen ###########" size = int(overall_scores.size(1)) # print "Size of the overall_scores = ", size flat_beam_scores = overall_scores.view(-1) # flat_beam_scores = syntax_topic_scores.view(-1) # flat_beam_scores = per_beam_best_scores.view(-1) best_scores, best_scores_id = flat_beam_scores.topk(self.size, 0, True, True) # We will debug the individual scores of the best candidates # Only keep the word probability part of the best score word_prob_best_scores = self.tt.zeros_like(best_scores) # word_prob_best_scores = torch.zeros_like(best_scores).cuda() # for i in range(self.size): # word_prob_best_scores[i] = per_beam_best_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size] # # Find Syntax topic scores of the best candidates # syntax_topic_best_scores = self.tt.zeros_like(best_scores) # # syntax_topic_best_scores = torch.zeros_like(best_scores).cuda() # for i in range(self.size): # syntax_topic_best_scores[i] = syntax_topic_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size] # # Find the similarity score component of the best candidates # best_hyp_similairty_scores = self.tt.zeros_like(best_scores) # # best_hyp_similairty_scores = torch.zeros_like(best_scores) # for i in range(self.size): # best_hyp_similairty_scores[i] = source_similarity_scores[int(best_scores_id[i] / size)][best_scores_id[i] - int(best_scores_id[i] / size) * size] # print best_scores # print word_prob_best_scores # print best_hyp_similairty_scores # print self.gamma * self.delay_function(iteration) # print self.gamma * self.delay_function(iteration) * best_hyp_similairty_scores # print syntax_topic_best_scores # print self.tt.log(syntax_topic_best_scores) # print iteration, self.alpha * self.delay_function(iteration) # print self.alpha * self.delay_function(iteration) * self.tt.log(syntax_topic_best_scores) prev_k = best_scores_id / size self.prev_ks.append(prev_k) # Recalculate the next_ys in a new for loop next_y = list() for i in range(self.size): # print per_beam_best_scores_ids[prev_k[i]][best_scores_id[i] - prev_k[i] * size] next_y.append(per_beam_best_scores_ids[prev_k[i]][best_scores_id[i] - prev_k[i] * size]) next_y = self.tt.LongTensor(next_y) if self.use_cuda: next_y = next_y.cuda() best_hyp_topic_prior_sum = list() for i in range(self.size): word = self.vocab.itos[next_y[i]] word_prev_id = self.next_ys[-1][prev_k[i]] word_prev = self.vocab.itos[word_prev_id] word_topic_prior = self.syntax_topics_model.get_weighted_topic_word_probability(word, word_prev) best_hyp_topic_prior_sum.append(self.next_ys_topic_prior_sum[-1][int(best_scores_id[i] / size)] + word_topic_prior) self.next_ys_topic_prior_sum.append(best_hyp_topic_prior_sum) self.next_ys.append(next_y) self.attn.append(attn_out.index_select(0, prev_k)) # exit() # for i in range(self.size): # word_id = next_y[i] # word = self.vocab.itos[word_id] # print word, syntax_topic_best_scores[i], word_prob_best_scores[i] # print "" # self.print_all_words_in_beam() # print "############## After new words chosen ###########" else: # beam_scores is only V dimensional vector # Thus for every word add the syntax_topic probability to the beam score syntax_topic_scores = self.tt.zeros_like(beam_scores) # syntax_topic_scores = torch.zeros_like(beam_scores).cuda() unk_id = None for i in range(num_words): word = self.vocab.itos[i] if "<unk>" in word: unk_id = i syntax_topic_score = self.syntax_topics_model.get_weighted_topic_word_probability(word, "<s>").dot(self.source_topic_prior) syntax_topic_scores[i] = syntax_topic_score # overall_scores = beam_scores + self.alpha * self.tt.log(syntax_topic_scores) # NOTE: Not calculating the syntax topic or the similarity score for the first word overall_scores = beam_scores # print "Unk id is", unk_id if unk_id is not None: overall_scores[unk_id] = -100000.0 flat_beam_scores = overall_scores.view(-1) best_scores, best_scores_id = flat_beam_scores.topk(self.size, 0, True, True) self.all_scores.append(self.scores) self.scores = best_scores # will store the word_prob + the topic log prob for hypothesis # best_scores_id is flattened, beam * word array, so calculate which # word and beam each score came from size = int(overall_scores.size(0)) prev_k = best_scores_id / num_words # next_class_or_topic = self.tt.zeros_like(prev_k) # for i in range(self.size): # next_class_or_topic[i] = int(class_or_topics[best_scores_id[i]]) # print prev_k # print overall_scores # print next_class_or_topic # print next_class_or_topic_number # print best_scores_id best_hyp_topic_prior_sum = list() for i in range(self.size): word = self.vocab.itos[best_scores_id[i]] word_topic_prior = self.syntax_topics_model.get_weighted_topic_word_probability(word, "<s>") best_hyp_topic_prior_sum.append(word_topic_prior) self.next_ys_topic_prior_sum.append(best_hyp_topic_prior_sum) self.prev_ks.append(prev_k) self.next_ys.append((best_scores_id - prev_k * num_words)) self.attn.append(attn_out.index_select(0, prev_k)) if self.global_scorer is not None: self.global_scorer.update_global_state(self) for i in range(self.next_ys[-1].size(0)): if self.next_ys[-1][i] == self._eos: timestep = len(self.next_ys) # MMI Objective stuff curr_hyp, _ = self.get_hyp(len(self.next_ys) - 1,i) word_hyp = self.hyp_to_words(curr_hyp) # s = self.scores[i] # s = self.scores[i] + (self.alpha * np.log(syntax_topic_best_scores[i])) + self.gamma * best_hyp_similairty_scores[i] # s = (self.alpha * np.log(syntax_topic_best_scores[i])) + self.gamma * best_hyp_similairty_scores[i] + self.theta * timestep word_prev = "<s>" hyp_topic_prior = np.zeros(self.syntax_topics_model.num_topics, dtype=np.float) for word in word_hyp: hyp_topic_prior += self.syntax_topics_model.get_weighted_topic_word_probability(word, word_prev) word_prev = word hyp_topic_prior /= np.linalg.norm(hyp_topic_prior) # s = (np.log(hyp_topic_prior.dot(self.source_topic_prior))) # print s, self.theta * timestep if self.use_dc: s = self.theta * timestep else: s = self.alpha * (np.log(hyp_topic_prior.dot(self.source_topic_prior))) + self.theta * timestep # s = self.scores[i] # s = (self.alpha * self.delay_function(iteration) * np.log(syntax_topic_best_scores[i])) + self.gamma * best_hyp_similairty_scores[i] # s = (self.alpha * np.log(syntax_topic_best_scores[i])) - (2 * (len(self.source) - iteration) if iteration < len(self.source) else 0.5 * (len(self.source) - iteration)) # s = - (1 * (len(self.source) - iteration) if iteration < len(self.source) else 0.0) # s = self.gamma * best_hyp_similairty_scores[i] - (0.5 * (len(self.source) - iteration) if iteration < len(self.source) else 0.0) if self.global_scorer is not None: s -= self.theta * timestep # global_scores = self.global_scorer.score(self, self.scores) # s = global_scores[i] # MMI score global_score = self.global_scorer.mmi_score(self, word_hyp, s) s = global_score[0] / float(len(self.next_ys) - 1) self.finished.append((s, len(self.next_ys) - 1, i)) # TODO: Experimental!! Dividing the finished scores by their lenghts to be fair # self.finished.append((s/float(len(self.next_ys) - 1), len(self.next_ys) - 1, i)) ##NOTE: Custom code if self.finished_marker[i] == -1: # print "SET AND FORGET FOR ", i, "#$#$#$#$##$" self.finished_marker[i] = len(self.next_ys) - 1 # End condition is when top-of-beam is EOS and no global score. if self.next_ys[-1][0] == self._eos: # self.all_scores.append(self.scores) self.eos_top = True ##NOTE: Debugging # print word_probs, "$$" # print self.get_current_state(), "$$" # self.print_all_words_in_beam() # print "############## Beam Advance ###########" def done(self): return self.eos_top and len(self.finished) >= self.n_best def sort_finished(self, minimum=None): if minimum is not None: i = 0 # Add from beam until we have minimum outputs. while len(self.finished) < minimum: s = self.scores[i] if self.global_scorer is not None: global_scores = self.global_scorer.score(self, self.scores) s = global_scores[i] self.finished.append((s, len(self.next_ys) - 1, i)) # print self.finished # exit() self.finished.sort(key=lambda a: -a[0]) scores = [sc for sc, _, _ in self.finished] ks = [(t, k) for _, t, k in self.finished] return scores, ks def get_hyp_with_class(self, timestep, k): """ Walk back to construct the full hypothesis while also storing the class/topic number """ hyp, class_or_topic = [], [] # print len(self.next_ys), len(self.next_class_or_topics), len(self.next_class_or_topic_numbers) for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1): hyp.append(self.next_ys[j+1][k]) class_or_topic.append("{}{}".format("C" if self.next_class_or_topics[j][k] == 1 else "T", self.next_class_or_topic_numbers[j][k])) k = self.prev_ks[j][k] class_or_topic.reverse() return hyp[::-1], class_or_topic def get_hyp(self, timestep, k): """ Walk back to construct the full hypothesis. """ hyp, attn = [], [] for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1): hyp.append(self.next_ys[j+1][k]) attn.append(self.attn[j][k]) k = self.prev_ks[j][k] return hyp[::-1], torch.stack(attn[::-1]) def hyp_to_words(self, hyp): return [self.vocab.itos[e] for e in hyp] class MMIGlobalScorer(object): """ Global scorer which rescores the candidates in beam using the (S|T) model ref: http://www.aclweb.org/anthology/N16-1014 """ def __init__(self, model, fields, cuda=False): self.model = model self.fields = fields self.src_vocab = self.fields["src"].vocab self.tgt_vocab = self.fields["tgt"].vocab # self.tt = torch.cuda if cuda else torch self.tt = torch self.use_cuda = cuda self.beta = .0 # Topic score multiplier self.alpha = 1.0 # S|T score multiplier self.gamma = 0.1 # Length penalty multipler # self.gamma = 0.0 # Length penalty multipler def make_features(self, data): levels = [data] return torch.cat([level.unsqueeze(2) for level in levels], 2) def _run_target(self, tgt_data, src_data, tgt_lengths): tgt = Variable(self.make_features(tgt_data)) src_in = Variable(self.make_features(src_data)[:-1]) # print "tgt" # print tgt # print "tgt_lengths" # print tgt_lengths # print "src_in" # print src_in # (1) run the encoder on the tgt enc_states, memory_bank = self.model.encoder(tgt, tgt_lengths) dec_states = \ self.model.decoder.init_decoder_state(tgt, memory_bank, enc_states) # (2) Compute the 'goldScore' # (i.e. log likelihood) of the source given target under the model (S|T) gold_scores = self.tt.FloatTensor(1).fill_(0) if self.use_cuda: gold_scores = gold_scores.cuda() dec_out, dec_states, attn = self.model.decoder( # src_in, memory_bank, dec_states, memory_lengths=tgt_lengths) #NOTE: For some unknown reasons it doesn't want memory_lenghts here src_in, memory_bank, dec_states) tgt_pad = self.fields["tgt"].vocab.stoi[onmt.io.PAD_WORD] for dec, src in zip(dec_out, src_data[1:]): # src data is src + bos and eos # Log prob of each word. # print "dec" # print dec # print "src" # print src # print self.model.generator.forward out = self.model.generator.forward(dec) src = src.unsqueeze(1) scores = out.data.gather(1, src) scores.masked_fill_(src.eq(tgt_pad), 0) gold_scores += scores return gold_scores def tgt_to_index(self, tgt): return [self.tgt_vocab.stoi[word] for word in tgt] def src_to_index(self, src): return [self.src_vocab.stoi[word] for word in src] def mmi_score(self, beam, hyp_word, prediction_score): # return 1 # Get the source src_list = self.tgt_to_index(beam.source_text) # beam's source is target here hyp_list = self.src_to_index(hyp_word) # Src list to torch LongTensor src_list.insert(0, beam._bos) src_list.append(beam._eos) src_data = self.tt.LongTensor(src_list) hyp_lengths = self.tt.LongTensor([len(hyp_list) - 1]) hyp = self.tt.LongTensor(hyp_list[:-1]) # Remove EOS from the hyp which is the src to the MMI model if self.use_cuda: src_data = src_data.cuda() hyp_lengths = hyp_lengths.cuda() hyp = hyp.cuda() src_data.unsqueeze_(1) hyp.unsqueeze_(1) # print hyp score = self._run_target(hyp, src_data, hyp_lengths) / float(len(src_list)) # print hyp_word # print score # print self.beta * prediction_score, self.alpha * float(score), self.gamma * len(hyp_word) # print hyp_word # print "" return self.beta * prediction_score + self.alpha * score + self.gamma * len(hyp_word) def update_global_state(self, beam): "Keeps the coverage vector as sum of attens" if len(beam.prev_ks) == 1: beam.global_state["coverage"] = beam.attn[-1] else: beam.global_state["coverage"] = beam.global_state["coverage"] \ .index_select(0, beam.prev_ks[-1]).add(beam.attn[-1]) class GNMTGlobalScorer(object): """ NMT re-ranking score from "Google's Neural Machine Translation System" :cite:`wu2016google` Args: alpha (float): length parameter beta (float): coverage parameter """ def __init__(self, alpha, beta): self.alpha = alpha self.beta = beta def score(self, beam, logprobs): "Additional term add to log probability" cov = beam.global_state["coverage"] pen = self.beta * torch.min(cov, cov.clone().fill_(1.0)).log().sum(1) l_term = (((5 + len(beam.next_ys)) ** self.alpha) / ((5 + 1) ** self.alpha)) return (logprobs / l_term) + pen def update_global_state(self, beam): "Keeps the coverage vector as sum of attens" if len(beam.prev_ks) == 1: beam.global_state["coverage"] = beam.attn[-1] else: beam.global_state["coverage"] = beam.global_state["coverage"] \ .index_select(0, beam.prev_ks[-1]).add(beam.attn[-1]) <file_sep>import numpy as np from nltk.translate import bleu_score from nltk.translate.bleu_score import SmoothingFunction import logging from collections import defaultdict from embedding_metrics import embedding_score, eval_embedding from gensim.models import Word2Vec from gensim.models import KeyedVectors import os import nltk def get_tokenize(): return nltk.RegexpTokenizer(r'\w+|#\w+|<\w+>|%\w+|[^\w\s]+').tokenize class EvaluatorBase(object): def initialize(self): raise NotImplementedError def add_example(self, ref, hyp, domain='default'): raise NotImplementedError def get_report(self, include_error=False): raise NotImplementedError @staticmethod def _get_prec_recall(tp, fp, fn): precision = tp / (tp + fp + 10e-20) recall = tp / (tp + fn + 10e-20) f1 = 2 * precision * recall / (precision + recall + 1e-20) return precision, recall, f1 @staticmethod def _get_tp_fp_fn(label_list, pred_list): tp = len([t for t in pred_list if t in label_list]) fp = max(0, len(pred_list) - tp) fn = max(0, len(label_list) - tp) return tp, fp, fn class BleuEvaluator(EvaluatorBase): """ Use string matching to find the F-1 score of slots Use logistic regression to find F-1 score of acts Use string matching to find F-1 score of KB_SEARCH """ # logger = logging.getLogger(__name__) def __init__(self, data_name, embedding_path): self.data_name = data_name self.domain_labels = [] self.domain_hyps = [] self.w2v = None if os.path.exists(embedding_path): self.w2v = KeyedVectors.load_word2vec_format(embedding_path, binary=True) else: raise ValueError("cannot find the embedding file") def initialize(self): self.domain_labels = [] self.domain_hyps = [] def add_example(self, ref, hyp, domain='default'): self.domain_labels.append(ref) self.domain_hyps.append(hyp) def embedding_report(self,): refs = self.domain_labels hyps = self.domain_hyps eval_embedding(refs, hyps, self.w2v) def calc_diversity(self): tokens = [0.0,0.0] tokenize = get_tokenize() types = [defaultdict(int),defaultdict(int)] predictions = self.domain_hyps for line in predictions: words = tokenize(line)[:] for n in range(2): for idx in range(len(words)-n): ngram = ' '.join(words[idx:idx+n+1]) types[n][ngram] = 1 tokens[n] += 1 div1 = len(types[0].keys())/tokens[0] div2 = len(types[1].keys())/tokens[1] # print(types[1].keys()) print("Distinct-1: {}, words: {}; Distinct-2: {}, words: {}".format(div1, str(len(types[0].keys()))+'/' + str(tokens[0]), div2, str(len(types[1].keys()))+'/' + str(tokens[1]))) def get_report(self, include_error=False): reports = [] tokenize = get_tokenize() len_list = [] labels = self.domain_labels predictions = self.domain_hyps # print("Generate report for {} samples".format(len(predictions))) refs, hyps = [], [] for label, hyp in zip(labels, predictions): ref_tokens = tokenize(label)[:] hyp_tokens = tokenize(hyp)[:] refs.append([ref_tokens]) hyps.append(hyp_tokens) len_list.append(len(hyp_tokens)) # compute corpus level scores bleu1 = bleu_score.corpus_bleu(refs, hyps, smoothing_function=SmoothingFunction().method1, weights=(1, 0, 0, 0)) bleu2 = bleu_score.corpus_bleu(refs, hyps, smoothing_function=SmoothingFunction().method1, weights=(0.5, 0.5, 0, 0)) bleu3 = bleu_score.corpus_bleu(refs, hyps, smoothing_function=SmoothingFunction().method1, weights=(0.33, 0.33, 0.33, 0)) bleu4 = bleu_score.corpus_bleu(refs, hyps, smoothing_function=SmoothingFunction().method1) report = "\nBLEU-1 %f BLEU-2 %f BLEU-3 %f BLEU-4 %f Avg-len %f" % ( bleu1, bleu2, bleu3, bleu4, np.mean(len_list)) print(report) def load_file(ref, pred): with open(ref, 'r') as f: data_ref = f.readlines() with open(pred, 'r') as f: data_pred = f.readlines() num = min(len(data_ref), len(data_pred)) return data_ref[:num], data_pred[:num] def daily_eval(evaluator): ref_path = '/your/folder/mirror-cvae/data/daily_dialog/test/mmi_dialogues_y.txt' pred_path_list = [] pred_path_list.append('/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r235_b10_real.txt') pred_path_list.append('/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r236_b10_real.txt') pred_path_list.append('/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r237_b10_real.txt') pred_path_list.append('/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r257_b10_real.txt') pred_path_list.append('/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r258_b10_real.txt') pred_path_list.append('/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r259_b10_real.txt') pred_path_list.append('/your/folder/folder_dc_mmi/new_DC_10_decoding_dailydialog_dev_test_predictions_r1.txt') # pred_path_list.append('/your/folder/folder_dc_mmi/new_DCMMI_10_decoding_dailydialog_dev_test_predictions_r1.txt') pred_path_list.append('/your/folder/folder_dc_mmi/new_DCMMI_10_decoding_dailydialog_dev_test_predictions_r2.txt') pred_path_list.append('/your/folder/VHRED/Output/daily_hred.txt') pred_path_list.append('/your/folder/VHRED/Output/daily_vhred.txt') pred_path_list.append('/your/folder/folder_dc_mmi/new_Seq2Seq_decoding_dailydialog_dev_test_predictions_r1.txt') pred_path_list.append('/your/folder/folder_dc_mmi/new_Seq2Seq_decoding_dailydialog_dev_test_predictions_r2.txt') pred_path_list.append('/your/folder/folder_dc_mmi/new_MMI_decoding_dailydialog_dev_test_predictions_r1_b10.txt') #MMI B10 pred_path_list.append('/your/folder/folder_dc_mmi/new_MMI_decoding_dailydialog_dev_test_predictions_r1.txt') #MMI B50 pred_path_list.append(ref_path) print("\n\n\n#####################") print("**** DailyDialog ****") for pred_path in pred_path_list: print("================================") print("\ninitialize evaluator") print('current file: ' + pred_path) evaluator.initialize() data_ref, data_pred = load_file(ref_path, pred_path) print("line number: {}".format(len(data_pred))) evaluator.domain_labels = data_ref evaluator.domain_hyps = data_pred evaluator.get_report() evaluator.calc_diversity() evaluator.embedding_report() def movie_eval(evaluator): ref_path = '/your/folder/movietriple/test/pair_mmi_dialogues_y.txt' pred_path_list = [] pred_path_list.append('/your/folder/folder_mirror_nmt/new_mirror_output_movienodc10_r1_b10_real.txt') pred_path_list.append('/your/folder/folder_dc_mmi/DC_10_decoding_pair_movie_dev_test_predictions.txt') # pred_path_list.append('/your/folder/folder_dc_mmi/DCMMI_10_decoding_pair_movie_dev_test_predictions.txt') pred_path_list.append('/your/folder/folder_dc_mmi/DCMMI_10_decoding_pair_movie_dev_test_predictions_r2.txt') pred_path_list.append('/your/folder/VHRED/Output/movie_hred.txt') pred_path_list.append('/your/folder/VHRED/Output/movie_vhred.txt') pred_path_list.append('/your/folder/folder_dc_mmi/seq2seq_10_decoding_pair_movie_dev_test_predictions.txt') pred_path_list.append('/your/folder/folder_dc_mmi/new_Seq2Seq_decoding_movie_dev_test_predictions_r2.txt') pred_path_list.append('/your/folder/folder_dc_mmi/MMI_10_decoding_pair_movie_dev_test_predictions_b10.txt') pred_path_list.append('/your/folder/folder_dc_mmi/MMI_10_decoding_pair_movie_dev_test_predictions_b50.txt') pred_path_list.append(ref_path) print("\n\n\n#####################") print('Movie') for pred_path in pred_path_list: print("\ninitialize evaluator") print('current file: ' + pred_path) evaluator.initialize() data_ref, data_pred = load_file(ref_path, pred_path) print("line number: {}".format(len(data_pred))) evaluator.domain_labels = data_ref evaluator.domain_hyps = data_pred evaluator.get_report() evaluator.calc_diversity() evaluator.embedding_report() if __name__ == "__main__": evaluator = BleuEvaluator('Test', '/your/folder/GoogleNews-vectors-negative300.bin') daily_eval(evaluator) movie_eval(evaluator) # reddit_eval(evaluator) # persona_eval(evaluator) <file_sep>import json import random import numpy as np import csv from numpy.lib.utils import source def check_file(path, dest): with open(path, 'r') as f: data = f.readlines() new_data = [] for line in data: if len(line.strip().split())<1: new_data.append('<unk>') else: new_data.append(line.strip()) with open(dest, 'w') as f: for x in new_data: f.write(x+ '\n') class build_dialogs(): def __init__(self, ctx_path, x_path, y_path): self.ctx_data = self.read_files(ctx_path) self.x_data = self.read_files(x_path) self.y_data = self.read_files(y_path) assert len(self.ctx_data)==len(self.x_data) and len(self.ctx_data)==len(self.y_data) def read_files(self, path): with open(path, 'r') as f: data = f.readlines() return data def build_single(self, source, dest): data = self.read_files(source) new_dialogs = [] for idx, line in enumerate(data): new_dialogs.append('*********** Sampled Dialogs ***********') new_dialogs.append('CTX: ' + self.ctx_data[idx].strip()) new_dialogs.append('Turn A: ' + self.x_data[idx].strip()) new_dialogs.append('True B: ' + self.y_data[idx].strip()) new_dialogs.append('Pred B: ' + line.strip()) with open(dest, 'w') as f: for x in new_dialogs: f.write(x+ '\n') def build_multiple(self, source_dict, dest): # source_dict = {'a':'path1', 'b':'path2'} data = {} num = 99999 for k,v in source_dict.items(): data[k]=self.read_files(v) num = min(num, len(data[k])) new_dialogs = [] for idx in range(num): new_dialogs.append('*********** Sampled Dialogs ***********') new_dialogs.append('CTX: ' + self.ctx_data[idx].strip()) new_dialogs.append('Turn A: ' + self.x_data[idx].strip()) new_dialogs.append('Reference: ' + self.y_data[idx].strip()) for k, v in data.items(): new_dialogs.append(k+': ' + v[idx].strip()) with open(dest, 'w') as f: for x in new_dialogs: f.write(x+ '\n') def build_crowdsourcing_file(self, f1_path, f1_name, f2_path, f2_name, target_path): dialog_list = [] file1 = self.read_files(f1_path) file2 = self.read_files(f2_path) print(len(file1)) print(len(file2)) length = min(len(file1), len(file2)) selected_list = random.sample(range(length), 100) reply_order = [] for idx in selected_list: context = 'Speaker A: ' + self.ctx_data[idx].strip() query = 'Speaker B: ' + self.x_data[idx].strip() ctx = context + ' <br> ' + query truth = 'Truth: ' + self.y_data[idx] r1 = file1[idx].strip() r2 = file2[idx].strip() if np.random.random()>0.5: pair_name = f1_name + '_' + f2_name reply1 = r1 reply2 = r2 else: pair_name = f2_name + '_' + f1_name reply1 = r2 reply2 = r1 dialog_single = {'context':ctx.replace('<unk>','_unk_'), 'truth':truth.replace('<unk>','_unk_'), 'reply_1':reply1.replace('<unk>','_unk_'), 'reply_2':reply2.replace('<unk>','_unk_'), 'order':pair_name, 'dialog_id':idx} dialog_list.append(dialog_single) with open(target_path, 'w') as f: fnames = ['context','truth', 'reply_1', 'reply_2', 'order', 'dialog_id'] writer = csv.DictWriter(f, fieldnames=fnames) writer.writeheader() writer.writerows(dialog_list) def build_bert_files(): def build_bert_file_step(ctx_path, y_path, tgt_bert): with open(ctx_path, 'r') as f1: ctx_data = f1.readlines() with open(y_path, 'r') as f2: y_data = f2.readlines() print(len(ctx_data), len(y_data)) with open(tgt_bert, 'w') as tgt_bert: for idx, line in enumerate(y_data[:-2]): ctx_line = ctx_data[idx].replace('__utt__', '__eou__').strip() tgt_bert.write(ctx_line + ' __sep__ ' + line.strip() + ' __sep__ ' + '0' +'\n') def build_dailydialog_bert(): ctx = '/your/folder/daily_dialog/test/pair_mmi_dialogues_ctx_and_x.txt' y_1 = '/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r234_b10_real.txt' y_2 = '/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r235_b10_real.txt' y_3 = '/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r236_b10_real.txt' build_bert_file_step(ctx, y_1, y_1.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, y_2, y_2.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, y_3, y_3.replace('.txt', '_bert.txt')) vhred = '/your/folder/VHRED/Output/daily_vhred.txt' hred = '/your/folder/VHRED/Output/daily_hred.txt' dc_10 = '/your/folder/folder_dc_mmi/new_DC_10_decoding_dailydialog_dev_test_predictions_r1.txt' dcmmi_10 = '/your/folder/folder_dc_mmi/new_DCMMI_10_decoding_dailydialog_dev_test_predictions_r1.txt' seq2seq = '/your/folder/folder_dc_mmi/new_Seq2Seq_decoding_dailydialog_dev_test_predictions_r2.txt' build_bert_file_step(ctx, vhred, vhred.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, hred, hred.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, dc_10, dc_10.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, dcmmi_10, dcmmi_10.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, seq2seq, seq2seq.replace('.txt', '_bert.txt')) def build_movie_bert(): ctx = '/your/folder/movietriple/test/pair_mmi_dialogues_ctx_and_x.txt' y_1 = '/your/folder/folder_mirror_nmt/new_mirror_output_movienodc10_r1_b10_real.txt' build_bert_file_step(ctx, y_1, y_1.replace('.txt', '_bert.txt')) dc_10_movie = '/your/folder/folder_dc_mmi/DC_10_decoding_pair_movie_dev_test_predictions.txt' dcmmi_10__movie = '/your/folder/folder_dc_mmi/DCMMI_10_decoding_pair_movie_dev_test_predictions.txt' vhred_movie = '/your/folder/VHRED/Output/movie_vhred.txt' hred_movie = '/your/folder/VHRED/Output/movie_hred.txt' seq2seq = '/your/folder/folder_dc_mmi/new_Seq2Seq_decoding_movie_dev_test_predictions_r2.txt' build_bert_file_step(ctx, vhred_movie, vhred_movie.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, hred_movie, hred_movie.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, dc_10_movie, dc_10_movie.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, dcmmi_10__movie, dcmmi_10__movie.replace('.txt', '_bert.txt')) build_bert_file_step(ctx, seq2seq, seq2seq.replace('.txt', '_bert.txt')) build_dailydialog_bert() build_movie_bert() if __name__ == "__main__": def build_data_for_seq2seq(): def construct_two_part_dialog(data, set_): path_ctx = '/your/folder/{}/{}/pair_mmi_dialogues_ctx.txt'.format(data, set_) path_x = '/your/folder/{}/{}/pair_mmi_dialogues_x.txt'.format(data, set_) dest = '/your/folder/{}/{}/pair_mmi_dialogues_ctx_and_x.txt'.format(data, set_) def read_files(path): with open(path, 'r') as f: data = f.readlines() return data ctx = read_files(path_ctx) x = read_files(path_x) assert len(x)==len(ctx) with open(dest, 'w') as f: for ctx, x in zip(ctx, x): x_new = ctx.strip() + ' __utt__ ' + x.strip() f.write(x_new+ '\n') construct_two_part_dialog('daily_dialog', 'train') construct_two_part_dialog('daily_dialog', 'validation') construct_two_part_dialog('daily_dialog', 'test') construct_two_part_dialog('movietriple', 'train') construct_two_part_dialog('movietriple', 'validation') construct_two_part_dialog('movietriple', 'test') def dailydialog_func(): ctx_path = '/your/folder/daily_dialog/test/pair_mmi_dialogues_ctx.txt' x_path = '/your/folder/daily_dialog/test/pair_mmi_dialogues_x.txt' y_path = '/your/folder/daily_dialog/test/pair_mmi_dialogues_y.txt' builder = build_dialogs(ctx_path, x_path, y_path) vhred = '/your/folder/VHRED/Output/daily_vhred.txt' hred = '/your/folder/VHRED/Output/daily_hred.txt' dc_10 = '/your/folder/folder_dc_mmi/new_DC_10_decoding_dailydialog_dev_test_predictions_r1.txt' dcmmi_10 = '/your/folder/folder_dc_mmi/new_DCMMI_10_decoding_dailydialog_dev_test_predictions_r1.txt' seq2seq = '/your/folder/folder_dc_mmi/new_Seq2Seq_decoding_dailydialog_dev_test_predictions_r2.txt' mmi_50 = '/your/folder/folder_dc_mmi/new_MMI_decoding_dailydialog_dev_test_predictions_r1.txt' dcmmi_r2 = '/your/folder/folder_dc_mmi/new_DCMMI_10_decoding_dailydialog_dev_test_predictions_r2.txt' # def builder_wrap(idx): # mirror_b10 = '/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r{}_b10_real.txt'.format(idx) # builder.build_single(mirror_b10, '/your/folder/Mirror-NMT/generated_dialogs/' + 'r{}b10.txt'.format(idx)) # builder.build_crowdsourcing_file(mirror_b10, 'mirror', vhred, 'vhred', '/your/folder/Mirror-NMT/generated_dialogs/' + 'r{}b10_vhred.csv'.format(idx)) # builder.build_crowdsourcing_file(mirror_b10, 'mirror', hred, 'hred', '/your/folder/Mirror-NMT/generated_dialogs/' + 'r{}b10_hred.csv'.format(idx)) # builder.build_crowdsourcing_file(mirror_b10, 'mirror', dc_10, 'dc', '/your/folder/Mirror-NMT/generated_dialogs/' + 'r{}b10_dc.csv'.format(idx)) # builder.build_crowdsourcing_file(mirror_b10, 'mirror', dcmmi_10, 'dcmmi', '/your/folder/Mirror-NMT/generated_dialogs/' + 'r{}b10_dcmmi.csv'.format(idx)) # for exp in range(244, 245): # builder_wrap(exp) # mirror_b10_234 = '/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r234_b10_real.txt' # mirror_b10_257 = '/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r257_b10_real.txt' mirror_b10_236 = '/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r236_b10_real.txt' # builder.build_crowdsourcing_file(mirror_b10_236, 'mirror', mirror_b10_257, 'mirrorcat','/your/folder/Mirror-NMT/generated_dialogs/' + 'r236b10_r257.csv') # builder.build_crowdsourcing_file(mirror_b10_236, 'mirror', seq2seq, 'seq2seq','/your/folder/Mirror-NMT/generated_dialogs/' + 'r236b10_seq2seq.csv') # builder.build_crowdsourcing_file(mirror_b10_236, 'mirror', mmi_50, 'mmi','/your/folder/Mirror-NMT/generated_dialogs/' + 'r236b10_mmi.csv') builder.build_crowdsourcing_file(mirror_b10_236, 'mirror', dcmmi_r2, 'dcmmi','/your/folder/Mirror-NMT/generated_dialogs/' + 'r236b10_dcmmir2.csv') def reddit_func(): ctx_path = '/your/folder/reddit_dialog/test/pair_mmi_dialogues_ctx.txt' x_path = '/your/folder/reddit_dialog/test/pair_mmi_dialogues_x.txt' y_path = '/your/folder/reddit_dialog/test/pair_mmi_dialogues_y.txt' builder = build_dialogs(ctx_path, x_path, y_path) dc_10_reddit = '/your/folder/folder_dc_mmi/new_DC_10_decoding_pair_reddit_dev_test_predictions.txt' dcmmi_10_reddit = '/your/folder/folder_dc_mmi/new_DCMMI_10_decoding_pair_reddit_dev_test_predictions.txt' vhred_reddit = '/your/folder/VHRED/Output/reddit_vhred.txt' hred_reddit = '/your/folder/VHRED/Output/reddit_hred.txt' def builder_wrap(idx): mirror_b10 = '/your/folder/folder_mirror_nmt/new_mirror_output_redditnodc10_r{}_b10_real.txt'.format(idx) builder.build_single(mirror_b10, '/your/folder/Mirror-NMT/generated_dialogs/reddit/reddit_' + 'r{}b10.txt'.format(idx)) builder.build_crowdsourcing_file(mirror_b10, 'mirror', vhred_reddit, 'vhred', '/your/folder/Mirror-NMT/generated_dialogs/reddit/reddit_' + 'r{}b10_vhred.csv'.format(idx)) builder.build_crowdsourcing_file(mirror_b10, 'mirror', hred_reddit, 'hred', '/your/folder/Mirror-NMT/generated_dialogs/reddit/reddit_' + 'r{}b10_hred.csv'.format(idx)) builder.build_crowdsourcing_file(mirror_b10, 'mirror', dc_10_reddit, 'dc', '/your/folder/Mirror-NMT/generated_dialogs/reddit/reddit_' + 'r{}b10_dc.csv'.format(idx)) builder.build_crowdsourcing_file(mirror_b10, 'mirror', dcmmi_10_reddit, 'dcmmi', '/your/folder/Mirror-NMT/generated_dialogs/reddit/reddit_' + 'r{}b10_dcmmi.csv'.format(idx)) for idx in range(1,11): builder_wrap(idx) def movie_func(): ctx_path = '/your/folder/movietriple/test/pair_mmi_dialogues_ctx.txt' x_path = '/your/folder/movietriple/test/pair_mmi_dialogues_x.txt' y_path = '/your/folder/movietriple/test/pair_mmi_dialogues_y.txt' builder = build_dialogs(ctx_path, x_path, y_path) dc_10_movie = '/your/folder/folder_dc_mmi/DC_10_decoding_pair_movie_dev_test_predictions.txt' dcmmi_10__movie = '/your/folder/folder_dc_mmi/DCMMI_10_decoding_pair_movie_dev_test_predictions.txt' vhred_movie = '/your/folder/VHRED/Output/movie_vhred.txt' hred_movie = '/your/folder/VHRED/Output/movie_hred.txt' seq2seq = '/your/folder/folder_dc_mmi/new_Seq2Seq_decoding_movie_dev_test_predictions_r2.txt' # mmi_50 = '/your/folder/folder_dc_mmi/MMI_10_decoding_pair_movie_dev_test_predictions_b50.txt' dcmmi_r2_movie = '/your/folder/folder_dc_mmi/DCMMI_10_decoding_pair_movie_dev_test_predictions_r2.txt' # def builder_wrap(idx): # mirror_b10 = '/your/folder/folder_mirror_nmt/new_mirror_output_movienodc10_r{}_b10_real.txt'.format(idx) # builder.build_single(mirror_b10, '/your/folder/Mirror-NMT/generated_dialogs/movie/movie_' + 'r{}b10.txt'.format(idx)) # builder.build_crowdsourcing_file(mirror_b10, 'mirror', vhred_movie, 'vhred', '/your/folder/Mirror-NMT/generated_dialogs/movie/movie_' + 'r{}b10_vhred.csv'.format(idx)) # builder.build_crowdsourcing_file(mirror_b10, 'mirror', hred_movie, 'hred', '/your/folder/Mirror-NMT/generated_dialogs/movie/movie_' + 'r{}b10_hred.csv'.format(idx)) # builder.build_crowdsourcing_file(mirror_b10, 'mirror', dc_10_movie, 'dc', '/your/folder/Mirror-NMT/generated_dialogs/movie/movie_' + 'r{}b10_dc.csv'.format(idx)) # builder.build_crowdsourcing_file(mirror_b10, 'mirror', dcmmi_10__movie, 'dcmmi', '/your/folder/Mirror-NMT/generated_dialogs/movie/movie_' + 'r{}b10_dcmmi.csv'.format(idx)) # builder.build_crowdsourcing_file(mirror_b10, 'mirror', seq2seq, 'seq2seq', '/your/folder/Mirror-NMT/generated_dialogs/movie/movie_' + 'r{}b10_dcmmi.csv'.format(idx)) mirror_b10 = '/your/folder/folder_mirror_nmt/new_mirror_output_movienodc10_r1_b10_real.txt' # builder.build_crowdsourcing_file(mirror_b10, 'mirror', seq2seq, 'seq2seq', '/your/folder/Mirror-NMT/generated_dialogs/movie/movie_r1b10_seq2seq.csv') # builder.build_crowdsourcing_file(mirror_b10, 'mirror', mmi_50, 'mmi', '/your/folder/Mirror-NMT/generated_dialogs/movie/movie_r1b10_mmi.csv') builder.build_crowdsourcing_file(mirror_b10, 'mirror', dcmmi_r2_movie, 'dcmmi', '/your/folder/Mirror-NMT/generated_dialogs/movie/movie_r1b10_dcmmir2.csv') # for idx in [1]: # builder_wrap(idx) def build_all_dialogues(): ctx_path = '/your/folder/daily_dialog/test/pair_mmi_dialogues_ctx.txt' x_path = '/your/folder/daily_dialog/test/pair_mmi_dialogues_x.txt' y_path = '/your/folder/daily_dialog/test/pair_mmi_dialogues_y.txt' builder = build_dialogs(ctx_path, x_path, y_path) source_dict = { 'Seq2Seq': '/your/folder/folder_dc_mmi/new_Seq2Seq_decoding_dailydialog_dev_test_predictions_r2.txt', 'HRED': '/your/folder/VHRED/Output/daily_hred.txt', 'VHRED': '/your/folder/VHRED/Output/daily_vhred.txt', 'MMI': '/your/folder/folder_dc_mmi/new_MMI_decoding_dailydialog_dev_test_predictions_r1.txt', 'DC': '/your/folder/folder_dc_mmi/new_DC_10_decoding_dailydialog_dev_test_predictions_r1.txt', 'DCMMI': '/your/folder/folder_dc_mmi/new_DCMMI_10_decoding_dailydialog_dev_test_predictions_r2.txt', 'MIRROR': '/your/folder/folder_mirror_nmt/new_mirror_output_nodc10_r236_b10_real.txt' } dest = '/your/folder/Mirror-NMT/generated_dialogs/all_daily.txt' builder.build_multiple(source_dict, dest) # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ctx_path = '/your/folder/movietriple/test/pair_mmi_dialogues_ctx.txt' x_path = '/your/folder/movietriple/test/pair_mmi_dialogues_x.txt' y_path = '/your/folder/movietriple/test/pair_mmi_dialogues_y.txt' builder = build_dialogs(ctx_path, x_path, y_path) source_dict = { 'Seq2Seq': '/your/folder/folder_dc_mmi/new_Seq2Seq_decoding_movie_dev_test_predictions_r2.txt', 'HRED': '/your/folder/VHRED/Output/movie_hred.txt', 'VHRED': '/your/folder/VHRED/Output/movie_vhred.txt', 'MMI': '/your/folder/folder_dc_mmi/MMI_10_decoding_pair_movie_dev_test_predictions_b50.txt', 'DC': '/your/folder/folder_dc_mmi/DC_10_decoding_pair_movie_dev_test_predictions.txt', 'DCMMI': '/your/folder/folder_dc_mmi/DCMMI_10_decoding_pair_movie_dev_test_predictions_r2.txt', 'MIRROR': '/your/folder/folder_mirror_nmt/new_mirror_output_movienodc10_r1_b10_real.txt', } dest = '/your/folder/Mirror-NMT/generated_dialogs/all_movie.txt' builder.build_multiple(source_dict, dest) # build_all_dialogues() # reddit_func() # dailydialog_func() movie_func() # build_data_for_seq2seq() # build_bert_files() <file_sep>""" Word embedding based evaluation metrics for dialogue. This method implements three evaluation metrics based on Word2Vec word embeddings, which compare a target utterance with a model utterance: 1) Computing cosine-similarity between the mean word embeddings of the target utterance and of the model utterance 2) Computing greedy meatching between word embeddings of target utterance and model utterance (Rus et al., 2012) 3) Computing word embedding extrema scores (Forgues et al., 2014) We believe that these metrics are suitable for evaluating dialogue systems. Example run: python embedding_metrics.py path_to_ground_truth.txt path_to_predictions.txt path_to_embeddings.bin The script assumes one example per line (e.g. one dialogue or one sentence per line), where line n in 'path_to_ground_truth.txt' matches that of line n in 'path_to_predictions.txt'. NOTE: The metrics are not symmetric w.r.t. the input sequences. Therefore, DO NOT swap the ground truths with the predicted responses. References: A Comparison of Greedy and Optimal Assessment of Natural Language Student Input Word Similarity Metrics Using Word to Word Similarity Metrics. <NAME>, <NAME>. 2012. Proceedings of the Seventh Workshop on Building Educational Applications Using NLP, NAACL 2012. Bootstrapping Dialog Systems with Word Embeddings. <NAME>, <NAME>, <NAME>, <NAME>. 2014. Workshop on Modern Machine Learning and Natural Language Processing, NIPS 2014. """ from random import randint from gensim.models import Word2Vec from gensim.models import KeyedVectors import numpy as np import argparse import scipy.stats as stats def cosine_similarity(s, g): similarity = np.sum(s * g, axis=1) / np.sqrt((np.sum(s * s, axis=1) * np.sum(g * g, axis=1))) # return np.sum(similarity) return similarity def eval_embedding(ground_truth, samples, word2vec): samples = [[word2vec[s] for s in sent.split() if s in word2vec] for sent in samples] ground_truth = [[word2vec[s] for s in sent.split() if s in word2vec] for sent in ground_truth] indices = [i for i, s, g in zip(range(len(samples)), samples, ground_truth) if s != [] and g != []] samples = [samples[i] for i in indices] ground_truth = [ground_truth[i] for i in indices] n = len(samples) metric_average = embedding_metric(samples, ground_truth, word2vec, 'average') metric_extrema = embedding_metric(samples, ground_truth, word2vec, 'extrema') metric_greedy = embedding_metric(samples, ground_truth, word2vec, 'greedy') confidence_avg, confidence_extrema, confidence_greedy = 1.96*np.std(metric_average)/np.sqrt(len(metric_average)), 1.96*np.std(metric_extrema)/np.sqrt(len(metric_extrema)), 1.96*np.std(metric_greedy)/np.sqrt(len(metric_greedy)) print_str = 'Metrics - Average: {} (-+{}), Extrema: {} (-+{}), Greedy: {} (-+{})'.format(metric_average.mean(), confidence_avg, metric_extrema.mean(), confidence_extrema, metric_greedy.mean(), confidence_greedy) print(print_str) def embedding_metric(samples, ground_truth, word2vec, method='average'): if method == 'average': # s, g: [n_samples, word_dim] s = [np.mean(sample, axis=0) for sample in samples] g = [np.mean(gt, axis=0) for gt in ground_truth] return cosine_similarity(np.array(s), np.array(g)) elif method == 'extrema': s_list = [] g_list = [] for sample, gt in zip(samples, ground_truth): s_max = np.max(sample, axis=0) s_min = np.min(sample, axis=0) s_plus = np.absolute(s_min) <= s_max s_abs = np.max(np.absolute(sample), axis=0) s = s_max * s_plus + s_min * np.logical_not(s_plus) s_list.append(s) g_max = np.max(gt, axis=0) g_min = np.min(gt, axis=0) g_plus = np.absolute(g_min) <= g_max g_abs = np.max(np.absolute(gt), axis=0) g = g_max * g_plus + g_min * np.logical_not(g_plus) g_list.append(g) return cosine_similarity(np.array(s_list), np.array(g_list)) elif method == 'greedy': sim_list = [] for s, g in zip(samples, ground_truth): s = np.array(s) g = np.array(g).T sim = (np.matmul(s, g) / np.sqrt(np.matmul(np.sum(s * s, axis=1, keepdims=True), np.sum(g * g, axis=0, keepdims=True)))) sim = np.max(sim, axis=0) sim_list.append(np.mean(sim)) # return np.sum(sim_list) return np.array(sim_list) else: raise NotImplementedError def embedding_score(refs, preds, w2v): r = average(refs, preds, w2v) print(" Embedding Average Score: %f +/- %f ( %f )" %(r[0], r[1], r[2])) r = greedy_match(refs, preds, w2v) print(" Greedy Matching Score: %f +/- %f ( %f )" %(r[0], r[1], r[2])) r = extrema_score(refs, preds, w2v) print(" Extrema Score: %f +/- %f ( %f )" %(r[0], r[1], r[2])) def greedy_match(fileone, filetwo, w2v): res1 = greedy_score(fileone, filetwo, w2v) res2 = greedy_score(filetwo, fileone, w2v) res_sum = (res1 + res2)/2.0 return np.mean(res_sum), 1.96*np.std(res_sum)/np.sqrt(float(len(res_sum))), np.std(res_sum),res_sum.tolist() def greedy_score(fileone, filetwo, w2v): r1 = fileone r2 = filetwo # dim = w2v.layer_size # embedding dimensions dim =300 scores = [] for i in range(len(r1)): tokens1 = r1[i].strip().split() tokens2 = r2[i].strip().split() X= np.zeros((dim,)) y_count = 0 x_count = 0 o = 0.0 Y = np.zeros((dim,1)) for tok in tokens2: if tok in w2v: Y = np.hstack((Y,(w2v[tok].reshape((dim,1))))) y_count += 1 for tok in tokens1: if tok in w2v: w_vec = w2v[tok].reshape((1,dim)) tmp = np.dot(w_vec, Y)/ np.linalg.norm(w_vec)/np.linalg.norm(Y) # tmp = w2v[tok].reshape((1,dim)).dot(Y) o += np.max(tmp) x_count += 1 # if none of the words in response or ground truth have embeddings, count result as zero if x_count < 1 or y_count < 1: scores.append(0) continue o /= float(x_count) scores.append(o) return np.asarray(scores) def extrema_score(fileone, filetwo, w2v): r1 = fileone r2 = filetwo scores = [] for i in range(len(r1)): tokens1 = r1[i].strip().split() tokens2 = r2[i].strip().split() X= [] for tok in tokens1: if tok in w2v: X.append(w2v[tok]) Y = [] for tok in tokens2: if tok in w2v: Y.append(w2v[tok]) # if none of the words have embeddings in ground truth, skip if np.linalg.norm(X) < 0.00000000001: continue # if none of the words have embeddings in response, count result as zero if np.linalg.norm(Y) < 0.00000000001: scores.append(0) continue xmax = np.max(X, 0) # get positive max xmin = np.min(X,0) # get abs of min xtrema = [] for i in range(len(xmax)): if np.abs(xmin[i]) > xmax[i]: xtrema.append(xmin[i]) else: xtrema.append(xmax[i]) X = np.array(xtrema) # get extrema ymax = np.max(Y, 0) ymin = np.min(Y,0) ytrema = [] for i in range(len(ymax)): if np.abs(ymin[i]) > ymax[i]: ytrema.append(ymin[i]) else: ytrema.append(ymax[i]) Y = np.array(ytrema) o = np.dot(X, Y.T)/np.linalg.norm(X)/np.linalg.norm(Y) scores.append(o) scores = np.asarray(scores) return np.mean(scores), 1.96*np.std(scores)/np.sqrt(float(len(scores))), np.std(scores),scores.tolist() def average(fileone, filetwo, w2v): r1 = fileone r2 = filetwo # dim = w2v.layer_size # dimension of embeddings dim =300 scores = [] for i in range(len(r1)): tokens1 = r1[i].strip().split() tokens2 = r2[i].strip().split() X= np.zeros((dim,)) for tok in tokens1: if tok in w2v: X+=w2v[tok] Y = np.zeros((dim,)) for tok in tokens2: if tok in w2v: Y += w2v[tok] # if none of the words in ground truth have embeddings, skip if np.linalg.norm(X) < 0.00000000001: continue # if none of the words have embeddings in response, count result as zero if np.linalg.norm(Y) < 0.00000000001: scores.append(0) continue X = np.array(X)/np.linalg.norm(X) Y = np.array(Y)/np.linalg.norm(Y) o = np.dot(X, Y.T)/np.linalg.norm(X)/np.linalg.norm(Y) scores.append(o) scores = np.asarray(scores) return np.mean(scores), 1.96*np.std(scores)/np.sqrt(float(len(scores))), np.std(scores),scores.tolist() <file_sep>from __future__ import division """ This is the loadable seq2seq trainer library that is in charge of training details, loss compute, and statistics. See train.py for a use case of this library. Note!!! To make this a general library, we implement *only* mechanism things here(i.e. what to do), and leave the strategy things to users(i.e. how to do it). Also see train.py(one of the users of this library) for the strategy things we do. """ import time import sys import math import torch import torch.nn as nn import onmt import onmt.io import onmt.modules import logging class MirrorStatistics(object): """ Accumulator for loss statistics. Currently calculates: * accuracy * perplexity * elapsed time """ def __init__(self, loss_cxz2y=0, loss_cyz2x=0, loss_cz2x=0, loss_cz2y=0, loss_kl_1=0, loss_kl_2=0, n_words=0, n_correct=0): self.loss_cxz2y = loss_cxz2y self.loss_cyz2x = loss_cyz2x self.loss_cz2x = loss_cz2x self.loss_cz2y = loss_cz2y self.loss_kl = loss_kl_1 self.loss_kl_2 = loss_kl_2 self.loss = 0.0 self.n_src_words = 0.0 self.n_words_cxz2y = 0.0 self.n_correct_cxz2y = 0.0 self.n_words_cyz2x = 0.0 self.n_correct_cyz2x = 0.0 self.n_words_cz2y = 0.0 self.n_correct_cz2y = 0.0 self.n_words_cz2x = 0.0 self.n_correct_cz2x = 0.0 self.start_time = time.time() self.counter=0 def update(self, stat_cxz2y, stat_cyz2x, stat_cz2y, stat_cz2x, kl_loss, back_factor=1.): self.counter+=1 self.loss_cxz2y += stat_cxz2y.loss self.n_words_cxz2y += stat_cxz2y.n_words self.n_correct_cxz2y += stat_cxz2y.n_correct self.loss_cyz2x += stat_cyz2x.loss self.n_words_cyz2x += stat_cyz2x.n_words self.n_correct_cyz2x += stat_cyz2x.n_correct self.loss_cz2x += stat_cz2x.loss self.n_words_cz2x += stat_cz2x.n_words self.n_correct_cz2x += stat_cz2x.n_correct self.loss_cz2y += stat_cz2y.loss self.n_words_cz2y += stat_cz2y.n_words self.n_correct_cz2y += stat_cz2y.n_correct self.loss_kl += kl_loss self.loss =1.0 * (self.loss_cxz2y + self.loss_cyz2x * back_factor + self.loss_cz2x + self.loss_cz2y * back_factor ) self.n_words = self.n_words_cxz2y + self.n_words_cyz2x + self.n_words_cz2x + self.n_words_cz2y self.n_correct = self.n_correct_cxz2y + self.n_correct_cyz2x + self.n_correct_cz2x + self.n_correct_cz2y # def ppl_all(self): def accuracy(self, n_correct=None, n_words=1): if n_correct is not None: return 100 * (1.0 * n_correct / n_words) else: return 100 * (1.0 * self.n_correct / self.n_words) def ppl(self, loss=None, n_words=1): if loss is None: return math.exp(min(self.loss / self.n_words, 100)) else: return math.exp(min(loss / n_words, 100)) def elapsed_time(self): return time.time() - self.start_time def output(self, epoch, batch, n_batches, start): """Write out statistics to stdout. Args: epoch (int): current epoch batch (int): current batch n_batch (int): total batches start (int): start time of epoch. """ t = self.elapsed_time() print(("Overall: Epoch %2d, %5d/%5d; acc: %6.2f; ppl: %6.2f;" + " %6.0f s elapsed") % (epoch, batch, n_batches, self.accuracy(), self.ppl(), # self.loss * 0.5 + self.loss_kl, time.time() - start)) # print("----------") # print(1.0 * self.n_correct_cxz2y.item()/self.n_words_cxz2y.item()) # print(1.0 * self.n_correct_cxz2y.item(), self.n_words_cxz2y.item()) # print(1.0 * math.exp(self.loss_cxz2y/self.n_words_cxz2y.item())) # print(self.loss_cxz2y/self.n_words_cxz2y.item()) # print(self.loss_cxz2y, self.n_words_cxz2y.item()) # print(math.exp(self.loss_cyz2x/self.n_words_cyz2x.item())) # print(self.loss_cyz2x/self.n_words_cyz2x.item()) # print(self.loss_cyz2x, self.n_words_cyz2x.item()) print(("CXZ2Y: acc: %6.3f; ppl: %6.3f ") %(self.accuracy(self.n_correct_cxz2y, self.n_words_cxz2y),self.ppl(self.loss_cxz2y, self.n_words_cxz2y))) print(("CYZ2X: acc: %6.3f; ppl: %6.3f ") %(self.accuracy(self.n_correct_cyz2x, self.n_words_cyz2x),self.ppl(self.loss_cyz2x, self.n_words_cyz2x))) print(("CZ2Y: acc: %6.3f; ppl: %6.3f ") %(self.accuracy(self.n_correct_cz2y, self.n_words_cz2y),self.ppl(self.loss_cz2y, self.n_words_cz2y))) print(("CZ2X: acc: %6.3f; ppl: %6.3f ") %(self.accuracy(self.n_correct_cz2x, self.n_words_cz2x),self.ppl(self.loss_cz2x, self.n_words_cz2x))) print(("KL loss: %6.5f ") %(self.loss_kl/batch)) sys.stdout.flush() def log(self, prefix, experiment, lr): t = self.elapsed_time() experiment.add_scalar_value(prefix + "_ppl", self.ppl()) experiment.add_scalar_value(prefix + "_kl", self.loss_kl/batch) # experiment.add_scalar_value(prefix + "_tgtper", self.n_words / t) experiment.add_scalar_value(prefix + "_lr", lr) class Statistics(object): """ Accumulator for loss statistics. Currently calculates: * accuracy * perplexity * elapsed time """ def __init__(self, loss=0, n_words=0, n_correct=0): self.loss = loss self.n_words = n_words self.n_correct = n_correct self.n_src_words = 0 self.start_time = time.time() def update(self, stat): self.loss += stat.loss self.n_words += stat.n_words self.n_correct += stat.n_correct def accuracy(self): return 100 * (1. * self.n_correct / self.n_words) def ppl(self): return math.exp(min(self.loss / self.n_words, 100)) def elapsed_time(self): return time.time() - self.start_time def output(self, epoch, batch, n_batches, start): """Write out statistics to stdout. Args: epoch (int): current epoch batch (int): current batch n_batch (int): total batches start (int): start time of epoch. """ t = self.elapsed_time() print(("Epoch %2d, %5d/%5d; acc: %6.2f; ppl: %6.2f; " + "%3.0f src tok/s; %3.0f tgt tok/s; %6.0f s elapsed") % (epoch, batch, n_batches, self.accuracy(), self.ppl(), self.n_src_words / (t + 1e-5), self.n_words / (t + 1e-5), time.time() - start)) sys.stdout.flush() def log(self, prefix, experiment, lr): t = self.elapsed_time() experiment.add_scalar_value(prefix + "_ppl", self.ppl()) experiment.add_scalar_value(prefix + "_accuracy", self.accuracy()) experiment.add_scalar_value(prefix + "_tgtper", self.n_words / t) experiment.add_scalar_value(prefix + "_lr", lr) class Trainer(object): """ Class that controls the training process. Args: model(:py:class:`onmt.Model.NMTModel`): translation model to train train_loss(:obj:`onmt.Loss.LossComputeBase`): training loss computation valid_loss(:obj:`onmt.Loss.LossComputeBase`): training loss computation optim(:obj:`onmt.Optim.Optim`): the optimizer responsible for update trunc_size(int): length of truncated back propagation through time shard_size(int): compute loss in shards of this size for efficiency data_type(string): type of the source input: [text|img|audio] """ def __init__(self, model, train_loss, valid_loss, optim, trunc_size=0, shard_size=32, data_type='text', normalization="sents", accum_count=1, back_factor=1.0, kl_balance=False, kl_fix=-1): # Basic attributes. self.model = model self.optim = optim self.train_loss = train_loss self.valid_loss = valid_loss self.back_factor = back_factor self.trunc_size = trunc_size self.shard_size = shard_size self.data_type = data_type self.accum_count = accum_count self.padding_idx = self.train_loss.loss_cxz2y.padding_idx self.normalization = normalization self.kl_knealling = 1. self.kl_balance = kl_balance self.best_model = {'model_name':'ooo', 'model_ppl':9999} self.checkpoint_list=[] assert(accum_count > 0) if accum_count > 1: assert(self.trunc_size == 0), \ """To enable accumulated gradients, you must disable target sequence truncating.""" self.kl_fix = kl_fix # Set model in training mode. self.model.train() def get_kl_knealling(self, epoch, batch_id, batch_num): # kl_ft = min(1.0 * (epoch * batch_num + batch_id) / (4.0 * batch_num),1.) if self.kl_fix>=0: return self.kl_fix else: return min(1.0 * (epoch * batch_num + batch_id) / (self.kl_balance * batch_num),1.) def train(self, train_iter, epoch, report_func=None): """ Train next epoch. Args: train_iter: training data iterator epoch(int): the epoch number report_func(fn): function for logging Returns: stats (:obj:`onmt.Statistics`): epoch loss statistics """ total_stats = MirrorStatistics() report_stats = MirrorStatistics() idx = 0 truebatch = [] accum = 0 normalization = 0 try: add_on = 0 if len(train_iter) % self.accum_count > 0: add_on += 1 num_batches = len(train_iter) / self.accum_count + add_on except NotImplementedError: # Dynamic batching num_batches = -1 # print("accum count: {}, num_batches: {}".format(self.accum_count, num_batches)) def gradient_accumulation(truebatch_, total_stats_, report_stats_, nt_): if self.accum_count > 1: self.model.zero_grad() for batch in truebatch_: target_size = max(batch.tgt.size(0), batch.tgt_back.size(0)) # print("target size: {}, target_back size: {}".format(batch.tgt.size(), batch.tgt_back.size())) # 42, 256 # Truncated BPTT (we discard this function here) # if self.trunc_size: # trunc_size = self.trunc_size # else: trunc_size = target_size dec_state = None src = onmt.io.make_features(batch, 'src', self.data_type) src_back = onmt.io.make_features(batch, 'src_back', self.data_type) ctx = onmt.io.make_features(batch, 'ctx', self.data_type) if self.data_type == 'text': _, src_lengths = batch.src _, ctx_lengths = batch.ctx _, src_back_lengths = batch.src_back report_stats.n_src_words += src_lengths.sum() else: src_lengths = None tgt_outer = onmt.io.make_features(batch, 'tgt') tgt_back_outer = onmt.io.make_features(batch, 'tgt_back') for j in range(0, target_size-1, trunc_size): # 1. Create truncated target. tgt = tgt_outer[j: j + trunc_size] tgt_back = tgt_back_outer[j: j + trunc_size] # 2. F-prop all but generator. # if self.accum_count == 1: # self.model.zero_grad() self.optim._zero_grad() # outputs, attns, dec_state = \ # self.model(src, tgt, ctx, src_lengths, src_back, tgt_back, src_back_lengths, ctx_lengths, dec_state) results = self.model(src, tgt, ctx, src_lengths, src_back, tgt_back, src_back_lengths, ctx_lengths) out_cxz2y, dec_state_cxz2y, attns_cxz2y=results.out_cxz2y, results.dec_state_cxz2y, results.attns_cxz2y, out_cyz2x, dec_state_cyz2x, attns_cyz2x=results.out_cyz2x, results.dec_state_cyz2x, results.attns_cyz2x, out_cz2x, dec_state_cz2x, attns_cz2x=results.out_cz2x, results.dec_state_cz2x, results.attns_cz2x, out_cz2y, dec_state_cz2y, attns_cz2y =results.out_cz2y, results.dec_state_cz2y, results.attns_cz2y kl_loss = results.kl_loss # 3. Compute loss in shards for memory efficiency. batch_stats_cxz2y, loss_cxz2y = self.train_loss.loss_cxz2y.mirror_compute_loss( batch, out_cxz2y, attns_cxz2y, back=False, ctx_src=False) batch_stats_cyz2x, loss_cyz2x = self.train_loss.loss_cyz2x.mirror_compute_loss( batch, out_cyz2x, attns_cyz2x, back=True, ctx_src=False) batch_stats_cz2x, loss_cz2x = self.train_loss.loss_cz2x.mirror_compute_loss( batch, out_cz2x, attns_cz2x, back=True, ctx_src=True) batch_stats_cz2y, loss_cz2y = self.train_loss.loss_cz2y.mirror_compute_loss( batch, out_cz2y, attns_cz2y, back=False, ctx_src=True) loss_all = self.kl_knealling * kl_loss.div(nt_) + 0.5 * (loss_cxz2y + loss_cyz2x * self.back_factor + loss_cz2x + loss_cz2y * self.back_factor).div(nt_) # loss_all += kl_loss.div(nt_) loss_all.backward() # 4. Update the parameters and statistics. # if self.accum_count == 1: self.optim.step() total_stats_.update(batch_stats_cxz2y, batch_stats_cyz2x, batch_stats_cz2y, batch_stats_cz2x, self.kl_knealling*kl_loss.div(nt_)) report_stats_.update(batch_stats_cxz2y, batch_stats_cyz2x, batch_stats_cz2y, batch_stats_cz2x, self.kl_knealling*kl_loss.div(nt_)) # print(report_stats_.loss_cxz2y, report_stats_.n_words_cxz2y, report_stats_.loss_cyz2x, report_stats_.n_words_cyz2x) # print(report_stats_.n_correct_cxz2y, report_stats_.n_words_cxz2y, report_stats_.n_correct_cyz2x, report_stats_.n_words_cyz2x) # If truncated, don't backprop fully. # if dec_state is not None: # dec_state.detach() # if self.accum_count > 1: # self.optim.step() for i, batch_ in enumerate(train_iter): cur_dataset = train_iter.get_cur_dataset() self.train_loss.loss_cxz2y.cur_dataset = cur_dataset self.train_loss.loss_cz2x.cur_dataset = cur_dataset self.train_loss.loss_cyz2x.cur_dataset = cur_dataset self.train_loss.loss_cz2y.cur_dataset = cur_dataset # if self.kl_balance: self.kl_knealling = self.get_kl_knealling(epoch-1, i, len(train_iter)) truebatch.append(batch_) accum += 1 if self.normalization is "tokens": normalization += batch_.tgt[1:].data.view(-1) \ .ne(self.padding_idx) else: normalization += batch_.batch_size if accum == self.accum_count: gradient_accumulation( truebatch, total_stats, report_stats, normalization) if report_func is not None: report_stats = report_func( epoch, idx, num_batches, total_stats.start_time, self.optim.lr, report_stats) truebatch = [] accum = 0 normalization = 0 idx += 1 # if i>100: # break if len(truebatch) > 0: gradient_accumulation( truebatch, total_stats, report_stats, normalization) truebatch = [] return total_stats def validate(self, valid_iter): """ Validate model. valid_iter: validate data iterator Returns: :obj:`onmt.Statistics`: validation loss statistics """ # Set model in validating mode. self.model.eval() total_stats = MirrorStatistics() for batch in valid_iter: cur_dataset = valid_iter.get_cur_dataset() self.valid_loss.loss_cxz2y.cur_dataset = cur_dataset self.valid_loss.loss_cz2x.cur_dataset = cur_dataset self.valid_loss.loss_cyz2x.cur_dataset = cur_dataset self.valid_loss.loss_cz2y.cur_dataset = cur_dataset src = onmt.io.make_features(batch, 'src', self.data_type) src_back = onmt.io.make_features(batch, 'src_back', self.data_type) ctx = onmt.io.make_features(batch, 'ctx', self.data_type) if self.data_type == 'text': _, src_lengths = batch.src _, src_back_lengths = batch.src_back _, ctx_lengths = batch.ctx else: src_lengths = None tgt = onmt.io.make_features(batch, 'tgt') tgt_back = onmt.io.make_features(batch, 'tgt_back') # F-prop through the model. results = self.model(src, tgt, ctx, src_lengths, src_back, tgt_back, src_back_lengths, ctx_lengths) out_cxz2y, attns_cxz2y = results.out_cxz2y, results.attns_cxz2y, out_cyz2x, attns_cyz2x = results.out_cyz2x, results.attns_cyz2x, out_cz2x, attns_cz2x = results.out_cz2x, results.attns_cz2x, out_cz2y, attns_cz2y = results.out_cz2y, results.attns_cz2y kl_loss = results.kl_loss # 3. Compute loss in shards for memory efficiency. batch_stats_cxz2y = self.valid_loss.loss_cxz2y.mirror_monolithic_compute_loss( batch, out_cxz2y, attns_cxz2y, back=False, ctx_src=False) batch_stats_cyz2x = self.valid_loss.loss_cyz2x.mirror_monolithic_compute_loss( batch, out_cyz2x, attns_cyz2x, back=True, ctx_src=False) batch_stats_cz2y = self.valid_loss.loss_cz2y.mirror_monolithic_compute_loss( batch, out_cz2y, attns_cz2y, back=False, ctx_src=True) batch_stats_cz2x = self.valid_loss.loss_cz2x.mirror_monolithic_compute_loss( batch, out_cz2x, attns_cz2x, back=True, ctx_src=True) # total_stats.update(batch_stats_cxz2y, batch_stats_cyz2x, batch_stats_cz2y, batch_stats_cz2x, kl_loss.div(batch.batch_size)) total_stats.update(batch_stats_cxz2y, batch_stats_cyz2x, batch_stats_cz2y, batch_stats_cz2x, self.kl_knealling * kl_loss) # Set model back to training mode. self.model.train() return total_stats def epoch_step(self, ppl, epoch): return self.optim.update_learning_rate(ppl, epoch) def drop_checkpoint(self, opt, epoch, fields, valid_stats, time_str='', total_loss=0): """ Save a resumable checkpoint. Args: opt (dict): option object epoch (int): epoch number fields (dict): fields and vocabulary valid_stats : statistics of last validation run """ real_model = (self.model.module if isinstance(self.model, nn.DataParallel) else self.model) # real_generator_cxz2y = (real_model.generator_cxz2y.module # if isinstance(real_model.generator_cxz2y, nn.DataParallel) # else real_model.generator_cxz2y) # real_generator_cz2x = (real_model.generator_cz2x.module # if isinstance(real_model.generator_cz2x, nn.DataParallel) # else real_model.generator_cz2x) # real_generator_cyz2x = (real_model.generator_cyz2x.module # if isinstance(real_model.generator_cyz2x, nn.DataParallel) # else real_model.generator_cyz2x) # real_generator_cz2y = (real_model.generator_cz2y.module # if isinstance(real_model.generator_cz2y, nn.DataParallel) # else real_model.generator_cz2y) model_state_dict = real_model.state_dict() # model_state_dict = {k: v for k, v in model_state_dict.items() # if 'generator' not in k} model_state_dict = {k: v for k, v in model_state_dict.items()} # generator_state_dict = real_generator.state_dict() checkpoint = { 'model': model_state_dict, # 'generator': generator_state_dict, 'vocab': onmt.io.save_fields_to_vocab(fields), 'opt': opt, 'epoch': epoch, 'optim': self.optim, } # total_loss = (valid_stats.loss * 0.5 + valid_stats.loss_kl) total_loss = total_loss torch.save(checkpoint, '%s_time_%s_acc_%.2f_ppl_%.2f_lossall_%.2f_e%d.pt' % (opt.save_model, time_str, valid_stats.accuracy(), valid_stats.ppl(), total_loss, epoch)) file_path='%s_time_%s_acc_%.2f_ppl_%.2f_lossall_%.2f_e%d.pt'% (opt.save_model, time_str, valid_stats.accuracy(), valid_stats.ppl(), total_loss, epoch) self.checkpoint_list.append(file_path) # if valid_stats.ppl()<=self.best_model['model_ppl']: # self.best_model['model_ppl']=valid_stats.ppl() # self.best_model['model_name']=file_path if total_loss<=self.best_model['model_ppl']: self.best_model['model_ppl']=total_loss self.best_model['model_name']=file_path
553d67667434a563e7fdfbd2ea4932ae65be676f
[ "Markdown", "Python" ]
14
Markdown
cszmli/mirror-sigir
fbcf09a5317dbf4f9f5836a945279d97e90005ff
15fbe03d9f2003e52074bf0b88b89a843ff29058
refs/heads/master
<file_sep>#include <iostream> #define max 10 #define null -1 using namespace std; struct node { char element; int left; int right; }tree1[max], tree2[max]; int build(node * tree); bool isomorphic(int r1, int r2); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int r1 = 0, r2 = 0; r1 = build(tree1); r2 = build(tree2); if (r1!=-1 && r2!=-1) { if (isomorphic(r1,r2)) cout << "Yes"; else cout << "No"; }else if (r1==-1 && r2==-1) { cout << "Yes"; }else cout << "No"; return 0; } bool isomorphic(int r1, int r2) { if (r1==null && r2==null) return true; if (r1==null || r2==null) return false; int n1 = 0, n2 = 0; if (tree1[r1].left==null) n1++; if (tree1[r1].right==null) n1++; if (tree2[r2].left==null) n2++; if (tree2[r2].right==null) n2++; if (n1!=n2) return false; if (tree1[r1].element!=tree2[r2].element) return false; if (n1==2) return true; else if (n1==1) { if (tree1[r1].left==null&&tree2[r2].left==null) { return isomorphic(tree1[r1].right,tree2[r2].right); } else if (tree1[r1].left==null&&tree2[r2].right==null) { return isomorphic(tree1[r1].right,tree2[r2].left); } else if (tree1[r1].right==null&&tree2[r2].left==null) { return isomorphic(tree1[r1].left,tree2[r2].right); } else if (tree1[r1].right==null&&tree2[r2].right==null) { return isomorphic(tree1[r1].left,tree2[r2].left); } } else if (n1==0) { if (tree1[tree1[r1].left].element==tree2[tree2[r2].left].element) { return isomorphic(tree1[r1].left,tree2[r2].left) && isomorphic(tree1[r1].right,tree2[r2].right); }else{ return isomorphic(tree1[r1].left,tree2[r2].right) && isomorphic(tree1[r1].right,tree2[r2].left); } } return true; } int build(node * tree) { int n;cin >> n; if (n==0) return -1; int * select = new int [n]; char le, ri; for (int i = 0; i < n; i++) select[i] = 0; for (int i = 0; i < n; i++) { cin >> tree[i].element >> le >> ri; if (le!='-') { tree[i].left = le - '0'; select[tree[i].left] = 1; }else tree[i].left = null; if (ri!='-') { tree[i].right = ri - '0'; select[tree[i].right] = 1; }else tree[i].right = null; } int ret = 0; for (int i = 0; i < n; i++) { if (select[i]==0) { ret = i; break; } } delete [] select; return ret; } <file_sep>#include <iostream> #define inf 10000 using namespace std; struct node { int index; node * next; }; node * Prim(int ** Graph, int n); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, m;cin >> n >> m; int ** Graph = new int * [n]; for (int i = 0; i < n; i++) { Graph[i] = new int [n]; for (int j = 0; j < n; j++) { Graph[i][j] = inf; } } int src, dest, consume; for (int i = 0; i < m; i++) { cin >> src >> dest >> consume; Graph[src-1][dest-1] = consume; } node * header = Prim(Graph,n); if (!header->index) { cout << 0; }else{ cout << header->index << endl; node * ptr = header->next; while (ptr->next) { src = ptr->index + 1; dest = ptr->next->index + 1; cout << src << "->" << dest << endl; ptr = ptr->next; } } for (int i = 0; i < n; i++) { delete [] Graph[i]; } delete [] Graph; return 0; } node * Prim(int ** Graph, int n) { node * header = new node; header->index = 0;header->next = new node; node * ptr = header->next; ptr->index = 0;ptr->next = NULL; int * dist = new int [n]; bool * collected = new bool [n]; for (int i = 1; i < n; i++) { dist[i] = inf; collected[i] = false; } dist[0] = 0; collected[0] = true; for (int i = 0; i < n; i++) { if (Graph[0][i]!=inf) dist[i] = Graph[0][i]; } while (true) { int min = inf, v = -1; for (int i = 0; i < n; i++) { if (!collected[i] && dist[i]<min) { v = i; min = dist[i]; } } if (min==inf) break; collected[v] = true; header->index += dist[v]; dist[v] = 0; ptr->next = new node;ptr = ptr->next; ptr->index = v;ptr->next = NULL; for (int i = 0; i < n; i++) { if (!collected[i] && Graph[v][i]<dist[i]) { dist[i] = Graph[v][i]; } if (dist[n-1]!=inf) { header->index += dist[n-1]; ptr->next = new node;ptr = ptr->next; ptr->index = n-1;ptr->next = NULL; return header; } } } if (!collected[n-1]) header->index = 0; delete [] dist; delete [] collected; return header; } <file_sep>#include <iostream> #include <cstring> using namespace std; struct listnode { bool push; int index; }; struct node { int index; node * left; node * right; }; listnode * readlist(listnode * list, int k); node * addtree(listnode * list, int root, int last); void treeprt(node * root, bool isroot); int main(int argc, char const *argv[]) { int n;cin >> n; listnode * list = new listnode [n*2]; list = readlist(list,n*2); node * tree = addtree(list,0,n*2-1); treeprt(tree,true); return 0; } void treeprt(node * root, bool isroot) { if(root->left) treeprt(root->left,false); if(root->right) treeprt(root->right,false); cout << root->index; if (!isroot) cout << ' '; } node * addtree(listnode * list, int root, int last) { int end = root, push = 1, pull = 0; while (push>pull && end<last) { end++; if (list[end].push) { push++; }else{ pull++; } } node * rootnode = new node; rootnode->index = list[root].index; rootnode->left = NULL; rootnode->right = NULL; if (root+1!=end) rootnode->left = addtree(list,root+1,end-1); if (end<last) rootnode->right = addtree(list,end+1,last); return rootnode; } listnode * readlist(listnode * list, int k) { char oper[5] = {0}; for (int i = 0; i < k; ++i) { cin >> oper; if (!strcmp(oper,"Push")) { list[i].push = true; cin >> list[i].index; }else{ list[i].push = false; } } return list; }<file_sep>#include <iostream> #define _MIN_ -10001 using namespace std; struct Heap { int * element; int size; int maxsize; }; Heap * createHeap(int n); void insertHeap(Heap * H, int value); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, m, value, item;cin >> n >> m; Heap * H = createHeap(n); for (int i = 0; i < n; i++) { cin >> value; insertHeap(H,value); } for (int i = 0; i < m; i++) { cin >> item; while (item>1) { cout << H->element[item] << ' '; item /= 2; } cout << H->element[item] << endl; } return 0; } void insertHeap(Heap * H, int value) { int i = ++H->size; for ( ; H->element[i/2] > value; i/=2 ) { H->element[i] = H->element[i/2]; } H->element[i] = value; } Heap * createHeap(int n) { Heap * H = new Heap; H->element = new int [n+1]; H->element[0] = _MIN_; H->size = 0; H->maxsize = n; return H; } <file_sep>#include <iostream> #include <cstdlib> using namespace std; struct node { int data; bool leaf; unsigned int pos; char left; char right; }; int readtree(node * tree, int n, int * num); void attachweight(node * tree, int ptr, int weight); void printleaf(node * tree, int n); int cmp(const void * front, const void * rear); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n;cin >> n; node * tree = new node [n]; int leafnum = 0; int head = readtree(tree,n,&leafnum); //cout << head; attachweight(tree,head,1); //cout << "attach done"; qsort(tree,n,sizeof(node),cmp); //cout << "sorted"; printleaf(tree,leafnum); delete [] tree; return 0; } void printleaf(node * tree, int n) { int cnt = 0; for (int i = 0; true; i++) { if (tree[i].leaf) { cout << tree[i].data; ++cnt; if (cnt!=n) { cout << ' '; }else return; } } } int cmp(const void * front, const void * rear) { int ret = ((node*)front)->pos - ((node*)rear)->pos; return ret; } void attachweight(node * tree, int ptr, int weight) { tree[ptr].pos = weight; if (tree[ptr].left!='-') { attachweight(tree,tree[ptr].left-'0',2*weight); } if (tree[ptr].right!='-') { attachweight(tree,tree[ptr].right-'0',2*weight+1); } } int readtree(node * tree, int n, int * num) { bool * ishead = new bool [n]; for (int i = 0; i < n; i++) { ishead[i] = true; } for (int i = 0; i < n; i++) { tree[i].data = i; tree[i].leaf = true; cin >> tree[i].left >> tree[i].right; if (tree[i].left!='-') { tree[i].leaf = false; ishead[tree[i].left-'0'] = false; } if (tree[i].right!='-') { tree[i].leaf = false; ishead[tree[i].right-'0'] = false; } if (tree[i].leaf) { (*num)++; } } int head = 0; for (int i = 0; i < n; i++) { if (ishead[i]==true) { head = i; break; } } delete [] ishead; return head; } <file_sep>#include <iostream> #include <iomanip> #define max 100005 using namespace std; struct node { int ads; int data; int next; }; node memory[max]; int getlength(node * head); node * reverse(node * head, int k); void print(node * head, int length); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int ads, n, k;cin >> ads >> n >> k; int address, data, next; for (int i = 0; i < n; i++) { cin >> address >> data >> next; memory[address].ads = address; memory[address].data = data; memory[address].next = next; } node head, *headptr; head.next = ads; headptr = &head; int length = getlength(headptr); for (size_t i = k; i <= length; i+=k) { int front = headptr->next; headptr->next = reverse(headptr,k)->ads; headptr = &memory[front]; //print(&head,length);cout << endl; } headptr = &head; print(headptr,length); return 0; } node * reverse(node * head, int k) { node * front = &memory[head->next]; node * rear = &memory[front->next]; node * temp; int cnt = 1; while (cnt<k) { temp = &memory[rear->next]; rear->next = front->ads; front = rear; rear = temp; cnt++; } memory[head->next].next = rear->ads; return front; } int getlength(node * head) { int cnt = 0, adds = head->next; while (adds!=-1) { cnt++; adds = memory[adds].next; } return cnt; } void print(node * head, int length) { node * ptr = &memory[head->next]; for (size_t i = 0; i < length; i++) { cout << setw(5) << setfill('0') << ptr->ads; cout << ' ' << ptr->data << ' '; if ( i==length-1 ) cout << "-1"; else cout << setw(5) << setfill('0') << ptr->next << endl; ptr = &memory[ptr->next]; } } <file_sep>#include <iostream> #include <cmath> #define max 100 #define r 50 struct node { int x, y; bool flag, visited; }; node croco[max]; bool found = false; using namespace std; double getdis(int x1, int y1, int x2, int y2) { double ret = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); return ret; } void dfs(node * ptr, int n, int d); int main(int argc, char const *argv[]) { freopen("../test.txt", "r", stdin); int n, d;cin >> n >> d; for (int i = 0; i < n; ++i) { cin >> croco[i].x >> croco[i].y; croco[i].flag = r - abs(croco[i].x) <= d || r - abs(croco[i].y) <= d; croco[i].visited = false; } for (int i = 0; i < n && !found; ++i) { if (!croco[i].visited && getdis(0,0,croco[i].x,croco[i].y)<=7.5+d) dfs(&croco[i],n,d); } if (!found) cout << "No"; return 0; } void dfs(node * ptr, int n, int d) { if (ptr->flag) { found = true; cout << "Yes"; return; } ptr->visited = true; for (int i = 0; i < n && !found; ++i) { if (!croco[i].visited && getdis(ptr->x,ptr->y,croco[i].x,croco[i].y)<=d) dfs(&croco[i],n,d); } }<file_sep>#include <iostream> using namespace std; int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int k; cin >> k; int* a = new int [k]; for (int i = 0; i < k; i++) { cin >> a[i]; } int maxsum = 0, sum = 0, first = 0, i, j, zeroposition; bool track = false, getzero = false; for (int cnt = 0; cnt < k; cnt++) { sum += a[cnt]; if (sum<0 && track) { track = false; }else if (sum>0 && !track) { track = true; first = cnt; }else if (sum==0) { getzero = true; zeroposition = cnt; } if (sum>maxsum) { maxsum = sum; i = first; j = cnt; } else if(sum<0) { sum=0; } } if (maxsum>0) cout << maxsum << ' ' << a[i] << ' ' << a[j]; else if (maxsum==0 && getzero) cout << 0 << ' ' << 0 << ' ' << 0; else cout << 0 << ' ' << a[0] << ' ' << a[k-1]; delete [] a; return 0; } <file_sep>#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int k; cin >> k; int* a = new int [k]; for (size_t i = 0; i < k; i++) { cin >> a[i]; } int maxsum = 0, sum = 0; for (size_t i = 0; i < k; i++) { sum += a[i]; if (sum>maxsum) maxsum = sum; else if(sum<0)sum=0; } if (maxsum>0) cout << maxsum; else cout << 0; delete [] a; return 0; } <file_sep>#include <iostream> #define MAXN 50 using namespace std; int maxheight = 0; int n; char preorder[MAXN], inorder[MAXN]; void calheight(int height, int prestart, int preend, int instart, int inend); int main(){ cin >> n >> preorder >> inorder; calheight(0,0,n-1,0,n-1); cout << maxheight; return 0; } void calheight(int height, int prestart, int preend, int instart, int inend) { int currentheight = height + 1, num = inend - instart + 1; if (currentheight > maxheight ) maxheight = currentheight; // cout << "here"; if (instart>inend || prestart>preend) return; // cout << "hello"; char rootchar = preorder[prestart]; int rootofinorder = instart; for ( ; rootofinorder <= inend; ++rootofinorder) { if (inorder[rootofinorder] == rootchar) { break; } } // cout << rootofinorder << endl; //search the right tree! if (rootofinorder!=inend) { int numofright = inend - rootofinorder; calheight(currentheight,prestart+num-numofright,preend,rootofinorder+1,inend); } if (rootofinorder!=instart) { int numofleft = rootofinorder - instart; calheight(currentheight,prestart+1,prestart+numofleft,instart,rootofinorder-1); } }<file_sep>#include <iostream> #define inf 10000 using namespace std; int ** makeGraph(int n, int m); void deleteGraph(int ** G, int n); int Prim(int ** G, int n); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, m;cin >> n >> m; int ** G = makeGraph(n,m); cout << Prim(G,n); deleteGraph(G,n); return 0; } int Prim(int ** G, int n) { bool * collected = new bool [n]; int * dist = new int [n], mincost = 0; for (int i = 0; i < n; i++) { collected[i] = false; dist[i] = inf; } collected[0] = true; dist[0] = 0; for (int i = 1; i < n; i++) { if (G[0][i]<dist[i]) { dist[i] = G[0][i]; } } while (true) { bool found = false; int min = inf, v = 0; for (int i = 1; i < n; i++) { if (!collected[i] && dist[i]<min) { found = true; min = dist[i]; v = i; } } if (!found) { break; } mincost += min; collected[v] = true; dist[v] = 0; // for every node w linking to the node v for (int w = 0; w < n; w++) { if (G[v][w]!=inf && !collected[w]) { if (G[v][w] < dist[w]) { dist[w] = G[v][w]; } } } } for (int i = 0; i < n; i++) { if (collected[i]==false) { return -1; } } return mincost; } void deleteGraph(int ** G, int n) { for (int i = 0; i < n; i++) { delete [] G[i]; } delete [] G; } int ** makeGraph(int n, int m) { int ** G = new int* [n]; for (int i = 0; i < n; i++) { G[i] = new int [n]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { G[i][j] = inf; } } int city1, city2, cost; for (int i = 0; i < m; i++) { cin >> city1 >> city2 >> cost; G[city1-1][city2-1] = cost; G[city2-1][city1-1] = cost; } return G; } <file_sep>#include <iostream> #include <cstring> #define max 6999 char c[max] = {0}; int f[max] = {0}; using namespace std; struct node { int freq; node * left; node * right; }; struct MinHeap { node * h[max]; int cap; }; void insert(MinHeap * heap, node * fnode) { int i = ++heap->cap; while (heap->h[i/2]->freq > fnode->freq) { heap->h[i] = heap->h[i/2]; i /= 2; } heap->h[i] = fnode; // cout << "inserting " << fnode->freq << endl; } node * pop(MinHeap * heap) { node * ret = heap->h[1]; heap->h[1] = heap->h[heap->cap--]; bool btl, btr; int i = 1; while (true) { if (i * 2 > heap->cap) break; if (i * 2 + 1 > heap->cap) { btl = heap->h[i]->freq > heap->h[i * 2]->freq; if (btl) { node * tmp = heap->h[i]; heap->h[i] = heap->h[i*2]; heap->h[i*2] = tmp; } break; } btl = heap->h[i]->freq > heap->h[i * 2]->freq; btr = heap->h[i]->freq > heap->h[i * 2 + 1]->freq; if (btl && btr) { if (heap->h[i*2]->freq - heap->h[i*2+1]->freq > 0) { btl = false; }else btr = false; } if (btl && !btr) { node * tmp = heap->h[i]; heap->h[i] = heap->h[i*2]; heap->h[i*2] = tmp; i *= 2; }else if (!btl && btr) { node * tmp = heap->h[i]; heap->h[i] = heap->h[i*2+1]; heap->h[i*2+1] = tmp; i = i * 2 + 1; }else if (!btl && !btr) { break; } } // cout << "poping " << ret->freq << endl; return ret; } int codelen(node * p, int depth) { if (!p->left) return depth * p->freq; else return codelen(p->left,depth+1) + codelen(p->right,depth+1); } int main(int argc, char const *argv[]) { freopen("../test.txt", "r", stdin); int n; cin >> n; MinHeap heap;heap.cap = 0;heap.h[0] = new node; heap.h[0]->freq = 0; for (int i = 0; i < n; ++i) { cin >> c[i] >> f[i]; node * temp = new node; temp->left = temp->right = NULL;temp->freq = f[i]; insert(&heap,temp); } while (heap.cap > 1) { node * n1 = pop(&heap); node * n2 = pop(&heap); node * newnode = new node; newnode->freq = n1->freq + n2->freq; newnode->left = n1; newnode->right = n2; insert(&heap,newnode); } int standlen = codelen(heap.h[1],0); // cout << standlen; int m;cin >> m; for (int j = 0; j < m; ++j) { // cout << "setting falg true"; bool flag = true; char c, str[max]; int tree[max*2+1], sum = 0; for (int i = 0; i < max*2+1; ++i) { tree[i] = -1; } for (int k = 0; k < n; ++k) { cin >> c >> str; sum += strlen(str) * f[k]; if (sum > standlen) { flag = false; continue; } char * ptr = str;int i = 1; while (*ptr!='\0' && flag) { if (*ptr++ == '0') i *= 2; else i = i * 2 + 1; if (*ptr == '\0') { if (tree[i * 2 + 1] != -1 || tree[i * 2] != -1) flag = false; else if (tree[i]==-1) tree[i] = 1; else if (tree[i]==0 || tree[i]==1) flag = false; }else{ if (tree[i]==-1) tree[i]=0; if (tree[i]== 1) flag = false; } } } switch (flag) { case true: cout << "Yes" << endl; break; case false: cout << "No" << endl; break; } } return 0; }<file_sep>/* starting at 14:35 ending at 14:40 */ #include <iostream> #include <cstdlib> using namespace std; int cmp(const void * a, const void * b) { return *((int*)a) - *((int*)b); } int main(int argc, char const *argv[]) { int n;cin >> n; int * input = new int [n]; for (int i = 0; i < n; i++) cin >> input[i]; qsort(input,n,sizeof(int),cmp); for (int i = 0; i < n; i++) { cout << input[i]; if (i + 1 != n) cout << ' '; } return 0; } <file_sep>#include <iostream> using namespace std; struct node { int element; node * next; }; struct Queue { int * queue; int head; int tail; int size; }; node * createGraph(int n); void readGraph(node * G, int e); void DFSlistComponents(node * G, int n); void deleteGraph(node * G, int n); void BFSlistComponents(node * G, int n); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, e;cin >> n >> e; node * G = createGraph(n); readGraph(G,e); DFSlistComponents(G,n); BFSlistComponents(G,n); deleteGraph(G,n); return 0; } int findMin(node * ptr, bool * visited) { int min; while (ptr->next && visited[ptr->next->element]) { ptr = ptr->next; } if (ptr->next==NULL) return -1; else min = ptr->next->element; ptr = ptr->next->next; while (ptr) { if (ptr->element<min && !visited[ptr->element]) { min = ptr->element; } ptr = ptr->next; } return min; } bool remains(node * ptr, bool * visited) { while (ptr->next) { if (!visited[ptr->next->element]) { return true; } ptr = ptr->next; } return false; } Queue * creatQueue(int n) { Queue * q = new Queue; q->size = n; q->queue = new int [n]; q->head = 0; q->tail = -1; return q; } void deleteQueue(Queue * q) { delete [] q->queue; delete q; } void enQueue(Queue * q, int element) { q->queue[++q->tail] = element; } int deQueue(Queue * q) { return q->queue[q->head++]; } void push(Queue * q, node * ptr, bool * visited) { while (remains(ptr,visited)) { int min = findMin(ptr,visited); if (min==-1) return; enQueue(q,min); visited[min] = true; } } void BFSlistComponents(node * G, int n) { Queue * q = creatQueue(n); bool * visited = new bool [n]; for (int i = 0; i < n; i++) { visited[i] = false; } for (int i = 0; i < n; i++) { if (!visited[i]) { cout << "{ "; enQueue(q,i); visited[i] = true; while (q->head!=q->tail+1) { int popelement = deQueue(q); cout << popelement <<" "; push(q,&G[popelement],visited); } cout << '}' << endl; } } delete [] visited; deleteQueue(q); } void DFS(node * G, int i, bool * visited) { while (remains(&G[i],visited)) { int min = findMin(&G[i],visited); if (min==-1) return; cout << min <<" "; visited[min] = true; DFS(G,min,visited); } } void DFSlistComponents(node * G, int n) { bool * visited = new bool [n]; for (int i = 0; i < n; i++) { visited[i] = false; } for (int i = 0; i < n; i++) { if (visited[i]) continue; cout << "{ "; if (!visited[i]) { cout << i <<" "; visited[i] = true; DFS(G,i,visited); } cout << "}" << endl; } delete [] visited; } void deleteGraph(node * G, int n) { for (int i = 0; i < n; i++) { node * ptr = G[i].next; while (ptr) { node * temp = ptr->next; delete ptr; ptr = temp; } } delete [] G; } void insertEdge(node * G, int i, int j) { node * ptr = &G[i]; while (ptr->next) { ptr = ptr->next; } ptr->next = new node; ptr = ptr->next; ptr->element = j; ptr->next = NULL; ptr = &G[j]; while (ptr->next) { ptr = ptr->next; } ptr->next = new node; ptr = ptr->next; ptr->element = i; ptr->next = NULL; } void readGraph(node * G, int e) { int vi, vj; for (int i = 0; i < e; i++) { cin >> vi >> vj; insertEdge(G, vi, vj); } } node * createGraph(int n) { node * G = new node [n]; for (int i = 0; i < n; i++) { G[i].element = i; G[i].next = NULL; } return G; } <file_sep>#include <iostream> #include <iomanip> using namespace std; struct node { int element; node * next; }; struct Queue { int * queue; int head; int tail; int size; }; node * createGraph(int n); void readGraph(node * G, int e); int BFSvalid(node * G, int i, int n); void deleteGraph(node * G, int n); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, m;cin >> n >> m; node * G = createGraph(n); readGraph(G,m); for (int i = 0; i < n; i++) { int valid = BFSvalid(G,i,n); double percentage = valid / (double)n; cout << i + 1 << ": "; cout << fixed << setprecision(2) << 100 * percentage; cout << '%' << endl; } deleteGraph(G,n); return 0; } int findMin(node * ptr, bool * visited) { int min; while (ptr->next && visited[ptr->next->element]) { ptr = ptr->next; } if (ptr->next==NULL) return -1; else min = ptr->next->element; ptr = ptr->next->next; while (ptr) { if (ptr->element<min && !visited[ptr->element]) { min = ptr->element; } ptr = ptr->next; } return min; } bool remains(node * ptr, bool * visited) { while (ptr->next) { if (!visited[ptr->next->element]) { return true; } ptr = ptr->next; } return false; } Queue * creatQueue(int n) { Queue * q = new Queue; q->size = n; q->queue = new int [n]; q->head = 0; q->tail = -1; return q; } void deleteQueue(Queue * q) { delete [] q->queue; delete q; } void enQueue(Queue * q, int element) { q->queue[++q->tail] = element; } int deQueue(Queue * q) { return q->queue[q->head++]; } void push(Queue * q, node * ptr, bool * visited, int * cnt) { while (remains(ptr,visited)) { int min = findMin(ptr,visited); if (min==-1) return; enQueue(q,min); (*cnt)++; visited[min] = true; } } int BFSvalid(node * G, int start, int n) { //return the number of valid nodes Queue * q = creatQueue(n); //of the BFS of node i bool * visited = new bool [n]; for (int i = 0; i < n; i++) { visited[i] = false; } int cnt = 1, degree = 6; enQueue(q,start); visited[start] = true; int sentry = q->tail; while (q->head!=q->tail+1 && degree>0) { while (q->head!=sentry+1) { int popelement = deQueue(q); push(q,&G[popelement],visited,&cnt); } sentry = q->tail; degree--; } delete [] visited; deleteQueue(q); return cnt; } void deleteGraph(node * G, int n) { for (int i = 0; i < n; i++) { node * ptr = G[i].next; while (ptr) { node * temp = ptr->next; delete ptr; ptr = temp; } } delete [] G; } void insertEdge(node * G, int i, int j) { node * ptr = &G[i]; while (ptr->next) { ptr = ptr->next; } ptr->next = new node; ptr = ptr->next; ptr->element = j; ptr->next = NULL; ptr = &G[j]; while (ptr->next) { ptr = ptr->next; } ptr->next = new node; ptr = ptr->next; ptr->element = i; ptr->next = NULL; } void readGraph(node * G, int e) { int vi, vj; for (int i = 0; i < e; i++) { cin >> vi >> vj; insertEdge(G, vi-1, vj-1); } } node * createGraph(int n) { node * G = new node [n]; for (int i = 0; i < n; i++) { G[i].element = i; G[i].next = NULL; } return G; } <file_sep>#include <iostream> #include "Graph_linked_list.h" using namespace std; struct Vertex { int index; int earliest_finish_time; int latest_finish_time; }; struct Edge { int required_time; int flexible_time; }; int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, m;cin >> n >> m; Edge ** Graph = new Edge * [n]; Vertex * vertexlist = new Vertex [n]; int * indegree = new int [n]; for (int i = 0; i < n; i++) { Graph[i] = new Edge [n]; for (int j = 0; j < n; j++) { Graph[i][j].required_time = 0; Graph[i][j].flexible_time = 0; } vertexlist[i].index = i; vertexlist[i].earliest_finish_time = 0; vertexlist[i].latest_finish_time = 0; indegree[i] = 0; } int src, dest, consume; for (int i = 0; i < m; i++) { cin >> src >> dest >> consume; Graph[src-1][dest-1].required_time = consume; indegree[dest-1]++; } for (int i = 0; i < n; i++) delete [] Graph[i]; delete [] Graph; delete [] vertexlist; delete [] indegree; return 0; } /* 邻接表存储 - 拓扑排序算法 */ bool TopSort( LGraph Graph, Vertex TopOrder[] ) { /* 对Graph进行拓扑排序, TopOrder[]顺序存储排序后的顶点下标 */ int Indegree[MaxVertexNum], cnt; Vertex V; PtrToAdjVNode W; Queue Q = CreateQueue( Graph->Nv ); /* 初始化Indegree[] */ for (V=0; V<Graph->Nv; V++) Indegree[V] = 0; /* 遍历图,得到Indegree[] */ for (V=0; V<Graph->Nv; V++) for (W=Graph->G[V].FirstEdge; W; W=W->Next) Indegree[W->AdjV]++; /* 对有向边<V, W->AdjV>累计终点的入度 */ /* 将所有入度为0的顶点入列 */ for (V=0; V<Graph->Nv; V++) if ( Indegree[V]==0 ) AddQ(Q, V); /* 下面进入拓扑排序 */ cnt = 0; while( !IsEmpty(Q) ){ V = DeleteQ(Q); /* 弹出一个入度为0的顶点 */ TopOrder[cnt++] = V; /* 将之存为结果序列的下一个元素 */ /* 对V的每个邻接点W->AdjV */ for ( W=Graph->G[V].FirstEdge; W; W=W->Next ) if ( --Indegree[W->AdjV] == 0 )/* 若删除V使得W->AdjV入度为0 */ AddQ(Q, W->AdjV); /* 则该顶点入列 */ } /* while结束*/ if ( cnt != Graph->Nv ) return false; /* 说明图中有回路, 返回不成功标志 */ else return true; } <file_sep>#include <iostream> #include <cstring> using namespace std; struct node { char address[6]; int data; char next[6]; }; int getelement(node * list, int n, char * address); void exchange(node * list, int element, int i); void printlist(node * list, int n); void reverse(node * list, int n, int k); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); char address[6];int n, k;cin >> address >> n >> k; node * list = new node [n]; for (int i = 0; i < n; i++) { cin >> list[i].address >> list[i].data >> list[i].next; } // ranking problem for (int i = 0; i < n; i++) { int element = getelement(list,n,address); strcpy(address,list[element].next); exchange(list,element,i); if (address[0]=='-') { n = i + 1; break; } } reverse(list,n,k); printlist(list,n); return 0; } void reverse(node * list, int n, int k) { int start = 0, end = k-1; if (end+1 > n) return; // change next for (int i = end; i >= start; i--) { if (i==start) { if (end+1==n) { strcpy(list[i].next,"-1"); }else{ strcpy(list[i].next,list[end+1].address); } } else strcpy(list[i].next,list[i-1].address); } // change sequence for (int i = start, j = end; i<j; i++, j--) { exchange(list,i,j); } } void printlist(node * list, int n) { for (int i = 0; i < n; i++) { cout << list[i].address << ' ' << list[i].data; cout << ' ' << list[i].next << endl; } } int getelement(node * list, int n, char * address) { for (int i = 0; i < n; i++) { if ( strcmp(list[i].address,address)==0 ) { return i; } } return -1; } void exchange(node * list, int element, int i) { node temp = list[element]; list[element] = list[i]; list[i] = temp; } <file_sep>#include <iostream> #define inf 10000 using namespace std; struct edge { int smallcity; int largecity; int weight; }; struct MinHeap { edge * elements; int size; int capacity; }; int ** makeGraph(int n, int m); void deleteGraph(int ** G, int n); edge * createSet(int ** G, int n, int m); void deleteSet(edge * E); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, m;cin >> n >> m; int ** G = makeGraph(n,m); edge * E = createSet(G,n,m); deleteGraph(G,n); deleteSet(E); return 0; } edge deleteMin(MinHeap * H) { int parent = 1, child; edge minitem = H->elements[1], temp = H->elements[H->size--]; for ( ; parent*2<=H->size; parent=child) { child = parent * 2; if (child!=H->size && H->elements[child].weight>H->elements[child+1].weight) { child++; } if (temp.weight>=H->elements[child].weight) { H->elements[parent] = H->elements[child]; }else break; } H->elements[parent] = temp; return minitem; } void Insert(MinHeap * H, edge item) { int i = ++H->size; for ( ; H->elements[i/2].weight>item.weight; i/=2) { H->elements[i] = H->elements[i/2]; } H->elements[i] = item; } MinHeap * creatHeap(edge * E, int m) { MinHeap * H = new MinHeap; H->elements = new edge [m+1]; H->size = 0; H->capacity = m; H->elements[0].weight = inf; for (int i = 0; i < m; i++) { Insert(H,E[i]); } return H; } int Kruskal(int n, int m, edge * E) { edge * MST = new edge [n-1]; int cntMST = 0, cntEdge = m, sum = 0; MinHeap * H = creatHeap(E,m); while (cntMST<n-1 && cntEdge) { deleteMin(H); } delete [] MST; return sum; } void deleteSet(edge * E) { delete [] E; } edge * createSet(int ** G, int n, int m) { edge * E = new edge [m]; int cnt = 0; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { if (G[i][j]!=inf) { E[cnt].smallcity = i; E[cnt].largecity = j; E[cnt].weight = G[i][j]; cnt++; } } } return E; } void deleteGraph(int ** G, int n) { for (int i = 0; i < n; i++) { delete [] G[i]; } delete [] G; } int ** makeGraph(int n, int m) { int ** G = new int* [n]; for (int i = 0; i < n; i++) { G[i] = new int [n]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { G[i][j] = inf; } } int city1, city2, cost; for (int i = 0; i < m; i++) { cin >> city1 >> city2 >> cost; G[city1-1][city2-1] = cost; G[city2-1][city1-1] = cost; } return G; } <file_sep>#include <iostream> #define MAXN 100 using namespace std; struct Node { int index; int earliest; int latest; }; struct Edge { int src; int dst; int time; }; struct EdgePtr { int src; //indegree when as a header int time; EdgePtr * next; }; int n, m; EdgePtr * Graph[MAXN]; Node node[MAXN]; Edge edge[MAXN*(MAXN-1)/2]; Node * queue[MAXN]; int front = 0, rear = -1; void init(); void test(); int GetIndegree(int index); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); cin >> n >> m; init(); TopSort(); return 0; } void TopSort() { int cnt = 0; for (size_t i = 0; i < n; i++) { if (GetIndegree(node[i].index)==0) { Enqueue(&node); } } while (!IsEmpty()) { Node * v = Dequeue();cnt++; //do something EdgePtr ptr = Graph[v->index]->next; while (ptr) { if } } } bool IsEmpty() { return front == rear + 1; } void Enqueue(Node * ptr) { queue[++rear] = ptr; } Node * Dequeue() { return queue[front++]; } void init() { for (int i = 0; i < n; i++) { node[i].index = i; node[i].earliest = node[i].latest = 0; Graph[i] = new EdgePtr; Graph[i]->src = 0; //indegree Graph[i]->next = NULL; } for (int i = 0; i < m; i++) { cin >> edge[i].src >> edge[i].dst >> edge[i].time; } for (int i = m; i < MAXN; i++) { edge[i].src = edge[i].dst = edge[i].time = 0; } for (int i = 0; i < m; i++) { /* insest */ EdgePtr * temp = new EdgePtr, * header = Graph[edge[i].dst]; temp->src = edge[i].src; temp->next = header->next; header->next = temp; header->src++; } } void test() { for (int i = 0; i < m; i++) { cout << Graph[i]->src << endl; } } int GetIndegree(int index) { return Graph[index]->src; } <file_sep>#include <iostream> #define inf 10000 using namespace std; struct node { int element; int weight; node * next; }; node * createGraph(int n); void readGraph(node * G, int e); int Dijkstra(node * G, int n, int s); void deleteGraph(node * G, int n); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, m;cin >> n >> m; node * G = createGraph(n); readGraph(G,m); int * shortest = new int [n]; for (int i = 0; i < n; i++) shortest[i] = -1; //if cannot reach all for (int i = 0; i < n; i++) { shortest[i] = Dijkstra(G,n,i); //return } int animal = 0, length = inf; for (int i = 0; i < n; i++) { if (shortest[i]!=-1 && shortest[i]<length) { length = shortest[i]; animal = i + 1; } } if (animal==0) { cout << 0; }else{ cout << animal << ' ' << length; } deleteGraph(G,n); delete [] shortest; return 0; } int Dijkstra(node * G, int n, int s) { int * dist = new int [n]; int * path = new int [n]; bool * collected = new bool [n]; for (int i = 0; i < n; i++) { dist[i] = inf; path[i] = -1; collected[i] = false; } dist[s] = 0; collected[s] = true; node * ptr = G[s].next; while (ptr) { if (!collected[ptr->element]) { int w = ptr->element; if (dist[s]+ptr->weight<dist[w]) { dist[w] = dist[s] + ptr->weight; path[w] = s; } } ptr = ptr->next; } while (true) { int min = inf, v = -1; for (int i = 0; i < n; i++) { if (!collected[i] && dist[i]!=-1 && dist[i]<min) { min = dist[i]; v = i; } } if (min==inf || v<0) break; collected[v] = true; node * ptr = G[v].next; while (ptr) { if (!collected[ptr->element]) { int w = ptr->element; if (dist[v]+ptr->weight<dist[w]) { dist[w] = dist[v] + ptr->weight; path[w] = v; } } ptr = ptr->next; } } int min = -1; for (int i = 0; i < n; i++) { if (dist[i]==inf) return -1; if (dist[i]>min) min = dist[i]; } delete [] dist; delete [] path; delete [] collected; return min; } void deleteGraph(node * G, int n) { for (int i = 0; i < n; i++) { node * ptr = G[i].next; while (ptr) { node * temp = ptr->next; delete ptr; ptr = temp; } } delete [] G; } void insertEdge(node * G, int i, int j, int weight) { node * ptr = &G[i]; while (ptr->next) { ptr = ptr->next; } ptr->next = new node; ptr = ptr->next; ptr->element = j; ptr->weight = weight; ptr->next = NULL; ptr = &G[j]; while (ptr->next) { ptr = ptr->next; } ptr->next = new node; ptr = ptr->next; ptr->element = i; ptr->weight = weight; ptr->next = NULL; } void readGraph(node * G, int e) { int vi, vj, weight; for (int i = 0; i < e; i++) { cin >> vi >> vj >> weight; insertEdge(G, vi-1, vj-1, weight); } } node * createGraph(int n) { node * G = new node [n]; for (int i = 0; i < n; i++) { G[i].element = i; G[i].weight = 0; G[i].next = NULL; } return G; } <file_sep>#include <iostream> using namespace std; const int MAX = 1003; struct node{ int coef;//系数 int expo;//指数 node * next; }; node * CreatList(node * head); //单链表的读入与创建 void PrintList(node * head); //输出以head为头结点的链表 node * MultiplyList(node * p1, node *p2); //多项式乘法 void Attach(int coef, int expo, node **nodepointer); //插入一个节点至nodepointer后 node * AddList(node * p1, node *p2); //多项式加法 void FreeList(node * p); //内存释放 int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); node *head1 = NULL, *head2 = NULL; head1 = CreatList(head1); head2 = CreatList(head2); node *multi = MultiplyList(head1, head2); node *add = AddList(head1, head2); PrintList(multi);cout << endl; PrintList(add); FreeList(head1);FreeList(head2);FreeList(multi);FreeList(add); return 0; } node * CreatList(node * head) { int coef, expo, k; node * p; head = new node; cin >> k; if ( !k ) return NULL; cin >> coef >> expo; head->coef = coef; head->expo = expo; head->next = NULL; p = head; for (size_t i = 1; i < k; i++) { cin >> coef >> expo; node *temp = new node; p->next = temp; temp->coef = coef; temp->expo = expo; temp->next = NULL; p = temp; } return head; } void PrintList(node * head) { if ( !head ) { cout << "0 0"; } while ( head ) { cout << head->coef << " " << head->expo; head = head->next; if ( head ) cout << " "; } } //by inserting to the right place 2 loops node * MultiplyList(node * p1, node *p2)//p is the pointor { //poining to the current node node *head = new node; head->expo = MAX; head->next = NULL; while ( p1 ) { node *p = p2; while ( p ) { //PrintList(head->next); //cout << endl << endl; int coef = p1->coef * p->coef; int expo = p1->expo + p->expo; node *temp = head; while ( true ) { //point to one in front // cout << "once "; if ( !(temp->next) || temp->next->expo<=expo ) break; temp = temp->next; } //now temp points to the insert place ahead // cout << "now expo is " << expo; // cout << "my temp->expo = " << temp->expo << endl; if ( temp->next && temp->next->expo == expo ) { if ( temp->next->coef + coef == 0 ) { //delete node * tobefreed = temp->next; temp->next = tobefreed->next; delete tobefreed; }else { //join together temp->next->coef += coef; } }else Attach(coef, expo, &temp); p = p->next; } p1 = p1->next; } node * tobedeleted = head; head = head->next; delete tobedeleted; return head; } void Attach(int coef, int expo, node **nodepointer) { // cout << "now coef=" << coef << " expo=" << expo << // " inserted after expo=" << (*nodepointer)->expo << endl; node * temp = new node; temp->coef = coef; temp->expo = expo; temp->next = (*nodepointer)->next; (*nodepointer)->next = temp;//here // cout << "now temp->next=" << temp->next; // cout << " *nodepointer points to expo" << (*nodepointer)->expo; } node * AddList(node * p1, node *p2) //receive 2 pointers and return the AddList { //head is a pointer to the head node node * p, * head; head = new node; //head is a head noder contains p = head; //nothing but a next pointor head->coef = 0; head->expo = 0; head->next = NULL; while ( p1 && p2 ) { int expo1, expo2; expo1 = p1->expo; expo2 = p2->expo; if ( expo1 > expo2 ) {//copy p->next = new node; p = p->next; p->next = NULL; p->expo = p1->expo; p->coef = p1->coef; p1 = p1->next; }else if ( expo1 < expo2 ) { p->next = new node; p = p->next; p->next = NULL; p->expo = p2->expo; p->coef = p2->coef; p2 = p2->next; }else { int coef = p1->coef + p2->coef; if ( coef ) { p->next = new node; p = p->next; p->next = NULL; p->expo = p1->expo; p->coef = coef; } p1 = p1->next; p2 = p2->next; } } while ( p2 ) { p->next = new node; p = p->next; p->next = NULL; p->expo = p2->expo; p->coef = p2->coef; p2 = p2->next; } while ( p1 ) { p->next = new node; p = p->next; p->next = NULL; p->expo = p1->expo; p->coef = p1->coef; p1 = p1->next; } //cout << head->next; p = head; head = head->next; delete p; return head; // if ( head->next ) { // }else { // return head; // } } void FreeList(node * p) { node * next; while ( p ) { next = p->next; delete p; p = p->next; } } /* 程序最后的两个细节问题 1- 当加法结果为零时的输出 2- 当有一个k为零时的输出 */ <file_sep>#include <iostream> #define inf 10000 using namespace std; int ** readGraph(int n, int m, int *** cost); void deleteGraph(int ** G, int n, int ** cost); int Dijkstra(int** G,int n,int s,int d,int** cost,int *spend); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, m, s, d, ** cost = NULL, fee; cin >> n >> m >> s >> d; int ** G = readGraph(n,m,&cost); int length = Dijkstra(G,n,s,d,cost,&fee); cout << length << ' ' << fee; deleteGraph(G,n,cost); return 0; } int Dijkstra(int** G,int n,int s,int d,int** cost,int *spend) { int * dist = new int [n]; int * fee = new int [n]; bool * collected = new bool [n]; for (int i = 0; i < n; i++) { dist[i] = inf; fee[i] = inf; collected[i] = false; } dist[s] = 0; collected[s] = true; for (int i = 0; i < n; i++) { if(!collected[i] && G[s][i]!=inf) { dist[i] = G[s][i]; fee[i] = cost[s][i]; } } int v = -1; while (true) { int min = inf; v = -1; for (int i = 0; i < n; i++) { if (!collected[i] && dist[i]!=-1 && dist[i]<min) { min = dist[i]; v = i; } } if (v==d || v==-1) break; collected[v] = true; for (int w = 0; w < n; w++) { if(!collected[w] && G[v][w]!=inf) { if (dist[v]+G[v][w]<dist[w]) { dist[w] = dist[v] + G[v][w]; fee[w] = fee[v] + cost[v][w]; }else if (dist[v]+G[v][w]==dist[w]) { if (fee[w] > fee[v] + cost[v][w]) { fee[w] = fee[v] + cost[v][w]; } } } } } int ret = dist[v]; *spend = fee[v]; delete [] dist; delete [] fee; delete [] collected; return ret; } void deleteGraph(int ** G, int n, int ** cost) { for (int i = 0; i < n; i++) { delete [] G[i]; delete [] cost[i]; } delete [] G; delete [] cost; } int ** readGraph(int n, int m, int *** cost) { int ** G = new int* [n]; *cost = new int* [n]; for (int i = 0; i < n; i++) { G[i] = new int [n]; (*cost)[i] = new int [n]; } for (int i = 0; i < n; i++) { G[i][i] = 0; (*cost)[i][i] = 0; } for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { G[i][j] = inf; G[j][i] = inf; (*cost)[i][j] = inf; (*cost)[j][i] = inf; } } int city1, city2, length, fee; for (int i = 0; i < m; i++) { cin >> city1 >> city2 >> length >> fee; G[city1][city2] = length; G[city2][city1] = length; (*cost)[city1][city2] = fee; (*cost)[city2][city1] = fee; } return G; } <file_sep>#include <iostream> using namespace std; struct node { int key; node * left; node * right; int height; }; node * insert(node * ptr, int x); int max(int a, int b); int getHeight(node * ptr); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, x;cin >> n; node * tree = NULL; for (int i = 0; i < n; i++) { cin >> x; tree = insert(tree,x); } cout << tree->key; return 0; } node * SingleLeftRotation(node * a) { node * b = a->left; a->left = b->right; b->right = a; a->height = max(getHeight(a->left),getHeight(a->right)) + 1; b->height = max(getHeight(b->left),getHeight(b->right)) + 1; return b; } node * SingleRightRotation(node * a) { node * b = a->right; a->right = b->left; b->left = a; a->height = max(getHeight(a->left),getHeight(a->right)) + 1; b->height = max(getHeight(b->left),getHeight(b->right)) + 1; return b; } node * LeftRightRotation(node * a) { a->left = SingleRightRotation(a->left); return SingleLeftRotation(a); } node * RightLeftRotation(node * a) { a->right = SingleLeftRotation(a->right); return SingleRightRotation(a); } node * insert(node * ptr, int x) { if (!ptr) { ptr = new node; ptr->key = x; ptr->left = ptr->right = NULL; ptr->height = 0; }else if(ptr->key<x) { ptr->right = insert(ptr->right,x); if (getHeight(ptr->left)-getHeight(ptr->right) == -2) { if (x>ptr->right->key) { ptr = SingleRightRotation(ptr); }else{ ptr = RightLeftRotation(ptr); } } }else if(ptr->key>x) { ptr->left = insert(ptr->left,x); if (getHeight(ptr->left)-getHeight(ptr->right) == 2) { if (x<ptr->left->key) { ptr = SingleLeftRotation(ptr); }else{ ptr = LeftRightRotation(ptr); } } } ptr->height = max( getHeight(ptr->left), getHeight(ptr->right) ) + 1; return ptr; } int max(int a, int b) { return a > b ? a : b; } int getHeight(node * ptr) { if (!ptr) { return 0; }else{ return ptr->height; } } <file_sep>#include <iostream> #include <cstdlib> #include <cmath> #define max 1003 int element[max] = {0}, cbs[max] = {0}; using namespace std; int cmp(const void * a, const void * b); int pos(int n); void setroot(int start, int end, int position); int main(int argc, char const *argv[]) { freopen("../test.txt", "r", stdin); int n; cin >> n; for (int i = 0; i < n; ++i) { cin >> element[i]; } qsort(element, n, sizeof(int), cmp); setroot(0, n-1, 1); for (int i = 1; i <= n; ++i) { cout << cbs[i]; if (i != n) cout << ' '; } return 0; } int cmp(const void * a, const void * b) { return *(int*)a - *(int*)b; } int pos(int n) { int fulldepth = 0, setoff, origin = n; while (n > 1) { fulldepth++; n /= 2; } int conditioncmp = (int)pow(2,fulldepth-1) - (int)(origin - pow(2,fulldepth) + 1); setoff = pow(2,fulldepth - 1) - 1; if ( conditioncmp < 0) { setoff -= conditioncmp; } // cout << "returning " << setoff << endl; return setoff; } void setroot(int start, int end, int position) { if (end == start) { cbs[position] = element[start]; return; } int n = end - start + 1; int rootpos = end - pos(n); int root = element[rootpos]; cbs[position] = root; // cout << "cbs[" << position << "] gets value: " << root << endl; if (rootpos > start) { setroot(start, rootpos - 1, position * 2); } if (rootpos < end) { setroot(rootpos + 1, end, position * 2 + 1); } } <file_sep>#include <iostream> #include <cmath> using namespace std; struct node { char element; char left; char right; //note : char to int conversion! }; char * maketree(); void print(char * head); bool childcmp(char* tree1, char* tree2); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); char *tree1 = maketree(); print(tree1); cout << endl; char *tree2 = maketree(); print(tree2); bool similar = true; if (*tree1!=*tree2) similar = false; else { similar = childcmp(tree1,tree2); } if (similar) cout << "Yes"; else cout << "No"; return 0; } char * writecmp(char * cmp, char * tree) { static int cnt = 1; } bool childcmp(char* tree1, char* tree2) { int length = tree1[0] char * cmp = new char [length+1]; cmp[0] = (char)length; writecmp(cmp,tree1); } void print(char * head) { int n = head[0]; int cnt = 0, i=1; while (cnt<n) { if (head[i]>='A' && head[i]<='J') { cout << head[i] << " "; cnt++; } i++; } } void setnode(char * head, int pos, char element) { head[pos] = element; } char * addfamilytotree(node * giventree, int n, char * head, int pos) { //cout << "adding " << n << " to " << pos << endl; node * src = &giventree[n]; if (src->left!=-1) { addfamilytotree(giventree,src->left,head,pos*2); }else{ setnode(head,pos*2,0); } setnode(head,pos,src->element); if (src->right!=-1) { addfamilytotree(giventree,src->right,head,pos*2+1); }else{ setnode(head,pos*2+1,0); } return head; } char * maketree() { int n;cin >> n; node *giventree = new node [n]; int *select = new int [n]; char ele, lef, rig; for (size_t i = 0; i < n; i++) select[i] = 0; for (size_t i = 0; i < n; i++) { cin >> ele >> lef >> rig; if (lef!='-') {giventree[i].left = lef - '0';select[giventree[i].left] = 1;} else giventree[i].left = -1; if (rig!='-') {giventree[i].right = rig - '0';select[giventree[i].right] = 1;} else giventree[i].right = -1; giventree[i].element = ele; } int root = 0; for (size_t i = 0; i < n; i++) { if (select[i]==0) { root = (int)i; break; } } int max = (int)pow(2,n); char * tree = new char [max]; tree[0] = (char)n; char * head = addfamilytotree(giventree,root,tree,1); return head; } <file_sep># Data Structure This repository is intended to track my leaning trace of the OJ: 数据结构与算法题目集(中文) ## 目录 - [数据结构与算法题目集(中文)](#数据结构与算法题目集(中文)) - [Acknowledgements](#Acknowledgements) # 数据结构与算法题目集(中文) |ID|Title|C++|备注| |:-:|:-|:-:|:-| |7-2|一元多项式的乘法与加法运算|[查看题解](https://ainevsia.github.io/2018/07/18/DS-7-2/)|链表| |7-3|树的同构|[查看题解](https://ainevsia.github.io/2018/08/11/DS-7-3/)|树的生成| |7-4|是否同一棵二叉搜索树|[查看题解](https://ainevsia.github.io/2018/08/12/DS-7-4/)|树的生成| |7-6|列出连通集|[查看题解](https://ainevsia.github.io/2018/08/14/DS-7-6/)|图的BFS遍历 DFS遍历 队列 图的领接表| |7-7|六度空间|[查看题解](https://ainevsia.github.io/2018/08/15/DS-7-7/)|图的BFS-6层遍历| |7-8|哈利·波特的考试|[查看题解](https://ainevsia.github.io/2018/08/17/DS-7-8/)|单源最短路径之Dijsktra算法| |7-9|旅游规划|[查看题解](https://ainevsia.github.io/2018/08/17/DS-7-9/)|Dijsktra算法、Floyd算法| # Acknowledgements <file_sep>#include <iostream> using namespace std; struct node { int value; node * left; node * right; int select; }; node * maketree(int n); void deletetree(node * tree); bool treecmp(node * tree, int n); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n;cin >> n; while (n) { int l;cin >> l; node * tree = maketree(n); for (int i = 0; i < l; i++) { if (treecmp(tree,n)) cout << "Yes" << endl; else cout << "No" << endl; } deletetree(tree); cin >> n; } return 0; } bool check(node * tree, int v) { if (!tree) return false; if (tree->value==v) { tree->select = 1; return true; } if (tree->select==0) { return false; } if (tree->value>v) { return check(tree->left,v); }else{ return check(tree->right,v); } } void settree(node * tree) { if (!tree) return; if (tree->left) settree(tree->left) ; if (tree->right) settree(tree->right); tree->select = 0; } bool treecmp(node * tree, int n) { settree(tree); int v; bool ret = true; for (int i = 0; i < n; i++) { cin >> v; if (!check(tree,v)) ret = false; } return ret; } void deletetree(node * tree) { if (!tree) return; if (tree->left) deletetree(tree->left) ; if (tree->right) deletetree(tree->right); delete tree; } node * newnode(int value) { node * treenode = new node; treenode->left = NULL ; treenode->right = NULL ; treenode->value = value ; treenode->select = 0 ; return treenode; } node * attachnode(node * tree, int value) { if (!tree) { return newnode(value); }else{ if (tree->value>value) tree->left = attachnode(tree->left ,value); else tree->right= attachnode(tree->right,value); return tree; } } node * maketree(int n) { int value; node * tree = NULL; for (int i = 0; i < n; i++) { cin >> value; tree = attachnode(tree,value); } return tree; } <file_sep>#include <iostream> #define inf 10000 using namespace std; int ** readGraph(int n, int m, int *** cost); void deleteGraph(int ** G, int n, int ** cost); void Floyd(int ** G, int n, int ** cost); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n, m, s, d, ** cost = NULL; cin >> n >> m >> s >> d; int ** G = readGraph(n,m,&cost); Floyd(G,n,cost); int length = G[s][d]; int fee = cost[s][d]; cout << length << ' ' << fee; deleteGraph(G,n,cost); return 0; } void Floyd(int ** G, int n, int ** cost) { for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (G[i][j] > G[i][k]+G[k][j]) { G[i][j] = G[i][k] + G[k][j]; cost[i][j] = cost[i][k] + cost[k][j]; } else if (G[i][j] == G[i][k]+G[k][j]) { if (cost[i][j] > cost[i][k] + cost[k][j]) { cost[i][j] = cost[i][k] + cost[k][j]; } } } } } } void deleteGraph(int ** G, int n, int ** cost) { for (int i = 0; i < n; i++) { delete [] G[i]; delete [] cost[i]; } delete [] G; delete [] cost; } int ** readGraph(int n, int m, int *** cost) { int ** G = new int* [n]; *cost = new int* [n]; for (int i = 0; i < n; i++) { G[i] = new int [n]; (*cost)[i] = new int [n]; } for (int i = 0; i < n; i++) { G[i][i] = 0; (*cost)[i][i] = 0; } for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { G[i][j] = inf; G[j][i] = inf; (*cost)[i][j] = inf; (*cost)[j][i] = inf; } } int city1, city2, length, fee; for (int i = 0; i < m; i++) { cin >> city1 >> city2 >> length >> fee; G[city1][city2] = length; G[city2][city1] = length; (*cost)[city1][city2] = fee; (*cost)[city2][city1] = fee; } return G; } <file_sep>#include <iostream> using namespace std; void comparetree(int n, int l); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); while (true) { int n;cin>>n; if (n==0) break; int l;cin>>l; comparetree(n,l); } return 0; } void print(bool same) { switch (same) { case true: cout << "Yes" << endl;break; case false:cout << "No" << endl;break; } } void comparetree(int n, int l) { int * src = new int [n]; //src--the original array int * select = new int [n]; //select 0-->not added to the cmp tree for (size_t i = 0; i < n; i++) cin >> src[i]; //select 1-->added to the cmp tree int * cmp = new int [n]; for (size_t i = 0; i < l; i++) { bool same = true; for (size_t i = 0; i < n; i++) {cin >> cmp[i];select[i]=0;} if (src[0]!=cmp[0]) { //judge the head same = false; print(same); continue; }else select[0] = 1; for (size_t i = 1; i < n && same; i++) { //i--indecate the cmp node int rootcmp = src[0]; for (size_t k = 1; k < n; k++) { if (src[k]>rootcmp&&select[k]==1&&cmp[i]>rootcmp) { rootcmp = src[k]; }else if (src[k]<rootcmp&&select[k]==1&&cmp[i]<rootcmp) { rootcmp = src[k]; } } for (size_t j = 1; j < n; j++) { if (select[j]==1) continue; if (cmp[i]==src[j]) { select[j] = 1; break; } int rootsrc = src[0]; for (size_t k = 1; k < j; k++) { if (src[k]>rootsrc&&src[j]>rootsrc) { rootsrc = src[k]; }else if (src[k]<rootsrc&&src[j]<rootsrc) { rootsrc = src[k]; } } if (rootcmp==rootsrc) { if (cmp[i]>rootcmp&&src[j]>rootsrc&&cmp[i]!=src[j]) { same = false; print(same); break; } if (cmp[i]<rootcmp&&src[j]<rootsrc&&cmp[i]!=src[j]) { same = false; print(same); break; } } } } if (same) print(same); } } <file_sep>/* starting at 14:42 ending at */ #include <iostream> #define MAXN 100 using namespace std; int n; int input[MAXN] = {0}; int seq[MAXN] = {0}; int sort[MAXN] = {0}; void printsort() {for (int i=0; i<n; i++) cout << sort[i] << ' '; cout << endl;} void printinput() {for (int i=0; i<n; i++) cout << input[i] << ' '; cout << endl;} void init(); bool cmp(); void myInsertSort(int i); // 我理解的插入排序怎么好像和大家理解的不太一样orz void InsertSort(int i); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); init(); bool isInsert = false; int SortingPtr; for ( SortingPtr = 0; SortingPtr < n; SortingPtr++) { InsertSort(SortingPtr); // printsort(); if (cmp()) { // cout << "arrived here" << endl; isInsert = true; break; } } if (isInsert) { cout << "Insertion Sort" << endl; InsertSort(SortingPtr + 1); for (int i = 0; i < n; i++) { cout << sort[i]; if (i + 1 != n) cout << ' '; } } if (!isInsert) { /* merge section */ } return 0; } void init() { cin >> n; for (int i = 0; i < n; i++) { cin >> input[i]; sort[i] = input[i]; } for (int i = 0; i < n; i++) cin >> seq[i]; } bool cmp() { bool eql = true; for (int i = 0; i < n; i++) { if (sort[i] != seq[i]) { eql = false; break; } } return eql; } void InsertSort(int i) { int insert = sort[i], ptr = 0; for ( ; ptr <= i; ptr++) { if (sort[ptr] >= insert) break; } for (int j = i; j > ptr; j--) { sort[j] = sort[j-1]; } sort[ptr] = insert; } void myInsertSort(int i) { // set the position i to sort int min = i; for (int j = i + 1; j < n; j++) { if (sort[j] < sort[min]) min = j; } int tmp = sort[min]; sort[min] = sort[i]; sort[i] = tmp; } <file_sep>#include <iostream> using namespace std; struct node { int key; int left; int right; int parent; int index; int factor; }; node * init (int n); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int n;cin >> n; node * tree = init(n), * ptr = NULL; for (size_t i = 0; i < n; i++) { cin >> tree[i].key; ptr = &tree[0]; while (ptr->left!=-1 || ptr->right!=-1) { if (tree[i].key<ptr->key && ptr->left!=-1) { ptr = &tree[ptr->left]; }else if (tree[i].key>ptr->key && ptr->right!=-1) { ptr = &tree[ptr->right]; }else{ break; } } tree[i].parent = ptr->index; if (tree[i].key<ptr->key) { ptr->left = i; ptr->factor++; }else if (tree[i].key>ptr->key) { ptr->right = i; } } for (size_t i = 0; i < n; i++) { printf("index=%d, key=%d, left=%d, right=%d, parent=%d\n", tree[i].index, tree[i].key, tree[i].left, tree[i].right, tree[i].parent); } delete [] tree; return 0; } node * init (int n) { node * tree = new node [n]; for (size_t i = 0; i < n; i++) { tree[i].parent = -1; tree[i].left = -1; tree[i].right = -1; tree[i].index = i; tree[i].factor = 0; } return tree; } <file_sep>// // Created by xuzhp on 2018/9/21. // #ifndef PROJECT_QUEUE_LINKED_LIST_H #define PROJECT_QUEUE_LINKED_LIST_H #include <iostream> #include <cstdlib> #define ERROR -1 #define ElementType int typedef int Position; struct QNode { ElementType *Data; /* 存储元素的数组 */ Position Front, Rear; /* 队列的头、尾指针 */ int MaxSize; /* 队列最大容量 */ }; typedef struct QNode *Queue; Queue CreateQueue( int MaxSize ) { Queue Q = (Queue)malloc(sizeof(struct QNode)); Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType)); Q->Front = Q->Rear = 0; Q->MaxSize = MaxSize; return Q; } bool IsFull( Queue Q ) { return ((Q->Rear+1)%Q->MaxSize == Q->Front); } bool AddQ( Queue Q, ElementType X ) { if ( IsFull(Q) ) { std::cout << "队列满"; return false; } else { Q->Rear = (Q->Rear+1)%Q->MaxSize; Q->Data[Q->Rear] = X; return true; } } bool IsEmpty( Queue Q ) { return (Q->Front == Q->Rear); } ElementType DeleteQ( Queue Q ) { if ( IsEmpty(Q) ) { std::cout << "队列空"; return ERROR; } else { Q->Front =(Q->Front+1)%Q->MaxSize; return Q->Data[Q->Front]; } } #endif //PROJECT_QUEUE_LINKED_LIST_H <file_sep>#include <iostream> using namespace std; bool check(int m, int n); int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); int m, n, k;cin >> m >> n >> k; for (int i = 0; i < k; i++) { bool valid = check(m,n); if (valid) cout << "YES" << endl; else cout << "NO" << endl; } return 0; } bool check(int m, int n) { int * stack = new int [n], stk = -1; int * store = new int [n], str = 0; for (int i = 0; i < n; i++) { cin >> store[i]; } bool valid = false; for (int topush = 1; topush <= n; topush++) { stack[++stk] = topush; if (stk==m) break; while (stk!=-1 && store[str]==stack[stk]) { stk--;str++; } } if (stk==-1) valid = true; delete [] stack; return valid; } <file_sep>#include <iostream> #include <cstring> using namespace std; void cal_pi(const char * pattern, int length, int * pi) { pi[0] = 0; int pre_pi = 0; for (int i = 1; i < length; ++i) { while (pre_pi > 0 && pattern[i]!=pattern[pre_pi]) pre_pi = pi[pre_pi-1]; if (pattern[i] == pattern[pre_pi]) pre_pi++; pi[i] = pre_pi; } } int main() { char pattern[] = "ababbabbabbababbabb"; int length = (int)(strlen(pattern)); int * pi = new int [length]; cal_pi(pattern, length, pi); for (int i = 0; i < length; ++i) cout << pattern[i] << '\t'; cout << endl; for (int i = 0; i < length; ++i) cout << pi[i] << '\t'; delete [] pi; return 0; }<file_sep>#include <iostream> #include <cstring> #define MAX 100 using namespace std; char x[MAX]; char y[MAX]; int main(int argc, char const *argv[]) { freopen("test.txt", "r", stdin); cin >> x >> y; int m = strlen(x) - 1, n = strlen(y) - 1; int ** c = new int* [m+1]; for (int i = 0; i <= m; ++i) c[i] = new int [n+1]; for (int i = 0; i <= m; ++i) c[i][0] = 0; for (int j = 0; j <= n; ++j) c[0][j] = 0; for (int i = 1; i <= m; ++i) for (int j = 1; j <= n; ++j) { if (x[i] == y[j]) c[i][j] = c[i-1][j-1] + 1; else if (c[i-1][j] >= c[i][j-1]) c[i][j] = c[i-1][j]; else c[i][j] = c[i][j-1]; } cout << c[m][n]; return 0; }<file_sep>#include <iostream> #include <cstdlib> struct node { double dis; }; using namespace std; int cmp (const void * a, const void * b) { return int((*((node**)a))->dis - (*((node**)b))->dis); } int intcmp (const void * a, const void * b) { return *(int*)b - *(int*)a; } int main() { node a, b, c; a.dis = 2.0; b.dis = 1.0; c.dis = 3.0; node * list[3]; list[0] = &a; list[1] = &b; list[2] = &c; int intlist[3] = {1,2,3}; qsort(list, 3, sizeof(node*), cmp); for (int i = 0; i < 3; ++i) { cout << list[i]->dis << endl; } qsort(intlist, 3, sizeof(int), intcmp); for (int i = 0; i < 3; ++i) { cout << intlist[i] << endl; } }<file_sep>// // Created by xuzhp on 2018/9/21. // #include <iostream> #define maxvertex 105 #define inf 10000 using namespace std; int graph[maxvertex][maxvertex]; int earlytime[maxvertex]; int latetime[maxvertex]; int indegree[maxvertex]; int outdegree[maxvertex]; int nv, ne; void init(); int FindMin(int a, int b); int FindMax(int a, int b); int EarlyTime(); void LateTime(int maxtime); int main() { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); cin >> nv >> ne; init(); int time = EarlyTime(); if (time<0) {cout << 0;return 0;} cout << time << endl; LateTime(time); for (int i = 0; i < nv; ++i) { if (earlytime[i]!=latetime[i]) continue; for (int j = nv - 1; j>= 0; --j) { if (graph[i][j]>=0 && earlytime[j]==latetime[j] && earlytime[i] + graph[i][j] == earlytime[j]) cout << i + 1 << "->" << j + 1 << endl; } } return 0; } void init() { for (int i = 0; i < nv; ++i) { for (int j = 0; j < nv; ++j) { graph[i][j] = -1; } earlytime[i] = 0; latetime[i] = inf; indegree[i] = 0; outdegree[i] = 0; } int src, dest, cost; for (int k = 0; k < ne; ++k) { cin >> src >> dest >> cost; graph[src-1][dest-1] = cost; indegree[dest-1]++; outdegree[src-1]++; } } int EarlyTime() { int queue[nv]; int first = -1, rear = -1, cnt = 0, temp, maxtime = -1; for (int i = 0; i < nv; ++i) if (indegree[i]==0) queue[++rear] = i; while (first < rear) { temp = queue[++first]; cnt++; for (int i = 0; i < nv; ++i) { if (graph[temp][i] >= 0) { // for every node of i earlytime[i] = FindMax(earlytime[i],graph[temp][i]+earlytime[temp]); maxtime = FindMax(earlytime[i],maxtime); if (--indegree[i]==0) queue[++rear] = i; } } } if (cnt!=nv) return -1; else return maxtime; } void LateTime(int maxtime) { int queue[nv]; int first = -1, rear = -1, temp; for (int i = 0; i < nv; ++i) { if (outdegree[i]==0) { queue[++rear] = i; latetime[i] = maxtime; } } while (first < rear) { temp = queue[++first]; for (int i = 0; i < nv; ++i) { if (graph[i][temp] >= 0) { // for every node of i latetime[i] = FindMin(latetime[i],latetime[temp]-graph[i][temp]); if (--outdegree[i]==0) queue[++rear] = i; } } } } int FindMin(int a, int b) { if (a>b) return b; else return a; } int FindMax(int a, int b) { if (a<b) return b; else return a; }<file_sep>#include <iostream> #include <cmath> #include <cstdlib> #define max 102 const int radius = 50; int maxtime = max; struct node { //crocodile -- node int x, y; //position label x and y bool flag; //true if the crocodile is close enough to the beach node * precedent; //pointer to the previous crocodile double distance; //distance to the previous crocodile int nodetime; //attribute that trace the distance from island }; struct Stack { //stack to implement the closest way node * stack[max * 2]; int sp; node * Pop(){return stack[sp--];} void Push(node * ptr){stack[++sp] = ptr;} }; node croco[max]; //all the crocodiles are kept in this array Stack priostack; //priority stack node * FinalNode = NULL;//keep the exit using namespace std; double getdis(int x1, int y1, int x2, int y2); void dfs(node * ptr, int n, int d, node * pre, int times); int cmp(const void * a, const void * b); int main(int argc, char const *argv[]) { freopen("../test.txt", "r", stdin); int n, d;cin >> n >> d; priostack.sp = -1; for (int i = 0; i < n; ++i) { //inialization cin >> croco[i].x >> croco[i].y; croco[i].flag = radius - abs(croco[i].x) <= d || radius - abs(croco[i].y) <= d; croco[i].precedent = NULL; croco[i].distance = 0; croco[i].nodetime = max; } //first iteration for (int i = 0; i < n; ++i) { if (getdis(0,0,croco[i].x,croco[i].y)<=7.5+d) { croco[i].distance = getdis(0,0,croco[i].x,croco[i].y); priostack.Push(&croco[i]); } } if (priostack.sp+1 > 1) qsort(&priostack.stack[0], priostack.sp+1, sizeof(node*), cmp); int cnt = 0, num = priostack.sp + 1; while (cnt++ < num) dfs(priostack.Pop(),n,d,NULL,1); //out put section if (maxtime == max) cout << 0; else if (d >= 43) cout << 1; else { int outputcnt = 0; while (FinalNode) { outputcnt++; priostack.Push(FinalNode); FinalNode = FinalNode->precedent; } cout << outputcnt + 1 << endl; while (outputcnt--) { FinalNode = priostack.Pop(); cout << FinalNode->x << ' ' << FinalNode->y << endl; } } return 0; } void dfs(node * ptr, int n, int d, node * pre, int times) { ptr->precedent = pre; if (ptr->flag && times < maxtime) { maxtime = times; FinalNode = ptr; } ptr->nodetime = times; int bp = priostack.sp; for (int i = 0; i < n; ++i) { if (croco[i].nodetime>times+1 && getdis(ptr->x,ptr->y,croco[i].x,croco[i].y)<=d) { croco[i].distance = getdis(0,0,croco[i].x,croco[i].y); priostack.Push(&croco[i]); } } int num = priostack.sp - bp; if (num > 1) qsort(&priostack.stack[bp+1], (size_t)priostack.sp-bp, sizeof(node*), cmp); int cnt = 0; while (cnt++ < num) dfs(priostack.Pop(),n,d,ptr,times+1); } int cmp(const void * a, const void * b) { double d = (*((node**)b))->distance - (*((node**)a))->distance; return d > 0 ? 1 : -1; } double getdis(int x1, int y1, int x2, int y2) { double ret = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); return ret; } <file_sep>// // Created by xuzhp on 2018/9/21. // #include <iostream> #include "Graph_linked_list.h" #define inf 10000 using namespace std; struct switch_point { int index; int earliest_finish_time; int latest_finish_time; }; int main(int argc, char const *argv[]) { freopen("D:\\SJTU\\Freshman Summer\\DS\\test.txt", "r", stdin); LGraph Graph = BuildGraph(); auto * TopOrder = new Vertex [Graph->Nv]; bool loop_donot_existed = TopSort(Graph,TopOrder); if (!loop_donot_existed) { cout << 0; return 0; } switch_point * task = new switch_point [Graph->Nv]; for (int i = 0; i < Graph->Nv; ++i) { task[i].index = i; task[i].earliest_finish_time = 0; task[i].latest_finish_time = inf; } // setting the earliest time int longest_time = 0; for (int i = 0; i < Graph->Nv; ++i) { //cout << "Now is at node " << TopOrder[i] + 1 << endl; PtrToAdjVNode ptr = Graph->G[TopOrder[i]].FirstEdge; for ( ; ptr; ptr = ptr->Next) { if (ptr->Weight+task[TopOrder[i]].earliest_finish_time > task[ptr->AdjV].earliest_finish_time) { task[ptr->AdjV].earliest_finish_time = ptr->Weight+task[TopOrder[i]].earliest_finish_time; if (longest_time < task[ptr->AdjV].earliest_finish_time) longest_time = task[ptr->AdjV].earliest_finish_time; //cout << "changing " << ptr->AdjV + 1 << "'s time to " << task[ptr->AdjV].earliest_finish_time << endl; } } } // setting the latest time for (int i = Graph->Nv - 1; i >= 0 ; --i) { //cout << "Now is at node " << TopOrder[i] + 1 << endl; PtrToAdjVNode ptr = Graph->G[TopOrder[i]].FirstEdge; if (!ptr) { task[TopOrder[i]].latest_finish_time = longest_time; //cout << "changing " << TopOrder[i] + 1 << "'s latest time to " << task[TopOrder[i]].earliest_finish_time << endl; continue; } for ( ; ptr; ptr = ptr->Next) { if (task[ptr->AdjV].latest_finish_time - ptr->Weight < task[TopOrder[i]].latest_finish_time) { task[TopOrder[i]].latest_finish_time = task[ptr->AdjV].latest_finish_time - ptr->Weight; //cout << "changing " << ptr->AdjV + 1 << "'s latest time to " << task[TopOrder[i]].latest_finish_time << endl; } } } // output cout << task[TopOrder[Graph->Nv-1]].earliest_finish_time << endl; for (int i = 0; i < Graph->Nv; ++i) { //cout << task[i].index + 1 << ' ' << task[i].latest_finish_time << endl; if (task[i].earliest_finish_time!=task[i].latest_finish_time) continue; PtrToAdjVNode ptr = Graph->G[i].FirstEdge; for ( ; ptr; ptr = ptr->Next) { if (task[ptr->AdjV].earliest_finish_time==task[ptr->AdjV].latest_finish_time) cout << i + 1 << "->" << ptr->AdjV + 1 << endl; } } return 0; }
94319c6af8482cfb9396409358bc447ae6a24af3
[ "Markdown", "C++" ]
39
Markdown
Ainevsia/Data-Structure-ZJU-PTA
988faaa5f1d0a80085593d5c98af0be674590a53
39439b0b8a82c574bd3226bc33c1b2ff9d1eeee3
refs/heads/master
<file_sep>/* * Copyright 2010 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ * $HeadURL$ */ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.02.24 at 11:39:42 PM CET // package com.hack23.cia.model.external.worldbank.indicators.impl; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.jvnet.jaxb2_commons.lang.Equals; import org.jvnet.jaxb2_commons.lang.EqualsStrategy; import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; import com.hack23.cia.model.common.api.ModelObject; /** * The Class Source. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Embeddable public class Source implements ModelObject, Equals { /** * */ private static final long serialVersionUID = 1L; /** The value. */ @XmlValue protected String value; /** The id. */ @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value. * * @return the value */ @Basic @Column(name = "VALUE_") public String getValue() { return value; } /** * Sets the value. * * @param value the new value */ public void setValue(final String value) { this.value = value; } /** * Gets the id. * * @return the id */ @Basic @Column(name = "ID") public String getId() { return id; } /** * Sets the id. * * @param value the new id */ public void setId(final String value) { this.id = value; } /** * With value. * * @param value the value * @return the source */ public Source withValue(final String value) { setValue(value); return this; } /** * With id. * * @param value the value * @return the source */ public Source withId(final String value) { setId(value); return this; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public final String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } /* (non-Javadoc) * @see org.jvnet.jaxb2_commons.lang.Equals#equals(org.jvnet.jaxb2_commons.locator.ObjectLocator, org.jvnet.jaxb2_commons.locator.ObjectLocator, java.lang.Object, org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy) */ public boolean equals(final ObjectLocator thisLocator, final ObjectLocator thatLocator, final Object object, final EqualsStrategy strategy) { if ((object == null)||(this.getClass()!= object.getClass())) { return false; } if (this == object) { return true; } final Source that = ((Source) object); { String lhsValue; lhsValue = this.getValue(); String rhsValue; rhsValue = that.getValue(); if (!strategy.equals(LocatorUtils.property(thisLocator, "value", lhsValue), LocatorUtils.property(thatLocator, "value", rhsValue), lhsValue, rhsValue)) { return false; } } { String lhsId; lhsId = this.getId(); String rhsId; rhsId = that.getId(); if (!strategy.equals(LocatorUtils.property(thisLocator, "id", lhsId), LocatorUtils.property(thatLocator, "id", rhsId), lhsId, rhsId)) { return false; } } return true; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(final Object object) { final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public final int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } } <file_sep>/* * Copyright 2010 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ * $HeadURL$ */ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.02.24 at 11:40:10 PM CET // package com.hack23.cia.model.external.riksdagen.utskottsforslag.impl; import java.math.BigInteger; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.jvnet.jaxb2_commons.lang.Equals; import org.jvnet.jaxb2_commons.lang.EqualsStrategy; import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; import com.hack23.cia.model.common.api.ModelObject; /** * The Class AgainstProposalData. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AgainstProposalData", propOrder = { "numberValue", "header", "proposalType", "parties", "proposalIssueNumber" }) @Entity(name = "AgainstProposalData") @Table(name = "AGAINST_PROPOSAL_DATA") @Inheritance(strategy = InheritanceType.JOINED) public class AgainstProposalData implements ModelObject, Equals { /** * */ private static final long serialVersionUID = 1L; /** The number value. */ @XmlElement(name = "nummer", required = true) protected BigInteger numberValue; /** The header. */ @XmlElement(name = "rubrik", required = true) protected String header; /** The proposal type. */ @XmlElement(name = "typ", required = true) protected String proposalType; /** The parties. */ @XmlElement(name = "partier", required = true) protected String parties; /** The proposal issue number. */ @XmlElement(name = "utskottsforslag_punkt", required = true) protected BigInteger proposalIssueNumber; /** The hjid. */ @XmlAttribute(name = "Hjid") protected Long hjid; /** * Gets the number value. * * @return the number value */ @Basic @Column(name = "NUMBER_VALUE", precision = 20) public BigInteger getNumberValue() { return numberValue; } /** * Sets the number value. * * @param value the new number value */ public void setNumberValue(final BigInteger value) { this.numberValue = value; } /** * Gets the header. * * @return the header */ @Basic @Column(name = "HEADER") public String getHeader() { return header; } /** * Sets the header. * * @param value the new header */ public void setHeader(final String value) { this.header = value; } /** * Gets the proposal type. * * @return the proposal type */ @Basic @Column(name = "PROPOSAL_TYPE") public String getProposalType() { return proposalType; } /** * Sets the proposal type. * * @param value the new proposal type */ public void setProposalType(final String value) { this.proposalType = value; } /** * Gets the parties. * * @return the parties */ @Basic @Column(name = "PARTIES") public String getParties() { return parties; } /** * Sets the parties. * * @param value the new parties */ public void setParties(final String value) { this.parties = value; } /** * Gets the proposal issue number. * * @return the proposal issue number */ @Basic @Column(name = "PROPOSAL_ISSUE_NUMBER", precision = 20) public BigInteger getProposalIssueNumber() { return proposalIssueNumber; } /** * Sets the proposal issue number. * * @param value the new proposal issue number */ public void setProposalIssueNumber(final BigInteger value) { this.proposalIssueNumber = value; } /** * With number value. * * @param value the value * @return the against proposal data */ public AgainstProposalData withNumberValue(final BigInteger value) { setNumberValue(value); return this; } /** * With header. * * @param value the value * @return the against proposal data */ public AgainstProposalData withHeader(final String value) { setHeader(value); return this; } /** * With proposal type. * * @param value the value * @return the against proposal data */ public AgainstProposalData withProposalType(final String value) { setProposalType(value); return this; } /** * With parties. * * @param value the value * @return the against proposal data */ public AgainstProposalData withParties(final String value) { setParties(value); return this; } /** * With proposal issue number. * * @param value the value * @return the against proposal data */ public AgainstProposalData withProposalIssueNumber(final BigInteger value) { setProposalIssueNumber(value); return this; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public final String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } /** * Gets the hjid. * * @return the hjid */ @Id @Column(name = "HJID") @GeneratedValue(strategy = GenerationType.AUTO) public Long getHjid() { return hjid; } /** * Sets the hjid. * * @param value the new hjid */ public void setHjid(final Long value) { this.hjid = value; } /* (non-Javadoc) * @see org.jvnet.jaxb2_commons.lang.Equals#equals(org.jvnet.jaxb2_commons.locator.ObjectLocator, org.jvnet.jaxb2_commons.locator.ObjectLocator, java.lang.Object, org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy) */ public boolean equals(final ObjectLocator thisLocator, final ObjectLocator thatLocator, final Object object, final EqualsStrategy strategy) { if ((object == null)||(this.getClass()!= object.getClass())) { return false; } if (this == object) { return true; } final AgainstProposalData that = ((AgainstProposalData) object); { BigInteger lhsNumberValue; lhsNumberValue = this.getNumberValue(); BigInteger rhsNumberValue; rhsNumberValue = that.getNumberValue(); if (!strategy.equals(LocatorUtils.property(thisLocator, "numberValue", lhsNumberValue), LocatorUtils.property(thatLocator, "numberValue", rhsNumberValue), lhsNumberValue, rhsNumberValue)) { return false; } } { String lhsHeader; lhsHeader = this.getHeader(); String rhsHeader; rhsHeader = that.getHeader(); if (!strategy.equals(LocatorUtils.property(thisLocator, "header", lhsHeader), LocatorUtils.property(thatLocator, "header", rhsHeader), lhsHeader, rhsHeader)) { return false; } } { String lhsProposalType; lhsProposalType = this.getProposalType(); String rhsProposalType; rhsProposalType = that.getProposalType(); if (!strategy.equals(LocatorUtils.property(thisLocator, "proposalType", lhsProposalType), LocatorUtils.property(thatLocator, "proposalType", rhsProposalType), lhsProposalType, rhsProposalType)) { return false; } } { String lhsParties; lhsParties = this.getParties(); String rhsParties; rhsParties = that.getParties(); if (!strategy.equals(LocatorUtils.property(thisLocator, "parties", lhsParties), LocatorUtils.property(thatLocator, "parties", rhsParties), lhsParties, rhsParties)) { return false; } } { BigInteger lhsProposalIssueNumber; lhsProposalIssueNumber = this.getProposalIssueNumber(); BigInteger rhsProposalIssueNumber; rhsProposalIssueNumber = that.getProposalIssueNumber(); if (!strategy.equals(LocatorUtils.property(thisLocator, "proposalIssueNumber", lhsProposalIssueNumber), LocatorUtils.property(thatLocator, "proposalIssueNumber", rhsProposalIssueNumber), lhsProposalIssueNumber, rhsProposalIssueNumber)) { return false; } } return true; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(final Object object) { final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public final int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } } <file_sep>/* * Copyright 2010 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ * $HeadURL$ */ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.02.24 at 11:40:02 PM CET // package com.hack23.cia.model.external.riksdagen.dokumentlista.impl; import java.math.BigInteger; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.jvnet.jaxb2_commons.lang.Equals; import org.jvnet.jaxb2_commons.lang.EqualsStrategy; import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; import com.hack23.cia.model.common.api.ModelObject; /** * The Class DocumentElement. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DocumentElement", propOrder = { "hit", "id", "domainOrg", "documentName", "debateName", "noteTitle", "note", "summary", "databaseSource", "origin", "lang", "rm", "relatedId", "documentType", "docType", "subType", "status", "label", "tempLabel", "org", "numberValue", "title", "subTitle", "createdDate", "madePublicDate", "systemDate", "kallId", "documentFormat", "documentUrlText", "documentUrlHtml", "documentStatusUrlXml", "committeeReportUrlXml" }) @Entity(name = "DocumentElement") @Table(name = "DOCUMENT_ELEMENT") @Inheritance(strategy = InheritanceType.JOINED) public class DocumentElement implements ModelObject, Equals { /** * */ private static final long serialVersionUID = 1L; /** The hit. */ @XmlElement(name = "traff", required = true) protected BigInteger hit; /** The id. */ @XmlElement(required = true) protected String id; /** The domain org. */ @XmlElement(name = "domain", required = true) protected String domainOrg; /** The document name. */ @XmlElement(name = "dokumentnamn", required = true) protected String documentName; /** The debate name. */ @XmlElement(name = "debattnamn", required = true) protected String debateName; /** The note title. */ @XmlElement(name = "notisrubrik", required = true) protected String noteTitle; /** The note. */ @XmlElement(name = "notis", required = true) protected String note; /** The summary. */ @XmlElement(required = true) protected String summary; /** The database source. */ @XmlElement(name = "database", required = true) protected String databaseSource; /** The origin. */ @XmlElement(name = "kalla", required = true) protected String origin; /** The lang. */ @XmlElement(required = true) protected String lang; /** The rm. */ @XmlElement(required = true) protected String rm; /** The related id. */ @XmlElement(name = "relaterat_id", required = true) protected String relatedId; /** The document type. */ @XmlElement(name = "typ", required = true) protected String documentType; /** The doc type. */ @XmlElement(name = "doktyp", required = true) protected String docType; /** The sub type. */ @XmlElement(name = "subtyp", required = true) protected String subType; /** The status. */ @XmlElement(required = true) protected String status; /** The label. */ @XmlElement(name = "beteckning", required = true) protected String label; /** The temp label. */ @XmlElement(name = "tempbeteckning", required = true) protected String tempLabel; /** The org. */ @XmlElement(name = "organ", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NCName") protected String org; /** The number value. */ @XmlElement(name = "nummer", required = true) protected BigInteger numberValue; /** The title. */ @XmlElement(name = "titel", required = true) protected String title; /** The sub title. */ @XmlElement(name = "undertitel", required = true) protected String subTitle; /** The created date. */ @XmlElement(name = "datum", required = true) protected String createdDate; /** The made public date. */ @XmlElement(name = "publicerad", required = true) protected String madePublicDate; /** The system date. */ @XmlElement(name = "systemdatum", required = true) protected String systemDate; /** The kall id. */ @XmlElement(name = "kall_id", required = true) protected String kallId; /** The document format. */ @XmlElement(name = "dokumentformat", required = true) protected String documentFormat; /** The document url text. */ @XmlElement(name = "dokument_url_text", required = true) @XmlSchemaType(name = "anyURI") protected String documentUrlText; /** The document url html. */ @XmlElement(name = "dokument_url_html", required = true) @XmlSchemaType(name = "anyURI") protected String documentUrlHtml; /** The document status url xml. */ @XmlElement(name = "dokumentstatus_url_xml", required = true) @XmlSchemaType(name = "anyURI") protected String documentStatusUrlXml; /** The committee report url xml. */ @XmlElement(name = "utskottsforslag_url_xml", required = true) @XmlSchemaType(name = "anyURI") protected String committeeReportUrlXml; /** * Gets the hit. * * @return the hit */ @Basic @Column(name = "HIT", precision = 20) public BigInteger getHit() { return hit; } /** * Sets the hit. * * @param value the new hit */ public void setHit(final BigInteger value) { this.hit = value; } /** * Gets the id. * * @return the id */ @Id @Column(name = "ID") public String getId() { return id; } /** * Sets the id. * * @param value the new id */ public void setId(final String value) { this.id = value; } /** * Gets the domain org. * * @return the domain org */ @Basic @Column(name = "DOMAIN_ORG") public String getDomainOrg() { return domainOrg; } /** * Sets the domain org. * * @param value the new domain org */ public void setDomainOrg(final String value) { this.domainOrg = value; } /** * Gets the document name. * * @return the document name */ @Basic @Column(name = "DOCUMENT_NAME") public String getDocumentName() { return documentName; } /** * Sets the document name. * * @param value the new document name */ public void setDocumentName(final String value) { this.documentName = value; } /** * Gets the debate name. * * @return the debate name */ @Basic @Column(name = "DEBATE_NAME") public String getDebateName() { return debateName; } /** * Sets the debate name. * * @param value the new debate name */ public void setDebateName(final String value) { this.debateName = value; } /** * Gets the note title. * * @return the note title */ @Basic @Column(name = "NOTE_TITLE") public String getNoteTitle() { return noteTitle; } /** * Sets the note title. * * @param value the new note title */ public void setNoteTitle(final String value) { this.noteTitle = value; } /** * Gets the note. * * @return the note */ @Basic @Column(name = "NOTE") public String getNote() { return note; } /** * Sets the note. * * @param value the new note */ public void setNote(final String value) { this.note = value; } /** * Gets the summary. * * @return the summary */ @Basic @Column(name = "SUMMARY") public String getSummary() { return summary; } /** * Sets the summary. * * @param value the new summary */ public void setSummary(final String value) { this.summary = value; } /** * Gets the database source. * * @return the database source */ @Basic @Column(name = "DATABASE_SOURCE") public String getDatabaseSource() { return databaseSource; } /** * Sets the database source. * * @param value the new database source */ public void setDatabaseSource(final String value) { this.databaseSource = value; } /** * Gets the origin. * * @return the origin */ @Basic @Column(name = "ORIGIN") public String getOrigin() { return origin; } /** * Sets the origin. * * @param value the new origin */ public void setOrigin(final String value) { this.origin = value; } /** * Gets the lang. * * @return the lang */ @Basic @Column(name = "LANG") public String getLang() { return lang; } /** * Sets the lang. * * @param value the new lang */ public void setLang(final String value) { this.lang = value; } /** * Gets the rm. * * @return the rm */ @Basic @Column(name = "RM") public String getRm() { return rm; } /** * Sets the rm. * * @param value the new rm */ public void setRm(final String value) { this.rm = value; } /** * Gets the related id. * * @return the related id */ @Basic @Column(name = "RELATED_ID") public String getRelatedId() { return relatedId; } /** * Sets the related id. * * @param value the new related id */ public void setRelatedId(final String value) { this.relatedId = value; } /** * Gets the document type. * * @return the document type */ @Basic @Column(name = "DOCUMENT_TYPE") public String getDocumentType() { return documentType; } /** * Sets the document type. * * @param value the new document type */ public void setDocumentType(final String value) { this.documentType = value; } /** * Gets the doc type. * * @return the doc type */ @Basic @Column(name = "DOC_TYPE") public String getDocType() { return docType; } /** * Sets the doc type. * * @param value the new doc type */ public void setDocType(final String value) { this.docType = value; } /** * Gets the sub type. * * @return the sub type */ @Basic @Column(name = "SUB_TYPE") public String getSubType() { return subType; } /** * Sets the sub type. * * @param value the new sub type */ public void setSubType(final String value) { this.subType = value; } /** * Gets the status. * * @return the status */ @Basic @Column(name = "STATUS") public String getStatus() { return status; } /** * Sets the status. * * @param value the new status */ public void setStatus(final String value) { this.status = value; } /** * Gets the label. * * @return the label */ @Basic @Column(name = "LABEL") public String getLabel() { return label; } /** * Sets the label. * * @param value the new label */ public void setLabel(final String value) { this.label = value; } /** * Gets the temp label. * * @return the temp label */ @Basic @Column(name = "TEMP_LABEL") public String getTempLabel() { return tempLabel; } /** * Sets the temp label. * * @param value the new temp label */ public void setTempLabel(final String value) { this.tempLabel = value; } /** * Gets the org. * * @return the org */ @Basic @Column(name = "ORG") public String getOrg() { return org; } /** * Sets the org. * * @param value the new org */ public void setOrg(final String value) { this.org = value; } /** * Gets the number value. * * @return the number value */ @Basic @Column(name = "NUMBER_VALUE", precision = 20) public BigInteger getNumberValue() { return numberValue; } /** * Sets the number value. * * @param value the new number value */ public void setNumberValue(final BigInteger value) { this.numberValue = value; } /** * Gets the title. * * @return the title */ @Basic @Column(name = "TITLE", length = 65536) public String getTitle() { return title; } /** * Sets the title. * * @param value the new title */ public void setTitle(final String value) { this.title = value; } /** * Gets the sub title. * * @return the sub title */ @Basic @Column(name = "SUB_TITLE", length = 65536) public String getSubTitle() { return subTitle; } /** * Sets the sub title. * * @param value the new sub title */ public void setSubTitle(final String value) { this.subTitle = value; } /** * Gets the created date. * * @return the created date */ @Basic @Column(name = "CREATED_DATE") public String getCreatedDate() { return createdDate; } /** * Sets the created date. * * @param value the new created date */ public void setCreatedDate(final String value) { this.createdDate = value; } /** * Gets the made public date. * * @return the made public date */ @Basic @Column(name = "MADE_PUBLIC_DATE") public String getMadePublicDate() { return madePublicDate; } /** * Sets the made public date. * * @param value the new made public date */ public void setMadePublicDate(final String value) { this.madePublicDate = value; } /** * Gets the system date. * * @return the system date */ @Basic @Column(name = "SYSTEM_DATE") public String getSystemDate() { return systemDate; } /** * Sets the system date. * * @param value the new system date */ public void setSystemDate(final String value) { this.systemDate = value; } /** * Gets the kall id. * * @return the kall id */ @Basic @Column(name = "KALL_ID") public String getKallId() { return kallId; } /** * Sets the kall id. * * @param value the new kall id */ public void setKallId(final String value) { this.kallId = value; } /** * Gets the document format. * * @return the document format */ @Basic @Column(name = "DOCUMENT_FORMAT") public String getDocumentFormat() { return documentFormat; } /** * Sets the document format. * * @param value the new document format */ public void setDocumentFormat(final String value) { this.documentFormat = value; } /** * Gets the document url text. * * @return the document url text */ @Basic @Column(name = "DOCUMENT_URL_TEXT") public String getDocumentUrlText() { return documentUrlText; } /** * Sets the document url text. * * @param value the new document url text */ public void setDocumentUrlText(final String value) { this.documentUrlText = value; } /** * Gets the document url html. * * @return the document url html */ @Basic @Column(name = "DOCUMENT_URL_HTML") public String getDocumentUrlHtml() { return documentUrlHtml; } /** * Sets the document url html. * * @param value the new document url html */ public void setDocumentUrlHtml(final String value) { this.documentUrlHtml = value; } /** * Gets the document status url xml. * * @return the document status url xml */ @Basic @Column(name = "DOCUMENT_STATUS_URL_XML") public String getDocumentStatusUrlXml() { return documentStatusUrlXml; } /** * Sets the document status url xml. * * @param value the new document status url xml */ public void setDocumentStatusUrlXml(final String value) { this.documentStatusUrlXml = value; } /** * Gets the committee report url xml. * * @return the committee report url xml */ @Basic @Column(name = "COMMITTEE_REPORT_URL_XML") public String getCommitteeReportUrlXml() { return committeeReportUrlXml; } /** * Sets the committee report url xml. * * @param value the new committee report url xml */ public void setCommitteeReportUrlXml(final String value) { this.committeeReportUrlXml = value; } /** * With hit. * * @param value the value * @return the document element */ public DocumentElement withHit(final BigInteger value) { setHit(value); return this; } /** * With id. * * @param value the value * @return the document element */ public DocumentElement withId(final String value) { setId(value); return this; } /** * With domain org. * * @param value the value * @return the document element */ public DocumentElement withDomainOrg(final String value) { setDomainOrg(value); return this; } /** * With document name. * * @param value the value * @return the document element */ public DocumentElement withDocumentName(final String value) { setDocumentName(value); return this; } /** * With debate name. * * @param value the value * @return the document element */ public DocumentElement withDebateName(final String value) { setDebateName(value); return this; } /** * With note title. * * @param value the value * @return the document element */ public DocumentElement withNoteTitle(final String value) { setNoteTitle(value); return this; } /** * With note. * * @param value the value * @return the document element */ public DocumentElement withNote(final String value) { setNote(value); return this; } /** * With summary. * * @param value the value * @return the document element */ public DocumentElement withSummary(final String value) { setSummary(value); return this; } /** * With database source. * * @param value the value * @return the document element */ public DocumentElement withDatabaseSource(final String value) { setDatabaseSource(value); return this; } /** * With origin. * * @param value the value * @return the document element */ public DocumentElement withOrigin(final String value) { setOrigin(value); return this; } /** * With lang. * * @param value the value * @return the document element */ public DocumentElement withLang(final String value) { setLang(value); return this; } /** * With rm. * * @param value the value * @return the document element */ public DocumentElement withRm(final String value) { setRm(value); return this; } /** * With related id. * * @param value the value * @return the document element */ public DocumentElement withRelatedId(final String value) { setRelatedId(value); return this; } /** * With document type. * * @param value the value * @return the document element */ public DocumentElement withDocumentType(final String value) { setDocumentType(value); return this; } /** * With doc type. * * @param value the value * @return the document element */ public DocumentElement withDocType(final String value) { setDocType(value); return this; } /** * With sub type. * * @param value the value * @return the document element */ public DocumentElement withSubType(final String value) { setSubType(value); return this; } /** * With status. * * @param value the value * @return the document element */ public DocumentElement withStatus(final String value) { setStatus(value); return this; } /** * With label. * * @param value the value * @return the document element */ public DocumentElement withLabel(final String value) { setLabel(value); return this; } /** * With temp label. * * @param value the value * @return the document element */ public DocumentElement withTempLabel(final String value) { setTempLabel(value); return this; } /** * With org. * * @param value the value * @return the document element */ public DocumentElement withOrg(final String value) { setOrg(value); return this; } /** * With number value. * * @param value the value * @return the document element */ public DocumentElement withNumberValue(final BigInteger value) { setNumberValue(value); return this; } /** * With title. * * @param value the value * @return the document element */ public DocumentElement withTitle(final String value) { setTitle(value); return this; } /** * With sub title. * * @param value the value * @return the document element */ public DocumentElement withSubTitle(final String value) { setSubTitle(value); return this; } /** * With created date. * * @param value the value * @return the document element */ public DocumentElement withCreatedDate(final String value) { setCreatedDate(value); return this; } /** * With made public date. * * @param value the value * @return the document element */ public DocumentElement withMadePublicDate(final String value) { setMadePublicDate(value); return this; } /** * With system date. * * @param value the value * @return the document element */ public DocumentElement withSystemDate(final String value) { setSystemDate(value); return this; } /** * With kall id. * * @param value the value * @return the document element */ public DocumentElement withKallId(final String value) { setKallId(value); return this; } /** * With document format. * * @param value the value * @return the document element */ public DocumentElement withDocumentFormat(final String value) { setDocumentFormat(value); return this; } /** * With document url text. * * @param value the value * @return the document element */ public DocumentElement withDocumentUrlText(final String value) { setDocumentUrlText(value); return this; } /** * With document url html. * * @param value the value * @return the document element */ public DocumentElement withDocumentUrlHtml(final String value) { setDocumentUrlHtml(value); return this; } /** * With document status url xml. * * @param value the value * @return the document element */ public DocumentElement withDocumentStatusUrlXml(final String value) { setDocumentStatusUrlXml(value); return this; } /** * With committee report url xml. * * @param value the value * @return the document element */ public DocumentElement withCommitteeReportUrlXml(final String value) { setCommitteeReportUrlXml(value); return this; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public final String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } /* (non-Javadoc) * @see org.jvnet.jaxb2_commons.lang.Equals#equals(org.jvnet.jaxb2_commons.locator.ObjectLocator, org.jvnet.jaxb2_commons.locator.ObjectLocator, java.lang.Object, org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy) */ public boolean equals(final ObjectLocator thisLocator, final ObjectLocator thatLocator, final Object object, final EqualsStrategy strategy) { if ((object == null)||(this.getClass()!= object.getClass())) { return false; } if (this == object) { return true; } final DocumentElement that = ((DocumentElement) object); { BigInteger lhsHit; lhsHit = this.getHit(); BigInteger rhsHit; rhsHit = that.getHit(); if (!strategy.equals(LocatorUtils.property(thisLocator, "hit", lhsHit), LocatorUtils.property(thatLocator, "hit", rhsHit), lhsHit, rhsHit)) { return false; } } { String lhsId; lhsId = this.getId(); String rhsId; rhsId = that.getId(); if (!strategy.equals(LocatorUtils.property(thisLocator, "id", lhsId), LocatorUtils.property(thatLocator, "id", rhsId), lhsId, rhsId)) { return false; } } { String lhsDomainOrg; lhsDomainOrg = this.getDomainOrg(); String rhsDomainOrg; rhsDomainOrg = that.getDomainOrg(); if (!strategy.equals(LocatorUtils.property(thisLocator, "domainOrg", lhsDomainOrg), LocatorUtils.property(thatLocator, "domainOrg", rhsDomainOrg), lhsDomainOrg, rhsDomainOrg)) { return false; } } { String lhsDocumentName; lhsDocumentName = this.getDocumentName(); String rhsDocumentName; rhsDocumentName = that.getDocumentName(); if (!strategy.equals(LocatorUtils.property(thisLocator, "documentName", lhsDocumentName), LocatorUtils.property(thatLocator, "documentName", rhsDocumentName), lhsDocumentName, rhsDocumentName)) { return false; } } { String lhsDebateName; lhsDebateName = this.getDebateName(); String rhsDebateName; rhsDebateName = that.getDebateName(); if (!strategy.equals(LocatorUtils.property(thisLocator, "debateName", lhsDebateName), LocatorUtils.property(thatLocator, "debateName", rhsDebateName), lhsDebateName, rhsDebateName)) { return false; } } { String lhsNoteTitle; lhsNoteTitle = this.getNoteTitle(); String rhsNoteTitle; rhsNoteTitle = that.getNoteTitle(); if (!strategy.equals(LocatorUtils.property(thisLocator, "noteTitle", lhsNoteTitle), LocatorUtils.property(thatLocator, "noteTitle", rhsNoteTitle), lhsNoteTitle, rhsNoteTitle)) { return false; } } { String lhsNote; lhsNote = this.getNote(); String rhsNote; rhsNote = that.getNote(); if (!strategy.equals(LocatorUtils.property(thisLocator, "note", lhsNote), LocatorUtils.property(thatLocator, "note", rhsNote), lhsNote, rhsNote)) { return false; } } { String lhsSummary; lhsSummary = this.getSummary(); String rhsSummary; rhsSummary = that.getSummary(); if (!strategy.equals(LocatorUtils.property(thisLocator, "summary", lhsSummary), LocatorUtils.property(thatLocator, "summary", rhsSummary), lhsSummary, rhsSummary)) { return false; } } { String lhsDatabaseSource; lhsDatabaseSource = this.getDatabaseSource(); String rhsDatabaseSource; rhsDatabaseSource = that.getDatabaseSource(); if (!strategy.equals(LocatorUtils.property(thisLocator, "databaseSource", lhsDatabaseSource), LocatorUtils.property(thatLocator, "databaseSource", rhsDatabaseSource), lhsDatabaseSource, rhsDatabaseSource)) { return false; } } { String lhsOrigin; lhsOrigin = this.getOrigin(); String rhsOrigin; rhsOrigin = that.getOrigin(); if (!strategy.equals(LocatorUtils.property(thisLocator, "origin", lhsOrigin), LocatorUtils.property(thatLocator, "origin", rhsOrigin), lhsOrigin, rhsOrigin)) { return false; } } { String lhsLang; lhsLang = this.getLang(); String rhsLang; rhsLang = that.getLang(); if (!strategy.equals(LocatorUtils.property(thisLocator, "lang", lhsLang), LocatorUtils.property(thatLocator, "lang", rhsLang), lhsLang, rhsLang)) { return false; } } { String lhsRm; lhsRm = this.getRm(); String rhsRm; rhsRm = that.getRm(); if (!strategy.equals(LocatorUtils.property(thisLocator, "rm", lhsRm), LocatorUtils.property(thatLocator, "rm", rhsRm), lhsRm, rhsRm)) { return false; } } { String lhsRelatedId; lhsRelatedId = this.getRelatedId(); String rhsRelatedId; rhsRelatedId = that.getRelatedId(); if (!strategy.equals(LocatorUtils.property(thisLocator, "relatedId", lhsRelatedId), LocatorUtils.property(thatLocator, "relatedId", rhsRelatedId), lhsRelatedId, rhsRelatedId)) { return false; } } { String lhsDocumentType; lhsDocumentType = this.getDocumentType(); String rhsDocumentType; rhsDocumentType = that.getDocumentType(); if (!strategy.equals(LocatorUtils.property(thisLocator, "documentType", lhsDocumentType), LocatorUtils.property(thatLocator, "documentType", rhsDocumentType), lhsDocumentType, rhsDocumentType)) { return false; } } { String lhsDocType; lhsDocType = this.getDocType(); String rhsDocType; rhsDocType = that.getDocType(); if (!strategy.equals(LocatorUtils.property(thisLocator, "docType", lhsDocType), LocatorUtils.property(thatLocator, "docType", rhsDocType), lhsDocType, rhsDocType)) { return false; } } { String lhsSubType; lhsSubType = this.getSubType(); String rhsSubType; rhsSubType = that.getSubType(); if (!strategy.equals(LocatorUtils.property(thisLocator, "subType", lhsSubType), LocatorUtils.property(thatLocator, "subType", rhsSubType), lhsSubType, rhsSubType)) { return false; } } { String lhsStatus; lhsStatus = this.getStatus(); String rhsStatus; rhsStatus = that.getStatus(); if (!strategy.equals(LocatorUtils.property(thisLocator, "status", lhsStatus), LocatorUtils.property(thatLocator, "status", rhsStatus), lhsStatus, rhsStatus)) { return false; } } { String lhsLabel; lhsLabel = this.getLabel(); String rhsLabel; rhsLabel = that.getLabel(); if (!strategy.equals(LocatorUtils.property(thisLocator, "label", lhsLabel), LocatorUtils.property(thatLocator, "label", rhsLabel), lhsLabel, rhsLabel)) { return false; } } { String lhsTempLabel; lhsTempLabel = this.getTempLabel(); String rhsTempLabel; rhsTempLabel = that.getTempLabel(); if (!strategy.equals(LocatorUtils.property(thisLocator, "tempLabel", lhsTempLabel), LocatorUtils.property(thatLocator, "tempLabel", rhsTempLabel), lhsTempLabel, rhsTempLabel)) { return false; } } { String lhsOrg; lhsOrg = this.getOrg(); String rhsOrg; rhsOrg = that.getOrg(); if (!strategy.equals(LocatorUtils.property(thisLocator, "org", lhsOrg), LocatorUtils.property(thatLocator, "org", rhsOrg), lhsOrg, rhsOrg)) { return false; } } { BigInteger lhsNumberValue; lhsNumberValue = this.getNumberValue(); BigInteger rhsNumberValue; rhsNumberValue = that.getNumberValue(); if (!strategy.equals(LocatorUtils.property(thisLocator, "numberValue", lhsNumberValue), LocatorUtils.property(thatLocator, "numberValue", rhsNumberValue), lhsNumberValue, rhsNumberValue)) { return false; } } { String lhsTitle; lhsTitle = this.getTitle(); String rhsTitle; rhsTitle = that.getTitle(); if (!strategy.equals(LocatorUtils.property(thisLocator, "title", lhsTitle), LocatorUtils.property(thatLocator, "title", rhsTitle), lhsTitle, rhsTitle)) { return false; } } { String lhsSubTitle; lhsSubTitle = this.getSubTitle(); String rhsSubTitle; rhsSubTitle = that.getSubTitle(); if (!strategy.equals(LocatorUtils.property(thisLocator, "subTitle", lhsSubTitle), LocatorUtils.property(thatLocator, "subTitle", rhsSubTitle), lhsSubTitle, rhsSubTitle)) { return false; } } { String lhsCreatedDate; lhsCreatedDate = this.getCreatedDate(); String rhsCreatedDate; rhsCreatedDate = that.getCreatedDate(); if (!strategy.equals(LocatorUtils.property(thisLocator, "createdDate", lhsCreatedDate), LocatorUtils.property(thatLocator, "createdDate", rhsCreatedDate), lhsCreatedDate, rhsCreatedDate)) { return false; } } { String lhsMadePublicDate; lhsMadePublicDate = this.getMadePublicDate(); String rhsMadePublicDate; rhsMadePublicDate = that.getMadePublicDate(); if (!strategy.equals(LocatorUtils.property(thisLocator, "madePublicDate", lhsMadePublicDate), LocatorUtils.property(thatLocator, "madePublicDate", rhsMadePublicDate), lhsMadePublicDate, rhsMadePublicDate)) { return false; } } { String lhsSystemDate; lhsSystemDate = this.getSystemDate(); String rhsSystemDate; rhsSystemDate = that.getSystemDate(); if (!strategy.equals(LocatorUtils.property(thisLocator, "systemDate", lhsSystemDate), LocatorUtils.property(thatLocator, "systemDate", rhsSystemDate), lhsSystemDate, rhsSystemDate)) { return false; } } { String lhsKallId; lhsKallId = this.getKallId(); String rhsKallId; rhsKallId = that.getKallId(); if (!strategy.equals(LocatorUtils.property(thisLocator, "kallId", lhsKallId), LocatorUtils.property(thatLocator, "kallId", rhsKallId), lhsKallId, rhsKallId)) { return false; } } { String lhsDocumentFormat; lhsDocumentFormat = this.getDocumentFormat(); String rhsDocumentFormat; rhsDocumentFormat = that.getDocumentFormat(); if (!strategy.equals(LocatorUtils.property(thisLocator, "documentFormat", lhsDocumentFormat), LocatorUtils.property(thatLocator, "documentFormat", rhsDocumentFormat), lhsDocumentFormat, rhsDocumentFormat)) { return false; } } { String lhsDocumentUrlText; lhsDocumentUrlText = this.getDocumentUrlText(); String rhsDocumentUrlText; rhsDocumentUrlText = that.getDocumentUrlText(); if (!strategy.equals(LocatorUtils.property(thisLocator, "documentUrlText", lhsDocumentUrlText), LocatorUtils.property(thatLocator, "documentUrlText", rhsDocumentUrlText), lhsDocumentUrlText, rhsDocumentUrlText)) { return false; } } { String lhsDocumentUrlHtml; lhsDocumentUrlHtml = this.getDocumentUrlHtml(); String rhsDocumentUrlHtml; rhsDocumentUrlHtml = that.getDocumentUrlHtml(); if (!strategy.equals(LocatorUtils.property(thisLocator, "documentUrlHtml", lhsDocumentUrlHtml), LocatorUtils.property(thatLocator, "documentUrlHtml", rhsDocumentUrlHtml), lhsDocumentUrlHtml, rhsDocumentUrlHtml)) { return false; } } { String lhsDocumentStatusUrlXml; lhsDocumentStatusUrlXml = this.getDocumentStatusUrlXml(); String rhsDocumentStatusUrlXml; rhsDocumentStatusUrlXml = that.getDocumentStatusUrlXml(); if (!strategy.equals(LocatorUtils.property(thisLocator, "documentStatusUrlXml", lhsDocumentStatusUrlXml), LocatorUtils.property(thatLocator, "documentStatusUrlXml", rhsDocumentStatusUrlXml), lhsDocumentStatusUrlXml, rhsDocumentStatusUrlXml)) { return false; } } { String lhsCommitteeReportUrlXml; lhsCommitteeReportUrlXml = this.getCommitteeReportUrlXml(); String rhsCommitteeReportUrlXml; rhsCommitteeReportUrlXml = that.getCommitteeReportUrlXml(); if (!strategy.equals(LocatorUtils.property(thisLocator, "committeeReportUrlXml", lhsCommitteeReportUrlXml), LocatorUtils.property(thatLocator, "committeeReportUrlXml", rhsCommitteeReportUrlXml), lhsCommitteeReportUrlXml, rhsCommitteeReportUrlXml)) { return false; } } return true; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(final Object object) { final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public final int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } } <file_sep>/* * Copyright 2010 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ * $HeadURL$ */ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.02.24 at 11:40:07 PM CET // package com.hack23.cia.model.external.riksdagen.dokumentstatus.impl; import java.math.BigInteger; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.jvnet.jaxb2_commons.lang.Equals; import org.jvnet.jaxb2_commons.lang.EqualsStrategy; import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; import com.hack23.cia.model.common.api.ModelObject; import com.hack23.cia.model.common.impl.xml.XmlDateTypeAdapter; /** * The Class DocumentActivityData. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DocumentActivityData", propOrder = { "createdDate", "code", "activityName", "orderNumber", "process", "status" }) @Entity(name = "DocumentActivityData") @Table(name = "DOCUMENT_ACTIVITY_DATA") @Inheritance(strategy = InheritanceType.JOINED) public class DocumentActivityData implements ModelObject, Equals { /** * */ private static final long serialVersionUID = 1L; /** The created date. */ @XmlElement(name = "datum", required = true, type = String.class) @XmlJavaTypeAdapter(XmlDateTypeAdapter.class) @XmlSchemaType(name = "date") protected Date createdDate; /** The code. */ @XmlElement(name = "kod", required = true) protected String code; /** The activity name. */ @XmlElement(name = "namn", required = true) protected String activityName; /** The order number. */ @XmlElement(name = "ordning", required = true) protected BigInteger orderNumber; /** The process. */ @XmlElement(required = true) protected String process; /** The status. */ @XmlElement(required = true) protected String status; /** The hjid. */ @XmlAttribute(name = "Hjid") protected Long hjid; /** * Gets the created date. * * @return the created date */ @Basic @Column(name = "CREATED_DATE") @Temporal(TemporalType.DATE) public Date getCreatedDate() { return createdDate; } /** * Sets the created date. * * @param value the new created date */ public void setCreatedDate(final Date value) { this.createdDate = value; } /** * Gets the code. * * @return the code */ @Basic @Column(name = "CODE") public String getCode() { return code; } /** * Sets the code. * * @param value the new code */ public void setCode(final String value) { this.code = value; } /** * Gets the activity name. * * @return the activity name */ @Basic @Column(name = "ACTIVITY_NAME") public String getActivityName() { return activityName; } /** * Sets the activity name. * * @param value the new activity name */ public void setActivityName(final String value) { this.activityName = value; } /** * Gets the order number. * * @return the order number */ @Basic @Column(name = "ORDER_NUMBER", precision = 20) public BigInteger getOrderNumber() { return orderNumber; } /** * Sets the order number. * * @param value the new order number */ public void setOrderNumber(final BigInteger value) { this.orderNumber = value; } /** * Gets the process. * * @return the process */ @Basic @Column(name = "PROCESS") public String getProcess() { return process; } /** * Sets the process. * * @param value the new process */ public void setProcess(final String value) { this.process = value; } /** * Gets the status. * * @return the status */ @Basic @Column(name = "STATUS") public String getStatus() { return status; } /** * Sets the status. * * @param value the new status */ public void setStatus(final String value) { this.status = value; } /** * With created date. * * @param value the value * @return the document activity data */ public DocumentActivityData withCreatedDate(final Date value) { setCreatedDate(value); return this; } /** * With code. * * @param value the value * @return the document activity data */ public DocumentActivityData withCode(final String value) { setCode(value); return this; } /** * With activity name. * * @param value the value * @return the document activity data */ public DocumentActivityData withActivityName(final String value) { setActivityName(value); return this; } /** * With order number. * * @param value the value * @return the document activity data */ public DocumentActivityData withOrderNumber(final BigInteger value) { setOrderNumber(value); return this; } /** * With process. * * @param value the value * @return the document activity data */ public DocumentActivityData withProcess(final String value) { setProcess(value); return this; } /** * With status. * * @param value the value * @return the document activity data */ public DocumentActivityData withStatus(final String value) { setStatus(value); return this; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public final String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } /** * Gets the hjid. * * @return the hjid */ @Id @Column(name = "HJID") @GeneratedValue(strategy = GenerationType.AUTO) public Long getHjid() { return hjid; } /** * Sets the hjid. * * @param value the new hjid */ public void setHjid(final Long value) { this.hjid = value; } /* (non-Javadoc) * @see org.jvnet.jaxb2_commons.lang.Equals#equals(org.jvnet.jaxb2_commons.locator.ObjectLocator, org.jvnet.jaxb2_commons.locator.ObjectLocator, java.lang.Object, org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy) */ public boolean equals(final ObjectLocator thisLocator, final ObjectLocator thatLocator, final Object object, final EqualsStrategy strategy) { if ((object == null)||(this.getClass()!= object.getClass())) { return false; } if (this == object) { return true; } final DocumentActivityData that = ((DocumentActivityData) object); { Date lhsCreatedDate; lhsCreatedDate = this.getCreatedDate(); Date rhsCreatedDate; rhsCreatedDate = that.getCreatedDate(); if (!strategy.equals(LocatorUtils.property(thisLocator, "createdDate", lhsCreatedDate), LocatorUtils.property(thatLocator, "createdDate", rhsCreatedDate), lhsCreatedDate, rhsCreatedDate)) { return false; } } { String lhsCode; lhsCode = this.getCode(); String rhsCode; rhsCode = that.getCode(); if (!strategy.equals(LocatorUtils.property(thisLocator, "code", lhsCode), LocatorUtils.property(thatLocator, "code", rhsCode), lhsCode, rhsCode)) { return false; } } { String lhsActivityName; lhsActivityName = this.getActivityName(); String rhsActivityName; rhsActivityName = that.getActivityName(); if (!strategy.equals(LocatorUtils.property(thisLocator, "activityName", lhsActivityName), LocatorUtils.property(thatLocator, "activityName", rhsActivityName), lhsActivityName, rhsActivityName)) { return false; } } { BigInteger lhsOrderNumber; lhsOrderNumber = this.getOrderNumber(); BigInteger rhsOrderNumber; rhsOrderNumber = that.getOrderNumber(); if (!strategy.equals(LocatorUtils.property(thisLocator, "orderNumber", lhsOrderNumber), LocatorUtils.property(thatLocator, "orderNumber", rhsOrderNumber), lhsOrderNumber, rhsOrderNumber)) { return false; } } { String lhsProcess; lhsProcess = this.getProcess(); String rhsProcess; rhsProcess = that.getProcess(); if (!strategy.equals(LocatorUtils.property(thisLocator, "process", lhsProcess), LocatorUtils.property(thatLocator, "process", rhsProcess), lhsProcess, rhsProcess)) { return false; } } { String lhsStatus; lhsStatus = this.getStatus(); String rhsStatus; rhsStatus = that.getStatus(); if (!strategy.equals(LocatorUtils.property(thisLocator, "status", lhsStatus), LocatorUtils.property(thatLocator, "status", rhsStatus), lhsStatus, rhsStatus)) { return false; } } return true; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(final Object object) { final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public final int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } } <file_sep>/* * Copyright 2010 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ * $HeadURL$ */ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.02.24 at 11:39:47 PM CET // package com.hack23.cia.model.external.val.partier.impl; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.jvnet.jaxb2_commons.lang.Equals; import org.jvnet.jaxb2_commons.lang.EqualsStrategy; import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; import com.hack23.cia.model.common.api.ModelObject; import com.hack23.cia.model.common.impl.xml.XmlDateTypeAdapter; /** * The Class SwedenPoliticalParty. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SwedenPoliticalParty", propOrder = { "partyName", "shortCode", "partyId", "coAddress", "phoneNumber", "address", "faxNumber", "postCode", "city", "email", "website", "registeredDate" }) @Entity(name = "SwedenPoliticalParty") @Table(name = "SWEDEN_POLITICAL_PARTY") @Inheritance(strategy = InheritanceType.JOINED) public class SwedenPoliticalParty implements ModelObject, Equals { /** * */ private static final long serialVersionUID = 1L; /** The party name. */ @XmlElement(name = "partibeteckning", required = true) protected String partyName; /** The short code. */ @XmlElement(name = "forkortning", required = true) protected String shortCode; /** The party id. */ @XmlElement(name = "id_parti", required = true) protected String partyId; /** The co address. */ @XmlElement(name = "co_adress", required = true) protected String coAddress; /** The phone number. */ @XmlElement(name = "telefon", required = true) protected String phoneNumber; /** The address. */ @XmlElement(name = "gatuadress", required = true) protected String address; /** The fax number. */ @XmlElement(name = "telefax", required = true) protected String faxNumber; /** The post code. */ @XmlElement(name = "postnummer", required = true) protected String postCode; /** The city. */ @XmlElement(name = "postort", required = true) protected String city; /** The email. */ @XmlElement(name = "epost", required = true) protected String email; /** The website. */ @XmlElement(name = "webbplats", required = true) @XmlSchemaType(name = "anyURI") protected String website; /** The registered date. */ @XmlElement(name = "registreringsdatum", required = true, type = String.class) @XmlJavaTypeAdapter(XmlDateTypeAdapter.class) @XmlSchemaType(name = "date") protected Date registeredDate; /** The hjid. */ @XmlAttribute(name = "Hjid") protected Long hjid; /** * Gets the party name. * * @return the party name */ @Basic @Column(name = "PARTY_NAME") public String getPartyName() { return partyName; } /** * Sets the party name. * * @param value the new party name */ public void setPartyName(final String value) { this.partyName = value; } /** * Gets the short code. * * @return the short code */ @Basic @Column(name = "SHORT_CODE") public String getShortCode() { return shortCode; } /** * Sets the short code. * * @param value the new short code */ public void setShortCode(final String value) { this.shortCode = value; } /** * Gets the party id. * * @return the party id */ @Basic @Column(name = "PARTY_ID") public String getPartyId() { return partyId; } /** * Sets the party id. * * @param value the new party id */ public void setPartyId(final String value) { this.partyId = value; } /** * Gets the co address. * * @return the co address */ @Basic @Column(name = "CO_ADDRESS") public String getCoAddress() { return coAddress; } /** * Sets the co address. * * @param value the new co address */ public void setCoAddress(final String value) { this.coAddress = value; } /** * Gets the phone number. * * @return the phone number */ @Basic @Column(name = "PHONE_NUMBER") public String getPhoneNumber() { return phoneNumber; } /** * Sets the phone number. * * @param value the new phone number */ public void setPhoneNumber(final String value) { this.phoneNumber = value; } /** * Gets the address. * * @return the address */ @Basic @Column(name = "ADDRESS") public String getAddress() { return address; } /** * Sets the address. * * @param value the new address */ public void setAddress(final String value) { this.address = value; } /** * Gets the fax number. * * @return the fax number */ @Basic @Column(name = "FAX_NUMBER") public String getFaxNumber() { return faxNumber; } /** * Sets the fax number. * * @param value the new fax number */ public void setFaxNumber(final String value) { this.faxNumber = value; } /** * Gets the post code. * * @return the post code */ @Basic @Column(name = "POST_CODE") public String getPostCode() { return postCode; } /** * Sets the post code. * * @param value the new post code */ public void setPostCode(final String value) { this.postCode = value; } /** * Gets the city. * * @return the city */ @Basic @Column(name = "CITY") public String getCity() { return city; } /** * Sets the city. * * @param value the new city */ public void setCity(final String value) { this.city = value; } /** * Gets the email. * * @return the email */ @Basic @Column(name = "EMAIL") public String getEmail() { return email; } /** * Sets the email. * * @param value the new email */ public void setEmail(final String value) { this.email = value; } /** * Gets the website. * * @return the website */ @Basic @Column(name = "WEBSITE") public String getWebsite() { return website; } /** * Sets the website. * * @param value the new website */ public void setWebsite(final String value) { this.website = value; } /** * Gets the registered date. * * @return the registered date */ @Basic @Column(name = "REGISTERED_DATE") @Temporal(TemporalType.DATE) public Date getRegisteredDate() { return registeredDate; } /** * Sets the registered date. * * @param value the new registered date */ public void setRegisteredDate(final Date value) { this.registeredDate = value; } /** * Gets the hjid. * * @return the hjid */ @Id @Column(name = "HJID") @GeneratedValue(strategy = GenerationType.AUTO) public Long getHjid() { return hjid; } /** * Sets the hjid. * * @param value the new hjid */ public void setHjid(final Long value) { this.hjid = value; } /* (non-Javadoc) * @see org.jvnet.jaxb2_commons.lang.Equals#equals(org.jvnet.jaxb2_commons.locator.ObjectLocator, org.jvnet.jaxb2_commons.locator.ObjectLocator, java.lang.Object, org.jvnet.jaxb2_commons.lang.EqualsStrategy) */ public boolean equals(final ObjectLocator thisLocator, final ObjectLocator thatLocator, final Object object, final EqualsStrategy strategy) { if ((object == null)||(this.getClass()!= object.getClass())) { return false; } if (this == object) { return true; } final SwedenPoliticalParty that = ((SwedenPoliticalParty) object); { String lhsPartyName; lhsPartyName = this.getPartyName(); String rhsPartyName; rhsPartyName = that.getPartyName(); if (!strategy.equals(LocatorUtils.property(thisLocator, "partyName", lhsPartyName), LocatorUtils.property(thatLocator, "partyName", rhsPartyName), lhsPartyName, rhsPartyName)) { return false; } } { String lhsShortCode; lhsShortCode = this.getShortCode(); String rhsShortCode; rhsShortCode = that.getShortCode(); if (!strategy.equals(LocatorUtils.property(thisLocator, "shortCode", lhsShortCode), LocatorUtils.property(thatLocator, "shortCode", rhsShortCode), lhsShortCode, rhsShortCode)) { return false; } } { String lhsPartyId; lhsPartyId = this.getPartyId(); String rhsPartyId; rhsPartyId = that.getPartyId(); if (!strategy.equals(LocatorUtils.property(thisLocator, "partyId", lhsPartyId), LocatorUtils.property(thatLocator, "partyId", rhsPartyId), lhsPartyId, rhsPartyId)) { return false; } } { String lhsCoAddress; lhsCoAddress = this.getCoAddress(); String rhsCoAddress; rhsCoAddress = that.getCoAddress(); if (!strategy.equals(LocatorUtils.property(thisLocator, "coAddress", lhsCoAddress), LocatorUtils.property(thatLocator, "coAddress", rhsCoAddress), lhsCoAddress, rhsCoAddress)) { return false; } } { String lhsPhoneNumber; lhsPhoneNumber = this.getPhoneNumber(); String rhsPhoneNumber; rhsPhoneNumber = that.getPhoneNumber(); if (!strategy.equals(LocatorUtils.property(thisLocator, "phoneNumber", lhsPhoneNumber), LocatorUtils.property(thatLocator, "phoneNumber", rhsPhoneNumber), lhsPhoneNumber, rhsPhoneNumber)) { return false; } } { String lhsAddress; lhsAddress = this.getAddress(); String rhsAddress; rhsAddress = that.getAddress(); if (!strategy.equals(LocatorUtils.property(thisLocator, "address", lhsAddress), LocatorUtils.property(thatLocator, "address", rhsAddress), lhsAddress, rhsAddress)) { return false; } } { String lhsFaxNumber; lhsFaxNumber = this.getFaxNumber(); String rhsFaxNumber; rhsFaxNumber = that.getFaxNumber(); if (!strategy.equals(LocatorUtils.property(thisLocator, "faxNumber", lhsFaxNumber), LocatorUtils.property(thatLocator, "faxNumber", rhsFaxNumber), lhsFaxNumber, rhsFaxNumber)) { return false; } } { String lhsPostCode; lhsPostCode = this.getPostCode(); String rhsPostCode; rhsPostCode = that.getPostCode(); if (!strategy.equals(LocatorUtils.property(thisLocator, "postCode", lhsPostCode), LocatorUtils.property(thatLocator, "postCode", rhsPostCode), lhsPostCode, rhsPostCode)) { return false; } } { String lhsCity; lhsCity = this.getCity(); String rhsCity; rhsCity = that.getCity(); if (!strategy.equals(LocatorUtils.property(thisLocator, "city", lhsCity), LocatorUtils.property(thatLocator, "city", rhsCity), lhsCity, rhsCity)) { return false; } } { String lhsEmail; lhsEmail = this.getEmail(); String rhsEmail; rhsEmail = that.getEmail(); if (!strategy.equals(LocatorUtils.property(thisLocator, "email", lhsEmail), LocatorUtils.property(thatLocator, "email", rhsEmail), lhsEmail, rhsEmail)) { return false; } } { String lhsWebsite; lhsWebsite = this.getWebsite(); String rhsWebsite; rhsWebsite = that.getWebsite(); if (!strategy.equals(LocatorUtils.property(thisLocator, "website", lhsWebsite), LocatorUtils.property(thatLocator, "website", rhsWebsite), lhsWebsite, rhsWebsite)) { return false; } } { Date lhsRegisteredDate; lhsRegisteredDate = this.getRegisteredDate(); Date rhsRegisteredDate; rhsRegisteredDate = that.getRegisteredDate(); if (!strategy.equals(LocatorUtils.property(thisLocator, "registeredDate", lhsRegisteredDate), LocatorUtils.property(thatLocator, "registeredDate", rhsRegisteredDate), lhsRegisteredDate, rhsRegisteredDate)) { return false; } } return true; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(final Object object) { final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public final String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public final int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
fe1bd5ebf667a62544df922aa3fd0e5e13346e74
[ "Java" ]
5
Java
fossabot/cia
097358d7cab6a26124036a89e773a69f23b941b6
3e8c61858958b4be6f517e272000d822f8020462
refs/heads/master
<repo_name>AprilC1983/C196MobileApp<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/Exceptions/HasCoursesAssignedException.java package com.example.acmay.c196mobileapp.Exceptions; public class HasCoursesAssignedException extends Exception{ public HasCoursesAssignedException(String s){ super(s); } } <file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/database/TermEntity.java package com.example.acmay.c196mobileapp.database; import android.arch.persistence.room.Entity; import android.arch.persistence.room.Ignore; import android.arch.persistence.room.PrimaryKey; import java.util.Date; @Entity(tableName = "terms") public class TermEntity { public int getTermID() { return termID; } @PrimaryKey(autoGenerate = true) private int termID; private Date createDate; private Date startDate; private Date endDate; private String title; public TermEntity(int termID, Date createDate, Date startDate, Date endDate, String title) { this.termID = termID; this.createDate = createDate; this.startDate = startDate; this.endDate = endDate; this.title = title; } @Ignore public TermEntity(Date createDate, Date startDate, Date endDate, String title) { this.createDate = createDate; this.startDate = startDate; this.endDate = endDate; this.title = title; } @Ignore public TermEntity() { } @Ignore public TermEntity(int id, Date createDate, String title) { this.termID = id; this.createDate = createDate; this.title = title; } @Ignore public TermEntity(Date createDate, String title) { this.createDate = createDate; this.title = title; } public int getId() { return termID; } public void setId(int id) { this.termID = id; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Override public String toString() { return "TermEntity{" + "id=" + termID + ", createDate=" + createDate + ", title='" + title + '\'' + '}'; } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/ui/AssessmentAdapter.java package com.example.acmay.c196mobileapp.ui; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.acmay.c196mobileapp.AssessmentDetailActivity; import com.example.acmay.c196mobileapp.AssessmentEditorActivity; import com.example.acmay.c196mobileapp.R; import com.example.acmay.c196mobileapp.database.AssessmentEntity; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import static com.example.acmay.c196mobileapp.utilities.Constants.ASS_ID_KEY; public class AssessmentAdapter extends RecyclerView.Adapter<AssessmentAdapter.ViewHolder> { private final List<AssessmentEntity> mAssessments; private final Context mContext; public AssessmentAdapter(List<AssessmentEntity> mAssessments, Context mContext) { this.mAssessments = mAssessments; this.mContext = mContext; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.list_item_1, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { final AssessmentEntity assessment = mAssessments.get(position); holder.mTextView.setText(assessment.getText()); //open assessment editor holder.eFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, AssessmentEditorActivity.class); intent.putExtra(ASS_ID_KEY, assessment.getId()); mContext.startActivity(intent); } }); //display assessment details holder.mTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, AssessmentDetailActivity.class); intent.putExtra(ASS_ID_KEY, assessment.getId()); mContext.startActivity(intent); } }); } @Override public int getItemCount() { return mAssessments.size(); } public class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.display_text_1) TextView mTextView; @BindView(R.id.edit_fab_1) FloatingActionButton eFab; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } } <file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/viewmodel/MentorDetailViewModel.java package com.example.acmay.c196mobileapp.viewmodel; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.MutableLiveData; import android.support.annotation.NonNull; import android.text.TextUtils; import com.example.acmay.c196mobileapp.database.AppRepository; import com.example.acmay.c196mobileapp.database.MentorEntity; import java.util.Date; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class MentorDetailViewModel extends AndroidViewModel { public MutableLiveData<MentorEntity> mLiveMentor = new MutableLiveData<>(); private AppRepository mRepository; private Executor executor = Executors.newSingleThreadExecutor(); public MentorDetailViewModel(@NonNull Application application) { super(application); mRepository = AppRepository.getInstance(getApplication()); } public void loadData(final int mentorId) { executor.execute(new Runnable() { @Override public void run() { MentorEntity mentor = mRepository.getMentorById(mentorId); mLiveMentor.postValue(mentor); } }); } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/AlertActivity.java package com.example.acmay.c196mobileapp; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.widget.Button; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.example.acmay.c196mobileapp.utilities.Constants.ALERT_MESSAGE_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.EDITING_KEY; public class AlertActivity extends AppCompatActivity { @BindView(R.id.alert_msg) TextView alertTxt; @BindView(R.id.ok_btn) Button okBtn; @BindView(R.id.ignore_btn) Button ignoreBtn; //exits Course detail screen @OnClick(R.id.ignore_btn) void ignoreClickHandler(){ finish(); } //open the note editor activity to add a note @OnClick(R.id.ok_btn) void addClickHandler(){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } private boolean mEditing; private int courseId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alert_layout); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ButterKnife.bind(this); if(savedInstanceState != null){ mEditing = savedInstanceState.getBoolean(EDITING_KEY); } Bundle extras = getIntent().getExtras(); if(extras == null){ setTitle("Error"); alertTxt.setText("Sorry, message unavailable"); } else { setTitle("Alert"); String message = (String) extras.get(ALERT_MESSAGE_KEY); alertTxt.setText(message); } } @Override public void onBackPressed() { finish(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(EDITING_KEY, true); super.onSaveInstanceState(outState); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/database/MentorDao.java package com.example.acmay.c196mobileapp.database; import android.arch.lifecycle.LiveData; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.OnConflictStrategy; import android.arch.persistence.room.Query; import java.util.List; @Dao public interface MentorDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insertMentor(MentorEntity mentorEntity); @Insert(onConflict = OnConflictStrategy.REPLACE) void insertAll(List<MentorEntity> mentors); @Delete void deleteMentor(MentorEntity mentorEntity); @Query("SELECT * FROM mentors WHERE mentorID = :id") MentorEntity getMentorById(int id); @Query("SELECT * FROM mentors ORDER BY createDate DESC") LiveData<List<MentorEntity>> getAll(); @Query("DELETE FROM mentors") int deleteAll(); @Query("SELECT COUNT(*) FROM mentors") int getCount(); }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/CourseEditorActivity.java package com.example.acmay.c196mobileapp; import android.app.AlarmManager; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.DatePicker; import android.widget.RadioButton; import android.widget.TextView; import com.example.acmay.c196mobileapp.database.CourseEntity; import com.example.acmay.c196mobileapp.viewmodel.CourseViewModel; import java.util.Date; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.example.acmay.c196mobileapp.utilities.Constants.CHANNEL_ID; import static com.example.acmay.c196mobileapp.utilities.Constants.ALERT_MESSAGE_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.COURSE_ID_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.EDITING_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.TERM_ID_KEY; public class CourseEditorActivity extends AppCompatActivity { @BindView(R.id.course_text) TextView courseTextView; @BindView(R.id.course_start_picker) DatePicker courseStart; @BindView(R.id.course_end_picker) DatePicker courseEnd; @BindView(R.id.plan_to_take_rb) RadioButton plannedRb; @BindView(R.id.in_progress_rb) RadioButton inProgRb; @BindView(R.id.completed_rb) RadioButton completedRb; @BindView(R.id.dropped_rb) RadioButton droppedRb; //exits course screen without saving data @OnClick(R.id.course_cancel_btn) void cancelClickHandler(){ finish(); } //Saves course data without continuing to the assessment editor @OnClick(R.id.course_save_btn) void saveClickHandler(){ saveAndReturn(); } private CourseViewModel mViewModel; private boolean mNewCourse, mEditing; private int courseID; private int termID; private String planned = "Plan to take"; private String taking = "In Progress"; private String completed = "Completed"; private String dropped = "Dropped"; private String msgTxt = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.course_editor); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ButterKnife.bind(this); if(savedInstanceState != null){ mEditing = savedInstanceState.getBoolean(EDITING_KEY); } initViewModel(); } private void initViewModel(){ mViewModel = ViewModelProviders.of(this) .get(CourseViewModel.class); mViewModel.mLiveCourse.observe(this, new Observer<CourseEntity>() { @Override public void onChanged(@Nullable CourseEntity courseEntity) { if(courseEntity != null && !mEditing) { String currentStatus = courseEntity.getStatus(); if(currentStatus == planned){ plannedRb.setChecked(true); }else if(currentStatus == taking){ inProgRb.setChecked(true); }else if(currentStatus == completed){ completedRb.setChecked(true); }else if(currentStatus == dropped){ droppedRb.setChecked(true); } courseTextView.setText(courseEntity.getTitle()); } } }); Bundle extras = getIntent().getExtras(); if(extras == null){ setTitle(R.string.new_course); mNewCourse = true; } else { setTitle(R.string.edit_course); courseID = extras.getInt(COURSE_ID_KEY); Log.i("cid", "course id = " + courseID); mViewModel.loadData(courseID); termID = extras.getInt(TERM_ID_KEY); } } //Creates a notification channel private void createAlert(long date, String courseMsg) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.channel_name); String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); //Specifies which screen launches***********************************************************************8 Intent intent = new Intent(this, AlertActivity.class); intent.putExtra(ALERT_MESSAGE_KEY, courseMsg); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); //This will trigger an alert for start and end dates AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC, date, pendingIntent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if(!mNewCourse){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_editor, menu); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == android.R.id.home){ saveAndReturn(); return true; } else if(item.getItemId() == R.id.action_delete){ mViewModel.deleteCourse(); finish(); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { saveAndReturn(); } private void saveAndReturn() { String title = courseTextView.getText().toString(); String status = ""; String startMessage; String endMessage; long startLong; long endLong; if(plannedRb.isChecked()){ status = planned; }else if(inProgRb.isChecked()){ status = taking; }else if(completedRb.isChecked()){ status = completed; }else if(droppedRb.isChecked()){ status = dropped; } int startDay = courseStart.getDayOfMonth(); int startMonth = courseStart.getMonth(); int startYear = courseStart.getYear(); int endDay = courseEnd.getDayOfMonth(); int endMonth = courseEnd.getMonth(); int endYear = courseEnd.getYear(); java.util.Date start = new java.util.Date(startYear - 1900, startMonth, startDay); java.util.Date end = new Date(endYear - 1900, endMonth, endDay); startLong = start.getTime(); endLong = end.getTime(); startMessage = title + " begins today"; endMessage = title + " is ending today"; createAlert(startLong, startMessage); createAlert(endLong, endMessage); mViewModel.saveCourse(termID, start, end, title, status); finish(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(EDITING_KEY, true); super.onSaveInstanceState(outState); } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/viewmodel/CourseDetailViewModel.java package com.example.acmay.c196mobileapp.viewmodel; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.MutableLiveData; import android.support.annotation.NonNull; import android.text.TextUtils; import com.example.acmay.c196mobileapp.database.AppRepository; import com.example.acmay.c196mobileapp.database.CourseEntity; import java.util.Date; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class CourseDetailViewModel extends AndroidViewModel { public MutableLiveData<CourseEntity> mLiveCourse = new MutableLiveData<>(); private AppRepository mRepository; private Executor executor = Executors.newSingleThreadExecutor(); public CourseDetailViewModel(@NonNull Application application) { super(application); mRepository = AppRepository.getInstance(getApplication()); } public void loadData(final int courseId) { executor.execute(new Runnable() { @Override public void run() { CourseEntity course = mRepository.getCourseById(courseId); mLiveCourse.postValue(course); } }); } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/viewmodel/MainViewModel.java package com.example.acmay.c196mobileapp.viewmodel; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.LiveData; import android.support.annotation.NonNull; import com.example.acmay.c196mobileapp.database.AppRepository; import com.example.acmay.c196mobileapp.database.AssessmentEntity; import com.example.acmay.c196mobileapp.database.CourseEntity; import com.example.acmay.c196mobileapp.database.MentorEntity; import com.example.acmay.c196mobileapp.database.NoteEntity; import com.example.acmay.c196mobileapp.database.TermEntity; import java.util.List; public class MainViewModel extends AndroidViewModel { public LiveData<List<TermEntity>> mTerms; public LiveData<List<CourseEntity>> mCourses; public LiveData<List<AssessmentEntity>> mAssessments; public LiveData<List<MentorEntity>> mMentors; public LiveData<List<NoteEntity>> mNotes; private AppRepository mRepository; public MainViewModel(@NonNull Application application) { super(application); mRepository = AppRepository.getInstance(application.getApplicationContext()); mTerms = mRepository.mTerms; mCourses = mRepository.mCourses; mAssessments = mRepository.mAssessments; mMentors = mRepository.mMentors; mNotes = mRepository.mNotess; } public void addSampleData() { mRepository.addSampleData(); } public void deleteAllTerms() { mRepository.deleteAllTerms(); } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/utilities/Constants.java package com.example.acmay.c196mobileapp.utilities; public class Constants { public static final String TERM_ID_KEY = "term_id_key"; public static final String COURSE_ID_KEY = "course_id_key"; public static final String ASS_ID_KEY = "ass_id_key"; public static final String NOTE_ID_KEY = "note_id_key"; public static final String MENTOR_ID_KEY = "mentor_id_key"; public static final String EDITING_KEY = "editing_key"; public static final String CHANNEL_ID = "10001"; public static final String ALERT_MESSAGE_KEY = "alert_message"; public static final String EMAIL_ID = "email_id"; public static final String SUBJECT_ID = "subject_id"; public static final String MESSAGE_ID = "message_id"; } <file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/database/CourseEntity.java package com.example.acmay.c196mobileapp.database; import android.arch.persistence.room.Entity; import android.arch.persistence.room.ForeignKey; import android.arch.persistence.room.Ignore; import android.arch.persistence.room.Index; import android.arch.persistence.room.PrimaryKey; import java.util.Date; @Entity(tableName = "courses", foreignKeys = @ForeignKey(entity = TermEntity.class, parentColumns = "termID", childColumns = "termID", onDelete = ForeignKey.CASCADE)) public class CourseEntity { @PrimaryKey(autoGenerate = true) private int courseID; private int termID; private Date createDate; private Date startDate; private Date endDate; private String title; private String status; public CourseEntity(int termID, Date createDate, Date startDate, Date endDate, String title, String status) { this.termID = termID; this.createDate = createDate; this.startDate = startDate; this.endDate = endDate; this.title = title; this.status = status; } @Ignore public CourseEntity(int termID, Date createDate, String title, Date startDate, Date endDate) { this.termID = termID; this.createDate = createDate; this.startDate = startDate; this.endDate = endDate; this.title = title; } @Ignore public CourseEntity() { } @Ignore public CourseEntity(int id, Date date, String title) { this.termID = id; this.createDate = date; this.title = title; } @Ignore public CourseEntity(Date date, String title) { this.createDate = date; this.title = title; } public int getId() { return courseID; } public void setId(int id) { this.courseID = id; } public Date getDate() { return createDate; } public void setDate(Date date) { this.createDate = date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getTermID() { return termID; } public void setTermID(int termID) { this.termID = termID; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public int getCourseID() { return courseID; } public void setCourseID(int courseID) { this.courseID = courseID; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "CourseEntity{" + "id=" + courseID + ", createDate=" + createDate + ", title='" + title + '\'' + '}'; } } <file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/ui/NoteAdapter.java package com.example.acmay.c196mobileapp.ui; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.acmay.c196mobileapp.AssessmentDisplayActivity; import com.example.acmay.c196mobileapp.CourseDetailActivity; import com.example.acmay.c196mobileapp.NoteEditorActivity; import com.example.acmay.c196mobileapp.MentorDisplayActivity; import com.example.acmay.c196mobileapp.R; import com.example.acmay.c196mobileapp.TermDetailActivity; import com.example.acmay.c196mobileapp.database.NoteEntity; import com.example.acmay.c196mobileapp.database.TermDao; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import static android.content.ContentValues.TAG; import static com.example.acmay.c196mobileapp.utilities.Constants.NOTE_ID_KEY; public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> { private final List<NoteEntity> mNotes; private final Context mContext; public NoteAdapter(List<NoteEntity> mNotes, Context mContext) { this.mNotes = mNotes; this.mContext = mContext; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.list_item_1, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { final NoteEntity note = mNotes.get(position); holder.mTextView.setText(note.getText()); holder.eFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, NoteEditorActivity.class); intent.putExtra(NOTE_ID_KEY, note.getId()); mContext.startActivity(intent); Log.i(TAG, "onClick: Open Note editor"); } }); /* //This click listener will take user to the display of the assessments holder.cFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, MentorDisplayActivity.class); intent.putExtra(NOTE_ID_KEY, note.getId()); mContext.startActivity(intent); Log.i(TAG, "onClick: Open assessment display"); } }); */ /* //Display the Note detail screen holder.mTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, NoteDetailActivity.class); intent.putExtra(COURSE_ID_KEY, course.getId()); mContext.startActivity(intent); Log.i(TAG, "onClick: Open course details"); } }); */ } @Override public int getItemCount() { return mNotes.size(); } public class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.display_text_1) TextView mTextView; @BindView(R.id.edit_fab_1) FloatingActionButton eFab; //@BindView(R.id.continue_fab) //FloatingActionButton cFab; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/viewmodel/AssessmentDetailViewModel.java package com.example.acmay.c196mobileapp.viewmodel; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.MutableLiveData; import android.support.annotation.NonNull; import android.text.TextUtils; import com.example.acmay.c196mobileapp.database.AppRepository; import com.example.acmay.c196mobileapp.database.AssessmentEntity; import java.util.Date; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class AssessmentDetailViewModel extends AndroidViewModel { public MutableLiveData<AssessmentEntity> mLiveAssessment = new MutableLiveData<>(); private AppRepository mRepository; private Executor executor = Executors.newSingleThreadExecutor(); public AssessmentDetailViewModel(@NonNull Application application) { super(application); mRepository = AppRepository.getInstance(getApplication()); } public void loadData(final int assessmentId) { executor.execute(new Runnable() { @Override public void run() { AssessmentEntity assessment = mRepository.getAssessmentById(assessmentId); mLiveAssessment.postValue(assessment); } }); } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/CourseDetailActivity.java package com.example.acmay.c196mobileapp; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; import com.example.acmay.c196mobileapp.database.CourseEntity; import com.example.acmay.c196mobileapp.viewmodel.CourseDetailViewModel; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.example.acmay.c196mobileapp.utilities.Constants.COURSE_ID_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.EDITING_KEY; public class CourseDetailActivity extends AppCompatActivity { @BindView(R.id.course_title_text) TextView courseDetailTextView; @BindView(R.id.course_start_text) TextView courseStart; @BindView(R.id.course_end_text) TextView courseEnd; @BindView(R.id.status_text) TextView courseStatus; /* //Exits Course detail screen and returns user to the list of courses @OnClick(R.id.course_detail_exit) void continueClickHandler(){ Intent intent = new Intent(this, CourseDisplayActivity.class); startActivity(intent); finish(); } */ //exits Course detail screen @OnClick(R.id.course_detail_exit) void cancelClickHandler(){ finish(); } //open the note editor activity to add a note @OnClick(R.id.view_btn) void addClickHandler(){ Intent intent = new Intent(this, NoteDisplayActivity.class); intent.putExtra(COURSE_ID_KEY, courseId); Log.i("ndis", "addClickHandler: cid is " + courseId); startActivity(intent); finish(); } //view existing notes @OnClick(R.id.add_btn) void viewClickHandler(){ Intent intent = new Intent(this, NoteEditorActivity.class); startActivity(intent); intent.putExtra(COURSE_ID_KEY, courseId); Log.i("ndis", "viewClickHandler: cid is " + courseId); finish(); } private CourseDetailViewModel mViewModel; private boolean mNewCourseDetail, mEditing; private int courseId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.course_detail); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ButterKnife.bind(this); /* if(savedInstanceState != null){ mEditing = savedInstanceState.getBoolean(EDITING_KEY); } */ initViewModel(); } private void initViewModel(){ mViewModel = ViewModelProviders.of(this) .get(CourseDetailViewModel.class); mViewModel.mLiveCourse.observe(this, new Observer<CourseEntity>() { @Override public void onChanged(@Nullable CourseEntity courseEntity) { if(courseEntity != null && !mEditing) { courseDetailTextView.setText("Course Title: " + courseEntity.getTitle()); courseStart.setText("Start Date: " + courseEntity.getStartDate()); courseEnd.setText("End Date: " + courseEntity.getEndDate()); courseStatus.setText("Status: " + courseEntity.getStatus()); } } }); Bundle extras = getIntent().getExtras(); if(extras == null){ setTitle(R.string.selected_course); mNewCourseDetail = true; } else { setTitle(R.string.selected_course); courseId = extras.getInt(COURSE_ID_KEY); mViewModel.loadData(courseId); } } @Override public void onBackPressed() { finish(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(EDITING_KEY, true); super.onSaveInstanceState(outState); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.action_back){ Intent intent = new Intent(this, CourseDisplayActivity.class); //startActivity(intent); finish(); return true; } return super.onOptionsItemSelected(item); } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/TermDetailActivity.java package com.example.acmay.c196mobileapp; import android.app.AlertDialog; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; import com.example.acmay.c196mobileapp.database.TermEntity; import com.example.acmay.c196mobileapp.viewmodel.TermDetailViewModel; import java.util.Date; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; //import static com.example.acmay.c196mobileapp.utilities.Constants.TERM_DETAIL_ID_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.CHANNEL_ID; import static com.example.acmay.c196mobileapp.utilities.Constants.EDITING_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.TERM_ID_KEY; public class TermDetailActivity extends AppCompatActivity { @BindView(R.id.term_title_text) TextView termDetailTextView; @BindView(R.id.term_start_text) TextView termStart; @BindView(R.id.term_end_text) TextView termEnd; //exits term detail screen @OnClick(R.id.term_detail_exit) void cancelClickHandler() { finish(); } @OnClick(R.id.delete_term_btn) void delete() { mViewModel.deleteTerm(TermDetailActivity.this); } private TermDetailViewModel mViewModel; private boolean mNewTermDetail, mEditing; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.term_detail); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ButterKnife.bind(this); initViewModel(); } private void initViewModel() { mViewModel = ViewModelProviders.of(this) .get(TermDetailViewModel.class); mViewModel.mLiveTerm.observe(this, new Observer<TermEntity>() { @Override public void onChanged(@Nullable TermEntity termEntity) { if (termEntity != null && !mEditing) { termDetailTextView.setText("Term: " + termEntity.getTitle()); termStart.setText("Start Date: " + termEntity.getStartDate()); termEnd.setText("End Date: " + termEntity.getEndDate()); Date start = termEntity.getStartDate(); } } }); Bundle extras = getIntent().getExtras(); if (extras == null) { setTitle(R.string.selected_term); mNewTermDetail = true; } else { setTitle(R.string.selected_term); int termDetailId = extras.getInt(TERM_ID_KEY); mViewModel.loadData(termDetailId); } } @Override public void onBackPressed() { finish(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(EDITING_KEY, true); super.onSaveInstanceState(outState); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.action_back){ Intent intent = new Intent(this, MainActivity.class); //startActivity(intent); finish(); return true; } return super.onOptionsItemSelected(item); } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/EmailActivity.java package com.example.acmay.c196mobileapp; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; import com.example.acmay.c196mobileapp.database.NoteEntity; import com.example.acmay.c196mobileapp.viewmodel.NoteViewModel; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.example.acmay.c196mobileapp.utilities.Constants.COURSE_ID_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.EDITING_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.EMAIL_ID; import static com.example.acmay.c196mobileapp.utilities.Constants.MESSAGE_ID; import static com.example.acmay.c196mobileapp.utilities.Constants.NOTE_ID_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.SUBJECT_ID; public class EmailActivity extends AppCompatActivity { @BindView(R.id.recipientTxt) TextView recipTxt; @BindView(R.id.subjectTxt) TextView subTxt; @BindView(R.id.messageTxt) TextView msgTxt; //exits Note screen without saving data @OnClick(R.id.sendBtn) void sendClickHandler(){ String message = msgTxt.getText().toString(); String recipient = recipTxt.getText().toString(); String subject = subTxt.getText().toString(); Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient}); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, message); intent.setType("message/rfc822"); startActivity(Intent.createChooser(intent,"Choose Mail App")); finish(); } private boolean mEditing; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.email_editor); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ButterKnife.bind(this); if(savedInstanceState != null){ mEditing = savedInstanceState.getBoolean(EDITING_KEY); } Bundle extras = getIntent().getExtras(); if(extras != null) { String note = extras.getString(MESSAGE_ID); msgTxt.setText(note); }else if(extras == null){ Log.i("email", "onCreate: extras was null"); } } @Override public void onBackPressed() { saveAndReturn(); } private void saveAndReturn() { finish(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(EDITING_KEY, true); super.onSaveInstanceState(outState); } @Override public boolean onCreateOptionsMenu(Menu menu) { //if(!mNewCourse){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); //} return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { /* if(item.getItemId() == android.R.id.home){ saveAndReturn(); return true; } else if(item.getItemId() == R.id.action_delete){ mViewModel.deleteCourse(); finish(); } */ return super.onOptionsItemSelected(item); } }<file_sep>/app/src/main/java/com/example/acmay/c196mobileapp/MentorDisplayActivity.java package com.example.acmay.c196mobileapp; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.example.acmay.c196mobileapp.database.CourseEntity; import com.example.acmay.c196mobileapp.database.MentorEntity; import com.example.acmay.c196mobileapp.ui.MentorAdapter; import com.example.acmay.c196mobileapp.viewmodel.MainViewModel; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.example.acmay.c196mobileapp.utilities.Constants.COURSE_ID_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.MENTOR_ID_KEY; import static com.example.acmay.c196mobileapp.utilities.Constants.TERM_ID_KEY; public class MentorDisplayActivity extends AppCompatActivity { @BindView(R.id.recycler_view) RecyclerView mRecyclerView; public static final String TAG = "Mentor Display"; @OnClick(R.id.add_fab) void fabClickHandler(){ Intent intent = new Intent(this, MentorEditorActivity.class); intent.putExtra(COURSE_ID_KEY, courseId); startActivity(intent); //Log.i("zz", "fabClickHandler mentor: cid is " + courseId); } private List<MentorEntity> allMentors = new ArrayList<>(); private List<MentorEntity> displayMentors = new ArrayList<>(); private MentorAdapter mAdapter; private MainViewModel mViewModel; private int courseId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ButterKnife.bind(this); initRecyclerView(); initViewModel(); } //displays the selected mentor(s) private void initViewModel() { final Observer<List<MentorEntity>> mentorsObserver = new Observer<List<MentorEntity>>() { @Override public void onChanged(@Nullable List<MentorEntity> mentorEntities) { allMentors.clear(); allMentors.addAll(mentorEntities); List<MentorEntity> selectedMentors; selectedMentors = getSelected(allMentors); displayMentors.clear(); displayMentors.addAll(selectedMentors); if(mAdapter == null){ mAdapter = new MentorAdapter(displayMentors, MentorDisplayActivity.this); mRecyclerView.setAdapter(mAdapter); } else{ mAdapter.notifyDataSetChanged(); } } }; mViewModel = ViewModelProviders.of(this) .get(MainViewModel.class); mViewModel.mMentors.observe(this, mentorsObserver); } //initializes the recyclerview private void initRecyclerView() { mRecyclerView.setHasFixedSize(true); LinearLayoutManager layoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(layoutManager); DividerItemDecoration divider = new DividerItemDecoration( mRecyclerView.getContext(), layoutManager.getOrientation()); mRecyclerView.addItemDecoration(divider); } //returns a list of courses associated with the selected term private List<MentorEntity> getSelected(List<MentorEntity> all){ Bundle extras = getIntent().getExtras(); courseId = extras.getInt(COURSE_ID_KEY); Log.i("zz", "getSelected in mentor display cid is: " + courseId); List<MentorEntity> selected = new ArrayList<>(); for(int i = 0; i < allMentors.size(); i++){ MentorEntity mentor; mentor = allMentors.get(i); int course = mentor.getCourseID(); if(course == courseId){ selected.add(mentor); } } return selected; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.action_back){ Intent intent = new Intent(this, CourseDisplayActivity.class); //startActivity(intent); finish(); return true; } return super.onOptionsItemSelected(item); } }
214dfd99c8431da0e1429675a61642690ca58835
[ "Java" ]
17
Java
AprilC1983/C196MobileApp
a0c90e77152e2940efc7f102a9882cc774b242ab
c404ab82e7817d148eeecced1e929e7373de1ae4
refs/heads/main
<repo_name>taillong/hait-advanced-teamB<file_sep>/requirements.txt Django==2.2.16 djangorestframework==3.12.1 pytz==2020.1 sqlparse==0.4.1 <file_sep>/README.md # hait-advanced-teamB
75d5cc83e0c93ba0de3eb203c05bb0a676a143ab
[ "Markdown", "Text" ]
2
Markdown
taillong/hait-advanced-teamB
8ac71c828f805ba7f83f2d603551c975cda5545e
ee0e4ebc3df17ebb698cfff63744d4ab655d92ea
refs/heads/master
<file_sep># Project_TreeMatch Project: Tree Match <file_sep>package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "strconv" "github.com/gorilla/mux" "gopkg.in/go-playground/validator.v9" ) // Question struct type Question struct { ID int `json:"id" validate:"required"` Question string `json:"question" validate:"required"` Validation []string `json:"validation" validate:"required"` } // Questions struct type Questions struct { Questions []Question `json:"questions"` } // Step struct type Step struct { ID int `json:"id" validate:"required"` QuestionID int `json:"question_id" validate:"required_without=ResultID"` Answers map[string]int `json:"answers" validate:"required_without=ResultID"` ResultID int `json:"result_id" validate:"required_without_all=QuestionID Answers"` } // Steps struct type Steps struct { Steps []Step `json:"steps"` } // Result struct type Result struct { ID int `json:"id" validate:"required"` Name string `json:"name" validate:"required"` Description string `json:"description" validate:"required"` } // Results struct type Results struct { Results []Result `json:"results"` } // TemQuestion to display type TemQuestion struct { StepID int `json:"step_id"` Question string `json:"question"` Answers []string `json:"answers"` } // QuestionFormat struct type QuestionFormat struct { Question TemQuestion `json:"question"` } // TemAnswer struct type TemAnswer struct { StepID int `json:"step_id" validate:"required"` Answer string `json:"answer" validate:"required"` } // Match struct type Match struct { Name string `json:"name"` Description string `json:"description"` } // MatchFormat struct type MatchFormat struct { MatchFormat Match `json:"match"` } // ErrMsg struct type ErrMsg struct { ErrMsg string } // init var questions Questions var steps Steps var results Results var temQ QuestionFormat func main() { // make database from JSON file ----------------------// // for validation validate := validator.New() // open, close file jsonFile, err := os.Open("questions.json") if err != nil { fmt.Println(err) } fmt.Println("File opened.") defer jsonFile.Close() // read file byteValue, _ := ioutil.ReadAll(jsonFile) // get questions json.Unmarshal(byteValue, &questions) if len(questions.Questions) <= 0 { log.Fatal("There is no questions.") } for i := 0; i < len(questions.Questions)-1; i++ { err = validate.Struct(questions.Questions[i]) if err != nil { s := "---- Suspect quesiont ID = " + strconv.Itoa(i+1) + " ----\n" log.Fatal(s + err.Error()) } } // get steps json.Unmarshal(byteValue, &steps) if len(steps.Steps) <= 0 { log.Fatal("There is no steps.") } for i := 0; i < len(steps.Steps)-1; i++ { err = validate.Struct(steps.Steps[i]) if err != nil { s := "---- Suspect step ID = " + strconv.Itoa(i+1) + " ----\n" log.Fatal(s + err.Error()) } } // get results json.Unmarshal(byteValue, &results) if len(results.Results) <= 0 { log.Fatal("There is no results.") } for i := 0; i < len(results.Results)-1; i++ { err = validate.Struct(results.Results[i]) if err != nil { s := "---- Suspect result ID = " + strconv.Itoa(i+1) + " ----\n" log.Fatal(s + err.Error()) } } // make API -----------------------------------------// // initial Router r := mux.NewRouter() // Route Handles / Endpointers r.HandleFunc("/api/begin", begin).Methods("GET") r.HandleFunc("/api/answer", answer).Methods("POST") log.Fatal(http.ListenAndServe(":8080", r)) } // get answer and return new question / match // format: // { // "step_id": 1, // "answer": "courtyard" // } func answer(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") // get answer var answer TemAnswer _ = json.NewDecoder(r.Body).Decode(&answer) fmt.Println(answer.StepID) fmt.Println(answer) if answer.StepID <= 0 || answer.StepID > len(steps.Steps) { T := ErrMsg{ErrMsg: "Wrong step_id input, step_id can't be empty, only can be number, input again please."} json.NewEncoder(w).Encode(T) return } if len(answer.Answer) <= 0 { T := ErrMsg{ErrMsg: "Wrong answer input, answer can be only from previous answer, input again please."} json.NewEncoder(w).Encode(T) return } // find next question(or a tree match!) // get the step struct curStep := steps.Steps[answer.StepID-1] //var nextStepID int nextStepID := curStep.Answers[answer.Answer] if nextStepID <= 0 { T := ErrMsg{ErrMsg: "Wrong answer input, answer must be identical with one of previous answers choices, input again please."} json.NewEncoder(w).Encode(T) return } nextStep := steps.Steps[nextStepID-1] if nextStep.ResultID != 0 { m := Match{Name: results.Results[nextStep.ResultID-1].Name, Description: results.Results[nextStep.ResultID-1].Description} match := MatchFormat{MatchFormat: m} json.NewEncoder(w).Encode(match) return } nextQID := nextStep.QuestionID json.NewEncoder(w).Encode(questions.Questions[nextQID-1]) } // begin with first step's question func begin(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") qID := steps.Steps[0].QuestionID q := TemQuestion{ StepID: 1, Question: questions.Questions[qID-1].Question, Answers: questions.Questions[qID-1].Validation, } temQ = QuestionFormat{Question: q} json.NewEncoder(w).Encode(temQ) return }
1fb4562f7f0a6ece2298177625b0fe656eb13f38
[ "Markdown", "Go" ]
2
Markdown
chen-qian-dan/Project_TreeMatch
cac9d0ffc1f50bb5d6f228ebaa63c329997353b5
408cf049b06c91bd0c9bdd6b5f0be09d1fbaff26
refs/heads/master
<file_sep># screamapp A social media app based on freecodecamp
37fc1ed2dfd331c342bc8c4514ac6493220d617a
[ "Markdown" ]
1
Markdown
AntonnioJones/screamapp
5651e50f5cd25a362b03b65aeb56a32fd1636504
c6f19840065fe98fdd3f609cad13314129c8997a
refs/heads/master
<repo_name>kvkens/DataBaseTools<file_sep>/PasswordGenerator/Password.cs /* * Created by SharpDevelop. * User: Kvkens * Date: 2016/1/8 * Time: 12:56 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Text; namespace PasswordGenerator { /// <summary> /// Description of Password. /// </summary> public class Password { public Password() { } public string GetPassword(int _length,bool _isnum) { string words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; StringBuilder sb = new StringBuilder(); Random random = new Random(); int FinalLength = _isnum ? words.Length : words.Length - 10; for (int i = 0; i < _length; i++) { sb.Append(words[random.Next(0,FinalLength)]); } return sb.ToString(); } } } <file_sep>/PasswordGenerator/MainForm.cs /* * Created by SharpDevelop. * User: Kvkens * Date: 2016/1/7 * Time: 13:13 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace PasswordGenerator { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // } void TxtGenPasswordClick(object sender, EventArgs e) { TxtGenPassword.SelectAll(); TxtGenPassword.Copy(); LabInfo.Text="已经复制到剪贴板,直接粘贴使用!"; } void BtnGeneratorClick(object sender, EventArgs e) { Password password = new Password(); TxtGenPassword.Text = password.GetPassword(int.Parse(Nud.Value.ToString()),ChkIsNum.Checked); LabInfo.Text=""; } } } <file_sep>/DataBaseTools/MainForm.cs /* * Created by SharpDevelop. * User: Kvkens * Date: 2015/12/28 * Time: 13:00 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Configuration; using MySql.Data.MySqlClient; using System.Data; namespace DataBaseTools { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { public MySqlConnection myconn=null; public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // } void BtnLoginDatabaseClick(object sender, EventArgs e) { string sql = string.Format("select * from {0}",TxtTable.Text.Trim()); var ds = GetDataSet(sql); // while (dr.Read()) { // MessageBox.Show(dr.GetString(0)); // } dgv.DataSource = ds; dgv.DataMember = "dnf"; myconn.Close(); } /// <summary> /// 获得MySqlConnection /// </summary> /// <returns>MySqlConnection</returns> public MySqlConnection GetConnection() { string sqlconn = string.Format("server={0};user id={1};password={2};database={3};port={4}",TxtDataIP.Text,TxtUsername.Text,TxtPassword.Text,TxtDataBase.Text,TxtDataPort.Text); myconn = new MySqlConnection(sqlconn); return myconn; } /// <summary> /// 获得DataReader /// </summary> /// <param name="sqlcmdstr"></param> /// <returns>MySqlDataReader</returns> public MySqlDataReader GetDataReader(string sqlcmdstr) { MySqlConnection sqlconn = this.GetConnection(); var sqlcmd = new MySqlCommand(sqlcmdstr,sqlconn); sqlconn.Open(); MySqlDataReader sqldr = sqlcmd.ExecuteReader(CommandBehavior.CloseConnection); return sqldr; } public DataSet GetDataSet(string sqlcmdstr) { MySqlConnection sqlconn = this.GetConnection(); var sqlcmd = new MySqlCommand(sqlcmdstr,sqlconn); sqlconn.Open(); var sqlda = new MySqlDataAdapter(sqlcmd); var ds = new DataSet(); sqlda.Fill(ds,"dnf"); return ds; } void MainFormLoad(object sender, EventArgs e) { string Username = ConfigurationManager.AppSettings["Username"].ToString(); string Password = ConfigurationManager.AppSettings["Password"].ToString(); string Database = ConfigurationManager.AppSettings["Database"].ToString(); string Ip = ConfigurationManager.AppSettings["Ip"].ToString(); string Port = ConfigurationManager.AppSettings["Port"].ToString(); TxtUsername.Text = Username.Trim(); TxtPassword.Text = <PASSWORD>.Trim(); TxtDataBase.Text = Database.Trim(); TxtDataIP.Text = Ip.Trim(); TxtDataPort.Text = Port.Trim(); } } } <file_sep>/DataBaseTools/Test.cs /* * Created by SharpDevelop. * User: Kvkens * Date: 2015/12/30 * Time: 13:52 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Drawing; using System.Windows.Forms; namespace DataBaseTools { /// <summary> /// Description of Test. /// </summary> public partial class Test : Form { MainForm frm = new MainForm(); public Test() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // } public Test(MainForm mainfrm) { InitializeComponent(); frm = mainfrm; } void Button1Click(object sender, EventArgs e) { frm.ChangeTable("asd"); } } }
4cefb5de907d0d745cf4f75ec732bce3bef06587
[ "C#" ]
4
C#
kvkens/DataBaseTools
f762990859d7bd3dc237e1dac4bb2b8348b3bab3
4399881ea01b8431da6b2d14055250e9ece5bc53
refs/heads/master
<repo_name>frei-sven/PCRM<file_sep>/PCRM.Database/DataAccess/IPcrmDao.cs using PCRM.Database.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PCRM.Database.DataAccess { interface IPcrmDao { Employee GetEmployee(int id); } } <file_sep>/ConsoleClient/Program.cs using PCRM.Database.Context; using PCRM.Database.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleClient { class Program { static void Main(string[] args) { Console.WriteLine("Read Database:"); ReadDatabase(); ReadKey(); //Console.WriteLine("\nInsert Employee"); //InsertEmployee(); //ReadKey(); Console.ReadKey(); } private static void InsertEmployee() { Employee emp = new Employee { Firstname = "Ordos", Lastname = "Feuermensch", Department = "Zeitlose Insel", Salary = 80 }; using (var context = new PcrmContext()) { var project = context.Projects.Find(1); emp.Projects.Add(project); if(context.Employees.Where(e => e.Firstname.Equals(emp.Firstname)).Any()) { context.Employees.Add(emp); context.SaveChanges(); } } } static void ReadDatabase() { using (var context = new PcrmContext()) { Console.WriteLine("Employees:"); foreach (var e in context.Employees.ToList()) { Console.WriteLine($" Employee #{e.Id}: {e.Firstname} {e.Lastname}"); foreach (var pro in e.Projects) { Console.WriteLine($" -{pro.Name}"); } } Console.WriteLine("Projects:"); foreach (var p in context.Projects.ToList()) { Console.WriteLine($" Project #{p.Id}: {p.Name} - {p.Description}"); Console.Write("=> "); foreach (var emp in p.Employees) { Console.Write($"{emp.Firstname} {emp.Lastname}, "); } Console.WriteLine(); } } } private static void ReadKey() { Console.Write("Press Key..."); Console.ReadKey(); } } } <file_sep>/Restful/PcrmService.svc.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using PCRM.Database; using PCRM.Database.DataAccess; using Restful.Entities; namespace Restful { public class PcrmService : IPcrmService { private PcrmDao _pcrmDao; public RestEmployee GetEmployee(int id) { _pcrmDao = new PcrmDao(); return new RestEmployee(_pcrmDao.GetEmployee(id)); } } } <file_sep>/pcrm.sql -- phpMyAdmin SQL Dump -- version 4.6.5.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Erstellungszeit: 26. Apr 2017 um 10:48 -- Server-Version: 10.1.21-MariaDB -- PHP-Version: 5.6.30 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Datenbank: `pcrm` -- -- -------------------------------------------------------- -- -- Tabellenstruktur für Tabelle `approach` -- CREATE TABLE `approach` ( `id` int(11) NOT NULL, `priority` int(11) NOT NULL, `date` date NOT NULL, `time` time NOT NULL, `comment` varchar(200) NOT NULL, `status` tinyint(1) NOT NULL, `employee_IDFS` int(11) NOT NULL, `contactperson_IDFS` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Daten für Tabelle `approach` -- INSERT INTO `approach` (`id`, `priority`, `date`, `time`, `comment`, `status`, `employee_IDFS`, `contactperson_IDFS`) VALUES (5, 2, '2017-02-22', '15:00:00', 'Informations about the new delivery', 0, 8, 2), (6, 3, '2017-03-22', '12:05:00', 'Top Secret!', 0, 11, 7), (7, 2, '2017-03-22', '12:05:00', 'Smalltalk', 0, 3, 10), (8, 1, '2017-03-22', '18:00:00', 'Important informations about my house.', 0, 5, 5), (9, 1, '2017-03-22', '17:00:00', 'Do I want to know?', 0, 9, 10), (11, 2, '2017-03-23', '08:00:00', 'Tomorrow', 0, 3, 2), (12, 2, '2017-03-22', '14:30:00', 'New Cookingshow', 0, 5, 2), (13, 1, '2017-03-22', '18:15:00', 'I want to talk to you and make kids with your goose.', 0, 1, 8), (14, 3, '2017-03-27', '08:00:00', 'Remember me?', 1, 1, 2), (15, 3, '2017-03-27', '15:20:00', 'Just to test.', 1, 4, 1), (16, 2, '2017-03-27', '17:15:00', 'An<NAME>', 1, 1, 6), (17, 1, '2017-03-27', '18:00:00', 'You smart', 0, 7, 2), (18, 3, '2017-03-28', '16:20:00', 'Die transparenz...', 0, 1, 10), (19, 3, '2017-03-28', '17:50:00', 'Mir mached das ja die ganz ziit!', 0, 1, 5), (20, 3, '2017-03-28', '13:00:00', 'Ich find grad mini Idee saumässig geil.', 0, 1, 8), (21, 2, '2017-03-28', '13:00:00', 'Arrogante blöde H*****hn', 0, 4, 2), (22, 2, '2017-03-28', '09:00:00', 'Hoi. Hoi? Hoi!', 1, 9, 6), (23, 1, '2017-03-29', '12:00:00', 'Hi', 0, 1, 1); -- -------------------------------------------------------- -- -- Tabellenstruktur für Tabelle `contact` -- CREATE TABLE `contact` ( `id` int(11) NOT NULL, `date` date NOT NULL, `time` time NOT NULL, `text` varchar(1000) NOT NULL, `comment` varchar(200) NOT NULL, `contactperson_IDFS` int(11) NOT NULL, `employee_IDFS` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Daten für Tabelle `contact` -- INSERT INTO `contact` (`id`, `date`, `time`, `text`, `comment`, `contactperson_IDFS`, `employee_IDFS`) VALUES (2, '2017-03-23', '00:00:00', 'Phonecall to discuss the new ingredients.', 'Discussed new taste \"Full Nature\"', 2, 11), (3, '2017-03-24', '15:05:00', 'Hoch die Hände..', '..Wochenende!', 2, 4), (4, '2017-03-25', '09:29:24', 'Du bist wirklich ein harter Bänger.', 'Ooop there it is.', 2, 7), (5, '2017-03-25', '20:30:00', 'G N K K', 'Trill', 2, 1); -- -------------------------------------------------------- -- -- Tabellenstruktur für Tabelle `contactperson` -- CREATE TABLE `contactperson` ( `id` int(11) NOT NULL, `lastname` varchar(50) NOT NULL, `firstname` varchar(50) NOT NULL, `phonenumber` varchar(20) NOT NULL, `mail` varchar(50) NOT NULL, `comment` varchar(200) NOT NULL, `project_IDFS` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Daten für Tabelle `contactperson` -- INSERT INTO `contactperson` (`id`, `lastname`, `firstname`, `phonenumber`, `mail`, `comment`, `project_IDFS`) VALUES (1, 'Maier', 'Peter', '079 841 83 19', '<EMAIL>', 'This is the first Contactperson ever!', 1), (2, 'Tüfpli', 'Susanne', '076 819 95 41', '<EMAIL>', 'For selling the good things.', 7), (5, 'Edwards', 'Denise', '86-(137)961-8203', '<EMAIL>', '3D Modeling', 7), (6, 'Boyd', 'David', '86-(326)472-3333', '<EMAIL>', 'Mobile Games', 1), (7, 'Adams', 'Julie', '33-(708)627-8477', '<EMAIL>', 'Zoning', 2), (8, 'Hall', 'Doris', '55-(888)172-3475', '<EMAIL>', 'For Sale By Owner', 3), (9, 'Coleman', 'Christopher', '51-(702)515-9699', '<EMAIL>', 'Twitter Marketing', 4), (10, 'Oliver', 'Deborah', '7-(892)344-5662', '<EMAIL>', 'Offshore Operations', 5); -- -------------------------------------------------------- -- -- Tabellenstruktur für Tabelle `employee` -- CREATE TABLE `employee` ( `id` int(11) NOT NULL, `firstname` varchar(50) COLLATE utf8_bin NOT NULL, `lastname` varchar(50) COLLATE utf8_bin NOT NULL, `department` varchar(50) COLLATE utf8_bin NOT NULL, `salary` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Daten für Tabelle `employee` -- INSERT INTO `employee` (`id`, `firstname`, `lastname`, `department`, `salary`) VALUES (1, 'Friedrich', 'Dörrbohne', 'IT', 30), (2, 'Thomas', 'Dütschler', 'Java', 32), (3, 'Stefan', 'Hugentobler', 'Backend', 20), (4, 'Quantum', 'Terraria', 'TV & Film', 60), (5, 'Quentin', 'Tortelloni', 'Hungry', 25), (6, 'Armin', 'Steiner', 'IT', 37), (7, 'Tobias', 'Justus', 'Cake Factory', 55), (8, 'Fredi', 'Buur', 'Landwirtschaft', 13), (9, 'Sergon', 'Gjschk', 'IT', 22), (10, 'Mihai', 'Petran', 'Landwirtschaft', 15), (11, 'Martin', 'Stäubli', 'Kräuterhaus', 42), (12, 'Ordos', 'Feuermensch', 'Zeitlose Insel', 80), (13, 'Ordos', 'Feuermensch', 'Zeitlose Insel', 80), (14, 'Ordos', 'Feuermensch', 'Zeitlose Insel', 80); -- -------------------------------------------------------- -- -- Tabellenstruktur für Tabelle `project` -- CREATE TABLE `project` ( `id` int(11) NOT NULL, `name` varchar(50) COLLATE utf8_bin NOT NULL, `description` varchar(50) COLLATE utf8_bin NOT NULL, `status` varchar(50) COLLATE utf8_bin NOT NULL, `projecthead_IDFS` int(11) NOT NULL, `volume` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Daten für Tabelle `project` -- INSERT INTO `project` (`id`, `name`, `description`, `status`, `projecthead_IDFS`, `volume`) VALUES (1, 'Backbone', 'IT Backbone', 'Work in Progress', 2, 100), (2, 'PFD', 'The Puzzle Factory Department', 'Running', 1, 0), (3, 'TFB', 'The Farting Beans', 'Working in Progress', 3, 15), (4, 'KVB', 'Kollektiv- und Vorsorgebuchhaltung', 'Running', 3, 100), (5, 'MovieMaker', 'The Original MovieMaker', 'Running on High Priority', 1, 0), (6, 'ADP', 'The absolute done Project', 'done', 1, 0), (7, 'CPF', 'Cherry Pie Factory', 'Running', 5, 0), (8, 'CPE', 'Cherry Pie Eater', 'Eating...', 4, 0); -- -------------------------------------------------------- -- -- Tabellenstruktur für Tabelle `projectemployee` -- CREATE TABLE `projectemployee` ( `employee_idfs` int(11) NOT NULL, `project_idfs` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Daten für Tabelle `projectemployee` -- INSERT INTO `projectemployee` (`employee_idfs`, `project_idfs`) VALUES (1, 2), (1, 2), (1, 4), (4, 5), (4, 5), (3, 3), (2, 3), (4, 3), (9, 3), (1, 8), (6, 8), (7, 8), (3, 8), (8, 8), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (9, 1), (10, 1), (2, 7), (7, 7), (8, 7), (5, 7), (10, 7), (11, 7), (12, 1), (13, 1), (14, 1); -- -------------------------------------------------------- -- -- Tabellenstruktur für Tabelle `projecttask` -- CREATE TABLE `projecttask` ( `task_Id` int(11) NOT NULL, `title` varchar(30) COLLATE utf8_bin NOT NULL, `description` varchar(200) COLLATE utf8_bin NOT NULL, `duration` int(11) NOT NULL, `project_IDFS` int(11) NOT NULL, `employee_IDFS` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Daten für Tabelle `projecttask` -- INSERT INTO `projecttask` (`task_Id`, `title`, `description`, `duration`, `project_IDFS`, `employee_IDFS`) VALUES (1, '<NAME>', '<NAME>', 3, 3, 2), (2, '<NAME>', 'Knocht den Rücken', 20, 1, 1), (3, 'Etwas machen', 'Es sollte etwas getan werden!', 55, 1, 4), (5, 'Schutzbrille kaufen', 'Sonst wird man blind ', 1, 1, 2), (6, 'Farting', 'MORE FARTING!!', 2, 3, 4), (7, 'Hardware erneuern', 'Die alte Hardware muss erneuert werden.', 10, 1, 2), (9, '<NAME>', 'Damit am Morgen niemand verhungert.', 1, 1, 1), (10, 'Beamer ersetzen', 'Den alten Beamer durch einen neuen ersetzen.', 3, 1, 3), (13, 'Postman', 'This task was created using Postman', 2, 3, 1), (14, 'Zutaten kaufen', 'Die Zutaten für den Kuchen kaufen', 2, 7, 8); -- -------------------------------------------------------- -- -- Tabellenstruktur für Tabelle `quicknote` -- CREATE TABLE `quicknote` ( `id` int(11) NOT NULL, `content` varchar(2000) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Daten für Tabelle `quicknote` -- INSERT INTO `quicknote` (`id`, `content`) VALUES (1, 'This note was created using Postman!'), (2, 'Hello I am a cool guy!'); -- -- Indizes der exportierten Tabellen -- -- -- Indizes für die Tabelle `approach` -- ALTER TABLE `approach` ADD PRIMARY KEY (`id`), ADD KEY `employee_IDFS` (`employee_IDFS`), ADD KEY `contactperson_IDFS` (`contactperson_IDFS`); -- -- Indizes für die Tabelle `contact` -- ALTER TABLE `contact` ADD PRIMARY KEY (`id`), ADD KEY `contactperson_IDFS` (`contactperson_IDFS`), ADD KEY `employee_IDFS` (`employee_IDFS`); -- -- Indizes für die Tabelle `contactperson` -- ALTER TABLE `contactperson` ADD PRIMARY KEY (`id`), ADD KEY `project_IDFS` (`project_IDFS`); -- -- Indizes für die Tabelle `employee` -- ALTER TABLE `employee` ADD PRIMARY KEY (`id`); -- -- Indizes für die Tabelle `project` -- ALTER TABLE `project` ADD PRIMARY KEY (`id`), ADD KEY `projecthead_IDFS` (`projecthead_IDFS`); -- -- Indizes für die Tabelle `projectemployee` -- ALTER TABLE `projectemployee` ADD KEY `employee_idfs` (`employee_idfs`), ADD KEY `project_idfs` (`project_idfs`); -- -- Indizes für die Tabelle `projecttask` -- ALTER TABLE `projecttask` ADD PRIMARY KEY (`task_Id`), ADD KEY `project_IDFS` (`project_IDFS`), ADD KEY `employee_IDFS` (`employee_IDFS`); -- -- Indizes für die Tabelle `quicknote` -- ALTER TABLE `quicknote` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT für exportierte Tabellen -- -- -- AUTO_INCREMENT für Tabelle `approach` -- ALTER TABLE `approach` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24; -- -- AUTO_INCREMENT für Tabelle `contact` -- ALTER TABLE `contact` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT für Tabelle `contactperson` -- ALTER TABLE `contactperson` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT für Tabelle `employee` -- ALTER TABLE `employee` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT für Tabelle `project` -- ALTER TABLE `project` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT für Tabelle `projecttask` -- ALTER TABLE `projecttask` MODIFY `task_Id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT für Tabelle `quicknote` -- ALTER TABLE `quicknote` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- Constraints der exportierten Tabellen -- -- -- Constraints der Tabelle `approach` -- ALTER TABLE `approach` ADD CONSTRAINT `approach_ibfk_1` FOREIGN KEY (`employee_IDFS`) REFERENCES `employee` (`id`), ADD CONSTRAINT `approach_ibfk_2` FOREIGN KEY (`contactperson_IDFS`) REFERENCES `contactperson` (`id`); -- -- Constraints der Tabelle `contact` -- ALTER TABLE `contact` ADD CONSTRAINT `contact_ibfk_1` FOREIGN KEY (`contactperson_IDFS`) REFERENCES `contactperson` (`id`), ADD CONSTRAINT `contact_ibfk_2` FOREIGN KEY (`employee_IDFS`) REFERENCES `employee` (`id`); -- -- Constraints der Tabelle `contactperson` -- ALTER TABLE `contactperson` ADD CONSTRAINT `contactperson_ibfk_1` FOREIGN KEY (`project_IDFS`) REFERENCES `project` (`id`); -- -- Constraints der Tabelle `project` -- ALTER TABLE `project` ADD CONSTRAINT `project_ibfk_1` FOREIGN KEY (`projecthead_IDFS`) REFERENCES `employee` (`id`); -- -- Constraints der Tabelle `projectemployee` -- ALTER TABLE `projectemployee` ADD CONSTRAINT `projectemployee_ibfk_1` FOREIGN KEY (`employee_idfs`) REFERENCES `employee` (`id`), ADD CONSTRAINT `projectemployee_ibfk_2` FOREIGN KEY (`project_idfs`) REFERENCES `project` (`id`); -- -- Constraints der Tabelle `projecttask` -- ALTER TABLE `projecttask` ADD CONSTRAINT `projecttask_ibfk_1` FOREIGN KEY (`project_IDFS`) REFERENCES `project` (`id`), ADD CONSTRAINT `projecttask_ibfk_2` FOREIGN KEY (`employee_IDFS`) REFERENCES `employee` (`id`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/PCRM.Database/DataAccess/PcrmDao.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PCRM.Database.Entities; using PCRM.Database.Context; namespace PCRM.Database.DataAccess { public class PcrmDao : IPcrmDao { private PcrmContext _context; public Employee GetEmployee(int id) { using (_context = new PcrmContext()) { return _context.Employees.Find(id); } } } } <file_sep>/README.md # PCRM PCRM with .Net C# <file_sep>/Restful/IPcrmService.cs using Restful.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace Restful { [ServiceContract] public interface IPcrmService { [WebGet(UriTemplate = "employee/{id}")] [OperationContract] RestEmployee GetEmployee(int id); } } <file_sep>/WebClient/Controllers/EmployeeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Restful.Entities; using Restful; namespace WebClient.Controllers { using Helper; public class EmployeeController : Controller { // GET: Employee [HttpGet] public ActionResult Index() { List<RestEmployee> employees = EmployeeRepository.GetAll(); return View(employees); } // GET: Employee/Details/5 [HttpGet] public ActionResult Details(int id) { RestEmployee employee = EmployeeRepository.GetById(id); return View(employee); } // GET: Employee/Create public ActionResult Create() { return View(); } // POST: Employee/Create [HttpPost] public ActionResult Create(FormCollection collection) { try { // TODO: Add insert logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Employee/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: Employee/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Employee/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: Employee/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } } }
8223b7076e0739e25d2f09c3f063eb91349cb953
[ "C#", "Markdown", "SQL" ]
8
C#
frei-sven/PCRM
b40a99a08e5b55a9a82617be1f5075558b788099
06749c7ffb2103493c31ee264e08260beba3215f
refs/heads/master
<repo_name>Tdornak/Class3Homework<file_sep>/src/java/Model/AreaCalculatorService.java package Model; /** * * @author tdornak */ public class AreaCalculatorService { private CalculatorStrategy calculator; public AreaCalculatorService(String name) { if (name.equalsIgnoreCase("rectangle")) { calculator = new RectangleCalculator(); } else if (name.equalsIgnoreCase("triangle")) { calculator = new TriangleCalculator(); } else if (name.equalsIgnoreCase("circle")) { calculator = new CircleCalculator(); } } public String calculateArea(double width, double height) { return calculator.calculateArea(width, height); } } <file_sep>/web/index.jsp <%-- Document : index Created on : Sep 3, 2014, 9:33:25 PM Author : tdornak --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="css/areaCalculator.css" rel="stylesheet" type="text/css"/> <title>Calc JSP</title> </head> <body> <div class="container"> <h2>Rectangle Area Calculator</h2> <form id="rectangleAreaCalculator" name="rectangleAreaCalculator" method="POST" action="Calc"> <p> <label id="rectangleLblWidth" for="rectangleTxtWidth" form="rectangleAreaCalculator">Enter width:</label> <input type="text" name="txtWidth" id="rectangleTxtWidth" value=""><br> </p> <p> <label id="rectangleLblHeight" for="rectangleTxtHeight" form="rectangleAreaCalculator">Enter height:</label> <input type="text" name="txtHeight" id="rectangleTxtHeight" value=""><br> </p> <input type="submit" name="submit" value="Rectangle"> </form> <div class="answer"> <% if (request == null) { } else { Object obj = request.getAttribute("area"); if (obj == null) { out.println("Something has gone horribly wrong"); } else if (request.getAttribute("name").toString().equalsIgnoreCase("rectangle")) { out.println(obj.toString()); } } %> </div> <h2>Triangle Area Calculator</h2> <form id="triangleAreaCalculator" name="triangleAreaCalculator" method="POST" action="Calc"> <p> <label id="triangleLblWidth" for="triangleTxtWidth" form="triangleAreaCalculator">Enter width:</label> <input type="text" name="txtWidth" id="triangleTxtWidth" value=""><br> </p> <p> <label id="triangleLblHeight" for="triangleTxtHeight" form="triangleAreaCalculator">Enter height:</label> <input type="text" name="txtHeight" id="triangleTxtHeight" value=""><br> </p> <input type="submit" name="submit" value="Triangle"> </form> <div class="answer"> <% if (request == null) { } else { Object obj = request.getAttribute("area"); if (obj == null) { out.println("Something has gone horribly wrong"); } else if (request.getAttribute("name").toString().equalsIgnoreCase("triangle")) { out.println(obj.toString()); } } %> </div> <h2>Circle Area Calculator</h2> <form id="circleAreaCalculator" name="circleAreaCalculator" method="POST" action="Calc"> <p> <label id="circleLblRadius" for="circleTxtRadius" form="circleAreaCalculator">Enter radius:</label> <input type="text" name="txtWidth" id="circleTxtRadius" value=""><br> </p> <input type="submit" name="submit" value="Circle"> </form> <div class="answer"> <% if (request == null) { } else { Object obj = request.getAttribute("area"); if (obj == null) { out.println("Something has gone horribly wrong"); } else if (request.getAttribute("name").toString().equalsIgnoreCase("circle")) { out.println(obj.toString()); } } %> </div> </div> </body> </html> <file_sep>/src/java/Model/CalculatorStrategy.java package Model; /** * * @author tdornak */ public interface CalculatorStrategy { public abstract String calculateArea(double width, double height); }
a340604f44924a86f1287df853a0d3c84da114fe
[ "Java", "Java Server Pages" ]
3
Java
Tdornak/Class3Homework
e6eb66451da3036634aa611980ec70f3d4beccd0
a1d1091d9f4d65f286fb0ed645109be86dbcd62f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ArmRest.Models.PublicIpAddress { public class DnsSettings { public string domainNameLabel { get; set; } public string fqdn { get; set; } } public class IpConfiguration { public string id { get; set; } } public class Properties { public string provisioningState { get; set; } public string resourceGuid { get; set; } public string ipAddress { get; set; } public string publicIPAllocationMethod { get; set; } public int idleTimeoutInMinutes { get; set; } public DnsSettings dnsSettings { get; set; } public IpConfiguration ipConfiguration { get; set; } } public class RootObject { public string name { get; set; } public string id { get; set; } public string etag { get; set; } public string type { get; set; } public string location { get; set; } public Properties properties { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Net.Http.Headers; using Newtonsoft.Json; using System.Text; using ArmRest.Models; using ArmRest.Util; namespace ArmRest.Controllers { public class TestAuthController : ApiController { public Subscriptions Get() { try { var subscriptions = ListSubscriptions.GetSubscriptions(); return subscriptions; } catch { return null; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ArmRest.Models.NetworkInterfaceDetails { public class PublicIPAddress { public string id { get; set; } } public class Subnet { public string id { get; set; } } public class Properties2 { public string provisioningState { get; set; } public string privateIPAddress { get; set; } public string privateIPAllocationMethod { get; set; } public PublicIPAddress publicIPAddress { get; set; } public Subnet subnet { get; set; } } public class IpConfiguration { public string name { get; set; } public string id { get; set; } public string etag { get; set; } public Properties2 properties { get; set; } } public class DnsSettings { public List<object> dnsServers { get; set; } public List<object> appliedDnsServers { get; set; } } public class NetworkSecurityGroup { public string id { get; set; } } public class VirtualMachine { public string id { get; set; } } public class Properties { public string provisioningState { get; set; } public string resourceGuid { get; set; } public List<IpConfiguration> ipConfigurations { get; set; } public DnsSettings dnsSettings { get; set; } public bool enableIPForwarding { get; set; } public NetworkSecurityGroup networkSecurityGroup { get; set; } public VirtualMachine virtualMachine { get; set; } } public class RootObject { public string name { get; set; } public string id { get; set; } public string etag { get; set; } public string type { get; set; } public string location { get; set; } public Properties properties { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using ArmRest.Models; using ArmRest.Util; using Newtonsoft.Json; using System.Net; using System.Configuration; namespace ArmRest.Util { public static class ComputeResources { private static string ResourceGroupFilter = ConfigurationManager.AppSettings["Ansible:ResourceGroupNameFilter"]; private static string ResourceGroupCasing = ConfigurationManager.AppSettings["Ansible:ResourceGroupCasing"]; private static string SubscriptionFilter = ConfigurationManager.AppSettings["Ansible:SubscriptionFilter"]; private static string ReturnOnlyPoweredOnVms = ConfigurationManager.AppSettings["Ansible:ReturnRunningVmsOnly"]; private static string HostCasingSetting = ConfigurationManager.AppSettings["Ansible:HostCasing"]; private static string LocationTagName = ConfigurationManager.AppSettings["Ansible:LocationTagName"]; private static string LocationTag = ConfigurationManager.AppSettings["Ansible:LocationTagValue"]; public static bool RemoveStageFromRgName = bool.Parse(ConfigurationManager.AppSettings["Ansible:RemoveStageFromRgName"]); public static Dictionary<String,Object> GetHosts(String accessToken, String subscriptionId = null ) { //get the subs List<String> subList = new List<string>(); if (subscriptionId != null) { subList.Add(subscriptionId); } else { Subscriptions subscriptions = ListSubscriptions.GetSubscriptions(); foreach (var sub in subscriptions.value) { if (sub.id.Contains(SubscriptionFilter)) { subList.Add(sub.subscriptionId); } } } var ansibleHostList = new Dictionary<String, Object>(); var ansibleHostVarsList = new Dictionary<String, Object>(); accessToken = Adal.AccessToken(); string authToken = "Bearer" + " " + accessToken; var client = new WebClient(); client.Headers.Add("Authorization", authToken); client.Headers.Add("Content-Type", "application/json"); foreach (var subId in subList) { Uri resourceGroupsUri = new Uri(String.Format("https://management.azure.com/subscriptions/{0}/resourcegroups?api-version=2015-01-01", subId)); String text = ""; text = client.DownloadString(resourceGroupsUri); ResourceGroups rgList = Newtonsoft.Json.JsonConvert.DeserializeObject<ResourceGroups>(text); List<ResourceGroup> filteredResourceGroups = new List<ResourceGroup>(); foreach (var rg in rgList.value) { if (ResourceGroupFilter == "*") { filteredResourceGroups.Add(rg); } else if (rg.name.ToLower().Contains(ResourceGroupFilter.ToLower())) { filteredResourceGroups.Add(rg); } } foreach (ResourceGroup rg in filteredResourceGroups) { //get each host String rgId = rg.id; String rgName = rg.name; //remove Prod/Test/Dev from rg name if (RemoveStageFromRgName) { if (rgName.ToLower().StartsWith("prod.")) { rgName = rgName.Remove(0, 5); } else if (rgName.ToLower().StartsWith("test.")) { rgName = rgName.Remove(0, 5); } else if (rgName.ToLower().StartsWith("dev.")) { rgName = rgName.Remove(0, 4); } else if (rgName.ToLower().StartsWith("uat.")) { rgName = rgName.Remove(0, 4); } } if (ResourceGroupCasing != "") { if (ResourceGroupCasing.ToLower() == "lowercase") { rgName = rgName.ToLower(); } } String rgComputeUrl = String.Format("https://management.azure.com{0}/providers/Microsoft.Compute/virtualmachines?api-version=2015-05-01-preview", rgId); String rgVmsText = client.DownloadString(rgComputeUrl); ComputeVms rgCompVms = JsonConvert.DeserializeObject<ComputeVms>(rgVmsText); if (rgCompVms.value.Count != 0) { //resource group has vms. Fill the thing List<Object> hostList = new List<Object>(); foreach (var vm in rgCompVms.value) { var tagDict = new Dictionary<String, Object>(); bool VerifyPoweredOnVM = true; if (ReturnOnlyPoweredOnVms.ToLower() == "true") { VerifyPoweredOnVM = GetVmPowerStatus(accessToken, vm); } var simplifiedNic = GetNicDetails(accessToken, vm); vm.simplifiedNicDetails = simplifiedNic; if (HostCasingSetting == "UpperCase") { vm.name = vm.name.ToUpper(); } if (HostCasingSetting == "LowerCase") { vm.name = vm.name.ToLower(); } string vmname = vm.name; if ((vm.tags != null) && (vm.tags.ContainsKey("AnsibleDomainSuffix"))) { vmname = vm.name + "." + vm.tags["AnsibleDomainSuffix"]; } else if ((rg.tags != null) && (rg.tags.ContainsKey("AnsibleDomainSuffix"))) { vmname = vm.name + "." + rg.tags["AnsibleDomainSuffix"]; } String ansibleReturnType = null; if ((vm.tags != null) && (vm.tags.ContainsKey("AnsibleReturn"))) { ansibleReturnType = vm.tags["AnsibleReturn"]; } else if ((rg.tags != null) && (rg.tags.ContainsKey("AnsibleReturn"))) { ansibleReturnType = rg.tags["AnsibleReturn"]; } //add location thing if specified if (LocationTag != "" && LocationTagName != "") { String Location = LocationTag.Replace("%location%", vm.location); tagDict.Add(LocationTagName, Location); } //If ansiblereturn is set, figure out what to return if (ansibleReturnType != null) { if ((ansibleReturnType.ToLower() == "privateipaddress") && (vm.simplifiedNicDetails.InternalIpAddress != null)) { vmname = vm.simplifiedNicDetails.InternalIpAddress; } else if ((ansibleReturnType.ToLower() == "publicipaddress") && (vm.simplifiedNicDetails.PublicIpAddress != null)) { vmname = vm.simplifiedNicDetails.PublicIpAddress; } else if ((ansibleReturnType.ToLower() == "publichostname") && (vm.simplifiedNicDetails.PublicHostName != null)) { vmname = vm.simplifiedNicDetails.PublicHostName; } else if ((ansibleReturnType.ToLower() == "privateipaddress_asansiblehost") && (vm.simplifiedNicDetails.InternalIpAddress != null)) { tagDict.Add("ansible_host", vm.simplifiedNicDetails.InternalIpAddress); } else if ((ansibleReturnType.ToLower() == "publicipaddress_asansiblehost") && (vm.simplifiedNicDetails.PublicIpAddress != null)) { tagDict.Add("ansible_host", vmname = vm.simplifiedNicDetails.PublicIpAddress); } else if ((ansibleReturnType.ToLower() == "publichostname_asansiblehost") && (vm.simplifiedNicDetails.PublicHostName != null)) { tagDict.Add("ansible_host", vmname = vmname = vm.simplifiedNicDetails.PublicHostName); } } //vmname is now either computername, computername+domain, one ip address or public fqdn if (VerifyPoweredOnVM == true) { hostList.Add(vmname); //check if we have hostsvars to add to meta if ((vm.tags != null) && (vm.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")).Count() > 0)) { foreach (var tag in vm.tags.Where(t => t.Key.ToLower().StartsWith("ansible__"))) { tagDict.Add(tag.Key.ToLower().Replace("ansible__", ""), tag.Value); } } } if (tagDict.Count > 0) { //add tags if any ansibleHostVarsList.Add(vmname, tagDict); } } //Add the rg to the main obj var rgValueList = new Dictionary<String, Object>(); rgValueList.Add("hosts", hostList); //add vars to the main object if they exists if ((rg.tags != null) && (rg.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")).Count() > 0)) { var tagDict = new Dictionary<String, Object>(); foreach (var tag in rg.tags.Where(t => t.Key.ToLower().StartsWith("ansible__"))) { tagDict.Add(tag.Key.ToLower().Replace("ansible__", ""), tag.Value); } rgValueList.Add("vars", tagDict); } ansibleHostList.Add(rgName, rgValueList); } } } //Add the _meta thing to the result output var metaDict = new Dictionary<String, Object>(); metaDict.Add("hostvars", ansibleHostVarsList); ansibleHostList.Add("_meta", metaDict); return ansibleHostList; } public static ResourceGroup GetHostResourceGroup(String accessToken, ComputeVm thisVm) { string vmId = thisVm.id; var SplitUrl = vmId.Split('/'); var rgName = SplitUrl[4]; var subscriptionName = SplitUrl[2]; string authToken = "Bearer" + " " + accessToken; var client = new WebClient(); client.Headers.Add("Authorization", authToken); client.Headers.Add("Content-Type", "application/json"); string singleRgUrl = String.Format("https://management.azure.com/subscriptions/{0}/resourcegroups/{1}?api-version=2015-01-01 ", subscriptionName, rgName); String text = ""; text = client.DownloadString(singleRgUrl); ResourceGroup thisRg = Newtonsoft.Json.JsonConvert.DeserializeObject<ResourceGroup>(text); return thisRg; } public static bool GetVmPowerStatus(String accessToken, ComputeVm thisVm) { bool returnResult = false; string vmId = thisVm.id; var SplitUrl = vmId.Split('/'); var rgName = SplitUrl[4]; var subscriptionName = SplitUrl[2]; string authToken = "Bearer" + " " + accessToken; var client = new WebClient(); client.Headers.Add("Authorization", authToken); client.Headers.Add("Content-Type", "application/json"); string vmStatusUrl = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}?$expand=instanceView&api-version=2015-06-15", subscriptionName, rgName, thisVm.name); String text = ""; text = client.DownloadString(vmStatusUrl); var vmStatus = Newtonsoft.Json.JsonConvert.DeserializeObject<ComputeVm>(text); var InstanceView = vmStatus.properties.instanceView.statuses; var ThisInstanceviewPowerState = InstanceView.Where(p => p.code.Contains("PowerState")).FirstOrDefault(); var ThisInstanceviewProvisioningState = InstanceView.Where(p => p.code.Contains("ProvisioningState")).FirstOrDefault(); try { if ((ThisInstanceviewPowerState.code == "PowerState/running") && (ThisInstanceviewProvisioningState.code == "ProvisioningState/succeeded")) { returnResult = true; } System.Diagnostics.Debug.WriteLine(string.Format("VM {0} in RG {1} has power state {2}", thisVm.name, rgName, ThisInstanceviewPowerState.code)); } catch (Exception e) { returnResult = false; } return returnResult; } public static SimplifiedNic GetNicDetails(String accessToken, ComputeVm Vm) { string authToken = "Bearer" + " " + accessToken; var client = new WebClient(); client.Headers.Add("Authorization", authToken); client.Headers.Add("Content-Type", "application/json"); var nic = Vm.properties.networkProfile.networkInterfaces.FirstOrDefault(); string nicLink = nic.id; String nicUrl = String.Format("https://management.azure.com{0}{1}", nicLink, "?api-version=2015-05-01-preview"); String nicText = client.DownloadString(nicUrl); //ComputeVms rgCompVms = JsonConvert.DeserializeObject<ComputeVms>(rgVmsText); ArmRest.Models.NetworkInterfaceDetails.RootObject nicObj = JsonConvert.DeserializeObject<ArmRest.Models.NetworkInterfaceDetails.RootObject>(nicText); String InternalIpAddress = nicObj.properties.ipConfigurations.FirstOrDefault().properties.privateIPAddress; ArmRest.Models.PublicIpAddress.RootObject publicIpAddressObj = new Models.PublicIpAddress.RootObject(); if (nicObj.properties.ipConfigurations.FirstOrDefault().properties.publicIPAddress != null) { String PublicIpLink = nicObj.properties.ipConfigurations.FirstOrDefault().properties.publicIPAddress.id; String publicIpUrl = String.Format("https://management.azure.com{0}{1}", PublicIpLink, "?api-version=2015-05-01-preview"); String publicIpText = client.DownloadString(publicIpUrl); publicIpAddressObj = JsonConvert.DeserializeObject<ArmRest.Models.PublicIpAddress.RootObject>(publicIpText); } SimplifiedNic thisSimplifiedNic = new SimplifiedNic(); thisSimplifiedNic.InternalIpAddress = InternalIpAddress; String PublicIpAddress = null; if (publicIpAddressObj != null) { try { PublicIpAddress = publicIpAddressObj.properties.ipAddress; thisSimplifiedNic.PublicIpAddress = PublicIpAddress; } catch { } try { thisSimplifiedNic.PublicHostName = publicIpAddressObj.properties.dnsSettings.fqdn; } catch { } } return thisSimplifiedNic; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ArmRest.Models { public class HardwareProfile { public string vmSize { get; set; } } public class ImageReference { public string publisher { get; set; } public string offer { get; set; } public string sku { get; set; } public string version { get; set; } } public class Vhd { public string uri { get; set; } } public class OsDisk { public string osType { get; set; } public string name { get; set; } public string createOption { get; set; } public Vhd vhd { get; set; } public string caching { get; set; } } public class StorageProfile { public ImageReference imageReference { get; set; } public OsDisk osDisk { get; set; } public List<object> dataDisks { get; set; } } public class WindowsConfiguration { public bool provisionVMAgent { get; set; } public bool enableAutomaticUpdates { get; set; } } public class OsProfile { public string computerName { get; set; } public string adminUsername { get; set; } public WindowsConfiguration windowsConfiguration { get; set; } public List<object> secrets { get; set; } } public class NicProperties2 { } public class NetworkInterface { public string id { get; set; } public NicProperties2 properties { get; set; } } public class NetworkProfile { public List<NetworkInterface> networkInterfaces { get; set; } } public class Properties { public HardwareProfile hardwareProfile { get; set; } public StorageProfile storageProfile { get; set; } public OsProfile osProfile { get; set; } public NetworkProfile networkProfile { get; set; } public string provisioningState { get; set; } public InstanceView instanceView { get; set; } } public class InstanceView { public List<InstanceViewStatus> statuses { get; set; } } public class InstanceViewStatus { public string code { get; set; } public string level { get; set; } public string displayStatus { get; set; } public string time { get; set; } } public class Resource { public string id { get; set; } } public class ComputeVm { public Properties properties { get; set; } public List<Resource> resources { get; set; } public string id { get; set; } public string name { get; set; } public string type { get; set; } public string location { get; set; } public Dictionary<String, String> tags { get; set; } = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); public SimplifiedNic simplifiedNicDetails { get; set; } } public class ComputeVms { public List<ComputeVm> value { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Net.Http.Headers; using Newtonsoft.Json; using System.Text; using System.Configuration; using ArmRest.Util; using ArmRest.Models; using System.Dynamic; using ClaySharp; namespace ArmRest.Controllers { public class ListHostsController : ApiController { private static string ResourceGroupFilter = ConfigurationManager.AppSettings["Ansible:ResourceGroupNameFilter"]; private static string SubscriptionFilter = ConfigurationManager.AppSettings["Ansible:SubscriptionFilter"]; public HttpResponseMessage Get(String subscriptionId = null, bool UseExternalIpAddress = false) { String accessToken = Adal.AccessToken(); var ansibleHosts = ComputeResources.GetHosts(accessToken); String json = JsonConvert.SerializeObject(ansibleHosts); System.Diagnostics.Debug.WriteLine(json); var response = this.Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(json, Encoding.UTF8, "application/json"); return response; } } } <file_sep>#!/usr/bin/env python import requests import sys, getopt from ansible.constants import p, get_config from ansible import utils operation = str(sys.argv[1]) #if running multiple armrest instances, use this to separate them #for instance, if armrest_instance is set to "prod", the corresponding configuration section in ansible.cfg should be "armrest_prod" armrest_instance = "" if armrest_instance != "": armrest_config = "armrest_" + armrest_instance else: armrest_config = "armrest" armrest_uri = get_config(p, armrest_config, "armrest_uri", "ARMREST_URI","") #print(armrest_uri) armrest_use_cache = get_config(p, armrest_config, "armrest_use_cache", "ARMREST_USE_CACHE","") armrest_cache_lifetime_seconds = get_config(p, armrest_config, "armrest_cache_lifetime_seconds", "ARMREST_CACHE_LIFETIME_SECONDS","") if (armrest_use_cache == True): import requests_cache requests.cache.install_cache('armrest_cache', backend='sqlite', expire_after=armrest_cache_lifetime_seconds) if (operation == '--list'): armrest_list_uri = armrest_uri + "/api/listhosts" r = requests.get(armrest_list_uri) print(r.text) if (operation == '--host'): armrest_host = str(sys.argv[2]) armrest_host_uri = armrest_uri + "/api/getsinglehost?hostname=" + armrest_host r = requests.get(armrest_host_uri) print(r.text)<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ArmRest.Models { public class SimplifiedNic { public string InternalIpAddress { get; set; } public string PublicIpAddress { get; set; } public string PublicHostName { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Configuration; using Newtonsoft.Json; using ArmRest.Util; using ArmRest.Models; using System.Text; namespace ArmRest.Controllers { public class GetSingleHostController : ApiController { private static string SubscriptionFilter = ConfigurationManager.AppSettings["Ansible:SubscriptionFilter"]; public HttpResponseMessage Get(String hostName) { List<String> subList = new List<string>(); Subscriptions subscriptions = ListSubscriptions.GetSubscriptions(); foreach (var sub in subscriptions.value) { if (sub.id.Contains(SubscriptionFilter)) { subList.Add(sub.subscriptionId); } } String accessToken = ""; accessToken = Adal.AccessToken(); string authToken = "Bearer" + " " + accessToken; var client = new WebClient(); client.Headers.Add("Authorization", authToken); client.Headers.Add("Content-Type", "application/json"); ComputeVms masterComputeVmsList = new ComputeVms(); masterComputeVmsList.value = new List<ComputeVm>(); foreach (var subId in subList) { Uri resourceGroupsUri = new Uri(String.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Compute/virtualmachines?api-version=2015-05-01-preview", subId)); String text = ""; text = client.DownloadString(resourceGroupsUri); ComputeVms computeVmsList = JsonConvert.DeserializeObject<ComputeVms>(text); foreach (var vm in computeVmsList.value) { masterComputeVmsList.value.Add(vm); } } foreach (var vm in masterComputeVmsList.value) { ResourceGroup thisRg = ComputeResources.GetHostResourceGroup(accessToken, vm); if ((vm.tags != null) && (vm.tags.ContainsKey("AnsibleDomainSuffix"))) { vm.name = vm.name + "." + vm.tags["AnsibleDomainSuffix"]; } else if ((thisRg.tags != null) && (thisRg.tags.ContainsKey("AnsibleDomainSuffix"))) { vm.name = vm.name + "." + thisRg.tags["AnsibleDomainSuffix"]; } } ComputeVm thisComputeVm = masterComputeVmsList.value.Where(t => t.name.ToLower() == hostName.ToLower()).FirstOrDefault(); if (thisComputeVm == null) { var response = this.Request.CreateResponse(HttpStatusCode.NotFound); return response; } else { Dictionary<String, String> TagsDict = new Dictionary<String, String>(); if (thisComputeVm.tags != null) { foreach (var tag in thisComputeVm.tags.Where(t => t.Key.ToLower().StartsWith("ansible__"))) { TagsDict.Add((tag.Key.ToLower().Replace("ansible__", "")), tag.Value); } } String json = JsonConvert.SerializeObject(TagsDict); var response = this.Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(json, Encoding.UTF8, "application/json"); return response; } } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using ArmRest.Models; namespace ArmRest.Util { public class ListSubscriptions { public static Subscriptions GetSubscriptions() { String accessToken = ""; Uri Url = new Uri("https://management.azure.com/subscriptions?&api-version=2015-01-01"); String text = ""; try { accessToken = Adal.AccessToken(); string authToken = "Bearer" + " " + accessToken; //HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url); //httpWebRequest.Headers.Add("Authorization", authToken); //var response = httpWebRequest.GetResponse(); var client = new WebClient(); client.Headers.Add("Authorization", authToken); client.Headers.Add("Content-Type", "application/json"); text = client.DownloadString(Url); var subscriptions = JsonConvert.DeserializeObject<Subscriptions>(text); return subscriptions; } catch { return null; } } } }<file_sep>* Forked from https://github.com/trondhindenes/armrest ## Armrest ### Short description Ansible Dynamic Inventory for Azure Resource Manager. This code is very non-optimized, and can be made more efficient by reducing auth calls to azure. Which I haven't gotten around to just yet. ### Description and setup: http://hindenes.com/trondsworking/2015/08/11/using-azure-resource-manager-as-an-ansible-inventory-source/ ### Tags #### Supported tags (either on vm or resource group): * ansible__*: the prefix will be removed, and the rest of the tag will be stamped as hostvars * AnsibleReturn: controls whether hostname, ip address etc will be returned. Allowed values are: privateipaddress publicipaddress publichostname privateipaddress_asansiblehost publicipaddress_asansiblehost publichostname_asansiblehost The _asansiblehost will retain the "real" hostname and instead use the "ansible_host" hostvar in order to allow Ansible to connect to the correct host. * AnsibleDomainSuffix: If publichostname/publichostname_asansiblehost is used, this value contains the domain suffix to be appended to the host name #### Other config options See also web.config for a list of configurable values there.<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using Microsoft.IdentityModel.Clients.ActiveDirectory; using System.Globalization; namespace ArmRest.Util { public class Adal { private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"]; private static string authorityUri = ConfigurationManager.AppSettings["ida:authorityUri"]; private static string resourceUri = ConfigurationManager.AppSettings["ida:resourceUri"]; private static string clientID = ConfigurationManager.AppSettings["ida:clientID"]; private static string clientSecret = ConfigurationManager.AppSettings["ida:clientSecret"]; private static string redirectUri = ConfigurationManager.AppSettings["ida:redirectUri"]; private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; private static string Result = ""; static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); public static String AccessToken(bool forceReauth = false) { //TokenCache TC = new TokenCache(); //AuthenticationContext authContext = new AuthenticationContext(authority); //ClientCredential clientCredential = new ClientCredential(clientID, clientSecret); //ClientAssertion clientAss = new ClientAssertion(clientID, clientSecret); ////string token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken.ToString(); ////string result = authContext.AcquireToken(resourceUri, clientCredential).AccessToken.ToString(); //string result = authContext.AcquireToken(resourceUri, clientAss).AccessToken.ToString(); if ((Result == "") || (forceReauth = true)) { //UserCredential uc = new UserCredential(username, password); var cred = new ClientCredential(clientID, clientSecret); AuthenticationContext authContext = new AuthenticationContext(authority); Result = authContext.AcquireToken(resourceUri, cred).AccessToken.ToString(); System.Diagnostics.Debug.WriteLine("Bearer " + Result); } //public AuthenticationResult AcquireToken(string resource, string clientId, UserCredential userCredential); return Result; } } }<file_sep>@using ArmRest.Areas.HelpPage.ModelDescriptions @model SimpleTypeModelDescription @Model.Documentation<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ArmRest.Models { public class ResourceGroup { public string id { get; set; } public string name { get; set; } public string location { get; set; } public ResourceGroupProperties properties { get; set; } public Dictionary<String, String> tags { get; set; } = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); } public class ResourceGroupProperties { public string provisioningState { get; set; } } public class ResourceGroups { public List<ResourceGroup> value { get; set; } } }<file_sep><%@ Application Codebehind="Global.asax.cs" Inherits="ArmRest.WebApiApplication" Language="C#" %>
08568d918ad0c4dae54099f687770cdfa3030a3f
[ "HTML+Razor", "C#", "Markdown", "ASP.NET", "Python" ]
15
HTML+Razor
trondhindenes/armrest
f000e062fe912d9b874ac1f0a451512196e2afc8
52cadd3566318e9b2ffbe92a547109482ed54250
refs/heads/master
<repo_name>tiepdotme/netzaffe.de<file_sep>/_drafts/jekyll-deployment-auf-uberspace.md --- title: Jekyll Deployment auf Uberspace via Bare Repo und post-receive Hook tags: - Jekyll - howto - "#!/bin/bash" - uberspace - git - snippet layout: post toc: true permalink: /jekyll-deployment-auf-uberspace-via-bare-repo-und-post-receive-hook/ --- Deployment einer [Jekyll-Site](/tags/jekyll) auf [Uberspace](https://uberspace.de) via *Git Bare Repository*[^2] und *post-receive Hook*[^1]. Zielstellung ist, dass ein `git push` auf das *uberspace Remote Repository*[^3] das weiter unten beschriebene Skript triggert, welches aus deinem Jekyll Repository mit all seinen Änderungen (wie z.B. Markdown, Config-, Layout- und Include-Änderungen und Gemfile[^4]) eine Website generiert und dann der Welt auf dem *Webserver*[^5] deiner Uberspace 6 Umgebung verfügbar macht.<!--break--> ## Vorbereitungen auf uberspace Wir starten nach erfolgreichem SSH-Login auf unserem Uberspace-Host in unserem Home-Verzeichnis und legen Ordner für unser Repos und tmp an, ``` mkdir -p repos/tmp ``` dann erstellen wir eine Ordner für unsere Repos, ``` cd repos ``` erstellen den Ordner für das Repo auf das wir später *pushen* wollen (Ab hier solltet ihr das exemplarische *netzaffe.de* durch eure Domain ersetzen.) ``` mkdir netzaffe.de.git ``` und wechseln hinein. ``` cd netzaffe.de.git ``` Jetzt initialisieren wir den Ordner als *Bare Repo*[^2], ``` git init --bare ``` wechseln in das Verzeichnis *hooks*. ``` cd hooks ``` Dann fügen das [Skript](https://gist.github.com/fl3a/032fadb155a75adac03c85cf204051f6) als *post-receive Hook*[^1] hinzu, hier passiert später die ganze Magie. ``` curl -O post-receive https://gist.githubusercontent.com/fl3a/032fadb155a75adac03c85cf204051f6/raw/b49e91fd1158faca3e73274fc5e84a2115d4863b/uberspace-jekyll.sh ``` Last but not least, muss das Skript noch ausführbar gemacht werden: ``` chmod +x post-receive ``` ## Das post-receive Skript Wenn komplette Prozess der Übertragung (Push) abgeschlossen ist, greift der sogenannte *post-receive Hook*[^1] und führt das gleichnamige Skript (sofern vorhanden) aus. Das [uberspace-jekyll-deployment.sh](https://gist.github.com/fl3a/032fadb155a75adac03c85cf204051f6) Skript welches wir als *post-receive Hook*[^1] nutzen findest du auch als Gist auf github. ``` #!/bin/bash # # Deployment of Jekyll-Sites on Uberspace # via Git Bare Repository and post-receive Hook # # See https://netzaffe.de/jekyll-deployment-auf-uberspace-via-bare-repo-und-post-receive-hook/ # for requirement and more detailed description (german) read oldrev newrev ref pushed_branch=${ref#refs/heads/} ## Variables build_branch='master' site='netzaffe.de' site_prefix='sandbox.' git_repo=${HOME}/repos/${site}.git tmp=${HOME}/repos/tmp/${site} www=/var/www/virtual/${USER}/${site_prefix}${site} ## Do the magic [ $pushed_branch != $build_branch ] && exit git clone ${git_repo} ${tmp} cd ${tmp} bundle install --path=~/.gem JEKYLL_ENV=production jekyll build --source ${tmp} --destination ${www} rm -rf ${tmp} exit ``` ### Anpassungen Im Skript sind nur 3 Variablen anzupassen (sofern alles wie oben beschrieben umgesetzt wurde ;-D). 1. `build_branch`, **der** Branch der für das Deployment genutzt werden soll. Andere Zweige werden ignoriert. Hier `master`. 2. `site` die Site bwz. die Domain. Hier `netzaffe.de` 3. `site_prefix`, Optionaler Prefix bzw. Subdomain, der der Variablen site vorangestellt wird. Hier `sandbox.`. ### Beschreibung des Skipts Die anderen Variablen werden aus den oben angepassten und/oder Umgebungsvariablen[^6] zusammengesetzt. * `git_repo`, Pfad, wo die Bare-Repo[^2] liegt, es fließt die Umgebungsvariable[^5] *HOME* und die Variable *site* mit ein. * `tmp`, hier wird unser Bare-Repo[^2] temporär *hin-ge-clon-ed*, um als Quelle für die Generierung des statischen HTML für die Site zu dienen. Es fließen die Umgebungsvariablei[^6] *HOME* und die Variable *site* mit ein. * `www`, das Verzeichnis, das letztendlich vom Webserver ausgeliefert wird. Es fließen die Umgebungsvariable[^6]] *USER* sowie *site_prefix* und *site* ein. Das *Do the magic* 1. Überprüfung ob der übertragene- (pushed) und Build-Branch übereinstimmen, ansonsten Abruch. 2. Klonen des Bare-Repos[^2] nach *tmp* 2. Verzeichniswechsel nach *tmp* 3. Installation der im Gemfile spezifizierten Abhängigkeiten via `bundle install`[^4] 4. Generierung der HTML von *tmp* nach *www* via `jekyll build` 5. Löschen von *tmp* 6. Beendigung des Skripts ## Vorbereitungen im lokalen Git-Repository Das waren die Schrite auf deinem Uberspace, weiter gehts in deinen Repo. Das oben erstellte Bare-Repository fügst du deinem Repo als sog. Remote-Repository[^3] Namens *uberspace* hinzu: ``` git remote add uberspace <EMAIL>:repos/netzaffe.de.git ``` Fertig, jetzt noch der push vom *master* nach *uberspace*. ``` git push uberspace master ``` Nach der Übertragung der Daten solltest du die Ausgaben von `bundle install` und `jekyll build` sehen. Dieses Howto bezieht sich auf Uberspace 6, für Anmerkungen, Ideen und Feedback (nicht nur zu Uberspace 7) würde ich mich freuen! ## Credits Dieser Artikel basiert im wesentlichen auf [Jekyll Auf Uberspace Mit Git](https://www.wittberger.net/post/jekyll-auf-uberspace-mit-git/) und [Jekyll Auf Uberspace](https://lc3dyr.de/blog/2012/07/22/Jekyll-auf-Uberspace/). Danke! Der Artikel ist eine Essenz, die sich nur auf das Deployment bezieht. Zudem ist er aktualisiert (seit 2012, 2013 hat sich einiges in Jekyll und auf Uberspace etc getan) und das Skript hat noch etwas Liebe erfahren. --- [^1]: [Git auf einen Server bekommen](https://git-scm.com/book/de/v1/Git-auf-dem-Server-Git-auf-einen-Server-bekommen), [What is a bare git repository?](http://www.saintsjd.com/2011/01/what-is-a-bare-git-repository/) [^2]: [What are Git hooks?](https://githooks.com/), [Git individuell einrichten - Git Hooks](https://git-scm.com/book/de/v1/Git-individuell-einrichten-Git-Hooks) [^3]: [Git Grundlagen - Mit externen Repositorys arbeiten](https://git-scm.com/book/de/v1/Git-Grundlagen-Mit-externen-Repositorys-arbeite), [man git-remote](https://git-scm.com/docs/git-remote) [^4]: [Gems, Gemfiles and the Bundler](https://learn.cloudcannon.com/jekyll/gemfiles-and-the-bundler/) [^5]: [Uberspace Wiki: Webserver](https://wiki.uberspace.de/webserver) [^6]: [Linux/UNIX Umgebungsvariablen](https://linuxwiki.de/UmgebungsVariable) <file_sep>/_posts/2006-12-22-lpic-2-2-tage-vor-weihnachten.md --- tags: - Zertifikat - Weihnachten - LPIC - Linux nid: 340 layout: post title: LPIC 2 - 2 Tage vor Weihnachten created: 1166812247 --- <img src="http://netzaffe.de/assets/imgs/lpi-lpic2-123x150.gif" alt="LPIC 2" align="left" vspace="10" hspace="10" /> Das Lernen hat sich gelohnt, heute, 2 Tage vor Weihnachten, habe ich die Prüfung zur LPIC2 bestanden. <p> Danach habe ich auf den letzten Drücker und nicht ganz uneigennützig ein Weihnachtsgeschenk für meinen Papa besorgt,<br /> eine Flasche guten Scotch-Whisky von <a href="http://www.cadenheads.de">Cadenheads in Sülz auf der Luxenburger</a>.</p> <p> Jetzt kann die besinnliche Zeit kommen!</p> <!--break--> <file_sep>/_posts/2010-05-12-scrum-aus-der-praxis-drupaldevdays-2010.md --- tags: - Session - Scrum - Projektmanagement - München - DrupalDevDays - Drupalcamp - Drupal nid: 991 layout: post title: Scrum aus der Praxis @ DrupalDevDays 2010 created: 1273659038 --- <img src="/assets/imgs/2010-drupaldevdays-munich-luckow-fl3a-scrum-presentation.jpg" alt="@luckow and @fl3a, Scrum aus der Praxis, DrupalDevDays 2010, Munich" /> <small>Foto: beta.robot, by-nc-sa, <a href="http://www.flickr.com/photos/beta-robot/4591718950/">http://www.flickr.com/photos/beta-robot/4591718950/</a></small> <p> <NAME>, <a href="http://twitter.com/luckow">@luckow</a> und ich während der Session "<a href="http://www.drupal-dev-days.de/de/sessions/scrum-erste-schritte">Scrum aus der Praxis</a>" auf den <a href="http://www.drupal-dev-days.de" title="DrupalDevDays">DrupalDevDays</a>, Mai 2010 in München. </p> Zu den Slides: https://www.slideshare.net/fl3a/scrum-aus-der-praxis-drupaldevdays-2010 <!--break--> <file_sep>/_drafts/von-jekyll-nach-drupal.md --- title: "s/Drupal/Jekyll" tags: - Drupal - Jekyll, - SSG - netzaffe layout: post --- tl;dr Ich bin vom Drupal CMS Framework[^drupal] auf den Jekyll[^jekyll] SSG umgestiegen. Darum habe ich das getan und das hat mich an Jekyll überzeugt. Ich betreibe dieses Blog, oder genauer gesagt, das Stück Software aus dem dieses Blog hervorgegangen ist seit 15 Jahren. Das waren 15 Jahre mit Drupal, gestartet mit der Version 4.5, das hier war auch immer meine Spielwiese um z.B. neue Drupal-Module auzuprobieren. 2009 habe ich das Update auf Drupal 6 gemacht, seit dem Erscheinen von Drupal 8, nutze ich den Drupal 6 LTS aus der Community (es werden laut Drupal Policy immer nur 2 Versionen unterstützt, ergo zu diesen Zeitpunkt Drupal in der Version 7 und v.8.). Am Ende ist und bleibt es trotz Versorgung mit Updates ein 10 Jahre altes Stück Software mit einer altertümlichen Anmutung, weit vor der *Ära Mobile* und sicherlich auch mit dem ein oder anderen Rudimenten in der Datenbank verursacht durch diverse Module, die diese Installation in diesen Jahren erlebt hat. Da ein Update unabwendbar war, habe ich teils mit dafür gesorgt, daß die von mir benötigten Module auch für Drupal 8 zur Verfügung stehen, z.B. den Drupal Modulen Footnotes[^fn], GeshiFilter[^geshi] oder Gist Input Filter[^gist]. Unabhängig davon, daß die Migrationen bei mir nicht auf korrekt durchliefen, hat sich für mich Drupal 8 als zu groß und sperrig angefühlt. Schon recht lange stand der SSG Jekyll in meinem Backlog (<NAME> für die Inspiration!), im Winter 2018 bin ich dann mal dazu gekommen, Jekyll zu installieren und bin das Step by Step Tutorial[^sbst] durchgegangen. Aber was hat mich an Jekyll so begeistert?<!--break--> - Drupal 6 Importer - KISS - Einfacher Start - Einfache Struktur - Textdateien - Markdown[^md] [^kramdown] - Liquid Template Engine[^liquid] - Geschwindigkeit - Plain HTML - Keine Sicherheits-Updates mehr Beim 2. Drupalgeddon 2[^sa], das hatte ein Risiko-Level[^risk] von 24 bei einer Skala bis 25, kam ich mit meiner handvoll Drupal Sites doch etwas ins Schwitzen. - Nerdy Arbeitsweise - Git - Ein neues Spielzeug ## Fußnoten & Weiterführendes *[CMS]: Content Management System *[SSG]: Static Site Generator [^drupal]: [Drupal CMS](https://drupal.org) [^jekyll]: [Jekyll](https://jekyllrb.com) [^hacks]: Modifiertes Drush, MydropWizzard Modul und Updates über github statt d.o[^do] [^fn]: [footnotes 8.x port](https://www.drupal.org/sandbox/fl3a/2593257) [^sbst]: [Jekyll Step by Step Tutorial](https://jekyllrb.com/docs/step-by-step/01-setup/) [^geshi]: [GeSHi Filter for syntax highlighting](https://www.drupal.org/project/geshifilter) [^gist]: [Gist Input Filter (gist_filter) 8.x Port](https://www.drupal.org/sandbox/fl3a/2819998) [^md]: [Markdown Syntax](https://daringfireball.net/projects/markdown/syntax) [^sa]: [Drupal core - Highly critical - Remote Code Execution - SA-CORE-2018-002](https://www.drupal.org/SA-CORE-2018-002) [^kramdown]: [Kramdown Syntax](https://kramdown.gettalong.org/syntax.html) [^liquid]: [Liquid template language](https://shopify.github.io/liquid/) *[CMS]: Content Management System *[SSG]: Statischer Seiten Generator *[do]: drupal.org *[LTS]: Long Term Support <file_sep>/_posts/2009-05-19-du-bist-terrorist.md --- tags: - Überwachung - Netzkultur - Internet - Datenintegrität nid: 843 layout: post title: Du bist Terrorist created: 1242731373 --- <object width="510" height="287"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=4631958&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00ADEF&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=4631958&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00ADEF&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="500" height="281"></embed></object> <blockquote> Gemeinsam für ein sicheres Deutschland.<br /> Die Kampagne „Du bist Deutschland“ war 2005 der Beginn einer positiven Stimmungswelle im ganzen Land. Diese gebündelte Energie hat sich 2009 umgekehrt, denn nun bist du potenzieller Terrorist und wirst überwacht. <br /> <br /> <a href="http://www.DubistTerrorist.de">www.DubistTerrorist.de</a></p> </blockquote> via <a href="http://netzpolitik.org">netzpolitik.org</a> <!--break--> <file_sep>/florian-latzel.md --- layout: page title: <NAME> toc: true permalink: /florian-latzel image: /assets/imgs/florian-latzel-reinblau-teamtreffen-2017-05-19-rkr.jpg last_modified_at: 2019-04-04 --- ## Über mich ### Vorstellung in kurz & knapp <figure role="group"> <img src="/assets/imgs/florian-latzel-reinblau-teamtreffen-2017-05-19-rkr.jpg" alt="<NAME>, Reinblau Teamtreffen, Mai 2017" /> <figcaption><NAME>, Reinblau Teamtreffen, Mai 2017, &copy; <NAME></figcaption> </figure> Hallo, ich heiße <NAME>. - Jahrgang 1978, in Köln geboren - lebt und arbeitet im wunderschönen [Köln-Mülheim](/tags/muellem/index.html) - macht was mit Menschen, die was mit Computern machen - Staatl. gepr. Informatiker FR Softwaretechnologie mit ein paar [Zertifikaten](/tags/zertifikat/index.html) - seit 2006 freiberuflicher IT-Berater, seit 2018 [Scrum Master](/tags/scrum-master/index.html) bei REWE digital - mag Rheinblick, [Reinblau](/tags/reinblau/index.html), gute Ideen, [Fahrräder](/tags/fahrrad/index.html) und ist gerne [draußen](/tags/draussen/index.html). - glaubt an [Open Source](/tags/open-source/index.html) und Karma und [Agile Softwareentwicklung](/tags/agile/index.html) Hier hier erfährst Du vielleicht noch mehr über mich. ### Sonstwo im Interweb Hier findest du mich auch noch: - [~~facebook~~](/node/1630) - [twitter](http://twitter.com/fl3a) - [soundcloud](http://soundcloud.com/florian-latzel/favorites) - [drupal.org](http://drupal.org/user/51103) - [github](https://github.com/fl3a) - [xing](http://www.xing.com/profile/Florian_Latzel) - [slideshare](http://de.slideshare.net/fl3a) - [linkedin](https://de.linkedin.com/in/florianlatzel/en) Sag gerne hallo via EMail, noch lieber via [PGP/GnuPG verschlüsselter EMail](/gnupg-micro-howto.html), [hier](https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x768146CD269B69D1) ist mein [GnuPG-Key](/gnupg-micro-howto.html). ### Beruflich & Privat Ich versuche Berufliches und Privates so gut es geht zu trennen. Bitte hilf mir dabei! Wenn Du ein Anliegen also beruflicher Natur hast, dann besuche doch bitte [is-loesungen.de](https://is-loesungen.de) dort erfährst Du auch etwas mehr über meine Dienstleistungen, Einsatzgebiete, bisherigen Projekte Benutze bitte die dortigen Kontaktmöglichkeiten! Wir sollten dann Dein Anliegen bei einer Tasse Kaffee besprechen. ## Über diese Seite Das ist mein privates Blog, manchmal schreibe ich hier was über [Themen](/themen.html). ### Lizenz Die Inhalte dieser Seite, soweit nicht anders angegeben, sind unter der Creative Commons &mdash; Namensnennung - Weitergabe unter gleichen Bedingungen 4.0 International [(CC BY-SA 4.0)](https://creativecommons.org/licenses/by-sa/4.0/deed.de) lizensiert. Du darfst: - **Teilen** — das Material in jedwedem Format oder Medium vervielfältigen und weiterverbreiten - **Bearbeiten** — das Material remixen, verändern und darauf aufbauen und zwar für beliebige Zwecke, sogar kommerziell. Der Lizenzgeber kann diese Freiheiten nicht widerrufen solange Du dich an die Lizenzbedingungen hälst. Unter folgenden Bedingungen: - **Namensnennung** — Du musst angemessene Urheber- und Rechteangaben machen, einen Link zur Lizenz beifügen und angeben, ob Änderungen vorgenommen wurden. Diese Angaben dürfen in jeder angemessenen Art und Weise gemacht werden, allerdings nicht so, dass der Eindruck entsteht, der Lizenzgeber unterstüt gerade dich oder deine Nutzung besonders. - **Weitergabe unter gleichen Bedingungen** — Wenn du das Material remixt, veränderst oder anderweitig direkt darauf aufbaust, darfst du deine Beiträge nur unter derselben Lizenz wie das Original verbreiten. <file_sep>/_posts/2016-10-29-agile-scrum-lean-und-kanban-events-in-koeln-bonn-duesseldorf-und-umgebung.md --- title: Agile, Scrum, Lean und Kanban Events in Köln, Bonn, Düsseldorf und Umgebung tags: - Scrum - Meetup - Köln - Kanban - Düsseldorf - Bonn - Agile - Aachen - Community - Scrumtisch Köln nid: 1642 permalink: "/agile-scrum-lean-kanban-events-koeln-bonn-duesseldorf-umgebung.html" created: 1477757270 layout: post last_modified_at: 2019-04-09 --- Was für regelmäßigen Meetups zu Agile Themen wie Scrum, KANBAN, eXtreme Programming, Lean und Arbeit auf Augenhöhe gibt in Köln und Umgebung? Welche (Un)Konferenzen finden in NRW statt? Wo kann ich mich über Agiles Projektmanagement austauschen oder einfach nur Gleichgesinnte treffen und wo ist die nächste Selbsthilfegruppe der Anonymen Agilisten[^anon-agile]? Ich habe mal eine Liste von Scrumtischen, Agile- und KANBAN- und Artverwandten-Meetups und Konferenzen in der Region zusammengetragen. Hier findest Du Termine, wo die Agile Community in Köln, Bonn, Düsseldorf, Aachen und dem Ruhrgebiet zusammenkommt. Für manche Treffen ist eine Anmeldung über xing oder meetup Vorraussetzung, dass heisst ein Benutzerkonto dort ist obligatorisch. **Agile Community Köln** - [Scrumtisch Köln](https://www.xing.com/net/scrumtischkoeln), jeden dritten Mittwoch im Monat, Anmeldung über xing - [Lean Coffee Cologne](http://leancoffee.cologne), wöchendlich, unter anderem auch für Gründer und Product Owner, mehr auf [leancoffee.cologne](http://leancoffee.cologne/) - [Limited <acronym title="Work in progress">WIP</acronym> Society Cologne (Kanban)](http://lwscologne.wordpress.com/), jeden zweiten Mittwoch im Monat, Infos und Anmeldung über die [xing Gruppe](https://www.xing.com/communities/groups/limited-wip-society-cologne-f66d-1045957/events) - [Agile Cologne](http://www.agilecologne.de/), die jährlich stattfindende (Un)Konferenz in Köln - [CoRe, Coach Reflection Day](https://www.coachreflectionday.org/), Bundesweite Veranstaltungsreihe, findet seit 2017 auch in Köln statt<!--break--> - [Agile Intervision](https://agile-intervision.de/), kollegiale Fallberatung für Scrum Master und Agile Coaches, weiteres über die [accsv-cgn Mailingliste](https://www.freelists.org/list/accsv-cgn) und auf [xing](https://www.xing.com/communities/groups/agile-intervision-90f0-1105436) - [Product Owner Meetup Köln/Product Owner Monthly](https://www.meetup.com/de-DE/Product-Owner-Meetup-Koeln/), jeden letzten Donnerstag im Monat - [Agile QA Cologne](https://www.meetup.com/de-DE/agileqa-cologne/), Quality Assurance in Agilen Projekten - [Agile at Scale - Köln Meetup](https://www.meetup.com/de-DE/Agile-at-Scale-Koln-Meetup/) - [Köln Liberating Structures Meetup](https://www.meetup.com/de-DE/Koln-Liberating-Structures-Meetup/), Meetup zum Ausprobieren und Erfahrungsaustausch der Liberating Structures Toolbox und Strings - [Köln Teal](https://www.meetup.com/de-DE/Koln-Teal-Reinventing-Organizations-Meetup/) Reinventing Organizations - Meetup - [Agile Ale](https://www.kernpunkt.de/agile-networking-event), präsentiert kernpunkt's Reise der agilen Unternehmenstransformation, Jeden dritten Mittwoch oder Donnerstag im Monat - [Spielend begreifen - get it through games](https://www.xing.com/communities/groups/spielend-begreifen-get-it-through-games-90f0-1106969), Spiele mit Mehrwert, alles was Verstehen fördert, egal ob Simulationen/Planspiele, Teamspiele oder Ice-Breaker für Teams und Organisationen - [Cologne Enterprise Changemaker](https://www.meetup.com/de-DE/Cologne-Enterprise-Changemaker/) - [Product People](http://productpeople.net/), seit 2017 stattfindende (Un-)Konferenz für Product Owner, Produkt‑Manager und Business‑Analysten **Agile Community Bonn** - [Bonn Agile Meetup](https://www.meetup.com/de-DE/Bonn-Agile/), am ersten Dienstag des Monats in wechselden Locations, Anmeldung über meetup - [Bonner Scrumtisch](https://www.xing.com/communities/groups/scrumtisch-bonn-380f-1077974), am zweiten Dienstag des Monats in wechselnden Locations, Anmeldung über xing - [Lean Coffee Bonn](https://www.xing.com/communities/groups/lean-coffee-90f0-1066150) **Agile Community Düsselorf** - [Agiler Stammtisch Düsseldorf aka <NAME>](https://www.meetup.com/de-DE/Agiler-Stammtisch-Duesseldorf/), findet jeden ersten Donnerstag im Monat in der Brauerei "Zum Schlüssel" statt. Mehr Informationen und Anmeldung über Meetup - [Das Agile Café in Düsseldorf](http://www.prowareness.de/event_show/?eventtitle=agile-caf--) ist ein Format vom Prowareness, Infos und Anmeldung die Website von Prowareness oder [xing](https://www.xing.com/communities/groups/agile-plus-market-duesseldorf-1cbe-1070927) - [Lean DUS](https://leandus.de) wird von der sipgate GmbH veranstaltet Agenda, Talks + Anmeldung über die Lean DUS Website - [Scrum Deutschland](), eine von Prowareness organisierte, jährlich stattfindende Konferenz - [Lean Coffee Düsseldorf](https://www.xing.com/communities/groups/lean-coffee-90f0-1066150) - [Düsseldorf Liberating Structures](https://www.meetup.com/de-DE/meetup-group-JUAeEreA/) **Agile Community Solingen** - [Agiler Stammtisch Solingen](https://www.meetup.com/de-DE/Agiler-Stammtisch-Duesseldorf/), bei der codecentric AG **Agile Community Aachen** - [Scrumtisch Aachen](http://www.scrumtisch-aachen.de/), findet monatlich in wechselnden Locations statt, Anmeldung über [xing](https://www.xing.com/communities/groups/scrumtisch-aachen-f66d-1002514) **Agile Community Ruhrgebiet** - [Agile Stammtisch Ruhr in Dortmund aka Lean Pils](http://www.meetup.com/de-DE/Agiler-Stammtisch-Ruhr/) findet jeden dritten Donnerstag im Monat statt in wechselnden Locations statt, Anmeldung über Meetup - [Scrumtisch Essen](https://www.xing.com/communities/groups/agile-punkt-ruhr-1cbe-1071167), jeden vierten Donnerstag im Monat, Anmeldung über xing - [agile.ruhr](http://agile.ruhr), die zweitägige (Un)Konferenz im zu Agile, Lean und Arbeit auf Augenhöhe im Ruhrgebiet, seit 2018 gibts auch noch den agile-ruhr Day - [Liberating Structures RUHR](https://www.meetup.com/de-DE/Liberating-Structures-in-RUHR/) **Kennst Du noch mehr regelmäßige Agile Events?** Diese Liste ist wahrscheinlich nicht komplett. Kennst Du noch weitere regelmäßig stattfindende Veranstaltungen? Lass es mich bitte durch einen Kommentar oder eine Mail wissen, ich aktualisiere dann gerne die Liste! Du kannst natürlich auch gerne einen *Pull Request* auf diese Seite stellen! * * * [^anon-agile]: [https://twitter.com/fl3a/status/733018819170578432](https://twitter.com/fl3a/status/733018819170578432) <file_sep>/_drafts/2012-12-01-howto-setup-gitolite-on-debian-wheezy.md --- tags: - howto - Git - Debian - config nid: 1615 permalink: "/howto-setup-gitolite-on-debian-wheezy.html" layout: book title: 'Howto: Setup Gitolite on Debian Wheezy' created: 1354361320 --- Installation von gitolite (2.3-1) auf Debian Wheezy/unstable. <h2>Erzeugung eines SSH-Kepairs</h2> <code> ssh-keygen -t rsa </code> <code> Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: e0:90:34:92:d8:e1:08:fc:24:45:b5:17:5a:0d:c9:2b root@git The key's randomart image is: +--[ RSA 2048]----+ |oo==+..++ | |o=o+ o+o.. | |. = oo... | | . E.o | | o S | | | | | | | | | +-----------------+ </code> <h2>Installation von gitolite</h2> <code> apt-get install gitolite </code> <!--break--> <code> Paketlisten werden gelesen... Fertig Abhängigkeitsbaum wird aufgebaut. Statusinformationen werden eingelesen.... Fertig Die folgenden zusätzlichen Pakete werden installiert: git git-man libcurl3-gnutls liberror-perl librtmp0 libssh2-1 rsync Vorgeschlagene Pakete: git-daemon-run git-daemon-sysvinit git-doc git-el git-arch git-cvs git-svn git-email git-gui gitk gitweb Die folgenden NEUEN Pakete werden installiert: git git-man gitolite libcurl3-gnutls liberror-perl librtmp0 libssh2-1 rsync 0 aktualisiert, 8 neu installiert, 0 zu entfernen und 0 nicht aktualisiert. Es müssen 8.920 kB an Archiven heruntergeladen werden. Nach dieser Operation werden 16,9 MB Plattenplatz zusätzlich benutzt. Möchten Sie fortfahren [J/n]? [...] No adminkey given - not setting up gitolite. </code> <h2>Konfiguration</h2> Da sich die Installation mit <strong>"No adminkey given - not setting up gitolite."</strong> verabschiedet, stoßen wir die Konfiguration manuell an... <code> dpkg-reconfigure gitolite </code> ...und landen in einem NCurses-Dialog: <strong>Gitolite Systemnutzer</strong> <code> Bitte geben Sie einen Namen für den Systemnutzer ein, der von gitolite verwendet werden soll, um auf die Repositorys zuzugreifen. Er wird falls Name des Systemnutzers für gitolite: </code> Hier behalten wir die Voreinstallung: <code> gitolite </code> <strong>Repository-Pfad</strong> <code> Bitte geben Sie den Pfad ein, in dem gitolite die Repositorys speichern soll. Dies wird zum Heimatverzeichnis des Systemnutzers. Repository-Pfad: </code> Auch hier nutzen wir den Default: <code> /var/lib/gitolite </code> <strong>Gitolite Admin Key</strong> <code> Bitte geben Sie den Schlüssel eines Nutzers an, der die Zugriffskonfiguration von gitolite administrieren wird. Dies kann entweder der öffentliche SSH-Schlüssel selbst sein oder aber der Pfad zu einer Datei, die ihn enthält. Falls dies leer gelassen wird, bleibt gitolite unkonfiguriert und muss manuell aufgesetzt werden. SSH-Schlüssel des Administrators: </code> Hier geben wir den Pfad zum öffentlichen SSH-Schlüssel, den wir oben erzeugt haben an: <code> /root/.ssh/id_rsa.pub </code> <code> creating gitolite-admin... Initialized empty Git repository in /var/lib/gitolite/repositories/gitolite-admin.git/ creating testing... Initialized empty Git repository in /var/lib/gitolite/repositories/testing.git/ [master (root-commit) c3ee4ee] start 2 files changed, 6 insertions(+) create mode 100644 conf/gitolite.conf create mode 100644 keydir/admin.pub </code> <h2>Klonen des Admin-Repositoires</h2> Zu Abweichungen zum Standard-SSH wie hier, habe ich bereits <a href="/node/990">SSH Port und GIT URLS</a> geschrieben. <code> git clone ssh://gitolite@git.example.com:1337/gitolite-admin </code> <code> Cloning into 'gitolite-admin'... The authenticity of host '[git.example.com]:1337 ([127.0.1.1]:1337)' can't be established. ECDSA key fingerprint is 54:89:8b:b9:9b:e8:ef:22:31:06:2e:fa:01:a0:80:07. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '[git.example.com]:1337' (ECDSA) to the list of known hosts. remote: Counting objects: 6, done. remote: Compressing objects: 100% (4/4), done. Receiving objects: 100% (6/6), 712 bytes, done. remote: Total 6 (delta 0), reused 0 (delta 0) </code> <h2>Struktur des Admin-Repositories</h2> <code> gitolite-admin/ ├── conf │   └── gitolite.conf └── keydir └── admin.pub </code> <h2>Weiterführend</h2> <ul> <li><a href="http://gitolite.com/gitolite/master-toc.html">gitolite documentation</a></li> <li><a href="http://sitaramc.github.com/gitolite/write-types.html">different types of write operations</a></li> <li><a href="http://eosrei.net/blog/2012/01/one-conf-repo-gitolite-using-include">One conf per repo in Gitolite using include </a></li> <li><a href="http://sitaramc.github.com/gitolite/syntax.html">gitolite.conf Syntax</a></li> </ul> <file_sep>/_posts/2012-07-10-drupal-distro-build-skript.md --- tags: - snippet - Installations Profile - drush - Drupal - "#!/bin/bash" nid: 1609 layout: post title: Drupal-Distro-Build-Skript created: 1341939334 --- Das Testen von Drupal-Installationsprofilen ist relativ mühselig, da sich ein Teil der Schritte, bis man überhaupt erst zum Testen der eigentlichen Funktionalität kommt, mit dem Build-Prozess beschäftigt. Diesen muß man eigentlich für jede Änderung erneut durchlaufen... <ol class="decimal"> <li>Drush make (das macht es im Falls des <a href="https://github.com/fl3a/fserver_profile">Feature-Server-Installations-Profiles</a>) <ol class="decimal"> <li>Drush make mit <em>distro.make</em> aus dem Git-Repository </li> <li>Download des Drupal-Cores</li> <li>Klonen des in <em>distro.make</em> hinterlegten Repositories für das Installationsprofil</li> <li>Rekursive Suche nach weiteren Drush-Makefiles, runterladen der Drupal-Module und des Themes, die im gefundenen Makefile <em>drupal-org.make</em> spezifiziert sind</li> </ol> </li> <li>Sybolischer-Link vom erstellten Build auf die DocumentRoot des für Testzwecke angelegten VirtualHosts</li> <li>Drop auf alle Tabellen in der Zieldatenbank</li> <li>Installation von Drupal und einem bestimmtem Installationsprofiles, hier <em>fserver_profile</em></li> </ol> In der scheinbaren Routine des manuellen Durchlaufen dieser Schritte entsteht zudem auch mal schnell ein Fehler. So habe ich beim gefühlt 100sten Mal des Durchlaufens dieser Prozedur versehentlich in der falschen Datenbank alle Tabellen <em>ge-dropt-t</em> und dachte mir, Automatisierung muss her, schreib ein Shellskript... <!--break--> <h2>Vorraussetzungen</h2> Neben den <em><a href="http://drupal.org/requirements/">Standard-System-Vorrausetzungen</a></em> für Drupal, wird zusätzlich folgendes für das Bash-Skript benötigt: <ul> <li><a href="http://git-scm.com/">git</a></li> <li><a href="http://drupal.org/project/drush">drush</a></li> <li><a href="http://drupal.org/project/drush_make">drush make</a><br />Falls Drush vor v.5 genutzt wird </li> <li><a href="http://drupal.org/project/drush_site_install6">drush site-install 6.x</a><br />Falls Drush vor v.4 mit Drupal-6.x genutzt wird</li> </ul> Zur Ausführung sollte sich das Skript im Suchpfad <em>$PATH</em> befinden, kann aber natürlich auch mit einem vorangestellten <em>bash</em> gestartet werden. <h2>Das Skript</h2> Einfaches Bash-Skript welches die o.g. Schritte durchläuft. Das <em>droppen</em> der Tabellen in der Zieldatenbank erfolgt über <em>drush site-install</em>. [gist:3089178:drupal_distro_build.sh] <h2>Konfiguration</h2> Die vom Skript benötigten Variablen, befanden sich in einer früheren Version zwischen der Interpreterdeklaration und <em>set -o nounset</em>, diese habe ich ausgelagert um das Arbeiten mit verschiedenen Branches und Projekten einfacher zu gestalten. Die Konfiguration wird dem Skript als Parmeter beim Aufruf übergeben [gist:3089178:example.build.conf.sh] <h2>Beispiele</h2> <ol> <li>Einfacher Aufruf mit Ausgabe <code> drupal_distro_build.sh fserver6_build.conf.sh </code> </li> <li> Aufruf mit Mailversand der Ausgabe des Buildprozesses, der Betreff ist hier der Name des Builds<br /> <code> drupal_distro_build.sh fserver6_build.conf.sh | mail -s `head -n 1` <EMAIL></code> </li> <li>Aufruf mit Generierung eines Logfile, welches so heißt wie der Build + Suffix <em>.log</em> <code> drupal_distro_build.sh fserver6_build.conf.sh | tee `head -n 1 `.log</code> </ol> <h2>Möglichkeiten</h2> Mögliche Verwendung und Einsatzszenarien: <ul> <li>In Git-Hooks</li> <li>In Continious Integration</li> <li>...und natürlich manuell</li> </ul> <h2>Quellen</h2> Auf github, <a href="https://gist.github.com/3089178">Gist 3089178</a> <code> git clone git://gist.github.com/3089178.git drupal_distro_build </code> <file_sep>/_drafts/personal-maps-workshop.md --- title: Personal Maps Workshop tags: [Tuckman Phasenmodell, Forming, Contact, Kennenlernen, Empathie, Management 3.0, Personal Maps] --- Wenn eine Gruppe von Menschen sich zusammenfindet um ein Team zu werden, dann befindet es sich lt. Tuckmanns Modell der Teamphasen[^1] in der *Forming Phase*, die im Zeichen des Zusammenkommens (Contact) steht. Ein Format um das Team im Kennenlernprozeß zu unterstützen sind Personal Maps[^2] [^3], eine Methode aus dem Management 3.0[^4] [^5]. <!--break--> ## Personal Maps Ziel ist es Empathie und Nähe zu erzeugen und wird gerade deshalb im Bereich der Remote-Arbeit sehr gerne genutzt. Sie dient dazu zu erfahren was Menschen, mit denen wir auf Arbeit einen Großteil unserer Lebenszeit verbringen neben der Fachlichkeit noch ausmacht. Ein großer Fokus liegt also auf dem Öffen der eigenen Geschichte und des Privatlebens. Wir gehen schneller Emotionale Verbindungen ein, unterstützen den Prozess des Kennenlernens und können Stimmungen besser deuten, wenn wir ggf. auch die Gründe kennen, z.B. bei Magelnde Konzentration aufgrund Schlaflosigkeit weil sein/ihr Kind welches gerade zahnt. Ein gewünschter Nebeneffekt ist das Personal Maps wunderbare Anknüpfungspunkte liefern, z.B. über interessante Themen oder Gemeinsame Punkte. ## Struktur der Personal Map Die Map hat die folgende Struktur: Den Mittelknoten, mit deinen Namen, davon gehen die folgenden Hauptknoten: - Interessen/Hobbies - Hier gerne mehr - Familie - z.B. Verheiratet, Kinder, Patchwork-Struktur - Ziele - Werte - Zuhause - z.B. wichtige Stationen, Städte - Ausbildung - z.B. Ausbildung, Studium, Abschlüsse, Zertifikate - Arbeit - z.B. Stationen, Position und Arbeitsgeber - Freunde Ggf. noch die zusätzlichen Knoten - Fun Facts ## Material für den Workshop Analog Wie ### Analog - Beschreibbare Fläche, wie Abwischbare Wand oder Whiteboad - Boardmarker - Flipchartpapier oder anderes Papier - Klebeband - Verschiedene Stifte ### Digital - Rechner - Mapmap Programm deiner Wahl, e.g. - xMind (opensource) - Confluence mit Gliffy Plugin # Ablauf eines Personal Maps Workshops Dauer ca. 1,5 Stunden bei einem Personal Maps Workshop mit 5 Team-Mitgliedern - Disclaimer vorweg: "Nur so offen sein, wie ihr es euch traut" - Vertrauen schaffen, auflockern mit ein Paar Blitzlichtern in Form von ein paar persönlichen Fotos oder Lustigen Situationen - Mit gutem Vorbild vorangehen und die eigene, sehr umfangreichen Personal Maps vorstellen - die Grundstruktur skizzieren - 30min für das Zeichen der eigenen Personal - 30min für das Vorstellen der eigenen Personal Maps ## Variationen - Verbal, z.B. in 1 und 1 bei einen Walk and Talk - Die eigene personal Map von einem anderen Team-Mitglied vorstellen lassen ## Weitere Formate für die Forming Phase - Schlüsselbund vorstellen - Waschzettel - FishBowl - Persönlichkeits-Tests wie z.B. MBTI[^6] ## Weiterführende Links/Fußnoten [^1]: [Tuckmanns Modell der Teamphasen](https://teamentwicklung-lab.de/tuckman-phasenmodell) [^2]: [Personal Maps](https://management30.com/practice/personal-maps/) [^3]: [Personal Maps: Improving team collaboration](https://www.happymelly.com/personal-maps-connecting-teams-improving-team) [^4]: [Management 3.0](https://management30.com/) [^5]: [Artikel über Management 3.0](http://www.lean-agility.de/2018/11/management-30.html) [^6]: [Myers-Briggs-Typenindikator](https://de.wikipedia.org/wiki/Myers-Briggs-Typenindikator) <file_sep>/_drafts/2016-02-18-installation-und-nutzung-von-drupal-composer-mit-drupal-8.md --- tags: [] nid: 1641 permalink: "/installation-und-nutzung-von-drupal-composer-mit-drupal-8" layout: blog title: Installation und Nutzung von Drupal-Composer mit Drupal 8 created: 1455825942 --- TLDR: Composer hat sich in der PHP-Welt als Dependency Manager (vergleichbar mit npm aus der Node/JS- oder bundler aus der Ruby-Welt) etabliert und hat schon seit einiger Zeit in die Drupal Welt Einzug erhalten wo die Insel-Lösung drush-make<fn>https://github.com/drush-ops/drush/blob/master/docs/make.md</fn> vorherschte. So beschäftigt sich dieser Artikel mit Composer<fn>https://getcomposer.org/</fn>, dem Drupal-Composer Projekt-Template<fn>https://github.com/drupal-composer/drupal-project</fn> und Composer als Makefile-Ersatz in Zusammenhang mit Drupal 8.<!--break--> <h2>Installation von Composer</h2> Natürlich ist die Installation von Composer die Grundvoraussetzung für Drupal-Composer, hier exemplarisch auf uberspace im bin-Verzeichnis meines Benutzers (<code>--install-dir</code>) und dem Dateinamen composer (<code>--filename</code>, Default <em>composer.phar</em>). <code> curl -sS https://getcomposer.org/installer | php -- --install-dir=$HOME/bin --filename=composer </code> <h2>Das Drupal-Composer Template</h2> Neben dem Composer selbst ist die zweite Zutat das <strong>Composer Template für Drupal-Projekte</strong>, hierüber ist dann möglich auf drupal.org gehostete Module via Composer zu installieren, das funktioniert über den Drupal Packagist<fn>https://packagist.drupal-composer.org/</fn> als Repository. Installation einer Drupal-8 Site mit dem Composer-Template im Verzeichnis example.com: <code> composer create-project drupal-composer/drupal-project:8.x-dev example.com --stability dev --no-interaction </code> <strong>Was macht das Drupal-Composer-Template?</strong> Neben der Installation von z.B. noch weiterer Vendors wie phpunit oder composer/installers<fn>https://github.com/composer/installers</fn>, welches die Drupal-Pakete direkt ihren passenden und angedachten Platz läd (s.u.) sorgt es für eine sinnige Struktur und Bereitstellung von Werkzeugen, wie z.B.: <ul> <li>Es installiert Drupal in das Verzeichnis web</li> <li>Drupal-Modules (Pakete vom Typ drupal-module) werden nach web/modules/contrib/ geladen</li> <li>Drupal-Themes (Pakete vom Typ drupal-theme) werden nach web/themes/contrib/ geladen</li> <li>Drupal-installations-Profile (Pakete vom Typ drupal-profile )werden nach web/profiles/contrib/ geladen</li> <li>Es legt schreibbares Versionen von settings.php und services.yml an</li> <li>Es legt ein schreibbares sites/default/files Verzeichnis an</li> <li>Die neuste Version von drush ist installiert und unter vendor/bin/drush verfügbar</li> <li>Die neuste Version von DrupalConsole ist installiert und unter vendor/bin/console verfügbar</li> <li><strike>Drupal Packagist</strike><fn>https://packagist.drupal-composer.org/</fn>packages.drupal.org<fn>https://github.com/drupal-composer/drupal-project/commit/49184d678ff0de7f0cda0b597a7b170c6e5261e6</fn> ist als Repository hinterlegt um Drupal-Module, -Themes etc zu verwalten</li> </ul> Hier ein Blick in das mit dem Template erzeugte Projekt example.com: <code> example.com/ ├── composer.json ├── composer.lock ├── drush ├── LICENSE ├── phpunit.xml.dist ├── README.md ├── scripts ├── vendor │   ├── bin │   │   ├── drupal -> ../drupal/console/bin/drupal │   │   ├── drush -> ../drush/drush/drush │   │   └── [...] │   ├── drupal │   │   └── console │   │   └── bin │ │      └── drupal │   └── drush │      └── drush │      └── drush └── web ├── core │   ├── assets │   ├── config │   ├── includes │   ├── lib │   ├── misc │   ├── modules │   ├── profiles │   ├── scripts │   ├── tests │   └── themes ├── modules │   └── contrib ├── profiles │   └── contrib ├── sites │   └── default │   └── files └── themes    └── contrib </code> <small>Abb. 1, Auszug Ausgabe des Befehls "tree" auf das mit Composer-Template erzeugte example.com</small> <h2>Composer Generate</h2> Falls ihr eine bestehende Drupal-8-Seite habt, mit der Drush-Erweiterung <em>Composer Generate</em><fn>https://www.drupal.org/project/composer_generate</fn> kann eine <em>composer.json</em> aus aus bereits bestehenden Drupal-Sites erzeugt werden, die ladet ihr via <code>drush dl composer_generate</code> herunter und führt dann ein <code>drush composer-generate</code> aus der bestehenden Site aus. <code> { "require": { "drupal/big_pipe": "8.1.*", "drupal/composer_manager": "8.1.*", "drupal/devel": "8.1.*", "drupal/drupalmoduleupgrader": "8.1.*", "drupal/footnotes": "8.2.*", "drupal/geshifilter": "8.1.*", "drupal/git_deploy": "8.2.*", "drupal/libraries": "8.3.*" }, "minimum-stability": "dev", "prefer-stable": true } </code> <small>Abb. 2, Ausgabe drush composer-generate</small> Die obige Ausgabe, also die verwendeten Pakete vom Type Drupal-Modul könnt ihr dann in der <em>composer.json</em> in eurem Composer-Template im require-Abschnitt anfügen, mit der Ausführung von <code>composer update</code> werden die Pakete heruntergeladen und die Datei <em>composer.lock</em><fn>https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file</fn> wird aktualisiert. <h2>Installation von Drupal-Modulen mit composer</h2> Installation von Google Analytics mit exakter Versionsangabe, gewollt ist 8.x-2.0-rc1<fn>https://www.drupal.org/node/2620812</fn>, die Versionsangaben werden in composer allerdings anders notiert<fn>https://getcomposer.org/doc/articles/versions.md</fn>, 8.2.0-rc1<fn>https://packagist.drupal-composer.org/packages/drupal/google_analytics#8.2.0-rc1</fn>. <code> composer require drupal/google_analytics:8.2.0-rc1 </code> <code> ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) - Installing drupal/google_analytics (8.2.0-rc1) Downloading: 100% Writing lock file Generating autoload files </code> <h2>Drupal Updates mit Composer</h2> Das Aktualisieren von Drupal und Contribs, bei z.B. anstehenden Sicherheitsupdates auf den Drupal-Kern geht analog zu drush, hier ist ja ebenfalls möglich das Projekt anzugeben (<em>drush up drupal</em>). Hier der Aufruf für die Aktualisierung des Pakets <em>drupal/core</em>, ohne Spezifizierung des Pakets würden alle Pakete (Contrib, vendor, etc) aktualisiert werden: <code> composer update drupal/core </code> <code> Loading composer repositories with package information Updating dependencies (including require-dev) - Removing drupal/core (8.0.3) - Installing drupal/core (8.0.4) Writing lock file Generating autoload files </code> Ein kleines Bonbon ist, dass an dieser Stelle unser Lock-File die neue Version (8.0.4) für Drupal aktualisiert hat, sprich unser "Make-File" ist nach der Aktualisierung ebenfalls auf dem neusten Stand. <h2>Patches auf Drupal-Pakete</h2> Für den Umgang mit Patches auf z.B. Drupal-Pakete ist das Plugin cweagans/composer-patches<fn>https://github.com/cweagans/composer-patches</fn> im Drupal-Composer-Template als Abhängigkeit enthalten und verfügbar. So ist es möglich lokale oder Remote-Patches zu handhaben. Patches werden in der Sektion <em>extra</em>, <em>patches</em> nach folgendem Schema spezifiziert: <code> "extra": { "patches": { "vendor/project": { "Patch description": "URL to patch" } } } </code> <small>Abb. 3, Schema für Patches</small> Beispiel, Remote-Patch auf den Drupal-Kern, <em>Remove file lookup in process plugin [d6]</em><fn>https://www.drupal.org/node/2640842</fn>: <code> "extra": { "patches": { "drupal/core": { "Remove file lookup in process plugin [d6]": "https://www.drupal.org/files/issues/2640842-8.patch" } } } </code> <small>Abb. 4, Beispiel Patch auf den Drupal-Kern</small> Angewendet wird der Patche mit <code>composer update</code> nach dem Ergänzen der composer.json um den Patch in Abb. 4: <code> Gathering patches for root package. Removing package drupal/core so that it can be re-installed and re-patched. Deleting web/core - deleted Loading composer repositories with package information Updating dependencies (including require-dev) Gathering patches for root package. Gathering patches for dependencies. This might take a minute. - Installing drupal/core (8.0.5) Loading from cache - Applying patches for drupal/core https://www.drupal.org/files/issues/2640842-8.patch (Remove file lookup in process plugin [d6]) </code> <small>Abb. 5, Teil der Ausgabe von composer update mit Drupal-Patch.</small> <file_sep>/_posts/2017-05-23-das-war-die-agile-cologne-2017.md --- tags: - Scrumtisch Köln - Scrum - Reinblau - Open Space - Lean - Köln - Kanban - Community - Agile nid: 1644 permalink: "/das-war-die-agile-cologne-2017.html" layout: post title: Das war die Agile Cologne 2017 created: 1495529504 --- <p><img src="/assets/imgs/agilecologne17/agile-cologne-logo-220x81.jpeg" style="float:left;padding-right: 10px;" alt="Agile Cologne Logo" />Wie 180 weitere "Agile Begeisterte" zog es auch Boris und mich am 24. März 2017 – selbstverständlich mit blauen Reinblau-T-Shirts ausgestattet –&nbsp;wieder zur Agile Cologne<fn>https://agilecologne.de/</fn>. Die Veranstaltung fand dieses Mal im GS1 Knowledge Center in Köln statt und konnte im Vergleich zum Vorjahr an Teilnehmern zulegen.</p> <p>Auch dieses Jahr gab es ein qualitativ hochwertiges Potpourri an Themen, die im Open Space<fn value="2">https://de.wikipedia.org/wiki/Open_Space</fn> entstanden: von Agilen Prozessen wie Scrum, Kanban, über Sessions zu speziellen Scrum-Rollen – Product Owner, Scrum Master – oder Sessions über Retrospektiven bis hin zu einer handvoll Sessions zu Agilen Spielen (Ubongo Flow Game, Ballpoint Game).</p><!--break--> <p>Aufgrund der Vielfalt und teilweise neun parallelen Sessions sind Boris und ich uns in keiner Session begegnet.</p> <img alt="Open Space Sessionplan, Agile Cologne 2017" data-align="right" data-caption="Open Space Sessionplan,&amp;nbsp;© <NAME>,&amp;nbsp;https://twitter.com/hollipolli2904/status/845221419768315907" data-entity-type="file" src="/assets/imgs/agilecologne17/open-space-agile-cologne-2017_0.jpg" /><br /> <small>Open Space Sessionplan, © <NAME>, Quelle Twitter<fn>https://twitter.com/hollipolli2904/status/845221419768315907</fn></small> <p>Hier unsere Highlights der diesjährigen Agile Cologne. <!--break--></p> <h2>Agile Transition</h2> <p>Martin und Matthias berichteten über ihren Weg vom Piloten zur Agilen Welle bei der Santander Bank. Bei Ihnen baut die Agile Transition auf 3 Säulen auf:</p> <ol> <li>Scrum</li> <li>Design Thinking</li> <li>DevOps</li> </ol> <h2>Project End Retrospective</h2> <p>Harald berichte über seiner Erfahrung mit einem Projekt Review bzw. einer Post Mortem Analyse mittels einer Retrospektive. Ein wichtiger Faktor war, dass das Team nach diesem Projekt weiterhin zusammengearbeitet hat.</p> <p>Das Projekt Review dauerte 2,5 Stunden und orientierte sich an fünf Phasen der Retrospektive, Harald nutzte die sog. Starfish Retrospektive. In Phase 4, in der entschieden wird, was zu tun ist, ließ das Team seine Learnings in die Team Charta bzw. ihr Manifest einfließen.</p> <img alt="Project End Retrospective Flipchart, Agile Cologne 2017" data-caption="Project End Retrospective Flipchart, Agile Cologne 2017" data-entity-type="file" src="/assets/imgs/agilecologne17/project-end-retrospective-agile-cologne-2017.jpg" /> <p>&nbsp;</p> <h2>Visual Facilitating</h2> <p>Visual Facilitating mit Daniel war eine sehr greifbare Session, die mir sehr viel Spaß gemacht hat. Auf der Agile Cologne XXL im letzten Herbst hat Boris bereits seine "kreative Ader" kennengelernt:</p> <p>&nbsp;</p> <blockquote class="twitter-tweet" data-lang="de"> <p dir="ltr" lang="de">Sketchnoting – ich werde mir wohl bald ein Ohr abschneiden müssen … <a href="https://t.co/CIJKxlV1xm">pic.twitter.com/CIJKxlV1xm</a></p> — <NAME> (@bbarunte) <a href="https://twitter.com/bbarunte/status/782918811808833536">3. Oktober 2016</a></blockquote> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> <p>&nbsp;</p> <p>Zuerst ging es um ein paar grundlegende Prinzipien, z.B.:</p> <ul> <li>Alles Technik und keine Kunst</li> <li>Erst Text, dann Rahmen</li> <li>Finden einer Reihenfolge, bspw. bei Boxen</li> <li>Vernünftige Schreibposition</li> <li>Niemals nachzeichnen bzw. korrigieren</li> </ul> <p>Dann fingen wir mit Bannern und Boxen an und kamen von Symbolen zu Figuren und Gesichtern. Als weiterführende Literatur wurden uns die Bikablos ans Herz gelegt.</p> <h2>The ME in all the WE</h2> <p>The ME in all the WE mit Falk. Falk hat sich ein Spiel ausgedacht, welche als teambildende Maßnahme, wie für das Kennenlernen genutzt werden kann. Wir, die Teilnehmenden waren quasi die Probanden.</p> <img alt="The ME in ALL the WE, Agile Cologne 2017 von <NAME>" data-caption="The ME in ALL the WE, Agile Cologne 2017, © <NAME>, https://twitter.com/bluescrum/status/845292676467580929" data-entity-type="file" src="/assets/imgs/agilecologne17/the-me-in-all-the-we-agile-cologne-2017_0.jpg" /><br /> <small>"The ME in ALL the WE, Agile Cologne 2017, © <NAME>, Quelle Twitter <fn>https://twitter.com/bluescrum/status/845292676467580929</fn></small> <p>Jeder aus dem Team suchte sich aus einer größeren Menge von Karten mit z.T. gegenteiligen Wertepaaren, wie z.B. Driving the… Car vs. Bike, Starwars vs. Startrek oder Ski vs. Snowboard zwei Karten aus. Dann haben wir die Auswahl auf auf zehn reduziert, alleine die Auswahl der Karten war ein sehr kommunikativer Vorgang.</p> <img alt="The ME in ALL the WE, ausgebreitete Karten auf dem Boden, Agile Cologne 2017" data-caption="The ME in ALL the WE, ausgebreitete Karten auf dem Boden, Agile Cologne 2017" title="" data-entity-type="file" src="/assets/imgs/agilecologne17/the-me-in-all-the-we-agile-cologne-2017-2.jpg" /> <p>Anschließend übertrug jedes Teammitglied seinen Standpunkt auf sein Blatt mit einem Teamradar mit entsprechend zehn Punkten.</p> <h2>Umgang mit Fehlern — Erleuchtung vs. Scheitern</h2> <p>Getreu dem Motto: Fail early, fail often, fail cheap hat Cynthia eine Session zum Umgang mit Fehlern bzw. Fehlerkultur gehalten.</p> <blockquote class="twitter-tweet" data-lang="de"> <p dir="ltr" lang="de">...betrifft die meisten von uns natürlich nicht, war aber gut - Umgang mit Fehlern / Erleuchtung vs. Scheitern von <a href="https://twitter.com/LunaMel801">@LunaMel801</a> <a href="https://twitter.com/hashtag/agilecologne?src=hash">#agilecologne</a> <a href="https://t.co/5AKkzDCwKH">pic.twitter.com/5AKkzDCwKH</a></p> — <NAME> (@bbarunte) <a href="https://twitter.com/bbarunte/status/845328738975932417">24. März 2017</a></blockquote> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> <h2>Danke und bis zur Agile Cologne XXL im Herbst!</h2> <p>Wir sind mit großer Vorfreunde zur diesjährigen Agile Cologne gekommen, gegangen sind wir mit Inspiration und neuer Energie. Hierfür und für einen toll organisierten Event möchten wir von Reinblau uns beim Orga-Team, <NAME>, <NAME>, <NAME> und <NAME> bedanken.</p> <p>Reinblau hat dieses Format gerne wieder mit einem Sponsorenpaket unterstützt. Wir freuen uns schon jetzt auf die Agile Cologne XXL im Herbst!</p> <h2>Gut zu wissen</h2> <p>Die Agile Cologne ist eine Eventreihe, die&nbsp;seit 2013 zum fünften Mal jährlich stattfindet. Sie bietet&nbsp;Agile-, Lean-, Scrum-, sowie Kanban-Interessierten ein Forum.</p> <p>Die Agile Cologne ist eine Unconference, das bedeutet, es gibt im voraus keine feste Agenda, sondern diese via Open Space<fn value="2">https://de.wikipedia.org/wiki/Open_Space</fn> von den Teilnehmen selbst entwickelt wird.</p> <p>Seit 2015 gibt es die Agile Cologne auch als 2-tägiges&nbsp;Event und heißt dann Agile Cologne XXL.</p> <p>Wem der Rythmus von 2 Veranstaltungen pro Jahr zum Austauschen und Fachsimpeln über Agille Produkt- und Softwareentwicklung im Kölner Umland zu wenig ist, dem möchte ich eine von mir zusammengetragene Liste von Meetups und Usergroups zum Thema&nbsp;Agilität&nbsp;ans Herz legen:&nbsp;<a href="/agile-scrum-lean-kanban-events-koeln-bonn-duesseldorf-umgebung.html">Regelmäßige Agile, Scrum, Lean und Kanban Events in Köln, Bonn, Düsseldorf und Umgebung</a>.</p> <file_sep>/impressum.md --- title: Impressum permalink: /impressum layout: page --- Verantwortlich für den Inhalt laut § 55 Abs. 2 RStV und § 55 Abs. 2 RStV <NAME> Graf-Adolf-Str. 66 D-51065 Köln-Mülheim +49 [0] 163 191 77 floh-at-netzaffe-punkt-de USt-IdNr. DE 814 723 558 <file_sep>/_config.yml # Welcome to Jekyll! # # This config file is meant for settings that affect your whole blog, values # which you are expected to set up once and rarely edit after that. If you find # yourself editing this file very often, consider using Jekyll's data files # feature for the data you need to update frequently. # # For technical reasons, this file is *NOT* reloaded automatically when you use # 'bundle exec jekyll serve'. If you change this file, please restart the server process. # Site settings # These are used to personalize your new site. If you look in the HTML files, # you will see them accessed via {{ site.title }}, {{ site.email }}, and so on. # You can create any custom variable you would like, and they will be accessible # in the templates via {{ site.myvariable }}. title: netzaffe.de author: "<NAME>" email: <EMAIL> description: >- # this means to ignore newlines until "baseurl:" Über meine Abenteuer im Taka-VUCA-Land. Notizen, Berichte über dies, das, verschiedene Dinge. baseurl: "" # the subpath of your site, e.g. /blog url: "https://netzaffe.de" # the base hostname & protocol for your site, e.g. http://example.com twitter_username: fl3a github_username: fl3a #drupal_username: fl3a linkedin_username: florianlatzel #xing_username: Florian_Latzel gnupg_keyid: "<KEY>" defaults: - values: author: "<NAME>" # Drupal like teaser show_excerpts : true excerpt_separator : "<!--break-->" read_more : "Weiterlesen" # Build settings markdown: kramdown theme: minima plugins: - jekyll-feed - jekyll-toc - jekyll-sitemap - jekyll-seo-tag - jekyll-paginate-v2 # Pagination Settings # https://github.com/sverrirs/jekyll-paginate-v2 # https://github.com/sverrirs/jekyll-paginate-v2/blob/master/README-GENERATOR.md#site-configuration pagination: enabled: true per_page: 10 permalink: '/page/:num/' limit: 0 sort_field: 'date' sort_reverse: true # Plugin: Auto Pages (jekyll-paginate-v2) autopages: enabled : true categories: enabled : false collections: enabled : false tags: enabled : true slugify: mode: latin cased: true layouts: - "home.html" title : ":tag" permalink : "/tags/:tag" # jekyll-seo-tag # https://github.com/jekyll/jekyll-seo-tag lang: "de_DE" social: name: <NAME> links: - https://twitter.com/fl3a - http://de.linkedin.com/in/florianlatzel/en - https://github.com/fl3a - http://soundcloud.com/florian-latzel - http://drupal.org/u/fl3a - http://de.slideshare.net/fl3a - http://www.xing.com/profile/Florian_Latzel # Exclude from processing. # The following items will not be processed, by default. Create a custom list # to override the default setting. # exclude: # - Gemfile # - Gemfile.lock # - node_modules # - vendor/bundle/ # - vendor/cache/ # - vendor/gems/ # - vendor/ruby/ <file_sep>/.htaccess # # Redirects # # BEGIN Rules # To redirect all users to access the site WITHOUT the 'www.' prefix, # (http://www.example.com/... will be redirected to http://example.com/...) RewriteCond %{HTTP_HOST} ^www\.netzaffe\.de$ [NC] RewriteRule ^(.*)$ https://netzaffe.de/$1 [L,R=301] # Redirect to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # Redirect urls starting with /blog/ (Drupal imported) to jekylls standard url schema, # eg.: /blog/2009/07/04/drupallinuxtag09-open-source-drupal-linux-und-ballons.html # -> /2009/07/04/drupallinuxtag09-open-source-drupal-linux-und-ballons.html RedirectMatch 301 ^/blog/(.*).html$ /$1.html # Redirect tag urls ending with .html # /tags/scrum.html -> /tags/scrum/index.html RedirectMatch 301 ^/tags/([^/]+)\.html$ /tags/$1/index.html # Redirect all Drupal legacy tag urls to tag page RedirectMatch 301 ^/taxonomy/term/\d+$ /themen.html RedirectMatch 301 ^/taxonomy/term/\d+/\d+$ /themen.html # Redirect all Drupal legacy tag feeds to /feed.xml RedirectMatch 301 ^/taxonomy/term/(.*)/feed$ /feed.xml # END Rules # BEGIN Book pages Redirect 301 /book/export/html/667 /gnupg-micro-howto.html RedirectMatch 301 /gnupg-micro-howto/(.*) /gnupg-micro-howto.html Redirect 301 /book/export/html/978 /git-gitosis-gitweb-the-debian-way.html RedirectMatch 301 /git-gitosis-gitweb-the-debian-way/(.*) /git-gitosis-gitweb-the-debian-way.html Redirect 301 /book/export/html/520 /drupal-6-multisiteumgebung-mit-postgresql-unter-debian-4.html RedirectMatch 301 /drupal-6-multisiteumgebung-mit-postgresql-unter-debian-4/(.*) /drupal-6-multisiteumgebung-mit-postgresql-unter-debian-4.html # END Book pages # BEGIN misc Redirect 301 /node/1630 /2014/08/28/facebook-tschoe-mit-oe-mit-oe.html Redirect 301 /php-codesniffer-und-php-mess-detector-mit-syntastic-in-vim-integrieren /2016/03/13/php_codesniffer-und-php-mess-detector-mit-syntastic-in-vim-integrieren.html Redirect 301 /php-properties-klassenvariablen-doxygen-dokumentieren /2014/10/10/php-properties-klassenvariablen-in-doxygen-dokumentieren.html Redirect 301 /ein-experiment-drupalcamp-goes-barcamp /2018/03/27/ein-experiment-drupalcamp-ruhr-goes-barcamp.html Redirect 301 /scrum-starter-kit /2018/03/03/scrum-starter-kit.html Redirect 301 /ueberpruefung-von-ssl-zertifikaten-bei-wget-und-curl-ignorieren /2015/03/01/ueberprfung-von-ssl-zertifikaten-bei-wget-und-curl-ignorieren.html Redirect 301 /pear-phpunit-composer-und-drupal /2015/02/28/pear-phpunit-de-composer-und-drupal.html Redirect 301 /blog http://netzaffe.de Redirect 301 /blog?page=1 http://netzaffe.de/ Redirect 301 /node?page=1 http://netzaffe.de/ Redirect /blog/2014/11/26/svn-ueber-ssh-unter-linux-username-bei-svn-checkout-angeben.html /2014/11/26/svnssh-unter-linux-username-bei-svn-checkout-angeben.html Redirect 301 /rss.xml /feed.xml Redirect 301 /autocompletition-fuer-drush-aktivieren /2013/04/21/autocompletition-fuer-drush-aktivieren.html Redirect 301 /2019/04/05/daily-scrum-daily-questions.html /2019/04/05/daily-scrum-fragen.html # Temporär, Artikel in _draft Redirect 301 /drupal-6-multisiteumgebung-mit-postgresql-unter-debian-4.html /tags/drupal/index.html Redirect 301 /2010/12/11/arbeit-sparen-mit-cluster-ssh.html /2010/12/10/arbeit-sparen-mit-cluster-ssh.html # Temp: Umlaute Redirect 301 /tags/scrumtisch-koeln/index.html /tags/scrumtisch-koln/index.html Redirect 301 /tags/duesseldorf/index.html /tags/dusseldorf/index.html Redirect 301 /ueber.html /florian-latzel.html Redirect 301 /florian-fl3a-latzel.html /florian-latzel.html # END misc <file_sep>/_posts/2016-12-19-scrum-in-45-minuten-vortrag-auf-dem-drupalcamp-mnchen-2016.md --- tags: - Session - Scrum - Reinblau - Agile - Projektmanagement - München - Drupalcamp - dcmuc16 nid: 1643 permalink: "/scrum-in-45-minuten-drupalcamp-muenchen-2016.html" layout: post title: Scrum in 45 Minuten - Vortrag auf dem Drupalcamp München 2016 created: 1482169913 --- <img src="/assets/imgs/eine-einfuehrung-in-scrum-roger-pfaff-florian-latzel-drupalcamp-munic-2016-khe.jpg" alt="Folie Scrum-Rolle Development Team, <NAME> und <NAME> präsentieren Eine Einführung in Scrum" /> <small>Scrum Rolle Development Team, CC BY-NC 3.0 DE <NAME><fn>https://twitter.com/diekatja/status/805088880705802240</fn></small> <a href="http://twitter.com/rogerpfaff">Roger</a> und Ich haben auf dem DrupalCamp München 2016<fn>http://dcmuc16.drupalcamp.de</fn> eine Session über das agile Rahmenwerk Scrum gehalten,&nbsp;hier die Beschreibung&nbsp;der eingereichten Session<fn>http://dcmuc16.drupalcamp.de/sessions/eine-einfuhrung-scrum</fn>: <blockquote> Scrum ist einer der bekanntesten Vertreter aus dem Umfeld des Agilen Produkt- und Projektmanagements. Scrum ist immer noch Bestandteil der meisten Buzzword-Bingos, gehört neben Agile ins Vokabular des klassischen Projektmanagers und ist auch noch nach über 20 Jahren hip und gefragt.<!--break--> In dieser Session wollen Roger und ich euch das agile Framework vorstellen und werden unter anderem auf die folgenden Fragen eingehen: Was ist Scrum, woher kommt es?<br /> Was ist der Unterschied zum Wasserfall-Modell?<br /> Welche Scrum-Rollen gibt es und was ist deren Aufgabe?<br /> Was sind Scrum-Zeremonien und wie werden diese abgehalten?<br /> Was sind Scrum-Artefakte?<br /> Welche Werkzeuge gibt es und welche eignen sich für Verteilte-/Remote-/Distributed-Teams? </blockquote> <p>Während &nbsp;die vergangenen Sessions<fn>http://netzaffe.de/blog/2010/05/12/scrum-aus-der-praxis-drupaldevdays-2010.html</fn> eher ein Augenmerk auf das Rahmenwerk, also Rollen, Zeremonien und Artefakte hatten, haben wir bei dieser Session ein größeres Augenmerk die Ebene hinter Scrum gelegt.</p> <p>So haben wir das Manifest für Agile Softwareentwicklung<fn>http://agilemanifesto.org/iso/de/manifesto.html</fn> hinzugefügt und &nbsp;sind ausführlicher auf agile Werte&nbsp;und Prinzipien<fn>http://agilemanifesto.org/iso/de/principles.html</fn> eingegangen.</p> <p>In zukünftigen Sessions werden wir auch mal intensiv auf die einzelnen Elemente von Scrum eingehen. Denn sogar zu einer Retrospektive, einer Sprint-Review oder auch nur einer User Story kann man locker eine ganze Session halten und die Besucher der Session in ein tieferes Verständnis davon bringen.</p> <strong>Gut zu wissen</strong> Scrum ist ein Vorgehensmodell für Projekt- und Produktmanagement und wird häufig als Synonym für Agile Softwareentwicklung benutzt. Scrum ist leichtgewichtig (im Sinne von Lean) und besteht aus aus einem kleinen Set an Regeln, nämlich 3 Rollen, fünf Aktivitäten und drei Artefakten. Die Definition von Scrum und seinen Regeln findest du im offiziellen Scrum-Guide<fn>http://www.scrumguides.org/</fn> beschrieben.
7f17143d03ff8cf12cf994ce5edf642de78abb30
[ "Markdown", "ApacheConf", "YAML" ]
16
Markdown
tiepdotme/netzaffe.de
b01d88f445463b6dbaa105310316607a07293c8b
5bb26f5b08d5582fdc418298b899b1f326493e17
refs/heads/master
<file_sep>num = int(input("enter the number:")) temp = num rev = 0 while(num > 0): dig = num % 10 rev = rev * 10 + dig num = num // 10 if temp == rev: print(f'The number:{temp} is a palindrome') else: print(f'The number:{temp} is not a palindrome') <file_sep>s = "hello world" print(s.capitalize()) <file_sep>def reverseword(s): w = s.split(" ") nw = [i[::-1] for i in w] ns = " ".join(nw) return ns s ="Pace Wisdom Solutions" print(reverseword(s)) <file_sep>import csv import pandas as pd df = pd.read_csv("myfile.csv") df1=df.stud_nam df2 = pd.DataFrame({'totl_mrks':df.sum(axis=1)}) df3= pd.DataFrame({'avg_mrks':df.mean(axis=1)}) frames = [df1, df2, df3] result = pd.concat(frames, axis=1) result.to_csv('city.csv')
23267926d6d6ea7d56c42eb8d49643a457ec15fa
[ "Python" ]
4
Python
vishnuak15/Assignment1
19145e189e40ba0198054757412744d1a147ac15
175b49063fd8b50c0044117f4e2694b16e7cca2f
refs/heads/main
<repo_name>carlo98/tablut-THOR<file_sep>/monte_carlo_data.py """ Date: 05/11/2020 Author: <NAME> & <NAME> Population-based search for best weight of heuristic's component. """ from multiprocessing import Pool import subprocess import time import numpy as np from random_player_white import Client MAX_TIME_ACTION = 5 # Maximum time allowed to search for action def create_play_player(port, color, max_time_act, weights, name, host, file_access): client_m = Client(port, color, max_time_act, weights=weights, name=name, host=host, file_access=file_access) client_m.run() def run(): """ Starts two matches between a couple of solutions, returns point earned by each one. """ pool = Pool() proc = subprocess.Popen('ant server', shell=True) # Requires server files in path time.sleep(5) white_thread = pool.apply_async(create_play_player, args=(5800, "WHITE", MAX_TIME_ACTION, [np.random.rand() * 50, np.random.rand() * 50, np.random.rand() * 50, np.random.rand() * 50, np.random.rand() * 50, np.random.rand() * 50], "EHILA", "127.0.0.1", True)) # time.sleep(1) # Important, pass list just to one of the two threads, to avoid synchronization problems black_thread = pool.apply_async(create_play_player, args=(5801, "BLACK", MAX_TIME_ACTION, [np.random.rand() * 50, np.random.rand() * 50, np.random.rand() * 50, np.random.rand() * 50, np.random.rand() * 50, np.random.rand() * 50], "OOOOO", "127.0.0.1", False)) black_thread.wait() white_thread.wait() pool.close() proc.terminate() cont = 0 while cont <= 30: run() cont += 1 <file_sep>/THOR.py import argparse from tablut.client.tablut_client import Client parser = argparse.ArgumentParser(description='Default: Color = White and Timeout = 60s') parser.add_argument("-c", "--color", default='white', help="Set the player color.") parser.add_argument("-t", "--max_time", type=int, default=10, help="Change max_time") args = parser.parse_args() if args.color.lower() == 'white': color = "WHITE" elif args.color.lower() == 'black': color = "BLACK" else: print("Wrong color, possible choices are white/black") exit(-1) max_time = args.max_time if color == "WHITE": server_port = 5800 else: server_port = 5801 Client(server_port, color, max_time-0.2).run() <file_sep>/src/tests/king_capture_tests.java package tests; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import it.unibo.ai.didattica.competition.tablut.domain.State.Turn; import thor.BitState; import thor.Game; import thor.Minmax; class king_capture_tests { @BeforeEach void setUp() throws Exception { } @Test void capture_king_right_camp() throws IOException { BitState bs = new BitState(); int[] white_bitboard = { 256, 0, 0, 0, 0, 0, 0, 0, 0 }; int[] black_bitboard = { 0, 4, 0, 0, 0, 0, 0, 0, 0 }; int[] king_bitboard = { 0, 0, 0, 2, 0, 0, 0, 0, 0 }; bs.setBlack_bitboard(black_bitboard); bs.setWhite_bitboard(white_bitboard); bs.setKing_bitboard(king_bitboard); bs.setTurn(Turn.BLACK); String c = "BLACK"; Game game = new Game(c); Minmax minmax = new Minmax(game); List<Integer> action = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0)); action = minmax.makeDecision(10, bs, true); System.out.println("action = " + action.get(0) + " " + action.get(1) + " " + action.get(2) + " " + action.get(3) + " " + action.get(4)); BitState new_bs = new BitState(bs, action); int[] k_bitboard_expected = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertArrayEquals(k_bitboard_expected, new_bs.getKing_bitboard()); } @Test void capture_king_below_camp() throws IOException { BitState bs = new BitState(); int[] white_bitboard = { 256, 0, 0, 0, 0, 0, 0, 0, 0 }; int[] black_bitboard = { 0, 2, 0, 0, 0, 0, 0, 0, 0 }; int[] king_bitboard = { 0, 0, 0, 2, 0, 0, 0, 0, 0 }; bs.setBlack_bitboard(black_bitboard); bs.setWhite_bitboard(white_bitboard); bs.setKing_bitboard(king_bitboard); bs.setTurn(Turn.BLACK); String c = "BLACK"; Game game = new Game(c); Minmax minmax = new Minmax(game); List<Integer> action = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0)); action = minmax.makeDecision(10, bs, true); System.out.println("action = " + action.get(0) + " " + action.get(1) + " " + action.get(2) + " " + action.get(3) + " " + action.get(4)); BitState new_bs = new BitState(bs, action); int[] k_bitboard_expected = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertArrayEquals(k_bitboard_expected, new_bs.getKing_bitboard()); } @Test void capture_king_left_camp() throws IOException { BitState bs = new BitState(); int[] white_bitboard = { 256, 0, 0, 0, 0, 0, 0, 0, 0 }; int[] black_bitboard = { 0, 32, 0, 0, 0, 0, 0, 0, 0 }; int[] king_bitboard = { 0, 0, 0, 0, 64, 0, 0, 0, 0 }; bs.setBlack_bitboard(black_bitboard); bs.setWhite_bitboard(white_bitboard); bs.setKing_bitboard(king_bitboard); bs.setTurn(Turn.BLACK); String c = "BLACK"; Game game = new Game(c); Minmax minmax = new Minmax(game); List<Integer> action = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0)); action = minmax.makeDecision(10, bs, true); System.out.println("action = " + action.get(0) + " " + action.get(1) + " " + action.get(2) + " " + action.get(3) + " " + action.get(4)); BitState new_bs = new BitState(bs, action); int[] k_bitboard_expected = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertArrayEquals(k_bitboard_expected, new_bs.getKing_bitboard()); } @Test void capture_king_above_camp() throws IOException { BitState bs = new BitState(); int[] white_bitboard = { 256, 0, 0, 0, 0, 0, 0, 0, 0 }; int[] black_bitboard = { 0, 0, 1, 0, 0, 0, 0, 0, 0 }; int[] king_bitboard = { 0, 32, 0, 0, 0, 0, 0, 0, 0 }; bs.setBlack_bitboard(black_bitboard); bs.setWhite_bitboard(white_bitboard); bs.setKing_bitboard(king_bitboard); bs.setTurn(Turn.BLACK); String c = "BLACK"; Game game = new Game(c); Minmax minmax = new Minmax(game); List<Integer> action = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0)); action = minmax.makeDecision(10, bs, true); System.out.println("action = " + action.get(0) + " " + action.get(1) + " " + action.get(2) + " " + action.get(3) + " " + action.get(4)); BitState new_bs = new BitState(bs, action); int[] k_bitboard_expected = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertArrayEquals(k_bitboard_expected, new_bs.getKing_bitboard()); } @Test void capture_king_castle_with_alternative() throws IOException { BitState bs = new BitState(); int[] white_bitboard = { 0, 8, 0, 0, 0, 0, 0, 0, 0 }; int[] black_bitboard = { 0, 0, 0, 16, 32, 16, 0, 8, 0 }; int[] king_bitboard = { 0, 0, 0, 0, 16, 0, 0, 0, 0 }; bs.setBlack_bitboard(black_bitboard); bs.setWhite_bitboard(white_bitboard); bs.setKing_bitboard(king_bitboard); bs.setTurn(Turn.BLACK); String c = "BLACK"; Game game = new Game(c); Minmax minmax = new Minmax(game); List<Integer> action = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0)); action = minmax.makeDecision(10, bs, true); System.out.println("case: castle, action = " + action.get(0) + " " + action.get(1) + " " + action.get(2) + " " + action.get(3) + " " + action.get(4)); BitState new_bs = new BitState(bs, action); int[] k_bitboard_expected = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertArrayEquals(k_bitboard_expected, new_bs.getKing_bitboard()); } @Test void capture_king_next_to_castle() throws IOException { BitState bs = new BitState(); int[] white_bitboard = { 0, 8, 0, 0, 0, 18, 0, 0, 0 }; int[] black_bitboard = { 0, 0, 0, 8, 4, 0, 0, 8, 0 }; int[] king_bitboard = { 0, 0, 0, 0, 8, 0, 0, 0, 0 }; bs.setBlack_bitboard(black_bitboard); bs.setWhite_bitboard(white_bitboard); bs.setKing_bitboard(king_bitboard); bs.setTurn(Turn.BLACK); String c = "BLACK"; Game game = new Game(c); Minmax minmax = new Minmax(game); List<Integer> action = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0)); action = minmax.makeDecision(10, bs, true); System.out.println("case: castle, action = " + action.get(0) + " " + action.get(1) + " " + action.get(2) + " " + action.get(3) + " " + action.get(4)); BitState new_bs = new BitState(bs, action); int[] k_bitboard_expected = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertArrayEquals(k_bitboard_expected, new_bs.getKing_bitboard()); } @Test void game_position() throws IOException { BitState bs = new BitState(); int[] white_bitboard = { 0, 32, 0, 68, 96, 16, 16, 0, 0 }; int[] black_bitboard = { 56, 4, 0, 257, 385, 257, 0, 4, 33 }; int[] king_bitboard = { 0, 0, 0, 0, 16, 0, 0, 0, 0 }; bs.setBlack_bitboard(black_bitboard); bs.setWhite_bitboard(white_bitboard); bs.setKing_bitboard(king_bitboard); bs.setTurn(Turn.BLACK); String c = "BLACK"; Game game = new Game(c); Minmax minmax = new Minmax(game); List<Integer> action = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0)); action = minmax.makeDecision(20, bs, true); System.out.println("case: game, action = " + action.get(0) + " " + action.get(1) + " " + action.get(2) + " " + action.get(3) + " " + action.get(4)); BitState new_bs = new BitState(bs, action); int[] k_bitboard_expected = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertArrayEquals(k_bitboard_expected, new_bs.getKing_bitboard()); } } <file_sep>/tablut/state/tablut_state.py import numpy as np import copy from tablut.utils.state_utils import * from tablut.utils.bitboards import * class State: def __init__(self, json_string=None, second_init_args=None): """" s= original state, k == True -> king moves, k==False ->pawn moves start_row,start_col -> pieces coordinates end_row, end_col -> final coordinates """ if json_string is not None: self.white_bitboard = np.zeros(9, dtype=int) self.black_bitboard = np.zeros(9, dtype=int) self.king_bitboard = np.zeros(9, dtype=int) self.turn = json_string["turn"] i_row = 0 for row in json_string.get("board"): for col in row: self.white_bitboard[i_row] <<= 1 self.black_bitboard[i_row] <<= 1 self.king_bitboard[i_row] <<= 1 if col == "WHITE": self.white_bitboard[i_row] ^= 1 elif col == "BLACK": self.black_bitboard[i_row] ^= 1 elif col == "KING": self.king_bitboard[i_row] ^= 1 i_row += 1 pass elif second_init_args is not None: s = second_init_args[0] k = second_init_args[1] start_row = second_init_args[2] start_col = second_init_args[3] end_row = second_init_args[4] end_col = second_init_args[5] self.white_bitboard = copy.deepcopy(s.white_bitboard) self.black_bitboard = copy.deepcopy(s.black_bitboard) self.king_bitboard = copy.deepcopy(s.king_bitboard) if s.turn == "WHITE": "in the original state, white moves, so in the new state black moves" self.turn = "BLACK" if k is False: self.white_bitboard[start_row] -= (1 << (8 - start_col)) self.white_bitboard[end_row] += (1 << (8 - end_col)) else: self.king_bitboard[start_row] -= (1 << (8 - start_col)) self.king_bitboard[end_row] += (1 << (8 - end_col)) self.black_bitboard = white_tries_capture_black_pawn(self.white_bitboard + self.king_bitboard, self.black_bitboard, end_row, end_col) else: self.turn = "WHITE" self.black_bitboard[start_row] -= (1 << (8 - start_col)) self.black_bitboard[end_row] += (1 << (8 - end_col)) self.white_bitboard = black_tries_capture_white_pawn(self.black_bitboard, self.white_bitboard, end_row, end_col) self.king_bitboard = black_tries_capture_king(self.black_bitboard, self.king_bitboard, end_row, end_col) pass def check_victory(self): if np.count_nonzero(self.king_bitboard) == 0: "king captured" return -1 if np.count_nonzero(self.king_bitboard & escapes_bitboard) != 0: "king escaped" return 1 return 0 def compute_heuristic(self, weights, color): "victory condition, of course" victory_cond = self.check_victory() if victory_cond == -1 and color == "BLACK": # king captured and black player -> Win return MAX_VAL_HEURISTIC elif victory_cond == -1 and color == "WHITE": # King captured and white player -> Lose return -MAX_VAL_HEURISTIC elif victory_cond == 1 and color == "BLACK": # King escaped and black player -> Lose return -MAX_VAL_HEURISTIC elif victory_cond == 1 and color == "WHITE": # King escaped and white player -> Win return MAX_VAL_HEURISTIC "if the exits are blocked, white has a strong disadvantage" blocks_occupied_by_black = np.count_nonzero(self.black_bitboard & blocks_bitboard) blocks_occupied_by_white = np.count_nonzero(self.white_bitboard & blocks_bitboard) + \ np.count_nonzero(self.king_bitboard & blocks_bitboard) coeff_min_black = (-1) ** (color == "WHITE") coeff_min_white = (-1) ** (color == "BLACK") blocks_cond = coeff_min_black * weights[0] * blocks_occupied_by_black \ + coeff_min_white * weights[1] * blocks_occupied_by_white #open_blocks_cond = coeff_min_white * weights[2] * (8 - blocks_occupied_by_white - blocks_occupied_by_black) "remaining pieces are considered" white_cnt = 0 black_cnt = 0 for r in range(0, 9): for c in range(0, 9): curr_mask = 1 << (8 - c) if self.white_bitboard[r] & curr_mask != 0: white_cnt += 1 if self.black_bitboard[r] & curr_mask != 0: black_cnt += 1 remaining_whites_cond = coeff_min_white * weights[3] * white_cnt remaining_blacks_cond = coeff_min_black * weights[4] * black_cnt "aggressive king condition" ak_cond = coeff_min_white * weights[5] * self.open_king_paths() locked_camps_cond = coeff_min_white * weights[6] * self.locked_back_camps() h = blocks_cond + remaining_whites_cond + remaining_blacks_cond + ak_cond + locked_camps_cond return h def compute_heuristic_test(self, weights, color): "victory condition, of course" victory_cond = self.check_victory() if victory_cond == -1 and color == "BLACK": # king captured and black player -> Win return MAX_VAL_HEURISTIC, 0, 0, 0, 0 elif victory_cond == -1 and color == "WHITE": # King captured and white player -> Lose return -MAX_VAL_HEURISTIC, 0, 0, 0, 0 elif victory_cond == 1 and color == "BLACK": # King escaped and black player -> Lose return -MAX_VAL_HEURISTIC, 0, 0, 0, 0 elif victory_cond == 1 and color == "WHITE": # King escaped and white player -> Win return MAX_VAL_HEURISTIC, 0, 0, 0, 0 "if the exits are blocked, white has a strong disadvantage" blocks_occupied_by_black = np.count_nonzero(self.black_bitboard & blocks_bitboard) blocks_occupied_by_white = np.count_nonzero(self.white_bitboard & blocks_bitboard) + \ np.count_nonzero(self.king_bitboard & blocks_bitboard) coeff_min_black = (-1) ** (color == "WHITE") coeff_min_white = (-1) ** (color == "BLACK") blocks_cond = coeff_min_black * weights[0] * blocks_occupied_by_black \ + coeff_min_white * weights[1] * blocks_occupied_by_white open_blocks_cond = coeff_min_white * weights[2] * (8 - blocks_occupied_by_white - blocks_occupied_by_black) "remaining pieces are considered" white_cnt = 0 black_cnt = 0 for r in range(0, 9): for c in range(0, 9): curr_mask = 1 << (8 - c) if self.white_bitboard[r] & curr_mask != 0: white_cnt += 1 if self.black_bitboard[r] & curr_mask != 0: black_cnt += 1 remaining_whites_cond = coeff_min_white * weights[3] * white_cnt remaining_blacks_cond = coeff_min_black * weights[4] * black_cnt "aggressive king condition" ak_cond = coeff_min_white * weights[5] * self.open_king_paths() h = blocks_cond + remaining_whites_cond + remaining_blacks_cond + open_blocks_cond + ak_cond return blocks_cond, remaining_blacks_cond, remaining_whites_cond, open_blocks_cond, ak_cond def open_king_paths(self): "king coordinates" king_row = np.nonzero(self.king_bitboard)[0] king_bin_col = self.king_bitboard[king_row] king_col = int(8 - np.log2(king_bin_col)) "check for pawns/camps left and right" right_mask = 511 * np.ones(1, dtype=int) left_mask = (king_bin_col << 1) * np.ones(1, dtype=int) for col in range(0, king_col + 1): right_mask >>= 1 if col <= king_col - 2: left_mask ^= king_bin_col left_mask <<= 1 "check for pawns/camps up and down" above_the_column = [] below_the_column = [] for row in range(0, 9): if row != king_row and row < king_row: above_the_column += list(bit(camps_bitboard[row])) + list(bit(self.white_bitboard[row])) + list( bit(self.black_bitboard[row])) elif row != king_row and row > king_row: below_the_column += list(bit(camps_bitboard[row])) + list(bit(self.white_bitboard[row])) + list( bit(self.black_bitboard[row])) open_paths = 4 if (king_row in [3, 4, 5] or ((right_mask & self.white_bitboard[king_row]) + (right_mask & self.black_bitboard[king_row]) + (right_mask & camps_bitboard[king_row]) != 0)): open_paths -= 1 if (king_row in [3, 4, 5] or (left_mask & self.white_bitboard[king_row]) + (left_mask & self.black_bitboard[king_row]) + (left_mask & camps_bitboard[king_row]) != 0): open_paths -= 1 if king_col in [3, 4, 5] or king_bin_col in above_the_column: open_paths -= 1 if king_col in [3, 4, 5] or king_bin_col in below_the_column: open_paths -= 1 return open_paths def locked_back_camps(self): locked_camps = 0 hor_map = 0b000111000 if self.black_bitboard[0] & hor_map == 0b000111000: locked_camps += 1 if self.black_bitboard[8] & hor_map == 0b000111000: locked_camps += 1 row4 = list(bit(self.black_bitboard[3])) row5 = list(bit(self.black_bitboard[4])) row6 = list(bit(self.black_bitboard[5])) if 256 in row4 and 256 in row5 and 256 in row6: locked_camps += 1 if 2 in row4 and 2 in row5 and 2 in row6: locked_camps += 1 return locked_camps def get_hash(self): """ Returns an identifier for the state. Identifier is unique. """ turn = 1 if self.turn == "WHITE" else 0 return tuple(self.king_bitboard), tuple(self.white_bitboard), tuple(self.black_bitboard), turn <file_sep>/tablut/search/min_max.py """ Date: 07/11/2020 Author: <NAME> Implementation of minmax algorithm with alpha-beta pruning. """ import numpy as np import time from tablut.state.tablut_state import State from tablut.utils.state_utils import MAX_VAL_HEURISTIC, DRAW_POINTS from tablut.utils.common_utils import cont_pieces, MAX_NUM_CHECKERS #TODO: remove num_state_visited, use just in test phase def max_value(state, game, alpha, beta, depth, max_depth, time_start, state_hash_table, num_state_visited): num_state_visited[0] += 1 tmp_victory = state.check_victory() if tmp_victory == -1 and game.color == "BLACK": # king captured and black player -> Win return MAX_VAL_HEURISTIC elif tmp_victory == -1 and game.color == "WHITE": # King captured and white player -> Lose return -MAX_VAL_HEURISTIC elif tmp_victory == 1 and game.color == "BLACK": # King escaped and black player -> Lose return -MAX_VAL_HEURISTIC elif tmp_victory == 1 and game.color == "WHITE": # King escaped and white player -> Win return MAX_VAL_HEURISTIC state_hash = state.get_hash() index_checkers = MAX_NUM_CHECKERS-cont_pieces(state) hash_result = state_hash_table[index_checkers].get(state_hash) all_actions = None if hash_result is not None: if hash_result['used'] == 1: return -DRAW_POINTS if hash_result.get('all_actions') is not None: all_actions = hash_result.get('all_actions') if cutoff_test(depth, max_depth, game.max_time, time_start): # If reached maximum depth or total time if hash_result is not None and hash_result.get("value") is not None: return hash_result["value"] # If state previously evaluated don't recompute heuristic value = state.compute_heuristic(game.weights, game.color) # If state not previously evaluated add_to_hash(state_hash_table, state_hash, value, None, index_checkers) # Add state and value to hash table return value # Body v = -np.inf if all_actions is None: all_actions = game.produce_actions(state) if hash_result is not None: add_to_hash(state_hash_table, state_hash, hash_result['value'], all_actions, index_checkers) if len(all_actions) == 0: return -MAX_VAL_HEURISTIC for a in all_actions: v = max(v, min_value(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, alpha, beta, depth + 1, max_depth, time_start, state_hash_table, num_state_visited)) if v >= beta: return v alpha = max(alpha, v) return v def min_value(state, game, alpha, beta, depth, max_depth, time_start, state_hash_table, num_state_visited): num_state_visited[0] += 1 tmp_victory = state.check_victory() if tmp_victory == -1 and game.color == "BLACK": # king captured and black player -> Win return MAX_VAL_HEURISTIC elif tmp_victory == -1 and game.color == "WHITE": # King captured and white player -> Lose return -MAX_VAL_HEURISTIC elif tmp_victory == 1 and game.color == "BLACK": # King escaped and black player -> Lose return -MAX_VAL_HEURISTIC elif tmp_victory == 1 and game.color == "WHITE": # King escaped and white player -> Win return MAX_VAL_HEURISTIC state_hash = state.get_hash() index_checkers = MAX_NUM_CHECKERS-cont_pieces(state) hash_result = state_hash_table[index_checkers].get(state_hash) all_actions = None if hash_result is not None: if hash_result['used'] == 1: return -DRAW_POINTS if hash_result.get('all_actions') is not None: all_actions = hash_result.get('all_actions') if cutoff_test(depth, max_depth, game.max_time, time_start): # If reached maximum depth or total time if hash_result is not None and hash_result.get("value") is not None: return hash_result["value"] # If state previously evaluated don't recompute heuristic value = state.compute_heuristic(game.weights, game.color) # If state not previously evaluated add_to_hash(state_hash_table, state_hash, value, None, index_checkers) # Add state and value to hash table return value # Body v = np.inf if all_actions is None: all_actions = game.produce_actions(state) if hash_result is not None: add_to_hash(state_hash_table, state_hash, hash_result['value'], all_actions, index_checkers) if len(all_actions) == 0: return MAX_VAL_HEURISTIC for a in all_actions: v = min(v, max_value(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, alpha, beta, depth + 1, max_depth, time_start, state_hash_table, num_state_visited)) if v <= alpha: return v beta = min(beta, v) return v def add_to_hash(table, state_hash, value, all_actions, index_checkers): """ Adds current state and its value to hash table. """ table[index_checkers][state_hash] = {"value": value, "used": 0, 'all_actions': all_actions} def cutoff_test(depth, max_depth, max_time, time_start): """ Returns True if reached maximum depth or finished time False if search is to be continued """ if depth >= max_depth or time.time()-time_start >= max_time: return True return False def choose_action(state, game, state_hash_table): """ Search for the best action using min max with alpha beta pruning iteratively increasing the maximum depth. It stops only when available time is almost up. """ time_start = time.time() best_score_end = -np.inf beta = np.inf best_action = None best_action_end = None max_depth = 2 num_state_visited = [0] flag = False all_actions = game.produce_actions(state) # Getting all possible actions given state while time.time()-time_start < game.max_time: cont = 0 best_score = -np.inf for a in all_actions: v = min_value(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, best_score, beta, 1, max_depth, time_start, state_hash_table, num_state_visited) cont += 1 if v > best_score: best_score = v best_action = a if time.time()-time_start >= game.max_time: break # If search at current maximum depth is finished, update best action if cont == len(all_actions): best_score_end = best_score best_action_end = best_action flag = True print("Depth reached:", max_depth) elif flag: print("Depth reached:", max_depth-1) else: print("Minimum depth not reached") max_depth += 1 # Iteratively increasing depth print(num_state_visited, " state visited state in ", time.time()-time_start, " seconds.") return best_action_end, best_score_end <file_sep>/tablut/utils/hashtable.py class HashEntry: def __init__(self,key,value,actions,max_depth,current_depth): self.key =key self.value = value self.actions = actions self.forward_depth = max_depth-current_depth def get_key(self): return self.key def get_value(self): return self.value def get_actions(self): return self.actions def get_forward_depth(self): return self.forward_depth <file_sep>/src/thor/Game.java package thor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import it.unibo.ai.didattica.competition.tablut.domain.State.Turn; /** * @author <NAME>, <NAME> * Class used to create all possible actions given a state and turn. * */ public class Game { private int[][] possible_actions_hor = new int[9][9]; private int[][] possible_actions_ver = new int[9][9]; private String color; String getColor() { return this.color; } public Game(String color) { super(); this.color = color; this.possible_actions_hor[0][0] = 0b011000000; this.possible_actions_hor[0][1] = 0b101000000; this.possible_actions_hor[0][2] = 0b110000000; this.possible_actions_hor[0][3] = 0b111011111; this.possible_actions_hor[0][4] = 0b111101111; this.possible_actions_hor[0][5] = 0b111110111; this.possible_actions_hor[0][6] = 0b000000011; this.possible_actions_hor[0][7] = 0b000000101; this.possible_actions_hor[0][8] = 0b000000110; this.possible_actions_hor[1][0] = 0b011100000; this.possible_actions_hor[1][1] = 0b101100000; this.possible_actions_hor[1][2] = 0b110100000; this.possible_actions_hor[1][3] = 0b111000000; this.possible_actions_hor[1][4] = 0b111101111; this.possible_actions_hor[1][5] = 0b000000111; this.possible_actions_hor[1][6] = 0b000001011; this.possible_actions_hor[1][7] = 0b000001101; this.possible_actions_hor[1][8] = 0b000001110; this.possible_actions_hor[2][0] = 0b011111111; this.possible_actions_hor[2][1] = 0b101111111; this.possible_actions_hor[2][2] = 0b110111111; this.possible_actions_hor[2][3] = 0b111011111; this.possible_actions_hor[2][4] = 0b111101111; this.possible_actions_hor[2][5] = 0b111110111; this.possible_actions_hor[2][6] = 0b111111011; this.possible_actions_hor[2][7] = 0b111111101; this.possible_actions_hor[2][8] = 0b111111110; this.possible_actions_hor[3][0] = 0b011111110; this.possible_actions_hor[3][1] = 0b001111110; this.possible_actions_hor[3][2] = 0b010111110; this.possible_actions_hor[3][3] = 0b011011110; this.possible_actions_hor[3][4] = 0b011101110; this.possible_actions_hor[3][5] = 0b011110110; this.possible_actions_hor[3][6] = 0b011111010; this.possible_actions_hor[3][7] = 0b011111100; this.possible_actions_hor[3][8] = 0b011111110; this.possible_actions_hor[4][0] = 0b011100000; this.possible_actions_hor[4][1] = 0b101100000; this.possible_actions_hor[4][2] = 0b000100000; this.possible_actions_hor[4][3] = 0b001000000; this.possible_actions_hor[4][4] = 0b001101100; this.possible_actions_hor[4][5] = 0b000000100; this.possible_actions_hor[4][6] = 0b000001000; this.possible_actions_hor[4][7] = 0b000001101; this.possible_actions_hor[4][8] = 0b000001110; this.possible_actions_hor[5] = this.possible_actions_hor[3]; this.possible_actions_hor[6] = this.possible_actions_hor[2]; this.possible_actions_hor[7] = this.possible_actions_hor[1]; this.possible_actions_hor[8] = this.possible_actions_hor[0]; for (int i = 0; i < this.possible_actions_hor.length; i++) { for (int j = 0; j < this.possible_actions_hor[0].length; j++) { this.possible_actions_ver[j][i] = this.possible_actions_hor[i][j]; } } } public List<List<Integer>> produce_actions(BitState state) { List<List<Integer>> all_actions = new ArrayList<>(); int new_pos_mask = 0; if (state.getTurn() == Turn.WHITE) { int r = 0; while (state.getKing_bitboard()[r] == 0) // Searching king row r += 1; int tmp_r = 8 - r; int c = 0; int tmp_c = 8 - c; int curr_pos_mask = (1 << tmp_c); while ((state.getKing_bitboard()[r] & curr_pos_mask) != curr_pos_mask) { // Searching king column c += 1; tmp_c = (8 - c); curr_pos_mask = (1 << tmp_c); } // First look for actions that lead to escapes int poss_actions_mask = (~state.getWhite_bitboard()[r] & this.possible_actions_hor[r][c]); // Horizontal // actions poss_actions_mask &= (~state.getBlack_bitboard()[r]); int i = 1; List<List<Integer>> tmp_list = new ArrayList<>(); if (c != 0) { new_pos_mask = curr_pos_mask << i; while (i <= c && (poss_actions_mask & new_pos_mask) != 0) { // Actions to the left, checkers cannot jump tmp_list.add(new ArrayList<Integer>(Arrays.asList(1, r, c, r, c - i))); i += 1; if (i <= c) new_pos_mask = new_pos_mask << 1; } Collections.reverse(tmp_list); all_actions.addAll(tmp_list); } i = 1; tmp_list.clear(); if (c != 8) { new_pos_mask = (curr_pos_mask >> i); // Actions to the right, checkers cannot jump while (i <= tmp_c && (poss_actions_mask & new_pos_mask) != 0) { tmp_list.add(new ArrayList<Integer>(Arrays.asList(1, r, c, r, c + i))); i += 1; if (i <= tmp_c) new_pos_mask = new_pos_mask >> 1; } Collections.reverse(tmp_list); all_actions.addAll(tmp_list); } int white_column = Utils.build_column(state.getWhite_bitboard(), curr_pos_mask); // Building column given // position int black_column = Utils.build_column(state.getBlack_bitboard(), curr_pos_mask); curr_pos_mask = (1 << tmp_r); // Vertical actions poss_actions_mask = (~white_column & this.possible_actions_ver[r][c]); poss_actions_mask &= (~black_column); i = 1; tmp_list.clear(); if (r != 0) { new_pos_mask = curr_pos_mask << i; while (i <= r && (poss_actions_mask & new_pos_mask) != 0) { // Actions up, checkers cannot jump tmp_list.add(new ArrayList<Integer>(Arrays.asList(1, r, c, r - i, c))); i += 1; if (i <= r) new_pos_mask = new_pos_mask << 1; } Collections.reverse(tmp_list); all_actions.addAll(tmp_list); } i = 1; tmp_list.clear(); if (r != 8) { new_pos_mask = curr_pos_mask >> i; // Actions down, checkers cannot jump while (i <= tmp_r && (poss_actions_mask & new_pos_mask) != 0) { tmp_list.add(new ArrayList<Integer>(Arrays.asList(1, r, c, r + i, c))); i += 1; if (i <= tmp_r) new_pos_mask = new_pos_mask >> 1; } Collections.reverse(tmp_list); all_actions.addAll(tmp_list); } for (r = 0; r < state.getWhite_bitboard().length; r++) { // Searching white pawns if (state.getWhite_bitboard()[r] != 0) { tmp_r = 8 - r; for (c = 0; c < state.getWhite_bitboard().length; c++) { curr_pos_mask = (1 << (8 - c)); // Horizontal moves // If current position is occupied by a white pawn if ((state.getWhite_bitboard()[r] & curr_pos_mask) == curr_pos_mask) { tmp_c = 8 - c; poss_actions_mask = (~state.getWhite_bitboard()[r] & this.possible_actions_hor[r][c]); poss_actions_mask &= (~state.getKing_bitboard()[r]); poss_actions_mask &= (~state.getBlack_bitboard()[r]); i = 1; if (c != 0) { new_pos_mask = curr_pos_mask << i; // Actions to the left, checkers cannot jump while (i <= c && (poss_actions_mask & new_pos_mask) != 0) { all_actions.add(new ArrayList<Integer>(Arrays.asList(0, r, c, r, c - i))); i += 1; if (i <= c) new_pos_mask = new_pos_mask << 1; } } i = 1; if (c != 8) { new_pos_mask = curr_pos_mask >> i; // Actions to the right, checkers cannot jump while (i <= tmp_c && (poss_actions_mask & new_pos_mask) != 0) { all_actions.add(new ArrayList<Integer>(Arrays.asList(0, r, c, r, c + i))); i += 1; if (i <= tmp_c) new_pos_mask = new_pos_mask >> 1; } } white_column = Utils.build_column(state.getWhite_bitboard(), curr_pos_mask); // Building // column // given // position black_column = Utils.build_column(state.getBlack_bitboard(), curr_pos_mask); int king_column = Utils.build_column(state.getKing_bitboard(), curr_pos_mask); curr_pos_mask = (1 << tmp_r); // Vertical actions poss_actions_mask = (~white_column & this.possible_actions_ver[r][c]); poss_actions_mask &= (~black_column); poss_actions_mask &= (~king_column); i = 1; if (r != 0) { new_pos_mask = curr_pos_mask << i; // Actions up, checkers cannot jump while (i <= r && (poss_actions_mask & new_pos_mask) != 0) { all_actions.add(new ArrayList<Integer>(Arrays.asList(0, r, c, r - i, c))); i += 1; if (i <= r) new_pos_mask = new_pos_mask << 1; } } i = 1; if (r != 8) { new_pos_mask = curr_pos_mask >> i; // Actions down, checkers cannot jump while (i <= tmp_r && (poss_actions_mask & new_pos_mask) != 0) { all_actions.add(new ArrayList<Integer>(Arrays.asList(0, r, c, r + i, c))); i += 1; if (i <= tmp_r) new_pos_mask = new_pos_mask >> 1; } } } } } } } else if (state.getTurn() == Turn.BLACK) { int r = 0; int c = 0; int tmp_c = 0; int tmp_r = 0; for (r = 0; r < state.getBlack_bitboard().length; r++) { // Searching black pawns if (state.getBlack_bitboard()[r] != 0) { tmp_r = 8 - r; for (c = 0; c < state.getBlack_bitboard().length; c++) { int curr_pos_mask = (1 << (8 - c)); // Horizontal moves // If current position is occupied by a white pawn if ((state.getBlack_bitboard()[r] & curr_pos_mask) == curr_pos_mask) { tmp_c = 8 - c; int poss_actions_mask = (~state.getWhite_bitboard()[r] & this.possible_actions_hor[r][c]); poss_actions_mask &= (~state.getKing_bitboard()[r]); poss_actions_mask &= (~state.getBlack_bitboard()[r]); int i = 1; if (c != 0) { new_pos_mask = curr_pos_mask << i; // Actions to the left, checkers cannot jump while (i <= c && (poss_actions_mask & new_pos_mask) != 0) { all_actions.add(new ArrayList<Integer>(Arrays.asList(0, r, c, r, c - i))); i += 1; if (i <= c) new_pos_mask = new_pos_mask << 1; } } i = 1; if (c != 8) { new_pos_mask = curr_pos_mask >> i; // Actions to the right, checkers cannot jump while (i <= tmp_c && (poss_actions_mask & new_pos_mask) != 0) { all_actions.add(new ArrayList<Integer>(Arrays.asList(0, r, c, r, c + i))); i += 1; if (i <= tmp_c) new_pos_mask = new_pos_mask >> 1; } } int white_column = Utils.build_column(state.getWhite_bitboard(), curr_pos_mask); // Building // column // given // position int black_column = Utils.build_column(state.getBlack_bitboard(), curr_pos_mask); int king_column = Utils.build_column(state.getKing_bitboard(), curr_pos_mask); curr_pos_mask = 1 << tmp_r; // Vertical actions poss_actions_mask = (~white_column & this.possible_actions_ver[r][c]); poss_actions_mask &= (~black_column); poss_actions_mask &= (~king_column); i = 1; if (r != 0) { new_pos_mask = curr_pos_mask << i; // Actions up, checkers cannot jump while (i <= r && (poss_actions_mask & new_pos_mask) != 0) { all_actions.add(new ArrayList<Integer>(Arrays.asList(0, r, c, r - i, c))); i += 1; if (i <= r) new_pos_mask = new_pos_mask << 1; } } i = 1; if (r != 8) { new_pos_mask = curr_pos_mask >> i; // Actions down, checkers cannot jump while (i <= tmp_r && (poss_actions_mask & new_pos_mask) != 0) { all_actions.add(new ArrayList<Integer>(Arrays.asList(0, r, c, r + i, c))); i += 1; if (i <= tmp_r) new_pos_mask = new_pos_mask >> 1; } } } } } } } return all_actions; } } <file_sep>/tablut/utils/bitboards.py """ Constant bitboards: castle, escapes and camps. """ import numpy as np MAX_NUM_CHECKERS = 25 castle_bitboard = np.array([ 0b000000000, 0b000000000, 0b000000000, 0b000000000, 0b000010000, 0b000000000, 0b000000000, 0b000000000, 0b000000000], dtype=np.int) escapes_bitboard = np.array([ 0b011000110, 0b100000001, 0b100000001, 0b000000000, 0b000000000, 0b000000000, 0b100000001, 0b100000001, 0b011000110], dtype=np.int) camps_bitboard = np.array([ 0b000111000, 0b000010000, 0B000000000, 0b100000001, 0b110000011, 0b100000001, 0b000000000, 0b000010000, 0b000111000], dtype=np.int) blocks_bitboard = np.array([ 0b000000000, 0b001000100, 0b010000010, 0b000000000, 0b000000000, 0b000000000, 0b010000010, 0b001000100, 0b000000000], dtype=np.int) <file_sep>/tablut/test/test.py from tablut.search.game import Game from tablut.search.min_max import choose_action from tablut.state.tablut_state import * from tablut.test.future_min_max_test import * if __name__ == '__main__': board_string = [] board_string.append(str.split("SPACE SPACE SPACE BLACK BLACK BLACK SPACE SPACE SPACE")) board_string.append(str.split("SPACE SPACE SPACE SPACE BLACK SPACE SPACE SPACE SPACE")) board_string.append(str.split("SPACE SPACE SPACE SPACE WHITE SPACE SPACE SPACE SPACE")) board_string.append(str.split("BLACK SPACE SPACE SPACE WHITE SPACE SPACE SPACE BLACK")) board_string.append(str.split("BLACK BLACK WHITE WHITE KING WHITE WHITE BLACK BLACK")) board_string.append(str.split("BLACK SPACE SPACE SPACE WHITE SPACE SPACE SPACE SPACE")) board_string.append(str.split("SPACE SPACE SPACE SPACE WHITE SPACE SPACE SPACE SPACE")) board_string.append(str.split("SPACE SPACE SPACE SPACE BLACK SPACE SPACE SPACE SPACE")) board_string.append(str.split("SPACE SPACE SPACE BLACK BLACK BLACK SPACE SPACE SPACE")) json_string = {"turn": "BLACK", "board": board_string} print(json_string.get("turn")) game = Game(10, "BLACK", [70, 85, 99, 73, 66, 81, 1]) s = State(json_string) ht = {} state_hash_tables_tmp = [] for i in range(MAX_NUM_CHECKERS): state_hash_tables_tmp.append({}) state_hash_tables_tmp[i] = dict() state_hash_tables_tmp[0][s.get_hash()] = {"value": 0, 'used': 1} #a,v = choose_action(s,game,state_hash_tables_tmp) a, v = lazy_smp_process(s, game, ht) print(a) <file_sep>/tablut/utils/state_utils.py from tablut.utils.bitboards import * import numpy as np MAX_VAL_HEURISTIC = 5000 # TODO: to be set at maximum value achievable by heuristic DRAW_POINTS = MAX_VAL_HEURISTIC-1 def build_column(bitboard, mask): """ Builds column at given position. """ num = 0 for i in range(len(bitboard)): if bitboard[i] & mask != 0: num ^= 256 >> i return num def bit(n): mask = 0b000000001 i = 0 while i <= 8: b = n & mask yield b mask = mask << 1 i += 1 lut_positions = {1: 8, 2: 7, 4: 6, 8: 5, 16: 4, 32: 3, 64: 2, 128: 1, 256: 0} def step_rotate(bitboard): new_bitboard = np.zeros(9, dtype=int) col = 1 for r in bitboard: positions = np.unique(list(bit(r))) for p in positions: if p != 0: i = lut_positions.get(p) new_bitboard[i] ^= col col <<=1 return new_bitboard def black_tries_capture_white_pawn(black_bitboard, white_bitboard, row, col): binary_column = 1 << (8 - col) if row >= 2: "upwards capture" if binary_column in bit(white_bitboard[row - 1]): "a white pawn is above" if binary_column in bit(black_bitboard[row - 2] or binary_column in bit(camps_bitboard[row - 2]) \ or binary_column in bit(castle_bitboard[row - 2])): "capture is possible, proceed" white_bitboard[row - 1] ^= binary_column if col <= 6: "right capture" if (binary_column >> 1) in bit(white_bitboard[row]): "a white pawn is right" if (binary_column >> 2) in bit(black_bitboard[row]) or (binary_column >> 2) in bit(camps_bitboard[row]) \ or (binary_column >> 2) in bit(castle_bitboard[row]): white_bitboard[row] ^= binary_column >> 1 if row <= 6: "downwards capture" binary_column = 1 << (8 - col) if binary_column in bit(white_bitboard[row + 1]): "a white pawn is below" if binary_column in bit(black_bitboard[row + 2] or binary_column in bit(camps_bitboard[row + 2]) \ or binary_column in bit(castle_bitboard[row + 2])): "capture is possible, proceed" white_bitboard[row + 1] ^= binary_column if col >= 2: "left capture" if (binary_column << 1) in bit(white_bitboard[row]): "a white pawn is right" if (binary_column << 2) in bit(black_bitboard[row]) or (binary_column << 2) in bit(camps_bitboard[row]) \ or (binary_column << 2) in bit(castle_bitboard[row]): white_bitboard[row] ^= binary_column << 1 return white_bitboard def black_tries_capture_king(black_bitboard, king_bitboard, row, col): king_row = np.nonzero(king_bitboard)[0] king_col = int(8 - np.log2(king_bitboard[king_row])) if king_row in (0, 8) or king_col in (0, 8) \ or (row, col) not in ( (king_row, king_col + 1), (king_row, king_col - 1), (king_row + 1, king_col), (king_row - 1, king_col)): "the move does not attack the king, or the king cannot be attacked (last rows/cols)" return king_bitboard king_bin_col = (1 << (8 - king_col)) if king_row == 4 and king_col == 4: if 16 in bit(black_bitboard[king_row - 1]) and 16 in bit(black_bitboard[king_row + 1]) \ and 32 in bit(black_bitboard[king_row]) and 8 in bit(black_bitboard[king_row]): king_bitboard[king_row] = 0 elif king_row == 3 and king_col == 4: if 16 in bit(black_bitboard[king_row - 1]) \ and 32 in bit(black_bitboard[king_row]) and 8 in bit(black_bitboard[king_row]): king_bitboard[king_row] = 0 elif king_row == 4 and king_col == 5: if 8 in bit(black_bitboard[king_row - 1]) and 8 in bit(black_bitboard[king_row + 1]) \ and 4 in bit(black_bitboard[king_row]): king_bitboard[king_row] = 0 elif king_row == 5 and king_col == 4: if 16 in bit(black_bitboard[king_row + 1]) \ and 32 in bit(black_bitboard[king_row]) and 8 in bit(black_bitboard[king_row]): king_bitboard[king_row] = 0 elif king_row == 4 and king_col == 3: if 32 in bit(black_bitboard[king_row - 1]) and 32 in bit(black_bitboard[king_row + 1]) \ and 64 in bit(black_bitboard[king_row]): king_bitboard[king_row] = 0 elif king_row == row: other_col = 2 * king_col - col other_col_bin = 1 << (8 - other_col) if other_col_bin in bit(black_bitboard[king_row]): king_bitboard[king_row] = 0 else: other_row = 2 * king_row - row if king_bin_col in bit(black_bitboard[other_row]): king_bitboard[king_row] = 0 return king_bitboard def white_tries_capture_black_pawn(white_bitboard, black_bitboard, row, col): binary_column = 1 << (8 - col) if row >= 2: "upwards capture" if binary_column in bit(black_bitboard[row - 1]) and (row, col) != (2, 4): "a black pawn is above" if binary_column in bit(white_bitboard[row - 2] or binary_column in bit(camps_bitboard[row - 2]) \ or binary_column in bit(castle_bitboard[row - 2])): "capture is possible, proceed" black_bitboard[row - 1] ^= binary_column if col <= 6: "right capture" if (binary_column >> 1) in bit(black_bitboard[row]) and (row, col) != (4, 6): "a black pawn is right" if (binary_column >> 2) in bit(white_bitboard[row]) or (binary_column >> 2) in bit(camps_bitboard[row]) \ or (binary_column >> 2) in bit(castle_bitboard[row]): black_bitboard[row] ^= binary_column >> 1 if row <= 6: "downwards capture" binary_column = 1 << (8 - col) if binary_column in bit(black_bitboard[row + 1]) and (row, col) != (6, 4): "a black pawn is below" if binary_column in bit(white_bitboard[row + 2] or binary_column in bit(camps_bitboard[row + 2]) \ or binary_column in bit(castle_bitboard[row + 2])): "capture is possible, proceed" black_bitboard[row + 1] ^= binary_column if col >= 2: "left capture" if (binary_column << 1) in bit(black_bitboard[row]) and (row, col) != (4, 2): "a black pawn is left" if (binary_column << 2) in bit(white_bitboard[row]) or (binary_column << 2) in bit(camps_bitboard[row]) \ or (binary_column << 2) in bit(castle_bitboard[row]): black_bitboard[row] ^= binary_column << 1 return black_bitboard def action_to_server_format(action): """ Return format required by server. """ start_row = action[1] + 1 end_row = action[3] + 1 start_col = chr(65 + action[2]) end_col = chr(65 + action[4]) return { 'from': str(start_col) + str(start_row), 'to': str(end_col) + str(end_row) } <file_sep>/tablut/genetic/genetic_search.py """ Date: 16/11/2020 Author: <NAME> Population-based search for best weight of heuristic's component, using data obtained by random matches. """ import numpy as np import os import pickle from tablut.utils.state_utils import * from tablut.utils.bitboards import * from concurrent.futures import ProcessPoolExecutor N_POP = 500 # Number of solutions in population. N_PARAM = 6 # Number of parameter of each solution MAX_PARAM_VALUE = 300 # Maximum value allowed for each parameter MIN_PARAM_VALUE = 0 # Minimum value allowed for each parameter MAX_ITER = 1000 # Maximum number of iterations PERC_NEW_POP = .5 # Percentage of new individuals at each iteration EPS = 50 # Maximum change of each parameter due to mutation MAX_ITER_NO_BETTER = 10 # Maximum number of iterations without better solution N_PROC = 8 # Keep N_POP/N_PROC integer ERROR_ZERO = 0.05 def check_victory(state): if np.count_nonzero(state['king_bitboard']) == 0: "king captured" return -1 if np.count_nonzero(state['king_bitboard'] & escapes_bitboard) != 0: "king escaped" return 1 return 0 def open_king_paths(state): "king coordinates" king_row = np.nonzero(state['king_bitboard'])[0] king_bin_col = state['king_bitboard'][king_row] king_col = int(8 - np.log2(king_bin_col)) "check for pawns/camps left and right" right_mask = 511 * np.ones(1, dtype=int) left_mask = (king_bin_col << 1) * np.ones(1, dtype=int) for col in range(0, king_col+1): right_mask >>= 1 if col <= king_col - 2: left_mask ^= king_bin_col left_mask <<= 1 "check for pawns/camps up and down" above_the_column = [] below_the_column = [] for row in range(0, 9): if row != king_row and row < king_row: above_the_column += list(bit(camps_bitboard[row])) + list(bit(state['white_bitboard'][row])) + \ list(bit(state['black_bitboard'][row])) elif row != king_row and row > king_row: below_the_column += list(bit(camps_bitboard[row])) + list(bit(state['white_bitboard'][row])) + \ list(bit(state['black_bitboard'][row])) open_paths = 4 if (king_row in [3, 4, 5] or ((right_mask & state['white_bitboard'][king_row]) + (right_mask & state['black_bitboard'][king_row]) + (right_mask & camps_bitboard[king_row]) != 0)): open_paths -= 1 if (king_row in [3, 4, 5] or (left_mask & state['white_bitboard'][king_row]) + (left_mask & state['black_bitboard'][king_row]) + (left_mask & camps_bitboard[king_row]) != 0): open_paths -= 1 if king_col in [3, 4, 5] or king_bin_col in above_the_column: open_paths -= 1 if king_col in [3, 4, 5] or king_bin_col in below_the_column: open_paths -= 1 return open_paths def compute_heuristic(s, color, weights): state = {'king_bitboard': np.array(s[0], np.int), 'white_bitboard': np.array(s[1], np.int), 'black_bitboard': np.array(s[2], np.int)} "victory condition, of course" victory_cond = check_victory(state) if victory_cond == -1 and color == "BLACK": # king captured and black player -> Win return -1 elif victory_cond == -1 and color == "WHITE": # King captured and white player -> Lose return 1 elif victory_cond == 1 and color == "BLACK": # King escaped and black player -> Lose return 1 elif victory_cond == 1 and color == "WHITE": # King escaped and white player -> Win return -1 "if the exits are blocked, white has a strong disadvantage" blocks_occupied_by_black = np.count_nonzero(state['black_bitboard'] & blocks_bitboard) blocks_occupied_by_white = np.count_nonzero(state['white_bitboard'] & blocks_bitboard) + \ np.count_nonzero(state['king_bitboard'] & blocks_bitboard) coeff_min_black = (-1) ** (color == "BLACK") coeff_min_white = (-1) ** (color == "WHITE") blocks_cond = coeff_min_black * weights[0] * blocks_occupied_by_black \ + coeff_min_white * weights[1] * blocks_occupied_by_white open_blocks_cond = coeff_min_white * weights[2] * (8 - blocks_occupied_by_white - blocks_occupied_by_black) "remaining pieces are considered" white_cnt = 0 black_cnt = 0 for r in range(0, 9): for c in range(0, 9): curr_mask = 1 << (8 - c) if state['white_bitboard'][r] & curr_mask != 0: white_cnt += 1 if state['black_bitboard'][r] & curr_mask != 0: black_cnt += 1 remaining_whites_cond = coeff_min_white * weights[3] * white_cnt remaining_blacks_cond = coeff_min_black * weights[4] * black_cnt "aggressive king condition" ak_cond = coeff_min_white * weights[5] * open_king_paths(state) return_value = blocks_cond + remaining_whites_cond + remaining_blacks_cond + open_blocks_cond + ak_cond return return_value def eval_pop_thread(args): """ Evaluates solutions, returns a list of floats, between 0 and 1 (probabilities of survival and reproduction). """ m_solutions, m_state_hash_table, id_mi = args[0], args[1], args[2] step = int(N_POP/N_PROC) prob_surv = np.zeros(step) for index_sol in range(len(m_solutions)): print("Solution ", index_sol, " Id: ", id_mi) sol = m_solutions[index_sol] tmp_points = 0 max_sol = np.max(sol) for state_key in m_state_hash_table: state = m_state_hash_table[state_key] tmp_w = compute_heuristic(state_key, 'WHITE', sol) tmp_b = compute_heuristic(state_key, 'BLACK', sol) if tmp_w < 0 and state['value']['white'] / state['games'] > 0.5: tmp_points += 1 elif tmp_w > 0 and state['value']['black'] / state['games'] > 0.5: tmp_points += 1 elif 0+ERROR_ZERO * max_sol >= tmp_w >= 0-ERROR_ZERO * max_sol and \ state['value']['black'] / state['games'] < 0.5 and state['value']['white'] / state['games'] < 0.5: tmp_points += 1 if tmp_b < 0 and state['value']['black'] / state['games'] > 0.5: tmp_points += 1 elif tmp_b > 0 and state['value']['white'] / state['games'] > 0.5: tmp_points += 1 elif 0 + ERROR_ZERO * max_sol >= tmp_b >= 0-ERROR_ZERO * max_sol and \ state['value']['black'] / state['games'] < 0.5 and state['value']['white'] / state['games'] < 0.5: tmp_points += 1 tmp_points /= 2 prob_surv[index_sol] = tmp_points return prob_surv def eval_pop(solutions, m_state_hash_table): pool = ProcessPoolExecutor(N_PROC) step = int(len(solutions)/N_PROC) args_list = [] for i_m in range(N_PROC): args_list.append((solutions[step*i_m: step*i_m+step], m_state_hash_table, i_m)) prob_surv_m = [] for s_list in pool.map(eval_pop_thread, args_list): prob_surv_m += list(s_list) prob_surv_m = np.array(prob_surv_m) prob_surv_m /= len(m_state_hash_table) print(prob_surv_m) return prob_surv_m def mate(sol1, sol2): """ Create a new individual by applying crossover. Linear combination with random weights between 0 and 1 """ lambda_1 = np.random.rand() lambda_2 = np.random.rand() m_newborn = [] for x in range(N_PARAM): new_value = lambda_1*sol1[x] + lambda_2*sol2[x] if new_value > MAX_PARAM_VALUE: new_value = MAX_PARAM_VALUE elif new_value < MIN_PARAM_VALUE: new_value = MIN_PARAM_VALUE m_newborn.append(new_value) return m_newborn def add_newborn(m_newborn, solutions, prob_surv): """ Removing solution based on strength to make room for new individual. """ index_remove = np.random.randint(0, N_POP) while np.random.rand() <= prob_surv[index_remove]: index_remove = np.random.randint(0, N_POP) solutions[index_remove] = m_newborn def mutations(solutions, prob_surv): """ Mutating individuals based on their probability of survival. """ for j in range(N_POP): number_poss_mutations = np.random.randint(1, N_PARAM+1) # Choosing number of possible mutations for k in range(number_poss_mutations): param_index = np.random.randint(0, N_PARAM) # Choosing parameter to mutate random_mutation = np.random.rand() if random_mutation > prob_surv[j]: if np.random.rand() > 0.5: solutions[j][param_index] += int((random_mutation-prob_surv[j])*EPS) if solutions[j][param_index] > MAX_PARAM_VALUE: solutions[j][param_index] = MAX_PARAM_VALUE elif solutions[j][param_index] < MIN_PARAM_VALUE: solutions[j][param_index] = MIN_PARAM_VALUE else: solutions[j][param_index] -= int((random_mutation - prob_surv[j]) * EPS) if solutions[j][param_index] > MAX_PARAM_VALUE: solutions[j][param_index] = MAX_PARAM_VALUE elif solutions[j][param_index] < MIN_PARAM_VALUE: solutions[j][param_index] = MIN_PARAM_VALUE exists = os.path.isfile('state_hash') if exists: file = open("state_hash", "rb") state_hash_table = pickle.load(file) file.close() num_iter = 0 population = [] for i in range(N_POP): # Randomly initializing population population.append([np.random.randint(MIN_PARAM_VALUE, MAX_PARAM_VALUE+1) for x in range(N_PARAM)]) prob_survival = eval_pop(population, state_hash_table) # First evaluation of pop best_sol = [] best_sol_prob = 0.0 no_best_sol = 0 while num_iter <= MAX_ITER and no_best_sol <= MAX_ITER_NO_BETTER: i = 0 while i <= PERC_NEW_POP*N_POP: index_par1 = np.random.randint(0, N_POP) # Picking random parents while np.random.rand() > prob_survival[index_par1]: index_par1 = np.random.randint(0, N_POP) # Choosing parents based on their strength index_par2 = np.random.randint(0, N_POP) while index_par2 == index_par1 or np.random.rand() > prob_survival[index_par2]: index_par2 = np.random.randint(0, N_POP) newborn = mate(population[index_par1], population[index_par2]) # Creating new individual add_newborn(newborn, population, prob_survival) # Add new individual by removing less strong old ones i += 1 mutations(population, prob_survival) # Mutations hit less strong individual with higher probability prob_survival = eval_pop(population, state_hash_table) # Population evaluation best_sol_find_index = int(np.argmax(prob_survival)) if best_sol_prob < prob_survival[best_sol_find_index]: best_sol = population[best_sol_find_index] best_sol_prob = prob_survival[best_sol_find_index] no_best_sol = 0 print("Best sol: ", population[best_sol_find_index]) print("Value: ", prob_survival[best_sol_find_index]) print("Iteration: ", num_iter) num_iter += 1 no_best_sol += 1 print(best_sol_prob) print(best_sol) <file_sep>/random_player_white.py """ Date: 07/11/2020 Author: <NAME> Implementation of minmax algorithm with alpha-beta pruning. """ from tablut.state.tablut_state import State from tablut.client.connection_handler import ConnectionHandler from tablut.search.game import Game from tablut.search.min_max_parallel import choose_action from tablut.utils.state_utils import action_to_server_format from tablut.utils.common_utils import clear_hash_table, update_used, MAX_NUM_CHECKERS import pickle import os class Client(ConnectionHandler): """Extends ConnectionHandler, handling the connection between client and server.""" def __init__(self, port, color, max_time, host="localhost", weights=None, name='WHITE_RANDOM', file_access=False): super().__init__(port, host) self.color = color self.max_time = max_time self.player_name = name self.weights = weights self.file_access = file_access self.game = Game(self.max_time, self.color, self.weights) self.state_hash_tables_tmp = dict() for i in range(MAX_NUM_CHECKERS): self.state_hash_tables_tmp[i] = dict() def run(self): """Client's body.""" if self.file_access: exists = os.path.isfile('state_hash') if exists: file = open("state_hash", "rb") state_hash_table = pickle.load(file) file.close() else: state_hash_table = dict() state_list = [] id_win = None try: self.connect() self.send_string(self.player_name) state = State(self.read_string()) self.state_hash_tables_tmp[0][state.get_hash()] = {"value": 0, 'used': 1} while True: # Playing if self.color == state.turn: # check turn action, value = choose_action(state, self.game, self.state_hash_tables_tmp) # Retrieving best action and its value and pass weights self.send_string(action_to_server_format(action)) print("Choosen action value:", value) else: clear_hash_table(self.state_hash_tables_tmp, state) state_server = self.read_string() state = State(state_server) blocks_cond, remaining_blacks_cond, remaining_whites_cond, open_blocks_cond, ak_cond = \ state.compute_heuristic_test(self.game.weights, self.game.color) print(self.game.color, blocks_cond, remaining_blacks_cond, remaining_whites_cond, open_blocks_cond, ak_cond) if state_server['turn'] == "WHITEWIN": id_win = "WHITE" break elif state_server['turn'] == "BLACKWIN": id_win = "BLACK" break elif state_server['turn'] == "DRAW": id_win = "DRAW" break if self.file_access: state_list.append(state) update_used(self.state_hash_tables_tmp, state, self.game.weights, self.game.color) except Exception as e: print(e) finally: if self.file_access: for state in state_list: state_hash = state.get_hash() hash_result = state_hash_table.get(state_hash) if hash_result is not None: if id_win == "WHITE": hash_result["value"]["white"] += 1 elif id_win == "BLACK": hash_result["value"]["black"] += 1 elif id_win == "DRAW": hash_result["value"]["black"] += 0.3 hash_result["value"]["white"] += 0.3 hash_result["games"] += 1 else: value = dict() if id_win == "WHITE": value["white"] = 1 value["black"] = 0 elif id_win == "BLACK": value["black"] = 1 value["white"] = 0 elif id_win == "DRAW": value["black"] = 0.3 value["white"] = 0.3 add_to_hash(state_hash_table, state_hash, value, self.game.produce_actions(state)) # Add state and value to hash table file = open("state_hash", "wb") pickle.dump(state_hash_table, file) file.close() print("Game ended.") def add_to_hash(table, state_hash, value, all_actions): """ Adds current state and its value to hash table. """ table[state_hash] = {"value": value, "games": 1, "all_actions": all_actions} <file_sep>/tablut/utils/common_utils.py from tablut.utils.bitboards import MAX_NUM_CHECKERS def clear_hash_table(state_hash_tables, state): index_hash = MAX_NUM_CHECKERS - cont_pieces(state) - 1 while index_hash >= 0 and state_hash_tables.get(index_hash) is not None: state_hash_tables.pop(index_hash) index_hash -= 1 def cont_pieces(state): cnt = 0 for r in range(0, 9): for c in range(0, 9): curr_mask = 256 >> c if state.white_bitboard[r] & curr_mask != 0: cnt += 1 elif state.black_bitboard[r] & curr_mask != 0: cnt += 1 elif state.king_bitboard[r] & curr_mask != 0: cnt += 1 return cnt def update_used(state_hash_table, state, weights, color): """ Adds current state and its value to hash table. """ state_hash = state.get_hash() index_hash = MAX_NUM_CHECKERS - cont_pieces(state) hash_result = state_hash_table[index_hash].get(state_hash) if hash_result is not None: state_hash_table[index_hash][state_hash]['used'] = 1 else: state_hash_table[index_hash][state_hash] = {"value": state.compute_heuristic(weights, color), "used": 1} <file_sep>/tablut/search/min_max_parallel_2.py """ Date: 07/11/2020 Author: <NAME> Implementation of minmax algorithm with alpha-beta pruning. """ import numpy as np import time from tablut.state.tablut_state import State from tablut.utils.state_utils import MAX_VAL_HEURISTIC from threading import Thread, Lock lock_2 = Lock() #TODO: remove num_state_visited, use just in test phase def max_value(state, game, alpha, beta, depth, max_depth, time_start, state_hash_table, id_m, v, lock_p): lock_2.acquire() state_hash = state.get_hash() hash_result = state_hash_table.get(state_hash) lock_2.release() all_actions = None if hash_result is not None: if hash_result['used'] == 1: v[id_m] = 0 return if hash_result.get('all_actions') is not None: all_actions = hash_result.get('all_actions') if cutoff_test(depth, max_depth, game.max_time, time_start): # If reached maximum depth or total time if hash_result is not None: v[id_m] = hash_result["value"] # If state previously evaluated don't recompute heuristic return value = state.compute_heuristic(game.weights, game.color) # If state not previously evaluated lock_2.acquire() add_to_hash(state_hash_table, state_hash, value, all_actions) # Add state and value to hash table lock_2.release() v[id_m] = value return tmp_victory = state.check_victory() if tmp_victory == -1 and game.color == "BLACK": # king captured and black player -> Win v[id_m] = -MAX_VAL_HEURISTIC return elif tmp_victory == -1 and game.color == "WHITE": # King captured and white player -> Lose v[id_m] = MAX_VAL_HEURISTIC return elif tmp_victory == 1 and game.color == "BLACK": # King escaped and black player -> Lose v[id_m] = MAX_VAL_HEURISTIC return elif tmp_victory == 1 and game.color == "WHITE": # King escaped and white player -> Win v[id_m] = -MAX_VAL_HEURISTIC return # Body if all_actions is None: all_actions = game.produce_actions(state) if hash_result is not None: add_to_hash(state_hash_table, state_hash, hash_result['value'], all_actions) if len(all_actions) == 0: return -MAX_VAL_HEURISTIC return_values = [np.inf for x in range(len(all_actions))] lock_p.acquire() best_score = [alpha[0]] lock_p.release() thread_list = [] lock_m = Lock() a = all_actions[0] thread = Thread(target=min_value, args=(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, best_score, beta, depth + 1, max_depth, time_start, state_hash_table, 0, return_values, lock_m)) thread.start() thread.join() if return_values[0] > best_score[0]: best_score[0] = return_values[0] for i in range(len(all_actions[1:int(len(all_actions)/2)])): a = all_actions[i] lock_p.acquire() if alpha[0] > best_score[0]: best_score[0] = alpha[0] lock_p.release() thread_list.append(Thread(target=min_value, args=(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, best_score, beta, depth + 1, max_depth, time_start, state_hash_table, i, return_values, lock_m))) thread_list[i].start() flag_t = True while flag_t: flag_t = False for i in range(len(thread_list)): if not thread_list[i].is_alive(): lock_m.acquire() if return_values[i] >= beta[0]: v[id_m] = return_values[i] lock_m.release() return best_score[0] = max(best_score[0], return_values[i]) lock_m.release() else: flag_t = True for i in range(len(thread_list)): thread_list[i].join() thread_list = [] for i in range(len(all_actions[int(len(all_actions)/2)+1:])): a = all_actions[i] lock_p.acquire() if alpha[0] > best_score[0]: best_score[0] = alpha[0] lock_p.release() thread_list.append(Thread(target=min_value, args=(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, best_score, beta, depth + 1, max_depth, time_start, state_hash_table, i, return_values, lock_m))) thread_list[i].start() flag_t = True while flag_t: flag_t = False for i in range(len(thread_list)): if not thread_list[i].is_alive(): lock_m.acquire() if return_values[i] >= beta[0]: v[id_m] = return_values[i] lock_m.release() return best_score[0] = max(best_score[0], return_values[i]) lock_m.release() else: flag_t = True for i in range(len(thread_list)): thread_list[i].join() v[id_m] = return_values[-1] return def min_value(state, game, alpha, beta, depth, max_depth, time_start, state_hash_table, id_m, v, lock_p): lock_2.acquire() state_hash = state.get_hash() hash_result = state_hash_table.get(state_hash) lock_2.release() all_actions = None if hash_result is not None: if hash_result['used'] == 1: v[id_m] = 0 return if hash_result.get('all_actions') is not None: all_actions = hash_result.get('all_actions') if cutoff_test(depth, max_depth, game.max_time, time_start): # If reached maximum depth or total time if hash_result is not None: v[id_m] = hash_result["value"] # If state previously evaluated don't recompute heuristic return value = state.compute_heuristic(game.weights, game.color) # If state not previously evaluated lock_2.acquire() add_to_hash(state_hash_table, state_hash, value, all_actions) # Add state and value to hash table lock_2.release() v[id_m] = value return tmp_victory = state.check_victory() if tmp_victory == -1 and game.color == "BLACK": # king captured and black player -> Win v[id_m] = -MAX_VAL_HEURISTIC return elif tmp_victory == -1 and game.color == "WHITE": # King captured and white player -> Lose v[id_m] = MAX_VAL_HEURISTIC return elif tmp_victory == 1 and game.color == "BLACK": # King escaped and black player -> Lose v[id_m] = MAX_VAL_HEURISTIC return elif tmp_victory == 1 and game.color == "WHITE": # King escaped and white player -> Win v[id_m] = -MAX_VAL_HEURISTIC return # Body if all_actions is None: all_actions = game.produce_actions(state) if hash_result is not None: add_to_hash(state_hash_table, state_hash, hash_result['value'], all_actions) if len(all_actions) == 0: v[id_m] = MAX_VAL_HEURISTIC return return_values = [-np.inf for x in range(len(all_actions))] lock_p.acquire() best_score = [beta[0]] lock_p.release() thread_list = [] lock_m = Lock() a = all_actions[0] thread = Thread(target=max_value, args=(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, alpha, best_score, depth+1, max_depth, time_start, state_hash_table, 0, return_values, lock_m)) thread.start() thread.join() if return_values[0] < best_score[0]: best_score[0] = return_values[0] for i in range(len(all_actions[1:int(len(all_actions)/2)])): a = all_actions[i] lock_p.acquire() if beta[0] < best_score[0]: best_score[0] = beta[0] lock_p.release() thread_list.append(Thread(target=max_value, args=(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, alpha, best_score, depth+1, max_depth, time_start, state_hash_table, i, return_values, lock_m))) thread_list[i].start() flag_t = True while flag_t: flag_t = False for i in range(len(thread_list)): if not thread_list[i].is_alive(): lock_m.acquire() if return_values[i] <= alpha[0]: v[id_m] = return_values[i] lock_m.release() return best_score[0] = min(best_score[0], return_values[i]) lock_m.release() else: flag_t = True for i in range(len(thread_list)): thread_list[i].join() thread_list = [] for i in range(len(all_actions[int(len(all_actions)/2)+1:])): a = all_actions[i] lock_p.acquire() if beta[0] < best_score[0]: best_score[0] = beta[0] lock_p.release() thread_list.append(Thread(target=max_value, args=(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, alpha, best_score, depth+1, max_depth, time_start, state_hash_table, i, return_values, lock_m))) thread_list[i].start() flag_t = True while flag_t: flag_t = False for i in range(len(thread_list)): if not thread_list[i].is_alive(): lock_m.acquire() if return_values[i] <= alpha[0]: v[id_m] = return_values[i] lock_m.release() return best_score[0] = min(best_score[0], return_values[i]) lock_m.release() else: flag_t = True for i in range(len(thread_list)): thread_list[i].join() v[id_m] = return_values[-1] return def add_to_hash(table, state_hash, value, all_actions): """ Adds current state and its value to hash table. """ table[state_hash] = {"value": value, "used": 0, 'all_actions': all_actions} def update_used(state_hash_table, state, weights, color): """ Adds current state and its value to hash table. """ state_hash = state.get_hash() hash_result = state_hash_table.get(state_hash) if hash_result is not None: state_hash_table[state_hash]['used'] = 1 else: state_hash_table[state_hash] = {"value": state.compute_heuristic(weights, color), "used": 1} def cutoff_test(depth, max_depth, max_time, time_start): """ Returns True if reached maximum depth or finished time False if search is to be continued """ if depth >= max_depth or time.time()-time_start >= max_time: return True return False def choose_action(state, game, state_hash_table): """ Search for the best action using min max with alpha beta pruning iteratively increasing the maximum depth. It stops only when available time is almost up. """ time_start = time.time() all_actions = game.produce_actions(state) # Getting all possible actions given state best_score = [np.inf] best_score_end = np.inf alpha = [-np.inf] best_action = None best_action_end = None max_depth = 2 flag = False lock_m = Lock() return_values = [-np.inf for x in range(len(all_actions))] while time.time()-time_start < game.max_time: thread_list = [] if len(all_actions) > 0: a = all_actions[0] thread_list.append(Thread(target=max_value, args=(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, alpha, best_score, 1, max_depth, time_start, state_hash_table, 0, return_values, lock_m))) thread_list[0].start() thread_list[0].join() if return_values[0] < best_score[0]: best_score[0] = return_values[0] best_action = a for i in range(len(all_actions[1:])): a = all_actions[i+1] thread_list.append(Thread(target=max_value, args=(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, alpha, best_score, 1, max_depth, time_start, state_hash_table, i+1, return_values, lock_m))) thread_list[i+1].start() flag_t = True flag_time = False while flag_t and not flag_time: flag_t = False for i in range(len(all_actions)): if not thread_list[i].is_alive(): lock_m.acquire() if return_values[i] < best_score[0]: best_score[0] = return_values[i] best_action = all_actions[i] lock_m.release() else: flag_t = True if time.time() - time_start >= game.max_time: flag_time = True for i in range(len(thread_list)): thread_list[i].join() if not flag_time: best_score_end = best_score[0] best_action_end = best_action flag = True print("Depth reached:", max_depth) elif flag: print("Depth reached:", max_depth - 1) else: print("Minimum depth not reached") max_depth += 1 # Iteratively increasing depth return best_action_end, best_score_end <file_sep>/show_mc_data.py """ Date: 07/11/2020 Author: <NAME> """ import pickle import os exists = os.path.isfile('state_hash') if exists: file = open("state_hash", "rb") state_hash_table = pickle.load(file) file.close() point_white = 0 point_black = 0 games = 0 for state in state_hash_table.values(): point_white += state['value']['white'] point_black += state['value']['black'] games += state['games'] tmp_white_p = state['value']['white'] / state['games'] tmp_black_p = state['value']['black'] / state['games'] print("White: ", tmp_white_p, " Black: ", tmp_black_p, " Draw: ", 1-tmp_black_p-tmp_white_p) print("Points over total number of matches:") print("Total Black: ", point_black / games) print("Total White: ", point_white / games) else: print("File doesn't exist.") <file_sep>/tablut/genetic/tournament_search.py """ Date: 05/11/2020 Author: <NAME> & <NAME> Population-based search for best weight of heuristic's component. """ from tablut.client.tablut_client import Client from multiprocessing import Pool import subprocess import numpy as np import time from itertools import permutations from multiprocessing import Queue q = Queue() N_PARAM = 6 # Number of parameter of each solution MAX_TIME_ACTION = 5 # Maximum time allowed to search for action NUM_MATCH = 4 PARAMS = [20, 30, 30, 20, 20, 100] def create_play_player(port, color, max_time_act, weights, name, host, args=None): client_m = Client(port, color, max_time_act, weights=weights, name=name, host=host) client_m.run(args) def eval_match(sol1, sol2): """ Starts two matches between a couple of solutions, returns point earned by each one. """ sol1_points = 0 sol2_points = 0 result = [] pool = Pool() proc = subprocess.Popen(['ant', 'server']) # Requires server files in path time.sleep(2) white_thread = pool.apply_async(create_play_player, args=(5800, "WHITE", MAX_TIME_ACTION, sol1, "sol1", "127.0.0.1", result)) # Important, pass list just to one of the two threads, to avoid synchronization problems black_thread = pool.apply_async(create_play_player, args=(5801, "BLACK", MAX_TIME_ACTION, sol2, "sol2", "127.0.0.1", result)) black_thread.wait() white_thread.wait() pool.close() while not q.empty(): result.append(q.get()) proc.wait() proc.terminate() if len(result) > 0 and result[0] == "WHITE": sol1_points += 3 elif len(result) > 0 and result[0] == "BLACK": sol2_points += 3 else: sol1_points += 1 sol2_points += 1 result = [] pool = Pool() proc = subprocess.Popen(['ant', 'server']) # Requires server files in path time.sleep(2) white_thread = pool.apply_async(create_play_player, args=(5800, "WHITE", MAX_TIME_ACTION, sol2, "sol2", "127.0.0.1", result)) # Important, pass list just to one of the two threads, to avoid synchronization problems black_thread = pool.apply_async(create_play_player, args=(5801, "BLACK", MAX_TIME_ACTION, sol1, "sol1", "127.0.0.1", result)) black_thread.wait() white_thread.wait() while not q.empty(): result.append(q.get()) pool.close() proc.wait() proc.terminate() if len(result) > 0 and result[0] == "WHITE": sol2_points += 3 elif len(result) > 0 and result[0] == "BLACK": sol1_points += 3 else: sol2_points += 1 sol1_points += 1 return sol1_points, sol2_points def eval_pop(): """ Evaluates solutions, returns a list of floats, between 0 and 1 (probabilities of survival and reproduction). """ solutions = [[2, 1, 2, 1, 1, 100]] solutions_tmp = list(permutations(PARAMS)) for sol in solutions_tmp: if sol not in solutions: solutions.append(sol) print(len(solutions)) dones = [[] for x in range(len(solutions))] points = np.zeros(len(solutions)) for i in range(len(solutions)): for y in range(len(solutions)): if len(dones[i]) >= NUM_MATCH: break if y != i and y not in dones[i]: dones[i].append(y) dones[y].append(i) tmp_p_1, tmp_p_2 = eval_match(solutions[i], solutions[y]) points[i] += tmp_p_1 points[y] += tmp_p_2 print("MATCH BETWEEN ", i, " AND ", y, " RESULT: ", tmp_p_1, " - ", tmp_p_2) print("Results:") for i in range(len(solutions)): print("Solution ", solutions[i], " Points ", points[i]) eval_pop() <file_sep>/tablut/client/connection_handler.py import json import socket class ConnectionHandler: """Manages the connection between client and server""" def __init__(self, port=80, host="localhost"): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.port = port self.host = host def connect(self): """Connect to the server. Throws Exception in case of error""" try: self.socket.connect((self.host, self.port)) return self except socket.error: print("Can't connect to host: %s at port: %d" % (self.host, self.port)) def disconnect(self): """Disconnect the client.""" self.socket.close() return self def send_int(self, integer): """Send an integer value to the server.""" bytes_to_send = integer.to_bytes(4, byteorder='big') return self.socket.send(bytes_to_send) # Send the integer, converted in bytes, to the server def send_string(self, message): """Send a string value, converted to json, to the server.""" message = json.dumps(message) # Convert message to JSON self.send_int(len(message)) # Send message length to the server self.socket.sendall(message.encode()) # Send the string to the server return self def read_string(self): """Return a string value sent by the server converted in json format.""" string_length = self.read_int() # Read the length of the string from an integer sent by the server itself message = self.socket.recv(string_length, socket.MSG_WAITALL) # Read the actual string message = message.decode('utf-8') # Decode the message return json.loads(message) # Convert object to JSON def read_int(self): """Return an integer value sent by the server.""" read_bytes = b'' # Create empty bytes while len(read_bytes) < 4: # Wait for all the bytes data = self.socket.recv(4 - len(read_bytes)) if not data: break read_bytes += data return int.from_bytes(read_bytes, byteorder='big') # Converts bytes to int <file_sep>/src/thor/BitState.java package thor; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import it.unibo.ai.didattica.competition.tablut.domain.State; import it.unibo.ai.didattica.competition.tablut.domain.State.Pawn; import it.unibo.ai.didattica.competition.tablut.domain.State.Turn; /** * @author <NAME>, <NAME> * @implNote Class that represents a state as three bitboards and turn. * */ public class BitState { private int[] white_bitboard = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private int[] black_bitboard = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private int[] king_bitboard = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private Turn turn = null; private int[][] lut_white = { { -Utils.MAX_VAL_HEURISTIC, 50, 100, 150, 200, 250, 340, 390, 420, 450 }, // Remaining // white { Utils.MAX_VAL_HEURISTIC, -30, -60, -90, -120, -150, -180, -210, -240, -270, -300, -330, -400, -420, -440, -460, -480 }, // Remaining black { -600, -200, -100, -30, -20, 40, 50, 80, 100 }, // Open diagonal blocks { 0, 200, 500, 1000, Utils.MAX_VAL_HEURISTIC }, // Aggressive king, number of path open to escapes { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195 } // Blocks occupied by white }; private int[][] lut_black = { { -110, -95, -90, -75, -60, -45, -30, -15, 0 } // wings in camps }; /** * @param state State in server format */ public BitState(State state) { this.turn = state.getTurn(); for (int row = 0; row < state.getBoard().length; row++) { for (int col = 0; col < state.getBoard().length; col++) { this.white_bitboard[row] <<= 1; this.black_bitboard[row] <<= 1; this.king_bitboard[row] <<= 1; if (state.getPawn(row, col).equalsPawn(Pawn.WHITE.toString())) this.white_bitboard[row] ^= 1; else if (state.getPawn(row, col).equalsPawn(Pawn.BLACK.toString())) this.black_bitboard[row] ^= 1; else if (state.getPawn(row, col).equalsPawn(Pawn.KING.toString())) this.king_bitboard[row] ^= 1; } } } public int[] getWhite_bitboard() { return white_bitboard.clone(); } public int[] getBlack_bitboard() { return black_bitboard.clone(); } public int[] getKing_bitboard() { return king_bitboard.clone(); } Turn getTurn() { return turn; } // used for testing public BitState() { } public void setWhite_bitboard(int[] white_bitboard) { this.white_bitboard = white_bitboard; } public void setBlack_bitboard(int[] black_bitboard) { this.black_bitboard = black_bitboard; } public void setKing_bitboard(int[] king_bitboard) { this.king_bitboard = king_bitboard; } public void setTurn(Turn turn) { this.turn = turn; } /** * @param s Old state * @param action Action to be performed */ public BitState(BitState s, List<Integer> action) { int k = action.get(0); int start_row = action.get(1); int start_col = action.get(2); int end_row = action.get(3); int end_col = action.get(4); int[] tmp_bitboard = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; this.white_bitboard = s.getWhite_bitboard(); this.black_bitboard = s.getBlack_bitboard(); this.king_bitboard = s.getKing_bitboard(); if (s.turn == Turn.WHITE) { this.turn = Turn.BLACK; if (k == 0) { this.white_bitboard[start_row] -= (1 << (8 - start_col)); this.white_bitboard[end_row] += (1 << (8 - end_col)); } else { this.king_bitboard[start_row] -= (1 << (8 - start_col)); this.king_bitboard[end_row] += (1 << (8 - end_col)); } for (int i = 0; i < this.king_bitboard.length; i++) { tmp_bitboard[i] = this.white_bitboard[i] + this.king_bitboard[i]; } this.black_bitboard = Utils.white_tries_capture_black_pawn(tmp_bitboard, this.black_bitboard, end_row, end_col); } else { this.turn = Turn.WHITE; this.black_bitboard[start_row] -= (1 << (8 - start_col)); this.black_bitboard[end_row] += (1 << (8 - end_col)); this.white_bitboard = Utils.black_tries_capture_white_pawn(this.black_bitboard, this.white_bitboard, end_row, end_col); this.king_bitboard = Utils.black_tries_capture_king(this.black_bitboard, this.king_bitboard, end_row, end_col); } } /** * @return -1 if king has been captured, 1 if king has escaped, 0 otherwise */ public int check_victory() { int[] tmp_bitboard = new int[9]; if (!Arrays.stream(this.king_bitboard).anyMatch(i -> i != 0)) { return -1; } for (int i = 0; i < this.king_bitboard.length; i++) { tmp_bitboard[i] = (Utils.escapes_bitboard[i] & this.king_bitboard[i]); } if (Arrays.stream(tmp_bitboard).anyMatch(i -> i != 0)) { return 1; } return 0; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(black_bitboard); result = prime * result + Arrays.hashCode(king_bitboard); result = prime * result + Arrays.hashCode(white_bitboard); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BitState other = (BitState) obj; if (!Arrays.equals(black_bitboard, other.black_bitboard)) return false; if (!Arrays.equals(king_bitboard, other.king_bitboard)) return false; if (!Arrays.equals(white_bitboard, other.white_bitboard)) return false; return true; } /** * @param color String, Color of player * @return double, Value of current state for given player */ public double compute_heuristic(String color) { int color_mult = 1; int white_cnt = 1, black_cnt = 0; int curr_mask, remaining_whites_cond, remaining_blacks_cond, ak_cond, blocks_cond_black, blocks_cond_white, blocks_open = 8, blocks_occupied = 0; int wings_cond; int victory_cond = this.check_victory(); int h_partial; if (color.equalsIgnoreCase("WHITE")) { color_mult = 1; } else { color_mult = -1; } if (victory_cond == -1) // King captured return color_mult * (-Utils.MAX_VAL_HEURISTIC); else if (victory_cond == 1) // King escaped return color_mult * (Utils.MAX_VAL_HEURISTIC); for (int i = 0; i < this.black_bitboard.length; i++) { blocks_open -= Integer.bitCount(this.black_bitboard[i] & Utils.blocks_bitboard[i]); } blocks_cond_black = lut_white[2][blocks_open]; for (int i = 0; i < this.white_bitboard.length; i++) { blocks_occupied += Integer.bitCount(this.white_bitboard[i] & Utils.blocksWhite_bitboard[i]); } blocks_cond_white = lut_white[4][blocks_occupied]; /* remaining pieces */ for (int r = 0; r < this.black_bitboard.length; r++) { for (int c = 0; c < this.black_bitboard.length; c++) { curr_mask = (1 << (8 - c)); if ((this.white_bitboard[r] & curr_mask) != 0) { white_cnt += 1; } if ((this.black_bitboard[r] & curr_mask) != 0) { black_cnt += 1; } } } remaining_whites_cond = lut_white[0][white_cnt]; remaining_blacks_cond = lut_white[1][black_cnt]; /* aggressive king */ ak_cond = lut_white[3][this.open_king_paths()]; /* camp wings */ wings_cond = lut_black[0][locked_wings()]; /* partial heuristic */ h_partial = remaining_whites_cond + remaining_blacks_cond + ak_cond + blocks_cond_black + blocks_cond_white + wings_cond; return color_mult * h_partial; } /** * @return int, number of pawns present in positions identified by wings_bitboard */ int locked_wings() { int locked_wings = 0; for (int i = 0; i < this.black_bitboard.length; i++) { locked_wings += Integer.bitCount(this.black_bitboard[i] & Utils.wings_bitboard[i]); } return locked_wings; } /** * @return int, number of open path to escape positions for king */ int open_king_paths() { // king coordinates int king_row, king_col, king_bin_col, left_mask, open_paths; int right_mask = 511; List<Integer> above_the_column = new ArrayList<>(); List<Integer> below_the_column = new ArrayList<>(); for (king_row = 0; king_row < 9; king_row++) if (this.king_bitboard[king_row] != 0) { break; } king_bin_col = this.king_bitboard[king_row]; king_col = Utils.lut_positions.get(king_bin_col); // check for pawns/camps left and right left_mask = (king_bin_col << 1); for (int col = 0; col <= king_col; col++) { right_mask >>= 1; if (col <= king_col - 2) { left_mask ^= king_bin_col; left_mask <<= 1; } } // check for pawns/camps up and down for (int row = 0; row <= king_col; row++) { if (row != king_row && row < king_row) { above_the_column.addAll( Arrays.stream(Utils.bit(Utils.camps_bitboard[row])).boxed().collect(Collectors.toList())); above_the_column.addAll( Arrays.stream(Utils.bit(this.white_bitboard[row])).boxed().collect(Collectors.toList())); above_the_column.addAll( Arrays.stream(Utils.bit(this.black_bitboard[row])).boxed().collect(Collectors.toList())); } else if (row != king_row && row > king_row) { below_the_column.addAll( Arrays.stream(Utils.bit(Utils.camps_bitboard[row])).boxed().collect(Collectors.toList())); below_the_column.addAll( Arrays.stream(Utils.bit(this.white_bitboard[row])).boxed().collect(Collectors.toList())); below_the_column.addAll( Arrays.stream(Utils.bit(this.black_bitboard[row])).boxed().collect(Collectors.toList())); } } open_paths = 4; if ((king_row == 3 || king_row == 4 || king_row == 5) || ((right_mask & this.white_bitboard[king_row]) + (right_mask & this.black_bitboard[king_row]) + (right_mask & Utils.camps_bitboard[king_row]) != 0)) { open_paths -= 1; } if ((king_row == 3 || king_row == 4 || king_row == 5) || (left_mask & this.white_bitboard[king_row]) + (left_mask & this.black_bitboard[king_row]) + (left_mask & Utils.camps_bitboard[king_row]) != 0) { open_paths -= 1; } if ((king_row == 3 || king_row == 4 || king_row == 5) || above_the_column.contains(king_bin_col)) { open_paths -= 1; } if ((king_row == 3 || king_row == 4 || king_row == 5) || below_the_column.contains(king_bin_col)) { open_paths -= 1; } return open_paths; } /** * @return int, number of back camps occupied by black pawns */ int locked_back_camps() { int locked_camps = 0; int hor_map = 0b000111000; if ((this.black_bitboard[0] & hor_map) == 0b000111000) { locked_camps += 1; } if ((this.black_bitboard[8] & hor_map) == 0b000111000) { locked_camps += 1; } List<Integer> row4 = Arrays.stream(Utils.bit(this.black_bitboard[3])).boxed().collect(Collectors.toList()); List<Integer> row5 = Arrays.stream(Utils.bit(this.black_bitboard[4])).boxed().collect(Collectors.toList()); List<Integer> row6 = Arrays.stream(Utils.bit(this.black_bitboard[5])).boxed().collect(Collectors.toList()); if (row4.contains(256) && row5.contains(256) && row6.contains(256)) { locked_camps += 1; } if (row4.contains(2) && row5.contains(2) && row6.contains(2)) { locked_camps += 1; } return locked_camps; } } <file_sep>/tablut/search/min_max_parallel.py """ Date: 07/11/2020 Author: <NAME> Implementation of minmax algorithm with alpha-beta pruning. """ import numpy as np import time from tablut.state.tablut_state import State from tablut.utils.state_utils import MAX_VAL_HEURISTIC, DRAW_POINTS from tablut.utils.common_utils import cont_pieces, MAX_NUM_CHECKERS from threading import Lock, Thread import copy N_THREAD = 16 lock_hash = Lock() lock_value = Lock() lock_bool = Lock() lock_time = Lock() #TODO: remove num_state_visited, use just in test phase def max_value(state, game, alpha, beta, depth, max_depth, time_start, state_hash_table): tmp_victory = state.check_victory() if tmp_victory == -1 and game.color == "BLACK": # king captured and black player -> Win return MAX_VAL_HEURISTIC elif tmp_victory == -1 and game.color == "WHITE": # King captured and white player -> Lose return -MAX_VAL_HEURISTIC elif tmp_victory == 1 and game.color == "BLACK": # King escaped and black player -> Lose return -MAX_VAL_HEURISTIC elif tmp_victory == 1 and game.color == "WHITE": # King escaped and white player -> Win return MAX_VAL_HEURISTIC state_hash = state.get_hash() index_checkers = MAX_NUM_CHECKERS-cont_pieces(state) lock_hash.acquire() hash_result = copy.deepcopy(state_hash_table[index_checkers].get(state_hash)) lock_hash.release() all_actions = None if hash_result is not None: if hash_result['used'] == 1: return -DRAW_POINTS if hash_result.get('all_actions') is not None: all_actions = hash_result.get('all_actions') if cutoff_test(depth, max_depth, game.max_time, time_start): # If reached maximum depth or total time if hash_result is not None and hash_result.get("value") is not None: return hash_result["value"] # If state previously evaluated don't recompute heuristic value = state.compute_heuristic(game.weights, game.color) # If state not previously evaluated add_to_hash(state_hash_table, state_hash, value, None, index_checkers) # Add state and value to hash table return value # Body v = -np.inf if all_actions is None: all_actions = game.produce_actions(state) if hash_result is not None: add_to_hash(state_hash_table, state_hash, hash_result['value'], all_actions, index_checkers) if len(all_actions) == 0: return -MAX_VAL_HEURISTIC for a in all_actions: v = max(v, min_value(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, alpha, beta, depth + 1, max_depth, time_start, state_hash_table)) if v >= beta: return v alpha = max(alpha, v) return v def min_value(state, game, alpha, beta, depth, max_depth, time_start, state_hash_table): tmp_victory = state.check_victory() if tmp_victory == -1 and game.color == "BLACK": # king captured and black player -> Win return MAX_VAL_HEURISTIC elif tmp_victory == -1 and game.color == "WHITE": # King captured and white player -> Lose return -MAX_VAL_HEURISTIC elif tmp_victory == 1 and game.color == "BLACK": # King escaped and black player -> Lose return -MAX_VAL_HEURISTIC elif tmp_victory == 1 and game.color == "WHITE": # King escaped and white player -> Win return MAX_VAL_HEURISTIC state_hash = state.get_hash() index_checkers = MAX_NUM_CHECKERS - cont_pieces(state) lock_hash.acquire() hash_result = copy.deepcopy(state_hash_table[index_checkers].get(state_hash)) lock_hash.release() all_actions = None if hash_result is not None: if hash_result['used'] == 1: return -DRAW_POINTS if hash_result.get('all_actions') is not None: all_actions = hash_result.get('all_actions') if cutoff_test(depth, max_depth, game.max_time, time_start): # If reached maximum depth or total time if hash_result is not None and hash_result.get("value") is not None: return hash_result["value"] # If state previously evaluated don't recompute heuristic value = state.compute_heuristic(game.weights, game.color) # If state not previously evaluated add_to_hash(state_hash_table, state_hash, value, None, index_checkers) # Add state and value to hash table return value # Body v = np.inf if all_actions is None: all_actions = game.produce_actions(state) if hash_result is not None: add_to_hash(state_hash_table, state_hash, hash_result['value'], all_actions, index_checkers) if len(all_actions) == 0: return MAX_VAL_HEURISTIC for a in all_actions: v = min(v, max_value(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, alpha, beta, depth + 1, max_depth, time_start, state_hash_table)) if v <= alpha: return v beta = min(beta, v) return v def add_to_hash(table, state_hash, value, all_actions, index_checkers): """ Adds current state and its value to hash table. """ lock_hash.acquire() table[index_checkers][state_hash] = {"value": value, "used": 0, 'all_actions': all_actions} lock_hash.release() def cutoff_test(depth, max_depth, max_time, time_start): """ Returns True if reached maximum depth or finished time False if search is to be continued """ if depth >= max_depth or time.time()-time_start >= max_time: return True return False def choose_action(state, game, state_hash_table): """ Search for the best action using min max with alpha beta pruning iteratively increasing the maximum depth. It stops only when available time is almost up. """ time_start = time.time() max_depth = 2 flag = False best_score_end = np.inf best_action_end = None best_action = None beta = np.inf flag_time = [False] best_scores = [] all_actions = game.produce_actions(state) # Getting all possible actions given state if len(all_actions) > 0: thread_list = [] active = [] action = [] while time.time()-time_start < game.max_time: best_score = [-np.inf] for i in range(len(best_scores)): best_scores[i] = -np.inf for j in range(len(all_actions)): a = all_actions[j] if j == 0: v = min_value(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, best_score[0], beta, 1, max_depth, time_start, state_hash_table) if v > best_score[0]: best_score[0] = v best_action = a else: if len(thread_list) < N_THREAD: active.append(False) action.append(a) best_scores.append(np.inf) thread_list.append(Thread(target=search_thread, args=(state, action, game, best_score, beta, 1, max_depth, time_start, state_hash_table, flag_time, active, len(thread_list), best_scores))) thread_list[len(thread_list) - 1].start() else: flag_assign = True while flag_assign: for i in range(len(thread_list)): lock_bool.acquire() tmp = active[i] lock_bool.release() if not tmp: lock_value.acquire() if best_scores[i] > best_score[0]: best_score[0] = best_scores[i] best_action = action[i] lock_value.release() action[i] = a lock_bool.acquire() active[i] = True lock_bool.release() flag_assign = False break if time.time() - time_start >= game.max_time: lock_time.acquire() flag_time[0] = True lock_time.release() break flag_t = True while flag_t and not flag_time[0]: flag_t = False for i in range(N_THREAD): lock_bool.acquire() tmp = active[i] lock_bool.release() if tmp: flag_t = True if time.time() - time_start >= game.max_time: lock_time.acquire() flag_time[0] = True lock_time.release() # If search at current maximum depth is finished, update best action tmp_time = flag_time[0] if not tmp_time: for i in range(len(thread_list)): if best_scores[i] > best_score[0]: best_score[0] = best_scores[i] best_action = action[i] best_score_end = best_score[0] best_action_end = best_action flag = True print("Depth reached:", max_depth) elif flag: print("Depth reached:", max_depth - 1) else: print("Minimum depth not reached") max_depth += 1 # Iteratively increasing depth for i in range(len(thread_list)): thread_list[i].join() return best_action_end, best_score_end def search_thread(state, action, game, best_score, beta, depth, max_depth, time_start, state_hash_table, stop, active, id_m, best_scores): lock_time.acquire() tmp_time = stop[0] lock_time.release() while not tmp_time: lock_bool.acquire() active[id_m] = False tmp = active[id_m] lock_bool.release() while not tmp and not tmp_time: lock_bool.acquire() tmp = active[id_m] lock_bool.release() lock_time.acquire() tmp_time = stop[0] lock_time.release() if tmp_time: break lock_value.acquire() tmp_best = best_score[0] a = action[id_m] lock_value.release() v = min_value(State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])), game, tmp_best, beta, depth+1, max_depth, time_start, state_hash_table) if v > best_scores[id_m]: best_scores[id_m] = v lock_time.acquire() tmp_time = stop[0] lock_time.release() return <file_sep>/README.md # tablut-THOR Agent for University of Bologna Fundamentals of Artificial Intelligence tablut competition: The agent plays Tablut using Ashton's rules. The time limit for a single move is 60s. Third position, 2020. ## Instructions A server build from https://github.com/AGalassi/TablutCompetition.git is required to use the agent. From VM, in "/tablut", after server launch, launch player from terminal: - ./runmyplayer "white" time ip_server - ./runmyplayer "black" time ip_server time: time available to find action, in seconds, int ip_server: String ## General Algorithm The agent uses the minmax algorithm with alpha-beta pruning, implemented in Java. A worse performing python implementation was also attempted, and can be found in the /tablut folder. An additional (partial) optimization step has been takend introducing parallelization of search at first depth: while possibly excluding cuts among the main subtrees, it allows to better exploitation of the hardware, with minimal communication overhead. ## Heuristics and Strategy The heuristic has been kept relatively simple, due to the time limit. Various conditions are evaluated, giving an idea of both white and black players' strategy. * Remaining pieces: the difference in pieces is a clear condition of advantage, the weigth of white pieces is higher, since they are fewer * Aggressive king: positions in which the king has one open path to the exit have a high weight, avoiding (or reaching, depending on colour) such positions is incetivized expecially in they are at max depth: being aggressive might be a strong tactics when the depth reached by both programs is the same. * Blocks: both white and blacks try to obtain ("block") specific positions on the board, that allow easier movement or control over the area * Fronts: black player tries to keep a pawn in the front line of the camps: this position is quite powerful because it has rapid access to many quadrants, so it is preferred to first move rear pawns. ## Further ideas and improvements At the time of submission, we were not able to implement some ideas suggested, which might have improved performance, some are listed below in case of future experimentation: * Dictionary of states and actions, with symmetry: since the board is extremely symmetric, we considered the option of keeping a dictionary of all the positions reached, their value, and the actions that they generate, in order not to compute them again. At the moment we have not yet found a satisfactory implementation. * Lazy SMP strategy: the idea is running multiple threads at different levels, each filling the dictonary suggested above, many current chess algorithm use similar strategies, but particular attention must be paid regarding concurrent accessses or data integrity. * Updating heuristic: heuristics should likely change during the duration of the game: some of the above conditions are better in the early game: a turn or diminishing return might be used to change the strategy. * King heatmap, last move heatmap: players should keep in consideration the opponent's last move and act accordingly, this might be done including heatmaps changing positional heuristic depending on moves. Due to the usage of bitmap instead of arrrays, heatmaps would introduce overhead in the conversion. * An additional strategy for black would be the blockade: reduction of number of available moves for the white player. <file_sep>/tablut/genetic/genetic_search_match.py """ Date: 05/11/2020 Author: <NAME> & <NAME> Population-based search for best weight of heuristic's component, through matches. """ from tablut.client.tablut_client import Client from multiprocessing import Pool import subprocess import numpy as np import time from multiprocessing import Queue q = Queue() N_POP = 200 # Number of solutions in population. NUM_MATCH = 1 # Percentage of solutions to play against. N_PARAM = 6 # Number of parameter of each solution MAX_PARAM_VALUE = 40 # Maximum value allowed for each parameter MIN_PARAM_VALUE = 0 # Minimum value allowed for each parameter MAX_ITER = 200 # Maximum number of iterations PERC_NEW_POP = .3 # Percentage of new individuals at each iteration EPS = MAX_PARAM_VALUE / 5 # Maximum change of each parameter due to mutation MAX_ITER_NO_BETTER = 10 # Maximum number of iterations without better solution MAX_TIME_ACTION = 1 # Maximum time allowed to search for action def create_play_player(port, color, max_time_act, weights, name, host, args=None): client_m = Client(port, color, max_time_act, weights=weights, name=name, host=host) client_m.run(args) def eval_match(sol1, sol2): """ Starts two matches between a couple of solutions, returns point earned by each one. """ sol1_points = 0 sol2_points = 0 result = [] pool = Pool() proc = subprocess.Popen(['ant', 'server']) # Requires server files in path time.sleep(2) white_thread = pool.apply_async(create_play_player, args=(5800, "WHITE", MAX_TIME_ACTION, sol1, "sol1", "127.0.0.1", result)) # Important, pass list just to one of the two threads, to avoid synchronization problems black_thread = pool.apply_async(create_play_player, args=(5801, "BLACK", MAX_TIME_ACTION, sol2, "sol2", "127.0.0.1", result)) black_thread.wait() white_thread.wait() pool.close() while not q.empty(): result.append(q.get()) proc.wait() proc.terminate() if result[0] == "WHITE": sol1_points += 3 elif result[0] == "BLACK": sol2_points += 3 else: sol1_points += 1 sol2_points += 1 result = [] pool = Pool() proc = subprocess.Popen(['ant', 'server']) # Requires server files in path time.sleep(2) white_thread = pool.apply_async(create_play_player, args=(5800, "WHITE", MAX_TIME_ACTION, sol2, "sol2", "127.0.0.1", result)) # Important, pass list just to one of the two threads, to avoid synchronization problems black_thread = pool.apply_async(create_play_player, args=(5801, "BLACK", MAX_TIME_ACTION, sol1, "sol1", "127.0.0.1", result)) black_thread.wait() white_thread.wait() while not q.empty(): result.append(q.get()) pool.close() proc.wait() proc.terminate() if result[0] == "WHITE": sol2_points += 3 elif result[0] == "BLACK": sol1_points += 3 else: sol2_points += 1 sol1_points += 1 return sol1_points, sol2_points def eval_pop(solutions): """ Evaluates solutions, returns a list of floats, between 0 and 1 (probabilities of survival and reproduction). """ prob_surv = np.zeros(N_POP, dtype=np.float) num_games = np.zeros(N_POP, dtype=np.int) np.random.shuffle(solutions) for index_sol1 in range(len(solutions)): old_index = index_sol1 for match_num in range(NUM_MATCH): index_sol2 = np.random.randint(old_index, N_POP) while index_sol2 == old_index: index_sol2 = np.random.randint(0, N_POP) point_sol1, point_sol2 = eval_match(solutions[index_sol1], solutions[index_sol2]) prob_surv[index_sol1] += point_sol1 prob_surv[index_sol2] += point_sol2 num_games[index_sol1] += 2 num_games[index_sol2] += 2 old_index = index_sol2 prob_surv = np.array(prob_surv) prob_surv /= 3*num_games return prob_surv def test_eval(solutions): max_dist = [] for sol in solutions: par_first = 0 par_second = 0 for u in range(0, int(N_PARAM/2)): par_first += sol[u] for u in range(int(N_PARAM/2), N_PARAM): par_second += sol[u] max_dist.append(np.abs(float(par_first-par_second)) if par_first >= par_second else 0.0) max_dist = np.array(max_dist) max_dist /= 4000 return max_dist def mate(sol1, sol2): """ Create a new individual by applying crossover. Linear combination with random weights between 0 and 1 """ lambda_1 = np.random.rand() lambda_2 = np.random.rand() m_newborn = [] for x in range(N_PARAM): new_value = lambda_1*sol1[x] + lambda_2*sol2[x] if new_value > MAX_PARAM_VALUE: new_value = MAX_PARAM_VALUE elif new_value < MIN_PARAM_VALUE: new_value = MIN_PARAM_VALUE m_newborn.append(new_value) return m_newborn def add_newborn(m_newborn, solutions, prob_surv): """ Removing solution based on strength to make room for new individual. """ index_remove = np.random.randint(0, N_POP) while np.random.rand() <= prob_surv[index_remove]: index_remove = np.random.randint(0, N_POP) solutions[index_remove] = m_newborn def mutations(solutions, prob_surv): """ Mutating individuals based on their probability of survival. """ for j in range(N_POP): number_poss_mutations = np.random.randint(0, N_PARAM) # Choosing number of possible mutations for k in range(number_poss_mutations): param_index = np.random.randint(0, N_PARAM) # Choosing parameter to mutate random_mutation = np.random.rand() if random_mutation > prob_surv[j]: if np.random.rand() > 0.5: solutions[j][param_index] += int((random_mutation-prob_surv[j])*EPS) if solutions[j][param_index] > MAX_PARAM_VALUE: solutions[j][param_index] = MAX_PARAM_VALUE elif solutions[j][param_index] < MIN_PARAM_VALUE: solutions[j][param_index] = MIN_PARAM_VALUE else: solutions[j][param_index] -= int((random_mutation - prob_surv[j]) * EPS) if solutions[j][param_index] > MAX_PARAM_VALUE: solutions[j][param_index] = MAX_PARAM_VALUE elif solutions[j][param_index] < MIN_PARAM_VALUE: solutions[j][param_index] = MIN_PARAM_VALUE def find_best_sol(solutions): """ Finding best solution, by evaluating all possible couples. """ points = np.zeros(N_POP, dtype=np.int) for index_sol1 in range(len(solutions)): for index_sol2 in range(len(solutions)): if index_sol2 > index_sol1: point_sol1, point_sol2 = eval_match(solutions[index_sol1], solutions[index_sol2]) points[index_sol1] += point_sol1 points[index_sol2] += point_sol2 return np.argmax(points) num_iter = 0 population = [] for i in range(N_POP): # Randomly initializing population population.append([np.random.randint(MIN_PARAM_VALUE, MAX_PARAM_VALUE+1) for x in range(N_PARAM)]) prob_survival = eval_pop(population) # First evaluation of pop best_sol = [] best_sol_prob = 0.0 no_best_sol = 0 while num_iter <= MAX_ITER and no_best_sol <= MAX_ITER_NO_BETTER: i = 0 while i <= PERC_NEW_POP*N_POP: index_par1 = np.random.randint(0, N_POP) # Picking random parents while np.random.rand() > prob_survival[index_par1]: index_par1 = np.random.randint(0, N_POP) # Choosing parents based on their strength index_par2 = np.random.randint(0, N_POP) while index_par2 == index_par1 or np.random.rand() > prob_survival[index_par2]: index_par2 = np.random.randint(0, N_POP) newborn = mate(population[index_par1], population[index_par2]) # Creating new individual add_newborn(newborn, population, prob_survival) # Add new individual by removing less strong old ones i += 1 mutations(population, prob_survival) # Mutations hit less strong individual with higher probability prob_survival = eval_pop(population) # Population evaluation best_sol_find_index = int(np.argmax(prob_survival)) if best_sol_prob < prob_survival[best_sol_find_index]: best_sol = population[best_sol_find_index] best_sol_prob = prob_survival[best_sol_find_index] no_best_sol = 0 print("Best sol: ", population[best_sol_find_index]) print("Value: ", prob_survival[best_sol_find_index]) print("Iteration: ", num_iter) num_iter += 1 no_best_sol += 1 index_best_sol = find_best_sol(population) print("Best sol: ", population[int(index_best_sol)]) <file_sep>/tablut/search/game.py """ Date: 08/11/2020 Author: <NAME> Implementation of method required by tablut game. """ import numpy as np from tablut.utils.state_utils import build_column class Game: def __init__(self, max_time, color, weights): self.max_time = max_time self.color = color self.weights = weights self.possible_actions_hor = np.empty(shape=(9, 9), dtype=int) self.possible_actions_ver = np.empty(shape=(9, 9), dtype=int) # Create possible actions from each position self.possible_actions_hor[0][0] = 0b011000000 self.possible_actions_hor[0][1] = 0b101000000 self.possible_actions_hor[0][2] = 0b110000000 self.possible_actions_hor[0][3] = 0b111011111 self.possible_actions_hor[0][4] = 0b111101111 self.possible_actions_hor[0][5] = 0b111110111 self.possible_actions_hor[0][6] = 0b000000011 self.possible_actions_hor[0][7] = 0b000000101 self.possible_actions_hor[0][8] = 0b000000110 self.possible_actions_hor[1][0] = 0b011100000 self.possible_actions_hor[1][1] = 0b101100000 self.possible_actions_hor[1][2] = 0b110100000 self.possible_actions_hor[1][3] = 0b111000000 self.possible_actions_hor[1][4] = 0b111101111 self.possible_actions_hor[1][5] = 0b000000111 self.possible_actions_hor[1][6] = 0b000001011 self.possible_actions_hor[1][7] = 0b000001101 self.possible_actions_hor[1][8] = 0b000001110 self.possible_actions_hor[2][0] = 0b011111111 self.possible_actions_hor[2][1] = 0b101111111 self.possible_actions_hor[2][2] = 0b110111111 self.possible_actions_hor[2][3] = 0b111011111 self.possible_actions_hor[2][4] = 0b111101111 self.possible_actions_hor[2][5] = 0b111110111 self.possible_actions_hor[2][6] = 0b111111011 self.possible_actions_hor[2][7] = 0b111111101 self.possible_actions_hor[2][8] = 0b111111110 self.possible_actions_hor[3][0] = 0b011111110 self.possible_actions_hor[3][1] = 0b001111110 self.possible_actions_hor[3][2] = 0b010111110 self.possible_actions_hor[3][3] = 0b011011110 self.possible_actions_hor[3][4] = 0b011101110 self.possible_actions_hor[3][5] = 0b011110110 self.possible_actions_hor[3][6] = 0b011111010 self.possible_actions_hor[3][7] = 0b011111100 self.possible_actions_hor[3][8] = 0b011111110 self.possible_actions_hor[4][0] = 0b011100000 self.possible_actions_hor[4][1] = 0b101100000 self.possible_actions_hor[4][2] = 0b000100000 self.possible_actions_hor[4][3] = 0b001000000 self.possible_actions_hor[4][4] = 0b001101100 self.possible_actions_hor[4][5] = 0b000000100 self.possible_actions_hor[4][6] = 0b000001000 self.possible_actions_hor[4][7] = 0b000001101 self.possible_actions_hor[4][8] = 0b000001110 self.possible_actions_hor[5] = self.possible_actions_hor[3] self.possible_actions_hor[6] = self.possible_actions_hor[2] self.possible_actions_hor[7] = self.possible_actions_hor[1] self.possible_actions_hor[8] = self.possible_actions_hor[0] self.possible_actions_ver = np.transpose(self.possible_actions_hor) def produce_actions(self, state): """ Returns a list of possible actions, each action is: [k, start_row, start_col, end_row, end_col] where k == True -> king moves, k==False ->pawn moves start_row,start_col -> pieces coordinates end_row, end_col -> final coordinates """ action_list = [] if state.turn == "WHITE": r = 0 while state.king_bitboard[r] == 0: # Searching king row r += 1 tmp_r = 8 - r c = 0 tmp_c = 8 - c curr_pos_mask = (1 << tmp_c) while state.king_bitboard[r] & curr_pos_mask != curr_pos_mask: # Searching king column c += 1 tmp_c = (8 - c) curr_pos_mask = (1 << tmp_c) # First look for actions that lead to escapes poss_actions_mask = ~state.white_bitboard[r] & self.possible_actions_hor[r][c] # Horizontal actions poss_actions_mask &= ~state.black_bitboard[r] i = 1 tmp_list = [] if c != 0: new_pos_mask = curr_pos_mask << i while i <= c and poss_actions_mask & new_pos_mask != 0: # Actions to the left, checkers cannot jump tmp_list.append((True, r, c, r, c - i)) i += 1 if i <= c: new_pos_mask = new_pos_mask << 1 tmp_list.reverse() action_list = action_list + tmp_list i = 1 tmp_list = [] if c != 8: new_pos_mask = curr_pos_mask >> i # Actions to the right, checkers cannot jump while i <= tmp_c and poss_actions_mask & new_pos_mask != 0: tmp_list.append((True, r, c, r, c + i)) i += 1 if i <= tmp_c: new_pos_mask = new_pos_mask >> 1 tmp_list.reverse() action_list = action_list + tmp_list white_column = build_column(state.white_bitboard, curr_pos_mask) # Building column given position black_column = build_column(state.black_bitboard, curr_pos_mask) curr_pos_mask = (1 << tmp_r) # Vertical actions poss_actions_mask = ~white_column & self.possible_actions_ver[r][c] poss_actions_mask &= ~black_column i = 1 tmp_list = [] if r != 0: new_pos_mask = curr_pos_mask << i while i <= r and poss_actions_mask & new_pos_mask != 0: # Actions up, checkers cannot jump tmp_list.append((True, r, c, r - i, c)) i += 1 if i <= r: new_pos_mask = new_pos_mask << 1 tmp_list.reverse() action_list = action_list + tmp_list i = 1 tmp_list = [] if r != 8: new_pos_mask = curr_pos_mask >> i # Actions down, checkers cannot jump while i <= tmp_r and poss_actions_mask & new_pos_mask != 0: tmp_list.append((True, r, c, r + i, c)) i += 1 if i <= tmp_r: new_pos_mask = new_pos_mask >> 1 tmp_list.reverse() action_list = action_list + tmp_list for r in range(len(state.white_bitboard)): # Searching white pawns if state.white_bitboard[r] != 0: tmp_r = 8 - r for c in range(len(state.white_bitboard)): curr_pos_mask = (1 << (8 - c)) # Horizontal moves # If current position is occupied by a white pawn if state.white_bitboard[r] & curr_pos_mask == curr_pos_mask: tmp_c = 8 - c poss_actions_mask = ~state.white_bitboard[r] & self.possible_actions_hor[r][c] poss_actions_mask &= ~state.king_bitboard[r] poss_actions_mask &= ~state.black_bitboard[r] i = 1 if c != 0: new_pos_mask = curr_pos_mask << i # Actions to the left, checkers cannot jump while i <= c and poss_actions_mask & new_pos_mask != 0: action_list.append((False, r, c, r, c - i)) i += 1 if i <= c: new_pos_mask = new_pos_mask << 1 i = 1 if c != 8: new_pos_mask = curr_pos_mask >> i # Actions to the right, checkers cannot jump while i <= tmp_c and poss_actions_mask & new_pos_mask != 0: action_list.append((False, r, c, r, c + i)) i += 1 if i <= tmp_c: new_pos_mask = new_pos_mask >> 1 white_column = build_column(state.white_bitboard, curr_pos_mask) # Building column given position black_column = build_column(state.black_bitboard, curr_pos_mask) king_column = build_column(state.king_bitboard, curr_pos_mask) curr_pos_mask = (1 << tmp_r) # Vertical actions poss_actions_mask = ~white_column & self.possible_actions_ver[r][c] poss_actions_mask &= ~black_column poss_actions_mask &= ~king_column i = 1 if r != 0: new_pos_mask = curr_pos_mask << i # Actions up, checkers cannot jump while i <= r and poss_actions_mask & new_pos_mask != 0: action_list.append((False, r, c, r - i, c)) i += 1 if i <= r: new_pos_mask = new_pos_mask << 1 i = 1 if r != 8: new_pos_mask = curr_pos_mask >> i # Actions down, checkers cannot jump while i <= tmp_r and poss_actions_mask & new_pos_mask != 0: action_list.append((False, r, c, r + i, c)) i += 1 if i <= tmp_r: new_pos_mask = new_pos_mask >> 1 if state.turn == "BLACK": for r in range(len(state.black_bitboard)): # Searching black pawns if state.black_bitboard[r] != 0: tmp_r = 8 - r for c in range(len(state.black_bitboard)): curr_pos_mask = (1 << (8 - c)) # If current position is occupied by a black pawn if state.black_bitboard[r] & curr_pos_mask == curr_pos_mask: # Horizontal actions tmp_c = 8 - c poss_actions_mask = ~state.white_bitboard[r] & self.possible_actions_hor[r][c] poss_actions_mask &= ~state.king_bitboard[r] poss_actions_mask &= ~state.black_bitboard[r] i = 1 new_pos_mask = curr_pos_mask << i # Actions to the left, checkers cannot jump while i <= c and poss_actions_mask & new_pos_mask != 0: action_list.append((False, r, c, r, c - i)) i += 1 if i <= c: new_pos_mask = new_pos_mask << 1 i = 1 new_pos_mask = curr_pos_mask >> i # Actions to the right, checkers cannot jump while i <= tmp_c and poss_actions_mask & new_pos_mask != 0: action_list.append((False, r, c, r, c + i)) i += 1 if i <= tmp_c: new_pos_mask = new_pos_mask >> 1 white_column = build_column(state.white_bitboard, curr_pos_mask) # Building column given position black_column = build_column(state.black_bitboard, curr_pos_mask) king_column = build_column(state.king_bitboard, curr_pos_mask) curr_pos_mask = (1 << tmp_r) # Vertical actions poss_actions_mask = ~white_column & self.possible_actions_ver[r][c] poss_actions_mask &= ~black_column poss_actions_mask &= ~king_column i = 1 if r != 0: new_pos_mask = curr_pos_mask << i # Actions up, checkers cannot jump while i <= r and poss_actions_mask & new_pos_mask != 0: action_list.append((False, r, c, r - i, c)) i += 1 if i <= r: new_pos_mask = new_pos_mask << 1 i = 1 if r != 8: new_pos_mask = curr_pos_mask >> i # Actions down, checkers cannot jump while i <= tmp_r and poss_actions_mask & new_pos_mask != 0: action_list.append((False, r, c, r + i, c)) i += 1 if i <= tmp_r: new_pos_mask = new_pos_mask >> 1 return action_list <file_sep>/tablut/client/tablut_client.py from tablut.client.connection_handler import ConnectionHandler from tablut.search.min_max import choose_action from tablut.state.tablut_state import State from tablut.search.game import Game from tablut.utils.state_utils import action_to_server_format from tablut.utils.common_utils import clear_hash_table, update_used, MAX_NUM_CHECKERS class Client(ConnectionHandler): """Extends ConnectionHandler, handling the connection between client and server.""" def __init__(self, port, color, max_time, host="localhost", weights=None, name=None): super().__init__(port, host) self.color = color self.max_time = max_time if weights is None: self.weights = [70, 85, 99, 74, 66, 82, 90] # Best weights find by our genetic algorithm else: self.weights = weights # Searching best params if name is None: self.player_name = "THOR" else: self.player_name = name self.game = Game(self.max_time, self.color, self.weights) self.state_hash_tables_tmp = dict() for i in range(MAX_NUM_CHECKERS): self.state_hash_tables_tmp[i] = dict() def run(self): """Client's body.""" try: self.connect() self.send_string(self.player_name) state = State(self.read_string()) self.state_hash_tables_tmp[0][state.get_hash()] = {"value": 0, 'used': 1} while True: # Playing if self.color == state.turn: # check turn action, value = choose_action(state, self.game, self.state_hash_tables_tmp) # Retrieving best action and its value and pass weights self.send_string(action_to_server_format(action)) print("Choosen action:", action_to_server_format(action)) print("Choosen action value:", value) else: clear_hash_table(self.state_hash_tables_tmp, state) state = State(self.read_string()) update_used(self.state_hash_tables_tmp, state, self.game.weights, self.game.color) except Exception as e: print(e) finally: print("Game ended.") <file_sep>/tablut/test/future_min_max_test.py from concurrent.futures import * from tablut.utils.hashtable import * import time import numpy as np from tablut.state.tablut_state import State from multiprocessing import cpu_count def lazy_smp_process(state, game, htable): time_start = time.time() print(time_start) cpu_num = cpu_count() print(cpu_num) pool = ProcessPoolExecutor(cpu_num) chosen_action = None chosen_value = None """futures = [pool.submit(alpha_beta_cutoff_search, state, game, 1, htable), pool.submit(alpha_beta_cutoff_search, state, game, 2, htable), pool.submit(alpha_beta_cutoff_search, state, game, 3, htable), pool.submit(alpha_beta_cutoff_search, state, game, 4, htable)] """ futures = [] for p in range(cpu_num): d = int(p / 2 + 1) futures.append(pool.submit(alpha_beta_cutoff_search, state, game, d, htable, time_start)) "we suppose not to go above 7 levels" working_at_depth = [2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] max_depth = 0 try: while True: "wait returns completed tasks and working task" remaining_time = game.max_time - (time.time() - time_start) if remaining_time <= 0.1: raise TimeoutError (tasks_completed, working) = wait(futures, remaining_time, return_when=FIRST_COMPLETED) "check the completed results, give the new task" for x in tasks_completed: i = futures.index(x) (action, value, depth) = x.result() if depth > max_depth: "a new depth has been completed" max_depth = depth print(max_depth) chosen_action = action chosen_value = value working_at_depth[depth] = 2 dp = depth + 1 while working_at_depth[dp] > 1: dp += 1 working_at_depth[dp] += 1 futures[i] = pool.submit(alpha_beta_cutoff_search, state, game, dp, htable) print('I am %d, now going to %d' % (i, dp)) finally: return chosen_action, chosen_value def eval_fn(state, game): v = state.compute_heuristic(game.weights, game.color) return v def min_value(state, game, alpha, beta, depth, max_depth, htable, time_start): if game.max_time - (time.time() - time_start) <= 0.1: return False hash_key = state.get_hash() update_hash = True hash_available = False if hash_key in htable: hash_available = True hash_state = htable.get(hash_key) if hash_state.get_forward_depth() >= max_depth - depth: return hash_state.get_value() else: update_hash = False if depth == max_depth: return eval_fn(state, game) v = np.inf if hash_available: all_actions = hash_state.get_actions() else: all_actions = game.produce_actions(state) np.random.shuffle(all_actions) for a in all_actions: if game.max_time - (time.time() - time_start) <= 0.1: return False new_state = State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])) v = min(v, max_value(new_state, game, alpha, beta, depth + 1, max_depth, htable)) if update_hash or not hash_available: key = new_state.get_hash() htable[key] = HashEntry(key, v, all_actions, max_depth, depth) if v <= alpha: return v beta = min(beta, v) return v def max_value(state, game, alpha, beta, depth, max_depth, htable, time_start): if game.max_time - (time.time() - time_start) <= 0.1: return False hash_key = state.get_hash() update_hash = True hash_available = False if hash_key in htable: hash_available = True hash_state = htable.get(hash_key) if hash_state.get_forward_depth() >= max_depth - depth: return hash_state.get_value() else: update_hash = False if depth == max_depth: return eval_fn(state, game) v = -np.inf if hash_available: all_actions = hash_state.get_actions() else: all_actions = game.produce_actions(state) np.random.shuffle(all_actions) for a in all_actions: if game.max_time - (time.time() - time_start) <= 0.1: return False new_state = State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])) v = max(v, min_value(new_state, game, alpha, beta, depth + 1, max_depth, htable)) if update_hash or not hash_available: key = new_state.get_hash() htable[key] = HashEntry(key, v, all_actions, max_depth, depth) if v >= beta: return v alpha = max(alpha, v) return v def alpha_beta_cutoff_search(state, game, max_depth, htable, time_start): """Search game to determine best action; use alpha-beta pruning. This version cuts off search and uses an evaluation function.""" best_score = -np.inf beta = np.inf best_action = None action_list = game.produce_actions(state) np.random.shuffle(action_list) for a in action_list: new_state = State(second_init_args=(state, a[0], a[1], a[2], a[3], a[4])) v = min_value(new_state, game, best_score, beta, 1, max_depth, htable, time_start) if v > best_score: best_score = v best_action = a return best_action, best_score, max_depth
46ad2b75b479f26a0a6c92a3a8bdb8dabf198684
[ "Java", "Markdown", "Python" ]
24
Java
carlo98/tablut-THOR
b990d49c66735c40afbfa7d26aeec7694a80a729
f247433af22fa66ad16c11d670837597f33e153b
refs/heads/master
<file_sep>package com.example.kyungrikim.netserver2; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.URLDecoder; import java.util.Enumeration; import android.support.v7.app.ActionBarActivity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Enumeration; import android.support.v7.app.ActionBarActivity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends ActionBarActivity { private TextView tvClientMsg,tvServerIP,tvServerPort; private final int SERVER_PORT = 8080; //Define the server port @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvClientMsg = (TextView) findViewById(R.id.textViewClientMessage); tvServerIP = (TextView) findViewById(R.id.textViewServerIP); tvServerPort = (TextView) findViewById(R.id.textViewServerPort); tvServerPort.setText(Integer.toString(SERVER_PORT)); //Call method getDeviceIpAddress(); //New thread to listen to incoming connections new Thread(new Runnable() { @Override public void run() { try { //Create a server socket object and bind it to a port ServerSocket socServer = new ServerSocket(SERVER_PORT); //Create server side client socket reference Socket socClient = null; //Infinite loop will listen for client requests to connect while (true) { //Accept the client connection and hand over communication to server side client socket socClient = socServer.accept(); //For each client new instance of AsyncTask will be created ServerAsyncTask serverAsyncTask = new ServerAsyncTask(); //Start the AsyncTask execution //Accepted client socket object will pass as the parameter serverAsyncTask.execute(new Socket[] {socClient}); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } /** * Get ip address of the device */ public void getDeviceIpAddress() { try { //Loop through all the network interface devices for (Enumeration<NetworkInterface> enumeration = NetworkInterface .getNetworkInterfaces(); enumeration.hasMoreElements();) { NetworkInterface networkInterface = enumeration.nextElement(); //Loop through all the ip addresses of the network interface devices for (Enumeration<InetAddress> enumerationIpAddr = networkInterface.getInetAddresses(); enumerationIpAddr.hasMoreElements();) { InetAddress inetAddress = enumerationIpAddr.nextElement(); //Filter out loopback address and other irrelevant ip addresses if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) { //Print the device ip address in to the text view tvServerIP.setText(inetAddress.getHostAddress()); } } } } catch (SocketException e) { Log.e("ERROR:", e.toString()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * AsyncTask which handles the communication with clients */ class ServerAsyncTask extends AsyncTask<Socket, Void, String> { //Background task which serve for the client @Override protected String doInBackground(Socket... params) { String result = null; JSONObject jsonObject = null; //Get the accepted socket object Socket mySocket = params[0]; try { //Get the data input stream comming from the client InputStream is = mySocket.getInputStream(); //Get the output stream to the client PrintWriter out = new PrintWriter( mySocket.getOutputStream(), true); //Write data to the data output stream //out.println("Hello from server"); //Buffer the data input stream BufferedReader br = new BufferedReader( new InputStreamReader(is)); //Read the contents of the data buffer //while(true) { Log.d("kk", "read"); result = br.readLine(); Log.d("kk", "hihi"); String data = URLDecoder.decode(result, "UTF-8"); // if (result.equals('\0') || data.equals("END")) { // break; // } data = URLDecoder.decode(data, "ascii"); data.replace(" ?.!/;\\0", ""); jsonObject = new JSONObject(data); result = jsonObject.getString("name"); //Close the client connection mySocket.close(); //} } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String s) { //After finishing the execution of background task data will be write the text view tvClientMsg.setText(s); } } } <file_sep>import socket import json from io import StringIO from time import ctime HOST = '172.16.17.32' PORT = 63635 BUFSIZ = 1024 ADDR = (HOST, PORT) if __name__ == '__main__': server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(ADDR) server_socket.listen(5) server_socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) while True: print('Server waiting for connection...') client_sock, addr = server_socket.accept() print("연결수락"); print('Client connected from: ', addr) while True: data = client_sock.recv(BUFSIZ) if not data or data.decode('utf-8') == 'END': break print(data) data = data.decode('ascii') data = data.translate(str.maketrans('', '', " ?.!/;\0")) parsed_json = json.loads(data) print("Received from client: %s" % data) print("name : " + parsed_json['name']) print("company : " + parsed_json['company']) print("age : " + parsed_json['age']) #.decode('utf- 8') #print("Sending the server time to client: %s" %ctime()) #try: # client_sock.send(bytes(ctime(), 'utf-8')) #except KeyboardInterrupt: # print("Exited by user") client_sock.close() server_socket.close() <file_sep>package com.example.kyungrikim.net2; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends Activity { private TextView txtResponse; private EditText edtTextAddress, edtTextPort; private Button btnConnect, btnClear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtTextAddress = (EditText) findViewById(R.id.address); edtTextPort = (EditText) findViewById(R.id.port); btnConnect = (Button) findViewById(R.id.connect); btnClear = (Button) findViewById(R.id.clear); txtResponse = (TextView) findViewById(R.id.response); btnConnect.setOnClickListener(buttonConnectOnClickListener); btnClear.setOnClickListener(new OnClickListener() { public void onClick(View v) { txtResponse.setText(""); } }); } // Ŭ���̺�Ʈ ������ OnClickListener buttonConnectOnClickListener = new OnClickListener() { public void onClick(View arg0) { NetworkTask myClientTask = new NetworkTask( edtTextAddress.getText().toString(), Integer.parseInt(edtTextPort.getText().toString()) ); myClientTask.execute(); } }; public class NetworkTask extends AsyncTask<Void, Void, Void> { String dstAddress; int dstPort; String response; JSONObject jsonObject = new JSONObject(); NetworkTask(String addr, int port) { dstAddress = addr; dstPort = port; } private void sendObject(){ try{ jsonObject.put("name", "wdkang"); jsonObject.put("company", "acanet"); jsonObject.put("age", "26"); }catch (JSONException e){ e.printStackTrace(); } } @Override protected Void doInBackground(Void... arg0) { try { Log.e("TCP","server connecting~~!"); Socket socket = new Socket(dstAddress, dstPort); sendObject(); /* InputStream inputStream = socket.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream( 1024); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); } response = byteArrayOutputStream.toString("UTF-8"); */ try{ OutputStream outputStream = socket.getOutputStream(); PrintStream printStream = new PrintStream(outputStream); printStream.print(jsonObject); printStream.close(); } catch (IOException e) { Log.e("TCP","don't send message!"); e.printStackTrace(); } socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { txtResponse.setText(response); //txtResponse.setText("a"); super.onPostExecute(result); } } } <file_sep>package com.ramotion.circlemenu.example.simple; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Toast; import com.ramotion.circlemenu.CircleMenuView; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class MainActivity extends AppCompatActivity { private class NetworkManagerThread extends Thread { public void run() { try { Log.i("TCP", "NetworkManagerThread"); ServerSocket socServer = new ServerSocket(8888); Socket socClient = null; BufferedReader br = null; PrintStream ps = null; String s = null; while (true) { socClient = socServer.accept(); Log.i("TCP", "" + socClient.getInetAddress().getHostAddress()); br = new BufferedReader(new InputStreamReader(socClient.getInputStream())); ps = new PrintStream(socClient.getOutputStream()); s = br.readLine(); Log.i("TCP", s); ps.println("OKAY"); br.close(); ps.close(); socClient.close(); } } catch (IOException e) { e.printStackTrace(); } } } private String ip = "192.168.137.62"; private String port = "7880"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new NetworkManagerThread().start(); final CircleMenuView menu = findViewById(R.id.circle_menu); menu.setEventListener(new CircleMenuView.EventListener() { @Override public void onMenuOpenAnimationStart(@NonNull CircleMenuView view) { Log.d("D", "onMenuOpenAnimationStart"); } @Override public void onMenuOpenAnimationEnd(@NonNull CircleMenuView view) { Log.d("D", "onMenuOpenAnimationEnd"); } @Override public void onMenuCloseAnimationStart(@NonNull CircleMenuView view) { Log.d("D", "onMenuCloseAnimationStart"); } @Override public void onMenuCloseAnimationEnd(@NonNull CircleMenuView view) { Log.d("D", "onMenuCloseAnimationEnd"); } @Override public void onButtonClickAnimationStart(@NonNull CircleMenuView view, int index) { Log.d("D", "onButtonClickAnimationStart| index: " + index); NetworkTask myClientTask = new NetworkTask( ip, Integer.parseInt(port) ); myClientTask.execute(); JSONObject jsonObject = new JSONObject(); switch (index) { case 0: myClientTask.sendObject("User_Device", "PowerOn"); break; case 1: myClientTask.sendObject("User_Device", "Open"); break; case 2: myClientTask.sendObject("User_Device", "Close"); break; case 3: myClientTask.sendObject("User_Device", "EngineStart"); break; default: myClientTask.sendObject("User_Device", "EngineStop"); } } @Override public void onButtonClickAnimationEnd(@NonNull CircleMenuView view, int index) { Log.d("D", "onButtonClickAnimationEnd| index: " + index); } }); } public class NetworkTask extends AsyncTask<Void, Void, Void> { String dstAddress; int dstPort; JSONObject jsonObject = new JSONObject(); String response; NetworkTask(String addr, int port) { dstAddress = addr; dstPort = port; } private void sendObject(String name, String value) { try { Log.i(name, value); jsonObject.put(name, value); } catch (JSONException e) { e.printStackTrace(); } } @Override protected Void doInBackground(Void... arg0) { int code = 0; InputStream inputStream; OutputStream outputStream = null; PrintStream printStream = null; BufferedReader inFromServer = null; try { Socket socket = new Socket(dstAddress, dstPort); Log.i("TCP", "Server Connected"); try { inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); printStream = new PrintStream(outputStream); inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream())); printStream.println("open"); //open command 전송 response = inFromServer.readLine(); //user authentication Log.i("TCP", "Message From Server : " + response); try { code = Integer.parseInt(response); } catch (NumberFormatException e) { e.printStackTrace(); } code += 1; printStream.println(String.valueOf(code)); Log.i("TCP", "Send Authentication Message to Server : " + code); /* response = inFromServer.readLine(); //final response received Log.i("TCP", "Authentication Message From Server : " + response); */ response = inFromServer.readLine(); //final response received Log.i("TCP", "Core Code Message From Server : " + response); if(response.equals("Code Requesting")){ printStream.println("Core Code"); } Log.i("TCP", "Code Send Completed"); printStream.close(); } catch (IOException e) { Log.e("TCP", "Connecting Failed"); e.printStackTrace(); }finally { try{ if(printStream != null){ printStream.close(); } if(inFromServer != null){ inFromServer.close(); } }catch (IOException e){ // } } socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } } <file_sep>import logging DEFAULT_MASTER_PORT=11311 class Master(object): def __init__(self, port=DEFAULT_MASTER_PORT, num_workers=rosmaster.master_api.NUM_WORKERS): self.port = port self.num_workers = num_workers def start(self): """ Start the ROS Master. """ self.handler = None self.master_node = None self.uri = None handler = rosmaster.master_api.ROSMasterHandler(self.num_workers) master_node = rosgraph.xmlrpc.XmlRpcNode(self.port, handler) master_node.start() while not master_node.uri: time.sleep(0.0001) self.handler = handler self.master_node = master_node self.uri = master_node.uri logging.getLogger('rosmaster.master').info("Master initialized: port[%s], uri[%s]", self.port, self.uri) def ok(self): if self.master_node is not None: return self.master_node.handler._ok() else: return False def stop(self): if self.master_node is not None: self.master_node.shutdown('Master.stop') self.master_node = None <file_sep>import logging import time DEFAULT_MASTER_PORT=11311 <file_sep># Code-Splitting-for-Car- Car Secure Booting &amp; Secure Infotainment system <file_sep>package server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class CarControlModule { public static void main(String[] args) { ServerSocket server = null; Socket client = null; try { server = new ServerSocket(7880); while (true) { client = server.accept(); System.out.println("User App Connect Acceppted"); process(client); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void process(Socket socket) throws IOException { BufferedReader br = null; String command = null; PrintStream ps = null; try { br = new BufferedReader(new InputStreamReader(socket.getInputStream())); ps = new PrintStream(socket.getOutputStream()); command = br.readLine(); command = command.toLowerCase(); if (command.equals("open")) { System.out.println("Open Message Received"); processOpen(br, ps); } ps.println("Open Message Received!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (br != null) { System.out.println("Buffered Reader Close"); br.close(); } if (socket != null) { System.out.println("User Socket Close\n"); socket.close(); } } } private static String processOpen(BufferedReader br, PrintStream ps) throws IOException { boolean b = false; b = authenticateUser(br, ps); if (!b) { return "auth failed"; } b = verifyOpen(); if (!b) { return "Open failed"; } b = execCore(br, ps); if(!b) { return "Get CoreCode failed"; } powerONInfotainment(); return "OK"; } private static boolean authenticateUser(BufferedReader br, PrintStream ps) throws IOException { int code = 0; String ret = null; int retcode = 0; code = 10; ps.println(String.valueOf(code)); ret = br.readLine(); retcode = Integer.parseInt(ret); if(retcode != (code + 1)) { return false; } return true; } private static boolean verifyOpen() { return true; } private static boolean execCore(BufferedReader br, PrintStream ps) throws IOException { String ret = null; ps.println("Code Requesting"); ret = br.readLine(); System.out.println(ret); ret = ret.toLowerCase(); System.out.println(ret); if(!ret.equals("core code")) { return false; } System.out.println("CoreCode Received\n"); System.out.println("Code Reconstruction...\n"); try { Runtime.getRuntime().exec("/Users/kyungrikim/Desktop/a.out"); }catch(Exception e) { e.printStackTrace(); } return true; } private static void powerONInfotainment() throws IOException { Socket infotainment = null; PrintStream ps = null; String ip = "192.168.137.220"; int port = 8888; try { infotainment = new Socket(ip, port); System.out.println("Infotainment Connect Requested"); ps = new PrintStream(infotainment.getOutputStream()); System.out.println("Send PowerON Message To INFO"); ps.println("PowerON"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (ps != null) { System.out.println("INFO PrintStream Close"); ps.close(); } if (infotainment != null) { System.out.println("INFO Socket Close"); infotainment.close(); } } } }
4de9077885fc05ef4c9ac0f7b7a707070c93ebf5
[ "Java", "Markdown", "Python" ]
8
Java
HyeminS/Code-Splitting-for-Car-
afa052a6aec9229e90042fc1c6f6ec7ba4068818
15d805ce090011396ca9d8635a312561c94420d9
refs/heads/master
<repo_name>sukilo/TheNeW<file_sep>/app/src/main/java/ca/bcit/practice/onMarkerClicked.java package ca.bcit.practice; import android.content.Intent; import android.net.Uri; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.android.gms.maps.GoogleMap; public class onMarkerClicked extends AppCompatActivity { private GoogleMap mMap; private DrawerLayout mDrawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_onmarkerclicked); // set toolbar as action bar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); //drawer button ActionBar actionbar = getSupportActionBar(); actionbar.setDisplayHomeAsUpEnabled(true); actionbar.setHomeAsUpIndicator(R.drawable.ic_dehaze_white_24dp); //change state and position mDrawerLayout = findViewById(R.id.drawer_layout); mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } }); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // set item as selected to persist highlight menuItem.setChecked(true); // close drawer when item is tapped switch (menuItem.getItemId()) { case R.id.nav_home: Intent home = new Intent(onMarkerClicked.this, Home.class); startActivity(home); break; case R.id.nav_about: Intent about = new Intent(onMarkerClicked.this, AboutUs.class); startActivity(about); break; case R.id.nav_settings: Intent settings = new Intent(onMarkerClicked.this, Settings.class); startActivity(settings); break; } mDrawerLayout.closeDrawers(); return true; } }); Button b1 = (Button)findViewById(R.id.getDirection); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=Your location&daddr=")); startActivity(intent); } }); String getMTitle = getIntent().getStringExtra("title"); String getMDesc = getIntent().getStringExtra("desc"); TextView title = (TextView)findViewById(R.id.mTitle); TextView description = (TextView)findViewById(R.id.desc); title.setText(getMTitle); description.setText(getMDesc); } //open when tapped public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; } return super.onOptionsItemSelected(item); } } <file_sep>/app/src/main/java/ca/bcit/practice/Settings.java package ca.bcit.practice; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.preference.PreferenceManager; import android.support.design.widget.NavigationView; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.util.Locale; import java.util.Set; public class Settings extends AppCompatActivity { private DrawerLayout mDrawerLayout; private String LANG_CURRENT = "en"; SharedPreferences preferences1; SharedPreferences preferences2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); // set toolbar as action bar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); //drawer button ActionBar actionbar = getSupportActionBar(); actionbar.setDisplayHomeAsUpEnabled(true); actionbar.setHomeAsUpIndicator(R.drawable.ic_dehaze_white_24dp); //change state and position mDrawerLayout = findViewById(R.id.drawer_layout); mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } }); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // set item as selected to persist highlight menuItem.setChecked(true); // close drawer when item is tapped switch (menuItem.getItemId()) { case R.id.nav_home: Intent home = new Intent(Settings.this, Home.class); startActivity(home); break; case R.id.nav_about: Intent about = new Intent(Settings.this, AboutUs.class); startActivity(about); break; case R.id.nav_settings: Intent setting = new Intent(Settings.this, Settings.class); startActivity(setting); break; } mDrawerLayout.closeDrawers(); return true; } }); findViewById(R.id.change).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (LANG_CURRENT.equals("en")) { changeLang(Settings.this, "ko"); } else { changeLang(Settings.this, "en"); } //finish(); //recreate(); startActivity(new Intent(Settings.this, Settings.class)); } }); } //open when tapped public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; } return super.onOptionsItemSelected(item); } public void changeLang(Context context, String lang) { preferences1 = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences1.edit(); editor.putString("Language", lang); editor.apply(); } @Override protected void attachBaseContext(Context newBase) { preferences2 = PreferenceManager.getDefaultSharedPreferences(newBase); LANG_CURRENT = preferences2.getString("Language", "en"); super.attachBaseContext(MyContextWrapper.wrap(newBase, LANG_CURRENT)); } } <file_sep>/app/src/main/java/ca/bcit/practice/Home.java package ca.bcit.practice; import android.content.Intent; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageButton; public class Home extends AppCompatActivity { private DrawerLayout mDrawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // set toolbar as action bar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); //drawer button ActionBar actionbar = getSupportActionBar(); actionbar.setDisplayHomeAsUpEnabled(true); actionbar.setHomeAsUpIndicator(R.drawable.ic_dehaze_white_24dp); //change state and position mDrawerLayout = findViewById(R.id.drawer_layout); mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } }); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // set item as selected to persist highlight menuItem.setChecked(true); // close drawer when item is tapped switch (menuItem.getItemId()) { case R.id.nav_home: Intent home = new Intent(Home.this, Home.class); startActivity(home); break; case R.id.nav_about: Intent about = new Intent(Home.this, AboutUs.class); startActivity(about); break; case R.id.nav_settings: Intent setting = new Intent(Home.this, Settings.class); startActivity(setting); break; } mDrawerLayout.closeDrawers(); return true; } }); ImageButton button1 = (ImageButton)findViewById(R.id.family); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(Home.this, MapsActivity.class); startActivity(i); } }); ImageButton button2 = (ImageButton)findViewById(R.id.education); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i2 = new Intent(Home.this, MapsActivity2.class); startActivity(i2); } }); ImageButton button3 = (ImageButton)findViewById(R.id.settlement); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i3 = new Intent(Home.this, MapsActivity3.class); startActivity(i3); } }); ImageButton button4 = (ImageButton)findViewById(R.id.housing); button4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i4 = new Intent(Home.this, MapsActivity4.class); startActivity(i4); } }); //add animation to HOME buttons ImageButton b1 = (ImageButton)findViewById(R.id.family); Animation a1 = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.slide_in); b1.startAnimation(a1); ImageButton b2 = (ImageButton)findViewById(R.id.education); Animation a2 = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.slide_in); a2.setStartOffset(200); b2.startAnimation(a2); ImageButton b3 = (ImageButton)findViewById(R.id.settlement); Animation a3 = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.slide_in); a3.setStartOffset(400); b3.startAnimation(a3); ImageButton b4 = (ImageButton)findViewById(R.id.housing); Animation a4 = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.slide_in); a4.setStartOffset(600); b4.startAnimation(a4); } //open when tapped public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; } return super.onOptionsItemSelected(item); } }<file_sep>/app/src/main/res/values/colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <color name="white">#ffffff</color> <color name="black">#000000</color> <color name="navy">#c99b49</color> <color name="yellow">#FFC90E</color> <color name="whiteTrans">#33ffffff</color> </resources>
1d02c3afb7aa905dda5b0d3bfc996b48541d5465
[ "Java", "XML" ]
4
Java
sukilo/TheNeW
68c73e868fda0a9f6b9088ec82440533d3ce5f49
c7e17ac5c5a6dbd4fd542be9fe759c6271a174bc
refs/heads/master
<repo_name>PavelVlasenko/SecurityManager<file_sep>/src/SecurityManagerTool.java import java.security.AccessController; /** * Security manager for policy files * * @author <NAME> */ public class SecurityManagerTool { SecurityManager security; /** * Init security manager with policy file * * @param filePath Security policy file path */ public void loadPolicyFile(String filePath) { System.setProperty("java.security.policy","file:"+filePath); security = new SecurityManager(); System.setSecurityManager(security); } public void checkOpenFile(String filePath) { try { if(security != null) { security.getSecurityContext(); security.checkRead(filePath); } else { System.out.println("Security manager not init"); SecurityManager security = System.getSecurityManager(); } //if safe do this action System.out.println("Safe operation"); } catch(SecurityException e) { //if unsafe do this action System.out.println("Unsafe operation"); } } } <file_sep>/src/Main.java import com.sun.jmx.remote.security.SubjectDelegator; import javax.security.auth.Subject; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.AccessController; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.Enumeration; public class Main { public static void main(String[] args) throws Exception { testAuthJAAS(); } /** * JAAS Authentification and implementation doAs and doAsPrivileged method */ public static void testAuthJAAS() { // Initialize JAAS Authentificator and try to login JAAS_Authentificator auth = new JAAS_Authentificator(); auth.initialize("file:///home/pvlasenko/security.jks", "bob", "file:///home/pvlasenko/key.txt", "file:///home/pvlasenko/prkey.txt"); auth.auth(); //DoAs Method Subject.doAs(auth.subject, new ExampleAction()); //DoAsPrivileged Subject.doAsPrivileged(auth.subject, new ExampleAction(), AccessController.getContext()); } public static void testPolicy() { SecurityManagerTool securityManagerTool = new SecurityManagerTool(); securityManagerTool.loadPolicyFile("/home/pvlasenko/Documents/Upwork/SecurityManager/security.config"); //test System.out.println("Unsafe operation test"); securityManagerTool.checkOpenFile("/home/pvlasenko/test/testFileUnsafe.txt"); System.out.println("Safe operation"); securityManagerTool.checkOpenFile("/home/pvlasenko/test/testFileSafe.txt"); } public static void testCert() { FileInputStream is = null; try { File file = new File("/home/pvlasenko/security.jks"); is = new FileInputStream(file); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); String password = "<PASSWORD>"; keystore.load(is, password.toCharArray()); // Print all keys and certificate /*Enumeration enumeration = keystore.aliases(); while(enumeration.hasMoreElements()) { String alias = (String)enumeration.nextElement(); System.out.println("alias name: " + alias); Certificate certificate = keystore.getCertificate(alias); System.out.println(certificate.toString()); }*/ String allias = "bob"; Certificate c = keystore.getCertificate(allias); CertificateFactory fact = CertificateFactory.getInstance("X.509"); FileInputStream is2 = new FileInputStream ("/home/pvlasenko/bob.crt"); Certificate cer = fact.generateCertificate(is2); boolean compare = c.equals(cer); } catch (java.security.cert.CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if(null != is) try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
1c9eb565dc3bb570de927a42a09c5c86d7be51cf
[ "Java" ]
2
Java
PavelVlasenko/SecurityManager
32cbe57f4240ebbba100f225fcee5a40ab619530
0e13f3ceecdd0bc5c33e623d563a1d12a34e6945
refs/heads/master
<repo_name>n2code/ssync<file_sep>/readme.md # sync files all over the place **ssync** (**s**ystem **sync**) is a symlinking git wrapper for [config] files. :construction: *Still under development but apparently stable. Keep backups though, just in case.* ## Synopsis It acts as a wrapper to put any file into its repository and puts a symlink in the original place. This allows to apply version control without having to store stuff in one place or litter your drive with separate repositories. The idea is to synchronize multiple machines this way by synchronizing everything that is not created by packages but was placed or configured manually. If you only care about files in `/etc` you might want to have a look at [etckeeper](https://github.com/joeyh/etckeeper), if manually gitting `~/.config` is enough, fine... but if you like to unify all of this and would like to have full control over a selective set of files **ssync** might be just the right tool for you. ## Requirements - Dependencies - `git` version 2.X - `rsync` (tested with version 3) - GNU's `coreutils`, `bash` version 4 - Permissions - needs to run as **root** to properly deal with file permissions ## Setup & Usage As root user these are the first steps to get started: ``` # ssync ``` ssync will tell you to edit the config template created at `/etc/ssync.conf`. Afterwards execute the setup: ``` # ssync setup new ``` On subsequent installations you would call `ssync setup` but for now the `new` parameter is required to create a new ssync-compatible repository and push it upstream. Look at the initial commit: ``` # ssync log ``` For the moment the repo is clean: ``` # ssync status ``` Add some files or folders to keep in sync: ``` # ssync add /etc/bash.bashrc # ssync add foo_file # ssync add /root/bar_directory ``` This moves the specified paths to the repository and puts symlinks in their original places. Now `ssync status` will show these recent changes. To remove repository contents and restore them try: ``` # ssync rm /root/bar_directory ``` To synchronize your files to other machines package the changes with ``` # ssync commit "added some files" ``` and publish them: ``` # ssync publish ``` After installing ssync on another machine you can would use ``` # ssync update ``` to fetch the latest changes. **For a full command overview use: `ssync help`** <file_sep>/usr/bin/ssync #!/bin/bash ####################################################### # ssync - a symlinking git wrapper for [config] files # # URL: https://github.com/n2code/ssync # # Licensed under the terms of the MIT license. # ####################################################### #check system requirements startup_fails=0 programs="bash git rsync" for program in $programs; do command -v $program >/dev/null 2>&1 || { echo "ssync requires $program, please install it." 1>&2; ((startup_fails++)); } done [[ $startup_fails -eq 0 ]] || { echo "[!] Requirements for running ssync not fulfilled." 1>&2; exit 1; } function main { #file descriptor #9 is our verbose output, all superfluous information goes there if [[ "$1" == "verbose" ]]; then shift exec 9>&1 else exec 9>/dev/null fi #ssync command mainarg="$1" shift callname="$( basename "${BASH_SOURCE[0]}" )" if [[ "$mainarg" =~ ^help|-h|--help$ ]]; then usagehelp && exit 0 fi #root is required for almost all commands assert_root script_path="/usr/bin/ssync" config_path="/etc/ssync.conf" config_template_path="/usr/share/ssync/ssync.conf.template" #check config file or offer template check_properly_configured #config valid, load them! source "$config_path" permfile="ssync-file-permissions" linkindex="ssync-linkindex" #if setup complete check proper access check_setup #alright, let's get to work and process the ssync command case "$mainarg" in setup) sync_setup "$1";; uninstall) sync_uninstall;; fix) sync_fix;; add|rm|check) let c_ok=0 c_fail=0 #loop over arguments if multiple files given/globbed while : ; do #normalize: calculate resolved non-repo path and strip repo fullpath="$(realpath --quiet --canonicalize-missing --no-symlinks "$1")" fullpath="${fullpath##"$syncrepo/files"}" if [[ -z "$fullpath" ]]; then errecho "ERROR, no path given!" helphint && exit 1 fi #execute and record status message case "$mainarg" in add) sync_add "$fullpath";; rm) sync_rm "$fullpath";; check) sync_check "$fullpath";; esac if [[ "$?" != "0" ]]; then ((c_fail++)); else ((c_ok++)); fi shift [[ "$1" ]] || break done if [[ "$mainarg" != "check" ]]; then if ((c_ok + c_fail > 1 && c_fail > 0)); then errecho "[!] Multiple files given: $c_ok ok, $c_fail failed" fi fi ((c_fail == 0)) ;; commit) sync_commit "$1";; links) sync_links;; status) sync_status;; log) sync_log;; update) sync_update;; publish) sync_publish;; reset) sync_reset;; git) case "$1" in override) shift git "$@" ;; diff|log|shortlog|show|status) cd "$syncrepo" && git "$@" ;; *) errecho "AVOID THESE GIT COMMANDS TO KEEP SSYNC WORKING PROPERLY.\nUse the designated ssync commands instead:" helphint errecho "If you are absolutely sure about what you are doing:\n ssync git override $1 ..." exit 1 ;; esac ;; *) usagehelp && exit 1;; esac } ############################################################## #################### SETUP AND HELPERS #################### ############################################################## function errecho { echo -e "$1" 1>&2 } function is_root { [[ $EUID -eq 0 ]] } function assert_root { #make sure user is root unless simple querying commands are called if ! is_root && ! [[ "$mainarg" =~ ^check|status|log|links$ ]]; then errecho "This must be run as root." exit 1 fi } function check_properly_configured { #look if config file exists and differs from template, otherwise copy it and display explanation if ( test ! -f "$config_path" ) || ( cmp -s "$config_template_path" "$config_path" >/dev/null ); then if cp "$config_template_path" "$config_path"; then echo "Welcome to ssync! A default configuration was copied to $config_path Edit this file and restart this setup by using ssync setup new for a first time installation. This initializes a fresh repo and pushes it upstream. Otherwise use ssync setup for subsequent installations - this will only pull from GITURL." else echo "Unable to copy default configuration to $config_path" assert_root fi exit 1 fi } function check_setup { if [[ "$mainarg" == "setup" ]]; then #calling setup does not require setup return 0 fi #setup is complete if local git repo exists if ! [[ -e "$syncrepo/.git" ]]; then errecho "ERROR: Setup not completed.\nNo repository found in $syncrepo" helphint && exit 1 fi if ! [[ -e "$syncrepo/$permfile" && -e "$syncrepo/$linkindex" ]]; then errecho "ERROR: No valid ssync repository in $syncrepo\n$permfile or $linkindex missing." exit 1 fi check_branch "$machinebranch" } function helphint { errecho " => $callname help" } function usagehelp () { echo "USAGE: $callname [verbose] COMMAND ssync (system sync) is a symlinking git wrapper for [config] files. COMMANDS: setup [new] Initializes ssync. If config file is not found a template is created and the user is prompted to edit it and execute this command again. Adding the \"new\" option creates the necessary repository structures and pushes them to an empty git repository with the specified GITURL, otherwise it is simply cloned. add PATH Move file or folder to repository to enable synchronization. This creates a symlink in its original place. rm PATH Unlink element in repository and restore original file/folder. It is not possible to remove children of a linked parent folder. check PATH Query if path is part of repository. status Display changes since last commit (added or removed entries). commit [MESSAGE] Bundle changes in a commit for synchronization. reset Discard all uncommitted changes. update Fetch latest changes from central repository and merge them. publish Publish local changes/merges. Automatically updates first. links List paths of all repository elements. uninstall Restore (see \"rm\" command) all contents and delete local repository. git ... Pipe git command through to underlying git." } function ask_confirm { #query user for positive confirmation, has a timeout which returns failure local message="$1" answer while [[ ! "$answer" =~ ^[yYnN]$ ]]; do if ! read -r -n 1 -p "$message [y/n]: " -t 30 answer < /dev/tty; then answer="n" echo -n "$answer (chosen by timeout)" fi echo done if [[ "$answer" =~ ^[yY]$ ]]; then return 0; else return 1; fi } ############################################################## #################### CORE FUNCTIONS #################### ############################################################## function is_gpg_enabled { #is gpgkey configured in config file? if [[ ! -z "$gpgkey" ]]; then return 0; else return 1; fi } function gpg_check { #makes sure given git reference is trusted local testedref="$1" if is_gpg_enabled; then echo -n "GPG check for $testedref... " if ! git verify-commit "$testedref" 2>&1; then errecho "\n########## GPG TRUST FAIL! ##########" exit 1 else echo "ok" fi fi return 0 } function is_indexed { #is given entry in index file? local matches matches="$(grep --count --fixed-strings --line-regexp "$2" "$1")" case "$matches" in "0") return 42;; "1") return 0;; *) errecho "WARNING: $1 corrupt. Duplicate entries!"; return 0;; esac } function add_to_index { #adds entry to sorted index file local indexfile="$1" location="$2" if is_indexed "$indexfile" "$location"; then errecho "WARNING: Attempt to add already index entry to $1" else echo "$location" | LC_ALL=C sort -o "$indexfile" - "$indexfile" fi } function remove_from_index { #deletes entry from index file local indexfile="$1" location="$2" tmpindex if ! is_indexed "$indexfile" "$location"; then errecho "WARNING: Attempt to remove non-indexed entry from $indexfile" else #temporary copy to modify index itself tmpindex="$(mktemp)" cp "$indexfile" "$tmpindex" grep --invert-match --fixed-strings --line-regexp "$location" "$tmpindex" > "$indexfile" rm "$tmpindex" fi } function is_child_of { #tests if a path is a child of another path, normalized to non-repo path local child="$1" parent="$2" reduced #resolve links child="$(readlink -m "$child")" parent="$(readlink -m "$parent")" #strip repo if currently synced child="${child##"$syncrepo/files"}" parent="${parent##"$syncrepo/files"}" #remove base from path and see if path has changed (check for starting slash to account for partial directory names having been removed) reduced="${child##"$parent"}" if [[ "$reduced" != "$child" ]] && [[ "$reduced" == /* ]]; then return 0; else return 1; fi } function is_in_repo { #is path versioned in repo? local tested="$1" line while read line; do if [[ "$tested" == "$line" ]]; then echo "In repository index: $tested" >&9 return 0 elif is_child_of "$tested" "$line"; then echo "Parent in repository: $line" >&9 return 0 fi done <"$syncrepo/$linkindex" return 1 } function has_child_in_repo { #are children of this path versioned in repo? local parent="$1" line while read line; do if is_child_of "$line" "$parent"; then echo "Child in repository: $line" >&9 return 0 fi done <"$syncrepo/$linkindex" return 1 } function mkdir_p_confirm_inheritance { local dir="$1" local parent="$(dirname "$dir")" if [[ ! -e "$parent" ]]; then mkdir_p_confirm_inheritance "$parent" || return 1 fi if [[ ! -d "$dir" ]]; then mkdir -v "$dir" >&9 || return 1 if ask_confirm "Inherit ownership and mode for newly created directory $dir from parent?"; then chown --changes -- "$(stat --printf="%U:%G" "$parent")" "$dir" >&9 \ && chmod --changes "$(stat --printf="%04a" "$parent")" "$dir" >&9 fi fi } function add_clone_link { #creates a repo-pointing link (and necessary parent directories) local original="$1" link="$2" echo -n "Creating link: " >&9 \ && mkdir_p_confirm_inheritance "$(dirname "$link")" \ && ln --symbolic --verbose -- "$original" "$link" >&9 } function is_index_changed { if [[ -z "$(cd "$syncrepo" && git status --porcelain "$linkindex")" ]]; then return 1; else return 0; fi } function save_permissions { #saves versioned files' permissions to permission index local line hit #edge case: no files versioned yet if [[ ! -e "$syncrepo/files" ]]; then return 0; fi cd "$syncrepo" while read -u 3 line; do #gitignored files wont be synced so avoid recording their stats if ! git check-ignore --quiet "$line"; then hit="${line##"$syncrepo/files"}" #make absolutely sure that this file is wanted #probably not necessary at this point, tbh... if is_in_repo "$hit" 9>/dev/null; then #no dereferencing to get versioned symlinks' permissions as well echo "$(stat --printf="%04a:%U:%G" "$line"):$hit" fi fi done 3< <(find -P "$syncrepo/files" -mindepth 1 | LC_ALL=C sort) > "$syncrepo/$permfile" } function restore_permissions { #restores versioned files' permissions from permission index local mod user group location echo "Adjusting permissions..." while IFS=: read -u 3 -r mod user group location; do virtuallocation="$location" location="$syncrepo/files$location" if [[ -L "$location" || -e "$location" ]]; then #change ownership if values differ if [[ "$user:$group" != "$(stat --printf="%U:%G" "$location")" ]]; then chown --no-dereference --changes -- "$user:$group" "$location" >&9 #adjust link to repo if is_indexed "$syncrepo/$linkindex" "$virtuallocation"; then chown --no-dereference --changes -- "$user:$group" "$virtuallocation" >&9 fi fi #change permissions if they differ and not a symlink (link permissions cannot be changed) if [[ ! -L "$location" && "$mod" != "$(stat --printf="%04a" "$location")" ]]; then chmod --changes "$mod" "$location" >&9 fi else errecho "$location not found, permission restore failed." fi done 3< "$syncrepo/$permfile" } function is_repo_clean { #are the no changes to permissions and/or files? cd "$syncrepo" #update permission index so git will detect this as a file change save_permissions if [[ -z "$(git status --porcelain)" ]]; then return 0; else return 1; fi } function check_repo_clean { #makes sure repository is in committed state if is_repo_clean; then return 0 else errecho "[!] Aborting operation. Repository is not clean, see: $callname status" exit 1 fi } function check_branch { #makes sure given branch is checked out local expectedbranch="$1" if [[ "$(cd "$syncrepo" && git symbolic-ref --short --quiet HEAD)" == "$expectedbranch" ]]; then return 0 else errecho "[!] Aborting operation. Not on branch $expectedbranch as expected." exit 1 fi } ############################################################## #################### SSYNC COMMANDS #################### ############################################################## function sync_setup { exec 9>&1 if [[ "$1" == "new" ]]; then echo "SYSTEMSYNC-REPO-CREATION" echo "########################" #create a repository containing the ssync structures and push it temprepo="$(mktemp -d)" cd "$temprepo" touch "$permfile" "$linkindex" git init . git branch "$syncbranch" git checkout "$syncbranch" git config user.name "ssync" git config user.email "ssync@localhost" if is_gpg_enabled; then git config user.signingkey "$gpgkey" git config commit.gpgsign true fi git add --all git commit -m "initialized ssync repository" git remote add central "$giturl" git push -u central "$syncbranch" || { errecho "Upload failed, aborting setup." && exit 1; } rm -r "$temprepo" cd "/" fi echo "SYSTEMSYNC-SETUP" echo "################" echo "Cloning sync repository..." if ! git clone --origin origin "$giturl" "$syncrepo"; then errecho "CLONE FAILED." && exit 1 fi check_setup echo "Setting up hooks..." #these hooks trigger ssync fix on every working tree update which updates permissions and local files/links echo -e "#!/bin/bash\n$script_path fix" > "$syncrepo/.git/hooks/post-checkout" chmod u+x "$syncrepo/.git/hooks/post-checkout" cp "$syncrepo/.git/hooks/post-checkout" "$syncrepo/.git/hooks/post-merge" echo "Setting up local repository..." cd "$syncrepo" git config user.name "$gituser" git config user.email "$gitemail" git config push.default matching #Versioning files exactly as-is, apart from file mode (handled by permission restoration) git config core.autocrlf false git config core.whitespace "" git config core.fileMode false if is_gpg_enabled; then git config user.signingkey "$gpgkey" git config commit.gpgsign true fi gpg_check "origin/$syncbranch" git checkout "$syncbranch" git branch -u "origin/$syncbranch" git branch "$machinebranch" git checkout "$machinebranch" gpg_check "$machinebranch" echo "################" echo "Setup complete." } function sync_add { local passed="$1" target target="$syncrepo/files$passed" if is_in_repo "$passed"; then errecho "ERROR, already part of repository $syncrepo" elif has_child_in_repo "$passed"; then errecho "ERROR, child path already in repo" elif [[ -L "$passed" ]]; then errecho "ERROR, symlinks cannot be synced" elif [[ -e "$passed" && ( -d "$passed" || -f "$passed" ) ]]; then if [[ -d "$passed" ]]; then successmessage="Directory sync added." elif [[ -f "$passed" ]]; then successmessage="File sync added." fi rsync --recursive --links --perms --times --group --owner --relative --devices --specials --verbose "$passed/" "$syncrepo/files/" >&9 \ && rm --recursive --verbose -- "$passed" >&9 \ && echo "Relinking former location..." >&9 \ && add_clone_link "$target" "$passed" \ && chown --no-dereference --reference="$target" --verbose -- "$passed" >&9 \ && chmod --reference="$target" --changes -- "$passed" >&9 \ && add_to_index "$syncrepo/$linkindex" "$passed" \ && echo "$successmessage" >&9 \ && return 0 else errecho "ERROR, source directory or file not found" fi return 1 } function sync_rm { local passed="$1" repodata repodata="$syncrepo/files$passed" if ! is_indexed "$syncrepo/$linkindex" "$passed"; then errecho "ERROR, no repository link (see: $callname links)" elif [[ ! -L "$passed" ]]; then errecho "ERROR, no symlink encountered" errecho "WARNING: $syncrepo/$linkindex corrupt. Link missing!" else rm --verbose "$passed" >&9 \ && rsync --recursive --links --perms --times --group --owner --relative --devices --specials --verbose "$syncrepo/files/.$passed" "/" >&9 \ && rm -r --verbose "$repodata" >&9 \ && remove_from_index "$syncrepo/$linkindex" "$passed" \ && echo "Restored at original location." >&9 \ && return 0 fi return 1 } function sync_commit { cd "$syncrepo" save_permissions git add --all msg="ssync: $( git diff --staged --stat | tail -n1 )" if [[ ! -z "$1" ]]; then msg="$1"; fi git commit -m "$msg" } function sync_links { cat "$syncrepo/$linkindex" } function sync_status { local changes cd "$syncrepo" changes="$(git --no-pager diff "$linkindex" | grep -E "^[+-]/.+$" | LC_ALL=C sort)" if [[ -z "$changes" ]]; then if is_repo_clean; then echo "No uncommitted changes." return 0 elif [[ "$(git status --porcelain)" =~ ^.." $permfile"$ ]]; then #if the only changes that git discovers are in the permission index: echo "There are uncommitted permission changes but no file changes." return 1 else echo "There are uncommitted file changes. (for details: $callname git status)" return 1 fi else echo -e "Links have changed:\n$changes" return 1 fi } function sync_check { if is_in_repo "$1"; then echo "In ssync repository." return 0 else echo "Not in repository." return 1 fi } function sync_fix { local location target reallocation problems=0 echo "Checking local repository against index..." while read -u 4 location; do target="$syncrepo/files$location" echo -n "$location => " >&9 #Local path is a symlink, handle conflict if not pointing to repo if [[ -L "$location" ]]; then reallocation="$(realpath --quiet --canonicalize-missing "$location")" if [[ "$reallocation" == "$syncrepo/files/"* ]]; then echo "ok" >&9 else echo "LINK CONFLICT!" >&9 errecho "The indexed symlink is not pointing to the repository as expected: $location" if ask_confirm "Delete existing symlink and link to repository instead?"; then ( rm -- "$location" && [[ ! -e "$location" ]] \ && add_clone_link "$target" "$location" ) \ || { errecho "Correcting link failed."; ((problems++)); } else ((problems++)); fi fi #otherwise confirm if existing contents can be removed elif [[ -e "$location" ]]; then echo "CONTENT CONFLICT!" >&9 errecho "Symlink to repository expected but file/folder found: $location" if ask_confirm "Delete existing file/folder and link to repository instead?"; then ( rm -r -i -- "$location" < /dev/tty && [[ ! -e "$location" ]] \ && add_clone_link "$target" "$location" ) \ || { errecho "Linking failed."; ((problems++)); } else ((problems++)); fi #last possibility: nothing present so simply add the missing link else echo "adding..." >&9 echo "Restoring missing link: $location" \ && add_clone_link "$target" "$location" \ || { errecho "Adding link failed."; ((problems++)); } fi done 4<"$syncrepo/$linkindex" if (( $problems > 0 )); then errecho "[!] WARNING: $problems problem(s) unresolved and remaining. Re-run \"$callname fix\" to check again." return 1 else #all links are in their correct place, therefore: restore_permissions echo "[i] Repository state clean." return 0 fi } function sync_log { cd "$syncrepo" && git log --graph --abbrev-commit --decorate --date-order --date=relative --format=format:'%C(bold blue)%h %C(bold green)(%ar) %C(bold yellow)%d %C(white)%s %C(dim white)[%an]%C(reset)' --all } function sync_update { local verify if is_gpg_enabled; then verify="--verify-signatures"; fi if [[ -e "$syncrepo/.git/MERGE_HEAD" ]]; then errecho "[!] Merge not complete. Fix and run: $callname commit" return 1 else #fetch sync branch, check signatures, update local pointer without checking out and finally merge in changes cd "$syncrepo" \ && git fetch origin \ && check_repo_clean \ && gpg_check "$machinebranch" \ && gpg_check "origin/$syncbranch" \ && git branch --quiet -f "$syncbranch" "origin/$syncbranch" \ && { git merge --ff $verify "$syncbranch" && echo "[i] Updated from central repository." && return 0 \ || { errecho "[!] Merge needs manual intervention. Do so and run: $callname commit" && return 1; }; } \ || { errecho "[!] Update failed." && return 1; } fi } function sync_publish { #update (pull+merge) and push - that's all! cd "$syncrepo" \ && echo "Updating..." \ && sync_update > /dev/null \ && echo "Publishing..." \ && gpg_check "$machinebranch" \ && git branch -f "$syncbranch" "$machinebranch" \ && git push origin "$syncbranch" \ && echo "[i] Published changes." } function sync_uninstall { echo "This will restore all the content that is currently controlled by ssync and delete the local repository ($syncrepo)." if ask_confirm "Are you ABSOLUTELY sure you want to do this?" && ask_confirm "Seriously, you understand the consequences and want to proceed?"; then if [[ -s "$syncrepo/$linkindex" ]]; then "$script_path" verbose rm $(cat "$syncrepo/$linkindex") fi if [[ -s "$syncrepo/$linkindex" ]]; then errecho "\n[!] Something went wrong. Aborting uninstall." else rm -r "$syncrepo" \ && echo "[i] Uninstall successful." \ && return 0 fi fi return 1 } function sync_reset { cd "$syncrepo" if ask_confirm "All uncommitted changes will be lost. Continue?"; then added="$(git --no-pager diff "$linkindex" | grep --only-matching --color=never -P "^[+]\K/.+$")" removed="$(git --no-pager diff "$linkindex" | grep --only-matching --color=never -P "^[-]\K/.+$")" #Undo ssync add/rm since last commit if [[ ! -z "$added" ]]; then echo -e "Added since commit:\n$added\nRestoring..." "$script_path" rm $added fi if [[ ! -z "$removed" ]]; then echo -e "Removed since commit:\n$removed\nRelinking..." "$script_path" add $removed fi #If correctly undone reset git if ! is_index_changed; then echo "Resetting git..." git reset --hard "$machinebranch" \ && git checkout --quiet "$machinebranch" \ && echo "[i] Resetted to committed state." \ && return 0 else errecho "[!] Reset not completed. Try again." fi fi return 1 } ### Actual execution ### main "$@" #Goodbye!
14e8eb9f19060af5a878b58d4ec0ff1096886e69
[ "Markdown", "Shell" ]
2
Markdown
n2code/ssync
ff421600b95fd2557e33663168f7a2b41420fab7
93625e750a12ef5da9326292a1477e1288560bc5
refs/heads/master
<file_sep># todo-chrome-extension A simple todo chrome extension with html, css, javascript ![alt text](http://res.cloudinary.com/dripiece/image/upload/c_scale,w_374/v1629740739/todoextension_atouku.png) ![alt text](http://res.cloudinary.com/dripiece/image/upload/c_scale,w_390/v1629747656/todoextension1_ne12bc.png)
3ef9aa02f9167ef3a7143ee1c3f4cbb7eb92424b
[ "Markdown" ]
1
Markdown
onmarx/todo-chrome-extension
9e1fe363fee9602bc985e40b875106e5707ef355
8b0deb4b9f5d2e03ce9cb57818b851edec44cc5c
refs/heads/master
<file_sep>![](https://github.com/MiguelRAvila/ZenDmenu/blob/master/rsc/ss.png) > ### 🚀 Floating and enhanced dmenu build ### Patches - Center dmenu - Floating in the top of screen - Search Highlight - Lineheight - More Colors - Cleaner design (Removed '<' and '>') ### Installation 1. Clone this repo with `git clone https://github.com/MiguelRAvila/CleanDmenu.git` 2. Run `cd CleanDmenu` 3. Run `sudo make install` 4. Now you can run it with `cldmenu_run` (you can use `-l 15` flag for the list style with 15 elements) 5. ENJOY! 🚀 > In other to not interfer with the dmenu utility, the program will run with `cldmenu` in stead of `dmenu`. ### Customization > #### 🌟 You can customize the *width*, *font* and *colors* in the `config.h` file. ##### Colors: You can modify colors here (line 10), I wrote some comments for an easy change. Note: By default It has the Miramare color scheme. ![](https://github.com/MiguelRAvila/ZenDmenu/blob/master/rsc/code1.png) ##### Width: In line 3: `static int min_width = 400;` You change the numeric value for a different width ##### Font: In line 6: `"Proxima Nova:size=11"` You can change the font and size. <file_sep>/* ___ _ ___ / __| |___ __ _ _ _ | \ _ __ ___ _ _ _ _ | (__| / -_) _` | ' \| |) | ' \/ -_) ' \ || | \___|_\___\__,_|_||_|___/|_|_|_\___|_||_\_,_| Floating and enhanced dmenu build */ static int topbar = 20; /* -b option; if 0, dmenu appears at bottom */ static int centered = 1; /* -c option; centers dmenu on screen */ static int min_width = 800; /* minimum width when centered */ /* -fn option overrides fonts[0]; default X11 font or font set */ static const char *fonts[] = { "Proxima Nova:size=10" }; static const char *prompt = NULL; /* -p option; prompt to the left of input field */ static const char *colors[SchemeLast][2] = { /* foreground background */ [SchemeNorm] = { "#eaeaea", "#0f0f0f" }, /* Background color */ [SchemeSel] = { "#0f0f0f", "#e6d6ac" }, /* Main selection color */ [SchemeSelHighlight] = { "#1F2229", "#e6d6ac" }, /* Highlight slectioned color */ [SchemeNormHighlight] = { "#1F2229", "#e68183" }, /* Highlight no-slectioned color */ [SchemeOut] = { "#000000", "#00ffff" }, /* Secondary Color */ [SchemeMid] = { "#eaeaea", "#0f0f0f" }, /* Secondary Color */ }; /* -l option; if nonzero, dmenu uses vertical list with given number of lines */ static unsigned int lines = 0; static unsigned int lineheight = 18; /* -h option; minimum height of a menu line */ /* * Characters not considered part of a word while deleting words * for example: " /?\"&[]" */ static const char worddelimiters[] = " "; /* Size of the window border */ static unsigned int border_width = 0; /* -bw option; to add border width */ <file_sep># cldmenu - enhanced dynamic menu # See LICENSE file for copyright and license details. include config.mk SRC = drw.c cldmenu.c stest.c util.c OBJ = $(SRC:.c=.o) all: options cldmenu stest options: @echo cldmenu build options: @echo "CFLAGS = $(CFLAGS)" @echo "LDFLAGS = $(LDFLAGS)" @echo "CC = $(CC)" .c.o: $(CC) -c $(CFLAGS) $< config.h: cp config.def.h $@ $(OBJ): arg.h config.h config.mk drw.h cldmenu: cldmenu.o drw.o util.o $(CC) -o $@ cldmenu.o drw.o util.o $(LDFLAGS) stest: stest.o $(CC) -o $@ stest.o $(LDFLAGS) clean: rm -f cldmenu stest $(OBJ) cldmenu-$(VERSION).tar.gz dist: clean mkdir -p cldmenu-$(VERSION) cp LICENSE Makefile README arg.h config.def.h config.mk cldmenu.1\ drw.h util.h cldmenu_path cldmenu_run stest.1 $(SRC)\ cldmenu-$(VERSION) tar -cf cldmenu-$(VERSION).tar cldmenu-$(VERSION) gzip cldmenu-$(VERSION).tar rm -rf cldmenu-$(VERSION) install: all mkdir -p $(DESTDIR)$(PREFIX)/bin cp -f cldmenu cldmenu_path cldmenu_run stest $(DESTDIR)$(PREFIX)/bin chmod 755 $(DESTDIR)$(PREFIX)/bin/cldmenu chmod 755 $(DESTDIR)$(PREFIX)/bin/cldmenu_path chmod 755 $(DESTDIR)$(PREFIX)/bin/cldmenu_run chmod 755 $(DESTDIR)$(PREFIX)/bin/stest mkdir -p $(DESTDIR)$(MANPREFIX)/man1 sed "s/VERSION/$(VERSION)/g" < cldmenu.1 > $(DESTDIR)$(MANPREFIX)/man1/cldmenu.1 sed "s/VERSION/$(VERSION)/g" < stest.1 > $(DESTDIR)$(MANPREFIX)/man1/stest.1 chmod 644 $(DESTDIR)$(MANPREFIX)/man1/cldmenu.1 chmod 644 $(DESTDIR)$(MANPREFIX)/man1/stest.1 uninstall: rm -f $(DESTDIR)$(PREFIX)/bin/cldmenu\ $(DESTDIR)$(PREFIX)/bin/cldmenu_path\ $(DESTDIR)$(PREFIX)/bin/cldmenu_run\ $(DESTDIR)$(PREFIX)/bin/stest\ $(DESTDIR)$(MANPREFIX)/man1/cldmenu.1\ $(DESTDIR)$(MANPREFIX)/man1/stest.1 .PHONY: all options clean dist install uninstall <file_sep>#!/bin/sh cldmenu_path | cldmenu "$@" -p "Run:" | ${SHELL:-"/bin/sh"} &
9e0caf1fb00dc089ae49ce1641a1f365473d09a1
[ "Makefile", "Markdown", "C", "Shell" ]
4
Makefile
FDT2k/CleanDmenu
75c9d9675c5cb9d08283ccd584f57980c92be6b5
8a3c3186fc2750245b0ddd683ed208e10fc736e5
refs/heads/master
<file_sep>@echo off set APK_TOOL_COMMAND="apktool\apktool.bat" set DEX2JAR_COMMAND="dex2jar-0.0.9.8\dex2jar.bat" set JD_GUI_COMMAND="jd-gui-0.3.3.windows\jd-gui.exe" set INPUT_APK=%1 if not exist %INPUT_APK% ( echo APK file does not exist. ) else ( echo Decompiling %INPUT_APK% ... echo Decompiling resources ... call %APK_TOOL_COMMAND% d -s -f "%INPUT_APK%" "%INPUT_APK:.apk=%" echo Finished decompiling resources ... echo Decompiling classes ... call %DEX2JAR_COMMAND% "%INPUT_APK:.apk=%\classes.dex" echo Finished decompiling classes ... %JD_GUI_COMMAND% "%INPUT_APK:.apk=%\classes_dex2jar.jar" ) <file_sep>AndroidDecompilor ================= Decompile APKs, can only be run on Windows system.
769048d87f5aec95c903c27524afb301cd3c2caf
[ "Markdown", "Batchfile" ]
2
Markdown
nowingfly/androiddecompilor
e1956d24e3308ad480640c20417c97f2f75b874f
6a02f733f1daac047b79695b5ab2dfebfabbdb72