Initial Commit of Project Files

- Everything you ever wanted and more. Host alongside "Mario Kart
DS.nds" provided by yourself to mess with it.
pull/3/head
RHY3756547 2017-04-28 05:35:26 +01:00
parent 371e2f8565
commit 3b47a86756
99 changed files with 20130 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*.nds
*.exe
mongoose.conf
Code/Engine/col.lua

113
Code/Audio/nitroAudio.js Normal file
View File

@ -0,0 +1,113 @@
//
// nitroAudio.js
//--------------------
// Provides an interface for playing nds music and sound effects.
// by RHY3756547
//
window.AudioContext = window.AudioContext || window.webkitAudioContext;
window.nitroAudio = new (function() {
var t = this;
var ctx;
t.sounds = [];
t.tick = tick;
t.playSound = playSound;
t.kill = kill;
t.init = init;
t.instaKill = instaKill;
t.sdat = null;
function init(sdat) {
ctx = new AudioContext();
t.ctx = ctx;
var listener = ctx.listener;
listener.dopplerFactor = 1;
listener.speedOfSound = 100/1024; //343.3
SSEQWaveCache.init(sdat, ctx);
t.sdat = sdat;
}
function tick() {
for (var i=0; i<t.sounds.length; i++) {
var snd = t.sounds[i];
snd.seq.tick();
if (snd.obj != null && snd.obj.soundProps != null && snd.panner != null) updatePanner(snd.panner, snd.obj.soundProps);
}
for (var i=0; i<t.sounds.length; i++) {
var snd = t.sounds[i];
snd.dead = snd.seq.dead;
if (snd.dead) {
snd.gainN.disconnect();
t.sounds.splice(i--, 1);
}
}
}
function kill(sound) {
if (!sound.killing) {
sound.killing = true;
sound.seq.kill();
}
}
function instaKill(sound) { //instantly kills a sound
if (sound == null) return;
var ind = t.sounds.indexOf(sound)
sound.gainN.disconnect();
if (ind == -1) return;
t.sounds.splice(ind, 1);
}
function playSound(seqN, params, arcN, obj) { //if arc is not specified, we just play a normal sequence. this allows 3 overloads.
//obj should have a property "soundProps" where it sets its falloff, position and velocity relative to the oberver occasionally
var sound = { dead: false, killing: false, obj: obj };
var output;
if (obj != null) { //if obj is not null then we have a 3d target to assign this sound to.
output = ctx.createPanner();
sound.gainN = ctx.createGain();
sound.gainN.connect(ctx.destination);
output.connect(sound.gainN);
sound.panner = output;
updatePanner(sound.panner, sound.obj.soundProps);
} else {
output = ctx.createGain();
sound.gainN = output;
output.connect(ctx.destination);
}
var player;
if (arcN == null) {
var seq = t.sdat.sections["$INFO"][0][seqN];
if (seq == null) return;
sound.seq = new SSEQPlayer(seq, t.sdat, ctx, output, params);
} else {
var arc = t.sdat.sections["$INFO"][1][arcN];
if (arc == null) return;
var seq = arc.arc.entries[seqN];
if (seq == null) return;
sound.seq = new SSEQPlayer(seq, t.sdat, ctx, output, params);
}
//now that we have the player, package it in an object
t.sounds.push(sound);
return sound;
}
function updatePanner(panner, soundProps) {
if (panner == null || soundProps == null) return;
if (soundProps.pos != null) panner.setPosition(soundProps.pos[0], soundProps.pos[1], soundProps.pos[2]);
//if (soundProps.vel != null) panner.setVelocity(soundProps.vel[0], soundProps.vel[1], soundProps.vel[2]);
if (soundProps.refDistance != null) panner.refDistance = soundProps.refDistance;
if (soundProps.panningModel != null) panner.panningModel = soundProps.panningModel;
if (soundProps.rolloffFactor != null) panner.rolloffFactor = soundProps.rolloffFactor;
}
})();

690
Code/Audio/sseqPlayer.js Normal file
View File

@ -0,0 +1,690 @@
//
// sseqPlayer.js
//--------------------
// Provides an interface for playing SSEQs onto an AudioContext.
// by RHY3756547
//
//
window.SSEQWaveCache = new (function() {
var cache = [];
var sdat, ctx;
this.cacheWaveArc = function(num) {
if (cache[num] == null) {
var warinfo = sdat.sections["$INFO"][3]
if (warinfo[num] == null) return;
var arc = warinfo[num].arc.samples;
if (arc == null) return;
cache[num] = [];
for (var i=0; i<arc.length; i++) {
cache[num].push({info: arc[i], buf: arc[i].getAudioBuffer(ctx)});
}
}
}
this.getWave = function(arc, num) {
return cache[arc][num];
}
this.init = function(s, c) {
cache = [];
sdat = s;
ctx = c;
}
})();
window.SSEQPlayer = function(sseqHead, sdat, ctx, outputTarget, properties) {
//a virtual machine, super fun obviously
//
//player handles loaded sounds.
var CYCLE_TIME = 0.0052;
var t = this;
t.bpm = 120;
t.bpmMultiplier = 1;
t.transpose = 0; //overall transpose value, only set by external factors (threads cannot set this)
t.volume = (t.volume == null)?1:t.volume;
if (properties != null) {
var p;
for (p in properties) {
if (properties.hasOwnProperty(p)) {
t[p] = properties[p];
}
}
}
var ctx = ctx;
t.ctx = ctx;
var sseqHead = sseqHead;
var sdat = sdat;
t.lastNoteEnd = 0;
t.tick = tick;
t.threads = [];
t.trackAlloc = 0;
t.trackStarted = 0;
t.playNote = playNote;
t.cutNoteShort = cutNoteShort;
t.startThread = startThread;
t.terminateThread = terminateThread;
t.setTempo = setTempo;
t.updateNoteFreq = updateNoteFreq;
t.setTranspose = setTranspose;
t.kill = kill;
t.bank = null;
t.vars = [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];
t.dead = false;
t.masterGain = ctx.createGain();
console.log("seqvol: "+(sseqHead.vol)/0x7F)
t.masterGain.gain.value = (sseqHead.vol*t.volume)/0x7F;
t.masterGain.connect((outputTarget != null)?outputTarget:ctx.destination);
startThread(sseqHead.pc); //starts a thread with its initial pc pos
loadBank(sseqHead.bank);
t.loadBank = loadBank;
var threadsToKill = [];
t.baseAudioTime = ctx.currentTime;
var buffer = 0.020;
t.remainder = 0;
tick();
function tick() {
var time = (ctx.currentTime-t.baseAudioTime)*(48*t.bpm/60)+t.remainder;
t.remainder = time%1;
time = Math.floor(time);
t.baseAudioTime = ctx.currentTime;
for (var i=0; i<t.threads.length; i++) {
t.threads[i].tick(time);
}
while (threadsToKill.length>0) {
t.threads.splice(threadsToKill.pop(), 1);
}
if (t.threads.length == 0 && ctx.currentTime > t.lastNoteEnd) t.dead = true;
}
function startThread(pc) {
var thread = new SSEQThread(sseqHead.seq.data, pc, t);
t.threads.push(thread);
}
function terminateThread(thread) {
threadsToKill.push(t.threads.indexOf(thread));
}
function setTempo(bpm) {
//sets tempo of threads and alters their wait times to adjust
t.bpm = bpm*t.bpmMultiplier;
}
function loadBank(bn) {
t.bank = sdat.sections["$INFO"][2][bn];
if (t.bank == null) {return;}
for (var i=0; i<4; i++) {
if (t.bank.waveArcs[i] != 0xFFFF) SSEQWaveCache.cacheWaveArc(t.bank.waveArcs[i]);
}
}
function cutNoteShort(thread, note) {
try { //can throw exception if note has already ended.
if (note.ended) return;
var time = thread.calculateCurrentTime();
var baseTime = (time == Infinity)?ctx.currentTime:time;
if (baseTime > note.noteEndsAt) return;
var releaseTime = note.relTime;
note.note.gain.cancelScheduledValues(baseTime);
note.note.gain.linearRampToValueAtTime(0, baseTime+releaseTime); //then release
note.src.stop(baseTime+releaseTime);
if (baseTime+releaseTime > t.lastNoteEnd) t.lastNoteEnd = baseTime+releaseTime;
} catch (e) {}
}
function setTranspose(newT) {
t.transpose = newT;
for (var i=0; i<t.threads.length; i++) {
var note = t.threads[i].lastNote;
if (note != null) updateNoteFreq(t.threads[i], note);
}
}
function updateNoteFreq(thread, note) {
var noteOffsets = (note.pitched?((thread.pitchBend/0x7F)*thread.pitchBendRange):0)+thread.transpose+t.transpose;
note.src.playbackRate.setValueAtTime((noteToFreq(note.start+noteOffsets)/note.base)/note.snd.info.mul, ctx.currentTime);
}
function kill() { //smoothly kills a sequence. If you want to instantly kill it, disconnect and then dereference it.
t.lastNoteEnd = 0;
for (var i=0; i<t.threads.length; i++) {
var note = t.threads[i].lastNote;
if (note != null) cutNoteShort(t.threads[i], note);
t.threads.splice(i--, 1);
}
}
function playNote(thread, velocity, duration, num) {
if (thread.wait < 0) console.log("warning - MIDI buffer overflowed! "+thread.wait);
velocity /= 127;
if (t.bank.bank.instruments == null) return;
var inst = t.bank.bank.instruments[thread.program];
if (inst == null) return null;
var oldinst = inst;
inst = getInst(inst, num);
if (inst == null) { /*debugger;*/ return; }
var fireNote = true;
var note;
var source;
var snd;
if (thread.tie && thread.lastNote != null) {
note = thread.lastNote.note;
source = thread.lastNote.src;
snd = thread.lastNote.snd;
} else {
note = ctx.createGain();
note.connect(thread.gain);
snd = SSEQWaveCache.getWave(t.bank.waveArcs[inst.swar], inst.swav);
source = ctx.createBufferSource();
source.loop = (snd.info.bLoop == 1);
source.loopStart = snd.info.loopSTime;
source.loopEnd = snd.buf.duration;
source.buffer = snd.buf;
source.connect(note);
}
var noteOffsets = thread.transpose+t.transpose; // (thread.pitchBend/0x7F)*thread.pitchBendRange+
var baseTime = thread.calculateCurrentTime();
var realDur = (thread.tie)?Infinity:(ticksToMs(duration)/1000);
var targetFreq = (noteToFreq(num+noteOffsets)/inst.freq)/snd.info.mul;
if (thread.portaKey&0x80) source.playbackRate.value = targetFreq; //sound frequency may have been adjusted for the device to support it
else {
//handle porta
//we need to calculate the sweep time then apply a linear transform to the playback rate to get there
//when portaTime is 0 we use the length of the note
var sweepPitch = thread.sweepPitch+(thread.portaKey-num)*(1<<6);
source.playbackRate.setValueAtTime((noteToFreq(thread.portaKey+noteOffsets)/inst.freq)/snd.info.mul, baseTime);
if (thread.portaTime == 0 && duration != Infinity) source.playbackRate.exponentialRampToValueAtTime(targetFreq, baseTime+(ticksToMs(duration)/1000));
else {
var timeS = thread.portaTime*thread.portaTime;
var time = ticksToMs((Math.abs(sweepPitch)*timeS)>>11)/1000;
source.playbackRate.exponentialRampToValueAtTime(targetFreq, baseTime+time);
}
}
//sequence the note
var atk = (thread.attack != null)?thread.attack:inst.attack;
var dec = (thread.decay != null)?thread.decay:inst.decay;
var sus = (thread.sustain != null)?thread.sustain:inst.sustainLvl;
var rel = (thread.release != null)?thread.release:inst.release;
var attackTime = calculateRequiredAttackCycles(convertAttToRate(atk))*CYCLE_TIME;//(255/convertAttToRate(inst.attack))*0.016; //0.01;
var decayTime = (92544/convertFallToRate(dec))*(1-sus/0x7F)*CYCLE_TIME/2;
var releaseTime = (92544/convertFallToRate(rel))*(sus/0x7F)*CYCLE_TIME/2;
if ((!thread.tie) || thread.lastNote == null) {
note.gain.value = 0.0;
note.gain.setValueAtTime(0.0, baseTime); //initially 0
note.gain.linearRampToValueAtTime(velocity, baseTime+attackTime); //attack
note.gain.linearRampToValueAtTime(velocity*sus/0x7F, baseTime+attackTime+decayTime); //decay
source.start(baseTime);
source.onended = function(){
note.ended = true;
source.disconnect();
}
}
if (realDur != Infinity) {
if (baseTime+attackTime+decayTime < baseTime+realDur) note.gain.linearRampToValueAtTime(velocity*sus/0x7F, baseTime+realDur); //sustain until
note.gain.linearRampToValueAtTime(0, baseTime+realDur+releaseTime); //then release
source.stop(baseTime+realDur+releaseTime);
if (baseTime+realDur+releaseTime > t.lastNoteEnd) t.lastNoteEnd = baseTime+realDur+releaseTime;
}
return {src: source, base: inst.freq, start:num, note: note, relTime: releaseTime, snd: snd, noteEndsAt:baseTime+realDur};
}
function calculateRequiredAttackCycles(att) {
var value = 92544;
var ticks = 0;
while (value > 0) {
value = Math.floor((att*value)/255);
ticks++
}
return ticks;
}
function convertAttToRate(attack) {
var table = [0x00, 0x01, 0x05, 0x0E, 0x1A, 0x26, 0x33, 0x3F, 0x49, 0x54,
0x5C, 0x64, 0x6D, 0x74, 0x7B, 0x7F, 0x84, 0x89, 0x8F];
if (attack & 0x80) return 0;
else if (attack >= 0x6F) return table[0x7F-attack];
else return 0xFF-attack;
}
function convertFallToRate(fall) {
if (fall&0x80) return 0;
else if (fall == 0x7F) return 0xFFFF;
else if (fall == 0x7E) return 0x3C00;
else if (fall < 0x32) return ((fall<<1)+1)&0xFFFF;
else return (0x1E00/(0x7E-fall))&0xFFFF;
}
function noteToFreq(n) {
return Math.pow(2, (n-49)/12)*440;
}
function getInst(inst, note) {
switch (inst.type) {
case 0:
return null;
case 1:
return inst;
case 2:
return inst.entries[Math.max(inst.lower, Math.min(inst.upper, note))-inst.lower];
case 3:
for (var i=0; i<inst.regions.length; i++) {
if (note <= inst.regions[i]) return inst.entries[i];
}
return null;
}
}
function ticksToMs(ticks) {
return (ticks/48)*(60000/t.bpm);
}
}
function SSEQThread(prog, pc, player) {
var VOLMUL = 1/4;
var t = this;
var pc = pc;
var prog = prog;
var player = player;
var comparisonResult = false;
//hacky implementation for certain instructions forcing the values of the next. thanks guys for making me have to do this
var force = false;
var forceCommand = 0;
var forceValue = 0;
var forceSpecial = 0;
t.buffer = 10; //the distance in beats where we queue notes to fire.
t.wait = 0;
t.offT = 0;
t.program = 0;
t.pitchBendRange = 1;
t.pitchBend = 0;
t.portaKey = 0x80; //is a byte, top bit is on/off (set is off).
t.portaTime = 0;
t.sweepPitch = 0;
t.transpose = 0;
t.attack = null;
t.delay = null;
t.sustain = null;
t.release = null;
t.tie = false;
t.tick = tick;
t.calculateCurrentTime = calculateCurrentTime;
t.noteWait = true;
t.loopPtr = 0;
t.loopTimes = 0;
//set up volume and pan controls
var ctx = player.ctx;
var gainL = ctx.createGain();
var gainR = ctx.createGain();
gainL.gain.value = 1;
gainR.gain.value = 1;
var merger = ctx.createChannelMerger(2);
var splitter = ctx.createChannelSplitter(2);
t.pan = 0;
t.gain = player.ctx.createGain();
t.gain.connect(gainL);
t.gain.connect(gainR);
t.gain.gain.value = VOLMUL;
//splitter.connect(gainL, 0);
//splitter.connect(gainR, 1);
gainL.connect(merger, 0, 0);
gainR.connect(merger, 0, 1);
merger.connect(player.masterGain, 0, 0);
//end audio setup
t.lastNote = null;
t.dead = false;
t.stack = [];
function tick(time) {
t.wait -= time;
t.offT = 0;
var insts = 0;
while (t.wait < t.buffer && !t.dead) {
var inst = (force)?forceCommand:prog[pc++];
if (inst<0x80) noteOn(inst);
else if (Instructions[inst] != null) Instructions[inst](inst);
else throw "bad instruction??";
if (force && inst != 0xA0 && inst != 0xA1) force = false;
if (++insts > 10000) { Instructions[0xFF](); console.error("audio thread locked up")};
}
if (t.wait == Infinity && t.lastNote != null && t.lastNote.note.ended) Instructions[0xFF]();
}
function noteOn(num) {
if (num == 0) return; //NOP
var velocity = forcableValue(true);
var length = forcableValueFunc(false, readVariableLength);
if (length == 0) length = Infinity;
t.lastNote = player.playNote(t, velocity, length, num);
if (t.noteWait) t.wait += length;
}
function ticksToMs(ticks) {
return (ticks/48)*(60000/player.bpm);
}
function readVariableLength() {
var read = prog[pc++];
var value = read&0x7F;
while (read & 0x80) {
var read = prog[pc++];
value = (value<<7) | (read&0x7F);
}
return value;
}
function calculateCurrentTime() {
return player.baseAudioTime+ticksToMs(t.wait-player.remainder)/1000;
}
var InstArgs = [ //starts at 0x80
[readVariableLength], [readVariableLength], [], [], [], [], [], [], [], [], [], [], [], [], [], [], //0x80-0x8F
[], [], [], [read8, read24], [read24], [read24], [], [], [], [], [], [], [], [], [], [], //0x90-0x9F
[read8, readSpecial, read16, read16], [read8, readSpecial], [], [], [], [], [], [], [], [], [], [], [], [], [], [],
[read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [], [], //0xB0-0xBF
[read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8],
[read8], [read8], [read8], [read8], [read8], [read8], [read8], [], [], [], [], [], [], [], [], [],
[read16], [read16], [read16], [], [], [], [], [], [], [], [], [], [], [], [], [],
[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],
]
var Instructions = [];
Instructions[0xFE] = function() { //track definition
player.trackAlloc = read16();
}
Instructions[0x93] = function() { //track definition
var trackID = prog[pc++];
var newPC = prog[pc++];
newPC |= prog[pc++]<<8;
newPC |= prog[pc++]<<16;
var bit = 1<<trackID;
if ((!(player.trackStarted&bit)) && (player.trackAlloc&bit)) {
player.trackStarted |= bit;
player.startThread(newPC);
}
}
Instructions[0x80] = function() { //rest
var length = forcableValueFunc(false, readVariableLength);
t.wait += length;
}
Instructions[0x81] = function() { //bank or program change
var dat = forcableValueFunc(false, readVariableLength);
t.program = dat&0x7F;
var bank = dat>>7;
if (bank != 0) player.loadBank(bank);
}
Instructions[0x94] = function() { //JUMP
var newPC = prog[pc++];
newPC |= prog[pc++]<<8;
newPC |= prog[pc++]<<16;
pc = newPC;
}
Instructions[0x95] = function() { //CALL
var newPC = prog[pc++];
newPC |= prog[pc++]<<8;
newPC |= prog[pc++]<<16;
t.stack.push(pc);
pc = newPC;
}
Instructions[0xFD] = function() { //RETURN
if (t.stack.length == 0) Instructions[0xFF]();
pc = t.stack.pop();
}
//LOGIC INSTRUCTIONS
Instructions[0xA0] = function() { //random
force = true; //this command forces the input to the next command to be a generated random number
forceCommand = prog[pc++];
if (forceCommand < 0x80 || (forceCommand >= 0xB0 && forceCommand <= 0xBD)) forceSpecial = prog[pc++];
var min = reads16();
var max = reads16();
forceValue = Math.floor(Math.random()*(max-min+1))+min;
}
Instructions[0xA1] = function() { //from var
force = true; //this command forces the input to the next command to be from a variable. use with caution probably!
forceCommand = prog[pc++];
if (forceCommand < 0x80 || (forceCommand >= 0xB0 && forceCommand <= 0xBD)) forceSpecial = prog[pc++];
forceValue = player.vars[prog[pc++]];
}
function varInst(inst){
var varNum = forcableValue(true);
var arg = forcableValue();
if (arg & 0x80) arg -= 256;
if (inst == 0xB4 && arg == 0) return;
varFunc[inst-0xB0](varNum, arg)
}
var varFunc = [ //"=", "+=", "-=", "*=", "/=", "[Shift]", "[Rand]"
function(a, b) { player.vars[a] = b },
function(a, b) { player.vars[a] += b },
function(a, b) { player.vars[a] -= b },
function(a, b) { player.vars[a] *= b },
function(a, b) { player.vars[a] = Math.floor(player.vars[a]/b) },
function(a, b) {
if (b < 0) player.vars[a] = player.vars[a]>>(-b);
else player.vars[a] = player.vars[a]<<b;
},
function(a, b) {
if (b < 0) player.vars[a] = -(Math.floor(Math.random()*256)%(1-b));
else player.vars[a] = -(Math.floor(Math.random()*256)%(b+1));
}
]
Instructions[0xB0] = varInst;
Instructions[0xB1] = varInst;
Instructions[0xB2] = varInst;
Instructions[0xB3] = varInst;
Instructions[0xB4] = varInst;
Instructions[0xB5] = varInst;
Instructions[0xB6] = varInst;
function boolInst(inst){
var varNum = forcableValue(true);
var arg = forcableValue();
if (arg & 0x80) arg -= 256;
comparisonResult = boolFunc[inst-0xB8](varNum, arg);
}
var boolFunc = [
function(a, b) { return player.vars[a] == b },
function(a, b) { return player.vars[a] >= b },
function(a, b) { return player.vars[a] > b },
function(a, b) { return player.vars[a] <= b },
function(a, b) { return player.vars[a] < b },
function(a, b) { return player.vars[a] != b },
]
Instructions[0xB8] = boolInst;
Instructions[0xB9] = boolInst;
Instructions[0xBA] = boolInst;
Instructions[0xBB] = boolInst;
Instructions[0xBC] = boolInst;
Instructions[0xBD] = boolInst;
Instructions[0xA2] = function() { //if#
if (!comparisonResult) {
//skip next
var inst = prog[pc++];
if (inst < 0x80) {
read8();
readVariableLength();
} else {
var cmds = InstArgs[inst-0x80];
var last = 0;
for (var i=0; i<cmds.length; i++) {
last = cmds[i](last);
}
}
}
}
//END LOGIC INSTRUCTIONS
Instructions[0xC0] = function() { var value = forcableValue(); setPan((value-64)/64) } //pan
Instructions[0xC1] = function() { var value = forcableValue(); t.gain.gain.setValueAtTime((value/0x7F)*VOLMUL, calculateCurrentTime()); } //volume
Instructions[0xC2] = function() { var value = forcableValue(); player.masterGain.gain.setValueAtTime(value/0x7F, calculateCurrentTime()); } //master volume
Instructions[0xC3] = function() { t.transpose = forcableValue(); if (t.transpose & 0x80) t.transpose -= 256; } //transpose
Instructions[0xC4] = function() {
t.pitchBend = forcableValue();
if (t.pitchBend & 128) t.pitchBend -= 256;
if (t.lastNote != null) {
t.lastNote.pitched = true;
player.updateNoteFreq(t, t.lastNote);
}
} //pitch bend
Instructions[0xC5] = function() { t.pitchBendRange = prog[pc++]; } //pitch bend range
Instructions[0xC6] = function() { var value = prog[pc++]; } //track priority
Instructions[0xC7] = function() { t.noteWait = (prog[pc++]>0); } //mono/poly
Instructions[0xC8] = function() { t.tie = prog[pc++]; if (t.lastNote != null) player.cutNoteShort(t, t.lastNote); t.lastNote = null; } //tie
Instructions[0xC9] = function() { t.portaKey = prog[pc++]; } //portamento control
Instructions[0xCA] = function() { var value = forcableValue(); } //modulation depth
Instructions[0xCB] = function() { var value = forcableValue(); } //modulation speed
Instructions[0xCC] = function() { var value = prog[pc++]; } //modulation type
Instructions[0xCD] = function() { var value = prog[pc++]; } //modulation range
Instructions[0xCE] = function() { t.portaKey = (t.portaKey&0x7F)|((!prog[pc++])<<7); } //portamento on/off
Instructions[0xCF] = function() { t.portaTime = forcableValue(); } //portamento time
Instructions[0xD0] = function() { t.attack = forcableValue(); } //attack rate
Instructions[0xD1] = function() { t.decay = forcableValue(); } //decay rate
Instructions[0xD2] = function() { t.sustain = forcableValue(); } //sustain rate
Instructions[0xD3] = function() { t.release = forcableValue(); } //release rate
Instructions[0xD4] = function() { t.loopTimes = forcableValue(); t.loopPtr = pc; } //loop start
Instructions[0xFC] = function() { if (t.loopTimes-- > 0) pc = t.loopPtr; } //loop end
Instructions[0xD5] = function() { var value = forcableValue(); } //expression
Instructions[0xD6] = function() { var value = prog[pc++]; } //print variable
Instructions[0xE0] = function() { var value = prog[pc++]; value |= prog[pc++]<<8 } //modulation delay
Instructions[0xE1] = function() {
var value = prog[pc++];
value |= prog[pc++]<<8;
player.setTempo(value);
} //set BPM
Instructions[0xE3] = function() { t.sweepPitch = forcableValueFunc(false, reads16); } //sweep pitch
Instructions[0xFF] = function() {
if (t.lastNote != null) player.cutNoteShort(t, t.lastNote);
player.terminateThread(t);
t.dead = true;
} //end of track
function read16() {
var value = prog[pc++];
value |= prog[pc++]<<8;
return value;
}
function reads16() {
var value = read16();
if (value & 0x8000) value -= 0x10000;
return value;
}
function read8() {
return prog[pc++];
}
function readSpecial(last) {
if (last < 0x80 || (last >= 0xB0 && last < 0xBD)) return prog[pc++];
else return 0;
}
function read24() {
var value = prog[pc++];
value |= prog[pc++]<<8;
value |= prog[pc++]<<16;
return value;
}
function forcableValueFunc(special, func) {
if (force) return special?forceSpecial:forceValue;
else return func();
}
function forcableValue(special) {
if (force) return special?forceSpecial:forceValue;
else return prog[pc++];
}
function setPan(value) {
t.pan = value;
if (value > 0) {
gainR.gain.value = 1;
gainL.gain.value = 1-value;
} else {
gainR.gain.value = 1+value;
gainL.gain.value = 1;
}
}
function noteToFreq(n) {
return Math.pow(2, (n-49)/12)*440;
}
}

View File

@ -0,0 +1,98 @@
//
// cameraIngame.js
//--------------------
// The ingame camera that follows the kart from behind.
// by RHY3756547
//
// includes: main.js
//
window.cameraIngame = function(kart) {
var thisObj = this;
this.kart = kart;
this.getView = getView;
this.targetShadowPos = [0, 0, 0]
var mat = mat4.create();
var camOffset = [0, 32, -48]
var lookAtOffset = [0, 16, 0]
var camNormal = [0, 1, 0];
var camAngle = 0;
var boostOff = 0;
function getView(scene) {
var basis = buildBasis();
var camPos = vec3.transformMat4([], camOffset, basis);
var lookAtPos = vec3.transformMat4([], lookAtOffset, basis);
vec3.scale(camPos, camPos, 1/1024);
vec3.scale(lookAtPos, lookAtPos, 1/1024);
var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]);
var kpos = vec3.clone(kart.pos);
if (kart.drifting && !kart.driftLanded && kart.ylock>0) kpos[1] -= kart.ylock;
mat4.translate(mat, mat, vec3.scale([], kpos, -1/1024));
//interpolate visual normal roughly to target
camNormal[0] += (kart.kartNormal[0]-camNormal[0])*0.075;
camNormal[1] += (kart.kartNormal[1]-camNormal[1])*0.075;
camNormal[2] += (kart.kartNormal[2]-camNormal[2])*0.075;
vec3.normalize(camNormal, camNormal);
camAngle += dirDiff(kart.physicalDir+kart.driftOff/2, camAngle)*0.075;
camAngle = fixDir(camAngle);
boostOff += (((kart.boostNorm+kart.boostMT > 0)?5:0) - boostOff)*0.075
var p = mat4.perspective(mat4.create(), ((70+boostOff)/180)*Math.PI, gl.viewportWidth / gl.viewportHeight, 0.01, 10000.0);
var dist = 192;
this.targetShadowPos = vec3.add([], kart.pos, [Math.sin(kart.angle)*dist, 0, -Math.cos(kart.angle)*dist])
thisObj.view = {p:p, mv:mat};
return thisObj.view;
}
function buildBasis() {
//order y, x, z
var basis = gramShmidt(camNormal, [Math.cos(camAngle), 0, Math.sin(camAngle)], [Math.sin(camAngle), 0, -Math.cos(camAngle)]);
var temp = basis[0];
basis[0] = basis[1];
basis[1] = temp; //todo: cleanup
return [
basis[0][0], basis[0][1], basis[0][2], 0,
basis[1][0], basis[1][1], basis[1][2], 0,
basis[2][0], basis[2][1], basis[2][2], 0,
0, 0, 0, 1
]
}
function gramShmidt(v1, v2, v3) {
var u1 = v1;
var u2 = vec3.sub([0, 0, 0], v2, project(u1, v2));
var u3 = vec3.sub([0, 0, 0], vec3.sub([0, 0, 0], v3, project(u1, v3)), project(u2, v3));
return [vec3.normalize(u1, u1), vec3.normalize(u2, u2), vec3.normalize(u3, u3)]
}
function project(u, v) {
return vec3.scale([], u, (vec3.dot(u, v)/vec3.dot(u, u)))
}
function fixDir(dir) {
return posMod(dir, Math.PI*2);
}
function dirDiff(dir1, dir2) {
var d = fixDir(dir1-dir2);
return (d>Math.PI)?(-2*Math.PI+d):d;
}
function posMod(i, n) {
return (i % n + n) % n;
}
}

View File

@ -0,0 +1,118 @@
//
// cameraIntro.js
//--------------------
// Runs the intro camera for a scene.
// by RHY3756547
//
// includes: main.js
//
window.cameraIntro = function() {
var thisObj = this;
this.kart = kart;
this.getView = getView;
this.targetShadowPos = [0, 0, 0]
var mat = mat4.create();
var curCamNum = -1;
var curCam = null;
var route = null;
var routePos = 0;
var routeSpeed = 0;
var routeProg = 0;
var duration = 0;
var pointInterp = 0;
var normalFOV = 70;
var zoomLevel = 1;
var viewW;
var viewH;
function getView(scene, width, height) {
if (curCam == null) {
restartCam(scene);
}
viewW = width;
viewH = height;
if (zoomLevel < curCam.zoomMark1) zoomLevel += curCam.zoomSpeedM1;
else if (zoomLevel > curCam.zoomMark2) zoomLevel += curCam.zoomSpeedM2;
else zoomLevel += curCam.zoomSpeed;
if (zoomLevel > curCam.zoomEnd) zoomLevel = curCam.zoomEnd;
if (duration-- < 0) {
var cams = scene.nkm.sections["CAME"].entries;
if (curCam.nextCam != -1) {
curCamNum = curCam.nextCam;
curCam = cams[curCamNum];
zoomLevel = curCam.zoomStart;
initCam(scene, curCam)
} else {
restartCam(scene);
}
}
thisObj.view = camFunc(scene, curCam);
}
function restartCam(scene) {
var cams = scene.nkm.sections["CAME"].entries;
for (var i=0; i<cams.length; i++) {
if (cams[i].firstCam == 2) {
curCamNum = i;
curCam = cams[curCamNum];
zoomLevel = curCam.zoomStart;
initCam(scene, curCam)
}
}
}
function recalcRouteSpeed() {
routeSpeed = (curCam.routeSpeed/100)/60;
//(curCam.routeSpeed/20)/vec3.dist(route[routePos].pos, route[(routePos+1)%route.length].pos);
}
var camFunc = function(scene, came) {
var camPos = vec3.lerp([], route[routePos].pos, route[(routePos+1)%route.length].pos, routeProg);
routeProg += routeSpeed;
if (routeProg > 1) {
routePos = (routePos+1)%route.length;
routeProg = 0;
recalcRouteSpeed();
}
pointInterp += (curCam.pointSpeed/100)/60;
if (pointInterp > 1) pointInterp = 1;
var lookAtPos = vec3.lerp([], curCam.pos2, curCam.pos3, pointInterp)
vec3.scale(camPos, camPos, 1/1024);
vec3.scale(lookAtPos, lookAtPos, 1/1024);
var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]);
var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0);
thisObj.targetShadowPos = lookAtPos;
return {p:p, mv:mat}
}
var initCam = function(scene, came) {
var routes = scene.paths;
route = routes[came.camRoute];
routePos = 0;
routeProg = 0;
duration = came.duration;
recalcRouteSpeed();
}
}

View File

@ -0,0 +1,216 @@
//
// cameraSpectator.js
//--------------------
// Spectates a specific kart. Requires NKM AREA and CAME to be set up correctly.
// by RHY3756547
//
// includes: main.js
//
window.cameraSpectator = function(kart) {
var thisObj = this;
this.kart = kart;
this.getView = getView;
this.targetShadowPos = [0, 0, 0]
var mat = mat4.create();
var curCamNum = -1;
var curCam = null;
var route = null;
var routePos = 0;
var routeSpeed = 0;
var routeProg = 0;
var relPos = [];
var posOff = [];
var normalFOV = 70;
var zoomLevel = 1;
var viewW;
var viewH;
function getView(scene, width, height) {
viewW = width;
viewH = height;
var cams = scene.nkm.sections["CAME"].entries;
var tArea = getNearestArea(scene.nkm.sections["AREA"].entries, kart.pos)
if (tArea.came != curCamNum) {
//restart camera.
curCamNum = tArea.came;
curCam = cams[curCamNum];
zoomLevel = curCam.zoomStart;
initCam[curCam.camType](scene, curCam)
}
if (zoomLevel < curCam.zoomMark1) zoomLevel += curCam.zoomSpeedM1;
else if (zoomLevel > curCam.zoomMark2) zoomLevel += curCam.zoomSpeedM2;
else zoomLevel += curCam.zoomSpeed;
if (zoomLevel > curCam.zoomEnd) zoomLevel = curCam.zoomEnd;
thisObj.view = camFunc[curCam.camType](scene, curCam);
return thisObj.view;
}
var camFunc = [];
camFunc[1] = function(scene, came) {
var camPos = vec3.lerp([], route[routePos].pos, route[(routePos+1)%route.length].pos, routeProg);
routeProg += routeSpeed;
if (routeProg > 1) {
routePos = (routePos+1)%route.length;
routeProg = 0;
recalcRouteSpeed();
}
var lookAtPos = vec3.transformMat4([], [0, 4, 0], kart.mat);
vec3.scale(camPos, camPos, 1/1024);
vec3.scale(lookAtPos, lookAtPos, 1/1024);
var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]);
var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0);
thisObj.targetShadowPos = kart.pos;
return {p:p, mv:mat}
}
camFunc[0] = function(scene, came) { //point cam
var camPos = vec3.clone(came.pos1);
var lookAtPos = vec3.transformMat4([], [0, 4, 0], kart.mat);
vec3.scale(camPos, camPos, 1/1024);
vec3.scale(lookAtPos, lookAtPos, 1/1024);
var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]);
var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0);
thisObj.targetShadowPos = kart.pos;
return {p:p, mv:mat}
}
camFunc[5] = function(scene, came) { //dash cam
var basis = kart.basis;
var camPos = vec3.transformMat4([], relPos, basis);
var lookAtPos = vec3.transformMat4([], [0, 0, 0], basis);
vec3.scale(camPos, camPos, 1/1024);
vec3.scale(lookAtPos, lookAtPos, 1/1024);
var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]);
var off = mat4.create();
mat4.translate(off, off, [-came.pos3[0]/1024, came.pos3[1]/1024, -came.pos3[2]/1024]);
mat4.mul(mat, off, mat);
var kpos = vec3.clone(kart.pos);
if (kart.drifting && !kart.driftLanded && kart.ylock>0) kpos[1] -= kart.ylock;
mat4.translate(mat, mat, vec3.scale([], kpos, -1/1024));
var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0);
thisObj.targetShadowPos = kart.pos;
return {p:p, mv:mat}
}
camFunc[2] = camFunc[0];
var initCam = [];
initCam[1] = function(scene, came) {
var routes = scene.paths;
route = routes[came.camRoute];
routePos = 0;
routeProg = 0;
recalcRouteSpeed();
}
initCam[2] = function(scene, came) {
}
function recalcRouteSpeed() {
routeSpeed = (curCam.routeSpeed/100)/60;
//(curCam.routeSpeed/20)/vec3.dist(route[routePos].pos, route[(routePos+1)%route.length].pos);
}
initCam[5] = function(scene, came) {
var mat = mat4.create();
mat4.rotateY(mat, mat, (180-came.pos2[0])*(Math.PI/180));
mat4.rotateX(mat, mat, -came.pos2[1]*(Math.PI/180));
relPos = vec3.transformMat4([], [0, 0, -came.pos2[2]], mat);
/*var basis = kart.basis;
relPos = vec3.sub(relPos, came.pos1, kart.pos);
vec3.transformMat4(relPos, relPos, mat4.invert([], basis));*/
}
initCam[0] = initCam[2];
function getNearestArea(areas, pos) {
var smallestDist = Infinity;
var closestArea = null;
for (var i=0; i<areas.length; i++) {
var a = areas[i];
var sub = vec3.sub([], a.pos, pos);
vec3.divide(sub, sub, a.dimensions);
var dist = Math.sqrt(sub[0]*sub[0] + sub[1]*sub[1] + sub[2]*sub[2]);
if (dist<smallestDist && a.came != 255) {
smallestDist = dist;
closestArea = a;
}
}
return closestArea;
}
function buildBasis() {
//order y, x, z
var basis = gramShmidt(camNormal, [Math.cos(camAngle), 0, Math.sin(camAngle)], [Math.sin(camAngle), 0, -Math.cos(camAngle)]);
var temp = basis[0];
basis[0] = basis[1];
basis[1] = temp; //todo: cleanup
return [
basis[0][0], basis[0][1], basis[0][2], 0,
basis[1][0], basis[1][1], basis[1][2], 0,
basis[2][0], basis[2][1], basis[2][2], 0,
0, 0, 0, 1
]
}
function gramShmidt(v1, v2, v3) {
var u1 = v1;
var u2 = vec3.sub([0, 0, 0], v2, project(u1, v2));
var u3 = vec3.sub([0, 0, 0], vec3.sub([0, 0, 0], v3, project(u1, v3)), project(u2, v3));
return [vec3.normalize(u1, u1), vec3.normalize(u2, u2), vec3.normalize(u3, u3)]
}
function project(u, v) {
return vec3.scale([], u, (vec3.dot(u, v)/vec3.dot(u, u)))
}
function fixDir(dir) {
return posMod(dir, Math.PI*2);
}
function dirDiff(dir1, dir2) {
var d = fixDir(dir1-dir2);
return (d>Math.PI)?(-2*Math.PI+d):d;
}
function posMod(i, n) {
return (i % n + n) % n;
}
}

View File

@ -0,0 +1,336 @@
//
// collisionTypes.js
//--------------------
// Includes enums for collision types.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/kcl.js
//
window.MKDS_COLSOUNDS = new function() {
this.DRIFT_ASPHALT = 84;
this.DRIFT_CONCRETE = 85;
this.DRIFT_EDGE = 86; //happens when you hit an edge while drifting?
this.DRIFT_DIRT = 87;
this.DRIFT_ROAD = 88;
this.DRIFT_STONE = 89;
this.DRIFT_SAND = 90;
this.DRIFT_ICE = 91;
this.DRIFT_GLASS = 92;
this.DRIFT_WATER = 93;
this.DRIFT_BOARD = 94; //boardwalk!
this.DRIFT_CARPET = 95; //like luigis mansion
this.DRIFT_METALGAUZE = 96;
this.DRIFT_PLASTIC = 97;
this.DRIFT_RAINBOW = 99;
this.DRIFT_MARSH = 100; //luigis mansion
this.LAND_ASPHALT = 103;
this.LAND_SAND = 104;
this.LAND_DIRT = 105;
this.LAND_ICE = 106;
this.LAND_GRASS = 107;
this.LAND_SNOW = 108;
this.LAND_METALGAUZE = 109;
this.LAND_MARSH = 110;
this.LAND_WATER = 111;
this.LAND_WATERDEEP = 112;
this.LAND_CARPET = 113;
this.DRIVE_DIRT = 114;
this.DRIVE_GRASS = 115;
this.DRIVE_WATER = 116;
this.DRIVE_STONE = 117;
this.DRIVE_SAND = 118;
this.DRIVE_MARSH = 119;
this.DRIVE_CARPET = 120;
this.HIT_CAR = 128;
this.HIT_CONCRETE = 129;
this.HIT_FENCE = 130;
this.HIT_WOOD = 131;
this.HIT_TREE = 132;
this.HIT_BUSH = 133;
this.HIT_CLIFF = 134;
this.HIT_SIGN = 135;
this.HIT_ICE = 136;
this.HIT_SNOW = 137;
this.HIT_TABLE = 138;
this.HIT_BOUNCY = 139;
this.HIT_JELLY = 140;
this.HIT_METALGAUZE = 141;
this.HIT_METAL = 142;
this.BRAKE = 143;
this.BRAKE_CONCRETE = 144;
this.BRAKE_DIRT = 145;
this.BRAKE_STONE = 146;
this.BRAKE_ICE = 147;
this.BRAKE_GLASS = 148;
this.BRAKE_WATER = 149;
this.BRAKE_BOARD = 150; //boardwalk
this.BRAKE_CARPET = 151;
this.BRAKE_METALGAUZE = 152;
this.BRAKE_PLASTIC = 153;
this.BRAKE_METAL = 154;
this.BRAKE_RAINBOW = 155;
this.BRAKE_MARSH = 156;
this.BRAKE_BOOST = 158;
}
window.MKDS_COLTYPE = new (function(){
this.ROAD = 0x00;
this.OFFROADMAIN = 0x01;
this.OFFROAD3 = 0x02;
this.OFFROAD2 = 0x03;
this.RAINBOWFALL = 0x04;
this.OFFROAD1 = 0x05;
this.SLIPPERY = 0x06;
this.BOOST = 0x07;
this.WALL = 0x08;
this.WALL2 = 0x09;
this.OOB = 0x0A; //voids out the player, returns to lakitu checkpoint.
this.FALL = 0x0B; //like out of bounds, but you fall through it.
this.JUMP_PAD = 0x0C; //jump pads on GBA levels
this.STICKY = 0x0D; //sets gravity to negative this plane's normal until the object hasn't collided for a few frames.
this.SMALLJUMP = 0x0E; //choco island 2's disaster ramps
this.CANNON = 0x0F; //activates cannon. basic effect id is the cannon to use.
this.UNKNOWN = 0x10; //it is a mystery...
this.FALLSWATER = 0x11; //points to falls object in nkm, gets motion parameters from there.
this.BOOST2 = 0x12;
this.LOOP = 0x13; //like sticky but with boost applied. see rainbow road ds
this.SOUNDROAD = 0x14;
this.RR_SPECIAL_WALL = 0x15;
this.GROUP_ROAD = [
this.ROAD, this.OFFROAD1, this.OFFROAD2, this.OFFROAD3, this.OFFROAD4, this.SLIPPERY, this.BOOST,
this.JUMP_PAD, this.STICKY, this.SMALLJUMP, this.FALLSWATER, this.BOOST2, this.LOOP, this.SOUNDROAD,
this.OOB, this.OFFROADMAIN
]
this.GROUP_SOLID = [
this.ROAD, this.OFFROAD1, this.OFFROAD2, this.OFFROAD3, this.OFFROAD4, this.SLIPPERY, this.BOOST,
this.JUMP_PAD, this.STICKY, this.SMALLJUMP, this.FALLSWATER, this.BOOST2, this.LOOP, this.SOUNDROAD,
this.OOB, this.OFFROADMAIN,
this.WALL, this.WALL2, this.RR_SPECIAL_WALL
]
this.GROUP_WALL = [
this.WALL, this.WALL2, this.RR_SPECIAL_WALL
]
this.GROUP_BOOST = [
this.BOOST, this.BOOST2, this.LOOP
]
this.PHYS_MAP = new Array(31);
this.PHYS_MAP[this.ROAD] = 0;
this.PHYS_MAP[this.OFFROAD3] = 2;
this.PHYS_MAP[this.OFFROAD2] = 3;
this.PHYS_MAP[this.OFFROAD1] = 4;
this.PHYS_MAP[this.OFFROADMAIN] = 5;
this.PHYS_MAP[this.SLIPPERY] = 6;
this.PHYS_MAP[this.BOOST] = 8;
this.PHYS_MAP[this.BOOST2] = 8;
this.PHYS_MAP[this.FALLSWATER] = 10;
this.PHYS_MAP[this.LOOP] = 11;
//collision sound handlers
var waterRoad = {drift: MKDS_COLSOUNDS.DRIFT_WATER, brake: MKDS_COLSOUNDS.BRAKE_WATER, land: MKDS_COLSOUNDS.LAND_WATER, drive: MKDS_COLSOUNDS.DRIVE_WATER};
this.SOUNDMAP = {
0x00: //road
[
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT},
{drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND},
{drift: MKDS_COLSOUNDS.DRIFT_STONE, brake: MKDS_COLSOUNDS.BRAKE_STONE, land: MKDS_COLSOUNDS.LAND_ASPHALT, drive: MKDS_COLSOUNDS.DRIVE_STONE},
{drift: MKDS_COLSOUNDS.DRIFT_CONCRETE, brake: MKDS_COLSOUNDS.BRAKE_CONCRETE, land: MKDS_COLSOUNDS.LAND_ASPHALT},
{drift: MKDS_COLSOUNDS.DRIFT_BOARD, brake: MKDS_COLSOUNDS.BRAKE_BOARD, land: MKDS_COLSOUNDS.LAND_ASPHALT},
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_SNOW}, //snow?
{drift: MKDS_COLSOUNDS.DRIFT_METALGAUZE, brake: MKDS_COLSOUNDS.BRAKE_METALGAUZE, land: MKDS_COLSOUNDS.LAND_METALGAUZE},
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT},
],
0x01: //road 2 the roadening
[
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT},
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT},
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT},
{drift: MKDS_COLSOUNDS.DRIFT_WATER, brake: MKDS_COLSOUNDS.BRAKE_WATER, land: MKDS_COLSOUNDS.LAND_WATERDEEP, drive: MKDS_COLSOUNDS.DRIVE_WATER},
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT},
{},
{},
{}
],
0x02: //road 3
[
{drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND , land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND},
waterRoad,
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_SNOW}, //snow
{drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND},
{},
{},
{},
{}
],
0x03: //road 4
[
{drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND , land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND},
{drift: MKDS_COLSOUNDS.DRIFT_DIRT, brake: MKDS_COLSOUNDS.BRAKE_DIRT, land: MKDS_COLSOUNDS.LAND_DIRT, drive: MKDS_COLSOUNDS.DRIVE_DIRT},
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_GRASS, drive: MKDS_COLSOUNDS.DRIVE_GRASS},
{drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND},
{drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND},
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_SNOW}, //snow
{},
{}
],
0x05: //road 5
[
{drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND , land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND},
{drift: MKDS_COLSOUNDS.DRIFT_DIRT, brake: MKDS_COLSOUNDS.BRAKE_DIRT, land: MKDS_COLSOUNDS.LAND_DIRT, drive: MKDS_COLSOUNDS.DRIVE_DIRT},
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_GRASS, drive: MKDS_COLSOUNDS.DRIVE_GRASS},
{drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND},
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_GRASS, drive: MKDS_COLSOUNDS.DRIVE_GRASS},
{},
{},
{}
],
0x06: //slippery
[
{drift: MKDS_COLSOUNDS.DRIFT_ICE, brake: MKDS_COLSOUNDS.BRAKE_ICE, land:MKDS_COLSOUNDS.LAND_ICE},
{drift: MKDS_COLSOUNDS.DRIFT_MARSH, brake: MKDS_COLSOUNDS.BRAKE_MARSH, land:MKDS_COLSOUNDS.LAND_MARSH, drive: MKDS_COLSOUNDS.DRIVE_MARSH},
{},
{},
{},
{},
{},
{}
],
0x07: //bo0st
[
{drift: MKDS_COLSOUNDS.BRAKE_PLASTIC, brake: MKDS_COLSOUNDS.BRAKE_PLASTIC, land:MKDS_COLSOUNDS.LAND_ASPHALT},
{drift: MKDS_COLSOUNDS.BRAKE_PLASTIC, brake: MKDS_COLSOUNDS.BRAKE_PLASTIC, land:MKDS_COLSOUNDS.LAND_ASPHALT},
{},
{},
{},
{},
{},
{}
],
0x08: //wall
[//placeholders
{hit: MKDS_COLSOUNDS.HIT_CONCRETE},
{hit: MKDS_COLSOUNDS.HIT_CLIFF},
{hit: MKDS_COLSOUNDS.HIT_SIGN}, //cliff
{hit: MKDS_COLSOUNDS.HIT_WOOD},
{hit: MKDS_COLSOUNDS.HIT_BUSH},
{},
{hit: MKDS_COLSOUNDS.HIT_JELLY},
{hit: MKDS_COLSOUNDS.HIT_ICE},
],
0x09: //wall 2
[
{hit: MKDS_COLSOUNDS.HIT_CONCRETE},
{hit: MKDS_COLSOUNDS.HIT_STONE},
{hit: MKDS_COLSOUNDS.HIT_METAL},
{hit: MKDS_COLSOUNDS.HIT_WOOD},
{hit: MKDS_COLSOUNDS.HIT_BUSH},
{},
{hit: MKDS_COLSOUNDS.HIT_JELLY},
{hit: MKDS_COLSOUNDS.HIT_ICE},
],
0x10: //wall 3
[
{hit: MKDS_COLSOUNDS.HIT_CONCRETE},
{},
{},
{},
{},
{},
{},
{},
],
0x15: //wall with sound effect
[
{hit: MKDS_COLSOUNDS.HIT_CONCRETE},
{hit: MKDS_COLSOUNDS.HIT_STONE},
{hit: MKDS_COLSOUNDS.HIT_RAINBOW}, //only diff i think
{hit: MKDS_COLSOUNDS.HIT_WOOD},
{hit: MKDS_COLSOUNDS.HIT_BUSH},
{},
{hit: MKDS_COLSOUNDS.HIT_JELLY},
{hit: MKDS_COLSOUNDS.HIT_ICE},
],
0x11: [ //yoshi falls water
waterRoad,
waterRoad,
waterRoad,
waterRoad,
waterRoad,
waterRoad,
waterRoad,
waterRoad
],
0x12: //boost
[
{drift: MKDS_COLSOUNDS.BRAKE_PLASTIC, brake: MKDS_COLSOUNDS.BRAKE_PLASTIC, land:MKDS_COLSOUNDS.LAND_ASPHALT},
{},
{},
{},
{},
{},
{},
{}
],
0x13: //looping
[
{drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land:MKDS_COLSOUNDS.LAND_ASPHALT},
{drift: MKDS_COLSOUNDS.DRIFT_RAINBOW, brake: MKDS_COLSOUNDS.BRAKE_RAINBOW, land:MKDS_COLSOUNDS.LAND_ASPHALT},
{},
{},
{},
{},
{},
{}
],
0x14: //road with sfx
[
{},
{drift: MKDS_COLSOUNDS.DRIFT_CARPET, brake: MKDS_COLSOUNDS.BRAKE_CARPET, land:MKDS_COLSOUNDS.LAND_CARPET, drive: MKDS_COLSOUNDS.DRIVE_CARPET},
{drift: MKDS_COLSOUNDS.DRIFT_RAINBOW, brake: MKDS_COLSOUNDS.BRAKE_RAINBOW, land:MKDS_COLSOUNDS.LAND_ASPHALT},
{},
{}, //stairs
{},
{},
{}
]
}
})()

View File

@ -0,0 +1,35 @@
//
// controlDefault.js
//--------------------
// Provides default (keyboard) controls for kart. In future there will be an AI controller and default will support gamepad.
// by RHY3756547
//
// includes: main.js
//
window.controlDefault = function() {
var thisObj = this;
this.local = true;
var kart;
this.setKart = function(k) {
kart = k;
thisObj.kart = k;
}
this.fetchInput = fetchInput;
function fetchInput() {
return {
accel: keysArray[88], //x
decel: keysArray[90], //z
drift: keysArray[83], //s
item: keysArray[65], //a
//-1 to 1, intensity.
turn: (keysArray[37]?-1:0)+(keysArray[39]?1:0),
airTurn: (keysArray[40]?-1:0)+(keysArray[38]?1:0) //air excitebike turn, doesn't really have much function
};
}
}

View File

@ -0,0 +1,41 @@
//
// controlDefault.js
//--------------------
// Provides default (keyboard) controls for kart. In future there will be an AI controller and default will support gamepad.
// by RHY3756547
//
// includes: main.js
//
window.controlNetwork = function() {
var t = this;
var kart;
this.local = false;
this.turn = 0;
this.airTurn = 0;
this.binput = 0;
this.setKart = function(k) {
kart = k;
t.kart = k;
}
this.fetchInput = fetchInput;
function fetchInput() {
//local controllers generally just return input and handle items - the network controller restores kart data from the stream sent from the server. Obviously this data needs to be verified by the server...
return {
accel: t.binput&1, //x
decel: t.binput&2, //z
drift: t.binput&4, //s
item: false,//keysArray[65], //a
//-1 to 1, intensity.
turn: t.turn,//(keysArray[37]?-1:0)+(keysArray[39]?1:0),
airTurn: t.airTurn//(keysArray[40]?-1:0)+(keysArray[38]?1:0) //air excitebike turn, doesn't really have much function
};
}
}

View File

@ -0,0 +1,141 @@
//
// controlRaceCPU.js
//--------------------
// Provides AI control for default races
// by RHY3756547
//
// includes: main.js
//
window.controlRaceCPU = function(nkm) {
var thisObj = this;
var kart;
this.setKart = function(k) {
kart = k;
thisObj.kart = k;
calcDestNorm();
}
this.fetchInput = fetchInput;
var battleMode = (nkm.sections["EPAT"] == null);
var paths, points;
if (battleMode) { //MEEPO!!
var paths = nkm.sections["MEPA"].entries;
var points = nkm.sections["MEPO"].entries;
} else {
var paths = nkm.sections["EPAT"].entries;
var points = nkm.sections["EPOI"].entries;
}
var ePath = paths[0];
var ePoiInd = ePath.startInd;
var ePoi = points[ePath.startInd];
var posOffset = [0, 0, 0];
var destOff = [0, 0, 0];
var offTrans = 0;
chooseNewOff();
var destNorm;
var destConst;
var destPoint;
function fetchInput() {
//basically as a cpu, we're really dumb and need a constant supply of points to drive to.
//battle mode AI is a lot more complex, but since we're only going in one direction it can be kept simple.
var accel = true; //currently always driving forward. should change for sharp turns and when we get stuck on a wall
//(drive in direction of wall? we may need to reverse, "if stuck for too long we can just call lakitu and the players won't even notice" - Nintendo)
var dist = vec3.dot(destNorm, kart.pos) + destConst;
if (dist < ePoi.pointSize) advancePoint();
destPoint = vec3.add([], ePoi.pos, vec3.scale([], vec3.lerp([], posOffset, destOff, offTrans), ePoi.pointSize));
var dirToPt = Math.atan2(destPoint[0]-kart.pos[0], kart.pos[2]-destPoint[2]);
var diff = dirDiff(dirToPt, kart.physicalDir);
var turn = Math.min(Math.max(-1, (diff*3)), 1);
offTrans += 1/240;
if (offTrans >= 1) chooseNewOff();
return {
accel: accel, //x
decel: false, //z
drift: false, //s
item: false, //a
//-1 to 1, intensity.
turn: turn,
airTurn: 0 //air excitebike turn, doesn't really have much function
};
}
function chooseNewOff() {
posOffset = destOff;
var ang = Math.random()*Math.PI*2;
var strength = Math.random();
destOff = [Math.sin(ang)*strength, 0, Math.cos(ang)*strength];
offTrans = 0;
}
function calcDestNorm() {
var norm = vec3.sub([], kart.pos, ePoi.pos);
vec3.normalize(norm, norm);
destNorm = norm;
destConst = -vec3.dot(ePoi.pos, norm)
}
function advancePoint() {
if (++ePoiInd < ePath.startInd+ePath.pathLen) {
//next within this path
ePoi = points[ePoiInd];
} else {
//advance to one of next possible paths
if (battleMode) {
var pathInd = ((Math.random()>0.5 && ePath.source.length>0)?ePath.source:ePath.dest)[Math.floor(Math.random()*ePath.dest.length)];
ePoiInd = pathInd;
ePoi = points[ePoiInd];
recomputePath();
} else {
var pathInd = ePath.dest[Math.floor(Math.random()*ePath.dest.length)];
ePath = paths[pathInd];
ePoi = points[ePath.startInd];
ePoiInd = ePath.startInd;
}
}
calcDestNorm();
}
function recomputePath() { //use if point is set by anything but the path system, eg. respawn
for (var i=0; i<paths.length; i++) {
var rel = (ePoiInd-paths[i].startInd);
if (rel >= 0 && rel < paths[i].pathLen) {
ePath = paths[i];
}
}
}
function fixDir(dir) {
return posMod(dir, Math.PI*2);
}
function dirDiff(dir1, dir2) {
var d = fixDir(dir1-dir2);
return (d>Math.PI)?(-2*Math.PI+d):d;
}
function posMod(i, n) {
return (i % n + n) % n;
}
}

100
Code/Engine/ingameRes.js Normal file
View File

@ -0,0 +1,100 @@
//
// ingameRes.js
//--------------------
// Provides access to general ingame resources.
// by RHY3756547
//
window.IngameRes = function(rom) {
var r = this;
this.kartPhys = new kartphysicalparam(rom.getFile("/data/KartModelMenu/kartphysicalparam.bin"));
this.kartOff = new kartoffsetdata(rom.getFile("/data/KartModelMenu/kartoffsetdata.bin"));
this.MapObj = new narc(lz77.decompress(rom.getFile("/data/Main/MapObj.carc"))); //contains generic map obj, look in here when mapobj res is missing from course. (itembox etc)
this.MainRace = new narc(lz77.decompress(rom.getFile("/data/MainRace.carc"))); //contains item models.
this.MainEffect = new narc(lz77.decompress(rom.getFile("/data/MainEffect.carc"))); //contains particles.
this.Main2D = new narc(lz77.decompress(rom.getFile("/data/Main2D.carc")));
this.KartModelSub = new narc(lz77.decompress(rom.getFile("/data/KartModelSub.carc"))); //contains characters + animations
this.Race = new narc(lz77.decompress(rom.getFile("/data/Scene/Race.carc"))); //contains lakitu, count, various graphics
this.RaceLoc = new narc(lz77.decompress(rom.getFile("/data/Scene/Race_us.carc"))); //contains lakitu lap signs, START, YOU WIN etc. some of these will be replaced by hi res graphics by default.
this.MainFont = new nftr(r.Main2D.getFile("marioFont.NFTR"));
//debugger;
this.getChar = getChar;
this.getKart = getKart;
var itemNames = [
"banana", "bomb", "gesso" /*squid*/, "kinoko" /*mushroom*/, "kinoko_p" /*queen shroom*/, "koura_g" /*green shell*/, "koura_r" /*red shell*/, "star", "teresa" /*boo*/, "thunder",
"koura_w" /*blue shell item rep*/, "f_box", "killer" /*bullet bill*/
]
var charNames = [
"mario", "donkey", "kinopio", "koopa", "peach", "wario", "yoshi", "luigi", "karon", "daisy", "waluigi", "robo", "heyho"
]
var charAbbrv = [
"MR", "DK", "KO", "KP", "PC", "WR", "YS", "LG", "KA", "DS", "WL", "RB", "HH"
]
var tireName = ["kart_tire_L", "kart_tire_M", "kart_tire_S"];
var characters = [];
var karts = [];
loadItems();
loadTires();
function loadItems() { //loads physical representations of items
var t = {}
for (var i=0; i<itemNames.length; i++) {
var n = itemNames[i];
t[n] = new nitroModel(new nsbmd(r.MainRace.getFile("/Item/it_"+n+".nsbmd")));
}
t.blueShell = new nitroModel(new nsbmd(r.MainRace.getFile("/Item/koura_w.nsbmd")));
t.splat = new nitroModel(new nsbmd(r.MainRace.getFile("/Item/geso_sumi.nsbmd")));
r.items = t;
}
function loadTires() {
var path = "/data/KartModelMenu/kart/tire/";
var tires = {};
for (var i=0; i<tireName.length; i++) tires[tireName[i]] = new nitroModel(new nsbmd(rom.getFile(path+tireName[i]+".nsbmd")), new nsbtx(rom.getFile(path+tireName[i]+".nsbtx")));
r.tireRes = tires;
}
function getChar(ind) {
if (characters[ind] != null) return characters[ind];
var base = "/character/"+charNames[ind]+"/P_"+charAbbrv[ind];
var obj = {
model: new nitroModel(new nsbmd(r.KartModelSub.getFile(base+".nsbmd")), new nsbtx(r.KartModelSub.getFile(base+".nsbtx")), {tex:{1:2}, pal:{1:2}}),
driveA: new nsbca(r.KartModelSub.getFile(base+"_drive.nsbca")),
loseA: new nsbca(r.KartModelSub.getFile(base+"_lose.nsbca")),
spinA: new nsbca(r.KartModelSub.getFile(base+"_spin.nsbca")),
winA: new nsbca(r.KartModelSub.getFile(base+"_win.nsbca")),
}
characters[ind] = obj;
return characters[ind];
}
var letters = ["a", "b", "c"]
function getKart(ind) { //returns a nitroModel, but also includes a property "shadVol" containing the kart's shadow volume.
if (karts[ind] != null) return karts[ind];
var c = Math.floor(ind/3);
var t = ind%3;
if (t == 0) c = 0; //only mario has standard kart
var name = charAbbrv[c]+"_"+letters[t];
var path = "/data/KartModelMenu/kart/"+charNames[c]+"/kart_"+name;
var model = new nitroModel(new nsbmd(rom.getFile(path+".nsbmd")), new nsbtx(rom.getFile(path+".nsbtx")));
model.shadVol = new nitroModel(new nsbmd(rom.getFile("/data/KartModelMenu/kart/shadow/sh_"+name+".nsbmd")));
//todo, assign special pallete for A karts
karts[ind] = model;
return karts[ind];
}
}

View File

@ -0,0 +1,114 @@
//
// itemController.js
//--------------------
// An item controller for scenes. Allows items to be synced to multiple clients.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
//
window.ItemController = function(scene) {
var t = this;
t.scene = scene;
t.items = [];
t.curInd = 0; //next item index. Max value is insanely high so there shouldn't be much of a problem.
t.cliID = 0; //client id, used along with item index to specify your items.
t.time = 0;
t.addItem = addItem;
t.changeItem = changeItem;
t.update = update;
t.draw = draw;
var RedShell, Banana, Bomb, BlueShell, Star, MultiItem, Shroom, TripleShroom, QueenShroom, Bullet, Ghost, Squid //these are all null
var itemFunc = [
GreenShell,
RedShell,
Banana,
Bomb,
BlueShell,
Star,
MultiItem, //triple shells, lucky 7 if you're into that kind of thing
Shroom,
TripleShroom,
QueenShroom,
Bullet,
Ghost,
Squid
]
function update(scene) {
var itC = t.items.slice(0);
for (var i=0; i<itC.length; i++) {
var ent = itC[i];
ent.update(scene);
}
}
function draw(mvMatrix, pMatrix, gl) {
for (var i=0; i<t.items.length; i++) {
var e = t.items[i];
t.items[i].draw(mvMatrix, pMatrix, gl);
}
}
function addItem(type, ownerKart, params) {
//sends add item packet. params: itemID, time, params, itemType
var p = {
t:"a",
i:t.itemID++,
c:t.cliID,
d:t.time,
f:type,
o:ownerKart,
p:params
}
resvPacket(p); //instantly respond to own packets
}
function changeItem(item, funcNum, reason, params) {
//sends change item packet. params: itemID, cliID, function, reason, params
var p = {
t:"c",
i:item.itemID,
c:item.cliID,
f:funcNum,
r:reason,
p:params
}
resvPacket(p); //instantly respond to own packets
}
function resvPacket(p) {
switch (p.t) {
case "ci":
var func = itemFunc[p.f];
if (func != null) {
var item = new func(scene, scene.karts[p.o], p.d, p.i, p.c, p.p);
t.items.push(item);
} else console.error("item id incorrect??")
break;
case "~i":
var it = getItemObj(p.c, p.i);
if (it != null) {
var func = it.cFunc[p.f];
if (func != null) {
func(p.r, p.p);
} else console.error("invalid item change function, maybe wrong type?")
} else console.error("attempt to modify item that is either dead or does not exist")
break;
}
}
function getItemObj(cli, id) {
for (var i=0; i<t.items.length; i++) {
var item = t.items[i];
if (item.cliID == cli && item.itemID == id) {
return item;
}
}
}
}

View File

@ -0,0 +1,303 @@
//
// largeSphereCollider.js
//--------------------
// Provides functions to detect collision against sets of triangles for swept ellipsoids and small rays (low cost, used for green shells).
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/kcl.js
//
window.lsc = new (function() {
this.raycast = raycast;
this.sweepEllipse = sweepEllipse;
this.pointInTriangle = pointInTriangle; //expose this because its kinda useful
function raycast(pos, dir, kclO, error, ignoreList) { //used for shells, bananas and spammable items. Much faster than sphere sweep. Error used to avoid falling through really small seams between tris.
var error = (error==null)?0:error;
var t=1;
var tris = getTriList(pos, dir, kclO);
var colPlane = null;
var colPoint = null; //can be calculated from t, but we calculate it anyway so why not include
for (var i=0; i<tris.length; i++) {
//first, check if we intersect the plane within reasonable t.
//only if this happens do we check if the point is in the triangle.
//we would also only do sphere sweep if this happens.
var tri = tris[i];
if (ignoreList.indexOf(tri) != -1) continue;
var planeConst = -vec3.dot(tri.Normal, tri.Vertex1);
var dist = vec3.dot(tri.Normal, pos) + planeConst;
var modDir = vec3.dot(tri.Normal, dir);
if (dist < 0 || modDir == 0) continue; //can't collide with back side of polygons! also can't intersect plane with ray perpendicular to plane
var newT = -dist/modDir;
if (newT>0 && newT<t) {
//we have a winner! check if the plane intersecion point is in the triangle.
var pt = vec3.add([], pos, vec3.scale([], dir, newT))
if (pointInTriangle(tri, pt, error)) {
t = newT;
colPlane = tri;
colPoint = pt; //result!
}
}
}
if (colPlane != null) {
return {
t: t,
plane: colPlane,
colPoint: colPoint,
normal: colPlane.Normal
}
} else return null;
}
function modTri(tri, mat) {
var obj = {};
obj.Vertex1 = vec3.transformMat4([], tri.Vertex1, mat);
obj.Vertex2 = vec3.transformMat4([], tri.Vertex2, mat);
obj.Vertex3 = vec3.transformMat4([], tri.Vertex3, mat);
obj.Normal = vec3.transformMat3([], tri.Normal, mat3.fromMat4([], mat));
vec3.normalize(obj.Normal, obj.Normal);
obj.CollisionType = tri.CollisionType;
return obj;
}
function scaleTri(tri, eDim) {
var obj = {};
obj.Vertex1 = vec3.divide([], tri.Vertex1, eDim);
obj.Vertex2 = vec3.divide([], tri.Vertex2, eDim);
obj.Vertex3 = vec3.divide([], tri.Vertex3, eDim);
obj.Normal = tri.Normal
obj.CollisionType = tri.CollisionType;
return obj;
}
var t, colPlane, colPoint, emb, edge, colO, planeNormal;
function sweepEllipse(pos, dir, scn, eDimensions, ignoreList) { //used for karts or things that need to occupy physical space.
t=1;
var ed = vec3.divide([], [1, 1, 1], eDimensions);
var tris = getTriList(pos, dir, scn.kcl);
var oPos = pos;
var oDir = dir;
var pos = vec3.divide([], pos, eDimensions); //need to rescale position to move into ellipsoid space
var dir = vec3.divide([], dir, eDimensions);
colPlane = null;
colPoint = null; //can be calculated from t, but we calculate it anyway so why not include
emb = false;
edge = false;
ellipseVTris(pos, dir, tris, eDimensions, ignoreList, true);
for (var i=0; i<scn.colEnt.length; i++) {
var c = scn.colEnt[i];
var col = c.getCollision();
if (vec3.distance(oPos, c.pos) < c.colRad) {
ellipseVTris(pos, dir, col.tris, mat4.mul([], mat4.scale([], mat4.create(), ed), col.mat), ignoreList, false, c);
}
}
if (colPlane != null) {
var norm = vec3.scale([], dir, t)
vec3.add(norm, pos, norm);
vec3.sub(norm, norm, colPoint);
if (Math.sqrt(vec3.dot(norm, norm)) < 0.98) emb = true;
vec3.mul(colPoint, colPoint, eDimensions);
return {
t: t,
plane: colPlane,
colPoint: colPoint,
normal: norm,
pNormal: planeNormal,
embedded: emb,
object: colO
}
} else return null;
}
function ellipseVTris(pos, dir, tris, mat, ignoreList, eDims, targ) {
for (var i=0; i<tris.length; i++) {
//first, check if we intersect the plane within reasonable t.
//only if this happens do we check if the point is in the triangle.
//we would also only do sphere sweep if this happens.
var oTri = tris[i];
if (ignoreList.indexOf(oTri) != -1) continue;
var tri = (eDims)?scaleTri(tris[i], mat):modTri(tris[i], mat);
var planeConst = -vec3.dot(tri.Normal, tri.Vertex1);
var dist = vec3.dot(tri.Normal, pos) + planeConst;
var modDir = vec3.dot(tri.Normal, dir);
if (dist < 0) continue; //can't collide with back side of polygons! also can't intersect plane with ray perpendicular to plane
var t0, t1, embedded = false;
if (modDir == 0) {
if (Math.abs(dist) < 1) {
t0 = 0;
t1 = 1;
embedded = true;
} else {
t0 = 1000;
t1 = 2000;
}
} else {
t0 = (1-dist)/modDir;
t1 = ((-1)-dist)/modDir;
}
if (t0 > t1) { //make sure t0 is smallest value
var temp = t1;
t1 = t0;
t0 = temp;
}
if (!(t0>1 || t1<0)) {
//we will intersect this triangle's plane within this frame.
//
// Three things can happen for the earliest intersection:
// - sphere intersects plane of triangle (pt on plane projected from new position is inside triangle)
// - sphere intersects edge of triangle
// - sphere intersects point of triangle
if (t0 < 0) { embedded = true; t0 = 0; }
if (t1 > 1) t1 = 1;
var newT = t0;
//sphere intersects plane of triangle
var pt = [];
if (embedded) {
vec3.sub(pt, pos, vec3.scale([], tri.Normal, dist));
} else {
vec3.add(pt, pos, vec3.scale([], dir, newT))
vec3.sub(pt, pt, tri.Normal); //project new position onto plane along normal
}
if (pointInTriangle(tri, pt, 0) && newT<t) {
t = newT;
colPlane = oTri;
colPoint = pt; //result!
colO = targ;
edge = false;
emb = embedded;
planeNormal = tri.Normal;
continue;
}
//no inside intersection check vertices:
for (var j=1; j<=3; j++) {
var vert = vec3.sub([], pos, tri["Vertex"+j]);
var root = getSmallestRoot(vec3.dot(dir, dir), 2*vec3.dot(dir, vert), vec3.dot(vert, vert)-1, t);
if (root != null) {
t = root;
colPlane = oTri;
colO = targ;
colPoint = vec3.clone(tri["Vertex"+j]); //result!
planeNormal = tri.Normal;
edge = false;
}
}
//... and lines
for (var j=1; j<=3; j++) {
var vert = tri["Vertex"+j];
var nextV = tri["Vertex"+((j%3)+1)];
var distVert = vec3.sub([], vert, pos);
var distLine = vec3.sub([], nextV, vert);
var edgeDist = vec3.dot(distLine, distLine);
var edgeDotVelocity = vec3.dot(distLine, dir);
var edgeDotVert = vec3.dot(distVert, distLine);
var root = getSmallestRoot(
edgeDist*(-1)*vec3.dot(dir, dir) + edgeDotVelocity*edgeDotVelocity,
edgeDist*2*vec3.dot(dir, distVert) - 2*edgeDotVelocity*edgeDotVert,
edgeDist*(1-vec3.dot(distVert, distVert)) + edgeDotVert*edgeDotVert,
t
);
if (root != null) {
var edgePos = (edgeDotVelocity*root - edgeDotVert)/edgeDist;
if (edgePos >= 0 && edgePos <= 1) {
t = root;
colPlane = oTri;
colO = targ;
colPoint = vec3.add([], vert, vec3.scale(distLine, distLine, edgePos)); //result!
planeNormal = tri.Normal;
edge = true;
}
}
}
}
}
}
function getSmallestRoot(a, b, c, upperLimit) {
var det = (b*b) - 4*(a*c);
if (det<0) return null; //no result :'(
else {
det = Math.sqrt(det);
var root1 = ((-b)-det)/(2*a)
var root2 = ((-b)+det)/(2*a)
if (root1 > root2) { //ensure root1 is smallest
var temp = root1;
root1 = root2;
root2 = temp;
}
if (root1>0 && root1<upperLimit) {
return root1;
} else if (root2>0 && root2<upperLimit) {
return root2;
} else {
return null;
}
}
}
function pointInTriangle(tri, point, error) { //barycentric check
//compute direction vectors to the other verts and the point
var v0 = vec3.sub([], tri.Vertex3, tri.Vertex1);
var v1 = vec3.sub([], tri.Vertex2, tri.Vertex1);
var v2 = vec3.sub([], point, tri.Vertex1);
//we need to find u and v across the two vectors v0 and v1 such that adding them will result in our point's position
//where the unit length of both vectors v0 and v1 is 1, the sum of both u and v should not exceed 1 and neither should be negative
var dot00 = vec3.dot(v0, v0); var dot01 = vec3.dot(v0, v1); var dot02 = vec3.dot(v0, v2);
var dot11 = vec3.dot(v1, v1); var dot12 = vec3.dot(v1, v2);
//dot11 and dot00 result in the square of the distance for v0 and v1
var inverse = 1/(dot00*dot11 - dot01*dot01);
var u = (dot11*dot02 - dot01*dot12)*inverse;
var v = (dot00*dot12 - dot01*dot02)*inverse;
return (u>=-error && v>=-error && (u+v)<1+error);
}
function getTriList(pos, diff, kclO) { //gets tris from kcl around a line. currently only fetches from middle point of line, but should include multiple samples for large differences in future.
var sample = vec3.add([], pos, vec3.scale([], diff, 0.5))
return kclO.getPlanesAt(sample[0], sample[1], sample[2]);
}
})();

113
Code/Engine/mkdsConst.js Normal file
View File

@ -0,0 +1,113 @@
//
// mkdsConst.js
//--------------------
// Provides various game constants.
// by RHY3756547
//
window.MKDSCONST = new (function() {
this.COURSEDIR = "/data/Course/";
this.COURSES = [ //in order of course id, nitro through retro
"cross_course",
"bank_course",
"beach_course",
"mansion_course",
"desert_course",
"town_course",
"pinball_course",
"ridge_course",
"snow_course",
"clock_course",
"mario_course",
"airship_course",
"stadium_course",
"garden_course",
"koopa_course",
"rainbow_course",
"old_mario_sfc",
"old_momo_64",
"old_peach_agb",
"old_luigi_gc",
"old_donut_sfc",
"old_frappe_64",
"old_koopa_agb",
"old_baby_gc",
"old_noko_sfc",
"old_choco_64",
"old_luigi_agb",
"old_kinoko_gc",
"old_choco_sfc",
"old_hyudoro_64",
"old_sky_agb",
"old_yoshi_gc",
"mini_stage1",
"mini_stage2",
"mini_stage3",
"mini_stage4",
"mini_block_64",
"mini_dokan_gc"
]
this.COURSE_MUSIC = [
74,
16,
15,
21,
38,
17,
19,
36,
37,
39,
74,
18,
19,
20,
40,
41,
22,
30,
26,
33,
24,
31,
27,
34,
23,
29,
26,
35,
25,
32,
28,
33,
43,
43,
43,
43,
43,
43
]
})();

View File

@ -0,0 +1,156 @@
//
// clientScene.js
//--------------------
// Manages the game state when connected to a server. Drives the course scene and track picker.
// by RHY3756547
//
window.clientScene = function(wsUrl, wsInstance, res) {
var res = res; //gameRes
var t = this;
var WebSocket = window.WebSocket || window.MozWebSocket;
var ws = new WebSocket(wsUrl);
ws.binaryType = "arraybuffer";
t.ws = ws;
t.mode = -1;
t.activeScene = null;
t.myKart = null;
ws.onopen = function() {
console.log("initial connection")
//first we need to establish connection to the instance.
var obj = {
t:"*",
i:wsInstance,
c:{
name:"TestUser"+Math.round(Math.random()*10000),
char:Math.floor(Math.random()*12),
kart:Math.floor(Math.random()*0x24)
}
}
sendJSONMessage(obj);
};
ws.onmessage = function(evt) {
var d = evt.data;
if (typeof d != "string") {
//binary data
var view = new DataView(d);
var handler = binH[view.getUint8(0)];
if (handler != null) handler(view);
} else {
//JSON string
var obj;
try {
obj = JSON.parse(d);
} catch (err) {
debugger; //packet recieved from server is bullshit
return;
}
var handler = wsH["$"+obj.t];
if (handler != null) handler(obj);
}
}
this.update = function() {
if (t.activeScene != null) t.activeScene.update();
if (t.myKart != null) sendKartInfo(t.myKart);
}
this.render = function() {
if (t.activeScene != null) sceneDrawer.drawTest(gl, t.activeScene, 0, 0, gl.viewportWidth, gl.viewportHeight)
}
function abFromBlob(blob, callback) {
var fileReader = new FileReader();
fileReader.onload = function() {
callback(this.result);
};
fileReader.readAsArrayBuffer(blob);
}
function sendKartInfo(kart) {
var dat = new ArrayBuffer(0x61);
var view = new DataView(dat);
view.setUint8(0, 32);
netKart.saveKart(view, 1, kart, kart.lastInput);
ws.send(dat);
}
var wsH = {};
wsH["$*"] = function(obj) { //initiate scene.
t.myKart = null;
if (obj.m == 1) { //race
t.mode = 1;
var mainNarc, texNarc
if (obj.c.substr(0, 5) == "mkds/") {
var cnum = Number(obj.c.substr(5));
var music = MKDSCONST.COURSE_MUSIC[cnum];
var cDir = MKDSCONST.COURSEDIR+MKDSCONST.COURSES[cnum];
var mainNarc = new narc(lz77.decompress(gameROM.getFile(cDir+".carc")));
var texNarc = new narc(lz77.decompress(gameROM.getFile(cDir+"Tex.carc")));
setUpCourse(mainNarc, texNarc, music, obj)
}
else throw "custom tracks are not implemented yet!"
}
}
wsH["$+"] = function(obj) { //add kart. only used in debug circumstances. (people can't join normal gamemodes midgame)
console.log("kart added");
if (t.mode != 1) return;
var kart = new Kart([0, -2000, 0], 0, 0, obj.k.kart, obj.k.char, new ((obj.p)?((window.prompt("press y for cpu controlled") == "y")?controlRaceCPU:controlDefault):controlNetwork)(t.activeScene.nkm, {}), t.activeScene);
t.activeScene.karts.push(kart);
}
wsH["$-"] = function(obj) { //kart disconnect.
t.activeScene.karts[obj.k].active = false;
}
var binH = [];
binH[32] = function(view) {
//if we are in a race, update kart positions in main scene. we should trust the server on this, however if anything goes wrong it will be caught earlier.
if (t.mode != 1) return;
var n = view.getUint16(0x01, true);
var off = 0x03;
for (var i=0; i<n; i++) {
var kart = t.activeScene.karts[view.getUint16(off, true)];
off += 2;
if (kart != null && !kart.local) netKart.restoreKart(view, off, kart);
off += 0x60;
}
}
function setUpCourse(mainNarc, texNarc, music, obj) {
var chars = [];
for (var i=0; i<obj.k.length; i++) {
var k = obj.k[i];
var pKart = (i == obj.p);
//TODO: custom character support
chars.push({charN:k.char, kartN:k.kart, controller:((pKart)?((window.prompt("press y for cpu controlled") == "y")?controlRaceCPU:controlDefault):controlNetwork), raceCam:pKart, extraParams:[{k:"name", v:k.name}, {k:"active", v:k.active}]});
if (pKart) {
for (var i=0; i<7; i++) {
var tchar = Math.floor(Math.random()*12);
var tkart = Math.floor(Math.random()*0x24);
chars.push({charN:tchar, kartN:tkart, controller:controlRaceCPU, raceCam:false, extraParams:[{k:"name", v:"no"}, {k:"active", v:true}]});
}
}
}
t.activeScene = new courseScene(mainNarc, texNarc, music, chars, {}, res);
for (var i=0; i<obj.k.length; i++) {
t.activeScene.karts[i].active = obj.k[i].active;
if (t.activeScene.karts[i].local) t.myKart = t.activeScene.karts[i];
}
}
function sendJSONMessage(obj) {
ws.send(JSON.stringify(obj));
}
}

View File

@ -0,0 +1,456 @@
//
// courseScene.js
//--------------------
// Manages the ingame state of a course.
// by RHY3756547
//
// includes: narc.js
// formats/*
// engine/*
// entities/*
// gl-matrix.js
// render/*
//
window.courseScene = function(mainNarc, texNarc, music, chars, options, gameRes) {
var startSetups = [
{maxplayers:12, toAline:4, xspacing:32, yspacing:32, liney:160},
{maxplayers:24, toAline:4, xspacing:32, yspacing:32, liney:80},
{maxplayers:36, toAline:6, xspacing:21, yspacing:21, liney:80},
{maxplayers:48, toAline:6, xspacing:21, yspacing:21, liney:54},
{maxplayers:64, toAline:8, xspacing:16, yspacing:16, liney:54},
{maxplayers:112, toAline:8, xspacing:16, yspacing:16, liney:32},
]
var scn = this;
scn.sndUpdate = sndUpdate;
scn.update = update;
scn.draw = draw;
scn.removeParticle = removeParticle;
scn.removeEntity = removeEntity;
scn.updateMode = updateMode;
scn.lapAdvance = lapAdvance;
scn.fileBank = {};
var loadFunc = {
$nsbmd: nsbmd,
$nsbtx: nsbtx,
$nsbca: nsbca,
$nsbta: nsbta,
$nsbtp: nsbtp,
}
scn.typeRes = [];
scn.gameRes = gameRes;
scn.lightMat = [];
scn.farShadMat = [];
scn.shadMat = [];
//game mode initialization
scn.mode = { mode: -1, time: 0 };
var musicRestartTimer = -1;
var musicRestart = 3.5*60;
var musicRestartType = 0;
var finishers = [];
//load main course
var courseTx = new nsbtx(texNarc.getFile("/course_model.nsbtx"), false, true);
var taFile = mainNarc.getFile("/course_model.nsbta");
if (taFile != null) var courseTa = new nsbta(taFile); //can be null
var courseMdl = new nsbmd(mainNarc.getFile("/course_model.nsbmd"));
var course = new nitroModel(courseMdl, courseTx)
if (taFile != null) course.loadTexAnim(courseTa);
//load sky
var skyTx = new nsbtx(texNarc.getFile("/course_model_V.nsbtx"), false, true);
var staFile = mainNarc.getFile("/course_model_V.nsbta");
if (staFile != null) var skyTa = new nsbta(staFile); //can be null
console.log("--------- LOADING SKY ---------")
var skyMdl = new nsbmd(mainNarc.getFile("/course_model_V.nsbmd"));
var sky = new nitroModel(skyMdl, skyTx)
if (staFile != null) sky.loadTexAnim(skyTa);
ckcl = new kcl(mainNarc.getFile("/course_collision.kcl"), false);
cnkm = new nkm(mainNarc.getFile("/course_map.nkm"));
scn.course = course;
scn.sky = sky;
scn.kcl = ckcl;
scn.nkm = cnkm;
scn.entities = []; //these should never change
scn.karts = []; //these should probably not change
scn.items = new ItemController(scn); //these should change a lot!!
scn.particles = []; //not synced with server at all
scn.colEnt = [];
scn.musicPlayer = null;
startCourse(chars);
var frame = 0;
var entsToRemove = [];
function draw(gl, pMatrix, shadow) {
gl.cullFace(gl.BACK);
/*var mat = scn.camera.getView(scn);
var pMatrix = mat.p;
var mvMatrix = mat.mv;*/
var mvMatrix = mat4.create();
nitroRender.setAlpha(1);
if (!shadow) {
var skyMat = mat4.scale(mat4.create(), mvMatrix, [1/64, 1/64, 1/64]);
sky.setFrame(frame);
sky.draw(skyMat, pMatrix);
}
var lvlMat = mat4.scale(mat4.create(), mvMatrix, [1/64, 1/64, 1/64]);//[2, 2, 2]);
course.setFrame(frame);
course.draw(lvlMat, pMatrix);
var transE = [];
mat4.scale(mvMatrix, mvMatrix, [1/1024, 1/1024, 1/1024])
//"so why are these separated rhys??"
//
//fantastic i'm glad you asked
//if we draw lots of the same model, not animated in a row we don't need to resend the matStack for that model
//which saves a lot of time for the 2 extra model types per car.
for (var i=0; i<scn.karts.length; i++) if (scn.karts[i].active) scn.karts[i].drawKart(mvMatrix, pMatrix, gl);
for (var i=0; i<scn.karts.length; i++) if (scn.karts[i].active) scn.karts[i].drawWheels(mvMatrix, pMatrix, gl);
for (var i=0; i<scn.karts.length; i++) if (scn.karts[i].active) scn.karts[i].drawChar(mvMatrix, pMatrix, gl);
for (var i=0; i<scn.entities.length; i++) {
var e = scn.entities[i];
if (e.transparent) transE.push(e);
else e.draw(mvMatrix, pMatrix, gl);
}
for (var i=0; i<scn.particles.length; i++) {
var e = scn.particles[i];
e.draw(mvMatrix, pMatrix, gl);
}
scn.items.draw(mvMatrix, pMatrix, gl);
}
function sndUpdate(view) {
var mulmat = mat4.create();
mat4.scale(mulmat, mulmat, [1/1024, 1/1024, 1/1024]);
var view = mat4.mul([], view, mulmat)
for (var i=0; i<scn.karts.length; i++) {
var e = scn.karts[i];
if (e.sndUpdate != null) e.sndUpdate(view);
}
for (var i=0; i<scn.entities.length; i++) {
var e = scn.entities[i];
if (e.sndUpdate != null) e.sndUpdate(view);
}
}
function update() {
var shadres = 0.25;
var targ = vec3.transformMat4([], scn.camera.targetShadowPos, scn.lightMat);
vec3.scale(targ, targ, 1/1024);
mat4.mul(scn.shadMat, mat4.ortho(mat4.create(), targ[0]-shadres, targ[0]+shadres, targ[1]-shadres, targ[1]+shadres, -targ[2]-2.5, -targ[2]+2.5), scn.lightMat);
for (var i=0; i<scn.karts.length; i++) {
var ent = scn.karts[i];
if (ent.active) ent.update(scn);
}
var entC = scn.entities.slice(0);
for (var i=0; i<entC.length; i++) {
var ent = entC[i];
ent.update(scn);
}
var prtC = scn.particles.slice(0);
for (var i=0; i<prtC.length; i++) {
var ent = prtC[i];
ent.update(scn);
}
scn.items.update(scn);
if (musicRestartTimer > -1) {
musicRestartTimer++;
if (musicRestartTimer > musicRestart) {
scn.musicPlayer = nitroAudio.playSound(music, {volume:2, bpmMultiplier:(musicRestartType==0)?1.25:1}, null);
musicRestartTimer = -1;
}
}
for (var i=0; i<entsToRemove.length; i++) {
scn.entities.splice(scn.entities.indexOf(entsToRemove[i]), 1);
}
entsToRemove = [];
var mat = scn.camera.getView(scn, nitroRender.getViewWidth(), nitroRender.getViewHeight());
frame++;
}
function removeParticle(obj) {
scn.particles.splice(scn.particles.indexOf(obj), 1);
}
function removeEntity(obj) {
entsToRemove.push(obj);
}
function compilePaths() {
var path = scn.nkm.sections["PATH"].entries;
var pts = scn.nkm.sections["POIT"].entries;
var paths = [];
var ind = 0;
for (var i=0; i<path.length; i++) {
var p = [];
for (var j=0; j<path[i].numPts; j++) {
p.push(pts[ind++]);
}
paths.push(p);
}
scn.paths = paths;
}
function startCourse() {
scn.lightMat = mat4.create();
mat4.rotateX(scn.lightMat, scn.lightMat, Math.PI*(61/180));
mat4.rotateY(scn.lightMat, scn.lightMat, Math.PI*(21/180));
mat4.mul(scn.farShadMat, mat4.ortho(mat4.create(), -5, 5, -5, 5, -5, 5), scn.lightMat);
compilePaths();
//chars format: {charN: int, kartN: int, controller: function, raceCam: bool, controlOptions: object}
var startSet = null;
for (var i=0; i<startSetups.length; i++) {
if (chars.length < startSetups[i].maxplayers) {
startSet = startSetups[i];
break;
}
}
var startpos = scn.nkm.sections["KTPS"].entries[0];
for (var i=0; i<chars.length; i++) {
var c = chars[i];
var kart = new Kart(vec3.add([], startpos.pos, startPosition(startSet.toAline, startSet.xspacing, startSet.yspacing, startSet.liney, startpos.angle[1], i)), (180-startpos.angle[1])*(Math.PI/180), 0, c.kartN, c.charN, new c.controller(scn.nkm, c.controlOptions), scn);
scn.karts.push(kart);
var spectator = false; //(prompt("Type y for spectator cam")=="y")
if (c.raceCam) scn.camera = (spectator?(new cameraSpectator(kart, scn)):(new cameraIngame(kart, scn)));
}
var obj = scn.nkm.sections["OBJI"].entries;
for (var i=0; i<obj.length; i++) {
var o = obj[i];
var func = objDatabase.idToType[o.ID];
if (func != null) {
var ent = new func(o, scn);
if (scn.typeRes[o.ID] == null) loadRes(ent.requireRes(), o.ID)
else ent.requireRes(); //some objects use this for determining their function.
ent.provideRes(scn.typeRes[o.ID]);
scn.entities.push(ent);
if (ent.collidable) scn.colEnt.push(ent);
}
}
}
function loadOrGet(res) {
var ext = res.split(".").pop();
if (scn.fileBank["$"+ext] == null) scn.fileBank["$"+ext] = {};
var item = scn.fileBank["$"+ext]["$"+res];
if (item != null) return item;
var func = loadFunc["$"+ext];
if (func != null) {
var test = mainNarc.getFile(res);
if (test == null) test = gameRes.MapObj.getFile(res.split("/").pop())
if (test == null) throw "COULD NOT FIND RESOURCE "+res+"!";
if (res == "/MapObj/itembox.nsbmd") throwWhatever = true;
var item = new func(test);
scn.fileBank["$"+ext]["$"+res] = item;
return item;
}
}
// the thresholds for different win sounds and music
// thresh, goalsound, goalmusic, goalpostmusic
var finishPercents = [
[0, 66, 46, 58],
[0.5, 66, 47, 56],
[1.1, 67, 48, 57]
]
function lapAdvance(kart) {
//if the kart is us, play some sounds and show lakitu
var winPercent = finishers.length/scn.karts.length;
if (kart.local) {
if (kart.lapNumber == 3) {
//last lap
musicRestartTimer = 0;
nitroAudio.instaKill(scn.musicPlayer);
scn.musicPlayer = nitroAudio.playSound(62, {volume:2}, null);
}
else if (kart.lapNumber == 4) {
var finishTuple = [];
for (var i=0; i<finishPercents.length; i++) {
if (finishPercents[i][0] > winPercent) continue;
finishTuple = finishPercents[i];
}
kart.controller = new controlRaceCPU(scn.nkm, {});
kart.controller.setKart(kart);
kart.anim.setAnim(winPercent>0.5?kart.charRes.LoseA:kart.charRes.winA);
kart.animMode = "raceEnd";
scn.camera = (new cameraSpectator(kart, scn));
nitroAudio.playSound(finishTuple[1], {volume:2}, 0);
nitroAudio.playSound(finishTuple[2], {volume:2}, null);
nitroAudio.instaKill(scn.musicPlayer);
musicRestartTimer = 0;
musicRestart = 7.5*60;
musicRestartType = 1;
music = finishTuple[3];
scn.entities.push(new Race3DUI(scn, "goal"));
}
else if (kart.lapNumber < 4) nitroAudio.playSound(65, {volume:2}, 0);
}
if (kart.lapNumber == 4) finishers.push(kart);
}
function startPosition(toAline, xspacing, yspacing, liney, angle, i) {
var horizN = i%toAline;
var vertN = Math.floor(i/toAline);
var staggered = (vertN%2); //second line moves 1/2 x spacing to the right
var relPos = [(horizN-(toAline/2)-0.25)*xspacing+staggered*0.5, 8, -(horizN*yspacing + vertN*liney)];
var mat = mat4.rotateY([], mat4.create(), angle*(Math.PI/180));
vec3.transformMat4(relPos, relPos, mat);
return relPos;
}
function loadRes(res, id) {
var models = [];
for (var i=0; i<res.mdl.length; i++) {
var inf = res.mdl[i];
var bmd = loadOrGet("/MapObj/"+inf.nsbmd);
var btx = (inf.nsbtx == null)?null:loadOrGet("/MapObj/"+inf.nsbtx);
var mdl = new nitroModel(bmd, btx);
models.push(mdl);
}
var other = [];
if (res.other != null) {
for (var i=0; i<res.other.length; i++) {
other.push(loadOrGet("/MapObj/"+res.other[i]));
}
}
scn.typeRes[id] = {mdl:models, other: other};
}
function updateMode(mode) {
// updates the game mode...
// {
// id = (0:pregame, 1:countdown, 2:race, 3:postgame)
// time = (elapsed time in seconds)
// frameDiv = (0-60)
// }
var lastid = scn.mode.id;
if (lastid != mode.id) {
//mode switch
switch (mode.id) {
case 0:
//race init. fade scene in and play init music.
nitroAudio.playSound(11, {volume:2}, null); //7:race (gp), 11:race2 (vs), 12:battle
break;
case 1:
//spawn lakitu and countdown animation. allow pre-acceleration.
//generally happens at least 2 seconds after init
scn.entities.push(new Race3DUI(scn, "count", -30));
break;
case 2:
//enable all racers and start music
for (var i=0; i<scn.karts.length; i++) {
scn.karts[i].preboost = false;
}
nitroAudio.playSound(40, {volume:2, bpmMultiplier:16}, 0);
scn.entities.push(new Race3DUI(scn, "start"));
break;
}
}
if (scn.mode.time != mode.time) {
switch (mode.id) {
case 0:
break;
case 1:
if (mode.time > 0) {
//beeps for countdown
nitroAudio.playSound(39, {bpmMultiplier:16}, 0);
}
break;
case 2:
//show ui and play music at certain time after go
if (mode.time == 1) {
scn.musicPlayer = nitroAudio.playSound(music, {volume:2}, null);
}
//
break;
}
}
//win sting: 46
//ok sting: 47
//lose sting: 48
//battle lose sting: 49
//battle win sting: 50
//ok sting??: 51
//mission mode win sting: 52
//mission mode win2 sting: 53
//mission mode superwin sting: 54
//boss win sting: 55
//ok music: 56
//lose music: 57
//win music: 58
//racelose : 61
//ok music: 58
//good time trials music: 59
//ok time trials: 60
//final lap: 62
//full results win: 63
//results draw: 64
//full results lose: 65
//gp results cutscene music: 66
//gp results win music: 67
//??? : 68
//credits: 69-70
// star: 73
scn.mode = mode;
}
}

View File

@ -0,0 +1,132 @@
//
// sceneDrawer.js
//--------------------
// Provides functions to draw scenes in various ways.
// by RHY3756547
//
window.sceneDrawer = new function() {
var gl, shadowTarg;
var shadowRes = 2048;
this.init = function(gl) {
gl = gl;
shadowTarg = createRenderTarget(gl, shadowRes, shadowRes, true);
}
this.drawWithShadow = function(gl, scn, x, y, width, height) {
if (scn.lastWidth != width || scn.lastHeight != height) {
scn.lastWidth = width;
scn.lastHeight = height;
scn.renderTarg = createRenderTarget(gl, width, height, true);
}
var view = scn.camera.getView(scn, width, height);
var viewProj = mat4.mul(view.p, view.p, view.mv);
var shadMat = scn.shadMat;
if (scn.farShad == null) {
scn.farShad = createRenderTarget(gl, shadowRes*2, shadowRes*2, true);
gl.viewport(0, 0, shadowRes*2, shadowRes*2);
gl.bindFramebuffer(gl.FRAMEBUFFER, scn.farShad.fb);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
gl.colorMask(false, false, false, false);
scn.draw(gl, scn.farShadMat, true);
}
gl.viewport(0, 0, shadowRes, shadowRes);
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowTarg.fb);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
gl.colorMask(false, false, false, false);
scn.draw(gl, shadMat, true);
gl.viewport(0, 0, width, height);
gl.bindFramebuffer(gl.FRAMEBUFFER, scn.renderTarg.fb);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
gl.colorMask(true, true, true, true);
scn.draw(gl, viewProj, false);
scn.sndUpdate(view.mv);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(x, y, width, height);
shadowRender.drawShadowed(scn.renderTarg.color, scn.renderTarg.depth, shadowTarg.depth, scn.farShad.depth, viewProj, shadMat, scn.farShadMat)
}
this.drawTest = function(gl, scn, x, y, width, height) {
var view = scn.camera.view; //scn.camera.getView(scn, width, height);
var viewProj = mat4.mul(mat4.create(), view.p, view.mv);
view = {p: viewProj, mv: view.mv};
var shadMat = scn.shadMat;
nitroRender.unsetShadowMode();
nitroRender.flagShadow = true;
nitroRender.updateBillboards(scn.lightMat);
if (scn.farShad == null) {
scn.farShad = createRenderTarget(gl, shadowRes*2, shadowRes*2, true);
gl.viewport(0, 0, shadowRes*2, shadowRes*2);
gl.bindFramebuffer(gl.FRAMEBUFFER, scn.farShad.fb);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
gl.colorMask(false, false, false, false);
scn.draw(gl, scn.farShadMat, true);
}
gl.viewport(0, 0, shadowRes, shadowRes);
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowTarg.fb);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
gl.colorMask(false, false, false, false);
scn.draw(gl, shadMat, true);
nitroRender.setShadowMode(shadowTarg.depth, scn.farShad.depth, shadMat, scn.farShadMat);
nitroRender.flagShadow = false;
nitroRender.updateBillboards(view.mv);
gl.viewport(x, y, width, height);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
gl.colorMask(true, true, true, true);
scn.draw(gl, viewProj, false);
scn.sndUpdate(view.mv);
}
function createRenderTarget(gl, xsize, ysize, depth) {
var depthTextureExt = gl.getExtension("WEBGL_depth_texture");
if (!depthTextureExt) alert("depth texture not supported! we're DOOMED! jk we'll just have to add a fallback for people with potato gfx");
var colorTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, colorTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, xsize, ysize, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
var depthTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, depthTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, xsize, ysize, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
var framebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTexture, 0);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
return {
color: colorTexture,
depth: depthTexture,
fb: framebuffer
}
}
}

View File

@ -0,0 +1,86 @@
//
// singleScene.js
//--------------------
// Drives the course scene when not connected to a server. Simulates responses expected from a server.
// by RHY3756547
//
window.singleScene = function(course, wsInstance, res) {
var res = res; //gameRes
var t = this;
t.mode = -1;
t.activeScene = null;
t.myKart = null;
var mchar = Math.floor(Math.random()*12);
var mkart = Math.floor(Math.random()*0x24);
this.update = function() {
if (t.activeScene != null) {
t.activeScene.update();
//simulate what a server would do
updateServer();
}
}
var advanceTimes = [3,4,-1,-1]
function updateServer() {
var m = t.mode;
m.frameDiv++;
if (m.frameDiv == 60) {
m.frameDiv -= 60;
m.time++;
var timeAd = advanceTimes[m.id];
if (timeAd != -1 && m.time >= timeAd) {
m.id++;
m.time = 0;
}
}
t.activeScene.updateMode(JSON.parse(JSON.stringify(t.mode)));
}
this.render = function() {
if (t.activeScene != null) sceneDrawer.drawTest(gl, t.activeScene, 0, 0, gl.viewportWidth, gl.viewportHeight)
}
begin(course);
function begin(course) {
var mainNarc, texNarc
if (course.substr(0, 5) == "mkds/") {
var cnum = Number(course.substr(5));
var music = MKDSCONST.COURSE_MUSIC[cnum];
var cDir = MKDSCONST.COURSEDIR+MKDSCONST.COURSES[cnum];
var mainNarc = new narc(lz77.decompress(gameROM.getFile(cDir+".carc")));
var texNarc = new narc(lz77.decompress(gameROM.getFile(cDir+"Tex.carc")));
setUpCourse(mainNarc, texNarc, music)
} else throw "custom tracks are not implemented yet!"
}
function setUpCourse(mainNarc, texNarc, music) {
var chars = [];
chars.push({charN:mchar, kartN:mkart, controller:((window.prompt("press y for cpu controlled") == "y")?controlRaceCPU:controlDefault), raceCam:true, extraParams:[{k:"name", v:"single"}, {k:"active", v:true}]});
for (var i=0; i<7; i++) {
var tchar = Math.floor(Math.random()*12);
var tkart = Math.floor(Math.random()*0x24);
chars.push({charN:tchar, kartN:tkart, controller:controlRaceCPU, raceCam:false, extraParams:[{k:"name", v:"no"}, {k:"active", v:true}]});
}
t.activeScene = new courseScene(mainNarc, texNarc, music, chars, {}, res);
t.myKart = t.activeScene.karts[0];
t.mode = {
id:0,
time:0,
frameDiv:0,
}
t.activeScene.updateMode(t.mode);
}
}

View File

@ -0,0 +1,83 @@
window.fileStore = new (function(){
var db;
var indexedDB;
this.requestGameFiles = requestGameFiles;
function requestGameFiles(callback) {
indexedDB = window.indexedDB
|| window.webkitIndexedDB
|| window.mozIndexedDB
|| window.shimIndexedDB;
var request = indexedDB.open("MKJS_DB", 1);
request.onerror = window.onerror;
request.onsuccess = function(event) {
db = event.target.result;
loadGameFiles(callback);
}
request.onupgradeneeded = function(event) {
db = event.target.result;
var objectStore = db.createObjectStore("files", { keyPath: "filename" });
objectStore.transaction.oncomplete = function(event) {
loadGameFiles(callback);
}
}
}
function loadGameFiles(callback) {
var transaction = db.transaction(["files"]);
var objectStore = transaction.objectStore("files");
var request = objectStore.get("mkds.nds");
request.onerror = function(event) {
alert("Fatal database error!");
};
request.onsuccess = function(event) {
if (request.result == null) downloadGame("Mario Kart DS.nds", callback);
else callback(request.result.data);
};
}
function downloadGame(url, callback) {
if (typeof url == "string") {
var xml = new XMLHttpRequest();
xml.open("GET", url, true);
xml.responseType = "arraybuffer";
xml.onload = function() {
storeGame(xml.response, callback);
}
xml.send();
} else {
alert("You need to supply MKJS with a Mario Kart DS ROM to function. Click anywhere on the page to load a file.")
fileCallback = callback;
document.getElementById("fileIn").onchange = fileInChange;
waitForROM = true;
}
}
function fileInChange(e) {
var bFile = e.target.files[0];
var bReader = new FileReader();
bReader.onload = function(e) {
waitForROM = false; //todo: verify
storeGame(e.target.result, fileCallback);
};
bReader.readAsArrayBuffer(bFile);
}
function storeGame(dat, callback) {
var transaction = db.transaction(["files"], "readwrite");
var objectStore = transaction.objectStore("files");
var request = objectStore.put({filename:"mkds.nds", data:dat});
request.onerror = function(event) {
alert("Failed to store game locally!");
callback(dat);
};
request.onsuccess = function(event) {
callback(dat);
};
}
})();

View File

@ -0,0 +1,196 @@
//
// bowserPlatforms.js
//--------------------
// Provides platforms for Bowser's Castle
// by RHY3756547
//
// includes:
// render stuff idk
//
window.ObjRotaryRoom = function(obji, scene) {
var obji = obji;
var res = [];
var t = this;
t.collidable = true;
t.colMode = 0;
t.colRad = 512;
t.getCollision = getCollision;
t.moveWith = moveWith;
t.pos = vec3.clone(obji.pos);
//t.angle = vec3.clone(obji.angle);
t.scale = vec3.clone(obji.scale);
t.requireRes = requireRes;
t.provideRes = provideRes;
t.update = update;
t.draw = draw;
t.speed = (obji.setting1&0xFFFF)/8192;
t.angle = 0;
var dirVel = 0;
function update(scene) {
dirVel = t.speed;
t.angle += dirVel;
}
function draw(view, pMatrix) {
var mat = mat4.translate(mat4.create(), view, t.pos);
mat4.scale(mat, mat, vec3.scale([], t.scale, 16));
mat4.rotateY(mat, mat, t.angle);
res.mdl[0].draw(mat, pMatrix);
}
function requireRes() { //scene asks what resources to load
return {mdl:[{nsbmd:"rotary_room.nsbmd"}]};
}
function provideRes(r) {
res = r; //...and gives them to us. :)
}
function getCollision() {
var obj = {};
var inf = res.mdl[0].getCollisionModel(0, 0);
obj.tris = inf.dat;
var mat = mat4.translate([], mat4.create(), t.pos);
mat4.scale(mat, mat, vec3.mul([], [16*inf.scale, 16*inf.scale, 16*inf.scale], t.scale));
mat4.rotateY(mat, mat, t.angle);
obj.mat = mat;
return obj;
}
function moveWith(obj) { //used for collidable objects that move.
var p = vec3.sub([], obj.pos, t.pos);
vec3.transformMat4(p, p, mat4.rotateY([], mat4.create(), dirVel));
vec3.add(obj.pos, t.pos, p);
obj.physicalDir -= dirVel;
}
}
window.ObjRoutePlatform = function(obji, scene) {
var obji = obji;
var res = [];
var genCol;
var t = this;
t.collidable = true;
t.colMode = 0;
t.colRad = 512;
t.getCollision = getCollision;
t.moveWith = moveWith;
t.pos = vec3.clone(obji.pos);
//t.angle = vec3.clone(obji.angle);
t.scale = vec3.clone(obji.scale);
t.requireRes = requireRes;
t.provideRes = provideRes;
t.update = update;
t.draw = draw;
generateCol();
t.statDur = (obji.setting1&0xFFFF);
t.route = scene.paths[obji.routeID];
t.routeSpeed = 1/6;
t.routePos = 0;
t.nextNode = t.route[t.routePos];
t.prevPos = t.pos;
t.elapsedTime = 0;
t.mode = 0;
var movVel;
//t.speed = (obji.setting1&0xFFFF)/8192;
function update(scene) {
if (t.mode == 0) {
t.elapsedTime += t.routeSpeed;
movVel = vec3.sub([], t.nextNode.pos, t.prevPos);
//vec3.normalize(movVel, movVel);
vec3.scale(movVel, movVel, t.routeSpeed/t.nextNode.duration);
vec3.add(t.pos, t.pos, movVel);
if (t.elapsedTime >= t.nextNode.duration) {
t.elapsedTime = 0;
t.prevPos = t.nextNode.pos;
t.routePos = (t.routePos+1)%t.route.length;
t.nextNode = t.route[t.routePos];
t.mode = 1;
}
} else {
t.elapsedTime += 1;
movVel = [0, 0, 0];
if (t.elapsedTime > t.statDur) {
t.mode = 0;
t.elapsedTime = 0;
}
}
}
function draw(view, pMatrix) {
var mat = mat4.translate(mat4.create(), view, t.pos);
mat4.scale(mat, mat, vec3.scale([], t.scale, 16));
res.mdl[0].draw(mat, pMatrix);
}
function requireRes() { //scene asks what resources to load
return {mdl:[{nsbmd:"koopa_block.nsbmd"}]}; //25x, 11y
}
function provideRes(r) {
res = r; //...and gives them to us. :)
}
function generateCol() {
genCol = {dat: [
{
Vertex1: [25, 0, 11],
Vertex2: [25, 0, -11],
Vertex3: [-25, 0, -11],
Normal: [0, 1, 0]
},
{
Vertex1: [-25, 0, -11],
Vertex2: [-25, 0, 11],
Vertex3: [25, 0, 11],
Normal: [0, 1, 0]
},
], scale: 1};
}
function getCollision() {
var obj = {};
var inf = genCol;//res.mdl[0].getCollisionModel(0, 0);
obj.tris = inf.dat;
var mat = mat4.translate([], mat4.create(), t.pos);
mat4.scale(mat, mat, vec3.mul([], [16*inf.scale, 16*inf.scale, 16*inf.scale], t.scale));
obj.mat = mat;
return obj;
}
function moveWith(obj) { //used for collidable objects that move.
/*var p = vec3.sub([], obj.pos, t.pos);
vec3.transformMat4(p, p, mat4.rotateY([], mat4.create(), dirVel));
vec3.add(obj.pos, t.pos, p);
obj.physicalDir -= dirVel;*/
vec3.add(obj.pos, obj.pos, movVel);
}
}

View File

@ -0,0 +1,273 @@
//
// decorations.js
//--------------------
// Provides decoration objects.
// by RHY3756547
//
// includes:
// render stuff idk
//
window.ObjDecor = function(obji, scene) {
var forceBill;
var obji = obji;
var res = [];
var t = this;
t.pos = vec3.clone(obji.pos);
t.angle = vec3.clone(obji.angle);
t.scale = vec3.clone(obji.scale);
t.requireRes = requireRes;
t.provideRes = provideRes;
t.update = update;
t.draw = draw;
var mat = mat4.create();
var frame = 0;
var anim = null;
var animFrame = 0;
var animMat = null;
function draw(view, pMatrix) {
mat4.translate(mat, view, t.pos);
if (t.angle[2] != 0) mat4.rotateZ(mat, mat, t.angle[2]*(Math.PI/180));
if (t.angle[1] != 0) mat4.rotateY(mat, mat, t.angle[1]*(Math.PI/180));
if (t.angle[0] != 0) mat4.rotateX(mat, mat, t.angle[0]*(Math.PI/180));
if (anim != null) {
animMat = anim.setFrame(0, 0, animFrame++);
}
mat4.scale(mat, mat, vec3.scale([], t.scale, 16));
res.mdl[0].draw(mat, pMatrix, animMat);
}
function update() {
}
function requireRes() { //scene asks what resources to load
forceBill = true;
switch (obji.ID) {
case 0x012D:
return {mdl:[{nsbmd:"BeachTree1.nsbmd"}]}; //non solid
case 0x012E:
return {mdl:[{nsbmd:"BeachTree1.nsbmd"}]};
case 0x012F:
return {mdl:[{nsbmd:"earthen_pipe1.nsbmd"}]}; //why is there an earthen pipe 2
case 0x0130:
return {mdl:[{nsbmd:"opa_tree1.nsbmd"}]};
case 0x0131:
return {mdl:[{nsbmd:"OlgPipe1.nsbmd"}]};
case 0x0132:
return {mdl:[{nsbmd:"OlgMush1.nsbmd"}]};
case 0x0133:
return {mdl:[{nsbmd:"of6yoshi1.nsbmd"}]};
case 0x0134:
return {mdl:[{nsbmd:"cow.nsbmd"}], other:[null, null, "cow.nsbtp"]}; //has animation, cow.nsbtp
case 0x0135:
forceBill = false;
return {mdl:[{nsbmd:"NsKiller1.nsbmd"}, {nsbmd:"NsKiller2.nsbmd"}, {nsbmd:"NsKiller2_s.nsbmd"}]}; //probably animates
case 0x0138:
return {mdl:[{nsbmd:"GardenTree1.nsbmd"}]};
case 0x0139:
return {mdl:[{nsbmd:"kamome.nsbmd"}], other:[null, null, "kamone.nsbtp"]}; //animates using nsbtp, and uses route to move
case 0x013A:
return {mdl:[{nsbmd:"CrossTree1.nsbmd"}]};
//0x013C is big cheep cheep
case 0x013C:
forceBill = false;
return {mdl:[{nsbmd:"bakubaku.nsbmd"}]};
//0x013D is spooky ghost
case 0x013D:
forceBill = false;
return {mdl:[{nsbmd:"teresa.nsbmd"}], other:[null, null, "teresa.nsbtp"]};
case 0x013E:
return {mdl:[{nsbmd:"Bank_Tree1.nsbmd"}]};
case 0x013F:
return {mdl:[{nsbmd:"GardenTree1.nsbmd"}]}; //non solid
case 0x0140:
return {mdl:[{nsbmd:"chandelier.nsbmd"}], other:[null, "chandelier.nsbca"]};
case 0x0142:
return {mdl:[{nsbmd:"MarioTree3.nsbmd"}]};
case 0x0145:
return {mdl:[{nsbmd:"TownTree1.nsbmd"}]};
case 0x0146:
//solid
return {mdl:[{nsbmd:"Snow_Tree1.nsbmd"}]};
case 0x0148:
return {mdl:[{nsbmd:"DeTree1.nsbmd"}]};
case 0x0149:
return {mdl:[{nsbmd:"BankEgg1.nsbmd"}]};
case 0x014B:
return {mdl:[{nsbmd:"KinoHouse1.nsbmd"}]};
case 0x014C:
return {mdl:[{nsbmd:"KinoHouse2.nsbmd"}]};
case 0x014D:
return {mdl:[{nsbmd:"KinoMount1.nsbmd"}]};
case 0x014E:
return {mdl:[{nsbmd:"KinoMount2.nsbmd"}]};
case 0x014F:
return {mdl:[{nsbmd:"olaTree1c.nsbmd"}]};
case 0x0150:
return {mdl:[{nsbmd:"osaTree1c.nsbmd"}]};
case 0x0151:
forceBill = false;
return {mdl:[{nsbmd:"picture1.nsbmd"}], other:[null, "picture1.nsbca"]};
case 0x0152:
forceBill = false;
return {mdl:[{nsbmd:"picture2.nsbmd"}], other:[null, "picture2.nsbca"]};
case 0x0153:
return {mdl:[{nsbmd:"om6Tree1.nsbmd"}]};
//0x0154 is rainbow road rotating star
case 0x0154:
forceBill = false;
return {mdl:[{nsbmd:"RainStar.nsbmd"}], other:["RainStar.nsbta"]};
case 0x0155:
return {mdl:[{nsbmd:"Of6Tree1.nsbmd"}]};
case 0x0156:
return {mdl:[{nsbmd:"Of6Tree1.nsbmd"}]};
case 0x0157:
return {mdl:[{nsbmd:"TownMonte.nsbmd"}], other:[null, null, "TownMonte.nsbtp"]}; //pianta!
//debug pianta bridge
case 0x00CC:
forceBill = false;
return {mdl:[{nsbmd:"bridge.nsbmd"}], other:[null, "bridge.nsbca"]};
//debug puddle
case 0x000D:
forceBill = false;
return {mdl:[{nsbmd:"puddle.nsbmd"}]};
//debug airship
case 0x0158:
forceBill = false;
return {mdl:[{nsbmd:"airship.nsbmd"}]};
//need version for 3d objects?
//DEBUG ENEMIES - remove here when implemented.
case 0x0191: //goomba
return {mdl:[{nsbmd:"kuribo.nsbmd"}], other:[null, null, "kuribo.nsbtp"]}; //has nsbtp, route
case 0x0192: //rock
forceBill = false;
return {mdl:[{nsbmd:"rock.nsbmd"}, {nsbmd:"rock_shadow.nsbmd"}]}; //has route
case 0x0193: //thwomp
forceBill = false;
return {mdl:[{nsbmd:"dossun.nsbmd"}, {nsbmd:"dossun_shadow.nsbmd"}]}; //has route
case 0x0196: //chain chomp
forceBill = false;
return {mdl:[{nsbmd:"wanwan.nsbmd"}, {nsbmd:"wanwan_chain.nsbmd"}, {nsbmd:"wanwan_kui.nsbmd"}, {nsbmd:"rock_shadow.nsbmd"}]};
case 0x0198: //bowser castle GBA fireball
return {mdl:[{nsbmd:"mkd_ef_bubble.nsbmd"}]};
case 0x0199: //peach gardens monty
forceBill = false;
return {mdl:[{nsbmd:"choropu.nsbmd"}], other:[null, null, "choropu.nsbtp"]}; //has nsbtp
case 0x019B: //cheep cheep (bouncing)
return {mdl:[{nsbmd:"pukupuku.nsbmd"}], other:[null, null, "pukupuku.nsbtp"]}; //has nsbtp
case 0x019D: //snowman
return {mdl:[{nsbmd:"sman_top.nsbmd"}, {nsbmd:"sman_bottom.nsbmd"}]};
case 0x019E: //trunk with bats
forceBill = false;
return {mdl:[{nsbmd:"kanoke_64.nsbmd"}, {nsbmd:"basabasa.nsbmd"}], other:[null, "kanoke_64.nsbca"]}; //basa has nsbtp
case 0x01A0: //bat
return {mdl:[{nsbmd:"basabasa.nsbmd"}], other:[null, null, "basabasa.nsbtp"]}; //has nsbtp
case 0x01A1: //as fortress cannon
forceBill = false;
return {mdl:[{nsbmd:"NsCannon1.nsbmd"}]};
case 0x01A3: //mansion moving tree
forceBill = false;
return {mdl:[{nsbmd:"move_tree.nsbmd"}], other:[null, "move_tree.nsbca"]}; //has route
case 0x01A4: //flame
forceBill = false;
return {mdl:[{nsbmd:"mkd_ef_burner.nsbmd"}], other:["mkd_ef_burner.nsbta", null]};
case 0x01A5: //chain chomp no base
forceBill = false;
return {mdl:[{nsbmd:"wanwan.nsbmd"}, {nsbmd:"wanwan_chain.nsbmd"}, {nsbmd:"rock_shadow.nsbmd"}]};
case 0x01A6: //plant
return {mdl:[{nsbmd:"ob_pakkun_sf.nsbmd"}], other:[null, null, "ob_pakkun_sf.nsbtp"]}; //has nsbtp
case 0x01A7: //monty airship
forceBill = false;
return {mdl:[{nsbmd:"poo.nsbmd"}, {nsbmd:"cover.nsbmd"}, {nsbmd:"hole.nsbmd"}], other:[null, null, "poo.nsbtp"]}; //poo has nsbtp
case 0x01A8: //bound
forceBill = false;
return {mdl:[{nsbmd:"bound.nsbmd"}], other:[null, null, "bound.nsbtp"]}; //has nsbtp
case 0x01A9: //flipper
forceBill = false;
return {mdl:[{nsbmd:"flipper.nsbmd"}], other:["flipper.nsbta", null, "flipper.nsbtp"]}; //has nsbtp
case 0x01AA: //3d fire plant
forceBill = false;
//note... what exactly is PakkunZHead...
return {mdl:[{nsbmd:"PakkunMouth.nsbmd"}, {nsbmd:"PakkunBody.nsbmd"}, {nsbmd:"FireBall.nsbmd"}], other:[null, "PakkunMouth.nsbca"]};
case 0x01AC: //crab
forceBill = false;
return {mdl:[{nsbmd:"crab.nsbmd"}, {nsbmd:"crab_hand.nsbmd"}], other:[null, null, "crab.nsbtp"]}; //both have nsbtp
case 0x01AD: //desert hills sun
forceBill = false;
return {mdl:[{nsbmd:"sun.nsbmd"}, {nsbmd:"sun_LOD.nsbmd"}]/*, other:[null, "sun.nsbca"]*/}; //exesun animation does not load
case 0x01B0: //routed iron ball
return {mdl:[{nsbmd:"IronBall.nsbmd"}]};
case 0x01B1: //routed choco mountain rock
forceBill = false;
return {mdl:[{nsbmd:"rock2.nsbmd"}]};
case 0x01B2: //sanbo... whatever that is (pokey?) routed
return {mdl:[{nsbmd:"sanbo_h.nsbmd"}, {nsbmd:"sanbo_b.nsbmd"}]};
case 0x01B3: //iron ball
return {mdl:[{nsbmd:"IronBall.nsbmd"}]};
case 0x01B4: //cream
forceBill = false;
return {mdl:[{nsbmd:"cream.nsbmd"}, {nsbmd:"cream_effect.nsbmd"}]};
case 0x01B5: //berry
forceBill = false;
return {mdl:[{nsbmd:"berry.nsbmd"}, {nsbmd:"cream_effect.nsbmd"}]};
}
}
function provideRes(r) {
res = r; //...and gives them to us. :)
if (forceBill) {
t.angle[1] = 0;
var bmd = r.mdl[0].bmd;
bmd.hasBillboards = true;
var models = bmd.modelData.objectData;
for (var i=0; i<models.length; i++) {
var objs = models[i].objects.objectData;
for (var j=0; j<objs.length; j++) {
objs[i].billboardMode = 2;
}
}
}
if (r.other != null) {
if (r.other.length > 0 && r.other[0] != null) {
res.mdl[0].loadTexAnim(r.other[0]);
}
if (r.other.length > 1 && r.other[1] != null)
anim = new nitroAnimator(r.mdl[0].bmd, r.other[1]);
}
}
}

120
Code/Entities/itembox.js Normal file
View File

@ -0,0 +1,120 @@
//
// itembox.js
//--------------------
// Drives and animates itembox entity.
// by RHY3756547
//
window.ItemBox = function(obji, scene) {
var obji = obji;
var res = [];
var t = this;
var anim = 0;
var animFrame = 0;
var animMat;
var frames = 0;
t.soundProps = {};
t.pos = vec3.clone(obji.pos);
//t.angle = vec3.clone(obji.angle);
t.scale = vec3.clone(obji.scale);
t.sndUpdate = sndUpdate;
t.requireRes = requireRes;
t.provideRes = provideRes;
t.update = update;
t.draw = draw;
t.mode = 0;
t.time = 0;
var test = 0;
function update(scene) {
switch (t.mode) {
case 0: //alive
for (var i=0; i<scene.karts.length; i++) {
var ok = scene.karts[i];
var dist = vec3.dist(vec3.add([], t.pos, [0,1,0]), ok.pos);
if (dist < 24) {
var breakSound = nitroAudio.playSound(212, {}, 0, t);
breakSound.gainN.gain.value = 4;
for (var j=0; j<10; j++) {
scene.particles.push(new ItemShard(scene, ok, res.mdl[2]));
}
t.mode = 1;
t.time = 0;
break;
}
}
break;
case 1: //dead
if (t.time++ > 30) {
t.mode = 2;
t.time = 0;
}
break;
case 2: //respawning
if (t.time++ > 30) {
t.mode = 0;
t.time = 0;
}
break;
}
animMat = anim.setFrame(0, 0, animFrame);
animFrame = (animFrame+1)%frames;
}
function draw(view, pMatrix, gl) {
if (t.mode == 0 || t.mode == 2) {
if (t.mode == 2) nitroRender.setColMult([1, 1, 1, t.time/30]);
var mat = mat4.translate(mat4.create(), view, t.pos);
mat4.scale(mat, mat, vec3.scale([], t.scale, 16));
//res.mdl[2].draw(mat, pMatrix);
mat4.translate(mat, mat, [0, 1, 0])
gl.enable(gl.CULL_FACE); //box part
//gl.depthMask(false);
res.mdl[0].drawPoly(mat, pMatrix, 0, 1, animMat);
//gl.depthMask(true);
gl.disable(gl.CULL_FACE);
//question mark part
gl.depthRange(0, 0.99); //hack to push question mark forward in z buffer, causes a few issues with far away boxes though
res.mdl[0].drawPoly(mat, pMatrix, 0, 0, animMat);
gl.depthRange(0, 1);
if (t.mode == 2) nitroRender.setColMult([1, 1, 1, 1]);
}
}
function sndUpdate(view) {
t.soundProps.pos = vec3.transformMat4([], t.pos, view);
if (t.soundProps.lastPos != null) t.soundProps.vel = vec3.sub([], t.soundProps.pos, t.soundProps.lastPos);
else t.soundProps.vel = [0, 0, 0];
t.soundProps.lastPos = t.soundProps.pos;
t.soundProps.refDistance = 192/1024;
t.soundProps.rolloffFactor = 1;
}
function requireRes() { //scene asks what resources to load
return {mdl:[{nsbmd:"itembox.nsbmd"}, {nsbmd:"obj_shadow.nsbmd"}, {nsbmd:"itembox_hahen.nsbmd"}], other:["itembox.nsbca"]};
}
function provideRes(r) {
res = r; //...and gives them to us. :)
anim = new nitroAnimator(r.mdl[0].bmd, r.other[0]);
frames = r.other[0].animData.objectData[0].frames;
animFrame = Math.floor(Math.random()*frames);
animMat = anim.setFrame(0, 0, animFrame);
}
}

890
Code/Entities/kart.js Normal file
View File

@ -0,0 +1,890 @@
//
// kart.js
//--------------------
// Entity type for karts.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/kcl.js
//
window.Kart = function(pos, angle, speed, kartN, charN, controller, scene) {
var k = this;
var minimumMove = 0.05;
var MAXSPEED = 24;
var BOOSTTIME = 90;
var kartSoundBase = 170;
var COLBOUNCE_TIME = 20;
var COLBOUNCE_STRENGTH = 1;
var params = scene.gameRes.kartPhys.karts[kartN];
var offsets = scene.gameRes.kartOff.karts[kartN];
this.local = controller.local;
this.active = true;
this.preboost = true;
this.soundProps = {};
this.pos = pos;
this.angle = angle;
this.vel = vec3.create();
this.weight = params.weight;
this.params = params;
this.kartBounce = kartBounce;
this.speed = speed;
this.drifting = false;
this.driftMode = 0; //1 left, 2 right, 0 undecided
this.driftLanded = false; //if we haven't landed then apply a constant turn.
//powerslide info: to advance to the next mode you need to hold the same button for 10 or more frames. Mode 0 starts facing drift direction, 1 is other way, 2 is returning (mini spark), 3 is other way, 4 is returning (turbo spark)
this.driftPSTick = 0;
this.driftPSMode = 0;
this.kartTargetNormal = [0, 1, 0];
this.kartNormal = [0, 1, 0];
this.airTime = 0;
this.controller = controller;
this.driftOff = 0;
this.physicalDir = angle;
this.mat = mat4.create();
this.basis = mat4.create();
this.ylock = 0;
this.cannon = null;
this.gravity = [0, -0.17, 0]; //100% confirmed by me messing around with the gravity value in mkds. for sticky surface and loop should modify to face plane until in air
this.update = update;
this.sndUpdate = sndUpdate;
this.draw = draw;
this.drawKart = drawKart;
this.drawWheels = drawWheels;
this.drawChar = drawChar;
this.trackAttach = null; //a normal for the kart to attach to (loop)
this.boostMT = 0;
this.boostNorm = 0;
this.kartColVel = vec3.create();
this.kartColTimer = 0;
var charRes = scene.gameRes.getChar(charN);
var kartRes = scene.gameRes.getKart(kartN);
var kartPolys = [];
var kObj = kartRes.bmd.modelData.objectData[0];
for (var i=0; i<kObj.polys.objectData.length; i++) {
if (kObj.materials.names[kObj.polys.objectData[i].mat] != "kart_tire\0\0\0\0\0\0\0") kartPolys.push(i)
}
var tireRes = scene.gameRes.tireRes;
this.anim = new nitroAnimator(charRes.model.bmd, charRes.driveA);
this.charRes = charRes;
this.animMode = "drive";
this.driveAnimF = 14; //29 frames in total, 14 is mid
this.animFrame = 0; //only used for non drive anim
this.animMat = null;
this.lastInput = null;
//race statistics
this.lapNumber = 0;
this.passedKTP2 = false;
this.checkPointNumber = 0;
var nkm = scene.nkm;
var startLine = nkm.sections["KTPS"].entries[0];
var passLine = nkm.sections["KTP2"].entries[0];
var checkpoints = nkm.sections["CPOI"].entries;
var respawns = nkm.sections["CPOI"].entries;
var futureChecks = [1];
var hitGroundAnim = [ //length 13, on y axis
1.070,
1.130,
1.170,
1.190,
1.2,
1.190,
1.170,
1.130,
1.070,
1,
0.950,
0.920,
0.950,
]
var charGroundAnim = [ //length 13, on y axis
1,
1,
1,
1,
1,
1.080,
1.140,
1.180,
1.140,
1.060,
0.970,
0.960,
0.980,
]
var lastCollided = -1;
var lastBE = -1;
var lastColSounds = {};
var ylvel = 0;
var wheelTurn = 0;
var onGround;
var kartAnim = 0;
var groundAnim = -1;
var stuckTo = null;
var updateMat = true;
var drawMat = {
kart: mat4.create(),
wheels: [mat4.create(), mat4.create(), mat4.create(), mat4.create()],
character: mat4.create()
}
controller.setKart(k);
var soundMode = -1;
var sounds = { //sounds that can be simultaneous
kart: null,
drift: null,
lastTerrain: -1,
lastBE: -1,
drive: null,
boost: null,
powerslide: null,
boostSoundTrig: true, //true if a new boost sound can be played
transpose: 0
}
updateKartSound(0, {turn:0});
function recalcMat(view) {
var mat = mat4.mul([], view, k.mat);
var xscale = 1+Math.cos((kartAnim/4)*Math.PI)*0.015;
var yscale = 1+Math.cos(((kartAnim+4)/4)*Math.PI)*0.015;
if (groundAnim != -1) yscale *= hitGroundAnim[groundAnim];
mat4.translate(mat, mat, [0, -params.colRadius, 0]); //main part
var kmat = mat4.scale(drawMat.kart, mat, [16*xscale, 16*yscale, 16]);
//wheels
for (var i=0; i<4; i++) {
var scale = 16*((i<2)?offsets.frontTireSize:1);
var wmat = mat4.translate(drawMat.wheels[i], mat, [0, 0, 0]);
if (groundAnim != -1) mat4.scale(wmat, wmat, [1, hitGroundAnim[groundAnim], 1]);
mat4.translate(wmat, wmat, offsets.wheels[i]);
mat4.scale(wmat, wmat, [scale, scale, scale]);
if (i<2) mat4.rotateY(wmat, wmat, ((k.driveAnimF-14)/14)*Math.PI/6);
mat4.rotateX(wmat, wmat, wheelTurn);
}
var scale = 16;
var pos = vec3.clone(offsets.chars[charN]);
if (groundAnim != -1) pos[1] *= charGroundAnim[groundAnim];
var cmat = mat4.translate(drawMat.character, mat, vec3.scale([], pos, 16))
mat4.scale(cmat, cmat, [scale, scale, scale]);
if (k.animMode == "drive") k.animMat = k.anim.setFrame(0, 0, k.driveAnimF);
else k.animMat = k.anim.setFrame(0, 0, k.animFrame++);
updateMat = false;
}
function drawChar(view, pMatrix) {
charRes.model.draw(drawMat.character, pMatrix, k.animMat);
}
function drawKart(view, pMatrix, gl) {
if (updateMat) recalcMat(view);
//if we're in simple shadows mode, draw the kart's stencil shadow.
if (false) {
//gl.enable(gl.CULL_FACE); //culling is fun!
gl.clear(gl.STENCIL_BUFFER_BIT);
//gl.cullFace(gl.FRONT);
gl.colorMask(false, false, false, false);
gl.depthMask(false);
gl.enable(gl.STENCIL_TEST);
gl.stencilMask(0xFF);
gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
gl.stencilOp(gl.KEEP, gl.INCR, gl.KEEP);
kartRes.shadVol.draw(drawMat.kart, pMatrix, simpleMatStack);
gl.colorMask(true, true, true, true)
//gl.cullFace(gl.BACK);
gl.stencilFunc(gl.LESS , 0, 0xFF);
gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
kartRes.shadVol.draw(drawMat.kart, pMatrix, simpleMatStack);
gl.disable(gl.STENCIL_TEST);
//gl.disable(gl.CULL_FACE);
gl.depthMask(true);
}
for (var i=0; i<kartPolys.length; i++) {
kartRes.drawPoly(drawMat.kart, pMatrix, 0, kartPolys[i], simpleMatStack);
}
}
function drawWheels(view, pMatrix) {
if (updateMat) recalcMat(view);
var wheelMod = tireRes[offsets.name];
for (var i=0; i<4; i++) {
wheelMod.draw(drawMat.wheels[i], pMatrix, simpleMatStack);
}
}
function draw(view, pMatrix) {
drawWheels(view, pMatrix);
drawKart(view, pMatrix);
drawChar(view, pMatrix);
}
function update(scene) {
var lastPos = vec3.clone(k.pos);
updateMat = true;
if (groundAnim != -1) {
if (++groundAnim >= hitGroundAnim.length) groundAnim = -1;
}
onGround = (k.airTime < 5);
kartAnim = (kartAnim+1)%8;
var input = k.controller.fetchInput();
k.lastInput = input;
if (input.turn > 0.3) {
if (k.driveAnimF < 28) k.driveAnimF++;
} else if (input.turn < -0.3) {
if (k.driveAnimF > 0) k.driveAnimF--;
} else {
if (k.driveAnimF > 14) k.driveAnimF--;
else if (k.driveAnimF < 14) k.driveAnimF++;
}
//update sounds
var newSoundMode = soundMode;
if (input.accel) {
if (soundMode == 0 || soundMode == 6) newSoundMode = 2;
if (soundMode == 4) newSoundMode = 3;
} else {
if (soundMode != 0) {
if (soundMode == 2 || soundMode == 3) newSoundMode = 4;
if (newSoundMode == 4 && k.speed < 0.5) newSoundMode = 0;
}
}
if (k.boostMT+k.boostNorm > 0) {
if (k.boostNorm == BOOSTTIME || k.boostMT == params.miniTurbo) {
if (sounds.boostSoundTrig) {
if (sounds.boost != null) nitroAudio.instaKill(sounds.boost);
sounds.boost = nitroAudio.playSound(160, {}, 0, k);
sounds.boost.gainN.gain.value = 2;
sounds.boostSoundTrig = false;
}
} else {
sounds.boostSoundTrig = true;
}
} else if (sounds.boost != null) {
nitroAudio.kill(sounds.boost);
sounds.boost = null;
}
if (onGround && k.speed > 0.5) {
if (lastCollided != sounds.lastTerrain || lastBE != sounds.lastBE || sounds.drive == null) {
if (sounds.drive != null) nitroAudio.kill(sounds.drive);
if (lastColSounds.drive != null) {
sounds.drive = nitroAudio.playSound(lastColSounds.drive, {}, 0, k);
sounds.drive.gainN.gain.value = 2;
}
}
if (k.drifting && k.driftLanded) {
if (lastCollided != sounds.lastTerrain || lastBE != sounds.lastBE || sounds.drift == null) {
if (sounds.drift != null) nitroAudio.kill(sounds.drift);
if (lastColSounds.drift != null) {
sounds.drift = nitroAudio.playSound(lastColSounds.drift, {}, 0, k);
}
}
} else if (sounds.drift != null) { nitroAudio.kill(sounds.drift); sounds.drift = null; }
sounds.lastTerrain = lastCollided;
sounds.lastBE = lastBE;
} else {
if (sounds.drift != null) { nitroAudio.kill(sounds.drift); sounds.drift = null; }
if (sounds.drive != null) { nitroAudio.kill(sounds.drive); sounds.drive = null; }
}
//end sound update
if (k.preboost) {
} else if (k.cannon != null) { //when cannon is active, we fly forward at max move speed until we get to the cannon point.
var c = scene.nkm.sections["KTPC"].entries[k.cannon];
var mat = mat4.create();
mat4.rotateY(mat, mat, c.angle[1]*(Math.PI/180));
mat4.rotateX(mat, mat, c.angle[0]*(-Math.PI/180));
var forward = [0, 0, 1];
var up = [0, 1, 0];
k.vel = vec3.scale([], vec3.transformMat4(forward, forward, mat), MAXSPEED);
k.speed = MAXSPEED;
vec3.add(k.pos, k.pos, k.vel);
k.physicalDir = (180-c.angle[1])*(Math.PI/180);
k.angle = k.physicalDir;
k.kartTargetNormal = vec3.transformMat4(up, up, mat);
var planeConst = -vec3.dot(c.pos, forward);
var cannonDist = vec3.dot(k.pos, forward) + planeConst;
if (cannonDist > 0) k.cannon = null;
} else { //default kart mode
var groundEffect = 0;
if (lastCollided != -1) {
groundEffect = MKDS_COLTYPE.PHYS_MAP[lastCollided];
if (groundEffect == null) groundEffect = 0;
}
var effect = params.colParam[groundEffect];
var top = params.topSpeed*effect.topSpeedMul; //if you let go of accel, drift ends anyway, so always accel in drift.
var boosting = (k.boostNorm + k.boostMT)>0;
if (boosting) {
var top2
if (k.boostNorm>0){
top2 = params.topSpeed*1.3;
k.boostNorm--;
} else {
top2 = params.topSpeed*((effect.topSpeedMul >= 1)?1.3:effect.topSpeedMul);
}
if (k.boostMT>0) {
k.boostMT--;
}
if (k.speed <= top2) {
k.speed += 1;
if (k.speed > top2) k.speed = top2;
} else {
k.speed *= 0.95;
}
}
//kart controls
if (k.drifting) {
if ((onGround) && !(input.accel && input.drift && (k.speed > 2 || !k.driftLanded))) {
//end drift, execute miniturbo
k.drifting = false;
if (sounds.powerslide != null) {
nitroAudio.instaKill(sounds.powerslide);
sounds.powerslide = null;
}
if (k.driftPSMode == 3) {
k.boostMT = params.miniTurbo;
}
k.driftPSMode = 0;
k.driftPSTick = 0;
}
if (k.driftMode == 0) {
if (input.turn > 0.30) {
k.driftMode = 2;
} else if (input.turn < -0.30) {
k.driftMode = 1;
}
} else {
if (k.driftLanded) {
var change = (((k.driftMode-1.5)*Math.PI/1.5)-k.driftOff)*0.05;
k.driftOff += change;
k.physicalDir -= change;
}
//if we're above the initial y position, add a constant turn with a period of 180 frames.
if (!k.driftLanded && k.ylock>=0) {
k.physicalDir += (Math.PI*2/180)*(k.driftMode*2-3);
}
}
if (onGround) {
if (!k.driftLanded) {
if (k.driftMode == 0) k.drifting = false;
else {
k.driftPSMode = 0;
k.driftPSTick = 0;
k.driftLanded = true;
}
}
if (k.drifting) {
if (!boosting) {
if (k.speed <= top) {
k.speed += (k.speed/top > params.driftAccelSwitch)?params.driftAccel2:params.driftAccel1;
if (k.speed > top) k.speed = top;
} else {
k.speed *= 0.95;
}
}
var turn = ((k.driftMode == 1)?(input.turn-1):(input.turn+1))/2;
k.physicalDir += params.driftTurnRate*turn+((k.driftMode == 1)?-1:1)*(50/32768)*Math.PI; //what is this mystery number i hear you ask? well my friend, this is the turn rate for outward drift.
//miniturbo code
if (input.turn != 0) {
var inward = ((input.turn>0) == k.driftMode-1); //if we're turning
switch (k.driftPSMode) {
case 0: //dpad away from direction for 10 frames
if (!inward) k.driftPSTick++;
else if (k.driftPSTick > 9) {
k.driftPSMode++;
k.driftPSTick = 1;
//play blue spark sound
var blue = nitroAudio.playSound(210, {}, 0, k);
blue.gainN.gain.value = 2;
} else k.driftPSTick = 0;
break;
case 1: //dpad toward direction for 10 frames
if (inward) k.driftPSTick++;
else if (k.driftPSTick > 9) {
k.driftPSMode++;
k.driftPSTick = 1;
} else k.driftPSTick = 0;
break;
case 2: //dpad away from direction for 10 frames
if (!inward) k.driftPSTick++;
else if (k.driftPSTick > 9) {
k.driftPSMode++;
k.driftPSTick = 1;
//play red sparks sound, full MT!
sounds.powerslide = nitroAudio.playSound(209, {}, 0, k);
sounds.powerslide.gainN.gain.value = 2;
} else k.driftPSTick = 0;
break;
case 3: //turbo charged
break;
}
}
}
}
}
if (!k.drifting) {
if (onGround) {
var effect = params.colParam[groundEffect];
if (!boosting) {
if (input.accel) {
if (k.speed <= top) {
k.speed += (k.speed/top > params.accelSwitch)?params.accel2:params.accel1;
if (k.speed > top) k.speed = top;
} else {
k.speed *= 0.95;
}
} else {
k.speed *= params.decel;
}
}
if ((input.accel && k.speed >= 0) || (k.speed > 0.1)) {
k.physicalDir += params.turnRate*input.turn;
} else if ( k.speed < -0.1) {
k.physicalDir -= params.turnRate*input.turn;
}
if (input.drift) {
ylvel = 1.25;
k.vel[1] += 1.25;
k.airTime = 4;
k.drifting = true;
k.driftLanded = false;
k.driftMode = 0;
k.ylock = 0;
var boing = nitroAudio.playSound(207, {transpose: -4}, 0, k);
boing.gainN.gain.value = 2;
}
} else {
if (input.drift) {
ylvel = 0;
k.drifting = true;
k.driftLanded = false;
k.driftMode = 0;
k.ylock = -0.001;
}
}
}
k.physicalDir = fixDir(k.physicalDir);
if (k.driftOff != 0 && (!k.drifting || !k.driftLanded)) {
if (k.driftOff > 0) {
k.physicalDir += params.driftOffRestore;
k.driftOff -= params.driftOffRestore;
if (k.driftOff < 0) k.driftOff = 0;
} else {
k.physicalDir -= params.driftOffRestore;
k.driftOff += params.driftOffRestore;
if (k.driftOff > 0) k.driftOff = 0;
}
}
checkKartCollision(scene);
if (!onGround) {
this.kartTargetNormal = [0, 1, 0];
vec3.add(k.vel, k.vel, k.gravity)
if (k.ylock >= 0) {
ylvel += k.gravity[1];
k.ylock += ylvel;
}
if (k.kartColTimer == COLBOUNCE_TIME) {
vec3.add(k.vel, k.vel, k.kartColVel);
}
} else {
k.angle += dirDiff(k.physicalDir, k.angle)*effect.handling/2;
k.angle = fixDir(k.physicalDir);
k.vel[1] += k.gravity[1];
k.vel = [Math.sin(k.angle)*k.speed, k.vel[1], -Math.cos(k.angle)*k.speed]
if (k.kartColTimer > 0) {
vec3.add(k.vel, k.vel, vec3.scale([], k.kartColVel, k.kartColTimer/10))
}
}
if (k.kartColTimer > 0) k.kartColTimer--;
wheelTurn += k.speed/16;
wheelTurn = fixDir(wheelTurn);
k.airTime++;
//end kart controls
//move kart on moving platforms (no collision, will be corrected by next step)
if (stuckTo != null) {
if (stuckTo.moveWith != null) stuckTo.moveWith(k);
stuckTo = null;
}
//move kart.
var steps = 0;
var remainingT = 1;
var velSeg = vec3.clone(k.vel);
var posSeg = vec3.clone(k.pos);
var ignoreList = [];
while (steps++ < 10 && remainingT > 0.01) {
var result = lsc.sweepEllipse(posSeg, velSeg, scene, [params.colRadius, params.colRadius, params.colRadius], ignoreList);
if (result != null) {
colResponse(posSeg, velSeg, result, ignoreList)
remainingT -= result.t;
if (remainingT > 0.01) {
velSeg = vec3.scale(vec3.create(), k.vel, remainingT);
}
} else {
vec3.add(posSeg, posSeg, velSeg);
remainingT = 0;
}
}
k.pos = posSeg;
}
//interpolate visual normal roughly to target
var rate = onGround?0.15:0.025;
k.kartNormal[0] += (k.kartTargetNormal[0]-k.kartNormal[0])*rate;
k.kartNormal[1] += (k.kartTargetNormal[1]-k.kartNormal[1])*rate;
k.kartNormal[2] += (k.kartTargetNormal[2]-k.kartNormal[2])*rate;
vec3.normalize(k.kartNormal, k.kartNormal);
k.basis = buildBasis();
var mat = mat4.create();
mat4.translate(mat, mat, k.pos);
k.mat = mat4.mul(mat, mat, k.basis);
if (input.item) {
scene.items.addItem(0, scene.karts.indexOf(k), {})
}
updateKartSound(newSoundMode, input);
positionChanged(lastPos, k.pos);
}
function genFutureChecks() {
//all future points that
var chosen = {}
var current = checkpoints[k.checkPointNumber];
var expectedSection = current.nextSection;
futureChecks = [];
for (var i=k.checkPointNumber+1; i<checkpoints.length; i++) {
var check = checkpoints[i];
if (expectedSection != -1 && check.currentSection != expectedSection) continue;
if (chosen[check.currentSection] != true) {
futureChecks.push(i);
chosen[check.currentSection] = true;
}
}
}
function positionChanged(oldPos, pos) {
//crossed into new checkpoint?
for (var i=0; i<futureChecks.length; i++) {
var check = checkpoints[futureChecks[i]];
var distOld = vec2.sub([], [check.x1, check.z1], [oldPos[0], oldPos[2]]);
var dist = vec2.sub([], [check.x1, check.z1], [pos[0], pos[2]]);
var dot = vec2.dot(dist, [check.sinus, check.cosinus]);
var dotOld = vec2.dot(distOld, [check.sinus, check.cosinus]);
var lineCheck = vec2.sub([], [check.x1, check.z1], [check.x2, check.z2]);
var lineDot = vec2.dot(dist, lineCheck);
if (lineDot > 0 && lineDot < vec2.sqrLen(lineCheck) && dot < 0 && dotOld >= 0) {
k.checkPointNumber = futureChecks[i];
genFutureChecks();
break;
}
}
if (!k.passedKTP2 && forwardCrossedKTP(passLine, oldPos, pos)) k.passedKTP2 = true;
if (k.passedKTP2 && futureChecks.length == 0) {
//we can finish the lap
if (forwardCrossedKTP(startLine, oldPos, pos)) {
k.lapNumber++;
k.checkPointNumber = 0;
k.passedKTP2 = 0;
scene.lapAdvance(k);
}
}
}
function forwardCrossedKTP(ktp, oldPos, pos) {
var distOld = vec2.sub([], [ktp.pos[0], ktp.pos[2]], [oldPos[0], oldPos[2]]);
var dist = vec2.sub([], [ktp.pos[0], ktp.pos[2]], [pos[0], pos[2]]);
var ang = (ktp.angle[1]/180)*Math.PI;
var sinus = Math.sin(ang);
var cosinus = Math.cos(ang);
var dot = vec2.dot(dist, [sinus, cosinus]);
var dotOld = vec2.dot(distOld, [sinus, cosinus]);
return (dot < 0 && dotOld >= 0);
}
function checkKartCollision(scene) { //check collision with other karts. Really simple.
for (var i=0; i<scene.karts.length; i++) {
var ok = scene.karts[i];
if (!ok.active) continue;
if (k != ok) {
var dist = vec3.dist(k.pos, ok.pos);
if (dist < 16) {
kartBounce(ok);
ok.kartBounce(k);
}
}
}
}
function kartBounce(ok) {
k.kartColTimer = COLBOUNCE_TIME;
var weightMul = COLBOUNCE_STRENGTH*(1+(ok.weight-k.weight))*((ok.boostNorm>0 || ok.boostMT>0)?2:1)*((k.boostNorm>0 || k.boostMT>0)?0.5:1);
//as well as side bounce also add velocity difference if other vel > mine.
vec3.sub(k.kartColVel, k.pos, ok.pos);
k.kartColVel[1] = 0;
vec3.normalize(k.kartColVel, k.kartColVel);
vec3.scale(k.kartColVel, k.kartColVel, weightMul);
if (vec3.length(k.vel) < vec3.length(ok.vel)) vec3.add(k.kartColVel, k.kartColVel, vec3.sub([], ok.vel, k.vel));
k.kartColVel[1] = 0;
}
function fixDir(dir) {
return posMod(dir, Math.PI*2);
}
function dirDiff(dir1, dir2) {
var d = fixDir(dir1-dir2);
return (d>Math.PI)?(-2*Math.PI+d):d;
}
function posMod(i, n) {
return (i % n + n) % n;
}
function updateKartSound(mode, input) {
var turn = (onGround && !k.drifting)?(1-Math.abs(input.turn)/11):1;
var transpose = (mode == 0)?0:(22*turn*k.speed/params.topSpeed);
sounds.transpose += (transpose-sounds.transpose)/15;
if (mode != soundMode) {
soundMode = mode;
if (sounds.kart != null) nitroAudio.instaKill(sounds.kart);
sounds.kart = nitroAudio.playSound(kartSoundBase+soundMode, {transpose:sounds.transpose, volume:1}, 0, k);
//if (mode == 3) sounds.kart.gainN.gain.value = 0.5;
} else {
sounds.kart.seq.setTranspose(sounds.transpose);
}
}
function buildBasis() {
//order y, x, z
var dir = k.physicalDir+k.driftOff+(Math.sin((COLBOUNCE_TIME-k.kartColTimer)/3)*(Math.PI/6)*(k.kartColTimer/COLBOUNCE_TIME));
var basis = gramShmidt(k.kartNormal, [Math.cos(dir), 0, Math.sin(dir)], [Math.sin(dir), 0, -Math.cos(dir)]);
var temp = basis[0];
basis[0] = basis[1];
basis[1] = temp; //todo: cleanup
return [
basis[0][0], basis[0][1], basis[0][2], 0,
basis[1][0], basis[1][1], basis[1][2], 0,
basis[2][0], basis[2][1], basis[2][2], 0,
0, 0, 0, 1
]
}
function sndUpdate(view) {
k.soundProps.pos = vec3.transformMat4([], k.pos, view);
if (k.soundProps.lastPos != null) k.soundProps.vel = vec3.sub([], k.soundProps.pos, k.soundProps.lastPos);
else k.soundProps.vel = [0, 0, 0];
k.soundProps.lastPos = k.soundProps.pos;
k.soundProps.refDistance = 192/1024;
k.soundProps.rolloffFactor = 1;
var calcVol = (k.soundProps.refDistance / (k.soundProps.refDistance + k.soundProps.rolloffFactor * (Math.sqrt(vec3.dot(k.soundProps.pos, k.soundProps.pos)) - k.soundProps.refDistance)));
}
function gramShmidt(v1, v2, v3) {
var u1 = v1;
var u2 = vec3.sub([0, 0, 0], v2, project(u1, v2));
var u3 = vec3.sub([0, 0, 0], vec3.sub([0, 0, 0], v3, project(u1, v3)), project(u2, v3));
return [vec3.normalize(u1, u1), vec3.normalize(u2, u2), vec3.normalize(u3, u3)]
}
function colSound(collision, effect) {
if (MKDS_COLTYPE.SOUNDMAP[collision] == null) return {};
return MKDS_COLTYPE.SOUNDMAP[collision][effect] || {};
}
function project(u, v) {
return vec3.scale([], u, (vec3.dot(u, v)/vec3.dot(u, u)))
}
function colResponse(pos, pvel, dat, ignoreList) {
var plane = dat.plane;
var colType = (plane.CollisionType>>8)&31;
var colBE = (plane.CollisionType>>5)&7;
lastCollided = colType;
lastBE = colBE;
lastColSounds = colSound(lastCollided, colBE);
var n = vec3.normalize([], dat.normal);
var gravS = Math.sqrt(vec3.dot(k.gravity, k.gravity));
var angle = Math.acos(vec3.dot(vec3.scale(vec3.create(), k.gravity, -1/gravS), n));
var adjustPos = true;
if (MKDS_COLTYPE.GROUP_WALL.indexOf(colType) != -1) { //wall
//sliding plane, except normal is transformed to be entirely on the xz plane (cannot ride on top of wall, treated as vertical)
var xz = Math.sqrt(n[0]*n[0]+n[2]*n[2])
var adjN = [n[0]/xz, 0, n[2]/xz]
var proj = vec3.dot(k.vel, adjN);
if (proj < -1) {
if (lastColSounds.hit != null) nitroAudio.playSound(lastColSounds.hit, {volume:1}, 0, k)
}
vec3.sub(k.vel, k.vel, vec3.scale(vec3.create(), adjN, proj));
//convert back to angle + speed to keep change to kart vel
var v = k.vel;
k.speed = Math.sqrt(v[0]*v[0]+v[2]*v[2]);
k.angle = Math.atan2(v[0], -v[2]);
} else if (MKDS_COLTYPE.GROUP_ROAD.indexOf(colType) != -1) {
//sliding plane
if (MKDS_COLTYPE.GROUP_BOOST.indexOf(colType) != -1) {
k.boostNorm = BOOSTTIME;
}
if (k.vel[1] > 0) k.vel[1] = 0;
var proj = vec3.dot(k.vel, n);
if (proj < -4 && k.vel[1] < -2) { proj -= 1.5; }
vec3.sub(k.vel, k.vel, vec3.scale(vec3.create(), n, proj));
k.kartTargetNormal = dat.pNormal;
if (!onGround) {
console.log("ground: "+colType+", "+colBE);
groundAnim = 0;
if (lastColSounds.land != null) nitroAudio.playSound(lastColSounds.land, {volume:1}, 0, k)
}
k.airTime = 0;
stuckTo = dat.object;
} else if (colType == MKDS_COLTYPE.CANNON) {
//cannon!!
k.cannon = colBE;
} else {
adjustPos = false;
ignoreList.push(plane);
}
//vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); //move away from plane slightly
if (adjustPos) { //move back from plane slightly
//vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove));
vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t));
vec3.add(pos, vec3.scale([], n, params.colRadius+minimumMove), dat.colPoint);
/*if (dat.embedded) {
} else {
var velMag = Math.sqrt(vec3.dot(pvel, pvel));
if (velMag*dat.t > minimumMove) {
vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t-(minimumMove/velMag)));
} else {
//do not move, too close
}
}*/
} else {
vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t));
}
}
}

View File

@ -0,0 +1,119 @@
//
// objDatabase.js
//--------------------
// Links object IDs to specific entity types. Must be initialized after all js files are loaded!
// by RHY3756547
//
// includes:
// entities/*
//
window.objDatabase = new (function(){
this.init = function() {
this.idToType = [];
var t = this.idToType;
t[0x0001] = ObjWater;
t[0x0003] = ObjWater;
t[0x0006] = ObjWater;
t[0x0008] = ObjSoundMaker;
t[0x0009] = ObjWater;
t[0x000C] = ObjWater;
t[0x0065] = ItemBox;
t[0x00CA] = ObjRoutePlatform;
t[0x00CB] = ObjGear;
t[0x00CE] = ObjGear; //test_cylinder, tick tock clock end
t[0x00D0] = ObjRotaryRoom;
t[0x00D1] = ObjGear; //rotary bridge
t[0x012D] = ObjDecor;
t[0x012E] = ObjDecor;
t[0x012F] = ObjDecor;
t[0x0130] = ObjDecor;
t[0x0131] = ObjDecor;
t[0x0132] = ObjDecor;
t[0x0133] = ObjDecor;
t[0x0134] = ObjDecor;
t[0x0135] = ObjDecor;
t[0x0138] = ObjDecor;
t[0x0139] = ObjDecor;
t[0x013C] = ObjDecor; //DEBUG: cheep cheep (routed)
t[0x013D] = ObjDecor; //DEBUG: ghost
t[0x013A] = ObjDecor; //figure 8 tree
t[0x013C] = ObjDecor;
t[0x013F] = ObjDecor;
t[0x0140] = ObjDecor;
t[0x0142] = ObjDecor; //more trees
t[0x0145] = ObjDecor;
t[0x0146] = ObjDecor;
t[0x0148] = ObjDecor;
t[0x0149] = ObjDecor; //yoshi falls egg
t[0x014B] = ObjDecor;
t[0x014C] = ObjDecor;
t[0x014D] = ObjDecor;
t[0x014E] = ObjDecor;
t[0x014F] = ObjDecor;
t[0x0150] = ObjDecor;
t[0x0151] = ObjDecor;
t[0x0152] = ObjDecor;
t[0x0153] = ObjDecor;
t[0x0154] = ObjDecor; //rainbow star
t[0x0155] = ObjDecor;
t[0x0156] = ObjDecor;
t[0x0157] = ObjDecor;
t[0x019C] = ObjTruck;
t[0x019A] = ObjCar;
t[0x0195] = ObjBus;
t[0x00CC] = ObjDecor; //DEBUG: pianta bridge
t[0x000D] = ObjDecor; //DEBUG: puddle
t[0x0158] = ObjDecor; //DEBUG: airship (routed)
//DEBUG ENEMIES AS DECOR: switch as implemented:
t[0x0191] = ObjDecor;
t[0x0192] = ObjDecor;
t[0x0193] = ObjDecor;
t[0x0196] = ObjDecor;
t[0x0198] = ObjDecor;
t[0x0199] = ObjDecor;
//truck
t[0x019B] = ObjDecor;
t[0x019D] = ObjDecor;
t[0x019E] = ObjDecor;
t[0x01A0] = ObjDecor;
t[0x01A1] = ObjDecor;
t[0x01A3] = ObjDecor;
t[0x01A4] = ObjDecor;
t[0x01A5] = ObjDecor;
t[0x01A6] = ObjDecor;
t[0x01A7] = ObjDecor;
t[0x01A8] = ObjDecor;
t[0x01A9] = ObjDecor;
t[0x01AA] = ObjDecor;
t[0x01AC] = ObjDecor;
t[0x01AD] = ObjDecor;
//rotating fireballs
t[0x01B0] = ObjDecor;
t[0x01B1] = ObjDecor;
t[0x01B2] = ObjDecor;
t[0x01B3] = ObjDecor;
t[0x01B4] = ObjDecor;
t[0x01B5] = ObjDecor;
}
})();

View File

@ -0,0 +1,161 @@
//
// rotatingGear.js
//--------------------
// Provides rotating gear objects for tick tock clock
// by RHY3756547
//
// includes:
// render stuff idk
//
window.ObjGear = function(obji, scene) {
var obji = obji;
var res = [];
var t = this;
t.collidable = true;
t.colMode = 0;
t.colRad = 512;
t.getCollision = getCollision;
t.moveWith = moveWith;
t.pos = vec3.clone(obji.pos);
//t.angle = vec3.clone(obji.angle);
t.scale = vec3.clone(obji.scale);
t.requireRes = requireRes;
t.provideRes = provideRes;
t.update = update;
t.draw = draw;
t.speed = (obji.setting1&0xFFFF)/8192;
t.duration = obji.setting1>>16;
t.rampDur = obji.setting2&0xFFFF;
t.statDur = obji.setting2>>16;
t.wB1 = obji.setting3&0xFFFF; //ONE of these flips direction, the other makes the gear use the black model. Not sure which is which, but for tick tock clock there is no need to get this right.
t.wB2 = obji.setting3>>16;
t.time = 0;
t.mode = 0; //0=rampup, 1=normal, 2=rampdown, 3=stationary
t.angle = 0;
t.dir = (t.wB1 == 0)
var dirVel = 0;
var prevMat;
var curMat;
setMat();
prevMat = curMat;
function setMat() {
prevMat = curMat;
var mat = mat4.create();
mat4.translate(mat, mat, t.pos);
mat4.scale(mat, mat, vec3.scale([], t.scale, 16));
mat4.rotateY(mat, mat, obji.angle[1]*(Math.PI/180));
mat4.rotateX(mat, mat, obji.angle[0]*(Math.PI/180));
mat4.rotateY(mat, mat, t.angle);
curMat = mat;
}
function update(scene) {
t.time++;
switch (t.mode) {
case 0:
dirVel = t.speed*(t.time/t.rampDur)*((t.dir)?-1:1);
if (t.time > t.rampDur) {
t.time = 0; t.mode = 1;
}
break;
case 1:
dirVel = t.speed*((t.dir)?-1:1);
if (t.time > t.duration) {
t.time = 0; t.mode = 2;
}
break;
case 2:
dirVel = t.speed*(1-t.time/t.rampDur)*((t.dir)?-1:1);
if (t.time > t.rampDur) {
t.time = 0; t.mode = 3; t.dir = !t.dir;
}
break;
case 3:
dirVel = 0;
if (t.time > t.statDur) {
t.time = 0; t.mode = 0;
}
break;
}
t.angle += dirVel;
setMat();
}
function draw(view, pMatrix) {
var mat = mat4.translate(mat4.create(), view, t.pos);
mat4.scale(mat, mat, vec3.scale([], t.scale, 16));
mat4.rotateY(mat, mat, obji.angle[1]*(Math.PI/180));
mat4.rotateX(mat, mat, obji.angle[0]*(Math.PI/180));
mat4.rotateY(mat, mat, t.angle);
res.mdl[t.wB1].draw(mat, pMatrix);
}
function requireRes() { //scene asks what resources to load
switch (obji.ID) {
case 0x00CB:
return {mdl:[{nsbmd:"gear_white.nsbmd"}, {nsbmd:"gear_black.nsbmd"}]};
case 0x00CE:
return {mdl:[{nsbmd:"test_cylinder.nsbmd"}]};
case 0x00D1:
t.colRad = 4096;
return {mdl:[{nsbmd:"rotary_bridge.nsbmd"}]};
}
}
function provideRes(r) {
res = r; //...and gives them to us. :)
}
function getCollision() {
var obj = {};
var inf = res.mdl[0].getCollisionModel(0, 0);
obj.tris = inf.dat;
var mat = mat4.translate([], mat4.create(), t.pos);
mat4.scale(mat, mat, vec3.mul([], [16*inf.scale, 16*inf.scale, 16*inf.scale], t.scale));
mat4.rotateY(mat, mat, obji.angle[1]*(Math.PI/180));
mat4.rotateX(mat, mat, obji.angle[0]*(Math.PI/180));
mat4.rotateY(mat, mat, t.angle);
obj.mat = mat;
return obj;
}
function moveWith(obj) { //used for collidable objects that move.
//the most general way to move something with an object is to multiply its position by the inverse mv matrix of that object, and then the new mv matrix.
vec3.transformMat4(obj.pos, obj.pos, mat4.invert([], prevMat))
vec3.transformMat4(obj.pos, obj.pos, curMat)
/*var p = vec3.sub([], obj.pos, t.pos);
if (obji.ID == 0x00D1) { //todo: maybe something more general
vec3.transformMat4(p, p, mat4.rotateX([], mat4.create(), dirVel));
vec3.add(obj.pos, t.pos, p);
} else {
vec3.transformMat4(p, p, mat4.rotateY([], mat4.create(), dirVel));
vec3.add(obj.pos, t.pos, p);
obj.physicalDir -= dirVel;
}*/
}
}

118
Code/Entities/shell.js Normal file
View File

@ -0,0 +1,118 @@
//
// shell.js
//--------------------
// Entity type for shells. (green)
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/kcl.js
//
window.GreenShell = function(scene, owner, time, itemID, cliID, params) {
var t = this;
var minimumMove = 0.01;
this.pos = vec3.transformMat4([], [0, (-owner.params.colRadius)+1, 16], owner.mat);
this.vel = vec3.create();
this.gravity = [0, -0.17, 0]; //100% confirmed by me messing around with the gravity value in mkds
this.angle = owner.angle;
this.speed = 10;
this.yvel = 0;
this.update = update;
this.draw = draw;
function update(scene) {
t.vel = [Math.sin(t.angle)*t.speed, t.yvel, -Math.cos(t.angle)*t.speed]
vec3.add(t.vel, t.vel, t.gravity);
//simple point move.
var steps = 0;
var remainingT = 1;
var velSeg = vec3.clone(t.vel);
var posSeg = vec3.clone(t.pos);
var ignoreList = [];
while (steps++ < 10 && remainingT > 0.01) {
var result = lsc.raycast(posSeg, velSeg, scene.kcl, 0.05, ignoreList);
if (result != null) {
colResponse(posSeg, velSeg, result, ignoreList)
remainingT -= result.t;
if (remainingT > 0.01) {
velSeg = vec3.scale(vec3.create(), t.vel, remainingT);
}
} else {
vec3.add(posSeg, posSeg, velSeg);
remainingT = 0;
}
}
t.pos = posSeg;
t.yvel = t.vel[1];
}
function draw(mvMatrix, pMatrix) {
var mat = mat4.translate(mat4.create(), mvMatrix, vec3.add(vec3.create(), t.pos, [0, 3, 0]));
spritify(mat);
mat4.scale(mat, mat, [16, 16, 16]);
scene.gameRes.items.koura_g.draw(mat, pMatrix);
}
var spritify = function(mat, scale) {
var scale = (scale == null)?Math.sqrt(mat[0]*mat[0]+mat[1]*mat[1]+mat[2]*mat[2]):scale;
mat[0]=scale; mat[1]=0; mat[2]=0;
mat[4]=0; mat[5]=scale; mat[6]=0;
mat[8]=0; mat[9]=0; mat[10]=scale;
}
function colResponse(pos, pvel, dat, ignoreList) {
var plane = dat.plane;
var colType = (plane.CollisionType>>8)&31;
vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t));
var n = dat.normal;
vec3.normalize(n, n);
var gravS = Math.sqrt(vec3.dot(t.gravity, t.gravity));
var angle = Math.acos(vec3.dot(vec3.scale(vec3.create(), t.gravity, -1/gravS), n));
var adjustPos = true
if (MKDS_COLTYPE.GROUP_WALL.indexOf(colType) != -1) { //wall
//shell reflection code - slide y vel across plane, bounce on xz
vec3.add(t.vel, vec3.scale(vec3.create(), n, -2*(vec3.dot(t.vel, n)/vec3.dot(n,n))), t.vel);
t.vel[1] = 0;
var v = t.vel;
t.angle = Math.atan2(v[0], -v[2]);
} else if (MKDS_COLTYPE.GROUP_ROAD.indexOf(colType) != -1) {
//sliding plane
var proj = vec3.dot(t.vel, n);
vec3.sub(t.vel, t.vel, vec3.scale(vec3.create(), n, proj));
} else {
adjustPos = false;
ignoreList.push(plane);
}
var rVelMag = Math.sqrt(vec3.dot(t.vel, t.vel));
vec3.scale(t.vel, t.vel, t.speed/rVelMag); //force speed to shell speed for green shells.
//vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); //move away from plane slightly
if (adjustPos) { //move back from plane slightly
vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove));
/*
var velMag = Math.sqrt(vec3.dot(pvel, pvel));
if (velMag*dat.t > minimumMove) {
vec3.sub(pos, pos, vec3.scale(vec3.create(), pvel, minimumMove/velMag)); //move back slightly after moving
} else {
vec3.sub(pos, pos, vec3.scale(vec3.create(), pvel, dat.t)); //if we're already too close undo the movement.
}
*/
}
}
}

View File

@ -0,0 +1,77 @@
//
// soundMaker.js
//--------------------
// Provides env sound object, such as crowd for figure 8
// by RHY3756547
//
//0008
window.ObjSoundMaker = function(obji, scene) {
var obji = obji;
var t = this;
t.pos = vec3.clone(obji.pos);
t.soundProps = {};
t.sndUpdate = sndUpdate;
t.requireRes = requireRes;
t.provideRes = provideRes;
t.update = update;
t.draw = draw;
var mat = mat4.create();
var frame = 0;
var sound = null;
var sN = 0;
var threshold = 0.2;
var gain = 1;
switch (obji.ID) {
case 0x0008:
sN = 259;
gain = 2;
threshold = 0.2;
break;
}
function draw(view, pMatrix) {
}
function update() {
}
function sndUpdate(view) {
t.soundProps.pos = vec3.transformMat4([], t.pos, view);
t.soundProps.pos = [0, 0, Math.sqrt(vec3.dot(t.soundProps.pos, t.soundProps.pos))]
//if (t.soundProps.lastPos != null) t.soundProps.vel = vec3.sub([], t.soundProps.pos, t.soundProps.lastPos);
//else t.soundProps.vel = [0, 0, 0];
//t.soundProps.lastPos = t.soundProps.pos;
t.soundProps.refDistance = 1024/1024;
//t.soundProps.rolloffFactor = 1;
var calcVol = (t.soundProps.refDistance / (t.soundProps.refDistance + t.soundProps.rolloffFactor * (t.soundProps.pos[2] - t.soundProps.refDistance)));
if (calcVol<threshold) {
if (sound != null) {
nitroAudio.instaKill(sound);
sound = null;
}
} else {
if (sound == null) {
sound = nitroAudio.playSound(sN, {}, 0, t);
sound.gainN.gain.value = gain;
}
}
}
function requireRes() {
return {mdl: []};
}
function provideRes(r) { }
}

View File

@ -0,0 +1,94 @@
//
// trafficCar.js
//--------------------
// Provides multiple types of traffic.
// by RHY3756547
//
// includes:
// render stuff idk
//
window.ObjTruck = function(obji, scene) {
var obji = obji;
var res = [];
var t = this;
t.pos = vec3.clone(obji.pos);
//t.angle = vec3.clone(obji.angle);
t.scale = vec3.clone(obji.scale);
t.requireRes = requireRes;
t.provideRes = provideRes;
t.update = update;
t.draw = draw;
t.route = scene.paths[obji.routeID];
t.routeSpeed = (obji.setting1>>16)/100;
t.routePos = (obji.setting1&0xFFFF)%t.route.length;
t.nextNode = t.route[t.routePos];
t.prevPos = t.pos;
t.elapsedTime = 0;
var facingNormal = [0, 1, 0];
var curNormal = [0, 1, 0];
var floorNormal = [0, 1, 0];
function update(scene) {
//simple behaviour, just follow the path! piece of cake.
t.elapsedTime += t.routeSpeed;
t.pos = vec3.lerp([], t.prevPos, t.nextNode.pos, t.elapsedTime/t.nextNode.duration);
if (t.elapsedTime >= t.nextNode.duration) {
t.elapsedTime = 0;
t.prevPos = t.nextNode.pos;
t.routePos = (t.routePos+1)%t.route.length;
t.nextNode = t.route[t.routePos];
}
facingNormal = vec3.sub([], t.prevPos, t.nextNode.pos)
vec3.normalize(facingNormal, facingNormal);
var rate = 0.025
curNormal[0] += (facingNormal[0]-curNormal[0])*rate;
curNormal[1] += (facingNormal[1]-curNormal[1])*rate;
curNormal[2] += (facingNormal[2]-curNormal[2])*rate;
vec3.normalize(curNormal, curNormal);
var spos = vec3.clone(t.pos);
spos[1] += 32;
var result = lsc.raycast(spos, [0, -100, 0], scene.kcl, 0.05, []);
if (result != null) {
floorNormal = result.normal;
} else {
floorNormal = [0,1,0];
}
}
function draw(view, pMatrix) {
var mat = mat4.translate(mat4.create(), view, t.pos);
mat4.scale(mat, mat, vec3.scale([], t.scale, 16));
mat4.mul(mat, mat, mat4.invert([], mat4.lookAt([], [0, 0, 0], curNormal, floorNormal)));
res.mdl[0].draw(mat, pMatrix);
}
function requireRes() { //scene asks what resources to load
switch (obji.ID) {
case 0x019A:
return {mdl:[{nsbmd:"car_a.nsbmd"}]}; //one model, car
case 0x019C:
return {mdl:[{nsbmd:"truck_a.nsbmd"}]}; //one model, truck
case 0x0195:
return {mdl:[{nsbmd:"bus_a.nsbmd"}]}; //one model, bus
}
}
function provideRes(r) {
res = r; //...and gives them to us. :)
}
}
window.ObjCar = ObjTruck;
window.ObjBus = ObjTruck;

86
Code/Entities/water.js Normal file
View File

@ -0,0 +1,86 @@
//
// water.js
//--------------------
// Provides multiple types of traffic.
// by RHY3756547
//
// includes:
// render stuff idk
//
window.ObjWater = function(obji, scene) {
var obji = obji;
var res = [];
var t = this;
t.pos = vec3.clone(obji.pos);
//t.angle = vec3.clone(obji.angle);
t.scale = vec3.clone(obji.scale);
t.requireRes = requireRes;
t.provideRes = provideRes;
t.update = update;
t.draw = draw;
var frame = 0;
function draw(view, pMatrix) {
if (nitroRender.flagShadow) return;
var waterM = mat4.create();
gl.enable(gl.STENCIL_TEST);
gl.stencilMask(0xFF);
gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE); //when depth test passes for water lower layer, pixel is already drawn, do not cover it with the white overlay (set stencil bit)
var height = (t.pos[1])+6.144+Math.sin(frame/150)*12.288 //0.106
mat4.translate(waterM, view, [Math.sin(frame/180)*96, height-3.072, Math.cos(frame/146)*96])
nitroRender.setAlpha(0x0A/31);
res.mdl[0].drawPoly(mat4.scale([], waterM, [16, 16, 16]), pMatrix, 0, 0); //water
if (res.mdl[1] != null) {
mat4.translate(waterM, view, [-Math.sin((frame+30)/180)*96, height-3, Math.cos((frame+100)/146)*96])
nitroRender.setAlpha(0x02/31);
res.mdl[1].draw(mat4.scale([], waterM, [16, 16, 16]), pMatrix); //water white detail part. stencil should do nothing here, since it's in the same position as the above.
}
gl.stencilFunc(gl.EQUAL, 0, 0xFF);
gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
if (!obji.ID == 9) {
mat4.translate(waterM, view, [0, height, 0])
nitroRender.setAlpha(0x10/31);
res.mdl[0].drawPoly(mat4.scale([], waterM, [16, 16, 16]), pMatrix, 0, 1); //white shore wash part, water is stencil masked out
}
gl.disable(gl.STENCIL_TEST);
nitroRender.setAlpha(1);
}
function update() {
frame = (frame+1)%197100; //it's a big number but yolo... we have the technology...
}
function requireRes() { //scene asks what resources to load
switch (obji.ID) {
case 0x0001:
return {mdl:[{nsbmd:"beach_waterC.nsbmd"}, {nsbmd:"beach_waterA.nsbmd"}]};
case 0x0003:
return {mdl:[{nsbmd:"town_waterC.nsbmd"}, {nsbmd:"town_waterA.nsbmd"}]};
case 0x0006:
return {mdl:[{nsbmd:"yoshi_waterC.nsbmd"}]};
case 0x0009:
return {mdl:[{nsbmd:"hyudoro_waterC.nsbmd"}, {nsbmd:"hyudoro_waterA.nsbmd"}]};
case 0x000C:
return {mdl:[{nsbmd:"mini_stage3_waterC.nsbmd"}, {nsbmd:"mini_stage3_waterA.nsbmd"}]};
}
}
function provideRes(r) {
res = r; //...and gives them to us. :)
}
}

158
Code/Formats/.subl29.tmp Normal file
View File

@ -0,0 +1,158 @@
//
// nsbtx.js
//--------------------
// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js
//
window.nsbtx = function(input, tex0, autogen) {
var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff,
compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff,
palOffset, mainOff
var textureInfo, paletteInfo, palData, texData, colourBuffer
var thisObj = this;
var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16]
if (input != null) {
load(input, tex0, autogen);
}
this.load = load;
this.readTexWithPal = readTexWithPal;
this.scopeEval = function(code) {return eval(code)} //for debug purposes
function load(input, tex0, autogen) {
var colourBuffer = new Uint32Array(4);
var view = new DataView(input);
var header = null;
var offset = 0;
if (!tex0) { //nitro 3d header
header = nitro.readHeader(view);
if (header.stamp != "BTX0") throw "NSBTX invalid. Expected BTX0, found "+header.stamp;
if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one.";
offset = header.sectionOffsets[0];
}
mainOff = offset;
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3);
if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp;
var size = view.getUint32(offset+0x04, true);
var texDataSize = view.getUint16(offset+0x0C, true)<<8;
var texInfoOff = view.getUint16(offset+0x0E, true);
var texOffset = view.getUint16(offset+0x14, true);
var compTexSize = view.getUint16(offset+0x1C, true)<<8;
var compTexInfoOff = view.getUint16(offset+0x1E, true);
var compTexOffset = view.getUint32(offset+0x24, true);
var compTexInfoDataOff = view.getUint32(offset+0x28, true);
var palSize = view.getUint32(offset+0x30, true)<<3;
var palInfoOff = view.getUint32(offset+0x34, true);
var palOffset = view.getUint32(offset+0x38, true);
//read palletes, then textures.
palData = input.slice(mainOff + palOffset, palSize);
texData = input.slice(mainOff + texOffset, texDataSize);
paletteInfo = nitro.read3dInfo(view, palInfoOff, palInfoHandler);
textureInfo = nitro.read3dInfo(view, texInfoOff, texInfoHandler);
/*if (f) {
console.log(textureInfo.objectData.length)
for (var i=0; i<textureInfo.objectData.length; i++) {
var canvas = readTexWithPal(i, textureInfo.objectData[i].pal)
document.body.appendChild(canvas);
console.log("uh")
}
}*/
}
function readTexWithPal(textureId, palId) {
palView = new DataView(palData);
texView = new DataView(texData);
var tex = textureInfo.objectData[textureId];
var pal = paletteInfo.objectData[palId];
var bit = bitDepths[pal.format]; //todo, compressed format whatever that is
var canvas = document.createElement("canvas");
canvas.width = tex.width;
canvas.height = tex.height;
var ctx = canvas.getContext("2d");
var data = ctx.getImageData(0, 0, tex.width, tex.height);
var off = tex.texOffset
var palOff = pal.palOffset;
var total = tex.width*tex.height;
var databuf = texView.readUint8(off);
for (var i=0; i<total; i++) {
var col;
if (bitDepths == 2) {
col = readPalColour(palView, palOff, (databuf>>((i%4)*2))&3)
if (i%4 == 3) databuf = texView.readUint8(++off);
} else if (bitDepths == 4) {
if (i%2 == 0) {
col = readPalColour(palView, palOff, databuf&15)
} else {
col = readPalColour(palView, palOff, databuf>>4)
databuf = texView.readUint8(++off);
}
} else if (bitDepths == 8) {
col = readPalColour(palView, palOff, texView.readUint8(off))
off += 1;
} else if (bitDepths == 16) {
col = readPalColour(palView, palOff, texView.readUint16(off, true))
off += 2;
}
data.data.set(col, i*4);
}
return canvas;
}
function readPalColour(view, palOff, ind) {
var col = palView.getUint16(palOff+ind*2, true);
colourBuffer[0] = Math.round(((col&31)/31)*255)
colourBuffer[1] = Math.round((((col>>5)&31)/31)*255)
colourBuffer[2] = Math.round((((col>>10)&31)/31)*255)
colourBuffer[3] = Math.round((col>>15)*255)
}
function palInfoHandler(view, offset) {
var palOffset = view.getUint16(offset, true)<<3;
var unknown = view.getUint16(offset+2, true);
return {
palOffset: palOffset,
nextoff: offset+4
}
}
function texInfoHandler(view, offset) {
var texOffset = view.getUint16(offset, true)<<3;
var flags = view.getUint16(offset+2, true);
var width2 = view.getUint8(offset+4, true);
var unknown = view.getUint8(offset+5, true);
var height2 = view.getUint8(offset+6, true);
var unknown2 = view.getUint8(offset+7, true);
return {
texOffset: texOffset,
pal: (flags>>13),
format: ((flags>>10)&7),
height: ((flags>>7)&7)<<3,
width: ((flags>>4)&7)<<3,
nextoff: offset+8
}
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
}

158
Code/Formats/.subl509.tmp Normal file
View File

@ -0,0 +1,158 @@
//
// nsbtx.js
//--------------------
// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js
//
window.nsbtx = function(input, tex0, autogen) {
var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff,
compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff,
palOffset, mainOff
var textureInfo, paletteInfo, palData, texData, colourBuffer
var thisObj = this;
var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16]
if (input != null) {
load(input, tex0, autogen);
}
this.load = load;
this.readTexWithPal = readTexWithPal;
this.scopeEval = function(code) {return eval(code)} //for debug purposes
function load(input, tex0, autogen) {
var colourBuffer = new Uint32Array(4);
var view = new DataView(input);
var header = null;
var offset = 0;
if (!tex0) { //nitro 3d header
header = nitro.readHeader(view);
if (header.stamp != "BTX0") throw "NSBTX invalid. Expected BTX0, found "+header.stamp;
if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one.";
offset = header.sectionOffsets[0];
}
mainOff = offset;
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3);
if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp;
var size = view.getUint32(offset+0x04, true);
var texDataSize = view.getUint16(offset+0x0C, true)<<8;
var texInfoOff = view.getUint16(offset+0x0E, true);
var texOffset = view.getUint16(offset+0x14, true);
var compTexSize = view.getUint16(offset+0x1C, true)<<8;
var compTexInfoOff = view.getUint16(offset+0x1E, true);
var compTexOffset = view.getUint32(offset+0x24, true);
var compTexInfoDataOff = view.getUint32(offset+0x28, true);
var palSize = view.getUint32(offset+0x30, true)<<3;
var palInfoOff = view.getUint32(offset+0x34, true);
var palOffset = view.getUint32(offset+0x38, true);
//read palletes, then textures.
palData = input.slice(mainOff + palOffset, palSize);
texData = input.slice(mainOff + texOffset, texDataSize);
paletteInfo = nitro.read3dInfo(view, palInfoOff, palInfoHandler);
textureInfo = nitro.read3dInfo(view, texInfoOff, texInfoHandler);
if (autogen) {
console.log(textureInfo.objectData.length)
for (var i=0; i<textureInfo.objectData.length; i++) {
var canvas = readTexWithPal(i, textureInfo.objectData[i].pal)
document.body.appendChild(canvas);
console.log("uh")
}
}
}
function readTexWithPal(textureId, palId) {
palView = new DataView(palData);
texView = new DataView(texData);
var tex = textureInfo.objectData[textureId];
var pal = paletteInfo.objectData[palId];
var bit = bitDepths[pal.format]; //todo, compressed format whatever that is
var canvas = document.createElement("canvas");
canvas.width = tex.width;
canvas.height = tex.height;
var ctx = canvas.getContext("2d");
var data = ctx.getImageData(0, 0, tex.width, tex.height);
var off = tex.texOffset
var palOff = pal.palOffset;
var total = tex.width*tex.height;
var databuf = texView.readUint8(off);
for (var i=0; i<total; i++) {
var col;
if (bitDepths == 2) {
col = readPalColour(palView, palOff, (databuf>>((i%4)*2))&3)
if (i%4 == 3) databuf = texView.readUint8(++off);
} else if (bitDepths == 4) {
if (i%2 == 0) {
col = readPalColour(palView, palOff, databuf&15)
} else {
col = readPalColour(palView, palOff, databuf>>4)
databuf = texView.readUint8(++off);
}
} else if (bitDepths == 8) {
col = readPalColour(palView, palOff, texView.readUint8(off))
off += 1;
} else if (bitDepths == 16) {
col = readPalColour(palView, palOff, texView.readUint16(off, true))
off += 2;
}
data.data.set(col, i*4);
}
return canvas;
}
function readPalColour(view, palOff, ind) {
var col = palView.getUint16(palOff+ind*2, true);
colourBuffer[0] = Math.round(((col&31)/31)*255)
colourBuffer[1] = Math.round((((col>>5)&31)/31)*255)
colourBuffer[2] = Math.round((((col>>10)&31)/31)*255)
colourBuffer[3] = Math.round((col>>15)*255)
}
function palInfoHandler(view, offset) {
var palOffset = view.getUint16(offset, true)<<3;
var unknown = view.getUint16(offset+2, true);
return {
palOffset: palOffset,
nextoff: offset+4
}
}
function texInfoHandler(view, offset) {
var texOffset = view.getUint16(offset, true)<<3;
var flags = view.getUint16(offset+2, true);
var width2 = view.getUint8(offset+4, true);
var unknown = view.getUint8(offset+5, true);
var height2 = view.getUint8(offset+6, true);
var unknown2 = view.getUint8(offset+7, true);
return {
texOffset: texOffset,
pal: (flags>>13),
format: ((flags>>10)&7),
height: ((flags>>7)&7)<<3,
width: ((flags>>4)&7)<<3,
nextoff: offset+8
}
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
}

158
Code/Formats/.sublaf1.tmp Normal file
View File

@ -0,0 +1,158 @@
//
// nsbtx.js
//--------------------
// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js
//
window.nsbtx = function(input, tex0, autogen) {
var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff,
compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff,
palOffset, mainOff
var textureInfo, paletteInfo, palData, texData, colourBuffer
var thisObj = this;
var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16]
if (input != null) {
load(input, tex0, autogen);
}
this.load = load;
this.readTexWithPal = readTexWithPal;
this.scopeEval = function(code) {return eval(code)} //for debug purposes
function load(input, tex0, autogen) {
var colourBuffer = new Uint32Array(4);
var view = new DataView(input);
var header = null;
var offset = 0;
if (!tex0) { //nitro 3d header
header = nitro.readHeader(view);
if (header.stamp != "BTX0") throw "NSBTX invalid. Expected BTX0, found "+header.stamp;
if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one.";
offset = header.sectionOffsets[0];
}
mainOff = offset;
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3);
if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp;
var size = view.getUint32(offset+0x04, true);
var texDataSize = view.getUint16(offset+0x0C, true)<<8;
var texInfoOff = view.getUint16(offset+0x0E, true);
var texOffset = view.getUint16(offset+0x14, true);
var compTexSize = view.getUint16(offset+0x1C, true)<<8;
var compTexInfoOff = view.getUint16(offset+0x1E, true);
var compTexOffset = view.getUint32(offset+0x24, true);
var compTexInfoDataOff = view.getUint32(offset+0x28, true);
var palSize = view.getUint32(offset+0x30, true)<<3;
var palInfoOff = view.getUint32(offset+0x34, true);
var palOffset = view.getUint32(offset+0x38, true);
//read palletes, then textures.
palData = input.slice(mainOff + palOffset, palSize);
texData = input.slice(mainOff + texOffset, texDataSize);
paletteInfo = nitro.read3dInfo(view, palInfoOff, palInfoHandler);
textureInfo = nitro.read3dInfo(view, texInfoOff, texInfoHandler);
if (false) {
console.log(textureInfo.objectData.length)
for (var i=0; i<textureInfo.objectData.length; i++) {
var canvas = readTexWithPal(i, textureInfo.objectData[i].pal)
document.body.appendChild(canvas);
console.log("uh")
}
}
}
function readTexWithPal(textureId, palId) {
palView = new DataView(palData);
texView = new DataView(texData);
var tex = textureInfo.objectData[textureId];
var pal = paletteInfo.objectData[palId];
var bit = bitDepths[pal.format]; //todo, compressed format whatever that is
var canvas = document.createElement("canvas");
canvas.width = tex.width;
canvas.height = tex.height;
var ctx = canvas.getContext("2d");
var data = ctx.getImageData(0, 0, tex.width, tex.height);
var off = tex.texOffset
var palOff = pal.palOffset;
var total = tex.width*tex.height;
var databuf = texView.readUint8(off);
for (var i=0; i<total; i++) {
var col;
if (bitDepths == 2) {
col = readPalColour(palView, palOff, (databuf>>((i%4)*2))&3)
if (i%4 == 3) databuf = texView.readUint8(++off);
} else if (bitDepths == 4) {
if (i%2 == 0) {
col = readPalColour(palView, palOff, databuf&15)
} else {
col = readPalColour(palView, palOff, databuf>>4)
databuf = texView.readUint8(++off);
}
} else if (bitDepths == 8) {
col = readPalColour(palView, palOff, texView.readUint8(off))
off += 1;
} else if (bitDepths == 16) {
col = readPalColour(palView, palOff, texView.readUint16(off, true))
off += 2;
}
data.data.set(col, i*4);
}
return canvas;
}
function readPalColour(view, palOff, ind) {
var col = palView.getUint16(palOff+ind*2, true);
colourBuffer[0] = Math.round(((col&31)/31)*255)
colourBuffer[1] = Math.round((((col>>5)&31)/31)*255)
colourBuffer[2] = Math.round((((col>>10)&31)/31)*255)
colourBuffer[3] = Math.round((col>>15)*255)
}
function palInfoHandler(view, offset) {
var palOffset = view.getUint16(offset, true)<<3;
var unknown = view.getUint16(offset+2, true);
return {
palOffset: palOffset,
nextoff: offset+4
}
}
function texInfoHandler(view, offset) {
var texOffset = view.getUint16(offset, true)<<3;
var flags = view.getUint16(offset+2, true);
var width2 = view.getUint8(offset+4, true);
var unknown = view.getUint8(offset+5, true);
var height2 = view.getUint8(offset+6, true);
var unknown2 = view.getUint8(offset+7, true);
return {
texOffset: texOffset,
pal: (flags>>13),
format: ((flags>>10)&7),
height: ((flags>>7)&7)<<3,
width: ((flags>>4)&7)<<3,
nextoff: offset+8
}
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
}

113
Code/Formats/Net/netKart.js Normal file
View File

@ -0,0 +1,113 @@
//
// netKart.js
//--------------------
// Singleton for serializing and restoring kart data.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /entities/kart.js
//
window.netKart = new function() {
var animNames = ["drive", "win", "lose", "spin"]
this.saveKart = saveKart;
this.restoreKart = restoreKart;
function saveKart(view, off, k, input) { // requires 0x60 bytes of space from the offset location
saveVec3(view, off, k.pos);
saveVec3(view, off+0xC, k.vel);
view.setFloat32(off+0x18, k.angle, true);
view.setFloat32(off+0x1C, k.physicalDir, true);
view.setFloat32(off+0x20, k.driftOff, true);
if (k.cannon != null) view.setUint16(off+0x24, k.cannon, true);
else view.setUint16(off+0x24, 0xFFFF, true);
view.setUint16(off+0x26, k.airTime, true);
view.setUint16(off+0x28, k.lastCollided, true);
view.setUint8(off+0x2A, k.boostMT);
view.setUint8(off+0x2B, k.boostNorm);
view.setUint16(off+0x2C, k.stuckTo, true);
view.setUint8(off+0x2E, k.wheelTurn);
saveVec3(view, off+0x30, k.kartColVel);
view.setUint8(off+0x3C, k.kartColTimer);
saveVec3(view, off+0x3D, k.kartTargetNormal);
saveVec3(view, off+0x49, k.trackAttach);
var driftFlags = ((k.drifting)?1:0)|(k.driftMode<<1)|((k.driftLanded)?8:0);
view.setUint8(off+0x55, driftFlags);
view.setUint8(off+0x56, animNames.indexOf(k.animMode));
var binput = ((input.accel)?1:0)|((input.decel)?2:0)|((input.drift)?4:0);
view.setUint8(off+0x57, binput);
view.setFloat32(off+0x58, input.turn, true);
view.setFloat32(off+0x5C, input.airTurn, true);
}
function restoreKart(view, off, k) { // we use the same endianness format as the ds to avoid confusion.
try {
k.pos = readVec3(view, off, k.pos);
k.vel = readVec3(view, off+0xC, k.vel);
k.angle = view.getFloat32(off+0x18, true);
k.physicalDir = view.getFloat32(off+0x1C, true);
k.driftOff = view.getFloat32(off+0x20, true);
k.cannon = view.getUint16(off+0x24, true);
if (k.cannon == 0xFFFF) k.cannon = null;
k.airTime = view.getUint16(off+0x26, true);
k.lastCollided = view.getUint16(off+0x28, true);
k.boostMT = view.getUint8(off+0x2A);
k.boostNorm = view.getUint8(off+0x2B);
k.stuckTo = view.getUint16(off+0x2C, true);
k.wheelTurn = view.getUint8(off+0x2E);
k.kartColVel = readVec3(view, off+0x30, k.kartColVel);
k.kartColTimer = view.getUint8(off+0x3C);
k.kartTargetNormal = readVec3(view, off+0x3D, k.kartTargetNormal);
k.trackAttach = readVec3(view, off+0x49, k.trackAttach);
var driftFlags = view.getUint8(off+0x55);
k.drifting = driftFlags&1;
k.driftMode = (driftFlags>>1)&3;
k.driftLanded = driftFlags&8;
k.animMode = animNames[view.getUint8(off+0x56)];
k.controller.binput = view.getUint8(off+0x57);
k.controller.turn = view.getFloat32(off+0x58, true);
k.controller.airTurn = view.getFloat32(off+0x5C, true);
} catch (err) {
console.err("Kart restore failure:"+err.message);
//failed to restore kart data. may wish to disconnect on this, but it's probably better to not react.
}
}
function saveVec3(view, off, vec) {
var vec = vec;
if (vec == null) vec = [NaN, NaN, NaN];
view.setFloat32(off, vec[0], true);
view.setFloat32(off+4, vec[1], true);
view.setFloat32(off+8, vec[2], true);
}
function readVec3(view, off, vec) {
var first = view.getFloat32(off, true);
if (isNaN(first)) return null;
vec = vec3.create();
vec[0] = first;
vec[1] = view.getFloat32(off+4, true);
vec[2] = view.getFloat32(off+8, true);
return vec;
}
}

View File

@ -0,0 +1,71 @@
//
// kartoffsetdata.js
//--------------------
// Provides functionality to read mario kart ds kart wheel and character model offsets.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
//
window.kartoffsetdata = function(input) {
var thisObj = this;
if (input != null) {
load(input);
}
this.load = load;
function load(input) {
var view = new DataView(input);
var off = 0;
var karts = []
for (var i=0; i<37; i++) {
var obj = {};
obj.name = readString(view, off, 0x10);
off += 0x10;
obj.frontTireSize = view.getInt32(off, true)/4096;
off += 4;
var wheels = [];
for (var j=0; j<4; j++) {
var pos = vec3.create();
pos[0] = view.getInt32(off, true)/4096;
pos[1] = view.getInt32(off+4, true)/4096;
pos[2] = view.getInt32(off+8, true)/4096;
off += 12;
wheels.push(pos);
}
var chars = [];
for (var j=0; j<13; j++) {
var pos = vec3.create();
pos[0] = view.getInt32(off, true)/4096;
pos[1] = view.getInt32(off+4, true)/4096;
console.log("charPos: "+pos[1]);
pos[2] = view.getInt32(off+8, true)/4096;
off += 12;
chars.push(pos);
}
obj.wheels = wheels;
obj.chars = chars;
karts.push(obj);
}
thisObj.karts = karts;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
function readString(view, offset, length) {
var str = "";
for (var i=0; i<length; i++) {
var b = view.getUint8(offset++);
if (b != 0) str += String.fromCharCode(b);
}
return str;
}
}

View File

@ -0,0 +1,65 @@
//
// kartphysicalparam.js
//--------------------
// Provides functionality to read mario kart ds kart physical parameters
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0) (maybe)
//
window.kartphysicalparam = function(input) {
var thisObj = this;
if (input != null) {
load(input);
}
this.load = load;
function load(input) {
var view = new DataView(input);
var off = 0;
var karts = []
for (var i=0; i<50; i++) {
var obj = {};
var colParam = [];
obj.colRadius = view.getInt32(off, true)/4096;
obj.unknown1 = view.getInt32(off+0x4, true)/4096;
obj.unknown2 = view.getInt32(off+0x8, true)/4096;
obj.weight = view.getInt16(off+0xC, true)/4096;
obj.miniTurbo = view.getUint16(off+0xE, true);
obj.topSpeed = view.getInt32(off+0x10, true)/4096;
obj.accel1 = view.getInt32(off+0x14, true)/4096;
obj.accel2 = view.getInt32(off+0x18, true)/4096;
obj.accelSwitch = view.getInt32(off+0x1C, true)/4096;
obj.driftAccel1 = view.getInt32(off+0x20, true)/4096;
obj.driftAccel2 = view.getInt32(off+0x24, true)/4096;
obj.driftAccelSwitch = view.getInt32(off+0x28, true)/4096;
obj.decel = view.getInt32(off+0x2C, true)/4096;
obj.turnRate = (view.getInt16(off+0x30, true)/32768)*Math.PI;
obj.driftTurnRate = (view.getInt16(off+0x32, true)/32768)*Math.PI;
obj.driftOffRestore = (view.getInt16(off+0x34, true)/32768)*Math.PI;
obj.unknown3 = view.getInt16(off+0x36, true);
var off1 = off+0x38;
var off2 = off+0x68;
for (var j=0; j<12; j++) {
var handling = view.getInt32(off1, true)/4096;
var topSpeed = view.getInt32(off2, true)/4096;
colParam.push({
handling: handling,
topSpeedMul: topSpeed
});
off1+=4;
off2+=4;
}
obj.colParam = colParam;
karts.push(obj);
off += 0x98;
}
thisObj.karts = karts;
}
}

295
Code/Formats/kcl.js Normal file
View File

@ -0,0 +1,295 @@
//
// kcl.js
//--------------------
// Loads kcl files and provides a variety of functions for accessing and using the data.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
//
window.kcl = function(input, mkwii) {
//todo, support versions for other games (MKWii etc)
this.load = load;
this.getPlanesAt = getPlanesAt;
var vertexOffset, normalOffset, planeOffset, octreeOffset, unknown1, topLeftVec,
xMask, yMask, zMask, coordShift, yShift, zShift, unknown2, trisMapped = 0,
//decoded data
planes, octree, end, mkwiiMode //little endian for ds, big endian for wii
var sf, mouseX = 0, mouseY = 0, offx, offz, loaded = false //for testing
var Fixed32Point = 4096;
if (input != null) {
//handle input, load kcl from data
if (typeof input == "string") {
var xml = new XMLHttpRequest();
xml.responseType = "arraybuffer";
xml.open("GET", input, true);
xml.onload = function() {
load(xml.response);
}
xml.send();
} else {
load(input, mkwii);
}
}
window.onmousemove = function(evt) {
mouseX = evt.pageX;
mouseY = evt.pageY;
}
this.scopeEval = function(code) {return eval(code)} //for debug purposes
//canvas = document.getElementById("canvas");
//ctx = canvas.getContext("2d");
//setInterval(render, 16);
function readBigDec(view, off, mkwii) {
if (mkwii) return view.getFloat32(off);
else return view.getInt32(off, end)/Fixed32Point;
}
function load(buffer, mkwii) {
var mkwii = mkwii;
if (mkwii == null) mkwii = false;
end = !mkwii;
mkwiiMode = mkwii;
var time = Date.now();
//loads kcl from an array buffer.
var view = new DataView(buffer);
vertexOffset = view.getUint32(0x00, end);
normalOffset = view.getUint32(0x04, end);
planeOffset = view.getUint32(0x08, end);
octreeOffset = view.getUint32(0x0C, end);
unknown1 = readBigDec(view, 0x10, mkwii);
var vec = vec3.create();
vec[0] = readBigDec(view, 0x14, mkwii);
vec[1] = readBigDec(view, 0x18, mkwii);
vec[2] = readBigDec(view, 0x1C, mkwii);
topLeftVec = vec;
xMask = view.getUint32(0x20, end);
yMask = view.getUint32(0x24, end);
zMask = view.getUint32(0x28, end);
coordShift = view.getUint32(0x2C, end);
yShift = view.getUint32(0x30, end);
zShift = view.getUint32(0x34, end);
unknown2 = readBigDec(view, 0x38, mkwii);
//read planes, there should be as many as there is 16 byte spaces between planeOffset+0x10 and octreeOffset
offset = planeOffset+0x10;
planes = [null]; //0 index is empty
var minx=0, maxx=0, minz=0, maxz=0;
while (offset < octreeOffset) {
planes.push(new Plane(view, offset));
offset += 0x10;
var vert = planes[planes.length-1].Vertex1;
if (vert[0] < minx) minx=vert[0];
if (vert[0] > maxx) maxx=vert[0];
if (vert[2] < minz) minz=vert[2];
if (vert[2] > maxz) maxz=vert[2];
}
console.log("minx: "+minx+" maxx: "+maxx+" minz: "+minz+" maxz: "+maxz)
//var sfx = canvas.width/(maxx-minx);
//var sfy = canvas.height/(maxz-minz);
//offx = -((minx+maxx)/2);
//offz = -((minz+maxz)/2);
//sf = Math.min(sfx, sfy)*0.8;
octree = []
var rootNodes = ((~xMask >> coordShift) + 1) * ((~yMask >> coordShift) + 1) * ((~zMask >> coordShift) + 1);
for (var i=0; i<rootNodes; i++) {
var off = octreeOffset+i*4;
octree.push(decodeCube(octreeOffset, off, view));
}
loaded = true;
//alert("process took "+(Date.now()-time)+"ms");
}
function render() {
if (!loaded) return;
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.translate(canvas.width/2, canvas.height/2);
ctx.scale(sf, sf);
ctx.translate(offx, offz);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 5;
testDrawPlanes(planes);
var test = getPlanesAt(((mouseX-canvas.width/2)/sf)-offx, topLeftVec[1]+Math.random()*(~yMask), ((mouseY-canvas.height/2)/sf)-offz);
ctx.strokeStyle = "#FF0000";
ctx.lineWidth = 20;
testDrawPlanes(test);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 3;
drawOctreeBorders();
ctx.restore();
/*if (test5 != null) {
ctx.lineWidth = 0.01;
ctx.save();
ctx.translate(canvas.width/2, canvas.height/2);
ctx.scale(sf, sf);
ctx.translate(offx, offz);
ctx.scale(1024, 1024);
ctx.strokeStyle = "#0000FF";
var mdl = test5.modelBuffers[0];
for (var i=0; i<mdl.length; i++) {
var strip = mdl[i].strips[0];
var off = 0;
for (var j=0; j<strip.verts/3; j++) {
ctx.beginPath();
ctx.moveTo(strip.posArray[off], strip.posArray[off+2]);
ctx.lineTo(strip.posArray[off+3], strip.posArray[off+5]);
ctx.lineTo(strip.posArray[off+6], strip.posArray[off+8]);
ctx.closePath();
ctx.stroke();
off += 9;
}
}
ctx.restore();
}*/
}
function drawOctreeBorders() {
var size = 1<<coordShift;
for (var x=0; x<((~xMask >> coordShift) + 1); x++) {
for (var z=0; z<((~zMask >> coordShift) + 1); z++) {
ctx.strokeRect(topLeftVec[0]+size*x, topLeftVec[2]+size*z, size, size);
}
}
}
function testDrawPlanes(planes) {
for (var i=1; i<planes.length; i++) {
var plane = planes[i];
ctx.beginPath();
ctx.moveTo(plane.Vertex1[0], plane.Vertex1[2]);
ctx.lineTo(plane.Vertex2[0], plane.Vertex2[2]);
ctx.lineTo(plane.Vertex3[0], plane.Vertex3[2]);
ctx.closePath();
ctx.stroke();
}
}
function getPlanesAt(x, y, z) {
x -= topLeftVec[0];
y -= topLeftVec[1];
z -= topLeftVec[2];
if (x<0 || y<0 || z<0) return []; //no collision
else {
x = Math.floor(x);
y = Math.floor(y);
z = Math.floor(z);
if ((x&xMask)>0 || (y&yMask)>0 || (z&zMask)>0) return []; //no collision
var index = (x>>coordShift)|((y>>coordShift)<<yShift)|((z>>coordShift)<<zShift)
return traverseOctree(octree[index], x, y, z, coordShift-1);
}
}
function traverseOctree(node, x, y, z, shift) {
if (node.leaf) return node.realTris;
//otherwise we're a node! find next index and traverse
var index = ((x>>shift)&1)|(((y>>shift)&1)<<1)|(((z>>shift)&1)<<2);
return traverseOctree(node.items[index], x, y, z, shift-1);
}
function decodeCube(baseoff, off, view) {
var data = view.getUint32(off, end);
var off2 = baseoff+(data&0x7FFFFFFF);
if (off2 >= view.byteLength) {
return {
leaf: true,
tris: [],
realTris: []
}
}
if (data&0x80000000) { //is a leaf.
off2 += 2;
var tris = [];
var realTris = [];
while (true) {
var read = view.getUint16(off2, end);
if (read == 0) break; //zero terminated
tris.push(read);
realTris.push(planes[read]);
trisMapped += 1;
off2 += 2;
}
return {
leaf: true,
tris: tris,
realTris: realTris
}
} else { //contains 8 more cubes
var cubes = [];
var boff = off2;
for (var i=0; i<8; i++) {
cubes.push(decodeCube(boff, off2, view));
off2 += 4;
}
return {
leaf: false,
items: cubes
}
}
}
function Plane(view, offset) {
this.Len = readBigDec(view, offset, mkwiiMode);
this.Vertex1 = readVert(view.getUint16(offset+0x4, end), view);
this.Normal = readNormal(view.getUint16(offset+0x6, end), view);
this.NormalA = readNormal(view.getUint16(offset+0x8, end), view);
this.NormalB = readNormal(view.getUint16(offset+0xA, end), view);
this.NormalC = readNormal(view.getUint16(offset+0xC, end), view);
this.CollisionType = view.getUint16(offset+0xE, end);
var crossA = vec3.cross(vec3.create(), this.NormalA, this.Normal);
var crossB = vec3.cross(vec3.create(), this.NormalB, this.Normal);
this.Vertex2 = vec3.scaleAndAdd(vec3.create(), this.Vertex1, crossB, (this.Len/vec3.dot(crossB, this.NormalC)));
this.Vertex3 = vec3.scaleAndAdd(vec3.create(), this.Vertex1, crossA, (this.Len/vec3.dot(crossA, this.NormalC)));
}
function readVert(num, view) {
var vec = vec3.create();
var loc = vertexOffset+num*0xC;
vec[0] = readBigDec(view, loc, mkwiiMode);
vec[1] = readBigDec(view, loc+0x4, mkwiiMode);
vec[2] = readBigDec(view, loc+0x8, mkwiiMode);
return vec;
}
function readNormal(num, view) {
var mkwii = mkwiiMode;
var vec = vec3.create();
if (mkwii) {
var loc = normalOffset+num*0xC;
vec[0] = view.getFloat32(loc);
vec[1] = view.getFloat32(loc+0x4);
vec[2] = view.getFloat32(loc+0x8);
} else {
var loc = normalOffset+num*0x6;
vec[0] = view.getInt16(loc, end)/4096; //fixed point
vec[1] = view.getInt16(loc+0x2, end)/4096;
vec[2] = view.getInt16(loc+0x4, end)/4096;
}
return vec;
}
}

41
Code/Formats/lz77.js Normal file
View File

@ -0,0 +1,41 @@
//
// lz77.js
//--------------------
// Reads and decompresses lz77 (mode 0x10 only) files. In future may be able to recompress.
// by RHY3756547
//
window.lz77 = new (function() {
this.decompress = function(buffer) {
var view = new DataView(buffer);
var compType = view.getUint8(0);
var size = view.getUint32(0, true)>>8;
var targ = new ArrayBuffer(size);
var targA = new Uint8Array(targ);
var off = 4;
var dOff = 0;
var eof = buffer.byteLength;
while (off<eof) {
var flag = view.getUint8(off++);
for (var j=7; j>=0; j--) {
if (off>=eof) break;
if ((flag>>j)&1) { //1=compressed, 2=raw byte
var dat = view.getUint16(off);
off += 2;
var cOff = (dOff-(dat&4095))-1;
var len = (dat>>12)+3;
for (var k=0; k<len; k++) {
targA[dOff++] = targA[cOff++];
}
} else {
targA[dOff++] = view.getUint8(off++);
}
}
}
return targ;
}
})();

196
Code/Formats/narc.js Normal file
View File

@ -0,0 +1,196 @@
//
// narc.js
//--------------------
// Reads narc archives and provides access to files by directory structure.
// by RHY3756547
//
window.narc = function(input) {
this.load = load;
this.getFile = getFile;
var arc = this;
var handlers = [];
window.onmousemove = function(evt) {
mouseX = evt.pageX;
mouseY = evt.pageY;
}
this.scopeEval = function(code) {return eval(code)} //for debug purposes
function load(buffer) {
arc.buffer = buffer; //we will use this data in the future.
var view = new DataView(buffer);
arc.stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3);
if (arc.stamp != "NARC") throw "File provided is not a NARC archive! Expected NARC, found "+arc.stamp+".";
arc.byteOrder = view.getUint16(0x4, true); //todo: check byte order and flip to little endian when necessary
arc.version = view.getUint16(0x6, true);
arc.size = view.getUint32(0x8, true);
arc.headSize = view.getUint16(0xC, true);
arc.numBlocks = view.getUint16(0xE, true);
var off = arc.headSize;
arc.sections = {};
for (var i=0; i<arc.numBlocks; i++) {
var section = readSection(view, off);
arc.sections[section.type] = section;
off = 4*Math.ceil(section.nextOff/4);
}
}
function readSection(view, off) {
var obj = {};
obj.type = readChar(view, off+0x0)+readChar(view, off+0x1)+readChar(view, off+0x2)+readChar(view, off+0x3);
obj.size = view.getUint32(off+0x4, true);
if (handlers[obj.type] == null) throw "Unknown NARC section "+obj.type+"!";
handlers[obj.type](view, off+0x8, obj);
obj.nextOff = off+obj.size;
return obj;
}
function getFile(name) {
var path = name.split("/");
var start = (path[0] == "")?1:0; //fix dirs relative to root (eg "/hi/test.bin")
var table = arc.sections["BTNF"].directories;
var curDir = table[0].entries; //root
for (var i=start; i<path.length; i++) {
var found = false;
for (var j=0; j<curDir.length; j++) {
if (curDir[j].name == path[i]) {
if (curDir[j].dir) {
found = true;
curDir = table[curDir[j].id-0xF000].entries;
break;
} else {
return readFileWithID(curDir[j].id);
}
}
}
if (!found) {
console.error("File not found: "+name+", could not find "+path[i]);
return null;
}
}
console.error("Path is not a file: "+name);
return null; //incomplete path; we ended on a directory, not a file!
}
function readFileWithID(id) {
var table = arc.sections["BTAF"].files;
var file = table[id];
var off = arc.sections["GMIF"].baseOff;
if (file == null) {
console.error("File ID invalid: "+id);
return null;
}
return arc.buffer.slice(file.start+off, file.end+off);
}
var handlers = {};
handlers["BTAF"] = function(view, off, obj) {
obj.numFiles = view.getUint16(off, true);
obj.reserved = view.getUint16(off+0x2, true);
obj.files = [];
off += 4;
for (var i=0; i<obj.numFiles; i++) {
var fl = {}
fl.start = view.getUint32(off, true);
fl.end = view.getUint32(off+4, true);
obj.files.push(fl);
off += 8;
}
}
handlers["BTNF"] = function(view, off, obj) { //filename table - includes directories and filenames.
var soff = off;
obj.directories = [];
//read root dir, then we know number of directories to read.
var root = {};
var dirOff = soff+view.getUint32(off, true);
root.firstFile = view.getUint16(off+4, true);
populateDir(view, dirOff, root);
root.numDir = view.getUint16(off+6, true);
off += 8;
obj.directories.push(root);
var n = root.numDir-1;
for (var i=0; i<n; i++) {
var dir = {};
var dirOff = soff+view.getUint32(off, true);
dir.firstFile = view.getUint16(off+4, true);
populateDir(view, dirOff, dir);
dir.parent = view.getUint16(off+6, true);
off += 8;
obj.directories.push(dir);
}
}
handlers["GMIF"] = function(view, off, obj) {
obj.baseOff = off;
}
function populateDir(view, off, dir) {
curFile = dir.firstFile;
dir.entries = [];
while (true) {
var flag = view.getUint8(off++);
var len = flag&127;
if (! (flag&128)) { //file or end of dir
if (len == 0) return;
else {
dir.entries.push({
dir: false,
id: curFile++,
name: readString(view, off, len)
})
off += len;
}
} else {
var dirID = view.getUint16(off+len, true);
dir.entries.push({
dir: true,
id: dirID,
name: readString(view, off, len)
});
off += len+2;
}
}
}
function readString(view, off, length) {
var str = "";
for (var i=0; i<length; i++) {
str += readChar(view, off++);
}
return str;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
if (input != null) {
if (typeof input == "string") {
var xml = new XMLHttpRequest();
xml.responseType = "arraybuffer";
xml.open("GET", input, true);
xml.onload = function() {
load(xml.response);
}
xml.send();
} else {
load(input);
}
}
}

170
Code/Formats/ndsFS.js Normal file
View File

@ -0,0 +1,170 @@
//
// ndsFS.js
//--------------------
// Reads nds roms using nitroFS and provides access to files by directory structure.
// by RHY3756547
//
window.ndsFS = function(input) {
this.load = load;
this.getFile = getFile;
var arc = this;
var handlers = [];
window.onmousemove = function(evt) {
mouseX = evt.pageX;
mouseY = evt.pageY;
}
this.scopeEval = function(code) {return eval(code)} //for debug purposes
function load(buffer) {
arc.buffer = buffer; //we will use this data in the future.
var view = new DataView(buffer);
arc.view = view;
arc.sections = {};
arc.nameOff = view.getUint32(0x40, true);
arc.fileOff = view.getUint32(0x48, true)
arc.sections["BTNF"] = {};
handlers["BTNF"](view, arc.nameOff, arc.sections["BTNF"]) //file name table
/*arc.sections["BTAF"] = {};
handlers["BTAF"](view, , arc.sections["BTAF"]) //file alloc table */
}
function getFile(name) {
var path = name.split("/");
var start = (path[0] == "")?1:0; //fix dirs relative to root (eg "/hi/test.bin")
var table = arc.sections["BTNF"].directories;
var curDir = table[0].entries; //root
for (var i=start; i<path.length; i++) {
var found = false;
for (var j=0; j<curDir.length; j++) {
if (curDir[j].name == path[i]) {
if (curDir[j].dir) {
found = true;
curDir = table[curDir[j].id-0xF000].entries;
break;
} else {
return readFileWithID(curDir[j].id);
}
}
}
if (!found) {
console.error("File not found: "+name+", could not find "+path[i]);
return null;
}
}
console.error("Path is not a file: "+name);
return null; //incomplete path; we ended on a directory, not a file!
}
function readFileWithID(id) {
var off = arc.fileOff+id*8;
/*var table = arc.sections["BTAF"].files;
var file = table[id];
if (file == null) {
console.error("File ID invalid: "+id);
return null;
}*/
return arc.buffer.slice(arc.view.getUint32(off, true), arc.view.getUint32(off+4, true));
}
var handlers = {};
handlers["BTAF"] = function(view, off, obj) {
obj.files = [];
for (var i=0; i<obj.numFiles; i++) {
var fl = {}
fl.start = view.getUint32(off, true);
fl.end = view.getUint32(off+4, true);
obj.files.push(fl);
off += 8;
}
}
handlers["BTNF"] = function(view, off, obj) { //filename table - includes directories and filenames.
var soff = off;
obj.directories = [];
//read root dir, then we know number of directories to read.
var root = {};
var dirOff = soff+view.getUint32(off, true);
root.firstFile = view.getUint16(off+4, true);
populateDir(view, dirOff, root);
root.numDir = view.getUint16(off+6, true);
off += 8;
obj.directories.push(root);
var n = root.numDir-1;
for (var i=0; i<n; i++) {
var dir = {};
var dirOff = soff+view.getUint32(off, true);
dir.firstFile = view.getUint16(off+4, true);
populateDir(view, dirOff, dir);
dir.parent = view.getUint16(off+6, true);
off += 8;
obj.directories.push(dir);
}
}
function populateDir(view, off, dir) {
curFile = dir.firstFile;
dir.entries = [];
while (true) {
var flag = view.getUint8(off++);
var len = flag&127;
if (! (flag&128)) { //file or end of dir
if (len == 0) return;
else {
dir.entries.push({
dir: false,
id: curFile++,
name: readString(view, off, len)
})
off += len;
}
} else {
var dirID = view.getUint16(off+len, true);
dir.entries.push({
dir: true,
id: dirID,
name: readString(view, off, len)
});
off += len+2;
}
}
}
function readString(view, off, length) {
var str = "";
for (var i=0; i<length; i++) {
str += readChar(view, off++);
}
return str;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
if (input != null) {
if (typeof input == "string") {
var xml = new XMLHttpRequest();
xml.responseType = "arraybuffer";
xml.open("GET", input, true);
xml.onload = function() {
load(xml.response);
}
xml.send();
} else {
load(input);
}
}
}

37
Code/Formats/nftr.js Normal file
View File

@ -0,0 +1,37 @@
//
// nftr.js
//--------------------
// Reads NFTR fonts and compiles them to a texture and character lookup table. Texture is replaceable.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js
//
window.nftr = function(input) {
var mainOff;
var mainObj = this;
if (input != null) {
load(input);
}
this.load = load;
function load(input) {
var view = new DataView(input);
var header = null;
var offset = 0;
var tex;
//nitro 3d header
header = nitro.readHeader(view);
//debugger;
if (header.stamp != "RTFN") throw "NFTR invalid. Expected RTFN, found "+header.stamp;
offset = header.sectionOffsets[0];
//end nitro
mainOff = offset;
}
}

85
Code/Formats/nitro.js Normal file
View File

@ -0,0 +1,85 @@
//
// nitro.js
//--------------------
// General purpose functions for nitro formats, eg. NSBTX or NSBMD
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
//
window.nitro = new function() {
this.readHeader = function(view) { //input: DataView with base offset at header position
var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3);
var unknown1 = view.getUint32(0x4, true);
var filesize = view.getUint32(0x8, true);
var headsize = view.getUint16(0xC, true);
var numSections = view.getUint16(0xE, true);
var sectionOffsets = [];
for (var i=0; i<numSections; i++) {
sectionOffsets.push(view.getUint32(0x10+i*4, true));
}
return {
stamp: stamp,
unknown1: unknown1,
filesize: filesize,
headsize: headsize,
numSections: numSections,
sectionOffsets: sectionOffsets
}
}
this.read3dInfo = function(view, offset, dataHandler) {
var baseOff = offset;
offset += 1; //skip dummy
var numObjects = view.getUint8(offset++);
var secSize = view.getUint16(offset, true);
offset += 2;
//unknown block. documentation out of 10
var uhdSize = view.getUint16(offset, true);
offset += 2;
var usecSize = view.getUint16(offset, true);
offset += 2;
var unknown = view.getUint32(offset, true); //usually 0x0000017F
offset += 4;
var objectUnk = []
for (var i=0; i<numObjects; i++) {
var uk1 = view.getUint16(offset, true);
var uk2 = view.getUint16(offset+2, true);
objectUnk.push({uk1: uk1, uk2: uk2});
offset += 4;
}
//info block
var ihdSize = view.getUint16(offset, true);
offset += 2;
var isecSize = view.getUint16(offset, true);
offset += 2;
var objectData = []
for (var i=0; i<numObjects; i++) {
var data = dataHandler(view, offset, baseOff, i); //must return object with "nextoff" as offset after reading data
objectData.push(data)
offset = data.nextoff;
}
var names = []
for (var i=0; i<numObjects; i++) {
var name = "";
for (var j=0; j<16; j++) {
name += readChar(view, offset++)
}
names.push(name);
}
return {
numObjects: numObjects,
unknown: unknown,
objectUnk: objectUnk,
objectData: objectData,
names: names,
nextoff: offset
}
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
}

393
Code/Formats/nkm.js Normal file
View File

@ -0,0 +1,393 @@
//
// nkm.js
//--------------------
// Loads nkm files and provides a variety of functions for accessing and using the data.
//
// nkm files usually drive the game logic of tracks (checkpoints, ai waypoints, objects on track) so it's pretty
// crucial to have this up and running.
//
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
//
window.nkm = function(input, mkwii) {
//todo, support versions for other games (MKWii etc)
this.load = load;
var thisObj = this;
var handlers = [];
window.onmousemove = function(evt) {
mouseX = evt.pageX;
mouseY = evt.pageY;
}
this.scopeEval = function(code) {return eval(code)} //for debug purposes
function load(buffer, mkwii) {
var view = new DataView(buffer);
thisObj.stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3);
thisObj.version = view.getUint16(0x4, true);
var n = view.getUint16(0x6, true);
var off = 8;
var sections = {};
for (var i=0; i<(n-8)/4; i++) {
var soff = view.getUint32(off, true);
var section = readSection(view, soff+n)
sections[section.type] = section;
off += 4;
}
thisObj.sections = sections;
}
function readSection(view, off) {
var obj = {};
obj.type = readChar(view, off+0x0)+readChar(view, off+0x1)+readChar(view, off+0x2)+readChar(view, off+0x3);
if (obj.type == "STAG") {
handlers["STAG"](view, off, obj);
} else {
var handler = handlers[obj.type];
if (handler == null) {
console.error("Unknown NKM section type "+obj.type+"!");
return obj;
}
var entN = view.getUint32(off+0x4, true);
off += 0x8;
var entries = [];
for (var i=0; i<entN; i++) {
var item = handler(view, off);
entries.push(item);
off = item.nextOff;
}
obj.entries = entries;
}
return obj;
}
handlers["OBJI"] = function(view, off) {
var obj = {};
obj.pos = vec3.create();
obj.pos[0] = view.getInt32(off, true)/4096;
obj.pos[1] = view.getInt32(off+4, true)/4096;
obj.pos[2] = view.getInt32(off+8, true)/4096;
obj.angle = [];
obj.angle[0] = view.getInt32(off+0xC, true)/4096;
obj.angle[1] = view.getInt32(off+0x10, true)/4096;
obj.angle[2] = view.getInt32(off+0x14, true)/4096;
obj.scale = vec3.create();
obj.scale[0] = view.getInt32(off+0x18, true)/4096;
obj.scale[1] = view.getInt32(off+0x1C, true)/4096;
obj.scale[2] = view.getInt32(off+0x20, true)/4096;
obj.ID = view.getUint16(off+0x24, true);
obj.routeID = view.getUint16(off+0x26, true);
obj.setting1 = view.getUint32(off+0x28, true);
obj.setting2 = view.getUint32(off+0x2C, true);
obj.setting3 = view.getUint32(off+0x30, true);
obj.setting4 = view.getUint32(off+0x34, true);
obj.timeTrials = view.getUint32(off+0x38, true);
obj.nextOff = off+0x3C;
return obj;
}
handlers["PATH"] = function(view, off) {
var obj = {};
obj.routeID = view.getUint8(off);
obj.loop = view.getUint8(off+1);
obj.numPts = view.getUint16(off+2, true);
obj.nextOff = off+0x4;
return obj;
}
handlers["POIT"] = function(view, off) {
var obj = {};
obj.pos = vec3.create();
obj.pos[0] = view.getInt32(off, true)/4096;
obj.pos[1] = view.getInt32(off+4, true)/4096;
obj.pos[2] = view.getInt32(off+8, true)/4096;
obj.pointInd = view.getUint16(off+0xC, true);
obj.duration = view.getUint16(off+0xE, true);
obj.unknown = view.getUint32(off+0x10, true);
obj.nextOff = off+0x14;
return obj;
}
handlers["STAG"] = function(view, off, obj) {
obj.courseID = view.getUint16(off+0x4, true);
obj.laps = view.getUint16(off+0x6, true); //doubles as battle mode duration
obj.unknown = view.getUint8(off+0x8);
obj.fogEnable = view.getUint8(off+0x9);
obj.fogMode = view.getUint8(off+0xA);
obj.fogSlope = view.getUint8(off+0xB);
//skip 8 bytes of unknown, probably more fog stuff. (disabled for now)
obj.fogDist = view.getInt32(off+0x14, true)/4096;
obj.fogCol = readRGB(view, off+0x18);
obj.fogAlpha = view.getUint16(off+0x1A, true);
obj.kclCol = [readRGB(view, off+0x1C), readRGB(view, off+0x1E), readRGB(view, off+0x20), readRGB(view, off+0x22)];
//unknown 8 bytes again
return obj;
}
handlers["KTPS"] = function(view, off) { //start positions
var obj = {};
obj.pos = vec3.create();
obj.pos[0] = view.getInt32(off, true)/4096;
obj.pos[1] = view.getInt32(off+4, true)/4096;
obj.pos[2] = view.getInt32(off+8, true)/4096;
obj.angle = [];
obj.angle[0] = view.getInt32(off+0xC, true)/4096;
obj.angle[1] = view.getInt32(off+0x10, true)/4096;
obj.angle[2] = view.getInt32(off+0x14, true)/4096;
obj.id1 = view.getInt16(off+0x18, true);
obj.id2 = view.getInt16(off+0x1A, true);
obj.nextOff = off+0x1C;
return obj;
}
handlers["KTP2"] = handlers["KTPS"]; //must pass this point for lap to count. ids irrelevant
handlers["KTPJ"] = function(view, off){
var obj = handlers["KTPS"](view, off);
obj.respawnID = view.getInt32(off+0x1C, true);
obj.nextOff += 0x4;
return obj;
}; //respawn points. id1 is cpu route, id2 is item route
handlers["KTPC"] = handlers["KTPS"]; //cannon positions. id1 is cpu route, id2 is cannon id
handlers["KTPM"] = handlers["KTPS"]; //mission kart position. must pass for mission to succeed.
handlers["CPOI"] = function(view, off) {
var obj = {};
obj.x1 = view.getInt32(off, true)/4096;
obj.z1 = view.getInt32(off+0x4, true)/4096;
obj.x2 = view.getInt32(off+0x8, true)/4096;
obj.z2 = view.getInt32(off+0xC, true)/4096;
obj.sinus = view.getInt32(off+0x10, true)/4096;
obj.cosinus = view.getInt32(off+0x14, true)/4096;
obj.distance = view.getInt32(off+0x18, true)/4096;
obj.nextSection = view.getInt16(off+0x1C, true);
obj.currentSection = view.getInt16(off+0x1E, true);
obj.keyPoint = view.getInt16(off+0x20, true);
obj.respawn = view.getUint8(off+0x22);
obj.unknown = view.getUint8(off+0x23);
obj.nextOff = off+0x24;
return obj;
}
handlers["CPAT"] = function(view, off) { //checkpoint path
var obj = {};
obj.startInd = view.getInt16(off, true);
obj.pathLen = view.getInt16(off+0x2, true);
obj.dest = [view.getInt8(off+0x4)];
var tmp = view.getInt8(off+0x5)
if (tmp != -1) obj.dest.push(tmp);
var tmp2 = view.getInt8(off+0x6)
if (tmp2 != -1) obj.dest.push(tmp2);
obj.source = [view.getInt8(off+0x7)];
var tmp3 = view.getInt8(off+0x8)
if (tmp3 != -1) obj.source.push(tmp3);
var tmp4 = view.getInt8(off+0x9)
if (tmp4 != -1) obj.source.push(tmp4);
obj.sectionOrder = view.getInt16(off+0xA, true);
obj.nextOff = off+0xC;
return obj;
}
handlers["MEPA"] = function(view, off) { //checkpoint path
var obj = {};
obj.startInd = view.getInt16(off, true);
obj.pathLen = view.getInt16(off+0x2, true);
obj.dest = [];
var o = off+4;
for(var i=0; i<8; i++) {
var tmp = view.getInt8(o++);
if (tmp != -1) obj.dest.push(tmp);
}
obj.source = [];
for(var i=0; i<8; i++) {
var tmp = view.getInt8(o++);
if (tmp != -1) obj.source.push(tmp);
}
obj.nextOff = o;
return obj;
}
handlers["IPAT"] = handlers["CPAT"]; //item path
handlers["EPAT"] = handlers["CPAT"]; //enemy path
handlers["IPOI"] = function(view, off) {
var obj = {};
obj.pos = vec3.create();
obj.pos[0] = view.getInt32(off, true)/4096;
obj.pos[1] = view.getInt32(off+4, true)/4096;
obj.pos[2] = view.getInt32(off+8, true)/4096;
obj.unknown1 = view.getUint8(off+0xC); //tends to be 0 or FF
obj.unknown2 = view.getUint8(off+0xD);
obj.unknown3 = view.getUint8(off+0xE);
obj.unknown4 = view.getUint8(off+0xF);
obj.unknown5 = view.getUint32(off+0x10, true); //tends to be 0
obj.nextOff = off+0x14;
return obj;
}
handlers["EPOI"] = function(view, off) {
var obj = {};
obj.pos = vec3.create();
obj.pos[0] = view.getInt32(off, true)/4096;
obj.pos[1] = view.getInt32(off+4, true)/4096;
obj.pos[2] = view.getInt32(off+8, true)/4096;
obj.pointSize = view.getInt32(off+0xC, true)/4096;
obj.cpuDrift = view.getUint16(off+0x10, true); //will find out what this means in due time, a watcher on this value while a cpu is going around the track should clear things up.
obj.unknown1 = view.getUint16(off+0x12, true); //tends to be 0
obj.unknown2 = view.getUint32(off+0x14, true); //tends to be 0
obj.nextOff = off+0x18;
return obj;
}
handlers["MEPO"] = function(view, off) { //theres usually 5 of these LOL!!! im not sorry
var obj = {};
obj.pos = vec3.create();
obj.pos[0] = view.getInt32(off, true)/4096;
obj.pos[1] = view.getInt32(off+4, true)/4096;
obj.pos[2] = view.getInt32(off+8, true)/4096;
obj.pointSize = view.getInt32(off+0xC, true)/4096;
obj.cpuDrift = view.getUint16(off+0x10, true); //will find out what this means in due time, a watcher on this value while a cpu is going around the track should clear things up.
obj.unknown1 = view.getUint16(off+0x12, true); //tends to be 0
obj.unknown1 = view.getUint32(off+0x14, true); //tends to be 0
obj.nextOff = off+0x18;
return obj;
}
handlers["AREA"] = function(view, off) { //area for cameras. this section is ridiculous - will need thorough investigation if we want to get race spectate cameras working.
var obj = {};
obj.pos = vec3.create();
obj.pos[0] = view.getInt32(off, true)/4096;
obj.pos[1] = view.getInt32(off+4, true)/4096;
obj.pos[2] = view.getInt32(off+8, true)/4096;
obj.dimensions = vec3.create();
obj.dimensions[0] = view.getInt32(off+0xC, true)/4096;
obj.dimensions[1] = view.getInt32(off+0x10, true)/4096;
obj.dimensions[2] = view.getInt32(off+0x14, true)/4096;
//44 bytes of unknown, ouch!
obj.came = view.getUint8(off+0x43);
obj.one = view.getUint32(off+0x44, true); //good ole one
obj.nextOff = off+0x48;
return obj;
}
handlers["CAME"] = function(view, off) { //cameras. not really much known about these right now.
var obj = {};
obj.pos1 = vec3.create();
obj.pos1[0] = view.getInt32(off, true)/4096;
obj.pos1[1] = view.getInt32(off+4, true)/4096;
obj.pos1[2] = view.getInt32(off+8, true)/4096;
obj.angle = vec3.create();
obj.angle[0] = view.getInt32(off+0xC, true)/4096;
obj.angle[1] = view.getInt32(off+0x10, true)/4096;
obj.angle[2] = view.getInt32(off+0x14, true)/4096;
obj.pos2 = vec3.create();
obj.pos2[0] = view.getInt32(off+0x18, true)/4096;
obj.pos2[1] = view.getInt32(off+0x1C, true)/4096;
obj.pos2[2] = view.getInt32(off+0x20, true)/4096;
obj.pos3 = vec3.create();
obj.pos3[0] = view.getInt32(off+0x24, true)/4096;
obj.pos3[1] = view.getInt32(off+0x28, true)/4096;
obj.pos3[2] = view.getInt32(off+0x2C, true)/4096;
//44 bytes of unknown, ouch!
obj.zoomSpeedM1 = view.getInt16(off+0x30, true)/4096;
obj.zoomStart = view.getInt16(off+0x32, true)/4096; //alters zoom somehow
obj.zoomEnd = view.getInt16(off+0x34, true)/4096;
obj.zoomSpeedM2 = view.getInt16(off+0x36, true)/4096;
obj.zoomMark1 = view.getInt16(off+0x38, true)/4096; //zoom speed changes at zoom marks
obj.zoomMark2 = view.getInt16(off+0x3A, true)/4096;
obj.zoomSpeed = view.getInt16(off+0x3C, true)/4096;
obj.camType = view.getInt16(off+0x3E, true);
obj.camRoute = view.getInt16(off+0x40, true);
obj.routeSpeed = view.getInt16(off+0x42, true);
obj.pointSpeed = view.getInt16(off+0x44, true);
obj.duration = view.getInt16(off+0x46, true);
obj.nextCam = view.getInt16(off+0x48, true);
obj.firstCam = view.getUint8(off+0x4A);
obj.one = view.getUint8(off+0x4B); //tends to be 1 if cam type is 5
obj.nextOff = off+0x4C;
return obj;
}
function readRGB(view, offset) {
var dat = view.getUint16(offset, true);
var col = [dat&31, (dat>>5)&31, (dat>>10)&31];
return col;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
if (input != null) {
if (typeof input == "string") {
var xml = new XMLHttpRequest();
xml.responseType = "arraybuffer";
xml.open("GET", input, true);
xml.onload = function() {
load(xml.response);
}
xml.send();
} else {
load(input, mkwii);
}
}
}

246
Code/Formats/nsbca.js Normal file
View File

@ -0,0 +1,246 @@
//
// nsbca.js
//--------------------
// Reads NSBCA files (bone animations) for use in combination with an NSBMD (model) file
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js
//
// most investigation done by florian for the mkds course modifier.
// I've tried to keep things much simpler than they were in his code.
window.nsbca = function(input) {
var mainOff;
var animData;
var speeds = [1.0, 0.5, 1/3];
var mainObj = this;
if (input != null) {
load(input);
}
this.load = load;
function load(input) {
var view = new DataView(input);
var header = null;
var offset = 0;
var tex;
//nitro 3d header
header = nitro.readHeader(view);
if (header.stamp != "BCA0") throw "NSBCA invalid. Expected BCA0, found "+header.stamp;
if (header.numSections > 1) throw "NSBCA invalid. Too many sections - should have 1 maximum.";
offset = header.sectionOffsets[0];
//end nitro
mainOff = offset;
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3);
if (stamp != "JNT0") throw "NSBCA invalid. Expected JNT0, found "+stamp;
animData = nitro.read3dInfo(view, mainOff+8, animInfoHandler);
mainObj.animData = animData;
}
function animInfoHandler(view, off, base) {
var offset = mainOff + view.getUint32(off, true);
var obj = {nextoff: off + 4}
readAnim(view, offset, obj);
return obj;
}
function readAnim(view, off, obj) {
obj.baseOff = off;
obj.stamp = readChar(view, off+0x0)+readChar(view, off+0x2)+readChar(view, off+0x3);
obj.frames = view.getUint16(off+0x4, true);
obj.numObj = view.getUint16(off+0x6, true);
obj.unknown = view.getUint32(off+0x8, true); //NOTE: this may be a flag. used later to specify extra frames if not = 3
obj.off1 = view.getUint32(off+0xC, true);
obj.off2 = view.getUint32(off+0x10, true); //offset to rotation data
off += 0x14;
var transforms = [];
for (var i=0; i<obj.numObj; i++) {
var off2 = view.getUint16(off, true)+obj.baseOff;
transforms.push(readTrans(view, off2, obj));
off += 2;
}
obj.trans = transforms;
}
function readTrans(view, off, obj) {
var flag = view.getUint16(off, true); //--zyx-Sr-RZYX-T-
off += 4;
var transform = {};
if (!((flag>>1) & 1)) { //T: translation
var translate = [[], [], []]; //store translations in x,y,z arrays
var tlExtra = [];
for (var i=0; i<3; i++) { //iterate over x y z (for translation)
var f = (flag>>(3+i))&1;
if (f) { //one value
translate[i].push(view.getInt32(off, true)/4096);
off += 4;
} else { //credit to florian for cracking this.
var inf = {};
inf.startFrame = view.getUint16(off, true)
var dat = view.getUint16(off+2, true)
inf.endFrame = dat&0x0FFF;
inf.halfSize = ((dat>>12)&3);
inf.speed = speeds[((dat>>14)&3)];
inf.off = view.getUint32(off+4, true);
var extra = (obj.unknown != 3)?0:(obj.frames-inf.endFrame);
var length = Math.floor((obj.frames+extra)*inf.speed);
var w = (inf.halfSize)?2:4;
var off2 = obj.baseOff+inf.off;
for (var j=0; j<length; j++) {
translate[i].push(((inf.halfSize)?view.getInt16(off2, true):view.getInt32(off2, true))/4096);
off2 += w;
}
tlExtra[i] = inf;
off += 8;
}
}
transform.translate = translate;
transform.tlExtra = tlExtra;
}
if (!((flag>>6) & 1)) { //R: rotation, which is both fun and exciting.
var rotate = [];
var rotExtra;
var f = (flag>>8)&1;
if (f) { //one value
rotate.push(readRotation(view, off, obj));
off += 4;
} else { //credit to florian for cracking this.
var inf = {};
inf.startFrame = view.getUint16(off, true)
var dat = view.getUint16(off+2, true) //low 12 bits are end frame, high 4 are size flag and speed
inf.endFrame = dat&0x0FFF;
inf.halfSize = ((dat>>12)&3); //not used by rotation?
inf.speed = speeds[((dat>>14)&3)];
inf.off = view.getUint32(off+4, true);
var extra = (obj.unknown != 3)?0:(obj.frames-inf.endFrame);
//florian's rotate code seems to ignore this extra value. I'll need more examples of nsbca to test this more thoroughly.
var length = Math.floor((obj.frames+extra)*inf.speed);
var off2 = obj.baseOff+inf.off;
try {
for (var j=0; j<length; j++) {
rotate.push(readRotation(view, off2, obj));
off2 += 2;
}
} catch (e) {
}
rotExtra = inf;
off += 8;
}
transform.rotate = rotate;
transform.rotExtra = rotExtra;
}
if (!((flag>>9) & 1)) { //S: scale
var scale = [[], [], []]; //store scales in x,y,z arrays
var scExtra = [];
for (var i=0; i<3; i++) { //iterate over x y z (for scale)
var f = (flag>>(11+i))&1;
if (f) { //one value
scale[i].push({
s1: view.getInt32(off, true)/4096,
s2: view.getInt32(off, true)/4096
});
off += 8;
} else { //credit to florian for cracking this.
var inf = {};
inf.startFrame = view.getUint16(off, true)
var dat = view.getUint16(off+2, true)
inf.endFrame = dat&0x0FFF;
inf.halfSize = ((dat>>12)&3);
inf.speed = speeds[((dat>>14)&3)];
inf.off = view.getUint32(off+4, true);
var extra = (obj.unknown != 3)?0:(obj.frames-inf.endFrame);
var length = Math.ceil((obj.frames+extra)*inf.speed);
var w = ((inf.halfSize)?2:4);
var off2 = obj.baseOff+inf.off;
for (var j=0; j<length; j++) {
scale[i].push({
s1: ((inf.halfSize)?view.getInt16(off2, true):view.getInt32(off2, true))/4096,
s2: ((inf.halfSize)?view.getInt16(off2+w, true):view.getInt32(off2+w, true))/4096
});
off2 += w*2;
}
scExtra[i] = inf;
off += 8;
}
}
transform.scale = scale;
transform.scExtra = scExtra;
}
return transform;
}
function readRotation(view, off, obj) {
var dat = view.getInt16(off, true);
var ind = (dat&0x7FFF);
var mode = (dat>>15);
if (mode) { //rotation is pivot
var off2 = obj.baseOff+obj.off1+ind*6; //jump to rotation data
return {
pivot: true,
param: view.getUint16(off2, true),
a: view.getInt16(off2+2, true)/4096,
b: view.getInt16(off2+4, true)/4096
};
} else {
var off2 = obj.baseOff+obj.off2+ind*10; //jump to rotation data
var d1 = view.getInt16(off2, true);
var d2 = view.getInt16(off2+2, true);
var d3 = view.getInt16(off2+4, true);
var d4 = view.getInt16(off2+6, true);
var d5 = view.getInt16(off2+8, true);
var i6 = ((d5&7)<<12) | ((d1&7)<<9) | ((d2&7)<<6) | ((d3&7)<<3) | ((d4&7));
if (i6&4096) i6 = (-8192)+i6;
var v1 = [d1>>3, d2>>3, d3>>3]
var v2 = [d4>>3, d5>>3, i6]
vec3.scale(v1, v1, 1/4096);
vec3.scale(v2, v2, 1/4096);
var v3 = vec3.cross([], v1, v2)
var mat = [
v1[0], v1[1], v1[2],
v2[0], v2[1], v2[2],
v3[0], v3[1], v3[2]
]
return {
pivot: false,
mat: mat
};
}
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
}

411
Code/Formats/nsbmd.js Normal file
View File

@ -0,0 +1,411 @@
//
// nsbmd.js
//--------------------
// Reads NSBMD models and any texture data within them.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js
// /formats/nsbtx.js
//
window.nsbmd = function(input) {
var mainOff, modelData, texPalOff, materials;
var mainObj = this;
if (input != null) {
load(input);
}
this.load = load;
function load(input) {
mainObj.hasBillboards = false;
var view = new DataView(input);
var header = null;
var offset = 0;
var tex;
//nitro 3d header
header = nitro.readHeader(view);
if (header.stamp != "BMD0") throw "NSBMD invalid. Expected BMD0, found "+header.stamp;
if (header.numSections > 2) throw "NSBMD invalid. Too many sections - should have 2 maximum.";
if (header.numSections == 2) tex = new nsbtx(input.slice(header.sectionOffsets[1]), true, true);
offset = header.sectionOffsets[0];
//end nitro
mainOff = offset;
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3);
if (stamp != "MDL0") throw "NSBMD invalid. Expected MDL0, found "+stamp;
mainObj.tex = tex;
modelData = nitro.read3dInfo(view, mainOff+8, modelInfoHandler);
mainObj.modelData = modelData;
}
function modelInfoHandler(view, offset) {
var mdlOff = view.getUint32(offset, true);
var off = mainOff+mdlOff;
var obj = readModelData(view, off);
obj.nextoff = offset+4;
return obj;
}
function readModelData(view, offset) {
var head = {}
head.blockSize = view.getUint32(offset, true);
head.bonesOffset = offset+view.getUint32(offset+4, true);
head.materialsOffset = offset+view.getUint32(offset+8, true);
head.polyStartOffset = offset+view.getUint32(offset+0xC, true);
head.polyEndOffset = offset+view.getUint32(offset+0x10, true);
head.numObjects = view.getUint8(offset+0x17);
head.numMaterials = view.getUint8(offset+0x18);
head.numPolys = view.getUint8(offset+0x19);
head.maxStack = view.getUint8(offset+0x1A);
head.scale = view.getInt32(offset+0x1C, true)/4096;
head.numVerts = view.getUint16(offset+0x24, true);
head.numSurfaces = view.getUint16(offset+0x26, true);
head.numTriangles = view.getUint16(offset+0x28, true);
head.numQuads = view.getUint16(offset+0x2A, true);
head.bboxX = view.getInt16(offset+0x2C, true)/4096;
head.bboxY = view.getInt16(offset+0x2E, true)/4096;
head.bboxZ = view.getInt16(offset+0x30, true)/4096;
head.bboxWidth = view.getInt16(offset+0x32, true)/4096;
head.bboxHeight = view.getInt16(offset+0x34, true)/4096;
head.bboxDepth = view.getInt16(offset+0x36, true)/4096;
//head.runtimeData = view.getUint64(offset+0x38, true);
texPalOff = head.materialsOffset; //leak into local scope so it can be used by tex and pal bindings
var objects = nitro.read3dInfo(view, offset+0x40, objInfoHandler);
var polys = nitro.read3dInfo(view, head.polyStartOffset, polyInfoHandler);
materials = nitro.read3dInfo(view, head.materialsOffset+4, matInfoHandler);
var tex = nitro.read3dInfo(view, head.materialsOffset+view.getUint16(head.materialsOffset, true), texInfoHandler);
var palt = nitro.read3dInfo(view, head.materialsOffset+view.getUint16(head.materialsOffset+2, true), palInfoHandler);
var commands = parseBones(head.bonesOffset, view, polys, materials, objects, head.maxStack);
return {head: head, objects: objects, polys: polys, materials: materials, tex:tex, palt:palt, commands:commands}
}
function parseBones(offset, view, polys, materials, objects, maxStack) {
var last;
var commands = [];
var freeStack = maxStack;
var forceID=null;
var lastMat = null;
while (offset<texPalOff) { //bones
last = view.getUint8(offset++);
console.log("bone cmd: 0x"+last.toString(16));
switch (last) {
case 0x06: //bind object transforms to parent. bone exists but is not placed in the stack
var obj = view.getUint8(offset++);
var parent = view.getUint8(offset++);
var zero = view.getUint8(offset++);
var object = objects.objectData[obj];
object.parent = parent;
commands.push({obj:obj, parent:parent, stackID:freeStack++});
break;
case 0x26:
case 0x46: //placed in the stack at stack id
var obj = view.getUint8(offset++);
var parent = view.getUint8(offset++);
var zero = view.getUint8(offset++);
var stackID = view.getUint8(offset++);
var object = objects.objectData[obj];
object.parent = parent;
commands.push({obj:obj, parent:parent, stackID:((last == 0x26)?stackID:freeStack++), restoreID:((last == 0x46)?stackID:null)});
break;
case 0x66: //has ability to restore to another stack id. no idea how this works
var obj = view.getUint8(offset++);
var parent = view.getUint8(offset++);
var zero = view.getUint8(offset++);
var stackID = view.getUint8(offset++);
var restoreID = view.getUint8(offset++);
var object = objects.objectData[obj];
object.parent = parent;
commands.push({obj:obj, parent:parent, stackID:stackID, restoreID:restoreID});
break;
case 0x04:
case 0x24:
case 0x44: //bind material to polygon: matID, 5, polyID
var mat = view.getUint8(offset++);
lastMat = mat;
var five = view.getUint8(offset++); //???
var poly = view.getUint8(offset++);
polys.objectData[poly].stackID = (forceID == null)?(commands[commands.length-1].stackID):forceID;
polys.objectData[poly].mat = mat;
break;
case 1:
break;
case 2: //node visibility (maybe to implement this set matrix to 0)
var node = view.getUint8(offset++);
var vis = view.getUint8(offset++);
objects.objectData[node].vis = vis;
console.log("visibility thing "+node);
if (node > 10) debugger;
break;
case 3: //stack id for poly (wit)
forceID = view.getUint8(offset++);
console.log("stackid is "+forceID);
case 0:
break;
case 5:
//i don't... what??
//holy shp!
var poly = view.getUint8(offset++);
polys.objectData[poly].stackID = (stackID == null)?(commands[commands.length-1].forceID):forceID;
polys.objectData[poly].mat = lastMat;
break;
case 7:
//sets object to be billboard
var obj = view.getUint8(offset++);
objects.objectData[obj].billboardMode = 1;
mainObj.hasBillboards = true;
break;
case 8:
//sets object to be billboard around only y axis. (xz remain unchanged)
var obj = view.getUint8(offset++);
objects.objectData[obj].billboardMode = 2;
mainObj.hasBillboards = true;
break;
case 0x0b:
break; //begin, not quite sure what of. doesn't seem to change anything
case 0x2b:
break; //end
default:
console.log("bone transform unknown: "+last);
break;
}
}
//if (window.throwWhatever) debugger;
return commands;
}
function matInfoHandler(view, off, base) {
var offset = texPalOff + view.getUint32(off, true);
var rel = 0;
/*while (rel < 40) {
var flags = view.getUint16(offset+rel, true);
if ((flags&15)==15) console.log("rel at "+rel);
rel += 2;
}*/
var polyAttrib = view.getUint16(offset+12, true);
console.log(polyAttrib);
var flags = view.getUint16(offset+22, true); //other info in here is specular data etc.
//scale starts at 44;
var mat;
offset += 44;
switch ((flags>>14) & 0x03) { //texture scaling mode
case 0:
mat = mat3.create(); //no scale
break;
case 1:
mat = mat3.create();
mat3.scale(mat, mat, [view.getInt32(offset, true)/4096, view.getInt32(offset+4, true)/4096]);
//mat3.translate(mat, mat, [-anim.translateS[(texFrame>>anim.frameStep.translateS)%anim.translateS.length], anim.translateT[(texFrame>>anim.frameStep.translateT)%anim.translateT.length]]) //for some mystery reason I need to negate the S translation
break;
case 2:
case 3:
mat = mat3.create(); //custom tex mat
alert("custom");
for (var i=0; i<16; i++) {
mat[i] = view.getInt32(offset, true)/4096;
offset += 4;
}
}
var cullMode = ((polyAttrib>>6)&3);
var alpha = ((polyAttrib>>16)&31)/31;
if (alpha == 0) alpha = 1;
return {
height: 8 << ((flags>>7)&7),
width: 8 << ((flags>>4)&7),
repeatX: flags&1,
repeatY: (flags>>1)&1,
flipX: (flags>>2)&1,
flipY: (flags>>3)&1,
texMat: mat,
alpha: alpha,
cullMode: cullMode,
nextoff: off + 4
}
}
function texInfoHandler(view, off, base, ind) {
var oDat = texPalOff+view.getUint16(off, true); //contains offset to array of materials to bind to
var num = view.getUint8(off+2, true);
var mats = [];
for (var i=0; i<num; i++) {
var mat = view.getUint8(oDat++);
materials.objectData[mat].tex = ind; //bind to this material
mats.push(mat);
}
return {
mats: mats,
nextoff: off + 4
}
}
function palInfoHandler(view, off, base, ind) {
var oDat = texPalOff+view.getUint16(off, true); //contains offset to array of materials to bind to
var num = view.getUint8(off+2, true);
var mats = [];
for (var i=0; i<num; i++) {
var mat = view.getUint8(oDat++);
materials.objectData[mat].pal = ind; //bind to this material
mats.push(mat);
}
return {
mats: mats,
nextoff: off + 4
}
}
function polyInfoHandler(view, off, base) {
var offset = base + view.getUint32(off, true);
var dlStart = offset+view.getUint32(offset+8, true);
var displayList = view.buffer.slice(dlStart, dlStart+view.getUint32(offset+0xC, true))
return {
nextoff: off + 4,
disp: displayList
}
}
function objInfoHandler(view, off, base) {
var offset = base + view.getUint32(off, true);
var flag = view.getUint16(offset, true); //flag format nnnn psrt
var rotTerm1 = view.getInt16(offset+0x2, true)/4096; //first term of rotate mat if present
var translate = vec3.create();
if (!(flag&1)) { //translate (t) flag is 0
translate[0] = view.getInt32(offset+0x4, true)/4096;
translate[1] = view.getInt32(offset+0x8, true)/4096;
translate[2] = view.getInt32(offset+0xC, true)/4096;
offset += 0xC;
}
var pivot;
var A, B, neg, mode;
if (flag&8) { //pivot exists
pivot = new Float32Array([0,0,0,0,0,0,0,0,0]);
mode = (flag>>4)&15;
neg = (flag>>8)&15;
A = view.getInt16(offset+0x4, true)/4096;
B = view.getInt16(offset+0x6, true)/4096;
pivot[mode] = (neg&1)?-1:1;
var horiz = mode%3;
var vert = Math.floor(mode/3)
var left = (horiz==0)?1:0; var top = ((vert==0)?1:0)*3;
var right = (horiz==2)?1:2; var btm = ((vert==2)?1:2)*3;
pivot[left+top] = A;
pivot[right+top] = B;
pivot[left+btm] = (neg&2)?-B:B;
pivot[right+btm] = (neg&4)?-A:A;
offset += 4;
} else {
pivot = mat3.create()
}
var scale = vec3.create();
if (!(flag&4)) {
scale[0] = view.getInt32(offset+0x4, true)/4096;
scale[1] = view.getInt32(offset+0x8, true)/4096;
scale[2] = view.getInt32(offset+0xC, true)/4096;
offset += 0xC;
} else {
scale[0] = 1;
scale[1] = 1;
scale[2] = 1;
}
if ((!(flag&8)) && (!(flag&2))) { //rotate matrix, replaces pivot
pivot[0] = rotTerm1;
pivot[1] = view.getInt16(offset+0x4, true)/4096;
pivot[2] = view.getInt16(offset+0x6, true)/4096;
pivot[3] = view.getInt16(offset+0x8, true)/4096;
pivot[4] = view.getInt16(offset+0xA, true)/4096;
pivot[5] = view.getInt16(offset+0xC, true)/4096;
pivot[6] = view.getInt16(offset+0xE, true)/4096;
pivot[7] = view.getInt16(offset+0x10, true)/4096;
pivot[8] = view.getInt16(offset+0x12, true)/4096;
offset += 16;
}
var mat = mat4.create();
mat4.translate(mat, mat, translate);
mat4.multiply(mat, mat, mat4FromMat3(pivot));
mat4.scale(mat, mat, scale);
return {
translate: translate,
pivot: pivot,
pA: A,
pB: B,
pMode: mode,
pNeg: neg,
scale: scale,
flag: flag,
mat: mat,
billboardMode: 0,
nextoff: off + 4
}
}
function mat4FromMat3(mat) {
dest = mat4.create();
dest[0] = mat[0];
dest[1] = mat[1];
dest[2] = mat[2];
dest[3] = 0;
dest[4] = mat[3];
dest[5] = mat[4];
dest[6] = mat[5];
dest[7] = 0;
dest[8] = mat[6];
dest[9] = mat[7];
dest[10] = mat[8];
dest[11] = 0;
dest[12] = 0;
dest[13] = 0;
dest[14] = 0;
dest[15] = 1;
return dest;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
}

142
Code/Formats/nsbta.js Normal file
View File

@ -0,0 +1,142 @@
//
// nsbta.js
//--------------------
// Reads NSBTA files (texture uv animation via uv transform matrices within a polygon) for use in combination with an NSBMD (model) file
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js
//
// man oh man if only there were some documentation on this that weren't shoddily written code in mkds course modifier
// well i guess we can find out how the format works
// together :')
window.nsbta = function(input) {
var mainOff;
var animData;
var mainObj = this;
var prop = [
"scaleS",
"scaleT",
"rotation",
"translateS",
"translateT"
]
if (input != null) {
load(input);
}
this.load = load;
function load(input) {
var view = new DataView(input);
var header = null;
var offset = 0;
var tex;
//nitro 3d header
header = nitro.readHeader(view);
if (header.stamp != "BTA0") throw "NSBTA invalid. Expected BTA0, found "+header.stamp;
if (header.numSections > 1) throw "NSBTA invalid. Too many sections - should have 1 maximum.";
offset = header.sectionOffsets[0];
//end nitro
mainOff = offset;
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3);
if (stamp != "SRT0") throw "NSBTA invalid. Expected SRT0, found "+stamp;
animData = nitro.read3dInfo(view, mainOff+8, animInfoHandler);
mainObj.animData = animData;
}
function animInfoHandler(view, offset) {
var animOff = view.getUint32(offset, true);
var off = mainOff+animOff;
var obj = readAnimData(view, off);
obj.nextoff = offset+4;
return obj;
}
function readAnimData(view, offset) {
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); //should be M_AT, where _ is a 0 character
var unknown1 = view.getUint16(offset+4, true);
var unknown2 = view.getUint8(offset+6, false);
var unknown3 = view.getUint8(offset+7, false);
var data = nitro.read3dInfo(view, offset+8, matInfoHandler);
return {data: data, nextoff: data.nextoff};
}
function matInfoHandler(view, offset, base) {
// there doesn't seem to be any documentation on this so I'm going to take the first step and maybe explain a few things here:
// each material has 5 sets of 16 bit values of the following type:
//
// frames: determines the number of frames worth of transforms of this type are stored
// flags: if >4096 then multiple frames are used instead of inline data. not much else is known
// offset/data: depending on previous flag, either points to an array of data or provides the data for the sole frame. relative to base of this 3dinfoobject
// data2: used for rotation matrix (second value)
//
// order is as follows:
// scaleS, scaleT, rotation, translateS, translateT (all values are signed fixed point 1.3.12)
//
// note: rotation external data has two 16 bit integers instead of one per frame.
//
// also!! rotation matrices work as follows:
//
// | B A |
// | -A B |
//
// kind of like nsbmd pivot
var obj = {}
obj.flags = []; //for debug
obj.frames = [];
obj.frameStep = {};
for (var i=0; i<5; i++) {
obj[prop[i]] = [];
var frames = view.getUint16(offset, true);
var flags = view.getUint16(offset+2, true);
var value = view.getUint16(offset+4, true);
var data2 = view.getInt16(offset+6, true)/4096;
//flags research so far:
//bit 13 (8196) - set if inline single frame data, unset if multiple frame data at offset
//bit 14-15 - framestep, aka what to shift frame counters by (eg for half framerate this would be 1, frame>>1, essentially dividing the frame speed by 2.)
obj.frameStep[prop[i]] = (flags>>14);
obj.flags[i] = flags;
obj.frames[i] = frames;
if (flags & 8192) {
if (value & 32768) value = 65536-value; //convert to int
obj[prop[i]].push(value/4096);
if (i == 2) obj[prop[i]].push(data2);
} else { //data is found at offset
frames = frames>>obj.frameStep[prop[i]];
//frames -= 1;
var off = base + value-8;
for (var j=0; j<frames*((i==2)?2:1); j++) {
var prevvalue = view.getInt16(off-2, true)/4096;
//debugger;
obj[prop[i]].push(view.getInt16(off, true)/4096);
off += 2;
}
}
offset += 8;
}
obj.nextoff = offset;
return obj;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
}

158
Code/Formats/nsbtp.js Normal file
View File

@ -0,0 +1,158 @@
//
// nsbtp.js
//--------------------
// Reads NSBTP files (texture info animation) for use in combination with an NSBMD (model) file
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js
//
window.nsbtp = function(input) {
var mainOff, matOff;
var animData;
//anim data structure:
// {
// objectData: [
// {
// obj: { }
// }
// ]
// }
var mainObj = this;
var prop = [
"scaleS",
"scaleT",
"rotation",
"translateS",
"translateT"
]
if (input != null) {
load(input);
}
this.load = load;
function load(input) {
var view = new DataView(input);
var header = null;
var offset = 0;
var tex;
//nitro 3d header
header = nitro.readHeader(view);
if (header.stamp != "BTP0") throw "NSBTP invalid. Expected BTP0, found "+header.stamp;
if (header.numSections > 1) throw "NSBTP invalid. Too many sections - should have 1 maximum.";
offset = header.sectionOffsets[0];
//end nitro
mainOff = offset;
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3);
if (stamp != "PAT0") throw "NSBTP invalid. Expected PAT0, found "+stamp;
animData = nitro.read3dInfo(view, mainOff+8, animInfoHandler);
debugger;
mainObj.animData = animData;
}
function animInfoHandler(view, offset) {
var animOff = view.getUint32(offset, true);
var off = mainOff+animOff;
var obj = readAnimData(view, off);
obj.nextoff = offset+4;
return obj;
}
function readAnimData(view, offset) {
matOff = offset;
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); //should be M_PT, where _ is a 0 character
offset += 4;
//b400 0303 4400 7400 - countdown (3..2..1.. then start is another model, duration 180 frames, 3 frames of anim)
//1400 0404 4800 8800 - kuribo (4 frames, shorter animation duration)
//1e00 0202 4000 6000 - pinball stage (2 frames)
//0200 0202 4000 6000 - fish, cow and crab (duration and total 2 frames, unusually short animation)
//0d00 0404 5000 9000 - bat (duration 13, 6 frames, uneven pacing)
//16bit duration (60fps frames, total)
//8bit tex start
//8bit pal start
//16bit unknown (flags? kuribo repeats by playing backwards)
//16bit unknown
//example data, for 3 mat 3 pal data
//var tinfo = texInfoHandler(view, offset+4);
//8 bytes here? looks like texinfo
var duration = view.getUint16(offset, true);
var tframes = view.getUint8(offset+2);
var pframes = view.getUint8(offset+3);
var unknown = view.getUint16(offset+4, true);
var unknown2 = view.getUint16(offset+6, true);
//...then another nitro
var data = nitro.read3dInfo(view, offset+8, matInfoHandler);
return {data: data, nextoff: data.nextoff, tframes:tframes, pframes:pframes, unknown:unknown, unknown2:unknown2, duration:duration};
}
function matInfoHandler(view, offset, base) {
var obj = {}
obj.frames = [];
// in here...
// 16bit frames
// 16bit maybe material number (probably? mostly 0) to replace
// 16bit unknown (flags? 0x4400 count, 0x1101 waluigi, 0x3303 goomba, 0x0010 fish)
// 16bit offset from M_PT (always 0x38)
//at offset (frame of these)
// 16bit happenAt
// 8bit tex
// 8bit pal
//then (frame of these)
// 16char texname
//then (frame of these)
// 16char palname
var frames = view.getUint16(offset, true);
obj.matinfo = view.getUint16(offset+2, true);
obj.flags = view.getUint16(offset+4, true);
var offset2 = view.getUint16(offset+6, true);
offset += 8;
obj.nextoff = offset;
offset = matOff + offset2;
//info and timing for each frame
for (var i=0; i<frames; i++) {
obj.frames[i] = {
time: view.getUint16(offset, true),
tex: view.getUint8(offset+2),
mat: view.getUint8(offset+3),
}
offset += 4;
}
//read 16char tex names
for (var i=0; i<frames; i++) {
}
//read 16char pal names
for (var i=0; i<frames; i++) {
}
return obj;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
}

277
Code/Formats/nsbtx.js Normal file
View File

@ -0,0 +1,277 @@
//
// nsbtx.js
//--------------------
// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js
//
window.nsbtx = function(input, tex0) {
var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff,
compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff,
palOffset, mainOff
var textureInfo, paletteInfo, palData, texData, compData, compInfoData, colourBuffer
var thisObj = this;
var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16]
if (input != null) {
load(input, tex0);
}
this.load = load;
this.readTexWithPal = readTexWithPal;
this.cache = {}; //textures for btx are cached in this object.
this.scopeEval = function(code) {return eval(code)} //for debug purposes
function load(input, tex0) {
colourBuffer = new Uint32Array(4);
var view = new DataView(input);
var header = null;
var offset = 0;
if (!tex0) { //nitro 3d header
header = nitro.readHeader(view);
if (header.stamp != "BTX0") throw "nsbtx invalid. Expected BTX0, found "+header.stamp;
if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one.";
offset = header.sectionOffsets[0];
}
mainOff = offset;
var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3);
if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp;
var size = view.getUint32(offset+0x04, true);
texDataSize = view.getUint16(offset+0x0C, true)<<3;
texInfoOff = view.getUint16(offset+0x0E, true);
texOffset = view.getUint16(offset+0x14, true);
compTexSize = view.getUint16(offset+0x1C, true)<<3;
compTexInfoOff = view.getUint16(offset+0x1E, true);
compTexOffset = view.getUint32(offset+0x24, true);
compTexInfoDataOff = view.getUint32(offset+0x28, true);
palSize = view.getUint32(offset+0x30, true)<<3;
palInfoOff = view.getUint32(offset+0x34, true);
palOffset = view.getUint32(offset+0x38, true);
//read palletes, then textures.
var po = mainOff + palOffset;
palData = input.slice(po, po+palSize);
var to = mainOff + texOffset;
texData = input.slice(to, to+texDataSize);
var co = mainOff + compTexOffset;
compData = input.slice(co, co+compTexSize); //pixel information for compression. 2bpp, 16 pixels, so per 4x4 block takes up 4 bytes
var cio = mainOff + compTexInfoDataOff;
compInfoData = input.slice(cio, cio+compTexSize/2); //each 4x4 block has a 16bit information uint. 2 bytes per block, thus half the size of above.
paletteInfo = nitro.read3dInfo(view, mainOff + palInfoOff, palInfoHandler);
textureInfo = nitro.read3dInfo(view, mainOff + texInfoOff, texInfoHandler);
thisObj.paletteInfo = paletteInfo;
thisObj.textureInfo = textureInfo;
}
function readTexWithPal(textureId, palId) {
var tex = textureInfo.objectData[textureId];
var pal = paletteInfo.objectData[palId];
var format = tex.format;
var trans = tex.pal0trans;
if (format == 5) return readCompressedTex(tex, pal); //compressed 4x4 texture, different processing entirely
var off = tex.texOffset;
var palView = new DataView(palData);
var texView = new DataView(texData);
var palOff = pal.palOffset;
var canvas = document.createElement("canvas");
canvas.width = tex.width;
canvas.height = tex.height;
var ctx = canvas.getContext("2d");
var img = ctx.getImageData(0, 0, tex.width, tex.height);
var total = tex.width*tex.height;
var databuf;
for (var i=0; i<total; i++) {
var col;
if (format == 1) { //A3I5 encoding. 3 bits alpha 5 bits pal index
var dat = texView.getUint8(off++)
col = readPalColour(palView, palOff, dat&31, trans);
col[3] = (dat>>5)*(255/7);
} else if (format == 2) { //2 bit pal
if (i%4 == 0) databuf = texView.getUint8(off++);
col = readPalColour(palView, palOff, (databuf>>((i%4)*2))&3, trans)
} else if (format == 3) { //4 bit pal
if (i%2 == 0) {
databuf = texView.getUint8(off++);
col = readPalColour(palView, palOff, databuf&15, trans)
} else {
col = readPalColour(palView, palOff, databuf>>4, trans)
}
} else if (format == 4) { //8 bit pal
col = readPalColour(palView, palOff, texView.getUint8(off++), trans)
} else if (format == 6) { //A5I3 encoding. 5 bits alpha 3 bits pal index
var dat = texView.getUint8(off++)
col = readPalColour(palView, palOff, dat&7, trans);
col[3] = (dat>>3)*(255/31);
} else if (format == 7) { //raw color data
col = texView.getUint16(off, true);
colourBuffer[0] = Math.round(((col&31)/31)*255)
colourBuffer[1] = Math.round((((col>>5)&31)/31)*255)
colourBuffer[2] = Math.round((((col>>10)&31)/31)*255)
colourBuffer[3] = Math.round((col>>15)*255);
col = colourBuffer;
off += 2;
} else {
console.log("texture format is none, ignoring")
return canvas;
}
img.data.set(col, i*4);
}
ctx.putImageData(img, 0, 0)
return canvas;
}
function readCompressedTex(tex, pal) { //format 5, 4x4 texels. I'll keep this well documented so it's easy to understand.
var off = tex.texOffset;
var texView = new DataView(compData); //real texture data - 32 bits per 4x4 block (one byte per 4px horizontal line, each descending 1px)
var compView = new DataView(compInfoData); //view into compression info - informs of pallete and parameters.
var palView = new DataView(palData); //view into the texture pallete
var compOff = off/2; //info is 2 bytes per block, so the offset is half that of the tex offset.
var palOff = pal.palOffset;
var transColor = new Uint8Array([0, 0, 0, 0]); //transparent black
var canvas = document.createElement("canvas");
canvas.width = tex.width;
canvas.height = tex.height;
var ctx = canvas.getContext("2d");
var img = ctx.getImageData(0, 0, tex.width, tex.height);
var w = tex.width>>2; //iterate over blocks, block w and h is /4.
var h = tex.height>>2;
for (var y=0; y<h; y++) {
for (var x=0; x<w; x++) {
//inside block
var bInfo = compView.getUint16(compOff, true); //block info
var addr = (bInfo & 0x3fff); //offset to relevant pallete
var mode = ((bInfo >> 14) & 3);
var finalPo = palOff+addr*4;
var imgoff = x*4+(y*w*16);
for (var iy=0; iy<4; iy++) {
var dat = texView.getUint8(off++);
for (var ix=0; ix<4; ix++) { //iterate over horiz lines
var part = (dat>>(ix*2))&3;
var col;
switch (mode) {
case 0: //value 3 is transparent, otherwise pal colour
if (part == 3) col = transColor;
else col = readPalColour(palView, finalPo, part);
break;
case 1: //average mode - colour 2 is average of 1st two, 3 is transparent. 0&1 are normal.
if (part == 3) col = transColor;
else if (part == 2) col = readFractionalPal(palView, finalPo, 0.5);
else col = readPalColour(palView, finalPo, part);
break;
case 2: //pal colour
col = readPalColour(palView, finalPo, part);
break;
case 3: //5/8 3/8 mode - colour 2 is 5/8 of col0 plus 3/8 of col1, 3 is 3/8 of col0 plus 5/8 of col1. 0&1 are normal.
if (part == 3) col = readFractionalPal(palView, finalPo, 3/8);
else if (part == 2) col = readFractionalPal(palView, finalPo, 5/8);
else col = readPalColour(palView, finalPo, part);
break;
}
img.data.set(col, (imgoff++)*4)
}
imgoff += tex.width-4;
}
compOff += 2; //align off to next block
}
}
ctx.putImageData(img, 0, 0)
return canvas;
}
function readPalColour(view, palOff, ind, pal0trans) {
var col = view.getUint16(palOff+ind*2, true);
var f = 255/31;
colourBuffer[0] = Math.round((col&31)*f)
colourBuffer[1] = Math.round(((col>>5)&31)*f)
colourBuffer[2] = Math.round(((col>>10)&31)*f)
colourBuffer[3] = (pal0trans && ind == 0)?0:255;
return colourBuffer;
}
function readFractionalPal(view, palOff, i) {
var col = view.getUint16(palOff, true);
var col2 = view.getUint16(palOff+2, true);
var ni = 1-i;
var f = 255/31;
colourBuffer[0] = Math.round((col&31)*f*i + (col2&31)*f*ni)
colourBuffer[1] = Math.round(((col>>5)&31)*f*i + ((col2>>5)&31)*f*ni)
colourBuffer[2] = Math.round(((col>>10)&31)*f*i + ((col2>>10)&31)*f*ni)
colourBuffer[3] = 255;
return colourBuffer;
}
function palInfoHandler(view, offset) {
var palOffset = view.getUint16(offset, true)<<3;
var unknown = view.getUint16(offset+2, true);
return {
palOffset: palOffset,
unknown: unknown,
nextoff: offset+4
}
}
function texInfoHandler(view, offset) {
var texOffset = view.getUint16(offset, true)<<3;
var flags = view.getUint16(offset+2, true);
var width2 = view.getUint8(offset+4, true);
var unknown = view.getUint8(offset+5, true);
var height2 = view.getUint8(offset+6, true);
var unknown2 = view.getUint8(offset+7, true);
return {
texOffset: texOffset,
pal0trans: (flags>>13)&1, //two top flags are texture matrix modes. not sure if it really matters (except for nsbta animation maybe, but 0 = no transform and things that have tex animations are set to 0 anyways).
format: ((flags>>10)&7),
height: 8 << ((flags>>7)&7),
width: 8 << ((flags>>4)&7),
repeatX: flags&1,
repeatY: (flags>>1)&1,
flipX: (flags>>2)&1,
flipY: (flags>>3)&1,
unkWidth: width2,
unk1: unknown,
unkHeight: height2,
unk2: unknown2,
nextoff: offset+8
}
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
}

102
Code/Formats/sbnk.js Normal file
View File

@ -0,0 +1,102 @@
//
// sbnk.js
//--------------------
// Reads sbnk files.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
//
window.sbnk = function(input, dataView) {
var t = this;
this.load = load;
function load(input, dataView) {
var view = (dataView)?input:(new DataView(input));
var header = null;
var offset = 0;
var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3);
if (stamp != "SBNK") throw "SWAV invalid. Expected SWAV, found "+stamp;
offset += 16;
var data = readChar(view, offset)+readChar(view, offset+1)+readChar(view, offset+2)+readChar(view, offset+3);
if (data != "DATA") throw "SWAV invalid, expected DATA, found "+data;
offset += 8;
offset += 32; //skip reserved
var numInst = view.getUint32(offset, true);
t.instruments = [];
offset += 4;
for (var i=0; i<numInst; i++) {
var fRecord = view.getUint8(offset);
var nOffset = view.getUint16(offset+1, true);
if (fRecord == 0) {
t.instruments.push({type:0});
} else if (fRecord < 16) { //note/wave definition
var obj = readParams(view, nOffset);
obj.type = 1;
t.instruments.push(obj);
} else if (fRecord == 16) {
var obj = {};
obj.lower = view.getUint8(nOffset++);
obj.upper = view.getUint8(nOffset++);
obj.entries = []
var notes = (obj.upper-obj.lower)+1;
for (var j=0; j<notes; j++) {
obj.entries.push(readParams(view, nOffset+2));
nOffset += 12;
}
obj.type = 2;
t.instruments.push(obj);
} else if (fRecord == 17) {
var obj = {};
obj.regions = [];
for (var j=0; j<8; j++) {
var dat = view.getUint8(nOffset+j);
if (dat != 0) obj.regions.push(dat);
else break;
}
obj.entries = [];
nOffset += 8;
for (var j=0; j<obj.regions.length; j++) {
obj.entries.push(readParams(view, nOffset+2));
nOffset += 12;
}
obj.type = 3;
t.instruments.push(obj);
}
offset += 4;
}
}
function readParams(view, off) {
var obj = {};
obj.swav = view.getUint16(off, true);
obj.swar = view.getUint16(off+2, true);
obj.note = view.getUint8(off+4);
obj.freq = noteToFreq(obj.note);
obj.attack = view.getUint8(off+5);
obj.decay = view.getUint8(off+6);
obj.sustainLvl = view.getUint8(off+7);
obj.release = view.getUint8(off+8);
obj.pan = view.getUint8(off+9);
return obj;
}
function noteToFreq(n) {
return Math.pow(2, (n-49)/12)*440;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
if (input != null) {
load(input, dataView);
}
}

168
Code/Formats/sdat.js Normal file
View File

@ -0,0 +1,168 @@
//
// sdat.js
//--------------------
// Reads sdat archives.
// Right now this just loads literally every resource in the sdat since in js there is no such thing as half loading a
// file from local storage, so why not just load it once and store in a usable format.
//
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
//
window.sdat = function(input) {
var t = this;
this.sections = {};
this.load = load;
function load(input) {
t.buffer = input;
var view = new DataView(input);
var header = null;
var offset = 0;
var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3);
if (stamp != "SDAT") throw "SDAT invalid. Expected SDAT, found "+stamp;
var unknown1 = view.getUint32(0x4, true);
var filesize = view.getUint32(0x8, true);
var headsize = view.getUint16(0xC, true);
var numSections = view.getUint16(0xE, true);
var sectionOffsets = [];
var sectionSizes = [];
for (var i=3; i>-1; i--) { //reverse order so we can process files into js objects
var off = (view.getUint32(0x10+i*8, true));
var size = (view.getUint32(0x14+i*8, true));
if (size != 0) readSection(view, off);
}
}
function readSection(view, off) {
var stamp = "$"+readChar(view, off)+readChar(view, off+1)+readChar(view, off+2)+readChar(view, off+3);
if (sectionFunc[stamp] != null) t.sections[stamp] = sectionFunc[stamp](view, off+8);
else console.error("Invalid section in SDAT! No handler for section type "+stamp.substr(1, 4));
}
var sectionFunc = {}
sectionFunc["$SYMB"] = function(view, off) {
}
sectionFunc["$INFO"] = function(view, off) {
var obj = [];
for (var i=0; i<8; i++) {
var relOff = off+view.getUint32(off+i*4, true)-8;
var count = view.getUint32(relOff, true);
obj[i] = [];
relOff += 4;
var last = null;
for (var j=0; j<count; j++) {
var infoOff = view.getUint32(relOff, true);
//WRONG
last = recordInfoFunc[i](view, off+infoOff-8);//(infoOff == 0 && last != null)?last.nextOff:(off+infoOff-8));
obj[i][j] = last;
relOff += 4;
}
}
console.log(obj);
return obj;
}
sectionFunc["$FAT "] = function(view, off) {
var a = [];
var count = view.getUint32(off, true);
off += 4;
for (var i=0; i<count; i++) {
var obj = {};
obj.off = view.getUint32(off, true);
obj.size = view.getUint32(off+4, true);
off += 16;
a.push(obj);
}
console.log(a);
return a;
}
sectionFunc["$FILE"] = function(view, off) {
console.log("file");
}
var recordInfoFunc = []
recordInfoFunc[0] = function(view, off) {
var obj = {};
obj.fileID = view.getUint16(off, true);
obj.seq = new sseq(getFile(obj.fileID));
obj.pc = 0;
obj.unknown = view.getUint16(off+2, true);
obj.bank = view.getUint16(off+4, true);
obj.vol = view.getUint8(off+6);
obj.cpr = view.getUint8(off+7);
obj.ppr = view.getUint8(off+8);
obj.ply = view.getUint8(off+9);
obj.nextOff = off+10;
return obj;
}
recordInfoFunc[1] = function(view, off) {
var obj = {};
obj.fileID = view.getUint16(off, true);
obj.arc = new ssar(getFile(obj.fileID));
obj.unknown = view.getUint16(off+2, true);
obj.nextOff = off+4;
return obj;
}
recordInfoFunc[2] = function(view, off) {
var obj = {};
obj.fileID = view.getUint16(off, true);
obj.unknown = view.getUint16(off+2, true);
obj.bank = new sbnk(getFile(obj.fileID));
obj.waveArcs = [];
off += 4;
for (var i=0; i<4; i++) {
obj.waveArcs[i] = view.getUint16(off, true);
off += 2;
}
obj.nextOff = off;
return obj;
}
recordInfoFunc[3] = function(view, off) {
var obj = {};
obj.fileID = view.getUint16(off, true);
obj.unknown = view.getUint16(off+2, true);
obj.arc = new swar(getFile(obj.fileID));
obj.nextOff = off+4;
return obj;
}
recordInfoFunc[4] = function(view, off) {}
recordInfoFunc[5] = function(view, off) {}
recordInfoFunc[6] = function(view, off) {}
recordInfoFunc[7] = function(view, off) {
var obj = {};
obj.fileID = view.getUint16(off, true);
obj.unknown = view.getUint16(off+2, true);
obj.vol = view.getUint8(off+4);
obj.pri = view.getUint8(off+5);
obj.ply = view.getUint8(off+6);
obj.nextOff = off+7;
return obj;
}
function getFile(fid) {
var file = t.sections["$FAT "][fid];
if (file != null) {
return t.buffer.slice(file.off, file.off+file.size);
}
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
if (input != null) {
load(input);
}
}

56
Code/Formats/ssar.js Normal file
View File

@ -0,0 +1,56 @@
//
// ssar.js
//--------------------
// Reads ssar files.
// by RHY3756547
//
window.ssar = function(input) {
var t = this;
this.load = load;
function load(input) {
var view = new DataView(input);
var header = null;
var offset = 0;
var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3);
if (stamp != "SSAR") throw "SSAR invalid. Expected SSAR, found "+stamp;
offset += 16;
var data = readChar(view, offset)+readChar(view, offset+1)+readChar(view, offset+2)+readChar(view, offset+3);
if (data != "DATA") throw "SSAR invalid, expected DATA, found "+data;
offset += 8;
t.dataOff = view.getUint32(offset, true);
t.data = new Uint8Array(view.buffer.slice(t.dataOff));
var count = view.getUint32(offset+4, true);
t.entries = [];
offset += 8;
for (var i=0; i<count; i++) {
t.entries.push(readSeqEntry(view, offset));
offset += 12;
}
}
function readSeqEntry(view, off) {
var obj = {};
obj.pc = view.getUint32(off, true);
obj.seq = {data:t.data};
obj.bank = view.getUint16(off+4, true);
obj.vol = view.getUint8(off+6);
obj.cpr = view.getUint8(off+7);
obj.ppr = view.getUint8(off+8);
obj.ply = view.getUint8(off+9);
return obj;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
if (input != null) {
load(input);
}
}

34
Code/Formats/sseq.js Normal file
View File

@ -0,0 +1,34 @@
//
// sseq.js
//--------------------
// Reads sseq files.
// by RHY3756547
//
window.sseq = function(input) {
var t = this;
this.load = load;
function load(input, archived) {
var view = new DataView(input);
var header = null;
var offset = 0;
var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3);
if (stamp != "SSEQ") throw "SSEQ invalid. Expected SSEQ, found "+stamp;
offset += 16;
var data = readChar(view, offset)+readChar(view, offset+1)+readChar(view, offset+2)+readChar(view, offset+3);
if (data != "DATA") throw "SWAV invalid, expected DATA, found "+data;
offset += 8;
t.data = new Uint8Array(input.slice(view.getUint32(offset, true)));
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
if (input != null) {
load(input);
}
}

43
Code/Formats/swar.js Normal file
View File

@ -0,0 +1,43 @@
//
// swar.js
//--------------------
// Reads swar files.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
//
window.swar = function(input, dataView) {
var t = this;
this.load = load;
function load(input, dataView) {
var view = (dataView)?input:(new DataView(input));
var header = null;
var offset = 0;
var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3);
if (stamp != "SWAR") throw "SWAR invalid. Expected SWAR, found "+stamp;
offset += 16; //skip magic number, size and number of blocks
var data = readChar(view, offset)+readChar(view, offset+1)+readChar(view, offset+2)+readChar(view, offset+3);
if (data != "DATA") throw "SWAV invalid, expected DATA, found "+data;
offset += 40; //skip reserved 0s and size
var nSamples = view.getUint32(offset, true);
offset += 4;
t.samples = [];
for (var i=0; i<nSamples; i++) {
t.samples.push(new swav(new DataView(input, view.getUint32(offset, true)), false, true));
offset += 4;
}
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
if (input != null) {
load(input, dataView);
}
}

128
Code/Formats/swav.js Normal file
View File

@ -0,0 +1,128 @@
//
// swav.js
//--------------------
// Reads swav files.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
//
window.swav = function(input, hasHead, dataView) {
var t = this;
this.load = load;
this.getAudioBuffer = getAudioBuffer;
function load(input, hasHead, dataView) {
var view = (dataView)?input:(new DataView(input));
var header = null;
var offset = 0;
if (hasHead) {
var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3);
if (stamp != "SWAV") throw "SWAV invalid. Expected SWAV, found "+stamp;
offset += 16;
var data = readChar(view, offset)+readChar(view, offset+1)+readChar(view, offset+2)+readChar(view, offset+3);
if (data != "DATA") throw "SWAV invalid, expected DATA, found "+data;
offset += 8;
}
t.waveType = view.getUint8(offset);
t.bLoop = view.getUint8(offset+1);
t.nSampleRate = view.getUint16(offset+2, true);
if (t.nSampleRate < 3000) throw "BAD SAMPLE RATE! "+t.nSampleRate;
t.nTime = view.getUint16(offset+4, true);
t.nLoopOff = view.getUint16(offset+6, true);
t.nNonLoopLen = view.getUint32(offset+8, true);
t.bytesize = (t.nLoopOff+t.nNonLoopLen)*4;
t.mul = 1;
offset += 12;
var data;
switch (t.waveType) {
case 0:
var size = t.bytesize;
data = new Float32Array(size);
for (var i=0; i<size; i++) {
data[i] = view.getInt8(offset++)/0x7F;
}
t.loopSTime = (t.nLoopOff*4)/t.nSampleRate;
break;
case 1:
var size = t.bytesize/2;
data = new Float32Array(size);
for (var i=0; i<size; i++) {
data[i] = view.getInt16(offset, true)/0x7FFF;
offset += 2;
}
t.loopSTime = (t.nLoopOff*2)/t.nSampleRate;
break;
case 2:
data = decodeADPCM(view, offset);
t.loopSTime = ((t.nLoopOff-1)*8)/t.nSampleRate;
break;
}
t.data = data;
}
function getAudioBuffer(ctx) {
while (true) {
try {
var buf = ctx.createBuffer(1, t.data.length, t.nSampleRate);
buf.getChannelData(0).set(t.data);
return buf;
} catch (e) {
t.nSampleRate *= 2; //keep increasing sample rate until the target supports it.
t.loopSTime /= 2;
t.mul *= 2;
}
if (t.nSampleRate > 96000) return ctx.createBuffer(1, 1, 44000); //give up and return an empty buffer
}
}
var indChanges = [-1, -1, -1, -1, 2, 4, 6, 8];
var ADPCMTable = [
0x0007,0x0008,0x0009,0x000A,0x000B,0x000C,0x000D,0x000E,0x0010,0x0011,0x0013,0x0015,
0x0017,0x0019,0x001C,0x001F,0x0022,0x0025,0x0029,0x002D,0x0032,0x0037,0x003C,0x0042,
0x0049,0x0050,0x0058,0x0061,0x006B,0x0076,0x0082,0x008F,0x009D,0x00AD,0x00BE,0x00D1,
0x00E6,0x00FD,0x0117,0x0133,0x0151,0x0173,0x0198,0x01C1,0x01EE,0x0220,0x0256,0x0292,
0x02D4,0x031C,0x036C,0x03C3,0x0424,0x048E,0x0502,0x0583,0x0610,0x06AB,0x0756,0x0812,
0x08E0,0x09C3,0x0ABD,0x0BD0,0x0CFF,0x0E4C,0x0FBA,0x114C,0x1307,0x14EE,0x1706,0x1954,
0x1BDC,0x1EA5,0x21B6,0x2515,0x28CA,0x2CDF,0x315B,0x364B,0x3BB9,0x41B2,0x4844,0x4F7E,
0x5771,0x602F,0x69CE,0x7462,0x7FFF
]; //thanks no$gba docs
function decodeADPCM(view, off) {
var pcm = view.getUint16(off, true); //initial pcm
var ind = view.getUint8(off+2); //initial index
off += 4;
var size = t.bytesize-4;
var out = new Float32Array((size*2));
var write = 0;
//out[write++] = pcm/0x7FFF;
for (var i=0; i<size; i++) {
var b = view.getUint8(off++);
for (var j=0; j<2; j++) {
var nibble = (b>>(j*4))&15;
var diff = Math.floor(((nibble&7)*2+1)*ADPCMTable[ind]/8);
if (nibble&8) pcm = Math.max(pcm-diff, -0x7FFF);
else pcm = Math.min(pcm+diff, 0x7FFF);
out[write++] = pcm/0x7FFF;
ind = Math.min(88, Math.max(0, ind + indChanges[nibble&7]));
}
}
return out;
}
function readChar(view, offset) {
return String.fromCharCode(view.getUint8(offset));
}
if (input != null) {
load(input, hasHead, dataView);
}
}

3
Code/IndexedDBShim.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,39 @@
//
// itemboxShard.js
//--------------------
// by RHY3756547
//
window.ItemShard = function(scene, targ, model) {
var t = this;
t.update = update;
t.draw = draw;
t.time = 0;
t.pos = vec3.clone(targ.pos);
t.vel = vec3.add([], targ.vel, [(Math.random()-0.5)*5, Math.random()*7, (Math.random()-0.5)*5]);
t.dirVel = [(Math.random()-0.5), (Math.random()-0.5), (Math.random()-0.5)];
t.dir = [Math.random()*2*Math.PI, Math.random()*2*Math.PI, Math.random()*2*Math.PI];
t.scale = Math.random()+0.5;
t.scale = [t.scale, t.scale, t.scale];
function update(scene) {
vec3.add(t.pos, t.pos, t.vel);
vec3.add(t.vel, t.vel, [0, -0.17, 0]);
vec3.add(t.dir, t.dir, t.dirVel);
if (t.time++ > 30) scene.removeParticle(t);
}
function draw(view, pMatrix, gl) {
var mat = mat4.translate(mat4.create(), view, t.pos);
mat4.rotateZ(mat, mat, t.dir[2]);
mat4.rotateY(mat, mat, t.dir[1]);
mat4.rotateX(mat, mat, t.dir[0]);
mat4.scale(mat, mat, vec3.scale([], t.scale, 16));
model.draw(mat, pMatrix);
}
}

View File

@ -0,0 +1,244 @@
//
// nitroAnimator.js
//--------------------
// Runs nsbca animations and provides matrix stacks that can be used with nitroRender to draw them.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/*
//
window.nitroAnimator = function(bmd, bca) {
var t = this;
t.bmd = bmd;
t.bca = bca;
var bmd = bmd;
var bca = bca;
t.setFrame = setFrame;
t.setAnim = setAnim;
t.getLength = getLength;
var matBufEmpty = new Float32Array(31*16);
var workingMat = mat4.create();
var temp = mat4.create();
var off=0;
var objMats = [];
for (var i=0; i<31; i++) {
matBufEmpty.set(temp, off);
objMats.push(mat4.create());
off += 16;
}
var matBuf = new Float32Array(31*16);
var matStack = {built: true, dat: matBuf};
function setAnim(b) {
bca = b;
t.bca = b;
}
function getLength(anim) {
return bca.animData.objectData[anim].frames;
}
function setFrame(anim, modelind, frame) {
var b = bca.animData.objectData[anim];
var fLow = Math.floor(frame);
var fHigh = Math.ceil(frame);
var iterp = frame%1;
var model = bmd.modelData.objectData[modelind];
var fallback = model.objects.objectData;
for (var i=0; i<b.trans.length; i++) {
var mat = objMats[i];
mat4.identity(mat);
var a = b.trans[i]; //animated transforms
var fa = fallback[i]; //fallback
var translate;
if (a.translate != null) {
translate = [];
if (a.tlExtra[0] != null) {
var f = frame * a.tlExtra[0].speed;
var fLow = Math.floor(f)%a.translate[0].length;
var fHigh = Math.ceil(f)%a.translate[0].length;
var p = f%1;
translate[0] = a.translate[0][fHigh]*(p) + a.translate[0][fLow]*(1-p);
} else translate[0] = a.translate[0][0];
if (a.tlExtra[1] != null) {
var f = frame * a.tlExtra[1].speed;
var fLow = Math.floor(f)%a.translate[1].length;
var fHigh = Math.ceil(f)%a.translate[1].length;
var p = f%1;
translate[1] = a.translate[1][fHigh]*(p) + a.translate[1][fLow]*(1-p);
} else translate[1] = a.translate[1][0];
if (a.tlExtra[2] != null) {
var f = frame * a.tlExtra[2].speed;
var fLow = Math.floor(f)%a.translate[2].length;
var fHigh = Math.ceil(f)%a.translate[2].length;
var p = f%1;
translate[2] = a.translate[2][fHigh]*(p) + a.translate[2][fLow]*(1-p);
} else translate[2] = a.translate[2][0];
} else {
translate = fa.translate;
}
var rotate;
if (a.rotate != null) {
if (a.rotExtra != null) {
var f = frame * a.rotExtra.speed;
var fLow = Math.floor(f)%a.rotate.length;
var fHigh = Math.ceil(f)%a.rotate.length;
var p = f%1;
var r1 = parseRotation(a.rotate[fLow]);
var r2 = parseRotation(a.rotate[fHigh]);
rotate = lerpMat3(r1, r2, p);
} else {
rotate = parseRotation(a.rotate[0]);
}
} else {
rotate = fa.pivot;
}
var scale;
if (a.scale != null) {
scale = [];
if (a.scExtra[0] != null) {
var f = frame * a.scExtra[0].speed;
var fLow = Math.floor(f)%a.scale[0].length;
var fHigh = Math.ceil(f)%a.scale[0].length;
var p = f%1;
scale[0] = a.scale[0][fHigh].s1*(p) + a.scale[0][fLow].s1*(1-p);
} else scale[0] = a.scale[0][0].s1;
if (a.scExtra[1] != null) {
var f = frame * a.scExtra[1].speed;
var fLow = Math.floor(f)%a.scale[1].length;
var fHigh = Math.ceil(f)%a.scale[1].length;
var p = f%1;
scale[1] = a.scale[1][fHigh].s1*(p) + a.scale[1][fLow].s1*(1-p);
} else scale[1] = a.scale[1][0].s1;
if (a.scExtra[2] != null) {
var f = frame * a.scExtra[2].speed;
var fLow = Math.floor(f)%a.scale[2].length;
var fHigh = Math.ceil(f)%a.scale[2].length;
var p = f%1;
scale[2] = a.scale[2][fHigh].s1*(p) + a.scale[2][fLow].s1*(1-p);
} else scale[2] = a.scale[2][0].s1;
} else {
scale = fa.scale;
}
mat4.translate(mat, mat, translate);
mat4.multiply(mat, mat, mat4FromMat3(rotate));
mat4.scale(mat, mat, scale);
}
generateMatrixStack(model, matBuf)
return matStack;
}
function generateMatrixStack(model, targ) {
var matrices = []
var objs = model.objects.objectData;
var cmds = model.commands;
var curMat = mat4.create();
var lastStackID = 0;
for (var i=0; i<cmds.length; i++) {
var cmd = cmds[i];
if (cmd.restoreID != null) curMat = mat4.clone(matrices[cmd.restoreID]);
var o = objs[cmd.obj];
mat4.multiply(curMat, curMat, objMats[cmd.obj]);
if (o.billboardMode == 1) mat4.multiply(curMat, curMat, nitroRender.billboardMat);
if (o.billboardMode == 2) mat4.multiply(curMat, curMat, nitroRender.yBillboardMat);
if (cmd.stackID != null) {
matrices[cmd.stackID] = mat4.clone(curMat);
lastStackID = cmd.stackID;
} else {
matrices[lastStackID] = mat4.clone(curMat);
}
}
model.lastStackID = lastStackID;
targ.set(matBufEmpty);
var off=0;
for (var i=0; i<31; i++) {
if (matrices[i] != null) targ.set(matrices[i], off);
off += 16;
}
return targ;
}
function mat4FromMat3(mat) {
dest = mat4.create();
dest[0] = mat[0];
dest[1] = mat[1];
dest[2] = mat[2];
dest[3] = 0;
dest[4] = mat[3];
dest[5] = mat[4];
dest[6] = mat[5];
dest[7] = 0;
dest[8] = mat[6];
dest[9] = mat[7];
dest[10] = mat[8];
dest[11] = 0;
dest[12] = 0;
dest[13] = 0;
dest[14] = 0;
dest[15] = 1;
return dest;
}
function parseRotation(rot) {
if (rot.pivot) {
var flag = rot.param;
var pivot = [0,0,0,0,0,0,0,0,0];
var mode = flag&15;
var neg = (flag>>4)&15;
var A = rot.a;
var B = rot.b;
pivot[mode] = (neg&1)?-1:1;
var horiz = mode%3;
var vert = Math.floor(mode/3)
var left = (horiz==0)?1:0; var top = ((vert==0)?1:0)*3;
var right = (horiz==2)?1:2; var btm = ((vert==2)?1:2)*3;
pivot[left+top] = A;
pivot[right+top] = B;
pivot[left+btm] = (neg&2)?-B:B;
pivot[right+btm] = (neg&4)?-A:A;
return pivot;
} else {
return rot.mat;
}
}
function lerpMat3(m1, m2, p) { //this is probably a dumb idea, but it's not the worst thing i've come up with...
var q = 1-p;
return [
m1[0]*q+m2[0]*p, m1[1]*q+m2[1]*p, m1[2]*q+m2[2]*p,
m1[3]*q+m2[3]*p, m1[4]*q+m2[4]*p, m1[5]*q+m2[5]*p,
m1[6]*q+m2[6]*p, m1[7]*q+m2[7]*p, m1[8]*q+m2[8]*p,
]
}
}

741
Code/Render/nitroRender.js Normal file
View File

@ -0,0 +1,741 @@
//
// nitroRender.js
//--------------------
// Provides an interface with which NSBMD models can be drawn to a fst canvas.
// by RHY3756547
//
// includes: gl-matrix.js (glMatrix 2.0)
// /formats/nitro.js --passive requirement from other nitro formats
// /formats/nsbmd.js
// /formats/nsbta.js
// /formats/nsbtx.js
//
window.nitroRender = new function() {
var gl, frag, vert, nitroShader;
var cVec, color, texCoord, norm;
var vecMode, vecPos, vecNorm, vecTx, vecCol, vecNum, vecMat, curMat;
var texWidth, texHeight, alphaMul = 1;
this.cullModes = [];
this.billboardID = 0; //incrememts every time billboards need to be updated. cycles &0xFFFFFF to avoid issues
this.lastMatStack = null; //used to check if we need to send the matStack again. will be used with a versioning system in future.
this.last = {}; //obj: the last vertex buffers drawn
var optimiseTriangles = true; //improves draw performance by >10x on most models.
var modelBuffer;
var shaders = [];
this.renderDispList = renderDispList;
this.setAlpha = setAlpha;
this.getViewWidth = getViewWidth;
this.getViewHeight = getViewHeight;
this.flagShadow = false;
var parameters = {
0: 0,
0x10:1, 0x11:0, 0x12:1, 0x13:1, 0x14:1, 0x15:0, 0x16:16, 0x17:12, 0x18:16, 0x19:12, 0x1A:9, 0x1B:3, 0x1C:3, //matrix commands
0x20:1, 0x21:1, 0x22:1, 0x23:2, 0x24:1, 0x25:1, 0x26:1, 0x27:1, 0x28:1, 0x29:1, 0x2A:1, 0x2B:1, //vertex commands
0x30:1, 0x31:1, 0x32:1, 0x33:1, 0x34:32, //material param
0x40:1, 0x41:0, //begin or end vertices
0x50:1, //swap buffers
0x60:1, //viewport
0x70:3, 0x71:2, 0x72:1 //tests
}
var instructions = {};
instructions[0x14] = function(view, off) { //restore to matrix, used constantly for bone transforms
curMat = view.getUint8(off);
}
instructions[0x20] = function(view, off) { //color
var dat = view.getUint16(off,true);
color[0] = (dat&31)/31;
color[1] = ((dat>>5)&31)/31;
color[2] = ((dat>>10)&31)/31;
}
instructions[0x21] = function(view, off) { //normal
var dat = view.getUint32(off, true);
norm[0] = tenBitSign(dat);
norm[1] = tenBitSign(dat>>10);
norm[2] = tenBitSign(dat>>20);
}
instructions[0x22] = function(view, off) { //texcoord
texCoord[0] = (view.getInt16(off, true)/16)/texWidth;
texCoord[1] = (view.getInt16(off+2, true)/16)/texHeight;
}
instructions[0x23] = function(view, off) { //xyz 16 bit
cVec[0] = view.getInt16(off, true)/4096;
cVec[1] = view.getInt16(off+2, true)/4096;
cVec[2] = view.getInt16(off+4, true)/4096;
pushVector();
}
instructions[0x24] = function(view, off) { //xyz 10 bit
var dat = view.getUint32(off, true);
cVec[0] = tenBitSign(dat);
cVec[1] = tenBitSign(dat>>10);
cVec[2] = tenBitSign(dat>>20);
pushVector();
}
instructions[0x25] = function(view, off) { //xy 16 bit
cVec[0] = view.getInt16(off, true)/4096;
cVec[1] = view.getInt16(off+2, true)/4096;
pushVector();
}
instructions[0x26] = function(view, off) { //xz 16 bit
cVec[0] = view.getInt16(off, true)/4096;
cVec[2] = view.getInt16(off+2, true)/4096;
pushVector();
}
instructions[0x27] = function(view, off) { //yz 16 bit
cVec[1] = view.getInt16(off, true)/4096;
cVec[2] = view.getInt16(off+2, true)/4096;
pushVector();
}
instructions[0x28] = function(view, off) { //xyz 10 bit relative
var dat = view.getUint32(off, true);
cVec[0] += relativeSign(dat);
cVec[1] += relativeSign(dat>>10);
cVec[2] += relativeSign(dat>>20);
pushVector();
}
instructions[0x40] = function(view, off) { //begin vtx
var dat = view.getUint32(off, true);
vecMode = dat;
if (!optimiseTriangles) {
vecPos = [];
vecNorm = [];
vecTx = [];
vecCol = [];
vecMat = [];
}
vecNum = 0;
}
instructions[0x41] = function(view, off) { //end vtx
if (!optimiseTriangles) pushStrip();
}
function setAlpha(alpha) { //for fading specific things out or whatever
alphaMul = alpha;
}
function getViewWidth(){
return gl.viewportWidth;
}
function getViewHeight() {
return gl.viewportHeight;
}
function pushStrip() { //push the last group of triangles to the buffer. Should do this on matrix change... details fourthcoming
var modes = (optimiseTriangles)?[gl.TRIANGLES, gl.TRIANGLES, gl.TRIANGLES, gl.TRIANGLES]:[gl.TRIANGLES, gl.TRIANGLES, gl.TRIANGLE_STRIP, gl.TRIANGLE_STRIP];
var pos = gl.createBuffer();
var col = gl.createBuffer();
var tx = gl.createBuffer();
var mat = gl.createBuffer();
var norm = gl.createBuffer();
var posArray = new Float32Array(vecPos);
gl.bindBuffer(gl.ARRAY_BUFFER, pos);
gl.bufferData(gl.ARRAY_BUFFER, posArray, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, tx);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecTx), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, col);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecCol), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, mat);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecMat), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, norm);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecNorm), gl.STATIC_DRAW);
modelBuffer.strips.push({
posArray: posArray,
vPos: pos,
vTx: tx,
vCol: col,
vMat: mat,
vNorm: norm,
verts: vecPos.length/3,
mode: modes[vecMode]
})
}
function pushVector() {
if (vecMode == 1 && vecNum%4 == 3) { //quads - special case
vecPos = vecPos.concat(vecPos.slice(vecPos.length-9, vecPos.length-6)).concat(vecPos.slice(vecPos.length-3));
vecNorm = vecNorm.concat(vecNorm.slice(vecNorm.length-9, vecNorm.length-6)).concat(vecNorm.slice(vecNorm.length-3));
vecTx = vecTx.concat(vecTx.slice(vecTx.length-6, vecTx.length-4)).concat(vecTx.slice(vecTx.length-2));
vecCol = vecCol.concat(vecCol.slice(vecCol.length-12, vecCol.length-8)).concat(vecCol.slice(vecCol.length-4));
vecMat = vecMat.concat(vecMat.slice(vecMat.length-3, vecMat.length-2)).concat(vecMat.slice(vecMat.length-1));
}
if (optimiseTriangles && (vecMode > 1) && (vecNum > 2)) { //convert tri strips to individual triangles so we get one buffer per polygon
vecPos = vecPos.concat(vecPos.slice(vecPos.length-6));
vecNorm = vecNorm.concat(vecNorm.slice(vecNorm.length-6));
vecTx = vecTx.concat(vecTx.slice(vecTx.length-4));
vecCol = vecCol.concat(vecCol.slice(vecCol.length-8));
vecMat = vecMat.concat(vecMat.slice(vecMat.length-2));
}
vecNum++;
vecPos = vecPos.concat(cVec);
vecTx = vecTx.concat(texCoord);
vecCol = vecCol.concat(color);
vecNorm = vecNorm.concat(norm);
vecMat.push(curMat);
}
function tenBitSign(val) {
val &= 1023;
if (val & 512) return (val-1024)/64;
else return val/64;
}
function relativeSign(val) {
val &= 1023;
if (val & 512) return (val-1024)/4096;
else return val/4096;
}
this.init = function(ctx) {
gl = ctx;
this.gl = gl;
shaders = nitroShaders.compileShaders(gl);
this.nitroShader = shaders[0];
this.cullModes = [gl.FRONT_AND_BACK, gl.FRONT, gl.BACK];
}
this.prepareShader = function() {
//prepares the shader so no redundant calls have to be made. Should be called upon every program change.
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
this.last = {};
gl.activeTexture(gl.TEXTURE0);
gl.uniform1i(this.nitroShader.samplerUniform, 0);
}
this.setShadowMode = function(sTex, fsTex, sMat, fsMat) {
this.nitroShader = shaders[1];
var shader = shaders[1];
gl.useProgram(shader);
gl.uniformMatrix4fv(shader.shadowMatUniform, false, sMat);
gl.uniformMatrix4fv(shader.farShadowMatUniform, false, fsMat);
gl.uniform1f(shader.shadOffUniform, 0.00005+((mobile)?0.0005:0));
gl.uniform1f(shader.farShadOffUniform, 0.0005);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, sTex);
gl.uniform1i(shader.lightSamplerUniform, 1);
gl.activeTexture(gl.TEXTURE2);
gl.bindTexture(gl.TEXTURE_2D, fsTex);
gl.uniform1i(shader.farLightSamplerUniform, 2);
this.setColMult([1, 1, 1, 1]);
this.prepareShader();
}
this.unsetShadowMode = function() {
this.nitroShader = shaders[0];
gl.useProgram(this.nitroShader);
this.setColMult([1, 1, 1, 1]);
this.prepareShader();
}
this.setColMult = function(color) {
gl.useProgram(this.nitroShader);
gl.uniform4fv(this.nitroShader.colMultUniform, color);
}
this.updateBillboards = function(view) {
this.billboardID = (this.billboardID+1)%0xFFFFFF;
var nv = mat4.clone(view);
nv[12] = 0;
nv[13] = 0;
nv[14] = 0; //nullify translation
var nv2 = mat4.clone(nv);
this.billboardMat = mat4.invert(nv, nv);
nv2[4] = 0;
nv2[5] = 1; //do not invert y axis view
nv2[6] = 0;
this.yBillboardMat = mat4.invert(nv2, nv2);
}
function renderDispList(disp, tex, startStack) { //renders the display list to a form of vertex buffer. The idea is that NSBTA and NSBCA can still be applied to the buffer at little performance cost. (rather than recompiling the model)
modelBuffer = {
strips: []
/* strip entry format:
vPos: glBuffer,
vTx: glBuffer,
vCol: glBuffer,
verts: int count of vertices,
mode: (eg. gl.TRIANGLES, gl.TRIANGLESTRIP)
mat: transformation matrix to apply. unused atm as matrix functions are unimplemented
*/
} //the nitroModel will store this and use it for rendering instead of the display list in future.
curMat = startStack; //start on root bone
var shader = nitroRender.nitroShader;
var gl = nitroRender.gl;
var off=0;
var view = new DataView(disp);
texWidth = tex.width;
texHeight = tex.height;
cVec = [0,0,0];
norm = [0,1,0];
texCoord = [0,0];
color = [1,1,1,alphaMul]; //todo: polygon attributes
vecMode = 0;
vecNum = 0;
vecPos = [];
vecNorm = [];
vecTx = [];
vecCol = [];
vecMat = [];
while (off < disp.byteLength) {
var ioff = off;
off += 4;
for (var i=0; i<4; i++) {
var inst = view.getUint8(ioff++);
if (instructions[inst] != null) {
instructions[inst](view, off);
} else {
if (inst != 0) alert("invalid instruction 0x"+(inst.toString(16)));
}
var temp = parameters[inst];
off += (temp == null)?0:temp*4;
}
}
if (optimiseTriangles) pushStrip();
return modelBuffer;
}
};
function nitroModel(bmd, btx, remap) {
var bmd = bmd;
this.bmd = bmd;
var thisObj = this;
var loadedTex;
var texCanvas;
var tex;
var texAnim;
var texFrame;
var modelBuffers;
var collisionModel = [];
var matBufEmpty = new Float32Array(31*16);
var temp = mat4.create();
var off=0;
for (var i=0; i<31; i++) {
matBufEmpty.set(temp, off);
off += 16;
}
temp = null;
var texMap = { tex:{}, pal:{} };
//var matStack;
this.draw = draw;
this.drawPoly = externDrawPoly;
this.drawModel = externDrawModel;
this.getCollisionModel = getCollisionModel;
modelBuffers = []
this.modelBuffers = modelBuffers;
var matBuf = [];
for (var i=0; i<bmd.modelData.objectData.length; i++) {
modelBuffers.push(new Array(bmd.modelData.objectData[i].polys.objectData.length));
matBuf.push({built: false, dat: new Float32Array(31*16)});
}
if (remap != null) {
setTextureRemap(remap)
}
if (btx != null) {
loadTexture(btx);
} else if (bmd.tex != null) {
loadTexture(bmd.tex)
} else {
loadWhiteTex();
}
function loadWhiteTex(btx) { //examines the materials in the loaded model and generates textures for each.
var gl = nitroRender.gl; //get gl object from nitro render singleton
loadedTex = btx;
texCanvas = [];
tex = [];
var models = bmd.modelData.objectData;
for (var j=0; j<models.length; j++) {
var model = models[j];
var mat = model.materials.objectData
for (var i=0; i<mat.length; i++) {
var m = mat[i];
var fC = document.createElement("canvas");
fC.width = 2;
fC.height = 2;
var ctx = fC.getContext("2d")
ctx.fillStyle = "black";
ctx.globalAlpha=0.33;
ctx.fillRect(0,0,2,2);
texCanvas.push(fC);
var t = loadTex(fC, gl, !m.repeatX, !m.repeatY);
t.realWidth = 2;
t.realHeight = 2;
tex.push(t);
}
}
}
function loadTexture(btx) { //examines the materials in the loaded model and generates textures for each.
var gl = nitroRender.gl; //get gl object from nitro render singleton
loadedTex = btx;
texCanvas = [];
tex = [];
var models = bmd.modelData.objectData;
for (var j=0; j<models.length; j++) {
var model = models[j];
var mat = model.materials.objectData
for (var i=0; i<mat.length; i++) {
var m = mat[i];
var texI = mat[i].tex;
var palI = mat[i].pal;
//remap below
var nTex = texMap.tex[texI];
var nPal = texMap.pal[palI];
if ((texI == null && nTex == null) || (palI == null && nPal == null)) {
debugger;
console.warn("WARNING: material "+i+" in model could not be assigned a texture.")
var fC = document.createElement("canvas");
fC.width = 2;
fC.height = 2;
var ctx = fC.getContext("2d")
ctx.fillStyle = "white";
ctx.fillRect(0,0,2,2);
texCanvas.push(fC);
var t = loadTex(fC, gl, !m.repeatX, !m.repeatY);
t.realWidth = 2;
t.realHeight = 2;
tex.push(t);
continue;
}
var truetex = (nTex==null)?texI:nTex;
var truepal = (nPal==null)?palI:nPal;
var cacheID = truetex+":"+truepal;
var cached = btx.cache[cacheID];
if (cached == null) {
var canvas = btx.readTexWithPal(truetex, truepal);
if (m.flipX || m.flipY) {
var fC = document.createElement("canvas");
var ctx = fC.getContext("2d");
fC.width = (m.flipX)?canvas.width*2:canvas.width;
fC.height = (m.flipY)?canvas.height*2:canvas.height;
ctx.drawImage(canvas, 0, 0);
ctx.save();
if (m.flipX) {
ctx.translate(2*canvas.width, 0);
ctx.scale(-1, 1);
ctx.drawImage(canvas, 0, 0);
ctx.restore();
ctx.save();
}
if (m.flipY) {
ctx.translate(0, 2*canvas.height);
ctx.scale(1, -1);
ctx.drawImage(fC, 0, 0);
ctx.restore();
}
texCanvas.push(fC);
var t = loadTex(fC, gl, !m.repeatX, !m.repeatY);
t.realWidth = canvas.width;
t.realHeight = canvas.height;
tex.push(t);
btx.cache[cacheID] = t;
} else {
texCanvas.push(canvas);
var t = loadTex(canvas, gl, !m.repeatX, !m.repeatY);
t.realWidth = canvas.width;
t.realHeight = canvas.height;
tex.push(t);
btx.cache[cacheID] = t;
}
} else {
tex.push(cached);
}
}
}
}
function setTextureRemap(remap) {
texMap = remap;
if (loadedTex != null) loadTexture(loadedTex)
}
this.loadTexAnim = function(bta) {
texAnim = bta;
texFrame = 0;
}
this.setFrame = function(frame) {
texFrame = frame;
}
function externDrawModel(mv, project, mdl) {
var models = bmd.modelData.objectData;
drawModel(models[mdl], mv, project, mdl);
}
function externDrawPoly(mv, project, modelind, poly, matStack) {
var models = bmd.modelData.objectData;
var model = models[modelind];
var polys = model.polys.objectData;
var matStack = matStack;
if (matStack == null) {
matStack = matBuf[modelind];
if (((thisObj.billboardID != nitroRender.billboardID) && bmd.hasBillboards) || (!matStack.built)) {
nitroRender.lastMatStack = null;
generateMatrixStack(model, matStack.dat);
matStack.built = true;
thisObj.billboardID = nitroRender.billboardID;
}
}
var shader = nitroRender.nitroShader;
var mv = mat4.scale([], mv, [model.head.scale, model.head.scale, model.head.scale]);
gl.uniformMatrix4fv(shader.mvMatrixUniform, false, mv);
gl.uniformMatrix4fv(shader.pMatrixUniform, false, project);
if (matStack != nitroRender.lastMatStack) {
gl.uniformMatrix4fv(shader.matStackUniform, false, matStack.dat);
nitroRender.lastMatStack = matStack;
}
drawPoly(polys[poly], modelind, poly);
}
function draw(mv, project, matStack) {
var models = bmd.modelData.objectData;
for (var j=0; j<models.length; j++) {
drawModel(models[j], mv, project, j, matStack);
}
}
function getCollisionModel(modelind, polyind) { //simple func to get collision model for a model. used when I'm too lazy to define my own... REQUIRES TRI MODE ACTIVE!
if (collisionModel[modelind] == null) collisionModel[modelind] = [];
if (collisionModel[modelind][polyind] != null) return collisionModel[modelind][polyind];
var model = bmd.modelData.objectData[modelind];
var poly = model.polys.objectData[polyind];
if (modelBuffers[modelind][polyind] == null) modelBuffers[modelind][polyind] = nitroRender.renderDispList(poly.disp, tex[poly.mat], (poly.stackID == null)?model.lastStackID:poly.stackID);
var tris = modelBuffers[modelind][polyind].strips[0].posArray;
var out = [];
var tC = tris.length/9;
var off = 0;
for (var i=0; i<tC; i++) {
var t = {}
t.Vertex1 = [tris[off++], tris[off++], tris[off++]];
t.Vertex2 = [tris[off++], tris[off++], tris[off++]];
t.Vertex3 = [tris[off++], tris[off++], tris[off++]];
//calculate normal
var v = vec3.sub([], t.Vertex2, t.Vertex1);
var w = vec3.sub([], t.Vertex3, t.Vertex1);
t.Normal = vec3.cross([], v, w)
vec3.normalize(t.Normal, t.Normal);
out.push(t);
}
collisionModel[modelind][polyind] = {dat:out, scale:model.head.scale};
return collisionModel[modelind][polyind];
}
function drawModel(model, mv, project, modelind, matStack) {
var polys = model.polys.objectData;
var matStack = matStack;
if (matStack == null) {
matStack = matBuf[modelind];
if (((thisObj.billboardID != nitroRender.billboardID) && bmd.hasBillboards) || (!matStack.built)) {
nitroRender.lastMatStack = null;
generateMatrixStack(model, matStack.dat);
matStack.built = true;
thisObj.billboardID = nitroRender.billboardID;
}
}
var shader = nitroRender.nitroShader;
var mv = mat4.scale([], mv, [model.head.scale, model.head.scale, model.head.scale]);
gl.uniformMatrix4fv(shader.mvMatrixUniform, false, mv);
gl.uniformMatrix4fv(shader.pMatrixUniform, false, project);
if (matStack != nitroRender.lastMatStack) {
gl.uniformMatrix4fv(shader.matStackUniform, false, matStack.dat);
nitroRender.lastMatStack = matStack;
}
for (var i=0; i<polys.length; i++) {
drawPoly(polys[i], modelind, i);
}
}
function drawPoly(poly, modelind, polyind) {
var shader = nitroRender.nitroShader;
var model = bmd.modelData.objectData[modelind];
var gl = nitroRender.gl;
//texture 0 SHOULD be bound, assuming the nitrorender program has been prepared
if (nitroRender.last.tex != tex[poly.mat]) {
gl.bindTexture(gl.TEXTURE_2D, tex[poly.mat]); //load up material texture
nitroRender.last.tex = tex[poly.mat];
}
var material = model.materials.objectData[poly.mat];
nitroRender.setAlpha(material.alpha)
if (texAnim != null) {
//generate and send texture matrix from data
var matname = model.materials.names[poly.mat]; //attach tex anim to mat with same name
var anims = texAnim.animData.objectData[modelind].data;
var animNum = anims.names.indexOf(matname);
if (animNum != -1) {
//we got a match! it's wonderful :')
var anim = anims.objectData[animNum];
var mat = mat3.create(); //material texture mat is ignored
mat3.scale(mat, mat, [anim.scaleS[(texFrame>>anim.frameStep.scaleS)%anim.scaleS.length], anim.scaleT[(texFrame>>anim.frameStep.scaleT)%anim.scaleT.length]]);
mat3.translate(mat, mat, [-anim.translateS[(texFrame>>anim.frameStep.translateS)%anim.translateS.length], anim.translateT[(texFrame>>anim.frameStep.translateT)%anim.translateT.length]]) //for some mystery reason I need to negate the S translation
gl.uniformMatrix3fv(shader.texMatrixUniform, false, mat);
} else {
gl.uniformMatrix3fv(shader.texMatrixUniform, false, material.texMat);
}
} else gl.uniformMatrix3fv(shader.texMatrixUniform, false, material.texMat);
if (modelBuffers[modelind][polyind] == null) modelBuffers[modelind][polyind] = nitroRender.renderDispList(poly.disp, tex[poly.mat], (poly.stackID == null)?model.lastStackID:poly.stackID);
drawModelBuffer(modelBuffers[modelind][polyind], gl, shader);
}
function generateMatrixStack(model, targ) { //this generates a matrix stack with the default bones. use nitroAnimator to pass custom matrix stacks using nsbca animations.
var matrices = [];
var objs = model.objects.objectData;
var cmds = model.commands;
var curMat = mat4.create();
var lastStackID = 0;
for (var i=0; i<cmds.length; i++) {
var cmd = cmds[i];
if (cmd.restoreID != null) curMat = mat4.clone(matrices[cmd.restoreID]);
var o = objs[cmd.obj];
mat4.multiply(curMat, curMat, o.mat);
if (o.billboardMode == 1) mat4.multiply(curMat, curMat, nitroRender.billboardMat);
if (o.billboardMode == 2) mat4.multiply(curMat, curMat, nitroRender.yBillboardMat);
if (cmd.stackID != null) {
matrices[cmd.stackID] = mat4.clone(curMat);
lastStackID = cmd.stackID;
} else {
matrices[lastStackID] = mat4.clone(curMat);
}
}
model.lastStackID = lastStackID;
targ.set(matBufEmpty);
var off=0;
for (var i=0; i<31; i++) {
if (matrices[i] != null) targ.set(matrices[i], off);
off += 16;
}
return targ;
}
function drawModelBuffer(buf, gl, shader) {
for (var i=0; i<buf.strips.length; i++) {
var obj = buf.strips[i];
if (obj != nitroRender.last.obj) {
gl.bindBuffer(gl.ARRAY_BUFFER, obj.vPos);
gl.vertexAttribPointer(shader.vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, obj.vTx);
gl.vertexAttribPointer(shader.textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, obj.vCol);
gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, obj.vMat);
gl.vertexAttribPointer(shader.matAttribute, 1, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, obj.vNorm);
gl.vertexAttribPointer(shader.normAttribute, 3, gl.FLOAT, false, 0, 0);
nitroRender.last.obj = obj;
}
gl.drawArrays(obj.mode, 0, obj.verts);
}
}
}
function loadTex(img, gl, clampx, clampy) { //general purpose function for loading an image into a texture.
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
if (clampx) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
if (clampy) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
texture.width = img.width;
texture.height = img.height;
gl.bindTexture(gl.TEXTURE_2D, null);
return texture;
}

357
Code/Render/nitroShaders.js Normal file
View File

@ -0,0 +1,357 @@
//
// nitroShaders.js
//--------------------
// Dynamically compiles all shader modes of the nitro renderer.
// by RHY3756547
//
window.nitroShaders = new (function() {
var t = this;
this.defaultFrag = "precision highp float;\n\
\n\
varying vec2 vTextureCoord;\n\
varying vec4 color;\n\
\n\
uniform sampler2D uSampler;\n\
\n\
void main(void) {\n\
gl_FragColor = texture2D(uSampler, vTextureCoord)*color;\n\
if (gl_FragColor.a == 0.0) discard;\n\
}"
this.defaultVert = "attribute vec3 aVertexPosition;\n\
attribute vec2 aTextureCoord;\n\
attribute vec4 aColor;\n\
attribute float matrixID;\n\
attribute vec3 aNormal;\n\
\n\
uniform mat4 uMVMatrix;\n\
uniform mat4 uPMatrix;\n\
uniform mat3 texMatrix;\n\
uniform mat4 matStack[16];\n\
\n\
uniform vec4 colMult;\n\
\n\
varying vec2 vTextureCoord;\n\
varying vec4 color;\n\
\n\
\n\
void main(void) {\n\
gl_Position = uPMatrix * uMVMatrix * matStack[int(matrixID)] * vec4(aVertexPosition, 1.0);\n\
vTextureCoord = (texMatrix * vec3(aTextureCoord, 1.0)).xy;\n\
vec3 adjNorm = normalize(vec3(uMVMatrix * matStack[int(matrixID)] * vec4(aNormal, 0.0)));\n\
float diffuse = 0.7-dot(adjNorm, vec3(0.0, -1.0, 0.0))*0.3;\n\
\n\
color = aColor*colMult;\n\
color = vec4(color.x*diffuse, color.y*diffuse, color.z*diffuse, color.w);\n\
}"
this.shadFrag = "precision highp float;\n\
\n\
varying vec2 vTextureCoord;\n\
varying vec4 color;\n\
varying vec4 lightDist;\n\
varying vec4 fLightDist;\n\
\n\
uniform float shadOff; \n\
uniform float farShadOff; \n\
uniform sampler2D lightDSampler;\n\
uniform sampler2D farLightDSampler;\n\
\n\
uniform sampler2D uSampler;\n\
\n\
float shadowCompare(sampler2D map, vec2 pos, float compare) {\n\
float depth = texture2D(map, pos).r;\n\
return step(compare, depth);\n\
}\n\
\n\
float shadowLerp(sampler2D depths, vec2 size, vec2 uv, float compare){\n\
vec2 texelSize = vec2(1.0)/size;\n\
vec2 f = fract(uv*size+0.5);\n\
vec2 centroidUV = floor(uv*size+0.5)/size;\n\
\n\
float lb = shadowCompare(depths, centroidUV+texelSize*vec2(0.0, 0.0), compare);\n\
float lt = shadowCompare(depths, centroidUV+texelSize*vec2(0.0, 1.0), compare);\n\
float rb = shadowCompare(depths, centroidUV+texelSize*vec2(1.0, 0.0), compare);\n\
float rt = shadowCompare(depths, centroidUV+texelSize*vec2(1.0, 1.0), compare);\n\
float a = mix(lb, lt, f.y);\n\
float b = mix(rb, rt, f.y);\n\
float c = mix(a, b, f.x);\n\
return c;\n\
}\n\
\n\
void main(void) {\n\
vec4 col = texture2D(uSampler, vTextureCoord)*color;\n\
\n\
vec2 ldNorm = abs((lightDist.xy)-vec2(0.5, 0.5));\n\
float dist = max(ldNorm.x, ldNorm.y);\n\
\n\
if (dist > 0.5) {\n\
gl_FragColor = col*mix(vec4(0.5, 0.5, 0.7, 1.0), vec4(1.0, 1.0, 1.0, 1.0), shadowLerp(farLightDSampler, vec2(4096.0, 4096.0), fLightDist.xy, fLightDist.z-farShadOff));\n\
} else if (dist > 0.4) {\n\
float lerp1 = shadowLerp(farLightDSampler, vec2(4096.0, 4096.0), fLightDist.xy, fLightDist.z-farShadOff);\n\
float lerp2 = shadowLerp(lightDSampler, vec2(2048.0, 2048.0), lightDist.xy, lightDist.z-shadOff);\n\
\n\
gl_FragColor = col*mix(vec4(0.5, 0.5, 0.7, 1.0), vec4(1.0, 1.0, 1.0, 1.0), mix(lerp2, lerp1, (dist-0.4)*10.0));\n\
} else {\n\
gl_FragColor = col*mix(vec4(0.5, 0.5, 0.7, 1.0), vec4(1.0, 1.0, 1.0, 1.0), shadowLerp(lightDSampler, vec2(2048.0, 2048.0), lightDist.xy, lightDist.z-shadOff));\n\
}\n\
\n\
if (gl_FragColor.a == 0.0) discard;\n\
}\n\
"
this.shadVert = "attribute vec3 aVertexPosition;\n\
attribute vec2 aTextureCoord;\n\
attribute vec4 aColor;\n\
attribute float matrixID;\n\
attribute vec3 aNormal;\n\
\n\
uniform mat4 uMVMatrix;\n\
uniform mat4 uPMatrix;\n\
uniform mat3 texMatrix;\n\
uniform mat4 matStack[16];\n\
\n\
uniform vec4 colMult;\n\
\n\
uniform mat4 shadowMat;\n\
uniform mat4 farShadowMat;\n\
\n\
varying vec2 vTextureCoord;\n\
varying vec4 color;\n\
varying vec4 lightDist;\n\
varying vec4 fLightDist;\n\
\n\
\n\
void main(void) {\n\
vec4 pos = uMVMatrix * matStack[int(matrixID)] * vec4(aVertexPosition, 1.0);\n\
gl_Position = uPMatrix * pos;\n\
vTextureCoord = (texMatrix * vec3(aTextureCoord, 1.0)).xy;\n\
\n\
lightDist = (shadowMat*pos + vec4(1, 1, 1, 0)) / 2.0;\n\
fLightDist = (farShadowMat*pos + vec4(1, 1, 1, 0)) / 2.0;\n\
vec3 adjNorm = normalize(vec3(uMVMatrix * matStack[int(matrixID)] * vec4(aNormal, 0.0)));\n\
float diffuse = 0.7-dot(adjNorm, vec3(0.0, -1.0, 0.0))*0.3;\n\
\n\
color = aColor*colMult;\n\
color = vec4(color.x*diffuse, color.y*diffuse, color.z*diffuse, color.w);\n\
}"
var dFrag = {
begin: "precision highp float;\n\
\n\
varying vec2 vTextureCoord;\n\
varying vec4 color;\n\
\n\
uniform sampler2D uSampler;\n",
main: "\n\
gl_FragColor = texture2D(uSampler, vTextureCoord)*color;\n\
if (gl_FragColor.a == 0.0) discard;\n",
extra: "",
}
var dVert = {
begin: "attribute vec3 aVertexPosition;\n\
attribute vec2 aTextureCoord;\n\
attribute vec4 aColor;\n\
attribute float matrixID;\n\
\n\
uniform mat4 uMVMatrix;\n\
uniform mat4 uPMatrix;\n\
uniform mat3 texMatrix;\n\
uniform mat4 matStack[16];\n\
\n\
uniform vec4 colMult;\n\
\n\
varying vec2 vTextureCoord;\n\
varying vec4 color;\n\
\n\
\n",
main: "\n\
vec4 pos = uMVMatrix * matStack[int(matrixID)] * vec4(aVertexPosition, 1.0);\n\
gl_Position = uPMatrix * pos;\n\
vTextureCoord = (texMatrix * vec3(aTextureCoord, 1.0)).xy;\n\
\n\
lightDist = (shadowMat*pos + vec4(1, 1, 1, 0)) / 2.0;\n\
fLightDist = (farShadowMat*pos + vec4(1, 1, 1, 0)) / 2.0;\n\
\n\
color = aColor*colMult;\n\
",
extra: ""
}
var lightVert = {
begin: "attribute vec3 aNormal;\n",
main: "vec3 adjNorm = normalize(vec3(uMVMatrix * matStack[int(matrixID)] * vec4(aNormal, 0.0)));\n\
float diffuse = 0.7-dot(adjNorm, vec3(0.0, -1.0, 0.0))*0.3;\n\
color = vec4(color.x*diffuse, color.y*diffuse, color.z*diffuse, color.w);\n",
extra: ""
}
var lightFrag = {
begin: "",
main:"",
end:""
}
var sdVert = {
begin: "uniform mat4 shadowMat;\n\
uniform mat4 farShadowMat;\n\
\n\
varying vec4 lightDist;\n\
varying vec4 fLightDist;\n",
main: "lightDist = (shadowMat*pos + vec4(1, 1, 1, 0)) / 2.0;\n\
fLightDist = (farShadowMat*pos + vec4(1, 1, 1, 0)) / 2.0;\n"
}
var sdFrag = {
begin: "varying vec4 lightDist;\n\
varying vec4 fLightDist;\n\
\n\
uniform float shadOff; \n\
uniform float farShadOff; \n\
uniform sampler2D lightDSampler;\n\
uniform sampler2D farLightDSampler;\n",
main: "if (lightDist.x<0.0 || lightDist.y<0.0 || lightDist.x>1.0 || lightDist.y>1.0) {\n\
if (texture2D(farLightDSampler, fLightDist.xy).r+farShadOff < fLightDist.z) {\n\
gl_FragColor = gl_FragColor*vec4(0.5, 0.5, 0.7, 1);\n\
}\n\
} else {\n\
if (texture2D(lightDSampler, lightDist.xy).r+shadOff < lightDist.z) {\n\
gl_FragColor = gl_FragColor*vec4(0.5, 0.5, 0.7, 1);\n\
}\n\
}\n",
extra: ""
}
var baseConf = {
frag: this.defaultFrag, vert: this.defaultVert,
uniforms: [
["pMatrixUniform", "uPMatrix"],
["matStackUniform", "matStack"],
["mvMatrixUniform", "uMVMatrix"],
["texMatrixUniform", "texMatrix"],
["samplerUniform", "uSampler"],
["colMultUniform", "colMult"],
],
attributes: [
["vertexPositionAttribute", "aVertexPosition"],
["textureCoordAttribute", "aTextureCoord"],
["colorAttribute", "aColor"],
["matAttribute", "matrixID"],
["normAttribute", "aNormal"]
]
};
var config = [];
var fragParts = [
dFrag,
lightFrag,
sdFrag
]
var shadUnif = [
["shadowMatUniform", "shadowMat"],
["farShadowMatUniform", "farShadowMat"],
["shadOffUniform", "shadOff"],
["farShadOffUniform", "farShadOff"],
["lightSamplerUniform", "lightDSampler"],
["farLightSamplerUniform", "farLightDSampler"]
]
config[0] = baseConf;
config[1] = {frag: this.shadFrag, vert: this.shadVert, uniforms: baseConf.uniforms.slice(0), attributes: baseConf.attributes.slice(0)};
config[1].uniforms = config[1].uniforms.concat(shadUnif);
function makeShader(source, base, id) { //makes shaders using flags
}
function combineGLSL(shaderParts) {
var out = "";
for (var i=0; i<shaderParts.length; i++) out += shaderParts[i].begin;
out += "\nvoid main(void) {\n";
for (var i=0; i<shaderParts.length; i++) out += shaderParts[i].main;
out += "\n}\n";
for (var i=0; i<shaderParts.length; i++) out += shaderParts[i].extra;
return out;
}
this.compileShaders = function(gl) {
t.shaders = [];
for (var i=0; i<config.length; i++) {
var conf = config[i];
frag = getShader(gl, conf.frag, "frag");
vert = getShader(gl, conf.vert, "vert");
var shader = gl.createProgram();
gl.attachShader(shader, vert);
gl.attachShader(shader, frag);
gl.linkProgram(shader);
if (!gl.getProgramParameter(shader, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
for (var j=0; j<conf.attributes.length; j++) {
var a = conf.attributes[j];
shader[a[0]] = gl.getAttribLocation(shader, a[1]);
gl.enableVertexAttribArray(shader[a[0]]);
}
for (var j=0; j<conf.uniforms.length; j++) {
var a = conf.uniforms[j];
shader[a[0]] = gl.getUniformLocation(shader, a[1]);
}
t.shaders.push(shader);
}
return t.shaders;
}
function getShader(gl, str, type) {
var shader;
if (type == "frag") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (type == "vert") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
})();

193
Code/Render/shadowRender.js Normal file
View File

@ -0,0 +1,193 @@
//
// shadowRender.js
//--------------------
// Provides a shader to draw a shadowed scene using a depth and color texture. (plus depth texture for light source)
// by RHY3756547
//
window.shadowRender = new function() {
var shadFrag = "precision highp float;\n\
\n\
varying vec2 vTextureCoord;\n\
varying vec4 color;\n\
\n\
uniform sampler2D cSampler;\n\
uniform sampler2D depSampler;\n\
uniform sampler2D lightDSampler;\n\
uniform sampler2D farLightDSampler;\n\
\n\
uniform mat4 shadowMat;\n\
uniform mat4 farShadowMat;\n\
uniform mat4 invViewProj;\n\
\n\
\n\
vec3 positionFromDepth(vec2 vTex)\n\
{\n\
float z = texture2D(depSampler, vTex).r * 2.0 - 1.0;\n\
float x = vTex.x * 2.0 - 1.0;\n\
float y = vTex.y * 2.0 - 1.0;\n\
vec4 vProjectedPos = vec4(x, y, z, 1.0);\n\
\n\
// Transform by the inverse projection matrix\n\
vec4 vPositionVS = invViewProj*vProjectedPos;\n\
\n\
// Divide by w to get the view-space position\n\
return vPositionVS.xyz/vPositionVS.w;\n\
}\n\
\n\
void main(void) {\n\
vec3 pos = positionFromDepth(vTextureCoord);\n\
vec4 col = texture2D(cSampler, vTextureCoord);\n\
\n\
vec4 lightDist = (shadowMat*vec4(pos, 1.0) + vec4(1, 1, 1, 0)) / 2.0;\n\
if (lightDist.x<0.0 || lightDist.y<0.0 || lightDist.x>1.0 || lightDist.y>1.0) {\n\
vec4 flightDist = (farShadowMat*vec4(pos, 1.0) + vec4(1, 1, 1, 0)) / 2.0;\n\
if (texture2D(farLightDSampler, flightDist.xy).r+0.0005 < flightDist.z) {\n\
gl_FragColor = col*vec4(0.5, 0.5, 0.7, 1);\n\
} else {\n\
gl_FragColor = col;\n\
}\n\
} else {\n\
\n\
if (texture2D(lightDSampler, lightDist.xy).r+0.00005 < lightDist.z) {\n\
gl_FragColor = col*vec4(0.5, 0.5, 0.7, 1);\n\
} else {\n\
gl_FragColor = col;\n\
}\n\
}\n\
\n\
if (gl_FragColor.a == 0.0) discard;\n\
}\n\
\n\
"
var shadVert = "attribute vec3 aVertexPosition;\n\
attribute vec2 aTextureCoord;\n\
\n\
varying vec2 vTextureCoord;\n\
\n\
void main(void) {\n\
gl_Position = vec4(aVertexPosition, 1.0);\n\
vTextureCoord = vec3(aTextureCoord, 1.0).xy;\n\
}"
var shadowShader, vecPosBuffer, vecTxBuffer;
this.drawShadowed = drawShadowed;
this.init = function(ctx) {
gl = ctx;
this.gl = gl;
frag = getShader(shadFrag, "frag");
vert = getShader(shadVert, "vert");
shadowShader = gl.createProgram();
gl.attachShader(shadowShader, vert);
gl.attachShader(shadowShader, frag);
gl.linkProgram(shadowShader);
if (!gl.getProgramParameter(shadowShader, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
shadowShader.vertexPositionAttribute = gl.getAttribLocation(shadowShader, "aVertexPosition");
gl.enableVertexAttribArray(shadowShader.vertexPositionAttribute);
shadowShader.textureCoordAttribute = gl.getAttribLocation(shadowShader, "aTextureCoord");
gl.enableVertexAttribArray(shadowShader.textureCoordAttribute);
shadowShader.colTexUniform = gl.getUniformLocation(shadowShader, "cSampler");
shadowShader.depTexUniform = gl.getUniformLocation(shadowShader, "depSampler");
shadowShader.lightTexUniform = gl.getUniformLocation(shadowShader, "lightDSampler");
shadowShader.lightFarTexUniform = gl.getUniformLocation(shadowShader, "farLightDSampler");
shadowShader.lightViewUniform = gl.getUniformLocation(shadowShader, "shadowMat");
shadowShader.lightFarViewUniform = gl.getUniformLocation(shadowShader, "farShadowMat");
shadowShader.camViewUniform = gl.getUniformLocation(shadowShader, "invViewProj");
this.shadowShader = shadowShader;
vecPosBuffer = gl.createBuffer();
vecTxBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vecPosBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(
[-1, -1, 0,
1, -1, 0,
1, 1, 0,
1, 1, 0,
-1, 1, 0,
-1, -1, 0,
]
), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, vecTxBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(
[
0, 0,
1, 0,
1, 1,
1, 1,
0, 1,
0, 0,
]
), gl.STATIC_DRAW);
}
function getShader(str, type) {
var shader;
if (type == "frag") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (type == "vert") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function drawShadowed(colTex, depTex, lightTex, lightFarTex, camView, lightView, lightFarView) {
var shader = shadowShader;
gl.useProgram(shader);
gl.uniformMatrix4fv(shader.lightViewUniform, false, lightView);
gl.uniformMatrix4fv(shader.lightFarViewUniform, false, lightFarView);
gl.uniformMatrix4fv(shader.camViewUniform, false, mat4.invert(mat4.create(), camView));
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, lightTex); //load up material texture
gl.uniform1i(shader.lightTexUniform, 0);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, colTex); //load up material texture
gl.uniform1i(shader.colTexUniform, 1);
gl.activeTexture(gl.TEXTURE2);
gl.bindTexture(gl.TEXTURE_2D, depTex); //load up material texture
gl.uniform1i(shader.depTexUniform, 2);
gl.activeTexture(gl.TEXTURE3);
gl.bindTexture(gl.TEXTURE_2D, lightFarTex); //load up material texture
gl.uniform1i(shader.lightFarTexUniform, 3);
gl.bindBuffer(gl.ARRAY_BUFFER, vecPosBuffer);
gl.vertexAttribPointer(shader.vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, vecTxBuffer);
gl.vertexAttribPointer(shader.textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
}

86
Code/UI/race3DUI.js Normal file
View File

@ -0,0 +1,86 @@
//
// race3DUI.js
//--------------------
// by RHY3756547
//
// includes:
// render stuff idk
//
window.Race3DUI = function(scene, type, animStart) {
//type: count, goal, start, lose, win
var forceBill;
var obji = obji;
var res = [];
var t = this;
t.pos = vec3.clone([0,0,0]);
t.update = update;
t.draw = draw;
var mat = mat4.create();
var frame = 0;
var anim = null;
var animFrame = 0;
if (animStart != null) animFrame = animStart;
var animMat = null;
var model = null;
var proj = mat4.create();
var length = 0;
var params = {
"count": [ //offset 21 down
-128/1024, 128/1024, -(192-11)/1024, 11/1024
],
"start": [ //offset 86 up
-128/1024, 128/1024, -(192+66)/1024, -66/1024
]
}
var param = params[type];
if (param == null) param = params["count"]
mat4.ortho(proj, param[0], param[1], param[2], param[3], -0.001, 10);
buildOrtho(nitroRender.getViewWidth(), nitroRender.getViewHeight());
var lastWidth = 0;
initRes();
function initRes() {
var bmd = scene.gameRes.Race.getFile(type+".nsbmd");
if (bmd == null) bmd = scene.gameRes.RaceLoc.getFile(type+".nsbmd");
bmd = new nsbmd(bmd);
var bca = new nsbca(scene.gameRes.Race.getFile(type+".nsbca"));
anim = new nitroAnimator(bmd, bca);
length = anim.getLength(0);
if (type == "count") length *= 3;
model = new nitroModel(bmd);
}
function buildOrtho(width, height) {
lastWidth = width;
var ratio = width / height;
var w = (param[3]-param[2]) * ratio/2;
mat4.ortho(proj, -w, w, param[2], param[3], -0.001, 10);
}
function draw(view, pMatrix) {
if (nitroRender.flagShadow || animFrame < 0) return;
var width = nitroRender.getViewWidth();
if (width != lastWidth) buildOrtho(width, nitroRender.getViewHeight());
mat4.translate(mat, view, t.pos);
model.draw(mat, proj, animMat);
}
function update() {
if (anim != null) {
animMat = anim.setFrame(0, 0, Math.max(0, animFrame++));
}
if (animFrame > length) {
scene.removeEntity(t);
}
}
}

105
Code/UI/uiPlace.js Normal file
View File

@ -0,0 +1,105 @@
//
// !! all UI objects assume you have forced positive y as down!
//
window.uiPlace = function(gl) {
var WHITE = [1, 1, 1, 1];
var frontBuf = {
pos: gl.createBuffer(),
col: gl.createBuffer(),
tx: gl.createBuffer()
}
var backBuf = {
pos: gl.createBuffer(),
col: gl.createBuffer(),
tx: gl.createBuffer()
}
var backActive = false;
function setPlace(num) {
if (nun < 10) {
} else {
var tens = Math.floor(num/10)%10;
var suffix = (tens == 1)?3:(Math.min(3, (num-1)%10));
}
}
function genVertRect(targ, dx, dy, dwidth, dheight, sx, sy, swidth, sheight, z, cornerColours) { //y is down positive. we adjust texture coords to fit this.
var cornerColours = cornerColours
if (cornerColours == null) cornerColours = [WHITE, WHITE, WHITE, WHITE];
var vpos = targ.vpos;
var vcol = targ.vcol;
var vtx = targ.vtx;
// tri 1
//
// 1 2
// ---------
// | /
// | /
// | /
// |/
//
// 3
//
vpos.push(dx);
vpos.push(dy);
vpos.push(z);
vcol = vcol.concat(vcol, cornerColours[0]);
vtx.push(sx);
vtx.push(1-sy);
vpos.push(dx+dwidth);
vpos.push(dy);
vpos.push(z);
vcol = vcol.concat(vcol, cornerColours[1]);
vtx.push(sx+swidth);
vtx.push(1-sy);
vpos.push(dx);
vpos.push(dy+dheight);
vpos.push(z);
vcol = vcol.concat(vcol, cornerColours[2]);
vtx.push(sx);
vtx.push(1-(sy+sheight));
//tri 2
//
// 1
// /|
// / |
// / |
// / |
// --------- 3
// 2
vpos.push(dx+dwidth);
vpos.push(dy);
vpos.push(z);
vcol = vcol.concat(vcol, cornerColours[1]);
vtx.push(sx+swidth);
vtx.push(1-sy);
vpos.push(dx);
vpos.push(dy+dheight);
vpos.push(z);
vcol = vcol.concat(vcol, cornerColours[2]);
vtx.push(sx);
vtx.push(1-(sy+sheight));
vpos.push(dx+dwidth);
vpos.push(dy+dheight);
vpos.push(z);
vcol = vcol.concat(vcol, cornerColours[2]);
vtx.push(sx+swidth);
vtx.push(1-(sy+sheight));
}
}

28
Code/glMatrix/gl-matrix-min.js vendored Normal file

File diff suppressed because one or more lines are too long

4292
Code/glMatrix/gl-matrix.js Normal file

File diff suppressed because it is too large Load Diff

BIN
Resource/placeAtlas.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 260 KiB

52
Server/config.json Normal file
View File

@ -0,0 +1,52 @@
{
"port": 8081,
"instances": 1,
"defaultInstance": {
"mapRotation": [
"mkdsDefault"
],
"mapMode": "random",
"itemConfig": [
{
"item": 0,
"cfg": {}
},
{
"item": 1,
"cfg": {}
},
{
"item": 2,
"cfg": {}
}
],
"itemChance": [
{
"placement": 0.25,
"choices": [
{
"item": 0,
"chance": 0.5
},
{
"item": 1,
"chance": 0.75
},
{
"item": 2,
"chance": 1
}
]
},
{
"placement": 1,
"choices": [
{
"item": 2,
"chance": 1
}
]
}
]
}
}

View File

@ -0,0 +1,41 @@
// instances are basically individual game servers; it is possible to run more than one on the same server.
// the connection to the instance should be the first thing the client sends to the websocket server. the client is then bound to this instance for the duration of the connecton.
//
// normally a race packet exchange goes like this:
//
// C -> S: join instance. submit (kartInitFormat) (as obj.c) minus flags.
// S -> C: send back instance state, type "*". includes mode m (0 = choose course, 1 = race), data d.
//
// data d for race is in format {c:(courseName), k:(kartInitFormat[]), r:(tickRate in 1/60 tick duration increments), i:(itemConfig), p:(your kart, or -1 if in spectator mode)}
// kartInitFormat: {
// name: (username),
// char: (characterID), //physical character id.
// kart: (kartID), //physical kart id.
// kModel: (kartModelID, undefined normally. if non zero use model sent by server)
// cModel: (charModelID, same as above)
// customKParam: (same format as kartoffsetdata entry. note that custom characters always use the same offset. may be undefined.)
// flags: (info on player, eg if player is an admin, mod, on mobile etc.)
// active: boolean //karts are never deleted - they are just set as inactive after disconnect. the karts list is only completely refreshed on course change or restart.
// }
//
// repeatedly:
// C -> S: send kart data every tick. positions and checkpoint numbers
// S -> C: send array of updated kart data to back to client
//
// item request:
// C -> S: request item packet (hit itembox), type "ri"
// S -> C: return which item to select. type "si", sent to all clients so they know what you have.
// C -> S: when the user is ready to use their item, they will create the item and send a message to the server to create it on all sides. this is of type "ci", and includes the tick the item was fired on.
// S -> C (all others): type "ci" is mirrored to all other clients, server verifies that client has right to send that item first
// ---the item is now on all clients at the correct place---
// C -> S: when a client gets hit with an item, they send a packet of type "~i" with reason "h" for hit. "~i" is "change item". items that destroy themselves do not need to send this -
// they will annihilate automatically on all clients at the same tick if karts do not interfere.
//
// S -> C: when a spectator connects to a game in progress, they will be sent all item packets in order in an array with type "pi" (packed items).
//
// win:
// C -> S: completed all laps and finished course. type "w", includes finish tick.
// S -> C (all other): "w" mirrored to clients.
// C (all other) -> S: "wa" (win acknowledge) - ping back to server to confirm win. we wait until all clients agree or the timeout on the clients occurs (usually 2s)
// this is to settle win conflicts.

View File

@ -0,0 +1,169 @@
function mkjsInstance(config, instanceConfig, wss) {
var userID = 0;
var sockets = [];
var kartInf = [];
var relkDat = [];
var t = this;
var upInt = setInterval(update, 16.667);
function update() {
//generate and send kart dat packet
if (relkDat.length != 0) {
var d = new ArrayBuffer(3+relkDat.length*0x62);
var arr = new Uint8Array(d);
var view = new DataView(d);
arr[0] = 32;
view.setUint16(1, relkDat.length, true);
var off = 3;
for (var i=0; i<relkDat.length; i++) {
view.setUint16(off, relkDat[i].k, true)
var cpy = new Uint8Array(relkDat[i].d);
arr.set(cpy, off+2);
off += 0x62;
}
for (var i=0; i<sockets.length; i++) {
sockets[i].send(d)
}
relkDat = [];
}
}
//HANDLERS BELOW
function addKart(cli) {
var c = JSON.parse(JSON.stringify(cli.credentials));
c.active = true;
cli.kartID = kartInf.length;
kartInf.push(c);
for (var i=0; i<sockets.length; i++) {
if (sockets[i] != cli) sockets[i].send(JSON.stringify({
t:"+",
k:c
}))
}
}
this.addClient = function(clientSocket) {
console.log("added client")
sockets.push(clientSocket);
clientSocket.credentials.userID = userID++;
addKart(clientSocket);
sendInstanceInfo(clientSocket);
//sendClientID(clientSocket);
}
function sendInstanceInfo(clientSocket) {
clientSocket.send(JSON.stringify({
t:"*",
k:kartInf,
p:clientSocket.kartID,
c:"mkds/"+Math.floor(Math.random()*36),
r: 1,
m: 1
}))
}
function sendToClient(cli, dat) {
//this function is just here to double check if the client socket hasn't mysteriously closed yet.
//occasionally a socket can close and we will still be sending data before the "onclose" event for that socket fires.
//todo: check if there is a reliable way to determine if a socket has closed
try {
cli.send(dat);
} catch(err) {
console.warn("WARN: failed to send packet to a client. They may have already disconnected.")
}
}
this.removeClient = function(clientSocket) {
//attempt to remove client -- may not be in this instance!
var ind = sockets.indexOf(clientSocket);
if (ind != -1) sockets.splice(ind, 1); //shouldn't cause any problems.
if (clientSocket.kartID != null) {
//tell all other clients that this client's kart is now inactive.
var dat = JSON.stringify({
t:"-",
k:clientSocket.kartID
});
kartInf[clientSocket.kartID].active = false;
for (var i=0; i<sockets.length; i++) sockets[i].send(dat)
}
if (sockets.length == 0) t.resetInstance();
}
function toArrayBuffer(buffer) { //why are you making my life so difficult :(
var ab = new ArrayBuffer(buffer.length);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}
this.handleMessage = function(cli, data, flags) {
if (sockets.indexOf(cli) == null) {
socket.send(JSON.stringify(
{
t: "!",
m: "FATAL ERROR: Server does not recognise client! Are you connecting to the wrong instance?"
}
));
} else {
var d = toArrayBuffer(data);
if (flags.binary) {
//binary data
var view = new DataView(d);
var handler = binH[view.getUint8(0)];
if (handler != null) handler(cli, view);
} else {
//JSON string
var obj;
try {
obj = JSON.parse(d);
} catch (err) {
debugger; //packet recieved from server is bullshit
return;
}
var handler = wsH["$"+obj.t];
if (handler != null) handler(cli, obj);
}
}
}
var binH = [];
binH[32] = function(cli, view) {
if (cli.kartID != null) relkDat.push({k:cli.kartID, d:view.buffer.slice(1)});
}
this.resetInstance = function() {
console.log("instance reset")
userID = 0;
kartInf = [];
relkDat = [];
for (var i=0; i<sockets.length; i++) {
sockets[i].credentials.userID = userID++; //reassign user IDs to clients.
sendClientID(sockets[i]);
}
}
function sendClientID(socket) {
socket.send(JSON.stringify(
{
t: "#",
i: socket.credentials.userID
}
));
}
}
exports.mkjsInstance = mkjsInstance;

7
Server/node_modules/safe-buffer/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,7 @@
language: node_js
node_js:
- 'node'
- '5'
- '4'
- '0.12'
- '0.10'

21
Server/node_modules/safe-buffer/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Feross Aboukhadijeh
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

581
Server/node_modules/safe-buffer/README.md generated vendored Normal file
View File

@ -0,0 +1,581 @@
# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url]
#### Safer Node.js Buffer API
**Use the new Node.js v6 Buffer APIs (`Buffer.from`, `Buffer.alloc`,
`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in Node.js v0.10, v0.12, v4.x, and v5.x.**
**Uses the built-in implementations when available.**
[travis-image]: https://img.shields.io/travis/feross/safe-buffer.svg
[travis-url]: https://travis-ci.org/feross/safe-buffer
[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg
[npm-url]: https://npmjs.org/package/safe-buffer
[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg
## install
```
npm install safe-buffer
```
## usage
The goal of this package is to provide a safe replacement for the node.js `Buffer`.
It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to
the top of your node.js modules:
```js
var Buffer = require('safe-buffer').Buffer
// Existing buffer code will continue to work without issues:
new Buffer('hey', 'utf8')
new Buffer([1, 2, 3], 'utf8')
new Buffer(obj)
new Buffer(16) // create an uninitialized buffer (potentially unsafe)
// But you can use these new explicit APIs to make clear what you want:
Buffer.from('hey', 'utf8') // convert from many types to a Buffer
Buffer.alloc(16) // create a zero-filled buffer (safe)
Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
```
## api
### Class Method: Buffer.from(array)
<!-- YAML
added: v3.0.0
-->
* `array` {Array}
Allocates a new `Buffer` using an `array` of octets.
```js
const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
// creates a new Buffer containing ASCII bytes
// ['b','u','f','f','e','r']
```
A `TypeError` will be thrown if `array` is not an `Array`.
### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
<!-- YAML
added: v5.10.0
-->
* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
a `new ArrayBuffer()`
* `byteOffset` {Number} Default: `0`
* `length` {Number} Default: `arrayBuffer.length - byteOffset`
When passed a reference to the `.buffer` property of a `TypedArray` instance,
the newly created `Buffer` will share the same allocated memory as the
TypedArray.
```js
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
const buf = Buffer.from(arr.buffer); // shares the memory with arr;
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// changing the TypedArray changes the Buffer also
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>
```
The optional `byteOffset` and `length` arguments specify a memory range within
the `arrayBuffer` that will be shared by the `Buffer`.
```js
const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2
```
A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`.
### Class Method: Buffer.from(buffer)
<!-- YAML
added: v3.0.0
-->
* `buffer` {Buffer}
Copies the passed `buffer` data onto a new `Buffer` instance.
```js
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// 'auffer'
console.log(buf2.toString());
// 'buffer' (copy is not changed)
```
A `TypeError` will be thrown if `buffer` is not a `Buffer`.
### Class Method: Buffer.from(str[, encoding])
<!-- YAML
added: v5.10.0
-->
* `str` {String} String to encode.
* `encoding` {String} Encoding to use, Default: `'utf8'`
Creates a new `Buffer` containing the given JavaScript string `str`. If
provided, the `encoding` parameter identifies the character encoding.
If not provided, `encoding` defaults to `'utf8'`.
```js
const buf1 = Buffer.from('this is a tést');
console.log(buf1.toString());
// prints: this is a tést
console.log(buf1.toString('ascii'));
// prints: this is a tC)st
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf2.toString());
// prints: this is a tést
```
A `TypeError` will be thrown if `str` is not a string.
### Class Method: Buffer.alloc(size[, fill[, encoding]])
<!-- YAML
added: v5.10.0
-->
* `size` {Number}
* `fill` {Value} Default: `undefined`
* `encoding` {String} Default: `utf8`
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
`Buffer` will be *zero-filled*.
```js
const buf = Buffer.alloc(5);
console.log(buf);
// <Buffer 00 00 00 00 00>
```
The `size` must be less than or equal to the value of
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
be created if a `size` less than or equal to 0 is specified.
If `fill` is specified, the allocated `Buffer` will be initialized by calling
`buf.fill(fill)`. See [`buf.fill()`][] for more information.
```js
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// <Buffer 61 61 61 61 61>
```
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
initialized by calling `buf.fill(fill, encoding)`. For example:
```js
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
```
Calling `Buffer.alloc(size)` can be significantly slower than the alternative
`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance
contents will *never contain sensitive data*.
A `TypeError` will be thrown if `size` is not a number.
### Class Method: Buffer.allocUnsafe(size)
<!-- YAML
added: v5.10.0
-->
* `size` {Number}
Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
thrown. A zero-length Buffer will be created if a `size` less than or equal to
0 is specified.
The underlying memory for `Buffer` instances created in this way is *not
initialized*. The contents of the newly created `Buffer` are unknown and
*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
`Buffer` instances to zeroes.
```js
const buf = Buffer.allocUnsafe(5);
console.log(buf);
// <Buffer 78 e0 82 02 01>
// (octets will be different, every time)
buf.fill(0);
console.log(buf);
// <Buffer 00 00 00 00 00>
```
A `TypeError` will be thrown if `size` is not a number.
Note that the `Buffer` module pre-allocates an internal `Buffer` instance of
size `Buffer.poolSize` that is used as a pool for the fast allocation of new
`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated
`new Buffer(size)` constructor) only when `size` is less than or equal to
`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default
value of `Buffer.poolSize` is `8192` but can be modified.
Use of this pre-allocated internal memory pool is a key difference between
calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer
pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The
difference is subtle but can be important when an application requires the
additional performance that `Buffer.allocUnsafe(size)` provides.
### Class Method: Buffer.allocUnsafeSlow(size)
<!-- YAML
added: v5.10.0
-->
* `size` {Number}
Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
`size` must be less than or equal to the value of
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
be created if a `size` less than or equal to 0 is specified.
The underlying memory for `Buffer` instances created in this way is *not
initialized*. The contents of the newly created `Buffer` are unknown and
*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
`Buffer` instances to zeroes.
When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
allocations under 4KB are, by default, sliced from a single pre-allocated
`Buffer`. This allows applications to avoid the garbage collection overhead of
creating many individually allocated Buffers. This approach improves both
performance and memory usage by eliminating the need to track and cleanup as
many `Persistent` objects.
However, in the case where a developer may need to retain a small chunk of
memory from a pool for an indeterminate amount of time, it may be appropriate
to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then
copy out the relevant bits.
```js
// need to keep around a few small chunks of memory
const store = [];
socket.on('readable', () => {
const data = socket.read();
// allocate for retained data
const sb = Buffer.allocUnsafeSlow(10);
// copy the data into the new allocation
data.copy(sb, 0, 0, 10);
store.push(sb);
});
```
Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after*
a developer has observed undue memory retention in their applications.
A `TypeError` will be thrown if `size` is not a number.
### All the Rest
The rest of the `Buffer` API is exactly the same as in node.js.
[See the docs](https://nodejs.org/api/buffer.html).
## Related links
- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660)
- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4)
## Why is `Buffer` unsafe?
Today, the node.js `Buffer` constructor is overloaded to handle many different argument
types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.),
`ArrayBuffer`, and also `Number`.
The API is optimized for convenience: you can throw any type at it, and it will try to do
what you want.
Because the Buffer constructor is so powerful, you often see code like this:
```js
// Convert UTF-8 strings to hex
function toHex (str) {
return new Buffer(str).toString('hex')
}
```
***But what happens if `toHex` is called with a `Number` argument?***
### Remote Memory Disclosure
If an attacker can make your program call the `Buffer` constructor with a `Number`
argument, then they can make it allocate uninitialized memory from the node.js process.
This could potentially disclose TLS private keys, user data, or database passwords.
When the `Buffer` constructor is passed a `Number` argument, it returns an
**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like
this, you **MUST** overwrite the contents before returning it to the user.
From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size):
> `new Buffer(size)`
>
> - `size` Number
>
> The underlying memory for `Buffer` instances created in this way is not initialized.
> **The contents of a newly created `Buffer` are unknown and could contain sensitive
> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes.
(Emphasis our own.)
Whenever the programmer intended to create an uninitialized `Buffer` you often see code
like this:
```js
var buf = new Buffer(16)
// Immediately overwrite the uninitialized buffer with data from another buffer
for (var i = 0; i < buf.length; i++) {
buf[i] = otherBuf[i]
}
```
### Would this ever be a problem in real code?
Yes. It's surprisingly common to forget to check the type of your variables in a
dynamically-typed language like JavaScript.
Usually the consequences of assuming the wrong type is that your program crashes with an
uncaught exception. But the failure mode for forgetting to check the type of arguments to
the `Buffer` constructor is more catastrophic.
Here's an example of a vulnerable service that takes a JSON payload and converts it to
hex:
```js
// Take a JSON payload {str: "some string"} and convert it to hex
var server = http.createServer(function (req, res) {
var data = ''
req.setEncoding('utf8')
req.on('data', function (chunk) {
data += chunk
})
req.on('end', function () {
var body = JSON.parse(data)
res.end(new Buffer(body.str).toString('hex'))
})
})
server.listen(8080)
```
In this example, an http client just has to send:
```json
{
"str": 1000
}
```
and it will get back 1,000 bytes of uninitialized memory from the server.
This is a very serious bug. It's similar in severity to the
[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process
memory by remote attackers.
### Which real-world packages were vulnerable?
#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht)
[Mathias Buus](https://github.com/mafintosh) and I
([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages,
[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow
anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get
them to reveal 20 bytes at a time of uninitialized memory from the node.js process.
Here's
[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8)
that fixed it. We released a new fixed version, created a
[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all
vulnerable versions on npm so users will get a warning to upgrade to a newer version.
#### [`ws`](https://www.npmjs.com/package/ws)
That got us wondering if there were other vulnerable packages. Sure enough, within a short
period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the
most popular WebSocket implementation in node.js.
If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as
expected, then uninitialized server memory would be disclosed to the remote peer.
These were the vulnerable methods:
```js
socket.send(number)
socket.ping(number)
socket.pong(number)
```
Here's a vulnerable socket server with some echo functionality:
```js
server.on('connection', function (socket) {
socket.on('message', function (message) {
message = JSON.parse(message)
if (message.type === 'echo') {
socket.send(message.data) // send back the user's message
}
})
})
```
`socket.send(number)` called on the server, will disclose server memory.
Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue
was fixed, with a more detailed explanation. Props to
[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the
[Node Security Project disclosure](https://nodesecurity.io/advisories/67).
### What's the solution?
It's important that node.js offers a fast way to get memory otherwise performance-critical
applications would needlessly get a lot slower.
But we need a better way to *signal our intent* as programmers. **When we want
uninitialized memory, we should request it explicitly.**
Sensitive functionality should not be packed into a developer-friendly API that loosely
accepts many different types. This type of API encourages the lazy practice of passing
variables in without checking the type very carefully.
#### A new API: `Buffer.allocUnsafe(number)`
The functionality of creating buffers with uninitialized memory should be part of another
API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that
frequently gets user input of all sorts of different types passed into it.
```js
var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory!
// Immediately overwrite the uninitialized buffer with data from another buffer
for (var i = 0; i < buf.length; i++) {
buf[i] = otherBuf[i]
}
```
### How do we fix node.js core?
We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as
`semver-major`) which defends against one case:
```js
var str = 16
new Buffer(str, 'utf8')
```
In this situation, it's implied that the programmer intended the first argument to be a
string, since they passed an encoding as a second argument. Today, node.js will allocate
uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not
what the programmer intended.
But this is only a partial solution, since if the programmer does `new Buffer(variable)`
(without an `encoding` parameter) there's no way to know what they intended. If `variable`
is sometimes a number, then uninitialized memory will sometimes be returned.
### What's the real long-term fix?
We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when
we need uninitialized memory. But that would break 1000s of packages.
~~We believe the best solution is to:~~
~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~
~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~
#### Update
We now support adding three new APIs:
- `Buffer.from(value)` - convert from any type to a buffer
- `Buffer.alloc(size)` - create a zero-filled buffer
- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size
This solves the core problem that affected `ws` and `bittorrent-dht` which is
`Buffer(variable)` getting tricked into taking a number argument.
This way, existing code continues working and the impact on the npm ecosystem will be
minimal. Over time, npm maintainers can migrate performance-critical code to use
`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`.
### Conclusion
We think there's a serious design issue with the `Buffer` API as it exists today. It
promotes insecure software by putting high-risk functionality into a convenient API
with friendly "developer ergonomics".
This wasn't merely a theoretical exercise because we found the issue in some of the
most popular npm packages.
Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of
`buffer`.
```js
var Buffer = require('safe-buffer').Buffer
```
Eventually, we hope that node.js core can switch to this new, safer behavior. We believe
the impact on the ecosystem would be minimal since it's not a breaking change.
Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while
older, insecure packages would magically become safe from this attack vector.
## links
- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514)
- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67)
- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68)
## credit
The original issues in `bittorrent-dht`
([disclosure](https://nodesecurity.io/advisories/68)) and
`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by
[Mathias Buus](https://github.com/mafintosh) and
[Feross Aboukhadijeh](http://feross.org/).
Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues
and for his work running the [Node Security Project](https://nodesecurity.io/).
Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and
auditing the code.
## license
MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org)

1
Server/node_modules/safe-buffer/browser.js generated vendored Normal file
View File

@ -0,0 +1 @@
module.exports = require('buffer')

58
Server/node_modules/safe-buffer/index.js generated vendored Normal file
View File

@ -0,0 +1,58 @@
var buffer = require('buffer')
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
Object.keys(buffer).forEach(function (prop) {
exports[prop] = buffer[prop]
})
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
Object.keys(Buffer).forEach(function (prop) {
SafeBuffer[prop] = Buffer[prop]
})
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}

103
Server/node_modules/safe-buffer/package.json generated vendored Normal file
View File

@ -0,0 +1,103 @@
{
"_args": [
[
{
"raw": "safe-buffer@~5.0.1",
"scope": null,
"escapedName": "safe-buffer",
"name": "safe-buffer",
"rawSpec": "~5.0.1",
"spec": ">=5.0.1 <5.1.0",
"type": "range"
},
"D:\\Programs\\Dropbox\\Public\\mkds\\Server\\node_modules\\ws"
]
],
"_from": "safe-buffer@>=5.0.1 <5.1.0",
"_id": "safe-buffer@5.0.1",
"_inCache": true,
"_location": "/safe-buffer",
"_nodeVersion": "4.4.5",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/safe-buffer-5.0.1.tgz_1464588482081_0.8112505874596536"
},
"_npmUser": {
"name": "feross",
"email": "feross@feross.org"
},
"_npmVersion": "2.15.5",
"_phantomChildren": {},
"_requested": {
"raw": "safe-buffer@~5.0.1",
"scope": null,
"escapedName": "safe-buffer",
"name": "safe-buffer",
"rawSpec": "~5.0.1",
"spec": ">=5.0.1 <5.1.0",
"type": "range"
},
"_requiredBy": [
"/ws"
],
"_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.0.1.tgz",
"_shasum": "d263ca54696cd8a306b5ca6551e92de57918fbe7",
"_shrinkwrap": null,
"_spec": "safe-buffer@~5.0.1",
"_where": "D:\\Programs\\Dropbox\\Public\\mkds\\Server\\node_modules\\ws",
"author": {
"name": "Feross Aboukhadijeh",
"email": "feross@feross.org",
"url": "http://feross.org"
},
"browser": "./browser.js",
"bugs": {
"url": "https://github.com/feross/safe-buffer/issues"
},
"dependencies": {},
"description": "Safer Node.js Buffer API",
"devDependencies": {
"standard": "^7.0.0",
"tape": "^4.0.0",
"zuul": "^3.0.0"
},
"directories": {},
"dist": {
"shasum": "d263ca54696cd8a306b5ca6551e92de57918fbe7",
"tarball": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.0.1.tgz"
},
"gitHead": "1e371a367da962afae2bebc527b50271c739d28c",
"homepage": "https://github.com/feross/safe-buffer",
"keywords": [
"buffer",
"buffer allocate",
"node security",
"safe",
"safe-buffer",
"security",
"uninitialized"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "feross",
"email": "feross@feross.org"
},
{
"name": "mafintosh",
"email": "mathiasbuus@gmail.com"
}
],
"name": "safe-buffer",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/feross/safe-buffer.git"
},
"scripts": {
"test": "standard && tape test.js"
},
"version": "5.0.1"
}

99
Server/node_modules/safe-buffer/test.js generated vendored Normal file
View File

@ -0,0 +1,99 @@
var test = require('tape')
var SafeBuffer = require('./').Buffer
test('new SafeBuffer(value) works just like Buffer', function (t) {
t.deepEqual(new SafeBuffer('hey'), new Buffer('hey'))
t.deepEqual(new SafeBuffer('hey', 'utf8'), new Buffer('hey', 'utf8'))
t.deepEqual(new SafeBuffer('686579', 'hex'), new Buffer('686579', 'hex'))
t.deepEqual(new SafeBuffer([1, 2, 3]), new Buffer([1, 2, 3]))
t.deepEqual(new SafeBuffer(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3])))
t.equal(typeof SafeBuffer.isBuffer, 'function')
t.equal(SafeBuffer.isBuffer(new SafeBuffer('hey')), true)
t.equal(Buffer.isBuffer(new SafeBuffer('hey')), true)
t.notOk(SafeBuffer.isBuffer({}))
t.end()
})
test('SafeBuffer.from(value) converts to a Buffer', function (t) {
t.deepEqual(SafeBuffer.from('hey'), new Buffer('hey'))
t.deepEqual(SafeBuffer.from('hey', 'utf8'), new Buffer('hey', 'utf8'))
t.deepEqual(SafeBuffer.from('686579', 'hex'), new Buffer('686579', 'hex'))
t.deepEqual(SafeBuffer.from([1, 2, 3]), new Buffer([1, 2, 3]))
t.deepEqual(SafeBuffer.from(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3])))
t.end()
})
test('SafeBuffer.alloc(number) returns zeroed-out memory', function (t) {
for (var i = 0; i < 10; i++) {
var expected1 = new Buffer(1000)
expected1.fill(0)
t.deepEqual(SafeBuffer.alloc(1000), expected1)
var expected2 = new Buffer(1000 * 1000)
expected2.fill(0)
t.deepEqual(SafeBuffer.alloc(1000 * 1000), expected2)
}
t.end()
})
test('SafeBuffer.allocUnsafe(number)', function (t) {
var buf = SafeBuffer.allocUnsafe(100) // unitialized memory
t.equal(buf.length, 100)
t.equal(SafeBuffer.isBuffer(buf), true)
t.equal(Buffer.isBuffer(buf), true)
t.end()
})
test('SafeBuffer.from() throws with number types', function (t) {
t.plan(5)
t.throws(function () {
SafeBuffer.from(0)
})
t.throws(function () {
SafeBuffer.from(-1)
})
t.throws(function () {
SafeBuffer.from(NaN)
})
t.throws(function () {
SafeBuffer.from(Infinity)
})
t.throws(function () {
SafeBuffer.from(99)
})
})
test('SafeBuffer.allocUnsafe() throws with non-number types', function (t) {
t.plan(4)
t.throws(function () {
SafeBuffer.allocUnsafe('hey')
})
t.throws(function () {
SafeBuffer.allocUnsafe('hey', 'utf8')
})
t.throws(function () {
SafeBuffer.allocUnsafe([1, 2, 3])
})
t.throws(function () {
SafeBuffer.allocUnsafe({})
})
})
test('SafeBuffer.alloc() throws with non-number types', function (t) {
t.plan(4)
t.throws(function () {
SafeBuffer.alloc('hey')
})
t.throws(function () {
SafeBuffer.alloc('hey', 'utf8')
})
t.throws(function () {
SafeBuffer.alloc([1, 2, 3])
})
t.throws(function () {
SafeBuffer.alloc({})
})
})

22
Server/node_modules/ultron/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Unshift.io, Arnout Kazemier, the Contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

138
Server/node_modules/ultron/index.js generated vendored Normal file
View File

@ -0,0 +1,138 @@
'use strict';
var has = Object.prototype.hasOwnProperty;
/**
* An auto incrementing id which we can use to create "unique" Ultron instances
* so we can track the event emitters that are added through the Ultron
* interface.
*
* @type {Number}
* @private
*/
var id = 0;
/**
* Ultron is high-intelligence robot. It gathers intelligence so it can start improving
* upon his rudimentary design. It will learn from your EventEmitting patterns
* and exterminate them.
*
* @constructor
* @param {EventEmitter} ee EventEmitter instance we need to wrap.
* @api public
*/
function Ultron(ee) {
if (!(this instanceof Ultron)) return new Ultron(ee);
this.id = id++;
this.ee = ee;
}
/**
* Register a new EventListener for the given event.
*
* @param {String} event Name of the event.
* @param {Functon} fn Callback function.
* @param {Mixed} context The context of the function.
* @returns {Ultron}
* @api public
*/
Ultron.prototype.on = function on(event, fn, context) {
fn.__ultron = this.id;
this.ee.on(event, fn, context);
return this;
};
/**
* Add an EventListener that's only called once.
*
* @param {String} event Name of the event.
* @param {Function} fn Callback function.
* @param {Mixed} context The context of the function.
* @returns {Ultron}
* @api public
*/
Ultron.prototype.once = function once(event, fn, context) {
fn.__ultron = this.id;
this.ee.once(event, fn, context);
return this;
};
/**
* Remove the listeners we assigned for the given event.
*
* @returns {Ultron}
* @api public
*/
Ultron.prototype.remove = function remove() {
var args = arguments
, ee = this.ee
, event;
//
// When no event names are provided we assume that we need to clear all the
// events that were assigned through us.
//
if (args.length === 1 && 'string' === typeof args[0]) {
args = args[0].split(/[, ]+/);
} else if (!args.length) {
if (ee.eventNames) {
args = ee.eventNames();
} else if (ee._events) {
args = [];
for (event in ee._events) {
if (has.call(ee._events, event)) args.push(event);
}
if (Object.getOwnPropertySymbols) {
args = args.concat(Object.getOwnPropertySymbols(ee._events));
}
}
}
for (var i = 0; i < args.length; i++) {
var listeners = ee.listeners(args[i]);
for (var j = 0; j < listeners.length; j++) {
event = listeners[j];
//
// Once listeners have a `listener` property that stores the real listener
// in the EventEmitter that ships with Node.js.
//
if (event.listener) {
if (event.listener.__ultron !== this.id) continue;
delete event.listener.__ultron;
} else {
if (event.__ultron !== this.id) continue;
delete event.__ultron;
}
ee.removeListener(args[i], event);
}
}
return this;
};
/**
* Destroy the Ultron instance, remove all listeners and release all references.
*
* @returns {Boolean}
* @api public
*/
Ultron.prototype.destroy = function destroy() {
if (!this.ee) return false;
this.remove();
this.ee = null;
return true;
};
//
// Expose the module.
//
module.exports = Ultron;

112
Server/node_modules/ultron/package.json generated vendored Normal file
View File

@ -0,0 +1,112 @@
{
"_args": [
[
{
"raw": "ultron@~1.1.0",
"scope": null,
"escapedName": "ultron",
"name": "ultron",
"rawSpec": "~1.1.0",
"spec": ">=1.1.0 <1.2.0",
"type": "range"
},
"D:\\Programs\\Dropbox\\Public\\mkds\\Server\\node_modules\\ws"
]
],
"_from": "ultron@>=1.1.0 <1.2.0",
"_id": "ultron@1.1.0",
"_inCache": true,
"_location": "/ultron",
"_nodeVersion": "6.2.1",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/ultron-1.1.0.tgz_1483969751660_0.8877595944795758"
},
"_npmUser": {
"name": "3rdeden",
"email": "npm@3rd-Eden.com"
},
"_npmVersion": "3.9.3",
"_phantomChildren": {},
"_requested": {
"raw": "ultron@~1.1.0",
"scope": null,
"escapedName": "ultron",
"name": "ultron",
"rawSpec": "~1.1.0",
"spec": ">=1.1.0 <1.2.0",
"type": "range"
},
"_requiredBy": [
"/ws"
],
"_resolved": "https://registry.npmjs.org/ultron/-/ultron-1.1.0.tgz",
"_shasum": "b07a2e6a541a815fc6a34ccd4533baec307ca864",
"_shrinkwrap": null,
"_spec": "ultron@~1.1.0",
"_where": "D:\\Programs\\Dropbox\\Public\\mkds\\Server\\node_modules\\ws",
"author": {
"name": "Arnout Kazemier"
},
"bugs": {
"url": "https://github.com/unshiftio/ultron/issues"
},
"dependencies": {},
"description": "Ultron is high-intelligence robot. It gathers intel so it can start improving upon his rudimentary design",
"devDependencies": {
"assume": "1.4.x",
"eventemitter3": "2.0.x",
"istanbul": "0.4.x",
"mocha": "~3.2.0",
"pre-commit": "~1.2.0"
},
"directories": {},
"dist": {
"shasum": "b07a2e6a541a815fc6a34ccd4533baec307ca864",
"tarball": "https://registry.npmjs.org/ultron/-/ultron-1.1.0.tgz"
},
"gitHead": "6eb97b74402978aebda4a9d497cb6243ec80c9f1",
"homepage": "https://github.com/unshiftio/ultron",
"keywords": [
"Ultron",
"robot",
"gather",
"intelligence",
"event",
"events",
"eventemitter",
"emitter",
"cleanup"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "unshift",
"email": "npm@unshift.io"
},
{
"name": "v1",
"email": "info@3rd-Eden.com"
},
{
"name": "3rdeden",
"email": "npm@3rd-Eden.com"
}
],
"name": "ultron",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/unshiftio/ultron.git"
},
"scripts": {
"100%": "istanbul check-coverage --statements 100 --functions 100 --lines 100 --branches 100",
"coverage": "istanbul cover _mocha -- test.js",
"test": "mocha test.js",
"test-travis": "istanbul cover _mocha --report lcovonly -- test.js",
"watch": "mocha --watch test.js"
},
"version": "1.1.0"
}

21
Server/node_modules/ws/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

259
Server/node_modules/ws/README.md generated vendored Normal file
View File

@ -0,0 +1,259 @@
# ws: a Node.js WebSocket library
[![Version npm](https://img.shields.io/npm/v/ws.svg)](https://www.npmjs.com/package/ws)
[![Linux Build](https://img.shields.io/travis/websockets/ws/master.svg)](https://travis-ci.org/websockets/ws)
[![Windows Build](https://ci.appveyor.com/api/projects/status/github/websockets/ws?branch=master&svg=true)](https://ci.appveyor.com/project/lpinca/ws)
[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg)](https://coveralls.io/r/websockets/ws?branch=master)
`ws` is a simple to use, blazing fast, and thoroughly tested WebSocket client
and server implementation.
Passes the quite extensive Autobahn test suite. See http://websockets.github.io/ws/
for the full reports.
## Protocol support
* **HyBi drafts 07-12** (Use the option `protocolVersion: 8`)
* **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`)
## Installing
```
npm install --save ws
```
### Opt-in for performance
There are 2 optional modules that can be installed along side with the `ws`
module. These modules are binary addons which improve certain operations, but as
they are binary addons they require compilation which can fail if no c++
compiler is installed on the host system.
- `npm install --save bufferutil`: Improves internal buffer operations which
allows for faster processing of masked WebSocket frames and general buffer
operations.
- `npm install --save utf-8-validate`: The specification requires validation of
invalid UTF-8 chars, some of these validations could not be done in JavaScript
hence the need for a binary addon. In most cases you will already be
validating the input that you receive for security purposes leading to double
validation. But if you want to be 100% spec-conforming and have fast
validation of UTF-8 then this module is a must.
## API Docs
See [`/doc/ws.md`](https://github.com/websockets/ws/blob/master/doc/ws.md)
for Node.js-like docs for the ws classes.
## WebSocket compression
`ws` supports the [permessage-deflate extension][permessage-deflate] extension
which enables the client and server to negotiate a compression algorithm and
its parameters, and then selectively apply it to the data payloads of each
WebSocket message.
The extension is enabled by default but adds a significant overhead in terms of
performance and memory comsumption. We suggest to use WebSocket compression
only if it is really needed.
To disable the extension you can set the `perMessageDeflate` option to `false`.
On the server:
```js
const WebSocket = require('ws');
const wss = new WebSocket.Server({
perMessageDeflate: false,
port: 8080
});
```
On the client:
```js
const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path', {
perMessageDeflate: false
});
```
## Usage examples
### Sending and receiving text data
```js
const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function incoming(data, flags) {
// flags.binary will be set if a binary data is received.
// flags.masked will be set if the data was masked.
});
```
### Sending binary data
```js
const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function open() {
const array = new Float32Array(5);
for (var i = 0; i < array.length; ++i) {
array[i] = i / 2;
}
ws.send(array);
});
```
### Server example
```js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
```
### Broadcast example
```js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
// Broadcast to all.
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
};
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
// Broadcast to everyone else.
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
});
});
```
### ExpressJS example
```js
const express = require('express');
const http = require('http');
const url = require('url');
const WebSocket = require('ws');
const app = express();
app.use(function (req, res) {
res.send({ msg: "hello" });
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
const location = url.parse(ws.upgradeReq.url, true);
// You might use location.query.access_token to authenticate or share sessions
// or ws.upgradeReq.headers.cookie (see http://stackoverflow.com/a/16395220/151312)
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
server.listen(8080, function listening() {
console.log('Listening on %d', server.address().port);
});
```
### echo.websocket.org demo
```js
const WebSocket = require('ws');
const ws = new WebSocket('wss://echo.websocket.org/', {
origin: 'https://websocket.org'
});
ws.on('open', function open() {
console.log('connected');
ws.send(Date.now());
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function incoming(data, flags) {
console.log(`Roundtrip time: ${Date.now() - data} ms`, flags);
setTimeout(function timeout() {
ws.send(Date.now());
}, 500);
});
```
### Other examples
For a full example with a browser client communicating with a ws server, see the
examples folder.
Otherwise, see the test cases.
## Error handling best practices
```js
// If the WebSocket is closed before the following send is attempted
ws.send('something');
// Errors (both immediate and async write errors) can be detected in an optional
// callback. The callback is also the only way of being notified that data has
// actually been sent.
ws.send('something', function ack(error) {
// If error is not defined, the send has been completed, otherwise the error
// object will indicate what failed.
});
// Immediate errors can also be handled with `try...catch`, but **note** that
// since sends are inherently asynchronous, socket write failures will *not* be
// captured when this technique is used.
try { ws.send('something'); }
catch (e) { /* handle error */ }
```
## Changelog
We're using the GitHub [`releases`](https://github.com/websockets/ws/releases)
for changelog entries.
## License
[MIT](LICENSE)
[permessage-deflate]: https://tools.ietf.org/html/rfc7692

33
Server/node_modules/ws/SECURITY.md generated vendored Normal file
View File

@ -0,0 +1,33 @@
# Security Guidelines
Please contact us directly at **security@3rd-Eden.com** for any bug that might
impact the security of this project. Please prefix the subject of your email
with `[security]` in lowercase and square brackets. Our email filters will
automatically prevent these messages from being moved to our spam box.
You will receive an acknowledgement of your report within **24 hours**.
All emails that do not include security vulnerabilities will be removed and
blocked instantly.
## Exceptions
If you do not receive an acknowledgement within the said time frame please give
us the benefit of the doubt as it's possible that we haven't seen it yet. In
this case please send us a message **without details** using one of the
following methods:
- Contact the lead developers of this project on their personal e-mails. You
can find the e-mails in the git logs, for example using the following command:
`git --no-pager show -s --format='%an <%ae>' <gitsha>` where `<gitsha>` is the
SHA1 of their latest commit in the project.
- Create a GitHub issue stating contact details and the severity of the issue.
Once we have acknowledged receipt of your report and confirmed the bug
ourselves we will work with you to fix the vulnerability and publicly acknowledge
your responsible disclosure, if you wish. In addition to that we will report
all vulnerabilities to the [Node Security Project](https://nodesecurity.io/).
## History
04 Jan 2016: [Buffer vulnerablity](https://github.com/websockets/ws/releases/tag/1.0.1)

15
Server/node_modules/ws/index.js generated vendored Normal file
View File

@ -0,0 +1,15 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
'use strict';
const WebSocket = require('./lib/WebSocket');
WebSocket.Server = require('./lib/WebSocketServer');
WebSocket.Receiver = require('./lib/Receiver');
WebSocket.Sender = require('./lib/Sender');
module.exports = WebSocket;

71
Server/node_modules/ws/lib/BufferUtil.js generated vendored Normal file
View File

@ -0,0 +1,71 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
'use strict';
const safeBuffer = require('safe-buffer');
const Buffer = safeBuffer.Buffer;
/**
* Merges an array of buffers into a new buffer.
*
* @param {Buffer[]} list The array of buffers to concat
* @param {Number} totalLength The total length of buffers in the list
* @return {Buffer} The resulting buffer
* @public
*/
const concat = (list, totalLength) => {
const target = Buffer.allocUnsafe(totalLength);
var offset = 0;
for (var i = 0; i < list.length; i++) {
const buf = list[i];
buf.copy(target, offset);
offset += buf.length;
}
return target;
};
try {
const bufferUtil = require('bufferutil');
module.exports = Object.assign({ concat }, bufferUtil.BufferUtil || bufferUtil);
} catch (e) /* istanbul ignore next */ {
/**
* Masks a buffer using the given mask.
*
* @param {Buffer} source The buffer to mask
* @param {Buffer} mask The mask to use
* @param {Buffer} output The buffer where to store the result
* @param {Number} offset The offset at which to start writing
* @param {Number} length The number of bytes to mask.
* @public
*/
const mask = (source, mask, output, offset, length) => {
for (var i = 0; i < length; i++) {
output[offset + i] = source[i] ^ mask[i & 3];
}
};
/**
* Unmasks a buffer using the given mask.
*
* @param {Buffer} buffer The buffer to unmask
* @param {Buffer} mask The mask to use
* @public
*/
const unmask = (buffer, mask) => {
// Required until https://github.com/nodejs/node/issues/9006 is resolved.
const length = buffer.length;
for (var i = 0; i < length; i++) {
buffer[i] ^= mask[i & 3];
}
};
module.exports = { concat, mask, unmask };
}

10
Server/node_modules/ws/lib/Constants.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
'use strict';
const safeBuffer = require('safe-buffer');
const Buffer = safeBuffer.Buffer;
exports.BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];
exports.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
exports.EMPTY_BUFFER = Buffer.alloc(0);
exports.NOOP = () => {};

28
Server/node_modules/ws/lib/ErrorCodes.js generated vendored Normal file
View File

@ -0,0 +1,28 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
'use strict';
module.exports = {
isValidErrorCode: function (code) {
return (code >= 1000 && code <= 1013 && code !== 1004 && code !== 1005 && code !== 1006) ||
(code >= 3000 && code <= 4999);
},
1000: 'normal',
1001: 'going away',
1002: 'protocol error',
1003: 'unsupported data',
1004: 'reserved',
1005: 'reserved for extensions',
1006: 'reserved for extensions',
1007: 'inconsistent or invalid data',
1008: 'policy violation',
1009: 'message too big',
1010: 'extension handshake missing',
1011: 'an unexpected condition prevented the request from being fulfilled',
1012: 'service restart',
1013: 'try again later'
};

155
Server/node_modules/ws/lib/EventTarget.js generated vendored Normal file
View File

@ -0,0 +1,155 @@
'use strict';
/**
* Class representing an event.
*
* @private
*/
class Event {
/**
* Create a new `Event`.
*
* @param {String} type The name of the event
* @param {Object} target A reference to the target to which the event was dispatched
*/
constructor (type, target) {
this.target = target;
this.type = type;
}
}
/**
* Class representing a message event.
*
* @extends Event
* @private
*/
class MessageEvent extends Event {
/**
* Create a new `MessageEvent`.
*
* @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data
* @param {Boolean} isBinary Specifies if `data` is binary
* @param {WebSocket} target A reference to the target to which the event was dispatched
*/
constructor (data, isBinary, target) {
super('message', target);
this.binary = isBinary; // non-standard.
this.data = data;
}
}
/**
* Class representing a close event.
*
* @extends Event
* @private
*/
class CloseEvent extends Event {
/**
* Create a new `CloseEvent`.
*
* @param {Number} code The status code explaining why the connection is being closed
* @param {String} reason A human-readable string explaining why the connection is closing
* @param {WebSocket} target A reference to the target to which the event was dispatched
*/
constructor (code, reason, target) {
super('close', target);
this.wasClean = code === undefined || code === 1000;
this.reason = reason;
this.target = target;
this.type = 'close';
this.code = code;
}
}
/**
* Class representing an open event.
*
* @extends Event
* @private
*/
class OpenEvent extends Event {
/**
* Create a new `OpenEvent`.
*
* @param {WebSocket} target A reference to the target to which the event was dispatched
*/
constructor (target) {
super('open', target);
}
}
/**
* This provides methods for emulating the `EventTarget` interface. It's not
* meant to be used directly.
*
* @mixin
*/
const EventTarget = {
/**
* Register an event listener.
*
* @param {String} method A string representing the event type to listen for
* @param {Function} listener The listener to add
* @public
*/
addEventListener (method, listener) {
if (typeof listener !== 'function') return;
function onMessage (data, flags) {
listener.call(this, new MessageEvent(data, !!flags.binary, this));
}
function onClose (code, message) {
listener.call(this, new CloseEvent(code, message, this));
}
function onError (event) {
event.type = 'error';
event.target = this;
listener.call(this, event);
}
function onOpen () {
listener.call(this, new OpenEvent(this));
}
if (method === 'message') {
onMessage._listener = listener;
this.on(method, onMessage);
} else if (method === 'close') {
onClose._listener = listener;
this.on(method, onClose);
} else if (method === 'error') {
onError._listener = listener;
this.on(method, onError);
} else if (method === 'open') {
onOpen._listener = listener;
this.on(method, onOpen);
} else {
this.on(method, listener);
}
},
/**
* Remove an event listener.
*
* @param {String} method A string representing the event type to remove
* @param {Function} listener The listener to remove
* @public
*/
removeEventListener (method, listener) {
const listeners = this.listeners(method);
for (var i = 0; i < listeners.length; i++) {
if (listeners[i] === listener || listeners[i]._listener === listener) {
this.removeListener(method, listeners[i]);
}
}
}
};
module.exports = EventTarget;

67
Server/node_modules/ws/lib/Extensions.js generated vendored Normal file
View File

@ -0,0 +1,67 @@
'use strict';
/**
* Parse the `Sec-WebSocket-Extensions` header into an object.
*
* @param {String} value field value of the header
* @return {Object} The parsed object
* @public
*/
const parse = (value) => {
value = value || '';
const extensions = {};
value.split(',').forEach((v) => {
const params = v.split(';');
const token = params.shift().trim();
const paramsList = extensions[token] = extensions[token] || [];
const parsedParams = {};
params.forEach((param) => {
const parts = param.trim().split('=');
const key = parts[0];
var value = parts[1];
if (value === undefined) {
value = true;
} else {
// unquote value
if (value[0] === '"') {
value = value.slice(1);
}
if (value[value.length - 1] === '"') {
value = value.slice(0, value.length - 1);
}
}
(parsedParams[key] = parsedParams[key] || []).push(value);
});
paramsList.push(parsedParams);
});
return extensions;
};
/**
* Serialize a parsed `Sec-WebSocket-Extensions` header to a string.
*
* @param {Object} value The object to format
* @return {String} A string representing the given value
* @public
*/
const format = (value) => {
return Object.keys(value).map((token) => {
var paramsList = value[token];
if (!Array.isArray(paramsList)) paramsList = [paramsList];
return paramsList.map((params) => {
return [token].concat(Object.keys(params).map((k) => {
var p = params[k];
if (!Array.isArray(p)) p = [p];
return p.map((v) => v === true ? k : `${k}=${v}`).join('; ');
})).join('; ');
}).join(', ');
}).join(', ');
};
module.exports = { format, parse };

384
Server/node_modules/ws/lib/PerMessageDeflate.js generated vendored Normal file
View File

@ -0,0 +1,384 @@
'use strict';
const safeBuffer = require('safe-buffer');
const zlib = require('zlib');
const bufferUtil = require('./BufferUtil');
const Buffer = safeBuffer.Buffer;
const AVAILABLE_WINDOW_BITS = [8, 9, 10, 11, 12, 13, 14, 15];
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
const EMPTY_BLOCK = Buffer.from([0x00]);
const DEFAULT_WINDOW_BITS = 15;
const DEFAULT_MEM_LEVEL = 8;
/**
* Per-message Deflate implementation.
*/
class PerMessageDeflate {
constructor (options, isServer, maxPayload) {
this._options = options || {};
this._isServer = !!isServer;
this._inflate = null;
this._deflate = null;
this.params = null;
this._maxPayload = maxPayload || 0;
this.threshold = this._options.threshold === undefined ? 1024 : this._options.threshold;
}
static get extensionName () {
return 'permessage-deflate';
}
/**
* Create extension parameters offer.
*
* @return {Object} Extension parameters
* @public
*/
offer () {
const params = {};
if (this._options.serverNoContextTakeover) {
params.server_no_context_takeover = true;
}
if (this._options.clientNoContextTakeover) {
params.client_no_context_takeover = true;
}
if (this._options.serverMaxWindowBits) {
params.server_max_window_bits = this._options.serverMaxWindowBits;
}
if (this._options.clientMaxWindowBits) {
params.client_max_window_bits = this._options.clientMaxWindowBits;
} else if (this._options.clientMaxWindowBits == null) {
params.client_max_window_bits = true;
}
return params;
}
/**
* Accept extension offer.
*
* @param {Array} paramsList Extension parameters
* @return {Object} Accepted configuration
* @public
*/
accept (paramsList) {
paramsList = this.normalizeParams(paramsList);
var params;
if (this._isServer) {
params = this.acceptAsServer(paramsList);
} else {
params = this.acceptAsClient(paramsList);
}
this.params = params;
return params;
}
/**
* Releases all resources used by the extension.
*
* @public
*/
cleanup () {
if (this._inflate) {
if (this._inflate.writeInProgress) {
this._inflate.pendingClose = true;
} else {
this._inflate.close();
this._inflate = null;
}
}
if (this._deflate) {
if (this._deflate.writeInProgress) {
this._deflate.pendingClose = true;
} else {
this._deflate.close();
this._deflate = null;
}
}
}
/**
* Accept extension offer from client.
*
* @param {Array} paramsList Extension parameters
* @return {Object} Accepted configuration
* @private
*/
acceptAsServer (paramsList) {
const accepted = {};
const result = paramsList.some((params) => {
if ((
this._options.serverNoContextTakeover === false &&
params.server_no_context_takeover
) || (
this._options.serverMaxWindowBits === false &&
params.server_max_window_bits
) || (
typeof this._options.serverMaxWindowBits === 'number' &&
typeof params.server_max_window_bits === 'number' &&
this._options.serverMaxWindowBits > params.server_max_window_bits
) || (
typeof this._options.clientMaxWindowBits === 'number' &&
!params.client_max_window_bits
)) {
return;
}
if (
this._options.serverNoContextTakeover ||
params.server_no_context_takeover
) {
accepted.server_no_context_takeover = true;
}
if (this._options.clientNoContextTakeover) {
accepted.client_no_context_takeover = true;
}
if (
this._options.clientNoContextTakeover !== false &&
params.client_no_context_takeover
) {
accepted.client_no_context_takeover = true;
}
if (typeof this._options.serverMaxWindowBits === 'number') {
accepted.server_max_window_bits = this._options.serverMaxWindowBits;
} else if (typeof params.server_max_window_bits === 'number') {
accepted.server_max_window_bits = params.server_max_window_bits;
}
if (typeof this._options.clientMaxWindowBits === 'number') {
accepted.client_max_window_bits = this._options.clientMaxWindowBits;
} else if (
this._options.clientMaxWindowBits !== false &&
typeof params.client_max_window_bits === 'number'
) {
accepted.client_max_window_bits = params.client_max_window_bits;
}
return true;
});
if (!result) throw new Error(`Doesn't support the offered configuration`);
return accepted;
}
/**
* Accept extension response from server.
*
* @param {Array} paramsList Extension parameters
* @return {Object} Accepted configuration
* @private
*/
acceptAsClient (paramsList) {
const params = paramsList[0];
if (this._options.clientNoContextTakeover != null) {
if (
this._options.clientNoContextTakeover === false &&
params.client_no_context_takeover
) {
throw new Error('Invalid value for "client_no_context_takeover"');
}
}
if (this._options.clientMaxWindowBits != null) {
if (
this._options.clientMaxWindowBits === false &&
params.client_max_window_bits
) {
throw new Error('Invalid value for "client_max_window_bits"');
}
if (
typeof this._options.clientMaxWindowBits === 'number' && (
!params.client_max_window_bits ||
params.client_max_window_bits > this._options.clientMaxWindowBits
)) {
throw new Error('Invalid value for "client_max_window_bits"');
}
}
return params;
}
/**
* Normalize extensions parameters.
*
* @param {Array} paramsList Extension parameters
* @return {Array} Normalized extensions parameters
* @private
*/
normalizeParams (paramsList) {
return paramsList.map((params) => {
Object.keys(params).forEach((key) => {
var value = params[key];
if (value.length > 1) {
throw new Error(`Multiple extension parameters for ${key}`);
}
value = value[0];
switch (key) {
case 'server_no_context_takeover':
case 'client_no_context_takeover':
if (value !== true) {
throw new Error(`invalid extension parameter value for ${key} (${value})`);
}
params[key] = true;
break;
case 'server_max_window_bits':
case 'client_max_window_bits':
if (typeof value === 'string') {
value = parseInt(value, 10);
if (!~AVAILABLE_WINDOW_BITS.indexOf(value)) {
throw new Error(`invalid extension parameter value for ${key} (${value})`);
}
}
if (!this._isServer && value === true) {
throw new Error(`Missing extension parameter value for ${key}`);
}
params[key] = value;
break;
default:
throw new Error(`Not defined extension parameter (${key})`);
}
});
return params;
});
}
/**
* Decompress data.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
decompress (data, fin, callback) {
const endpoint = this._isServer ? 'client' : 'server';
if (!this._inflate) {
const maxWindowBits = this.params[`${endpoint}_max_window_bits`];
this._inflate = zlib.createInflateRaw({
windowBits: typeof maxWindowBits === 'number' ? maxWindowBits : DEFAULT_WINDOW_BITS
});
}
this._inflate.writeInProgress = true;
var totalLength = 0;
const buffers = [];
var err;
const onData = (data) => {
totalLength += data.length;
if (this._maxPayload < 1 || totalLength <= this._maxPayload) {
return buffers.push(data);
}
err = new Error('max payload size exceeded');
err.closeCode = 1009;
this._inflate.reset();
};
const onError = (err) => {
cleanup();
callback(err);
};
const cleanup = () => {
if (!this._inflate) return;
this._inflate.removeListener('error', onError);
this._inflate.removeListener('data', onData);
this._inflate.writeInProgress = false;
if (
(fin && this.params[`${endpoint}_no_context_takeover`]) ||
this._inflate.pendingClose
) {
this._inflate.close();
this._inflate = null;
}
};
this._inflate.on('error', onError).on('data', onData);
this._inflate.write(data);
if (fin) this._inflate.write(TRAILER);
this._inflate.flush(() => {
cleanup();
if (err) callback(err);
else callback(null, bufferUtil.concat(buffers, totalLength));
});
}
/**
* Compress data.
*
* @param {Buffer} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
compress (data, fin, callback) {
if (!data || data.length === 0) {
process.nextTick(callback, null, EMPTY_BLOCK);
return;
}
const endpoint = this._isServer ? 'server' : 'client';
if (!this._deflate) {
const maxWindowBits = this.params[`${endpoint}_max_window_bits`];
this._deflate = zlib.createDeflateRaw({
flush: zlib.Z_SYNC_FLUSH,
windowBits: typeof maxWindowBits === 'number' ? maxWindowBits : DEFAULT_WINDOW_BITS,
memLevel: this._options.memLevel || DEFAULT_MEM_LEVEL
});
}
this._deflate.writeInProgress = true;
var totalLength = 0;
const buffers = [];
const onData = (data) => {
totalLength += data.length;
buffers.push(data);
};
const onError = (err) => {
cleanup();
callback(err);
};
const cleanup = () => {
if (!this._deflate) return;
this._deflate.removeListener('error', onError);
this._deflate.removeListener('data', onData);
this._deflate.writeInProgress = false;
if (
(fin && this.params[`${endpoint}_no_context_takeover`]) ||
this._deflate.pendingClose
) {
this._deflate.close();
this._deflate = null;
}
};
this._deflate.on('error', onError).on('data', onData);
this._deflate.write(data);
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
cleanup();
var data = bufferUtil.concat(buffers, totalLength);
if (fin) data = data.slice(0, data.length - 4);
callback(null, data);
});
}
}
module.exports = PerMessageDeflate;

555
Server/node_modules/ws/lib/Receiver.js generated vendored Normal file
View File

@ -0,0 +1,555 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
'use strict';
const safeBuffer = require('safe-buffer');
const PerMessageDeflate = require('./PerMessageDeflate');
const isValidUTF8 = require('./Validation');
const bufferUtil = require('./BufferUtil');
const ErrorCodes = require('./ErrorCodes');
const constants = require('./Constants');
const Buffer = safeBuffer.Buffer;
const GET_INFO = 0;
const GET_PAYLOAD_LENGTH_16 = 1;
const GET_PAYLOAD_LENGTH_64 = 2;
const GET_MASK = 3;
const GET_DATA = 4;
const INFLATING = 5;
/**
* HyBi Receiver implementation.
*/
class Receiver {
/**
* Creates a Receiver instance.
*
* @param {Object} extensions An object containing the negotiated extensions
* @param {Number} maxPayload The maximum allowed message length
* @param {String} binaryType The type for binary data
*/
constructor (extensions, maxPayload, binaryType) {
this.binaryType = binaryType || constants.BINARY_TYPES[0];
this.extensions = extensions || {};
this.maxPayload = maxPayload | 0;
this.bufferedBytes = 0;
this.buffers = [];
this.compressed = false;
this.payloadLength = 0;
this.fragmented = 0;
this.masked = false;
this.fin = false;
this.mask = null;
this.opcode = 0;
this.totalPayloadLength = 0;
this.messageLength = 0;
this.fragments = [];
this.cleanupCallback = null;
this.hadError = false;
this.dead = false;
this.loop = false;
this.onmessage = null;
this.onclose = null;
this.onerror = null;
this.onping = null;
this.onpong = null;
this.state = GET_INFO;
}
/**
* Consumes bytes from the available buffered data.
*
* @param {Number} bytes The number of bytes to consume
* @return {Buffer} Consumed bytes
* @private
*/
readBuffer (bytes) {
var offset = 0;
var dst;
var l;
this.bufferedBytes -= bytes;
if (bytes === this.buffers[0].length) return this.buffers.shift();
if (bytes < this.buffers[0].length) {
dst = this.buffers[0].slice(0, bytes);
this.buffers[0] = this.buffers[0].slice(bytes);
return dst;
}
dst = Buffer.allocUnsafe(bytes);
while (bytes > 0) {
l = this.buffers[0].length;
if (bytes >= l) {
this.buffers[0].copy(dst, offset);
offset += l;
this.buffers.shift();
} else {
this.buffers[0].copy(dst, offset, 0, bytes);
this.buffers[0] = this.buffers[0].slice(bytes);
}
bytes -= l;
}
return dst;
}
/**
* Checks if the number of buffered bytes is bigger or equal than `n` and
* calls `cleanup` if necessary.
*
* @param {Number} n The number of bytes to check against
* @return {Boolean} `true` if `bufferedBytes >= n`, else `false`
* @private
*/
hasBufferedBytes (n) {
if (this.bufferedBytes >= n) return true;
this.loop = false;
if (this.dead) this.cleanup(this.cleanupCallback);
return false;
}
/**
* Adds new data to the parser.
*
* @public
*/
add (data) {
if (this.dead) return;
this.bufferedBytes += data.length;
this.buffers.push(data);
this.startLoop();
}
/**
* Starts the parsing loop.
*
* @private
*/
startLoop () {
this.loop = true;
while (this.loop) {
switch (this.state) {
case GET_INFO:
this.getInfo();
break;
case GET_PAYLOAD_LENGTH_16:
this.getPayloadLength16();
break;
case GET_PAYLOAD_LENGTH_64:
this.getPayloadLength64();
break;
case GET_MASK:
this.getMask();
break;
case GET_DATA:
this.getData();
break;
default: // `INFLATING`
this.loop = false;
}
}
}
/**
* Reads the first two bytes of a frame.
*
* @private
*/
getInfo () {
if (!this.hasBufferedBytes(2)) return;
const buf = this.readBuffer(2);
if ((buf[0] & 0x30) !== 0x00) {
this.error(new Error('RSV2 and RSV3 must be clear'), 1002);
return;
}
const compressed = (buf[0] & 0x40) === 0x40;
if (compressed && !this.extensions[PerMessageDeflate.extensionName]) {
this.error(new Error('RSV1 must be clear'), 1002);
return;
}
this.fin = (buf[0] & 0x80) === 0x80;
this.opcode = buf[0] & 0x0f;
this.payloadLength = buf[1] & 0x7f;
if (this.opcode === 0x00) {
if (compressed) {
this.error(new Error('RSV1 must be clear'), 1002);
return;
}
if (!this.fragmented) {
this.error(new Error(`invalid opcode: ${this.opcode}`), 1002);
return;
} else {
this.opcode = this.fragmented;
}
} else if (this.opcode === 0x01 || this.opcode === 0x02) {
if (this.fragmented) {
this.error(new Error(`invalid opcode: ${this.opcode}`), 1002);
return;
}
this.compressed = compressed;
} else if (this.opcode > 0x07 && this.opcode < 0x0b) {
if (!this.fin) {
this.error(new Error('FIN must be set'), 1002);
return;
}
if (compressed) {
this.error(new Error('RSV1 must be clear'), 1002);
return;
}
if (this.payloadLength > 0x7d) {
this.error(new Error('invalid payload length'), 1002);
return;
}
} else {
this.error(new Error(`invalid opcode: ${this.opcode}`), 1002);
return;
}
if (!this.fin && !this.fragmented) this.fragmented = this.opcode;
this.masked = (buf[1] & 0x80) === 0x80;
if (this.payloadLength === 126) this.state = GET_PAYLOAD_LENGTH_16;
else if (this.payloadLength === 127) this.state = GET_PAYLOAD_LENGTH_64;
else this.haveLength();
}
/**
* Gets extended payload length (7+16).
*
* @private
*/
getPayloadLength16 () {
if (!this.hasBufferedBytes(2)) return;
this.payloadLength = this.readBuffer(2).readUInt16BE(0, true);
this.haveLength();
}
/**
* Gets extended payload length (7+64).
*
* @private
*/
getPayloadLength64 () {
if (!this.hasBufferedBytes(8)) return;
const buf = this.readBuffer(8);
const num = buf.readUInt32BE(0, true);
//
// The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
// if payload length is greater than this number.
//
if (num > Math.pow(2, 53 - 32) - 1) {
this.error(new Error('max payload size exceeded'), 1009);
return;
}
this.payloadLength = (num * Math.pow(2, 32)) + buf.readUInt32BE(4, true);
this.haveLength();
}
/**
* Payload length has been read.
*
* @private
*/
haveLength () {
if (this.opcode < 0x08 && this.maxPayloadExceeded(this.payloadLength)) {
return;
}
if (this.masked) this.state = GET_MASK;
else this.state = GET_DATA;
}
/**
* Reads mask bytes.
*
* @private
*/
getMask () {
if (!this.hasBufferedBytes(4)) return;
this.mask = this.readBuffer(4);
this.state = GET_DATA;
}
/**
* Reads data bytes.
*
* @private
*/
getData () {
var data = constants.EMPTY_BUFFER;
if (this.payloadLength) {
if (!this.hasBufferedBytes(this.payloadLength)) return;
data = this.readBuffer(this.payloadLength);
if (this.masked) bufferUtil.unmask(data, this.mask);
}
if (this.opcode > 0x07) {
this.controlMessage(data);
} else if (this.compressed) {
this.state = INFLATING;
this.decompress(data);
} else if (this.pushFragment(data)) {
this.dataMessage();
}
}
/**
* Decompresses data.
*
* @param {Buffer} data Compressed data
* @private
*/
decompress (data) {
const extension = this.extensions[PerMessageDeflate.extensionName];
extension.decompress(data, this.fin, (err, buf) => {
if (err) {
this.error(err, err.closeCode === 1009 ? 1009 : 1007);
return;
}
if (this.pushFragment(buf)) this.dataMessage();
this.startLoop();
});
}
/**
* Handles a data message.
*
* @private
*/
dataMessage () {
if (this.fin) {
const messageLength = this.messageLength;
const fragments = this.fragments;
this.totalPayloadLength = 0;
this.messageLength = 0;
this.fragmented = 0;
this.fragments = [];
if (this.opcode === 2) {
var data;
if (this.binaryType === 'nodebuffer') {
data = toBuffer(fragments, messageLength);
} else if (this.binaryType === 'arraybuffer') {
data = toArrayBuffer(toBuffer(fragments, messageLength));
} else {
data = fragments;
}
this.onmessage(data, { masked: this.masked, binary: true });
} else {
const buf = toBuffer(fragments, messageLength);
if (!isValidUTF8(buf)) {
this.error(new Error('invalid utf8 sequence'), 1007);
return;
}
this.onmessage(buf.toString(), { masked: this.masked });
}
}
this.state = GET_INFO;
}
/**
* Handles a control message.
*
* @param {Buffer} data Data to handle
* @private
*/
controlMessage (data) {
if (this.opcode === 0x08) {
if (data.length === 0) {
this.onclose(1000, '', { masked: this.masked });
this.loop = false;
this.cleanup(this.cleanupCallback);
} else if (data.length === 1) {
this.error(new Error('invalid payload length'), 1002);
} else {
const code = data.readUInt16BE(0, true);
if (!ErrorCodes.isValidErrorCode(code)) {
this.error(new Error(`invalid status code: ${code}`), 1002);
return;
}
const buf = data.slice(2);
if (!isValidUTF8(buf)) {
this.error(new Error('invalid utf8 sequence'), 1007);
return;
}
this.onclose(code, buf.toString(), { masked: this.masked });
this.loop = false;
this.cleanup(this.cleanupCallback);
}
return;
}
const flags = { masked: this.masked, binary: true };
if (this.opcode === 0x09) this.onping(data, flags);
else this.onpong(data, flags);
this.state = GET_INFO;
}
/**
* Handles an error.
*
* @param {Error} err The error
* @param {Number} code Close code
* @private
*/
error (err, code) {
this.onerror(err, code);
this.hadError = true;
this.loop = false;
this.cleanup(this.cleanupCallback);
}
/**
* Checks payload size, disconnects socket when it exceeds `maxPayload`.
*
* @param {Number} length Payload length
* @private
*/
maxPayloadExceeded (length) {
if (length === 0 || this.maxPayload < 1) return false;
const fullLength = this.totalPayloadLength + length;
if (fullLength <= this.maxPayload) {
this.totalPayloadLength = fullLength;
return false;
}
this.error(new Error('max payload size exceeded'), 1009);
return true;
}
/**
* Appends a fragment in the fragments array after checking that the sum of
* fragment lengths does not exceed `maxPayload`.
*
* @param {Buffer} fragment The fragment to add
* @return {Boolean} `true` if `maxPayload` is not exceeded, else `false`
* @private
*/
pushFragment (fragment) {
if (fragment.length === 0) return true;
const totalLength = this.messageLength + fragment.length;
if (this.maxPayload < 1 || totalLength <= this.maxPayload) {
this.messageLength = totalLength;
this.fragments.push(fragment);
return true;
}
this.error(new Error('max payload size exceeded'), 1009);
return false;
}
/**
* Releases resources used by the receiver.
*
* @param {Function} cb Callback
* @public
*/
cleanup (cb) {
this.dead = true;
if (!this.hadError && (this.loop || this.state === INFLATING)) {
this.cleanupCallback = cb;
} else {
this.extensions = null;
this.fragments = null;
this.buffers = null;
this.mask = null;
this.cleanupCallback = null;
this.onmessage = null;
this.onclose = null;
this.onerror = null;
this.onping = null;
this.onpong = null;
if (cb) cb();
}
}
}
module.exports = Receiver;
/**
* Makes a buffer from a list of fragments.
*
* @param {Buffer[]} fragments The list of fragments composing the message
* @param {Number} messageLength The length of the message
* @return {Buffer}
* @private
*/
function toBuffer (fragments, messageLength) {
if (fragments.length === 1) return fragments[0];
if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength);
return constants.EMPTY_BUFFER;
}
/**
* Converts a buffer to an `ArrayBuffer`.
*
* @param {Buffer} The buffer to convert
* @return {ArrayBuffer} Converted buffer
*/
function toArrayBuffer (buf) {
if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
return buf.buffer;
}
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
}

404
Server/node_modules/ws/lib/Sender.js generated vendored Normal file
View File

@ -0,0 +1,404 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
'use strict';
const safeBuffer = require('safe-buffer');
const crypto = require('crypto');
const PerMessageDeflate = require('./PerMessageDeflate');
const bufferUtil = require('./BufferUtil');
const ErrorCodes = require('./ErrorCodes');
const Buffer = safeBuffer.Buffer;
/**
* HyBi Sender implementation.
*/
class Sender {
/**
* Creates a Sender instance.
*
* @param {net.Socket} socket The connection socket
* @param {Object} extensions An object containing the negotiated extensions
*/
constructor (socket, extensions) {
this.perMessageDeflate = (extensions || {})[PerMessageDeflate.extensionName];
this._socket = socket;
this.firstFragment = true;
this.compress = false;
this.bufferedBytes = 0;
this.deflating = false;
this.queue = [];
this.onerror = null;
}
/**
* Frames a piece of data according to the HyBi WebSocket protocol.
*
* @param {Buffer} data The data to frame
* @param {Object} options Options object
* @param {Number} options.opcode The opcode
* @param {Boolean} options.readOnly Specifies whether `data` can be modified
* @param {Boolean} options.fin Specifies whether or not to set the FIN bit
* @param {Boolean} options.mask Specifies whether or not to mask `data`
* @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
* @return {Buffer[]} The framed data as a list of `Buffer` instances
* @public
*/
static frame (data, options) {
const merge = data.length < 1024 || (options.mask && options.readOnly);
var offset = options.mask ? 6 : 2;
var payloadLength = data.length;
if (data.length >= 65536) {
offset += 8;
payloadLength = 127;
} else if (data.length > 125) {
offset += 2;
payloadLength = 126;
}
const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);
target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
if (options.rsv1) target[0] |= 0x40;
if (payloadLength === 126) {
target.writeUInt16BE(data.length, 2, true);
} else if (payloadLength === 127) {
target.writeUInt32BE(0, 2, true);
target.writeUInt32BE(data.length, 6, true);
}
if (!options.mask) {
target[1] = payloadLength;
if (merge) {
data.copy(target, offset);
return [target];
}
return [target, data];
}
const mask = crypto.randomBytes(4);
target[1] = payloadLength | 0x80;
target[offset - 4] = mask[0];
target[offset - 3] = mask[1];
target[offset - 2] = mask[2];
target[offset - 1] = mask[3];
if (merge) {
bufferUtil.mask(data, mask, target, offset, data.length);
return [target];
}
bufferUtil.mask(data, mask, data, 0, data.length);
return [target, data];
}
/**
* Sends a close message to the other peer.
*
* @param {(Number|undefined)} code The status code component of the body
* @param {String} data The message component of the body
* @param {Boolean} mask Specifies whether or not to mask the message
* @param {Function} cb Callback
* @public
*/
close (code, data, mask, cb) {
if (code !== undefined && (typeof code !== 'number' || !ErrorCodes.isValidErrorCode(code))) {
throw new Error('first argument must be a valid error code number');
}
const buf = Buffer.allocUnsafe(2 + (data ? Buffer.byteLength(data) : 0));
buf.writeUInt16BE(code || 1000, 0, true);
if (buf.length > 2) buf.write(data, 2);
if (this.deflating) {
this.enqueue([this.doClose, buf, mask, cb]);
} else {
this.doClose(buf, mask, cb);
}
}
/**
* Frames and sends a close message.
*
* @param {Buffer} data The message to send
* @param {Boolean} mask Specifies whether or not to mask `data`
* @param {Function} cb Callback
* @private
*/
doClose (data, mask, cb) {
this.sendFrame(Sender.frame(data, {
readOnly: false,
opcode: 0x08,
rsv1: false,
fin: true,
mask
}), cb);
}
/**
* Sends a ping message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} mask Specifies whether or not to mask `data`
* @public
*/
ping (data, mask) {
var readOnly = true;
if (!Buffer.isBuffer(data)) {
if (data instanceof ArrayBuffer) {
data = Buffer.from(data);
} else if (ArrayBuffer.isView(data)) {
data = viewToBuffer(data);
} else {
data = Buffer.from(data);
readOnly = false;
}
}
if (this.deflating) {
this.enqueue([this.doPing, data, mask, readOnly]);
} else {
this.doPing(data, mask, readOnly);
}
}
/**
* Frames and sends a ping message.
*
* @param {*} data The message to send
* @param {Boolean} mask Specifies whether or not to mask `data`
* @param {Boolean} readOnly Specifies whether `data` can be modified
* @private
*/
doPing (data, mask, readOnly) {
this.sendFrame(Sender.frame(data, {
opcode: 0x09,
rsv1: false,
fin: true,
readOnly,
mask
}));
}
/**
* Sends a pong message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} mask Specifies whether or not to mask `data`
* @public
*/
pong (data, mask) {
var readOnly = true;
if (!Buffer.isBuffer(data)) {
if (data instanceof ArrayBuffer) {
data = Buffer.from(data);
} else if (ArrayBuffer.isView(data)) {
data = viewToBuffer(data);
} else {
data = Buffer.from(data);
readOnly = false;
}
}
if (this.deflating) {
this.enqueue([this.doPong, data, mask, readOnly]);
} else {
this.doPong(data, mask, readOnly);
}
}
/**
* Frames and sends a pong message.
*
* @param {*} data The message to send
* @param {Boolean} mask Specifies whether or not to mask `data`
* @param {Boolean} readOnly Specifies whether `data` can be modified
* @private
*/
doPong (data, mask, readOnly) {
this.sendFrame(Sender.frame(data, {
opcode: 0x0a,
rsv1: false,
fin: true,
readOnly,
mask
}));
}
/**
* Sends a data message to the other peer.
*
* @param {*} data The message to send
* @param {Object} options Options object
* @param {Boolean} options.compress Specifies whether or not to compress `data`
* @param {Boolean} options.binary Specifies whether `data` is binary or text
* @param {Boolean} options.fin Specifies whether the fragment is the last one
* @param {Boolean} options.mask Specifies whether or not to mask `data`
* @param {Function} cb Callback
* @public
*/
send (data, options, cb) {
var opcode = options.binary ? 2 : 1;
var rsv1 = options.compress;
var readOnly = true;
if (!Buffer.isBuffer(data)) {
if (data instanceof ArrayBuffer) {
data = Buffer.from(data);
} else if (ArrayBuffer.isView(data)) {
data = viewToBuffer(data);
} else {
data = Buffer.from(data);
readOnly = false;
}
}
if (this.firstFragment) {
this.firstFragment = false;
if (rsv1 && this.perMessageDeflate) {
rsv1 = data.length >= this.perMessageDeflate.threshold;
}
this.compress = rsv1;
} else {
rsv1 = false;
opcode = 0;
}
if (options.fin) this.firstFragment = true;
if (this.perMessageDeflate) {
const opts = {
compress: this.compress,
mask: options.mask,
fin: options.fin,
readOnly,
opcode,
rsv1
};
if (this.deflating) {
this.enqueue([this.dispatch, data, opts, cb]);
} else {
this.dispatch(data, opts, cb);
}
} else {
this.sendFrame(Sender.frame(data, {
mask: options.mask,
fin: options.fin,
rsv1: false,
readOnly,
opcode
}), cb);
}
}
/**
* Dispatches a data message.
*
* @param {Buffer} data The message to send
* @param {Object} options Options object
* @param {Number} options.opcode The opcode
* @param {Boolean} options.readOnly Specifies whether `data` can be modified
* @param {Boolean} options.fin Specifies whether or not to set the FIN bit
* @param {Boolean} options.compress Specifies whether or not to compress `data`
* @param {Boolean} options.mask Specifies whether or not to mask `data`
* @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
* @param {Function} cb Callback
* @private
*/
dispatch (data, options, cb) {
if (!options.compress) {
this.sendFrame(Sender.frame(data, options), cb);
return;
}
this.deflating = true;
this.perMessageDeflate.compress(data, options.fin, (err, buf) => {
if (err) {
if (cb) cb(err);
else this.onerror(err);
return;
}
options.readOnly = false;
this.sendFrame(Sender.frame(buf, options), cb);
this.deflating = false;
this.dequeue();
});
}
/**
* Executes queued send operations.
*
* @private
*/
dequeue () {
while (!this.deflating && this.queue.length) {
const params = this.queue.shift();
this.bufferedBytes -= params[1].length;
params[0].apply(this, params.slice(1));
}
}
/**
* Enqueues a send operation.
*
* @param {Array} params Send operation parameters.
* @private
*/
enqueue (params) {
this.bufferedBytes += params[1].length;
this.queue.push(params);
}
/**
* Sends a frame.
*
* @param {Buffer[]} list The frame to send
* @param {Function} cb Callback
* @private
*/
sendFrame (list, cb) {
if (list.length === 2) {
this._socket.write(list[0]);
this._socket.write(list[1], cb);
} else {
this._socket.write(list[0], cb);
}
}
}
module.exports = Sender;
/**
* Converts an `ArrayBuffer` view into a buffer.
*
* @param {(DataView|TypedArray)} view The view to convert
* @return {Buffer} Converted view
* @private
*/
function viewToBuffer (view) {
const buf = Buffer.from(view.buffer);
if (view.byteLength !== view.buffer.byteLength) {
return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);
}
return buf;
}

17
Server/node_modules/ws/lib/Validation.js generated vendored Normal file
View File

@ -0,0 +1,17 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
'use strict';
try {
const isValidUTF8 = require('utf-8-validate');
module.exports = typeof isValidUTF8 === 'object'
? isValidUTF8.Validation.isValidUTF8 // utf-8-validate@<3.0.0
: isValidUTF8;
} catch (e) /* istanbul ignore next */ {
module.exports = () => true;
}

704
Server/node_modules/ws/lib/WebSocket.js generated vendored Normal file
View File

@ -0,0 +1,704 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
'use strict';
const EventEmitter = require('events');
const crypto = require('crypto');
const Ultron = require('ultron');
const https = require('https');
const http = require('http');
const url = require('url');
const PerMessageDeflate = require('./PerMessageDeflate');
const EventTarget = require('./EventTarget');
const Extensions = require('./Extensions');
const constants = require('./Constants');
const Receiver = require('./Receiver');
const Sender = require('./Sender');
const protocolVersions = [8, 13];
const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly.
/**
* Class representing a WebSocket.
*
* @extends EventEmitter
*/
class WebSocket extends EventEmitter {
/**
* Create a new `WebSocket`.
*
* @param {String} address The URL to which to connect
* @param {(String|String[])} protocols The subprotocols
* @param {Object} options Connection options
*/
constructor (address, protocols, options) {
super();
if (!protocols) {
protocols = [];
} else if (typeof protocols === 'string') {
protocols = [protocols];
} else if (!Array.isArray(protocols)) {
options = protocols;
protocols = [];
}
this.readyState = WebSocket.CONNECTING;
this.bytesReceived = 0;
this.extensions = {};
this.protocol = '';
this._binaryType = constants.BINARY_TYPES[0];
this._finalize = this.finalize.bind(this);
this._finalizeCalled = false;
this._closeMessage = null;
this._closeTimer = null;
this._closeCode = null;
this._receiver = null;
this._sender = null;
this._socket = null;
this._ultron = null;
if (Array.isArray(address)) {
initAsServerClient.call(this, address[0], address[1], address[2], options);
} else {
initAsClient.call(this, address, protocols, options);
}
}
get CONNECTING () { return WebSocket.CONNECTING; }
get CLOSING () { return WebSocket.CLOSING; }
get CLOSED () { return WebSocket.CLOSED; }
get OPEN () { return WebSocket.OPEN; }
/**
* @type {Number}
*/
get bufferedAmount () {
var amount = 0;
if (this._socket) {
amount = this._socket.bufferSize + this._sender.bufferedBytes;
}
return amount;
}
/**
* This deviates from the WHATWG interface since ws doesn't support the required
* default "blob" type (instead we define a custom "nodebuffer" type).
*
* @type {String}
*/
get binaryType () {
return this._binaryType;
}
set binaryType (type) {
if (constants.BINARY_TYPES.indexOf(type) < 0) return;
this._binaryType = type;
//
// Allow to change `binaryType` on the fly.
//
if (this._receiver) this._receiver.binaryType = type;
}
/**
* Set up the socket and the internal resources.
*
* @param {net.Socket} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @private
*/
setSocket (socket, head) {
socket.setTimeout(0);
socket.setNoDelay();
this._receiver = new Receiver(this.extensions, this.maxPayload, this.binaryType);
this._sender = new Sender(socket, this.extensions);
this._ultron = new Ultron(socket);
this._socket = socket;
// socket cleanup handlers
this._ultron.on('close', this._finalize);
this._ultron.on('error', this._finalize);
this._ultron.on('end', this._finalize);
// ensure that the head is added to the receiver
if (head && head.length > 0) {
socket.unshift(head);
head = null;
}
// subsequent packets are pushed to the receiver
this._ultron.on('data', (data) => {
this.bytesReceived += data.length;
this._receiver.add(data);
});
// receiver event handlers
this._receiver.onmessage = (data, flags) => this.emit('message', data, flags);
this._receiver.onping = (data, flags) => {
this.pong(data, !this._isServer, true);
this.emit('ping', data, flags);
};
this._receiver.onpong = (data, flags) => this.emit('pong', data, flags);
this._receiver.onclose = (code, reason) => {
this._closeMessage = reason;
this._closeCode = code;
this.close(code, reason);
};
this._receiver.onerror = (error, code) => {
// close the connection when the receiver reports a HyBi error code
this.close(code, '');
this.emit('error', error);
};
// sender event handlers
this._sender.onerror = (error) => {
this.close(1002, '');
this.emit('error', error);
};
this.readyState = WebSocket.OPEN;
this.emit('open');
}
/**
* Clean up and release internal resources.
*
* @param {(Boolean|Error)} Indicates whether or not an error occurred
* @private
*/
finalize (error) {
if (this._finalizeCalled) return;
this.readyState = WebSocket.CLOSING;
this._finalizeCalled = true;
clearTimeout(this._closeTimer);
this._closeTimer = null;
//
// If the connection was closed abnormally (with an error), or if the close
// control frame was malformed or not received then the close code must be
// 1006.
//
if (error) this._closeCode = 1006;
if (this._socket) {
this._ultron.destroy();
this._socket.on('error', function onerror () {
this.destroy();
});
if (!error) this._socket.end();
else this._socket.destroy();
this._socket = null;
this._ultron = null;
}
if (this._sender) {
this._sender = this._sender.onerror = null;
}
if (this._receiver) {
this._receiver.cleanup(() => this.emitClose());
this._receiver = null;
} else {
this.emitClose();
}
}
/**
* Emit the `close` event.
*
* @private
*/
emitClose () {
this.readyState = WebSocket.CLOSED;
this.emit('close', this._closeCode || 1006, this._closeMessage || '');
if (this.extensions[PerMessageDeflate.extensionName]) {
this.extensions[PerMessageDeflate.extensionName].cleanup();
}
this.extensions = null;
this.removeAllListeners();
this.on('error', constants.NOOP); // Catch all errors after this.
}
/**
* Pause the socket stream.
*
* @public
*/
pause () {
if (this.readyState !== WebSocket.OPEN) throw new Error('not opened');
this._socket.pause();
}
/**
* Resume the socket stream
*
* @public
*/
resume () {
if (this.readyState !== WebSocket.OPEN) throw new Error('not opened');
this._socket.resume();
}
/**
* Start a closing handshake.
*
* @param {Number} code Status code explaining why the connection is closing
* @param {String} data A string explaining why the connection is closing
* @public
*/
close (code, data) {
if (this.readyState === WebSocket.CLOSED) return;
if (this.readyState === WebSocket.CONNECTING) {
if (this._req && !this._req.aborted) {
this._req.abort();
this.emit('error', new Error('closed before the connection is established'));
this.finalize(true);
}
return;
}
if (this.readyState === WebSocket.CLOSING) {
if (this._closeCode && this._socket) this._socket.end();
return;
}
this.readyState = WebSocket.CLOSING;
this._sender.close(code, data, !this._isServer, (err) => {
if (err) this.emit('error', err);
if (this._socket) {
if (this._closeCode) this._socket.end();
//
// Ensure that the connection is cleaned up even when the closing
// handshake fails.
//
clearTimeout(this._closeTimer);
this._closeTimer = setTimeout(this._finalize, closeTimeout, true);
}
});
}
/**
* Send a ping message.
*
* @param {*} data The message to send
* @param {Boolean} mask Indicates whether or not to mask `data`
* @param {Boolean} failSilently Indicates whether or not to throw if `readyState` isn't `OPEN`
* @public
*/
ping (data, mask, failSilently) {
if (this.readyState !== WebSocket.OPEN) {
if (failSilently) return;
throw new Error('not opened');
}
if (typeof data === 'number') data = data.toString();
if (mask === undefined) mask = !this._isServer;
this._sender.ping(data || constants.EMPTY_BUFFER, mask);
}
/**
* Send a pong message.
*
* @param {*} data The message to send
* @param {Boolean} mask Indicates whether or not to mask `data`
* @param {Boolean} failSilently Indicates whether or not to throw if `readyState` isn't `OPEN`
* @public
*/
pong (data, mask, failSilently) {
if (this.readyState !== WebSocket.OPEN) {
if (failSilently) return;
throw new Error('not opened');
}
if (typeof data === 'number') data = data.toString();
if (mask === undefined) mask = !this._isServer;
this._sender.pong(data || constants.EMPTY_BUFFER, mask);
}
/**
* Send a data message.
*
* @param {*} data The message to send
* @param {Object} options Options object
* @param {Boolean} options.compress Specifies whether or not to compress `data`
* @param {Boolean} options.binary Specifies whether `data` is binary or text
* @param {Boolean} options.fin Specifies whether the fragment is the last one
* @param {Boolean} options.mask Specifies whether or not to mask `data`
* @param {Function} cb Callback which is executed when data is written out
* @public
*/
send (data, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
if (this.readyState !== WebSocket.OPEN) {
if (cb) cb(new Error('not opened'));
else throw new Error('not opened');
return;
}
if (typeof data === 'number') data = data.toString();
const opts = Object.assign({
binary: typeof data !== 'string',
mask: !this._isServer,
compress: true,
fin: true
}, options);
if (!this.extensions[PerMessageDeflate.extensionName]) {
opts.compress = false;
}
this._sender.send(data || constants.EMPTY_BUFFER, opts, cb);
}
/**
* Forcibly close the connection.
*
* @public
*/
terminate () {
if (this.readyState === WebSocket.CLOSED) return;
if (this.readyState === WebSocket.CONNECTING) {
if (this._req && !this._req.aborted) {
this._req.abort();
this.emit('error', new Error('closed before the connection is established'));
this.finalize(true);
}
return;
}
this.finalize(true);
}
}
WebSocket.CONNECTING = 0;
WebSocket.OPEN = 1;
WebSocket.CLOSING = 2;
WebSocket.CLOSED = 3;
//
// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
//
['open', 'error', 'close', 'message'].forEach((method) => {
Object.defineProperty(WebSocket.prototype, `on${method}`, {
/**
* Return the listener of the event.
*
* @return {(Function|undefined)} The event listener or `undefined`
* @public
*/
get () {
const listeners = this.listeners(method);
for (var i = 0; i < listeners.length; i++) {
if (listeners[i]._listener) return listeners[i]._listener;
}
},
/**
* Add a listener for the event.
*
* @param {Function} listener The listener to add
* @public
*/
set (listener) {
const listeners = this.listeners(method);
for (var i = 0; i < listeners.length; i++) {
//
// Remove only the listeners added via `addEventListener`.
//
if (listeners[i]._listener) this.removeListener(method, listeners[i]);
}
this.addEventListener(method, listener);
}
});
});
WebSocket.prototype.addEventListener = EventTarget.addEventListener;
WebSocket.prototype.removeEventListener = EventTarget.removeEventListener;
module.exports = WebSocket;
/**
* Initialize a WebSocket server client.
*
* @param {http.IncomingMessage} req The request object
* @param {net.Socket} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Object} options WebSocket attributes
* @param {Number} options.protocolVersion The WebSocket protocol version
* @param {Object} options.extensions The negotiated extensions
* @param {Number} options.maxPayload The maximum allowed message size
* @param {String} options.protocol The chosen subprotocol
* @private
*/
function initAsServerClient (req, socket, head, options) {
this.protocolVersion = options.protocolVersion;
this.extensions = options.extensions;
this.maxPayload = options.maxPayload;
this.protocol = options.protocol;
this.upgradeReq = req;
this._isServer = true;
this.setSocket(socket, head);
}
/**
* Initialize a WebSocket client.
*
* @param {String} address The URL to which to connect
* @param {String[]} protocols The list of subprotocols
* @param {Object} options Connection options
* @param {String} options.protocol Value of the `Sec-WebSocket-Protocol` header
* @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate
* @param {String} options.localAddress Local interface to bind for network connections
* @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header
* @param {Object} options.headers An object containing request headers
* @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header
* @param {http.Agent} options.agent Use the specified Agent
* @param {String} options.host Value of the `Host` header
* @param {Number} options.family IP address family to use during hostname lookup (4 or 6).
* @param {Function} options.checkServerIdentity A function to validate the server hostname
* @param {Boolean} options.rejectUnauthorized Verify or not the server certificate
* @param {String} options.passphrase The passphrase for the private key or pfx
* @param {String} options.ciphers The ciphers to use or exclude
* @param {(String|String[]|Buffer|Buffer[])} options.cert The certificate key
* @param {(String|String[]|Buffer|Buffer[])} options.key The private key
* @param {(String|Buffer)} options.pfx The private key, certificate, and CA certs
* @param {(String|String[]|Buffer|Buffer[])} options.ca Trusted certificates
* @private
*/
function initAsClient (address, protocols, options) {
options = Object.assign({
protocolVersion: protocolVersions[1],
protocol: protocols.join(','),
perMessageDeflate: true,
localAddress: null,
headers: null,
family: null,
origin: null,
agent: null,
host: null,
//
// SSL options.
//
checkServerIdentity: null,
rejectUnauthorized: null,
passphrase: null,
ciphers: null,
cert: null,
key: null,
pfx: null,
ca: null
}, options);
if (protocolVersions.indexOf(options.protocolVersion) === -1) {
throw new Error(
`unsupported protocol version: ${options.protocolVersion} ` +
`(supported versions: ${protocolVersions.join(', ')})`
);
}
this.protocolVersion = options.protocolVersion;
this._isServer = false;
this.url = address;
const serverUrl = url.parse(address);
const isUnixSocket = serverUrl.protocol === 'ws+unix:';
if (!serverUrl.host && (!isUnixSocket || !serverUrl.path)) {
throw new Error('invalid url');
}
const isSecure = serverUrl.protocol === 'wss:' || serverUrl.protocol === 'https:';
const key = crypto.randomBytes(16).toString('base64');
const httpObj = isSecure ? https : http;
//
// Prepare extensions.
//
const extensionsOffer = {};
var perMessageDeflate;
if (options.perMessageDeflate) {
perMessageDeflate = new PerMessageDeflate(
options.perMessageDeflate !== true ? options.perMessageDeflate : {},
false
);
extensionsOffer[PerMessageDeflate.extensionName] = perMessageDeflate.offer();
}
const requestOptions = {
port: serverUrl.port || (isSecure ? 443 : 80),
host: serverUrl.hostname,
path: '/',
headers: {
'Sec-WebSocket-Version': options.protocolVersion,
'Sec-WebSocket-Key': key,
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
};
if (options.headers) Object.assign(requestOptions.headers, options.headers);
if (Object.keys(extensionsOffer).length) {
requestOptions.headers['Sec-WebSocket-Extensions'] = Extensions.format(extensionsOffer);
}
if (options.protocol) {
requestOptions.headers['Sec-WebSocket-Protocol'] = options.protocol;
}
if (options.origin) {
if (options.protocolVersion < 13) {
requestOptions.headers['Sec-WebSocket-Origin'] = options.origin;
} else {
requestOptions.headers.Origin = options.origin;
}
}
if (options.host) requestOptions.headers.Host = options.host;
if (serverUrl.auth) requestOptions.auth = serverUrl.auth;
if (options.localAddress) requestOptions.localAddress = options.localAddress;
if (options.family) requestOptions.family = options.family;
if (isUnixSocket) {
const parts = serverUrl.path.split(':');
requestOptions.socketPath = parts[0];
requestOptions.path = parts[1];
} else if (serverUrl.path) {
//
// Make sure that path starts with `/`.
//
if (serverUrl.path.charAt(0) !== '/') {
requestOptions.path = `/${serverUrl.path}`;
} else {
requestOptions.path = serverUrl.path;
}
}
var agent = options.agent;
//
// A custom agent is required for these options.
//
if (
options.rejectUnauthorized != null ||
options.checkServerIdentity ||
options.passphrase ||
options.ciphers ||
options.cert ||
options.key ||
options.pfx ||
options.ca
) {
if (options.passphrase) requestOptions.passphrase = options.passphrase;
if (options.ciphers) requestOptions.ciphers = options.ciphers;
if (options.cert) requestOptions.cert = options.cert;
if (options.key) requestOptions.key = options.key;
if (options.pfx) requestOptions.pfx = options.pfx;
if (options.ca) requestOptions.ca = options.ca;
if (options.checkServerIdentity) {
requestOptions.checkServerIdentity = options.checkServerIdentity;
}
if (options.rejectUnauthorized != null) {
requestOptions.rejectUnauthorized = options.rejectUnauthorized;
}
if (!agent) agent = new httpObj.Agent(requestOptions);
}
if (agent) requestOptions.agent = agent;
this._req = httpObj.get(requestOptions);
this._req.on('error', (error) => {
if (this._req.aborted) return;
this._req = null;
this.emit('error', error);
this.finalize(true);
});
this._req.on('response', (res) => {
if (!this.emit('unexpected-response', this._req, res)) {
this._req.abort();
this.emit('error', new Error(`unexpected server response (${res.statusCode})`));
this.finalize(true);
}
});
this._req.on('upgrade', (res, socket, head) => {
this._req = null;
const digest = crypto.createHash('sha1')
.update(key + constants.GUID, 'binary')
.digest('base64');
if (res.headers['sec-websocket-accept'] !== digest) {
socket.destroy();
this.emit('error', new Error('invalid server key'));
return this.finalize(true);
}
const serverProt = res.headers['sec-websocket-protocol'];
const protList = (options.protocol || '').split(/, */);
var protError;
if (!options.protocol && serverProt) {
protError = 'server sent a subprotocol even though none requested';
} else if (options.protocol && !serverProt) {
protError = 'server sent no subprotocol even though requested';
} else if (serverProt && protList.indexOf(serverProt) === -1) {
protError = 'server responded with an invalid protocol';
}
if (protError) {
socket.destroy();
this.emit('error', new Error(protError));
return this.finalize(true);
}
if (serverProt) this.protocol = serverProt;
const serverExtensions = Extensions.parse(res.headers['sec-websocket-extensions']);
if (perMessageDeflate && serverExtensions[PerMessageDeflate.extensionName]) {
try {
perMessageDeflate.accept(serverExtensions[PerMessageDeflate.extensionName]);
} catch (err) {
socket.destroy();
this.emit('error', new Error('invalid extension parameter'));
return this.finalize(true);
}
this.extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
this.setSocket(socket, head);
});
}

336
Server/node_modules/ws/lib/WebSocketServer.js generated vendored Normal file
View File

@ -0,0 +1,336 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
'use strict';
const safeBuffer = require('safe-buffer');
const EventEmitter = require('events');
const crypto = require('crypto');
const Ultron = require('ultron');
const http = require('http');
const url = require('url');
const PerMessageDeflate = require('./PerMessageDeflate');
const Extensions = require('./Extensions');
const constants = require('./Constants');
const WebSocket = require('./WebSocket');
const Buffer = safeBuffer.Buffer;
/**
* Class representing a WebSocket server.
*
* @extends EventEmitter
*/
class WebSocketServer extends EventEmitter {
/**
* Create a `WebSocketServer` instance.
*
* @param {Object} options Configuration options
* @param {String} options.host The hostname where to bind the server
* @param {Number} options.port The port where to bind the server
* @param {http.Server} options.server A pre-created HTTP/S server to use
* @param {Function} options.verifyClient An hook to reject connections
* @param {Function} options.handleProtocols An hook to handle protocols
* @param {String} options.path Accept only connections matching this path
* @param {Boolean} options.noServer Enable no server mode
* @param {Boolean} options.clientTracking Specifies whether or not to track clients
* @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate
* @param {Number} options.maxPayload The maximum allowed message size
* @param {Function} callback A listener for the `listening` event
*/
constructor (options, callback) {
super();
options = Object.assign({
maxPayload: 100 * 1024 * 1024,
perMessageDeflate: true,
handleProtocols: null,
clientTracking: true,
verifyClient: null,
noServer: false,
backlog: null, // use default (511 as implemented in net.js)
server: null,
host: null,
path: null,
port: null
}, options);
if (options.port == null && !options.server && !options.noServer) {
throw new TypeError('missing or invalid options');
}
if (options.port != null) {
this._server = http.createServer((req, res) => {
const body = http.STATUS_CODES[426];
res.writeHead(426, {
'Content-Length': body.length,
'Content-Type': 'text/plain'
});
res.end(body);
});
this._server.allowHalfOpen = false;
this._server.listen(options.port, options.host, options.backlog, callback);
} else if (options.server) {
this._server = options.server;
}
if (this._server) {
this._ultron = new Ultron(this._server);
this._ultron.on('listening', () => this.emit('listening'));
this._ultron.on('error', (err) => this.emit('error', err));
this._ultron.on('upgrade', (req, socket, head) => {
this.handleUpgrade(req, socket, head, (client) => {
this.emit(`connection${req.url}`, client);
this.emit('connection', client);
});
});
}
if (options.clientTracking) this.clients = new Set();
this.options = options;
this.path = options.path;
}
/**
* Close the server.
*
* @param {Function} cb Callback
* @public
*/
close (cb) {
//
// Terminate all associated clients.
//
if (this.clients) {
for (const client of this.clients) client.terminate();
}
const server = this._server;
if (server) {
this._ultron.destroy();
this._ultron = this._server = null;
//
// Close the http server if it was internally created.
//
if (this.options.port != null) return server.close(cb);
}
if (cb) cb();
}
/**
* See if a given request should be handled by this server instance.
*
* @param {http.IncomingMessage} req Request object to inspect
* @return {Boolean} `true` if the request is valid, else `false`
* @public
*/
shouldHandle (req) {
if (this.options.path && url.parse(req.url).pathname !== this.options.path) {
return false;
}
return true;
}
/**
* Handle a HTTP Upgrade request.
*
* @param {http.IncomingMessage} req The request object
* @param {net.Socket} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @public
*/
handleUpgrade (req, socket, head, cb) {
socket.on('error', socketError);
const version = +req.headers['sec-websocket-version'];
if (
req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' ||
!req.headers['sec-websocket-key'] || (version !== 8 && version !== 13) ||
!this.shouldHandle(req)
) {
return abortConnection(socket, 400);
}
var protocol = (req.headers['sec-websocket-protocol'] || '').split(/, */);
//
// Optionally call external protocol selection handler.
//
if (this.options.handleProtocols) {
protocol = this.options.handleProtocols(protocol);
if (protocol === false) return abortConnection(socket, 401);
} else {
protocol = protocol[0];
}
//
// Optionally call external client verification handler.
//
if (this.options.verifyClient) {
const info = {
origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
secure: !!(req.connection.authorized || req.connection.encrypted),
req
};
if (this.options.verifyClient.length === 2) {
this.options.verifyClient(info, (verified, code, message) => {
if (!verified) return abortConnection(socket, code || 401, message);
this.completeUpgrade(protocol, version, req, socket, head, cb);
});
return;
} else if (!this.options.verifyClient(info)) {
return abortConnection(socket, 401);
}
}
this.completeUpgrade(protocol, version, req, socket, head, cb);
}
/**
* Upgrade the connection to WebSocket.
*
* @param {String} protocol The chosen subprotocol
* @param {Number} version The WebSocket protocol version
* @param {http.IncomingMessage} req The request object
* @param {net.Socket} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @private
*/
completeUpgrade (protocol, version, req, socket, head, cb) {
//
// Destroy the socket if the client has already sent a FIN packet.
//
if (!socket.readable || !socket.writable) return socket.destroy();
const key = crypto.createHash('sha1')
.update(req.headers['sec-websocket-key'] + constants.GUID, 'binary')
.digest('base64');
const headers = [
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Accept: ${key}`
];
if (protocol) headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
const offer = Extensions.parse(req.headers['sec-websocket-extensions']);
var extensions;
try {
extensions = acceptExtensions(this.options, offer);
} catch (err) {
return abortConnection(socket, 400);
}
const props = Object.keys(extensions);
if (props.length) {
const serverExtensions = props.reduce((obj, key) => {
obj[key] = [extensions[key].params];
return obj;
}, {});
headers.push(`Sec-WebSocket-Extensions: ${Extensions.format(serverExtensions)}`);
}
//
// Allow external modification/inspection of handshake headers.
//
this.emit('headers', headers);
socket.write(headers.concat('', '').join('\r\n'));
const client = new WebSocket([req, socket, head], {
maxPayload: this.options.maxPayload,
protocolVersion: version,
extensions,
protocol
});
if (this.clients) {
this.clients.add(client);
client.on('close', () => this.clients.delete(client));
}
socket.removeListener('error', socketError);
cb(client);
}
}
module.exports = WebSocketServer;
/**
* Handle premature socket errors.
*
* @private
*/
function socketError () {
this.destroy();
}
/**
* Accept WebSocket extensions.
*
* @param {Object} options The `WebSocketServer` configuration options
* @param {Object} offer The parsed value of the `sec-websocket-extensions` header
* @return {Object} Accepted extensions
* @private
*/
function acceptExtensions (options, offer) {
const pmd = options.perMessageDeflate;
const extensions = {};
if (pmd && offer[PerMessageDeflate.extensionName]) {
const perMessageDeflate = new PerMessageDeflate(
pmd !== true ? pmd : {},
true,
options.maxPayload
);
perMessageDeflate.accept(offer[PerMessageDeflate.extensionName]);
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
return extensions;
}
/**
* Close the connection when preconditions are not fulfilled.
*
* @param {net.Socket} socket The socket of the upgrade request
* @param {Number} code The HTTP response status code
* @param {String} [message] The HTTP response body
* @private
*/
function abortConnection (socket, code, message) {
if (socket.writable) {
message = message || http.STATUS_CODES[code];
socket.write(
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
'Connection: close\r\n' +
'Content-type: text/html\r\n' +
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
'\r\n' +
message
);
}
socket.removeListener('error', socketError);
socket.destroy();
}

122
Server/node_modules/ws/package.json generated vendored Normal file
View File

@ -0,0 +1,122 @@
{
"_args": [
[
{
"raw": "ws",
"scope": null,
"escapedName": "ws",
"name": "ws",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"D:\\Programs\\Dropbox\\Public\\mkds\\Server"
]
],
"_from": "ws@latest",
"_id": "ws@2.2.3",
"_inCache": true,
"_location": "/ws",
"_nodeVersion": "7.8.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/ws-2.2.3.tgz_1491214217857_0.5180311135482043"
},
"_npmUser": {
"name": "lpinca",
"email": "luigipinca@gmail.com"
},
"_npmVersion": "4.2.0",
"_phantomChildren": {},
"_requested": {
"raw": "ws",
"scope": null,
"escapedName": "ws",
"name": "ws",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER"
],
"_resolved": "https://registry.npmjs.org/ws/-/ws-2.2.3.tgz",
"_shasum": "f36c9719a56dff813f455af912a2078145bbd940",
"_shrinkwrap": null,
"_spec": "ws",
"_where": "D:\\Programs\\Dropbox\\Public\\mkds\\Server",
"author": {
"name": "Einar Otto Stangvik",
"email": "einaros@gmail.com",
"url": "http://2x.io"
},
"bugs": {
"url": "https://github.com/websockets/ws/issues"
},
"dependencies": {
"safe-buffer": "~5.0.1",
"ultron": "~1.1.0"
},
"description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
"devDependencies": {
"benchmark": "~2.1.2",
"bufferutil": "~3.0.0",
"eslint": "~3.19.0",
"eslint-config-standard": "~8.0.0-beta.1",
"eslint-plugin-import": "~2.2.0",
"eslint-plugin-node": "~4.2.0",
"eslint-plugin-promise": "~3.5.0",
"eslint-plugin-standard": "~2.1.0",
"mocha": "~3.2.0",
"nyc": "~10.2.0",
"utf-8-validate": "~3.0.0"
},
"directories": {},
"dist": {
"shasum": "f36c9719a56dff813f455af912a2078145bbd940",
"tarball": "https://registry.npmjs.org/ws/-/ws-2.2.3.tgz"
},
"gitHead": "212c7aab04a5f23d89111c1722371211efa2dd89",
"homepage": "https://github.com/websockets/ws#readme",
"keywords": [
"HyBi",
"Push",
"RFC-6455",
"WebSocket",
"WebSockets",
"real-time"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "3rdeden",
"email": "npm@3rd-Eden.com"
},
{
"name": "einaros",
"email": "einaros@gmail.com"
},
{
"name": "lpinca",
"email": "luigipinca@gmail.com"
},
{
"name": "v1",
"email": "npm@3rd-Eden.com"
}
],
"name": "ws",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/websockets/ws.git"
},
"scripts": {
"integration": "eslint . && mocha test/*.integration.js",
"lint": "eslint .",
"test": "eslint . && nyc --reporter=html --reporter=text mocha test/*.test.js"
},
"version": "2.2.3"
}

1
Server/run.bat Normal file
View File

@ -0,0 +1 @@
node server.js

4
Server/run.sh Normal file
View File

@ -0,0 +1,4 @@
#!/bin/sh
# just boots the server. nothing fancy right now.
nodejs server.js

116
Server/server.js Normal file
View File

@ -0,0 +1,116 @@
//
// MKJS Dedicated server main file.
//
// Default config:
var defaultCfg = {
port:8080,
instances:1,
defaultInstance: {
mapRotation: [
"mkdsDefault" //auto includes all default maps. if you want to specify specific maps you will need to remove this and add "mkds/tracknum" for each default track you want to include.
//custom tracks are read from the "maps/" folder.
],
mapMode: "random",
itemConfig: [
//specifies item number and default params
//eg triple green will have settings to choose how many shells you start with.
{item:0, cfg:{}},
{item:1, cfg:{}},
{item:2, cfg:{}},
],
itemChance: [
//specifies brackets where certain items have a specific chance of appearing.
//should be in order of near first place first.
{
placement: 0.25, //if 8 players, players 1 and 2 will get this chance distribution.
choices: [
//the random selector generates a number between 0 and 1. if it is less than an item's "chance", that item will be selected. If not we try the next one.
//real % chance per item is (item.chance - last.chance)*100
{item:0, chance:0.5},
{item:1, chance:0.75},
{item:2, chance:1}
]
},
{
placement: 1,
choices: [
{item:2, chance:1}
]
},
]
}
}
// --
process.title = "MKJS Dedicated Server";
console.log("Initializing server...");
try {
var ws = require('ws'),
http = require('http'),
fs = require('fs'),
inst = require('./modules/mkjsInstance.js');
} catch (err) {
console.error("FATAL ERROR - could not load modules. Ensure you have ws for websockets.");
process.exit(1);
}
console.log("Modules Ready!");
try {
var config = JSON.parse(fs.readFileSync('config.json', 'ascii'));
} catch (err) {
if (err.errno == 34) {
console.error("No config file. Writing default config.");
fs.writeFileSync('config.json', JSON.stringify(defaultCfg, null, "\t"), 'ascii')
var config = JSON.parse(fs.readFileSync('config.json', 'ascii'));
} else {
console.error("FATAL ERROR - could not load config. Check that the syntax is correct.");
process.exit(1);
}
}
var wss = new ws.Server({port: config.port});
var instances = [];
for (var i=0; i<config.instances; i++) {
instances.push(new inst.mkjsInstance(config, config.defaultInstance, wss));
}
wss.on('connection', function(cli) {
//client needs to connect to an instance before anything.
cli.on('message', function(data, flags) {
if (cli.inst == null) {
if (flags.binary) cli.close(); //first packet must identify location.
else {
try {
var obj = JSON.parse(data);
if (obj.t == "*") {
cli.credentials = obj.c;
var inst = instances[obj.i];
if (inst == null) cli.close(); //that instance does not exist
else {
cli.inst = inst;
inst.addClient(cli);
}
}
} catch (err) {
cli.close(); //just leave
}
}
} else {
cli.inst.handleMessage(cli, data, flags);
}
});
cli.on('close', function() {
if (cli.inst != null) {
cli.inst.removeClient(cli);
}
})
})

80
audio.html Normal file
View File

@ -0,0 +1,80 @@
<head>
<script src="code/formats/sdat.js"></script>
<script src="code/formats/swav.js"></script>
<script src="code/formats/swar.js"></script>
<script src="code/formats/sbnk.js"></script>
<script src="code/formats/sseq.js"></script>
<script src="code/formats/ssar.js"></script>
<script src="code/audio/sseqPlayer.js"></script>
<script src="code/audio/nitroAudio.js"></script>
<script>
files = {};
fileQuota = 1;
filesLoaded = 0;
window.onload = function(argument) {
loadFile("sound_data.sdat");
}
var i=0;
var last = null;
function init() {
nitroAudio.init(new sdat(files["sound_data.sdat"])); //89
//you need to extract this one yourself!
play.addEventListener('click', function() {
if (last != null) nitroAudio.instaKill(last);
document.getElementById('seq').innerText = "Current SSEQ: "+i;
last = nitroAudio.playSound(i++);
})
/*
var ctx = new AudioContext();
test = new sdat(files["sound_data.sdat"]);
testAud = new SSEQPlayer(test.sections["$INFO"][0][5], test, ctx);
var elem = document.getElementById('play'),
buf = ctx.createBuffer(1, 1, 44000);
osc = ctx.createBufferSource();
osc.buffer = buf;
osc.connect(ctx.destination);
if (osc.noteOn) osc.start = osc.noteOn;
play.addEventListener('click', function() {
if (!osc.donezo) {
osc.start(0);
osc.donezo = true;
}
testAud.masterGain.disconnect();
testAud = new SSEQPlayer(test.sections["$INFO"][0][++i], test, ctx);//.arc.entries[++i]
document.getElementById('seq').innerText = "Current SSEQ: "+i;
}, false);
*/
setInterval(tick, 16);
}
function tick() {
nitroAudio.tick();
}
function loadFile(url) {
var xml = new XMLHttpRequest();
xml.open("GET", url, true);
xml.responseType = "arraybuffer";
xml.onload = function() {
files[url] = xml.response;
if (++filesLoaded == fileQuota) init();
}
xml.send();
}
window.onerror = function(msg, ln, test) {
alert("ERROR: "+msg+", "+ln+", "+test);
}
</script>
</head>
<body>
<button id="play" style="width:200px; height:40px;">Click to play next sequence</button>
<span id="seq">Current SSEQ: 0</span>
</body>

81
audioSFX.html Normal file
View File

@ -0,0 +1,81 @@
<head>
<script src="code/formats/sdat.js"></script>
<script src="code/formats/swav.js"></script>
<script src="code/formats/swar.js"></script>
<script src="code/formats/sbnk.js"></script>
<script src="code/formats/sseq.js"></script>
<script src="code/formats/ssar.js"></script>
<script src="code/audio/sseqPlayer.js"></script>
<script src="code/audio/nitroAudio.js"></script>
<script>
files = {};
fileQuota = 1;
filesLoaded = 0;
window.onload = function(argument) {
loadFile("sound_data.sdat");
}
var i=0;
var last = null;
function init() {
nitroAudio.init(new sdat(files["sound_data.sdat"])); //89
//nitroAudio .playSound(0);
play.addEventListener('click', function() {
if (last != null) nitroAudio.instaKill(last);
document.getElementById('seq').innerText = "Current SSEQ: "+i;
last = nitroAudio.playSound(i++, {}, 0);
})
/*
var ctx = new AudioContext();
test = new sdat(files["sound_data.sdat"]);
testAud = new SSEQPlayer(test.sections["$INFO"][0][5], test, ctx);
var elem = document.getElementById('play'),
buf = ctx.createBuffer(1, 1, 44000);
osc = ctx.createBufferSource();
osc.buffer = buf;
osc.connect(ctx.destination);
if (osc.noteOn) osc.start = osc.noteOn;
play.addEventListener('click', function() {
if (!osc.donezo) {
osc.start(0);
osc.donezo = true;
}
testAud.masterGain.disconnect();
testAud = new SSEQPlayer(test.sections["$INFO"][0][++i], test, ctx);//.arc.entries[++i]
document.getElementById('seq').innerText = "Current SSEQ: "+i;
}, false);
*/
setInterval(tick, 16);
}
function tick() {
nitroAudio.tick();
}
function loadFile(url) {
var xml = new XMLHttpRequest();
xml.open("GET", url, true);
xml.responseType = "arraybuffer";
xml.onload = function() {
files[url] = xml.response;
if (++filesLoaded == fileQuota) init();
}
xml.send();
}
window.onerror = function(msg, ln, test) {
alert("ERROR: "+msg+", "+ln+", "+test);
}
</script>
</head>
<body>
<button id="play" style="width:200px; height:40px;">Click to play next sequence</button>
<span id="seq">Current SSEQ: 0</span>
</body>

1
index.html Normal file

File diff suppressed because one or more lines are too long