...and add it all back.

pull/3/head
RHY3756547 2017-09-08 17:22:15 +01:00
parent a16ba9a907
commit 3ae7c01030
119 changed files with 41373 additions and 0 deletions

3
code/IndexedDBShim.min.js vendored Normal file

File diff suppressed because one or more lines are too long

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));
}
}

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);
}
}
}

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;
}
}

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);
}
}

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

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));
}
}

BIN
resource/placeAtlas.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 260 KiB

BIN
server/Antlr3.Runtime.dll Normal file

Binary file not shown.

BIN
server/Antlr3.Runtime.pdb Normal file

Binary file not shown.

View File

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
<TelemetryModules>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector"/>
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
<!--
Use the following syntax here to collect additional performance counters:
<Counters>
<Add PerformanceCounter="\Process(??APP_WIN32_PROC??)\Handle Count" ReportAs="Process handle count" />
...
</Counters>
PerformanceCounter must be either \CategoryName(InstanceName)\CounterName or \CategoryName\CounterName
Counter names may only contain letters, round brackets, forward slashes, hyphens, underscores, spaces and dots.
You may provide an optional ReportAs attribute which will be used as the metric name when reporting counter data.
For the purposes of reporting, metric names will be sanitized by removing all invalid characters from the resulting metric name.
NOTE: performance counters configuration will be lost upon NuGet upgrade.
The following placeholders are supported as InstanceName:
??APP_WIN32_PROC?? - instance name of the application process for Win32 counters.
??APP_W3SVC_PROC?? - instance name of the application IIS worker process for IIS/ASP.NET counters.
??APP_CLR_PROC?? - instance name of the application CLR process for .NET counters.
-->
</Add>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
<Handlers>
<!--
Add entries here to filter out additional handlers:
NOTE: handler configuration will be lost upon NuGet upgrade.
-->
<Add>System.Web.Handlers.TransferRequestHandler</Add>
<Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
<Add>System.Web.StaticFileHandler</Add>
<Add>System.Web.Handlers.AssemblyResourceLoader</Add>
<Add>System.Web.Optimization.BundleHandler</Add>
<Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
<Add>System.Web.Handlers.TraceHandler</Add>
<Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
<Add>System.Web.HttpDebugHandler</Add>
</Handlers>
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web"/>
</TelemetryModules>
<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel"/>
<TelemetryProcessors>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
<MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
</Add>
</TelemetryProcessors>
<!--
Learn more about Application Insights configuration with ApplicationInsights.config here:
http://go.microsoft.com/fwlink/?LinkID=513840
Note: If not present, please add <InstrumentationKey>Your Key</InstrumentationKey> to the top of this file.
-->
<TelemetryInitializers>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.DomainNameRoleInstanceTelemetryInitializer, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web">
<Filters>
<Add Pattern="(YottaaMonitor|BrowserMob|HttpMonitor|YandexBot|BingPreview|PagePeeker|ThumbShotsBot|WebThumb|URL2PNG|ZooShot|GomezA|Catchpoint bot|Willow Internet Crawler|Google SketchUp|Read%20Later|KTXN|Pingdom|AlwaysOn)"/>
<Add Pattern="Slurp" SourceName="Yahoo Bot"/>
<Add Pattern="(bot|zao|borg|Bot|oegp|silk|Xenu|zeal|^NING|crawl|Crawl|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|^Java/|^JNLP/|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|spider|Spider|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|^voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr\-agent|Squrl Java|A6\-Indexer|netresearch|searchsight|http%20client|Python-urllib|dataparksearch|Screaming Frog|AppEngine-Google|YahooCacheSystem|semanticdiscovery|facebookexternalhit|Google.*/\+/web/snippet|Google-HTTP-Java-Client)"
SourceName="Spider"/>
</Filters>
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web"/>
</TelemetryInitializers>
</ApplicationInsights>

Binary file not shown.

BIN
server/CommandLine.dll Normal file

Binary file not shown.

1390
server/CommandLine.xml Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,876 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>Common.Logging.Core</name>
</assembly>
<members>
<member name="T:Common.Logging.Factory.StringFormatMethodAttribute">
<summary>
Indicates that the marked method builds string by format pattern and (optional) arguments.
Parameter, which contains format string, should be given in constructor. The format string
should be in <see cref="M:System.String.Format(System.IFormatProvider,System.String,System.Object[])"/>-like form
</summary>
<example><code>
[StringFormatMethod("message")]
public void ShowError(string message, params object[] args) { /* do something */ }
public void Foo() {
ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
}
</code></example>
</member>
<member name="M:Common.Logging.Factory.StringFormatMethodAttribute.#ctor(System.String)">
<param name="formatParameterName">
Specifies which parameter of an annotated method should be treated as format-string
</param>
</member>
<member name="P:Common.Logging.Factory.StringFormatMethodAttribute.FormatParameterName">
<summary>
The name of the string parameter being formatted
</summary>
</member>
<member name="T:Common.Logging.FormatMessageHandler">
<summary>
The type of method that is passed into e.g. <see cref="M:Common.Logging.ILog.Debug(System.Action{Common.Logging.FormatMessageHandler})"/>
and allows the callback method to "submit" it's message to the underlying output system.
</summary>
<param name="format">the format argument as in <see cref="M:System.String.Format(System.String,System.Object[])"/></param>
<param name="args">the argument list as in <see cref="M:System.String.Format(System.String,System.Object[])"/></param>
<seealso cref="T:Common.Logging.ILog"/>
<author>Erich Eichinger</author>
</member>
<member name="T:Common.Logging.IConfigurationReader">
<summary>
Interface for basic operations to read .NET application configuration information.
</summary>
<remarks>Provides a simple abstraction to handle BCL API differences between .NET 1.x and 2.0. Also
useful for testing scenarios.</remarks>
<author>Mark Pollack</author>
</member>
<member name="M:Common.Logging.IConfigurationReader.GetSection(System.String)">
<summary>
Parses the configuration section and returns the resulting object.
</summary>
<remarks>
<p>
Primary purpose of this method is to allow us to parse and
load configuration sections using the same API regardless
of the .NET framework version.
</p>
See also <c>System.Configuration.ConfigurationManager</c>
</remarks>
<param name="sectionName">Name of the configuration section.</param>
<returns>Object created by a corresponding IConfigurationSectionHandler.</returns>
</member>
<member name="T:Common.Logging.ILog">
<summary>
A simple logging interface abstracting logging APIs.
</summary>
<remarks>
<para>
Implementations should defer calling a message's <see cref="M:System.Object.ToString"/> until the message really needs
to be logged to avoid performance penalties.
</para>
<para>
Each <see cref="T:Common.Logging.ILog"/> log method offers to pass in a <see cref="T:System.Action`1"/> instead of the actual message.
Using this style has the advantage to defer possibly expensive message argument evaluation and formatting (and formatting arguments!) until the message gets
actually logged. If the message is not logged at all (e.g. due to <see cref="T:Common.Logging.LogLevel"/> settings),
you won't have to pay the peformance penalty of creating the message.
</para>
</remarks>
<example>
The example below demonstrates using callback style for creating the message, where the call to the
<see cref="M:System.Random.NextDouble"/> and the underlying <see cref="M:System.String.Format(System.String,System.Object[])"/> only happens, if level <see cref="F:Common.Logging.LogLevel.Debug"/> is enabled:
<code>
Log.Debug( m=&gt;m("result is {0}", random.NextDouble()) );
Log.Debug(delegate(m) { m("result is {0}", random.NextDouble()); });
</code>
</example>
<seealso cref="T:System.Action`1"/>
<author>Mark Pollack</author>
<author>Bruno Baia</author>
<author>Erich Eichinger</author>
</member>
<member name="M:Common.Logging.ILog.Trace(System.Object)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Trace"/> level.
</summary>
<param name="message">The message object to log.</param>
</member>
<member name="M:Common.Logging.ILog.Trace(System.Object,System.Exception)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Trace"/> level including
the stack trace of the <see cref="T:System.Exception"/> passed
as a parameter.
</summary>
<param name="message">The message object to log.</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.TraceFormat(System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Trace"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.TraceFormat(System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Trace"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.TraceFormat(System.IFormatProvider,System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Trace"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.TraceFormat(System.IFormatProvider,System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Trace"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.Trace(System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Trace"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Trace(System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Trace"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.Trace(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Trace"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Trace(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Trace"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.Debug(System.Object)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Debug"/> level.
</summary>
<param name="message">The message object to log.</param>
</member>
<member name="M:Common.Logging.ILog.Debug(System.Object,System.Exception)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Debug"/> level including
the stack trace of the <see cref="T:System.Exception"/> passed
as a parameter.
</summary>
<param name="message">The message object to log.</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.DebugFormat(System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Debug"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.DebugFormat(System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Debug"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.DebugFormat(System.IFormatProvider,System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Debug"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.DebugFormat(System.IFormatProvider,System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Debug"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.Debug(System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Debug"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Debug(System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Debug"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.Debug(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Debug"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Debug(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Debug"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack Debug.</param>
</member>
<member name="M:Common.Logging.ILog.Info(System.Object)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Info"/> level.
</summary>
<param name="message">The message object to log.</param>
</member>
<member name="M:Common.Logging.ILog.Info(System.Object,System.Exception)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Info"/> level including
the stack trace of the <see cref="T:System.Exception"/> passed
as a parameter.
</summary>
<param name="message">The message object to log.</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.InfoFormat(System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Info"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.InfoFormat(System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Info"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.InfoFormat(System.IFormatProvider,System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Info"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.InfoFormat(System.IFormatProvider,System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Info"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.Info(System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Info"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Info(System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Info"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.Info(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Info"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Info(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Info"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack Info.</param>
</member>
<member name="M:Common.Logging.ILog.Warn(System.Object)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Warn"/> level.
</summary>
<param name="message">The message object to log.</param>
</member>
<member name="M:Common.Logging.ILog.Warn(System.Object,System.Exception)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Warn"/> level including
the stack trace of the <see cref="T:System.Exception"/> passed
as a parameter.
</summary>
<param name="message">The message object to log.</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.WarnFormat(System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Warn"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.WarnFormat(System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Warn"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.WarnFormat(System.IFormatProvider,System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Warn"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.WarnFormat(System.IFormatProvider,System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Warn"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.Warn(System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Warn"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Warn(System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Warn"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.Warn(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Warn"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Warn(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Warn"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack Warn.</param>
</member>
<member name="M:Common.Logging.ILog.Error(System.Object)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Error"/> level.
</summary>
<param name="message">The message object to log.</param>
</member>
<member name="M:Common.Logging.ILog.Error(System.Object,System.Exception)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Error"/> level including
the stack trace of the <see cref="T:System.Exception"/> passed
as a parameter.
</summary>
<param name="message">The message object to log.</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.ErrorFormat(System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Error"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.ErrorFormat(System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Error"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.ErrorFormat(System.IFormatProvider,System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Error"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.ErrorFormat(System.IFormatProvider,System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Error"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.Error(System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Error"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Error(System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Error"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.Error(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Error"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Error(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Error"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack Error.</param>
</member>
<member name="M:Common.Logging.ILog.Fatal(System.Object)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level.
</summary>
<param name="message">The message object to log.</param>
</member>
<member name="M:Common.Logging.ILog.Fatal(System.Object,System.Exception)">
<summary>
Log a message object with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level including
the stack trace of the <see cref="T:System.Exception"/> passed
as a parameter.
</summary>
<param name="message">The message object to log.</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.FatalFormat(System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.FatalFormat(System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level.
</summary>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args">the list of format arguments</param>
</member>
<member name="M:Common.Logging.ILog.FatalFormat(System.IFormatProvider,System.String,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.FatalFormat(System.IFormatProvider,System.String,System.Exception,System.Object[])">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level.
</summary>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="format">The format of the message object to log.<see cref="M:System.String.Format(System.String,System.Object[])"/> </param>
<param name="exception">The exception to log.</param>
<param name="args"></param>
</member>
<member name="M:Common.Logging.ILog.Fatal(System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Fatal(System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack trace.</param>
</member>
<member name="M:Common.Logging.ILog.Fatal(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler})">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
</member>
<member name="M:Common.Logging.ILog.Fatal(System.IFormatProvider,System.Action{Common.Logging.FormatMessageHandler},System.Exception)">
<summary>
Log a message with the <see cref="F:Common.Logging.LogLevel.Fatal"/> level using a callback to obtain the message
</summary>
<remarks>
Using this method avoids the cost of creating a message and evaluating message arguments
that probably won't be logged due to loglevel settings.
</remarks>
<param name="formatProvider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
<param name="formatMessageCallback">A callback used by the logger to obtain the message if log level is matched</param>
<param name="exception">The exception to log, including its stack Fatal.</param>
</member>
<member name="P:Common.Logging.ILog.IsTraceEnabled">
<summary>
Checks if this logger is enabled for the <see cref="F:Common.Logging.LogLevel.Trace"/> level.
</summary>
</member>
<member name="P:Common.Logging.ILog.IsDebugEnabled">
<summary>
Checks if this logger is enabled for the <see cref="F:Common.Logging.LogLevel.Debug"/> level.
</summary>
</member>
<member name="P:Common.Logging.ILog.IsErrorEnabled">
<summary>
Checks if this logger is enabled for the <see cref="F:Common.Logging.LogLevel.Error"/> level.
</summary>
</member>
<member name="P:Common.Logging.ILog.IsFatalEnabled">
<summary>
Checks if this logger is enabled for the <see cref="F:Common.Logging.LogLevel.Fatal"/> level.
</summary>
</member>
<member name="P:Common.Logging.ILog.IsInfoEnabled">
<summary>
Checks if this logger is enabled for the <see cref="F:Common.Logging.LogLevel.Info"/> level.
</summary>
</member>
<member name="P:Common.Logging.ILog.IsWarnEnabled">
<summary>
Checks if this logger is enabled for the <see cref="F:Common.Logging.LogLevel.Warn"/> level.
</summary>
</member>
<member name="P:Common.Logging.ILog.GlobalVariablesContext">
<summary>
Returns the global context for variables
</summary>
</member>
<member name="P:Common.Logging.ILog.ThreadVariablesContext">
<summary>
Returns the thread-specific context for variables
</summary>
</member>
<member name="T:Common.Logging.ILoggerFactoryAdapter">
<summary>
LoggerFactoryAdapter interface is used internally by LogManager
Only developers wishing to write new Common.Logging adapters need to
worry about this interface.
</summary>
<author>Gilles Bayon</author>
</member>
<member name="M:Common.Logging.ILoggerFactoryAdapter.GetLogger(System.Type)">
<summary>
Get a ILog instance by type.
</summary>
<param name="type">The type to use for the logger</param>
<returns></returns>
</member>
<member name="M:Common.Logging.ILoggerFactoryAdapter.GetLogger(System.String)">
<summary>
Get a ILog instance by key.
</summary>
<param name="key">The key of the logger</param>
<returns></returns>
</member>
<member name="T:Common.Logging.ILogManager">
<summary>
Interface for LogManager
</summary>
</member>
<member name="M:Common.Logging.ILogManager.Reset">
<summary>
Reset the <see cref="N:Common.Logging"/> infrastructure to its default settings. This means, that configuration settings
will be re-read from section <c>&lt;common/logging&gt;</c> of your <c>app.config</c>.
</summary>
<remarks>
This is mainly used for unit testing, you wouldn't normally use this in your applications.<br/>
<b>Note:</b><see cref="T:Common.Logging.ILog"/> instances already handed out from this LogManager are not(!) affected.
Resetting LogManager only affects new instances being handed out.
</remarks>
</member>
<member name="M:Common.Logging.ILogManager.Reset(Common.Logging.IConfigurationReader)">
<summary>
Reset the <see cref="N:Common.Logging"/> infrastructure to its default settings. This means, that configuration settings
will be re-read from section <c>&lt;common/logging&gt;</c> of your <c>app.config</c>.
</summary>
<remarks>
This is mainly used for unit testing, you wouldn't normally use this in your applications.<br/>
<b>Note:</b><see cref="T:Common.Logging.ILog"/> instances already handed out from this LogManager are not(!) affected.
Resetting LogManager only affects new instances being handed out.
</remarks>
<param name="reader">
the <see cref="T:Common.Logging.IConfigurationReader"/> instance to obtain settings for
re-initializing the LogManager.
</param>
</member>
<member name="M:Common.Logging.ILogManager.GetCurrentClassLogger">
<summary>
Gets the logger by calling <see cref="M:Common.Logging.ILoggerFactoryAdapter.GetLogger(System.Type)"/>
on the currently configured <see cref="P:Common.Logging.ILogManager.Adapter"/> using the type of the calling class.
</summary>
<remarks>
This method needs to inspect the StackTrace in order to determine the calling
class. This of course comes with a performance penalty, thus you shouldn't call it too
often in your application.
</remarks>
<seealso cref="M:Common.Logging.ILogManager.GetLogger(System.Type)"/>
<returns>the logger instance obtained from the current <see cref="P:Common.Logging.ILogManager.Adapter"/></returns>
</member>
<member name="M:Common.Logging.ILogManager.GetLogger``1">
<summary>
Gets the logger by calling <see cref="M:Common.Logging.ILoggerFactoryAdapter.GetLogger(System.Type)"/>
on the currently configured <see cref="P:Common.Logging.ILogManager.Adapter"/> using the specified type.
</summary>
<returns>the logger instance obtained from the current <see cref="P:Common.Logging.ILogManager.Adapter"/></returns>
</member>
<member name="M:Common.Logging.ILogManager.GetLogger(System.Type)">
<summary>
Gets the logger by calling <see cref="M:Common.Logging.ILoggerFactoryAdapter.GetLogger(System.Type)"/>
on the currently configured <see cref="P:Common.Logging.ILogManager.Adapter"/> using the specified type.
</summary>
<param name="type">The type.</param>
<returns>the logger instance obtained from the current <see cref="P:Common.Logging.ILogManager.Adapter"/></returns>
</member>
<member name="M:Common.Logging.ILogManager.GetLogger(System.String)">
<summary>
Gets the logger by calling <see cref="M:Common.Logging.ILoggerFactoryAdapter.GetLogger(System.String)"/>
on the currently configured <see cref="P:Common.Logging.ILogManager.Adapter"/> using the specified key.
</summary>
<param name="key">The key.</param>
<returns>the logger instance obtained from the current <see cref="P:Common.Logging.ILogManager.Adapter"/></returns>
</member>
<member name="P:Common.Logging.ILogManager.COMMON_LOGGING_SECTION">
<summary>
The key of the default configuration section to read settings from.
</summary>
<remarks>
You can always change the source of your configuration settings by setting another <see cref="T:Common.Logging.IConfigurationReader"/> instance
on <see cref="P:Common.Logging.ILogManager.ConfigurationReader"/>.
</remarks>
</member>
<member name="P:Common.Logging.ILogManager.ConfigurationReader">
<summary>
Gets the configuration reader used to initialize the LogManager.
</summary>
<remarks>Primarily used for testing purposes but maybe useful to obtain configuration
information from some place other than the .NET application configuration file.</remarks>
<value>The configuration reader.</value>
</member>
<member name="P:Common.Logging.ILogManager.Adapter">
<summary>
Gets or sets the adapter.
</summary>
<value>The adapter.</value>
</member>
<member name="T:Common.Logging.IVariablesContext">
<summary>
A context for logger variables
</summary>
</member>
<member name="M:Common.Logging.IVariablesContext.Set(System.String,System.Object)">
<summary>
Sets the value of a new or existing variable within the global context
</summary>
<param name="key">The key of the variable that is to be added</param>
<param name="value">The value to add</param>
</member>
<member name="M:Common.Logging.IVariablesContext.Get(System.String)">
<summary>
Gets the value of a variable within the global context
</summary>
<param name="key">The key of the variable to get</param>
<returns>The value or null if not found</returns>
</member>
<member name="M:Common.Logging.IVariablesContext.Contains(System.String)">
<summary>
Checks if a variable is set within the global context
</summary>
<param name="key">The key of the variable to check for</param>
<returns>True if the variable is set</returns>
</member>
<member name="M:Common.Logging.IVariablesContext.Remove(System.String)">
<summary>
Removes a variable from the global context by key
</summary>
<param name="key">The key of the variable to remove</param>
</member>
<member name="M:Common.Logging.IVariablesContext.Clear">
<summary>
Clears the global context variables
</summary>
</member>
<member name="T:Common.Logging.LogLevel">
<summary>
The 7 possible logging levels
</summary>
<author>Gilles Bayon</author>
</member>
<member name="F:Common.Logging.LogLevel.All">
<summary>
All logging levels
</summary>
</member>
<member name="F:Common.Logging.LogLevel.Trace">
<summary>
A trace logging level
</summary>
</member>
<member name="F:Common.Logging.LogLevel.Debug">
<summary>
A debug logging level
</summary>
</member>
<member name="F:Common.Logging.LogLevel.Info">
<summary>
A info logging level
</summary>
</member>
<member name="F:Common.Logging.LogLevel.Warn">
<summary>
A warn logging level
</summary>
</member>
<member name="F:Common.Logging.LogLevel.Error">
<summary>
An error logging level
</summary>
</member>
<member name="F:Common.Logging.LogLevel.Fatal">
<summary>
A fatal logging level
</summary>
</member>
<member name="F:Common.Logging.LogLevel.Off">
<summary>
Do not log anything.
</summary>
</member>
</members>
</doc>

BIN
server/Common.Logging.dll Normal file

Binary file not shown.

BIN
server/Common.Logging.pdb Normal file

Binary file not shown.

2774
server/Common.Logging.xml Normal file

File diff suppressed because it is too large Load Diff

BIN
server/Dapper.dll Normal file

Binary file not shown.

BIN
server/Dapper.pdb Normal file

Binary file not shown.

1412
server/Dapper.xml Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
server/FSO.Common.dll Normal file

Binary file not shown.

BIN
server/FSO.Common.pdb Normal file

Binary file not shown.

BIN
server/FSO.Content.dll Normal file

Binary file not shown.

BIN
server/FSO.Content.pdb Normal file

Binary file not shown.

BIN
server/FSO.Files.dll Normal file

Binary file not shown.

View File

@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>

BIN
server/FSO.Files.pdb Normal file

Binary file not shown.

BIN
server/FSO.HIT.dll Normal file

Binary file not shown.

BIN
server/FSO.HIT.pdb Normal file

Binary file not shown.

BIN
server/FSO.LotView.dll Normal file

Binary file not shown.

BIN
server/FSO.LotView.pdb Normal file

Binary file not shown.

BIN
server/FSO.Server.Api.dll Normal file

Binary file not shown.

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<appSettings>
<add key="connectionString" value="server=127.0.0.1;uid=root;pwd=;database=fso2;" />
<add key="maintainance" value="true" />
<add key="authTicketDuration" value="300" />
<add key="secret" value="38F7E3B816EF9F31BFAB8F4C9716C90D106BD85E9D6913FBB4D833C866F837B0" />
<add key="updateUrl" value="http://someUrl" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Ninject" publicKeyToken="c7192dc5380945e7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.2.0.0" newVersion="3.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Ninject.Extensions.ChildKernel" publicKeyToken="c7192dc5380945e7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.2.0.0" newVersion="3.2.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
</compilers>
</system.codedom>
</configuration>

BIN
server/FSO.Server.Api.pdb Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More